repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
blackdeviant/nickless | drivers/mtd/nand/gpio.c | 5028 | 11699 | /*
* drivers/mtd/nand/gpio.c
*
* Updated, and converted to generic GPIO based driver by Russell King.
*
* Written by Ben Dooks <ben@simtec.co.uk>
* Based on 2.4 version by Mark Whittaker
*
* © 2004 Simtec Electronics
*
* Device driver for NAND connected via GPIO
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <linux/io.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/nand.h>
#include <linux/mtd/partitions.h>
#include <linux/mtd/nand-gpio.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/of_gpio.h>
struct gpiomtd {
void __iomem *io_sync;
struct mtd_info mtd_info;
struct nand_chip nand_chip;
struct gpio_nand_platdata plat;
};
#define gpio_nand_getpriv(x) container_of(x, struct gpiomtd, mtd_info)
#ifdef CONFIG_ARM
/* gpio_nand_dosync()
*
* Make sure the GPIO state changes occur in-order with writes to NAND
* memory region.
* Needed on PXA due to bus-reordering within the SoC itself (see section on
* I/O ordering in PXA manual (section 2.3, p35)
*/
static void gpio_nand_dosync(struct gpiomtd *gpiomtd)
{
unsigned long tmp;
if (gpiomtd->io_sync) {
/*
* Linux memory barriers don't cater for what's required here.
* What's required is what's here - a read from a separate
* region with a dependency on that read.
*/
tmp = readl(gpiomtd->io_sync);
asm volatile("mov %1, %0\n" : "=r" (tmp) : "r" (tmp));
}
}
#else
static inline void gpio_nand_dosync(struct gpiomtd *gpiomtd) {}
#endif
static void gpio_nand_cmd_ctrl(struct mtd_info *mtd, int cmd, unsigned int ctrl)
{
struct gpiomtd *gpiomtd = gpio_nand_getpriv(mtd);
gpio_nand_dosync(gpiomtd);
if (ctrl & NAND_CTRL_CHANGE) {
gpio_set_value(gpiomtd->plat.gpio_nce, !(ctrl & NAND_NCE));
gpio_set_value(gpiomtd->plat.gpio_cle, !!(ctrl & NAND_CLE));
gpio_set_value(gpiomtd->plat.gpio_ale, !!(ctrl & NAND_ALE));
gpio_nand_dosync(gpiomtd);
}
if (cmd == NAND_CMD_NONE)
return;
writeb(cmd, gpiomtd->nand_chip.IO_ADDR_W);
gpio_nand_dosync(gpiomtd);
}
static void gpio_nand_writebuf(struct mtd_info *mtd, const u_char *buf, int len)
{
struct nand_chip *this = mtd->priv;
writesb(this->IO_ADDR_W, buf, len);
}
static void gpio_nand_readbuf(struct mtd_info *mtd, u_char *buf, int len)
{
struct nand_chip *this = mtd->priv;
readsb(this->IO_ADDR_R, buf, len);
}
static int gpio_nand_verifybuf(struct mtd_info *mtd, const u_char *buf, int len)
{
struct nand_chip *this = mtd->priv;
unsigned char read, *p = (unsigned char *) buf;
int i, err = 0;
for (i = 0; i < len; i++) {
read = readb(this->IO_ADDR_R);
if (read != p[i]) {
pr_debug("%s: err at %d (read %04x vs %04x)\n",
__func__, i, read, p[i]);
err = -EFAULT;
}
}
return err;
}
static void gpio_nand_writebuf16(struct mtd_info *mtd, const u_char *buf,
int len)
{
struct nand_chip *this = mtd->priv;
if (IS_ALIGNED((unsigned long)buf, 2)) {
writesw(this->IO_ADDR_W, buf, len>>1);
} else {
int i;
unsigned short *ptr = (unsigned short *)buf;
for (i = 0; i < len; i += 2, ptr++)
writew(*ptr, this->IO_ADDR_W);
}
}
static void gpio_nand_readbuf16(struct mtd_info *mtd, u_char *buf, int len)
{
struct nand_chip *this = mtd->priv;
if (IS_ALIGNED((unsigned long)buf, 2)) {
readsw(this->IO_ADDR_R, buf, len>>1);
} else {
int i;
unsigned short *ptr = (unsigned short *)buf;
for (i = 0; i < len; i += 2, ptr++)
*ptr = readw(this->IO_ADDR_R);
}
}
static int gpio_nand_verifybuf16(struct mtd_info *mtd, const u_char *buf,
int len)
{
struct nand_chip *this = mtd->priv;
unsigned short read, *p = (unsigned short *) buf;
int i, err = 0;
len >>= 1;
for (i = 0; i < len; i++) {
read = readw(this->IO_ADDR_R);
if (read != p[i]) {
pr_debug("%s: err at %d (read %04x vs %04x)\n",
__func__, i, read, p[i]);
err = -EFAULT;
}
}
return err;
}
static int gpio_nand_devready(struct mtd_info *mtd)
{
struct gpiomtd *gpiomtd = gpio_nand_getpriv(mtd);
return gpio_get_value(gpiomtd->plat.gpio_rdy);
}
#ifdef CONFIG_OF
static const struct of_device_id gpio_nand_id_table[] = {
{ .compatible = "gpio-control-nand" },
{}
};
MODULE_DEVICE_TABLE(of, gpio_nand_id_table);
static int gpio_nand_get_config_of(const struct device *dev,
struct gpio_nand_platdata *plat)
{
u32 val;
if (!of_property_read_u32(dev->of_node, "bank-width", &val)) {
if (val == 2) {
plat->options |= NAND_BUSWIDTH_16;
} else if (val != 1) {
dev_err(dev, "invalid bank-width %u\n", val);
return -EINVAL;
}
}
plat->gpio_rdy = of_get_gpio(dev->of_node, 0);
plat->gpio_nce = of_get_gpio(dev->of_node, 1);
plat->gpio_ale = of_get_gpio(dev->of_node, 2);
plat->gpio_cle = of_get_gpio(dev->of_node, 3);
plat->gpio_nwp = of_get_gpio(dev->of_node, 4);
if (!of_property_read_u32(dev->of_node, "chip-delay", &val))
plat->chip_delay = val;
return 0;
}
static struct resource *gpio_nand_get_io_sync_of(struct platform_device *pdev)
{
struct resource *r = devm_kzalloc(&pdev->dev, sizeof(*r), GFP_KERNEL);
u64 addr;
if (!r || of_property_read_u64(pdev->dev.of_node,
"gpio-control-nand,io-sync-reg", &addr))
return NULL;
r->start = addr;
r->end = r->start + 0x3;
r->flags = IORESOURCE_MEM;
return r;
}
#else /* CONFIG_OF */
#define gpio_nand_id_table NULL
static inline int gpio_nand_get_config_of(const struct device *dev,
struct gpio_nand_platdata *plat)
{
return -ENOSYS;
}
static inline struct resource *
gpio_nand_get_io_sync_of(struct platform_device *pdev)
{
return NULL;
}
#endif /* CONFIG_OF */
static inline int gpio_nand_get_config(const struct device *dev,
struct gpio_nand_platdata *plat)
{
int ret = gpio_nand_get_config_of(dev, plat);
if (!ret)
return ret;
if (dev->platform_data) {
memcpy(plat, dev->platform_data, sizeof(*plat));
return 0;
}
return -EINVAL;
}
static inline struct resource *
gpio_nand_get_io_sync(struct platform_device *pdev)
{
struct resource *r = gpio_nand_get_io_sync_of(pdev);
if (r)
return r;
return platform_get_resource(pdev, IORESOURCE_MEM, 1);
}
static int __devexit gpio_nand_remove(struct platform_device *dev)
{
struct gpiomtd *gpiomtd = platform_get_drvdata(dev);
struct resource *res;
nand_release(&gpiomtd->mtd_info);
res = gpio_nand_get_io_sync(dev);
iounmap(gpiomtd->io_sync);
if (res)
release_mem_region(res->start, resource_size(res));
res = platform_get_resource(dev, IORESOURCE_MEM, 0);
iounmap(gpiomtd->nand_chip.IO_ADDR_R);
release_mem_region(res->start, resource_size(res));
if (gpio_is_valid(gpiomtd->plat.gpio_nwp))
gpio_set_value(gpiomtd->plat.gpio_nwp, 0);
gpio_set_value(gpiomtd->plat.gpio_nce, 1);
gpio_free(gpiomtd->plat.gpio_cle);
gpio_free(gpiomtd->plat.gpio_ale);
gpio_free(gpiomtd->plat.gpio_nce);
if (gpio_is_valid(gpiomtd->plat.gpio_nwp))
gpio_free(gpiomtd->plat.gpio_nwp);
gpio_free(gpiomtd->plat.gpio_rdy);
kfree(gpiomtd);
return 0;
}
static void __iomem *request_and_remap(struct resource *res, size_t size,
const char *name, int *err)
{
void __iomem *ptr;
if (!request_mem_region(res->start, resource_size(res), name)) {
*err = -EBUSY;
return NULL;
}
ptr = ioremap(res->start, size);
if (!ptr) {
release_mem_region(res->start, resource_size(res));
*err = -ENOMEM;
}
return ptr;
}
static int __devinit gpio_nand_probe(struct platform_device *dev)
{
struct gpiomtd *gpiomtd;
struct nand_chip *this;
struct resource *res0, *res1;
struct mtd_part_parser_data ppdata = {};
int ret = 0;
if (!dev->dev.of_node && !dev->dev.platform_data)
return -EINVAL;
res0 = platform_get_resource(dev, IORESOURCE_MEM, 0);
if (!res0)
return -EINVAL;
gpiomtd = kzalloc(sizeof(*gpiomtd), GFP_KERNEL);
if (gpiomtd == NULL) {
dev_err(&dev->dev, "failed to create NAND MTD\n");
return -ENOMEM;
}
this = &gpiomtd->nand_chip;
this->IO_ADDR_R = request_and_remap(res0, 2, "NAND", &ret);
if (!this->IO_ADDR_R) {
dev_err(&dev->dev, "unable to map NAND\n");
goto err_map;
}
res1 = gpio_nand_get_io_sync(dev);
if (res1) {
gpiomtd->io_sync = request_and_remap(res1, 4, "NAND sync", &ret);
if (!gpiomtd->io_sync) {
dev_err(&dev->dev, "unable to map sync NAND\n");
goto err_sync;
}
}
ret = gpio_nand_get_config(&dev->dev, &gpiomtd->plat);
if (ret)
goto err_nce;
ret = gpio_request(gpiomtd->plat.gpio_nce, "NAND NCE");
if (ret)
goto err_nce;
gpio_direction_output(gpiomtd->plat.gpio_nce, 1);
if (gpio_is_valid(gpiomtd->plat.gpio_nwp)) {
ret = gpio_request(gpiomtd->plat.gpio_nwp, "NAND NWP");
if (ret)
goto err_nwp;
gpio_direction_output(gpiomtd->plat.gpio_nwp, 1);
}
ret = gpio_request(gpiomtd->plat.gpio_ale, "NAND ALE");
if (ret)
goto err_ale;
gpio_direction_output(gpiomtd->plat.gpio_ale, 0);
ret = gpio_request(gpiomtd->plat.gpio_cle, "NAND CLE");
if (ret)
goto err_cle;
gpio_direction_output(gpiomtd->plat.gpio_cle, 0);
ret = gpio_request(gpiomtd->plat.gpio_rdy, "NAND RDY");
if (ret)
goto err_rdy;
gpio_direction_input(gpiomtd->plat.gpio_rdy);
this->IO_ADDR_W = this->IO_ADDR_R;
this->ecc.mode = NAND_ECC_SOFT;
this->options = gpiomtd->plat.options;
this->chip_delay = gpiomtd->plat.chip_delay;
/* install our routines */
this->cmd_ctrl = gpio_nand_cmd_ctrl;
this->dev_ready = gpio_nand_devready;
if (this->options & NAND_BUSWIDTH_16) {
this->read_buf = gpio_nand_readbuf16;
this->write_buf = gpio_nand_writebuf16;
this->verify_buf = gpio_nand_verifybuf16;
} else {
this->read_buf = gpio_nand_readbuf;
this->write_buf = gpio_nand_writebuf;
this->verify_buf = gpio_nand_verifybuf;
}
/* set the mtd private data for the nand driver */
gpiomtd->mtd_info.priv = this;
gpiomtd->mtd_info.owner = THIS_MODULE;
if (nand_scan(&gpiomtd->mtd_info, 1)) {
dev_err(&dev->dev, "no nand chips found?\n");
ret = -ENXIO;
goto err_wp;
}
if (gpiomtd->plat.adjust_parts)
gpiomtd->plat.adjust_parts(&gpiomtd->plat,
gpiomtd->mtd_info.size);
ppdata.of_node = dev->dev.of_node;
ret = mtd_device_parse_register(&gpiomtd->mtd_info, NULL, &ppdata,
gpiomtd->plat.parts,
gpiomtd->plat.num_parts);
if (ret)
goto err_wp;
platform_set_drvdata(dev, gpiomtd);
return 0;
err_wp:
if (gpio_is_valid(gpiomtd->plat.gpio_nwp))
gpio_set_value(gpiomtd->plat.gpio_nwp, 0);
gpio_free(gpiomtd->plat.gpio_rdy);
err_rdy:
gpio_free(gpiomtd->plat.gpio_cle);
err_cle:
gpio_free(gpiomtd->plat.gpio_ale);
err_ale:
if (gpio_is_valid(gpiomtd->plat.gpio_nwp))
gpio_free(gpiomtd->plat.gpio_nwp);
err_nwp:
gpio_free(gpiomtd->plat.gpio_nce);
err_nce:
iounmap(gpiomtd->io_sync);
if (res1)
release_mem_region(res1->start, resource_size(res1));
err_sync:
iounmap(gpiomtd->nand_chip.IO_ADDR_R);
release_mem_region(res0->start, resource_size(res0));
err_map:
kfree(gpiomtd);
return ret;
}
static struct platform_driver gpio_nand_driver = {
.probe = gpio_nand_probe,
.remove = gpio_nand_remove,
.driver = {
.name = "gpio-nand",
.of_match_table = gpio_nand_id_table,
},
};
static int __init gpio_nand_init(void)
{
printk(KERN_INFO "GPIO NAND driver, © 2004 Simtec Electronics\n");
return platform_driver_register(&gpio_nand_driver);
}
static void __exit gpio_nand_exit(void)
{
platform_driver_unregister(&gpio_nand_driver);
}
module_init(gpio_nand_init);
module_exit(gpio_nand_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Ben Dooks <ben@simtec.co.uk>");
MODULE_DESCRIPTION("GPIO NAND Driver");
| gpl-2.0 |
InfinitiveOS-Devices/android_kernel_huawei_msm8916 | drivers/usb/mon/mon_stat.c | 8868 | 1569 | /*
* The USB Monitor, inspired by Dave Harding's USBMon.
*
* This is the 's' or 'stat' reader which debugs usbmon itself.
* Note that this code blows through locks, so make sure that
* /dbg/usbmon/0s is well protected from non-root users.
*
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/export.h>
#include <linux/usb.h>
#include <linux/fs.h>
#include <asm/uaccess.h>
#include "usb_mon.h"
#define STAT_BUF_SIZE 80
struct snap {
int slen;
char str[STAT_BUF_SIZE];
};
static int mon_stat_open(struct inode *inode, struct file *file)
{
struct mon_bus *mbus;
struct snap *sp;
if ((sp = kmalloc(sizeof(struct snap), GFP_KERNEL)) == NULL)
return -ENOMEM;
mbus = inode->i_private;
sp->slen = snprintf(sp->str, STAT_BUF_SIZE,
"nreaders %d events %u text_lost %u\n",
mbus->nreaders, mbus->cnt_events, mbus->cnt_text_lost);
file->private_data = sp;
return 0;
}
static ssize_t mon_stat_read(struct file *file, char __user *buf,
size_t nbytes, loff_t *ppos)
{
struct snap *sp = file->private_data;
return simple_read_from_buffer(buf, nbytes, ppos, sp->str, sp->slen);
}
static int mon_stat_release(struct inode *inode, struct file *file)
{
struct snap *sp = file->private_data;
file->private_data = NULL;
kfree(sp);
return 0;
}
const struct file_operations mon_fops_stat = {
.owner = THIS_MODULE,
.open = mon_stat_open,
.llseek = no_llseek,
.read = mon_stat_read,
/* .write = mon_stat_write, */
/* .poll = mon_stat_poll, */
/* .unlocked_ioctl = mon_stat_ioctl, */
.release = mon_stat_release,
};
| gpl-2.0 |
GrinningFerret/android_kernel_lge_w7 | arch/m32r/lib/usercopy.c | 13732 | 9059 | /*
* User address space access functions.
* The non inlined parts of asm-m32r/uaccess.h are here.
*
* Copyright 1997 Andi Kleen <ak@muc.de>
* Copyright 1997 Linus Torvalds
* Copyright 2001, 2002, 2004 Hirokazu Takata
*/
#include <linux/prefetch.h>
#include <linux/string.h>
#include <linux/thread_info.h>
#include <asm/uaccess.h>
unsigned long
__generic_copy_to_user(void __user *to, const void *from, unsigned long n)
{
prefetch(from);
if (access_ok(VERIFY_WRITE, to, n))
__copy_user(to,from,n);
return n;
}
unsigned long
__generic_copy_from_user(void *to, const void __user *from, unsigned long n)
{
prefetchw(to);
if (access_ok(VERIFY_READ, from, n))
__copy_user_zeroing(to,from,n);
else
memset(to, 0, n);
return n;
}
/*
* Copy a null terminated string from userspace.
*/
#ifdef CONFIG_ISA_DUAL_ISSUE
#define __do_strncpy_from_user(dst,src,count,res) \
do { \
int __d0, __d1, __d2; \
__asm__ __volatile__( \
" beqz %1, 2f\n" \
" .fillinsn\n" \
"0: ldb r14, @%3 || addi %3, #1\n" \
" stb r14, @%4 || addi %4, #1\n" \
" beqz r14, 1f\n" \
" addi %1, #-1\n" \
" bnez %1, 0b\n" \
" .fillinsn\n" \
"1: sub %0, %1\n" \
" .fillinsn\n" \
"2:\n" \
".section .fixup,\"ax\"\n" \
" .balign 4\n" \
"3: seth r14, #high(2b)\n" \
" or3 r14, r14, #low(2b)\n" \
" jmp r14 || ldi %0, #%5\n" \
".previous\n" \
".section __ex_table,\"a\"\n" \
" .balign 4\n" \
" .long 0b,3b\n" \
".previous" \
: "=&r"(res), "=&r"(count), "=&r" (__d0), "=&r" (__d1), \
"=&r" (__d2) \
: "i"(-EFAULT), "0"(count), "1"(count), "3"(src), \
"4"(dst) \
: "r14", "cbit", "memory"); \
} while (0)
#else /* not CONFIG_ISA_DUAL_ISSUE */
#define __do_strncpy_from_user(dst,src,count,res) \
do { \
int __d0, __d1, __d2; \
__asm__ __volatile__( \
" beqz %1, 2f\n" \
" .fillinsn\n" \
"0: ldb r14, @%3\n" \
" stb r14, @%4\n" \
" addi %3, #1\n" \
" addi %4, #1\n" \
" beqz r14, 1f\n" \
" addi %1, #-1\n" \
" bnez %1, 0b\n" \
" .fillinsn\n" \
"1: sub %0, %1\n" \
" .fillinsn\n" \
"2:\n" \
".section .fixup,\"ax\"\n" \
" .balign 4\n" \
"3: ldi %0, #%5\n" \
" seth r14, #high(2b)\n" \
" or3 r14, r14, #low(2b)\n" \
" jmp r14\n" \
".previous\n" \
".section __ex_table,\"a\"\n" \
" .balign 4\n" \
" .long 0b,3b\n" \
".previous" \
: "=&r"(res), "=&r"(count), "=&r" (__d0), "=&r" (__d1), \
"=&r" (__d2) \
: "i"(-EFAULT), "0"(count), "1"(count), "3"(src), \
"4"(dst) \
: "r14", "cbit", "memory"); \
} while (0)
#endif /* CONFIG_ISA_DUAL_ISSUE */
long
__strncpy_from_user(char *dst, const char __user *src, long count)
{
long res;
__do_strncpy_from_user(dst, src, count, res);
return res;
}
long
strncpy_from_user(char *dst, const char __user *src, long count)
{
long res = -EFAULT;
if (access_ok(VERIFY_READ, src, 1))
__do_strncpy_from_user(dst, src, count, res);
return res;
}
/*
* Zero Userspace
*/
#ifdef CONFIG_ISA_DUAL_ISSUE
#define __do_clear_user(addr,size) \
do { \
int __dst, __c; \
__asm__ __volatile__( \
" beqz %1, 9f\n" \
" and3 r14, %0, #3\n" \
" bnez r14, 2f\n" \
" and3 r14, %1, #3\n" \
" bnez r14, 2f\n" \
" and3 %1, %1, #3\n" \
" beqz %2, 2f\n" \
" addi %0, #-4\n" \
" .fillinsn\n" \
"0: ; word clear \n" \
" st %6, @+%0 || addi %2, #-1\n" \
" bnez %2, 0b\n" \
" beqz %1, 9f\n" \
" .fillinsn\n" \
"2: ; byte clear \n" \
" stb %6, @%0 || addi %1, #-1\n" \
" addi %0, #1\n" \
" bnez %1, 2b\n" \
" .fillinsn\n" \
"9:\n" \
".section .fixup,\"ax\"\n" \
" .balign 4\n" \
"4: slli %2, #2\n" \
" seth r14, #high(9b)\n" \
" or3 r14, r14, #low(9b)\n" \
" jmp r14 || add %1, %2\n" \
".previous\n" \
".section __ex_table,\"a\"\n" \
" .balign 4\n" \
" .long 0b,4b\n" \
" .long 2b,9b\n" \
".previous\n" \
: "=&r"(__dst), "=&r"(size), "=&r"(__c) \
: "0"(addr), "1"(size), "2"(size / 4), "r"(0) \
: "r14", "cbit", "memory"); \
} while (0)
#else /* not CONFIG_ISA_DUAL_ISSUE */
#define __do_clear_user(addr,size) \
do { \
int __dst, __c; \
__asm__ __volatile__( \
" beqz %1, 9f\n" \
" and3 r14, %0, #3\n" \
" bnez r14, 2f\n" \
" and3 r14, %1, #3\n" \
" bnez r14, 2f\n" \
" and3 %1, %1, #3\n" \
" beqz %2, 2f\n" \
" addi %0, #-4\n" \
" .fillinsn\n" \
"0: st %6, @+%0 ; word clear \n" \
" addi %2, #-1\n" \
" bnez %2, 0b\n" \
" beqz %1, 9f\n" \
" .fillinsn\n" \
"2: stb %6, @%0 ; byte clear \n" \
" addi %1, #-1\n" \
" addi %0, #1\n" \
" bnez %1, 2b\n" \
" .fillinsn\n" \
"9:\n" \
".section .fixup,\"ax\"\n" \
" .balign 4\n" \
"4: slli %2, #2\n" \
" add %1, %2\n" \
" seth r14, #high(9b)\n" \
" or3 r14, r14, #low(9b)\n" \
" jmp r14\n" \
".previous\n" \
".section __ex_table,\"a\"\n" \
" .balign 4\n" \
" .long 0b,4b\n" \
" .long 2b,9b\n" \
".previous\n" \
: "=&r"(__dst), "=&r"(size), "=&r"(__c) \
: "0"(addr), "1"(size), "2"(size / 4), "r"(0) \
: "r14", "cbit", "memory"); \
} while (0)
#endif /* not CONFIG_ISA_DUAL_ISSUE */
unsigned long
clear_user(void __user *to, unsigned long n)
{
if (access_ok(VERIFY_WRITE, to, n))
__do_clear_user(to, n);
return n;
}
unsigned long
__clear_user(void __user *to, unsigned long n)
{
__do_clear_user(to, n);
return n;
}
/*
* Return the size of a string (including the ending 0)
*
* Return 0 on exception, a value greater than N if too long
*/
#ifdef CONFIG_ISA_DUAL_ISSUE
long strnlen_user(const char __user *s, long n)
{
unsigned long mask = -__addr_ok(s);
unsigned long res;
__asm__ __volatile__(
" and %0, %5 || mv r1, %1\n"
" beqz %0, strnlen_exit\n"
" and3 r0, %1, #3\n"
" bnez r0, strnlen_byte_loop\n"
" cmpui %0, #4\n"
" bc strnlen_byte_loop\n"
"strnlen_word_loop:\n"
"0: ld r0, @%1+\n"
" pcmpbz r0\n"
" bc strnlen_last_bytes_fixup\n"
" addi %0, #-4\n"
" beqz %0, strnlen_exit\n"
" bgtz %0, strnlen_word_loop\n"
"strnlen_last_bytes:\n"
" mv %0, %4\n"
"strnlen_last_bytes_fixup:\n"
" addi %1, #-4\n"
"strnlen_byte_loop:\n"
"1: ldb r0, @%1 || addi %0, #-1\n"
" beqz r0, strnlen_exit\n"
" addi %1, #1\n"
" bnez %0, strnlen_byte_loop\n"
"strnlen_exit:\n"
" sub %1, r1\n"
" add3 %0, %1, #1\n"
" .fillinsn\n"
"9:\n"
".section .fixup,\"ax\"\n"
" .balign 4\n"
"4: addi %1, #-4\n"
" .fillinsn\n"
"5: seth r1, #high(9b)\n"
" or3 r1, r1, #low(9b)\n"
" jmp r1 || ldi %0, #0\n"
".previous\n"
".section __ex_table,\"a\"\n"
" .balign 4\n"
" .long 0b,4b\n"
" .long 1b,5b\n"
".previous"
: "=&r" (res), "=r" (s)
: "0" (n), "1" (s), "r" (n & 3), "r" (mask), "r"(0x01010101)
: "r0", "r1", "cbit");
/* NOTE: strnlen_user() algorithm:
* {
* char *p;
* for (p = s; n-- && *p != '\0'; ++p)
* ;
* return p - s + 1;
* }
*/
/* NOTE: If a null char. exists, return 0.
* if ((x - 0x01010101) & ~x & 0x80808080)\n"
* return 0;\n"
*/
return res & mask;
}
#else /* not CONFIG_ISA_DUAL_ISSUE */
long strnlen_user(const char __user *s, long n)
{
unsigned long mask = -__addr_ok(s);
unsigned long res;
__asm__ __volatile__(
" and %0, %5\n"
" mv r1, %1\n"
" beqz %0, strnlen_exit\n"
" and3 r0, %1, #3\n"
" bnez r0, strnlen_byte_loop\n"
" cmpui %0, #4\n"
" bc strnlen_byte_loop\n"
" sll3 r3, %6, #7\n"
"strnlen_word_loop:\n"
"0: ld r0, @%1+\n"
" not r2, r0\n"
" sub r0, %6\n"
" and r2, r3\n"
" and r2, r0\n"
" bnez r2, strnlen_last_bytes_fixup\n"
" addi %0, #-4\n"
" beqz %0, strnlen_exit\n"
" bgtz %0, strnlen_word_loop\n"
"strnlen_last_bytes:\n"
" mv %0, %4\n"
"strnlen_last_bytes_fixup:\n"
" addi %1, #-4\n"
"strnlen_byte_loop:\n"
"1: ldb r0, @%1\n"
" addi %0, #-1\n"
" beqz r0, strnlen_exit\n"
" addi %1, #1\n"
" bnez %0, strnlen_byte_loop\n"
"strnlen_exit:\n"
" sub %1, r1\n"
" add3 %0, %1, #1\n"
" .fillinsn\n"
"9:\n"
".section .fixup,\"ax\"\n"
" .balign 4\n"
"4: addi %1, #-4\n"
" .fillinsn\n"
"5: ldi %0, #0\n"
" seth r1, #high(9b)\n"
" or3 r1, r1, #low(9b)\n"
" jmp r1\n"
".previous\n"
".section __ex_table,\"a\"\n"
" .balign 4\n"
" .long 0b,4b\n"
" .long 1b,5b\n"
".previous"
: "=&r" (res), "=r" (s)
: "0" (n), "1" (s), "r" (n & 3), "r" (mask), "r"(0x01010101)
: "r0", "r1", "r2", "r3", "cbit");
/* NOTE: strnlen_user() algorithm:
* {
* char *p;
* for (p = s; n-- && *p != '\0'; ++p)
* ;
* return p - s + 1;
* }
*/
/* NOTE: If a null char. exists, return 0.
* if ((x - 0x01010101) & ~x & 0x80808080)\n"
* return 0;\n"
*/
return res & mask;
}
#endif /* CONFIG_ISA_DUAL_ISSUE */
| gpl-2.0 |
garwynn/D710BST_FL24_Kernel | drivers/input/joystick/iforce/iforce-ff.c | 14756 | 15609 | /*
* Copyright (c) 2000-2002 Vojtech Pavlik <vojtech@ucw.cz>
* Copyright (c) 2001-2002, 2007 Johann Deneux <johann.deneux@gmail.com>
*
* USB/RS232 I-Force joysticks and wheels.
*/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Should you need to contact me, the author, you can do so either by
* e-mail - mail your message to <vojtech@ucw.cz>, or by paper mail:
* Vojtech Pavlik, Simunkova 1594, Prague 8, 182 00 Czech Republic
*/
#include "iforce.h"
/*
* Set the magnitude of a constant force effect
* Return error code
*
* Note: caller must ensure exclusive access to device
*/
static int make_magnitude_modifier(struct iforce* iforce,
struct resource* mod_chunk, int no_alloc, __s16 level)
{
unsigned char data[3];
if (!no_alloc) {
mutex_lock(&iforce->mem_mutex);
if (allocate_resource(&(iforce->device_memory), mod_chunk, 2,
iforce->device_memory.start, iforce->device_memory.end, 2L,
NULL, NULL)) {
mutex_unlock(&iforce->mem_mutex);
return -ENOSPC;
}
mutex_unlock(&iforce->mem_mutex);
}
data[0] = LO(mod_chunk->start);
data[1] = HI(mod_chunk->start);
data[2] = HIFIX80(level);
iforce_send_packet(iforce, FF_CMD_MAGNITUDE, data);
iforce_dump_packet("magnitude: ", FF_CMD_MAGNITUDE, data);
return 0;
}
/*
* Upload the component of an effect dealing with the period, phase and magnitude
*/
static int make_period_modifier(struct iforce* iforce,
struct resource* mod_chunk, int no_alloc,
__s16 magnitude, __s16 offset, u16 period, u16 phase)
{
unsigned char data[7];
period = TIME_SCALE(period);
if (!no_alloc) {
mutex_lock(&iforce->mem_mutex);
if (allocate_resource(&(iforce->device_memory), mod_chunk, 0x0c,
iforce->device_memory.start, iforce->device_memory.end, 2L,
NULL, NULL)) {
mutex_unlock(&iforce->mem_mutex);
return -ENOSPC;
}
mutex_unlock(&iforce->mem_mutex);
}
data[0] = LO(mod_chunk->start);
data[1] = HI(mod_chunk->start);
data[2] = HIFIX80(magnitude);
data[3] = HIFIX80(offset);
data[4] = HI(phase);
data[5] = LO(period);
data[6] = HI(period);
iforce_send_packet(iforce, FF_CMD_PERIOD, data);
return 0;
}
/*
* Uploads the part of an effect setting the envelope of the force
*/
static int make_envelope_modifier(struct iforce* iforce,
struct resource* mod_chunk, int no_alloc,
u16 attack_duration, __s16 initial_level,
u16 fade_duration, __s16 final_level)
{
unsigned char data[8];
attack_duration = TIME_SCALE(attack_duration);
fade_duration = TIME_SCALE(fade_duration);
if (!no_alloc) {
mutex_lock(&iforce->mem_mutex);
if (allocate_resource(&(iforce->device_memory), mod_chunk, 0x0e,
iforce->device_memory.start, iforce->device_memory.end, 2L,
NULL, NULL)) {
mutex_unlock(&iforce->mem_mutex);
return -ENOSPC;
}
mutex_unlock(&iforce->mem_mutex);
}
data[0] = LO(mod_chunk->start);
data[1] = HI(mod_chunk->start);
data[2] = LO(attack_duration);
data[3] = HI(attack_duration);
data[4] = HI(initial_level);
data[5] = LO(fade_duration);
data[6] = HI(fade_duration);
data[7] = HI(final_level);
iforce_send_packet(iforce, FF_CMD_ENVELOPE, data);
return 0;
}
/*
* Component of spring, friction, inertia... effects
*/
static int make_condition_modifier(struct iforce* iforce,
struct resource* mod_chunk, int no_alloc,
__u16 rsat, __u16 lsat, __s16 rk, __s16 lk, u16 db, __s16 center)
{
unsigned char data[10];
if (!no_alloc) {
mutex_lock(&iforce->mem_mutex);
if (allocate_resource(&(iforce->device_memory), mod_chunk, 8,
iforce->device_memory.start, iforce->device_memory.end, 2L,
NULL, NULL)) {
mutex_unlock(&iforce->mem_mutex);
return -ENOSPC;
}
mutex_unlock(&iforce->mem_mutex);
}
data[0] = LO(mod_chunk->start);
data[1] = HI(mod_chunk->start);
data[2] = (100 * rk) >> 15; /* Dangerous: the sign is extended by gcc on plateforms providing an arith shift */
data[3] = (100 * lk) >> 15; /* This code is incorrect on cpus lacking arith shift */
center = (500 * center) >> 15;
data[4] = LO(center);
data[5] = HI(center);
db = (1000 * db) >> 16;
data[6] = LO(db);
data[7] = HI(db);
data[8] = (100 * rsat) >> 16;
data[9] = (100 * lsat) >> 16;
iforce_send_packet(iforce, FF_CMD_CONDITION, data);
iforce_dump_packet("condition", FF_CMD_CONDITION, data);
return 0;
}
static unsigned char find_button(struct iforce *iforce, signed short button)
{
int i;
for (i = 1; iforce->type->btn[i] >= 0; i++)
if (iforce->type->btn[i] == button)
return i + 1;
return 0;
}
/*
* Analyse the changes in an effect, and tell if we need to send an condition
* parameter packet
*/
static int need_condition_modifier(struct iforce *iforce,
struct ff_effect *old,
struct ff_effect *new)
{
int ret = 0;
int i;
if (new->type != FF_SPRING && new->type != FF_FRICTION) {
dev_warn(&iforce->dev->dev, "bad effect type in %s\n",
__func__);
return 0;
}
for (i = 0; i < 2; i++) {
ret |= old->u.condition[i].right_saturation != new->u.condition[i].right_saturation
|| old->u.condition[i].left_saturation != new->u.condition[i].left_saturation
|| old->u.condition[i].right_coeff != new->u.condition[i].right_coeff
|| old->u.condition[i].left_coeff != new->u.condition[i].left_coeff
|| old->u.condition[i].deadband != new->u.condition[i].deadband
|| old->u.condition[i].center != new->u.condition[i].center;
}
return ret;
}
/*
* Analyse the changes in an effect, and tell if we need to send a magnitude
* parameter packet
*/
static int need_magnitude_modifier(struct iforce *iforce,
struct ff_effect *old,
struct ff_effect *effect)
{
if (effect->type != FF_CONSTANT) {
dev_warn(&iforce->dev->dev, "bad effect type in %s\n",
__func__);
return 0;
}
return old->u.constant.level != effect->u.constant.level;
}
/*
* Analyse the changes in an effect, and tell if we need to send an envelope
* parameter packet
*/
static int need_envelope_modifier(struct iforce *iforce, struct ff_effect *old,
struct ff_effect *effect)
{
switch (effect->type) {
case FF_CONSTANT:
if (old->u.constant.envelope.attack_length != effect->u.constant.envelope.attack_length
|| old->u.constant.envelope.attack_level != effect->u.constant.envelope.attack_level
|| old->u.constant.envelope.fade_length != effect->u.constant.envelope.fade_length
|| old->u.constant.envelope.fade_level != effect->u.constant.envelope.fade_level)
return 1;
break;
case FF_PERIODIC:
if (old->u.periodic.envelope.attack_length != effect->u.periodic.envelope.attack_length
|| old->u.periodic.envelope.attack_level != effect->u.periodic.envelope.attack_level
|| old->u.periodic.envelope.fade_length != effect->u.periodic.envelope.fade_length
|| old->u.periodic.envelope.fade_level != effect->u.periodic.envelope.fade_level)
return 1;
break;
default:
dev_warn(&iforce->dev->dev, "bad effect type in %s\n",
__func__);
}
return 0;
}
/*
* Analyse the changes in an effect, and tell if we need to send a periodic
* parameter effect
*/
static int need_period_modifier(struct iforce *iforce, struct ff_effect *old,
struct ff_effect *new)
{
if (new->type != FF_PERIODIC) {
dev_warn(&iforce->dev->dev, "bad effect type in %s\n",
__func__);
return 0;
}
return (old->u.periodic.period != new->u.periodic.period
|| old->u.periodic.magnitude != new->u.periodic.magnitude
|| old->u.periodic.offset != new->u.periodic.offset
|| old->u.periodic.phase != new->u.periodic.phase);
}
/*
* Analyse the changes in an effect, and tell if we need to send an effect
* packet
*/
static int need_core(struct ff_effect *old, struct ff_effect *new)
{
if (old->direction != new->direction
|| old->trigger.button != new->trigger.button
|| old->trigger.interval != new->trigger.interval
|| old->replay.length != new->replay.length
|| old->replay.delay != new->replay.delay)
return 1;
return 0;
}
/*
* Send the part common to all effects to the device
*/
static int make_core(struct iforce* iforce, u16 id, u16 mod_id1, u16 mod_id2,
u8 effect_type, u8 axes, u16 duration, u16 delay, u16 button,
u16 interval, u16 direction)
{
unsigned char data[14];
duration = TIME_SCALE(duration);
delay = TIME_SCALE(delay);
interval = TIME_SCALE(interval);
data[0] = LO(id);
data[1] = effect_type;
data[2] = LO(axes) | find_button(iforce, button);
data[3] = LO(duration);
data[4] = HI(duration);
data[5] = HI(direction);
data[6] = LO(interval);
data[7] = HI(interval);
data[8] = LO(mod_id1);
data[9] = HI(mod_id1);
data[10] = LO(mod_id2);
data[11] = HI(mod_id2);
data[12] = LO(delay);
data[13] = HI(delay);
/* Stop effect */
/* iforce_control_playback(iforce, id, 0);*/
iforce_send_packet(iforce, FF_CMD_EFFECT, data);
/* If needed, restart effect */
if (test_bit(FF_CORE_SHOULD_PLAY, iforce->core_effects[id].flags)) {
/* BUG: perhaps we should replay n times, instead of 1. But we do not know n */
iforce_control_playback(iforce, id, 1);
}
return 0;
}
/*
* Upload a periodic effect to the device
* See also iforce_upload_constant.
*/
int iforce_upload_periodic(struct iforce *iforce, struct ff_effect *effect, struct ff_effect *old)
{
u8 wave_code;
int core_id = effect->id;
struct iforce_core_effect* core_effect = iforce->core_effects + core_id;
struct resource* mod1_chunk = &(iforce->core_effects[core_id].mod1_chunk);
struct resource* mod2_chunk = &(iforce->core_effects[core_id].mod2_chunk);
int param1_err = 1;
int param2_err = 1;
int core_err = 0;
if (!old || need_period_modifier(iforce, old, effect)) {
param1_err = make_period_modifier(iforce, mod1_chunk,
old != NULL,
effect->u.periodic.magnitude, effect->u.periodic.offset,
effect->u.periodic.period, effect->u.periodic.phase);
if (param1_err)
return param1_err;
set_bit(FF_MOD1_IS_USED, core_effect->flags);
}
if (!old || need_envelope_modifier(iforce, old, effect)) {
param2_err = make_envelope_modifier(iforce, mod2_chunk,
old !=NULL,
effect->u.periodic.envelope.attack_length,
effect->u.periodic.envelope.attack_level,
effect->u.periodic.envelope.fade_length,
effect->u.periodic.envelope.fade_level);
if (param2_err)
return param2_err;
set_bit(FF_MOD2_IS_USED, core_effect->flags);
}
switch (effect->u.periodic.waveform) {
case FF_SQUARE: wave_code = 0x20; break;
case FF_TRIANGLE: wave_code = 0x21; break;
case FF_SINE: wave_code = 0x22; break;
case FF_SAW_UP: wave_code = 0x23; break;
case FF_SAW_DOWN: wave_code = 0x24; break;
default: wave_code = 0x20; break;
}
if (!old || need_core(old, effect)) {
core_err = make_core(iforce, effect->id,
mod1_chunk->start,
mod2_chunk->start,
wave_code,
0x20,
effect->replay.length,
effect->replay.delay,
effect->trigger.button,
effect->trigger.interval,
effect->direction);
}
/* If one of the parameter creation failed, we already returned an
* error code.
* If the core creation failed, we return its error code.
* Else: if one parameter at least was created, we return 0
* else we return 1;
*/
return core_err < 0 ? core_err : (param1_err && param2_err);
}
/*
* Upload a constant force effect
* Return value:
* <0 Error code
* 0 Ok, effect created or updated
* 1 effect did not change since last upload, and no packet was therefore sent
*/
int iforce_upload_constant(struct iforce *iforce, struct ff_effect *effect, struct ff_effect *old)
{
int core_id = effect->id;
struct iforce_core_effect* core_effect = iforce->core_effects + core_id;
struct resource* mod1_chunk = &(iforce->core_effects[core_id].mod1_chunk);
struct resource* mod2_chunk = &(iforce->core_effects[core_id].mod2_chunk);
int param1_err = 1;
int param2_err = 1;
int core_err = 0;
if (!old || need_magnitude_modifier(iforce, old, effect)) {
param1_err = make_magnitude_modifier(iforce, mod1_chunk,
old != NULL,
effect->u.constant.level);
if (param1_err)
return param1_err;
set_bit(FF_MOD1_IS_USED, core_effect->flags);
}
if (!old || need_envelope_modifier(iforce, old, effect)) {
param2_err = make_envelope_modifier(iforce, mod2_chunk,
old != NULL,
effect->u.constant.envelope.attack_length,
effect->u.constant.envelope.attack_level,
effect->u.constant.envelope.fade_length,
effect->u.constant.envelope.fade_level);
if (param2_err)
return param2_err;
set_bit(FF_MOD2_IS_USED, core_effect->flags);
}
if (!old || need_core(old, effect)) {
core_err = make_core(iforce, effect->id,
mod1_chunk->start,
mod2_chunk->start,
0x00,
0x20,
effect->replay.length,
effect->replay.delay,
effect->trigger.button,
effect->trigger.interval,
effect->direction);
}
/* If one of the parameter creation failed, we already returned an
* error code.
* If the core creation failed, we return its error code.
* Else: if one parameter at least was created, we return 0
* else we return 1;
*/
return core_err < 0 ? core_err : (param1_err && param2_err);
}
/*
* Upload an condition effect. Those are for example friction, inertia, springs...
*/
int iforce_upload_condition(struct iforce *iforce, struct ff_effect *effect, struct ff_effect *old)
{
int core_id = effect->id;
struct iforce_core_effect* core_effect = iforce->core_effects + core_id;
struct resource* mod1_chunk = &(core_effect->mod1_chunk);
struct resource* mod2_chunk = &(core_effect->mod2_chunk);
u8 type;
int param_err = 1;
int core_err = 0;
switch (effect->type) {
case FF_SPRING: type = 0x40; break;
case FF_DAMPER: type = 0x41; break;
default: return -1;
}
if (!old || need_condition_modifier(iforce, old, effect)) {
param_err = make_condition_modifier(iforce, mod1_chunk,
old != NULL,
effect->u.condition[0].right_saturation,
effect->u.condition[0].left_saturation,
effect->u.condition[0].right_coeff,
effect->u.condition[0].left_coeff,
effect->u.condition[0].deadband,
effect->u.condition[0].center);
if (param_err)
return param_err;
set_bit(FF_MOD1_IS_USED, core_effect->flags);
param_err = make_condition_modifier(iforce, mod2_chunk,
old != NULL,
effect->u.condition[1].right_saturation,
effect->u.condition[1].left_saturation,
effect->u.condition[1].right_coeff,
effect->u.condition[1].left_coeff,
effect->u.condition[1].deadband,
effect->u.condition[1].center);
if (param_err)
return param_err;
set_bit(FF_MOD2_IS_USED, core_effect->flags);
}
if (!old || need_core(old, effect)) {
core_err = make_core(iforce, effect->id,
mod1_chunk->start, mod2_chunk->start,
type, 0xc0,
effect->replay.length, effect->replay.delay,
effect->trigger.button, effect->trigger.interval,
effect->direction);
}
/* If the parameter creation failed, we already returned an
* error code.
* If the core creation failed, we return its error code.
* Else: if a parameter was created, we return 0
* else we return 1;
*/
return core_err < 0 ? core_err : param_err;
}
| gpl-2.0 |
vwmofo/SebastianFM-kernel | drivers/net/wireless/bcmdhd/sbutils.c | 165 | 24913 | /*
* Misc utility routines for accessing chip-specific features
* of the SiliconBackplane-based Broadcom chips.
*
* Copyright (C) 1999-2011, Broadcom Corporation
*
* Unless you and Broadcom execute a separate written software license
* agreement governing use of this software, this software is licensed to you
* under the terms of the GNU General Public License version 2 (the "GPL"),
* available at http://www.broadcom.com/licenses/GPLv2.php, with the
* following added to such license:
*
* As a special exception, the copyright holders of this software give you
* permission to link this software with independent modules, and to copy and
* distribute the resulting executable under terms of your choice, provided that
* you also meet, for each linked independent module, the terms and conditions of
* the license of that module. An independent module is a module which is not
* derived from this software. The special exception does not apply to any
* modifications of the software.
*
* Notwithstanding the above, under no circumstances may you combine this
* software in any way with any other Broadcom software provided under a license
* other than the GPL, without Broadcom's express prior written consent.
*
* $Id: sbutils.c 275693 2011-08-04 19:59:34Z $
*/
#include <typedefs.h>
#include <bcmdefs.h>
#include <osl.h>
#include <bcmutils.h>
#include <siutils.h>
#include <bcmdevs.h>
#include <hndsoc.h>
#include <sbchipc.h>
#include <pcicfg.h>
#include <sbpcmcia.h>
#include "siutils_priv.h"
/* local prototypes */
static uint _sb_coreidx(si_info_t *sii, uint32 sba);
static uint _sb_scan(si_info_t *sii, uint32 sba, void *regs, uint bus, uint32 sbba,
uint ncores);
static uint32 _sb_coresba(si_info_t *sii);
static void *_sb_setcoreidx(si_info_t *sii, uint coreidx);
#define SET_SBREG(sii, r, mask, val) \
W_SBREG((sii), (r), ((R_SBREG((sii), (r)) & ~(mask)) | (val)))
#define REGS2SB(va) (sbconfig_t*) ((int8*)(va) + SBCONFIGOFF)
/* sonicsrev */
#define SONICS_2_2 (SBIDL_RV_2_2 >> SBIDL_RV_SHIFT)
#define SONICS_2_3 (SBIDL_RV_2_3 >> SBIDL_RV_SHIFT)
#define R_SBREG(sii, sbr) sb_read_sbreg((sii), (sbr))
#define W_SBREG(sii, sbr, v) sb_write_sbreg((sii), (sbr), (v))
#define AND_SBREG(sii, sbr, v) W_SBREG((sii), (sbr), (R_SBREG((sii), (sbr)) & (v)))
#define OR_SBREG(sii, sbr, v) W_SBREG((sii), (sbr), (R_SBREG((sii), (sbr)) | (v)))
static uint32
sb_read_sbreg(si_info_t *sii, volatile uint32 *sbr)
{
uint8 tmp;
uint32 val, intr_val = 0;
/*
* compact flash only has 11 bits address, while we needs 12 bits address.
* MEM_SEG will be OR'd with other 11 bits address in hardware,
* so we program MEM_SEG with 12th bit when necessary(access sb regsiters).
* For normal PCMCIA bus(CFTable_regwinsz > 2k), do nothing special
*/
if (PCMCIA(sii)) {
INTR_OFF(sii, intr_val);
tmp = 1;
OSL_PCMCIA_WRITE_ATTR(sii->osh, MEM_SEG, &tmp, 1);
sbr = (volatile uint32 *)((uintptr)sbr & ~(1 << 11)); /* mask out bit 11 */
}
val = R_REG(sii->osh, sbr);
if (PCMCIA(sii)) {
tmp = 0;
OSL_PCMCIA_WRITE_ATTR(sii->osh, MEM_SEG, &tmp, 1);
INTR_RESTORE(sii, intr_val);
}
return (val);
}
static void
sb_write_sbreg(si_info_t *sii, volatile uint32 *sbr, uint32 v)
{
uint8 tmp;
volatile uint32 dummy;
uint32 intr_val = 0;
/*
* compact flash only has 11 bits address, while we needs 12 bits address.
* MEM_SEG will be OR'd with other 11 bits address in hardware,
* so we program MEM_SEG with 12th bit when necessary(access sb regsiters).
* For normal PCMCIA bus(CFTable_regwinsz > 2k), do nothing special
*/
if (PCMCIA(sii)) {
INTR_OFF(sii, intr_val);
tmp = 1;
OSL_PCMCIA_WRITE_ATTR(sii->osh, MEM_SEG, &tmp, 1);
sbr = (volatile uint32 *)((uintptr)sbr & ~(1 << 11)); /* mask out bit 11 */
}
if (BUSTYPE(sii->pub.bustype) == PCMCIA_BUS) {
dummy = R_REG(sii->osh, sbr);
W_REG(sii->osh, (volatile uint16 *)sbr, (uint16)(v & 0xffff));
dummy = R_REG(sii->osh, sbr);
W_REG(sii->osh, ((volatile uint16 *)sbr + 1), (uint16)((v >> 16) & 0xffff));
} else
W_REG(sii->osh, sbr, v);
if (PCMCIA(sii)) {
tmp = 0;
OSL_PCMCIA_WRITE_ATTR(sii->osh, MEM_SEG, &tmp, 1);
INTR_RESTORE(sii, intr_val);
}
}
uint
sb_coreid(si_t *sih)
{
si_info_t *sii;
sbconfig_t *sb;
sii = SI_INFO(sih);
sb = REGS2SB(sii->curmap);
return ((R_SBREG(sii, &sb->sbidhigh) & SBIDH_CC_MASK) >> SBIDH_CC_SHIFT);
}
uint
sb_intflag(si_t *sih)
{
si_info_t *sii;
void *corereg;
sbconfig_t *sb;
uint origidx, intflag, intr_val = 0;
sii = SI_INFO(sih);
INTR_OFF(sii, intr_val);
origidx = si_coreidx(sih);
corereg = si_setcore(sih, CC_CORE_ID, 0);
ASSERT(corereg != NULL);
sb = REGS2SB(corereg);
intflag = R_SBREG(sii, &sb->sbflagst);
sb_setcoreidx(sih, origidx);
INTR_RESTORE(sii, intr_val);
return intflag;
}
uint
sb_flag(si_t *sih)
{
si_info_t *sii;
sbconfig_t *sb;
sii = SI_INFO(sih);
sb = REGS2SB(sii->curmap);
return R_SBREG(sii, &sb->sbtpsflag) & SBTPS_NUM0_MASK;
}
void
sb_setint(si_t *sih, int siflag)
{
si_info_t *sii;
sbconfig_t *sb;
uint32 vec;
sii = SI_INFO(sih);
sb = REGS2SB(sii->curmap);
if (siflag == -1)
vec = 0;
else
vec = 1 << siflag;
W_SBREG(sii, &sb->sbintvec, vec);
}
/* return core index of the core with address 'sba' */
static uint
_sb_coreidx(si_info_t *sii, uint32 sba)
{
uint i;
for (i = 0; i < sii->numcores; i ++)
if (sba == sii->coresba[i])
return i;
return BADIDX;
}
/* return core address of the current core */
static uint32
_sb_coresba(si_info_t *sii)
{
uint32 sbaddr;
switch (BUSTYPE(sii->pub.bustype)) {
case SI_BUS: {
sbconfig_t *sb = REGS2SB(sii->curmap);
sbaddr = sb_base(R_SBREG(sii, &sb->sbadmatch0));
break;
}
case PCI_BUS:
sbaddr = OSL_PCI_READ_CONFIG(sii->osh, PCI_BAR0_WIN, sizeof(uint32));
break;
case PCMCIA_BUS: {
uint8 tmp = 0;
OSL_PCMCIA_READ_ATTR(sii->osh, PCMCIA_ADDR0, &tmp, 1);
sbaddr = (uint32)tmp << 12;
OSL_PCMCIA_READ_ATTR(sii->osh, PCMCIA_ADDR1, &tmp, 1);
sbaddr |= (uint32)tmp << 16;
OSL_PCMCIA_READ_ATTR(sii->osh, PCMCIA_ADDR2, &tmp, 1);
sbaddr |= (uint32)tmp << 24;
break;
}
case SPI_BUS:
case SDIO_BUS:
sbaddr = (uint32)(uintptr)sii->curmap;
break;
default:
sbaddr = BADCOREADDR;
break;
}
return sbaddr;
}
uint
sb_corevendor(si_t *sih)
{
si_info_t *sii;
sbconfig_t *sb;
sii = SI_INFO(sih);
sb = REGS2SB(sii->curmap);
return ((R_SBREG(sii, &sb->sbidhigh) & SBIDH_VC_MASK) >> SBIDH_VC_SHIFT);
}
uint
sb_corerev(si_t *sih)
{
si_info_t *sii;
sbconfig_t *sb;
uint sbidh;
sii = SI_INFO(sih);
sb = REGS2SB(sii->curmap);
sbidh = R_SBREG(sii, &sb->sbidhigh);
return (SBCOREREV(sbidh));
}
/* set core-specific control flags */
void
sb_core_cflags_wo(si_t *sih, uint32 mask, uint32 val)
{
si_info_t *sii;
sbconfig_t *sb;
uint32 w;
sii = SI_INFO(sih);
sb = REGS2SB(sii->curmap);
ASSERT((val & ~mask) == 0);
/* mask and set */
w = (R_SBREG(sii, &sb->sbtmstatelow) & ~(mask << SBTML_SICF_SHIFT)) |
(val << SBTML_SICF_SHIFT);
W_SBREG(sii, &sb->sbtmstatelow, w);
}
/* set/clear core-specific control flags */
uint32
sb_core_cflags(si_t *sih, uint32 mask, uint32 val)
{
si_info_t *sii;
sbconfig_t *sb;
uint32 w;
sii = SI_INFO(sih);
sb = REGS2SB(sii->curmap);
ASSERT((val & ~mask) == 0);
/* mask and set */
if (mask || val) {
w = (R_SBREG(sii, &sb->sbtmstatelow) & ~(mask << SBTML_SICF_SHIFT)) |
(val << SBTML_SICF_SHIFT);
W_SBREG(sii, &sb->sbtmstatelow, w);
}
/* return the new value
* for write operation, the following readback ensures the completion of write opration.
*/
return (R_SBREG(sii, &sb->sbtmstatelow) >> SBTML_SICF_SHIFT);
}
/* set/clear core-specific status flags */
uint32
sb_core_sflags(si_t *sih, uint32 mask, uint32 val)
{
si_info_t *sii;
sbconfig_t *sb;
uint32 w;
sii = SI_INFO(sih);
sb = REGS2SB(sii->curmap);
ASSERT((val & ~mask) == 0);
ASSERT((mask & ~SISF_CORE_BITS) == 0);
/* mask and set */
if (mask || val) {
w = (R_SBREG(sii, &sb->sbtmstatehigh) & ~(mask << SBTMH_SISF_SHIFT)) |
(val << SBTMH_SISF_SHIFT);
W_SBREG(sii, &sb->sbtmstatehigh, w);
}
/* return the new value */
return (R_SBREG(sii, &sb->sbtmstatehigh) >> SBTMH_SISF_SHIFT);
}
bool
sb_iscoreup(si_t *sih)
{
si_info_t *sii;
sbconfig_t *sb;
sii = SI_INFO(sih);
sb = REGS2SB(sii->curmap);
return ((R_SBREG(sii, &sb->sbtmstatelow) &
(SBTML_RESET | SBTML_REJ_MASK | (SICF_CLOCK_EN << SBTML_SICF_SHIFT))) ==
(SICF_CLOCK_EN << SBTML_SICF_SHIFT));
}
/*
* Switch to 'coreidx', issue a single arbitrary 32bit register mask&set operation,
* switch back to the original core, and return the new value.
*
* When using the silicon backplane, no fidleing with interrupts or core switches are needed.
*
* Also, when using pci/pcie, we can optimize away the core switching for pci registers
* and (on newer pci cores) chipcommon registers.
*/
uint
sb_corereg(si_t *sih, uint coreidx, uint regoff, uint mask, uint val)
{
uint origidx = 0;
uint32 *r = NULL;
uint w;
uint intr_val = 0;
bool fast = FALSE;
si_info_t *sii;
sii = SI_INFO(sih);
ASSERT(GOODIDX(coreidx));
ASSERT(regoff < SI_CORE_SIZE);
ASSERT((val & ~mask) == 0);
if (coreidx >= SI_MAXCORES)
return 0;
if (BUSTYPE(sii->pub.bustype) == SI_BUS) {
/* If internal bus, we can always get at everything */
fast = TRUE;
/* map if does not exist */
if (!sii->regs[coreidx]) {
sii->regs[coreidx] = REG_MAP(sii->coresba[coreidx],
SI_CORE_SIZE);
ASSERT(GOODREGS(sii->regs[coreidx]));
}
r = (uint32 *)((uchar *)sii->regs[coreidx] + regoff);
} else if (BUSTYPE(sii->pub.bustype) == PCI_BUS) {
/* If pci/pcie, we can get at pci/pcie regs and on newer cores to chipc */
if ((sii->coreid[coreidx] == CC_CORE_ID) && SI_FAST(sii)) {
/* Chipc registers are mapped at 12KB */
fast = TRUE;
r = (uint32 *)((char *)sii->curmap + PCI_16KB0_CCREGS_OFFSET + regoff);
} else if (sii->pub.buscoreidx == coreidx) {
/* pci registers are at either in the last 2KB of an 8KB window
* or, in pcie and pci rev 13 at 8KB
*/
fast = TRUE;
if (SI_FAST(sii))
r = (uint32 *)((char *)sii->curmap +
PCI_16KB0_PCIREGS_OFFSET + regoff);
else
r = (uint32 *)((char *)sii->curmap +
((regoff >= SBCONFIGOFF) ?
PCI_BAR0_PCISBR_OFFSET : PCI_BAR0_PCIREGS_OFFSET) +
regoff);
}
}
if (!fast) {
INTR_OFF(sii, intr_val);
/* save current core index */
origidx = si_coreidx(&sii->pub);
/* switch core */
r = (uint32*) ((uchar*)sb_setcoreidx(&sii->pub, coreidx) + regoff);
}
ASSERT(r != NULL);
#ifdef HTC_KlocWork
if(r == NULL) {
SI_ERROR(("[HTCKW] sb_corereg: r is NULL\n"));
return 0;
}
#endif
/* mask and set */
if (mask || val) {
if (regoff >= SBCONFIGOFF) {
w = (R_SBREG(sii, r) & ~mask) | val;
W_SBREG(sii, r, w);
} else {
w = (R_REG(sii->osh, r) & ~mask) | val;
W_REG(sii->osh, r, w);
}
}
/* readback */
if (regoff >= SBCONFIGOFF)
w = R_SBREG(sii, r);
else {
if ((CHIPID(sii->pub.chip) == BCM5354_CHIP_ID) &&
(coreidx == SI_CC_IDX) &&
(regoff == OFFSETOF(chipcregs_t, watchdog))) {
w = val;
} else
w = R_REG(sii->osh, r);
}
if (!fast) {
/* restore core index */
if (origidx != coreidx)
sb_setcoreidx(&sii->pub, origidx);
INTR_RESTORE(sii, intr_val);
}
return (w);
}
/* Scan the enumeration space to find all cores starting from the given
* bus 'sbba'. Append coreid and other info to the lists in 'si'. 'sba'
* is the default core address at chip POR time and 'regs' is the virtual
* address that the default core is mapped at. 'ncores' is the number of
* cores expected on bus 'sbba'. It returns the total number of cores
* starting from bus 'sbba', inclusive.
*/
#define SB_MAXBUSES 2
static uint
_sb_scan(si_info_t *sii, uint32 sba, void *regs, uint bus, uint32 sbba, uint numcores)
{
uint next;
uint ncc = 0;
uint i;
if (bus >= SB_MAXBUSES) {
SI_ERROR(("_sb_scan: bus 0x%08x at level %d is too deep to scan\n", sbba, bus));
return 0;
}
SI_MSG(("_sb_scan: scan bus 0x%08x assume %u cores\n", sbba, numcores));
/* Scan all cores on the bus starting from core 0.
* Core addresses must be contiguous on each bus.
*/
for (i = 0, next = sii->numcores; i < numcores && next < SB_BUS_MAXCORES; i++, next++) {
sii->coresba[next] = sbba + (i * SI_CORE_SIZE);
/* keep and reuse the initial register mapping */
if ((BUSTYPE(sii->pub.bustype) == SI_BUS) && (sii->coresba[next] == sba)) {
SI_VMSG(("_sb_scan: reuse mapped regs %p for core %u\n", regs, next));
sii->regs[next] = regs;
}
/* change core to 'next' and read its coreid */
sii->curmap = _sb_setcoreidx(sii, next);
sii->curidx = next;
sii->coreid[next] = sb_coreid(&sii->pub);
/* core specific processing... */
/* chipc provides # cores */
if (sii->coreid[next] == CC_CORE_ID) {
chipcregs_t *cc = (chipcregs_t *)sii->curmap;
uint32 ccrev = sb_corerev(&sii->pub);
/* determine numcores - this is the total # cores in the chip */
if (((ccrev == 4) || (ccrev >= 6))){
#ifdef HTC_KlocWork
if(cc != NULL)
#endif
numcores = (R_REG(sii->osh, &cc->chipid) & CID_CC_MASK) >>
CID_CC_SHIFT;
}
else {
/* Older chips */
uint chip = CHIPID(sii->pub.chip);
if (chip == BCM4306_CHIP_ID) /* < 4306c0 */
numcores = 6;
else if (chip == BCM4704_CHIP_ID)
numcores = 9;
else if (chip == BCM5365_CHIP_ID)
numcores = 7;
else {
SI_ERROR(("sb_chip2numcores: unsupported chip 0x%x\n",
chip));
ASSERT(0);
numcores = 1;
}
}
SI_VMSG(("_sb_scan: there are %u cores in the chip %s\n", numcores,
sii->pub.issim ? "QT" : ""));
}
/* scan bridged SB(s) and add results to the end of the list */
else if (sii->coreid[next] == OCP_CORE_ID) {
sbconfig_t *sb = REGS2SB(sii->curmap);
uint32 nsbba = R_SBREG(sii, &sb->sbadmatch1);
uint nsbcc;
sii->numcores = next + 1;
if ((nsbba & 0xfff00000) != SI_ENUM_BASE)
continue;
nsbba &= 0xfffff000;
if (_sb_coreidx(sii, nsbba) != BADIDX)
continue;
nsbcc = (R_SBREG(sii, &sb->sbtmstatehigh) & 0x000f0000) >> 16;
nsbcc = _sb_scan(sii, sba, regs, bus + 1, nsbba, nsbcc);
if (sbba == SI_ENUM_BASE)
numcores -= nsbcc;
ncc += nsbcc;
}
}
SI_MSG(("_sb_scan: found %u cores on bus 0x%08x\n", i, sbba));
sii->numcores = i + ncc;
return sii->numcores;
}
/* scan the sb enumerated space to identify all cores */
void
sb_scan(si_t *sih, void *regs, uint devid)
{
si_info_t *sii;
uint32 origsba;
sbconfig_t *sb;
sii = SI_INFO(sih);
sb = REGS2SB(sii->curmap);
sii->pub.socirev = (R_SBREG(sii, &sb->sbidlow) & SBIDL_RV_MASK) >> SBIDL_RV_SHIFT;
/* Save the current core info and validate it later till we know
* for sure what is good and what is bad.
*/
origsba = _sb_coresba(sii);
/* scan all SB(s) starting from SI_ENUM_BASE */
sii->numcores = _sb_scan(sii, origsba, regs, 0, SI_ENUM_BASE, 1);
}
/*
* This function changes logical "focus" to the indicated core;
* must be called with interrupts off.
* Moreover, callers should keep interrupts off during switching out of and back to d11 core
*/
void *
sb_setcoreidx(si_t *sih, uint coreidx)
{
si_info_t *sii;
sii = SI_INFO(sih);
if (coreidx >= sii->numcores)
return (NULL);
/*
* If the user has provided an interrupt mask enabled function,
* then assert interrupts are disabled before switching the core.
*/
ASSERT((sii->intrsenabled_fn == NULL) || !(*(sii)->intrsenabled_fn)((sii)->intr_arg));
sii->curmap = _sb_setcoreidx(sii, coreidx);
sii->curidx = coreidx;
return (sii->curmap);
}
/* This function changes the logical "focus" to the indicated core.
* Return the current core's virtual address.
*/
static void *
_sb_setcoreidx(si_info_t *sii, uint coreidx)
{
uint32 sbaddr = sii->coresba[coreidx];
void *regs;
switch (BUSTYPE(sii->pub.bustype)) {
case SI_BUS:
/* map new one */
if (!sii->regs[coreidx]) {
sii->regs[coreidx] = REG_MAP(sbaddr, SI_CORE_SIZE);
ASSERT(GOODREGS(sii->regs[coreidx]));
}
regs = sii->regs[coreidx];
break;
case PCI_BUS:
/* point bar0 window */
OSL_PCI_WRITE_CONFIG(sii->osh, PCI_BAR0_WIN, 4, sbaddr);
regs = sii->curmap;
break;
case PCMCIA_BUS: {
uint8 tmp = (sbaddr >> 12) & 0x0f;
OSL_PCMCIA_WRITE_ATTR(sii->osh, PCMCIA_ADDR0, &tmp, 1);
tmp = (sbaddr >> 16) & 0xff;
OSL_PCMCIA_WRITE_ATTR(sii->osh, PCMCIA_ADDR1, &tmp, 1);
tmp = (sbaddr >> 24) & 0xff;
OSL_PCMCIA_WRITE_ATTR(sii->osh, PCMCIA_ADDR2, &tmp, 1);
regs = sii->curmap;
break;
}
case SPI_BUS:
case SDIO_BUS:
/* map new one */
if (!sii->regs[coreidx]) {
sii->regs[coreidx] = (void *)(uintptr)sbaddr;
ASSERT(GOODREGS(sii->regs[coreidx]));
}
regs = sii->regs[coreidx];
break;
default:
ASSERT(0);
regs = NULL;
break;
}
return regs;
}
/* Return the address of sbadmatch0/1/2/3 register */
static volatile uint32 *
sb_admatch(si_info_t *sii, uint asidx)
{
sbconfig_t *sb;
volatile uint32 *addrm;
sb = REGS2SB(sii->curmap);
switch (asidx) {
case 0:
addrm = &sb->sbadmatch0;
break;
case 1:
addrm = &sb->sbadmatch1;
break;
case 2:
addrm = &sb->sbadmatch2;
break;
case 3:
addrm = &sb->sbadmatch3;
break;
default:
SI_ERROR(("%s: Address space index (%d) out of range\n", __FUNCTION__, asidx));
return 0;
}
return (addrm);
}
/* Return the number of address spaces in current core */
int
sb_numaddrspaces(si_t *sih)
{
si_info_t *sii;
sbconfig_t *sb;
sii = SI_INFO(sih);
sb = REGS2SB(sii->curmap);
/* + 1 because of enumeration space */
return ((R_SBREG(sii, &sb->sbidlow) & SBIDL_AR_MASK) >> SBIDL_AR_SHIFT) + 1;
}
/* Return the address of the nth address space in the current core */
uint32
sb_addrspace(si_t *sih, uint asidx)
{
si_info_t *sii;
sii = SI_INFO(sih);
return (sb_base(R_SBREG(sii, sb_admatch(sii, asidx))));
}
/* Return the size of the nth address space in the current core */
uint32
sb_addrspacesize(si_t *sih, uint asidx)
{
si_info_t *sii;
sii = SI_INFO(sih);
return (sb_size(R_SBREG(sii, sb_admatch(sii, asidx))));
}
/* do buffered registers update */
void
sb_commit(si_t *sih)
{
si_info_t *sii;
uint origidx;
uint intr_val = 0;
sii = SI_INFO(sih);
origidx = sii->curidx;
ASSERT(GOODIDX(origidx));
INTR_OFF(sii, intr_val);
/* switch over to chipcommon core if there is one, else use pci */
if (sii->pub.ccrev != NOREV) {
chipcregs_t *ccregs = (chipcregs_t *)si_setcore(sih, CC_CORE_ID, 0);
ASSERT(ccregs != NULL);
#ifdef HTC_KlocWork
if(ccregs != NULL) {
/* do the buffer registers update */
W_REG(sii->osh, &ccregs->broadcastaddress, SB_COMMIT);
W_REG(sii->osh, &ccregs->broadcastdata, 0x0);
}
#else
/* do the buffer registers update */
W_REG(sii->osh, &ccregs->broadcastaddress, SB_COMMIT);
W_REG(sii->osh, &ccregs->broadcastdata, 0x0);
#endif
} else
ASSERT(0);
/* restore core index */
sb_setcoreidx(sih, origidx);
INTR_RESTORE(sii, intr_val);
}
void
sb_core_disable(si_t *sih, uint32 bits)
{
si_info_t *sii;
volatile uint32 dummy;
sbconfig_t *sb;
sii = SI_INFO(sih);
ASSERT(GOODREGS(sii->curmap));
sb = REGS2SB(sii->curmap);
/* if core is already in reset, just return */
if (R_SBREG(sii, &sb->sbtmstatelow) & SBTML_RESET)
return;
/* if clocks are not enabled, put into reset and return */
if ((R_SBREG(sii, &sb->sbtmstatelow) & (SICF_CLOCK_EN << SBTML_SICF_SHIFT)) == 0)
goto disable;
/* set target reject and spin until busy is clear (preserve core-specific bits) */
OR_SBREG(sii, &sb->sbtmstatelow, SBTML_REJ);
dummy = R_SBREG(sii, &sb->sbtmstatelow);
OSL_DELAY(1);
SPINWAIT((R_SBREG(sii, &sb->sbtmstatehigh) & SBTMH_BUSY), 100000);
if (R_SBREG(sii, &sb->sbtmstatehigh) & SBTMH_BUSY)
SI_ERROR(("%s: target state still busy\n", __FUNCTION__));
if (R_SBREG(sii, &sb->sbidlow) & SBIDL_INIT) {
OR_SBREG(sii, &sb->sbimstate, SBIM_RJ);
dummy = R_SBREG(sii, &sb->sbimstate);
OSL_DELAY(1);
SPINWAIT((R_SBREG(sii, &sb->sbimstate) & SBIM_BY), 100000);
}
/* set reset and reject while enabling the clocks */
W_SBREG(sii, &sb->sbtmstatelow,
(((bits | SICF_FGC | SICF_CLOCK_EN) << SBTML_SICF_SHIFT) |
SBTML_REJ | SBTML_RESET));
dummy = R_SBREG(sii, &sb->sbtmstatelow);
OSL_DELAY(10);
/* don't forget to clear the initiator reject bit */
if (R_SBREG(sii, &sb->sbidlow) & SBIDL_INIT)
AND_SBREG(sii, &sb->sbimstate, ~SBIM_RJ);
disable:
/* leave reset and reject asserted */
W_SBREG(sii, &sb->sbtmstatelow, ((bits << SBTML_SICF_SHIFT) | SBTML_REJ | SBTML_RESET));
OSL_DELAY(1);
}
/* reset and re-enable a core
* inputs:
* bits - core specific bits that are set during and after reset sequence
* resetbits - core specific bits that are set only during reset sequence
*/
void
sb_core_reset(si_t *sih, uint32 bits, uint32 resetbits)
{
si_info_t *sii;
sbconfig_t *sb;
volatile uint32 dummy;
sii = SI_INFO(sih);
ASSERT(GOODREGS(sii->curmap));
sb = REGS2SB(sii->curmap);
/*
* Must do the disable sequence first to work for arbitrary current core state.
*/
sb_core_disable(sih, (bits | resetbits));
/*
* Now do the initialization sequence.
*/
/* set reset while enabling the clock and forcing them on throughout the core */
W_SBREG(sii, &sb->sbtmstatelow,
(((bits | resetbits | SICF_FGC | SICF_CLOCK_EN) << SBTML_SICF_SHIFT) |
SBTML_RESET));
dummy = R_SBREG(sii, &sb->sbtmstatelow);
OSL_DELAY(1);
if (R_SBREG(sii, &sb->sbtmstatehigh) & SBTMH_SERR) {
W_SBREG(sii, &sb->sbtmstatehigh, 0);
}
if ((dummy = R_SBREG(sii, &sb->sbimstate)) & (SBIM_IBE | SBIM_TO)) {
AND_SBREG(sii, &sb->sbimstate, ~(SBIM_IBE | SBIM_TO));
}
/* clear reset and allow it to propagate throughout the core */
W_SBREG(sii, &sb->sbtmstatelow,
((bits | resetbits | SICF_FGC | SICF_CLOCK_EN) << SBTML_SICF_SHIFT));
dummy = R_SBREG(sii, &sb->sbtmstatelow);
OSL_DELAY(1);
/* leave clock enabled */
W_SBREG(sii, &sb->sbtmstatelow, ((bits | SICF_CLOCK_EN) << SBTML_SICF_SHIFT));
dummy = R_SBREG(sii, &sb->sbtmstatelow);
OSL_DELAY(1);
}
/*
* Set the initiator timeout for the "master core".
* The master core is defined to be the core in control
* of the chip and so it issues accesses to non-memory
* locations (Because of dma *any* core can access memeory).
*
* The routine uses the bus to decide who is the master:
* SI_BUS => mips
* JTAG_BUS => chipc
* PCI_BUS => pci or pcie
* PCMCIA_BUS => pcmcia
* SDIO_BUS => pcmcia
*
* This routine exists so callers can disable initiator
* timeouts so accesses to very slow devices like otp
* won't cause an abort. The routine allows arbitrary
* settings of the service and request timeouts, though.
*
* Returns the timeout state before changing it or -1
* on error.
*/
#define TO_MASK (SBIMCL_RTO_MASK | SBIMCL_STO_MASK)
uint32
sb_set_initiator_to(si_t *sih, uint32 to, uint idx)
{
si_info_t *sii;
uint origidx;
uint intr_val = 0;
uint32 tmp, ret = 0xffffffff;
sbconfig_t *sb;
sii = SI_INFO(sih);
if ((to & ~TO_MASK) != 0)
return ret;
/* Figure out the master core */
if (idx == BADIDX) {
switch (BUSTYPE(sii->pub.bustype)) {
case PCI_BUS:
idx = sii->pub.buscoreidx;
break;
case JTAG_BUS:
idx = SI_CC_IDX;
break;
case PCMCIA_BUS:
case SDIO_BUS:
idx = si_findcoreidx(sih, PCMCIA_CORE_ID, 0);
break;
case SI_BUS:
idx = si_findcoreidx(sih, MIPS33_CORE_ID, 0);
break;
default:
ASSERT(0);
}
if (idx == BADIDX)
return ret;
}
INTR_OFF(sii, intr_val);
origidx = si_coreidx(sih);
sb = REGS2SB(sb_setcoreidx(sih, idx));
tmp = R_SBREG(sii, &sb->sbimconfiglow);
ret = tmp & TO_MASK;
W_SBREG(sii, &sb->sbimconfiglow, (tmp & ~TO_MASK) | to);
sb_commit(sih);
sb_setcoreidx(sih, origidx);
INTR_RESTORE(sii, intr_val);
return ret;
}
uint32
sb_base(uint32 admatch)
{
uint32 base;
uint type;
type = admatch & SBAM_TYPE_MASK;
ASSERT(type < 3);
base = 0;
if (type == 0) {
base = admatch & SBAM_BASE0_MASK;
} else if (type == 1) {
ASSERT(!(admatch & SBAM_ADNEG)); /* neg not supported */
base = admatch & SBAM_BASE1_MASK;
} else if (type == 2) {
ASSERT(!(admatch & SBAM_ADNEG)); /* neg not supported */
base = admatch & SBAM_BASE2_MASK;
}
return (base);
}
uint32
sb_size(uint32 admatch)
{
uint32 size;
uint type;
type = admatch & SBAM_TYPE_MASK;
ASSERT(type < 3);
size = 0;
if (type == 0) {
size = 1 << (((admatch & SBAM_ADINT0_MASK) >> SBAM_ADINT0_SHIFT) + 1);
} else if (type == 1) {
ASSERT(!(admatch & SBAM_ADNEG)); /* neg not supported */
size = 1 << (((admatch & SBAM_ADINT1_MASK) >> SBAM_ADINT1_SHIFT) + 1);
} else if (type == 2) {
ASSERT(!(admatch & SBAM_ADNEG)); /* neg not supported */
size = 1 << (((admatch & SBAM_ADINT2_MASK) >> SBAM_ADINT2_SHIFT) + 1);
}
return (size);
}
| gpl-2.0 |
Wenzel/kvm | drivers/gpio/gpio-lp3943.c | 421 | 5601 | /*
* TI/National Semiconductor LP3943 GPIO driver
*
* Copyright 2013 Texas Instruments
*
* Author: Milo Kim <milo.kim@ti.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2.
*/
#include <linux/bitops.h>
#include <linux/err.h>
#include <linux/gpio.h>
#include <linux/i2c.h>
#include <linux/mfd/lp3943.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
enum lp3943_gpios {
LP3943_GPIO1,
LP3943_GPIO2,
LP3943_GPIO3,
LP3943_GPIO4,
LP3943_GPIO5,
LP3943_GPIO6,
LP3943_GPIO7,
LP3943_GPIO8,
LP3943_GPIO9,
LP3943_GPIO10,
LP3943_GPIO11,
LP3943_GPIO12,
LP3943_GPIO13,
LP3943_GPIO14,
LP3943_GPIO15,
LP3943_GPIO16,
LP3943_MAX_GPIO,
};
struct lp3943_gpio {
struct gpio_chip chip;
struct lp3943 *lp3943;
u16 input_mask; /* 1 = GPIO is input direction, 0 = output */
};
static int lp3943_gpio_request(struct gpio_chip *chip, unsigned offset)
{
struct lp3943_gpio *lp3943_gpio = gpiochip_get_data(chip);
struct lp3943 *lp3943 = lp3943_gpio->lp3943;
/* Return an error if the pin is already assigned */
if (test_and_set_bit(offset, &lp3943->pin_used))
return -EBUSY;
return 0;
}
static void lp3943_gpio_free(struct gpio_chip *chip, unsigned offset)
{
struct lp3943_gpio *lp3943_gpio = gpiochip_get_data(chip);
struct lp3943 *lp3943 = lp3943_gpio->lp3943;
clear_bit(offset, &lp3943->pin_used);
}
static int lp3943_gpio_set_mode(struct lp3943_gpio *lp3943_gpio, u8 offset,
u8 val)
{
struct lp3943 *lp3943 = lp3943_gpio->lp3943;
const struct lp3943_reg_cfg *mux = lp3943->mux_cfg;
return lp3943_update_bits(lp3943, mux[offset].reg, mux[offset].mask,
val << mux[offset].shift);
}
static int lp3943_gpio_direction_input(struct gpio_chip *chip, unsigned offset)
{
struct lp3943_gpio *lp3943_gpio = gpiochip_get_data(chip);
lp3943_gpio->input_mask |= BIT(offset);
return lp3943_gpio_set_mode(lp3943_gpio, offset, LP3943_GPIO_IN);
}
static int lp3943_get_gpio_in_status(struct lp3943_gpio *lp3943_gpio,
struct gpio_chip *chip, unsigned offset)
{
u8 addr, read;
int err;
switch (offset) {
case LP3943_GPIO1 ... LP3943_GPIO8:
addr = LP3943_REG_GPIO_A;
break;
case LP3943_GPIO9 ... LP3943_GPIO16:
addr = LP3943_REG_GPIO_B;
offset = offset - 8;
break;
default:
return -EINVAL;
}
err = lp3943_read_byte(lp3943_gpio->lp3943, addr, &read);
if (err)
return err;
return !!(read & BIT(offset));
}
static int lp3943_get_gpio_out_status(struct lp3943_gpio *lp3943_gpio,
struct gpio_chip *chip, unsigned offset)
{
struct lp3943 *lp3943 = lp3943_gpio->lp3943;
const struct lp3943_reg_cfg *mux = lp3943->mux_cfg;
u8 read;
int err;
err = lp3943_read_byte(lp3943, mux[offset].reg, &read);
if (err)
return err;
read = (read & mux[offset].mask) >> mux[offset].shift;
if (read == LP3943_GPIO_OUT_HIGH)
return 1;
else if (read == LP3943_GPIO_OUT_LOW)
return 0;
else
return -EINVAL;
}
static int lp3943_gpio_get(struct gpio_chip *chip, unsigned offset)
{
struct lp3943_gpio *lp3943_gpio = gpiochip_get_data(chip);
/*
* Limitation:
* LP3943 doesn't have the GPIO direction register. It provides
* only input and output status registers.
* So, direction info is required to handle the 'get' operation.
* This variable is updated whenever the direction is changed and
* it is used here.
*/
if (lp3943_gpio->input_mask & BIT(offset))
return lp3943_get_gpio_in_status(lp3943_gpio, chip, offset);
else
return lp3943_get_gpio_out_status(lp3943_gpio, chip, offset);
}
static void lp3943_gpio_set(struct gpio_chip *chip, unsigned offset, int value)
{
struct lp3943_gpio *lp3943_gpio = gpiochip_get_data(chip);
u8 data;
if (value)
data = LP3943_GPIO_OUT_HIGH;
else
data = LP3943_GPIO_OUT_LOW;
lp3943_gpio_set_mode(lp3943_gpio, offset, data);
}
static int lp3943_gpio_direction_output(struct gpio_chip *chip, unsigned offset,
int value)
{
struct lp3943_gpio *lp3943_gpio = gpiochip_get_data(chip);
lp3943_gpio_set(chip, offset, value);
lp3943_gpio->input_mask &= ~BIT(offset);
return 0;
}
static const struct gpio_chip lp3943_gpio_chip = {
.label = "lp3943",
.owner = THIS_MODULE,
.request = lp3943_gpio_request,
.free = lp3943_gpio_free,
.direction_input = lp3943_gpio_direction_input,
.get = lp3943_gpio_get,
.direction_output = lp3943_gpio_direction_output,
.set = lp3943_gpio_set,
.base = -1,
.ngpio = LP3943_MAX_GPIO,
.can_sleep = 1,
};
static int lp3943_gpio_probe(struct platform_device *pdev)
{
struct lp3943 *lp3943 = dev_get_drvdata(pdev->dev.parent);
struct lp3943_gpio *lp3943_gpio;
lp3943_gpio = devm_kzalloc(&pdev->dev, sizeof(*lp3943_gpio),
GFP_KERNEL);
if (!lp3943_gpio)
return -ENOMEM;
lp3943_gpio->lp3943 = lp3943;
lp3943_gpio->chip = lp3943_gpio_chip;
lp3943_gpio->chip.parent = &pdev->dev;
platform_set_drvdata(pdev, lp3943_gpio);
return devm_gpiochip_add_data(&pdev->dev, &lp3943_gpio->chip,
lp3943_gpio);
}
static const struct of_device_id lp3943_gpio_of_match[] = {
{ .compatible = "ti,lp3943-gpio", },
{ }
};
MODULE_DEVICE_TABLE(of, lp3943_gpio_of_match);
static struct platform_driver lp3943_gpio_driver = {
.probe = lp3943_gpio_probe,
.driver = {
.name = "lp3943-gpio",
.of_match_table = lp3943_gpio_of_match,
},
};
module_platform_driver(lp3943_gpio_driver);
MODULE_DESCRIPTION("LP3943 GPIO driver");
MODULE_ALIAS("platform:lp3943-gpio");
MODULE_AUTHOR("Milo Kim");
MODULE_LICENSE("GPL");
| gpl-2.0 |
ShadowGame/Core-1 | Core/dep/g3dlite/source/BumpMapPreprocess.cpp | 677 | 1095 | /**
\file BumpMapPreprocess.cpp
\maintainer Morgan McGuire, http://graphics.cs.williams.edu
\created 2010-01-28
\edited 2010-01-28
Copyright 2000-2010, Morgan McGuire.
All rights reserved.
*/
#include "G3D/BumpMapPreprocess.h"
#include "G3D/Any.h"
#include "G3D/stringutils.h"
namespace G3D {
BumpMapPreprocess::BumpMapPreprocess(const Any& any) {
*this = BumpMapPreprocess();
for (Any::AnyTable::Iterator it = any.table().begin(); it.hasMore(); ++it) {
const std::string& key = toLower(it->key);
if (key == "lowpassfilter") {
lowPassFilter = it->value;
} else if (key == "zextentpixels") {
zExtentPixels = it->value;
} else if (key == "scalezbynz") {
scaleZByNz = it->value;
} else {
any.verify(false, "Illegal key: " + it->key);
}
}
}
BumpMapPreprocess::operator Any() const {
Any any(Any::TABLE, "BumpMapPreprocess");
any["lowPassFilter"] = lowPassFilter;
any["zExtentPixels"] = zExtentPixels;
any["scaleZByNz"] = scaleZByNz;
return any;
}
}
| gpl-2.0 |
trupeace/arm10c-tp | drivers/mtd/maps/physmap.c | 933 | 6936 | /*
* Normal mappings of chips in physical memory
*
* Copyright (C) 2003 MontaVista Software Inc.
* Author: Jun Sun, jsun@mvista.com or jsun@junsun.net
*
* 031022 - [jsun] add run-time configure and partition setup
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/map.h>
#include <linux/mtd/partitions.h>
#include <linux/mtd/physmap.h>
#include <linux/mtd/concat.h>
#include <linux/io.h>
#define MAX_RESOURCES 4
struct physmap_flash_info {
struct mtd_info *mtd[MAX_RESOURCES];
struct mtd_info *cmtd;
struct map_info map[MAX_RESOURCES];
spinlock_t vpp_lock;
int vpp_refcnt;
};
static int physmap_flash_remove(struct platform_device *dev)
{
struct physmap_flash_info *info;
struct physmap_flash_data *physmap_data;
int i;
info = platform_get_drvdata(dev);
if (info == NULL)
return 0;
physmap_data = dev_get_platdata(&dev->dev);
if (info->cmtd) {
mtd_device_unregister(info->cmtd);
if (info->cmtd != info->mtd[0])
mtd_concat_destroy(info->cmtd);
}
for (i = 0; i < MAX_RESOURCES; i++) {
if (info->mtd[i] != NULL)
map_destroy(info->mtd[i]);
}
if (physmap_data->exit)
physmap_data->exit(dev);
return 0;
}
static void physmap_set_vpp(struct map_info *map, int state)
{
struct platform_device *pdev;
struct physmap_flash_data *physmap_data;
struct physmap_flash_info *info;
unsigned long flags;
pdev = (struct platform_device *)map->map_priv_1;
physmap_data = dev_get_platdata(&pdev->dev);
if (!physmap_data->set_vpp)
return;
info = platform_get_drvdata(pdev);
spin_lock_irqsave(&info->vpp_lock, flags);
if (state) {
if (++info->vpp_refcnt == 1) /* first nested 'on' */
physmap_data->set_vpp(pdev, 1);
} else {
if (--info->vpp_refcnt == 0) /* last nested 'off' */
physmap_data->set_vpp(pdev, 0);
}
spin_unlock_irqrestore(&info->vpp_lock, flags);
}
static const char * const rom_probe_types[] = {
"cfi_probe", "jedec_probe", "qinfo_probe", "map_rom", NULL };
static const char * const part_probe_types[] = {
"cmdlinepart", "RedBoot", "afs", NULL };
static int physmap_flash_probe(struct platform_device *dev)
{
struct physmap_flash_data *physmap_data;
struct physmap_flash_info *info;
const char * const *probe_type;
const char * const *part_types;
int err = 0;
int i;
int devices_found = 0;
physmap_data = dev_get_platdata(&dev->dev);
if (physmap_data == NULL)
return -ENODEV;
info = devm_kzalloc(&dev->dev, sizeof(struct physmap_flash_info),
GFP_KERNEL);
if (info == NULL) {
err = -ENOMEM;
goto err_out;
}
if (physmap_data->init) {
err = physmap_data->init(dev);
if (err)
goto err_out;
}
platform_set_drvdata(dev, info);
for (i = 0; i < dev->num_resources; i++) {
printk(KERN_NOTICE "physmap platform flash device: %.8llx at %.8llx\n",
(unsigned long long)resource_size(&dev->resource[i]),
(unsigned long long)dev->resource[i].start);
if (!devm_request_mem_region(&dev->dev,
dev->resource[i].start,
resource_size(&dev->resource[i]),
dev_name(&dev->dev))) {
dev_err(&dev->dev, "Could not reserve memory region\n");
err = -ENOMEM;
goto err_out;
}
info->map[i].name = dev_name(&dev->dev);
info->map[i].phys = dev->resource[i].start;
info->map[i].size = resource_size(&dev->resource[i]);
info->map[i].bankwidth = physmap_data->width;
info->map[i].set_vpp = physmap_set_vpp;
info->map[i].pfow_base = physmap_data->pfow_base;
info->map[i].map_priv_1 = (unsigned long)dev;
info->map[i].virt = devm_ioremap(&dev->dev, info->map[i].phys,
info->map[i].size);
if (info->map[i].virt == NULL) {
dev_err(&dev->dev, "Failed to ioremap flash region\n");
err = -EIO;
goto err_out;
}
simple_map_init(&info->map[i]);
probe_type = rom_probe_types;
if (physmap_data->probe_type == NULL) {
for (; info->mtd[i] == NULL && *probe_type != NULL; probe_type++)
info->mtd[i] = do_map_probe(*probe_type, &info->map[i]);
} else
info->mtd[i] = do_map_probe(physmap_data->probe_type, &info->map[i]);
if (info->mtd[i] == NULL) {
dev_err(&dev->dev, "map_probe failed\n");
err = -ENXIO;
goto err_out;
} else {
devices_found++;
}
info->mtd[i]->owner = THIS_MODULE;
info->mtd[i]->dev.parent = &dev->dev;
}
if (devices_found == 1) {
info->cmtd = info->mtd[0];
} else if (devices_found > 1) {
/*
* We detected multiple devices. Concatenate them together.
*/
info->cmtd = mtd_concat_create(info->mtd, devices_found, dev_name(&dev->dev));
if (info->cmtd == NULL)
err = -ENXIO;
}
if (err)
goto err_out;
spin_lock_init(&info->vpp_lock);
part_types = physmap_data->part_probe_types ? : part_probe_types;
mtd_device_parse_register(info->cmtd, part_types, NULL,
physmap_data->parts, physmap_data->nr_parts);
return 0;
err_out:
physmap_flash_remove(dev);
return err;
}
#ifdef CONFIG_PM
static void physmap_flash_shutdown(struct platform_device *dev)
{
struct physmap_flash_info *info = platform_get_drvdata(dev);
int i;
for (i = 0; i < MAX_RESOURCES && info->mtd[i]; i++)
if (mtd_suspend(info->mtd[i]) == 0)
mtd_resume(info->mtd[i]);
}
#else
#define physmap_flash_shutdown NULL
#endif
static struct platform_driver physmap_flash_driver = {
.probe = physmap_flash_probe,
.remove = physmap_flash_remove,
.shutdown = physmap_flash_shutdown,
.driver = {
.name = "physmap-flash",
.owner = THIS_MODULE,
},
};
#ifdef CONFIG_MTD_PHYSMAP_COMPAT
static struct physmap_flash_data physmap_flash_data = {
.width = CONFIG_MTD_PHYSMAP_BANKWIDTH,
};
static struct resource physmap_flash_resource = {
.start = CONFIG_MTD_PHYSMAP_START,
.end = CONFIG_MTD_PHYSMAP_START + CONFIG_MTD_PHYSMAP_LEN - 1,
.flags = IORESOURCE_MEM,
};
static struct platform_device physmap_flash = {
.name = "physmap-flash",
.id = 0,
.dev = {
.platform_data = &physmap_flash_data,
},
.num_resources = 1,
.resource = &physmap_flash_resource,
};
#endif
static int __init physmap_init(void)
{
int err;
err = platform_driver_register(&physmap_flash_driver);
#ifdef CONFIG_MTD_PHYSMAP_COMPAT
if (err == 0) {
err = platform_device_register(&physmap_flash);
if (err)
platform_driver_unregister(&physmap_flash_driver);
}
#endif
return err;
}
static void __exit physmap_exit(void)
{
#ifdef CONFIG_MTD_PHYSMAP_COMPAT
platform_device_unregister(&physmap_flash);
#endif
platform_driver_unregister(&physmap_flash_driver);
}
module_init(physmap_init);
module_exit(physmap_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("David Woodhouse <dwmw2@infradead.org>");
MODULE_DESCRIPTION("Generic configurable MTD map driver");
/* legacy platform drivers can't hotplug or coldplg */
#ifndef CONFIG_MTD_PHYSMAP_COMPAT
/* work with hotplug and coldplug */
MODULE_ALIAS("platform:physmap-flash");
#endif
| gpl-2.0 |
sktjdgns1189/android_kernel_samsung_SHW-M190S-4.2.2 | drivers/power/bq27x00_battery.c | 933 | 10586 | /*
* BQ27x00 battery driver
*
* Copyright (C) 2008 Rodolfo Giometti <giometti@linux.it>
* Copyright (C) 2008 Eurotech S.p.A. <info@eurotech.it>
*
* Based on a previous work by Copyright (C) 2008 Texas Instruments, Inc.
*
* This package is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
*/
#include <linux/module.h>
#include <linux/param.h>
#include <linux/jiffies.h>
#include <linux/workqueue.h>
#include <linux/delay.h>
#include <linux/platform_device.h>
#include <linux/power_supply.h>
#include <linux/idr.h>
#include <linux/i2c.h>
#include <linux/slab.h>
#include <asm/unaligned.h>
#define DRIVER_VERSION "1.1.0"
#define BQ27x00_REG_TEMP 0x06
#define BQ27x00_REG_VOLT 0x08
#define BQ27x00_REG_AI 0x14
#define BQ27x00_REG_FLAGS 0x0A
#define BQ27x00_REG_TTE 0x16
#define BQ27x00_REG_TTF 0x18
#define BQ27x00_REG_TTECP 0x26
#define BQ27000_REG_RSOC 0x0B /* Relative State-of-Charge */
#define BQ27000_FLAG_CHGS BIT(7)
#define BQ27500_REG_SOC 0x2c
#define BQ27500_FLAG_DSC BIT(0)
#define BQ27500_FLAG_FC BIT(9)
/* If the system has several batteries we need a different name for each
* of them...
*/
static DEFINE_IDR(battery_id);
static DEFINE_MUTEX(battery_mutex);
struct bq27x00_device_info;
struct bq27x00_access_methods {
int (*read)(u8 reg, int *rt_value, int b_single,
struct bq27x00_device_info *di);
};
enum bq27x00_chip { BQ27000, BQ27500 };
struct bq27x00_device_info {
struct device *dev;
int id;
struct bq27x00_access_methods *bus;
struct power_supply bat;
enum bq27x00_chip chip;
struct i2c_client *client;
};
static enum power_supply_property bq27x00_battery_props[] = {
POWER_SUPPLY_PROP_STATUS,
POWER_SUPPLY_PROP_PRESENT,
POWER_SUPPLY_PROP_VOLTAGE_NOW,
POWER_SUPPLY_PROP_CURRENT_NOW,
POWER_SUPPLY_PROP_CAPACITY,
POWER_SUPPLY_PROP_TEMP,
POWER_SUPPLY_PROP_TIME_TO_EMPTY_NOW,
POWER_SUPPLY_PROP_TIME_TO_EMPTY_AVG,
POWER_SUPPLY_PROP_TIME_TO_FULL_NOW,
};
/*
* Common code for BQ27x00 devices
*/
static int bq27x00_read(u8 reg, int *rt_value, int b_single,
struct bq27x00_device_info *di)
{
return di->bus->read(reg, rt_value, b_single, di);
}
/*
* Return the battery temperature in tenths of degree Celsius
* Or < 0 if something fails.
*/
static int bq27x00_battery_temperature(struct bq27x00_device_info *di)
{
int ret;
int temp = 0;
ret = bq27x00_read(BQ27x00_REG_TEMP, &temp, 0, di);
if (ret) {
dev_err(di->dev, "error reading temperature\n");
return ret;
}
if (di->chip == BQ27500)
return temp - 2731;
else
return ((temp >> 2) - 273) * 10;
}
/*
* Return the battery Voltage in milivolts
* Or < 0 if something fails.
*/
static int bq27x00_battery_voltage(struct bq27x00_device_info *di)
{
int ret;
int volt = 0;
ret = bq27x00_read(BQ27x00_REG_VOLT, &volt, 0, di);
if (ret) {
dev_err(di->dev, "error reading voltage\n");
return ret;
}
return volt * 1000;
}
/*
* Return the battery average current
* Note that current can be negative signed as well
* Or 0 if something fails.
*/
static int bq27x00_battery_current(struct bq27x00_device_info *di)
{
int ret;
int curr = 0;
int flags = 0;
ret = bq27x00_read(BQ27x00_REG_AI, &curr, 0, di);
if (ret) {
dev_err(di->dev, "error reading current\n");
return 0;
}
if (di->chip == BQ27500) {
/* bq27500 returns signed value */
curr = (int)(s16)curr;
} else {
ret = bq27x00_read(BQ27x00_REG_FLAGS, &flags, 0, di);
if (ret < 0) {
dev_err(di->dev, "error reading flags\n");
return 0;
}
if (flags & BQ27000_FLAG_CHGS) {
dev_dbg(di->dev, "negative current!\n");
curr = -curr;
}
}
return curr * 1000;
}
/*
* Return the battery Relative State-of-Charge
* Or < 0 if something fails.
*/
static int bq27x00_battery_rsoc(struct bq27x00_device_info *di)
{
int ret;
int rsoc = 0;
if (di->chip == BQ27500)
ret = bq27x00_read(BQ27500_REG_SOC, &rsoc, 0, di);
else
ret = bq27x00_read(BQ27000_REG_RSOC, &rsoc, 1, di);
if (ret) {
dev_err(di->dev, "error reading relative State-of-Charge\n");
return ret;
}
return rsoc;
}
static int bq27x00_battery_status(struct bq27x00_device_info *di,
union power_supply_propval *val)
{
int flags = 0;
int status;
int ret;
ret = bq27x00_read(BQ27x00_REG_FLAGS, &flags, 0, di);
if (ret < 0) {
dev_err(di->dev, "error reading flags\n");
return ret;
}
if (di->chip == BQ27500) {
if (flags & BQ27500_FLAG_FC)
status = POWER_SUPPLY_STATUS_FULL;
else if (flags & BQ27500_FLAG_DSC)
status = POWER_SUPPLY_STATUS_DISCHARGING;
else
status = POWER_SUPPLY_STATUS_CHARGING;
} else {
if (flags & BQ27000_FLAG_CHGS)
status = POWER_SUPPLY_STATUS_CHARGING;
else
status = POWER_SUPPLY_STATUS_DISCHARGING;
}
val->intval = status;
return 0;
}
/*
* Read a time register.
* Return < 0 if something fails.
*/
static int bq27x00_battery_time(struct bq27x00_device_info *di, int reg,
union power_supply_propval *val)
{
int tval = 0;
int ret;
ret = bq27x00_read(reg, &tval, 0, di);
if (ret) {
dev_err(di->dev, "error reading register %02x\n", reg);
return ret;
}
if (tval == 65535)
return -ENODATA;
val->intval = tval * 60;
return 0;
}
#define to_bq27x00_device_info(x) container_of((x), \
struct bq27x00_device_info, bat);
static int bq27x00_battery_get_property(struct power_supply *psy,
enum power_supply_property psp,
union power_supply_propval *val)
{
int ret = 0;
struct bq27x00_device_info *di = to_bq27x00_device_info(psy);
switch (psp) {
case POWER_SUPPLY_PROP_STATUS:
ret = bq27x00_battery_status(di, val);
break;
case POWER_SUPPLY_PROP_VOLTAGE_NOW:
case POWER_SUPPLY_PROP_PRESENT:
val->intval = bq27x00_battery_voltage(di);
if (psp == POWER_SUPPLY_PROP_PRESENT)
val->intval = val->intval <= 0 ? 0 : 1;
break;
case POWER_SUPPLY_PROP_CURRENT_NOW:
val->intval = bq27x00_battery_current(di);
break;
case POWER_SUPPLY_PROP_CAPACITY:
val->intval = bq27x00_battery_rsoc(di);
break;
case POWER_SUPPLY_PROP_TEMP:
val->intval = bq27x00_battery_temperature(di);
break;
case POWER_SUPPLY_PROP_TIME_TO_EMPTY_NOW:
ret = bq27x00_battery_time(di, BQ27x00_REG_TTE, val);
break;
case POWER_SUPPLY_PROP_TIME_TO_EMPTY_AVG:
ret = bq27x00_battery_time(di, BQ27x00_REG_TTECP, val);
break;
case POWER_SUPPLY_PROP_TIME_TO_FULL_NOW:
ret = bq27x00_battery_time(di, BQ27x00_REG_TTF, val);
break;
default:
return -EINVAL;
}
return ret;
}
static void bq27x00_powersupply_init(struct bq27x00_device_info *di)
{
di->bat.type = POWER_SUPPLY_TYPE_BATTERY;
di->bat.properties = bq27x00_battery_props;
di->bat.num_properties = ARRAY_SIZE(bq27x00_battery_props);
di->bat.get_property = bq27x00_battery_get_property;
di->bat.external_power_changed = NULL;
}
/*
* i2c specific code
*/
static int bq27x00_read_i2c(u8 reg, int *rt_value, int b_single,
struct bq27x00_device_info *di)
{
struct i2c_client *client = di->client;
struct i2c_msg msg[1];
unsigned char data[2];
int err;
if (!client->adapter)
return -ENODEV;
msg->addr = client->addr;
msg->flags = 0;
msg->len = 1;
msg->buf = data;
data[0] = reg;
err = i2c_transfer(client->adapter, msg, 1);
if (err >= 0) {
if (!b_single)
msg->len = 2;
else
msg->len = 1;
msg->flags = I2C_M_RD;
err = i2c_transfer(client->adapter, msg, 1);
if (err >= 0) {
if (!b_single)
*rt_value = get_unaligned_le16(data);
else
*rt_value = data[0];
return 0;
}
}
return err;
}
static int bq27x00_battery_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
char *name;
struct bq27x00_device_info *di;
struct bq27x00_access_methods *bus;
int num;
int retval = 0;
/* Get new ID for the new battery device */
retval = idr_pre_get(&battery_id, GFP_KERNEL);
if (retval == 0)
return -ENOMEM;
mutex_lock(&battery_mutex);
retval = idr_get_new(&battery_id, client, &num);
mutex_unlock(&battery_mutex);
if (retval < 0)
return retval;
name = kasprintf(GFP_KERNEL, "%s-%d", id->name, num);
if (!name) {
dev_err(&client->dev, "failed to allocate device name\n");
retval = -ENOMEM;
goto batt_failed_1;
}
di = kzalloc(sizeof(*di), GFP_KERNEL);
if (!di) {
dev_err(&client->dev, "failed to allocate device info data\n");
retval = -ENOMEM;
goto batt_failed_2;
}
di->id = num;
di->chip = id->driver_data;
bus = kzalloc(sizeof(*bus), GFP_KERNEL);
if (!bus) {
dev_err(&client->dev, "failed to allocate access method "
"data\n");
retval = -ENOMEM;
goto batt_failed_3;
}
i2c_set_clientdata(client, di);
di->dev = &client->dev;
di->bat.name = name;
bus->read = &bq27x00_read_i2c;
di->bus = bus;
di->client = client;
bq27x00_powersupply_init(di);
retval = power_supply_register(&client->dev, &di->bat);
if (retval) {
dev_err(&client->dev, "failed to register battery\n");
goto batt_failed_4;
}
dev_info(&client->dev, "support ver. %s enabled\n", DRIVER_VERSION);
return 0;
batt_failed_4:
kfree(bus);
batt_failed_3:
kfree(di);
batt_failed_2:
kfree(name);
batt_failed_1:
mutex_lock(&battery_mutex);
idr_remove(&battery_id, num);
mutex_unlock(&battery_mutex);
return retval;
}
static int bq27x00_battery_remove(struct i2c_client *client)
{
struct bq27x00_device_info *di = i2c_get_clientdata(client);
power_supply_unregister(&di->bat);
kfree(di->bat.name);
mutex_lock(&battery_mutex);
idr_remove(&battery_id, di->id);
mutex_unlock(&battery_mutex);
kfree(di);
return 0;
}
/*
* Module stuff
*/
static const struct i2c_device_id bq27x00_id[] = {
{ "bq27200", BQ27000 }, /* bq27200 is same as bq27000, but with i2c */
{ "bq27500", BQ27500 },
{},
};
static struct i2c_driver bq27x00_battery_driver = {
.driver = {
.name = "bq27x00-battery",
},
.probe = bq27x00_battery_probe,
.remove = bq27x00_battery_remove,
.id_table = bq27x00_id,
};
static int __init bq27x00_battery_init(void)
{
int ret;
ret = i2c_add_driver(&bq27x00_battery_driver);
if (ret)
printk(KERN_ERR "Unable to register BQ27x00 driver\n");
return ret;
}
module_init(bq27x00_battery_init);
static void __exit bq27x00_battery_exit(void)
{
i2c_del_driver(&bq27x00_battery_driver);
}
module_exit(bq27x00_battery_exit);
MODULE_AUTHOR("Rodolfo Giometti <giometti@linux.it>");
MODULE_DESCRIPTION("BQ27x00 battery monitor driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
lukier/linux-samsung | drivers/media/platform/s5p-tv/mixer_vp_layer.c | 1701 | 6395 | /*
* Samsung TV Mixer driver
*
* Copyright (c) 2010-2011 Samsung Electronics Co., Ltd.
*
* Tomasz Stanislawski, <t.stanislaws@samsung.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundiation. either version 2 of the License,
* or (at your option) any later version
*/
#include "mixer.h"
#include "regs-vp.h"
#include <media/videobuf2-dma-contig.h>
/* FORMAT DEFINITIONS */
static const struct mxr_format mxr_fmt_nv12 = {
.name = "NV12",
.fourcc = V4L2_PIX_FMT_NV12,
.colorspace = V4L2_COLORSPACE_JPEG,
.num_planes = 2,
.plane = {
{ .width = 1, .height = 1, .size = 1 },
{ .width = 2, .height = 2, .size = 2 },
},
.num_subframes = 1,
.cookie = VP_MODE_NV12 | VP_MODE_MEM_LINEAR,
};
static const struct mxr_format mxr_fmt_nv21 = {
.name = "NV21",
.fourcc = V4L2_PIX_FMT_NV21,
.colorspace = V4L2_COLORSPACE_JPEG,
.num_planes = 2,
.plane = {
{ .width = 1, .height = 1, .size = 1 },
{ .width = 2, .height = 2, .size = 2 },
},
.num_subframes = 1,
.cookie = VP_MODE_NV21 | VP_MODE_MEM_LINEAR,
};
static const struct mxr_format mxr_fmt_nv12m = {
.name = "NV12 (mplane)",
.fourcc = V4L2_PIX_FMT_NV12M,
.colorspace = V4L2_COLORSPACE_JPEG,
.num_planes = 2,
.plane = {
{ .width = 1, .height = 1, .size = 1 },
{ .width = 2, .height = 2, .size = 2 },
},
.num_subframes = 2,
.plane2subframe = {0, 1},
.cookie = VP_MODE_NV12 | VP_MODE_MEM_LINEAR,
};
static const struct mxr_format mxr_fmt_nv12mt = {
.name = "NV12 tiled (mplane)",
.fourcc = V4L2_PIX_FMT_NV12MT,
.colorspace = V4L2_COLORSPACE_JPEG,
.num_planes = 2,
.plane = {
{ .width = 128, .height = 32, .size = 4096 },
{ .width = 128, .height = 32, .size = 2048 },
},
.num_subframes = 2,
.plane2subframe = {0, 1},
.cookie = VP_MODE_NV12 | VP_MODE_MEM_TILED,
};
static const struct mxr_format *mxr_video_format[] = {
&mxr_fmt_nv12,
&mxr_fmt_nv21,
&mxr_fmt_nv12m,
&mxr_fmt_nv12mt,
};
/* AUXILIARY CALLBACKS */
static void mxr_vp_layer_release(struct mxr_layer *layer)
{
mxr_base_layer_unregister(layer);
mxr_base_layer_release(layer);
}
static void mxr_vp_buffer_set(struct mxr_layer *layer,
struct mxr_buffer *buf)
{
dma_addr_t luma_addr[2] = {0, 0};
dma_addr_t chroma_addr[2] = {0, 0};
if (buf == NULL) {
mxr_reg_vp_buffer(layer->mdev, luma_addr, chroma_addr);
return;
}
luma_addr[0] = vb2_dma_contig_plane_dma_addr(&buf->vb, 0);
if (layer->fmt->num_subframes == 2) {
chroma_addr[0] = vb2_dma_contig_plane_dma_addr(&buf->vb, 1);
} else {
/* FIXME: mxr_get_plane_size compute integer division,
* which is slow and should not be performed in interrupt */
chroma_addr[0] = luma_addr[0] + mxr_get_plane_size(
&layer->fmt->plane[0], layer->geo.src.full_width,
layer->geo.src.full_height);
}
if (layer->fmt->cookie & VP_MODE_MEM_TILED) {
luma_addr[1] = luma_addr[0] + 0x40;
chroma_addr[1] = chroma_addr[0] + 0x40;
} else {
luma_addr[1] = luma_addr[0] + layer->geo.src.full_width;
chroma_addr[1] = chroma_addr[0];
}
mxr_reg_vp_buffer(layer->mdev, luma_addr, chroma_addr);
}
static void mxr_vp_stream_set(struct mxr_layer *layer, int en)
{
mxr_reg_vp_layer_stream(layer->mdev, en);
}
static void mxr_vp_format_set(struct mxr_layer *layer)
{
mxr_reg_vp_format(layer->mdev, layer->fmt, &layer->geo);
}
static inline unsigned int do_center(unsigned int center,
unsigned int size, unsigned int upper, unsigned int flags)
{
unsigned int lower;
if (flags & MXR_NO_OFFSET)
return 0;
lower = center - min(center, size / 2);
return min(lower, upper - size);
}
static void mxr_vp_fix_geometry(struct mxr_layer *layer,
enum mxr_geometry_stage stage, unsigned long flags)
{
struct mxr_geometry *geo = &layer->geo;
struct mxr_crop *src = &geo->src;
struct mxr_crop *dst = &geo->dst;
unsigned long x_center, y_center;
switch (stage) {
case MXR_GEOMETRY_SINK: /* nothing to be fixed here */
case MXR_GEOMETRY_COMPOSE:
/* remember center of the area */
x_center = dst->x_offset + dst->width / 2;
y_center = dst->y_offset + dst->height / 2;
/* ensure that compose is reachable using 16x scaling */
dst->width = clamp(dst->width, 8U, 16 * src->full_width);
dst->height = clamp(dst->height, 1U, 16 * src->full_height);
/* setup offsets */
dst->x_offset = do_center(x_center, dst->width,
dst->full_width, flags);
dst->y_offset = do_center(y_center, dst->height,
dst->full_height, flags);
flags = 0; /* remove possible MXR_NO_OFFSET flag */
/* fall through */
case MXR_GEOMETRY_CROP:
/* remember center of the area */
x_center = src->x_offset + src->width / 2;
y_center = src->y_offset + src->height / 2;
/* ensure scaling is between 0.25x .. 16x */
src->width = clamp(src->width, round_up(dst->width / 16, 4),
dst->width * 4);
src->height = clamp(src->height, round_up(dst->height / 16, 4),
dst->height * 4);
/* hardware limits */
src->width = clamp(src->width, 32U, 2047U);
src->height = clamp(src->height, 4U, 2047U);
/* setup offsets */
src->x_offset = do_center(x_center, src->width,
src->full_width, flags);
src->y_offset = do_center(y_center, src->height,
src->full_height, flags);
/* setting scaling ratio */
geo->x_ratio = (src->width << 16) / dst->width;
geo->y_ratio = (src->height << 16) / dst->height;
/* fall through */
case MXR_GEOMETRY_SOURCE:
src->full_width = clamp(src->full_width,
ALIGN(src->width + src->x_offset, 8), 8192U);
src->full_height = clamp(src->full_height,
src->height + src->y_offset, 8192U);
}
}
/* PUBLIC API */
struct mxr_layer *mxr_vp_layer_create(struct mxr_device *mdev, int idx)
{
struct mxr_layer *layer;
int ret;
struct mxr_layer_ops ops = {
.release = mxr_vp_layer_release,
.buffer_set = mxr_vp_buffer_set,
.stream_set = mxr_vp_stream_set,
.format_set = mxr_vp_format_set,
.fix_geometry = mxr_vp_fix_geometry,
};
char name[32];
sprintf(name, "video%d", idx);
layer = mxr_base_layer_create(mdev, idx, name, &ops);
if (layer == NULL) {
mxr_err(mdev, "failed to initialize layer(%d) base\n", idx);
goto fail;
}
layer->fmt_array = mxr_video_format;
layer->fmt_array_size = ARRAY_SIZE(mxr_video_format);
ret = mxr_base_layer_register(layer);
if (ret)
goto fail_layer;
return layer;
fail_layer:
mxr_base_layer_release(layer);
fail:
return NULL;
}
| gpl-2.0 |
chenxiaolong/Note4Kernel | drivers/staging/rtl8192u/ieee80211/ieee80211_softmac_wx.c | 2213 | 14474 | /* IEEE 802.11 SoftMAC layer
* Copyright (c) 2005 Andrea Merello <andreamrl@tiscali.it>
*
* Mostly extracted from the rtl8180-sa2400 driver for the
* in-kernel generic ieee802.11 stack.
*
* Some pieces of code might be stolen from ipw2100 driver
* copyright of who own it's copyright ;-)
*
* PS wx handler mostly stolen from hostap, copyright who
* own it's copyright ;-)
*
* released under the GPL
*/
#include <linux/etherdevice.h>
#include "ieee80211.h"
#include "dot11d.h"
/* FIXME: add A freqs */
const long ieee80211_wlan_frequencies[] = {
2412, 2417, 2422, 2427,
2432, 2437, 2442, 2447,
2452, 2457, 2462, 2467,
2472, 2484
};
int ieee80211_wx_set_freq(struct ieee80211_device *ieee, struct iw_request_info *a,
union iwreq_data *wrqu, char *b)
{
int ret;
struct iw_freq *fwrq = & wrqu->freq;
down(&ieee->wx_sem);
if(ieee->iw_mode == IW_MODE_INFRA){
ret = -EOPNOTSUPP;
goto out;
}
/* if setting by freq convert to channel */
if (fwrq->e == 1) {
if ((fwrq->m >= (int) 2.412e8 &&
fwrq->m <= (int) 2.487e8)) {
int f = fwrq->m / 100000;
int c = 0;
while ((c < 14) && (f != ieee80211_wlan_frequencies[c]))
c++;
/* hack to fall through */
fwrq->e = 0;
fwrq->m = c + 1;
}
}
if (fwrq->e > 0 || fwrq->m > 14 || fwrq->m < 1 ){
ret = -EOPNOTSUPP;
goto out;
}else { /* Set the channel */
if (!(GET_DOT11D_INFO(ieee)->channel_map)[fwrq->m]) {
ret = -EINVAL;
goto out;
}
ieee->current_network.channel = fwrq->m;
ieee->set_chan(ieee->dev, ieee->current_network.channel);
if(ieee->iw_mode == IW_MODE_ADHOC || ieee->iw_mode == IW_MODE_MASTER)
if(ieee->state == IEEE80211_LINKED){
ieee80211_stop_send_beacons(ieee);
ieee80211_start_send_beacons(ieee);
}
}
ret = 0;
out:
up(&ieee->wx_sem);
return ret;
}
int ieee80211_wx_get_freq(struct ieee80211_device *ieee,
struct iw_request_info *a,
union iwreq_data *wrqu, char *b)
{
struct iw_freq *fwrq = & wrqu->freq;
if (ieee->current_network.channel == 0)
return -1;
//NM 0.7.0 will not accept channel any more.
fwrq->m = ieee80211_wlan_frequencies[ieee->current_network.channel-1] * 100000;
fwrq->e = 1;
// fwrq->m = ieee->current_network.channel;
// fwrq->e = 0;
return 0;
}
int ieee80211_wx_get_wap(struct ieee80211_device *ieee,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
unsigned long flags;
wrqu->ap_addr.sa_family = ARPHRD_ETHER;
if (ieee->iw_mode == IW_MODE_MONITOR)
return -1;
/* We want avoid to give to the user inconsistent infos*/
spin_lock_irqsave(&ieee->lock, flags);
if (ieee->state != IEEE80211_LINKED &&
ieee->state != IEEE80211_LINKED_SCANNING &&
ieee->wap_set == 0)
memset(wrqu->ap_addr.sa_data, 0, ETH_ALEN);
else
memcpy(wrqu->ap_addr.sa_data,
ieee->current_network.bssid, ETH_ALEN);
spin_unlock_irqrestore(&ieee->lock, flags);
return 0;
}
int ieee80211_wx_set_wap(struct ieee80211_device *ieee,
struct iw_request_info *info,
union iwreq_data *awrq,
char *extra)
{
int ret = 0;
unsigned long flags;
short ifup = ieee->proto_started;//dev->flags & IFF_UP;
struct sockaddr *temp = (struct sockaddr *)awrq;
ieee->sync_scan_hurryup = 1;
down(&ieee->wx_sem);
/* use ifconfig hw ether */
if (ieee->iw_mode == IW_MODE_MASTER){
ret = -1;
goto out;
}
if (temp->sa_family != ARPHRD_ETHER){
ret = -EINVAL;
goto out;
}
if (ifup)
ieee80211_stop_protocol(ieee);
/* just to avoid to give inconsistent infos in the
* get wx method. not really needed otherwise
*/
spin_lock_irqsave(&ieee->lock, flags);
memcpy(ieee->current_network.bssid, temp->sa_data, ETH_ALEN);
ieee->wap_set = !is_zero_ether_addr(temp->sa_data);
spin_unlock_irqrestore(&ieee->lock, flags);
if (ifup)
ieee80211_start_protocol(ieee);
out:
up(&ieee->wx_sem);
return ret;
}
int ieee80211_wx_get_essid(struct ieee80211_device *ieee, struct iw_request_info *a,union iwreq_data *wrqu,char *b)
{
int len,ret = 0;
unsigned long flags;
if (ieee->iw_mode == IW_MODE_MONITOR)
return -1;
/* We want avoid to give to the user inconsistent infos*/
spin_lock_irqsave(&ieee->lock, flags);
if (ieee->current_network.ssid[0] == '\0' ||
ieee->current_network.ssid_len == 0){
ret = -1;
goto out;
}
if (ieee->state != IEEE80211_LINKED &&
ieee->state != IEEE80211_LINKED_SCANNING &&
ieee->ssid_set == 0){
ret = -1;
goto out;
}
len = ieee->current_network.ssid_len;
wrqu->essid.length = len;
strncpy(b,ieee->current_network.ssid,len);
wrqu->essid.flags = 1;
out:
spin_unlock_irqrestore(&ieee->lock, flags);
return ret;
}
int ieee80211_wx_set_rate(struct ieee80211_device *ieee,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
u32 target_rate = wrqu->bitrate.value;
ieee->rate = target_rate/100000;
//FIXME: we might want to limit rate also in management protocols.
return 0;
}
int ieee80211_wx_get_rate(struct ieee80211_device *ieee,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
u32 tmp_rate;
tmp_rate = TxCountToDataRate(ieee, ieee->softmac_stats.CurrentShowTxate);
wrqu->bitrate.value = tmp_rate * 500000;
return 0;
}
int ieee80211_wx_set_rts(struct ieee80211_device *ieee,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
if (wrqu->rts.disabled || !wrqu->rts.fixed)
ieee->rts = DEFAULT_RTS_THRESHOLD;
else
{
if (wrqu->rts.value < MIN_RTS_THRESHOLD ||
wrqu->rts.value > MAX_RTS_THRESHOLD)
return -EINVAL;
ieee->rts = wrqu->rts.value;
}
return 0;
}
int ieee80211_wx_get_rts(struct ieee80211_device *ieee,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
wrqu->rts.value = ieee->rts;
wrqu->rts.fixed = 0; /* no auto select */
wrqu->rts.disabled = (wrqu->rts.value == DEFAULT_RTS_THRESHOLD);
return 0;
}
int ieee80211_wx_set_mode(struct ieee80211_device *ieee, struct iw_request_info *a,
union iwreq_data *wrqu, char *b)
{
ieee->sync_scan_hurryup = 1;
down(&ieee->wx_sem);
if (wrqu->mode == ieee->iw_mode)
goto out;
if (wrqu->mode == IW_MODE_MONITOR){
ieee->dev->type = ARPHRD_IEEE80211;
}else{
ieee->dev->type = ARPHRD_ETHER;
}
if (!ieee->proto_started){
ieee->iw_mode = wrqu->mode;
}else{
ieee80211_stop_protocol(ieee);
ieee->iw_mode = wrqu->mode;
ieee80211_start_protocol(ieee);
}
out:
up(&ieee->wx_sem);
return 0;
}
void ieee80211_wx_sync_scan_wq(struct work_struct *work)
{
struct ieee80211_device *ieee = container_of(work, struct ieee80211_device, wx_sync_scan_wq);
short chan;
HT_EXTCHNL_OFFSET chan_offset=0;
HT_CHANNEL_WIDTH bandwidth=0;
int b40M = 0;
static int count;
chan = ieee->current_network.channel;
netif_carrier_off(ieee->dev);
if (ieee->data_hard_stop)
ieee->data_hard_stop(ieee->dev);
ieee80211_stop_send_beacons(ieee);
ieee->state = IEEE80211_LINKED_SCANNING;
ieee->link_change(ieee->dev);
ieee->InitialGainHandler(ieee->dev,IG_Backup);
if (ieee->pHTInfo->bCurrentHTSupport && ieee->pHTInfo->bEnableHT && ieee->pHTInfo->bCurBW40MHz) {
b40M = 1;
chan_offset = ieee->pHTInfo->CurSTAExtChnlOffset;
bandwidth = (HT_CHANNEL_WIDTH)ieee->pHTInfo->bCurBW40MHz;
printk("Scan in 40M, force to 20M first:%d, %d\n", chan_offset, bandwidth);
ieee->SetBWModeHandler(ieee->dev, HT_CHANNEL_WIDTH_20, HT_EXTCHNL_OFFSET_NO_EXT);
}
ieee80211_start_scan_syncro(ieee);
if (b40M) {
printk("Scan in 20M, back to 40M\n");
if (chan_offset == HT_EXTCHNL_OFFSET_UPPER)
ieee->set_chan(ieee->dev, chan + 2);
else if (chan_offset == HT_EXTCHNL_OFFSET_LOWER)
ieee->set_chan(ieee->dev, chan - 2);
else
ieee->set_chan(ieee->dev, chan);
ieee->SetBWModeHandler(ieee->dev, bandwidth, chan_offset);
} else {
ieee->set_chan(ieee->dev, chan);
}
ieee->InitialGainHandler(ieee->dev,IG_Restore);
ieee->state = IEEE80211_LINKED;
ieee->link_change(ieee->dev);
// To prevent the immediately calling watch_dog after scan.
if(ieee->LinkDetectInfo.NumRecvBcnInPeriod==0||ieee->LinkDetectInfo.NumRecvDataInPeriod==0 )
{
ieee->LinkDetectInfo.NumRecvBcnInPeriod = 1;
ieee->LinkDetectInfo.NumRecvDataInPeriod= 1;
}
if (ieee->data_hard_resume)
ieee->data_hard_resume(ieee->dev);
if(ieee->iw_mode == IW_MODE_ADHOC || ieee->iw_mode == IW_MODE_MASTER)
ieee80211_start_send_beacons(ieee);
netif_carrier_on(ieee->dev);
count = 0;
up(&ieee->wx_sem);
}
int ieee80211_wx_set_scan(struct ieee80211_device *ieee, struct iw_request_info *a,
union iwreq_data *wrqu, char *b)
{
int ret = 0;
down(&ieee->wx_sem);
if (ieee->iw_mode == IW_MODE_MONITOR || !(ieee->proto_started)){
ret = -1;
goto out;
}
if ( ieee->state == IEEE80211_LINKED){
queue_work(ieee->wq, &ieee->wx_sync_scan_wq);
/* intentionally forget to up sem */
return 0;
}
out:
up(&ieee->wx_sem);
return ret;
}
int ieee80211_wx_set_essid(struct ieee80211_device *ieee,
struct iw_request_info *a,
union iwreq_data *wrqu, char *extra)
{
int ret=0,len;
short proto_started;
unsigned long flags;
ieee->sync_scan_hurryup = 1;
down(&ieee->wx_sem);
proto_started = ieee->proto_started;
if (wrqu->essid.length > IW_ESSID_MAX_SIZE){
ret= -E2BIG;
goto out;
}
if (ieee->iw_mode == IW_MODE_MONITOR){
ret= -1;
goto out;
}
if(proto_started)
ieee80211_stop_protocol(ieee);
/* this is just to be sure that the GET wx callback
* has consisten infos. not needed otherwise
*/
spin_lock_irqsave(&ieee->lock, flags);
if (wrqu->essid.flags && wrqu->essid.length) {
//first flush current network.ssid
len = ((wrqu->essid.length-1) < IW_ESSID_MAX_SIZE) ? (wrqu->essid.length-1) : IW_ESSID_MAX_SIZE;
strncpy(ieee->current_network.ssid, extra, len+1);
ieee->current_network.ssid_len = len+1;
ieee->ssid_set = 1;
}
else{
ieee->ssid_set = 0;
ieee->current_network.ssid[0] = '\0';
ieee->current_network.ssid_len = 0;
}
spin_unlock_irqrestore(&ieee->lock, flags);
if (proto_started)
ieee80211_start_protocol(ieee);
out:
up(&ieee->wx_sem);
return ret;
}
int ieee80211_wx_get_mode(struct ieee80211_device *ieee, struct iw_request_info *a,
union iwreq_data *wrqu, char *b)
{
wrqu->mode = ieee->iw_mode;
return 0;
}
int ieee80211_wx_set_rawtx(struct ieee80211_device *ieee,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
int *parms = (int *)extra;
int enable = (parms[0] > 0);
short prev = ieee->raw_tx;
down(&ieee->wx_sem);
if(enable)
ieee->raw_tx = 1;
else
ieee->raw_tx = 0;
printk(KERN_INFO"raw TX is %s\n",
ieee->raw_tx ? "enabled" : "disabled");
if(ieee->iw_mode == IW_MODE_MONITOR)
{
if(prev == 0 && ieee->raw_tx){
if (ieee->data_hard_resume)
ieee->data_hard_resume(ieee->dev);
netif_carrier_on(ieee->dev);
}
if(prev && ieee->raw_tx == 1)
netif_carrier_off(ieee->dev);
}
up(&ieee->wx_sem);
return 0;
}
int ieee80211_wx_get_name(struct ieee80211_device *ieee,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
strlcpy(wrqu->name, "802.11", IFNAMSIZ);
if (ieee->modulation & IEEE80211_CCK_MODULATION) {
strlcat(wrqu->name, "b", IFNAMSIZ);
if (ieee->modulation & IEEE80211_OFDM_MODULATION)
strlcat(wrqu->name, "/g", IFNAMSIZ);
} else if (ieee->modulation & IEEE80211_OFDM_MODULATION) {
strlcat(wrqu->name, "g", IFNAMSIZ);
}
if (ieee->mode & (IEEE_N_24G | IEEE_N_5G))
strlcat(wrqu->name, "/n", IFNAMSIZ);
if ((ieee->state == IEEE80211_LINKED) ||
(ieee->state == IEEE80211_LINKED_SCANNING))
strlcat(wrqu->name, " linked", IFNAMSIZ);
else if (ieee->state != IEEE80211_NOLINK)
strlcat(wrqu->name, " link..", IFNAMSIZ);
return 0;
}
/* this is mostly stolen from hostap */
int ieee80211_wx_set_power(struct ieee80211_device *ieee,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
int ret = 0;
down(&ieee->wx_sem);
if (wrqu->power.disabled){
ieee->ps = IEEE80211_PS_DISABLED;
goto exit;
}
if (wrqu->power.flags & IW_POWER_TIMEOUT) {
//ieee->ps_period = wrqu->power.value / 1000;
ieee->ps_timeout = wrqu->power.value / 1000;
}
if (wrqu->power.flags & IW_POWER_PERIOD) {
//ieee->ps_timeout = wrqu->power.value / 1000;
ieee->ps_period = wrqu->power.value / 1000;
//wrq->value / 1024;
}
switch (wrqu->power.flags & IW_POWER_MODE) {
case IW_POWER_UNICAST_R:
ieee->ps = IEEE80211_PS_UNICAST;
break;
case IW_POWER_MULTICAST_R:
ieee->ps = IEEE80211_PS_MBCAST;
break;
case IW_POWER_ALL_R:
ieee->ps = IEEE80211_PS_UNICAST | IEEE80211_PS_MBCAST;
break;
case IW_POWER_ON:
// ieee->ps = IEEE80211_PS_DISABLED;
break;
default:
ret = -EINVAL;
goto exit;
}
exit:
up(&ieee->wx_sem);
return ret;
}
/* this is stolen from hostap */
int ieee80211_wx_get_power(struct ieee80211_device *ieee,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
int ret =0;
down(&ieee->wx_sem);
if(ieee->ps == IEEE80211_PS_DISABLED){
wrqu->power.disabled = 1;
goto exit;
}
wrqu->power.disabled = 0;
if ((wrqu->power.flags & IW_POWER_TYPE) == IW_POWER_TIMEOUT) {
wrqu->power.flags = IW_POWER_TIMEOUT;
wrqu->power.value = ieee->ps_timeout * 1000;
} else {
// ret = -EOPNOTSUPP;
// goto exit;
wrqu->power.flags = IW_POWER_PERIOD;
wrqu->power.value = ieee->ps_period * 1000;
//ieee->current_network.dtim_period * ieee->current_network.beacon_interval * 1024;
}
if ((ieee->ps & (IEEE80211_PS_MBCAST | IEEE80211_PS_UNICAST)) == (IEEE80211_PS_MBCAST | IEEE80211_PS_UNICAST))
wrqu->power.flags |= IW_POWER_ALL_R;
else if (ieee->ps & IEEE80211_PS_MBCAST)
wrqu->power.flags |= IW_POWER_MULTICAST_R;
else
wrqu->power.flags |= IW_POWER_UNICAST_R;
exit:
up(&ieee->wx_sem);
return ret;
}
EXPORT_SYMBOL(ieee80211_wx_get_essid);
EXPORT_SYMBOL(ieee80211_wx_set_essid);
EXPORT_SYMBOL(ieee80211_wx_set_rate);
EXPORT_SYMBOL(ieee80211_wx_get_rate);
EXPORT_SYMBOL(ieee80211_wx_set_wap);
EXPORT_SYMBOL(ieee80211_wx_get_wap);
EXPORT_SYMBOL(ieee80211_wx_set_mode);
EXPORT_SYMBOL(ieee80211_wx_get_mode);
EXPORT_SYMBOL(ieee80211_wx_set_scan);
EXPORT_SYMBOL(ieee80211_wx_get_freq);
EXPORT_SYMBOL(ieee80211_wx_set_freq);
EXPORT_SYMBOL(ieee80211_wx_set_rawtx);
EXPORT_SYMBOL(ieee80211_wx_get_name);
EXPORT_SYMBOL(ieee80211_wx_set_power);
EXPORT_SYMBOL(ieee80211_wx_get_power);
EXPORT_SYMBOL(ieee80211_wlan_frequencies);
EXPORT_SYMBOL(ieee80211_wx_set_rts);
EXPORT_SYMBOL(ieee80211_wx_get_rts);
| gpl-2.0 |
TheNikiz/android_kernel_samsung_vivaltonfc3g | drivers/hwmon/w83627hf.c | 2213 | 57673 | /*
* w83627hf.c - Part of lm_sensors, Linux kernel modules for hardware
* monitoring
* Copyright (c) 1998 - 2003 Frodo Looijaard <frodol@dds.nl>,
* Philip Edelbrock <phil@netroedge.com>,
* and Mark Studebaker <mdsxyz123@yahoo.com>
* Ported to 2.6 by Bernhard C. Schrenk <clemy@clemy.org>
* Copyright (c) 2007 - 1012 Jean Delvare <khali@linux-fr.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
* Supports following chips:
*
* Chip #vin #fanin #pwm #temp wchipid vendid i2c ISA
* w83627hf 9 3 2 3 0x20 0x5ca3 no yes(LPC)
* w83627thf 7 3 3 3 0x90 0x5ca3 no yes(LPC)
* w83637hf 7 3 3 3 0x80 0x5ca3 no yes(LPC)
* w83687thf 7 3 3 3 0x90 0x5ca3 no yes(LPC)
* w83697hf 8 2 2 2 0x60 0x5ca3 no yes(LPC)
*
* For other winbond chips, and for i2c support in the above chips,
* use w83781d.c.
*
* Note: automatic ("cruise") fan control for 697, 637 & 627thf not
* supported yet.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
#include <linux/platform_device.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/hwmon-vid.h>
#include <linux/err.h>
#include <linux/mutex.h>
#include <linux/ioport.h>
#include <linux/acpi.h>
#include <linux/io.h>
#include "lm75.h"
static struct platform_device *pdev;
#define DRVNAME "w83627hf"
enum chips { w83627hf, w83627thf, w83697hf, w83637hf, w83687thf };
struct w83627hf_sio_data {
enum chips type;
int sioaddr;
};
static u8 force_i2c = 0x1f;
module_param(force_i2c, byte, 0);
MODULE_PARM_DESC(force_i2c,
"Initialize the i2c address of the sensors");
static bool init = 1;
module_param(init, bool, 0);
MODULE_PARM_DESC(init, "Set to zero to bypass chip initialization");
static unsigned short force_id;
module_param(force_id, ushort, 0);
MODULE_PARM_DESC(force_id, "Override the detected device ID");
/* modified from kernel/include/traps.c */
#define DEV 0x07 /* Register: Logical device select */
/* logical device numbers for superio_select (below) */
#define W83627HF_LD_FDC 0x00
#define W83627HF_LD_PRT 0x01
#define W83627HF_LD_UART1 0x02
#define W83627HF_LD_UART2 0x03
#define W83627HF_LD_KBC 0x05
#define W83627HF_LD_CIR 0x06 /* w83627hf only */
#define W83627HF_LD_GAME 0x07
#define W83627HF_LD_MIDI 0x07
#define W83627HF_LD_GPIO1 0x07
#define W83627HF_LD_GPIO5 0x07 /* w83627thf only */
#define W83627HF_LD_GPIO2 0x08
#define W83627HF_LD_GPIO3 0x09
#define W83627HF_LD_GPIO4 0x09 /* w83627thf only */
#define W83627HF_LD_ACPI 0x0a
#define W83627HF_LD_HWM 0x0b
#define DEVID 0x20 /* Register: Device ID */
#define W83627THF_GPIO5_EN 0x30 /* w83627thf only */
#define W83627THF_GPIO5_IOSR 0xf3 /* w83627thf only */
#define W83627THF_GPIO5_DR 0xf4 /* w83627thf only */
#define W83687THF_VID_EN 0x29 /* w83687thf only */
#define W83687THF_VID_CFG 0xF0 /* w83687thf only */
#define W83687THF_VID_DATA 0xF1 /* w83687thf only */
static inline void
superio_outb(struct w83627hf_sio_data *sio, int reg, int val)
{
outb(reg, sio->sioaddr);
outb(val, sio->sioaddr + 1);
}
static inline int
superio_inb(struct w83627hf_sio_data *sio, int reg)
{
outb(reg, sio->sioaddr);
return inb(sio->sioaddr + 1);
}
static inline void
superio_select(struct w83627hf_sio_data *sio, int ld)
{
outb(DEV, sio->sioaddr);
outb(ld, sio->sioaddr + 1);
}
static inline void
superio_enter(struct w83627hf_sio_data *sio)
{
outb(0x87, sio->sioaddr);
outb(0x87, sio->sioaddr);
}
static inline void
superio_exit(struct w83627hf_sio_data *sio)
{
outb(0xAA, sio->sioaddr);
}
#define W627_DEVID 0x52
#define W627THF_DEVID 0x82
#define W697_DEVID 0x60
#define W637_DEVID 0x70
#define W687THF_DEVID 0x85
#define WINB_ACT_REG 0x30
#define WINB_BASE_REG 0x60
/* Constants specified below */
/* Alignment of the base address */
#define WINB_ALIGNMENT ~7
/* Offset & size of I/O region we are interested in */
#define WINB_REGION_OFFSET 5
#define WINB_REGION_SIZE 2
/* Where are the sensors address/data registers relative to the region offset */
#define W83781D_ADDR_REG_OFFSET 0
#define W83781D_DATA_REG_OFFSET 1
/* The W83781D registers */
/* The W83782D registers for nr=7,8 are in bank 5 */
#define W83781D_REG_IN_MAX(nr) ((nr < 7) ? (0x2b + (nr) * 2) : \
(0x554 + (((nr) - 7) * 2)))
#define W83781D_REG_IN_MIN(nr) ((nr < 7) ? (0x2c + (nr) * 2) : \
(0x555 + (((nr) - 7) * 2)))
#define W83781D_REG_IN(nr) ((nr < 7) ? (0x20 + (nr)) : \
(0x550 + (nr) - 7))
/* nr:0-2 for fans:1-3 */
#define W83627HF_REG_FAN_MIN(nr) (0x3b + (nr))
#define W83627HF_REG_FAN(nr) (0x28 + (nr))
#define W83627HF_REG_TEMP2_CONFIG 0x152
#define W83627HF_REG_TEMP3_CONFIG 0x252
/* these are zero-based, unlike config constants above */
static const u16 w83627hf_reg_temp[] = { 0x27, 0x150, 0x250 };
static const u16 w83627hf_reg_temp_hyst[] = { 0x3A, 0x153, 0x253 };
static const u16 w83627hf_reg_temp_over[] = { 0x39, 0x155, 0x255 };
#define W83781D_REG_BANK 0x4E
#define W83781D_REG_CONFIG 0x40
#define W83781D_REG_ALARM1 0x459
#define W83781D_REG_ALARM2 0x45A
#define W83781D_REG_ALARM3 0x45B
#define W83781D_REG_BEEP_CONFIG 0x4D
#define W83781D_REG_BEEP_INTS1 0x56
#define W83781D_REG_BEEP_INTS2 0x57
#define W83781D_REG_BEEP_INTS3 0x453
#define W83781D_REG_VID_FANDIV 0x47
#define W83781D_REG_CHIPID 0x49
#define W83781D_REG_WCHIPID 0x58
#define W83781D_REG_CHIPMAN 0x4F
#define W83781D_REG_PIN 0x4B
#define W83781D_REG_VBAT 0x5D
#define W83627HF_REG_PWM1 0x5A
#define W83627HF_REG_PWM2 0x5B
static const u8 W83627THF_REG_PWM_ENABLE[] = {
0x04, /* FAN 1 mode */
0x04, /* FAN 2 mode */
0x12, /* FAN AUX mode */
};
static const u8 W83627THF_PWM_ENABLE_SHIFT[] = { 2, 4, 1 };
#define W83627THF_REG_PWM1 0x01 /* 697HF/637HF/687THF too */
#define W83627THF_REG_PWM2 0x03 /* 697HF/637HF/687THF too */
#define W83627THF_REG_PWM3 0x11 /* 637HF/687THF too */
#define W83627THF_REG_VRM_OVT_CFG 0x18 /* 637HF/687THF too */
static const u8 regpwm_627hf[] = { W83627HF_REG_PWM1, W83627HF_REG_PWM2 };
static const u8 regpwm[] = { W83627THF_REG_PWM1, W83627THF_REG_PWM2,
W83627THF_REG_PWM3 };
#define W836X7HF_REG_PWM(type, nr) (((type) == w83627hf) ? \
regpwm_627hf[nr] : regpwm[nr])
#define W83627HF_REG_PWM_FREQ 0x5C /* Only for the 627HF */
#define W83637HF_REG_PWM_FREQ1 0x00 /* 697HF/687THF too */
#define W83637HF_REG_PWM_FREQ2 0x02 /* 697HF/687THF too */
#define W83637HF_REG_PWM_FREQ3 0x10 /* 687THF too */
static const u8 W83637HF_REG_PWM_FREQ[] = { W83637HF_REG_PWM_FREQ1,
W83637HF_REG_PWM_FREQ2,
W83637HF_REG_PWM_FREQ3 };
#define W83627HF_BASE_PWM_FREQ 46870
#define W83781D_REG_I2C_ADDR 0x48
#define W83781D_REG_I2C_SUBADDR 0x4A
/* Sensor selection */
#define W83781D_REG_SCFG1 0x5D
static const u8 BIT_SCFG1[] = { 0x02, 0x04, 0x08 };
#define W83781D_REG_SCFG2 0x59
static const u8 BIT_SCFG2[] = { 0x10, 0x20, 0x40 };
#define W83781D_DEFAULT_BETA 3435
/*
* Conversions. Limit checking is only done on the TO_REG
* variants. Note that you should be a bit careful with which arguments
* these macros are called: arguments may be evaluated more than once.
* Fixing this is just not worth it.
*/
#define IN_TO_REG(val) (clamp_val((((val) + 8) / 16), 0, 255))
#define IN_FROM_REG(val) ((val) * 16)
static inline u8 FAN_TO_REG(long rpm, int div)
{
if (rpm == 0)
return 255;
rpm = clamp_val(rpm, 1, 1000000);
return clamp_val((1350000 + rpm * div / 2) / (rpm * div), 1, 254);
}
#define TEMP_MIN (-128000)
#define TEMP_MAX ( 127000)
/*
* TEMP: 0.001C/bit (-128C to +127C)
* REG: 1C/bit, two's complement
*/
static u8 TEMP_TO_REG(long temp)
{
int ntemp = clamp_val(temp, TEMP_MIN, TEMP_MAX);
ntemp += (ntemp < 0 ? -500 : 500);
return (u8)(ntemp / 1000);
}
static int TEMP_FROM_REG(u8 reg)
{
return (s8)reg * 1000;
}
#define FAN_FROM_REG(val,div) ((val)==0?-1:(val)==255?0:1350000/((val)*(div)))
#define PWM_TO_REG(val) (clamp_val((val), 0, 255))
static inline unsigned long pwm_freq_from_reg_627hf(u8 reg)
{
unsigned long freq;
freq = W83627HF_BASE_PWM_FREQ >> reg;
return freq;
}
static inline u8 pwm_freq_to_reg_627hf(unsigned long val)
{
u8 i;
/*
* Only 5 dividers (1 2 4 8 16)
* Search for the nearest available frequency
*/
for (i = 0; i < 4; i++) {
if (val > (((W83627HF_BASE_PWM_FREQ >> i) +
(W83627HF_BASE_PWM_FREQ >> (i+1))) / 2))
break;
}
return i;
}
static inline unsigned long pwm_freq_from_reg(u8 reg)
{
/* Clock bit 8 -> 180 kHz or 24 MHz */
unsigned long clock = (reg & 0x80) ? 180000UL : 24000000UL;
reg &= 0x7f;
/* This should not happen but anyway... */
if (reg == 0)
reg++;
return clock / (reg << 8);
}
static inline u8 pwm_freq_to_reg(unsigned long val)
{
/* Minimum divider value is 0x01 and maximum is 0x7F */
if (val >= 93750) /* The highest we can do */
return 0x01;
if (val >= 720) /* Use 24 MHz clock */
return 24000000UL / (val << 8);
if (val < 6) /* The lowest we can do */
return 0xFF;
else /* Use 180 kHz clock */
return 0x80 | (180000UL / (val << 8));
}
#define BEEP_MASK_FROM_REG(val) ((val) & 0xff7fff)
#define BEEP_MASK_TO_REG(val) ((val) & 0xff7fff)
#define DIV_FROM_REG(val) (1 << (val))
static inline u8 DIV_TO_REG(long val)
{
int i;
val = clamp_val(val, 1, 128) >> 1;
for (i = 0; i < 7; i++) {
if (val == 0)
break;
val >>= 1;
}
return (u8)i;
}
/*
* For each registered chip, we need to keep some data in memory.
* The structure is dynamically allocated.
*/
struct w83627hf_data {
unsigned short addr;
const char *name;
struct device *hwmon_dev;
struct mutex lock;
enum chips type;
struct mutex update_lock;
char valid; /* !=0 if following fields are valid */
unsigned long last_updated; /* In jiffies */
u8 in[9]; /* Register value */
u8 in_max[9]; /* Register value */
u8 in_min[9]; /* Register value */
u8 fan[3]; /* Register value */
u8 fan_min[3]; /* Register value */
u16 temp[3]; /* Register value */
u16 temp_max[3]; /* Register value */
u16 temp_max_hyst[3]; /* Register value */
u8 fan_div[3]; /* Register encoding, shifted right */
u8 vid; /* Register encoding, combined */
u32 alarms; /* Register encoding, combined */
u32 beep_mask; /* Register encoding, combined */
u8 pwm[3]; /* Register value */
u8 pwm_enable[3]; /* 1 = manual
* 2 = thermal cruise (also called SmartFan I)
* 3 = fan speed cruise
*/
u8 pwm_freq[3]; /* Register value */
u16 sens[3]; /* 1 = pentium diode; 2 = 3904 diode;
* 4 = thermistor
*/
u8 vrm;
u8 vrm_ovt; /* Register value, 627THF/637HF/687THF only */
#ifdef CONFIG_PM
/* Remember extra register values over suspend/resume */
u8 scfg1;
u8 scfg2;
#endif
};
static int w83627hf_probe(struct platform_device *pdev);
static int w83627hf_remove(struct platform_device *pdev);
static int w83627hf_read_value(struct w83627hf_data *data, u16 reg);
static int w83627hf_write_value(struct w83627hf_data *data, u16 reg, u16 value);
static void w83627hf_update_fan_div(struct w83627hf_data *data);
static struct w83627hf_data *w83627hf_update_device(struct device *dev);
static void w83627hf_init_device(struct platform_device *pdev);
#ifdef CONFIG_PM
static int w83627hf_suspend(struct device *dev)
{
struct w83627hf_data *data = w83627hf_update_device(dev);
mutex_lock(&data->update_lock);
data->scfg1 = w83627hf_read_value(data, W83781D_REG_SCFG1);
data->scfg2 = w83627hf_read_value(data, W83781D_REG_SCFG2);
mutex_unlock(&data->update_lock);
return 0;
}
static int w83627hf_resume(struct device *dev)
{
struct w83627hf_data *data = dev_get_drvdata(dev);
int i, num_temps = (data->type == w83697hf) ? 2 : 3;
/* Restore limits */
mutex_lock(&data->update_lock);
for (i = 0; i <= 8; i++) {
/* skip missing sensors */
if (((data->type == w83697hf) && (i == 1)) ||
((data->type != w83627hf && data->type != w83697hf)
&& (i == 5 || i == 6)))
continue;
w83627hf_write_value(data, W83781D_REG_IN_MAX(i),
data->in_max[i]);
w83627hf_write_value(data, W83781D_REG_IN_MIN(i),
data->in_min[i]);
}
for (i = 0; i <= 2; i++)
w83627hf_write_value(data, W83627HF_REG_FAN_MIN(i),
data->fan_min[i]);
for (i = 0; i < num_temps; i++) {
w83627hf_write_value(data, w83627hf_reg_temp_over[i],
data->temp_max[i]);
w83627hf_write_value(data, w83627hf_reg_temp_hyst[i],
data->temp_max_hyst[i]);
}
/* Fixup BIOS bugs */
if (data->type == w83627thf || data->type == w83637hf ||
data->type == w83687thf)
w83627hf_write_value(data, W83627THF_REG_VRM_OVT_CFG,
data->vrm_ovt);
w83627hf_write_value(data, W83781D_REG_SCFG1, data->scfg1);
w83627hf_write_value(data, W83781D_REG_SCFG2, data->scfg2);
/* Force re-reading all values */
data->valid = 0;
mutex_unlock(&data->update_lock);
return 0;
}
static const struct dev_pm_ops w83627hf_dev_pm_ops = {
.suspend = w83627hf_suspend,
.resume = w83627hf_resume,
};
#define W83627HF_DEV_PM_OPS (&w83627hf_dev_pm_ops)
#else
#define W83627HF_DEV_PM_OPS NULL
#endif /* CONFIG_PM */
static struct platform_driver w83627hf_driver = {
.driver = {
.owner = THIS_MODULE,
.name = DRVNAME,
.pm = W83627HF_DEV_PM_OPS,
},
.probe = w83627hf_probe,
.remove = w83627hf_remove,
};
static ssize_t
show_in_input(struct device *dev, struct device_attribute *devattr, char *buf)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = w83627hf_update_device(dev);
return sprintf(buf, "%ld\n", (long)IN_FROM_REG(data->in[nr]));
}
static ssize_t
show_in_min(struct device *dev, struct device_attribute *devattr, char *buf)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = w83627hf_update_device(dev);
return sprintf(buf, "%ld\n", (long)IN_FROM_REG(data->in_min[nr]));
}
static ssize_t
show_in_max(struct device *dev, struct device_attribute *devattr, char *buf)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = w83627hf_update_device(dev);
return sprintf(buf, "%ld\n", (long)IN_FROM_REG(data->in_max[nr]));
}
static ssize_t
store_in_min(struct device *dev, struct device_attribute *devattr,
const char *buf, size_t count)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = dev_get_drvdata(dev);
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->in_min[nr] = IN_TO_REG(val);
w83627hf_write_value(data, W83781D_REG_IN_MIN(nr), data->in_min[nr]);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t
store_in_max(struct device *dev, struct device_attribute *devattr,
const char *buf, size_t count)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = dev_get_drvdata(dev);
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->in_max[nr] = IN_TO_REG(val);
w83627hf_write_value(data, W83781D_REG_IN_MAX(nr), data->in_max[nr]);
mutex_unlock(&data->update_lock);
return count;
}
#define sysfs_vin_decl(offset) \
static SENSOR_DEVICE_ATTR(in##offset##_input, S_IRUGO, \
show_in_input, NULL, offset); \
static SENSOR_DEVICE_ATTR(in##offset##_min, S_IRUGO|S_IWUSR, \
show_in_min, store_in_min, offset); \
static SENSOR_DEVICE_ATTR(in##offset##_max, S_IRUGO|S_IWUSR, \
show_in_max, store_in_max, offset);
sysfs_vin_decl(1);
sysfs_vin_decl(2);
sysfs_vin_decl(3);
sysfs_vin_decl(4);
sysfs_vin_decl(5);
sysfs_vin_decl(6);
sysfs_vin_decl(7);
sysfs_vin_decl(8);
/* use a different set of functions for in0 */
static ssize_t show_in_0(struct w83627hf_data *data, char *buf, u8 reg)
{
long in0;
if ((data->vrm_ovt & 0x01) &&
(w83627thf == data->type || w83637hf == data->type
|| w83687thf == data->type))
/* use VRM9 calculation */
in0 = (long)((reg * 488 + 70000 + 50) / 100);
else
/* use VRM8 (standard) calculation */
in0 = (long)IN_FROM_REG(reg);
return sprintf(buf,"%ld\n", in0);
}
static ssize_t show_regs_in_0(struct device *dev, struct device_attribute *attr, char *buf)
{
struct w83627hf_data *data = w83627hf_update_device(dev);
return show_in_0(data, buf, data->in[0]);
}
static ssize_t show_regs_in_min0(struct device *dev, struct device_attribute *attr, char *buf)
{
struct w83627hf_data *data = w83627hf_update_device(dev);
return show_in_0(data, buf, data->in_min[0]);
}
static ssize_t show_regs_in_max0(struct device *dev, struct device_attribute *attr, char *buf)
{
struct w83627hf_data *data = w83627hf_update_device(dev);
return show_in_0(data, buf, data->in_max[0]);
}
static ssize_t store_regs_in_min0(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct w83627hf_data *data = dev_get_drvdata(dev);
unsigned long val;
int err;
err = kstrtoul(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
if ((data->vrm_ovt & 0x01) &&
(w83627thf == data->type || w83637hf == data->type
|| w83687thf == data->type))
/* use VRM9 calculation */
data->in_min[0] =
clamp_val(((val * 100) - 70000 + 244) / 488, 0, 255);
else
/* use VRM8 (standard) calculation */
data->in_min[0] = IN_TO_REG(val);
w83627hf_write_value(data, W83781D_REG_IN_MIN(0), data->in_min[0]);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t store_regs_in_max0(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct w83627hf_data *data = dev_get_drvdata(dev);
unsigned long val;
int err;
err = kstrtoul(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
if ((data->vrm_ovt & 0x01) &&
(w83627thf == data->type || w83637hf == data->type
|| w83687thf == data->type))
/* use VRM9 calculation */
data->in_max[0] =
clamp_val(((val * 100) - 70000 + 244) / 488, 0, 255);
else
/* use VRM8 (standard) calculation */
data->in_max[0] = IN_TO_REG(val);
w83627hf_write_value(data, W83781D_REG_IN_MAX(0), data->in_max[0]);
mutex_unlock(&data->update_lock);
return count;
}
static DEVICE_ATTR(in0_input, S_IRUGO, show_regs_in_0, NULL);
static DEVICE_ATTR(in0_min, S_IRUGO | S_IWUSR,
show_regs_in_min0, store_regs_in_min0);
static DEVICE_ATTR(in0_max, S_IRUGO | S_IWUSR,
show_regs_in_max0, store_regs_in_max0);
static ssize_t
show_fan_input(struct device *dev, struct device_attribute *devattr, char *buf)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = w83627hf_update_device(dev);
return sprintf(buf, "%ld\n", FAN_FROM_REG(data->fan[nr],
(long)DIV_FROM_REG(data->fan_div[nr])));
}
static ssize_t
show_fan_min(struct device *dev, struct device_attribute *devattr, char *buf)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = w83627hf_update_device(dev);
return sprintf(buf, "%ld\n", FAN_FROM_REG(data->fan_min[nr],
(long)DIV_FROM_REG(data->fan_div[nr])));
}
static ssize_t
store_fan_min(struct device *dev, struct device_attribute *devattr,
const char *buf, size_t count)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = dev_get_drvdata(dev);
unsigned long val;
int err;
err = kstrtoul(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->fan_min[nr] = FAN_TO_REG(val, DIV_FROM_REG(data->fan_div[nr]));
w83627hf_write_value(data, W83627HF_REG_FAN_MIN(nr),
data->fan_min[nr]);
mutex_unlock(&data->update_lock);
return count;
}
#define sysfs_fan_decl(offset) \
static SENSOR_DEVICE_ATTR(fan##offset##_input, S_IRUGO, \
show_fan_input, NULL, offset - 1); \
static SENSOR_DEVICE_ATTR(fan##offset##_min, S_IRUGO | S_IWUSR, \
show_fan_min, store_fan_min, offset - 1);
sysfs_fan_decl(1);
sysfs_fan_decl(2);
sysfs_fan_decl(3);
static ssize_t
show_temp(struct device *dev, struct device_attribute *devattr, char *buf)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = w83627hf_update_device(dev);
u16 tmp = data->temp[nr];
return sprintf(buf, "%ld\n", (nr) ? (long) LM75_TEMP_FROM_REG(tmp)
: (long) TEMP_FROM_REG(tmp));
}
static ssize_t
show_temp_max(struct device *dev, struct device_attribute *devattr,
char *buf)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = w83627hf_update_device(dev);
u16 tmp = data->temp_max[nr];
return sprintf(buf, "%ld\n", (nr) ? (long) LM75_TEMP_FROM_REG(tmp)
: (long) TEMP_FROM_REG(tmp));
}
static ssize_t
show_temp_max_hyst(struct device *dev, struct device_attribute *devattr,
char *buf)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = w83627hf_update_device(dev);
u16 tmp = data->temp_max_hyst[nr];
return sprintf(buf, "%ld\n", (nr) ? (long) LM75_TEMP_FROM_REG(tmp)
: (long) TEMP_FROM_REG(tmp));
}
static ssize_t
store_temp_max(struct device *dev, struct device_attribute *devattr,
const char *buf, size_t count)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = dev_get_drvdata(dev);
u16 tmp;
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
tmp = (nr) ? LM75_TEMP_TO_REG(val) : TEMP_TO_REG(val);
mutex_lock(&data->update_lock);
data->temp_max[nr] = tmp;
w83627hf_write_value(data, w83627hf_reg_temp_over[nr], tmp);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t
store_temp_max_hyst(struct device *dev, struct device_attribute *devattr,
const char *buf, size_t count)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = dev_get_drvdata(dev);
u16 tmp;
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
tmp = (nr) ? LM75_TEMP_TO_REG(val) : TEMP_TO_REG(val);
mutex_lock(&data->update_lock);
data->temp_max_hyst[nr] = tmp;
w83627hf_write_value(data, w83627hf_reg_temp_hyst[nr], tmp);
mutex_unlock(&data->update_lock);
return count;
}
#define sysfs_temp_decl(offset) \
static SENSOR_DEVICE_ATTR(temp##offset##_input, S_IRUGO, \
show_temp, NULL, offset - 1); \
static SENSOR_DEVICE_ATTR(temp##offset##_max, S_IRUGO|S_IWUSR, \
show_temp_max, store_temp_max, offset - 1); \
static SENSOR_DEVICE_ATTR(temp##offset##_max_hyst, S_IRUGO|S_IWUSR, \
show_temp_max_hyst, store_temp_max_hyst, offset - 1);
sysfs_temp_decl(1);
sysfs_temp_decl(2);
sysfs_temp_decl(3);
static ssize_t
show_vid_reg(struct device *dev, struct device_attribute *attr, char *buf)
{
struct w83627hf_data *data = w83627hf_update_device(dev);
return sprintf(buf, "%ld\n", (long) vid_from_reg(data->vid, data->vrm));
}
static DEVICE_ATTR(cpu0_vid, S_IRUGO, show_vid_reg, NULL);
static ssize_t
show_vrm_reg(struct device *dev, struct device_attribute *attr, char *buf)
{
struct w83627hf_data *data = dev_get_drvdata(dev);
return sprintf(buf, "%ld\n", (long) data->vrm);
}
static ssize_t
store_vrm_reg(struct device *dev, struct device_attribute *attr, const char *buf, size_t count)
{
struct w83627hf_data *data = dev_get_drvdata(dev);
unsigned long val;
int err;
err = kstrtoul(buf, 10, &val);
if (err)
return err;
data->vrm = val;
return count;
}
static DEVICE_ATTR(vrm, S_IRUGO | S_IWUSR, show_vrm_reg, store_vrm_reg);
static ssize_t
show_alarms_reg(struct device *dev, struct device_attribute *attr, char *buf)
{
struct w83627hf_data *data = w83627hf_update_device(dev);
return sprintf(buf, "%ld\n", (long) data->alarms);
}
static DEVICE_ATTR(alarms, S_IRUGO, show_alarms_reg, NULL);
static ssize_t
show_alarm(struct device *dev, struct device_attribute *attr, char *buf)
{
struct w83627hf_data *data = w83627hf_update_device(dev);
int bitnr = to_sensor_dev_attr(attr)->index;
return sprintf(buf, "%u\n", (data->alarms >> bitnr) & 1);
}
static SENSOR_DEVICE_ATTR(in0_alarm, S_IRUGO, show_alarm, NULL, 0);
static SENSOR_DEVICE_ATTR(in1_alarm, S_IRUGO, show_alarm, NULL, 1);
static SENSOR_DEVICE_ATTR(in2_alarm, S_IRUGO, show_alarm, NULL, 2);
static SENSOR_DEVICE_ATTR(in3_alarm, S_IRUGO, show_alarm, NULL, 3);
static SENSOR_DEVICE_ATTR(in4_alarm, S_IRUGO, show_alarm, NULL, 8);
static SENSOR_DEVICE_ATTR(in5_alarm, S_IRUGO, show_alarm, NULL, 9);
static SENSOR_DEVICE_ATTR(in6_alarm, S_IRUGO, show_alarm, NULL, 10);
static SENSOR_DEVICE_ATTR(in7_alarm, S_IRUGO, show_alarm, NULL, 16);
static SENSOR_DEVICE_ATTR(in8_alarm, S_IRUGO, show_alarm, NULL, 17);
static SENSOR_DEVICE_ATTR(fan1_alarm, S_IRUGO, show_alarm, NULL, 6);
static SENSOR_DEVICE_ATTR(fan2_alarm, S_IRUGO, show_alarm, NULL, 7);
static SENSOR_DEVICE_ATTR(fan3_alarm, S_IRUGO, show_alarm, NULL, 11);
static SENSOR_DEVICE_ATTR(temp1_alarm, S_IRUGO, show_alarm, NULL, 4);
static SENSOR_DEVICE_ATTR(temp2_alarm, S_IRUGO, show_alarm, NULL, 5);
static SENSOR_DEVICE_ATTR(temp3_alarm, S_IRUGO, show_alarm, NULL, 13);
static ssize_t
show_beep_mask(struct device *dev, struct device_attribute *attr, char *buf)
{
struct w83627hf_data *data = w83627hf_update_device(dev);
return sprintf(buf, "%ld\n",
(long)BEEP_MASK_FROM_REG(data->beep_mask));
}
static ssize_t
store_beep_mask(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct w83627hf_data *data = dev_get_drvdata(dev);
unsigned long val;
int err;
err = kstrtoul(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
/* preserve beep enable */
data->beep_mask = (data->beep_mask & 0x8000)
| BEEP_MASK_TO_REG(val);
w83627hf_write_value(data, W83781D_REG_BEEP_INTS1,
data->beep_mask & 0xff);
w83627hf_write_value(data, W83781D_REG_BEEP_INTS3,
((data->beep_mask) >> 16) & 0xff);
w83627hf_write_value(data, W83781D_REG_BEEP_INTS2,
(data->beep_mask >> 8) & 0xff);
mutex_unlock(&data->update_lock);
return count;
}
static DEVICE_ATTR(beep_mask, S_IRUGO | S_IWUSR,
show_beep_mask, store_beep_mask);
static ssize_t
show_beep(struct device *dev, struct device_attribute *attr, char *buf)
{
struct w83627hf_data *data = w83627hf_update_device(dev);
int bitnr = to_sensor_dev_attr(attr)->index;
return sprintf(buf, "%u\n", (data->beep_mask >> bitnr) & 1);
}
static ssize_t
store_beep(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct w83627hf_data *data = dev_get_drvdata(dev);
int bitnr = to_sensor_dev_attr(attr)->index;
u8 reg;
unsigned long bit;
int err;
err = kstrtoul(buf, 10, &bit);
if (err)
return err;
if (bit & ~1)
return -EINVAL;
mutex_lock(&data->update_lock);
if (bit)
data->beep_mask |= (1 << bitnr);
else
data->beep_mask &= ~(1 << bitnr);
if (bitnr < 8) {
reg = w83627hf_read_value(data, W83781D_REG_BEEP_INTS1);
if (bit)
reg |= (1 << bitnr);
else
reg &= ~(1 << bitnr);
w83627hf_write_value(data, W83781D_REG_BEEP_INTS1, reg);
} else if (bitnr < 16) {
reg = w83627hf_read_value(data, W83781D_REG_BEEP_INTS2);
if (bit)
reg |= (1 << (bitnr - 8));
else
reg &= ~(1 << (bitnr - 8));
w83627hf_write_value(data, W83781D_REG_BEEP_INTS2, reg);
} else {
reg = w83627hf_read_value(data, W83781D_REG_BEEP_INTS3);
if (bit)
reg |= (1 << (bitnr - 16));
else
reg &= ~(1 << (bitnr - 16));
w83627hf_write_value(data, W83781D_REG_BEEP_INTS3, reg);
}
mutex_unlock(&data->update_lock);
return count;
}
static SENSOR_DEVICE_ATTR(in0_beep, S_IRUGO | S_IWUSR,
show_beep, store_beep, 0);
static SENSOR_DEVICE_ATTR(in1_beep, S_IRUGO | S_IWUSR,
show_beep, store_beep, 1);
static SENSOR_DEVICE_ATTR(in2_beep, S_IRUGO | S_IWUSR,
show_beep, store_beep, 2);
static SENSOR_DEVICE_ATTR(in3_beep, S_IRUGO | S_IWUSR,
show_beep, store_beep, 3);
static SENSOR_DEVICE_ATTR(in4_beep, S_IRUGO | S_IWUSR,
show_beep, store_beep, 8);
static SENSOR_DEVICE_ATTR(in5_beep, S_IRUGO | S_IWUSR,
show_beep, store_beep, 9);
static SENSOR_DEVICE_ATTR(in6_beep, S_IRUGO | S_IWUSR,
show_beep, store_beep, 10);
static SENSOR_DEVICE_ATTR(in7_beep, S_IRUGO | S_IWUSR,
show_beep, store_beep, 16);
static SENSOR_DEVICE_ATTR(in8_beep, S_IRUGO | S_IWUSR,
show_beep, store_beep, 17);
static SENSOR_DEVICE_ATTR(fan1_beep, S_IRUGO | S_IWUSR,
show_beep, store_beep, 6);
static SENSOR_DEVICE_ATTR(fan2_beep, S_IRUGO | S_IWUSR,
show_beep, store_beep, 7);
static SENSOR_DEVICE_ATTR(fan3_beep, S_IRUGO | S_IWUSR,
show_beep, store_beep, 11);
static SENSOR_DEVICE_ATTR(temp1_beep, S_IRUGO | S_IWUSR,
show_beep, store_beep, 4);
static SENSOR_DEVICE_ATTR(temp2_beep, S_IRUGO | S_IWUSR,
show_beep, store_beep, 5);
static SENSOR_DEVICE_ATTR(temp3_beep, S_IRUGO | S_IWUSR,
show_beep, store_beep, 13);
static SENSOR_DEVICE_ATTR(beep_enable, S_IRUGO | S_IWUSR,
show_beep, store_beep, 15);
static ssize_t
show_fan_div(struct device *dev, struct device_attribute *devattr, char *buf)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = w83627hf_update_device(dev);
return sprintf(buf, "%ld\n",
(long) DIV_FROM_REG(data->fan_div[nr]));
}
/*
* Note: we save and restore the fan minimum here, because its value is
* determined in part by the fan divisor. This follows the principle of
* least surprise; the user doesn't expect the fan minimum to change just
* because the divisor changed.
*/
static ssize_t
store_fan_div(struct device *dev, struct device_attribute *devattr,
const char *buf, size_t count)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = dev_get_drvdata(dev);
unsigned long min;
u8 reg;
unsigned long val;
int err;
err = kstrtoul(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
/* Save fan_min */
min = FAN_FROM_REG(data->fan_min[nr],
DIV_FROM_REG(data->fan_div[nr]));
data->fan_div[nr] = DIV_TO_REG(val);
reg = (w83627hf_read_value(data, nr==2 ? W83781D_REG_PIN : W83781D_REG_VID_FANDIV)
& (nr==0 ? 0xcf : 0x3f))
| ((data->fan_div[nr] & 0x03) << (nr==0 ? 4 : 6));
w83627hf_write_value(data, nr==2 ? W83781D_REG_PIN : W83781D_REG_VID_FANDIV, reg);
reg = (w83627hf_read_value(data, W83781D_REG_VBAT)
& ~(1 << (5 + nr)))
| ((data->fan_div[nr] & 0x04) << (3 + nr));
w83627hf_write_value(data, W83781D_REG_VBAT, reg);
/* Restore fan_min */
data->fan_min[nr] = FAN_TO_REG(min, DIV_FROM_REG(data->fan_div[nr]));
w83627hf_write_value(data, W83627HF_REG_FAN_MIN(nr), data->fan_min[nr]);
mutex_unlock(&data->update_lock);
return count;
}
static SENSOR_DEVICE_ATTR(fan1_div, S_IRUGO|S_IWUSR,
show_fan_div, store_fan_div, 0);
static SENSOR_DEVICE_ATTR(fan2_div, S_IRUGO|S_IWUSR,
show_fan_div, store_fan_div, 1);
static SENSOR_DEVICE_ATTR(fan3_div, S_IRUGO|S_IWUSR,
show_fan_div, store_fan_div, 2);
static ssize_t
show_pwm(struct device *dev, struct device_attribute *devattr, char *buf)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = w83627hf_update_device(dev);
return sprintf(buf, "%ld\n", (long) data->pwm[nr]);
}
static ssize_t
store_pwm(struct device *dev, struct device_attribute *devattr,
const char *buf, size_t count)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = dev_get_drvdata(dev);
unsigned long val;
int err;
err = kstrtoul(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
if (data->type == w83627thf) {
/* bits 0-3 are reserved in 627THF */
data->pwm[nr] = PWM_TO_REG(val) & 0xf0;
w83627hf_write_value(data,
W836X7HF_REG_PWM(data->type, nr),
data->pwm[nr] |
(w83627hf_read_value(data,
W836X7HF_REG_PWM(data->type, nr)) & 0x0f));
} else {
data->pwm[nr] = PWM_TO_REG(val);
w83627hf_write_value(data,
W836X7HF_REG_PWM(data->type, nr),
data->pwm[nr]);
}
mutex_unlock(&data->update_lock);
return count;
}
static SENSOR_DEVICE_ATTR(pwm1, S_IRUGO|S_IWUSR, show_pwm, store_pwm, 0);
static SENSOR_DEVICE_ATTR(pwm2, S_IRUGO|S_IWUSR, show_pwm, store_pwm, 1);
static SENSOR_DEVICE_ATTR(pwm3, S_IRUGO|S_IWUSR, show_pwm, store_pwm, 2);
static ssize_t
show_pwm_enable(struct device *dev, struct device_attribute *devattr, char *buf)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = w83627hf_update_device(dev);
return sprintf(buf, "%d\n", data->pwm_enable[nr]);
}
static ssize_t
store_pwm_enable(struct device *dev, struct device_attribute *devattr,
const char *buf, size_t count)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = dev_get_drvdata(dev);
u8 reg;
unsigned long val;
int err;
err = kstrtoul(buf, 10, &val);
if (err)
return err;
if (!val || val > 3) /* modes 1, 2 and 3 are supported */
return -EINVAL;
mutex_lock(&data->update_lock);
data->pwm_enable[nr] = val;
reg = w83627hf_read_value(data, W83627THF_REG_PWM_ENABLE[nr]);
reg &= ~(0x03 << W83627THF_PWM_ENABLE_SHIFT[nr]);
reg |= (val - 1) << W83627THF_PWM_ENABLE_SHIFT[nr];
w83627hf_write_value(data, W83627THF_REG_PWM_ENABLE[nr], reg);
mutex_unlock(&data->update_lock);
return count;
}
static SENSOR_DEVICE_ATTR(pwm1_enable, S_IRUGO|S_IWUSR, show_pwm_enable,
store_pwm_enable, 0);
static SENSOR_DEVICE_ATTR(pwm2_enable, S_IRUGO|S_IWUSR, show_pwm_enable,
store_pwm_enable, 1);
static SENSOR_DEVICE_ATTR(pwm3_enable, S_IRUGO|S_IWUSR, show_pwm_enable,
store_pwm_enable, 2);
static ssize_t
show_pwm_freq(struct device *dev, struct device_attribute *devattr, char *buf)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = w83627hf_update_device(dev);
if (data->type == w83627hf)
return sprintf(buf, "%ld\n",
pwm_freq_from_reg_627hf(data->pwm_freq[nr]));
else
return sprintf(buf, "%ld\n",
pwm_freq_from_reg(data->pwm_freq[nr]));
}
static ssize_t
store_pwm_freq(struct device *dev, struct device_attribute *devattr,
const char *buf, size_t count)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = dev_get_drvdata(dev);
static const u8 mask[]={0xF8, 0x8F};
unsigned long val;
int err;
err = kstrtoul(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
if (data->type == w83627hf) {
data->pwm_freq[nr] = pwm_freq_to_reg_627hf(val);
w83627hf_write_value(data, W83627HF_REG_PWM_FREQ,
(data->pwm_freq[nr] << (nr*4)) |
(w83627hf_read_value(data,
W83627HF_REG_PWM_FREQ) & mask[nr]));
} else {
data->pwm_freq[nr] = pwm_freq_to_reg(val);
w83627hf_write_value(data, W83637HF_REG_PWM_FREQ[nr],
data->pwm_freq[nr]);
}
mutex_unlock(&data->update_lock);
return count;
}
static SENSOR_DEVICE_ATTR(pwm1_freq, S_IRUGO|S_IWUSR,
show_pwm_freq, store_pwm_freq, 0);
static SENSOR_DEVICE_ATTR(pwm2_freq, S_IRUGO|S_IWUSR,
show_pwm_freq, store_pwm_freq, 1);
static SENSOR_DEVICE_ATTR(pwm3_freq, S_IRUGO|S_IWUSR,
show_pwm_freq, store_pwm_freq, 2);
static ssize_t
show_temp_type(struct device *dev, struct device_attribute *devattr,
char *buf)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = w83627hf_update_device(dev);
return sprintf(buf, "%ld\n", (long) data->sens[nr]);
}
static ssize_t
store_temp_type(struct device *dev, struct device_attribute *devattr,
const char *buf, size_t count)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = dev_get_drvdata(dev);
unsigned long val;
u32 tmp;
int err;
err = kstrtoul(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
switch (val) {
case 1: /* PII/Celeron diode */
tmp = w83627hf_read_value(data, W83781D_REG_SCFG1);
w83627hf_write_value(data, W83781D_REG_SCFG1,
tmp | BIT_SCFG1[nr]);
tmp = w83627hf_read_value(data, W83781D_REG_SCFG2);
w83627hf_write_value(data, W83781D_REG_SCFG2,
tmp | BIT_SCFG2[nr]);
data->sens[nr] = val;
break;
case 2: /* 3904 */
tmp = w83627hf_read_value(data, W83781D_REG_SCFG1);
w83627hf_write_value(data, W83781D_REG_SCFG1,
tmp | BIT_SCFG1[nr]);
tmp = w83627hf_read_value(data, W83781D_REG_SCFG2);
w83627hf_write_value(data, W83781D_REG_SCFG2,
tmp & ~BIT_SCFG2[nr]);
data->sens[nr] = val;
break;
case W83781D_DEFAULT_BETA:
dev_warn(dev, "Sensor type %d is deprecated, please use 4 "
"instead\n", W83781D_DEFAULT_BETA);
/* fall through */
case 4: /* thermistor */
tmp = w83627hf_read_value(data, W83781D_REG_SCFG1);
w83627hf_write_value(data, W83781D_REG_SCFG1,
tmp & ~BIT_SCFG1[nr]);
data->sens[nr] = val;
break;
default:
dev_err(dev,
"Invalid sensor type %ld; must be 1, 2, or 4\n",
(long) val);
break;
}
mutex_unlock(&data->update_lock);
return count;
}
#define sysfs_temp_type(offset) \
static SENSOR_DEVICE_ATTR(temp##offset##_type, S_IRUGO | S_IWUSR, \
show_temp_type, store_temp_type, offset - 1);
sysfs_temp_type(1);
sysfs_temp_type(2);
sysfs_temp_type(3);
static ssize_t
show_name(struct device *dev, struct device_attribute *devattr, char *buf)
{
struct w83627hf_data *data = dev_get_drvdata(dev);
return sprintf(buf, "%s\n", data->name);
}
static DEVICE_ATTR(name, S_IRUGO, show_name, NULL);
static int __init w83627hf_find(int sioaddr, unsigned short *addr,
struct w83627hf_sio_data *sio_data)
{
int err = -ENODEV;
u16 val;
static __initconst char *const names[] = {
"W83627HF",
"W83627THF",
"W83697HF",
"W83637HF",
"W83687THF",
};
sio_data->sioaddr = sioaddr;
superio_enter(sio_data);
val = force_id ? force_id : superio_inb(sio_data, DEVID);
switch (val) {
case W627_DEVID:
sio_data->type = w83627hf;
break;
case W627THF_DEVID:
sio_data->type = w83627thf;
break;
case W697_DEVID:
sio_data->type = w83697hf;
break;
case W637_DEVID:
sio_data->type = w83637hf;
break;
case W687THF_DEVID:
sio_data->type = w83687thf;
break;
case 0xff: /* No device at all */
goto exit;
default:
pr_debug(DRVNAME ": Unsupported chip (DEVID=0x%02x)\n", val);
goto exit;
}
superio_select(sio_data, W83627HF_LD_HWM);
val = (superio_inb(sio_data, WINB_BASE_REG) << 8) |
superio_inb(sio_data, WINB_BASE_REG + 1);
*addr = val & WINB_ALIGNMENT;
if (*addr == 0) {
pr_warn("Base address not set, skipping\n");
goto exit;
}
val = superio_inb(sio_data, WINB_ACT_REG);
if (!(val & 0x01)) {
pr_warn("Enabling HWM logical device\n");
superio_outb(sio_data, WINB_ACT_REG, val | 0x01);
}
err = 0;
pr_info(DRVNAME ": Found %s chip at %#x\n",
names[sio_data->type], *addr);
exit:
superio_exit(sio_data);
return err;
}
#define VIN_UNIT_ATTRS(_X_) \
&sensor_dev_attr_in##_X_##_input.dev_attr.attr, \
&sensor_dev_attr_in##_X_##_min.dev_attr.attr, \
&sensor_dev_attr_in##_X_##_max.dev_attr.attr, \
&sensor_dev_attr_in##_X_##_alarm.dev_attr.attr, \
&sensor_dev_attr_in##_X_##_beep.dev_attr.attr
#define FAN_UNIT_ATTRS(_X_) \
&sensor_dev_attr_fan##_X_##_input.dev_attr.attr, \
&sensor_dev_attr_fan##_X_##_min.dev_attr.attr, \
&sensor_dev_attr_fan##_X_##_div.dev_attr.attr, \
&sensor_dev_attr_fan##_X_##_alarm.dev_attr.attr, \
&sensor_dev_attr_fan##_X_##_beep.dev_attr.attr
#define TEMP_UNIT_ATTRS(_X_) \
&sensor_dev_attr_temp##_X_##_input.dev_attr.attr, \
&sensor_dev_attr_temp##_X_##_max.dev_attr.attr, \
&sensor_dev_attr_temp##_X_##_max_hyst.dev_attr.attr, \
&sensor_dev_attr_temp##_X_##_type.dev_attr.attr, \
&sensor_dev_attr_temp##_X_##_alarm.dev_attr.attr, \
&sensor_dev_attr_temp##_X_##_beep.dev_attr.attr
static struct attribute *w83627hf_attributes[] = {
&dev_attr_in0_input.attr,
&dev_attr_in0_min.attr,
&dev_attr_in0_max.attr,
&sensor_dev_attr_in0_alarm.dev_attr.attr,
&sensor_dev_attr_in0_beep.dev_attr.attr,
VIN_UNIT_ATTRS(2),
VIN_UNIT_ATTRS(3),
VIN_UNIT_ATTRS(4),
VIN_UNIT_ATTRS(7),
VIN_UNIT_ATTRS(8),
FAN_UNIT_ATTRS(1),
FAN_UNIT_ATTRS(2),
TEMP_UNIT_ATTRS(1),
TEMP_UNIT_ATTRS(2),
&dev_attr_alarms.attr,
&sensor_dev_attr_beep_enable.dev_attr.attr,
&dev_attr_beep_mask.attr,
&sensor_dev_attr_pwm1.dev_attr.attr,
&sensor_dev_attr_pwm2.dev_attr.attr,
&dev_attr_name.attr,
NULL
};
static const struct attribute_group w83627hf_group = {
.attrs = w83627hf_attributes,
};
static struct attribute *w83627hf_attributes_opt[] = {
VIN_UNIT_ATTRS(1),
VIN_UNIT_ATTRS(5),
VIN_UNIT_ATTRS(6),
FAN_UNIT_ATTRS(3),
TEMP_UNIT_ATTRS(3),
&sensor_dev_attr_pwm3.dev_attr.attr,
&sensor_dev_attr_pwm1_freq.dev_attr.attr,
&sensor_dev_attr_pwm2_freq.dev_attr.attr,
&sensor_dev_attr_pwm3_freq.dev_attr.attr,
&sensor_dev_attr_pwm1_enable.dev_attr.attr,
&sensor_dev_attr_pwm2_enable.dev_attr.attr,
&sensor_dev_attr_pwm3_enable.dev_attr.attr,
NULL
};
static const struct attribute_group w83627hf_group_opt = {
.attrs = w83627hf_attributes_opt,
};
static int w83627hf_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct w83627hf_sio_data *sio_data = dev->platform_data;
struct w83627hf_data *data;
struct resource *res;
int err, i;
static const char *names[] = {
"w83627hf",
"w83627thf",
"w83697hf",
"w83637hf",
"w83687thf",
};
res = platform_get_resource(pdev, IORESOURCE_IO, 0);
if (!devm_request_region(dev, res->start, WINB_REGION_SIZE, DRVNAME)) {
dev_err(dev, "Failed to request region 0x%lx-0x%lx\n",
(unsigned long)res->start,
(unsigned long)(res->start + WINB_REGION_SIZE - 1));
return -EBUSY;
}
data = devm_kzalloc(dev, sizeof(struct w83627hf_data), GFP_KERNEL);
if (!data)
return -ENOMEM;
data->addr = res->start;
data->type = sio_data->type;
data->name = names[sio_data->type];
mutex_init(&data->lock);
mutex_init(&data->update_lock);
platform_set_drvdata(pdev, data);
/* Initialize the chip */
w83627hf_init_device(pdev);
/* A few vars need to be filled upon startup */
for (i = 0; i <= 2; i++)
data->fan_min[i] = w83627hf_read_value(
data, W83627HF_REG_FAN_MIN(i));
w83627hf_update_fan_div(data);
/* Register common device attributes */
err = sysfs_create_group(&dev->kobj, &w83627hf_group);
if (err)
return err;
/* Register chip-specific device attributes */
if (data->type == w83627hf || data->type == w83697hf)
if ((err = device_create_file(dev,
&sensor_dev_attr_in5_input.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_in5_min.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_in5_max.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_in5_alarm.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_in5_beep.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_in6_input.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_in6_min.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_in6_max.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_in6_alarm.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_in6_beep.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_pwm1_freq.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_pwm2_freq.dev_attr)))
goto error;
if (data->type != w83697hf)
if ((err = device_create_file(dev,
&sensor_dev_attr_in1_input.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_in1_min.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_in1_max.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_in1_alarm.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_in1_beep.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_fan3_input.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_fan3_min.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_fan3_div.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_fan3_alarm.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_fan3_beep.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_temp3_input.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_temp3_max.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_temp3_max_hyst.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_temp3_alarm.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_temp3_beep.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_temp3_type.dev_attr)))
goto error;
if (data->type != w83697hf && data->vid != 0xff) {
/* Convert VID to voltage based on VRM */
data->vrm = vid_which_vrm();
if ((err = device_create_file(dev, &dev_attr_cpu0_vid))
|| (err = device_create_file(dev, &dev_attr_vrm)))
goto error;
}
if (data->type == w83627thf || data->type == w83637hf
|| data->type == w83687thf) {
err = device_create_file(dev, &sensor_dev_attr_pwm3.dev_attr);
if (err)
goto error;
}
if (data->type == w83637hf || data->type == w83687thf)
if ((err = device_create_file(dev,
&sensor_dev_attr_pwm1_freq.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_pwm2_freq.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_pwm3_freq.dev_attr)))
goto error;
if (data->type != w83627hf)
if ((err = device_create_file(dev,
&sensor_dev_attr_pwm1_enable.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_pwm2_enable.dev_attr)))
goto error;
if (data->type == w83627thf || data->type == w83637hf
|| data->type == w83687thf) {
err = device_create_file(dev,
&sensor_dev_attr_pwm3_enable.dev_attr);
if (err)
goto error;
}
data->hwmon_dev = hwmon_device_register(dev);
if (IS_ERR(data->hwmon_dev)) {
err = PTR_ERR(data->hwmon_dev);
goto error;
}
return 0;
error:
sysfs_remove_group(&dev->kobj, &w83627hf_group);
sysfs_remove_group(&dev->kobj, &w83627hf_group_opt);
return err;
}
static int w83627hf_remove(struct platform_device *pdev)
{
struct w83627hf_data *data = platform_get_drvdata(pdev);
hwmon_device_unregister(data->hwmon_dev);
sysfs_remove_group(&pdev->dev.kobj, &w83627hf_group);
sysfs_remove_group(&pdev->dev.kobj, &w83627hf_group_opt);
return 0;
}
/* Registers 0x50-0x5f are banked */
static inline void w83627hf_set_bank(struct w83627hf_data *data, u16 reg)
{
if ((reg & 0x00f0) == 0x50) {
outb_p(W83781D_REG_BANK, data->addr + W83781D_ADDR_REG_OFFSET);
outb_p(reg >> 8, data->addr + W83781D_DATA_REG_OFFSET);
}
}
/* Not strictly necessary, but play it safe for now */
static inline void w83627hf_reset_bank(struct w83627hf_data *data, u16 reg)
{
if (reg & 0xff00) {
outb_p(W83781D_REG_BANK, data->addr + W83781D_ADDR_REG_OFFSET);
outb_p(0, data->addr + W83781D_DATA_REG_OFFSET);
}
}
static int w83627hf_read_value(struct w83627hf_data *data, u16 reg)
{
int res, word_sized;
mutex_lock(&data->lock);
word_sized = (((reg & 0xff00) == 0x100)
|| ((reg & 0xff00) == 0x200))
&& (((reg & 0x00ff) == 0x50)
|| ((reg & 0x00ff) == 0x53)
|| ((reg & 0x00ff) == 0x55));
w83627hf_set_bank(data, reg);
outb_p(reg & 0xff, data->addr + W83781D_ADDR_REG_OFFSET);
res = inb_p(data->addr + W83781D_DATA_REG_OFFSET);
if (word_sized) {
outb_p((reg & 0xff) + 1,
data->addr + W83781D_ADDR_REG_OFFSET);
res =
(res << 8) + inb_p(data->addr +
W83781D_DATA_REG_OFFSET);
}
w83627hf_reset_bank(data, reg);
mutex_unlock(&data->lock);
return res;
}
static int w83627thf_read_gpio5(struct platform_device *pdev)
{
struct w83627hf_sio_data *sio_data = pdev->dev.platform_data;
int res = 0xff, sel;
superio_enter(sio_data);
superio_select(sio_data, W83627HF_LD_GPIO5);
/* Make sure these GPIO pins are enabled */
if (!(superio_inb(sio_data, W83627THF_GPIO5_EN) & (1<<3))) {
dev_dbg(&pdev->dev, "GPIO5 disabled, no VID function\n");
goto exit;
}
/*
* Make sure the pins are configured for input
* There must be at least five (VRM 9), and possibly 6 (VRM 10)
*/
sel = superio_inb(sio_data, W83627THF_GPIO5_IOSR) & 0x3f;
if ((sel & 0x1f) != 0x1f) {
dev_dbg(&pdev->dev, "GPIO5 not configured for VID "
"function\n");
goto exit;
}
dev_info(&pdev->dev, "Reading VID from GPIO5\n");
res = superio_inb(sio_data, W83627THF_GPIO5_DR) & sel;
exit:
superio_exit(sio_data);
return res;
}
static int w83687thf_read_vid(struct platform_device *pdev)
{
struct w83627hf_sio_data *sio_data = pdev->dev.platform_data;
int res = 0xff;
superio_enter(sio_data);
superio_select(sio_data, W83627HF_LD_HWM);
/* Make sure these GPIO pins are enabled */
if (!(superio_inb(sio_data, W83687THF_VID_EN) & (1 << 2))) {
dev_dbg(&pdev->dev, "VID disabled, no VID function\n");
goto exit;
}
/* Make sure the pins are configured for input */
if (!(superio_inb(sio_data, W83687THF_VID_CFG) & (1 << 4))) {
dev_dbg(&pdev->dev, "VID configured as output, "
"no VID function\n");
goto exit;
}
res = superio_inb(sio_data, W83687THF_VID_DATA) & 0x3f;
exit:
superio_exit(sio_data);
return res;
}
static int w83627hf_write_value(struct w83627hf_data *data, u16 reg, u16 value)
{
int word_sized;
mutex_lock(&data->lock);
word_sized = (((reg & 0xff00) == 0x100)
|| ((reg & 0xff00) == 0x200))
&& (((reg & 0x00ff) == 0x53)
|| ((reg & 0x00ff) == 0x55));
w83627hf_set_bank(data, reg);
outb_p(reg & 0xff, data->addr + W83781D_ADDR_REG_OFFSET);
if (word_sized) {
outb_p(value >> 8,
data->addr + W83781D_DATA_REG_OFFSET);
outb_p((reg & 0xff) + 1,
data->addr + W83781D_ADDR_REG_OFFSET);
}
outb_p(value & 0xff,
data->addr + W83781D_DATA_REG_OFFSET);
w83627hf_reset_bank(data, reg);
mutex_unlock(&data->lock);
return 0;
}
static void w83627hf_init_device(struct platform_device *pdev)
{
struct w83627hf_data *data = platform_get_drvdata(pdev);
int i;
enum chips type = data->type;
u8 tmp;
/* Minimize conflicts with other winbond i2c-only clients... */
/* disable i2c subclients... how to disable main i2c client?? */
/* force i2c address to relatively uncommon address */
if (type == w83627hf) {
w83627hf_write_value(data, W83781D_REG_I2C_SUBADDR, 0x89);
w83627hf_write_value(data, W83781D_REG_I2C_ADDR, force_i2c);
}
/* Read VID only once */
if (type == w83627hf || type == w83637hf) {
int lo = w83627hf_read_value(data, W83781D_REG_VID_FANDIV);
int hi = w83627hf_read_value(data, W83781D_REG_CHIPID);
data->vid = (lo & 0x0f) | ((hi & 0x01) << 4);
} else if (type == w83627thf) {
data->vid = w83627thf_read_gpio5(pdev);
} else if (type == w83687thf) {
data->vid = w83687thf_read_vid(pdev);
}
/* Read VRM & OVT Config only once */
if (type == w83627thf || type == w83637hf || type == w83687thf) {
data->vrm_ovt =
w83627hf_read_value(data, W83627THF_REG_VRM_OVT_CFG);
}
tmp = w83627hf_read_value(data, W83781D_REG_SCFG1);
for (i = 1; i <= 3; i++) {
if (!(tmp & BIT_SCFG1[i - 1])) {
data->sens[i - 1] = 4;
} else {
if (w83627hf_read_value
(data,
W83781D_REG_SCFG2) & BIT_SCFG2[i - 1])
data->sens[i - 1] = 1;
else
data->sens[i - 1] = 2;
}
if ((type == w83697hf) && (i == 2))
break;
}
if(init) {
/* Enable temp2 */
tmp = w83627hf_read_value(data, W83627HF_REG_TEMP2_CONFIG);
if (tmp & 0x01) {
dev_warn(&pdev->dev, "Enabling temp2, readings "
"might not make sense\n");
w83627hf_write_value(data, W83627HF_REG_TEMP2_CONFIG,
tmp & 0xfe);
}
/* Enable temp3 */
if (type != w83697hf) {
tmp = w83627hf_read_value(data,
W83627HF_REG_TEMP3_CONFIG);
if (tmp & 0x01) {
dev_warn(&pdev->dev, "Enabling temp3, "
"readings might not make sense\n");
w83627hf_write_value(data,
W83627HF_REG_TEMP3_CONFIG, tmp & 0xfe);
}
}
}
/* Start monitoring */
w83627hf_write_value(data, W83781D_REG_CONFIG,
(w83627hf_read_value(data,
W83781D_REG_CONFIG) & 0xf7)
| 0x01);
/* Enable VBAT monitoring if needed */
tmp = w83627hf_read_value(data, W83781D_REG_VBAT);
if (!(tmp & 0x01))
w83627hf_write_value(data, W83781D_REG_VBAT, tmp | 0x01);
}
static void w83627hf_update_fan_div(struct w83627hf_data *data)
{
int reg;
reg = w83627hf_read_value(data, W83781D_REG_VID_FANDIV);
data->fan_div[0] = (reg >> 4) & 0x03;
data->fan_div[1] = (reg >> 6) & 0x03;
if (data->type != w83697hf) {
data->fan_div[2] = (w83627hf_read_value(data,
W83781D_REG_PIN) >> 6) & 0x03;
}
reg = w83627hf_read_value(data, W83781D_REG_VBAT);
data->fan_div[0] |= (reg >> 3) & 0x04;
data->fan_div[1] |= (reg >> 4) & 0x04;
if (data->type != w83697hf)
data->fan_div[2] |= (reg >> 5) & 0x04;
}
static struct w83627hf_data *w83627hf_update_device(struct device *dev)
{
struct w83627hf_data *data = dev_get_drvdata(dev);
int i, num_temps = (data->type == w83697hf) ? 2 : 3;
int num_pwms = (data->type == w83697hf) ? 2 : 3;
mutex_lock(&data->update_lock);
if (time_after(jiffies, data->last_updated + HZ + HZ / 2)
|| !data->valid) {
for (i = 0; i <= 8; i++) {
/* skip missing sensors */
if (((data->type == w83697hf) && (i == 1)) ||
((data->type != w83627hf && data->type != w83697hf)
&& (i == 5 || i == 6)))
continue;
data->in[i] =
w83627hf_read_value(data, W83781D_REG_IN(i));
data->in_min[i] =
w83627hf_read_value(data,
W83781D_REG_IN_MIN(i));
data->in_max[i] =
w83627hf_read_value(data,
W83781D_REG_IN_MAX(i));
}
for (i = 0; i <= 2; i++) {
data->fan[i] =
w83627hf_read_value(data, W83627HF_REG_FAN(i));
data->fan_min[i] =
w83627hf_read_value(data,
W83627HF_REG_FAN_MIN(i));
}
for (i = 0; i <= 2; i++) {
u8 tmp = w83627hf_read_value(data,
W836X7HF_REG_PWM(data->type, i));
/* bits 0-3 are reserved in 627THF */
if (data->type == w83627thf)
tmp &= 0xf0;
data->pwm[i] = tmp;
if (i == 1 &&
(data->type == w83627hf || data->type == w83697hf))
break;
}
if (data->type == w83627hf) {
u8 tmp = w83627hf_read_value(data,
W83627HF_REG_PWM_FREQ);
data->pwm_freq[0] = tmp & 0x07;
data->pwm_freq[1] = (tmp >> 4) & 0x07;
} else if (data->type != w83627thf) {
for (i = 1; i <= 3; i++) {
data->pwm_freq[i - 1] =
w83627hf_read_value(data,
W83637HF_REG_PWM_FREQ[i - 1]);
if (i == 2 && (data->type == w83697hf))
break;
}
}
if (data->type != w83627hf) {
for (i = 0; i < num_pwms; i++) {
u8 tmp = w83627hf_read_value(data,
W83627THF_REG_PWM_ENABLE[i]);
data->pwm_enable[i] =
((tmp >> W83627THF_PWM_ENABLE_SHIFT[i])
& 0x03) + 1;
}
}
for (i = 0; i < num_temps; i++) {
data->temp[i] = w83627hf_read_value(
data, w83627hf_reg_temp[i]);
data->temp_max[i] = w83627hf_read_value(
data, w83627hf_reg_temp_over[i]);
data->temp_max_hyst[i] = w83627hf_read_value(
data, w83627hf_reg_temp_hyst[i]);
}
w83627hf_update_fan_div(data);
data->alarms =
w83627hf_read_value(data, W83781D_REG_ALARM1) |
(w83627hf_read_value(data, W83781D_REG_ALARM2) << 8) |
(w83627hf_read_value(data, W83781D_REG_ALARM3) << 16);
i = w83627hf_read_value(data, W83781D_REG_BEEP_INTS2);
data->beep_mask = (i << 8) |
w83627hf_read_value(data, W83781D_REG_BEEP_INTS1) |
w83627hf_read_value(data, W83781D_REG_BEEP_INTS3) << 16;
data->last_updated = jiffies;
data->valid = 1;
}
mutex_unlock(&data->update_lock);
return data;
}
static int __init w83627hf_device_add(unsigned short address,
const struct w83627hf_sio_data *sio_data)
{
struct resource res = {
.start = address + WINB_REGION_OFFSET,
.end = address + WINB_REGION_OFFSET + WINB_REGION_SIZE - 1,
.name = DRVNAME,
.flags = IORESOURCE_IO,
};
int err;
err = acpi_check_resource_conflict(&res);
if (err)
goto exit;
pdev = platform_device_alloc(DRVNAME, address);
if (!pdev) {
err = -ENOMEM;
pr_err("Device allocation failed\n");
goto exit;
}
err = platform_device_add_resources(pdev, &res, 1);
if (err) {
pr_err("Device resource addition failed (%d)\n", err);
goto exit_device_put;
}
err = platform_device_add_data(pdev, sio_data,
sizeof(struct w83627hf_sio_data));
if (err) {
pr_err("Platform data allocation failed\n");
goto exit_device_put;
}
err = platform_device_add(pdev);
if (err) {
pr_err("Device addition failed (%d)\n", err);
goto exit_device_put;
}
return 0;
exit_device_put:
platform_device_put(pdev);
exit:
return err;
}
static int __init sensors_w83627hf_init(void)
{
int err;
unsigned short address;
struct w83627hf_sio_data sio_data;
if (w83627hf_find(0x2e, &address, &sio_data)
&& w83627hf_find(0x4e, &address, &sio_data))
return -ENODEV;
err = platform_driver_register(&w83627hf_driver);
if (err)
goto exit;
/* Sets global pdev as a side effect */
err = w83627hf_device_add(address, &sio_data);
if (err)
goto exit_driver;
return 0;
exit_driver:
platform_driver_unregister(&w83627hf_driver);
exit:
return err;
}
static void __exit sensors_w83627hf_exit(void)
{
platform_device_unregister(pdev);
platform_driver_unregister(&w83627hf_driver);
}
MODULE_AUTHOR("Frodo Looijaard <frodol@dds.nl>, "
"Philip Edelbrock <phil@netroedge.com>, "
"and Mark Studebaker <mdsxyz123@yahoo.com>");
MODULE_DESCRIPTION("W83627HF driver");
MODULE_LICENSE("GPL");
module_init(sensors_w83627hf_init);
module_exit(sensors_w83627hf_exit);
| gpl-2.0 |
HridayHS/Lightning-Kernel | drivers/input/mouse/synaptics_i2c.c | 3237 | 17500 | /*
* Synaptics touchpad with I2C interface
*
* Copyright (C) 2009 Compulab, Ltd.
* Mike Rapoport <mike@compulab.co.il>
* Igor Grinberg <grinberg@compulab.co.il>
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of this archive for
* more details.
*/
#include <linux/module.h>
#include <linux/i2c.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <linux/input.h>
#include <linux/delay.h>
#include <linux/workqueue.h>
#include <linux/slab.h>
#include <linux/pm.h>
#define DRIVER_NAME "synaptics_i2c"
/* maximum product id is 15 characters */
#define PRODUCT_ID_LENGTH 15
#define REGISTER_LENGTH 8
/*
* after soft reset, we should wait for 1 ms
* before the device becomes operational
*/
#define SOFT_RESET_DELAY_MS 3
/* and after hard reset, we should wait for max 500ms */
#define HARD_RESET_DELAY_MS 500
/* Registers by SMBus address */
#define PAGE_SEL_REG 0xff
#define DEVICE_STATUS_REG 0x09
/* Registers by RMI address */
#define DEV_CONTROL_REG 0x0000
#define INTERRUPT_EN_REG 0x0001
#define ERR_STAT_REG 0x0002
#define INT_REQ_STAT_REG 0x0003
#define DEV_COMMAND_REG 0x0004
#define RMI_PROT_VER_REG 0x0200
#define MANUFACT_ID_REG 0x0201
#define PHYS_INT_VER_REG 0x0202
#define PROD_PROPERTY_REG 0x0203
#define INFO_QUERY_REG0 0x0204
#define INFO_QUERY_REG1 (INFO_QUERY_REG0 + 1)
#define INFO_QUERY_REG2 (INFO_QUERY_REG0 + 2)
#define INFO_QUERY_REG3 (INFO_QUERY_REG0 + 3)
#define PRODUCT_ID_REG0 0x0210
#define PRODUCT_ID_REG1 (PRODUCT_ID_REG0 + 1)
#define PRODUCT_ID_REG2 (PRODUCT_ID_REG0 + 2)
#define PRODUCT_ID_REG3 (PRODUCT_ID_REG0 + 3)
#define PRODUCT_ID_REG4 (PRODUCT_ID_REG0 + 4)
#define PRODUCT_ID_REG5 (PRODUCT_ID_REG0 + 5)
#define PRODUCT_ID_REG6 (PRODUCT_ID_REG0 + 6)
#define PRODUCT_ID_REG7 (PRODUCT_ID_REG0 + 7)
#define PRODUCT_ID_REG8 (PRODUCT_ID_REG0 + 8)
#define PRODUCT_ID_REG9 (PRODUCT_ID_REG0 + 9)
#define PRODUCT_ID_REG10 (PRODUCT_ID_REG0 + 10)
#define PRODUCT_ID_REG11 (PRODUCT_ID_REG0 + 11)
#define PRODUCT_ID_REG12 (PRODUCT_ID_REG0 + 12)
#define PRODUCT_ID_REG13 (PRODUCT_ID_REG0 + 13)
#define PRODUCT_ID_REG14 (PRODUCT_ID_REG0 + 14)
#define PRODUCT_ID_REG15 (PRODUCT_ID_REG0 + 15)
#define DATA_REG0 0x0400
#define ABS_PRESSURE_REG 0x0401
#define ABS_MSB_X_REG 0x0402
#define ABS_LSB_X_REG (ABS_MSB_X_REG + 1)
#define ABS_MSB_Y_REG 0x0404
#define ABS_LSB_Y_REG (ABS_MSB_Y_REG + 1)
#define REL_X_REG 0x0406
#define REL_Y_REG 0x0407
#define DEV_QUERY_REG0 0x1000
#define DEV_QUERY_REG1 (DEV_QUERY_REG0 + 1)
#define DEV_QUERY_REG2 (DEV_QUERY_REG0 + 2)
#define DEV_QUERY_REG3 (DEV_QUERY_REG0 + 3)
#define DEV_QUERY_REG4 (DEV_QUERY_REG0 + 4)
#define DEV_QUERY_REG5 (DEV_QUERY_REG0 + 5)
#define DEV_QUERY_REG6 (DEV_QUERY_REG0 + 6)
#define DEV_QUERY_REG7 (DEV_QUERY_REG0 + 7)
#define DEV_QUERY_REG8 (DEV_QUERY_REG0 + 8)
#define GENERAL_2D_CONTROL_REG 0x1041
#define SENSOR_SENSITIVITY_REG 0x1044
#define SENS_MAX_POS_MSB_REG 0x1046
#define SENS_MAX_POS_LSB_REG (SENS_MAX_POS_UPPER_REG + 1)
/* Register bits */
/* Device Control Register Bits */
#define REPORT_RATE_1ST_BIT 6
/* Interrupt Enable Register Bits (INTERRUPT_EN_REG) */
#define F10_ABS_INT_ENA 0
#define F10_REL_INT_ENA 1
#define F20_INT_ENA 2
/* Interrupt Request Register Bits (INT_REQ_STAT_REG | DEVICE_STATUS_REG) */
#define F10_ABS_INT_REQ 0
#define F10_REL_INT_REQ 1
#define F20_INT_REQ 2
/* Device Status Register Bits (DEVICE_STATUS_REG) */
#define STAT_CONFIGURED 6
#define STAT_ERROR 7
/* Device Command Register Bits (DEV_COMMAND_REG) */
#define RESET_COMMAND 0x01
#define REZERO_COMMAND 0x02
/* Data Register 0 Bits (DATA_REG0) */
#define GESTURE 3
/* Device Query Registers Bits */
/* DEV_QUERY_REG3 */
#define HAS_PALM_DETECT 1
#define HAS_MULTI_FING 2
#define HAS_SCROLLER 4
#define HAS_2D_SCROLL 5
/* General 2D Control Register Bits (GENERAL_2D_CONTROL_REG) */
#define NO_DECELERATION 1
#define REDUCE_REPORTING 3
#define NO_FILTER 5
/* Function Masks */
/* Device Control Register Masks (DEV_CONTROL_REG) */
#define REPORT_RATE_MSK 0xc0
#define SLEEP_MODE_MSK 0x07
/* Device Sleep Modes */
#define FULL_AWAKE 0x0
#define NORMAL_OP 0x1
#define LOW_PWR_OP 0x2
#define VERY_LOW_PWR_OP 0x3
#define SENS_SLEEP 0x4
#define SLEEP_MOD 0x5
#define DEEP_SLEEP 0x6
#define HIBERNATE 0x7
/* Interrupt Register Mask */
/* (INT_REQ_STAT_REG | DEVICE_STATUS_REG | INTERRUPT_EN_REG) */
#define INT_ENA_REQ_MSK 0x07
#define INT_ENA_ABS_MSK 0x01
#define INT_ENA_REL_MSK 0x02
#define INT_ENA_F20_MSK 0x04
/* Device Status Register Masks (DEVICE_STATUS_REG) */
#define CONFIGURED_MSK 0x40
#define ERROR_MSK 0x80
/* Data Register 0 Masks */
#define FINGER_WIDTH_MSK 0xf0
#define GESTURE_MSK 0x08
#define SENSOR_STATUS_MSK 0x07
/*
* MSB Position Register Masks
* ABS_MSB_X_REG | ABS_MSB_Y_REG | SENS_MAX_POS_MSB_REG |
* DEV_QUERY_REG3 | DEV_QUERY_REG5
*/
#define MSB_POSITION_MSK 0x1f
/* Device Query Registers Masks */
/* DEV_QUERY_REG2 */
#define NUM_EXTRA_POS_MSK 0x07
/* When in IRQ mode read the device every THREAD_IRQ_SLEEP_SECS */
#define THREAD_IRQ_SLEEP_SECS 2
#define THREAD_IRQ_SLEEP_MSECS (THREAD_IRQ_SLEEP_SECS * MSEC_PER_SEC)
/*
* When in Polling mode and no data received for NO_DATA_THRES msecs
* reduce the polling rate to NO_DATA_SLEEP_MSECS
*/
#define NO_DATA_THRES (MSEC_PER_SEC)
#define NO_DATA_SLEEP_MSECS (MSEC_PER_SEC / 4)
/* Control touchpad's No Deceleration option */
static bool no_decel = 1;
module_param(no_decel, bool, 0644);
MODULE_PARM_DESC(no_decel, "No Deceleration. Default = 1 (on)");
/* Control touchpad's Reduced Reporting option */
static bool reduce_report;
module_param(reduce_report, bool, 0644);
MODULE_PARM_DESC(reduce_report, "Reduced Reporting. Default = 0 (off)");
/* Control touchpad's No Filter option */
static bool no_filter;
module_param(no_filter, bool, 0644);
MODULE_PARM_DESC(no_filter, "No Filter. Default = 0 (off)");
/*
* touchpad Attention line is Active Low and Open Drain,
* therefore should be connected to pulled up line
* and the irq configuration should be set to Falling Edge Trigger
*/
/* Control IRQ / Polling option */
static bool polling_req;
module_param(polling_req, bool, 0444);
MODULE_PARM_DESC(polling_req, "Request Polling. Default = 0 (use irq)");
/* Control Polling Rate */
static int scan_rate = 80;
module_param(scan_rate, int, 0644);
MODULE_PARM_DESC(scan_rate, "Polling rate in times/sec. Default = 80");
/* The main device structure */
struct synaptics_i2c {
struct i2c_client *client;
struct input_dev *input;
struct delayed_work dwork;
spinlock_t lock;
int no_data_count;
int no_decel_param;
int reduce_report_param;
int no_filter_param;
int scan_rate_param;
int scan_ms;
};
static inline void set_scan_rate(struct synaptics_i2c *touch, int scan_rate)
{
touch->scan_ms = MSEC_PER_SEC / scan_rate;
touch->scan_rate_param = scan_rate;
}
/*
* Driver's initial design makes no race condition possible on i2c bus,
* so there is no need in any locking.
* Keep it in mind, while playing with the code.
*/
static s32 synaptics_i2c_reg_get(struct i2c_client *client, u16 reg)
{
int ret;
ret = i2c_smbus_write_byte_data(client, PAGE_SEL_REG, reg >> 8);
if (ret == 0)
ret = i2c_smbus_read_byte_data(client, reg & 0xff);
return ret;
}
static s32 synaptics_i2c_reg_set(struct i2c_client *client, u16 reg, u8 val)
{
int ret;
ret = i2c_smbus_write_byte_data(client, PAGE_SEL_REG, reg >> 8);
if (ret == 0)
ret = i2c_smbus_write_byte_data(client, reg & 0xff, val);
return ret;
}
static s32 synaptics_i2c_word_get(struct i2c_client *client, u16 reg)
{
int ret;
ret = i2c_smbus_write_byte_data(client, PAGE_SEL_REG, reg >> 8);
if (ret == 0)
ret = i2c_smbus_read_word_data(client, reg & 0xff);
return ret;
}
static int synaptics_i2c_config(struct i2c_client *client)
{
int ret, control;
u8 int_en;
/* set Report Rate to Device Highest (>=80) and Sleep to normal */
ret = synaptics_i2c_reg_set(client, DEV_CONTROL_REG, 0xc1);
if (ret)
return ret;
/* set Interrupt Disable to Func20 / Enable to Func10) */
int_en = (polling_req) ? 0 : INT_ENA_ABS_MSK | INT_ENA_REL_MSK;
ret = synaptics_i2c_reg_set(client, INTERRUPT_EN_REG, int_en);
if (ret)
return ret;
control = synaptics_i2c_reg_get(client, GENERAL_2D_CONTROL_REG);
/* No Deceleration */
control |= no_decel ? 1 << NO_DECELERATION : 0;
/* Reduced Reporting */
control |= reduce_report ? 1 << REDUCE_REPORTING : 0;
/* No Filter */
control |= no_filter ? 1 << NO_FILTER : 0;
ret = synaptics_i2c_reg_set(client, GENERAL_2D_CONTROL_REG, control);
if (ret)
return ret;
return 0;
}
static int synaptics_i2c_reset_config(struct i2c_client *client)
{
int ret;
/* Reset the Touchpad */
ret = synaptics_i2c_reg_set(client, DEV_COMMAND_REG, RESET_COMMAND);
if (ret) {
dev_err(&client->dev, "Unable to reset device\n");
} else {
msleep(SOFT_RESET_DELAY_MS);
ret = synaptics_i2c_config(client);
if (ret)
dev_err(&client->dev, "Unable to config device\n");
}
return ret;
}
static int synaptics_i2c_check_error(struct i2c_client *client)
{
int status, ret = 0;
status = i2c_smbus_read_byte_data(client, DEVICE_STATUS_REG) &
(CONFIGURED_MSK | ERROR_MSK);
if (status != CONFIGURED_MSK)
ret = synaptics_i2c_reset_config(client);
return ret;
}
static bool synaptics_i2c_get_input(struct synaptics_i2c *touch)
{
struct input_dev *input = touch->input;
int xy_delta, gesture;
s32 data;
s8 x_delta, y_delta;
/* Deal with spontanious resets and errors */
if (synaptics_i2c_check_error(touch->client))
return 0;
/* Get Gesture Bit */
data = synaptics_i2c_reg_get(touch->client, DATA_REG0);
gesture = (data >> GESTURE) & 0x1;
/*
* Get Relative axes. we have to get them in one shot,
* so we get 2 bytes starting from REL_X_REG.
*/
xy_delta = synaptics_i2c_word_get(touch->client, REL_X_REG) & 0xffff;
/* Separate X from Y */
x_delta = xy_delta & 0xff;
y_delta = (xy_delta >> REGISTER_LENGTH) & 0xff;
/* Report the button event */
input_report_key(input, BTN_LEFT, gesture);
/* Report the deltas */
input_report_rel(input, REL_X, x_delta);
input_report_rel(input, REL_Y, -y_delta);
input_sync(input);
return xy_delta || gesture;
}
static void synaptics_i2c_reschedule_work(struct synaptics_i2c *touch,
unsigned long delay)
{
unsigned long flags;
spin_lock_irqsave(&touch->lock, flags);
mod_delayed_work(system_wq, &touch->dwork, delay);
spin_unlock_irqrestore(&touch->lock, flags);
}
static irqreturn_t synaptics_i2c_irq(int irq, void *dev_id)
{
struct synaptics_i2c *touch = dev_id;
synaptics_i2c_reschedule_work(touch, 0);
return IRQ_HANDLED;
}
static void synaptics_i2c_check_params(struct synaptics_i2c *touch)
{
bool reset = false;
if (scan_rate != touch->scan_rate_param)
set_scan_rate(touch, scan_rate);
if (no_decel != touch->no_decel_param) {
touch->no_decel_param = no_decel;
reset = true;
}
if (no_filter != touch->no_filter_param) {
touch->no_filter_param = no_filter;
reset = true;
}
if (reduce_report != touch->reduce_report_param) {
touch->reduce_report_param = reduce_report;
reset = true;
}
if (reset)
synaptics_i2c_reset_config(touch->client);
}
/* Control the Device polling rate / Work Handler sleep time */
static unsigned long synaptics_i2c_adjust_delay(struct synaptics_i2c *touch,
bool have_data)
{
unsigned long delay, nodata_count_thres;
if (polling_req) {
delay = touch->scan_ms;
if (have_data) {
touch->no_data_count = 0;
} else {
nodata_count_thres = NO_DATA_THRES / touch->scan_ms;
if (touch->no_data_count < nodata_count_thres)
touch->no_data_count++;
else
delay = NO_DATA_SLEEP_MSECS;
}
return msecs_to_jiffies(delay);
} else {
delay = msecs_to_jiffies(THREAD_IRQ_SLEEP_MSECS);
return round_jiffies_relative(delay);
}
}
/* Work Handler */
static void synaptics_i2c_work_handler(struct work_struct *work)
{
bool have_data;
struct synaptics_i2c *touch =
container_of(work, struct synaptics_i2c, dwork.work);
unsigned long delay;
synaptics_i2c_check_params(touch);
have_data = synaptics_i2c_get_input(touch);
delay = synaptics_i2c_adjust_delay(touch, have_data);
/*
* While interrupt driven, there is no real need to poll the device.
* But touchpads are very sensitive, so there could be errors
* related to physical environment and the attention line isn't
* necessarily asserted. In such case we can lose the touchpad.
* We poll the device once in THREAD_IRQ_SLEEP_SECS and
* if error is detected, we try to reset and reconfigure the touchpad.
*/
synaptics_i2c_reschedule_work(touch, delay);
}
static int synaptics_i2c_open(struct input_dev *input)
{
struct synaptics_i2c *touch = input_get_drvdata(input);
int ret;
ret = synaptics_i2c_reset_config(touch->client);
if (ret)
return ret;
if (polling_req)
synaptics_i2c_reschedule_work(touch,
msecs_to_jiffies(NO_DATA_SLEEP_MSECS));
return 0;
}
static void synaptics_i2c_close(struct input_dev *input)
{
struct synaptics_i2c *touch = input_get_drvdata(input);
if (!polling_req)
synaptics_i2c_reg_set(touch->client, INTERRUPT_EN_REG, 0);
cancel_delayed_work_sync(&touch->dwork);
/* Save some power */
synaptics_i2c_reg_set(touch->client, DEV_CONTROL_REG, DEEP_SLEEP);
}
static void synaptics_i2c_set_input_params(struct synaptics_i2c *touch)
{
struct input_dev *input = touch->input;
input->name = touch->client->name;
input->phys = touch->client->adapter->name;
input->id.bustype = BUS_I2C;
input->id.version = synaptics_i2c_word_get(touch->client,
INFO_QUERY_REG0);
input->dev.parent = &touch->client->dev;
input->open = synaptics_i2c_open;
input->close = synaptics_i2c_close;
input_set_drvdata(input, touch);
/* Register the device as mouse */
__set_bit(EV_REL, input->evbit);
__set_bit(REL_X, input->relbit);
__set_bit(REL_Y, input->relbit);
/* Register device's buttons and keys */
__set_bit(EV_KEY, input->evbit);
__set_bit(BTN_LEFT, input->keybit);
}
static struct synaptics_i2c *synaptics_i2c_touch_create(struct i2c_client *client)
{
struct synaptics_i2c *touch;
touch = kzalloc(sizeof(struct synaptics_i2c), GFP_KERNEL);
if (!touch)
return NULL;
touch->client = client;
touch->no_decel_param = no_decel;
touch->scan_rate_param = scan_rate;
set_scan_rate(touch, scan_rate);
INIT_DELAYED_WORK(&touch->dwork, synaptics_i2c_work_handler);
spin_lock_init(&touch->lock);
return touch;
}
static int synaptics_i2c_probe(struct i2c_client *client,
const struct i2c_device_id *dev_id)
{
int ret;
struct synaptics_i2c *touch;
touch = synaptics_i2c_touch_create(client);
if (!touch)
return -ENOMEM;
ret = synaptics_i2c_reset_config(client);
if (ret)
goto err_mem_free;
if (client->irq < 1)
polling_req = true;
touch->input = input_allocate_device();
if (!touch->input) {
ret = -ENOMEM;
goto err_mem_free;
}
synaptics_i2c_set_input_params(touch);
if (!polling_req) {
dev_dbg(&touch->client->dev,
"Requesting IRQ: %d\n", touch->client->irq);
ret = request_irq(touch->client->irq, synaptics_i2c_irq,
IRQ_TYPE_EDGE_FALLING,
DRIVER_NAME, touch);
if (ret) {
dev_warn(&touch->client->dev,
"IRQ request failed: %d, "
"falling back to polling\n", ret);
polling_req = true;
synaptics_i2c_reg_set(touch->client,
INTERRUPT_EN_REG, 0);
}
}
if (polling_req)
dev_dbg(&touch->client->dev,
"Using polling at rate: %d times/sec\n", scan_rate);
/* Register the device in input subsystem */
ret = input_register_device(touch->input);
if (ret) {
dev_err(&client->dev,
"Input device register failed: %d\n", ret);
goto err_input_free;
}
i2c_set_clientdata(client, touch);
return 0;
err_input_free:
input_free_device(touch->input);
err_mem_free:
kfree(touch);
return ret;
}
static int synaptics_i2c_remove(struct i2c_client *client)
{
struct synaptics_i2c *touch = i2c_get_clientdata(client);
if (!polling_req)
free_irq(client->irq, touch);
input_unregister_device(touch->input);
kfree(touch);
return 0;
}
#ifdef CONFIG_PM_SLEEP
static int synaptics_i2c_suspend(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct synaptics_i2c *touch = i2c_get_clientdata(client);
cancel_delayed_work_sync(&touch->dwork);
/* Save some power */
synaptics_i2c_reg_set(touch->client, DEV_CONTROL_REG, DEEP_SLEEP);
return 0;
}
static int synaptics_i2c_resume(struct device *dev)
{
int ret;
struct i2c_client *client = to_i2c_client(dev);
struct synaptics_i2c *touch = i2c_get_clientdata(client);
ret = synaptics_i2c_reset_config(client);
if (ret)
return ret;
synaptics_i2c_reschedule_work(touch,
msecs_to_jiffies(NO_DATA_SLEEP_MSECS));
return 0;
}
#endif
static SIMPLE_DEV_PM_OPS(synaptics_i2c_pm, synaptics_i2c_suspend,
synaptics_i2c_resume);
static const struct i2c_device_id synaptics_i2c_id_table[] = {
{ "synaptics_i2c", 0 },
{ },
};
MODULE_DEVICE_TABLE(i2c, synaptics_i2c_id_table);
static struct i2c_driver synaptics_i2c_driver = {
.driver = {
.name = DRIVER_NAME,
.owner = THIS_MODULE,
.pm = &synaptics_i2c_pm,
},
.probe = synaptics_i2c_probe,
.remove = synaptics_i2c_remove,
.id_table = synaptics_i2c_id_table,
};
module_i2c_driver(synaptics_i2c_driver);
MODULE_DESCRIPTION("Synaptics I2C touchpad driver");
MODULE_AUTHOR("Mike Rapoport, Igor Grinberg, Compulab");
MODULE_LICENSE("GPL");
| gpl-2.0 |
dsexton702/sgs4g_gb_kernel | drivers/gpio/it8761e_gpio.c | 3493 | 4937 | /*
* it8761_gpio.c - GPIO interface for IT8761E Super I/O chip
*
* Author: Denis Turischev <denis@compulab.co.il>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License 2 as published
* by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/io.h>
#include <linux/errno.h>
#include <linux/ioport.h>
#include <linux/gpio.h>
#define SIO_CHIP_ID 0x8761
#define CHIP_ID_HIGH_BYTE 0x20
#define CHIP_ID_LOW_BYTE 0x21
static u8 ports[2] = { 0x2e, 0x4e };
static u8 port;
static DEFINE_SPINLOCK(sio_lock);
#define GPIO_NAME "it8761-gpio"
#define GPIO_BA_HIGH_BYTE 0x60
#define GPIO_BA_LOW_BYTE 0x61
#define GPIO_IOSIZE 4
#define GPIO1X_IO 0xf0
#define GPIO2X_IO 0xf1
static u16 gpio_ba;
static u8 read_reg(u8 addr, u8 port)
{
outb(addr, port);
return inb(port + 1);
}
static void write_reg(u8 data, u8 addr, u8 port)
{
outb(addr, port);
outb(data, port + 1);
}
static void enter_conf_mode(u8 port)
{
outb(0x87, port);
outb(0x61, port);
outb(0x55, port);
outb((port == 0x2e) ? 0x55 : 0xaa, port);
}
static void exit_conf_mode(u8 port)
{
outb(0x2, port);
outb(0x2, port + 1);
}
static void enter_gpio_mode(u8 port)
{
write_reg(0x2, 0x7, port);
}
static int it8761e_gpio_get(struct gpio_chip *gc, unsigned gpio_num)
{
u16 reg;
u8 bit;
bit = gpio_num % 8;
reg = (gpio_num >= 8) ? gpio_ba + 1 : gpio_ba;
return !!(inb(reg) & (1 << bit));
}
static int it8761e_gpio_direction_in(struct gpio_chip *gc, unsigned gpio_num)
{
u8 curr_dirs;
u8 io_reg, bit;
bit = gpio_num % 8;
io_reg = (gpio_num >= 8) ? GPIO2X_IO : GPIO1X_IO;
spin_lock(&sio_lock);
enter_conf_mode(port);
enter_gpio_mode(port);
curr_dirs = read_reg(io_reg, port);
if (curr_dirs & (1 << bit))
write_reg(curr_dirs & ~(1 << bit), io_reg, port);
exit_conf_mode(port);
spin_unlock(&sio_lock);
return 0;
}
static void it8761e_gpio_set(struct gpio_chip *gc,
unsigned gpio_num, int val)
{
u8 curr_vals, bit;
u16 reg;
bit = gpio_num % 8;
reg = (gpio_num >= 8) ? gpio_ba + 1 : gpio_ba;
spin_lock(&sio_lock);
curr_vals = inb(reg);
if (val)
outb(curr_vals | (1 << bit) , reg);
else
outb(curr_vals & ~(1 << bit), reg);
spin_unlock(&sio_lock);
}
static int it8761e_gpio_direction_out(struct gpio_chip *gc,
unsigned gpio_num, int val)
{
u8 curr_dirs, io_reg, bit;
bit = gpio_num % 8;
io_reg = (gpio_num >= 8) ? GPIO2X_IO : GPIO1X_IO;
it8761e_gpio_set(gc, gpio_num, val);
spin_lock(&sio_lock);
enter_conf_mode(port);
enter_gpio_mode(port);
curr_dirs = read_reg(io_reg, port);
if (!(curr_dirs & (1 << bit)))
write_reg(curr_dirs | (1 << bit), io_reg, port);
exit_conf_mode(port);
spin_unlock(&sio_lock);
return 0;
}
static struct gpio_chip it8761e_gpio_chip = {
.label = GPIO_NAME,
.owner = THIS_MODULE,
.get = it8761e_gpio_get,
.direction_input = it8761e_gpio_direction_in,
.set = it8761e_gpio_set,
.direction_output = it8761e_gpio_direction_out,
};
static int __init it8761e_gpio_init(void)
{
int i, id, err;
/* chip and port detection */
for (i = 0; i < ARRAY_SIZE(ports); i++) {
spin_lock(&sio_lock);
enter_conf_mode(ports[i]);
id = (read_reg(CHIP_ID_HIGH_BYTE, ports[i]) << 8) +
read_reg(CHIP_ID_LOW_BYTE, ports[i]);
exit_conf_mode(ports[i]);
spin_unlock(&sio_lock);
if (id == SIO_CHIP_ID) {
port = ports[i];
break;
}
}
if (!port)
return -ENODEV;
/* fetch GPIO base address */
enter_conf_mode(port);
enter_gpio_mode(port);
gpio_ba = (read_reg(GPIO_BA_HIGH_BYTE, port) << 8) +
read_reg(GPIO_BA_LOW_BYTE, port);
exit_conf_mode(port);
if (!request_region(gpio_ba, GPIO_IOSIZE, GPIO_NAME))
return -EBUSY;
it8761e_gpio_chip.base = -1;
it8761e_gpio_chip.ngpio = 16;
err = gpiochip_add(&it8761e_gpio_chip);
if (err < 0)
goto gpiochip_add_err;
return 0;
gpiochip_add_err:
release_region(gpio_ba, GPIO_IOSIZE);
gpio_ba = 0;
return err;
}
static void __exit it8761e_gpio_exit(void)
{
if (gpio_ba) {
int ret = gpiochip_remove(&it8761e_gpio_chip);
WARN(ret, "%s(): gpiochip_remove() failed, ret=%d\n",
__func__, ret);
release_region(gpio_ba, GPIO_IOSIZE);
gpio_ba = 0;
}
}
module_init(it8761e_gpio_init);
module_exit(it8761e_gpio_exit);
MODULE_AUTHOR("Denis Turischev <denis@compulab.co.il>");
MODULE_DESCRIPTION("GPIO interface for IT8761E Super I/O chip");
MODULE_LICENSE("GPL");
| gpl-2.0 |
smaeul/kernel_samsung_aries | tools/perf/builtin-bench.c | 4261 | 4952 | /*
*
* builtin-bench.c
*
* General benchmarking subsystem provided by perf
*
* Copyright (C) 2009, Hitoshi Mitake <mitake@dcl.info.waseda.ac.jp>
*
*/
/*
*
* Available subsystem list:
* sched ... scheduler and IPC mechanism
* mem ... memory access performance
*
*/
#include "perf.h"
#include "util/util.h"
#include "util/parse-options.h"
#include "builtin.h"
#include "bench/bench.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct bench_suite {
const char *name;
const char *summary;
int (*fn)(int, const char **, const char *);
};
\
/* sentinel: easy for help */
#define suite_all { "all", "test all suite (pseudo suite)", NULL }
static struct bench_suite sched_suites[] = {
{ "messaging",
"Benchmark for scheduler and IPC mechanisms",
bench_sched_messaging },
{ "pipe",
"Flood of communication over pipe() between two processes",
bench_sched_pipe },
suite_all,
{ NULL,
NULL,
NULL }
};
static struct bench_suite mem_suites[] = {
{ "memcpy",
"Simple memory copy in various ways",
bench_mem_memcpy },
suite_all,
{ NULL,
NULL,
NULL }
};
struct bench_subsys {
const char *name;
const char *summary;
struct bench_suite *suites;
};
static struct bench_subsys subsystems[] = {
{ "sched",
"scheduler and IPC mechanism",
sched_suites },
{ "mem",
"memory access performance",
mem_suites },
{ "all", /* sentinel: easy for help */
"test all subsystem (pseudo subsystem)",
NULL },
{ NULL,
NULL,
NULL }
};
static void dump_suites(int subsys_index)
{
int i;
printf("# List of available suites for %s...\n\n",
subsystems[subsys_index].name);
for (i = 0; subsystems[subsys_index].suites[i].name; i++)
printf("%14s: %s\n",
subsystems[subsys_index].suites[i].name,
subsystems[subsys_index].suites[i].summary);
printf("\n");
return;
}
static const char *bench_format_str;
int bench_format = BENCH_FORMAT_DEFAULT;
static const struct option bench_options[] = {
OPT_STRING('f', "format", &bench_format_str, "default",
"Specify format style"),
OPT_END()
};
static const char * const bench_usage[] = {
"perf bench [<common options>] <subsystem> <suite> [<options>]",
NULL
};
static void print_usage(void)
{
int i;
printf("Usage: \n");
for (i = 0; bench_usage[i]; i++)
printf("\t%s\n", bench_usage[i]);
printf("\n");
printf("# List of available subsystems...\n\n");
for (i = 0; subsystems[i].name; i++)
printf("%14s: %s\n",
subsystems[i].name, subsystems[i].summary);
printf("\n");
}
static int bench_str2int(const char *str)
{
if (!str)
return BENCH_FORMAT_DEFAULT;
if (!strcmp(str, BENCH_FORMAT_DEFAULT_STR))
return BENCH_FORMAT_DEFAULT;
else if (!strcmp(str, BENCH_FORMAT_SIMPLE_STR))
return BENCH_FORMAT_SIMPLE;
return BENCH_FORMAT_UNKNOWN;
}
static void all_suite(struct bench_subsys *subsys) /* FROM HERE */
{
int i;
const char *argv[2];
struct bench_suite *suites = subsys->suites;
argv[1] = NULL;
/*
* TODO:
* preparing preset parameters for
* embedded, ordinary PC, HPC, etc...
* will be helpful
*/
for (i = 0; suites[i].fn; i++) {
printf("# Running %s/%s benchmark...\n",
subsys->name,
suites[i].name);
argv[1] = suites[i].name;
suites[i].fn(1, argv, NULL);
printf("\n");
}
}
static void all_subsystem(void)
{
int i;
for (i = 0; subsystems[i].suites; i++)
all_suite(&subsystems[i]);
}
int cmd_bench(int argc, const char **argv, const char *prefix __used)
{
int i, j, status = 0;
if (argc < 2) {
/* No subsystem specified. */
print_usage();
goto end;
}
argc = parse_options(argc, argv, bench_options, bench_usage,
PARSE_OPT_STOP_AT_NON_OPTION);
bench_format = bench_str2int(bench_format_str);
if (bench_format == BENCH_FORMAT_UNKNOWN) {
printf("Unknown format descriptor:%s\n", bench_format_str);
goto end;
}
if (argc < 1) {
print_usage();
goto end;
}
if (!strcmp(argv[0], "all")) {
all_subsystem();
goto end;
}
for (i = 0; subsystems[i].name; i++) {
if (strcmp(subsystems[i].name, argv[0]))
continue;
if (argc < 2) {
/* No suite specified. */
dump_suites(i);
goto end;
}
if (!strcmp(argv[1], "all")) {
all_suite(&subsystems[i]);
goto end;
}
for (j = 0; subsystems[i].suites[j].name; j++) {
if (strcmp(subsystems[i].suites[j].name, argv[1]))
continue;
if (bench_format == BENCH_FORMAT_DEFAULT)
printf("# Running %s/%s benchmark...\n",
subsystems[i].name,
subsystems[i].suites[j].name);
status = subsystems[i].suites[j].fn(argc - 1,
argv + 1, prefix);
goto end;
}
if (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) {
dump_suites(i);
goto end;
}
printf("Unknown suite:%s for %s\n", argv[1], argv[0]);
status = 1;
goto end;
}
printf("Unknown subsystem:%s\n", argv[0]);
status = 1;
end:
return status;
}
| gpl-2.0 |
AOSPA-legacy/android_kernel_oppo_n1 | drivers/net/ethernet/smsc/smc91x.c | 4517 | 63678 | /*
* smc91x.c
* This is a driver for SMSC's 91C9x/91C1xx single-chip Ethernet devices.
*
* Copyright (C) 1996 by Erik Stahlman
* Copyright (C) 2001 Standard Microsystems Corporation
* Developed by Simple Network Magic Corporation
* Copyright (C) 2003 Monta Vista Software, Inc.
* Unified SMC91x driver by Nicolas Pitre
*
* 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
*
* Arguments:
* io = for the base address
* irq = for the IRQ
* nowait = 0 for normal wait states, 1 eliminates additional wait states
*
* original author:
* Erik Stahlman <erik@vt.edu>
*
* hardware multicast code:
* Peter Cammaert <pc@denkart.be>
*
* contributors:
* Daris A Nevil <dnevil@snmc.com>
* Nicolas Pitre <nico@fluxnic.net>
* Russell King <rmk@arm.linux.org.uk>
*
* History:
* 08/20/00 Arnaldo Melo fix kfree(skb) in smc_hardware_send_packet
* 12/15/00 Christian Jullien fix "Warning: kfree_skb on hard IRQ"
* 03/16/01 Daris A Nevil modified smc9194.c for use with LAN91C111
* 08/22/01 Scott Anderson merge changes from smc9194 to smc91111
* 08/21/01 Pramod B Bhardwaj added support for RevB of LAN91C111
* 12/20/01 Jeff Sutherland initial port to Xscale PXA with DMA support
* 04/07/03 Nicolas Pitre unified SMC91x driver, killed irq races,
* more bus abstraction, big cleanup, etc.
* 29/09/03 Russell King - add driver model support
* - ethtool support
* - convert to use generic MII interface
* - add link up/down notification
* - don't try to handle full negotiation in
* smc_phy_configure
* - clean up (and fix stack overrun) in PHY
* MII read/write functions
* 22/09/04 Nicolas Pitre big update (see commit log for details)
*/
static const char version[] =
"smc91x.c: v1.1, sep 22 2004 by Nicolas Pitre <nico@fluxnic.net>\n";
/* Debugging level */
#ifndef SMC_DEBUG
#define SMC_DEBUG 0
#endif
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/errno.h>
#include <linux/ioport.h>
#include <linux/crc32.h>
#include <linux/platform_device.h>
#include <linux/spinlock.h>
#include <linux/ethtool.h>
#include <linux/mii.h>
#include <linux/workqueue.h>
#include <linux/of.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <asm/io.h>
#include "smc91x.h"
#ifndef SMC_NOWAIT
# define SMC_NOWAIT 0
#endif
static int nowait = SMC_NOWAIT;
module_param(nowait, int, 0400);
MODULE_PARM_DESC(nowait, "set to 1 for no wait state");
/*
* Transmit timeout, default 5 seconds.
*/
static int watchdog = 1000;
module_param(watchdog, int, 0400);
MODULE_PARM_DESC(watchdog, "transmit timeout in milliseconds");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:smc91x");
/*
* The internal workings of the driver. If you are changing anything
* here with the SMC stuff, you should have the datasheet and know
* what you are doing.
*/
#define CARDNAME "smc91x"
/*
* Use power-down feature of the chip
*/
#define POWER_DOWN 1
/*
* Wait time for memory to be free. This probably shouldn't be
* tuned that much, as waiting for this means nothing else happens
* in the system
*/
#define MEMORY_WAIT_TIME 16
/*
* The maximum number of processing loops allowed for each call to the
* IRQ handler.
*/
#define MAX_IRQ_LOOPS 8
/*
* This selects whether TX packets are sent one by one to the SMC91x internal
* memory and throttled until transmission completes. This may prevent
* RX overruns a litle by keeping much of the memory free for RX packets
* but to the expense of reduced TX throughput and increased IRQ overhead.
* Note this is not a cure for a too slow data bus or too high IRQ latency.
*/
#define THROTTLE_TX_PKTS 0
/*
* The MII clock high/low times. 2x this number gives the MII clock period
* in microseconds. (was 50, but this gives 6.4ms for each MII transaction!)
*/
#define MII_DELAY 1
#if SMC_DEBUG > 0
#define DBG(n, args...) \
do { \
if (SMC_DEBUG >= (n)) \
printk(args); \
} while (0)
#define PRINTK(args...) printk(args)
#else
#define DBG(n, args...) do { } while(0)
#define PRINTK(args...) printk(KERN_DEBUG args)
#endif
#if SMC_DEBUG > 3
static void PRINT_PKT(u_char *buf, int length)
{
int i;
int remainder;
int lines;
lines = length / 16;
remainder = length % 16;
for (i = 0; i < lines ; i ++) {
int cur;
for (cur = 0; cur < 8; cur++) {
u_char a, b;
a = *buf++;
b = *buf++;
printk("%02x%02x ", a, b);
}
printk("\n");
}
for (i = 0; i < remainder/2 ; i++) {
u_char a, b;
a = *buf++;
b = *buf++;
printk("%02x%02x ", a, b);
}
printk("\n");
}
#else
#define PRINT_PKT(x...) do { } while(0)
#endif
/* this enables an interrupt in the interrupt mask register */
#define SMC_ENABLE_INT(lp, x) do { \
unsigned char mask; \
unsigned long smc_enable_flags; \
spin_lock_irqsave(&lp->lock, smc_enable_flags); \
mask = SMC_GET_INT_MASK(lp); \
mask |= (x); \
SMC_SET_INT_MASK(lp, mask); \
spin_unlock_irqrestore(&lp->lock, smc_enable_flags); \
} while (0)
/* this disables an interrupt from the interrupt mask register */
#define SMC_DISABLE_INT(lp, x) do { \
unsigned char mask; \
unsigned long smc_disable_flags; \
spin_lock_irqsave(&lp->lock, smc_disable_flags); \
mask = SMC_GET_INT_MASK(lp); \
mask &= ~(x); \
SMC_SET_INT_MASK(lp, mask); \
spin_unlock_irqrestore(&lp->lock, smc_disable_flags); \
} while (0)
/*
* Wait while MMU is busy. This is usually in the order of a few nanosecs
* if at all, but let's avoid deadlocking the system if the hardware
* decides to go south.
*/
#define SMC_WAIT_MMU_BUSY(lp) do { \
if (unlikely(SMC_GET_MMU_CMD(lp) & MC_BUSY)) { \
unsigned long timeout = jiffies + 2; \
while (SMC_GET_MMU_CMD(lp) & MC_BUSY) { \
if (time_after(jiffies, timeout)) { \
printk("%s: timeout %s line %d\n", \
dev->name, __FILE__, __LINE__); \
break; \
} \
cpu_relax(); \
} \
} \
} while (0)
/*
* this does a soft reset on the device
*/
static void smc_reset(struct net_device *dev)
{
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
unsigned int ctl, cfg;
struct sk_buff *pending_skb;
DBG(2, "%s: %s\n", dev->name, __func__);
/* Disable all interrupts, block TX tasklet */
spin_lock_irq(&lp->lock);
SMC_SELECT_BANK(lp, 2);
SMC_SET_INT_MASK(lp, 0);
pending_skb = lp->pending_tx_skb;
lp->pending_tx_skb = NULL;
spin_unlock_irq(&lp->lock);
/* free any pending tx skb */
if (pending_skb) {
dev_kfree_skb(pending_skb);
dev->stats.tx_errors++;
dev->stats.tx_aborted_errors++;
}
/*
* This resets the registers mostly to defaults, but doesn't
* affect EEPROM. That seems unnecessary
*/
SMC_SELECT_BANK(lp, 0);
SMC_SET_RCR(lp, RCR_SOFTRST);
/*
* Setup the Configuration Register
* This is necessary because the CONFIG_REG is not affected
* by a soft reset
*/
SMC_SELECT_BANK(lp, 1);
cfg = CONFIG_DEFAULT;
/*
* Setup for fast accesses if requested. If the card/system
* can't handle it then there will be no recovery except for
* a hard reset or power cycle
*/
if (lp->cfg.flags & SMC91X_NOWAIT)
cfg |= CONFIG_NO_WAIT;
/*
* Release from possible power-down state
* Configuration register is not affected by Soft Reset
*/
cfg |= CONFIG_EPH_POWER_EN;
SMC_SET_CONFIG(lp, cfg);
/* this should pause enough for the chip to be happy */
/*
* elaborate? What does the chip _need_? --jgarzik
*
* This seems to be undocumented, but something the original
* driver(s) have always done. Suspect undocumented timing
* info/determined empirically. --rmk
*/
udelay(1);
/* Disable transmit and receive functionality */
SMC_SELECT_BANK(lp, 0);
SMC_SET_RCR(lp, RCR_CLEAR);
SMC_SET_TCR(lp, TCR_CLEAR);
SMC_SELECT_BANK(lp, 1);
ctl = SMC_GET_CTL(lp) | CTL_LE_ENABLE;
/*
* Set the control register to automatically release successfully
* transmitted packets, to make the best use out of our limited
* memory
*/
if(!THROTTLE_TX_PKTS)
ctl |= CTL_AUTO_RELEASE;
else
ctl &= ~CTL_AUTO_RELEASE;
SMC_SET_CTL(lp, ctl);
/* Reset the MMU */
SMC_SELECT_BANK(lp, 2);
SMC_SET_MMU_CMD(lp, MC_RESET);
SMC_WAIT_MMU_BUSY(lp);
}
/*
* Enable Interrupts, Receive, and Transmit
*/
static void smc_enable(struct net_device *dev)
{
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
int mask;
DBG(2, "%s: %s\n", dev->name, __func__);
/* see the header file for options in TCR/RCR DEFAULT */
SMC_SELECT_BANK(lp, 0);
SMC_SET_TCR(lp, lp->tcr_cur_mode);
SMC_SET_RCR(lp, lp->rcr_cur_mode);
SMC_SELECT_BANK(lp, 1);
SMC_SET_MAC_ADDR(lp, dev->dev_addr);
/* now, enable interrupts */
mask = IM_EPH_INT|IM_RX_OVRN_INT|IM_RCV_INT;
if (lp->version >= (CHIP_91100 << 4))
mask |= IM_MDINT;
SMC_SELECT_BANK(lp, 2);
SMC_SET_INT_MASK(lp, mask);
/*
* From this point the register bank must _NOT_ be switched away
* to something else than bank 2 without proper locking against
* races with any tasklet or interrupt handlers until smc_shutdown()
* or smc_reset() is called.
*/
}
/*
* this puts the device in an inactive state
*/
static void smc_shutdown(struct net_device *dev)
{
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
struct sk_buff *pending_skb;
DBG(2, "%s: %s\n", CARDNAME, __func__);
/* no more interrupts for me */
spin_lock_irq(&lp->lock);
SMC_SELECT_BANK(lp, 2);
SMC_SET_INT_MASK(lp, 0);
pending_skb = lp->pending_tx_skb;
lp->pending_tx_skb = NULL;
spin_unlock_irq(&lp->lock);
if (pending_skb)
dev_kfree_skb(pending_skb);
/* and tell the card to stay away from that nasty outside world */
SMC_SELECT_BANK(lp, 0);
SMC_SET_RCR(lp, RCR_CLEAR);
SMC_SET_TCR(lp, TCR_CLEAR);
#ifdef POWER_DOWN
/* finally, shut the chip down */
SMC_SELECT_BANK(lp, 1);
SMC_SET_CONFIG(lp, SMC_GET_CONFIG(lp) & ~CONFIG_EPH_POWER_EN);
#endif
}
/*
* This is the procedure to handle the receipt of a packet.
*/
static inline void smc_rcv(struct net_device *dev)
{
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
unsigned int packet_number, status, packet_len;
DBG(3, "%s: %s\n", dev->name, __func__);
packet_number = SMC_GET_RXFIFO(lp);
if (unlikely(packet_number & RXFIFO_REMPTY)) {
PRINTK("%s: smc_rcv with nothing on FIFO.\n", dev->name);
return;
}
/* read from start of packet */
SMC_SET_PTR(lp, PTR_READ | PTR_RCV | PTR_AUTOINC);
/* First two words are status and packet length */
SMC_GET_PKT_HDR(lp, status, packet_len);
packet_len &= 0x07ff; /* mask off top bits */
DBG(2, "%s: RX PNR 0x%x STATUS 0x%04x LENGTH 0x%04x (%d)\n",
dev->name, packet_number, status,
packet_len, packet_len);
back:
if (unlikely(packet_len < 6 || status & RS_ERRORS)) {
if (status & RS_TOOLONG && packet_len <= (1514 + 4 + 6)) {
/* accept VLAN packets */
status &= ~RS_TOOLONG;
goto back;
}
if (packet_len < 6) {
/* bloody hardware */
printk(KERN_ERR "%s: fubar (rxlen %u status %x\n",
dev->name, packet_len, status);
status |= RS_TOOSHORT;
}
SMC_WAIT_MMU_BUSY(lp);
SMC_SET_MMU_CMD(lp, MC_RELEASE);
dev->stats.rx_errors++;
if (status & RS_ALGNERR)
dev->stats.rx_frame_errors++;
if (status & (RS_TOOSHORT | RS_TOOLONG))
dev->stats.rx_length_errors++;
if (status & RS_BADCRC)
dev->stats.rx_crc_errors++;
} else {
struct sk_buff *skb;
unsigned char *data;
unsigned int data_len;
/* set multicast stats */
if (status & RS_MULTICAST)
dev->stats.multicast++;
/*
* Actual payload is packet_len - 6 (or 5 if odd byte).
* We want skb_reserve(2) and the final ctrl word
* (2 bytes, possibly containing the payload odd byte).
* Furthermore, we add 2 bytes to allow rounding up to
* multiple of 4 bytes on 32 bit buses.
* Hence packet_len - 6 + 2 + 2 + 2.
*/
skb = netdev_alloc_skb(dev, packet_len);
if (unlikely(skb == NULL)) {
printk(KERN_NOTICE "%s: Low memory, packet dropped.\n",
dev->name);
SMC_WAIT_MMU_BUSY(lp);
SMC_SET_MMU_CMD(lp, MC_RELEASE);
dev->stats.rx_dropped++;
return;
}
/* Align IP header to 32 bits */
skb_reserve(skb, 2);
/* BUG: the LAN91C111 rev A never sets this bit. Force it. */
if (lp->version == 0x90)
status |= RS_ODDFRAME;
/*
* If odd length: packet_len - 5,
* otherwise packet_len - 6.
* With the trailing ctrl byte it's packet_len - 4.
*/
data_len = packet_len - ((status & RS_ODDFRAME) ? 5 : 6);
data = skb_put(skb, data_len);
SMC_PULL_DATA(lp, data, packet_len - 4);
SMC_WAIT_MMU_BUSY(lp);
SMC_SET_MMU_CMD(lp, MC_RELEASE);
PRINT_PKT(data, packet_len - 4);
skb->protocol = eth_type_trans(skb, dev);
netif_rx(skb);
dev->stats.rx_packets++;
dev->stats.rx_bytes += data_len;
}
}
#ifdef CONFIG_SMP
/*
* On SMP we have the following problem:
*
* A = smc_hardware_send_pkt()
* B = smc_hard_start_xmit()
* C = smc_interrupt()
*
* A and B can never be executed simultaneously. However, at least on UP,
* it is possible (and even desirable) for C to interrupt execution of
* A or B in order to have better RX reliability and avoid overruns.
* C, just like A and B, must have exclusive access to the chip and
* each of them must lock against any other concurrent access.
* Unfortunately this is not possible to have C suspend execution of A or
* B taking place on another CPU. On UP this is no an issue since A and B
* are run from softirq context and C from hard IRQ context, and there is
* no other CPU where concurrent access can happen.
* If ever there is a way to force at least B and C to always be executed
* on the same CPU then we could use read/write locks to protect against
* any other concurrent access and C would always interrupt B. But life
* isn't that easy in a SMP world...
*/
#define smc_special_trylock(lock, flags) \
({ \
int __ret; \
local_irq_save(flags); \
__ret = spin_trylock(lock); \
if (!__ret) \
local_irq_restore(flags); \
__ret; \
})
#define smc_special_lock(lock, flags) spin_lock_irqsave(lock, flags)
#define smc_special_unlock(lock, flags) spin_unlock_irqrestore(lock, flags)
#else
#define smc_special_trylock(lock, flags) (flags == flags)
#define smc_special_lock(lock, flags) do { flags = 0; } while (0)
#define smc_special_unlock(lock, flags) do { flags = 0; } while (0)
#endif
/*
* This is called to actually send a packet to the chip.
*/
static void smc_hardware_send_pkt(unsigned long data)
{
struct net_device *dev = (struct net_device *)data;
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
struct sk_buff *skb;
unsigned int packet_no, len;
unsigned char *buf;
unsigned long flags;
DBG(3, "%s: %s\n", dev->name, __func__);
if (!smc_special_trylock(&lp->lock, flags)) {
netif_stop_queue(dev);
tasklet_schedule(&lp->tx_task);
return;
}
skb = lp->pending_tx_skb;
if (unlikely(!skb)) {
smc_special_unlock(&lp->lock, flags);
return;
}
lp->pending_tx_skb = NULL;
packet_no = SMC_GET_AR(lp);
if (unlikely(packet_no & AR_FAILED)) {
printk("%s: Memory allocation failed.\n", dev->name);
dev->stats.tx_errors++;
dev->stats.tx_fifo_errors++;
smc_special_unlock(&lp->lock, flags);
goto done;
}
/* point to the beginning of the packet */
SMC_SET_PN(lp, packet_no);
SMC_SET_PTR(lp, PTR_AUTOINC);
buf = skb->data;
len = skb->len;
DBG(2, "%s: TX PNR 0x%x LENGTH 0x%04x (%d) BUF 0x%p\n",
dev->name, packet_no, len, len, buf);
PRINT_PKT(buf, len);
/*
* Send the packet length (+6 for status words, length, and ctl.
* The card will pad to 64 bytes with zeroes if packet is too small.
*/
SMC_PUT_PKT_HDR(lp, 0, len + 6);
/* send the actual data */
SMC_PUSH_DATA(lp, buf, len & ~1);
/* Send final ctl word with the last byte if there is one */
SMC_outw(((len & 1) ? (0x2000 | buf[len-1]) : 0), ioaddr, DATA_REG(lp));
/*
* If THROTTLE_TX_PKTS is set, we stop the queue here. This will
* have the effect of having at most one packet queued for TX
* in the chip's memory at all time.
*
* If THROTTLE_TX_PKTS is not set then the queue is stopped only
* when memory allocation (MC_ALLOC) does not succeed right away.
*/
if (THROTTLE_TX_PKTS)
netif_stop_queue(dev);
/* queue the packet for TX */
SMC_SET_MMU_CMD(lp, MC_ENQUEUE);
smc_special_unlock(&lp->lock, flags);
dev->trans_start = jiffies;
dev->stats.tx_packets++;
dev->stats.tx_bytes += len;
SMC_ENABLE_INT(lp, IM_TX_INT | IM_TX_EMPTY_INT);
done: if (!THROTTLE_TX_PKTS)
netif_wake_queue(dev);
dev_kfree_skb(skb);
}
/*
* Since I am not sure if I will have enough room in the chip's ram
* to store the packet, I call this routine which either sends it
* now, or set the card to generates an interrupt when ready
* for the packet.
*/
static int smc_hard_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
unsigned int numPages, poll_count, status;
unsigned long flags;
DBG(3, "%s: %s\n", dev->name, __func__);
BUG_ON(lp->pending_tx_skb != NULL);
/*
* The MMU wants the number of pages to be the number of 256 bytes
* 'pages', minus 1 (since a packet can't ever have 0 pages :))
*
* The 91C111 ignores the size bits, but earlier models don't.
*
* Pkt size for allocating is data length +6 (for additional status
* words, length and ctl)
*
* If odd size then last byte is included in ctl word.
*/
numPages = ((skb->len & ~1) + (6 - 1)) >> 8;
if (unlikely(numPages > 7)) {
printk("%s: Far too big packet error.\n", dev->name);
dev->stats.tx_errors++;
dev->stats.tx_dropped++;
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
smc_special_lock(&lp->lock, flags);
/* now, try to allocate the memory */
SMC_SET_MMU_CMD(lp, MC_ALLOC | numPages);
/*
* Poll the chip for a short amount of time in case the
* allocation succeeds quickly.
*/
poll_count = MEMORY_WAIT_TIME;
do {
status = SMC_GET_INT(lp);
if (status & IM_ALLOC_INT) {
SMC_ACK_INT(lp, IM_ALLOC_INT);
break;
}
} while (--poll_count);
smc_special_unlock(&lp->lock, flags);
lp->pending_tx_skb = skb;
if (!poll_count) {
/* oh well, wait until the chip finds memory later */
netif_stop_queue(dev);
DBG(2, "%s: TX memory allocation deferred.\n", dev->name);
SMC_ENABLE_INT(lp, IM_ALLOC_INT);
} else {
/*
* Allocation succeeded: push packet to the chip's own memory
* immediately.
*/
smc_hardware_send_pkt((unsigned long)dev);
}
return NETDEV_TX_OK;
}
/*
* This handles a TX interrupt, which is only called when:
* - a TX error occurred, or
* - CTL_AUTO_RELEASE is not set and TX of a packet completed.
*/
static void smc_tx(struct net_device *dev)
{
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
unsigned int saved_packet, packet_no, tx_status, pkt_len;
DBG(3, "%s: %s\n", dev->name, __func__);
/* If the TX FIFO is empty then nothing to do */
packet_no = SMC_GET_TXFIFO(lp);
if (unlikely(packet_no & TXFIFO_TEMPTY)) {
PRINTK("%s: smc_tx with nothing on FIFO.\n", dev->name);
return;
}
/* select packet to read from */
saved_packet = SMC_GET_PN(lp);
SMC_SET_PN(lp, packet_no);
/* read the first word (status word) from this packet */
SMC_SET_PTR(lp, PTR_AUTOINC | PTR_READ);
SMC_GET_PKT_HDR(lp, tx_status, pkt_len);
DBG(2, "%s: TX STATUS 0x%04x PNR 0x%02x\n",
dev->name, tx_status, packet_no);
if (!(tx_status & ES_TX_SUC))
dev->stats.tx_errors++;
if (tx_status & ES_LOSTCARR)
dev->stats.tx_carrier_errors++;
if (tx_status & (ES_LATCOL | ES_16COL)) {
PRINTK("%s: %s occurred on last xmit\n", dev->name,
(tx_status & ES_LATCOL) ?
"late collision" : "too many collisions");
dev->stats.tx_window_errors++;
if (!(dev->stats.tx_window_errors & 63) && net_ratelimit()) {
printk(KERN_INFO "%s: unexpectedly large number of "
"bad collisions. Please check duplex "
"setting.\n", dev->name);
}
}
/* kill the packet */
SMC_WAIT_MMU_BUSY(lp);
SMC_SET_MMU_CMD(lp, MC_FREEPKT);
/* Don't restore Packet Number Reg until busy bit is cleared */
SMC_WAIT_MMU_BUSY(lp);
SMC_SET_PN(lp, saved_packet);
/* re-enable transmit */
SMC_SELECT_BANK(lp, 0);
SMC_SET_TCR(lp, lp->tcr_cur_mode);
SMC_SELECT_BANK(lp, 2);
}
/*---PHY CONTROL AND CONFIGURATION-----------------------------------------*/
static void smc_mii_out(struct net_device *dev, unsigned int val, int bits)
{
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
unsigned int mii_reg, mask;
mii_reg = SMC_GET_MII(lp) & ~(MII_MCLK | MII_MDOE | MII_MDO);
mii_reg |= MII_MDOE;
for (mask = 1 << (bits - 1); mask; mask >>= 1) {
if (val & mask)
mii_reg |= MII_MDO;
else
mii_reg &= ~MII_MDO;
SMC_SET_MII(lp, mii_reg);
udelay(MII_DELAY);
SMC_SET_MII(lp, mii_reg | MII_MCLK);
udelay(MII_DELAY);
}
}
static unsigned int smc_mii_in(struct net_device *dev, int bits)
{
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
unsigned int mii_reg, mask, val;
mii_reg = SMC_GET_MII(lp) & ~(MII_MCLK | MII_MDOE | MII_MDO);
SMC_SET_MII(lp, mii_reg);
for (mask = 1 << (bits - 1), val = 0; mask; mask >>= 1) {
if (SMC_GET_MII(lp) & MII_MDI)
val |= mask;
SMC_SET_MII(lp, mii_reg);
udelay(MII_DELAY);
SMC_SET_MII(lp, mii_reg | MII_MCLK);
udelay(MII_DELAY);
}
return val;
}
/*
* Reads a register from the MII Management serial interface
*/
static int smc_phy_read(struct net_device *dev, int phyaddr, int phyreg)
{
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
unsigned int phydata;
SMC_SELECT_BANK(lp, 3);
/* Idle - 32 ones */
smc_mii_out(dev, 0xffffffff, 32);
/* Start code (01) + read (10) + phyaddr + phyreg */
smc_mii_out(dev, 6 << 10 | phyaddr << 5 | phyreg, 14);
/* Turnaround (2bits) + phydata */
phydata = smc_mii_in(dev, 18);
/* Return to idle state */
SMC_SET_MII(lp, SMC_GET_MII(lp) & ~(MII_MCLK|MII_MDOE|MII_MDO));
DBG(3, "%s: phyaddr=0x%x, phyreg=0x%x, phydata=0x%x\n",
__func__, phyaddr, phyreg, phydata);
SMC_SELECT_BANK(lp, 2);
return phydata;
}
/*
* Writes a register to the MII Management serial interface
*/
static void smc_phy_write(struct net_device *dev, int phyaddr, int phyreg,
int phydata)
{
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
SMC_SELECT_BANK(lp, 3);
/* Idle - 32 ones */
smc_mii_out(dev, 0xffffffff, 32);
/* Start code (01) + write (01) + phyaddr + phyreg + turnaround + phydata */
smc_mii_out(dev, 5 << 28 | phyaddr << 23 | phyreg << 18 | 2 << 16 | phydata, 32);
/* Return to idle state */
SMC_SET_MII(lp, SMC_GET_MII(lp) & ~(MII_MCLK|MII_MDOE|MII_MDO));
DBG(3, "%s: phyaddr=0x%x, phyreg=0x%x, phydata=0x%x\n",
__func__, phyaddr, phyreg, phydata);
SMC_SELECT_BANK(lp, 2);
}
/*
* Finds and reports the PHY address
*/
static void smc_phy_detect(struct net_device *dev)
{
struct smc_local *lp = netdev_priv(dev);
int phyaddr;
DBG(2, "%s: %s\n", dev->name, __func__);
lp->phy_type = 0;
/*
* Scan all 32 PHY addresses if necessary, starting at
* PHY#1 to PHY#31, and then PHY#0 last.
*/
for (phyaddr = 1; phyaddr < 33; ++phyaddr) {
unsigned int id1, id2;
/* Read the PHY identifiers */
id1 = smc_phy_read(dev, phyaddr & 31, MII_PHYSID1);
id2 = smc_phy_read(dev, phyaddr & 31, MII_PHYSID2);
DBG(3, "%s: phy_id1=0x%x, phy_id2=0x%x\n",
dev->name, id1, id2);
/* Make sure it is a valid identifier */
if (id1 != 0x0000 && id1 != 0xffff && id1 != 0x8000 &&
id2 != 0x0000 && id2 != 0xffff && id2 != 0x8000) {
/* Save the PHY's address */
lp->mii.phy_id = phyaddr & 31;
lp->phy_type = id1 << 16 | id2;
break;
}
}
}
/*
* Sets the PHY to a configuration as determined by the user
*/
static int smc_phy_fixed(struct net_device *dev)
{
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
int phyaddr = lp->mii.phy_id;
int bmcr, cfg1;
DBG(3, "%s: %s\n", dev->name, __func__);
/* Enter Link Disable state */
cfg1 = smc_phy_read(dev, phyaddr, PHY_CFG1_REG);
cfg1 |= PHY_CFG1_LNKDIS;
smc_phy_write(dev, phyaddr, PHY_CFG1_REG, cfg1);
/*
* Set our fixed capabilities
* Disable auto-negotiation
*/
bmcr = 0;
if (lp->ctl_rfduplx)
bmcr |= BMCR_FULLDPLX;
if (lp->ctl_rspeed == 100)
bmcr |= BMCR_SPEED100;
/* Write our capabilities to the phy control register */
smc_phy_write(dev, phyaddr, MII_BMCR, bmcr);
/* Re-Configure the Receive/Phy Control register */
SMC_SELECT_BANK(lp, 0);
SMC_SET_RPC(lp, lp->rpc_cur_mode);
SMC_SELECT_BANK(lp, 2);
return 1;
}
/*
* smc_phy_reset - reset the phy
* @dev: net device
* @phy: phy address
*
* Issue a software reset for the specified PHY and
* wait up to 100ms for the reset to complete. We should
* not access the PHY for 50ms after issuing the reset.
*
* The time to wait appears to be dependent on the PHY.
*
* Must be called with lp->lock locked.
*/
static int smc_phy_reset(struct net_device *dev, int phy)
{
struct smc_local *lp = netdev_priv(dev);
unsigned int bmcr;
int timeout;
smc_phy_write(dev, phy, MII_BMCR, BMCR_RESET);
for (timeout = 2; timeout; timeout--) {
spin_unlock_irq(&lp->lock);
msleep(50);
spin_lock_irq(&lp->lock);
bmcr = smc_phy_read(dev, phy, MII_BMCR);
if (!(bmcr & BMCR_RESET))
break;
}
return bmcr & BMCR_RESET;
}
/*
* smc_phy_powerdown - powerdown phy
* @dev: net device
*
* Power down the specified PHY
*/
static void smc_phy_powerdown(struct net_device *dev)
{
struct smc_local *lp = netdev_priv(dev);
unsigned int bmcr;
int phy = lp->mii.phy_id;
if (lp->phy_type == 0)
return;
/* We need to ensure that no calls to smc_phy_configure are
pending.
*/
cancel_work_sync(&lp->phy_configure);
bmcr = smc_phy_read(dev, phy, MII_BMCR);
smc_phy_write(dev, phy, MII_BMCR, bmcr | BMCR_PDOWN);
}
/*
* smc_phy_check_media - check the media status and adjust TCR
* @dev: net device
* @init: set true for initialisation
*
* Select duplex mode depending on negotiation state. This
* also updates our carrier state.
*/
static void smc_phy_check_media(struct net_device *dev, int init)
{
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
if (mii_check_media(&lp->mii, netif_msg_link(lp), init)) {
/* duplex state has changed */
if (lp->mii.full_duplex) {
lp->tcr_cur_mode |= TCR_SWFDUP;
} else {
lp->tcr_cur_mode &= ~TCR_SWFDUP;
}
SMC_SELECT_BANK(lp, 0);
SMC_SET_TCR(lp, lp->tcr_cur_mode);
}
}
/*
* Configures the specified PHY through the MII management interface
* using Autonegotiation.
* Calls smc_phy_fixed() if the user has requested a certain config.
* If RPC ANEG bit is set, the media selection is dependent purely on
* the selection by the MII (either in the MII BMCR reg or the result
* of autonegotiation.) If the RPC ANEG bit is cleared, the selection
* is controlled by the RPC SPEED and RPC DPLX bits.
*/
static void smc_phy_configure(struct work_struct *work)
{
struct smc_local *lp =
container_of(work, struct smc_local, phy_configure);
struct net_device *dev = lp->dev;
void __iomem *ioaddr = lp->base;
int phyaddr = lp->mii.phy_id;
int my_phy_caps; /* My PHY capabilities */
int my_ad_caps; /* My Advertised capabilities */
int status;
DBG(3, "%s:smc_program_phy()\n", dev->name);
spin_lock_irq(&lp->lock);
/*
* We should not be called if phy_type is zero.
*/
if (lp->phy_type == 0)
goto smc_phy_configure_exit;
if (smc_phy_reset(dev, phyaddr)) {
printk("%s: PHY reset timed out\n", dev->name);
goto smc_phy_configure_exit;
}
/*
* Enable PHY Interrupts (for register 18)
* Interrupts listed here are disabled
*/
smc_phy_write(dev, phyaddr, PHY_MASK_REG,
PHY_INT_LOSSSYNC | PHY_INT_CWRD | PHY_INT_SSD |
PHY_INT_ESD | PHY_INT_RPOL | PHY_INT_JAB |
PHY_INT_SPDDET | PHY_INT_DPLXDET);
/* Configure the Receive/Phy Control register */
SMC_SELECT_BANK(lp, 0);
SMC_SET_RPC(lp, lp->rpc_cur_mode);
/* If the user requested no auto neg, then go set his request */
if (lp->mii.force_media) {
smc_phy_fixed(dev);
goto smc_phy_configure_exit;
}
/* Copy our capabilities from MII_BMSR to MII_ADVERTISE */
my_phy_caps = smc_phy_read(dev, phyaddr, MII_BMSR);
if (!(my_phy_caps & BMSR_ANEGCAPABLE)) {
printk(KERN_INFO "Auto negotiation NOT supported\n");
smc_phy_fixed(dev);
goto smc_phy_configure_exit;
}
my_ad_caps = ADVERTISE_CSMA; /* I am CSMA capable */
if (my_phy_caps & BMSR_100BASE4)
my_ad_caps |= ADVERTISE_100BASE4;
if (my_phy_caps & BMSR_100FULL)
my_ad_caps |= ADVERTISE_100FULL;
if (my_phy_caps & BMSR_100HALF)
my_ad_caps |= ADVERTISE_100HALF;
if (my_phy_caps & BMSR_10FULL)
my_ad_caps |= ADVERTISE_10FULL;
if (my_phy_caps & BMSR_10HALF)
my_ad_caps |= ADVERTISE_10HALF;
/* Disable capabilities not selected by our user */
if (lp->ctl_rspeed != 100)
my_ad_caps &= ~(ADVERTISE_100BASE4|ADVERTISE_100FULL|ADVERTISE_100HALF);
if (!lp->ctl_rfduplx)
my_ad_caps &= ~(ADVERTISE_100FULL|ADVERTISE_10FULL);
/* Update our Auto-Neg Advertisement Register */
smc_phy_write(dev, phyaddr, MII_ADVERTISE, my_ad_caps);
lp->mii.advertising = my_ad_caps;
/*
* Read the register back. Without this, it appears that when
* auto-negotiation is restarted, sometimes it isn't ready and
* the link does not come up.
*/
status = smc_phy_read(dev, phyaddr, MII_ADVERTISE);
DBG(2, "%s: phy caps=%x\n", dev->name, my_phy_caps);
DBG(2, "%s: phy advertised caps=%x\n", dev->name, my_ad_caps);
/* Restart auto-negotiation process in order to advertise my caps */
smc_phy_write(dev, phyaddr, MII_BMCR, BMCR_ANENABLE | BMCR_ANRESTART);
smc_phy_check_media(dev, 1);
smc_phy_configure_exit:
SMC_SELECT_BANK(lp, 2);
spin_unlock_irq(&lp->lock);
}
/*
* smc_phy_interrupt
*
* Purpose: Handle interrupts relating to PHY register 18. This is
* called from the "hard" interrupt handler under our private spinlock.
*/
static void smc_phy_interrupt(struct net_device *dev)
{
struct smc_local *lp = netdev_priv(dev);
int phyaddr = lp->mii.phy_id;
int phy18;
DBG(2, "%s: %s\n", dev->name, __func__);
if (lp->phy_type == 0)
return;
for(;;) {
smc_phy_check_media(dev, 0);
/* Read PHY Register 18, Status Output */
phy18 = smc_phy_read(dev, phyaddr, PHY_INT_REG);
if ((phy18 & PHY_INT_INT) == 0)
break;
}
}
/*--- END PHY CONTROL AND CONFIGURATION-------------------------------------*/
static void smc_10bt_check_media(struct net_device *dev, int init)
{
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
unsigned int old_carrier, new_carrier;
old_carrier = netif_carrier_ok(dev) ? 1 : 0;
SMC_SELECT_BANK(lp, 0);
new_carrier = (SMC_GET_EPH_STATUS(lp) & ES_LINK_OK) ? 1 : 0;
SMC_SELECT_BANK(lp, 2);
if (init || (old_carrier != new_carrier)) {
if (!new_carrier) {
netif_carrier_off(dev);
} else {
netif_carrier_on(dev);
}
if (netif_msg_link(lp))
printk(KERN_INFO "%s: link %s\n", dev->name,
new_carrier ? "up" : "down");
}
}
static void smc_eph_interrupt(struct net_device *dev)
{
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
unsigned int ctl;
smc_10bt_check_media(dev, 0);
SMC_SELECT_BANK(lp, 1);
ctl = SMC_GET_CTL(lp);
SMC_SET_CTL(lp, ctl & ~CTL_LE_ENABLE);
SMC_SET_CTL(lp, ctl);
SMC_SELECT_BANK(lp, 2);
}
/*
* This is the main routine of the driver, to handle the device when
* it needs some attention.
*/
static irqreturn_t smc_interrupt(int irq, void *dev_id)
{
struct net_device *dev = dev_id;
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
int status, mask, timeout, card_stats;
int saved_pointer;
DBG(3, "%s: %s\n", dev->name, __func__);
spin_lock(&lp->lock);
/* A preamble may be used when there is a potential race
* between the interruptible transmit functions and this
* ISR. */
SMC_INTERRUPT_PREAMBLE;
saved_pointer = SMC_GET_PTR(lp);
mask = SMC_GET_INT_MASK(lp);
SMC_SET_INT_MASK(lp, 0);
/* set a timeout value, so I don't stay here forever */
timeout = MAX_IRQ_LOOPS;
do {
status = SMC_GET_INT(lp);
DBG(2, "%s: INT 0x%02x MASK 0x%02x MEM 0x%04x FIFO 0x%04x\n",
dev->name, status, mask,
({ int meminfo; SMC_SELECT_BANK(lp, 0);
meminfo = SMC_GET_MIR(lp);
SMC_SELECT_BANK(lp, 2); meminfo; }),
SMC_GET_FIFO(lp));
status &= mask;
if (!status)
break;
if (status & IM_TX_INT) {
/* do this before RX as it will free memory quickly */
DBG(3, "%s: TX int\n", dev->name);
smc_tx(dev);
SMC_ACK_INT(lp, IM_TX_INT);
if (THROTTLE_TX_PKTS)
netif_wake_queue(dev);
} else if (status & IM_RCV_INT) {
DBG(3, "%s: RX irq\n", dev->name);
smc_rcv(dev);
} else if (status & IM_ALLOC_INT) {
DBG(3, "%s: Allocation irq\n", dev->name);
tasklet_hi_schedule(&lp->tx_task);
mask &= ~IM_ALLOC_INT;
} else if (status & IM_TX_EMPTY_INT) {
DBG(3, "%s: TX empty\n", dev->name);
mask &= ~IM_TX_EMPTY_INT;
/* update stats */
SMC_SELECT_BANK(lp, 0);
card_stats = SMC_GET_COUNTER(lp);
SMC_SELECT_BANK(lp, 2);
/* single collisions */
dev->stats.collisions += card_stats & 0xF;
card_stats >>= 4;
/* multiple collisions */
dev->stats.collisions += card_stats & 0xF;
} else if (status & IM_RX_OVRN_INT) {
DBG(1, "%s: RX overrun (EPH_ST 0x%04x)\n", dev->name,
({ int eph_st; SMC_SELECT_BANK(lp, 0);
eph_st = SMC_GET_EPH_STATUS(lp);
SMC_SELECT_BANK(lp, 2); eph_st; }));
SMC_ACK_INT(lp, IM_RX_OVRN_INT);
dev->stats.rx_errors++;
dev->stats.rx_fifo_errors++;
} else if (status & IM_EPH_INT) {
smc_eph_interrupt(dev);
} else if (status & IM_MDINT) {
SMC_ACK_INT(lp, IM_MDINT);
smc_phy_interrupt(dev);
} else if (status & IM_ERCV_INT) {
SMC_ACK_INT(lp, IM_ERCV_INT);
PRINTK("%s: UNSUPPORTED: ERCV INTERRUPT\n", dev->name);
}
} while (--timeout);
/* restore register states */
SMC_SET_PTR(lp, saved_pointer);
SMC_SET_INT_MASK(lp, mask);
spin_unlock(&lp->lock);
#ifndef CONFIG_NET_POLL_CONTROLLER
if (timeout == MAX_IRQ_LOOPS)
PRINTK("%s: spurious interrupt (mask = 0x%02x)\n",
dev->name, mask);
#endif
DBG(3, "%s: Interrupt done (%d loops)\n",
dev->name, MAX_IRQ_LOOPS - timeout);
/*
* We return IRQ_HANDLED unconditionally here even if there was
* nothing to do. There is a possibility that a packet might
* get enqueued into the chip right after TX_EMPTY_INT is raised
* but just before the CPU acknowledges the IRQ.
* Better take an unneeded IRQ in some occasions than complexifying
* the code for all cases.
*/
return IRQ_HANDLED;
}
#ifdef CONFIG_NET_POLL_CONTROLLER
/*
* Polling receive - used by netconsole and other diagnostic tools
* to allow network i/o with interrupts disabled.
*/
static void smc_poll_controller(struct net_device *dev)
{
disable_irq(dev->irq);
smc_interrupt(dev->irq, dev);
enable_irq(dev->irq);
}
#endif
/* Our watchdog timed out. Called by the networking layer */
static void smc_timeout(struct net_device *dev)
{
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
int status, mask, eph_st, meminfo, fifo;
DBG(2, "%s: %s\n", dev->name, __func__);
spin_lock_irq(&lp->lock);
status = SMC_GET_INT(lp);
mask = SMC_GET_INT_MASK(lp);
fifo = SMC_GET_FIFO(lp);
SMC_SELECT_BANK(lp, 0);
eph_st = SMC_GET_EPH_STATUS(lp);
meminfo = SMC_GET_MIR(lp);
SMC_SELECT_BANK(lp, 2);
spin_unlock_irq(&lp->lock);
PRINTK( "%s: TX timeout (INT 0x%02x INTMASK 0x%02x "
"MEM 0x%04x FIFO 0x%04x EPH_ST 0x%04x)\n",
dev->name, status, mask, meminfo, fifo, eph_st );
smc_reset(dev);
smc_enable(dev);
/*
* Reconfiguring the PHY doesn't seem like a bad idea here, but
* smc_phy_configure() calls msleep() which calls schedule_timeout()
* which calls schedule(). Hence we use a work queue.
*/
if (lp->phy_type != 0)
schedule_work(&lp->phy_configure);
/* We can accept TX packets again */
dev->trans_start = jiffies; /* prevent tx timeout */
netif_wake_queue(dev);
}
/*
* This routine will, depending on the values passed to it,
* either make it accept multicast packets, go into
* promiscuous mode (for TCPDUMP and cousins) or accept
* a select set of multicast packets
*/
static void smc_set_multicast_list(struct net_device *dev)
{
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
unsigned char multicast_table[8];
int update_multicast = 0;
DBG(2, "%s: %s\n", dev->name, __func__);
if (dev->flags & IFF_PROMISC) {
DBG(2, "%s: RCR_PRMS\n", dev->name);
lp->rcr_cur_mode |= RCR_PRMS;
}
/* BUG? I never disable promiscuous mode if multicasting was turned on.
Now, I turn off promiscuous mode, but I don't do anything to multicasting
when promiscuous mode is turned on.
*/
/*
* Here, I am setting this to accept all multicast packets.
* I don't need to zero the multicast table, because the flag is
* checked before the table is
*/
else if (dev->flags & IFF_ALLMULTI || netdev_mc_count(dev) > 16) {
DBG(2, "%s: RCR_ALMUL\n", dev->name);
lp->rcr_cur_mode |= RCR_ALMUL;
}
/*
* This sets the internal hardware table to filter out unwanted
* multicast packets before they take up memory.
*
* The SMC chip uses a hash table where the high 6 bits of the CRC of
* address are the offset into the table. If that bit is 1, then the
* multicast packet is accepted. Otherwise, it's dropped silently.
*
* To use the 6 bits as an offset into the table, the high 3 bits are
* the number of the 8 bit register, while the low 3 bits are the bit
* within that register.
*/
else if (!netdev_mc_empty(dev)) {
struct netdev_hw_addr *ha;
/* table for flipping the order of 3 bits */
static const unsigned char invert3[] = {0, 4, 2, 6, 1, 5, 3, 7};
/* start with a table of all zeros: reject all */
memset(multicast_table, 0, sizeof(multicast_table));
netdev_for_each_mc_addr(ha, dev) {
int position;
/* only use the low order bits */
position = crc32_le(~0, ha->addr, 6) & 0x3f;
/* do some messy swapping to put the bit in the right spot */
multicast_table[invert3[position&7]] |=
(1<<invert3[(position>>3)&7]);
}
/* be sure I get rid of flags I might have set */
lp->rcr_cur_mode &= ~(RCR_PRMS | RCR_ALMUL);
/* now, the table can be loaded into the chipset */
update_multicast = 1;
} else {
DBG(2, "%s: ~(RCR_PRMS|RCR_ALMUL)\n", dev->name);
lp->rcr_cur_mode &= ~(RCR_PRMS | RCR_ALMUL);
/*
* since I'm disabling all multicast entirely, I need to
* clear the multicast list
*/
memset(multicast_table, 0, sizeof(multicast_table));
update_multicast = 1;
}
spin_lock_irq(&lp->lock);
SMC_SELECT_BANK(lp, 0);
SMC_SET_RCR(lp, lp->rcr_cur_mode);
if (update_multicast) {
SMC_SELECT_BANK(lp, 3);
SMC_SET_MCAST(lp, multicast_table);
}
SMC_SELECT_BANK(lp, 2);
spin_unlock_irq(&lp->lock);
}
/*
* Open and Initialize the board
*
* Set up everything, reset the card, etc..
*/
static int
smc_open(struct net_device *dev)
{
struct smc_local *lp = netdev_priv(dev);
DBG(2, "%s: %s\n", dev->name, __func__);
/*
* Check that the address is valid. If its not, refuse
* to bring the device up. The user must specify an
* address using ifconfig eth0 hw ether xx:xx:xx:xx:xx:xx
*/
if (!is_valid_ether_addr(dev->dev_addr)) {
PRINTK("%s: no valid ethernet hw addr\n", __func__);
return -EINVAL;
}
/* Setup the default Register Modes */
lp->tcr_cur_mode = TCR_DEFAULT;
lp->rcr_cur_mode = RCR_DEFAULT;
lp->rpc_cur_mode = RPC_DEFAULT |
lp->cfg.leda << RPC_LSXA_SHFT |
lp->cfg.ledb << RPC_LSXB_SHFT;
/*
* If we are not using a MII interface, we need to
* monitor our own carrier signal to detect faults.
*/
if (lp->phy_type == 0)
lp->tcr_cur_mode |= TCR_MON_CSN;
/* reset the hardware */
smc_reset(dev);
smc_enable(dev);
/* Configure the PHY, initialize the link state */
if (lp->phy_type != 0)
smc_phy_configure(&lp->phy_configure);
else {
spin_lock_irq(&lp->lock);
smc_10bt_check_media(dev, 1);
spin_unlock_irq(&lp->lock);
}
netif_start_queue(dev);
return 0;
}
/*
* smc_close
*
* this makes the board clean up everything that it can
* and not talk to the outside world. Caused by
* an 'ifconfig ethX down'
*/
static int smc_close(struct net_device *dev)
{
struct smc_local *lp = netdev_priv(dev);
DBG(2, "%s: %s\n", dev->name, __func__);
netif_stop_queue(dev);
netif_carrier_off(dev);
/* clear everything */
smc_shutdown(dev);
tasklet_kill(&lp->tx_task);
smc_phy_powerdown(dev);
return 0;
}
/*
* Ethtool support
*/
static int
smc_ethtool_getsettings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct smc_local *lp = netdev_priv(dev);
int ret;
cmd->maxtxpkt = 1;
cmd->maxrxpkt = 1;
if (lp->phy_type != 0) {
spin_lock_irq(&lp->lock);
ret = mii_ethtool_gset(&lp->mii, cmd);
spin_unlock_irq(&lp->lock);
} else {
cmd->supported = SUPPORTED_10baseT_Half |
SUPPORTED_10baseT_Full |
SUPPORTED_TP | SUPPORTED_AUI;
if (lp->ctl_rspeed == 10)
ethtool_cmd_speed_set(cmd, SPEED_10);
else if (lp->ctl_rspeed == 100)
ethtool_cmd_speed_set(cmd, SPEED_100);
cmd->autoneg = AUTONEG_DISABLE;
cmd->transceiver = XCVR_INTERNAL;
cmd->port = 0;
cmd->duplex = lp->tcr_cur_mode & TCR_SWFDUP ? DUPLEX_FULL : DUPLEX_HALF;
ret = 0;
}
return ret;
}
static int
smc_ethtool_setsettings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct smc_local *lp = netdev_priv(dev);
int ret;
if (lp->phy_type != 0) {
spin_lock_irq(&lp->lock);
ret = mii_ethtool_sset(&lp->mii, cmd);
spin_unlock_irq(&lp->lock);
} else {
if (cmd->autoneg != AUTONEG_DISABLE ||
cmd->speed != SPEED_10 ||
(cmd->duplex != DUPLEX_HALF && cmd->duplex != DUPLEX_FULL) ||
(cmd->port != PORT_TP && cmd->port != PORT_AUI))
return -EINVAL;
// lp->port = cmd->port;
lp->ctl_rfduplx = cmd->duplex == DUPLEX_FULL;
// if (netif_running(dev))
// smc_set_port(dev);
ret = 0;
}
return ret;
}
static void
smc_ethtool_getdrvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
{
strncpy(info->driver, CARDNAME, sizeof(info->driver));
strncpy(info->version, version, sizeof(info->version));
strncpy(info->bus_info, dev_name(dev->dev.parent), sizeof(info->bus_info));
}
static int smc_ethtool_nwayreset(struct net_device *dev)
{
struct smc_local *lp = netdev_priv(dev);
int ret = -EINVAL;
if (lp->phy_type != 0) {
spin_lock_irq(&lp->lock);
ret = mii_nway_restart(&lp->mii);
spin_unlock_irq(&lp->lock);
}
return ret;
}
static u32 smc_ethtool_getmsglevel(struct net_device *dev)
{
struct smc_local *lp = netdev_priv(dev);
return lp->msg_enable;
}
static void smc_ethtool_setmsglevel(struct net_device *dev, u32 level)
{
struct smc_local *lp = netdev_priv(dev);
lp->msg_enable = level;
}
static int smc_write_eeprom_word(struct net_device *dev, u16 addr, u16 word)
{
u16 ctl;
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
spin_lock_irq(&lp->lock);
/* load word into GP register */
SMC_SELECT_BANK(lp, 1);
SMC_SET_GP(lp, word);
/* set the address to put the data in EEPROM */
SMC_SELECT_BANK(lp, 2);
SMC_SET_PTR(lp, addr);
/* tell it to write */
SMC_SELECT_BANK(lp, 1);
ctl = SMC_GET_CTL(lp);
SMC_SET_CTL(lp, ctl | (CTL_EEPROM_SELECT | CTL_STORE));
/* wait for it to finish */
do {
udelay(1);
} while (SMC_GET_CTL(lp) & CTL_STORE);
/* clean up */
SMC_SET_CTL(lp, ctl);
SMC_SELECT_BANK(lp, 2);
spin_unlock_irq(&lp->lock);
return 0;
}
static int smc_read_eeprom_word(struct net_device *dev, u16 addr, u16 *word)
{
u16 ctl;
struct smc_local *lp = netdev_priv(dev);
void __iomem *ioaddr = lp->base;
spin_lock_irq(&lp->lock);
/* set the EEPROM address to get the data from */
SMC_SELECT_BANK(lp, 2);
SMC_SET_PTR(lp, addr | PTR_READ);
/* tell it to load */
SMC_SELECT_BANK(lp, 1);
SMC_SET_GP(lp, 0xffff); /* init to known */
ctl = SMC_GET_CTL(lp);
SMC_SET_CTL(lp, ctl | (CTL_EEPROM_SELECT | CTL_RELOAD));
/* wait for it to finish */
do {
udelay(1);
} while (SMC_GET_CTL(lp) & CTL_RELOAD);
/* read word from GP register */
*word = SMC_GET_GP(lp);
/* clean up */
SMC_SET_CTL(lp, ctl);
SMC_SELECT_BANK(lp, 2);
spin_unlock_irq(&lp->lock);
return 0;
}
static int smc_ethtool_geteeprom_len(struct net_device *dev)
{
return 0x23 * 2;
}
static int smc_ethtool_geteeprom(struct net_device *dev,
struct ethtool_eeprom *eeprom, u8 *data)
{
int i;
int imax;
DBG(1, "Reading %d bytes at %d(0x%x)\n",
eeprom->len, eeprom->offset, eeprom->offset);
imax = smc_ethtool_geteeprom_len(dev);
for (i = 0; i < eeprom->len; i += 2) {
int ret;
u16 wbuf;
int offset = i + eeprom->offset;
if (offset > imax)
break;
ret = smc_read_eeprom_word(dev, offset >> 1, &wbuf);
if (ret != 0)
return ret;
DBG(2, "Read 0x%x from 0x%x\n", wbuf, offset >> 1);
data[i] = (wbuf >> 8) & 0xff;
data[i+1] = wbuf & 0xff;
}
return 0;
}
static int smc_ethtool_seteeprom(struct net_device *dev,
struct ethtool_eeprom *eeprom, u8 *data)
{
int i;
int imax;
DBG(1, "Writing %d bytes to %d(0x%x)\n",
eeprom->len, eeprom->offset, eeprom->offset);
imax = smc_ethtool_geteeprom_len(dev);
for (i = 0; i < eeprom->len; i += 2) {
int ret;
u16 wbuf;
int offset = i + eeprom->offset;
if (offset > imax)
break;
wbuf = (data[i] << 8) | data[i + 1];
DBG(2, "Writing 0x%x to 0x%x\n", wbuf, offset >> 1);
ret = smc_write_eeprom_word(dev, offset >> 1, wbuf);
if (ret != 0)
return ret;
}
return 0;
}
static const struct ethtool_ops smc_ethtool_ops = {
.get_settings = smc_ethtool_getsettings,
.set_settings = smc_ethtool_setsettings,
.get_drvinfo = smc_ethtool_getdrvinfo,
.get_msglevel = smc_ethtool_getmsglevel,
.set_msglevel = smc_ethtool_setmsglevel,
.nway_reset = smc_ethtool_nwayreset,
.get_link = ethtool_op_get_link,
.get_eeprom_len = smc_ethtool_geteeprom_len,
.get_eeprom = smc_ethtool_geteeprom,
.set_eeprom = smc_ethtool_seteeprom,
};
static const struct net_device_ops smc_netdev_ops = {
.ndo_open = smc_open,
.ndo_stop = smc_close,
.ndo_start_xmit = smc_hard_start_xmit,
.ndo_tx_timeout = smc_timeout,
.ndo_set_rx_mode = smc_set_multicast_list,
.ndo_change_mtu = eth_change_mtu,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_mac_address = eth_mac_addr,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = smc_poll_controller,
#endif
};
/*
* smc_findirq
*
* This routine has a simple purpose -- make the SMC chip generate an
* interrupt, so an auto-detect routine can detect it, and find the IRQ,
*/
/*
* does this still work?
*
* I just deleted auto_irq.c, since it was never built...
* --jgarzik
*/
static int __devinit smc_findirq(struct smc_local *lp)
{
void __iomem *ioaddr = lp->base;
int timeout = 20;
unsigned long cookie;
DBG(2, "%s: %s\n", CARDNAME, __func__);
cookie = probe_irq_on();
/*
* What I try to do here is trigger an ALLOC_INT. This is done
* by allocating a small chunk of memory, which will give an interrupt
* when done.
*/
/* enable ALLOCation interrupts ONLY */
SMC_SELECT_BANK(lp, 2);
SMC_SET_INT_MASK(lp, IM_ALLOC_INT);
/*
* Allocate 512 bytes of memory. Note that the chip was just
* reset so all the memory is available
*/
SMC_SET_MMU_CMD(lp, MC_ALLOC | 1);
/*
* Wait until positive that the interrupt has been generated
*/
do {
int int_status;
udelay(10);
int_status = SMC_GET_INT(lp);
if (int_status & IM_ALLOC_INT)
break; /* got the interrupt */
} while (--timeout);
/*
* there is really nothing that I can do here if timeout fails,
* as autoirq_report will return a 0 anyway, which is what I
* want in this case. Plus, the clean up is needed in both
* cases.
*/
/* and disable all interrupts again */
SMC_SET_INT_MASK(lp, 0);
/* and return what I found */
return probe_irq_off(cookie);
}
/*
* Function: smc_probe(unsigned long ioaddr)
*
* Purpose:
* Tests to see if a given ioaddr points to an SMC91x chip.
* Returns a 0 on success
*
* Algorithm:
* (1) see if the high byte of BANK_SELECT is 0x33
* (2) compare the ioaddr with the base register's address
* (3) see if I recognize the chip ID in the appropriate register
*
* Here I do typical initialization tasks.
*
* o Initialize the structure if needed
* o print out my vanity message if not done so already
* o print out what type of hardware is detected
* o print out the ethernet address
* o find the IRQ
* o set up my private data
* o configure the dev structure with my subroutines
* o actually GRAB the irq.
* o GRAB the region
*/
static int __devinit smc_probe(struct net_device *dev, void __iomem *ioaddr,
unsigned long irq_flags)
{
struct smc_local *lp = netdev_priv(dev);
static int version_printed = 0;
int retval;
unsigned int val, revision_register;
const char *version_string;
DBG(2, "%s: %s\n", CARDNAME, __func__);
/* First, see if the high byte is 0x33 */
val = SMC_CURRENT_BANK(lp);
DBG(2, "%s: bank signature probe returned 0x%04x\n", CARDNAME, val);
if ((val & 0xFF00) != 0x3300) {
if ((val & 0xFF) == 0x33) {
printk(KERN_WARNING
"%s: Detected possible byte-swapped interface"
" at IOADDR %p\n", CARDNAME, ioaddr);
}
retval = -ENODEV;
goto err_out;
}
/*
* The above MIGHT indicate a device, but I need to write to
* further test this.
*/
SMC_SELECT_BANK(lp, 0);
val = SMC_CURRENT_BANK(lp);
if ((val & 0xFF00) != 0x3300) {
retval = -ENODEV;
goto err_out;
}
/*
* well, we've already written once, so hopefully another
* time won't hurt. This time, I need to switch the bank
* register to bank 1, so I can access the base address
* register
*/
SMC_SELECT_BANK(lp, 1);
val = SMC_GET_BASE(lp);
val = ((val & 0x1F00) >> 3) << SMC_IO_SHIFT;
if (((unsigned int)ioaddr & (0x3e0 << SMC_IO_SHIFT)) != val) {
printk("%s: IOADDR %p doesn't match configuration (%x).\n",
CARDNAME, ioaddr, val);
}
/*
* check if the revision register is something that I
* recognize. These might need to be added to later,
* as future revisions could be added.
*/
SMC_SELECT_BANK(lp, 3);
revision_register = SMC_GET_REV(lp);
DBG(2, "%s: revision = 0x%04x\n", CARDNAME, revision_register);
version_string = chip_ids[ (revision_register >> 4) & 0xF];
if (!version_string || (revision_register & 0xff00) != 0x3300) {
/* I don't recognize this chip, so... */
printk("%s: IO %p: Unrecognized revision register 0x%04x"
", Contact author.\n", CARDNAME,
ioaddr, revision_register);
retval = -ENODEV;
goto err_out;
}
/* At this point I'll assume that the chip is an SMC91x. */
if (version_printed++ == 0)
printk("%s", version);
/* fill in some of the fields */
dev->base_addr = (unsigned long)ioaddr;
lp->base = ioaddr;
lp->version = revision_register & 0xff;
spin_lock_init(&lp->lock);
/* Get the MAC address */
SMC_SELECT_BANK(lp, 1);
SMC_GET_MAC_ADDR(lp, dev->dev_addr);
/* now, reset the chip, and put it into a known state */
smc_reset(dev);
/*
* If dev->irq is 0, then the device has to be banged on to see
* what the IRQ is.
*
* This banging doesn't always detect the IRQ, for unknown reasons.
* a workaround is to reset the chip and try again.
*
* Interestingly, the DOS packet driver *SETS* the IRQ on the card to
* be what is requested on the command line. I don't do that, mostly
* because the card that I have uses a non-standard method of accessing
* the IRQs, and because this _should_ work in most configurations.
*
* Specifying an IRQ is done with the assumption that the user knows
* what (s)he is doing. No checking is done!!!!
*/
if (dev->irq < 1) {
int trials;
trials = 3;
while (trials--) {
dev->irq = smc_findirq(lp);
if (dev->irq)
break;
/* kick the card and try again */
smc_reset(dev);
}
}
if (dev->irq == 0) {
printk("%s: Couldn't autodetect your IRQ. Use irq=xx.\n",
dev->name);
retval = -ENODEV;
goto err_out;
}
dev->irq = irq_canonicalize(dev->irq);
/* Fill in the fields of the device structure with ethernet values. */
ether_setup(dev);
dev->watchdog_timeo = msecs_to_jiffies(watchdog);
dev->netdev_ops = &smc_netdev_ops;
dev->ethtool_ops = &smc_ethtool_ops;
tasklet_init(&lp->tx_task, smc_hardware_send_pkt, (unsigned long)dev);
INIT_WORK(&lp->phy_configure, smc_phy_configure);
lp->dev = dev;
lp->mii.phy_id_mask = 0x1f;
lp->mii.reg_num_mask = 0x1f;
lp->mii.force_media = 0;
lp->mii.full_duplex = 0;
lp->mii.dev = dev;
lp->mii.mdio_read = smc_phy_read;
lp->mii.mdio_write = smc_phy_write;
/*
* Locate the phy, if any.
*/
if (lp->version >= (CHIP_91100 << 4))
smc_phy_detect(dev);
/* then shut everything down to save power */
smc_shutdown(dev);
smc_phy_powerdown(dev);
/* Set default parameters */
lp->msg_enable = NETIF_MSG_LINK;
lp->ctl_rfduplx = 0;
lp->ctl_rspeed = 10;
if (lp->version >= (CHIP_91100 << 4)) {
lp->ctl_rfduplx = 1;
lp->ctl_rspeed = 100;
}
/* Grab the IRQ */
retval = request_irq(dev->irq, smc_interrupt, irq_flags, dev->name, dev);
if (retval)
goto err_out;
#ifdef CONFIG_ARCH_PXA
# ifdef SMC_USE_PXA_DMA
lp->cfg.flags |= SMC91X_USE_DMA;
# endif
if (lp->cfg.flags & SMC91X_USE_DMA) {
int dma = pxa_request_dma(dev->name, DMA_PRIO_LOW,
smc_pxa_dma_irq, NULL);
if (dma >= 0)
dev->dma = dma;
}
#endif
retval = register_netdev(dev);
if (retval == 0) {
/* now, print out the card info, in a short format.. */
printk("%s: %s (rev %d) at %p IRQ %d",
dev->name, version_string, revision_register & 0x0f,
lp->base, dev->irq);
if (dev->dma != (unsigned char)-1)
printk(" DMA %d", dev->dma);
printk("%s%s\n",
lp->cfg.flags & SMC91X_NOWAIT ? " [nowait]" : "",
THROTTLE_TX_PKTS ? " [throttle_tx]" : "");
if (!is_valid_ether_addr(dev->dev_addr)) {
printk("%s: Invalid ethernet MAC address. Please "
"set using ifconfig\n", dev->name);
} else {
/* Print the Ethernet address */
printk("%s: Ethernet addr: %pM\n",
dev->name, dev->dev_addr);
}
if (lp->phy_type == 0) {
PRINTK("%s: No PHY found\n", dev->name);
} else if ((lp->phy_type & 0xfffffff0) == 0x0016f840) {
PRINTK("%s: PHY LAN83C183 (LAN91C111 Internal)\n", dev->name);
} else if ((lp->phy_type & 0xfffffff0) == 0x02821c50) {
PRINTK("%s: PHY LAN83C180\n", dev->name);
}
}
err_out:
#ifdef CONFIG_ARCH_PXA
if (retval && dev->dma != (unsigned char)-1)
pxa_free_dma(dev->dma);
#endif
return retval;
}
static int smc_enable_device(struct platform_device *pdev)
{
struct net_device *ndev = platform_get_drvdata(pdev);
struct smc_local *lp = netdev_priv(ndev);
unsigned long flags;
unsigned char ecor, ecsr;
void __iomem *addr;
struct resource * res;
res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "smc91x-attrib");
if (!res)
return 0;
/*
* Map the attribute space. This is overkill, but clean.
*/
addr = ioremap(res->start, ATTRIB_SIZE);
if (!addr)
return -ENOMEM;
/*
* Reset the device. We must disable IRQs around this
* since a reset causes the IRQ line become active.
*/
local_irq_save(flags);
ecor = readb(addr + (ECOR << SMC_IO_SHIFT)) & ~ECOR_RESET;
writeb(ecor | ECOR_RESET, addr + (ECOR << SMC_IO_SHIFT));
readb(addr + (ECOR << SMC_IO_SHIFT));
/*
* Wait 100us for the chip to reset.
*/
udelay(100);
/*
* The device will ignore all writes to the enable bit while
* reset is asserted, even if the reset bit is cleared in the
* same write. Must clear reset first, then enable the device.
*/
writeb(ecor, addr + (ECOR << SMC_IO_SHIFT));
writeb(ecor | ECOR_ENABLE, addr + (ECOR << SMC_IO_SHIFT));
/*
* Set the appropriate byte/word mode.
*/
ecsr = readb(addr + (ECSR << SMC_IO_SHIFT)) & ~ECSR_IOIS8;
if (!SMC_16BIT(lp))
ecsr |= ECSR_IOIS8;
writeb(ecsr, addr + (ECSR << SMC_IO_SHIFT));
local_irq_restore(flags);
iounmap(addr);
/*
* Wait for the chip to wake up. We could poll the control
* register in the main register space, but that isn't mapped
* yet. We know this is going to take 750us.
*/
msleep(1);
return 0;
}
static int smc_request_attrib(struct platform_device *pdev,
struct net_device *ndev)
{
struct resource * res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "smc91x-attrib");
struct smc_local *lp __maybe_unused = netdev_priv(ndev);
if (!res)
return 0;
if (!request_mem_region(res->start, ATTRIB_SIZE, CARDNAME))
return -EBUSY;
return 0;
}
static void smc_release_attrib(struct platform_device *pdev,
struct net_device *ndev)
{
struct resource * res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "smc91x-attrib");
struct smc_local *lp __maybe_unused = netdev_priv(ndev);
if (res)
release_mem_region(res->start, ATTRIB_SIZE);
}
static inline void smc_request_datacs(struct platform_device *pdev, struct net_device *ndev)
{
if (SMC_CAN_USE_DATACS) {
struct resource * res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "smc91x-data32");
struct smc_local *lp = netdev_priv(ndev);
if (!res)
return;
if(!request_mem_region(res->start, SMC_DATA_EXTENT, CARDNAME)) {
printk(KERN_INFO "%s: failed to request datacs memory region.\n", CARDNAME);
return;
}
lp->datacs = ioremap(res->start, SMC_DATA_EXTENT);
}
}
static void smc_release_datacs(struct platform_device *pdev, struct net_device *ndev)
{
if (SMC_CAN_USE_DATACS) {
struct smc_local *lp = netdev_priv(ndev);
struct resource * res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "smc91x-data32");
if (lp->datacs)
iounmap(lp->datacs);
lp->datacs = NULL;
if (res)
release_mem_region(res->start, SMC_DATA_EXTENT);
}
}
/*
* smc_init(void)
* Input parameters:
* dev->base_addr == 0, try to find all possible locations
* dev->base_addr > 0x1ff, this is the address to check
* dev->base_addr == <anything else>, return failure code
*
* Output:
* 0 --> there is a device
* anything else, error
*/
static int __devinit smc_drv_probe(struct platform_device *pdev)
{
struct smc91x_platdata *pd = pdev->dev.platform_data;
struct smc_local *lp;
struct net_device *ndev;
struct resource *res, *ires;
unsigned int __iomem *addr;
unsigned long irq_flags = SMC_IRQ_FLAGS;
int ret;
ndev = alloc_etherdev(sizeof(struct smc_local));
if (!ndev) {
ret = -ENOMEM;
goto out;
}
SET_NETDEV_DEV(ndev, &pdev->dev);
/* get configuration from platform data, only allow use of
* bus width if both SMC_CAN_USE_xxx and SMC91X_USE_xxx are set.
*/
lp = netdev_priv(ndev);
if (pd) {
memcpy(&lp->cfg, pd, sizeof(lp->cfg));
lp->io_shift = SMC91X_IO_SHIFT(lp->cfg.flags);
} else {
lp->cfg.flags |= (SMC_CAN_USE_8BIT) ? SMC91X_USE_8BIT : 0;
lp->cfg.flags |= (SMC_CAN_USE_16BIT) ? SMC91X_USE_16BIT : 0;
lp->cfg.flags |= (SMC_CAN_USE_32BIT) ? SMC91X_USE_32BIT : 0;
lp->cfg.flags |= (nowait) ? SMC91X_NOWAIT : 0;
}
if (!lp->cfg.leda && !lp->cfg.ledb) {
lp->cfg.leda = RPC_LSA_DEFAULT;
lp->cfg.ledb = RPC_LSB_DEFAULT;
}
ndev->dma = (unsigned char)-1;
res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "smc91x-regs");
if (!res)
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
ret = -ENODEV;
goto out_free_netdev;
}
if (!request_mem_region(res->start, SMC_IO_EXTENT, CARDNAME)) {
ret = -EBUSY;
goto out_free_netdev;
}
ires = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (!ires) {
ret = -ENODEV;
goto out_release_io;
}
ndev->irq = ires->start;
if (irq_flags == -1 || ires->flags & IRQF_TRIGGER_MASK)
irq_flags = ires->flags & IRQF_TRIGGER_MASK;
ret = smc_request_attrib(pdev, ndev);
if (ret)
goto out_release_io;
#if defined(CONFIG_SA1100_ASSABET)
neponset_ncr_set(NCR_ENET_OSC_EN);
#endif
platform_set_drvdata(pdev, ndev);
ret = smc_enable_device(pdev);
if (ret)
goto out_release_attrib;
addr = ioremap(res->start, SMC_IO_EXTENT);
if (!addr) {
ret = -ENOMEM;
goto out_release_attrib;
}
#ifdef CONFIG_ARCH_PXA
{
struct smc_local *lp = netdev_priv(ndev);
lp->device = &pdev->dev;
lp->physaddr = res->start;
}
#endif
ret = smc_probe(ndev, addr, irq_flags);
if (ret != 0)
goto out_iounmap;
smc_request_datacs(pdev, ndev);
return 0;
out_iounmap:
platform_set_drvdata(pdev, NULL);
iounmap(addr);
out_release_attrib:
smc_release_attrib(pdev, ndev);
out_release_io:
release_mem_region(res->start, SMC_IO_EXTENT);
out_free_netdev:
free_netdev(ndev);
out:
printk("%s: not found (%d).\n", CARDNAME, ret);
return ret;
}
static int __devexit smc_drv_remove(struct platform_device *pdev)
{
struct net_device *ndev = platform_get_drvdata(pdev);
struct smc_local *lp = netdev_priv(ndev);
struct resource *res;
platform_set_drvdata(pdev, NULL);
unregister_netdev(ndev);
free_irq(ndev->irq, ndev);
#ifdef CONFIG_ARCH_PXA
if (ndev->dma != (unsigned char)-1)
pxa_free_dma(ndev->dma);
#endif
iounmap(lp->base);
smc_release_datacs(pdev,ndev);
smc_release_attrib(pdev,ndev);
res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "smc91x-regs");
if (!res)
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
release_mem_region(res->start, SMC_IO_EXTENT);
free_netdev(ndev);
return 0;
}
static int smc_drv_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct net_device *ndev = platform_get_drvdata(pdev);
if (ndev) {
if (netif_running(ndev)) {
netif_device_detach(ndev);
smc_shutdown(ndev);
smc_phy_powerdown(ndev);
}
}
return 0;
}
static int smc_drv_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct net_device *ndev = platform_get_drvdata(pdev);
if (ndev) {
struct smc_local *lp = netdev_priv(ndev);
smc_enable_device(pdev);
if (netif_running(ndev)) {
smc_reset(ndev);
smc_enable(ndev);
if (lp->phy_type != 0)
smc_phy_configure(&lp->phy_configure);
netif_device_attach(ndev);
}
}
return 0;
}
#ifdef CONFIG_OF
static const struct of_device_id smc91x_match[] = {
{ .compatible = "smsc,lan91c94", },
{ .compatible = "smsc,lan91c111", },
{},
};
MODULE_DEVICE_TABLE(of, smc91x_match);
#else
#define smc91x_match NULL
#endif
static struct dev_pm_ops smc_drv_pm_ops = {
.suspend = smc_drv_suspend,
.resume = smc_drv_resume,
};
static struct platform_driver smc_driver = {
.probe = smc_drv_probe,
.remove = __devexit_p(smc_drv_remove),
.driver = {
.name = CARDNAME,
.owner = THIS_MODULE,
.pm = &smc_drv_pm_ops,
.of_match_table = smc91x_match,
},
};
module_platform_driver(smc_driver);
| gpl-2.0 |
SlimRoms/kernel_samsung_jf | drivers/usb/gadget/pch_udc.c | 4773 | 91855 | /*
* Copyright (C) 2011 LAPIS Semiconductor 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; version 2 of the License.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/list.h>
#include <linux/interrupt.h>
#include <linux/usb/ch9.h>
#include <linux/usb/gadget.h>
#include <linux/gpio.h>
#include <linux/irq.h>
/* GPIO port for VBUS detecting */
static int vbus_gpio_port = -1; /* GPIO port number (-1:Not used) */
#define PCH_VBUS_PERIOD 3000 /* VBUS polling period (msec) */
#define PCH_VBUS_INTERVAL 10 /* VBUS polling interval (msec) */
/* Address offset of Registers */
#define UDC_EP_REG_SHIFT 0x20 /* Offset to next EP */
#define UDC_EPCTL_ADDR 0x00 /* Endpoint control */
#define UDC_EPSTS_ADDR 0x04 /* Endpoint status */
#define UDC_BUFIN_FRAMENUM_ADDR 0x08 /* buffer size in / frame number out */
#define UDC_BUFOUT_MAXPKT_ADDR 0x0C /* buffer size out / maxpkt in */
#define UDC_SUBPTR_ADDR 0x10 /* setup buffer pointer */
#define UDC_DESPTR_ADDR 0x14 /* Data descriptor pointer */
#define UDC_CONFIRM_ADDR 0x18 /* Write/Read confirmation */
#define UDC_DEVCFG_ADDR 0x400 /* Device configuration */
#define UDC_DEVCTL_ADDR 0x404 /* Device control */
#define UDC_DEVSTS_ADDR 0x408 /* Device status */
#define UDC_DEVIRQSTS_ADDR 0x40C /* Device irq status */
#define UDC_DEVIRQMSK_ADDR 0x410 /* Device irq mask */
#define UDC_EPIRQSTS_ADDR 0x414 /* Endpoint irq status */
#define UDC_EPIRQMSK_ADDR 0x418 /* Endpoint irq mask */
#define UDC_DEVLPM_ADDR 0x41C /* LPM control / status */
#define UDC_CSR_BUSY_ADDR 0x4f0 /* UDC_CSR_BUSY Status register */
#define UDC_SRST_ADDR 0x4fc /* SOFT RESET register */
#define UDC_CSR_ADDR 0x500 /* USB_DEVICE endpoint register */
/* Endpoint control register */
/* Bit position */
#define UDC_EPCTL_MRXFLUSH (1 << 12)
#define UDC_EPCTL_RRDY (1 << 9)
#define UDC_EPCTL_CNAK (1 << 8)
#define UDC_EPCTL_SNAK (1 << 7)
#define UDC_EPCTL_NAK (1 << 6)
#define UDC_EPCTL_P (1 << 3)
#define UDC_EPCTL_F (1 << 1)
#define UDC_EPCTL_S (1 << 0)
#define UDC_EPCTL_ET_SHIFT 4
/* Mask patern */
#define UDC_EPCTL_ET_MASK 0x00000030
/* Value for ET field */
#define UDC_EPCTL_ET_CONTROL 0
#define UDC_EPCTL_ET_ISO 1
#define UDC_EPCTL_ET_BULK 2
#define UDC_EPCTL_ET_INTERRUPT 3
/* Endpoint status register */
/* Bit position */
#define UDC_EPSTS_XFERDONE (1 << 27)
#define UDC_EPSTS_RSS (1 << 26)
#define UDC_EPSTS_RCS (1 << 25)
#define UDC_EPSTS_TXEMPTY (1 << 24)
#define UDC_EPSTS_TDC (1 << 10)
#define UDC_EPSTS_HE (1 << 9)
#define UDC_EPSTS_MRXFIFO_EMP (1 << 8)
#define UDC_EPSTS_BNA (1 << 7)
#define UDC_EPSTS_IN (1 << 6)
#define UDC_EPSTS_OUT_SHIFT 4
/* Mask patern */
#define UDC_EPSTS_OUT_MASK 0x00000030
#define UDC_EPSTS_ALL_CLR_MASK 0x1F0006F0
/* Value for OUT field */
#define UDC_EPSTS_OUT_SETUP 2
#define UDC_EPSTS_OUT_DATA 1
/* Device configuration register */
/* Bit position */
#define UDC_DEVCFG_CSR_PRG (1 << 17)
#define UDC_DEVCFG_SP (1 << 3)
/* SPD Valee */
#define UDC_DEVCFG_SPD_HS 0x0
#define UDC_DEVCFG_SPD_FS 0x1
#define UDC_DEVCFG_SPD_LS 0x2
/* Device control register */
/* Bit position */
#define UDC_DEVCTL_THLEN_SHIFT 24
#define UDC_DEVCTL_BRLEN_SHIFT 16
#define UDC_DEVCTL_CSR_DONE (1 << 13)
#define UDC_DEVCTL_SD (1 << 10)
#define UDC_DEVCTL_MODE (1 << 9)
#define UDC_DEVCTL_BREN (1 << 8)
#define UDC_DEVCTL_THE (1 << 7)
#define UDC_DEVCTL_DU (1 << 4)
#define UDC_DEVCTL_TDE (1 << 3)
#define UDC_DEVCTL_RDE (1 << 2)
#define UDC_DEVCTL_RES (1 << 0)
/* Device status register */
/* Bit position */
#define UDC_DEVSTS_TS_SHIFT 18
#define UDC_DEVSTS_ENUM_SPEED_SHIFT 13
#define UDC_DEVSTS_ALT_SHIFT 8
#define UDC_DEVSTS_INTF_SHIFT 4
#define UDC_DEVSTS_CFG_SHIFT 0
/* Mask patern */
#define UDC_DEVSTS_TS_MASK 0xfffc0000
#define UDC_DEVSTS_ENUM_SPEED_MASK 0x00006000
#define UDC_DEVSTS_ALT_MASK 0x00000f00
#define UDC_DEVSTS_INTF_MASK 0x000000f0
#define UDC_DEVSTS_CFG_MASK 0x0000000f
/* value for maximum speed for SPEED field */
#define UDC_DEVSTS_ENUM_SPEED_FULL 1
#define UDC_DEVSTS_ENUM_SPEED_HIGH 0
#define UDC_DEVSTS_ENUM_SPEED_LOW 2
#define UDC_DEVSTS_ENUM_SPEED_FULLX 3
/* Device irq register */
/* Bit position */
#define UDC_DEVINT_RWKP (1 << 7)
#define UDC_DEVINT_ENUM (1 << 6)
#define UDC_DEVINT_SOF (1 << 5)
#define UDC_DEVINT_US (1 << 4)
#define UDC_DEVINT_UR (1 << 3)
#define UDC_DEVINT_ES (1 << 2)
#define UDC_DEVINT_SI (1 << 1)
#define UDC_DEVINT_SC (1 << 0)
/* Mask patern */
#define UDC_DEVINT_MSK 0x7f
/* Endpoint irq register */
/* Bit position */
#define UDC_EPINT_IN_SHIFT 0
#define UDC_EPINT_OUT_SHIFT 16
#define UDC_EPINT_IN_EP0 (1 << 0)
#define UDC_EPINT_OUT_EP0 (1 << 16)
/* Mask patern */
#define UDC_EPINT_MSK_DISABLE_ALL 0xffffffff
/* UDC_CSR_BUSY Status register */
/* Bit position */
#define UDC_CSR_BUSY (1 << 0)
/* SOFT RESET register */
/* Bit position */
#define UDC_PSRST (1 << 1)
#define UDC_SRST (1 << 0)
/* USB_DEVICE endpoint register */
/* Bit position */
#define UDC_CSR_NE_NUM_SHIFT 0
#define UDC_CSR_NE_DIR_SHIFT 4
#define UDC_CSR_NE_TYPE_SHIFT 5
#define UDC_CSR_NE_CFG_SHIFT 7
#define UDC_CSR_NE_INTF_SHIFT 11
#define UDC_CSR_NE_ALT_SHIFT 15
#define UDC_CSR_NE_MAX_PKT_SHIFT 19
/* Mask patern */
#define UDC_CSR_NE_NUM_MASK 0x0000000f
#define UDC_CSR_NE_DIR_MASK 0x00000010
#define UDC_CSR_NE_TYPE_MASK 0x00000060
#define UDC_CSR_NE_CFG_MASK 0x00000780
#define UDC_CSR_NE_INTF_MASK 0x00007800
#define UDC_CSR_NE_ALT_MASK 0x00078000
#define UDC_CSR_NE_MAX_PKT_MASK 0x3ff80000
#define PCH_UDC_CSR(ep) (UDC_CSR_ADDR + ep*4)
#define PCH_UDC_EPINT(in, num)\
(1 << (num + (in ? UDC_EPINT_IN_SHIFT : UDC_EPINT_OUT_SHIFT)))
/* Index of endpoint */
#define UDC_EP0IN_IDX 0
#define UDC_EP0OUT_IDX 1
#define UDC_EPIN_IDX(ep) (ep * 2)
#define UDC_EPOUT_IDX(ep) (ep * 2 + 1)
#define PCH_UDC_EP0 0
#define PCH_UDC_EP1 1
#define PCH_UDC_EP2 2
#define PCH_UDC_EP3 3
/* Number of endpoint */
#define PCH_UDC_EP_NUM 32 /* Total number of EPs (16 IN,16 OUT) */
#define PCH_UDC_USED_EP_NUM 4 /* EP number of EP's really used */
/* Length Value */
#define PCH_UDC_BRLEN 0x0F /* Burst length */
#define PCH_UDC_THLEN 0x1F /* Threshold length */
/* Value of EP Buffer Size */
#define UDC_EP0IN_BUFF_SIZE 16
#define UDC_EPIN_BUFF_SIZE 256
#define UDC_EP0OUT_BUFF_SIZE 16
#define UDC_EPOUT_BUFF_SIZE 256
/* Value of EP maximum packet size */
#define UDC_EP0IN_MAX_PKT_SIZE 64
#define UDC_EP0OUT_MAX_PKT_SIZE 64
#define UDC_BULK_MAX_PKT_SIZE 512
/* DMA */
#define DMA_DIR_RX 1 /* DMA for data receive */
#define DMA_DIR_TX 2 /* DMA for data transmit */
#define DMA_ADDR_INVALID (~(dma_addr_t)0)
#define UDC_DMA_MAXPACKET 65536 /* maximum packet size for DMA */
/**
* struct pch_udc_data_dma_desc - Structure to hold DMA descriptor information
* for data
* @status: Status quadlet
* @reserved: Reserved
* @dataptr: Buffer descriptor
* @next: Next descriptor
*/
struct pch_udc_data_dma_desc {
u32 status;
u32 reserved;
u32 dataptr;
u32 next;
};
/**
* struct pch_udc_stp_dma_desc - Structure to hold DMA descriptor information
* for control data
* @status: Status
* @reserved: Reserved
* @data12: First setup word
* @data34: Second setup word
*/
struct pch_udc_stp_dma_desc {
u32 status;
u32 reserved;
struct usb_ctrlrequest request;
} __attribute((packed));
/* DMA status definitions */
/* Buffer status */
#define PCH_UDC_BUFF_STS 0xC0000000
#define PCH_UDC_BS_HST_RDY 0x00000000
#define PCH_UDC_BS_DMA_BSY 0x40000000
#define PCH_UDC_BS_DMA_DONE 0x80000000
#define PCH_UDC_BS_HST_BSY 0xC0000000
/* Rx/Tx Status */
#define PCH_UDC_RXTX_STS 0x30000000
#define PCH_UDC_RTS_SUCC 0x00000000
#define PCH_UDC_RTS_DESERR 0x10000000
#define PCH_UDC_RTS_BUFERR 0x30000000
/* Last Descriptor Indication */
#define PCH_UDC_DMA_LAST 0x08000000
/* Number of Rx/Tx Bytes Mask */
#define PCH_UDC_RXTX_BYTES 0x0000ffff
/**
* struct pch_udc_cfg_data - Structure to hold current configuration
* and interface information
* @cur_cfg: current configuration in use
* @cur_intf: current interface in use
* @cur_alt: current alt interface in use
*/
struct pch_udc_cfg_data {
u16 cur_cfg;
u16 cur_intf;
u16 cur_alt;
};
/**
* struct pch_udc_ep - Structure holding a PCH USB device Endpoint information
* @ep: embedded ep request
* @td_stp_phys: for setup request
* @td_data_phys: for data request
* @td_stp: for setup request
* @td_data: for data request
* @dev: reference to device struct
* @offset_addr: offset address of ep register
* @desc: for this ep
* @queue: queue for requests
* @num: endpoint number
* @in: endpoint is IN
* @halted: endpoint halted?
* @epsts: Endpoint status
*/
struct pch_udc_ep {
struct usb_ep ep;
dma_addr_t td_stp_phys;
dma_addr_t td_data_phys;
struct pch_udc_stp_dma_desc *td_stp;
struct pch_udc_data_dma_desc *td_data;
struct pch_udc_dev *dev;
unsigned long offset_addr;
const struct usb_endpoint_descriptor *desc;
struct list_head queue;
unsigned num:5,
in:1,
halted:1;
unsigned long epsts;
};
/**
* struct pch_vbus_gpio_data - Structure holding GPIO informaton
* for detecting VBUS
* @port: gpio port number
* @intr: gpio interrupt number
* @irq_work_fall Structure for WorkQueue
* @irq_work_rise Structure for WorkQueue
*/
struct pch_vbus_gpio_data {
int port;
int intr;
struct work_struct irq_work_fall;
struct work_struct irq_work_rise;
};
/**
* struct pch_udc_dev - Structure holding complete information
* of the PCH USB device
* @gadget: gadget driver data
* @driver: reference to gadget driver bound
* @pdev: reference to the PCI device
* @ep: array of endpoints
* @lock: protects all state
* @active: enabled the PCI device
* @stall: stall requested
* @prot_stall: protcol stall requested
* @irq_registered: irq registered with system
* @mem_region: device memory mapped
* @registered: driver regsitered with system
* @suspended: driver in suspended state
* @connected: gadget driver associated
* @vbus_session: required vbus_session state
* @set_cfg_not_acked: pending acknowledgement 4 setup
* @waiting_zlp_ack: pending acknowledgement 4 ZLP
* @data_requests: DMA pool for data requests
* @stp_requests: DMA pool for setup requests
* @dma_addr: DMA pool for received
* @ep0out_buf: Buffer for DMA
* @setup_data: Received setup data
* @phys_addr: of device memory
* @base_addr: for mapped device memory
* @irq: IRQ line for the device
* @cfg_data: current cfg, intf, and alt in use
* @vbus_gpio: GPIO informaton for detecting VBUS
*/
struct pch_udc_dev {
struct usb_gadget gadget;
struct usb_gadget_driver *driver;
struct pci_dev *pdev;
struct pch_udc_ep ep[PCH_UDC_EP_NUM];
spinlock_t lock; /* protects all state */
unsigned active:1,
stall:1,
prot_stall:1,
irq_registered:1,
mem_region:1,
registered:1,
suspended:1,
connected:1,
vbus_session:1,
set_cfg_not_acked:1,
waiting_zlp_ack:1;
struct pci_pool *data_requests;
struct pci_pool *stp_requests;
dma_addr_t dma_addr;
void *ep0out_buf;
struct usb_ctrlrequest setup_data;
unsigned long phys_addr;
void __iomem *base_addr;
unsigned irq;
struct pch_udc_cfg_data cfg_data;
struct pch_vbus_gpio_data vbus_gpio;
};
#define PCH_UDC_PCI_BAR 1
#define PCI_DEVICE_ID_INTEL_EG20T_UDC 0x8808
#define PCI_VENDOR_ID_ROHM 0x10DB
#define PCI_DEVICE_ID_ML7213_IOH_UDC 0x801D
#define PCI_DEVICE_ID_ML7831_IOH_UDC 0x8808
static const char ep0_string[] = "ep0in";
static DEFINE_SPINLOCK(udc_stall_spinlock); /* stall spin lock */
struct pch_udc_dev *pch_udc; /* pointer to device object */
static bool speed_fs;
module_param_named(speed_fs, speed_fs, bool, S_IRUGO);
MODULE_PARM_DESC(speed_fs, "true for Full speed operation");
/**
* struct pch_udc_request - Structure holding a PCH USB device request packet
* @req: embedded ep request
* @td_data_phys: phys. address
* @td_data: first dma desc. of chain
* @td_data_last: last dma desc. of chain
* @queue: associated queue
* @dma_going: DMA in progress for request
* @dma_mapped: DMA memory mapped for request
* @dma_done: DMA completed for request
* @chain_len: chain length
* @buf: Buffer memory for align adjustment
* @dma: DMA memory for align adjustment
*/
struct pch_udc_request {
struct usb_request req;
dma_addr_t td_data_phys;
struct pch_udc_data_dma_desc *td_data;
struct pch_udc_data_dma_desc *td_data_last;
struct list_head queue;
unsigned dma_going:1,
dma_mapped:1,
dma_done:1;
unsigned chain_len;
void *buf;
dma_addr_t dma;
};
static inline u32 pch_udc_readl(struct pch_udc_dev *dev, unsigned long reg)
{
return ioread32(dev->base_addr + reg);
}
static inline void pch_udc_writel(struct pch_udc_dev *dev,
unsigned long val, unsigned long reg)
{
iowrite32(val, dev->base_addr + reg);
}
static inline void pch_udc_bit_set(struct pch_udc_dev *dev,
unsigned long reg,
unsigned long bitmask)
{
pch_udc_writel(dev, pch_udc_readl(dev, reg) | bitmask, reg);
}
static inline void pch_udc_bit_clr(struct pch_udc_dev *dev,
unsigned long reg,
unsigned long bitmask)
{
pch_udc_writel(dev, pch_udc_readl(dev, reg) & ~(bitmask), reg);
}
static inline u32 pch_udc_ep_readl(struct pch_udc_ep *ep, unsigned long reg)
{
return ioread32(ep->dev->base_addr + ep->offset_addr + reg);
}
static inline void pch_udc_ep_writel(struct pch_udc_ep *ep,
unsigned long val, unsigned long reg)
{
iowrite32(val, ep->dev->base_addr + ep->offset_addr + reg);
}
static inline void pch_udc_ep_bit_set(struct pch_udc_ep *ep,
unsigned long reg,
unsigned long bitmask)
{
pch_udc_ep_writel(ep, pch_udc_ep_readl(ep, reg) | bitmask, reg);
}
static inline void pch_udc_ep_bit_clr(struct pch_udc_ep *ep,
unsigned long reg,
unsigned long bitmask)
{
pch_udc_ep_writel(ep, pch_udc_ep_readl(ep, reg) & ~(bitmask), reg);
}
/**
* pch_udc_csr_busy() - Wait till idle.
* @dev: Reference to pch_udc_dev structure
*/
static void pch_udc_csr_busy(struct pch_udc_dev *dev)
{
unsigned int count = 200;
/* Wait till idle */
while ((pch_udc_readl(dev, UDC_CSR_BUSY_ADDR) & UDC_CSR_BUSY)
&& --count)
cpu_relax();
if (!count)
dev_err(&dev->pdev->dev, "%s: wait error\n", __func__);
}
/**
* pch_udc_write_csr() - Write the command and status registers.
* @dev: Reference to pch_udc_dev structure
* @val: value to be written to CSR register
* @addr: address of CSR register
*/
static void pch_udc_write_csr(struct pch_udc_dev *dev, unsigned long val,
unsigned int ep)
{
unsigned long reg = PCH_UDC_CSR(ep);
pch_udc_csr_busy(dev); /* Wait till idle */
pch_udc_writel(dev, val, reg);
pch_udc_csr_busy(dev); /* Wait till idle */
}
/**
* pch_udc_read_csr() - Read the command and status registers.
* @dev: Reference to pch_udc_dev structure
* @addr: address of CSR register
*
* Return codes: content of CSR register
*/
static u32 pch_udc_read_csr(struct pch_udc_dev *dev, unsigned int ep)
{
unsigned long reg = PCH_UDC_CSR(ep);
pch_udc_csr_busy(dev); /* Wait till idle */
pch_udc_readl(dev, reg); /* Dummy read */
pch_udc_csr_busy(dev); /* Wait till idle */
return pch_udc_readl(dev, reg);
}
/**
* pch_udc_rmt_wakeup() - Initiate for remote wakeup
* @dev: Reference to pch_udc_dev structure
*/
static inline void pch_udc_rmt_wakeup(struct pch_udc_dev *dev)
{
pch_udc_bit_set(dev, UDC_DEVCTL_ADDR, UDC_DEVCTL_RES);
mdelay(1);
pch_udc_bit_clr(dev, UDC_DEVCTL_ADDR, UDC_DEVCTL_RES);
}
/**
* pch_udc_get_frame() - Get the current frame from device status register
* @dev: Reference to pch_udc_dev structure
* Retern current frame
*/
static inline int pch_udc_get_frame(struct pch_udc_dev *dev)
{
u32 frame = pch_udc_readl(dev, UDC_DEVSTS_ADDR);
return (frame & UDC_DEVSTS_TS_MASK) >> UDC_DEVSTS_TS_SHIFT;
}
/**
* pch_udc_clear_selfpowered() - Clear the self power control
* @dev: Reference to pch_udc_regs structure
*/
static inline void pch_udc_clear_selfpowered(struct pch_udc_dev *dev)
{
pch_udc_bit_clr(dev, UDC_DEVCFG_ADDR, UDC_DEVCFG_SP);
}
/**
* pch_udc_set_selfpowered() - Set the self power control
* @dev: Reference to pch_udc_regs structure
*/
static inline void pch_udc_set_selfpowered(struct pch_udc_dev *dev)
{
pch_udc_bit_set(dev, UDC_DEVCFG_ADDR, UDC_DEVCFG_SP);
}
/**
* pch_udc_set_disconnect() - Set the disconnect status.
* @dev: Reference to pch_udc_regs structure
*/
static inline void pch_udc_set_disconnect(struct pch_udc_dev *dev)
{
pch_udc_bit_set(dev, UDC_DEVCTL_ADDR, UDC_DEVCTL_SD);
}
/**
* pch_udc_clear_disconnect() - Clear the disconnect status.
* @dev: Reference to pch_udc_regs structure
*/
static void pch_udc_clear_disconnect(struct pch_udc_dev *dev)
{
/* Clear the disconnect */
pch_udc_bit_set(dev, UDC_DEVCTL_ADDR, UDC_DEVCTL_RES);
pch_udc_bit_clr(dev, UDC_DEVCTL_ADDR, UDC_DEVCTL_SD);
mdelay(1);
/* Resume USB signalling */
pch_udc_bit_clr(dev, UDC_DEVCTL_ADDR, UDC_DEVCTL_RES);
}
/**
* pch_udc_reconnect() - This API initializes usb device controller,
* and clear the disconnect status.
* @dev: Reference to pch_udc_regs structure
*/
static void pch_udc_init(struct pch_udc_dev *dev);
static void pch_udc_reconnect(struct pch_udc_dev *dev)
{
pch_udc_init(dev);
/* enable device interrupts */
/* pch_udc_enable_interrupts() */
pch_udc_bit_clr(dev, UDC_DEVIRQMSK_ADDR,
UDC_DEVINT_UR | UDC_DEVINT_ENUM);
/* Clear the disconnect */
pch_udc_bit_set(dev, UDC_DEVCTL_ADDR, UDC_DEVCTL_RES);
pch_udc_bit_clr(dev, UDC_DEVCTL_ADDR, UDC_DEVCTL_SD);
mdelay(1);
/* Resume USB signalling */
pch_udc_bit_clr(dev, UDC_DEVCTL_ADDR, UDC_DEVCTL_RES);
}
/**
* pch_udc_vbus_session() - set or clearr the disconnect status.
* @dev: Reference to pch_udc_regs structure
* @is_active: Parameter specifying the action
* 0: indicating VBUS power is ending
* !0: indicating VBUS power is starting
*/
static inline void pch_udc_vbus_session(struct pch_udc_dev *dev,
int is_active)
{
if (is_active) {
pch_udc_reconnect(dev);
dev->vbus_session = 1;
} else {
if (dev->driver && dev->driver->disconnect) {
spin_unlock(&dev->lock);
dev->driver->disconnect(&dev->gadget);
spin_lock(&dev->lock);
}
pch_udc_set_disconnect(dev);
dev->vbus_session = 0;
}
}
/**
* pch_udc_ep_set_stall() - Set the stall of endpoint
* @ep: Reference to structure of type pch_udc_ep_regs
*/
static void pch_udc_ep_set_stall(struct pch_udc_ep *ep)
{
if (ep->in) {
pch_udc_ep_bit_set(ep, UDC_EPCTL_ADDR, UDC_EPCTL_F);
pch_udc_ep_bit_set(ep, UDC_EPCTL_ADDR, UDC_EPCTL_S);
} else {
pch_udc_ep_bit_set(ep, UDC_EPCTL_ADDR, UDC_EPCTL_S);
}
}
/**
* pch_udc_ep_clear_stall() - Clear the stall of endpoint
* @ep: Reference to structure of type pch_udc_ep_regs
*/
static inline void pch_udc_ep_clear_stall(struct pch_udc_ep *ep)
{
/* Clear the stall */
pch_udc_ep_bit_clr(ep, UDC_EPCTL_ADDR, UDC_EPCTL_S);
/* Clear NAK by writing CNAK */
pch_udc_ep_bit_set(ep, UDC_EPCTL_ADDR, UDC_EPCTL_CNAK);
}
/**
* pch_udc_ep_set_trfr_type() - Set the transfer type of endpoint
* @ep: Reference to structure of type pch_udc_ep_regs
* @type: Type of endpoint
*/
static inline void pch_udc_ep_set_trfr_type(struct pch_udc_ep *ep,
u8 type)
{
pch_udc_ep_writel(ep, ((type << UDC_EPCTL_ET_SHIFT) &
UDC_EPCTL_ET_MASK), UDC_EPCTL_ADDR);
}
/**
* pch_udc_ep_set_bufsz() - Set the maximum packet size for the endpoint
* @ep: Reference to structure of type pch_udc_ep_regs
* @buf_size: The buffer word size
*/
static void pch_udc_ep_set_bufsz(struct pch_udc_ep *ep,
u32 buf_size, u32 ep_in)
{
u32 data;
if (ep_in) {
data = pch_udc_ep_readl(ep, UDC_BUFIN_FRAMENUM_ADDR);
data = (data & 0xffff0000) | (buf_size & 0xffff);
pch_udc_ep_writel(ep, data, UDC_BUFIN_FRAMENUM_ADDR);
} else {
data = pch_udc_ep_readl(ep, UDC_BUFOUT_MAXPKT_ADDR);
data = (buf_size << 16) | (data & 0xffff);
pch_udc_ep_writel(ep, data, UDC_BUFOUT_MAXPKT_ADDR);
}
}
/**
* pch_udc_ep_set_maxpkt() - Set the Max packet size for the endpoint
* @ep: Reference to structure of type pch_udc_ep_regs
* @pkt_size: The packet byte size
*/
static void pch_udc_ep_set_maxpkt(struct pch_udc_ep *ep, u32 pkt_size)
{
u32 data = pch_udc_ep_readl(ep, UDC_BUFOUT_MAXPKT_ADDR);
data = (data & 0xffff0000) | (pkt_size & 0xffff);
pch_udc_ep_writel(ep, data, UDC_BUFOUT_MAXPKT_ADDR);
}
/**
* pch_udc_ep_set_subptr() - Set the Setup buffer pointer for the endpoint
* @ep: Reference to structure of type pch_udc_ep_regs
* @addr: Address of the register
*/
static inline void pch_udc_ep_set_subptr(struct pch_udc_ep *ep, u32 addr)
{
pch_udc_ep_writel(ep, addr, UDC_SUBPTR_ADDR);
}
/**
* pch_udc_ep_set_ddptr() - Set the Data descriptor pointer for the endpoint
* @ep: Reference to structure of type pch_udc_ep_regs
* @addr: Address of the register
*/
static inline void pch_udc_ep_set_ddptr(struct pch_udc_ep *ep, u32 addr)
{
pch_udc_ep_writel(ep, addr, UDC_DESPTR_ADDR);
}
/**
* pch_udc_ep_set_pd() - Set the poll demand bit for the endpoint
* @ep: Reference to structure of type pch_udc_ep_regs
*/
static inline void pch_udc_ep_set_pd(struct pch_udc_ep *ep)
{
pch_udc_ep_bit_set(ep, UDC_EPCTL_ADDR, UDC_EPCTL_P);
}
/**
* pch_udc_ep_set_rrdy() - Set the receive ready bit for the endpoint
* @ep: Reference to structure of type pch_udc_ep_regs
*/
static inline void pch_udc_ep_set_rrdy(struct pch_udc_ep *ep)
{
pch_udc_ep_bit_set(ep, UDC_EPCTL_ADDR, UDC_EPCTL_RRDY);
}
/**
* pch_udc_ep_clear_rrdy() - Clear the receive ready bit for the endpoint
* @ep: Reference to structure of type pch_udc_ep_regs
*/
static inline void pch_udc_ep_clear_rrdy(struct pch_udc_ep *ep)
{
pch_udc_ep_bit_clr(ep, UDC_EPCTL_ADDR, UDC_EPCTL_RRDY);
}
/**
* pch_udc_set_dma() - Set the 'TDE' or RDE bit of device control
* register depending on the direction specified
* @dev: Reference to structure of type pch_udc_regs
* @dir: whether Tx or Rx
* DMA_DIR_RX: Receive
* DMA_DIR_TX: Transmit
*/
static inline void pch_udc_set_dma(struct pch_udc_dev *dev, int dir)
{
if (dir == DMA_DIR_RX)
pch_udc_bit_set(dev, UDC_DEVCTL_ADDR, UDC_DEVCTL_RDE);
else if (dir == DMA_DIR_TX)
pch_udc_bit_set(dev, UDC_DEVCTL_ADDR, UDC_DEVCTL_TDE);
}
/**
* pch_udc_clear_dma() - Clear the 'TDE' or RDE bit of device control
* register depending on the direction specified
* @dev: Reference to structure of type pch_udc_regs
* @dir: Whether Tx or Rx
* DMA_DIR_RX: Receive
* DMA_DIR_TX: Transmit
*/
static inline void pch_udc_clear_dma(struct pch_udc_dev *dev, int dir)
{
if (dir == DMA_DIR_RX)
pch_udc_bit_clr(dev, UDC_DEVCTL_ADDR, UDC_DEVCTL_RDE);
else if (dir == DMA_DIR_TX)
pch_udc_bit_clr(dev, UDC_DEVCTL_ADDR, UDC_DEVCTL_TDE);
}
/**
* pch_udc_set_csr_done() - Set the device control register
* CSR done field (bit 13)
* @dev: reference to structure of type pch_udc_regs
*/
static inline void pch_udc_set_csr_done(struct pch_udc_dev *dev)
{
pch_udc_bit_set(dev, UDC_DEVCTL_ADDR, UDC_DEVCTL_CSR_DONE);
}
/**
* pch_udc_disable_interrupts() - Disables the specified interrupts
* @dev: Reference to structure of type pch_udc_regs
* @mask: Mask to disable interrupts
*/
static inline void pch_udc_disable_interrupts(struct pch_udc_dev *dev,
u32 mask)
{
pch_udc_bit_set(dev, UDC_DEVIRQMSK_ADDR, mask);
}
/**
* pch_udc_enable_interrupts() - Enable the specified interrupts
* @dev: Reference to structure of type pch_udc_regs
* @mask: Mask to enable interrupts
*/
static inline void pch_udc_enable_interrupts(struct pch_udc_dev *dev,
u32 mask)
{
pch_udc_bit_clr(dev, UDC_DEVIRQMSK_ADDR, mask);
}
/**
* pch_udc_disable_ep_interrupts() - Disable endpoint interrupts
* @dev: Reference to structure of type pch_udc_regs
* @mask: Mask to disable interrupts
*/
static inline void pch_udc_disable_ep_interrupts(struct pch_udc_dev *dev,
u32 mask)
{
pch_udc_bit_set(dev, UDC_EPIRQMSK_ADDR, mask);
}
/**
* pch_udc_enable_ep_interrupts() - Enable endpoint interrupts
* @dev: Reference to structure of type pch_udc_regs
* @mask: Mask to enable interrupts
*/
static inline void pch_udc_enable_ep_interrupts(struct pch_udc_dev *dev,
u32 mask)
{
pch_udc_bit_clr(dev, UDC_EPIRQMSK_ADDR, mask);
}
/**
* pch_udc_read_device_interrupts() - Read the device interrupts
* @dev: Reference to structure of type pch_udc_regs
* Retern The device interrupts
*/
static inline u32 pch_udc_read_device_interrupts(struct pch_udc_dev *dev)
{
return pch_udc_readl(dev, UDC_DEVIRQSTS_ADDR);
}
/**
* pch_udc_write_device_interrupts() - Write device interrupts
* @dev: Reference to structure of type pch_udc_regs
* @val: The value to be written to interrupt register
*/
static inline void pch_udc_write_device_interrupts(struct pch_udc_dev *dev,
u32 val)
{
pch_udc_writel(dev, val, UDC_DEVIRQSTS_ADDR);
}
/**
* pch_udc_read_ep_interrupts() - Read the endpoint interrupts
* @dev: Reference to structure of type pch_udc_regs
* Retern The endpoint interrupt
*/
static inline u32 pch_udc_read_ep_interrupts(struct pch_udc_dev *dev)
{
return pch_udc_readl(dev, UDC_EPIRQSTS_ADDR);
}
/**
* pch_udc_write_ep_interrupts() - Clear endpoint interupts
* @dev: Reference to structure of type pch_udc_regs
* @val: The value to be written to interrupt register
*/
static inline void pch_udc_write_ep_interrupts(struct pch_udc_dev *dev,
u32 val)
{
pch_udc_writel(dev, val, UDC_EPIRQSTS_ADDR);
}
/**
* pch_udc_read_device_status() - Read the device status
* @dev: Reference to structure of type pch_udc_regs
* Retern The device status
*/
static inline u32 pch_udc_read_device_status(struct pch_udc_dev *dev)
{
return pch_udc_readl(dev, UDC_DEVSTS_ADDR);
}
/**
* pch_udc_read_ep_control() - Read the endpoint control
* @ep: Reference to structure of type pch_udc_ep_regs
* Retern The endpoint control register value
*/
static inline u32 pch_udc_read_ep_control(struct pch_udc_ep *ep)
{
return pch_udc_ep_readl(ep, UDC_EPCTL_ADDR);
}
/**
* pch_udc_clear_ep_control() - Clear the endpoint control register
* @ep: Reference to structure of type pch_udc_ep_regs
* Retern The endpoint control register value
*/
static inline void pch_udc_clear_ep_control(struct pch_udc_ep *ep)
{
return pch_udc_ep_writel(ep, 0, UDC_EPCTL_ADDR);
}
/**
* pch_udc_read_ep_status() - Read the endpoint status
* @ep: Reference to structure of type pch_udc_ep_regs
* Retern The endpoint status
*/
static inline u32 pch_udc_read_ep_status(struct pch_udc_ep *ep)
{
return pch_udc_ep_readl(ep, UDC_EPSTS_ADDR);
}
/**
* pch_udc_clear_ep_status() - Clear the endpoint status
* @ep: Reference to structure of type pch_udc_ep_regs
* @stat: Endpoint status
*/
static inline void pch_udc_clear_ep_status(struct pch_udc_ep *ep,
u32 stat)
{
return pch_udc_ep_writel(ep, stat, UDC_EPSTS_ADDR);
}
/**
* pch_udc_ep_set_nak() - Set the bit 7 (SNAK field)
* of the endpoint control register
* @ep: Reference to structure of type pch_udc_ep_regs
*/
static inline void pch_udc_ep_set_nak(struct pch_udc_ep *ep)
{
pch_udc_ep_bit_set(ep, UDC_EPCTL_ADDR, UDC_EPCTL_SNAK);
}
/**
* pch_udc_ep_clear_nak() - Set the bit 8 (CNAK field)
* of the endpoint control register
* @ep: reference to structure of type pch_udc_ep_regs
*/
static void pch_udc_ep_clear_nak(struct pch_udc_ep *ep)
{
unsigned int loopcnt = 0;
struct pch_udc_dev *dev = ep->dev;
if (!(pch_udc_ep_readl(ep, UDC_EPCTL_ADDR) & UDC_EPCTL_NAK))
return;
if (!ep->in) {
loopcnt = 10000;
while (!(pch_udc_read_ep_status(ep) & UDC_EPSTS_MRXFIFO_EMP) &&
--loopcnt)
udelay(5);
if (!loopcnt)
dev_err(&dev->pdev->dev, "%s: RxFIFO not Empty\n",
__func__);
}
loopcnt = 10000;
while ((pch_udc_read_ep_control(ep) & UDC_EPCTL_NAK) && --loopcnt) {
pch_udc_ep_bit_set(ep, UDC_EPCTL_ADDR, UDC_EPCTL_CNAK);
udelay(5);
}
if (!loopcnt)
dev_err(&dev->pdev->dev, "%s: Clear NAK not set for ep%d%s\n",
__func__, ep->num, (ep->in ? "in" : "out"));
}
/**
* pch_udc_ep_fifo_flush() - Flush the endpoint fifo
* @ep: reference to structure of type pch_udc_ep_regs
* @dir: direction of endpoint
* 0: endpoint is OUT
* !0: endpoint is IN
*/
static void pch_udc_ep_fifo_flush(struct pch_udc_ep *ep, int dir)
{
if (dir) { /* IN ep */
pch_udc_ep_bit_set(ep, UDC_EPCTL_ADDR, UDC_EPCTL_F);
return;
}
}
/**
* pch_udc_ep_enable() - This api enables endpoint
* @regs: Reference to structure pch_udc_ep_regs
* @desc: endpoint descriptor
*/
static void pch_udc_ep_enable(struct pch_udc_ep *ep,
struct pch_udc_cfg_data *cfg,
const struct usb_endpoint_descriptor *desc)
{
u32 val = 0;
u32 buff_size = 0;
pch_udc_ep_set_trfr_type(ep, desc->bmAttributes);
if (ep->in)
buff_size = UDC_EPIN_BUFF_SIZE;
else
buff_size = UDC_EPOUT_BUFF_SIZE;
pch_udc_ep_set_bufsz(ep, buff_size, ep->in);
pch_udc_ep_set_maxpkt(ep, usb_endpoint_maxp(desc));
pch_udc_ep_set_nak(ep);
pch_udc_ep_fifo_flush(ep, ep->in);
/* Configure the endpoint */
val = ep->num << UDC_CSR_NE_NUM_SHIFT | ep->in << UDC_CSR_NE_DIR_SHIFT |
((desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) <<
UDC_CSR_NE_TYPE_SHIFT) |
(cfg->cur_cfg << UDC_CSR_NE_CFG_SHIFT) |
(cfg->cur_intf << UDC_CSR_NE_INTF_SHIFT) |
(cfg->cur_alt << UDC_CSR_NE_ALT_SHIFT) |
usb_endpoint_maxp(desc) << UDC_CSR_NE_MAX_PKT_SHIFT;
if (ep->in)
pch_udc_write_csr(ep->dev, val, UDC_EPIN_IDX(ep->num));
else
pch_udc_write_csr(ep->dev, val, UDC_EPOUT_IDX(ep->num));
}
/**
* pch_udc_ep_disable() - This api disables endpoint
* @regs: Reference to structure pch_udc_ep_regs
*/
static void pch_udc_ep_disable(struct pch_udc_ep *ep)
{
if (ep->in) {
/* flush the fifo */
pch_udc_ep_writel(ep, UDC_EPCTL_F, UDC_EPCTL_ADDR);
/* set NAK */
pch_udc_ep_writel(ep, UDC_EPCTL_SNAK, UDC_EPCTL_ADDR);
pch_udc_ep_bit_set(ep, UDC_EPSTS_ADDR, UDC_EPSTS_IN);
} else {
/* set NAK */
pch_udc_ep_writel(ep, UDC_EPCTL_SNAK, UDC_EPCTL_ADDR);
}
/* reset desc pointer */
pch_udc_ep_writel(ep, 0, UDC_DESPTR_ADDR);
}
/**
* pch_udc_wait_ep_stall() - Wait EP stall.
* @dev: Reference to pch_udc_dev structure
*/
static void pch_udc_wait_ep_stall(struct pch_udc_ep *ep)
{
unsigned int count = 10000;
/* Wait till idle */
while ((pch_udc_read_ep_control(ep) & UDC_EPCTL_S) && --count)
udelay(5);
if (!count)
dev_err(&ep->dev->pdev->dev, "%s: wait error\n", __func__);
}
/**
* pch_udc_init() - This API initializes usb device controller
* @dev: Rreference to pch_udc_regs structure
*/
static void pch_udc_init(struct pch_udc_dev *dev)
{
if (NULL == dev) {
pr_err("%s: Invalid address\n", __func__);
return;
}
/* Soft Reset and Reset PHY */
pch_udc_writel(dev, UDC_SRST, UDC_SRST_ADDR);
pch_udc_writel(dev, UDC_SRST | UDC_PSRST, UDC_SRST_ADDR);
mdelay(1);
pch_udc_writel(dev, UDC_SRST, UDC_SRST_ADDR);
pch_udc_writel(dev, 0x00, UDC_SRST_ADDR);
mdelay(1);
/* mask and clear all device interrupts */
pch_udc_bit_set(dev, UDC_DEVIRQMSK_ADDR, UDC_DEVINT_MSK);
pch_udc_bit_set(dev, UDC_DEVIRQSTS_ADDR, UDC_DEVINT_MSK);
/* mask and clear all ep interrupts */
pch_udc_bit_set(dev, UDC_EPIRQMSK_ADDR, UDC_EPINT_MSK_DISABLE_ALL);
pch_udc_bit_set(dev, UDC_EPIRQSTS_ADDR, UDC_EPINT_MSK_DISABLE_ALL);
/* enable dynamic CSR programmingi, self powered and device speed */
if (speed_fs)
pch_udc_bit_set(dev, UDC_DEVCFG_ADDR, UDC_DEVCFG_CSR_PRG |
UDC_DEVCFG_SP | UDC_DEVCFG_SPD_FS);
else /* defaul high speed */
pch_udc_bit_set(dev, UDC_DEVCFG_ADDR, UDC_DEVCFG_CSR_PRG |
UDC_DEVCFG_SP | UDC_DEVCFG_SPD_HS);
pch_udc_bit_set(dev, UDC_DEVCTL_ADDR,
(PCH_UDC_THLEN << UDC_DEVCTL_THLEN_SHIFT) |
(PCH_UDC_BRLEN << UDC_DEVCTL_BRLEN_SHIFT) |
UDC_DEVCTL_MODE | UDC_DEVCTL_BREN |
UDC_DEVCTL_THE);
}
/**
* pch_udc_exit() - This API exit usb device controller
* @dev: Reference to pch_udc_regs structure
*/
static void pch_udc_exit(struct pch_udc_dev *dev)
{
/* mask all device interrupts */
pch_udc_bit_set(dev, UDC_DEVIRQMSK_ADDR, UDC_DEVINT_MSK);
/* mask all ep interrupts */
pch_udc_bit_set(dev, UDC_EPIRQMSK_ADDR, UDC_EPINT_MSK_DISABLE_ALL);
/* put device in disconnected state */
pch_udc_set_disconnect(dev);
}
/**
* pch_udc_pcd_get_frame() - This API is invoked to get the current frame number
* @gadget: Reference to the gadget driver
*
* Return codes:
* 0: Success
* -EINVAL: If the gadget passed is NULL
*/
static int pch_udc_pcd_get_frame(struct usb_gadget *gadget)
{
struct pch_udc_dev *dev;
if (!gadget)
return -EINVAL;
dev = container_of(gadget, struct pch_udc_dev, gadget);
return pch_udc_get_frame(dev);
}
/**
* pch_udc_pcd_wakeup() - This API is invoked to initiate a remote wakeup
* @gadget: Reference to the gadget driver
*
* Return codes:
* 0: Success
* -EINVAL: If the gadget passed is NULL
*/
static int pch_udc_pcd_wakeup(struct usb_gadget *gadget)
{
struct pch_udc_dev *dev;
unsigned long flags;
if (!gadget)
return -EINVAL;
dev = container_of(gadget, struct pch_udc_dev, gadget);
spin_lock_irqsave(&dev->lock, flags);
pch_udc_rmt_wakeup(dev);
spin_unlock_irqrestore(&dev->lock, flags);
return 0;
}
/**
* pch_udc_pcd_selfpowered() - This API is invoked to specify whether the device
* is self powered or not
* @gadget: Reference to the gadget driver
* @value: Specifies self powered or not
*
* Return codes:
* 0: Success
* -EINVAL: If the gadget passed is NULL
*/
static int pch_udc_pcd_selfpowered(struct usb_gadget *gadget, int value)
{
struct pch_udc_dev *dev;
if (!gadget)
return -EINVAL;
dev = container_of(gadget, struct pch_udc_dev, gadget);
if (value)
pch_udc_set_selfpowered(dev);
else
pch_udc_clear_selfpowered(dev);
return 0;
}
/**
* pch_udc_pcd_pullup() - This API is invoked to make the device
* visible/invisible to the host
* @gadget: Reference to the gadget driver
* @is_on: Specifies whether the pull up is made active or inactive
*
* Return codes:
* 0: Success
* -EINVAL: If the gadget passed is NULL
*/
static int pch_udc_pcd_pullup(struct usb_gadget *gadget, int is_on)
{
struct pch_udc_dev *dev;
if (!gadget)
return -EINVAL;
dev = container_of(gadget, struct pch_udc_dev, gadget);
if (is_on) {
pch_udc_reconnect(dev);
} else {
if (dev->driver && dev->driver->disconnect) {
spin_unlock(&dev->lock);
dev->driver->disconnect(&dev->gadget);
spin_lock(&dev->lock);
}
pch_udc_set_disconnect(dev);
}
return 0;
}
/**
* pch_udc_pcd_vbus_session() - This API is used by a driver for an external
* transceiver (or GPIO) that
* detects a VBUS power session starting/ending
* @gadget: Reference to the gadget driver
* @is_active: specifies whether the session is starting or ending
*
* Return codes:
* 0: Success
* -EINVAL: If the gadget passed is NULL
*/
static int pch_udc_pcd_vbus_session(struct usb_gadget *gadget, int is_active)
{
struct pch_udc_dev *dev;
if (!gadget)
return -EINVAL;
dev = container_of(gadget, struct pch_udc_dev, gadget);
pch_udc_vbus_session(dev, is_active);
return 0;
}
/**
* pch_udc_pcd_vbus_draw() - This API is used by gadget drivers during
* SET_CONFIGURATION calls to
* specify how much power the device can consume
* @gadget: Reference to the gadget driver
* @mA: specifies the current limit in 2mA unit
*
* Return codes:
* -EINVAL: If the gadget passed is NULL
* -EOPNOTSUPP:
*/
static int pch_udc_pcd_vbus_draw(struct usb_gadget *gadget, unsigned int mA)
{
return -EOPNOTSUPP;
}
static int pch_udc_start(struct usb_gadget_driver *driver,
int (*bind)(struct usb_gadget *));
static int pch_udc_stop(struct usb_gadget_driver *driver);
static const struct usb_gadget_ops pch_udc_ops = {
.get_frame = pch_udc_pcd_get_frame,
.wakeup = pch_udc_pcd_wakeup,
.set_selfpowered = pch_udc_pcd_selfpowered,
.pullup = pch_udc_pcd_pullup,
.vbus_session = pch_udc_pcd_vbus_session,
.vbus_draw = pch_udc_pcd_vbus_draw,
.start = pch_udc_start,
.stop = pch_udc_stop,
};
/**
* pch_vbus_gpio_get_value() - This API gets value of GPIO port as VBUS status.
* @dev: Reference to the driver structure
*
* Return value:
* 1: VBUS is high
* 0: VBUS is low
* -1: It is not enable to detect VBUS using GPIO
*/
static int pch_vbus_gpio_get_value(struct pch_udc_dev *dev)
{
int vbus = 0;
if (dev->vbus_gpio.port)
vbus = gpio_get_value(dev->vbus_gpio.port) ? 1 : 0;
else
vbus = -1;
return vbus;
}
/**
* pch_vbus_gpio_work_fall() - This API keeps watch on VBUS becoming Low.
* If VBUS is Low, disconnect is processed
* @irq_work: Structure for WorkQueue
*
*/
static void pch_vbus_gpio_work_fall(struct work_struct *irq_work)
{
struct pch_vbus_gpio_data *vbus_gpio = container_of(irq_work,
struct pch_vbus_gpio_data, irq_work_fall);
struct pch_udc_dev *dev =
container_of(vbus_gpio, struct pch_udc_dev, vbus_gpio);
int vbus_saved = -1;
int vbus;
int count;
if (!dev->vbus_gpio.port)
return;
for (count = 0; count < (PCH_VBUS_PERIOD / PCH_VBUS_INTERVAL);
count++) {
vbus = pch_vbus_gpio_get_value(dev);
if ((vbus_saved == vbus) && (vbus == 0)) {
dev_dbg(&dev->pdev->dev, "VBUS fell");
if (dev->driver
&& dev->driver->disconnect) {
dev->driver->disconnect(
&dev->gadget);
}
if (dev->vbus_gpio.intr)
pch_udc_init(dev);
else
pch_udc_reconnect(dev);
return;
}
vbus_saved = vbus;
mdelay(PCH_VBUS_INTERVAL);
}
}
/**
* pch_vbus_gpio_work_rise() - This API checks VBUS is High.
* If VBUS is High, connect is processed
* @irq_work: Structure for WorkQueue
*
*/
static void pch_vbus_gpio_work_rise(struct work_struct *irq_work)
{
struct pch_vbus_gpio_data *vbus_gpio = container_of(irq_work,
struct pch_vbus_gpio_data, irq_work_rise);
struct pch_udc_dev *dev =
container_of(vbus_gpio, struct pch_udc_dev, vbus_gpio);
int vbus;
if (!dev->vbus_gpio.port)
return;
mdelay(PCH_VBUS_INTERVAL);
vbus = pch_vbus_gpio_get_value(dev);
if (vbus == 1) {
dev_dbg(&dev->pdev->dev, "VBUS rose");
pch_udc_reconnect(dev);
return;
}
}
/**
* pch_vbus_gpio_irq() - IRQ handler for GPIO intrerrupt for changing VBUS
* @irq: Interrupt request number
* @dev: Reference to the device structure
*
* Return codes:
* 0: Success
* -EINVAL: GPIO port is invalid or can't be initialized.
*/
static irqreturn_t pch_vbus_gpio_irq(int irq, void *data)
{
struct pch_udc_dev *dev = (struct pch_udc_dev *)data;
if (!dev->vbus_gpio.port || !dev->vbus_gpio.intr)
return IRQ_NONE;
if (pch_vbus_gpio_get_value(dev))
schedule_work(&dev->vbus_gpio.irq_work_rise);
else
schedule_work(&dev->vbus_gpio.irq_work_fall);
return IRQ_HANDLED;
}
/**
* pch_vbus_gpio_init() - This API initializes GPIO port detecting VBUS.
* @dev: Reference to the driver structure
* @vbus_gpio Number of GPIO port to detect gpio
*
* Return codes:
* 0: Success
* -EINVAL: GPIO port is invalid or can't be initialized.
*/
static int pch_vbus_gpio_init(struct pch_udc_dev *dev, int vbus_gpio_port)
{
int err;
int irq_num = 0;
dev->vbus_gpio.port = 0;
dev->vbus_gpio.intr = 0;
if (vbus_gpio_port <= -1)
return -EINVAL;
err = gpio_is_valid(vbus_gpio_port);
if (!err) {
pr_err("%s: gpio port %d is invalid\n",
__func__, vbus_gpio_port);
return -EINVAL;
}
err = gpio_request(vbus_gpio_port, "pch_vbus");
if (err) {
pr_err("%s: can't request gpio port %d, err: %d\n",
__func__, vbus_gpio_port, err);
return -EINVAL;
}
dev->vbus_gpio.port = vbus_gpio_port;
gpio_direction_input(vbus_gpio_port);
INIT_WORK(&dev->vbus_gpio.irq_work_fall, pch_vbus_gpio_work_fall);
irq_num = gpio_to_irq(vbus_gpio_port);
if (irq_num > 0) {
irq_set_irq_type(irq_num, IRQ_TYPE_EDGE_BOTH);
err = request_irq(irq_num, pch_vbus_gpio_irq, 0,
"vbus_detect", dev);
if (!err) {
dev->vbus_gpio.intr = irq_num;
INIT_WORK(&dev->vbus_gpio.irq_work_rise,
pch_vbus_gpio_work_rise);
} else {
pr_err("%s: can't request irq %d, err: %d\n",
__func__, irq_num, err);
}
}
return 0;
}
/**
* pch_vbus_gpio_free() - This API frees resources of GPIO port
* @dev: Reference to the driver structure
*/
static void pch_vbus_gpio_free(struct pch_udc_dev *dev)
{
if (dev->vbus_gpio.intr)
free_irq(dev->vbus_gpio.intr, dev);
if (dev->vbus_gpio.port)
gpio_free(dev->vbus_gpio.port);
}
/**
* complete_req() - This API is invoked from the driver when processing
* of a request is complete
* @ep: Reference to the endpoint structure
* @req: Reference to the request structure
* @status: Indicates the success/failure of completion
*/
static void complete_req(struct pch_udc_ep *ep, struct pch_udc_request *req,
int status)
{
struct pch_udc_dev *dev;
unsigned halted = ep->halted;
list_del_init(&req->queue);
/* set new status if pending */
if (req->req.status == -EINPROGRESS)
req->req.status = status;
else
status = req->req.status;
dev = ep->dev;
if (req->dma_mapped) {
if (req->dma == DMA_ADDR_INVALID) {
if (ep->in)
dma_unmap_single(&dev->pdev->dev, req->req.dma,
req->req.length,
DMA_TO_DEVICE);
else
dma_unmap_single(&dev->pdev->dev, req->req.dma,
req->req.length,
DMA_FROM_DEVICE);
req->req.dma = DMA_ADDR_INVALID;
} else {
if (ep->in)
dma_unmap_single(&dev->pdev->dev, req->dma,
req->req.length,
DMA_TO_DEVICE);
else {
dma_unmap_single(&dev->pdev->dev, req->dma,
req->req.length,
DMA_FROM_DEVICE);
memcpy(req->req.buf, req->buf, req->req.length);
}
kfree(req->buf);
req->dma = DMA_ADDR_INVALID;
}
req->dma_mapped = 0;
}
ep->halted = 1;
spin_unlock(&dev->lock);
if (!ep->in)
pch_udc_ep_clear_rrdy(ep);
req->req.complete(&ep->ep, &req->req);
spin_lock(&dev->lock);
ep->halted = halted;
}
/**
* empty_req_queue() - This API empties the request queue of an endpoint
* @ep: Reference to the endpoint structure
*/
static void empty_req_queue(struct pch_udc_ep *ep)
{
struct pch_udc_request *req;
ep->halted = 1;
while (!list_empty(&ep->queue)) {
req = list_entry(ep->queue.next, struct pch_udc_request, queue);
complete_req(ep, req, -ESHUTDOWN); /* Remove from list */
}
}
/**
* pch_udc_free_dma_chain() - This function frees the DMA chain created
* for the request
* @dev Reference to the driver structure
* @req Reference to the request to be freed
*
* Return codes:
* 0: Success
*/
static void pch_udc_free_dma_chain(struct pch_udc_dev *dev,
struct pch_udc_request *req)
{
struct pch_udc_data_dma_desc *td = req->td_data;
unsigned i = req->chain_len;
dma_addr_t addr2;
dma_addr_t addr = (dma_addr_t)td->next;
td->next = 0x00;
for (; i > 1; --i) {
/* do not free first desc., will be done by free for request */
td = phys_to_virt(addr);
addr2 = (dma_addr_t)td->next;
pci_pool_free(dev->data_requests, td, addr);
td->next = 0x00;
addr = addr2;
}
req->chain_len = 1;
}
/**
* pch_udc_create_dma_chain() - This function creates or reinitializes
* a DMA chain
* @ep: Reference to the endpoint structure
* @req: Reference to the request
* @buf_len: The buffer length
* @gfp_flags: Flags to be used while mapping the data buffer
*
* Return codes:
* 0: success,
* -ENOMEM: pci_pool_alloc invocation fails
*/
static int pch_udc_create_dma_chain(struct pch_udc_ep *ep,
struct pch_udc_request *req,
unsigned long buf_len,
gfp_t gfp_flags)
{
struct pch_udc_data_dma_desc *td = req->td_data, *last;
unsigned long bytes = req->req.length, i = 0;
dma_addr_t dma_addr;
unsigned len = 1;
if (req->chain_len > 1)
pch_udc_free_dma_chain(ep->dev, req);
if (req->dma == DMA_ADDR_INVALID)
td->dataptr = req->req.dma;
else
td->dataptr = req->dma;
td->status = PCH_UDC_BS_HST_BSY;
for (; ; bytes -= buf_len, ++len) {
td->status = PCH_UDC_BS_HST_BSY | min(buf_len, bytes);
if (bytes <= buf_len)
break;
last = td;
td = pci_pool_alloc(ep->dev->data_requests, gfp_flags,
&dma_addr);
if (!td)
goto nomem;
i += buf_len;
td->dataptr = req->td_data->dataptr + i;
last->next = dma_addr;
}
req->td_data_last = td;
td->status |= PCH_UDC_DMA_LAST;
td->next = req->td_data_phys;
req->chain_len = len;
return 0;
nomem:
if (len > 1) {
req->chain_len = len;
pch_udc_free_dma_chain(ep->dev, req);
}
req->chain_len = 1;
return -ENOMEM;
}
/**
* prepare_dma() - This function creates and initializes the DMA chain
* for the request
* @ep: Reference to the endpoint structure
* @req: Reference to the request
* @gfp: Flag to be used while mapping the data buffer
*
* Return codes:
* 0: Success
* Other 0: linux error number on failure
*/
static int prepare_dma(struct pch_udc_ep *ep, struct pch_udc_request *req,
gfp_t gfp)
{
int retval;
/* Allocate and create a DMA chain */
retval = pch_udc_create_dma_chain(ep, req, ep->ep.maxpacket, gfp);
if (retval) {
pr_err("%s: could not create DMA chain:%d\n", __func__, retval);
return retval;
}
if (ep->in)
req->td_data->status = (req->td_data->status &
~PCH_UDC_BUFF_STS) | PCH_UDC_BS_HST_RDY;
return 0;
}
/**
* process_zlp() - This function process zero length packets
* from the gadget driver
* @ep: Reference to the endpoint structure
* @req: Reference to the request
*/
static void process_zlp(struct pch_udc_ep *ep, struct pch_udc_request *req)
{
struct pch_udc_dev *dev = ep->dev;
/* IN zlp's are handled by hardware */
complete_req(ep, req, 0);
/* if set_config or set_intf is waiting for ack by zlp
* then set CSR_DONE
*/
if (dev->set_cfg_not_acked) {
pch_udc_set_csr_done(dev);
dev->set_cfg_not_acked = 0;
}
/* setup command is ACK'ed now by zlp */
if (!dev->stall && dev->waiting_zlp_ack) {
pch_udc_ep_clear_nak(&(dev->ep[UDC_EP0IN_IDX]));
dev->waiting_zlp_ack = 0;
}
}
/**
* pch_udc_start_rxrequest() - This function starts the receive requirement.
* @ep: Reference to the endpoint structure
* @req: Reference to the request structure
*/
static void pch_udc_start_rxrequest(struct pch_udc_ep *ep,
struct pch_udc_request *req)
{
struct pch_udc_data_dma_desc *td_data;
pch_udc_clear_dma(ep->dev, DMA_DIR_RX);
td_data = req->td_data;
/* Set the status bits for all descriptors */
while (1) {
td_data->status = (td_data->status & ~PCH_UDC_BUFF_STS) |
PCH_UDC_BS_HST_RDY;
if ((td_data->status & PCH_UDC_DMA_LAST) == PCH_UDC_DMA_LAST)
break;
td_data = phys_to_virt(td_data->next);
}
/* Write the descriptor pointer */
pch_udc_ep_set_ddptr(ep, req->td_data_phys);
req->dma_going = 1;
pch_udc_enable_ep_interrupts(ep->dev, UDC_EPINT_OUT_EP0 << ep->num);
pch_udc_set_dma(ep->dev, DMA_DIR_RX);
pch_udc_ep_clear_nak(ep);
pch_udc_ep_set_rrdy(ep);
}
/**
* pch_udc_pcd_ep_enable() - This API enables the endpoint. It is called
* from gadget driver
* @usbep: Reference to the USB endpoint structure
* @desc: Reference to the USB endpoint descriptor structure
*
* Return codes:
* 0: Success
* -EINVAL:
* -ESHUTDOWN:
*/
static int pch_udc_pcd_ep_enable(struct usb_ep *usbep,
const struct usb_endpoint_descriptor *desc)
{
struct pch_udc_ep *ep;
struct pch_udc_dev *dev;
unsigned long iflags;
if (!usbep || (usbep->name == ep0_string) || !desc ||
(desc->bDescriptorType != USB_DT_ENDPOINT) || !desc->wMaxPacketSize)
return -EINVAL;
ep = container_of(usbep, struct pch_udc_ep, ep);
dev = ep->dev;
if (!dev->driver || (dev->gadget.speed == USB_SPEED_UNKNOWN))
return -ESHUTDOWN;
spin_lock_irqsave(&dev->lock, iflags);
ep->desc = desc;
ep->halted = 0;
pch_udc_ep_enable(ep, &ep->dev->cfg_data, desc);
ep->ep.maxpacket = usb_endpoint_maxp(desc);
pch_udc_enable_ep_interrupts(ep->dev, PCH_UDC_EPINT(ep->in, ep->num));
spin_unlock_irqrestore(&dev->lock, iflags);
return 0;
}
/**
* pch_udc_pcd_ep_disable() - This API disables endpoint and is called
* from gadget driver
* @usbep Reference to the USB endpoint structure
*
* Return codes:
* 0: Success
* -EINVAL:
*/
static int pch_udc_pcd_ep_disable(struct usb_ep *usbep)
{
struct pch_udc_ep *ep;
struct pch_udc_dev *dev;
unsigned long iflags;
if (!usbep)
return -EINVAL;
ep = container_of(usbep, struct pch_udc_ep, ep);
dev = ep->dev;
if ((usbep->name == ep0_string) || !ep->desc)
return -EINVAL;
spin_lock_irqsave(&ep->dev->lock, iflags);
empty_req_queue(ep);
ep->halted = 1;
pch_udc_ep_disable(ep);
pch_udc_disable_ep_interrupts(ep->dev, PCH_UDC_EPINT(ep->in, ep->num));
ep->desc = NULL;
ep->ep.desc = NULL;
INIT_LIST_HEAD(&ep->queue);
spin_unlock_irqrestore(&ep->dev->lock, iflags);
return 0;
}
/**
* pch_udc_alloc_request() - This function allocates request structure.
* It is called by gadget driver
* @usbep: Reference to the USB endpoint structure
* @gfp: Flag to be used while allocating memory
*
* Return codes:
* NULL: Failure
* Allocated address: Success
*/
static struct usb_request *pch_udc_alloc_request(struct usb_ep *usbep,
gfp_t gfp)
{
struct pch_udc_request *req;
struct pch_udc_ep *ep;
struct pch_udc_data_dma_desc *dma_desc;
struct pch_udc_dev *dev;
if (!usbep)
return NULL;
ep = container_of(usbep, struct pch_udc_ep, ep);
dev = ep->dev;
req = kzalloc(sizeof *req, gfp);
if (!req)
return NULL;
req->req.dma = DMA_ADDR_INVALID;
req->dma = DMA_ADDR_INVALID;
INIT_LIST_HEAD(&req->queue);
if (!ep->dev->dma_addr)
return &req->req;
/* ep0 in requests are allocated from data pool here */
dma_desc = pci_pool_alloc(ep->dev->data_requests, gfp,
&req->td_data_phys);
if (NULL == dma_desc) {
kfree(req);
return NULL;
}
/* prevent from using desc. - set HOST BUSY */
dma_desc->status |= PCH_UDC_BS_HST_BSY;
dma_desc->dataptr = __constant_cpu_to_le32(DMA_ADDR_INVALID);
req->td_data = dma_desc;
req->td_data_last = dma_desc;
req->chain_len = 1;
return &req->req;
}
/**
* pch_udc_free_request() - This function frees request structure.
* It is called by gadget driver
* @usbep: Reference to the USB endpoint structure
* @usbreq: Reference to the USB request
*/
static void pch_udc_free_request(struct usb_ep *usbep,
struct usb_request *usbreq)
{
struct pch_udc_ep *ep;
struct pch_udc_request *req;
struct pch_udc_dev *dev;
if (!usbep || !usbreq)
return;
ep = container_of(usbep, struct pch_udc_ep, ep);
req = container_of(usbreq, struct pch_udc_request, req);
dev = ep->dev;
if (!list_empty(&req->queue))
dev_err(&dev->pdev->dev, "%s: %s req=0x%p queue not empty\n",
__func__, usbep->name, req);
if (req->td_data != NULL) {
if (req->chain_len > 1)
pch_udc_free_dma_chain(ep->dev, req);
pci_pool_free(ep->dev->data_requests, req->td_data,
req->td_data_phys);
}
kfree(req);
}
/**
* pch_udc_pcd_queue() - This function queues a request packet. It is called
* by gadget driver
* @usbep: Reference to the USB endpoint structure
* @usbreq: Reference to the USB request
* @gfp: Flag to be used while mapping the data buffer
*
* Return codes:
* 0: Success
* linux error number: Failure
*/
static int pch_udc_pcd_queue(struct usb_ep *usbep, struct usb_request *usbreq,
gfp_t gfp)
{
int retval = 0;
struct pch_udc_ep *ep;
struct pch_udc_dev *dev;
struct pch_udc_request *req;
unsigned long iflags;
if (!usbep || !usbreq || !usbreq->complete || !usbreq->buf)
return -EINVAL;
ep = container_of(usbep, struct pch_udc_ep, ep);
dev = ep->dev;
if (!ep->desc && ep->num)
return -EINVAL;
req = container_of(usbreq, struct pch_udc_request, req);
if (!list_empty(&req->queue))
return -EINVAL;
if (!dev->driver || (dev->gadget.speed == USB_SPEED_UNKNOWN))
return -ESHUTDOWN;
spin_lock_irqsave(&dev->lock, iflags);
/* map the buffer for dma */
if (usbreq->length &&
((usbreq->dma == DMA_ADDR_INVALID) || !usbreq->dma)) {
if (!((unsigned long)(usbreq->buf) & 0x03)) {
if (ep->in)
usbreq->dma = dma_map_single(&dev->pdev->dev,
usbreq->buf,
usbreq->length,
DMA_TO_DEVICE);
else
usbreq->dma = dma_map_single(&dev->pdev->dev,
usbreq->buf,
usbreq->length,
DMA_FROM_DEVICE);
} else {
req->buf = kzalloc(usbreq->length, GFP_ATOMIC);
if (!req->buf) {
retval = -ENOMEM;
goto probe_end;
}
if (ep->in) {
memcpy(req->buf, usbreq->buf, usbreq->length);
req->dma = dma_map_single(&dev->pdev->dev,
req->buf,
usbreq->length,
DMA_TO_DEVICE);
} else
req->dma = dma_map_single(&dev->pdev->dev,
req->buf,
usbreq->length,
DMA_FROM_DEVICE);
}
req->dma_mapped = 1;
}
if (usbreq->length > 0) {
retval = prepare_dma(ep, req, GFP_ATOMIC);
if (retval)
goto probe_end;
}
usbreq->actual = 0;
usbreq->status = -EINPROGRESS;
req->dma_done = 0;
if (list_empty(&ep->queue) && !ep->halted) {
/* no pending transfer, so start this req */
if (!usbreq->length) {
process_zlp(ep, req);
retval = 0;
goto probe_end;
}
if (!ep->in) {
pch_udc_start_rxrequest(ep, req);
} else {
/*
* For IN trfr the descriptors will be programmed and
* P bit will be set when
* we get an IN token
*/
pch_udc_wait_ep_stall(ep);
pch_udc_ep_clear_nak(ep);
pch_udc_enable_ep_interrupts(ep->dev, (1 << ep->num));
}
}
/* Now add this request to the ep's pending requests */
if (req != NULL)
list_add_tail(&req->queue, &ep->queue);
probe_end:
spin_unlock_irqrestore(&dev->lock, iflags);
return retval;
}
/**
* pch_udc_pcd_dequeue() - This function de-queues a request packet.
* It is called by gadget driver
* @usbep: Reference to the USB endpoint structure
* @usbreq: Reference to the USB request
*
* Return codes:
* 0: Success
* linux error number: Failure
*/
static int pch_udc_pcd_dequeue(struct usb_ep *usbep,
struct usb_request *usbreq)
{
struct pch_udc_ep *ep;
struct pch_udc_request *req;
struct pch_udc_dev *dev;
unsigned long flags;
int ret = -EINVAL;
ep = container_of(usbep, struct pch_udc_ep, ep);
dev = ep->dev;
if (!usbep || !usbreq || (!ep->desc && ep->num))
return ret;
req = container_of(usbreq, struct pch_udc_request, req);
spin_lock_irqsave(&ep->dev->lock, flags);
/* make sure it's still queued on this endpoint */
list_for_each_entry(req, &ep->queue, queue) {
if (&req->req == usbreq) {
pch_udc_ep_set_nak(ep);
if (!list_empty(&req->queue))
complete_req(ep, req, -ECONNRESET);
ret = 0;
break;
}
}
spin_unlock_irqrestore(&ep->dev->lock, flags);
return ret;
}
/**
* pch_udc_pcd_set_halt() - This function Sets or clear the endpoint halt
* feature
* @usbep: Reference to the USB endpoint structure
* @halt: Specifies whether to set or clear the feature
*
* Return codes:
* 0: Success
* linux error number: Failure
*/
static int pch_udc_pcd_set_halt(struct usb_ep *usbep, int halt)
{
struct pch_udc_ep *ep;
struct pch_udc_dev *dev;
unsigned long iflags;
int ret;
if (!usbep)
return -EINVAL;
ep = container_of(usbep, struct pch_udc_ep, ep);
dev = ep->dev;
if (!ep->desc && !ep->num)
return -EINVAL;
if (!ep->dev->driver || (ep->dev->gadget.speed == USB_SPEED_UNKNOWN))
return -ESHUTDOWN;
spin_lock_irqsave(&udc_stall_spinlock, iflags);
if (list_empty(&ep->queue)) {
if (halt) {
if (ep->num == PCH_UDC_EP0)
ep->dev->stall = 1;
pch_udc_ep_set_stall(ep);
pch_udc_enable_ep_interrupts(ep->dev,
PCH_UDC_EPINT(ep->in,
ep->num));
} else {
pch_udc_ep_clear_stall(ep);
}
ret = 0;
} else {
ret = -EAGAIN;
}
spin_unlock_irqrestore(&udc_stall_spinlock, iflags);
return ret;
}
/**
* pch_udc_pcd_set_wedge() - This function Sets or clear the endpoint
* halt feature
* @usbep: Reference to the USB endpoint structure
* @halt: Specifies whether to set or clear the feature
*
* Return codes:
* 0: Success
* linux error number: Failure
*/
static int pch_udc_pcd_set_wedge(struct usb_ep *usbep)
{
struct pch_udc_ep *ep;
struct pch_udc_dev *dev;
unsigned long iflags;
int ret;
if (!usbep)
return -EINVAL;
ep = container_of(usbep, struct pch_udc_ep, ep);
dev = ep->dev;
if (!ep->desc && !ep->num)
return -EINVAL;
if (!ep->dev->driver || (ep->dev->gadget.speed == USB_SPEED_UNKNOWN))
return -ESHUTDOWN;
spin_lock_irqsave(&udc_stall_spinlock, iflags);
if (!list_empty(&ep->queue)) {
ret = -EAGAIN;
} else {
if (ep->num == PCH_UDC_EP0)
ep->dev->stall = 1;
pch_udc_ep_set_stall(ep);
pch_udc_enable_ep_interrupts(ep->dev,
PCH_UDC_EPINT(ep->in, ep->num));
ep->dev->prot_stall = 1;
ret = 0;
}
spin_unlock_irqrestore(&udc_stall_spinlock, iflags);
return ret;
}
/**
* pch_udc_pcd_fifo_flush() - This function Flush the FIFO of specified endpoint
* @usbep: Reference to the USB endpoint structure
*/
static void pch_udc_pcd_fifo_flush(struct usb_ep *usbep)
{
struct pch_udc_ep *ep;
if (!usbep)
return;
ep = container_of(usbep, struct pch_udc_ep, ep);
if (ep->desc || !ep->num)
pch_udc_ep_fifo_flush(ep, ep->in);
}
static const struct usb_ep_ops pch_udc_ep_ops = {
.enable = pch_udc_pcd_ep_enable,
.disable = pch_udc_pcd_ep_disable,
.alloc_request = pch_udc_alloc_request,
.free_request = pch_udc_free_request,
.queue = pch_udc_pcd_queue,
.dequeue = pch_udc_pcd_dequeue,
.set_halt = pch_udc_pcd_set_halt,
.set_wedge = pch_udc_pcd_set_wedge,
.fifo_status = NULL,
.fifo_flush = pch_udc_pcd_fifo_flush,
};
/**
* pch_udc_init_setup_buff() - This function initializes the SETUP buffer
* @td_stp: Reference to the SETP buffer structure
*/
static void pch_udc_init_setup_buff(struct pch_udc_stp_dma_desc *td_stp)
{
static u32 pky_marker;
if (!td_stp)
return;
td_stp->reserved = ++pky_marker;
memset(&td_stp->request, 0xFF, sizeof td_stp->request);
td_stp->status = PCH_UDC_BS_HST_RDY;
}
/**
* pch_udc_start_next_txrequest() - This function starts
* the next transmission requirement
* @ep: Reference to the endpoint structure
*/
static void pch_udc_start_next_txrequest(struct pch_udc_ep *ep)
{
struct pch_udc_request *req;
struct pch_udc_data_dma_desc *td_data;
if (pch_udc_read_ep_control(ep) & UDC_EPCTL_P)
return;
if (list_empty(&ep->queue))
return;
/* next request */
req = list_entry(ep->queue.next, struct pch_udc_request, queue);
if (req->dma_going)
return;
if (!req->td_data)
return;
pch_udc_wait_ep_stall(ep);
req->dma_going = 1;
pch_udc_ep_set_ddptr(ep, 0);
td_data = req->td_data;
while (1) {
td_data->status = (td_data->status & ~PCH_UDC_BUFF_STS) |
PCH_UDC_BS_HST_RDY;
if ((td_data->status & PCH_UDC_DMA_LAST) == PCH_UDC_DMA_LAST)
break;
td_data = phys_to_virt(td_data->next);
}
pch_udc_ep_set_ddptr(ep, req->td_data_phys);
pch_udc_set_dma(ep->dev, DMA_DIR_TX);
pch_udc_ep_set_pd(ep);
pch_udc_enable_ep_interrupts(ep->dev, PCH_UDC_EPINT(ep->in, ep->num));
pch_udc_ep_clear_nak(ep);
}
/**
* pch_udc_complete_transfer() - This function completes a transfer
* @ep: Reference to the endpoint structure
*/
static void pch_udc_complete_transfer(struct pch_udc_ep *ep)
{
struct pch_udc_request *req;
struct pch_udc_dev *dev = ep->dev;
if (list_empty(&ep->queue))
return;
req = list_entry(ep->queue.next, struct pch_udc_request, queue);
if ((req->td_data_last->status & PCH_UDC_BUFF_STS) !=
PCH_UDC_BS_DMA_DONE)
return;
if ((req->td_data_last->status & PCH_UDC_RXTX_STS) !=
PCH_UDC_RTS_SUCC) {
dev_err(&dev->pdev->dev, "Invalid RXTX status (0x%08x) "
"epstatus=0x%08x\n",
(req->td_data_last->status & PCH_UDC_RXTX_STS),
(int)(ep->epsts));
return;
}
req->req.actual = req->req.length;
req->td_data_last->status = PCH_UDC_BS_HST_BSY | PCH_UDC_DMA_LAST;
req->td_data->status = PCH_UDC_BS_HST_BSY | PCH_UDC_DMA_LAST;
complete_req(ep, req, 0);
req->dma_going = 0;
if (!list_empty(&ep->queue)) {
pch_udc_wait_ep_stall(ep);
pch_udc_ep_clear_nak(ep);
pch_udc_enable_ep_interrupts(ep->dev,
PCH_UDC_EPINT(ep->in, ep->num));
} else {
pch_udc_disable_ep_interrupts(ep->dev,
PCH_UDC_EPINT(ep->in, ep->num));
}
}
/**
* pch_udc_complete_receiver() - This function completes a receiver
* @ep: Reference to the endpoint structure
*/
static void pch_udc_complete_receiver(struct pch_udc_ep *ep)
{
struct pch_udc_request *req;
struct pch_udc_dev *dev = ep->dev;
unsigned int count;
struct pch_udc_data_dma_desc *td;
dma_addr_t addr;
if (list_empty(&ep->queue))
return;
/* next request */
req = list_entry(ep->queue.next, struct pch_udc_request, queue);
pch_udc_clear_dma(ep->dev, DMA_DIR_RX);
pch_udc_ep_set_ddptr(ep, 0);
if ((req->td_data_last->status & PCH_UDC_BUFF_STS) ==
PCH_UDC_BS_DMA_DONE)
td = req->td_data_last;
else
td = req->td_data;
while (1) {
if ((td->status & PCH_UDC_RXTX_STS) != PCH_UDC_RTS_SUCC) {
dev_err(&dev->pdev->dev, "Invalid RXTX status=0x%08x "
"epstatus=0x%08x\n",
(req->td_data->status & PCH_UDC_RXTX_STS),
(int)(ep->epsts));
return;
}
if ((td->status & PCH_UDC_BUFF_STS) == PCH_UDC_BS_DMA_DONE)
if (td->status | PCH_UDC_DMA_LAST) {
count = td->status & PCH_UDC_RXTX_BYTES;
break;
}
if (td == req->td_data_last) {
dev_err(&dev->pdev->dev, "Not complete RX descriptor");
return;
}
addr = (dma_addr_t)td->next;
td = phys_to_virt(addr);
}
/* on 64k packets the RXBYTES field is zero */
if (!count && (req->req.length == UDC_DMA_MAXPACKET))
count = UDC_DMA_MAXPACKET;
req->td_data->status |= PCH_UDC_DMA_LAST;
td->status |= PCH_UDC_BS_HST_BSY;
req->dma_going = 0;
req->req.actual = count;
complete_req(ep, req, 0);
/* If there is a new/failed requests try that now */
if (!list_empty(&ep->queue)) {
req = list_entry(ep->queue.next, struct pch_udc_request, queue);
pch_udc_start_rxrequest(ep, req);
}
}
/**
* pch_udc_svc_data_in() - This function process endpoint interrupts
* for IN endpoints
* @dev: Reference to the device structure
* @ep_num: Endpoint that generated the interrupt
*/
static void pch_udc_svc_data_in(struct pch_udc_dev *dev, int ep_num)
{
u32 epsts;
struct pch_udc_ep *ep;
ep = &dev->ep[UDC_EPIN_IDX(ep_num)];
epsts = ep->epsts;
ep->epsts = 0;
if (!(epsts & (UDC_EPSTS_IN | UDC_EPSTS_BNA | UDC_EPSTS_HE |
UDC_EPSTS_TDC | UDC_EPSTS_RCS | UDC_EPSTS_TXEMPTY |
UDC_EPSTS_RSS | UDC_EPSTS_XFERDONE)))
return;
if ((epsts & UDC_EPSTS_BNA))
return;
if (epsts & UDC_EPSTS_HE)
return;
if (epsts & UDC_EPSTS_RSS) {
pch_udc_ep_set_stall(ep);
pch_udc_enable_ep_interrupts(ep->dev,
PCH_UDC_EPINT(ep->in, ep->num));
}
if (epsts & UDC_EPSTS_RCS) {
if (!dev->prot_stall) {
pch_udc_ep_clear_stall(ep);
} else {
pch_udc_ep_set_stall(ep);
pch_udc_enable_ep_interrupts(ep->dev,
PCH_UDC_EPINT(ep->in, ep->num));
}
}
if (epsts & UDC_EPSTS_TDC)
pch_udc_complete_transfer(ep);
/* On IN interrupt, provide data if we have any */
if ((epsts & UDC_EPSTS_IN) && !(epsts & UDC_EPSTS_RSS) &&
!(epsts & UDC_EPSTS_TDC) && !(epsts & UDC_EPSTS_TXEMPTY))
pch_udc_start_next_txrequest(ep);
}
/**
* pch_udc_svc_data_out() - Handles interrupts from OUT endpoint
* @dev: Reference to the device structure
* @ep_num: Endpoint that generated the interrupt
*/
static void pch_udc_svc_data_out(struct pch_udc_dev *dev, int ep_num)
{
u32 epsts;
struct pch_udc_ep *ep;
struct pch_udc_request *req = NULL;
ep = &dev->ep[UDC_EPOUT_IDX(ep_num)];
epsts = ep->epsts;
ep->epsts = 0;
if ((epsts & UDC_EPSTS_BNA) && (!list_empty(&ep->queue))) {
/* next request */
req = list_entry(ep->queue.next, struct pch_udc_request,
queue);
if ((req->td_data_last->status & PCH_UDC_BUFF_STS) !=
PCH_UDC_BS_DMA_DONE) {
if (!req->dma_going)
pch_udc_start_rxrequest(ep, req);
return;
}
}
if (epsts & UDC_EPSTS_HE)
return;
if (epsts & UDC_EPSTS_RSS) {
pch_udc_ep_set_stall(ep);
pch_udc_enable_ep_interrupts(ep->dev,
PCH_UDC_EPINT(ep->in, ep->num));
}
if (epsts & UDC_EPSTS_RCS) {
if (!dev->prot_stall) {
pch_udc_ep_clear_stall(ep);
} else {
pch_udc_ep_set_stall(ep);
pch_udc_enable_ep_interrupts(ep->dev,
PCH_UDC_EPINT(ep->in, ep->num));
}
}
if (((epsts & UDC_EPSTS_OUT_MASK) >> UDC_EPSTS_OUT_SHIFT) ==
UDC_EPSTS_OUT_DATA) {
if (ep->dev->prot_stall == 1) {
pch_udc_ep_set_stall(ep);
pch_udc_enable_ep_interrupts(ep->dev,
PCH_UDC_EPINT(ep->in, ep->num));
} else {
pch_udc_complete_receiver(ep);
}
}
if (list_empty(&ep->queue))
pch_udc_set_dma(dev, DMA_DIR_RX);
}
/**
* pch_udc_svc_control_in() - Handle Control IN endpoint interrupts
* @dev: Reference to the device structure
*/
static void pch_udc_svc_control_in(struct pch_udc_dev *dev)
{
u32 epsts;
struct pch_udc_ep *ep;
struct pch_udc_ep *ep_out;
ep = &dev->ep[UDC_EP0IN_IDX];
ep_out = &dev->ep[UDC_EP0OUT_IDX];
epsts = ep->epsts;
ep->epsts = 0;
if (!(epsts & (UDC_EPSTS_IN | UDC_EPSTS_BNA | UDC_EPSTS_HE |
UDC_EPSTS_TDC | UDC_EPSTS_RCS | UDC_EPSTS_TXEMPTY |
UDC_EPSTS_XFERDONE)))
return;
if ((epsts & UDC_EPSTS_BNA))
return;
if (epsts & UDC_EPSTS_HE)
return;
if ((epsts & UDC_EPSTS_TDC) && (!dev->stall)) {
pch_udc_complete_transfer(ep);
pch_udc_clear_dma(dev, DMA_DIR_RX);
ep_out->td_data->status = (ep_out->td_data->status &
~PCH_UDC_BUFF_STS) |
PCH_UDC_BS_HST_RDY;
pch_udc_ep_clear_nak(ep_out);
pch_udc_set_dma(dev, DMA_DIR_RX);
pch_udc_ep_set_rrdy(ep_out);
}
/* On IN interrupt, provide data if we have any */
if ((epsts & UDC_EPSTS_IN) && !(epsts & UDC_EPSTS_TDC) &&
!(epsts & UDC_EPSTS_TXEMPTY))
pch_udc_start_next_txrequest(ep);
}
/**
* pch_udc_svc_control_out() - Routine that handle Control
* OUT endpoint interrupts
* @dev: Reference to the device structure
*/
static void pch_udc_svc_control_out(struct pch_udc_dev *dev)
{
u32 stat;
int setup_supported;
struct pch_udc_ep *ep;
ep = &dev->ep[UDC_EP0OUT_IDX];
stat = ep->epsts;
ep->epsts = 0;
/* If setup data */
if (((stat & UDC_EPSTS_OUT_MASK) >> UDC_EPSTS_OUT_SHIFT) ==
UDC_EPSTS_OUT_SETUP) {
dev->stall = 0;
dev->ep[UDC_EP0IN_IDX].halted = 0;
dev->ep[UDC_EP0OUT_IDX].halted = 0;
dev->setup_data = ep->td_stp->request;
pch_udc_init_setup_buff(ep->td_stp);
pch_udc_clear_dma(dev, DMA_DIR_RX);
pch_udc_ep_fifo_flush(&(dev->ep[UDC_EP0IN_IDX]),
dev->ep[UDC_EP0IN_IDX].in);
if ((dev->setup_data.bRequestType & USB_DIR_IN))
dev->gadget.ep0 = &dev->ep[UDC_EP0IN_IDX].ep;
else /* OUT */
dev->gadget.ep0 = &ep->ep;
spin_unlock(&dev->lock);
/* If Mass storage Reset */
if ((dev->setup_data.bRequestType == 0x21) &&
(dev->setup_data.bRequest == 0xFF))
dev->prot_stall = 0;
/* call gadget with setup data received */
setup_supported = dev->driver->setup(&dev->gadget,
&dev->setup_data);
spin_lock(&dev->lock);
if (dev->setup_data.bRequestType & USB_DIR_IN) {
ep->td_data->status = (ep->td_data->status &
~PCH_UDC_BUFF_STS) |
PCH_UDC_BS_HST_RDY;
pch_udc_ep_set_ddptr(ep, ep->td_data_phys);
}
/* ep0 in returns data on IN phase */
if (setup_supported >= 0 && setup_supported <
UDC_EP0IN_MAX_PKT_SIZE) {
pch_udc_ep_clear_nak(&(dev->ep[UDC_EP0IN_IDX]));
/* Gadget would have queued a request when
* we called the setup */
if (!(dev->setup_data.bRequestType & USB_DIR_IN)) {
pch_udc_set_dma(dev, DMA_DIR_RX);
pch_udc_ep_clear_nak(ep);
}
} else if (setup_supported < 0) {
/* if unsupported request, then stall */
pch_udc_ep_set_stall(&(dev->ep[UDC_EP0IN_IDX]));
pch_udc_enable_ep_interrupts(ep->dev,
PCH_UDC_EPINT(ep->in, ep->num));
dev->stall = 0;
pch_udc_set_dma(dev, DMA_DIR_RX);
} else {
dev->waiting_zlp_ack = 1;
}
} else if ((((stat & UDC_EPSTS_OUT_MASK) >> UDC_EPSTS_OUT_SHIFT) ==
UDC_EPSTS_OUT_DATA) && !dev->stall) {
pch_udc_clear_dma(dev, DMA_DIR_RX);
pch_udc_ep_set_ddptr(ep, 0);
if (!list_empty(&ep->queue)) {
ep->epsts = stat;
pch_udc_svc_data_out(dev, PCH_UDC_EP0);
}
pch_udc_set_dma(dev, DMA_DIR_RX);
}
pch_udc_ep_set_rrdy(ep);
}
/**
* pch_udc_postsvc_epinters() - This function enables end point interrupts
* and clears NAK status
* @dev: Reference to the device structure
* @ep_num: End point number
*/
static void pch_udc_postsvc_epinters(struct pch_udc_dev *dev, int ep_num)
{
struct pch_udc_ep *ep;
struct pch_udc_request *req;
ep = &dev->ep[UDC_EPIN_IDX(ep_num)];
if (!list_empty(&ep->queue)) {
req = list_entry(ep->queue.next, struct pch_udc_request, queue);
pch_udc_enable_ep_interrupts(ep->dev,
PCH_UDC_EPINT(ep->in, ep->num));
pch_udc_ep_clear_nak(ep);
}
}
/**
* pch_udc_read_all_epstatus() - This function read all endpoint status
* @dev: Reference to the device structure
* @ep_intr: Status of endpoint interrupt
*/
static void pch_udc_read_all_epstatus(struct pch_udc_dev *dev, u32 ep_intr)
{
int i;
struct pch_udc_ep *ep;
for (i = 0; i < PCH_UDC_USED_EP_NUM; i++) {
/* IN */
if (ep_intr & (0x1 << i)) {
ep = &dev->ep[UDC_EPIN_IDX(i)];
ep->epsts = pch_udc_read_ep_status(ep);
pch_udc_clear_ep_status(ep, ep->epsts);
}
/* OUT */
if (ep_intr & (0x10000 << i)) {
ep = &dev->ep[UDC_EPOUT_IDX(i)];
ep->epsts = pch_udc_read_ep_status(ep);
pch_udc_clear_ep_status(ep, ep->epsts);
}
}
}
/**
* pch_udc_activate_control_ep() - This function enables the control endpoints
* for traffic after a reset
* @dev: Reference to the device structure
*/
static void pch_udc_activate_control_ep(struct pch_udc_dev *dev)
{
struct pch_udc_ep *ep;
u32 val;
/* Setup the IN endpoint */
ep = &dev->ep[UDC_EP0IN_IDX];
pch_udc_clear_ep_control(ep);
pch_udc_ep_fifo_flush(ep, ep->in);
pch_udc_ep_set_bufsz(ep, UDC_EP0IN_BUFF_SIZE, ep->in);
pch_udc_ep_set_maxpkt(ep, UDC_EP0IN_MAX_PKT_SIZE);
/* Initialize the IN EP Descriptor */
ep->td_data = NULL;
ep->td_stp = NULL;
ep->td_data_phys = 0;
ep->td_stp_phys = 0;
/* Setup the OUT endpoint */
ep = &dev->ep[UDC_EP0OUT_IDX];
pch_udc_clear_ep_control(ep);
pch_udc_ep_fifo_flush(ep, ep->in);
pch_udc_ep_set_bufsz(ep, UDC_EP0OUT_BUFF_SIZE, ep->in);
pch_udc_ep_set_maxpkt(ep, UDC_EP0OUT_MAX_PKT_SIZE);
val = UDC_EP0OUT_MAX_PKT_SIZE << UDC_CSR_NE_MAX_PKT_SHIFT;
pch_udc_write_csr(ep->dev, val, UDC_EP0OUT_IDX);
/* Initialize the SETUP buffer */
pch_udc_init_setup_buff(ep->td_stp);
/* Write the pointer address of dma descriptor */
pch_udc_ep_set_subptr(ep, ep->td_stp_phys);
/* Write the pointer address of Setup descriptor */
pch_udc_ep_set_ddptr(ep, ep->td_data_phys);
/* Initialize the dma descriptor */
ep->td_data->status = PCH_UDC_DMA_LAST;
ep->td_data->dataptr = dev->dma_addr;
ep->td_data->next = ep->td_data_phys;
pch_udc_ep_clear_nak(ep);
}
/**
* pch_udc_svc_ur_interrupt() - This function handles a USB reset interrupt
* @dev: Reference to driver structure
*/
static void pch_udc_svc_ur_interrupt(struct pch_udc_dev *dev)
{
struct pch_udc_ep *ep;
int i;
pch_udc_clear_dma(dev, DMA_DIR_TX);
pch_udc_clear_dma(dev, DMA_DIR_RX);
/* Mask all endpoint interrupts */
pch_udc_disable_ep_interrupts(dev, UDC_EPINT_MSK_DISABLE_ALL);
/* clear all endpoint interrupts */
pch_udc_write_ep_interrupts(dev, UDC_EPINT_MSK_DISABLE_ALL);
for (i = 0; i < PCH_UDC_EP_NUM; i++) {
ep = &dev->ep[i];
pch_udc_clear_ep_status(ep, UDC_EPSTS_ALL_CLR_MASK);
pch_udc_clear_ep_control(ep);
pch_udc_ep_set_ddptr(ep, 0);
pch_udc_write_csr(ep->dev, 0x00, i);
}
dev->stall = 0;
dev->prot_stall = 0;
dev->waiting_zlp_ack = 0;
dev->set_cfg_not_acked = 0;
/* disable ep to empty req queue. Skip the control EP's */
for (i = 0; i < (PCH_UDC_USED_EP_NUM*2); i++) {
ep = &dev->ep[i];
pch_udc_ep_set_nak(ep);
pch_udc_ep_fifo_flush(ep, ep->in);
/* Complete request queue */
empty_req_queue(ep);
}
if (dev->driver && dev->driver->disconnect) {
spin_unlock(&dev->lock);
dev->driver->disconnect(&dev->gadget);
spin_lock(&dev->lock);
}
}
/**
* pch_udc_svc_enum_interrupt() - This function handles a USB speed enumeration
* done interrupt
* @dev: Reference to driver structure
*/
static void pch_udc_svc_enum_interrupt(struct pch_udc_dev *dev)
{
u32 dev_stat, dev_speed;
u32 speed = USB_SPEED_FULL;
dev_stat = pch_udc_read_device_status(dev);
dev_speed = (dev_stat & UDC_DEVSTS_ENUM_SPEED_MASK) >>
UDC_DEVSTS_ENUM_SPEED_SHIFT;
switch (dev_speed) {
case UDC_DEVSTS_ENUM_SPEED_HIGH:
speed = USB_SPEED_HIGH;
break;
case UDC_DEVSTS_ENUM_SPEED_FULL:
speed = USB_SPEED_FULL;
break;
case UDC_DEVSTS_ENUM_SPEED_LOW:
speed = USB_SPEED_LOW;
break;
default:
BUG();
}
dev->gadget.speed = speed;
pch_udc_activate_control_ep(dev);
pch_udc_enable_ep_interrupts(dev, UDC_EPINT_IN_EP0 | UDC_EPINT_OUT_EP0);
pch_udc_set_dma(dev, DMA_DIR_TX);
pch_udc_set_dma(dev, DMA_DIR_RX);
pch_udc_ep_set_rrdy(&(dev->ep[UDC_EP0OUT_IDX]));
/* enable device interrupts */
pch_udc_enable_interrupts(dev, UDC_DEVINT_UR | UDC_DEVINT_US |
UDC_DEVINT_ES | UDC_DEVINT_ENUM |
UDC_DEVINT_SI | UDC_DEVINT_SC);
}
/**
* pch_udc_svc_intf_interrupt() - This function handles a set interface
* interrupt
* @dev: Reference to driver structure
*/
static void pch_udc_svc_intf_interrupt(struct pch_udc_dev *dev)
{
u32 reg, dev_stat = 0;
int i, ret;
dev_stat = pch_udc_read_device_status(dev);
dev->cfg_data.cur_intf = (dev_stat & UDC_DEVSTS_INTF_MASK) >>
UDC_DEVSTS_INTF_SHIFT;
dev->cfg_data.cur_alt = (dev_stat & UDC_DEVSTS_ALT_MASK) >>
UDC_DEVSTS_ALT_SHIFT;
dev->set_cfg_not_acked = 1;
/* Construct the usb request for gadget driver and inform it */
memset(&dev->setup_data, 0 , sizeof dev->setup_data);
dev->setup_data.bRequest = USB_REQ_SET_INTERFACE;
dev->setup_data.bRequestType = USB_RECIP_INTERFACE;
dev->setup_data.wValue = cpu_to_le16(dev->cfg_data.cur_alt);
dev->setup_data.wIndex = cpu_to_le16(dev->cfg_data.cur_intf);
/* programm the Endpoint Cfg registers */
/* Only one end point cfg register */
reg = pch_udc_read_csr(dev, UDC_EP0OUT_IDX);
reg = (reg & ~UDC_CSR_NE_INTF_MASK) |
(dev->cfg_data.cur_intf << UDC_CSR_NE_INTF_SHIFT);
reg = (reg & ~UDC_CSR_NE_ALT_MASK) |
(dev->cfg_data.cur_alt << UDC_CSR_NE_ALT_SHIFT);
pch_udc_write_csr(dev, reg, UDC_EP0OUT_IDX);
for (i = 0; i < PCH_UDC_USED_EP_NUM * 2; i++) {
/* clear stall bits */
pch_udc_ep_clear_stall(&(dev->ep[i]));
dev->ep[i].halted = 0;
}
dev->stall = 0;
spin_unlock(&dev->lock);
ret = dev->driver->setup(&dev->gadget, &dev->setup_data);
spin_lock(&dev->lock);
}
/**
* pch_udc_svc_cfg_interrupt() - This function handles a set configuration
* interrupt
* @dev: Reference to driver structure
*/
static void pch_udc_svc_cfg_interrupt(struct pch_udc_dev *dev)
{
int i, ret;
u32 reg, dev_stat = 0;
dev_stat = pch_udc_read_device_status(dev);
dev->set_cfg_not_acked = 1;
dev->cfg_data.cur_cfg = (dev_stat & UDC_DEVSTS_CFG_MASK) >>
UDC_DEVSTS_CFG_SHIFT;
/* make usb request for gadget driver */
memset(&dev->setup_data, 0 , sizeof dev->setup_data);
dev->setup_data.bRequest = USB_REQ_SET_CONFIGURATION;
dev->setup_data.wValue = cpu_to_le16(dev->cfg_data.cur_cfg);
/* program the NE registers */
/* Only one end point cfg register */
reg = pch_udc_read_csr(dev, UDC_EP0OUT_IDX);
reg = (reg & ~UDC_CSR_NE_CFG_MASK) |
(dev->cfg_data.cur_cfg << UDC_CSR_NE_CFG_SHIFT);
pch_udc_write_csr(dev, reg, UDC_EP0OUT_IDX);
for (i = 0; i < PCH_UDC_USED_EP_NUM * 2; i++) {
/* clear stall bits */
pch_udc_ep_clear_stall(&(dev->ep[i]));
dev->ep[i].halted = 0;
}
dev->stall = 0;
/* call gadget zero with setup data received */
spin_unlock(&dev->lock);
ret = dev->driver->setup(&dev->gadget, &dev->setup_data);
spin_lock(&dev->lock);
}
/**
* pch_udc_dev_isr() - This function services device interrupts
* by invoking appropriate routines.
* @dev: Reference to the device structure
* @dev_intr: The Device interrupt status.
*/
static void pch_udc_dev_isr(struct pch_udc_dev *dev, u32 dev_intr)
{
int vbus;
/* USB Reset Interrupt */
if (dev_intr & UDC_DEVINT_UR) {
pch_udc_svc_ur_interrupt(dev);
dev_dbg(&dev->pdev->dev, "USB_RESET\n");
}
/* Enumeration Done Interrupt */
if (dev_intr & UDC_DEVINT_ENUM) {
pch_udc_svc_enum_interrupt(dev);
dev_dbg(&dev->pdev->dev, "USB_ENUM\n");
}
/* Set Interface Interrupt */
if (dev_intr & UDC_DEVINT_SI)
pch_udc_svc_intf_interrupt(dev);
/* Set Config Interrupt */
if (dev_intr & UDC_DEVINT_SC)
pch_udc_svc_cfg_interrupt(dev);
/* USB Suspend interrupt */
if (dev_intr & UDC_DEVINT_US) {
if (dev->driver
&& dev->driver->suspend) {
spin_unlock(&dev->lock);
dev->driver->suspend(&dev->gadget);
spin_lock(&dev->lock);
}
vbus = pch_vbus_gpio_get_value(dev);
if ((dev->vbus_session == 0)
&& (vbus != 1)) {
if (dev->driver && dev->driver->disconnect) {
spin_unlock(&dev->lock);
dev->driver->disconnect(&dev->gadget);
spin_lock(&dev->lock);
}
pch_udc_reconnect(dev);
} else if ((dev->vbus_session == 0)
&& (vbus == 1)
&& !dev->vbus_gpio.intr)
schedule_work(&dev->vbus_gpio.irq_work_fall);
dev_dbg(&dev->pdev->dev, "USB_SUSPEND\n");
}
/* Clear the SOF interrupt, if enabled */
if (dev_intr & UDC_DEVINT_SOF)
dev_dbg(&dev->pdev->dev, "SOF\n");
/* ES interrupt, IDLE > 3ms on the USB */
if (dev_intr & UDC_DEVINT_ES)
dev_dbg(&dev->pdev->dev, "ES\n");
/* RWKP interrupt */
if (dev_intr & UDC_DEVINT_RWKP)
dev_dbg(&dev->pdev->dev, "RWKP\n");
}
/**
* pch_udc_isr() - This function handles interrupts from the PCH USB Device
* @irq: Interrupt request number
* @dev: Reference to the device structure
*/
static irqreturn_t pch_udc_isr(int irq, void *pdev)
{
struct pch_udc_dev *dev = (struct pch_udc_dev *) pdev;
u32 dev_intr, ep_intr;
int i;
dev_intr = pch_udc_read_device_interrupts(dev);
ep_intr = pch_udc_read_ep_interrupts(dev);
/* For a hot plug, this find that the controller is hung up. */
if (dev_intr == ep_intr)
if (dev_intr == pch_udc_readl(dev, UDC_DEVCFG_ADDR)) {
dev_dbg(&dev->pdev->dev, "UDC: Hung up\n");
/* The controller is reset */
pch_udc_writel(dev, UDC_SRST, UDC_SRST_ADDR);
return IRQ_HANDLED;
}
if (dev_intr)
/* Clear device interrupts */
pch_udc_write_device_interrupts(dev, dev_intr);
if (ep_intr)
/* Clear ep interrupts */
pch_udc_write_ep_interrupts(dev, ep_intr);
if (!dev_intr && !ep_intr)
return IRQ_NONE;
spin_lock(&dev->lock);
if (dev_intr)
pch_udc_dev_isr(dev, dev_intr);
if (ep_intr) {
pch_udc_read_all_epstatus(dev, ep_intr);
/* Process Control In interrupts, if present */
if (ep_intr & UDC_EPINT_IN_EP0) {
pch_udc_svc_control_in(dev);
pch_udc_postsvc_epinters(dev, 0);
}
/* Process Control Out interrupts, if present */
if (ep_intr & UDC_EPINT_OUT_EP0)
pch_udc_svc_control_out(dev);
/* Process data in end point interrupts */
for (i = 1; i < PCH_UDC_USED_EP_NUM; i++) {
if (ep_intr & (1 << i)) {
pch_udc_svc_data_in(dev, i);
pch_udc_postsvc_epinters(dev, i);
}
}
/* Process data out end point interrupts */
for (i = UDC_EPINT_OUT_SHIFT + 1; i < (UDC_EPINT_OUT_SHIFT +
PCH_UDC_USED_EP_NUM); i++)
if (ep_intr & (1 << i))
pch_udc_svc_data_out(dev, i -
UDC_EPINT_OUT_SHIFT);
}
spin_unlock(&dev->lock);
return IRQ_HANDLED;
}
/**
* pch_udc_setup_ep0() - This function enables control endpoint for traffic
* @dev: Reference to the device structure
*/
static void pch_udc_setup_ep0(struct pch_udc_dev *dev)
{
/* enable ep0 interrupts */
pch_udc_enable_ep_interrupts(dev, UDC_EPINT_IN_EP0 |
UDC_EPINT_OUT_EP0);
/* enable device interrupts */
pch_udc_enable_interrupts(dev, UDC_DEVINT_UR | UDC_DEVINT_US |
UDC_DEVINT_ES | UDC_DEVINT_ENUM |
UDC_DEVINT_SI | UDC_DEVINT_SC);
}
/**
* gadget_release() - Free the gadget driver private data
* @pdev reference to struct pci_dev
*/
static void gadget_release(struct device *pdev)
{
struct pch_udc_dev *dev = dev_get_drvdata(pdev);
kfree(dev);
}
/**
* pch_udc_pcd_reinit() - This API initializes the endpoint structures
* @dev: Reference to the driver structure
*/
static void pch_udc_pcd_reinit(struct pch_udc_dev *dev)
{
const char *const ep_string[] = {
ep0_string, "ep0out", "ep1in", "ep1out", "ep2in", "ep2out",
"ep3in", "ep3out", "ep4in", "ep4out", "ep5in", "ep5out",
"ep6in", "ep6out", "ep7in", "ep7out", "ep8in", "ep8out",
"ep9in", "ep9out", "ep10in", "ep10out", "ep11in", "ep11out",
"ep12in", "ep12out", "ep13in", "ep13out", "ep14in", "ep14out",
"ep15in", "ep15out",
};
int i;
dev->gadget.speed = USB_SPEED_UNKNOWN;
INIT_LIST_HEAD(&dev->gadget.ep_list);
/* Initialize the endpoints structures */
memset(dev->ep, 0, sizeof dev->ep);
for (i = 0; i < PCH_UDC_EP_NUM; i++) {
struct pch_udc_ep *ep = &dev->ep[i];
ep->dev = dev;
ep->halted = 1;
ep->num = i / 2;
ep->in = ~i & 1;
ep->ep.name = ep_string[i];
ep->ep.ops = &pch_udc_ep_ops;
if (ep->in)
ep->offset_addr = ep->num * UDC_EP_REG_SHIFT;
else
ep->offset_addr = (UDC_EPINT_OUT_SHIFT + ep->num) *
UDC_EP_REG_SHIFT;
/* need to set ep->ep.maxpacket and set Default Configuration?*/
ep->ep.maxpacket = UDC_BULK_MAX_PKT_SIZE;
list_add_tail(&ep->ep.ep_list, &dev->gadget.ep_list);
INIT_LIST_HEAD(&ep->queue);
}
dev->ep[UDC_EP0IN_IDX].ep.maxpacket = UDC_EP0IN_MAX_PKT_SIZE;
dev->ep[UDC_EP0OUT_IDX].ep.maxpacket = UDC_EP0OUT_MAX_PKT_SIZE;
/* remove ep0 in and out from the list. They have own pointer */
list_del_init(&dev->ep[UDC_EP0IN_IDX].ep.ep_list);
list_del_init(&dev->ep[UDC_EP0OUT_IDX].ep.ep_list);
dev->gadget.ep0 = &dev->ep[UDC_EP0IN_IDX].ep;
INIT_LIST_HEAD(&dev->gadget.ep0->ep_list);
}
/**
* pch_udc_pcd_init() - This API initializes the driver structure
* @dev: Reference to the driver structure
*
* Return codes:
* 0: Success
*/
static int pch_udc_pcd_init(struct pch_udc_dev *dev)
{
pch_udc_init(dev);
pch_udc_pcd_reinit(dev);
pch_vbus_gpio_init(dev, vbus_gpio_port);
return 0;
}
/**
* init_dma_pools() - create dma pools during initialization
* @pdev: reference to struct pci_dev
*/
static int init_dma_pools(struct pch_udc_dev *dev)
{
struct pch_udc_stp_dma_desc *td_stp;
struct pch_udc_data_dma_desc *td_data;
/* DMA setup */
dev->data_requests = pci_pool_create("data_requests", dev->pdev,
sizeof(struct pch_udc_data_dma_desc), 0, 0);
if (!dev->data_requests) {
dev_err(&dev->pdev->dev, "%s: can't get request data pool\n",
__func__);
return -ENOMEM;
}
/* dma desc for setup data */
dev->stp_requests = pci_pool_create("setup requests", dev->pdev,
sizeof(struct pch_udc_stp_dma_desc), 0, 0);
if (!dev->stp_requests) {
dev_err(&dev->pdev->dev, "%s: can't get setup request pool\n",
__func__);
return -ENOMEM;
}
/* setup */
td_stp = pci_pool_alloc(dev->stp_requests, GFP_KERNEL,
&dev->ep[UDC_EP0OUT_IDX].td_stp_phys);
if (!td_stp) {
dev_err(&dev->pdev->dev,
"%s: can't allocate setup dma descriptor\n", __func__);
return -ENOMEM;
}
dev->ep[UDC_EP0OUT_IDX].td_stp = td_stp;
/* data: 0 packets !? */
td_data = pci_pool_alloc(dev->data_requests, GFP_KERNEL,
&dev->ep[UDC_EP0OUT_IDX].td_data_phys);
if (!td_data) {
dev_err(&dev->pdev->dev,
"%s: can't allocate data dma descriptor\n", __func__);
return -ENOMEM;
}
dev->ep[UDC_EP0OUT_IDX].td_data = td_data;
dev->ep[UDC_EP0IN_IDX].td_stp = NULL;
dev->ep[UDC_EP0IN_IDX].td_stp_phys = 0;
dev->ep[UDC_EP0IN_IDX].td_data = NULL;
dev->ep[UDC_EP0IN_IDX].td_data_phys = 0;
dev->ep0out_buf = kzalloc(UDC_EP0OUT_BUFF_SIZE * 4, GFP_KERNEL);
if (!dev->ep0out_buf)
return -ENOMEM;
dev->dma_addr = dma_map_single(&dev->pdev->dev, dev->ep0out_buf,
UDC_EP0OUT_BUFF_SIZE * 4,
DMA_FROM_DEVICE);
return 0;
}
static int pch_udc_start(struct usb_gadget_driver *driver,
int (*bind)(struct usb_gadget *))
{
struct pch_udc_dev *dev = pch_udc;
int retval;
if (!driver || (driver->max_speed == USB_SPEED_UNKNOWN) || !bind ||
!driver->setup || !driver->unbind || !driver->disconnect) {
dev_err(&dev->pdev->dev,
"%s: invalid driver parameter\n", __func__);
return -EINVAL;
}
if (!dev)
return -ENODEV;
if (dev->driver) {
dev_err(&dev->pdev->dev, "%s: already bound\n", __func__);
return -EBUSY;
}
driver->driver.bus = NULL;
dev->driver = driver;
dev->gadget.dev.driver = &driver->driver;
/* Invoke the bind routine of the gadget driver */
retval = bind(&dev->gadget);
if (retval) {
dev_err(&dev->pdev->dev, "%s: binding to %s returning %d\n",
__func__, driver->driver.name, retval);
dev->driver = NULL;
dev->gadget.dev.driver = NULL;
return retval;
}
/* get ready for ep0 traffic */
pch_udc_setup_ep0(dev);
/* clear SD */
if ((pch_vbus_gpio_get_value(dev) != 0) || !dev->vbus_gpio.intr)
pch_udc_clear_disconnect(dev);
dev->connected = 1;
return 0;
}
static int pch_udc_stop(struct usb_gadget_driver *driver)
{
struct pch_udc_dev *dev = pch_udc;
if (!dev)
return -ENODEV;
if (!driver || (driver != dev->driver)) {
dev_err(&dev->pdev->dev,
"%s: invalid driver parameter\n", __func__);
return -EINVAL;
}
pch_udc_disable_interrupts(dev, UDC_DEVINT_MSK);
/* Assures that there are no pending requests with this driver */
driver->disconnect(&dev->gadget);
driver->unbind(&dev->gadget);
dev->gadget.dev.driver = NULL;
dev->driver = NULL;
dev->connected = 0;
/* set SD */
pch_udc_set_disconnect(dev);
return 0;
}
static void pch_udc_shutdown(struct pci_dev *pdev)
{
struct pch_udc_dev *dev = pci_get_drvdata(pdev);
pch_udc_disable_interrupts(dev, UDC_DEVINT_MSK);
pch_udc_disable_ep_interrupts(dev, UDC_EPINT_MSK_DISABLE_ALL);
/* disable the pullup so the host will think we're gone */
pch_udc_set_disconnect(dev);
}
static void pch_udc_remove(struct pci_dev *pdev)
{
struct pch_udc_dev *dev = pci_get_drvdata(pdev);
usb_del_gadget_udc(&dev->gadget);
/* gadget driver must not be registered */
if (dev->driver)
dev_err(&pdev->dev,
"%s: gadget driver still bound!!!\n", __func__);
/* dma pool cleanup */
if (dev->data_requests)
pci_pool_destroy(dev->data_requests);
if (dev->stp_requests) {
/* cleanup DMA desc's for ep0in */
if (dev->ep[UDC_EP0OUT_IDX].td_stp) {
pci_pool_free(dev->stp_requests,
dev->ep[UDC_EP0OUT_IDX].td_stp,
dev->ep[UDC_EP0OUT_IDX].td_stp_phys);
}
if (dev->ep[UDC_EP0OUT_IDX].td_data) {
pci_pool_free(dev->stp_requests,
dev->ep[UDC_EP0OUT_IDX].td_data,
dev->ep[UDC_EP0OUT_IDX].td_data_phys);
}
pci_pool_destroy(dev->stp_requests);
}
if (dev->dma_addr)
dma_unmap_single(&dev->pdev->dev, dev->dma_addr,
UDC_EP0OUT_BUFF_SIZE * 4, DMA_FROM_DEVICE);
kfree(dev->ep0out_buf);
pch_vbus_gpio_free(dev);
pch_udc_exit(dev);
if (dev->irq_registered)
free_irq(pdev->irq, dev);
if (dev->base_addr)
iounmap(dev->base_addr);
if (dev->mem_region)
release_mem_region(dev->phys_addr,
pci_resource_len(pdev, PCH_UDC_PCI_BAR));
if (dev->active)
pci_disable_device(pdev);
if (dev->registered)
device_unregister(&dev->gadget.dev);
kfree(dev);
pci_set_drvdata(pdev, NULL);
}
#ifdef CONFIG_PM
static int pch_udc_suspend(struct pci_dev *pdev, pm_message_t state)
{
struct pch_udc_dev *dev = pci_get_drvdata(pdev);
pch_udc_disable_interrupts(dev, UDC_DEVINT_MSK);
pch_udc_disable_ep_interrupts(dev, UDC_EPINT_MSK_DISABLE_ALL);
pci_disable_device(pdev);
pci_enable_wake(pdev, PCI_D3hot, 0);
if (pci_save_state(pdev)) {
dev_err(&pdev->dev,
"%s: could not save PCI config state\n", __func__);
return -ENOMEM;
}
pci_set_power_state(pdev, pci_choose_state(pdev, state));
return 0;
}
static int pch_udc_resume(struct pci_dev *pdev)
{
int ret;
pci_set_power_state(pdev, PCI_D0);
pci_restore_state(pdev);
ret = pci_enable_device(pdev);
if (ret) {
dev_err(&pdev->dev, "%s: pci_enable_device failed\n", __func__);
return ret;
}
pci_enable_wake(pdev, PCI_D3hot, 0);
return 0;
}
#else
#define pch_udc_suspend NULL
#define pch_udc_resume NULL
#endif /* CONFIG_PM */
static int pch_udc_probe(struct pci_dev *pdev,
const struct pci_device_id *id)
{
unsigned long resource;
unsigned long len;
int retval;
struct pch_udc_dev *dev;
/* one udc only */
if (pch_udc) {
pr_err("%s: already probed\n", __func__);
return -EBUSY;
}
/* init */
dev = kzalloc(sizeof *dev, GFP_KERNEL);
if (!dev) {
pr_err("%s: no memory for device structure\n", __func__);
return -ENOMEM;
}
/* pci setup */
if (pci_enable_device(pdev) < 0) {
kfree(dev);
pr_err("%s: pci_enable_device failed\n", __func__);
return -ENODEV;
}
dev->active = 1;
pci_set_drvdata(pdev, dev);
/* PCI resource allocation */
resource = pci_resource_start(pdev, 1);
len = pci_resource_len(pdev, 1);
if (!request_mem_region(resource, len, KBUILD_MODNAME)) {
dev_err(&pdev->dev, "%s: pci device used already\n", __func__);
retval = -EBUSY;
goto finished;
}
dev->phys_addr = resource;
dev->mem_region = 1;
dev->base_addr = ioremap_nocache(resource, len);
if (!dev->base_addr) {
pr_err("%s: device memory cannot be mapped\n", __func__);
retval = -ENOMEM;
goto finished;
}
if (!pdev->irq) {
dev_err(&pdev->dev, "%s: irq not set\n", __func__);
retval = -ENODEV;
goto finished;
}
pch_udc = dev;
/* initialize the hardware */
if (pch_udc_pcd_init(dev)) {
retval = -ENODEV;
goto finished;
}
if (request_irq(pdev->irq, pch_udc_isr, IRQF_SHARED, KBUILD_MODNAME,
dev)) {
dev_err(&pdev->dev, "%s: request_irq(%d) fail\n", __func__,
pdev->irq);
retval = -ENODEV;
goto finished;
}
dev->irq = pdev->irq;
dev->irq_registered = 1;
pci_set_master(pdev);
pci_try_set_mwi(pdev);
/* device struct setup */
spin_lock_init(&dev->lock);
dev->pdev = pdev;
dev->gadget.ops = &pch_udc_ops;
retval = init_dma_pools(dev);
if (retval)
goto finished;
dev_set_name(&dev->gadget.dev, "gadget");
dev->gadget.dev.parent = &pdev->dev;
dev->gadget.dev.dma_mask = pdev->dev.dma_mask;
dev->gadget.dev.release = gadget_release;
dev->gadget.name = KBUILD_MODNAME;
dev->gadget.max_speed = USB_SPEED_HIGH;
retval = device_register(&dev->gadget.dev);
if (retval)
goto finished;
dev->registered = 1;
/* Put the device in disconnected state till a driver is bound */
pch_udc_set_disconnect(dev);
retval = usb_add_gadget_udc(&pdev->dev, &dev->gadget);
if (retval)
goto finished;
return 0;
finished:
pch_udc_remove(pdev);
return retval;
}
static DEFINE_PCI_DEVICE_TABLE(pch_udc_pcidev_id) = {
{
PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_EG20T_UDC),
.class = (PCI_CLASS_SERIAL_USB << 8) | 0xfe,
.class_mask = 0xffffffff,
},
{
PCI_DEVICE(PCI_VENDOR_ID_ROHM, PCI_DEVICE_ID_ML7213_IOH_UDC),
.class = (PCI_CLASS_SERIAL_USB << 8) | 0xfe,
.class_mask = 0xffffffff,
},
{
PCI_DEVICE(PCI_VENDOR_ID_ROHM, PCI_DEVICE_ID_ML7831_IOH_UDC),
.class = (PCI_CLASS_SERIAL_USB << 8) | 0xfe,
.class_mask = 0xffffffff,
},
{ 0 },
};
MODULE_DEVICE_TABLE(pci, pch_udc_pcidev_id);
static struct pci_driver pch_udc_driver = {
.name = KBUILD_MODNAME,
.id_table = pch_udc_pcidev_id,
.probe = pch_udc_probe,
.remove = pch_udc_remove,
.suspend = pch_udc_suspend,
.resume = pch_udc_resume,
.shutdown = pch_udc_shutdown,
};
static int __init pch_udc_pci_init(void)
{
return pci_register_driver(&pch_udc_driver);
}
module_init(pch_udc_pci_init);
static void __exit pch_udc_pci_exit(void)
{
pci_unregister_driver(&pch_udc_driver);
}
module_exit(pch_udc_pci_exit);
MODULE_DESCRIPTION("Intel EG20T USB Device Controller");
MODULE_AUTHOR("LAPIS Semiconductor, <tomoya-linux@dsn.lapis-semi.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
mukulsoni/android_kernel_samsung_ms013g-G4SWA | drivers/isdn/mISDN/hwchannel.c | 4773 | 8922 | /*
*
* Author Karsten Keil <kkeil@novell.com>
*
* Copyright 2008 by Karsten Keil <kkeil@novell.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.
*
*/
#include <linux/gfp.h>
#include <linux/module.h>
#include <linux/mISDNhw.h>
static void
dchannel_bh(struct work_struct *ws)
{
struct dchannel *dch = container_of(ws, struct dchannel, workq);
struct sk_buff *skb;
int err;
if (test_and_clear_bit(FLG_RECVQUEUE, &dch->Flags)) {
while ((skb = skb_dequeue(&dch->rqueue))) {
if (likely(dch->dev.D.peer)) {
err = dch->dev.D.recv(dch->dev.D.peer, skb);
if (err)
dev_kfree_skb(skb);
} else
dev_kfree_skb(skb);
}
}
if (test_and_clear_bit(FLG_PHCHANGE, &dch->Flags)) {
if (dch->phfunc)
dch->phfunc(dch);
}
}
static void
bchannel_bh(struct work_struct *ws)
{
struct bchannel *bch = container_of(ws, struct bchannel, workq);
struct sk_buff *skb;
int err;
if (test_and_clear_bit(FLG_RECVQUEUE, &bch->Flags)) {
while ((skb = skb_dequeue(&bch->rqueue))) {
bch->rcount--;
if (likely(bch->ch.peer)) {
err = bch->ch.recv(bch->ch.peer, skb);
if (err)
dev_kfree_skb(skb);
} else
dev_kfree_skb(skb);
}
}
}
int
mISDN_initdchannel(struct dchannel *ch, int maxlen, void *phf)
{
test_and_set_bit(FLG_HDLC, &ch->Flags);
ch->maxlen = maxlen;
ch->hw = NULL;
ch->rx_skb = NULL;
ch->tx_skb = NULL;
ch->tx_idx = 0;
ch->phfunc = phf;
skb_queue_head_init(&ch->squeue);
skb_queue_head_init(&ch->rqueue);
INIT_LIST_HEAD(&ch->dev.bchannels);
INIT_WORK(&ch->workq, dchannel_bh);
return 0;
}
EXPORT_SYMBOL(mISDN_initdchannel);
int
mISDN_initbchannel(struct bchannel *ch, int maxlen)
{
ch->Flags = 0;
ch->maxlen = maxlen;
ch->hw = NULL;
ch->rx_skb = NULL;
ch->tx_skb = NULL;
ch->tx_idx = 0;
skb_queue_head_init(&ch->rqueue);
ch->rcount = 0;
ch->next_skb = NULL;
INIT_WORK(&ch->workq, bchannel_bh);
return 0;
}
EXPORT_SYMBOL(mISDN_initbchannel);
int
mISDN_freedchannel(struct dchannel *ch)
{
if (ch->tx_skb) {
dev_kfree_skb(ch->tx_skb);
ch->tx_skb = NULL;
}
if (ch->rx_skb) {
dev_kfree_skb(ch->rx_skb);
ch->rx_skb = NULL;
}
skb_queue_purge(&ch->squeue);
skb_queue_purge(&ch->rqueue);
flush_work_sync(&ch->workq);
return 0;
}
EXPORT_SYMBOL(mISDN_freedchannel);
void
mISDN_clear_bchannel(struct bchannel *ch)
{
if (ch->tx_skb) {
dev_kfree_skb(ch->tx_skb);
ch->tx_skb = NULL;
}
ch->tx_idx = 0;
if (ch->rx_skb) {
dev_kfree_skb(ch->rx_skb);
ch->rx_skb = NULL;
}
if (ch->next_skb) {
dev_kfree_skb(ch->next_skb);
ch->next_skb = NULL;
}
test_and_clear_bit(FLG_TX_BUSY, &ch->Flags);
test_and_clear_bit(FLG_TX_NEXT, &ch->Flags);
test_and_clear_bit(FLG_ACTIVE, &ch->Flags);
}
EXPORT_SYMBOL(mISDN_clear_bchannel);
int
mISDN_freebchannel(struct bchannel *ch)
{
mISDN_clear_bchannel(ch);
skb_queue_purge(&ch->rqueue);
ch->rcount = 0;
flush_work_sync(&ch->workq);
return 0;
}
EXPORT_SYMBOL(mISDN_freebchannel);
static inline u_int
get_sapi_tei(u_char *p)
{
u_int sapi, tei;
sapi = *p >> 2;
tei = p[1] >> 1;
return sapi | (tei << 8);
}
void
recv_Dchannel(struct dchannel *dch)
{
struct mISDNhead *hh;
if (dch->rx_skb->len < 2) { /* at least 2 for sapi / tei */
dev_kfree_skb(dch->rx_skb);
dch->rx_skb = NULL;
return;
}
hh = mISDN_HEAD_P(dch->rx_skb);
hh->prim = PH_DATA_IND;
hh->id = get_sapi_tei(dch->rx_skb->data);
skb_queue_tail(&dch->rqueue, dch->rx_skb);
dch->rx_skb = NULL;
schedule_event(dch, FLG_RECVQUEUE);
}
EXPORT_SYMBOL(recv_Dchannel);
void
recv_Echannel(struct dchannel *ech, struct dchannel *dch)
{
struct mISDNhead *hh;
if (ech->rx_skb->len < 2) { /* at least 2 for sapi / tei */
dev_kfree_skb(ech->rx_skb);
ech->rx_skb = NULL;
return;
}
hh = mISDN_HEAD_P(ech->rx_skb);
hh->prim = PH_DATA_E_IND;
hh->id = get_sapi_tei(ech->rx_skb->data);
skb_queue_tail(&dch->rqueue, ech->rx_skb);
ech->rx_skb = NULL;
schedule_event(dch, FLG_RECVQUEUE);
}
EXPORT_SYMBOL(recv_Echannel);
void
recv_Bchannel(struct bchannel *bch, unsigned int id)
{
struct mISDNhead *hh;
hh = mISDN_HEAD_P(bch->rx_skb);
hh->prim = PH_DATA_IND;
hh->id = id;
if (bch->rcount >= 64) {
printk(KERN_WARNING "B-channel %p receive queue overflow, "
"flushing!\n", bch);
skb_queue_purge(&bch->rqueue);
bch->rcount = 0;
return;
}
bch->rcount++;
skb_queue_tail(&bch->rqueue, bch->rx_skb);
bch->rx_skb = NULL;
schedule_event(bch, FLG_RECVQUEUE);
}
EXPORT_SYMBOL(recv_Bchannel);
void
recv_Dchannel_skb(struct dchannel *dch, struct sk_buff *skb)
{
skb_queue_tail(&dch->rqueue, skb);
schedule_event(dch, FLG_RECVQUEUE);
}
EXPORT_SYMBOL(recv_Dchannel_skb);
void
recv_Bchannel_skb(struct bchannel *bch, struct sk_buff *skb)
{
if (bch->rcount >= 64) {
printk(KERN_WARNING "B-channel %p receive queue overflow, "
"flushing!\n", bch);
skb_queue_purge(&bch->rqueue);
bch->rcount = 0;
}
bch->rcount++;
skb_queue_tail(&bch->rqueue, skb);
schedule_event(bch, FLG_RECVQUEUE);
}
EXPORT_SYMBOL(recv_Bchannel_skb);
static void
confirm_Dsend(struct dchannel *dch)
{
struct sk_buff *skb;
skb = _alloc_mISDN_skb(PH_DATA_CNF, mISDN_HEAD_ID(dch->tx_skb),
0, NULL, GFP_ATOMIC);
if (!skb) {
printk(KERN_ERR "%s: no skb id %x\n", __func__,
mISDN_HEAD_ID(dch->tx_skb));
return;
}
skb_queue_tail(&dch->rqueue, skb);
schedule_event(dch, FLG_RECVQUEUE);
}
int
get_next_dframe(struct dchannel *dch)
{
dch->tx_idx = 0;
dch->tx_skb = skb_dequeue(&dch->squeue);
if (dch->tx_skb) {
confirm_Dsend(dch);
return 1;
}
dch->tx_skb = NULL;
test_and_clear_bit(FLG_TX_BUSY, &dch->Flags);
return 0;
}
EXPORT_SYMBOL(get_next_dframe);
void
confirm_Bsend(struct bchannel *bch)
{
struct sk_buff *skb;
if (bch->rcount >= 64) {
printk(KERN_WARNING "B-channel %p receive queue overflow, "
"flushing!\n", bch);
skb_queue_purge(&bch->rqueue);
bch->rcount = 0;
}
skb = _alloc_mISDN_skb(PH_DATA_CNF, mISDN_HEAD_ID(bch->tx_skb),
0, NULL, GFP_ATOMIC);
if (!skb) {
printk(KERN_ERR "%s: no skb id %x\n", __func__,
mISDN_HEAD_ID(bch->tx_skb));
return;
}
bch->rcount++;
skb_queue_tail(&bch->rqueue, skb);
schedule_event(bch, FLG_RECVQUEUE);
}
EXPORT_SYMBOL(confirm_Bsend);
int
get_next_bframe(struct bchannel *bch)
{
bch->tx_idx = 0;
if (test_bit(FLG_TX_NEXT, &bch->Flags)) {
bch->tx_skb = bch->next_skb;
if (bch->tx_skb) {
bch->next_skb = NULL;
test_and_clear_bit(FLG_TX_NEXT, &bch->Flags);
if (!test_bit(FLG_TRANSPARENT, &bch->Flags))
confirm_Bsend(bch); /* not for transparent */
return 1;
} else {
test_and_clear_bit(FLG_TX_NEXT, &bch->Flags);
printk(KERN_WARNING "B TX_NEXT without skb\n");
}
}
bch->tx_skb = NULL;
test_and_clear_bit(FLG_TX_BUSY, &bch->Flags);
return 0;
}
EXPORT_SYMBOL(get_next_bframe);
void
queue_ch_frame(struct mISDNchannel *ch, u_int pr, int id, struct sk_buff *skb)
{
struct mISDNhead *hh;
if (!skb) {
_queue_data(ch, pr, id, 0, NULL, GFP_ATOMIC);
} else {
if (ch->peer) {
hh = mISDN_HEAD_P(skb);
hh->prim = pr;
hh->id = id;
if (!ch->recv(ch->peer, skb))
return;
}
dev_kfree_skb(skb);
}
}
EXPORT_SYMBOL(queue_ch_frame);
int
dchannel_senddata(struct dchannel *ch, struct sk_buff *skb)
{
/* check oversize */
if (skb->len <= 0) {
printk(KERN_WARNING "%s: skb too small\n", __func__);
return -EINVAL;
}
if (skb->len > ch->maxlen) {
printk(KERN_WARNING "%s: skb too large(%d/%d)\n",
__func__, skb->len, ch->maxlen);
return -EINVAL;
}
/* HW lock must be obtained */
if (test_and_set_bit(FLG_TX_BUSY, &ch->Flags)) {
skb_queue_tail(&ch->squeue, skb);
return 0;
} else {
/* write to fifo */
ch->tx_skb = skb;
ch->tx_idx = 0;
return 1;
}
}
EXPORT_SYMBOL(dchannel_senddata);
int
bchannel_senddata(struct bchannel *ch, struct sk_buff *skb)
{
/* check oversize */
if (skb->len <= 0) {
printk(KERN_WARNING "%s: skb too small\n", __func__);
return -EINVAL;
}
if (skb->len > ch->maxlen) {
printk(KERN_WARNING "%s: skb too large(%d/%d)\n",
__func__, skb->len, ch->maxlen);
return -EINVAL;
}
/* HW lock must be obtained */
/* check for pending next_skb */
if (ch->next_skb) {
printk(KERN_WARNING
"%s: next_skb exist ERROR (skb->len=%d next_skb->len=%d)\n",
__func__, skb->len, ch->next_skb->len);
return -EBUSY;
}
if (test_and_set_bit(FLG_TX_BUSY, &ch->Flags)) {
test_and_set_bit(FLG_TX_NEXT, &ch->Flags);
ch->next_skb = skb;
return 0;
} else {
/* write to fifo */
ch->tx_skb = skb;
ch->tx_idx = 0;
return 1;
}
}
EXPORT_SYMBOL(bchannel_senddata);
| gpl-2.0 |
Arc-Team/android_kernel_samsung_comanche | drivers/usb/storage/protocol.c | 4773 | 7114 | /* Driver for USB Mass Storage compliant devices
*
* Current development and maintenance by:
* (c) 1999-2002 Matthew Dharm (mdharm-usb@one-eyed-alien.net)
*
* Developed with the assistance of:
* (c) 2000 David L. Brown, Jr. (usb-storage@davidb.org)
* (c) 2002 Alan Stern (stern@rowland.org)
*
* Initial work by:
* (c) 1999 Michael Gee (michael@linuxspecific.com)
*
* This driver is based on the 'USB Mass Storage Class' document. This
* describes in detail the protocol used to communicate with such
* devices. Clearly, the designers had SCSI and ATAPI commands in
* mind when they created this document. The commands are all very
* similar to commands in the SCSI-II and ATAPI specifications.
*
* It is important to note that in a number of cases this class
* exhibits class-specific exemptions from the USB specification.
* Notably the usage of NAK, STALL and ACK differs from the norm, in
* that they are used to communicate wait, failed and OK on commands.
*
* Also, for certain devices, the interrupt endpoint is used to convey
* status of a command.
*
* Please see http://www.one-eyed-alien.net/~mdharm/linux-usb for more
* information about 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, 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/highmem.h>
#include <linux/export.h>
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include "usb.h"
#include "protocol.h"
#include "debug.h"
#include "scsiglue.h"
#include "transport.h"
/***********************************************************************
* Protocol routines
***********************************************************************/
void usb_stor_pad12_command(struct scsi_cmnd *srb, struct us_data *us)
{
/*
* Pad the SCSI command with zeros out to 12 bytes. If the
* command already is 12 bytes or longer, leave it alone.
*
* NOTE: This only works because a scsi_cmnd struct field contains
* a unsigned char cmnd[16], so we know we have storage available
*/
for (; srb->cmd_len<12; srb->cmd_len++)
srb->cmnd[srb->cmd_len] = 0;
/* send the command to the transport layer */
usb_stor_invoke_transport(srb, us);
}
void usb_stor_ufi_command(struct scsi_cmnd *srb, struct us_data *us)
{
/* fix some commands -- this is a form of mode translation
* UFI devices only accept 12 byte long commands
*
* NOTE: This only works because a scsi_cmnd struct field contains
* a unsigned char cmnd[16], so we know we have storage available
*/
/* Pad the ATAPI command with zeros */
for (; srb->cmd_len<12; srb->cmd_len++)
srb->cmnd[srb->cmd_len] = 0;
/* set command length to 12 bytes (this affects the transport layer) */
srb->cmd_len = 12;
/* XXX We should be constantly re-evaluating the need for these */
/* determine the correct data length for these commands */
switch (srb->cmnd[0]) {
/* for INQUIRY, UFI devices only ever return 36 bytes */
case INQUIRY:
srb->cmnd[4] = 36;
break;
/* again, for MODE_SENSE_10, we get the minimum (8) */
case MODE_SENSE_10:
srb->cmnd[7] = 0;
srb->cmnd[8] = 8;
break;
/* for REQUEST_SENSE, UFI devices only ever return 18 bytes */
case REQUEST_SENSE:
srb->cmnd[4] = 18;
break;
} /* end switch on cmnd[0] */
/* send the command to the transport layer */
usb_stor_invoke_transport(srb, us);
}
void usb_stor_transparent_scsi_command(struct scsi_cmnd *srb,
struct us_data *us)
{
/* send the command to the transport layer */
usb_stor_invoke_transport(srb, us);
}
EXPORT_SYMBOL_GPL(usb_stor_transparent_scsi_command);
/***********************************************************************
* Scatter-gather transfer buffer access routines
***********************************************************************/
/* Copy a buffer of length buflen to/from the srb's transfer buffer.
* Update the **sgptr and *offset variables so that the next copy will
* pick up from where this one left off.
*/
unsigned int usb_stor_access_xfer_buf(unsigned char *buffer,
unsigned int buflen, struct scsi_cmnd *srb, struct scatterlist **sgptr,
unsigned int *offset, enum xfer_buf_dir dir)
{
unsigned int cnt;
struct scatterlist *sg = *sgptr;
/* We have to go through the list one entry
* at a time. Each s-g entry contains some number of pages, and
* each page has to be kmap()'ed separately. If the page is already
* in kernel-addressable memory then kmap() will return its address.
* If the page is not directly accessible -- such as a user buffer
* located in high memory -- then kmap() will map it to a temporary
* position in the kernel's virtual address space.
*/
if (!sg)
sg = scsi_sglist(srb);
/* This loop handles a single s-g list entry, which may
* include multiple pages. Find the initial page structure
* and the starting offset within the page, and update
* the *offset and **sgptr values for the next loop.
*/
cnt = 0;
while (cnt < buflen && sg) {
struct page *page = sg_page(sg) +
((sg->offset + *offset) >> PAGE_SHIFT);
unsigned int poff = (sg->offset + *offset) & (PAGE_SIZE-1);
unsigned int sglen = sg->length - *offset;
if (sglen > buflen - cnt) {
/* Transfer ends within this s-g entry */
sglen = buflen - cnt;
*offset += sglen;
} else {
/* Transfer continues to next s-g entry */
*offset = 0;
sg = sg_next(sg);
}
/* Transfer the data for all the pages in this
* s-g entry. For each page: call kmap(), do the
* transfer, and call kunmap() immediately after. */
while (sglen > 0) {
unsigned int plen = min(sglen, (unsigned int)
PAGE_SIZE - poff);
unsigned char *ptr = kmap(page);
if (dir == TO_XFER_BUF)
memcpy(ptr + poff, buffer + cnt, plen);
else
memcpy(buffer + cnt, ptr + poff, plen);
kunmap(page);
/* Start at the beginning of the next page */
poff = 0;
++page;
cnt += plen;
sglen -= plen;
}
}
*sgptr = sg;
/* Return the amount actually transferred */
return cnt;
}
EXPORT_SYMBOL_GPL(usb_stor_access_xfer_buf);
/* Store the contents of buffer into srb's transfer buffer and set the
* SCSI residue.
*/
void usb_stor_set_xfer_buf(unsigned char *buffer,
unsigned int buflen, struct scsi_cmnd *srb)
{
unsigned int offset = 0;
struct scatterlist *sg = NULL;
buflen = min(buflen, scsi_bufflen(srb));
buflen = usb_stor_access_xfer_buf(buffer, buflen, srb, &sg, &offset,
TO_XFER_BUF);
if (buflen < scsi_bufflen(srb))
scsi_set_resid(srb, scsi_bufflen(srb) - buflen);
}
EXPORT_SYMBOL_GPL(usb_stor_set_xfer_buf);
| gpl-2.0 |
boa19861105/Butterfly-Kernel | arch/sparc/lib/atomic32.c | 7077 | 2877 | /*
* atomic32.c: 32-bit atomic_t implementation
*
* Copyright (C) 2004 Keith M Wesolowski
* Copyright (C) 2007 Kyle McMartin
*
* Based on asm-parisc/atomic.h Copyright (C) 2000 Philipp Rumpf
*/
#include <linux/atomic.h>
#include <linux/spinlock.h>
#include <linux/module.h>
#ifdef CONFIG_SMP
#define ATOMIC_HASH_SIZE 4
#define ATOMIC_HASH(a) (&__atomic_hash[(((unsigned long)a)>>8) & (ATOMIC_HASH_SIZE-1)])
spinlock_t __atomic_hash[ATOMIC_HASH_SIZE] = {
[0 ... (ATOMIC_HASH_SIZE-1)] = __SPIN_LOCK_UNLOCKED(__atomic_hash)
};
#else /* SMP */
static DEFINE_SPINLOCK(dummy);
#define ATOMIC_HASH_SIZE 1
#define ATOMIC_HASH(a) (&dummy)
#endif /* SMP */
int __atomic_add_return(int i, atomic_t *v)
{
int ret;
unsigned long flags;
spin_lock_irqsave(ATOMIC_HASH(v), flags);
ret = (v->counter += i);
spin_unlock_irqrestore(ATOMIC_HASH(v), flags);
return ret;
}
EXPORT_SYMBOL(__atomic_add_return);
int atomic_cmpxchg(atomic_t *v, int old, int new)
{
int ret;
unsigned long flags;
spin_lock_irqsave(ATOMIC_HASH(v), flags);
ret = v->counter;
if (likely(ret == old))
v->counter = new;
spin_unlock_irqrestore(ATOMIC_HASH(v), flags);
return ret;
}
EXPORT_SYMBOL(atomic_cmpxchg);
int __atomic_add_unless(atomic_t *v, int a, int u)
{
int ret;
unsigned long flags;
spin_lock_irqsave(ATOMIC_HASH(v), flags);
ret = v->counter;
if (ret != u)
v->counter += a;
spin_unlock_irqrestore(ATOMIC_HASH(v), flags);
return ret;
}
EXPORT_SYMBOL(__atomic_add_unless);
/* Atomic operations are already serializing */
void atomic_set(atomic_t *v, int i)
{
unsigned long flags;
spin_lock_irqsave(ATOMIC_HASH(v), flags);
v->counter = i;
spin_unlock_irqrestore(ATOMIC_HASH(v), flags);
}
EXPORT_SYMBOL(atomic_set);
unsigned long ___set_bit(unsigned long *addr, unsigned long mask)
{
unsigned long old, flags;
spin_lock_irqsave(ATOMIC_HASH(addr), flags);
old = *addr;
*addr = old | mask;
spin_unlock_irqrestore(ATOMIC_HASH(addr), flags);
return old & mask;
}
EXPORT_SYMBOL(___set_bit);
unsigned long ___clear_bit(unsigned long *addr, unsigned long mask)
{
unsigned long old, flags;
spin_lock_irqsave(ATOMIC_HASH(addr), flags);
old = *addr;
*addr = old & ~mask;
spin_unlock_irqrestore(ATOMIC_HASH(addr), flags);
return old & mask;
}
EXPORT_SYMBOL(___clear_bit);
unsigned long ___change_bit(unsigned long *addr, unsigned long mask)
{
unsigned long old, flags;
spin_lock_irqsave(ATOMIC_HASH(addr), flags);
old = *addr;
*addr = old ^ mask;
spin_unlock_irqrestore(ATOMIC_HASH(addr), flags);
return old & mask;
}
EXPORT_SYMBOL(___change_bit);
unsigned long __cmpxchg_u32(volatile u32 *ptr, u32 old, u32 new)
{
unsigned long flags;
u32 prev;
spin_lock_irqsave(ATOMIC_HASH(ptr), flags);
if ((prev = *ptr) == old)
*ptr = new;
spin_unlock_irqrestore(ATOMIC_HASH(ptr), flags);
return (unsigned long)prev;
}
EXPORT_SYMBOL(__cmpxchg_u32);
| gpl-2.0 |
kernel-hut/android_kernel_xiaomi_dior | drivers/scsi/ultrastor.c | 9381 | 36980 | /*
* ultrastor.c Copyright (C) 1992 David B. Gentzel
* Low-level SCSI driver for UltraStor 14F, 24F, and 34F
* by David B. Gentzel, Whitfield Software Services, Carnegie, PA
* (gentzel@nova.enet.dec.com)
* scatter/gather added by Scott Taylor (n217cg@tamuts.tamu.edu)
* 24F and multiple command support by John F. Carr (jfc@athena.mit.edu)
* John's work modified by Caleb Epstein (cae@jpmorgan.com) and
* Eric Youngdale (ericy@cais.com).
* Thanks to UltraStor for providing the necessary documentation
*
* This is an old driver, for the 14F and 34F you should be using the
* u14-34f driver instead.
*/
/*
* TODO:
* 1. Find out why scatter/gather is limited to 16 requests per command.
* This is fixed, at least on the 24F, as of version 1.12 - CAE.
* 2. Look at command linking (mscp.command_link and
* mscp.command_link_id). (Does not work with many disks,
* and no performance increase. ERY).
* 3. Allow multiple adapters.
*/
/*
* NOTES:
* The UltraStor 14F, 24F, and 34F are a family of intelligent, high
* performance SCSI-2 host adapters. They all support command queueing
* and scatter/gather I/O. Some of them can also emulate the standard
* WD1003 interface for use with OS's which don't support SCSI. Here
* is the scoop on the various models:
* 14F - ISA first-party DMA HA with floppy support and WD1003 emulation.
* 14N - ISA HA with floppy support. I think that this is a non-DMA
* HA. Nothing further known.
* 24F - EISA Bus Master HA with floppy support and WD1003 emulation.
* 34F - VL-Bus Bus Master HA with floppy support (no WD1003 emulation).
*
* The 14F, 24F, and 34F are supported by this driver.
*
* Places flagged with a triple question-mark are things which are either
* unfinished, questionable, or wrong.
*/
/* Changes from version 1.11 alpha to 1.12
*
* Increased the size of the scatter-gather list to 33 entries for
* the 24F adapter (it was 16). I don't have the specs for the 14F
* or the 34F, so they may support larger s-g lists as well.
*
* Caleb Epstein <cae@jpmorgan.com>
*/
/* Changes from version 1.9 to 1.11
*
* Patches to bring this driver up to speed with the default kernel
* driver which supports only the 14F and 34F adapters. This version
* should compile cleanly into 0.99.13, 0.99.12 and probably 0.99.11.
*
* Fixes from Eric Youngdale to fix a few possible race conditions and
* several problems with bit testing operations (insufficient
* parentheses).
*
* Removed the ultrastor_abort() and ultrastor_reset() functions
* (enclosed them in #if 0 / #endif). These functions, at least on
* the 24F, cause the SCSI bus to do odd things and generally lead to
* kernel panics and machine hangs. This is like the Adaptec code.
*
* Use check/snarf_region for 14f, 34f to avoid I/O space address conflicts.
*/
/* Changes from version 1.8 to version 1.9
*
* 0.99.11 patches (cae@jpmorgan.com) */
/* Changes from version 1.7 to version 1.8
*
* Better error reporting.
*/
/* Changes from version 1.6 to version 1.7
*
* Removed CSIR command code.
*
* Better race condition avoidance (xchgb function added).
*
* Set ICM and OGM status to zero at probe (24F)
*
* reset sends soft reset to UltraStor adapter
*
* reset adapter if adapter interrupts with an invalid MSCP address
*
* handle aborted command interrupt (24F)
*
*/
/* Changes from version 1.5 to version 1.6:
*
* Read MSCP address from ICM _before_ clearing the interrupt flag.
* This fixes a race condition.
*/
/* Changes from version 1.4 to version 1.5:
*
* Abort now calls done when multiple commands are enabled.
*
* Clear busy when aborted command finishes, not when abort is called.
*
* More debugging messages for aborts.
*/
/* Changes from version 1.3 to version 1.4:
*
* Enable automatic request of sense data on error (requires newer version
* of scsi.c to be useful).
*
* Fix PORT_OVERRIDE for 14F.
*
* Fix abort and reset to work properly (config.aborted wasn't cleared
* after it was tested, so after a command abort no further commands would
* work).
*
* Boot time test to enable SCSI bus reset (defaults to not allowing reset).
*
* Fix test for OGM busy -- the busy bit is in different places on the 24F.
*
* Release ICM slot by clearing first byte on 24F.
*/
#include <linux/module.h>
#include <linux/blkdev.h>
#include <linux/interrupt.h>
#include <linux/stddef.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/ioport.h>
#include <linux/proc_fs.h>
#include <linux/spinlock.h>
#include <linux/stat.h>
#include <linux/bitops.h>
#include <linux/delay.h>
#include <asm/io.h>
#include <asm/dma.h>
#define ULTRASTOR_PRIVATE /* Get the private stuff from ultrastor.h */
#include "scsi.h"
#include <scsi/scsi_host.h>
#include "ultrastor.h"
#define FALSE 0
#define TRUE 1
#ifndef ULTRASTOR_DEBUG
#define ULTRASTOR_DEBUG (UD_ABORT|UD_CSIR|UD_RESET)
#endif
#define VERSION "1.12"
#define PACKED __attribute__((packed))
#define ALIGNED(x) __attribute__((aligned(x)))
/* The 14F uses an array of 4-byte ints for its scatter/gather list.
The data can be unaligned, but need not be. It's easier to give
the list normal alignment since it doesn't need to fit into a
packed structure. */
typedef struct {
u32 address;
u32 num_bytes;
} ultrastor_sg_list;
/* MailBox SCSI Command Packet. Basic command structure for communicating
with controller. */
struct mscp {
unsigned char opcode: 3; /* type of command */
unsigned char xdir: 2; /* data transfer direction */
unsigned char dcn: 1; /* disable disconnect */
unsigned char ca: 1; /* use cache (if available) */
unsigned char sg: 1; /* scatter/gather operation */
unsigned char target_id: 3; /* target SCSI id */
unsigned char ch_no: 2; /* SCSI channel (always 0 for 14f) */
unsigned char lun: 3; /* logical unit number */
unsigned int transfer_data PACKED; /* transfer data pointer */
unsigned int transfer_data_length PACKED; /* length in bytes */
unsigned int command_link PACKED; /* for linking command chains */
unsigned char scsi_command_link_id; /* identifies command in chain */
unsigned char number_of_sg_list; /* (if sg is set) 8 bytes per list */
unsigned char length_of_sense_byte;
unsigned char length_of_scsi_cdbs; /* 6, 10, or 12 */
unsigned char scsi_cdbs[12]; /* SCSI commands */
unsigned char adapter_status; /* non-zero indicates HA error */
unsigned char target_status; /* non-zero indicates target error */
u32 sense_data PACKED;
/* The following fields are for software only. They are included in
the MSCP structure because they are associated with SCSI requests. */
void (*done) (struct scsi_cmnd *);
struct scsi_cmnd *SCint;
ultrastor_sg_list sglist[ULTRASTOR_24F_MAX_SG]; /* use larger size for 24F */
};
/* Port addresses (relative to the base address) */
#define U14F_PRODUCT_ID(port) ((port) + 0x4)
#define CONFIG(port) ((port) + 0x6)
/* Port addresses relative to the doorbell base address. */
#define LCL_DOORBELL_MASK(port) ((port) + 0x0)
#define LCL_DOORBELL_INTR(port) ((port) + 0x1)
#define SYS_DOORBELL_MASK(port) ((port) + 0x2)
#define SYS_DOORBELL_INTR(port) ((port) + 0x3)
/* Used to store configuration info read from config i/o registers. Most of
this is not used yet, but might as well save it.
This structure also holds port addresses that are not at the same offset
on the 14F and 24F.
This structure holds all data that must be duplicated to support multiple
adapters. */
static struct ultrastor_config
{
unsigned short port_address; /* base address of card */
unsigned short doorbell_address; /* base address of doorbell CSRs */
unsigned short ogm_address; /* base address of OGM */
unsigned short icm_address; /* base address of ICM */
const void *bios_segment;
unsigned char interrupt: 4;
unsigned char dma_channel: 3;
unsigned char bios_drive_number: 1;
unsigned char heads;
unsigned char sectors;
unsigned char ha_scsi_id: 3;
unsigned char subversion: 4;
unsigned char revision;
/* The slot number is used to distinguish the 24F (slot != 0) from
the 14F and 34F (slot == 0). */
unsigned char slot;
#ifdef PRINT_U24F_VERSION
volatile int csir_done;
#endif
/* A pool of MSCP structures for this adapter, and a bitmask of
busy structures. (If ULTRASTOR_14F_MAX_CMDS == 1, a 1 byte
busy flag is used instead.) */
#if ULTRASTOR_MAX_CMDS == 1
unsigned char mscp_busy;
#else
unsigned long mscp_free;
#endif
volatile unsigned char aborted[ULTRASTOR_MAX_CMDS];
struct mscp mscp[ULTRASTOR_MAX_CMDS];
} config = {0};
/* Set this to 1 to reset the SCSI bus on error. */
static int ultrastor_bus_reset;
/* Allowed BIOS base addresses (NULL indicates reserved) */
static const void *const bios_segment_table[8] = {
NULL, (void *)0xC4000, (void *)0xC8000, (void *)0xCC000,
(void *)0xD0000, (void *)0xD4000, (void *)0xD8000, (void *)0xDC000,
};
/* Allowed IRQs for 14f */
static const unsigned char interrupt_table_14f[4] = { 15, 14, 11, 10 };
/* Allowed DMA channels for 14f (0 indicates reserved) */
static const unsigned char dma_channel_table_14f[4] = { 5, 6, 7, 0 };
/* Head/sector mappings allowed by 14f */
static const struct {
unsigned char heads;
unsigned char sectors;
} mapping_table[4] = { { 16, 63 }, { 64, 32 }, { 64, 63 }, { 64, 32 } };
#ifndef PORT_OVERRIDE
/* ??? A probe of address 0x310 screws up NE2000 cards */
static const unsigned short ultrastor_ports_14f[] = {
0x330, 0x340, /*0x310,*/ 0x230, 0x240, 0x210, 0x130, 0x140,
};
#endif
static void ultrastor_interrupt(void *);
static irqreturn_t do_ultrastor_interrupt(int, void *);
static inline void build_sg_list(struct mscp *, struct scsi_cmnd *SCpnt);
/* Always called with host lock held */
static inline int find_and_clear_bit_16(unsigned long *field)
{
int rv;
if (*field == 0)
panic("No free mscp");
asm volatile (
"xorl %0,%0\n\t"
"0: bsfw %1,%w0\n\t"
"btr %0,%1\n\t"
"jnc 0b"
: "=&r" (rv), "+m" (*field) :);
return rv;
}
/* This has been re-implemented with the help of Richard Earnshaw,
<rwe@pegasus.esprit.ec.org> and works with gcc-2.5.8 and gcc-2.6.0.
The instability noted by jfc below appears to be a bug in
gcc-2.5.x when compiling w/o optimization. --Caleb
This asm is fragile: it doesn't work without the casts and it may
not work without optimization. Maybe I should add a swap builtin
to gcc. --jfc */
static inline unsigned char xchgb(unsigned char reg,
volatile unsigned char *mem)
{
__asm__ ("xchgb %0,%1" : "=q" (reg), "=m" (*mem) : "0" (reg));
return reg;
}
#if ULTRASTOR_DEBUG & (UD_COMMAND | UD_ABORT)
/* Always called with the host lock held */
static void log_ultrastor_abort(struct ultrastor_config *config,
int command)
{
static char fmt[80] = "abort %d (%x); MSCP free pool: %x;";
int i;
for (i = 0; i < ULTRASTOR_MAX_CMDS; i++)
{
fmt[20 + i*2] = ' ';
if (! (config->mscp_free & (1 << i)))
fmt[21 + i*2] = '0' + config->mscp[i].target_id;
else
fmt[21 + i*2] = '-';
}
fmt[20 + ULTRASTOR_MAX_CMDS * 2] = '\n';
fmt[21 + ULTRASTOR_MAX_CMDS * 2] = 0;
printk(fmt, command, &config->mscp[command], config->mscp_free);
}
#endif
static int ultrastor_14f_detect(struct scsi_host_template * tpnt)
{
size_t i;
unsigned char in_byte, version_byte = 0;
struct config_1 {
unsigned char bios_segment: 3;
unsigned char removable_disks_as_fixed: 1;
unsigned char interrupt: 2;
unsigned char dma_channel: 2;
} config_1;
struct config_2 {
unsigned char ha_scsi_id: 3;
unsigned char mapping_mode: 2;
unsigned char bios_drive_number: 1;
unsigned char tfr_port: 2;
} config_2;
#if (ULTRASTOR_DEBUG & UD_DETECT)
printk("US14F: detect: called\n");
#endif
/* If a 24F has already been configured, don't look for a 14F. */
if (config.bios_segment)
return FALSE;
#ifdef PORT_OVERRIDE
if(!request_region(PORT_OVERRIDE, 0xc, "ultrastor")) {
printk("Ultrastor I/O space already in use\n");
return FALSE;
};
config.port_address = PORT_OVERRIDE;
#else
for (i = 0; i < ARRAY_SIZE(ultrastor_ports_14f); i++) {
if(!request_region(ultrastor_ports_14f[i], 0x0c, "ultrastor")) continue;
config.port_address = ultrastor_ports_14f[i];
#endif
#if (ULTRASTOR_DEBUG & UD_DETECT)
printk("US14F: detect: testing port address %03X\n", config.port_address);
#endif
in_byte = inb(U14F_PRODUCT_ID(config.port_address));
if (in_byte != US14F_PRODUCT_ID_0) {
#if (ULTRASTOR_DEBUG & UD_DETECT)
# ifdef PORT_OVERRIDE
printk("US14F: detect: wrong product ID 0 - %02X\n", in_byte);
# else
printk("US14F: detect: no adapter at port %03X\n", config.port_address);
# endif
#endif
#ifdef PORT_OVERRIDE
goto out_release_port;
#else
release_region(config.port_address, 0x0c);
continue;
#endif
}
in_byte = inb(U14F_PRODUCT_ID(config.port_address) + 1);
/* Only upper nibble is significant for Product ID 1 */
if ((in_byte & 0xF0) != US14F_PRODUCT_ID_1) {
#if (ULTRASTOR_DEBUG & UD_DETECT)
# ifdef PORT_OVERRIDE
printk("US14F: detect: wrong product ID 1 - %02X\n", in_byte);
# else
printk("US14F: detect: no adapter at port %03X\n", config.port_address);
# endif
#endif
#ifdef PORT_OVERRIDE
goto out_release_port;
#else
release_region(config.port_address, 0x0c);
continue;
#endif
}
version_byte = in_byte;
#ifndef PORT_OVERRIDE
break;
}
if (i == ARRAY_SIZE(ultrastor_ports_14f)) {
# if (ULTRASTOR_DEBUG & UD_DETECT)
printk("US14F: detect: no port address found!\n");
# endif
/* all ports probed already released - we can just go straight out */
return FALSE;
}
#endif
#if (ULTRASTOR_DEBUG & UD_DETECT)
printk("US14F: detect: adapter found at port address %03X\n",
config.port_address);
#endif
/* Set local doorbell mask to disallow bus reset unless
ultrastor_bus_reset is true. */
outb(ultrastor_bus_reset ? 0xc2 : 0x82, LCL_DOORBELL_MASK(config.port_address));
/* All above tests passed, must be the right thing. Get some useful
info. */
/* Register the I/O space that we use */
*(char *)&config_1 = inb(CONFIG(config.port_address + 0));
*(char *)&config_2 = inb(CONFIG(config.port_address + 1));
config.bios_segment = bios_segment_table[config_1.bios_segment];
config.doorbell_address = config.port_address;
config.ogm_address = config.port_address + 0x8;
config.icm_address = config.port_address + 0xC;
config.interrupt = interrupt_table_14f[config_1.interrupt];
config.ha_scsi_id = config_2.ha_scsi_id;
config.heads = mapping_table[config_2.mapping_mode].heads;
config.sectors = mapping_table[config_2.mapping_mode].sectors;
config.bios_drive_number = config_2.bios_drive_number;
config.subversion = (version_byte & 0x0F);
if (config.subversion == U34F)
config.dma_channel = 0;
else
config.dma_channel = dma_channel_table_14f[config_1.dma_channel];
if (!config.bios_segment) {
#if (ULTRASTOR_DEBUG & UD_DETECT)
printk("US14F: detect: not detected.\n");
#endif
goto out_release_port;
}
/* Final consistency check, verify previous info. */
if (config.subversion != U34F)
if (!config.dma_channel || !(config_2.tfr_port & 0x2)) {
#if (ULTRASTOR_DEBUG & UD_DETECT)
printk("US14F: detect: consistency check failed\n");
#endif
goto out_release_port;
}
/* If we were TRULY paranoid, we could issue a host adapter inquiry
command here and verify the data returned. But frankly, I'm
exhausted! */
/* Finally! Now I'm satisfied... */
#if (ULTRASTOR_DEBUG & UD_DETECT)
printk("US14F: detect: detect succeeded\n"
" Port address: %03X\n"
" BIOS segment: %05X\n"
" Interrupt: %u\n"
" DMA channel: %u\n"
" H/A SCSI ID: %u\n"
" Subversion: %u\n",
config.port_address, config.bios_segment, config.interrupt,
config.dma_channel, config.ha_scsi_id, config.subversion);
#endif
tpnt->this_id = config.ha_scsi_id;
tpnt->unchecked_isa_dma = (config.subversion != U34F);
#if ULTRASTOR_MAX_CMDS > 1
config.mscp_free = ~0;
#endif
/*
* Brrr, &config.mscp[0].SCint->host) it is something magical....
* XXX and FIXME
*/
if (request_irq(config.interrupt, do_ultrastor_interrupt, 0, "Ultrastor", &config.mscp[0].SCint->device->host)) {
printk("Unable to allocate IRQ%u for UltraStor controller.\n",
config.interrupt);
goto out_release_port;
}
if (config.dma_channel && request_dma(config.dma_channel,"Ultrastor")) {
printk("Unable to allocate DMA channel %u for UltraStor controller.\n",
config.dma_channel);
free_irq(config.interrupt, NULL);
goto out_release_port;
}
tpnt->sg_tablesize = ULTRASTOR_14F_MAX_SG;
printk("UltraStor driver version" VERSION ". Using %d SG lists.\n",
ULTRASTOR_14F_MAX_SG);
return TRUE;
out_release_port:
release_region(config.port_address, 0x0c);
return FALSE;
}
static int ultrastor_24f_detect(struct scsi_host_template * tpnt)
{
int i;
struct Scsi_Host * shpnt = NULL;
#if (ULTRASTOR_DEBUG & UD_DETECT)
printk("US24F: detect");
#endif
/* probe each EISA slot at slot address C80 */
for (i = 1; i < 15; i++)
{
unsigned char config_1, config_2;
unsigned short addr = (i << 12) | ULTRASTOR_24F_PORT;
if (inb(addr) != US24F_PRODUCT_ID_0 &&
inb(addr+1) != US24F_PRODUCT_ID_1 &&
inb(addr+2) != US24F_PRODUCT_ID_2)
continue;
config.revision = inb(addr+3);
config.slot = i;
if (! (inb(addr+4) & 1))
{
#if (ULTRASTOR_DEBUG & UD_DETECT)
printk("U24F: found disabled card in slot %u\n", i);
#endif
continue;
}
#if (ULTRASTOR_DEBUG & UD_DETECT)
printk("U24F: found card in slot %u\n", i);
#endif
config_1 = inb(addr + 5);
config.bios_segment = bios_segment_table[config_1 & 7];
switch(config_1 >> 4)
{
case 1:
config.interrupt = 15;
break;
case 2:
config.interrupt = 14;
break;
case 4:
config.interrupt = 11;
break;
case 8:
config.interrupt = 10;
break;
default:
printk("U24F: invalid IRQ\n");
return FALSE;
}
/* BIOS addr set */
/* base port set */
config.port_address = addr;
config.doorbell_address = addr + 12;
config.ogm_address = addr + 0x17;
config.icm_address = addr + 0x1C;
config_2 = inb(addr + 7);
config.ha_scsi_id = config_2 & 7;
config.heads = mapping_table[(config_2 >> 3) & 3].heads;
config.sectors = mapping_table[(config_2 >> 3) & 3].sectors;
#if (ULTRASTOR_DEBUG & UD_DETECT)
printk("US24F: detect: detect succeeded\n"
" Port address: %03X\n"
" BIOS segment: %05X\n"
" Interrupt: %u\n"
" H/A SCSI ID: %u\n",
config.port_address, config.bios_segment,
config.interrupt, config.ha_scsi_id);
#endif
tpnt->this_id = config.ha_scsi_id;
tpnt->unchecked_isa_dma = 0;
tpnt->sg_tablesize = ULTRASTOR_24F_MAX_SG;
shpnt = scsi_register(tpnt, 0);
if (!shpnt) {
printk(KERN_WARNING "(ultrastor:) Could not register scsi device. Aborting registration.\n");
free_irq(config.interrupt, do_ultrastor_interrupt);
return FALSE;
}
if (request_irq(config.interrupt, do_ultrastor_interrupt, 0, "Ultrastor", shpnt))
{
printk("Unable to allocate IRQ%u for UltraStor controller.\n",
config.interrupt);
return FALSE;
}
shpnt->irq = config.interrupt;
shpnt->dma_channel = config.dma_channel;
shpnt->io_port = config.port_address;
#if ULTRASTOR_MAX_CMDS > 1
config.mscp_free = ~0;
#endif
/* Mark ICM and OGM free */
outb(0, addr + 0x16);
outb(0, addr + 0x1B);
/* Set local doorbell mask to disallow bus reset unless
ultrastor_bus_reset is true. */
outb(ultrastor_bus_reset ? 0xc2 : 0x82, LCL_DOORBELL_MASK(addr+12));
outb(0x02, SYS_DOORBELL_MASK(addr+12));
printk("UltraStor driver version " VERSION ". Using %d SG lists.\n",
tpnt->sg_tablesize);
return TRUE;
}
return FALSE;
}
static int ultrastor_detect(struct scsi_host_template * tpnt)
{
tpnt->proc_name = "ultrastor";
return ultrastor_14f_detect(tpnt) || ultrastor_24f_detect(tpnt);
}
static int ultrastor_release(struct Scsi_Host *shost)
{
if (shost->irq)
free_irq(shost->irq, NULL);
if (shost->dma_channel != 0xff)
free_dma(shost->dma_channel);
if (shost->io_port && shost->n_io_port)
release_region(shost->io_port, shost->n_io_port);
scsi_unregister(shost);
return 0;
}
static const char *ultrastor_info(struct Scsi_Host * shpnt)
{
static char buf[64];
if (config.slot)
sprintf(buf, "UltraStor 24F SCSI @ Slot %u IRQ%u",
config.slot, config.interrupt);
else if (config.subversion)
sprintf(buf, "UltraStor 34F SCSI @ Port %03X BIOS %05X IRQ%u",
config.port_address, (int)config.bios_segment,
config.interrupt);
else
sprintf(buf, "UltraStor 14F SCSI @ Port %03X BIOS %05X IRQ%u DMA%u",
config.port_address, (int)config.bios_segment,
config.interrupt, config.dma_channel);
return buf;
}
static inline void build_sg_list(struct mscp *mscp, struct scsi_cmnd *SCpnt)
{
struct scatterlist *sg;
long transfer_length = 0;
int i, max;
max = scsi_sg_count(SCpnt);
scsi_for_each_sg(SCpnt, sg, max, i) {
mscp->sglist[i].address = isa_page_to_bus(sg_page(sg)) + sg->offset;
mscp->sglist[i].num_bytes = sg->length;
transfer_length += sg->length;
}
mscp->number_of_sg_list = max;
mscp->transfer_data = isa_virt_to_bus(mscp->sglist);
/* ??? May not be necessary. Docs are unclear as to whether transfer
length field is ignored or whether it should be set to the total
number of bytes of the transfer. */
mscp->transfer_data_length = transfer_length;
}
static int ultrastor_queuecommand_lck(struct scsi_cmnd *SCpnt,
void (*done) (struct scsi_cmnd *))
{
struct mscp *my_mscp;
#if ULTRASTOR_MAX_CMDS > 1
int mscp_index;
#endif
unsigned int status;
/* Next test is for debugging; "can't happen" */
if ((config.mscp_free & ((1U << ULTRASTOR_MAX_CMDS) - 1)) == 0)
panic("ultrastor_queuecommand: no free MSCP\n");
mscp_index = find_and_clear_bit_16(&config.mscp_free);
/* Has the command been aborted? */
if (xchgb(0xff, &config.aborted[mscp_index]) != 0)
{
status = DID_ABORT << 16;
goto aborted;
}
my_mscp = &config.mscp[mscp_index];
*(unsigned char *)my_mscp = OP_SCSI | (DTD_SCSI << 3);
/* Tape drives don't work properly if the cache is used. The SCSI
READ command for a tape doesn't have a block offset, and the adapter
incorrectly assumes that all reads from the tape read the same
blocks. Results will depend on read buffer size and other disk
activity.
??? Which other device types should never use the cache? */
my_mscp->ca = SCpnt->device->type != TYPE_TAPE;
my_mscp->target_id = SCpnt->device->id;
my_mscp->ch_no = 0;
my_mscp->lun = SCpnt->device->lun;
if (scsi_sg_count(SCpnt)) {
/* Set scatter/gather flag in SCSI command packet */
my_mscp->sg = TRUE;
build_sg_list(my_mscp, SCpnt);
} else {
/* Unset scatter/gather flag in SCSI command packet */
my_mscp->sg = FALSE;
my_mscp->transfer_data = isa_virt_to_bus(scsi_sglist(SCpnt));
my_mscp->transfer_data_length = scsi_bufflen(SCpnt);
}
my_mscp->command_link = 0; /*???*/
my_mscp->scsi_command_link_id = 0; /*???*/
my_mscp->length_of_sense_byte = SCSI_SENSE_BUFFERSIZE;
my_mscp->length_of_scsi_cdbs = SCpnt->cmd_len;
memcpy(my_mscp->scsi_cdbs, SCpnt->cmnd, my_mscp->length_of_scsi_cdbs);
my_mscp->adapter_status = 0;
my_mscp->target_status = 0;
my_mscp->sense_data = isa_virt_to_bus(&SCpnt->sense_buffer);
my_mscp->done = done;
my_mscp->SCint = SCpnt;
SCpnt->host_scribble = (unsigned char *)my_mscp;
/* Find free OGM slot. On 24F, look for OGM status byte == 0.
On 14F and 34F, wait for local interrupt pending flag to clear.
FIXME: now we are using new_eh we should punt here and let the
midlayer sort it out */
retry:
if (config.slot)
while (inb(config.ogm_address - 1) != 0 && config.aborted[mscp_index] == 0xff)
barrier();
/* else??? */
while ((inb(LCL_DOORBELL_INTR(config.doorbell_address)) & (config.slot ? 2 : 1)) && config.aborted[mscp_index] == 0xff)
barrier();
/* To avoid race conditions, keep the code to write to the adapter
atomic. This simplifies the abort code. Right now the
scsi mid layer has the host_lock already held
*/
if (inb(LCL_DOORBELL_INTR(config.doorbell_address)) & (config.slot ? 2 : 1))
goto retry;
status = xchgb(0, &config.aborted[mscp_index]);
if (status != 0xff) {
#if ULTRASTOR_DEBUG & (UD_COMMAND | UD_ABORT)
printk("USx4F: queuecommand: aborted\n");
#if ULTRASTOR_MAX_CMDS > 1
log_ultrastor_abort(&config, mscp_index);
#endif
#endif
status <<= 16;
aborted:
set_bit(mscp_index, &config.mscp_free);
/* If the driver queues commands, call the done proc here. Otherwise
return an error. */
#if ULTRASTOR_MAX_CMDS > 1
SCpnt->result = status;
done(SCpnt);
return 0;
#else
return status;
#endif
}
/* Store pointer in OGM address bytes */
outl(isa_virt_to_bus(my_mscp), config.ogm_address);
/* Issue OGM interrupt */
if (config.slot) {
/* Write OGM command register on 24F */
outb(1, config.ogm_address - 1);
outb(0x2, LCL_DOORBELL_INTR(config.doorbell_address));
} else {
outb(0x1, LCL_DOORBELL_INTR(config.doorbell_address));
}
#if (ULTRASTOR_DEBUG & UD_COMMAND)
printk("USx4F: queuecommand: returning\n");
#endif
return 0;
}
static DEF_SCSI_QCMD(ultrastor_queuecommand)
/* This code must deal with 2 cases:
1. The command has not been written to the OGM. In this case, set
the abort flag and return.
2. The command has been written to the OGM and is stuck somewhere in
the adapter.
2a. On a 24F, ask the adapter to abort the command. It will interrupt
when it does.
2b. Call the command's done procedure.
*/
static int ultrastor_abort(struct scsi_cmnd *SCpnt)
{
#if ULTRASTOR_DEBUG & UD_ABORT
char out[108];
unsigned char icm_status = 0, ogm_status = 0;
unsigned int icm_addr = 0, ogm_addr = 0;
#endif
unsigned int mscp_index;
unsigned char old_aborted;
unsigned long flags;
void (*done)(struct scsi_cmnd *);
struct Scsi_Host *host = SCpnt->device->host;
if(config.slot)
return FAILED; /* Do not attempt an abort for the 24f */
/* Simple consistency checking */
if(!SCpnt->host_scribble)
return FAILED;
mscp_index = ((struct mscp *)SCpnt->host_scribble) - config.mscp;
if (mscp_index >= ULTRASTOR_MAX_CMDS)
panic("Ux4F aborting invalid MSCP");
#if ULTRASTOR_DEBUG & UD_ABORT
if (config.slot)
{
int port0 = (config.slot << 12) | 0xc80;
int i;
unsigned long flags;
spin_lock_irqsave(host->host_lock, flags);
strcpy(out, "OGM %d:%x ICM %d:%x ports: ");
for (i = 0; i < 16; i++)
{
unsigned char p = inb(port0 + i);
out[28 + i * 3] = "0123456789abcdef"[p >> 4];
out[29 + i * 3] = "0123456789abcdef"[p & 15];
out[30 + i * 3] = ' ';
}
out[28 + i * 3] = '\n';
out[29 + i * 3] = 0;
ogm_status = inb(port0 + 22);
ogm_addr = (unsigned int)isa_bus_to_virt(inl(port0 + 23));
icm_status = inb(port0 + 27);
icm_addr = (unsigned int)isa_bus_to_virt(inl(port0 + 28));
spin_unlock_irqrestore(host->host_lock, flags);
}
/* First check to see if an interrupt is pending. I suspect the SiS
chipset loses interrupts. (I also suspect is mangles data, but
one bug at a time... */
if (config.slot ? inb(config.icm_address - 1) == 2 :
(inb(SYS_DOORBELL_INTR(config.doorbell_address)) & 1))
{
printk("Ux4F: abort while completed command pending\n");
spin_lock_irqsave(host->host_lock, flags);
/* FIXME: Ewww... need to think about passing host around properly */
ultrastor_interrupt(NULL);
spin_unlock_irqrestore(host->host_lock, flags);
return SUCCESS;
}
#endif
old_aborted = xchgb(DID_ABORT, &config.aborted[mscp_index]);
/* aborted == 0xff is the signal that queuecommand has not yet sent
the command. It will notice the new abort flag and fail. */
if (old_aborted == 0xff)
return SUCCESS;
/* On 24F, send an abort MSCP request. The adapter will interrupt
and the interrupt handler will call done. */
if (config.slot && inb(config.ogm_address - 1) == 0)
{
unsigned long flags;
spin_lock_irqsave(host->host_lock, flags);
outl(isa_virt_to_bus(&config.mscp[mscp_index]), config.ogm_address);
udelay(8);
outb(0x80, config.ogm_address - 1);
outb(0x2, LCL_DOORBELL_INTR(config.doorbell_address));
#if ULTRASTOR_DEBUG & UD_ABORT
log_ultrastor_abort(&config, mscp_index);
printk(out, ogm_status, ogm_addr, icm_status, icm_addr);
#endif
spin_unlock_irqrestore(host->host_lock, flags);
/* FIXME: add a wait for the abort to complete */
return SUCCESS;
}
#if ULTRASTOR_DEBUG & UD_ABORT
log_ultrastor_abort(&config, mscp_index);
#endif
/* Can't request a graceful abort. Either this is not a 24F or
the OGM is busy. Don't free the command -- the adapter might
still be using it. Setting SCint = 0 causes the interrupt
handler to ignore the command. */
/* FIXME - devices that implement soft resets will still be running
the command after a bus reset. We would probably rather leave
the command in the queue. The upper level code will automatically
leave the command in the active state instead of requeueing it. ERY */
#if ULTRASTOR_DEBUG & UD_ABORT
if (config.mscp[mscp_index].SCint != SCpnt)
printk("abort: command mismatch, %p != %p\n",
config.mscp[mscp_index].SCint, SCpnt);
#endif
if (config.mscp[mscp_index].SCint == NULL)
return FAILED;
if (config.mscp[mscp_index].SCint != SCpnt) panic("Bad abort");
config.mscp[mscp_index].SCint = NULL;
done = config.mscp[mscp_index].done;
config.mscp[mscp_index].done = NULL;
SCpnt->result = DID_ABORT << 16;
/* Take the host lock to guard against scsi layer re-entry */
done(SCpnt);
/* Need to set a timeout here in case command never completes. */
return SUCCESS;
}
static int ultrastor_host_reset(struct scsi_cmnd * SCpnt)
{
unsigned long flags;
int i;
struct Scsi_Host *host = SCpnt->device->host;
#if (ULTRASTOR_DEBUG & UD_RESET)
printk("US14F: reset: called\n");
#endif
if(config.slot)
return FAILED;
spin_lock_irqsave(host->host_lock, flags);
/* Reset the adapter and SCSI bus. The SCSI bus reset can be
inhibited by clearing ultrastor_bus_reset before probe. */
outb(0xc0, LCL_DOORBELL_INTR(config.doorbell_address));
if (config.slot)
{
outb(0, config.ogm_address - 1);
outb(0, config.icm_address - 1);
}
#if ULTRASTOR_MAX_CMDS == 1
if (config.mscp_busy && config.mscp->done && config.mscp->SCint)
{
config.mscp->SCint->result = DID_RESET << 16;
config.mscp->done(config.mscp->SCint);
}
config.mscp->SCint = 0;
#else
for (i = 0; i < ULTRASTOR_MAX_CMDS; i++)
{
if (! (config.mscp_free & (1 << i)) &&
config.mscp[i].done && config.mscp[i].SCint)
{
config.mscp[i].SCint->result = DID_RESET << 16;
config.mscp[i].done(config.mscp[i].SCint);
config.mscp[i].done = NULL;
}
config.mscp[i].SCint = NULL;
}
#endif
/* FIXME - if the device implements soft resets, then the command
will still be running. ERY
Even bigger deal with new_eh!
*/
memset((unsigned char *)config.aborted, 0, sizeof config.aborted);
#if ULTRASTOR_MAX_CMDS == 1
config.mscp_busy = 0;
#else
config.mscp_free = ~0;
#endif
spin_unlock_irqrestore(host->host_lock, flags);
return SUCCESS;
}
int ultrastor_biosparam(struct scsi_device *sdev, struct block_device *bdev,
sector_t capacity, int * dkinfo)
{
int size = capacity;
unsigned int s = config.heads * config.sectors;
dkinfo[0] = config.heads;
dkinfo[1] = config.sectors;
dkinfo[2] = size / s; /* Ignore partial cylinders */
#if 0
if (dkinfo[2] > 1024)
dkinfo[2] = 1024;
#endif
return 0;
}
static void ultrastor_interrupt(void *dev_id)
{
unsigned int status;
#if ULTRASTOR_MAX_CMDS > 1
unsigned int mscp_index;
#endif
struct mscp *mscp;
void (*done) (struct scsi_cmnd *);
struct scsi_cmnd *SCtmp;
#if ULTRASTOR_MAX_CMDS == 1
mscp = &config.mscp[0];
#else
mscp = (struct mscp *)isa_bus_to_virt(inl(config.icm_address));
mscp_index = mscp - config.mscp;
if (mscp_index >= ULTRASTOR_MAX_CMDS) {
printk("Ux4F interrupt: bad MSCP address %x\n", (unsigned int) mscp);
/* A command has been lost. Reset and report an error
for all commands. */
ultrastor_host_reset(dev_id);
return;
}
#endif
/* Clean ICM slot (set ICMINT bit to 0) */
if (config.slot) {
unsigned char icm_status = inb(config.icm_address - 1);
#if ULTRASTOR_DEBUG & (UD_INTERRUPT|UD_ERROR|UD_ABORT)
if (icm_status != 1 && icm_status != 2)
printk("US24F: ICM status %x for MSCP %d (%x)\n", icm_status,
mscp_index, (unsigned int) mscp);
#endif
/* The manual says clear interrupt then write 0 to ICM status.
This seems backwards, but I'll do it anyway. --jfc */
outb(2, SYS_DOORBELL_INTR(config.doorbell_address));
outb(0, config.icm_address - 1);
if (icm_status == 4) {
printk("UltraStor abort command failed\n");
return;
}
if (icm_status == 3) {
void (*done)(struct scsi_cmnd *) = mscp->done;
if (done) {
mscp->done = NULL;
mscp->SCint->result = DID_ABORT << 16;
done(mscp->SCint);
}
return;
}
} else {
outb(1, SYS_DOORBELL_INTR(config.doorbell_address));
}
SCtmp = mscp->SCint;
mscp->SCint = NULL;
if (!SCtmp)
{
#if ULTRASTOR_DEBUG & (UD_ABORT|UD_INTERRUPT)
printk("MSCP %d (%x): no command\n", mscp_index, (unsigned int) mscp);
#endif
#if ULTRASTOR_MAX_CMDS == 1
config.mscp_busy = FALSE;
#else
set_bit(mscp_index, &config.mscp_free);
#endif
config.aborted[mscp_index] = 0;
return;
}
/* Save done locally and zero before calling. This is needed as
once we call done, we may get another command queued before this
interrupt service routine can return. */
done = mscp->done;
mscp->done = NULL;
/* Let the higher levels know that we're done */
switch (mscp->adapter_status)
{
case 0:
status = DID_OK << 16;
break;
case 0x01: /* invalid command */
case 0x02: /* invalid parameters */
case 0x03: /* invalid data list */
default:
status = DID_ERROR << 16;
break;
case 0x84: /* SCSI bus abort */
status = DID_ABORT << 16;
break;
case 0x91:
status = DID_TIME_OUT << 16;
break;
}
SCtmp->result = status | mscp->target_status;
SCtmp->host_scribble = NULL;
/* Free up mscp block for next command */
#if ULTRASTOR_MAX_CMDS == 1
config.mscp_busy = FALSE;
#else
set_bit(mscp_index, &config.mscp_free);
#endif
#if ULTRASTOR_DEBUG & (UD_ABORT|UD_INTERRUPT)
if (config.aborted[mscp_index])
printk("Ux4 interrupt: MSCP %d (%x) aborted = %d\n",
mscp_index, (unsigned int) mscp, config.aborted[mscp_index]);
#endif
config.aborted[mscp_index] = 0;
if (done)
done(SCtmp);
else
printk("US14F: interrupt: unexpected interrupt\n");
if (config.slot ? inb(config.icm_address - 1) :
(inb(SYS_DOORBELL_INTR(config.doorbell_address)) & 1))
#if (ULTRASTOR_DEBUG & UD_MULTI_CMD)
printk("Ux4F: multiple commands completed\n");
#else
;
#endif
#if (ULTRASTOR_DEBUG & UD_INTERRUPT)
printk("USx4F: interrupt: returning\n");
#endif
}
static irqreturn_t do_ultrastor_interrupt(int irq, void *dev_id)
{
unsigned long flags;
struct Scsi_Host *dev = dev_id;
spin_lock_irqsave(dev->host_lock, flags);
ultrastor_interrupt(dev_id);
spin_unlock_irqrestore(dev->host_lock, flags);
return IRQ_HANDLED;
}
MODULE_LICENSE("GPL");
static struct scsi_host_template driver_template = {
.name = "UltraStor 14F/24F/34F",
.detect = ultrastor_detect,
.release = ultrastor_release,
.info = ultrastor_info,
.queuecommand = ultrastor_queuecommand,
.eh_abort_handler = ultrastor_abort,
.eh_host_reset_handler = ultrastor_host_reset,
.bios_param = ultrastor_biosparam,
.can_queue = ULTRASTOR_MAX_CMDS,
.sg_tablesize = ULTRASTOR_14F_MAX_SG,
.cmd_per_lun = ULTRASTOR_MAX_CMDS_PER_LUN,
.unchecked_isa_dma = 1,
.use_clustering = ENABLE_CLUSTERING,
};
#include "scsi_module.c"
| gpl-2.0 |
thanhphat11/Kernel-Stock-A900-SLK | drivers/input/touchscreen/inexio.c | 9893 | 4900 | /*
* iNexio serial touchscreen driver
*
* Copyright (c) 2008 Richard Lemon
* Based on the mtouch driver (c) Vojtech Pavlik and Dan Streetman
*
*/
/*
* 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.
*/
/*
* 2008/06/19 Richard Lemon <richard@codelemon.com>
* Copied mtouch.c and edited for iNexio protocol
*/
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/serio.h>
#include <linux/init.h>
#define DRIVER_DESC "iNexio serial touchscreen driver"
MODULE_AUTHOR("Richard Lemon <richard@codelemon.com>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
/*
* Definitions & global arrays.
*/
#define INEXIO_FORMAT_TOUCH_BIT 0x01
#define INEXIO_FORMAT_LENGTH 5
#define INEXIO_RESPONSE_BEGIN_BYTE 0x80
/* todo: check specs for max length of all responses */
#define INEXIO_MAX_LENGTH 16
#define INEXIO_MIN_XC 0
#define INEXIO_MAX_XC 0x3fff
#define INEXIO_MIN_YC 0
#define INEXIO_MAX_YC 0x3fff
#define INEXIO_GET_XC(data) (((data[1])<<7) | data[2])
#define INEXIO_GET_YC(data) (((data[3])<<7) | data[4])
#define INEXIO_GET_TOUCHED(data) (INEXIO_FORMAT_TOUCH_BIT & data[0])
/*
* Per-touchscreen data.
*/
struct inexio {
struct input_dev *dev;
struct serio *serio;
int idx;
unsigned char data[INEXIO_MAX_LENGTH];
char phys[32];
};
static void inexio_process_data(struct inexio *pinexio)
{
struct input_dev *dev = pinexio->dev;
if (INEXIO_FORMAT_LENGTH == ++pinexio->idx) {
input_report_abs(dev, ABS_X, INEXIO_GET_XC(pinexio->data));
input_report_abs(dev, ABS_Y, INEXIO_GET_YC(pinexio->data));
input_report_key(dev, BTN_TOUCH, INEXIO_GET_TOUCHED(pinexio->data));
input_sync(dev);
pinexio->idx = 0;
}
}
static irqreturn_t inexio_interrupt(struct serio *serio,
unsigned char data, unsigned int flags)
{
struct inexio* pinexio = serio_get_drvdata(serio);
pinexio->data[pinexio->idx] = data;
if (INEXIO_RESPONSE_BEGIN_BYTE&pinexio->data[0])
inexio_process_data(pinexio);
else
printk(KERN_DEBUG "inexio.c: unknown/unsynchronized data from device, byte %x\n",pinexio->data[0]);
return IRQ_HANDLED;
}
/*
* inexio_disconnect() is the opposite of inexio_connect()
*/
static void inexio_disconnect(struct serio *serio)
{
struct inexio* pinexio = serio_get_drvdata(serio);
input_get_device(pinexio->dev);
input_unregister_device(pinexio->dev);
serio_close(serio);
serio_set_drvdata(serio, NULL);
input_put_device(pinexio->dev);
kfree(pinexio);
}
/*
* inexio_connect() is the routine that is called when someone adds a
* new serio device that supports iNexio protocol and registers it as
* an input device. This is usually accomplished using inputattach.
*/
static int inexio_connect(struct serio *serio, struct serio_driver *drv)
{
struct inexio *pinexio;
struct input_dev *input_dev;
int err;
pinexio = kzalloc(sizeof(struct inexio), GFP_KERNEL);
input_dev = input_allocate_device();
if (!pinexio || !input_dev) {
err = -ENOMEM;
goto fail1;
}
pinexio->serio = serio;
pinexio->dev = input_dev;
snprintf(pinexio->phys, sizeof(pinexio->phys), "%s/input0", serio->phys);
input_dev->name = "iNexio Serial TouchScreen";
input_dev->phys = pinexio->phys;
input_dev->id.bustype = BUS_RS232;
input_dev->id.vendor = SERIO_INEXIO;
input_dev->id.product = 0;
input_dev->id.version = 0x0001;
input_dev->dev.parent = &serio->dev;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
input_dev->keybit[BIT_WORD(BTN_TOUCH)] = BIT_MASK(BTN_TOUCH);
input_set_abs_params(pinexio->dev, ABS_X, INEXIO_MIN_XC, INEXIO_MAX_XC, 0, 0);
input_set_abs_params(pinexio->dev, ABS_Y, INEXIO_MIN_YC, INEXIO_MAX_YC, 0, 0);
serio_set_drvdata(serio, pinexio);
err = serio_open(serio, drv);
if (err)
goto fail2;
err = input_register_device(pinexio->dev);
if (err)
goto fail3;
return 0;
fail3: serio_close(serio);
fail2: serio_set_drvdata(serio, NULL);
fail1: input_free_device(input_dev);
kfree(pinexio);
return err;
}
/*
* The serio driver structure.
*/
static struct serio_device_id inexio_serio_ids[] = {
{
.type = SERIO_RS232,
.proto = SERIO_INEXIO,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{ 0 }
};
MODULE_DEVICE_TABLE(serio, inexio_serio_ids);
static struct serio_driver inexio_drv = {
.driver = {
.name = "inexio",
},
.description = DRIVER_DESC,
.id_table = inexio_serio_ids,
.interrupt = inexio_interrupt,
.connect = inexio_connect,
.disconnect = inexio_disconnect,
};
/*
* The functions for inserting/removing us as a module.
*/
static int __init inexio_init(void)
{
return serio_register_driver(&inexio_drv);
}
static void __exit inexio_exit(void)
{
serio_unregister_driver(&inexio_drv);
}
module_init(inexio_init);
module_exit(inexio_exit);
| gpl-2.0 |
LDAP/android_kernel_motorola_msm8226 | drivers/ptp/ptp_sysfs.c | 10405 | 5915 | /*
* PTP 1588 clock support - sysfs interface.
*
* Copyright (C) 2010 OMICRON electronics GmbH
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/capability.h>
#include "ptp_private.h"
static ssize_t clock_name_show(struct device *dev,
struct device_attribute *attr, char *page)
{
struct ptp_clock *ptp = dev_get_drvdata(dev);
return snprintf(page, PAGE_SIZE-1, "%s\n", ptp->info->name);
}
#define PTP_SHOW_INT(name) \
static ssize_t name##_show(struct device *dev, \
struct device_attribute *attr, char *page) \
{ \
struct ptp_clock *ptp = dev_get_drvdata(dev); \
return snprintf(page, PAGE_SIZE-1, "%d\n", ptp->info->name); \
}
PTP_SHOW_INT(max_adj);
PTP_SHOW_INT(n_alarm);
PTP_SHOW_INT(n_ext_ts);
PTP_SHOW_INT(n_per_out);
PTP_SHOW_INT(pps);
#define PTP_RO_ATTR(_var, _name) { \
.attr = { .name = __stringify(_name), .mode = 0444 }, \
.show = _var##_show, \
}
struct device_attribute ptp_dev_attrs[] = {
PTP_RO_ATTR(clock_name, clock_name),
PTP_RO_ATTR(max_adj, max_adjustment),
PTP_RO_ATTR(n_alarm, n_alarms),
PTP_RO_ATTR(n_ext_ts, n_external_timestamps),
PTP_RO_ATTR(n_per_out, n_periodic_outputs),
PTP_RO_ATTR(pps, pps_available),
__ATTR_NULL,
};
static ssize_t extts_enable_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct ptp_clock *ptp = dev_get_drvdata(dev);
struct ptp_clock_info *ops = ptp->info;
struct ptp_clock_request req = { .type = PTP_CLK_REQ_EXTTS };
int cnt, enable;
int err = -EINVAL;
cnt = sscanf(buf, "%u %d", &req.extts.index, &enable);
if (cnt != 2)
goto out;
if (req.extts.index >= ops->n_ext_ts)
goto out;
err = ops->enable(ops, &req, enable ? 1 : 0);
if (err)
goto out;
return count;
out:
return err;
}
static ssize_t extts_fifo_show(struct device *dev,
struct device_attribute *attr, char *page)
{
struct ptp_clock *ptp = dev_get_drvdata(dev);
struct timestamp_event_queue *queue = &ptp->tsevq;
struct ptp_extts_event event;
unsigned long flags;
size_t qcnt;
int cnt = 0;
memset(&event, 0, sizeof(event));
if (mutex_lock_interruptible(&ptp->tsevq_mux))
return -ERESTARTSYS;
spin_lock_irqsave(&queue->lock, flags);
qcnt = queue_cnt(queue);
if (qcnt) {
event = queue->buf[queue->head];
queue->head = (queue->head + 1) % PTP_MAX_TIMESTAMPS;
}
spin_unlock_irqrestore(&queue->lock, flags);
if (!qcnt)
goto out;
cnt = snprintf(page, PAGE_SIZE, "%u %lld %u\n",
event.index, event.t.sec, event.t.nsec);
out:
mutex_unlock(&ptp->tsevq_mux);
return cnt;
}
static ssize_t period_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct ptp_clock *ptp = dev_get_drvdata(dev);
struct ptp_clock_info *ops = ptp->info;
struct ptp_clock_request req = { .type = PTP_CLK_REQ_PEROUT };
int cnt, enable, err = -EINVAL;
cnt = sscanf(buf, "%u %lld %u %lld %u", &req.perout.index,
&req.perout.start.sec, &req.perout.start.nsec,
&req.perout.period.sec, &req.perout.period.nsec);
if (cnt != 5)
goto out;
if (req.perout.index >= ops->n_per_out)
goto out;
enable = req.perout.period.sec || req.perout.period.nsec;
err = ops->enable(ops, &req, enable);
if (err)
goto out;
return count;
out:
return err;
}
static ssize_t pps_enable_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct ptp_clock *ptp = dev_get_drvdata(dev);
struct ptp_clock_info *ops = ptp->info;
struct ptp_clock_request req = { .type = PTP_CLK_REQ_PPS };
int cnt, enable;
int err = -EINVAL;
if (!capable(CAP_SYS_TIME))
return -EPERM;
cnt = sscanf(buf, "%d", &enable);
if (cnt != 1)
goto out;
err = ops->enable(ops, &req, enable ? 1 : 0);
if (err)
goto out;
return count;
out:
return err;
}
static DEVICE_ATTR(extts_enable, 0220, NULL, extts_enable_store);
static DEVICE_ATTR(fifo, 0444, extts_fifo_show, NULL);
static DEVICE_ATTR(period, 0220, NULL, period_store);
static DEVICE_ATTR(pps_enable, 0220, NULL, pps_enable_store);
int ptp_cleanup_sysfs(struct ptp_clock *ptp)
{
struct device *dev = ptp->dev;
struct ptp_clock_info *info = ptp->info;
if (info->n_ext_ts) {
device_remove_file(dev, &dev_attr_extts_enable);
device_remove_file(dev, &dev_attr_fifo);
}
if (info->n_per_out)
device_remove_file(dev, &dev_attr_period);
if (info->pps)
device_remove_file(dev, &dev_attr_pps_enable);
return 0;
}
int ptp_populate_sysfs(struct ptp_clock *ptp)
{
struct device *dev = ptp->dev;
struct ptp_clock_info *info = ptp->info;
int err;
if (info->n_ext_ts) {
err = device_create_file(dev, &dev_attr_extts_enable);
if (err)
goto out1;
err = device_create_file(dev, &dev_attr_fifo);
if (err)
goto out2;
}
if (info->n_per_out) {
err = device_create_file(dev, &dev_attr_period);
if (err)
goto out3;
}
if (info->pps) {
err = device_create_file(dev, &dev_attr_pps_enable);
if (err)
goto out4;
}
return 0;
out4:
if (info->n_per_out)
device_remove_file(dev, &dev_attr_period);
out3:
if (info->n_ext_ts)
device_remove_file(dev, &dev_attr_fifo);
out2:
if (info->n_ext_ts)
device_remove_file(dev, &dev_attr_extts_enable);
out1:
return err;
}
| gpl-2.0 |
misham/etaluma-kernel | arch/h8300/kernel/asm-offsets.c | 11429 | 2334 | /*
* This program is used to generate definitions needed by
* assembly language modules.
*
* We use the technique used in the OSF Mach kernel code:
* generate asm statements containing #defines,
* compile this file to assembler, and then extract the
* #defines from the assembly-language output.
*/
#include <linux/stddef.h>
#include <linux/sched.h>
#include <linux/kernel_stat.h>
#include <linux/ptrace.h>
#include <linux/hardirq.h>
#include <linux/kbuild.h>
#include <asm/bootinfo.h>
#include <asm/irq.h>
#include <asm/ptrace.h>
int main(void)
{
/* offsets into the task struct */
DEFINE(TASK_STATE, offsetof(struct task_struct, state));
DEFINE(TASK_FLAGS, offsetof(struct task_struct, flags));
DEFINE(TASK_PTRACE, offsetof(struct task_struct, ptrace));
DEFINE(TASK_BLOCKED, offsetof(struct task_struct, blocked));
DEFINE(TASK_THREAD, offsetof(struct task_struct, thread));
DEFINE(TASK_THREAD_INFO, offsetof(struct task_struct, stack));
DEFINE(TASK_MM, offsetof(struct task_struct, mm));
DEFINE(TASK_ACTIVE_MM, offsetof(struct task_struct, active_mm));
/* offsets into the irq_cpustat_t struct */
DEFINE(CPUSTAT_SOFTIRQ_PENDING, offsetof(irq_cpustat_t, __softirq_pending));
/* offsets into the thread struct */
DEFINE(THREAD_KSP, offsetof(struct thread_struct, ksp));
DEFINE(THREAD_USP, offsetof(struct thread_struct, usp));
DEFINE(THREAD_CCR, offsetof(struct thread_struct, ccr));
/* offsets into the pt_regs struct */
DEFINE(LER0, offsetof(struct pt_regs, er0) - sizeof(long));
DEFINE(LER1, offsetof(struct pt_regs, er1) - sizeof(long));
DEFINE(LER2, offsetof(struct pt_regs, er2) - sizeof(long));
DEFINE(LER3, offsetof(struct pt_regs, er3) - sizeof(long));
DEFINE(LER4, offsetof(struct pt_regs, er4) - sizeof(long));
DEFINE(LER5, offsetof(struct pt_regs, er5) - sizeof(long));
DEFINE(LER6, offsetof(struct pt_regs, er6) - sizeof(long));
DEFINE(LORIG, offsetof(struct pt_regs, orig_er0) - sizeof(long));
DEFINE(LCCR, offsetof(struct pt_regs, ccr) - sizeof(long));
DEFINE(LVEC, offsetof(struct pt_regs, vector) - sizeof(long));
#if defined(__H8300S__)
DEFINE(LEXR, offsetof(struct pt_regs, exr) - sizeof(long));
#endif
DEFINE(LRET, offsetof(struct pt_regs, pc) - sizeof(long));
DEFINE(PT_PTRACED, PT_PTRACED);
return 0;
}
| gpl-2.0 |
TeamExodus/kernel_oneplus_msm8994 | arch/alpha/kernel/irq_i8259.c | 11941 | 3962 | /*
* linux/arch/alpha/kernel/irq_i8259.c
*
* This is the 'legacy' 8259A Programmable Interrupt Controller,
* present in the majority of PC/AT boxes.
*
* Started hacking from linux-2.3.30pre6/arch/i386/kernel/i8259.c.
*/
#include <linux/init.h>
#include <linux/cache.h>
#include <linux/sched.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <asm/io.h>
#include "proto.h"
#include "irq_impl.h"
/* Note mask bit is true for DISABLED irqs. */
static unsigned int cached_irq_mask = 0xffff;
static DEFINE_SPINLOCK(i8259_irq_lock);
static inline void
i8259_update_irq_hw(unsigned int irq, unsigned long mask)
{
int port = 0x21;
if (irq & 8) mask >>= 8;
if (irq & 8) port = 0xA1;
outb(mask, port);
}
inline void
i8259a_enable_irq(struct irq_data *d)
{
spin_lock(&i8259_irq_lock);
i8259_update_irq_hw(d->irq, cached_irq_mask &= ~(1 << d->irq));
spin_unlock(&i8259_irq_lock);
}
static inline void
__i8259a_disable_irq(unsigned int irq)
{
i8259_update_irq_hw(irq, cached_irq_mask |= 1 << irq);
}
void
i8259a_disable_irq(struct irq_data *d)
{
spin_lock(&i8259_irq_lock);
__i8259a_disable_irq(d->irq);
spin_unlock(&i8259_irq_lock);
}
void
i8259a_mask_and_ack_irq(struct irq_data *d)
{
unsigned int irq = d->irq;
spin_lock(&i8259_irq_lock);
__i8259a_disable_irq(irq);
/* Ack the interrupt making it the lowest priority. */
if (irq >= 8) {
outb(0xE0 | (irq - 8), 0xa0); /* ack the slave */
irq = 2;
}
outb(0xE0 | irq, 0x20); /* ack the master */
spin_unlock(&i8259_irq_lock);
}
struct irq_chip i8259a_irq_type = {
.name = "XT-PIC",
.irq_unmask = i8259a_enable_irq,
.irq_mask = i8259a_disable_irq,
.irq_mask_ack = i8259a_mask_and_ack_irq,
};
void __init
init_i8259a_irqs(void)
{
static struct irqaction cascade = {
.handler = no_action,
.name = "cascade",
};
long i;
outb(0xff, 0x21); /* mask all of 8259A-1 */
outb(0xff, 0xA1); /* mask all of 8259A-2 */
for (i = 0; i < 16; i++) {
irq_set_chip_and_handler(i, &i8259a_irq_type, handle_level_irq);
}
setup_irq(2, &cascade);
}
#if defined(CONFIG_ALPHA_GENERIC)
# define IACK_SC alpha_mv.iack_sc
#elif defined(CONFIG_ALPHA_APECS)
# define IACK_SC APECS_IACK_SC
#elif defined(CONFIG_ALPHA_LCA)
# define IACK_SC LCA_IACK_SC
#elif defined(CONFIG_ALPHA_CIA)
# define IACK_SC CIA_IACK_SC
#elif defined(CONFIG_ALPHA_PYXIS)
# define IACK_SC PYXIS_IACK_SC
#elif defined(CONFIG_ALPHA_TITAN)
# define IACK_SC TITAN_IACK_SC
#elif defined(CONFIG_ALPHA_TSUNAMI)
# define IACK_SC TSUNAMI_IACK_SC
#elif defined(CONFIG_ALPHA_IRONGATE)
# define IACK_SC IRONGATE_IACK_SC
#endif
/* Note that CONFIG_ALPHA_POLARIS is intentionally left out here, since
sys_rx164 wants to use isa_no_iack_sc_device_interrupt for some reason. */
#if defined(IACK_SC)
void
isa_device_interrupt(unsigned long vector)
{
/*
* Generate a PCI interrupt acknowledge cycle. The PIC will
* respond with the interrupt vector of the highest priority
* interrupt that is pending. The PALcode sets up the
* interrupts vectors such that irq level L generates vector L.
*/
int j = *(vuip) IACK_SC;
j &= 0xff;
handle_irq(j);
}
#endif
#if defined(CONFIG_ALPHA_GENERIC) || !defined(IACK_SC)
void
isa_no_iack_sc_device_interrupt(unsigned long vector)
{
unsigned long pic;
/*
* It seems to me that the probability of two or more *device*
* interrupts occurring at almost exactly the same time is
* pretty low. So why pay the price of checking for
* additional interrupts here if the common case can be
* handled so much easier?
*/
/*
* The first read of gives you *all* interrupting lines.
* Therefore, read the mask register and and out those lines
* not enabled. Note that some documentation has 21 and a1
* write only. This is not true.
*/
pic = inb(0x20) | (inb(0xA0) << 8); /* read isr */
pic &= 0xFFFB; /* mask out cascade & hibits */
while (pic) {
int j = ffz(~pic);
pic &= pic - 1;
handle_irq(j);
}
}
#endif
| gpl-2.0 |
ShadowElite22/Xperia-Z2-Z3 | arch/alpha/kernel/core_lca.c | 11941 | 14094 | /*
* linux/arch/alpha/kernel/core_lca.c
*
* Written by David Mosberger (davidm@cs.arizona.edu) with some code
* taken from Dave Rusling's (david.rusling@reo.mts.dec.com) 32-bit
* bios code.
*
* Code common to all LCA core logic chips.
*/
#define __EXTERN_INLINE inline
#include <asm/io.h>
#include <asm/core_lca.h>
#undef __EXTERN_INLINE
#include <linux/types.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/tty.h>
#include <asm/ptrace.h>
#include <asm/irq_regs.h>
#include <asm/smp.h>
#include "proto.h"
#include "pci_impl.h"
/*
* BIOS32-style PCI interface:
*/
/*
* Machine check reasons. Defined according to PALcode sources
* (osf.h and platform.h).
*/
#define MCHK_K_TPERR 0x0080
#define MCHK_K_TCPERR 0x0082
#define MCHK_K_HERR 0x0084
#define MCHK_K_ECC_C 0x0086
#define MCHK_K_ECC_NC 0x0088
#define MCHK_K_UNKNOWN 0x008A
#define MCHK_K_CACKSOFT 0x008C
#define MCHK_K_BUGCHECK 0x008E
#define MCHK_K_OS_BUGCHECK 0x0090
#define MCHK_K_DCPERR 0x0092
#define MCHK_K_ICPERR 0x0094
/*
* Platform-specific machine-check reasons:
*/
#define MCHK_K_SIO_SERR 0x204 /* all platforms so far */
#define MCHK_K_SIO_IOCHK 0x206 /* all platforms so far */
#define MCHK_K_DCSR 0x208 /* all but Noname */
/*
* Given a bus, device, and function number, compute resulting
* configuration space address and setup the LCA_IOC_CONF register
* accordingly. It is therefore not safe to have concurrent
* invocations to configuration space access routines, but there
* really shouldn't be any need for this.
*
* Type 0:
*
* 3 3|3 3 2 2|2 2 2 2|2 2 2 2|1 1 1 1|1 1 1 1|1 1
* 3 2|1 0 9 8|7 6 5 4|3 2 1 0|9 8 7 6|5 4 3 2|1 0 9 8|7 6 5 4|3 2 1 0
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | | | | | | | | | | | | | | | | | | | | | | | |F|F|F|R|R|R|R|R|R|0|0|
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* 31:11 Device select bit.
* 10:8 Function number
* 7:2 Register number
*
* Type 1:
*
* 3 3|3 3 2 2|2 2 2 2|2 2 2 2|1 1 1 1|1 1 1 1|1 1
* 3 2|1 0 9 8|7 6 5 4|3 2 1 0|9 8 7 6|5 4 3 2|1 0 9 8|7 6 5 4|3 2 1 0
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | | | | | | | | | | |B|B|B|B|B|B|B|B|D|D|D|D|D|F|F|F|R|R|R|R|R|R|0|1|
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* 31:24 reserved
* 23:16 bus number (8 bits = 128 possible buses)
* 15:11 Device number (5 bits)
* 10:8 function number
* 7:2 register number
*
* Notes:
* The function number selects which function of a multi-function device
* (e.g., SCSI and Ethernet).
*
* The register selects a DWORD (32 bit) register offset. Hence it
* doesn't get shifted by 2 bits as we want to "drop" the bottom two
* bits.
*/
static int
mk_conf_addr(struct pci_bus *pbus, unsigned int device_fn, int where,
unsigned long *pci_addr)
{
unsigned long addr;
u8 bus = pbus->number;
if (bus == 0) {
int device = device_fn >> 3;
int func = device_fn & 0x7;
/* Type 0 configuration cycle. */
if (device > 12) {
return -1;
}
*(vulp)LCA_IOC_CONF = 0;
addr = (1 << (11 + device)) | (func << 8) | where;
} else {
/* Type 1 configuration cycle. */
*(vulp)LCA_IOC_CONF = 1;
addr = (bus << 16) | (device_fn << 8) | where;
}
*pci_addr = addr;
return 0;
}
static unsigned int
conf_read(unsigned long addr)
{
unsigned long flags, code, stat0;
unsigned int value;
local_irq_save(flags);
/* Reset status register to avoid losing errors. */
stat0 = *(vulp)LCA_IOC_STAT0;
*(vulp)LCA_IOC_STAT0 = stat0;
mb();
/* Access configuration space. */
value = *(vuip)addr;
draina();
stat0 = *(vulp)LCA_IOC_STAT0;
if (stat0 & LCA_IOC_STAT0_ERR) {
code = ((stat0 >> LCA_IOC_STAT0_CODE_SHIFT)
& LCA_IOC_STAT0_CODE_MASK);
if (code != 1) {
printk("lca.c:conf_read: got stat0=%lx\n", stat0);
}
/* Reset error status. */
*(vulp)LCA_IOC_STAT0 = stat0;
mb();
/* Reset machine check. */
wrmces(0x7);
value = 0xffffffff;
}
local_irq_restore(flags);
return value;
}
static void
conf_write(unsigned long addr, unsigned int value)
{
unsigned long flags, code, stat0;
local_irq_save(flags); /* avoid getting hit by machine check */
/* Reset status register to avoid losing errors. */
stat0 = *(vulp)LCA_IOC_STAT0;
*(vulp)LCA_IOC_STAT0 = stat0;
mb();
/* Access configuration space. */
*(vuip)addr = value;
draina();
stat0 = *(vulp)LCA_IOC_STAT0;
if (stat0 & LCA_IOC_STAT0_ERR) {
code = ((stat0 >> LCA_IOC_STAT0_CODE_SHIFT)
& LCA_IOC_STAT0_CODE_MASK);
if (code != 1) {
printk("lca.c:conf_write: got stat0=%lx\n", stat0);
}
/* Reset error status. */
*(vulp)LCA_IOC_STAT0 = stat0;
mb();
/* Reset machine check. */
wrmces(0x7);
}
local_irq_restore(flags);
}
static int
lca_read_config(struct pci_bus *bus, unsigned int devfn, int where,
int size, u32 *value)
{
unsigned long addr, pci_addr;
long mask;
int shift;
if (mk_conf_addr(bus, devfn, where, &pci_addr))
return PCIBIOS_DEVICE_NOT_FOUND;
shift = (where & 3) * 8;
mask = (size - 1) * 8;
addr = (pci_addr << 5) + mask + LCA_CONF;
*value = conf_read(addr) >> (shift);
return PCIBIOS_SUCCESSFUL;
}
static int
lca_write_config(struct pci_bus *bus, unsigned int devfn, int where, int size,
u32 value)
{
unsigned long addr, pci_addr;
long mask;
if (mk_conf_addr(bus, devfn, where, &pci_addr))
return PCIBIOS_DEVICE_NOT_FOUND;
mask = (size - 1) * 8;
addr = (pci_addr << 5) + mask + LCA_CONF;
conf_write(addr, value << ((where & 3) * 8));
return PCIBIOS_SUCCESSFUL;
}
struct pci_ops lca_pci_ops =
{
.read = lca_read_config,
.write = lca_write_config,
};
void
lca_pci_tbi(struct pci_controller *hose, dma_addr_t start, dma_addr_t end)
{
wmb();
*(vulp)LCA_IOC_TBIA = 0;
mb();
}
void __init
lca_init_arch(void)
{
struct pci_controller *hose;
/*
* Create our single hose.
*/
pci_isa_hose = hose = alloc_pci_controller();
hose->io_space = &ioport_resource;
hose->mem_space = &iomem_resource;
hose->index = 0;
hose->sparse_mem_base = LCA_SPARSE_MEM - IDENT_ADDR;
hose->dense_mem_base = LCA_DENSE_MEM - IDENT_ADDR;
hose->sparse_io_base = LCA_IO - IDENT_ADDR;
hose->dense_io_base = 0;
/*
* Set up the PCI to main memory translation windows.
*
* Mimic the SRM settings for the direct-map window.
* Window 0 is scatter-gather 8MB at 8MB (for isa).
* Window 1 is direct access 1GB at 1GB.
*
* Note that we do not try to save any of the DMA window CSRs
* before setting them, since we cannot read those CSRs on LCA.
*/
hose->sg_isa = iommu_arena_new(hose, 0x00800000, 0x00800000, 0);
hose->sg_pci = NULL;
__direct_map_base = 0x40000000;
__direct_map_size = 0x40000000;
*(vulp)LCA_IOC_W_BASE0 = hose->sg_isa->dma_base | (3UL << 32);
*(vulp)LCA_IOC_W_MASK0 = (hose->sg_isa->size - 1) & 0xfff00000;
*(vulp)LCA_IOC_T_BASE0 = virt_to_phys(hose->sg_isa->ptes);
*(vulp)LCA_IOC_W_BASE1 = __direct_map_base | (2UL << 32);
*(vulp)LCA_IOC_W_MASK1 = (__direct_map_size - 1) & 0xfff00000;
*(vulp)LCA_IOC_T_BASE1 = 0;
*(vulp)LCA_IOC_TB_ENA = 0x80;
lca_pci_tbi(hose, 0, -1);
/*
* Disable PCI parity for now. The NCR53c810 chip has
* troubles meeting the PCI spec which results in
* data parity errors.
*/
*(vulp)LCA_IOC_PAR_DIS = 1UL<<5;
/*
* Finally, set up for restoring the correct HAE if using SRM.
* Again, since we cannot read many of the CSRs on the LCA,
* one of which happens to be the HAE, we save the value that
* the SRM will expect...
*/
if (alpha_using_srm)
srm_hae = 0x80000000UL;
}
/*
* Constants used during machine-check handling. I suppose these
* could be moved into lca.h but I don't see much reason why anybody
* else would want to use them.
*/
#define ESR_EAV (1UL<< 0) /* error address valid */
#define ESR_CEE (1UL<< 1) /* correctable error */
#define ESR_UEE (1UL<< 2) /* uncorrectable error */
#define ESR_WRE (1UL<< 3) /* write-error */
#define ESR_SOR (1UL<< 4) /* error source */
#define ESR_CTE (1UL<< 7) /* cache-tag error */
#define ESR_MSE (1UL<< 9) /* multiple soft errors */
#define ESR_MHE (1UL<<10) /* multiple hard errors */
#define ESR_NXM (1UL<<12) /* non-existent memory */
#define IOC_ERR ( 1<<4) /* ioc logs an error */
#define IOC_CMD_SHIFT 0
#define IOC_CMD (0xf<<IOC_CMD_SHIFT)
#define IOC_CODE_SHIFT 8
#define IOC_CODE (0xf<<IOC_CODE_SHIFT)
#define IOC_LOST ( 1<<5)
#define IOC_P_NBR ((__u32) ~((1<<13) - 1))
static void
mem_error(unsigned long esr, unsigned long ear)
{
printk(" %s %s error to %s occurred at address %x\n",
((esr & ESR_CEE) ? "Correctable" :
(esr & ESR_UEE) ? "Uncorrectable" : "A"),
(esr & ESR_WRE) ? "write" : "read",
(esr & ESR_SOR) ? "memory" : "b-cache",
(unsigned) (ear & 0x1ffffff8));
if (esr & ESR_CTE) {
printk(" A b-cache tag parity error was detected.\n");
}
if (esr & ESR_MSE) {
printk(" Several other correctable errors occurred.\n");
}
if (esr & ESR_MHE) {
printk(" Several other uncorrectable errors occurred.\n");
}
if (esr & ESR_NXM) {
printk(" Attempted to access non-existent memory.\n");
}
}
static void
ioc_error(__u32 stat0, __u32 stat1)
{
static const char * const pci_cmd[] = {
"Interrupt Acknowledge", "Special", "I/O Read", "I/O Write",
"Rsvd 1", "Rsvd 2", "Memory Read", "Memory Write", "Rsvd3",
"Rsvd4", "Configuration Read", "Configuration Write",
"Memory Read Multiple", "Dual Address", "Memory Read Line",
"Memory Write and Invalidate"
};
static const char * const err_name[] = {
"exceeded retry limit", "no device", "bad data parity",
"target abort", "bad address parity", "page table read error",
"invalid page", "data error"
};
unsigned code = (stat0 & IOC_CODE) >> IOC_CODE_SHIFT;
unsigned cmd = (stat0 & IOC_CMD) >> IOC_CMD_SHIFT;
printk(" %s initiated PCI %s cycle to address %x"
" failed due to %s.\n",
code > 3 ? "PCI" : "CPU", pci_cmd[cmd], stat1, err_name[code]);
if (code == 5 || code == 6) {
printk(" (Error occurred at PCI memory address %x.)\n",
(stat0 & ~IOC_P_NBR));
}
if (stat0 & IOC_LOST) {
printk(" Other PCI errors occurred simultaneously.\n");
}
}
void
lca_machine_check(unsigned long vector, unsigned long la_ptr)
{
const char * reason;
union el_lca el;
el.c = (struct el_common *) la_ptr;
wrmces(rdmces()); /* reset machine check pending flag */
printk(KERN_CRIT "LCA machine check: vector=%#lx pc=%#lx code=%#x\n",
vector, get_irq_regs()->pc, (unsigned int) el.c->code);
/*
* The first quadword after the common header always seems to
* be the machine check reason---don't know why this isn't
* part of the common header instead. In the case of a long
* logout frame, the upper 32 bits is the machine check
* revision level, which we ignore for now.
*/
switch ((unsigned int) el.c->code) {
case MCHK_K_TPERR: reason = "tag parity error"; break;
case MCHK_K_TCPERR: reason = "tag control parity error"; break;
case MCHK_K_HERR: reason = "access to non-existent memory"; break;
case MCHK_K_ECC_C: reason = "correctable ECC error"; break;
case MCHK_K_ECC_NC: reason = "non-correctable ECC error"; break;
case MCHK_K_CACKSOFT: reason = "MCHK_K_CACKSOFT"; break;
case MCHK_K_BUGCHECK: reason = "illegal exception in PAL mode"; break;
case MCHK_K_OS_BUGCHECK: reason = "callsys in kernel mode"; break;
case MCHK_K_DCPERR: reason = "d-cache parity error"; break;
case MCHK_K_ICPERR: reason = "i-cache parity error"; break;
case MCHK_K_SIO_SERR: reason = "SIO SERR occurred on PCI bus"; break;
case MCHK_K_SIO_IOCHK: reason = "SIO IOCHK occurred on ISA bus"; break;
case MCHK_K_DCSR: reason = "MCHK_K_DCSR"; break;
case MCHK_K_UNKNOWN:
default: reason = "unknown"; break;
}
switch (el.c->size) {
case sizeof(struct el_lca_mcheck_short):
printk(KERN_CRIT
" Reason: %s (short frame%s, dc_stat=%#lx):\n",
reason, el.c->retry ? ", retryable" : "",
el.s->dc_stat);
if (el.s->esr & ESR_EAV) {
mem_error(el.s->esr, el.s->ear);
}
if (el.s->ioc_stat0 & IOC_ERR) {
ioc_error(el.s->ioc_stat0, el.s->ioc_stat1);
}
break;
case sizeof(struct el_lca_mcheck_long):
printk(KERN_CRIT " Reason: %s (long frame%s):\n",
reason, el.c->retry ? ", retryable" : "");
printk(KERN_CRIT
" reason: %#lx exc_addr: %#lx dc_stat: %#lx\n",
el.l->pt[0], el.l->exc_addr, el.l->dc_stat);
printk(KERN_CRIT " car: %#lx\n", el.l->car);
if (el.l->esr & ESR_EAV) {
mem_error(el.l->esr, el.l->ear);
}
if (el.l->ioc_stat0 & IOC_ERR) {
ioc_error(el.l->ioc_stat0, el.l->ioc_stat1);
}
break;
default:
printk(KERN_CRIT " Unknown errorlog size %d\n", el.c->size);
}
/* Dump the logout area to give all info. */
#ifdef CONFIG_VERBOSE_MCHECK
if (alpha_verbose_mcheck > 1) {
unsigned long * ptr = (unsigned long *) la_ptr;
long i;
for (i = 0; i < el.c->size / sizeof(long); i += 2) {
printk(KERN_CRIT " +%8lx %016lx %016lx\n",
i*sizeof(long), ptr[i], ptr[i+1]);
}
}
#endif /* CONFIG_VERBOSE_MCHECK */
}
/*
* The following routines are needed to support the SPEED changing
* necessary to successfully manage the thermal problem on the AlphaBook1.
*/
void
lca_clock_print(void)
{
long pmr_reg;
pmr_reg = LCA_READ_PMR;
printk("Status of clock control:\n");
printk("\tPrimary clock divisor\t0x%lx\n", LCA_GET_PRIMARY(pmr_reg));
printk("\tOverride clock divisor\t0x%lx\n", LCA_GET_OVERRIDE(pmr_reg));
printk("\tInterrupt override is %s\n",
(pmr_reg & LCA_PMR_INTO) ? "on" : "off");
printk("\tDMA override is %s\n",
(pmr_reg & LCA_PMR_DMAO) ? "on" : "off");
}
int
lca_get_clock(void)
{
long pmr_reg;
pmr_reg = LCA_READ_PMR;
return(LCA_GET_PRIMARY(pmr_reg));
}
void
lca_clock_fiddle(int divisor)
{
long pmr_reg;
pmr_reg = LCA_READ_PMR;
LCA_SET_PRIMARY_CLOCK(pmr_reg, divisor);
/* lca_norm_clock = divisor; */
LCA_WRITE_PMR(pmr_reg);
mb();
}
| gpl-2.0 |
surkovalex/linux | arch/alpha/kernel/core_mcpcia.c | 11941 | 16130 | /*
* linux/arch/alpha/kernel/core_mcpcia.c
*
* Based on code written by David A Rusling (david.rusling@reo.mts.dec.com).
*
* Code common to all MCbus-PCI Adaptor core logic chipsets
*/
#define __EXTERN_INLINE inline
#include <asm/io.h>
#include <asm/core_mcpcia.h>
#undef __EXTERN_INLINE
#include <linux/types.h>
#include <linux/pci.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <asm/ptrace.h>
#include "proto.h"
#include "pci_impl.h"
/*
* NOTE: Herein lie back-to-back mb instructions. They are magic.
* One plausible explanation is that the i/o controller does not properly
* handle the system transaction. Another involves timing. Ho hum.
*/
/*
* BIOS32-style PCI interface:
*/
#define DEBUG_CFG 0
#if DEBUG_CFG
# define DBG_CFG(args) printk args
#else
# define DBG_CFG(args)
#endif
/*
* Given a bus, device, and function number, compute resulting
* configuration space address and setup the MCPCIA_HAXR2 register
* accordingly. It is therefore not safe to have concurrent
* invocations to configuration space access routines, but there
* really shouldn't be any need for this.
*
* Type 0:
*
* 3 3|3 3 2 2|2 2 2 2|2 2 2 2|1 1 1 1|1 1 1 1|1 1
* 3 2|1 0 9 8|7 6 5 4|3 2 1 0|9 8 7 6|5 4 3 2|1 0 9 8|7 6 5 4|3 2 1 0
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | | |D|D|D|D|D|D|D|D|D|D|D|D|D|D|D|D|D|D|D|D|D|F|F|F|R|R|R|R|R|R|0|0|
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* 31:11 Device select bit.
* 10:8 Function number
* 7:2 Register number
*
* Type 1:
*
* 3 3|3 3 2 2|2 2 2 2|2 2 2 2|1 1 1 1|1 1 1 1|1 1
* 3 2|1 0 9 8|7 6 5 4|3 2 1 0|9 8 7 6|5 4 3 2|1 0 9 8|7 6 5 4|3 2 1 0
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | | | | | | | | | | |B|B|B|B|B|B|B|B|D|D|D|D|D|F|F|F|R|R|R|R|R|R|0|1|
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* 31:24 reserved
* 23:16 bus number (8 bits = 128 possible buses)
* 15:11 Device number (5 bits)
* 10:8 function number
* 7:2 register number
*
* Notes:
* The function number selects which function of a multi-function device
* (e.g., SCSI and Ethernet).
*
* The register selects a DWORD (32 bit) register offset. Hence it
* doesn't get shifted by 2 bits as we want to "drop" the bottom two
* bits.
*/
static unsigned int
conf_read(unsigned long addr, unsigned char type1,
struct pci_controller *hose)
{
unsigned long flags;
unsigned long mid = MCPCIA_HOSE2MID(hose->index);
unsigned int stat0, value, cpu;
cpu = smp_processor_id();
local_irq_save(flags);
DBG_CFG(("conf_read(addr=0x%lx, type1=%d, hose=%d)\n",
addr, type1, mid));
/* Reset status register to avoid losing errors. */
stat0 = *(vuip)MCPCIA_CAP_ERR(mid);
*(vuip)MCPCIA_CAP_ERR(mid) = stat0;
mb();
*(vuip)MCPCIA_CAP_ERR(mid);
DBG_CFG(("conf_read: MCPCIA_CAP_ERR(%d) was 0x%x\n", mid, stat0));
mb();
draina();
mcheck_expected(cpu) = 1;
mcheck_taken(cpu) = 0;
mcheck_extra(cpu) = mid;
mb();
/* Access configuration space. */
value = *((vuip)addr);
mb();
mb(); /* magic */
if (mcheck_taken(cpu)) {
mcheck_taken(cpu) = 0;
value = 0xffffffffU;
mb();
}
mcheck_expected(cpu) = 0;
mb();
DBG_CFG(("conf_read(): finished\n"));
local_irq_restore(flags);
return value;
}
static void
conf_write(unsigned long addr, unsigned int value, unsigned char type1,
struct pci_controller *hose)
{
unsigned long flags;
unsigned long mid = MCPCIA_HOSE2MID(hose->index);
unsigned int stat0, cpu;
cpu = smp_processor_id();
local_irq_save(flags); /* avoid getting hit by machine check */
/* Reset status register to avoid losing errors. */
stat0 = *(vuip)MCPCIA_CAP_ERR(mid);
*(vuip)MCPCIA_CAP_ERR(mid) = stat0; mb();
*(vuip)MCPCIA_CAP_ERR(mid);
DBG_CFG(("conf_write: MCPCIA CAP_ERR(%d) was 0x%x\n", mid, stat0));
draina();
mcheck_expected(cpu) = 1;
mcheck_extra(cpu) = mid;
mb();
/* Access configuration space. */
*((vuip)addr) = value;
mb();
mb(); /* magic */
*(vuip)MCPCIA_CAP_ERR(mid); /* read to force the write */
mcheck_expected(cpu) = 0;
mb();
DBG_CFG(("conf_write(): finished\n"));
local_irq_restore(flags);
}
static int
mk_conf_addr(struct pci_bus *pbus, unsigned int devfn, int where,
struct pci_controller *hose, unsigned long *pci_addr,
unsigned char *type1)
{
u8 bus = pbus->number;
unsigned long addr;
DBG_CFG(("mk_conf_addr(bus=%d,devfn=0x%x,hose=%d,where=0x%x,"
" pci_addr=0x%p, type1=0x%p)\n",
bus, devfn, hose->index, where, pci_addr, type1));
/* Type 1 configuration cycle for *ALL* busses. */
*type1 = 1;
if (!pbus->parent) /* No parent means peer PCI bus. */
bus = 0;
addr = (bus << 16) | (devfn << 8) | (where);
addr <<= 5; /* swizzle for SPARSE */
addr |= hose->config_space_base;
*pci_addr = addr;
DBG_CFG(("mk_conf_addr: returning pci_addr 0x%lx\n", addr));
return 0;
}
static int
mcpcia_read_config(struct pci_bus *bus, unsigned int devfn, int where,
int size, u32 *value)
{
struct pci_controller *hose = bus->sysdata;
unsigned long addr, w;
unsigned char type1;
if (mk_conf_addr(bus, devfn, where, hose, &addr, &type1))
return PCIBIOS_DEVICE_NOT_FOUND;
addr |= (size - 1) * 8;
w = conf_read(addr, type1, hose);
switch (size) {
case 1:
*value = __kernel_extbl(w, where & 3);
break;
case 2:
*value = __kernel_extwl(w, where & 3);
break;
case 4:
*value = w;
break;
}
return PCIBIOS_SUCCESSFUL;
}
static int
mcpcia_write_config(struct pci_bus *bus, unsigned int devfn, int where,
int size, u32 value)
{
struct pci_controller *hose = bus->sysdata;
unsigned long addr;
unsigned char type1;
if (mk_conf_addr(bus, devfn, where, hose, &addr, &type1))
return PCIBIOS_DEVICE_NOT_FOUND;
addr |= (size - 1) * 8;
value = __kernel_insql(value, where & 3);
conf_write(addr, value, type1, hose);
return PCIBIOS_SUCCESSFUL;
}
struct pci_ops mcpcia_pci_ops =
{
.read = mcpcia_read_config,
.write = mcpcia_write_config,
};
void
mcpcia_pci_tbi(struct pci_controller *hose, dma_addr_t start, dma_addr_t end)
{
wmb();
*(vuip)MCPCIA_SG_TBIA(MCPCIA_HOSE2MID(hose->index)) = 0;
mb();
}
static int __init
mcpcia_probe_hose(int h)
{
int cpu = smp_processor_id();
int mid = MCPCIA_HOSE2MID(h);
unsigned int pci_rev;
/* Gotta be REAL careful. If hose is absent, we get an mcheck. */
mb();
mb();
draina();
wrmces(7);
mcheck_expected(cpu) = 2; /* indicates probing */
mcheck_taken(cpu) = 0;
mcheck_extra(cpu) = mid;
mb();
/* Access the bus revision word. */
pci_rev = *(vuip)MCPCIA_REV(mid);
mb();
mb(); /* magic */
if (mcheck_taken(cpu)) {
mcheck_taken(cpu) = 0;
pci_rev = 0xffffffff;
mb();
}
mcheck_expected(cpu) = 0;
mb();
return (pci_rev >> 16) == PCI_CLASS_BRIDGE_HOST;
}
static void __init
mcpcia_new_hose(int h)
{
struct pci_controller *hose;
struct resource *io, *mem, *hae_mem;
int mid = MCPCIA_HOSE2MID(h);
hose = alloc_pci_controller();
if (h == 0)
pci_isa_hose = hose;
io = alloc_resource();
mem = alloc_resource();
hae_mem = alloc_resource();
hose->io_space = io;
hose->mem_space = hae_mem;
hose->sparse_mem_base = MCPCIA_SPARSE(mid) - IDENT_ADDR;
hose->dense_mem_base = MCPCIA_DENSE(mid) - IDENT_ADDR;
hose->sparse_io_base = MCPCIA_IO(mid) - IDENT_ADDR;
hose->dense_io_base = 0;
hose->config_space_base = MCPCIA_CONF(mid);
hose->index = h;
io->start = MCPCIA_IO(mid) - MCPCIA_IO_BIAS;
io->end = io->start + 0xffff;
io->name = pci_io_names[h];
io->flags = IORESOURCE_IO;
mem->start = MCPCIA_DENSE(mid) - MCPCIA_MEM_BIAS;
mem->end = mem->start + 0xffffffff;
mem->name = pci_mem_names[h];
mem->flags = IORESOURCE_MEM;
hae_mem->start = mem->start;
hae_mem->end = mem->start + MCPCIA_MEM_MASK;
hae_mem->name = pci_hae0_name;
hae_mem->flags = IORESOURCE_MEM;
if (request_resource(&ioport_resource, io) < 0)
printk(KERN_ERR "Failed to request IO on hose %d\n", h);
if (request_resource(&iomem_resource, mem) < 0)
printk(KERN_ERR "Failed to request MEM on hose %d\n", h);
if (request_resource(mem, hae_mem) < 0)
printk(KERN_ERR "Failed to request HAE_MEM on hose %d\n", h);
}
static void
mcpcia_pci_clr_err(int mid)
{
*(vuip)MCPCIA_CAP_ERR(mid);
*(vuip)MCPCIA_CAP_ERR(mid) = 0xffffffff; /* Clear them all. */
mb();
*(vuip)MCPCIA_CAP_ERR(mid); /* Re-read for force write. */
}
static void __init
mcpcia_startup_hose(struct pci_controller *hose)
{
int mid = MCPCIA_HOSE2MID(hose->index);
unsigned int tmp;
mcpcia_pci_clr_err(mid);
/*
* Set up error reporting.
*/
tmp = *(vuip)MCPCIA_CAP_ERR(mid);
tmp |= 0x0006; /* master/target abort */
*(vuip)MCPCIA_CAP_ERR(mid) = tmp;
mb();
tmp = *(vuip)MCPCIA_CAP_ERR(mid);
/*
* Set up the PCI->physical memory translation windows.
*
* Window 0 is scatter-gather 8MB at 8MB (for isa)
* Window 1 is scatter-gather (up to) 1GB at 1GB (for pci)
* Window 2 is direct access 2GB at 2GB
*/
hose->sg_isa = iommu_arena_new(hose, 0x00800000, 0x00800000, 0);
hose->sg_pci = iommu_arena_new(hose, 0x40000000,
size_for_memory(0x40000000), 0);
__direct_map_base = 0x80000000;
__direct_map_size = 0x80000000;
*(vuip)MCPCIA_W0_BASE(mid) = hose->sg_isa->dma_base | 3;
*(vuip)MCPCIA_W0_MASK(mid) = (hose->sg_isa->size - 1) & 0xfff00000;
*(vuip)MCPCIA_T0_BASE(mid) = virt_to_phys(hose->sg_isa->ptes) >> 8;
*(vuip)MCPCIA_W1_BASE(mid) = hose->sg_pci->dma_base | 3;
*(vuip)MCPCIA_W1_MASK(mid) = (hose->sg_pci->size - 1) & 0xfff00000;
*(vuip)MCPCIA_T1_BASE(mid) = virt_to_phys(hose->sg_pci->ptes) >> 8;
*(vuip)MCPCIA_W2_BASE(mid) = __direct_map_base | 1;
*(vuip)MCPCIA_W2_MASK(mid) = (__direct_map_size - 1) & 0xfff00000;
*(vuip)MCPCIA_T2_BASE(mid) = 0;
*(vuip)MCPCIA_W3_BASE(mid) = 0x0;
mcpcia_pci_tbi(hose, 0, -1);
*(vuip)MCPCIA_HBASE(mid) = 0x0;
mb();
*(vuip)MCPCIA_HAE_MEM(mid) = 0U;
mb();
*(vuip)MCPCIA_HAE_MEM(mid); /* read it back. */
*(vuip)MCPCIA_HAE_IO(mid) = 0;
mb();
*(vuip)MCPCIA_HAE_IO(mid); /* read it back. */
}
void __init
mcpcia_init_arch(void)
{
/* With multiple PCI busses, we play with I/O as physical addrs. */
ioport_resource.end = ~0UL;
/* Allocate hose 0. That's the one that all the ISA junk hangs
off of, from which we'll be registering stuff here in a bit.
Other hose detection is done in mcpcia_init_hoses, which is
called from init_IRQ. */
mcpcia_new_hose(0);
}
/* This is called from init_IRQ, since we cannot take interrupts
before then. Which means we cannot do this in init_arch. */
void __init
mcpcia_init_hoses(void)
{
struct pci_controller *hose;
int hose_count;
int h;
/* First, find how many hoses we have. */
hose_count = 0;
for (h = 0; h < MCPCIA_MAX_HOSES; ++h) {
if (mcpcia_probe_hose(h)) {
if (h != 0)
mcpcia_new_hose(h);
hose_count++;
}
}
printk("mcpcia_init_hoses: found %d hoses\n", hose_count);
/* Now do init for each hose. */
for (hose = hose_head; hose; hose = hose->next)
mcpcia_startup_hose(hose);
}
static void
mcpcia_print_uncorrectable(struct el_MCPCIA_uncorrected_frame_mcheck *logout)
{
struct el_common_EV5_uncorrectable_mcheck *frame;
int i;
frame = &logout->procdata;
/* Print PAL fields */
for (i = 0; i < 24; i += 2) {
printk(" paltmp[%d-%d] = %16lx %16lx\n",
i, i+1, frame->paltemp[i], frame->paltemp[i+1]);
}
for (i = 0; i < 8; i += 2) {
printk(" shadow[%d-%d] = %16lx %16lx\n",
i, i+1, frame->shadow[i],
frame->shadow[i+1]);
}
printk(" Addr of excepting instruction = %16lx\n",
frame->exc_addr);
printk(" Summary of arithmetic traps = %16lx\n",
frame->exc_sum);
printk(" Exception mask = %16lx\n",
frame->exc_mask);
printk(" Base address for PALcode = %16lx\n",
frame->pal_base);
printk(" Interrupt Status Reg = %16lx\n",
frame->isr);
printk(" CURRENT SETUP OF EV5 IBOX = %16lx\n",
frame->icsr);
printk(" I-CACHE Reg %s parity error = %16lx\n",
(frame->ic_perr_stat & 0x800L) ?
"Data" : "Tag",
frame->ic_perr_stat);
printk(" D-CACHE error Reg = %16lx\n",
frame->dc_perr_stat);
if (frame->dc_perr_stat & 0x2) {
switch (frame->dc_perr_stat & 0x03c) {
case 8:
printk(" Data error in bank 1\n");
break;
case 4:
printk(" Data error in bank 0\n");
break;
case 20:
printk(" Tag error in bank 1\n");
break;
case 10:
printk(" Tag error in bank 0\n");
break;
}
}
printk(" Effective VA = %16lx\n",
frame->va);
printk(" Reason for D-stream = %16lx\n",
frame->mm_stat);
printk(" EV5 SCache address = %16lx\n",
frame->sc_addr);
printk(" EV5 SCache TAG/Data parity = %16lx\n",
frame->sc_stat);
printk(" EV5 BC_TAG_ADDR = %16lx\n",
frame->bc_tag_addr);
printk(" EV5 EI_ADDR: Phys addr of Xfer = %16lx\n",
frame->ei_addr);
printk(" Fill Syndrome = %16lx\n",
frame->fill_syndrome);
printk(" EI_STAT reg = %16lx\n",
frame->ei_stat);
printk(" LD_LOCK = %16lx\n",
frame->ld_lock);
}
static void
mcpcia_print_system_area(unsigned long la_ptr)
{
struct el_common *frame;
struct pci_controller *hose;
struct IOD_subpacket {
unsigned long base;
unsigned int whoami;
unsigned int rsvd1;
unsigned int pci_rev;
unsigned int cap_ctrl;
unsigned int hae_mem;
unsigned int hae_io;
unsigned int int_ctl;
unsigned int int_reg;
unsigned int int_mask0;
unsigned int int_mask1;
unsigned int mc_err0;
unsigned int mc_err1;
unsigned int cap_err;
unsigned int rsvd2;
unsigned int pci_err1;
unsigned int mdpa_stat;
unsigned int mdpa_syn;
unsigned int mdpb_stat;
unsigned int mdpb_syn;
unsigned int rsvd3;
unsigned int rsvd4;
unsigned int rsvd5;
} *iodpp;
frame = (struct el_common *)la_ptr;
iodpp = (struct IOD_subpacket *) (la_ptr + frame->sys_offset);
for (hose = hose_head; hose; hose = hose->next, iodpp++) {
printk("IOD %d Register Subpacket - Bridge Base Address %16lx\n",
hose->index, iodpp->base);
printk(" WHOAMI = %8x\n", iodpp->whoami);
printk(" PCI_REV = %8x\n", iodpp->pci_rev);
printk(" CAP_CTRL = %8x\n", iodpp->cap_ctrl);
printk(" HAE_MEM = %8x\n", iodpp->hae_mem);
printk(" HAE_IO = %8x\n", iodpp->hae_io);
printk(" INT_CTL = %8x\n", iodpp->int_ctl);
printk(" INT_REG = %8x\n", iodpp->int_reg);
printk(" INT_MASK0 = %8x\n", iodpp->int_mask0);
printk(" INT_MASK1 = %8x\n", iodpp->int_mask1);
printk(" MC_ERR0 = %8x\n", iodpp->mc_err0);
printk(" MC_ERR1 = %8x\n", iodpp->mc_err1);
printk(" CAP_ERR = %8x\n", iodpp->cap_err);
printk(" PCI_ERR1 = %8x\n", iodpp->pci_err1);
printk(" MDPA_STAT = %8x\n", iodpp->mdpa_stat);
printk(" MDPA_SYN = %8x\n", iodpp->mdpa_syn);
printk(" MDPB_STAT = %8x\n", iodpp->mdpb_stat);
printk(" MDPB_SYN = %8x\n", iodpp->mdpb_syn);
}
}
void
mcpcia_machine_check(unsigned long vector, unsigned long la_ptr)
{
struct el_MCPCIA_uncorrected_frame_mcheck *mchk_logout;
unsigned int cpu = smp_processor_id();
int expected;
mchk_logout = (struct el_MCPCIA_uncorrected_frame_mcheck *)la_ptr;
expected = mcheck_expected(cpu);
mb();
mb(); /* magic */
draina();
switch (expected) {
case 0:
{
/* FIXME: how do we figure out which hose the
error was on? */
struct pci_controller *hose;
for (hose = hose_head; hose; hose = hose->next)
mcpcia_pci_clr_err(MCPCIA_HOSE2MID(hose->index));
break;
}
case 1:
mcpcia_pci_clr_err(mcheck_extra(cpu));
break;
default:
/* Otherwise, we're being called from mcpcia_probe_hose
and there's no hose clear an error from. */
break;
}
wrmces(0x7);
mb();
process_mcheck_info(vector, la_ptr, "MCPCIA", expected != 0);
if (!expected && vector != 0x620 && vector != 0x630) {
mcpcia_print_uncorrectable(mchk_logout);
mcpcia_print_system_area(la_ptr);
}
}
| gpl-2.0 |
cleaton/liquid-chocolate | net/ipv4/ip_input.c | 166 | 13150 | /*
* INET An implementation of the TCP/IP protocol suite for the LINUX
* operating system. INET is implemented using the BSD Socket
* interface as the means of communication with the user level.
*
* The Internet Protocol (IP) module.
*
* Authors: Ross Biro
* Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
* Donald Becker, <becker@super.org>
* Alan Cox, <alan@lxorguk.ukuu.org.uk>
* Richard Underwood
* Stefan Becker, <stefanb@yello.ping.de>
* Jorge Cwik, <jorge@laser.satlink.net>
* Arnt Gulbrandsen, <agulbra@nvg.unit.no>
*
*
* Fixes:
* Alan Cox : Commented a couple of minor bits of surplus code
* Alan Cox : Undefining IP_FORWARD doesn't include the code
* (just stops a compiler warning).
* Alan Cox : Frames with >=MAX_ROUTE record routes, strict routes or loose routes
* are junked rather than corrupting things.
* Alan Cox : Frames to bad broadcast subnets are dumped
* We used to process them non broadcast and
* boy could that cause havoc.
* Alan Cox : ip_forward sets the free flag on the
* new frame it queues. Still crap because
* it copies the frame but at least it
* doesn't eat memory too.
* Alan Cox : Generic queue code and memory fixes.
* Fred Van Kempen : IP fragment support (borrowed from NET2E)
* Gerhard Koerting: Forward fragmented frames correctly.
* Gerhard Koerting: Fixes to my fix of the above 8-).
* Gerhard Koerting: IP interface addressing fix.
* Linus Torvalds : More robustness checks
* Alan Cox : Even more checks: Still not as robust as it ought to be
* Alan Cox : Save IP header pointer for later
* Alan Cox : ip option setting
* Alan Cox : Use ip_tos/ip_ttl settings
* Alan Cox : Fragmentation bogosity removed
* (Thanks to Mark.Bush@prg.ox.ac.uk)
* Dmitry Gorodchanin : Send of a raw packet crash fix.
* Alan Cox : Silly ip bug when an overlength
* fragment turns up. Now frees the
* queue.
* Linus Torvalds/ : Memory leakage on fragmentation
* Alan Cox : handling.
* Gerhard Koerting: Forwarding uses IP priority hints
* Teemu Rantanen : Fragment problems.
* Alan Cox : General cleanup, comments and reformat
* Alan Cox : SNMP statistics
* Alan Cox : BSD address rule semantics. Also see
* UDP as there is a nasty checksum issue
* if you do things the wrong way.
* Alan Cox : Always defrag, moved IP_FORWARD to the config.in file
* Alan Cox : IP options adjust sk->priority.
* Pedro Roque : Fix mtu/length error in ip_forward.
* Alan Cox : Avoid ip_chk_addr when possible.
* Richard Underwood : IP multicasting.
* Alan Cox : Cleaned up multicast handlers.
* Alan Cox : RAW sockets demultiplex in the BSD style.
* Gunther Mayer : Fix the SNMP reporting typo
* Alan Cox : Always in group 224.0.0.1
* Pauline Middelink : Fast ip_checksum update when forwarding
* Masquerading support.
* Alan Cox : Multicast loopback error for 224.0.0.1
* Alan Cox : IP_MULTICAST_LOOP option.
* Alan Cox : Use notifiers.
* Bjorn Ekwall : Removed ip_csum (from slhc.c too)
* Bjorn Ekwall : Moved ip_fast_csum to ip.h (inline!)
* Stefan Becker : Send out ICMP HOST REDIRECT
* Arnt Gulbrandsen : ip_build_xmit
* Alan Cox : Per socket routing cache
* Alan Cox : Fixed routing cache, added header cache.
* Alan Cox : Loopback didn't work right in original ip_build_xmit - fixed it.
* Alan Cox : Only send ICMP_REDIRECT if src/dest are the same net.
* Alan Cox : Incoming IP option handling.
* Alan Cox : Set saddr on raw output frames as per BSD.
* Alan Cox : Stopped broadcast source route explosions.
* Alan Cox : Can disable source routing
* Takeshi Sone : Masquerading didn't work.
* Dave Bonn,Alan Cox : Faster IP forwarding whenever possible.
* Alan Cox : Memory leaks, tramples, misc debugging.
* Alan Cox : Fixed multicast (by popular demand 8))
* Alan Cox : Fixed forwarding (by even more popular demand 8))
* Alan Cox : Fixed SNMP statistics [I think]
* Gerhard Koerting : IP fragmentation forwarding fix
* Alan Cox : Device lock against page fault.
* Alan Cox : IP_HDRINCL facility.
* Werner Almesberger : Zero fragment bug
* Alan Cox : RAW IP frame length bug
* Alan Cox : Outgoing firewall on build_xmit
* A.N.Kuznetsov : IP_OPTIONS support throughout the kernel
* Alan Cox : Multicast routing hooks
* Jos Vos : Do accounting *before* call_in_firewall
* Willy Konynenberg : Transparent proxying support
*
*
*
* To Fix:
* IP fragmentation wants rewriting cleanly. The RFC815 algorithm is much more efficient
* and could be made very efficient with the addition of some virtual memory hacks to permit
* the allocation of a buffer that can then be 'grown' by twiddling page tables.
* Output fragmentation wants updating along with the buffer management to use a single
* interleaved copy algorithm so that fragmenting has a one copy overhead. Actual packet
* output should probably do its own fragmentation at the UDP/RAW layer. TCP shouldn't cause
* fragmentation anyway.
*
* 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 <asm/system.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/net.h>
#include <linux/socket.h>
#include <linux/sockios.h>
#include <linux/in.h>
#include <linux/inet.h>
#include <linux/inetdevice.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <net/snmp.h>
#include <net/ip.h>
#include <net/protocol.h>
#include <net/route.h>
#include <linux/skbuff.h>
#include <net/sock.h>
#include <net/arp.h>
#include <net/icmp.h>
#include <net/raw.h>
#include <net/checksum.h>
#include <linux/netfilter_ipv4.h>
#include <net/xfrm.h>
#include <linux/mroute.h>
#include <linux/netlink.h>
/*
* Process Router Attention IP option
*/
int ip_call_ra_chain(struct sk_buff *skb)
{
struct ip_ra_chain *ra;
u8 protocol = ip_hdr(skb)->protocol;
struct sock *last = NULL;
struct net_device *dev = skb->dev;
read_lock(&ip_ra_lock);
for (ra = ip_ra_chain; ra; ra = ra->next) {
struct sock *sk = ra->sk;
/* If socket is bound to an interface, only report
* the packet if it came from that interface.
*/
if (sk && inet_sk(sk)->num == protocol &&
(!sk->sk_bound_dev_if ||
sk->sk_bound_dev_if == dev->ifindex) &&
sock_net(sk) == dev_net(dev)) {
if (ip_hdr(skb)->frag_off & htons(IP_MF | IP_OFFSET)) {
if (ip_defrag(skb, IP_DEFRAG_CALL_RA_CHAIN)) {
read_unlock(&ip_ra_lock);
return 1;
}
}
if (last) {
struct sk_buff *skb2 = skb_clone(skb, GFP_ATOMIC);
if (skb2)
raw_rcv(last, skb2);
}
last = sk;
}
}
if (last) {
raw_rcv(last, skb);
read_unlock(&ip_ra_lock);
return 1;
}
read_unlock(&ip_ra_lock);
return 0;
}
static int ip_local_deliver_finish(struct sk_buff *skb)
{
struct net *net = dev_net(skb->dev);
__skb_pull(skb, ip_hdrlen(skb));
/* Point into the IP datagram, just past the header. */
skb_reset_transport_header(skb);
rcu_read_lock();
{
int protocol = ip_hdr(skb)->protocol;
int hash, raw;
struct net_protocol *ipprot;
resubmit:
raw = raw_local_deliver(skb, protocol);
hash = protocol & (MAX_INET_PROTOS - 1);
ipprot = rcu_dereference(inet_protos[hash]);
if (ipprot != NULL) {
int ret;
if (!net_eq(net, &init_net) && !ipprot->netns_ok) {
if (net_ratelimit())
printk("%s: proto %d isn't netns-ready\n",
__func__, protocol);
kfree_skb(skb);
goto out;
}
if (!ipprot->no_policy) {
if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb)) {
kfree_skb(skb);
goto out;
}
nf_reset(skb);
}
ret = ipprot->handler(skb);
if (ret < 0) {
protocol = -ret;
goto resubmit;
}
IP_INC_STATS_BH(net, IPSTATS_MIB_INDELIVERS);
} else {
if (!raw) {
if (xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb)) {
IP_INC_STATS_BH(net, IPSTATS_MIB_INUNKNOWNPROTOS);
icmp_send(skb, ICMP_DEST_UNREACH,
ICMP_PROT_UNREACH, 0);
}
} else
IP_INC_STATS_BH(net, IPSTATS_MIB_INDELIVERS);
kfree_skb(skb);
}
}
out:
rcu_read_unlock();
return 0;
}
/*
* Deliver IP Packets to the higher protocol layers.
*/
int ip_local_deliver(struct sk_buff *skb)
{
/*
* Reassemble IP fragments.
*/
if (ip_hdr(skb)->frag_off & htons(IP_MF | IP_OFFSET)) {
if (ip_defrag(skb, IP_DEFRAG_LOCAL_DELIVER))
return 0;
}
return NF_HOOK(PF_INET, NF_INET_LOCAL_IN, skb, skb->dev, NULL,
ip_local_deliver_finish);
}
static inline int ip_rcv_options(struct sk_buff *skb)
{
struct ip_options *opt;
struct iphdr *iph;
struct net_device *dev = skb->dev;
/* It looks as overkill, because not all
IP options require packet mangling.
But it is the easiest for now, especially taking
into account that combination of IP options
and running sniffer is extremely rare condition.
--ANK (980813)
*/
if (skb_cow(skb, skb_headroom(skb))) {
IP_INC_STATS_BH(dev_net(dev), IPSTATS_MIB_INDISCARDS);
goto drop;
}
iph = ip_hdr(skb);
opt = &(IPCB(skb)->opt);
opt->optlen = iph->ihl*4 - sizeof(struct iphdr);
if (ip_options_compile(dev_net(dev), opt, skb)) {
IP_INC_STATS_BH(dev_net(dev), IPSTATS_MIB_INHDRERRORS);
goto drop;
}
if (unlikely(opt->srr)) {
struct in_device *in_dev = in_dev_get(dev);
if (in_dev) {
if (!IN_DEV_SOURCE_ROUTE(in_dev)) {
if (IN_DEV_LOG_MARTIANS(in_dev) &&
net_ratelimit())
printk(KERN_INFO "source route option %pI4 -> %pI4\n",
&iph->saddr, &iph->daddr);
in_dev_put(in_dev);
goto drop;
}
in_dev_put(in_dev);
}
if (ip_options_rcv_srr(skb))
goto drop;
}
return 0;
drop:
return -1;
}
static int ip_rcv_finish(struct sk_buff *skb)
{
const struct iphdr *iph = ip_hdr(skb);
struct rtable *rt;
/*
* Initialise the virtual path cache for the packet. It describes
* how the packet travels inside Linux networking.
*/
if (skb->dst == NULL) {
int err = ip_route_input(skb, iph->daddr, iph->saddr, iph->tos,
skb->dev);
if (unlikely(err)) {
if (err == -EHOSTUNREACH)
IP_INC_STATS_BH(dev_net(skb->dev),
IPSTATS_MIB_INADDRERRORS);
else if (err == -ENETUNREACH)
IP_INC_STATS_BH(dev_net(skb->dev),
IPSTATS_MIB_INNOROUTES);
goto drop;
}
}
#ifdef CONFIG_NET_CLS_ROUTE
if (unlikely(skb->dst->tclassid)) {
struct ip_rt_acct *st = per_cpu_ptr(ip_rt_acct, smp_processor_id());
u32 idx = skb->dst->tclassid;
st[idx&0xFF].o_packets++;
st[idx&0xFF].o_bytes += skb->len;
st[(idx>>16)&0xFF].i_packets++;
st[(idx>>16)&0xFF].i_bytes += skb->len;
}
#endif
if (iph->ihl > 5 && ip_rcv_options(skb))
goto drop;
rt = skb->rtable;
if (rt->rt_type == RTN_MULTICAST)
IP_INC_STATS_BH(dev_net(rt->u.dst.dev), IPSTATS_MIB_INMCASTPKTS);
else if (rt->rt_type == RTN_BROADCAST)
IP_INC_STATS_BH(dev_net(rt->u.dst.dev), IPSTATS_MIB_INBCASTPKTS);
return dst_input(skb);
drop:
kfree_skb(skb);
return NET_RX_DROP;
}
/*
* Main IP Receive routine.
*/
int ip_rcv(struct sk_buff *skb, struct net_device *dev, struct packet_type *pt, struct net_device *orig_dev)
{
struct iphdr *iph;
u32 len;
/* When the interface is in promisc. mode, drop all the crap
* that it receives, do not try to analyse it.
*/
if (skb->pkt_type == PACKET_OTHERHOST)
goto drop;
IP_INC_STATS_BH(dev_net(dev), IPSTATS_MIB_INRECEIVES);
if ((skb = skb_share_check(skb, GFP_ATOMIC)) == NULL) {
IP_INC_STATS_BH(dev_net(dev), IPSTATS_MIB_INDISCARDS);
goto out;
}
if (!pskb_may_pull(skb, sizeof(struct iphdr)))
goto inhdr_error;
iph = ip_hdr(skb);
/*
* RFC1122: 3.2.1.2 MUST silently discard any IP frame that fails the checksum.
*
* Is the datagram acceptable?
*
* 1. Length at least the size of an ip header
* 2. Version of 4
* 3. Checksums correctly. [Speed optimisation for later, skip loopback checksums]
* 4. Doesn't have a bogus length
*/
if (iph->ihl < 5 || iph->version != 4)
goto inhdr_error;
if (!pskb_may_pull(skb, iph->ihl*4))
goto inhdr_error;
iph = ip_hdr(skb);
if (unlikely(ip_fast_csum((u8 *)iph, iph->ihl)))
goto inhdr_error;
len = ntohs(iph->tot_len);
if (skb->len < len) {
IP_INC_STATS_BH(dev_net(dev), IPSTATS_MIB_INTRUNCATEDPKTS);
goto drop;
} else if (len < (iph->ihl*4))
goto inhdr_error;
/* Our transport medium may have padded the buffer out. Now we know it
* is IP we can trim to the true length of the frame.
* Note this now means skb->len holds ntohs(iph->tot_len).
*/
if (pskb_trim_rcsum(skb, len)) {
IP_INC_STATS_BH(dev_net(dev), IPSTATS_MIB_INDISCARDS);
goto drop;
}
/* Remove any debris in the socket control block */
memset(IPCB(skb), 0, sizeof(struct inet_skb_parm));
return NF_HOOK(PF_INET, NF_INET_PRE_ROUTING, skb, dev, NULL,
ip_rcv_finish);
inhdr_error:
IP_INC_STATS_BH(dev_net(dev), IPSTATS_MIB_INHDRERRORS);
drop:
kfree_skb(skb);
out:
return NET_RX_DROP;
}
| gpl-2.0 |
djvoleur/S6-UniKernel_v4 | drivers/hwmon/f71882fg.c | 2214 | 84646 | /***************************************************************************
* Copyright (C) 2006 by Hans Edgington <hans@edgington.nl> *
* Copyright (C) 2007-2011 Hans de Goede <hdegoede@redhat.com> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
#include <linux/platform_device.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/err.h>
#include <linux/mutex.h>
#include <linux/io.h>
#include <linux/acpi.h>
#define DRVNAME "f71882fg"
#define SIO_F71858FG_LD_HWM 0x02 /* Hardware monitor logical device */
#define SIO_F71882FG_LD_HWM 0x04 /* Hardware monitor logical device */
#define SIO_UNLOCK_KEY 0x87 /* Key to enable Super-I/O */
#define SIO_LOCK_KEY 0xAA /* Key to disable Super-I/O */
#define SIO_REG_LDSEL 0x07 /* Logical device select */
#define SIO_REG_DEVID 0x20 /* Device ID (2 bytes) */
#define SIO_REG_DEVREV 0x22 /* Device revision */
#define SIO_REG_MANID 0x23 /* Fintek ID (2 bytes) */
#define SIO_REG_ENABLE 0x30 /* Logical device enable */
#define SIO_REG_ADDR 0x60 /* Logical device address (2 bytes) */
#define SIO_FINTEK_ID 0x1934 /* Manufacturers ID */
#define SIO_F71808E_ID 0x0901 /* Chipset ID */
#define SIO_F71808A_ID 0x1001 /* Chipset ID */
#define SIO_F71858_ID 0x0507 /* Chipset ID */
#define SIO_F71862_ID 0x0601 /* Chipset ID */
#define SIO_F71869_ID 0x0814 /* Chipset ID */
#define SIO_F71869A_ID 0x1007 /* Chipset ID */
#define SIO_F71882_ID 0x0541 /* Chipset ID */
#define SIO_F71889_ID 0x0723 /* Chipset ID */
#define SIO_F71889E_ID 0x0909 /* Chipset ID */
#define SIO_F71889A_ID 0x1005 /* Chipset ID */
#define SIO_F8000_ID 0x0581 /* Chipset ID */
#define SIO_F81865_ID 0x0704 /* Chipset ID */
#define REGION_LENGTH 8
#define ADDR_REG_OFFSET 5
#define DATA_REG_OFFSET 6
#define F71882FG_REG_IN_STATUS 0x12 /* f7188x only */
#define F71882FG_REG_IN_BEEP 0x13 /* f7188x only */
#define F71882FG_REG_IN(nr) (0x20 + (nr))
#define F71882FG_REG_IN1_HIGH 0x32 /* f7188x only */
#define F71882FG_REG_FAN(nr) (0xA0 + (16 * (nr)))
#define F71882FG_REG_FAN_TARGET(nr) (0xA2 + (16 * (nr)))
#define F71882FG_REG_FAN_FULL_SPEED(nr) (0xA4 + (16 * (nr)))
#define F71882FG_REG_FAN_STATUS 0x92
#define F71882FG_REG_FAN_BEEP 0x93
#define F71882FG_REG_TEMP(nr) (0x70 + 2 * (nr))
#define F71882FG_REG_TEMP_OVT(nr) (0x80 + 2 * (nr))
#define F71882FG_REG_TEMP_HIGH(nr) (0x81 + 2 * (nr))
#define F71882FG_REG_TEMP_STATUS 0x62
#define F71882FG_REG_TEMP_BEEP 0x63
#define F71882FG_REG_TEMP_CONFIG 0x69
#define F71882FG_REG_TEMP_HYST(nr) (0x6C + (nr))
#define F71882FG_REG_TEMP_TYPE 0x6B
#define F71882FG_REG_TEMP_DIODE_OPEN 0x6F
#define F71882FG_REG_PWM(nr) (0xA3 + (16 * (nr)))
#define F71882FG_REG_PWM_TYPE 0x94
#define F71882FG_REG_PWM_ENABLE 0x96
#define F71882FG_REG_FAN_HYST(nr) (0x98 + (nr))
#define F71882FG_REG_FAN_FAULT_T 0x9F
#define F71882FG_FAN_NEG_TEMP_EN 0x20
#define F71882FG_FAN_PROG_SEL 0x80
#define F71882FG_REG_POINT_PWM(pwm, point) (0xAA + (point) + (16 * (pwm)))
#define F71882FG_REG_POINT_TEMP(pwm, point) (0xA6 + (point) + (16 * (pwm)))
#define F71882FG_REG_POINT_MAPPING(nr) (0xAF + 16 * (nr))
#define F71882FG_REG_START 0x01
#define F71882FG_MAX_INS 9
#define FAN_MIN_DETECT 366 /* Lowest detectable fanspeed */
static unsigned short force_id;
module_param(force_id, ushort, 0);
MODULE_PARM_DESC(force_id, "Override the detected device ID");
enum chips { f71808e, f71808a, f71858fg, f71862fg, f71869, f71869a, f71882fg,
f71889fg, f71889ed, f71889a, f8000, f81865f };
static const char *const f71882fg_names[] = {
"f71808e",
"f71808a",
"f71858fg",
"f71862fg",
"f71869", /* Both f71869f and f71869e, reg. compatible and same id */
"f71869a",
"f71882fg",
"f71889fg", /* f81801u too, same id */
"f71889ed",
"f71889a",
"f8000",
"f81865f",
};
static const char f71882fg_has_in[][F71882FG_MAX_INS] = {
[f71808e] = { 1, 1, 1, 1, 1, 1, 0, 1, 1 },
[f71808a] = { 1, 1, 1, 1, 0, 0, 0, 1, 1 },
[f71858fg] = { 1, 1, 1, 0, 0, 0, 0, 0, 0 },
[f71862fg] = { 1, 1, 1, 1, 1, 1, 1, 1, 1 },
[f71869] = { 1, 1, 1, 1, 1, 1, 1, 1, 1 },
[f71869a] = { 1, 1, 1, 1, 1, 1, 1, 1, 1 },
[f71882fg] = { 1, 1, 1, 1, 1, 1, 1, 1, 1 },
[f71889fg] = { 1, 1, 1, 1, 1, 1, 1, 1, 1 },
[f71889ed] = { 1, 1, 1, 1, 1, 1, 1, 1, 1 },
[f71889a] = { 1, 1, 1, 1, 1, 1, 1, 1, 1 },
[f8000] = { 1, 1, 1, 0, 0, 0, 0, 0, 0 },
[f81865f] = { 1, 1, 1, 1, 1, 1, 1, 0, 0 },
};
static const char f71882fg_has_in1_alarm[] = {
[f71808e] = 0,
[f71808a] = 0,
[f71858fg] = 0,
[f71862fg] = 0,
[f71869] = 0,
[f71869a] = 0,
[f71882fg] = 1,
[f71889fg] = 1,
[f71889ed] = 1,
[f71889a] = 1,
[f8000] = 0,
[f81865f] = 1,
};
static const char f71882fg_fan_has_beep[] = {
[f71808e] = 0,
[f71808a] = 0,
[f71858fg] = 0,
[f71862fg] = 1,
[f71869] = 1,
[f71869a] = 1,
[f71882fg] = 1,
[f71889fg] = 1,
[f71889ed] = 1,
[f71889a] = 1,
[f8000] = 0,
[f81865f] = 1,
};
static const char f71882fg_nr_fans[] = {
[f71808e] = 3,
[f71808a] = 2, /* +1 fan which is monitor + simple pwm only */
[f71858fg] = 3,
[f71862fg] = 3,
[f71869] = 3,
[f71869a] = 3,
[f71882fg] = 4,
[f71889fg] = 3,
[f71889ed] = 3,
[f71889a] = 3,
[f8000] = 3, /* +1 fan which is monitor only */
[f81865f] = 2,
};
static const char f71882fg_temp_has_beep[] = {
[f71808e] = 0,
[f71808a] = 1,
[f71858fg] = 0,
[f71862fg] = 1,
[f71869] = 1,
[f71869a] = 1,
[f71882fg] = 1,
[f71889fg] = 1,
[f71889ed] = 1,
[f71889a] = 1,
[f8000] = 0,
[f81865f] = 1,
};
static const char f71882fg_nr_temps[] = {
[f71808e] = 2,
[f71808a] = 2,
[f71858fg] = 3,
[f71862fg] = 3,
[f71869] = 3,
[f71869a] = 3,
[f71882fg] = 3,
[f71889fg] = 3,
[f71889ed] = 3,
[f71889a] = 3,
[f8000] = 3,
[f81865f] = 2,
};
static struct platform_device *f71882fg_pdev;
/* Super-I/O Function prototypes */
static inline int superio_inb(int base, int reg);
static inline int superio_inw(int base, int reg);
static inline int superio_enter(int base);
static inline void superio_select(int base, int ld);
static inline void superio_exit(int base);
struct f71882fg_sio_data {
enum chips type;
};
struct f71882fg_data {
unsigned short addr;
enum chips type;
struct device *hwmon_dev;
struct mutex update_lock;
int temp_start; /* temp numbering start (0 or 1) */
char valid; /* !=0 if following fields are valid */
char auto_point_temp_signed;
unsigned long last_updated; /* In jiffies */
unsigned long last_limits; /* In jiffies */
/* Register Values */
u8 in[F71882FG_MAX_INS];
u8 in1_max;
u8 in_status;
u8 in_beep;
u16 fan[4];
u16 fan_target[4];
u16 fan_full_speed[4];
u8 fan_status;
u8 fan_beep;
/*
* Note: all models have max 3 temperature channels, but on some
* they are addressed as 0-2 and on others as 1-3, so for coding
* convenience we reserve space for 4 channels
*/
u16 temp[4];
u8 temp_ovt[4];
u8 temp_high[4];
u8 temp_hyst[2]; /* 2 hysts stored per reg */
u8 temp_type[4];
u8 temp_status;
u8 temp_beep;
u8 temp_diode_open;
u8 temp_config;
u8 pwm[4];
u8 pwm_enable;
u8 pwm_auto_point_hyst[2];
u8 pwm_auto_point_mapping[4];
u8 pwm_auto_point_pwm[4][5];
s8 pwm_auto_point_temp[4][4];
};
/* Sysfs in */
static ssize_t show_in(struct device *dev, struct device_attribute *devattr,
char *buf);
static ssize_t show_in_max(struct device *dev, struct device_attribute
*devattr, char *buf);
static ssize_t store_in_max(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count);
static ssize_t show_in_beep(struct device *dev, struct device_attribute
*devattr, char *buf);
static ssize_t store_in_beep(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count);
static ssize_t show_in_alarm(struct device *dev, struct device_attribute
*devattr, char *buf);
/* Sysfs Fan */
static ssize_t show_fan(struct device *dev, struct device_attribute *devattr,
char *buf);
static ssize_t show_fan_full_speed(struct device *dev,
struct device_attribute *devattr, char *buf);
static ssize_t store_fan_full_speed(struct device *dev,
struct device_attribute *devattr, const char *buf, size_t count);
static ssize_t show_fan_beep(struct device *dev, struct device_attribute
*devattr, char *buf);
static ssize_t store_fan_beep(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count);
static ssize_t show_fan_alarm(struct device *dev, struct device_attribute
*devattr, char *buf);
/* Sysfs Temp */
static ssize_t show_temp(struct device *dev, struct device_attribute
*devattr, char *buf);
static ssize_t show_temp_max(struct device *dev, struct device_attribute
*devattr, char *buf);
static ssize_t store_temp_max(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count);
static ssize_t show_temp_max_hyst(struct device *dev, struct device_attribute
*devattr, char *buf);
static ssize_t store_temp_max_hyst(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count);
static ssize_t show_temp_crit(struct device *dev, struct device_attribute
*devattr, char *buf);
static ssize_t store_temp_crit(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count);
static ssize_t show_temp_crit_hyst(struct device *dev, struct device_attribute
*devattr, char *buf);
static ssize_t show_temp_type(struct device *dev, struct device_attribute
*devattr, char *buf);
static ssize_t show_temp_beep(struct device *dev, struct device_attribute
*devattr, char *buf);
static ssize_t store_temp_beep(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count);
static ssize_t show_temp_alarm(struct device *dev, struct device_attribute
*devattr, char *buf);
static ssize_t show_temp_fault(struct device *dev, struct device_attribute
*devattr, char *buf);
/* PWM and Auto point control */
static ssize_t show_pwm(struct device *dev, struct device_attribute *devattr,
char *buf);
static ssize_t store_pwm(struct device *dev, struct device_attribute *devattr,
const char *buf, size_t count);
static ssize_t show_simple_pwm(struct device *dev,
struct device_attribute *devattr, char *buf);
static ssize_t store_simple_pwm(struct device *dev,
struct device_attribute *devattr, const char *buf, size_t count);
static ssize_t show_pwm_enable(struct device *dev,
struct device_attribute *devattr, char *buf);
static ssize_t store_pwm_enable(struct device *dev,
struct device_attribute *devattr, const char *buf, size_t count);
static ssize_t show_pwm_interpolate(struct device *dev,
struct device_attribute *devattr, char *buf);
static ssize_t store_pwm_interpolate(struct device *dev,
struct device_attribute *devattr, const char *buf, size_t count);
static ssize_t show_pwm_auto_point_channel(struct device *dev,
struct device_attribute *devattr, char *buf);
static ssize_t store_pwm_auto_point_channel(struct device *dev,
struct device_attribute *devattr, const char *buf, size_t count);
static ssize_t show_pwm_auto_point_temp_hyst(struct device *dev,
struct device_attribute *devattr, char *buf);
static ssize_t store_pwm_auto_point_temp_hyst(struct device *dev,
struct device_attribute *devattr, const char *buf, size_t count);
static ssize_t show_pwm_auto_point_pwm(struct device *dev,
struct device_attribute *devattr, char *buf);
static ssize_t store_pwm_auto_point_pwm(struct device *dev,
struct device_attribute *devattr, const char *buf, size_t count);
static ssize_t show_pwm_auto_point_temp(struct device *dev,
struct device_attribute *devattr, char *buf);
static ssize_t store_pwm_auto_point_temp(struct device *dev,
struct device_attribute *devattr, const char *buf, size_t count);
/* Sysfs misc */
static ssize_t show_name(struct device *dev, struct device_attribute *devattr,
char *buf);
static int f71882fg_probe(struct platform_device *pdev);
static int f71882fg_remove(struct platform_device *pdev);
static struct platform_driver f71882fg_driver = {
.driver = {
.owner = THIS_MODULE,
.name = DRVNAME,
},
.probe = f71882fg_probe,
.remove = f71882fg_remove,
};
static DEVICE_ATTR(name, S_IRUGO, show_name, NULL);
/*
* Temp attr for the f71858fg, the f71858fg is special as it has its
* temperature indexes start at 0 (the others start at 1)
*/
static struct sensor_device_attribute_2 f71858fg_temp_attr[] = {
SENSOR_ATTR_2(temp1_input, S_IRUGO, show_temp, NULL, 0, 0),
SENSOR_ATTR_2(temp1_max, S_IRUGO|S_IWUSR, show_temp_max,
store_temp_max, 0, 0),
SENSOR_ATTR_2(temp1_max_hyst, S_IRUGO|S_IWUSR, show_temp_max_hyst,
store_temp_max_hyst, 0, 0),
SENSOR_ATTR_2(temp1_max_alarm, S_IRUGO, show_temp_alarm, NULL, 0, 0),
SENSOR_ATTR_2(temp1_crit, S_IRUGO|S_IWUSR, show_temp_crit,
store_temp_crit, 0, 0),
SENSOR_ATTR_2(temp1_crit_hyst, S_IRUGO, show_temp_crit_hyst, NULL,
0, 0),
SENSOR_ATTR_2(temp1_crit_alarm, S_IRUGO, show_temp_alarm, NULL, 0, 4),
SENSOR_ATTR_2(temp1_fault, S_IRUGO, show_temp_fault, NULL, 0, 0),
SENSOR_ATTR_2(temp2_input, S_IRUGO, show_temp, NULL, 0, 1),
SENSOR_ATTR_2(temp2_max, S_IRUGO|S_IWUSR, show_temp_max,
store_temp_max, 0, 1),
SENSOR_ATTR_2(temp2_max_hyst, S_IRUGO|S_IWUSR, show_temp_max_hyst,
store_temp_max_hyst, 0, 1),
SENSOR_ATTR_2(temp2_max_alarm, S_IRUGO, show_temp_alarm, NULL, 0, 1),
SENSOR_ATTR_2(temp2_crit, S_IRUGO|S_IWUSR, show_temp_crit,
store_temp_crit, 0, 1),
SENSOR_ATTR_2(temp2_crit_hyst, S_IRUGO, show_temp_crit_hyst, NULL,
0, 1),
SENSOR_ATTR_2(temp2_crit_alarm, S_IRUGO, show_temp_alarm, NULL, 0, 5),
SENSOR_ATTR_2(temp2_fault, S_IRUGO, show_temp_fault, NULL, 0, 1),
SENSOR_ATTR_2(temp3_input, S_IRUGO, show_temp, NULL, 0, 2),
SENSOR_ATTR_2(temp3_max, S_IRUGO|S_IWUSR, show_temp_max,
store_temp_max, 0, 2),
SENSOR_ATTR_2(temp3_max_hyst, S_IRUGO|S_IWUSR, show_temp_max_hyst,
store_temp_max_hyst, 0, 2),
SENSOR_ATTR_2(temp3_max_alarm, S_IRUGO, show_temp_alarm, NULL, 0, 2),
SENSOR_ATTR_2(temp3_crit, S_IRUGO|S_IWUSR, show_temp_crit,
store_temp_crit, 0, 2),
SENSOR_ATTR_2(temp3_crit_hyst, S_IRUGO, show_temp_crit_hyst, NULL,
0, 2),
SENSOR_ATTR_2(temp3_crit_alarm, S_IRUGO, show_temp_alarm, NULL, 0, 6),
SENSOR_ATTR_2(temp3_fault, S_IRUGO, show_temp_fault, NULL, 0, 2),
};
/* Temp attr for the standard models */
static struct sensor_device_attribute_2 fxxxx_temp_attr[3][9] = { {
SENSOR_ATTR_2(temp1_input, S_IRUGO, show_temp, NULL, 0, 1),
SENSOR_ATTR_2(temp1_max, S_IRUGO|S_IWUSR, show_temp_max,
store_temp_max, 0, 1),
SENSOR_ATTR_2(temp1_max_hyst, S_IRUGO|S_IWUSR, show_temp_max_hyst,
store_temp_max_hyst, 0, 1),
/*
* Should really be temp1_max_alarm, but older versions did not handle
* the max and crit alarms separately and lm_sensors v2 depends on the
* presence of temp#_alarm files. The same goes for temp2/3 _alarm.
*/
SENSOR_ATTR_2(temp1_alarm, S_IRUGO, show_temp_alarm, NULL, 0, 1),
SENSOR_ATTR_2(temp1_crit, S_IRUGO|S_IWUSR, show_temp_crit,
store_temp_crit, 0, 1),
SENSOR_ATTR_2(temp1_crit_hyst, S_IRUGO, show_temp_crit_hyst, NULL,
0, 1),
SENSOR_ATTR_2(temp1_crit_alarm, S_IRUGO, show_temp_alarm, NULL, 0, 5),
SENSOR_ATTR_2(temp1_type, S_IRUGO, show_temp_type, NULL, 0, 1),
SENSOR_ATTR_2(temp1_fault, S_IRUGO, show_temp_fault, NULL, 0, 1),
}, {
SENSOR_ATTR_2(temp2_input, S_IRUGO, show_temp, NULL, 0, 2),
SENSOR_ATTR_2(temp2_max, S_IRUGO|S_IWUSR, show_temp_max,
store_temp_max, 0, 2),
SENSOR_ATTR_2(temp2_max_hyst, S_IRUGO|S_IWUSR, show_temp_max_hyst,
store_temp_max_hyst, 0, 2),
/* Should be temp2_max_alarm, see temp1_alarm note */
SENSOR_ATTR_2(temp2_alarm, S_IRUGO, show_temp_alarm, NULL, 0, 2),
SENSOR_ATTR_2(temp2_crit, S_IRUGO|S_IWUSR, show_temp_crit,
store_temp_crit, 0, 2),
SENSOR_ATTR_2(temp2_crit_hyst, S_IRUGO, show_temp_crit_hyst, NULL,
0, 2),
SENSOR_ATTR_2(temp2_crit_alarm, S_IRUGO, show_temp_alarm, NULL, 0, 6),
SENSOR_ATTR_2(temp2_type, S_IRUGO, show_temp_type, NULL, 0, 2),
SENSOR_ATTR_2(temp2_fault, S_IRUGO, show_temp_fault, NULL, 0, 2),
}, {
SENSOR_ATTR_2(temp3_input, S_IRUGO, show_temp, NULL, 0, 3),
SENSOR_ATTR_2(temp3_max, S_IRUGO|S_IWUSR, show_temp_max,
store_temp_max, 0, 3),
SENSOR_ATTR_2(temp3_max_hyst, S_IRUGO|S_IWUSR, show_temp_max_hyst,
store_temp_max_hyst, 0, 3),
/* Should be temp3_max_alarm, see temp1_alarm note */
SENSOR_ATTR_2(temp3_alarm, S_IRUGO, show_temp_alarm, NULL, 0, 3),
SENSOR_ATTR_2(temp3_crit, S_IRUGO|S_IWUSR, show_temp_crit,
store_temp_crit, 0, 3),
SENSOR_ATTR_2(temp3_crit_hyst, S_IRUGO, show_temp_crit_hyst, NULL,
0, 3),
SENSOR_ATTR_2(temp3_crit_alarm, S_IRUGO, show_temp_alarm, NULL, 0, 7),
SENSOR_ATTR_2(temp3_type, S_IRUGO, show_temp_type, NULL, 0, 3),
SENSOR_ATTR_2(temp3_fault, S_IRUGO, show_temp_fault, NULL, 0, 3),
} };
/* Temp attr for models which can beep on temp alarm */
static struct sensor_device_attribute_2 fxxxx_temp_beep_attr[3][2] = { {
SENSOR_ATTR_2(temp1_max_beep, S_IRUGO|S_IWUSR, show_temp_beep,
store_temp_beep, 0, 1),
SENSOR_ATTR_2(temp1_crit_beep, S_IRUGO|S_IWUSR, show_temp_beep,
store_temp_beep, 0, 5),
}, {
SENSOR_ATTR_2(temp2_max_beep, S_IRUGO|S_IWUSR, show_temp_beep,
store_temp_beep, 0, 2),
SENSOR_ATTR_2(temp2_crit_beep, S_IRUGO|S_IWUSR, show_temp_beep,
store_temp_beep, 0, 6),
}, {
SENSOR_ATTR_2(temp3_max_beep, S_IRUGO|S_IWUSR, show_temp_beep,
store_temp_beep, 0, 3),
SENSOR_ATTR_2(temp3_crit_beep, S_IRUGO|S_IWUSR, show_temp_beep,
store_temp_beep, 0, 7),
} };
/*
* Temp attr for the f8000
* Note on the f8000 temp_ovt (crit) is used as max, and temp_high (max)
* is used as hysteresis value to clear alarms
* Also like the f71858fg its temperature indexes start at 0
*/
static struct sensor_device_attribute_2 f8000_temp_attr[] = {
SENSOR_ATTR_2(temp1_input, S_IRUGO, show_temp, NULL, 0, 0),
SENSOR_ATTR_2(temp1_max, S_IRUGO|S_IWUSR, show_temp_crit,
store_temp_crit, 0, 0),
SENSOR_ATTR_2(temp1_max_hyst, S_IRUGO|S_IWUSR, show_temp_max,
store_temp_max, 0, 0),
SENSOR_ATTR_2(temp1_alarm, S_IRUGO, show_temp_alarm, NULL, 0, 4),
SENSOR_ATTR_2(temp1_fault, S_IRUGO, show_temp_fault, NULL, 0, 0),
SENSOR_ATTR_2(temp2_input, S_IRUGO, show_temp, NULL, 0, 1),
SENSOR_ATTR_2(temp2_max, S_IRUGO|S_IWUSR, show_temp_crit,
store_temp_crit, 0, 1),
SENSOR_ATTR_2(temp2_max_hyst, S_IRUGO|S_IWUSR, show_temp_max,
store_temp_max, 0, 1),
SENSOR_ATTR_2(temp2_alarm, S_IRUGO, show_temp_alarm, NULL, 0, 5),
SENSOR_ATTR_2(temp2_fault, S_IRUGO, show_temp_fault, NULL, 0, 1),
SENSOR_ATTR_2(temp3_input, S_IRUGO, show_temp, NULL, 0, 2),
SENSOR_ATTR_2(temp3_max, S_IRUGO|S_IWUSR, show_temp_crit,
store_temp_crit, 0, 2),
SENSOR_ATTR_2(temp3_max_hyst, S_IRUGO|S_IWUSR, show_temp_max,
store_temp_max, 0, 2),
SENSOR_ATTR_2(temp3_alarm, S_IRUGO, show_temp_alarm, NULL, 0, 6),
SENSOR_ATTR_2(temp3_fault, S_IRUGO, show_temp_fault, NULL, 0, 2),
};
/* in attr for all models */
static struct sensor_device_attribute_2 fxxxx_in_attr[] = {
SENSOR_ATTR_2(in0_input, S_IRUGO, show_in, NULL, 0, 0),
SENSOR_ATTR_2(in1_input, S_IRUGO, show_in, NULL, 0, 1),
SENSOR_ATTR_2(in2_input, S_IRUGO, show_in, NULL, 0, 2),
SENSOR_ATTR_2(in3_input, S_IRUGO, show_in, NULL, 0, 3),
SENSOR_ATTR_2(in4_input, S_IRUGO, show_in, NULL, 0, 4),
SENSOR_ATTR_2(in5_input, S_IRUGO, show_in, NULL, 0, 5),
SENSOR_ATTR_2(in6_input, S_IRUGO, show_in, NULL, 0, 6),
SENSOR_ATTR_2(in7_input, S_IRUGO, show_in, NULL, 0, 7),
SENSOR_ATTR_2(in8_input, S_IRUGO, show_in, NULL, 0, 8),
};
/* For models with in1 alarm capability */
static struct sensor_device_attribute_2 fxxxx_in1_alarm_attr[] = {
SENSOR_ATTR_2(in1_max, S_IRUGO|S_IWUSR, show_in_max, store_in_max,
0, 1),
SENSOR_ATTR_2(in1_beep, S_IRUGO|S_IWUSR, show_in_beep, store_in_beep,
0, 1),
SENSOR_ATTR_2(in1_alarm, S_IRUGO, show_in_alarm, NULL, 0, 1),
};
/* Fan / PWM attr common to all models */
static struct sensor_device_attribute_2 fxxxx_fan_attr[4][6] = { {
SENSOR_ATTR_2(fan1_input, S_IRUGO, show_fan, NULL, 0, 0),
SENSOR_ATTR_2(fan1_full_speed, S_IRUGO|S_IWUSR,
show_fan_full_speed,
store_fan_full_speed, 0, 0),
SENSOR_ATTR_2(fan1_alarm, S_IRUGO, show_fan_alarm, NULL, 0, 0),
SENSOR_ATTR_2(pwm1, S_IRUGO|S_IWUSR, show_pwm, store_pwm, 0, 0),
SENSOR_ATTR_2(pwm1_enable, S_IRUGO|S_IWUSR, show_pwm_enable,
store_pwm_enable, 0, 0),
SENSOR_ATTR_2(pwm1_interpolate, S_IRUGO|S_IWUSR,
show_pwm_interpolate, store_pwm_interpolate, 0, 0),
}, {
SENSOR_ATTR_2(fan2_input, S_IRUGO, show_fan, NULL, 0, 1),
SENSOR_ATTR_2(fan2_full_speed, S_IRUGO|S_IWUSR,
show_fan_full_speed,
store_fan_full_speed, 0, 1),
SENSOR_ATTR_2(fan2_alarm, S_IRUGO, show_fan_alarm, NULL, 0, 1),
SENSOR_ATTR_2(pwm2, S_IRUGO|S_IWUSR, show_pwm, store_pwm, 0, 1),
SENSOR_ATTR_2(pwm2_enable, S_IRUGO|S_IWUSR, show_pwm_enable,
store_pwm_enable, 0, 1),
SENSOR_ATTR_2(pwm2_interpolate, S_IRUGO|S_IWUSR,
show_pwm_interpolate, store_pwm_interpolate, 0, 1),
}, {
SENSOR_ATTR_2(fan3_input, S_IRUGO, show_fan, NULL, 0, 2),
SENSOR_ATTR_2(fan3_full_speed, S_IRUGO|S_IWUSR,
show_fan_full_speed,
store_fan_full_speed, 0, 2),
SENSOR_ATTR_2(fan3_alarm, S_IRUGO, show_fan_alarm, NULL, 0, 2),
SENSOR_ATTR_2(pwm3, S_IRUGO|S_IWUSR, show_pwm, store_pwm, 0, 2),
SENSOR_ATTR_2(pwm3_enable, S_IRUGO|S_IWUSR, show_pwm_enable,
store_pwm_enable, 0, 2),
SENSOR_ATTR_2(pwm3_interpolate, S_IRUGO|S_IWUSR,
show_pwm_interpolate, store_pwm_interpolate, 0, 2),
}, {
SENSOR_ATTR_2(fan4_input, S_IRUGO, show_fan, NULL, 0, 3),
SENSOR_ATTR_2(fan4_full_speed, S_IRUGO|S_IWUSR,
show_fan_full_speed,
store_fan_full_speed, 0, 3),
SENSOR_ATTR_2(fan4_alarm, S_IRUGO, show_fan_alarm, NULL, 0, 3),
SENSOR_ATTR_2(pwm4, S_IRUGO|S_IWUSR, show_pwm, store_pwm, 0, 3),
SENSOR_ATTR_2(pwm4_enable, S_IRUGO|S_IWUSR, show_pwm_enable,
store_pwm_enable, 0, 3),
SENSOR_ATTR_2(pwm4_interpolate, S_IRUGO|S_IWUSR,
show_pwm_interpolate, store_pwm_interpolate, 0, 3),
} };
/* Attr for the third fan of the f71808a, which only has manual pwm */
static struct sensor_device_attribute_2 f71808a_fan3_attr[] = {
SENSOR_ATTR_2(fan3_input, S_IRUGO, show_fan, NULL, 0, 2),
SENSOR_ATTR_2(fan3_alarm, S_IRUGO, show_fan_alarm, NULL, 0, 2),
SENSOR_ATTR_2(pwm3, S_IRUGO|S_IWUSR,
show_simple_pwm, store_simple_pwm, 0, 2),
};
/* Attr for models which can beep on Fan alarm */
static struct sensor_device_attribute_2 fxxxx_fan_beep_attr[] = {
SENSOR_ATTR_2(fan1_beep, S_IRUGO|S_IWUSR, show_fan_beep,
store_fan_beep, 0, 0),
SENSOR_ATTR_2(fan2_beep, S_IRUGO|S_IWUSR, show_fan_beep,
store_fan_beep, 0, 1),
SENSOR_ATTR_2(fan3_beep, S_IRUGO|S_IWUSR, show_fan_beep,
store_fan_beep, 0, 2),
SENSOR_ATTR_2(fan4_beep, S_IRUGO|S_IWUSR, show_fan_beep,
store_fan_beep, 0, 3),
};
/*
* PWM attr for the f71862fg, fewer pwms and fewer zones per pwm than the
* standard models
*/
static struct sensor_device_attribute_2 f71862fg_auto_pwm_attr[3][7] = { {
SENSOR_ATTR_2(pwm1_auto_channels_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_channel,
store_pwm_auto_point_channel, 0, 0),
SENSOR_ATTR_2(pwm1_auto_point1_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
1, 0),
SENSOR_ATTR_2(pwm1_auto_point2_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
4, 0),
SENSOR_ATTR_2(pwm1_auto_point1_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
0, 0),
SENSOR_ATTR_2(pwm1_auto_point2_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
3, 0),
SENSOR_ATTR_2(pwm1_auto_point1_temp_hyst, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp_hyst,
store_pwm_auto_point_temp_hyst,
0, 0),
SENSOR_ATTR_2(pwm1_auto_point2_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 3, 0),
}, {
SENSOR_ATTR_2(pwm2_auto_channels_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_channel,
store_pwm_auto_point_channel, 0, 1),
SENSOR_ATTR_2(pwm2_auto_point1_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
1, 1),
SENSOR_ATTR_2(pwm2_auto_point2_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
4, 1),
SENSOR_ATTR_2(pwm2_auto_point1_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
0, 1),
SENSOR_ATTR_2(pwm2_auto_point2_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
3, 1),
SENSOR_ATTR_2(pwm2_auto_point1_temp_hyst, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp_hyst,
store_pwm_auto_point_temp_hyst,
0, 1),
SENSOR_ATTR_2(pwm2_auto_point2_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 3, 1),
}, {
SENSOR_ATTR_2(pwm3_auto_channels_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_channel,
store_pwm_auto_point_channel, 0, 2),
SENSOR_ATTR_2(pwm3_auto_point1_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
1, 2),
SENSOR_ATTR_2(pwm3_auto_point2_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
4, 2),
SENSOR_ATTR_2(pwm3_auto_point1_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
0, 2),
SENSOR_ATTR_2(pwm3_auto_point2_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
3, 2),
SENSOR_ATTR_2(pwm3_auto_point1_temp_hyst, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp_hyst,
store_pwm_auto_point_temp_hyst,
0, 2),
SENSOR_ATTR_2(pwm3_auto_point2_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 3, 2),
} };
/*
* PWM attr for the f71808e/f71869, almost identical to the f71862fg, but the
* pwm setting when the temperature is above the pwmX_auto_point1_temp can be
* programmed instead of being hardcoded to 0xff
*/
static struct sensor_device_attribute_2 f71869_auto_pwm_attr[3][8] = { {
SENSOR_ATTR_2(pwm1_auto_channels_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_channel,
store_pwm_auto_point_channel, 0, 0),
SENSOR_ATTR_2(pwm1_auto_point1_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
0, 0),
SENSOR_ATTR_2(pwm1_auto_point2_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
1, 0),
SENSOR_ATTR_2(pwm1_auto_point3_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
4, 0),
SENSOR_ATTR_2(pwm1_auto_point1_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
0, 0),
SENSOR_ATTR_2(pwm1_auto_point2_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
3, 0),
SENSOR_ATTR_2(pwm1_auto_point1_temp_hyst, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp_hyst,
store_pwm_auto_point_temp_hyst,
0, 0),
SENSOR_ATTR_2(pwm1_auto_point2_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 3, 0),
}, {
SENSOR_ATTR_2(pwm2_auto_channels_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_channel,
store_pwm_auto_point_channel, 0, 1),
SENSOR_ATTR_2(pwm2_auto_point1_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
0, 1),
SENSOR_ATTR_2(pwm2_auto_point2_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
1, 1),
SENSOR_ATTR_2(pwm2_auto_point3_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
4, 1),
SENSOR_ATTR_2(pwm2_auto_point1_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
0, 1),
SENSOR_ATTR_2(pwm2_auto_point2_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
3, 1),
SENSOR_ATTR_2(pwm2_auto_point1_temp_hyst, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp_hyst,
store_pwm_auto_point_temp_hyst,
0, 1),
SENSOR_ATTR_2(pwm2_auto_point2_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 3, 1),
}, {
SENSOR_ATTR_2(pwm3_auto_channels_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_channel,
store_pwm_auto_point_channel, 0, 2),
SENSOR_ATTR_2(pwm3_auto_point1_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
0, 2),
SENSOR_ATTR_2(pwm3_auto_point2_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
1, 2),
SENSOR_ATTR_2(pwm3_auto_point3_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
4, 2),
SENSOR_ATTR_2(pwm3_auto_point1_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
0, 2),
SENSOR_ATTR_2(pwm3_auto_point2_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
3, 2),
SENSOR_ATTR_2(pwm3_auto_point1_temp_hyst, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp_hyst,
store_pwm_auto_point_temp_hyst,
0, 2),
SENSOR_ATTR_2(pwm3_auto_point2_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 3, 2),
} };
/* PWM attr for the standard models */
static struct sensor_device_attribute_2 fxxxx_auto_pwm_attr[4][14] = { {
SENSOR_ATTR_2(pwm1_auto_channels_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_channel,
store_pwm_auto_point_channel, 0, 0),
SENSOR_ATTR_2(pwm1_auto_point1_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
0, 0),
SENSOR_ATTR_2(pwm1_auto_point2_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
1, 0),
SENSOR_ATTR_2(pwm1_auto_point3_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
2, 0),
SENSOR_ATTR_2(pwm1_auto_point4_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
3, 0),
SENSOR_ATTR_2(pwm1_auto_point5_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
4, 0),
SENSOR_ATTR_2(pwm1_auto_point1_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
0, 0),
SENSOR_ATTR_2(pwm1_auto_point2_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
1, 0),
SENSOR_ATTR_2(pwm1_auto_point3_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
2, 0),
SENSOR_ATTR_2(pwm1_auto_point4_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
3, 0),
SENSOR_ATTR_2(pwm1_auto_point1_temp_hyst, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp_hyst,
store_pwm_auto_point_temp_hyst,
0, 0),
SENSOR_ATTR_2(pwm1_auto_point2_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 1, 0),
SENSOR_ATTR_2(pwm1_auto_point3_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 2, 0),
SENSOR_ATTR_2(pwm1_auto_point4_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 3, 0),
}, {
SENSOR_ATTR_2(pwm2_auto_channels_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_channel,
store_pwm_auto_point_channel, 0, 1),
SENSOR_ATTR_2(pwm2_auto_point1_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
0, 1),
SENSOR_ATTR_2(pwm2_auto_point2_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
1, 1),
SENSOR_ATTR_2(pwm2_auto_point3_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
2, 1),
SENSOR_ATTR_2(pwm2_auto_point4_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
3, 1),
SENSOR_ATTR_2(pwm2_auto_point5_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
4, 1),
SENSOR_ATTR_2(pwm2_auto_point1_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
0, 1),
SENSOR_ATTR_2(pwm2_auto_point2_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
1, 1),
SENSOR_ATTR_2(pwm2_auto_point3_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
2, 1),
SENSOR_ATTR_2(pwm2_auto_point4_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
3, 1),
SENSOR_ATTR_2(pwm2_auto_point1_temp_hyst, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp_hyst,
store_pwm_auto_point_temp_hyst,
0, 1),
SENSOR_ATTR_2(pwm2_auto_point2_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 1, 1),
SENSOR_ATTR_2(pwm2_auto_point3_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 2, 1),
SENSOR_ATTR_2(pwm2_auto_point4_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 3, 1),
}, {
SENSOR_ATTR_2(pwm3_auto_channels_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_channel,
store_pwm_auto_point_channel, 0, 2),
SENSOR_ATTR_2(pwm3_auto_point1_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
0, 2),
SENSOR_ATTR_2(pwm3_auto_point2_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
1, 2),
SENSOR_ATTR_2(pwm3_auto_point3_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
2, 2),
SENSOR_ATTR_2(pwm3_auto_point4_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
3, 2),
SENSOR_ATTR_2(pwm3_auto_point5_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
4, 2),
SENSOR_ATTR_2(pwm3_auto_point1_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
0, 2),
SENSOR_ATTR_2(pwm3_auto_point2_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
1, 2),
SENSOR_ATTR_2(pwm3_auto_point3_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
2, 2),
SENSOR_ATTR_2(pwm3_auto_point4_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
3, 2),
SENSOR_ATTR_2(pwm3_auto_point1_temp_hyst, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp_hyst,
store_pwm_auto_point_temp_hyst,
0, 2),
SENSOR_ATTR_2(pwm3_auto_point2_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 1, 2),
SENSOR_ATTR_2(pwm3_auto_point3_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 2, 2),
SENSOR_ATTR_2(pwm3_auto_point4_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 3, 2),
}, {
SENSOR_ATTR_2(pwm4_auto_channels_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_channel,
store_pwm_auto_point_channel, 0, 3),
SENSOR_ATTR_2(pwm4_auto_point1_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
0, 3),
SENSOR_ATTR_2(pwm4_auto_point2_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
1, 3),
SENSOR_ATTR_2(pwm4_auto_point3_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
2, 3),
SENSOR_ATTR_2(pwm4_auto_point4_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
3, 3),
SENSOR_ATTR_2(pwm4_auto_point5_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
4, 3),
SENSOR_ATTR_2(pwm4_auto_point1_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
0, 3),
SENSOR_ATTR_2(pwm4_auto_point2_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
1, 3),
SENSOR_ATTR_2(pwm4_auto_point3_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
2, 3),
SENSOR_ATTR_2(pwm4_auto_point4_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
3, 3),
SENSOR_ATTR_2(pwm4_auto_point1_temp_hyst, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp_hyst,
store_pwm_auto_point_temp_hyst,
0, 3),
SENSOR_ATTR_2(pwm4_auto_point2_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 1, 3),
SENSOR_ATTR_2(pwm4_auto_point3_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 2, 3),
SENSOR_ATTR_2(pwm4_auto_point4_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 3, 3),
} };
/* Fan attr specific to the f8000 (4th fan input can only measure speed) */
static struct sensor_device_attribute_2 f8000_fan_attr[] = {
SENSOR_ATTR_2(fan4_input, S_IRUGO, show_fan, NULL, 0, 3),
};
/*
* PWM attr for the f8000, zones mapped to temp instead of to pwm!
* Also the register block at offset A0 maps to TEMP1 (so our temp2, as the
* F8000 starts counting temps at 0), B0 maps the TEMP2 and C0 maps to TEMP0
*/
static struct sensor_device_attribute_2 f8000_auto_pwm_attr[3][14] = { {
SENSOR_ATTR_2(pwm1_auto_channels_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_channel,
store_pwm_auto_point_channel, 0, 0),
SENSOR_ATTR_2(temp1_auto_point1_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
0, 2),
SENSOR_ATTR_2(temp1_auto_point2_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
1, 2),
SENSOR_ATTR_2(temp1_auto_point3_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
2, 2),
SENSOR_ATTR_2(temp1_auto_point4_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
3, 2),
SENSOR_ATTR_2(temp1_auto_point5_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
4, 2),
SENSOR_ATTR_2(temp1_auto_point1_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
0, 2),
SENSOR_ATTR_2(temp1_auto_point2_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
1, 2),
SENSOR_ATTR_2(temp1_auto_point3_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
2, 2),
SENSOR_ATTR_2(temp1_auto_point4_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
3, 2),
SENSOR_ATTR_2(temp1_auto_point1_temp_hyst, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp_hyst,
store_pwm_auto_point_temp_hyst,
0, 2),
SENSOR_ATTR_2(temp1_auto_point2_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 1, 2),
SENSOR_ATTR_2(temp1_auto_point3_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 2, 2),
SENSOR_ATTR_2(temp1_auto_point4_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 3, 2),
}, {
SENSOR_ATTR_2(pwm2_auto_channels_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_channel,
store_pwm_auto_point_channel, 0, 1),
SENSOR_ATTR_2(temp2_auto_point1_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
0, 0),
SENSOR_ATTR_2(temp2_auto_point2_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
1, 0),
SENSOR_ATTR_2(temp2_auto_point3_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
2, 0),
SENSOR_ATTR_2(temp2_auto_point4_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
3, 0),
SENSOR_ATTR_2(temp2_auto_point5_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
4, 0),
SENSOR_ATTR_2(temp2_auto_point1_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
0, 0),
SENSOR_ATTR_2(temp2_auto_point2_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
1, 0),
SENSOR_ATTR_2(temp2_auto_point3_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
2, 0),
SENSOR_ATTR_2(temp2_auto_point4_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
3, 0),
SENSOR_ATTR_2(temp2_auto_point1_temp_hyst, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp_hyst,
store_pwm_auto_point_temp_hyst,
0, 0),
SENSOR_ATTR_2(temp2_auto_point2_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 1, 0),
SENSOR_ATTR_2(temp2_auto_point3_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 2, 0),
SENSOR_ATTR_2(temp2_auto_point4_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 3, 0),
}, {
SENSOR_ATTR_2(pwm3_auto_channels_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_channel,
store_pwm_auto_point_channel, 0, 2),
SENSOR_ATTR_2(temp3_auto_point1_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
0, 1),
SENSOR_ATTR_2(temp3_auto_point2_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
1, 1),
SENSOR_ATTR_2(temp3_auto_point3_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
2, 1),
SENSOR_ATTR_2(temp3_auto_point4_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
3, 1),
SENSOR_ATTR_2(temp3_auto_point5_pwm, S_IRUGO|S_IWUSR,
show_pwm_auto_point_pwm, store_pwm_auto_point_pwm,
4, 1),
SENSOR_ATTR_2(temp3_auto_point1_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
0, 1),
SENSOR_ATTR_2(temp3_auto_point2_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
1, 1),
SENSOR_ATTR_2(temp3_auto_point3_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
2, 1),
SENSOR_ATTR_2(temp3_auto_point4_temp, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp, store_pwm_auto_point_temp,
3, 1),
SENSOR_ATTR_2(temp3_auto_point1_temp_hyst, S_IRUGO|S_IWUSR,
show_pwm_auto_point_temp_hyst,
store_pwm_auto_point_temp_hyst,
0, 1),
SENSOR_ATTR_2(temp3_auto_point2_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 1, 1),
SENSOR_ATTR_2(temp3_auto_point3_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 2, 1),
SENSOR_ATTR_2(temp3_auto_point4_temp_hyst, S_IRUGO,
show_pwm_auto_point_temp_hyst, NULL, 3, 1),
} };
/* Super I/O functions */
static inline int superio_inb(int base, int reg)
{
outb(reg, base);
return inb(base + 1);
}
static int superio_inw(int base, int reg)
{
int val;
val = superio_inb(base, reg) << 8;
val |= superio_inb(base, reg + 1);
return val;
}
static inline int superio_enter(int base)
{
/* Don't step on other drivers' I/O space by accident */
if (!request_muxed_region(base, 2, DRVNAME)) {
pr_err("I/O address 0x%04x already in use\n", base);
return -EBUSY;
}
/* according to the datasheet the key must be send twice! */
outb(SIO_UNLOCK_KEY, base);
outb(SIO_UNLOCK_KEY, base);
return 0;
}
static inline void superio_select(int base, int ld)
{
outb(SIO_REG_LDSEL, base);
outb(ld, base + 1);
}
static inline void superio_exit(int base)
{
outb(SIO_LOCK_KEY, base);
release_region(base, 2);
}
static inline int fan_from_reg(u16 reg)
{
return reg ? (1500000 / reg) : 0;
}
static inline u16 fan_to_reg(int fan)
{
return fan ? (1500000 / fan) : 0;
}
static u8 f71882fg_read8(struct f71882fg_data *data, u8 reg)
{
u8 val;
outb(reg, data->addr + ADDR_REG_OFFSET);
val = inb(data->addr + DATA_REG_OFFSET);
return val;
}
static u16 f71882fg_read16(struct f71882fg_data *data, u8 reg)
{
u16 val;
val = f71882fg_read8(data, reg) << 8;
val |= f71882fg_read8(data, reg + 1);
return val;
}
static void f71882fg_write8(struct f71882fg_data *data, u8 reg, u8 val)
{
outb(reg, data->addr + ADDR_REG_OFFSET);
outb(val, data->addr + DATA_REG_OFFSET);
}
static void f71882fg_write16(struct f71882fg_data *data, u8 reg, u16 val)
{
f71882fg_write8(data, reg, val >> 8);
f71882fg_write8(data, reg + 1, val & 0xff);
}
static u16 f71882fg_read_temp(struct f71882fg_data *data, int nr)
{
if (data->type == f71858fg)
return f71882fg_read16(data, F71882FG_REG_TEMP(nr));
else
return f71882fg_read8(data, F71882FG_REG_TEMP(nr));
}
static struct f71882fg_data *f71882fg_update_device(struct device *dev)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
int nr_fans = f71882fg_nr_fans[data->type];
int nr_temps = f71882fg_nr_temps[data->type];
int nr, reg, point;
mutex_lock(&data->update_lock);
/* Update once every 60 seconds */
if (time_after(jiffies, data->last_limits + 60 * HZ) ||
!data->valid) {
if (f71882fg_has_in1_alarm[data->type]) {
data->in1_max =
f71882fg_read8(data, F71882FG_REG_IN1_HIGH);
data->in_beep =
f71882fg_read8(data, F71882FG_REG_IN_BEEP);
}
/* Get High & boundary temps*/
for (nr = data->temp_start; nr < nr_temps + data->temp_start;
nr++) {
data->temp_ovt[nr] = f71882fg_read8(data,
F71882FG_REG_TEMP_OVT(nr));
data->temp_high[nr] = f71882fg_read8(data,
F71882FG_REG_TEMP_HIGH(nr));
}
if (data->type != f8000) {
data->temp_hyst[0] = f71882fg_read8(data,
F71882FG_REG_TEMP_HYST(0));
data->temp_hyst[1] = f71882fg_read8(data,
F71882FG_REG_TEMP_HYST(1));
}
/* All but the f71858fg / f8000 have this register */
if ((data->type != f71858fg) && (data->type != f8000)) {
reg = f71882fg_read8(data, F71882FG_REG_TEMP_TYPE);
data->temp_type[1] = (reg & 0x02) ? 2 : 4;
data->temp_type[2] = (reg & 0x04) ? 2 : 4;
data->temp_type[3] = (reg & 0x08) ? 2 : 4;
}
if (f71882fg_fan_has_beep[data->type])
data->fan_beep = f71882fg_read8(data,
F71882FG_REG_FAN_BEEP);
if (f71882fg_temp_has_beep[data->type])
data->temp_beep = f71882fg_read8(data,
F71882FG_REG_TEMP_BEEP);
data->pwm_enable = f71882fg_read8(data,
F71882FG_REG_PWM_ENABLE);
data->pwm_auto_point_hyst[0] =
f71882fg_read8(data, F71882FG_REG_FAN_HYST(0));
data->pwm_auto_point_hyst[1] =
f71882fg_read8(data, F71882FG_REG_FAN_HYST(1));
for (nr = 0; nr < nr_fans; nr++) {
data->pwm_auto_point_mapping[nr] =
f71882fg_read8(data,
F71882FG_REG_POINT_MAPPING(nr));
switch (data->type) {
default:
for (point = 0; point < 5; point++) {
data->pwm_auto_point_pwm[nr][point] =
f71882fg_read8(data,
F71882FG_REG_POINT_PWM
(nr, point));
}
for (point = 0; point < 4; point++) {
data->pwm_auto_point_temp[nr][point] =
f71882fg_read8(data,
F71882FG_REG_POINT_TEMP
(nr, point));
}
break;
case f71808e:
case f71869:
data->pwm_auto_point_pwm[nr][0] =
f71882fg_read8(data,
F71882FG_REG_POINT_PWM(nr, 0));
/* Fall through */
case f71862fg:
data->pwm_auto_point_pwm[nr][1] =
f71882fg_read8(data,
F71882FG_REG_POINT_PWM
(nr, 1));
data->pwm_auto_point_pwm[nr][4] =
f71882fg_read8(data,
F71882FG_REG_POINT_PWM
(nr, 4));
data->pwm_auto_point_temp[nr][0] =
f71882fg_read8(data,
F71882FG_REG_POINT_TEMP
(nr, 0));
data->pwm_auto_point_temp[nr][3] =
f71882fg_read8(data,
F71882FG_REG_POINT_TEMP
(nr, 3));
break;
}
}
data->last_limits = jiffies;
}
/* Update every second */
if (time_after(jiffies, data->last_updated + HZ) || !data->valid) {
data->temp_status = f71882fg_read8(data,
F71882FG_REG_TEMP_STATUS);
data->temp_diode_open = f71882fg_read8(data,
F71882FG_REG_TEMP_DIODE_OPEN);
for (nr = data->temp_start; nr < nr_temps + data->temp_start;
nr++)
data->temp[nr] = f71882fg_read_temp(data, nr);
data->fan_status = f71882fg_read8(data,
F71882FG_REG_FAN_STATUS);
for (nr = 0; nr < nr_fans; nr++) {
data->fan[nr] = f71882fg_read16(data,
F71882FG_REG_FAN(nr));
data->fan_target[nr] =
f71882fg_read16(data, F71882FG_REG_FAN_TARGET(nr));
data->fan_full_speed[nr] =
f71882fg_read16(data,
F71882FG_REG_FAN_FULL_SPEED(nr));
data->pwm[nr] =
f71882fg_read8(data, F71882FG_REG_PWM(nr));
}
/* Some models have 1 more fan with limited capabilities */
if (data->type == f71808a) {
data->fan[2] = f71882fg_read16(data,
F71882FG_REG_FAN(2));
data->pwm[2] = f71882fg_read8(data,
F71882FG_REG_PWM(2));
}
if (data->type == f8000)
data->fan[3] = f71882fg_read16(data,
F71882FG_REG_FAN(3));
if (f71882fg_has_in1_alarm[data->type])
data->in_status = f71882fg_read8(data,
F71882FG_REG_IN_STATUS);
for (nr = 0; nr < F71882FG_MAX_INS; nr++)
if (f71882fg_has_in[data->type][nr])
data->in[nr] = f71882fg_read8(data,
F71882FG_REG_IN(nr));
data->last_updated = jiffies;
data->valid = 1;
}
mutex_unlock(&data->update_lock);
return data;
}
/* Sysfs Interface */
static ssize_t show_fan(struct device *dev, struct device_attribute *devattr,
char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
int speed = fan_from_reg(data->fan[nr]);
if (speed == FAN_MIN_DETECT)
speed = 0;
return sprintf(buf, "%d\n", speed);
}
static ssize_t show_fan_full_speed(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
int speed = fan_from_reg(data->fan_full_speed[nr]);
return sprintf(buf, "%d\n", speed);
}
static ssize_t store_fan_full_speed(struct device *dev,
struct device_attribute *devattr,
const char *buf, size_t count)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
int err, nr = to_sensor_dev_attr_2(devattr)->index;
long val;
err = kstrtol(buf, 10, &val);
if (err)
return err;
val = clamp_val(val, 23, 1500000);
val = fan_to_reg(val);
mutex_lock(&data->update_lock);
f71882fg_write16(data, F71882FG_REG_FAN_FULL_SPEED(nr), val);
data->fan_full_speed[nr] = val;
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_fan_beep(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
if (data->fan_beep & (1 << nr))
return sprintf(buf, "1\n");
else
return sprintf(buf, "0\n");
}
static ssize_t store_fan_beep(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
int err, nr = to_sensor_dev_attr_2(devattr)->index;
unsigned long val;
err = kstrtoul(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->fan_beep = f71882fg_read8(data, F71882FG_REG_FAN_BEEP);
if (val)
data->fan_beep |= 1 << nr;
else
data->fan_beep &= ~(1 << nr);
f71882fg_write8(data, F71882FG_REG_FAN_BEEP, data->fan_beep);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_fan_alarm(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
if (data->fan_status & (1 << nr))
return sprintf(buf, "1\n");
else
return sprintf(buf, "0\n");
}
static ssize_t show_in(struct device *dev, struct device_attribute *devattr,
char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
return sprintf(buf, "%d\n", data->in[nr] * 8);
}
static ssize_t show_in_max(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
return sprintf(buf, "%d\n", data->in1_max * 8);
}
static ssize_t store_in_max(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
int err;
long val;
err = kstrtol(buf, 10, &val);
if (err)
return err;
val /= 8;
val = clamp_val(val, 0, 255);
mutex_lock(&data->update_lock);
f71882fg_write8(data, F71882FG_REG_IN1_HIGH, val);
data->in1_max = val;
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_in_beep(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
if (data->in_beep & (1 << nr))
return sprintf(buf, "1\n");
else
return sprintf(buf, "0\n");
}
static ssize_t store_in_beep(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
int err, nr = to_sensor_dev_attr_2(devattr)->index;
unsigned long val;
err = kstrtoul(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->in_beep = f71882fg_read8(data, F71882FG_REG_IN_BEEP);
if (val)
data->in_beep |= 1 << nr;
else
data->in_beep &= ~(1 << nr);
f71882fg_write8(data, F71882FG_REG_IN_BEEP, data->in_beep);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_in_alarm(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
if (data->in_status & (1 << nr))
return sprintf(buf, "1\n");
else
return sprintf(buf, "0\n");
}
static ssize_t show_temp(struct device *dev, struct device_attribute *devattr,
char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
int sign, temp;
if (data->type == f71858fg) {
/* TEMP_TABLE_SEL 1 or 3 ? */
if (data->temp_config & 1) {
sign = data->temp[nr] & 0x0001;
temp = (data->temp[nr] >> 5) & 0x7ff;
} else {
sign = data->temp[nr] & 0x8000;
temp = (data->temp[nr] >> 5) & 0x3ff;
}
temp *= 125;
if (sign)
temp -= 128000;
} else
temp = data->temp[nr] * 1000;
return sprintf(buf, "%d\n", temp);
}
static ssize_t show_temp_max(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
return sprintf(buf, "%d\n", data->temp_high[nr] * 1000);
}
static ssize_t store_temp_max(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
int err, nr = to_sensor_dev_attr_2(devattr)->index;
long val;
err = kstrtol(buf, 10, &val);
if (err)
return err;
val /= 1000;
val = clamp_val(val, 0, 255);
mutex_lock(&data->update_lock);
f71882fg_write8(data, F71882FG_REG_TEMP_HIGH(nr), val);
data->temp_high[nr] = val;
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_temp_max_hyst(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
int temp_max_hyst;
mutex_lock(&data->update_lock);
if (nr & 1)
temp_max_hyst = data->temp_hyst[nr / 2] >> 4;
else
temp_max_hyst = data->temp_hyst[nr / 2] & 0x0f;
temp_max_hyst = (data->temp_high[nr] - temp_max_hyst) * 1000;
mutex_unlock(&data->update_lock);
return sprintf(buf, "%d\n", temp_max_hyst);
}
static ssize_t store_temp_max_hyst(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
int err, nr = to_sensor_dev_attr_2(devattr)->index;
ssize_t ret = count;
u8 reg;
long val;
err = kstrtol(buf, 10, &val);
if (err)
return err;
val /= 1000;
mutex_lock(&data->update_lock);
/* convert abs to relative and check */
data->temp_high[nr] = f71882fg_read8(data, F71882FG_REG_TEMP_HIGH(nr));
val = clamp_val(val, data->temp_high[nr] - 15, data->temp_high[nr]);
val = data->temp_high[nr] - val;
/* convert value to register contents */
reg = f71882fg_read8(data, F71882FG_REG_TEMP_HYST(nr / 2));
if (nr & 1)
reg = (reg & 0x0f) | (val << 4);
else
reg = (reg & 0xf0) | val;
f71882fg_write8(data, F71882FG_REG_TEMP_HYST(nr / 2), reg);
data->temp_hyst[nr / 2] = reg;
mutex_unlock(&data->update_lock);
return ret;
}
static ssize_t show_temp_crit(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
return sprintf(buf, "%d\n", data->temp_ovt[nr] * 1000);
}
static ssize_t store_temp_crit(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
int err, nr = to_sensor_dev_attr_2(devattr)->index;
long val;
err = kstrtol(buf, 10, &val);
if (err)
return err;
val /= 1000;
val = clamp_val(val, 0, 255);
mutex_lock(&data->update_lock);
f71882fg_write8(data, F71882FG_REG_TEMP_OVT(nr), val);
data->temp_ovt[nr] = val;
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_temp_crit_hyst(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
int temp_crit_hyst;
mutex_lock(&data->update_lock);
if (nr & 1)
temp_crit_hyst = data->temp_hyst[nr / 2] >> 4;
else
temp_crit_hyst = data->temp_hyst[nr / 2] & 0x0f;
temp_crit_hyst = (data->temp_ovt[nr] - temp_crit_hyst) * 1000;
mutex_unlock(&data->update_lock);
return sprintf(buf, "%d\n", temp_crit_hyst);
}
static ssize_t show_temp_type(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
return sprintf(buf, "%d\n", data->temp_type[nr]);
}
static ssize_t show_temp_beep(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
if (data->temp_beep & (1 << nr))
return sprintf(buf, "1\n");
else
return sprintf(buf, "0\n");
}
static ssize_t store_temp_beep(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
int err, nr = to_sensor_dev_attr_2(devattr)->index;
unsigned long val;
err = kstrtoul(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->temp_beep = f71882fg_read8(data, F71882FG_REG_TEMP_BEEP);
if (val)
data->temp_beep |= 1 << nr;
else
data->temp_beep &= ~(1 << nr);
f71882fg_write8(data, F71882FG_REG_TEMP_BEEP, data->temp_beep);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_temp_alarm(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
if (data->temp_status & (1 << nr))
return sprintf(buf, "1\n");
else
return sprintf(buf, "0\n");
}
static ssize_t show_temp_fault(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
if (data->temp_diode_open & (1 << nr))
return sprintf(buf, "1\n");
else
return sprintf(buf, "0\n");
}
static ssize_t show_pwm(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int val, nr = to_sensor_dev_attr_2(devattr)->index;
mutex_lock(&data->update_lock);
if (data->pwm_enable & (1 << (2 * nr)))
/* PWM mode */
val = data->pwm[nr];
else {
/* RPM mode */
val = 255 * fan_from_reg(data->fan_target[nr])
/ fan_from_reg(data->fan_full_speed[nr]);
}
mutex_unlock(&data->update_lock);
return sprintf(buf, "%d\n", val);
}
static ssize_t store_pwm(struct device *dev,
struct device_attribute *devattr, const char *buf,
size_t count)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
int err, nr = to_sensor_dev_attr_2(devattr)->index;
long val;
err = kstrtol(buf, 10, &val);
if (err)
return err;
val = clamp_val(val, 0, 255);
mutex_lock(&data->update_lock);
data->pwm_enable = f71882fg_read8(data, F71882FG_REG_PWM_ENABLE);
if ((data->type == f8000 && ((data->pwm_enable >> 2 * nr) & 3) != 2) ||
(data->type != f8000 && !((data->pwm_enable >> 2 * nr) & 2))) {
count = -EROFS;
goto leave;
}
if (data->pwm_enable & (1 << (2 * nr))) {
/* PWM mode */
f71882fg_write8(data, F71882FG_REG_PWM(nr), val);
data->pwm[nr] = val;
} else {
/* RPM mode */
int target, full_speed;
full_speed = f71882fg_read16(data,
F71882FG_REG_FAN_FULL_SPEED(nr));
target = fan_to_reg(val * fan_from_reg(full_speed) / 255);
f71882fg_write16(data, F71882FG_REG_FAN_TARGET(nr), target);
data->fan_target[nr] = target;
data->fan_full_speed[nr] = full_speed;
}
leave:
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_simple_pwm(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct f71882fg_data *data = f71882fg_update_device(dev);
int val, nr = to_sensor_dev_attr_2(devattr)->index;
val = data->pwm[nr];
return sprintf(buf, "%d\n", val);
}
static ssize_t store_simple_pwm(struct device *dev,
struct device_attribute *devattr,
const char *buf, size_t count)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
int err, nr = to_sensor_dev_attr_2(devattr)->index;
long val;
err = kstrtol(buf, 10, &val);
if (err)
return err;
val = clamp_val(val, 0, 255);
mutex_lock(&data->update_lock);
f71882fg_write8(data, F71882FG_REG_PWM(nr), val);
data->pwm[nr] = val;
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_pwm_enable(struct device *dev,
struct device_attribute *devattr, char *buf)
{
int result = 0;
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
switch ((data->pwm_enable >> 2 * nr) & 3) {
case 0:
case 1:
result = 2; /* Normal auto mode */
break;
case 2:
result = 1; /* Manual mode */
break;
case 3:
if (data->type == f8000)
result = 3; /* Thermostat mode */
else
result = 1; /* Manual mode */
break;
}
return sprintf(buf, "%d\n", result);
}
static ssize_t store_pwm_enable(struct device *dev, struct device_attribute
*devattr, const char *buf, size_t count)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
int err, nr = to_sensor_dev_attr_2(devattr)->index;
long val;
err = kstrtol(buf, 10, &val);
if (err)
return err;
/* Special case for F8000 pwm channel 3 which only does auto mode */
if (data->type == f8000 && nr == 2 && val != 2)
return -EINVAL;
mutex_lock(&data->update_lock);
data->pwm_enable = f71882fg_read8(data, F71882FG_REG_PWM_ENABLE);
/* Special case for F8000 auto PWM mode / Thermostat mode */
if (data->type == f8000 && ((data->pwm_enable >> 2 * nr) & 1)) {
switch (val) {
case 2:
data->pwm_enable &= ~(2 << (2 * nr));
break; /* Normal auto mode */
case 3:
data->pwm_enable |= 2 << (2 * nr);
break; /* Thermostat mode */
default:
count = -EINVAL;
goto leave;
}
} else {
switch (val) {
case 1:
/* The f71858fg does not support manual RPM mode */
if (data->type == f71858fg &&
((data->pwm_enable >> (2 * nr)) & 1)) {
count = -EINVAL;
goto leave;
}
data->pwm_enable |= 2 << (2 * nr);
break; /* Manual */
case 2:
data->pwm_enable &= ~(2 << (2 * nr));
break; /* Normal auto mode */
default:
count = -EINVAL;
goto leave;
}
}
f71882fg_write8(data, F71882FG_REG_PWM_ENABLE, data->pwm_enable);
leave:
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_pwm_auto_point_pwm(struct device *dev,
struct device_attribute *devattr,
char *buf)
{
int result;
struct f71882fg_data *data = f71882fg_update_device(dev);
int pwm = to_sensor_dev_attr_2(devattr)->index;
int point = to_sensor_dev_attr_2(devattr)->nr;
mutex_lock(&data->update_lock);
if (data->pwm_enable & (1 << (2 * pwm))) {
/* PWM mode */
result = data->pwm_auto_point_pwm[pwm][point];
} else {
/* RPM mode */
result = 32 * 255 / (32 + data->pwm_auto_point_pwm[pwm][point]);
}
mutex_unlock(&data->update_lock);
return sprintf(buf, "%d\n", result);
}
static ssize_t store_pwm_auto_point_pwm(struct device *dev,
struct device_attribute *devattr,
const char *buf, size_t count)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
int err, pwm = to_sensor_dev_attr_2(devattr)->index;
int point = to_sensor_dev_attr_2(devattr)->nr;
long val;
err = kstrtol(buf, 10, &val);
if (err)
return err;
val = clamp_val(val, 0, 255);
mutex_lock(&data->update_lock);
data->pwm_enable = f71882fg_read8(data, F71882FG_REG_PWM_ENABLE);
if (data->pwm_enable & (1 << (2 * pwm))) {
/* PWM mode */
} else {
/* RPM mode */
if (val < 29) /* Prevent negative numbers */
val = 255;
else
val = (255 - val) * 32 / val;
}
f71882fg_write8(data, F71882FG_REG_POINT_PWM(pwm, point), val);
data->pwm_auto_point_pwm[pwm][point] = val;
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_pwm_auto_point_temp_hyst(struct device *dev,
struct device_attribute *devattr,
char *buf)
{
int result = 0;
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
int point = to_sensor_dev_attr_2(devattr)->nr;
mutex_lock(&data->update_lock);
if (nr & 1)
result = data->pwm_auto_point_hyst[nr / 2] >> 4;
else
result = data->pwm_auto_point_hyst[nr / 2] & 0x0f;
result = 1000 * (data->pwm_auto_point_temp[nr][point] - result);
mutex_unlock(&data->update_lock);
return sprintf(buf, "%d\n", result);
}
static ssize_t store_pwm_auto_point_temp_hyst(struct device *dev,
struct device_attribute *devattr,
const char *buf, size_t count)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
int err, nr = to_sensor_dev_attr_2(devattr)->index;
int point = to_sensor_dev_attr_2(devattr)->nr;
u8 reg;
long val;
err = kstrtol(buf, 10, &val);
if (err)
return err;
val /= 1000;
mutex_lock(&data->update_lock);
data->pwm_auto_point_temp[nr][point] =
f71882fg_read8(data, F71882FG_REG_POINT_TEMP(nr, point));
val = clamp_val(val, data->pwm_auto_point_temp[nr][point] - 15,
data->pwm_auto_point_temp[nr][point]);
val = data->pwm_auto_point_temp[nr][point] - val;
reg = f71882fg_read8(data, F71882FG_REG_FAN_HYST(nr / 2));
if (nr & 1)
reg = (reg & 0x0f) | (val << 4);
else
reg = (reg & 0xf0) | val;
f71882fg_write8(data, F71882FG_REG_FAN_HYST(nr / 2), reg);
data->pwm_auto_point_hyst[nr / 2] = reg;
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_pwm_interpolate(struct device *dev,
struct device_attribute *devattr, char *buf)
{
int result;
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
result = (data->pwm_auto_point_mapping[nr] >> 4) & 1;
return sprintf(buf, "%d\n", result);
}
static ssize_t store_pwm_interpolate(struct device *dev,
struct device_attribute *devattr,
const char *buf, size_t count)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
int err, nr = to_sensor_dev_attr_2(devattr)->index;
unsigned long val;
err = kstrtoul(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->pwm_auto_point_mapping[nr] =
f71882fg_read8(data, F71882FG_REG_POINT_MAPPING(nr));
if (val)
val = data->pwm_auto_point_mapping[nr] | (1 << 4);
else
val = data->pwm_auto_point_mapping[nr] & (~(1 << 4));
f71882fg_write8(data, F71882FG_REG_POINT_MAPPING(nr), val);
data->pwm_auto_point_mapping[nr] = val;
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_pwm_auto_point_channel(struct device *dev,
struct device_attribute *devattr,
char *buf)
{
int result;
struct f71882fg_data *data = f71882fg_update_device(dev);
int nr = to_sensor_dev_attr_2(devattr)->index;
result = 1 << ((data->pwm_auto_point_mapping[nr] & 3) -
data->temp_start);
return sprintf(buf, "%d\n", result);
}
static ssize_t store_pwm_auto_point_channel(struct device *dev,
struct device_attribute *devattr,
const char *buf, size_t count)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
int err, nr = to_sensor_dev_attr_2(devattr)->index;
long val;
err = kstrtol(buf, 10, &val);
if (err)
return err;
switch (val) {
case 1:
val = 0;
break;
case 2:
val = 1;
break;
case 4:
val = 2;
break;
default:
return -EINVAL;
}
val += data->temp_start;
mutex_lock(&data->update_lock);
data->pwm_auto_point_mapping[nr] =
f71882fg_read8(data, F71882FG_REG_POINT_MAPPING(nr));
val = (data->pwm_auto_point_mapping[nr] & 0xfc) | val;
f71882fg_write8(data, F71882FG_REG_POINT_MAPPING(nr), val);
data->pwm_auto_point_mapping[nr] = val;
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_pwm_auto_point_temp(struct device *dev,
struct device_attribute *devattr,
char *buf)
{
int result;
struct f71882fg_data *data = f71882fg_update_device(dev);
int pwm = to_sensor_dev_attr_2(devattr)->index;
int point = to_sensor_dev_attr_2(devattr)->nr;
result = data->pwm_auto_point_temp[pwm][point];
return sprintf(buf, "%d\n", 1000 * result);
}
static ssize_t store_pwm_auto_point_temp(struct device *dev,
struct device_attribute *devattr,
const char *buf, size_t count)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
int err, pwm = to_sensor_dev_attr_2(devattr)->index;
int point = to_sensor_dev_attr_2(devattr)->nr;
long val;
err = kstrtol(buf, 10, &val);
if (err)
return err;
val /= 1000;
if (data->auto_point_temp_signed)
val = clamp_val(val, -128, 127);
else
val = clamp_val(val, 0, 127);
mutex_lock(&data->update_lock);
f71882fg_write8(data, F71882FG_REG_POINT_TEMP(pwm, point), val);
data->pwm_auto_point_temp[pwm][point] = val;
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_name(struct device *dev, struct device_attribute *devattr,
char *buf)
{
struct f71882fg_data *data = dev_get_drvdata(dev);
return sprintf(buf, "%s\n", f71882fg_names[data->type]);
}
static int f71882fg_create_sysfs_files(struct platform_device *pdev,
struct sensor_device_attribute_2 *attr, int count)
{
int err, i;
for (i = 0; i < count; i++) {
err = device_create_file(&pdev->dev, &attr[i].dev_attr);
if (err)
return err;
}
return 0;
}
static void f71882fg_remove_sysfs_files(struct platform_device *pdev,
struct sensor_device_attribute_2 *attr, int count)
{
int i;
for (i = 0; i < count; i++)
device_remove_file(&pdev->dev, &attr[i].dev_attr);
}
static int f71882fg_create_fan_sysfs_files(
struct platform_device *pdev, int idx)
{
struct f71882fg_data *data = platform_get_drvdata(pdev);
int err;
/* Sanity check the pwm setting */
err = 0;
switch (data->type) {
case f71858fg:
if (((data->pwm_enable >> (idx * 2)) & 3) == 3)
err = 1;
break;
case f71862fg:
if (((data->pwm_enable >> (idx * 2)) & 1) != 1)
err = 1;
break;
case f8000:
if (idx == 2)
err = data->pwm_enable & 0x20;
break;
default:
break;
}
if (err) {
dev_err(&pdev->dev,
"Invalid (reserved) pwm settings: 0x%02x, "
"skipping fan %d\n",
(data->pwm_enable >> (idx * 2)) & 3, idx + 1);
return 0; /* This is a non fatal condition */
}
err = f71882fg_create_sysfs_files(pdev, &fxxxx_fan_attr[idx][0],
ARRAY_SIZE(fxxxx_fan_attr[0]));
if (err)
return err;
if (f71882fg_fan_has_beep[data->type]) {
err = f71882fg_create_sysfs_files(pdev,
&fxxxx_fan_beep_attr[idx],
1);
if (err)
return err;
}
dev_info(&pdev->dev, "Fan: %d is in %s mode\n", idx + 1,
(data->pwm_enable & (1 << (2 * idx))) ? "duty-cycle" : "RPM");
/* Check for unsupported auto pwm settings */
switch (data->type) {
case f71808e:
case f71808a:
case f71869:
case f71869a:
case f71889fg:
case f71889ed:
case f71889a:
data->pwm_auto_point_mapping[idx] =
f71882fg_read8(data, F71882FG_REG_POINT_MAPPING(idx));
if ((data->pwm_auto_point_mapping[idx] & 0x80) ||
(data->pwm_auto_point_mapping[idx] & 3) == 0) {
dev_warn(&pdev->dev,
"Auto pwm controlled by raw digital "
"data, disabling pwm auto_point "
"sysfs attributes for fan %d\n", idx + 1);
return 0; /* This is a non fatal condition */
}
break;
default:
break;
}
switch (data->type) {
case f71862fg:
err = f71882fg_create_sysfs_files(pdev,
&f71862fg_auto_pwm_attr[idx][0],
ARRAY_SIZE(f71862fg_auto_pwm_attr[0]));
break;
case f71808e:
case f71869:
err = f71882fg_create_sysfs_files(pdev,
&f71869_auto_pwm_attr[idx][0],
ARRAY_SIZE(f71869_auto_pwm_attr[0]));
break;
case f8000:
err = f71882fg_create_sysfs_files(pdev,
&f8000_auto_pwm_attr[idx][0],
ARRAY_SIZE(f8000_auto_pwm_attr[0]));
break;
default:
err = f71882fg_create_sysfs_files(pdev,
&fxxxx_auto_pwm_attr[idx][0],
ARRAY_SIZE(fxxxx_auto_pwm_attr[0]));
}
return err;
}
static int f71882fg_probe(struct platform_device *pdev)
{
struct f71882fg_data *data;
struct f71882fg_sio_data *sio_data = pdev->dev.platform_data;
int nr_fans = f71882fg_nr_fans[sio_data->type];
int nr_temps = f71882fg_nr_temps[sio_data->type];
int err, i;
u8 start_reg, reg;
data = devm_kzalloc(&pdev->dev, sizeof(struct f71882fg_data),
GFP_KERNEL);
if (!data)
return -ENOMEM;
data->addr = platform_get_resource(pdev, IORESOURCE_IO, 0)->start;
data->type = sio_data->type;
data->temp_start =
(data->type == f71858fg || data->type == f8000) ? 0 : 1;
mutex_init(&data->update_lock);
platform_set_drvdata(pdev, data);
start_reg = f71882fg_read8(data, F71882FG_REG_START);
if (start_reg & 0x04) {
dev_warn(&pdev->dev, "Hardware monitor is powered down\n");
return -ENODEV;
}
if (!(start_reg & 0x03)) {
dev_warn(&pdev->dev, "Hardware monitoring not activated\n");
return -ENODEV;
}
/* Register sysfs interface files */
err = device_create_file(&pdev->dev, &dev_attr_name);
if (err)
goto exit_unregister_sysfs;
if (start_reg & 0x01) {
switch (data->type) {
case f71858fg:
data->temp_config =
f71882fg_read8(data, F71882FG_REG_TEMP_CONFIG);
if (data->temp_config & 0x10)
/*
* The f71858fg temperature alarms behave as
* the f8000 alarms in this mode
*/
err = f71882fg_create_sysfs_files(pdev,
f8000_temp_attr,
ARRAY_SIZE(f8000_temp_attr));
else
err = f71882fg_create_sysfs_files(pdev,
f71858fg_temp_attr,
ARRAY_SIZE(f71858fg_temp_attr));
break;
case f8000:
err = f71882fg_create_sysfs_files(pdev,
f8000_temp_attr,
ARRAY_SIZE(f8000_temp_attr));
break;
default:
err = f71882fg_create_sysfs_files(pdev,
&fxxxx_temp_attr[0][0],
ARRAY_SIZE(fxxxx_temp_attr[0]) * nr_temps);
}
if (err)
goto exit_unregister_sysfs;
if (f71882fg_temp_has_beep[data->type]) {
err = f71882fg_create_sysfs_files(pdev,
&fxxxx_temp_beep_attr[0][0],
ARRAY_SIZE(fxxxx_temp_beep_attr[0])
* nr_temps);
if (err)
goto exit_unregister_sysfs;
}
for (i = 0; i < F71882FG_MAX_INS; i++) {
if (f71882fg_has_in[data->type][i]) {
err = device_create_file(&pdev->dev,
&fxxxx_in_attr[i].dev_attr);
if (err)
goto exit_unregister_sysfs;
}
}
if (f71882fg_has_in1_alarm[data->type]) {
err = f71882fg_create_sysfs_files(pdev,
fxxxx_in1_alarm_attr,
ARRAY_SIZE(fxxxx_in1_alarm_attr));
if (err)
goto exit_unregister_sysfs;
}
}
if (start_reg & 0x02) {
switch (data->type) {
case f71808e:
case f71808a:
case f71869:
case f71869a:
/* These always have signed auto point temps */
data->auto_point_temp_signed = 1;
/* Fall through to select correct fan/pwm reg bank! */
case f71889fg:
case f71889ed:
case f71889a:
reg = f71882fg_read8(data, F71882FG_REG_FAN_FAULT_T);
if (reg & F71882FG_FAN_NEG_TEMP_EN)
data->auto_point_temp_signed = 1;
/* Ensure banked pwm registers point to right bank */
reg &= ~F71882FG_FAN_PROG_SEL;
f71882fg_write8(data, F71882FG_REG_FAN_FAULT_T, reg);
break;
default:
break;
}
data->pwm_enable =
f71882fg_read8(data, F71882FG_REG_PWM_ENABLE);
for (i = 0; i < nr_fans; i++) {
err = f71882fg_create_fan_sysfs_files(pdev, i);
if (err)
goto exit_unregister_sysfs;
}
/* Some types have 1 extra fan with limited functionality */
switch (data->type) {
case f71808a:
err = f71882fg_create_sysfs_files(pdev,
f71808a_fan3_attr,
ARRAY_SIZE(f71808a_fan3_attr));
break;
case f8000:
err = f71882fg_create_sysfs_files(pdev,
f8000_fan_attr,
ARRAY_SIZE(f8000_fan_attr));
break;
default:
break;
}
if (err)
goto exit_unregister_sysfs;
}
data->hwmon_dev = hwmon_device_register(&pdev->dev);
if (IS_ERR(data->hwmon_dev)) {
err = PTR_ERR(data->hwmon_dev);
data->hwmon_dev = NULL;
goto exit_unregister_sysfs;
}
return 0;
exit_unregister_sysfs:
f71882fg_remove(pdev); /* Will unregister the sysfs files for us */
return err; /* f71882fg_remove() also frees our data */
return err;
}
static int f71882fg_remove(struct platform_device *pdev)
{
struct f71882fg_data *data = platform_get_drvdata(pdev);
int nr_fans = f71882fg_nr_fans[data->type];
int nr_temps = f71882fg_nr_temps[data->type];
int i;
u8 start_reg = f71882fg_read8(data, F71882FG_REG_START);
if (data->hwmon_dev)
hwmon_device_unregister(data->hwmon_dev);
device_remove_file(&pdev->dev, &dev_attr_name);
if (start_reg & 0x01) {
switch (data->type) {
case f71858fg:
if (data->temp_config & 0x10)
f71882fg_remove_sysfs_files(pdev,
f8000_temp_attr,
ARRAY_SIZE(f8000_temp_attr));
else
f71882fg_remove_sysfs_files(pdev,
f71858fg_temp_attr,
ARRAY_SIZE(f71858fg_temp_attr));
break;
case f8000:
f71882fg_remove_sysfs_files(pdev,
f8000_temp_attr,
ARRAY_SIZE(f8000_temp_attr));
break;
default:
f71882fg_remove_sysfs_files(pdev,
&fxxxx_temp_attr[0][0],
ARRAY_SIZE(fxxxx_temp_attr[0]) * nr_temps);
}
if (f71882fg_temp_has_beep[data->type]) {
f71882fg_remove_sysfs_files(pdev,
&fxxxx_temp_beep_attr[0][0],
ARRAY_SIZE(fxxxx_temp_beep_attr[0]) * nr_temps);
}
for (i = 0; i < F71882FG_MAX_INS; i++) {
if (f71882fg_has_in[data->type][i]) {
device_remove_file(&pdev->dev,
&fxxxx_in_attr[i].dev_attr);
}
}
if (f71882fg_has_in1_alarm[data->type]) {
f71882fg_remove_sysfs_files(pdev,
fxxxx_in1_alarm_attr,
ARRAY_SIZE(fxxxx_in1_alarm_attr));
}
}
if (start_reg & 0x02) {
f71882fg_remove_sysfs_files(pdev, &fxxxx_fan_attr[0][0],
ARRAY_SIZE(fxxxx_fan_attr[0]) * nr_fans);
if (f71882fg_fan_has_beep[data->type]) {
f71882fg_remove_sysfs_files(pdev,
fxxxx_fan_beep_attr, nr_fans);
}
switch (data->type) {
case f71808a:
f71882fg_remove_sysfs_files(pdev,
&fxxxx_auto_pwm_attr[0][0],
ARRAY_SIZE(fxxxx_auto_pwm_attr[0]) * nr_fans);
f71882fg_remove_sysfs_files(pdev,
f71808a_fan3_attr,
ARRAY_SIZE(f71808a_fan3_attr));
break;
case f71862fg:
f71882fg_remove_sysfs_files(pdev,
&f71862fg_auto_pwm_attr[0][0],
ARRAY_SIZE(f71862fg_auto_pwm_attr[0]) *
nr_fans);
break;
case f71808e:
case f71869:
f71882fg_remove_sysfs_files(pdev,
&f71869_auto_pwm_attr[0][0],
ARRAY_SIZE(f71869_auto_pwm_attr[0]) * nr_fans);
break;
case f8000:
f71882fg_remove_sysfs_files(pdev,
f8000_fan_attr,
ARRAY_SIZE(f8000_fan_attr));
f71882fg_remove_sysfs_files(pdev,
&f8000_auto_pwm_attr[0][0],
ARRAY_SIZE(f8000_auto_pwm_attr[0]) * nr_fans);
break;
default:
f71882fg_remove_sysfs_files(pdev,
&fxxxx_auto_pwm_attr[0][0],
ARRAY_SIZE(fxxxx_auto_pwm_attr[0]) * nr_fans);
}
}
return 0;
}
static int __init f71882fg_find(int sioaddr, struct f71882fg_sio_data *sio_data)
{
u16 devid;
unsigned short address;
int err = superio_enter(sioaddr);
if (err)
return err;
devid = superio_inw(sioaddr, SIO_REG_MANID);
if (devid != SIO_FINTEK_ID) {
pr_debug("Not a Fintek device\n");
err = -ENODEV;
goto exit;
}
devid = force_id ? force_id : superio_inw(sioaddr, SIO_REG_DEVID);
switch (devid) {
case SIO_F71808E_ID:
sio_data->type = f71808e;
break;
case SIO_F71808A_ID:
sio_data->type = f71808a;
break;
case SIO_F71858_ID:
sio_data->type = f71858fg;
break;
case SIO_F71862_ID:
sio_data->type = f71862fg;
break;
case SIO_F71869_ID:
sio_data->type = f71869;
break;
case SIO_F71869A_ID:
sio_data->type = f71869a;
break;
case SIO_F71882_ID:
sio_data->type = f71882fg;
break;
case SIO_F71889_ID:
sio_data->type = f71889fg;
break;
case SIO_F71889E_ID:
sio_data->type = f71889ed;
break;
case SIO_F71889A_ID:
sio_data->type = f71889a;
break;
case SIO_F8000_ID:
sio_data->type = f8000;
break;
case SIO_F81865_ID:
sio_data->type = f81865f;
break;
default:
pr_info("Unsupported Fintek device: %04x\n",
(unsigned int)devid);
err = -ENODEV;
goto exit;
}
if (sio_data->type == f71858fg)
superio_select(sioaddr, SIO_F71858FG_LD_HWM);
else
superio_select(sioaddr, SIO_F71882FG_LD_HWM);
if (!(superio_inb(sioaddr, SIO_REG_ENABLE) & 0x01)) {
pr_warn("Device not activated\n");
err = -ENODEV;
goto exit;
}
address = superio_inw(sioaddr, SIO_REG_ADDR);
if (address == 0) {
pr_warn("Base address not set\n");
err = -ENODEV;
goto exit;
}
address &= ~(REGION_LENGTH - 1); /* Ignore 3 LSB */
err = address;
pr_info("Found %s chip at %#x, revision %d\n",
f71882fg_names[sio_data->type], (unsigned int)address,
(int)superio_inb(sioaddr, SIO_REG_DEVREV));
exit:
superio_exit(sioaddr);
return err;
}
static int __init f71882fg_device_add(int address,
const struct f71882fg_sio_data *sio_data)
{
struct resource res = {
.start = address,
.end = address + REGION_LENGTH - 1,
.flags = IORESOURCE_IO,
};
int err;
f71882fg_pdev = platform_device_alloc(DRVNAME, address);
if (!f71882fg_pdev)
return -ENOMEM;
res.name = f71882fg_pdev->name;
err = acpi_check_resource_conflict(&res);
if (err)
goto exit_device_put;
err = platform_device_add_resources(f71882fg_pdev, &res, 1);
if (err) {
pr_err("Device resource addition failed\n");
goto exit_device_put;
}
err = platform_device_add_data(f71882fg_pdev, sio_data,
sizeof(struct f71882fg_sio_data));
if (err) {
pr_err("Platform data allocation failed\n");
goto exit_device_put;
}
err = platform_device_add(f71882fg_pdev);
if (err) {
pr_err("Device addition failed\n");
goto exit_device_put;
}
return 0;
exit_device_put:
platform_device_put(f71882fg_pdev);
return err;
}
static int __init f71882fg_init(void)
{
int err;
int address;
struct f71882fg_sio_data sio_data;
memset(&sio_data, 0, sizeof(sio_data));
address = f71882fg_find(0x2e, &sio_data);
if (address < 0)
address = f71882fg_find(0x4e, &sio_data);
if (address < 0)
return address;
err = platform_driver_register(&f71882fg_driver);
if (err)
return err;
err = f71882fg_device_add(address, &sio_data);
if (err)
goto exit_driver;
return 0;
exit_driver:
platform_driver_unregister(&f71882fg_driver);
return err;
}
static void __exit f71882fg_exit(void)
{
platform_device_unregister(f71882fg_pdev);
platform_driver_unregister(&f71882fg_driver);
}
MODULE_DESCRIPTION("F71882FG Hardware Monitoring Driver");
MODULE_AUTHOR("Hans Edgington, Hans de Goede <hdegoede@redhat.com>");
MODULE_LICENSE("GPL");
module_init(f71882fg_init);
module_exit(f71882fg_exit);
| gpl-2.0 |
CyanogenMod/android_kernel_lge_v500 | drivers/mfd/marimba-codec.c | 3494 | 23492 | /* Copyright (c) 2009-2010, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/platform_device.h>
#include <linux/mfd/msm-adie-codec.h>
#include <linux/mfd/marimba.h>
#include <linux/debugfs.h>
#include <linux/uaccess.h>
#include <linux/string.h>
#define MARIMBA_CDC_RX_CTL 0x81
#define MARIMBA_CDC_RX_CTL_ST_EN_MASK 0x20
#define MARIMBA_CDC_RX_CTL_ST_EN_SHFT 0x5
#define MARIMBA_CODEC_CDC_LRXG 0x84
#define MARIMBA_CODEC_CDC_RRXG 0x85
#define MARIMBA_CODEC_CDC_LTXG 0x86
#define MARIMBA_CODEC_CDC_RTXG 0x87
#define MAX_MDELAY_US 2000
#define MIN_MDELAY_US 1000
struct adie_codec_path {
struct adie_codec_dev_profile *profile;
struct adie_codec_register_image img;
u32 hwsetting_idx;
u32 stage_idx;
u32 curr_stage;
};
static struct adie_codec_register adie_codec_tx_regs[] = {
{ 0x04, 0xc0, 0x8C },
{ 0x0D, 0xFF, 0x00 },
{ 0x0E, 0xFF, 0x00 },
{ 0x0F, 0xFF, 0x00 },
{ 0x10, 0xF8, 0x68 },
{ 0x11, 0xFE, 0x00 },
{ 0x12, 0xFE, 0x00 },
{ 0x13, 0xFF, 0x58 },
{ 0x14, 0xFF, 0x00 },
{ 0x15, 0xFE, 0x00 },
{ 0x16, 0xFF, 0x00 },
{ 0x1A, 0xFF, 0x00 },
{ 0x80, 0x01, 0x00 },
{ 0x82, 0x7F, 0x18 },
{ 0x83, 0x1C, 0x00 },
{ 0x86, 0xFF, 0xAC },
{ 0x87, 0xFF, 0xAC },
{ 0x89, 0xFF, 0xFF },
{ 0x8A, 0xF0, 0x30 }
};
static struct adie_codec_register adie_codec_rx_regs[] = {
{ 0x23, 0xF8, 0x00 },
{ 0x24, 0x6F, 0x00 },
{ 0x25, 0x7F, 0x00 },
{ 0x26, 0xFC, 0x00 },
{ 0x28, 0xFE, 0x00 },
{ 0x29, 0xFE, 0x00 },
{ 0x33, 0xFF, 0x00 },
{ 0x34, 0xFF, 0x00 },
{ 0x35, 0xFC, 0x00 },
{ 0x36, 0xFE, 0x00 },
{ 0x37, 0xFE, 0x00 },
{ 0x38, 0xFE, 0x00 },
{ 0x39, 0xF0, 0x00 },
{ 0x3A, 0xFF, 0x0A },
{ 0x3B, 0xFC, 0xAC },
{ 0x3C, 0xFC, 0xAC },
{ 0x3D, 0xFF, 0x55 },
{ 0x3E, 0xFF, 0x55 },
{ 0x3F, 0xCF, 0x00 },
{ 0x40, 0x3F, 0x00 },
{ 0x41, 0x3F, 0x00 },
{ 0x42, 0xFF, 0x00 },
{ 0x43, 0xF7, 0x00 },
{ 0x43, 0xF7, 0x00 },
{ 0x43, 0xF7, 0x00 },
{ 0x43, 0xF7, 0x00 },
{ 0x44, 0xF7, 0x00 },
{ 0x45, 0xFF, 0x00 },
{ 0x46, 0xFF, 0x00 },
{ 0x47, 0xF7, 0x00 },
{ 0x48, 0xF7, 0x00 },
{ 0x49, 0xFF, 0x00 },
{ 0x4A, 0xFF, 0x00 },
{ 0x80, 0x02, 0x00 },
{ 0x81, 0xFF, 0x4C },
{ 0x83, 0x23, 0x00 },
{ 0x84, 0xFF, 0xAC },
{ 0x85, 0xFF, 0xAC },
{ 0x88, 0xFF, 0xFF },
{ 0x8A, 0x0F, 0x03 },
{ 0x8B, 0xFF, 0xAC },
{ 0x8C, 0x03, 0x01 },
{ 0x8D, 0xFF, 0x00 },
{ 0x8E, 0xFF, 0x00 }
};
static struct adie_codec_register adie_codec_lb_regs[] = {
{ 0x2B, 0x8F, 0x02 },
{ 0x2C, 0x8F, 0x02 }
};
struct adie_codec_state {
struct adie_codec_path path[ADIE_CODEC_MAX];
u32 ref_cnt;
struct marimba *pdrv_ptr;
struct marimba_codec_platform_data *codec_pdata;
struct mutex lock;
};
static struct adie_codec_state adie_codec;
/* Array containing write details of Tx and RX Digital Volume
Tx and Rx and both the left and right channel use the same data
*/
u8 adie_codec_rx_tx_dig_vol_data[] = {
0x81, 0x82, 0x83, 0x84,
0x85, 0x86, 0x87, 0x88,
0x89, 0x8a, 0x8b, 0x8c,
0x8d, 0x8e, 0x8f, 0x90,
0x91, 0x92, 0x93, 0x94,
0x95, 0x96, 0x97, 0x98,
0x99, 0x9a, 0x9b, 0x9c,
0x9d, 0x9e, 0x9f, 0xa0,
0xa1, 0xa2, 0xa3, 0xa4,
0xa5, 0xa6, 0xa7, 0xa8,
0xa9, 0xaa, 0xab, 0xac,
0xad, 0xae, 0xaf, 0xb0,
0xb1, 0xb2, 0xb3, 0xb4,
0xb5, 0xb6, 0xb7, 0xb8,
0xb9, 0xba, 0xbb, 0xbc,
0xbd, 0xbe, 0xbf, 0xc0,
0xc1, 0xc2, 0xc3, 0xc4,
0xc5, 0xc6, 0xc7, 0xc8,
0xc9, 0xca, 0xcb, 0xcc,
0xcd, 0xce, 0xcf, 0xd0,
0xd1, 0xd2, 0xd3, 0xd4,
0xd5, 0xd6, 0xd7, 0xd8,
0xd9, 0xda, 0xdb, 0xdc,
0xdd, 0xde, 0xdf, 0xe0,
0xe1, 0xe2, 0xe3, 0xe4,
0xe5, 0xe6, 0xe7, 0xe8,
0xe9, 0xea, 0xeb, 0xec,
0xed, 0xee, 0xf0, 0xf1,
0xf2, 0xf3, 0xf4, 0xf5,
0xf6, 0xf7, 0xf8, 0xf9,
0xfa, 0xfb, 0xfc, 0xfd,
0xfe, 0xff, 0x00, 0x01,
0x02, 0x03, 0x04, 0x05,
0x06, 0x07, 0x08, 0x09,
0x0a, 0x0b, 0x0c, 0x0d,
0x0e, 0x0f, 0x10, 0x11,
0x12, 0x13, 0x14, 0x15,
0x16, 0x17, 0x18, 0x19,
0x1a, 0x1b, 0x1c, 0x1d,
0x1e, 0x1f, 0x20, 0x21,
0x22, 0x23, 0x24, 0x25,
0x26, 0x27, 0x28, 0x29,
0x2a, 0x2b, 0x2c, 0x2d,
0x2e, 0x2f, 0x30, 0x31,
0x32, 0x33, 0x34, 0x35,
0x36, 0x37, 0x38, 0x39,
0x3a, 0x3b, 0x3c, 0x3d,
0x3e, 0x3f, 0x40, 0x41,
0x42, 0x43, 0x44, 0x45,
0x46, 0x47, 0x48, 0x49,
0x4a, 0x4b, 0x4c, 0x4d,
0x4e, 0x4f, 0x50, 0x51,
0x52, 0x53, 0x54, 0x55,
0x56, 0x57, 0x58, 0x59,
0x5a, 0x5b, 0x5c, 0x5d,
0x5e, 0x5f, 0x60, 0x61,
0x62, 0x63, 0x64, 0x65,
0x66, 0x67, 0x68, 0x69,
0x6a, 0x6b, 0x6c, 0x6d,
0x6e, 0x6f, 0x70, 0x71,
0x72, 0x73, 0x74, 0x75,
0x76, 0x77, 0x78, 0x79,
0x7a, 0x7b, 0x7c, 0x7d,
0x7e, 0x7f
};
enum adie_vol_type {
ADIE_CODEC_RX_DIG_VOL,
ADIE_CODEC_TX_DIG_VOL,
ADIE_CODEC_VOL_TYPE_MAX
};
struct adie_codec_ch_vol_cntrl {
u8 codec_reg;
u8 codec_mask;
u8 *vol_cntrl_data;
};
struct adie_codec_vol_cntrl_data {
enum adie_vol_type vol_type;
/* Jump length used while doing writes in incremental fashion */
u32 jump_length;
s32 min_mb; /* Min Db applicable to the vol control */
s32 max_mb; /* Max Db applicable to the vol control */
u32 step_in_mb;
u32 steps; /* No of steps allowed for this vol type */
struct adie_codec_ch_vol_cntrl *ch_vol_cntrl_info;
};
static struct adie_codec_ch_vol_cntrl adie_codec_rx_vol_cntrl[] = {
{MARIMBA_CODEC_CDC_LRXG, 0xff, adie_codec_rx_tx_dig_vol_data},
{MARIMBA_CODEC_CDC_RRXG, 0xff, adie_codec_rx_tx_dig_vol_data}
};
static struct adie_codec_ch_vol_cntrl adie_codec_tx_vol_cntrl[] = {
{MARIMBA_CODEC_CDC_LTXG, 0xff, adie_codec_rx_tx_dig_vol_data},
{MARIMBA_CODEC_CDC_RTXG, 0xff, adie_codec_rx_tx_dig_vol_data}
};
static struct adie_codec_vol_cntrl_data adie_codec_vol_cntrl[] = {
{ADIE_CODEC_RX_DIG_VOL, 5100, -12700, 12700, 100, 255,
adie_codec_rx_vol_cntrl},
{ADIE_CODEC_TX_DIG_VOL, 5100, -12700, 12700, 100, 255,
adie_codec_tx_vol_cntrl}
};
static int adie_codec_write(u8 reg, u8 mask, u8 val)
{
int rc;
rc = marimba_write_bit_mask(adie_codec.pdrv_ptr, reg, &val, 1, mask);
if (IS_ERR_VALUE(rc)) {
pr_err("%s: fail to write reg %x\n", __func__, reg);
return -EIO;
}
pr_debug("%s: write reg %x val %x\n", __func__, reg, val);
return 0;
}
static int adie_codec_read(u8 reg, u8 *val)
{
return marimba_read(adie_codec.pdrv_ptr, reg, val, 1);
}
static int adie_codec_read_dig_vol(enum adie_vol_type vol_type, u32 chan_index,
u32 *cur_index)
{
u32 counter;
u32 size;
u8 reg, mask, cur_val;
int rc;
reg =
adie_codec_vol_cntrl[vol_type].
ch_vol_cntrl_info[chan_index].codec_reg;
mask =
adie_codec_vol_cntrl[vol_type].
ch_vol_cntrl_info[chan_index].codec_mask;
rc = marimba_read(adie_codec.pdrv_ptr, reg, &cur_val, 1);
if (IS_ERR_VALUE(rc)) {
pr_err("%s: fail to read reg %x\n", __func__, reg);
return -EIO;
}
cur_val = cur_val & mask;
pr_debug("%s: reg 0x%x mask 0x%x reg_value = 0x%x"
"vol_type = %d\n", __func__, reg, mask, cur_val, vol_type);
size = adie_codec_vol_cntrl[vol_type].steps;
for (counter = 0; counter <= size; counter++) {
if (adie_codec_vol_cntrl[vol_type].ch_vol_cntrl_info
[chan_index].vol_cntrl_data[counter] == cur_val) {
*cur_index = counter;
return 0;
}
}
pr_err("%s: could not find 0x%x in reg 0x%x values array\n",
__func__, cur_val, reg);
return -EINVAL;;
}
static int adie_codec_set_dig_vol(enum adie_vol_type vol_type, u32 chan_index,
u32 cur_index, u32 target_index)
{
u32 count;
u8 reg, mask, val;
u32 i;
u32 index;
u32 index_jump;
int rc;
index_jump = adie_codec_vol_cntrl[vol_type].jump_length;
reg =
adie_codec_vol_cntrl[vol_type].
ch_vol_cntrl_info[chan_index].codec_reg;
mask =
adie_codec_vol_cntrl[vol_type].
ch_vol_cntrl_info[chan_index].codec_mask;
/* compare the target index with current index */
if (cur_index < target_index) {
/* Volume is being increased loop and increase it in 4-5 steps
*/
count = ((target_index - cur_index) * 100 / index_jump);
index = cur_index;
for (i = 1; i <= count; i++) {
index = index + (int)(index_jump / 100);
val =
adie_codec_vol_cntrl[vol_type].ch_vol_cntrl_info
[chan_index].vol_cntrl_data[index];
pr_debug("%s: write reg %x val 0x%x\n",
__func__, reg, val);
rc = adie_codec_write(reg, mask, val);
if (rc < 0) {
pr_err("%s: write reg %x val 0x%x failed\n",
__func__, reg, val);
return rc;
}
}
/*do one final write to take it to the target index level */
val =
adie_codec_vol_cntrl[vol_type].ch_vol_cntrl_info
[chan_index].vol_cntrl_data[target_index];
pr_debug("%s: write reg %x val 0x%x\n", __func__, reg, val);
rc = adie_codec_write(reg, mask, val);
if (rc < 0) {
pr_err("%s: write reg %x val 0x%x failed\n",
__func__, reg, val);
return rc;
}
} else {
/* Volume is being decreased from the current setting */
index = cur_index;
/* loop and decrease it in 4-5 steps */
count = ((cur_index - target_index) * 100 / index_jump);
for (i = 1; i <= count; i++) {
index = index - (int)(index_jump / 100);
val =
adie_codec_vol_cntrl[vol_type].ch_vol_cntrl_info
[chan_index].vol_cntrl_data[index];
pr_debug("%s: write reg %x val 0x%x\n",
__func__, reg, val);
rc = adie_codec_write(reg, mask, val);
if (rc < 0) {
pr_err("%s: write reg %x val 0x%x failed\n",
__func__, reg, val);
return rc;
}
}
/* do one final write to take it to the target index level */
val =
adie_codec_vol_cntrl[vol_type].ch_vol_cntrl_info
[chan_index].vol_cntrl_data[target_index];
pr_debug("%s: write reg %x val 0x%x\n", __func__, reg, val);
rc = adie_codec_write(reg, mask, val);
if (rc < 0) {
pr_err("%s: write reg %x val 0x%x failed\n",
__func__, reg, val);
return rc;
}
}
return 0;
}
static int marimba_adie_codec_set_device_digital_volume(
struct adie_codec_path *path_ptr,
u32 num_channels, u32 vol_percentage /* in percentage */)
{
enum adie_vol_type vol_type;
s32 milli_bel;
u32 chan_index;
u32 step_index;
u32 cur_step_index = 0;
if (!path_ptr || (path_ptr->curr_stage !=
ADIE_CODEC_DIGITAL_ANALOG_READY)) {
pr_info("%s: Marimba codec not ready for volume control\n",
__func__);
return -EPERM;
}
if (num_channels > 2) {
pr_err("%s: Marimba codec only supports max two channels\n",
__func__);
return -EINVAL;
}
if (path_ptr->profile->path_type == ADIE_CODEC_RX)
vol_type = ADIE_CODEC_RX_DIG_VOL;
else if (path_ptr->profile->path_type == ADIE_CODEC_TX)
vol_type = ADIE_CODEC_TX_DIG_VOL;
else {
pr_err("%s: invalid device data neither RX nor TX\n",
__func__);
return -EINVAL;
}
milli_bel = ((adie_codec_vol_cntrl[vol_type].max_mb -
adie_codec_vol_cntrl[vol_type].min_mb) *
vol_percentage) / 100;
milli_bel = adie_codec_vol_cntrl[vol_type].min_mb + milli_bel;
pr_debug("%s: milli bell = %d vol_type = %d vol_percentage = %d"
" num_cha = %d \n",
__func__, milli_bel, vol_type, vol_percentage, num_channels);
step_index = ((milli_bel
- adie_codec_vol_cntrl[vol_type].min_mb
+ (adie_codec_vol_cntrl[vol_type].step_in_mb / 2))
/ adie_codec_vol_cntrl[vol_type].step_in_mb);
for (chan_index = 0; chan_index < num_channels; chan_index++) {
adie_codec_read_dig_vol(vol_type, chan_index, &cur_step_index);
pr_debug("%s: cur_step_index = %u current vol = 0x%x\n",
__func__, cur_step_index,
adie_codec_vol_cntrl[vol_type].ch_vol_cntrl_info
[chan_index].vol_cntrl_data[cur_step_index]);
pr_debug("%s: step index = %u new volume = 0x%x\n",
__func__, step_index,
adie_codec_vol_cntrl[vol_type].ch_vol_cntrl_info
[chan_index].vol_cntrl_data[step_index]);
adie_codec_set_dig_vol(vol_type, chan_index, cur_step_index,
step_index);
}
return 0;
}
static int marimba_adie_codec_setpath(struct adie_codec_path *path_ptr,
u32 freq_plan, u32 osr)
{
int rc = 0;
u32 i, freq_idx = 0, freq = 0;
if ((path_ptr->curr_stage != ADIE_CODEC_DIGITAL_OFF) &&
(path_ptr->curr_stage != ADIE_CODEC_FLASH_IMAGE)) {
rc = -EBUSY;
goto error;
}
for (i = 0; i < path_ptr->profile->setting_sz; i++) {
if (path_ptr->profile->settings[i].osr == osr) {
if (path_ptr->profile->settings[i].freq_plan >=
freq_plan) {
if (freq == 0) {
freq = path_ptr->profile->settings[i].
freq_plan;
freq_idx = i;
} else if (path_ptr->profile->settings[i].
freq_plan < freq) {
freq = path_ptr->profile->settings[i].
freq_plan;
freq_idx = i;
}
}
}
}
if (freq_idx >= path_ptr->profile->setting_sz)
rc = -ENODEV;
else {
path_ptr->hwsetting_idx = freq_idx;
path_ptr->stage_idx = 0;
}
error:
return rc;
}
static u32 marimba_adie_codec_freq_supported(
struct adie_codec_dev_profile *profile,
u32 requested_freq)
{
u32 i, rc = -EINVAL;
for (i = 0; i < profile->setting_sz; i++) {
if (profile->settings[i].freq_plan >= requested_freq) {
rc = 0;
break;
}
}
return rc;
}
static int marimba_adie_codec_enable_sidetone(
struct adie_codec_path *rx_path_ptr,
u32 enable)
{
int rc = 0;
pr_debug("%s()\n", __func__);
mutex_lock(&adie_codec.lock);
if (!rx_path_ptr || &adie_codec.path[ADIE_CODEC_RX] != rx_path_ptr) {
pr_err("%s: invalid path pointer\n", __func__);
rc = -EINVAL;
goto error;
} else if (rx_path_ptr->curr_stage !=
ADIE_CODEC_DIGITAL_ANALOG_READY) {
pr_err("%s: bad state\n", __func__);
rc = -EPERM;
goto error;
}
if (enable)
rc = adie_codec_write(MARIMBA_CDC_RX_CTL,
MARIMBA_CDC_RX_CTL_ST_EN_MASK,
(0x1 << MARIMBA_CDC_RX_CTL_ST_EN_SHFT));
else
rc = adie_codec_write(MARIMBA_CDC_RX_CTL,
MARIMBA_CDC_RX_CTL_ST_EN_MASK, 0);
error:
mutex_unlock(&adie_codec.lock);
return rc;
}
static void adie_codec_reach_stage_action(struct adie_codec_path *path_ptr,
u32 stage)
{
u32 iter;
struct adie_codec_register *reg_info;
if (stage == ADIE_CODEC_FLASH_IMAGE) {
/* perform reimage */
for (iter = 0; iter < path_ptr->img.img_sz; iter++) {
reg_info = &path_ptr->img.regs[iter];
adie_codec_write(reg_info->reg,
reg_info->mask, reg_info->val);
}
}
}
static int marimba_adie_codec_proceed_stage(struct adie_codec_path *path_ptr,
u32 state)
{
int rc = 0, loop_exit = 0;
struct adie_codec_action_unit *curr_action;
struct adie_codec_hwsetting_entry *setting;
u8 reg, mask, val;
mutex_lock(&adie_codec.lock);
setting = &path_ptr->profile->settings[path_ptr->hwsetting_idx];
while (!loop_exit) {
curr_action = &setting->actions[path_ptr->stage_idx];
switch (curr_action->type) {
case ADIE_CODEC_ACTION_ENTRY:
ADIE_CODEC_UNPACK_ENTRY(curr_action->action,
reg, mask, val);
adie_codec_write(reg, mask, val);
break;
case ADIE_CODEC_ACTION_DELAY_WAIT:
if (curr_action->action > MAX_MDELAY_US)
msleep(curr_action->action/1000);
else if (curr_action->action < MIN_MDELAY_US)
udelay(curr_action->action);
else
mdelay(curr_action->action/1000);
break;
case ADIE_CODEC_ACTION_STAGE_REACHED:
adie_codec_reach_stage_action(path_ptr,
curr_action->action);
if (curr_action->action == state) {
path_ptr->curr_stage = state;
loop_exit = 1;
}
break;
default:
BUG();
}
path_ptr->stage_idx++;
if (path_ptr->stage_idx == setting->action_sz)
path_ptr->stage_idx = 0;
}
mutex_unlock(&adie_codec.lock);
return rc;
}
static void marimba_codec_bring_up(void)
{
/* bring up sequence for Marimba codec core
* ensure RESET_N = 0 and GDFS_CLAMP_EN=1 -
* set GDFS_EN_FEW=1 then GDFS_EN_REST=1 then
* GDFS_CLAMP_EN = 0 and finally RESET_N = 1
* Marimba codec bring up should use the Marimba
* slave address after which the codec slave
* address can be used
*/
/* Bring up codec */
adie_codec_write(0xFF, 0xFF, 0x08);
/* set GDFS_EN_FEW=1 */
adie_codec_write(0xFF, 0xFF, 0x0a);
/* set GDFS_EN_REST=1 */
adie_codec_write(0xFF, 0xFF, 0x0e);
/* set RESET_N=1 */
adie_codec_write(0xFF, 0xFF, 0x07);
adie_codec_write(0xFF, 0xFF, 0x17);
/* enable band gap */
adie_codec_write(0x03, 0xFF, 0x04);
/* dither delay selected and dmic gain stage bypassed */
adie_codec_write(0x8F, 0xFF, 0x44);
}
static void marimba_codec_bring_down(void)
{
adie_codec_write(0xFF, 0xFF, 0x07);
adie_codec_write(0xFF, 0xFF, 0x06);
adie_codec_write(0xFF, 0xFF, 0x0e);
adie_codec_write(0xFF, 0xFF, 0x08);
adie_codec_write(0x03, 0xFF, 0x00);
}
static int marimba_adie_codec_open(struct adie_codec_dev_profile *profile,
struct adie_codec_path **path_pptr)
{
int rc = 0;
mutex_lock(&adie_codec.lock);
if (!profile || !path_pptr) {
rc = -EINVAL;
goto error;
}
if (adie_codec.path[profile->path_type].profile) {
rc = -EBUSY;
goto error;
}
if (!adie_codec.ref_cnt) {
if (adie_codec.codec_pdata &&
adie_codec.codec_pdata->marimba_codec_power) {
rc = adie_codec.codec_pdata->marimba_codec_power(1);
if (rc) {
pr_err("%s: could not power up marimba "
"codec\n", __func__);
goto error;
}
}
marimba_codec_bring_up();
}
adie_codec.path[profile->path_type].profile = profile;
*path_pptr = (void *) &adie_codec.path[profile->path_type];
adie_codec.ref_cnt++;
adie_codec.path[profile->path_type].hwsetting_idx = 0;
adie_codec.path[profile->path_type].curr_stage = ADIE_CODEC_FLASH_IMAGE;
adie_codec.path[profile->path_type].stage_idx = 0;
error:
mutex_unlock(&adie_codec.lock);
return rc;
}
static int marimba_adie_codec_close(struct adie_codec_path *path_ptr)
{
int rc = 0;
mutex_lock(&adie_codec.lock);
if (!path_ptr) {
rc = -EINVAL;
goto error;
}
if (path_ptr->curr_stage != ADIE_CODEC_DIGITAL_OFF)
adie_codec_proceed_stage(path_ptr, ADIE_CODEC_DIGITAL_OFF);
BUG_ON(!adie_codec.ref_cnt);
path_ptr->profile = NULL;
adie_codec.ref_cnt--;
if (!adie_codec.ref_cnt) {
marimba_codec_bring_down();
if (adie_codec.codec_pdata &&
adie_codec.codec_pdata->marimba_codec_power) {
rc = adie_codec.codec_pdata->marimba_codec_power(0);
if (rc) {
pr_err("%s: could not power down marimba "
"codec\n", __func__);
goto error;
}
}
}
error:
mutex_unlock(&adie_codec.lock);
return rc;
}
static const struct adie_codec_operations marimba_adie_ops = {
.codec_id = MARIMBA_ID,
.codec_open = marimba_adie_codec_open,
.codec_close = marimba_adie_codec_close,
.codec_setpath = marimba_adie_codec_setpath,
.codec_proceed_stage = marimba_adie_codec_proceed_stage,
.codec_freq_supported = marimba_adie_codec_freq_supported,
.codec_enable_sidetone = marimba_adie_codec_enable_sidetone,
.codec_set_device_digital_volume =
marimba_adie_codec_set_device_digital_volume,
};
#ifdef CONFIG_DEBUG_FS
static struct dentry *debugfs_marimba_dent;
static struct dentry *debugfs_peek;
static struct dentry *debugfs_poke;
static struct dentry *debugfs_power;
static unsigned char read_data;
static int codec_debug_open(struct inode *inode, struct file *file)
{
file->private_data = inode->i_private;
return 0;
}
static int get_parameters(char *buf, long int *param1, int num_of_par)
{
char *token;
int base, cnt;
token = strsep(&buf, " ");
for (cnt = 0; cnt < num_of_par; cnt++) {
if (token != NULL) {
if ((token[1] == 'x') || (token[1] == 'X'))
base = 16;
else
base = 10;
if (strict_strtoul(token, base, ¶m1[cnt]) != 0)
return -EINVAL;
token = strsep(&buf, " ");
}
else
return -EINVAL;
}
return 0;
}
static ssize_t codec_debug_read(struct file *file, char __user *ubuf,
size_t count, loff_t *ppos)
{
char lbuf[8];
snprintf(lbuf, sizeof(lbuf), "0x%x\n", read_data);
return simple_read_from_buffer(ubuf, count, ppos, lbuf, strlen(lbuf));
}
static ssize_t codec_debug_write(struct file *filp,
const char __user *ubuf, size_t cnt, loff_t *ppos)
{
char *access_str = filp->private_data;
char lbuf[32];
int rc;
long int param[5];
if (cnt > sizeof(lbuf) - 1)
return -EINVAL;
rc = copy_from_user(lbuf, ubuf, cnt);
if (rc)
return -EFAULT;
lbuf[cnt] = '\0';
if (!strcmp(access_str, "power")) {
if (get_parameters(lbuf, param, 1) == 0) {
switch (param[0]) {
case 1:
adie_codec.codec_pdata->marimba_codec_power(1);
marimba_codec_bring_up();
break;
case 0:
marimba_codec_bring_down();
adie_codec.codec_pdata->marimba_codec_power(0);
break;
default:
rc = -EINVAL;
break;
}
} else
rc = -EINVAL;
} else if (!strcmp(access_str, "poke")) {
/* write */
rc = get_parameters(lbuf, param, 2);
if ((param[0] <= 0xFF) && (param[1] <= 0xFF) &&
(rc == 0))
adie_codec_write(param[0], 0xFF, param[1]);
else
rc = -EINVAL;
} else if (!strcmp(access_str, "peek")) {
/* read */
rc = get_parameters(lbuf, param, 1);
if ((param[0] <= 0xFF) && (rc == 0))
adie_codec_read(param[0], &read_data);
else
rc = -EINVAL;
}
if (rc == 0)
rc = cnt;
else
pr_err("%s: rc = %d\n", __func__, rc);
return rc;
}
static const struct file_operations codec_debug_ops = {
.open = codec_debug_open,
.write = codec_debug_write,
.read = codec_debug_read
};
#endif
static int marimba_codec_probe(struct platform_device *pdev)
{
int rc;
adie_codec.pdrv_ptr = platform_get_drvdata(pdev);
adie_codec.codec_pdata = pdev->dev.platform_data;
if (adie_codec.codec_pdata->snddev_profile_init)
adie_codec.codec_pdata->snddev_profile_init();
/* Register the marimba ADIE operations */
rc = adie_codec_register_codec_operations(&marimba_adie_ops);
#ifdef CONFIG_DEBUG_FS
debugfs_marimba_dent = debugfs_create_dir("msm_adie_codec", 0);
if (!IS_ERR(debugfs_marimba_dent)) {
debugfs_peek = debugfs_create_file("peek",
S_IFREG | S_IRUGO, debugfs_marimba_dent,
(void *) "peek", &codec_debug_ops);
debugfs_poke = debugfs_create_file("poke",
S_IFREG | S_IRUGO, debugfs_marimba_dent,
(void *) "poke", &codec_debug_ops);
debugfs_power = debugfs_create_file("power",
S_IFREG | S_IRUGO, debugfs_marimba_dent,
(void *) "power", &codec_debug_ops);
}
#endif
return rc;
}
static struct platform_driver marimba_codec_driver = {
.probe = marimba_codec_probe,
.driver = {
.name = "marimba_codec",
.owner = THIS_MODULE,
},
};
static int __init marimba_codec_init(void)
{
s32 rc;
rc = platform_driver_register(&marimba_codec_driver);
if (IS_ERR_VALUE(rc))
goto error;
adie_codec.path[ADIE_CODEC_TX].img.regs = adie_codec_tx_regs;
adie_codec.path[ADIE_CODEC_TX].img.img_sz =
ARRAY_SIZE(adie_codec_tx_regs);
adie_codec.path[ADIE_CODEC_RX].img.regs = adie_codec_rx_regs;
adie_codec.path[ADIE_CODEC_RX].img.img_sz =
ARRAY_SIZE(adie_codec_rx_regs);
adie_codec.path[ADIE_CODEC_LB].img.regs = adie_codec_lb_regs;
adie_codec.path[ADIE_CODEC_LB].img.img_sz =
ARRAY_SIZE(adie_codec_lb_regs);
mutex_init(&adie_codec.lock);
error:
return rc;
}
static void __exit marimba_codec_exit(void)
{
#ifdef CONFIG_DEBUG_FS
debugfs_remove(debugfs_peek);
debugfs_remove(debugfs_poke);
debugfs_remove(debugfs_power);
debugfs_remove(debugfs_marimba_dent);
#endif
platform_driver_unregister(&marimba_codec_driver);
}
module_init(marimba_codec_init);
module_exit(marimba_codec_exit);
MODULE_DESCRIPTION("Marimba codec driver");
MODULE_VERSION("1.0");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
hiikezoe/android_kernel_nec_n06e | drivers/acpi/ac.c | 3494 | 9450 | /*
* acpi_ac.c - ACPI AC Adapter Driver ($Revision: 27 $)
*
* Copyright (C) 2001, 2002 Andy Grover <andrew.grover@intel.com>
* Copyright (C) 2001, 2002 Paul Diefenbaugh <paul.s.diefenbaugh@intel.com>
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/types.h>
#ifdef CONFIG_ACPI_PROCFS_POWER
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#endif
#include <linux/power_supply.h>
#include <acpi/acpi_bus.h>
#include <acpi/acpi_drivers.h>
#define PREFIX "ACPI: "
#define ACPI_AC_CLASS "ac_adapter"
#define ACPI_AC_DEVICE_NAME "AC Adapter"
#define ACPI_AC_FILE_STATE "state"
#define ACPI_AC_NOTIFY_STATUS 0x80
#define ACPI_AC_STATUS_OFFLINE 0x00
#define ACPI_AC_STATUS_ONLINE 0x01
#define ACPI_AC_STATUS_UNKNOWN 0xFF
#define _COMPONENT ACPI_AC_COMPONENT
ACPI_MODULE_NAME("ac");
MODULE_AUTHOR("Paul Diefenbaugh");
MODULE_DESCRIPTION("ACPI AC Adapter Driver");
MODULE_LICENSE("GPL");
#ifdef CONFIG_ACPI_PROCFS_POWER
extern struct proc_dir_entry *acpi_lock_ac_dir(void);
extern void *acpi_unlock_ac_dir(struct proc_dir_entry *acpi_ac_dir);
static int acpi_ac_open_fs(struct inode *inode, struct file *file);
#endif
static int acpi_ac_add(struct acpi_device *device);
static int acpi_ac_remove(struct acpi_device *device, int type);
static int acpi_ac_resume(struct acpi_device *device);
static void acpi_ac_notify(struct acpi_device *device, u32 event);
static const struct acpi_device_id ac_device_ids[] = {
{"ACPI0003", 0},
{"", 0},
};
MODULE_DEVICE_TABLE(acpi, ac_device_ids);
static struct acpi_driver acpi_ac_driver = {
.name = "ac",
.class = ACPI_AC_CLASS,
.ids = ac_device_ids,
.flags = ACPI_DRIVER_ALL_NOTIFY_EVENTS,
.ops = {
.add = acpi_ac_add,
.remove = acpi_ac_remove,
.resume = acpi_ac_resume,
.notify = acpi_ac_notify,
},
};
struct acpi_ac {
struct power_supply charger;
struct acpi_device * device;
unsigned long long state;
};
#define to_acpi_ac(x) container_of(x, struct acpi_ac, charger)
#ifdef CONFIG_ACPI_PROCFS_POWER
static const struct file_operations acpi_ac_fops = {
.owner = THIS_MODULE,
.open = acpi_ac_open_fs,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
#endif
/* --------------------------------------------------------------------------
AC Adapter Management
-------------------------------------------------------------------------- */
static int acpi_ac_get_state(struct acpi_ac *ac)
{
acpi_status status = AE_OK;
if (!ac)
return -EINVAL;
status = acpi_evaluate_integer(ac->device->handle, "_PSR", NULL, &ac->state);
if (ACPI_FAILURE(status)) {
ACPI_EXCEPTION((AE_INFO, status, "Error reading AC Adapter state"));
ac->state = ACPI_AC_STATUS_UNKNOWN;
return -ENODEV;
}
return 0;
}
/* --------------------------------------------------------------------------
sysfs I/F
-------------------------------------------------------------------------- */
static int get_ac_property(struct power_supply *psy,
enum power_supply_property psp,
union power_supply_propval *val)
{
struct acpi_ac *ac = to_acpi_ac(psy);
if (!ac)
return -ENODEV;
if (acpi_ac_get_state(ac))
return -ENODEV;
switch (psp) {
case POWER_SUPPLY_PROP_ONLINE:
val->intval = ac->state;
break;
default:
return -EINVAL;
}
return 0;
}
static enum power_supply_property ac_props[] = {
POWER_SUPPLY_PROP_ONLINE,
};
#ifdef CONFIG_ACPI_PROCFS_POWER
/* --------------------------------------------------------------------------
FS Interface (/proc)
-------------------------------------------------------------------------- */
static struct proc_dir_entry *acpi_ac_dir;
static int acpi_ac_seq_show(struct seq_file *seq, void *offset)
{
struct acpi_ac *ac = seq->private;
if (!ac)
return 0;
if (acpi_ac_get_state(ac)) {
seq_puts(seq, "ERROR: Unable to read AC Adapter state\n");
return 0;
}
seq_puts(seq, "state: ");
switch (ac->state) {
case ACPI_AC_STATUS_OFFLINE:
seq_puts(seq, "off-line\n");
break;
case ACPI_AC_STATUS_ONLINE:
seq_puts(seq, "on-line\n");
break;
default:
seq_puts(seq, "unknown\n");
break;
}
return 0;
}
static int acpi_ac_open_fs(struct inode *inode, struct file *file)
{
return single_open(file, acpi_ac_seq_show, PDE(inode)->data);
}
static int acpi_ac_add_fs(struct acpi_device *device)
{
struct proc_dir_entry *entry = NULL;
printk(KERN_WARNING PREFIX "Deprecated procfs I/F for AC is loaded,"
" please retry with CONFIG_ACPI_PROCFS_POWER cleared\n");
if (!acpi_device_dir(device)) {
acpi_device_dir(device) = proc_mkdir(acpi_device_bid(device),
acpi_ac_dir);
if (!acpi_device_dir(device))
return -ENODEV;
}
/* 'state' [R] */
entry = proc_create_data(ACPI_AC_FILE_STATE,
S_IRUGO, acpi_device_dir(device),
&acpi_ac_fops, acpi_driver_data(device));
if (!entry)
return -ENODEV;
return 0;
}
static int acpi_ac_remove_fs(struct acpi_device *device)
{
if (acpi_device_dir(device)) {
remove_proc_entry(ACPI_AC_FILE_STATE, acpi_device_dir(device));
remove_proc_entry(acpi_device_bid(device), acpi_ac_dir);
acpi_device_dir(device) = NULL;
}
return 0;
}
#endif
/* --------------------------------------------------------------------------
Driver Model
-------------------------------------------------------------------------- */
static void acpi_ac_notify(struct acpi_device *device, u32 event)
{
struct acpi_ac *ac = acpi_driver_data(device);
if (!ac)
return;
switch (event) {
default:
ACPI_DEBUG_PRINT((ACPI_DB_INFO,
"Unsupported event [0x%x]\n", event));
case ACPI_AC_NOTIFY_STATUS:
case ACPI_NOTIFY_BUS_CHECK:
case ACPI_NOTIFY_DEVICE_CHECK:
acpi_ac_get_state(ac);
acpi_bus_generate_proc_event(device, event, (u32) ac->state);
acpi_bus_generate_netlink_event(device->pnp.device_class,
dev_name(&device->dev), event,
(u32) ac->state);
acpi_notifier_call_chain(device, event, (u32) ac->state);
kobject_uevent(&ac->charger.dev->kobj, KOBJ_CHANGE);
}
return;
}
static int acpi_ac_add(struct acpi_device *device)
{
int result = 0;
struct acpi_ac *ac = NULL;
if (!device)
return -EINVAL;
ac = kzalloc(sizeof(struct acpi_ac), GFP_KERNEL);
if (!ac)
return -ENOMEM;
ac->device = device;
strcpy(acpi_device_name(device), ACPI_AC_DEVICE_NAME);
strcpy(acpi_device_class(device), ACPI_AC_CLASS);
device->driver_data = ac;
result = acpi_ac_get_state(ac);
if (result)
goto end;
#ifdef CONFIG_ACPI_PROCFS_POWER
result = acpi_ac_add_fs(device);
#endif
if (result)
goto end;
ac->charger.name = acpi_device_bid(device);
ac->charger.type = POWER_SUPPLY_TYPE_MAINS;
ac->charger.properties = ac_props;
ac->charger.num_properties = ARRAY_SIZE(ac_props);
ac->charger.get_property = get_ac_property;
power_supply_register(&ac->device->dev, &ac->charger);
printk(KERN_INFO PREFIX "%s [%s] (%s)\n",
acpi_device_name(device), acpi_device_bid(device),
ac->state ? "on-line" : "off-line");
end:
if (result) {
#ifdef CONFIG_ACPI_PROCFS_POWER
acpi_ac_remove_fs(device);
#endif
kfree(ac);
}
return result;
}
static int acpi_ac_resume(struct acpi_device *device)
{
struct acpi_ac *ac;
unsigned old_state;
if (!device || !acpi_driver_data(device))
return -EINVAL;
ac = acpi_driver_data(device);
old_state = ac->state;
if (acpi_ac_get_state(ac))
return 0;
if (old_state != ac->state)
kobject_uevent(&ac->charger.dev->kobj, KOBJ_CHANGE);
return 0;
}
static int acpi_ac_remove(struct acpi_device *device, int type)
{
struct acpi_ac *ac = NULL;
if (!device || !acpi_driver_data(device))
return -EINVAL;
ac = acpi_driver_data(device);
if (ac->charger.dev)
power_supply_unregister(&ac->charger);
#ifdef CONFIG_ACPI_PROCFS_POWER
acpi_ac_remove_fs(device);
#endif
kfree(ac);
return 0;
}
static int __init acpi_ac_init(void)
{
int result;
if (acpi_disabled)
return -ENODEV;
#ifdef CONFIG_ACPI_PROCFS_POWER
acpi_ac_dir = acpi_lock_ac_dir();
if (!acpi_ac_dir)
return -ENODEV;
#endif
result = acpi_bus_register_driver(&acpi_ac_driver);
if (result < 0) {
#ifdef CONFIG_ACPI_PROCFS_POWER
acpi_unlock_ac_dir(acpi_ac_dir);
#endif
return -ENODEV;
}
return 0;
}
static void __exit acpi_ac_exit(void)
{
acpi_bus_unregister_driver(&acpi_ac_driver);
#ifdef CONFIG_ACPI_PROCFS_POWER
acpi_unlock_ac_dir(acpi_ac_dir);
#endif
return;
}
module_init(acpi_ac_init);
module_exit(acpi_ac_exit);
| gpl-2.0 |
LeJay/android_kernel_samsung_jactivelte | drivers/pci/hotplug/pciehp_core.c | 3494 | 9777 | /*
* PCI Express Hot Plug Controller Driver
*
* Copyright (C) 1995,2001 Compaq Computer Corporation
* Copyright (C) 2001 Greg Kroah-Hartman (greg@kroah.com)
* Copyright (C) 2001 IBM Corp.
* Copyright (C) 2003-2004 Intel Corporation
*
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
* NON INFRINGEMENT. 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.
*
* Send feedback to <greg@kroah.com>, <kristen.c.accardi@intel.com>
*
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/pci.h>
#include "pciehp.h"
#include <linux/interrupt.h>
#include <linux/time.h>
/* Global variables */
bool pciehp_debug;
bool pciehp_poll_mode;
int pciehp_poll_time;
bool pciehp_force;
struct workqueue_struct *pciehp_wq;
#define DRIVER_VERSION "0.4"
#define DRIVER_AUTHOR "Dan Zink <dan.zink@compaq.com>, Greg Kroah-Hartman <greg@kroah.com>, Dely Sy <dely.l.sy@intel.com>"
#define DRIVER_DESC "PCI Express Hot Plug Controller Driver"
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
module_param(pciehp_debug, bool, 0644);
module_param(pciehp_poll_mode, bool, 0644);
module_param(pciehp_poll_time, int, 0644);
module_param(pciehp_force, bool, 0644);
MODULE_PARM_DESC(pciehp_debug, "Debugging mode enabled or not");
MODULE_PARM_DESC(pciehp_poll_mode, "Using polling mechanism for hot-plug events or not");
MODULE_PARM_DESC(pciehp_poll_time, "Polling mechanism frequency, in seconds");
MODULE_PARM_DESC(pciehp_force, "Force pciehp, even if OSHP is missing");
#define PCIE_MODULE_NAME "pciehp"
static int set_attention_status (struct hotplug_slot *slot, u8 value);
static int enable_slot (struct hotplug_slot *slot);
static int disable_slot (struct hotplug_slot *slot);
static int get_power_status (struct hotplug_slot *slot, u8 *value);
static int get_attention_status (struct hotplug_slot *slot, u8 *value);
static int get_latch_status (struct hotplug_slot *slot, u8 *value);
static int get_adapter_status (struct hotplug_slot *slot, u8 *value);
/**
* release_slot - free up the memory used by a slot
* @hotplug_slot: slot to free
*/
static void release_slot(struct hotplug_slot *hotplug_slot)
{
struct slot *slot = hotplug_slot->private;
ctrl_dbg(slot->ctrl, "%s: physical_slot = %s\n",
__func__, hotplug_slot_name(hotplug_slot));
kfree(hotplug_slot->ops);
kfree(hotplug_slot->info);
kfree(hotplug_slot);
}
static int init_slot(struct controller *ctrl)
{
struct slot *slot = ctrl->slot;
struct hotplug_slot *hotplug = NULL;
struct hotplug_slot_info *info = NULL;
struct hotplug_slot_ops *ops = NULL;
char name[SLOT_NAME_SIZE];
int retval = -ENOMEM;
hotplug = kzalloc(sizeof(*hotplug), GFP_KERNEL);
if (!hotplug)
goto out;
info = kzalloc(sizeof(*info), GFP_KERNEL);
if (!info)
goto out;
/* Setup hotplug slot ops */
ops = kzalloc(sizeof(*ops), GFP_KERNEL);
if (!ops)
goto out;
ops->enable_slot = enable_slot;
ops->disable_slot = disable_slot;
ops->get_power_status = get_power_status;
ops->get_adapter_status = get_adapter_status;
if (MRL_SENS(ctrl))
ops->get_latch_status = get_latch_status;
if (ATTN_LED(ctrl)) {
ops->get_attention_status = get_attention_status;
ops->set_attention_status = set_attention_status;
}
/* register this slot with the hotplug pci core */
hotplug->info = info;
hotplug->private = slot;
hotplug->release = &release_slot;
hotplug->ops = ops;
slot->hotplug_slot = hotplug;
snprintf(name, SLOT_NAME_SIZE, "%u", PSN(ctrl));
ctrl_dbg(ctrl, "Registering domain:bus:dev=%04x:%02x:00 sun=%x\n",
pci_domain_nr(ctrl->pcie->port->subordinate),
ctrl->pcie->port->subordinate->number, PSN(ctrl));
retval = pci_hp_register(hotplug,
ctrl->pcie->port->subordinate, 0, name);
if (retval)
ctrl_err(ctrl,
"pci_hp_register failed with error %d\n", retval);
out:
if (retval) {
kfree(ops);
kfree(info);
kfree(hotplug);
}
return retval;
}
static void cleanup_slot(struct controller *ctrl)
{
pci_hp_deregister(ctrl->slot->hotplug_slot);
}
/*
* set_attention_status - Turns the Amber LED for a slot on, off or blink
*/
static int set_attention_status(struct hotplug_slot *hotplug_slot, u8 status)
{
struct slot *slot = hotplug_slot->private;
ctrl_dbg(slot->ctrl, "%s: physical_slot = %s\n",
__func__, slot_name(slot));
return pciehp_set_attention_status(slot, status);
}
static int enable_slot(struct hotplug_slot *hotplug_slot)
{
struct slot *slot = hotplug_slot->private;
ctrl_dbg(slot->ctrl, "%s: physical_slot = %s\n",
__func__, slot_name(slot));
return pciehp_sysfs_enable_slot(slot);
}
static int disable_slot(struct hotplug_slot *hotplug_slot)
{
struct slot *slot = hotplug_slot->private;
ctrl_dbg(slot->ctrl, "%s: physical_slot = %s\n",
__func__, slot_name(slot));
return pciehp_sysfs_disable_slot(slot);
}
static int get_power_status(struct hotplug_slot *hotplug_slot, u8 *value)
{
struct slot *slot = hotplug_slot->private;
ctrl_dbg(slot->ctrl, "%s: physical_slot = %s\n",
__func__, slot_name(slot));
return pciehp_get_power_status(slot, value);
}
static int get_attention_status(struct hotplug_slot *hotplug_slot, u8 *value)
{
struct slot *slot = hotplug_slot->private;
ctrl_dbg(slot->ctrl, "%s: physical_slot = %s\n",
__func__, slot_name(slot));
return pciehp_get_attention_status(slot, value);
}
static int get_latch_status(struct hotplug_slot *hotplug_slot, u8 *value)
{
struct slot *slot = hotplug_slot->private;
ctrl_dbg(slot->ctrl, "%s: physical_slot = %s\n",
__func__, slot_name(slot));
return pciehp_get_latch_status(slot, value);
}
static int get_adapter_status(struct hotplug_slot *hotplug_slot, u8 *value)
{
struct slot *slot = hotplug_slot->private;
ctrl_dbg(slot->ctrl, "%s: physical_slot = %s\n",
__func__, slot_name(slot));
return pciehp_get_adapter_status(slot, value);
}
static int pciehp_probe(struct pcie_device *dev)
{
int rc;
struct controller *ctrl;
struct slot *slot;
u8 occupied, poweron;
if (pciehp_force)
dev_info(&dev->device,
"Bypassing BIOS check for pciehp use on %s\n",
pci_name(dev->port));
else if (pciehp_acpi_slot_detection_check(dev->port))
goto err_out_none;
ctrl = pcie_init(dev);
if (!ctrl) {
dev_err(&dev->device, "Controller initialization failed\n");
goto err_out_none;
}
set_service_data(dev, ctrl);
/* Setup the slot information structures */
rc = init_slot(ctrl);
if (rc) {
if (rc == -EBUSY)
ctrl_warn(ctrl, "Slot already registered by another "
"hotplug driver\n");
else
ctrl_err(ctrl, "Slot initialization failed\n");
goto err_out_release_ctlr;
}
/* Enable events after we have setup the data structures */
rc = pcie_init_notification(ctrl);
if (rc) {
ctrl_err(ctrl, "Notification initialization failed\n");
goto err_out_free_ctrl_slot;
}
/* Check if slot is occupied */
slot = ctrl->slot;
pciehp_get_adapter_status(slot, &occupied);
pciehp_get_power_status(slot, &poweron);
if (occupied && pciehp_force)
pciehp_enable_slot(slot);
/* If empty slot's power status is on, turn power off */
if (!occupied && poweron && POWER_CTRL(ctrl))
pciehp_power_off_slot(slot);
return 0;
err_out_free_ctrl_slot:
cleanup_slot(ctrl);
err_out_release_ctlr:
pciehp_release_ctrl(ctrl);
err_out_none:
return -ENODEV;
}
static void pciehp_remove(struct pcie_device *dev)
{
struct controller *ctrl = get_service_data(dev);
cleanup_slot(ctrl);
pciehp_release_ctrl(ctrl);
}
#ifdef CONFIG_PM
static int pciehp_suspend (struct pcie_device *dev)
{
dev_info(&dev->device, "%s ENTRY\n", __func__);
return 0;
}
static int pciehp_resume (struct pcie_device *dev)
{
dev_info(&dev->device, "%s ENTRY\n", __func__);
if (pciehp_force) {
struct controller *ctrl = get_service_data(dev);
struct slot *slot;
u8 status;
/* reinitialize the chipset's event detection logic */
pcie_enable_notification(ctrl);
slot = ctrl->slot;
/* Check if slot is occupied */
pciehp_get_adapter_status(slot, &status);
if (status)
pciehp_enable_slot(slot);
else
pciehp_disable_slot(slot);
}
return 0;
}
#endif /* PM */
static struct pcie_port_service_driver hpdriver_portdrv = {
.name = PCIE_MODULE_NAME,
.port_type = PCIE_ANY_PORT,
.service = PCIE_PORT_SERVICE_HP,
.probe = pciehp_probe,
.remove = pciehp_remove,
#ifdef CONFIG_PM
.suspend = pciehp_suspend,
.resume = pciehp_resume,
#endif /* PM */
};
static int __init pcied_init(void)
{
int retval = 0;
pciehp_wq = alloc_workqueue("pciehp", 0, 0);
if (!pciehp_wq)
return -ENOMEM;
pciehp_firmware_init();
retval = pcie_port_service_register(&hpdriver_portdrv);
dbg("pcie_port_service_register = %d\n", retval);
info(DRIVER_DESC " version: " DRIVER_VERSION "\n");
if (retval) {
destroy_workqueue(pciehp_wq);
dbg("Failure to register service\n");
}
return retval;
}
static void __exit pcied_cleanup(void)
{
dbg("unload_pciehpd()\n");
pcie_port_service_unregister(&hpdriver_portdrv);
destroy_workqueue(pciehp_wq);
info(DRIVER_DESC " version: " DRIVER_VERSION " unloaded\n");
}
module_init(pcied_init);
module_exit(pcied_cleanup);
| gpl-2.0 |
CrazyGamerGR/CrazySuperKernel-CM14.1-G5 | tools/perf/ui/helpline.c | 4262 | 1192 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../debug.h"
#include "helpline.h"
#include "ui.h"
char ui_helpline__current[512];
static void nop_helpline__pop(void)
{
}
static void nop_helpline__push(const char *msg __maybe_unused)
{
}
static int nop_helpline__show(const char *fmt __maybe_unused,
va_list ap __maybe_unused)
{
return 0;
}
static struct ui_helpline default_helpline_fns = {
.pop = nop_helpline__pop,
.push = nop_helpline__push,
.show = nop_helpline__show,
};
struct ui_helpline *helpline_fns = &default_helpline_fns;
void ui_helpline__pop(void)
{
helpline_fns->pop();
}
void ui_helpline__push(const char *msg)
{
helpline_fns->push(msg);
}
void ui_helpline__vpush(const char *fmt, va_list ap)
{
char *s;
if (vasprintf(&s, fmt, ap) < 0)
vfprintf(stderr, fmt, ap);
else {
ui_helpline__push(s);
free(s);
}
}
void ui_helpline__fpush(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
ui_helpline__vpush(fmt, ap);
va_end(ap);
}
void ui_helpline__puts(const char *msg)
{
ui_helpline__pop();
ui_helpline__push(msg);
}
int ui_helpline__vshow(const char *fmt, va_list ap)
{
return helpline_fns->show(fmt, ap);
}
| gpl-2.0 |
proyvind/linux-3.12 | tools/perf/ui/helpline.c | 4262 | 1192 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../debug.h"
#include "helpline.h"
#include "ui.h"
char ui_helpline__current[512];
static void nop_helpline__pop(void)
{
}
static void nop_helpline__push(const char *msg __maybe_unused)
{
}
static int nop_helpline__show(const char *fmt __maybe_unused,
va_list ap __maybe_unused)
{
return 0;
}
static struct ui_helpline default_helpline_fns = {
.pop = nop_helpline__pop,
.push = nop_helpline__push,
.show = nop_helpline__show,
};
struct ui_helpline *helpline_fns = &default_helpline_fns;
void ui_helpline__pop(void)
{
helpline_fns->pop();
}
void ui_helpline__push(const char *msg)
{
helpline_fns->push(msg);
}
void ui_helpline__vpush(const char *fmt, va_list ap)
{
char *s;
if (vasprintf(&s, fmt, ap) < 0)
vfprintf(stderr, fmt, ap);
else {
ui_helpline__push(s);
free(s);
}
}
void ui_helpline__fpush(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
ui_helpline__vpush(fmt, ap);
va_end(ap);
}
void ui_helpline__puts(const char *msg)
{
ui_helpline__pop();
ui_helpline__push(msg);
}
int ui_helpline__vshow(const char *fmt, va_list ap)
{
return helpline_fns->show(fmt, ap);
}
| gpl-2.0 |
pasterp/kernel_S8515 | drivers/i2c/busses/i2c-mxs.c | 4774 | 10655 | /*
* Freescale MXS I2C bus driver
*
* Copyright (C) 2011 Wolfram Sang, Pengutronix e.K.
*
* based on a (non-working) driver which was:
*
* Copyright (C) 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved.
*
* TODO: add dma-support if platform-support for it is available
*
* 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/slab.h>
#include <linux/device.h>
#include <linux/module.h>
#include <linux/i2c.h>
#include <linux/err.h>
#include <linux/interrupt.h>
#include <linux/completion.h>
#include <linux/platform_device.h>
#include <linux/jiffies.h>
#include <linux/io.h>
#include <mach/common.h>
#define DRIVER_NAME "mxs-i2c"
#define MXS_I2C_CTRL0 (0x00)
#define MXS_I2C_CTRL0_SET (0x04)
#define MXS_I2C_CTRL0_SFTRST 0x80000000
#define MXS_I2C_CTRL0_SEND_NAK_ON_LAST 0x02000000
#define MXS_I2C_CTRL0_RETAIN_CLOCK 0x00200000
#define MXS_I2C_CTRL0_POST_SEND_STOP 0x00100000
#define MXS_I2C_CTRL0_PRE_SEND_START 0x00080000
#define MXS_I2C_CTRL0_MASTER_MODE 0x00020000
#define MXS_I2C_CTRL0_DIRECTION 0x00010000
#define MXS_I2C_CTRL0_XFER_COUNT(v) ((v) & 0x0000FFFF)
#define MXS_I2C_CTRL1 (0x40)
#define MXS_I2C_CTRL1_SET (0x44)
#define MXS_I2C_CTRL1_CLR (0x48)
#define MXS_I2C_CTRL1_BUS_FREE_IRQ 0x80
#define MXS_I2C_CTRL1_DATA_ENGINE_CMPLT_IRQ 0x40
#define MXS_I2C_CTRL1_NO_SLAVE_ACK_IRQ 0x20
#define MXS_I2C_CTRL1_OVERSIZE_XFER_TERM_IRQ 0x10
#define MXS_I2C_CTRL1_EARLY_TERM_IRQ 0x08
#define MXS_I2C_CTRL1_MASTER_LOSS_IRQ 0x04
#define MXS_I2C_CTRL1_SLAVE_STOP_IRQ 0x02
#define MXS_I2C_CTRL1_SLAVE_IRQ 0x01
#define MXS_I2C_IRQ_MASK (MXS_I2C_CTRL1_DATA_ENGINE_CMPLT_IRQ | \
MXS_I2C_CTRL1_NO_SLAVE_ACK_IRQ | \
MXS_I2C_CTRL1_EARLY_TERM_IRQ | \
MXS_I2C_CTRL1_MASTER_LOSS_IRQ | \
MXS_I2C_CTRL1_SLAVE_STOP_IRQ | \
MXS_I2C_CTRL1_SLAVE_IRQ)
#define MXS_I2C_QUEUECTRL (0x60)
#define MXS_I2C_QUEUECTRL_SET (0x64)
#define MXS_I2C_QUEUECTRL_CLR (0x68)
#define MXS_I2C_QUEUECTRL_QUEUE_RUN 0x20
#define MXS_I2C_QUEUECTRL_PIO_QUEUE_MODE 0x04
#define MXS_I2C_QUEUESTAT (0x70)
#define MXS_I2C_QUEUESTAT_RD_QUEUE_EMPTY 0x00002000
#define MXS_I2C_QUEUESTAT_WRITE_QUEUE_CNT_MASK 0x0000001F
#define MXS_I2C_QUEUECMD (0x80)
#define MXS_I2C_QUEUEDATA (0x90)
#define MXS_I2C_DATA (0xa0)
#define MXS_CMD_I2C_SELECT (MXS_I2C_CTRL0_RETAIN_CLOCK | \
MXS_I2C_CTRL0_PRE_SEND_START | \
MXS_I2C_CTRL0_MASTER_MODE | \
MXS_I2C_CTRL0_DIRECTION | \
MXS_I2C_CTRL0_XFER_COUNT(1))
#define MXS_CMD_I2C_WRITE (MXS_I2C_CTRL0_PRE_SEND_START | \
MXS_I2C_CTRL0_MASTER_MODE | \
MXS_I2C_CTRL0_DIRECTION)
#define MXS_CMD_I2C_READ (MXS_I2C_CTRL0_SEND_NAK_ON_LAST | \
MXS_I2C_CTRL0_MASTER_MODE)
/**
* struct mxs_i2c_dev - per device, private MXS-I2C data
*
* @dev: driver model device node
* @regs: IO registers pointer
* @cmd_complete: completion object for transaction wait
* @cmd_err: error code for last transaction
* @adapter: i2c subsystem adapter node
*/
struct mxs_i2c_dev {
struct device *dev;
void __iomem *regs;
struct completion cmd_complete;
u32 cmd_err;
struct i2c_adapter adapter;
};
/*
* TODO: check if calls to here are really needed. If not, we could get rid of
* mxs_reset_block and the mach-dependency. Needs an I2C analyzer, probably.
*/
static void mxs_i2c_reset(struct mxs_i2c_dev *i2c)
{
mxs_reset_block(i2c->regs);
writel(MXS_I2C_IRQ_MASK << 8, i2c->regs + MXS_I2C_CTRL1_SET);
writel(MXS_I2C_QUEUECTRL_PIO_QUEUE_MODE,
i2c->regs + MXS_I2C_QUEUECTRL_SET);
}
static void mxs_i2c_pioq_setup_read(struct mxs_i2c_dev *i2c, u8 addr, int len,
int flags)
{
u32 data;
writel(MXS_CMD_I2C_SELECT, i2c->regs + MXS_I2C_QUEUECMD);
data = (addr << 1) | I2C_SMBUS_READ;
writel(data, i2c->regs + MXS_I2C_DATA);
data = MXS_CMD_I2C_READ | MXS_I2C_CTRL0_XFER_COUNT(len) | flags;
writel(data, i2c->regs + MXS_I2C_QUEUECMD);
}
static void mxs_i2c_pioq_setup_write(struct mxs_i2c_dev *i2c,
u8 addr, u8 *buf, int len, int flags)
{
u32 data;
int i, shifts_left;
data = MXS_CMD_I2C_WRITE | MXS_I2C_CTRL0_XFER_COUNT(len + 1) | flags;
writel(data, i2c->regs + MXS_I2C_QUEUECMD);
/*
* We have to copy the slave address (u8) and buffer (arbitrary number
* of u8) into the data register (u32). To achieve that, the u8 are put
* into the MSBs of 'data' which is then shifted for the next u8. When
* appropriate, 'data' is written to MXS_I2C_DATA. So, the first u32
* looks like this:
*
* 3 2 1 0
* 10987654|32109876|54321098|76543210
* --------+--------+--------+--------
* buffer+2|buffer+1|buffer+0|slave_addr
*/
data = ((addr << 1) | I2C_SMBUS_WRITE) << 24;
for (i = 0; i < len; i++) {
data >>= 8;
data |= buf[i] << 24;
if ((i & 3) == 2)
writel(data, i2c->regs + MXS_I2C_DATA);
}
/* Write out the remaining bytes if any */
shifts_left = 24 - (i & 3) * 8;
if (shifts_left)
writel(data >> shifts_left, i2c->regs + MXS_I2C_DATA);
}
/*
* TODO: should be replaceable with a waitqueue and RD_QUEUE_IRQ (setting the
* rd_threshold to 1). Couldn't get this to work, though.
*/
static int mxs_i2c_wait_for_data(struct mxs_i2c_dev *i2c)
{
unsigned long timeout = jiffies + msecs_to_jiffies(1000);
while (readl(i2c->regs + MXS_I2C_QUEUESTAT)
& MXS_I2C_QUEUESTAT_RD_QUEUE_EMPTY) {
if (time_after(jiffies, timeout))
return -ETIMEDOUT;
cond_resched();
}
return 0;
}
static int mxs_i2c_finish_read(struct mxs_i2c_dev *i2c, u8 *buf, int len)
{
u32 data;
int i;
for (i = 0; i < len; i++) {
if ((i & 3) == 0) {
if (mxs_i2c_wait_for_data(i2c))
return -ETIMEDOUT;
data = readl(i2c->regs + MXS_I2C_QUEUEDATA);
}
buf[i] = data & 0xff;
data >>= 8;
}
return 0;
}
/*
* Low level master read/write transaction.
*/
static int mxs_i2c_xfer_msg(struct i2c_adapter *adap, struct i2c_msg *msg,
int stop)
{
struct mxs_i2c_dev *i2c = i2c_get_adapdata(adap);
int ret;
int flags;
dev_dbg(i2c->dev, "addr: 0x%04x, len: %d, flags: 0x%x, stop: %d\n",
msg->addr, msg->len, msg->flags, stop);
if (msg->len == 0)
return -EINVAL;
init_completion(&i2c->cmd_complete);
i2c->cmd_err = 0;
flags = stop ? MXS_I2C_CTRL0_POST_SEND_STOP : 0;
if (msg->flags & I2C_M_RD)
mxs_i2c_pioq_setup_read(i2c, msg->addr, msg->len, flags);
else
mxs_i2c_pioq_setup_write(i2c, msg->addr, msg->buf, msg->len,
flags);
writel(MXS_I2C_QUEUECTRL_QUEUE_RUN,
i2c->regs + MXS_I2C_QUEUECTRL_SET);
ret = wait_for_completion_timeout(&i2c->cmd_complete,
msecs_to_jiffies(1000));
if (ret == 0)
goto timeout;
if ((!i2c->cmd_err) && (msg->flags & I2C_M_RD)) {
ret = mxs_i2c_finish_read(i2c, msg->buf, msg->len);
if (ret)
goto timeout;
}
if (i2c->cmd_err == -ENXIO)
mxs_i2c_reset(i2c);
else
writel(MXS_I2C_QUEUECTRL_QUEUE_RUN,
i2c->regs + MXS_I2C_QUEUECTRL_CLR);
dev_dbg(i2c->dev, "Done with err=%d\n", i2c->cmd_err);
return i2c->cmd_err;
timeout:
dev_dbg(i2c->dev, "Timeout!\n");
mxs_i2c_reset(i2c);
return -ETIMEDOUT;
}
static int mxs_i2c_xfer(struct i2c_adapter *adap, struct i2c_msg msgs[],
int num)
{
int i;
int err;
for (i = 0; i < num; i++) {
err = mxs_i2c_xfer_msg(adap, &msgs[i], i == (num - 1));
if (err)
return err;
}
return num;
}
static u32 mxs_i2c_func(struct i2c_adapter *adap)
{
return I2C_FUNC_I2C | (I2C_FUNC_SMBUS_EMUL & ~I2C_FUNC_SMBUS_QUICK);
}
static irqreturn_t mxs_i2c_isr(int this_irq, void *dev_id)
{
struct mxs_i2c_dev *i2c = dev_id;
u32 stat = readl(i2c->regs + MXS_I2C_CTRL1) & MXS_I2C_IRQ_MASK;
bool is_last_cmd;
if (!stat)
return IRQ_NONE;
if (stat & MXS_I2C_CTRL1_NO_SLAVE_ACK_IRQ)
i2c->cmd_err = -ENXIO;
else if (stat & (MXS_I2C_CTRL1_EARLY_TERM_IRQ |
MXS_I2C_CTRL1_MASTER_LOSS_IRQ |
MXS_I2C_CTRL1_SLAVE_STOP_IRQ | MXS_I2C_CTRL1_SLAVE_IRQ))
/* MXS_I2C_CTRL1_OVERSIZE_XFER_TERM_IRQ is only for slaves */
i2c->cmd_err = -EIO;
is_last_cmd = (readl(i2c->regs + MXS_I2C_QUEUESTAT) &
MXS_I2C_QUEUESTAT_WRITE_QUEUE_CNT_MASK) == 0;
if (is_last_cmd || i2c->cmd_err)
complete(&i2c->cmd_complete);
writel(stat, i2c->regs + MXS_I2C_CTRL1_CLR);
return IRQ_HANDLED;
}
static const struct i2c_algorithm mxs_i2c_algo = {
.master_xfer = mxs_i2c_xfer,
.functionality = mxs_i2c_func,
};
static int __devinit mxs_i2c_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct mxs_i2c_dev *i2c;
struct i2c_adapter *adap;
struct resource *res;
resource_size_t res_size;
int err, irq;
i2c = devm_kzalloc(dev, sizeof(struct mxs_i2c_dev), GFP_KERNEL);
if (!i2c)
return -ENOMEM;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res)
return -ENOENT;
res_size = resource_size(res);
if (!devm_request_mem_region(dev, res->start, res_size, res->name))
return -EBUSY;
i2c->regs = devm_ioremap_nocache(dev, res->start, res_size);
if (!i2c->regs)
return -EBUSY;
irq = platform_get_irq(pdev, 0);
if (irq < 0)
return irq;
err = devm_request_irq(dev, irq, mxs_i2c_isr, 0, dev_name(dev), i2c);
if (err)
return err;
i2c->dev = dev;
platform_set_drvdata(pdev, i2c);
/* Do reset to enforce correct startup after pinmuxing */
mxs_i2c_reset(i2c);
adap = &i2c->adapter;
strlcpy(adap->name, "MXS I2C adapter", sizeof(adap->name));
adap->owner = THIS_MODULE;
adap->algo = &mxs_i2c_algo;
adap->dev.parent = dev;
adap->nr = pdev->id;
i2c_set_adapdata(adap, i2c);
err = i2c_add_numbered_adapter(adap);
if (err) {
dev_err(dev, "Failed to add adapter (%d)\n", err);
writel(MXS_I2C_CTRL0_SFTRST,
i2c->regs + MXS_I2C_CTRL0_SET);
return err;
}
return 0;
}
static int __devexit mxs_i2c_remove(struct platform_device *pdev)
{
struct mxs_i2c_dev *i2c = platform_get_drvdata(pdev);
int ret;
ret = i2c_del_adapter(&i2c->adapter);
if (ret)
return -EBUSY;
writel(MXS_I2C_CTRL0_SFTRST, i2c->regs + MXS_I2C_CTRL0_SET);
platform_set_drvdata(pdev, NULL);
return 0;
}
static struct platform_driver mxs_i2c_driver = {
.driver = {
.name = DRIVER_NAME,
.owner = THIS_MODULE,
},
.remove = __devexit_p(mxs_i2c_remove),
};
static int __init mxs_i2c_init(void)
{
return platform_driver_probe(&mxs_i2c_driver, mxs_i2c_probe);
}
subsys_initcall(mxs_i2c_init);
static void __exit mxs_i2c_exit(void)
{
platform_driver_unregister(&mxs_i2c_driver);
}
module_exit(mxs_i2c_exit);
MODULE_AUTHOR("Wolfram Sang <w.sang@pengutronix.de>");
MODULE_DESCRIPTION("MXS I2C Bus Driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:" DRIVER_NAME);
| gpl-2.0 |
PureNexusProject/android_kernel_asus_flo | drivers/staging/omapdrm/omap_drv.c | 4774 | 21092 | /*
* drivers/staging/omapdrm/omap_drv.c
*
* Copyright (C) 2011 Texas Instruments
* Author: Rob Clark <rob@ti.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "omap_drv.h"
#include "drm_crtc_helper.h"
#include "drm_fb_helper.h"
#include "omap_dmm_tiler.h"
#define DRIVER_NAME MODULE_NAME
#define DRIVER_DESC "OMAP DRM"
#define DRIVER_DATE "20110917"
#define DRIVER_MAJOR 1
#define DRIVER_MINOR 0
#define DRIVER_PATCHLEVEL 0
struct drm_device *drm_device;
static int num_crtc = CONFIG_DRM_OMAP_NUM_CRTCS;
MODULE_PARM_DESC(num_crtc, "Number of overlays to use as CRTCs");
module_param(num_crtc, int, 0600);
/*
* mode config funcs
*/
/* Notes about mapping DSS and DRM entities:
* CRTC: overlay
* encoder: manager.. with some extension to allow one primary CRTC
* and zero or more video CRTC's to be mapped to one encoder?
* connector: dssdev.. manager can be attached/detached from different
* devices
*/
static void omap_fb_output_poll_changed(struct drm_device *dev)
{
struct omap_drm_private *priv = dev->dev_private;
DBG("dev=%p", dev);
if (priv->fbdev) {
drm_fb_helper_hotplug_event(priv->fbdev);
}
}
static struct drm_mode_config_funcs omap_mode_config_funcs = {
.fb_create = omap_framebuffer_create,
.output_poll_changed = omap_fb_output_poll_changed,
};
static int get_connector_type(struct omap_dss_device *dssdev)
{
switch (dssdev->type) {
case OMAP_DISPLAY_TYPE_HDMI:
return DRM_MODE_CONNECTOR_HDMIA;
case OMAP_DISPLAY_TYPE_DPI:
if (!strcmp(dssdev->name, "dvi"))
return DRM_MODE_CONNECTOR_DVID;
/* fallthrough */
default:
return DRM_MODE_CONNECTOR_Unknown;
}
}
#if 0 /* enable when dss2 supports hotplug */
static int omap_drm_notifier(struct notifier_block *nb,
unsigned long evt, void *arg)
{
switch (evt) {
case OMAP_DSS_SIZE_CHANGE:
case OMAP_DSS_HOTPLUG_CONNECT:
case OMAP_DSS_HOTPLUG_DISCONNECT: {
struct drm_device *dev = drm_device;
DBG("hotplug event: evt=%d, dev=%p", evt, dev);
if (dev) {
drm_sysfs_hotplug_event(dev);
}
return NOTIFY_OK;
}
default: /* don't care about other events for now */
return NOTIFY_DONE;
}
}
#endif
static void dump_video_chains(void)
{
int i;
DBG("dumping video chains: ");
for (i = 0; i < omap_dss_get_num_overlays(); i++) {
struct omap_overlay *ovl = omap_dss_get_overlay(i);
struct omap_overlay_manager *mgr = ovl->manager;
struct omap_dss_device *dssdev = mgr ? mgr->device : NULL;
if (dssdev) {
DBG("%d: %s -> %s -> %s", i, ovl->name, mgr->name,
dssdev->name);
} else if (mgr) {
DBG("%d: %s -> %s", i, ovl->name, mgr->name);
} else {
DBG("%d: %s", i, ovl->name);
}
}
}
/* create encoders for each manager */
static int create_encoder(struct drm_device *dev,
struct omap_overlay_manager *mgr)
{
struct omap_drm_private *priv = dev->dev_private;
struct drm_encoder *encoder = omap_encoder_init(dev, mgr);
if (!encoder) {
dev_err(dev->dev, "could not create encoder: %s\n",
mgr->name);
return -ENOMEM;
}
BUG_ON(priv->num_encoders >= ARRAY_SIZE(priv->encoders));
priv->encoders[priv->num_encoders++] = encoder;
return 0;
}
/* create connectors for each display device */
static int create_connector(struct drm_device *dev,
struct omap_dss_device *dssdev)
{
struct omap_drm_private *priv = dev->dev_private;
static struct notifier_block *notifier;
struct drm_connector *connector;
int j;
if (!dssdev->driver) {
dev_warn(dev->dev, "%s has no driver.. skipping it\n",
dssdev->name);
return 0;
}
if (!(dssdev->driver->get_timings ||
dssdev->driver->read_edid)) {
dev_warn(dev->dev, "%s driver does not support "
"get_timings or read_edid.. skipping it!\n",
dssdev->name);
return 0;
}
connector = omap_connector_init(dev,
get_connector_type(dssdev), dssdev);
if (!connector) {
dev_err(dev->dev, "could not create connector: %s\n",
dssdev->name);
return -ENOMEM;
}
BUG_ON(priv->num_connectors >= ARRAY_SIZE(priv->connectors));
priv->connectors[priv->num_connectors++] = connector;
#if 0 /* enable when dss2 supports hotplug */
notifier = kzalloc(sizeof(struct notifier_block), GFP_KERNEL);
notifier->notifier_call = omap_drm_notifier;
omap_dss_add_notify(dssdev, notifier);
#else
notifier = NULL;
#endif
for (j = 0; j < priv->num_encoders; j++) {
struct omap_overlay_manager *mgr =
omap_encoder_get_manager(priv->encoders[j]);
if (mgr->device == dssdev) {
drm_mode_connector_attach_encoder(connector,
priv->encoders[j]);
}
}
return 0;
}
/* create up to max_overlays CRTCs mapping to overlays.. by default,
* connect the overlays to different managers/encoders, giving priority
* to encoders connected to connectors with a detected connection
*/
static int create_crtc(struct drm_device *dev, struct omap_overlay *ovl,
int *j, unsigned int connected_connectors)
{
struct omap_drm_private *priv = dev->dev_private;
struct omap_overlay_manager *mgr = NULL;
struct drm_crtc *crtc;
/* find next best connector, ones with detected connection first
*/
while (*j < priv->num_connectors && !mgr) {
if (connected_connectors & (1 << *j)) {
struct drm_encoder *encoder =
omap_connector_attached_encoder(
priv->connectors[*j]);
if (encoder) {
mgr = omap_encoder_get_manager(encoder);
}
}
(*j)++;
}
/* if we couldn't find another connected connector, lets start
* looking at the unconnected connectors:
*
* note: it might not be immediately apparent, but thanks to
* the !mgr check in both this loop and the one above, the only
* way to enter this loop is with *j == priv->num_connectors,
* so idx can never go negative.
*/
while (*j < 2 * priv->num_connectors && !mgr) {
int idx = *j - priv->num_connectors;
if (!(connected_connectors & (1 << idx))) {
struct drm_encoder *encoder =
omap_connector_attached_encoder(
priv->connectors[idx]);
if (encoder) {
mgr = omap_encoder_get_manager(encoder);
}
}
(*j)++;
}
crtc = omap_crtc_init(dev, ovl, priv->num_crtcs);
if (!crtc) {
dev_err(dev->dev, "could not create CRTC: %s\n",
ovl->name);
return -ENOMEM;
}
BUG_ON(priv->num_crtcs >= ARRAY_SIZE(priv->crtcs));
priv->crtcs[priv->num_crtcs++] = crtc;
return 0;
}
static int create_plane(struct drm_device *dev, struct omap_overlay *ovl,
unsigned int possible_crtcs)
{
struct omap_drm_private *priv = dev->dev_private;
struct drm_plane *plane =
omap_plane_init(dev, ovl, possible_crtcs, false);
if (!plane) {
dev_err(dev->dev, "could not create plane: %s\n",
ovl->name);
return -ENOMEM;
}
BUG_ON(priv->num_planes >= ARRAY_SIZE(priv->planes));
priv->planes[priv->num_planes++] = plane;
return 0;
}
static int match_dev_name(struct omap_dss_device *dssdev, void *data)
{
return !strcmp(dssdev->name, data);
}
static unsigned int detect_connectors(struct drm_device *dev)
{
struct omap_drm_private *priv = dev->dev_private;
unsigned int connected_connectors = 0;
int i;
for (i = 0; i < priv->num_connectors; i++) {
struct drm_connector *connector = priv->connectors[i];
if (omap_connector_detect(connector, true) ==
connector_status_connected) {
connected_connectors |= (1 << i);
}
}
return connected_connectors;
}
static int omap_modeset_init(struct drm_device *dev)
{
const struct omap_drm_platform_data *pdata = dev->dev->platform_data;
struct omap_kms_platform_data *kms_pdata = NULL;
struct omap_drm_private *priv = dev->dev_private;
struct omap_dss_device *dssdev = NULL;
int i, j;
unsigned int connected_connectors = 0;
drm_mode_config_init(dev);
if (pdata && pdata->kms_pdata) {
kms_pdata = pdata->kms_pdata;
/* if platform data is provided by the board file, use it to
* control which overlays, managers, and devices we own.
*/
for (i = 0; i < kms_pdata->mgr_cnt; i++) {
struct omap_overlay_manager *mgr =
omap_dss_get_overlay_manager(
kms_pdata->mgr_ids[i]);
create_encoder(dev, mgr);
}
for (i = 0; i < kms_pdata->dev_cnt; i++) {
struct omap_dss_device *dssdev =
omap_dss_find_device(
(void *)kms_pdata->dev_names[i],
match_dev_name);
if (!dssdev) {
dev_warn(dev->dev, "no such dssdev: %s\n",
kms_pdata->dev_names[i]);
continue;
}
create_connector(dev, dssdev);
}
connected_connectors = detect_connectors(dev);
j = 0;
for (i = 0; i < kms_pdata->ovl_cnt; i++) {
struct omap_overlay *ovl =
omap_dss_get_overlay(kms_pdata->ovl_ids[i]);
create_crtc(dev, ovl, &j, connected_connectors);
}
for (i = 0; i < kms_pdata->pln_cnt; i++) {
struct omap_overlay *ovl =
omap_dss_get_overlay(kms_pdata->pln_ids[i]);
create_plane(dev, ovl, (1 << priv->num_crtcs) - 1);
}
} else {
/* otherwise just grab up to CONFIG_DRM_OMAP_NUM_CRTCS and try
* to make educated guesses about everything else
*/
int max_overlays = min(omap_dss_get_num_overlays(), num_crtc);
for (i = 0; i < omap_dss_get_num_overlay_managers(); i++) {
create_encoder(dev, omap_dss_get_overlay_manager(i));
}
for_each_dss_dev(dssdev) {
create_connector(dev, dssdev);
}
connected_connectors = detect_connectors(dev);
j = 0;
for (i = 0; i < max_overlays; i++) {
create_crtc(dev, omap_dss_get_overlay(i),
&j, connected_connectors);
}
/* use any remaining overlays as drm planes */
for (; i < omap_dss_get_num_overlays(); i++) {
struct omap_overlay *ovl = omap_dss_get_overlay(i);
create_plane(dev, ovl, (1 << priv->num_crtcs) - 1);
}
}
/* for now keep the mapping of CRTCs and encoders static.. */
for (i = 0; i < priv->num_encoders; i++) {
struct drm_encoder *encoder = priv->encoders[i];
struct omap_overlay_manager *mgr =
omap_encoder_get_manager(encoder);
encoder->possible_crtcs = (1 << priv->num_crtcs) - 1;
DBG("%s: possible_crtcs=%08x", mgr->name,
encoder->possible_crtcs);
}
dump_video_chains();
dev->mode_config.min_width = 32;
dev->mode_config.min_height = 32;
/* note: eventually will need some cpu_is_omapXYZ() type stuff here
* to fill in these limits properly on different OMAP generations..
*/
dev->mode_config.max_width = 2048;
dev->mode_config.max_height = 2048;
dev->mode_config.funcs = &omap_mode_config_funcs;
return 0;
}
static void omap_modeset_free(struct drm_device *dev)
{
drm_mode_config_cleanup(dev);
}
/*
* drm ioctl funcs
*/
static int ioctl_get_param(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct drm_omap_param *args = data;
DBG("%p: param=%llu", dev, args->param);
switch (args->param) {
case OMAP_PARAM_CHIPSET_ID:
args->value = GET_OMAP_TYPE;
break;
default:
DBG("unknown parameter %lld", args->param);
return -EINVAL;
}
return 0;
}
static int ioctl_set_param(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct drm_omap_param *args = data;
switch (args->param) {
default:
DBG("unknown parameter %lld", args->param);
return -EINVAL;
}
return 0;
}
static int ioctl_gem_new(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct drm_omap_gem_new *args = data;
DBG("%p:%p: size=0x%08x, flags=%08x", dev, file_priv,
args->size.bytes, args->flags);
return omap_gem_new_handle(dev, file_priv, args->size,
args->flags, &args->handle);
}
static int ioctl_gem_cpu_prep(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct drm_omap_gem_cpu_prep *args = data;
struct drm_gem_object *obj;
int ret;
VERB("%p:%p: handle=%d, op=%x", dev, file_priv, args->handle, args->op);
obj = drm_gem_object_lookup(dev, file_priv, args->handle);
if (!obj) {
return -ENOENT;
}
ret = omap_gem_op_sync(obj, args->op);
if (!ret) {
ret = omap_gem_op_start(obj, args->op);
}
drm_gem_object_unreference_unlocked(obj);
return ret;
}
static int ioctl_gem_cpu_fini(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct drm_omap_gem_cpu_fini *args = data;
struct drm_gem_object *obj;
int ret;
VERB("%p:%p: handle=%d", dev, file_priv, args->handle);
obj = drm_gem_object_lookup(dev, file_priv, args->handle);
if (!obj) {
return -ENOENT;
}
/* XXX flushy, flushy */
ret = 0;
if (!ret) {
ret = omap_gem_op_finish(obj, args->op);
}
drm_gem_object_unreference_unlocked(obj);
return ret;
}
static int ioctl_gem_info(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct drm_omap_gem_info *args = data;
struct drm_gem_object *obj;
int ret = 0;
DBG("%p:%p: handle=%d", dev, file_priv, args->handle);
obj = drm_gem_object_lookup(dev, file_priv, args->handle);
if (!obj) {
return -ENOENT;
}
args->size = omap_gem_mmap_size(obj);
args->offset = omap_gem_mmap_offset(obj);
drm_gem_object_unreference_unlocked(obj);
return ret;
}
struct drm_ioctl_desc ioctls[DRM_COMMAND_END - DRM_COMMAND_BASE] = {
DRM_IOCTL_DEF_DRV(OMAP_GET_PARAM, ioctl_get_param, DRM_UNLOCKED|DRM_AUTH),
DRM_IOCTL_DEF_DRV(OMAP_SET_PARAM, ioctl_set_param, DRM_UNLOCKED|DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY),
DRM_IOCTL_DEF_DRV(OMAP_GEM_NEW, ioctl_gem_new, DRM_UNLOCKED|DRM_AUTH),
DRM_IOCTL_DEF_DRV(OMAP_GEM_CPU_PREP, ioctl_gem_cpu_prep, DRM_UNLOCKED|DRM_AUTH),
DRM_IOCTL_DEF_DRV(OMAP_GEM_CPU_FINI, ioctl_gem_cpu_fini, DRM_UNLOCKED|DRM_AUTH),
DRM_IOCTL_DEF_DRV(OMAP_GEM_INFO, ioctl_gem_info, DRM_UNLOCKED|DRM_AUTH),
};
/*
* drm driver funcs
*/
/**
* load - setup chip and create an initial config
* @dev: DRM device
* @flags: startup flags
*
* The driver load routine has to do several things:
* - initialize the memory manager
* - allocate initial config memory
* - setup the DRM framebuffer with the allocated memory
*/
static int dev_load(struct drm_device *dev, unsigned long flags)
{
struct omap_drm_private *priv;
int ret;
DBG("load: dev=%p", dev);
drm_device = dev;
priv = kzalloc(sizeof(*priv), GFP_KERNEL);
if (!priv) {
dev_err(dev->dev, "could not allocate priv\n");
return -ENOMEM;
}
dev->dev_private = priv;
priv->wq = alloc_workqueue("omapdrm",
WQ_UNBOUND | WQ_NON_REENTRANT, 1);
INIT_LIST_HEAD(&priv->obj_list);
omap_gem_init(dev);
ret = omap_modeset_init(dev);
if (ret) {
dev_err(dev->dev, "omap_modeset_init failed: ret=%d\n", ret);
dev->dev_private = NULL;
kfree(priv);
return ret;
}
priv->fbdev = omap_fbdev_init(dev);
if (!priv->fbdev) {
dev_warn(dev->dev, "omap_fbdev_init failed\n");
/* well, limp along without an fbdev.. maybe X11 will work? */
}
drm_kms_helper_poll_init(dev);
ret = drm_vblank_init(dev, priv->num_crtcs);
if (ret) {
dev_warn(dev->dev, "could not init vblank\n");
}
return 0;
}
static int dev_unload(struct drm_device *dev)
{
struct omap_drm_private *priv = dev->dev_private;
DBG("unload: dev=%p", dev);
drm_vblank_cleanup(dev);
drm_kms_helper_poll_fini(dev);
omap_fbdev_free(dev);
omap_modeset_free(dev);
omap_gem_deinit(dev);
flush_workqueue(priv->wq);
destroy_workqueue(priv->wq);
kfree(dev->dev_private);
dev->dev_private = NULL;
return 0;
}
static int dev_open(struct drm_device *dev, struct drm_file *file)
{
file->driver_priv = NULL;
DBG("open: dev=%p, file=%p", dev, file);
return 0;
}
static int dev_firstopen(struct drm_device *dev)
{
DBG("firstopen: dev=%p", dev);
return 0;
}
/**
* lastclose - clean up after all DRM clients have exited
* @dev: DRM device
*
* Take care of cleaning up after all DRM clients have exited. In the
* mode setting case, we want to restore the kernel's initial mode (just
* in case the last client left us in a bad state).
*/
static void dev_lastclose(struct drm_device *dev)
{
/* we don't support vga-switcheroo.. so just make sure the fbdev
* mode is active
*/
struct omap_drm_private *priv = dev->dev_private;
int ret;
DBG("lastclose: dev=%p", dev);
ret = drm_fb_helper_restore_fbdev_mode(priv->fbdev);
if (ret)
DBG("failed to restore crtc mode");
}
static void dev_preclose(struct drm_device *dev, struct drm_file *file)
{
DBG("preclose: dev=%p", dev);
}
static void dev_postclose(struct drm_device *dev, struct drm_file *file)
{
DBG("postclose: dev=%p, file=%p", dev, file);
}
/**
* enable_vblank - enable vblank interrupt events
* @dev: DRM device
* @crtc: which irq to enable
*
* Enable vblank interrupts for @crtc. If the device doesn't have
* a hardware vblank counter, this routine should be a no-op, since
* interrupts will have to stay on to keep the count accurate.
*
* RETURNS
* Zero on success, appropriate errno if the given @crtc's vblank
* interrupt cannot be enabled.
*/
static int dev_enable_vblank(struct drm_device *dev, int crtc)
{
DBG("enable_vblank: dev=%p, crtc=%d", dev, crtc);
return 0;
}
/**
* disable_vblank - disable vblank interrupt events
* @dev: DRM device
* @crtc: which irq to enable
*
* Disable vblank interrupts for @crtc. If the device doesn't have
* a hardware vblank counter, this routine should be a no-op, since
* interrupts will have to stay on to keep the count accurate.
*/
static void dev_disable_vblank(struct drm_device *dev, int crtc)
{
DBG("disable_vblank: dev=%p, crtc=%d", dev, crtc);
}
static irqreturn_t dev_irq_handler(DRM_IRQ_ARGS)
{
return IRQ_HANDLED;
}
static void dev_irq_preinstall(struct drm_device *dev)
{
DBG("irq_preinstall: dev=%p", dev);
}
static int dev_irq_postinstall(struct drm_device *dev)
{
DBG("irq_postinstall: dev=%p", dev);
return 0;
}
static void dev_irq_uninstall(struct drm_device *dev)
{
DBG("irq_uninstall: dev=%p", dev);
}
static struct vm_operations_struct omap_gem_vm_ops = {
.fault = omap_gem_fault,
.open = drm_gem_vm_open,
.close = drm_gem_vm_close,
};
static const struct file_operations omapdriver_fops = {
.owner = THIS_MODULE,
.open = drm_open,
.unlocked_ioctl = drm_ioctl,
.release = drm_release,
.mmap = omap_gem_mmap,
.poll = drm_poll,
.fasync = drm_fasync,
.read = drm_read,
.llseek = noop_llseek,
};
static struct drm_driver omap_drm_driver = {
.driver_features =
DRIVER_HAVE_IRQ | DRIVER_MODESET | DRIVER_GEM,
.load = dev_load,
.unload = dev_unload,
.open = dev_open,
.firstopen = dev_firstopen,
.lastclose = dev_lastclose,
.preclose = dev_preclose,
.postclose = dev_postclose,
.get_vblank_counter = drm_vblank_count,
.enable_vblank = dev_enable_vblank,
.disable_vblank = dev_disable_vblank,
.irq_preinstall = dev_irq_preinstall,
.irq_postinstall = dev_irq_postinstall,
.irq_uninstall = dev_irq_uninstall,
.irq_handler = dev_irq_handler,
.reclaim_buffers = drm_core_reclaim_buffers,
#ifdef CONFIG_DEBUG_FS
.debugfs_init = omap_debugfs_init,
.debugfs_cleanup = omap_debugfs_cleanup,
#endif
.gem_init_object = omap_gem_init_object,
.gem_free_object = omap_gem_free_object,
.gem_vm_ops = &omap_gem_vm_ops,
.dumb_create = omap_gem_dumb_create,
.dumb_map_offset = omap_gem_dumb_map_offset,
.dumb_destroy = omap_gem_dumb_destroy,
.ioctls = ioctls,
.num_ioctls = DRM_OMAP_NUM_IOCTLS,
.fops = &omapdriver_fops,
.name = DRIVER_NAME,
.desc = DRIVER_DESC,
.date = DRIVER_DATE,
.major = DRIVER_MAJOR,
.minor = DRIVER_MINOR,
.patchlevel = DRIVER_PATCHLEVEL,
};
static int pdev_suspend(struct platform_device *pDevice, pm_message_t state)
{
DBG("");
return 0;
}
static int pdev_resume(struct platform_device *device)
{
DBG("");
return 0;
}
static void pdev_shutdown(struct platform_device *device)
{
DBG("");
}
static int pdev_probe(struct platform_device *device)
{
DBG("%s", device->name);
return drm_platform_init(&omap_drm_driver, device);
}
static int pdev_remove(struct platform_device *device)
{
DBG("");
drm_platform_exit(&omap_drm_driver, device);
platform_driver_unregister(&omap_dmm_driver);
return 0;
}
struct platform_driver pdev = {
.driver = {
.name = DRIVER_NAME,
.owner = THIS_MODULE,
},
.probe = pdev_probe,
.remove = pdev_remove,
.suspend = pdev_suspend,
.resume = pdev_resume,
.shutdown = pdev_shutdown,
};
static int __init omap_drm_init(void)
{
DBG("init");
if (platform_driver_register(&omap_dmm_driver)) {
/* we can continue on without DMM.. so not fatal */
dev_err(NULL, "DMM registration failed\n");
}
return platform_driver_register(&pdev);
}
static void __exit omap_drm_fini(void)
{
DBG("fini");
platform_driver_unregister(&pdev);
}
/* need late_initcall() so we load after dss_driver's are loaded */
late_initcall(omap_drm_init);
module_exit(omap_drm_fini);
MODULE_AUTHOR("Rob Clark <rob@ti.com>");
MODULE_DESCRIPTION("OMAP DRM Display Driver");
MODULE_ALIAS("platform:" DRIVER_NAME);
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
Ander-Alvarez/ultracm13 | drivers/video/fb_defio.c | 5030 | 6352 | /*
* linux/drivers/video/fb_defio.c
*
* Copyright (C) 2006 Jaya Kumar
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of this archive
* for more details.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/vmalloc.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/fb.h>
#include <linux/list.h>
/* to support deferred IO */
#include <linux/rmap.h>
#include <linux/pagemap.h>
struct page *fb_deferred_io_page(struct fb_info *info, unsigned long offs)
{
void *screen_base = (void __force *) info->screen_base;
struct page *page;
if (is_vmalloc_addr(screen_base + offs))
page = vmalloc_to_page(screen_base + offs);
else
page = pfn_to_page((info->fix.smem_start + offs) >> PAGE_SHIFT);
return page;
}
/* this is to find and return the vmalloc-ed fb pages */
static int fb_deferred_io_fault(struct vm_area_struct *vma,
struct vm_fault *vmf)
{
unsigned long offset;
struct page *page;
struct fb_info *info = vma->vm_private_data;
offset = vmf->pgoff << PAGE_SHIFT;
if (offset >= info->fix.smem_len)
return VM_FAULT_SIGBUS;
page = fb_deferred_io_page(info, offset);
if (!page)
return VM_FAULT_SIGBUS;
get_page(page);
if (vma->vm_file)
page->mapping = vma->vm_file->f_mapping;
else
printk(KERN_ERR "no mapping available\n");
BUG_ON(!page->mapping);
page->index = vmf->pgoff;
vmf->page = page;
return 0;
}
int fb_deferred_io_fsync(struct file *file, loff_t start, loff_t end, int datasync)
{
struct fb_info *info = file->private_data;
struct inode *inode = file->f_path.dentry->d_inode;
int err = filemap_write_and_wait_range(inode->i_mapping, start, end);
if (err)
return err;
/* Skip if deferred io is compiled-in but disabled on this fbdev */
if (!info->fbdefio)
return 0;
mutex_lock(&inode->i_mutex);
/* Kill off the delayed work */
cancel_delayed_work_sync(&info->deferred_work);
/* Run it immediately */
err = schedule_delayed_work(&info->deferred_work, 0);
mutex_unlock(&inode->i_mutex);
return err;
}
EXPORT_SYMBOL_GPL(fb_deferred_io_fsync);
/* vm_ops->page_mkwrite handler */
static int fb_deferred_io_mkwrite(struct vm_area_struct *vma,
struct vm_fault *vmf)
{
struct page *page = vmf->page;
struct fb_info *info = vma->vm_private_data;
struct fb_deferred_io *fbdefio = info->fbdefio;
struct page *cur;
/* this is a callback we get when userspace first tries to
write to the page. we schedule a workqueue. that workqueue
will eventually mkclean the touched pages and execute the
deferred framebuffer IO. then if userspace touches a page
again, we repeat the same scheme */
/* protect against the workqueue changing the page list */
mutex_lock(&fbdefio->lock);
/*
* We want the page to remain locked from ->page_mkwrite until
* the PTE is marked dirty to avoid page_mkclean() being called
* before the PTE is updated, which would leave the page ignored
* by defio.
* Do this by locking the page here and informing the caller
* about it with VM_FAULT_LOCKED.
*/
lock_page(page);
/* we loop through the pagelist before adding in order
to keep the pagelist sorted */
list_for_each_entry(cur, &fbdefio->pagelist, lru) {
/* this check is to catch the case where a new
process could start writing to the same page
through a new pte. this new access can cause the
mkwrite even when the original ps's pte is marked
writable */
if (unlikely(cur == page))
goto page_already_added;
else if (cur->index > page->index)
break;
}
list_add_tail(&page->lru, &cur->lru);
page_already_added:
mutex_unlock(&fbdefio->lock);
/* come back after delay to process the deferred IO */
schedule_delayed_work(&info->deferred_work, fbdefio->delay);
return VM_FAULT_LOCKED;
}
static const struct vm_operations_struct fb_deferred_io_vm_ops = {
.fault = fb_deferred_io_fault,
.page_mkwrite = fb_deferred_io_mkwrite,
};
static int fb_deferred_io_set_page_dirty(struct page *page)
{
if (!PageDirty(page))
SetPageDirty(page);
return 0;
}
static const struct address_space_operations fb_deferred_io_aops = {
.set_page_dirty = fb_deferred_io_set_page_dirty,
};
static int fb_deferred_io_mmap(struct fb_info *info, struct vm_area_struct *vma)
{
vma->vm_ops = &fb_deferred_io_vm_ops;
vma->vm_flags |= ( VM_RESERVED | VM_DONTEXPAND );
if (!(info->flags & FBINFO_VIRTFB))
vma->vm_flags |= VM_IO;
vma->vm_private_data = info;
return 0;
}
/* workqueue callback */
static void fb_deferred_io_work(struct work_struct *work)
{
struct fb_info *info = container_of(work, struct fb_info,
deferred_work.work);
struct list_head *node, *next;
struct page *cur;
struct fb_deferred_io *fbdefio = info->fbdefio;
/* here we mkclean the pages, then do all deferred IO */
mutex_lock(&fbdefio->lock);
list_for_each_entry(cur, &fbdefio->pagelist, lru) {
lock_page(cur);
page_mkclean(cur);
unlock_page(cur);
}
/* driver's callback with pagelist */
fbdefio->deferred_io(info, &fbdefio->pagelist);
/* clear the list */
list_for_each_safe(node, next, &fbdefio->pagelist) {
list_del(node);
}
mutex_unlock(&fbdefio->lock);
}
void fb_deferred_io_init(struct fb_info *info)
{
struct fb_deferred_io *fbdefio = info->fbdefio;
BUG_ON(!fbdefio);
mutex_init(&fbdefio->lock);
info->fbops->fb_mmap = fb_deferred_io_mmap;
INIT_DELAYED_WORK(&info->deferred_work, fb_deferred_io_work);
INIT_LIST_HEAD(&fbdefio->pagelist);
if (fbdefio->delay == 0) /* set a default of 1 s */
fbdefio->delay = HZ;
}
EXPORT_SYMBOL_GPL(fb_deferred_io_init);
void fb_deferred_io_open(struct fb_info *info,
struct inode *inode,
struct file *file)
{
file->f_mapping->a_ops = &fb_deferred_io_aops;
}
EXPORT_SYMBOL_GPL(fb_deferred_io_open);
void fb_deferred_io_cleanup(struct fb_info *info)
{
struct fb_deferred_io *fbdefio = info->fbdefio;
struct page *page;
int i;
BUG_ON(!fbdefio);
cancel_delayed_work_sync(&info->deferred_work);
/* clear out the mapping that we setup */
for (i = 0 ; i < info->fix.smem_len; i += PAGE_SIZE) {
page = fb_deferred_io_page(info, i);
page->mapping = NULL;
}
info->fbops->fb_mmap = NULL;
mutex_destroy(&fbdefio->lock);
}
EXPORT_SYMBOL_GPL(fb_deferred_io_cleanup);
MODULE_LICENSE("GPL");
| gpl-2.0 |
zlaja/android_kernel_lge_msm8610 | drivers/staging/media/easycap/easycap_low.c | 5030 | 24963 | /*****************************************************************************
* *
* *
* 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 {
u16 reg;
u16 set;
} stk1160configPAL[] = {
{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[] = {
{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 {
u8 reg;
u8 set;
} saa7113configPAL[] = {
{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[] = {
{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 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
*/
/*--------------------------------------------------------------------------*/
static 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
*/
/*--------------------------------------------------------------------------*/
static 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.
*/
/*--------------------------------------------------------------------------*/
static 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;
}
/****************************************************************************/
/****************************************************************************/
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, rc;
const struct saa7113config *cfg;
if (!p)
return -ENODEV;
cfg = (ntsc) ? saa7113configNTSC : saa7113configPAL;
for (i = 0; cfg[i].reg != 0xFF; i++) {
rc = write_saa(p, cfg[i].reg, cfg[i].set);
if (rc)
dev_err(&p->dev,
"Failed to set SAA register %d", cfg[i].reg);
}
return 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;
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;
}
/****************************************************************************/
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;
}
/****************************************************************************/
static int read_stk(struct usb_device *p, u32 reg0)
{
u8 igot;
if (!p)
return -ENODEV;
igot = 0;
GET(p, reg0, &igot);
return igot;
}
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 easycap_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 easycap_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 (easycap_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 easycap_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;
}
/*****************************************************************************/
| gpl-2.0 |
fus1on/3.4.xx_LG_kernel | drivers/usb/wusbcore/security.c | 5030 | 16472 | /*
* Wireless USB Host Controller
* Security support: encryption enablement, etc
*
* Copyright (C) 2006 Intel Corporation
* Inaky Perez-Gonzalez <inaky.perez-gonzalez@intel.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*
*
* FIXME: docs
*/
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/usb/ch9.h>
#include <linux/random.h>
#include <linux/export.h>
#include "wusbhc.h"
static void wusbhc_set_gtk_callback(struct urb *urb);
static void wusbhc_gtk_rekey_done_work(struct work_struct *work);
int wusbhc_sec_create(struct wusbhc *wusbhc)
{
wusbhc->gtk.descr.bLength = sizeof(wusbhc->gtk.descr) + sizeof(wusbhc->gtk.data);
wusbhc->gtk.descr.bDescriptorType = USB_DT_KEY;
wusbhc->gtk.descr.bReserved = 0;
wusbhc->gtk_index = wusb_key_index(0, WUSB_KEY_INDEX_TYPE_GTK,
WUSB_KEY_INDEX_ORIGINATOR_HOST);
INIT_WORK(&wusbhc->gtk_rekey_done_work, wusbhc_gtk_rekey_done_work);
return 0;
}
/* Called when the HC is destroyed */
void wusbhc_sec_destroy(struct wusbhc *wusbhc)
{
}
/**
* wusbhc_next_tkid - generate a new, currently unused, TKID
* @wusbhc: the WUSB host controller
* @wusb_dev: the device whose PTK the TKID is for
* (or NULL for a TKID for a GTK)
*
* The generated TKID consist of two parts: the device's authenicated
* address (or 0 or a GTK); and an incrementing number. This ensures
* that TKIDs cannot be shared between devices and by the time the
* incrementing number wraps around the older TKIDs will no longer be
* in use (a maximum of two keys may be active at any one time).
*/
static u32 wusbhc_next_tkid(struct wusbhc *wusbhc, struct wusb_dev *wusb_dev)
{
u32 *tkid;
u32 addr;
if (wusb_dev == NULL) {
tkid = &wusbhc->gtk_tkid;
addr = 0;
} else {
tkid = &wusb_port_by_idx(wusbhc, wusb_dev->port_idx)->ptk_tkid;
addr = wusb_dev->addr & 0x7f;
}
*tkid = (addr << 8) | ((*tkid + 1) & 0xff);
return *tkid;
}
static void wusbhc_generate_gtk(struct wusbhc *wusbhc)
{
const size_t key_size = sizeof(wusbhc->gtk.data);
u32 tkid;
tkid = wusbhc_next_tkid(wusbhc, NULL);
wusbhc->gtk.descr.tTKID[0] = (tkid >> 0) & 0xff;
wusbhc->gtk.descr.tTKID[1] = (tkid >> 8) & 0xff;
wusbhc->gtk.descr.tTKID[2] = (tkid >> 16) & 0xff;
get_random_bytes(wusbhc->gtk.descr.bKeyData, key_size);
}
/**
* wusbhc_sec_start - start the security management process
* @wusbhc: the WUSB host controller
*
* Generate and set an initial GTK on the host controller.
*
* Called when the HC is started.
*/
int wusbhc_sec_start(struct wusbhc *wusbhc)
{
const size_t key_size = sizeof(wusbhc->gtk.data);
int result;
wusbhc_generate_gtk(wusbhc);
result = wusbhc->set_gtk(wusbhc, wusbhc->gtk_tkid,
&wusbhc->gtk.descr.bKeyData, key_size);
if (result < 0)
dev_err(wusbhc->dev, "cannot set GTK for the host: %d\n",
result);
return result;
}
/**
* wusbhc_sec_stop - stop the security management process
* @wusbhc: the WUSB host controller
*
* Wait for any pending GTK rekeys to stop.
*/
void wusbhc_sec_stop(struct wusbhc *wusbhc)
{
cancel_work_sync(&wusbhc->gtk_rekey_done_work);
}
/** @returns encryption type name */
const char *wusb_et_name(u8 x)
{
switch (x) {
case USB_ENC_TYPE_UNSECURE: return "unsecure";
case USB_ENC_TYPE_WIRED: return "wired";
case USB_ENC_TYPE_CCM_1: return "CCM-1";
case USB_ENC_TYPE_RSA_1: return "RSA-1";
default: return "unknown";
}
}
EXPORT_SYMBOL_GPL(wusb_et_name);
/*
* Set the device encryption method
*
* We tell the device which encryption method to use; we do this when
* setting up the device's security.
*/
static int wusb_dev_set_encryption(struct usb_device *usb_dev, int value)
{
int result;
struct device *dev = &usb_dev->dev;
struct wusb_dev *wusb_dev = usb_dev->wusb_dev;
if (value) {
value = wusb_dev->ccm1_etd.bEncryptionValue;
} else {
/* FIXME: should be wusb_dev->etd[UNSECURE].bEncryptionValue */
value = 0;
}
/* Set device's */
result = usb_control_msg(usb_dev, usb_sndctrlpipe(usb_dev, 0),
USB_REQ_SET_ENCRYPTION,
USB_DIR_OUT | USB_TYPE_STANDARD | USB_RECIP_DEVICE,
value, 0, NULL, 0, 1000 /* FIXME: arbitrary */);
if (result < 0)
dev_err(dev, "Can't set device's WUSB encryption to "
"%s (value %d): %d\n",
wusb_et_name(wusb_dev->ccm1_etd.bEncryptionType),
wusb_dev->ccm1_etd.bEncryptionValue, result);
return result;
}
/*
* Set the GTK to be used by a device.
*
* The device must be authenticated.
*/
static int wusb_dev_set_gtk(struct wusbhc *wusbhc, struct wusb_dev *wusb_dev)
{
struct usb_device *usb_dev = wusb_dev->usb_dev;
return usb_control_msg(
usb_dev, usb_sndctrlpipe(usb_dev, 0),
USB_REQ_SET_DESCRIPTOR,
USB_DIR_OUT | USB_TYPE_STANDARD | USB_RECIP_DEVICE,
USB_DT_KEY << 8 | wusbhc->gtk_index, 0,
&wusbhc->gtk.descr, wusbhc->gtk.descr.bLength,
1000);
}
/* FIXME: prototype for adding security */
int wusb_dev_sec_add(struct wusbhc *wusbhc,
struct usb_device *usb_dev, struct wusb_dev *wusb_dev)
{
int result, bytes, secd_size;
struct device *dev = &usb_dev->dev;
struct usb_security_descriptor *secd;
const struct usb_encryption_descriptor *etd, *ccm1_etd = NULL;
const void *itr, *top;
char buf[64];
secd = kmalloc(sizeof(*secd), GFP_KERNEL);
if (secd == NULL) {
result = -ENOMEM;
goto out;
}
result = usb_get_descriptor(usb_dev, USB_DT_SECURITY,
0, secd, sizeof(*secd));
if (result < sizeof(*secd)) {
dev_err(dev, "Can't read security descriptor or "
"not enough data: %d\n", result);
goto out;
}
secd_size = le16_to_cpu(secd->wTotalLength);
secd = krealloc(secd, secd_size, GFP_KERNEL);
if (secd == NULL) {
dev_err(dev, "Can't allocate space for security descriptors\n");
goto out;
}
result = usb_get_descriptor(usb_dev, USB_DT_SECURITY,
0, secd, secd_size);
if (result < secd_size) {
dev_err(dev, "Can't read security descriptor or "
"not enough data: %d\n", result);
goto out;
}
bytes = 0;
itr = &secd[1];
top = (void *)secd + result;
while (itr < top) {
etd = itr;
if (top - itr < sizeof(*etd)) {
dev_err(dev, "BUG: bad device security descriptor; "
"not enough data (%zu vs %zu bytes left)\n",
top - itr, sizeof(*etd));
break;
}
if (etd->bLength < sizeof(*etd)) {
dev_err(dev, "BUG: bad device encryption descriptor; "
"descriptor is too short "
"(%u vs %zu needed)\n",
etd->bLength, sizeof(*etd));
break;
}
itr += etd->bLength;
bytes += snprintf(buf + bytes, sizeof(buf) - bytes,
"%s (0x%02x/%02x) ",
wusb_et_name(etd->bEncryptionType),
etd->bEncryptionValue, etd->bAuthKeyIndex);
if (etd->bEncryptionType == USB_ENC_TYPE_CCM_1)
ccm1_etd = etd;
}
/* This code only supports CCM1 as of now. */
/* FIXME: user has to choose which sec mode to use?
* In theory we want CCM */
if (ccm1_etd == NULL) {
dev_err(dev, "WUSB device doesn't support CCM1 encryption, "
"can't use!\n");
result = -EINVAL;
goto out;
}
wusb_dev->ccm1_etd = *ccm1_etd;
dev_dbg(dev, "supported encryption: %s; using %s (0x%02x/%02x)\n",
buf, wusb_et_name(ccm1_etd->bEncryptionType),
ccm1_etd->bEncryptionValue, ccm1_etd->bAuthKeyIndex);
result = 0;
out:
kfree(secd);
return result;
}
void wusb_dev_sec_rm(struct wusb_dev *wusb_dev)
{
/* Nothing so far */
}
/**
* Update the address of an unauthenticated WUSB device
*
* Once we have successfully authenticated, we take it to addr0 state
* and then to a normal address.
*
* Before the device's address (as known by it) was usb_dev->devnum |
* 0x80 (unauthenticated address). With this we update it to usb_dev->devnum.
*/
int wusb_dev_update_address(struct wusbhc *wusbhc, struct wusb_dev *wusb_dev)
{
int result = -ENOMEM;
struct usb_device *usb_dev = wusb_dev->usb_dev;
struct device *dev = &usb_dev->dev;
u8 new_address = wusb_dev->addr & 0x7F;
/* Set address 0 */
result = usb_control_msg(usb_dev, usb_sndctrlpipe(usb_dev, 0),
USB_REQ_SET_ADDRESS, 0,
0, 0, NULL, 0, 1000 /* FIXME: arbitrary */);
if (result < 0) {
dev_err(dev, "auth failed: can't set address 0: %d\n",
result);
goto error_addr0;
}
result = wusb_set_dev_addr(wusbhc, wusb_dev, 0);
if (result < 0)
goto error_addr0;
usb_set_device_state(usb_dev, USB_STATE_DEFAULT);
usb_ep0_reinit(usb_dev);
/* Set new (authenticated) address. */
result = usb_control_msg(usb_dev, usb_sndctrlpipe(usb_dev, 0),
USB_REQ_SET_ADDRESS, 0,
new_address, 0, NULL, 0,
1000 /* FIXME: arbitrary */);
if (result < 0) {
dev_err(dev, "auth failed: can't set address %u: %d\n",
new_address, result);
goto error_addr;
}
result = wusb_set_dev_addr(wusbhc, wusb_dev, new_address);
if (result < 0)
goto error_addr;
usb_set_device_state(usb_dev, USB_STATE_ADDRESS);
usb_ep0_reinit(usb_dev);
usb_dev->authenticated = 1;
error_addr:
error_addr0:
return result;
}
/*
*
*
*/
/* FIXME: split and cleanup */
int wusb_dev_4way_handshake(struct wusbhc *wusbhc, struct wusb_dev *wusb_dev,
struct wusb_ckhdid *ck)
{
int result = -ENOMEM;
struct usb_device *usb_dev = wusb_dev->usb_dev;
struct device *dev = &usb_dev->dev;
u32 tkid;
__le32 tkid_le;
struct usb_handshake *hs;
struct aes_ccm_nonce ccm_n;
u8 mic[8];
struct wusb_keydvt_in keydvt_in;
struct wusb_keydvt_out keydvt_out;
hs = kcalloc(3, sizeof(hs[0]), GFP_KERNEL);
if (hs == NULL) {
dev_err(dev, "can't allocate handshake data\n");
goto error_kzalloc;
}
/* We need to turn encryption before beginning the 4way
* hshake (WUSB1.0[.3.2.2]) */
result = wusb_dev_set_encryption(usb_dev, 1);
if (result < 0)
goto error_dev_set_encryption;
tkid = wusbhc_next_tkid(wusbhc, wusb_dev);
tkid_le = cpu_to_le32(tkid);
hs[0].bMessageNumber = 1;
hs[0].bStatus = 0;
memcpy(hs[0].tTKID, &tkid_le, sizeof(hs[0].tTKID));
hs[0].bReserved = 0;
memcpy(hs[0].CDID, &wusb_dev->cdid, sizeof(hs[0].CDID));
get_random_bytes(&hs[0].nonce, sizeof(hs[0].nonce));
memset(hs[0].MIC, 0, sizeof(hs[0].MIC)); /* Per WUSB1.0[T7-22] */
result = usb_control_msg(
usb_dev, usb_sndctrlpipe(usb_dev, 0),
USB_REQ_SET_HANDSHAKE,
USB_DIR_OUT | USB_TYPE_STANDARD | USB_RECIP_DEVICE,
1, 0, &hs[0], sizeof(hs[0]), 1000 /* FIXME: arbitrary */);
if (result < 0) {
dev_err(dev, "Handshake1: request failed: %d\n", result);
goto error_hs1;
}
/* Handshake 2, from the device -- need to verify fields */
result = usb_control_msg(
usb_dev, usb_rcvctrlpipe(usb_dev, 0),
USB_REQ_GET_HANDSHAKE,
USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE,
2, 0, &hs[1], sizeof(hs[1]), 1000 /* FIXME: arbitrary */);
if (result < 0) {
dev_err(dev, "Handshake2: request failed: %d\n", result);
goto error_hs2;
}
result = -EINVAL;
if (hs[1].bMessageNumber != 2) {
dev_err(dev, "Handshake2 failed: bad message number %u\n",
hs[1].bMessageNumber);
goto error_hs2;
}
if (hs[1].bStatus != 0) {
dev_err(dev, "Handshake2 failed: bad status %u\n",
hs[1].bStatus);
goto error_hs2;
}
if (memcmp(hs[0].tTKID, hs[1].tTKID, sizeof(hs[0].tTKID))) {
dev_err(dev, "Handshake2 failed: TKID mismatch "
"(#1 0x%02x%02x%02x vs #2 0x%02x%02x%02x)\n",
hs[0].tTKID[0], hs[0].tTKID[1], hs[0].tTKID[2],
hs[1].tTKID[0], hs[1].tTKID[1], hs[1].tTKID[2]);
goto error_hs2;
}
if (memcmp(hs[0].CDID, hs[1].CDID, sizeof(hs[0].CDID))) {
dev_err(dev, "Handshake2 failed: CDID mismatch\n");
goto error_hs2;
}
/* Setup the CCM nonce */
memset(&ccm_n.sfn, 0, sizeof(ccm_n.sfn)); /* Per WUSB1.0[6.5.2] */
memcpy(ccm_n.tkid, &tkid_le, sizeof(ccm_n.tkid));
ccm_n.src_addr = wusbhc->uwb_rc->uwb_dev.dev_addr;
ccm_n.dest_addr.data[0] = wusb_dev->addr;
ccm_n.dest_addr.data[1] = 0;
/* Derive the KCK and PTK from CK, the CCM, H and D nonces */
memcpy(keydvt_in.hnonce, hs[0].nonce, sizeof(keydvt_in.hnonce));
memcpy(keydvt_in.dnonce, hs[1].nonce, sizeof(keydvt_in.dnonce));
result = wusb_key_derive(&keydvt_out, ck->data, &ccm_n, &keydvt_in);
if (result < 0) {
dev_err(dev, "Handshake2 failed: cannot derive keys: %d\n",
result);
goto error_hs2;
}
/* Compute MIC and verify it */
result = wusb_oob_mic(mic, keydvt_out.kck, &ccm_n, &hs[1]);
if (result < 0) {
dev_err(dev, "Handshake2 failed: cannot compute MIC: %d\n",
result);
goto error_hs2;
}
if (memcmp(hs[1].MIC, mic, sizeof(hs[1].MIC))) {
dev_err(dev, "Handshake2 failed: MIC mismatch\n");
goto error_hs2;
}
/* Send Handshake3 */
hs[2].bMessageNumber = 3;
hs[2].bStatus = 0;
memcpy(hs[2].tTKID, &tkid_le, sizeof(hs[2].tTKID));
hs[2].bReserved = 0;
memcpy(hs[2].CDID, &wusb_dev->cdid, sizeof(hs[2].CDID));
memcpy(hs[2].nonce, hs[0].nonce, sizeof(hs[2].nonce));
result = wusb_oob_mic(hs[2].MIC, keydvt_out.kck, &ccm_n, &hs[2]);
if (result < 0) {
dev_err(dev, "Handshake3 failed: cannot compute MIC: %d\n",
result);
goto error_hs2;
}
result = usb_control_msg(
usb_dev, usb_sndctrlpipe(usb_dev, 0),
USB_REQ_SET_HANDSHAKE,
USB_DIR_OUT | USB_TYPE_STANDARD | USB_RECIP_DEVICE,
3, 0, &hs[2], sizeof(hs[2]), 1000 /* FIXME: arbitrary */);
if (result < 0) {
dev_err(dev, "Handshake3: request failed: %d\n", result);
goto error_hs3;
}
result = wusbhc->set_ptk(wusbhc, wusb_dev->port_idx, tkid,
keydvt_out.ptk, sizeof(keydvt_out.ptk));
if (result < 0)
goto error_wusbhc_set_ptk;
result = wusb_dev_set_gtk(wusbhc, wusb_dev);
if (result < 0) {
dev_err(dev, "Set GTK for device: request failed: %d\n",
result);
goto error_wusbhc_set_gtk;
}
/* Update the device's address from unauth to auth */
if (usb_dev->authenticated == 0) {
result = wusb_dev_update_address(wusbhc, wusb_dev);
if (result < 0)
goto error_dev_update_address;
}
result = 0;
dev_info(dev, "device authenticated\n");
error_dev_update_address:
error_wusbhc_set_gtk:
error_wusbhc_set_ptk:
error_hs3:
error_hs2:
error_hs1:
memset(hs, 0, 3*sizeof(hs[0]));
memset(&keydvt_out, 0, sizeof(keydvt_out));
memset(&keydvt_in, 0, sizeof(keydvt_in));
memset(&ccm_n, 0, sizeof(ccm_n));
memset(mic, 0, sizeof(mic));
if (result < 0)
wusb_dev_set_encryption(usb_dev, 0);
error_dev_set_encryption:
kfree(hs);
error_kzalloc:
return result;
}
/*
* Once all connected and authenticated devices have received the new
* GTK, switch the host to using it.
*/
static void wusbhc_gtk_rekey_done_work(struct work_struct *work)
{
struct wusbhc *wusbhc = container_of(work, struct wusbhc, gtk_rekey_done_work);
size_t key_size = sizeof(wusbhc->gtk.data);
mutex_lock(&wusbhc->mutex);
if (--wusbhc->pending_set_gtks == 0)
wusbhc->set_gtk(wusbhc, wusbhc->gtk_tkid, &wusbhc->gtk.descr.bKeyData, key_size);
mutex_unlock(&wusbhc->mutex);
}
static void wusbhc_set_gtk_callback(struct urb *urb)
{
struct wusbhc *wusbhc = urb->context;
queue_work(wusbd, &wusbhc->gtk_rekey_done_work);
}
/**
* wusbhc_gtk_rekey - generate and distribute a new GTK
* @wusbhc: the WUSB host controller
*
* Generate a new GTK and distribute it to all connected and
* authenticated devices. When all devices have the new GTK, the host
* starts using it.
*
* This must be called after every device disconnect (see [WUSB]
* section 6.2.11.2).
*/
void wusbhc_gtk_rekey(struct wusbhc *wusbhc)
{
static const size_t key_size = sizeof(wusbhc->gtk.data);
int p;
wusbhc_generate_gtk(wusbhc);
for (p = 0; p < wusbhc->ports_max; p++) {
struct wusb_dev *wusb_dev;
wusb_dev = wusbhc->port[p].wusb_dev;
if (!wusb_dev || !wusb_dev->usb_dev || !wusb_dev->usb_dev->authenticated)
continue;
usb_fill_control_urb(wusb_dev->set_gtk_urb, wusb_dev->usb_dev,
usb_sndctrlpipe(wusb_dev->usb_dev, 0),
(void *)wusb_dev->set_gtk_req,
&wusbhc->gtk.descr, wusbhc->gtk.descr.bLength,
wusbhc_set_gtk_callback, wusbhc);
if (usb_submit_urb(wusb_dev->set_gtk_urb, GFP_KERNEL) == 0)
wusbhc->pending_set_gtks++;
}
if (wusbhc->pending_set_gtks == 0)
wusbhc->set_gtk(wusbhc, wusbhc->gtk_tkid, &wusbhc->gtk.descr.bKeyData, key_size);
}
| gpl-2.0 |
Nick73/King_Kernel | drivers/infiniband/hw/qib/qib_ud.c | 7078 | 16612 | /*
* Copyright (c) 2006, 2007, 2008, 2009 QLogic Corporation. All rights reserved.
* Copyright (c) 2005, 2006 PathScale, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <rdma/ib_smi.h>
#include "qib.h"
#include "qib_mad.h"
/**
* qib_ud_loopback - handle send on loopback QPs
* @sqp: the sending QP
* @swqe: the send work request
*
* This is called from qib_make_ud_req() to forward a WQE addressed
* to the same HCA.
* Note that the receive interrupt handler may be calling qib_ud_rcv()
* while this is being called.
*/
static void qib_ud_loopback(struct qib_qp *sqp, struct qib_swqe *swqe)
{
struct qib_ibport *ibp = to_iport(sqp->ibqp.device, sqp->port_num);
struct qib_pportdata *ppd;
struct qib_qp *qp;
struct ib_ah_attr *ah_attr;
unsigned long flags;
struct qib_sge_state ssge;
struct qib_sge *sge;
struct ib_wc wc;
u32 length;
qp = qib_lookup_qpn(ibp, swqe->wr.wr.ud.remote_qpn);
if (!qp) {
ibp->n_pkt_drops++;
return;
}
if (qp->ibqp.qp_type != sqp->ibqp.qp_type ||
!(ib_qib_state_ops[qp->state] & QIB_PROCESS_RECV_OK)) {
ibp->n_pkt_drops++;
goto drop;
}
ah_attr = &to_iah(swqe->wr.wr.ud.ah)->attr;
ppd = ppd_from_ibp(ibp);
if (qp->ibqp.qp_num > 1) {
u16 pkey1;
u16 pkey2;
u16 lid;
pkey1 = qib_get_pkey(ibp, sqp->s_pkey_index);
pkey2 = qib_get_pkey(ibp, qp->s_pkey_index);
if (unlikely(!qib_pkey_ok(pkey1, pkey2))) {
lid = ppd->lid | (ah_attr->src_path_bits &
((1 << ppd->lmc) - 1));
qib_bad_pqkey(ibp, IB_NOTICE_TRAP_BAD_PKEY, pkey1,
ah_attr->sl,
sqp->ibqp.qp_num, qp->ibqp.qp_num,
cpu_to_be16(lid),
cpu_to_be16(ah_attr->dlid));
goto drop;
}
}
/*
* Check that the qkey matches (except for QP0, see 9.6.1.4.1).
* Qkeys with the high order bit set mean use the
* qkey from the QP context instead of the WR (see 10.2.5).
*/
if (qp->ibqp.qp_num) {
u32 qkey;
qkey = (int)swqe->wr.wr.ud.remote_qkey < 0 ?
sqp->qkey : swqe->wr.wr.ud.remote_qkey;
if (unlikely(qkey != qp->qkey)) {
u16 lid;
lid = ppd->lid | (ah_attr->src_path_bits &
((1 << ppd->lmc) - 1));
qib_bad_pqkey(ibp, IB_NOTICE_TRAP_BAD_QKEY, qkey,
ah_attr->sl,
sqp->ibqp.qp_num, qp->ibqp.qp_num,
cpu_to_be16(lid),
cpu_to_be16(ah_attr->dlid));
goto drop;
}
}
/*
* A GRH is expected to precede the data even if not
* present on the wire.
*/
length = swqe->length;
memset(&wc, 0, sizeof wc);
wc.byte_len = length + sizeof(struct ib_grh);
if (swqe->wr.opcode == IB_WR_SEND_WITH_IMM) {
wc.wc_flags = IB_WC_WITH_IMM;
wc.ex.imm_data = swqe->wr.ex.imm_data;
}
spin_lock_irqsave(&qp->r_lock, flags);
/*
* Get the next work request entry to find where to put the data.
*/
if (qp->r_flags & QIB_R_REUSE_SGE)
qp->r_flags &= ~QIB_R_REUSE_SGE;
else {
int ret;
ret = qib_get_rwqe(qp, 0);
if (ret < 0) {
qib_rc_error(qp, IB_WC_LOC_QP_OP_ERR);
goto bail_unlock;
}
if (!ret) {
if (qp->ibqp.qp_num == 0)
ibp->n_vl15_dropped++;
goto bail_unlock;
}
}
/* Silently drop packets which are too big. */
if (unlikely(wc.byte_len > qp->r_len)) {
qp->r_flags |= QIB_R_REUSE_SGE;
ibp->n_pkt_drops++;
goto bail_unlock;
}
if (ah_attr->ah_flags & IB_AH_GRH) {
qib_copy_sge(&qp->r_sge, &ah_attr->grh,
sizeof(struct ib_grh), 1);
wc.wc_flags |= IB_WC_GRH;
} else
qib_skip_sge(&qp->r_sge, sizeof(struct ib_grh), 1);
ssge.sg_list = swqe->sg_list + 1;
ssge.sge = *swqe->sg_list;
ssge.num_sge = swqe->wr.num_sge;
sge = &ssge.sge;
while (length) {
u32 len = sge->length;
if (len > length)
len = length;
if (len > sge->sge_length)
len = sge->sge_length;
BUG_ON(len == 0);
qib_copy_sge(&qp->r_sge, sge->vaddr, len, 1);
sge->vaddr += len;
sge->length -= len;
sge->sge_length -= len;
if (sge->sge_length == 0) {
if (--ssge.num_sge)
*sge = *ssge.sg_list++;
} else if (sge->length == 0 && sge->mr->lkey) {
if (++sge->n >= QIB_SEGSZ) {
if (++sge->m >= sge->mr->mapsz)
break;
sge->n = 0;
}
sge->vaddr =
sge->mr->map[sge->m]->segs[sge->n].vaddr;
sge->length =
sge->mr->map[sge->m]->segs[sge->n].length;
}
length -= len;
}
while (qp->r_sge.num_sge) {
atomic_dec(&qp->r_sge.sge.mr->refcount);
if (--qp->r_sge.num_sge)
qp->r_sge.sge = *qp->r_sge.sg_list++;
}
if (!test_and_clear_bit(QIB_R_WRID_VALID, &qp->r_aflags))
goto bail_unlock;
wc.wr_id = qp->r_wr_id;
wc.status = IB_WC_SUCCESS;
wc.opcode = IB_WC_RECV;
wc.qp = &qp->ibqp;
wc.src_qp = sqp->ibqp.qp_num;
wc.pkey_index = qp->ibqp.qp_type == IB_QPT_GSI ?
swqe->wr.wr.ud.pkey_index : 0;
wc.slid = ppd->lid | (ah_attr->src_path_bits & ((1 << ppd->lmc) - 1));
wc.sl = ah_attr->sl;
wc.dlid_path_bits = ah_attr->dlid & ((1 << ppd->lmc) - 1);
wc.port_num = qp->port_num;
/* Signal completion event if the solicited bit is set. */
qib_cq_enter(to_icq(qp->ibqp.recv_cq), &wc,
swqe->wr.send_flags & IB_SEND_SOLICITED);
ibp->n_loop_pkts++;
bail_unlock:
spin_unlock_irqrestore(&qp->r_lock, flags);
drop:
if (atomic_dec_and_test(&qp->refcount))
wake_up(&qp->wait);
}
/**
* qib_make_ud_req - construct a UD request packet
* @qp: the QP
*
* Return 1 if constructed; otherwise, return 0.
*/
int qib_make_ud_req(struct qib_qp *qp)
{
struct qib_other_headers *ohdr;
struct ib_ah_attr *ah_attr;
struct qib_pportdata *ppd;
struct qib_ibport *ibp;
struct qib_swqe *wqe;
unsigned long flags;
u32 nwords;
u32 extra_bytes;
u32 bth0;
u16 lrh0;
u16 lid;
int ret = 0;
int next_cur;
spin_lock_irqsave(&qp->s_lock, flags);
if (!(ib_qib_state_ops[qp->state] & QIB_PROCESS_NEXT_SEND_OK)) {
if (!(ib_qib_state_ops[qp->state] & QIB_FLUSH_SEND))
goto bail;
/* We are in the error state, flush the work request. */
if (qp->s_last == qp->s_head)
goto bail;
/* If DMAs are in progress, we can't flush immediately. */
if (atomic_read(&qp->s_dma_busy)) {
qp->s_flags |= QIB_S_WAIT_DMA;
goto bail;
}
wqe = get_swqe_ptr(qp, qp->s_last);
qib_send_complete(qp, wqe, IB_WC_WR_FLUSH_ERR);
goto done;
}
if (qp->s_cur == qp->s_head)
goto bail;
wqe = get_swqe_ptr(qp, qp->s_cur);
next_cur = qp->s_cur + 1;
if (next_cur >= qp->s_size)
next_cur = 0;
/* Construct the header. */
ibp = to_iport(qp->ibqp.device, qp->port_num);
ppd = ppd_from_ibp(ibp);
ah_attr = &to_iah(wqe->wr.wr.ud.ah)->attr;
if (ah_attr->dlid >= QIB_MULTICAST_LID_BASE) {
if (ah_attr->dlid != QIB_PERMISSIVE_LID)
ibp->n_multicast_xmit++;
else
ibp->n_unicast_xmit++;
} else {
ibp->n_unicast_xmit++;
lid = ah_attr->dlid & ~((1 << ppd->lmc) - 1);
if (unlikely(lid == ppd->lid)) {
/*
* If DMAs are in progress, we can't generate
* a completion for the loopback packet since
* it would be out of order.
* XXX Instead of waiting, we could queue a
* zero length descriptor so we get a callback.
*/
if (atomic_read(&qp->s_dma_busy)) {
qp->s_flags |= QIB_S_WAIT_DMA;
goto bail;
}
qp->s_cur = next_cur;
spin_unlock_irqrestore(&qp->s_lock, flags);
qib_ud_loopback(qp, wqe);
spin_lock_irqsave(&qp->s_lock, flags);
qib_send_complete(qp, wqe, IB_WC_SUCCESS);
goto done;
}
}
qp->s_cur = next_cur;
extra_bytes = -wqe->length & 3;
nwords = (wqe->length + extra_bytes) >> 2;
/* header size in 32-bit words LRH+BTH+DETH = (8+12+8)/4. */
qp->s_hdrwords = 7;
qp->s_cur_size = wqe->length;
qp->s_cur_sge = &qp->s_sge;
qp->s_srate = ah_attr->static_rate;
qp->s_wqe = wqe;
qp->s_sge.sge = wqe->sg_list[0];
qp->s_sge.sg_list = wqe->sg_list + 1;
qp->s_sge.num_sge = wqe->wr.num_sge;
qp->s_sge.total_len = wqe->length;
if (ah_attr->ah_flags & IB_AH_GRH) {
/* Header size in 32-bit words. */
qp->s_hdrwords += qib_make_grh(ibp, &qp->s_hdr.u.l.grh,
&ah_attr->grh,
qp->s_hdrwords, nwords);
lrh0 = QIB_LRH_GRH;
ohdr = &qp->s_hdr.u.l.oth;
/*
* Don't worry about sending to locally attached multicast
* QPs. It is unspecified by the spec. what happens.
*/
} else {
/* Header size in 32-bit words. */
lrh0 = QIB_LRH_BTH;
ohdr = &qp->s_hdr.u.oth;
}
if (wqe->wr.opcode == IB_WR_SEND_WITH_IMM) {
qp->s_hdrwords++;
ohdr->u.ud.imm_data = wqe->wr.ex.imm_data;
bth0 = IB_OPCODE_UD_SEND_ONLY_WITH_IMMEDIATE << 24;
} else
bth0 = IB_OPCODE_UD_SEND_ONLY << 24;
lrh0 |= ah_attr->sl << 4;
if (qp->ibqp.qp_type == IB_QPT_SMI)
lrh0 |= 0xF000; /* Set VL (see ch. 13.5.3.1) */
else
lrh0 |= ibp->sl_to_vl[ah_attr->sl] << 12;
qp->s_hdr.lrh[0] = cpu_to_be16(lrh0);
qp->s_hdr.lrh[1] = cpu_to_be16(ah_attr->dlid); /* DEST LID */
qp->s_hdr.lrh[2] = cpu_to_be16(qp->s_hdrwords + nwords + SIZE_OF_CRC);
lid = ppd->lid;
if (lid) {
lid |= ah_attr->src_path_bits & ((1 << ppd->lmc) - 1);
qp->s_hdr.lrh[3] = cpu_to_be16(lid);
} else
qp->s_hdr.lrh[3] = IB_LID_PERMISSIVE;
if (wqe->wr.send_flags & IB_SEND_SOLICITED)
bth0 |= IB_BTH_SOLICITED;
bth0 |= extra_bytes << 20;
bth0 |= qp->ibqp.qp_type == IB_QPT_SMI ? QIB_DEFAULT_P_KEY :
qib_get_pkey(ibp, qp->ibqp.qp_type == IB_QPT_GSI ?
wqe->wr.wr.ud.pkey_index : qp->s_pkey_index);
ohdr->bth[0] = cpu_to_be32(bth0);
/*
* Use the multicast QP if the destination LID is a multicast LID.
*/
ohdr->bth[1] = ah_attr->dlid >= QIB_MULTICAST_LID_BASE &&
ah_attr->dlid != QIB_PERMISSIVE_LID ?
cpu_to_be32(QIB_MULTICAST_QPN) :
cpu_to_be32(wqe->wr.wr.ud.remote_qpn);
ohdr->bth[2] = cpu_to_be32(qp->s_next_psn++ & QIB_PSN_MASK);
/*
* Qkeys with the high order bit set mean use the
* qkey from the QP context instead of the WR (see 10.2.5).
*/
ohdr->u.ud.deth[0] = cpu_to_be32((int)wqe->wr.wr.ud.remote_qkey < 0 ?
qp->qkey : wqe->wr.wr.ud.remote_qkey);
ohdr->u.ud.deth[1] = cpu_to_be32(qp->ibqp.qp_num);
done:
ret = 1;
goto unlock;
bail:
qp->s_flags &= ~QIB_S_BUSY;
unlock:
spin_unlock_irqrestore(&qp->s_lock, flags);
return ret;
}
static unsigned qib_lookup_pkey(struct qib_ibport *ibp, u16 pkey)
{
struct qib_pportdata *ppd = ppd_from_ibp(ibp);
struct qib_devdata *dd = ppd->dd;
unsigned ctxt = ppd->hw_pidx;
unsigned i;
pkey &= 0x7fff; /* remove limited/full membership bit */
for (i = 0; i < ARRAY_SIZE(dd->rcd[ctxt]->pkeys); ++i)
if ((dd->rcd[ctxt]->pkeys[i] & 0x7fff) == pkey)
return i;
/*
* Should not get here, this means hardware failed to validate pkeys.
* Punt and return index 0.
*/
return 0;
}
/**
* qib_ud_rcv - receive an incoming UD packet
* @ibp: the port the packet came in on
* @hdr: the packet header
* @has_grh: true if the packet has a GRH
* @data: the packet data
* @tlen: the packet length
* @qp: the QP the packet came on
*
* This is called from qib_qp_rcv() to process an incoming UD packet
* for the given QP.
* Called at interrupt level.
*/
void qib_ud_rcv(struct qib_ibport *ibp, struct qib_ib_header *hdr,
int has_grh, void *data, u32 tlen, struct qib_qp *qp)
{
struct qib_other_headers *ohdr;
int opcode;
u32 hdrsize;
u32 pad;
struct ib_wc wc;
u32 qkey;
u32 src_qp;
u16 dlid;
/* Check for GRH */
if (!has_grh) {
ohdr = &hdr->u.oth;
hdrsize = 8 + 12 + 8; /* LRH + BTH + DETH */
} else {
ohdr = &hdr->u.l.oth;
hdrsize = 8 + 40 + 12 + 8; /* LRH + GRH + BTH + DETH */
}
qkey = be32_to_cpu(ohdr->u.ud.deth[0]);
src_qp = be32_to_cpu(ohdr->u.ud.deth[1]) & QIB_QPN_MASK;
/*
* Get the number of bytes the message was padded by
* and drop incomplete packets.
*/
pad = (be32_to_cpu(ohdr->bth[0]) >> 20) & 3;
if (unlikely(tlen < (hdrsize + pad + 4)))
goto drop;
tlen -= hdrsize + pad + 4;
/*
* Check that the permissive LID is only used on QP0
* and the QKEY matches (see 9.6.1.4.1 and 9.6.1.5.1).
*/
if (qp->ibqp.qp_num) {
if (unlikely(hdr->lrh[1] == IB_LID_PERMISSIVE ||
hdr->lrh[3] == IB_LID_PERMISSIVE))
goto drop;
if (qp->ibqp.qp_num > 1) {
u16 pkey1, pkey2;
pkey1 = be32_to_cpu(ohdr->bth[0]);
pkey2 = qib_get_pkey(ibp, qp->s_pkey_index);
if (unlikely(!qib_pkey_ok(pkey1, pkey2))) {
qib_bad_pqkey(ibp, IB_NOTICE_TRAP_BAD_PKEY,
pkey1,
(be16_to_cpu(hdr->lrh[0]) >> 4) &
0xF,
src_qp, qp->ibqp.qp_num,
hdr->lrh[3], hdr->lrh[1]);
return;
}
}
if (unlikely(qkey != qp->qkey)) {
qib_bad_pqkey(ibp, IB_NOTICE_TRAP_BAD_QKEY, qkey,
(be16_to_cpu(hdr->lrh[0]) >> 4) & 0xF,
src_qp, qp->ibqp.qp_num,
hdr->lrh[3], hdr->lrh[1]);
return;
}
/* Drop invalid MAD packets (see 13.5.3.1). */
if (unlikely(qp->ibqp.qp_num == 1 &&
(tlen != 256 ||
(be16_to_cpu(hdr->lrh[0]) >> 12) == 15)))
goto drop;
} else {
struct ib_smp *smp;
/* Drop invalid MAD packets (see 13.5.3.1). */
if (tlen != 256 || (be16_to_cpu(hdr->lrh[0]) >> 12) != 15)
goto drop;
smp = (struct ib_smp *) data;
if ((hdr->lrh[1] == IB_LID_PERMISSIVE ||
hdr->lrh[3] == IB_LID_PERMISSIVE) &&
smp->mgmt_class != IB_MGMT_CLASS_SUBN_DIRECTED_ROUTE)
goto drop;
}
/*
* The opcode is in the low byte when its in network order
* (top byte when in host order).
*/
opcode = be32_to_cpu(ohdr->bth[0]) >> 24;
if (qp->ibqp.qp_num > 1 &&
opcode == IB_OPCODE_UD_SEND_ONLY_WITH_IMMEDIATE) {
wc.ex.imm_data = ohdr->u.ud.imm_data;
wc.wc_flags = IB_WC_WITH_IMM;
tlen -= sizeof(u32);
} else if (opcode == IB_OPCODE_UD_SEND_ONLY) {
wc.ex.imm_data = 0;
wc.wc_flags = 0;
} else
goto drop;
/*
* A GRH is expected to precede the data even if not
* present on the wire.
*/
wc.byte_len = tlen + sizeof(struct ib_grh);
/*
* Get the next work request entry to find where to put the data.
*/
if (qp->r_flags & QIB_R_REUSE_SGE)
qp->r_flags &= ~QIB_R_REUSE_SGE;
else {
int ret;
ret = qib_get_rwqe(qp, 0);
if (ret < 0) {
qib_rc_error(qp, IB_WC_LOC_QP_OP_ERR);
return;
}
if (!ret) {
if (qp->ibqp.qp_num == 0)
ibp->n_vl15_dropped++;
return;
}
}
/* Silently drop packets which are too big. */
if (unlikely(wc.byte_len > qp->r_len)) {
qp->r_flags |= QIB_R_REUSE_SGE;
goto drop;
}
if (has_grh) {
qib_copy_sge(&qp->r_sge, &hdr->u.l.grh,
sizeof(struct ib_grh), 1);
wc.wc_flags |= IB_WC_GRH;
} else
qib_skip_sge(&qp->r_sge, sizeof(struct ib_grh), 1);
qib_copy_sge(&qp->r_sge, data, wc.byte_len - sizeof(struct ib_grh), 1);
while (qp->r_sge.num_sge) {
atomic_dec(&qp->r_sge.sge.mr->refcount);
if (--qp->r_sge.num_sge)
qp->r_sge.sge = *qp->r_sge.sg_list++;
}
if (!test_and_clear_bit(QIB_R_WRID_VALID, &qp->r_aflags))
return;
wc.wr_id = qp->r_wr_id;
wc.status = IB_WC_SUCCESS;
wc.opcode = IB_WC_RECV;
wc.vendor_err = 0;
wc.qp = &qp->ibqp;
wc.src_qp = src_qp;
wc.pkey_index = qp->ibqp.qp_type == IB_QPT_GSI ?
qib_lookup_pkey(ibp, be32_to_cpu(ohdr->bth[0])) : 0;
wc.slid = be16_to_cpu(hdr->lrh[3]);
wc.sl = (be16_to_cpu(hdr->lrh[0]) >> 4) & 0xF;
dlid = be16_to_cpu(hdr->lrh[1]);
/*
* Save the LMC lower bits if the destination LID is a unicast LID.
*/
wc.dlid_path_bits = dlid >= QIB_MULTICAST_LID_BASE ? 0 :
dlid & ((1 << ppd_from_ibp(ibp)->lmc) - 1);
wc.port_num = qp->port_num;
/* Signal completion event if the solicited bit is set. */
qib_cq_enter(to_icq(qp->ibqp.recv_cq), &wc,
(ohdr->bth[0] &
cpu_to_be32(IB_BTH_SOLICITED)) != 0);
return;
drop:
ibp->n_pkt_drops++;
}
| gpl-2.0 |
zombi-x/that1_kernel_asus_tf700t | drivers/block/mg_disk.c | 8358 | 26577 | /*
* drivers/block/mg_disk.c
*
* Support for the mGine m[g]flash IO mode.
* Based on legacy hd.c
*
* (c) 2008 mGine Co.,LTD
* (c) 2008 unsik Kim <donari75@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/blkdev.h>
#include <linux/hdreg.h>
#include <linux/ata.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <linux/mg_disk.h>
#include <linux/slab.h>
#define MG_RES_SEC (CONFIG_MG_DISK_RES << 1)
/* name for block device */
#define MG_DISK_NAME "mgd"
#define MG_DISK_MAJ 0
#define MG_DISK_MAX_PART 16
#define MG_SECTOR_SIZE 512
#define MG_MAX_SECTS 256
/* Register offsets */
#define MG_BUFF_OFFSET 0x8000
#define MG_REG_OFFSET 0xC000
#define MG_REG_FEATURE (MG_REG_OFFSET + 2) /* write case */
#define MG_REG_ERROR (MG_REG_OFFSET + 2) /* read case */
#define MG_REG_SECT_CNT (MG_REG_OFFSET + 4)
#define MG_REG_SECT_NUM (MG_REG_OFFSET + 6)
#define MG_REG_CYL_LOW (MG_REG_OFFSET + 8)
#define MG_REG_CYL_HIGH (MG_REG_OFFSET + 0xA)
#define MG_REG_DRV_HEAD (MG_REG_OFFSET + 0xC)
#define MG_REG_COMMAND (MG_REG_OFFSET + 0xE) /* write case */
#define MG_REG_STATUS (MG_REG_OFFSET + 0xE) /* read case */
#define MG_REG_DRV_CTRL (MG_REG_OFFSET + 0x10)
#define MG_REG_BURST_CTRL (MG_REG_OFFSET + 0x12)
/* handy status */
#define MG_STAT_READY (ATA_DRDY | ATA_DSC)
#define MG_READY_OK(s) (((s) & (MG_STAT_READY | (ATA_BUSY | ATA_DF | \
ATA_ERR))) == MG_STAT_READY)
/* error code for others */
#define MG_ERR_NONE 0
#define MG_ERR_TIMEOUT 0x100
#define MG_ERR_INIT_STAT 0x101
#define MG_ERR_TRANSLATION 0x102
#define MG_ERR_CTRL_RST 0x103
#define MG_ERR_INV_STAT 0x104
#define MG_ERR_RSTOUT 0x105
#define MG_MAX_ERRORS 6 /* Max read/write errors */
/* command */
#define MG_CMD_RD 0x20
#define MG_CMD_WR 0x30
#define MG_CMD_SLEEP 0x99
#define MG_CMD_WAKEUP 0xC3
#define MG_CMD_ID 0xEC
#define MG_CMD_WR_CONF 0x3C
#define MG_CMD_RD_CONF 0x40
/* operation mode */
#define MG_OP_CASCADE (1 << 0)
#define MG_OP_CASCADE_SYNC_RD (1 << 1)
#define MG_OP_CASCADE_SYNC_WR (1 << 2)
#define MG_OP_INTERLEAVE (1 << 3)
/* synchronous */
#define MG_BURST_LAT_4 (3 << 4)
#define MG_BURST_LAT_5 (4 << 4)
#define MG_BURST_LAT_6 (5 << 4)
#define MG_BURST_LAT_7 (6 << 4)
#define MG_BURST_LAT_8 (7 << 4)
#define MG_BURST_LEN_4 (1 << 1)
#define MG_BURST_LEN_8 (2 << 1)
#define MG_BURST_LEN_16 (3 << 1)
#define MG_BURST_LEN_32 (4 << 1)
#define MG_BURST_LEN_CONT (0 << 1)
/* timeout value (unit: ms) */
#define MG_TMAX_CONF_TO_CMD 1
#define MG_TMAX_WAIT_RD_DRQ 10
#define MG_TMAX_WAIT_WR_DRQ 500
#define MG_TMAX_RST_TO_BUSY 10
#define MG_TMAX_HDRST_TO_RDY 500
#define MG_TMAX_SWRST_TO_RDY 500
#define MG_TMAX_RSTOUT 3000
#define MG_DEV_MASK (MG_BOOT_DEV | MG_STORAGE_DEV | MG_STORAGE_DEV_SKIP_RST)
/* main structure for mflash driver */
struct mg_host {
struct device *dev;
struct request_queue *breq;
struct request *req;
spinlock_t lock;
struct gendisk *gd;
struct timer_list timer;
void (*mg_do_intr) (struct mg_host *);
u16 id[ATA_ID_WORDS];
u16 cyls;
u16 heads;
u16 sectors;
u32 n_sectors;
u32 nres_sectors;
void __iomem *dev_base;
unsigned int irq;
unsigned int rst;
unsigned int rstout;
u32 major;
u32 error;
};
/*
* Debugging macro and defines
*/
#undef DO_MG_DEBUG
#ifdef DO_MG_DEBUG
# define MG_DBG(fmt, args...) \
printk(KERN_DEBUG "%s:%d "fmt, __func__, __LINE__, ##args)
#else /* CONFIG_MG_DEBUG */
# define MG_DBG(fmt, args...) do { } while (0)
#endif /* CONFIG_MG_DEBUG */
static void mg_request(struct request_queue *);
static bool mg_end_request(struct mg_host *host, int err, unsigned int nr_bytes)
{
if (__blk_end_request(host->req, err, nr_bytes))
return true;
host->req = NULL;
return false;
}
static bool mg_end_request_cur(struct mg_host *host, int err)
{
return mg_end_request(host, err, blk_rq_cur_bytes(host->req));
}
static void mg_dump_status(const char *msg, unsigned int stat,
struct mg_host *host)
{
char *name = MG_DISK_NAME;
if (host->req)
name = host->req->rq_disk->disk_name;
printk(KERN_ERR "%s: %s: status=0x%02x { ", name, msg, stat & 0xff);
if (stat & ATA_BUSY)
printk("Busy ");
if (stat & ATA_DRDY)
printk("DriveReady ");
if (stat & ATA_DF)
printk("WriteFault ");
if (stat & ATA_DSC)
printk("SeekComplete ");
if (stat & ATA_DRQ)
printk("DataRequest ");
if (stat & ATA_CORR)
printk("CorrectedError ");
if (stat & ATA_ERR)
printk("Error ");
printk("}\n");
if ((stat & ATA_ERR) == 0) {
host->error = 0;
} else {
host->error = inb((unsigned long)host->dev_base + MG_REG_ERROR);
printk(KERN_ERR "%s: %s: error=0x%02x { ", name, msg,
host->error & 0xff);
if (host->error & ATA_BBK)
printk("BadSector ");
if (host->error & ATA_UNC)
printk("UncorrectableError ");
if (host->error & ATA_IDNF)
printk("SectorIdNotFound ");
if (host->error & ATA_ABORTED)
printk("DriveStatusError ");
if (host->error & ATA_AMNF)
printk("AddrMarkNotFound ");
printk("}");
if (host->error & (ATA_BBK | ATA_UNC | ATA_IDNF | ATA_AMNF)) {
if (host->req)
printk(", sector=%u",
(unsigned int)blk_rq_pos(host->req));
}
printk("\n");
}
}
static unsigned int mg_wait(struct mg_host *host, u32 expect, u32 msec)
{
u8 status;
unsigned long expire, cur_jiffies;
struct mg_drv_data *prv_data = host->dev->platform_data;
host->error = MG_ERR_NONE;
expire = jiffies + msecs_to_jiffies(msec);
/* These 2 times dummy status read prevents reading invalid
* status. A very little time (3 times of mflash operating clk)
* is required for busy bit is set. Use dummy read instead of
* busy wait, because mflash's PLL is machine dependent.
*/
if (prv_data->use_polling) {
status = inb((unsigned long)host->dev_base + MG_REG_STATUS);
status = inb((unsigned long)host->dev_base + MG_REG_STATUS);
}
status = inb((unsigned long)host->dev_base + MG_REG_STATUS);
do {
cur_jiffies = jiffies;
if (status & ATA_BUSY) {
if (expect == ATA_BUSY)
break;
} else {
/* Check the error condition! */
if (status & ATA_ERR) {
mg_dump_status("mg_wait", status, host);
break;
}
if (expect == MG_STAT_READY)
if (MG_READY_OK(status))
break;
if (expect == ATA_DRQ)
if (status & ATA_DRQ)
break;
}
if (!msec) {
mg_dump_status("not ready", status, host);
return MG_ERR_INV_STAT;
}
status = inb((unsigned long)host->dev_base + MG_REG_STATUS);
} while (time_before(cur_jiffies, expire));
if (time_after_eq(cur_jiffies, expire) && msec)
host->error = MG_ERR_TIMEOUT;
return host->error;
}
static unsigned int mg_wait_rstout(u32 rstout, u32 msec)
{
unsigned long expire;
expire = jiffies + msecs_to_jiffies(msec);
while (time_before(jiffies, expire)) {
if (gpio_get_value(rstout) == 1)
return MG_ERR_NONE;
msleep(10);
}
return MG_ERR_RSTOUT;
}
static void mg_unexpected_intr(struct mg_host *host)
{
u32 status = inb((unsigned long)host->dev_base + MG_REG_STATUS);
mg_dump_status("mg_unexpected_intr", status, host);
}
static irqreturn_t mg_irq(int irq, void *dev_id)
{
struct mg_host *host = dev_id;
void (*handler)(struct mg_host *) = host->mg_do_intr;
spin_lock(&host->lock);
host->mg_do_intr = NULL;
del_timer(&host->timer);
if (!handler)
handler = mg_unexpected_intr;
handler(host);
spin_unlock(&host->lock);
return IRQ_HANDLED;
}
/* local copy of ata_id_string() */
static void mg_id_string(const u16 *id, unsigned char *s,
unsigned int ofs, unsigned int len)
{
unsigned int c;
BUG_ON(len & 1);
while (len > 0) {
c = id[ofs] >> 8;
*s = c;
s++;
c = id[ofs] & 0xff;
*s = c;
s++;
ofs++;
len -= 2;
}
}
/* local copy of ata_id_c_string() */
static void mg_id_c_string(const u16 *id, unsigned char *s,
unsigned int ofs, unsigned int len)
{
unsigned char *p;
mg_id_string(id, s, ofs, len - 1);
p = s + strnlen(s, len - 1);
while (p > s && p[-1] == ' ')
p--;
*p = '\0';
}
static int mg_get_disk_id(struct mg_host *host)
{
u32 i;
s32 err;
const u16 *id = host->id;
struct mg_drv_data *prv_data = host->dev->platform_data;
char fwrev[ATA_ID_FW_REV_LEN + 1];
char model[ATA_ID_PROD_LEN + 1];
char serial[ATA_ID_SERNO_LEN + 1];
if (!prv_data->use_polling)
outb(ATA_NIEN, (unsigned long)host->dev_base + MG_REG_DRV_CTRL);
outb(MG_CMD_ID, (unsigned long)host->dev_base + MG_REG_COMMAND);
err = mg_wait(host, ATA_DRQ, MG_TMAX_WAIT_RD_DRQ);
if (err)
return err;
for (i = 0; i < (MG_SECTOR_SIZE >> 1); i++)
host->id[i] = le16_to_cpu(inw((unsigned long)host->dev_base +
MG_BUFF_OFFSET + i * 2));
outb(MG_CMD_RD_CONF, (unsigned long)host->dev_base + MG_REG_COMMAND);
err = mg_wait(host, MG_STAT_READY, MG_TMAX_CONF_TO_CMD);
if (err)
return err;
if ((id[ATA_ID_FIELD_VALID] & 1) == 0)
return MG_ERR_TRANSLATION;
host->n_sectors = ata_id_u32(id, ATA_ID_LBA_CAPACITY);
host->cyls = id[ATA_ID_CYLS];
host->heads = id[ATA_ID_HEADS];
host->sectors = id[ATA_ID_SECTORS];
if (MG_RES_SEC && host->heads && host->sectors) {
/* modify cyls, n_sectors */
host->cyls = (host->n_sectors - MG_RES_SEC) /
host->heads / host->sectors;
host->nres_sectors = host->n_sectors - host->cyls *
host->heads * host->sectors;
host->n_sectors -= host->nres_sectors;
}
mg_id_c_string(id, fwrev, ATA_ID_FW_REV, sizeof(fwrev));
mg_id_c_string(id, model, ATA_ID_PROD, sizeof(model));
mg_id_c_string(id, serial, ATA_ID_SERNO, sizeof(serial));
printk(KERN_INFO "mg_disk: model: %s\n", model);
printk(KERN_INFO "mg_disk: firm: %.8s\n", fwrev);
printk(KERN_INFO "mg_disk: serial: %s\n", serial);
printk(KERN_INFO "mg_disk: %d + reserved %d sectors\n",
host->n_sectors, host->nres_sectors);
if (!prv_data->use_polling)
outb(0, (unsigned long)host->dev_base + MG_REG_DRV_CTRL);
return err;
}
static int mg_disk_init(struct mg_host *host)
{
struct mg_drv_data *prv_data = host->dev->platform_data;
s32 err;
u8 init_status;
/* hdd rst low */
gpio_set_value(host->rst, 0);
err = mg_wait(host, ATA_BUSY, MG_TMAX_RST_TO_BUSY);
if (err)
return err;
/* hdd rst high */
gpio_set_value(host->rst, 1);
err = mg_wait(host, MG_STAT_READY, MG_TMAX_HDRST_TO_RDY);
if (err)
return err;
/* soft reset on */
outb(ATA_SRST | (prv_data->use_polling ? ATA_NIEN : 0),
(unsigned long)host->dev_base + MG_REG_DRV_CTRL);
err = mg_wait(host, ATA_BUSY, MG_TMAX_RST_TO_BUSY);
if (err)
return err;
/* soft reset off */
outb(prv_data->use_polling ? ATA_NIEN : 0,
(unsigned long)host->dev_base + MG_REG_DRV_CTRL);
err = mg_wait(host, MG_STAT_READY, MG_TMAX_SWRST_TO_RDY);
if (err)
return err;
init_status = inb((unsigned long)host->dev_base + MG_REG_STATUS) & 0xf;
if (init_status == 0xf)
return MG_ERR_INIT_STAT;
return err;
}
static void mg_bad_rw_intr(struct mg_host *host)
{
if (host->req)
if (++host->req->errors >= MG_MAX_ERRORS ||
host->error == MG_ERR_TIMEOUT)
mg_end_request_cur(host, -EIO);
}
static unsigned int mg_out(struct mg_host *host,
unsigned int sect_num,
unsigned int sect_cnt,
unsigned int cmd,
void (*intr_addr)(struct mg_host *))
{
struct mg_drv_data *prv_data = host->dev->platform_data;
if (mg_wait(host, MG_STAT_READY, MG_TMAX_CONF_TO_CMD))
return host->error;
if (!prv_data->use_polling) {
host->mg_do_intr = intr_addr;
mod_timer(&host->timer, jiffies + 3 * HZ);
}
if (MG_RES_SEC)
sect_num += MG_RES_SEC;
outb((u8)sect_cnt, (unsigned long)host->dev_base + MG_REG_SECT_CNT);
outb((u8)sect_num, (unsigned long)host->dev_base + MG_REG_SECT_NUM);
outb((u8)(sect_num >> 8), (unsigned long)host->dev_base +
MG_REG_CYL_LOW);
outb((u8)(sect_num >> 16), (unsigned long)host->dev_base +
MG_REG_CYL_HIGH);
outb((u8)((sect_num >> 24) | ATA_LBA | ATA_DEVICE_OBS),
(unsigned long)host->dev_base + MG_REG_DRV_HEAD);
outb(cmd, (unsigned long)host->dev_base + MG_REG_COMMAND);
return MG_ERR_NONE;
}
static void mg_read_one(struct mg_host *host, struct request *req)
{
u16 *buff = (u16 *)req->buffer;
u32 i;
for (i = 0; i < MG_SECTOR_SIZE >> 1; i++)
*buff++ = inw((unsigned long)host->dev_base + MG_BUFF_OFFSET +
(i << 1));
}
static void mg_read(struct request *req)
{
struct mg_host *host = req->rq_disk->private_data;
if (mg_out(host, blk_rq_pos(req), blk_rq_sectors(req),
MG_CMD_RD, NULL) != MG_ERR_NONE)
mg_bad_rw_intr(host);
MG_DBG("requested %d sects (from %ld), buffer=0x%p\n",
blk_rq_sectors(req), blk_rq_pos(req), req->buffer);
do {
if (mg_wait(host, ATA_DRQ,
MG_TMAX_WAIT_RD_DRQ) != MG_ERR_NONE) {
mg_bad_rw_intr(host);
return;
}
mg_read_one(host, req);
outb(MG_CMD_RD_CONF, (unsigned long)host->dev_base +
MG_REG_COMMAND);
} while (mg_end_request(host, 0, MG_SECTOR_SIZE));
}
static void mg_write_one(struct mg_host *host, struct request *req)
{
u16 *buff = (u16 *)req->buffer;
u32 i;
for (i = 0; i < MG_SECTOR_SIZE >> 1; i++)
outw(*buff++, (unsigned long)host->dev_base + MG_BUFF_OFFSET +
(i << 1));
}
static void mg_write(struct request *req)
{
struct mg_host *host = req->rq_disk->private_data;
unsigned int rem = blk_rq_sectors(req);
if (mg_out(host, blk_rq_pos(req), rem,
MG_CMD_WR, NULL) != MG_ERR_NONE) {
mg_bad_rw_intr(host);
return;
}
MG_DBG("requested %d sects (from %ld), buffer=0x%p\n",
rem, blk_rq_pos(req), req->buffer);
if (mg_wait(host, ATA_DRQ,
MG_TMAX_WAIT_WR_DRQ) != MG_ERR_NONE) {
mg_bad_rw_intr(host);
return;
}
do {
mg_write_one(host, req);
outb(MG_CMD_WR_CONF, (unsigned long)host->dev_base +
MG_REG_COMMAND);
rem--;
if (rem > 1 && mg_wait(host, ATA_DRQ,
MG_TMAX_WAIT_WR_DRQ) != MG_ERR_NONE) {
mg_bad_rw_intr(host);
return;
} else if (mg_wait(host, MG_STAT_READY,
MG_TMAX_WAIT_WR_DRQ) != MG_ERR_NONE) {
mg_bad_rw_intr(host);
return;
}
} while (mg_end_request(host, 0, MG_SECTOR_SIZE));
}
static void mg_read_intr(struct mg_host *host)
{
struct request *req = host->req;
u32 i;
/* check status */
do {
i = inb((unsigned long)host->dev_base + MG_REG_STATUS);
if (i & ATA_BUSY)
break;
if (!MG_READY_OK(i))
break;
if (i & ATA_DRQ)
goto ok_to_read;
} while (0);
mg_dump_status("mg_read_intr", i, host);
mg_bad_rw_intr(host);
mg_request(host->breq);
return;
ok_to_read:
mg_read_one(host, req);
MG_DBG("sector %ld, remaining=%ld, buffer=0x%p\n",
blk_rq_pos(req), blk_rq_sectors(req) - 1, req->buffer);
/* send read confirm */
outb(MG_CMD_RD_CONF, (unsigned long)host->dev_base + MG_REG_COMMAND);
if (mg_end_request(host, 0, MG_SECTOR_SIZE)) {
/* set handler if read remains */
host->mg_do_intr = mg_read_intr;
mod_timer(&host->timer, jiffies + 3 * HZ);
} else /* goto next request */
mg_request(host->breq);
}
static void mg_write_intr(struct mg_host *host)
{
struct request *req = host->req;
u32 i;
bool rem;
/* check status */
do {
i = inb((unsigned long)host->dev_base + MG_REG_STATUS);
if (i & ATA_BUSY)
break;
if (!MG_READY_OK(i))
break;
if ((blk_rq_sectors(req) <= 1) || (i & ATA_DRQ))
goto ok_to_write;
} while (0);
mg_dump_status("mg_write_intr", i, host);
mg_bad_rw_intr(host);
mg_request(host->breq);
return;
ok_to_write:
if ((rem = mg_end_request(host, 0, MG_SECTOR_SIZE))) {
/* write 1 sector and set handler if remains */
mg_write_one(host, req);
MG_DBG("sector %ld, remaining=%ld, buffer=0x%p\n",
blk_rq_pos(req), blk_rq_sectors(req), req->buffer);
host->mg_do_intr = mg_write_intr;
mod_timer(&host->timer, jiffies + 3 * HZ);
}
/* send write confirm */
outb(MG_CMD_WR_CONF, (unsigned long)host->dev_base + MG_REG_COMMAND);
if (!rem)
mg_request(host->breq);
}
void mg_times_out(unsigned long data)
{
struct mg_host *host = (struct mg_host *)data;
char *name;
spin_lock_irq(&host->lock);
if (!host->req)
goto out_unlock;
host->mg_do_intr = NULL;
name = host->req->rq_disk->disk_name;
printk(KERN_DEBUG "%s: timeout\n", name);
host->error = MG_ERR_TIMEOUT;
mg_bad_rw_intr(host);
out_unlock:
mg_request(host->breq);
spin_unlock_irq(&host->lock);
}
static void mg_request_poll(struct request_queue *q)
{
struct mg_host *host = q->queuedata;
while (1) {
if (!host->req) {
host->req = blk_fetch_request(q);
if (!host->req)
break;
}
if (unlikely(host->req->cmd_type != REQ_TYPE_FS)) {
mg_end_request_cur(host, -EIO);
continue;
}
if (rq_data_dir(host->req) == READ)
mg_read(host->req);
else
mg_write(host->req);
}
}
static unsigned int mg_issue_req(struct request *req,
struct mg_host *host,
unsigned int sect_num,
unsigned int sect_cnt)
{
switch (rq_data_dir(req)) {
case READ:
if (mg_out(host, sect_num, sect_cnt, MG_CMD_RD, &mg_read_intr)
!= MG_ERR_NONE) {
mg_bad_rw_intr(host);
return host->error;
}
break;
case WRITE:
/* TODO : handler */
outb(ATA_NIEN, (unsigned long)host->dev_base + MG_REG_DRV_CTRL);
if (mg_out(host, sect_num, sect_cnt, MG_CMD_WR, &mg_write_intr)
!= MG_ERR_NONE) {
mg_bad_rw_intr(host);
return host->error;
}
del_timer(&host->timer);
mg_wait(host, ATA_DRQ, MG_TMAX_WAIT_WR_DRQ);
outb(0, (unsigned long)host->dev_base + MG_REG_DRV_CTRL);
if (host->error) {
mg_bad_rw_intr(host);
return host->error;
}
mg_write_one(host, req);
mod_timer(&host->timer, jiffies + 3 * HZ);
outb(MG_CMD_WR_CONF, (unsigned long)host->dev_base +
MG_REG_COMMAND);
break;
}
return MG_ERR_NONE;
}
/* This function also called from IRQ context */
static void mg_request(struct request_queue *q)
{
struct mg_host *host = q->queuedata;
struct request *req;
u32 sect_num, sect_cnt;
while (1) {
if (!host->req) {
host->req = blk_fetch_request(q);
if (!host->req)
break;
}
req = host->req;
/* check unwanted request call */
if (host->mg_do_intr)
return;
del_timer(&host->timer);
sect_num = blk_rq_pos(req);
/* deal whole segments */
sect_cnt = blk_rq_sectors(req);
/* sanity check */
if (sect_num >= get_capacity(req->rq_disk) ||
((sect_num + sect_cnt) >
get_capacity(req->rq_disk))) {
printk(KERN_WARNING
"%s: bad access: sector=%d, count=%d\n",
req->rq_disk->disk_name,
sect_num, sect_cnt);
mg_end_request_cur(host, -EIO);
continue;
}
if (unlikely(req->cmd_type != REQ_TYPE_FS)) {
mg_end_request_cur(host, -EIO);
continue;
}
if (!mg_issue_req(req, host, sect_num, sect_cnt))
return;
}
}
static int mg_getgeo(struct block_device *bdev, struct hd_geometry *geo)
{
struct mg_host *host = bdev->bd_disk->private_data;
geo->cylinders = (unsigned short)host->cyls;
geo->heads = (unsigned char)host->heads;
geo->sectors = (unsigned char)host->sectors;
return 0;
}
static const struct block_device_operations mg_disk_ops = {
.getgeo = mg_getgeo
};
static int mg_suspend(struct platform_device *plat_dev, pm_message_t state)
{
struct mg_drv_data *prv_data = plat_dev->dev.platform_data;
struct mg_host *host = prv_data->host;
if (mg_wait(host, MG_STAT_READY, MG_TMAX_CONF_TO_CMD))
return -EIO;
if (!prv_data->use_polling)
outb(ATA_NIEN, (unsigned long)host->dev_base + MG_REG_DRV_CTRL);
outb(MG_CMD_SLEEP, (unsigned long)host->dev_base + MG_REG_COMMAND);
/* wait until mflash deep sleep */
msleep(1);
if (mg_wait(host, MG_STAT_READY, MG_TMAX_CONF_TO_CMD)) {
if (!prv_data->use_polling)
outb(0, (unsigned long)host->dev_base + MG_REG_DRV_CTRL);
return -EIO;
}
return 0;
}
static int mg_resume(struct platform_device *plat_dev)
{
struct mg_drv_data *prv_data = plat_dev->dev.platform_data;
struct mg_host *host = prv_data->host;
if (mg_wait(host, MG_STAT_READY, MG_TMAX_CONF_TO_CMD))
return -EIO;
outb(MG_CMD_WAKEUP, (unsigned long)host->dev_base + MG_REG_COMMAND);
/* wait until mflash wakeup */
msleep(1);
if (mg_wait(host, MG_STAT_READY, MG_TMAX_CONF_TO_CMD))
return -EIO;
if (!prv_data->use_polling)
outb(0, (unsigned long)host->dev_base + MG_REG_DRV_CTRL);
return 0;
}
static int mg_probe(struct platform_device *plat_dev)
{
struct mg_host *host;
struct resource *rsc;
struct mg_drv_data *prv_data = plat_dev->dev.platform_data;
int err = 0;
if (!prv_data) {
printk(KERN_ERR "%s:%d fail (no driver_data)\n",
__func__, __LINE__);
err = -EINVAL;
goto probe_err;
}
/* alloc mg_host */
host = kzalloc(sizeof(struct mg_host), GFP_KERNEL);
if (!host) {
printk(KERN_ERR "%s:%d fail (no memory for mg_host)\n",
__func__, __LINE__);
err = -ENOMEM;
goto probe_err;
}
host->major = MG_DISK_MAJ;
/* link each other */
prv_data->host = host;
host->dev = &plat_dev->dev;
/* io remap */
rsc = platform_get_resource(plat_dev, IORESOURCE_MEM, 0);
if (!rsc) {
printk(KERN_ERR "%s:%d platform_get_resource fail\n",
__func__, __LINE__);
err = -EINVAL;
goto probe_err_2;
}
host->dev_base = ioremap(rsc->start, resource_size(rsc));
if (!host->dev_base) {
printk(KERN_ERR "%s:%d ioremap fail\n",
__func__, __LINE__);
err = -EIO;
goto probe_err_2;
}
MG_DBG("dev_base = 0x%x\n", (u32)host->dev_base);
/* get reset pin */
rsc = platform_get_resource_byname(plat_dev, IORESOURCE_IO,
MG_RST_PIN);
if (!rsc) {
printk(KERN_ERR "%s:%d get reset pin fail\n",
__func__, __LINE__);
err = -EIO;
goto probe_err_3;
}
host->rst = rsc->start;
/* init rst pin */
err = gpio_request(host->rst, MG_RST_PIN);
if (err)
goto probe_err_3;
gpio_direction_output(host->rst, 1);
/* reset out pin */
if (!(prv_data->dev_attr & MG_DEV_MASK))
goto probe_err_3a;
if (prv_data->dev_attr != MG_BOOT_DEV) {
rsc = platform_get_resource_byname(plat_dev, IORESOURCE_IO,
MG_RSTOUT_PIN);
if (!rsc) {
printk(KERN_ERR "%s:%d get reset-out pin fail\n",
__func__, __LINE__);
err = -EIO;
goto probe_err_3a;
}
host->rstout = rsc->start;
err = gpio_request(host->rstout, MG_RSTOUT_PIN);
if (err)
goto probe_err_3a;
gpio_direction_input(host->rstout);
}
/* disk reset */
if (prv_data->dev_attr == MG_STORAGE_DEV) {
/* If POR seq. not yet finised, wait */
err = mg_wait_rstout(host->rstout, MG_TMAX_RSTOUT);
if (err)
goto probe_err_3b;
err = mg_disk_init(host);
if (err) {
printk(KERN_ERR "%s:%d fail (err code : %d)\n",
__func__, __LINE__, err);
err = -EIO;
goto probe_err_3b;
}
}
/* get irq resource */
if (!prv_data->use_polling) {
host->irq = platform_get_irq(plat_dev, 0);
if (host->irq == -ENXIO) {
err = host->irq;
goto probe_err_3b;
}
err = request_irq(host->irq, mg_irq,
IRQF_DISABLED | IRQF_TRIGGER_RISING,
MG_DEV_NAME, host);
if (err) {
printk(KERN_ERR "%s:%d fail (request_irq err=%d)\n",
__func__, __LINE__, err);
goto probe_err_3b;
}
}
/* get disk id */
err = mg_get_disk_id(host);
if (err) {
printk(KERN_ERR "%s:%d fail (err code : %d)\n",
__func__, __LINE__, err);
err = -EIO;
goto probe_err_4;
}
err = register_blkdev(host->major, MG_DISK_NAME);
if (err < 0) {
printk(KERN_ERR "%s:%d register_blkdev fail (err code : %d)\n",
__func__, __LINE__, err);
goto probe_err_4;
}
if (!host->major)
host->major = err;
spin_lock_init(&host->lock);
if (prv_data->use_polling)
host->breq = blk_init_queue(mg_request_poll, &host->lock);
else
host->breq = blk_init_queue(mg_request, &host->lock);
if (!host->breq) {
err = -ENOMEM;
printk(KERN_ERR "%s:%d (blk_init_queue) fail\n",
__func__, __LINE__);
goto probe_err_5;
}
host->breq->queuedata = host;
/* mflash is random device, thanx for the noop */
err = elevator_change(host->breq, "noop");
if (err) {
printk(KERN_ERR "%s:%d (elevator_init) fail\n",
__func__, __LINE__);
goto probe_err_6;
}
blk_queue_max_hw_sectors(host->breq, MG_MAX_SECTS);
blk_queue_logical_block_size(host->breq, MG_SECTOR_SIZE);
init_timer(&host->timer);
host->timer.function = mg_times_out;
host->timer.data = (unsigned long)host;
host->gd = alloc_disk(MG_DISK_MAX_PART);
if (!host->gd) {
printk(KERN_ERR "%s:%d (alloc_disk) fail\n",
__func__, __LINE__);
err = -ENOMEM;
goto probe_err_7;
}
host->gd->major = host->major;
host->gd->first_minor = 0;
host->gd->fops = &mg_disk_ops;
host->gd->queue = host->breq;
host->gd->private_data = host;
sprintf(host->gd->disk_name, MG_DISK_NAME"a");
set_capacity(host->gd, host->n_sectors);
add_disk(host->gd);
return err;
probe_err_7:
del_timer_sync(&host->timer);
probe_err_6:
blk_cleanup_queue(host->breq);
probe_err_5:
unregister_blkdev(MG_DISK_MAJ, MG_DISK_NAME);
probe_err_4:
if (!prv_data->use_polling)
free_irq(host->irq, host);
probe_err_3b:
gpio_free(host->rstout);
probe_err_3a:
gpio_free(host->rst);
probe_err_3:
iounmap(host->dev_base);
probe_err_2:
kfree(host);
probe_err:
return err;
}
static int mg_remove(struct platform_device *plat_dev)
{
struct mg_drv_data *prv_data = plat_dev->dev.platform_data;
struct mg_host *host = prv_data->host;
int err = 0;
/* delete timer */
del_timer_sync(&host->timer);
/* remove disk */
if (host->gd) {
del_gendisk(host->gd);
put_disk(host->gd);
}
/* remove queue */
if (host->breq)
blk_cleanup_queue(host->breq);
/* unregister blk device */
unregister_blkdev(host->major, MG_DISK_NAME);
/* free irq */
if (!prv_data->use_polling)
free_irq(host->irq, host);
/* free reset-out pin */
if (prv_data->dev_attr != MG_BOOT_DEV)
gpio_free(host->rstout);
/* free rst pin */
if (host->rst)
gpio_free(host->rst);
/* unmap io */
if (host->dev_base)
iounmap(host->dev_base);
/* free mg_host */
kfree(host);
return err;
}
static struct platform_driver mg_disk_driver = {
.probe = mg_probe,
.remove = mg_remove,
.suspend = mg_suspend,
.resume = mg_resume,
.driver = {
.name = MG_DEV_NAME,
.owner = THIS_MODULE,
}
};
/****************************************************************************
*
* Module stuff
*
****************************************************************************/
static int __init mg_init(void)
{
printk(KERN_INFO "mGine mflash driver, (c) 2008 mGine Co.\n");
return platform_driver_register(&mg_disk_driver);
}
static void __exit mg_exit(void)
{
printk(KERN_INFO "mflash driver : bye bye\n");
platform_driver_unregister(&mg_disk_driver);
}
module_init(mg_init);
module_exit(mg_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("unsik Kim <donari75@gmail.com>");
MODULE_DESCRIPTION("mGine m[g]flash device driver");
| gpl-2.0 |
yacuken/android_kernel_samsung_espresso10 | arch/x86/mm/kmemcheck/opcode.c | 12710 | 1920 | #include <linux/types.h>
#include "opcode.h"
static bool opcode_is_prefix(uint8_t b)
{
return
/* Group 1 */
b == 0xf0 || b == 0xf2 || b == 0xf3
/* Group 2 */
|| b == 0x2e || b == 0x36 || b == 0x3e || b == 0x26
|| b == 0x64 || b == 0x65
/* Group 3 */
|| b == 0x66
/* Group 4 */
|| b == 0x67;
}
#ifdef CONFIG_X86_64
static bool opcode_is_rex_prefix(uint8_t b)
{
return (b & 0xf0) == 0x40;
}
#else
static bool opcode_is_rex_prefix(uint8_t b)
{
return false;
}
#endif
#define REX_W (1 << 3)
/*
* This is a VERY crude opcode decoder. We only need to find the size of the
* load/store that caused our #PF and this should work for all the opcodes
* that we care about. Moreover, the ones who invented this instruction set
* should be shot.
*/
void kmemcheck_opcode_decode(const uint8_t *op, unsigned int *size)
{
/* Default operand size */
int operand_size_override = 4;
/* prefixes */
for (; opcode_is_prefix(*op); ++op) {
if (*op == 0x66)
operand_size_override = 2;
}
/* REX prefix */
if (opcode_is_rex_prefix(*op)) {
uint8_t rex = *op;
++op;
if (rex & REX_W) {
switch (*op) {
case 0x63:
*size = 4;
return;
case 0x0f:
++op;
switch (*op) {
case 0xb6:
case 0xbe:
*size = 1;
return;
case 0xb7:
case 0xbf:
*size = 2;
return;
}
break;
}
*size = 8;
return;
}
}
/* escape opcode */
if (*op == 0x0f) {
++op;
/*
* This is move with zero-extend and sign-extend, respectively;
* we don't have to think about 0xb6/0xbe, because this is
* already handled in the conditional below.
*/
if (*op == 0xb7 || *op == 0xbf)
operand_size_override = 2;
}
*size = (*op & 1) ? operand_size_override : 1;
}
const uint8_t *kmemcheck_opcode_get_primary(const uint8_t *op)
{
/* skip prefixes */
while (opcode_is_prefix(*op))
++op;
if (opcode_is_rex_prefix(*op))
++op;
return op;
}
| gpl-2.0 |
qoo00783/linux | net/ipv6/xfrm6_policy.c | 167 | 9361 | /*
* xfrm6_policy.c: based on xfrm4_policy.c
*
* Authors:
* Mitsuru KANDA @USAGI
* Kazunori MIYAZAWA @USAGI
* Kunihiro Ishiguro <kunihiro@ipinfusion.com>
* IPv6 support
* YOSHIFUJI Hideaki
* Split up af-specific portion
*
*/
#include <linux/err.h>
#include <linux/kernel.h>
#include <linux/netdevice.h>
#include <net/addrconf.h>
#include <net/dst.h>
#include <net/xfrm.h>
#include <net/ip.h>
#include <net/ipv6.h>
#include <net/ip6_route.h>
#include <net/vrf.h>
#if IS_ENABLED(CONFIG_IPV6_MIP6)
#include <net/mip6.h>
#endif
static struct xfrm_policy_afinfo xfrm6_policy_afinfo;
static struct dst_entry *xfrm6_dst_lookup(struct net *net, int tos, int oif,
const xfrm_address_t *saddr,
const xfrm_address_t *daddr)
{
struct flowi6 fl6;
struct dst_entry *dst;
int err;
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_oif = oif;
memcpy(&fl6.daddr, daddr, sizeof(fl6.daddr));
if (saddr)
memcpy(&fl6.saddr, saddr, sizeof(fl6.saddr));
dst = ip6_route_output(net, NULL, &fl6);
err = dst->error;
if (dst->error) {
dst_release(dst);
dst = ERR_PTR(err);
}
return dst;
}
static int xfrm6_get_saddr(struct net *net, int oif,
xfrm_address_t *saddr, xfrm_address_t *daddr)
{
struct dst_entry *dst;
struct net_device *dev;
dst = xfrm6_dst_lookup(net, 0, oif, NULL, daddr);
if (IS_ERR(dst))
return -EHOSTUNREACH;
dev = ip6_dst_idev(dst)->dev;
ipv6_dev_get_saddr(dev_net(dev), dev, &daddr->in6, 0, &saddr->in6);
dst_release(dst);
return 0;
}
static int xfrm6_get_tos(const struct flowi *fl)
{
return 0;
}
static int xfrm6_init_path(struct xfrm_dst *path, struct dst_entry *dst,
int nfheader_len)
{
if (dst->ops->family == AF_INET6) {
struct rt6_info *rt = (struct rt6_info *)dst;
path->path_cookie = rt6_get_cookie(rt);
}
path->u.rt6.rt6i_nfheader_len = nfheader_len;
return 0;
}
static int xfrm6_fill_dst(struct xfrm_dst *xdst, struct net_device *dev,
const struct flowi *fl)
{
struct rt6_info *rt = (struct rt6_info *)xdst->route;
xdst->u.dst.dev = dev;
dev_hold(dev);
xdst->u.rt6.rt6i_idev = in6_dev_get(dev);
if (!xdst->u.rt6.rt6i_idev) {
dev_put(dev);
return -ENODEV;
}
/* Sheit... I remember I did this right. Apparently,
* it was magically lost, so this code needs audit */
xdst->u.rt6.rt6i_flags = rt->rt6i_flags & (RTF_ANYCAST |
RTF_LOCAL);
xdst->u.rt6.rt6i_metric = rt->rt6i_metric;
xdst->u.rt6.rt6i_node = rt->rt6i_node;
xdst->route_cookie = rt6_get_cookie(rt);
xdst->u.rt6.rt6i_gateway = rt->rt6i_gateway;
xdst->u.rt6.rt6i_dst = rt->rt6i_dst;
xdst->u.rt6.rt6i_src = rt->rt6i_src;
return 0;
}
static inline void
_decode_session6(struct sk_buff *skb, struct flowi *fl, int reverse)
{
struct flowi6 *fl6 = &fl->u.ip6;
int onlyproto = 0;
const struct ipv6hdr *hdr = ipv6_hdr(skb);
u16 offset = sizeof(*hdr);
struct ipv6_opt_hdr *exthdr;
const unsigned char *nh = skb_network_header(skb);
u16 nhoff = IP6CB(skb)->nhoff;
int oif = 0;
u8 nexthdr;
if (!nhoff)
nhoff = offsetof(struct ipv6hdr, nexthdr);
nexthdr = nh[nhoff];
if (skb_dst(skb)) {
oif = vrf_master_ifindex(skb_dst(skb)->dev) ?
: skb_dst(skb)->dev->ifindex;
}
memset(fl6, 0, sizeof(struct flowi6));
fl6->flowi6_mark = skb->mark;
fl6->flowi6_oif = reverse ? skb->skb_iif : oif;
fl6->daddr = reverse ? hdr->saddr : hdr->daddr;
fl6->saddr = reverse ? hdr->daddr : hdr->saddr;
while (nh + offset + 1 < skb->data ||
pskb_may_pull(skb, nh + offset + 1 - skb->data)) {
nh = skb_network_header(skb);
exthdr = (struct ipv6_opt_hdr *)(nh + offset);
switch (nexthdr) {
case NEXTHDR_FRAGMENT:
onlyproto = 1;
case NEXTHDR_ROUTING:
case NEXTHDR_HOP:
case NEXTHDR_DEST:
offset += ipv6_optlen(exthdr);
nexthdr = exthdr->nexthdr;
exthdr = (struct ipv6_opt_hdr *)(nh + offset);
break;
case IPPROTO_UDP:
case IPPROTO_UDPLITE:
case IPPROTO_TCP:
case IPPROTO_SCTP:
case IPPROTO_DCCP:
if (!onlyproto && (nh + offset + 4 < skb->data ||
pskb_may_pull(skb, nh + offset + 4 - skb->data))) {
__be16 *ports;
nh = skb_network_header(skb);
ports = (__be16 *)(nh + offset);
fl6->fl6_sport = ports[!!reverse];
fl6->fl6_dport = ports[!reverse];
}
fl6->flowi6_proto = nexthdr;
return;
case IPPROTO_ICMPV6:
if (!onlyproto && pskb_may_pull(skb, nh + offset + 2 - skb->data)) {
u8 *icmp;
nh = skb_network_header(skb);
icmp = (u8 *)(nh + offset);
fl6->fl6_icmp_type = icmp[0];
fl6->fl6_icmp_code = icmp[1];
}
fl6->flowi6_proto = nexthdr;
return;
#if IS_ENABLED(CONFIG_IPV6_MIP6)
case IPPROTO_MH:
offset += ipv6_optlen(exthdr);
if (!onlyproto && pskb_may_pull(skb, nh + offset + 3 - skb->data)) {
struct ip6_mh *mh;
nh = skb_network_header(skb);
mh = (struct ip6_mh *)(nh + offset);
fl6->fl6_mh_type = mh->ip6mh_type;
}
fl6->flowi6_proto = nexthdr;
return;
#endif
/* XXX Why are there these headers? */
case IPPROTO_AH:
case IPPROTO_ESP:
case IPPROTO_COMP:
default:
fl6->fl6_ipsec_spi = 0;
fl6->flowi6_proto = nexthdr;
return;
}
}
}
static inline int xfrm6_garbage_collect(struct dst_ops *ops)
{
struct net *net = container_of(ops, struct net, xfrm.xfrm6_dst_ops);
xfrm6_policy_afinfo.garbage_collect(net);
return dst_entries_get_fast(ops) > ops->gc_thresh * 2;
}
static void xfrm6_update_pmtu(struct dst_entry *dst, struct sock *sk,
struct sk_buff *skb, u32 mtu)
{
struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
struct dst_entry *path = xdst->route;
path->ops->update_pmtu(path, sk, skb, mtu);
}
static void xfrm6_redirect(struct dst_entry *dst, struct sock *sk,
struct sk_buff *skb)
{
struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
struct dst_entry *path = xdst->route;
path->ops->redirect(path, sk, skb);
}
static void xfrm6_dst_destroy(struct dst_entry *dst)
{
struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
if (likely(xdst->u.rt6.rt6i_idev))
in6_dev_put(xdst->u.rt6.rt6i_idev);
dst_destroy_metrics_generic(dst);
xfrm_dst_destroy(xdst);
}
static void xfrm6_dst_ifdown(struct dst_entry *dst, struct net_device *dev,
int unregister)
{
struct xfrm_dst *xdst;
if (!unregister)
return;
xdst = (struct xfrm_dst *)dst;
if (xdst->u.rt6.rt6i_idev->dev == dev) {
struct inet6_dev *loopback_idev =
in6_dev_get(dev_net(dev)->loopback_dev);
BUG_ON(!loopback_idev);
do {
in6_dev_put(xdst->u.rt6.rt6i_idev);
xdst->u.rt6.rt6i_idev = loopback_idev;
in6_dev_hold(loopback_idev);
xdst = (struct xfrm_dst *)xdst->u.dst.child;
} while (xdst->u.dst.xfrm);
__in6_dev_put(loopback_idev);
}
xfrm_dst_ifdown(dst, dev);
}
static struct dst_ops xfrm6_dst_ops = {
.family = AF_INET6,
.gc = xfrm6_garbage_collect,
.update_pmtu = xfrm6_update_pmtu,
.redirect = xfrm6_redirect,
.cow_metrics = dst_cow_metrics_generic,
.destroy = xfrm6_dst_destroy,
.ifdown = xfrm6_dst_ifdown,
.local_out = __ip6_local_out,
.gc_thresh = 32768,
};
static struct xfrm_policy_afinfo xfrm6_policy_afinfo = {
.family = AF_INET6,
.dst_ops = &xfrm6_dst_ops,
.dst_lookup = xfrm6_dst_lookup,
.get_saddr = xfrm6_get_saddr,
.decode_session = _decode_session6,
.get_tos = xfrm6_get_tos,
.init_path = xfrm6_init_path,
.fill_dst = xfrm6_fill_dst,
.blackhole_route = ip6_blackhole_route,
};
static int __init xfrm6_policy_init(void)
{
return xfrm_policy_register_afinfo(&xfrm6_policy_afinfo);
}
static void xfrm6_policy_fini(void)
{
xfrm_policy_unregister_afinfo(&xfrm6_policy_afinfo);
}
#ifdef CONFIG_SYSCTL
static struct ctl_table xfrm6_policy_table[] = {
{
.procname = "xfrm6_gc_thresh",
.data = &init_net.xfrm.xfrm6_dst_ops.gc_thresh,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec,
},
{ }
};
static int __net_init xfrm6_net_init(struct net *net)
{
struct ctl_table *table;
struct ctl_table_header *hdr;
table = xfrm6_policy_table;
if (!net_eq(net, &init_net)) {
table = kmemdup(table, sizeof(xfrm6_policy_table), GFP_KERNEL);
if (!table)
goto err_alloc;
table[0].data = &net->xfrm.xfrm6_dst_ops.gc_thresh;
}
hdr = register_net_sysctl(net, "net/ipv6", table);
if (!hdr)
goto err_reg;
net->ipv6.sysctl.xfrm6_hdr = hdr;
return 0;
err_reg:
if (!net_eq(net, &init_net))
kfree(table);
err_alloc:
return -ENOMEM;
}
static void __net_exit xfrm6_net_exit(struct net *net)
{
struct ctl_table *table;
if (!net->ipv6.sysctl.xfrm6_hdr)
return;
table = net->ipv6.sysctl.xfrm6_hdr->ctl_table_arg;
unregister_net_sysctl_table(net->ipv6.sysctl.xfrm6_hdr);
if (!net_eq(net, &init_net))
kfree(table);
}
static struct pernet_operations xfrm6_net_ops = {
.init = xfrm6_net_init,
.exit = xfrm6_net_exit,
};
#endif
int __init xfrm6_init(void)
{
int ret;
dst_entries_init(&xfrm6_dst_ops);
ret = xfrm6_policy_init();
if (ret) {
dst_entries_destroy(&xfrm6_dst_ops);
goto out;
}
ret = xfrm6_state_init();
if (ret)
goto out_policy;
ret = xfrm6_protocol_init();
if (ret)
goto out_state;
#ifdef CONFIG_SYSCTL
register_pernet_subsys(&xfrm6_net_ops);
#endif
out:
return ret;
out_state:
xfrm6_state_fini();
out_policy:
xfrm6_policy_fini();
goto out;
}
void xfrm6_fini(void)
{
#ifdef CONFIG_SYSCTL
unregister_pernet_subsys(&xfrm6_net_ops);
#endif
xfrm6_protocol_fini();
xfrm6_policy_fini();
xfrm6_state_fini();
dst_entries_destroy(&xfrm6_dst_ops);
}
| gpl-2.0 |
erlerobot/ubuntu-vivid | tools/perf/util/probe-finder.c | 167 | 39830 | /*
* probe-finder.c : C expression to kprobe event converter
*
* Written by Masami Hiramatsu <mhiramat@redhat.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 <sys/utsname.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <getopt.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <dwarf-regs.h>
#include <linux/bitops.h>
#include "event.h"
#include "debug.h"
#include "util.h"
#include "symbol.h"
#include "probe-finder.h"
/* Kprobe tracer basic type is up to u64 */
#define MAX_BASIC_TYPE_BITS 64
/* Line number list operations */
/* Add a line to line number list */
static int line_list__add_line(struct list_head *head, int line)
{
struct line_node *ln;
struct list_head *p;
/* Reverse search, because new line will be the last one */
list_for_each_entry_reverse(ln, head, list) {
if (ln->line < line) {
p = &ln->list;
goto found;
} else if (ln->line == line) /* Already exist */
return 1;
}
/* List is empty, or the smallest entry */
p = head;
found:
pr_debug("line list: add a line %u\n", line);
ln = zalloc(sizeof(struct line_node));
if (ln == NULL)
return -ENOMEM;
ln->line = line;
INIT_LIST_HEAD(&ln->list);
list_add(&ln->list, p);
return 0;
}
/* Check if the line in line number list */
static int line_list__has_line(struct list_head *head, int line)
{
struct line_node *ln;
/* Reverse search, because new line will be the last one */
list_for_each_entry(ln, head, list)
if (ln->line == line)
return 1;
return 0;
}
/* Init line number list */
static void line_list__init(struct list_head *head)
{
INIT_LIST_HEAD(head);
}
/* Free line number list */
static void line_list__free(struct list_head *head)
{
struct line_node *ln;
while (!list_empty(head)) {
ln = list_first_entry(head, struct line_node, list);
list_del(&ln->list);
free(ln);
}
}
/* Dwarf FL wrappers */
static char *debuginfo_path; /* Currently dummy */
static const Dwfl_Callbacks offline_callbacks = {
.find_debuginfo = dwfl_standard_find_debuginfo,
.debuginfo_path = &debuginfo_path,
.section_address = dwfl_offline_section_address,
/* We use this table for core files too. */
.find_elf = dwfl_build_id_find_elf,
};
/* Get a Dwarf from offline image */
static int debuginfo__init_offline_dwarf(struct debuginfo *self,
const char *path)
{
Dwfl_Module *mod;
int fd;
fd = open(path, O_RDONLY);
if (fd < 0)
return fd;
self->dwfl = dwfl_begin(&offline_callbacks);
if (!self->dwfl)
goto error;
mod = dwfl_report_offline(self->dwfl, "", "", fd);
if (!mod)
goto error;
self->dbg = dwfl_module_getdwarf(mod, &self->bias);
if (!self->dbg)
goto error;
return 0;
error:
if (self->dwfl)
dwfl_end(self->dwfl);
else
close(fd);
memset(self, 0, sizeof(*self));
return -ENOENT;
}
#if _ELFUTILS_PREREQ(0, 148)
/* This method is buggy if elfutils is older than 0.148 */
static int __linux_kernel_find_elf(Dwfl_Module *mod,
void **userdata,
const char *module_name,
Dwarf_Addr base,
char **file_name, Elf **elfp)
{
int fd;
const char *path = kernel_get_module_path(module_name);
pr_debug2("Use file %s for %s\n", path, module_name);
if (path) {
fd = open(path, O_RDONLY);
if (fd >= 0) {
*file_name = strdup(path);
return fd;
}
}
/* If failed, try to call standard method */
return dwfl_linux_kernel_find_elf(mod, userdata, module_name, base,
file_name, elfp);
}
static const Dwfl_Callbacks kernel_callbacks = {
.find_debuginfo = dwfl_standard_find_debuginfo,
.debuginfo_path = &debuginfo_path,
.find_elf = __linux_kernel_find_elf,
.section_address = dwfl_linux_kernel_module_section_address,
};
/* Get a Dwarf from live kernel image */
static int debuginfo__init_online_kernel_dwarf(struct debuginfo *self,
Dwarf_Addr addr)
{
self->dwfl = dwfl_begin(&kernel_callbacks);
if (!self->dwfl)
return -EINVAL;
/* Load the kernel dwarves: Don't care the result here */
dwfl_linux_kernel_report_kernel(self->dwfl);
dwfl_linux_kernel_report_modules(self->dwfl);
self->dbg = dwfl_addrdwarf(self->dwfl, addr, &self->bias);
/* Here, check whether we could get a real dwarf */
if (!self->dbg) {
pr_debug("Failed to find kernel dwarf at %lx\n",
(unsigned long)addr);
dwfl_end(self->dwfl);
memset(self, 0, sizeof(*self));
return -ENOENT;
}
return 0;
}
#else
/* With older elfutils, this just support kernel module... */
static int debuginfo__init_online_kernel_dwarf(struct debuginfo *self,
Dwarf_Addr addr __maybe_unused)
{
const char *path = kernel_get_module_path("kernel");
if (!path) {
pr_err("Failed to find vmlinux path\n");
return -ENOENT;
}
pr_debug2("Use file %s for debuginfo\n", path);
return debuginfo__init_offline_dwarf(self, path);
}
#endif
struct debuginfo *debuginfo__new(const char *path)
{
struct debuginfo *self = zalloc(sizeof(struct debuginfo));
if (!self)
return NULL;
if (debuginfo__init_offline_dwarf(self, path) < 0) {
free(self);
self = NULL;
}
return self;
}
struct debuginfo *debuginfo__new_online_kernel(unsigned long addr)
{
struct debuginfo *self = zalloc(sizeof(struct debuginfo));
if (!self)
return NULL;
if (debuginfo__init_online_kernel_dwarf(self, (Dwarf_Addr)addr) < 0) {
free(self);
self = NULL;
}
return self;
}
void debuginfo__delete(struct debuginfo *self)
{
if (self) {
if (self->dwfl)
dwfl_end(self->dwfl);
free(self);
}
}
/*
* Probe finder related functions
*/
static struct probe_trace_arg_ref *alloc_trace_arg_ref(long offs)
{
struct probe_trace_arg_ref *ref;
ref = zalloc(sizeof(struct probe_trace_arg_ref));
if (ref != NULL)
ref->offset = offs;
return ref;
}
/*
* Convert a location into trace_arg.
* If tvar == NULL, this just checks variable can be converted.
*/
static int convert_variable_location(Dwarf_Die *vr_die, Dwarf_Addr addr,
Dwarf_Op *fb_ops,
struct probe_trace_arg *tvar)
{
Dwarf_Attribute attr;
Dwarf_Op *op;
size_t nops;
unsigned int regn;
Dwarf_Word offs = 0;
bool ref = false;
const char *regs;
int ret;
if (dwarf_attr(vr_die, DW_AT_external, &attr) != NULL)
goto static_var;
/* TODO: handle more than 1 exprs */
if (dwarf_attr(vr_die, DW_AT_location, &attr) == NULL ||
dwarf_getlocation_addr(&attr, addr, &op, &nops, 1) <= 0 ||
nops == 0) {
/* TODO: Support const_value */
return -ENOENT;
}
if (op->atom == DW_OP_addr) {
static_var:
if (!tvar)
return 0;
/* Static variables on memory (not stack), make @varname */
ret = strlen(dwarf_diename(vr_die));
tvar->value = zalloc(ret + 2);
if (tvar->value == NULL)
return -ENOMEM;
snprintf(tvar->value, ret + 2, "@%s", dwarf_diename(vr_die));
tvar->ref = alloc_trace_arg_ref((long)offs);
if (tvar->ref == NULL)
return -ENOMEM;
return 0;
}
/* If this is based on frame buffer, set the offset */
if (op->atom == DW_OP_fbreg) {
if (fb_ops == NULL)
return -ENOTSUP;
ref = true;
offs = op->number;
op = &fb_ops[0];
}
if (op->atom >= DW_OP_breg0 && op->atom <= DW_OP_breg31) {
regn = op->atom - DW_OP_breg0;
offs += op->number;
ref = true;
} else if (op->atom >= DW_OP_reg0 && op->atom <= DW_OP_reg31) {
regn = op->atom - DW_OP_reg0;
} else if (op->atom == DW_OP_bregx) {
regn = op->number;
offs += op->number2;
ref = true;
} else if (op->atom == DW_OP_regx) {
regn = op->number;
} else {
pr_debug("DW_OP %x is not supported.\n", op->atom);
return -ENOTSUP;
}
if (!tvar)
return 0;
regs = get_arch_regstr(regn);
if (!regs) {
/* This should be a bug in DWARF or this tool */
pr_warning("Mapping for the register number %u "
"missing on this architecture.\n", regn);
return -ERANGE;
}
tvar->value = strdup(regs);
if (tvar->value == NULL)
return -ENOMEM;
if (ref) {
tvar->ref = alloc_trace_arg_ref((long)offs);
if (tvar->ref == NULL)
return -ENOMEM;
}
return 0;
}
#define BYTES_TO_BITS(nb) ((nb) * BITS_PER_LONG / sizeof(long))
static int convert_variable_type(Dwarf_Die *vr_die,
struct probe_trace_arg *tvar,
const char *cast)
{
struct probe_trace_arg_ref **ref_ptr = &tvar->ref;
Dwarf_Die type;
char buf[16];
int bsize, boffs, total;
int ret;
/* TODO: check all types */
if (cast && strcmp(cast, "string") != 0) {
/* Non string type is OK */
tvar->type = strdup(cast);
return (tvar->type == NULL) ? -ENOMEM : 0;
}
bsize = dwarf_bitsize(vr_die);
if (bsize > 0) {
/* This is a bitfield */
boffs = dwarf_bitoffset(vr_die);
total = dwarf_bytesize(vr_die);
if (boffs < 0 || total < 0)
return -ENOENT;
ret = snprintf(buf, 16, "b%d@%d/%zd", bsize, boffs,
BYTES_TO_BITS(total));
goto formatted;
}
if (die_get_real_type(vr_die, &type) == NULL) {
pr_warning("Failed to get a type information of %s.\n",
dwarf_diename(vr_die));
return -ENOENT;
}
pr_debug("%s type is %s.\n",
dwarf_diename(vr_die), dwarf_diename(&type));
if (cast && strcmp(cast, "string") == 0) { /* String type */
ret = dwarf_tag(&type);
if (ret != DW_TAG_pointer_type &&
ret != DW_TAG_array_type) {
pr_warning("Failed to cast into string: "
"%s(%s) is not a pointer nor array.\n",
dwarf_diename(vr_die), dwarf_diename(&type));
return -EINVAL;
}
if (ret == DW_TAG_pointer_type) {
if (die_get_real_type(&type, &type) == NULL) {
pr_warning("Failed to get a type"
" information.\n");
return -ENOENT;
}
while (*ref_ptr)
ref_ptr = &(*ref_ptr)->next;
/* Add new reference with offset +0 */
*ref_ptr = zalloc(sizeof(struct probe_trace_arg_ref));
if (*ref_ptr == NULL) {
pr_warning("Out of memory error\n");
return -ENOMEM;
}
}
if (!die_compare_name(&type, "char") &&
!die_compare_name(&type, "unsigned char")) {
pr_warning("Failed to cast into string: "
"%s is not (unsigned) char *.\n",
dwarf_diename(vr_die));
return -EINVAL;
}
tvar->type = strdup(cast);
return (tvar->type == NULL) ? -ENOMEM : 0;
}
ret = dwarf_bytesize(&type);
if (ret <= 0)
/* No size ... try to use default type */
return 0;
ret = BYTES_TO_BITS(ret);
/* Check the bitwidth */
if (ret > MAX_BASIC_TYPE_BITS) {
pr_info("%s exceeds max-bitwidth. Cut down to %d bits.\n",
dwarf_diename(&type), MAX_BASIC_TYPE_BITS);
ret = MAX_BASIC_TYPE_BITS;
}
ret = snprintf(buf, 16, "%c%d",
die_is_signed_type(&type) ? 's' : 'u', ret);
formatted:
if (ret < 0 || ret >= 16) {
if (ret >= 16)
ret = -E2BIG;
pr_warning("Failed to convert variable type: %s\n",
strerror(-ret));
return ret;
}
tvar->type = strdup(buf);
if (tvar->type == NULL)
return -ENOMEM;
return 0;
}
static int convert_variable_fields(Dwarf_Die *vr_die, const char *varname,
struct perf_probe_arg_field *field,
struct probe_trace_arg_ref **ref_ptr,
Dwarf_Die *die_mem)
{
struct probe_trace_arg_ref *ref = *ref_ptr;
Dwarf_Die type;
Dwarf_Word offs;
int ret, tag;
pr_debug("converting %s in %s\n", field->name, varname);
if (die_get_real_type(vr_die, &type) == NULL) {
pr_warning("Failed to get the type of %s.\n", varname);
return -ENOENT;
}
pr_debug2("Var real type: (%x)\n", (unsigned)dwarf_dieoffset(&type));
tag = dwarf_tag(&type);
if (field->name[0] == '[' &&
(tag == DW_TAG_array_type || tag == DW_TAG_pointer_type)) {
if (field->next)
/* Save original type for next field */
memcpy(die_mem, &type, sizeof(*die_mem));
/* Get the type of this array */
if (die_get_real_type(&type, &type) == NULL) {
pr_warning("Failed to get the type of %s.\n", varname);
return -ENOENT;
}
pr_debug2("Array real type: (%x)\n",
(unsigned)dwarf_dieoffset(&type));
if (tag == DW_TAG_pointer_type) {
ref = zalloc(sizeof(struct probe_trace_arg_ref));
if (ref == NULL)
return -ENOMEM;
if (*ref_ptr)
(*ref_ptr)->next = ref;
else
*ref_ptr = ref;
}
ref->offset += dwarf_bytesize(&type) * field->index;
if (!field->next)
/* Save vr_die for converting types */
memcpy(die_mem, vr_die, sizeof(*die_mem));
goto next;
} else if (tag == DW_TAG_pointer_type) {
/* Check the pointer and dereference */
if (!field->ref) {
pr_err("Semantic error: %s must be referred by '->'\n",
field->name);
return -EINVAL;
}
/* Get the type pointed by this pointer */
if (die_get_real_type(&type, &type) == NULL) {
pr_warning("Failed to get the type of %s.\n", varname);
return -ENOENT;
}
/* Verify it is a data structure */
tag = dwarf_tag(&type);
if (tag != DW_TAG_structure_type && tag != DW_TAG_union_type) {
pr_warning("%s is not a data structure nor an union.\n",
varname);
return -EINVAL;
}
ref = zalloc(sizeof(struct probe_trace_arg_ref));
if (ref == NULL)
return -ENOMEM;
if (*ref_ptr)
(*ref_ptr)->next = ref;
else
*ref_ptr = ref;
} else {
/* Verify it is a data structure */
if (tag != DW_TAG_structure_type && tag != DW_TAG_union_type) {
pr_warning("%s is not a data structure nor an union.\n",
varname);
return -EINVAL;
}
if (field->name[0] == '[') {
pr_err("Semantic error: %s is not a pointor"
" nor array.\n", varname);
return -EINVAL;
}
if (field->ref) {
pr_err("Semantic error: %s must be referred by '.'\n",
field->name);
return -EINVAL;
}
if (!ref) {
pr_warning("Structure on a register is not "
"supported yet.\n");
return -ENOTSUP;
}
}
if (die_find_member(&type, field->name, die_mem) == NULL) {
pr_warning("%s(tyep:%s) has no member %s.\n", varname,
dwarf_diename(&type), field->name);
return -EINVAL;
}
/* Get the offset of the field */
if (tag == DW_TAG_union_type) {
offs = 0;
} else {
ret = die_get_data_member_location(die_mem, &offs);
if (ret < 0) {
pr_warning("Failed to get the offset of %s.\n",
field->name);
return ret;
}
}
ref->offset += (long)offs;
next:
/* Converting next field */
if (field->next)
return convert_variable_fields(die_mem, field->name,
field->next, &ref, die_mem);
else
return 0;
}
/* Show a variables in kprobe event format */
static int convert_variable(Dwarf_Die *vr_die, struct probe_finder *pf)
{
Dwarf_Die die_mem;
int ret;
pr_debug("Converting variable %s into trace event.\n",
dwarf_diename(vr_die));
ret = convert_variable_location(vr_die, pf->addr, pf->fb_ops,
pf->tvar);
if (ret == -ENOENT)
pr_err("Failed to find the location of %s at this address.\n"
" Perhaps, it has been optimized out.\n", pf->pvar->var);
else if (ret == -ENOTSUP)
pr_err("Sorry, we don't support this variable location yet.\n");
else if (pf->pvar->field) {
ret = convert_variable_fields(vr_die, pf->pvar->var,
pf->pvar->field, &pf->tvar->ref,
&die_mem);
vr_die = &die_mem;
}
if (ret == 0)
ret = convert_variable_type(vr_die, pf->tvar, pf->pvar->type);
/* *expr will be cached in libdw. Don't free it. */
return ret;
}
/* Find a variable in a scope DIE */
static int find_variable(Dwarf_Die *sc_die, struct probe_finder *pf)
{
Dwarf_Die vr_die;
char buf[32], *ptr;
int ret = 0;
if (!is_c_varname(pf->pvar->var)) {
/* Copy raw parameters */
pf->tvar->value = strdup(pf->pvar->var);
if (pf->tvar->value == NULL)
return -ENOMEM;
if (pf->pvar->type) {
pf->tvar->type = strdup(pf->pvar->type);
if (pf->tvar->type == NULL)
return -ENOMEM;
}
if (pf->pvar->name) {
pf->tvar->name = strdup(pf->pvar->name);
if (pf->tvar->name == NULL)
return -ENOMEM;
} else
pf->tvar->name = NULL;
return 0;
}
if (pf->pvar->name)
pf->tvar->name = strdup(pf->pvar->name);
else {
ret = synthesize_perf_probe_arg(pf->pvar, buf, 32);
if (ret < 0)
return ret;
ptr = strchr(buf, ':'); /* Change type separator to _ */
if (ptr)
*ptr = '_';
pf->tvar->name = strdup(buf);
}
if (pf->tvar->name == NULL)
return -ENOMEM;
pr_debug("Searching '%s' variable in context.\n", pf->pvar->var);
/* Search child die for local variables and parameters. */
if (!die_find_variable_at(sc_die, pf->pvar->var, pf->addr, &vr_die)) {
/* Search again in global variables */
if (!die_find_variable_at(&pf->cu_die, pf->pvar->var, 0, &vr_die))
ret = -ENOENT;
}
if (ret >= 0)
ret = convert_variable(&vr_die, pf);
if (ret < 0)
pr_warning("Failed to find '%s' in this function.\n",
pf->pvar->var);
return ret;
}
/* Convert subprogram DIE to trace point */
static int convert_to_trace_point(Dwarf_Die *sp_die, Dwarf_Addr paddr,
bool retprobe, struct probe_trace_point *tp)
{
Dwarf_Addr eaddr, highaddr;
const char *name;
/* Copy the name of probe point */
name = dwarf_diename(sp_die);
if (name) {
if (dwarf_entrypc(sp_die, &eaddr) != 0) {
pr_warning("Failed to get entry address of %s\n",
dwarf_diename(sp_die));
return -ENOENT;
}
if (dwarf_highpc(sp_die, &highaddr) != 0) {
pr_warning("Failed to get end address of %s\n",
dwarf_diename(sp_die));
return -ENOENT;
}
if (paddr > highaddr) {
pr_warning("Offset specified is greater than size of %s\n",
dwarf_diename(sp_die));
return -EINVAL;
}
tp->symbol = strdup(name);
if (tp->symbol == NULL)
return -ENOMEM;
tp->offset = (unsigned long)(paddr - eaddr);
} else
/* This function has no name. */
tp->offset = (unsigned long)paddr;
/* Return probe must be on the head of a subprogram */
if (retprobe) {
if (eaddr != paddr) {
pr_warning("Return probe must be on the head of"
" a real function.\n");
return -EINVAL;
}
tp->retprobe = true;
}
return 0;
}
/* Call probe_finder callback with scope DIE */
static int call_probe_finder(Dwarf_Die *sc_die, struct probe_finder *pf)
{
Dwarf_Attribute fb_attr;
size_t nops;
int ret;
if (!sc_die) {
pr_err("Caller must pass a scope DIE. Program error.\n");
return -EINVAL;
}
/* If not a real subprogram, find a real one */
if (dwarf_tag(sc_die) != DW_TAG_subprogram) {
if (!die_find_realfunc(&pf->cu_die, pf->addr, &pf->sp_die)) {
pr_warning("Failed to find probe point in any "
"functions.\n");
return -ENOENT;
}
} else
memcpy(&pf->sp_die, sc_die, sizeof(Dwarf_Die));
/* Get the frame base attribute/ops from subprogram */
dwarf_attr(&pf->sp_die, DW_AT_frame_base, &fb_attr);
ret = dwarf_getlocation_addr(&fb_attr, pf->addr, &pf->fb_ops, &nops, 1);
if (ret <= 0 || nops == 0) {
pf->fb_ops = NULL;
#if _ELFUTILS_PREREQ(0, 142)
} else if (nops == 1 && pf->fb_ops[0].atom == DW_OP_call_frame_cfa &&
pf->cfi != NULL) {
Dwarf_Frame *frame;
if (dwarf_cfi_addrframe(pf->cfi, pf->addr, &frame) != 0 ||
dwarf_frame_cfa(frame, &pf->fb_ops, &nops) != 0) {
pr_warning("Failed to get call frame on 0x%jx\n",
(uintmax_t)pf->addr);
return -ENOENT;
}
#endif
}
/* Call finder's callback handler */
ret = pf->callback(sc_die, pf);
/* *pf->fb_ops will be cached in libdw. Don't free it. */
pf->fb_ops = NULL;
return ret;
}
struct find_scope_param {
const char *function;
const char *file;
int line;
int diff;
Dwarf_Die *die_mem;
bool found;
};
static int find_best_scope_cb(Dwarf_Die *fn_die, void *data)
{
struct find_scope_param *fsp = data;
const char *file;
int lno;
/* Skip if declared file name does not match */
if (fsp->file) {
file = dwarf_decl_file(fn_die);
if (!file || strcmp(fsp->file, file) != 0)
return 0;
}
/* If the function name is given, that's what user expects */
if (fsp->function) {
if (die_compare_name(fn_die, fsp->function)) {
memcpy(fsp->die_mem, fn_die, sizeof(Dwarf_Die));
fsp->found = true;
return 1;
}
} else {
/* With the line number, find the nearest declared DIE */
dwarf_decl_line(fn_die, &lno);
if (lno < fsp->line && fsp->diff > fsp->line - lno) {
/* Keep a candidate and continue */
fsp->diff = fsp->line - lno;
memcpy(fsp->die_mem, fn_die, sizeof(Dwarf_Die));
fsp->found = true;
}
}
return 0;
}
/* Find an appropriate scope fits to given conditions */
static Dwarf_Die *find_best_scope(struct probe_finder *pf, Dwarf_Die *die_mem)
{
struct find_scope_param fsp = {
.function = pf->pev->point.function,
.file = pf->fname,
.line = pf->lno,
.diff = INT_MAX,
.die_mem = die_mem,
.found = false,
};
cu_walk_functions_at(&pf->cu_die, pf->addr, find_best_scope_cb, &fsp);
return fsp.found ? die_mem : NULL;
}
static int probe_point_line_walker(const char *fname, int lineno,
Dwarf_Addr addr, void *data)
{
struct probe_finder *pf = data;
Dwarf_Die *sc_die, die_mem;
int ret;
if (lineno != pf->lno || strtailcmp(fname, pf->fname) != 0)
return 0;
pf->addr = addr;
sc_die = find_best_scope(pf, &die_mem);
if (!sc_die) {
pr_warning("Failed to find scope of probe point.\n");
return -ENOENT;
}
ret = call_probe_finder(sc_die, pf);
/* Continue if no error, because the line will be in inline function */
return ret < 0 ? ret : 0;
}
/* Find probe point from its line number */
static int find_probe_point_by_line(struct probe_finder *pf)
{
return die_walk_lines(&pf->cu_die, probe_point_line_walker, pf);
}
/* Find lines which match lazy pattern */
static int find_lazy_match_lines(struct list_head *head,
const char *fname, const char *pat)
{
FILE *fp;
char *line = NULL;
size_t line_len;
ssize_t len;
int count = 0, linenum = 1;
fp = fopen(fname, "r");
if (!fp) {
pr_warning("Failed to open %s: %s\n", fname, strerror(errno));
return -errno;
}
while ((len = getline(&line, &line_len, fp)) > 0) {
if (line[len - 1] == '\n')
line[len - 1] = '\0';
if (strlazymatch(line, pat)) {
line_list__add_line(head, linenum);
count++;
}
linenum++;
}
if (ferror(fp))
count = -errno;
free(line);
fclose(fp);
if (count == 0)
pr_debug("No matched lines found in %s.\n", fname);
return count;
}
static int probe_point_lazy_walker(const char *fname, int lineno,
Dwarf_Addr addr, void *data)
{
struct probe_finder *pf = data;
Dwarf_Die *sc_die, die_mem;
int ret;
if (!line_list__has_line(&pf->lcache, lineno) ||
strtailcmp(fname, pf->fname) != 0)
return 0;
pr_debug("Probe line found: line:%d addr:0x%llx\n",
lineno, (unsigned long long)addr);
pf->addr = addr;
pf->lno = lineno;
sc_die = find_best_scope(pf, &die_mem);
if (!sc_die) {
pr_warning("Failed to find scope of probe point.\n");
return -ENOENT;
}
ret = call_probe_finder(sc_die, pf);
/*
* Continue if no error, because the lazy pattern will match
* to other lines
*/
return ret < 0 ? ret : 0;
}
/* Find probe points from lazy pattern */
static int find_probe_point_lazy(Dwarf_Die *sp_die, struct probe_finder *pf)
{
int ret = 0;
if (list_empty(&pf->lcache)) {
/* Matching lazy line pattern */
ret = find_lazy_match_lines(&pf->lcache, pf->fname,
pf->pev->point.lazy_line);
if (ret <= 0)
return ret;
}
return die_walk_lines(sp_die, probe_point_lazy_walker, pf);
}
static int probe_point_inline_cb(Dwarf_Die *in_die, void *data)
{
struct probe_finder *pf = data;
struct perf_probe_point *pp = &pf->pev->point;
Dwarf_Addr addr;
int ret;
if (pp->lazy_line)
ret = find_probe_point_lazy(in_die, pf);
else {
/* Get probe address */
if (dwarf_entrypc(in_die, &addr) != 0) {
pr_warning("Failed to get entry address of %s.\n",
dwarf_diename(in_die));
return -ENOENT;
}
pf->addr = addr;
pf->addr += pp->offset;
pr_debug("found inline addr: 0x%jx\n",
(uintmax_t)pf->addr);
ret = call_probe_finder(in_die, pf);
}
return ret;
}
/* Callback parameter with return value for libdw */
struct dwarf_callback_param {
void *data;
int retval;
};
/* Search function from function name */
static int probe_point_search_cb(Dwarf_Die *sp_die, void *data)
{
struct dwarf_callback_param *param = data;
struct probe_finder *pf = param->data;
struct perf_probe_point *pp = &pf->pev->point;
Dwarf_Attribute attr;
/* Check tag and diename */
if (dwarf_tag(sp_die) != DW_TAG_subprogram ||
!die_compare_name(sp_die, pp->function) ||
dwarf_attr(sp_die, DW_AT_declaration, &attr))
return DWARF_CB_OK;
/* Check declared file */
if (pp->file && strtailcmp(pp->file, dwarf_decl_file(sp_die)))
return DWARF_CB_OK;
pf->fname = dwarf_decl_file(sp_die);
if (pp->line) { /* Function relative line */
dwarf_decl_line(sp_die, &pf->lno);
pf->lno += pp->line;
param->retval = find_probe_point_by_line(pf);
} else if (!dwarf_func_inline(sp_die)) {
/* Real function */
if (pp->lazy_line)
param->retval = find_probe_point_lazy(sp_die, pf);
else {
if (dwarf_entrypc(sp_die, &pf->addr) != 0) {
pr_warning("Failed to get entry address of "
"%s.\n", dwarf_diename(sp_die));
param->retval = -ENOENT;
return DWARF_CB_ABORT;
}
pf->addr += pp->offset;
/* TODO: Check the address in this function */
param->retval = call_probe_finder(sp_die, pf);
}
} else
/* Inlined function: search instances */
param->retval = die_walk_instances(sp_die,
probe_point_inline_cb, (void *)pf);
return DWARF_CB_ABORT; /* Exit; no same symbol in this CU. */
}
static int find_probe_point_by_func(struct probe_finder *pf)
{
struct dwarf_callback_param _param = {.data = (void *)pf,
.retval = 0};
dwarf_getfuncs(&pf->cu_die, probe_point_search_cb, &_param, 0);
return _param.retval;
}
struct pubname_callback_param {
char *function;
char *file;
Dwarf_Die *cu_die;
Dwarf_Die *sp_die;
int found;
};
static int pubname_search_cb(Dwarf *dbg, Dwarf_Global *gl, void *data)
{
struct pubname_callback_param *param = data;
if (dwarf_offdie(dbg, gl->die_offset, param->sp_die)) {
if (dwarf_tag(param->sp_die) != DW_TAG_subprogram)
return DWARF_CB_OK;
if (die_compare_name(param->sp_die, param->function)) {
if (!dwarf_offdie(dbg, gl->cu_offset, param->cu_die))
return DWARF_CB_OK;
if (param->file &&
strtailcmp(param->file, dwarf_decl_file(param->sp_die)))
return DWARF_CB_OK;
param->found = 1;
return DWARF_CB_ABORT;
}
}
return DWARF_CB_OK;
}
/* Find probe points from debuginfo */
static int debuginfo__find_probes(struct debuginfo *self,
struct probe_finder *pf)
{
struct perf_probe_point *pp = &pf->pev->point;
Dwarf_Off off, noff;
size_t cuhl;
Dwarf_Die *diep;
int ret = 0;
#if _ELFUTILS_PREREQ(0, 142)
/* Get the call frame information from this dwarf */
pf->cfi = dwarf_getcfi(self->dbg);
#endif
off = 0;
line_list__init(&pf->lcache);
/* Fastpath: lookup by function name from .debug_pubnames section */
if (pp->function) {
struct pubname_callback_param pubname_param = {
.function = pp->function,
.file = pp->file,
.cu_die = &pf->cu_die,
.sp_die = &pf->sp_die,
.found = 0,
};
struct dwarf_callback_param probe_param = {
.data = pf,
};
dwarf_getpubnames(self->dbg, pubname_search_cb,
&pubname_param, 0);
if (pubname_param.found) {
ret = probe_point_search_cb(&pf->sp_die, &probe_param);
if (ret)
goto found;
}
}
/* Loop on CUs (Compilation Unit) */
while (!dwarf_nextcu(self->dbg, off, &noff, &cuhl, NULL, NULL, NULL)) {
/* Get the DIE(Debugging Information Entry) of this CU */
diep = dwarf_offdie(self->dbg, off + cuhl, &pf->cu_die);
if (!diep)
continue;
/* Check if target file is included. */
if (pp->file)
pf->fname = cu_find_realpath(&pf->cu_die, pp->file);
else
pf->fname = NULL;
if (!pp->file || pf->fname) {
if (pp->function)
ret = find_probe_point_by_func(pf);
else if (pp->lazy_line)
ret = find_probe_point_lazy(NULL, pf);
else {
pf->lno = pp->line;
ret = find_probe_point_by_line(pf);
}
if (ret < 0)
break;
}
off = noff;
}
found:
line_list__free(&pf->lcache);
return ret;
}
/* Add a found probe point into trace event list */
static int add_probe_trace_event(Dwarf_Die *sc_die, struct probe_finder *pf)
{
struct trace_event_finder *tf =
container_of(pf, struct trace_event_finder, pf);
struct probe_trace_event *tev;
int ret, i;
/* Check number of tevs */
if (tf->ntevs == tf->max_tevs) {
pr_warning("Too many( > %d) probe point found.\n",
tf->max_tevs);
return -ERANGE;
}
tev = &tf->tevs[tf->ntevs++];
/* Trace point should be converted from subprogram DIE */
ret = convert_to_trace_point(&pf->sp_die, pf->addr,
pf->pev->point.retprobe, &tev->point);
if (ret < 0)
return ret;
pr_debug("Probe point found: %s+%lu\n", tev->point.symbol,
tev->point.offset);
/* Find each argument */
tev->nargs = pf->pev->nargs;
tev->args = zalloc(sizeof(struct probe_trace_arg) * tev->nargs);
if (tev->args == NULL)
return -ENOMEM;
for (i = 0; i < pf->pev->nargs; i++) {
pf->pvar = &pf->pev->args[i];
pf->tvar = &tev->args[i];
/* Variable should be found from scope DIE */
ret = find_variable(sc_die, pf);
if (ret != 0)
return ret;
}
return 0;
}
/* Find probe_trace_events specified by perf_probe_event from debuginfo */
int debuginfo__find_trace_events(struct debuginfo *self,
struct perf_probe_event *pev,
struct probe_trace_event **tevs, int max_tevs)
{
struct trace_event_finder tf = {
.pf = {.pev = pev, .callback = add_probe_trace_event},
.max_tevs = max_tevs};
int ret;
/* Allocate result tevs array */
*tevs = zalloc(sizeof(struct probe_trace_event) * max_tevs);
if (*tevs == NULL)
return -ENOMEM;
tf.tevs = *tevs;
tf.ntevs = 0;
ret = debuginfo__find_probes(self, &tf.pf);
if (ret < 0) {
free(*tevs);
*tevs = NULL;
return ret;
}
return (ret < 0) ? ret : tf.ntevs;
}
#define MAX_VAR_LEN 64
/* Collect available variables in this scope */
static int collect_variables_cb(Dwarf_Die *die_mem, void *data)
{
struct available_var_finder *af = data;
struct variable_list *vl;
char buf[MAX_VAR_LEN];
int tag, ret;
vl = &af->vls[af->nvls - 1];
tag = dwarf_tag(die_mem);
if (tag == DW_TAG_formal_parameter ||
tag == DW_TAG_variable) {
ret = convert_variable_location(die_mem, af->pf.addr,
af->pf.fb_ops, NULL);
if (ret == 0) {
ret = die_get_varname(die_mem, buf, MAX_VAR_LEN);
pr_debug2("Add new var: %s\n", buf);
if (ret > 0)
strlist__add(vl->vars, buf);
}
}
if (af->child && dwarf_haspc(die_mem, af->pf.addr))
return DIE_FIND_CB_CONTINUE;
else
return DIE_FIND_CB_SIBLING;
}
/* Add a found vars into available variables list */
static int add_available_vars(Dwarf_Die *sc_die, struct probe_finder *pf)
{
struct available_var_finder *af =
container_of(pf, struct available_var_finder, pf);
struct variable_list *vl;
Dwarf_Die die_mem;
int ret;
/* Check number of tevs */
if (af->nvls == af->max_vls) {
pr_warning("Too many( > %d) probe point found.\n", af->max_vls);
return -ERANGE;
}
vl = &af->vls[af->nvls++];
/* Trace point should be converted from subprogram DIE */
ret = convert_to_trace_point(&pf->sp_die, pf->addr,
pf->pev->point.retprobe, &vl->point);
if (ret < 0)
return ret;
pr_debug("Probe point found: %s+%lu\n", vl->point.symbol,
vl->point.offset);
/* Find local variables */
vl->vars = strlist__new(true, NULL);
if (vl->vars == NULL)
return -ENOMEM;
af->child = true;
die_find_child(sc_die, collect_variables_cb, (void *)af, &die_mem);
/* Find external variables */
if (!af->externs)
goto out;
/* Don't need to search child DIE for externs. */
af->child = false;
die_find_child(&pf->cu_die, collect_variables_cb, (void *)af, &die_mem);
out:
if (strlist__empty(vl->vars)) {
strlist__delete(vl->vars);
vl->vars = NULL;
}
return ret;
}
/* Find available variables at given probe point */
int debuginfo__find_available_vars_at(struct debuginfo *self,
struct perf_probe_event *pev,
struct variable_list **vls,
int max_vls, bool externs)
{
struct available_var_finder af = {
.pf = {.pev = pev, .callback = add_available_vars},
.max_vls = max_vls, .externs = externs};
int ret;
/* Allocate result vls array */
*vls = zalloc(sizeof(struct variable_list) * max_vls);
if (*vls == NULL)
return -ENOMEM;
af.vls = *vls;
af.nvls = 0;
ret = debuginfo__find_probes(self, &af.pf);
if (ret < 0) {
/* Free vlist for error */
while (af.nvls--) {
if (af.vls[af.nvls].point.symbol)
free(af.vls[af.nvls].point.symbol);
if (af.vls[af.nvls].vars)
strlist__delete(af.vls[af.nvls].vars);
}
free(af.vls);
*vls = NULL;
return ret;
}
return (ret < 0) ? ret : af.nvls;
}
/* Reverse search */
int debuginfo__find_probe_point(struct debuginfo *self, unsigned long addr,
struct perf_probe_point *ppt)
{
Dwarf_Die cudie, spdie, indie;
Dwarf_Addr _addr, baseaddr;
const char *fname = NULL, *func = NULL, *tmp;
int baseline = 0, lineno = 0, ret = 0;
/* Adjust address with bias */
addr += self->bias;
/* Find cu die */
if (!dwarf_addrdie(self->dbg, (Dwarf_Addr)addr - self->bias, &cudie)) {
pr_warning("Failed to find debug information for address %lx\n",
addr);
ret = -EINVAL;
goto end;
}
/* Find a corresponding line (filename and lineno) */
cu_find_lineinfo(&cudie, addr, &fname, &lineno);
/* Don't care whether it failed or not */
/* Find a corresponding function (name, baseline and baseaddr) */
if (die_find_realfunc(&cudie, (Dwarf_Addr)addr, &spdie)) {
/* Get function entry information */
tmp = dwarf_diename(&spdie);
if (!tmp ||
dwarf_entrypc(&spdie, &baseaddr) != 0 ||
dwarf_decl_line(&spdie, &baseline) != 0)
goto post;
func = tmp;
if (addr == (unsigned long)baseaddr)
/* Function entry - Relative line number is 0 */
lineno = baseline;
else if (die_find_inlinefunc(&spdie, (Dwarf_Addr)addr,
&indie)) {
if (dwarf_entrypc(&indie, &_addr) == 0 &&
_addr == addr)
/*
* addr is at an inline function entry.
* In this case, lineno should be the call-site
* line number.
*/
lineno = die_get_call_lineno(&indie);
else {
/*
* addr is in an inline function body.
* Since lineno points one of the lines
* of the inline function, baseline should
* be the entry line of the inline function.
*/
tmp = dwarf_diename(&indie);
if (tmp &&
dwarf_decl_line(&spdie, &baseline) == 0)
func = tmp;
}
}
}
post:
/* Make a relative line number or an offset */
if (lineno)
ppt->line = lineno - baseline;
else if (func)
ppt->offset = addr - (unsigned long)baseaddr;
/* Duplicate strings */
if (func) {
ppt->function = strdup(func);
if (ppt->function == NULL) {
ret = -ENOMEM;
goto end;
}
}
if (fname) {
ppt->file = strdup(fname);
if (ppt->file == NULL) {
if (ppt->function) {
free(ppt->function);
ppt->function = NULL;
}
ret = -ENOMEM;
goto end;
}
}
end:
if (ret == 0 && (fname || func))
ret = 1; /* Found a point */
return ret;
}
/* Add a line and store the src path */
static int line_range_add_line(const char *src, unsigned int lineno,
struct line_range *lr)
{
/* Copy source path */
if (!lr->path) {
lr->path = strdup(src);
if (lr->path == NULL)
return -ENOMEM;
}
return line_list__add_line(&lr->line_list, lineno);
}
static int line_range_walk_cb(const char *fname, int lineno,
Dwarf_Addr addr __maybe_unused,
void *data)
{
struct line_finder *lf = data;
if ((strtailcmp(fname, lf->fname) != 0) ||
(lf->lno_s > lineno || lf->lno_e < lineno))
return 0;
if (line_range_add_line(fname, lineno, lf->lr) < 0)
return -EINVAL;
return 0;
}
/* Find line range from its line number */
static int find_line_range_by_line(Dwarf_Die *sp_die, struct line_finder *lf)
{
int ret;
ret = die_walk_lines(sp_die ?: &lf->cu_die, line_range_walk_cb, lf);
/* Update status */
if (ret >= 0)
if (!list_empty(&lf->lr->line_list))
ret = lf->found = 1;
else
ret = 0; /* Lines are not found */
else {
free(lf->lr->path);
lf->lr->path = NULL;
}
return ret;
}
static int line_range_inline_cb(Dwarf_Die *in_die, void *data)
{
find_line_range_by_line(in_die, data);
/*
* We have to check all instances of inlined function, because
* some execution paths can be optimized out depends on the
* function argument of instances
*/
return 0;
}
/* Search function from function name */
static int line_range_search_cb(Dwarf_Die *sp_die, void *data)
{
struct dwarf_callback_param *param = data;
struct line_finder *lf = param->data;
struct line_range *lr = lf->lr;
/* Check declared file */
if (lr->file && strtailcmp(lr->file, dwarf_decl_file(sp_die)))
return DWARF_CB_OK;
if (dwarf_tag(sp_die) == DW_TAG_subprogram &&
die_compare_name(sp_die, lr->function)) {
lf->fname = dwarf_decl_file(sp_die);
dwarf_decl_line(sp_die, &lr->offset);
pr_debug("fname: %s, lineno:%d\n", lf->fname, lr->offset);
lf->lno_s = lr->offset + lr->start;
if (lf->lno_s < 0) /* Overflow */
lf->lno_s = INT_MAX;
lf->lno_e = lr->offset + lr->end;
if (lf->lno_e < 0) /* Overflow */
lf->lno_e = INT_MAX;
pr_debug("New line range: %d to %d\n", lf->lno_s, lf->lno_e);
lr->start = lf->lno_s;
lr->end = lf->lno_e;
if (dwarf_func_inline(sp_die))
param->retval = die_walk_instances(sp_die,
line_range_inline_cb, lf);
else
param->retval = find_line_range_by_line(sp_die, lf);
return DWARF_CB_ABORT;
}
return DWARF_CB_OK;
}
static int find_line_range_by_func(struct line_finder *lf)
{
struct dwarf_callback_param param = {.data = (void *)lf, .retval = 0};
dwarf_getfuncs(&lf->cu_die, line_range_search_cb, ¶m, 0);
return param.retval;
}
int debuginfo__find_line_range(struct debuginfo *self, struct line_range *lr)
{
struct line_finder lf = {.lr = lr, .found = 0};
int ret = 0;
Dwarf_Off off = 0, noff;
size_t cuhl;
Dwarf_Die *diep;
const char *comp_dir;
/* Fastpath: lookup by function name from .debug_pubnames section */
if (lr->function) {
struct pubname_callback_param pubname_param = {
.function = lr->function, .file = lr->file,
.cu_die = &lf.cu_die, .sp_die = &lf.sp_die, .found = 0};
struct dwarf_callback_param line_range_param = {
.data = (void *)&lf, .retval = 0};
dwarf_getpubnames(self->dbg, pubname_search_cb,
&pubname_param, 0);
if (pubname_param.found) {
line_range_search_cb(&lf.sp_die, &line_range_param);
if (lf.found)
goto found;
}
}
/* Loop on CUs (Compilation Unit) */
while (!lf.found && ret >= 0) {
if (dwarf_nextcu(self->dbg, off, &noff, &cuhl,
NULL, NULL, NULL) != 0)
break;
/* Get the DIE(Debugging Information Entry) of this CU */
diep = dwarf_offdie(self->dbg, off + cuhl, &lf.cu_die);
if (!diep)
continue;
/* Check if target file is included. */
if (lr->file)
lf.fname = cu_find_realpath(&lf.cu_die, lr->file);
else
lf.fname = 0;
if (!lr->file || lf.fname) {
if (lr->function)
ret = find_line_range_by_func(&lf);
else {
lf.lno_s = lr->start;
lf.lno_e = lr->end;
ret = find_line_range_by_line(NULL, &lf);
}
}
off = noff;
}
found:
/* Store comp_dir */
if (lf.found) {
comp_dir = cu_get_comp_dir(&lf.cu_die);
if (comp_dir) {
lr->comp_dir = strdup(comp_dir);
if (!lr->comp_dir)
ret = -ENOMEM;
}
}
pr_debug("path: %s\n", lr->path);
return (ret < 0) ? ret : lf.found;
}
| gpl-2.0 |
spiderworthy/linux | drivers/gpu/drm/tilcdc/tilcdc_drv.c | 423 | 16988 | /*
* Copyright (C) 2012 Texas Instruments
* Author: Rob Clark <robdclark@gmail.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* LCDC DRM driver, based on da8xx-fb */
#include "tilcdc_drv.h"
#include "tilcdc_regs.h"
#include "tilcdc_tfp410.h"
#include "tilcdc_slave.h"
#include "tilcdc_panel.h"
#include "drm_fb_helper.h"
static LIST_HEAD(module_list);
static bool slave_probing;
void tilcdc_module_init(struct tilcdc_module *mod, const char *name,
const struct tilcdc_module_ops *funcs)
{
mod->name = name;
mod->funcs = funcs;
INIT_LIST_HEAD(&mod->list);
list_add(&mod->list, &module_list);
}
void tilcdc_module_cleanup(struct tilcdc_module *mod)
{
list_del(&mod->list);
}
void tilcdc_slave_probedefer(bool defered)
{
slave_probing = defered;
}
static struct of_device_id tilcdc_of_match[];
static struct drm_framebuffer *tilcdc_fb_create(struct drm_device *dev,
struct drm_file *file_priv, struct drm_mode_fb_cmd2 *mode_cmd)
{
return drm_fb_cma_create(dev, file_priv, mode_cmd);
}
static void tilcdc_fb_output_poll_changed(struct drm_device *dev)
{
struct tilcdc_drm_private *priv = dev->dev_private;
drm_fbdev_cma_hotplug_event(priv->fbdev);
}
static const struct drm_mode_config_funcs mode_config_funcs = {
.fb_create = tilcdc_fb_create,
.output_poll_changed = tilcdc_fb_output_poll_changed,
};
static int modeset_init(struct drm_device *dev)
{
struct tilcdc_drm_private *priv = dev->dev_private;
struct tilcdc_module *mod;
drm_mode_config_init(dev);
priv->crtc = tilcdc_crtc_create(dev);
list_for_each_entry(mod, &module_list, list) {
DBG("loading module: %s", mod->name);
mod->funcs->modeset_init(mod, dev);
}
if ((priv->num_encoders == 0) || (priv->num_connectors == 0)) {
/* oh nos! */
dev_err(dev->dev, "no encoders/connectors found\n");
drm_mode_config_cleanup(dev);
return -ENXIO;
}
dev->mode_config.min_width = 0;
dev->mode_config.min_height = 0;
dev->mode_config.max_width = tilcdc_crtc_max_width(priv->crtc);
dev->mode_config.max_height = 2048;
dev->mode_config.funcs = &mode_config_funcs;
return 0;
}
#ifdef CONFIG_CPU_FREQ
static int cpufreq_transition(struct notifier_block *nb,
unsigned long val, void *data)
{
struct tilcdc_drm_private *priv = container_of(nb,
struct tilcdc_drm_private, freq_transition);
if (val == CPUFREQ_POSTCHANGE) {
if (priv->lcd_fck_rate != clk_get_rate(priv->clk)) {
priv->lcd_fck_rate = clk_get_rate(priv->clk);
tilcdc_crtc_update_clk(priv->crtc);
}
}
return 0;
}
#endif
/*
* DRM operations:
*/
static int tilcdc_unload(struct drm_device *dev)
{
struct tilcdc_drm_private *priv = dev->dev_private;
drm_fbdev_cma_fini(priv->fbdev);
drm_kms_helper_poll_fini(dev);
drm_mode_config_cleanup(dev);
drm_vblank_cleanup(dev);
pm_runtime_get_sync(dev->dev);
drm_irq_uninstall(dev);
pm_runtime_put_sync(dev->dev);
#ifdef CONFIG_CPU_FREQ
cpufreq_unregister_notifier(&priv->freq_transition,
CPUFREQ_TRANSITION_NOTIFIER);
#endif
if (priv->clk)
clk_put(priv->clk);
if (priv->mmio)
iounmap(priv->mmio);
flush_workqueue(priv->wq);
destroy_workqueue(priv->wq);
dev->dev_private = NULL;
pm_runtime_disable(dev->dev);
kfree(priv);
return 0;
}
static int tilcdc_load(struct drm_device *dev, unsigned long flags)
{
struct platform_device *pdev = dev->platformdev;
struct device_node *node = pdev->dev.of_node;
struct tilcdc_drm_private *priv;
struct tilcdc_module *mod;
struct resource *res;
u32 bpp = 0;
int ret;
priv = kzalloc(sizeof(*priv), GFP_KERNEL);
if (!priv) {
dev_err(dev->dev, "failed to allocate private data\n");
return -ENOMEM;
}
dev->dev_private = priv;
priv->wq = alloc_ordered_workqueue("tilcdc", 0);
if (!priv->wq) {
ret = -ENOMEM;
goto fail_free_priv;
}
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
dev_err(dev->dev, "failed to get memory resource\n");
ret = -EINVAL;
goto fail_free_wq;
}
priv->mmio = ioremap_nocache(res->start, resource_size(res));
if (!priv->mmio) {
dev_err(dev->dev, "failed to ioremap\n");
ret = -ENOMEM;
goto fail_free_wq;
}
priv->clk = clk_get(dev->dev, "fck");
if (IS_ERR(priv->clk)) {
dev_err(dev->dev, "failed to get functional clock\n");
ret = -ENODEV;
goto fail_iounmap;
}
priv->disp_clk = clk_get(dev->dev, "dpll_disp_ck");
if (IS_ERR(priv->clk)) {
dev_err(dev->dev, "failed to get display clock\n");
ret = -ENODEV;
goto fail_put_clk;
}
#ifdef CONFIG_CPU_FREQ
priv->lcd_fck_rate = clk_get_rate(priv->clk);
priv->freq_transition.notifier_call = cpufreq_transition;
ret = cpufreq_register_notifier(&priv->freq_transition,
CPUFREQ_TRANSITION_NOTIFIER);
if (ret) {
dev_err(dev->dev, "failed to register cpufreq notifier\n");
goto fail_put_disp_clk;
}
#endif
if (of_property_read_u32(node, "max-bandwidth", &priv->max_bandwidth))
priv->max_bandwidth = TILCDC_DEFAULT_MAX_BANDWIDTH;
DBG("Maximum Bandwidth Value %d", priv->max_bandwidth);
if (of_property_read_u32(node, "ti,max-width", &priv->max_width))
priv->max_width = TILCDC_DEFAULT_MAX_WIDTH;
DBG("Maximum Horizontal Pixel Width Value %dpixels", priv->max_width);
if (of_property_read_u32(node, "ti,max-pixelclock",
&priv->max_pixelclock))
priv->max_pixelclock = TILCDC_DEFAULT_MAX_PIXELCLOCK;
DBG("Maximum Pixel Clock Value %dKHz", priv->max_pixelclock);
pm_runtime_enable(dev->dev);
/* Determine LCD IP Version */
pm_runtime_get_sync(dev->dev);
switch (tilcdc_read(dev, LCDC_PID_REG)) {
case 0x4c100102:
priv->rev = 1;
break;
case 0x4f200800:
case 0x4f201000:
priv->rev = 2;
break;
default:
dev_warn(dev->dev, "Unknown PID Reg value 0x%08x, "
"defaulting to LCD revision 1\n",
tilcdc_read(dev, LCDC_PID_REG));
priv->rev = 1;
break;
}
pm_runtime_put_sync(dev->dev);
ret = modeset_init(dev);
if (ret < 0) {
dev_err(dev->dev, "failed to initialize mode setting\n");
goto fail_cpufreq_unregister;
}
ret = drm_vblank_init(dev, 1);
if (ret < 0) {
dev_err(dev->dev, "failed to initialize vblank\n");
goto fail_mode_config_cleanup;
}
pm_runtime_get_sync(dev->dev);
ret = drm_irq_install(dev, platform_get_irq(dev->platformdev, 0));
pm_runtime_put_sync(dev->dev);
if (ret < 0) {
dev_err(dev->dev, "failed to install IRQ handler\n");
goto fail_vblank_cleanup;
}
platform_set_drvdata(pdev, dev);
list_for_each_entry(mod, &module_list, list) {
DBG("%s: preferred_bpp: %d", mod->name, mod->preferred_bpp);
bpp = mod->preferred_bpp;
if (bpp > 0)
break;
}
priv->fbdev = drm_fbdev_cma_init(dev, bpp,
dev->mode_config.num_crtc,
dev->mode_config.num_connector);
if (IS_ERR(priv->fbdev)) {
ret = PTR_ERR(priv->fbdev);
goto fail_irq_uninstall;
}
drm_kms_helper_poll_init(dev);
return 0;
fail_irq_uninstall:
pm_runtime_get_sync(dev->dev);
drm_irq_uninstall(dev);
pm_runtime_put_sync(dev->dev);
fail_vblank_cleanup:
drm_vblank_cleanup(dev);
fail_mode_config_cleanup:
drm_mode_config_cleanup(dev);
fail_cpufreq_unregister:
pm_runtime_disable(dev->dev);
#ifdef CONFIG_CPU_FREQ
cpufreq_unregister_notifier(&priv->freq_transition,
CPUFREQ_TRANSITION_NOTIFIER);
fail_put_disp_clk:
clk_put(priv->disp_clk);
#endif
fail_put_clk:
clk_put(priv->clk);
fail_iounmap:
iounmap(priv->mmio);
fail_free_wq:
flush_workqueue(priv->wq);
destroy_workqueue(priv->wq);
fail_free_priv:
dev->dev_private = NULL;
kfree(priv);
return ret;
}
static void tilcdc_preclose(struct drm_device *dev, struct drm_file *file)
{
struct tilcdc_drm_private *priv = dev->dev_private;
tilcdc_crtc_cancel_page_flip(priv->crtc, file);
}
static void tilcdc_lastclose(struct drm_device *dev)
{
struct tilcdc_drm_private *priv = dev->dev_private;
drm_fbdev_cma_restore_mode(priv->fbdev);
}
static irqreturn_t tilcdc_irq(int irq, void *arg)
{
struct drm_device *dev = arg;
struct tilcdc_drm_private *priv = dev->dev_private;
return tilcdc_crtc_irq(priv->crtc);
}
static void tilcdc_irq_preinstall(struct drm_device *dev)
{
tilcdc_clear_irqstatus(dev, 0xffffffff);
}
static int tilcdc_irq_postinstall(struct drm_device *dev)
{
struct tilcdc_drm_private *priv = dev->dev_private;
/* enable FIFO underflow irq: */
if (priv->rev == 1)
tilcdc_set(dev, LCDC_RASTER_CTRL_REG, LCDC_V1_UNDERFLOW_INT_ENA);
else
tilcdc_set(dev, LCDC_INT_ENABLE_SET_REG, LCDC_V2_UNDERFLOW_INT_ENA);
return 0;
}
static void tilcdc_irq_uninstall(struct drm_device *dev)
{
struct tilcdc_drm_private *priv = dev->dev_private;
/* disable irqs that we might have enabled: */
if (priv->rev == 1) {
tilcdc_clear(dev, LCDC_RASTER_CTRL_REG,
LCDC_V1_UNDERFLOW_INT_ENA | LCDC_V1_PL_INT_ENA);
tilcdc_clear(dev, LCDC_DMA_CTRL_REG, LCDC_V1_END_OF_FRAME_INT_ENA);
} else {
tilcdc_clear(dev, LCDC_INT_ENABLE_SET_REG,
LCDC_V2_UNDERFLOW_INT_ENA | LCDC_V2_PL_INT_ENA |
LCDC_V2_END_OF_FRAME0_INT_ENA | LCDC_V2_END_OF_FRAME1_INT_ENA |
LCDC_FRAME_DONE);
}
}
static void enable_vblank(struct drm_device *dev, bool enable)
{
struct tilcdc_drm_private *priv = dev->dev_private;
u32 reg, mask;
if (priv->rev == 1) {
reg = LCDC_DMA_CTRL_REG;
mask = LCDC_V1_END_OF_FRAME_INT_ENA;
} else {
reg = LCDC_INT_ENABLE_SET_REG;
mask = LCDC_V2_END_OF_FRAME0_INT_ENA |
LCDC_V2_END_OF_FRAME1_INT_ENA | LCDC_FRAME_DONE;
}
if (enable)
tilcdc_set(dev, reg, mask);
else
tilcdc_clear(dev, reg, mask);
}
static int tilcdc_enable_vblank(struct drm_device *dev, int crtc)
{
enable_vblank(dev, true);
return 0;
}
static void tilcdc_disable_vblank(struct drm_device *dev, int crtc)
{
enable_vblank(dev, false);
}
#if defined(CONFIG_DEBUG_FS) || defined(CONFIG_PM_SLEEP)
static const struct {
const char *name;
uint8_t rev;
uint8_t save;
uint32_t reg;
} registers[] = {
#define REG(rev, save, reg) { #reg, rev, save, reg }
/* exists in revision 1: */
REG(1, false, LCDC_PID_REG),
REG(1, true, LCDC_CTRL_REG),
REG(1, false, LCDC_STAT_REG),
REG(1, true, LCDC_RASTER_CTRL_REG),
REG(1, true, LCDC_RASTER_TIMING_0_REG),
REG(1, true, LCDC_RASTER_TIMING_1_REG),
REG(1, true, LCDC_RASTER_TIMING_2_REG),
REG(1, true, LCDC_DMA_CTRL_REG),
REG(1, true, LCDC_DMA_FB_BASE_ADDR_0_REG),
REG(1, true, LCDC_DMA_FB_CEILING_ADDR_0_REG),
REG(1, true, LCDC_DMA_FB_BASE_ADDR_1_REG),
REG(1, true, LCDC_DMA_FB_CEILING_ADDR_1_REG),
/* new in revision 2: */
REG(2, false, LCDC_RAW_STAT_REG),
REG(2, false, LCDC_MASKED_STAT_REG),
REG(2, false, LCDC_INT_ENABLE_SET_REG),
REG(2, false, LCDC_INT_ENABLE_CLR_REG),
REG(2, false, LCDC_END_OF_INT_IND_REG),
REG(2, true, LCDC_CLK_ENABLE_REG),
REG(2, true, LCDC_INT_ENABLE_SET_REG),
#undef REG
};
#endif
#ifdef CONFIG_DEBUG_FS
static int tilcdc_regs_show(struct seq_file *m, void *arg)
{
struct drm_info_node *node = (struct drm_info_node *) m->private;
struct drm_device *dev = node->minor->dev;
struct tilcdc_drm_private *priv = dev->dev_private;
unsigned i;
pm_runtime_get_sync(dev->dev);
seq_printf(m, "revision: %d\n", priv->rev);
for (i = 0; i < ARRAY_SIZE(registers); i++)
if (priv->rev >= registers[i].rev)
seq_printf(m, "%s:\t %08x\n", registers[i].name,
tilcdc_read(dev, registers[i].reg));
pm_runtime_put_sync(dev->dev);
return 0;
}
static int tilcdc_mm_show(struct seq_file *m, void *arg)
{
struct drm_info_node *node = (struct drm_info_node *) m->private;
struct drm_device *dev = node->minor->dev;
return drm_mm_dump_table(m, &dev->vma_offset_manager->vm_addr_space_mm);
}
static struct drm_info_list tilcdc_debugfs_list[] = {
{ "regs", tilcdc_regs_show, 0 },
{ "mm", tilcdc_mm_show, 0 },
{ "fb", drm_fb_cma_debugfs_show, 0 },
};
static int tilcdc_debugfs_init(struct drm_minor *minor)
{
struct drm_device *dev = minor->dev;
struct tilcdc_module *mod;
int ret;
ret = drm_debugfs_create_files(tilcdc_debugfs_list,
ARRAY_SIZE(tilcdc_debugfs_list),
minor->debugfs_root, minor);
list_for_each_entry(mod, &module_list, list)
if (mod->funcs->debugfs_init)
mod->funcs->debugfs_init(mod, minor);
if (ret) {
dev_err(dev->dev, "could not install tilcdc_debugfs_list\n");
return ret;
}
return ret;
}
static void tilcdc_debugfs_cleanup(struct drm_minor *minor)
{
struct tilcdc_module *mod;
drm_debugfs_remove_files(tilcdc_debugfs_list,
ARRAY_SIZE(tilcdc_debugfs_list), minor);
list_for_each_entry(mod, &module_list, list)
if (mod->funcs->debugfs_cleanup)
mod->funcs->debugfs_cleanup(mod, minor);
}
#endif
static const struct file_operations fops = {
.owner = THIS_MODULE,
.open = drm_open,
.release = drm_release,
.unlocked_ioctl = drm_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = drm_compat_ioctl,
#endif
.poll = drm_poll,
.read = drm_read,
.llseek = no_llseek,
.mmap = drm_gem_cma_mmap,
};
static struct drm_driver tilcdc_driver = {
.driver_features = DRIVER_HAVE_IRQ | DRIVER_GEM | DRIVER_MODESET,
.load = tilcdc_load,
.unload = tilcdc_unload,
.preclose = tilcdc_preclose,
.lastclose = tilcdc_lastclose,
.set_busid = drm_platform_set_busid,
.irq_handler = tilcdc_irq,
.irq_preinstall = tilcdc_irq_preinstall,
.irq_postinstall = tilcdc_irq_postinstall,
.irq_uninstall = tilcdc_irq_uninstall,
.get_vblank_counter = drm_vblank_count,
.enable_vblank = tilcdc_enable_vblank,
.disable_vblank = tilcdc_disable_vblank,
.gem_free_object = drm_gem_cma_free_object,
.gem_vm_ops = &drm_gem_cma_vm_ops,
.dumb_create = drm_gem_cma_dumb_create,
.dumb_map_offset = drm_gem_cma_dumb_map_offset,
.dumb_destroy = drm_gem_dumb_destroy,
#ifdef CONFIG_DEBUG_FS
.debugfs_init = tilcdc_debugfs_init,
.debugfs_cleanup = tilcdc_debugfs_cleanup,
#endif
.fops = &fops,
.name = "tilcdc",
.desc = "TI LCD Controller DRM",
.date = "20121205",
.major = 1,
.minor = 0,
};
/*
* Power management:
*/
#ifdef CONFIG_PM_SLEEP
static int tilcdc_pm_suspend(struct device *dev)
{
struct drm_device *ddev = dev_get_drvdata(dev);
struct tilcdc_drm_private *priv = ddev->dev_private;
unsigned i, n = 0;
drm_kms_helper_poll_disable(ddev);
/* Save register state: */
for (i = 0; i < ARRAY_SIZE(registers); i++)
if (registers[i].save && (priv->rev >= registers[i].rev))
priv->saved_register[n++] = tilcdc_read(ddev, registers[i].reg);
return 0;
}
static int tilcdc_pm_resume(struct device *dev)
{
struct drm_device *ddev = dev_get_drvdata(dev);
struct tilcdc_drm_private *priv = ddev->dev_private;
unsigned i, n = 0;
/* Restore register state: */
for (i = 0; i < ARRAY_SIZE(registers); i++)
if (registers[i].save && (priv->rev >= registers[i].rev))
tilcdc_write(ddev, registers[i].reg, priv->saved_register[n++]);
drm_kms_helper_poll_enable(ddev);
return 0;
}
#endif
static const struct dev_pm_ops tilcdc_pm_ops = {
SET_SYSTEM_SLEEP_PM_OPS(tilcdc_pm_suspend, tilcdc_pm_resume)
};
/*
* Platform driver:
*/
static int tilcdc_pdev_probe(struct platform_device *pdev)
{
/* bail out early if no DT data: */
if (!pdev->dev.of_node) {
dev_err(&pdev->dev, "device-tree data is missing\n");
return -ENXIO;
}
/* defer probing if slave is in deferred probing */
if (slave_probing == true)
return -EPROBE_DEFER;
return drm_platform_init(&tilcdc_driver, pdev);
}
static int tilcdc_pdev_remove(struct platform_device *pdev)
{
drm_put_dev(platform_get_drvdata(pdev));
return 0;
}
static struct of_device_id tilcdc_of_match[] = {
{ .compatible = "ti,am33xx-tilcdc", },
{ },
};
MODULE_DEVICE_TABLE(of, tilcdc_of_match);
static struct platform_driver tilcdc_platform_driver = {
.probe = tilcdc_pdev_probe,
.remove = tilcdc_pdev_remove,
.driver = {
.name = "tilcdc",
.pm = &tilcdc_pm_ops,
.of_match_table = tilcdc_of_match,
},
};
static int __init tilcdc_drm_init(void)
{
DBG("init");
tilcdc_tfp410_init();
tilcdc_slave_init();
tilcdc_panel_init();
return platform_driver_register(&tilcdc_platform_driver);
}
static void __exit tilcdc_drm_fini(void)
{
DBG("fini");
platform_driver_unregister(&tilcdc_platform_driver);
tilcdc_panel_fini();
tilcdc_slave_fini();
tilcdc_tfp410_fini();
}
module_init(tilcdc_drm_init);
module_exit(tilcdc_drm_fini);
MODULE_AUTHOR("Rob Clark <robdclark@gmail.com");
MODULE_DESCRIPTION("TI LCD Controller DRM Driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
templetontsai/nexus7-grouper-kernel | drivers/usb/gadget/pxa25x_udc.c | 423 | 59942 | /*
* Intel PXA25x and IXP4xx on-chip full speed USB device controllers
*
* Copyright (C) 2002 Intrinsyc, Inc. (Frank Becker)
* Copyright (C) 2003 Robert Schwebel, Pengutronix
* Copyright (C) 2003 Benedikt Spranger, Pengutronix
* Copyright (C) 2003 David Brownell
* Copyright (C) 2003 Joshua Wise
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/* #define VERBOSE_DEBUG */
#include <linux/device.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/ioport.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/timer.h>
#include <linux/list.h>
#include <linux/interrupt.h>
#include <linux/mm.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <linux/irq.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/seq_file.h>
#include <linux/debugfs.h>
#include <linux/io.h>
#include <linux/prefetch.h>
#include <asm/byteorder.h>
#include <asm/dma.h>
#include <asm/gpio.h>
#include <asm/system.h>
#include <asm/mach-types.h>
#include <asm/unaligned.h>
#include <linux/usb/ch9.h>
#include <linux/usb/gadget.h>
#include <linux/usb/otg.h>
/*
* This driver is PXA25x only. Grab the right register definitions.
*/
#ifdef CONFIG_ARCH_PXA
#include <mach/pxa25x-udc.h>
#endif
#ifdef CONFIG_ARCH_LUBBOCK
#include <mach/lubbock.h>
#endif
#include <asm/mach/udc_pxa2xx.h>
/*
* This driver handles the USB Device Controller (UDC) in Intel's PXA 25x
* series processors. The UDC for the IXP 4xx series is very similar.
* There are fifteen endpoints, in addition to ep0.
*
* Such controller drivers work with a gadget driver. The gadget driver
* returns descriptors, implements configuration and data protocols used
* by the host to interact with this device, and allocates endpoints to
* the different protocol interfaces. The controller driver virtualizes
* usb hardware so that the gadget drivers will be more portable.
*
* This UDC hardware wants to implement a bit too much USB protocol, so
* it constrains the sorts of USB configuration change events that work.
* The errata for these chips are misleading; some "fixed" bugs from
* pxa250 a0/a1 b0/b1/b2 sure act like they're still there.
*
* Note that the UDC hardware supports DMA (except on IXP) but that's
* not used here. IN-DMA (to host) is simple enough, when the data is
* suitably aligned (16 bytes) ... the network stack doesn't do that,
* other software can. OUT-DMA is buggy in most chip versions, as well
* as poorly designed (data toggle not automatic). So this driver won't
* bother using DMA. (Mostly-working IN-DMA support was available in
* kernels before 2.6.23, but was never enabled or well tested.)
*/
#define DRIVER_VERSION "30-June-2007"
#define DRIVER_DESC "PXA 25x USB Device Controller driver"
static const char driver_name [] = "pxa25x_udc";
static const char ep0name [] = "ep0";
#ifdef CONFIG_ARCH_IXP4XX
/* cpu-specific register addresses are compiled in to this code */
#ifdef CONFIG_ARCH_PXA
#error "Can't configure both IXP and PXA"
#endif
/* IXP doesn't yet support <linux/clk.h> */
#define clk_get(dev,name) NULL
#define clk_enable(clk) do { } while (0)
#define clk_disable(clk) do { } while (0)
#define clk_put(clk) do { } while (0)
#endif
#include "pxa25x_udc.h"
#ifdef CONFIG_USB_PXA25X_SMALL
#define SIZE_STR " (small)"
#else
#define SIZE_STR ""
#endif
/* ---------------------------------------------------------------------------
* endpoint related parts of the api to the usb controller hardware,
* used by gadget driver; and the inner talker-to-hardware core.
* ---------------------------------------------------------------------------
*/
static void pxa25x_ep_fifo_flush (struct usb_ep *ep);
static void nuke (struct pxa25x_ep *, int status);
/* one GPIO should control a D+ pullup, so host sees this device (or not) */
static void pullup_off(void)
{
struct pxa2xx_udc_mach_info *mach = the_controller->mach;
int off_level = mach->gpio_pullup_inverted;
if (gpio_is_valid(mach->gpio_pullup))
gpio_set_value(mach->gpio_pullup, off_level);
else if (mach->udc_command)
mach->udc_command(PXA2XX_UDC_CMD_DISCONNECT);
}
static void pullup_on(void)
{
struct pxa2xx_udc_mach_info *mach = the_controller->mach;
int on_level = !mach->gpio_pullup_inverted;
if (gpio_is_valid(mach->gpio_pullup))
gpio_set_value(mach->gpio_pullup, on_level);
else if (mach->udc_command)
mach->udc_command(PXA2XX_UDC_CMD_CONNECT);
}
static void pio_irq_enable(int bEndpointAddress)
{
bEndpointAddress &= 0xf;
if (bEndpointAddress < 8)
UICR0 &= ~(1 << bEndpointAddress);
else {
bEndpointAddress -= 8;
UICR1 &= ~(1 << bEndpointAddress);
}
}
static void pio_irq_disable(int bEndpointAddress)
{
bEndpointAddress &= 0xf;
if (bEndpointAddress < 8)
UICR0 |= 1 << bEndpointAddress;
else {
bEndpointAddress -= 8;
UICR1 |= 1 << bEndpointAddress;
}
}
/* The UDCCR reg contains mask and interrupt status bits,
* so using '|=' isn't safe as it may ack an interrupt.
*/
#define UDCCR_MASK_BITS (UDCCR_REM | UDCCR_SRM | UDCCR_UDE)
static inline void udc_set_mask_UDCCR(int mask)
{
UDCCR = (UDCCR & UDCCR_MASK_BITS) | (mask & UDCCR_MASK_BITS);
}
static inline void udc_clear_mask_UDCCR(int mask)
{
UDCCR = (UDCCR & UDCCR_MASK_BITS) & ~(mask & UDCCR_MASK_BITS);
}
static inline void udc_ack_int_UDCCR(int mask)
{
/* udccr contains the bits we dont want to change */
__u32 udccr = UDCCR & UDCCR_MASK_BITS;
UDCCR = udccr | (mask & ~UDCCR_MASK_BITS);
}
/*
* endpoint enable/disable
*
* we need to verify the descriptors used to enable endpoints. since pxa25x
* endpoint configurations are fixed, and are pretty much always enabled,
* there's not a lot to manage here.
*
* because pxa25x can't selectively initialize bulk (or interrupt) endpoints,
* (resetting endpoint halt and toggle), SET_INTERFACE is unusable except
* for a single interface (with only the default altsetting) and for gadget
* drivers that don't halt endpoints (not reset by set_interface). that also
* means that if you use ISO, you must violate the USB spec rule that all
* iso endpoints must be in non-default altsettings.
*/
static int pxa25x_ep_enable (struct usb_ep *_ep,
const struct usb_endpoint_descriptor *desc)
{
struct pxa25x_ep *ep;
struct pxa25x_udc *dev;
ep = container_of (_ep, struct pxa25x_ep, ep);
if (!_ep || !desc || ep->desc || _ep->name == ep0name
|| desc->bDescriptorType != USB_DT_ENDPOINT
|| ep->bEndpointAddress != desc->bEndpointAddress
|| ep->fifo_size < le16_to_cpu
(desc->wMaxPacketSize)) {
DMSG("%s, bad ep or descriptor\n", __func__);
return -EINVAL;
}
/* xfer types must match, except that interrupt ~= bulk */
if (ep->bmAttributes != desc->bmAttributes
&& ep->bmAttributes != USB_ENDPOINT_XFER_BULK
&& desc->bmAttributes != USB_ENDPOINT_XFER_INT) {
DMSG("%s, %s type mismatch\n", __func__, _ep->name);
return -EINVAL;
}
/* hardware _could_ do smaller, but driver doesn't */
if ((desc->bmAttributes == USB_ENDPOINT_XFER_BULK
&& le16_to_cpu (desc->wMaxPacketSize)
!= BULK_FIFO_SIZE)
|| !desc->wMaxPacketSize) {
DMSG("%s, bad %s maxpacket\n", __func__, _ep->name);
return -ERANGE;
}
dev = ep->dev;
if (!dev->driver || dev->gadget.speed == USB_SPEED_UNKNOWN) {
DMSG("%s, bogus device state\n", __func__);
return -ESHUTDOWN;
}
ep->desc = desc;
ep->stopped = 0;
ep->pio_irqs = 0;
ep->ep.maxpacket = le16_to_cpu (desc->wMaxPacketSize);
/* flush fifo (mostly for OUT buffers) */
pxa25x_ep_fifo_flush (_ep);
/* ... reset halt state too, if we could ... */
DBG(DBG_VERBOSE, "enabled %s\n", _ep->name);
return 0;
}
static int pxa25x_ep_disable (struct usb_ep *_ep)
{
struct pxa25x_ep *ep;
unsigned long flags;
ep = container_of (_ep, struct pxa25x_ep, ep);
if (!_ep || !ep->desc) {
DMSG("%s, %s not enabled\n", __func__,
_ep ? ep->ep.name : NULL);
return -EINVAL;
}
local_irq_save(flags);
nuke (ep, -ESHUTDOWN);
/* flush fifo (mostly for IN buffers) */
pxa25x_ep_fifo_flush (_ep);
ep->desc = NULL;
ep->stopped = 1;
local_irq_restore(flags);
DBG(DBG_VERBOSE, "%s disabled\n", _ep->name);
return 0;
}
/*-------------------------------------------------------------------------*/
/* for the pxa25x, these can just wrap kmalloc/kfree. gadget drivers
* must still pass correctly initialized endpoints, since other controller
* drivers may care about how it's currently set up (dma issues etc).
*/
/*
* pxa25x_ep_alloc_request - allocate a request data structure
*/
static struct usb_request *
pxa25x_ep_alloc_request (struct usb_ep *_ep, gfp_t gfp_flags)
{
struct pxa25x_request *req;
req = kzalloc(sizeof(*req), gfp_flags);
if (!req)
return NULL;
INIT_LIST_HEAD (&req->queue);
return &req->req;
}
/*
* pxa25x_ep_free_request - deallocate a request data structure
*/
static void
pxa25x_ep_free_request (struct usb_ep *_ep, struct usb_request *_req)
{
struct pxa25x_request *req;
req = container_of (_req, struct pxa25x_request, req);
WARN_ON(!list_empty (&req->queue));
kfree(req);
}
/*-------------------------------------------------------------------------*/
/*
* done - retire a request; caller blocked irqs
*/
static void done(struct pxa25x_ep *ep, struct pxa25x_request *req, int status)
{
unsigned stopped = ep->stopped;
list_del_init(&req->queue);
if (likely (req->req.status == -EINPROGRESS))
req->req.status = status;
else
status = req->req.status;
if (status && status != -ESHUTDOWN)
DBG(DBG_VERBOSE, "complete %s req %p stat %d len %u/%u\n",
ep->ep.name, &req->req, status,
req->req.actual, req->req.length);
/* don't modify queue heads during completion callback */
ep->stopped = 1;
req->req.complete(&ep->ep, &req->req);
ep->stopped = stopped;
}
static inline void ep0_idle (struct pxa25x_udc *dev)
{
dev->ep0state = EP0_IDLE;
}
static int
write_packet(volatile u32 *uddr, struct pxa25x_request *req, unsigned max)
{
u8 *buf;
unsigned length, count;
buf = req->req.buf + req->req.actual;
prefetch(buf);
/* how big will this packet be? */
length = min(req->req.length - req->req.actual, max);
req->req.actual += length;
count = length;
while (likely(count--))
*uddr = *buf++;
return length;
}
/*
* write to an IN endpoint fifo, as many packets as possible.
* irqs will use this to write the rest later.
* caller guarantees at least one packet buffer is ready (or a zlp).
*/
static int
write_fifo (struct pxa25x_ep *ep, struct pxa25x_request *req)
{
unsigned max;
max = le16_to_cpu(ep->desc->wMaxPacketSize);
do {
unsigned count;
int is_last, is_short;
count = write_packet(ep->reg_uddr, req, max);
/* last packet is usually short (or a zlp) */
if (unlikely (count != max))
is_last = is_short = 1;
else {
if (likely(req->req.length != req->req.actual)
|| req->req.zero)
is_last = 0;
else
is_last = 1;
/* interrupt/iso maxpacket may not fill the fifo */
is_short = unlikely (max < ep->fifo_size);
}
DBG(DBG_VERY_NOISY, "wrote %s %d bytes%s%s %d left %p\n",
ep->ep.name, count,
is_last ? "/L" : "", is_short ? "/S" : "",
req->req.length - req->req.actual, req);
/* let loose that packet. maybe try writing another one,
* double buffering might work. TSP, TPC, and TFS
* bit values are the same for all normal IN endpoints.
*/
*ep->reg_udccs = UDCCS_BI_TPC;
if (is_short)
*ep->reg_udccs = UDCCS_BI_TSP;
/* requests complete when all IN data is in the FIFO */
if (is_last) {
done (ep, req, 0);
if (list_empty(&ep->queue))
pio_irq_disable (ep->bEndpointAddress);
return 1;
}
// TODO experiment: how robust can fifo mode tweaking be?
// double buffering is off in the default fifo mode, which
// prevents TFS from being set here.
} while (*ep->reg_udccs & UDCCS_BI_TFS);
return 0;
}
/* caller asserts req->pending (ep0 irq status nyet cleared); starts
* ep0 data stage. these chips want very simple state transitions.
*/
static inline
void ep0start(struct pxa25x_udc *dev, u32 flags, const char *tag)
{
UDCCS0 = flags|UDCCS0_SA|UDCCS0_OPR;
USIR0 = USIR0_IR0;
dev->req_pending = 0;
DBG(DBG_VERY_NOISY, "%s %s, %02x/%02x\n",
__func__, tag, UDCCS0, flags);
}
static int
write_ep0_fifo (struct pxa25x_ep *ep, struct pxa25x_request *req)
{
unsigned count;
int is_short;
count = write_packet(&UDDR0, req, EP0_FIFO_SIZE);
ep->dev->stats.write.bytes += count;
/* last packet "must be" short (or a zlp) */
is_short = (count != EP0_FIFO_SIZE);
DBG(DBG_VERY_NOISY, "ep0in %d bytes %d left %p\n", count,
req->req.length - req->req.actual, req);
if (unlikely (is_short)) {
if (ep->dev->req_pending)
ep0start(ep->dev, UDCCS0_IPR, "short IN");
else
UDCCS0 = UDCCS0_IPR;
count = req->req.length;
done (ep, req, 0);
ep0_idle(ep->dev);
#ifndef CONFIG_ARCH_IXP4XX
#if 1
/* This seems to get rid of lost status irqs in some cases:
* host responds quickly, or next request involves config
* change automagic, or should have been hidden, or ...
*
* FIXME get rid of all udelays possible...
*/
if (count >= EP0_FIFO_SIZE) {
count = 100;
do {
if ((UDCCS0 & UDCCS0_OPR) != 0) {
/* clear OPR, generate ack */
UDCCS0 = UDCCS0_OPR;
break;
}
count--;
udelay(1);
} while (count);
}
#endif
#endif
} else if (ep->dev->req_pending)
ep0start(ep->dev, 0, "IN");
return is_short;
}
/*
* read_fifo - unload packet(s) from the fifo we use for usb OUT
* transfers and put them into the request. caller should have made
* sure there's at least one packet ready.
*
* returns true if the request completed because of short packet or the
* request buffer having filled (and maybe overran till end-of-packet).
*/
static int
read_fifo (struct pxa25x_ep *ep, struct pxa25x_request *req)
{
for (;;) {
u32 udccs;
u8 *buf;
unsigned bufferspace, count, is_short;
/* make sure there's a packet in the FIFO.
* UDCCS_{BO,IO}_RPC are all the same bit value.
* UDCCS_{BO,IO}_RNE are all the same bit value.
*/
udccs = *ep->reg_udccs;
if (unlikely ((udccs & UDCCS_BO_RPC) == 0))
break;
buf = req->req.buf + req->req.actual;
prefetchw(buf);
bufferspace = req->req.length - req->req.actual;
/* read all bytes from this packet */
if (likely (udccs & UDCCS_BO_RNE)) {
count = 1 + (0x0ff & *ep->reg_ubcr);
req->req.actual += min (count, bufferspace);
} else /* zlp */
count = 0;
is_short = (count < ep->ep.maxpacket);
DBG(DBG_VERY_NOISY, "read %s %02x, %d bytes%s req %p %d/%d\n",
ep->ep.name, udccs, count,
is_short ? "/S" : "",
req, req->req.actual, req->req.length);
while (likely (count-- != 0)) {
u8 byte = (u8) *ep->reg_uddr;
if (unlikely (bufferspace == 0)) {
/* this happens when the driver's buffer
* is smaller than what the host sent.
* discard the extra data.
*/
if (req->req.status != -EOVERFLOW)
DMSG("%s overflow %d\n",
ep->ep.name, count);
req->req.status = -EOVERFLOW;
} else {
*buf++ = byte;
bufferspace--;
}
}
*ep->reg_udccs = UDCCS_BO_RPC;
/* RPC/RSP/RNE could now reflect the other packet buffer */
/* iso is one request per packet */
if (ep->bmAttributes == USB_ENDPOINT_XFER_ISOC) {
if (udccs & UDCCS_IO_ROF)
req->req.status = -EHOSTUNREACH;
/* more like "is_done" */
is_short = 1;
}
/* completion */
if (is_short || req->req.actual == req->req.length) {
done (ep, req, 0);
if (list_empty(&ep->queue))
pio_irq_disable (ep->bEndpointAddress);
return 1;
}
/* finished that packet. the next one may be waiting... */
}
return 0;
}
/*
* special ep0 version of the above. no UBCR0 or double buffering; status
* handshaking is magic. most device protocols don't need control-OUT.
* CDC vendor commands (and RNDIS), mass storage CB/CBI, and some other
* protocols do use them.
*/
static int
read_ep0_fifo (struct pxa25x_ep *ep, struct pxa25x_request *req)
{
u8 *buf, byte;
unsigned bufferspace;
buf = req->req.buf + req->req.actual;
bufferspace = req->req.length - req->req.actual;
while (UDCCS0 & UDCCS0_RNE) {
byte = (u8) UDDR0;
if (unlikely (bufferspace == 0)) {
/* this happens when the driver's buffer
* is smaller than what the host sent.
* discard the extra data.
*/
if (req->req.status != -EOVERFLOW)
DMSG("%s overflow\n", ep->ep.name);
req->req.status = -EOVERFLOW;
} else {
*buf++ = byte;
req->req.actual++;
bufferspace--;
}
}
UDCCS0 = UDCCS0_OPR | UDCCS0_IPR;
/* completion */
if (req->req.actual >= req->req.length)
return 1;
/* finished that packet. the next one may be waiting... */
return 0;
}
/*-------------------------------------------------------------------------*/
static int
pxa25x_ep_queue(struct usb_ep *_ep, struct usb_request *_req, gfp_t gfp_flags)
{
struct pxa25x_request *req;
struct pxa25x_ep *ep;
struct pxa25x_udc *dev;
unsigned long flags;
req = container_of(_req, struct pxa25x_request, req);
if (unlikely (!_req || !_req->complete || !_req->buf
|| !list_empty(&req->queue))) {
DMSG("%s, bad params\n", __func__);
return -EINVAL;
}
ep = container_of(_ep, struct pxa25x_ep, ep);
if (unlikely (!_ep || (!ep->desc && ep->ep.name != ep0name))) {
DMSG("%s, bad ep\n", __func__);
return -EINVAL;
}
dev = ep->dev;
if (unlikely (!dev->driver
|| dev->gadget.speed == USB_SPEED_UNKNOWN)) {
DMSG("%s, bogus device state\n", __func__);
return -ESHUTDOWN;
}
/* iso is always one packet per request, that's the only way
* we can report per-packet status. that also helps with dma.
*/
if (unlikely (ep->bmAttributes == USB_ENDPOINT_XFER_ISOC
&& req->req.length > le16_to_cpu
(ep->desc->wMaxPacketSize)))
return -EMSGSIZE;
DBG(DBG_NOISY, "%s queue req %p, len %d buf %p\n",
_ep->name, _req, _req->length, _req->buf);
local_irq_save(flags);
_req->status = -EINPROGRESS;
_req->actual = 0;
/* kickstart this i/o queue? */
if (list_empty(&ep->queue) && !ep->stopped) {
if (ep->desc == NULL/* ep0 */) {
unsigned length = _req->length;
switch (dev->ep0state) {
case EP0_IN_DATA_PHASE:
dev->stats.write.ops++;
if (write_ep0_fifo(ep, req))
req = NULL;
break;
case EP0_OUT_DATA_PHASE:
dev->stats.read.ops++;
/* messy ... */
if (dev->req_config) {
DBG(DBG_VERBOSE, "ep0 config ack%s\n",
dev->has_cfr ? "" : " raced");
if (dev->has_cfr)
UDCCFR = UDCCFR_AREN|UDCCFR_ACM
|UDCCFR_MB1;
done(ep, req, 0);
dev->ep0state = EP0_END_XFER;
local_irq_restore (flags);
return 0;
}
if (dev->req_pending)
ep0start(dev, UDCCS0_IPR, "OUT");
if (length == 0 || ((UDCCS0 & UDCCS0_RNE) != 0
&& read_ep0_fifo(ep, req))) {
ep0_idle(dev);
done(ep, req, 0);
req = NULL;
}
break;
default:
DMSG("ep0 i/o, odd state %d\n", dev->ep0state);
local_irq_restore (flags);
return -EL2HLT;
}
/* can the FIFO can satisfy the request immediately? */
} else if ((ep->bEndpointAddress & USB_DIR_IN) != 0) {
if ((*ep->reg_udccs & UDCCS_BI_TFS) != 0
&& write_fifo(ep, req))
req = NULL;
} else if ((*ep->reg_udccs & UDCCS_BO_RFS) != 0
&& read_fifo(ep, req)) {
req = NULL;
}
if (likely (req && ep->desc))
pio_irq_enable(ep->bEndpointAddress);
}
/* pio or dma irq handler advances the queue. */
if (likely(req != NULL))
list_add_tail(&req->queue, &ep->queue);
local_irq_restore(flags);
return 0;
}
/*
* nuke - dequeue ALL requests
*/
static void nuke(struct pxa25x_ep *ep, int status)
{
struct pxa25x_request *req;
/* called with irqs blocked */
while (!list_empty(&ep->queue)) {
req = list_entry(ep->queue.next,
struct pxa25x_request,
queue);
done(ep, req, status);
}
if (ep->desc)
pio_irq_disable (ep->bEndpointAddress);
}
/* dequeue JUST ONE request */
static int pxa25x_ep_dequeue(struct usb_ep *_ep, struct usb_request *_req)
{
struct pxa25x_ep *ep;
struct pxa25x_request *req;
unsigned long flags;
ep = container_of(_ep, struct pxa25x_ep, ep);
if (!_ep || ep->ep.name == ep0name)
return -EINVAL;
local_irq_save(flags);
/* make sure it's actually queued on this endpoint */
list_for_each_entry (req, &ep->queue, queue) {
if (&req->req == _req)
break;
}
if (&req->req != _req) {
local_irq_restore(flags);
return -EINVAL;
}
done(ep, req, -ECONNRESET);
local_irq_restore(flags);
return 0;
}
/*-------------------------------------------------------------------------*/
static int pxa25x_ep_set_halt(struct usb_ep *_ep, int value)
{
struct pxa25x_ep *ep;
unsigned long flags;
ep = container_of(_ep, struct pxa25x_ep, ep);
if (unlikely (!_ep
|| (!ep->desc && ep->ep.name != ep0name))
|| ep->bmAttributes == USB_ENDPOINT_XFER_ISOC) {
DMSG("%s, bad ep\n", __func__);
return -EINVAL;
}
if (value == 0) {
/* this path (reset toggle+halt) is needed to implement
* SET_INTERFACE on normal hardware. but it can't be
* done from software on the PXA UDC, and the hardware
* forgets to do it as part of SET_INTERFACE automagic.
*/
DMSG("only host can clear %s halt\n", _ep->name);
return -EROFS;
}
local_irq_save(flags);
if ((ep->bEndpointAddress & USB_DIR_IN) != 0
&& ((*ep->reg_udccs & UDCCS_BI_TFS) == 0
|| !list_empty(&ep->queue))) {
local_irq_restore(flags);
return -EAGAIN;
}
/* FST bit is the same for control, bulk in, bulk out, interrupt in */
*ep->reg_udccs = UDCCS_BI_FST|UDCCS_BI_FTF;
/* ep0 needs special care */
if (!ep->desc) {
start_watchdog(ep->dev);
ep->dev->req_pending = 0;
ep->dev->ep0state = EP0_STALL;
/* and bulk/intr endpoints like dropping stalls too */
} else {
unsigned i;
for (i = 0; i < 1000; i += 20) {
if (*ep->reg_udccs & UDCCS_BI_SST)
break;
udelay(20);
}
}
local_irq_restore(flags);
DBG(DBG_VERBOSE, "%s halt\n", _ep->name);
return 0;
}
static int pxa25x_ep_fifo_status(struct usb_ep *_ep)
{
struct pxa25x_ep *ep;
ep = container_of(_ep, struct pxa25x_ep, ep);
if (!_ep) {
DMSG("%s, bad ep\n", __func__);
return -ENODEV;
}
/* pxa can't report unclaimed bytes from IN fifos */
if ((ep->bEndpointAddress & USB_DIR_IN) != 0)
return -EOPNOTSUPP;
if (ep->dev->gadget.speed == USB_SPEED_UNKNOWN
|| (*ep->reg_udccs & UDCCS_BO_RFS) == 0)
return 0;
else
return (*ep->reg_ubcr & 0xfff) + 1;
}
static void pxa25x_ep_fifo_flush(struct usb_ep *_ep)
{
struct pxa25x_ep *ep;
ep = container_of(_ep, struct pxa25x_ep, ep);
if (!_ep || ep->ep.name == ep0name || !list_empty(&ep->queue)) {
DMSG("%s, bad ep\n", __func__);
return;
}
/* toggle and halt bits stay unchanged */
/* for OUT, just read and discard the FIFO contents. */
if ((ep->bEndpointAddress & USB_DIR_IN) == 0) {
while (((*ep->reg_udccs) & UDCCS_BO_RNE) != 0)
(void) *ep->reg_uddr;
return;
}
/* most IN status is the same, but ISO can't stall */
*ep->reg_udccs = UDCCS_BI_TPC|UDCCS_BI_FTF|UDCCS_BI_TUR
| (ep->bmAttributes == USB_ENDPOINT_XFER_ISOC
? 0 : UDCCS_BI_SST);
}
static struct usb_ep_ops pxa25x_ep_ops = {
.enable = pxa25x_ep_enable,
.disable = pxa25x_ep_disable,
.alloc_request = pxa25x_ep_alloc_request,
.free_request = pxa25x_ep_free_request,
.queue = pxa25x_ep_queue,
.dequeue = pxa25x_ep_dequeue,
.set_halt = pxa25x_ep_set_halt,
.fifo_status = pxa25x_ep_fifo_status,
.fifo_flush = pxa25x_ep_fifo_flush,
};
/* ---------------------------------------------------------------------------
* device-scoped parts of the api to the usb controller hardware
* ---------------------------------------------------------------------------
*/
static int pxa25x_udc_get_frame(struct usb_gadget *_gadget)
{
return ((UFNRH & 0x07) << 8) | (UFNRL & 0xff);
}
static int pxa25x_udc_wakeup(struct usb_gadget *_gadget)
{
/* host may not have enabled remote wakeup */
if ((UDCCS0 & UDCCS0_DRWF) == 0)
return -EHOSTUNREACH;
udc_set_mask_UDCCR(UDCCR_RSM);
return 0;
}
static void stop_activity(struct pxa25x_udc *, struct usb_gadget_driver *);
static void udc_enable (struct pxa25x_udc *);
static void udc_disable(struct pxa25x_udc *);
/* We disable the UDC -- and its 48 MHz clock -- whenever it's not
* in active use.
*/
static int pullup(struct pxa25x_udc *udc)
{
int is_active = udc->vbus && udc->pullup && !udc->suspended;
DMSG("%s\n", is_active ? "active" : "inactive");
if (is_active) {
if (!udc->active) {
udc->active = 1;
/* Enable clock for USB device */
clk_enable(udc->clk);
udc_enable(udc);
}
} else {
if (udc->active) {
if (udc->gadget.speed != USB_SPEED_UNKNOWN) {
DMSG("disconnect %s\n", udc->driver
? udc->driver->driver.name
: "(no driver)");
stop_activity(udc, udc->driver);
}
udc_disable(udc);
/* Disable clock for USB device */
clk_disable(udc->clk);
udc->active = 0;
}
}
return 0;
}
/* VBUS reporting logically comes from a transceiver */
static int pxa25x_udc_vbus_session(struct usb_gadget *_gadget, int is_active)
{
struct pxa25x_udc *udc;
udc = container_of(_gadget, struct pxa25x_udc, gadget);
udc->vbus = is_active;
DMSG("vbus %s\n", is_active ? "supplied" : "inactive");
pullup(udc);
return 0;
}
/* drivers may have software control over D+ pullup */
static int pxa25x_udc_pullup(struct usb_gadget *_gadget, int is_active)
{
struct pxa25x_udc *udc;
udc = container_of(_gadget, struct pxa25x_udc, gadget);
/* not all boards support pullup control */
if (!gpio_is_valid(udc->mach->gpio_pullup) && !udc->mach->udc_command)
return -EOPNOTSUPP;
udc->pullup = (is_active != 0);
pullup(udc);
return 0;
}
/* boards may consume current from VBUS, up to 100-500mA based on config.
* the 500uA suspend ceiling means that exclusively vbus-powered PXA designs
* violate USB specs.
*/
static int pxa25x_udc_vbus_draw(struct usb_gadget *_gadget, unsigned mA)
{
struct pxa25x_udc *udc;
udc = container_of(_gadget, struct pxa25x_udc, gadget);
if (udc->transceiver)
return otg_set_power(udc->transceiver, mA);
return -EOPNOTSUPP;
}
static int pxa25x_start(struct usb_gadget_driver *driver,
int (*bind)(struct usb_gadget *));
static int pxa25x_stop(struct usb_gadget_driver *driver);
static const struct usb_gadget_ops pxa25x_udc_ops = {
.get_frame = pxa25x_udc_get_frame,
.wakeup = pxa25x_udc_wakeup,
.vbus_session = pxa25x_udc_vbus_session,
.pullup = pxa25x_udc_pullup,
.vbus_draw = pxa25x_udc_vbus_draw,
.start = pxa25x_start,
.stop = pxa25x_stop,
};
/*-------------------------------------------------------------------------*/
#ifdef CONFIG_USB_GADGET_DEBUG_FS
static int
udc_seq_show(struct seq_file *m, void *_d)
{
struct pxa25x_udc *dev = m->private;
unsigned long flags;
int i;
u32 tmp;
local_irq_save(flags);
/* basic device status */
seq_printf(m, DRIVER_DESC "\n"
"%s version: %s\nGadget driver: %s\nHost %s\n\n",
driver_name, DRIVER_VERSION SIZE_STR "(pio)",
dev->driver ? dev->driver->driver.name : "(none)",
dev->gadget.speed == USB_SPEED_FULL ? "full speed" : "disconnected");
/* registers for device and ep0 */
seq_printf(m,
"uicr %02X.%02X, usir %02X.%02x, ufnr %02X.%02X\n",
UICR1, UICR0, USIR1, USIR0, UFNRH, UFNRL);
tmp = UDCCR;
seq_printf(m,
"udccr %02X =%s%s%s%s%s%s%s%s\n", tmp,
(tmp & UDCCR_REM) ? " rem" : "",
(tmp & UDCCR_RSTIR) ? " rstir" : "",
(tmp & UDCCR_SRM) ? " srm" : "",
(tmp & UDCCR_SUSIR) ? " susir" : "",
(tmp & UDCCR_RESIR) ? " resir" : "",
(tmp & UDCCR_RSM) ? " rsm" : "",
(tmp & UDCCR_UDA) ? " uda" : "",
(tmp & UDCCR_UDE) ? " ude" : "");
tmp = UDCCS0;
seq_printf(m,
"udccs0 %02X =%s%s%s%s%s%s%s%s\n", tmp,
(tmp & UDCCS0_SA) ? " sa" : "",
(tmp & UDCCS0_RNE) ? " rne" : "",
(tmp & UDCCS0_FST) ? " fst" : "",
(tmp & UDCCS0_SST) ? " sst" : "",
(tmp & UDCCS0_DRWF) ? " dwrf" : "",
(tmp & UDCCS0_FTF) ? " ftf" : "",
(tmp & UDCCS0_IPR) ? " ipr" : "",
(tmp & UDCCS0_OPR) ? " opr" : "");
if (dev->has_cfr) {
tmp = UDCCFR;
seq_printf(m,
"udccfr %02X =%s%s\n", tmp,
(tmp & UDCCFR_AREN) ? " aren" : "",
(tmp & UDCCFR_ACM) ? " acm" : "");
}
if (dev->gadget.speed != USB_SPEED_FULL || !dev->driver)
goto done;
seq_printf(m, "ep0 IN %lu/%lu, OUT %lu/%lu\nirqs %lu\n\n",
dev->stats.write.bytes, dev->stats.write.ops,
dev->stats.read.bytes, dev->stats.read.ops,
dev->stats.irqs);
/* dump endpoint queues */
for (i = 0; i < PXA_UDC_NUM_ENDPOINTS; i++) {
struct pxa25x_ep *ep = &dev->ep [i];
struct pxa25x_request *req;
if (i != 0) {
const struct usb_endpoint_descriptor *desc;
desc = ep->desc;
if (!desc)
continue;
tmp = *dev->ep [i].reg_udccs;
seq_printf(m,
"%s max %d %s udccs %02x irqs %lu\n",
ep->ep.name, le16_to_cpu(desc->wMaxPacketSize),
"pio", tmp, ep->pio_irqs);
/* TODO translate all five groups of udccs bits! */
} else /* ep0 should only have one transfer queued */
seq_printf(m, "ep0 max 16 pio irqs %lu\n",
ep->pio_irqs);
if (list_empty(&ep->queue)) {
seq_printf(m, "\t(nothing queued)\n");
continue;
}
list_for_each_entry(req, &ep->queue, queue) {
seq_printf(m,
"\treq %p len %d/%d buf %p\n",
&req->req, req->req.actual,
req->req.length, req->req.buf);
}
}
done:
local_irq_restore(flags);
return 0;
}
static int
udc_debugfs_open(struct inode *inode, struct file *file)
{
return single_open(file, udc_seq_show, inode->i_private);
}
static const struct file_operations debug_fops = {
.open = udc_debugfs_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
#define create_debug_files(dev) \
do { \
dev->debugfs_udc = debugfs_create_file(dev->gadget.name, \
S_IRUGO, NULL, dev, &debug_fops); \
} while (0)
#define remove_debug_files(dev) \
do { \
if (dev->debugfs_udc) \
debugfs_remove(dev->debugfs_udc); \
} while (0)
#else /* !CONFIG_USB_GADGET_DEBUG_FILES */
#define create_debug_files(dev) do {} while (0)
#define remove_debug_files(dev) do {} while (0)
#endif /* CONFIG_USB_GADGET_DEBUG_FILES */
/*-------------------------------------------------------------------------*/
/*
* udc_disable - disable USB device controller
*/
static void udc_disable(struct pxa25x_udc *dev)
{
/* block all irqs */
udc_set_mask_UDCCR(UDCCR_SRM|UDCCR_REM);
UICR0 = UICR1 = 0xff;
UFNRH = UFNRH_SIM;
/* if hardware supports it, disconnect from usb */
pullup_off();
udc_clear_mask_UDCCR(UDCCR_UDE);
ep0_idle (dev);
dev->gadget.speed = USB_SPEED_UNKNOWN;
}
/*
* udc_reinit - initialize software state
*/
static void udc_reinit(struct pxa25x_udc *dev)
{
u32 i;
/* device/ep0 records init */
INIT_LIST_HEAD (&dev->gadget.ep_list);
INIT_LIST_HEAD (&dev->gadget.ep0->ep_list);
dev->ep0state = EP0_IDLE;
/* basic endpoint records init */
for (i = 0; i < PXA_UDC_NUM_ENDPOINTS; i++) {
struct pxa25x_ep *ep = &dev->ep[i];
if (i != 0)
list_add_tail (&ep->ep.ep_list, &dev->gadget.ep_list);
ep->desc = NULL;
ep->stopped = 0;
INIT_LIST_HEAD (&ep->queue);
ep->pio_irqs = 0;
}
/* the rest was statically initialized, and is read-only */
}
/* until it's enabled, this UDC should be completely invisible
* to any USB host.
*/
static void udc_enable (struct pxa25x_udc *dev)
{
udc_clear_mask_UDCCR(UDCCR_UDE);
/* try to clear these bits before we enable the udc */
udc_ack_int_UDCCR(UDCCR_SUSIR|/*UDCCR_RSTIR|*/UDCCR_RESIR);
ep0_idle(dev);
dev->gadget.speed = USB_SPEED_UNKNOWN;
dev->stats.irqs = 0;
/*
* sequence taken from chapter 12.5.10, PXA250 AppProcDevManual:
* - enable UDC
* - if RESET is already in progress, ack interrupt
* - unmask reset interrupt
*/
udc_set_mask_UDCCR(UDCCR_UDE);
if (!(UDCCR & UDCCR_UDA))
udc_ack_int_UDCCR(UDCCR_RSTIR);
if (dev->has_cfr /* UDC_RES2 is defined */) {
/* pxa255 (a0+) can avoid a set_config race that could
* prevent gadget drivers from configuring correctly
*/
UDCCFR = UDCCFR_ACM | UDCCFR_MB1;
} else {
/* "USB test mode" for pxa250 errata 40-42 (stepping a0, a1)
* which could result in missing packets and interrupts.
* supposedly one bit per endpoint, controlling whether it
* double buffers or not; ACM/AREN bits fit into the holes.
* zero bits (like USIR0_IRx) disable double buffering.
*/
UDC_RES1 = 0x00;
UDC_RES2 = 0x00;
}
/* enable suspend/resume and reset irqs */
udc_clear_mask_UDCCR(UDCCR_SRM | UDCCR_REM);
/* enable ep0 irqs */
UICR0 &= ~UICR0_IM0;
/* if hardware supports it, pullup D+ and wait for reset */
pullup_on();
}
/* when a driver is successfully registered, it will receive
* control requests including set_configuration(), which enables
* non-control requests. then usb traffic follows until a
* disconnect is reported. then a host may connect again, or
* the driver might get unbound.
*/
static int pxa25x_start(struct usb_gadget_driver *driver,
int (*bind)(struct usb_gadget *))
{
struct pxa25x_udc *dev = the_controller;
int retval;
if (!driver
|| driver->speed < USB_SPEED_FULL
|| !bind
|| !driver->disconnect
|| !driver->setup)
return -EINVAL;
if (!dev)
return -ENODEV;
if (dev->driver)
return -EBUSY;
/* first hook up the driver ... */
dev->driver = driver;
dev->gadget.dev.driver = &driver->driver;
dev->pullup = 1;
retval = device_add (&dev->gadget.dev);
if (retval) {
fail:
dev->driver = NULL;
dev->gadget.dev.driver = NULL;
return retval;
}
retval = bind(&dev->gadget);
if (retval) {
DMSG("bind to driver %s --> error %d\n",
driver->driver.name, retval);
device_del (&dev->gadget.dev);
goto fail;
}
/* ... then enable host detection and ep0; and we're ready
* for set_configuration as well as eventual disconnect.
*/
DMSG("registered gadget driver '%s'\n", driver->driver.name);
/* connect to bus through transceiver */
if (dev->transceiver) {
retval = otg_set_peripheral(dev->transceiver, &dev->gadget);
if (retval) {
DMSG("can't bind to transceiver\n");
if (driver->unbind)
driver->unbind(&dev->gadget);
goto bind_fail;
}
}
pullup(dev);
dump_state(dev);
return 0;
bind_fail:
return retval;
}
static void
stop_activity(struct pxa25x_udc *dev, struct usb_gadget_driver *driver)
{
int i;
/* don't disconnect drivers more than once */
if (dev->gadget.speed == USB_SPEED_UNKNOWN)
driver = NULL;
dev->gadget.speed = USB_SPEED_UNKNOWN;
/* prevent new request submissions, kill any outstanding requests */
for (i = 0; i < PXA_UDC_NUM_ENDPOINTS; i++) {
struct pxa25x_ep *ep = &dev->ep[i];
ep->stopped = 1;
nuke(ep, -ESHUTDOWN);
}
del_timer_sync(&dev->timer);
/* report disconnect; the driver is already quiesced */
if (driver)
driver->disconnect(&dev->gadget);
/* re-init driver-visible data structures */
udc_reinit(dev);
}
static int pxa25x_stop(struct usb_gadget_driver *driver)
{
struct pxa25x_udc *dev = the_controller;
if (!dev)
return -ENODEV;
if (!driver || driver != dev->driver || !driver->unbind)
return -EINVAL;
local_irq_disable();
dev->pullup = 0;
pullup(dev);
stop_activity(dev, driver);
local_irq_enable();
if (dev->transceiver)
(void) otg_set_peripheral(dev->transceiver, NULL);
driver->unbind(&dev->gadget);
dev->gadget.dev.driver = NULL;
dev->driver = NULL;
device_del (&dev->gadget.dev);
DMSG("unregistered gadget driver '%s'\n", driver->driver.name);
dump_state(dev);
return 0;
}
/*-------------------------------------------------------------------------*/
#ifdef CONFIG_ARCH_LUBBOCK
/* Lubbock has separate connect and disconnect irqs. More typical designs
* use one GPIO as the VBUS IRQ, and another to control the D+ pullup.
*/
static irqreturn_t
lubbock_vbus_irq(int irq, void *_dev)
{
struct pxa25x_udc *dev = _dev;
int vbus;
dev->stats.irqs++;
switch (irq) {
case LUBBOCK_USB_IRQ:
vbus = 1;
disable_irq(LUBBOCK_USB_IRQ);
enable_irq(LUBBOCK_USB_DISC_IRQ);
break;
case LUBBOCK_USB_DISC_IRQ:
vbus = 0;
disable_irq(LUBBOCK_USB_DISC_IRQ);
enable_irq(LUBBOCK_USB_IRQ);
break;
default:
return IRQ_NONE;
}
pxa25x_udc_vbus_session(&dev->gadget, vbus);
return IRQ_HANDLED;
}
#endif
/*-------------------------------------------------------------------------*/
static inline void clear_ep_state (struct pxa25x_udc *dev)
{
unsigned i;
/* hardware SET_{CONFIGURATION,INTERFACE} automagic resets endpoint
* fifos, and pending transactions mustn't be continued in any case.
*/
for (i = 1; i < PXA_UDC_NUM_ENDPOINTS; i++)
nuke(&dev->ep[i], -ECONNABORTED);
}
static void udc_watchdog(unsigned long _dev)
{
struct pxa25x_udc *dev = (void *)_dev;
local_irq_disable();
if (dev->ep0state == EP0_STALL
&& (UDCCS0 & UDCCS0_FST) == 0
&& (UDCCS0 & UDCCS0_SST) == 0) {
UDCCS0 = UDCCS0_FST|UDCCS0_FTF;
DBG(DBG_VERBOSE, "ep0 re-stall\n");
start_watchdog(dev);
}
local_irq_enable();
}
static void handle_ep0 (struct pxa25x_udc *dev)
{
u32 udccs0 = UDCCS0;
struct pxa25x_ep *ep = &dev->ep [0];
struct pxa25x_request *req;
union {
struct usb_ctrlrequest r;
u8 raw [8];
u32 word [2];
} u;
if (list_empty(&ep->queue))
req = NULL;
else
req = list_entry(ep->queue.next, struct pxa25x_request, queue);
/* clear stall status */
if (udccs0 & UDCCS0_SST) {
nuke(ep, -EPIPE);
UDCCS0 = UDCCS0_SST;
del_timer(&dev->timer);
ep0_idle(dev);
}
/* previous request unfinished? non-error iff back-to-back ... */
if ((udccs0 & UDCCS0_SA) != 0 && dev->ep0state != EP0_IDLE) {
nuke(ep, 0);
del_timer(&dev->timer);
ep0_idle(dev);
}
switch (dev->ep0state) {
case EP0_IDLE:
/* late-breaking status? */
udccs0 = UDCCS0;
/* start control request? */
if (likely((udccs0 & (UDCCS0_OPR|UDCCS0_SA|UDCCS0_RNE))
== (UDCCS0_OPR|UDCCS0_SA|UDCCS0_RNE))) {
int i;
nuke (ep, -EPROTO);
/* read SETUP packet */
for (i = 0; i < 8; i++) {
if (unlikely(!(UDCCS0 & UDCCS0_RNE))) {
bad_setup:
DMSG("SETUP %d!\n", i);
goto stall;
}
u.raw [i] = (u8) UDDR0;
}
if (unlikely((UDCCS0 & UDCCS0_RNE) != 0))
goto bad_setup;
got_setup:
DBG(DBG_VERBOSE, "SETUP %02x.%02x v%04x i%04x l%04x\n",
u.r.bRequestType, u.r.bRequest,
le16_to_cpu(u.r.wValue),
le16_to_cpu(u.r.wIndex),
le16_to_cpu(u.r.wLength));
/* cope with automagic for some standard requests. */
dev->req_std = (u.r.bRequestType & USB_TYPE_MASK)
== USB_TYPE_STANDARD;
dev->req_config = 0;
dev->req_pending = 1;
switch (u.r.bRequest) {
/* hardware restricts gadget drivers here! */
case USB_REQ_SET_CONFIGURATION:
if (u.r.bRequestType == USB_RECIP_DEVICE) {
/* reflect hardware's automagic
* up to the gadget driver.
*/
config_change:
dev->req_config = 1;
clear_ep_state(dev);
/* if !has_cfr, there's no synch
* else use AREN (later) not SA|OPR
* USIR0_IR0 acts edge sensitive
*/
}
break;
/* ... and here, even more ... */
case USB_REQ_SET_INTERFACE:
if (u.r.bRequestType == USB_RECIP_INTERFACE) {
/* udc hardware is broken by design:
* - altsetting may only be zero;
* - hw resets all interfaces' eps;
* - ep reset doesn't include halt(?).
*/
DMSG("broken set_interface (%d/%d)\n",
le16_to_cpu(u.r.wIndex),
le16_to_cpu(u.r.wValue));
goto config_change;
}
break;
/* hardware was supposed to hide this */
case USB_REQ_SET_ADDRESS:
if (u.r.bRequestType == USB_RECIP_DEVICE) {
ep0start(dev, 0, "address");
return;
}
break;
}
if (u.r.bRequestType & USB_DIR_IN)
dev->ep0state = EP0_IN_DATA_PHASE;
else
dev->ep0state = EP0_OUT_DATA_PHASE;
i = dev->driver->setup(&dev->gadget, &u.r);
if (i < 0) {
/* hardware automagic preventing STALL... */
if (dev->req_config) {
/* hardware sometimes neglects to tell
* tell us about config change events,
* so later ones may fail...
*/
WARNING("config change %02x fail %d?\n",
u.r.bRequest, i);
return;
/* TODO experiment: if has_cfr,
* hardware didn't ACK; maybe we
* could actually STALL!
*/
}
DBG(DBG_VERBOSE, "protocol STALL, "
"%02x err %d\n", UDCCS0, i);
stall:
/* the watchdog timer helps deal with cases
* where udc seems to clear FST wrongly, and
* then NAKs instead of STALLing.
*/
ep0start(dev, UDCCS0_FST|UDCCS0_FTF, "stall");
start_watchdog(dev);
dev->ep0state = EP0_STALL;
/* deferred i/o == no response yet */
} else if (dev->req_pending) {
if (likely(dev->ep0state == EP0_IN_DATA_PHASE
|| dev->req_std || u.r.wLength))
ep0start(dev, 0, "defer");
else
ep0start(dev, UDCCS0_IPR, "defer/IPR");
}
/* expect at least one data or status stage irq */
return;
} else if (likely((udccs0 & (UDCCS0_OPR|UDCCS0_SA))
== (UDCCS0_OPR|UDCCS0_SA))) {
unsigned i;
/* pxa210/250 erratum 131 for B0/B1 says RNE lies.
* still observed on a pxa255 a0.
*/
DBG(DBG_VERBOSE, "e131\n");
nuke(ep, -EPROTO);
/* read SETUP data, but don't trust it too much */
for (i = 0; i < 8; i++)
u.raw [i] = (u8) UDDR0;
if ((u.r.bRequestType & USB_RECIP_MASK)
> USB_RECIP_OTHER)
goto stall;
if (u.word [0] == 0 && u.word [1] == 0)
goto stall;
goto got_setup;
} else {
/* some random early IRQ:
* - we acked FST
* - IPR cleared
* - OPR got set, without SA (likely status stage)
*/
UDCCS0 = udccs0 & (UDCCS0_SA|UDCCS0_OPR);
}
break;
case EP0_IN_DATA_PHASE: /* GET_DESCRIPTOR etc */
if (udccs0 & UDCCS0_OPR) {
UDCCS0 = UDCCS0_OPR|UDCCS0_FTF;
DBG(DBG_VERBOSE, "ep0in premature status\n");
if (req)
done(ep, req, 0);
ep0_idle(dev);
} else /* irq was IPR clearing */ {
if (req) {
/* this IN packet might finish the request */
(void) write_ep0_fifo(ep, req);
} /* else IN token before response was written */
}
break;
case EP0_OUT_DATA_PHASE: /* SET_DESCRIPTOR etc */
if (udccs0 & UDCCS0_OPR) {
if (req) {
/* this OUT packet might finish the request */
if (read_ep0_fifo(ep, req))
done(ep, req, 0);
/* else more OUT packets expected */
} /* else OUT token before read was issued */
} else /* irq was IPR clearing */ {
DBG(DBG_VERBOSE, "ep0out premature status\n");
if (req)
done(ep, req, 0);
ep0_idle(dev);
}
break;
case EP0_END_XFER:
if (req)
done(ep, req, 0);
/* ack control-IN status (maybe in-zlp was skipped)
* also appears after some config change events.
*/
if (udccs0 & UDCCS0_OPR)
UDCCS0 = UDCCS0_OPR;
ep0_idle(dev);
break;
case EP0_STALL:
UDCCS0 = UDCCS0_FST;
break;
}
USIR0 = USIR0_IR0;
}
static void handle_ep(struct pxa25x_ep *ep)
{
struct pxa25x_request *req;
int is_in = ep->bEndpointAddress & USB_DIR_IN;
int completed;
u32 udccs, tmp;
do {
completed = 0;
if (likely (!list_empty(&ep->queue)))
req = list_entry(ep->queue.next,
struct pxa25x_request, queue);
else
req = NULL;
// TODO check FST handling
udccs = *ep->reg_udccs;
if (unlikely(is_in)) { /* irq from TPC, SST, or (ISO) TUR */
tmp = UDCCS_BI_TUR;
if (likely(ep->bmAttributes == USB_ENDPOINT_XFER_BULK))
tmp |= UDCCS_BI_SST;
tmp &= udccs;
if (likely (tmp))
*ep->reg_udccs = tmp;
if (req && likely ((udccs & UDCCS_BI_TFS) != 0))
completed = write_fifo(ep, req);
} else { /* irq from RPC (or for ISO, ROF) */
if (likely(ep->bmAttributes == USB_ENDPOINT_XFER_BULK))
tmp = UDCCS_BO_SST | UDCCS_BO_DME;
else
tmp = UDCCS_IO_ROF | UDCCS_IO_DME;
tmp &= udccs;
if (likely(tmp))
*ep->reg_udccs = tmp;
/* fifos can hold packets, ready for reading... */
if (likely(req)) {
completed = read_fifo(ep, req);
} else
pio_irq_disable (ep->bEndpointAddress);
}
ep->pio_irqs++;
} while (completed);
}
/*
* pxa25x_udc_irq - interrupt handler
*
* avoid delays in ep0 processing. the control handshaking isn't always
* under software control (pxa250c0 and the pxa255 are better), and delays
* could cause usb protocol errors.
*/
static irqreturn_t
pxa25x_udc_irq(int irq, void *_dev)
{
struct pxa25x_udc *dev = _dev;
int handled;
dev->stats.irqs++;
do {
u32 udccr = UDCCR;
handled = 0;
/* SUSpend Interrupt Request */
if (unlikely(udccr & UDCCR_SUSIR)) {
udc_ack_int_UDCCR(UDCCR_SUSIR);
handled = 1;
DBG(DBG_VERBOSE, "USB suspend\n");
if (dev->gadget.speed != USB_SPEED_UNKNOWN
&& dev->driver
&& dev->driver->suspend)
dev->driver->suspend(&dev->gadget);
ep0_idle (dev);
}
/* RESume Interrupt Request */
if (unlikely(udccr & UDCCR_RESIR)) {
udc_ack_int_UDCCR(UDCCR_RESIR);
handled = 1;
DBG(DBG_VERBOSE, "USB resume\n");
if (dev->gadget.speed != USB_SPEED_UNKNOWN
&& dev->driver
&& dev->driver->resume)
dev->driver->resume(&dev->gadget);
}
/* ReSeT Interrupt Request - USB reset */
if (unlikely(udccr & UDCCR_RSTIR)) {
udc_ack_int_UDCCR(UDCCR_RSTIR);
handled = 1;
if ((UDCCR & UDCCR_UDA) == 0) {
DBG(DBG_VERBOSE, "USB reset start\n");
/* reset driver and endpoints,
* in case that's not yet done
*/
stop_activity (dev, dev->driver);
} else {
DBG(DBG_VERBOSE, "USB reset end\n");
dev->gadget.speed = USB_SPEED_FULL;
memset(&dev->stats, 0, sizeof dev->stats);
/* driver and endpoints are still reset */
}
} else {
u32 usir0 = USIR0 & ~UICR0;
u32 usir1 = USIR1 & ~UICR1;
int i;
if (unlikely (!usir0 && !usir1))
continue;
DBG(DBG_VERY_NOISY, "irq %02x.%02x\n", usir1, usir0);
/* control traffic */
if (usir0 & USIR0_IR0) {
dev->ep[0].pio_irqs++;
handle_ep0(dev);
handled = 1;
}
/* endpoint data transfers */
for (i = 0; i < 8; i++) {
u32 tmp = 1 << i;
if (i && (usir0 & tmp)) {
handle_ep(&dev->ep[i]);
USIR0 |= tmp;
handled = 1;
}
#ifndef CONFIG_USB_PXA25X_SMALL
if (usir1 & tmp) {
handle_ep(&dev->ep[i+8]);
USIR1 |= tmp;
handled = 1;
}
#endif
}
}
/* we could also ask for 1 msec SOF (SIR) interrupts */
} while (handled);
return IRQ_HANDLED;
}
/*-------------------------------------------------------------------------*/
static void nop_release (struct device *dev)
{
DMSG("%s %s\n", __func__, dev_name(dev));
}
/* this uses load-time allocation and initialization (instead of
* doing it at run-time) to save code, eliminate fault paths, and
* be more obviously correct.
*/
static struct pxa25x_udc memory = {
.gadget = {
.ops = &pxa25x_udc_ops,
.ep0 = &memory.ep[0].ep,
.name = driver_name,
.dev = {
.init_name = "gadget",
.release = nop_release,
},
},
/* control endpoint */
.ep[0] = {
.ep = {
.name = ep0name,
.ops = &pxa25x_ep_ops,
.maxpacket = EP0_FIFO_SIZE,
},
.dev = &memory,
.reg_udccs = &UDCCS0,
.reg_uddr = &UDDR0,
},
/* first group of endpoints */
.ep[1] = {
.ep = {
.name = "ep1in-bulk",
.ops = &pxa25x_ep_ops,
.maxpacket = BULK_FIFO_SIZE,
},
.dev = &memory,
.fifo_size = BULK_FIFO_SIZE,
.bEndpointAddress = USB_DIR_IN | 1,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.reg_udccs = &UDCCS1,
.reg_uddr = &UDDR1,
},
.ep[2] = {
.ep = {
.name = "ep2out-bulk",
.ops = &pxa25x_ep_ops,
.maxpacket = BULK_FIFO_SIZE,
},
.dev = &memory,
.fifo_size = BULK_FIFO_SIZE,
.bEndpointAddress = 2,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.reg_udccs = &UDCCS2,
.reg_ubcr = &UBCR2,
.reg_uddr = &UDDR2,
},
#ifndef CONFIG_USB_PXA25X_SMALL
.ep[3] = {
.ep = {
.name = "ep3in-iso",
.ops = &pxa25x_ep_ops,
.maxpacket = ISO_FIFO_SIZE,
},
.dev = &memory,
.fifo_size = ISO_FIFO_SIZE,
.bEndpointAddress = USB_DIR_IN | 3,
.bmAttributes = USB_ENDPOINT_XFER_ISOC,
.reg_udccs = &UDCCS3,
.reg_uddr = &UDDR3,
},
.ep[4] = {
.ep = {
.name = "ep4out-iso",
.ops = &pxa25x_ep_ops,
.maxpacket = ISO_FIFO_SIZE,
},
.dev = &memory,
.fifo_size = ISO_FIFO_SIZE,
.bEndpointAddress = 4,
.bmAttributes = USB_ENDPOINT_XFER_ISOC,
.reg_udccs = &UDCCS4,
.reg_ubcr = &UBCR4,
.reg_uddr = &UDDR4,
},
.ep[5] = {
.ep = {
.name = "ep5in-int",
.ops = &pxa25x_ep_ops,
.maxpacket = INT_FIFO_SIZE,
},
.dev = &memory,
.fifo_size = INT_FIFO_SIZE,
.bEndpointAddress = USB_DIR_IN | 5,
.bmAttributes = USB_ENDPOINT_XFER_INT,
.reg_udccs = &UDCCS5,
.reg_uddr = &UDDR5,
},
/* second group of endpoints */
.ep[6] = {
.ep = {
.name = "ep6in-bulk",
.ops = &pxa25x_ep_ops,
.maxpacket = BULK_FIFO_SIZE,
},
.dev = &memory,
.fifo_size = BULK_FIFO_SIZE,
.bEndpointAddress = USB_DIR_IN | 6,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.reg_udccs = &UDCCS6,
.reg_uddr = &UDDR6,
},
.ep[7] = {
.ep = {
.name = "ep7out-bulk",
.ops = &pxa25x_ep_ops,
.maxpacket = BULK_FIFO_SIZE,
},
.dev = &memory,
.fifo_size = BULK_FIFO_SIZE,
.bEndpointAddress = 7,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.reg_udccs = &UDCCS7,
.reg_ubcr = &UBCR7,
.reg_uddr = &UDDR7,
},
.ep[8] = {
.ep = {
.name = "ep8in-iso",
.ops = &pxa25x_ep_ops,
.maxpacket = ISO_FIFO_SIZE,
},
.dev = &memory,
.fifo_size = ISO_FIFO_SIZE,
.bEndpointAddress = USB_DIR_IN | 8,
.bmAttributes = USB_ENDPOINT_XFER_ISOC,
.reg_udccs = &UDCCS8,
.reg_uddr = &UDDR8,
},
.ep[9] = {
.ep = {
.name = "ep9out-iso",
.ops = &pxa25x_ep_ops,
.maxpacket = ISO_FIFO_SIZE,
},
.dev = &memory,
.fifo_size = ISO_FIFO_SIZE,
.bEndpointAddress = 9,
.bmAttributes = USB_ENDPOINT_XFER_ISOC,
.reg_udccs = &UDCCS9,
.reg_ubcr = &UBCR9,
.reg_uddr = &UDDR9,
},
.ep[10] = {
.ep = {
.name = "ep10in-int",
.ops = &pxa25x_ep_ops,
.maxpacket = INT_FIFO_SIZE,
},
.dev = &memory,
.fifo_size = INT_FIFO_SIZE,
.bEndpointAddress = USB_DIR_IN | 10,
.bmAttributes = USB_ENDPOINT_XFER_INT,
.reg_udccs = &UDCCS10,
.reg_uddr = &UDDR10,
},
/* third group of endpoints */
.ep[11] = {
.ep = {
.name = "ep11in-bulk",
.ops = &pxa25x_ep_ops,
.maxpacket = BULK_FIFO_SIZE,
},
.dev = &memory,
.fifo_size = BULK_FIFO_SIZE,
.bEndpointAddress = USB_DIR_IN | 11,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.reg_udccs = &UDCCS11,
.reg_uddr = &UDDR11,
},
.ep[12] = {
.ep = {
.name = "ep12out-bulk",
.ops = &pxa25x_ep_ops,
.maxpacket = BULK_FIFO_SIZE,
},
.dev = &memory,
.fifo_size = BULK_FIFO_SIZE,
.bEndpointAddress = 12,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.reg_udccs = &UDCCS12,
.reg_ubcr = &UBCR12,
.reg_uddr = &UDDR12,
},
.ep[13] = {
.ep = {
.name = "ep13in-iso",
.ops = &pxa25x_ep_ops,
.maxpacket = ISO_FIFO_SIZE,
},
.dev = &memory,
.fifo_size = ISO_FIFO_SIZE,
.bEndpointAddress = USB_DIR_IN | 13,
.bmAttributes = USB_ENDPOINT_XFER_ISOC,
.reg_udccs = &UDCCS13,
.reg_uddr = &UDDR13,
},
.ep[14] = {
.ep = {
.name = "ep14out-iso",
.ops = &pxa25x_ep_ops,
.maxpacket = ISO_FIFO_SIZE,
},
.dev = &memory,
.fifo_size = ISO_FIFO_SIZE,
.bEndpointAddress = 14,
.bmAttributes = USB_ENDPOINT_XFER_ISOC,
.reg_udccs = &UDCCS14,
.reg_ubcr = &UBCR14,
.reg_uddr = &UDDR14,
},
.ep[15] = {
.ep = {
.name = "ep15in-int",
.ops = &pxa25x_ep_ops,
.maxpacket = INT_FIFO_SIZE,
},
.dev = &memory,
.fifo_size = INT_FIFO_SIZE,
.bEndpointAddress = USB_DIR_IN | 15,
.bmAttributes = USB_ENDPOINT_XFER_INT,
.reg_udccs = &UDCCS15,
.reg_uddr = &UDDR15,
},
#endif /* !CONFIG_USB_PXA25X_SMALL */
};
#define CP15R0_VENDOR_MASK 0xffffe000
#if defined(CONFIG_ARCH_PXA)
#define CP15R0_XSCALE_VALUE 0x69052000 /* intel/arm/xscale */
#elif defined(CONFIG_ARCH_IXP4XX)
#define CP15R0_XSCALE_VALUE 0x69054000 /* intel/arm/ixp4xx */
#endif
#define CP15R0_PROD_MASK 0x000003f0
#define PXA25x 0x00000100 /* and PXA26x */
#define PXA210 0x00000120
#define CP15R0_REV_MASK 0x0000000f
#define CP15R0_PRODREV_MASK (CP15R0_PROD_MASK | CP15R0_REV_MASK)
#define PXA255_A0 0x00000106 /* or PXA260_B1 */
#define PXA250_C0 0x00000105 /* or PXA26x_B0 */
#define PXA250_B2 0x00000104
#define PXA250_B1 0x00000103 /* or PXA260_A0 */
#define PXA250_B0 0x00000102
#define PXA250_A1 0x00000101
#define PXA250_A0 0x00000100
#define PXA210_C0 0x00000125
#define PXA210_B2 0x00000124
#define PXA210_B1 0x00000123
#define PXA210_B0 0x00000122
#define IXP425_A0 0x000001c1
#define IXP425_B0 0x000001f1
#define IXP465_AD 0x00000200
/*
* probe - binds to the platform device
*/
static int __init pxa25x_udc_probe(struct platform_device *pdev)
{
struct pxa25x_udc *dev = &memory;
int retval, irq;
u32 chiprev;
/* insist on Intel/ARM/XScale */
asm("mrc%? p15, 0, %0, c0, c0" : "=r" (chiprev));
if ((chiprev & CP15R0_VENDOR_MASK) != CP15R0_XSCALE_VALUE) {
pr_err("%s: not XScale!\n", driver_name);
return -ENODEV;
}
/* trigger chiprev-specific logic */
switch (chiprev & CP15R0_PRODREV_MASK) {
#if defined(CONFIG_ARCH_PXA)
case PXA255_A0:
dev->has_cfr = 1;
break;
case PXA250_A0:
case PXA250_A1:
/* A0/A1 "not released"; ep 13, 15 unusable */
/* fall through */
case PXA250_B2: case PXA210_B2:
case PXA250_B1: case PXA210_B1:
case PXA250_B0: case PXA210_B0:
/* OUT-DMA is broken ... */
/* fall through */
case PXA250_C0: case PXA210_C0:
break;
#elif defined(CONFIG_ARCH_IXP4XX)
case IXP425_A0:
case IXP425_B0:
case IXP465_AD:
dev->has_cfr = 1;
break;
#endif
default:
pr_err("%s: unrecognized processor: %08x\n",
driver_name, chiprev);
/* iop3xx, ixp4xx, ... */
return -ENODEV;
}
irq = platform_get_irq(pdev, 0);
if (irq < 0)
return -ENODEV;
dev->clk = clk_get(&pdev->dev, NULL);
if (IS_ERR(dev->clk)) {
retval = PTR_ERR(dev->clk);
goto err_clk;
}
pr_debug("%s: IRQ %d%s%s\n", driver_name, irq,
dev->has_cfr ? "" : " (!cfr)",
SIZE_STR "(pio)"
);
/* other non-static parts of init */
dev->dev = &pdev->dev;
dev->mach = pdev->dev.platform_data;
dev->transceiver = otg_get_transceiver();
if (gpio_is_valid(dev->mach->gpio_pullup)) {
if ((retval = gpio_request(dev->mach->gpio_pullup,
"pca25x_udc GPIO PULLUP"))) {
dev_dbg(&pdev->dev,
"can't get pullup gpio %d, err: %d\n",
dev->mach->gpio_pullup, retval);
goto err_gpio_pullup;
}
gpio_direction_output(dev->mach->gpio_pullup, 0);
}
init_timer(&dev->timer);
dev->timer.function = udc_watchdog;
dev->timer.data = (unsigned long) dev;
device_initialize(&dev->gadget.dev);
dev->gadget.dev.parent = &pdev->dev;
dev->gadget.dev.dma_mask = pdev->dev.dma_mask;
the_controller = dev;
platform_set_drvdata(pdev, dev);
udc_disable(dev);
udc_reinit(dev);
dev->vbus = 0;
/* irq setup after old hardware state is cleaned up */
retval = request_irq(irq, pxa25x_udc_irq,
IRQF_DISABLED, driver_name, dev);
if (retval != 0) {
pr_err("%s: can't get irq %d, err %d\n",
driver_name, irq, retval);
goto err_irq1;
}
dev->got_irq = 1;
#ifdef CONFIG_ARCH_LUBBOCK
if (machine_is_lubbock()) {
retval = request_irq(LUBBOCK_USB_DISC_IRQ,
lubbock_vbus_irq,
IRQF_DISABLED | IRQF_SAMPLE_RANDOM,
driver_name, dev);
if (retval != 0) {
pr_err("%s: can't get irq %i, err %d\n",
driver_name, LUBBOCK_USB_DISC_IRQ, retval);
goto err_irq_lub;
}
retval = request_irq(LUBBOCK_USB_IRQ,
lubbock_vbus_irq,
IRQF_DISABLED | IRQF_SAMPLE_RANDOM,
driver_name, dev);
if (retval != 0) {
pr_err("%s: can't get irq %i, err %d\n",
driver_name, LUBBOCK_USB_IRQ, retval);
goto lubbock_fail0;
}
} else
#endif
create_debug_files(dev);
retval = usb_add_gadget_udc(&pdev->dev, &dev->gadget);
if (!retval)
return retval;
remove_debug_files(dev);
#ifdef CONFIG_ARCH_LUBBOCK
lubbock_fail0:
free_irq(LUBBOCK_USB_DISC_IRQ, dev);
err_irq_lub:
free_irq(irq, dev);
#endif
err_irq1:
if (gpio_is_valid(dev->mach->gpio_pullup))
gpio_free(dev->mach->gpio_pullup);
err_gpio_pullup:
if (dev->transceiver) {
otg_put_transceiver(dev->transceiver);
dev->transceiver = NULL;
}
clk_put(dev->clk);
err_clk:
return retval;
}
static void pxa25x_udc_shutdown(struct platform_device *_dev)
{
pullup_off();
}
static int __exit pxa25x_udc_remove(struct platform_device *pdev)
{
struct pxa25x_udc *dev = platform_get_drvdata(pdev);
usb_del_gadget_udc(&dev->gadget);
if (dev->driver)
return -EBUSY;
dev->pullup = 0;
pullup(dev);
remove_debug_files(dev);
if (dev->got_irq) {
free_irq(platform_get_irq(pdev, 0), dev);
dev->got_irq = 0;
}
#ifdef CONFIG_ARCH_LUBBOCK
if (machine_is_lubbock()) {
free_irq(LUBBOCK_USB_DISC_IRQ, dev);
free_irq(LUBBOCK_USB_IRQ, dev);
}
#endif
if (gpio_is_valid(dev->mach->gpio_pullup))
gpio_free(dev->mach->gpio_pullup);
clk_put(dev->clk);
if (dev->transceiver) {
otg_put_transceiver(dev->transceiver);
dev->transceiver = NULL;
}
platform_set_drvdata(pdev, NULL);
the_controller = NULL;
return 0;
}
/*-------------------------------------------------------------------------*/
#ifdef CONFIG_PM
/* USB suspend (controlled by the host) and system suspend (controlled
* by the PXA) don't necessarily work well together. If USB is active,
* the 48 MHz clock is required; so the system can't enter 33 MHz idle
* mode, or any deeper PM saving state.
*
* For now, we punt and forcibly disconnect from the USB host when PXA
* enters any suspend state. While we're disconnected, we always disable
* the 48MHz USB clock ... allowing PXA sleep and/or 33 MHz idle states.
* Boards without software pullup control shouldn't use those states.
* VBUS IRQs should probably be ignored so that the PXA device just acts
* "dead" to USB hosts until system resume.
*/
static int pxa25x_udc_suspend(struct platform_device *dev, pm_message_t state)
{
struct pxa25x_udc *udc = platform_get_drvdata(dev);
unsigned long flags;
if (!gpio_is_valid(udc->mach->gpio_pullup) && !udc->mach->udc_command)
WARNING("USB host won't detect disconnect!\n");
udc->suspended = 1;
local_irq_save(flags);
pullup(udc);
local_irq_restore(flags);
return 0;
}
static int pxa25x_udc_resume(struct platform_device *dev)
{
struct pxa25x_udc *udc = platform_get_drvdata(dev);
unsigned long flags;
udc->suspended = 0;
local_irq_save(flags);
pullup(udc);
local_irq_restore(flags);
return 0;
}
#else
#define pxa25x_udc_suspend NULL
#define pxa25x_udc_resume NULL
#endif
/*-------------------------------------------------------------------------*/
static struct platform_driver udc_driver = {
.shutdown = pxa25x_udc_shutdown,
.remove = __exit_p(pxa25x_udc_remove),
.suspend = pxa25x_udc_suspend,
.resume = pxa25x_udc_resume,
.driver = {
.owner = THIS_MODULE,
.name = "pxa25x-udc",
},
};
static int __init udc_init(void)
{
pr_info("%s: version %s\n", driver_name, DRIVER_VERSION);
return platform_driver_probe(&udc_driver, pxa25x_udc_probe);
}
module_init(udc_init);
static void __exit udc_exit(void)
{
platform_driver_unregister(&udc_driver);
}
module_exit(udc_exit);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_AUTHOR("Frank Becker, Robert Schwebel, David Brownell");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:pxa25x-udc");
| gpl-2.0 |
Bdaman80/BDA-Lexikon | arch/x86/crypto/aesni-intel_glue.c | 935 | 22816 | /*
* Support for Intel AES-NI instructions. This file contains glue
* code, the real AES implementation is in intel-aes_asm.S.
*
* Copyright (C) 2008, Intel Corp.
* Author: Huang Ying <ying.huang@intel.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <linux/hardirq.h>
#include <linux/types.h>
#include <linux/crypto.h>
#include <linux/err.h>
#include <crypto/algapi.h>
#include <crypto/aes.h>
#include <crypto/cryptd.h>
#include <crypto/ctr.h>
#include <asm/i387.h>
#include <asm/aes.h>
#if defined(CONFIG_CRYPTO_CTR) || defined(CONFIG_CRYPTO_CTR_MODULE)
#define HAS_CTR
#endif
#if defined(CONFIG_CRYPTO_LRW) || defined(CONFIG_CRYPTO_LRW_MODULE)
#define HAS_LRW
#endif
#if defined(CONFIG_CRYPTO_PCBC) || defined(CONFIG_CRYPTO_PCBC_MODULE)
#define HAS_PCBC
#endif
#if defined(CONFIG_CRYPTO_XTS) || defined(CONFIG_CRYPTO_XTS_MODULE)
#define HAS_XTS
#endif
struct async_aes_ctx {
struct cryptd_ablkcipher *cryptd_tfm;
};
#define AESNI_ALIGN 16
#define AES_BLOCK_MASK (~(AES_BLOCK_SIZE-1))
asmlinkage int aesni_set_key(struct crypto_aes_ctx *ctx, const u8 *in_key,
unsigned int key_len);
asmlinkage void aesni_enc(struct crypto_aes_ctx *ctx, u8 *out,
const u8 *in);
asmlinkage void aesni_dec(struct crypto_aes_ctx *ctx, u8 *out,
const u8 *in);
asmlinkage void aesni_ecb_enc(struct crypto_aes_ctx *ctx, u8 *out,
const u8 *in, unsigned int len);
asmlinkage void aesni_ecb_dec(struct crypto_aes_ctx *ctx, u8 *out,
const u8 *in, unsigned int len);
asmlinkage void aesni_cbc_enc(struct crypto_aes_ctx *ctx, u8 *out,
const u8 *in, unsigned int len, u8 *iv);
asmlinkage void aesni_cbc_dec(struct crypto_aes_ctx *ctx, u8 *out,
const u8 *in, unsigned int len, u8 *iv);
asmlinkage void aesni_ctr_enc(struct crypto_aes_ctx *ctx, u8 *out,
const u8 *in, unsigned int len, u8 *iv);
static inline struct crypto_aes_ctx *aes_ctx(void *raw_ctx)
{
unsigned long addr = (unsigned long)raw_ctx;
unsigned long align = AESNI_ALIGN;
if (align <= crypto_tfm_ctx_alignment())
align = 1;
return (struct crypto_aes_ctx *)ALIGN(addr, align);
}
static int aes_set_key_common(struct crypto_tfm *tfm, void *raw_ctx,
const u8 *in_key, unsigned int key_len)
{
struct crypto_aes_ctx *ctx = aes_ctx(raw_ctx);
u32 *flags = &tfm->crt_flags;
int err;
if (key_len != AES_KEYSIZE_128 && key_len != AES_KEYSIZE_192 &&
key_len != AES_KEYSIZE_256) {
*flags |= CRYPTO_TFM_RES_BAD_KEY_LEN;
return -EINVAL;
}
if (!irq_fpu_usable())
err = crypto_aes_expand_key(ctx, in_key, key_len);
else {
kernel_fpu_begin();
err = aesni_set_key(ctx, in_key, key_len);
kernel_fpu_end();
}
return err;
}
static int aes_set_key(struct crypto_tfm *tfm, const u8 *in_key,
unsigned int key_len)
{
return aes_set_key_common(tfm, crypto_tfm_ctx(tfm), in_key, key_len);
}
static void aes_encrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src)
{
struct crypto_aes_ctx *ctx = aes_ctx(crypto_tfm_ctx(tfm));
if (!irq_fpu_usable())
crypto_aes_encrypt_x86(ctx, dst, src);
else {
kernel_fpu_begin();
aesni_enc(ctx, dst, src);
kernel_fpu_end();
}
}
static void aes_decrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src)
{
struct crypto_aes_ctx *ctx = aes_ctx(crypto_tfm_ctx(tfm));
if (!irq_fpu_usable())
crypto_aes_decrypt_x86(ctx, dst, src);
else {
kernel_fpu_begin();
aesni_dec(ctx, dst, src);
kernel_fpu_end();
}
}
static struct crypto_alg aesni_alg = {
.cra_name = "aes",
.cra_driver_name = "aes-aesni",
.cra_priority = 300,
.cra_flags = CRYPTO_ALG_TYPE_CIPHER,
.cra_blocksize = AES_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct crypto_aes_ctx)+AESNI_ALIGN-1,
.cra_alignmask = 0,
.cra_module = THIS_MODULE,
.cra_list = LIST_HEAD_INIT(aesni_alg.cra_list),
.cra_u = {
.cipher = {
.cia_min_keysize = AES_MIN_KEY_SIZE,
.cia_max_keysize = AES_MAX_KEY_SIZE,
.cia_setkey = aes_set_key,
.cia_encrypt = aes_encrypt,
.cia_decrypt = aes_decrypt
}
}
};
static void __aes_encrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src)
{
struct crypto_aes_ctx *ctx = aes_ctx(crypto_tfm_ctx(tfm));
aesni_enc(ctx, dst, src);
}
static void __aes_decrypt(struct crypto_tfm *tfm, u8 *dst, const u8 *src)
{
struct crypto_aes_ctx *ctx = aes_ctx(crypto_tfm_ctx(tfm));
aesni_dec(ctx, dst, src);
}
static struct crypto_alg __aesni_alg = {
.cra_name = "__aes-aesni",
.cra_driver_name = "__driver-aes-aesni",
.cra_priority = 0,
.cra_flags = CRYPTO_ALG_TYPE_CIPHER,
.cra_blocksize = AES_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct crypto_aes_ctx)+AESNI_ALIGN-1,
.cra_alignmask = 0,
.cra_module = THIS_MODULE,
.cra_list = LIST_HEAD_INIT(__aesni_alg.cra_list),
.cra_u = {
.cipher = {
.cia_min_keysize = AES_MIN_KEY_SIZE,
.cia_max_keysize = AES_MAX_KEY_SIZE,
.cia_setkey = aes_set_key,
.cia_encrypt = __aes_encrypt,
.cia_decrypt = __aes_decrypt
}
}
};
static int ecb_encrypt(struct blkcipher_desc *desc,
struct scatterlist *dst, struct scatterlist *src,
unsigned int nbytes)
{
struct crypto_aes_ctx *ctx = aes_ctx(crypto_blkcipher_ctx(desc->tfm));
struct blkcipher_walk walk;
int err;
blkcipher_walk_init(&walk, dst, src, nbytes);
err = blkcipher_walk_virt(desc, &walk);
desc->flags &= ~CRYPTO_TFM_REQ_MAY_SLEEP;
kernel_fpu_begin();
while ((nbytes = walk.nbytes)) {
aesni_ecb_enc(ctx, walk.dst.virt.addr, walk.src.virt.addr,
nbytes & AES_BLOCK_MASK);
nbytes &= AES_BLOCK_SIZE - 1;
err = blkcipher_walk_done(desc, &walk, nbytes);
}
kernel_fpu_end();
return err;
}
static int ecb_decrypt(struct blkcipher_desc *desc,
struct scatterlist *dst, struct scatterlist *src,
unsigned int nbytes)
{
struct crypto_aes_ctx *ctx = aes_ctx(crypto_blkcipher_ctx(desc->tfm));
struct blkcipher_walk walk;
int err;
blkcipher_walk_init(&walk, dst, src, nbytes);
err = blkcipher_walk_virt(desc, &walk);
desc->flags &= ~CRYPTO_TFM_REQ_MAY_SLEEP;
kernel_fpu_begin();
while ((nbytes = walk.nbytes)) {
aesni_ecb_dec(ctx, walk.dst.virt.addr, walk.src.virt.addr,
nbytes & AES_BLOCK_MASK);
nbytes &= AES_BLOCK_SIZE - 1;
err = blkcipher_walk_done(desc, &walk, nbytes);
}
kernel_fpu_end();
return err;
}
static struct crypto_alg blk_ecb_alg = {
.cra_name = "__ecb-aes-aesni",
.cra_driver_name = "__driver-ecb-aes-aesni",
.cra_priority = 0,
.cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER,
.cra_blocksize = AES_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct crypto_aes_ctx)+AESNI_ALIGN-1,
.cra_alignmask = 0,
.cra_type = &crypto_blkcipher_type,
.cra_module = THIS_MODULE,
.cra_list = LIST_HEAD_INIT(blk_ecb_alg.cra_list),
.cra_u = {
.blkcipher = {
.min_keysize = AES_MIN_KEY_SIZE,
.max_keysize = AES_MAX_KEY_SIZE,
.setkey = aes_set_key,
.encrypt = ecb_encrypt,
.decrypt = ecb_decrypt,
},
},
};
static int cbc_encrypt(struct blkcipher_desc *desc,
struct scatterlist *dst, struct scatterlist *src,
unsigned int nbytes)
{
struct crypto_aes_ctx *ctx = aes_ctx(crypto_blkcipher_ctx(desc->tfm));
struct blkcipher_walk walk;
int err;
blkcipher_walk_init(&walk, dst, src, nbytes);
err = blkcipher_walk_virt(desc, &walk);
desc->flags &= ~CRYPTO_TFM_REQ_MAY_SLEEP;
kernel_fpu_begin();
while ((nbytes = walk.nbytes)) {
aesni_cbc_enc(ctx, walk.dst.virt.addr, walk.src.virt.addr,
nbytes & AES_BLOCK_MASK, walk.iv);
nbytes &= AES_BLOCK_SIZE - 1;
err = blkcipher_walk_done(desc, &walk, nbytes);
}
kernel_fpu_end();
return err;
}
static int cbc_decrypt(struct blkcipher_desc *desc,
struct scatterlist *dst, struct scatterlist *src,
unsigned int nbytes)
{
struct crypto_aes_ctx *ctx = aes_ctx(crypto_blkcipher_ctx(desc->tfm));
struct blkcipher_walk walk;
int err;
blkcipher_walk_init(&walk, dst, src, nbytes);
err = blkcipher_walk_virt(desc, &walk);
desc->flags &= ~CRYPTO_TFM_REQ_MAY_SLEEP;
kernel_fpu_begin();
while ((nbytes = walk.nbytes)) {
aesni_cbc_dec(ctx, walk.dst.virt.addr, walk.src.virt.addr,
nbytes & AES_BLOCK_MASK, walk.iv);
nbytes &= AES_BLOCK_SIZE - 1;
err = blkcipher_walk_done(desc, &walk, nbytes);
}
kernel_fpu_end();
return err;
}
static struct crypto_alg blk_cbc_alg = {
.cra_name = "__cbc-aes-aesni",
.cra_driver_name = "__driver-cbc-aes-aesni",
.cra_priority = 0,
.cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER,
.cra_blocksize = AES_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct crypto_aes_ctx)+AESNI_ALIGN-1,
.cra_alignmask = 0,
.cra_type = &crypto_blkcipher_type,
.cra_module = THIS_MODULE,
.cra_list = LIST_HEAD_INIT(blk_cbc_alg.cra_list),
.cra_u = {
.blkcipher = {
.min_keysize = AES_MIN_KEY_SIZE,
.max_keysize = AES_MAX_KEY_SIZE,
.setkey = aes_set_key,
.encrypt = cbc_encrypt,
.decrypt = cbc_decrypt,
},
},
};
static void ctr_crypt_final(struct crypto_aes_ctx *ctx,
struct blkcipher_walk *walk)
{
u8 *ctrblk = walk->iv;
u8 keystream[AES_BLOCK_SIZE];
u8 *src = walk->src.virt.addr;
u8 *dst = walk->dst.virt.addr;
unsigned int nbytes = walk->nbytes;
aesni_enc(ctx, keystream, ctrblk);
crypto_xor(keystream, src, nbytes);
memcpy(dst, keystream, nbytes);
crypto_inc(ctrblk, AES_BLOCK_SIZE);
}
static int ctr_crypt(struct blkcipher_desc *desc,
struct scatterlist *dst, struct scatterlist *src,
unsigned int nbytes)
{
struct crypto_aes_ctx *ctx = aes_ctx(crypto_blkcipher_ctx(desc->tfm));
struct blkcipher_walk walk;
int err;
blkcipher_walk_init(&walk, dst, src, nbytes);
err = blkcipher_walk_virt_block(desc, &walk, AES_BLOCK_SIZE);
desc->flags &= ~CRYPTO_TFM_REQ_MAY_SLEEP;
kernel_fpu_begin();
while ((nbytes = walk.nbytes) >= AES_BLOCK_SIZE) {
aesni_ctr_enc(ctx, walk.dst.virt.addr, walk.src.virt.addr,
nbytes & AES_BLOCK_MASK, walk.iv);
nbytes &= AES_BLOCK_SIZE - 1;
err = blkcipher_walk_done(desc, &walk, nbytes);
}
if (walk.nbytes) {
ctr_crypt_final(ctx, &walk);
err = blkcipher_walk_done(desc, &walk, 0);
}
kernel_fpu_end();
return err;
}
static struct crypto_alg blk_ctr_alg = {
.cra_name = "__ctr-aes-aesni",
.cra_driver_name = "__driver-ctr-aes-aesni",
.cra_priority = 0,
.cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER,
.cra_blocksize = 1,
.cra_ctxsize = sizeof(struct crypto_aes_ctx)+AESNI_ALIGN-1,
.cra_alignmask = 0,
.cra_type = &crypto_blkcipher_type,
.cra_module = THIS_MODULE,
.cra_list = LIST_HEAD_INIT(blk_ctr_alg.cra_list),
.cra_u = {
.blkcipher = {
.min_keysize = AES_MIN_KEY_SIZE,
.max_keysize = AES_MAX_KEY_SIZE,
.ivsize = AES_BLOCK_SIZE,
.setkey = aes_set_key,
.encrypt = ctr_crypt,
.decrypt = ctr_crypt,
},
},
};
static int ablk_set_key(struct crypto_ablkcipher *tfm, const u8 *key,
unsigned int key_len)
{
struct async_aes_ctx *ctx = crypto_ablkcipher_ctx(tfm);
struct crypto_ablkcipher *child = &ctx->cryptd_tfm->base;
int err;
crypto_ablkcipher_clear_flags(child, CRYPTO_TFM_REQ_MASK);
crypto_ablkcipher_set_flags(child, crypto_ablkcipher_get_flags(tfm)
& CRYPTO_TFM_REQ_MASK);
err = crypto_ablkcipher_setkey(child, key, key_len);
crypto_ablkcipher_set_flags(tfm, crypto_ablkcipher_get_flags(child)
& CRYPTO_TFM_RES_MASK);
return err;
}
static int ablk_encrypt(struct ablkcipher_request *req)
{
struct crypto_ablkcipher *tfm = crypto_ablkcipher_reqtfm(req);
struct async_aes_ctx *ctx = crypto_ablkcipher_ctx(tfm);
if (!irq_fpu_usable()) {
struct ablkcipher_request *cryptd_req =
ablkcipher_request_ctx(req);
memcpy(cryptd_req, req, sizeof(*req));
ablkcipher_request_set_tfm(cryptd_req, &ctx->cryptd_tfm->base);
return crypto_ablkcipher_encrypt(cryptd_req);
} else {
struct blkcipher_desc desc;
desc.tfm = cryptd_ablkcipher_child(ctx->cryptd_tfm);
desc.info = req->info;
desc.flags = 0;
return crypto_blkcipher_crt(desc.tfm)->encrypt(
&desc, req->dst, req->src, req->nbytes);
}
}
static int ablk_decrypt(struct ablkcipher_request *req)
{
struct crypto_ablkcipher *tfm = crypto_ablkcipher_reqtfm(req);
struct async_aes_ctx *ctx = crypto_ablkcipher_ctx(tfm);
if (!irq_fpu_usable()) {
struct ablkcipher_request *cryptd_req =
ablkcipher_request_ctx(req);
memcpy(cryptd_req, req, sizeof(*req));
ablkcipher_request_set_tfm(cryptd_req, &ctx->cryptd_tfm->base);
return crypto_ablkcipher_decrypt(cryptd_req);
} else {
struct blkcipher_desc desc;
desc.tfm = cryptd_ablkcipher_child(ctx->cryptd_tfm);
desc.info = req->info;
desc.flags = 0;
return crypto_blkcipher_crt(desc.tfm)->decrypt(
&desc, req->dst, req->src, req->nbytes);
}
}
static void ablk_exit(struct crypto_tfm *tfm)
{
struct async_aes_ctx *ctx = crypto_tfm_ctx(tfm);
cryptd_free_ablkcipher(ctx->cryptd_tfm);
}
static void ablk_init_common(struct crypto_tfm *tfm,
struct cryptd_ablkcipher *cryptd_tfm)
{
struct async_aes_ctx *ctx = crypto_tfm_ctx(tfm);
ctx->cryptd_tfm = cryptd_tfm;
tfm->crt_ablkcipher.reqsize = sizeof(struct ablkcipher_request) +
crypto_ablkcipher_reqsize(&cryptd_tfm->base);
}
static int ablk_ecb_init(struct crypto_tfm *tfm)
{
struct cryptd_ablkcipher *cryptd_tfm;
cryptd_tfm = cryptd_alloc_ablkcipher("__driver-ecb-aes-aesni", 0, 0);
if (IS_ERR(cryptd_tfm))
return PTR_ERR(cryptd_tfm);
ablk_init_common(tfm, cryptd_tfm);
return 0;
}
static struct crypto_alg ablk_ecb_alg = {
.cra_name = "ecb(aes)",
.cra_driver_name = "ecb-aes-aesni",
.cra_priority = 400,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER|CRYPTO_ALG_ASYNC,
.cra_blocksize = AES_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct async_aes_ctx),
.cra_alignmask = 0,
.cra_type = &crypto_ablkcipher_type,
.cra_module = THIS_MODULE,
.cra_list = LIST_HEAD_INIT(ablk_ecb_alg.cra_list),
.cra_init = ablk_ecb_init,
.cra_exit = ablk_exit,
.cra_u = {
.ablkcipher = {
.min_keysize = AES_MIN_KEY_SIZE,
.max_keysize = AES_MAX_KEY_SIZE,
.setkey = ablk_set_key,
.encrypt = ablk_encrypt,
.decrypt = ablk_decrypt,
},
},
};
static int ablk_cbc_init(struct crypto_tfm *tfm)
{
struct cryptd_ablkcipher *cryptd_tfm;
cryptd_tfm = cryptd_alloc_ablkcipher("__driver-cbc-aes-aesni", 0, 0);
if (IS_ERR(cryptd_tfm))
return PTR_ERR(cryptd_tfm);
ablk_init_common(tfm, cryptd_tfm);
return 0;
}
static struct crypto_alg ablk_cbc_alg = {
.cra_name = "cbc(aes)",
.cra_driver_name = "cbc-aes-aesni",
.cra_priority = 400,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER|CRYPTO_ALG_ASYNC,
.cra_blocksize = AES_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct async_aes_ctx),
.cra_alignmask = 0,
.cra_type = &crypto_ablkcipher_type,
.cra_module = THIS_MODULE,
.cra_list = LIST_HEAD_INIT(ablk_cbc_alg.cra_list),
.cra_init = ablk_cbc_init,
.cra_exit = ablk_exit,
.cra_u = {
.ablkcipher = {
.min_keysize = AES_MIN_KEY_SIZE,
.max_keysize = AES_MAX_KEY_SIZE,
.ivsize = AES_BLOCK_SIZE,
.setkey = ablk_set_key,
.encrypt = ablk_encrypt,
.decrypt = ablk_decrypt,
},
},
};
static int ablk_ctr_init(struct crypto_tfm *tfm)
{
struct cryptd_ablkcipher *cryptd_tfm;
cryptd_tfm = cryptd_alloc_ablkcipher("__driver-ctr-aes-aesni", 0, 0);
if (IS_ERR(cryptd_tfm))
return PTR_ERR(cryptd_tfm);
ablk_init_common(tfm, cryptd_tfm);
return 0;
}
static struct crypto_alg ablk_ctr_alg = {
.cra_name = "ctr(aes)",
.cra_driver_name = "ctr-aes-aesni",
.cra_priority = 400,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER|CRYPTO_ALG_ASYNC,
.cra_blocksize = 1,
.cra_ctxsize = sizeof(struct async_aes_ctx),
.cra_alignmask = 0,
.cra_type = &crypto_ablkcipher_type,
.cra_module = THIS_MODULE,
.cra_list = LIST_HEAD_INIT(ablk_ctr_alg.cra_list),
.cra_init = ablk_ctr_init,
.cra_exit = ablk_exit,
.cra_u = {
.ablkcipher = {
.min_keysize = AES_MIN_KEY_SIZE,
.max_keysize = AES_MAX_KEY_SIZE,
.ivsize = AES_BLOCK_SIZE,
.setkey = ablk_set_key,
.encrypt = ablk_encrypt,
.decrypt = ablk_encrypt,
.geniv = "chainiv",
},
},
};
#ifdef HAS_CTR
static int ablk_rfc3686_ctr_init(struct crypto_tfm *tfm)
{
struct cryptd_ablkcipher *cryptd_tfm;
cryptd_tfm = cryptd_alloc_ablkcipher(
"rfc3686(__driver-ctr-aes-aesni)", 0, 0);
if (IS_ERR(cryptd_tfm))
return PTR_ERR(cryptd_tfm);
ablk_init_common(tfm, cryptd_tfm);
return 0;
}
static struct crypto_alg ablk_rfc3686_ctr_alg = {
.cra_name = "rfc3686(ctr(aes))",
.cra_driver_name = "rfc3686-ctr-aes-aesni",
.cra_priority = 400,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER|CRYPTO_ALG_ASYNC,
.cra_blocksize = 1,
.cra_ctxsize = sizeof(struct async_aes_ctx),
.cra_alignmask = 0,
.cra_type = &crypto_ablkcipher_type,
.cra_module = THIS_MODULE,
.cra_list = LIST_HEAD_INIT(ablk_rfc3686_ctr_alg.cra_list),
.cra_init = ablk_rfc3686_ctr_init,
.cra_exit = ablk_exit,
.cra_u = {
.ablkcipher = {
.min_keysize = AES_MIN_KEY_SIZE+CTR_RFC3686_NONCE_SIZE,
.max_keysize = AES_MAX_KEY_SIZE+CTR_RFC3686_NONCE_SIZE,
.ivsize = CTR_RFC3686_IV_SIZE,
.setkey = ablk_set_key,
.encrypt = ablk_encrypt,
.decrypt = ablk_decrypt,
.geniv = "seqiv",
},
},
};
#endif
#ifdef HAS_LRW
static int ablk_lrw_init(struct crypto_tfm *tfm)
{
struct cryptd_ablkcipher *cryptd_tfm;
cryptd_tfm = cryptd_alloc_ablkcipher("fpu(lrw(__driver-aes-aesni))",
0, 0);
if (IS_ERR(cryptd_tfm))
return PTR_ERR(cryptd_tfm);
ablk_init_common(tfm, cryptd_tfm);
return 0;
}
static struct crypto_alg ablk_lrw_alg = {
.cra_name = "lrw(aes)",
.cra_driver_name = "lrw-aes-aesni",
.cra_priority = 400,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER|CRYPTO_ALG_ASYNC,
.cra_blocksize = AES_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct async_aes_ctx),
.cra_alignmask = 0,
.cra_type = &crypto_ablkcipher_type,
.cra_module = THIS_MODULE,
.cra_list = LIST_HEAD_INIT(ablk_lrw_alg.cra_list),
.cra_init = ablk_lrw_init,
.cra_exit = ablk_exit,
.cra_u = {
.ablkcipher = {
.min_keysize = AES_MIN_KEY_SIZE + AES_BLOCK_SIZE,
.max_keysize = AES_MAX_KEY_SIZE + AES_BLOCK_SIZE,
.ivsize = AES_BLOCK_SIZE,
.setkey = ablk_set_key,
.encrypt = ablk_encrypt,
.decrypt = ablk_decrypt,
},
},
};
#endif
#ifdef HAS_PCBC
static int ablk_pcbc_init(struct crypto_tfm *tfm)
{
struct cryptd_ablkcipher *cryptd_tfm;
cryptd_tfm = cryptd_alloc_ablkcipher("fpu(pcbc(__driver-aes-aesni))",
0, 0);
if (IS_ERR(cryptd_tfm))
return PTR_ERR(cryptd_tfm);
ablk_init_common(tfm, cryptd_tfm);
return 0;
}
static struct crypto_alg ablk_pcbc_alg = {
.cra_name = "pcbc(aes)",
.cra_driver_name = "pcbc-aes-aesni",
.cra_priority = 400,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER|CRYPTO_ALG_ASYNC,
.cra_blocksize = AES_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct async_aes_ctx),
.cra_alignmask = 0,
.cra_type = &crypto_ablkcipher_type,
.cra_module = THIS_MODULE,
.cra_list = LIST_HEAD_INIT(ablk_pcbc_alg.cra_list),
.cra_init = ablk_pcbc_init,
.cra_exit = ablk_exit,
.cra_u = {
.ablkcipher = {
.min_keysize = AES_MIN_KEY_SIZE,
.max_keysize = AES_MAX_KEY_SIZE,
.ivsize = AES_BLOCK_SIZE,
.setkey = ablk_set_key,
.encrypt = ablk_encrypt,
.decrypt = ablk_decrypt,
},
},
};
#endif
#ifdef HAS_XTS
static int ablk_xts_init(struct crypto_tfm *tfm)
{
struct cryptd_ablkcipher *cryptd_tfm;
cryptd_tfm = cryptd_alloc_ablkcipher("fpu(xts(__driver-aes-aesni))",
0, 0);
if (IS_ERR(cryptd_tfm))
return PTR_ERR(cryptd_tfm);
ablk_init_common(tfm, cryptd_tfm);
return 0;
}
static struct crypto_alg ablk_xts_alg = {
.cra_name = "xts(aes)",
.cra_driver_name = "xts-aes-aesni",
.cra_priority = 400,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER|CRYPTO_ALG_ASYNC,
.cra_blocksize = AES_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct async_aes_ctx),
.cra_alignmask = 0,
.cra_type = &crypto_ablkcipher_type,
.cra_module = THIS_MODULE,
.cra_list = LIST_HEAD_INIT(ablk_xts_alg.cra_list),
.cra_init = ablk_xts_init,
.cra_exit = ablk_exit,
.cra_u = {
.ablkcipher = {
.min_keysize = 2 * AES_MIN_KEY_SIZE,
.max_keysize = 2 * AES_MAX_KEY_SIZE,
.ivsize = AES_BLOCK_SIZE,
.setkey = ablk_set_key,
.encrypt = ablk_encrypt,
.decrypt = ablk_decrypt,
},
},
};
#endif
static int __init aesni_init(void)
{
int err;
if (!cpu_has_aes) {
printk(KERN_INFO "Intel AES-NI instructions are not detected.\n");
return -ENODEV;
}
if ((err = crypto_register_alg(&aesni_alg)))
goto aes_err;
if ((err = crypto_register_alg(&__aesni_alg)))
goto __aes_err;
if ((err = crypto_register_alg(&blk_ecb_alg)))
goto blk_ecb_err;
if ((err = crypto_register_alg(&blk_cbc_alg)))
goto blk_cbc_err;
if ((err = crypto_register_alg(&blk_ctr_alg)))
goto blk_ctr_err;
if ((err = crypto_register_alg(&ablk_ecb_alg)))
goto ablk_ecb_err;
if ((err = crypto_register_alg(&ablk_cbc_alg)))
goto ablk_cbc_err;
if ((err = crypto_register_alg(&ablk_ctr_alg)))
goto ablk_ctr_err;
#ifdef HAS_CTR
if ((err = crypto_register_alg(&ablk_rfc3686_ctr_alg)))
goto ablk_rfc3686_ctr_err;
#endif
#ifdef HAS_LRW
if ((err = crypto_register_alg(&ablk_lrw_alg)))
goto ablk_lrw_err;
#endif
#ifdef HAS_PCBC
if ((err = crypto_register_alg(&ablk_pcbc_alg)))
goto ablk_pcbc_err;
#endif
#ifdef HAS_XTS
if ((err = crypto_register_alg(&ablk_xts_alg)))
goto ablk_xts_err;
#endif
return err;
#ifdef HAS_XTS
ablk_xts_err:
#endif
#ifdef HAS_PCBC
crypto_unregister_alg(&ablk_pcbc_alg);
ablk_pcbc_err:
#endif
#ifdef HAS_LRW
crypto_unregister_alg(&ablk_lrw_alg);
ablk_lrw_err:
#endif
#ifdef HAS_CTR
crypto_unregister_alg(&ablk_rfc3686_ctr_alg);
ablk_rfc3686_ctr_err:
#endif
crypto_unregister_alg(&ablk_ctr_alg);
ablk_ctr_err:
crypto_unregister_alg(&ablk_cbc_alg);
ablk_cbc_err:
crypto_unregister_alg(&ablk_ecb_alg);
ablk_ecb_err:
crypto_unregister_alg(&blk_ctr_alg);
blk_ctr_err:
crypto_unregister_alg(&blk_cbc_alg);
blk_cbc_err:
crypto_unregister_alg(&blk_ecb_alg);
blk_ecb_err:
crypto_unregister_alg(&__aesni_alg);
__aes_err:
crypto_unregister_alg(&aesni_alg);
aes_err:
return err;
}
static void __exit aesni_exit(void)
{
#ifdef HAS_XTS
crypto_unregister_alg(&ablk_xts_alg);
#endif
#ifdef HAS_PCBC
crypto_unregister_alg(&ablk_pcbc_alg);
#endif
#ifdef HAS_LRW
crypto_unregister_alg(&ablk_lrw_alg);
#endif
#ifdef HAS_CTR
crypto_unregister_alg(&ablk_rfc3686_ctr_alg);
#endif
crypto_unregister_alg(&ablk_ctr_alg);
crypto_unregister_alg(&ablk_cbc_alg);
crypto_unregister_alg(&ablk_ecb_alg);
crypto_unregister_alg(&blk_ctr_alg);
crypto_unregister_alg(&blk_cbc_alg);
crypto_unregister_alg(&blk_ecb_alg);
crypto_unregister_alg(&__aesni_alg);
crypto_unregister_alg(&aesni_alg);
}
module_init(aesni_init);
module_exit(aesni_exit);
MODULE_DESCRIPTION("Rijndael (AES) Cipher Algorithm, Intel AES-NI instructions optimized");
MODULE_LICENSE("GPL");
MODULE_ALIAS("aes");
| gpl-2.0 |
HRTKernel/Hacker-Kernel-H850 | drivers/net/ethernet/amd/hplance.c | 1703 | 6698 | /* hplance.c : the Linux/hp300/lance ethernet driver
*
* Copyright (C) 05/1998 Peter Maydell <pmaydell@chiark.greenend.org.uk>
* Based on the Sun Lance driver and the NetBSD HP Lance driver
* Uses the generic 7990.c LANCE code.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/string.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/errno.h>
/* Used for the temporal inet entries and routing */
#include <linux/socket.h>
#include <linux/route.h>
#include <linux/dio.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <asm/io.h>
#include <asm/pgtable.h>
#include "hplance.h"
/* We have 16392 bytes of RAM for the init block and buffers. This places
* an upper limit on the number of buffers we can use. NetBSD uses 8 Rx
* buffers and 2 Tx buffers, it takes (8 + 2) * 1544 bytes.
*/
#define LANCE_LOG_TX_BUFFERS 1
#define LANCE_LOG_RX_BUFFERS 3
#include "7990.h" /* use generic LANCE code */
/* Our private data structure */
struct hplance_private {
struct lance_private lance;
};
/* function prototypes... This is easy because all the grot is in the
* generic LANCE support. All we have to support is probing for boards,
* plus board-specific init, open and close actions.
* Oh, and we need to tell the generic code how to read and write LANCE registers...
*/
static int hplance_init_one(struct dio_dev *d, const struct dio_device_id *ent);
static void hplance_init(struct net_device *dev, struct dio_dev *d);
static void hplance_remove_one(struct dio_dev *d);
static void hplance_writerap(void *priv, unsigned short value);
static void hplance_writerdp(void *priv, unsigned short value);
static unsigned short hplance_readrdp(void *priv);
static int hplance_open(struct net_device *dev);
static int hplance_close(struct net_device *dev);
static struct dio_device_id hplance_dio_tbl[] = {
{ DIO_ID_LAN },
{ 0 }
};
static struct dio_driver hplance_driver = {
.name = "hplance",
.id_table = hplance_dio_tbl,
.probe = hplance_init_one,
.remove = hplance_remove_one,
};
static const struct net_device_ops hplance_netdev_ops = {
.ndo_open = hplance_open,
.ndo_stop = hplance_close,
.ndo_start_xmit = lance_start_xmit,
.ndo_set_rx_mode = lance_set_multicast,
.ndo_change_mtu = eth_change_mtu,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_mac_address = eth_mac_addr,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = lance_poll,
#endif
};
/* Find all the HP Lance boards and initialise them... */
static int hplance_init_one(struct dio_dev *d, const struct dio_device_id *ent)
{
struct net_device *dev;
int err = -ENOMEM;
dev = alloc_etherdev(sizeof(struct hplance_private));
if (!dev)
goto out;
err = -EBUSY;
if (!request_mem_region(dio_resource_start(d),
dio_resource_len(d), d->name))
goto out_free_netdev;
hplance_init(dev, d);
err = register_netdev(dev);
if (err)
goto out_release_mem_region;
dio_set_drvdata(d, dev);
printk(KERN_INFO "%s: %s; select code %d, addr %pM, irq %d\n",
dev->name, d->name, d->scode, dev->dev_addr, d->ipl);
return 0;
out_release_mem_region:
release_mem_region(dio_resource_start(d), dio_resource_len(d));
out_free_netdev:
free_netdev(dev);
out:
return err;
}
static void hplance_remove_one(struct dio_dev *d)
{
struct net_device *dev = dio_get_drvdata(d);
unregister_netdev(dev);
release_mem_region(dio_resource_start(d), dio_resource_len(d));
free_netdev(dev);
}
/* Initialise a single lance board at the given DIO device */
static void hplance_init(struct net_device *dev, struct dio_dev *d)
{
unsigned long va = (d->resource.start + DIO_VIRADDRBASE);
struct hplance_private *lp;
int i;
/* reset the board */
out_8(va + DIO_IDOFF, 0xff);
udelay(100); /* ariba! ariba! udelay! udelay! */
/* Fill the dev fields */
dev->base_addr = va;
dev->netdev_ops = &hplance_netdev_ops;
dev->dma = 0;
for (i = 0; i < 6; i++) {
/* The NVRAM holds our ethernet address, one nibble per byte,
* at bytes NVRAMOFF+1,3,5,7,9...
*/
dev->dev_addr[i] = ((in_8(va + HPLANCE_NVRAMOFF + i*4 + 1) & 0xF) << 4)
| (in_8(va + HPLANCE_NVRAMOFF + i*4 + 3) & 0xF);
}
lp = netdev_priv(dev);
lp->lance.name = d->name;
lp->lance.base = va;
lp->lance.init_block = (struct lance_init_block *)(va + HPLANCE_MEMOFF); /* CPU addr */
lp->lance.lance_init_block = NULL; /* LANCE addr of same RAM */
lp->lance.busmaster_regval = LE_C3_BSWP; /* we're bigendian */
lp->lance.irq = d->ipl;
lp->lance.writerap = hplance_writerap;
lp->lance.writerdp = hplance_writerdp;
lp->lance.readrdp = hplance_readrdp;
lp->lance.lance_log_rx_bufs = LANCE_LOG_RX_BUFFERS;
lp->lance.lance_log_tx_bufs = LANCE_LOG_TX_BUFFERS;
lp->lance.rx_ring_mod_mask = RX_RING_MOD_MASK;
lp->lance.tx_ring_mod_mask = TX_RING_MOD_MASK;
}
/* This is disgusting. We have to check the DIO status register for ack every
* time we read or write the LANCE registers.
*/
static void hplance_writerap(void *priv, unsigned short value)
{
struct lance_private *lp = (struct lance_private *)priv;
do {
out_be16(lp->base + HPLANCE_REGOFF + LANCE_RAP, value);
} while ((in_8(lp->base + HPLANCE_STATUS) & LE_ACK) == 0);
}
static void hplance_writerdp(void *priv, unsigned short value)
{
struct lance_private *lp = (struct lance_private *)priv;
do {
out_be16(lp->base + HPLANCE_REGOFF + LANCE_RDP, value);
} while ((in_8(lp->base + HPLANCE_STATUS) & LE_ACK) == 0);
}
static unsigned short hplance_readrdp(void *priv)
{
struct lance_private *lp = (struct lance_private *)priv;
__u16 value;
do {
value = in_be16(lp->base + HPLANCE_REGOFF + LANCE_RDP);
} while ((in_8(lp->base + HPLANCE_STATUS) & LE_ACK) == 0);
return value;
}
static int hplance_open(struct net_device *dev)
{
int status;
struct lance_private *lp = netdev_priv(dev);
status = lance_open(dev); /* call generic lance open code */
if (status)
return status;
/* enable interrupts at board level. */
out_8(lp->base + HPLANCE_STATUS, LE_IE);
return 0;
}
static int hplance_close(struct net_device *dev)
{
struct lance_private *lp = netdev_priv(dev);
out_8(lp->base + HPLANCE_STATUS, 0); /* disable interrupts at boardlevel */
lance_close(dev);
return 0;
}
static int __init hplance_init_module(void)
{
return dio_register_driver(&hplance_driver);
}
static void __exit hplance_cleanup_module(void)
{
dio_unregister_driver(&hplance_driver);
}
module_init(hplance_init_module);
module_exit(hplance_cleanup_module);
MODULE_LICENSE("GPL");
| gpl-2.0 |
kbc-developers/kernel_samsung_exynos4412 | drivers/xen/xenbus/xenbus_xs.c | 1959 | 21017 | /******************************************************************************
* xenbus_xs.c
*
* This is the kernel equivalent of the "xs" library. We don't need everything
* and we use xenbus_comms for communication.
*
* Copyright (C) 2005 Rusty Russell, IBM 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; or, when distributed
* separately from the Linux kernel or incorporated into other
* software packages, subject to the following license:
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this source file (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <linux/unistd.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/uio.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/fcntl.h>
#include <linux/kthread.h>
#include <linux/rwsem.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <xen/xenbus.h>
#include "xenbus_comms.h"
struct xs_stored_msg {
struct list_head list;
struct xsd_sockmsg hdr;
union {
/* Queued replies. */
struct {
char *body;
} reply;
/* Queued watch events. */
struct {
struct xenbus_watch *handle;
char **vec;
unsigned int vec_size;
} watch;
} u;
};
struct xs_handle {
/* A list of replies. Currently only one will ever be outstanding. */
struct list_head reply_list;
spinlock_t reply_lock;
wait_queue_head_t reply_waitq;
/*
* Mutex ordering: transaction_mutex -> watch_mutex -> request_mutex.
* response_mutex is never taken simultaneously with the other three.
*
* transaction_mutex must be held before incrementing
* transaction_count. The mutex is held when a suspend is in
* progress to prevent new transactions starting.
*
* When decrementing transaction_count to zero the wait queue
* should be woken up, the suspend code waits for count to
* reach zero.
*/
/* One request at a time. */
struct mutex request_mutex;
/* Protect xenbus reader thread against save/restore. */
struct mutex response_mutex;
/* Protect transactions against save/restore. */
struct mutex transaction_mutex;
atomic_t transaction_count;
wait_queue_head_t transaction_wq;
/* Protect watch (de)register against save/restore. */
struct rw_semaphore watch_mutex;
};
static struct xs_handle xs_state;
/* List of registered watches, and a lock to protect it. */
static LIST_HEAD(watches);
static DEFINE_SPINLOCK(watches_lock);
/* List of pending watch callback events, and a lock to protect it. */
static LIST_HEAD(watch_events);
static DEFINE_SPINLOCK(watch_events_lock);
/*
* Details of the xenwatch callback kernel thread. The thread waits on the
* watch_events_waitq for work to do (queued on watch_events list). When it
* wakes up it acquires the xenwatch_mutex before reading the list and
* carrying out work.
*/
static pid_t xenwatch_pid;
static DEFINE_MUTEX(xenwatch_mutex);
static DECLARE_WAIT_QUEUE_HEAD(watch_events_waitq);
static int get_error(const char *errorstring)
{
unsigned int i;
for (i = 0; strcmp(errorstring, xsd_errors[i].errstring) != 0; i++) {
if (i == ARRAY_SIZE(xsd_errors) - 1) {
printk(KERN_WARNING
"XENBUS xen store gave: unknown error %s",
errorstring);
return EINVAL;
}
}
return xsd_errors[i].errnum;
}
static void *read_reply(enum xsd_sockmsg_type *type, unsigned int *len)
{
struct xs_stored_msg *msg;
char *body;
spin_lock(&xs_state.reply_lock);
while (list_empty(&xs_state.reply_list)) {
spin_unlock(&xs_state.reply_lock);
/* XXX FIXME: Avoid synchronous wait for response here. */
wait_event(xs_state.reply_waitq,
!list_empty(&xs_state.reply_list));
spin_lock(&xs_state.reply_lock);
}
msg = list_entry(xs_state.reply_list.next,
struct xs_stored_msg, list);
list_del(&msg->list);
spin_unlock(&xs_state.reply_lock);
*type = msg->hdr.type;
if (len)
*len = msg->hdr.len;
body = msg->u.reply.body;
kfree(msg);
return body;
}
static void transaction_start(void)
{
mutex_lock(&xs_state.transaction_mutex);
atomic_inc(&xs_state.transaction_count);
mutex_unlock(&xs_state.transaction_mutex);
}
static void transaction_end(void)
{
if (atomic_dec_and_test(&xs_state.transaction_count))
wake_up(&xs_state.transaction_wq);
}
static void transaction_suspend(void)
{
mutex_lock(&xs_state.transaction_mutex);
wait_event(xs_state.transaction_wq,
atomic_read(&xs_state.transaction_count) == 0);
}
static void transaction_resume(void)
{
mutex_unlock(&xs_state.transaction_mutex);
}
void *xenbus_dev_request_and_reply(struct xsd_sockmsg *msg)
{
void *ret;
struct xsd_sockmsg req_msg = *msg;
int err;
if (req_msg.type == XS_TRANSACTION_START)
transaction_start();
mutex_lock(&xs_state.request_mutex);
err = xb_write(msg, sizeof(*msg) + msg->len);
if (err) {
msg->type = XS_ERROR;
ret = ERR_PTR(err);
} else
ret = read_reply(&msg->type, &msg->len);
mutex_unlock(&xs_state.request_mutex);
if ((msg->type == XS_TRANSACTION_END) ||
((req_msg.type == XS_TRANSACTION_START) &&
(msg->type == XS_ERROR)))
transaction_end();
return ret;
}
EXPORT_SYMBOL(xenbus_dev_request_and_reply);
/* Send message to xs, get kmalloc'ed reply. ERR_PTR() on error. */
static void *xs_talkv(struct xenbus_transaction t,
enum xsd_sockmsg_type type,
const struct kvec *iovec,
unsigned int num_vecs,
unsigned int *len)
{
struct xsd_sockmsg msg;
void *ret = NULL;
unsigned int i;
int err;
msg.tx_id = t.id;
msg.req_id = 0;
msg.type = type;
msg.len = 0;
for (i = 0; i < num_vecs; i++)
msg.len += iovec[i].iov_len;
mutex_lock(&xs_state.request_mutex);
err = xb_write(&msg, sizeof(msg));
if (err) {
mutex_unlock(&xs_state.request_mutex);
return ERR_PTR(err);
}
for (i = 0; i < num_vecs; i++) {
err = xb_write(iovec[i].iov_base, iovec[i].iov_len);
if (err) {
mutex_unlock(&xs_state.request_mutex);
return ERR_PTR(err);
}
}
ret = read_reply(&msg.type, len);
mutex_unlock(&xs_state.request_mutex);
if (IS_ERR(ret))
return ret;
if (msg.type == XS_ERROR) {
err = get_error(ret);
kfree(ret);
return ERR_PTR(-err);
}
if (msg.type != type) {
if (printk_ratelimit())
printk(KERN_WARNING
"XENBUS unexpected type [%d], expected [%d]\n",
msg.type, type);
kfree(ret);
return ERR_PTR(-EINVAL);
}
return ret;
}
/* Simplified version of xs_talkv: single message. */
static void *xs_single(struct xenbus_transaction t,
enum xsd_sockmsg_type type,
const char *string,
unsigned int *len)
{
struct kvec iovec;
iovec.iov_base = (void *)string;
iovec.iov_len = strlen(string) + 1;
return xs_talkv(t, type, &iovec, 1, len);
}
/* Many commands only need an ack, don't care what it says. */
static int xs_error(char *reply)
{
if (IS_ERR(reply))
return PTR_ERR(reply);
kfree(reply);
return 0;
}
static unsigned int count_strings(const char *strings, unsigned int len)
{
unsigned int num;
const char *p;
for (p = strings, num = 0; p < strings + len; p += strlen(p) + 1)
num++;
return num;
}
/* Return the path to dir with /name appended. Buffer must be kfree()'ed. */
static char *join(const char *dir, const char *name)
{
char *buffer;
if (strlen(name) == 0)
buffer = kasprintf(GFP_NOIO | __GFP_HIGH, "%s", dir);
else
buffer = kasprintf(GFP_NOIO | __GFP_HIGH, "%s/%s", dir, name);
return (!buffer) ? ERR_PTR(-ENOMEM) : buffer;
}
static char **split(char *strings, unsigned int len, unsigned int *num)
{
char *p, **ret;
/* Count the strings. */
*num = count_strings(strings, len);
/* Transfer to one big alloc for easy freeing. */
ret = kmalloc(*num * sizeof(char *) + len, GFP_NOIO | __GFP_HIGH);
if (!ret) {
kfree(strings);
return ERR_PTR(-ENOMEM);
}
memcpy(&ret[*num], strings, len);
kfree(strings);
strings = (char *)&ret[*num];
for (p = strings, *num = 0; p < strings + len; p += strlen(p) + 1)
ret[(*num)++] = p;
return ret;
}
char **xenbus_directory(struct xenbus_transaction t,
const char *dir, const char *node, unsigned int *num)
{
char *strings, *path;
unsigned int len;
path = join(dir, node);
if (IS_ERR(path))
return (char **)path;
strings = xs_single(t, XS_DIRECTORY, path, &len);
kfree(path);
if (IS_ERR(strings))
return (char **)strings;
return split(strings, len, num);
}
EXPORT_SYMBOL_GPL(xenbus_directory);
/* Check if a path exists. Return 1 if it does. */
int xenbus_exists(struct xenbus_transaction t,
const char *dir, const char *node)
{
char **d;
int dir_n;
d = xenbus_directory(t, dir, node, &dir_n);
if (IS_ERR(d))
return 0;
kfree(d);
return 1;
}
EXPORT_SYMBOL_GPL(xenbus_exists);
/* Get the value of a single file.
* Returns a kmalloced value: call free() on it after use.
* len indicates length in bytes.
*/
void *xenbus_read(struct xenbus_transaction t,
const char *dir, const char *node, unsigned int *len)
{
char *path;
void *ret;
path = join(dir, node);
if (IS_ERR(path))
return (void *)path;
ret = xs_single(t, XS_READ, path, len);
kfree(path);
return ret;
}
EXPORT_SYMBOL_GPL(xenbus_read);
/* Write the value of a single file.
* Returns -err on failure.
*/
int xenbus_write(struct xenbus_transaction t,
const char *dir, const char *node, const char *string)
{
const char *path;
struct kvec iovec[2];
int ret;
path = join(dir, node);
if (IS_ERR(path))
return PTR_ERR(path);
iovec[0].iov_base = (void *)path;
iovec[0].iov_len = strlen(path) + 1;
iovec[1].iov_base = (void *)string;
iovec[1].iov_len = strlen(string);
ret = xs_error(xs_talkv(t, XS_WRITE, iovec, ARRAY_SIZE(iovec), NULL));
kfree(path);
return ret;
}
EXPORT_SYMBOL_GPL(xenbus_write);
/* Create a new directory. */
int xenbus_mkdir(struct xenbus_transaction t,
const char *dir, const char *node)
{
char *path;
int ret;
path = join(dir, node);
if (IS_ERR(path))
return PTR_ERR(path);
ret = xs_error(xs_single(t, XS_MKDIR, path, NULL));
kfree(path);
return ret;
}
EXPORT_SYMBOL_GPL(xenbus_mkdir);
/* Destroy a file or directory (directories must be empty). */
int xenbus_rm(struct xenbus_transaction t, const char *dir, const char *node)
{
char *path;
int ret;
path = join(dir, node);
if (IS_ERR(path))
return PTR_ERR(path);
ret = xs_error(xs_single(t, XS_RM, path, NULL));
kfree(path);
return ret;
}
EXPORT_SYMBOL_GPL(xenbus_rm);
/* Start a transaction: changes by others will not be seen during this
* transaction, and changes will not be visible to others until end.
*/
int xenbus_transaction_start(struct xenbus_transaction *t)
{
char *id_str;
transaction_start();
id_str = xs_single(XBT_NIL, XS_TRANSACTION_START, "", NULL);
if (IS_ERR(id_str)) {
transaction_end();
return PTR_ERR(id_str);
}
t->id = simple_strtoul(id_str, NULL, 0);
kfree(id_str);
return 0;
}
EXPORT_SYMBOL_GPL(xenbus_transaction_start);
/* End a transaction.
* If abandon is true, transaction is discarded instead of committed.
*/
int xenbus_transaction_end(struct xenbus_transaction t, int abort)
{
char abortstr[2];
int err;
if (abort)
strcpy(abortstr, "F");
else
strcpy(abortstr, "T");
err = xs_error(xs_single(t, XS_TRANSACTION_END, abortstr, NULL));
transaction_end();
return err;
}
EXPORT_SYMBOL_GPL(xenbus_transaction_end);
/* Single read and scanf: returns -errno or num scanned. */
int xenbus_scanf(struct xenbus_transaction t,
const char *dir, const char *node, const char *fmt, ...)
{
va_list ap;
int ret;
char *val;
val = xenbus_read(t, dir, node, NULL);
if (IS_ERR(val))
return PTR_ERR(val);
va_start(ap, fmt);
ret = vsscanf(val, fmt, ap);
va_end(ap);
kfree(val);
/* Distinctive errno. */
if (ret == 0)
return -ERANGE;
return ret;
}
EXPORT_SYMBOL_GPL(xenbus_scanf);
/* Single printf and write: returns -errno or 0. */
int xenbus_printf(struct xenbus_transaction t,
const char *dir, const char *node, const char *fmt, ...)
{
va_list ap;
int ret;
#define PRINTF_BUFFER_SIZE 4096
char *printf_buffer;
printf_buffer = kmalloc(PRINTF_BUFFER_SIZE, GFP_NOIO | __GFP_HIGH);
if (printf_buffer == NULL)
return -ENOMEM;
va_start(ap, fmt);
ret = vsnprintf(printf_buffer, PRINTF_BUFFER_SIZE, fmt, ap);
va_end(ap);
BUG_ON(ret > PRINTF_BUFFER_SIZE-1);
ret = xenbus_write(t, dir, node, printf_buffer);
kfree(printf_buffer);
return ret;
}
EXPORT_SYMBOL_GPL(xenbus_printf);
/* Takes tuples of names, scanf-style args, and void **, NULL terminated. */
int xenbus_gather(struct xenbus_transaction t, const char *dir, ...)
{
va_list ap;
const char *name;
int ret = 0;
va_start(ap, dir);
while (ret == 0 && (name = va_arg(ap, char *)) != NULL) {
const char *fmt = va_arg(ap, char *);
void *result = va_arg(ap, void *);
char *p;
p = xenbus_read(t, dir, name, NULL);
if (IS_ERR(p)) {
ret = PTR_ERR(p);
break;
}
if (fmt) {
if (sscanf(p, fmt, result) == 0)
ret = -EINVAL;
kfree(p);
} else
*(char **)result = p;
}
va_end(ap);
return ret;
}
EXPORT_SYMBOL_GPL(xenbus_gather);
static int xs_watch(const char *path, const char *token)
{
struct kvec iov[2];
iov[0].iov_base = (void *)path;
iov[0].iov_len = strlen(path) + 1;
iov[1].iov_base = (void *)token;
iov[1].iov_len = strlen(token) + 1;
return xs_error(xs_talkv(XBT_NIL, XS_WATCH, iov,
ARRAY_SIZE(iov), NULL));
}
static int xs_unwatch(const char *path, const char *token)
{
struct kvec iov[2];
iov[0].iov_base = (char *)path;
iov[0].iov_len = strlen(path) + 1;
iov[1].iov_base = (char *)token;
iov[1].iov_len = strlen(token) + 1;
return xs_error(xs_talkv(XBT_NIL, XS_UNWATCH, iov,
ARRAY_SIZE(iov), NULL));
}
static struct xenbus_watch *find_watch(const char *token)
{
struct xenbus_watch *i, *cmp;
cmp = (void *)simple_strtoul(token, NULL, 16);
list_for_each_entry(i, &watches, list)
if (i == cmp)
return i;
return NULL;
}
/* Register callback to watch this node. */
int register_xenbus_watch(struct xenbus_watch *watch)
{
/* Pointer in ascii is the token. */
char token[sizeof(watch) * 2 + 1];
int err;
sprintf(token, "%lX", (long)watch);
down_read(&xs_state.watch_mutex);
spin_lock(&watches_lock);
BUG_ON(find_watch(token));
list_add(&watch->list, &watches);
spin_unlock(&watches_lock);
err = xs_watch(watch->node, token);
/* Ignore errors due to multiple registration. */
if ((err != 0) && (err != -EEXIST)) {
spin_lock(&watches_lock);
list_del(&watch->list);
spin_unlock(&watches_lock);
}
up_read(&xs_state.watch_mutex);
return err;
}
EXPORT_SYMBOL_GPL(register_xenbus_watch);
void unregister_xenbus_watch(struct xenbus_watch *watch)
{
struct xs_stored_msg *msg, *tmp;
char token[sizeof(watch) * 2 + 1];
int err;
sprintf(token, "%lX", (long)watch);
down_read(&xs_state.watch_mutex);
spin_lock(&watches_lock);
BUG_ON(!find_watch(token));
list_del(&watch->list);
spin_unlock(&watches_lock);
err = xs_unwatch(watch->node, token);
if (err)
printk(KERN_WARNING
"XENBUS Failed to release watch %s: %i\n",
watch->node, err);
up_read(&xs_state.watch_mutex);
/* Make sure there are no callbacks running currently (unless
its us) */
if (current->pid != xenwatch_pid)
mutex_lock(&xenwatch_mutex);
/* Cancel pending watch events. */
spin_lock(&watch_events_lock);
list_for_each_entry_safe(msg, tmp, &watch_events, list) {
if (msg->u.watch.handle != watch)
continue;
list_del(&msg->list);
kfree(msg->u.watch.vec);
kfree(msg);
}
spin_unlock(&watch_events_lock);
if (current->pid != xenwatch_pid)
mutex_unlock(&xenwatch_mutex);
}
EXPORT_SYMBOL_GPL(unregister_xenbus_watch);
void xs_suspend(void)
{
transaction_suspend();
down_write(&xs_state.watch_mutex);
mutex_lock(&xs_state.request_mutex);
mutex_lock(&xs_state.response_mutex);
}
void xs_resume(void)
{
struct xenbus_watch *watch;
char token[sizeof(watch) * 2 + 1];
xb_init_comms();
mutex_unlock(&xs_state.response_mutex);
mutex_unlock(&xs_state.request_mutex);
transaction_resume();
/* No need for watches_lock: the watch_mutex is sufficient. */
list_for_each_entry(watch, &watches, list) {
sprintf(token, "%lX", (long)watch);
xs_watch(watch->node, token);
}
up_write(&xs_state.watch_mutex);
}
void xs_suspend_cancel(void)
{
mutex_unlock(&xs_state.response_mutex);
mutex_unlock(&xs_state.request_mutex);
up_write(&xs_state.watch_mutex);
mutex_unlock(&xs_state.transaction_mutex);
}
static int xenwatch_thread(void *unused)
{
struct list_head *ent;
struct xs_stored_msg *msg;
for (;;) {
wait_event_interruptible(watch_events_waitq,
!list_empty(&watch_events));
if (kthread_should_stop())
break;
mutex_lock(&xenwatch_mutex);
spin_lock(&watch_events_lock);
ent = watch_events.next;
if (ent != &watch_events)
list_del(ent);
spin_unlock(&watch_events_lock);
if (ent != &watch_events) {
msg = list_entry(ent, struct xs_stored_msg, list);
msg->u.watch.handle->callback(
msg->u.watch.handle,
(const char **)msg->u.watch.vec,
msg->u.watch.vec_size);
kfree(msg->u.watch.vec);
kfree(msg);
}
mutex_unlock(&xenwatch_mutex);
}
return 0;
}
static int process_msg(void)
{
struct xs_stored_msg *msg;
char *body;
int err;
/*
* We must disallow save/restore while reading a xenstore message.
* A partial read across s/r leaves us out of sync with xenstored.
*/
for (;;) {
err = xb_wait_for_data_to_read();
if (err)
return err;
mutex_lock(&xs_state.response_mutex);
if (xb_data_to_read())
break;
/* We raced with save/restore: pending data 'disappeared'. */
mutex_unlock(&xs_state.response_mutex);
}
msg = kmalloc(sizeof(*msg), GFP_NOIO | __GFP_HIGH);
if (msg == NULL) {
err = -ENOMEM;
goto out;
}
err = xb_read(&msg->hdr, sizeof(msg->hdr));
if (err) {
kfree(msg);
goto out;
}
if (msg->hdr.len > XENSTORE_PAYLOAD_MAX) {
kfree(msg);
err = -EINVAL;
goto out;
}
body = kmalloc(msg->hdr.len + 1, GFP_NOIO | __GFP_HIGH);
if (body == NULL) {
kfree(msg);
err = -ENOMEM;
goto out;
}
err = xb_read(body, msg->hdr.len);
if (err) {
kfree(body);
kfree(msg);
goto out;
}
body[msg->hdr.len] = '\0';
if (msg->hdr.type == XS_WATCH_EVENT) {
msg->u.watch.vec = split(body, msg->hdr.len,
&msg->u.watch.vec_size);
if (IS_ERR(msg->u.watch.vec)) {
err = PTR_ERR(msg->u.watch.vec);
kfree(msg);
goto out;
}
spin_lock(&watches_lock);
msg->u.watch.handle = find_watch(
msg->u.watch.vec[XS_WATCH_TOKEN]);
if (msg->u.watch.handle != NULL) {
spin_lock(&watch_events_lock);
list_add_tail(&msg->list, &watch_events);
wake_up(&watch_events_waitq);
spin_unlock(&watch_events_lock);
} else {
kfree(msg->u.watch.vec);
kfree(msg);
}
spin_unlock(&watches_lock);
} else {
msg->u.reply.body = body;
spin_lock(&xs_state.reply_lock);
list_add_tail(&msg->list, &xs_state.reply_list);
spin_unlock(&xs_state.reply_lock);
wake_up(&xs_state.reply_waitq);
}
out:
mutex_unlock(&xs_state.response_mutex);
return err;
}
static int xenbus_thread(void *unused)
{
int err;
for (;;) {
err = process_msg();
if (err)
printk(KERN_WARNING "XENBUS error %d while reading "
"message\n", err);
if (kthread_should_stop())
break;
}
return 0;
}
int xs_init(void)
{
int err;
struct task_struct *task;
INIT_LIST_HEAD(&xs_state.reply_list);
spin_lock_init(&xs_state.reply_lock);
init_waitqueue_head(&xs_state.reply_waitq);
mutex_init(&xs_state.request_mutex);
mutex_init(&xs_state.response_mutex);
mutex_init(&xs_state.transaction_mutex);
init_rwsem(&xs_state.watch_mutex);
atomic_set(&xs_state.transaction_count, 0);
init_waitqueue_head(&xs_state.transaction_wq);
/* Initialize the shared memory rings to talk to xenstored */
err = xb_init_comms();
if (err)
return err;
task = kthread_run(xenwatch_thread, NULL, "xenwatch");
if (IS_ERR(task))
return PTR_ERR(task);
xenwatch_pid = task->pid;
task = kthread_run(xenbus_thread, NULL, "xenbus");
if (IS_ERR(task))
return PTR_ERR(task);
return 0;
}
| gpl-2.0 |
CyanHacker-Lollipop/kernel_moto_shamu | drivers/media/dvb-frontends/cxd2820r_c.c | 2471 | 7460 | /*
* Sony CXD2820R demodulator driver
*
* Copyright (C) 2010 Antti Palosaari <crope@iki.fi>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "cxd2820r_priv.h"
int cxd2820r_set_frontend_c(struct dvb_frontend *fe)
{
struct cxd2820r_priv *priv = fe->demodulator_priv;
struct dtv_frontend_properties *c = &fe->dtv_property_cache;
int ret, i;
u8 buf[2];
u32 if_freq;
u16 if_ctl;
u64 num;
struct reg_val_mask tab[] = {
{ 0x00080, 0x01, 0xff },
{ 0x00081, 0x05, 0xff },
{ 0x00085, 0x07, 0xff },
{ 0x00088, 0x01, 0xff },
{ 0x00082, 0x20, 0x60 },
{ 0x1016a, 0x48, 0xff },
{ 0x100a5, 0x00, 0x01 },
{ 0x10020, 0x06, 0x07 },
{ 0x10059, 0x50, 0xff },
{ 0x10087, 0x0c, 0x3c },
{ 0x1008b, 0x07, 0xff },
{ 0x1001f, priv->cfg.if_agc_polarity << 7, 0x80 },
{ 0x10070, priv->cfg.ts_mode, 0xff },
};
dev_dbg(&priv->i2c->dev, "%s: frequency=%d symbol_rate=%d\n", __func__,
c->frequency, c->symbol_rate);
/* program tuner */
if (fe->ops.tuner_ops.set_params)
fe->ops.tuner_ops.set_params(fe);
if (priv->delivery_system != SYS_DVBC_ANNEX_A) {
for (i = 0; i < ARRAY_SIZE(tab); i++) {
ret = cxd2820r_wr_reg_mask(priv, tab[i].reg,
tab[i].val, tab[i].mask);
if (ret)
goto error;
}
}
priv->delivery_system = SYS_DVBC_ANNEX_A;
priv->ber_running = 0; /* tune stops BER counter */
/* program IF frequency */
if (fe->ops.tuner_ops.get_if_frequency) {
ret = fe->ops.tuner_ops.get_if_frequency(fe, &if_freq);
if (ret)
goto error;
} else
if_freq = 0;
dev_dbg(&priv->i2c->dev, "%s: if_freq=%d\n", __func__, if_freq);
num = if_freq / 1000; /* Hz => kHz */
num *= 0x4000;
if_ctl = cxd2820r_div_u64_round_closest(num, 41000);
buf[0] = (if_ctl >> 8) & 0x3f;
buf[1] = (if_ctl >> 0) & 0xff;
ret = cxd2820r_wr_regs(priv, 0x10042, buf, 2);
if (ret)
goto error;
ret = cxd2820r_wr_reg(priv, 0x000ff, 0x08);
if (ret)
goto error;
ret = cxd2820r_wr_reg(priv, 0x000fe, 0x01);
if (ret)
goto error;
return ret;
error:
dev_dbg(&priv->i2c->dev, "%s: failed=%d\n", __func__, ret);
return ret;
}
int cxd2820r_get_frontend_c(struct dvb_frontend *fe)
{
struct cxd2820r_priv *priv = fe->demodulator_priv;
struct dtv_frontend_properties *c = &fe->dtv_property_cache;
int ret;
u8 buf[2];
ret = cxd2820r_rd_regs(priv, 0x1001a, buf, 2);
if (ret)
goto error;
c->symbol_rate = 2500 * ((buf[0] & 0x0f) << 8 | buf[1]);
ret = cxd2820r_rd_reg(priv, 0x10019, &buf[0]);
if (ret)
goto error;
switch ((buf[0] >> 0) & 0x07) {
case 0:
c->modulation = QAM_16;
break;
case 1:
c->modulation = QAM_32;
break;
case 2:
c->modulation = QAM_64;
break;
case 3:
c->modulation = QAM_128;
break;
case 4:
c->modulation = QAM_256;
break;
}
switch ((buf[0] >> 7) & 0x01) {
case 0:
c->inversion = INVERSION_OFF;
break;
case 1:
c->inversion = INVERSION_ON;
break;
}
return ret;
error:
dev_dbg(&priv->i2c->dev, "%s: failed=%d\n", __func__, ret);
return ret;
}
int cxd2820r_read_ber_c(struct dvb_frontend *fe, u32 *ber)
{
struct cxd2820r_priv *priv = fe->demodulator_priv;
int ret;
u8 buf[3], start_ber = 0;
*ber = 0;
if (priv->ber_running) {
ret = cxd2820r_rd_regs(priv, 0x10076, buf, sizeof(buf));
if (ret)
goto error;
if ((buf[2] >> 7) & 0x01 || (buf[2] >> 4) & 0x01) {
*ber = (buf[2] & 0x0f) << 16 | buf[1] << 8 | buf[0];
start_ber = 1;
}
} else {
priv->ber_running = 1;
start_ber = 1;
}
if (start_ber) {
/* (re)start BER */
ret = cxd2820r_wr_reg(priv, 0x10079, 0x01);
if (ret)
goto error;
}
return ret;
error:
dev_dbg(&priv->i2c->dev, "%s: failed=%d\n", __func__, ret);
return ret;
}
int cxd2820r_read_signal_strength_c(struct dvb_frontend *fe,
u16 *strength)
{
struct cxd2820r_priv *priv = fe->demodulator_priv;
int ret;
u8 buf[2];
u16 tmp;
ret = cxd2820r_rd_regs(priv, 0x10049, buf, sizeof(buf));
if (ret)
goto error;
tmp = (buf[0] & 0x03) << 8 | buf[1];
tmp = (~tmp & 0x03ff);
if (tmp == 512)
/* ~no signal */
tmp = 0;
else if (tmp > 350)
tmp = 350;
/* scale value to 0x0000-0xffff */
*strength = tmp * 0xffff / (350-0);
return ret;
error:
dev_dbg(&priv->i2c->dev, "%s: failed=%d\n", __func__, ret);
return ret;
}
int cxd2820r_read_snr_c(struct dvb_frontend *fe, u16 *snr)
{
struct cxd2820r_priv *priv = fe->demodulator_priv;
int ret;
u8 tmp;
unsigned int A, B;
/* report SNR in dB * 10 */
ret = cxd2820r_rd_reg(priv, 0x10019, &tmp);
if (ret)
goto error;
if (((tmp >> 0) & 0x03) % 2) {
A = 875;
B = 650;
} else {
A = 950;
B = 760;
}
ret = cxd2820r_rd_reg(priv, 0x1004d, &tmp);
if (ret)
goto error;
#define CXD2820R_LOG2_E_24 24204406 /* log2(e) << 24 */
if (tmp)
*snr = A * (intlog2(B / tmp) >> 5) / (CXD2820R_LOG2_E_24 >> 5)
/ 10;
else
*snr = 0;
return ret;
error:
dev_dbg(&priv->i2c->dev, "%s: failed=%d\n", __func__, ret);
return ret;
}
int cxd2820r_read_ucblocks_c(struct dvb_frontend *fe, u32 *ucblocks)
{
*ucblocks = 0;
/* no way to read ? */
return 0;
}
int cxd2820r_read_status_c(struct dvb_frontend *fe, fe_status_t *status)
{
struct cxd2820r_priv *priv = fe->demodulator_priv;
int ret;
u8 buf[2];
*status = 0;
ret = cxd2820r_rd_regs(priv, 0x10088, buf, sizeof(buf));
if (ret)
goto error;
if (((buf[0] >> 0) & 0x01) == 1) {
*status |= FE_HAS_SIGNAL | FE_HAS_CARRIER |
FE_HAS_VITERBI | FE_HAS_SYNC;
if (((buf[1] >> 3) & 0x01) == 1) {
*status |= FE_HAS_SIGNAL | FE_HAS_CARRIER |
FE_HAS_VITERBI | FE_HAS_SYNC | FE_HAS_LOCK;
}
}
dev_dbg(&priv->i2c->dev, "%s: lock=%02x %02x\n", __func__, buf[0],
buf[1]);
return ret;
error:
dev_dbg(&priv->i2c->dev, "%s: failed=%d\n", __func__, ret);
return ret;
}
int cxd2820r_init_c(struct dvb_frontend *fe)
{
struct cxd2820r_priv *priv = fe->demodulator_priv;
int ret;
ret = cxd2820r_wr_reg(priv, 0x00085, 0x07);
if (ret)
goto error;
return ret;
error:
dev_dbg(&priv->i2c->dev, "%s: failed=%d\n", __func__, ret);
return ret;
}
int cxd2820r_sleep_c(struct dvb_frontend *fe)
{
struct cxd2820r_priv *priv = fe->demodulator_priv;
int ret, i;
struct reg_val_mask tab[] = {
{ 0x000ff, 0x1f, 0xff },
{ 0x00085, 0x00, 0xff },
{ 0x00088, 0x01, 0xff },
{ 0x00081, 0x00, 0xff },
{ 0x00080, 0x00, 0xff },
};
dev_dbg(&priv->i2c->dev, "%s\n", __func__);
priv->delivery_system = SYS_UNDEFINED;
for (i = 0; i < ARRAY_SIZE(tab); i++) {
ret = cxd2820r_wr_reg_mask(priv, tab[i].reg, tab[i].val,
tab[i].mask);
if (ret)
goto error;
}
return ret;
error:
dev_dbg(&priv->i2c->dev, "%s: failed=%d\n", __func__, ret);
return ret;
}
int cxd2820r_get_tune_settings_c(struct dvb_frontend *fe,
struct dvb_frontend_tune_settings *s)
{
s->min_delay_ms = 500;
s->step_size = 0; /* no zigzag */
s->max_drift = 0;
return 0;
}
| gpl-2.0 |
mdeejay/android_kernel_monarudo | security/integrity/evm/evm_main.c | 4263 | 12199 | /*
* Copyright (C) 2005-2010 IBM Corporation
*
* Author:
* Mimi Zohar <zohar@us.ibm.com>
* Kylene Hall <kjhall@us.ibm.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 2 of the License.
*
* File: evm_main.c
* implements evm_inode_setxattr, evm_inode_post_setxattr,
* evm_inode_removexattr, and evm_verifyxattr
*/
#include <linux/module.h>
#include <linux/crypto.h>
#include <linux/xattr.h>
#include <linux/integrity.h>
#include <linux/evm.h>
#include <crypto/hash.h>
#include "evm.h"
int evm_initialized;
char *evm_hmac = "hmac(sha1)";
char *evm_hash = "sha1";
char *evm_config_xattrnames[] = {
#ifdef CONFIG_SECURITY_SELINUX
XATTR_NAME_SELINUX,
#endif
#ifdef CONFIG_SECURITY_SMACK
XATTR_NAME_SMACK,
#endif
XATTR_NAME_CAPS,
NULL
};
static int evm_fixmode;
static int __init evm_set_fixmode(char *str)
{
if (strncmp(str, "fix", 3) == 0)
evm_fixmode = 1;
return 0;
}
__setup("evm=", evm_set_fixmode);
static int evm_find_protected_xattrs(struct dentry *dentry)
{
struct inode *inode = dentry->d_inode;
char **xattr;
int error;
int count = 0;
if (!inode->i_op || !inode->i_op->getxattr)
return -EOPNOTSUPP;
for (xattr = evm_config_xattrnames; *xattr != NULL; xattr++) {
error = inode->i_op->getxattr(dentry, *xattr, NULL, 0);
if (error < 0) {
if (error == -ENODATA)
continue;
return error;
}
count++;
}
return count;
}
/*
* evm_verify_hmac - calculate and compare the HMAC with the EVM xattr
*
* Compute the HMAC on the dentry's protected set of extended attributes
* and compare it against the stored security.evm xattr.
*
* For performance:
* - use the previoulsy retrieved xattr value and length to calculate the
* HMAC.)
* - cache the verification result in the iint, when available.
*
* Returns integrity status
*/
static enum integrity_status evm_verify_hmac(struct dentry *dentry,
const char *xattr_name,
char *xattr_value,
size_t xattr_value_len,
struct integrity_iint_cache *iint)
{
struct evm_ima_xattr_data *xattr_data = NULL;
struct evm_ima_xattr_data calc;
enum integrity_status evm_status = INTEGRITY_PASS;
int rc, xattr_len;
if (iint && iint->evm_status == INTEGRITY_PASS)
return iint->evm_status;
/* if status is not PASS, try to check again - against -ENOMEM */
/* first need to know the sig type */
rc = vfs_getxattr_alloc(dentry, XATTR_NAME_EVM, (char **)&xattr_data, 0,
GFP_NOFS);
if (rc <= 0) {
if (rc == 0)
evm_status = INTEGRITY_FAIL; /* empty */
else if (rc == -ENODATA) {
rc = evm_find_protected_xattrs(dentry);
if (rc > 0)
evm_status = INTEGRITY_NOLABEL;
else if (rc == 0)
evm_status = INTEGRITY_NOXATTRS; /* new file */
}
goto out;
}
xattr_len = rc - 1;
/* check value type */
switch (xattr_data->type) {
case EVM_XATTR_HMAC:
rc = evm_calc_hmac(dentry, xattr_name, xattr_value,
xattr_value_len, calc.digest);
if (rc)
break;
rc = memcmp(xattr_data->digest, calc.digest,
sizeof(calc.digest));
if (rc)
rc = -EINVAL;
break;
case EVM_IMA_XATTR_DIGSIG:
rc = evm_calc_hash(dentry, xattr_name, xattr_value,
xattr_value_len, calc.digest);
if (rc)
break;
rc = integrity_digsig_verify(INTEGRITY_KEYRING_EVM,
xattr_data->digest, xattr_len,
calc.digest, sizeof(calc.digest));
if (!rc) {
/* we probably want to replace rsa with hmac here */
evm_update_evmxattr(dentry, xattr_name, xattr_value,
xattr_value_len);
}
break;
default:
rc = -EINVAL;
break;
}
if (rc)
evm_status = (rc == -ENODATA) ?
INTEGRITY_NOXATTRS : INTEGRITY_FAIL;
out:
if (iint)
iint->evm_status = evm_status;
kfree(xattr_data);
return evm_status;
}
static int evm_protected_xattr(const char *req_xattr_name)
{
char **xattrname;
int namelen;
int found = 0;
namelen = strlen(req_xattr_name);
for (xattrname = evm_config_xattrnames; *xattrname != NULL; xattrname++) {
if ((strlen(*xattrname) == namelen)
&& (strncmp(req_xattr_name, *xattrname, namelen) == 0)) {
found = 1;
break;
}
if (strncmp(req_xattr_name,
*xattrname + XATTR_SECURITY_PREFIX_LEN,
strlen(req_xattr_name)) == 0) {
found = 1;
break;
}
}
return found;
}
/**
* evm_verifyxattr - verify the integrity of the requested xattr
* @dentry: object of the verify xattr
* @xattr_name: requested xattr
* @xattr_value: requested xattr value
* @xattr_value_len: requested xattr value length
*
* Calculate the HMAC for the given dentry and verify it against the stored
* security.evm xattr. For performance, use the xattr value and length
* previously retrieved to calculate the HMAC.
*
* Returns the xattr integrity status.
*
* This function requires the caller to lock the inode's i_mutex before it
* is executed.
*/
enum integrity_status evm_verifyxattr(struct dentry *dentry,
const char *xattr_name,
void *xattr_value, size_t xattr_value_len,
struct integrity_iint_cache *iint)
{
if (!evm_initialized || !evm_protected_xattr(xattr_name))
return INTEGRITY_UNKNOWN;
if (!iint) {
iint = integrity_iint_find(dentry->d_inode);
if (!iint)
return INTEGRITY_UNKNOWN;
}
return evm_verify_hmac(dentry, xattr_name, xattr_value,
xattr_value_len, iint);
}
EXPORT_SYMBOL_GPL(evm_verifyxattr);
/*
* evm_verify_current_integrity - verify the dentry's metadata integrity
* @dentry: pointer to the affected dentry
*
* Verify and return the dentry's metadata integrity. The exceptions are
* before EVM is initialized or in 'fix' mode.
*/
static enum integrity_status evm_verify_current_integrity(struct dentry *dentry)
{
struct inode *inode = dentry->d_inode;
if (!evm_initialized || !S_ISREG(inode->i_mode) || evm_fixmode)
return 0;
return evm_verify_hmac(dentry, NULL, NULL, 0, NULL);
}
/*
* evm_protect_xattr - protect the EVM extended attribute
*
* Prevent security.evm from being modified or removed without the
* necessary permissions or when the existing value is invalid.
*
* The posix xattr acls are 'system' prefixed, which normally would not
* affect security.evm. An interesting side affect of writing posix xattr
* acls is their modifying of the i_mode, which is included in security.evm.
* For posix xattr acls only, permit security.evm, even if it currently
* doesn't exist, to be updated.
*/
static int evm_protect_xattr(struct dentry *dentry, const char *xattr_name,
const void *xattr_value, size_t xattr_value_len)
{
enum integrity_status evm_status;
if (strcmp(xattr_name, XATTR_NAME_EVM) == 0) {
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
} else if (!evm_protected_xattr(xattr_name)) {
if (!posix_xattr_acl(xattr_name))
return 0;
evm_status = evm_verify_current_integrity(dentry);
if ((evm_status == INTEGRITY_PASS) ||
(evm_status == INTEGRITY_NOXATTRS))
return 0;
return -EPERM;
}
evm_status = evm_verify_current_integrity(dentry);
return evm_status == INTEGRITY_PASS ? 0 : -EPERM;
}
/**
* evm_inode_setxattr - protect the EVM extended attribute
* @dentry: pointer to the affected dentry
* @xattr_name: pointer to the affected extended attribute name
* @xattr_value: pointer to the new extended attribute value
* @xattr_value_len: pointer to the new extended attribute value length
*
* Updating 'security.evm' requires CAP_SYS_ADMIN privileges and that
* the current value is valid.
*/
int evm_inode_setxattr(struct dentry *dentry, const char *xattr_name,
const void *xattr_value, size_t xattr_value_len)
{
return evm_protect_xattr(dentry, xattr_name, xattr_value,
xattr_value_len);
}
/**
* evm_inode_removexattr - protect the EVM extended attribute
* @dentry: pointer to the affected dentry
* @xattr_name: pointer to the affected extended attribute name
*
* Removing 'security.evm' requires CAP_SYS_ADMIN privileges and that
* the current value is valid.
*/
int evm_inode_removexattr(struct dentry *dentry, const char *xattr_name)
{
return evm_protect_xattr(dentry, xattr_name, NULL, 0);
}
/**
* evm_inode_post_setxattr - update 'security.evm' to reflect the changes
* @dentry: pointer to the affected dentry
* @xattr_name: pointer to the affected extended attribute name
* @xattr_value: pointer to the new extended attribute value
* @xattr_value_len: pointer to the new extended attribute value length
*
* Update the HMAC stored in 'security.evm' to reflect the change.
*
* No need to take the i_mutex lock here, as this function is called from
* __vfs_setxattr_noperm(). The caller of which has taken the inode's
* i_mutex lock.
*/
void evm_inode_post_setxattr(struct dentry *dentry, const char *xattr_name,
const void *xattr_value, size_t xattr_value_len)
{
if (!evm_initialized || (!evm_protected_xattr(xattr_name)
&& !posix_xattr_acl(xattr_name)))
return;
evm_update_evmxattr(dentry, xattr_name, xattr_value, xattr_value_len);
return;
}
/**
* evm_inode_post_removexattr - update 'security.evm' after removing the xattr
* @dentry: pointer to the affected dentry
* @xattr_name: pointer to the affected extended attribute name
*
* Update the HMAC stored in 'security.evm' to reflect removal of the xattr.
*/
void evm_inode_post_removexattr(struct dentry *dentry, const char *xattr_name)
{
struct inode *inode = dentry->d_inode;
if (!evm_initialized || !evm_protected_xattr(xattr_name))
return;
mutex_lock(&inode->i_mutex);
evm_update_evmxattr(dentry, xattr_name, NULL, 0);
mutex_unlock(&inode->i_mutex);
return;
}
/**
* evm_inode_setattr - prevent updating an invalid EVM extended attribute
* @dentry: pointer to the affected dentry
*/
int evm_inode_setattr(struct dentry *dentry, struct iattr *attr)
{
unsigned int ia_valid = attr->ia_valid;
enum integrity_status evm_status;
if (!(ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID)))
return 0;
evm_status = evm_verify_current_integrity(dentry);
if ((evm_status == INTEGRITY_PASS) ||
(evm_status == INTEGRITY_NOXATTRS))
return 0;
return -EPERM;
}
/**
* evm_inode_post_setattr - update 'security.evm' after modifying metadata
* @dentry: pointer to the affected dentry
* @ia_valid: for the UID and GID status
*
* For now, update the HMAC stored in 'security.evm' to reflect UID/GID
* changes.
*
* This function is called from notify_change(), which expects the caller
* to lock the inode's i_mutex.
*/
void evm_inode_post_setattr(struct dentry *dentry, int ia_valid)
{
if (!evm_initialized)
return;
if (ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID))
evm_update_evmxattr(dentry, NULL, NULL, 0);
return;
}
/*
* evm_inode_init_security - initializes security.evm
*/
int evm_inode_init_security(struct inode *inode,
const struct xattr *lsm_xattr,
struct xattr *evm_xattr)
{
struct evm_ima_xattr_data *xattr_data;
int rc;
if (!evm_initialized || !evm_protected_xattr(lsm_xattr->name))
return 0;
xattr_data = kzalloc(sizeof(*xattr_data), GFP_NOFS);
if (!xattr_data)
return -ENOMEM;
xattr_data->type = EVM_XATTR_HMAC;
rc = evm_init_hmac(inode, lsm_xattr, xattr_data->digest);
if (rc < 0)
goto out;
evm_xattr->value = xattr_data;
evm_xattr->value_len = sizeof(*xattr_data);
evm_xattr->name = kstrdup(XATTR_EVM_SUFFIX, GFP_NOFS);
return 0;
out:
kfree(xattr_data);
return rc;
}
EXPORT_SYMBOL_GPL(evm_inode_init_security);
static int __init init_evm(void)
{
int error;
error = evm_init_secfs();
if (error < 0) {
printk(KERN_INFO "EVM: Error registering secfs\n");
goto err;
}
return 0;
err:
return error;
}
static void __exit cleanup_evm(void)
{
evm_cleanup_secfs();
if (hmac_tfm)
crypto_free_shash(hmac_tfm);
if (hash_tfm)
crypto_free_shash(hash_tfm);
}
/*
* evm_display_config - list the EVM protected security extended attributes
*/
static int __init evm_display_config(void)
{
char **xattrname;
for (xattrname = evm_config_xattrnames; *xattrname != NULL; xattrname++)
printk(KERN_INFO "EVM: %s\n", *xattrname);
return 0;
}
pure_initcall(evm_display_config);
late_initcall(init_evm);
MODULE_DESCRIPTION("Extended Verification Module");
MODULE_LICENSE("GPL");
| gpl-2.0 |
KingKaminari/kaminarikernel | drivers/mmc/host/dw_mmc-pltfm.c | 4775 | 2953 | /*
* Synopsys DesignWare Multimedia Card Interface driver
*
* Copyright (C) 2009 NXP Semiconductors
* Copyright (C) 2009, 2010 Imagination Technologies Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/io.h>
#include <linux/irq.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/mmc/host.h>
#include <linux/mmc/mmc.h>
#include <linux/mmc/dw_mmc.h>
#include "dw_mmc.h"
static int dw_mci_pltfm_probe(struct platform_device *pdev)
{
struct dw_mci *host;
struct resource *regs;
int ret;
host = kzalloc(sizeof(struct dw_mci), GFP_KERNEL);
if (!host)
return -ENOMEM;
regs = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!regs) {
ret = -ENXIO;
goto err_free;
}
host->irq = platform_get_irq(pdev, 0);
if (host->irq < 0) {
ret = host->irq;
goto err_free;
}
host->dev = pdev->dev;
host->irq_flags = 0;
host->pdata = pdev->dev.platform_data;
ret = -ENOMEM;
host->regs = ioremap(regs->start, resource_size(regs));
if (!host->regs)
goto err_free;
platform_set_drvdata(pdev, host);
ret = dw_mci_probe(host);
if (ret)
goto err_out;
return ret;
err_out:
iounmap(host->regs);
err_free:
kfree(host);
return ret;
}
static int __exit dw_mci_pltfm_remove(struct platform_device *pdev)
{
struct dw_mci *host = platform_get_drvdata(pdev);
platform_set_drvdata(pdev, NULL);
dw_mci_remove(host);
iounmap(host->regs);
kfree(host);
return 0;
}
#ifdef CONFIG_PM_SLEEP
/*
* TODO: we should probably disable the clock to the card in the suspend path.
*/
static int dw_mci_pltfm_suspend(struct device *dev)
{
int ret;
struct dw_mci *host = dev_get_drvdata(dev);
ret = dw_mci_suspend(host);
if (ret)
return ret;
return 0;
}
static int dw_mci_pltfm_resume(struct device *dev)
{
int ret;
struct dw_mci *host = dev_get_drvdata(dev);
ret = dw_mci_resume(host);
if (ret)
return ret;
return 0;
}
#else
#define dw_mci_pltfm_suspend NULL
#define dw_mci_pltfm_resume NULL
#endif /* CONFIG_PM_SLEEP */
static SIMPLE_DEV_PM_OPS(dw_mci_pltfm_pmops, dw_mci_pltfm_suspend, dw_mci_pltfm_resume);
static struct platform_driver dw_mci_pltfm_driver = {
.remove = __exit_p(dw_mci_pltfm_remove),
.driver = {
.name = "dw_mmc",
.pm = &dw_mci_pltfm_pmops,
},
};
static int __init dw_mci_init(void)
{
return platform_driver_probe(&dw_mci_pltfm_driver, dw_mci_pltfm_probe);
}
static void __exit dw_mci_exit(void)
{
platform_driver_unregister(&dw_mci_pltfm_driver);
}
module_init(dw_mci_init);
module_exit(dw_mci_exit);
MODULE_DESCRIPTION("DW Multimedia Card Interface driver");
MODULE_AUTHOR("NXP Semiconductor VietNam");
MODULE_AUTHOR("Imagination Technologies Ltd");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
GustavoRD78/78Kernel-ZL-233 | drivers/mmc/host/dw_mmc-pltfm.c | 4775 | 2953 | /*
* Synopsys DesignWare Multimedia Card Interface driver
*
* Copyright (C) 2009 NXP Semiconductors
* Copyright (C) 2009, 2010 Imagination Technologies Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/io.h>
#include <linux/irq.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/mmc/host.h>
#include <linux/mmc/mmc.h>
#include <linux/mmc/dw_mmc.h>
#include "dw_mmc.h"
static int dw_mci_pltfm_probe(struct platform_device *pdev)
{
struct dw_mci *host;
struct resource *regs;
int ret;
host = kzalloc(sizeof(struct dw_mci), GFP_KERNEL);
if (!host)
return -ENOMEM;
regs = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!regs) {
ret = -ENXIO;
goto err_free;
}
host->irq = platform_get_irq(pdev, 0);
if (host->irq < 0) {
ret = host->irq;
goto err_free;
}
host->dev = pdev->dev;
host->irq_flags = 0;
host->pdata = pdev->dev.platform_data;
ret = -ENOMEM;
host->regs = ioremap(regs->start, resource_size(regs));
if (!host->regs)
goto err_free;
platform_set_drvdata(pdev, host);
ret = dw_mci_probe(host);
if (ret)
goto err_out;
return ret;
err_out:
iounmap(host->regs);
err_free:
kfree(host);
return ret;
}
static int __exit dw_mci_pltfm_remove(struct platform_device *pdev)
{
struct dw_mci *host = platform_get_drvdata(pdev);
platform_set_drvdata(pdev, NULL);
dw_mci_remove(host);
iounmap(host->regs);
kfree(host);
return 0;
}
#ifdef CONFIG_PM_SLEEP
/*
* TODO: we should probably disable the clock to the card in the suspend path.
*/
static int dw_mci_pltfm_suspend(struct device *dev)
{
int ret;
struct dw_mci *host = dev_get_drvdata(dev);
ret = dw_mci_suspend(host);
if (ret)
return ret;
return 0;
}
static int dw_mci_pltfm_resume(struct device *dev)
{
int ret;
struct dw_mci *host = dev_get_drvdata(dev);
ret = dw_mci_resume(host);
if (ret)
return ret;
return 0;
}
#else
#define dw_mci_pltfm_suspend NULL
#define dw_mci_pltfm_resume NULL
#endif /* CONFIG_PM_SLEEP */
static SIMPLE_DEV_PM_OPS(dw_mci_pltfm_pmops, dw_mci_pltfm_suspend, dw_mci_pltfm_resume);
static struct platform_driver dw_mci_pltfm_driver = {
.remove = __exit_p(dw_mci_pltfm_remove),
.driver = {
.name = "dw_mmc",
.pm = &dw_mci_pltfm_pmops,
},
};
static int __init dw_mci_init(void)
{
return platform_driver_probe(&dw_mci_pltfm_driver, dw_mci_pltfm_probe);
}
static void __exit dw_mci_exit(void)
{
platform_driver_unregister(&dw_mci_pltfm_driver);
}
module_init(dw_mci_init);
module_exit(dw_mci_exit);
MODULE_DESCRIPTION("DW Multimedia Card Interface driver");
MODULE_AUTHOR("NXP Semiconductor VietNam");
MODULE_AUTHOR("Imagination Technologies Ltd");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
fxTHaxxorX/android_kernel_sony_msm8974 | drivers/media/dvb/frontends/dvb_dummy_fe.c | 5031 | 7065 | /*
* Driver for Dummy Frontend
*
* Written by Emard <emard@softhome.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.=
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/string.h>
#include <linux/slab.h>
#include "dvb_frontend.h"
#include "dvb_dummy_fe.h"
struct dvb_dummy_fe_state {
struct dvb_frontend frontend;
};
static int dvb_dummy_fe_read_status(struct dvb_frontend* fe, fe_status_t* status)
{
*status = FE_HAS_SIGNAL
| FE_HAS_CARRIER
| FE_HAS_VITERBI
| FE_HAS_SYNC
| FE_HAS_LOCK;
return 0;
}
static int dvb_dummy_fe_read_ber(struct dvb_frontend* fe, u32* ber)
{
*ber = 0;
return 0;
}
static int dvb_dummy_fe_read_signal_strength(struct dvb_frontend* fe, u16* strength)
{
*strength = 0;
return 0;
}
static int dvb_dummy_fe_read_snr(struct dvb_frontend* fe, u16* snr)
{
*snr = 0;
return 0;
}
static int dvb_dummy_fe_read_ucblocks(struct dvb_frontend* fe, u32* ucblocks)
{
*ucblocks = 0;
return 0;
}
/*
* Only needed if it actually reads something from the hardware
*/
static int dvb_dummy_fe_get_frontend(struct dvb_frontend *fe)
{
return 0;
}
static int dvb_dummy_fe_set_frontend(struct dvb_frontend *fe)
{
if (fe->ops.tuner_ops.set_params) {
fe->ops.tuner_ops.set_params(fe);
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 0);
}
return 0;
}
static int dvb_dummy_fe_sleep(struct dvb_frontend* fe)
{
return 0;
}
static int dvb_dummy_fe_init(struct dvb_frontend* fe)
{
return 0;
}
static int dvb_dummy_fe_set_tone(struct dvb_frontend* fe, fe_sec_tone_mode_t tone)
{
return 0;
}
static int dvb_dummy_fe_set_voltage(struct dvb_frontend* fe, fe_sec_voltage_t voltage)
{
return 0;
}
static void dvb_dummy_fe_release(struct dvb_frontend* fe)
{
struct dvb_dummy_fe_state* state = fe->demodulator_priv;
kfree(state);
}
static struct dvb_frontend_ops dvb_dummy_fe_ofdm_ops;
struct dvb_frontend* dvb_dummy_fe_ofdm_attach(void)
{
struct dvb_dummy_fe_state* state = NULL;
/* allocate memory for the internal state */
state = kzalloc(sizeof(struct dvb_dummy_fe_state), GFP_KERNEL);
if (state == NULL) goto error;
/* create dvb_frontend */
memcpy(&state->frontend.ops, &dvb_dummy_fe_ofdm_ops, sizeof(struct dvb_frontend_ops));
state->frontend.demodulator_priv = state;
return &state->frontend;
error:
kfree(state);
return NULL;
}
static struct dvb_frontend_ops dvb_dummy_fe_qpsk_ops;
struct dvb_frontend *dvb_dummy_fe_qpsk_attach(void)
{
struct dvb_dummy_fe_state* state = NULL;
/* allocate memory for the internal state */
state = kzalloc(sizeof(struct dvb_dummy_fe_state), GFP_KERNEL);
if (state == NULL) goto error;
/* create dvb_frontend */
memcpy(&state->frontend.ops, &dvb_dummy_fe_qpsk_ops, sizeof(struct dvb_frontend_ops));
state->frontend.demodulator_priv = state;
return &state->frontend;
error:
kfree(state);
return NULL;
}
static struct dvb_frontend_ops dvb_dummy_fe_qam_ops;
struct dvb_frontend *dvb_dummy_fe_qam_attach(void)
{
struct dvb_dummy_fe_state* state = NULL;
/* allocate memory for the internal state */
state = kzalloc(sizeof(struct dvb_dummy_fe_state), GFP_KERNEL);
if (state == NULL) goto error;
/* create dvb_frontend */
memcpy(&state->frontend.ops, &dvb_dummy_fe_qam_ops, sizeof(struct dvb_frontend_ops));
state->frontend.demodulator_priv = state;
return &state->frontend;
error:
kfree(state);
return NULL;
}
static struct dvb_frontend_ops dvb_dummy_fe_ofdm_ops = {
.delsys = { SYS_DVBT },
.info = {
.name = "Dummy DVB-T",
.frequency_min = 0,
.frequency_max = 863250000,
.frequency_stepsize = 62500,
.caps = FE_CAN_FEC_1_2 | FE_CAN_FEC_2_3 | FE_CAN_FEC_3_4 |
FE_CAN_FEC_4_5 | FE_CAN_FEC_5_6 | FE_CAN_FEC_6_7 |
FE_CAN_FEC_7_8 | FE_CAN_FEC_8_9 | FE_CAN_FEC_AUTO |
FE_CAN_QAM_16 | FE_CAN_QAM_64 | FE_CAN_QAM_AUTO |
FE_CAN_TRANSMISSION_MODE_AUTO |
FE_CAN_GUARD_INTERVAL_AUTO |
FE_CAN_HIERARCHY_AUTO,
},
.release = dvb_dummy_fe_release,
.init = dvb_dummy_fe_init,
.sleep = dvb_dummy_fe_sleep,
.set_frontend = dvb_dummy_fe_set_frontend,
.get_frontend = dvb_dummy_fe_get_frontend,
.read_status = dvb_dummy_fe_read_status,
.read_ber = dvb_dummy_fe_read_ber,
.read_signal_strength = dvb_dummy_fe_read_signal_strength,
.read_snr = dvb_dummy_fe_read_snr,
.read_ucblocks = dvb_dummy_fe_read_ucblocks,
};
static struct dvb_frontend_ops dvb_dummy_fe_qam_ops = {
.delsys = { SYS_DVBC_ANNEX_A },
.info = {
.name = "Dummy DVB-C",
.frequency_stepsize = 62500,
.frequency_min = 51000000,
.frequency_max = 858000000,
.symbol_rate_min = (57840000/2)/64, /* SACLK/64 == (XIN/2)/64 */
.symbol_rate_max = (57840000/2)/4, /* SACLK/4 */
.caps = FE_CAN_QAM_16 | FE_CAN_QAM_32 | FE_CAN_QAM_64 |
FE_CAN_QAM_128 | FE_CAN_QAM_256 |
FE_CAN_FEC_AUTO | FE_CAN_INVERSION_AUTO
},
.release = dvb_dummy_fe_release,
.init = dvb_dummy_fe_init,
.sleep = dvb_dummy_fe_sleep,
.set_frontend = dvb_dummy_fe_set_frontend,
.get_frontend = dvb_dummy_fe_get_frontend,
.read_status = dvb_dummy_fe_read_status,
.read_ber = dvb_dummy_fe_read_ber,
.read_signal_strength = dvb_dummy_fe_read_signal_strength,
.read_snr = dvb_dummy_fe_read_snr,
.read_ucblocks = dvb_dummy_fe_read_ucblocks,
};
static struct dvb_frontend_ops dvb_dummy_fe_qpsk_ops = {
.delsys = { SYS_DVBS },
.info = {
.name = "Dummy DVB-S",
.frequency_min = 950000,
.frequency_max = 2150000,
.frequency_stepsize = 250, /* kHz for QPSK frontends */
.frequency_tolerance = 29500,
.symbol_rate_min = 1000000,
.symbol_rate_max = 45000000,
.caps = FE_CAN_INVERSION_AUTO |
FE_CAN_FEC_1_2 | FE_CAN_FEC_2_3 | FE_CAN_FEC_3_4 |
FE_CAN_FEC_5_6 | FE_CAN_FEC_7_8 | FE_CAN_FEC_AUTO |
FE_CAN_QPSK
},
.release = dvb_dummy_fe_release,
.init = dvb_dummy_fe_init,
.sleep = dvb_dummy_fe_sleep,
.set_frontend = dvb_dummy_fe_set_frontend,
.get_frontend = dvb_dummy_fe_get_frontend,
.read_status = dvb_dummy_fe_read_status,
.read_ber = dvb_dummy_fe_read_ber,
.read_signal_strength = dvb_dummy_fe_read_signal_strength,
.read_snr = dvb_dummy_fe_read_snr,
.read_ucblocks = dvb_dummy_fe_read_ucblocks,
.set_voltage = dvb_dummy_fe_set_voltage,
.set_tone = dvb_dummy_fe_set_tone,
};
MODULE_DESCRIPTION("DVB DUMMY Frontend");
MODULE_AUTHOR("Emard");
MODULE_LICENSE("GPL");
EXPORT_SYMBOL(dvb_dummy_fe_ofdm_attach);
EXPORT_SYMBOL(dvb_dummy_fe_qam_attach);
EXPORT_SYMBOL(dvb_dummy_fe_qpsk_attach);
| gpl-2.0 |
iamthedarkone/Burst | arch/arm/common/time-acorn.c | 5031 | 2095 | /*
* linux/arch/arm/common/time-acorn.c
*
* Copyright (c) 1996-2000 Russell King.
*
* 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.
*
* Changelog:
* 24-Sep-1996 RMK Created
* 10-Oct-1996 RMK Brought up to date with arch-sa110eval
* 04-Dec-1997 RMK Updated for new arch/arm/time.c
* 13=Jun-2004 DS Moved to arch/arm/common b/c shared w/CLPS7500
*/
#include <linux/timex.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/io.h>
#include <mach/hardware.h>
#include <asm/hardware/ioc.h>
#include <asm/mach/time.h>
unsigned long ioc_timer_gettimeoffset(void)
{
unsigned int count1, count2, status;
long offset;
ioc_writeb (0, IOC_T0LATCH);
barrier ();
count1 = ioc_readb(IOC_T0CNTL) | (ioc_readb(IOC_T0CNTH) << 8);
barrier ();
status = ioc_readb(IOC_IRQREQA);
barrier ();
ioc_writeb (0, IOC_T0LATCH);
barrier ();
count2 = ioc_readb(IOC_T0CNTL) | (ioc_readb(IOC_T0CNTH) << 8);
offset = count2;
if (count2 < count1) {
/*
* We have not had an interrupt between reading count1
* and count2.
*/
if (status & (1 << 5))
offset -= LATCH;
} else if (count2 > count1) {
/*
* We have just had another interrupt between reading
* count1 and count2.
*/
offset -= LATCH;
}
offset = (LATCH - offset) * (tick_nsec / 1000);
return (offset + LATCH/2) / LATCH;
}
void __init ioctime_init(void)
{
ioc_writeb(LATCH & 255, IOC_T0LTCHL);
ioc_writeb(LATCH >> 8, IOC_T0LTCHH);
ioc_writeb(0, IOC_T0GO);
}
static irqreturn_t
ioc_timer_interrupt(int irq, void *dev_id)
{
timer_tick();
return IRQ_HANDLED;
}
static struct irqaction ioc_timer_irq = {
.name = "timer",
.flags = IRQF_DISABLED,
.handler = ioc_timer_interrupt
};
/*
* Set up timer interrupt.
*/
static void __init ioc_timer_init(void)
{
ioctime_init();
setup_irq(IRQ_TIMER, &ioc_timer_irq);
}
struct sys_timer ioc_timer = {
.init = ioc_timer_init,
.offset = ioc_timer_gettimeoffset,
};
| gpl-2.0 |
SlimKat-U8950/chil360-kernel | drivers/tty/serial/max3100.c | 5031 | 21761 | /*
*
* Copyright (C) 2008 Christian Pellegrin <chripell@evolware.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.
*
*
* Notes: the MAX3100 doesn't provide an interrupt on CTS so we have
* to use polling for flow control. TX empty IRQ is unusable, since
* writing conf clears FIFO buffer and we cannot have this interrupt
* always asking us for attention.
*
* Example platform data:
static struct plat_max3100 max3100_plat_data = {
.loopback = 0,
.crystal = 0,
.poll_time = 100,
};
static struct spi_board_info spi_board_info[] = {
{
.modalias = "max3100",
.platform_data = &max3100_plat_data,
.irq = IRQ_EINT12,
.max_speed_hz = 5*1000*1000,
.chip_select = 0,
},
};
* The initial minor number is 209 in the low-density serial port:
* mknod /dev/ttyMAX0 c 204 209
*/
#define MAX3100_MAJOR 204
#define MAX3100_MINOR 209
/* 4 MAX3100s should be enough for everyone */
#define MAX_MAX3100 4
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/device.h>
#include <linux/module.h>
#include <linux/serial_core.h>
#include <linux/serial.h>
#include <linux/spi/spi.h>
#include <linux/freezer.h>
#include <linux/tty.h>
#include <linux/tty_flip.h>
#include <linux/serial_max3100.h>
#define MAX3100_C (1<<14)
#define MAX3100_D (0<<14)
#define MAX3100_W (1<<15)
#define MAX3100_RX (0<<15)
#define MAX3100_WC (MAX3100_W | MAX3100_C)
#define MAX3100_RC (MAX3100_RX | MAX3100_C)
#define MAX3100_WD (MAX3100_W | MAX3100_D)
#define MAX3100_RD (MAX3100_RX | MAX3100_D)
#define MAX3100_CMD (3 << 14)
#define MAX3100_T (1<<14)
#define MAX3100_R (1<<15)
#define MAX3100_FEN (1<<13)
#define MAX3100_SHDN (1<<12)
#define MAX3100_TM (1<<11)
#define MAX3100_RM (1<<10)
#define MAX3100_PM (1<<9)
#define MAX3100_RAM (1<<8)
#define MAX3100_IR (1<<7)
#define MAX3100_ST (1<<6)
#define MAX3100_PE (1<<5)
#define MAX3100_L (1<<4)
#define MAX3100_BAUD (0xf)
#define MAX3100_TE (1<<10)
#define MAX3100_RAFE (1<<10)
#define MAX3100_RTS (1<<9)
#define MAX3100_CTS (1<<9)
#define MAX3100_PT (1<<8)
#define MAX3100_DATA (0xff)
#define MAX3100_RT (MAX3100_R | MAX3100_T)
#define MAX3100_RTC (MAX3100_RT | MAX3100_CTS | MAX3100_RAFE)
/* the following simulate a status reg for ignore_status_mask */
#define MAX3100_STATUS_PE 1
#define MAX3100_STATUS_FE 2
#define MAX3100_STATUS_OE 4
struct max3100_port {
struct uart_port port;
struct spi_device *spi;
int cts; /* last CTS received for flow ctrl */
int tx_empty; /* last TX empty bit */
spinlock_t conf_lock; /* shared data */
int conf_commit; /* need to make changes */
int conf; /* configuration for the MAX31000
* (bits 0-7, bits 8-11 are irqs) */
int rts_commit; /* need to change rts */
int rts; /* rts status */
int baud; /* current baud rate */
int parity; /* keeps track if we should send parity */
#define MAX3100_PARITY_ON 1
#define MAX3100_PARITY_ODD 2
#define MAX3100_7BIT 4
int rx_enabled; /* if we should rx chars */
int irq; /* irq assigned to the max3100 */
int minor; /* minor number */
int crystal; /* 1 if 3.6864Mhz crystal 0 for 1.8432 */
int loopback; /* 1 if we are in loopback mode */
/* for handling irqs: need workqueue since we do spi_sync */
struct workqueue_struct *workqueue;
struct work_struct work;
/* set to 1 to make the workhandler exit as soon as possible */
int force_end_work;
/* need to know we are suspending to avoid deadlock on workqueue */
int suspending;
/* hook for suspending MAX3100 via dedicated pin */
void (*max3100_hw_suspend) (int suspend);
/* poll time (in ms) for ctrl lines */
int poll_time;
/* and its timer */
struct timer_list timer;
};
static struct max3100_port *max3100s[MAX_MAX3100]; /* the chips */
static DEFINE_MUTEX(max3100s_lock); /* race on probe */
static int max3100_do_parity(struct max3100_port *s, u16 c)
{
int parity;
if (s->parity & MAX3100_PARITY_ODD)
parity = 1;
else
parity = 0;
if (s->parity & MAX3100_7BIT)
c &= 0x7f;
else
c &= 0xff;
parity = parity ^ (hweight8(c) & 1);
return parity;
}
static int max3100_check_parity(struct max3100_port *s, u16 c)
{
return max3100_do_parity(s, c) == ((c >> 8) & 1);
}
static void max3100_calc_parity(struct max3100_port *s, u16 *c)
{
if (s->parity & MAX3100_7BIT)
*c &= 0x7f;
else
*c &= 0xff;
if (s->parity & MAX3100_PARITY_ON)
*c |= max3100_do_parity(s, *c) << 8;
}
static void max3100_work(struct work_struct *w);
static void max3100_dowork(struct max3100_port *s)
{
if (!s->force_end_work && !work_pending(&s->work) &&
!freezing(current) && !s->suspending)
queue_work(s->workqueue, &s->work);
}
static void max3100_timeout(unsigned long data)
{
struct max3100_port *s = (struct max3100_port *)data;
if (s->port.state) {
max3100_dowork(s);
mod_timer(&s->timer, jiffies + s->poll_time);
}
}
static int max3100_sr(struct max3100_port *s, u16 tx, u16 *rx)
{
struct spi_message message;
u16 etx, erx;
int status;
struct spi_transfer tran = {
.tx_buf = &etx,
.rx_buf = &erx,
.len = 2,
};
etx = cpu_to_be16(tx);
spi_message_init(&message);
spi_message_add_tail(&tran, &message);
status = spi_sync(s->spi, &message);
if (status) {
dev_warn(&s->spi->dev, "error while calling spi_sync\n");
return -EIO;
}
*rx = be16_to_cpu(erx);
s->tx_empty = (*rx & MAX3100_T) > 0;
dev_dbg(&s->spi->dev, "%04x - %04x\n", tx, *rx);
return 0;
}
static int max3100_handlerx(struct max3100_port *s, u16 rx)
{
unsigned int ch, flg, status = 0;
int ret = 0, cts;
if (rx & MAX3100_R && s->rx_enabled) {
dev_dbg(&s->spi->dev, "%s\n", __func__);
ch = rx & (s->parity & MAX3100_7BIT ? 0x7f : 0xff);
if (rx & MAX3100_RAFE) {
s->port.icount.frame++;
flg = TTY_FRAME;
status |= MAX3100_STATUS_FE;
} else {
if (s->parity & MAX3100_PARITY_ON) {
if (max3100_check_parity(s, rx)) {
s->port.icount.rx++;
flg = TTY_NORMAL;
} else {
s->port.icount.parity++;
flg = TTY_PARITY;
status |= MAX3100_STATUS_PE;
}
} else {
s->port.icount.rx++;
flg = TTY_NORMAL;
}
}
uart_insert_char(&s->port, status, MAX3100_STATUS_OE, ch, flg);
ret = 1;
}
cts = (rx & MAX3100_CTS) > 0;
if (s->cts != cts) {
s->cts = cts;
uart_handle_cts_change(&s->port, cts ? TIOCM_CTS : 0);
}
return ret;
}
static void max3100_work(struct work_struct *w)
{
struct max3100_port *s = container_of(w, struct max3100_port, work);
int rxchars;
u16 tx, rx;
int conf, cconf, rts, crts;
struct circ_buf *xmit = &s->port.state->xmit;
dev_dbg(&s->spi->dev, "%s\n", __func__);
rxchars = 0;
do {
spin_lock(&s->conf_lock);
conf = s->conf;
cconf = s->conf_commit;
s->conf_commit = 0;
rts = s->rts;
crts = s->rts_commit;
s->rts_commit = 0;
spin_unlock(&s->conf_lock);
if (cconf)
max3100_sr(s, MAX3100_WC | conf, &rx);
if (crts) {
max3100_sr(s, MAX3100_WD | MAX3100_TE |
(s->rts ? MAX3100_RTS : 0), &rx);
rxchars += max3100_handlerx(s, rx);
}
max3100_sr(s, MAX3100_RD, &rx);
rxchars += max3100_handlerx(s, rx);
if (rx & MAX3100_T) {
tx = 0xffff;
if (s->port.x_char) {
tx = s->port.x_char;
s->port.icount.tx++;
s->port.x_char = 0;
} else if (!uart_circ_empty(xmit) &&
!uart_tx_stopped(&s->port)) {
tx = xmit->buf[xmit->tail];
xmit->tail = (xmit->tail + 1) &
(UART_XMIT_SIZE - 1);
s->port.icount.tx++;
}
if (tx != 0xffff) {
max3100_calc_parity(s, &tx);
tx |= MAX3100_WD | (s->rts ? MAX3100_RTS : 0);
max3100_sr(s, tx, &rx);
rxchars += max3100_handlerx(s, rx);
}
}
if (rxchars > 16 && s->port.state->port.tty != NULL) {
tty_flip_buffer_push(s->port.state->port.tty);
rxchars = 0;
}
if (uart_circ_chars_pending(xmit) < WAKEUP_CHARS)
uart_write_wakeup(&s->port);
} while (!s->force_end_work &&
!freezing(current) &&
((rx & MAX3100_R) ||
(!uart_circ_empty(xmit) &&
!uart_tx_stopped(&s->port))));
if (rxchars > 0 && s->port.state->port.tty != NULL)
tty_flip_buffer_push(s->port.state->port.tty);
}
static irqreturn_t max3100_irq(int irqno, void *dev_id)
{
struct max3100_port *s = dev_id;
dev_dbg(&s->spi->dev, "%s\n", __func__);
max3100_dowork(s);
return IRQ_HANDLED;
}
static void max3100_enable_ms(struct uart_port *port)
{
struct max3100_port *s = container_of(port,
struct max3100_port,
port);
if (s->poll_time > 0)
mod_timer(&s->timer, jiffies);
dev_dbg(&s->spi->dev, "%s\n", __func__);
}
static void max3100_start_tx(struct uart_port *port)
{
struct max3100_port *s = container_of(port,
struct max3100_port,
port);
dev_dbg(&s->spi->dev, "%s\n", __func__);
max3100_dowork(s);
}
static void max3100_stop_rx(struct uart_port *port)
{
struct max3100_port *s = container_of(port,
struct max3100_port,
port);
dev_dbg(&s->spi->dev, "%s\n", __func__);
s->rx_enabled = 0;
spin_lock(&s->conf_lock);
s->conf &= ~MAX3100_RM;
s->conf_commit = 1;
spin_unlock(&s->conf_lock);
max3100_dowork(s);
}
static unsigned int max3100_tx_empty(struct uart_port *port)
{
struct max3100_port *s = container_of(port,
struct max3100_port,
port);
dev_dbg(&s->spi->dev, "%s\n", __func__);
/* may not be truly up-to-date */
max3100_dowork(s);
return s->tx_empty;
}
static unsigned int max3100_get_mctrl(struct uart_port *port)
{
struct max3100_port *s = container_of(port,
struct max3100_port,
port);
dev_dbg(&s->spi->dev, "%s\n", __func__);
/* may not be truly up-to-date */
max3100_dowork(s);
/* always assert DCD and DSR since these lines are not wired */
return (s->cts ? TIOCM_CTS : 0) | TIOCM_DSR | TIOCM_CAR;
}
static void max3100_set_mctrl(struct uart_port *port, unsigned int mctrl)
{
struct max3100_port *s = container_of(port,
struct max3100_port,
port);
int rts;
dev_dbg(&s->spi->dev, "%s\n", __func__);
rts = (mctrl & TIOCM_RTS) > 0;
spin_lock(&s->conf_lock);
if (s->rts != rts) {
s->rts = rts;
s->rts_commit = 1;
max3100_dowork(s);
}
spin_unlock(&s->conf_lock);
}
static void
max3100_set_termios(struct uart_port *port, struct ktermios *termios,
struct ktermios *old)
{
struct max3100_port *s = container_of(port,
struct max3100_port,
port);
int baud = 0;
unsigned cflag;
u32 param_new, param_mask, parity = 0;
dev_dbg(&s->spi->dev, "%s\n", __func__);
cflag = termios->c_cflag;
param_new = 0;
param_mask = 0;
baud = tty_termios_baud_rate(termios);
param_new = s->conf & MAX3100_BAUD;
switch (baud) {
case 300:
if (s->crystal)
baud = s->baud;
else
param_new = 15;
break;
case 600:
param_new = 14 + s->crystal;
break;
case 1200:
param_new = 13 + s->crystal;
break;
case 2400:
param_new = 12 + s->crystal;
break;
case 4800:
param_new = 11 + s->crystal;
break;
case 9600:
param_new = 10 + s->crystal;
break;
case 19200:
param_new = 9 + s->crystal;
break;
case 38400:
param_new = 8 + s->crystal;
break;
case 57600:
param_new = 1 + s->crystal;
break;
case 115200:
param_new = 0 + s->crystal;
break;
case 230400:
if (s->crystal)
param_new = 0;
else
baud = s->baud;
break;
default:
baud = s->baud;
}
tty_termios_encode_baud_rate(termios, baud, baud);
s->baud = baud;
param_mask |= MAX3100_BAUD;
if ((cflag & CSIZE) == CS8) {
param_new &= ~MAX3100_L;
parity &= ~MAX3100_7BIT;
} else {
param_new |= MAX3100_L;
parity |= MAX3100_7BIT;
cflag = (cflag & ~CSIZE) | CS7;
}
param_mask |= MAX3100_L;
if (cflag & CSTOPB)
param_new |= MAX3100_ST;
else
param_new &= ~MAX3100_ST;
param_mask |= MAX3100_ST;
if (cflag & PARENB) {
param_new |= MAX3100_PE;
parity |= MAX3100_PARITY_ON;
} else {
param_new &= ~MAX3100_PE;
parity &= ~MAX3100_PARITY_ON;
}
param_mask |= MAX3100_PE;
if (cflag & PARODD)
parity |= MAX3100_PARITY_ODD;
else
parity &= ~MAX3100_PARITY_ODD;
/* mask termios capabilities we don't support */
cflag &= ~CMSPAR;
termios->c_cflag = cflag;
s->port.ignore_status_mask = 0;
if (termios->c_iflag & IGNPAR)
s->port.ignore_status_mask |=
MAX3100_STATUS_PE | MAX3100_STATUS_FE |
MAX3100_STATUS_OE;
/* we are sending char from a workqueue so enable */
s->port.state->port.tty->low_latency = 1;
if (s->poll_time > 0)
del_timer_sync(&s->timer);
uart_update_timeout(port, termios->c_cflag, baud);
spin_lock(&s->conf_lock);
s->conf = (s->conf & ~param_mask) | (param_new & param_mask);
s->conf_commit = 1;
s->parity = parity;
spin_unlock(&s->conf_lock);
max3100_dowork(s);
if (UART_ENABLE_MS(&s->port, termios->c_cflag))
max3100_enable_ms(&s->port);
}
static void max3100_shutdown(struct uart_port *port)
{
struct max3100_port *s = container_of(port,
struct max3100_port,
port);
dev_dbg(&s->spi->dev, "%s\n", __func__);
if (s->suspending)
return;
s->force_end_work = 1;
if (s->poll_time > 0)
del_timer_sync(&s->timer);
if (s->workqueue) {
flush_workqueue(s->workqueue);
destroy_workqueue(s->workqueue);
s->workqueue = NULL;
}
if (s->irq)
free_irq(s->irq, s);
/* set shutdown mode to save power */
if (s->max3100_hw_suspend)
s->max3100_hw_suspend(1);
else {
u16 tx, rx;
tx = MAX3100_WC | MAX3100_SHDN;
max3100_sr(s, tx, &rx);
}
}
static int max3100_startup(struct uart_port *port)
{
struct max3100_port *s = container_of(port,
struct max3100_port,
port);
char b[12];
dev_dbg(&s->spi->dev, "%s\n", __func__);
s->conf = MAX3100_RM;
s->baud = s->crystal ? 230400 : 115200;
s->rx_enabled = 1;
if (s->suspending)
return 0;
s->force_end_work = 0;
s->parity = 0;
s->rts = 0;
sprintf(b, "max3100-%d", s->minor);
s->workqueue = create_freezable_workqueue(b);
if (!s->workqueue) {
dev_warn(&s->spi->dev, "cannot create workqueue\n");
return -EBUSY;
}
INIT_WORK(&s->work, max3100_work);
if (request_irq(s->irq, max3100_irq,
IRQF_TRIGGER_FALLING, "max3100", s) < 0) {
dev_warn(&s->spi->dev, "cannot allocate irq %d\n", s->irq);
s->irq = 0;
destroy_workqueue(s->workqueue);
s->workqueue = NULL;
return -EBUSY;
}
if (s->loopback) {
u16 tx, rx;
tx = 0x4001;
max3100_sr(s, tx, &rx);
}
if (s->max3100_hw_suspend)
s->max3100_hw_suspend(0);
s->conf_commit = 1;
max3100_dowork(s);
/* wait for clock to settle */
msleep(50);
max3100_enable_ms(&s->port);
return 0;
}
static const char *max3100_type(struct uart_port *port)
{
struct max3100_port *s = container_of(port,
struct max3100_port,
port);
dev_dbg(&s->spi->dev, "%s\n", __func__);
return s->port.type == PORT_MAX3100 ? "MAX3100" : NULL;
}
static void max3100_release_port(struct uart_port *port)
{
struct max3100_port *s = container_of(port,
struct max3100_port,
port);
dev_dbg(&s->spi->dev, "%s\n", __func__);
}
static void max3100_config_port(struct uart_port *port, int flags)
{
struct max3100_port *s = container_of(port,
struct max3100_port,
port);
dev_dbg(&s->spi->dev, "%s\n", __func__);
if (flags & UART_CONFIG_TYPE)
s->port.type = PORT_MAX3100;
}
static int max3100_verify_port(struct uart_port *port,
struct serial_struct *ser)
{
struct max3100_port *s = container_of(port,
struct max3100_port,
port);
int ret = -EINVAL;
dev_dbg(&s->spi->dev, "%s\n", __func__);
if (ser->type == PORT_UNKNOWN || ser->type == PORT_MAX3100)
ret = 0;
return ret;
}
static void max3100_stop_tx(struct uart_port *port)
{
struct max3100_port *s = container_of(port,
struct max3100_port,
port);
dev_dbg(&s->spi->dev, "%s\n", __func__);
}
static int max3100_request_port(struct uart_port *port)
{
struct max3100_port *s = container_of(port,
struct max3100_port,
port);
dev_dbg(&s->spi->dev, "%s\n", __func__);
return 0;
}
static void max3100_break_ctl(struct uart_port *port, int break_state)
{
struct max3100_port *s = container_of(port,
struct max3100_port,
port);
dev_dbg(&s->spi->dev, "%s\n", __func__);
}
static struct uart_ops max3100_ops = {
.tx_empty = max3100_tx_empty,
.set_mctrl = max3100_set_mctrl,
.get_mctrl = max3100_get_mctrl,
.stop_tx = max3100_stop_tx,
.start_tx = max3100_start_tx,
.stop_rx = max3100_stop_rx,
.enable_ms = max3100_enable_ms,
.break_ctl = max3100_break_ctl,
.startup = max3100_startup,
.shutdown = max3100_shutdown,
.set_termios = max3100_set_termios,
.type = max3100_type,
.release_port = max3100_release_port,
.request_port = max3100_request_port,
.config_port = max3100_config_port,
.verify_port = max3100_verify_port,
};
static struct uart_driver max3100_uart_driver = {
.owner = THIS_MODULE,
.driver_name = "ttyMAX",
.dev_name = "ttyMAX",
.major = MAX3100_MAJOR,
.minor = MAX3100_MINOR,
.nr = MAX_MAX3100,
};
static int uart_driver_registered;
static int __devinit max3100_probe(struct spi_device *spi)
{
int i, retval;
struct plat_max3100 *pdata;
u16 tx, rx;
mutex_lock(&max3100s_lock);
if (!uart_driver_registered) {
uart_driver_registered = 1;
retval = uart_register_driver(&max3100_uart_driver);
if (retval) {
printk(KERN_ERR "Couldn't register max3100 uart driver\n");
mutex_unlock(&max3100s_lock);
return retval;
}
}
for (i = 0; i < MAX_MAX3100; i++)
if (!max3100s[i])
break;
if (i == MAX_MAX3100) {
dev_warn(&spi->dev, "too many MAX3100 chips\n");
mutex_unlock(&max3100s_lock);
return -ENOMEM;
}
max3100s[i] = kzalloc(sizeof(struct max3100_port), GFP_KERNEL);
if (!max3100s[i]) {
dev_warn(&spi->dev,
"kmalloc for max3100 structure %d failed!\n", i);
mutex_unlock(&max3100s_lock);
return -ENOMEM;
}
max3100s[i]->spi = spi;
max3100s[i]->irq = spi->irq;
spin_lock_init(&max3100s[i]->conf_lock);
dev_set_drvdata(&spi->dev, max3100s[i]);
pdata = spi->dev.platform_data;
max3100s[i]->crystal = pdata->crystal;
max3100s[i]->loopback = pdata->loopback;
max3100s[i]->poll_time = pdata->poll_time * HZ / 1000;
if (pdata->poll_time > 0 && max3100s[i]->poll_time == 0)
max3100s[i]->poll_time = 1;
max3100s[i]->max3100_hw_suspend = pdata->max3100_hw_suspend;
max3100s[i]->minor = i;
init_timer(&max3100s[i]->timer);
max3100s[i]->timer.function = max3100_timeout;
max3100s[i]->timer.data = (unsigned long) max3100s[i];
dev_dbg(&spi->dev, "%s: adding port %d\n", __func__, i);
max3100s[i]->port.irq = max3100s[i]->irq;
max3100s[i]->port.uartclk = max3100s[i]->crystal ? 3686400 : 1843200;
max3100s[i]->port.fifosize = 16;
max3100s[i]->port.ops = &max3100_ops;
max3100s[i]->port.flags = UPF_SKIP_TEST | UPF_BOOT_AUTOCONF;
max3100s[i]->port.line = i;
max3100s[i]->port.type = PORT_MAX3100;
max3100s[i]->port.dev = &spi->dev;
retval = uart_add_one_port(&max3100_uart_driver, &max3100s[i]->port);
if (retval < 0)
dev_warn(&spi->dev,
"uart_add_one_port failed for line %d with error %d\n",
i, retval);
/* set shutdown mode to save power. Will be woken-up on open */
if (max3100s[i]->max3100_hw_suspend)
max3100s[i]->max3100_hw_suspend(1);
else {
tx = MAX3100_WC | MAX3100_SHDN;
max3100_sr(max3100s[i], tx, &rx);
}
mutex_unlock(&max3100s_lock);
return 0;
}
static int __devexit max3100_remove(struct spi_device *spi)
{
struct max3100_port *s = dev_get_drvdata(&spi->dev);
int i;
mutex_lock(&max3100s_lock);
/* find out the index for the chip we are removing */
for (i = 0; i < MAX_MAX3100; i++)
if (max3100s[i] == s)
break;
dev_dbg(&spi->dev, "%s: removing port %d\n", __func__, i);
uart_remove_one_port(&max3100_uart_driver, &max3100s[i]->port);
kfree(max3100s[i]);
max3100s[i] = NULL;
/* check if this is the last chip we have */
for (i = 0; i < MAX_MAX3100; i++)
if (max3100s[i]) {
mutex_unlock(&max3100s_lock);
return 0;
}
pr_debug("removing max3100 driver\n");
uart_unregister_driver(&max3100_uart_driver);
mutex_unlock(&max3100s_lock);
return 0;
}
#ifdef CONFIG_PM
static int max3100_suspend(struct spi_device *spi, pm_message_t state)
{
struct max3100_port *s = dev_get_drvdata(&spi->dev);
dev_dbg(&s->spi->dev, "%s\n", __func__);
disable_irq(s->irq);
s->suspending = 1;
uart_suspend_port(&max3100_uart_driver, &s->port);
if (s->max3100_hw_suspend)
s->max3100_hw_suspend(1);
else {
/* no HW suspend, so do SW one */
u16 tx, rx;
tx = MAX3100_WC | MAX3100_SHDN;
max3100_sr(s, tx, &rx);
}
return 0;
}
static int max3100_resume(struct spi_device *spi)
{
struct max3100_port *s = dev_get_drvdata(&spi->dev);
dev_dbg(&s->spi->dev, "%s\n", __func__);
if (s->max3100_hw_suspend)
s->max3100_hw_suspend(0);
uart_resume_port(&max3100_uart_driver, &s->port);
s->suspending = 0;
enable_irq(s->irq);
s->conf_commit = 1;
if (s->workqueue)
max3100_dowork(s);
return 0;
}
#else
#define max3100_suspend NULL
#define max3100_resume NULL
#endif
static struct spi_driver max3100_driver = {
.driver = {
.name = "max3100",
.owner = THIS_MODULE,
},
.probe = max3100_probe,
.remove = __devexit_p(max3100_remove),
.suspend = max3100_suspend,
.resume = max3100_resume,
};
static int __init max3100_init(void)
{
return spi_register_driver(&max3100_driver);
}
module_init(max3100_init);
static void __exit max3100_exit(void)
{
spi_unregister_driver(&max3100_driver);
}
module_exit(max3100_exit);
MODULE_DESCRIPTION("MAX3100 driver");
MODULE_AUTHOR("Christian Pellegrin <chripell@evolware.org>");
MODULE_LICENSE("GPL");
MODULE_ALIAS("spi:max3100");
| gpl-2.0 |
cm-3470/android_kernel_samsung_gardalte | drivers/gpu/drm/ttm/ttm_lock.c | 6055 | 7397 | /**************************************************************************
*
* Copyright (c) 2007-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>
*/
#include "ttm/ttm_lock.h"
#include "ttm/ttm_module.h"
#include <linux/atomic.h>
#include <linux/errno.h>
#include <linux/wait.h>
#include <linux/sched.h>
#include <linux/module.h>
#define TTM_WRITE_LOCK_PENDING (1 << 0)
#define TTM_VT_LOCK_PENDING (1 << 1)
#define TTM_SUSPEND_LOCK_PENDING (1 << 2)
#define TTM_VT_LOCK (1 << 3)
#define TTM_SUSPEND_LOCK (1 << 4)
void ttm_lock_init(struct ttm_lock *lock)
{
spin_lock_init(&lock->lock);
init_waitqueue_head(&lock->queue);
lock->rw = 0;
lock->flags = 0;
lock->kill_takers = false;
lock->signal = SIGKILL;
}
EXPORT_SYMBOL(ttm_lock_init);
void ttm_read_unlock(struct ttm_lock *lock)
{
spin_lock(&lock->lock);
if (--lock->rw == 0)
wake_up_all(&lock->queue);
spin_unlock(&lock->lock);
}
EXPORT_SYMBOL(ttm_read_unlock);
static bool __ttm_read_lock(struct ttm_lock *lock)
{
bool locked = false;
spin_lock(&lock->lock);
if (unlikely(lock->kill_takers)) {
send_sig(lock->signal, current, 0);
spin_unlock(&lock->lock);
return false;
}
if (lock->rw >= 0 && lock->flags == 0) {
++lock->rw;
locked = true;
}
spin_unlock(&lock->lock);
return locked;
}
int ttm_read_lock(struct ttm_lock *lock, bool interruptible)
{
int ret = 0;
if (interruptible)
ret = wait_event_interruptible(lock->queue,
__ttm_read_lock(lock));
else
wait_event(lock->queue, __ttm_read_lock(lock));
return ret;
}
EXPORT_SYMBOL(ttm_read_lock);
static bool __ttm_read_trylock(struct ttm_lock *lock, bool *locked)
{
bool block = true;
*locked = false;
spin_lock(&lock->lock);
if (unlikely(lock->kill_takers)) {
send_sig(lock->signal, current, 0);
spin_unlock(&lock->lock);
return false;
}
if (lock->rw >= 0 && lock->flags == 0) {
++lock->rw;
block = false;
*locked = true;
} else if (lock->flags == 0) {
block = false;
}
spin_unlock(&lock->lock);
return !block;
}
int ttm_read_trylock(struct ttm_lock *lock, bool interruptible)
{
int ret = 0;
bool locked;
if (interruptible)
ret = wait_event_interruptible
(lock->queue, __ttm_read_trylock(lock, &locked));
else
wait_event(lock->queue, __ttm_read_trylock(lock, &locked));
if (unlikely(ret != 0)) {
BUG_ON(locked);
return ret;
}
return (locked) ? 0 : -EBUSY;
}
void ttm_write_unlock(struct ttm_lock *lock)
{
spin_lock(&lock->lock);
lock->rw = 0;
wake_up_all(&lock->queue);
spin_unlock(&lock->lock);
}
EXPORT_SYMBOL(ttm_write_unlock);
static bool __ttm_write_lock(struct ttm_lock *lock)
{
bool locked = false;
spin_lock(&lock->lock);
if (unlikely(lock->kill_takers)) {
send_sig(lock->signal, current, 0);
spin_unlock(&lock->lock);
return false;
}
if (lock->rw == 0 && ((lock->flags & ~TTM_WRITE_LOCK_PENDING) == 0)) {
lock->rw = -1;
lock->flags &= ~TTM_WRITE_LOCK_PENDING;
locked = true;
} else {
lock->flags |= TTM_WRITE_LOCK_PENDING;
}
spin_unlock(&lock->lock);
return locked;
}
int ttm_write_lock(struct ttm_lock *lock, bool interruptible)
{
int ret = 0;
if (interruptible) {
ret = wait_event_interruptible(lock->queue,
__ttm_write_lock(lock));
if (unlikely(ret != 0)) {
spin_lock(&lock->lock);
lock->flags &= ~TTM_WRITE_LOCK_PENDING;
wake_up_all(&lock->queue);
spin_unlock(&lock->lock);
}
} else
wait_event(lock->queue, __ttm_read_lock(lock));
return ret;
}
EXPORT_SYMBOL(ttm_write_lock);
void ttm_write_lock_downgrade(struct ttm_lock *lock)
{
spin_lock(&lock->lock);
lock->rw = 1;
wake_up_all(&lock->queue);
spin_unlock(&lock->lock);
}
static int __ttm_vt_unlock(struct ttm_lock *lock)
{
int ret = 0;
spin_lock(&lock->lock);
if (unlikely(!(lock->flags & TTM_VT_LOCK)))
ret = -EINVAL;
lock->flags &= ~TTM_VT_LOCK;
wake_up_all(&lock->queue);
spin_unlock(&lock->lock);
return ret;
}
static void ttm_vt_lock_remove(struct ttm_base_object **p_base)
{
struct ttm_base_object *base = *p_base;
struct ttm_lock *lock = container_of(base, struct ttm_lock, base);
int ret;
*p_base = NULL;
ret = __ttm_vt_unlock(lock);
BUG_ON(ret != 0);
}
static bool __ttm_vt_lock(struct ttm_lock *lock)
{
bool locked = false;
spin_lock(&lock->lock);
if (lock->rw == 0) {
lock->flags &= ~TTM_VT_LOCK_PENDING;
lock->flags |= TTM_VT_LOCK;
locked = true;
} else {
lock->flags |= TTM_VT_LOCK_PENDING;
}
spin_unlock(&lock->lock);
return locked;
}
int ttm_vt_lock(struct ttm_lock *lock,
bool interruptible,
struct ttm_object_file *tfile)
{
int ret = 0;
if (interruptible) {
ret = wait_event_interruptible(lock->queue,
__ttm_vt_lock(lock));
if (unlikely(ret != 0)) {
spin_lock(&lock->lock);
lock->flags &= ~TTM_VT_LOCK_PENDING;
wake_up_all(&lock->queue);
spin_unlock(&lock->lock);
return ret;
}
} else
wait_event(lock->queue, __ttm_vt_lock(lock));
/*
* Add a base-object, the destructor of which will
* make sure the lock is released if the client dies
* while holding it.
*/
ret = ttm_base_object_init(tfile, &lock->base, false,
ttm_lock_type, &ttm_vt_lock_remove, NULL);
if (ret)
(void)__ttm_vt_unlock(lock);
else
lock->vt_holder = tfile;
return ret;
}
EXPORT_SYMBOL(ttm_vt_lock);
int ttm_vt_unlock(struct ttm_lock *lock)
{
return ttm_ref_object_base_unref(lock->vt_holder,
lock->base.hash.key, TTM_REF_USAGE);
}
EXPORT_SYMBOL(ttm_vt_unlock);
void ttm_suspend_unlock(struct ttm_lock *lock)
{
spin_lock(&lock->lock);
lock->flags &= ~TTM_SUSPEND_LOCK;
wake_up_all(&lock->queue);
spin_unlock(&lock->lock);
}
EXPORT_SYMBOL(ttm_suspend_unlock);
static bool __ttm_suspend_lock(struct ttm_lock *lock)
{
bool locked = false;
spin_lock(&lock->lock);
if (lock->rw == 0) {
lock->flags &= ~TTM_SUSPEND_LOCK_PENDING;
lock->flags |= TTM_SUSPEND_LOCK;
locked = true;
} else {
lock->flags |= TTM_SUSPEND_LOCK_PENDING;
}
spin_unlock(&lock->lock);
return locked;
}
void ttm_suspend_lock(struct ttm_lock *lock)
{
wait_event(lock->queue, __ttm_suspend_lock(lock));
}
EXPORT_SYMBOL(ttm_suspend_lock);
| gpl-2.0 |
IonKiwi/android_kernel_samsung_kccat6 | fs/yaffs2/yaffs_nameval.c | 7847 | 4411 | /*
* YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
*
* Copyright (C) 2002-2010 Aleph One Ltd.
* for Toby Churchill Ltd and Brightstar Engineering
*
* Created by Charles Manning <charles@aleph1.co.uk>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/*
* This simple implementation of a name-value store assumes a small number of values and fits
* into a small finite buffer.
*
* Each attribute is stored as a record:
* sizeof(int) bytes record size.
* strnlen+1 bytes name null terminated.
* nbytes value.
* ----------
* total size stored in record size
*
* This code has not been tested with unicode yet.
*/
#include "yaffs_nameval.h"
#include "yportenv.h"
static int nval_find(const char *xb, int xb_size, const YCHAR * name,
int *exist_size)
{
int pos = 0;
int size;
memcpy(&size, xb, sizeof(int));
while (size > 0 && (size < xb_size) && (pos + size < xb_size)) {
if (strncmp
((YCHAR *) (xb + pos + sizeof(int)), name, size) == 0) {
if (exist_size)
*exist_size = size;
return pos;
}
pos += size;
if (pos < xb_size - sizeof(int))
memcpy(&size, xb + pos, sizeof(int));
else
size = 0;
}
if (exist_size)
*exist_size = 0;
return -1;
}
static int nval_used(const char *xb, int xb_size)
{
int pos = 0;
int size;
memcpy(&size, xb + pos, sizeof(int));
while (size > 0 && (size < xb_size) && (pos + size < xb_size)) {
pos += size;
if (pos < xb_size - sizeof(int))
memcpy(&size, xb + pos, sizeof(int));
else
size = 0;
}
return pos;
}
int nval_del(char *xb, int xb_size, const YCHAR * name)
{
int pos = nval_find(xb, xb_size, name, NULL);
int size;
if (pos >= 0 && pos < xb_size) {
/* Find size, shift rest over this record, then zero out the rest of buffer */
memcpy(&size, xb + pos, sizeof(int));
memcpy(xb + pos, xb + pos + size, xb_size - (pos + size));
memset(xb + (xb_size - size), 0, size);
return 0;
} else {
return -ENODATA;
}
}
int nval_set(char *xb, int xb_size, const YCHAR * name, const char *buf,
int bsize, int flags)
{
int pos;
int namelen = strnlen(name, xb_size);
int reclen;
int size_exist = 0;
int space;
int start;
pos = nval_find(xb, xb_size, name, &size_exist);
if (flags & XATTR_CREATE && pos >= 0)
return -EEXIST;
if (flags & XATTR_REPLACE && pos < 0)
return -ENODATA;
start = nval_used(xb, xb_size);
space = xb_size - start + size_exist;
reclen = (sizeof(int) + namelen + 1 + bsize);
if (reclen > space)
return -ENOSPC;
if (pos >= 0) {
nval_del(xb, xb_size, name);
start = nval_used(xb, xb_size);
}
pos = start;
memcpy(xb + pos, &reclen, sizeof(int));
pos += sizeof(int);
strncpy((YCHAR *) (xb + pos), name, reclen);
pos += (namelen + 1);
memcpy(xb + pos, buf, bsize);
return 0;
}
int nval_get(const char *xb, int xb_size, const YCHAR * name, char *buf,
int bsize)
{
int pos = nval_find(xb, xb_size, name, NULL);
int size;
if (pos >= 0 && pos < xb_size) {
memcpy(&size, xb + pos, sizeof(int));
pos += sizeof(int); /* advance past record length */
size -= sizeof(int);
/* Advance over name string */
while (xb[pos] && size > 0 && pos < xb_size) {
pos++;
size--;
}
/*Advance over NUL */
pos++;
size--;
if (size <= bsize) {
memcpy(buf, xb + pos, size);
return size;
}
}
if (pos >= 0)
return -ERANGE;
else
return -ENODATA;
}
int nval_list(const char *xb, int xb_size, char *buf, int bsize)
{
int pos = 0;
int size;
int name_len;
int ncopied = 0;
int filled = 0;
memcpy(&size, xb + pos, sizeof(int));
while (size > sizeof(int) && size <= xb_size && (pos + size) < xb_size
&& !filled) {
pos += sizeof(int);
size -= sizeof(int);
name_len = strnlen((YCHAR *) (xb + pos), size);
if (ncopied + name_len + 1 < bsize) {
memcpy(buf, xb + pos, name_len * sizeof(YCHAR));
buf += name_len;
*buf = '\0';
buf++;
if (sizeof(YCHAR) > 1) {
*buf = '\0';
buf++;
}
ncopied += (name_len + 1);
} else {
filled = 1;
}
pos += size;
if (pos < xb_size - sizeof(int))
memcpy(&size, xb + pos, sizeof(int));
else
size = 0;
}
return ncopied;
}
int nval_hasvalues(const char *xb, int xb_size)
{
return nval_used(xb, xb_size) > 0;
}
| gpl-2.0 |
ace8957/SeniorDesignKernel | arch/mips/math-emu/ieee754d.c | 10407 | 3739 | /*
* Some debug functions
*
* MIPS floating point support
*
* Copyright (C) 1994-2000 Algorithmics Ltd.
*
* This program is free software; you can distribute it and/or modify it
* under the terms of the GNU General Public License (Version 2) as
* published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston MA 02111-1307, USA.
*
* Nov 7, 2000
* Modified to build and operate in Linux kernel environment.
*
* Kevin D. Kissell, kevink@mips.com and Carsten Langgaard, carstenl@mips.com
* Copyright (C) 2000 MIPS Technologies, Inc. All rights reserved.
*/
#include <linux/kernel.h>
#include "ieee754.h"
#define DP_EBIAS 1023
#define DP_EMIN (-1022)
#define DP_EMAX 1023
#define DP_FBITS 52
#define SP_EBIAS 127
#define SP_EMIN (-126)
#define SP_EMAX 127
#define SP_FBITS 23
#define DP_MBIT(x) ((u64)1 << (x))
#define DP_HIDDEN_BIT DP_MBIT(DP_FBITS)
#define DP_SIGN_BIT DP_MBIT(63)
#define SP_MBIT(x) ((u32)1 << (x))
#define SP_HIDDEN_BIT SP_MBIT(SP_FBITS)
#define SP_SIGN_BIT SP_MBIT(31)
#define SPSIGN(sp) (sp.parts.sign)
#define SPBEXP(sp) (sp.parts.bexp)
#define SPMANT(sp) (sp.parts.mant)
#define DPSIGN(dp) (dp.parts.sign)
#define DPBEXP(dp) (dp.parts.bexp)
#define DPMANT(dp) (dp.parts.mant)
ieee754dp ieee754dp_dump(char *m, ieee754dp x)
{
int i;
printk("%s", m);
printk("<%08x,%08x>\n", (unsigned) (x.bits >> 32),
(unsigned) x.bits);
printk("\t=");
switch (ieee754dp_class(x)) {
case IEEE754_CLASS_QNAN:
case IEEE754_CLASS_SNAN:
printk("Nan %c", DPSIGN(x) ? '-' : '+');
for (i = DP_FBITS - 1; i >= 0; i--)
printk("%c", DPMANT(x) & DP_MBIT(i) ? '1' : '0');
break;
case IEEE754_CLASS_INF:
printk("%cInfinity", DPSIGN(x) ? '-' : '+');
break;
case IEEE754_CLASS_ZERO:
printk("%cZero", DPSIGN(x) ? '-' : '+');
break;
case IEEE754_CLASS_DNORM:
printk("%c0.", DPSIGN(x) ? '-' : '+');
for (i = DP_FBITS - 1; i >= 0; i--)
printk("%c", DPMANT(x) & DP_MBIT(i) ? '1' : '0');
printk("e%d", DPBEXP(x) - DP_EBIAS);
break;
case IEEE754_CLASS_NORM:
printk("%c1.", DPSIGN(x) ? '-' : '+');
for (i = DP_FBITS - 1; i >= 0; i--)
printk("%c", DPMANT(x) & DP_MBIT(i) ? '1' : '0');
printk("e%d", DPBEXP(x) - DP_EBIAS);
break;
default:
printk("Illegal/Unknown IEEE754 value class");
}
printk("\n");
return x;
}
ieee754sp ieee754sp_dump(char *m, ieee754sp x)
{
int i;
printk("%s=", m);
printk("<%08x>\n", (unsigned) x.bits);
printk("\t=");
switch (ieee754sp_class(x)) {
case IEEE754_CLASS_QNAN:
case IEEE754_CLASS_SNAN:
printk("Nan %c", SPSIGN(x) ? '-' : '+');
for (i = SP_FBITS - 1; i >= 0; i--)
printk("%c", SPMANT(x) & SP_MBIT(i) ? '1' : '0');
break;
case IEEE754_CLASS_INF:
printk("%cInfinity", SPSIGN(x) ? '-' : '+');
break;
case IEEE754_CLASS_ZERO:
printk("%cZero", SPSIGN(x) ? '-' : '+');
break;
case IEEE754_CLASS_DNORM:
printk("%c0.", SPSIGN(x) ? '-' : '+');
for (i = SP_FBITS - 1; i >= 0; i--)
printk("%c", SPMANT(x) & SP_MBIT(i) ? '1' : '0');
printk("e%d", SPBEXP(x) - SP_EBIAS);
break;
case IEEE754_CLASS_NORM:
printk("%c1.", SPSIGN(x) ? '-' : '+');
for (i = SP_FBITS - 1; i >= 0; i--)
printk("%c", SPMANT(x) & SP_MBIT(i) ? '1' : '0');
printk("e%d", SPBEXP(x) - SP_EBIAS);
break;
default:
printk("Illegal/Unknown IEEE754 value class");
}
printk("\n");
return x;
}
| gpl-2.0 |
scoty755/android_kernel_lge_msm8974 | arch/powerpc/math-emu/fmsubs.c | 13735 | 1154 | #include <linux/types.h>
#include <linux/errno.h>
#include <asm/uaccess.h>
#include <asm/sfp-machine.h>
#include <math-emu/soft-fp.h>
#include <math-emu/double.h>
#include <math-emu/single.h>
int
fmsubs(void *frD, void *frA, void *frB, void *frC)
{
FP_DECL_D(R);
FP_DECL_D(A);
FP_DECL_D(B);
FP_DECL_D(C);
FP_DECL_D(T);
FP_DECL_EX;
#ifdef DEBUG
printk("%s: %p %p %p %p\n", __func__, frD, frA, frB, frC);
#endif
FP_UNPACK_DP(A, frA);
FP_UNPACK_DP(B, frB);
FP_UNPACK_DP(C, frC);
#ifdef DEBUG
printk("A: %ld %lu %lu %ld (%ld)\n", A_s, A_f1, A_f0, A_e, A_c);
printk("B: %ld %lu %lu %ld (%ld)\n", B_s, B_f1, B_f0, B_e, B_c);
printk("C: %ld %lu %lu %ld (%ld)\n", C_s, C_f1, C_f0, C_e, C_c);
#endif
if ((A_c == FP_CLS_INF && C_c == FP_CLS_ZERO) ||
(A_c == FP_CLS_ZERO && C_c == FP_CLS_INF))
FP_SET_EXCEPTION(EFLAG_VXIMZ);
FP_MUL_D(T, A, C);
if (B_c != FP_CLS_NAN)
B_s ^= 1;
if (T_s != B_s && T_c == FP_CLS_INF && B_c == FP_CLS_INF)
FP_SET_EXCEPTION(EFLAG_VXISI);
FP_ADD_D(R, T, B);
#ifdef DEBUG
printk("D: %ld %lu %lu %ld (%ld)\n", R_s, R_f1, R_f0, R_e, R_c);
#endif
__FP_PACK_DS(frD, R);
return FP_CUR_EXCEPTIONS;
}
| gpl-2.0 |
Loller79/Solid_Kernel-STOCK-KK-CAF | arch/powerpc/math-emu/fmadd.c | 13735 | 1100 | #include <linux/types.h>
#include <linux/errno.h>
#include <asm/uaccess.h>
#include <asm/sfp-machine.h>
#include <math-emu/soft-fp.h>
#include <math-emu/double.h>
int
fmadd(void *frD, void *frA, void *frB, void *frC)
{
FP_DECL_D(R);
FP_DECL_D(A);
FP_DECL_D(B);
FP_DECL_D(C);
FP_DECL_D(T);
FP_DECL_EX;
#ifdef DEBUG
printk("%s: %p %p %p %p\n", __func__, frD, frA, frB, frC);
#endif
FP_UNPACK_DP(A, frA);
FP_UNPACK_DP(B, frB);
FP_UNPACK_DP(C, frC);
#ifdef DEBUG
printk("A: %ld %lu %lu %ld (%ld)\n", A_s, A_f1, A_f0, A_e, A_c);
printk("B: %ld %lu %lu %ld (%ld)\n", B_s, B_f1, B_f0, B_e, B_c);
printk("C: %ld %lu %lu %ld (%ld)\n", C_s, C_f1, C_f0, C_e, C_c);
#endif
if ((A_c == FP_CLS_INF && C_c == FP_CLS_ZERO) ||
(A_c == FP_CLS_ZERO && C_c == FP_CLS_INF))
FP_SET_EXCEPTION(EFLAG_VXIMZ);
FP_MUL_D(T, A, C);
if (T_s != B_s && T_c == FP_CLS_INF && B_c == FP_CLS_INF)
FP_SET_EXCEPTION(EFLAG_VXISI);
FP_ADD_D(R, T, B);
#ifdef DEBUG
printk("D: %ld %lu %lu %ld (%ld)\n", R_s, R_f1, R_f0, R_e, R_c);
#endif
__FP_PACK_D(frD, R);
return FP_CUR_EXCEPTIONS;
}
| gpl-2.0 |
mparus/android_kernel_huawei_msm8916_g760 | net/mac80211/michael.c | 15015 | 2237 | /*
* Michael MIC implementation - optimized for TKIP MIC operations
* Copyright 2002-2003, Instant802 Networks, 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/types.h>
#include <linux/bitops.h>
#include <linux/ieee80211.h>
#include <asm/unaligned.h>
#include "michael.h"
static void michael_block(struct michael_mic_ctx *mctx, u32 val)
{
mctx->l ^= val;
mctx->r ^= rol32(mctx->l, 17);
mctx->l += mctx->r;
mctx->r ^= ((mctx->l & 0xff00ff00) >> 8) |
((mctx->l & 0x00ff00ff) << 8);
mctx->l += mctx->r;
mctx->r ^= rol32(mctx->l, 3);
mctx->l += mctx->r;
mctx->r ^= ror32(mctx->l, 2);
mctx->l += mctx->r;
}
static void michael_mic_hdr(struct michael_mic_ctx *mctx, const u8 *key,
struct ieee80211_hdr *hdr)
{
u8 *da, *sa, tid;
da = ieee80211_get_DA(hdr);
sa = ieee80211_get_SA(hdr);
if (ieee80211_is_data_qos(hdr->frame_control))
tid = *ieee80211_get_qos_ctl(hdr) & IEEE80211_QOS_CTL_TID_MASK;
else
tid = 0;
mctx->l = get_unaligned_le32(key);
mctx->r = get_unaligned_le32(key + 4);
/*
* A pseudo header (DA, SA, Priority, 0, 0, 0) is used in Michael MIC
* calculation, but it is _not_ transmitted
*/
michael_block(mctx, get_unaligned_le32(da));
michael_block(mctx, get_unaligned_le16(&da[4]) |
(get_unaligned_le16(sa) << 16));
michael_block(mctx, get_unaligned_le32(&sa[2]));
michael_block(mctx, tid);
}
void michael_mic(const u8 *key, struct ieee80211_hdr *hdr,
const u8 *data, size_t data_len, u8 *mic)
{
u32 val;
size_t block, blocks, left;
struct michael_mic_ctx mctx;
michael_mic_hdr(&mctx, key, hdr);
/* Real data */
blocks = data_len / 4;
left = data_len % 4;
for (block = 0; block < blocks; block++)
michael_block(&mctx, get_unaligned_le32(&data[block * 4]));
/* Partial block of 0..3 bytes and padding: 0x5a + 4..7 zeros to make
* total length a multiple of 4. */
val = 0x5a;
while (left > 0) {
val <<= 8;
left--;
val |= data[blocks * 4 + left];
}
michael_block(&mctx, val);
michael_block(&mctx, 0);
put_unaligned_le32(mctx.l, mic);
put_unaligned_le32(mctx.r, mic + 4);
}
| gpl-2.0 |
onejay09/kernel_HTC_msm7x30_KK | kernel/time/timer_stats.c | 168 | 12072 | /*
* kernel/time/timer_stats.c
*
* Collect timer usage statistics.
*
* Copyright(C) 2006, Red Hat, Inc., Ingo Molnar
* Copyright(C) 2006 Timesys Corp., Thomas Gleixner <tglx@timesys.com>
*
* timer_stats is based on timer_top, a similar functionality which was part of
* Con Kolivas dyntick patch set. It was developed by Daniel Petrini at the
* Instituto Nokia de Tecnologia - INdT - Manaus. timer_top's design was based
* on dynamic allocation of the statistics entries and linear search based
* lookup combined with a global lock, rather than the static array, hash
* and per-CPU locking which is used by timer_stats. It was written for the
* pre hrtimer kernel code and therefore did not take hrtimers into account.
* Nevertheless it provided the base for the timer_stats implementation and
* was a helpful source of inspiration. Kudos to Daniel and the Nokia folks
* for this effort.
*
* timer_top.c is
* Copyright (C) 2005 Instituto Nokia de Tecnologia - INdT - Manaus
* Written by Daniel Petrini <d.pensator@gmail.com>
* timer_top.c was released under the GNU General Public License version 2
*
* We export the addresses and counting of timer functions being called,
* the pid and cmdline from the owner process if applicable.
*
* Start/stop data collection:
* # echo [1|0] >/proc/timer_stats
*
* Display the information collected so far:
* # cat /proc/timer_stats
*
* 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/proc_fs.h>
#include <linux/module.h>
#include <linux/spinlock.h>
#include <linux/sched.h>
#include <linux/seq_file.h>
#include <linux/kallsyms.h>
#include <asm/uaccess.h>
/*
* This is our basic unit of interest: a timer expiry event identified
* by the timer, its start/expire functions and the PID of the task that
* started the timer. We count the number of times an event happens:
*/
struct entry {
/*
* Hash list:
*/
struct entry *next;
/*
* Hash keys:
*/
void *timer;
void *start_func;
void *expire_func;
pid_t pid;
/*
* Number of timeout events:
*/
unsigned long count;
unsigned int timer_flag;
/*
* We save the command-line string to preserve
* this information past task exit:
*/
char comm[TASK_COMM_LEN + 1];
} ____cacheline_aligned_in_smp;
/*
* Spinlock protecting the tables - not taken during lookup:
*/
static DEFINE_SPINLOCK(table_lock);
/*
* Per-CPU lookup locks for fast hash lookup:
*/
static DEFINE_PER_CPU(raw_spinlock_t, tstats_lookup_lock);
/*
* Mutex to serialize state changes with show-stats activities:
*/
static DEFINE_MUTEX(show_mutex);
/*
* Collection status, active/inactive:
*/
int __read_mostly timer_stats_active;
/*
* Beginning/end timestamps of measurement:
*/
static ktime_t time_start, time_stop;
/*
* tstat entry structs only get allocated while collection is
* active and never freed during that time - this simplifies
* things quite a bit.
*
* They get freed when a new collection period is started.
*/
#define MAX_ENTRIES_BITS 10
#define MAX_ENTRIES (1UL << MAX_ENTRIES_BITS)
static unsigned long nr_entries;
static struct entry entries[MAX_ENTRIES];
static atomic_t overflow_count;
/*
* The entries are in a hash-table, for fast lookup:
*/
#define TSTAT_HASH_BITS (MAX_ENTRIES_BITS - 1)
#define TSTAT_HASH_SIZE (1UL << TSTAT_HASH_BITS)
#define TSTAT_HASH_MASK (TSTAT_HASH_SIZE - 1)
#define __tstat_hashfn(entry) \
(((unsigned long)(entry)->timer ^ \
(unsigned long)(entry)->start_func ^ \
(unsigned long)(entry)->expire_func ^ \
(unsigned long)(entry)->pid ) & TSTAT_HASH_MASK)
#define tstat_hashentry(entry) (tstat_hash_table + __tstat_hashfn(entry))
static struct entry *tstat_hash_table[TSTAT_HASH_SIZE] __read_mostly;
static void reset_entries(void)
{
nr_entries = 0;
memset(entries, 0, sizeof(entries));
memset(tstat_hash_table, 0, sizeof(tstat_hash_table));
atomic_set(&overflow_count, 0);
}
static struct entry *alloc_entry(void)
{
if (nr_entries >= MAX_ENTRIES)
return NULL;
return entries + nr_entries++;
}
static int match_entries(struct entry *entry1, struct entry *entry2)
{
return entry1->timer == entry2->timer &&
entry1->start_func == entry2->start_func &&
entry1->expire_func == entry2->expire_func &&
entry1->pid == entry2->pid;
}
/*
* Look up whether an entry matching this item is present
* in the hash already. Must be called with irqs off and the
* lookup lock held:
*/
static struct entry *tstat_lookup(struct entry *entry, char *comm)
{
struct entry **head, *curr, *prev;
head = tstat_hashentry(entry);
curr = *head;
/*
* The fastpath is when the entry is already hashed,
* we do this with the lookup lock held, but with the
* table lock not held:
*/
while (curr) {
if (match_entries(curr, entry))
return curr;
curr = curr->next;
}
/*
* Slowpath: allocate, set up and link a new hash entry:
*/
prev = NULL;
curr = *head;
spin_lock(&table_lock);
/*
* Make sure we have not raced with another CPU:
*/
while (curr) {
if (match_entries(curr, entry))
goto out_unlock;
prev = curr;
curr = curr->next;
}
curr = alloc_entry();
if (curr) {
*curr = *entry;
curr->count = 0;
curr->next = NULL;
memcpy(curr->comm, comm, TASK_COMM_LEN);
smp_mb(); /* Ensure that curr is initialized before insert */
if (prev)
prev->next = curr;
else
*head = curr;
}
out_unlock:
spin_unlock(&table_lock);
return curr;
}
/**
* timer_stats_update_stats - Update the statistics for a timer.
* @timer: pointer to either a timer_list or a hrtimer
* @pid: the pid of the task which set up the timer
* @startf: pointer to the function which did the timer setup
* @timerf: pointer to the timer callback function of the timer
* @comm: name of the process which set up the timer
*
* When the timer is already registered, then the event counter is
* incremented. Otherwise the timer is registered in a free slot.
*/
void timer_stats_update_stats(void *timer, pid_t pid, void *startf,
void *timerf, char *comm,
unsigned int timer_flag)
{
/*
* It doesn't matter which lock we take:
*/
raw_spinlock_t *lock;
struct entry *entry, input;
unsigned long flags;
if (likely(!timer_stats_active))
return;
lock = &per_cpu(tstats_lookup_lock, raw_smp_processor_id());
input.timer = timer;
input.start_func = startf;
input.expire_func = timerf;
input.pid = pid;
input.timer_flag = timer_flag;
raw_spin_lock_irqsave(lock, flags);
if (!timer_stats_active)
goto out_unlock;
entry = tstat_lookup(&input, comm);
if (likely(entry))
entry->count++;
else
atomic_inc(&overflow_count);
out_unlock:
raw_spin_unlock_irqrestore(lock, flags);
}
static void print_name_offset(struct seq_file *m, unsigned long addr)
{
char symname[KSYM_NAME_LEN];
if (lookup_symbol_name(addr, symname) < 0)
seq_printf(m, "<%p>", (void *)addr);
else
seq_printf(m, "%s", symname);
}
static int tstats_show(struct seq_file *m, void *v)
{
struct timespec period;
struct entry *entry;
unsigned long ms;
long events = 0;
ktime_t time;
int i;
mutex_lock(&show_mutex);
/*
* If still active then calculate up to now:
*/
if (timer_stats_active)
time_stop = ktime_get();
time = ktime_sub(time_stop, time_start);
period = ktime_to_timespec(time);
ms = period.tv_nsec / 1000000;
seq_puts(m, "Timer Stats Version: v0.2\n");
seq_printf(m, "Sample period: %ld.%03ld s\n", period.tv_sec, ms);
if (atomic_read(&overflow_count))
seq_printf(m, "Overflow: %d entries\n",
atomic_read(&overflow_count));
for (i = 0; i < nr_entries; i++) {
entry = entries + i;
if (entry->timer_flag & TIMER_STATS_FLAG_DEFERRABLE) {
seq_printf(m, "%4luD, %5d %-16s ",
entry->count, entry->pid, entry->comm);
} else {
seq_printf(m, " %4lu, %5d %-16s ",
entry->count, entry->pid, entry->comm);
}
print_name_offset(m, (unsigned long)entry->start_func);
seq_puts(m, " (");
print_name_offset(m, (unsigned long)entry->expire_func);
seq_puts(m, ")\n");
events += entry->count;
}
ms += period.tv_sec * 1000;
if (!ms)
ms = 1;
if (events && period.tv_sec)
seq_printf(m, "%ld total events, %ld.%03ld events/sec\n",
events, events * 1000 / ms,
(events * 1000000 / ms) % 1000);
else
seq_printf(m, "%ld total events\n", events);
mutex_unlock(&show_mutex);
return 0;
}
#if defined(CONFIG_ARCH_MSM8X60_LTE) || defined(CONFIG_ARCH_MSM7X27)
void htc_prink_name_offset(unsigned long addr)
{
char symname[KSYM_NAME_LEN];
if (lookup_symbol_name(addr, symname) < 0)
printk("<%p>", (void *)addr);
else
printk("%s", symname);
}
void htc_timer_stats_show(u16 water_mark)
{
struct timespec period;
struct entry *entry;
unsigned long ms;
long events = 0;
ktime_t time;
int i;
mutex_lock(&show_mutex);
/*
* If still active then calculate up to now:
*/
if (timer_stats_active)
time_stop = ktime_get();
time = ktime_sub(time_stop, time_start);
period = ktime_to_timespec(time);
ms = period.tv_nsec / 1000000;
for (i = 0; i < nr_entries; i++) {
entry = entries + i;
events += entry->count;
if (entry->count < water_mark)
continue;
if (entry->timer_flag & TIMER_STATS_FLAG_DEFERRABLE) {
printk("%4luD, %5d %-16s ",
entry->count, entry->pid, entry->comm);
} else {
printk(" %4lu, %5d %-16s ",
entry->count, entry->pid, entry->comm);
}
htc_prink_name_offset((unsigned long)entry->start_func);
printk(" (");
htc_prink_name_offset((unsigned long)entry->expire_func);
printk(")\n");
}
ms += period.tv_sec * 1000;
if (!ms)
ms = 1;
if (events && period.tv_sec)
printk("%ld total events, %ld.%03ld events/sec\n",
events, events * 1000 / ms,
(events * 1000000 / ms) % 1000);
else
printk("%ld total events\n", events);
mutex_unlock(&show_mutex);
}
#endif
/*
* After a state change, make sure all concurrent lookup/update
* activities have stopped:
*/
static void sync_access(void)
{
unsigned long flags;
int cpu;
for_each_online_cpu(cpu) {
raw_spinlock_t *lock = &per_cpu(tstats_lookup_lock, cpu);
raw_spin_lock_irqsave(lock, flags);
/* nothing */
raw_spin_unlock_irqrestore(lock, flags);
}
}
static ssize_t tstats_write(struct file *file, const char __user *buf,
size_t count, loff_t *offs)
{
char ctl[2];
if (count != 2 || *offs)
return -EINVAL;
if (copy_from_user(ctl, buf, count))
return -EFAULT;
mutex_lock(&show_mutex);
switch (ctl[0]) {
case '0':
if (timer_stats_active) {
timer_stats_active = 0;
time_stop = ktime_get();
sync_access();
}
break;
case '1':
if (!timer_stats_active) {
reset_entries();
time_start = ktime_get();
smp_mb();
timer_stats_active = 1;
}
break;
default:
count = -EINVAL;
}
mutex_unlock(&show_mutex);
return count;
}
#if defined(CONFIG_ARCH_MSM8X60_LTE) || defined(CONFIG_ARCH_MSM7X27)
void htc_timer_stats_OnOff(char OnOff)
{
mutex_lock(&show_mutex);
switch (OnOff) {
case '0':
if (timer_stats_active) {
timer_stats_active = 0;
time_stop = ktime_get();
sync_access();
}
break;
case '1':
if (!timer_stats_active) {
reset_entries();
time_start = ktime_get();
smp_mb();
timer_stats_active = 1;
}
break;
default:
break;
}
mutex_unlock(&show_mutex);
}
#endif
static int tstats_open(struct inode *inode, struct file *filp)
{
return single_open(filp, tstats_show, NULL);
}
static const struct file_operations tstats_fops = {
.open = tstats_open,
.read = seq_read,
.write = tstats_write,
.llseek = seq_lseek,
.release = single_release,
};
void __init init_timer_stats(void)
{
int cpu;
for_each_possible_cpu(cpu)
raw_spin_lock_init(&per_cpu(tstats_lookup_lock, cpu));
}
static int __init init_tstats_procfs(void)
{
struct proc_dir_entry *pe;
pe = proc_create("timer_stats", 0644, NULL, &tstats_fops);
if (!pe)
return -ENOMEM;
return 0;
}
__initcall(init_tstats_procfs);
| gpl-2.0 |
Haderach/linux-mirror | drivers/staging/iio/meter/ade7753.c | 168 | 12686 | /*
* ADE7753 Single-Phase Multifunction Metering IC with di/dt Sensor Interface
*
* Copyright 2010 Analog Devices Inc.
*
* Licensed under the GPL-2 or later.
*/
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/delay.h>
#include <linux/mutex.h>
#include <linux/device.h>
#include <linux/kernel.h>
#include <linux/spi/spi.h>
#include <linux/slab.h>
#include <linux/sysfs.h>
#include <linux/list.h>
#include <linux/module.h>
#include <linux/iio/iio.h>
#include <linux/iio/sysfs.h>
#include "meter.h"
#include "ade7753.h"
static int ade7753_spi_write_reg_8(struct device *dev,
u8 reg_address,
u8 val)
{
int ret;
struct iio_dev *indio_dev = dev_to_iio_dev(dev);
struct ade7753_state *st = iio_priv(indio_dev);
mutex_lock(&st->buf_lock);
st->tx[0] = ADE7753_WRITE_REG(reg_address);
st->tx[1] = val;
ret = spi_write(st->us, st->tx, 2);
mutex_unlock(&st->buf_lock);
return ret;
}
static int ade7753_spi_write_reg_16(struct device *dev,
u8 reg_address,
u16 value)
{
int ret;
struct iio_dev *indio_dev = dev_to_iio_dev(dev);
struct ade7753_state *st = iio_priv(indio_dev);
mutex_lock(&st->buf_lock);
st->tx[0] = ADE7753_WRITE_REG(reg_address);
st->tx[1] = (value >> 8) & 0xFF;
st->tx[2] = value & 0xFF;
ret = spi_write(st->us, st->tx, 3);
mutex_unlock(&st->buf_lock);
return ret;
}
static int ade7753_spi_read_reg_8(struct device *dev,
u8 reg_address,
u8 *val)
{
struct iio_dev *indio_dev = dev_to_iio_dev(dev);
struct ade7753_state *st = iio_priv(indio_dev);
ssize_t ret;
ret = spi_w8r8(st->us, ADE7753_READ_REG(reg_address));
if (ret < 0) {
dev_err(&st->us->dev, "problem when reading 8 bit register 0x%02X",
reg_address);
return ret;
}
*val = ret;
return 0;
}
static int ade7753_spi_read_reg_16(struct device *dev,
u8 reg_address,
u16 *val)
{
struct iio_dev *indio_dev = dev_to_iio_dev(dev);
struct ade7753_state *st = iio_priv(indio_dev);
ssize_t ret;
ret = spi_w8r16be(st->us, ADE7753_READ_REG(reg_address));
if (ret < 0) {
dev_err(&st->us->dev, "problem when reading 16 bit register 0x%02X",
reg_address);
return ret;
}
*val = ret;
return 0;
}
static int ade7753_spi_read_reg_24(struct device *dev,
u8 reg_address,
u32 *val)
{
struct iio_dev *indio_dev = dev_to_iio_dev(dev);
struct ade7753_state *st = iio_priv(indio_dev);
int ret;
struct spi_transfer xfers[] = {
{
.tx_buf = st->tx,
.bits_per_word = 8,
.len = 1,
}, {
.rx_buf = st->tx,
.bits_per_word = 8,
.len = 3,
}
};
mutex_lock(&st->buf_lock);
st->tx[0] = ADE7753_READ_REG(reg_address);
ret = spi_sync_transfer(st->us, xfers, ARRAY_SIZE(xfers));
if (ret) {
dev_err(&st->us->dev, "problem when reading 24 bit register 0x%02X",
reg_address);
goto error_ret;
}
*val = (st->rx[0] << 16) | (st->rx[1] << 8) | st->rx[2];
error_ret:
mutex_unlock(&st->buf_lock);
return ret;
}
static ssize_t ade7753_read_8bit(struct device *dev,
struct device_attribute *attr,
char *buf)
{
int ret;
u8 val;
struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
ret = ade7753_spi_read_reg_8(dev, this_attr->address, &val);
if (ret)
return ret;
return sprintf(buf, "%u\n", val);
}
static ssize_t ade7753_read_16bit(struct device *dev,
struct device_attribute *attr,
char *buf)
{
int ret;
u16 val;
struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
ret = ade7753_spi_read_reg_16(dev, this_attr->address, &val);
if (ret)
return ret;
return sprintf(buf, "%u\n", val);
}
static ssize_t ade7753_read_24bit(struct device *dev,
struct device_attribute *attr,
char *buf)
{
int ret;
u32 val;
struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
ret = ade7753_spi_read_reg_24(dev, this_attr->address, &val);
if (ret)
return ret;
return sprintf(buf, "%u\n", val);
}
static ssize_t ade7753_write_8bit(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
int ret;
u8 val;
ret = kstrtou8(buf, 10, &val);
if (ret)
goto error_ret;
ret = ade7753_spi_write_reg_8(dev, this_attr->address, val);
error_ret:
return ret ? ret : len;
}
static ssize_t ade7753_write_16bit(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
int ret;
u16 val;
ret = kstrtou16(buf, 10, &val);
if (ret)
goto error_ret;
ret = ade7753_spi_write_reg_16(dev, this_attr->address, val);
error_ret:
return ret ? ret : len;
}
static int ade7753_reset(struct device *dev)
{
u16 val;
ade7753_spi_read_reg_16(dev, ADE7753_MODE, &val);
val |= BIT(6); /* Software Chip Reset */
return ade7753_spi_write_reg_16(dev, ADE7753_MODE, val);
}
static IIO_DEV_ATTR_AENERGY(ade7753_read_24bit, ADE7753_AENERGY);
static IIO_DEV_ATTR_LAENERGY(ade7753_read_24bit, ADE7753_LAENERGY);
static IIO_DEV_ATTR_VAENERGY(ade7753_read_24bit, ADE7753_VAENERGY);
static IIO_DEV_ATTR_LVAENERGY(ade7753_read_24bit, ADE7753_LVAENERGY);
static IIO_DEV_ATTR_CFDEN(S_IWUSR | S_IRUGO,
ade7753_read_16bit,
ade7753_write_16bit,
ADE7753_CFDEN);
static IIO_DEV_ATTR_CFNUM(S_IWUSR | S_IRUGO,
ade7753_read_8bit,
ade7753_write_8bit,
ADE7753_CFNUM);
static IIO_DEV_ATTR_CHKSUM(ade7753_read_8bit, ADE7753_CHKSUM);
static IIO_DEV_ATTR_PHCAL(S_IWUSR | S_IRUGO,
ade7753_read_16bit,
ade7753_write_16bit,
ADE7753_PHCAL);
static IIO_DEV_ATTR_APOS(S_IWUSR | S_IRUGO,
ade7753_read_16bit,
ade7753_write_16bit,
ADE7753_APOS);
static IIO_DEV_ATTR_SAGCYC(S_IWUSR | S_IRUGO,
ade7753_read_8bit,
ade7753_write_8bit,
ADE7753_SAGCYC);
static IIO_DEV_ATTR_SAGLVL(S_IWUSR | S_IRUGO,
ade7753_read_8bit,
ade7753_write_8bit,
ADE7753_SAGLVL);
static IIO_DEV_ATTR_LINECYC(S_IWUSR | S_IRUGO,
ade7753_read_8bit,
ade7753_write_8bit,
ADE7753_LINECYC);
static IIO_DEV_ATTR_WDIV(S_IWUSR | S_IRUGO,
ade7753_read_8bit,
ade7753_write_8bit,
ADE7753_WDIV);
static IIO_DEV_ATTR_IRMS(S_IWUSR | S_IRUGO,
ade7753_read_24bit,
NULL,
ADE7753_IRMS);
static IIO_DEV_ATTR_VRMS(S_IRUGO,
ade7753_read_24bit,
NULL,
ADE7753_VRMS);
static IIO_DEV_ATTR_IRMSOS(S_IWUSR | S_IRUGO,
ade7753_read_16bit,
ade7753_write_16bit,
ADE7753_IRMSOS);
static IIO_DEV_ATTR_VRMSOS(S_IWUSR | S_IRUGO,
ade7753_read_16bit,
ade7753_write_16bit,
ADE7753_VRMSOS);
static IIO_DEV_ATTR_WGAIN(S_IWUSR | S_IRUGO,
ade7753_read_16bit,
ade7753_write_16bit,
ADE7753_WGAIN);
static IIO_DEV_ATTR_VAGAIN(S_IWUSR | S_IRUGO,
ade7753_read_16bit,
ade7753_write_16bit,
ADE7753_VAGAIN);
static IIO_DEV_ATTR_PGA_GAIN(S_IWUSR | S_IRUGO,
ade7753_read_16bit,
ade7753_write_16bit,
ADE7753_GAIN);
static IIO_DEV_ATTR_IPKLVL(S_IWUSR | S_IRUGO,
ade7753_read_8bit,
ade7753_write_8bit,
ADE7753_IPKLVL);
static IIO_DEV_ATTR_VPKLVL(S_IWUSR | S_IRUGO,
ade7753_read_8bit,
ade7753_write_8bit,
ADE7753_VPKLVL);
static IIO_DEV_ATTR_IPEAK(S_IRUGO,
ade7753_read_24bit,
NULL,
ADE7753_IPEAK);
static IIO_DEV_ATTR_VPEAK(S_IRUGO,
ade7753_read_24bit,
NULL,
ADE7753_VPEAK);
static IIO_DEV_ATTR_VPERIOD(S_IRUGO,
ade7753_read_16bit,
NULL,
ADE7753_PERIOD);
static IIO_DEV_ATTR_CH_OFF(1, S_IWUSR | S_IRUGO,
ade7753_read_8bit,
ade7753_write_8bit,
ADE7753_CH1OS);
static IIO_DEV_ATTR_CH_OFF(2, S_IWUSR | S_IRUGO,
ade7753_read_8bit,
ade7753_write_8bit,
ADE7753_CH2OS);
static int ade7753_set_irq(struct device *dev, bool enable)
{
int ret;
u8 irqen;
ret = ade7753_spi_read_reg_8(dev, ADE7753_IRQEN, &irqen);
if (ret)
goto error_ret;
if (enable)
irqen |= BIT(3); /* Enables an interrupt when a data is
present in the waveform register */
else
irqen &= ~BIT(3);
ret = ade7753_spi_write_reg_8(dev, ADE7753_IRQEN, irqen);
error_ret:
return ret;
}
/* Power down the device */
static int ade7753_stop_device(struct device *dev)
{
u16 val;
ade7753_spi_read_reg_16(dev, ADE7753_MODE, &val);
val |= BIT(4); /* AD converters can be turned off */
return ade7753_spi_write_reg_16(dev, ADE7753_MODE, val);
}
static int ade7753_initial_setup(struct iio_dev *indio_dev)
{
int ret;
struct device *dev = &indio_dev->dev;
struct ade7753_state *st = iio_priv(indio_dev);
/* use low spi speed for init */
st->us->mode = SPI_MODE_3;
spi_setup(st->us);
/* Disable IRQ */
ret = ade7753_set_irq(dev, false);
if (ret) {
dev_err(dev, "disable irq failed");
goto err_ret;
}
ade7753_reset(dev);
msleep(ADE7753_STARTUP_DELAY);
err_ret:
return ret;
}
static ssize_t ade7753_read_frequency(struct device *dev,
struct device_attribute *attr,
char *buf)
{
int ret;
u16 t;
int sps;
ret = ade7753_spi_read_reg_16(dev, ADE7753_MODE, &t);
if (ret)
return ret;
t = (t >> 11) & 0x3;
sps = 27900 / (1 + t);
return sprintf(buf, "%d\n", sps);
}
static ssize_t ade7753_write_frequency(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t len)
{
struct iio_dev *indio_dev = dev_to_iio_dev(dev);
struct ade7753_state *st = iio_priv(indio_dev);
u16 val;
int ret;
u16 reg, t;
ret = kstrtou16(buf, 10, &val);
if (ret)
return ret;
if (!val)
return -EINVAL;
mutex_lock(&indio_dev->mlock);
t = 27900 / val;
if (t > 0)
t--;
if (t > 1)
st->us->max_speed_hz = ADE7753_SPI_SLOW;
else
st->us->max_speed_hz = ADE7753_SPI_FAST;
ret = ade7753_spi_read_reg_16(dev, ADE7753_MODE, ®);
if (ret)
goto out;
reg &= ~(3 << 11);
reg |= t << 11;
ret = ade7753_spi_write_reg_16(dev, ADE7753_MODE, reg);
out:
mutex_unlock(&indio_dev->mlock);
return ret ? ret : len;
}
static IIO_DEV_ATTR_TEMP_RAW(ade7753_read_8bit);
static IIO_CONST_ATTR(in_temp_offset, "-25 C");
static IIO_CONST_ATTR(in_temp_scale, "0.67 C");
static IIO_DEV_ATTR_SAMP_FREQ(S_IWUSR | S_IRUGO,
ade7753_read_frequency,
ade7753_write_frequency);
static IIO_CONST_ATTR_SAMP_FREQ_AVAIL("27900 14000 7000 3500");
static struct attribute *ade7753_attributes[] = {
&iio_dev_attr_in_temp_raw.dev_attr.attr,
&iio_const_attr_in_temp_offset.dev_attr.attr,
&iio_const_attr_in_temp_scale.dev_attr.attr,
&iio_dev_attr_sampling_frequency.dev_attr.attr,
&iio_const_attr_sampling_frequency_available.dev_attr.attr,
&iio_dev_attr_phcal.dev_attr.attr,
&iio_dev_attr_cfden.dev_attr.attr,
&iio_dev_attr_aenergy.dev_attr.attr,
&iio_dev_attr_laenergy.dev_attr.attr,
&iio_dev_attr_vaenergy.dev_attr.attr,
&iio_dev_attr_lvaenergy.dev_attr.attr,
&iio_dev_attr_cfnum.dev_attr.attr,
&iio_dev_attr_apos.dev_attr.attr,
&iio_dev_attr_sagcyc.dev_attr.attr,
&iio_dev_attr_saglvl.dev_attr.attr,
&iio_dev_attr_linecyc.dev_attr.attr,
&iio_dev_attr_chksum.dev_attr.attr,
&iio_dev_attr_pga_gain.dev_attr.attr,
&iio_dev_attr_wgain.dev_attr.attr,
&iio_dev_attr_choff_1.dev_attr.attr,
&iio_dev_attr_choff_2.dev_attr.attr,
&iio_dev_attr_wdiv.dev_attr.attr,
&iio_dev_attr_irms.dev_attr.attr,
&iio_dev_attr_vrms.dev_attr.attr,
&iio_dev_attr_irmsos.dev_attr.attr,
&iio_dev_attr_vrmsos.dev_attr.attr,
&iio_dev_attr_vagain.dev_attr.attr,
&iio_dev_attr_ipklvl.dev_attr.attr,
&iio_dev_attr_vpklvl.dev_attr.attr,
&iio_dev_attr_ipeak.dev_attr.attr,
&iio_dev_attr_vpeak.dev_attr.attr,
&iio_dev_attr_vperiod.dev_attr.attr,
NULL,
};
static const struct attribute_group ade7753_attribute_group = {
.attrs = ade7753_attributes,
};
static const struct iio_info ade7753_info = {
.attrs = &ade7753_attribute_group,
.driver_module = THIS_MODULE,
};
static int ade7753_probe(struct spi_device *spi)
{
int ret;
struct ade7753_state *st;
struct iio_dev *indio_dev;
/* setup the industrialio driver allocated elements */
indio_dev = devm_iio_device_alloc(&spi->dev, sizeof(*st));
if (!indio_dev)
return -ENOMEM;
/* this is only used for removal purposes */
spi_set_drvdata(spi, indio_dev);
st = iio_priv(indio_dev);
st->us = spi;
mutex_init(&st->buf_lock);
indio_dev->name = spi->dev.driver->name;
indio_dev->dev.parent = &spi->dev;
indio_dev->info = &ade7753_info;
indio_dev->modes = INDIO_DIRECT_MODE;
/* Get the device into a sane initial state */
ret = ade7753_initial_setup(indio_dev);
if (ret)
return ret;
return iio_device_register(indio_dev);
}
/* fixme, confirm ordering in this function */
static int ade7753_remove(struct spi_device *spi)
{
struct iio_dev *indio_dev = spi_get_drvdata(spi);
iio_device_unregister(indio_dev);
ade7753_stop_device(&indio_dev->dev);
return 0;
}
static struct spi_driver ade7753_driver = {
.driver = {
.name = "ade7753",
},
.probe = ade7753_probe,
.remove = ade7753_remove,
};
module_spi_driver(ade7753_driver);
MODULE_AUTHOR("Barry Song <21cnbao@gmail.com>");
MODULE_DESCRIPTION("Analog Devices ADE7753/6 Single-Phase Multifunction Meter");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("spi:ade7753");
| gpl-2.0 |
tony0924/itri | drivers/edac/r82600_edac.c | 2472 | 12088 | /*
* Radisys 82600 Embedded chipset Memory Controller kernel module
* (C) 2005 EADS Astrium
* This file may be distributed under the terms of the
* GNU General Public License.
*
* Written by Tim Small <tim@buttersideup.com>, based on work by Thayne
* Harbaugh, Dan Hollis <goemon at anime dot net> and others.
*
* $Id: edac_r82600.c,v 1.1.2.6 2005/10/05 00:43:44 dsp_llnl Exp $
*
* Written with reference to 82600 High Integration Dual PCI System
* Controller Data Book:
* www.radisys.com/files/support_downloads/007-01277-0002.82600DataBook.pdf
* references to this document given in []
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/pci_ids.h>
#include <linux/edac.h>
#include "edac_core.h"
#define R82600_REVISION " Ver: 2.0.2"
#define EDAC_MOD_STR "r82600_edac"
#define r82600_printk(level, fmt, arg...) \
edac_printk(level, "r82600", fmt, ##arg)
#define r82600_mc_printk(mci, level, fmt, arg...) \
edac_mc_chipset_printk(mci, level, "r82600", fmt, ##arg)
/* Radisys say "The 82600 integrates a main memory SDRAM controller that
* supports up to four banks of memory. The four banks can support a mix of
* sizes of 64 bit wide (72 bits with ECC) Synchronous DRAM (SDRAM) DIMMs,
* each of which can be any size from 16MB to 512MB. Both registered (control
* signals buffered) and unbuffered DIMM types are supported. Mixing of
* registered and unbuffered DIMMs as well as mixing of ECC and non-ECC DIMMs
* is not allowed. The 82600 SDRAM interface operates at the same frequency as
* the CPU bus, 66MHz, 100MHz or 133MHz."
*/
#define R82600_NR_CSROWS 4
#define R82600_NR_CHANS 1
#define R82600_NR_DIMMS 4
#define R82600_BRIDGE_ID 0x8200
/* Radisys 82600 register addresses - device 0 function 0 - PCI bridge */
#define R82600_DRAMC 0x57 /* Various SDRAM related control bits
* all bits are R/W
*
* 7 SDRAM ISA Hole Enable
* 6 Flash Page Mode Enable
* 5 ECC Enable: 1=ECC 0=noECC
* 4 DRAM DIMM Type: 1=
* 3 BIOS Alias Disable
* 2 SDRAM BIOS Flash Write Enable
* 1:0 SDRAM Refresh Rate: 00=Disabled
* 01=7.8usec (256Mbit SDRAMs)
* 10=15.6us 11=125usec
*/
#define R82600_SDRAMC 0x76 /* "SDRAM Control Register"
* More SDRAM related control bits
* all bits are R/W
*
* 15:8 Reserved.
*
* 7:5 Special SDRAM Mode Select
*
* 4 Force ECC
*
* 1=Drive ECC bits to 0 during
* write cycles (i.e. ECC test mode)
*
* 0=Normal ECC functioning
*
* 3 Enhanced Paging Enable
*
* 2 CAS# Latency 0=3clks 1=2clks
*
* 1 RAS# to CAS# Delay 0=3 1=2
*
* 0 RAS# Precharge 0=3 1=2
*/
#define R82600_EAP 0x80 /* ECC Error Address Pointer Register
*
* 31 Disable Hardware Scrubbing (RW)
* 0=Scrub on corrected read
* 1=Don't scrub on corrected read
*
* 30:12 Error Address Pointer (RO)
* Upper 19 bits of error address
*
* 11:4 Syndrome Bits (RO)
*
* 3 BSERR# on multibit error (RW)
* 1=enable 0=disable
*
* 2 NMI on Single Bit Eror (RW)
* 1=NMI triggered by SBE n.b. other
* prerequeists
* 0=NMI not triggered
*
* 1 MBE (R/WC)
* read 1=MBE at EAP (see above)
* read 0=no MBE, or SBE occurred first
* write 1=Clear MBE status (must also
* clear SBE)
* write 0=NOP
*
* 1 SBE (R/WC)
* read 1=SBE at EAP (see above)
* read 0=no SBE, or MBE occurred first
* write 1=Clear SBE status (must also
* clear MBE)
* write 0=NOP
*/
#define R82600_DRBA 0x60 /* + 0x60..0x63 SDRAM Row Boundary Address
* Registers
*
* 7:0 Address lines 30:24 - upper limit of
* each row [p57]
*/
struct r82600_error_info {
u32 eapr;
};
static bool disable_hardware_scrub;
static struct edac_pci_ctl_info *r82600_pci;
static void r82600_get_error_info(struct mem_ctl_info *mci,
struct r82600_error_info *info)
{
struct pci_dev *pdev;
pdev = to_pci_dev(mci->pdev);
pci_read_config_dword(pdev, R82600_EAP, &info->eapr);
if (info->eapr & BIT(0))
/* Clear error to allow next error to be reported [p.62] */
pci_write_bits32(pdev, R82600_EAP,
((u32) BIT(0) & (u32) BIT(1)),
((u32) BIT(0) & (u32) BIT(1)));
if (info->eapr & BIT(1))
/* Clear error to allow next error to be reported [p.62] */
pci_write_bits32(pdev, R82600_EAP,
((u32) BIT(0) & (u32) BIT(1)),
((u32) BIT(0) & (u32) BIT(1)));
}
static int r82600_process_error_info(struct mem_ctl_info *mci,
struct r82600_error_info *info,
int handle_errors)
{
int error_found;
u32 eapaddr, page;
u32 syndrome;
error_found = 0;
/* bits 30:12 store the upper 19 bits of the 32 bit error address */
eapaddr = ((info->eapr >> 12) & 0x7FFF) << 13;
/* Syndrome in bits 11:4 [p.62] */
syndrome = (info->eapr >> 4) & 0xFF;
/* the R82600 reports at less than page *
* granularity (upper 19 bits only) */
page = eapaddr >> PAGE_SHIFT;
if (info->eapr & BIT(0)) { /* CE? */
error_found = 1;
if (handle_errors)
edac_mc_handle_error(HW_EVENT_ERR_CORRECTED, mci, 1,
page, 0, syndrome,
edac_mc_find_csrow_by_page(mci, page),
0, -1,
mci->ctl_name, "");
}
if (info->eapr & BIT(1)) { /* UE? */
error_found = 1;
if (handle_errors)
/* 82600 doesn't give enough info */
edac_mc_handle_error(HW_EVENT_ERR_UNCORRECTED, mci, 1,
page, 0, 0,
edac_mc_find_csrow_by_page(mci, page),
0, -1,
mci->ctl_name, "");
}
return error_found;
}
static void r82600_check(struct mem_ctl_info *mci)
{
struct r82600_error_info info;
edac_dbg(1, "MC%d\n", mci->mc_idx);
r82600_get_error_info(mci, &info);
r82600_process_error_info(mci, &info, 1);
}
static inline int ecc_enabled(u8 dramcr)
{
return dramcr & BIT(5);
}
static void r82600_init_csrows(struct mem_ctl_info *mci, struct pci_dev *pdev,
u8 dramcr)
{
struct csrow_info *csrow;
struct dimm_info *dimm;
int index;
u8 drbar; /* SDRAM Row Boundary Address Register */
u32 row_high_limit, row_high_limit_last;
u32 reg_sdram, ecc_on, row_base;
ecc_on = ecc_enabled(dramcr);
reg_sdram = dramcr & BIT(4);
row_high_limit_last = 0;
for (index = 0; index < mci->nr_csrows; index++) {
csrow = mci->csrows[index];
dimm = csrow->channels[0]->dimm;
/* find the DRAM Chip Select Base address and mask */
pci_read_config_byte(pdev, R82600_DRBA + index, &drbar);
edac_dbg(1, "Row=%d DRBA = %#0x\n", index, drbar);
row_high_limit = ((u32) drbar << 24);
/* row_high_limit = ((u32)drbar << 24) | 0xffffffUL; */
edac_dbg(1, "Row=%d, Boundary Address=%#0x, Last = %#0x\n",
index, row_high_limit, row_high_limit_last);
/* Empty row [p.57] */
if (row_high_limit == row_high_limit_last)
continue;
row_base = row_high_limit_last;
csrow->first_page = row_base >> PAGE_SHIFT;
csrow->last_page = (row_high_limit >> PAGE_SHIFT) - 1;
dimm->nr_pages = csrow->last_page - csrow->first_page + 1;
/* Error address is top 19 bits - so granularity is *
* 14 bits */
dimm->grain = 1 << 14;
dimm->mtype = reg_sdram ? MEM_RDDR : MEM_DDR;
/* FIXME - check that this is unknowable with this chipset */
dimm->dtype = DEV_UNKNOWN;
/* Mode is global on 82600 */
dimm->edac_mode = ecc_on ? EDAC_SECDED : EDAC_NONE;
row_high_limit_last = row_high_limit;
}
}
static int r82600_probe1(struct pci_dev *pdev, int dev_idx)
{
struct mem_ctl_info *mci;
struct edac_mc_layer layers[2];
u8 dramcr;
u32 eapr;
u32 scrub_disabled;
u32 sdram_refresh_rate;
struct r82600_error_info discard;
edac_dbg(0, "\n");
pci_read_config_byte(pdev, R82600_DRAMC, &dramcr);
pci_read_config_dword(pdev, R82600_EAP, &eapr);
scrub_disabled = eapr & BIT(31);
sdram_refresh_rate = dramcr & (BIT(0) | BIT(1));
edac_dbg(2, "sdram refresh rate = %#0x\n", sdram_refresh_rate);
edac_dbg(2, "DRAMC register = %#0x\n", dramcr);
layers[0].type = EDAC_MC_LAYER_CHIP_SELECT;
layers[0].size = R82600_NR_CSROWS;
layers[0].is_virt_csrow = true;
layers[1].type = EDAC_MC_LAYER_CHANNEL;
layers[1].size = R82600_NR_CHANS;
layers[1].is_virt_csrow = false;
mci = edac_mc_alloc(0, ARRAY_SIZE(layers), layers, 0);
if (mci == NULL)
return -ENOMEM;
edac_dbg(0, "mci = %p\n", mci);
mci->pdev = &pdev->dev;
mci->mtype_cap = MEM_FLAG_RDDR | MEM_FLAG_DDR;
mci->edac_ctl_cap = EDAC_FLAG_NONE | EDAC_FLAG_EC | EDAC_FLAG_SECDED;
/* FIXME try to work out if the chip leads have been used for COM2
* instead on this board? [MA6?] MAYBE:
*/
/* On the R82600, the pins for memory bits 72:65 - i.e. the *
* EC bits are shared with the pins for COM2 (!), so if COM2 *
* is enabled, we assume COM2 is wired up, and thus no EDAC *
* is possible. */
mci->edac_cap = EDAC_FLAG_NONE | EDAC_FLAG_EC | EDAC_FLAG_SECDED;
if (ecc_enabled(dramcr)) {
if (scrub_disabled)
edac_dbg(3, "mci = %p - Scrubbing disabled! EAP: %#0x\n",
mci, eapr);
} else
mci->edac_cap = EDAC_FLAG_NONE;
mci->mod_name = EDAC_MOD_STR;
mci->mod_ver = R82600_REVISION;
mci->ctl_name = "R82600";
mci->dev_name = pci_name(pdev);
mci->edac_check = r82600_check;
mci->ctl_page_to_phys = NULL;
r82600_init_csrows(mci, pdev, dramcr);
r82600_get_error_info(mci, &discard); /* clear counters */
/* Here we assume that we will never see multiple instances of this
* type of memory controller. The ID is therefore hardcoded to 0.
*/
if (edac_mc_add_mc(mci)) {
edac_dbg(3, "failed edac_mc_add_mc()\n");
goto fail;
}
/* get this far and it's successful */
if (disable_hardware_scrub) {
edac_dbg(3, "Disabling Hardware Scrub (scrub on error)\n");
pci_write_bits32(pdev, R82600_EAP, BIT(31), BIT(31));
}
/* allocating generic PCI control info */
r82600_pci = edac_pci_create_generic_ctl(&pdev->dev, EDAC_MOD_STR);
if (!r82600_pci) {
printk(KERN_WARNING
"%s(): Unable to create PCI control\n",
__func__);
printk(KERN_WARNING
"%s(): PCI error report via EDAC not setup\n",
__func__);
}
edac_dbg(3, "success\n");
return 0;
fail:
edac_mc_free(mci);
return -ENODEV;
}
/* returns count (>= 0), or negative on error */
static int r82600_init_one(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
edac_dbg(0, "\n");
/* don't need to call pci_enable_device() */
return r82600_probe1(pdev, ent->driver_data);
}
static void r82600_remove_one(struct pci_dev *pdev)
{
struct mem_ctl_info *mci;
edac_dbg(0, "\n");
if (r82600_pci)
edac_pci_release_generic_ctl(r82600_pci);
if ((mci = edac_mc_del_mc(&pdev->dev)) == NULL)
return;
edac_mc_free(mci);
}
static DEFINE_PCI_DEVICE_TABLE(r82600_pci_tbl) = {
{
PCI_DEVICE(PCI_VENDOR_ID_RADISYS, R82600_BRIDGE_ID)
},
{
0,
} /* 0 terminated list. */
};
MODULE_DEVICE_TABLE(pci, r82600_pci_tbl);
static struct pci_driver r82600_driver = {
.name = EDAC_MOD_STR,
.probe = r82600_init_one,
.remove = r82600_remove_one,
.id_table = r82600_pci_tbl,
};
static int __init r82600_init(void)
{
/* Ensure that the OPSTATE is set correctly for POLL or NMI */
opstate_init();
return pci_register_driver(&r82600_driver);
}
static void __exit r82600_exit(void)
{
pci_unregister_driver(&r82600_driver);
}
module_init(r82600_init);
module_exit(r82600_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Tim Small <tim@buttersideup.com> - WPAD Ltd. "
"on behalf of EADS Astrium");
MODULE_DESCRIPTION("MC support for Radisys 82600 memory controllers");
module_param(disable_hardware_scrub, bool, 0644);
MODULE_PARM_DESC(disable_hardware_scrub,
"If set, disable the chipset's automatic scrub for CEs");
module_param(edac_op_state, int, 0444);
MODULE_PARM_DESC(edac_op_state, "EDAC Error Reporting state: 0=Poll,1=NMI");
| gpl-2.0 |
NEKTech-Labs/wrapfs-kernel-linux-3.17 | net/irda/irnet/irnet_ppp.c | 3240 | 33374 | /*
* IrNET protocol module : Synchronous PPP over an IrDA socket.
*
* Jean II - HPL `00 - <jt@hpl.hp.com>
*
* This file implement the PPP interface and /dev/irnet character device.
* The PPP interface hook to the ppp_generic module, handle all our
* relationship to the PPP code in the kernel (and by extension to pppd),
* and exchange PPP frames with this module (send/receive).
* The /dev/irnet device is used primarily for 2 functions :
* 1) as a stub for pppd (the ppp daemon), so that we can appropriately
* generate PPP sessions (we pretend we are a tty).
* 2) as a control channel (write commands, read events)
*/
#include <linux/sched.h>
#include <linux/slab.h>
#include "irnet_ppp.h" /* Private header */
/* Please put other headers in irnet.h - Thanks */
/* Generic PPP callbacks (to call us) */
static const struct ppp_channel_ops irnet_ppp_ops = {
.start_xmit = ppp_irnet_send,
.ioctl = ppp_irnet_ioctl
};
/************************* CONTROL CHANNEL *************************/
/*
* When a pppd instance is not active on /dev/irnet, it acts as a control
* channel.
* Writing allow to set up the IrDA destination of the IrNET channel,
* and any application may be read events happening in IrNET...
*/
/*------------------------------------------------------------------*/
/*
* Write is used to send a command to configure a IrNET channel
* before it is open by pppd. The syntax is : "command argument"
* Currently there is only two defined commands :
* o name : set the requested IrDA nickname of the IrNET peer.
* o addr : set the requested IrDA address of the IrNET peer.
* Note : the code is crude, but effective...
*/
static inline ssize_t
irnet_ctrl_write(irnet_socket * ap,
const char __user *buf,
size_t count)
{
char command[IRNET_MAX_COMMAND];
char * start; /* Current command being processed */
char * next; /* Next command to process */
int length; /* Length of current command */
DENTER(CTRL_TRACE, "(ap=0x%p, count=%Zd)\n", ap, count);
/* Check for overflow... */
DABORT(count >= IRNET_MAX_COMMAND, -ENOMEM,
CTRL_ERROR, "Too much data !!!\n");
/* Get the data in the driver */
if(copy_from_user(command, buf, count))
{
DERROR(CTRL_ERROR, "Invalid user space pointer.\n");
return -EFAULT;
}
/* Safe terminate the string */
command[count] = '\0';
DEBUG(CTRL_INFO, "Command line received is ``%s'' (%Zd).\n",
command, count);
/* Check every commands in the command line */
next = command;
while(next != NULL)
{
/* Look at the next command */
start = next;
/* Scrap whitespaces before the command */
start = skip_spaces(start);
/* ',' is our command separator */
next = strchr(start, ',');
if(next)
{
*next = '\0'; /* Terminate command */
length = next - start; /* Length */
next++; /* Skip the '\0' */
}
else
length = strlen(start);
DEBUG(CTRL_INFO, "Found command ``%s'' (%d).\n", start, length);
/* Check if we recognised one of the known command
* We can't use "switch" with strings, so hack with "continue" */
/* First command : name -> Requested IrDA nickname */
if(!strncmp(start, "name", 4))
{
/* Copy the name only if is included and not "any" */
if((length > 5) && (strcmp(start + 5, "any")))
{
/* Strip out trailing whitespaces */
while(isspace(start[length - 1]))
length--;
DABORT(length < 5 || length > NICKNAME_MAX_LEN + 5,
-EINVAL, CTRL_ERROR, "Invalid nickname.\n");
/* Copy the name for later reuse */
memcpy(ap->rname, start + 5, length - 5);
ap->rname[length - 5] = '\0';
}
else
ap->rname[0] = '\0';
DEBUG(CTRL_INFO, "Got rname = ``%s''\n", ap->rname);
/* Restart the loop */
continue;
}
/* Second command : addr, daddr -> Requested IrDA destination address
* Also process : saddr -> Requested IrDA source address */
if((!strncmp(start, "addr", 4)) ||
(!strncmp(start, "daddr", 5)) ||
(!strncmp(start, "saddr", 5)))
{
__u32 addr = DEV_ADDR_ANY;
/* Copy the address only if is included and not "any" */
if((length > 5) && (strcmp(start + 5, "any")))
{
char * begp = start + 5;
char * endp;
/* Scrap whitespaces before the command */
begp = skip_spaces(begp);
/* Convert argument to a number (last arg is the base) */
addr = simple_strtoul(begp, &endp, 16);
/* Has it worked ? (endp should be start + length) */
DABORT(endp <= (start + 5), -EINVAL,
CTRL_ERROR, "Invalid address.\n");
}
/* Which type of address ? */
if(start[0] == 's')
{
/* Save it */
ap->rsaddr = addr;
DEBUG(CTRL_INFO, "Got rsaddr = %08x\n", ap->rsaddr);
}
else
{
/* Save it */
ap->rdaddr = addr;
DEBUG(CTRL_INFO, "Got rdaddr = %08x\n", ap->rdaddr);
}
/* Restart the loop */
continue;
}
/* Other possible command : connect N (number of retries) */
/* No command matched -> Failed... */
DABORT(1, -EINVAL, CTRL_ERROR, "Not a recognised IrNET command.\n");
}
/* Success : we have parsed all commands successfully */
return count;
}
#ifdef INITIAL_DISCOVERY
/*------------------------------------------------------------------*/
/*
* Function irnet_get_discovery_log (self)
*
* Query the content on the discovery log if not done
*
* This function query the current content of the discovery log
* at the startup of the event channel and save it in the internal struct.
*/
static void
irnet_get_discovery_log(irnet_socket * ap)
{
__u16 mask = irlmp_service_to_hint(S_LAN);
/* Ask IrLMP for the current discovery log */
ap->discoveries = irlmp_get_discoveries(&ap->disco_number, mask,
DISCOVERY_DEFAULT_SLOTS);
/* Check if the we got some results */
if(ap->discoveries == NULL)
ap->disco_number = -1;
DEBUG(CTRL_INFO, "Got the log (0x%p), size is %d\n",
ap->discoveries, ap->disco_number);
}
/*------------------------------------------------------------------*/
/*
* Function irnet_read_discovery_log (self, event)
*
* Read the content on the discovery log
*
* This function dump the current content of the discovery log
* at the startup of the event channel.
* Return 1 if wrote an event on the control channel...
*
* State of the ap->disco_XXX variables :
* Socket creation : discoveries = NULL ; disco_index = 0 ; disco_number = 0
* While reading : discoveries = ptr ; disco_index = X ; disco_number = Y
* After reading : discoveries = NULL ; disco_index = Y ; disco_number = -1
*/
static inline int
irnet_read_discovery_log(irnet_socket *ap, char *event, int buf_size)
{
int done_event = 0;
DENTER(CTRL_TRACE, "(ap=0x%p, event=0x%p)\n",
ap, event);
/* Test if we have some work to do or we have already finished */
if(ap->disco_number == -1)
{
DEBUG(CTRL_INFO, "Already done\n");
return 0;
}
/* Test if it's the first time and therefore we need to get the log */
if(ap->discoveries == NULL)
irnet_get_discovery_log(ap);
/* Check if we have more item to dump */
if(ap->disco_index < ap->disco_number)
{
/* Write an event */
snprintf(event, buf_size,
"Found %08x (%s) behind %08x {hints %02X-%02X}\n",
ap->discoveries[ap->disco_index].daddr,
ap->discoveries[ap->disco_index].info,
ap->discoveries[ap->disco_index].saddr,
ap->discoveries[ap->disco_index].hints[0],
ap->discoveries[ap->disco_index].hints[1]);
DEBUG(CTRL_INFO, "Writing discovery %d : %s\n",
ap->disco_index, ap->discoveries[ap->disco_index].info);
/* We have an event */
done_event = 1;
/* Next discovery */
ap->disco_index++;
}
/* Check if we have done the last item */
if(ap->disco_index >= ap->disco_number)
{
/* No more items : remove the log and signal termination */
DEBUG(CTRL_INFO, "Cleaning up log (0x%p)\n",
ap->discoveries);
if(ap->discoveries != NULL)
{
/* Cleanup our copy of the discovery log */
kfree(ap->discoveries);
ap->discoveries = NULL;
}
ap->disco_number = -1;
}
return done_event;
}
#endif /* INITIAL_DISCOVERY */
/*------------------------------------------------------------------*/
/*
* Read is used to get IrNET events
*/
static inline ssize_t
irnet_ctrl_read(irnet_socket * ap,
struct file * file,
char __user * buf,
size_t count)
{
DECLARE_WAITQUEUE(wait, current);
char event[75];
ssize_t ret = 0;
DENTER(CTRL_TRACE, "(ap=0x%p, count=%Zd)\n", ap, count);
#ifdef INITIAL_DISCOVERY
/* Check if we have read the log */
if (irnet_read_discovery_log(ap, event, sizeof(event)))
{
count = min(strlen(event), count);
if (copy_to_user(buf, event, count))
{
DERROR(CTRL_ERROR, "Invalid user space pointer.\n");
return -EFAULT;
}
DEXIT(CTRL_TRACE, "\n");
return count;
}
#endif /* INITIAL_DISCOVERY */
/* Put ourselves on the wait queue to be woken up */
add_wait_queue(&irnet_events.rwait, &wait);
current->state = TASK_INTERRUPTIBLE;
for(;;)
{
/* If there is unread events */
ret = 0;
if(ap->event_index != irnet_events.index)
break;
ret = -EAGAIN;
if(file->f_flags & O_NONBLOCK)
break;
ret = -ERESTARTSYS;
if(signal_pending(current))
break;
/* Yield and wait to be woken up */
schedule();
}
current->state = TASK_RUNNING;
remove_wait_queue(&irnet_events.rwait, &wait);
/* Did we got it ? */
if(ret != 0)
{
/* No, return the error code */
DEXIT(CTRL_TRACE, " - ret %Zd\n", ret);
return ret;
}
/* Which event is it ? */
switch(irnet_events.log[ap->event_index].event)
{
case IRNET_DISCOVER:
snprintf(event, sizeof(event),
"Discovered %08x (%s) behind %08x {hints %02X-%02X}\n",
irnet_events.log[ap->event_index].daddr,
irnet_events.log[ap->event_index].name,
irnet_events.log[ap->event_index].saddr,
irnet_events.log[ap->event_index].hints.byte[0],
irnet_events.log[ap->event_index].hints.byte[1]);
break;
case IRNET_EXPIRE:
snprintf(event, sizeof(event),
"Expired %08x (%s) behind %08x {hints %02X-%02X}\n",
irnet_events.log[ap->event_index].daddr,
irnet_events.log[ap->event_index].name,
irnet_events.log[ap->event_index].saddr,
irnet_events.log[ap->event_index].hints.byte[0],
irnet_events.log[ap->event_index].hints.byte[1]);
break;
case IRNET_CONNECT_TO:
snprintf(event, sizeof(event), "Connected to %08x (%s) on ppp%d\n",
irnet_events.log[ap->event_index].daddr,
irnet_events.log[ap->event_index].name,
irnet_events.log[ap->event_index].unit);
break;
case IRNET_CONNECT_FROM:
snprintf(event, sizeof(event), "Connection from %08x (%s) on ppp%d\n",
irnet_events.log[ap->event_index].daddr,
irnet_events.log[ap->event_index].name,
irnet_events.log[ap->event_index].unit);
break;
case IRNET_REQUEST_FROM:
snprintf(event, sizeof(event), "Request from %08x (%s) behind %08x\n",
irnet_events.log[ap->event_index].daddr,
irnet_events.log[ap->event_index].name,
irnet_events.log[ap->event_index].saddr);
break;
case IRNET_NOANSWER_FROM:
snprintf(event, sizeof(event), "No-answer from %08x (%s) on ppp%d\n",
irnet_events.log[ap->event_index].daddr,
irnet_events.log[ap->event_index].name,
irnet_events.log[ap->event_index].unit);
break;
case IRNET_BLOCKED_LINK:
snprintf(event, sizeof(event), "Blocked link with %08x (%s) on ppp%d\n",
irnet_events.log[ap->event_index].daddr,
irnet_events.log[ap->event_index].name,
irnet_events.log[ap->event_index].unit);
break;
case IRNET_DISCONNECT_FROM:
snprintf(event, sizeof(event), "Disconnection from %08x (%s) on ppp%d\n",
irnet_events.log[ap->event_index].daddr,
irnet_events.log[ap->event_index].name,
irnet_events.log[ap->event_index].unit);
break;
case IRNET_DISCONNECT_TO:
snprintf(event, sizeof(event), "Disconnected to %08x (%s)\n",
irnet_events.log[ap->event_index].daddr,
irnet_events.log[ap->event_index].name);
break;
default:
snprintf(event, sizeof(event), "Bug\n");
}
/* Increment our event index */
ap->event_index = (ap->event_index + 1) % IRNET_MAX_EVENTS;
DEBUG(CTRL_INFO, "Event is :%s", event);
count = min(strlen(event), count);
if (copy_to_user(buf, event, count))
{
DERROR(CTRL_ERROR, "Invalid user space pointer.\n");
return -EFAULT;
}
DEXIT(CTRL_TRACE, "\n");
return count;
}
/*------------------------------------------------------------------*/
/*
* Poll : called when someone do a select on /dev/irnet.
* Just check if there are new events...
*/
static inline unsigned int
irnet_ctrl_poll(irnet_socket * ap,
struct file * file,
poll_table * wait)
{
unsigned int mask;
DENTER(CTRL_TRACE, "(ap=0x%p)\n", ap);
poll_wait(file, &irnet_events.rwait, wait);
mask = POLLOUT | POLLWRNORM;
/* If there is unread events */
if(ap->event_index != irnet_events.index)
mask |= POLLIN | POLLRDNORM;
#ifdef INITIAL_DISCOVERY
if(ap->disco_number != -1)
{
/* Test if it's the first time and therefore we need to get the log */
if(ap->discoveries == NULL)
irnet_get_discovery_log(ap);
/* Recheck */
if(ap->disco_number != -1)
mask |= POLLIN | POLLRDNORM;
}
#endif /* INITIAL_DISCOVERY */
DEXIT(CTRL_TRACE, " - mask=0x%X\n", mask);
return mask;
}
/*********************** FILESYSTEM CALLBACKS ***********************/
/*
* Implement the usual open, read, write functions that will be called
* by the file system when some action is performed on /dev/irnet.
* Most of those actions will in fact be performed by "pppd" or
* the control channel, we just act as a redirector...
*/
/*------------------------------------------------------------------*/
/*
* Open : when somebody open /dev/irnet
* We basically create a new instance of irnet and initialise it.
*/
static int
dev_irnet_open(struct inode * inode,
struct file * file)
{
struct irnet_socket * ap;
int err;
DENTER(FS_TRACE, "(file=0x%p)\n", file);
#ifdef SECURE_DEVIRNET
/* This could (should?) be enforced by the permissions on /dev/irnet. */
if(!capable(CAP_NET_ADMIN))
return -EPERM;
#endif /* SECURE_DEVIRNET */
/* Allocate a private structure for this IrNET instance */
ap = kzalloc(sizeof(*ap), GFP_KERNEL);
DABORT(ap == NULL, -ENOMEM, FS_ERROR, "Can't allocate struct irnet...\n");
/* initialize the irnet structure */
ap->file = file;
/* PPP channel setup */
ap->ppp_open = 0;
ap->chan.private = ap;
ap->chan.ops = &irnet_ppp_ops;
ap->chan.mtu = (2048 - TTP_MAX_HEADER - 2 - PPP_HDRLEN);
ap->chan.hdrlen = 2 + TTP_MAX_HEADER; /* for A/C + Max IrDA hdr */
/* PPP parameters */
ap->mru = (2048 - TTP_MAX_HEADER - 2 - PPP_HDRLEN);
ap->xaccm[0] = ~0U;
ap->xaccm[3] = 0x60000000U;
ap->raccm = ~0U;
/* Setup the IrDA part... */
err = irda_irnet_create(ap);
if(err)
{
DERROR(FS_ERROR, "Can't setup IrDA link...\n");
kfree(ap);
return err;
}
/* For the control channel */
ap->event_index = irnet_events.index; /* Cancel all past events */
mutex_init(&ap->lock);
/* Put our stuff where we will be able to find it later */
file->private_data = ap;
DEXIT(FS_TRACE, " - ap=0x%p\n", ap);
return 0;
}
/*------------------------------------------------------------------*/
/*
* Close : when somebody close /dev/irnet
* Destroy the instance of /dev/irnet
*/
static int
dev_irnet_close(struct inode * inode,
struct file * file)
{
irnet_socket * ap = file->private_data;
DENTER(FS_TRACE, "(file=0x%p, ap=0x%p)\n",
file, ap);
DABORT(ap == NULL, 0, FS_ERROR, "ap is NULL !!!\n");
/* Detach ourselves */
file->private_data = NULL;
/* Close IrDA stuff */
irda_irnet_destroy(ap);
/* Disconnect from the generic PPP layer if not already done */
if(ap->ppp_open)
{
DERROR(FS_ERROR, "Channel still registered - deregistering !\n");
ap->ppp_open = 0;
ppp_unregister_channel(&ap->chan);
}
kfree(ap);
DEXIT(FS_TRACE, "\n");
return 0;
}
/*------------------------------------------------------------------*/
/*
* Write does nothing.
* (we receive packet from ppp_generic through ppp_irnet_send())
*/
static ssize_t
dev_irnet_write(struct file * file,
const char __user *buf,
size_t count,
loff_t * ppos)
{
irnet_socket * ap = file->private_data;
DPASS(FS_TRACE, "(file=0x%p, ap=0x%p, count=%Zd)\n",
file, ap, count);
DABORT(ap == NULL, -ENXIO, FS_ERROR, "ap is NULL !!!\n");
/* If we are connected to ppp_generic, let it handle the job */
if(ap->ppp_open)
return -EAGAIN;
else
return irnet_ctrl_write(ap, buf, count);
}
/*------------------------------------------------------------------*/
/*
* Read doesn't do much either.
* (pppd poll us, but ultimately reads through /dev/ppp)
*/
static ssize_t
dev_irnet_read(struct file * file,
char __user * buf,
size_t count,
loff_t * ppos)
{
irnet_socket * ap = file->private_data;
DPASS(FS_TRACE, "(file=0x%p, ap=0x%p, count=%Zd)\n",
file, ap, count);
DABORT(ap == NULL, -ENXIO, FS_ERROR, "ap is NULL !!!\n");
/* If we are connected to ppp_generic, let it handle the job */
if(ap->ppp_open)
return -EAGAIN;
else
return irnet_ctrl_read(ap, file, buf, count);
}
/*------------------------------------------------------------------*/
/*
* Poll : called when someone do a select on /dev/irnet
*/
static unsigned int
dev_irnet_poll(struct file * file,
poll_table * wait)
{
irnet_socket * ap = file->private_data;
unsigned int mask;
DENTER(FS_TRACE, "(file=0x%p, ap=0x%p)\n",
file, ap);
mask = POLLOUT | POLLWRNORM;
DABORT(ap == NULL, mask, FS_ERROR, "ap is NULL !!!\n");
/* If we are connected to ppp_generic, let it handle the job */
if(!ap->ppp_open)
mask |= irnet_ctrl_poll(ap, file, wait);
DEXIT(FS_TRACE, " - mask=0x%X\n", mask);
return mask;
}
/*------------------------------------------------------------------*/
/*
* IOCtl : Called when someone does some ioctls on /dev/irnet
* This is the way pppd configure us and control us while the PPP
* instance is active.
*/
static long
dev_irnet_ioctl(
struct file * file,
unsigned int cmd,
unsigned long arg)
{
irnet_socket * ap = file->private_data;
int err;
int val;
void __user *argp = (void __user *)arg;
DENTER(FS_TRACE, "(file=0x%p, ap=0x%p, cmd=0x%X)\n",
file, ap, cmd);
/* Basic checks... */
DASSERT(ap != NULL, -ENXIO, PPP_ERROR, "ap is NULL...\n");
#ifdef SECURE_DEVIRNET
if(!capable(CAP_NET_ADMIN))
return -EPERM;
#endif /* SECURE_DEVIRNET */
err = -EFAULT;
switch(cmd)
{
/* Set discipline (should be N_SYNC_PPP or N_TTY) */
case TIOCSETD:
if(get_user(val, (int __user *)argp))
break;
if((val == N_SYNC_PPP) || (val == N_PPP))
{
DEBUG(FS_INFO, "Entering PPP discipline.\n");
/* PPP channel setup (ap->chan in configured in dev_irnet_open())*/
if (mutex_lock_interruptible(&ap->lock))
return -EINTR;
err = ppp_register_channel(&ap->chan);
if(err == 0)
{
/* Our ppp side is active */
ap->ppp_open = 1;
DEBUG(FS_INFO, "Trying to establish a connection.\n");
/* Setup the IrDA link now - may fail... */
irda_irnet_connect(ap);
}
else
DERROR(FS_ERROR, "Can't setup PPP channel...\n");
mutex_unlock(&ap->lock);
}
else
{
/* In theory, should be N_TTY */
DEBUG(FS_INFO, "Exiting PPP discipline.\n");
/* Disconnect from the generic PPP layer */
if (mutex_lock_interruptible(&ap->lock))
return -EINTR;
if(ap->ppp_open)
{
ap->ppp_open = 0;
ppp_unregister_channel(&ap->chan);
}
else
DERROR(FS_ERROR, "Channel not registered !\n");
err = 0;
mutex_unlock(&ap->lock);
}
break;
/* Query PPP channel and unit number */
case PPPIOCGCHAN:
if (mutex_lock_interruptible(&ap->lock))
return -EINTR;
if(ap->ppp_open && !put_user(ppp_channel_index(&ap->chan),
(int __user *)argp))
err = 0;
mutex_unlock(&ap->lock);
break;
case PPPIOCGUNIT:
if (mutex_lock_interruptible(&ap->lock))
return -EINTR;
if(ap->ppp_open && !put_user(ppp_unit_number(&ap->chan),
(int __user *)argp))
err = 0;
mutex_unlock(&ap->lock);
break;
/* All these ioctls can be passed both directly and from ppp_generic,
* so we just deal with them in one place...
*/
case PPPIOCGFLAGS:
case PPPIOCSFLAGS:
case PPPIOCGASYNCMAP:
case PPPIOCSASYNCMAP:
case PPPIOCGRASYNCMAP:
case PPPIOCSRASYNCMAP:
case PPPIOCGXASYNCMAP:
case PPPIOCSXASYNCMAP:
case PPPIOCGMRU:
case PPPIOCSMRU:
DEBUG(FS_INFO, "Standard PPP ioctl.\n");
if(!capable(CAP_NET_ADMIN))
err = -EPERM;
else {
if (mutex_lock_interruptible(&ap->lock))
return -EINTR;
err = ppp_irnet_ioctl(&ap->chan, cmd, arg);
mutex_unlock(&ap->lock);
}
break;
/* TTY IOCTLs : Pretend that we are a tty, to keep pppd happy */
/* Get termios */
case TCGETS:
DEBUG(FS_INFO, "Get termios.\n");
if (mutex_lock_interruptible(&ap->lock))
return -EINTR;
#ifndef TCGETS2
if(!kernel_termios_to_user_termios((struct termios __user *)argp, &ap->termios))
err = 0;
#else
if(kernel_termios_to_user_termios_1((struct termios __user *)argp, &ap->termios))
err = 0;
#endif
mutex_unlock(&ap->lock);
break;
/* Set termios */
case TCSETSF:
DEBUG(FS_INFO, "Set termios.\n");
if (mutex_lock_interruptible(&ap->lock))
return -EINTR;
#ifndef TCGETS2
if(!user_termios_to_kernel_termios(&ap->termios, (struct termios __user *)argp))
err = 0;
#else
if(!user_termios_to_kernel_termios_1(&ap->termios, (struct termios __user *)argp))
err = 0;
#endif
mutex_unlock(&ap->lock);
break;
/* Set DTR/RTS */
case TIOCMBIS:
case TIOCMBIC:
/* Set exclusive/non-exclusive mode */
case TIOCEXCL:
case TIOCNXCL:
DEBUG(FS_INFO, "TTY compatibility.\n");
err = 0;
break;
case TCGETA:
DEBUG(FS_INFO, "TCGETA\n");
break;
case TCFLSH:
DEBUG(FS_INFO, "TCFLSH\n");
/* Note : this will flush buffers in PPP, so it *must* be done
* We should also worry that we don't accept junk here and that
* we get rid of our own buffers */
#ifdef FLUSH_TO_PPP
if (mutex_lock_interruptible(&ap->lock))
return -EINTR;
ppp_output_wakeup(&ap->chan);
mutex_unlock(&ap->lock);
#endif /* FLUSH_TO_PPP */
err = 0;
break;
case FIONREAD:
DEBUG(FS_INFO, "FIONREAD\n");
val = 0;
if(put_user(val, (int __user *)argp))
break;
err = 0;
break;
default:
DERROR(FS_ERROR, "Unsupported ioctl (0x%X)\n", cmd);
err = -ENOTTY;
}
DEXIT(FS_TRACE, " - err = 0x%X\n", err);
return err;
}
/************************** PPP CALLBACKS **************************/
/*
* This are the functions that the generic PPP driver in the kernel
* will call to communicate to us.
*/
/*------------------------------------------------------------------*/
/*
* Prepare the ppp frame for transmission over the IrDA socket.
* We make sure that the header space is enough, and we change ppp header
* according to flags passed by pppd.
* This is not a callback, but just a helper function used in ppp_irnet_send()
*/
static inline struct sk_buff *
irnet_prepare_skb(irnet_socket * ap,
struct sk_buff * skb)
{
unsigned char * data;
int proto; /* PPP protocol */
int islcp; /* Protocol == LCP */
int needaddr; /* Need PPP address */
DENTER(PPP_TRACE, "(ap=0x%p, skb=0x%p)\n",
ap, skb);
/* Extract PPP protocol from the frame */
data = skb->data;
proto = (data[0] << 8) + data[1];
/* LCP packets with codes between 1 (configure-request)
* and 7 (code-reject) must be sent as though no options
* have been negotiated. */
islcp = (proto == PPP_LCP) && (1 <= data[2]) && (data[2] <= 7);
/* compress protocol field if option enabled */
if((data[0] == 0) && (ap->flags & SC_COMP_PROT) && (!islcp))
skb_pull(skb,1);
/* Check if we need address/control fields */
needaddr = 2*((ap->flags & SC_COMP_AC) == 0 || islcp);
/* Is the skb headroom large enough to contain all IrDA-headers? */
if((skb_headroom(skb) < (ap->max_header_size + needaddr)) ||
(skb_shared(skb)))
{
struct sk_buff * new_skb;
DEBUG(PPP_INFO, "Reallocating skb\n");
/* Create a new skb */
new_skb = skb_realloc_headroom(skb, ap->max_header_size + needaddr);
/* We have to free the original skb anyway */
dev_kfree_skb(skb);
/* Did the realloc succeed ? */
DABORT(new_skb == NULL, NULL, PPP_ERROR, "Could not realloc skb\n");
/* Use the new skb instead */
skb = new_skb;
}
/* prepend address/control fields if necessary */
if(needaddr)
{
skb_push(skb, 2);
skb->data[0] = PPP_ALLSTATIONS;
skb->data[1] = PPP_UI;
}
DEXIT(PPP_TRACE, "\n");
return skb;
}
/*------------------------------------------------------------------*/
/*
* Send a packet to the peer over the IrTTP connection.
* Returns 1 iff the packet was accepted.
* Returns 0 iff packet was not consumed.
* If the packet was not accepted, we will call ppp_output_wakeup
* at some later time to reactivate flow control in ppp_generic.
*/
static int
ppp_irnet_send(struct ppp_channel * chan,
struct sk_buff * skb)
{
irnet_socket * self = (struct irnet_socket *) chan->private;
int ret;
DENTER(PPP_TRACE, "(channel=0x%p, ap/self=0x%p)\n",
chan, self);
/* Check if things are somewhat valid... */
DASSERT(self != NULL, 0, PPP_ERROR, "Self is NULL !!!\n");
/* Check if we are connected */
if(!(test_bit(0, &self->ttp_open)))
{
#ifdef CONNECT_IN_SEND
/* Let's try to connect one more time... */
/* Note : we won't be connected after this call, but we should be
* ready for next packet... */
/* If we are already connecting, this will fail */
irda_irnet_connect(self);
#endif /* CONNECT_IN_SEND */
DEBUG(PPP_INFO, "IrTTP not ready ! (%ld-%ld)\n",
self->ttp_open, self->ttp_connect);
/* Note : we can either drop the packet or block the packet.
*
* Blocking the packet allow us a better connection time,
* because by calling ppp_output_wakeup() we can have
* ppp_generic resending the LCP request immediately to us,
* rather than waiting for one of pppd periodic transmission of
* LCP request.
*
* On the other hand, if we block all packet, all those periodic
* transmissions of pppd accumulate in ppp_generic, creating a
* backlog of LCP request. When we eventually connect later on,
* we have to transmit all this backlog before we can connect
* proper (if we don't timeout before).
*
* The current strategy is as follow :
* While we are attempting to connect, we block packets to get
* a better connection time.
* If we fail to connect, we drain the queue and start dropping packets
*/
#ifdef BLOCK_WHEN_CONNECT
/* If we are attempting to connect */
if(test_bit(0, &self->ttp_connect))
{
/* Blocking packet, ppp_generic will retry later */
return 0;
}
#endif /* BLOCK_WHEN_CONNECT */
/* Dropping packet, pppd will retry later */
dev_kfree_skb(skb);
return 1;
}
/* Check if the queue can accept any packet, otherwise block */
if(self->tx_flow != FLOW_START)
DRETURN(0, PPP_INFO, "IrTTP queue full (%d skbs)...\n",
skb_queue_len(&self->tsap->tx_queue));
/* Prepare ppp frame for transmission */
skb = irnet_prepare_skb(self, skb);
DABORT(skb == NULL, 1, PPP_ERROR, "Prepare skb for Tx failed.\n");
/* Send the packet to IrTTP */
ret = irttp_data_request(self->tsap, skb);
if(ret < 0)
{
/*
* > IrTTPs tx queue is full, so we just have to
* > drop the frame! You might think that we should
* > just return -1 and don't deallocate the frame,
* > but that is dangerous since it's possible that
* > we have replaced the original skb with a new
* > one with larger headroom, and that would really
* > confuse do_dev_queue_xmit() in dev.c! I have
* > tried :-) DB
* Correction : we verify the flow control above (self->tx_flow),
* so we come here only if IrTTP doesn't like the packet (empty,
* too large, IrTTP not connected). In those rare cases, it's ok
* to drop it, we don't want to see it here again...
* Jean II
*/
DERROR(PPP_ERROR, "IrTTP doesn't like this packet !!! (0x%X)\n", ret);
/* irttp_data_request already free the packet */
}
DEXIT(PPP_TRACE, "\n");
return 1; /* Packet has been consumed */
}
/*------------------------------------------------------------------*/
/*
* Take care of the ioctls that ppp_generic doesn't want to deal with...
* Note : we are also called from dev_irnet_ioctl().
*/
static int
ppp_irnet_ioctl(struct ppp_channel * chan,
unsigned int cmd,
unsigned long arg)
{
irnet_socket * ap = (struct irnet_socket *) chan->private;
int err;
int val;
u32 accm[8];
void __user *argp = (void __user *)arg;
DENTER(PPP_TRACE, "(channel=0x%p, ap=0x%p, cmd=0x%X)\n",
chan, ap, cmd);
/* Basic checks... */
DASSERT(ap != NULL, -ENXIO, PPP_ERROR, "ap is NULL...\n");
err = -EFAULT;
switch(cmd)
{
/* PPP flags */
case PPPIOCGFLAGS:
val = ap->flags | ap->rbits;
if(put_user(val, (int __user *) argp))
break;
err = 0;
break;
case PPPIOCSFLAGS:
if(get_user(val, (int __user *) argp))
break;
ap->flags = val & ~SC_RCV_BITS;
ap->rbits = val & SC_RCV_BITS;
err = 0;
break;
/* Async map stuff - all dummy to please pppd */
case PPPIOCGASYNCMAP:
if(put_user(ap->xaccm[0], (u32 __user *) argp))
break;
err = 0;
break;
case PPPIOCSASYNCMAP:
if(get_user(ap->xaccm[0], (u32 __user *) argp))
break;
err = 0;
break;
case PPPIOCGRASYNCMAP:
if(put_user(ap->raccm, (u32 __user *) argp))
break;
err = 0;
break;
case PPPIOCSRASYNCMAP:
if(get_user(ap->raccm, (u32 __user *) argp))
break;
err = 0;
break;
case PPPIOCGXASYNCMAP:
if(copy_to_user(argp, ap->xaccm, sizeof(ap->xaccm)))
break;
err = 0;
break;
case PPPIOCSXASYNCMAP:
if(copy_from_user(accm, argp, sizeof(accm)))
break;
accm[2] &= ~0x40000000U; /* can't escape 0x5e */
accm[3] |= 0x60000000U; /* must escape 0x7d, 0x7e */
memcpy(ap->xaccm, accm, sizeof(ap->xaccm));
err = 0;
break;
/* Max PPP frame size */
case PPPIOCGMRU:
if(put_user(ap->mru, (int __user *) argp))
break;
err = 0;
break;
case PPPIOCSMRU:
if(get_user(val, (int __user *) argp))
break;
if(val < PPP_MRU)
val = PPP_MRU;
ap->mru = val;
err = 0;
break;
default:
DEBUG(PPP_INFO, "Unsupported ioctl (0x%X)\n", cmd);
err = -ENOIOCTLCMD;
}
DEXIT(PPP_TRACE, " - err = 0x%X\n", err);
return err;
}
/************************** INITIALISATION **************************/
/*
* Module initialisation and all that jazz...
*/
/*------------------------------------------------------------------*/
/*
* Hook our device callbacks in the filesystem, to connect our code
* to /dev/irnet
*/
static inline int __init
ppp_irnet_init(void)
{
int err = 0;
DENTER(MODULE_TRACE, "()\n");
/* Allocate ourselves as a minor in the misc range */
err = misc_register(&irnet_misc_device);
DEXIT(MODULE_TRACE, "\n");
return err;
}
/*------------------------------------------------------------------*/
/*
* Cleanup at exit...
*/
static inline void __exit
ppp_irnet_cleanup(void)
{
DENTER(MODULE_TRACE, "()\n");
/* De-allocate /dev/irnet minor in misc range */
misc_deregister(&irnet_misc_device);
DEXIT(MODULE_TRACE, "\n");
}
/*------------------------------------------------------------------*/
/*
* Module main entry point
*/
static int __init
irnet_init(void)
{
int err;
/* Initialise both parts... */
err = irda_irnet_init();
if(!err)
err = ppp_irnet_init();
return err;
}
/*------------------------------------------------------------------*/
/*
* Module exit
*/
static void __exit
irnet_cleanup(void)
{
irda_irnet_cleanup();
ppp_irnet_cleanup();
}
/*------------------------------------------------------------------*/
/*
* Module magic
*/
module_init(irnet_init);
module_exit(irnet_cleanup);
MODULE_AUTHOR("Jean Tourrilhes <jt@hpl.hp.com>");
MODULE_DESCRIPTION("IrNET : Synchronous PPP over IrDA");
MODULE_LICENSE("GPL");
MODULE_ALIAS_CHARDEV(10, 187);
| gpl-2.0 |
fastly/linux | drivers/video/bf537-lq035.c | 3240 | 22433 | /*
* Analog Devices Blackfin(BF537 STAMP) + SHARP TFT LCD.
* http://docs.blackfin.uclinux.org/doku.php?id=hw:cards:tft-lcd
*
* Copyright 2006-2010 Analog Devices Inc.
* Licensed under the GPL-2.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/delay.h>
#include <linux/fb.h>
#include <linux/ioport.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/gpio.h>
#include <linux/interrupt.h>
#include <linux/sched.h>
#include <linux/timer.h>
#include <linux/device.h>
#include <linux/backlight.h>
#include <linux/lcd.h>
#include <linux/i2c.h>
#include <linux/spinlock.h>
#include <linux/dma-mapping.h>
#include <linux/slab.h>
#include <linux/platform_device.h>
#include <asm/blackfin.h>
#include <asm/irq.h>
#include <asm/dpmc.h>
#include <asm/dma.h>
#include <asm/portmux.h>
#define NO_BL 1
#define MAX_BRIGHENESS 95
#define MIN_BRIGHENESS 5
#define NBR_PALETTE 256
static const unsigned short ppi_pins[] = {
P_PPI0_CLK, P_PPI0_D0, P_PPI0_D1, P_PPI0_D2, P_PPI0_D3,
P_PPI0_D4, P_PPI0_D5, P_PPI0_D6, P_PPI0_D7,
P_PPI0_D8, P_PPI0_D9, P_PPI0_D10, P_PPI0_D11,
P_PPI0_D12, P_PPI0_D13, P_PPI0_D14, P_PPI0_D15, 0
};
static unsigned char *fb_buffer; /* RGB Buffer */
static unsigned long *dma_desc_table;
static int t_conf_done, lq035_open_cnt;
static DEFINE_SPINLOCK(bfin_lq035_lock);
static int landscape;
module_param(landscape, int, 0);
MODULE_PARM_DESC(landscape,
"LANDSCAPE use 320x240 instead of Native 240x320 Resolution");
static int bgr;
module_param(bgr, int, 0);
MODULE_PARM_DESC(bgr,
"BGR use 16-bit BGR-565 instead of RGB-565");
static int nocursor = 1;
module_param(nocursor, int, 0644);
MODULE_PARM_DESC(nocursor, "cursor enable/disable");
static unsigned long current_brightness; /* backlight */
/* AD5280 vcomm */
static unsigned char vcomm_value = 150;
static struct i2c_client *ad5280_client;
static void set_vcomm(void)
{
int nr;
if (!ad5280_client)
return;
nr = i2c_smbus_write_byte_data(ad5280_client, 0x00, vcomm_value);
if (nr)
pr_err("i2c_smbus_write_byte_data fail: %d\n", nr);
}
static int ad5280_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
int ret;
if (!i2c_check_functionality(client->adapter,
I2C_FUNC_SMBUS_BYTE_DATA)) {
dev_err(&client->dev, "SMBUS Byte Data not Supported\n");
return -EIO;
}
ret = i2c_smbus_write_byte_data(client, 0x00, vcomm_value);
if (ret) {
dev_err(&client->dev, "write fail: %d\n", ret);
return ret;
}
ad5280_client = client;
return 0;
}
static int ad5280_remove(struct i2c_client *client)
{
ad5280_client = NULL;
return 0;
}
static const struct i2c_device_id ad5280_id[] = {
{"bf537-lq035-ad5280", 0},
{}
};
MODULE_DEVICE_TABLE(i2c, ad5280_id);
static struct i2c_driver ad5280_driver = {
.driver = {
.name = "bf537-lq035-ad5280",
},
.probe = ad5280_probe,
.remove = ad5280_remove,
.id_table = ad5280_id,
};
#ifdef CONFIG_PNAV10
#define MOD GPIO_PH13
#define bfin_write_TIMER_LP_CONFIG bfin_write_TIMER0_CONFIG
#define bfin_write_TIMER_LP_WIDTH bfin_write_TIMER0_WIDTH
#define bfin_write_TIMER_LP_PERIOD bfin_write_TIMER0_PERIOD
#define bfin_read_TIMER_LP_COUNTER bfin_read_TIMER0_COUNTER
#define TIMDIS_LP TIMDIS0
#define TIMEN_LP TIMEN0
#define bfin_write_TIMER_SPS_CONFIG bfin_write_TIMER1_CONFIG
#define bfin_write_TIMER_SPS_WIDTH bfin_write_TIMER1_WIDTH
#define bfin_write_TIMER_SPS_PERIOD bfin_write_TIMER1_PERIOD
#define TIMDIS_SPS TIMDIS1
#define TIMEN_SPS TIMEN1
#define bfin_write_TIMER_SP_CONFIG bfin_write_TIMER5_CONFIG
#define bfin_write_TIMER_SP_WIDTH bfin_write_TIMER5_WIDTH
#define bfin_write_TIMER_SP_PERIOD bfin_write_TIMER5_PERIOD
#define TIMDIS_SP TIMDIS5
#define TIMEN_SP TIMEN5
#define bfin_write_TIMER_PS_CLS_CONFIG bfin_write_TIMER2_CONFIG
#define bfin_write_TIMER_PS_CLS_WIDTH bfin_write_TIMER2_WIDTH
#define bfin_write_TIMER_PS_CLS_PERIOD bfin_write_TIMER2_PERIOD
#define TIMDIS_PS_CLS TIMDIS2
#define TIMEN_PS_CLS TIMEN2
#define bfin_write_TIMER_REV_CONFIG bfin_write_TIMER3_CONFIG
#define bfin_write_TIMER_REV_WIDTH bfin_write_TIMER3_WIDTH
#define bfin_write_TIMER_REV_PERIOD bfin_write_TIMER3_PERIOD
#define TIMDIS_REV TIMDIS3
#define TIMEN_REV TIMEN3
#define bfin_read_TIMER_REV_COUNTER bfin_read_TIMER3_COUNTER
#define FREQ_PPI_CLK (5*1024*1024) /* PPI_CLK 5MHz */
#define TIMERS {P_TMR0, P_TMR1, P_TMR2, P_TMR3, P_TMR5, 0}
#else
#define UD GPIO_PF13 /* Up / Down */
#define MOD GPIO_PF10
#define LBR GPIO_PF14 /* Left Right */
#define bfin_write_TIMER_LP_CONFIG bfin_write_TIMER6_CONFIG
#define bfin_write_TIMER_LP_WIDTH bfin_write_TIMER6_WIDTH
#define bfin_write_TIMER_LP_PERIOD bfin_write_TIMER6_PERIOD
#define bfin_read_TIMER_LP_COUNTER bfin_read_TIMER6_COUNTER
#define TIMDIS_LP TIMDIS6
#define TIMEN_LP TIMEN6
#define bfin_write_TIMER_SPS_CONFIG bfin_write_TIMER1_CONFIG
#define bfin_write_TIMER_SPS_WIDTH bfin_write_TIMER1_WIDTH
#define bfin_write_TIMER_SPS_PERIOD bfin_write_TIMER1_PERIOD
#define TIMDIS_SPS TIMDIS1
#define TIMEN_SPS TIMEN1
#define bfin_write_TIMER_SP_CONFIG bfin_write_TIMER0_CONFIG
#define bfin_write_TIMER_SP_WIDTH bfin_write_TIMER0_WIDTH
#define bfin_write_TIMER_SP_PERIOD bfin_write_TIMER0_PERIOD
#define TIMDIS_SP TIMDIS0
#define TIMEN_SP TIMEN0
#define bfin_write_TIMER_PS_CLS_CONFIG bfin_write_TIMER7_CONFIG
#define bfin_write_TIMER_PS_CLS_WIDTH bfin_write_TIMER7_WIDTH
#define bfin_write_TIMER_PS_CLS_PERIOD bfin_write_TIMER7_PERIOD
#define TIMDIS_PS_CLS TIMDIS7
#define TIMEN_PS_CLS TIMEN7
#define bfin_write_TIMER_REV_CONFIG bfin_write_TIMER5_CONFIG
#define bfin_write_TIMER_REV_WIDTH bfin_write_TIMER5_WIDTH
#define bfin_write_TIMER_REV_PERIOD bfin_write_TIMER5_PERIOD
#define TIMDIS_REV TIMDIS5
#define TIMEN_REV TIMEN5
#define bfin_read_TIMER_REV_COUNTER bfin_read_TIMER5_COUNTER
#define FREQ_PPI_CLK (6*1000*1000) /* PPI_CLK 6MHz */
#define TIMERS {P_TMR0, P_TMR1, P_TMR5, P_TMR6, P_TMR7, 0}
#endif
#define LCD_X_RES 240 /* Horizontal Resolution */
#define LCD_Y_RES 320 /* Vertical Resolution */
#define LCD_BBP 16 /* Bit Per Pixel */
/* the LCD and the DMA start counting differently;
* since one starts at 0 and the other starts at 1,
* we have a difference of 1 between START_LINES
* and U_LINES.
*/
#define START_LINES 8 /* lines for field flyback or field blanking signal */
#define U_LINES 9 /* number of undisplayed blanking lines */
#define FRAMES_PER_SEC (60)
#define DCLKS_PER_FRAME (FREQ_PPI_CLK/FRAMES_PER_SEC)
#define DCLKS_PER_LINE (DCLKS_PER_FRAME/(LCD_Y_RES+U_LINES))
#define PPI_CONFIG_VALUE (PORT_DIR|XFR_TYPE|DLEN_16|POLS)
#define PPI_DELAY_VALUE (0)
#define TIMER_CONFIG (PWM_OUT|PERIOD_CNT|TIN_SEL|CLK_SEL)
#define ACTIVE_VIDEO_MEM_OFFSET (LCD_X_RES*START_LINES*(LCD_BBP/8))
#define ACTIVE_VIDEO_MEM_SIZE (LCD_Y_RES*LCD_X_RES*(LCD_BBP/8))
#define TOTAL_VIDEO_MEM_SIZE ((LCD_Y_RES+U_LINES)*LCD_X_RES*(LCD_BBP/8))
#define TOTAL_DMA_DESC_SIZE (2 * sizeof(u32) * (LCD_Y_RES + U_LINES))
static void start_timers(void) /* CHECK with HW */
{
unsigned long flags;
local_irq_save(flags);
bfin_write_TIMER_ENABLE(TIMEN_REV);
SSYNC();
while (bfin_read_TIMER_REV_COUNTER() <= 11)
continue;
bfin_write_TIMER_ENABLE(TIMEN_LP);
SSYNC();
while (bfin_read_TIMER_LP_COUNTER() < 3)
continue;
bfin_write_TIMER_ENABLE(TIMEN_SP|TIMEN_SPS|TIMEN_PS_CLS);
SSYNC();
t_conf_done = 1;
local_irq_restore(flags);
}
static void config_timers(void)
{
/* Stop timers */
bfin_write_TIMER_DISABLE(TIMDIS_SP|TIMDIS_SPS|TIMDIS_REV|
TIMDIS_LP|TIMDIS_PS_CLS);
SSYNC();
/* LP, timer 6 */
bfin_write_TIMER_LP_CONFIG(TIMER_CONFIG|PULSE_HI);
bfin_write_TIMER_LP_WIDTH(1);
bfin_write_TIMER_LP_PERIOD(DCLKS_PER_LINE);
SSYNC();
/* SPS, timer 1 */
bfin_write_TIMER_SPS_CONFIG(TIMER_CONFIG|PULSE_HI);
bfin_write_TIMER_SPS_WIDTH(DCLKS_PER_LINE*2);
bfin_write_TIMER_SPS_PERIOD((DCLKS_PER_LINE * (LCD_Y_RES+U_LINES)));
SSYNC();
/* SP, timer 0 */
bfin_write_TIMER_SP_CONFIG(TIMER_CONFIG|PULSE_HI);
bfin_write_TIMER_SP_WIDTH(1);
bfin_write_TIMER_SP_PERIOD(DCLKS_PER_LINE);
SSYNC();
/* PS & CLS, timer 7 */
bfin_write_TIMER_PS_CLS_CONFIG(TIMER_CONFIG);
bfin_write_TIMER_PS_CLS_WIDTH(LCD_X_RES + START_LINES);
bfin_write_TIMER_PS_CLS_PERIOD(DCLKS_PER_LINE);
SSYNC();
#ifdef NO_BL
/* REV, timer 5 */
bfin_write_TIMER_REV_CONFIG(TIMER_CONFIG|PULSE_HI);
bfin_write_TIMER_REV_WIDTH(DCLKS_PER_LINE);
bfin_write_TIMER_REV_PERIOD(DCLKS_PER_LINE*2);
SSYNC();
#endif
}
static void config_ppi(void)
{
bfin_write_PPI_DELAY(PPI_DELAY_VALUE);
bfin_write_PPI_COUNT(LCD_X_RES-1);
/* 0x10 -> PORT_CFG -> 2 or 3 frame syncs */
bfin_write_PPI_CONTROL((PPI_CONFIG_VALUE|0x10) & (~POLS));
}
static int config_dma(void)
{
u32 i;
if (landscape) {
for (i = 0; i < U_LINES; ++i) {
/* blanking lines point to first line of fb_buffer */
dma_desc_table[2*i] = (unsigned long)&dma_desc_table[2*i+2];
dma_desc_table[2*i+1] = (unsigned long)fb_buffer;
}
for (i = U_LINES; i < U_LINES + LCD_Y_RES; ++i) {
/* visible lines */
dma_desc_table[2*i] = (unsigned long)&dma_desc_table[2*i+2];
dma_desc_table[2*i+1] = (unsigned long)fb_buffer +
(LCD_Y_RES+U_LINES-1-i)*2;
}
/* last descriptor points to first */
dma_desc_table[2*(LCD_Y_RES+U_LINES-1)] = (unsigned long)&dma_desc_table[0];
set_dma_x_count(CH_PPI, LCD_X_RES);
set_dma_x_modify(CH_PPI, LCD_Y_RES * (LCD_BBP / 8));
set_dma_y_count(CH_PPI, 0);
set_dma_y_modify(CH_PPI, 0);
set_dma_next_desc_addr(CH_PPI, (void *)dma_desc_table[0]);
set_dma_config(CH_PPI, DMAFLOW_LARGE | NDSIZE_4 | WDSIZE_16);
} else {
set_dma_config(CH_PPI, set_bfin_dma_config(DIR_READ,
DMA_FLOW_AUTO,
INTR_DISABLE,
DIMENSION_2D,
DATA_SIZE_16,
DMA_NOSYNC_KEEP_DMA_BUF));
set_dma_x_count(CH_PPI, LCD_X_RES);
set_dma_x_modify(CH_PPI, LCD_BBP / 8);
set_dma_y_count(CH_PPI, LCD_Y_RES+U_LINES);
set_dma_y_modify(CH_PPI, LCD_BBP / 8);
set_dma_start_addr(CH_PPI, (unsigned long) fb_buffer);
}
return 0;
}
static int request_ports(void)
{
u16 tmr_req[] = TIMERS;
/*
UD: PF13
MOD: PF10
LBR: PF14
PPI_CLK: PF15
*/
if (peripheral_request_list(ppi_pins, KBUILD_MODNAME)) {
pr_err("requesting PPI peripheral failed\n");
return -EBUSY;
}
if (peripheral_request_list(tmr_req, KBUILD_MODNAME)) {
peripheral_free_list(ppi_pins);
pr_err("requesting timer peripheral failed\n");
return -EBUSY;
}
#if (defined(UD) && defined(LBR))
if (gpio_request_one(UD, GPIOF_OUT_INIT_LOW, KBUILD_MODNAME)) {
pr_err("requesting GPIO %d failed\n", UD);
return -EBUSY;
}
if (gpio_request_one(LBR, GPIOF_OUT_INIT_HIGH, KBUILD_MODNAME)) {
pr_err("requesting GPIO %d failed\n", LBR);
gpio_free(UD);
return -EBUSY;
}
#endif
if (gpio_request_one(MOD, GPIOF_OUT_INIT_HIGH, KBUILD_MODNAME)) {
pr_err("requesting GPIO %d failed\n", MOD);
#if (defined(UD) && defined(LBR))
gpio_free(LBR);
gpio_free(UD);
#endif
return -EBUSY;
}
SSYNC();
return 0;
}
static void free_ports(void)
{
u16 tmr_req[] = TIMERS;
peripheral_free_list(ppi_pins);
peripheral_free_list(tmr_req);
#if defined(UD) && defined(LBR)
gpio_free(LBR);
gpio_free(UD);
#endif
gpio_free(MOD);
}
static struct fb_info bfin_lq035_fb;
static struct fb_var_screeninfo bfin_lq035_fb_defined = {
.bits_per_pixel = LCD_BBP,
.activate = FB_ACTIVATE_TEST,
.xres = LCD_X_RES, /*default portrait mode RGB*/
.yres = LCD_Y_RES,
.xres_virtual = LCD_X_RES,
.yres_virtual = LCD_Y_RES,
.height = -1,
.width = -1,
.left_margin = 0,
.right_margin = 0,
.upper_margin = 0,
.lower_margin = 0,
.red = {11, 5, 0},
.green = {5, 6, 0},
.blue = {0, 5, 0},
.transp = {0, 0, 0},
};
static struct fb_fix_screeninfo bfin_lq035_fb_fix = {
.id = KBUILD_MODNAME,
.smem_len = ACTIVE_VIDEO_MEM_SIZE,
.type = FB_TYPE_PACKED_PIXELS,
.visual = FB_VISUAL_TRUECOLOR,
.xpanstep = 0,
.ypanstep = 0,
.line_length = LCD_X_RES*(LCD_BBP/8),
.accel = FB_ACCEL_NONE,
};
static int bfin_lq035_fb_open(struct fb_info *info, int user)
{
unsigned long flags;
spin_lock_irqsave(&bfin_lq035_lock, flags);
lq035_open_cnt++;
spin_unlock_irqrestore(&bfin_lq035_lock, flags);
if (lq035_open_cnt <= 1) {
bfin_write_PPI_CONTROL(0);
SSYNC();
set_vcomm();
config_dma();
config_ppi();
/* start dma */
enable_dma(CH_PPI);
SSYNC();
bfin_write_PPI_CONTROL(bfin_read_PPI_CONTROL() | PORT_EN);
SSYNC();
if (!t_conf_done) {
config_timers();
start_timers();
}
/* gpio_set_value(MOD,1); */
}
return 0;
}
static int bfin_lq035_fb_release(struct fb_info *info, int user)
{
unsigned long flags;
spin_lock_irqsave(&bfin_lq035_lock, flags);
lq035_open_cnt--;
spin_unlock_irqrestore(&bfin_lq035_lock, flags);
if (lq035_open_cnt <= 0) {
bfin_write_PPI_CONTROL(0);
SSYNC();
disable_dma(CH_PPI);
}
return 0;
}
static int bfin_lq035_fb_check_var(struct fb_var_screeninfo *var,
struct fb_info *info)
{
switch (var->bits_per_pixel) {
case 16:/* DIRECTCOLOUR, 64k */
var->red.offset = info->var.red.offset;
var->green.offset = info->var.green.offset;
var->blue.offset = info->var.blue.offset;
var->red.length = info->var.red.length;
var->green.length = info->var.green.length;
var->blue.length = info->var.blue.length;
var->transp.offset = 0;
var->transp.length = 0;
var->transp.msb_right = 0;
var->red.msb_right = 0;
var->green.msb_right = 0;
var->blue.msb_right = 0;
break;
default:
pr_debug("%s: depth not supported: %u BPP\n", __func__,
var->bits_per_pixel);
return -EINVAL;
}
if (info->var.xres != var->xres ||
info->var.yres != var->yres ||
info->var.xres_virtual != var->xres_virtual ||
info->var.yres_virtual != var->yres_virtual) {
pr_debug("%s: Resolution not supported: X%u x Y%u\n",
__func__, var->xres, var->yres);
return -EINVAL;
}
/*
* Memory limit
*/
if ((info->fix.line_length * var->yres_virtual) > info->fix.smem_len) {
pr_debug("%s: Memory Limit requested yres_virtual = %u\n",
__func__, var->yres_virtual);
return -ENOMEM;
}
return 0;
}
/* fb_rotate
* Rotate the display of this angle. This doesn't seems to be used by the core,
* but as our hardware supports it, so why not implementing it...
*/
static void bfin_lq035_fb_rotate(struct fb_info *fbi, int angle)
{
pr_debug("%s: %p %d", __func__, fbi, angle);
#if (defined(UD) && defined(LBR))
switch (angle) {
case 180:
gpio_set_value(LBR, 0);
gpio_set_value(UD, 1);
break;
default:
gpio_set_value(LBR, 1);
gpio_set_value(UD, 0);
break;
}
#endif
}
static int bfin_lq035_fb_cursor(struct fb_info *info, struct fb_cursor *cursor)
{
if (nocursor)
return 0;
else
return -EINVAL; /* just to force soft_cursor() call */
}
static int bfin_lq035_fb_setcolreg(u_int regno, u_int red, u_int green,
u_int blue, u_int transp,
struct fb_info *info)
{
if (regno >= NBR_PALETTE)
return -EINVAL;
if (info->var.grayscale)
/* grayscale = 0.30*R + 0.59*G + 0.11*B */
red = green = blue = (red * 77 + green * 151 + blue * 28) >> 8;
if (info->fix.visual == FB_VISUAL_TRUECOLOR) {
u32 value;
/* Place color in the pseudopalette */
if (regno > 16)
return -EINVAL;
red >>= (16 - info->var.red.length);
green >>= (16 - info->var.green.length);
blue >>= (16 - info->var.blue.length);
value = (red << info->var.red.offset) |
(green << info->var.green.offset)|
(blue << info->var.blue.offset);
value &= 0xFFFF;
((u32 *) (info->pseudo_palette))[regno] = value;
}
return 0;
}
static struct fb_ops bfin_lq035_fb_ops = {
.owner = THIS_MODULE,
.fb_open = bfin_lq035_fb_open,
.fb_release = bfin_lq035_fb_release,
.fb_check_var = bfin_lq035_fb_check_var,
.fb_rotate = bfin_lq035_fb_rotate,
.fb_fillrect = cfb_fillrect,
.fb_copyarea = cfb_copyarea,
.fb_imageblit = cfb_imageblit,
.fb_cursor = bfin_lq035_fb_cursor,
.fb_setcolreg = bfin_lq035_fb_setcolreg,
};
static int bl_get_brightness(struct backlight_device *bd)
{
return current_brightness;
}
static const struct backlight_ops bfin_lq035fb_bl_ops = {
.get_brightness = bl_get_brightness,
};
static struct backlight_device *bl_dev;
static int bfin_lcd_get_power(struct lcd_device *dev)
{
return 0;
}
static int bfin_lcd_set_power(struct lcd_device *dev, int power)
{
return 0;
}
static int bfin_lcd_get_contrast(struct lcd_device *dev)
{
return (int)vcomm_value;
}
static int bfin_lcd_set_contrast(struct lcd_device *dev, int contrast)
{
if (contrast > 255)
contrast = 255;
if (contrast < 0)
contrast = 0;
vcomm_value = (unsigned char)contrast;
set_vcomm();
return 0;
}
static int bfin_lcd_check_fb(struct lcd_device *lcd, struct fb_info *fi)
{
if (!fi || (fi == &bfin_lq035_fb))
return 1;
return 0;
}
static struct lcd_ops bfin_lcd_ops = {
.get_power = bfin_lcd_get_power,
.set_power = bfin_lcd_set_power,
.get_contrast = bfin_lcd_get_contrast,
.set_contrast = bfin_lcd_set_contrast,
.check_fb = bfin_lcd_check_fb,
};
static struct lcd_device *lcd_dev;
static int bfin_lq035_probe(struct platform_device *pdev)
{
struct backlight_properties props;
dma_addr_t dma_handle;
int ret;
if (request_dma(CH_PPI, KBUILD_MODNAME)) {
pr_err("couldn't request PPI DMA\n");
return -EFAULT;
}
if (request_ports()) {
pr_err("couldn't request gpio port\n");
ret = -EFAULT;
goto out_ports;
}
fb_buffer = dma_alloc_coherent(NULL, TOTAL_VIDEO_MEM_SIZE,
&dma_handle, GFP_KERNEL);
if (fb_buffer == NULL) {
pr_err("couldn't allocate dma buffer\n");
ret = -ENOMEM;
goto out_dma_coherent;
}
if (L1_DATA_A_LENGTH)
dma_desc_table = l1_data_sram_zalloc(TOTAL_DMA_DESC_SIZE);
else
dma_desc_table = dma_alloc_coherent(NULL, TOTAL_DMA_DESC_SIZE,
&dma_handle, 0);
if (dma_desc_table == NULL) {
pr_err("couldn't allocate dma descriptor\n");
ret = -ENOMEM;
goto out_table;
}
bfin_lq035_fb.screen_base = (void *)fb_buffer;
bfin_lq035_fb_fix.smem_start = (int)fb_buffer;
if (landscape) {
bfin_lq035_fb_defined.xres = LCD_Y_RES;
bfin_lq035_fb_defined.yres = LCD_X_RES;
bfin_lq035_fb_defined.xres_virtual = LCD_Y_RES;
bfin_lq035_fb_defined.yres_virtual = LCD_X_RES;
bfin_lq035_fb_fix.line_length = LCD_Y_RES*(LCD_BBP/8);
} else {
bfin_lq035_fb.screen_base += ACTIVE_VIDEO_MEM_OFFSET;
bfin_lq035_fb_fix.smem_start += ACTIVE_VIDEO_MEM_OFFSET;
}
bfin_lq035_fb_defined.green.msb_right = 0;
bfin_lq035_fb_defined.red.msb_right = 0;
bfin_lq035_fb_defined.blue.msb_right = 0;
bfin_lq035_fb_defined.green.offset = 5;
bfin_lq035_fb_defined.green.length = 6;
bfin_lq035_fb_defined.red.length = 5;
bfin_lq035_fb_defined.blue.length = 5;
if (bgr) {
bfin_lq035_fb_defined.red.offset = 0;
bfin_lq035_fb_defined.blue.offset = 11;
} else {
bfin_lq035_fb_defined.red.offset = 11;
bfin_lq035_fb_defined.blue.offset = 0;
}
bfin_lq035_fb.fbops = &bfin_lq035_fb_ops;
bfin_lq035_fb.var = bfin_lq035_fb_defined;
bfin_lq035_fb.fix = bfin_lq035_fb_fix;
bfin_lq035_fb.flags = FBINFO_DEFAULT;
bfin_lq035_fb.pseudo_palette = devm_kzalloc(&pdev->dev,
sizeof(u32) * 16,
GFP_KERNEL);
if (bfin_lq035_fb.pseudo_palette == NULL) {
pr_err("failed to allocate pseudo_palette\n");
ret = -ENOMEM;
goto out_table;
}
if (fb_alloc_cmap(&bfin_lq035_fb.cmap, NBR_PALETTE, 0) < 0) {
pr_err("failed to allocate colormap (%d entries)\n",
NBR_PALETTE);
ret = -EFAULT;
goto out_table;
}
if (register_framebuffer(&bfin_lq035_fb) < 0) {
pr_err("unable to register framebuffer\n");
ret = -EINVAL;
goto out_reg;
}
i2c_add_driver(&ad5280_driver);
memset(&props, 0, sizeof(props));
props.type = BACKLIGHT_RAW;
props.max_brightness = MAX_BRIGHENESS;
bl_dev = backlight_device_register("bf537-bl", NULL, NULL,
&bfin_lq035fb_bl_ops, &props);
lcd_dev = lcd_device_register(KBUILD_MODNAME, &pdev->dev, NULL,
&bfin_lcd_ops);
if (IS_ERR(lcd_dev)) {
pr_err("unable to register lcd\n");
ret = PTR_ERR(lcd_dev);
goto out_lcd;
}
lcd_dev->props.max_contrast = 255,
pr_info("initialized");
return 0;
out_lcd:
unregister_framebuffer(&bfin_lq035_fb);
out_reg:
fb_dealloc_cmap(&bfin_lq035_fb.cmap);
out_table:
dma_free_coherent(NULL, TOTAL_VIDEO_MEM_SIZE, fb_buffer, 0);
fb_buffer = NULL;
out_dma_coherent:
free_ports();
out_ports:
free_dma(CH_PPI);
return ret;
}
static int bfin_lq035_remove(struct platform_device *pdev)
{
if (fb_buffer != NULL)
dma_free_coherent(NULL, TOTAL_VIDEO_MEM_SIZE, fb_buffer, 0);
if (L1_DATA_A_LENGTH)
l1_data_sram_free(dma_desc_table);
else
dma_free_coherent(NULL, TOTAL_DMA_DESC_SIZE, NULL, 0);
bfin_write_TIMER_DISABLE(TIMEN_SP|TIMEN_SPS|TIMEN_PS_CLS|
TIMEN_LP|TIMEN_REV);
t_conf_done = 0;
free_dma(CH_PPI);
fb_dealloc_cmap(&bfin_lq035_fb.cmap);
lcd_device_unregister(lcd_dev);
backlight_device_unregister(bl_dev);
unregister_framebuffer(&bfin_lq035_fb);
i2c_del_driver(&ad5280_driver);
free_ports();
pr_info("unregistered LCD driver\n");
return 0;
}
#ifdef CONFIG_PM
static int bfin_lq035_suspend(struct platform_device *pdev, pm_message_t state)
{
if (lq035_open_cnt > 0) {
bfin_write_PPI_CONTROL(0);
SSYNC();
disable_dma(CH_PPI);
}
return 0;
}
static int bfin_lq035_resume(struct platform_device *pdev)
{
if (lq035_open_cnt > 0) {
bfin_write_PPI_CONTROL(0);
SSYNC();
config_dma();
config_ppi();
enable_dma(CH_PPI);
bfin_write_PPI_CONTROL(bfin_read_PPI_CONTROL() | PORT_EN);
SSYNC();
config_timers();
start_timers();
} else {
t_conf_done = 0;
}
return 0;
}
#else
# define bfin_lq035_suspend NULL
# define bfin_lq035_resume NULL
#endif
static struct platform_driver bfin_lq035_driver = {
.probe = bfin_lq035_probe,
.remove = bfin_lq035_remove,
.suspend = bfin_lq035_suspend,
.resume = bfin_lq035_resume,
.driver = {
.name = KBUILD_MODNAME,
.owner = THIS_MODULE,
},
};
static int __init bfin_lq035_driver_init(void)
{
request_module("i2c-bfin-twi");
return platform_driver_register(&bfin_lq035_driver);
}
module_init(bfin_lq035_driver_init);
static void __exit bfin_lq035_driver_cleanup(void)
{
platform_driver_unregister(&bfin_lq035_driver);
}
module_exit(bfin_lq035_driver_cleanup);
MODULE_DESCRIPTION("SHARP LQ035Q7DB03 TFT LCD Driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
pablohaylan/I9500_Stock_Kernel_KK_4.4.2 | sound/soc/codecs/tlv320aic23.c | 4776 | 19256 | /*
* ALSA SoC TLV320AIC23 codec driver
*
* Author: Arun KS, <arunks@mistralsolutions.com>
* Copyright: (C) 2008 Mistral Solutions Pvt Ltd.,
*
* Based on sound/soc/codecs/wm8731.c by Richard Purdie
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* Notes:
* The AIC23 is a driver for a low power stereo audio
* codec tlv320aic23
*
* The machine layer should disable unsupported inputs/outputs by
* snd_soc_dapm_disable_pin(codec, "LHPOUT"), etc.
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/pm.h>
#include <linux/i2c.h>
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include <sound/tlv.h>
#include <sound/initval.h>
#include "tlv320aic23.h"
#define AIC23_VERSION "0.1"
/*
* AIC23 register cache
*/
static const u16 tlv320aic23_reg[] = {
0x0097, 0x0097, 0x00F9, 0x00F9, /* 0 */
0x001A, 0x0004, 0x0007, 0x0001, /* 4 */
0x0020, 0x0000, 0x0000, 0x0000, /* 8 */
0x0000, 0x0000, 0x0000, 0x0000, /* 12 */
};
static const char *rec_src_text[] = { "Line", "Mic" };
static const char *deemph_text[] = {"None", "32Khz", "44.1Khz", "48Khz"};
static const struct soc_enum rec_src_enum =
SOC_ENUM_SINGLE(TLV320AIC23_ANLG, 2, 2, rec_src_text);
static const struct snd_kcontrol_new tlv320aic23_rec_src_mux_controls =
SOC_DAPM_ENUM("Input Select", rec_src_enum);
static const struct soc_enum tlv320aic23_rec_src =
SOC_ENUM_SINGLE(TLV320AIC23_ANLG, 2, 2, rec_src_text);
static const struct soc_enum tlv320aic23_deemph =
SOC_ENUM_SINGLE(TLV320AIC23_DIGT, 1, 4, deemph_text);
static const DECLARE_TLV_DB_SCALE(out_gain_tlv, -12100, 100, 0);
static const DECLARE_TLV_DB_SCALE(input_gain_tlv, -1725, 75, 0);
static const DECLARE_TLV_DB_SCALE(sidetone_vol_tlv, -1800, 300, 0);
static int snd_soc_tlv320aic23_put_volsw(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
u16 val, reg;
val = (ucontrol->value.integer.value[0] & 0x07);
/* linear conversion to userspace
* 000 = -6db
* 001 = -9db
* 010 = -12db
* 011 = -18db (Min)
* 100 = 0db (Max)
*/
val = (val >= 4) ? 4 : (3 - val);
reg = snd_soc_read(codec, TLV320AIC23_ANLG) & (~0x1C0);
snd_soc_write(codec, TLV320AIC23_ANLG, reg | (val << 6));
return 0;
}
static int snd_soc_tlv320aic23_get_volsw(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
u16 val;
val = snd_soc_read(codec, TLV320AIC23_ANLG) & (0x1C0);
val = val >> 6;
val = (val >= 4) ? 4 : (3 - val);
ucontrol->value.integer.value[0] = val;
return 0;
}
static const struct snd_kcontrol_new tlv320aic23_snd_controls[] = {
SOC_DOUBLE_R_TLV("Digital Playback Volume", TLV320AIC23_LCHNVOL,
TLV320AIC23_RCHNVOL, 0, 127, 0, out_gain_tlv),
SOC_SINGLE("Digital Playback Switch", TLV320AIC23_DIGT, 3, 1, 1),
SOC_DOUBLE_R("Line Input Switch", TLV320AIC23_LINVOL,
TLV320AIC23_RINVOL, 7, 1, 0),
SOC_DOUBLE_R_TLV("Line Input Volume", TLV320AIC23_LINVOL,
TLV320AIC23_RINVOL, 0, 31, 0, input_gain_tlv),
SOC_SINGLE("Mic Input Switch", TLV320AIC23_ANLG, 1, 1, 1),
SOC_SINGLE("Mic Booster Switch", TLV320AIC23_ANLG, 0, 1, 0),
SOC_SINGLE_EXT_TLV("Sidetone Volume", TLV320AIC23_ANLG, 6, 4, 0,
snd_soc_tlv320aic23_get_volsw,
snd_soc_tlv320aic23_put_volsw, sidetone_vol_tlv),
SOC_ENUM("Playback De-emphasis", tlv320aic23_deemph),
};
/* PGA Mixer controls for Line and Mic switch */
static const struct snd_kcontrol_new tlv320aic23_output_mixer_controls[] = {
SOC_DAPM_SINGLE("Line Bypass Switch", TLV320AIC23_ANLG, 3, 1, 0),
SOC_DAPM_SINGLE("Mic Sidetone Switch", TLV320AIC23_ANLG, 5, 1, 0),
SOC_DAPM_SINGLE("Playback Switch", TLV320AIC23_ANLG, 4, 1, 0),
};
static const struct snd_soc_dapm_widget tlv320aic23_dapm_widgets[] = {
SND_SOC_DAPM_DAC("DAC", "Playback", TLV320AIC23_PWR, 3, 1),
SND_SOC_DAPM_ADC("ADC", "Capture", TLV320AIC23_PWR, 2, 1),
SND_SOC_DAPM_MUX("Capture Source", SND_SOC_NOPM, 0, 0,
&tlv320aic23_rec_src_mux_controls),
SND_SOC_DAPM_MIXER("Output Mixer", TLV320AIC23_PWR, 4, 1,
&tlv320aic23_output_mixer_controls[0],
ARRAY_SIZE(tlv320aic23_output_mixer_controls)),
SND_SOC_DAPM_PGA("Line Input", TLV320AIC23_PWR, 0, 1, NULL, 0),
SND_SOC_DAPM_PGA("Mic Input", TLV320AIC23_PWR, 1, 1, NULL, 0),
SND_SOC_DAPM_OUTPUT("LHPOUT"),
SND_SOC_DAPM_OUTPUT("RHPOUT"),
SND_SOC_DAPM_OUTPUT("LOUT"),
SND_SOC_DAPM_OUTPUT("ROUT"),
SND_SOC_DAPM_INPUT("LLINEIN"),
SND_SOC_DAPM_INPUT("RLINEIN"),
SND_SOC_DAPM_INPUT("MICIN"),
};
static const struct snd_soc_dapm_route tlv320aic23_intercon[] = {
/* Output Mixer */
{"Output Mixer", "Line Bypass Switch", "Line Input"},
{"Output Mixer", "Playback Switch", "DAC"},
{"Output Mixer", "Mic Sidetone Switch", "Mic Input"},
/* Outputs */
{"RHPOUT", NULL, "Output Mixer"},
{"LHPOUT", NULL, "Output Mixer"},
{"LOUT", NULL, "Output Mixer"},
{"ROUT", NULL, "Output Mixer"},
/* Inputs */
{"Line Input", "NULL", "LLINEIN"},
{"Line Input", "NULL", "RLINEIN"},
{"Mic Input", "NULL", "MICIN"},
/* input mux */
{"Capture Source", "Line", "Line Input"},
{"Capture Source", "Mic", "Mic Input"},
{"ADC", NULL, "Capture Source"},
};
/* AIC23 driver data */
struct aic23 {
enum snd_soc_control_type control_type;
int mclk;
int requested_adc;
int requested_dac;
};
/*
* Common Crystals used
* 11.2896 Mhz /128 = *88.2k /192 = 58.8k
* 12.0000 Mhz /125 = *96k /136 = 88.235K
* 12.2880 Mhz /128 = *96k /192 = 64k
* 16.9344 Mhz /128 = 132.3k /192 = *88.2k
* 18.4320 Mhz /128 = 144k /192 = *96k
*/
/*
* Normal BOSR 0-256/2 = 128, 1-384/2 = 192
* USB BOSR 0-250/2 = 125, 1-272/2 = 136
*/
static const int bosr_usb_divisor_table[] = {
128, 125, 192, 136
};
#define LOWER_GROUP ((1<<0) | (1<<1) | (1<<2) | (1<<3) | (1<<6) | (1<<7))
#define UPPER_GROUP ((1<<8) | (1<<9) | (1<<10) | (1<<11) | (1<<15))
static const unsigned short sr_valid_mask[] = {
LOWER_GROUP|UPPER_GROUP, /* Normal, bosr - 0*/
LOWER_GROUP, /* Usb, bosr - 0*/
LOWER_GROUP|UPPER_GROUP, /* Normal, bosr - 1*/
UPPER_GROUP, /* Usb, bosr - 1*/
};
/*
* Every divisor is a factor of 11*12
*/
#define SR_MULT (11*12)
#define A(x) (SR_MULT/x)
static const unsigned char sr_adc_mult_table[] = {
A(2), A(2), A(12), A(12), 0, 0, A(3), A(1),
A(2), A(2), A(11), A(11), 0, 0, 0, A(1)
};
static const unsigned char sr_dac_mult_table[] = {
A(2), A(12), A(2), A(12), 0, 0, A(3), A(1),
A(2), A(11), A(2), A(11), 0, 0, 0, A(1)
};
static unsigned get_score(int adc, int adc_l, int adc_h, int need_adc,
int dac, int dac_l, int dac_h, int need_dac)
{
if ((adc >= adc_l) && (adc <= adc_h) &&
(dac >= dac_l) && (dac <= dac_h)) {
int diff_adc = need_adc - adc;
int diff_dac = need_dac - dac;
return abs(diff_adc) + abs(diff_dac);
}
return UINT_MAX;
}
static int find_rate(int mclk, u32 need_adc, u32 need_dac)
{
int i, j;
int best_i = -1;
int best_j = -1;
int best_div = 0;
unsigned best_score = UINT_MAX;
int adc_l, adc_h, dac_l, dac_h;
need_adc *= SR_MULT;
need_dac *= SR_MULT;
/*
* rates given are +/- 1/32
*/
adc_l = need_adc - (need_adc >> 5);
adc_h = need_adc + (need_adc >> 5);
dac_l = need_dac - (need_dac >> 5);
dac_h = need_dac + (need_dac >> 5);
for (i = 0; i < ARRAY_SIZE(bosr_usb_divisor_table); i++) {
int base = mclk / bosr_usb_divisor_table[i];
int mask = sr_valid_mask[i];
for (j = 0; j < ARRAY_SIZE(sr_adc_mult_table);
j++, mask >>= 1) {
int adc;
int dac;
int score;
if ((mask & 1) == 0)
continue;
adc = base * sr_adc_mult_table[j];
dac = base * sr_dac_mult_table[j];
score = get_score(adc, adc_l, adc_h, need_adc,
dac, dac_l, dac_h, need_dac);
if (best_score > score) {
best_score = score;
best_i = i;
best_j = j;
best_div = 0;
}
score = get_score((adc >> 1), adc_l, adc_h, need_adc,
(dac >> 1), dac_l, dac_h, need_dac);
/* prefer to have a /2 */
if ((score != UINT_MAX) && (best_score >= score)) {
best_score = score;
best_i = i;
best_j = j;
best_div = 1;
}
}
}
return (best_j << 2) | best_i | (best_div << TLV320AIC23_CLKIN_SHIFT);
}
#ifdef DEBUG
static void get_current_sample_rates(struct snd_soc_codec *codec, int mclk,
u32 *sample_rate_adc, u32 *sample_rate_dac)
{
int src = snd_soc_read(codec, TLV320AIC23_SRATE);
int sr = (src >> 2) & 0x0f;
int val = (mclk / bosr_usb_divisor_table[src & 3]);
int adc = (val * sr_adc_mult_table[sr]) / SR_MULT;
int dac = (val * sr_dac_mult_table[sr]) / SR_MULT;
if (src & TLV320AIC23_CLKIN_HALF) {
adc >>= 1;
dac >>= 1;
}
*sample_rate_adc = adc;
*sample_rate_dac = dac;
}
#endif
static int set_sample_rate_control(struct snd_soc_codec *codec, int mclk,
u32 sample_rate_adc, u32 sample_rate_dac)
{
/* Search for the right sample rate */
int data = find_rate(mclk, sample_rate_adc, sample_rate_dac);
if (data < 0) {
printk(KERN_ERR "%s:Invalid rate %u,%u requested\n",
__func__, sample_rate_adc, sample_rate_dac);
return -EINVAL;
}
snd_soc_write(codec, TLV320AIC23_SRATE, data);
#ifdef DEBUG
{
u32 adc, dac;
get_current_sample_rates(codec, mclk, &adc, &dac);
printk(KERN_DEBUG "actual samplerate = %u,%u reg=%x\n",
adc, dac, data);
}
#endif
return 0;
}
static int tlv320aic23_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_codec *codec = rtd->codec;
u16 iface_reg;
int ret;
struct aic23 *aic23 = snd_soc_codec_get_drvdata(codec);
u32 sample_rate_adc = aic23->requested_adc;
u32 sample_rate_dac = aic23->requested_dac;
u32 sample_rate = params_rate(params);
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
aic23->requested_dac = sample_rate_dac = sample_rate;
if (!sample_rate_adc)
sample_rate_adc = sample_rate;
} else {
aic23->requested_adc = sample_rate_adc = sample_rate;
if (!sample_rate_dac)
sample_rate_dac = sample_rate;
}
ret = set_sample_rate_control(codec, aic23->mclk, sample_rate_adc,
sample_rate_dac);
if (ret < 0)
return ret;
iface_reg = snd_soc_read(codec, TLV320AIC23_DIGT_FMT) & ~(0x03 << 2);
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S16_LE:
break;
case SNDRV_PCM_FORMAT_S20_3LE:
iface_reg |= (0x01 << 2);
break;
case SNDRV_PCM_FORMAT_S24_LE:
iface_reg |= (0x02 << 2);
break;
case SNDRV_PCM_FORMAT_S32_LE:
iface_reg |= (0x03 << 2);
break;
}
snd_soc_write(codec, TLV320AIC23_DIGT_FMT, iface_reg);
return 0;
}
static int tlv320aic23_pcm_prepare(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_codec *codec = rtd->codec;
/* set active */
snd_soc_write(codec, TLV320AIC23_ACTIVE, 0x0001);
return 0;
}
static void tlv320aic23_shutdown(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_codec *codec = rtd->codec;
struct aic23 *aic23 = snd_soc_codec_get_drvdata(codec);
/* deactivate */
if (!codec->active) {
udelay(50);
snd_soc_write(codec, TLV320AIC23_ACTIVE, 0x0);
}
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
aic23->requested_dac = 0;
else
aic23->requested_adc = 0;
}
static int tlv320aic23_mute(struct snd_soc_dai *dai, int mute)
{
struct snd_soc_codec *codec = dai->codec;
u16 reg;
reg = snd_soc_read(codec, TLV320AIC23_DIGT);
if (mute)
reg |= TLV320AIC23_DACM_MUTE;
else
reg &= ~TLV320AIC23_DACM_MUTE;
snd_soc_write(codec, TLV320AIC23_DIGT, reg);
return 0;
}
static int tlv320aic23_set_dai_fmt(struct snd_soc_dai *codec_dai,
unsigned int fmt)
{
struct snd_soc_codec *codec = codec_dai->codec;
u16 iface_reg;
iface_reg = snd_soc_read(codec, TLV320AIC23_DIGT_FMT) & (~0x03);
/* set master/slave audio interface */
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBM_CFM:
iface_reg |= TLV320AIC23_MS_MASTER;
break;
case SND_SOC_DAIFMT_CBS_CFS:
iface_reg &= ~TLV320AIC23_MS_MASTER;
break;
default:
return -EINVAL;
}
/* interface format */
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_I2S:
iface_reg |= TLV320AIC23_FOR_I2S;
break;
case SND_SOC_DAIFMT_DSP_A:
iface_reg |= TLV320AIC23_LRP_ON;
case SND_SOC_DAIFMT_DSP_B:
iface_reg |= TLV320AIC23_FOR_DSP;
break;
case SND_SOC_DAIFMT_RIGHT_J:
break;
case SND_SOC_DAIFMT_LEFT_J:
iface_reg |= TLV320AIC23_FOR_LJUST;
break;
default:
return -EINVAL;
}
snd_soc_write(codec, TLV320AIC23_DIGT_FMT, iface_reg);
return 0;
}
static int tlv320aic23_set_dai_sysclk(struct snd_soc_dai *codec_dai,
int clk_id, unsigned int freq, int dir)
{
struct aic23 *aic23 = snd_soc_dai_get_drvdata(codec_dai);
aic23->mclk = freq;
return 0;
}
static int tlv320aic23_set_bias_level(struct snd_soc_codec *codec,
enum snd_soc_bias_level level)
{
u16 reg = snd_soc_read(codec, TLV320AIC23_PWR) & 0x17f;
switch (level) {
case SND_SOC_BIAS_ON:
/* vref/mid, osc on, dac unmute */
reg &= ~(TLV320AIC23_DEVICE_PWR_OFF | TLV320AIC23_OSC_OFF | \
TLV320AIC23_DAC_OFF);
snd_soc_write(codec, TLV320AIC23_PWR, reg);
break;
case SND_SOC_BIAS_PREPARE:
break;
case SND_SOC_BIAS_STANDBY:
/* everything off except vref/vmid, */
snd_soc_write(codec, TLV320AIC23_PWR,
reg | TLV320AIC23_CLK_OFF);
break;
case SND_SOC_BIAS_OFF:
/* everything off, dac mute, inactive */
snd_soc_write(codec, TLV320AIC23_ACTIVE, 0x0);
snd_soc_write(codec, TLV320AIC23_PWR, 0x1ff);
break;
}
codec->dapm.bias_level = level;
return 0;
}
#define AIC23_RATES SNDRV_PCM_RATE_8000_96000
#define AIC23_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S20_3LE | \
SNDRV_PCM_FMTBIT_S24_3LE | SNDRV_PCM_FMTBIT_S32_LE)
static const struct snd_soc_dai_ops tlv320aic23_dai_ops = {
.prepare = tlv320aic23_pcm_prepare,
.hw_params = tlv320aic23_hw_params,
.shutdown = tlv320aic23_shutdown,
.digital_mute = tlv320aic23_mute,
.set_fmt = tlv320aic23_set_dai_fmt,
.set_sysclk = tlv320aic23_set_dai_sysclk,
};
static struct snd_soc_dai_driver tlv320aic23_dai = {
.name = "tlv320aic23-hifi",
.playback = {
.stream_name = "Playback",
.channels_min = 2,
.channels_max = 2,
.rates = AIC23_RATES,
.formats = AIC23_FORMATS,},
.capture = {
.stream_name = "Capture",
.channels_min = 2,
.channels_max = 2,
.rates = AIC23_RATES,
.formats = AIC23_FORMATS,},
.ops = &tlv320aic23_dai_ops,
};
static int tlv320aic23_suspend(struct snd_soc_codec *codec)
{
tlv320aic23_set_bias_level(codec, SND_SOC_BIAS_OFF);
return 0;
}
static int tlv320aic23_resume(struct snd_soc_codec *codec)
{
snd_soc_cache_sync(codec);
tlv320aic23_set_bias_level(codec, SND_SOC_BIAS_STANDBY);
return 0;
}
static int tlv320aic23_probe(struct snd_soc_codec *codec)
{
struct aic23 *aic23 = snd_soc_codec_get_drvdata(codec);
int ret;
printk(KERN_INFO "AIC23 Audio Codec %s\n", AIC23_VERSION);
ret = snd_soc_codec_set_cache_io(codec, 7, 9, aic23->control_type);
if (ret < 0) {
dev_err(codec->dev, "Failed to set cache I/O: %d\n", ret);
return ret;
}
/* Reset codec */
snd_soc_write(codec, TLV320AIC23_RESET, 0);
/* Write the register default value to cache for reserved registers,
* so the write to the these registers are suppressed by the cache
* restore code when it skips writes of default registers.
*/
snd_soc_cache_write(codec, 0x0A, 0);
snd_soc_cache_write(codec, 0x0B, 0);
snd_soc_cache_write(codec, 0x0C, 0);
snd_soc_cache_write(codec, 0x0D, 0);
snd_soc_cache_write(codec, 0x0E, 0);
/* power on device */
tlv320aic23_set_bias_level(codec, SND_SOC_BIAS_STANDBY);
snd_soc_write(codec, TLV320AIC23_DIGT, TLV320AIC23_DEEMP_44K);
/* Unmute input */
snd_soc_update_bits(codec, TLV320AIC23_LINVOL,
TLV320AIC23_LIM_MUTED, TLV320AIC23_LRS_ENABLED);
snd_soc_update_bits(codec, TLV320AIC23_RINVOL,
TLV320AIC23_LIM_MUTED, TLV320AIC23_LRS_ENABLED);
snd_soc_update_bits(codec, TLV320AIC23_ANLG,
TLV320AIC23_BYPASS_ON | TLV320AIC23_MICM_MUTED,
0);
/* Default output volume */
snd_soc_write(codec, TLV320AIC23_LCHNVOL,
TLV320AIC23_DEFAULT_OUT_VOL & TLV320AIC23_OUT_VOL_MASK);
snd_soc_write(codec, TLV320AIC23_RCHNVOL,
TLV320AIC23_DEFAULT_OUT_VOL & TLV320AIC23_OUT_VOL_MASK);
snd_soc_write(codec, TLV320AIC23_ACTIVE, 0x1);
snd_soc_add_codec_controls(codec, tlv320aic23_snd_controls,
ARRAY_SIZE(tlv320aic23_snd_controls));
return 0;
}
static int tlv320aic23_remove(struct snd_soc_codec *codec)
{
tlv320aic23_set_bias_level(codec, SND_SOC_BIAS_OFF);
return 0;
}
static struct snd_soc_codec_driver soc_codec_dev_tlv320aic23 = {
.reg_cache_size = ARRAY_SIZE(tlv320aic23_reg),
.reg_word_size = sizeof(u16),
.reg_cache_default = tlv320aic23_reg,
.probe = tlv320aic23_probe,
.remove = tlv320aic23_remove,
.suspend = tlv320aic23_suspend,
.resume = tlv320aic23_resume,
.set_bias_level = tlv320aic23_set_bias_level,
.dapm_widgets = tlv320aic23_dapm_widgets,
.num_dapm_widgets = ARRAY_SIZE(tlv320aic23_dapm_widgets),
.dapm_routes = tlv320aic23_intercon,
.num_dapm_routes = ARRAY_SIZE(tlv320aic23_intercon),
};
#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
/*
* If the i2c layer weren't so broken, we could pass this kind of data
* around
*/
static int tlv320aic23_codec_probe(struct i2c_client *i2c,
const struct i2c_device_id *i2c_id)
{
struct aic23 *aic23;
int ret;
if (!i2c_check_functionality(i2c->adapter, I2C_FUNC_SMBUS_BYTE_DATA))
return -EINVAL;
aic23 = devm_kzalloc(&i2c->dev, sizeof(struct aic23), GFP_KERNEL);
if (aic23 == NULL)
return -ENOMEM;
i2c_set_clientdata(i2c, aic23);
aic23->control_type = SND_SOC_I2C;
ret = snd_soc_register_codec(&i2c->dev,
&soc_codec_dev_tlv320aic23, &tlv320aic23_dai, 1);
return ret;
}
static int __exit tlv320aic23_i2c_remove(struct i2c_client *i2c)
{
snd_soc_unregister_codec(&i2c->dev);
return 0;
}
static const struct i2c_device_id tlv320aic23_id[] = {
{"tlv320aic23", 0},
{}
};
MODULE_DEVICE_TABLE(i2c, tlv320aic23_id);
static struct i2c_driver tlv320aic23_i2c_driver = {
.driver = {
.name = "tlv320aic23-codec",
},
.probe = tlv320aic23_codec_probe,
.remove = __exit_p(tlv320aic23_i2c_remove),
.id_table = tlv320aic23_id,
};
#endif
static int __init tlv320aic23_modinit(void)
{
int ret;
#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
ret = i2c_add_driver(&tlv320aic23_i2c_driver);
if (ret != 0) {
printk(KERN_ERR "Failed to register TLV320AIC23 I2C driver: %d\n",
ret);
}
#endif
return ret;
}
module_init(tlv320aic23_modinit);
static void __exit tlv320aic23_exit(void)
{
#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
i2c_del_driver(&tlv320aic23_i2c_driver);
#endif
}
module_exit(tlv320aic23_exit);
MODULE_DESCRIPTION("ASoC TLV320AIC23 codec driver");
MODULE_AUTHOR("Arun KS <arunks@mistralsolutions.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
javelinanddart/kernel_samsung_jf | drivers/staging/media/solo6x10/enc.c | 5800 | 7302 | /*
* Copyright (C) 2010 Bluecherry, LLC www.bluecherrydvr.com
* Copyright (C) 2010 Ben Collins <bcollins@bluecherry.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include "solo6x10.h"
#include "osd-font.h"
#define CAPTURE_MAX_BANDWIDTH 32 /* D1 4channel (D1 == 4) */
#define OSG_BUFFER_SIZE 1024
#define VI_PROG_HSIZE (1280 - 16)
#define VI_PROG_VSIZE (1024 - 16)
static void solo_capture_config(struct solo_dev *solo_dev)
{
int i, j;
unsigned long height;
unsigned long width;
unsigned char *buf;
solo_reg_write(solo_dev, SOLO_CAP_BASE,
SOLO_CAP_MAX_PAGE(SOLO_CAP_EXT_MAX_PAGE *
solo_dev->nr_chans) |
SOLO_CAP_BASE_ADDR(SOLO_CAP_EXT_ADDR(solo_dev) >> 16));
solo_reg_write(solo_dev, SOLO_CAP_BTW,
(1 << 17) | SOLO_CAP_PROG_BANDWIDTH(2) |
SOLO_CAP_MAX_BANDWIDTH(CAPTURE_MAX_BANDWIDTH));
/* Set scale 1, 9 dimension */
width = solo_dev->video_hsize;
height = solo_dev->video_vsize;
solo_reg_write(solo_dev, SOLO_DIM_SCALE1,
SOLO_DIM_H_MB_NUM(width / 16) |
SOLO_DIM_V_MB_NUM_FRAME(height / 8) |
SOLO_DIM_V_MB_NUM_FIELD(height / 16));
/* Set scale 2, 10 dimension */
width = solo_dev->video_hsize / 2;
height = solo_dev->video_vsize;
solo_reg_write(solo_dev, SOLO_DIM_SCALE2,
SOLO_DIM_H_MB_NUM(width / 16) |
SOLO_DIM_V_MB_NUM_FRAME(height / 8) |
SOLO_DIM_V_MB_NUM_FIELD(height / 16));
/* Set scale 3, 11 dimension */
width = solo_dev->video_hsize / 2;
height = solo_dev->video_vsize / 2;
solo_reg_write(solo_dev, SOLO_DIM_SCALE3,
SOLO_DIM_H_MB_NUM(width / 16) |
SOLO_DIM_V_MB_NUM_FRAME(height / 8) |
SOLO_DIM_V_MB_NUM_FIELD(height / 16));
/* Set scale 4, 12 dimension */
width = solo_dev->video_hsize / 3;
height = solo_dev->video_vsize / 3;
solo_reg_write(solo_dev, SOLO_DIM_SCALE4,
SOLO_DIM_H_MB_NUM(width / 16) |
SOLO_DIM_V_MB_NUM_FRAME(height / 8) |
SOLO_DIM_V_MB_NUM_FIELD(height / 16));
/* Set scale 5, 13 dimension */
width = solo_dev->video_hsize / 4;
height = solo_dev->video_vsize / 2;
solo_reg_write(solo_dev, SOLO_DIM_SCALE5,
SOLO_DIM_H_MB_NUM(width / 16) |
SOLO_DIM_V_MB_NUM_FRAME(height / 8) |
SOLO_DIM_V_MB_NUM_FIELD(height / 16));
/* Progressive */
width = VI_PROG_HSIZE;
height = VI_PROG_VSIZE;
solo_reg_write(solo_dev, SOLO_DIM_PROG,
SOLO_DIM_H_MB_NUM(width / 16) |
SOLO_DIM_V_MB_NUM_FRAME(height / 16) |
SOLO_DIM_V_MB_NUM_FIELD(height / 16));
/* Clear OSD */
solo_reg_write(solo_dev, SOLO_VE_OSD_CH, 0);
solo_reg_write(solo_dev, SOLO_VE_OSD_BASE, SOLO_EOSD_EXT_ADDR >> 16);
solo_reg_write(solo_dev, SOLO_VE_OSD_CLR,
0xF0 << 16 | 0x80 << 8 | 0x80);
solo_reg_write(solo_dev, SOLO_VE_OSD_OPT, 0);
/* Clear OSG buffer */
buf = kzalloc(OSG_BUFFER_SIZE, GFP_KERNEL);
if (!buf)
return;
for (i = 0; i < solo_dev->nr_chans; i++) {
for (j = 0; j < SOLO_EOSD_EXT_SIZE; j += OSG_BUFFER_SIZE) {
solo_p2m_dma(solo_dev, SOLO_P2M_DMA_ID_MP4E, 1, buf,
SOLO_EOSD_EXT_ADDR +
(i * SOLO_EOSD_EXT_SIZE) + j,
OSG_BUFFER_SIZE);
}
}
kfree(buf);
}
int solo_osd_print(struct solo_enc_dev *solo_enc)
{
struct solo_dev *solo_dev = solo_enc->solo_dev;
char *str = solo_enc->osd_text;
u8 *buf;
u32 reg = solo_reg_read(solo_dev, SOLO_VE_OSD_CH);
int len = strlen(str);
int i, j;
int x = 1, y = 1;
if (len == 0) {
reg &= ~(1 << solo_enc->ch);
solo_reg_write(solo_dev, SOLO_VE_OSD_CH, reg);
return 0;
}
buf = kzalloc(SOLO_EOSD_EXT_SIZE, GFP_KERNEL);
if (!buf)
return -ENOMEM;
for (i = 0; i < len; i++) {
for (j = 0; j < 16; j++) {
buf[(j*2) + (i%2) + ((x + (i/2)) * 32) + (y * 2048)] =
(solo_osd_font[(str[i] * 4) + (j / 4)]
>> ((3 - (j % 4)) * 8)) & 0xff;
}
}
solo_p2m_dma(solo_dev, 0, 1, buf, SOLO_EOSD_EXT_ADDR +
(solo_enc->ch * SOLO_EOSD_EXT_SIZE), SOLO_EOSD_EXT_SIZE);
reg |= (1 << solo_enc->ch);
solo_reg_write(solo_dev, SOLO_VE_OSD_CH, reg);
kfree(buf);
return 0;
}
static void solo_jpeg_config(struct solo_dev *solo_dev)
{
u32 reg;
if (solo_dev->flags & FLAGS_6110)
reg = (4 << 24) | (3 << 16) | (2 << 8) | (1 << 0);
else
reg = (2 << 24) | (2 << 16) | (2 << 8) | (2 << 0);
solo_reg_write(solo_dev, SOLO_VE_JPEG_QP_TBL, reg);
solo_reg_write(solo_dev, SOLO_VE_JPEG_QP_CH_L, 0);
solo_reg_write(solo_dev, SOLO_VE_JPEG_QP_CH_H, 0);
solo_reg_write(solo_dev, SOLO_VE_JPEG_CFG,
(SOLO_JPEG_EXT_SIZE(solo_dev) & 0xffff0000) |
((SOLO_JPEG_EXT_ADDR(solo_dev) >> 16) & 0x0000ffff));
solo_reg_write(solo_dev, SOLO_VE_JPEG_CTRL, 0xffffffff);
/* que limit, samp limit, pos limit */
solo_reg_write(solo_dev, 0x0688, (0 << 16) | (30 << 8) | 60);
}
static void solo_mp4e_config(struct solo_dev *solo_dev)
{
int i;
u32 reg;
/* We can only use VE_INTR_CTRL(0) if we want to support mjpeg */
solo_reg_write(solo_dev, SOLO_VE_CFG0,
SOLO_VE_INTR_CTRL(0) |
SOLO_VE_BLOCK_SIZE(SOLO_MP4E_EXT_SIZE(solo_dev) >> 16) |
SOLO_VE_BLOCK_BASE(SOLO_MP4E_EXT_ADDR(solo_dev) >> 16));
solo_reg_write(solo_dev, SOLO_VE_CFG1,
SOLO_VE_INSERT_INDEX | SOLO_VE_MOTION_MODE(0));
solo_reg_write(solo_dev, SOLO_VE_WMRK_POLY, 0);
solo_reg_write(solo_dev, SOLO_VE_VMRK_INIT_KEY, 0);
solo_reg_write(solo_dev, SOLO_VE_WMRK_STRL, 0);
solo_reg_write(solo_dev, SOLO_VE_ENCRYP_POLY, 0);
solo_reg_write(solo_dev, SOLO_VE_ENCRYP_INIT, 0);
reg = SOLO_VE_LITTLE_ENDIAN | SOLO_COMP_ATTR_FCODE(1) |
SOLO_COMP_TIME_INC(0) | SOLO_COMP_TIME_WIDTH(15);
if (solo_dev->flags & FLAGS_6110)
reg |= SOLO_DCT_INTERVAL(10);
else
reg |= SOLO_DCT_INTERVAL(36 / 4);
solo_reg_write(solo_dev, SOLO_VE_ATTR, reg);
for (i = 0; i < solo_dev->nr_chans; i++)
solo_reg_write(solo_dev, SOLO_VE_CH_REF_BASE(i),
(SOLO_EREF_EXT_ADDR(solo_dev) +
(i * SOLO_EREF_EXT_SIZE)) >> 16);
if (solo_dev->flags & FLAGS_6110)
solo_reg_write(solo_dev, 0x0634, 0x00040008); /* ? */
}
int solo_enc_init(struct solo_dev *solo_dev)
{
int i;
solo_capture_config(solo_dev);
solo_mp4e_config(solo_dev);
solo_jpeg_config(solo_dev);
for (i = 0; i < solo_dev->nr_chans; i++) {
solo_reg_write(solo_dev, SOLO_CAP_CH_SCALE(i), 0);
solo_reg_write(solo_dev, SOLO_CAP_CH_COMP_ENA_E(i), 0);
}
solo_irq_on(solo_dev, SOLO_IRQ_ENCODER);
return 0;
}
void solo_enc_exit(struct solo_dev *solo_dev)
{
int i;
solo_irq_off(solo_dev, SOLO_IRQ_ENCODER);
for (i = 0; i < solo_dev->nr_chans; i++) {
solo_reg_write(solo_dev, SOLO_CAP_CH_SCALE(i), 0);
solo_reg_write(solo_dev, SOLO_CAP_CH_COMP_ENA_E(i), 0);
}
}
| gpl-2.0 |
ShadySquirrel/lge-kernel-gproj | arch/arm/plat-spear/padmux.c | 8104 | 3900 | /*
* arch/arm/plat-spear/include/plat/padmux.c
*
* SPEAr platform specific gpio pads muxing source file
*
* Copyright (C) 2009 ST Microelectronics
* Viresh Kumar<viresh.kumar@st.com>
*
* This file is licensed under the terms of the GNU General Public
* License version 2. This program is licensed "as is" without any
* warranty of any kind, whether express or implied.
*/
#include <linux/err.h>
#include <linux/io.h>
#include <linux/slab.h>
#include <plat/padmux.h>
/*
* struct pmx: pmx definition structure
*
* base: base address of configuration registers
* mode_reg: mode configurations
* mux_reg: muxing configurations
* active_mode: pointer to current active mode
*/
struct pmx {
u32 base;
struct pmx_reg mode_reg;
struct pmx_reg mux_reg;
struct pmx_mode *active_mode;
};
static struct pmx *pmx;
/**
* pmx_mode_set - Enables an multiplexing mode
* @mode - pointer to pmx mode
*
* It will set mode of operation in hardware.
* Returns -ve on Err otherwise 0
*/
static int pmx_mode_set(struct pmx_mode *mode)
{
u32 val;
if (!mode->name)
return -EFAULT;
pmx->active_mode = mode;
val = readl(pmx->base + pmx->mode_reg.offset);
val &= ~pmx->mode_reg.mask;
val |= mode->mask & pmx->mode_reg.mask;
writel(val, pmx->base + pmx->mode_reg.offset);
return 0;
}
/**
* pmx_devs_enable - Enables list of devices
* @devs - pointer to pmx device array
* @count - number of devices to enable
*
* It will enable pads for all required peripherals once and only once.
* If peripheral is not supported by current mode then request is rejected.
* Conflicts between peripherals are not handled and peripherals will be
* enabled in the order they are present in pmx_dev array.
* In case of conflicts last peripheral enabled will be present.
* Returns -ve on Err otherwise 0
*/
static int pmx_devs_enable(struct pmx_dev **devs, u8 count)
{
u32 val, i, mask;
if (!count)
return -EINVAL;
val = readl(pmx->base + pmx->mux_reg.offset);
for (i = 0; i < count; i++) {
u8 j = 0;
if (!devs[i]->name || !devs[i]->modes) {
printk(KERN_ERR "padmux: dev name or modes is null\n");
continue;
}
/* check if peripheral exists in active mode */
if (pmx->active_mode) {
bool found = false;
for (j = 0; j < devs[i]->mode_count; j++) {
if (devs[i]->modes[j].ids &
pmx->active_mode->id) {
found = true;
break;
}
}
if (found == false) {
printk(KERN_ERR "%s device not available in %s"\
"mode\n", devs[i]->name,
pmx->active_mode->name);
continue;
}
}
/* enable peripheral */
mask = devs[i]->modes[j].mask & pmx->mux_reg.mask;
if (devs[i]->enb_on_reset)
val &= ~mask;
else
val |= mask;
devs[i]->is_active = true;
}
writel(val, pmx->base + pmx->mux_reg.offset);
kfree(pmx);
/* this will ensure that multiplexing can't be changed now */
pmx = (struct pmx *)-1;
return 0;
}
/**
* pmx_register - registers a platform requesting pad mux feature
* @driver - pointer to driver structure containing driver specific parameters
*
* Also this must be called only once. This will allocate memory for pmx
* structure, will call pmx_mode_set, will call pmx_devs_enable.
* Returns -ve on Err otherwise 0
*/
int pmx_register(struct pmx_driver *driver)
{
int ret = 0;
if (pmx)
return -EPERM;
if (!driver->base || !driver->devs)
return -EFAULT;
pmx = kzalloc(sizeof(*pmx), GFP_KERNEL);
if (!pmx)
return -ENOMEM;
pmx->base = (u32)driver->base;
pmx->mode_reg.offset = driver->mode_reg.offset;
pmx->mode_reg.mask = driver->mode_reg.mask;
pmx->mux_reg.offset = driver->mux_reg.offset;
pmx->mux_reg.mask = driver->mux_reg.mask;
/* choose mode to enable */
if (driver->mode) {
ret = pmx_mode_set(driver->mode);
if (ret)
goto pmx_fail;
}
ret = pmx_devs_enable(driver->devs, driver->devs_count);
if (ret)
goto pmx_fail;
return 0;
pmx_fail:
return ret;
}
| gpl-2.0 |
Split-Screen/android_kernel_motorola_msm8610 | lib/find_last_bit.c | 8104 | 1139 | /* find_last_bit.c: fallback find next bit implementation
*
* Copyright (C) 2008 IBM Corporation
* Written by Rusty Russell <rusty@rustcorp.com.au>
* (Inspired by David Howell's find_next_bit implementation)
*
* 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/bitops.h>
#include <linux/export.h>
#include <asm/types.h>
#include <asm/byteorder.h>
#ifndef find_last_bit
unsigned long find_last_bit(const unsigned long *addr, unsigned long size)
{
unsigned long words;
unsigned long tmp;
/* Start at final word. */
words = size / BITS_PER_LONG;
/* Partial final word? */
if (size & (BITS_PER_LONG-1)) {
tmp = (addr[words] & (~0UL >> (BITS_PER_LONG
- (size & (BITS_PER_LONG-1)))));
if (tmp)
goto found;
}
while (words) {
tmp = addr[--words];
if (tmp) {
found:
return words * BITS_PER_LONG + __fls(tmp);
}
}
/* Not found */
return size;
}
EXPORT_SYMBOL(find_last_bit);
#endif
| gpl-2.0 |
klquicksall/Galaxy-Nexus-4.2 | arch/powerpc/math-emu/fnmadds.c | 13736 | 1169 | #include <linux/types.h>
#include <linux/errno.h>
#include <asm/uaccess.h>
#include <asm/sfp-machine.h>
#include <math-emu/soft-fp.h>
#include <math-emu/double.h>
#include <math-emu/single.h>
int
fnmadds(void *frD, void *frA, void *frB, void *frC)
{
FP_DECL_D(R);
FP_DECL_D(A);
FP_DECL_D(B);
FP_DECL_D(C);
FP_DECL_D(T);
FP_DECL_EX;
#ifdef DEBUG
printk("%s: %p %p %p %p\n", __func__, frD, frA, frB, frC);
#endif
FP_UNPACK_DP(A, frA);
FP_UNPACK_DP(B, frB);
FP_UNPACK_DP(C, frC);
#ifdef DEBUG
printk("A: %ld %lu %lu %ld (%ld)\n", A_s, A_f1, A_f0, A_e, A_c);
printk("B: %ld %lu %lu %ld (%ld)\n", B_s, B_f1, B_f0, B_e, B_c);
printk("C: %ld %lu %lu %ld (%ld)\n", C_s, C_f1, C_f0, C_e, C_c);
#endif
if ((A_c == FP_CLS_INF && C_c == FP_CLS_ZERO) ||
(A_c == FP_CLS_ZERO && C_c == FP_CLS_INF))
FP_SET_EXCEPTION(EFLAG_VXIMZ);
FP_MUL_D(T, A, C);
if (T_s != B_s && T_c == FP_CLS_INF && B_c == FP_CLS_INF)
FP_SET_EXCEPTION(EFLAG_VXISI);
FP_ADD_D(R, T, B);
if (R_c != FP_CLS_NAN)
R_s ^= 1;
#ifdef DEBUG
printk("D: %ld %lu %lu %ld (%ld)\n", R_s, R_f1, R_f0, R_e, R_c);
#endif
__FP_PACK_DS(frD, R);
return FP_CUR_EXCEPTIONS;
}
| gpl-2.0 |
lordeko/Alucard-Kernel-jfltexx | arch/powerpc/math-emu/fnmsubs.c | 13736 | 1192 | #include <linux/types.h>
#include <linux/errno.h>
#include <asm/uaccess.h>
#include <asm/sfp-machine.h>
#include <math-emu/soft-fp.h>
#include <math-emu/double.h>
#include <math-emu/single.h>
int
fnmsubs(void *frD, void *frA, void *frB, void *frC)
{
FP_DECL_D(R);
FP_DECL_D(A);
FP_DECL_D(B);
FP_DECL_D(C);
FP_DECL_D(T);
FP_DECL_EX;
#ifdef DEBUG
printk("%s: %p %p %p %p\n", __func__, frD, frA, frB, frC);
#endif
FP_UNPACK_DP(A, frA);
FP_UNPACK_DP(B, frB);
FP_UNPACK_DP(C, frC);
#ifdef DEBUG
printk("A: %ld %lu %lu %ld (%ld)\n", A_s, A_f1, A_f0, A_e, A_c);
printk("B: %ld %lu %lu %ld (%ld)\n", B_s, B_f1, B_f0, B_e, B_c);
printk("C: %ld %lu %lu %ld (%ld)\n", C_s, C_f1, C_f0, C_e, C_c);
#endif
if ((A_c == FP_CLS_INF && C_c == FP_CLS_ZERO) ||
(A_c == FP_CLS_ZERO && C_c == FP_CLS_INF))
FP_SET_EXCEPTION(EFLAG_VXIMZ);
FP_MUL_D(T, A, C);
if (B_c != FP_CLS_NAN)
B_s ^= 1;
if (T_s != B_s && T_c == FP_CLS_INF && B_c == FP_CLS_INF)
FP_SET_EXCEPTION(EFLAG_VXISI);
FP_ADD_D(R, T, B);
if (R_c != FP_CLS_NAN)
R_s ^= 1;
#ifdef DEBUG
printk("D: %ld %lu %lu %ld (%ld)\n", R_s, R_f1, R_f0, R_e, R_c);
#endif
__FP_PACK_DS(frD, R);
return FP_CUR_EXCEPTIONS;
}
| gpl-2.0 |
shahan-mik3/android_kernel_xiaomi_cancro | drivers/cpufreq/maple-cpufreq.c | 169 | 8495 | /*
* Copyright (C) 2011 Dmitry Eremin-Solenikov
* Copyright (C) 2002 - 2005 Benjamin Herrenschmidt <benh@kernel.crashing.org>
* and Markus Demleitner <msdemlei@cl.uni-heidelberg.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This driver adds basic cpufreq support for SMU & 970FX based G5 Macs,
* that is iMac G5 and latest single CPU desktop.
*/
#undef DEBUG
#include <linux/module.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/sched.h>
#include <linux/cpufreq.h>
#include <linux/init.h>
#include <linux/completion.h>
#include <linux/mutex.h>
#include <linux/time.h>
#include <linux/of.h>
#define DBG(fmt...) pr_debug(fmt)
/* see 970FX user manual */
#define SCOM_PCR 0x0aa001 /* PCR scom addr */
#define PCR_HILO_SELECT 0x80000000U /* 1 = PCR, 0 = PCRH */
#define PCR_SPEED_FULL 0x00000000U /* 1:1 speed value */
#define PCR_SPEED_HALF 0x00020000U /* 1:2 speed value */
#define PCR_SPEED_QUARTER 0x00040000U /* 1:4 speed value */
#define PCR_SPEED_MASK 0x000e0000U /* speed mask */
#define PCR_SPEED_SHIFT 17
#define PCR_FREQ_REQ_VALID 0x00010000U /* freq request valid */
#define PCR_VOLT_REQ_VALID 0x00008000U /* volt request valid */
#define PCR_TARGET_TIME_MASK 0x00006000U /* target time */
#define PCR_STATLAT_MASK 0x00001f00U /* STATLAT value */
#define PCR_SNOOPLAT_MASK 0x000000f0U /* SNOOPLAT value */
#define PCR_SNOOPACC_MASK 0x0000000fU /* SNOOPACC value */
#define SCOM_PSR 0x408001 /* PSR scom addr */
/* warning: PSR is a 64 bits register */
#define PSR_CMD_RECEIVED 0x2000000000000000U /* command received */
#define PSR_CMD_COMPLETED 0x1000000000000000U /* command completed */
#define PSR_CUR_SPEED_MASK 0x0300000000000000U /* current speed */
#define PSR_CUR_SPEED_SHIFT (56)
/*
* The G5 only supports two frequencies (Quarter speed is not supported)
*/
#define CPUFREQ_HIGH 0
#define CPUFREQ_LOW 1
static struct cpufreq_frequency_table maple_cpu_freqs[] = {
{CPUFREQ_HIGH, 0},
{CPUFREQ_LOW, 0},
{0, CPUFREQ_TABLE_END},
};
static struct freq_attr *maple_cpu_freqs_attr[] = {
&cpufreq_freq_attr_scaling_available_freqs,
NULL,
};
/* Power mode data is an array of the 32 bits PCR values to use for
* the various frequencies, retrieved from the device-tree
*/
static int maple_pmode_cur;
static DEFINE_MUTEX(maple_switch_mutex);
static const u32 *maple_pmode_data;
static int maple_pmode_max;
/*
* SCOM based frequency switching for 970FX rev3
*/
static int maple_scom_switch_freq(int speed_mode)
{
unsigned long flags;
int to;
local_irq_save(flags);
/* Clear PCR high */
scom970_write(SCOM_PCR, 0);
/* Clear PCR low */
scom970_write(SCOM_PCR, PCR_HILO_SELECT | 0);
/* Set PCR low */
scom970_write(SCOM_PCR, PCR_HILO_SELECT |
maple_pmode_data[speed_mode]);
/* Wait for completion */
for (to = 0; to < 10; to++) {
unsigned long psr = scom970_read(SCOM_PSR);
if ((psr & PSR_CMD_RECEIVED) == 0 &&
(((psr >> PSR_CUR_SPEED_SHIFT) ^
(maple_pmode_data[speed_mode] >> PCR_SPEED_SHIFT)) & 0x3)
== 0)
break;
if (psr & PSR_CMD_COMPLETED)
break;
udelay(100);
}
local_irq_restore(flags);
maple_pmode_cur = speed_mode;
ppc_proc_freq = maple_cpu_freqs[speed_mode].frequency * 1000ul;
return 0;
}
static int maple_scom_query_freq(void)
{
unsigned long psr = scom970_read(SCOM_PSR);
int i;
for (i = 0; i <= maple_pmode_max; i++)
if ((((psr >> PSR_CUR_SPEED_SHIFT) ^
(maple_pmode_data[i] >> PCR_SPEED_SHIFT)) & 0x3) == 0)
break;
return i;
}
/*
* Common interface to the cpufreq core
*/
static int maple_cpufreq_verify(struct cpufreq_policy *policy)
{
return cpufreq_frequency_table_verify(policy, maple_cpu_freqs);
}
static int maple_cpufreq_target(struct cpufreq_policy *policy,
unsigned int target_freq, unsigned int relation)
{
unsigned int newstate = 0;
struct cpufreq_freqs freqs;
int rc;
if (cpufreq_frequency_table_target(policy, maple_cpu_freqs,
target_freq, relation, &newstate))
return -EINVAL;
if (maple_pmode_cur == newstate)
return 0;
mutex_lock(&maple_switch_mutex);
freqs.old = maple_cpu_freqs[maple_pmode_cur].frequency;
freqs.new = maple_cpu_freqs[newstate].frequency;
cpufreq_notify_transition(policy, &freqs, CPUFREQ_PRECHANGE);
rc = maple_scom_switch_freq(newstate);
cpufreq_notify_transition(policy, &freqs, CPUFREQ_POSTCHANGE);
mutex_unlock(&maple_switch_mutex);
return rc;
}
static unsigned int maple_cpufreq_get_speed(unsigned int cpu)
{
return maple_cpu_freqs[maple_pmode_cur].frequency;
}
static int maple_cpufreq_cpu_init(struct cpufreq_policy *policy)
{
policy->cpuinfo.transition_latency = 12000;
policy->cur = maple_cpu_freqs[maple_scom_query_freq()].frequency;
/* secondary CPUs are tied to the primary one by the
* cpufreq core if in the secondary policy we tell it that
* it actually must be one policy together with all others. */
cpumask_copy(policy->cpus, cpu_online_mask);
cpufreq_frequency_table_get_attr(maple_cpu_freqs, policy->cpu);
return cpufreq_frequency_table_cpuinfo(policy,
maple_cpu_freqs);
}
static struct cpufreq_driver maple_cpufreq_driver = {
.name = "maple",
.owner = THIS_MODULE,
.flags = CPUFREQ_CONST_LOOPS,
.init = maple_cpufreq_cpu_init,
.verify = maple_cpufreq_verify,
.target = maple_cpufreq_target,
.get = maple_cpufreq_get_speed,
.attr = maple_cpu_freqs_attr,
};
static int __init maple_cpufreq_init(void)
{
struct device_node *cpus;
struct device_node *cpunode;
unsigned int psize;
unsigned long max_freq;
const u32 *valp;
u32 pvr_hi;
int rc = -ENODEV;
/*
* Behave here like powermac driver which checks machine compatibility
* to ease merging of two drivers in future.
*/
if (!of_machine_is_compatible("Momentum,Maple") &&
!of_machine_is_compatible("Momentum,Apache"))
return 0;
cpus = of_find_node_by_path("/cpus");
if (cpus == NULL) {
DBG("No /cpus node !\n");
return -ENODEV;
}
/* Get first CPU node */
for (cpunode = NULL;
(cpunode = of_get_next_child(cpus, cpunode)) != NULL;) {
const u32 *reg = of_get_property(cpunode, "reg", NULL);
if (reg == NULL || (*reg) != 0)
continue;
if (!strcmp(cpunode->type, "cpu"))
break;
}
if (cpunode == NULL) {
printk(KERN_ERR "cpufreq: Can't find any CPU 0 node\n");
goto bail_cpus;
}
/* Check 970FX for now */
/* we actually don't care on which CPU to access PVR */
pvr_hi = PVR_VER(mfspr(SPRN_PVR));
if (pvr_hi != 0x3c && pvr_hi != 0x44) {
printk(KERN_ERR "cpufreq: Unsupported CPU version (%x)\n",
pvr_hi);
goto bail_noprops;
}
/* Look for the powertune data in the device-tree */
/*
* On Maple this property is provided by PIBS in dual-processor config,
* not provided by PIBS in CPU0 config and also not provided by SLOF,
* so YMMV
*/
maple_pmode_data = of_get_property(cpunode, "power-mode-data", &psize);
if (!maple_pmode_data) {
DBG("No power-mode-data !\n");
goto bail_noprops;
}
maple_pmode_max = psize / sizeof(u32) - 1;
/*
* From what I see, clock-frequency is always the maximal frequency.
* The current driver can not slew sysclk yet, so we really only deal
* with powertune steps for now. We also only implement full freq and
* half freq in this version. So far, I haven't yet seen a machine
* supporting anything else.
*/
valp = of_get_property(cpunode, "clock-frequency", NULL);
if (!valp)
return -ENODEV;
max_freq = (*valp)/1000;
maple_cpu_freqs[0].frequency = max_freq;
maple_cpu_freqs[1].frequency = max_freq/2;
/* Force apply current frequency to make sure everything is in
* sync (voltage is right for example). Firmware may leave us with
* a strange setting ...
*/
msleep(10);
maple_pmode_cur = -1;
maple_scom_switch_freq(maple_scom_query_freq());
printk(KERN_INFO "Registering Maple CPU frequency driver\n");
printk(KERN_INFO "Low: %d Mhz, High: %d Mhz, Cur: %d MHz\n",
maple_cpu_freqs[1].frequency/1000,
maple_cpu_freqs[0].frequency/1000,
maple_cpu_freqs[maple_pmode_cur].frequency/1000);
rc = cpufreq_register_driver(&maple_cpufreq_driver);
of_node_put(cpunode);
of_node_put(cpus);
return rc;
bail_noprops:
of_node_put(cpunode);
bail_cpus:
of_node_put(cpus);
return rc;
}
module_init(maple_cpufreq_init);
MODULE_LICENSE("GPL");
| gpl-2.0 |
eldarerathis/android_kernel_msm | drivers/video/msm/mdss/mdp3_ctrl.c | 169 | 30284 | /* Copyright (c) 2013, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#define pr_fmt(fmt) "%s: " fmt, __func__
#include <linux/dma-mapping.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/major.h>
#include <linux/module.h>
#include <linux/uaccess.h>
#include <linux/delay.h>
#include "mdp3_ctrl.h"
#include "mdp3.h"
#include "mdp3_ppp.h"
#define MDP_CORE_CLK_RATE 100000000
#define MDP_VSYNC_CLK_RATE 19200000
static void mdp3_ctrl_pan_display(struct msm_fb_data_type *mfd);
static int mdp3_overlay_unset(struct msm_fb_data_type *mfd, int ndx);
static int mdp3_histogram_stop(struct mdp3_session_data *session,
u32 block);
static void mdp3_bufq_init(struct mdp3_buffer_queue *bufq)
{
bufq->count = 0;
bufq->push_idx = 0;
bufq->pop_idx = 0;
}
static void mdp3_bufq_deinit(struct mdp3_buffer_queue *bufq)
{
int count = bufq->count;
if (!count)
return;
while (count--) {
struct mdp3_img_data *data = &bufq->img_data[bufq->pop_idx];
bufq->pop_idx = (bufq->pop_idx + 1) % MDP3_MAX_BUF_QUEUE;
mdp3_put_img(data);
}
bufq->count = 0;
bufq->push_idx = 0;
bufq->pop_idx = 0;
}
static int mdp3_bufq_push(struct mdp3_buffer_queue *bufq,
struct mdp3_img_data *data)
{
if (bufq->count >= MDP3_MAX_BUF_QUEUE) {
pr_err("bufq full\n");
return -EPERM;
}
bufq->img_data[bufq->push_idx] = *data;
bufq->push_idx = (bufq->push_idx + 1) % MDP3_MAX_BUF_QUEUE;
bufq->count++;
return 0;
}
static struct mdp3_img_data *mdp3_bufq_pop(struct mdp3_buffer_queue *bufq)
{
struct mdp3_img_data *data;
if (bufq->count == 0)
return NULL;
data = &bufq->img_data[bufq->pop_idx];
bufq->count--;
bufq->pop_idx = (bufq->pop_idx + 1) % MDP3_MAX_BUF_QUEUE;
return data;
}
static int mdp3_bufq_count(struct mdp3_buffer_queue *bufq)
{
return bufq->count;
}
void vsync_notify_handler(void *arg)
{
struct mdp3_session_data *session = (struct mdp3_session_data *)arg;
session->vsync_time = ktime_get();
sysfs_notify_dirent(session->vsync_event_sd);
}
static int mdp3_ctrl_vsync_enable(struct msm_fb_data_type *mfd, int enable)
{
struct mdp3_session_data *mdp3_session;
struct mdp3_vsync_notification vsync_client;
struct mdp3_vsync_notification *arg = NULL;
pr_debug("mdp3_ctrl_vsync_enable =%d\n", enable);
mdp3_session = (struct mdp3_session_data *)mfd->mdp.private1;
if (!mdp3_session || !mdp3_session->panel || !mdp3_session->dma ||
!mdp3_session->intf)
return -ENODEV;
if (!mdp3_session->status) {
pr_debug("fb%d is not on yet", mfd->index);
return -EINVAL;
}
if (enable) {
vsync_client.handler = vsync_notify_handler;
vsync_client.arg = mdp3_session;
arg = &vsync_client;
}
mutex_lock(&mdp3_session->lock);
mdp3_session->dma->vsync_enable(mdp3_session->dma, arg);
if (enable && mdp3_session->status == 1 && !mdp3_session->intf->active)
mod_timer(&mdp3_session->vsync_timer,
jiffies + msecs_to_jiffies(mdp3_session->vsync_period));
else if (!enable)
del_timer(&mdp3_session->vsync_timer);
mutex_unlock(&mdp3_session->lock);
return 0;
}
void mdp3_vsync_timer_func(unsigned long arg)
{
struct mdp3_session_data *session = (struct mdp3_session_data *)arg;
if (session->status == 1 && !session->intf->active) {
pr_debug("mdp3_vsync_timer_func trigger\n");
vsync_notify_handler(session);
mod_timer(&session->vsync_timer,
jiffies + msecs_to_jiffies(session->vsync_period));
}
}
static int mdp3_ctrl_async_blit_req(struct msm_fb_data_type *mfd,
void __user *p)
{
struct mdp_async_blit_req_list req_list_header;
int rc, count;
void __user *p_req;
if (copy_from_user(&req_list_header, p, sizeof(req_list_header)))
return -EFAULT;
p_req = p + sizeof(req_list_header);
count = req_list_header.count;
if (count < 0 || count >= MAX_BLIT_REQ)
return -EINVAL;
rc = mdp3_ppp_parse_req(p_req, &req_list_header, 1);
if (!rc)
rc = copy_to_user(p, &req_list_header, sizeof(req_list_header));
return rc;
}
static int mdp3_ctrl_blit_req(struct msm_fb_data_type *mfd, void __user *p)
{
struct mdp_async_blit_req_list req_list_header;
int rc, count;
void __user *p_req;
if (copy_from_user(&(req_list_header.count), p,
sizeof(struct mdp_blit_req_list)))
return -EFAULT;
p_req = p + sizeof(struct mdp_blit_req_list);
count = req_list_header.count;
if (count < 0 || count >= MAX_BLIT_REQ)
return -EINVAL;
req_list_header.sync.acq_fen_fd_cnt = 0;
rc = mdp3_ppp_parse_req(p_req, &req_list_header, 0);
return rc;
}
static ssize_t mdp3_vsync_show_event(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct fb_info *fbi = dev_get_drvdata(dev);
struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)fbi->par;
struct mdp3_session_data *mdp3_session = NULL;
u64 vsync_ticks;
int rc;
if (!mfd || !mfd->mdp.private1)
return -EAGAIN;
mdp3_session = (struct mdp3_session_data *)mfd->mdp.private1;
vsync_ticks = ktime_to_ns(mdp3_session->vsync_time);
pr_debug("fb%d vsync=%llu", mfd->index, vsync_ticks);
rc = scnprintf(buf, PAGE_SIZE, "VSYNC=%llu", vsync_ticks);
return rc;
}
static DEVICE_ATTR(vsync_event, S_IRUGO, mdp3_vsync_show_event, NULL);
static struct attribute *vsync_fs_attrs[] = {
&dev_attr_vsync_event.attr,
NULL,
};
static struct attribute_group vsync_fs_attr_group = {
.attrs = vsync_fs_attrs,
};
static int mdp3_ctrl_res_req_bus(struct msm_fb_data_type *mfd, int status)
{
int rc = 0;
if (status) {
struct mdss_panel_info *panel_info = mfd->panel_info;
int ab = 0;
int ib = 0;
ab = panel_info->xres * panel_info->yres * 4;
ab *= panel_info->mipi.frame_rate;
ib = (ab * 3) / 2;
rc = mdp3_bus_scale_set_quota(MDP3_CLIENT_DMA_P, ab, ib);
} else {
rc = mdp3_bus_scale_set_quota(MDP3_CLIENT_DMA_P, 0, 0);
}
return rc;
}
static int mdp3_ctrl_res_req_clk(struct msm_fb_data_type *mfd, int status)
{
int rc = 0;
if (status) {
mdp3_clk_set_rate(MDP3_CLK_CORE, MDP_CORE_CLK_RATE,
MDP3_CLIENT_DMA_P);
mdp3_clk_set_rate(MDP3_CLK_VSYNC, MDP_VSYNC_CLK_RATE,
MDP3_CLIENT_DMA_P);
rc = mdp3_clk_enable(true);
if (rc)
return rc;
} else {
rc = mdp3_clk_enable(false);
}
return rc;
}
static int mdp3_ctrl_get_intf_type(struct msm_fb_data_type *mfd)
{
int type;
switch (mfd->panel.type) {
case MIPI_VIDEO_PANEL:
type = MDP3_DMA_OUTPUT_SEL_DSI_VIDEO;
break;
case MIPI_CMD_PANEL:
type = MDP3_DMA_OUTPUT_SEL_DSI_CMD;
break;
case LCDC_PANEL:
type = MDP3_DMA_OUTPUT_SEL_LCDC;
break;
default:
type = MDP3_DMA_OUTPUT_SEL_MAX;
}
return type;
}
static int mdp3_ctrl_get_source_format(struct msm_fb_data_type *mfd)
{
int format;
switch (mfd->fb_imgType) {
case MDP_RGB_565:
format = MDP3_DMA_IBUF_FORMAT_RGB565;
break;
case MDP_RGB_888:
format = MDP3_DMA_IBUF_FORMAT_RGB888;
break;
case MDP_ARGB_8888:
case MDP_RGBA_8888:
format = MDP3_DMA_IBUF_FORMAT_XRGB8888;
break;
default:
format = MDP3_DMA_IBUF_FORMAT_UNDEFINED;
}
return format;
}
static int mdp3_ctrl_get_pack_pattern(struct msm_fb_data_type *mfd)
{
int packPattern = MDP3_DMA_OUTPUT_PACK_PATTERN_RGB;
if (mfd->fb_imgType == MDP_RGBA_8888)
packPattern = MDP3_DMA_OUTPUT_PACK_PATTERN_BGR;
return packPattern;
}
static int mdp3_ctrl_intf_init(struct msm_fb_data_type *mfd,
struct mdp3_intf *intf)
{
int rc;
struct mdp3_intf_cfg cfg;
struct mdp3_video_intf_cfg *video = &cfg.video;
struct mdss_panel_info *p = mfd->panel_info;
int h_back_porch = p->lcdc.h_back_porch;
int h_front_porch = p->lcdc.h_front_porch;
int w = p->xres;
int v_back_porch = p->lcdc.v_back_porch;
int v_front_porch = p->lcdc.v_front_porch;
int h = p->yres;
int h_sync_skew = p->lcdc.hsync_skew;
int h_pulse_width = p->lcdc.h_pulse_width;
int v_pulse_width = p->lcdc.v_pulse_width;
int hsync_period = h_front_porch + h_back_porch + w + h_pulse_width;
int vsync_period = v_front_porch + v_back_porch + h + v_pulse_width;
vsync_period *= hsync_period;
cfg.type = mdp3_ctrl_get_intf_type(mfd);
if (cfg.type == MDP3_DMA_OUTPUT_SEL_DSI_VIDEO ||
cfg.type == MDP3_DMA_OUTPUT_SEL_LCDC) {
video->hsync_period = hsync_period;
video->hsync_pulse_width = h_pulse_width;
video->vsync_period = vsync_period;
video->vsync_pulse_width = v_pulse_width * hsync_period;
video->display_start_x = h_back_porch + h_pulse_width;
video->display_end_x = hsync_period - h_front_porch - 1;
video->display_start_y =
(v_back_porch + v_pulse_width) * hsync_period;
video->display_end_y =
vsync_period - v_front_porch * hsync_period - 1;
video->active_start_x = video->display_start_x;
video->active_end_x = video->display_end_x;
video->active_h_enable = true;
video->active_start_y = video->display_start_y;
video->active_end_y = video->display_end_y;
video->active_v_enable = true;
video->hsync_skew = h_sync_skew;
video->hsync_polarity = 1;
video->vsync_polarity = 1;
video->de_polarity = 1;
} else if (cfg.type == MDP3_DMA_OUTPUT_SEL_DSI_CMD) {
cfg.dsi_cmd.primary_dsi_cmd_id = 0;
cfg.dsi_cmd.secondary_dsi_cmd_id = 1;
cfg.dsi_cmd.dsi_cmd_tg_intf_sel = 0;
} else
return -EINVAL;
rc = mdp3_intf_init(intf, &cfg);
return rc;
}
static int mdp3_ctrl_dma_init(struct msm_fb_data_type *mfd,
struct mdp3_dma *dma)
{
int rc;
struct mdss_panel_info *panel_info = mfd->panel_info;
struct fb_info *fbi = mfd->fbi;
struct fb_fix_screeninfo *fix;
struct fb_var_screeninfo *var;
struct mdp3_dma_output_config outputConfig;
struct mdp3_dma_source sourceConfig;
int frame_rate = mfd->panel_info->mipi.frame_rate;
fix = &fbi->fix;
var = &fbi->var;
sourceConfig.format = mdp3_ctrl_get_source_format(mfd);
sourceConfig.width = panel_info->xres;
sourceConfig.height = panel_info->yres;
sourceConfig.x = 0;
sourceConfig.y = 0;
sourceConfig.stride = fix->line_length;
sourceConfig.buf = (void *)mfd->iova;
sourceConfig.vsync_count =
MDP_VSYNC_CLK_RATE / (frame_rate * sourceConfig.width);
outputConfig.dither_en = 0;
outputConfig.out_sel = mdp3_ctrl_get_intf_type(mfd);
outputConfig.bit_mask_polarity = 0;
outputConfig.color_components_flip = 0;
outputConfig.pack_pattern = mdp3_ctrl_get_pack_pattern(mfd);
outputConfig.pack_align = MDP3_DMA_OUTPUT_PACK_ALIGN_LSB;
outputConfig.color_comp_out_bits = (MDP3_DMA_OUTPUT_COMP_BITS_8 << 4) |
(MDP3_DMA_OUTPUT_COMP_BITS_8 << 2)|
MDP3_DMA_OUTPUT_COMP_BITS_8;
rc = mdp3_dma_init(dma, &sourceConfig, &outputConfig);
return rc;
}
static int mdp3_ctrl_on(struct msm_fb_data_type *mfd)
{
int rc = 0;
struct mdp3_session_data *mdp3_session;
struct mdss_panel_data *panel;
pr_debug("mdp3_ctrl_on\n");
mdp3_session = (struct mdp3_session_data *)mfd->mdp.private1;
if (!mdp3_session || !mdp3_session->panel || !mdp3_session->dma ||
!mdp3_session->intf) {
pr_err("mdp3_ctrl_on no device");
return -ENODEV;
}
mutex_lock(&mdp3_session->lock);
if (mdp3_session->status) {
pr_debug("fb%d is on already", mfd->index);
goto on_error;
}
rc = mdp3_iommu_enable(MDP3_CLIENT_DMA_P);
if (rc) {
pr_err("fail to attach MDP DMA SMMU\n");
goto on_error;
}
/* request bus bandwidth before DSI DMA traffic */
rc = mdp3_ctrl_res_req_bus(mfd, 1);
if (rc) {
pr_err("fail to request bus resource\n");
goto on_error;
}
panel = mdp3_session->panel;
if (panel->event_handler) {
rc = panel->event_handler(panel, MDSS_EVENT_UNBLANK, NULL);
rc |= panel->event_handler(panel, MDSS_EVENT_PANEL_ON, NULL);
}
if (rc) {
pr_err("fail to turn on the panel\n");
goto on_error;
}
rc = mdp3_ctrl_res_req_clk(mfd, 1);
if (rc) {
pr_err("fail to request mdp clk resource\n");
goto on_error;
}
mdp3_irq_register();
rc = mdp3_ctrl_dma_init(mfd, mdp3_session->dma);
if (rc) {
pr_err("dma init failed\n");
goto on_error;
}
rc = mdp3_ppp_init();
if (rc) {
pr_err("ppp init failed\n");
goto on_error;
}
rc = mdp3_ctrl_intf_init(mfd, mdp3_session->intf);
if (rc) {
pr_err("display interface init failed\n");
goto on_error;
}
if (panel->set_backlight)
panel->set_backlight(panel, panel->panel_info.bl_max);
pr_debug("mdp3_ctrl_on dma start\n");
if (mfd->fbi->screen_base) {
rc = mdp3_session->dma->start(mdp3_session->dma,
mdp3_session->intf);
if (rc) {
pr_err("fail to start the MDP display interface\n");
goto on_error;
}
}
on_error:
if (!rc)
mdp3_session->status = 1;
mutex_unlock(&mdp3_session->lock);
return rc;
}
static int mdp3_ctrl_off(struct msm_fb_data_type *mfd)
{
int rc = 0;
struct mdp3_session_data *mdp3_session;
struct mdss_panel_data *panel;
pr_debug("mdp3_ctrl_off\n");
mdp3_session = (struct mdp3_session_data *)mfd->mdp.private1;
if (!mdp3_session || !mdp3_session->panel || !mdp3_session->dma ||
!mdp3_session->intf) {
pr_err("mdp3_ctrl_on no device");
return -ENODEV;
}
panel = mdp3_session->panel;
mutex_lock(&mdp3_session->lock);
if (!mdp3_session->status) {
pr_debug("fb%d is off already", mfd->index);
goto off_error;
}
mdp3_histogram_stop(mdp3_session, MDP_BLOCK_DMA_P);
pr_debug("mdp3_ctrl_off turn panel off\n");
if (panel->set_backlight)
panel->set_backlight(panel, 0);
if (panel->event_handler)
rc = panel->event_handler(panel, MDSS_EVENT_PANEL_OFF, NULL);
if (rc)
pr_err("fail to turn off the panel\n");
rc = mdp3_session->dma->stop(mdp3_session->dma, mdp3_session->intf);
if (rc)
pr_err("fail to stop the MDP3 dma\n");
mdp3_irq_deregister();
pr_debug("mdp3_ctrl_off stop clock\n");
rc = mdp3_ctrl_res_req_clk(mfd, 0);
if (rc)
pr_err("mdp clock resource release failed\n");
pr_debug("mdp3_ctrl_off stop dsi controller\n");
if (panel->event_handler)
rc = panel->event_handler(panel, MDSS_EVENT_BLANK, NULL);
if (rc)
pr_err("fail to turn off the panel\n");
pr_debug("mdp3_ctrl_off release bus\n");
rc = mdp3_ctrl_res_req_bus(mfd, 0);
if (rc)
pr_err("mdp bus resource release failed\n");
rc = mdp3_iommu_disable(MDP3_CLIENT_DMA_P);
if (rc)
pr_err("fail to dettach MDP DMA SMMU\n");
off_error:
mdp3_session->status = 0;
mdp3_bufq_deinit(&mdp3_session->bufq_out);
mutex_unlock(&mdp3_session->lock);
if (mdp3_session->overlay.id != MSMFB_NEW_REQUEST)
mdp3_overlay_unset(mfd, mdp3_session->overlay.id);
return 0;
}
static int mdp3_overlay_get(struct msm_fb_data_type *mfd,
struct mdp_overlay *req)
{
int rc = 0;
struct mdp3_session_data *mdp3_session = mfd->mdp.private1;
mutex_lock(&mdp3_session->lock);
if (mdp3_session->overlay.id == req->id)
*req = mdp3_session->overlay;
else
rc = -EINVAL;
mutex_unlock(&mdp3_session->lock);
return rc;
}
static int mdp3_overlay_set(struct msm_fb_data_type *mfd,
struct mdp_overlay *req)
{
int rc = 0;
struct mdp3_session_data *mdp3_session = mfd->mdp.private1;
mutex_lock(&mdp3_session->lock);
if (mdp3_session->overlay.id == req->id) {
mdp3_session->overlay = *req;
if (req->id == MSMFB_NEW_REQUEST) {
mdp3_session->overlay.id = 1;
req->id = 1;
}
} else {
rc = -EINVAL;
}
mutex_unlock(&mdp3_session->lock);
return rc;
}
static int mdp3_overlay_unset(struct msm_fb_data_type *mfd, int ndx)
{
int rc = 0;
struct mdp3_session_data *mdp3_session = mfd->mdp.private1;
mutex_lock(&mdp3_session->lock);
if (mdp3_session->overlay.id == ndx && ndx == 1) {
mdp3_session->overlay.id = MSMFB_NEW_REQUEST;
mdp3_bufq_deinit(&mdp3_session->bufq_in);
} else {
rc = -EINVAL;
}
mutex_unlock(&mdp3_session->lock);
return rc;
}
static int mdp3_overlay_queue_buffer(struct msm_fb_data_type *mfd,
struct msmfb_overlay_data *req)
{
int rc;
struct mdp3_session_data *mdp3_session = mfd->mdp.private1;
struct msmfb_data *img = &req->data;
struct mdp3_img_data data;
rc = mdp3_get_img(img, &data);
if (rc) {
pr_err("fail to get overlay buffer\n");
return rc;
}
rc = mdp3_bufq_push(&mdp3_session->bufq_in, &data);
if (rc) {
pr_err("fail to queue the overlay buffer, buffer drop\n");
mdp3_put_img(&data);
return rc;
}
return 0;
}
static int mdp3_overlay_play(struct msm_fb_data_type *mfd,
struct msmfb_overlay_data *req)
{
struct mdp3_session_data *mdp3_session = mfd->mdp.private1;
int rc = 0;
pr_debug("mdp3_overlay_play req id=%x mem_id=%d\n",
req->id, req->data.memory_id);
mutex_lock(&mdp3_session->lock);
if (mfd->panel_power_on)
rc = mdp3_overlay_queue_buffer(mfd, req);
else
rc = -EPERM;
mutex_unlock(&mdp3_session->lock);
return rc;
}
static int mdp3_ctrl_display_commit_kickoff(struct msm_fb_data_type *mfd)
{
struct mdp3_session_data *mdp3_session;
struct mdp3_img_data *data;
int rc = 0;
if (!mfd || !mfd->mdp.private1)
return -EINVAL;
mdp3_session = mfd->mdp.private1;
if (!mdp3_session || !mdp3_session->dma)
return -EINVAL;
if (!mdp3_session->status) {
pr_err("%s, display off!\n", __func__);
return -EPERM;
}
mutex_lock(&mdp3_session->lock);
data = mdp3_bufq_pop(&mdp3_session->bufq_in);
if (data) {
mdp3_session->dma->update(mdp3_session->dma,
(void *)data->addr,
mdp3_session->intf);
mdp3_bufq_push(&mdp3_session->bufq_out, data);
}
if (mdp3_bufq_count(&mdp3_session->bufq_out) > 2) {
data = mdp3_bufq_pop(&mdp3_session->bufq_out);
mdp3_put_img(data);
if (mfd->fbi->screen_base)
mdp3_fbmem_free(mfd);
}
mutex_unlock(&mdp3_session->lock);
mdss_fb_update_notify_update(mfd);
return rc;
}
static void mdp3_ctrl_pan_display(struct msm_fb_data_type *mfd)
{
struct fb_info *fbi;
struct mdp3_session_data *mdp3_session;
u32 offset;
int bpp;
pr_debug("mdp3_ctrl_pan_display\n");
if (!mfd || !mfd->mdp.private1)
return;
mdp3_session = (struct mdp3_session_data *)mfd->mdp.private1;
if (!mdp3_session || !mdp3_session->dma)
return;
if (!mdp3_session->status) {
pr_err("mdp3_ctrl_pan_display, display off!\n");
return;
}
mutex_lock(&mdp3_session->lock);
fbi = mfd->fbi;
bpp = fbi->var.bits_per_pixel / 8;
offset = fbi->var.xoffset * bpp +
fbi->var.yoffset * fbi->fix.line_length;
if (offset > fbi->fix.smem_len) {
pr_err("invalid fb offset=%u total length=%u\n",
offset, fbi->fix.smem_len);
goto pan_error;
}
if (mfd->fbi->screen_base) {
mdp3_session->dma->update(mdp3_session->dma,
(void *)mfd->iova + offset,
mdp3_session->intf);
} else {
pr_debug("mdp3_ctrl_pan_display no memory, stop interface");
mdp3_session->dma->stop(mdp3_session->dma, mdp3_session->intf);
}
pan_error:
mutex_unlock(&mdp3_session->lock);
}
static int mdp3_get_metadata(struct msm_fb_data_type *mfd,
struct msmfb_metadata *metadata)
{
int ret = 0;
switch (metadata->op) {
case metadata_op_frame_rate:
metadata->data.panel_frame_rate =
mfd->panel_info->mipi.frame_rate;
break;
case metadata_op_get_caps:
metadata->data.caps.mdp_rev = 304;
metadata->data.caps.rgb_pipes = 0;
metadata->data.caps.vig_pipes = 0;
metadata->data.caps.dma_pipes = 1;
break;
default:
pr_warn("Unsupported request to MDP META IOCTL.\n");
ret = -EINVAL;
break;
}
return ret;
}
static int mdp3_histogram_start(struct mdp3_session_data *session,
struct mdp_histogram_start_req *req)
{
int ret;
struct mdp3_dma_histogram_config histo_config;
pr_debug("mdp3_histogram_start\n");
if (req->block != MDP_BLOCK_DMA_P ||
req->num_bins != MDP_HISTOGRAM_BIN_NUM) {
pr_err("mdp3_histogram_start invalid request\n");
return -EINVAL;
}
if (!session->dma->histo_op ||
!session->dma->config_histo) {
pr_err("mdp3_histogram_start not supported\n");
return -EINVAL;
}
mutex_lock(&session->histo_lock);
if (session->histo_status) {
pr_err("mdp3_histogram_start already started\n");
ret = -EBUSY;
goto histogram_start_err;
}
ret = session->dma->histo_op(session->dma, MDP3_DMA_HISTO_OP_RESET);
if (ret) {
pr_err("mdp3_histogram_start reset error\n");
goto histogram_start_err;
}
histo_config.frame_count = req->frame_cnt;
histo_config.bit_mask = req->bit_mask;
histo_config.auto_clear_en = 1;
histo_config.bit_mask_polarity = 0;
ret = session->dma->config_histo(session->dma, &histo_config);
if (ret) {
pr_err("mdp3_histogram_start config error\n");
goto histogram_start_err;
}
ret = session->dma->histo_op(session->dma, MDP3_DMA_HISTO_OP_START);
if (ret) {
pr_err("mdp3_histogram_start config error\n");
goto histogram_start_err;
}
session->histo_status = 1;
histogram_start_err:
mutex_unlock(&session->histo_lock);
return ret;
}
static int mdp3_histogram_stop(struct mdp3_session_data *session,
u32 block)
{
int ret;
pr_debug("mdp3_histogram_stop\n");
if (!session->dma->histo_op || block != MDP_BLOCK_DMA_P) {
pr_err("mdp3_histogram_stop not supported\n");
return -EINVAL;
}
mutex_lock(&session->histo_lock);
if (!session->histo_status) {
ret = 0;
goto histogram_stop_err;
}
ret = session->dma->histo_op(session->dma, MDP3_DMA_HISTO_OP_CANCEL);
if (ret)
pr_err("mdp3_histogram_stop error\n");
session->histo_status = 0;
histogram_stop_err:
mutex_unlock(&session->histo_lock);
return ret;
}
static int mdp3_histogram_collect(struct mdp3_session_data *session,
struct mdp_histogram_data *hist)
{
int ret;
struct mdp3_dma_histogram_data *mdp3_histo;
if (!session->dma->get_histo) {
pr_err("mdp3_histogram_collect not supported\n");
return -EINVAL;
}
mutex_lock(&session->histo_lock);
if (!session->histo_status) {
pr_err("mdp3_histogram_collect not started\n");
mutex_unlock(&session->histo_lock);
return -EPERM;
}
mutex_unlock(&session->histo_lock);
ret = session->dma->get_histo(session->dma);
if (ret) {
pr_err("mdp3_histogram_collect error = %d\n", ret);
return ret;
}
mdp3_histo = &session->dma->histo_data;
ret = copy_to_user(hist->c0, mdp3_histo->r_data,
sizeof(uint32_t) * MDP_HISTOGRAM_BIN_NUM);
if (ret)
return ret;
ret = copy_to_user(hist->c1, mdp3_histo->g_data,
sizeof(uint32_t) * MDP_HISTOGRAM_BIN_NUM);
if (ret)
return ret;
ret = copy_to_user(hist->c2, mdp3_histo->b_data,
sizeof(uint32_t) * MDP_HISTOGRAM_BIN_NUM);
if (ret)
return ret;
ret = copy_to_user(hist->extra_info, mdp3_histo->extra,
sizeof(uint32_t) * 2);
if (ret)
return ret;
hist->bin_cnt = MDP_HISTOGRAM_BIN_NUM;
hist->block = MDP_BLOCK_DMA_P;
return ret;
}
static int mdp3_bl_scale_config(struct msm_fb_data_type *mfd,
struct mdp_bl_scale_data *data)
{
int ret = 0;
int curr_bl;
mutex_lock(&mfd->bl_lock);
curr_bl = mfd->bl_level;
mfd->bl_scale = data->scale;
mfd->bl_min_lvl = data->min_lvl;
pr_debug("update scale = %d, min_lvl = %d\n", mfd->bl_scale,
mfd->bl_min_lvl);
/* update current backlight to use new scaling*/
mdss_fb_set_backlight(mfd, curr_bl);
mutex_unlock(&mfd->bl_lock);
return ret;
}
static int mdp3_pp_ioctl(struct msm_fb_data_type *mfd,
void __user *argp)
{
int ret = -EINVAL;
struct msmfb_mdp_pp mdp_pp;
ret = copy_from_user(&mdp_pp, argp, sizeof(mdp_pp));
if (ret)
return ret;
switch (mdp_pp.op) {
case mdp_bl_scale_cfg:
ret = mdp3_bl_scale_config(mfd, (struct mdp_bl_scale_data *)
&mdp_pp.data.bl_scale_data);
break;
default:
pr_err("Unsupported request to MDP_PP IOCTL.\n");
ret = -EINVAL;
break;
}
if (!ret)
ret = copy_to_user(argp, &mdp_pp, sizeof(struct msmfb_mdp_pp));
return ret;
}
static int mdp3_histo_ioctl(struct msm_fb_data_type *mfd, u32 cmd,
void __user *argp)
{
int ret = -ENOSYS;
struct mdp_histogram_data hist;
struct mdp_histogram_start_req hist_req;
u32 block;
struct mdp3_session_data *mdp3_session;
if (!mfd || !mfd->mdp.private1)
return -EINVAL;
mdp3_session = mfd->mdp.private1;
switch (cmd) {
case MSMFB_HISTOGRAM_START:
ret = copy_from_user(&hist_req, argp, sizeof(hist_req));
if (ret)
return ret;
ret = mdp3_histogram_start(mdp3_session, &hist_req);
break;
case MSMFB_HISTOGRAM_STOP:
ret = copy_from_user(&block, argp, sizeof(int));
if (ret)
return ret;
ret = mdp3_histogram_stop(mdp3_session, block);
break;
case MSMFB_HISTOGRAM:
ret = copy_from_user(&hist, argp, sizeof(hist));
if (ret)
return ret;
ret = mdp3_histogram_collect(mdp3_session, &hist);
if (!ret)
ret = copy_to_user(argp, &hist, sizeof(hist));
break;
default:
break;
}
return ret;
}
static int mdp3_ctrl_lut_update(struct msm_fb_data_type *mfd,
struct fb_cmap *cmap)
{
int rc = 0;
struct mdp3_session_data *mdp3_session = mfd->mdp.private1;
struct mdp3_dma_lut_config lut_config;
struct mdp3_dma_lut lut;
static u16 r[MDP_LUT_SIZE];
static u16 g[MDP_LUT_SIZE];
static u16 b[MDP_LUT_SIZE];
if (!mdp3_session->dma->config_lut)
return -EINVAL;
if (cmap->start + cmap->len > MDP_LUT_SIZE) {
pr_err("mdp3_ctrl_lut_update invalid arguments\n");
return -EINVAL;
}
rc = copy_from_user(r + cmap->start,
cmap->red, sizeof(u16)*cmap->len);
rc |= copy_from_user(g + cmap->start,
cmap->green, sizeof(u16)*cmap->len);
rc |= copy_from_user(b + cmap->start,
cmap->blue, sizeof(u16)*cmap->len);
if (rc)
return rc;
lut_config.lut_enable = 7;
lut_config.lut_sel = mdp3_session->lut_sel;
lut_config.lut_position = 0;
lut.color0_lut = r;
lut.color1_lut = g;
lut.color2_lut = b;
mutex_lock(&mdp3_session->lock);
if (!mdp3_session->status) {
pr_err("%s, display off!\n", __func__);
mutex_unlock(&mdp3_session->lock);
return -EPERM;
}
rc = mdp3_session->dma->config_lut(mdp3_session->dma, &lut_config,
&lut);
if (rc)
pr_err("mdp3_ctrl_lut_update failed\n");
mdp3_session->lut_sel = (mdp3_session->lut_sel + 1) % 2;
mutex_unlock(&mdp3_session->lock);
return rc;
}
static int mdp3_ctrl_ioctl_handler(struct msm_fb_data_type *mfd,
u32 cmd, void __user *argp)
{
int rc = -EINVAL;
struct mdp3_session_data *mdp3_session;
struct msmfb_metadata metadata;
struct mdp_overlay req;
struct msmfb_overlay_data ov_data;
int val;
mdp3_session = (struct mdp3_session_data *)mfd->mdp.private1;
if (!mdp3_session)
return -ENODEV;
if (!mdp3_session->status) {
pr_err("mdp3_ctrl_ioctl_handler, display off!\n");
return -EPERM;
}
switch (cmd) {
case MSMFB_MDP_PP:
rc = mdp3_pp_ioctl(mfd, argp);
break;
case MSMFB_HISTOGRAM_START:
case MSMFB_HISTOGRAM_STOP:
case MSMFB_HISTOGRAM:
rc = mdp3_histo_ioctl(mfd, cmd, argp);
break;
case MSMFB_VSYNC_CTRL:
case MSMFB_OVERLAY_VSYNC_CTRL:
if (!copy_from_user(&val, argp, sizeof(val))) {
rc = mdp3_ctrl_vsync_enable(mfd, val);
} else {
pr_err("MSMFB_OVERLAY_VSYNC_CTRL failed\n");
rc = -EFAULT;
}
break;
case MSMFB_ASYNC_BLIT:
rc = mdp3_ctrl_async_blit_req(mfd, argp);
break;
case MSMFB_BLIT:
rc = mdp3_ctrl_blit_req(mfd, argp);
break;
case MSMFB_METADATA_GET:
rc = copy_from_user(&metadata, argp, sizeof(metadata));
if (rc)
return rc;
rc = mdp3_get_metadata(mfd, &metadata);
if (!rc)
rc = copy_to_user(argp, &metadata, sizeof(metadata));
break;
case MSMFB_OVERLAY_GET:
rc = copy_from_user(&req, argp, sizeof(req));
if (!rc) {
rc = mdp3_overlay_get(mfd, &req);
if (!IS_ERR_VALUE(rc))
rc = copy_to_user(argp, &req, sizeof(req));
}
if (rc)
pr_err("OVERLAY_GET failed (%d)\n", rc);
break;
case MSMFB_OVERLAY_SET:
rc = copy_from_user(&req, argp, sizeof(req));
if (!rc) {
rc = mdp3_overlay_set(mfd, &req);
if (!IS_ERR_VALUE(rc))
rc = copy_to_user(argp, &req, sizeof(req));
}
if (rc)
pr_err("OVERLAY_SET failed (%d)\n", rc);
break;
case MSMFB_OVERLAY_UNSET:
if (!IS_ERR_VALUE(copy_from_user(&val, argp, sizeof(val))))
rc = mdp3_overlay_unset(mfd, val);
break;
case MSMFB_OVERLAY_PLAY:
rc = copy_from_user(&ov_data, argp, sizeof(ov_data));
if (!rc)
rc = mdp3_overlay_play(mfd, &ov_data);
if (rc)
pr_err("OVERLAY_PLAY failed (%d)\n", rc);
break;
default:
break;
}
return rc;
}
int mdp3_ctrl_init(struct msm_fb_data_type *mfd)
{
struct device *dev = mfd->fbi->dev;
struct msm_mdp_interface *mdp3_interface = &mfd->mdp;
struct mdp3_session_data *mdp3_session = NULL;
u32 intf_type = MDP3_DMA_OUTPUT_SEL_DSI_VIDEO;
int rc;
pr_debug("mdp3_ctrl_init\n");
mdp3_interface->on_fnc = mdp3_ctrl_on;
mdp3_interface->off_fnc = mdp3_ctrl_off;
mdp3_interface->do_histogram = NULL;
mdp3_interface->cursor_update = NULL;
mdp3_interface->dma_fnc = mdp3_ctrl_pan_display;
mdp3_interface->ioctl_handler = mdp3_ctrl_ioctl_handler;
mdp3_interface->kickoff_fnc = mdp3_ctrl_display_commit_kickoff;
mdp3_interface->lut_update = mdp3_ctrl_lut_update;
mdp3_session = kmalloc(sizeof(struct mdp3_session_data), GFP_KERNEL);
if (!mdp3_session) {
pr_err("fail to allocate mdp3 private data structure");
return -ENOMEM;
}
memset(mdp3_session, 0, sizeof(struct mdp3_session_data));
mutex_init(&mdp3_session->lock);
mutex_init(&mdp3_session->histo_lock);
mdp3_session->dma = mdp3_get_dma_pipe(MDP3_DMA_CAP_ALL);
if (!mdp3_session->dma) {
rc = -ENODEV;
goto init_done;
}
intf_type = mdp3_ctrl_get_intf_type(mfd);
mdp3_session->intf = mdp3_get_display_intf(intf_type);
if (!mdp3_session->intf) {
rc = -ENODEV;
goto init_done;
}
mdp3_session->mfd = mfd;
mdp3_session->panel = dev_get_platdata(&mfd->pdev->dev);
mdp3_session->status = 0;
mdp3_session->overlay.id = MSMFB_NEW_REQUEST;
mdp3_bufq_init(&mdp3_session->bufq_in);
mdp3_bufq_init(&mdp3_session->bufq_out);
mdp3_session->histo_status = 0;
mdp3_session->lut_sel = 0;
init_timer(&mdp3_session->vsync_timer);
mdp3_session->vsync_timer.function = mdp3_vsync_timer_func;
mdp3_session->vsync_timer.data = (u32)mdp3_session;
mdp3_session->vsync_period = 1000 / mfd->panel_info->mipi.frame_rate;
mfd->mdp.private1 = mdp3_session;
rc = sysfs_create_group(&dev->kobj, &vsync_fs_attr_group);
if (rc) {
pr_err("vsync sysfs group creation failed, ret=%d\n", rc);
goto init_done;
}
mdp3_session->vsync_event_sd = sysfs_get_dirent(dev->kobj.sd, NULL,
"vsync_event");
if (!mdp3_session->vsync_event_sd) {
pr_err("vsync_event sysfs lookup failed\n");
rc = -ENODEV;
goto init_done;
}
kobject_uevent(&dev->kobj, KOBJ_ADD);
pr_debug("vsync kobject_uevent(KOBJ_ADD)\n");
init_done:
if (IS_ERR_VALUE(rc))
kfree(mdp3_session);
return rc;
}
| gpl-2.0 |
davidmueller13/L900_3.8_Experiment | drivers/iio/frequency/adf4350.c | 169 | 11781 | /*
* ADF4350/ADF4351 SPI Wideband Synthesizer driver
*
* Copyright 2012 Analog Devices Inc.
*
* Licensed under the GPL-2.
*/
#include <linux/device.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/sysfs.h>
#include <linux/spi/spi.h>
#include <linux/regulator/consumer.h>
#include <linux/err.h>
#include <linux/module.h>
#include <linux/gcd.h>
#include <linux/gpio.h>
#include <asm/div64.h>
#include <linux/iio/iio.h>
#include <linux/iio/sysfs.h>
#include <linux/iio/frequency/adf4350.h>
enum {
ADF4350_FREQ,
ADF4350_FREQ_REFIN,
ADF4350_FREQ_RESOLUTION,
ADF4350_PWRDOWN,
};
struct adf4350_state {
struct spi_device *spi;
struct regulator *reg;
struct adf4350_platform_data *pdata;
unsigned long clkin;
unsigned long chspc; /* Channel Spacing */
unsigned long fpfd; /* Phase Frequency Detector */
unsigned long min_out_freq;
unsigned r0_fract;
unsigned r0_int;
unsigned r1_mod;
unsigned r4_rf_div_sel;
unsigned long regs[6];
unsigned long regs_hw[6];
/*
* DMA (thus cache coherency maintenance) requires the
* transfer buffers to live in their own cache lines.
*/
__be32 val ____cacheline_aligned;
};
static struct adf4350_platform_data default_pdata = {
.clkin = 122880000,
.channel_spacing = 10000,
.r2_user_settings = ADF4350_REG2_PD_POLARITY_POS |
ADF4350_REG2_CHARGE_PUMP_CURR_uA(2500),
.r3_user_settings = ADF4350_REG3_12BIT_CLKDIV_MODE(0),
.r4_user_settings = ADF4350_REG4_OUTPUT_PWR(3) |
ADF4350_REG4_MUTE_TILL_LOCK_EN,
.gpio_lock_detect = -1,
};
static int adf4350_sync_config(struct adf4350_state *st)
{
int ret, i, doublebuf = 0;
for (i = ADF4350_REG5; i >= ADF4350_REG0; i--) {
if ((st->regs_hw[i] != st->regs[i]) ||
((i == ADF4350_REG0) && doublebuf)) {
switch (i) {
case ADF4350_REG1:
case ADF4350_REG4:
doublebuf = 1;
break;
}
st->val = cpu_to_be32(st->regs[i] | i);
ret = spi_write(st->spi, &st->val, 4);
if (ret < 0)
return ret;
st->regs_hw[i] = st->regs[i];
dev_dbg(&st->spi->dev, "[%d] 0x%X\n",
i, (u32)st->regs[i] | i);
}
}
return 0;
}
static int adf4350_reg_access(struct iio_dev *indio_dev,
unsigned reg, unsigned writeval,
unsigned *readval)
{
struct adf4350_state *st = iio_priv(indio_dev);
int ret;
if (reg > ADF4350_REG5)
return -EINVAL;
mutex_lock(&indio_dev->mlock);
if (readval == NULL) {
st->regs[reg] = writeval & ~(BIT(0) | BIT(1) | BIT(2));
ret = adf4350_sync_config(st);
} else {
*readval = st->regs_hw[reg];
ret = 0;
}
mutex_unlock(&indio_dev->mlock);
return ret;
}
static int adf4350_tune_r_cnt(struct adf4350_state *st, unsigned short r_cnt)
{
struct adf4350_platform_data *pdata = st->pdata;
do {
r_cnt++;
st->fpfd = (st->clkin * (pdata->ref_doubler_en ? 2 : 1)) /
(r_cnt * (pdata->ref_div2_en ? 2 : 1));
} while (st->fpfd > ADF4350_MAX_FREQ_PFD);
return r_cnt;
}
static int adf4350_set_freq(struct adf4350_state *st, unsigned long long freq)
{
struct adf4350_platform_data *pdata = st->pdata;
u64 tmp;
u32 div_gcd, prescaler, chspc;
u16 mdiv, r_cnt = 0;
u8 band_sel_div;
if (freq > ADF4350_MAX_OUT_FREQ || freq < st->min_out_freq)
return -EINVAL;
if (freq > ADF4350_MAX_FREQ_45_PRESC) {
prescaler = ADF4350_REG1_PRESCALER;
mdiv = 75;
} else {
prescaler = 0;
mdiv = 23;
}
st->r4_rf_div_sel = 0;
while (freq < ADF4350_MIN_VCO_FREQ) {
freq <<= 1;
st->r4_rf_div_sel++;
}
/*
* Allow a predefined reference division factor
* if not set, compute our own
*/
if (pdata->ref_div_factor)
r_cnt = pdata->ref_div_factor - 1;
chspc = st->chspc;
do {
do {
do {
r_cnt = adf4350_tune_r_cnt(st, r_cnt);
st->r1_mod = st->fpfd / chspc;
if (r_cnt > ADF4350_MAX_R_CNT) {
/* try higher spacing values */
chspc++;
r_cnt = 0;
}
} while ((st->r1_mod > ADF4350_MAX_MODULUS) && r_cnt);
} while (r_cnt == 0);
tmp = freq * (u64)st->r1_mod + (st->fpfd >> 1);
do_div(tmp, st->fpfd); /* Div round closest (n + d/2)/d */
st->r0_fract = do_div(tmp, st->r1_mod);
st->r0_int = tmp;
} while (mdiv > st->r0_int);
band_sel_div = DIV_ROUND_UP(st->fpfd, ADF4350_MAX_BANDSEL_CLK);
if (st->r0_fract && st->r1_mod) {
div_gcd = gcd(st->r1_mod, st->r0_fract);
st->r1_mod /= div_gcd;
st->r0_fract /= div_gcd;
} else {
st->r0_fract = 0;
st->r1_mod = 1;
}
dev_dbg(&st->spi->dev, "VCO: %llu Hz, PFD %lu Hz\n"
"REF_DIV %d, R0_INT %d, R0_FRACT %d\n"
"R1_MOD %d, RF_DIV %d\nPRESCALER %s, BAND_SEL_DIV %d\n",
freq, st->fpfd, r_cnt, st->r0_int, st->r0_fract, st->r1_mod,
1 << st->r4_rf_div_sel, prescaler ? "8/9" : "4/5",
band_sel_div);
st->regs[ADF4350_REG0] = ADF4350_REG0_INT(st->r0_int) |
ADF4350_REG0_FRACT(st->r0_fract);
st->regs[ADF4350_REG1] = ADF4350_REG1_PHASE(1) |
ADF4350_REG1_MOD(st->r1_mod) |
prescaler;
st->regs[ADF4350_REG2] =
ADF4350_REG2_10BIT_R_CNT(r_cnt) |
ADF4350_REG2_DOUBLE_BUFF_EN |
(pdata->ref_doubler_en ? ADF4350_REG2_RMULT2_EN : 0) |
(pdata->ref_div2_en ? ADF4350_REG2_RDIV2_EN : 0) |
(pdata->r2_user_settings & (ADF4350_REG2_PD_POLARITY_POS |
ADF4350_REG2_LDP_6ns | ADF4350_REG2_LDF_INT_N |
ADF4350_REG2_CHARGE_PUMP_CURR_uA(5000) |
ADF4350_REG2_MUXOUT(0x7) | ADF4350_REG2_NOISE_MODE(0x9)));
st->regs[ADF4350_REG3] = pdata->r3_user_settings &
(ADF4350_REG3_12BIT_CLKDIV(0xFFF) |
ADF4350_REG3_12BIT_CLKDIV_MODE(0x3) |
ADF4350_REG3_12BIT_CSR_EN |
ADF4351_REG3_CHARGE_CANCELLATION_EN |
ADF4351_REG3_ANTI_BACKLASH_3ns_EN |
ADF4351_REG3_BAND_SEL_CLOCK_MODE_HIGH);
st->regs[ADF4350_REG4] =
ADF4350_REG4_FEEDBACK_FUND |
ADF4350_REG4_RF_DIV_SEL(st->r4_rf_div_sel) |
ADF4350_REG4_8BIT_BAND_SEL_CLKDIV(band_sel_div) |
ADF4350_REG4_RF_OUT_EN |
(pdata->r4_user_settings &
(ADF4350_REG4_OUTPUT_PWR(0x3) |
ADF4350_REG4_AUX_OUTPUT_PWR(0x3) |
ADF4350_REG4_AUX_OUTPUT_EN |
ADF4350_REG4_AUX_OUTPUT_FUND |
ADF4350_REG4_MUTE_TILL_LOCK_EN));
st->regs[ADF4350_REG5] = ADF4350_REG5_LD_PIN_MODE_DIGITAL;
return adf4350_sync_config(st);
}
static ssize_t adf4350_write(struct iio_dev *indio_dev,
uintptr_t private,
const struct iio_chan_spec *chan,
const char *buf, size_t len)
{
struct adf4350_state *st = iio_priv(indio_dev);
unsigned long long readin;
int ret;
ret = kstrtoull(buf, 10, &readin);
if (ret)
return ret;
mutex_lock(&indio_dev->mlock);
switch ((u32)private) {
case ADF4350_FREQ:
ret = adf4350_set_freq(st, readin);
break;
case ADF4350_FREQ_REFIN:
if (readin > ADF4350_MAX_FREQ_REFIN)
ret = -EINVAL;
else
st->clkin = readin;
break;
case ADF4350_FREQ_RESOLUTION:
if (readin == 0)
ret = -EINVAL;
else
st->chspc = readin;
break;
case ADF4350_PWRDOWN:
if (readin)
st->regs[ADF4350_REG2] |= ADF4350_REG2_POWER_DOWN_EN;
else
st->regs[ADF4350_REG2] &= ~ADF4350_REG2_POWER_DOWN_EN;
adf4350_sync_config(st);
break;
default:
ret = -EINVAL;
}
mutex_unlock(&indio_dev->mlock);
return ret ? ret : len;
}
static ssize_t adf4350_read(struct iio_dev *indio_dev,
uintptr_t private,
const struct iio_chan_spec *chan,
char *buf)
{
struct adf4350_state *st = iio_priv(indio_dev);
unsigned long long val;
int ret = 0;
mutex_lock(&indio_dev->mlock);
switch ((u32)private) {
case ADF4350_FREQ:
val = (u64)((st->r0_int * st->r1_mod) + st->r0_fract) *
(u64)st->fpfd;
do_div(val, st->r1_mod * (1 << st->r4_rf_div_sel));
/* PLL unlocked? return error */
if (gpio_is_valid(st->pdata->gpio_lock_detect))
if (!gpio_get_value(st->pdata->gpio_lock_detect)) {
dev_dbg(&st->spi->dev, "PLL un-locked\n");
ret = -EBUSY;
}
break;
case ADF4350_FREQ_REFIN:
val = st->clkin;
break;
case ADF4350_FREQ_RESOLUTION:
val = st->chspc;
break;
case ADF4350_PWRDOWN:
val = !!(st->regs[ADF4350_REG2] & ADF4350_REG2_POWER_DOWN_EN);
break;
default:
ret = -EINVAL;
}
mutex_unlock(&indio_dev->mlock);
return ret < 0 ? ret : sprintf(buf, "%llu\n", val);
}
#define _ADF4350_EXT_INFO(_name, _ident) { \
.name = _name, \
.read = adf4350_read, \
.write = adf4350_write, \
.private = _ident, \
}
static const struct iio_chan_spec_ext_info adf4350_ext_info[] = {
/* Ideally we use IIO_CHAN_INFO_FREQUENCY, but there are
* values > 2^32 in order to support the entire frequency range
* in Hz. Using scale is a bit ugly.
*/
_ADF4350_EXT_INFO("frequency", ADF4350_FREQ),
_ADF4350_EXT_INFO("frequency_resolution", ADF4350_FREQ_RESOLUTION),
_ADF4350_EXT_INFO("refin_frequency", ADF4350_FREQ_REFIN),
_ADF4350_EXT_INFO("powerdown", ADF4350_PWRDOWN),
{ },
};
static const struct iio_chan_spec adf4350_chan = {
.type = IIO_ALTVOLTAGE,
.indexed = 1,
.output = 1,
.ext_info = adf4350_ext_info,
};
static const struct iio_info adf4350_info = {
.debugfs_reg_access = &adf4350_reg_access,
.driver_module = THIS_MODULE,
};
static int adf4350_probe(struct spi_device *spi)
{
struct adf4350_platform_data *pdata = spi->dev.platform_data;
struct iio_dev *indio_dev;
struct adf4350_state *st;
int ret;
if (!pdata) {
dev_warn(&spi->dev, "no platform data? using default\n");
pdata = &default_pdata;
}
indio_dev = iio_device_alloc(sizeof(*st));
if (indio_dev == NULL)
return -ENOMEM;
st = iio_priv(indio_dev);
st->reg = regulator_get(&spi->dev, "vcc");
if (!IS_ERR(st->reg)) {
ret = regulator_enable(st->reg);
if (ret)
goto error_put_reg;
}
spi_set_drvdata(spi, indio_dev);
st->spi = spi;
st->pdata = pdata;
indio_dev->dev.parent = &spi->dev;
indio_dev->name = (pdata->name[0] != 0) ? pdata->name :
spi_get_device_id(spi)->name;
indio_dev->info = &adf4350_info;
indio_dev->modes = INDIO_DIRECT_MODE;
indio_dev->channels = &adf4350_chan;
indio_dev->num_channels = 1;
st->chspc = pdata->channel_spacing;
st->clkin = pdata->clkin;
st->min_out_freq = spi_get_device_id(spi)->driver_data == 4351 ?
ADF4351_MIN_OUT_FREQ : ADF4350_MIN_OUT_FREQ;
memset(st->regs_hw, 0xFF, sizeof(st->regs_hw));
if (gpio_is_valid(pdata->gpio_lock_detect)) {
ret = gpio_request(pdata->gpio_lock_detect, indio_dev->name);
if (ret) {
dev_err(&spi->dev, "fail to request lock detect GPIO-%d",
pdata->gpio_lock_detect);
goto error_disable_reg;
}
gpio_direction_input(pdata->gpio_lock_detect);
}
if (pdata->power_up_frequency) {
ret = adf4350_set_freq(st, pdata->power_up_frequency);
if (ret)
goto error_free_gpio;
}
ret = iio_device_register(indio_dev);
if (ret)
goto error_free_gpio;
return 0;
error_free_gpio:
if (gpio_is_valid(pdata->gpio_lock_detect))
gpio_free(pdata->gpio_lock_detect);
error_disable_reg:
if (!IS_ERR(st->reg))
regulator_disable(st->reg);
error_put_reg:
if (!IS_ERR(st->reg))
regulator_put(st->reg);
iio_device_free(indio_dev);
return ret;
}
static int adf4350_remove(struct spi_device *spi)
{
struct iio_dev *indio_dev = spi_get_drvdata(spi);
struct adf4350_state *st = iio_priv(indio_dev);
struct regulator *reg = st->reg;
st->regs[ADF4350_REG2] |= ADF4350_REG2_POWER_DOWN_EN;
adf4350_sync_config(st);
iio_device_unregister(indio_dev);
if (!IS_ERR(reg)) {
regulator_disable(reg);
regulator_put(reg);
}
if (gpio_is_valid(st->pdata->gpio_lock_detect))
gpio_free(st->pdata->gpio_lock_detect);
iio_device_free(indio_dev);
return 0;
}
static const struct spi_device_id adf4350_id[] = {
{"adf4350", 4350},
{"adf4351", 4351},
{}
};
static struct spi_driver adf4350_driver = {
.driver = {
.name = "adf4350",
.owner = THIS_MODULE,
},
.probe = adf4350_probe,
.remove = adf4350_remove,
.id_table = adf4350_id,
};
module_spi_driver(adf4350_driver);
MODULE_AUTHOR("Michael Hennerich <hennerich@blackfin.uclinux.org>");
MODULE_DESCRIPTION("Analog Devices ADF4350/ADF4351 PLL");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
vcgato29/cygwin | opcodes/m10300-opc.c | 169 | 103399 | /* Assemble Matsushita MN10300 instructions.
Copyright 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2007
Free Software Foundation, Inc.
This file is part of the GNU opcodes library.
This library 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 3, or (at your option)
any later version.
It is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
MA 02110-1301, USA. */
/* This file is formatted at > 80 columns. Attempting to read it
on a screeen with less than 80 columns will be difficult. */
#include "sysdep.h"
#include "opcode/mn10300.h"
const struct mn10300_operand mn10300_operands[] = {
#define UNUSED 0
{0, 0, 0},
/* dn register in the first register operand position. */
#define DN0 (UNUSED+1)
{2, 0, MN10300_OPERAND_DREG},
/* dn register in the second register operand position. */
#define DN1 (DN0+1)
{2, 2, MN10300_OPERAND_DREG},
/* dn register in the third register operand position. */
#define DN2 (DN1+1)
{2, 4, MN10300_OPERAND_DREG},
/* dm register in the first register operand position. */
#define DM0 (DN2+1)
{2, 0, MN10300_OPERAND_DREG},
/* dm register in the second register operand position. */
#define DM1 (DM0+1)
{2, 2, MN10300_OPERAND_DREG},
/* dm register in the third register operand position. */
#define DM2 (DM1+1)
{2, 4, MN10300_OPERAND_DREG},
/* an register in the first register operand position. */
#define AN0 (DM2+1)
{2, 0, MN10300_OPERAND_AREG},
/* an register in the second register operand position. */
#define AN1 (AN0+1)
{2, 2, MN10300_OPERAND_AREG},
/* an register in the third register operand position. */
#define AN2 (AN1+1)
{2, 4, MN10300_OPERAND_AREG},
/* am register in the first register operand position. */
#define AM0 (AN2+1)
{2, 0, MN10300_OPERAND_AREG},
/* am register in the second register operand position. */
#define AM1 (AM0+1)
{2, 2, MN10300_OPERAND_AREG},
/* am register in the third register operand position. */
#define AM2 (AM1+1)
{2, 4, MN10300_OPERAND_AREG},
/* 8 bit unsigned immediate which may promote to a 16bit
unsigned immediate. */
#define IMM8 (AM2+1)
{8, 0, MN10300_OPERAND_PROMOTE},
/* 16 bit unsigned immediate which may promote to a 32bit
unsigned immediate. */
#define IMM16 (IMM8+1)
{16, 0, MN10300_OPERAND_PROMOTE},
/* 16 bit pc-relative immediate which may promote to a 16bit
pc-relative immediate. */
#define IMM16_PCREL (IMM16+1)
{16, 0, MN10300_OPERAND_PCREL | MN10300_OPERAND_RELAX | MN10300_OPERAND_SIGNED},
/* 16bit unsigned displacement in a memory operation which
may promote to a 32bit displacement. */
#define IMM16_MEM (IMM16_PCREL+1)
{16, 0, MN10300_OPERAND_PROMOTE | MN10300_OPERAND_MEMADDR},
/* 32bit immediate, high 16 bits in the main instruction
word, 16bits in the extension word.
The "bits" field indicates how many bits are in the
main instruction word for MN10300_OPERAND_SPLIT! */
#define IMM32 (IMM16_MEM+1)
{16, 0, MN10300_OPERAND_SPLIT},
/* 32bit pc-relative offset. */
#define IMM32_PCREL (IMM32+1)
{16, 0, MN10300_OPERAND_SPLIT | MN10300_OPERAND_PCREL},
/* 32bit memory offset. */
#define IMM32_MEM (IMM32_PCREL+1)
{16, 0, MN10300_OPERAND_SPLIT | MN10300_OPERAND_MEMADDR},
/* 32bit immediate, high 16 bits in the main instruction
word, 16bits in the extension word, low 16bits are left
shifted 8 places.
The "bits" field indicates how many bits are in the
main instruction word for MN10300_OPERAND_SPLIT! */
#define IMM32_LOWSHIFT8 (IMM32_MEM+1)
{16, 8, MN10300_OPERAND_SPLIT | MN10300_OPERAND_MEMADDR},
/* 32bit immediate, high 24 bits in the main instruction
word, 8 in the extension word.
The "bits" field indicates how many bits are in the
main instruction word for MN10300_OPERAND_SPLIT! */
#define IMM32_HIGH24 (IMM32_LOWSHIFT8+1)
{24, 0, MN10300_OPERAND_SPLIT | MN10300_OPERAND_PCREL},
/* 32bit immediate, high 24 bits in the main instruction
word, 8 in the extension word, low 8 bits are left
shifted 16 places.
The "bits" field indicates how many bits are in the
main instruction word for MN10300_OPERAND_SPLIT! */
#define IMM32_HIGH24_LOWSHIFT16 (IMM32_HIGH24+1)
{24, 16, MN10300_OPERAND_SPLIT | MN10300_OPERAND_PCREL},
/* Stack pointer. */
#define SP (IMM32_HIGH24_LOWSHIFT16+1)
{8, 0, MN10300_OPERAND_SP},
/* Processor status word. */
#define PSW (SP+1)
{0, 0, MN10300_OPERAND_PSW},
/* MDR register. */
#define MDR (PSW+1)
{0, 0, MN10300_OPERAND_MDR},
/* Index register. */
#define DI (MDR+1)
{2, 2, MN10300_OPERAND_DREG},
/* 8 bit signed displacement, may promote to 16bit signed displacement. */
#define SD8 (DI+1)
{8, 0, MN10300_OPERAND_SIGNED | MN10300_OPERAND_PROMOTE},
/* 16 bit signed displacement, may promote to 32bit displacement. */
#define SD16 (SD8+1)
{16, 0, MN10300_OPERAND_SIGNED | MN10300_OPERAND_PROMOTE},
/* 8 bit signed displacement that can not promote. */
#define SD8N (SD16+1)
{8, 0, MN10300_OPERAND_SIGNED},
/* 8 bit pc-relative displacement. */
#define SD8N_PCREL (SD8N+1)
{8, 0, MN10300_OPERAND_SIGNED | MN10300_OPERAND_PCREL | MN10300_OPERAND_RELAX},
/* 8 bit signed displacement shifted left 8 bits in the instruction. */
#define SD8N_SHIFT8 (SD8N_PCREL+1)
{8, 8, MN10300_OPERAND_SIGNED},
/* 8 bit signed immediate which may promote to 16bit signed immediate. */
#define SIMM8 (SD8N_SHIFT8+1)
{8, 0, MN10300_OPERAND_SIGNED | MN10300_OPERAND_PROMOTE},
/* 16 bit signed immediate which may promote to 32bit immediate. */
#define SIMM16 (SIMM8+1)
{16, 0, MN10300_OPERAND_SIGNED | MN10300_OPERAND_PROMOTE},
/* Either an open paren or close paren. */
#define PAREN (SIMM16+1)
{0, 0, MN10300_OPERAND_PAREN},
/* dn register that appears in the first and second register positions. */
#define DN01 (PAREN+1)
{2, 0, MN10300_OPERAND_DREG | MN10300_OPERAND_REPEATED},
/* an register that appears in the first and second register positions. */
#define AN01 (DN01+1)
{2, 0, MN10300_OPERAND_AREG | MN10300_OPERAND_REPEATED},
/* 16bit pc-relative displacement which may promote to 32bit pc-relative
displacement. */
#define D16_SHIFT (AN01+1)
{16, 8, MN10300_OPERAND_PCREL | MN10300_OPERAND_RELAX | MN10300_OPERAND_SIGNED},
/* 8 bit immediate found in the extension word. */
#define IMM8E (D16_SHIFT+1)
{8, 0, MN10300_OPERAND_EXTENDED},
/* Register list found in the extension word shifted 8 bits left. */
#define REGSE_SHIFT8 (IMM8E+1)
{8, 8, MN10300_OPERAND_EXTENDED | MN10300_OPERAND_REG_LIST},
/* Register list shifted 8 bits left. */
#define REGS_SHIFT8 (REGSE_SHIFT8 + 1)
{8, 8, MN10300_OPERAND_REG_LIST},
/* Reigster list. */
#define REGS (REGS_SHIFT8+1)
{8, 0, MN10300_OPERAND_REG_LIST},
/* UStack pointer. */
#define USP (REGS+1)
{0, 0, MN10300_OPERAND_USP},
/* SStack pointer. */
#define SSP (USP+1)
{0, 0, MN10300_OPERAND_SSP},
/* MStack pointer. */
#define MSP (SSP+1)
{0, 0, MN10300_OPERAND_MSP},
/* PC . */
#define PC (MSP+1)
{0, 0, MN10300_OPERAND_PC},
/* 4 bit immediate for syscall. */
#define IMM4 (PC+1)
{4, 0, 0},
/* Processor status word. */
#define EPSW (IMM4+1)
{0, 0, MN10300_OPERAND_EPSW},
/* rn register in the first register operand position. */
#define RN0 (EPSW+1)
{4, 0, MN10300_OPERAND_RREG},
/* rn register in the fourth register operand position. */
#define RN2 (RN0+1)
{4, 4, MN10300_OPERAND_RREG},
/* rm register in the first register operand position. */
#define RM0 (RN2+1)
{4, 0, MN10300_OPERAND_RREG},
/* rm register in the second register operand position. */
#define RM1 (RM0+1)
{4, 2, MN10300_OPERAND_RREG},
/* rm register in the third register operand position. */
#define RM2 (RM1+1)
{4, 4, MN10300_OPERAND_RREG},
#define RN02 (RM2+1)
{4, 0, MN10300_OPERAND_RREG | MN10300_OPERAND_REPEATED},
#define XRN0 (RN02+1)
{4, 0, MN10300_OPERAND_XRREG},
#define XRM2 (XRN0+1)
{4, 4, MN10300_OPERAND_XRREG},
/* + for autoincrement */
#define PLUS (XRM2+1)
{0, 0, MN10300_OPERAND_PLUS},
#define XRN02 (PLUS+1)
{4, 0, MN10300_OPERAND_XRREG | MN10300_OPERAND_REPEATED},
/* Ick */
#define RD0 (XRN02+1)
{4, -8, MN10300_OPERAND_RREG},
#define RD2 (RD0+1)
{4, -4, MN10300_OPERAND_RREG},
/* 8 unsigned displacement in a memory operation which
may promote to a 32bit displacement. */
#define IMM8_MEM (RD2+1)
{8, 0, MN10300_OPERAND_PROMOTE | MN10300_OPERAND_MEMADDR},
/* Index register. */
#define RI (IMM8_MEM+1)
{4, 4, MN10300_OPERAND_RREG},
/* 24 bit signed displacement, may promote to 32bit displacement. */
#define SD24 (RI+1)
{8, 0, MN10300_OPERAND_24BIT | MN10300_OPERAND_SIGNED | MN10300_OPERAND_PROMOTE},
/* 24 bit unsigned immediate which may promote to a 32bit
unsigned immediate. */
#define IMM24 (SD24+1)
{8, 0, MN10300_OPERAND_24BIT | MN10300_OPERAND_PROMOTE},
/* 24 bit signed immediate which may promote to a 32bit
signed immediate. */
#define SIMM24 (IMM24+1)
{8, 0, MN10300_OPERAND_24BIT | MN10300_OPERAND_PROMOTE | MN10300_OPERAND_SIGNED},
/* 24bit unsigned displacement in a memory operation which
may promote to a 32bit displacement. */
#define IMM24_MEM (SIMM24+1)
{8, 0, MN10300_OPERAND_24BIT | MN10300_OPERAND_PROMOTE | MN10300_OPERAND_MEMADDR},
/* 32bit immediate, high 8 bits in the main instruction
word, 24 in the extension word.
The "bits" field indicates how many bits are in the
main instruction word for MN10300_OPERAND_SPLIT! */
#define IMM32_HIGH8 (IMM24_MEM+1)
{8, 0, MN10300_OPERAND_SPLIT},
/* Similarly, but a memory address. */
#define IMM32_HIGH8_MEM (IMM32_HIGH8+1)
{8, 0, MN10300_OPERAND_SPLIT | MN10300_OPERAND_MEMADDR},
/* rm register in the seventh register operand position. */
#define RM6 (IMM32_HIGH8_MEM+1)
{4, 12, MN10300_OPERAND_RREG},
/* rm register in the fifth register operand position. */
#define RN4 (RM6+1)
{4, 8, MN10300_OPERAND_RREG},
/* 4 bit immediate for dsp instructions. */
#define IMM4_2 (RN4+1)
{4, 4, 0},
/* 4 bit immediate for dsp instructions. */
#define SIMM4_2 (IMM4_2+1)
{4, 4, MN10300_OPERAND_SIGNED},
/* 4 bit immediate for dsp instructions. */
#define SIMM4_6 (SIMM4_2+1)
{4, 12, MN10300_OPERAND_SIGNED},
#define FPCR (SIMM4_6+1)
{0, 0, MN10300_OPERAND_FPCR},
/* We call f[sd]m registers those whose most significant bit is stored
* within the opcode half-word, i.e., in a bit on the left of the 4
* least significant bits, and f[sd]n registers those whose most
* significant bit is stored at the end of the full word, after the 4
* least significant bits. They're not numbered after their position
* in the mnemonic asm instruction, but after their position in the
* opcode word, i.e., depending on the amount of shift they need.
*
* The additional bit is shifted as follows: for `n' registers, it
* will be shifted by (|shift|/4); for `m' registers, it will be
* shifted by (8+(8&shift)+(shift&4)/4); for accumulator, whose
* specifications are only 3-bits long, the two least-significant bits
* are shifted by 16, and the most-significant bit is shifted by -2
* (i.e., it's stored in the least significant bit of the full
* word). */
/* fsm register in the first register operand position. */
#define FSM0 (FPCR+1)
{5, 0, MN10300_OPERAND_FSREG },
/* fsm register in the second register operand position. */
#define FSM1 (FSM0+1)
{5, 4, MN10300_OPERAND_FSREG },
/* fsm register in the third register operand position. */
#define FSM2 (FSM1+1)
{5, 8, MN10300_OPERAND_FSREG },
/* fsm register in the fourth register operand position. */
#define FSM3 (FSM2+1)
{5, 12, MN10300_OPERAND_FSREG },
/* fsn register in the first register operand position. */
#define FSN1 (FSM3+1)
{5, -4, MN10300_OPERAND_FSREG },
/* fsn register in the second register operand position. */
#define FSN2 (FSN1+1)
{5, -8, MN10300_OPERAND_FSREG },
/* fsm register in the third register operand position. */
#define FSN3 (FSN2+1)
{5, -12, MN10300_OPERAND_FSREG },
/* fsm accumulator, in the fourth register operand position. */
#define FSACC (FSN3+1)
{3, -16, MN10300_OPERAND_FSREG },
/* fdm register in the first register operand position. */
#define FDM0 (FSACC+1)
{5, 0, MN10300_OPERAND_FDREG },
/* fdm register in the second register operand position. */
#define FDM1 (FDM0+1)
{5, 4, MN10300_OPERAND_FDREG },
/* fdm register in the third register operand position. */
#define FDM2 (FDM1+1)
{5, 8, MN10300_OPERAND_FDREG },
/* fdm register in the fourth register operand position. */
#define FDM3 (FDM2+1)
{5, 12, MN10300_OPERAND_FDREG },
/* fdn register in the first register operand position. */
#define FDN1 (FDM3+1)
{5, -4, MN10300_OPERAND_FDREG },
/* fdn register in the second register operand position. */
#define FDN2 (FDN1+1)
{5, -8, MN10300_OPERAND_FDREG },
/* fdn register in the third register operand position. */
#define FDN3 (FDN2+1)
{5, -12, MN10300_OPERAND_FDREG },
} ;
#define MEM(ADDR) PAREN, ADDR, PAREN
#define MEMINC(ADDR) PAREN, ADDR, PLUS, PAREN
#define MEMINC2(ADDR,INC) PAREN, ADDR, PLUS, INC, PAREN
#define MEM2(ADDR1,ADDR2) PAREN, ADDR1, ADDR2, PAREN
/* The opcode table.
The format of the opcode table is:
NAME OPCODE MASK MATCH_MASK, FORMAT, PROCESSOR { OPERANDS }
NAME is the name of the instruction.
OPCODE is the instruction opcode.
MASK is the opcode mask; this is used to tell the disassembler
which bits in the actual opcode must match OPCODE.
OPERANDS is the list of operands.
The disassembler reads the table in order and prints the first
instruction which matches, so this table is sorted to put more
specific instructions before more general instructions. It is also
sorted by major opcode. */
const struct mn10300_opcode mn10300_opcodes[] = {
{ "mov", 0x8000, 0xf000, 0, FMT_S1, 0, {SIMM8, DN01}},
{ "mov", 0x80, 0xf0, 0x3, FMT_S0, 0, {DM1, DN0}},
{ "mov", 0xf1e0, 0xfff0, 0, FMT_D0, 0, {DM1, AN0}},
{ "mov", 0xf1d0, 0xfff0, 0, FMT_D0, 0, {AM1, DN0}},
{ "mov", 0x9000, 0xf000, 0, FMT_S1, 0, {IMM8, AN01}},
{ "mov", 0x90, 0xf0, 0x3, FMT_S0, 0, {AM1, AN0}},
{ "mov", 0x3c, 0xfc, 0, FMT_S0, 0, {SP, AN0}},
{ "mov", 0xf2f0, 0xfff3, 0, FMT_D0, 0, {AM1, SP}},
{ "mov", 0xf2e4, 0xfffc, 0, FMT_D0, 0, {PSW, DN0}},
{ "mov", 0xf2f3, 0xfff3, 0, FMT_D0, 0, {DM1, PSW}},
{ "mov", 0xf2e0, 0xfffc, 0, FMT_D0, 0, {MDR, DN0}},
{ "mov", 0xf2f2, 0xfff3, 0, FMT_D0, 0, {DM1, MDR}},
{ "mov", 0x70, 0xf0, 0, FMT_S0, 0, {MEM(AM0), DN1}},
{ "mov", 0x5800, 0xfcff, 0, FMT_S1, 0, {MEM(SP), DN0}},
{ "mov", 0x300000, 0xfc0000, 0, FMT_S2, 0, {MEM(IMM16_MEM), DN0}},
{ "mov", 0xf000, 0xfff0, 0, FMT_D0, 0, {MEM(AM0), AN1}},
{ "mov", 0x5c00, 0xfcff, 0, FMT_S1, 0, {MEM(SP), AN0}},
{ "mov", 0xfaa00000, 0xfffc0000, 0, FMT_D2, 0, {MEM(IMM16_MEM), AN0}},
{ "mov", 0x60, 0xf0, 0, FMT_S0, 0, {DM1, MEM(AN0)}},
{ "mov", 0x4200, 0xf3ff, 0, FMT_S1, 0, {DM1, MEM(SP)}},
{ "mov", 0x010000, 0xf30000, 0, FMT_S2, 0, {DM1, MEM(IMM16_MEM)}},
{ "mov", 0xf010, 0xfff0, 0, FMT_D0, 0, {AM1, MEM(AN0)}},
{ "mov", 0x4300, 0xf3ff, 0, FMT_S1, 0, {AM1, MEM(SP)}},
{ "mov", 0xfa800000, 0xfff30000, 0, FMT_D2, 0, {AM1, MEM(IMM16_MEM)}},
{ "mov", 0x5c00, 0xfc00, 0, FMT_S1, 0, {MEM2(IMM8, SP), AN0}},
{ "mov", 0xf80000, 0xfff000, 0, FMT_D1, 0, {MEM2(SD8, AM0), DN1}},
{ "mov", 0xfa000000, 0xfff00000, 0, FMT_D2, 0, {MEM2(SD16, AM0), DN1}},
{ "mov", 0x5800, 0xfc00, 0, FMT_S1, 0, {MEM2(IMM8, SP), DN0}},
{ "mov", 0xfab40000, 0xfffc0000, 0, FMT_D2, 0, {MEM2(IMM16, SP), DN0}},
{ "mov", 0xf300, 0xffc0, 0, FMT_D0, 0, {MEM2(DI, AM0), DN2}},
{ "mov", 0xf82000, 0xfff000, 0, FMT_D1, 0, {MEM2(SD8,AM0), AN1}},
{ "mov", 0xfa200000, 0xfff00000, 0, FMT_D2, 0, {MEM2(SD16, AM0), AN1}},
{ "mov", 0xfab00000, 0xfffc0000, 0, FMT_D2, 0, {MEM2(IMM16, SP), AN0}},
{ "mov", 0xf380, 0xffc0, 0, FMT_D0, 0, {MEM2(DI, AM0), AN2}},
{ "mov", 0x4300, 0xf300, 0, FMT_S1, 0, {AM1, MEM2(IMM8, SP)}},
{ "mov", 0xf81000, 0xfff000, 0, FMT_D1, 0, {DM1, MEM2(SD8, AN0)}},
{ "mov", 0xfa100000, 0xfff00000, 0, FMT_D2, 0, {DM1, MEM2(SD16, AN0)}},
{ "mov", 0x4200, 0xf300, 0, FMT_S1, 0, {DM1, MEM2(IMM8, SP)}},
{ "mov", 0xfa910000, 0xfff30000, 0, FMT_D2, 0, {DM1, MEM2(IMM16, SP)}},
{ "mov", 0xf340, 0xffc0, 0, FMT_D0, 0, {DM2, MEM2(DI, AN0)}},
{ "mov", 0xf83000, 0xfff000, 0, FMT_D1, 0, {AM1, MEM2(SD8, AN0)}},
{ "mov", 0xfa300000, 0xfff00000, 0, FMT_D2, 0, {AM1, MEM2(SD16, AN0)}},
{ "mov", 0xfa900000, 0xfff30000, 0, FMT_D2, 0, {AM1, MEM2(IMM16, SP)}},
{ "mov", 0xf3c0, 0xffc0, 0, FMT_D0, 0, {AM2, MEM2(DI, AN0)}},
{ "mov", 0xf020, 0xfffc, 0, FMT_D0, AM33, {USP, AN0}},
{ "mov", 0xf024, 0xfffc, 0, FMT_D0, AM33, {SSP, AN0}},
{ "mov", 0xf028, 0xfffc, 0, FMT_D0, AM33, {MSP, AN0}},
{ "mov", 0xf02c, 0xfffc, 0, FMT_D0, AM33, {PC, AN0}},
{ "mov", 0xf030, 0xfff3, 0, FMT_D0, AM33, {AN1, USP}},
{ "mov", 0xf031, 0xfff3, 0, FMT_D0, AM33, {AN1, SSP}},
{ "mov", 0xf032, 0xfff3, 0, FMT_D0, AM33, {AN1, MSP}},
{ "mov", 0xf2ec, 0xfffc, 0, FMT_D0, AM33, {EPSW, DN0}},
{ "mov", 0xf2f1, 0xfff3, 0, FMT_D0, AM33, {DM1, EPSW}},
{ "mov", 0xf500, 0xffc0, 0, FMT_D0, AM33, {AM2, RN0}},
{ "mov", 0xf540, 0xffc0, 0, FMT_D0, AM33, {DM2, RN0}},
{ "mov", 0xf580, 0xffc0, 0, FMT_D0, AM33, {RM1, AN0}},
{ "mov", 0xf5c0, 0xffc0, 0, FMT_D0, AM33, {RM1, DN0}},
{ "mov", 0xf90800, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
{ "mov", 0xf9e800, 0xffff00, 0, FMT_D6, AM33, {XRM2, RN0}},
{ "mov", 0xf9f800, 0xffff00, 0, FMT_D6, AM33, {RM2, XRN0}},
{ "mov", 0xf90a00, 0xffff00, 0, FMT_D6, AM33, {MEM(RM0), RN2}},
{ "mov", 0xf98a00, 0xffff0f, 0, FMT_D6, AM33, {MEM(SP), RN2}},
{ "mov", 0xf96a00, 0xffff00, 0x12, FMT_D6, AM33, {MEMINC(RM0), RN2}},
{ "mov", 0xfb0e0000, 0xffff0f00, 0, FMT_D7, AM33, {MEM(IMM8_MEM), RN2}},
{ "mov", 0xfd0e0000, 0xffff0f00, 0, FMT_D8, AM33, {MEM(IMM24_MEM), RN2}},
{ "mov", 0xf91a00, 0xffff00, 0, FMT_D6, AM33, {RM2, MEM(RN0)}},
{ "mov", 0xf99a00, 0xffff0f, 0, FMT_D6, AM33, {RM2, MEM(SP)}},
{ "mov", 0xf97a00, 0xffff00, 0, FMT_D6, AM33, {RM2, MEMINC(RN0)}},
{ "mov", 0xfb1e0000, 0xffff0f00, 0, FMT_D7, AM33, {RM2, MEM(IMM8_MEM)}},
{ "mov", 0xfd1e0000, 0xffff0f00, 0, FMT_D8, AM33, {RM2, MEM(IMM24_MEM)}},
{ "mov", 0xfb0a0000, 0xffff0000, 0, FMT_D7, AM33, {MEM2(SD8, RM0), RN2}},
{ "mov", 0xfd0a0000, 0xffff0000, 0, FMT_D8, AM33, {MEM2(SD24, RM0), RN2}},
{ "mov", 0xfb8e0000, 0xffff000f, 0, FMT_D7, AM33, {MEM2(RI, RM0), RD2}},
{ "mov", 0xfb1a0000, 0xffff0000, 0, FMT_D7, AM33, {RM2, MEM2(SD8, RN0)}},
{ "mov", 0xfd1a0000, 0xffff0000, 0, FMT_D8, AM33, {RM2, MEM2(SD24, RN0)}},
{ "mov", 0xfb8a0000, 0xffff0f00, 0, FMT_D7, AM33, {MEM2(IMM8, SP), RN2}},
{ "mov", 0xfd8a0000, 0xffff0f00, 0, FMT_D8, AM33, {MEM2(IMM24, SP), RN2}},
{ "mov", 0xfb9a0000, 0xffff0f00, 0, FMT_D7, AM33, {RM2, MEM2(IMM8, SP)}},
{ "mov", 0xfd9a0000, 0xffff0f00, 0, FMT_D8, AM33, {RM2, MEM2(IMM24, SP)}},
{ "mov", 0xfb9e0000, 0xffff000f, 0, FMT_D7, AM33, {RD2, MEM2(RI, RN0)}},
{ "mov", 0xfb6a0000, 0xffff0000, 0x22, FMT_D7, AM33, {MEMINC2 (RM0, SIMM8), RN2}},
{ "mov", 0xfb7a0000, 0xffff0000, 0, FMT_D7, AM33, {RM2, MEMINC2 (RN0, SIMM8)}},
{ "mov", 0xfd6a0000, 0xffff0000, 0x22, FMT_D8, AM33, {MEMINC2 (RM0, IMM24), RN2}},
{ "mov", 0xfd7a0000, 0xffff0000, 0, FMT_D8, AM33, {RM2, MEMINC2 (RN0, IMM24)}},
{ "mov", 0xfe6a0000, 0xffff0000, 0x22, FMT_D9, AM33, {MEMINC2 (RM0, IMM32_HIGH8), RN2}},
{ "mov", 0xfe7a0000, 0xffff0000, 0, FMT_D9, AM33, {RN2, MEMINC2 (RM0, IMM32_HIGH8)}},
/* These must come after most of the other move instructions to avoid matching
a symbolic name with IMMxx operands. Ugh. */
{ "mov", 0x2c0000, 0xfc0000, 0, FMT_S2, 0, {SIMM16, DN0}},
{ "mov", 0xfccc0000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "mov", 0x240000, 0xfc0000, 0, FMT_S2, 0, {IMM16, AN0}},
{ "mov", 0xfcdc0000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, AN0}},
{ "mov", 0xfca40000, 0xfffc0000, 0, FMT_D4, 0, {MEM(IMM32_MEM), DN0}},
{ "mov", 0xfca00000, 0xfffc0000, 0, FMT_D4, 0, {MEM(IMM32_MEM), AN0}},
{ "mov", 0xfc810000, 0xfff30000, 0, FMT_D4, 0, {DM1, MEM(IMM32_MEM)}},
{ "mov", 0xfc800000, 0xfff30000, 0, FMT_D4, 0, {AM1, MEM(IMM32_MEM)}},
{ "mov", 0xfc000000, 0xfff00000, 0, FMT_D4, 0, {MEM2(IMM32,AM0), DN1}},
{ "mov", 0xfcb40000, 0xfffc0000, 0, FMT_D4, 0, {MEM2(IMM32, SP), DN0}},
{ "mov", 0xfc200000, 0xfff00000, 0, FMT_D4, 0, {MEM2(IMM32,AM0), AN1}},
{ "mov", 0xfcb00000, 0xfffc0000, 0, FMT_D4, 0, {MEM2(IMM32, SP), AN0}},
{ "mov", 0xfc100000, 0xfff00000, 0, FMT_D4, 0, {DM1, MEM2(IMM32,AN0)}},
{ "mov", 0xfc910000, 0xfff30000, 0, FMT_D4, 0, {DM1, MEM2(IMM32, SP)}},
{ "mov", 0xfc300000, 0xfff00000, 0, FMT_D4, 0, {AM1, MEM2(IMM32,AN0)}},
{ "mov", 0xfc900000, 0xfff30000, 0, FMT_D4, 0, {AM1, MEM2(IMM32, SP)}},
/* These non-promoting variants need to come after all the other memory
moves. */
{ "mov", 0xf8f000, 0xfffc00, 0, FMT_D1, AM30, {MEM2(SD8N, AM0), SP}},
{ "mov", 0xf8f400, 0xfffc00, 0, FMT_D1, AM30, {SP, MEM2(SD8N, AN0)}},
/* These are the same as the previous non-promoting versions. The am33
does not have restrictions on the offsets used to load/store the stack
pointer. */
{ "mov", 0xf8f000, 0xfffc00, 0, FMT_D1, AM33, {MEM2(SD8, AM0), SP}},
{ "mov", 0xf8f400, 0xfffc00, 0, FMT_D1, AM33, {SP, MEM2(SD8, AN0)}},
/* These must come last so that we favor shorter move instructions for
loading immediates into d0-d3/a0-a3. */
{ "mov", 0xfb080000, 0xffff0000, 0, FMT_D7, AM33, {SIMM8, RN02}},
{ "mov", 0xfd080000, 0xffff0000, 0, FMT_D8, AM33, {SIMM24, RN02}},
{ "mov", 0xfe080000, 0xffff0000, 0, FMT_D9, AM33, {IMM32_HIGH8, RN02}},
{ "mov", 0xfbf80000, 0xffff0000, 0, FMT_D7, AM33, {IMM8, XRN02}},
{ "mov", 0xfdf80000, 0xffff0000, 0, FMT_D8, AM33, {IMM24, XRN02}},
{ "mov", 0xfef80000, 0xffff0000, 0, FMT_D9, AM33, {IMM32_HIGH8, XRN02}},
{ "mov", 0xfe0e0000, 0xffff0f00, 0, FMT_D9, AM33, {MEM(IMM32_HIGH8_MEM), RN2}},
{ "mov", 0xfe1e0000, 0xffff0f00, 0, FMT_D9, AM33, {RM2, MEM(IMM32_HIGH8_MEM)}},
{ "mov", 0xfe0a0000, 0xffff0000, 0, FMT_D9, AM33, {MEM2(IMM32_HIGH8,RM0), RN2}},
{ "mov", 0xfe1a0000, 0xffff0000, 0, FMT_D9, AM33, {RM2, MEM2(IMM32_HIGH8, RN0)}},
{ "mov", 0xfe8a0000, 0xffff0f00, 0, FMT_D9, AM33, {MEM2(IMM32_HIGH8, SP), RN2}},
{ "mov", 0xfe9a0000, 0xffff0f00, 0, FMT_D9, AM33, {RM2, MEM2(IMM32_HIGH8, SP)}},
{ "movu", 0xfb180000, 0xffff0000, 0, FMT_D7, AM33, {IMM8, RN02}},
{ "movu", 0xfd180000, 0xffff0000, 0, FMT_D8, AM33, {IMM24, RN02}},
{ "movu", 0xfe180000, 0xffff0000, 0, FMT_D9, AM33, {IMM32_HIGH8, RN02}},
{ "mcst9", 0xf630, 0xfff0, 0, FMT_D0, AM33, {DN01}},
{ "mcst48", 0xf660, 0xfff0, 0, FMT_D0, AM33, {DN01}},
{ "swap", 0xf680, 0xfff0, 0, FMT_D0, AM33, {DM1, DN0}},
{ "swap", 0xf9cb00, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
{ "swaph", 0xf690, 0xfff0, 0, FMT_D0, AM33, {DM1, DN0}},
{ "swaph", 0xf9db00, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
{ "getchx", 0xf6c0, 0xfff0, 0, FMT_D0, AM33, {DN01}},
{ "getclx", 0xf6d0, 0xfff0, 0, FMT_D0, AM33, {DN01}},
{ "mac", 0xfb0f0000, 0xffff0000, 0xc, FMT_D7, AM33, {RM2, RN0, RD2, RD0}},
{ "mac", 0xf90b00, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
{ "mac", 0xfb0b0000, 0xffff0000, 0, FMT_D7, AM33, {SIMM8, RN02}},
{ "mac", 0xfd0b0000, 0xffff0000, 0, FMT_D8, AM33, {SIMM24, RN02}},
{ "mac", 0xfe0b0000, 0xffff0000, 0, FMT_D9, AM33, {IMM32_HIGH8, RN02}},
{ "macu", 0xfb1f0000, 0xffff0000, 0xc, FMT_D7, AM33, {RM2, RN0, RD2, RD0}},
{ "macu", 0xf91b00, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
{ "macu", 0xfb1b0000, 0xffff0000, 0, FMT_D7, AM33, {IMM8, RN02}},
{ "macu", 0xfd1b0000, 0xffff0000, 0, FMT_D8, AM33, {IMM24, RN02}},
{ "macu", 0xfe1b0000, 0xffff0000, 0, FMT_D9, AM33, {IMM32_HIGH8, RN02}},
{ "macb", 0xfb2f0000, 0xffff000f, 0, FMT_D7, AM33, {RM2, RN0, RD2}},
{ "macb", 0xf92b00, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
{ "macb", 0xfb2b0000, 0xffff0000, 0, FMT_D7, AM33, {SIMM8, RN02}},
{ "macb", 0xfd2b0000, 0xffff0000, 0, FMT_D8, AM33, {SIMM24, RN02}},
{ "macb", 0xfe2b0000, 0xffff0000, 0, FMT_D9, AM33, {IMM32_HIGH8, RN02}},
{ "macbu", 0xfb3f0000, 0xffff000f, 0, FMT_D7, AM33, {RM2, RN0, RD2}},
{ "macbu", 0xf93b00, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
{ "macbu", 0xfb3b0000, 0xffff0000, 0, FMT_D7, AM33, {IMM8, RN02}},
{ "macbu", 0xfd3b0000, 0xffff0000, 0, FMT_D8, AM33, {IMM24, RN02}},
{ "macbu", 0xfe3b0000, 0xffff0000, 0, FMT_D9, AM33, {IMM32_HIGH8, RN02}},
{ "mach", 0xfb4f0000, 0xffff0000, 0xc, FMT_D7, AM33, {RM2, RN0, RD2, RD0}},
{ "mach", 0xf94b00, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
{ "mach", 0xfb4b0000, 0xffff0000, 0, FMT_D7, AM33, {SIMM8, RN02}},
{ "mach", 0xfd4b0000, 0xffff0000, 0, FMT_D8, AM33, {SIMM24, RN02}},
{ "mach", 0xfe4b0000, 0xffff0000, 0, FMT_D9, AM33, {IMM32_HIGH8, RN02}},
{ "machu", 0xfb5f0000, 0xffff0000, 0xc, FMT_D7, AM33, {RM2, RN0, RD2, RD0}},
{ "machu", 0xf95b00, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
{ "machu", 0xfb5b0000, 0xffff0000, 0, FMT_D7, AM33, {IMM8, RN02}},
{ "machu", 0xfd5b0000, 0xffff0000, 0, FMT_D8, AM33, {IMM24, RN02}},
{ "machu", 0xfe5b0000, 0xffff0000, 0, FMT_D9, AM33, {IMM32_HIGH8, RN02}},
{ "dmach", 0xfb6f0000, 0xffff000f, 0, FMT_D7, AM33, {RM2, RN0, RD2}},
{ "dmach", 0xf96b00, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
{ "dmach", 0xfe6b0000, 0xffff0000, 0, FMT_D9, AM33, {IMM32_HIGH8, RN02}},
{ "dmachu", 0xfb7f0000, 0xffff000f, 0, FMT_D7, AM33, {RM2, RN0, RD2}},
{ "dmachu", 0xf97b00, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
{ "dmachu", 0xfe7b0000, 0xffff0000, 0, FMT_D9, AM33, {IMM32_HIGH8, RN02}},
{ "dmulh", 0xfb8f0000, 0xffff0000, 0xc, FMT_D7, AM33, {RM2, RN0, RD2, RD0}},
{ "dmulh", 0xf98b00, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
{ "dmulh", 0xfe8b0000, 0xffff0000, 0, FMT_D9, AM33, {IMM32_HIGH8, RN02}},
{ "dmulhu", 0xfb9f0000, 0xffff0000, 0xc, FMT_D7, AM33, {RM2, RN0, RD2, RD0}},
{ "dmulhu", 0xf99b00, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
{ "dmulhu", 0xfe9b0000, 0xffff0000, 0, FMT_D9, AM33, {IMM32_HIGH8, RN02}},
{ "mcste", 0xf9bb00, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
{ "mcste", 0xfbbb0000, 0xffff0000, 0, FMT_D7, AM33, {IMM8, RN02}},
{ "swhw", 0xf9eb00, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
{ "movbu", 0xf040, 0xfff0, 0, FMT_D0, 0, {MEM(AM0), DN1}},
{ "movbu", 0xf84000, 0xfff000, 0, FMT_D1, 0, {MEM2(SD8, AM0), DN1}},
{ "movbu", 0xfa400000, 0xfff00000, 0, FMT_D2, 0, {MEM2(SD16, AM0), DN1}},
{ "movbu", 0xf8b800, 0xfffcff, 0, FMT_D1, 0, {MEM(SP), DN0}},
{ "movbu", 0xf8b800, 0xfffc00, 0, FMT_D1, 0, {MEM2(IMM8, SP), DN0}},
{ "movbu", 0xfab80000, 0xfffc0000, 0, FMT_D2, 0, {MEM2(IMM16, SP), DN0}},
{ "movbu", 0xf400, 0xffc0, 0, FMT_D0, 0, {MEM2(DI, AM0), DN2}},
{ "movbu", 0x340000, 0xfc0000, 0, FMT_S2, 0, {MEM(IMM16_MEM), DN0}},
{ "movbu", 0xf050, 0xfff0, 0, FMT_D0, 0, {DM1, MEM(AN0)}},
{ "movbu", 0xf85000, 0xfff000, 0, FMT_D1, 0, {DM1, MEM2(SD8, AN0)}},
{ "movbu", 0xfa500000, 0xfff00000, 0, FMT_D2, 0, {DM1, MEM2(SD16, AN0)}},
{ "movbu", 0xf89200, 0xfff3ff, 0, FMT_D1, 0, {DM1, MEM(SP)}},
{ "movbu", 0xf89200, 0xfff300, 0, FMT_D1, 0, {DM1, MEM2(IMM8, SP)}},
{ "movbu", 0xfa920000, 0xfff30000, 0, FMT_D2, 0, {DM1, MEM2(IMM16, SP)}},
{ "movbu", 0xf440, 0xffc0, 0, FMT_D0, 0, {DM2, MEM2(DI, AN0)}},
{ "movbu", 0x020000, 0xf30000, 0, FMT_S2, 0, {DM1, MEM(IMM16_MEM)}},
{ "movbu", 0xf92a00, 0xffff00, 0, FMT_D6, AM33, {MEM(RM0), RN2}},
{ "movbu", 0xf93a00, 0xffff00, 0, FMT_D6, AM33, {RM2, MEM(RN0)}},
{ "movbu", 0xf9aa00, 0xffff0f, 0, FMT_D6, AM33, {MEM(SP), RN2}},
{ "movbu", 0xf9ba00, 0xffff0f, 0, FMT_D6, AM33, {RM2, MEM(SP)}},
{ "movbu", 0xfb2a0000, 0xffff0000, 0, FMT_D7, AM33, {MEM2(SD8, RM0), RN2}},
{ "movbu", 0xfd2a0000, 0xffff0000, 0, FMT_D8, AM33, {MEM2(SD24, RM0), RN2}},
{ "movbu", 0xfb3a0000, 0xffff0000, 0, FMT_D7, AM33, {RM2, MEM2(SD8, RN0)}},
{ "movbu", 0xfd3a0000, 0xffff0000, 0, FMT_D8, AM33, {RM2, MEM2(SD24, RN0)}},
{ "movbu", 0xfbaa0000, 0xffff0f00, 0, FMT_D7, AM33, {MEM2(IMM8, SP), RN2}},
{ "movbu", 0xfdaa0000, 0xffff0f00, 0, FMT_D8, AM33, {MEM2(IMM24, SP), RN2}},
{ "movbu", 0xfbba0000, 0xffff0f00, 0, FMT_D7, AM33, {RM2, MEM2(IMM8, SP)}},
{ "movbu", 0xfdba0000, 0xffff0f00, 0, FMT_D8, AM33, {RM2, MEM2(IMM24, SP)}},
{ "movbu", 0xfb2e0000, 0xffff0f00, 0, FMT_D7, AM33, {MEM(IMM8_MEM), RN2}},
{ "movbu", 0xfd2e0000, 0xffff0f00, 0, FMT_D8, AM33, {MEM(IMM24_MEM), RN2}},
{ "movbu", 0xfb3e0000, 0xffff0f00, 0, FMT_D7, AM33, {RM2, MEM(IMM8_MEM)}},
{ "movbu", 0xfd3e0000, 0xffff0f00, 0, FMT_D8, AM33, {RM2, MEM(IMM24_MEM)}},
{ "movbu", 0xfbae0000, 0xffff000f, 0, FMT_D7, AM33, {MEM2(RI, RM0), RD2}},
{ "movbu", 0xfbbe0000, 0xffff000f, 0, FMT_D7, AM33, {RD2, MEM2(RI, RN0)}},
{ "movbu", 0xfc400000, 0xfff00000, 0, FMT_D4, 0, {MEM2(IMM32,AM0), DN1}},
{ "movbu", 0xfcb80000, 0xfffc0000, 0, FMT_D4, 0, {MEM2(IMM32, SP), DN0}},
{ "movbu", 0xfca80000, 0xfffc0000, 0, FMT_D4, 0, {MEM(IMM32_MEM), DN0}},
{ "movbu", 0xfc500000, 0xfff00000, 0, FMT_D4, 0, {DM1, MEM2(IMM32,AN0)}},
{ "movbu", 0xfc920000, 0xfff30000, 0, FMT_D4, 0, {DM1, MEM2(IMM32, SP)}},
{ "movbu", 0xfc820000, 0xfff30000, 0, FMT_D4, 0, {DM1, MEM(IMM32_MEM)}},
{ "movbu", 0xfe2a0000, 0xffff0000, 0, FMT_D9, AM33, {MEM2(IMM32_HIGH8,RM0), RN2}},
{ "movbu", 0xfe3a0000, 0xffff0000, 0, FMT_D9, AM33, {RM2, MEM2(IMM32_HIGH8, RN0)}},
{ "movbu", 0xfeaa0000, 0xffff0f00, 0, FMT_D9, AM33, {MEM2(IMM32_HIGH8,SP), RN2}},
{ "movbu", 0xfeba0000, 0xffff0f00, 0, FMT_D9, AM33, {RM2, MEM2(IMM32_HIGH8, SP)}},
{ "movbu", 0xfe2e0000, 0xffff0f00, 0, FMT_D9, AM33, {MEM(IMM32_HIGH8_MEM), RN2}},
{ "movbu", 0xfe3e0000, 0xffff0f00, 0, FMT_D9, AM33, {RM2, MEM(IMM32_HIGH8_MEM)}},
{ "movhu", 0xf060, 0xfff0, 0, FMT_D0, 0, {MEM(AM0), DN1}},
{ "movhu", 0xf86000, 0xfff000, 0, FMT_D1, 0, {MEM2(SD8, AM0), DN1}},
{ "movhu", 0xfa600000, 0xfff00000, 0, FMT_D2, 0, {MEM2(SD16, AM0), DN1}},
{ "movhu", 0xf8bc00, 0xfffcff, 0, FMT_D1, 0, {MEM(SP), DN0}},
{ "movhu", 0xf8bc00, 0xfffc00, 0, FMT_D1, 0, {MEM2(IMM8, SP), DN0}},
{ "movhu", 0xfabc0000, 0xfffc0000, 0, FMT_D2, 0, {MEM2(IMM16, SP), DN0}},
{ "movhu", 0xf480, 0xffc0, 0, FMT_D0, 0, {MEM2(DI, AM0), DN2}},
{ "movhu", 0x380000, 0xfc0000, 0, FMT_S2, 0, {MEM(IMM16_MEM), DN0}},
{ "movhu", 0xf070, 0xfff0, 0, FMT_D0, 0, {DM1, MEM(AN0)}},
{ "movhu", 0xf87000, 0xfff000, 0, FMT_D1, 0, {DM1, MEM2(SD8, AN0)}},
{ "movhu", 0xfa700000, 0xfff00000, 0, FMT_D2, 0, {DM1, MEM2(SD16, AN0)}},
{ "movhu", 0xf89300, 0xfff3ff, 0, FMT_D1, 0, {DM1, MEM(SP)}},
{ "movhu", 0xf89300, 0xfff300, 0, FMT_D1, 0, {DM1, MEM2(IMM8, SP)}},
{ "movhu", 0xfa930000, 0xfff30000, 0, FMT_D2, 0, {DM1, MEM2(IMM16, SP)}},
{ "movhu", 0xf4c0, 0xffc0, 0, FMT_D0, 0, {DM2, MEM2(DI, AN0)}},
{ "movhu", 0x030000, 0xf30000, 0, FMT_S2, 0, {DM1, MEM(IMM16_MEM)}},
{ "movhu", 0xf94a00, 0xffff00, 0, FMT_D6, AM33, {MEM(RM0), RN2}},
{ "movhu", 0xf95a00, 0xffff00, 0, FMT_D6, AM33, {RM2, MEM(RN0)}},
{ "movhu", 0xf9ca00, 0xffff0f, 0, FMT_D6, AM33, {MEM(SP), RN2}},
{ "movhu", 0xf9da00, 0xffff0f, 0, FMT_D6, AM33, {RM2, MEM(SP)}},
{ "movhu", 0xf9ea00, 0xffff00, 0x12, FMT_D6, AM33, {MEMINC(RM0), RN2}},
{ "movhu", 0xf9fa00, 0xffff00, 0, FMT_D6, AM33, {RM2, MEMINC(RN0)}},
{ "movhu", 0xfb4a0000, 0xffff0000, 0, FMT_D7, AM33, {MEM2(SD8, RM0), RN2}},
{ "movhu", 0xfd4a0000, 0xffff0000, 0, FMT_D8, AM33, {MEM2(SD24, RM0), RN2}},
{ "movhu", 0xfb5a0000, 0xffff0000, 0, FMT_D7, AM33, {RM2, MEM2(SD8, RN0)}},
{ "movhu", 0xfd5a0000, 0xffff0000, 0, FMT_D8, AM33, {RM2, MEM2(SD24, RN0)}},
{ "movhu", 0xfbca0000, 0xffff0f00, 0, FMT_D7, AM33, {MEM2(IMM8, SP), RN2}},
{ "movhu", 0xfdca0000, 0xffff0f00, 0, FMT_D8, AM33, {MEM2(IMM24, SP), RN2}},
{ "movhu", 0xfbda0000, 0xffff0f00, 0, FMT_D7, AM33, {RM2, MEM2(IMM8, SP)}},
{ "movhu", 0xfdda0000, 0xffff0f00, 0, FMT_D8, AM33, {RM2, MEM2(IMM24, SP)}},
{ "movhu", 0xfb4e0000, 0xffff0f00, 0, FMT_D7, AM33, {MEM(IMM8_MEM), RN2}},
{ "movhu", 0xfd4e0000, 0xffff0f00, 0, FMT_D8, AM33, {MEM(IMM24_MEM), RN2}},
{ "movhu", 0xfbce0000, 0xffff000f, 0, FMT_D7, AM33, {MEM2(RI, RM0), RD2}},
{ "movhu", 0xfbde0000, 0xffff000f, 0, FMT_D7, AM33, {RD2, MEM2(RI, RN0)}},
{ "movhu", 0xfc600000, 0xfff00000, 0, FMT_D4, 0, {MEM2(IMM32,AM0), DN1}},
{ "movhu", 0xfcbc0000, 0xfffc0000, 0, FMT_D4, 0, {MEM2(IMM32, SP), DN0}},
{ "movhu", 0xfcac0000, 0xfffc0000, 0, FMT_D4, 0, {MEM(IMM32_MEM), DN0}},
{ "movhu", 0xfc700000, 0xfff00000, 0, FMT_D4, 0, {DM1, MEM2(IMM32,AN0)}},
{ "movhu", 0xfc930000, 0xfff30000, 0, FMT_D4, 0, {DM1, MEM2(IMM32, SP)}},
{ "movhu", 0xfc830000, 0xfff30000, 0, FMT_D4, 0, {DM1, MEM(IMM32_MEM)}},
{ "movhu", 0xfe4a0000, 0xffff0000, 0, FMT_D9, AM33, {MEM2(IMM32_HIGH8,RM0), RN2}},
{ "movhu", 0xfe5a0000, 0xffff0000, 0, FMT_D9, AM33, {RM2, MEM2(IMM32_HIGH8, RN0)}},
{ "movhu", 0xfeca0000, 0xffff0f00, 0, FMT_D9, AM33, {MEM2(IMM32_HIGH8, SP), RN2}},
{ "movhu", 0xfeda0000, 0xffff0f00, 0, FMT_D9, AM33, {RM2, MEM2(IMM32_HIGH8, SP)}},
{ "movhu", 0xfe4e0000, 0xffff0f00, 0, FMT_D9, AM33, {MEM(IMM32_HIGH8_MEM), RN2}},
{ "movhu", 0xfb5e0000, 0xffff0f00, 0, FMT_D7, AM33, {RM2, MEM(IMM8_MEM)}},
{ "movhu", 0xfd5e0000, 0xffff0f00, 0, FMT_D8, AM33, {RM2, MEM(IMM24_MEM)}},
{ "movhu", 0xfe5e0000, 0xffff0f00, 0, FMT_D9, AM33, {RM2, MEM(IMM32_HIGH8_MEM)}},
{ "movhu", 0xfbea0000, 0xffff0000, 0x22, FMT_D7, AM33, {MEMINC2 (RM0, SIMM8), RN2}},
{ "movhu", 0xfbfa0000, 0xffff0000, 0, FMT_D7, AM33, {RM2, MEMINC2 (RN0, SIMM8)}},
{ "movhu", 0xfdea0000, 0xffff0000, 0x22, FMT_D8, AM33, {MEMINC2 (RM0, IMM24), RN2}},
{ "movhu", 0xfdfa0000, 0xffff0000, 0, FMT_D8, AM33, {RM2, MEMINC2 (RN0, IMM24)}},
{ "movhu", 0xfeea0000, 0xffff0000, 0x22, FMT_D9, AM33, {MEMINC2 (RM0, IMM32_HIGH8), RN2}},
{ "movhu", 0xfefa0000, 0xffff0000, 0, FMT_D9, AM33, {RN2, MEMINC2 (RM0, IMM32_HIGH8)}},
{ "ext", 0xf2d0, 0xfffc, 0, FMT_D0, 0, {DN0}},
{ "ext", 0xf91800, 0xffff00, 0, FMT_D6, AM33, {RN02}},
{ "extb", 0xf92800, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
{ "extb", 0x10, 0xfc, 0, FMT_S0, 0, {DN0}},
{ "extb", 0xf92800, 0xffff00, 0, FMT_D6, AM33, {RN02}},
{ "extbu", 0xf93800, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
{ "extbu", 0x14, 0xfc, 0, FMT_S0, 0, {DN0}},
{ "extbu", 0xf93800, 0xffff00, 0, FMT_D6, AM33, {RN02}},
{ "exth", 0xf94800, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
{ "exth", 0x18, 0xfc, 0, FMT_S0, 0, {DN0}},
{ "exth", 0xf94800, 0xffff00, 0, FMT_D6, AM33, {RN02}},
{ "exthu", 0xf95800, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
{ "exthu", 0x1c, 0xfc, 0, FMT_S0, 0, {DN0}},
{ "exthu", 0xf95800, 0xffff00, 0, FMT_D6, AM33, {RN02}},
{ "movm", 0xce00, 0xff00, 0, FMT_S1, 0, {MEM(SP), REGS}},
{ "movm", 0xcf00, 0xff00, 0, FMT_S1, 0, {REGS, MEM(SP)}},
{ "movm", 0xf8ce00, 0xffff00, 0, FMT_D1, AM33, {MEM(USP), REGS}},
{ "movm", 0xf8cf00, 0xffff00, 0, FMT_D1, AM33, {REGS, MEM(USP)}},
{ "clr", 0x00, 0xf3, 0, FMT_S0, 0, {DN1}},
{ "clr", 0xf96800, 0xffff00, 0, FMT_D6, AM33, {RN02}},
{ "add", 0xfb7c0000, 0xffff000f, 0, FMT_D7, AM33, {RM2, RN0, RD2}},
{ "add", 0xe0, 0xf0, 0, FMT_S0, 0, {DM1, DN0}},
{ "add", 0xf160, 0xfff0, 0, FMT_D0, 0, {DM1, AN0}},
{ "add", 0xf150, 0xfff0, 0, FMT_D0, 0, {AM1, DN0}},
{ "add", 0xf170, 0xfff0, 0, FMT_D0, 0, {AM1, AN0}},
{ "add", 0x2800, 0xfc00, 0, FMT_S1, 0, {SIMM8, DN0}},
{ "add", 0xfac00000, 0xfffc0000, 0, FMT_D2, 0, {SIMM16, DN0}},
{ "add", 0x2000, 0xfc00, 0, FMT_S1, 0, {SIMM8, AN0}},
{ "add", 0xfad00000, 0xfffc0000, 0, FMT_D2, 0, {SIMM16, AN0}},
{ "add", 0xf8fe00, 0xffff00, 0, FMT_D1, 0, {SIMM8, SP}},
{ "add", 0xfafe0000, 0xffff0000, 0, FMT_D2, 0, {SIMM16, SP}},
{ "add", 0xf97800, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
{ "add", 0xfcc00000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "add", 0xfcd00000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, AN0}},
{ "add", 0xfcfe0000, 0xffff0000, 0, FMT_D4, 0, {IMM32, SP}},
{ "add", 0xfb780000, 0xffff0000, 0, FMT_D7, AM33, {SIMM8, RN02}},
{ "add", 0xfd780000, 0xffff0000, 0, FMT_D8, AM33, {SIMM24, RN02}},
{ "add", 0xfe780000, 0xffff0000, 0, FMT_D9, AM33, {IMM32_HIGH8, RN02}},
{ "addc", 0xfb8c0000, 0xffff000f, 0, FMT_D7, AM33, {RM2, RN0, RD2}},
{ "addc", 0xf140, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "addc", 0xf98800, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
{ "addc", 0xfb880000, 0xffff0000, 0, FMT_D7, AM33, {SIMM8, RN02}},
{ "addc", 0xfd880000, 0xffff0000, 0, FMT_D8, AM33, {SIMM24, RN02}},
{ "addc", 0xfe880000, 0xffff0000, 0, FMT_D9, AM33, {IMM32_HIGH8, RN02}},
{ "sub", 0xfb9c0000, 0xffff000f, 0, FMT_D7, AM33, {RM2, RN0, RD2}},
{ "sub", 0xf100, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "sub", 0xf120, 0xfff0, 0, FMT_D0, 0, {DM1, AN0}},
{ "sub", 0xf110, 0xfff0, 0, FMT_D0, 0, {AM1, DN0}},
{ "sub", 0xf130, 0xfff0, 0, FMT_D0, 0, {AM1, AN0}},
{ "sub", 0xf99800, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
{ "sub", 0xfcc40000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "sub", 0xfcd40000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, AN0}},
{ "sub", 0xfb980000, 0xffff0000, 0, FMT_D7, AM33, {SIMM8, RN02}},
{ "sub", 0xfd980000, 0xffff0000, 0, FMT_D8, AM33, {SIMM24, RN02}},
{ "sub", 0xfe980000, 0xffff0000, 0, FMT_D9, AM33, {IMM32_HIGH8, RN02}},
{ "subc", 0xfbac0000, 0xffff000f, 0, FMT_D7, AM33, {RM2, RN0, RD2}},
{ "subc", 0xf180, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "subc", 0xf9a800, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
{ "subc", 0xfba80000, 0xffff0000, 0, FMT_D7, AM33, {SIMM8, RN02}},
{ "subc", 0xfda80000, 0xffff0000, 0, FMT_D8, AM33, {SIMM24, RN02}},
{ "subc", 0xfea80000, 0xffff0000, 0, FMT_D9, AM33, {IMM32_HIGH8, RN02}},
{ "mul", 0xfbad0000, 0xffff0000, 0xc, FMT_D7, AM33, {RM2, RN0, RD2, RD0}},
{ "mul", 0xf240, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "mul", 0xf9a900, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
{ "mul", 0xfba90000, 0xffff0000, 0, FMT_D7, AM33, {SIMM8, RN02}},
{ "mul", 0xfda90000, 0xffff0000, 0, FMT_D8, AM33, {SIMM24, RN02}},
{ "mul", 0xfea90000, 0xffff0000, 0, FMT_D9, AM33, {IMM32_HIGH8, RN02}},
{ "mulu", 0xfbbd0000, 0xffff0000, 0xc, FMT_D7, AM33, {RM2, RN0, RD2, RD0}},
{ "mulu", 0xf250, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "mulu", 0xf9b900, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
{ "mulu", 0xfbb90000, 0xffff0000, 0, FMT_D7, AM33, {IMM8, RN02}},
{ "mulu", 0xfdb90000, 0xffff0000, 0, FMT_D8, AM33, {IMM24, RN02}},
{ "mulu", 0xfeb90000, 0xffff0000, 0, FMT_D9, AM33, {IMM32_HIGH8, RN02}},
{ "div", 0xf260, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "div", 0xf9c900, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
{ "divu", 0xf270, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "divu", 0xf9d900, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
{ "inc", 0x40, 0xf3, 0, FMT_S0, 0, {DN1}},
{ "inc", 0x41, 0xf3, 0, FMT_S0, 0, {AN1}},
{ "inc", 0xf9b800, 0xffff00, 0, FMT_D6, AM33, {RN02}},
{ "inc4", 0x50, 0xfc, 0, FMT_S0, 0, {AN0}},
{ "inc4", 0xf9c800, 0xffff00, 0, FMT_D6, AM33, {RN02}},
{ "cmp", 0xa000, 0xf000, 0, FMT_S1, 0, {SIMM8, DN01}},
{ "cmp", 0xa0, 0xf0, 0x3, FMT_S0, 0, {DM1, DN0}},
{ "cmp", 0xf1a0, 0xfff0, 0, FMT_D0, 0, {DM1, AN0}},
{ "cmp", 0xf190, 0xfff0, 0, FMT_D0, 0, {AM1, DN0}},
{ "cmp", 0xb000, 0xf000, 0, FMT_S1, 0, {IMM8, AN01}},
{ "cmp", 0xb0, 0xf0, 0x3, FMT_S0, 0, {AM1, AN0}},
{ "cmp", 0xfac80000, 0xfffc0000, 0, FMT_D2, 0, {SIMM16, DN0}},
{ "cmp", 0xfad80000, 0xfffc0000, 0, FMT_D2, 0, {IMM16, AN0}},
{ "cmp", 0xf9d800, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
{ "cmp", 0xfcc80000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "cmp", 0xfcd80000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, AN0}},
{ "cmp", 0xfbd80000, 0xffff0000, 0, FMT_D7, AM33, {SIMM8, RN02}},
{ "cmp", 0xfdd80000, 0xffff0000, 0, FMT_D8, AM33, {SIMM24, RN02}},
{ "cmp", 0xfed80000, 0xffff0000, 0, FMT_D9, AM33, {IMM32_HIGH8, RN02}},
{ "and", 0xfb0d0000, 0xffff000f, 0, FMT_D7, AM33, {RM2, RN0, RD2}},
{ "and", 0xf200, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "and", 0xf8e000, 0xfffc00, 0, FMT_D1, 0, {IMM8, DN0}},
{ "and", 0xfae00000, 0xfffc0000, 0, FMT_D2, 0, {IMM16, DN0}},
{ "and", 0xfafc0000, 0xffff0000, 0, FMT_D2, 0, {IMM16, PSW}},
{ "and", 0xfcfc0000, 0xffff0000, 0, FMT_D4, AM33, {IMM32, EPSW}},
{ "and", 0xf90900, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
{ "and", 0xfce00000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "and", 0xfb090000, 0xffff0000, 0, FMT_D7, AM33, {IMM8, RN02}},
{ "and", 0xfd090000, 0xffff0000, 0, FMT_D8, AM33, {IMM24, RN02}},
{ "and", 0xfe090000, 0xffff0000, 0, FMT_D9, AM33, {IMM32_HIGH8, RN02}},
{ "or", 0xfb1d0000, 0xffff000f, 0, FMT_D7, AM33, {RM2, RN0, RD2}},
{ "or", 0xf210, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "or", 0xf8e400, 0xfffc00, 0, FMT_D1, 0, {IMM8, DN0}},
{ "or", 0xfae40000, 0xfffc0000, 0, FMT_D2, 0, {IMM16, DN0}},
{ "or", 0xfafd0000, 0xffff0000, 0, FMT_D2, 0, {IMM16, PSW}},
{ "or", 0xfcfd0000, 0xffff0000, 0, FMT_D4, AM33, {IMM32, EPSW}},
{ "or", 0xf91900, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
{ "or", 0xfce40000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "or", 0xfb190000, 0xffff0000, 0, FMT_D7, AM33, {IMM8, RN02}},
{ "or", 0xfd190000, 0xffff0000, 0, FMT_D8, AM33, {IMM24, RN02}},
{ "or", 0xfe190000, 0xffff0000, 0, FMT_D9, AM33, {IMM32_HIGH8, RN02}},
{ "xor", 0xfb2d0000, 0xffff000f, 0, FMT_D7, AM33, {RM2, RN0, RD2}},
{ "xor", 0xf220, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "xor", 0xfae80000, 0xfffc0000, 0, FMT_D2, 0, {IMM16, DN0}},
{ "xor", 0xf92900, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
{ "xor", 0xfce80000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "xor", 0xfb290000, 0xffff0000, 0, FMT_D7, AM33, {IMM8, RN02}},
{ "xor", 0xfd290000, 0xffff0000, 0, FMT_D8, AM33, {IMM24, RN02}},
{ "xor", 0xfe290000, 0xffff0000, 0, FMT_D9, AM33, {IMM32_HIGH8, RN02}},
{ "not", 0xf230, 0xfffc, 0, FMT_D0, 0, {DN0}},
{ "not", 0xf93900, 0xffff00, 0, FMT_D6, AM33, {RN02}},
{ "btst", 0xf8ec00, 0xfffc00, 0, FMT_D1, 0, {IMM8, DN0}},
{ "btst", 0xfaec0000, 0xfffc0000, 0, FMT_D2, 0, {IMM16, DN0}},
{ "btst", 0xfcec0000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
/* Place these before the ones with IMM8E and SD8N_SHIFT8 since we want the
them to match last since they do not promote. */
{ "btst", 0xfbe90000, 0xffff0000, 0, FMT_D7, AM33, {IMM8, RN02}},
{ "btst", 0xfde90000, 0xffff0000, 0, FMT_D8, AM33, {IMM24, RN02}},
{ "btst", 0xfee90000, 0xffff0000, 0, FMT_D9, AM33, {IMM32_HIGH8, RN02}},
{ "btst", 0xfe820000, 0xffff0000, 0, FMT_D3, AM33_2, {IMM8E, MEM(IMM16_MEM)}},
{ "btst", 0xfe020000, 0xffff0000, 0, FMT_D5, 0, {IMM8E, MEM(IMM32_LOWSHIFT8)}},
{ "btst", 0xfaf80000, 0xfffc0000, 0, FMT_D2, 0, {IMM8, MEM2(SD8N_SHIFT8, AN0)}},
{ "bset", 0xf080, 0xfff0, 0, FMT_D0, 0, {DM1, MEM(AN0)}},
{ "bset", 0xfe800000, 0xffff0000, 0, FMT_D3, AM33_2, {IMM8E, MEM(IMM16_MEM)}},
{ "bset", 0xfe000000, 0xffff0000, 0, FMT_D5, 0, {IMM8E, MEM(IMM32_LOWSHIFT8)}},
{ "bset", 0xfaf00000, 0xfffc0000, 0, FMT_D2, 0, {IMM8, MEM2(SD8N_SHIFT8, AN0)}},
{ "bclr", 0xf090, 0xfff0, 0, FMT_D0, 0, {DM1, MEM(AN0)}},
{ "bclr", 0xfe810000, 0xffff0000, 0, FMT_D3, AM33_2, {IMM8E, MEM(IMM16_MEM)}},
{ "bclr", 0xfe010000, 0xffff0000, 0, FMT_D5, 0, {IMM8E, MEM(IMM32_LOWSHIFT8)}},
{ "bclr", 0xfaf40000, 0xfffc0000, 0, FMT_D2, 0, {IMM8, MEM2(SD8N_SHIFT8,AN0)}},
{ "asr", 0xfb4d0000, 0xffff000f, 0, FMT_D7, AM33, {RM2, RN0, RD2}},
{ "asr", 0xf2b0, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "asr", 0xf8c800, 0xfffc00, 0, FMT_D1, 0, {IMM8, DN0}},
{ "asr", 0xf94900, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
{ "asr", 0xfb490000, 0xffff0000, 0, FMT_D7, AM33, {IMM8, RN02}},
{ "asr", 0xfd490000, 0xffff0000, 0, FMT_D8, AM33, {IMM24, RN02}},
{ "asr", 0xfe490000, 0xffff0000, 0, FMT_D9, AM33, {IMM32_HIGH8, RN02}},
{ "asr", 0xf8c801, 0xfffcff, 0, FMT_D1, 0, {DN0}},
{ "asr", 0xfb490001, 0xffff00ff, 0, FMT_D7, AM33, {RN02}},
{ "lsr", 0xfb5d0000, 0xffff000f, 0, FMT_D7, AM33, {RM2, RN0, RD2}},
{ "lsr", 0xf2a0, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "lsr", 0xf8c400, 0xfffc00, 0, FMT_D1, 0, {IMM8, DN0}},
{ "lsr", 0xf95900, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
{ "lsr", 0xfb590000, 0xffff0000, 0, FMT_D7, AM33, {IMM8, RN02}},
{ "lsr", 0xfd590000, 0xffff0000, 0, FMT_D8, AM33, {IMM24, RN02}},
{ "lsr", 0xfe590000, 0xffff0000, 0, FMT_D9, AM33, {IMM32_HIGH8, RN02}},
{ "lsr", 0xf8c401, 0xfffcff, 0, FMT_D1, 0, {DN0}},
{ "lsr", 0xfb590001, 0xffff00ff, 0, FMT_D7, AM33, {RN02}},
{ "asl", 0xfb6d0000, 0xffff000f, 0, FMT_D7, AM33, {RM2, RN0, RD2}},
{ "asl", 0xf290, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "asl", 0xf8c000, 0xfffc00, 0, FMT_D1, 0, {IMM8, DN0}},
{ "asl", 0xf96900, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
{ "asl", 0xfb690000, 0xffff0000, 0, FMT_D7, AM33, {SIMM8, RN02}},
{ "asl", 0xfd690000, 0xffff0000, 0, FMT_D8, AM33, {IMM24, RN02}},
{ "asl", 0xfe690000, 0xffff0000, 0, FMT_D9, AM33, {IMM32_HIGH8, RN02}},
{ "asl", 0xf8c001, 0xfffcff, 0, FMT_D1, 0, {DN0}},
{ "asl", 0xfb690001, 0xffff00ff, 0, FMT_D7, AM33, {RN02}},
{ "asl2", 0x54, 0xfc, 0, FMT_S0, 0, {DN0}},
{ "asl2", 0xf97900, 0xffff00, 0, FMT_D6, AM33, {RN02}},
{ "ror", 0xf284, 0xfffc, 0, FMT_D0, 0, {DN0}},
{ "ror", 0xf98900, 0xffff00, 0, FMT_D6, AM33, {RN02}},
{ "rol", 0xf280, 0xfffc, 0, FMT_D0, 0, {DN0}},
{ "rol", 0xf99900, 0xffff00, 0, FMT_D6, AM33, {RN02}},
{ "beq", 0xc800, 0xff00, 0, FMT_S1, 0, {SD8N_PCREL}},
{ "bne", 0xc900, 0xff00, 0, FMT_S1, 0, {SD8N_PCREL}},
{ "bgt", 0xc100, 0xff00, 0, FMT_S1, 0, {SD8N_PCREL}},
{ "bge", 0xc200, 0xff00, 0, FMT_S1, 0, {SD8N_PCREL}},
{ "ble", 0xc300, 0xff00, 0, FMT_S1, 0, {SD8N_PCREL}},
{ "blt", 0xc000, 0xff00, 0, FMT_S1, 0, {SD8N_PCREL}},
{ "bhi", 0xc500, 0xff00, 0, FMT_S1, 0, {SD8N_PCREL}},
{ "bcc", 0xc600, 0xff00, 0, FMT_S1, 0, {SD8N_PCREL}},
{ "bls", 0xc700, 0xff00, 0, FMT_S1, 0, {SD8N_PCREL}},
{ "bcs", 0xc400, 0xff00, 0, FMT_S1, 0, {SD8N_PCREL}},
{ "bvc", 0xf8e800, 0xffff00, 0, FMT_D1, 0, {SD8N_PCREL}},
{ "bvs", 0xf8e900, 0xffff00, 0, FMT_D1, 0, {SD8N_PCREL}},
{ "bnc", 0xf8ea00, 0xffff00, 0, FMT_D1, 0, {SD8N_PCREL}},
{ "bns", 0xf8eb00, 0xffff00, 0, FMT_D1, 0, {SD8N_PCREL}},
{ "bra", 0xca00, 0xff00, 0, FMT_S1, 0, {SD8N_PCREL}},
{ "leq", 0xd8, 0xff, 0, FMT_S0, 0, {UNUSED}},
{ "lne", 0xd9, 0xff, 0, FMT_S0, 0, {UNUSED}},
{ "lgt", 0xd1, 0xff, 0, FMT_S0, 0, {UNUSED}},
{ "lge", 0xd2, 0xff, 0, FMT_S0, 0, {UNUSED}},
{ "lle", 0xd3, 0xff, 0, FMT_S0, 0, {UNUSED}},
{ "llt", 0xd0, 0xff, 0, FMT_S0, 0, {UNUSED}},
{ "lhi", 0xd5, 0xff, 0, FMT_S0, 0, {UNUSED}},
{ "lcc", 0xd6, 0xff, 0, FMT_S0, 0, {UNUSED}},
{ "lls", 0xd7, 0xff, 0, FMT_S0, 0, {UNUSED}},
{ "lcs", 0xd4, 0xff, 0, FMT_S0, 0, {UNUSED}},
{ "lra", 0xda, 0xff, 0, FMT_S0, 0, {UNUSED}},
{ "setlb", 0xdb, 0xff, 0, FMT_S0, 0, {UNUSED}},
{ "fbeq", 0xf8d000, 0xffff00, 0, FMT_D1, AM33_2, {SD8N_PCREL}},
{ "fbne", 0xf8d100, 0xffff00, 0, FMT_D1, AM33_2, {SD8N_PCREL}},
{ "fbgt", 0xf8d200, 0xffff00, 0, FMT_D1, AM33_2, {SD8N_PCREL}},
{ "fbge", 0xf8d300, 0xffff00, 0, FMT_D1, AM33_2, {SD8N_PCREL}},
{ "fblt", 0xf8d400, 0xffff00, 0, FMT_D1, AM33_2, {SD8N_PCREL}},
{ "fble", 0xf8d500, 0xffff00, 0, FMT_D1, AM33_2, {SD8N_PCREL}},
{ "fbuo", 0xf8d600, 0xffff00, 0, FMT_D1, AM33_2, {SD8N_PCREL}},
{ "fblg", 0xf8d700, 0xffff00, 0, FMT_D1, AM33_2, {SD8N_PCREL}},
{ "fbleg", 0xf8d800, 0xffff00, 0, FMT_D1, AM33_2, {SD8N_PCREL}},
{ "fbug", 0xf8d900, 0xffff00, 0, FMT_D1, AM33_2, {SD8N_PCREL}},
{ "fbuge", 0xf8da00, 0xffff00, 0, FMT_D1, AM33_2, {SD8N_PCREL}},
{ "fbul", 0xf8db00, 0xffff00, 0, FMT_D1, AM33_2, {SD8N_PCREL}},
{ "fbule", 0xf8dc00, 0xffff00, 0, FMT_D1, AM33_2, {SD8N_PCREL}},
{ "fbue", 0xf8dd00, 0xffff00, 0, FMT_D1, AM33_2, {SD8N_PCREL}},
{ "fleq", 0xf0d0, 0xffff, 0, FMT_D0, AM33_2, {UNUSED}},
{ "flne", 0xf0d1, 0xffff, 0, FMT_D0, AM33_2, {UNUSED}},
{ "flgt", 0xf0d2, 0xffff, 0, FMT_D0, AM33_2, {UNUSED}},
{ "flge", 0xf0d3, 0xffff, 0, FMT_D0, AM33_2, {UNUSED}},
{ "fllt", 0xf0d4, 0xffff, 0, FMT_D0, AM33_2, {UNUSED}},
{ "flle", 0xf0d5, 0xffff, 0, FMT_D0, AM33_2, {UNUSED}},
{ "fluo", 0xf0d6, 0xffff, 0, FMT_D0, AM33_2, {UNUSED}},
{ "fllg", 0xf0d7, 0xffff, 0, FMT_D0, AM33_2, {UNUSED}},
{ "flleg", 0xf0d8, 0xffff, 0, FMT_D0, AM33_2, {UNUSED}},
{ "flug", 0xf0d9, 0xffff, 0, FMT_D0, AM33_2, {UNUSED}},
{ "fluge", 0xf0da, 0xffff, 0, FMT_D0, AM33_2, {UNUSED}},
{ "flul", 0xf0db, 0xffff, 0, FMT_D0, AM33_2, {UNUSED}},
{ "flule", 0xf0dc, 0xffff, 0, FMT_D0, AM33_2, {UNUSED}},
{ "flue", 0xf0dd, 0xffff, 0, FMT_D0, AM33_2, {UNUSED}},
{ "jmp", 0xf0f4, 0xfffc, 0, FMT_D0, 0, {PAREN,AN0,PAREN}},
{ "jmp", 0xcc0000, 0xff0000, 0, FMT_S2, 0, {IMM16_PCREL}},
{ "jmp", 0xdc000000, 0xff000000, 0, FMT_S4, 0, {IMM32_HIGH24}},
{ "call", 0xcd000000, 0xff000000, 0, FMT_S4, 0, {D16_SHIFT,REGS,IMM8E}},
{ "call", 0xdd000000, 0xff000000, 0, FMT_S6, 0, {IMM32_HIGH24_LOWSHIFT16, REGSE_SHIFT8,IMM8E}},
{ "calls", 0xf0f0, 0xfffc, 0, FMT_D0, 0, {PAREN,AN0,PAREN}},
{ "calls", 0xfaff0000, 0xffff0000, 0, FMT_D2, 0, {IMM16_PCREL}},
{ "calls", 0xfcff0000, 0xffff0000, 0, FMT_D4, 0, {IMM32_PCREL}},
{ "ret", 0xdf0000, 0xff0000, 0, FMT_S2, 0, {REGS_SHIFT8, IMM8}},
{ "retf", 0xde0000, 0xff0000, 0, FMT_S2, 0, {REGS_SHIFT8, IMM8}},
{ "rets", 0xf0fc, 0xffff, 0, FMT_D0, 0, {UNUSED}},
{ "rti", 0xf0fd, 0xffff, 0, FMT_D0, 0, {UNUSED}},
{ "trap", 0xf0fe, 0xffff, 0, FMT_D0, 0, {UNUSED}},
{ "rtm", 0xf0ff, 0xffff, 0, FMT_D0, 0, {UNUSED}},
{ "nop", 0xcb, 0xff, 0, FMT_S0, 0, {UNUSED}},
{ "dcpf", 0xf9a600, 0xffff0f, 0, FMT_D6, AM33_2, {MEM (RM2)}},
{ "dcpf", 0xf9a700, 0xffffff, 0, FMT_D6, AM33_2, {MEM (SP)}},
{ "dcpf", 0xfba60000, 0xffff00ff, 0, FMT_D7, AM33_2, {MEM2 (RI,RM0)}},
{ "dcpf", 0xfba70000, 0xffff0f00, 0, FMT_D7, AM33_2, {MEM2 (SD8,RM2)}},
{ "dcpf", 0xfda70000, 0xffff0f00, 0, FMT_D8, AM33_2, {MEM2 (SD24,RM2)}},
{ "dcpf", 0xfe460000, 0xffff0f00, 0, FMT_D9, AM33_2, {MEM2 (IMM32_HIGH8,RM2)}},
{ "fmov", 0xf92000, 0xfffe00, 0, FMT_D6, AM33_2, {MEM (RM2), FSM0}},
{ "fmov", 0xf92200, 0xfffe00, 0, FMT_D6, AM33_2, {MEMINC (RM2), FSM0}},
{ "fmov", 0xf92400, 0xfffef0, 0, FMT_D6, AM33_2, {MEM (SP), FSM0}},
{ "fmov", 0xf92600, 0xfffe00, 0, FMT_D6, AM33_2, {RM2, FSM0}},
{ "fmov", 0xf93000, 0xfffd00, 0, FMT_D6, AM33_2, {FSM1, MEM (RM0)}},
{ "fmov", 0xf93100, 0xfffd00, 0, FMT_D6, AM33_2, {FSM1, MEMINC (RM0)}},
{ "fmov", 0xf93400, 0xfffd0f, 0, FMT_D6, AM33_2, {FSM1, MEM (SP)}},
{ "fmov", 0xf93500, 0xfffd00, 0, FMT_D6, AM33_2, {FSM1, RM0}},
{ "fmov", 0xf94000, 0xfffc00, 0, FMT_D6, AM33_2, {FSM1, FSM0}},
{ "fmov", 0xf9a000, 0xfffe01, 0, FMT_D6, AM33_2, {MEM (RM2), FDM0}},
{ "fmov", 0xf9a200, 0xfffe01, 0, FMT_D6, AM33_2, {MEMINC (RM2), FDM0}},
{ "fmov", 0xf9a400, 0xfffef1, 0, FMT_D6, AM33_2, {MEM (SP), FDM0}},
{ "fmov", 0xf9b000, 0xfffd10, 0, FMT_D6, AM33_2, {FDM1, MEM (RM0)}},
{ "fmov", 0xf9b100, 0xfffd10, 0, FMT_D6, AM33_2, {FDM1, MEMINC (RM0)}},
{ "fmov", 0xf9b400, 0xfffd1f, 0, FMT_D6, AM33_2, {FDM1, MEM (SP)}},
{ "fmov", 0xf9b500, 0xffff0f, 0, FMT_D6, AM33_2, {RM2, FPCR}},
{ "fmov", 0xf9b700, 0xfffff0, 0, FMT_D6, AM33_2, {FPCR, RM0}},
{ "fmov", 0xf9c000, 0xfffc11, 0, FMT_D6, AM33_2, {FDM1, FDM0}},
{ "fmov", 0xfb200000, 0xfffe0000, 0, FMT_D7, AM33_2, {MEM2 (SD8, RM2), FSM2}},
{ "fmov", 0xfb220000, 0xfffe0000, 0, FMT_D7, AM33_2, {MEMINC2 (RM2, SIMM8), FSM2}},
{ "fmov", 0xfb240000, 0xfffef000, 0, FMT_D7, AM33_2, {MEM2 (IMM8, SP), FSM2}},
{ "fmov", 0xfb270000, 0xffff000d, 0, FMT_D7, AM33_2, {MEM2 (RI, RM0), FSN1}},
{ "fmov", 0xfb300000, 0xfffd0000, 0, FMT_D7, AM33_2, {FSM3, MEM2 (SD8, RM0)}},
{ "fmov", 0xfb310000, 0xfffd0000, 0, FMT_D7, AM33_2, {FSM3, MEMINC2 (RM0, SIMM8)}},
{ "fmov", 0xfb340000, 0xfffd0f00, 0, FMT_D7, AM33_2, {FSM3, MEM2 (IMM8, SP)}},
{ "fmov", 0xfb370000, 0xffff000d, 0, FMT_D7, AM33_2, {FSN1, MEM2(RI, RM0)}},
/* FIXME: the spec doesn't say the fd register must be even for the
* next two insns. Assuming it was a mistake in the spec. */
{ "fmov", 0xfb470000, 0xffff001d, 0, FMT_D7, AM33_2, {MEM2 (RI, RM0), FDN1}},
{ "fmov", 0xfb570000, 0xffff001d, 0, FMT_D7, AM33_2, {FDN1, MEM2(RI, RM0)}},
/* END of FIXME */
{ "fmov", 0xfba00000, 0xfffe0100, 0, FMT_D7, AM33_2, {MEM2 (SD8, RM2), FDM2}},
{ "fmov", 0xfba20000, 0xfffe0100, 0, FMT_D7, AM33_2, {MEMINC2 (RM2, SIMM8), FDM2}},
{ "fmov", 0xfba40000, 0xfffef100, 0, FMT_D7, AM33_2, {MEM2 (IMM8, SP), FDM2}},
{ "fmov", 0xfbb00000, 0xfffd1000, 0, FMT_D7, AM33_2, {FDM3, MEM2 (SD8, RM0)}},
{ "fmov", 0xfbb10000, 0xfffd1000, 0, FMT_D7, AM33_2, {FDM3, MEMINC2 (RM0, SIMM8)}},
{ "fmov", 0xfbb40000, 0xfffd1f00, 0, FMT_D7, AM33_2, {FDM3, MEM2 (IMM8, SP)}},
{ "fmov", 0xfd200000, 0xfffe0000, 0, FMT_D8, AM33_2, {MEM2 (SIMM24, RM2), FSM2}},
{ "fmov", 0xfd220000, 0xfffe0000, 0, FMT_D8, AM33_2, {MEMINC2 (RM2, SIMM24), FSM2}},
{ "fmov", 0xfd240000, 0xfffef000, 0, FMT_D8, AM33_2, {MEM2 (IMM24, SP), FSM2}},
{ "fmov", 0xfd300000, 0xfffd0000, 0, FMT_D8, AM33_2, {FSM3, MEM2 (SIMM24, RM0)}},
{ "fmov", 0xfd310000, 0xfffd0000, 0, FMT_D8, AM33_2, {FSM3, MEMINC2 (RM0, SIMM24)}},
{ "fmov", 0xfd340000, 0xfffd0f00, 0, FMT_D8, AM33_2, {FSM3, MEM2 (IMM24, SP)}},
{ "fmov", 0xfda00000, 0xfffe0100, 0, FMT_D8, AM33_2, {MEM2 (SIMM24, RM2), FDM2}},
{ "fmov", 0xfda20000, 0xfffe0100, 0, FMT_D8, AM33_2, {MEMINC2 (RM2, SIMM24), FDM2}},
{ "fmov", 0xfda40000, 0xfffef100, 0, FMT_D8, AM33_2, {MEM2 (IMM24, SP), FDM2}},
{ "fmov", 0xfdb00000, 0xfffd1000, 0, FMT_D8, AM33_2, {FDM3, MEM2 (SIMM24, RM0)}},
{ "fmov", 0xfdb10000, 0xfffd1000, 0, FMT_D8, AM33_2, {FDM3, MEMINC2 (RM0, SIMM24)}},
{ "fmov", 0xfdb40000, 0xfffd1f00, 0, FMT_D8, AM33_2, {FDM3, MEM2 (IMM24, SP)}},
{ "fmov", 0xfdb50000, 0xffff0000, 0, FMT_D4, AM33_2, {IMM32, FPCR}},
{ "fmov", 0xfe200000, 0xfffe0000, 0, FMT_D9, AM33_2, {MEM2 (IMM32_HIGH8, RM2), FSM2}},
{ "fmov", 0xfe220000, 0xfffe0000, 0, FMT_D9, AM33_2, {MEMINC2 (RM2, IMM32_HIGH8), FSM2}},
{ "fmov", 0xfe240000, 0xfffef000, 0, FMT_D9, AM33_2, {MEM2 (IMM32_HIGH8, SP), FSM2}},
{ "fmov", 0xfe260000, 0xfffef000, 0, FMT_D9, AM33_2, {IMM32_HIGH8, FSM2}},
{ "fmov", 0xfe300000, 0xfffd0000, 0, FMT_D9, AM33_2, {FSM3, MEM2 (IMM32_HIGH8, RM0)}},
{ "fmov", 0xfe310000, 0xfffd0000, 0, FMT_D9, AM33_2, {FSM3, MEMINC2 (RM0, IMM32_HIGH8)}},
{ "fmov", 0xfe340000, 0xfffd0f00, 0, FMT_D9, AM33_2, {FSM3, MEM2 (IMM32_HIGH8, SP)}},
{ "fmov", 0xfe400000, 0xfffe0100, 0, FMT_D9, AM33_2, {MEM2 (IMM32_HIGH8, RM2), FDM2}},
{ "fmov", 0xfe420000, 0xfffe0100, 0, FMT_D9, AM33_2, {MEMINC2 (RM2, IMM32_HIGH8), FDM2}},
{ "fmov", 0xfe440000, 0xfffef100, 0, FMT_D9, AM33_2, {MEM2 (IMM32_HIGH8, SP), FDM2}},
{ "fmov", 0xfe500000, 0xfffd1000, 0, FMT_D9, AM33_2, {FDM3, MEM2 (IMM32_HIGH8, RM0)}},
{ "fmov", 0xfe510000, 0xfffd1000, 0, FMT_D9, AM33_2, {FDM3, MEMINC2 (RM0, IMM32_HIGH8)}},
{ "fmov", 0xfe540000, 0xfffd1f00, 0, FMT_D9, AM33_2, {FDM3, MEM2 (IMM32_HIGH8, SP)}},
/* FIXME: these are documented in the instruction bitmap, but not in
* the instruction manual. */
{ "ftoi", 0xfb400000, 0xffff0f05, 0, FMT_D10,AM33_2, {FSN3, FSN1}},
{ "itof", 0xfb420000, 0xffff0f05, 0, FMT_D10,AM33_2, {FSN3, FSN1}},
{ "ftod", 0xfb520000, 0xffff0f15, 0, FMT_D10,AM33_2, {FSN3, FDN1}},
{ "dtof", 0xfb560000, 0xffff1f05, 0, FMT_D10,AM33_2, {FDN3, FSN1}},
/* END of FIXME */
{ "fabs", 0xfb440000, 0xffff0f05, 0, FMT_D10,AM33_2, {FSN3, FSN1}},
{ "fabs", 0xfbc40000, 0xffff1f15, 0, FMT_D10,AM33_2, {FDN3, FDN1}},
{ "fabs", 0xf94400, 0xfffef0, 0, FMT_D6, AM33_2, {FSM0}},
{ "fabs", 0xf9c400, 0xfffef1, 0, FMT_D6, AM33_2, {FDM0}},
{ "fneg", 0xfb460000, 0xffff0f05, 0, FMT_D10,AM33_2, {FSN3, FSN1}},
{ "fneg", 0xfbc60000, 0xffff1f15, 0, FMT_D10,AM33_2, {FDN3, FDN1}},
{ "fneg", 0xf94600, 0xfffef0, 0, FMT_D6, AM33_2, {FSM0}},
{ "fneg", 0xf9c600, 0xfffef1, 0, FMT_D6, AM33_2, {FDM0}},
{ "frsqrt", 0xfb500000, 0xffff0f05, 0, FMT_D10,AM33_2, {FSN3, FSN1}},
{ "frsqrt", 0xfbd00000, 0xffff1f15, 0, FMT_D10,AM33_2, {FDN3, FDN1}},
{ "frsqrt", 0xf95000, 0xfffef0, 0, FMT_D6, AM33_2, {FSM0}},
{ "frsqrt", 0xf9d000, 0xfffef1, 0, FMT_D6, AM33_2, {FDM0}},
/* FIXME: this is documented in the instruction bitmap, but not in
* the instruction manual. */
{ "fsqrt", 0xfb540000, 0xffff0f05, 0, FMT_D10,AM33_2, {FSN3, FSN1}},
{ "fsqrt", 0xfbd40000, 0xffff1f15, 0, FMT_D10,AM33_2, {FDN3, FDN1}},
{ "fsqrt", 0xf95200, 0xfffef0, 0, FMT_D6, AM33_2, {FSM0}},
{ "fsqrt", 0xf9d200, 0xfffef1, 0, FMT_D6, AM33_2, {FDM0}},
/* END of FIXME */
{ "fcmp", 0xf95400, 0xfffc00, 0, FMT_D6, AM33_2, {FSM1, FSM0}},
{ "fcmp", 0xf9d400, 0xfffc11, 0, FMT_D6, AM33_2, {FDM1, FDM0}},
{ "fcmp", 0xfe350000, 0xfffd0f00, 0, FMT_D9, AM33_2, {IMM32_HIGH8, FSM3}},
{ "fadd", 0xfb600000, 0xffff0001, 0, FMT_D10,AM33_2, {FSN3, FSN2, FSN1}},
{ "fadd", 0xfbe00000, 0xffff1111, 0, FMT_D10,AM33_2, {FDN3, FDN2, FDN1}},
{ "fadd", 0xf96000, 0xfffc00, 0, FMT_D6, AM33_2, {FSM1, FSM0}},
{ "fadd", 0xf9e000, 0xfffc11, 0, FMT_D6, AM33_2, {FDM1, FDM0}},
{ "fadd", 0xfe600000, 0xfffc0000, 0, FMT_D9, AM33_2, {IMM32_HIGH8, FSM3, FSM2}},
{ "fsub", 0xfb640000, 0xffff0001, 0, FMT_D10,AM33_2, {FSN3, FSN2, FSN1}},
{ "fsub", 0xfbe40000, 0xffff1111, 0, FMT_D10,AM33_2, {FDN3, FDN2, FDN1}},
{ "fsub", 0xf96400, 0xfffc00, 0, FMT_D6, AM33_2, {FSM1, FSM0}},
{ "fsub", 0xf9e400, 0xfffc11, 0, FMT_D6, AM33_2, {FDM1, FDM0}},
{ "fsub", 0xfe640000, 0xfffc0000, 0, FMT_D9, AM33_2, {IMM32_HIGH8, FSM3, FSM2}},
{ "fmul", 0xfb700000, 0xffff0001, 0, FMT_D10,AM33_2, {FSN3, FSN2, FSN1}},
{ "fmul", 0xfbf00000, 0xffff1111, 0, FMT_D10,AM33_2, {FDN3, FDN2, FDN1}},
{ "fmul", 0xf97000, 0xfffc00, 0, FMT_D6, AM33_2, {FSM1, FSM0}},
{ "fmul", 0xf9f000, 0xfffc11, 0, FMT_D6, AM33_2, {FDM1, FDM0}},
{ "fmul", 0xfe700000, 0xfffc0000, 0, FMT_D9, AM33_2, {IMM32_HIGH8, FSM3, FSM2}},
{ "fdiv", 0xfb740000, 0xffff0001, 0, FMT_D10,AM33_2, {FSN3, FSN2, FSN1}},
{ "fdiv", 0xfbf40000, 0xffff1111, 0, FMT_D10,AM33_2, {FDN3, FDN2, FDN1}},
{ "fdiv", 0xf97400, 0xfffc00, 0, FMT_D6, AM33_2, {FSM1, FSM0}},
{ "fdiv", 0xf9f400, 0xfffc11, 0, FMT_D6, AM33_2, {FDM1, FDM0}},
{ "fdiv", 0xfe740000, 0xfffc0000, 0, FMT_D9, AM33_2, {IMM32_HIGH8, FSM3, FSM2}},
{ "fmadd", 0xfb800000, 0xfffc0000, 0, FMT_D10,AM33_2, {FSN3, FSN2, FSN1, FSACC}},
{ "fmsub", 0xfb840000, 0xfffc0000, 0, FMT_D10,AM33_2, {FSN3, FSN2, FSN1, FSACC}},
{ "fnmadd", 0xfb900000, 0xfffc0000, 0, FMT_D10,AM33_2, {FSN3, FSN2, FSN1, FSACC}},
{ "fnmsub", 0xfb940000, 0xfffc0000, 0, FMT_D10,AM33_2, {FSN3, FSN2, FSN1, FSACC}},
/* UDF instructions. */
{ "udf00", 0xf600, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "udf00", 0xf90000, 0xfffc00, 0, FMT_D1, 0, {SIMM8, DN0}},
{ "udf00", 0xfb000000, 0xfffc0000, 0, FMT_D2, 0, {SIMM16, DN0}},
{ "udf00", 0xfd000000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "udf01", 0xf610, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "udf01", 0xf91000, 0xfffc00, 0, FMT_D1, 0, {SIMM8, DN0}},
{ "udf01", 0xfb100000, 0xfffc0000, 0, FMT_D2, 0, {SIMM16, DN0}},
{ "udf01", 0xfd100000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "udf02", 0xf620, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "udf02", 0xf92000, 0xfffc00, 0, FMT_D1, 0, {SIMM8, DN0}},
{ "udf02", 0xfb200000, 0xfffc0000, 0, FMT_D2, 0, {SIMM16, DN0}},
{ "udf02", 0xfd200000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "udf03", 0xf630, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "udf03", 0xf93000, 0xfffc00, 0, FMT_D1, 0, {SIMM8, DN0}},
{ "udf03", 0xfb300000, 0xfffc0000, 0, FMT_D2, 0, {SIMM16, DN0}},
{ "udf03", 0xfd300000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "udf04", 0xf640, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "udf04", 0xf94000, 0xfffc00, 0, FMT_D1, 0, {SIMM8, DN0}},
{ "udf04", 0xfb400000, 0xfffc0000, 0, FMT_D2, 0, {SIMM16, DN0}},
{ "udf04", 0xfd400000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "udf05", 0xf650, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "udf05", 0xf95000, 0xfffc00, 0, FMT_D1, 0, {SIMM8, DN0}},
{ "udf05", 0xfb500000, 0xfffc0000, 0, FMT_D2, 0, {SIMM16, DN0}},
{ "udf05", 0xfd500000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "udf06", 0xf660, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "udf06", 0xf96000, 0xfffc00, 0, FMT_D1, 0, {SIMM8, DN0}},
{ "udf06", 0xfb600000, 0xfffc0000, 0, FMT_D2, 0, {SIMM16, DN0}},
{ "udf06", 0xfd600000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "udf07", 0xf670, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "udf07", 0xf97000, 0xfffc00, 0, FMT_D1, 0, {SIMM8, DN0}},
{ "udf07", 0xfb700000, 0xfffc0000, 0, FMT_D2, 0, {SIMM16, DN0}},
{ "udf07", 0xfd700000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "udf08", 0xf680, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "udf08", 0xf98000, 0xfffc00, 0, FMT_D1, 0, {SIMM8, DN0}},
{ "udf08", 0xfb800000, 0xfffc0000, 0, FMT_D2, 0, {SIMM16, DN0}},
{ "udf08", 0xfd800000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "udf09", 0xf690, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "udf09", 0xf99000, 0xfffc00, 0, FMT_D1, 0, {SIMM8, DN0}},
{ "udf09", 0xfb900000, 0xfffc0000, 0, FMT_D2, 0, {SIMM16, DN0}},
{ "udf09", 0xfd900000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "udf10", 0xf6a0, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "udf10", 0xf9a000, 0xfffc00, 0, FMT_D1, 0, {SIMM8, DN0}},
{ "udf10", 0xfba00000, 0xfffc0000, 0, FMT_D2, 0, {SIMM16, DN0}},
{ "udf10", 0xfda00000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "udf11", 0xf6b0, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "udf11", 0xf9b000, 0xfffc00, 0, FMT_D1, 0, {SIMM8, DN0}},
{ "udf11", 0xfbb00000, 0xfffc0000, 0, FMT_D2, 0, {SIMM16, DN0}},
{ "udf11", 0xfdb00000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "udf12", 0xf6c0, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "udf12", 0xf9c000, 0xfffc00, 0, FMT_D1, 0, {SIMM8, DN0}},
{ "udf12", 0xfbc00000, 0xfffc0000, 0, FMT_D2, 0, {SIMM16, DN0}},
{ "udf12", 0xfdc00000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "udf13", 0xf6d0, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "udf13", 0xf9d000, 0xfffc00, 0, FMT_D1, 0, {SIMM8, DN0}},
{ "udf13", 0xfbd00000, 0xfffc0000, 0, FMT_D2, 0, {SIMM16, DN0}},
{ "udf13", 0xfdd00000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "udf14", 0xf6e0, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "udf14", 0xf9e000, 0xfffc00, 0, FMT_D1, 0, {SIMM8, DN0}},
{ "udf14", 0xfbe00000, 0xfffc0000, 0, FMT_D2, 0, {SIMM16, DN0}},
{ "udf14", 0xfde00000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "udf15", 0xf6f0, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "udf15", 0xf9f000, 0xfffc00, 0, FMT_D1, 0, {SIMM8, DN0}},
{ "udf15", 0xfbf00000, 0xfffc0000, 0, FMT_D2, 0, {SIMM16, DN0}},
{ "udf15", 0xfdf00000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "udf20", 0xf500, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "udf21", 0xf510, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "udf22", 0xf520, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "udf23", 0xf530, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "udf24", 0xf540, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "udf25", 0xf550, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "udf26", 0xf560, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "udf27", 0xf570, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "udf28", 0xf580, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "udf29", 0xf590, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "udf30", 0xf5a0, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "udf31", 0xf5b0, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "udf32", 0xf5c0, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "udf33", 0xf5d0, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "udf34", 0xf5e0, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "udf35", 0xf5f0, 0xfff0, 0, FMT_D0, 0, {DM1, DN0}},
{ "udfu00", 0xf90400, 0xfffc00, 0, FMT_D1, 0, {IMM8, DN0}},
{ "udfu00", 0xfb040000, 0xfffc0000, 0, FMT_D2, 0, {IMM16, DN0}},
{ "udfu00", 0xfd040000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "udfu01", 0xf91400, 0xfffc00, 0, FMT_D1, 0, {IMM8, DN0}},
{ "udfu01", 0xfb140000, 0xfffc0000, 0, FMT_D2, 0, {IMM16, DN0}},
{ "udfu01", 0xfd140000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "udfu02", 0xf92400, 0xfffc00, 0, FMT_D1, 0, {IMM8, DN0}},
{ "udfu02", 0xfb240000, 0xfffc0000, 0, FMT_D2, 0, {IMM16, DN0}},
{ "udfu02", 0xfd240000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "udfu03", 0xf93400, 0xfffc00, 0, FMT_D1, 0, {IMM8, DN0}},
{ "udfu03", 0xfb340000, 0xfffc0000, 0, FMT_D2, 0, {IMM16, DN0}},
{ "udfu03", 0xfd340000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "udfu04", 0xf94400, 0xfffc00, 0, FMT_D1, 0, {IMM8, DN0}},
{ "udfu04", 0xfb440000, 0xfffc0000, 0, FMT_D2, 0, {IMM16, DN0}},
{ "udfu04", 0xfd440000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "udfu05", 0xf95400, 0xfffc00, 0, FMT_D1, 0, {IMM8, DN0}},
{ "udfu05", 0xfb540000, 0xfffc0000, 0, FMT_D2, 0, {IMM16, DN0}},
{ "udfu05", 0xfd540000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "udfu06", 0xf96400, 0xfffc00, 0, FMT_D1, 0, {IMM8, DN0}},
{ "udfu06", 0xfb640000, 0xfffc0000, 0, FMT_D2, 0, {IMM16, DN0}},
{ "udfu06", 0xfd640000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "udfu07", 0xf97400, 0xfffc00, 0, FMT_D1, 0, {IMM8, DN0}},
{ "udfu07", 0xfb740000, 0xfffc0000, 0, FMT_D2, 0, {IMM16, DN0}},
{ "udfu07", 0xfd740000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "udfu08", 0xf98400, 0xfffc00, 0, FMT_D1, 0, {IMM8, DN0}},
{ "udfu08", 0xfb840000, 0xfffc0000, 0, FMT_D2, 0, {IMM16, DN0}},
{ "udfu08", 0xfd840000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "udfu09", 0xf99400, 0xfffc00, 0, FMT_D1, 0, {IMM8, DN0}},
{ "udfu09", 0xfb940000, 0xfffc0000, 0, FMT_D2, 0, {IMM16, DN0}},
{ "udfu09", 0xfd940000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "udfu10", 0xf9a400, 0xfffc00, 0, FMT_D1, 0, {IMM8, DN0}},
{ "udfu10", 0xfba40000, 0xfffc0000, 0, FMT_D2, 0, {IMM16, DN0}},
{ "udfu10", 0xfda40000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "udfu11", 0xf9b400, 0xfffc00, 0, FMT_D1, 0, {IMM8, DN0}},
{ "udfu11", 0xfbb40000, 0xfffc0000, 0, FMT_D2, 0, {IMM16, DN0}},
{ "udfu11", 0xfdb40000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "udfu12", 0xf9c400, 0xfffc00, 0, FMT_D1, 0, {IMM8, DN0}},
{ "udfu12", 0xfbc40000, 0xfffc0000, 0, FMT_D2, 0, {IMM16, DN0}},
{ "udfu12", 0xfdc40000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "udfu13", 0xf9d400, 0xfffc00, 0, FMT_D1, 0, {IMM8, DN0}},
{ "udfu13", 0xfbd40000, 0xfffc0000, 0, FMT_D2, 0, {IMM16, DN0}},
{ "udfu13", 0xfdd40000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "udfu14", 0xf9e400, 0xfffc00, 0, FMT_D1, 0, {IMM8, DN0}},
{ "udfu14", 0xfbe40000, 0xfffc0000, 0, FMT_D2, 0, {IMM16, DN0}},
{ "udfu14", 0xfde40000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "udfu15", 0xf9f400, 0xfffc00, 0, FMT_D1, 0, {IMM8, DN0}},
{ "udfu15", 0xfbf40000, 0xfffc0000, 0, FMT_D2, 0, {IMM16, DN0}},
{ "udfu15", 0xfdf40000, 0xfffc0000, 0, FMT_D4, 0, {IMM32, DN0}},
{ "putx", 0xf500, 0xfff0, 0, FMT_D0, AM30, {DN01}},
{ "getx", 0xf6f0, 0xfff0, 0, FMT_D0, AM30, {DN01}},
{ "mulq", 0xf600, 0xfff0, 0, FMT_D0, AM30, {DM1, DN0}},
{ "mulq", 0xf90000, 0xfffc00, 0, FMT_D1, AM30, {SIMM8, DN0}},
{ "mulq", 0xfb000000, 0xfffc0000, 0, FMT_D2, AM30, {SIMM16, DN0}},
{ "mulq", 0xfd000000, 0xfffc0000, 0, FMT_D4, AM30, {IMM32, DN0}},
{ "mulqu", 0xf610, 0xfff0, 0, FMT_D0, AM30, {DM1, DN0}},
{ "mulqu", 0xf91400, 0xfffc00, 0, FMT_D1, AM30, {SIMM8, DN0}},
{ "mulqu", 0xfb140000, 0xfffc0000, 0, FMT_D2, AM30, {SIMM16, DN0}},
{ "mulqu", 0xfd140000, 0xfffc0000, 0, FMT_D4, AM30, {IMM32, DN0}},
{ "sat16", 0xf640, 0xfff0, 0, FMT_D0, AM30, {DM1, DN0}},
{ "sat16", 0xf9ab00, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
{ "sat24", 0xf650, 0xfff0, 0, FMT_D0, AM30, {DM1, DN0}},
{ "sat24", 0xfbaf0000, 0xffff00ff, 0, FMT_D7, AM33, {RM2, RN0}},
{ "bsch", 0xfbff0000, 0xffff000f, 0, FMT_D7, AM33, {RM2, RN0, RD2}},
{ "bsch", 0xf670, 0xfff0, 0, FMT_D0, AM30, {DM1, DN0}},
{ "bsch", 0xf9fb00, 0xffff00, 0, FMT_D6, AM33, {RM2, RN0}},
/* Extension. We need some instruction to trigger "emulated syscalls"
for our simulator. */
{ "syscall", 0xf0e0, 0xfff0, 0, FMT_D0, AM33, {IMM4}},
{ "syscall", 0xf0c0, 0xffff, 0, FMT_D0, 0, {UNUSED}},
/* Extension. When talking to the simulator, gdb requires some instruction
that will trigger a "breakpoint" (really just an instruction that isn't
otherwise used by the tools. This instruction must be the same size
as the smallest instruction on the target machine. In the case of the
mn10x00 the "break" instruction must be one byte. 0xff is available on
both mn10x00 architectures. */
{ "break", 0xff, 0xff, 0, FMT_S0, 0, {UNUSED}},
{ "add_add", 0xf7000000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "add_add", 0xf7100000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "add_add", 0xf7040000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, RM2, RN0}},
{ "add_add", 0xf7140000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, SIMM4_2, RN0}},
{ "add_sub", 0xf7200000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "add_sub", 0xf7300000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "add_sub", 0xf7240000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, RM2, RN0}},
{ "add_sub", 0xf7340000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, SIMM4_2, RN0}},
{ "add_cmp", 0xf7400000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "add_cmp", 0xf7500000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "add_cmp", 0xf7440000, 0xffff0000, 0x0, FMT_D10, AM33, {SIMM4_6, RN4, RM2, RN0}},
{ "add_cmp", 0xf7540000, 0xffff0000, 0x0, FMT_D10, AM33, {SIMM4_6, RN4, SIMM4_2, RN0}},
{ "add_mov", 0xf7600000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "add_mov", 0xf7700000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "add_mov", 0xf7640000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, RM2, RN0}},
{ "add_mov", 0xf7740000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, SIMM4_2, RN0}},
{ "add_asr", 0xf7800000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "add_asr", 0xf7900000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, IMM4_2, RN0}},
{ "add_asr", 0xf7840000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, RM2, RN0}},
{ "add_asr", 0xf7940000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, IMM4_2, RN0}},
{ "add_lsr", 0xf7a00000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "add_lsr", 0xf7b00000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, IMM4_2, RN0}},
{ "add_lsr", 0xf7a40000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, RM2, RN0}},
{ "add_lsr", 0xf7b40000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, IMM4_2, RN0}},
{ "add_asl", 0xf7c00000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "add_asl", 0xf7d00000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, IMM4_2, RN0}},
{ "add_asl", 0xf7c40000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, RM2, RN0}},
{ "add_asl", 0xf7d40000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, IMM4_2, RN0}},
{ "cmp_add", 0xf7010000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "cmp_add", 0xf7110000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "cmp_add", 0xf7050000, 0xffff0000, 0x0, FMT_D10, AM33, {SIMM4_6, RN4, RM2, RN0}},
{ "cmp_add", 0xf7150000, 0xffff0000, 0x0, FMT_D10, AM33, {SIMM4_6, RN4, SIMM4_2, RN0}},
{ "cmp_sub", 0xf7210000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "cmp_sub", 0xf7310000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "cmp_sub", 0xf7250000, 0xffff0000, 0x0, FMT_D10, AM33, {SIMM4_6, RN4, RM2, RN0}},
{ "cmp_sub", 0xf7350000, 0xffff0000, 0x0, FMT_D10, AM33, {SIMM4_6, RN4, SIMM4_2, RN0}},
{ "cmp_mov", 0xf7610000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "cmp_mov", 0xf7710000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "cmp_mov", 0xf7650000, 0xffff0000, 0x0, FMT_D10, AM33, {SIMM4_6, RN4, RM2, RN0}},
{ "cmp_mov", 0xf7750000, 0xffff0000, 0x0, FMT_D10, AM33, {SIMM4_6, RN4, SIMM4_2, RN0}},
{ "cmp_asr", 0xf7810000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "cmp_asr", 0xf7910000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, IMM4_2, RN0}},
{ "cmp_asr", 0xf7850000, 0xffff0000, 0x0, FMT_D10, AM33, {SIMM4_6, RN4, RM2, RN0}},
{ "cmp_asr", 0xf7950000, 0xffff0000, 0x0, FMT_D10, AM33, {SIMM4_6, RN4, IMM4_2, RN0}},
{ "cmp_lsr", 0xf7a10000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "cmp_lsr", 0xf7b10000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, IMM4_2, RN0}},
{ "cmp_lsr", 0xf7a50000, 0xffff0000, 0x0, FMT_D10, AM33, {SIMM4_6, RN4, RM2, RN0}},
{ "cmp_lsr", 0xf7b50000, 0xffff0000, 0x0, FMT_D10, AM33, {SIMM4_6, RN4, IMM4_2, RN0}},
{ "cmp_asl", 0xf7c10000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "cmp_asl", 0xf7d10000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, IMM4_2, RN0}},
{ "cmp_asl", 0xf7c50000, 0xffff0000, 0x0, FMT_D10, AM33, {SIMM4_6, RN4, RM2, RN0}},
{ "cmp_asl", 0xf7d50000, 0xffff0000, 0x0, FMT_D10, AM33, {SIMM4_6, RN4, IMM4_2, RN0}},
{ "sub_add", 0xf7020000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "sub_add", 0xf7120000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "sub_add", 0xf7060000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, RM2, RN0}},
{ "sub_add", 0xf7160000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, SIMM4_2, RN0}},
{ "sub_sub", 0xf7220000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "sub_sub", 0xf7320000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "sub_sub", 0xf7260000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, RM2, RN0}},
{ "sub_sub", 0xf7360000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, SIMM4_2, RN0}},
{ "sub_cmp", 0xf7420000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "sub_cmp", 0xf7520000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "sub_cmp", 0xf7460000, 0xffff0000, 0x0, FMT_D10, AM33, {SIMM4_6, RN4, RM2, RN0}},
{ "sub_cmp", 0xf7560000, 0xffff0000, 0x0, FMT_D10, AM33, {SIMM4_6, RN4, SIMM4_2, RN0}},
{ "sub_mov", 0xf7620000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "sub_mov", 0xf7720000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "sub_mov", 0xf7660000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, RM2, RN0}},
{ "sub_mov", 0xf7760000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, SIMM4_2, RN0}},
{ "sub_asr", 0xf7820000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "sub_asr", 0xf7920000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, IMM4_2, RN0}},
{ "sub_asr", 0xf7860000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, RM2, RN0}},
{ "sub_asr", 0xf7960000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, IMM4_2, RN0}},
{ "sub_lsr", 0xf7a20000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "sub_lsr", 0xf7b20000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, IMM4_2, RN0}},
{ "sub_lsr", 0xf7a60000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, RM2, RN0}},
{ "sub_lsr", 0xf7b60000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, IMM4_2, RN0}},
{ "sub_asl", 0xf7c20000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "sub_asl", 0xf7d20000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, IMM4_2, RN0}},
{ "sub_asl", 0xf7c60000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, RM2, RN0}},
{ "sub_asl", 0xf7d60000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, IMM4_2, RN0}},
{ "mov_add", 0xf7030000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "mov_add", 0xf7130000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "mov_add", 0xf7070000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, RM2, RN0}},
{ "mov_add", 0xf7170000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, SIMM4_2, RN0}},
{ "mov_sub", 0xf7230000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "mov_sub", 0xf7330000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "mov_sub", 0xf7270000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, RM2, RN0}},
{ "mov_sub", 0xf7370000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, SIMM4_2, RN0}},
{ "mov_cmp", 0xf7430000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "mov_cmp", 0xf7530000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "mov_cmp", 0xf7470000, 0xffff0000, 0x0, FMT_D10, AM33, {SIMM4_6, RN4, RM2, RN0}},
{ "mov_cmp", 0xf7570000, 0xffff0000, 0x0, FMT_D10, AM33, {SIMM4_6, RN4, SIMM4_2, RN0}},
{ "mov_mov", 0xf7630000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "mov_mov", 0xf7730000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "mov_mov", 0xf7670000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, RM2, RN0}},
{ "mov_mov", 0xf7770000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, SIMM4_2, RN0}},
{ "mov_asr", 0xf7830000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "mov_asr", 0xf7930000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, IMM4_2, RN0}},
{ "mov_asr", 0xf7870000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, RM2, RN0}},
{ "mov_asr", 0xf7970000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, IMM4_2, RN0}},
{ "mov_lsr", 0xf7a30000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "mov_lsr", 0xf7b30000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, IMM4_2, RN0}},
{ "mov_lsr", 0xf7a70000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, RM2, RN0}},
{ "mov_lsr", 0xf7b70000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, IMM4_2, RN0}},
{ "mov_asl", 0xf7c30000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "mov_asl", 0xf7d30000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, IMM4_2, RN0}},
{ "mov_asl", 0xf7c70000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, RM2, RN0}},
{ "mov_asl", 0xf7d70000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_6, RN4, IMM4_2, RN0}},
{ "and_add", 0xf7080000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "and_add", 0xf7180000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "and_sub", 0xf7280000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "and_sub", 0xf7380000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "and_cmp", 0xf7480000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "and_cmp", 0xf7580000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "and_mov", 0xf7680000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "and_mov", 0xf7780000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "and_asr", 0xf7880000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "and_asr", 0xf7980000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, IMM4_2, RN0}},
{ "and_lsr", 0xf7a80000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "and_lsr", 0xf7b80000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, IMM4_2, RN0}},
{ "and_asl", 0xf7c80000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "and_asl", 0xf7d80000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, IMM4_2, RN0}},
{ "dmach_add", 0xf7090000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "dmach_add", 0xf7190000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "dmach_sub", 0xf7290000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "dmach_sub", 0xf7390000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "dmach_cmp", 0xf7490000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "dmach_cmp", 0xf7590000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "dmach_mov", 0xf7690000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "dmach_mov", 0xf7790000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "dmach_asr", 0xf7890000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "dmach_asr", 0xf7990000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, IMM4_2, RN0}},
{ "dmach_lsr", 0xf7a90000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "dmach_lsr", 0xf7b90000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, IMM4_2, RN0}},
{ "dmach_asl", 0xf7c90000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "dmach_asl", 0xf7d90000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, IMM4_2, RN0}},
{ "xor_add", 0xf70a0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "xor_add", 0xf71a0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "xor_sub", 0xf72a0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "xor_sub", 0xf73a0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "xor_cmp", 0xf74a0000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "xor_cmp", 0xf75a0000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "xor_mov", 0xf76a0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "xor_mov", 0xf77a0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "xor_asr", 0xf78a0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "xor_asr", 0xf79a0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, IMM4_2, RN0}},
{ "xor_lsr", 0xf7aa0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "xor_lsr", 0xf7ba0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, IMM4_2, RN0}},
{ "xor_asl", 0xf7ca0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "xor_asl", 0xf7da0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, IMM4_2, RN0}},
{ "swhw_add", 0xf70b0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "swhw_add", 0xf71b0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "swhw_sub", 0xf72b0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "swhw_sub", 0xf73b0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "swhw_cmp", 0xf74b0000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "swhw_cmp", 0xf75b0000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "swhw_mov", 0xf76b0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "swhw_mov", 0xf77b0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "swhw_asr", 0xf78b0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "swhw_asr", 0xf79b0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, IMM4_2, RN0}},
{ "swhw_lsr", 0xf7ab0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "swhw_lsr", 0xf7bb0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, IMM4_2, RN0}},
{ "swhw_asl", 0xf7cb0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "swhw_asl", 0xf7db0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, IMM4_2, RN0}},
{ "or_add", 0xf70c0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "or_add", 0xf71c0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "or_sub", 0xf72c0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "or_sub", 0xf73c0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "or_cmp", 0xf74c0000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "or_cmp", 0xf75c0000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "or_mov", 0xf76c0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "or_mov", 0xf77c0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "or_asr", 0xf78c0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "or_asr", 0xf79c0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, IMM4_2, RN0}},
{ "or_lsr", 0xf7ac0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "or_lsr", 0xf7bc0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, IMM4_2, RN0}},
{ "or_asl", 0xf7cc0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "or_asl", 0xf7dc0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, IMM4_2, RN0}},
{ "sat16_add", 0xf70d0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "sat16_add", 0xf71d0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "sat16_sub", 0xf72d0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "sat16_sub", 0xf73d0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "sat16_cmp", 0xf74d0000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "sat16_cmp", 0xf75d0000, 0xffff0000, 0x0, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "sat16_mov", 0xf76d0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "sat16_mov", 0xf77d0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, SIMM4_2, RN0}},
{ "sat16_asr", 0xf78d0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "sat16_asr", 0xf79d0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, IMM4_2, RN0}},
{ "sat16_lsr", 0xf7ad0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "sat16_lsr", 0xf7bd0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, IMM4_2, RN0}},
{ "sat16_asl", 0xf7cd0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, RM2, RN0}},
{ "sat16_asl", 0xf7dd0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM6, RN4, IMM4_2, RN0}},
/* Ugh. Synthetic instructions. */
{ "add_and", 0xf7080000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "add_and", 0xf7180000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_2, RN0, RM6, RN4}},
{ "add_dmach", 0xf7090000, 0xffff0000, 0x0, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "add_dmach", 0xf7190000, 0xffff0000, 0x0, FMT_D10, AM33, {SIMM4_2, RN0, RM6, RN4}},
{ "add_or", 0xf70c0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "add_or", 0xf71c0000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_2, RN0, RM6, RN4}},
{ "add_sat16", 0xf70d0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "add_sat16", 0xf71d0000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_2, RN0, RM6, RN4}},
{ "add_swhw", 0xf70b0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "add_swhw", 0xf71b0000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_2, RN0, RM6, RN4}},
{ "add_xor", 0xf70a0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "add_xor", 0xf71a0000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_2, RN0, RM6, RN4}},
{ "asl_add", 0xf7c00000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "asl_add", 0xf7d00000, 0xffff0000, 0xa, FMT_D10, AM33, {IMM4_2, RN0, RM6, RN4}},
{ "asl_add", 0xf7c40000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, SIMM4_6, RN4}},
{ "asl_add", 0xf7d40000, 0xffff0000, 0xa, FMT_D10, AM33, {IMM4_2, RN0, SIMM4_6, RN4}},
{ "asl_and", 0xf7c80000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "asl_and", 0xf7d80000, 0xffff0000, 0xa, FMT_D10, AM33, {IMM4_2, RN0, RM6, RN4}},
{ "asl_cmp", 0xf7c10000, 0xffff0000, 0x0, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "asl_cmp", 0xf7d10000, 0xffff0000, 0x0, FMT_D10, AM33, {IMM4_2, RN0, RM6, RN4, }},
{ "asl_cmp", 0xf7c50000, 0xffff0000, 0x0, FMT_D10, AM33, {RM2, RN0, SIMM4_6, RN4}},
{ "asl_cmp", 0xf7d50000, 0xffff0000, 0x0, FMT_D10, AM33, {IMM4_2, RN0, SIMM4_6, RN4}},
{ "asl_dmach", 0xf7c90000, 0xffff0000, 0x0, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "asl_dmach", 0xf7d90000, 0xffff0000, 0x0, FMT_D10, AM33, {IMM4_2, RN0, RM6, RN4}},
{ "asl_mov", 0xf7c30000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "asl_mov", 0xf7d30000, 0xffff0000, 0xa, FMT_D10, AM33, {IMM4_2, RN0, RM6, RN4}},
{ "asl_mov", 0xf7c70000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, SIMM4_6, RN4}},
{ "asl_mov", 0xf7d70000, 0xffff0000, 0xa, FMT_D10, AM33, {IMM4_2, RN0, SIMM4_6, RN4}},
{ "asl_or", 0xf7cc0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "asl_or", 0xf7dc0000, 0xffff0000, 0xa, FMT_D10, AM33, {IMM4_2, RN0, RM6, RN4}},
{ "asl_sat16", 0xf7cd0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "asl_sat16", 0xf7dd0000, 0xffff0000, 0xa, FMT_D10, AM33, {IMM4_2, RN0, RM6, RN4}},
{ "asl_sub", 0xf7c20000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "asl_sub", 0xf7d20000, 0xffff0000, 0xa, FMT_D10, AM33, {IMM4_2, RN0, RM6, RN4}},
{ "asl_sub", 0xf7c60000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, SIMM4_6, RN4}},
{ "asl_sub", 0xf7d60000, 0xffff0000, 0xa, FMT_D10, AM33, {IMM4_2, RN0, SIMM4_6, RN4}},
{ "asl_swhw", 0xf7cb0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "asl_swhw", 0xf7db0000, 0xffff0000, 0xa, FMT_D10, AM33, {IMM4_2, RN0, RM6, RN4}},
{ "asl_xor", 0xf7ca0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "asl_xor", 0xf7da0000, 0xffff0000, 0xa, FMT_D10, AM33, {IMM4_2, RN0, RM6, RN4}},
{ "asr_add", 0xf7800000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "asr_add", 0xf7900000, 0xffff0000, 0xa, FMT_D10, AM33, {IMM4_2, RN0, RM6, RN4}},
{ "asr_add", 0xf7840000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, SIMM4_6, RN4}},
{ "asr_add", 0xf7940000, 0xffff0000, 0xa, FMT_D10, AM33, {IMM4_2, RN0, SIMM4_6, RN4}},
{ "asr_and", 0xf7880000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "asr_and", 0xf7980000, 0xffff0000, 0xa, FMT_D10, AM33, {IMM4_2, RN0, RM6, RN4}},
{ "asr_cmp", 0xf7810000, 0xffff0000, 0x0, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "asr_cmp", 0xf7910000, 0xffff0000, 0x0, FMT_D10, AM33, {IMM4_2, RN0, RM6, RN4, }},
{ "asr_cmp", 0xf7850000, 0xffff0000, 0x0, FMT_D10, AM33, {RM2, RN0, SIMM4_6, RN4}},
{ "asr_cmp", 0xf7950000, 0xffff0000, 0x0, FMT_D10, AM33, {IMM4_2, RN0, SIMM4_6, RN4}},
{ "asr_dmach", 0xf7890000, 0xffff0000, 0x0, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "asr_dmach", 0xf7990000, 0xffff0000, 0x0, FMT_D10, AM33, {IMM4_2, RN0, RM6, RN4}},
{ "asr_mov", 0xf7830000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "asr_mov", 0xf7930000, 0xffff0000, 0xa, FMT_D10, AM33, {IMM4_2, RN0, RM6, RN4}},
{ "asr_mov", 0xf7870000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, SIMM4_6, RN4}},
{ "asr_mov", 0xf7970000, 0xffff0000, 0xa, FMT_D10, AM33, {IMM4_2, RN0, SIMM4_6, RN4}},
{ "asr_or", 0xf78c0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "asr_or", 0xf79c0000, 0xffff0000, 0xa, FMT_D10, AM33, {IMM4_2, RN0, RM6, RN4}},
{ "asr_sat16", 0xf78d0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "asr_sat16", 0xf79d0000, 0xffff0000, 0xa, FMT_D10, AM33, {IMM4_2, RN0, RM6, RN4}},
{ "asr_sub", 0xf7820000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "asr_sub", 0xf7920000, 0xffff0000, 0xa, FMT_D10, AM33, {IMM4_2, RN0, RM6, RN4}},
{ "asr_sub", 0xf7860000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, SIMM4_6, RN4}},
{ "asr_sub", 0xf7960000, 0xffff0000, 0xa, FMT_D10, AM33, {IMM4_2, RN0, SIMM4_6, RN4}},
{ "asr_swhw", 0xf78b0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "asr_swhw", 0xf79b0000, 0xffff0000, 0xa, FMT_D10, AM33, {IMM4_2, RN0, RM6, RN4}},
{ "asr_xor", 0xf78a0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "asr_xor", 0xf79a0000, 0xffff0000, 0xa, FMT_D10, AM33, {IMM4_2, RN0, RM6, RN4}},
{ "cmp_and", 0xf7480000, 0xffff0000, 0x0, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "cmp_and", 0xf7580000, 0xffff0000, 0x0, FMT_D10, AM33, {SIMM4_2, RN0, RM6, RN4}},
{ "cmp_dmach", 0xf7490000, 0xffff0000, 0x0, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "cmp_dmach", 0xf7590000, 0xffff0000, 0x0, FMT_D10, AM33, {SIMM4_2, RN0, RM6, RN4}},
{ "cmp_or", 0xf74c0000, 0xffff0000, 0x0, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "cmp_or", 0xf75c0000, 0xffff0000, 0x0, FMT_D10, AM33, {SIMM4_2, RN0, RM6, RN4}},
{ "cmp_sat16", 0xf74d0000, 0xffff0000, 0x0, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "cmp_sat16", 0xf75d0000, 0xffff0000, 0x0, FMT_D10, AM33, {SIMM4_2, RN0, RM6, RN4}},
{ "cmp_swhw", 0xf74b0000, 0xffff0000, 0x0, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "cmp_swhw", 0xf75b0000, 0xffff0000, 0x0, FMT_D10, AM33, {SIMM4_2, RN0, RM6, RN4}},
{ "cmp_xor", 0xf74a0000, 0xffff0000, 0x0, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "cmp_xor", 0xf75a0000, 0xffff0000, 0x0, FMT_D10, AM33, {SIMM4_2, RN0, RM6, RN4}},
{ "lsr_add", 0xf7a00000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "lsr_add", 0xf7b00000, 0xffff0000, 0xa, FMT_D10, AM33, {IMM4_2, RN0, RM6, RN4}},
{ "lsr_add", 0xf7a40000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, SIMM4_6, RN4}},
{ "lsr_add", 0xf7b40000, 0xffff0000, 0xa, FMT_D10, AM33, {IMM4_2, RN0, SIMM4_6, RN4}},
{ "lsr_and", 0xf7a80000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "lsr_and", 0xf7b80000, 0xffff0000, 0xa, FMT_D10, AM33, {IMM4_2, RN0, RM6, RN4}},
{ "lsr_cmp", 0xf7a10000, 0xffff0000, 0x0, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "lsr_cmp", 0xf7b10000, 0xffff0000, 0x0, FMT_D10, AM33, {IMM4_2, RN0, RM6, RN4, }},
{ "lsr_cmp", 0xf7a50000, 0xffff0000, 0x0, FMT_D10, AM33, {RM2, RN0, SIMM4_6, RN4}},
{ "lsr_cmp", 0xf7b50000, 0xffff0000, 0x0, FMT_D10, AM33, {IMM4_2, RN0, SIMM4_6, RN4}},
{ "lsr_dmach", 0xf7a90000, 0xffff0000, 0x0, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "lsr_dmach", 0xf7b90000, 0xffff0000, 0x0, FMT_D10, AM33, {IMM4_2, RN0, RM6, RN4}},
{ "lsr_mov", 0xf7a30000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "lsr_mov", 0xf7b30000, 0xffff0000, 0xa, FMT_D10, AM33, {IMM4_2, RN0, RM6, RN4}},
{ "lsr_mov", 0xf7a70000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, SIMM4_6, RN4}},
{ "lsr_mov", 0xf7b70000, 0xffff0000, 0xa, FMT_D10, AM33, {IMM4_2, RN0, SIMM4_6, RN4}},
{ "lsr_or", 0xf7ac0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "lsr_or", 0xf7bc0000, 0xffff0000, 0xa, FMT_D10, AM33, {IMM4_2, RN0, RM6, RN4}},
{ "lsr_sat16", 0xf7ad0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "lsr_sat16", 0xf7bd0000, 0xffff0000, 0xa, FMT_D10, AM33, {IMM4_2, RN0, RM6, RN4}},
{ "lsr_sub", 0xf7a20000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "lsr_sub", 0xf7b20000, 0xffff0000, 0xa, FMT_D10, AM33, {IMM4_2, RN0, RM6, RN4}},
{ "lsr_sub", 0xf7a60000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, SIMM4_6, RN4}},
{ "lsr_sub", 0xf7b60000, 0xffff0000, 0xa, FMT_D10, AM33, {IMM4_2, RN0, SIMM4_6, RN4}},
{ "lsr_swhw", 0xf7ab0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "lsr_swhw", 0xf7bb0000, 0xffff0000, 0xa, FMT_D10, AM33, {IMM4_2, RN0, RM6, RN4}},
{ "lsr_xor", 0xf7aa0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "lsr_xor", 0xf7ba0000, 0xffff0000, 0xa, FMT_D10, AM33, {IMM4_2, RN0, RM6, RN4}},
{ "mov_and", 0xf7680000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "mov_and", 0xf7780000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_2, RN0, RM6, RN4}},
{ "mov_dmach", 0xf7690000, 0xffff0000, 0x0, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "mov_dmach", 0xf7790000, 0xffff0000, 0x0, FMT_D10, AM33, {SIMM4_2, RN0, RM6, RN4}},
{ "mov_or", 0xf76c0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "mov_or", 0xf77c0000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_2, RN0, RM6, RN4}},
{ "mov_sat16", 0xf76d0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "mov_sat16", 0xf77d0000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_2, RN0, RM6, RN4}},
{ "mov_swhw", 0xf76b0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "mov_swhw", 0xf77b0000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_2, RN0, RM6, RN4}},
{ "mov_xor", 0xf76a0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "mov_xor", 0xf77a0000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_2, RN0, RM6, RN4}},
{ "sub_and", 0xf7280000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "sub_and", 0xf7380000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_2, RN0, RM6, RN4}},
{ "sub_dmach", 0xf7290000, 0xffff0000, 0x0, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "sub_dmach", 0xf7390000, 0xffff0000, 0x0, FMT_D10, AM33, {SIMM4_2, RN0, RM6, RN4}},
{ "sub_or", 0xf72c0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "sub_or", 0xf73c0000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_2, RN0, RM6, RN4}},
{ "sub_sat16", 0xf72d0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "sub_sat16", 0xf73d0000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_2, RN0, RM6, RN4}},
{ "sub_swhw", 0xf72b0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "sub_swhw", 0xf73b0000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_2, RN0, RM6, RN4}},
{ "sub_xor", 0xf72a0000, 0xffff0000, 0xa, FMT_D10, AM33, {RM2, RN0, RM6, RN4}},
{ "sub_xor", 0xf73a0000, 0xffff0000, 0xa, FMT_D10, AM33, {SIMM4_2, RN0, RM6, RN4}},
{ "mov_llt", 0xf7e00000, 0xffff000f, 0x22, FMT_D10, AM33, {MEMINC2 (RN4,SIMM4_2), RM6}},
{ "mov_lgt", 0xf7e00001, 0xffff000f, 0x22, FMT_D10, AM33, {MEMINC2 (RN4,SIMM4_2), RM6}},
{ "mov_lge", 0xf7e00002, 0xffff000f, 0x22, FMT_D10, AM33, {MEMINC2 (RN4,SIMM4_2), RM6}},
{ "mov_lle", 0xf7e00003, 0xffff000f, 0x22, FMT_D10, AM33, {MEMINC2 (RN4,SIMM4_2), RM6}},
{ "mov_lcs", 0xf7e00004, 0xffff000f, 0x22, FMT_D10, AM33, {MEMINC2 (RN4,SIMM4_2), RM6}},
{ "mov_lhi", 0xf7e00005, 0xffff000f, 0x22, FMT_D10, AM33, {MEMINC2 (RN4,SIMM4_2), RM6}},
{ "mov_lcc", 0xf7e00006, 0xffff000f, 0x22, FMT_D10, AM33, {MEMINC2 (RN4,SIMM4_2), RM6}},
{ "mov_lls", 0xf7e00007, 0xffff000f, 0x22, FMT_D10, AM33, {MEMINC2 (RN4,SIMM4_2), RM6}},
{ "mov_leq", 0xf7e00008, 0xffff000f, 0x22, FMT_D10, AM33, {MEMINC2 (RN4,SIMM4_2), RM6}},
{ "mov_lne", 0xf7e00009, 0xffff000f, 0x22, FMT_D10, AM33, {MEMINC2 (RN4,SIMM4_2), RM6}},
{ "mov_lra", 0xf7e0000a, 0xffff000f, 0x22, FMT_D10, AM33, {MEMINC2 (RN4,SIMM4_2), RM6}},
{ "llt_mov", 0xf7e00000, 0xffff000f, 0x22, FMT_D10, AM33, {MEMINC2 (RN4,SIMM4_2), RM6}},
{ "lgt_mov", 0xf7e00001, 0xffff000f, 0x22, FMT_D10, AM33, {MEMINC2 (RN4,SIMM4_2), RM6}},
{ "lge_mov", 0xf7e00002, 0xffff000f, 0x22, FMT_D10, AM33, {MEMINC2 (RN4,SIMM4_2), RM6}},
{ "lle_mov", 0xf7e00003, 0xffff000f, 0x22, FMT_D10, AM33, {MEMINC2 (RN4,SIMM4_2), RM6}},
{ "lcs_mov", 0xf7e00004, 0xffff000f, 0x22, FMT_D10, AM33, {MEMINC2 (RN4,SIMM4_2), RM6}},
{ "lhi_mov", 0xf7e00005, 0xffff000f, 0x22, FMT_D10, AM33, {MEMINC2 (RN4,SIMM4_2), RM6}},
{ "lcc_mov", 0xf7e00006, 0xffff000f, 0x22, FMT_D10, AM33, {MEMINC2 (RN4,SIMM4_2), RM6}},
{ "lls_mov", 0xf7e00007, 0xffff000f, 0x22, FMT_D10, AM33, {MEMINC2 (RN4,SIMM4_2), RM6}},
{ "leq_mov", 0xf7e00008, 0xffff000f, 0x22, FMT_D10, AM33, {MEMINC2 (RN4,SIMM4_2), RM6}},
{ "lne_mov", 0xf7e00009, 0xffff000f, 0x22, FMT_D10, AM33, {MEMINC2 (RN4,SIMM4_2), RM6}},
{ "lra_mov", 0xf7e0000a, 0xffff000f, 0x22, FMT_D10, AM33, {MEMINC2 (RN4,SIMM4_2), RM6}},
{ 0, 0, 0, 0, 0, 0, {0}},
} ;
const int mn10300_num_opcodes =
sizeof (mn10300_opcodes) / sizeof (mn10300_opcodes[0]);
| gpl-2.0 |
lmajewski/linux-samsung-devel | drivers/gpu/drm/omapdrm/omap_fb.c | 681 | 13406 | /*
* drivers/gpu/drm/omapdrm/omap_fb.c
*
* Copyright (C) 2011 Texas Instruments
* Author: Rob Clark <rob@ti.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "omap_drv.h"
#include "omap_dmm_tiler.h"
#include "drm_crtc.h"
#include "drm_crtc_helper.h"
/*
* framebuffer funcs
*/
/* per-format info: */
struct format {
enum omap_color_mode dss_format;
uint32_t pixel_format;
struct {
int stride_bpp; /* this times width is stride */
int sub_y; /* sub-sample in y dimension */
} planes[4];
bool yuv;
};
static const struct format formats[] = {
/* 16bpp [A]RGB: */
{ OMAP_DSS_COLOR_RGB16, DRM_FORMAT_RGB565, {{2, 1}}, false }, /* RGB16-565 */
{ OMAP_DSS_COLOR_RGB12U, DRM_FORMAT_RGBX4444, {{2, 1}}, false }, /* RGB12x-4444 */
{ OMAP_DSS_COLOR_RGBX16, DRM_FORMAT_XRGB4444, {{2, 1}}, false }, /* xRGB12-4444 */
{ OMAP_DSS_COLOR_RGBA16, DRM_FORMAT_RGBA4444, {{2, 1}}, false }, /* RGBA12-4444 */
{ OMAP_DSS_COLOR_ARGB16, DRM_FORMAT_ARGB4444, {{2, 1}}, false }, /* ARGB16-4444 */
{ OMAP_DSS_COLOR_XRGB16_1555, DRM_FORMAT_XRGB1555, {{2, 1}}, false }, /* xRGB15-1555 */
{ OMAP_DSS_COLOR_ARGB16_1555, DRM_FORMAT_ARGB1555, {{2, 1}}, false }, /* ARGB16-1555 */
/* 24bpp RGB: */
{ OMAP_DSS_COLOR_RGB24P, DRM_FORMAT_RGB888, {{3, 1}}, false }, /* RGB24-888 */
/* 32bpp [A]RGB: */
{ OMAP_DSS_COLOR_RGBX32, DRM_FORMAT_RGBX8888, {{4, 1}}, false }, /* RGBx24-8888 */
{ OMAP_DSS_COLOR_RGB24U, DRM_FORMAT_XRGB8888, {{4, 1}}, false }, /* xRGB24-8888 */
{ OMAP_DSS_COLOR_RGBA32, DRM_FORMAT_RGBA8888, {{4, 1}}, false }, /* RGBA32-8888 */
{ OMAP_DSS_COLOR_ARGB32, DRM_FORMAT_ARGB8888, {{4, 1}}, false }, /* ARGB32-8888 */
/* YUV: */
{ OMAP_DSS_COLOR_NV12, DRM_FORMAT_NV12, {{1, 1}, {1, 2}}, true },
{ OMAP_DSS_COLOR_YUV2, DRM_FORMAT_YUYV, {{2, 1}}, true },
{ OMAP_DSS_COLOR_UYVY, DRM_FORMAT_UYVY, {{2, 1}}, true },
};
/* convert from overlay's pixel formats bitmask to an array of fourcc's */
uint32_t omap_framebuffer_get_formats(uint32_t *pixel_formats,
uint32_t max_formats, enum omap_color_mode supported_modes)
{
uint32_t nformats = 0;
int i = 0;
for (i = 0; i < ARRAY_SIZE(formats) && nformats < max_formats; i++)
if (formats[i].dss_format & supported_modes)
pixel_formats[nformats++] = formats[i].pixel_format;
return nformats;
}
/* per-plane info for the fb: */
struct plane {
struct drm_gem_object *bo;
uint32_t pitch;
uint32_t offset;
dma_addr_t paddr;
};
#define to_omap_framebuffer(x) container_of(x, struct omap_framebuffer, base)
struct omap_framebuffer {
struct drm_framebuffer base;
const struct format *format;
struct plane planes[4];
};
static int omap_framebuffer_create_handle(struct drm_framebuffer *fb,
struct drm_file *file_priv,
unsigned int *handle)
{
struct omap_framebuffer *omap_fb = to_omap_framebuffer(fb);
return drm_gem_handle_create(file_priv,
omap_fb->planes[0].bo, handle);
}
static void omap_framebuffer_destroy(struct drm_framebuffer *fb)
{
struct omap_framebuffer *omap_fb = to_omap_framebuffer(fb);
int i, n = drm_format_num_planes(fb->pixel_format);
DBG("destroy: FB ID: %d (%p)", fb->base.id, fb);
drm_framebuffer_cleanup(fb);
for (i = 0; i < n; i++) {
struct plane *plane = &omap_fb->planes[i];
if (plane->bo)
drm_gem_object_unreference_unlocked(plane->bo);
}
kfree(omap_fb);
}
static int omap_framebuffer_dirty(struct drm_framebuffer *fb,
struct drm_file *file_priv, unsigned flags, unsigned color,
struct drm_clip_rect *clips, unsigned num_clips)
{
int i;
drm_modeset_lock_all(fb->dev);
for (i = 0; i < num_clips; i++) {
omap_framebuffer_flush(fb, clips[i].x1, clips[i].y1,
clips[i].x2 - clips[i].x1,
clips[i].y2 - clips[i].y1);
}
drm_modeset_unlock_all(fb->dev);
return 0;
}
static const struct drm_framebuffer_funcs omap_framebuffer_funcs = {
.create_handle = omap_framebuffer_create_handle,
.destroy = omap_framebuffer_destroy,
.dirty = omap_framebuffer_dirty,
};
static uint32_t get_linear_addr(struct plane *plane,
const struct format *format, int n, int x, int y)
{
uint32_t offset;
offset = plane->offset +
(x * format->planes[n].stride_bpp) +
(y * plane->pitch / format->planes[n].sub_y);
return plane->paddr + offset;
}
/* update ovl info for scanout, handles cases of multi-planar fb's, etc.
*/
void omap_framebuffer_update_scanout(struct drm_framebuffer *fb,
struct omap_drm_window *win, struct omap_overlay_info *info)
{
struct omap_framebuffer *omap_fb = to_omap_framebuffer(fb);
const struct format *format = omap_fb->format;
struct plane *plane = &omap_fb->planes[0];
uint32_t x, y, orient = 0;
info->color_mode = format->dss_format;
info->pos_x = win->crtc_x;
info->pos_y = win->crtc_y;
info->out_width = win->crtc_w;
info->out_height = win->crtc_h;
info->width = win->src_w;
info->height = win->src_h;
x = win->src_x;
y = win->src_y;
if (omap_gem_flags(plane->bo) & OMAP_BO_TILED) {
uint32_t w = win->src_w;
uint32_t h = win->src_h;
switch (win->rotation & 0xf) {
default:
dev_err(fb->dev->dev, "invalid rotation: %02x",
(uint32_t)win->rotation);
/* fallthru to default to no rotation */
case 0:
case BIT(DRM_ROTATE_0):
orient = 0;
break;
case BIT(DRM_ROTATE_90):
orient = MASK_XY_FLIP | MASK_X_INVERT;
break;
case BIT(DRM_ROTATE_180):
orient = MASK_X_INVERT | MASK_Y_INVERT;
break;
case BIT(DRM_ROTATE_270):
orient = MASK_XY_FLIP | MASK_Y_INVERT;
break;
}
if (win->rotation & BIT(DRM_REFLECT_X))
orient ^= MASK_X_INVERT;
if (win->rotation & BIT(DRM_REFLECT_Y))
orient ^= MASK_Y_INVERT;
/* adjust x,y offset for flip/invert: */
if (orient & MASK_XY_FLIP)
swap(w, h);
if (orient & MASK_Y_INVERT)
y += h - 1;
if (orient & MASK_X_INVERT)
x += w - 1;
omap_gem_rotated_paddr(plane->bo, orient, x, y, &info->paddr);
info->rotation_type = OMAP_DSS_ROT_TILER;
info->screen_width = omap_gem_tiled_stride(plane->bo, orient);
} else {
switch (win->rotation & 0xf) {
case 0:
case BIT(DRM_ROTATE_0):
/* OK */
break;
default:
dev_warn(fb->dev->dev,
"rotation '%d' ignored for non-tiled fb\n",
win->rotation);
win->rotation = 0;
break;
}
info->paddr = get_linear_addr(plane, format, 0, x, y);
info->rotation_type = OMAP_DSS_ROT_DMA;
info->screen_width = plane->pitch;
}
/* convert to pixels: */
info->screen_width /= format->planes[0].stride_bpp;
if (format->dss_format == OMAP_DSS_COLOR_NV12) {
plane = &omap_fb->planes[1];
if (info->rotation_type == OMAP_DSS_ROT_TILER) {
WARN_ON(!(omap_gem_flags(plane->bo) & OMAP_BO_TILED));
omap_gem_rotated_paddr(plane->bo, orient,
x/2, y/2, &info->p_uv_addr);
} else {
info->p_uv_addr = get_linear_addr(plane, format, 1, x, y);
}
} else {
info->p_uv_addr = 0;
}
}
/* pin, prepare for scanout: */
int omap_framebuffer_pin(struct drm_framebuffer *fb)
{
struct omap_framebuffer *omap_fb = to_omap_framebuffer(fb);
int ret, i, n = drm_format_num_planes(fb->pixel_format);
for (i = 0; i < n; i++) {
struct plane *plane = &omap_fb->planes[i];
ret = omap_gem_get_paddr(plane->bo, &plane->paddr, true);
if (ret)
goto fail;
omap_gem_dma_sync(plane->bo, DMA_TO_DEVICE);
}
return 0;
fail:
for (i--; i >= 0; i--) {
struct plane *plane = &omap_fb->planes[i];
omap_gem_put_paddr(plane->bo);
plane->paddr = 0;
}
return ret;
}
/* unpin, no longer being scanned out: */
int omap_framebuffer_unpin(struct drm_framebuffer *fb)
{
struct omap_framebuffer *omap_fb = to_omap_framebuffer(fb);
int ret, i, n = drm_format_num_planes(fb->pixel_format);
for (i = 0; i < n; i++) {
struct plane *plane = &omap_fb->planes[i];
ret = omap_gem_put_paddr(plane->bo);
if (ret)
goto fail;
plane->paddr = 0;
}
return 0;
fail:
return ret;
}
struct drm_gem_object *omap_framebuffer_bo(struct drm_framebuffer *fb, int p)
{
struct omap_framebuffer *omap_fb = to_omap_framebuffer(fb);
if (p >= drm_format_num_planes(fb->pixel_format))
return NULL;
return omap_fb->planes[p].bo;
}
/* iterate thru all the connectors, returning ones that are attached
* to the same fb..
*/
struct drm_connector *omap_framebuffer_get_next_connector(
struct drm_framebuffer *fb, struct drm_connector *from)
{
struct drm_device *dev = fb->dev;
struct list_head *connector_list = &dev->mode_config.connector_list;
struct drm_connector *connector = from;
if (!from)
return list_first_entry_or_null(connector_list, typeof(*from),
head);
list_for_each_entry_from(connector, connector_list, head) {
if (connector != from) {
struct drm_encoder *encoder = connector->encoder;
struct drm_crtc *crtc = encoder ? encoder->crtc : NULL;
if (crtc && crtc->primary->fb == fb)
return connector;
}
}
return NULL;
}
/* flush an area of the framebuffer (in case of manual update display that
* is not automatically flushed)
*/
void omap_framebuffer_flush(struct drm_framebuffer *fb,
int x, int y, int w, int h)
{
struct drm_connector *connector = NULL;
VERB("flush: %d,%d %dx%d, fb=%p", x, y, w, h, fb);
/* FIXME: This is racy - no protection against modeset config changes. */
while ((connector = omap_framebuffer_get_next_connector(fb, connector))) {
/* only consider connectors that are part of a chain */
if (connector->encoder && connector->encoder->crtc) {
/* TODO: maybe this should propagate thru the crtc who
* could do the coordinate translation..
*/
struct drm_crtc *crtc = connector->encoder->crtc;
int cx = max(0, x - crtc->x);
int cy = max(0, y - crtc->y);
int cw = w + (x - crtc->x) - cx;
int ch = h + (y - crtc->y) - cy;
omap_connector_flush(connector, cx, cy, cw, ch);
}
}
}
#ifdef CONFIG_DEBUG_FS
void omap_framebuffer_describe(struct drm_framebuffer *fb, struct seq_file *m)
{
struct omap_framebuffer *omap_fb = to_omap_framebuffer(fb);
int i, n = drm_format_num_planes(fb->pixel_format);
seq_printf(m, "fb: %dx%d@%4.4s\n", fb->width, fb->height,
(char *)&fb->pixel_format);
for (i = 0; i < n; i++) {
struct plane *plane = &omap_fb->planes[i];
seq_printf(m, " %d: offset=%d pitch=%d, obj: ",
i, plane->offset, plane->pitch);
omap_gem_describe(plane->bo, m);
}
}
#endif
struct drm_framebuffer *omap_framebuffer_create(struct drm_device *dev,
struct drm_file *file, struct drm_mode_fb_cmd2 *mode_cmd)
{
struct drm_gem_object *bos[4];
struct drm_framebuffer *fb;
int ret;
ret = objects_lookup(dev, file, mode_cmd->pixel_format,
bos, mode_cmd->handles);
if (ret)
return ERR_PTR(ret);
fb = omap_framebuffer_init(dev, mode_cmd, bos);
if (IS_ERR(fb)) {
int i, n = drm_format_num_planes(mode_cmd->pixel_format);
for (i = 0; i < n; i++)
drm_gem_object_unreference_unlocked(bos[i]);
return fb;
}
return fb;
}
struct drm_framebuffer *omap_framebuffer_init(struct drm_device *dev,
struct drm_mode_fb_cmd2 *mode_cmd, struct drm_gem_object **bos)
{
struct omap_framebuffer *omap_fb;
struct drm_framebuffer *fb = NULL;
const struct format *format = NULL;
int ret, i, n = drm_format_num_planes(mode_cmd->pixel_format);
DBG("create framebuffer: dev=%p, mode_cmd=%p (%dx%d@%4.4s)",
dev, mode_cmd, mode_cmd->width, mode_cmd->height,
(char *)&mode_cmd->pixel_format);
for (i = 0; i < ARRAY_SIZE(formats); i++) {
if (formats[i].pixel_format == mode_cmd->pixel_format) {
format = &formats[i];
break;
}
}
if (!format) {
dev_err(dev->dev, "unsupported pixel format: %4.4s\n",
(char *)&mode_cmd->pixel_format);
ret = -EINVAL;
goto fail;
}
omap_fb = kzalloc(sizeof(*omap_fb), GFP_KERNEL);
if (!omap_fb) {
ret = -ENOMEM;
goto fail;
}
fb = &omap_fb->base;
omap_fb->format = format;
for (i = 0; i < n; i++) {
struct plane *plane = &omap_fb->planes[i];
int size, pitch = mode_cmd->pitches[i];
if (pitch < (mode_cmd->width * format->planes[i].stride_bpp)) {
dev_err(dev->dev, "provided buffer pitch is too small! %d < %d\n",
pitch, mode_cmd->width * format->planes[i].stride_bpp);
ret = -EINVAL;
goto fail;
}
size = pitch * mode_cmd->height / format->planes[i].sub_y;
if (size > (omap_gem_mmap_size(bos[i]) - mode_cmd->offsets[i])) {
dev_err(dev->dev, "provided buffer object is too small! %d < %d\n",
bos[i]->size - mode_cmd->offsets[i], size);
ret = -EINVAL;
goto fail;
}
plane->bo = bos[i];
plane->offset = mode_cmd->offsets[i];
plane->pitch = pitch;
plane->paddr = 0;
}
drm_helper_mode_fill_fb_struct(fb, mode_cmd);
ret = drm_framebuffer_init(dev, fb, &omap_framebuffer_funcs);
if (ret) {
dev_err(dev->dev, "framebuffer init failed: %d\n", ret);
goto fail;
}
DBG("create: FB ID: %d (%p)", fb->base.id, fb);
return fb;
fail:
if (fb)
omap_framebuffer_destroy(fb);
return ERR_PTR(ret);
}
| gpl-2.0 |
benpye/buzz-kernel-2.6.35 | drivers/parisc/iosapic.c | 937 | 28267 | /*
** I/O Sapic Driver - PCI interrupt line support
**
** (c) Copyright 1999 Grant Grundler
** (c) Copyright 1999 Hewlett-Packard Company
**
** 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 I/O sapic driver manages the Interrupt Redirection Table which is
** the control logic to convert PCI line based interrupts into a Message
** Signaled Interrupt (aka Transaction Based Interrupt, TBI).
**
** Acronyms
** --------
** HPA Hard Physical Address (aka MMIO address)
** IRQ Interrupt ReQuest. Implies Line based interrupt.
** IRT Interrupt Routing Table (provided by PAT firmware)
** IRdT Interrupt Redirection Table. IRQ line to TXN ADDR/DATA
** table which is implemented in I/O SAPIC.
** ISR Interrupt Service Routine. aka Interrupt handler.
** MSI Message Signaled Interrupt. PCI 2.2 functionality.
** aka Transaction Based Interrupt (or TBI).
** PA Precision Architecture. HP's RISC architecture.
** RISC Reduced Instruction Set Computer.
**
**
** What's a Message Signalled Interrupt?
** -------------------------------------
** MSI is a write transaction which targets a processor and is similar
** to a processor write to memory or MMIO. MSIs can be generated by I/O
** devices as well as processors and require *architecture* to work.
**
** PA only supports MSI. So I/O subsystems must either natively generate
** MSIs (e.g. GSC or HP-PB) or convert line based interrupts into MSIs
** (e.g. PCI and EISA). IA64 supports MSIs via a "local SAPIC" which
** acts on behalf of a processor.
**
** MSI allows any I/O device to interrupt any processor. This makes
** load balancing of the interrupt processing possible on an SMP platform.
** Interrupts are also ordered WRT to DMA data. It's possible on I/O
** coherent systems to completely eliminate PIO reads from the interrupt
** path. The device and driver must be designed and implemented to
** guarantee all DMA has been issued (issues about atomicity here)
** before the MSI is issued. I/O status can then safely be read from
** DMA'd data by the ISR.
**
**
** PA Firmware
** -----------
** PA-RISC platforms have two fundamentally different types of firmware.
** For PCI devices, "Legacy" PDC initializes the "INTERRUPT_LINE" register
** and BARs similar to a traditional PC BIOS.
** The newer "PAT" firmware supports PDC calls which return tables.
** PAT firmware only initializes the PCI Console and Boot interface.
** With these tables, the OS can program all other PCI devices.
**
** One such PAT PDC call returns the "Interrupt Routing Table" (IRT).
** The IRT maps each PCI slot's INTA-D "output" line to an I/O SAPIC
** input line. If the IRT is not available, this driver assumes
** INTERRUPT_LINE register has been programmed by firmware. The latter
** case also means online addition of PCI cards can NOT be supported
** even if HW support is present.
**
** All platforms with PAT firmware to date (Oct 1999) use one Interrupt
** Routing Table for the entire platform.
**
** Where's the iosapic?
** --------------------
** I/O sapic is part of the "Core Electronics Complex". And on HP platforms
** it's integrated as part of the PCI bus adapter, "lba". So no bus walk
** will discover I/O Sapic. I/O Sapic driver learns about each device
** when lba driver advertises the presence of the I/O sapic by calling
** iosapic_register().
**
**
** IRQ handling notes
** ------------------
** The IO-SAPIC can indicate to the CPU which interrupt was asserted.
** So, unlike the GSC-ASIC and Dino, we allocate one CPU interrupt per
** IO-SAPIC interrupt and call the device driver's handler directly.
** The IO-SAPIC driver hijacks the CPU interrupt handler so it can
** issue the End Of Interrupt command to the IO-SAPIC.
**
** Overview of exported iosapic functions
** --------------------------------------
** (caveat: code isn't finished yet - this is just the plan)
**
** iosapic_init:
** o initialize globals (lock, etc)
** o try to read IRT. Presence of IRT determines if this is
** a PAT platform or not.
**
** iosapic_register():
** o create iosapic_info instance data structure
** o allocate vector_info array for this iosapic
** o initialize vector_info - read corresponding IRdT?
**
** iosapic_xlate_pin: (only called by fixup_irq for PAT platform)
** o intr_pin = read cfg (INTERRUPT_PIN);
** o if (device under PCI-PCI bridge)
** translate slot/pin
**
** iosapic_fixup_irq:
** o if PAT platform (IRT present)
** intr_pin = iosapic_xlate_pin(isi,pcidev):
** intr_line = find IRT entry(isi, PCI_SLOT(pcidev), intr_pin)
** save IRT entry into vector_info later
** write cfg INTERRUPT_LINE (with intr_line)?
** else
** intr_line = pcidev->irq
** IRT pointer = NULL
** endif
** o locate vector_info (needs: isi, intr_line)
** o allocate processor "irq" and get txn_addr/data
** o request_irq(processor_irq, iosapic_interrupt, vector_info,...)
**
** iosapic_enable_irq:
** o clear any pending IRQ on that line
** o enable IRdT - call enable_irq(vector[line]->processor_irq)
** o write EOI in case line is already asserted.
**
** iosapic_disable_irq:
** o disable IRdT - call disable_irq(vector[line]->processor_irq)
*/
/* FIXME: determine which include files are really needed */
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/spinlock.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <asm/byteorder.h> /* get in-line asm for swab */
#include <asm/pdc.h>
#include <asm/pdcpat.h>
#include <asm/page.h>
#include <asm/system.h>
#include <asm/io.h> /* read/write functions */
#ifdef CONFIG_SUPERIO
#include <asm/superio.h>
#endif
#include <asm/ropes.h>
#include "./iosapic_private.h"
#define MODULE_NAME "iosapic"
/* "local" compile flags */
#undef PCI_BRIDGE_FUNCS
#undef DEBUG_IOSAPIC
#undef DEBUG_IOSAPIC_IRT
#ifdef DEBUG_IOSAPIC
#define DBG(x...) printk(x)
#else /* DEBUG_IOSAPIC */
#define DBG(x...)
#endif /* DEBUG_IOSAPIC */
#ifdef DEBUG_IOSAPIC_IRT
#define DBG_IRT(x...) printk(x)
#else
#define DBG_IRT(x...)
#endif
#ifdef CONFIG_64BIT
#define COMPARE_IRTE_ADDR(irte, hpa) ((irte)->dest_iosapic_addr == (hpa))
#else
#define COMPARE_IRTE_ADDR(irte, hpa) \
((irte)->dest_iosapic_addr == ((hpa) | 0xffffffff00000000ULL))
#endif
#define IOSAPIC_REG_SELECT 0x00
#define IOSAPIC_REG_WINDOW 0x10
#define IOSAPIC_REG_EOI 0x40
#define IOSAPIC_REG_VERSION 0x1
#define IOSAPIC_IRDT_ENTRY(idx) (0x10+(idx)*2)
#define IOSAPIC_IRDT_ENTRY_HI(idx) (0x11+(idx)*2)
static inline unsigned int iosapic_read(void __iomem *iosapic, unsigned int reg)
{
writel(reg, iosapic + IOSAPIC_REG_SELECT);
return readl(iosapic + IOSAPIC_REG_WINDOW);
}
static inline void iosapic_write(void __iomem *iosapic, unsigned int reg, u32 val)
{
writel(reg, iosapic + IOSAPIC_REG_SELECT);
writel(val, iosapic + IOSAPIC_REG_WINDOW);
}
#define IOSAPIC_VERSION_MASK 0x000000ff
#define IOSAPIC_VERSION(ver) ((int) (ver & IOSAPIC_VERSION_MASK))
#define IOSAPIC_MAX_ENTRY_MASK 0x00ff0000
#define IOSAPIC_MAX_ENTRY_SHIFT 0x10
#define IOSAPIC_IRDT_MAX_ENTRY(ver) \
(int) (((ver) & IOSAPIC_MAX_ENTRY_MASK) >> IOSAPIC_MAX_ENTRY_SHIFT)
/* bits in the "low" I/O Sapic IRdT entry */
#define IOSAPIC_IRDT_ENABLE 0x10000
#define IOSAPIC_IRDT_PO_LOW 0x02000
#define IOSAPIC_IRDT_LEVEL_TRIG 0x08000
#define IOSAPIC_IRDT_MODE_LPRI 0x00100
/* bits in the "high" I/O Sapic IRdT entry */
#define IOSAPIC_IRDT_ID_EID_SHIFT 0x10
static DEFINE_SPINLOCK(iosapic_lock);
static inline void iosapic_eoi(void __iomem *addr, unsigned int data)
{
__raw_writel(data, addr);
}
/*
** REVISIT: future platforms may have more than one IRT.
** If so, the following three fields form a structure which
** then be linked into a list. Names are chosen to make searching
** for them easy - not necessarily accurate (eg "cell").
**
** Alternative: iosapic_info could point to the IRT it's in.
** iosapic_register() could search a list of IRT's.
*/
static struct irt_entry *irt_cell;
static size_t irt_num_entry;
static struct irt_entry *iosapic_alloc_irt(int num_entries)
{
unsigned long a;
/* The IRT needs to be 8-byte aligned for the PDC call.
* Normally kmalloc would guarantee larger alignment, but
* if CONFIG_DEBUG_SLAB is enabled, then we can get only
* 4-byte alignment on 32-bit kernels
*/
a = (unsigned long)kmalloc(sizeof(struct irt_entry) * num_entries + 8, GFP_KERNEL);
a = (a + 7UL) & ~7UL;
return (struct irt_entry *)a;
}
/**
* iosapic_load_irt - Fill in the interrupt routing table
* @cell_num: The cell number of the CPU we're currently executing on
* @irt: The address to place the new IRT at
* @return The number of entries found
*
* The "Get PCI INT Routing Table Size" option returns the number of
* entries in the PCI interrupt routing table for the cell specified
* in the cell_number argument. The cell number must be for a cell
* within the caller's protection domain.
*
* The "Get PCI INT Routing Table" option returns, for the cell
* specified in the cell_number argument, the PCI interrupt routing
* table in the caller allocated memory pointed to by mem_addr.
* We assume the IRT only contains entries for I/O SAPIC and
* calculate the size based on the size of I/O sapic entries.
*
* The PCI interrupt routing table entry format is derived from the
* IA64 SAL Specification 2.4. The PCI interrupt routing table defines
* the routing of PCI interrupt signals between the PCI device output
* "pins" and the IO SAPICs' input "lines" (including core I/O PCI
* devices). This table does NOT include information for devices/slots
* behind PCI to PCI bridges. See PCI to PCI Bridge Architecture Spec.
* for the architected method of routing of IRQ's behind PPB's.
*/
static int __init
iosapic_load_irt(unsigned long cell_num, struct irt_entry **irt)
{
long status; /* PDC return value status */
struct irt_entry *table; /* start of interrupt routing tbl */
unsigned long num_entries = 0UL;
BUG_ON(!irt);
if (is_pdc_pat()) {
/* Use pat pdc routine to get interrupt routing table size */
DBG("calling get_irt_size (cell %ld)\n", cell_num);
status = pdc_pat_get_irt_size(&num_entries, cell_num);
DBG("get_irt_size: %ld\n", status);
BUG_ON(status != PDC_OK);
BUG_ON(num_entries == 0);
/*
** allocate memory for interrupt routing table
** This interface isn't really right. We are assuming
** the contents of the table are exclusively
** for I/O sapic devices.
*/
table = iosapic_alloc_irt(num_entries);
if (table == NULL) {
printk(KERN_WARNING MODULE_NAME ": read_irt : can "
"not alloc mem for IRT\n");
return 0;
}
/* get PCI INT routing table */
status = pdc_pat_get_irt(table, cell_num);
DBG("pdc_pat_get_irt: %ld\n", status);
WARN_ON(status != PDC_OK);
} else {
/*
** C3000/J5000 (and similar) platforms with Sprockets PDC
** will return exactly one IRT for all iosapics.
** So if we have one, don't need to get it again.
*/
if (irt_cell)
return 0;
/* Should be using the Elroy's HPA, but it's ignored anyway */
status = pdc_pci_irt_size(&num_entries, 0);
DBG("pdc_pci_irt_size: %ld\n", status);
if (status != PDC_OK) {
/* Not a "legacy" system with I/O SAPIC either */
return 0;
}
BUG_ON(num_entries == 0);
table = iosapic_alloc_irt(num_entries);
if (!table) {
printk(KERN_WARNING MODULE_NAME ": read_irt : can "
"not alloc mem for IRT\n");
return 0;
}
/* HPA ignored by this call too. */
status = pdc_pci_irt(num_entries, 0, table);
BUG_ON(status != PDC_OK);
}
/* return interrupt table address */
*irt = table;
#ifdef DEBUG_IOSAPIC_IRT
{
struct irt_entry *p = table;
int i;
printk(MODULE_NAME " Interrupt Routing Table (cell %ld)\n", cell_num);
printk(MODULE_NAME " start = 0x%p num_entries %ld entry_size %d\n",
table,
num_entries,
(int) sizeof(struct irt_entry));
for (i = 0 ; i < num_entries ; i++, p++) {
printk(MODULE_NAME " %02x %02x %02x %02x %02x %02x %02x %02x %08x%08x\n",
p->entry_type, p->entry_length, p->interrupt_type,
p->polarity_trigger, p->src_bus_irq_devno, p->src_bus_id,
p->src_seg_id, p->dest_iosapic_intin,
((u32 *) p)[2],
((u32 *) p)[3]
);
}
}
#endif /* DEBUG_IOSAPIC_IRT */
return num_entries;
}
void __init iosapic_init(void)
{
unsigned long cell = 0;
DBG("iosapic_init()\n");
#ifdef __LP64__
if (is_pdc_pat()) {
int status;
struct pdc_pat_cell_num cell_info;
status = pdc_pat_cell_get_number(&cell_info);
if (status == PDC_OK) {
cell = cell_info.cell_num;
}
}
#endif
/* get interrupt routing table for this cell */
irt_num_entry = iosapic_load_irt(cell, &irt_cell);
if (irt_num_entry == 0)
irt_cell = NULL; /* old PDC w/o iosapic */
}
/*
** Return the IRT entry in case we need to look something else up.
*/
static struct irt_entry *
irt_find_irqline(struct iosapic_info *isi, u8 slot, u8 intr_pin)
{
struct irt_entry *i = irt_cell;
int cnt; /* track how many entries we've looked at */
u8 irq_devno = (slot << IRT_DEV_SHIFT) | (intr_pin-1);
DBG_IRT("irt_find_irqline() SLOT %d pin %d\n", slot, intr_pin);
for (cnt=0; cnt < irt_num_entry; cnt++, i++) {
/*
** Validate: entry_type, entry_length, interrupt_type
**
** Difference between validate vs compare is the former
** should print debug info and is not expected to "fail"
** on current platforms.
*/
if (i->entry_type != IRT_IOSAPIC_TYPE) {
DBG_IRT(KERN_WARNING MODULE_NAME ":find_irqline(0x%p): skipping entry %d type %d\n", i, cnt, i->entry_type);
continue;
}
if (i->entry_length != IRT_IOSAPIC_LENGTH) {
DBG_IRT(KERN_WARNING MODULE_NAME ":find_irqline(0x%p): skipping entry %d length %d\n", i, cnt, i->entry_length);
continue;
}
if (i->interrupt_type != IRT_VECTORED_INTR) {
DBG_IRT(KERN_WARNING MODULE_NAME ":find_irqline(0x%p): skipping entry %d interrupt_type %d\n", i, cnt, i->interrupt_type);
continue;
}
if (!COMPARE_IRTE_ADDR(i, isi->isi_hpa))
continue;
if ((i->src_bus_irq_devno & IRT_IRQ_DEVNO_MASK) != irq_devno)
continue;
/*
** Ignore: src_bus_id and rc_seg_id correlate with
** iosapic_info->isi_hpa on HP platforms.
** If needed, pass in "PFA" (aka config space addr)
** instead of slot.
*/
/* Found it! */
return i;
}
printk(KERN_WARNING MODULE_NAME ": 0x%lx : no IRT entry for slot %d, pin %d\n",
isi->isi_hpa, slot, intr_pin);
return NULL;
}
/*
** xlate_pin() supports the skewing of IRQ lines done by subsidiary bridges.
** Legacy PDC already does this translation for us and stores it in INTR_LINE.
**
** PAT PDC needs to basically do what legacy PDC does:
** o read PIN
** o adjust PIN in case device is "behind" a PPB
** (eg 4-port 100BT and SCSI/LAN "Combo Card")
** o convert slot/pin to I/O SAPIC input line.
**
** HP platforms only support:
** o one level of skewing for any number of PPBs
** o only support PCI-PCI Bridges.
*/
static struct irt_entry *
iosapic_xlate_pin(struct iosapic_info *isi, struct pci_dev *pcidev)
{
u8 intr_pin, intr_slot;
pci_read_config_byte(pcidev, PCI_INTERRUPT_PIN, &intr_pin);
DBG_IRT("iosapic_xlate_pin(%s) SLOT %d pin %d\n",
pcidev->slot_name, PCI_SLOT(pcidev->devfn), intr_pin);
if (intr_pin == 0) {
/* The device does NOT support/use IRQ lines. */
return NULL;
}
/* Check if pcidev behind a PPB */
if (pcidev->bus->parent) {
/* Convert pcidev INTR_PIN into something we
** can lookup in the IRT.
*/
#ifdef PCI_BRIDGE_FUNCS
/*
** Proposal #1:
**
** call implementation specific translation function
** This is architecturally "cleaner". HP-UX doesn't
** support other secondary bus types (eg. E/ISA) directly.
** May be needed for other processor (eg IA64) architectures
** or by some ambitous soul who wants to watch TV.
*/
if (pci_bridge_funcs->xlate_intr_line) {
intr_pin = pci_bridge_funcs->xlate_intr_line(pcidev);
}
#else /* PCI_BRIDGE_FUNCS */
struct pci_bus *p = pcidev->bus;
/*
** Proposal #2:
** The "pin" is skewed ((pin + dev - 1) % 4).
**
** This isn't very clean since I/O SAPIC must assume:
** - all platforms only have PCI busses.
** - only PCI-PCI bridge (eg not PCI-EISA, PCI-PCMCIA)
** - IRQ routing is only skewed once regardless of
** the number of PPB's between iosapic and device.
** (Bit3 expansion chassis follows this rule)
**
** Advantage is it's really easy to implement.
*/
intr_pin = pci_swizzle_interrupt_pin(pcidev, intr_pin);
#endif /* PCI_BRIDGE_FUNCS */
/*
* Locate the host slot of the PPB.
*/
while (p->parent->parent)
p = p->parent;
intr_slot = PCI_SLOT(p->self->devfn);
} else {
intr_slot = PCI_SLOT(pcidev->devfn);
}
DBG_IRT("iosapic_xlate_pin: bus %d slot %d pin %d\n",
pcidev->bus->secondary, intr_slot, intr_pin);
return irt_find_irqline(isi, intr_slot, intr_pin);
}
static void iosapic_rd_irt_entry(struct vector_info *vi , u32 *dp0, u32 *dp1)
{
struct iosapic_info *isp = vi->iosapic;
u8 idx = vi->irqline;
*dp0 = iosapic_read(isp->addr, IOSAPIC_IRDT_ENTRY(idx));
*dp1 = iosapic_read(isp->addr, IOSAPIC_IRDT_ENTRY_HI(idx));
}
static void iosapic_wr_irt_entry(struct vector_info *vi, u32 dp0, u32 dp1)
{
struct iosapic_info *isp = vi->iosapic;
DBG_IRT("iosapic_wr_irt_entry(): irq %d hpa %lx 0x%x 0x%x\n",
vi->irqline, isp->isi_hpa, dp0, dp1);
iosapic_write(isp->addr, IOSAPIC_IRDT_ENTRY(vi->irqline), dp0);
/* Read the window register to flush the writes down to HW */
dp0 = readl(isp->addr+IOSAPIC_REG_WINDOW);
iosapic_write(isp->addr, IOSAPIC_IRDT_ENTRY_HI(vi->irqline), dp1);
/* Read the window register to flush the writes down to HW */
dp1 = readl(isp->addr+IOSAPIC_REG_WINDOW);
}
/*
** set_irt prepares the data (dp0, dp1) according to the vector_info
** and target cpu (id_eid). dp0/dp1 are then used to program I/O SAPIC
** IRdT for the given "vector" (aka IRQ line).
*/
static void
iosapic_set_irt_data( struct vector_info *vi, u32 *dp0, u32 *dp1)
{
u32 mode = 0;
struct irt_entry *p = vi->irte;
if ((p->polarity_trigger & IRT_PO_MASK) == IRT_ACTIVE_LO)
mode |= IOSAPIC_IRDT_PO_LOW;
if (((p->polarity_trigger >> IRT_EL_SHIFT) & IRT_EL_MASK) == IRT_LEVEL_TRIG)
mode |= IOSAPIC_IRDT_LEVEL_TRIG;
/*
** IA64 REVISIT
** PA doesn't support EXTINT or LPRIO bits.
*/
*dp0 = mode | (u32) vi->txn_data;
/*
** Extracting id_eid isn't a real clean way of getting it.
** But the encoding is the same for both PA and IA64 platforms.
*/
if (is_pdc_pat()) {
/*
** PAT PDC just hands it to us "right".
** txn_addr comes from cpu_data[x].txn_addr.
*/
*dp1 = (u32) (vi->txn_addr);
} else {
/*
** eg if base_addr == 0xfffa0000),
** we want to get 0xa0ff0000.
**
** eid 0x0ff00000 -> 0x00ff0000
** id 0x000ff000 -> 0xff000000
*/
*dp1 = (((u32)vi->txn_addr & 0x0ff00000) >> 4) |
(((u32)vi->txn_addr & 0x000ff000) << 12);
}
DBG_IRT("iosapic_set_irt_data(): 0x%x 0x%x\n", *dp0, *dp1);
}
static struct vector_info *iosapic_get_vector(unsigned int irq)
{
struct irq_desc *desc = irq_to_desc(irq);
return desc->chip_data;
}
static void iosapic_disable_irq(unsigned int irq)
{
unsigned long flags;
struct vector_info *vi = iosapic_get_vector(irq);
u32 d0, d1;
spin_lock_irqsave(&iosapic_lock, flags);
iosapic_rd_irt_entry(vi, &d0, &d1);
d0 |= IOSAPIC_IRDT_ENABLE;
iosapic_wr_irt_entry(vi, d0, d1);
spin_unlock_irqrestore(&iosapic_lock, flags);
}
static void iosapic_enable_irq(unsigned int irq)
{
struct vector_info *vi = iosapic_get_vector(irq);
u32 d0, d1;
/* data is initialized by fixup_irq */
WARN_ON(vi->txn_irq == 0);
iosapic_set_irt_data(vi, &d0, &d1);
iosapic_wr_irt_entry(vi, d0, d1);
#ifdef DEBUG_IOSAPIC_IRT
{
u32 *t = (u32 *) ((ulong) vi->eoi_addr & ~0xffUL);
printk("iosapic_enable_irq(): regs %p", vi->eoi_addr);
for ( ; t < vi->eoi_addr; t++)
printk(" %x", readl(t));
printk("\n");
}
printk("iosapic_enable_irq(): sel ");
{
struct iosapic_info *isp = vi->iosapic;
for (d0=0x10; d0<0x1e; d0++) {
d1 = iosapic_read(isp->addr, d0);
printk(" %x", d1);
}
}
printk("\n");
#endif
/*
* Issuing I/O SAPIC an EOI causes an interrupt IFF IRQ line is
* asserted. IRQ generally should not be asserted when a driver
* enables their IRQ. It can lead to "interesting" race conditions
* in the driver initialization sequence.
*/
DBG(KERN_DEBUG "enable_irq(%d): eoi(%p, 0x%x)\n", irq,
vi->eoi_addr, vi->eoi_data);
iosapic_eoi(vi->eoi_addr, vi->eoi_data);
}
/*
* PARISC only supports PCI devices below I/O SAPIC.
* PCI only supports level triggered in order to share IRQ lines.
* ergo I/O SAPIC must always issue EOI on parisc.
*
* i386/ia64 support ISA devices and have to deal with
* edge-triggered interrupts too.
*/
static void iosapic_end_irq(unsigned int irq)
{
struct vector_info *vi = iosapic_get_vector(irq);
DBG(KERN_DEBUG "end_irq(%d): eoi(%p, 0x%x)\n", irq,
vi->eoi_addr, vi->eoi_data);
iosapic_eoi(vi->eoi_addr, vi->eoi_data);
cpu_end_irq(irq);
}
static unsigned int iosapic_startup_irq(unsigned int irq)
{
iosapic_enable_irq(irq);
return 0;
}
#ifdef CONFIG_SMP
static int iosapic_set_affinity_irq(unsigned int irq,
const struct cpumask *dest)
{
struct vector_info *vi = iosapic_get_vector(irq);
u32 d0, d1, dummy_d0;
unsigned long flags;
int dest_cpu;
dest_cpu = cpu_check_affinity(irq, dest);
if (dest_cpu < 0)
return -1;
cpumask_copy(irq_desc[irq].affinity, cpumask_of(dest_cpu));
vi->txn_addr = txn_affinity_addr(irq, dest_cpu);
spin_lock_irqsave(&iosapic_lock, flags);
/* d1 contains the destination CPU, so only want to set that
* entry */
iosapic_rd_irt_entry(vi, &d0, &d1);
iosapic_set_irt_data(vi, &dummy_d0, &d1);
iosapic_wr_irt_entry(vi, d0, d1);
spin_unlock_irqrestore(&iosapic_lock, flags);
return 0;
}
#endif
static struct irq_chip iosapic_interrupt_type = {
.name = "IO-SAPIC-level",
.startup = iosapic_startup_irq,
.shutdown = iosapic_disable_irq,
.enable = iosapic_enable_irq,
.disable = iosapic_disable_irq,
.ack = cpu_ack_irq,
.end = iosapic_end_irq,
#ifdef CONFIG_SMP
.set_affinity = iosapic_set_affinity_irq,
#endif
};
int iosapic_fixup_irq(void *isi_obj, struct pci_dev *pcidev)
{
struct iosapic_info *isi = isi_obj;
struct irt_entry *irte = NULL; /* only used if PAT PDC */
struct vector_info *vi;
int isi_line; /* line used by device */
if (!isi) {
printk(KERN_WARNING MODULE_NAME ": hpa not registered for %s\n",
pci_name(pcidev));
return -1;
}
#ifdef CONFIG_SUPERIO
/*
* HACK ALERT! (non-compliant PCI device support)
*
* All SuckyIO interrupts are routed through the PIC's on function 1.
* But SuckyIO OHCI USB controller gets an IRT entry anyway because
* it advertises INT D for INT_PIN. Use that IRT entry to get the
* SuckyIO interrupt routing for PICs on function 1 (*BLEECCHH*).
*/
if (is_superio_device(pcidev)) {
/* We must call superio_fixup_irq() to register the pdev */
pcidev->irq = superio_fixup_irq(pcidev);
/* Don't return if need to program the IOSAPIC's IRT... */
if (PCI_FUNC(pcidev->devfn) != SUPERIO_USB_FN)
return pcidev->irq;
}
#endif /* CONFIG_SUPERIO */
/* lookup IRT entry for isi/slot/pin set */
irte = iosapic_xlate_pin(isi, pcidev);
if (!irte) {
printk("iosapic: no IRTE for %s (IRQ not connected?)\n",
pci_name(pcidev));
return -1;
}
DBG_IRT("iosapic_fixup_irq(): irte %p %x %x %x %x %x %x %x %x\n",
irte,
irte->entry_type,
irte->entry_length,
irte->polarity_trigger,
irte->src_bus_irq_devno,
irte->src_bus_id,
irte->src_seg_id,
irte->dest_iosapic_intin,
(u32) irte->dest_iosapic_addr);
isi_line = irte->dest_iosapic_intin;
/* get vector info for this input line */
vi = isi->isi_vector + isi_line;
DBG_IRT("iosapic_fixup_irq: line %d vi 0x%p\n", isi_line, vi);
/* If this IRQ line has already been setup, skip it */
if (vi->irte)
goto out;
vi->irte = irte;
/*
* Allocate processor IRQ
*
* XXX/FIXME The txn_alloc_irq() code and related code should be
* moved to enable_irq(). That way we only allocate processor IRQ
* bits for devices that actually have drivers claiming them.
* Right now we assign an IRQ to every PCI device present,
* regardless of whether it's used or not.
*/
vi->txn_irq = txn_alloc_irq(8);
if (vi->txn_irq < 0)
panic("I/O sapic: couldn't get TXN IRQ\n");
/* enable_irq() will use txn_* to program IRdT */
vi->txn_addr = txn_alloc_addr(vi->txn_irq);
vi->txn_data = txn_alloc_data(vi->txn_irq);
vi->eoi_addr = isi->addr + IOSAPIC_REG_EOI;
vi->eoi_data = cpu_to_le32(vi->txn_data);
cpu_claim_irq(vi->txn_irq, &iosapic_interrupt_type, vi);
out:
pcidev->irq = vi->txn_irq;
DBG_IRT("iosapic_fixup_irq() %d:%d %x %x line %d irq %d\n",
PCI_SLOT(pcidev->devfn), PCI_FUNC(pcidev->devfn),
pcidev->vendor, pcidev->device, isi_line, pcidev->irq);
return pcidev->irq;
}
/*
** squirrel away the I/O Sapic Version
*/
static unsigned int
iosapic_rd_version(struct iosapic_info *isi)
{
return iosapic_read(isi->addr, IOSAPIC_REG_VERSION);
}
/*
** iosapic_register() is called by "drivers" with an integrated I/O SAPIC.
** Caller must be certain they have an I/O SAPIC and know its MMIO address.
**
** o allocate iosapic_info and add it to the list
** o read iosapic version and squirrel that away
** o read size of IRdT.
** o allocate and initialize isi_vector[]
** o allocate irq region
*/
void *iosapic_register(unsigned long hpa)
{
struct iosapic_info *isi = NULL;
struct irt_entry *irte = irt_cell;
struct vector_info *vip;
int cnt; /* track how many entries we've looked at */
/*
* Astro based platforms can only support PCI OLARD if they implement
* PAT PDC. Legacy PDC omits LBAs with no PCI devices from the IRT.
* Search the IRT and ignore iosapic's which aren't in the IRT.
*/
for (cnt=0; cnt < irt_num_entry; cnt++, irte++) {
WARN_ON(IRT_IOSAPIC_TYPE != irte->entry_type);
if (COMPARE_IRTE_ADDR(irte, hpa))
break;
}
if (cnt >= irt_num_entry) {
DBG("iosapic_register() ignoring 0x%lx (NOT FOUND)\n", hpa);
return NULL;
}
isi = kzalloc(sizeof(struct iosapic_info), GFP_KERNEL);
if (!isi) {
BUG();
return NULL;
}
isi->addr = ioremap_nocache(hpa, 4096);
isi->isi_hpa = hpa;
isi->isi_version = iosapic_rd_version(isi);
isi->isi_num_vectors = IOSAPIC_IRDT_MAX_ENTRY(isi->isi_version) + 1;
vip = isi->isi_vector = (struct vector_info *)
kzalloc(sizeof(struct vector_info) * isi->isi_num_vectors, GFP_KERNEL);
if (vip == NULL) {
kfree(isi);
return NULL;
}
for (cnt=0; cnt < isi->isi_num_vectors; cnt++, vip++) {
vip->irqline = (unsigned char) cnt;
vip->iosapic = isi;
}
return isi;
}
#ifdef DEBUG_IOSAPIC
static void
iosapic_prt_irt(void *irt, long num_entry)
{
unsigned int i, *irp = (unsigned int *) irt;
printk(KERN_DEBUG MODULE_NAME ": Interrupt Routing Table (%lx entries)\n", num_entry);
for (i=0; i<num_entry; i++, irp += 4) {
printk(KERN_DEBUG "%p : %2d %.8x %.8x %.8x %.8x\n",
irp, i, irp[0], irp[1], irp[2], irp[3]);
}
}
static void
iosapic_prt_vi(struct vector_info *vi)
{
printk(KERN_DEBUG MODULE_NAME ": vector_info[%d] is at %p\n", vi->irqline, vi);
printk(KERN_DEBUG "\t\tstatus: %.4x\n", vi->status);
printk(KERN_DEBUG "\t\ttxn_irq: %d\n", vi->txn_irq);
printk(KERN_DEBUG "\t\ttxn_addr: %lx\n", vi->txn_addr);
printk(KERN_DEBUG "\t\ttxn_data: %lx\n", vi->txn_data);
printk(KERN_DEBUG "\t\teoi_addr: %p\n", vi->eoi_addr);
printk(KERN_DEBUG "\t\teoi_data: %x\n", vi->eoi_data);
}
static void
iosapic_prt_isi(struct iosapic_info *isi)
{
printk(KERN_DEBUG MODULE_NAME ": io_sapic_info at %p\n", isi);
printk(KERN_DEBUG "\t\tisi_hpa: %lx\n", isi->isi_hpa);
printk(KERN_DEBUG "\t\tisi_status: %x\n", isi->isi_status);
printk(KERN_DEBUG "\t\tisi_version: %x\n", isi->isi_version);
printk(KERN_DEBUG "\t\tisi_vector: %p\n", isi->isi_vector);
}
#endif /* DEBUG_IOSAPIC */
| gpl-2.0 |
allenbh/linux | drivers/net/wireless/ath/ath9k/common-beacon.c | 1193 | 5462 | /*
* Copyright (c) 2008-2011 Atheros Communications Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "common.h"
#define FUDGE 2
static u32 ath9k_get_next_tbtt(struct ath_hw *ah, u64 tsf,
unsigned int interval)
{
unsigned int offset, divisor;
tsf += TU_TO_USEC(FUDGE + ah->config.sw_beacon_response_time);
divisor = TU_TO_USEC(interval);
div_u64_rem(tsf, divisor, &offset);
return (u32) tsf + divisor - offset;
}
/*
* This sets up the beacon timers according to the timestamp of the last
* received beacon and the current TSF, configures PCF and DTIM
* handling, programs the sleep registers so the hardware will wakeup in
* time to receive beacons, and configures the beacon miss handling so
* we'll receive a BMISS interrupt when we stop seeing beacons from the AP
* we've associated with.
*/
int ath9k_cmn_beacon_config_sta(struct ath_hw *ah,
struct ath_beacon_config *conf,
struct ath9k_beacon_state *bs)
{
struct ath_common *common = ath9k_hw_common(ah);
int dtim_intval;
u64 tsf;
/* No need to configure beacon if we are not associated */
if (!test_bit(ATH_OP_PRIM_STA_VIF, &common->op_flags)) {
ath_dbg(common, BEACON,
"STA is not yet associated..skipping beacon config\n");
return -EPERM;
}
memset(bs, 0, sizeof(*bs));
conf->intval = conf->beacon_interval;
/*
* Setup dtim parameters according to
* last beacon we received (which may be none).
*/
dtim_intval = conf->intval * conf->dtim_period;
/*
* Pull nexttbtt forward to reflect the current
* TSF and calculate dtim state for the result.
*/
tsf = ath9k_hw_gettsf64(ah);
conf->nexttbtt = ath9k_get_next_tbtt(ah, tsf, conf->intval);
bs->bs_intval = TU_TO_USEC(conf->intval);
bs->bs_dtimperiod = conf->dtim_period * bs->bs_intval;
bs->bs_nexttbtt = conf->nexttbtt;
bs->bs_nextdtim = conf->nexttbtt;
if (conf->dtim_period > 1)
bs->bs_nextdtim = ath9k_get_next_tbtt(ah, tsf, dtim_intval);
/*
* Calculate the number of consecutive beacons to miss* before taking
* a BMISS interrupt. The configuration is specified in TU so we only
* need calculate based on the beacon interval. Note that we clamp the
* result to at most 15 beacons.
*/
bs->bs_bmissthreshold = DIV_ROUND_UP(conf->bmiss_timeout, conf->intval);
if (bs->bs_bmissthreshold > 15)
bs->bs_bmissthreshold = 15;
else if (bs->bs_bmissthreshold <= 0)
bs->bs_bmissthreshold = 1;
/*
* Calculate sleep duration. The configuration is given in ms.
* We ensure a multiple of the beacon period is used. Also, if the sleep
* duration is greater than the DTIM period then it makes senses
* to make it a multiple of that.
*
* XXX fixed at 100ms
*/
bs->bs_sleepduration = TU_TO_USEC(roundup(IEEE80211_MS_TO_TU(100),
conf->intval));
if (bs->bs_sleepduration > bs->bs_dtimperiod)
bs->bs_sleepduration = bs->bs_dtimperiod;
/* TSF out of range threshold fixed at 1 second */
bs->bs_tsfoor_threshold = ATH9K_TSFOOR_THRESHOLD;
ath_dbg(common, BEACON, "bmiss: %u sleep: %u\n",
bs->bs_bmissthreshold, bs->bs_sleepduration);
return 0;
}
EXPORT_SYMBOL(ath9k_cmn_beacon_config_sta);
void ath9k_cmn_beacon_config_adhoc(struct ath_hw *ah,
struct ath_beacon_config *conf)
{
struct ath_common *common = ath9k_hw_common(ah);
conf->intval = TU_TO_USEC(conf->beacon_interval);
if (conf->ibss_creator)
conf->nexttbtt = conf->intval;
else
conf->nexttbtt = ath9k_get_next_tbtt(ah, ath9k_hw_gettsf64(ah),
conf->beacon_interval);
if (conf->enable_beacon)
ah->imask |= ATH9K_INT_SWBA;
else
ah->imask &= ~ATH9K_INT_SWBA;
ath_dbg(common, BEACON,
"IBSS (%s) nexttbtt: %u intval: %u conf_intval: %u\n",
(conf->enable_beacon) ? "Enable" : "Disable",
conf->nexttbtt, conf->intval, conf->beacon_interval);
}
EXPORT_SYMBOL(ath9k_cmn_beacon_config_adhoc);
/*
* For multi-bss ap support beacons are either staggered evenly over N slots or
* burst together. For the former arrange for the SWBA to be delivered for each
* slot. Slots that are not occupied will generate nothing.
*/
void ath9k_cmn_beacon_config_ap(struct ath_hw *ah,
struct ath_beacon_config *conf,
unsigned int bc_buf)
{
struct ath_common *common = ath9k_hw_common(ah);
/* NB: the beacon interval is kept internally in TU's */
conf->intval = TU_TO_USEC(conf->beacon_interval);
conf->intval /= bc_buf;
conf->nexttbtt = ath9k_get_next_tbtt(ah, ath9k_hw_gettsf64(ah),
conf->beacon_interval);
if (conf->enable_beacon)
ah->imask |= ATH9K_INT_SWBA;
else
ah->imask &= ~ATH9K_INT_SWBA;
ath_dbg(common, BEACON,
"AP (%s) nexttbtt: %u intval: %u conf_intval: %u\n",
(conf->enable_beacon) ? "Enable" : "Disable",
conf->nexttbtt, conf->intval, conf->beacon_interval);
}
EXPORT_SYMBOL(ath9k_cmn_beacon_config_ap);
| gpl-2.0 |
thicklizard/m9-patches | drivers/i2c/busses/i2c-amd756.c | 2473 | 11415 | /*
Copyright (c) 1999-2002 Merlin Hughes <merlin@merlin.org>
Shamelessly ripped from i2c-piix4.c:
Copyright (c) 1998, 1999 Frodo Looijaard <frodol@dds.nl> and
Philip Edelbrock <phil@netroedge.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
2002-04-08: Added nForce support. (Csaba Halasz)
2002-10-03: Fixed nForce PnP I/O port. (Michael Steil)
2002-12-28: Rewritten into something that resembles a Linux driver (hch)
2003-11-29: Added back AMD8111 removed by the previous rewrite.
(Philip Pokorny)
*/
/*
Supports AMD756, AMD766, AMD768, AMD8111 and nVidia nForce
Note: we assume there can only be one device, with one SMBus interface.
*/
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/stddef.h>
#include <linux/ioport.h>
#include <linux/i2c.h>
#include <linux/init.h>
#include <linux/acpi.h>
#include <linux/io.h>
/* AMD756 SMBus address offsets */
#define SMB_ADDR_OFFSET 0xE0
#define SMB_IOSIZE 16
#define SMB_GLOBAL_STATUS (0x0 + amd756_ioport)
#define SMB_GLOBAL_ENABLE (0x2 + amd756_ioport)
#define SMB_HOST_ADDRESS (0x4 + amd756_ioport)
#define SMB_HOST_DATA (0x6 + amd756_ioport)
#define SMB_HOST_COMMAND (0x8 + amd756_ioport)
#define SMB_HOST_BLOCK_DATA (0x9 + amd756_ioport)
#define SMB_HAS_DATA (0xA + amd756_ioport)
#define SMB_HAS_DEVICE_ADDRESS (0xC + amd756_ioport)
#define SMB_HAS_HOST_ADDRESS (0xE + amd756_ioport)
#define SMB_SNOOP_ADDRESS (0xF + amd756_ioport)
/* PCI Address Constants */
/* address of I/O space */
#define SMBBA 0x058 /* mh */
#define SMBBANFORCE 0x014
/* general configuration */
#define SMBGCFG 0x041 /* mh */
/* silicon revision code */
#define SMBREV 0x008
/* Other settings */
#define MAX_TIMEOUT 500
/* AMD756 constants */
#define AMD756_QUICK 0x00
#define AMD756_BYTE 0x01
#define AMD756_BYTE_DATA 0x02
#define AMD756_WORD_DATA 0x03
#define AMD756_PROCESS_CALL 0x04
#define AMD756_BLOCK_DATA 0x05
static struct pci_driver amd756_driver;
static unsigned short amd756_ioport;
/*
SMBUS event = I/O 28-29 bit 11
see E0 for the status bits and enabled in E2
*/
#define GS_ABRT_STS (1 << 0)
#define GS_COL_STS (1 << 1)
#define GS_PRERR_STS (1 << 2)
#define GS_HST_STS (1 << 3)
#define GS_HCYC_STS (1 << 4)
#define GS_TO_STS (1 << 5)
#define GS_SMB_STS (1 << 11)
#define GS_CLEAR_STS (GS_ABRT_STS | GS_COL_STS | GS_PRERR_STS | \
GS_HCYC_STS | GS_TO_STS )
#define GE_CYC_TYPE_MASK (7)
#define GE_HOST_STC (1 << 3)
#define GE_ABORT (1 << 5)
static int amd756_transaction(struct i2c_adapter *adap)
{
int temp;
int result = 0;
int timeout = 0;
dev_dbg(&adap->dev, "Transaction (pre): GS=%04x, GE=%04x, ADD=%04x, "
"DAT=%04x\n", inw_p(SMB_GLOBAL_STATUS),
inw_p(SMB_GLOBAL_ENABLE), inw_p(SMB_HOST_ADDRESS),
inb_p(SMB_HOST_DATA));
/* Make sure the SMBus host is ready to start transmitting */
if ((temp = inw_p(SMB_GLOBAL_STATUS)) & (GS_HST_STS | GS_SMB_STS)) {
dev_dbg(&adap->dev, "SMBus busy (%04x). Waiting...\n", temp);
do {
msleep(1);
temp = inw_p(SMB_GLOBAL_STATUS);
} while ((temp & (GS_HST_STS | GS_SMB_STS)) &&
(timeout++ < MAX_TIMEOUT));
/* If the SMBus is still busy, we give up */
if (timeout > MAX_TIMEOUT) {
dev_dbg(&adap->dev, "Busy wait timeout (%04x)\n", temp);
goto abort;
}
timeout = 0;
}
/* start the transaction by setting the start bit */
outw_p(inw(SMB_GLOBAL_ENABLE) | GE_HOST_STC, SMB_GLOBAL_ENABLE);
/* We will always wait for a fraction of a second! */
do {
msleep(1);
temp = inw_p(SMB_GLOBAL_STATUS);
} while ((temp & GS_HST_STS) && (timeout++ < MAX_TIMEOUT));
/* If the SMBus is still busy, we give up */
if (timeout > MAX_TIMEOUT) {
dev_dbg(&adap->dev, "Completion timeout!\n");
goto abort;
}
if (temp & GS_PRERR_STS) {
result = -ENXIO;
dev_dbg(&adap->dev, "SMBus Protocol error (no response)!\n");
}
if (temp & GS_COL_STS) {
result = -EIO;
dev_warn(&adap->dev, "SMBus collision!\n");
}
if (temp & GS_TO_STS) {
result = -ETIMEDOUT;
dev_dbg(&adap->dev, "SMBus protocol timeout!\n");
}
if (temp & GS_HCYC_STS)
dev_dbg(&adap->dev, "SMBus protocol success!\n");
outw_p(GS_CLEAR_STS, SMB_GLOBAL_STATUS);
#ifdef DEBUG
if (((temp = inw_p(SMB_GLOBAL_STATUS)) & GS_CLEAR_STS) != 0x00) {
dev_dbg(&adap->dev,
"Failed reset at end of transaction (%04x)\n", temp);
}
#endif
dev_dbg(&adap->dev,
"Transaction (post): GS=%04x, GE=%04x, ADD=%04x, DAT=%04x\n",
inw_p(SMB_GLOBAL_STATUS), inw_p(SMB_GLOBAL_ENABLE),
inw_p(SMB_HOST_ADDRESS), inb_p(SMB_HOST_DATA));
return result;
abort:
dev_warn(&adap->dev, "Sending abort\n");
outw_p(inw(SMB_GLOBAL_ENABLE) | GE_ABORT, SMB_GLOBAL_ENABLE);
msleep(100);
outw_p(GS_CLEAR_STS, SMB_GLOBAL_STATUS);
return -EIO;
}
/* Return negative errno on error. */
static s32 amd756_access(struct i2c_adapter * adap, u16 addr,
unsigned short flags, char read_write,
u8 command, int size, union i2c_smbus_data * data)
{
int i, len;
int status;
switch (size) {
case I2C_SMBUS_QUICK:
outw_p(((addr & 0x7f) << 1) | (read_write & 0x01),
SMB_HOST_ADDRESS);
size = AMD756_QUICK;
break;
case I2C_SMBUS_BYTE:
outw_p(((addr & 0x7f) << 1) | (read_write & 0x01),
SMB_HOST_ADDRESS);
if (read_write == I2C_SMBUS_WRITE)
outb_p(command, SMB_HOST_DATA);
size = AMD756_BYTE;
break;
case I2C_SMBUS_BYTE_DATA:
outw_p(((addr & 0x7f) << 1) | (read_write & 0x01),
SMB_HOST_ADDRESS);
outb_p(command, SMB_HOST_COMMAND);
if (read_write == I2C_SMBUS_WRITE)
outw_p(data->byte, SMB_HOST_DATA);
size = AMD756_BYTE_DATA;
break;
case I2C_SMBUS_WORD_DATA:
outw_p(((addr & 0x7f) << 1) | (read_write & 0x01),
SMB_HOST_ADDRESS);
outb_p(command, SMB_HOST_COMMAND);
if (read_write == I2C_SMBUS_WRITE)
outw_p(data->word, SMB_HOST_DATA); /* TODO: endian???? */
size = AMD756_WORD_DATA;
break;
case I2C_SMBUS_BLOCK_DATA:
outw_p(((addr & 0x7f) << 1) | (read_write & 0x01),
SMB_HOST_ADDRESS);
outb_p(command, SMB_HOST_COMMAND);
if (read_write == I2C_SMBUS_WRITE) {
len = data->block[0];
if (len < 0)
len = 0;
if (len > 32)
len = 32;
outw_p(len, SMB_HOST_DATA);
/* i = inw_p(SMBHSTCNT); Reset SMBBLKDAT */
for (i = 1; i <= len; i++)
outb_p(data->block[i],
SMB_HOST_BLOCK_DATA);
}
size = AMD756_BLOCK_DATA;
break;
default:
dev_warn(&adap->dev, "Unsupported transaction %d\n", size);
return -EOPNOTSUPP;
}
/* How about enabling interrupts... */
outw_p(size & GE_CYC_TYPE_MASK, SMB_GLOBAL_ENABLE);
status = amd756_transaction(adap);
if (status)
return status;
if ((read_write == I2C_SMBUS_WRITE) || (size == AMD756_QUICK))
return 0;
switch (size) {
case AMD756_BYTE:
data->byte = inw_p(SMB_HOST_DATA);
break;
case AMD756_BYTE_DATA:
data->byte = inw_p(SMB_HOST_DATA);
break;
case AMD756_WORD_DATA:
data->word = inw_p(SMB_HOST_DATA); /* TODO: endian???? */
break;
case AMD756_BLOCK_DATA:
data->block[0] = inw_p(SMB_HOST_DATA) & 0x3f;
if(data->block[0] > 32)
data->block[0] = 32;
/* i = inw_p(SMBHSTCNT); Reset SMBBLKDAT */
for (i = 1; i <= data->block[0]; i++)
data->block[i] = inb_p(SMB_HOST_BLOCK_DATA);
break;
}
return 0;
}
static u32 amd756_func(struct i2c_adapter *adapter)
{
return I2C_FUNC_SMBUS_QUICK | I2C_FUNC_SMBUS_BYTE |
I2C_FUNC_SMBUS_BYTE_DATA | I2C_FUNC_SMBUS_WORD_DATA |
I2C_FUNC_SMBUS_BLOCK_DATA;
}
static const struct i2c_algorithm smbus_algorithm = {
.smbus_xfer = amd756_access,
.functionality = amd756_func,
};
struct i2c_adapter amd756_smbus = {
.owner = THIS_MODULE,
.class = I2C_CLASS_HWMON | I2C_CLASS_SPD,
.algo = &smbus_algorithm,
};
enum chiptype { AMD756, AMD766, AMD768, NFORCE, AMD8111 };
static const char* chipname[] = {
"AMD756", "AMD766", "AMD768",
"nVidia nForce", "AMD8111",
};
static DEFINE_PCI_DEVICE_TABLE(amd756_ids) = {
{ PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_VIPER_740B),
.driver_data = AMD756 },
{ PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_VIPER_7413),
.driver_data = AMD766 },
{ PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_OPUS_7443),
.driver_data = AMD768 },
{ PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_8111_SMBUS),
.driver_data = AMD8111 },
{ PCI_DEVICE(PCI_VENDOR_ID_NVIDIA, PCI_DEVICE_ID_NVIDIA_NFORCE_SMBUS),
.driver_data = NFORCE },
{ 0, }
};
MODULE_DEVICE_TABLE (pci, amd756_ids);
static int amd756_probe(struct pci_dev *pdev, const struct pci_device_id *id)
{
int nforce = (id->driver_data == NFORCE);
int error;
u8 temp;
if (amd756_ioport) {
dev_err(&pdev->dev, "Only one device supported "
"(you have a strange motherboard, btw)\n");
return -ENODEV;
}
if (nforce) {
if (PCI_FUNC(pdev->devfn) != 1)
return -ENODEV;
pci_read_config_word(pdev, SMBBANFORCE, &amd756_ioport);
amd756_ioport &= 0xfffc;
} else { /* amd */
if (PCI_FUNC(pdev->devfn) != 3)
return -ENODEV;
pci_read_config_byte(pdev, SMBGCFG, &temp);
if ((temp & 128) == 0) {
dev_err(&pdev->dev,
"Error: SMBus controller I/O not enabled!\n");
return -ENODEV;
}
/* Determine the address of the SMBus areas */
/* Technically it is a dword but... */
pci_read_config_word(pdev, SMBBA, &amd756_ioport);
amd756_ioport &= 0xff00;
amd756_ioport += SMB_ADDR_OFFSET;
}
error = acpi_check_region(amd756_ioport, SMB_IOSIZE,
amd756_driver.name);
if (error)
return -ENODEV;
if (!request_region(amd756_ioport, SMB_IOSIZE, amd756_driver.name)) {
dev_err(&pdev->dev, "SMB region 0x%x already in use!\n",
amd756_ioport);
return -ENODEV;
}
pci_read_config_byte(pdev, SMBREV, &temp);
dev_dbg(&pdev->dev, "SMBREV = 0x%X\n", temp);
dev_dbg(&pdev->dev, "AMD756_smba = 0x%X\n", amd756_ioport);
/* set up the sysfs linkage to our parent device */
amd756_smbus.dev.parent = &pdev->dev;
snprintf(amd756_smbus.name, sizeof(amd756_smbus.name),
"SMBus %s adapter at %04x", chipname[id->driver_data],
amd756_ioport);
error = i2c_add_adapter(&amd756_smbus);
if (error) {
dev_err(&pdev->dev,
"Adapter registration failed, module not inserted\n");
goto out_err;
}
return 0;
out_err:
release_region(amd756_ioport, SMB_IOSIZE);
return error;
}
static void amd756_remove(struct pci_dev *dev)
{
i2c_del_adapter(&amd756_smbus);
release_region(amd756_ioport, SMB_IOSIZE);
}
static struct pci_driver amd756_driver = {
.name = "amd756_smbus",
.id_table = amd756_ids,
.probe = amd756_probe,
.remove = amd756_remove,
};
module_pci_driver(amd756_driver);
MODULE_AUTHOR("Merlin Hughes <merlin@merlin.org>");
MODULE_DESCRIPTION("AMD756/766/768/8111 and nVidia nForce SMBus driver");
MODULE_LICENSE("GPL");
EXPORT_SYMBOL(amd756_smbus);
| gpl-2.0 |
OliverG96/android_kernel_samsung_golden | kernel/utsname.c | 2729 | 2557 | /*
* Copyright (C) 2004 IBM Corporation
*
* Author: Serge Hallyn <serue@us.ibm.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, version 2 of the
* License.
*/
#include <linux/module.h>
#include <linux/uts.h>
#include <linux/utsname.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/user_namespace.h>
#include <linux/proc_fs.h>
static struct uts_namespace *create_uts_ns(void)
{
struct uts_namespace *uts_ns;
uts_ns = kmalloc(sizeof(struct uts_namespace), GFP_KERNEL);
if (uts_ns)
kref_init(&uts_ns->kref);
return uts_ns;
}
/*
* Clone a new ns copying an original utsname, setting refcount to 1
* @old_ns: namespace to clone
* Return NULL on error (failure to kmalloc), new ns otherwise
*/
static struct uts_namespace *clone_uts_ns(struct task_struct *tsk,
struct uts_namespace *old_ns)
{
struct uts_namespace *ns;
ns = create_uts_ns();
if (!ns)
return ERR_PTR(-ENOMEM);
down_read(&uts_sem);
memcpy(&ns->name, &old_ns->name, sizeof(ns->name));
ns->user_ns = get_user_ns(task_cred_xxx(tsk, user)->user_ns);
up_read(&uts_sem);
return ns;
}
/*
* Copy task tsk's utsname namespace, or clone it if flags
* specifies CLONE_NEWUTS. In latter case, changes to the
* utsname of this process won't be seen by parent, and vice
* versa.
*/
struct uts_namespace *copy_utsname(unsigned long flags,
struct task_struct *tsk)
{
struct uts_namespace *old_ns = tsk->nsproxy->uts_ns;
struct uts_namespace *new_ns;
BUG_ON(!old_ns);
get_uts_ns(old_ns);
if (!(flags & CLONE_NEWUTS))
return old_ns;
new_ns = clone_uts_ns(tsk, old_ns);
put_uts_ns(old_ns);
return new_ns;
}
void free_uts_ns(struct kref *kref)
{
struct uts_namespace *ns;
ns = container_of(kref, struct uts_namespace, kref);
put_user_ns(ns->user_ns);
kfree(ns);
}
static void *utsns_get(struct task_struct *task)
{
struct uts_namespace *ns = NULL;
struct nsproxy *nsproxy;
rcu_read_lock();
nsproxy = task_nsproxy(task);
if (nsproxy) {
ns = nsproxy->uts_ns;
get_uts_ns(ns);
}
rcu_read_unlock();
return ns;
}
static void utsns_put(void *ns)
{
put_uts_ns(ns);
}
static int utsns_install(struct nsproxy *nsproxy, void *ns)
{
get_uts_ns(ns);
put_uts_ns(nsproxy->uts_ns);
nsproxy->uts_ns = ns;
return 0;
}
const struct proc_ns_operations utsns_operations = {
.name = "uts",
.type = CLONE_NEWUTS,
.get = utsns_get,
.put = utsns_put,
.install = utsns_install,
};
| gpl-2.0 |
rfalize/endeavoru-suitcasekernel | arch/unicore32/mm/alignment.c | 2985 | 13274 | /*
* linux/arch/unicore32/mm/alignment.c
*
* Code specific to PKUnity SoC and UniCore ISA
*
* Copyright (C) 2001-2010 GUAN Xue-tao
*
* 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.
*/
/*
* TODO:
* FPU ldm/stm not handling
*/
#include <linux/compiler.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/uaccess.h>
#include <asm/tlbflush.h>
#include <asm/unaligned.h>
#define CODING_BITS(i) (i & 0xe0000120)
#define LDST_P_BIT(i) (i & (1 << 28)) /* Preindex */
#define LDST_U_BIT(i) (i & (1 << 27)) /* Add offset */
#define LDST_W_BIT(i) (i & (1 << 25)) /* Writeback */
#define LDST_L_BIT(i) (i & (1 << 24)) /* Load */
#define LDST_P_EQ_U(i) ((((i) ^ ((i) >> 1)) & (1 << 27)) == 0)
#define LDSTH_I_BIT(i) (i & (1 << 26)) /* half-word immed */
#define LDM_S_BIT(i) (i & (1 << 26)) /* write ASR from BSR */
#define LDM_H_BIT(i) (i & (1 << 6)) /* select r0-r15 or r16-r31 */
#define RN_BITS(i) ((i >> 19) & 31) /* Rn */
#define RD_BITS(i) ((i >> 14) & 31) /* Rd */
#define RM_BITS(i) (i & 31) /* Rm */
#define REGMASK_BITS(i) (((i & 0x7fe00) >> 3) | (i & 0x3f))
#define OFFSET_BITS(i) (i & 0x03fff)
#define SHIFT_BITS(i) ((i >> 9) & 0x1f)
#define SHIFT_TYPE(i) (i & 0xc0)
#define SHIFT_LSL 0x00
#define SHIFT_LSR 0x40
#define SHIFT_ASR 0x80
#define SHIFT_RORRRX 0xc0
union offset_union {
unsigned long un;
signed long sn;
};
#define TYPE_ERROR 0
#define TYPE_FAULT 1
#define TYPE_LDST 2
#define TYPE_DONE 3
#define TYPE_SWAP 4
#define TYPE_COLS 5 /* Coprocessor load/store */
#define get8_unaligned_check(val, addr, err) \
__asm__( \
"1: ldb.u %1, [%2], #1\n" \
"2:\n" \
" .pushsection .fixup,\"ax\"\n" \
" .align 2\n" \
"3: mov %0, #1\n" \
" b 2b\n" \
" .popsection\n" \
" .pushsection __ex_table,\"a\"\n" \
" .align 3\n" \
" .long 1b, 3b\n" \
" .popsection\n" \
: "=r" (err), "=&r" (val), "=r" (addr) \
: "0" (err), "2" (addr))
#define get8t_unaligned_check(val, addr, err) \
__asm__( \
"1: ldb.u %1, [%2], #1\n" \
"2:\n" \
" .pushsection .fixup,\"ax\"\n" \
" .align 2\n" \
"3: mov %0, #1\n" \
" b 2b\n" \
" .popsection\n" \
" .pushsection __ex_table,\"a\"\n" \
" .align 3\n" \
" .long 1b, 3b\n" \
" .popsection\n" \
: "=r" (err), "=&r" (val), "=r" (addr) \
: "0" (err), "2" (addr))
#define get16_unaligned_check(val, addr) \
do { \
unsigned int err = 0, v, a = addr; \
get8_unaligned_check(val, a, err); \
get8_unaligned_check(v, a, err); \
val |= v << 8; \
if (err) \
goto fault; \
} while (0)
#define put16_unaligned_check(val, addr) \
do { \
unsigned int err = 0, v = val, a = addr; \
__asm__( \
"1: stb.u %1, [%2], #1\n" \
" mov %1, %1 >> #8\n" \
"2: stb.u %1, [%2]\n" \
"3:\n" \
" .pushsection .fixup,\"ax\"\n" \
" .align 2\n" \
"4: mov %0, #1\n" \
" b 3b\n" \
" .popsection\n" \
" .pushsection __ex_table,\"a\"\n" \
" .align 3\n" \
" .long 1b, 4b\n" \
" .long 2b, 4b\n" \
" .popsection\n" \
: "=r" (err), "=&r" (v), "=&r" (a) \
: "0" (err), "1" (v), "2" (a)); \
if (err) \
goto fault; \
} while (0)
#define __put32_unaligned_check(ins, val, addr) \
do { \
unsigned int err = 0, v = val, a = addr; \
__asm__( \
"1: "ins" %1, [%2], #1\n" \
" mov %1, %1 >> #8\n" \
"2: "ins" %1, [%2], #1\n" \
" mov %1, %1 >> #8\n" \
"3: "ins" %1, [%2], #1\n" \
" mov %1, %1 >> #8\n" \
"4: "ins" %1, [%2]\n" \
"5:\n" \
" .pushsection .fixup,\"ax\"\n" \
" .align 2\n" \
"6: mov %0, #1\n" \
" b 5b\n" \
" .popsection\n" \
" .pushsection __ex_table,\"a\"\n" \
" .align 3\n" \
" .long 1b, 6b\n" \
" .long 2b, 6b\n" \
" .long 3b, 6b\n" \
" .long 4b, 6b\n" \
" .popsection\n" \
: "=r" (err), "=&r" (v), "=&r" (a) \
: "0" (err), "1" (v), "2" (a)); \
if (err) \
goto fault; \
} while (0)
#define get32_unaligned_check(val, addr) \
do { \
unsigned int err = 0, v, a = addr; \
get8_unaligned_check(val, a, err); \
get8_unaligned_check(v, a, err); \
val |= v << 8; \
get8_unaligned_check(v, a, err); \
val |= v << 16; \
get8_unaligned_check(v, a, err); \
val |= v << 24; \
if (err) \
goto fault; \
} while (0)
#define put32_unaligned_check(val, addr) \
__put32_unaligned_check("stb.u", val, addr)
#define get32t_unaligned_check(val, addr) \
do { \
unsigned int err = 0, v, a = addr; \
get8t_unaligned_check(val, a, err); \
get8t_unaligned_check(v, a, err); \
val |= v << 8; \
get8t_unaligned_check(v, a, err); \
val |= v << 16; \
get8t_unaligned_check(v, a, err); \
val |= v << 24; \
if (err) \
goto fault; \
} while (0)
#define put32t_unaligned_check(val, addr) \
__put32_unaligned_check("stb.u", val, addr)
static void
do_alignment_finish_ldst(unsigned long addr, unsigned long instr,
struct pt_regs *regs, union offset_union offset)
{
if (!LDST_U_BIT(instr))
offset.un = -offset.un;
if (!LDST_P_BIT(instr))
addr += offset.un;
if (!LDST_P_BIT(instr) || LDST_W_BIT(instr))
regs->uregs[RN_BITS(instr)] = addr;
}
static int
do_alignment_ldrhstrh(unsigned long addr, unsigned long instr,
struct pt_regs *regs)
{
unsigned int rd = RD_BITS(instr);
/* old value 0x40002120, can't judge swap instr correctly */
if ((instr & 0x4b003fe0) == 0x40000120)
goto swp;
if (LDST_L_BIT(instr)) {
unsigned long val;
get16_unaligned_check(val, addr);
/* signed half-word? */
if (instr & 0x80)
val = (signed long)((signed short)val);
regs->uregs[rd] = val;
} else
put16_unaligned_check(regs->uregs[rd], addr);
return TYPE_LDST;
swp:
/* only handle swap word
* for swap byte should not active this alignment exception */
get32_unaligned_check(regs->uregs[RD_BITS(instr)], addr);
put32_unaligned_check(regs->uregs[RM_BITS(instr)], addr);
return TYPE_SWAP;
fault:
return TYPE_FAULT;
}
static int
do_alignment_ldrstr(unsigned long addr, unsigned long instr,
struct pt_regs *regs)
{
unsigned int rd = RD_BITS(instr);
if (!LDST_P_BIT(instr) && LDST_W_BIT(instr))
goto trans;
if (LDST_L_BIT(instr))
get32_unaligned_check(regs->uregs[rd], addr);
else
put32_unaligned_check(regs->uregs[rd], addr);
return TYPE_LDST;
trans:
if (LDST_L_BIT(instr))
get32t_unaligned_check(regs->uregs[rd], addr);
else
put32t_unaligned_check(regs->uregs[rd], addr);
return TYPE_LDST;
fault:
return TYPE_FAULT;
}
/*
* LDM/STM alignment handler.
*
* There are 4 variants of this instruction:
*
* B = rn pointer before instruction, A = rn pointer after instruction
* ------ increasing address ----->
* | | r0 | r1 | ... | rx | |
* PU = 01 B A
* PU = 11 B A
* PU = 00 A B
* PU = 10 A B
*/
static int
do_alignment_ldmstm(unsigned long addr, unsigned long instr,
struct pt_regs *regs)
{
unsigned int rd, rn, pc_correction, reg_correction, nr_regs, regbits;
unsigned long eaddr, newaddr;
if (LDM_S_BIT(instr))
goto bad;
pc_correction = 4; /* processor implementation defined */
/* count the number of registers in the mask to be transferred */
nr_regs = hweight16(REGMASK_BITS(instr)) * 4;
rn = RN_BITS(instr);
newaddr = eaddr = regs->uregs[rn];
if (!LDST_U_BIT(instr))
nr_regs = -nr_regs;
newaddr += nr_regs;
if (!LDST_U_BIT(instr))
eaddr = newaddr;
if (LDST_P_EQ_U(instr)) /* U = P */
eaddr += 4;
/*
* This is a "hint" - we already have eaddr worked out by the
* processor for us.
*/
if (addr != eaddr) {
printk(KERN_ERR "LDMSTM: PC = %08lx, instr = %08lx, "
"addr = %08lx, eaddr = %08lx\n",
instruction_pointer(regs), instr, addr, eaddr);
show_regs(regs);
}
if (LDM_H_BIT(instr))
reg_correction = 0x10;
else
reg_correction = 0x00;
for (regbits = REGMASK_BITS(instr), rd = 0; regbits;
regbits >>= 1, rd += 1)
if (regbits & 1) {
if (LDST_L_BIT(instr))
get32_unaligned_check(regs->
uregs[rd + reg_correction], eaddr);
else
put32_unaligned_check(regs->
uregs[rd + reg_correction], eaddr);
eaddr += 4;
}
if (LDST_W_BIT(instr))
regs->uregs[rn] = newaddr;
return TYPE_DONE;
fault:
regs->UCreg_pc -= pc_correction;
return TYPE_FAULT;
bad:
printk(KERN_ERR "Alignment trap: not handling ldm with s-bit set\n");
return TYPE_ERROR;
}
static int
do_alignment(unsigned long addr, unsigned int error_code, struct pt_regs *regs)
{
union offset_union offset;
unsigned long instr, instrptr;
int (*handler) (unsigned long addr, unsigned long instr,
struct pt_regs *regs);
unsigned int type;
instrptr = instruction_pointer(regs);
if (instrptr >= PAGE_OFFSET)
instr = *(unsigned long *)instrptr;
else {
__asm__ __volatile__(
"ldw.u %0, [%1]\n"
: "=&r"(instr)
: "r"(instrptr));
}
regs->UCreg_pc += 4;
switch (CODING_BITS(instr)) {
case 0x40000120: /* ldrh or strh */
if (LDSTH_I_BIT(instr))
offset.un = (instr & 0x3e00) >> 4 | (instr & 31);
else
offset.un = regs->uregs[RM_BITS(instr)];
handler = do_alignment_ldrhstrh;
break;
case 0x60000000: /* ldr or str immediate */
case 0x60000100: /* ldr or str immediate */
case 0x60000020: /* ldr or str immediate */
case 0x60000120: /* ldr or str immediate */
offset.un = OFFSET_BITS(instr);
handler = do_alignment_ldrstr;
break;
case 0x40000000: /* ldr or str register */
offset.un = regs->uregs[RM_BITS(instr)];
{
unsigned int shiftval = SHIFT_BITS(instr);
switch (SHIFT_TYPE(instr)) {
case SHIFT_LSL:
offset.un <<= shiftval;
break;
case SHIFT_LSR:
offset.un >>= shiftval;
break;
case SHIFT_ASR:
offset.sn >>= shiftval;
break;
case SHIFT_RORRRX:
if (shiftval == 0) {
offset.un >>= 1;
if (regs->UCreg_asr & PSR_C_BIT)
offset.un |= 1 << 31;
} else
offset.un = offset.un >> shiftval |
offset.un << (32 - shiftval);
break;
}
}
handler = do_alignment_ldrstr;
break;
case 0x80000000: /* ldm or stm */
case 0x80000020: /* ldm or stm */
handler = do_alignment_ldmstm;
break;
default:
goto bad;
}
type = handler(addr, instr, regs);
if (type == TYPE_ERROR || type == TYPE_FAULT)
goto bad_or_fault;
if (type == TYPE_LDST)
do_alignment_finish_ldst(addr, instr, regs, offset);
return 0;
bad_or_fault:
if (type == TYPE_ERROR)
goto bad;
regs->UCreg_pc -= 4;
/*
* We got a fault - fix it up, or die.
*/
do_bad_area(addr, error_code, regs);
return 0;
bad:
/*
* Oops, we didn't handle the instruction.
* However, we must handle fpu instr firstly.
*/
#ifdef CONFIG_UNICORE_FPU_F64
/* handle co.load/store */
#define CODING_COLS 0xc0000000
#define COLS_OFFSET_BITS(i) (i & 0x1FF)
#define COLS_L_BITS(i) (i & (1<<24))
#define COLS_FN_BITS(i) ((i>>14) & 31)
if ((instr & 0xe0000000) == CODING_COLS) {
unsigned int fn = COLS_FN_BITS(instr);
unsigned long val = 0;
if (COLS_L_BITS(instr)) {
get32t_unaligned_check(val, addr);
switch (fn) {
#define ASM_MTF(n) case n: \
__asm__ __volatile__("MTF %0, F" __stringify(n) \
: : "r"(val)); \
break;
ASM_MTF(0); ASM_MTF(1); ASM_MTF(2); ASM_MTF(3);
ASM_MTF(4); ASM_MTF(5); ASM_MTF(6); ASM_MTF(7);
ASM_MTF(8); ASM_MTF(9); ASM_MTF(10); ASM_MTF(11);
ASM_MTF(12); ASM_MTF(13); ASM_MTF(14); ASM_MTF(15);
ASM_MTF(16); ASM_MTF(17); ASM_MTF(18); ASM_MTF(19);
ASM_MTF(20); ASM_MTF(21); ASM_MTF(22); ASM_MTF(23);
ASM_MTF(24); ASM_MTF(25); ASM_MTF(26); ASM_MTF(27);
ASM_MTF(28); ASM_MTF(29); ASM_MTF(30); ASM_MTF(31);
#undef ASM_MTF
}
} else {
switch (fn) {
#define ASM_MFF(n) case n: \
__asm__ __volatile__("MFF %0, F" __stringify(n) \
: : "r"(val)); \
break;
ASM_MFF(0); ASM_MFF(1); ASM_MFF(2); ASM_MFF(3);
ASM_MFF(4); ASM_MFF(5); ASM_MFF(6); ASM_MFF(7);
ASM_MFF(8); ASM_MFF(9); ASM_MFF(10); ASM_MFF(11);
ASM_MFF(12); ASM_MFF(13); ASM_MFF(14); ASM_MFF(15);
ASM_MFF(16); ASM_MFF(17); ASM_MFF(18); ASM_MFF(19);
ASM_MFF(20); ASM_MFF(21); ASM_MFF(22); ASM_MFF(23);
ASM_MFF(24); ASM_MFF(25); ASM_MFF(26); ASM_MFF(27);
ASM_MFF(28); ASM_MFF(29); ASM_MFF(30); ASM_MFF(31);
#undef ASM_MFF
}
put32t_unaligned_check(val, addr);
}
return TYPE_COLS;
}
fault:
return TYPE_FAULT;
#endif
printk(KERN_ERR "Alignment trap: not handling instruction "
"%08lx at [<%08lx>]\n", instr, instrptr);
return 1;
}
/*
* This needs to be done after sysctl_init, otherwise sys/ will be
* overwritten. Actually, this shouldn't be in sys/ at all since
* it isn't a sysctl, and it doesn't contain sysctl information.
*/
static int __init alignment_init(void)
{
hook_fault_code(1, do_alignment, SIGBUS, BUS_ADRALN,
"alignment exception");
return 0;
}
fs_initcall(alignment_init);
| gpl-2.0 |
bmarko82/GT-I9505_MIUI_kernel | arch/arm/mach-imx/mach-mx53_ard.c | 4777 | 7601 | /*
* Copyright (C) 2011 Freescale Semiconductor, Inc. All Rights Reserved.
*/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <linux/init.h>
#include <linux/clk.h>
#include <linux/delay.h>
#include <linux/gpio.h>
#include <linux/smsc911x.h>
#include <linux/regulator/machine.h>
#include <linux/regulator/fixed.h>
#include <mach/common.h>
#include <mach/hardware.h>
#include <mach/iomux-mx53.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/time.h>
#include "devices-imx53.h"
#define ARD_ETHERNET_INT_B IMX_GPIO_NR(2, 31)
#define ARD_SD1_CD IMX_GPIO_NR(1, 1)
#define ARD_SD1_WP IMX_GPIO_NR(1, 9)
#define ARD_I2CPORTEXP_B IMX_GPIO_NR(2, 3)
#define ARD_VOLUMEDOWN IMX_GPIO_NR(4, 0)
#define ARD_HOME IMX_GPIO_NR(5, 10)
#define ARD_BACK IMX_GPIO_NR(5, 11)
#define ARD_PROG IMX_GPIO_NR(5, 12)
#define ARD_VOLUMEUP IMX_GPIO_NR(5, 13)
static iomux_v3_cfg_t mx53_ard_pads[] = {
/* UART1 */
MX53_PAD_PATA_DIOW__UART1_TXD_MUX,
MX53_PAD_PATA_DMACK__UART1_RXD_MUX,
/* WEIM for CS1 */
MX53_PAD_EIM_EB3__GPIO2_31, /* ETHERNET_INT_B */
MX53_PAD_EIM_D16__EMI_WEIM_D_16,
MX53_PAD_EIM_D17__EMI_WEIM_D_17,
MX53_PAD_EIM_D18__EMI_WEIM_D_18,
MX53_PAD_EIM_D19__EMI_WEIM_D_19,
MX53_PAD_EIM_D20__EMI_WEIM_D_20,
MX53_PAD_EIM_D21__EMI_WEIM_D_21,
MX53_PAD_EIM_D22__EMI_WEIM_D_22,
MX53_PAD_EIM_D23__EMI_WEIM_D_23,
MX53_PAD_EIM_D24__EMI_WEIM_D_24,
MX53_PAD_EIM_D25__EMI_WEIM_D_25,
MX53_PAD_EIM_D26__EMI_WEIM_D_26,
MX53_PAD_EIM_D27__EMI_WEIM_D_27,
MX53_PAD_EIM_D28__EMI_WEIM_D_28,
MX53_PAD_EIM_D29__EMI_WEIM_D_29,
MX53_PAD_EIM_D30__EMI_WEIM_D_30,
MX53_PAD_EIM_D31__EMI_WEIM_D_31,
MX53_PAD_EIM_DA0__EMI_NAND_WEIM_DA_0,
MX53_PAD_EIM_DA1__EMI_NAND_WEIM_DA_1,
MX53_PAD_EIM_DA2__EMI_NAND_WEIM_DA_2,
MX53_PAD_EIM_DA3__EMI_NAND_WEIM_DA_3,
MX53_PAD_EIM_DA4__EMI_NAND_WEIM_DA_4,
MX53_PAD_EIM_DA5__EMI_NAND_WEIM_DA_5,
MX53_PAD_EIM_DA6__EMI_NAND_WEIM_DA_6,
MX53_PAD_EIM_OE__EMI_WEIM_OE,
MX53_PAD_EIM_RW__EMI_WEIM_RW,
MX53_PAD_EIM_CS1__EMI_WEIM_CS_1,
/* SDHC1 */
MX53_PAD_SD1_CMD__ESDHC1_CMD,
MX53_PAD_SD1_CLK__ESDHC1_CLK,
MX53_PAD_SD1_DATA0__ESDHC1_DAT0,
MX53_PAD_SD1_DATA1__ESDHC1_DAT1,
MX53_PAD_SD1_DATA2__ESDHC1_DAT2,
MX53_PAD_SD1_DATA3__ESDHC1_DAT3,
MX53_PAD_PATA_DATA8__ESDHC1_DAT4,
MX53_PAD_PATA_DATA9__ESDHC1_DAT5,
MX53_PAD_PATA_DATA10__ESDHC1_DAT6,
MX53_PAD_PATA_DATA11__ESDHC1_DAT7,
MX53_PAD_GPIO_1__GPIO1_1,
MX53_PAD_GPIO_9__GPIO1_9,
/* I2C2 */
MX53_PAD_EIM_EB2__I2C2_SCL,
MX53_PAD_KEY_ROW3__I2C2_SDA,
/* I2C3 */
MX53_PAD_GPIO_3__I2C3_SCL,
MX53_PAD_GPIO_16__I2C3_SDA,
/* GPIO */
MX53_PAD_DISP0_DAT16__GPIO5_10, /* home */
MX53_PAD_DISP0_DAT17__GPIO5_11, /* back */
MX53_PAD_DISP0_DAT18__GPIO5_12, /* prog */
MX53_PAD_DISP0_DAT19__GPIO5_13, /* vol up */
MX53_PAD_GPIO_10__GPIO4_0, /* vol down */
};
#define GPIO_BUTTON(gpio_num, ev_code, act_low, descr, wake) \
{ \
.gpio = gpio_num, \
.type = EV_KEY, \
.code = ev_code, \
.active_low = act_low, \
.desc = "btn " descr, \
.wakeup = wake, \
}
static struct gpio_keys_button ard_buttons[] = {
GPIO_BUTTON(ARD_HOME, KEY_HOME, 1, "home", 0),
GPIO_BUTTON(ARD_BACK, KEY_BACK, 1, "back", 0),
GPIO_BUTTON(ARD_PROG, KEY_PROGRAM, 1, "program", 0),
GPIO_BUTTON(ARD_VOLUMEUP, KEY_VOLUMEUP, 1, "volume-up", 0),
GPIO_BUTTON(ARD_VOLUMEDOWN, KEY_VOLUMEDOWN, 1, "volume-down", 0),
};
static const struct gpio_keys_platform_data ard_button_data __initconst = {
.buttons = ard_buttons,
.nbuttons = ARRAY_SIZE(ard_buttons),
};
static struct resource ard_smsc911x_resources[] = {
{
.start = MX53_CS1_64MB_BASE_ADDR,
.end = MX53_CS1_64MB_BASE_ADDR + SZ_32M - 1,
.flags = IORESOURCE_MEM,
},
{
.start = IMX_GPIO_TO_IRQ(ARD_ETHERNET_INT_B),
.end = IMX_GPIO_TO_IRQ(ARD_ETHERNET_INT_B),
.flags = IORESOURCE_IRQ,
},
};
struct smsc911x_platform_config ard_smsc911x_config = {
.irq_polarity = SMSC911X_IRQ_POLARITY_ACTIVE_LOW,
.irq_type = SMSC911X_IRQ_TYPE_PUSH_PULL,
.flags = SMSC911X_USE_32BIT,
};
static struct platform_device ard_smsc_lan9220_device = {
.name = "smsc911x",
.id = -1,
.num_resources = ARRAY_SIZE(ard_smsc911x_resources),
.resource = ard_smsc911x_resources,
.dev = {
.platform_data = &ard_smsc911x_config,
},
};
static const struct esdhc_platform_data mx53_ard_sd1_data __initconst = {
.cd_gpio = ARD_SD1_CD,
.wp_gpio = ARD_SD1_WP,
};
static struct imxi2c_platform_data mx53_ard_i2c2_data = {
.bitrate = 50000,
};
static struct imxi2c_platform_data mx53_ard_i2c3_data = {
.bitrate = 400000,
};
static void __init mx53_ard_io_init(void)
{
gpio_request(ARD_ETHERNET_INT_B, "eth-int-b");
gpio_direction_input(ARD_ETHERNET_INT_B);
gpio_request(ARD_I2CPORTEXP_B, "i2cptexp-rst");
gpio_direction_output(ARD_I2CPORTEXP_B, 1);
}
/* Config CS1 settings for ethernet controller */
static int weim_cs_config(void)
{
u32 reg;
void __iomem *weim_base, *iomuxc_base;
weim_base = ioremap(MX53_WEIM_BASE_ADDR, SZ_4K);
if (!weim_base)
return -ENOMEM;
iomuxc_base = ioremap(MX53_IOMUXC_BASE_ADDR, SZ_4K);
if (!iomuxc_base) {
iounmap(weim_base);
return -ENOMEM;
}
/* CS1 timings for LAN9220 */
writel(0x20001, (weim_base + 0x18));
writel(0x0, (weim_base + 0x1C));
writel(0x16000202, (weim_base + 0x20));
writel(0x00000002, (weim_base + 0x24));
writel(0x16002082, (weim_base + 0x28));
writel(0x00000000, (weim_base + 0x2C));
writel(0x00000000, (weim_base + 0x90));
/* specify 64 MB on CS1 and CS0 on GPR1 */
reg = readl(iomuxc_base + 0x4);
reg &= ~0x3F;
reg |= 0x1B;
writel(reg, (iomuxc_base + 0x4));
iounmap(iomuxc_base);
iounmap(weim_base);
return 0;
}
static struct regulator_consumer_supply dummy_supplies[] = {
REGULATOR_SUPPLY("vdd33a", "smsc911x"),
REGULATOR_SUPPLY("vddvario", "smsc911x"),
};
void __init imx53_ard_common_init(void)
{
mxc_iomux_v3_setup_multiple_pads(mx53_ard_pads,
ARRAY_SIZE(mx53_ard_pads));
weim_cs_config();
}
static struct platform_device *devices[] __initdata = {
&ard_smsc_lan9220_device,
};
static void __init mx53_ard_board_init(void)
{
imx53_soc_init();
imx53_add_imx_uart(0, NULL);
imx53_ard_common_init();
mx53_ard_io_init();
regulator_register_fixed(0, dummy_supplies, ARRAY_SIZE(dummy_supplies));
platform_add_devices(devices, ARRAY_SIZE(devices));
imx53_add_sdhci_esdhc_imx(0, &mx53_ard_sd1_data);
imx53_add_imx2_wdt(0, NULL);
imx53_add_imx_i2c(1, &mx53_ard_i2c2_data);
imx53_add_imx_i2c(2, &mx53_ard_i2c3_data);
imx_add_gpio_keys(&ard_button_data);
imx53_add_ahci_imx();
}
static void __init mx53_ard_timer_init(void)
{
mx53_clocks_init(32768, 24000000, 22579200, 0);
}
static struct sys_timer mx53_ard_timer = {
.init = mx53_ard_timer_init,
};
MACHINE_START(MX53_ARD, "Freescale MX53 ARD Board")
.map_io = mx53_map_io,
.init_early = imx53_init_early,
.init_irq = mx53_init_irq,
.handle_irq = imx53_handle_irq,
.timer = &mx53_ard_timer,
.init_machine = mx53_ard_board_init,
.restart = mxc_restart,
MACHINE_END
| gpl-2.0 |
Rashed97/android_kernel_samsung_lt03lte | drivers/net/ethernet/intel/e1000e/param.c | 4777 | 13792 | /*******************************************************************************
Intel PRO/1000 Linux driver
Copyright(c) 1999 - 2012 Intel Corporation.
This program is free software; you can redistribute it and/or modify it
under the terms and conditions of the GNU General Public License,
version 2, as published by the Free Software Foundation.
This program is distributed in the hope it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
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".
Contact Information:
Linux NICS <linux.nics@intel.com>
e1000-devel Mailing List <e1000-devel@lists.sourceforge.net>
Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*******************************************************************************/
#include <linux/netdevice.h>
#include <linux/module.h>
#include <linux/pci.h>
#include "e1000.h"
/*
* This is the only thing that needs to be changed to adjust the
* maximum number of ports that the driver can manage.
*/
#define E1000_MAX_NIC 32
#define OPTION_UNSET -1
#define OPTION_DISABLED 0
#define OPTION_ENABLED 1
#define COPYBREAK_DEFAULT 256
unsigned int copybreak = COPYBREAK_DEFAULT;
module_param(copybreak, uint, 0644);
MODULE_PARM_DESC(copybreak,
"Maximum size of packet that is copied to a new buffer on receive");
/*
* All parameters are treated the same, as an integer array of values.
* This macro just reduces the need to repeat the same declaration code
* over and over (plus this helps to avoid typo bugs).
*/
#define E1000_PARAM_INIT { [0 ... E1000_MAX_NIC] = OPTION_UNSET }
#define E1000_PARAM(X, desc) \
static int __devinitdata X[E1000_MAX_NIC+1] \
= E1000_PARAM_INIT; \
static unsigned int num_##X; \
module_param_array_named(X, X, int, &num_##X, 0); \
MODULE_PARM_DESC(X, desc);
/*
* Transmit Interrupt Delay in units of 1.024 microseconds
* Tx interrupt delay needs to typically be set to something non-zero
*
* Valid Range: 0-65535
*/
E1000_PARAM(TxIntDelay, "Transmit Interrupt Delay");
#define DEFAULT_TIDV 8
#define MAX_TXDELAY 0xFFFF
#define MIN_TXDELAY 0
/*
* Transmit Absolute Interrupt Delay in units of 1.024 microseconds
*
* Valid Range: 0-65535
*/
E1000_PARAM(TxAbsIntDelay, "Transmit Absolute Interrupt Delay");
#define DEFAULT_TADV 32
#define MAX_TXABSDELAY 0xFFFF
#define MIN_TXABSDELAY 0
/*
* Receive Interrupt Delay in units of 1.024 microseconds
* hardware will likely hang if you set this to anything but zero.
*
* Valid Range: 0-65535
*/
E1000_PARAM(RxIntDelay, "Receive Interrupt Delay");
#define MAX_RXDELAY 0xFFFF
#define MIN_RXDELAY 0
/*
* Receive Absolute Interrupt Delay in units of 1.024 microseconds
*
* Valid Range: 0-65535
*/
E1000_PARAM(RxAbsIntDelay, "Receive Absolute Interrupt Delay");
#define MAX_RXABSDELAY 0xFFFF
#define MIN_RXABSDELAY 0
/*
* Interrupt Throttle Rate (interrupts/sec)
*
* Valid Range: 100-100000 or one of: 0=off, 1=dynamic, 3=dynamic conservative
*/
E1000_PARAM(InterruptThrottleRate, "Interrupt Throttling Rate");
#define DEFAULT_ITR 3
#define MAX_ITR 100000
#define MIN_ITR 100
/*
* IntMode (Interrupt Mode)
*
* Valid Range: varies depending on kernel configuration & hardware support
*
* legacy=0, MSI=1, MSI-X=2
*
* When MSI/MSI-X support is enabled in kernel-
* Default Value: 2 (MSI-X) when supported by hardware, 1 (MSI) otherwise
* When MSI/MSI-X support is not enabled in kernel-
* Default Value: 0 (legacy)
*
* When a mode is specified that is not allowed/supported, it will be
* demoted to the most advanced interrupt mode available.
*/
E1000_PARAM(IntMode, "Interrupt Mode");
#define MAX_INTMODE 2
#define MIN_INTMODE 0
/*
* Enable Smart Power Down of the PHY
*
* Valid Range: 0, 1
*
* Default Value: 0 (disabled)
*/
E1000_PARAM(SmartPowerDownEnable, "Enable PHY smart power down");
/*
* Enable Kumeran Lock Loss workaround
*
* Valid Range: 0, 1
*
* Default Value: 1 (enabled)
*/
E1000_PARAM(KumeranLockLoss, "Enable Kumeran lock loss workaround");
/*
* Write Protect NVM
*
* Valid Range: 0, 1
*
* Default Value: 1 (enabled)
*/
E1000_PARAM(WriteProtectNVM, "Write-protect NVM [WARNING: disabling this can lead to corrupted NVM]");
/*
* Enable CRC Stripping
*
* Valid Range: 0, 1
*
* Default Value: 1 (enabled)
*/
E1000_PARAM(CrcStripping, "Enable CRC Stripping, disable if your BMC needs " \
"the CRC");
struct e1000_option {
enum { enable_option, range_option, list_option } type;
const char *name;
const char *err;
int def;
union {
struct { /* range_option info */
int min;
int max;
} r;
struct { /* list_option info */
int nr;
struct e1000_opt_list { int i; char *str; } *p;
} l;
} arg;
};
static int __devinit e1000_validate_option(unsigned int *value,
const struct e1000_option *opt,
struct e1000_adapter *adapter)
{
if (*value == OPTION_UNSET) {
*value = opt->def;
return 0;
}
switch (opt->type) {
case enable_option:
switch (*value) {
case OPTION_ENABLED:
e_info("%s Enabled\n", opt->name);
return 0;
case OPTION_DISABLED:
e_info("%s Disabled\n", opt->name);
return 0;
}
break;
case range_option:
if (*value >= opt->arg.r.min && *value <= opt->arg.r.max) {
e_info("%s set to %i\n", opt->name, *value);
return 0;
}
break;
case list_option: {
int i;
struct e1000_opt_list *ent;
for (i = 0; i < opt->arg.l.nr; i++) {
ent = &opt->arg.l.p[i];
if (*value == ent->i) {
if (ent->str[0] != '\0')
e_info("%s\n", ent->str);
return 0;
}
}
}
break;
default:
BUG();
}
e_info("Invalid %s value specified (%i) %s\n", opt->name, *value,
opt->err);
*value = opt->def;
return -1;
}
/**
* e1000e_check_options - Range Checking for Command Line Parameters
* @adapter: board private structure
*
* This routine checks all command line parameters for valid user
* input. If an invalid value is given, or if no user specified
* value exists, a default value is used. The final value is stored
* in a variable in the adapter structure.
**/
void __devinit e1000e_check_options(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
int bd = adapter->bd_number;
if (bd >= E1000_MAX_NIC) {
e_notice("Warning: no configuration for board #%i\n", bd);
e_notice("Using defaults for all values\n");
}
{ /* Transmit Interrupt Delay */
static const struct e1000_option opt = {
.type = range_option,
.name = "Transmit Interrupt Delay",
.err = "using default of "
__MODULE_STRING(DEFAULT_TIDV),
.def = DEFAULT_TIDV,
.arg = { .r = { .min = MIN_TXDELAY,
.max = MAX_TXDELAY } }
};
if (num_TxIntDelay > bd) {
adapter->tx_int_delay = TxIntDelay[bd];
e1000_validate_option(&adapter->tx_int_delay, &opt,
adapter);
} else {
adapter->tx_int_delay = opt.def;
}
}
{ /* Transmit Absolute Interrupt Delay */
static const struct e1000_option opt = {
.type = range_option,
.name = "Transmit Absolute Interrupt Delay",
.err = "using default of "
__MODULE_STRING(DEFAULT_TADV),
.def = DEFAULT_TADV,
.arg = { .r = { .min = MIN_TXABSDELAY,
.max = MAX_TXABSDELAY } }
};
if (num_TxAbsIntDelay > bd) {
adapter->tx_abs_int_delay = TxAbsIntDelay[bd];
e1000_validate_option(&adapter->tx_abs_int_delay, &opt,
adapter);
} else {
adapter->tx_abs_int_delay = opt.def;
}
}
{ /* Receive Interrupt Delay */
static struct e1000_option opt = {
.type = range_option,
.name = "Receive Interrupt Delay",
.err = "using default of "
__MODULE_STRING(DEFAULT_RDTR),
.def = DEFAULT_RDTR,
.arg = { .r = { .min = MIN_RXDELAY,
.max = MAX_RXDELAY } }
};
if (num_RxIntDelay > bd) {
adapter->rx_int_delay = RxIntDelay[bd];
e1000_validate_option(&adapter->rx_int_delay, &opt,
adapter);
} else {
adapter->rx_int_delay = opt.def;
}
}
{ /* Receive Absolute Interrupt Delay */
static const struct e1000_option opt = {
.type = range_option,
.name = "Receive Absolute Interrupt Delay",
.err = "using default of "
__MODULE_STRING(DEFAULT_RADV),
.def = DEFAULT_RADV,
.arg = { .r = { .min = MIN_RXABSDELAY,
.max = MAX_RXABSDELAY } }
};
if (num_RxAbsIntDelay > bd) {
adapter->rx_abs_int_delay = RxAbsIntDelay[bd];
e1000_validate_option(&adapter->rx_abs_int_delay, &opt,
adapter);
} else {
adapter->rx_abs_int_delay = opt.def;
}
}
{ /* Interrupt Throttling Rate */
static const struct e1000_option opt = {
.type = range_option,
.name = "Interrupt Throttling Rate (ints/sec)",
.err = "using default of "
__MODULE_STRING(DEFAULT_ITR),
.def = DEFAULT_ITR,
.arg = { .r = { .min = MIN_ITR,
.max = MAX_ITR } }
};
if (num_InterruptThrottleRate > bd) {
adapter->itr = InterruptThrottleRate[bd];
/*
* Make sure a message is printed for non-special
* values. And in case of an invalid option, display
* warning, use default and got through itr/itr_setting
* adjustment logic below
*/
if ((adapter->itr > 4) &&
e1000_validate_option(&adapter->itr, &opt, adapter))
adapter->itr = opt.def;
} else {
/*
* If no option specified, use default value and go
* through the logic below to adjust itr/itr_setting
*/
adapter->itr = opt.def;
/*
* Make sure a message is printed for non-special
* default values
*/
if (adapter->itr > 40)
e_info("%s set to default %d\n", opt.name,
adapter->itr);
}
adapter->itr_setting = adapter->itr;
switch (adapter->itr) {
case 0:
e_info("%s turned off\n", opt.name);
break;
case 1:
e_info("%s set to dynamic mode\n", opt.name);
adapter->itr = 20000;
break;
case 3:
e_info("%s set to dynamic conservative mode\n",
opt.name);
adapter->itr = 20000;
break;
case 4:
e_info("%s set to simplified (2000-8000 ints) mode\n",
opt.name);
break;
default:
/*
* Save the setting, because the dynamic bits
* change itr.
*
* Clear the lower two bits because
* they are used as control.
*/
adapter->itr_setting &= ~3;
break;
}
}
{ /* Interrupt Mode */
static struct e1000_option opt = {
.type = range_option,
.name = "Interrupt Mode",
#ifndef CONFIG_PCI_MSI
.err = "defaulting to 0 (legacy)",
.def = E1000E_INT_MODE_LEGACY,
.arg = { .r = { .min = 0,
.max = 0 } }
#endif
};
#ifdef CONFIG_PCI_MSI
if (adapter->flags & FLAG_HAS_MSIX) {
opt.err = kstrdup("defaulting to 2 (MSI-X)",
GFP_KERNEL);
opt.def = E1000E_INT_MODE_MSIX;
opt.arg.r.max = E1000E_INT_MODE_MSIX;
} else {
opt.err = kstrdup("defaulting to 1 (MSI)", GFP_KERNEL);
opt.def = E1000E_INT_MODE_MSI;
opt.arg.r.max = E1000E_INT_MODE_MSI;
}
if (!opt.err) {
dev_err(&adapter->pdev->dev,
"Failed to allocate memory\n");
return;
}
#endif
if (num_IntMode > bd) {
unsigned int int_mode = IntMode[bd];
e1000_validate_option(&int_mode, &opt, adapter);
adapter->int_mode = int_mode;
} else {
adapter->int_mode = opt.def;
}
#ifdef CONFIG_PCI_MSI
kfree(opt.err);
#endif
}
{ /* Smart Power Down */
static const struct e1000_option opt = {
.type = enable_option,
.name = "PHY Smart Power Down",
.err = "defaulting to Disabled",
.def = OPTION_DISABLED
};
if (num_SmartPowerDownEnable > bd) {
unsigned int spd = SmartPowerDownEnable[bd];
e1000_validate_option(&spd, &opt, adapter);
if ((adapter->flags & FLAG_HAS_SMART_POWER_DOWN)
&& spd)
adapter->flags |= FLAG_SMART_POWER_DOWN;
}
}
{ /* CRC Stripping */
static const struct e1000_option opt = {
.type = enable_option,
.name = "CRC Stripping",
.err = "defaulting to Enabled",
.def = OPTION_ENABLED
};
if (num_CrcStripping > bd) {
unsigned int crc_stripping = CrcStripping[bd];
e1000_validate_option(&crc_stripping, &opt, adapter);
if (crc_stripping == OPTION_ENABLED) {
adapter->flags2 |= FLAG2_CRC_STRIPPING;
adapter->flags2 |= FLAG2_DFLT_CRC_STRIPPING;
}
} else {
adapter->flags2 |= FLAG2_CRC_STRIPPING;
adapter->flags2 |= FLAG2_DFLT_CRC_STRIPPING;
}
}
{ /* Kumeran Lock Loss Workaround */
static const struct e1000_option opt = {
.type = enable_option,
.name = "Kumeran Lock Loss Workaround",
.err = "defaulting to Enabled",
.def = OPTION_ENABLED
};
if (num_KumeranLockLoss > bd) {
unsigned int kmrn_lock_loss = KumeranLockLoss[bd];
e1000_validate_option(&kmrn_lock_loss, &opt, adapter);
if (hw->mac.type == e1000_ich8lan)
e1000e_set_kmrn_lock_loss_workaround_ich8lan(hw,
kmrn_lock_loss);
} else {
if (hw->mac.type == e1000_ich8lan)
e1000e_set_kmrn_lock_loss_workaround_ich8lan(hw,
opt.def);
}
}
{ /* Write-protect NVM */
static const struct e1000_option opt = {
.type = enable_option,
.name = "Write-protect NVM",
.err = "defaulting to Enabled",
.def = OPTION_ENABLED
};
if (adapter->flags & FLAG_IS_ICH) {
if (num_WriteProtectNVM > bd) {
unsigned int write_protect_nvm = WriteProtectNVM[bd];
e1000_validate_option(&write_protect_nvm, &opt,
adapter);
if (write_protect_nvm)
adapter->flags |= FLAG_READ_ONLY_NVM;
} else {
if (opt.def)
adapter->flags |= FLAG_READ_ONLY_NVM;
}
}
}
}
| gpl-2.0 |
adri360/DarkNoteIII-Kernel | sound/usb/usx2y/us122l.c | 5033 | 19290 | /*
* Copyright (C) 2007, 2008 Karsten Wiese <fzu@wemgehoertderstaat.de>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/slab.h>
#include <linux/usb.h>
#include <linux/usb/audio.h>
#include <linux/module.h>
#include <sound/core.h>
#include <sound/hwdep.h>
#include <sound/pcm.h>
#include <sound/initval.h>
#define MODNAME "US122L"
#include "usb_stream.c"
#include "../usbaudio.h"
#include "../midi.h"
#include "us122l.h"
MODULE_AUTHOR("Karsten Wiese <fzu@wemgehoertderstaat.de>");
MODULE_DESCRIPTION("TASCAM "NAME_ALLCAPS" Version 0.5");
MODULE_LICENSE("GPL");
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-max */
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* Id for this card */
/* Enable this card */
static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for "NAME_ALLCAPS".");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for "NAME_ALLCAPS".");
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable "NAME_ALLCAPS".");
static int snd_us122l_card_used[SNDRV_CARDS];
static int us122l_create_usbmidi(struct snd_card *card)
{
static struct snd_usb_midi_endpoint_info quirk_data = {
.out_ep = 4,
.in_ep = 3,
.out_cables = 0x001,
.in_cables = 0x001
};
static struct snd_usb_audio_quirk quirk = {
.vendor_name = "US122L",
.product_name = NAME_ALLCAPS,
.ifnum = 1,
.type = QUIRK_MIDI_US122L,
.data = &quirk_data
};
struct usb_device *dev = US122L(card)->dev;
struct usb_interface *iface = usb_ifnum_to_if(dev, 1);
return snd_usbmidi_create(card, iface,
&US122L(card)->midi_list, &quirk);
}
static int us144_create_usbmidi(struct snd_card *card)
{
static struct snd_usb_midi_endpoint_info quirk_data = {
.out_ep = 4,
.in_ep = 3,
.out_cables = 0x001,
.in_cables = 0x001
};
static struct snd_usb_audio_quirk quirk = {
.vendor_name = "US144",
.product_name = NAME_ALLCAPS,
.ifnum = 0,
.type = QUIRK_MIDI_US122L,
.data = &quirk_data
};
struct usb_device *dev = US122L(card)->dev;
struct usb_interface *iface = usb_ifnum_to_if(dev, 0);
return snd_usbmidi_create(card, iface,
&US122L(card)->midi_list, &quirk);
}
/*
* Wrapper for usb_control_msg().
* Allocates a temp buffer to prevent dmaing from/to the stack.
*/
static int us122l_ctl_msg(struct usb_device *dev, unsigned int pipe,
__u8 request, __u8 requesttype,
__u16 value, __u16 index, void *data,
__u16 size, int timeout)
{
int err;
void *buf = NULL;
if (size > 0) {
buf = kmemdup(data, size, GFP_KERNEL);
if (!buf)
return -ENOMEM;
}
err = usb_control_msg(dev, pipe, request, requesttype,
value, index, buf, size, timeout);
if (size > 0) {
memcpy(data, buf, size);
kfree(buf);
}
return err;
}
static void pt_info_set(struct usb_device *dev, u8 v)
{
int ret;
ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
'I',
USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
v, 0, NULL, 0, 1000);
snd_printdd(KERN_DEBUG "%i\n", ret);
}
static void usb_stream_hwdep_vm_open(struct vm_area_struct *area)
{
struct us122l *us122l = area->vm_private_data;
atomic_inc(&us122l->mmap_count);
snd_printdd(KERN_DEBUG "%i\n", atomic_read(&us122l->mmap_count));
}
static int usb_stream_hwdep_vm_fault(struct vm_area_struct *area,
struct vm_fault *vmf)
{
unsigned long offset;
struct page *page;
void *vaddr;
struct us122l *us122l = area->vm_private_data;
struct usb_stream *s;
mutex_lock(&us122l->mutex);
s = us122l->sk.s;
if (!s)
goto unlock;
offset = vmf->pgoff << PAGE_SHIFT;
if (offset < PAGE_ALIGN(s->read_size))
vaddr = (char *)s + offset;
else {
offset -= PAGE_ALIGN(s->read_size);
if (offset >= PAGE_ALIGN(s->write_size))
goto unlock;
vaddr = us122l->sk.write_page + offset;
}
page = virt_to_page(vaddr);
get_page(page);
mutex_unlock(&us122l->mutex);
vmf->page = page;
return 0;
unlock:
mutex_unlock(&us122l->mutex);
return VM_FAULT_SIGBUS;
}
static void usb_stream_hwdep_vm_close(struct vm_area_struct *area)
{
struct us122l *us122l = area->vm_private_data;
atomic_dec(&us122l->mmap_count);
snd_printdd(KERN_DEBUG "%i\n", atomic_read(&us122l->mmap_count));
}
static const struct vm_operations_struct usb_stream_hwdep_vm_ops = {
.open = usb_stream_hwdep_vm_open,
.fault = usb_stream_hwdep_vm_fault,
.close = usb_stream_hwdep_vm_close,
};
static int usb_stream_hwdep_open(struct snd_hwdep *hw, struct file *file)
{
struct us122l *us122l = hw->private_data;
struct usb_interface *iface;
snd_printdd(KERN_DEBUG "%p %p\n", hw, file);
if (hw->used >= 2)
return -EBUSY;
if (!us122l->first)
us122l->first = file;
if (us122l->dev->descriptor.idProduct == USB_ID_US144 ||
us122l->dev->descriptor.idProduct == USB_ID_US144MKII) {
iface = usb_ifnum_to_if(us122l->dev, 0);
usb_autopm_get_interface(iface);
}
iface = usb_ifnum_to_if(us122l->dev, 1);
usb_autopm_get_interface(iface);
return 0;
}
static int usb_stream_hwdep_release(struct snd_hwdep *hw, struct file *file)
{
struct us122l *us122l = hw->private_data;
struct usb_interface *iface;
snd_printdd(KERN_DEBUG "%p %p\n", hw, file);
if (us122l->dev->descriptor.idProduct == USB_ID_US144 ||
us122l->dev->descriptor.idProduct == USB_ID_US144MKII) {
iface = usb_ifnum_to_if(us122l->dev, 0);
usb_autopm_put_interface(iface);
}
iface = usb_ifnum_to_if(us122l->dev, 1);
usb_autopm_put_interface(iface);
if (us122l->first == file)
us122l->first = NULL;
mutex_lock(&us122l->mutex);
if (us122l->master == file)
us122l->master = us122l->slave;
us122l->slave = NULL;
mutex_unlock(&us122l->mutex);
return 0;
}
static int usb_stream_hwdep_mmap(struct snd_hwdep *hw,
struct file *filp, struct vm_area_struct *area)
{
unsigned long size = area->vm_end - area->vm_start;
struct us122l *us122l = hw->private_data;
unsigned long offset;
struct usb_stream *s;
int err = 0;
bool read;
offset = area->vm_pgoff << PAGE_SHIFT;
mutex_lock(&us122l->mutex);
s = us122l->sk.s;
read = offset < s->read_size;
if (read && area->vm_flags & VM_WRITE) {
err = -EPERM;
goto out;
}
snd_printdd(KERN_DEBUG "%lu %u\n", size,
read ? s->read_size : s->write_size);
/* if userspace tries to mmap beyond end of our buffer, fail */
if (size > PAGE_ALIGN(read ? s->read_size : s->write_size)) {
snd_printk(KERN_WARNING "%lu > %u\n", size,
read ? s->read_size : s->write_size);
err = -EINVAL;
goto out;
}
area->vm_ops = &usb_stream_hwdep_vm_ops;
area->vm_flags |= VM_RESERVED;
area->vm_private_data = us122l;
atomic_inc(&us122l->mmap_count);
out:
mutex_unlock(&us122l->mutex);
return err;
}
static unsigned int usb_stream_hwdep_poll(struct snd_hwdep *hw,
struct file *file, poll_table *wait)
{
struct us122l *us122l = hw->private_data;
unsigned *polled;
unsigned int mask;
poll_wait(file, &us122l->sk.sleep, wait);
mask = POLLIN | POLLOUT | POLLWRNORM | POLLERR;
if (mutex_trylock(&us122l->mutex)) {
struct usb_stream *s = us122l->sk.s;
if (s && s->state == usb_stream_ready) {
if (us122l->first == file)
polled = &s->periods_polled;
else
polled = &us122l->second_periods_polled;
if (*polled != s->periods_done) {
*polled = s->periods_done;
mask = POLLIN | POLLOUT | POLLWRNORM;
} else
mask = 0;
}
mutex_unlock(&us122l->mutex);
}
return mask;
}
static void us122l_stop(struct us122l *us122l)
{
struct list_head *p;
list_for_each(p, &us122l->midi_list)
snd_usbmidi_input_stop(p);
usb_stream_stop(&us122l->sk);
usb_stream_free(&us122l->sk);
}
static int us122l_set_sample_rate(struct usb_device *dev, int rate)
{
unsigned int ep = 0x81;
unsigned char data[3];
int err;
data[0] = rate;
data[1] = rate >> 8;
data[2] = rate >> 16;
err = us122l_ctl_msg(dev, usb_sndctrlpipe(dev, 0), UAC_SET_CUR,
USB_TYPE_CLASS|USB_RECIP_ENDPOINT|USB_DIR_OUT,
UAC_EP_CS_ATTR_SAMPLE_RATE << 8, ep, data, 3, 1000);
if (err < 0)
snd_printk(KERN_ERR "%d: cannot set freq %d to ep 0x%x\n",
dev->devnum, rate, ep);
return err;
}
static bool us122l_start(struct us122l *us122l,
unsigned rate, unsigned period_frames)
{
struct list_head *p;
int err;
unsigned use_packsize = 0;
bool success = false;
if (us122l->dev->speed == USB_SPEED_HIGH) {
/* The us-122l's descriptor defaults to iso max_packsize 78,
which isn't needed for samplerates <= 48000.
Lets save some memory:
*/
switch (rate) {
case 44100:
use_packsize = 36;
break;
case 48000:
use_packsize = 42;
break;
case 88200:
use_packsize = 72;
break;
}
}
if (!usb_stream_new(&us122l->sk, us122l->dev, 1, 2,
rate, use_packsize, period_frames, 6))
goto out;
err = us122l_set_sample_rate(us122l->dev, rate);
if (err < 0) {
us122l_stop(us122l);
snd_printk(KERN_ERR "us122l_set_sample_rate error \n");
goto out;
}
err = usb_stream_start(&us122l->sk);
if (err < 0) {
us122l_stop(us122l);
snd_printk(KERN_ERR "us122l_start error %i \n", err);
goto out;
}
list_for_each(p, &us122l->midi_list)
snd_usbmidi_input_start(p);
success = true;
out:
return success;
}
static int usb_stream_hwdep_ioctl(struct snd_hwdep *hw, struct file *file,
unsigned cmd, unsigned long arg)
{
struct usb_stream_config *cfg;
struct us122l *us122l = hw->private_data;
struct usb_stream *s;
unsigned min_period_frames;
int err = 0;
bool high_speed;
if (cmd != SNDRV_USB_STREAM_IOCTL_SET_PARAMS)
return -ENOTTY;
cfg = memdup_user((void *)arg, sizeof(*cfg));
if (IS_ERR(cfg))
return PTR_ERR(cfg);
if (cfg->version != USB_STREAM_INTERFACE_VERSION) {
err = -ENXIO;
goto free;
}
high_speed = us122l->dev->speed == USB_SPEED_HIGH;
if ((cfg->sample_rate != 44100 && cfg->sample_rate != 48000 &&
(!high_speed ||
(cfg->sample_rate != 88200 && cfg->sample_rate != 96000))) ||
cfg->frame_size != 6 ||
cfg->period_frames > 0x3000) {
err = -EINVAL;
goto free;
}
switch (cfg->sample_rate) {
case 44100:
min_period_frames = 48;
break;
case 48000:
min_period_frames = 52;
break;
default:
min_period_frames = 104;
break;
}
if (!high_speed)
min_period_frames <<= 1;
if (cfg->period_frames < min_period_frames) {
err = -EINVAL;
goto free;
}
snd_power_wait(hw->card, SNDRV_CTL_POWER_D0);
mutex_lock(&us122l->mutex);
s = us122l->sk.s;
if (!us122l->master)
us122l->master = file;
else if (us122l->master != file) {
if (!s || memcmp(cfg, &s->cfg, sizeof(*cfg))) {
err = -EIO;
goto unlock;
}
us122l->slave = file;
}
if (!s || memcmp(cfg, &s->cfg, sizeof(*cfg)) ||
s->state == usb_stream_xrun) {
us122l_stop(us122l);
if (!us122l_start(us122l, cfg->sample_rate, cfg->period_frames))
err = -EIO;
else
err = 1;
}
unlock:
mutex_unlock(&us122l->mutex);
free:
kfree(cfg);
wake_up_all(&us122l->sk.sleep);
return err;
}
#define SND_USB_STREAM_ID "USB STREAM"
static int usb_stream_hwdep_new(struct snd_card *card)
{
int err;
struct snd_hwdep *hw;
struct usb_device *dev = US122L(card)->dev;
err = snd_hwdep_new(card, SND_USB_STREAM_ID, 0, &hw);
if (err < 0)
return err;
hw->iface = SNDRV_HWDEP_IFACE_USB_STREAM;
hw->private_data = US122L(card);
hw->ops.open = usb_stream_hwdep_open;
hw->ops.release = usb_stream_hwdep_release;
hw->ops.ioctl = usb_stream_hwdep_ioctl;
hw->ops.ioctl_compat = usb_stream_hwdep_ioctl;
hw->ops.mmap = usb_stream_hwdep_mmap;
hw->ops.poll = usb_stream_hwdep_poll;
sprintf(hw->name, "/proc/bus/usb/%03d/%03d/hwdeppcm",
dev->bus->busnum, dev->devnum);
return 0;
}
static bool us122l_create_card(struct snd_card *card)
{
int err;
struct us122l *us122l = US122L(card);
if (us122l->dev->descriptor.idProduct == USB_ID_US144 ||
us122l->dev->descriptor.idProduct == USB_ID_US144MKII) {
err = usb_set_interface(us122l->dev, 0, 1);
if (err) {
snd_printk(KERN_ERR "usb_set_interface error \n");
return false;
}
}
err = usb_set_interface(us122l->dev, 1, 1);
if (err) {
snd_printk(KERN_ERR "usb_set_interface error \n");
return false;
}
pt_info_set(us122l->dev, 0x11);
pt_info_set(us122l->dev, 0x10);
if (!us122l_start(us122l, 44100, 256))
return false;
if (us122l->dev->descriptor.idProduct == USB_ID_US144 ||
us122l->dev->descriptor.idProduct == USB_ID_US144MKII)
err = us144_create_usbmidi(card);
else
err = us122l_create_usbmidi(card);
if (err < 0) {
snd_printk(KERN_ERR "us122l_create_usbmidi error %i \n", err);
us122l_stop(us122l);
return false;
}
err = usb_stream_hwdep_new(card);
if (err < 0) {
/* release the midi resources */
struct list_head *p;
list_for_each(p, &us122l->midi_list)
snd_usbmidi_disconnect(p);
us122l_stop(us122l);
return false;
}
return true;
}
static void snd_us122l_free(struct snd_card *card)
{
struct us122l *us122l = US122L(card);
int index = us122l->card_index;
if (index >= 0 && index < SNDRV_CARDS)
snd_us122l_card_used[index] = 0;
}
static int usx2y_create_card(struct usb_device *device, struct snd_card **cardp)
{
int dev;
struct snd_card *card;
int err;
for (dev = 0; dev < SNDRV_CARDS; ++dev)
if (enable[dev] && !snd_us122l_card_used[dev])
break;
if (dev >= SNDRV_CARDS)
return -ENODEV;
err = snd_card_create(index[dev], id[dev], THIS_MODULE,
sizeof(struct us122l), &card);
if (err < 0)
return err;
snd_us122l_card_used[US122L(card)->card_index = dev] = 1;
card->private_free = snd_us122l_free;
US122L(card)->dev = device;
mutex_init(&US122L(card)->mutex);
init_waitqueue_head(&US122L(card)->sk.sleep);
INIT_LIST_HEAD(&US122L(card)->midi_list);
strcpy(card->driver, "USB "NAME_ALLCAPS"");
sprintf(card->shortname, "TASCAM "NAME_ALLCAPS"");
sprintf(card->longname, "%s (%x:%x if %d at %03d/%03d)",
card->shortname,
le16_to_cpu(device->descriptor.idVendor),
le16_to_cpu(device->descriptor.idProduct),
0,
US122L(card)->dev->bus->busnum,
US122L(card)->dev->devnum
);
*cardp = card;
return 0;
}
static int us122l_usb_probe(struct usb_interface *intf,
const struct usb_device_id *device_id,
struct snd_card **cardp)
{
struct usb_device *device = interface_to_usbdev(intf);
struct snd_card *card;
int err;
err = usx2y_create_card(device, &card);
if (err < 0)
return err;
snd_card_set_dev(card, &intf->dev);
if (!us122l_create_card(card)) {
snd_card_free(card);
return -EINVAL;
}
err = snd_card_register(card);
if (err < 0) {
snd_card_free(card);
return err;
}
usb_get_intf(usb_ifnum_to_if(device, 0));
usb_get_dev(device);
*cardp = card;
return 0;
}
static int snd_us122l_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct usb_device *device = interface_to_usbdev(intf);
struct snd_card *card;
int err;
if ((device->descriptor.idProduct == USB_ID_US144 ||
device->descriptor.idProduct == USB_ID_US144MKII)
&& device->speed == USB_SPEED_HIGH) {
snd_printk(KERN_ERR "disable ehci-hcd to run US-144 \n");
return -ENODEV;
}
snd_printdd(KERN_DEBUG"%p:%i\n",
intf, intf->cur_altsetting->desc.bInterfaceNumber);
if (intf->cur_altsetting->desc.bInterfaceNumber != 1)
return 0;
err = us122l_usb_probe(usb_get_intf(intf), id, &card);
if (err < 0) {
usb_put_intf(intf);
return err;
}
usb_set_intfdata(intf, card);
return 0;
}
static void snd_us122l_disconnect(struct usb_interface *intf)
{
struct snd_card *card;
struct us122l *us122l;
struct list_head *p;
card = usb_get_intfdata(intf);
if (!card)
return;
snd_card_disconnect(card);
us122l = US122L(card);
mutex_lock(&us122l->mutex);
us122l_stop(us122l);
mutex_unlock(&us122l->mutex);
/* release the midi resources */
list_for_each(p, &us122l->midi_list) {
snd_usbmidi_disconnect(p);
}
usb_put_intf(usb_ifnum_to_if(us122l->dev, 0));
usb_put_intf(usb_ifnum_to_if(us122l->dev, 1));
usb_put_dev(us122l->dev);
while (atomic_read(&us122l->mmap_count))
msleep(500);
snd_card_free(card);
}
static int snd_us122l_suspend(struct usb_interface *intf, pm_message_t message)
{
struct snd_card *card;
struct us122l *us122l;
struct list_head *p;
card = usb_get_intfdata(intf);
if (!card)
return 0;
snd_power_change_state(card, SNDRV_CTL_POWER_D3hot);
us122l = US122L(card);
if (!us122l)
return 0;
list_for_each(p, &us122l->midi_list)
snd_usbmidi_input_stop(p);
mutex_lock(&us122l->mutex);
usb_stream_stop(&us122l->sk);
mutex_unlock(&us122l->mutex);
return 0;
}
static int snd_us122l_resume(struct usb_interface *intf)
{
struct snd_card *card;
struct us122l *us122l;
struct list_head *p;
int err;
card = usb_get_intfdata(intf);
if (!card)
return 0;
us122l = US122L(card);
if (!us122l)
return 0;
mutex_lock(&us122l->mutex);
/* needed, doesn't restart without: */
if (us122l->dev->descriptor.idProduct == USB_ID_US144 ||
us122l->dev->descriptor.idProduct == USB_ID_US144MKII) {
err = usb_set_interface(us122l->dev, 0, 1);
if (err) {
snd_printk(KERN_ERR "usb_set_interface error \n");
goto unlock;
}
}
err = usb_set_interface(us122l->dev, 1, 1);
if (err) {
snd_printk(KERN_ERR "usb_set_interface error \n");
goto unlock;
}
pt_info_set(us122l->dev, 0x11);
pt_info_set(us122l->dev, 0x10);
err = us122l_set_sample_rate(us122l->dev,
us122l->sk.s->cfg.sample_rate);
if (err < 0) {
snd_printk(KERN_ERR "us122l_set_sample_rate error \n");
goto unlock;
}
err = usb_stream_start(&us122l->sk);
if (err)
goto unlock;
list_for_each(p, &us122l->midi_list)
snd_usbmidi_input_start(p);
unlock:
mutex_unlock(&us122l->mutex);
snd_power_change_state(card, SNDRV_CTL_POWER_D0);
return err;
}
static struct usb_device_id snd_us122l_usb_id_table[] = {
{
.match_flags = USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x0644,
.idProduct = USB_ID_US122L
},
{ /* US-144 only works at USB1.1! Disable module ehci-hcd. */
.match_flags = USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x0644,
.idProduct = USB_ID_US144
},
{
.match_flags = USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x0644,
.idProduct = USB_ID_US122MKII
},
{
.match_flags = USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x0644,
.idProduct = USB_ID_US144MKII
},
{ /* terminator */ }
};
MODULE_DEVICE_TABLE(usb, snd_us122l_usb_id_table);
static struct usb_driver snd_us122l_usb_driver = {
.name = "snd-usb-us122l",
.probe = snd_us122l_probe,
.disconnect = snd_us122l_disconnect,
.suspend = snd_us122l_suspend,
.resume = snd_us122l_resume,
.reset_resume = snd_us122l_resume,
.id_table = snd_us122l_usb_id_table,
.supports_autosuspend = 1
};
module_usb_driver(snd_us122l_usb_driver);
| gpl-2.0 |
engine95/navelC-990 | drivers/gpu/drm/exynos/exynos_drm_encoder.c | 5033 | 12709 | /* exynos_drm_encoder.c
*
* Copyright (c) 2011 Samsung Electronics Co., Ltd.
* Authors:
* Inki Dae <inki.dae@samsung.com>
* Joonyoung Shim <jy0922.shim@samsung.com>
* Seung-Woo Kim <sw0312.kim@samsung.com>
*
* 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.
*/
#include "drmP.h"
#include "drm_crtc_helper.h"
#include "exynos_drm_drv.h"
#include "exynos_drm_crtc.h"
#include "exynos_drm_encoder.h"
#define to_exynos_encoder(x) container_of(x, struct exynos_drm_encoder,\
drm_encoder)
/*
* exynos specific encoder structure.
*
* @drm_encoder: encoder object.
* @manager: specific encoder has its own manager to control a hardware
* appropriately and we can access a hardware drawing on this manager.
* @dpms: store the encoder dpms value.
*/
struct exynos_drm_encoder {
struct drm_encoder drm_encoder;
struct exynos_drm_manager *manager;
int dpms;
};
static void exynos_drm_display_power(struct drm_encoder *encoder, int mode)
{
struct drm_device *dev = encoder->dev;
struct drm_connector *connector;
struct exynos_drm_manager *manager = exynos_drm_get_manager(encoder);
list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
if (connector->encoder == encoder) {
struct exynos_drm_display_ops *display_ops =
manager->display_ops;
DRM_DEBUG_KMS("connector[%d] dpms[%d]\n",
connector->base.id, mode);
if (display_ops && display_ops->power_on)
display_ops->power_on(manager->dev, mode);
}
}
}
static void exynos_drm_encoder_dpms(struct drm_encoder *encoder, int mode)
{
struct drm_device *dev = encoder->dev;
struct exynos_drm_manager *manager = exynos_drm_get_manager(encoder);
struct exynos_drm_manager_ops *manager_ops = manager->ops;
struct exynos_drm_encoder *exynos_encoder = to_exynos_encoder(encoder);
DRM_DEBUG_KMS("%s, encoder dpms: %d\n", __FILE__, mode);
if (exynos_encoder->dpms == mode) {
DRM_DEBUG_KMS("desired dpms mode is same as previous one.\n");
return;
}
mutex_lock(&dev->struct_mutex);
switch (mode) {
case DRM_MODE_DPMS_ON:
if (manager_ops && manager_ops->apply)
manager_ops->apply(manager->dev);
exynos_drm_display_power(encoder, mode);
exynos_encoder->dpms = mode;
break;
case DRM_MODE_DPMS_STANDBY:
case DRM_MODE_DPMS_SUSPEND:
case DRM_MODE_DPMS_OFF:
exynos_drm_display_power(encoder, mode);
exynos_encoder->dpms = mode;
break;
default:
DRM_ERROR("unspecified mode %d\n", mode);
break;
}
mutex_unlock(&dev->struct_mutex);
}
static bool
exynos_drm_encoder_mode_fixup(struct drm_encoder *encoder,
struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
struct drm_device *dev = encoder->dev;
struct drm_connector *connector;
struct exynos_drm_manager *manager = exynos_drm_get_manager(encoder);
struct exynos_drm_manager_ops *manager_ops = manager->ops;
DRM_DEBUG_KMS("%s\n", __FILE__);
list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
if (connector->encoder == encoder)
if (manager_ops && manager_ops->mode_fixup)
manager_ops->mode_fixup(manager->dev, connector,
mode, adjusted_mode);
}
return true;
}
static void exynos_drm_encoder_mode_set(struct drm_encoder *encoder,
struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
struct drm_device *dev = encoder->dev;
struct drm_connector *connector;
struct exynos_drm_manager *manager = exynos_drm_get_manager(encoder);
struct exynos_drm_manager_ops *manager_ops = manager->ops;
struct exynos_drm_overlay_ops *overlay_ops = manager->overlay_ops;
struct exynos_drm_overlay *overlay = get_exynos_drm_overlay(dev,
encoder->crtc);
DRM_DEBUG_KMS("%s\n", __FILE__);
list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
if (connector->encoder == encoder) {
if (manager_ops && manager_ops->mode_set)
manager_ops->mode_set(manager->dev,
adjusted_mode);
if (overlay_ops && overlay_ops->mode_set)
overlay_ops->mode_set(manager->dev, overlay);
}
}
}
static void exynos_drm_encoder_prepare(struct drm_encoder *encoder)
{
DRM_DEBUG_KMS("%s\n", __FILE__);
/* drm framework doesn't check NULL. */
}
static void exynos_drm_encoder_commit(struct drm_encoder *encoder)
{
struct exynos_drm_manager *manager = exynos_drm_get_manager(encoder);
struct exynos_drm_manager_ops *manager_ops = manager->ops;
DRM_DEBUG_KMS("%s\n", __FILE__);
if (manager_ops && manager_ops->commit)
manager_ops->commit(manager->dev);
}
static struct drm_crtc *
exynos_drm_encoder_get_crtc(struct drm_encoder *encoder)
{
return encoder->crtc;
}
static struct drm_encoder_helper_funcs exynos_encoder_helper_funcs = {
.dpms = exynos_drm_encoder_dpms,
.mode_fixup = exynos_drm_encoder_mode_fixup,
.mode_set = exynos_drm_encoder_mode_set,
.prepare = exynos_drm_encoder_prepare,
.commit = exynos_drm_encoder_commit,
.get_crtc = exynos_drm_encoder_get_crtc,
};
static void exynos_drm_encoder_destroy(struct drm_encoder *encoder)
{
struct exynos_drm_encoder *exynos_encoder =
to_exynos_encoder(encoder);
DRM_DEBUG_KMS("%s\n", __FILE__);
exynos_encoder->manager->pipe = -1;
drm_encoder_cleanup(encoder);
kfree(exynos_encoder);
}
static struct drm_encoder_funcs exynos_encoder_funcs = {
.destroy = exynos_drm_encoder_destroy,
};
static unsigned int exynos_drm_encoder_clones(struct drm_encoder *encoder)
{
struct drm_encoder *clone;
struct drm_device *dev = encoder->dev;
struct exynos_drm_encoder *exynos_encoder = to_exynos_encoder(encoder);
struct exynos_drm_display_ops *display_ops =
exynos_encoder->manager->display_ops;
unsigned int clone_mask = 0;
int cnt = 0;
list_for_each_entry(clone, &dev->mode_config.encoder_list, head) {
switch (display_ops->type) {
case EXYNOS_DISPLAY_TYPE_LCD:
case EXYNOS_DISPLAY_TYPE_HDMI:
case EXYNOS_DISPLAY_TYPE_VIDI:
clone_mask |= (1 << (cnt++));
break;
default:
continue;
}
}
return clone_mask;
}
void exynos_drm_encoder_setup(struct drm_device *dev)
{
struct drm_encoder *encoder;
DRM_DEBUG_KMS("%s\n", __FILE__);
list_for_each_entry(encoder, &dev->mode_config.encoder_list, head)
encoder->possible_clones = exynos_drm_encoder_clones(encoder);
}
struct drm_encoder *
exynos_drm_encoder_create(struct drm_device *dev,
struct exynos_drm_manager *manager,
unsigned int possible_crtcs)
{
struct drm_encoder *encoder;
struct exynos_drm_encoder *exynos_encoder;
DRM_DEBUG_KMS("%s\n", __FILE__);
if (!manager || !possible_crtcs)
return NULL;
if (!manager->dev)
return NULL;
exynos_encoder = kzalloc(sizeof(*exynos_encoder), GFP_KERNEL);
if (!exynos_encoder) {
DRM_ERROR("failed to allocate encoder\n");
return NULL;
}
exynos_encoder->dpms = DRM_MODE_DPMS_OFF;
exynos_encoder->manager = manager;
encoder = &exynos_encoder->drm_encoder;
encoder->possible_crtcs = possible_crtcs;
DRM_DEBUG_KMS("possible_crtcs = 0x%x\n", encoder->possible_crtcs);
drm_encoder_init(dev, encoder, &exynos_encoder_funcs,
DRM_MODE_ENCODER_TMDS);
drm_encoder_helper_add(encoder, &exynos_encoder_helper_funcs);
DRM_DEBUG_KMS("encoder has been created\n");
return encoder;
}
struct exynos_drm_manager *exynos_drm_get_manager(struct drm_encoder *encoder)
{
return to_exynos_encoder(encoder)->manager;
}
void exynos_drm_fn_encoder(struct drm_crtc *crtc, void *data,
void (*fn)(struct drm_encoder *, void *))
{
struct drm_device *dev = crtc->dev;
struct drm_encoder *encoder;
struct exynos_drm_private *private = dev->dev_private;
struct exynos_drm_manager *manager;
list_for_each_entry(encoder, &dev->mode_config.encoder_list, head) {
/*
* if crtc is detached from encoder, check pipe,
* otherwise check crtc attached to encoder
*/
if (!encoder->crtc) {
manager = to_exynos_encoder(encoder)->manager;
if (manager->pipe < 0 ||
private->crtc[manager->pipe] != crtc)
continue;
} else {
if (encoder->crtc != crtc)
continue;
}
fn(encoder, data);
}
}
void exynos_drm_enable_vblank(struct drm_encoder *encoder, void *data)
{
struct exynos_drm_manager *manager =
to_exynos_encoder(encoder)->manager;
struct exynos_drm_manager_ops *manager_ops = manager->ops;
int crtc = *(int *)data;
if (manager->pipe == -1)
manager->pipe = crtc;
if (manager_ops->enable_vblank)
manager_ops->enable_vblank(manager->dev);
}
void exynos_drm_disable_vblank(struct drm_encoder *encoder, void *data)
{
struct exynos_drm_manager *manager =
to_exynos_encoder(encoder)->manager;
struct exynos_drm_manager_ops *manager_ops = manager->ops;
int crtc = *(int *)data;
if (manager->pipe == -1)
manager->pipe = crtc;
if (manager_ops->disable_vblank)
manager_ops->disable_vblank(manager->dev);
}
void exynos_drm_encoder_crtc_plane_commit(struct drm_encoder *encoder,
void *data)
{
struct exynos_drm_manager *manager =
to_exynos_encoder(encoder)->manager;
struct exynos_drm_overlay_ops *overlay_ops = manager->overlay_ops;
int zpos = DEFAULT_ZPOS;
if (data)
zpos = *(int *)data;
if (overlay_ops && overlay_ops->commit)
overlay_ops->commit(manager->dev, zpos);
}
void exynos_drm_encoder_crtc_commit(struct drm_encoder *encoder, void *data)
{
struct exynos_drm_manager *manager =
to_exynos_encoder(encoder)->manager;
int crtc = *(int *)data;
int zpos = DEFAULT_ZPOS;
DRM_DEBUG_KMS("%s\n", __FILE__);
/*
* when crtc is detached from encoder, this pipe is used
* to select manager operation
*/
manager->pipe = crtc;
exynos_drm_encoder_crtc_plane_commit(encoder, &zpos);
}
void exynos_drm_encoder_dpms_from_crtc(struct drm_encoder *encoder, void *data)
{
struct exynos_drm_encoder *exynos_encoder = to_exynos_encoder(encoder);
int mode = *(int *)data;
DRM_DEBUG_KMS("%s\n", __FILE__);
exynos_drm_encoder_dpms(encoder, mode);
exynos_encoder->dpms = mode;
}
void exynos_drm_encoder_crtc_dpms(struct drm_encoder *encoder, void *data)
{
struct drm_device *dev = encoder->dev;
struct exynos_drm_encoder *exynos_encoder = to_exynos_encoder(encoder);
struct exynos_drm_manager *manager = exynos_encoder->manager;
struct exynos_drm_manager_ops *manager_ops = manager->ops;
struct drm_connector *connector;
int mode = *(int *)data;
DRM_DEBUG_KMS("%s\n", __FILE__);
if (manager_ops && manager_ops->dpms)
manager_ops->dpms(manager->dev, mode);
/*
* set current dpms mode to the connector connected to
* current encoder. connector->dpms would be checked
* at drm_helper_connector_dpms()
*/
list_for_each_entry(connector, &dev->mode_config.connector_list, head)
if (connector->encoder == encoder)
connector->dpms = mode;
/*
* if this condition is ok then it means that the crtc is already
* detached from encoder and last function for detaching is properly
* done, so clear pipe from manager to prevent repeated call.
*/
if (mode > DRM_MODE_DPMS_ON) {
if (!encoder->crtc)
manager->pipe = -1;
}
}
void exynos_drm_encoder_crtc_mode_set(struct drm_encoder *encoder, void *data)
{
struct exynos_drm_manager *manager =
to_exynos_encoder(encoder)->manager;
struct exynos_drm_overlay_ops *overlay_ops = manager->overlay_ops;
struct exynos_drm_overlay *overlay = data;
if (overlay_ops && overlay_ops->mode_set)
overlay_ops->mode_set(manager->dev, overlay);
}
void exynos_drm_encoder_crtc_disable(struct drm_encoder *encoder, void *data)
{
struct exynos_drm_manager *manager =
to_exynos_encoder(encoder)->manager;
struct exynos_drm_overlay_ops *overlay_ops = manager->overlay_ops;
int zpos = DEFAULT_ZPOS;
DRM_DEBUG_KMS("\n");
if (data)
zpos = *(int *)data;
if (overlay_ops && overlay_ops->disable)
overlay_ops->disable(manager->dev, zpos);
}
| gpl-2.0 |
emansih/d855_CM_kernel | arch/arm/mach-omap2/vp44xx_data.c | 5033 | 2909 | /*
* OMAP3 Voltage Processor (VP) data
*
* Copyright (C) 2007, 2010 Texas Instruments, Inc.
* Rajendra Nayak <rnayak@ti.com>
* Lesly A M <x0080970@ti.com>
* Thara Gopinath <thara@ti.com>
*
* Copyright (C) 2008, 2011 Nokia Corporation
* Kalle Jokiniemi
* Paul Walmsley
*
* 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/err.h>
#include <linux/init.h>
#include "common.h"
#include "prm44xx.h"
#include "prm-regbits-44xx.h"
#include "voltage.h"
#include "vp.h"
static const struct omap_vp_ops omap4_vp_ops = {
.check_txdone = omap4_prm_vp_check_txdone,
.clear_txdone = omap4_prm_vp_clear_txdone,
};
/*
* VP data common to 44xx chips
* XXX This stuff presumably belongs in the vp44xx.c or vp.c file.
*/
static const struct omap_vp_common omap4_vp_common = {
.vpconfig_erroroffset_mask = OMAP4430_ERROROFFSET_MASK,
.vpconfig_errorgain_mask = OMAP4430_ERRORGAIN_MASK,
.vpconfig_initvoltage_mask = OMAP4430_INITVOLTAGE_MASK,
.vpconfig_timeouten = OMAP4430_TIMEOUTEN_MASK,
.vpconfig_initvdd = OMAP4430_INITVDD_MASK,
.vpconfig_forceupdate = OMAP4430_FORCEUPDATE_MASK,
.vpconfig_vpenable = OMAP4430_VPENABLE_MASK,
.vstepmin_smpswaittimemin_shift = OMAP4430_SMPSWAITTIMEMIN_SHIFT,
.vstepmax_smpswaittimemax_shift = OMAP4430_SMPSWAITTIMEMAX_SHIFT,
.vstepmin_stepmin_shift = OMAP4430_VSTEPMIN_SHIFT,
.vstepmax_stepmax_shift = OMAP4430_VSTEPMAX_SHIFT,
.vlimitto_vddmin_shift = OMAP4430_VDDMIN_SHIFT,
.vlimitto_vddmax_shift = OMAP4430_VDDMAX_SHIFT,
.vlimitto_timeout_shift = OMAP4430_TIMEOUT_SHIFT,
.vpvoltage_mask = OMAP4430_VPVOLTAGE_MASK,
.ops = &omap4_vp_ops,
};
struct omap_vp_instance omap4_vp_mpu = {
.id = OMAP4_VP_VDD_MPU_ID,
.common = &omap4_vp_common,
.vpconfig = OMAP4_PRM_VP_MPU_CONFIG_OFFSET,
.vstepmin = OMAP4_PRM_VP_MPU_VSTEPMIN_OFFSET,
.vstepmax = OMAP4_PRM_VP_MPU_VSTEPMAX_OFFSET,
.vlimitto = OMAP4_PRM_VP_MPU_VLIMITTO_OFFSET,
.vstatus = OMAP4_PRM_VP_MPU_STATUS_OFFSET,
.voltage = OMAP4_PRM_VP_MPU_VOLTAGE_OFFSET,
};
struct omap_vp_instance omap4_vp_iva = {
.id = OMAP4_VP_VDD_IVA_ID,
.common = &omap4_vp_common,
.vpconfig = OMAP4_PRM_VP_IVA_CONFIG_OFFSET,
.vstepmin = OMAP4_PRM_VP_IVA_VSTEPMIN_OFFSET,
.vstepmax = OMAP4_PRM_VP_IVA_VSTEPMAX_OFFSET,
.vlimitto = OMAP4_PRM_VP_IVA_VLIMITTO_OFFSET,
.vstatus = OMAP4_PRM_VP_IVA_STATUS_OFFSET,
.voltage = OMAP4_PRM_VP_IVA_VOLTAGE_OFFSET,
};
struct omap_vp_instance omap4_vp_core = {
.id = OMAP4_VP_VDD_CORE_ID,
.common = &omap4_vp_common,
.vpconfig = OMAP4_PRM_VP_CORE_CONFIG_OFFSET,
.vstepmin = OMAP4_PRM_VP_CORE_VSTEPMIN_OFFSET,
.vstepmax = OMAP4_PRM_VP_CORE_VSTEPMAX_OFFSET,
.vlimitto = OMAP4_PRM_VP_CORE_VLIMITTO_OFFSET,
.vstatus = OMAP4_PRM_VP_CORE_STATUS_OFFSET,
.voltage = OMAP4_PRM_VP_CORE_VOLTAGE_OFFSET,
};
| gpl-2.0 |
mdmower/android_kernel_htc_m7 | drivers/mfd/tps65912-irq.c | 8361 | 6305 | /*
* tps65912-irq.c -- TI TPS6591x
*
* Copyright 2011 Texas Instruments Inc.
*
* Author: Margarita Olaya <magi@slimlogic.co.uk>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This driver is based on wm8350 implementation.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/bug.h>
#include <linux/device.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/gpio.h>
#include <linux/mfd/tps65912.h>
static inline int irq_to_tps65912_irq(struct tps65912 *tps65912,
int irq)
{
return irq - tps65912->irq_base;
}
/*
* This is a threaded IRQ handler so can access I2C/SPI. Since the
* IRQ handler explicitly clears the IRQ it handles the IRQ line
* will be reasserted and the physical IRQ will be handled again if
* another interrupt is asserted while we run - in the normal course
* of events this is a rare occurrence so we save I2C/SPI reads. We're
* also assuming that it's rare to get lots of interrupts firing
* simultaneously so try to minimise I/O.
*/
static irqreturn_t tps65912_irq(int irq, void *irq_data)
{
struct tps65912 *tps65912 = irq_data;
u32 irq_sts;
u32 irq_mask;
u8 reg;
int i;
tps65912->read(tps65912, TPS65912_INT_STS, 1, ®);
irq_sts = reg;
tps65912->read(tps65912, TPS65912_INT_STS2, 1, ®);
irq_sts |= reg << 8;
tps65912->read(tps65912, TPS65912_INT_STS3, 1, ®);
irq_sts |= reg << 16;
tps65912->read(tps65912, TPS65912_INT_STS4, 1, ®);
irq_sts |= reg << 24;
tps65912->read(tps65912, TPS65912_INT_MSK, 1, ®);
irq_mask = reg;
tps65912->read(tps65912, TPS65912_INT_MSK2, 1, ®);
irq_mask |= reg << 8;
tps65912->read(tps65912, TPS65912_INT_MSK3, 1, ®);
irq_mask |= reg << 16;
tps65912->read(tps65912, TPS65912_INT_MSK4, 1, ®);
irq_mask |= reg << 24;
irq_sts &= ~irq_mask;
if (!irq_sts)
return IRQ_NONE;
for (i = 0; i < tps65912->irq_num; i++) {
if (!(irq_sts & (1 << i)))
continue;
handle_nested_irq(tps65912->irq_base + i);
}
/* Write the STS register back to clear IRQs we handled */
reg = irq_sts & 0xFF;
irq_sts >>= 8;
if (reg)
tps65912->write(tps65912, TPS65912_INT_STS, 1, ®);
reg = irq_sts & 0xFF;
irq_sts >>= 8;
if (reg)
tps65912->write(tps65912, TPS65912_INT_STS2, 1, ®);
reg = irq_sts & 0xFF;
irq_sts >>= 8;
if (reg)
tps65912->write(tps65912, TPS65912_INT_STS3, 1, ®);
reg = irq_sts & 0xFF;
if (reg)
tps65912->write(tps65912, TPS65912_INT_STS4, 1, ®);
return IRQ_HANDLED;
}
static void tps65912_irq_lock(struct irq_data *data)
{
struct tps65912 *tps65912 = irq_data_get_irq_chip_data(data);
mutex_lock(&tps65912->irq_lock);
}
static void tps65912_irq_sync_unlock(struct irq_data *data)
{
struct tps65912 *tps65912 = irq_data_get_irq_chip_data(data);
u32 reg_mask;
u8 reg;
tps65912->read(tps65912, TPS65912_INT_MSK, 1, ®);
reg_mask = reg;
tps65912->read(tps65912, TPS65912_INT_MSK2, 1, ®);
reg_mask |= reg << 8;
tps65912->read(tps65912, TPS65912_INT_MSK3, 1, ®);
reg_mask |= reg << 16;
tps65912->read(tps65912, TPS65912_INT_MSK4, 1, ®);
reg_mask |= reg << 24;
if (tps65912->irq_mask != reg_mask) {
reg = tps65912->irq_mask & 0xFF;
tps65912->write(tps65912, TPS65912_INT_MSK, 1, ®);
reg = tps65912->irq_mask >> 8 & 0xFF;
tps65912->write(tps65912, TPS65912_INT_MSK2, 1, ®);
reg = tps65912->irq_mask >> 16 & 0xFF;
tps65912->write(tps65912, TPS65912_INT_MSK3, 1, ®);
reg = tps65912->irq_mask >> 24 & 0xFF;
tps65912->write(tps65912, TPS65912_INT_MSK4, 1, ®);
}
mutex_unlock(&tps65912->irq_lock);
}
static void tps65912_irq_enable(struct irq_data *data)
{
struct tps65912 *tps65912 = irq_data_get_irq_chip_data(data);
tps65912->irq_mask &= ~(1 << irq_to_tps65912_irq(tps65912, data->irq));
}
static void tps65912_irq_disable(struct irq_data *data)
{
struct tps65912 *tps65912 = irq_data_get_irq_chip_data(data);
tps65912->irq_mask |= (1 << irq_to_tps65912_irq(tps65912, data->irq));
}
static struct irq_chip tps65912_irq_chip = {
.name = "tps65912",
.irq_bus_lock = tps65912_irq_lock,
.irq_bus_sync_unlock = tps65912_irq_sync_unlock,
.irq_disable = tps65912_irq_disable,
.irq_enable = tps65912_irq_enable,
};
int tps65912_irq_init(struct tps65912 *tps65912, int irq,
struct tps65912_platform_data *pdata)
{
int ret, cur_irq;
int flags = IRQF_ONESHOT;
u8 reg;
if (!irq) {
dev_warn(tps65912->dev, "No interrupt support, no core IRQ\n");
return 0;
}
if (!pdata || !pdata->irq_base) {
dev_warn(tps65912->dev, "No interrupt support, no IRQ base\n");
return 0;
}
/* Clear unattended interrupts */
tps65912->read(tps65912, TPS65912_INT_STS, 1, ®);
tps65912->write(tps65912, TPS65912_INT_STS, 1, ®);
tps65912->read(tps65912, TPS65912_INT_STS2, 1, ®);
tps65912->write(tps65912, TPS65912_INT_STS2, 1, ®);
tps65912->read(tps65912, TPS65912_INT_STS3, 1, ®);
tps65912->write(tps65912, TPS65912_INT_STS3, 1, ®);
tps65912->read(tps65912, TPS65912_INT_STS4, 1, ®);
tps65912->write(tps65912, TPS65912_INT_STS4, 1, ®);
/* Mask top level interrupts */
tps65912->irq_mask = 0xFFFFFFFF;
mutex_init(&tps65912->irq_lock);
tps65912->chip_irq = irq;
tps65912->irq_base = pdata->irq_base;
tps65912->irq_num = TPS65912_NUM_IRQ;
/* Register with genirq */
for (cur_irq = tps65912->irq_base;
cur_irq < tps65912->irq_num + tps65912->irq_base;
cur_irq++) {
irq_set_chip_data(cur_irq, tps65912);
irq_set_chip_and_handler(cur_irq, &tps65912_irq_chip,
handle_edge_irq);
irq_set_nested_thread(cur_irq, 1);
/* ARM needs us to explicitly flag the IRQ as valid
* and will set them noprobe when we do so. */
#ifdef CONFIG_ARM
set_irq_flags(cur_irq, IRQF_VALID);
#else
irq_set_noprobe(cur_irq);
#endif
}
ret = request_threaded_irq(irq, NULL, tps65912_irq, flags,
"tps65912", tps65912);
irq_set_irq_type(irq, IRQ_TYPE_LEVEL_LOW);
if (ret != 0)
dev_err(tps65912->dev, "Failed to request IRQ: %d\n", ret);
return ret;
}
int tps65912_irq_exit(struct tps65912 *tps65912)
{
free_irq(tps65912->chip_irq, tps65912);
return 0;
}
| gpl-2.0 |
rofehr/linux-wetek | drivers/isdn/act2000/capi.c | 9385 | 32045 | /* $Id: capi.c,v 1.9.6.2 2001/09/23 22:24:32 kai Exp $
*
* ISDN lowlevel-module for the IBM ISDN-S0 Active 2000.
* CAPI encoder/decoder
*
* Author Fritz Elfert
* Copyright by Fritz Elfert <fritz@isdn4linux.de>
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
* Thanks to Friedemann Baitinger and IBM Germany
*
*/
#include "act2000.h"
#include "capi.h"
static actcapi_msgdsc valid_msg[] = {
{{ 0x86, 0x02}, "DATA_B3_IND"}, /* DATA_B3_IND/CONF must be first because of speed!!! */
{{ 0x86, 0x01}, "DATA_B3_CONF"},
{{ 0x02, 0x01}, "CONNECT_CONF"},
{{ 0x02, 0x02}, "CONNECT_IND"},
{{ 0x09, 0x01}, "CONNECT_INFO_CONF"},
{{ 0x03, 0x02}, "CONNECT_ACTIVE_IND"},
{{ 0x04, 0x01}, "DISCONNECT_CONF"},
{{ 0x04, 0x02}, "DISCONNECT_IND"},
{{ 0x05, 0x01}, "LISTEN_CONF"},
{{ 0x06, 0x01}, "GET_PARAMS_CONF"},
{{ 0x07, 0x01}, "INFO_CONF"},
{{ 0x07, 0x02}, "INFO_IND"},
{{ 0x08, 0x01}, "DATA_CONF"},
{{ 0x08, 0x02}, "DATA_IND"},
{{ 0x40, 0x01}, "SELECT_B2_PROTOCOL_CONF"},
{{ 0x80, 0x01}, "SELECT_B3_PROTOCOL_CONF"},
{{ 0x81, 0x01}, "LISTEN_B3_CONF"},
{{ 0x82, 0x01}, "CONNECT_B3_CONF"},
{{ 0x82, 0x02}, "CONNECT_B3_IND"},
{{ 0x83, 0x02}, "CONNECT_B3_ACTIVE_IND"},
{{ 0x84, 0x01}, "DISCONNECT_B3_CONF"},
{{ 0x84, 0x02}, "DISCONNECT_B3_IND"},
{{ 0x85, 0x01}, "GET_B3_PARAMS_CONF"},
{{ 0x01, 0x01}, "RESET_B3_CONF"},
{{ 0x01, 0x02}, "RESET_B3_IND"},
/* {{ 0x87, 0x02, "HANDSET_IND"}, not implemented */
{{ 0xff, 0x01}, "MANUFACTURER_CONF"},
{{ 0xff, 0x02}, "MANUFACTURER_IND"},
#ifdef DEBUG_MSG
/* Requests */
{{ 0x01, 0x00}, "RESET_B3_REQ"},
{{ 0x02, 0x00}, "CONNECT_REQ"},
{{ 0x04, 0x00}, "DISCONNECT_REQ"},
{{ 0x05, 0x00}, "LISTEN_REQ"},
{{ 0x06, 0x00}, "GET_PARAMS_REQ"},
{{ 0x07, 0x00}, "INFO_REQ"},
{{ 0x08, 0x00}, "DATA_REQ"},
{{ 0x09, 0x00}, "CONNECT_INFO_REQ"},
{{ 0x40, 0x00}, "SELECT_B2_PROTOCOL_REQ"},
{{ 0x80, 0x00}, "SELECT_B3_PROTOCOL_REQ"},
{{ 0x81, 0x00}, "LISTEN_B3_REQ"},
{{ 0x82, 0x00}, "CONNECT_B3_REQ"},
{{ 0x84, 0x00}, "DISCONNECT_B3_REQ"},
{{ 0x85, 0x00}, "GET_B3_PARAMS_REQ"},
{{ 0x86, 0x00}, "DATA_B3_REQ"},
{{ 0xff, 0x00}, "MANUFACTURER_REQ"},
/* Responses */
{{ 0x01, 0x03}, "RESET_B3_RESP"},
{{ 0x02, 0x03}, "CONNECT_RESP"},
{{ 0x03, 0x03}, "CONNECT_ACTIVE_RESP"},
{{ 0x04, 0x03}, "DISCONNECT_RESP"},
{{ 0x07, 0x03}, "INFO_RESP"},
{{ 0x08, 0x03}, "DATA_RESP"},
{{ 0x82, 0x03}, "CONNECT_B3_RESP"},
{{ 0x83, 0x03}, "CONNECT_B3_ACTIVE_RESP"},
{{ 0x84, 0x03}, "DISCONNECT_B3_RESP"},
{{ 0x86, 0x03}, "DATA_B3_RESP"},
{{ 0xff, 0x03}, "MANUFACTURER_RESP"},
#endif
{{ 0x00, 0x00}, NULL},
};
#define num_valid_imsg 27 /* MANUFACTURER_IND */
/*
* Check for a valid incoming CAPI message.
* Return:
* 0 = Invalid message
* 1 = Valid message, no B-Channel-data
* 2 = Valid message, B-Channel-data
*/
int
actcapi_chkhdr(act2000_card *card, actcapi_msghdr *hdr)
{
int i;
if (hdr->applicationID != 1)
return 0;
if (hdr->len < 9)
return 0;
for (i = 0; i < num_valid_imsg; i++)
if ((hdr->cmd.cmd == valid_msg[i].cmd.cmd) &&
(hdr->cmd.subcmd == valid_msg[i].cmd.subcmd)) {
return (i ? 1 : 2);
}
return 0;
}
#define ACTCAPI_MKHDR(l, c, s) { \
skb = alloc_skb(l + 8, GFP_ATOMIC); \
if (skb) { \
m = (actcapi_msg *)skb_put(skb, l + 8); \
m->hdr.len = l + 8; \
m->hdr.applicationID = 1; \
m->hdr.cmd.cmd = c; \
m->hdr.cmd.subcmd = s; \
m->hdr.msgnum = actcapi_nextsmsg(card); \
} else m = NULL; \
}
#define ACTCAPI_CHKSKB if (!skb) { \
printk(KERN_WARNING "actcapi: alloc_skb failed\n"); \
return; \
}
#define ACTCAPI_QUEUE_TX { \
actcapi_debug_msg(skb, 1); \
skb_queue_tail(&card->sndq, skb); \
act2000_schedule_tx(card); \
}
int
actcapi_listen_req(act2000_card *card)
{
__u16 eazmask = 0;
int i;
actcapi_msg *m;
struct sk_buff *skb;
for (i = 0; i < ACT2000_BCH; i++)
eazmask |= card->bch[i].eazmask;
ACTCAPI_MKHDR(9, 0x05, 0x00);
if (!skb) {
printk(KERN_WARNING "actcapi: alloc_skb failed\n");
return -ENOMEM;
}
m->msg.listen_req.controller = 0;
m->msg.listen_req.infomask = 0x3f; /* All information */
m->msg.listen_req.eazmask = eazmask;
m->msg.listen_req.simask = (eazmask) ? 0x86 : 0; /* All SI's */
ACTCAPI_QUEUE_TX;
return 0;
}
int
actcapi_connect_req(act2000_card *card, act2000_chan *chan, char *phone,
char eaz, int si1, int si2)
{
actcapi_msg *m;
struct sk_buff *skb;
ACTCAPI_MKHDR((11 + strlen(phone)), 0x02, 0x00);
if (!skb) {
printk(KERN_WARNING "actcapi: alloc_skb failed\n");
chan->fsm_state = ACT2000_STATE_NULL;
return -ENOMEM;
}
m->msg.connect_req.controller = 0;
m->msg.connect_req.bchan = 0x83;
m->msg.connect_req.infomask = 0x3f;
m->msg.connect_req.si1 = si1;
m->msg.connect_req.si2 = si2;
m->msg.connect_req.eaz = eaz ? eaz : '0';
m->msg.connect_req.addr.len = strlen(phone) + 1;
m->msg.connect_req.addr.tnp = 0x81;
memcpy(m->msg.connect_req.addr.num, phone, strlen(phone));
chan->callref = m->hdr.msgnum;
ACTCAPI_QUEUE_TX;
return 0;
}
static void
actcapi_connect_b3_req(act2000_card *card, act2000_chan *chan)
{
actcapi_msg *m;
struct sk_buff *skb;
ACTCAPI_MKHDR(17, 0x82, 0x00);
ACTCAPI_CHKSKB;
m->msg.connect_b3_req.plci = chan->plci;
memset(&m->msg.connect_b3_req.ncpi, 0,
sizeof(m->msg.connect_b3_req.ncpi));
m->msg.connect_b3_req.ncpi.len = 13;
m->msg.connect_b3_req.ncpi.modulo = 8;
ACTCAPI_QUEUE_TX;
}
/*
* Set net type (1TR6) or (EDSS1)
*/
int
actcapi_manufacturer_req_net(act2000_card *card)
{
actcapi_msg *m;
struct sk_buff *skb;
ACTCAPI_MKHDR(5, 0xff, 0x00);
if (!skb) {
printk(KERN_WARNING "actcapi: alloc_skb failed\n");
return -ENOMEM;
}
m->msg.manufacturer_req_net.manuf_msg = 0x11;
m->msg.manufacturer_req_net.controller = 1;
m->msg.manufacturer_req_net.nettype = (card->ptype == ISDN_PTYPE_EURO) ? 1 : 0;
ACTCAPI_QUEUE_TX;
printk(KERN_INFO "act2000 %s: D-channel protocol now %s\n",
card->interface.id, (card->ptype == ISDN_PTYPE_EURO) ? "euro" : "1tr6");
card->interface.features &=
~(ISDN_FEATURE_P_UNKNOWN | ISDN_FEATURE_P_EURO | ISDN_FEATURE_P_1TR6);
card->interface.features |=
((card->ptype == ISDN_PTYPE_EURO) ? ISDN_FEATURE_P_EURO : ISDN_FEATURE_P_1TR6);
return 0;
}
/*
* Switch V.42 on or off
*/
#if 0
int
actcapi_manufacturer_req_v42(act2000_card *card, ulong arg)
{
actcapi_msg *m;
struct sk_buff *skb;
ACTCAPI_MKHDR(8, 0xff, 0x00);
if (!skb) {
printk(KERN_WARNING "actcapi: alloc_skb failed\n");
return -ENOMEM;
}
m->msg.manufacturer_req_v42.manuf_msg = 0x10;
m->msg.manufacturer_req_v42.controller = 0;
m->msg.manufacturer_req_v42.v42control = (arg ? 1 : 0);
ACTCAPI_QUEUE_TX;
return 0;
}
#endif /* 0 */
/*
* Set error-handler
*/
int
actcapi_manufacturer_req_errh(act2000_card *card)
{
actcapi_msg *m;
struct sk_buff *skb;
ACTCAPI_MKHDR(4, 0xff, 0x00);
if (!skb) {
printk(KERN_WARNING "actcapi: alloc_skb failed\n");
return -ENOMEM;
}
m->msg.manufacturer_req_err.manuf_msg = 0x03;
m->msg.manufacturer_req_err.controller = 0;
ACTCAPI_QUEUE_TX;
return 0;
}
/*
* Set MSN-Mapping.
*/
int
actcapi_manufacturer_req_msn(act2000_card *card)
{
msn_entry *p = card->msn_list;
actcapi_msg *m;
struct sk_buff *skb;
int len;
while (p) {
int i;
len = strlen(p->msn);
for (i = 0; i < 2; i++) {
ACTCAPI_MKHDR(6 + len, 0xff, 0x00);
if (!skb) {
printk(KERN_WARNING "actcapi: alloc_skb failed\n");
return -ENOMEM;
}
m->msg.manufacturer_req_msn.manuf_msg = 0x13 + i;
m->msg.manufacturer_req_msn.controller = 0;
m->msg.manufacturer_req_msn.msnmap.eaz = p->eaz;
m->msg.manufacturer_req_msn.msnmap.len = len;
memcpy(m->msg.manufacturer_req_msn.msnmap.msn, p->msn, len);
ACTCAPI_QUEUE_TX;
}
p = p->next;
}
return 0;
}
void
actcapi_select_b2_protocol_req(act2000_card *card, act2000_chan *chan)
{
actcapi_msg *m;
struct sk_buff *skb;
ACTCAPI_MKHDR(10, 0x40, 0x00);
ACTCAPI_CHKSKB;
m->msg.select_b2_protocol_req.plci = chan->plci;
memset(&m->msg.select_b2_protocol_req.dlpd, 0,
sizeof(m->msg.select_b2_protocol_req.dlpd));
m->msg.select_b2_protocol_req.dlpd.len = 6;
switch (chan->l2prot) {
case ISDN_PROTO_L2_TRANS:
m->msg.select_b2_protocol_req.protocol = 0x03;
m->msg.select_b2_protocol_req.dlpd.dlen = 4000;
break;
case ISDN_PROTO_L2_HDLC:
m->msg.select_b2_protocol_req.protocol = 0x02;
m->msg.select_b2_protocol_req.dlpd.dlen = 4000;
break;
case ISDN_PROTO_L2_X75I:
case ISDN_PROTO_L2_X75UI:
case ISDN_PROTO_L2_X75BUI:
m->msg.select_b2_protocol_req.protocol = 0x01;
m->msg.select_b2_protocol_req.dlpd.dlen = 4000;
m->msg.select_b2_protocol_req.dlpd.laa = 3;
m->msg.select_b2_protocol_req.dlpd.lab = 1;
m->msg.select_b2_protocol_req.dlpd.win = 7;
m->msg.select_b2_protocol_req.dlpd.modulo = 8;
break;
}
ACTCAPI_QUEUE_TX;
}
static void
actcapi_select_b3_protocol_req(act2000_card *card, act2000_chan *chan)
{
actcapi_msg *m;
struct sk_buff *skb;
ACTCAPI_MKHDR(17, 0x80, 0x00);
ACTCAPI_CHKSKB;
m->msg.select_b3_protocol_req.plci = chan->plci;
memset(&m->msg.select_b3_protocol_req.ncpd, 0,
sizeof(m->msg.select_b3_protocol_req.ncpd));
switch (chan->l3prot) {
case ISDN_PROTO_L3_TRANS:
m->msg.select_b3_protocol_req.protocol = 0x04;
m->msg.select_b3_protocol_req.ncpd.len = 13;
m->msg.select_b3_protocol_req.ncpd.modulo = 8;
break;
}
ACTCAPI_QUEUE_TX;
}
static void
actcapi_listen_b3_req(act2000_card *card, act2000_chan *chan)
{
actcapi_msg *m;
struct sk_buff *skb;
ACTCAPI_MKHDR(2, 0x81, 0x00);
ACTCAPI_CHKSKB;
m->msg.listen_b3_req.plci = chan->plci;
ACTCAPI_QUEUE_TX;
}
static void
actcapi_disconnect_req(act2000_card *card, act2000_chan *chan)
{
actcapi_msg *m;
struct sk_buff *skb;
ACTCAPI_MKHDR(3, 0x04, 0x00);
ACTCAPI_CHKSKB;
m->msg.disconnect_req.plci = chan->plci;
m->msg.disconnect_req.cause = 0;
ACTCAPI_QUEUE_TX;
}
void
actcapi_disconnect_b3_req(act2000_card *card, act2000_chan *chan)
{
actcapi_msg *m;
struct sk_buff *skb;
ACTCAPI_MKHDR(17, 0x84, 0x00);
ACTCAPI_CHKSKB;
m->msg.disconnect_b3_req.ncci = chan->ncci;
memset(&m->msg.disconnect_b3_req.ncpi, 0,
sizeof(m->msg.disconnect_b3_req.ncpi));
m->msg.disconnect_b3_req.ncpi.len = 13;
m->msg.disconnect_b3_req.ncpi.modulo = 8;
chan->fsm_state = ACT2000_STATE_BHWAIT;
ACTCAPI_QUEUE_TX;
}
void
actcapi_connect_resp(act2000_card *card, act2000_chan *chan, __u8 cause)
{
actcapi_msg *m;
struct sk_buff *skb;
ACTCAPI_MKHDR(3, 0x02, 0x03);
ACTCAPI_CHKSKB;
m->msg.connect_resp.plci = chan->plci;
m->msg.connect_resp.rejectcause = cause;
if (cause) {
chan->fsm_state = ACT2000_STATE_NULL;
chan->plci = 0x8000;
} else
chan->fsm_state = ACT2000_STATE_IWAIT;
ACTCAPI_QUEUE_TX;
}
static void
actcapi_connect_active_resp(act2000_card *card, act2000_chan *chan)
{
actcapi_msg *m;
struct sk_buff *skb;
ACTCAPI_MKHDR(2, 0x03, 0x03);
ACTCAPI_CHKSKB;
m->msg.connect_resp.plci = chan->plci;
if (chan->fsm_state == ACT2000_STATE_IWAIT)
chan->fsm_state = ACT2000_STATE_IBWAIT;
ACTCAPI_QUEUE_TX;
}
static void
actcapi_connect_b3_resp(act2000_card *card, act2000_chan *chan, __u8 rejectcause)
{
actcapi_msg *m;
struct sk_buff *skb;
ACTCAPI_MKHDR((rejectcause ? 3 : 17), 0x82, 0x03);
ACTCAPI_CHKSKB;
m->msg.connect_b3_resp.ncci = chan->ncci;
m->msg.connect_b3_resp.rejectcause = rejectcause;
if (!rejectcause) {
memset(&m->msg.connect_b3_resp.ncpi, 0,
sizeof(m->msg.connect_b3_resp.ncpi));
m->msg.connect_b3_resp.ncpi.len = 13;
m->msg.connect_b3_resp.ncpi.modulo = 8;
chan->fsm_state = ACT2000_STATE_BWAIT;
}
ACTCAPI_QUEUE_TX;
}
static void
actcapi_connect_b3_active_resp(act2000_card *card, act2000_chan *chan)
{
actcapi_msg *m;
struct sk_buff *skb;
ACTCAPI_MKHDR(2, 0x83, 0x03);
ACTCAPI_CHKSKB;
m->msg.connect_b3_active_resp.ncci = chan->ncci;
chan->fsm_state = ACT2000_STATE_ACTIVE;
ACTCAPI_QUEUE_TX;
}
static void
actcapi_info_resp(act2000_card *card, act2000_chan *chan)
{
actcapi_msg *m;
struct sk_buff *skb;
ACTCAPI_MKHDR(2, 0x07, 0x03);
ACTCAPI_CHKSKB;
m->msg.info_resp.plci = chan->plci;
ACTCAPI_QUEUE_TX;
}
static void
actcapi_disconnect_b3_resp(act2000_card *card, act2000_chan *chan)
{
actcapi_msg *m;
struct sk_buff *skb;
ACTCAPI_MKHDR(2, 0x84, 0x03);
ACTCAPI_CHKSKB;
m->msg.disconnect_b3_resp.ncci = chan->ncci;
chan->ncci = 0x8000;
chan->queued = 0;
ACTCAPI_QUEUE_TX;
}
static void
actcapi_disconnect_resp(act2000_card *card, act2000_chan *chan)
{
actcapi_msg *m;
struct sk_buff *skb;
ACTCAPI_MKHDR(2, 0x04, 0x03);
ACTCAPI_CHKSKB;
m->msg.disconnect_resp.plci = chan->plci;
chan->plci = 0x8000;
ACTCAPI_QUEUE_TX;
}
static int
new_plci(act2000_card *card, __u16 plci)
{
int i;
for (i = 0; i < ACT2000_BCH; i++)
if (card->bch[i].plci == 0x8000) {
card->bch[i].plci = plci;
return i;
}
return -1;
}
static int
find_plci(act2000_card *card, __u16 plci)
{
int i;
for (i = 0; i < ACT2000_BCH; i++)
if (card->bch[i].plci == plci)
return i;
return -1;
}
static int
find_ncci(act2000_card *card, __u16 ncci)
{
int i;
for (i = 0; i < ACT2000_BCH; i++)
if (card->bch[i].ncci == ncci)
return i;
return -1;
}
static int
find_dialing(act2000_card *card, __u16 callref)
{
int i;
for (i = 0; i < ACT2000_BCH; i++)
if ((card->bch[i].callref == callref) &&
(card->bch[i].fsm_state == ACT2000_STATE_OCALL))
return i;
return -1;
}
static int
actcapi_data_b3_ind(act2000_card *card, struct sk_buff *skb) {
__u16 plci;
__u16 ncci;
__u16 controller;
__u8 blocknr;
int chan;
actcapi_msg *msg = (actcapi_msg *)skb->data;
EVAL_NCCI(msg->msg.data_b3_ind.fakencci, plci, controller, ncci);
chan = find_ncci(card, ncci);
if (chan < 0)
return 0;
if (card->bch[chan].fsm_state != ACT2000_STATE_ACTIVE)
return 0;
if (card->bch[chan].plci != plci)
return 0;
blocknr = msg->msg.data_b3_ind.blocknr;
skb_pull(skb, 19);
card->interface.rcvcallb_skb(card->myid, chan, skb);
if (!(skb = alloc_skb(11, GFP_ATOMIC))) {
printk(KERN_WARNING "actcapi: alloc_skb failed\n");
return 1;
}
msg = (actcapi_msg *)skb_put(skb, 11);
msg->hdr.len = 11;
msg->hdr.applicationID = 1;
msg->hdr.cmd.cmd = 0x86;
msg->hdr.cmd.subcmd = 0x03;
msg->hdr.msgnum = actcapi_nextsmsg(card);
msg->msg.data_b3_resp.ncci = ncci;
msg->msg.data_b3_resp.blocknr = blocknr;
ACTCAPI_QUEUE_TX;
return 1;
}
/*
* Walk over ackq, unlink DATA_B3_REQ from it, if
* ncci and blocknr are matching.
* Decrement queued-bytes counter.
*/
static int
handle_ack(act2000_card *card, act2000_chan *chan, __u8 blocknr) {
unsigned long flags;
struct sk_buff *skb;
struct sk_buff *tmp;
struct actcapi_msg *m;
int ret = 0;
spin_lock_irqsave(&card->lock, flags);
skb = skb_peek(&card->ackq);
spin_unlock_irqrestore(&card->lock, flags);
if (!skb) {
printk(KERN_WARNING "act2000: handle_ack nothing found!\n");
return 0;
}
tmp = skb;
while (1) {
m = (actcapi_msg *)tmp->data;
if ((((m->msg.data_b3_req.fakencci >> 8) & 0xff) == chan->ncci) &&
(m->msg.data_b3_req.blocknr == blocknr)) {
/* found corresponding DATA_B3_REQ */
skb_unlink(tmp, &card->ackq);
chan->queued -= m->msg.data_b3_req.datalen;
if (m->msg.data_b3_req.flags)
ret = m->msg.data_b3_req.datalen;
dev_kfree_skb(tmp);
if (chan->queued < 0)
chan->queued = 0;
return ret;
}
spin_lock_irqsave(&card->lock, flags);
tmp = skb_peek((struct sk_buff_head *)tmp);
spin_unlock_irqrestore(&card->lock, flags);
if ((tmp == skb) || (tmp == NULL)) {
/* reached end of queue */
printk(KERN_WARNING "act2000: handle_ack nothing found!\n");
return 0;
}
}
}
void
actcapi_dispatch(struct work_struct *work)
{
struct act2000_card *card =
container_of(work, struct act2000_card, rcv_tq);
struct sk_buff *skb;
actcapi_msg *msg;
__u16 ccmd;
int chan;
int len;
act2000_chan *ctmp;
isdn_ctrl cmd;
char tmp[170];
while ((skb = skb_dequeue(&card->rcvq))) {
actcapi_debug_msg(skb, 0);
msg = (actcapi_msg *)skb->data;
ccmd = ((msg->hdr.cmd.cmd << 8) | msg->hdr.cmd.subcmd);
switch (ccmd) {
case 0x8602:
/* DATA_B3_IND */
if (actcapi_data_b3_ind(card, skb))
return;
break;
case 0x8601:
/* DATA_B3_CONF */
chan = find_ncci(card, msg->msg.data_b3_conf.ncci);
if ((chan >= 0) && (card->bch[chan].fsm_state == ACT2000_STATE_ACTIVE)) {
if (msg->msg.data_b3_conf.info != 0)
printk(KERN_WARNING "act2000: DATA_B3_CONF: %04x\n",
msg->msg.data_b3_conf.info);
len = handle_ack(card, &card->bch[chan],
msg->msg.data_b3_conf.blocknr);
if (len) {
cmd.driver = card->myid;
cmd.command = ISDN_STAT_BSENT;
cmd.arg = chan;
cmd.parm.length = len;
card->interface.statcallb(&cmd);
}
}
break;
case 0x0201:
/* CONNECT_CONF */
chan = find_dialing(card, msg->hdr.msgnum);
if (chan >= 0) {
if (msg->msg.connect_conf.info) {
card->bch[chan].fsm_state = ACT2000_STATE_NULL;
cmd.driver = card->myid;
cmd.command = ISDN_STAT_DHUP;
cmd.arg = chan;
card->interface.statcallb(&cmd);
} else {
card->bch[chan].fsm_state = ACT2000_STATE_OWAIT;
card->bch[chan].plci = msg->msg.connect_conf.plci;
}
}
break;
case 0x0202:
/* CONNECT_IND */
chan = new_plci(card, msg->msg.connect_ind.plci);
if (chan < 0) {
ctmp = (act2000_chan *)tmp;
ctmp->plci = msg->msg.connect_ind.plci;
actcapi_connect_resp(card, ctmp, 0x11); /* All Card-Cannels busy */
} else {
card->bch[chan].fsm_state = ACT2000_STATE_ICALL;
cmd.driver = card->myid;
cmd.command = ISDN_STAT_ICALL;
cmd.arg = chan;
cmd.parm.setup.si1 = msg->msg.connect_ind.si1;
cmd.parm.setup.si2 = msg->msg.connect_ind.si2;
if (card->ptype == ISDN_PTYPE_EURO)
strcpy(cmd.parm.setup.eazmsn,
act2000_find_eaz(card, msg->msg.connect_ind.eaz));
else {
cmd.parm.setup.eazmsn[0] = msg->msg.connect_ind.eaz;
cmd.parm.setup.eazmsn[1] = 0;
}
memset(cmd.parm.setup.phone, 0, sizeof(cmd.parm.setup.phone));
memcpy(cmd.parm.setup.phone, msg->msg.connect_ind.addr.num,
msg->msg.connect_ind.addr.len - 1);
cmd.parm.setup.plan = msg->msg.connect_ind.addr.tnp;
cmd.parm.setup.screen = 0;
if (card->interface.statcallb(&cmd) == 2)
actcapi_connect_resp(card, &card->bch[chan], 0x15); /* Reject Call */
}
break;
case 0x0302:
/* CONNECT_ACTIVE_IND */
chan = find_plci(card, msg->msg.connect_active_ind.plci);
if (chan >= 0)
switch (card->bch[chan].fsm_state) {
case ACT2000_STATE_IWAIT:
actcapi_connect_active_resp(card, &card->bch[chan]);
break;
case ACT2000_STATE_OWAIT:
actcapi_connect_active_resp(card, &card->bch[chan]);
actcapi_select_b2_protocol_req(card, &card->bch[chan]);
break;
}
break;
case 0x8202:
/* CONNECT_B3_IND */
chan = find_plci(card, msg->msg.connect_b3_ind.plci);
if ((chan >= 0) && (card->bch[chan].fsm_state == ACT2000_STATE_IBWAIT)) {
card->bch[chan].ncci = msg->msg.connect_b3_ind.ncci;
actcapi_connect_b3_resp(card, &card->bch[chan], 0);
} else {
ctmp = (act2000_chan *)tmp;
ctmp->ncci = msg->msg.connect_b3_ind.ncci;
actcapi_connect_b3_resp(card, ctmp, 0x11); /* All Card-Cannels busy */
}
break;
case 0x8302:
/* CONNECT_B3_ACTIVE_IND */
chan = find_ncci(card, msg->msg.connect_b3_active_ind.ncci);
if ((chan >= 0) && (card->bch[chan].fsm_state == ACT2000_STATE_BWAIT)) {
actcapi_connect_b3_active_resp(card, &card->bch[chan]);
cmd.driver = card->myid;
cmd.command = ISDN_STAT_BCONN;
cmd.arg = chan;
card->interface.statcallb(&cmd);
}
break;
case 0x8402:
/* DISCONNECT_B3_IND */
chan = find_ncci(card, msg->msg.disconnect_b3_ind.ncci);
if (chan >= 0) {
ctmp = &card->bch[chan];
actcapi_disconnect_b3_resp(card, ctmp);
switch (ctmp->fsm_state) {
case ACT2000_STATE_ACTIVE:
ctmp->fsm_state = ACT2000_STATE_DHWAIT2;
cmd.driver = card->myid;
cmd.command = ISDN_STAT_BHUP;
cmd.arg = chan;
card->interface.statcallb(&cmd);
break;
case ACT2000_STATE_BHWAIT2:
actcapi_disconnect_req(card, ctmp);
ctmp->fsm_state = ACT2000_STATE_DHWAIT;
cmd.driver = card->myid;
cmd.command = ISDN_STAT_BHUP;
cmd.arg = chan;
card->interface.statcallb(&cmd);
break;
}
}
break;
case 0x0402:
/* DISCONNECT_IND */
chan = find_plci(card, msg->msg.disconnect_ind.plci);
if (chan >= 0) {
ctmp = &card->bch[chan];
actcapi_disconnect_resp(card, ctmp);
ctmp->fsm_state = ACT2000_STATE_NULL;
cmd.driver = card->myid;
cmd.command = ISDN_STAT_DHUP;
cmd.arg = chan;
card->interface.statcallb(&cmd);
} else {
ctmp = (act2000_chan *)tmp;
ctmp->plci = msg->msg.disconnect_ind.plci;
actcapi_disconnect_resp(card, ctmp);
}
break;
case 0x4001:
/* SELECT_B2_PROTOCOL_CONF */
chan = find_plci(card, msg->msg.select_b2_protocol_conf.plci);
if (chan >= 0)
switch (card->bch[chan].fsm_state) {
case ACT2000_STATE_ICALL:
case ACT2000_STATE_OWAIT:
ctmp = &card->bch[chan];
if (msg->msg.select_b2_protocol_conf.info == 0)
actcapi_select_b3_protocol_req(card, ctmp);
else {
ctmp->fsm_state = ACT2000_STATE_NULL;
cmd.driver = card->myid;
cmd.command = ISDN_STAT_DHUP;
cmd.arg = chan;
card->interface.statcallb(&cmd);
}
break;
}
break;
case 0x8001:
/* SELECT_B3_PROTOCOL_CONF */
chan = find_plci(card, msg->msg.select_b3_protocol_conf.plci);
if (chan >= 0)
switch (card->bch[chan].fsm_state) {
case ACT2000_STATE_ICALL:
case ACT2000_STATE_OWAIT:
ctmp = &card->bch[chan];
if (msg->msg.select_b3_protocol_conf.info == 0)
actcapi_listen_b3_req(card, ctmp);
else {
ctmp->fsm_state = ACT2000_STATE_NULL;
cmd.driver = card->myid;
cmd.command = ISDN_STAT_DHUP;
cmd.arg = chan;
card->interface.statcallb(&cmd);
}
}
break;
case 0x8101:
/* LISTEN_B3_CONF */
chan = find_plci(card, msg->msg.listen_b3_conf.plci);
if (chan >= 0)
switch (card->bch[chan].fsm_state) {
case ACT2000_STATE_ICALL:
ctmp = &card->bch[chan];
if (msg->msg.listen_b3_conf.info == 0)
actcapi_connect_resp(card, ctmp, 0);
else {
ctmp->fsm_state = ACT2000_STATE_NULL;
cmd.driver = card->myid;
cmd.command = ISDN_STAT_DHUP;
cmd.arg = chan;
card->interface.statcallb(&cmd);
}
break;
case ACT2000_STATE_OWAIT:
ctmp = &card->bch[chan];
if (msg->msg.listen_b3_conf.info == 0) {
actcapi_connect_b3_req(card, ctmp);
ctmp->fsm_state = ACT2000_STATE_OBWAIT;
cmd.driver = card->myid;
cmd.command = ISDN_STAT_DCONN;
cmd.arg = chan;
card->interface.statcallb(&cmd);
} else {
ctmp->fsm_state = ACT2000_STATE_NULL;
cmd.driver = card->myid;
cmd.command = ISDN_STAT_DHUP;
cmd.arg = chan;
card->interface.statcallb(&cmd);
}
break;
}
break;
case 0x8201:
/* CONNECT_B3_CONF */
chan = find_plci(card, msg->msg.connect_b3_conf.plci);
if ((chan >= 0) && (card->bch[chan].fsm_state == ACT2000_STATE_OBWAIT)) {
ctmp = &card->bch[chan];
if (msg->msg.connect_b3_conf.info) {
ctmp->fsm_state = ACT2000_STATE_NULL;
cmd.driver = card->myid;
cmd.command = ISDN_STAT_DHUP;
cmd.arg = chan;
card->interface.statcallb(&cmd);
} else {
ctmp->ncci = msg->msg.connect_b3_conf.ncci;
ctmp->fsm_state = ACT2000_STATE_BWAIT;
}
}
break;
case 0x8401:
/* DISCONNECT_B3_CONF */
chan = find_ncci(card, msg->msg.disconnect_b3_conf.ncci);
if ((chan >= 0) && (card->bch[chan].fsm_state == ACT2000_STATE_BHWAIT))
card->bch[chan].fsm_state = ACT2000_STATE_BHWAIT2;
break;
case 0x0702:
/* INFO_IND */
chan = find_plci(card, msg->msg.info_ind.plci);
if (chan >= 0)
/* TODO: Eval Charging info / cause */
actcapi_info_resp(card, &card->bch[chan]);
break;
case 0x0401:
/* LISTEN_CONF */
case 0x0501:
/* LISTEN_CONF */
case 0xff01:
/* MANUFACTURER_CONF */
break;
case 0xff02:
/* MANUFACTURER_IND */
if (msg->msg.manuf_msg == 3) {
memset(tmp, 0, sizeof(tmp));
strncpy(tmp,
&msg->msg.manufacturer_ind_err.errstring,
msg->hdr.len - 16);
if (msg->msg.manufacturer_ind_err.errcode)
printk(KERN_WARNING "act2000: %s\n", tmp);
else {
printk(KERN_DEBUG "act2000: %s\n", tmp);
if ((!strncmp(tmp, "INFO: Trace buffer con", 22)) ||
(!strncmp(tmp, "INFO: Compile Date/Tim", 22))) {
card->flags |= ACT2000_FLAGS_RUNNING;
cmd.command = ISDN_STAT_RUN;
cmd.driver = card->myid;
cmd.arg = 0;
actcapi_manufacturer_req_net(card);
actcapi_manufacturer_req_msn(card);
actcapi_listen_req(card);
card->interface.statcallb(&cmd);
}
}
}
break;
default:
printk(KERN_WARNING "act2000: UNHANDLED Message %04x\n", ccmd);
break;
}
dev_kfree_skb(skb);
}
}
#ifdef DEBUG_MSG
static void
actcapi_debug_caddr(actcapi_addr *addr)
{
char tmp[30];
printk(KERN_DEBUG " Alen = %d\n", addr->len);
if (addr->len > 0)
printk(KERN_DEBUG " Atnp = 0x%02x\n", addr->tnp);
if (addr->len > 1) {
memset(tmp, 0, 30);
memcpy(tmp, addr->num, addr->len - 1);
printk(KERN_DEBUG " Anum = '%s'\n", tmp);
}
}
static void
actcapi_debug_ncpi(actcapi_ncpi *ncpi)
{
printk(KERN_DEBUG " ncpi.len = %d\n", ncpi->len);
if (ncpi->len >= 2)
printk(KERN_DEBUG " ncpi.lic = 0x%04x\n", ncpi->lic);
if (ncpi->len >= 4)
printk(KERN_DEBUG " ncpi.hic = 0x%04x\n", ncpi->hic);
if (ncpi->len >= 6)
printk(KERN_DEBUG " ncpi.ltc = 0x%04x\n", ncpi->ltc);
if (ncpi->len >= 8)
printk(KERN_DEBUG " ncpi.htc = 0x%04x\n", ncpi->htc);
if (ncpi->len >= 10)
printk(KERN_DEBUG " ncpi.loc = 0x%04x\n", ncpi->loc);
if (ncpi->len >= 12)
printk(KERN_DEBUG " ncpi.hoc = 0x%04x\n", ncpi->hoc);
if (ncpi->len >= 13)
printk(KERN_DEBUG " ncpi.mod = %d\n", ncpi->modulo);
}
static void
actcapi_debug_dlpd(actcapi_dlpd *dlpd)
{
printk(KERN_DEBUG " dlpd.len = %d\n", dlpd->len);
if (dlpd->len >= 2)
printk(KERN_DEBUG " dlpd.dlen = 0x%04x\n", dlpd->dlen);
if (dlpd->len >= 3)
printk(KERN_DEBUG " dlpd.laa = 0x%02x\n", dlpd->laa);
if (dlpd->len >= 4)
printk(KERN_DEBUG " dlpd.lab = 0x%02x\n", dlpd->lab);
if (dlpd->len >= 5)
printk(KERN_DEBUG " dlpd.modulo = %d\n", dlpd->modulo);
if (dlpd->len >= 6)
printk(KERN_DEBUG " dlpd.win = %d\n", dlpd->win);
}
#ifdef DEBUG_DUMP_SKB
static void dump_skb(struct sk_buff *skb) {
char tmp[80];
char *p = skb->data;
char *t = tmp;
int i;
for (i = 0; i < skb->len; i++) {
t += sprintf(t, "%02x ", *p++ & 0xff);
if ((i & 0x0f) == 8) {
printk(KERN_DEBUG "dump: %s\n", tmp);
t = tmp;
}
}
if (i & 0x07)
printk(KERN_DEBUG "dump: %s\n", tmp);
}
#endif
void
actcapi_debug_msg(struct sk_buff *skb, int direction)
{
actcapi_msg *msg = (actcapi_msg *)skb->data;
char *descr;
int i;
char tmp[170];
#ifndef DEBUG_DATA_MSG
if (msg->hdr.cmd.cmd == 0x86)
return;
#endif
descr = "INVALID";
#ifdef DEBUG_DUMP_SKB
dump_skb(skb);
#endif
for (i = 0; i < ARRAY_SIZE(valid_msg); i++)
if ((msg->hdr.cmd.cmd == valid_msg[i].cmd.cmd) &&
(msg->hdr.cmd.subcmd == valid_msg[i].cmd.subcmd)) {
descr = valid_msg[i].description;
break;
}
printk(KERN_DEBUG "%s %s msg\n", direction ? "Outgoing" : "Incoming", descr);
printk(KERN_DEBUG " ApplID = %d\n", msg->hdr.applicationID);
printk(KERN_DEBUG " Len = %d\n", msg->hdr.len);
printk(KERN_DEBUG " MsgNum = 0x%04x\n", msg->hdr.msgnum);
printk(KERN_DEBUG " Cmd = 0x%02x\n", msg->hdr.cmd.cmd);
printk(KERN_DEBUG " SubCmd = 0x%02x\n", msg->hdr.cmd.subcmd);
switch (i) {
case 0:
/* DATA B3 IND */
printk(KERN_DEBUG " BLOCK = 0x%02x\n",
msg->msg.data_b3_ind.blocknr);
break;
case 2:
/* CONNECT CONF */
printk(KERN_DEBUG " PLCI = 0x%04x\n",
msg->msg.connect_conf.plci);
printk(KERN_DEBUG " Info = 0x%04x\n",
msg->msg.connect_conf.info);
break;
case 3:
/* CONNECT IND */
printk(KERN_DEBUG " PLCI = 0x%04x\n",
msg->msg.connect_ind.plci);
printk(KERN_DEBUG " Contr = %d\n",
msg->msg.connect_ind.controller);
printk(KERN_DEBUG " SI1 = %d\n",
msg->msg.connect_ind.si1);
printk(KERN_DEBUG " SI2 = %d\n",
msg->msg.connect_ind.si2);
printk(KERN_DEBUG " EAZ = '%c'\n",
msg->msg.connect_ind.eaz);
actcapi_debug_caddr(&msg->msg.connect_ind.addr);
break;
case 5:
/* CONNECT ACTIVE IND */
printk(KERN_DEBUG " PLCI = 0x%04x\n",
msg->msg.connect_active_ind.plci);
actcapi_debug_caddr(&msg->msg.connect_active_ind.addr);
break;
case 8:
/* LISTEN CONF */
printk(KERN_DEBUG " Contr = %d\n",
msg->msg.listen_conf.controller);
printk(KERN_DEBUG " Info = 0x%04x\n",
msg->msg.listen_conf.info);
break;
case 11:
/* INFO IND */
printk(KERN_DEBUG " PLCI = 0x%04x\n",
msg->msg.info_ind.plci);
printk(KERN_DEBUG " Imsk = 0x%04x\n",
msg->msg.info_ind.nr.mask);
if (msg->hdr.len > 12) {
int l = msg->hdr.len - 12;
int j;
char *p = tmp;
for (j = 0; j < l; j++)
p += sprintf(p, "%02x ", msg->msg.info_ind.el.display[j]);
printk(KERN_DEBUG " D = '%s'\n", tmp);
}
break;
case 14:
/* SELECT B2 PROTOCOL CONF */
printk(KERN_DEBUG " PLCI = 0x%04x\n",
msg->msg.select_b2_protocol_conf.plci);
printk(KERN_DEBUG " Info = 0x%04x\n",
msg->msg.select_b2_protocol_conf.info);
break;
case 15:
/* SELECT B3 PROTOCOL CONF */
printk(KERN_DEBUG " PLCI = 0x%04x\n",
msg->msg.select_b3_protocol_conf.plci);
printk(KERN_DEBUG " Info = 0x%04x\n",
msg->msg.select_b3_protocol_conf.info);
break;
case 16:
/* LISTEN B3 CONF */
printk(KERN_DEBUG " PLCI = 0x%04x\n",
msg->msg.listen_b3_conf.plci);
printk(KERN_DEBUG " Info = 0x%04x\n",
msg->msg.listen_b3_conf.info);
break;
case 18:
/* CONNECT B3 IND */
printk(KERN_DEBUG " NCCI = 0x%04x\n",
msg->msg.connect_b3_ind.ncci);
printk(KERN_DEBUG " PLCI = 0x%04x\n",
msg->msg.connect_b3_ind.plci);
actcapi_debug_ncpi(&msg->msg.connect_b3_ind.ncpi);
break;
case 19:
/* CONNECT B3 ACTIVE IND */
printk(KERN_DEBUG " NCCI = 0x%04x\n",
msg->msg.connect_b3_active_ind.ncci);
actcapi_debug_ncpi(&msg->msg.connect_b3_active_ind.ncpi);
break;
case 26:
/* MANUFACTURER IND */
printk(KERN_DEBUG " Mmsg = 0x%02x\n",
msg->msg.manufacturer_ind_err.manuf_msg);
switch (msg->msg.manufacturer_ind_err.manuf_msg) {
case 3:
printk(KERN_DEBUG " Contr = %d\n",
msg->msg.manufacturer_ind_err.controller);
printk(KERN_DEBUG " Code = 0x%08x\n",
msg->msg.manufacturer_ind_err.errcode);
memset(tmp, 0, sizeof(tmp));
strncpy(tmp, &msg->msg.manufacturer_ind_err.errstring,
msg->hdr.len - 16);
printk(KERN_DEBUG " Emsg = '%s'\n", tmp);
break;
}
break;
case 30:
/* LISTEN REQ */
printk(KERN_DEBUG " Imsk = 0x%08x\n",
msg->msg.listen_req.infomask);
printk(KERN_DEBUG " Emsk = 0x%04x\n",
msg->msg.listen_req.eazmask);
printk(KERN_DEBUG " Smsk = 0x%04x\n",
msg->msg.listen_req.simask);
break;
case 35:
/* SELECT_B2_PROTOCOL_REQ */
printk(KERN_DEBUG " PLCI = 0x%04x\n",
msg->msg.select_b2_protocol_req.plci);
printk(KERN_DEBUG " prot = 0x%02x\n",
msg->msg.select_b2_protocol_req.protocol);
if (msg->hdr.len >= 11)
printk(KERN_DEBUG "No dlpd\n");
else
actcapi_debug_dlpd(&msg->msg.select_b2_protocol_req.dlpd);
break;
case 44:
/* CONNECT RESP */
printk(KERN_DEBUG " PLCI = 0x%04x\n",
msg->msg.connect_resp.plci);
printk(KERN_DEBUG " CAUSE = 0x%02x\n",
msg->msg.connect_resp.rejectcause);
break;
case 45:
/* CONNECT ACTIVE RESP */
printk(KERN_DEBUG " PLCI = 0x%04x\n",
msg->msg.connect_active_resp.plci);
break;
}
}
#endif
| gpl-2.0 |
TeamBliss-Devices/android_kernel_lge_vk810 | drivers/scsi/bfa/bfa_hw_cb.c | 9897 | 4748 | /*
* Copyright (c) 2005-2010 Brocade Communications Systems, Inc.
* All rights reserved
* www.brocade.com
*
* Linux driver for Brocade Fibre Channel Host Bus Adapter.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License (GPL) Version 2 as
* published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*/
#include "bfad_drv.h"
#include "bfa_modules.h"
#include "bfi_reg.h"
void
bfa_hwcb_reginit(struct bfa_s *bfa)
{
struct bfa_iocfc_regs_s *bfa_regs = &bfa->iocfc.bfa_regs;
void __iomem *kva = bfa_ioc_bar0(&bfa->ioc);
int fn = bfa_ioc_pcifn(&bfa->ioc);
if (fn == 0) {
bfa_regs->intr_status = (kva + HOSTFN0_INT_STATUS);
bfa_regs->intr_mask = (kva + HOSTFN0_INT_MSK);
} else {
bfa_regs->intr_status = (kva + HOSTFN1_INT_STATUS);
bfa_regs->intr_mask = (kva + HOSTFN1_INT_MSK);
}
}
static void
bfa_hwcb_reqq_ack_msix(struct bfa_s *bfa, int reqq)
{
writel(__HFN_INT_CPE_Q0 << CPE_Q_NUM(bfa_ioc_pcifn(&bfa->ioc), reqq),
bfa->iocfc.bfa_regs.intr_status);
}
/*
* Actions to respond RME Interrupt for Crossbow ASIC:
* - Write 1 to Interrupt Status register
* INTX - done in bfa_intx()
* MSIX - done in bfa_hwcb_rspq_ack_msix()
* - Update CI (only if new CI)
*/
static void
bfa_hwcb_rspq_ack_msix(struct bfa_s *bfa, int rspq, u32 ci)
{
writel(__HFN_INT_RME_Q0 << RME_Q_NUM(bfa_ioc_pcifn(&bfa->ioc), rspq),
bfa->iocfc.bfa_regs.intr_status);
if (bfa_rspq_ci(bfa, rspq) == ci)
return;
bfa_rspq_ci(bfa, rspq) = ci;
writel(ci, bfa->iocfc.bfa_regs.rme_q_ci[rspq]);
mmiowb();
}
void
bfa_hwcb_rspq_ack(struct bfa_s *bfa, int rspq, u32 ci)
{
if (bfa_rspq_ci(bfa, rspq) == ci)
return;
bfa_rspq_ci(bfa, rspq) = ci;
writel(ci, bfa->iocfc.bfa_regs.rme_q_ci[rspq]);
mmiowb();
}
void
bfa_hwcb_msix_getvecs(struct bfa_s *bfa, u32 *msix_vecs_bmap,
u32 *num_vecs, u32 *max_vec_bit)
{
#define __HFN_NUMINTS 13
if (bfa_ioc_pcifn(&bfa->ioc) == 0) {
*msix_vecs_bmap = (__HFN_INT_CPE_Q0 | __HFN_INT_CPE_Q1 |
__HFN_INT_CPE_Q2 | __HFN_INT_CPE_Q3 |
__HFN_INT_RME_Q0 | __HFN_INT_RME_Q1 |
__HFN_INT_RME_Q2 | __HFN_INT_RME_Q3 |
__HFN_INT_MBOX_LPU0);
*max_vec_bit = __HFN_INT_MBOX_LPU0;
} else {
*msix_vecs_bmap = (__HFN_INT_CPE_Q4 | __HFN_INT_CPE_Q5 |
__HFN_INT_CPE_Q6 | __HFN_INT_CPE_Q7 |
__HFN_INT_RME_Q4 | __HFN_INT_RME_Q5 |
__HFN_INT_RME_Q6 | __HFN_INT_RME_Q7 |
__HFN_INT_MBOX_LPU1);
*max_vec_bit = __HFN_INT_MBOX_LPU1;
}
*msix_vecs_bmap |= (__HFN_INT_ERR_EMC | __HFN_INT_ERR_LPU0 |
__HFN_INT_ERR_LPU1 | __HFN_INT_ERR_PSS);
*num_vecs = __HFN_NUMINTS;
}
/*
* Dummy interrupt handler for handling spurious interrupts.
*/
static void
bfa_hwcb_msix_dummy(struct bfa_s *bfa, int vec)
{
}
/*
* No special setup required for crossbow -- vector assignments are implicit.
*/
void
bfa_hwcb_msix_init(struct bfa_s *bfa, int nvecs)
{
WARN_ON((nvecs != 1) && (nvecs != __HFN_NUMINTS));
bfa->msix.nvecs = nvecs;
bfa_hwcb_msix_uninstall(bfa);
}
void
bfa_hwcb_msix_ctrl_install(struct bfa_s *bfa)
{
int i;
if (bfa->msix.nvecs == 0)
return;
if (bfa->msix.nvecs == 1) {
for (i = BFI_MSIX_CPE_QMIN_CB; i < BFI_MSIX_CB_MAX; i++)
bfa->msix.handler[i] = bfa_msix_all;
return;
}
for (i = BFI_MSIX_RME_QMAX_CB+1; i < BFI_MSIX_CB_MAX; i++)
bfa->msix.handler[i] = bfa_msix_lpu_err;
}
void
bfa_hwcb_msix_queue_install(struct bfa_s *bfa)
{
int i;
if (bfa->msix.nvecs == 0)
return;
if (bfa->msix.nvecs == 1) {
for (i = BFI_MSIX_CPE_QMIN_CB; i <= BFI_MSIX_RME_QMAX_CB; i++)
bfa->msix.handler[i] = bfa_msix_all;
return;
}
for (i = BFI_MSIX_CPE_QMIN_CB; i <= BFI_MSIX_CPE_QMAX_CB; i++)
bfa->msix.handler[i] = bfa_msix_reqq;
for (i = BFI_MSIX_RME_QMIN_CB; i <= BFI_MSIX_RME_QMAX_CB; i++)
bfa->msix.handler[i] = bfa_msix_rspq;
}
void
bfa_hwcb_msix_uninstall(struct bfa_s *bfa)
{
int i;
for (i = 0; i < BFI_MSIX_CB_MAX; i++)
bfa->msix.handler[i] = bfa_hwcb_msix_dummy;
}
/*
* No special enable/disable -- vector assignments are implicit.
*/
void
bfa_hwcb_isr_mode_set(struct bfa_s *bfa, bfa_boolean_t msix)
{
if (msix) {
bfa->iocfc.hwif.hw_reqq_ack = bfa_hwcb_reqq_ack_msix;
bfa->iocfc.hwif.hw_rspq_ack = bfa_hwcb_rspq_ack_msix;
} else {
bfa->iocfc.hwif.hw_reqq_ack = NULL;
bfa->iocfc.hwif.hw_rspq_ack = bfa_hwcb_rspq_ack;
}
}
void
bfa_hwcb_msix_get_rme_range(struct bfa_s *bfa, u32 *start, u32 *end)
{
*start = BFI_MSIX_RME_QMIN_CB;
*end = BFI_MSIX_RME_QMAX_CB;
}
| gpl-2.0 |
SM-G920P/G920PVPU3BOI1 | net/netfilter/nf_tproxy_core.c | 10409 | 1415 | /*
* Transparent proxy support for Linux/iptables
*
* Copyright (c) 2006-2007 BalaBit IT Ltd.
* Author: Balazs Scheidler, Krisztian Kovacs
*
* 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/net.h>
#include <linux/if.h>
#include <linux/netdevice.h>
#include <net/udp.h>
#include <net/netfilter/nf_tproxy_core.h>
static void
nf_tproxy_destructor(struct sk_buff *skb)
{
struct sock *sk = skb->sk;
skb->sk = NULL;
skb->destructor = NULL;
if (sk)
sock_put(sk);
}
/* consumes sk */
void
nf_tproxy_assign_sock(struct sk_buff *skb, struct sock *sk)
{
/* assigning tw sockets complicates things; most
* skb->sk->X checks would have to test sk->sk_state first */
if (sk->sk_state == TCP_TIME_WAIT) {
inet_twsk_put(inet_twsk(sk));
return;
}
skb_orphan(skb);
skb->sk = sk;
skb->destructor = nf_tproxy_destructor;
}
EXPORT_SYMBOL_GPL(nf_tproxy_assign_sock);
static int __init nf_tproxy_init(void)
{
pr_info("NF_TPROXY: Transparent proxy support initialized, version 4.1.0\n");
pr_info("NF_TPROXY: Copyright (c) 2006-2007 BalaBit IT Ltd.\n");
return 0;
}
module_init(nf_tproxy_init);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Krisztian Kovacs");
MODULE_DESCRIPTION("Transparent proxy support core routines");
| gpl-2.0 |
TI-OpenLink/wl12xx_soldel_maintenance | drivers/scsi/aic7xxx/aic79xx_pci.c | 11177 | 27685 | /*
* Product specific probe and attach routines for:
* aic7901 and aic7902 SCSI controllers
*
* Copyright (c) 1994-2001 Justin T. Gibbs.
* Copyright (c) 2000-2002 Adaptec Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* NO WARRANTY
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* $Id: //depot/aic7xxx/aic7xxx/aic79xx_pci.c#92 $
*/
#ifdef __linux__
#include "aic79xx_osm.h"
#include "aic79xx_inline.h"
#else
#include <dev/aic7xxx/aic79xx_osm.h>
#include <dev/aic7xxx/aic79xx_inline.h>
#endif
#include "aic79xx_pci.h"
static inline uint64_t
ahd_compose_id(u_int device, u_int vendor, u_int subdevice, u_int subvendor)
{
uint64_t id;
id = subvendor
| (subdevice << 16)
| ((uint64_t)vendor << 32)
| ((uint64_t)device << 48);
return (id);
}
#define ID_AIC7902_PCI_REV_A4 0x3
#define ID_AIC7902_PCI_REV_B0 0x10
#define SUBID_HP 0x0E11
#define DEVID_9005_HOSTRAID(id) ((id) & 0x80)
#define DEVID_9005_TYPE(id) ((id) & 0xF)
#define DEVID_9005_TYPE_HBA 0x0 /* Standard Card */
#define DEVID_9005_TYPE_HBA_2EXT 0x1 /* 2 External Ports */
#define DEVID_9005_TYPE_IROC 0x8 /* Raid(0,1,10) Card */
#define DEVID_9005_TYPE_MB 0xF /* On Motherboard */
#define DEVID_9005_MFUNC(id) ((id) & 0x10)
#define DEVID_9005_PACKETIZED(id) ((id) & 0x8000)
#define SUBID_9005_TYPE(id) ((id) & 0xF)
#define SUBID_9005_TYPE_HBA 0x0 /* Standard Card */
#define SUBID_9005_TYPE_MB 0xF /* On Motherboard */
#define SUBID_9005_AUTOTERM(id) (((id) & 0x10) == 0)
#define SUBID_9005_LEGACYCONN_FUNC(id) ((id) & 0x20)
#define SUBID_9005_SEEPTYPE(id) (((id) & 0x0C0) >> 6)
#define SUBID_9005_SEEPTYPE_NONE 0x0
#define SUBID_9005_SEEPTYPE_4K 0x1
static ahd_device_setup_t ahd_aic7901_setup;
static ahd_device_setup_t ahd_aic7901A_setup;
static ahd_device_setup_t ahd_aic7902_setup;
static ahd_device_setup_t ahd_aic790X_setup;
static const struct ahd_pci_identity ahd_pci_ident_table[] =
{
/* aic7901 based controllers */
{
ID_AHA_29320A,
ID_ALL_MASK,
"Adaptec 29320A Ultra320 SCSI adapter",
ahd_aic7901_setup
},
{
ID_AHA_29320ALP,
ID_ALL_MASK,
"Adaptec 29320ALP PCIx Ultra320 SCSI adapter",
ahd_aic7901_setup
},
{
ID_AHA_29320LPE,
ID_ALL_MASK,
"Adaptec 29320LPE PCIe Ultra320 SCSI adapter",
ahd_aic7901_setup
},
/* aic7901A based controllers */
{
ID_AHA_29320LP,
ID_ALL_MASK,
"Adaptec 29320LP Ultra320 SCSI adapter",
ahd_aic7901A_setup
},
/* aic7902 based controllers */
{
ID_AHA_29320,
ID_ALL_MASK,
"Adaptec 29320 Ultra320 SCSI adapter",
ahd_aic7902_setup
},
{
ID_AHA_29320B,
ID_ALL_MASK,
"Adaptec 29320B Ultra320 SCSI adapter",
ahd_aic7902_setup
},
{
ID_AHA_39320,
ID_ALL_MASK,
"Adaptec 39320 Ultra320 SCSI adapter",
ahd_aic7902_setup
},
{
ID_AHA_39320_B,
ID_ALL_MASK,
"Adaptec 39320 Ultra320 SCSI adapter",
ahd_aic7902_setup
},
{
ID_AHA_39320_B_DELL,
ID_ALL_MASK,
"Adaptec (Dell OEM) 39320 Ultra320 SCSI adapter",
ahd_aic7902_setup
},
{
ID_AHA_39320A,
ID_ALL_MASK,
"Adaptec 39320A Ultra320 SCSI adapter",
ahd_aic7902_setup
},
{
ID_AHA_39320D,
ID_ALL_MASK,
"Adaptec 39320D Ultra320 SCSI adapter",
ahd_aic7902_setup
},
{
ID_AHA_39320D_HP,
ID_ALL_MASK,
"Adaptec (HP OEM) 39320D Ultra320 SCSI adapter",
ahd_aic7902_setup
},
{
ID_AHA_39320D_B,
ID_ALL_MASK,
"Adaptec 39320D Ultra320 SCSI adapter",
ahd_aic7902_setup
},
{
ID_AHA_39320D_B_HP,
ID_ALL_MASK,
"Adaptec (HP OEM) 39320D Ultra320 SCSI adapter",
ahd_aic7902_setup
},
/* Generic chip probes for devices we don't know 'exactly' */
{
ID_AIC7901 & ID_9005_GENERIC_MASK,
ID_9005_GENERIC_MASK,
"Adaptec AIC7901 Ultra320 SCSI adapter",
ahd_aic7901_setup
},
{
ID_AIC7901A & ID_DEV_VENDOR_MASK,
ID_DEV_VENDOR_MASK,
"Adaptec AIC7901A Ultra320 SCSI adapter",
ahd_aic7901A_setup
},
{
ID_AIC7902 & ID_9005_GENERIC_MASK,
ID_9005_GENERIC_MASK,
"Adaptec AIC7902 Ultra320 SCSI adapter",
ahd_aic7902_setup
}
};
static const u_int ahd_num_pci_devs = ARRAY_SIZE(ahd_pci_ident_table);
#define DEVCONFIG 0x40
#define PCIXINITPAT 0x0000E000ul
#define PCIXINIT_PCI33_66 0x0000E000ul
#define PCIXINIT_PCIX50_66 0x0000C000ul
#define PCIXINIT_PCIX66_100 0x0000A000ul
#define PCIXINIT_PCIX100_133 0x00008000ul
#define PCI_BUS_MODES_INDEX(devconfig) \
(((devconfig) & PCIXINITPAT) >> 13)
static const char *pci_bus_modes[] =
{
"PCI bus mode unknown",
"PCI bus mode unknown",
"PCI bus mode unknown",
"PCI bus mode unknown",
"PCI-X 101-133MHz",
"PCI-X 67-100MHz",
"PCI-X 50-66MHz",
"PCI 33 or 66MHz"
};
#define TESTMODE 0x00000800ul
#define IRDY_RST 0x00000200ul
#define FRAME_RST 0x00000100ul
#define PCI64BIT 0x00000080ul
#define MRDCEN 0x00000040ul
#define ENDIANSEL 0x00000020ul
#define MIXQWENDIANEN 0x00000008ul
#define DACEN 0x00000004ul
#define STPWLEVEL 0x00000002ul
#define QWENDIANSEL 0x00000001ul
#define DEVCONFIG1 0x44
#define PREQDIS 0x01
#define CSIZE_LATTIME 0x0c
#define CACHESIZE 0x000000fful
#define LATTIME 0x0000ff00ul
static int ahd_check_extport(struct ahd_softc *ahd);
static void ahd_configure_termination(struct ahd_softc *ahd,
u_int adapter_control);
static void ahd_pci_split_intr(struct ahd_softc *ahd, u_int intstat);
static void ahd_pci_intr(struct ahd_softc *ahd);
const struct ahd_pci_identity *
ahd_find_pci_device(ahd_dev_softc_t pci)
{
uint64_t full_id;
uint16_t device;
uint16_t vendor;
uint16_t subdevice;
uint16_t subvendor;
const struct ahd_pci_identity *entry;
u_int i;
vendor = ahd_pci_read_config(pci, PCIR_DEVVENDOR, /*bytes*/2);
device = ahd_pci_read_config(pci, PCIR_DEVICE, /*bytes*/2);
subvendor = ahd_pci_read_config(pci, PCIR_SUBVEND_0, /*bytes*/2);
subdevice = ahd_pci_read_config(pci, PCIR_SUBDEV_0, /*bytes*/2);
full_id = ahd_compose_id(device,
vendor,
subdevice,
subvendor);
/*
* Controllers, mask out the IROC/HostRAID bit
*/
full_id &= ID_ALL_IROC_MASK;
for (i = 0; i < ahd_num_pci_devs; i++) {
entry = &ahd_pci_ident_table[i];
if (entry->full_id == (full_id & entry->id_mask)) {
/* Honor exclusion entries. */
if (entry->name == NULL)
return (NULL);
return (entry);
}
}
return (NULL);
}
int
ahd_pci_config(struct ahd_softc *ahd, const struct ahd_pci_identity *entry)
{
struct scb_data *shared_scb_data;
u_int command;
uint32_t devconfig;
uint16_t subvendor;
int error;
shared_scb_data = NULL;
ahd->description = entry->name;
/*
* Record if this is an HP board.
*/
subvendor = ahd_pci_read_config(ahd->dev_softc,
PCIR_SUBVEND_0, /*bytes*/2);
if (subvendor == SUBID_HP)
ahd->flags |= AHD_HP_BOARD;
error = entry->setup(ahd);
if (error != 0)
return (error);
devconfig = ahd_pci_read_config(ahd->dev_softc, DEVCONFIG, /*bytes*/4);
if ((devconfig & PCIXINITPAT) == PCIXINIT_PCI33_66) {
ahd->chip |= AHD_PCI;
/* Disable PCIX workarounds when running in PCI mode. */
ahd->bugs &= ~AHD_PCIX_BUG_MASK;
} else {
ahd->chip |= AHD_PCIX;
}
ahd->bus_description = pci_bus_modes[PCI_BUS_MODES_INDEX(devconfig)];
ahd_power_state_change(ahd, AHD_POWER_STATE_D0);
error = ahd_pci_map_registers(ahd);
if (error != 0)
return (error);
/*
* If we need to support high memory, enable dual
* address cycles. This bit must be set to enable
* high address bit generation even if we are on a
* 64bit bus (PCI64BIT set in devconfig).
*/
if ((ahd->flags & (AHD_39BIT_ADDRESSING|AHD_64BIT_ADDRESSING)) != 0) {
if (bootverbose)
printk("%s: Enabling 39Bit Addressing\n",
ahd_name(ahd));
devconfig = ahd_pci_read_config(ahd->dev_softc,
DEVCONFIG, /*bytes*/4);
devconfig |= DACEN;
ahd_pci_write_config(ahd->dev_softc, DEVCONFIG,
devconfig, /*bytes*/4);
}
/* Ensure busmastering is enabled */
command = ahd_pci_read_config(ahd->dev_softc, PCIR_COMMAND, /*bytes*/2);
command |= PCIM_CMD_BUSMASTEREN;
ahd_pci_write_config(ahd->dev_softc, PCIR_COMMAND, command, /*bytes*/2);
error = ahd_softc_init(ahd);
if (error != 0)
return (error);
ahd->bus_intr = ahd_pci_intr;
error = ahd_reset(ahd, /*reinit*/FALSE);
if (error != 0)
return (ENXIO);
ahd->pci_cachesize =
ahd_pci_read_config(ahd->dev_softc, CSIZE_LATTIME,
/*bytes*/1) & CACHESIZE;
ahd->pci_cachesize *= 4;
ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
/* See if we have a SEEPROM and perform auto-term */
error = ahd_check_extport(ahd);
if (error != 0)
return (error);
/* Core initialization */
error = ahd_init(ahd);
if (error != 0)
return (error);
ahd->init_level++;
/*
* Allow interrupts now that we are completely setup.
*/
return ahd_pci_map_int(ahd);
}
#ifdef CONFIG_PM
void
ahd_pci_suspend(struct ahd_softc *ahd)
{
/*
* Save chip register configuration data for chip resets
* that occur during runtime and resume events.
*/
ahd->suspend_state.pci_state.devconfig =
ahd_pci_read_config(ahd->dev_softc, DEVCONFIG, /*bytes*/4);
ahd->suspend_state.pci_state.command =
ahd_pci_read_config(ahd->dev_softc, PCIR_COMMAND, /*bytes*/1);
ahd->suspend_state.pci_state.csize_lattime =
ahd_pci_read_config(ahd->dev_softc, CSIZE_LATTIME, /*bytes*/1);
}
void
ahd_pci_resume(struct ahd_softc *ahd)
{
ahd_pci_write_config(ahd->dev_softc, DEVCONFIG,
ahd->suspend_state.pci_state.devconfig, /*bytes*/4);
ahd_pci_write_config(ahd->dev_softc, PCIR_COMMAND,
ahd->suspend_state.pci_state.command, /*bytes*/1);
ahd_pci_write_config(ahd->dev_softc, CSIZE_LATTIME,
ahd->suspend_state.pci_state.csize_lattime, /*bytes*/1);
}
#endif
/*
* Perform some simple tests that should catch situations where
* our registers are invalidly mapped.
*/
int
ahd_pci_test_register_access(struct ahd_softc *ahd)
{
uint32_t cmd;
u_int targpcistat;
u_int pci_status1;
int error;
uint8_t hcntrl;
error = EIO;
/*
* Enable PCI error interrupt status, but suppress NMIs
* generated by SERR raised due to target aborts.
*/
cmd = ahd_pci_read_config(ahd->dev_softc, PCIR_COMMAND, /*bytes*/2);
ahd_pci_write_config(ahd->dev_softc, PCIR_COMMAND,
cmd & ~PCIM_CMD_SERRESPEN, /*bytes*/2);
/*
* First a simple test to see if any
* registers can be read. Reading
* HCNTRL has no side effects and has
* at least one bit that is guaranteed to
* be zero so it is a good register to
* use for this test.
*/
hcntrl = ahd_inb(ahd, HCNTRL);
if (hcntrl == 0xFF)
goto fail;
/*
* Next create a situation where write combining
* or read prefetching could be initiated by the
* CPU or host bridge. Our device does not support
* either, so look for data corruption and/or flaged
* PCI errors. First pause without causing another
* chip reset.
*/
hcntrl &= ~CHIPRST;
ahd_outb(ahd, HCNTRL, hcntrl|PAUSE);
while (ahd_is_paused(ahd) == 0)
;
/* Clear any PCI errors that occurred before our driver attached. */
ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
targpcistat = ahd_inb(ahd, TARGPCISTAT);
ahd_outb(ahd, TARGPCISTAT, targpcistat);
pci_status1 = ahd_pci_read_config(ahd->dev_softc,
PCIR_STATUS + 1, /*bytes*/1);
ahd_pci_write_config(ahd->dev_softc, PCIR_STATUS + 1,
pci_status1, /*bytes*/1);
ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
ahd_outb(ahd, CLRINT, CLRPCIINT);
ahd_outb(ahd, SEQCTL0, PERRORDIS);
ahd_outl(ahd, SRAM_BASE, 0x5aa555aa);
if (ahd_inl(ahd, SRAM_BASE) != 0x5aa555aa)
goto fail;
if ((ahd_inb(ahd, INTSTAT) & PCIINT) != 0) {
ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
targpcistat = ahd_inb(ahd, TARGPCISTAT);
if ((targpcistat & STA) != 0)
goto fail;
}
error = 0;
fail:
if ((ahd_inb(ahd, INTSTAT) & PCIINT) != 0) {
ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
targpcistat = ahd_inb(ahd, TARGPCISTAT);
/* Silently clear any latched errors. */
ahd_outb(ahd, TARGPCISTAT, targpcistat);
pci_status1 = ahd_pci_read_config(ahd->dev_softc,
PCIR_STATUS + 1, /*bytes*/1);
ahd_pci_write_config(ahd->dev_softc, PCIR_STATUS + 1,
pci_status1, /*bytes*/1);
ahd_outb(ahd, CLRINT, CLRPCIINT);
}
ahd_outb(ahd, SEQCTL0, PERRORDIS|FAILDIS);
ahd_pci_write_config(ahd->dev_softc, PCIR_COMMAND, cmd, /*bytes*/2);
return (error);
}
/*
* Check the external port logic for a serial eeprom
* and termination/cable detection contrls.
*/
static int
ahd_check_extport(struct ahd_softc *ahd)
{
struct vpd_config vpd;
struct seeprom_config *sc;
u_int adapter_control;
int have_seeprom;
int error;
sc = ahd->seep_config;
have_seeprom = ahd_acquire_seeprom(ahd);
if (have_seeprom) {
u_int start_addr;
/*
* Fetch VPD for this function and parse it.
*/
if (bootverbose)
printk("%s: Reading VPD from SEEPROM...",
ahd_name(ahd));
/* Address is always in units of 16bit words */
start_addr = ((2 * sizeof(*sc))
+ (sizeof(vpd) * (ahd->channel - 'A'))) / 2;
error = ahd_read_seeprom(ahd, (uint16_t *)&vpd,
start_addr, sizeof(vpd)/2,
/*bytestream*/TRUE);
if (error == 0)
error = ahd_parse_vpddata(ahd, &vpd);
if (bootverbose)
printk("%s: VPD parsing %s\n",
ahd_name(ahd),
error == 0 ? "successful" : "failed");
if (bootverbose)
printk("%s: Reading SEEPROM...", ahd_name(ahd));
/* Address is always in units of 16bit words */
start_addr = (sizeof(*sc) / 2) * (ahd->channel - 'A');
error = ahd_read_seeprom(ahd, (uint16_t *)sc,
start_addr, sizeof(*sc)/2,
/*bytestream*/FALSE);
if (error != 0) {
printk("Unable to read SEEPROM\n");
have_seeprom = 0;
} else {
have_seeprom = ahd_verify_cksum(sc);
if (bootverbose) {
if (have_seeprom == 0)
printk ("checksum error\n");
else
printk ("done.\n");
}
}
ahd_release_seeprom(ahd);
}
if (!have_seeprom) {
u_int nvram_scb;
/*
* Pull scratch ram settings and treat them as
* if they are the contents of an seeprom if
* the 'ADPT', 'BIOS', or 'ASPI' signature is found
* in SCB 0xFF. We manually compose the data as 16bit
* values to avoid endian issues.
*/
ahd_set_scbptr(ahd, 0xFF);
nvram_scb = ahd_inb_scbram(ahd, SCB_BASE + NVRAM_SCB_OFFSET);
if (nvram_scb != 0xFF
&& ((ahd_inb_scbram(ahd, SCB_BASE + 0) == 'A'
&& ahd_inb_scbram(ahd, SCB_BASE + 1) == 'D'
&& ahd_inb_scbram(ahd, SCB_BASE + 2) == 'P'
&& ahd_inb_scbram(ahd, SCB_BASE + 3) == 'T')
|| (ahd_inb_scbram(ahd, SCB_BASE + 0) == 'B'
&& ahd_inb_scbram(ahd, SCB_BASE + 1) == 'I'
&& ahd_inb_scbram(ahd, SCB_BASE + 2) == 'O'
&& ahd_inb_scbram(ahd, SCB_BASE + 3) == 'S')
|| (ahd_inb_scbram(ahd, SCB_BASE + 0) == 'A'
&& ahd_inb_scbram(ahd, SCB_BASE + 1) == 'S'
&& ahd_inb_scbram(ahd, SCB_BASE + 2) == 'P'
&& ahd_inb_scbram(ahd, SCB_BASE + 3) == 'I'))) {
uint16_t *sc_data;
int i;
ahd_set_scbptr(ahd, nvram_scb);
sc_data = (uint16_t *)sc;
for (i = 0; i < 64; i += 2)
*sc_data++ = ahd_inw_scbram(ahd, SCB_BASE+i);
have_seeprom = ahd_verify_cksum(sc);
if (have_seeprom)
ahd->flags |= AHD_SCB_CONFIG_USED;
}
}
#ifdef AHD_DEBUG
if (have_seeprom != 0
&& (ahd_debug & AHD_DUMP_SEEPROM) != 0) {
uint16_t *sc_data;
int i;
printk("%s: Seeprom Contents:", ahd_name(ahd));
sc_data = (uint16_t *)sc;
for (i = 0; i < (sizeof(*sc)); i += 2)
printk("\n\t0x%.4x", sc_data[i]);
printk("\n");
}
#endif
if (!have_seeprom) {
if (bootverbose)
printk("%s: No SEEPROM available.\n", ahd_name(ahd));
ahd->flags |= AHD_USEDEFAULTS;
error = ahd_default_config(ahd);
adapter_control = CFAUTOTERM|CFSEAUTOTERM;
kfree(ahd->seep_config);
ahd->seep_config = NULL;
} else {
error = ahd_parse_cfgdata(ahd, sc);
adapter_control = sc->adapter_control;
}
if (error != 0)
return (error);
ahd_configure_termination(ahd, adapter_control);
return (0);
}
static void
ahd_configure_termination(struct ahd_softc *ahd, u_int adapter_control)
{
int error;
u_int sxfrctl1;
uint8_t termctl;
uint32_t devconfig;
devconfig = ahd_pci_read_config(ahd->dev_softc, DEVCONFIG, /*bytes*/4);
devconfig &= ~STPWLEVEL;
if ((ahd->flags & AHD_STPWLEVEL_A) != 0)
devconfig |= STPWLEVEL;
if (bootverbose)
printk("%s: STPWLEVEL is %s\n",
ahd_name(ahd), (devconfig & STPWLEVEL) ? "on" : "off");
ahd_pci_write_config(ahd->dev_softc, DEVCONFIG, devconfig, /*bytes*/4);
/* Make sure current sensing is off. */
if ((ahd->flags & AHD_CURRENT_SENSING) != 0) {
(void)ahd_write_flexport(ahd, FLXADDR_ROMSTAT_CURSENSECTL, 0);
}
/*
* Read to sense. Write to set.
*/
error = ahd_read_flexport(ahd, FLXADDR_TERMCTL, &termctl);
if ((adapter_control & CFAUTOTERM) == 0) {
if (bootverbose)
printk("%s: Manual Primary Termination\n",
ahd_name(ahd));
termctl &= ~(FLX_TERMCTL_ENPRILOW|FLX_TERMCTL_ENPRIHIGH);
if ((adapter_control & CFSTERM) != 0)
termctl |= FLX_TERMCTL_ENPRILOW;
if ((adapter_control & CFWSTERM) != 0)
termctl |= FLX_TERMCTL_ENPRIHIGH;
} else if (error != 0) {
printk("%s: Primary Auto-Term Sensing failed! "
"Using Defaults.\n", ahd_name(ahd));
termctl = FLX_TERMCTL_ENPRILOW|FLX_TERMCTL_ENPRIHIGH;
}
if ((adapter_control & CFSEAUTOTERM) == 0) {
if (bootverbose)
printk("%s: Manual Secondary Termination\n",
ahd_name(ahd));
termctl &= ~(FLX_TERMCTL_ENSECLOW|FLX_TERMCTL_ENSECHIGH);
if ((adapter_control & CFSELOWTERM) != 0)
termctl |= FLX_TERMCTL_ENSECLOW;
if ((adapter_control & CFSEHIGHTERM) != 0)
termctl |= FLX_TERMCTL_ENSECHIGH;
} else if (error != 0) {
printk("%s: Secondary Auto-Term Sensing failed! "
"Using Defaults.\n", ahd_name(ahd));
termctl |= FLX_TERMCTL_ENSECLOW|FLX_TERMCTL_ENSECHIGH;
}
/*
* Now set the termination based on what we found.
*/
sxfrctl1 = ahd_inb(ahd, SXFRCTL1) & ~STPWEN;
ahd->flags &= ~AHD_TERM_ENB_A;
if ((termctl & FLX_TERMCTL_ENPRILOW) != 0) {
ahd->flags |= AHD_TERM_ENB_A;
sxfrctl1 |= STPWEN;
}
/* Must set the latch once in order to be effective. */
ahd_outb(ahd, SXFRCTL1, sxfrctl1|STPWEN);
ahd_outb(ahd, SXFRCTL1, sxfrctl1);
error = ahd_write_flexport(ahd, FLXADDR_TERMCTL, termctl);
if (error != 0) {
printk("%s: Unable to set termination settings!\n",
ahd_name(ahd));
} else if (bootverbose) {
printk("%s: Primary High byte termination %sabled\n",
ahd_name(ahd),
(termctl & FLX_TERMCTL_ENPRIHIGH) ? "En" : "Dis");
printk("%s: Primary Low byte termination %sabled\n",
ahd_name(ahd),
(termctl & FLX_TERMCTL_ENPRILOW) ? "En" : "Dis");
printk("%s: Secondary High byte termination %sabled\n",
ahd_name(ahd),
(termctl & FLX_TERMCTL_ENSECHIGH) ? "En" : "Dis");
printk("%s: Secondary Low byte termination %sabled\n",
ahd_name(ahd),
(termctl & FLX_TERMCTL_ENSECLOW) ? "En" : "Dis");
}
return;
}
#define DPE 0x80
#define SSE 0x40
#define RMA 0x20
#define RTA 0x10
#define STA 0x08
#define DPR 0x01
static const char *split_status_source[] =
{
"DFF0",
"DFF1",
"OVLY",
"CMC",
};
static const char *pci_status_source[] =
{
"DFF0",
"DFF1",
"SG",
"CMC",
"OVLY",
"NONE",
"MSI",
"TARG"
};
static const char *split_status_strings[] =
{
"%s: Received split response in %s.\n",
"%s: Received split completion error message in %s\n",
"%s: Receive overrun in %s\n",
"%s: Count not complete in %s\n",
"%s: Split completion data bucket in %s\n",
"%s: Split completion address error in %s\n",
"%s: Split completion byte count error in %s\n",
"%s: Signaled Target-abort to early terminate a split in %s\n"
};
static const char *pci_status_strings[] =
{
"%s: Data Parity Error has been reported via PERR# in %s\n",
"%s: Target initial wait state error in %s\n",
"%s: Split completion read data parity error in %s\n",
"%s: Split completion address attribute parity error in %s\n",
"%s: Received a Target Abort in %s\n",
"%s: Received a Master Abort in %s\n",
"%s: Signal System Error Detected in %s\n",
"%s: Address or Write Phase Parity Error Detected in %s.\n"
};
static void
ahd_pci_intr(struct ahd_softc *ahd)
{
uint8_t pci_status[8];
ahd_mode_state saved_modes;
u_int pci_status1;
u_int intstat;
u_int i;
u_int reg;
intstat = ahd_inb(ahd, INTSTAT);
if ((intstat & SPLTINT) != 0)
ahd_pci_split_intr(ahd, intstat);
if ((intstat & PCIINT) == 0)
return;
printk("%s: PCI error Interrupt\n", ahd_name(ahd));
saved_modes = ahd_save_modes(ahd);
ahd_dump_card_state(ahd);
ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
for (i = 0, reg = DF0PCISTAT; i < 8; i++, reg++) {
if (i == 5)
continue;
pci_status[i] = ahd_inb(ahd, reg);
/* Clear latched errors. So our interrupt deasserts. */
ahd_outb(ahd, reg, pci_status[i]);
}
for (i = 0; i < 8; i++) {
u_int bit;
if (i == 5)
continue;
for (bit = 0; bit < 8; bit++) {
if ((pci_status[i] & (0x1 << bit)) != 0) {
static const char *s;
s = pci_status_strings[bit];
if (i == 7/*TARG*/ && bit == 3)
s = "%s: Signaled Target Abort\n";
printk(s, ahd_name(ahd), pci_status_source[i]);
}
}
}
pci_status1 = ahd_pci_read_config(ahd->dev_softc,
PCIR_STATUS + 1, /*bytes*/1);
ahd_pci_write_config(ahd->dev_softc, PCIR_STATUS + 1,
pci_status1, /*bytes*/1);
ahd_restore_modes(ahd, saved_modes);
ahd_outb(ahd, CLRINT, CLRPCIINT);
ahd_unpause(ahd);
}
static void
ahd_pci_split_intr(struct ahd_softc *ahd, u_int intstat)
{
uint8_t split_status[4];
uint8_t split_status1[4];
uint8_t sg_split_status[2];
uint8_t sg_split_status1[2];
ahd_mode_state saved_modes;
u_int i;
uint16_t pcix_status;
/*
* Check for splits in all modes. Modes 0 and 1
* additionally have SG engine splits to look at.
*/
pcix_status = ahd_pci_read_config(ahd->dev_softc, PCIXR_STATUS,
/*bytes*/2);
printk("%s: PCI Split Interrupt - PCI-X status = 0x%x\n",
ahd_name(ahd), pcix_status);
saved_modes = ahd_save_modes(ahd);
for (i = 0; i < 4; i++) {
ahd_set_modes(ahd, i, i);
split_status[i] = ahd_inb(ahd, DCHSPLTSTAT0);
split_status1[i] = ahd_inb(ahd, DCHSPLTSTAT1);
/* Clear latched errors. So our interrupt deasserts. */
ahd_outb(ahd, DCHSPLTSTAT0, split_status[i]);
ahd_outb(ahd, DCHSPLTSTAT1, split_status1[i]);
if (i > 1)
continue;
sg_split_status[i] = ahd_inb(ahd, SGSPLTSTAT0);
sg_split_status1[i] = ahd_inb(ahd, SGSPLTSTAT1);
/* Clear latched errors. So our interrupt deasserts. */
ahd_outb(ahd, SGSPLTSTAT0, sg_split_status[i]);
ahd_outb(ahd, SGSPLTSTAT1, sg_split_status1[i]);
}
for (i = 0; i < 4; i++) {
u_int bit;
for (bit = 0; bit < 8; bit++) {
if ((split_status[i] & (0x1 << bit)) != 0) {
static const char *s;
s = split_status_strings[bit];
printk(s, ahd_name(ahd),
split_status_source[i]);
}
if (i > 1)
continue;
if ((sg_split_status[i] & (0x1 << bit)) != 0) {
static const char *s;
s = split_status_strings[bit];
printk(s, ahd_name(ahd), "SG");
}
}
}
/*
* Clear PCI-X status bits.
*/
ahd_pci_write_config(ahd->dev_softc, PCIXR_STATUS,
pcix_status, /*bytes*/2);
ahd_outb(ahd, CLRINT, CLRSPLTINT);
ahd_restore_modes(ahd, saved_modes);
}
static int
ahd_aic7901_setup(struct ahd_softc *ahd)
{
ahd->chip = AHD_AIC7901;
ahd->features = AHD_AIC7901_FE;
return (ahd_aic790X_setup(ahd));
}
static int
ahd_aic7901A_setup(struct ahd_softc *ahd)
{
ahd->chip = AHD_AIC7901A;
ahd->features = AHD_AIC7901A_FE;
return (ahd_aic790X_setup(ahd));
}
static int
ahd_aic7902_setup(struct ahd_softc *ahd)
{
ahd->chip = AHD_AIC7902;
ahd->features = AHD_AIC7902_FE;
return (ahd_aic790X_setup(ahd));
}
static int
ahd_aic790X_setup(struct ahd_softc *ahd)
{
ahd_dev_softc_t pci;
u_int rev;
pci = ahd->dev_softc;
rev = ahd_pci_read_config(pci, PCIR_REVID, /*bytes*/1);
if (rev < ID_AIC7902_PCI_REV_A4) {
printk("%s: Unable to attach to unsupported chip revision %d\n",
ahd_name(ahd), rev);
ahd_pci_write_config(pci, PCIR_COMMAND, 0, /*bytes*/2);
return (ENXIO);
}
ahd->channel = ahd_get_pci_function(pci) + 'A';
if (rev < ID_AIC7902_PCI_REV_B0) {
/*
* Enable A series workarounds.
*/
ahd->bugs |= AHD_SENT_SCB_UPDATE_BUG|AHD_ABORT_LQI_BUG
| AHD_PKT_BITBUCKET_BUG|AHD_LONG_SETIMO_BUG
| AHD_NLQICRC_DELAYED_BUG|AHD_SCSIRST_BUG
| AHD_LQO_ATNO_BUG|AHD_AUTOFLUSH_BUG
| AHD_CLRLQO_AUTOCLR_BUG|AHD_PCIX_MMAPIO_BUG
| AHD_PCIX_CHIPRST_BUG|AHD_PCIX_SCBRAM_RD_BUG
| AHD_PKTIZED_STATUS_BUG|AHD_PKT_LUN_BUG
| AHD_MDFF_WSCBPTR_BUG|AHD_REG_SLOW_SETTLE_BUG
| AHD_SET_MODE_BUG|AHD_BUSFREEREV_BUG
| AHD_NONPACKFIFO_BUG|AHD_PACED_NEGTABLE_BUG
| AHD_FAINT_LED_BUG;
/*
* IO Cell parameter setup.
*/
AHD_SET_PRECOMP(ahd, AHD_PRECOMP_CUTBACK_29);
if ((ahd->flags & AHD_HP_BOARD) == 0)
AHD_SET_SLEWRATE(ahd, AHD_SLEWRATE_DEF_REVA);
} else {
/* This is revision B and newer. */
extern uint32_t aic79xx_slowcrc;
u_int devconfig1;
ahd->features |= AHD_RTI|AHD_NEW_IOCELL_OPTS
| AHD_NEW_DFCNTRL_OPTS|AHD_FAST_CDB_DELIVERY
| AHD_BUSFREEREV_BUG;
ahd->bugs |= AHD_LQOOVERRUN_BUG|AHD_EARLY_REQ_BUG;
/* If the user requested that the SLOWCRC bit to be set. */
if (aic79xx_slowcrc)
ahd->features |= AHD_AIC79XXB_SLOWCRC;
/*
* Some issues have been resolved in the 7901B.
*/
if ((ahd->features & AHD_MULTI_FUNC) != 0)
ahd->bugs |= AHD_INTCOLLISION_BUG|AHD_ABORT_LQI_BUG;
/*
* IO Cell parameter setup.
*/
AHD_SET_PRECOMP(ahd, AHD_PRECOMP_CUTBACK_29);
AHD_SET_SLEWRATE(ahd, AHD_SLEWRATE_DEF_REVB);
AHD_SET_AMPLITUDE(ahd, AHD_AMPLITUDE_DEF);
/*
* Set the PREQDIS bit for H2B which disables some workaround
* that doesn't work on regular PCI busses.
* XXX - Find out exactly what this does from the hardware
* folks!
*/
devconfig1 = ahd_pci_read_config(pci, DEVCONFIG1, /*bytes*/1);
ahd_pci_write_config(pci, DEVCONFIG1,
devconfig1|PREQDIS, /*bytes*/1);
devconfig1 = ahd_pci_read_config(pci, DEVCONFIG1, /*bytes*/1);
}
return (0);
}
| gpl-2.0 |
BigBot96/android_kernel_samsung_espressovzw-jb | fs/partitions/karma.c | 11177 | 1102 | /*
* fs/partitions/karma.c
* Rio Karma partition info.
*
* Copyright (C) 2006 Bob Copeland (me@bobcopeland.com)
* based on osf.c
*/
#include "check.h"
#include "karma.h"
int karma_partition(struct parsed_partitions *state)
{
int i;
int slot = 1;
Sector sect;
unsigned char *data;
struct disklabel {
u8 d_reserved[270];
struct d_partition {
__le32 p_res;
u8 p_fstype;
u8 p_res2[3];
__le32 p_offset;
__le32 p_size;
} d_partitions[2];
u8 d_blank[208];
__le16 d_magic;
} __attribute__((packed)) *label;
struct d_partition *p;
data = read_part_sector(state, 0, §);
if (!data)
return -1;
label = (struct disklabel *)data;
if (le16_to_cpu(label->d_magic) != KARMA_LABEL_MAGIC) {
put_dev_sector(sect);
return 0;
}
p = label->d_partitions;
for (i = 0 ; i < 2; i++, p++) {
if (slot == state->limit)
break;
if (p->p_fstype == 0x4d && le32_to_cpu(p->p_size)) {
put_partition(state, slot, le32_to_cpu(p->p_offset),
le32_to_cpu(p->p_size));
}
slot++;
}
strlcat(state->pp_buf, "\n", PAGE_SIZE);
put_dev_sector(sect);
return 1;
}
| gpl-2.0 |
MotoXoomKernelFlavors/tiamat-kernel-mod | drivers/staging/ath6kl/hif/sdio/linux_sdio/src/hif.c | 170 | 44980 | //------------------------------------------------------------------------------
// <copyright file="hif.c" company="Atheros">
// Copyright (c) 2004-2010 Atheros Corporation. All rights reserved.
//
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
//
//------------------------------------------------------------------------------
//==============================================================================
// HIF layer reference implementation for Linux Native MMC stack
//
// Author(s): ="Atheros"
//==============================================================================
#include <linux/mmc/card.h>
#include <linux/mmc/mmc.h>
#include <linux/mmc/host.h>
#include <linux/mmc/sdio_func.h>
#include <linux/mmc/sdio_ids.h>
#include <linux/mmc/sdio.h>
#include <linux/mmc/sd.h>
#include <linux/kthread.h>
/* by default setup a bounce buffer for the data packets, if the underlying host controller driver
does not use DMA you may be able to skip this step and save the memory allocation and transfer time */
#define HIF_USE_DMA_BOUNCE_BUFFER 1
#include "hif_internal.h"
#define ATH_MODULE_NAME hif
#include "a_debug.h"
#include "AR6002/hw2.0/hw/mbox_host_reg.h"
#if HIF_USE_DMA_BOUNCE_BUFFER
/* macro to check if DMA buffer is WORD-aligned and DMA-able. Most host controllers assume the
* buffer is DMA'able and will bug-check otherwise (i.e. buffers on the stack).
* virt_addr_valid check fails on stack memory.
*/
#define BUFFER_NEEDS_BOUNCE(buffer) (((unsigned long)(buffer) & 0x3) || !virt_addr_valid((buffer)))
#else
#define BUFFER_NEEDS_BOUNCE(buffer) (false)
#endif
/* ATHENV */
#if defined(CONFIG_PM)
#define dev_to_sdio_func(d) container_of(d, struct sdio_func, dev)
#define to_sdio_driver(d) container_of(d, struct sdio_driver, drv)
static int hifDeviceSuspend(struct device *dev);
static int hifDeviceResume(struct device *dev);
#endif /* CONFIG_PM */
static int hifDeviceInserted(struct sdio_func *func, const struct sdio_device_id *id);
static void hifDeviceRemoved(struct sdio_func *func);
static struct hif_device *addHifDevice(struct sdio_func *func);
static struct hif_device *getHifDevice(struct sdio_func *func);
static void delHifDevice(struct hif_device * device);
static int Func0_CMD52WriteByte(struct mmc_card *card, unsigned int address, unsigned char byte);
static int Func0_CMD52ReadByte(struct mmc_card *card, unsigned int address, unsigned char *byte);
int reset_sdio_on_unload = 0;
module_param(reset_sdio_on_unload, int, 0644);
extern u32 nohifscattersupport;
/* ------ Static Variables ------ */
static const struct sdio_device_id ar6k_id_table[] = {
{ SDIO_DEVICE(MANUFACTURER_CODE, (MANUFACTURER_ID_AR6002_BASE | 0x0)) },
{ SDIO_DEVICE(MANUFACTURER_CODE, (MANUFACTURER_ID_AR6002_BASE | 0x1)) },
{ SDIO_DEVICE(MANUFACTURER_CODE, (MANUFACTURER_ID_AR6003_BASE | 0x0)) },
{ SDIO_DEVICE(MANUFACTURER_CODE, (MANUFACTURER_ID_AR6003_BASE | 0x1)) },
{ /* null */ },
};
MODULE_DEVICE_TABLE(sdio, ar6k_id_table);
static struct sdio_driver ar6k_driver = {
.name = "ar6k_wlan",
.id_table = ar6k_id_table,
.probe = hifDeviceInserted,
.remove = hifDeviceRemoved,
};
#if defined(CONFIG_PM)
/* New suspend/resume based on linux-2.6.32
* Need to patch linux-2.6.32 with mmc2.6.32_suspend.patch
* Need to patch with msmsdcc2.6.29_suspend.patch for msm_sdcc host
*/
static struct dev_pm_ops ar6k_device_pm_ops = {
.suspend = hifDeviceSuspend,
.resume = hifDeviceResume,
};
#endif /* CONFIG_PM */
/* make sure we only unregister when registered. */
static int registered = 0;
OSDRV_CALLBACKS osdrvCallbacks;
extern u32 onebitmode;
extern u32 busspeedlow;
extern u32 debughif;
static void ResetAllCards(void);
static int hifDisableFunc(struct hif_device *device, struct sdio_func *func);
static int hifEnableFunc(struct hif_device *device, struct sdio_func *func);
#ifdef DEBUG
ATH_DEBUG_INSTANTIATE_MODULE_VAR(hif,
"hif",
"(Linux MMC) Host Interconnect Framework",
ATH_DEBUG_MASK_DEFAULTS,
0,
NULL);
#endif
/* ------ Functions ------ */
int HIFInit(OSDRV_CALLBACKS *callbacks)
{
int status;
AR_DEBUG_ASSERT(callbacks != NULL);
A_REGISTER_MODULE_DEBUG_INFO(hif);
/* store the callback handlers */
osdrvCallbacks = *callbacks;
/* Register with bus driver core */
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: HIFInit registering\n"));
registered = 1;
#if defined(CONFIG_PM)
if (callbacks->deviceSuspendHandler && callbacks->deviceResumeHandler) {
ar6k_driver.drv.pm = &ar6k_device_pm_ops;
}
#endif /* CONFIG_PM */
status = sdio_register_driver(&ar6k_driver);
AR_DEBUG_ASSERT(status==0);
if (status != 0) {
return A_ERROR;
}
return 0;
}
static int
__HIFReadWrite(struct hif_device *device,
u32 address,
u8 *buffer,
u32 length,
u32 request,
void *context)
{
u8 opcode;
int status = 0;
int ret;
u8 *tbuffer;
bool bounced = false;
AR_DEBUG_ASSERT(device != NULL);
AR_DEBUG_ASSERT(device->func != NULL);
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: Device: 0x%p, buffer:0x%p (addr:0x%X)\n",
device, buffer, address));
do {
if (request & HIF_EXTENDED_IO) {
//AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: Command type: CMD53\n"));
} else {
AR_DEBUG_PRINTF(ATH_DEBUG_ERROR,
("AR6000: Invalid command type: 0x%08x\n", request));
status = A_EINVAL;
break;
}
if (request & HIF_BLOCK_BASIS) {
/* round to whole block length size */
length = (length / HIF_MBOX_BLOCK_SIZE) * HIF_MBOX_BLOCK_SIZE;
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE,
("AR6000: Block mode (BlockLen: %d)\n",
length));
} else if (request & HIF_BYTE_BASIS) {
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE,
("AR6000: Byte mode (BlockLen: %d)\n",
length));
} else {
AR_DEBUG_PRINTF(ATH_DEBUG_ERROR,
("AR6000: Invalid data mode: 0x%08x\n", request));
status = A_EINVAL;
break;
}
#if 0
/* useful for checking register accesses */
if (length & 0x3) {
A_PRINTF(KERN_ALERT"AR6000: HIF (%s) is not a multiple of 4 bytes, addr:0x%X, len:%d\n",
request & HIF_WRITE ? "write":"read", address, length);
}
#endif
if (request & HIF_WRITE) {
if ((address >= HIF_MBOX_START_ADDR(0)) &&
(address <= HIF_MBOX_END_ADDR(3)))
{
AR_DEBUG_ASSERT(length <= HIF_MBOX_WIDTH);
/*
* Mailbox write. Adjust the address so that the last byte
* falls on the EOM address.
*/
address += (HIF_MBOX_WIDTH - length);
}
}
if (request & HIF_FIXED_ADDRESS) {
opcode = CMD53_FIXED_ADDRESS;
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: Address mode: Fixed 0x%X\n", address));
} else if (request & HIF_INCREMENTAL_ADDRESS) {
opcode = CMD53_INCR_ADDRESS;
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: Address mode: Incremental 0x%X\n", address));
} else {
AR_DEBUG_PRINTF(ATH_DEBUG_ERROR,
("AR6000: Invalid address mode: 0x%08x\n", request));
status = A_EINVAL;
break;
}
if (request & HIF_WRITE) {
#if HIF_USE_DMA_BOUNCE_BUFFER
if (BUFFER_NEEDS_BOUNCE(buffer)) {
AR_DEBUG_ASSERT(device->dma_buffer != NULL);
tbuffer = device->dma_buffer;
/* copy the write data to the dma buffer */
AR_DEBUG_ASSERT(length <= HIF_DMA_BUFFER_SIZE);
memcpy(tbuffer, buffer, length);
bounced = true;
} else {
tbuffer = buffer;
}
#else
tbuffer = buffer;
#endif
if (opcode == CMD53_FIXED_ADDRESS) {
ret = sdio_writesb(device->func, address, tbuffer, length);
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: writesb ret=%d address: 0x%X, len: %d, 0x%X\n",
ret, address, length, *(int *)tbuffer));
} else {
ret = sdio_memcpy_toio(device->func, address, tbuffer, length);
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: writeio ret=%d address: 0x%X, len: %d, 0x%X\n",
ret, address, length, *(int *)tbuffer));
}
} else if (request & HIF_READ) {
#if HIF_USE_DMA_BOUNCE_BUFFER
if (BUFFER_NEEDS_BOUNCE(buffer)) {
AR_DEBUG_ASSERT(device->dma_buffer != NULL);
AR_DEBUG_ASSERT(length <= HIF_DMA_BUFFER_SIZE);
tbuffer = device->dma_buffer;
bounced = true;
} else {
tbuffer = buffer;
}
#else
tbuffer = buffer;
#endif
if (opcode == CMD53_FIXED_ADDRESS) {
ret = sdio_readsb(device->func, tbuffer, address, length);
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: readsb ret=%d address: 0x%X, len: %d, 0x%X\n",
ret, address, length, *(int *)tbuffer));
} else {
ret = sdio_memcpy_fromio(device->func, tbuffer, address, length);
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: readio ret=%d address: 0x%X, len: %d, 0x%X\n",
ret, address, length, *(int *)tbuffer));
}
#if HIF_USE_DMA_BOUNCE_BUFFER
if (bounced) {
/* copy the read data from the dma buffer */
memcpy(buffer, tbuffer, length);
}
#endif
} else {
AR_DEBUG_PRINTF(ATH_DEBUG_ERROR,
("AR6000: Invalid direction: 0x%08x\n", request));
status = A_EINVAL;
break;
}
if (ret) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERROR,
("AR6000: SDIO bus operation failed! MMC stack returned : %d \n", ret));
status = A_ERROR;
}
} while (false);
return status;
}
void AddToAsyncList(struct hif_device *device, BUS_REQUEST *busrequest)
{
unsigned long flags;
BUS_REQUEST *async;
BUS_REQUEST *active;
spin_lock_irqsave(&device->asynclock, flags);
active = device->asyncreq;
if (active == NULL) {
device->asyncreq = busrequest;
device->asyncreq->inusenext = NULL;
} else {
for (async = device->asyncreq;
async != NULL;
async = async->inusenext) {
active = async;
}
active->inusenext = busrequest;
busrequest->inusenext = NULL;
}
spin_unlock_irqrestore(&device->asynclock, flags);
}
/* queue a read/write request */
int
HIFReadWrite(struct hif_device *device,
u32 address,
u8 *buffer,
u32 length,
u32 request,
void *context)
{
int status = 0;
BUS_REQUEST *busrequest;
AR_DEBUG_ASSERT(device != NULL);
AR_DEBUG_ASSERT(device->func != NULL);
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: Device: %p addr:0x%X\n", device,address));
do {
if ((request & HIF_ASYNCHRONOUS) || (request & HIF_SYNCHRONOUS)){
/* serialize all requests through the async thread */
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: Execution mode: %s\n",
(request & HIF_ASYNCHRONOUS)?"Async":"Synch"));
busrequest = hifAllocateBusRequest(device);
if (busrequest == NULL) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERROR,
("AR6000: no async bus requests available (%s, addr:0x%X, len:%d) \n",
request & HIF_READ ? "READ":"WRITE", address, length));
return A_ERROR;
}
busrequest->address = address;
busrequest->buffer = buffer;
busrequest->length = length;
busrequest->request = request;
busrequest->context = context;
AddToAsyncList(device, busrequest);
if (request & HIF_SYNCHRONOUS) {
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: queued sync req: 0x%lX\n", (unsigned long)busrequest));
/* wait for completion */
up(&device->sem_async);
if (down_interruptible(&busrequest->sem_req) != 0) {
/* interrupted, exit */
return A_ERROR;
} else {
int status = busrequest->status;
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: sync return freeing 0x%lX: 0x%X\n",
(unsigned long)busrequest, busrequest->status));
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: freeing req: 0x%X\n", (unsigned int)request));
hifFreeBusRequest(device, busrequest);
return status;
}
} else {
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: queued async req: 0x%lX\n", (unsigned long)busrequest));
up(&device->sem_async);
return A_PENDING;
}
} else {
AR_DEBUG_PRINTF(ATH_DEBUG_ERROR,
("AR6000: Invalid execution mode: 0x%08x\n", (unsigned int)request));
status = A_EINVAL;
break;
}
} while(0);
return status;
}
/* thread to serialize all requests, both sync and async */
static int async_task(void *param)
{
struct hif_device *device;
BUS_REQUEST *request;
int status;
unsigned long flags;
device = (struct hif_device *)param;
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: async task\n"));
set_current_state(TASK_INTERRUPTIBLE);
while(!device->async_shutdown) {
/* wait for work */
if (down_interruptible(&device->sem_async) != 0) {
/* interrupted, exit */
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: async task interrupted\n"));
break;
}
if (device->async_shutdown) {
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: async task stopping\n"));
break;
}
/* we want to hold the host over multiple cmds if possible, but holding the host blocks card interrupts */
sdio_claim_host(device->func);
spin_lock_irqsave(&device->asynclock, flags);
/* pull the request to work on */
while (device->asyncreq != NULL) {
request = device->asyncreq;
if (request->inusenext != NULL) {
device->asyncreq = request->inusenext;
} else {
device->asyncreq = NULL;
}
spin_unlock_irqrestore(&device->asynclock, flags);
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: async_task processing req: 0x%lX\n", (unsigned long)request));
if (request->pScatterReq != NULL) {
A_ASSERT(device->scatter_enabled);
/* this is a queued scatter request, pass the request to scatter routine which
* executes it synchronously, note, no need to free the request since scatter requests
* are maintained on a separate list */
status = DoHifReadWriteScatter(device,request);
} else {
/* call HIFReadWrite in sync mode to do the work */
status = __HIFReadWrite(device, request->address, request->buffer,
request->length, request->request & ~HIF_SYNCHRONOUS, NULL);
if (request->request & HIF_ASYNCHRONOUS) {
void *context = request->context;
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: async_task freeing req: 0x%lX\n", (unsigned long)request));
hifFreeBusRequest(device, request);
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: async_task completion routine req: 0x%lX\n", (unsigned long)request));
device->htcCallbacks.rwCompletionHandler(context, status);
} else {
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: async_task upping req: 0x%lX\n", (unsigned long)request));
request->status = status;
up(&request->sem_req);
}
}
spin_lock_irqsave(&device->asynclock, flags);
}
spin_unlock_irqrestore(&device->asynclock, flags);
sdio_release_host(device->func);
}
complete_and_exit(&device->async_completion, 0);
return 0;
}
static s32 IssueSDCommand(struct hif_device *device, u32 opcode, u32 arg, u32 flags, u32 *resp)
{
struct mmc_command cmd;
s32 err;
struct mmc_host *host;
struct sdio_func *func;
func = device->func;
host = func->card->host;
memset(&cmd, 0, sizeof(struct mmc_command));
cmd.opcode = opcode;
cmd.arg = arg;
cmd.flags = flags;
err = mmc_wait_for_cmd(host, &cmd, 3);
if ((!err) && (resp)) {
*resp = cmd.resp[0];
}
return err;
}
int ReinitSDIO(struct hif_device *device)
{
s32 err;
struct mmc_host *host;
struct mmc_card *card;
struct sdio_func *func;
u8 cmd52_resp;
u32 clock;
func = device->func;
card = func->card;
host = card->host;
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: +ReinitSDIO \n"));
sdio_claim_host(func);
do {
if (!device->is_suspend) {
u32 resp;
u16 rca;
u32 i;
int bit = fls(host->ocr_avail) - 1;
/* emulate the mmc_power_up(...) */
host->ios.vdd = bit;
host->ios.chip_select = MMC_CS_DONTCARE;
host->ios.bus_mode = MMC_BUSMODE_OPENDRAIN;
host->ios.power_mode = MMC_POWER_UP;
host->ios.bus_width = MMC_BUS_WIDTH_1;
host->ios.timing = MMC_TIMING_LEGACY;
host->ops->set_ios(host, &host->ios);
/*
* This delay should be sufficient to allow the power supply
* to reach the minimum voltage.
*/
msleep(2);
host->ios.clock = host->f_min;
host->ios.power_mode = MMC_POWER_ON;
host->ops->set_ios(host, &host->ios);
/*
* This delay must be at least 74 clock sizes, or 1 ms, or the
* time required to reach a stable voltage.
*/
msleep(2);
/* Issue CMD0. Goto idle state */
host->ios.chip_select = MMC_CS_HIGH;
host->ops->set_ios(host, &host->ios);
msleep(1);
err = IssueSDCommand(device, MMC_GO_IDLE_STATE, 0, (MMC_RSP_NONE | MMC_CMD_BC), NULL);
host->ios.chip_select = MMC_CS_DONTCARE;
host->ops->set_ios(host, &host->ios);
msleep(1);
host->use_spi_crc = 0;
if (err) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("ReinitSDIO: CMD0 failed : %d \n",err));
break;
}
if (!host->ocr) {
/* Issue CMD5, arg = 0 */
err = IssueSDCommand(device, SD_IO_SEND_OP_COND, 0, (MMC_RSP_R4 | MMC_CMD_BCR), &resp);
if (err) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("ReinitSDIO: CMD5 failed : %d \n",err));
break;
}
host->ocr = resp;
}
/* Issue CMD5, arg = ocr. Wait till card is ready */
for (i=0;i<100;i++) {
err = IssueSDCommand(device, SD_IO_SEND_OP_COND, host->ocr, (MMC_RSP_R4 | MMC_CMD_BCR), &resp);
if (err) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("ReinitSDIO: CMD5 failed : %d \n",err));
break;
}
if (resp & MMC_CARD_BUSY) {
break;
}
msleep(10);
}
if ((i == 100) || (err)) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("ReinitSDIO: card in not ready : %d %d \n",i,err));
break;
}
/* Issue CMD3, get RCA */
err = IssueSDCommand(device, SD_SEND_RELATIVE_ADDR, 0, MMC_RSP_R6 | MMC_CMD_BCR, &resp);
if (err) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("ReinitSDIO: CMD3 failed : %d \n",err));
break;
}
rca = resp >> 16;
host->ios.bus_mode = MMC_BUSMODE_PUSHPULL;
host->ops->set_ios(host, &host->ios);
/* Issue CMD7, select card */
err = IssueSDCommand(device, MMC_SELECT_CARD, (rca << 16), MMC_RSP_R1 | MMC_CMD_AC, NULL);
if (err) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("ReinitSDIO: CMD7 failed : %d \n",err));
break;
}
}
/* Enable high speed */
if (card->host->caps & MMC_CAP_SD_HIGHSPEED) {
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("ReinitSDIO: Set high speed mode\n"));
err = Func0_CMD52ReadByte(card, SDIO_CCCR_SPEED, &cmd52_resp);
if (err) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("ReinitSDIO: CMD52 read to CCCR speed register failed : %d \n",err));
card->state &= ~MMC_STATE_HIGHSPEED;
/* no need to break */
} else {
err = Func0_CMD52WriteByte(card, SDIO_CCCR_SPEED, (cmd52_resp | SDIO_SPEED_EHS));
if (err) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("ReinitSDIO: CMD52 write to CCCR speed register failed : %d \n",err));
break;
}
mmc_card_set_highspeed(card);
host->ios.timing = MMC_TIMING_SD_HS;
host->ops->set_ios(host, &host->ios);
}
}
/* Set clock */
if (mmc_card_highspeed(card)) {
clock = 50000000;
} else {
clock = card->cis.max_dtr;
}
if (clock > host->f_max) {
clock = host->f_max;
}
host->ios.clock = clock;
host->ops->set_ios(host, &host->ios);
if (card->host->caps & MMC_CAP_4_BIT_DATA) {
/* CMD52: Set bus width & disable card detect resistor */
err = Func0_CMD52WriteByte(card, SDIO_CCCR_IF, SDIO_BUS_CD_DISABLE | SDIO_BUS_WIDTH_4BIT);
if (err) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("ReinitSDIO: CMD52 to set bus mode failed : %d \n",err));
break;
}
host->ios.bus_width = MMC_BUS_WIDTH_4;
host->ops->set_ios(host, &host->ios);
}
} while (0);
sdio_release_host(func);
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: -ReinitSDIO \n"));
return (err) ? A_ERROR : 0;
}
int
PowerStateChangeNotify(struct hif_device *device, HIF_DEVICE_POWER_CHANGE_TYPE config)
{
int status = 0;
#if defined(CONFIG_PM)
struct sdio_func *func = device->func;
int old_reset_val;
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: +PowerStateChangeNotify %d\n", config));
switch (config) {
case HIF_DEVICE_POWER_DOWN:
case HIF_DEVICE_POWER_CUT:
old_reset_val = reset_sdio_on_unload;
reset_sdio_on_unload = 1;
status = hifDisableFunc(device, func);
reset_sdio_on_unload = old_reset_val;
if (!device->is_suspend) {
struct mmc_host *host = func->card->host;
host->ios.clock = 0;
host->ios.vdd = 0;
host->ios.bus_mode = MMC_BUSMODE_OPENDRAIN;
host->ios.chip_select = MMC_CS_DONTCARE;
host->ios.power_mode = MMC_POWER_OFF;
host->ios.bus_width = MMC_BUS_WIDTH_1;
host->ios.timing = MMC_TIMING_LEGACY;
host->ops->set_ios(host, &host->ios);
}
break;
case HIF_DEVICE_POWER_UP:
if (device->powerConfig == HIF_DEVICE_POWER_CUT) {
status = ReinitSDIO(device);
}
if (status == 0) {
status = hifEnableFunc(device, func);
}
break;
}
device->powerConfig = config;
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: -PowerStateChangeNotify\n"));
#endif
return status;
}
int
HIFConfigureDevice(struct hif_device *device, HIF_DEVICE_CONFIG_OPCODE opcode,
void *config, u32 configLen)
{
u32 count;
int status = 0;
switch(opcode) {
case HIF_DEVICE_GET_MBOX_BLOCK_SIZE:
((u32 *)config)[0] = HIF_MBOX0_BLOCK_SIZE;
((u32 *)config)[1] = HIF_MBOX1_BLOCK_SIZE;
((u32 *)config)[2] = HIF_MBOX2_BLOCK_SIZE;
((u32 *)config)[3] = HIF_MBOX3_BLOCK_SIZE;
break;
case HIF_DEVICE_GET_MBOX_ADDR:
for (count = 0; count < 4; count ++) {
((u32 *)config)[count] = HIF_MBOX_START_ADDR(count);
}
if (configLen >= sizeof(struct hif_device_mbox_info)) {
SetExtendedMboxWindowInfo((u16)device->func->device,
(struct hif_device_mbox_info *)config);
}
break;
case HIF_DEVICE_GET_IRQ_PROC_MODE:
*((HIF_DEVICE_IRQ_PROCESSING_MODE *)config) = HIF_DEVICE_IRQ_SYNC_ONLY;
break;
case HIF_CONFIGURE_QUERY_SCATTER_REQUEST_SUPPORT:
if (!device->scatter_enabled) {
return A_ENOTSUP;
}
status = SetupHIFScatterSupport(device, (struct hif_device_scatter_support_info *)config);
if (status) {
device->scatter_enabled = false;
}
break;
case HIF_DEVICE_GET_OS_DEVICE:
/* pass back a pointer to the SDIO function's "dev" struct */
((struct hif_device_os_device_info *)config)->pOSDevice = &device->func->dev;
break;
case HIF_DEVICE_POWER_STATE_CHANGE:
status = PowerStateChangeNotify(device, *(HIF_DEVICE_POWER_CHANGE_TYPE *)config);
break;
default:
AR_DEBUG_PRINTF(ATH_DEBUG_WARN,
("AR6000: Unsupported configuration opcode: %d\n", opcode));
status = A_ERROR;
}
return status;
}
void
HIFShutDownDevice(struct hif_device *device)
{
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: +HIFShutDownDevice\n"));
if (device != NULL) {
AR_DEBUG_ASSERT(device->func != NULL);
} else {
/* since we are unloading the driver anyways, reset all cards in case the SDIO card
* is externally powered and we are unloading the SDIO stack. This avoids the problem when
* the SDIO stack is reloaded and attempts are made to re-enumerate a card that is already
* enumerated */
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: HIFShutDownDevice, resetting\n"));
ResetAllCards();
/* Unregister with bus driver core */
if (registered) {
registered = 0;
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE,
("AR6000: Unregistering with the bus driver\n"));
sdio_unregister_driver(&ar6k_driver);
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE,
("AR6000: Unregistered\n"));
}
}
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: -HIFShutDownDevice\n"));
}
static void
hifIRQHandler(struct sdio_func *func)
{
int status;
struct hif_device *device;
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: +hifIRQHandler\n"));
device = getHifDevice(func);
atomic_set(&device->irqHandling, 1);
/* release the host during ints so we can pick it back up when we process cmds */
sdio_release_host(device->func);
status = device->htcCallbacks.dsrHandler(device->htcCallbacks.context);
sdio_claim_host(device->func);
atomic_set(&device->irqHandling, 0);
AR_DEBUG_ASSERT(status == 0 || status == A_ECANCELED);
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: -hifIRQHandler\n"));
}
/* handle HTC startup via thread*/
static int startup_task(void *param)
{
struct hif_device *device;
device = (struct hif_device *)param;
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: call HTC from startup_task\n"));
/* start up inform DRV layer */
if ((osdrvCallbacks.deviceInsertedHandler(osdrvCallbacks.context,device)) != 0) {
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: Device rejected\n"));
}
return 0;
}
#if defined(CONFIG_PM)
static int enable_task(void *param)
{
struct hif_device *device;
device = (struct hif_device *)param;
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: call from resume_task\n"));
/* start up inform DRV layer */
if (device &&
device->claimedContext &&
osdrvCallbacks.devicePowerChangeHandler &&
osdrvCallbacks.devicePowerChangeHandler(device->claimedContext, HIF_DEVICE_POWER_UP) != 0)
{
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: Device rejected\n"));
}
return 0;
}
#endif
static int hifDeviceInserted(struct sdio_func *func, const struct sdio_device_id *id)
{
int ret;
struct hif_device * device;
int count;
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE,
("AR6000: hifDeviceInserted, Function: 0x%X, Vendor ID: 0x%X, Device ID: 0x%X, block size: 0x%X/0x%X\n",
func->num, func->vendor, func->device, func->max_blksize, func->cur_blksize));
addHifDevice(func);
device = getHifDevice(func);
device->id = id;
device->is_disabled = true;
spin_lock_init(&device->lock);
spin_lock_init(&device->asynclock);
DL_LIST_INIT(&device->ScatterReqHead);
if (!nohifscattersupport) {
/* try to allow scatter operation on all instances,
* unless globally overridden */
device->scatter_enabled = true;
}
/* Initialize the bus requests to be used later */
A_MEMZERO(device->busRequest, sizeof(device->busRequest));
for (count = 0; count < BUS_REQUEST_MAX_NUM; count ++) {
sema_init(&device->busRequest[count].sem_req, 0);
hifFreeBusRequest(device, &device->busRequest[count]);
}
sema_init(&device->sem_async, 0);
ret = hifEnableFunc(device, func);
return ret;
}
void
HIFAckInterrupt(struct hif_device *device)
{
AR_DEBUG_ASSERT(device != NULL);
/* Acknowledge our function IRQ */
}
void
HIFUnMaskInterrupt(struct hif_device *device)
{
int ret;
AR_DEBUG_ASSERT(device != NULL);
AR_DEBUG_ASSERT(device->func != NULL);
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: HIFUnMaskInterrupt\n"));
/* Register the IRQ Handler */
sdio_claim_host(device->func);
ret = sdio_claim_irq(device->func, hifIRQHandler);
sdio_release_host(device->func);
AR_DEBUG_ASSERT(ret == 0);
}
void HIFMaskInterrupt(struct hif_device *device)
{
int ret;
AR_DEBUG_ASSERT(device != NULL);
AR_DEBUG_ASSERT(device->func != NULL);
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: HIFMaskInterrupt\n"));
/* Mask our function IRQ */
sdio_claim_host(device->func);
while (atomic_read(&device->irqHandling)) {
sdio_release_host(device->func);
schedule_timeout(HZ/10);
sdio_claim_host(device->func);
}
ret = sdio_release_irq(device->func);
sdio_release_host(device->func);
AR_DEBUG_ASSERT(ret == 0);
}
BUS_REQUEST *hifAllocateBusRequest(struct hif_device *device)
{
BUS_REQUEST *busrequest;
unsigned long flag;
/* Acquire lock */
spin_lock_irqsave(&device->lock, flag);
/* Remove first in list */
if((busrequest = device->s_busRequestFreeQueue) != NULL)
{
device->s_busRequestFreeQueue = busrequest->next;
}
/* Release lock */
spin_unlock_irqrestore(&device->lock, flag);
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: hifAllocateBusRequest: 0x%p\n", busrequest));
return busrequest;
}
void
hifFreeBusRequest(struct hif_device *device, BUS_REQUEST *busrequest)
{
unsigned long flag;
AR_DEBUG_ASSERT(busrequest != NULL);
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: hifFreeBusRequest: 0x%p\n", busrequest));
/* Acquire lock */
spin_lock_irqsave(&device->lock, flag);
/* Insert first in list */
busrequest->next = device->s_busRequestFreeQueue;
busrequest->inusenext = NULL;
device->s_busRequestFreeQueue = busrequest;
/* Release lock */
spin_unlock_irqrestore(&device->lock, flag);
}
static int hifDisableFunc(struct hif_device *device, struct sdio_func *func)
{
int ret;
int status = 0;
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: +hifDisableFunc\n"));
device = getHifDevice(func);
if (!IS_ERR(device->async_task)) {
init_completion(&device->async_completion);
device->async_shutdown = 1;
up(&device->sem_async);
wait_for_completion(&device->async_completion);
device->async_task = NULL;
}
/* Disable the card */
sdio_claim_host(device->func);
ret = sdio_disable_func(device->func);
if (ret) {
status = A_ERROR;
}
if (reset_sdio_on_unload) {
/* reset the SDIO interface. This is useful in automated testing where the card
* does not need to be removed at the end of the test. It is expected that the user will
* also unload/reload the host controller driver to force the bus driver to re-enumerate the slot */
AR_DEBUG_PRINTF(ATH_DEBUG_WARN, ("AR6000: reseting SDIO card back to uninitialized state \n"));
/* NOTE : sdio_f0_writeb() cannot be used here, that API only allows access
* to undefined registers in the range of: 0xF0-0xFF */
ret = Func0_CMD52WriteByte(device->func->card, SDIO_CCCR_ABORT, (1 << 3));
if (ret) {
status = A_ERROR;
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("AR6000: reset failed : %d \n",ret));
}
}
sdio_release_host(device->func);
if (status == 0) {
device->is_disabled = true;
}
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: -hifDisableFunc\n"));
return status;
}
static int hifEnableFunc(struct hif_device *device, struct sdio_func *func)
{
struct task_struct* pTask;
const char *taskName = NULL;
int (*taskFunc)(void *) = NULL;
int ret = 0;
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: +hifEnableFunc\n"));
device = getHifDevice(func);
if (device->is_disabled) {
/* enable the SDIO function */
sdio_claim_host(func);
if ((device->id->device & MANUFACTURER_ID_AR6K_BASE_MASK) >= MANUFACTURER_ID_AR6003_BASE) {
/* enable 4-bit ASYNC interrupt on AR6003 or later devices */
ret = Func0_CMD52WriteByte(func->card, CCCR_SDIO_IRQ_MODE_REG, SDIO_IRQ_MODE_ASYNC_4BIT_IRQ);
if (ret) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR, ("AR6000: failed to enable 4-bit ASYNC IRQ mode %d \n",ret));
sdio_release_host(func);
return A_ERROR;
}
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: 4-bit ASYNC IRQ mode enabled\n"));
}
/* give us some time to enable, in ms */
func->enable_timeout = 100;
ret = sdio_enable_func(func);
if (ret) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERROR, ("AR6000: %s(), Unable to enable AR6K: 0x%X\n",
__FUNCTION__, ret));
sdio_release_host(func);
return A_ERROR;
}
ret = sdio_set_block_size(func, HIF_MBOX_BLOCK_SIZE);
sdio_release_host(func);
if (ret) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERROR, ("AR6000: %s(), Unable to set block size 0x%x AR6K: 0x%X\n",
__FUNCTION__, HIF_MBOX_BLOCK_SIZE, ret));
return A_ERROR;
}
device->is_disabled = false;
/* create async I/O thread */
if (!device->async_task) {
device->async_shutdown = 0;
device->async_task = kthread_create(async_task,
(void *)device,
"AR6K Async");
if (IS_ERR(device->async_task)) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERROR, ("AR6000: %s(), to create async task\n", __FUNCTION__));
return A_ERROR;
}
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: start async task\n"));
wake_up_process(device->async_task );
}
}
if (!device->claimedContext) {
taskFunc = startup_task;
taskName = "AR6K startup";
ret = 0;
#if defined(CONFIG_PM)
} else {
taskFunc = enable_task;
taskName = "AR6K enable";
ret = A_PENDING;
#endif /* CONFIG_PM */
}
/* create resume thread */
pTask = kthread_create(taskFunc, (void *)device, taskName);
if (IS_ERR(pTask)) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERROR, ("AR6000: %s(), to create enabel task\n", __FUNCTION__));
return A_ERROR;
}
wake_up_process(pTask);
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: -hifEnableFunc\n"));
/* task will call the enable func, indicate pending */
return ret;
}
#if defined(CONFIG_PM)
static int hifDeviceSuspend(struct device *dev)
{
struct sdio_func *func=dev_to_sdio_func(dev);
int status = 0;
struct hif_device *device;
device = getHifDevice(func);
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: +hifDeviceSuspend\n"));
if (device && device->claimedContext && osdrvCallbacks.deviceSuspendHandler) {
device->is_suspend = true; /* set true first for PowerStateChangeNotify(..) */
status = osdrvCallbacks.deviceSuspendHandler(device->claimedContext);
if (status) {
device->is_suspend = false;
}
}
CleanupHIFScatterResources(device);
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: -hifDeviceSuspend\n"));
switch (status) {
case 0:
return 0;
case A_EBUSY:
return -EBUSY; /* Hack for kernel in order to support deep sleep and wow */
default:
return -1;
}
}
static int hifDeviceResume(struct device *dev)
{
struct sdio_func *func=dev_to_sdio_func(dev);
int status = 0;
struct hif_device *device;
device = getHifDevice(func);
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: +hifDeviceResume\n"));
if (device && device->claimedContext && osdrvCallbacks.deviceSuspendHandler) {
status = osdrvCallbacks.deviceResumeHandler(device->claimedContext);
if (status == 0) {
device->is_suspend = false;
}
}
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: -hifDeviceResume\n"));
return status;
}
#endif /* CONFIG_PM */
static void hifDeviceRemoved(struct sdio_func *func)
{
int status = 0;
struct hif_device *device;
AR_DEBUG_ASSERT(func != NULL);
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: +hifDeviceRemoved\n"));
device = getHifDevice(func);
if (device->claimedContext != NULL) {
status = osdrvCallbacks.deviceRemovedHandler(device->claimedContext, device);
}
if (device->is_disabled) {
device->is_disabled = false;
} else {
status = hifDisableFunc(device, func);
}
CleanupHIFScatterResources(device);
delHifDevice(device);
AR_DEBUG_ASSERT(status == 0);
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: -hifDeviceRemoved\n"));
}
/*
* This should be moved to AR6K HTC layer.
*/
int hifWaitForPendingRecv(struct hif_device *device)
{
s32 cnt = 10;
u8 host_int_status;
int status = 0;
do {
while (atomic_read(&device->irqHandling)) {
/* wait until irq handler finished all the jobs */
schedule_timeout(HZ/10);
}
/* check if there is any pending irq due to force done */
host_int_status = 0;
status = HIFReadWrite(device, HOST_INT_STATUS_ADDRESS,
(u8 *)&host_int_status, sizeof(host_int_status),
HIF_RD_SYNC_BYTE_INC, NULL);
host_int_status = !status ? (host_int_status & (1 << 0)) : 0;
if (host_int_status) {
schedule(); /* schedule for next dsrHandler */
}
} while (host_int_status && --cnt > 0);
if (host_int_status && cnt == 0) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERROR,
("AR6000: %s(), Unable clear up pending IRQ before the system suspended\n", __FUNCTION__));
}
return 0;
}
static struct hif_device *
addHifDevice(struct sdio_func *func)
{
struct hif_device *hifdevice;
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: addHifDevice\n"));
AR_DEBUG_ASSERT(func != NULL);
hifdevice = kzalloc(sizeof(struct hif_device), GFP_KERNEL);
AR_DEBUG_ASSERT(hifdevice != NULL);
#if HIF_USE_DMA_BOUNCE_BUFFER
hifdevice->dma_buffer = kmalloc(HIF_DMA_BUFFER_SIZE, GFP_KERNEL);
AR_DEBUG_ASSERT(hifdevice->dma_buffer != NULL);
#endif
hifdevice->func = func;
hifdevice->powerConfig = HIF_DEVICE_POWER_UP;
sdio_set_drvdata(func, hifdevice);
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: addHifDevice; 0x%p\n", hifdevice));
return hifdevice;
}
static struct hif_device *
getHifDevice(struct sdio_func *func)
{
AR_DEBUG_ASSERT(func != NULL);
return (struct hif_device *)sdio_get_drvdata(func);
}
static void
delHifDevice(struct hif_device * device)
{
AR_DEBUG_ASSERT(device!= NULL);
AR_DEBUG_PRINTF(ATH_DEBUG_TRACE, ("AR6000: delHifDevice; 0x%p\n", device));
kfree(device->dma_buffer);
kfree(device);
}
static void ResetAllCards(void)
{
}
void HIFClaimDevice(struct hif_device *device, void *context)
{
device->claimedContext = context;
}
void HIFReleaseDevice(struct hif_device *device)
{
device->claimedContext = NULL;
}
int HIFAttachHTC(struct hif_device *device, HTC_CALLBACKS *callbacks)
{
if (device->htcCallbacks.context != NULL) {
/* already in use! */
return A_ERROR;
}
device->htcCallbacks = *callbacks;
return 0;
}
void HIFDetachHTC(struct hif_device *device)
{
A_MEMZERO(&device->htcCallbacks,sizeof(device->htcCallbacks));
}
#define SDIO_SET_CMD52_ARG(arg,rw,func,raw,address,writedata) \
(arg) = (((rw) & 1) << 31) | \
(((func) & 0x7) << 28) | \
(((raw) & 1) << 27) | \
(1 << 26) | \
(((address) & 0x1FFFF) << 9) | \
(1 << 8) | \
((writedata) & 0xFF)
#define SDIO_SET_CMD52_READ_ARG(arg,func,address) \
SDIO_SET_CMD52_ARG(arg,0,(func),0,address,0x00)
#define SDIO_SET_CMD52_WRITE_ARG(arg,func,address,value) \
SDIO_SET_CMD52_ARG(arg,1,(func),0,address,value)
static int Func0_CMD52WriteByte(struct mmc_card *card, unsigned int address, unsigned char byte)
{
struct mmc_command ioCmd;
unsigned long arg;
memset(&ioCmd,0,sizeof(ioCmd));
SDIO_SET_CMD52_WRITE_ARG(arg,0,address,byte);
ioCmd.opcode = SD_IO_RW_DIRECT;
ioCmd.arg = arg;
ioCmd.flags = MMC_RSP_R5 | MMC_CMD_AC;
return mmc_wait_for_cmd(card->host, &ioCmd, 0);
}
static int Func0_CMD52ReadByte(struct mmc_card *card, unsigned int address, unsigned char *byte)
{
struct mmc_command ioCmd;
unsigned long arg;
s32 err;
memset(&ioCmd,0,sizeof(ioCmd));
SDIO_SET_CMD52_READ_ARG(arg,0,address);
ioCmd.opcode = SD_IO_RW_DIRECT;
ioCmd.arg = arg;
ioCmd.flags = MMC_RSP_R5 | MMC_CMD_AC;
err = mmc_wait_for_cmd(card->host, &ioCmd, 0);
if ((!err) && (byte)) {
*byte = ioCmd.resp[0] & 0xFF;
}
return err;
}
| gpl-2.0 |
jamal-ahmad/Logging-Kernel | arch/x86/entry/vdso/vdso32-setup.c | 170 | 1906 | /*
* (C) Copyright 2002 Linus Torvalds
* Portions based on the vdso-randomization code from exec-shield:
* Copyright(C) 2005-2006, Red Hat, Inc., Ingo Molnar
*
* This file contains the needed initializations to support sysenter.
*/
#include <linux/init.h>
#include <linux/smp.h>
#include <linux/kernel.h>
#include <linux/mm_types.h>
#include <asm/cpufeature.h>
#include <asm/processor.h>
#include <asm/vdso.h>
#ifdef CONFIG_COMPAT_VDSO
#define VDSO_DEFAULT 0
#else
#define VDSO_DEFAULT 1
#endif
/*
* Should the kernel map a VDSO page into processes and pass its
* address down to glibc upon exec()?
*/
unsigned int __read_mostly vdso32_enabled = VDSO_DEFAULT;
static int __init vdso32_setup(char *s)
{
vdso32_enabled = simple_strtoul(s, NULL, 0);
if (vdso32_enabled > 1)
pr_warn("vdso32 values other than 0 and 1 are no longer allowed; vdso disabled\n");
return 1;
}
/*
* For consistency, the argument vdso32=[012] affects the 32-bit vDSO
* behavior on both 64-bit and 32-bit kernels.
* On 32-bit kernels, vdso=[012] means the same thing.
*/
__setup("vdso32=", vdso32_setup);
#ifdef CONFIG_X86_32
__setup_param("vdso=", vdso_setup, vdso32_setup, 0);
#endif
int __init sysenter_setup(void)
{
init_vdso_image(&vdso_image_32);
return 0;
}
#ifdef CONFIG_X86_64
subsys_initcall(sysenter_setup);
#ifdef CONFIG_SYSCTL
/* Register vsyscall32 into the ABI table */
#include <linux/sysctl.h>
static struct ctl_table abi_table2[] = {
{
.procname = "vsyscall32",
.data = &vdso32_enabled,
.maxlen = sizeof(int),
.mode = 0644,
.proc_handler = proc_dointvec
},
{}
};
static struct ctl_table abi_root_table2[] = {
{
.procname = "abi",
.mode = 0555,
.child = abi_table2
},
{}
};
static __init int ia32_binfmt_init(void)
{
register_sysctl_table(abi_root_table2);
return 0;
}
__initcall(ia32_binfmt_init);
#endif /* CONFIG_SYSCTL */
#endif /* CONFIG_X86_64 */
| gpl-2.0 |
kaneawk/android_kernel_motorola_msm8996 | drivers/media/v4l2-core/videobuf-dma-sg.c | 426 | 16925 | /*
* helper functions for SG DMA video4linux capture buffers
*
* The functions expect the hardware being able to scatter gather
* (i.e. the buffers are not linear in physical memory, but fragmented
* into PAGE_SIZE chunks). They also assume the driver does not need
* to touch the video data.
*
* (c) 2007 Mauro Carvalho Chehab, <mchehab@infradead.org>
*
* Highly based on video-buf written originally by:
* (c) 2001,02 Gerd Knorr <kraxel@bytesex.org>
* (c) 2006 Mauro Carvalho Chehab, <mchehab@infradead.org>
* (c) 2006 Ted Walther and John Sokol
*
* 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
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/dma-mapping.h>
#include <linux/vmalloc.h>
#include <linux/pagemap.h>
#include <linux/scatterlist.h>
#include <asm/page.h>
#include <asm/pgtable.h>
#include <media/videobuf-dma-sg.h>
#define MAGIC_DMABUF 0x19721112
#define MAGIC_SG_MEM 0x17890714
#define MAGIC_CHECK(is, should) \
if (unlikely((is) != (should))) { \
printk(KERN_ERR "magic mismatch: %x (expected %x)\n", \
is, should); \
BUG(); \
}
static int debug;
module_param(debug, int, 0644);
MODULE_DESCRIPTION("helper module to manage video4linux dma sg buffers");
MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@infradead.org>");
MODULE_LICENSE("GPL");
#define dprintk(level, fmt, arg...) \
if (debug >= level) \
printk(KERN_DEBUG "vbuf-sg: " fmt , ## arg)
/* --------------------------------------------------------------------- */
/*
* Return a scatterlist for some page-aligned vmalloc()'ed memory
* block (NULL on errors). Memory for the scatterlist is allocated
* using kmalloc. The caller must free the memory.
*/
static struct scatterlist *videobuf_vmalloc_to_sg(unsigned char *virt,
int nr_pages)
{
struct scatterlist *sglist;
struct page *pg;
int i;
sglist = vzalloc(nr_pages * sizeof(*sglist));
if (NULL == sglist)
return NULL;
sg_init_table(sglist, nr_pages);
for (i = 0; i < nr_pages; i++, virt += PAGE_SIZE) {
pg = vmalloc_to_page(virt);
if (NULL == pg)
goto err;
BUG_ON(PageHighMem(pg));
sg_set_page(&sglist[i], pg, PAGE_SIZE, 0);
}
return sglist;
err:
vfree(sglist);
return NULL;
}
/*
* Return a scatterlist for a an array of userpages (NULL on errors).
* Memory for the scatterlist is allocated using kmalloc. The caller
* must free the memory.
*/
static struct scatterlist *videobuf_pages_to_sg(struct page **pages,
int nr_pages, int offset, size_t size)
{
struct scatterlist *sglist;
int i;
if (NULL == pages[0])
return NULL;
sglist = vmalloc(nr_pages * sizeof(*sglist));
if (NULL == sglist)
return NULL;
sg_init_table(sglist, nr_pages);
if (PageHighMem(pages[0]))
/* DMA to highmem pages might not work */
goto highmem;
sg_set_page(&sglist[0], pages[0],
min_t(size_t, PAGE_SIZE - offset, size), offset);
size -= min_t(size_t, PAGE_SIZE - offset, size);
for (i = 1; i < nr_pages; i++) {
if (NULL == pages[i])
goto nopage;
if (PageHighMem(pages[i]))
goto highmem;
sg_set_page(&sglist[i], pages[i], min_t(size_t, PAGE_SIZE, size), 0);
size -= min_t(size_t, PAGE_SIZE, size);
}
return sglist;
nopage:
dprintk(2, "sgl: oops - no page\n");
vfree(sglist);
return NULL;
highmem:
dprintk(2, "sgl: oops - highmem page\n");
vfree(sglist);
return NULL;
}
/* --------------------------------------------------------------------- */
struct videobuf_dmabuf *videobuf_to_dma(struct videobuf_buffer *buf)
{
struct videobuf_dma_sg_memory *mem = buf->priv;
BUG_ON(!mem);
MAGIC_CHECK(mem->magic, MAGIC_SG_MEM);
return &mem->dma;
}
EXPORT_SYMBOL_GPL(videobuf_to_dma);
void videobuf_dma_init(struct videobuf_dmabuf *dma)
{
memset(dma, 0, sizeof(*dma));
dma->magic = MAGIC_DMABUF;
}
EXPORT_SYMBOL_GPL(videobuf_dma_init);
static int videobuf_dma_init_user_locked(struct videobuf_dmabuf *dma,
int direction, unsigned long data, unsigned long size)
{
unsigned long first, last;
int err, rw = 0;
dma->direction = direction;
switch (dma->direction) {
case DMA_FROM_DEVICE:
rw = READ;
break;
case DMA_TO_DEVICE:
rw = WRITE;
break;
default:
BUG();
}
first = (data & PAGE_MASK) >> PAGE_SHIFT;
last = ((data+size-1) & PAGE_MASK) >> PAGE_SHIFT;
dma->offset = data & ~PAGE_MASK;
dma->size = size;
dma->nr_pages = last-first+1;
dma->pages = kmalloc(dma->nr_pages * sizeof(struct page *), GFP_KERNEL);
if (NULL == dma->pages)
return -ENOMEM;
dprintk(1, "init user [0x%lx+0x%lx => %d pages]\n",
data, size, dma->nr_pages);
err = get_user_pages(current, current->mm,
data & PAGE_MASK, dma->nr_pages,
rw == READ, 1, /* force */
dma->pages, NULL);
if (err != dma->nr_pages) {
dma->nr_pages = (err >= 0) ? err : 0;
dprintk(1, "get_user_pages: err=%d [%d]\n", err, dma->nr_pages);
return err < 0 ? err : -EINVAL;
}
return 0;
}
int videobuf_dma_init_user(struct videobuf_dmabuf *dma, int direction,
unsigned long data, unsigned long size)
{
int ret;
down_read(¤t->mm->mmap_sem);
ret = videobuf_dma_init_user_locked(dma, direction, data, size);
up_read(¤t->mm->mmap_sem);
return ret;
}
EXPORT_SYMBOL_GPL(videobuf_dma_init_user);
int videobuf_dma_init_kernel(struct videobuf_dmabuf *dma, int direction,
int nr_pages)
{
int i;
dprintk(1, "init kernel [%d pages]\n", nr_pages);
dma->direction = direction;
dma->vaddr_pages = kcalloc(nr_pages, sizeof(*dma->vaddr_pages),
GFP_KERNEL);
if (!dma->vaddr_pages)
return -ENOMEM;
dma->dma_addr = kcalloc(nr_pages, sizeof(*dma->dma_addr), GFP_KERNEL);
if (!dma->dma_addr) {
kfree(dma->vaddr_pages);
return -ENOMEM;
}
for (i = 0; i < nr_pages; i++) {
void *addr;
addr = dma_alloc_coherent(dma->dev, PAGE_SIZE,
&(dma->dma_addr[i]), GFP_KERNEL);
if (addr == NULL)
goto out_free_pages;
dma->vaddr_pages[i] = virt_to_page(addr);
}
dma->vaddr = vmap(dma->vaddr_pages, nr_pages, VM_MAP | VM_IOREMAP,
PAGE_KERNEL);
if (NULL == dma->vaddr) {
dprintk(1, "vmalloc_32(%d pages) failed\n", nr_pages);
goto out_free_pages;
}
dprintk(1, "vmalloc is at addr 0x%08lx, size=%d\n",
(unsigned long)dma->vaddr,
nr_pages << PAGE_SHIFT);
memset(dma->vaddr, 0, nr_pages << PAGE_SHIFT);
dma->nr_pages = nr_pages;
return 0;
out_free_pages:
while (i > 0) {
void *addr;
i--;
addr = page_address(dma->vaddr_pages[i]);
dma_free_coherent(dma->dev, PAGE_SIZE, addr, dma->dma_addr[i]);
}
kfree(dma->dma_addr);
dma->dma_addr = NULL;
kfree(dma->vaddr_pages);
dma->vaddr_pages = NULL;
return -ENOMEM;
}
EXPORT_SYMBOL_GPL(videobuf_dma_init_kernel);
int videobuf_dma_init_overlay(struct videobuf_dmabuf *dma, int direction,
dma_addr_t addr, int nr_pages)
{
dprintk(1, "init overlay [%d pages @ bus 0x%lx]\n",
nr_pages, (unsigned long)addr);
dma->direction = direction;
if (0 == addr)
return -EINVAL;
dma->bus_addr = addr;
dma->nr_pages = nr_pages;
return 0;
}
EXPORT_SYMBOL_GPL(videobuf_dma_init_overlay);
int videobuf_dma_map(struct device *dev, struct videobuf_dmabuf *dma)
{
MAGIC_CHECK(dma->magic, MAGIC_DMABUF);
BUG_ON(0 == dma->nr_pages);
if (dma->pages) {
dma->sglist = videobuf_pages_to_sg(dma->pages, dma->nr_pages,
dma->offset, dma->size);
}
if (dma->vaddr) {
dma->sglist = videobuf_vmalloc_to_sg(dma->vaddr,
dma->nr_pages);
}
if (dma->bus_addr) {
dma->sglist = vmalloc(sizeof(*dma->sglist));
if (NULL != dma->sglist) {
dma->sglen = 1;
sg_dma_address(&dma->sglist[0]) = dma->bus_addr
& PAGE_MASK;
dma->sglist[0].offset = dma->bus_addr & ~PAGE_MASK;
sg_dma_len(&dma->sglist[0]) = dma->nr_pages * PAGE_SIZE;
}
}
if (NULL == dma->sglist) {
dprintk(1, "scatterlist is NULL\n");
return -ENOMEM;
}
if (!dma->bus_addr) {
dma->sglen = dma_map_sg(dev, dma->sglist,
dma->nr_pages, dma->direction);
if (0 == dma->sglen) {
printk(KERN_WARNING
"%s: videobuf_map_sg failed\n", __func__);
vfree(dma->sglist);
dma->sglist = NULL;
dma->sglen = 0;
return -ENOMEM;
}
}
return 0;
}
EXPORT_SYMBOL_GPL(videobuf_dma_map);
int videobuf_dma_unmap(struct device *dev, struct videobuf_dmabuf *dma)
{
MAGIC_CHECK(dma->magic, MAGIC_DMABUF);
if (!dma->sglen)
return 0;
dma_unmap_sg(dev, dma->sglist, dma->sglen, dma->direction);
vfree(dma->sglist);
dma->sglist = NULL;
dma->sglen = 0;
return 0;
}
EXPORT_SYMBOL_GPL(videobuf_dma_unmap);
int videobuf_dma_free(struct videobuf_dmabuf *dma)
{
int i;
MAGIC_CHECK(dma->magic, MAGIC_DMABUF);
BUG_ON(dma->sglen);
if (dma->pages) {
for (i = 0; i < dma->nr_pages; i++)
page_cache_release(dma->pages[i]);
kfree(dma->pages);
dma->pages = NULL;
}
if (dma->dma_addr) {
for (i = 0; i < dma->nr_pages; i++) {
void *addr;
addr = page_address(dma->vaddr_pages[i]);
dma_free_coherent(dma->dev, PAGE_SIZE, addr,
dma->dma_addr[i]);
}
kfree(dma->dma_addr);
dma->dma_addr = NULL;
kfree(dma->vaddr_pages);
dma->vaddr_pages = NULL;
vunmap(dma->vaddr);
dma->vaddr = NULL;
}
if (dma->bus_addr)
dma->bus_addr = 0;
dma->direction = DMA_NONE;
return 0;
}
EXPORT_SYMBOL_GPL(videobuf_dma_free);
/* --------------------------------------------------------------------- */
static void videobuf_vm_open(struct vm_area_struct *vma)
{
struct videobuf_mapping *map = vma->vm_private_data;
dprintk(2, "vm_open %p [count=%d,vma=%08lx-%08lx]\n", map,
map->count, vma->vm_start, vma->vm_end);
map->count++;
}
static void videobuf_vm_close(struct vm_area_struct *vma)
{
struct videobuf_mapping *map = vma->vm_private_data;
struct videobuf_queue *q = map->q;
struct videobuf_dma_sg_memory *mem;
int i;
dprintk(2, "vm_close %p [count=%d,vma=%08lx-%08lx]\n", map,
map->count, vma->vm_start, vma->vm_end);
map->count--;
if (0 == map->count) {
dprintk(1, "munmap %p q=%p\n", map, q);
videobuf_queue_lock(q);
for (i = 0; i < VIDEO_MAX_FRAME; i++) {
if (NULL == q->bufs[i])
continue;
mem = q->bufs[i]->priv;
if (!mem)
continue;
MAGIC_CHECK(mem->magic, MAGIC_SG_MEM);
if (q->bufs[i]->map != map)
continue;
q->bufs[i]->map = NULL;
q->bufs[i]->baddr = 0;
q->ops->buf_release(q, q->bufs[i]);
}
videobuf_queue_unlock(q);
kfree(map);
}
return;
}
/*
* Get a anonymous page for the mapping. Make sure we can DMA to that
* memory location with 32bit PCI devices (i.e. don't use highmem for
* now ...). Bounce buffers don't work very well for the data rates
* video capture has.
*/
static int videobuf_vm_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
struct page *page;
dprintk(3, "fault: fault @ %08lx [vma %08lx-%08lx]\n",
(unsigned long)vmf->virtual_address,
vma->vm_start, vma->vm_end);
page = alloc_page(GFP_USER | __GFP_DMA32);
if (!page)
return VM_FAULT_OOM;
clear_user_highpage(page, (unsigned long)vmf->virtual_address);
vmf->page = page;
return 0;
}
static const struct vm_operations_struct videobuf_vm_ops = {
.open = videobuf_vm_open,
.close = videobuf_vm_close,
.fault = videobuf_vm_fault,
};
/* ---------------------------------------------------------------------
* SG handlers for the generic methods
*/
/* Allocated area consists on 3 parts:
struct video_buffer
struct <driver>_buffer (cx88_buffer, saa7134_buf, ...)
struct videobuf_dma_sg_memory
*/
static struct videobuf_buffer *__videobuf_alloc_vb(size_t size)
{
struct videobuf_dma_sg_memory *mem;
struct videobuf_buffer *vb;
vb = kzalloc(size + sizeof(*mem), GFP_KERNEL);
if (!vb)
return vb;
mem = vb->priv = ((char *)vb) + size;
mem->magic = MAGIC_SG_MEM;
videobuf_dma_init(&mem->dma);
dprintk(1, "%s: allocated at %p(%ld+%ld) & %p(%ld)\n",
__func__, vb, (long)sizeof(*vb), (long)size - sizeof(*vb),
mem, (long)sizeof(*mem));
return vb;
}
static void *__videobuf_to_vaddr(struct videobuf_buffer *buf)
{
struct videobuf_dma_sg_memory *mem = buf->priv;
BUG_ON(!mem);
MAGIC_CHECK(mem->magic, MAGIC_SG_MEM);
return mem->dma.vaddr;
}
static int __videobuf_iolock(struct videobuf_queue *q,
struct videobuf_buffer *vb,
struct v4l2_framebuffer *fbuf)
{
int err, pages;
dma_addr_t bus;
struct videobuf_dma_sg_memory *mem = vb->priv;
BUG_ON(!mem);
MAGIC_CHECK(mem->magic, MAGIC_SG_MEM);
if (!mem->dma.dev)
mem->dma.dev = q->dev;
else
WARN_ON(mem->dma.dev != q->dev);
switch (vb->memory) {
case V4L2_MEMORY_MMAP:
case V4L2_MEMORY_USERPTR:
if (0 == vb->baddr) {
/* no userspace addr -- kernel bounce buffer */
pages = PAGE_ALIGN(vb->size) >> PAGE_SHIFT;
err = videobuf_dma_init_kernel(&mem->dma,
DMA_FROM_DEVICE,
pages);
if (0 != err)
return err;
} else if (vb->memory == V4L2_MEMORY_USERPTR) {
/* dma directly to userspace */
err = videobuf_dma_init_user(&mem->dma,
DMA_FROM_DEVICE,
vb->baddr, vb->bsize);
if (0 != err)
return err;
} else {
/* NOTE: HACK: videobuf_iolock on V4L2_MEMORY_MMAP
buffers can only be called from videobuf_qbuf
we take current->mm->mmap_sem there, to prevent
locking inversion, so don't take it here */
err = videobuf_dma_init_user_locked(&mem->dma,
DMA_FROM_DEVICE,
vb->baddr, vb->bsize);
if (0 != err)
return err;
}
break;
case V4L2_MEMORY_OVERLAY:
if (NULL == fbuf)
return -EINVAL;
/* FIXME: need sanity checks for vb->boff */
/*
* Using a double cast to avoid compiler warnings when
* building for PAE. Compiler doesn't like direct casting
* of a 32 bit ptr to 64 bit integer.
*/
bus = (dma_addr_t)(unsigned long)fbuf->base + vb->boff;
pages = PAGE_ALIGN(vb->size) >> PAGE_SHIFT;
err = videobuf_dma_init_overlay(&mem->dma, DMA_FROM_DEVICE,
bus, pages);
if (0 != err)
return err;
break;
default:
BUG();
}
err = videobuf_dma_map(q->dev, &mem->dma);
if (0 != err)
return err;
return 0;
}
static int __videobuf_sync(struct videobuf_queue *q,
struct videobuf_buffer *buf)
{
struct videobuf_dma_sg_memory *mem = buf->priv;
BUG_ON(!mem || !mem->dma.sglen);
MAGIC_CHECK(mem->magic, MAGIC_SG_MEM);
MAGIC_CHECK(mem->dma.magic, MAGIC_DMABUF);
dma_sync_sg_for_cpu(q->dev, mem->dma.sglist,
mem->dma.sglen, mem->dma.direction);
return 0;
}
static int __videobuf_mmap_mapper(struct videobuf_queue *q,
struct videobuf_buffer *buf,
struct vm_area_struct *vma)
{
struct videobuf_dma_sg_memory *mem = buf->priv;
struct videobuf_mapping *map;
unsigned int first, last, size = 0, i;
int retval;
retval = -EINVAL;
BUG_ON(!mem);
MAGIC_CHECK(mem->magic, MAGIC_SG_MEM);
/* look for first buffer to map */
for (first = 0; first < VIDEO_MAX_FRAME; first++) {
if (buf == q->bufs[first]) {
size = PAGE_ALIGN(q->bufs[first]->bsize);
break;
}
}
/* paranoia, should never happen since buf is always valid. */
if (!size) {
dprintk(1, "mmap app bug: offset invalid [offset=0x%lx]\n",
(vma->vm_pgoff << PAGE_SHIFT));
goto done;
}
last = first;
/* create mapping + update buffer list */
retval = -ENOMEM;
map = kmalloc(sizeof(struct videobuf_mapping), GFP_KERNEL);
if (NULL == map)
goto done;
size = 0;
for (i = first; i <= last; i++) {
if (NULL == q->bufs[i])
continue;
q->bufs[i]->map = map;
q->bufs[i]->baddr = vma->vm_start + size;
size += PAGE_ALIGN(q->bufs[i]->bsize);
}
map->count = 1;
map->q = q;
vma->vm_ops = &videobuf_vm_ops;
vma->vm_flags |= VM_DONTEXPAND | VM_DONTDUMP;
vma->vm_flags &= ~VM_IO; /* using shared anonymous pages */
vma->vm_private_data = map;
dprintk(1, "mmap %p: q=%p %08lx-%08lx pgoff %08lx bufs %d-%d\n",
map, q, vma->vm_start, vma->vm_end, vma->vm_pgoff, first, last);
retval = 0;
done:
return retval;
}
static struct videobuf_qtype_ops sg_ops = {
.magic = MAGIC_QTYPE_OPS,
.alloc_vb = __videobuf_alloc_vb,
.iolock = __videobuf_iolock,
.sync = __videobuf_sync,
.mmap_mapper = __videobuf_mmap_mapper,
.vaddr = __videobuf_to_vaddr,
};
void *videobuf_sg_alloc(size_t size)
{
struct videobuf_queue q;
/* Required to make generic handler to call __videobuf_alloc */
q.int_ops = &sg_ops;
q.msize = size;
return videobuf_alloc_vb(&q);
}
EXPORT_SYMBOL_GPL(videobuf_sg_alloc);
void videobuf_queue_sg_init(struct videobuf_queue *q,
const struct videobuf_queue_ops *ops,
struct device *dev,
spinlock_t *irqlock,
enum v4l2_buf_type type,
enum v4l2_field field,
unsigned int msize,
void *priv,
struct mutex *ext_lock)
{
videobuf_queue_core_init(q, ops, dev, irqlock, type, field, msize,
priv, &sg_ops, ext_lock);
}
EXPORT_SYMBOL_GPL(videobuf_queue_sg_init);
| gpl-2.0 |
RomanHargrave/pf-kernel | drivers/iio/common/hid-sensors/hid-sensor-trigger.c | 682 | 6150 | /*
* HID Sensors Driver
* Copyright (c) 2012, Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/hid-sensor-hub.h>
#include <linux/iio/iio.h>
#include <linux/iio/trigger.h>
#include <linux/iio/sysfs.h>
#include "hid-sensor-trigger.h"
static int _hid_sensor_power_state(struct hid_sensor_common *st, bool state)
{
int state_val;
int report_val;
s32 poll_value = 0;
if (state) {
if (!atomic_read(&st->user_requested_state))
return 0;
if (sensor_hub_device_open(st->hsdev))
return -EIO;
atomic_inc(&st->data_ready);
state_val = hid_sensor_get_usage_index(st->hsdev,
st->power_state.report_id,
st->power_state.index,
HID_USAGE_SENSOR_PROP_POWER_STATE_D0_FULL_POWER_ENUM);
report_val = hid_sensor_get_usage_index(st->hsdev,
st->report_state.report_id,
st->report_state.index,
HID_USAGE_SENSOR_PROP_REPORTING_STATE_ALL_EVENTS_ENUM);
poll_value = hid_sensor_read_poll_value(st);
} else {
int val;
val = atomic_dec_if_positive(&st->data_ready);
if (val < 0)
return 0;
sensor_hub_device_close(st->hsdev);
state_val = hid_sensor_get_usage_index(st->hsdev,
st->power_state.report_id,
st->power_state.index,
HID_USAGE_SENSOR_PROP_POWER_STATE_D4_POWER_OFF_ENUM);
report_val = hid_sensor_get_usage_index(st->hsdev,
st->report_state.report_id,
st->report_state.index,
HID_USAGE_SENSOR_PROP_REPORTING_STATE_NO_EVENTS_ENUM);
}
if (state_val >= 0) {
state_val += st->power_state.logical_minimum;
sensor_hub_set_feature(st->hsdev, st->power_state.report_id,
st->power_state.index, sizeof(state_val),
&state_val);
}
if (report_val >= 0) {
report_val += st->report_state.logical_minimum;
sensor_hub_set_feature(st->hsdev, st->report_state.report_id,
st->report_state.index,
sizeof(report_val),
&report_val);
}
sensor_hub_get_feature(st->hsdev, st->power_state.report_id,
st->power_state.index,
sizeof(state_val), &state_val);
if (state && poll_value)
msleep_interruptible(poll_value * 2);
return 0;
}
EXPORT_SYMBOL(hid_sensor_power_state);
int hid_sensor_power_state(struct hid_sensor_common *st, bool state)
{
#ifdef CONFIG_PM
int ret;
atomic_set(&st->user_requested_state, state);
if (state)
ret = pm_runtime_get_sync(&st->pdev->dev);
else {
pm_runtime_mark_last_busy(&st->pdev->dev);
ret = pm_runtime_put_autosuspend(&st->pdev->dev);
}
if (ret < 0) {
if (state)
pm_runtime_put_noidle(&st->pdev->dev);
return ret;
}
return 0;
#else
atomic_set(&st->user_requested_state, state);
return _hid_sensor_power_state(st, state);
#endif
}
static int hid_sensor_data_rdy_trigger_set_state(struct iio_trigger *trig,
bool state)
{
return hid_sensor_power_state(iio_trigger_get_drvdata(trig), state);
}
void hid_sensor_remove_trigger(struct hid_sensor_common *attrb)
{
iio_trigger_unregister(attrb->trigger);
iio_trigger_free(attrb->trigger);
}
EXPORT_SYMBOL(hid_sensor_remove_trigger);
static const struct iio_trigger_ops hid_sensor_trigger_ops = {
.owner = THIS_MODULE,
.set_trigger_state = &hid_sensor_data_rdy_trigger_set_state,
};
int hid_sensor_setup_trigger(struct iio_dev *indio_dev, const char *name,
struct hid_sensor_common *attrb)
{
int ret;
struct iio_trigger *trig;
trig = iio_trigger_alloc("%s-dev%d", name, indio_dev->id);
if (trig == NULL) {
dev_err(&indio_dev->dev, "Trigger Allocate Failed\n");
ret = -ENOMEM;
goto error_ret;
}
trig->dev.parent = indio_dev->dev.parent;
iio_trigger_set_drvdata(trig, attrb);
trig->ops = &hid_sensor_trigger_ops;
ret = iio_trigger_register(trig);
if (ret) {
dev_err(&indio_dev->dev, "Trigger Register Failed\n");
goto error_free_trig;
}
attrb->trigger = trig;
indio_dev->trig = iio_trigger_get(trig);
ret = pm_runtime_set_active(&indio_dev->dev);
if (ret)
goto error_unreg_trigger;
iio_device_set_drvdata(indio_dev, attrb);
pm_suspend_ignore_children(&attrb->pdev->dev, true);
pm_runtime_enable(&attrb->pdev->dev);
/* Default to 3 seconds, but can be changed from sysfs */
pm_runtime_set_autosuspend_delay(&attrb->pdev->dev,
3000);
pm_runtime_use_autosuspend(&attrb->pdev->dev);
return ret;
error_unreg_trigger:
iio_trigger_unregister(trig);
error_free_trig:
iio_trigger_free(trig);
error_ret:
return ret;
}
EXPORT_SYMBOL(hid_sensor_setup_trigger);
#ifdef CONFIG_PM
static int hid_sensor_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct iio_dev *indio_dev = platform_get_drvdata(pdev);
struct hid_sensor_common *attrb = iio_device_get_drvdata(indio_dev);
return _hid_sensor_power_state(attrb, false);
}
static int hid_sensor_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct iio_dev *indio_dev = platform_get_drvdata(pdev);
struct hid_sensor_common *attrb = iio_device_get_drvdata(indio_dev);
return _hid_sensor_power_state(attrb, true);
}
#endif
const struct dev_pm_ops hid_sensor_pm_ops = {
SET_SYSTEM_SLEEP_PM_OPS(hid_sensor_suspend, hid_sensor_resume)
SET_RUNTIME_PM_OPS(hid_sensor_suspend,
hid_sensor_resume, NULL)
};
EXPORT_SYMBOL(hid_sensor_pm_ops);
MODULE_AUTHOR("Srinivas Pandruvada <srinivas.pandruvada@intel.com>");
MODULE_DESCRIPTION("HID Sensor trigger processing");
MODULE_LICENSE("GPL");
| gpl-2.0 |
clemsyn/TF101-kernelOC | arch/sparc/mm/tsb.c | 1194 | 13612 | /* arch/sparc64/mm/tsb.c
*
* Copyright (C) 2006, 2008 David S. Miller <davem@davemloft.net>
*/
#include <linux/kernel.h>
#include <linux/preempt.h>
#include <linux/slab.h>
#include <asm/system.h>
#include <asm/page.h>
#include <asm/tlbflush.h>
#include <asm/tlb.h>
#include <asm/mmu_context.h>
#include <asm/pgtable.h>
#include <asm/tsb.h>
#include <asm/oplib.h>
extern struct tsb swapper_tsb[KERNEL_TSB_NENTRIES];
static inline unsigned long tsb_hash(unsigned long vaddr, unsigned long hash_shift, unsigned long nentries)
{
vaddr >>= hash_shift;
return vaddr & (nentries - 1);
}
static inline int tag_compare(unsigned long tag, unsigned long vaddr)
{
return (tag == (vaddr >> 22));
}
/* TSB flushes need only occur on the processor initiating the address
* space modification, not on each cpu the address space has run on.
* Only the TLB flush needs that treatment.
*/
void flush_tsb_kernel_range(unsigned long start, unsigned long end)
{
unsigned long v;
for (v = start; v < end; v += PAGE_SIZE) {
unsigned long hash = tsb_hash(v, PAGE_SHIFT,
KERNEL_TSB_NENTRIES);
struct tsb *ent = &swapper_tsb[hash];
if (tag_compare(ent->tag, v))
ent->tag = (1UL << TSB_TAG_INVALID_BIT);
}
}
static void __flush_tsb_one(struct mmu_gather *mp, unsigned long hash_shift, unsigned long tsb, unsigned long nentries)
{
unsigned long i;
for (i = 0; i < mp->tlb_nr; i++) {
unsigned long v = mp->vaddrs[i];
unsigned long tag, ent, hash;
v &= ~0x1UL;
hash = tsb_hash(v, hash_shift, nentries);
ent = tsb + (hash * sizeof(struct tsb));
tag = (v >> 22UL);
tsb_flush(ent, tag);
}
}
void flush_tsb_user(struct mmu_gather *mp)
{
struct mm_struct *mm = mp->mm;
unsigned long nentries, base, flags;
spin_lock_irqsave(&mm->context.lock, flags);
base = (unsigned long) mm->context.tsb_block[MM_TSB_BASE].tsb;
nentries = mm->context.tsb_block[MM_TSB_BASE].tsb_nentries;
if (tlb_type == cheetah_plus || tlb_type == hypervisor)
base = __pa(base);
__flush_tsb_one(mp, PAGE_SHIFT, base, nentries);
#ifdef CONFIG_HUGETLB_PAGE
if (mm->context.tsb_block[MM_TSB_HUGE].tsb) {
base = (unsigned long) mm->context.tsb_block[MM_TSB_HUGE].tsb;
nentries = mm->context.tsb_block[MM_TSB_HUGE].tsb_nentries;
if (tlb_type == cheetah_plus || tlb_type == hypervisor)
base = __pa(base);
__flush_tsb_one(mp, HPAGE_SHIFT, base, nentries);
}
#endif
spin_unlock_irqrestore(&mm->context.lock, flags);
}
#if defined(CONFIG_SPARC64_PAGE_SIZE_8KB)
#define HV_PGSZ_IDX_BASE HV_PGSZ_IDX_8K
#define HV_PGSZ_MASK_BASE HV_PGSZ_MASK_8K
#elif defined(CONFIG_SPARC64_PAGE_SIZE_64KB)
#define HV_PGSZ_IDX_BASE HV_PGSZ_IDX_64K
#define HV_PGSZ_MASK_BASE HV_PGSZ_MASK_64K
#else
#error Broken base page size setting...
#endif
#ifdef CONFIG_HUGETLB_PAGE
#if defined(CONFIG_HUGETLB_PAGE_SIZE_64K)
#define HV_PGSZ_IDX_HUGE HV_PGSZ_IDX_64K
#define HV_PGSZ_MASK_HUGE HV_PGSZ_MASK_64K
#elif defined(CONFIG_HUGETLB_PAGE_SIZE_512K)
#define HV_PGSZ_IDX_HUGE HV_PGSZ_IDX_512K
#define HV_PGSZ_MASK_HUGE HV_PGSZ_MASK_512K
#elif defined(CONFIG_HUGETLB_PAGE_SIZE_4MB)
#define HV_PGSZ_IDX_HUGE HV_PGSZ_IDX_4MB
#define HV_PGSZ_MASK_HUGE HV_PGSZ_MASK_4MB
#else
#error Broken huge page size setting...
#endif
#endif
static void setup_tsb_params(struct mm_struct *mm, unsigned long tsb_idx, unsigned long tsb_bytes)
{
unsigned long tsb_reg, base, tsb_paddr;
unsigned long page_sz, tte;
mm->context.tsb_block[tsb_idx].tsb_nentries =
tsb_bytes / sizeof(struct tsb);
base = TSBMAP_BASE;
tte = pgprot_val(PAGE_KERNEL_LOCKED);
tsb_paddr = __pa(mm->context.tsb_block[tsb_idx].tsb);
BUG_ON(tsb_paddr & (tsb_bytes - 1UL));
/* Use the smallest page size that can map the whole TSB
* in one TLB entry.
*/
switch (tsb_bytes) {
case 8192 << 0:
tsb_reg = 0x0UL;
#ifdef DCACHE_ALIASING_POSSIBLE
base += (tsb_paddr & 8192);
#endif
page_sz = 8192;
break;
case 8192 << 1:
tsb_reg = 0x1UL;
page_sz = 64 * 1024;
break;
case 8192 << 2:
tsb_reg = 0x2UL;
page_sz = 64 * 1024;
break;
case 8192 << 3:
tsb_reg = 0x3UL;
page_sz = 64 * 1024;
break;
case 8192 << 4:
tsb_reg = 0x4UL;
page_sz = 512 * 1024;
break;
case 8192 << 5:
tsb_reg = 0x5UL;
page_sz = 512 * 1024;
break;
case 8192 << 6:
tsb_reg = 0x6UL;
page_sz = 512 * 1024;
break;
case 8192 << 7:
tsb_reg = 0x7UL;
page_sz = 4 * 1024 * 1024;
break;
default:
printk(KERN_ERR "TSB[%s:%d]: Impossible TSB size %lu, killing process.\n",
current->comm, current->pid, tsb_bytes);
do_exit(SIGSEGV);
};
tte |= pte_sz_bits(page_sz);
if (tlb_type == cheetah_plus || tlb_type == hypervisor) {
/* Physical mapping, no locked TLB entry for TSB. */
tsb_reg |= tsb_paddr;
mm->context.tsb_block[tsb_idx].tsb_reg_val = tsb_reg;
mm->context.tsb_block[tsb_idx].tsb_map_vaddr = 0;
mm->context.tsb_block[tsb_idx].tsb_map_pte = 0;
} else {
tsb_reg |= base;
tsb_reg |= (tsb_paddr & (page_sz - 1UL));
tte |= (tsb_paddr & ~(page_sz - 1UL));
mm->context.tsb_block[tsb_idx].tsb_reg_val = tsb_reg;
mm->context.tsb_block[tsb_idx].tsb_map_vaddr = base;
mm->context.tsb_block[tsb_idx].tsb_map_pte = tte;
}
/* Setup the Hypervisor TSB descriptor. */
if (tlb_type == hypervisor) {
struct hv_tsb_descr *hp = &mm->context.tsb_descr[tsb_idx];
switch (tsb_idx) {
case MM_TSB_BASE:
hp->pgsz_idx = HV_PGSZ_IDX_BASE;
break;
#ifdef CONFIG_HUGETLB_PAGE
case MM_TSB_HUGE:
hp->pgsz_idx = HV_PGSZ_IDX_HUGE;
break;
#endif
default:
BUG();
};
hp->assoc = 1;
hp->num_ttes = tsb_bytes / 16;
hp->ctx_idx = 0;
switch (tsb_idx) {
case MM_TSB_BASE:
hp->pgsz_mask = HV_PGSZ_MASK_BASE;
break;
#ifdef CONFIG_HUGETLB_PAGE
case MM_TSB_HUGE:
hp->pgsz_mask = HV_PGSZ_MASK_HUGE;
break;
#endif
default:
BUG();
};
hp->tsb_base = tsb_paddr;
hp->resv = 0;
}
}
static struct kmem_cache *tsb_caches[8] __read_mostly;
static const char *tsb_cache_names[8] = {
"tsb_8KB",
"tsb_16KB",
"tsb_32KB",
"tsb_64KB",
"tsb_128KB",
"tsb_256KB",
"tsb_512KB",
"tsb_1MB",
};
void __init pgtable_cache_init(void)
{
unsigned long i;
for (i = 0; i < 8; i++) {
unsigned long size = 8192 << i;
const char *name = tsb_cache_names[i];
tsb_caches[i] = kmem_cache_create(name,
size, size,
0, NULL);
if (!tsb_caches[i]) {
prom_printf("Could not create %s cache\n", name);
prom_halt();
}
}
}
int sysctl_tsb_ratio = -2;
static unsigned long tsb_size_to_rss_limit(unsigned long new_size)
{
unsigned long num_ents = (new_size / sizeof(struct tsb));
if (sysctl_tsb_ratio < 0)
return num_ents - (num_ents >> -sysctl_tsb_ratio);
else
return num_ents + (num_ents >> sysctl_tsb_ratio);
}
/* When the RSS of an address space exceeds tsb_rss_limit for a TSB,
* do_sparc64_fault() invokes this routine to try and grow it.
*
* When we reach the maximum TSB size supported, we stick ~0UL into
* tsb_rss_limit for that TSB so the grow checks in do_sparc64_fault()
* will not trigger any longer.
*
* The TSB can be anywhere from 8K to 1MB in size, in increasing powers
* of two. The TSB must be aligned to it's size, so f.e. a 512K TSB
* must be 512K aligned. It also must be physically contiguous, so we
* cannot use vmalloc().
*
* The idea here is to grow the TSB when the RSS of the process approaches
* the number of entries that the current TSB can hold at once. Currently,
* we trigger when the RSS hits 3/4 of the TSB capacity.
*/
void tsb_grow(struct mm_struct *mm, unsigned long tsb_index, unsigned long rss)
{
unsigned long max_tsb_size = 1 * 1024 * 1024;
unsigned long new_size, old_size, flags;
struct tsb *old_tsb, *new_tsb;
unsigned long new_cache_index, old_cache_index;
unsigned long new_rss_limit;
gfp_t gfp_flags;
if (max_tsb_size > (PAGE_SIZE << MAX_ORDER))
max_tsb_size = (PAGE_SIZE << MAX_ORDER);
new_cache_index = 0;
for (new_size = 8192; new_size < max_tsb_size; new_size <<= 1UL) {
new_rss_limit = tsb_size_to_rss_limit(new_size);
if (new_rss_limit > rss)
break;
new_cache_index++;
}
if (new_size == max_tsb_size)
new_rss_limit = ~0UL;
retry_tsb_alloc:
gfp_flags = GFP_KERNEL;
if (new_size > (PAGE_SIZE * 2))
gfp_flags = __GFP_NOWARN | __GFP_NORETRY;
new_tsb = kmem_cache_alloc_node(tsb_caches[new_cache_index],
gfp_flags, numa_node_id());
if (unlikely(!new_tsb)) {
/* Not being able to fork due to a high-order TSB
* allocation failure is very bad behavior. Just back
* down to a 0-order allocation and force no TSB
* growing for this address space.
*/
if (mm->context.tsb_block[tsb_index].tsb == NULL &&
new_cache_index > 0) {
new_cache_index = 0;
new_size = 8192;
new_rss_limit = ~0UL;
goto retry_tsb_alloc;
}
/* If we failed on a TSB grow, we are under serious
* memory pressure so don't try to grow any more.
*/
if (mm->context.tsb_block[tsb_index].tsb != NULL)
mm->context.tsb_block[tsb_index].tsb_rss_limit = ~0UL;
return;
}
/* Mark all tags as invalid. */
tsb_init(new_tsb, new_size);
/* Ok, we are about to commit the changes. If we are
* growing an existing TSB the locking is very tricky,
* so WATCH OUT!
*
* We have to hold mm->context.lock while committing to the
* new TSB, this synchronizes us with processors in
* flush_tsb_user() and switch_mm() for this address space.
*
* But even with that lock held, processors run asynchronously
* accessing the old TSB via TLB miss handling. This is OK
* because those actions are just propagating state from the
* Linux page tables into the TSB, page table mappings are not
* being changed. If a real fault occurs, the processor will
* synchronize with us when it hits flush_tsb_user(), this is
* also true for the case where vmscan is modifying the page
* tables. The only thing we need to be careful with is to
* skip any locked TSB entries during copy_tsb().
*
* When we finish committing to the new TSB, we have to drop
* the lock and ask all other cpus running this address space
* to run tsb_context_switch() to see the new TSB table.
*/
spin_lock_irqsave(&mm->context.lock, flags);
old_tsb = mm->context.tsb_block[tsb_index].tsb;
old_cache_index =
(mm->context.tsb_block[tsb_index].tsb_reg_val & 0x7UL);
old_size = (mm->context.tsb_block[tsb_index].tsb_nentries *
sizeof(struct tsb));
/* Handle multiple threads trying to grow the TSB at the same time.
* One will get in here first, and bump the size and the RSS limit.
* The others will get in here next and hit this check.
*/
if (unlikely(old_tsb &&
(rss < mm->context.tsb_block[tsb_index].tsb_rss_limit))) {
spin_unlock_irqrestore(&mm->context.lock, flags);
kmem_cache_free(tsb_caches[new_cache_index], new_tsb);
return;
}
mm->context.tsb_block[tsb_index].tsb_rss_limit = new_rss_limit;
if (old_tsb) {
extern void copy_tsb(unsigned long old_tsb_base,
unsigned long old_tsb_size,
unsigned long new_tsb_base,
unsigned long new_tsb_size);
unsigned long old_tsb_base = (unsigned long) old_tsb;
unsigned long new_tsb_base = (unsigned long) new_tsb;
if (tlb_type == cheetah_plus || tlb_type == hypervisor) {
old_tsb_base = __pa(old_tsb_base);
new_tsb_base = __pa(new_tsb_base);
}
copy_tsb(old_tsb_base, old_size, new_tsb_base, new_size);
}
mm->context.tsb_block[tsb_index].tsb = new_tsb;
setup_tsb_params(mm, tsb_index, new_size);
spin_unlock_irqrestore(&mm->context.lock, flags);
/* If old_tsb is NULL, we're being invoked for the first time
* from init_new_context().
*/
if (old_tsb) {
/* Reload it on the local cpu. */
tsb_context_switch(mm);
/* Now force other processors to do the same. */
preempt_disable();
smp_tsb_sync(mm);
preempt_enable();
/* Now it is safe to free the old tsb. */
kmem_cache_free(tsb_caches[old_cache_index], old_tsb);
}
}
int init_new_context(struct task_struct *tsk, struct mm_struct *mm)
{
#ifdef CONFIG_HUGETLB_PAGE
unsigned long huge_pte_count;
#endif
unsigned int i;
spin_lock_init(&mm->context.lock);
mm->context.sparc64_ctx_val = 0UL;
#ifdef CONFIG_HUGETLB_PAGE
/* We reset it to zero because the fork() page copying
* will re-increment the counters as the parent PTEs are
* copied into the child address space.
*/
huge_pte_count = mm->context.huge_pte_count;
mm->context.huge_pte_count = 0;
#endif
/* copy_mm() copies over the parent's mm_struct before calling
* us, so we need to zero out the TSB pointer or else tsb_grow()
* will be confused and think there is an older TSB to free up.
*/
for (i = 0; i < MM_NUM_TSBS; i++)
mm->context.tsb_block[i].tsb = NULL;
/* If this is fork, inherit the parent's TSB size. We would
* grow it to that size on the first page fault anyways.
*/
tsb_grow(mm, MM_TSB_BASE, get_mm_rss(mm));
#ifdef CONFIG_HUGETLB_PAGE
if (unlikely(huge_pte_count))
tsb_grow(mm, MM_TSB_HUGE, huge_pte_count);
#endif
if (unlikely(!mm->context.tsb_block[MM_TSB_BASE].tsb))
return -ENOMEM;
return 0;
}
static void tsb_destroy_one(struct tsb_config *tp)
{
unsigned long cache_index;
if (!tp->tsb)
return;
cache_index = tp->tsb_reg_val & 0x7UL;
kmem_cache_free(tsb_caches[cache_index], tp->tsb);
tp->tsb = NULL;
tp->tsb_reg_val = 0UL;
}
void destroy_context(struct mm_struct *mm)
{
unsigned long flags, i;
for (i = 0; i < MM_NUM_TSBS; i++)
tsb_destroy_one(&mm->context.tsb_block[i]);
spin_lock_irqsave(&ctx_alloc_lock, flags);
if (CTX_VALID(mm->context)) {
unsigned long nr = CTX_NRBITS(mm->context);
mmu_context_bmap[nr>>6] &= ~(1UL << (nr & 63));
}
spin_unlock_irqrestore(&ctx_alloc_lock, flags);
}
| gpl-2.0 |
I8552-CM/android_kernel_arubaslim | drivers/mtd/nand/nandsim.c | 1450 | 69290 | /*
* NAND flash simulator.
*
* Author: Artem B. Bityuckiy <dedekind@oktetlabs.ru>, <dedekind@infradead.org>
*
* Copyright (C) 2004 Nokia Corporation
*
* Note: NS means "NAND Simulator".
* Note: Input means input TO flash chip, output means output FROM chip.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
*/
#include <linux/init.h>
#include <linux/types.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/vmalloc.h>
#include <linux/math64.h>
#include <linux/slab.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/nand.h>
#include <linux/mtd/nand_bch.h>
#include <linux/mtd/partitions.h>
#include <linux/delay.h>
#include <linux/list.h>
#include <linux/random.h>
#include <linux/sched.h>
#include <linux/fs.h>
#include <linux/pagemap.h>
/* Default simulator parameters values */
#if !defined(CONFIG_NANDSIM_FIRST_ID_BYTE) || \
!defined(CONFIG_NANDSIM_SECOND_ID_BYTE) || \
!defined(CONFIG_NANDSIM_THIRD_ID_BYTE) || \
!defined(CONFIG_NANDSIM_FOURTH_ID_BYTE)
#define CONFIG_NANDSIM_FIRST_ID_BYTE 0x98
#define CONFIG_NANDSIM_SECOND_ID_BYTE 0x39
#define CONFIG_NANDSIM_THIRD_ID_BYTE 0xFF /* No byte */
#define CONFIG_NANDSIM_FOURTH_ID_BYTE 0xFF /* No byte */
#endif
#ifndef CONFIG_NANDSIM_ACCESS_DELAY
#define CONFIG_NANDSIM_ACCESS_DELAY 25
#endif
#ifndef CONFIG_NANDSIM_PROGRAMM_DELAY
#define CONFIG_NANDSIM_PROGRAMM_DELAY 200
#endif
#ifndef CONFIG_NANDSIM_ERASE_DELAY
#define CONFIG_NANDSIM_ERASE_DELAY 2
#endif
#ifndef CONFIG_NANDSIM_OUTPUT_CYCLE
#define CONFIG_NANDSIM_OUTPUT_CYCLE 40
#endif
#ifndef CONFIG_NANDSIM_INPUT_CYCLE
#define CONFIG_NANDSIM_INPUT_CYCLE 50
#endif
#ifndef CONFIG_NANDSIM_BUS_WIDTH
#define CONFIG_NANDSIM_BUS_WIDTH 8
#endif
#ifndef CONFIG_NANDSIM_DO_DELAYS
#define CONFIG_NANDSIM_DO_DELAYS 0
#endif
#ifndef CONFIG_NANDSIM_LOG
#define CONFIG_NANDSIM_LOG 0
#endif
#ifndef CONFIG_NANDSIM_DBG
#define CONFIG_NANDSIM_DBG 0
#endif
#ifndef CONFIG_NANDSIM_MAX_PARTS
#define CONFIG_NANDSIM_MAX_PARTS 32
#endif
static uint first_id_byte = CONFIG_NANDSIM_FIRST_ID_BYTE;
static uint second_id_byte = CONFIG_NANDSIM_SECOND_ID_BYTE;
static uint third_id_byte = CONFIG_NANDSIM_THIRD_ID_BYTE;
static uint fourth_id_byte = CONFIG_NANDSIM_FOURTH_ID_BYTE;
static uint access_delay = CONFIG_NANDSIM_ACCESS_DELAY;
static uint programm_delay = CONFIG_NANDSIM_PROGRAMM_DELAY;
static uint erase_delay = CONFIG_NANDSIM_ERASE_DELAY;
static uint output_cycle = CONFIG_NANDSIM_OUTPUT_CYCLE;
static uint input_cycle = CONFIG_NANDSIM_INPUT_CYCLE;
static uint bus_width = CONFIG_NANDSIM_BUS_WIDTH;
static uint do_delays = CONFIG_NANDSIM_DO_DELAYS;
static uint log = CONFIG_NANDSIM_LOG;
static uint dbg = CONFIG_NANDSIM_DBG;
static unsigned long parts[CONFIG_NANDSIM_MAX_PARTS];
static unsigned int parts_num;
static char *badblocks = NULL;
static char *weakblocks = NULL;
static char *weakpages = NULL;
static unsigned int bitflips = 0;
static char *gravepages = NULL;
static unsigned int rptwear = 0;
static unsigned int overridesize = 0;
static char *cache_file = NULL;
static unsigned int bbt;
static unsigned int bch;
module_param(first_id_byte, uint, 0400);
module_param(second_id_byte, uint, 0400);
module_param(third_id_byte, uint, 0400);
module_param(fourth_id_byte, uint, 0400);
module_param(access_delay, uint, 0400);
module_param(programm_delay, uint, 0400);
module_param(erase_delay, uint, 0400);
module_param(output_cycle, uint, 0400);
module_param(input_cycle, uint, 0400);
module_param(bus_width, uint, 0400);
module_param(do_delays, uint, 0400);
module_param(log, uint, 0400);
module_param(dbg, uint, 0400);
module_param_array(parts, ulong, &parts_num, 0400);
module_param(badblocks, charp, 0400);
module_param(weakblocks, charp, 0400);
module_param(weakpages, charp, 0400);
module_param(bitflips, uint, 0400);
module_param(gravepages, charp, 0400);
module_param(rptwear, uint, 0400);
module_param(overridesize, uint, 0400);
module_param(cache_file, charp, 0400);
module_param(bbt, uint, 0400);
module_param(bch, uint, 0400);
MODULE_PARM_DESC(first_id_byte, "The first byte returned by NAND Flash 'read ID' command (manufacturer ID)");
MODULE_PARM_DESC(second_id_byte, "The second byte returned by NAND Flash 'read ID' command (chip ID)");
MODULE_PARM_DESC(third_id_byte, "The third byte returned by NAND Flash 'read ID' command");
MODULE_PARM_DESC(fourth_id_byte, "The fourth byte returned by NAND Flash 'read ID' command");
MODULE_PARM_DESC(access_delay, "Initial page access delay (microseconds)");
MODULE_PARM_DESC(programm_delay, "Page programm delay (microseconds");
MODULE_PARM_DESC(erase_delay, "Sector erase delay (milliseconds)");
MODULE_PARM_DESC(output_cycle, "Word output (from flash) time (nanoseconds)");
MODULE_PARM_DESC(input_cycle, "Word input (to flash) time (nanoseconds)");
MODULE_PARM_DESC(bus_width, "Chip's bus width (8- or 16-bit)");
MODULE_PARM_DESC(do_delays, "Simulate NAND delays using busy-waits if not zero");
MODULE_PARM_DESC(log, "Perform logging if not zero");
MODULE_PARM_DESC(dbg, "Output debug information if not zero");
MODULE_PARM_DESC(parts, "Partition sizes (in erase blocks) separated by commas");
/* Page and erase block positions for the following parameters are independent of any partitions */
MODULE_PARM_DESC(badblocks, "Erase blocks that are initially marked bad, separated by commas");
MODULE_PARM_DESC(weakblocks, "Weak erase blocks [: remaining erase cycles (defaults to 3)]"
" separated by commas e.g. 113:2 means eb 113"
" can be erased only twice before failing");
MODULE_PARM_DESC(weakpages, "Weak pages [: maximum writes (defaults to 3)]"
" separated by commas e.g. 1401:2 means page 1401"
" can be written only twice before failing");
MODULE_PARM_DESC(bitflips, "Maximum number of random bit flips per page (zero by default)");
MODULE_PARM_DESC(gravepages, "Pages that lose data [: maximum reads (defaults to 3)]"
" separated by commas e.g. 1401:2 means page 1401"
" can be read only twice before failing");
MODULE_PARM_DESC(rptwear, "Number of erases between reporting wear, if not zero");
MODULE_PARM_DESC(overridesize, "Specifies the NAND Flash size overriding the ID bytes. "
"The size is specified in erase blocks and as the exponent of a power of two"
" e.g. 5 means a size of 32 erase blocks");
MODULE_PARM_DESC(cache_file, "File to use to cache nand pages instead of memory");
MODULE_PARM_DESC(bbt, "0 OOB, 1 BBT with marker in OOB, 2 BBT with marker in data area");
MODULE_PARM_DESC(bch, "Enable BCH ecc and set how many bits should "
"be correctable in 512-byte blocks");
/* The largest possible page size */
#define NS_LARGEST_PAGE_SIZE 4096
/* The prefix for simulator output */
#define NS_OUTPUT_PREFIX "[nandsim]"
/* Simulator's output macros (logging, debugging, warning, error) */
#define NS_LOG(args...) \
do { if (log) printk(KERN_DEBUG NS_OUTPUT_PREFIX " log: " args); } while(0)
#define NS_DBG(args...) \
do { if (dbg) printk(KERN_DEBUG NS_OUTPUT_PREFIX " debug: " args); } while(0)
#define NS_WARN(args...) \
do { printk(KERN_WARNING NS_OUTPUT_PREFIX " warning: " args); } while(0)
#define NS_ERR(args...) \
do { printk(KERN_ERR NS_OUTPUT_PREFIX " error: " args); } while(0)
#define NS_INFO(args...) \
do { printk(KERN_INFO NS_OUTPUT_PREFIX " " args); } while(0)
/* Busy-wait delay macros (microseconds, milliseconds) */
#define NS_UDELAY(us) \
do { if (do_delays) udelay(us); } while(0)
#define NS_MDELAY(us) \
do { if (do_delays) mdelay(us); } while(0)
/* Is the nandsim structure initialized ? */
#define NS_IS_INITIALIZED(ns) ((ns)->geom.totsz != 0)
/* Good operation completion status */
#define NS_STATUS_OK(ns) (NAND_STATUS_READY | (NAND_STATUS_WP * ((ns)->lines.wp == 0)))
/* Operation failed completion status */
#define NS_STATUS_FAILED(ns) (NAND_STATUS_FAIL | NS_STATUS_OK(ns))
/* Calculate the page offset in flash RAM image by (row, column) address */
#define NS_RAW_OFFSET(ns) \
(((ns)->regs.row << (ns)->geom.pgshift) + ((ns)->regs.row * (ns)->geom.oobsz) + (ns)->regs.column)
/* Calculate the OOB offset in flash RAM image by (row, column) address */
#define NS_RAW_OFFSET_OOB(ns) (NS_RAW_OFFSET(ns) + ns->geom.pgsz)
/* After a command is input, the simulator goes to one of the following states */
#define STATE_CMD_READ0 0x00000001 /* read data from the beginning of page */
#define STATE_CMD_READ1 0x00000002 /* read data from the second half of page */
#define STATE_CMD_READSTART 0x00000003 /* read data second command (large page devices) */
#define STATE_CMD_PAGEPROG 0x00000004 /* start page program */
#define STATE_CMD_READOOB 0x00000005 /* read OOB area */
#define STATE_CMD_ERASE1 0x00000006 /* sector erase first command */
#define STATE_CMD_STATUS 0x00000007 /* read status */
#define STATE_CMD_STATUS_M 0x00000008 /* read multi-plane status (isn't implemented) */
#define STATE_CMD_SEQIN 0x00000009 /* sequential data input */
#define STATE_CMD_READID 0x0000000A /* read ID */
#define STATE_CMD_ERASE2 0x0000000B /* sector erase second command */
#define STATE_CMD_RESET 0x0000000C /* reset */
#define STATE_CMD_RNDOUT 0x0000000D /* random output command */
#define STATE_CMD_RNDOUTSTART 0x0000000E /* random output start command */
#define STATE_CMD_MASK 0x0000000F /* command states mask */
/* After an address is input, the simulator goes to one of these states */
#define STATE_ADDR_PAGE 0x00000010 /* full (row, column) address is accepted */
#define STATE_ADDR_SEC 0x00000020 /* sector address was accepted */
#define STATE_ADDR_COLUMN 0x00000030 /* column address was accepted */
#define STATE_ADDR_ZERO 0x00000040 /* one byte zero address was accepted */
#define STATE_ADDR_MASK 0x00000070 /* address states mask */
/* During data input/output the simulator is in these states */
#define STATE_DATAIN 0x00000100 /* waiting for data input */
#define STATE_DATAIN_MASK 0x00000100 /* data input states mask */
#define STATE_DATAOUT 0x00001000 /* waiting for page data output */
#define STATE_DATAOUT_ID 0x00002000 /* waiting for ID bytes output */
#define STATE_DATAOUT_STATUS 0x00003000 /* waiting for status output */
#define STATE_DATAOUT_STATUS_M 0x00004000 /* waiting for multi-plane status output */
#define STATE_DATAOUT_MASK 0x00007000 /* data output states mask */
/* Previous operation is done, ready to accept new requests */
#define STATE_READY 0x00000000
/* This state is used to mark that the next state isn't known yet */
#define STATE_UNKNOWN 0x10000000
/* Simulator's actions bit masks */
#define ACTION_CPY 0x00100000 /* copy page/OOB to the internal buffer */
#define ACTION_PRGPAGE 0x00200000 /* program the internal buffer to flash */
#define ACTION_SECERASE 0x00300000 /* erase sector */
#define ACTION_ZEROOFF 0x00400000 /* don't add any offset to address */
#define ACTION_HALFOFF 0x00500000 /* add to address half of page */
#define ACTION_OOBOFF 0x00600000 /* add to address OOB offset */
#define ACTION_MASK 0x00700000 /* action mask */
#define NS_OPER_NUM 13 /* Number of operations supported by the simulator */
#define NS_OPER_STATES 6 /* Maximum number of states in operation */
#define OPT_ANY 0xFFFFFFFF /* any chip supports this operation */
#define OPT_PAGE256 0x00000001 /* 256-byte page chips */
#define OPT_PAGE512 0x00000002 /* 512-byte page chips */
#define OPT_PAGE2048 0x00000008 /* 2048-byte page chips */
#define OPT_SMARTMEDIA 0x00000010 /* SmartMedia technology chips */
#define OPT_AUTOINCR 0x00000020 /* page number auto incrementation is possible */
#define OPT_PAGE512_8BIT 0x00000040 /* 512-byte page chips with 8-bit bus width */
#define OPT_PAGE4096 0x00000080 /* 4096-byte page chips */
#define OPT_LARGEPAGE (OPT_PAGE2048 | OPT_PAGE4096) /* 2048 & 4096-byte page chips */
#define OPT_SMALLPAGE (OPT_PAGE256 | OPT_PAGE512) /* 256 and 512-byte page chips */
/* Remove action bits from state */
#define NS_STATE(x) ((x) & ~ACTION_MASK)
/*
* Maximum previous states which need to be saved. Currently saving is
* only needed for page program operation with preceded read command
* (which is only valid for 512-byte pages).
*/
#define NS_MAX_PREVSTATES 1
/* Maximum page cache pages needed to read or write a NAND page to the cache_file */
#define NS_MAX_HELD_PAGES 16
/*
* A union to represent flash memory contents and flash buffer.
*/
union ns_mem {
u_char *byte; /* for byte access */
uint16_t *word; /* for 16-bit word access */
};
/*
* The structure which describes all the internal simulator data.
*/
struct nandsim {
struct mtd_partition partitions[CONFIG_NANDSIM_MAX_PARTS];
unsigned int nbparts;
uint busw; /* flash chip bus width (8 or 16) */
u_char ids[4]; /* chip's ID bytes */
uint32_t options; /* chip's characteristic bits */
uint32_t state; /* current chip state */
uint32_t nxstate; /* next expected state */
uint32_t *op; /* current operation, NULL operations isn't known yet */
uint32_t pstates[NS_MAX_PREVSTATES]; /* previous states */
uint16_t npstates; /* number of previous states saved */
uint16_t stateidx; /* current state index */
/* The simulated NAND flash pages array */
union ns_mem *pages;
/* Slab allocator for nand pages */
struct kmem_cache *nand_pages_slab;
/* Internal buffer of page + OOB size bytes */
union ns_mem buf;
/* NAND flash "geometry" */
struct {
uint64_t totsz; /* total flash size, bytes */
uint32_t secsz; /* flash sector (erase block) size, bytes */
uint pgsz; /* NAND flash page size, bytes */
uint oobsz; /* page OOB area size, bytes */
uint64_t totszoob; /* total flash size including OOB, bytes */
uint pgszoob; /* page size including OOB , bytes*/
uint secszoob; /* sector size including OOB, bytes */
uint pgnum; /* total number of pages */
uint pgsec; /* number of pages per sector */
uint secshift; /* bits number in sector size */
uint pgshift; /* bits number in page size */
uint oobshift; /* bits number in OOB size */
uint pgaddrbytes; /* bytes per page address */
uint secaddrbytes; /* bytes per sector address */
uint idbytes; /* the number ID bytes that this chip outputs */
} geom;
/* NAND flash internal registers */
struct {
unsigned command; /* the command register */
u_char status; /* the status register */
uint row; /* the page number */
uint column; /* the offset within page */
uint count; /* internal counter */
uint num; /* number of bytes which must be processed */
uint off; /* fixed page offset */
} regs;
/* NAND flash lines state */
struct {
int ce; /* chip Enable */
int cle; /* command Latch Enable */
int ale; /* address Latch Enable */
int wp; /* write Protect */
} lines;
/* Fields needed when using a cache file */
struct file *cfile; /* Open file */
unsigned char *pages_written; /* Which pages have been written */
void *file_buf;
struct page *held_pages[NS_MAX_HELD_PAGES];
int held_cnt;
};
/*
* Operations array. To perform any operation the simulator must pass
* through the correspondent states chain.
*/
static struct nandsim_operations {
uint32_t reqopts; /* options which are required to perform the operation */
uint32_t states[NS_OPER_STATES]; /* operation's states */
} ops[NS_OPER_NUM] = {
/* Read page + OOB from the beginning */
{OPT_SMALLPAGE, {STATE_CMD_READ0 | ACTION_ZEROOFF, STATE_ADDR_PAGE | ACTION_CPY,
STATE_DATAOUT, STATE_READY}},
/* Read page + OOB from the second half */
{OPT_PAGE512_8BIT, {STATE_CMD_READ1 | ACTION_HALFOFF, STATE_ADDR_PAGE | ACTION_CPY,
STATE_DATAOUT, STATE_READY}},
/* Read OOB */
{OPT_SMALLPAGE, {STATE_CMD_READOOB | ACTION_OOBOFF, STATE_ADDR_PAGE | ACTION_CPY,
STATE_DATAOUT, STATE_READY}},
/* Program page starting from the beginning */
{OPT_ANY, {STATE_CMD_SEQIN, STATE_ADDR_PAGE, STATE_DATAIN,
STATE_CMD_PAGEPROG | ACTION_PRGPAGE, STATE_READY}},
/* Program page starting from the beginning */
{OPT_SMALLPAGE, {STATE_CMD_READ0, STATE_CMD_SEQIN | ACTION_ZEROOFF, STATE_ADDR_PAGE,
STATE_DATAIN, STATE_CMD_PAGEPROG | ACTION_PRGPAGE, STATE_READY}},
/* Program page starting from the second half */
{OPT_PAGE512, {STATE_CMD_READ1, STATE_CMD_SEQIN | ACTION_HALFOFF, STATE_ADDR_PAGE,
STATE_DATAIN, STATE_CMD_PAGEPROG | ACTION_PRGPAGE, STATE_READY}},
/* Program OOB */
{OPT_SMALLPAGE, {STATE_CMD_READOOB, STATE_CMD_SEQIN | ACTION_OOBOFF, STATE_ADDR_PAGE,
STATE_DATAIN, STATE_CMD_PAGEPROG | ACTION_PRGPAGE, STATE_READY}},
/* Erase sector */
{OPT_ANY, {STATE_CMD_ERASE1, STATE_ADDR_SEC, STATE_CMD_ERASE2 | ACTION_SECERASE, STATE_READY}},
/* Read status */
{OPT_ANY, {STATE_CMD_STATUS, STATE_DATAOUT_STATUS, STATE_READY}},
/* Read multi-plane status */
{OPT_SMARTMEDIA, {STATE_CMD_STATUS_M, STATE_DATAOUT_STATUS_M, STATE_READY}},
/* Read ID */
{OPT_ANY, {STATE_CMD_READID, STATE_ADDR_ZERO, STATE_DATAOUT_ID, STATE_READY}},
/* Large page devices read page */
{OPT_LARGEPAGE, {STATE_CMD_READ0, STATE_ADDR_PAGE, STATE_CMD_READSTART | ACTION_CPY,
STATE_DATAOUT, STATE_READY}},
/* Large page devices random page read */
{OPT_LARGEPAGE, {STATE_CMD_RNDOUT, STATE_ADDR_COLUMN, STATE_CMD_RNDOUTSTART | ACTION_CPY,
STATE_DATAOUT, STATE_READY}},
};
struct weak_block {
struct list_head list;
unsigned int erase_block_no;
unsigned int max_erases;
unsigned int erases_done;
};
static LIST_HEAD(weak_blocks);
struct weak_page {
struct list_head list;
unsigned int page_no;
unsigned int max_writes;
unsigned int writes_done;
};
static LIST_HEAD(weak_pages);
struct grave_page {
struct list_head list;
unsigned int page_no;
unsigned int max_reads;
unsigned int reads_done;
};
static LIST_HEAD(grave_pages);
static unsigned long *erase_block_wear = NULL;
static unsigned int wear_eb_count = 0;
static unsigned long total_wear = 0;
static unsigned int rptwear_cnt = 0;
/* MTD structure for NAND controller */
static struct mtd_info *nsmtd;
static u_char ns_verify_buf[NS_LARGEST_PAGE_SIZE];
/*
* Allocate array of page pointers, create slab allocation for an array
* and initialize the array by NULL pointers.
*
* RETURNS: 0 if success, -ENOMEM if memory alloc fails.
*/
static int alloc_device(struct nandsim *ns)
{
struct file *cfile;
int i, err;
if (cache_file) {
cfile = filp_open(cache_file, O_CREAT | O_RDWR | O_LARGEFILE, 0600);
if (IS_ERR(cfile))
return PTR_ERR(cfile);
if (!cfile->f_op || (!cfile->f_op->read && !cfile->f_op->aio_read)) {
NS_ERR("alloc_device: cache file not readable\n");
err = -EINVAL;
goto err_close;
}
if (!cfile->f_op->write && !cfile->f_op->aio_write) {
NS_ERR("alloc_device: cache file not writeable\n");
err = -EINVAL;
goto err_close;
}
ns->pages_written = vzalloc(ns->geom.pgnum);
if (!ns->pages_written) {
NS_ERR("alloc_device: unable to allocate pages written array\n");
err = -ENOMEM;
goto err_close;
}
ns->file_buf = kmalloc(ns->geom.pgszoob, GFP_KERNEL);
if (!ns->file_buf) {
NS_ERR("alloc_device: unable to allocate file buf\n");
err = -ENOMEM;
goto err_free;
}
ns->cfile = cfile;
return 0;
}
ns->pages = vmalloc(ns->geom.pgnum * sizeof(union ns_mem));
if (!ns->pages) {
NS_ERR("alloc_device: unable to allocate page array\n");
return -ENOMEM;
}
for (i = 0; i < ns->geom.pgnum; i++) {
ns->pages[i].byte = NULL;
}
ns->nand_pages_slab = kmem_cache_create("nandsim",
ns->geom.pgszoob, 0, 0, NULL);
if (!ns->nand_pages_slab) {
NS_ERR("cache_create: unable to create kmem_cache\n");
return -ENOMEM;
}
return 0;
err_free:
vfree(ns->pages_written);
err_close:
filp_close(cfile, NULL);
return err;
}
/*
* Free any allocated pages, and free the array of page pointers.
*/
static void free_device(struct nandsim *ns)
{
int i;
if (ns->cfile) {
kfree(ns->file_buf);
vfree(ns->pages_written);
filp_close(ns->cfile, NULL);
return;
}
if (ns->pages) {
for (i = 0; i < ns->geom.pgnum; i++) {
if (ns->pages[i].byte)
kmem_cache_free(ns->nand_pages_slab,
ns->pages[i].byte);
}
kmem_cache_destroy(ns->nand_pages_slab);
vfree(ns->pages);
}
}
static char *get_partition_name(int i)
{
char buf[64];
sprintf(buf, "NAND simulator partition %d", i);
return kstrdup(buf, GFP_KERNEL);
}
/*
* Initialize the nandsim structure.
*
* RETURNS: 0 if success, -ERRNO if failure.
*/
static int init_nandsim(struct mtd_info *mtd)
{
struct nand_chip *chip = mtd->priv;
struct nandsim *ns = chip->priv;
int i, ret = 0;
uint64_t remains;
uint64_t next_offset;
if (NS_IS_INITIALIZED(ns)) {
NS_ERR("init_nandsim: nandsim is already initialized\n");
return -EIO;
}
/* Force mtd to not do delays */
chip->chip_delay = 0;
/* Initialize the NAND flash parameters */
ns->busw = chip->options & NAND_BUSWIDTH_16 ? 16 : 8;
ns->geom.totsz = mtd->size;
ns->geom.pgsz = mtd->writesize;
ns->geom.oobsz = mtd->oobsize;
ns->geom.secsz = mtd->erasesize;
ns->geom.pgszoob = ns->geom.pgsz + ns->geom.oobsz;
ns->geom.pgnum = div_u64(ns->geom.totsz, ns->geom.pgsz);
ns->geom.totszoob = ns->geom.totsz + (uint64_t)ns->geom.pgnum * ns->geom.oobsz;
ns->geom.secshift = ffs(ns->geom.secsz) - 1;
ns->geom.pgshift = chip->page_shift;
ns->geom.oobshift = ffs(ns->geom.oobsz) - 1;
ns->geom.pgsec = ns->geom.secsz / ns->geom.pgsz;
ns->geom.secszoob = ns->geom.secsz + ns->geom.oobsz * ns->geom.pgsec;
ns->options = 0;
if (ns->geom.pgsz == 256) {
ns->options |= OPT_PAGE256;
}
else if (ns->geom.pgsz == 512) {
ns->options |= (OPT_PAGE512 | OPT_AUTOINCR);
if (ns->busw == 8)
ns->options |= OPT_PAGE512_8BIT;
} else if (ns->geom.pgsz == 2048) {
ns->options |= OPT_PAGE2048;
} else if (ns->geom.pgsz == 4096) {
ns->options |= OPT_PAGE4096;
} else {
NS_ERR("init_nandsim: unknown page size %u\n", ns->geom.pgsz);
return -EIO;
}
if (ns->options & OPT_SMALLPAGE) {
if (ns->geom.totsz <= (32 << 20)) {
ns->geom.pgaddrbytes = 3;
ns->geom.secaddrbytes = 2;
} else {
ns->geom.pgaddrbytes = 4;
ns->geom.secaddrbytes = 3;
}
} else {
if (ns->geom.totsz <= (128 << 20)) {
ns->geom.pgaddrbytes = 4;
ns->geom.secaddrbytes = 2;
} else {
ns->geom.pgaddrbytes = 5;
ns->geom.secaddrbytes = 3;
}
}
/* Fill the partition_info structure */
if (parts_num > ARRAY_SIZE(ns->partitions)) {
NS_ERR("too many partitions.\n");
ret = -EINVAL;
goto error;
}
remains = ns->geom.totsz;
next_offset = 0;
for (i = 0; i < parts_num; ++i) {
uint64_t part_sz = (uint64_t)parts[i] * ns->geom.secsz;
if (!part_sz || part_sz > remains) {
NS_ERR("bad partition size.\n");
ret = -EINVAL;
goto error;
}
ns->partitions[i].name = get_partition_name(i);
ns->partitions[i].offset = next_offset;
ns->partitions[i].size = part_sz;
next_offset += ns->partitions[i].size;
remains -= ns->partitions[i].size;
}
ns->nbparts = parts_num;
if (remains) {
if (parts_num + 1 > ARRAY_SIZE(ns->partitions)) {
NS_ERR("too many partitions.\n");
ret = -EINVAL;
goto error;
}
ns->partitions[i].name = get_partition_name(i);
ns->partitions[i].offset = next_offset;
ns->partitions[i].size = remains;
ns->nbparts += 1;
}
/* Detect how many ID bytes the NAND chip outputs */
for (i = 0; nand_flash_ids[i].name != NULL; i++) {
if (second_id_byte != nand_flash_ids[i].id)
continue;
if (!(nand_flash_ids[i].options & NAND_NO_AUTOINCR))
ns->options |= OPT_AUTOINCR;
}
if (ns->busw == 16)
NS_WARN("16-bit flashes support wasn't tested\n");
printk("flash size: %llu MiB\n",
(unsigned long long)ns->geom.totsz >> 20);
printk("page size: %u bytes\n", ns->geom.pgsz);
printk("OOB area size: %u bytes\n", ns->geom.oobsz);
printk("sector size: %u KiB\n", ns->geom.secsz >> 10);
printk("pages number: %u\n", ns->geom.pgnum);
printk("pages per sector: %u\n", ns->geom.pgsec);
printk("bus width: %u\n", ns->busw);
printk("bits in sector size: %u\n", ns->geom.secshift);
printk("bits in page size: %u\n", ns->geom.pgshift);
printk("bits in OOB size: %u\n", ns->geom.oobshift);
printk("flash size with OOB: %llu KiB\n",
(unsigned long long)ns->geom.totszoob >> 10);
printk("page address bytes: %u\n", ns->geom.pgaddrbytes);
printk("sector address bytes: %u\n", ns->geom.secaddrbytes);
printk("options: %#x\n", ns->options);
if ((ret = alloc_device(ns)) != 0)
goto error;
/* Allocate / initialize the internal buffer */
ns->buf.byte = kmalloc(ns->geom.pgszoob, GFP_KERNEL);
if (!ns->buf.byte) {
NS_ERR("init_nandsim: unable to allocate %u bytes for the internal buffer\n",
ns->geom.pgszoob);
ret = -ENOMEM;
goto error;
}
memset(ns->buf.byte, 0xFF, ns->geom.pgszoob);
return 0;
error:
free_device(ns);
return ret;
}
/*
* Free the nandsim structure.
*/
static void free_nandsim(struct nandsim *ns)
{
kfree(ns->buf.byte);
free_device(ns);
return;
}
static int parse_badblocks(struct nandsim *ns, struct mtd_info *mtd)
{
char *w;
int zero_ok;
unsigned int erase_block_no;
loff_t offset;
if (!badblocks)
return 0;
w = badblocks;
do {
zero_ok = (*w == '0' ? 1 : 0);
erase_block_no = simple_strtoul(w, &w, 0);
if (!zero_ok && !erase_block_no) {
NS_ERR("invalid badblocks.\n");
return -EINVAL;
}
offset = erase_block_no * ns->geom.secsz;
if (mtd_block_markbad(mtd, offset)) {
NS_ERR("invalid badblocks.\n");
return -EINVAL;
}
if (*w == ',')
w += 1;
} while (*w);
return 0;
}
static int parse_weakblocks(void)
{
char *w;
int zero_ok;
unsigned int erase_block_no;
unsigned int max_erases;
struct weak_block *wb;
if (!weakblocks)
return 0;
w = weakblocks;
do {
zero_ok = (*w == '0' ? 1 : 0);
erase_block_no = simple_strtoul(w, &w, 0);
if (!zero_ok && !erase_block_no) {
NS_ERR("invalid weakblocks.\n");
return -EINVAL;
}
max_erases = 3;
if (*w == ':') {
w += 1;
max_erases = simple_strtoul(w, &w, 0);
}
if (*w == ',')
w += 1;
wb = kzalloc(sizeof(*wb), GFP_KERNEL);
if (!wb) {
NS_ERR("unable to allocate memory.\n");
return -ENOMEM;
}
wb->erase_block_no = erase_block_no;
wb->max_erases = max_erases;
list_add(&wb->list, &weak_blocks);
} while (*w);
return 0;
}
static int erase_error(unsigned int erase_block_no)
{
struct weak_block *wb;
list_for_each_entry(wb, &weak_blocks, list)
if (wb->erase_block_no == erase_block_no) {
if (wb->erases_done >= wb->max_erases)
return 1;
wb->erases_done += 1;
return 0;
}
return 0;
}
static int parse_weakpages(void)
{
char *w;
int zero_ok;
unsigned int page_no;
unsigned int max_writes;
struct weak_page *wp;
if (!weakpages)
return 0;
w = weakpages;
do {
zero_ok = (*w == '0' ? 1 : 0);
page_no = simple_strtoul(w, &w, 0);
if (!zero_ok && !page_no) {
NS_ERR("invalid weakpagess.\n");
return -EINVAL;
}
max_writes = 3;
if (*w == ':') {
w += 1;
max_writes = simple_strtoul(w, &w, 0);
}
if (*w == ',')
w += 1;
wp = kzalloc(sizeof(*wp), GFP_KERNEL);
if (!wp) {
NS_ERR("unable to allocate memory.\n");
return -ENOMEM;
}
wp->page_no = page_no;
wp->max_writes = max_writes;
list_add(&wp->list, &weak_pages);
} while (*w);
return 0;
}
static int write_error(unsigned int page_no)
{
struct weak_page *wp;
list_for_each_entry(wp, &weak_pages, list)
if (wp->page_no == page_no) {
if (wp->writes_done >= wp->max_writes)
return 1;
wp->writes_done += 1;
return 0;
}
return 0;
}
static int parse_gravepages(void)
{
char *g;
int zero_ok;
unsigned int page_no;
unsigned int max_reads;
struct grave_page *gp;
if (!gravepages)
return 0;
g = gravepages;
do {
zero_ok = (*g == '0' ? 1 : 0);
page_no = simple_strtoul(g, &g, 0);
if (!zero_ok && !page_no) {
NS_ERR("invalid gravepagess.\n");
return -EINVAL;
}
max_reads = 3;
if (*g == ':') {
g += 1;
max_reads = simple_strtoul(g, &g, 0);
}
if (*g == ',')
g += 1;
gp = kzalloc(sizeof(*gp), GFP_KERNEL);
if (!gp) {
NS_ERR("unable to allocate memory.\n");
return -ENOMEM;
}
gp->page_no = page_no;
gp->max_reads = max_reads;
list_add(&gp->list, &grave_pages);
} while (*g);
return 0;
}
static int read_error(unsigned int page_no)
{
struct grave_page *gp;
list_for_each_entry(gp, &grave_pages, list)
if (gp->page_no == page_no) {
if (gp->reads_done >= gp->max_reads)
return 1;
gp->reads_done += 1;
return 0;
}
return 0;
}
static void free_lists(void)
{
struct list_head *pos, *n;
list_for_each_safe(pos, n, &weak_blocks) {
list_del(pos);
kfree(list_entry(pos, struct weak_block, list));
}
list_for_each_safe(pos, n, &weak_pages) {
list_del(pos);
kfree(list_entry(pos, struct weak_page, list));
}
list_for_each_safe(pos, n, &grave_pages) {
list_del(pos);
kfree(list_entry(pos, struct grave_page, list));
}
kfree(erase_block_wear);
}
static int setup_wear_reporting(struct mtd_info *mtd)
{
size_t mem;
if (!rptwear)
return 0;
wear_eb_count = div_u64(mtd->size, mtd->erasesize);
mem = wear_eb_count * sizeof(unsigned long);
if (mem / sizeof(unsigned long) != wear_eb_count) {
NS_ERR("Too many erase blocks for wear reporting\n");
return -ENOMEM;
}
erase_block_wear = kzalloc(mem, GFP_KERNEL);
if (!erase_block_wear) {
NS_ERR("Too many erase blocks for wear reporting\n");
return -ENOMEM;
}
return 0;
}
static void update_wear(unsigned int erase_block_no)
{
unsigned long wmin = -1, wmax = 0, avg;
unsigned long deciles[10], decile_max[10], tot = 0;
unsigned int i;
if (!erase_block_wear)
return;
total_wear += 1;
if (total_wear == 0)
NS_ERR("Erase counter total overflow\n");
erase_block_wear[erase_block_no] += 1;
if (erase_block_wear[erase_block_no] == 0)
NS_ERR("Erase counter overflow for erase block %u\n", erase_block_no);
rptwear_cnt += 1;
if (rptwear_cnt < rptwear)
return;
rptwear_cnt = 0;
/* Calc wear stats */
for (i = 0; i < wear_eb_count; ++i) {
unsigned long wear = erase_block_wear[i];
if (wear < wmin)
wmin = wear;
if (wear > wmax)
wmax = wear;
tot += wear;
}
for (i = 0; i < 9; ++i) {
deciles[i] = 0;
decile_max[i] = (wmax * (i + 1) + 5) / 10;
}
deciles[9] = 0;
decile_max[9] = wmax;
for (i = 0; i < wear_eb_count; ++i) {
int d;
unsigned long wear = erase_block_wear[i];
for (d = 0; d < 10; ++d)
if (wear <= decile_max[d]) {
deciles[d] += 1;
break;
}
}
avg = tot / wear_eb_count;
/* Output wear report */
NS_INFO("*** Wear Report ***\n");
NS_INFO("Total numbers of erases: %lu\n", tot);
NS_INFO("Number of erase blocks: %u\n", wear_eb_count);
NS_INFO("Average number of erases: %lu\n", avg);
NS_INFO("Maximum number of erases: %lu\n", wmax);
NS_INFO("Minimum number of erases: %lu\n", wmin);
for (i = 0; i < 10; ++i) {
unsigned long from = (i ? decile_max[i - 1] + 1 : 0);
if (from > decile_max[i])
continue;
NS_INFO("Number of ebs with erase counts from %lu to %lu : %lu\n",
from,
decile_max[i],
deciles[i]);
}
NS_INFO("*** End of Wear Report ***\n");
}
/*
* Returns the string representation of 'state' state.
*/
static char *get_state_name(uint32_t state)
{
switch (NS_STATE(state)) {
case STATE_CMD_READ0:
return "STATE_CMD_READ0";
case STATE_CMD_READ1:
return "STATE_CMD_READ1";
case STATE_CMD_PAGEPROG:
return "STATE_CMD_PAGEPROG";
case STATE_CMD_READOOB:
return "STATE_CMD_READOOB";
case STATE_CMD_READSTART:
return "STATE_CMD_READSTART";
case STATE_CMD_ERASE1:
return "STATE_CMD_ERASE1";
case STATE_CMD_STATUS:
return "STATE_CMD_STATUS";
case STATE_CMD_STATUS_M:
return "STATE_CMD_STATUS_M";
case STATE_CMD_SEQIN:
return "STATE_CMD_SEQIN";
case STATE_CMD_READID:
return "STATE_CMD_READID";
case STATE_CMD_ERASE2:
return "STATE_CMD_ERASE2";
case STATE_CMD_RESET:
return "STATE_CMD_RESET";
case STATE_CMD_RNDOUT:
return "STATE_CMD_RNDOUT";
case STATE_CMD_RNDOUTSTART:
return "STATE_CMD_RNDOUTSTART";
case STATE_ADDR_PAGE:
return "STATE_ADDR_PAGE";
case STATE_ADDR_SEC:
return "STATE_ADDR_SEC";
case STATE_ADDR_ZERO:
return "STATE_ADDR_ZERO";
case STATE_ADDR_COLUMN:
return "STATE_ADDR_COLUMN";
case STATE_DATAIN:
return "STATE_DATAIN";
case STATE_DATAOUT:
return "STATE_DATAOUT";
case STATE_DATAOUT_ID:
return "STATE_DATAOUT_ID";
case STATE_DATAOUT_STATUS:
return "STATE_DATAOUT_STATUS";
case STATE_DATAOUT_STATUS_M:
return "STATE_DATAOUT_STATUS_M";
case STATE_READY:
return "STATE_READY";
case STATE_UNKNOWN:
return "STATE_UNKNOWN";
}
NS_ERR("get_state_name: unknown state, BUG\n");
return NULL;
}
/*
* Check if command is valid.
*
* RETURNS: 1 if wrong command, 0 if right.
*/
static int check_command(int cmd)
{
switch (cmd) {
case NAND_CMD_READ0:
case NAND_CMD_READ1:
case NAND_CMD_READSTART:
case NAND_CMD_PAGEPROG:
case NAND_CMD_READOOB:
case NAND_CMD_ERASE1:
case NAND_CMD_STATUS:
case NAND_CMD_SEQIN:
case NAND_CMD_READID:
case NAND_CMD_ERASE2:
case NAND_CMD_RESET:
case NAND_CMD_RNDOUT:
case NAND_CMD_RNDOUTSTART:
return 0;
case NAND_CMD_STATUS_MULTI:
default:
return 1;
}
}
/*
* Returns state after command is accepted by command number.
*/
static uint32_t get_state_by_command(unsigned command)
{
switch (command) {
case NAND_CMD_READ0:
return STATE_CMD_READ0;
case NAND_CMD_READ1:
return STATE_CMD_READ1;
case NAND_CMD_PAGEPROG:
return STATE_CMD_PAGEPROG;
case NAND_CMD_READSTART:
return STATE_CMD_READSTART;
case NAND_CMD_READOOB:
return STATE_CMD_READOOB;
case NAND_CMD_ERASE1:
return STATE_CMD_ERASE1;
case NAND_CMD_STATUS:
return STATE_CMD_STATUS;
case NAND_CMD_STATUS_MULTI:
return STATE_CMD_STATUS_M;
case NAND_CMD_SEQIN:
return STATE_CMD_SEQIN;
case NAND_CMD_READID:
return STATE_CMD_READID;
case NAND_CMD_ERASE2:
return STATE_CMD_ERASE2;
case NAND_CMD_RESET:
return STATE_CMD_RESET;
case NAND_CMD_RNDOUT:
return STATE_CMD_RNDOUT;
case NAND_CMD_RNDOUTSTART:
return STATE_CMD_RNDOUTSTART;
}
NS_ERR("get_state_by_command: unknown command, BUG\n");
return 0;
}
/*
* Move an address byte to the correspondent internal register.
*/
static inline void accept_addr_byte(struct nandsim *ns, u_char bt)
{
uint byte = (uint)bt;
if (ns->regs.count < (ns->geom.pgaddrbytes - ns->geom.secaddrbytes))
ns->regs.column |= (byte << 8 * ns->regs.count);
else {
ns->regs.row |= (byte << 8 * (ns->regs.count -
ns->geom.pgaddrbytes +
ns->geom.secaddrbytes));
}
return;
}
/*
* Switch to STATE_READY state.
*/
static inline void switch_to_ready_state(struct nandsim *ns, u_char status)
{
NS_DBG("switch_to_ready_state: switch to %s state\n", get_state_name(STATE_READY));
ns->state = STATE_READY;
ns->nxstate = STATE_UNKNOWN;
ns->op = NULL;
ns->npstates = 0;
ns->stateidx = 0;
ns->regs.num = 0;
ns->regs.count = 0;
ns->regs.off = 0;
ns->regs.row = 0;
ns->regs.column = 0;
ns->regs.status = status;
}
/*
* If the operation isn't known yet, try to find it in the global array
* of supported operations.
*
* Operation can be unknown because of the following.
* 1. New command was accepted and this is the first call to find the
* correspondent states chain. In this case ns->npstates = 0;
* 2. There are several operations which begin with the same command(s)
* (for example program from the second half and read from the
* second half operations both begin with the READ1 command). In this
* case the ns->pstates[] array contains previous states.
*
* Thus, the function tries to find operation containing the following
* states (if the 'flag' parameter is 0):
* ns->pstates[0], ... ns->pstates[ns->npstates], ns->state
*
* If (one and only one) matching operation is found, it is accepted (
* ns->ops, ns->state, ns->nxstate are initialized, ns->npstate is
* zeroed).
*
* If there are several matches, the current state is pushed to the
* ns->pstates.
*
* The operation can be unknown only while commands are input to the chip.
* As soon as address command is accepted, the operation must be known.
* In such situation the function is called with 'flag' != 0, and the
* operation is searched using the following pattern:
* ns->pstates[0], ... ns->pstates[ns->npstates], <address input>
*
* It is supposed that this pattern must either match one operation or
* none. There can't be ambiguity in that case.
*
* If no matches found, the function does the following:
* 1. if there are saved states present, try to ignore them and search
* again only using the last command. If nothing was found, switch
* to the STATE_READY state.
* 2. if there are no saved states, switch to the STATE_READY state.
*
* RETURNS: -2 - no matched operations found.
* -1 - several matches.
* 0 - operation is found.
*/
static int find_operation(struct nandsim *ns, uint32_t flag)
{
int opsfound = 0;
int i, j, idx = 0;
for (i = 0; i < NS_OPER_NUM; i++) {
int found = 1;
if (!(ns->options & ops[i].reqopts))
/* Ignore operations we can't perform */
continue;
if (flag) {
if (!(ops[i].states[ns->npstates] & STATE_ADDR_MASK))
continue;
} else {
if (NS_STATE(ns->state) != NS_STATE(ops[i].states[ns->npstates]))
continue;
}
for (j = 0; j < ns->npstates; j++)
if (NS_STATE(ops[i].states[j]) != NS_STATE(ns->pstates[j])
&& (ns->options & ops[idx].reqopts)) {
found = 0;
break;
}
if (found) {
idx = i;
opsfound += 1;
}
}
if (opsfound == 1) {
/* Exact match */
ns->op = &ops[idx].states[0];
if (flag) {
/*
* In this case the find_operation function was
* called when address has just began input. But it isn't
* yet fully input and the current state must
* not be one of STATE_ADDR_*, but the STATE_ADDR_*
* state must be the next state (ns->nxstate).
*/
ns->stateidx = ns->npstates - 1;
} else {
ns->stateidx = ns->npstates;
}
ns->npstates = 0;
ns->state = ns->op[ns->stateidx];
ns->nxstate = ns->op[ns->stateidx + 1];
NS_DBG("find_operation: operation found, index: %d, state: %s, nxstate %s\n",
idx, get_state_name(ns->state), get_state_name(ns->nxstate));
return 0;
}
if (opsfound == 0) {
/* Nothing was found. Try to ignore previous commands (if any) and search again */
if (ns->npstates != 0) {
NS_DBG("find_operation: no operation found, try again with state %s\n",
get_state_name(ns->state));
ns->npstates = 0;
return find_operation(ns, 0);
}
NS_DBG("find_operation: no operations found\n");
switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
return -2;
}
if (flag) {
/* This shouldn't happen */
NS_DBG("find_operation: BUG, operation must be known if address is input\n");
return -2;
}
NS_DBG("find_operation: there is still ambiguity\n");
ns->pstates[ns->npstates++] = ns->state;
return -1;
}
static void put_pages(struct nandsim *ns)
{
int i;
for (i = 0; i < ns->held_cnt; i++)
page_cache_release(ns->held_pages[i]);
}
/* Get page cache pages in advance to provide NOFS memory allocation */
static int get_pages(struct nandsim *ns, struct file *file, size_t count, loff_t pos)
{
pgoff_t index, start_index, end_index;
struct page *page;
struct address_space *mapping = file->f_mapping;
start_index = pos >> PAGE_CACHE_SHIFT;
end_index = (pos + count - 1) >> PAGE_CACHE_SHIFT;
if (end_index - start_index + 1 > NS_MAX_HELD_PAGES)
return -EINVAL;
ns->held_cnt = 0;
for (index = start_index; index <= end_index; index++) {
page = find_get_page(mapping, index);
if (page == NULL) {
page = find_or_create_page(mapping, index, GFP_NOFS);
if (page == NULL) {
write_inode_now(mapping->host, 1);
page = find_or_create_page(mapping, index, GFP_NOFS);
}
if (page == NULL) {
put_pages(ns);
return -ENOMEM;
}
unlock_page(page);
}
ns->held_pages[ns->held_cnt++] = page;
}
return 0;
}
static int set_memalloc(void)
{
if (current->flags & PF_MEMALLOC)
return 0;
current->flags |= PF_MEMALLOC;
return 1;
}
static void clear_memalloc(int memalloc)
{
if (memalloc)
current->flags &= ~PF_MEMALLOC;
}
static ssize_t read_file(struct nandsim *ns, struct file *file, void *buf, size_t count, loff_t *pos)
{
mm_segment_t old_fs;
ssize_t tx;
int err, memalloc;
err = get_pages(ns, file, count, *pos);
if (err)
return err;
old_fs = get_fs();
set_fs(get_ds());
memalloc = set_memalloc();
tx = vfs_read(file, (char __user *)buf, count, pos);
clear_memalloc(memalloc);
set_fs(old_fs);
put_pages(ns);
return tx;
}
static ssize_t write_file(struct nandsim *ns, struct file *file, void *buf, size_t count, loff_t *pos)
{
mm_segment_t old_fs;
ssize_t tx;
int err, memalloc;
err = get_pages(ns, file, count, *pos);
if (err)
return err;
old_fs = get_fs();
set_fs(get_ds());
memalloc = set_memalloc();
tx = vfs_write(file, (char __user *)buf, count, pos);
clear_memalloc(memalloc);
set_fs(old_fs);
put_pages(ns);
return tx;
}
/*
* Returns a pointer to the current page.
*/
static inline union ns_mem *NS_GET_PAGE(struct nandsim *ns)
{
return &(ns->pages[ns->regs.row]);
}
/*
* Retuns a pointer to the current byte, within the current page.
*/
static inline u_char *NS_PAGE_BYTE_OFF(struct nandsim *ns)
{
return NS_GET_PAGE(ns)->byte + ns->regs.column + ns->regs.off;
}
int do_read_error(struct nandsim *ns, int num)
{
unsigned int page_no = ns->regs.row;
if (read_error(page_no)) {
int i;
memset(ns->buf.byte, 0xFF, num);
for (i = 0; i < num; ++i)
ns->buf.byte[i] = random32();
NS_WARN("simulating read error in page %u\n", page_no);
return 1;
}
return 0;
}
void do_bit_flips(struct nandsim *ns, int num)
{
if (bitflips && random32() < (1 << 22)) {
int flips = 1;
if (bitflips > 1)
flips = (random32() % (int) bitflips) + 1;
while (flips--) {
int pos = random32() % (num * 8);
ns->buf.byte[pos / 8] ^= (1 << (pos % 8));
NS_WARN("read_page: flipping bit %d in page %d "
"reading from %d ecc: corrected=%u failed=%u\n",
pos, ns->regs.row, ns->regs.column + ns->regs.off,
nsmtd->ecc_stats.corrected, nsmtd->ecc_stats.failed);
}
}
}
/*
* Fill the NAND buffer with data read from the specified page.
*/
static void read_page(struct nandsim *ns, int num)
{
union ns_mem *mypage;
if (ns->cfile) {
if (!ns->pages_written[ns->regs.row]) {
NS_DBG("read_page: page %d not written\n", ns->regs.row);
memset(ns->buf.byte, 0xFF, num);
} else {
loff_t pos;
ssize_t tx;
NS_DBG("read_page: page %d written, reading from %d\n",
ns->regs.row, ns->regs.column + ns->regs.off);
if (do_read_error(ns, num))
return;
pos = (loff_t)ns->regs.row * ns->geom.pgszoob + ns->regs.column + ns->regs.off;
tx = read_file(ns, ns->cfile, ns->buf.byte, num, &pos);
if (tx != num) {
NS_ERR("read_page: read error for page %d ret %ld\n", ns->regs.row, (long)tx);
return;
}
do_bit_flips(ns, num);
}
return;
}
mypage = NS_GET_PAGE(ns);
if (mypage->byte == NULL) {
NS_DBG("read_page: page %d not allocated\n", ns->regs.row);
memset(ns->buf.byte, 0xFF, num);
} else {
NS_DBG("read_page: page %d allocated, reading from %d\n",
ns->regs.row, ns->regs.column + ns->regs.off);
if (do_read_error(ns, num))
return;
memcpy(ns->buf.byte, NS_PAGE_BYTE_OFF(ns), num);
do_bit_flips(ns, num);
}
}
/*
* Erase all pages in the specified sector.
*/
static void erase_sector(struct nandsim *ns)
{
union ns_mem *mypage;
int i;
if (ns->cfile) {
for (i = 0; i < ns->geom.pgsec; i++)
if (ns->pages_written[ns->regs.row + i]) {
NS_DBG("erase_sector: freeing page %d\n", ns->regs.row + i);
ns->pages_written[ns->regs.row + i] = 0;
}
return;
}
mypage = NS_GET_PAGE(ns);
for (i = 0; i < ns->geom.pgsec; i++) {
if (mypage->byte != NULL) {
NS_DBG("erase_sector: freeing page %d\n", ns->regs.row+i);
kmem_cache_free(ns->nand_pages_slab, mypage->byte);
mypage->byte = NULL;
}
mypage++;
}
}
/*
* Program the specified page with the contents from the NAND buffer.
*/
static int prog_page(struct nandsim *ns, int num)
{
int i;
union ns_mem *mypage;
u_char *pg_off;
if (ns->cfile) {
loff_t off, pos;
ssize_t tx;
int all;
NS_DBG("prog_page: writing page %d\n", ns->regs.row);
pg_off = ns->file_buf + ns->regs.column + ns->regs.off;
off = (loff_t)ns->regs.row * ns->geom.pgszoob + ns->regs.column + ns->regs.off;
if (!ns->pages_written[ns->regs.row]) {
all = 1;
memset(ns->file_buf, 0xff, ns->geom.pgszoob);
} else {
all = 0;
pos = off;
tx = read_file(ns, ns->cfile, pg_off, num, &pos);
if (tx != num) {
NS_ERR("prog_page: read error for page %d ret %ld\n", ns->regs.row, (long)tx);
return -1;
}
}
for (i = 0; i < num; i++)
pg_off[i] &= ns->buf.byte[i];
if (all) {
pos = (loff_t)ns->regs.row * ns->geom.pgszoob;
tx = write_file(ns, ns->cfile, ns->file_buf, ns->geom.pgszoob, &pos);
if (tx != ns->geom.pgszoob) {
NS_ERR("prog_page: write error for page %d ret %ld\n", ns->regs.row, (long)tx);
return -1;
}
ns->pages_written[ns->regs.row] = 1;
} else {
pos = off;
tx = write_file(ns, ns->cfile, pg_off, num, &pos);
if (tx != num) {
NS_ERR("prog_page: write error for page %d ret %ld\n", ns->regs.row, (long)tx);
return -1;
}
}
return 0;
}
mypage = NS_GET_PAGE(ns);
if (mypage->byte == NULL) {
NS_DBG("prog_page: allocating page %d\n", ns->regs.row);
/*
* We allocate memory with GFP_NOFS because a flash FS may
* utilize this. If it is holding an FS lock, then gets here,
* then kernel memory alloc runs writeback which goes to the FS
* again and deadlocks. This was seen in practice.
*/
mypage->byte = kmem_cache_alloc(ns->nand_pages_slab, GFP_NOFS);
if (mypage->byte == NULL) {
NS_ERR("prog_page: error allocating memory for page %d\n", ns->regs.row);
return -1;
}
memset(mypage->byte, 0xFF, ns->geom.pgszoob);
}
pg_off = NS_PAGE_BYTE_OFF(ns);
for (i = 0; i < num; i++)
pg_off[i] &= ns->buf.byte[i];
return 0;
}
/*
* If state has any action bit, perform this action.
*
* RETURNS: 0 if success, -1 if error.
*/
static int do_state_action(struct nandsim *ns, uint32_t action)
{
int num;
int busdiv = ns->busw == 8 ? 1 : 2;
unsigned int erase_block_no, page_no;
action &= ACTION_MASK;
/* Check that page address input is correct */
if (action != ACTION_SECERASE && ns->regs.row >= ns->geom.pgnum) {
NS_WARN("do_state_action: wrong page number (%#x)\n", ns->regs.row);
return -1;
}
switch (action) {
case ACTION_CPY:
/*
* Copy page data to the internal buffer.
*/
/* Column shouldn't be very large */
if (ns->regs.column >= (ns->geom.pgszoob - ns->regs.off)) {
NS_ERR("do_state_action: column number is too large\n");
break;
}
num = ns->geom.pgszoob - ns->regs.off - ns->regs.column;
read_page(ns, num);
NS_DBG("do_state_action: (ACTION_CPY:) copy %d bytes to int buf, raw offset %d\n",
num, NS_RAW_OFFSET(ns) + ns->regs.off);
if (ns->regs.off == 0)
NS_LOG("read page %d\n", ns->regs.row);
else if (ns->regs.off < ns->geom.pgsz)
NS_LOG("read page %d (second half)\n", ns->regs.row);
else
NS_LOG("read OOB of page %d\n", ns->regs.row);
NS_UDELAY(access_delay);
NS_UDELAY(input_cycle * ns->geom.pgsz / 1000 / busdiv);
break;
case ACTION_SECERASE:
/*
* Erase sector.
*/
if (ns->lines.wp) {
NS_ERR("do_state_action: device is write-protected, ignore sector erase\n");
return -1;
}
if (ns->regs.row >= ns->geom.pgnum - ns->geom.pgsec
|| (ns->regs.row & ~(ns->geom.secsz - 1))) {
NS_ERR("do_state_action: wrong sector address (%#x)\n", ns->regs.row);
return -1;
}
ns->regs.row = (ns->regs.row <<
8 * (ns->geom.pgaddrbytes - ns->geom.secaddrbytes)) | ns->regs.column;
ns->regs.column = 0;
erase_block_no = ns->regs.row >> (ns->geom.secshift - ns->geom.pgshift);
NS_DBG("do_state_action: erase sector at address %#x, off = %d\n",
ns->regs.row, NS_RAW_OFFSET(ns));
NS_LOG("erase sector %u\n", erase_block_no);
erase_sector(ns);
NS_MDELAY(erase_delay);
if (erase_block_wear)
update_wear(erase_block_no);
if (erase_error(erase_block_no)) {
NS_WARN("simulating erase failure in erase block %u\n", erase_block_no);
return -1;
}
break;
case ACTION_PRGPAGE:
/*
* Program page - move internal buffer data to the page.
*/
if (ns->lines.wp) {
NS_WARN("do_state_action: device is write-protected, programm\n");
return -1;
}
num = ns->geom.pgszoob - ns->regs.off - ns->regs.column;
if (num != ns->regs.count) {
NS_ERR("do_state_action: too few bytes were input (%d instead of %d)\n",
ns->regs.count, num);
return -1;
}
if (prog_page(ns, num) == -1)
return -1;
page_no = ns->regs.row;
NS_DBG("do_state_action: copy %d bytes from int buf to (%#x, %#x), raw off = %d\n",
num, ns->regs.row, ns->regs.column, NS_RAW_OFFSET(ns) + ns->regs.off);
NS_LOG("programm page %d\n", ns->regs.row);
NS_UDELAY(programm_delay);
NS_UDELAY(output_cycle * ns->geom.pgsz / 1000 / busdiv);
if (write_error(page_no)) {
NS_WARN("simulating write failure in page %u\n", page_no);
return -1;
}
break;
case ACTION_ZEROOFF:
NS_DBG("do_state_action: set internal offset to 0\n");
ns->regs.off = 0;
break;
case ACTION_HALFOFF:
if (!(ns->options & OPT_PAGE512_8BIT)) {
NS_ERR("do_state_action: BUG! can't skip half of page for non-512"
"byte page size 8x chips\n");
return -1;
}
NS_DBG("do_state_action: set internal offset to %d\n", ns->geom.pgsz/2);
ns->regs.off = ns->geom.pgsz/2;
break;
case ACTION_OOBOFF:
NS_DBG("do_state_action: set internal offset to %d\n", ns->geom.pgsz);
ns->regs.off = ns->geom.pgsz;
break;
default:
NS_DBG("do_state_action: BUG! unknown action\n");
}
return 0;
}
/*
* Switch simulator's state.
*/
static void switch_state(struct nandsim *ns)
{
if (ns->op) {
/*
* The current operation have already been identified.
* Just follow the states chain.
*/
ns->stateidx += 1;
ns->state = ns->nxstate;
ns->nxstate = ns->op[ns->stateidx + 1];
NS_DBG("switch_state: operation is known, switch to the next state, "
"state: %s, nxstate: %s\n",
get_state_name(ns->state), get_state_name(ns->nxstate));
/* See, whether we need to do some action */
if ((ns->state & ACTION_MASK) && do_state_action(ns, ns->state) < 0) {
switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
return;
}
} else {
/*
* We don't yet know which operation we perform.
* Try to identify it.
*/
/*
* The only event causing the switch_state function to
* be called with yet unknown operation is new command.
*/
ns->state = get_state_by_command(ns->regs.command);
NS_DBG("switch_state: operation is unknown, try to find it\n");
if (find_operation(ns, 0) != 0)
return;
if ((ns->state & ACTION_MASK) && do_state_action(ns, ns->state) < 0) {
switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
return;
}
}
/* For 16x devices column means the page offset in words */
if ((ns->nxstate & STATE_ADDR_MASK) && ns->busw == 16) {
NS_DBG("switch_state: double the column number for 16x device\n");
ns->regs.column <<= 1;
}
if (NS_STATE(ns->nxstate) == STATE_READY) {
/*
* The current state is the last. Return to STATE_READY
*/
u_char status = NS_STATUS_OK(ns);
/* In case of data states, see if all bytes were input/output */
if ((ns->state & (STATE_DATAIN_MASK | STATE_DATAOUT_MASK))
&& ns->regs.count != ns->regs.num) {
NS_WARN("switch_state: not all bytes were processed, %d left\n",
ns->regs.num - ns->regs.count);
status = NS_STATUS_FAILED(ns);
}
NS_DBG("switch_state: operation complete, switch to STATE_READY state\n");
switch_to_ready_state(ns, status);
return;
} else if (ns->nxstate & (STATE_DATAIN_MASK | STATE_DATAOUT_MASK)) {
/*
* If the next state is data input/output, switch to it now
*/
ns->state = ns->nxstate;
ns->nxstate = ns->op[++ns->stateidx + 1];
ns->regs.num = ns->regs.count = 0;
NS_DBG("switch_state: the next state is data I/O, switch, "
"state: %s, nxstate: %s\n",
get_state_name(ns->state), get_state_name(ns->nxstate));
/*
* Set the internal register to the count of bytes which
* are expected to be input or output
*/
switch (NS_STATE(ns->state)) {
case STATE_DATAIN:
case STATE_DATAOUT:
ns->regs.num = ns->geom.pgszoob - ns->regs.off - ns->regs.column;
break;
case STATE_DATAOUT_ID:
ns->regs.num = ns->geom.idbytes;
break;
case STATE_DATAOUT_STATUS:
case STATE_DATAOUT_STATUS_M:
ns->regs.count = ns->regs.num = 0;
break;
default:
NS_ERR("switch_state: BUG! unknown data state\n");
}
} else if (ns->nxstate & STATE_ADDR_MASK) {
/*
* If the next state is address input, set the internal
* register to the number of expected address bytes
*/
ns->regs.count = 0;
switch (NS_STATE(ns->nxstate)) {
case STATE_ADDR_PAGE:
ns->regs.num = ns->geom.pgaddrbytes;
break;
case STATE_ADDR_SEC:
ns->regs.num = ns->geom.secaddrbytes;
break;
case STATE_ADDR_ZERO:
ns->regs.num = 1;
break;
case STATE_ADDR_COLUMN:
/* Column address is always 2 bytes */
ns->regs.num = ns->geom.pgaddrbytes - ns->geom.secaddrbytes;
break;
default:
NS_ERR("switch_state: BUG! unknown address state\n");
}
} else {
/*
* Just reset internal counters.
*/
ns->regs.num = 0;
ns->regs.count = 0;
}
}
static u_char ns_nand_read_byte(struct mtd_info *mtd)
{
struct nandsim *ns = ((struct nand_chip *)mtd->priv)->priv;
u_char outb = 0x00;
/* Sanity and correctness checks */
if (!ns->lines.ce) {
NS_ERR("read_byte: chip is disabled, return %#x\n", (uint)outb);
return outb;
}
if (ns->lines.ale || ns->lines.cle) {
NS_ERR("read_byte: ALE or CLE pin is high, return %#x\n", (uint)outb);
return outb;
}
if (!(ns->state & STATE_DATAOUT_MASK)) {
NS_WARN("read_byte: unexpected data output cycle, state is %s "
"return %#x\n", get_state_name(ns->state), (uint)outb);
return outb;
}
/* Status register may be read as many times as it is wanted */
if (NS_STATE(ns->state) == STATE_DATAOUT_STATUS) {
NS_DBG("read_byte: return %#x status\n", ns->regs.status);
return ns->regs.status;
}
/* Check if there is any data in the internal buffer which may be read */
if (ns->regs.count == ns->regs.num) {
NS_WARN("read_byte: no more data to output, return %#x\n", (uint)outb);
return outb;
}
switch (NS_STATE(ns->state)) {
case STATE_DATAOUT:
if (ns->busw == 8) {
outb = ns->buf.byte[ns->regs.count];
ns->regs.count += 1;
} else {
outb = (u_char)cpu_to_le16(ns->buf.word[ns->regs.count >> 1]);
ns->regs.count += 2;
}
break;
case STATE_DATAOUT_ID:
NS_DBG("read_byte: read ID byte %d, total = %d\n", ns->regs.count, ns->regs.num);
outb = ns->ids[ns->regs.count];
ns->regs.count += 1;
break;
default:
BUG();
}
if (ns->regs.count == ns->regs.num) {
NS_DBG("read_byte: all bytes were read\n");
/*
* The OPT_AUTOINCR allows to read next consecutive pages without
* new read operation cycle.
*/
if ((ns->options & OPT_AUTOINCR) && NS_STATE(ns->state) == STATE_DATAOUT) {
ns->regs.count = 0;
if (ns->regs.row + 1 < ns->geom.pgnum)
ns->regs.row += 1;
NS_DBG("read_byte: switch to the next page (%#x)\n", ns->regs.row);
do_state_action(ns, ACTION_CPY);
}
else if (NS_STATE(ns->nxstate) == STATE_READY)
switch_state(ns);
}
return outb;
}
static void ns_nand_write_byte(struct mtd_info *mtd, u_char byte)
{
struct nandsim *ns = ((struct nand_chip *)mtd->priv)->priv;
/* Sanity and correctness checks */
if (!ns->lines.ce) {
NS_ERR("write_byte: chip is disabled, ignore write\n");
return;
}
if (ns->lines.ale && ns->lines.cle) {
NS_ERR("write_byte: ALE and CLE pins are high simultaneously, ignore write\n");
return;
}
if (ns->lines.cle == 1) {
/*
* The byte written is a command.
*/
if (byte == NAND_CMD_RESET) {
NS_LOG("reset chip\n");
switch_to_ready_state(ns, NS_STATUS_OK(ns));
return;
}
/* Check that the command byte is correct */
if (check_command(byte)) {
NS_ERR("write_byte: unknown command %#x\n", (uint)byte);
return;
}
if (NS_STATE(ns->state) == STATE_DATAOUT_STATUS
|| NS_STATE(ns->state) == STATE_DATAOUT_STATUS_M
|| NS_STATE(ns->state) == STATE_DATAOUT) {
int row = ns->regs.row;
switch_state(ns);
if (byte == NAND_CMD_RNDOUT)
ns->regs.row = row;
}
/* Check if chip is expecting command */
if (NS_STATE(ns->nxstate) != STATE_UNKNOWN && !(ns->nxstate & STATE_CMD_MASK)) {
/* Do not warn if only 2 id bytes are read */
if (!(ns->regs.command == NAND_CMD_READID &&
NS_STATE(ns->state) == STATE_DATAOUT_ID && ns->regs.count == 2)) {
/*
* We are in situation when something else (not command)
* was expected but command was input. In this case ignore
* previous command(s)/state(s) and accept the last one.
*/
NS_WARN("write_byte: command (%#x) wasn't expected, expected state is %s, "
"ignore previous states\n", (uint)byte, get_state_name(ns->nxstate));
}
switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
}
NS_DBG("command byte corresponding to %s state accepted\n",
get_state_name(get_state_by_command(byte)));
ns->regs.command = byte;
switch_state(ns);
} else if (ns->lines.ale == 1) {
/*
* The byte written is an address.
*/
if (NS_STATE(ns->nxstate) == STATE_UNKNOWN) {
NS_DBG("write_byte: operation isn't known yet, identify it\n");
if (find_operation(ns, 1) < 0)
return;
if ((ns->state & ACTION_MASK) && do_state_action(ns, ns->state) < 0) {
switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
return;
}
ns->regs.count = 0;
switch (NS_STATE(ns->nxstate)) {
case STATE_ADDR_PAGE:
ns->regs.num = ns->geom.pgaddrbytes;
break;
case STATE_ADDR_SEC:
ns->regs.num = ns->geom.secaddrbytes;
break;
case STATE_ADDR_ZERO:
ns->regs.num = 1;
break;
default:
BUG();
}
}
/* Check that chip is expecting address */
if (!(ns->nxstate & STATE_ADDR_MASK)) {
NS_ERR("write_byte: address (%#x) isn't expected, expected state is %s, "
"switch to STATE_READY\n", (uint)byte, get_state_name(ns->nxstate));
switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
return;
}
/* Check if this is expected byte */
if (ns->regs.count == ns->regs.num) {
NS_ERR("write_byte: no more address bytes expected\n");
switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
return;
}
accept_addr_byte(ns, byte);
ns->regs.count += 1;
NS_DBG("write_byte: address byte %#x was accepted (%d bytes input, %d expected)\n",
(uint)byte, ns->regs.count, ns->regs.num);
if (ns->regs.count == ns->regs.num) {
NS_DBG("address (%#x, %#x) is accepted\n", ns->regs.row, ns->regs.column);
switch_state(ns);
}
} else {
/*
* The byte written is an input data.
*/
/* Check that chip is expecting data input */
if (!(ns->state & STATE_DATAIN_MASK)) {
NS_ERR("write_byte: data input (%#x) isn't expected, state is %s, "
"switch to %s\n", (uint)byte,
get_state_name(ns->state), get_state_name(STATE_READY));
switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
return;
}
/* Check if this is expected byte */
if (ns->regs.count == ns->regs.num) {
NS_WARN("write_byte: %u input bytes has already been accepted, ignore write\n",
ns->regs.num);
return;
}
if (ns->busw == 8) {
ns->buf.byte[ns->regs.count] = byte;
ns->regs.count += 1;
} else {
ns->buf.word[ns->regs.count >> 1] = cpu_to_le16((uint16_t)byte);
ns->regs.count += 2;
}
}
return;
}
static void ns_hwcontrol(struct mtd_info *mtd, int cmd, unsigned int bitmask)
{
struct nandsim *ns = ((struct nand_chip *)mtd->priv)->priv;
ns->lines.cle = bitmask & NAND_CLE ? 1 : 0;
ns->lines.ale = bitmask & NAND_ALE ? 1 : 0;
ns->lines.ce = bitmask & NAND_NCE ? 1 : 0;
if (cmd != NAND_CMD_NONE)
ns_nand_write_byte(mtd, cmd);
}
static int ns_device_ready(struct mtd_info *mtd)
{
NS_DBG("device_ready\n");
return 1;
}
static uint16_t ns_nand_read_word(struct mtd_info *mtd)
{
struct nand_chip *chip = (struct nand_chip *)mtd->priv;
NS_DBG("read_word\n");
return chip->read_byte(mtd) | (chip->read_byte(mtd) << 8);
}
static void ns_nand_write_buf(struct mtd_info *mtd, const u_char *buf, int len)
{
struct nandsim *ns = ((struct nand_chip *)mtd->priv)->priv;
/* Check that chip is expecting data input */
if (!(ns->state & STATE_DATAIN_MASK)) {
NS_ERR("write_buf: data input isn't expected, state is %s, "
"switch to STATE_READY\n", get_state_name(ns->state));
switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
return;
}
/* Check if these are expected bytes */
if (ns->regs.count + len > ns->regs.num) {
NS_ERR("write_buf: too many input bytes\n");
switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
return;
}
memcpy(ns->buf.byte + ns->regs.count, buf, len);
ns->regs.count += len;
if (ns->regs.count == ns->regs.num) {
NS_DBG("write_buf: %d bytes were written\n", ns->regs.count);
}
}
static void ns_nand_read_buf(struct mtd_info *mtd, u_char *buf, int len)
{
struct nandsim *ns = ((struct nand_chip *)mtd->priv)->priv;
/* Sanity and correctness checks */
if (!ns->lines.ce) {
NS_ERR("read_buf: chip is disabled\n");
return;
}
if (ns->lines.ale || ns->lines.cle) {
NS_ERR("read_buf: ALE or CLE pin is high\n");
return;
}
if (!(ns->state & STATE_DATAOUT_MASK)) {
NS_WARN("read_buf: unexpected data output cycle, current state is %s\n",
get_state_name(ns->state));
return;
}
if (NS_STATE(ns->state) != STATE_DATAOUT) {
int i;
for (i = 0; i < len; i++)
buf[i] = ((struct nand_chip *)mtd->priv)->read_byte(mtd);
return;
}
/* Check if these are expected bytes */
if (ns->regs.count + len > ns->regs.num) {
NS_ERR("read_buf: too many bytes to read\n");
switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
return;
}
memcpy(buf, ns->buf.byte + ns->regs.count, len);
ns->regs.count += len;
if (ns->regs.count == ns->regs.num) {
if ((ns->options & OPT_AUTOINCR) && NS_STATE(ns->state) == STATE_DATAOUT) {
ns->regs.count = 0;
if (ns->regs.row + 1 < ns->geom.pgnum)
ns->regs.row += 1;
NS_DBG("read_buf: switch to the next page (%#x)\n", ns->regs.row);
do_state_action(ns, ACTION_CPY);
}
else if (NS_STATE(ns->nxstate) == STATE_READY)
switch_state(ns);
}
return;
}
static int ns_nand_verify_buf(struct mtd_info *mtd, const u_char *buf, int len)
{
ns_nand_read_buf(mtd, (u_char *)&ns_verify_buf[0], len);
if (!memcmp(buf, &ns_verify_buf[0], len)) {
NS_DBG("verify_buf: the buffer is OK\n");
return 0;
} else {
NS_DBG("verify_buf: the buffer is wrong\n");
return -EFAULT;
}
}
/*
* Module initialization function
*/
static int __init ns_init_module(void)
{
struct nand_chip *chip;
struct nandsim *nand;
int retval = -ENOMEM, i;
if (bus_width != 8 && bus_width != 16) {
NS_ERR("wrong bus width (%d), use only 8 or 16\n", bus_width);
return -EINVAL;
}
/* Allocate and initialize mtd_info, nand_chip and nandsim structures */
nsmtd = kzalloc(sizeof(struct mtd_info) + sizeof(struct nand_chip)
+ sizeof(struct nandsim), GFP_KERNEL);
if (!nsmtd) {
NS_ERR("unable to allocate core structures.\n");
return -ENOMEM;
}
chip = (struct nand_chip *)(nsmtd + 1);
nsmtd->priv = (void *)chip;
nand = (struct nandsim *)(chip + 1);
chip->priv = (void *)nand;
/*
* Register simulator's callbacks.
*/
chip->cmd_ctrl = ns_hwcontrol;
chip->read_byte = ns_nand_read_byte;
chip->dev_ready = ns_device_ready;
chip->write_buf = ns_nand_write_buf;
chip->read_buf = ns_nand_read_buf;
chip->verify_buf = ns_nand_verify_buf;
chip->read_word = ns_nand_read_word;
chip->ecc.mode = NAND_ECC_SOFT;
/* The NAND_SKIP_BBTSCAN option is necessary for 'overridesize' */
/* and 'badblocks' parameters to work */
chip->options |= NAND_SKIP_BBTSCAN;
switch (bbt) {
case 2:
chip->bbt_options |= NAND_BBT_NO_OOB;
case 1:
chip->bbt_options |= NAND_BBT_USE_FLASH;
case 0:
break;
default:
NS_ERR("bbt has to be 0..2\n");
retval = -EINVAL;
goto error;
}
/*
* Perform minimum nandsim structure initialization to handle
* the initial ID read command correctly
*/
if (third_id_byte != 0xFF || fourth_id_byte != 0xFF)
nand->geom.idbytes = 4;
else
nand->geom.idbytes = 2;
nand->regs.status = NS_STATUS_OK(nand);
nand->nxstate = STATE_UNKNOWN;
nand->options |= OPT_PAGE256; /* temporary value */
nand->ids[0] = first_id_byte;
nand->ids[1] = second_id_byte;
nand->ids[2] = third_id_byte;
nand->ids[3] = fourth_id_byte;
if (bus_width == 16) {
nand->busw = 16;
chip->options |= NAND_BUSWIDTH_16;
}
nsmtd->owner = THIS_MODULE;
if ((retval = parse_weakblocks()) != 0)
goto error;
if ((retval = parse_weakpages()) != 0)
goto error;
if ((retval = parse_gravepages()) != 0)
goto error;
retval = nand_scan_ident(nsmtd, 1, NULL);
if (retval) {
NS_ERR("cannot scan NAND Simulator device\n");
if (retval > 0)
retval = -ENXIO;
goto error;
}
if (bch) {
unsigned int eccsteps, eccbytes;
if (!mtd_nand_has_bch()) {
NS_ERR("BCH ECC support is disabled\n");
retval = -EINVAL;
goto error;
}
/* use 512-byte ecc blocks */
eccsteps = nsmtd->writesize/512;
eccbytes = (bch*13+7)/8;
/* do not bother supporting small page devices */
if ((nsmtd->oobsize < 64) || !eccsteps) {
NS_ERR("bch not available on small page devices\n");
retval = -EINVAL;
goto error;
}
if ((eccbytes*eccsteps+2) > nsmtd->oobsize) {
NS_ERR("invalid bch value %u\n", bch);
retval = -EINVAL;
goto error;
}
chip->ecc.mode = NAND_ECC_SOFT_BCH;
chip->ecc.size = 512;
chip->ecc.bytes = eccbytes;
NS_INFO("using %u-bit/%u bytes BCH ECC\n", bch, chip->ecc.size);
}
retval = nand_scan_tail(nsmtd);
if (retval) {
NS_ERR("can't register NAND Simulator\n");
if (retval > 0)
retval = -ENXIO;
goto error;
}
if (overridesize) {
uint64_t new_size = (uint64_t)nsmtd->erasesize << overridesize;
if (new_size >> overridesize != nsmtd->erasesize) {
NS_ERR("overridesize is too big\n");
retval = -EINVAL;
goto err_exit;
}
/* N.B. This relies on nand_scan not doing anything with the size before we change it */
nsmtd->size = new_size;
chip->chipsize = new_size;
chip->chip_shift = ffs(nsmtd->erasesize) + overridesize - 1;
chip->pagemask = (chip->chipsize >> chip->page_shift) - 1;
}
if ((retval = setup_wear_reporting(nsmtd)) != 0)
goto err_exit;
if ((retval = init_nandsim(nsmtd)) != 0)
goto err_exit;
if ((retval = nand_default_bbt(nsmtd)) != 0)
goto err_exit;
if ((retval = parse_badblocks(nand, nsmtd)) != 0)
goto err_exit;
/* Register NAND partitions */
retval = mtd_device_register(nsmtd, &nand->partitions[0],
nand->nbparts);
if (retval != 0)
goto err_exit;
return 0;
err_exit:
free_nandsim(nand);
nand_release(nsmtd);
for (i = 0;i < ARRAY_SIZE(nand->partitions); ++i)
kfree(nand->partitions[i].name);
error:
kfree(nsmtd);
free_lists();
return retval;
}
module_init(ns_init_module);
/*
* Module clean-up function
*/
static void __exit ns_cleanup_module(void)
{
struct nandsim *ns = ((struct nand_chip *)nsmtd->priv)->priv;
int i;
free_nandsim(ns); /* Free nandsim private resources */
nand_release(nsmtd); /* Unregister driver */
for (i = 0;i < ARRAY_SIZE(ns->partitions); ++i)
kfree(ns->partitions[i].name);
kfree(nsmtd); /* Free other structures */
free_lists();
}
module_exit(ns_cleanup_module);
MODULE_LICENSE ("GPL");
MODULE_AUTHOR ("Artem B. Bityuckiy");
MODULE_DESCRIPTION ("The NAND flash simulator");
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.