repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
Hacker432-Y550/android_kernel_huawei_msm8916 | drivers/staging/iio/gyro/adis16260_core.c | 2158 | 11393 | /*
* ADIS16260/ADIS16265 Programmable Digital Gyroscope Sensor Driver
*
* 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 <linux/iio/buffer.h>
#include "adis16260.h"
static ssize_t adis16260_read_frequency_available(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *indio_dev = dev_to_iio_dev(dev);
struct adis16260_state *st = iio_priv(indio_dev);
if (spi_get_device_id(st->adis.spi)->driver_data)
return sprintf(buf, "%s\n", "0.129 ~ 256");
else
return sprintf(buf, "%s\n", "256 2048");
}
static ssize_t adis16260_read_frequency(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *indio_dev = dev_to_iio_dev(dev);
struct adis16260_state *st = iio_priv(indio_dev);
int ret, len = 0;
u16 t;
int sps;
ret = adis_read_reg_16(&st->adis, ADIS16260_SMPL_PRD, &t);
if (ret)
return ret;
if (spi_get_device_id(st->adis.spi)->driver_data) /* If an adis16251 */
sps = (t & ADIS16260_SMPL_PRD_TIME_BASE) ? 8 : 256;
else
sps = (t & ADIS16260_SMPL_PRD_TIME_BASE) ? 66 : 2048;
sps /= (t & ADIS16260_SMPL_PRD_DIV_MASK) + 1;
len = sprintf(buf, "%d SPS\n", sps);
return len;
}
static ssize_t adis16260_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 adis16260_state *st = iio_priv(indio_dev);
long val;
int ret;
u8 t;
ret = strict_strtol(buf, 10, &val);
if (ret)
return ret;
if (val == 0)
return -EINVAL;
mutex_lock(&indio_dev->mlock);
if (spi_get_device_id(st->adis.spi)->driver_data) {
t = (256 / val);
if (t > 0)
t--;
t &= ADIS16260_SMPL_PRD_DIV_MASK;
} else {
t = (2048 / val);
if (t > 0)
t--;
t &= ADIS16260_SMPL_PRD_DIV_MASK;
}
if ((t & ADIS16260_SMPL_PRD_DIV_MASK) >= 0x0A)
st->adis.spi->max_speed_hz = ADIS16260_SPI_SLOW;
else
st->adis.spi->max_speed_hz = ADIS16260_SPI_FAST;
ret = adis_write_reg_8(&st->adis,
ADIS16260_SMPL_PRD,
t);
mutex_unlock(&indio_dev->mlock);
return ret ? ret : len;
}
/* Power down the device */
static int adis16260_stop_device(struct iio_dev *indio_dev)
{
struct adis16260_state *st = iio_priv(indio_dev);
int ret;
u16 val = ADIS16260_SLP_CNT_POWER_OFF;
ret = adis_write_reg_16(&st->adis, ADIS16260_SLP_CNT, val);
if (ret)
dev_err(&indio_dev->dev, "problem with turning device off: SLP_CNT");
return ret;
}
static IIO_DEV_ATTR_SAMP_FREQ(S_IWUSR | S_IRUGO,
adis16260_read_frequency,
adis16260_write_frequency);
static IIO_DEVICE_ATTR(sampling_frequency_available,
S_IRUGO, adis16260_read_frequency_available, NULL, 0);
#define ADIS16260_GYRO_CHANNEL_SET(axis, mod) \
struct iio_chan_spec adis16260_channels_##axis[] = { \
ADIS_GYRO_CHAN(mod, ADIS16260_GYRO_OUT, ADIS16260_SCAN_GYRO, \
BIT(IIO_CHAN_INFO_CALIBBIAS) | \
BIT(IIO_CHAN_INFO_CALIBSCALE), 14), \
ADIS_INCLI_CHAN(mod, ADIS16260_ANGL_OUT, ADIS16260_SCAN_ANGL, 0, 14), \
ADIS_TEMP_CHAN(ADIS16260_TEMP_OUT, ADIS16260_SCAN_TEMP, 12), \
ADIS_SUPPLY_CHAN(ADIS16260_SUPPLY_OUT, ADIS16260_SCAN_SUPPLY, 12), \
ADIS_AUX_ADC_CHAN(ADIS16260_AUX_ADC, ADIS16260_SCAN_AUX_ADC, 12), \
IIO_CHAN_SOFT_TIMESTAMP(5), \
}
static const ADIS16260_GYRO_CHANNEL_SET(x, X);
static const ADIS16260_GYRO_CHANNEL_SET(y, Y);
static const ADIS16260_GYRO_CHANNEL_SET(z, Z);
static const u8 adis16260_addresses[][2] = {
[ADIS16260_SCAN_GYRO] = { ADIS16260_GYRO_OFF, ADIS16260_GYRO_SCALE },
};
static int adis16260_read_raw(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan,
int *val, int *val2,
long mask)
{
struct adis16260_state *st = iio_priv(indio_dev);
int ret;
int bits;
u8 addr;
s16 val16;
switch (mask) {
case IIO_CHAN_INFO_RAW:
return adis_single_conversion(indio_dev, chan,
ADIS16260_ERROR_ACTIVE, val);
case IIO_CHAN_INFO_SCALE:
switch (chan->type) {
case IIO_ANGL_VEL:
*val = 0;
if (spi_get_device_id(st->adis.spi)->driver_data) {
/* 0.01832 degree / sec */
*val2 = IIO_DEGREE_TO_RAD(18320);
} else {
/* 0.07326 degree / sec */
*val2 = IIO_DEGREE_TO_RAD(73260);
}
return IIO_VAL_INT_PLUS_MICRO;
case IIO_VOLTAGE:
if (chan->channel == 0) {
*val = 1;
*val2 = 831500; /* 1.8315 mV */
} else {
*val = 0;
*val2 = 610500; /* 610.5 uV */
}
return IIO_VAL_INT_PLUS_MICRO;
case IIO_TEMP:
*val = 145;
*val2 = 300000; /* 0.1453 C */
return IIO_VAL_INT_PLUS_MICRO;
default:
return -EINVAL;
}
break;
case IIO_CHAN_INFO_OFFSET:
*val = 250000 / 1453; /* 25 C = 0x00 */
return IIO_VAL_INT;
case IIO_CHAN_INFO_CALIBBIAS:
switch (chan->type) {
case IIO_ANGL_VEL:
bits = 12;
break;
default:
return -EINVAL;
}
mutex_lock(&indio_dev->mlock);
addr = adis16260_addresses[chan->scan_index][0];
ret = adis_read_reg_16(&st->adis, addr, &val16);
if (ret) {
mutex_unlock(&indio_dev->mlock);
return ret;
}
val16 &= (1 << bits) - 1;
val16 = (s16)(val16 << (16 - bits)) >> (16 - bits);
*val = val16;
mutex_unlock(&indio_dev->mlock);
return IIO_VAL_INT;
case IIO_CHAN_INFO_CALIBSCALE:
switch (chan->type) {
case IIO_ANGL_VEL:
bits = 12;
break;
default:
return -EINVAL;
}
mutex_lock(&indio_dev->mlock);
addr = adis16260_addresses[chan->scan_index][1];
ret = adis_read_reg_16(&st->adis, addr, &val16);
if (ret) {
mutex_unlock(&indio_dev->mlock);
return ret;
}
*val = (1 << bits) - 1;
mutex_unlock(&indio_dev->mlock);
return IIO_VAL_INT;
}
return -EINVAL;
}
static int adis16260_write_raw(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan,
int val,
int val2,
long mask)
{
struct adis16260_state *st = iio_priv(indio_dev);
int bits = 12;
s16 val16;
u8 addr;
switch (mask) {
case IIO_CHAN_INFO_CALIBBIAS:
val16 = val & ((1 << bits) - 1);
addr = adis16260_addresses[chan->scan_index][0];
return adis_write_reg_16(&st->adis, addr, val16);
case IIO_CHAN_INFO_CALIBSCALE:
val16 = val & ((1 << bits) - 1);
addr = adis16260_addresses[chan->scan_index][1];
return adis_write_reg_16(&st->adis, addr, val16);
}
return -EINVAL;
}
static struct attribute *adis16260_attributes[] = {
&iio_dev_attr_sampling_frequency.dev_attr.attr,
&iio_dev_attr_sampling_frequency_available.dev_attr.attr,
NULL
};
static const struct attribute_group adis16260_attribute_group = {
.attrs = adis16260_attributes,
};
static const struct iio_info adis16260_info = {
.attrs = &adis16260_attribute_group,
.read_raw = &adis16260_read_raw,
.write_raw = &adis16260_write_raw,
.update_scan_mode = adis_update_scan_mode,
.driver_module = THIS_MODULE,
};
static const char * const adis1620_status_error_msgs[] = {
[ADIS16260_DIAG_STAT_FLASH_CHK_BIT] = "Flash checksum error",
[ADIS16260_DIAG_STAT_SELF_TEST_BIT] = "Self test error",
[ADIS16260_DIAG_STAT_OVERFLOW_BIT] = "Sensor overrange",
[ADIS16260_DIAG_STAT_SPI_FAIL_BIT] = "SPI failure",
[ADIS16260_DIAG_STAT_FLASH_UPT_BIT] = "Flash update failed",
[ADIS16260_DIAG_STAT_POWER_HIGH_BIT] = "Power supply above 5.25",
[ADIS16260_DIAG_STAT_POWER_LOW_BIT] = "Power supply below 4.75",
};
static const struct adis_data adis16260_data = {
.write_delay = 30,
.read_delay = 30,
.msc_ctrl_reg = ADIS16260_MSC_CTRL,
.glob_cmd_reg = ADIS16260_GLOB_CMD,
.diag_stat_reg = ADIS16260_DIAG_STAT,
.self_test_mask = ADIS16260_MSC_CTRL_MEM_TEST,
.startup_delay = ADIS16260_STARTUP_DELAY,
.status_error_msgs = adis1620_status_error_msgs,
.status_error_mask = BIT(ADIS16260_DIAG_STAT_FLASH_CHK_BIT) |
BIT(ADIS16260_DIAG_STAT_SELF_TEST_BIT) |
BIT(ADIS16260_DIAG_STAT_OVERFLOW_BIT) |
BIT(ADIS16260_DIAG_STAT_SPI_FAIL_BIT) |
BIT(ADIS16260_DIAG_STAT_FLASH_UPT_BIT) |
BIT(ADIS16260_DIAG_STAT_POWER_HIGH_BIT) |
BIT(ADIS16260_DIAG_STAT_POWER_LOW_BIT),
};
static int adis16260_probe(struct spi_device *spi)
{
int ret;
struct adis16260_platform_data *pd = spi->dev.platform_data;
struct adis16260_state *st;
struct iio_dev *indio_dev;
/* setup the industrialio driver allocated elements */
indio_dev = iio_device_alloc(sizeof(*st));
if (indio_dev == NULL) {
ret = -ENOMEM;
goto error_ret;
}
st = iio_priv(indio_dev);
if (pd)
st->negate = pd->negate;
/* this is only used for removal purposes */
spi_set_drvdata(spi, indio_dev);
indio_dev->name = spi_get_device_id(spi)->name;
indio_dev->dev.parent = &spi->dev;
indio_dev->info = &adis16260_info;
indio_dev->num_channels
= ARRAY_SIZE(adis16260_channels_x);
if (pd && pd->direction)
switch (pd->direction) {
case 'x':
indio_dev->channels = adis16260_channels_x;
break;
case 'y':
indio_dev->channels = adis16260_channels_y;
break;
case 'z':
indio_dev->channels = adis16260_channels_z;
break;
default:
return -EINVAL;
}
else
indio_dev->channels = adis16260_channels_x;
indio_dev->num_channels = ARRAY_SIZE(adis16260_channels_x);
indio_dev->modes = INDIO_DIRECT_MODE;
ret = adis_init(&st->adis, indio_dev, spi, &adis16260_data);
if (ret)
goto error_free_dev;
ret = adis_setup_buffer_and_trigger(&st->adis, indio_dev, NULL);
if (ret)
goto error_free_dev;
if (indio_dev->buffer) {
/* Set default scan mode */
iio_scan_mask_set(indio_dev, indio_dev->buffer,
ADIS16260_SCAN_SUPPLY);
iio_scan_mask_set(indio_dev, indio_dev->buffer,
ADIS16260_SCAN_GYRO);
iio_scan_mask_set(indio_dev, indio_dev->buffer,
ADIS16260_SCAN_AUX_ADC);
iio_scan_mask_set(indio_dev, indio_dev->buffer,
ADIS16260_SCAN_TEMP);
iio_scan_mask_set(indio_dev, indio_dev->buffer,
ADIS16260_SCAN_ANGL);
}
/* Get the device into a sane initial state */
ret = adis_initial_startup(&st->adis);
if (ret)
goto error_cleanup_buffer_trigger;
ret = iio_device_register(indio_dev);
if (ret)
goto error_cleanup_buffer_trigger;
return 0;
error_cleanup_buffer_trigger:
adis_cleanup_buffer_and_trigger(&st->adis, indio_dev);
error_free_dev:
iio_device_free(indio_dev);
error_ret:
return ret;
}
static int adis16260_remove(struct spi_device *spi)
{
struct iio_dev *indio_dev = spi_get_drvdata(spi);
struct adis16260_state *st = iio_priv(indio_dev);
iio_device_unregister(indio_dev);
adis16260_stop_device(indio_dev);
adis_cleanup_buffer_and_trigger(&st->adis, indio_dev);
iio_device_free(indio_dev);
return 0;
}
/*
* These parts do not need to be differentiated until someone adds
* support for the on chip filtering.
*/
static const struct spi_device_id adis16260_id[] = {
{"adis16260", 0},
{"adis16265", 0},
{"adis16250", 0},
{"adis16255", 0},
{"adis16251", 1},
{}
};
MODULE_DEVICE_TABLE(spi, adis16260_id);
static struct spi_driver adis16260_driver = {
.driver = {
.name = "adis16260",
.owner = THIS_MODULE,
},
.probe = adis16260_probe,
.remove = adis16260_remove,
.id_table = adis16260_id,
};
module_spi_driver(adis16260_driver);
MODULE_AUTHOR("Barry Song <21cnbao@gmail.com>");
MODULE_DESCRIPTION("Analog Devices ADIS16260/5 Digital Gyroscope Sensor");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
rickyzhang82/linux-odroid-u2 | net/netfilter/ipset/ip_set_hash_ipport.c | 2414 | 13160 | /* Copyright (C) 2003-2011 Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/* Kernel module implementing an IP set type: the hash:ip,port type */
#include <linux/jhash.h>
#include <linux/module.h>
#include <linux/ip.h>
#include <linux/skbuff.h>
#include <linux/errno.h>
#include <linux/random.h>
#include <net/ip.h>
#include <net/ipv6.h>
#include <net/netlink.h>
#include <net/tcp.h>
#include <linux/netfilter.h>
#include <linux/netfilter/ipset/pfxlen.h>
#include <linux/netfilter/ipset/ip_set.h>
#include <linux/netfilter/ipset/ip_set_timeout.h>
#include <linux/netfilter/ipset/ip_set_getport.h>
#include <linux/netfilter/ipset/ip_set_hash.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>");
MODULE_DESCRIPTION("hash:ip,port type of IP sets");
MODULE_ALIAS("ip_set_hash:ip,port");
/* Type specific function prefix */
#define TYPE hash_ipport
static bool
hash_ipport_same_set(const struct ip_set *a, const struct ip_set *b);
#define hash_ipport4_same_set hash_ipport_same_set
#define hash_ipport6_same_set hash_ipport_same_set
/* The type variant functions: IPv4 */
/* Member elements without timeout */
struct hash_ipport4_elem {
__be32 ip;
__be16 port;
u8 proto;
u8 padding;
};
/* Member elements with timeout support */
struct hash_ipport4_telem {
__be32 ip;
__be16 port;
u8 proto;
u8 padding;
unsigned long timeout;
};
static inline bool
hash_ipport4_data_equal(const struct hash_ipport4_elem *ip1,
const struct hash_ipport4_elem *ip2)
{
return ip1->ip == ip2->ip &&
ip1->port == ip2->port &&
ip1->proto == ip2->proto;
}
static inline bool
hash_ipport4_data_isnull(const struct hash_ipport4_elem *elem)
{
return elem->proto == 0;
}
static inline void
hash_ipport4_data_copy(struct hash_ipport4_elem *dst,
const struct hash_ipport4_elem *src)
{
dst->ip = src->ip;
dst->port = src->port;
dst->proto = src->proto;
}
static inline void
hash_ipport4_data_zero_out(struct hash_ipport4_elem *elem)
{
elem->proto = 0;
}
static bool
hash_ipport4_data_list(struct sk_buff *skb,
const struct hash_ipport4_elem *data)
{
NLA_PUT_IPADDR4(skb, IPSET_ATTR_IP, data->ip);
NLA_PUT_NET16(skb, IPSET_ATTR_PORT, data->port);
NLA_PUT_U8(skb, IPSET_ATTR_PROTO, data->proto);
return 0;
nla_put_failure:
return 1;
}
static bool
hash_ipport4_data_tlist(struct sk_buff *skb,
const struct hash_ipport4_elem *data)
{
const struct hash_ipport4_telem *tdata =
(const struct hash_ipport4_telem *)data;
NLA_PUT_IPADDR4(skb, IPSET_ATTR_IP, tdata->ip);
NLA_PUT_NET16(skb, IPSET_ATTR_PORT, tdata->port);
NLA_PUT_U8(skb, IPSET_ATTR_PROTO, data->proto);
NLA_PUT_NET32(skb, IPSET_ATTR_TIMEOUT,
htonl(ip_set_timeout_get(tdata->timeout)));
return 0;
nla_put_failure:
return 1;
}
#define PF 4
#define HOST_MASK 32
#include <linux/netfilter/ipset/ip_set_ahash.h>
static int
hash_ipport4_kadt(struct ip_set *set, const struct sk_buff *skb,
enum ipset_adt adt, u8 pf, u8 dim, u8 flags)
{
const struct ip_set_hash *h = set->data;
ipset_adtfn adtfn = set->variant->adt[adt];
struct hash_ipport4_elem data = { };
if (!ip_set_get_ip4_port(skb, flags & IPSET_DIM_TWO_SRC,
&data.port, &data.proto))
return -EINVAL;
ip4addrptr(skb, flags & IPSET_DIM_ONE_SRC, &data.ip);
return adtfn(set, &data, h->timeout);
}
static int
hash_ipport4_uadt(struct ip_set *set, struct nlattr *tb[],
enum ipset_adt adt, u32 *lineno, u32 flags)
{
const struct ip_set_hash *h = set->data;
ipset_adtfn adtfn = set->variant->adt[adt];
struct hash_ipport4_elem data = { };
u32 ip, ip_to, p, port, port_to;
u32 timeout = h->timeout;
bool with_ports = false;
int ret;
if (unlikely(!tb[IPSET_ATTR_IP] ||
!ip_set_attr_netorder(tb, IPSET_ATTR_PORT) ||
!ip_set_optattr_netorder(tb, IPSET_ATTR_PORT_TO) ||
!ip_set_optattr_netorder(tb, IPSET_ATTR_TIMEOUT)))
return -IPSET_ERR_PROTOCOL;
if (tb[IPSET_ATTR_LINENO])
*lineno = nla_get_u32(tb[IPSET_ATTR_LINENO]);
ret = ip_set_get_ipaddr4(tb[IPSET_ATTR_IP], &data.ip);
if (ret)
return ret;
if (tb[IPSET_ATTR_PORT])
data.port = nla_get_be16(tb[IPSET_ATTR_PORT]);
else
return -IPSET_ERR_PROTOCOL;
if (tb[IPSET_ATTR_PROTO]) {
data.proto = nla_get_u8(tb[IPSET_ATTR_PROTO]);
with_ports = ip_set_proto_with_ports(data.proto);
if (data.proto == 0)
return -IPSET_ERR_INVALID_PROTO;
} else
return -IPSET_ERR_MISSING_PROTO;
if (!(with_ports || data.proto == IPPROTO_ICMP))
data.port = 0;
if (tb[IPSET_ATTR_TIMEOUT]) {
if (!with_timeout(h->timeout))
return -IPSET_ERR_TIMEOUT;
timeout = ip_set_timeout_uget(tb[IPSET_ATTR_TIMEOUT]);
}
if (adt == IPSET_TEST ||
!(tb[IPSET_ATTR_IP_TO] || tb[IPSET_ATTR_CIDR] ||
tb[IPSET_ATTR_PORT_TO])) {
ret = adtfn(set, &data, timeout);
return ip_set_eexist(ret, flags) ? 0 : ret;
}
ip = ntohl(data.ip);
if (tb[IPSET_ATTR_IP_TO]) {
ret = ip_set_get_hostipaddr4(tb[IPSET_ATTR_IP_TO], &ip_to);
if (ret)
return ret;
if (ip > ip_to)
swap(ip, ip_to);
} else if (tb[IPSET_ATTR_CIDR]) {
u8 cidr = nla_get_u8(tb[IPSET_ATTR_CIDR]);
if (cidr > 32)
return -IPSET_ERR_INVALID_CIDR;
ip &= ip_set_hostmask(cidr);
ip_to = ip | ~ip_set_hostmask(cidr);
} else
ip_to = ip;
port_to = port = ntohs(data.port);
if (with_ports && tb[IPSET_ATTR_PORT_TO]) {
port_to = ip_set_get_h16(tb[IPSET_ATTR_PORT_TO]);
if (port > port_to)
swap(port, port_to);
}
for (; !before(ip_to, ip); ip++)
for (p = port; p <= port_to; p++) {
data.ip = htonl(ip);
data.port = htons(p);
ret = adtfn(set, &data, timeout);
if (ret && !ip_set_eexist(ret, flags))
return ret;
else
ret = 0;
}
return ret;
}
static bool
hash_ipport_same_set(const struct ip_set *a, const struct ip_set *b)
{
const struct ip_set_hash *x = a->data;
const struct ip_set_hash *y = b->data;
/* Resizing changes htable_bits, so we ignore it */
return x->maxelem == y->maxelem &&
x->timeout == y->timeout;
}
/* The type variant functions: IPv6 */
struct hash_ipport6_elem {
union nf_inet_addr ip;
__be16 port;
u8 proto;
u8 padding;
};
struct hash_ipport6_telem {
union nf_inet_addr ip;
__be16 port;
u8 proto;
u8 padding;
unsigned long timeout;
};
static inline bool
hash_ipport6_data_equal(const struct hash_ipport6_elem *ip1,
const struct hash_ipport6_elem *ip2)
{
return ipv6_addr_cmp(&ip1->ip.in6, &ip2->ip.in6) == 0 &&
ip1->port == ip2->port &&
ip1->proto == ip2->proto;
}
static inline bool
hash_ipport6_data_isnull(const struct hash_ipport6_elem *elem)
{
return elem->proto == 0;
}
static inline void
hash_ipport6_data_copy(struct hash_ipport6_elem *dst,
const struct hash_ipport6_elem *src)
{
memcpy(dst, src, sizeof(*dst));
}
static inline void
hash_ipport6_data_zero_out(struct hash_ipport6_elem *elem)
{
elem->proto = 0;
}
static bool
hash_ipport6_data_list(struct sk_buff *skb,
const struct hash_ipport6_elem *data)
{
NLA_PUT_IPADDR6(skb, IPSET_ATTR_IP, &data->ip);
NLA_PUT_NET16(skb, IPSET_ATTR_PORT, data->port);
NLA_PUT_U8(skb, IPSET_ATTR_PROTO, data->proto);
return 0;
nla_put_failure:
return 1;
}
static bool
hash_ipport6_data_tlist(struct sk_buff *skb,
const struct hash_ipport6_elem *data)
{
const struct hash_ipport6_telem *e =
(const struct hash_ipport6_telem *)data;
NLA_PUT_IPADDR6(skb, IPSET_ATTR_IP, &e->ip);
NLA_PUT_NET16(skb, IPSET_ATTR_PORT, data->port);
NLA_PUT_U8(skb, IPSET_ATTR_PROTO, data->proto);
NLA_PUT_NET32(skb, IPSET_ATTR_TIMEOUT,
htonl(ip_set_timeout_get(e->timeout)));
return 0;
nla_put_failure:
return 1;
}
#undef PF
#undef HOST_MASK
#define PF 6
#define HOST_MASK 128
#include <linux/netfilter/ipset/ip_set_ahash.h>
static int
hash_ipport6_kadt(struct ip_set *set, const struct sk_buff *skb,
enum ipset_adt adt, u8 pf, u8 dim, u8 flags)
{
const struct ip_set_hash *h = set->data;
ipset_adtfn adtfn = set->variant->adt[adt];
struct hash_ipport6_elem data = { };
if (!ip_set_get_ip6_port(skb, flags & IPSET_DIM_TWO_SRC,
&data.port, &data.proto))
return -EINVAL;
ip6addrptr(skb, flags & IPSET_DIM_ONE_SRC, &data.ip.in6);
return adtfn(set, &data, h->timeout);
}
static int
hash_ipport6_uadt(struct ip_set *set, struct nlattr *tb[],
enum ipset_adt adt, u32 *lineno, u32 flags)
{
const struct ip_set_hash *h = set->data;
ipset_adtfn adtfn = set->variant->adt[adt];
struct hash_ipport6_elem data = { };
u32 port, port_to;
u32 timeout = h->timeout;
bool with_ports = false;
int ret;
if (unlikely(!tb[IPSET_ATTR_IP] ||
!ip_set_attr_netorder(tb, IPSET_ATTR_PORT) ||
!ip_set_optattr_netorder(tb, IPSET_ATTR_PORT_TO) ||
!ip_set_optattr_netorder(tb, IPSET_ATTR_TIMEOUT) ||
tb[IPSET_ATTR_IP_TO] ||
tb[IPSET_ATTR_CIDR]))
return -IPSET_ERR_PROTOCOL;
if (tb[IPSET_ATTR_LINENO])
*lineno = nla_get_u32(tb[IPSET_ATTR_LINENO]);
ret = ip_set_get_ipaddr6(tb[IPSET_ATTR_IP], &data.ip);
if (ret)
return ret;
if (tb[IPSET_ATTR_PORT])
data.port = nla_get_be16(tb[IPSET_ATTR_PORT]);
else
return -IPSET_ERR_PROTOCOL;
if (tb[IPSET_ATTR_PROTO]) {
data.proto = nla_get_u8(tb[IPSET_ATTR_PROTO]);
with_ports = ip_set_proto_with_ports(data.proto);
if (data.proto == 0)
return -IPSET_ERR_INVALID_PROTO;
} else
return -IPSET_ERR_MISSING_PROTO;
if (!(with_ports || data.proto == IPPROTO_ICMPV6))
data.port = 0;
if (tb[IPSET_ATTR_TIMEOUT]) {
if (!with_timeout(h->timeout))
return -IPSET_ERR_TIMEOUT;
timeout = ip_set_timeout_uget(tb[IPSET_ATTR_TIMEOUT]);
}
if (adt == IPSET_TEST || !with_ports || !tb[IPSET_ATTR_PORT_TO]) {
ret = adtfn(set, &data, timeout);
return ip_set_eexist(ret, flags) ? 0 : ret;
}
port = ntohs(data.port);
port_to = ip_set_get_h16(tb[IPSET_ATTR_PORT_TO]);
if (port > port_to)
swap(port, port_to);
for (; port <= port_to; port++) {
data.port = htons(port);
ret = adtfn(set, &data, timeout);
if (ret && !ip_set_eexist(ret, flags))
return ret;
else
ret = 0;
}
return ret;
}
/* Create hash:ip type of sets */
static int
hash_ipport_create(struct ip_set *set, struct nlattr *tb[], u32 flags)
{
struct ip_set_hash *h;
u32 hashsize = IPSET_DEFAULT_HASHSIZE, maxelem = IPSET_DEFAULT_MAXELEM;
u8 hbits;
if (!(set->family == AF_INET || set->family == AF_INET6))
return -IPSET_ERR_INVALID_FAMILY;
if (unlikely(!ip_set_optattr_netorder(tb, IPSET_ATTR_HASHSIZE) ||
!ip_set_optattr_netorder(tb, IPSET_ATTR_MAXELEM) ||
!ip_set_optattr_netorder(tb, IPSET_ATTR_TIMEOUT)))
return -IPSET_ERR_PROTOCOL;
if (tb[IPSET_ATTR_HASHSIZE]) {
hashsize = ip_set_get_h32(tb[IPSET_ATTR_HASHSIZE]);
if (hashsize < IPSET_MIMINAL_HASHSIZE)
hashsize = IPSET_MIMINAL_HASHSIZE;
}
if (tb[IPSET_ATTR_MAXELEM])
maxelem = ip_set_get_h32(tb[IPSET_ATTR_MAXELEM]);
h = kzalloc(sizeof(*h), GFP_KERNEL);
if (!h)
return -ENOMEM;
h->maxelem = maxelem;
get_random_bytes(&h->initval, sizeof(h->initval));
h->timeout = IPSET_NO_TIMEOUT;
hbits = htable_bits(hashsize);
h->table = ip_set_alloc(
sizeof(struct htable)
+ jhash_size(hbits) * sizeof(struct hbucket));
if (!h->table) {
kfree(h);
return -ENOMEM;
}
h->table->htable_bits = hbits;
set->data = h;
if (tb[IPSET_ATTR_TIMEOUT]) {
h->timeout = ip_set_timeout_uget(tb[IPSET_ATTR_TIMEOUT]);
set->variant = set->family == AF_INET
? &hash_ipport4_tvariant : &hash_ipport6_tvariant;
if (set->family == AF_INET)
hash_ipport4_gc_init(set);
else
hash_ipport6_gc_init(set);
} else {
set->variant = set->family == AF_INET
? &hash_ipport4_variant : &hash_ipport6_variant;
}
pr_debug("create %s hashsize %u (%u) maxelem %u: %p(%p)\n",
set->name, jhash_size(h->table->htable_bits),
h->table->htable_bits, h->maxelem, set->data, h->table);
return 0;
}
static struct ip_set_type hash_ipport_type __read_mostly = {
.name = "hash:ip,port",
.protocol = IPSET_PROTOCOL,
.features = IPSET_TYPE_IP | IPSET_TYPE_PORT,
.dimension = IPSET_DIM_TWO,
.family = AF_UNSPEC,
.revision = 1,
.create = hash_ipport_create,
.create_policy = {
[IPSET_ATTR_HASHSIZE] = { .type = NLA_U32 },
[IPSET_ATTR_MAXELEM] = { .type = NLA_U32 },
[IPSET_ATTR_PROBES] = { .type = NLA_U8 },
[IPSET_ATTR_RESIZE] = { .type = NLA_U8 },
[IPSET_ATTR_PROTO] = { .type = NLA_U8 },
[IPSET_ATTR_TIMEOUT] = { .type = NLA_U32 },
},
.adt_policy = {
[IPSET_ATTR_IP] = { .type = NLA_NESTED },
[IPSET_ATTR_IP_TO] = { .type = NLA_NESTED },
[IPSET_ATTR_PORT] = { .type = NLA_U16 },
[IPSET_ATTR_PORT_TO] = { .type = NLA_U16 },
[IPSET_ATTR_CIDR] = { .type = NLA_U8 },
[IPSET_ATTR_PROTO] = { .type = NLA_U8 },
[IPSET_ATTR_TIMEOUT] = { .type = NLA_U32 },
[IPSET_ATTR_LINENO] = { .type = NLA_U32 },
},
.me = THIS_MODULE,
};
static int __init
hash_ipport_init(void)
{
return ip_set_type_register(&hash_ipport_type);
}
static void __exit
hash_ipport_fini(void)
{
ip_set_type_unregister(&hash_ipport_type);
}
module_init(hash_ipport_init);
module_exit(hash_ipport_fini);
| gpl-2.0 |
AndroidGX/SimpleGX-MM-6.0_H815 | net/mac80211/rc80211_minstrel_ht_debugfs.c | 2414 | 3936 | /*
* Copyright (C) 2010 Felix Fietkau <nbd@openwrt.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/netdevice.h>
#include <linux/types.h>
#include <linux/skbuff.h>
#include <linux/debugfs.h>
#include <linux/ieee80211.h>
#include <linux/export.h>
#include <net/mac80211.h>
#include "rc80211_minstrel.h"
#include "rc80211_minstrel_ht.h"
static char *
minstrel_ht_stats_dump(struct minstrel_ht_sta *mi, int i, char *p)
{
unsigned int max_mcs = MINSTREL_MAX_STREAMS * MINSTREL_STREAM_GROUPS;
const struct mcs_group *mg;
unsigned int j, tp, prob, eprob;
char htmode = '2';
char gimode = 'L';
if (!mi->groups[i].supported)
return p;
mg = &minstrel_mcs_groups[i];
if (mg->flags & IEEE80211_TX_RC_40_MHZ_WIDTH)
htmode = '4';
if (mg->flags & IEEE80211_TX_RC_SHORT_GI)
gimode = 'S';
for (j = 0; j < MCS_GROUP_RATES; j++) {
struct minstrel_rate_stats *mr = &mi->groups[i].rates[j];
static const int bitrates[4] = { 10, 20, 55, 110 };
int idx = i * MCS_GROUP_RATES + j;
if (!(mi->groups[i].supported & BIT(j)))
continue;
if (i == max_mcs)
p += sprintf(p, "CCK/%cP ", j < 4 ? 'L' : 'S');
else
p += sprintf(p, "HT%c0/%cGI ", htmode, gimode);
*(p++) = (idx == mi->max_tp_rate) ? 'T' : ' ';
*(p++) = (idx == mi->max_tp_rate2) ? 't' : ' ';
*(p++) = (idx == mi->max_prob_rate) ? 'P' : ' ';
if (i == max_mcs) {
int r = bitrates[j % 4];
p += sprintf(p, " %2u.%1uM", r / 10, r % 10);
} else {
p += sprintf(p, " MCS%-2u", (mg->streams - 1) *
MCS_GROUP_RATES + j);
}
tp = mr->cur_tp / 10;
prob = MINSTREL_TRUNC(mr->cur_prob * 1000);
eprob = MINSTREL_TRUNC(mr->probability * 1000);
p += sprintf(p, " %6u.%1u %6u.%1u %6u.%1u "
"%3u %3u(%3u) %8llu %8llu\n",
tp / 10, tp % 10,
eprob / 10, eprob % 10,
prob / 10, prob % 10,
mr->retry_count,
mr->last_success,
mr->last_attempts,
(unsigned long long)mr->succ_hist,
(unsigned long long)mr->att_hist);
}
return p;
}
static int
minstrel_ht_stats_open(struct inode *inode, struct file *file)
{
struct minstrel_ht_sta_priv *msp = inode->i_private;
struct minstrel_ht_sta *mi = &msp->ht;
struct minstrel_debugfs_info *ms;
unsigned int i;
unsigned int max_mcs = MINSTREL_MAX_STREAMS * MINSTREL_STREAM_GROUPS;
char *p;
int ret;
if (!msp->is_ht) {
inode->i_private = &msp->legacy;
ret = minstrel_stats_open(inode, file);
inode->i_private = msp;
return ret;
}
ms = kmalloc(sizeof(*ms) + 8192, GFP_KERNEL);
if (!ms)
return -ENOMEM;
file->private_data = ms;
p = ms->buf;
p += sprintf(p, "type rate throughput ewma prob this prob "
"retry this succ/attempt success attempts\n");
p = minstrel_ht_stats_dump(mi, max_mcs, p);
for (i = 0; i < max_mcs; i++)
p = minstrel_ht_stats_dump(mi, i, p);
p += sprintf(p, "\nTotal packet count:: ideal %d "
"lookaround %d\n",
max(0, (int) mi->total_packets - (int) mi->sample_packets),
mi->sample_packets);
p += sprintf(p, "Average A-MPDU length: %d.%d\n",
MINSTREL_TRUNC(mi->avg_ampdu_len),
MINSTREL_TRUNC(mi->avg_ampdu_len * 10) % 10);
ms->len = p - ms->buf;
return nonseekable_open(inode, file);
}
static const struct file_operations minstrel_ht_stat_fops = {
.owner = THIS_MODULE,
.open = minstrel_ht_stats_open,
.read = minstrel_stats_read,
.release = minstrel_stats_release,
.llseek = no_llseek,
};
void
minstrel_ht_add_sta_debugfs(void *priv, void *priv_sta, struct dentry *dir)
{
struct minstrel_ht_sta_priv *msp = priv_sta;
msp->dbg_stats = debugfs_create_file("rc_stats", S_IRUGO, dir, msp,
&minstrel_ht_stat_fops);
}
void
minstrel_ht_remove_sta_debugfs(void *priv, void *priv_sta)
{
struct minstrel_ht_sta_priv *msp = priv_sta;
debugfs_remove(msp->dbg_stats);
}
| gpl-2.0 |
android-legacy/kernel | drivers/net/wireless/ti/wlcore/sdio.c | 2670 | 10303 | /*
* This file is part of wl1271
*
* Copyright (C) 2009-2010 Nokia Corporation
*
* Contact: Luciano Coelho <luciano.coelho@nokia.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <linux/irq.h>
#include <linux/module.h>
#include <linux/vmalloc.h>
#include <linux/platform_device.h>
#include <linux/mmc/sdio.h>
#include <linux/mmc/sdio_func.h>
#include <linux/mmc/sdio_ids.h>
#include <linux/mmc/card.h>
#include <linux/mmc/host.h>
#include <linux/gpio.h>
#include <linux/wl12xx.h>
#include <linux/pm_runtime.h>
#include <linux/printk.h>
#include "wlcore.h"
#include "wl12xx_80211.h"
#include "io.h"
#ifndef SDIO_VENDOR_ID_TI
#define SDIO_VENDOR_ID_TI 0x0097
#endif
#ifndef SDIO_DEVICE_ID_TI_WL1271
#define SDIO_DEVICE_ID_TI_WL1271 0x4076
#endif
static bool dump = false;
struct wl12xx_sdio_glue {
struct device *dev;
struct platform_device *core;
};
static const struct sdio_device_id wl1271_devices[] = {
{ SDIO_DEVICE(SDIO_VENDOR_ID_TI, SDIO_DEVICE_ID_TI_WL1271) },
{}
};
MODULE_DEVICE_TABLE(sdio, wl1271_devices);
static void wl1271_sdio_set_block_size(struct device *child,
unsigned int blksz)
{
struct wl12xx_sdio_glue *glue = dev_get_drvdata(child->parent);
struct sdio_func *func = dev_to_sdio_func(glue->dev);
sdio_claim_host(func);
sdio_set_block_size(func, blksz);
sdio_release_host(func);
}
static int __must_check wl12xx_sdio_raw_read(struct device *child, int addr,
void *buf, size_t len, bool fixed)
{
int ret;
struct wl12xx_sdio_glue *glue = dev_get_drvdata(child->parent);
struct sdio_func *func = dev_to_sdio_func(glue->dev);
sdio_claim_host(func);
if (unlikely(dump)) {
printk(KERN_DEBUG "wlcore_sdio: READ from 0x%04x\n", addr);
print_hex_dump(KERN_DEBUG, "wlcore_sdio: READ ",
DUMP_PREFIX_OFFSET, 16, 1,
buf, len, false);
}
if (unlikely(addr == HW_ACCESS_ELP_CTRL_REG)) {
((u8 *)buf)[0] = sdio_f0_readb(func, addr, &ret);
dev_dbg(child->parent, "sdio read 52 addr 0x%x, byte 0x%02x\n",
addr, ((u8 *)buf)[0]);
} else {
if (fixed)
ret = sdio_readsb(func, buf, addr, len);
else
ret = sdio_memcpy_fromio(func, buf, addr, len);
dev_dbg(child->parent, "sdio read 53 addr 0x%x, %zu bytes\n",
addr, len);
}
sdio_release_host(func);
if (WARN_ON(ret))
dev_err(child->parent, "sdio read failed (%d)\n", ret);
return ret;
}
static int __must_check wl12xx_sdio_raw_write(struct device *child, int addr,
void *buf, size_t len, bool fixed)
{
int ret;
struct wl12xx_sdio_glue *glue = dev_get_drvdata(child->parent);
struct sdio_func *func = dev_to_sdio_func(glue->dev);
sdio_claim_host(func);
if (unlikely(dump)) {
printk(KERN_DEBUG "wlcore_sdio: WRITE to 0x%04x\n", addr);
print_hex_dump(KERN_DEBUG, "wlcore_sdio: WRITE ",
DUMP_PREFIX_OFFSET, 16, 1,
buf, len, false);
}
if (unlikely(addr == HW_ACCESS_ELP_CTRL_REG)) {
sdio_f0_writeb(func, ((u8 *)buf)[0], addr, &ret);
dev_dbg(child->parent, "sdio write 52 addr 0x%x, byte 0x%02x\n",
addr, ((u8 *)buf)[0]);
} else {
dev_dbg(child->parent, "sdio write 53 addr 0x%x, %zu bytes\n",
addr, len);
if (fixed)
ret = sdio_writesb(func, addr, buf, len);
else
ret = sdio_memcpy_toio(func, addr, buf, len);
}
sdio_release_host(func);
if (WARN_ON(ret))
dev_err(child->parent, "sdio write failed (%d)\n", ret);
return ret;
}
static int wl12xx_sdio_power_on(struct wl12xx_sdio_glue *glue)
{
int ret;
struct sdio_func *func = dev_to_sdio_func(glue->dev);
struct mmc_card *card = func->card;
ret = pm_runtime_get_sync(&card->dev);
if (ret) {
/*
* Runtime PM might be temporarily disabled, or the device
* might have a positive reference counter. Make sure it is
* really powered on.
*/
ret = mmc_power_restore_host(card->host);
if (ret < 0) {
pm_runtime_put_sync(&card->dev);
goto out;
}
}
sdio_claim_host(func);
sdio_enable_func(func);
sdio_release_host(func);
out:
return ret;
}
static int wl12xx_sdio_power_off(struct wl12xx_sdio_glue *glue)
{
int ret;
struct sdio_func *func = dev_to_sdio_func(glue->dev);
struct mmc_card *card = func->card;
sdio_claim_host(func);
sdio_disable_func(func);
sdio_release_host(func);
/* Power off the card manually in case it wasn't powered off above */
ret = mmc_power_save_host(card->host);
if (ret < 0)
goto out;
/* Let runtime PM know the card is powered off */
pm_runtime_put_sync(&card->dev);
out:
return ret;
}
static int wl12xx_sdio_set_power(struct device *child, bool enable)
{
struct wl12xx_sdio_glue *glue = dev_get_drvdata(child->parent);
if (enable)
return wl12xx_sdio_power_on(glue);
else
return wl12xx_sdio_power_off(glue);
}
static struct wl1271_if_operations sdio_ops = {
.read = wl12xx_sdio_raw_read,
.write = wl12xx_sdio_raw_write,
.power = wl12xx_sdio_set_power,
.set_block_size = wl1271_sdio_set_block_size,
};
static int wl1271_probe(struct sdio_func *func,
const struct sdio_device_id *id)
{
struct wlcore_platdev_data *pdev_data;
struct wl12xx_sdio_glue *glue;
struct resource res[1];
mmc_pm_flag_t mmcflags;
int ret = -ENOMEM;
const char *chip_family;
/* We are only able to handle the wlan function */
if (func->num != 0x02)
return -ENODEV;
pdev_data = kzalloc(sizeof(*pdev_data), GFP_KERNEL);
if (!pdev_data)
goto out;
pdev_data->if_ops = &sdio_ops;
glue = kzalloc(sizeof(*glue), GFP_KERNEL);
if (!glue) {
dev_err(&func->dev, "can't allocate glue\n");
goto out_free_pdev_data;
}
glue->dev = &func->dev;
/* Grab access to FN0 for ELP reg. */
func->card->quirks |= MMC_QUIRK_LENIENT_FN0;
/* Use block mode for transferring over one block size of data */
func->card->quirks |= MMC_QUIRK_BLKSZ_FOR_BYTE_MODE;
pdev_data->pdata = wl12xx_get_platform_data();
if (IS_ERR(pdev_data->pdata)) {
ret = PTR_ERR(pdev_data->pdata);
dev_err(glue->dev, "missing wlan platform data: %d\n", ret);
goto out_free_glue;
}
/* if sdio can keep power while host is suspended, enable wow */
mmcflags = sdio_get_host_pm_caps(func);
dev_dbg(glue->dev, "sdio PM caps = 0x%x\n", mmcflags);
if (mmcflags & MMC_PM_KEEP_POWER)
pdev_data->pdata->pwr_in_suspend = true;
sdio_set_drvdata(func, glue);
/* Tell PM core that we don't need the card to be powered now */
pm_runtime_put_noidle(&func->dev);
/*
* Due to a hardware bug, we can't differentiate wl18xx from
* wl12xx, because both report the same device ID. The only
* way to differentiate is by checking the SDIO revision,
* which is 3.00 on the wl18xx chips.
*/
if (func->card->cccr.sdio_vsn == SDIO_SDIO_REV_3_00)
chip_family = "wl18xx";
else
chip_family = "wl12xx";
glue->core = platform_device_alloc(chip_family, PLATFORM_DEVID_AUTO);
if (!glue->core) {
dev_err(glue->dev, "can't allocate platform_device");
ret = -ENOMEM;
goto out_free_glue;
}
glue->core->dev.parent = &func->dev;
memset(res, 0x00, sizeof(res));
res[0].start = pdev_data->pdata->irq;
res[0].flags = IORESOURCE_IRQ;
res[0].name = "irq";
ret = platform_device_add_resources(glue->core, res, ARRAY_SIZE(res));
if (ret) {
dev_err(glue->dev, "can't add resources\n");
goto out_dev_put;
}
ret = platform_device_add_data(glue->core, pdev_data,
sizeof(*pdev_data));
if (ret) {
dev_err(glue->dev, "can't add platform data\n");
goto out_dev_put;
}
ret = platform_device_add(glue->core);
if (ret) {
dev_err(glue->dev, "can't add platform device\n");
goto out_dev_put;
}
return 0;
out_dev_put:
platform_device_put(glue->core);
out_free_glue:
kfree(glue);
out_free_pdev_data:
kfree(pdev_data);
out:
return ret;
}
static void wl1271_remove(struct sdio_func *func)
{
struct wl12xx_sdio_glue *glue = sdio_get_drvdata(func);
/* Undo decrement done above in wl1271_probe */
pm_runtime_get_noresume(&func->dev);
platform_device_unregister(glue->core);
kfree(glue);
}
#ifdef CONFIG_PM
static int wl1271_suspend(struct device *dev)
{
/* Tell MMC/SDIO core it's OK to power down the card
* (if it isn't already), but not to remove it completely */
struct sdio_func *func = dev_to_sdio_func(dev);
struct wl12xx_sdio_glue *glue = sdio_get_drvdata(func);
struct wl1271 *wl = platform_get_drvdata(glue->core);
mmc_pm_flag_t sdio_flags;
int ret = 0;
dev_dbg(dev, "wl1271 suspend. wow_enabled: %d\n",
wl->wow_enabled);
/* check whether sdio should keep power */
if (wl->wow_enabled) {
sdio_flags = sdio_get_host_pm_caps(func);
if (!(sdio_flags & MMC_PM_KEEP_POWER)) {
dev_err(dev, "can't keep power while host "
"is suspended\n");
ret = -EINVAL;
goto out;
}
/* keep power while host suspended */
ret = sdio_set_host_pm_flags(func, MMC_PM_KEEP_POWER);
if (ret) {
dev_err(dev, "error while trying to keep power\n");
goto out;
}
}
out:
return ret;
}
static int wl1271_resume(struct device *dev)
{
dev_dbg(dev, "wl1271 resume\n");
return 0;
}
static const struct dev_pm_ops wl1271_sdio_pm_ops = {
.suspend = wl1271_suspend,
.resume = wl1271_resume,
};
#endif
static struct sdio_driver wl1271_sdio_driver = {
.name = "wl1271_sdio",
.id_table = wl1271_devices,
.probe = wl1271_probe,
.remove = wl1271_remove,
#ifdef CONFIG_PM
.drv = {
.pm = &wl1271_sdio_pm_ops,
},
#endif
};
static int __init wl1271_init(void)
{
return sdio_register_driver(&wl1271_sdio_driver);
}
static void __exit wl1271_exit(void)
{
sdio_unregister_driver(&wl1271_sdio_driver);
}
module_init(wl1271_init);
module_exit(wl1271_exit);
module_param(dump, bool, S_IRUSR | S_IWUSR);
MODULE_PARM_DESC(dump, "Enable sdio read/write dumps.");
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Luciano Coelho <coelho@ti.com>");
MODULE_AUTHOR("Juuso Oikarinen <juuso.oikarinen@nokia.com>");
| gpl-2.0 |
jetonbacaj/SomeKernel_G920P_PB6 | drivers/char/agp/generic.c | 2670 | 37483 | /*
* AGPGART driver.
* Copyright (C) 2004 Silicon Graphics, Inc.
* Copyright (C) 2002-2005 Dave Jones.
* Copyright (C) 1999 Jeff Hartmann.
* Copyright (C) 1999 Precision Insight, Inc.
* Copyright (C) 1999 Xi Graphics, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* JEFF HARTMANN, OR ANY OTHER CONTRIBUTORS 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.
*
* TODO:
* - Allocate more than order 0 pages to avoid too much linear map splitting.
*/
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/pagemap.h>
#include <linux/miscdevice.h>
#include <linux/pm.h>
#include <linux/agp_backend.h>
#include <linux/vmalloc.h>
#include <linux/dma-mapping.h>
#include <linux/mm.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <asm/io.h>
#include <asm/cacheflush.h>
#include <asm/pgtable.h>
#include "agp.h"
__u32 *agp_gatt_table;
int agp_memory_reserved;
/*
* Needed by the Nforce GART driver for the time being. Would be
* nice to do this some other way instead of needing this export.
*/
EXPORT_SYMBOL_GPL(agp_memory_reserved);
/*
* Generic routines for handling agp_memory structures -
* They use the basic page allocation routines to do the brunt of the work.
*/
void agp_free_key(int key)
{
if (key < 0)
return;
if (key < MAXKEY)
clear_bit(key, agp_bridge->key_list);
}
EXPORT_SYMBOL(agp_free_key);
static int agp_get_key(void)
{
int bit;
bit = find_first_zero_bit(agp_bridge->key_list, MAXKEY);
if (bit < MAXKEY) {
set_bit(bit, agp_bridge->key_list);
return bit;
}
return -1;
}
/*
* Use kmalloc if possible for the page list. Otherwise fall back to
* vmalloc. This speeds things up and also saves memory for small AGP
* regions.
*/
void agp_alloc_page_array(size_t size, struct agp_memory *mem)
{
mem->pages = NULL;
if (size <= 2*PAGE_SIZE)
mem->pages = kmalloc(size, GFP_KERNEL | __GFP_NOWARN);
if (mem->pages == NULL) {
mem->pages = vmalloc(size);
}
}
EXPORT_SYMBOL(agp_alloc_page_array);
void agp_free_page_array(struct agp_memory *mem)
{
if (is_vmalloc_addr(mem->pages)) {
vfree(mem->pages);
} else {
kfree(mem->pages);
}
}
EXPORT_SYMBOL(agp_free_page_array);
static struct agp_memory *agp_create_user_memory(unsigned long num_agp_pages)
{
struct agp_memory *new;
unsigned long alloc_size = num_agp_pages*sizeof(struct page *);
if (INT_MAX/sizeof(struct page *) < num_agp_pages)
return NULL;
new = kzalloc(sizeof(struct agp_memory), GFP_KERNEL);
if (new == NULL)
return NULL;
new->key = agp_get_key();
if (new->key < 0) {
kfree(new);
return NULL;
}
agp_alloc_page_array(alloc_size, new);
if (new->pages == NULL) {
agp_free_key(new->key);
kfree(new);
return NULL;
}
new->num_scratch_pages = 0;
return new;
}
struct agp_memory *agp_create_memory(int scratch_pages)
{
struct agp_memory *new;
new = kzalloc(sizeof(struct agp_memory), GFP_KERNEL);
if (new == NULL)
return NULL;
new->key = agp_get_key();
if (new->key < 0) {
kfree(new);
return NULL;
}
agp_alloc_page_array(PAGE_SIZE * scratch_pages, new);
if (new->pages == NULL) {
agp_free_key(new->key);
kfree(new);
return NULL;
}
new->num_scratch_pages = scratch_pages;
new->type = AGP_NORMAL_MEMORY;
return new;
}
EXPORT_SYMBOL(agp_create_memory);
/**
* agp_free_memory - free memory associated with an agp_memory pointer.
*
* @curr: agp_memory pointer to be freed.
*
* It is the only function that can be called when the backend is not owned
* by the caller. (So it can free memory on client death.)
*/
void agp_free_memory(struct agp_memory *curr)
{
size_t i;
if (curr == NULL)
return;
if (curr->is_bound)
agp_unbind_memory(curr);
if (curr->type >= AGP_USER_TYPES) {
agp_generic_free_by_type(curr);
return;
}
if (curr->type != 0) {
curr->bridge->driver->free_by_type(curr);
return;
}
if (curr->page_count != 0) {
if (curr->bridge->driver->agp_destroy_pages) {
curr->bridge->driver->agp_destroy_pages(curr);
} else {
for (i = 0; i < curr->page_count; i++) {
curr->bridge->driver->agp_destroy_page(
curr->pages[i],
AGP_PAGE_DESTROY_UNMAP);
}
for (i = 0; i < curr->page_count; i++) {
curr->bridge->driver->agp_destroy_page(
curr->pages[i],
AGP_PAGE_DESTROY_FREE);
}
}
}
agp_free_key(curr->key);
agp_free_page_array(curr);
kfree(curr);
}
EXPORT_SYMBOL(agp_free_memory);
#define ENTRIES_PER_PAGE (PAGE_SIZE / sizeof(unsigned long))
/**
* agp_allocate_memory - allocate a group of pages of a certain type.
*
* @page_count: size_t argument of the number of pages
* @type: u32 argument of the type of memory to be allocated.
*
* Every agp bridge device will allow you to allocate AGP_NORMAL_MEMORY which
* maps to physical ram. Any other type is device dependent.
*
* It returns NULL whenever memory is unavailable.
*/
struct agp_memory *agp_allocate_memory(struct agp_bridge_data *bridge,
size_t page_count, u32 type)
{
int scratch_pages;
struct agp_memory *new;
size_t i;
int cur_memory;
if (!bridge)
return NULL;
cur_memory = atomic_read(&bridge->current_memory_agp);
if ((cur_memory + page_count > bridge->max_memory_agp) ||
(cur_memory + page_count < page_count))
return NULL;
if (type >= AGP_USER_TYPES) {
new = agp_generic_alloc_user(page_count, type);
if (new)
new->bridge = bridge;
return new;
}
if (type != 0) {
new = bridge->driver->alloc_by_type(page_count, type);
if (new)
new->bridge = bridge;
return new;
}
scratch_pages = (page_count + ENTRIES_PER_PAGE - 1) / ENTRIES_PER_PAGE;
new = agp_create_memory(scratch_pages);
if (new == NULL)
return NULL;
if (bridge->driver->agp_alloc_pages) {
if (bridge->driver->agp_alloc_pages(bridge, new, page_count)) {
agp_free_memory(new);
return NULL;
}
new->bridge = bridge;
return new;
}
for (i = 0; i < page_count; i++) {
struct page *page = bridge->driver->agp_alloc_page(bridge);
if (page == NULL) {
agp_free_memory(new);
return NULL;
}
new->pages[i] = page;
new->page_count++;
}
new->bridge = bridge;
return new;
}
EXPORT_SYMBOL(agp_allocate_memory);
/* End - Generic routines for handling agp_memory structures */
static int agp_return_size(void)
{
int current_size;
void *temp;
temp = agp_bridge->current_size;
switch (agp_bridge->driver->size_type) {
case U8_APER_SIZE:
current_size = A_SIZE_8(temp)->size;
break;
case U16_APER_SIZE:
current_size = A_SIZE_16(temp)->size;
break;
case U32_APER_SIZE:
current_size = A_SIZE_32(temp)->size;
break;
case LVL2_APER_SIZE:
current_size = A_SIZE_LVL2(temp)->size;
break;
case FIXED_APER_SIZE:
current_size = A_SIZE_FIX(temp)->size;
break;
default:
current_size = 0;
break;
}
current_size -= (agp_memory_reserved / (1024*1024));
if (current_size <0)
current_size = 0;
return current_size;
}
int agp_num_entries(void)
{
int num_entries;
void *temp;
temp = agp_bridge->current_size;
switch (agp_bridge->driver->size_type) {
case U8_APER_SIZE:
num_entries = A_SIZE_8(temp)->num_entries;
break;
case U16_APER_SIZE:
num_entries = A_SIZE_16(temp)->num_entries;
break;
case U32_APER_SIZE:
num_entries = A_SIZE_32(temp)->num_entries;
break;
case LVL2_APER_SIZE:
num_entries = A_SIZE_LVL2(temp)->num_entries;
break;
case FIXED_APER_SIZE:
num_entries = A_SIZE_FIX(temp)->num_entries;
break;
default:
num_entries = 0;
break;
}
num_entries -= agp_memory_reserved>>PAGE_SHIFT;
if (num_entries<0)
num_entries = 0;
return num_entries;
}
EXPORT_SYMBOL_GPL(agp_num_entries);
/**
* agp_copy_info - copy bridge state information
*
* @info: agp_kern_info pointer. The caller should insure that this pointer is valid.
*
* This function copies information about the agp bridge device and the state of
* the agp backend into an agp_kern_info pointer.
*/
int agp_copy_info(struct agp_bridge_data *bridge, struct agp_kern_info *info)
{
memset(info, 0, sizeof(struct agp_kern_info));
if (!bridge) {
info->chipset = NOT_SUPPORTED;
return -EIO;
}
info->version.major = bridge->version->major;
info->version.minor = bridge->version->minor;
info->chipset = SUPPORTED;
info->device = bridge->dev;
if (bridge->mode & AGPSTAT_MODE_3_0)
info->mode = bridge->mode & ~AGP3_RESERVED_MASK;
else
info->mode = bridge->mode & ~AGP2_RESERVED_MASK;
info->aper_base = bridge->gart_bus_addr;
info->aper_size = agp_return_size();
info->max_memory = bridge->max_memory_agp;
info->current_memory = atomic_read(&bridge->current_memory_agp);
info->cant_use_aperture = bridge->driver->cant_use_aperture;
info->vm_ops = bridge->vm_ops;
info->page_mask = ~0UL;
return 0;
}
EXPORT_SYMBOL(agp_copy_info);
/* End - Routine to copy over information structure */
/*
* Routines for handling swapping of agp_memory into the GATT -
* These routines take agp_memory and insert them into the GATT.
* They call device specific routines to actually write to the GATT.
*/
/**
* agp_bind_memory - Bind an agp_memory structure into the GATT.
*
* @curr: agp_memory pointer
* @pg_start: an offset into the graphics aperture translation table
*
* It returns -EINVAL if the pointer == NULL.
* It returns -EBUSY if the area of the table requested is already in use.
*/
int agp_bind_memory(struct agp_memory *curr, off_t pg_start)
{
int ret_val;
if (curr == NULL)
return -EINVAL;
if (curr->is_bound) {
printk(KERN_INFO PFX "memory %p is already bound!\n", curr);
return -EINVAL;
}
if (!curr->is_flushed) {
curr->bridge->driver->cache_flush();
curr->is_flushed = true;
}
ret_val = curr->bridge->driver->insert_memory(curr, pg_start, curr->type);
if (ret_val != 0)
return ret_val;
curr->is_bound = true;
curr->pg_start = pg_start;
spin_lock(&agp_bridge->mapped_lock);
list_add(&curr->mapped_list, &agp_bridge->mapped_list);
spin_unlock(&agp_bridge->mapped_lock);
return 0;
}
EXPORT_SYMBOL(agp_bind_memory);
/**
* agp_unbind_memory - Removes an agp_memory structure from the GATT
*
* @curr: agp_memory pointer to be removed from the GATT.
*
* It returns -EINVAL if this piece of agp_memory is not currently bound to
* the graphics aperture translation table or if the agp_memory pointer == NULL
*/
int agp_unbind_memory(struct agp_memory *curr)
{
int ret_val;
if (curr == NULL)
return -EINVAL;
if (!curr->is_bound) {
printk(KERN_INFO PFX "memory %p was not bound!\n", curr);
return -EINVAL;
}
ret_val = curr->bridge->driver->remove_memory(curr, curr->pg_start, curr->type);
if (ret_val != 0)
return ret_val;
curr->is_bound = false;
curr->pg_start = 0;
spin_lock(&curr->bridge->mapped_lock);
list_del(&curr->mapped_list);
spin_unlock(&curr->bridge->mapped_lock);
return 0;
}
EXPORT_SYMBOL(agp_unbind_memory);
/* End - Routines for handling swapping of agp_memory into the GATT */
/* Generic Agp routines - Start */
static void agp_v2_parse_one(u32 *requested_mode, u32 *bridge_agpstat, u32 *vga_agpstat)
{
u32 tmp;
if (*requested_mode & AGP2_RESERVED_MASK) {
printk(KERN_INFO PFX "reserved bits set (%x) in mode 0x%x. Fixed.\n",
*requested_mode & AGP2_RESERVED_MASK, *requested_mode);
*requested_mode &= ~AGP2_RESERVED_MASK;
}
/*
* Some dumb bridges are programmed to disobey the AGP2 spec.
* This is likely a BIOS misprogramming rather than poweron default, or
* it would be a lot more common.
* https://bugs.freedesktop.org/show_bug.cgi?id=8816
* AGPv2 spec 6.1.9 states:
* The RATE field indicates the data transfer rates supported by this
* device. A.G.P. devices must report all that apply.
* Fix them up as best we can.
*/
switch (*bridge_agpstat & 7) {
case 4:
*bridge_agpstat |= (AGPSTAT2_2X | AGPSTAT2_1X);
printk(KERN_INFO PFX "BIOS bug. AGP bridge claims to only support x4 rate. "
"Fixing up support for x2 & x1\n");
break;
case 2:
*bridge_agpstat |= AGPSTAT2_1X;
printk(KERN_INFO PFX "BIOS bug. AGP bridge claims to only support x2 rate. "
"Fixing up support for x1\n");
break;
default:
break;
}
/* Check the speed bits make sense. Only one should be set. */
tmp = *requested_mode & 7;
switch (tmp) {
case 0:
printk(KERN_INFO PFX "%s tried to set rate=x0. Setting to x1 mode.\n", current->comm);
*requested_mode |= AGPSTAT2_1X;
break;
case 1:
case 2:
break;
case 3:
*requested_mode &= ~(AGPSTAT2_1X); /* rate=2 */
break;
case 4:
break;
case 5:
case 6:
case 7:
*requested_mode &= ~(AGPSTAT2_1X|AGPSTAT2_2X); /* rate=4*/
break;
}
/* disable SBA if it's not supported */
if (!((*bridge_agpstat & AGPSTAT_SBA) && (*vga_agpstat & AGPSTAT_SBA) && (*requested_mode & AGPSTAT_SBA)))
*bridge_agpstat &= ~AGPSTAT_SBA;
/* Set rate */
if (!((*bridge_agpstat & AGPSTAT2_4X) && (*vga_agpstat & AGPSTAT2_4X) && (*requested_mode & AGPSTAT2_4X)))
*bridge_agpstat &= ~AGPSTAT2_4X;
if (!((*bridge_agpstat & AGPSTAT2_2X) && (*vga_agpstat & AGPSTAT2_2X) && (*requested_mode & AGPSTAT2_2X)))
*bridge_agpstat &= ~AGPSTAT2_2X;
if (!((*bridge_agpstat & AGPSTAT2_1X) && (*vga_agpstat & AGPSTAT2_1X) && (*requested_mode & AGPSTAT2_1X)))
*bridge_agpstat &= ~AGPSTAT2_1X;
/* Now we know what mode it should be, clear out the unwanted bits. */
if (*bridge_agpstat & AGPSTAT2_4X)
*bridge_agpstat &= ~(AGPSTAT2_1X | AGPSTAT2_2X); /* 4X */
if (*bridge_agpstat & AGPSTAT2_2X)
*bridge_agpstat &= ~(AGPSTAT2_1X | AGPSTAT2_4X); /* 2X */
if (*bridge_agpstat & AGPSTAT2_1X)
*bridge_agpstat &= ~(AGPSTAT2_2X | AGPSTAT2_4X); /* 1X */
/* Apply any errata. */
if (agp_bridge->flags & AGP_ERRATA_FASTWRITES)
*bridge_agpstat &= ~AGPSTAT_FW;
if (agp_bridge->flags & AGP_ERRATA_SBA)
*bridge_agpstat &= ~AGPSTAT_SBA;
if (agp_bridge->flags & AGP_ERRATA_1X) {
*bridge_agpstat &= ~(AGPSTAT2_2X | AGPSTAT2_4X);
*bridge_agpstat |= AGPSTAT2_1X;
}
/* If we've dropped down to 1X, disable fast writes. */
if (*bridge_agpstat & AGPSTAT2_1X)
*bridge_agpstat &= ~AGPSTAT_FW;
}
/*
* requested_mode = Mode requested by (typically) X.
* bridge_agpstat = PCI_AGP_STATUS from agp bridge.
* vga_agpstat = PCI_AGP_STATUS from graphic card.
*/
static void agp_v3_parse_one(u32 *requested_mode, u32 *bridge_agpstat, u32 *vga_agpstat)
{
u32 origbridge=*bridge_agpstat, origvga=*vga_agpstat;
u32 tmp;
if (*requested_mode & AGP3_RESERVED_MASK) {
printk(KERN_INFO PFX "reserved bits set (%x) in mode 0x%x. Fixed.\n",
*requested_mode & AGP3_RESERVED_MASK, *requested_mode);
*requested_mode &= ~AGP3_RESERVED_MASK;
}
/* Check the speed bits make sense. */
tmp = *requested_mode & 7;
if (tmp == 0) {
printk(KERN_INFO PFX "%s tried to set rate=x0. Setting to AGP3 x4 mode.\n", current->comm);
*requested_mode |= AGPSTAT3_4X;
}
if (tmp >= 3) {
printk(KERN_INFO PFX "%s tried to set rate=x%d. Setting to AGP3 x8 mode.\n", current->comm, tmp * 4);
*requested_mode = (*requested_mode & ~7) | AGPSTAT3_8X;
}
/* ARQSZ - Set the value to the maximum one.
* Don't allow the mode register to override values. */
*bridge_agpstat = ((*bridge_agpstat & ~AGPSTAT_ARQSZ) |
max_t(u32,(*bridge_agpstat & AGPSTAT_ARQSZ),(*vga_agpstat & AGPSTAT_ARQSZ)));
/* Calibration cycle.
* Don't allow the mode register to override values. */
*bridge_agpstat = ((*bridge_agpstat & ~AGPSTAT_CAL_MASK) |
min_t(u32,(*bridge_agpstat & AGPSTAT_CAL_MASK),(*vga_agpstat & AGPSTAT_CAL_MASK)));
/* SBA *must* be supported for AGP v3 */
*bridge_agpstat |= AGPSTAT_SBA;
/*
* Set speed.
* Check for invalid speeds. This can happen when applications
* written before the AGP 3.0 standard pass AGP2.x modes to AGP3 hardware
*/
if (*requested_mode & AGPSTAT_MODE_3_0) {
/*
* Caller hasn't a clue what it is doing. Bridge is in 3.0 mode,
* have been passed a 3.0 mode, but with 2.x speed bits set.
* AGP2.x 4x -> AGP3.0 4x.
*/
if (*requested_mode & AGPSTAT2_4X) {
printk(KERN_INFO PFX "%s passes broken AGP3 flags (%x). Fixed.\n",
current->comm, *requested_mode);
*requested_mode &= ~AGPSTAT2_4X;
*requested_mode |= AGPSTAT3_4X;
}
} else {
/*
* The caller doesn't know what they are doing. We are in 3.0 mode,
* but have been passed an AGP 2.x mode.
* Convert AGP 1x,2x,4x -> AGP 3.0 4x.
*/
printk(KERN_INFO PFX "%s passes broken AGP2 flags (%x) in AGP3 mode. Fixed.\n",
current->comm, *requested_mode);
*requested_mode &= ~(AGPSTAT2_4X | AGPSTAT2_2X | AGPSTAT2_1X);
*requested_mode |= AGPSTAT3_4X;
}
if (*requested_mode & AGPSTAT3_8X) {
if (!(*bridge_agpstat & AGPSTAT3_8X)) {
*bridge_agpstat &= ~(AGPSTAT3_8X | AGPSTAT3_RSVD);
*bridge_agpstat |= AGPSTAT3_4X;
printk(KERN_INFO PFX "%s requested AGPx8 but bridge not capable.\n", current->comm);
return;
}
if (!(*vga_agpstat & AGPSTAT3_8X)) {
*bridge_agpstat &= ~(AGPSTAT3_8X | AGPSTAT3_RSVD);
*bridge_agpstat |= AGPSTAT3_4X;
printk(KERN_INFO PFX "%s requested AGPx8 but graphic card not capable.\n", current->comm);
return;
}
/* All set, bridge & device can do AGP x8*/
*bridge_agpstat &= ~(AGPSTAT3_4X | AGPSTAT3_RSVD);
goto done;
} else if (*requested_mode & AGPSTAT3_4X) {
*bridge_agpstat &= ~(AGPSTAT3_8X | AGPSTAT3_RSVD);
*bridge_agpstat |= AGPSTAT3_4X;
goto done;
} else {
/*
* If we didn't specify an AGP mode, we see if both
* the graphics card, and the bridge can do x8, and use if so.
* If not, we fall back to x4 mode.
*/
if ((*bridge_agpstat & AGPSTAT3_8X) && (*vga_agpstat & AGPSTAT3_8X)) {
printk(KERN_INFO PFX "No AGP mode specified. Setting to highest mode "
"supported by bridge & card (x8).\n");
*bridge_agpstat &= ~(AGPSTAT3_4X | AGPSTAT3_RSVD);
*vga_agpstat &= ~(AGPSTAT3_4X | AGPSTAT3_RSVD);
} else {
printk(KERN_INFO PFX "Fell back to AGPx4 mode because ");
if (!(*bridge_agpstat & AGPSTAT3_8X)) {
printk(KERN_INFO PFX "bridge couldn't do x8. bridge_agpstat:%x (orig=%x)\n",
*bridge_agpstat, origbridge);
*bridge_agpstat &= ~(AGPSTAT3_8X | AGPSTAT3_RSVD);
*bridge_agpstat |= AGPSTAT3_4X;
}
if (!(*vga_agpstat & AGPSTAT3_8X)) {
printk(KERN_INFO PFX "graphics card couldn't do x8. vga_agpstat:%x (orig=%x)\n",
*vga_agpstat, origvga);
*vga_agpstat &= ~(AGPSTAT3_8X | AGPSTAT3_RSVD);
*vga_agpstat |= AGPSTAT3_4X;
}
}
}
done:
/* Apply any errata. */
if (agp_bridge->flags & AGP_ERRATA_FASTWRITES)
*bridge_agpstat &= ~AGPSTAT_FW;
if (agp_bridge->flags & AGP_ERRATA_SBA)
*bridge_agpstat &= ~AGPSTAT_SBA;
if (agp_bridge->flags & AGP_ERRATA_1X) {
*bridge_agpstat &= ~(AGPSTAT2_2X | AGPSTAT2_4X);
*bridge_agpstat |= AGPSTAT2_1X;
}
}
/**
* agp_collect_device_status - determine correct agp_cmd from various agp_stat's
* @bridge: an agp_bridge_data struct allocated for the AGP host bridge.
* @requested_mode: requested agp_stat from userspace (Typically from X)
* @bridge_agpstat: current agp_stat from AGP bridge.
*
* This function will hunt for an AGP graphics card, and try to match
* the requested mode to the capabilities of both the bridge and the card.
*/
u32 agp_collect_device_status(struct agp_bridge_data *bridge, u32 requested_mode, u32 bridge_agpstat)
{
struct pci_dev *device = NULL;
u32 vga_agpstat;
u8 cap_ptr;
for (;;) {
device = pci_get_class(PCI_CLASS_DISPLAY_VGA << 8, device);
if (!device) {
printk(KERN_INFO PFX "Couldn't find an AGP VGA controller.\n");
return 0;
}
cap_ptr = pci_find_capability(device, PCI_CAP_ID_AGP);
if (cap_ptr)
break;
}
/*
* Ok, here we have a AGP device. Disable impossible
* settings, and adjust the readqueue to the minimum.
*/
pci_read_config_dword(device, cap_ptr+PCI_AGP_STATUS, &vga_agpstat);
/* adjust RQ depth */
bridge_agpstat = ((bridge_agpstat & ~AGPSTAT_RQ_DEPTH) |
min_t(u32, (requested_mode & AGPSTAT_RQ_DEPTH),
min_t(u32, (bridge_agpstat & AGPSTAT_RQ_DEPTH), (vga_agpstat & AGPSTAT_RQ_DEPTH))));
/* disable FW if it's not supported */
if (!((bridge_agpstat & AGPSTAT_FW) &&
(vga_agpstat & AGPSTAT_FW) &&
(requested_mode & AGPSTAT_FW)))
bridge_agpstat &= ~AGPSTAT_FW;
/* Check to see if we are operating in 3.0 mode */
if (agp_bridge->mode & AGPSTAT_MODE_3_0)
agp_v3_parse_one(&requested_mode, &bridge_agpstat, &vga_agpstat);
else
agp_v2_parse_one(&requested_mode, &bridge_agpstat, &vga_agpstat);
pci_dev_put(device);
return bridge_agpstat;
}
EXPORT_SYMBOL(agp_collect_device_status);
void agp_device_command(u32 bridge_agpstat, bool agp_v3)
{
struct pci_dev *device = NULL;
int mode;
mode = bridge_agpstat & 0x7;
if (agp_v3)
mode *= 4;
for_each_pci_dev(device) {
u8 agp = pci_find_capability(device, PCI_CAP_ID_AGP);
if (!agp)
continue;
dev_info(&device->dev, "putting AGP V%d device into %dx mode\n",
agp_v3 ? 3 : 2, mode);
pci_write_config_dword(device, agp + PCI_AGP_COMMAND, bridge_agpstat);
}
}
EXPORT_SYMBOL(agp_device_command);
void get_agp_version(struct agp_bridge_data *bridge)
{
u32 ncapid;
/* Exit early if already set by errata workarounds. */
if (bridge->major_version != 0)
return;
pci_read_config_dword(bridge->dev, bridge->capndx, &ncapid);
bridge->major_version = (ncapid >> AGP_MAJOR_VERSION_SHIFT) & 0xf;
bridge->minor_version = (ncapid >> AGP_MINOR_VERSION_SHIFT) & 0xf;
}
EXPORT_SYMBOL(get_agp_version);
void agp_generic_enable(struct agp_bridge_data *bridge, u32 requested_mode)
{
u32 bridge_agpstat, temp;
get_agp_version(agp_bridge);
dev_info(&agp_bridge->dev->dev, "AGP %d.%d bridge\n",
agp_bridge->major_version, agp_bridge->minor_version);
pci_read_config_dword(agp_bridge->dev,
agp_bridge->capndx + PCI_AGP_STATUS, &bridge_agpstat);
bridge_agpstat = agp_collect_device_status(agp_bridge, requested_mode, bridge_agpstat);
if (bridge_agpstat == 0)
/* Something bad happened. FIXME: Return error code? */
return;
bridge_agpstat |= AGPSTAT_AGP_ENABLE;
/* Do AGP version specific frobbing. */
if (bridge->major_version >= 3) {
if (bridge->mode & AGPSTAT_MODE_3_0) {
/* If we have 3.5, we can do the isoch stuff. */
if (bridge->minor_version >= 5)
agp_3_5_enable(bridge);
agp_device_command(bridge_agpstat, true);
return;
} else {
/* Disable calibration cycle in RX91<1> when not in AGP3.0 mode of operation.*/
bridge_agpstat &= ~(7<<10) ;
pci_read_config_dword(bridge->dev,
bridge->capndx+AGPCTRL, &temp);
temp |= (1<<9);
pci_write_config_dword(bridge->dev,
bridge->capndx+AGPCTRL, temp);
dev_info(&bridge->dev->dev, "bridge is in legacy mode, falling back to 2.x\n");
}
}
/* AGP v<3 */
agp_device_command(bridge_agpstat, false);
}
EXPORT_SYMBOL(agp_generic_enable);
int agp_generic_create_gatt_table(struct agp_bridge_data *bridge)
{
char *table;
char *table_end;
int size;
int page_order;
int num_entries;
int i;
void *temp;
struct page *page;
/* The generic routines can't handle 2 level gatt's */
if (bridge->driver->size_type == LVL2_APER_SIZE)
return -EINVAL;
table = NULL;
i = bridge->aperture_size_idx;
temp = bridge->current_size;
size = page_order = num_entries = 0;
if (bridge->driver->size_type != FIXED_APER_SIZE) {
do {
switch (bridge->driver->size_type) {
case U8_APER_SIZE:
size = A_SIZE_8(temp)->size;
page_order =
A_SIZE_8(temp)->page_order;
num_entries =
A_SIZE_8(temp)->num_entries;
break;
case U16_APER_SIZE:
size = A_SIZE_16(temp)->size;
page_order = A_SIZE_16(temp)->page_order;
num_entries = A_SIZE_16(temp)->num_entries;
break;
case U32_APER_SIZE:
size = A_SIZE_32(temp)->size;
page_order = A_SIZE_32(temp)->page_order;
num_entries = A_SIZE_32(temp)->num_entries;
break;
/* This case will never really happen. */
case FIXED_APER_SIZE:
case LVL2_APER_SIZE:
default:
size = page_order = num_entries = 0;
break;
}
table = alloc_gatt_pages(page_order);
if (table == NULL) {
i++;
switch (bridge->driver->size_type) {
case U8_APER_SIZE:
bridge->current_size = A_IDX8(bridge);
break;
case U16_APER_SIZE:
bridge->current_size = A_IDX16(bridge);
break;
case U32_APER_SIZE:
bridge->current_size = A_IDX32(bridge);
break;
/* These cases will never really happen. */
case FIXED_APER_SIZE:
case LVL2_APER_SIZE:
default:
break;
}
temp = bridge->current_size;
} else {
bridge->aperture_size_idx = i;
}
} while (!table && (i < bridge->driver->num_aperture_sizes));
} else {
size = ((struct aper_size_info_fixed *) temp)->size;
page_order = ((struct aper_size_info_fixed *) temp)->page_order;
num_entries = ((struct aper_size_info_fixed *) temp)->num_entries;
table = alloc_gatt_pages(page_order);
}
if (table == NULL)
return -ENOMEM;
table_end = table + ((PAGE_SIZE * (1 << page_order)) - 1);
for (page = virt_to_page(table); page <= virt_to_page(table_end); page++)
SetPageReserved(page);
bridge->gatt_table_real = (u32 *) table;
agp_gatt_table = (void *)table;
bridge->driver->cache_flush();
#ifdef CONFIG_X86
if (set_memory_uc((unsigned long)table, 1 << page_order))
printk(KERN_WARNING "Could not set GATT table memory to UC!\n");
bridge->gatt_table = (u32 __iomem *)table;
#else
bridge->gatt_table = ioremap_nocache(virt_to_phys(table),
(PAGE_SIZE * (1 << page_order)));
bridge->driver->cache_flush();
#endif
if (bridge->gatt_table == NULL) {
for (page = virt_to_page(table); page <= virt_to_page(table_end); page++)
ClearPageReserved(page);
free_gatt_pages(table, page_order);
return -ENOMEM;
}
bridge->gatt_bus_addr = virt_to_phys(bridge->gatt_table_real);
/* AK: bogus, should encode addresses > 4GB */
for (i = 0; i < num_entries; i++) {
writel(bridge->scratch_page, bridge->gatt_table+i);
readl(bridge->gatt_table+i); /* PCI Posting. */
}
return 0;
}
EXPORT_SYMBOL(agp_generic_create_gatt_table);
int agp_generic_free_gatt_table(struct agp_bridge_data *bridge)
{
int page_order;
char *table, *table_end;
void *temp;
struct page *page;
temp = bridge->current_size;
switch (bridge->driver->size_type) {
case U8_APER_SIZE:
page_order = A_SIZE_8(temp)->page_order;
break;
case U16_APER_SIZE:
page_order = A_SIZE_16(temp)->page_order;
break;
case U32_APER_SIZE:
page_order = A_SIZE_32(temp)->page_order;
break;
case FIXED_APER_SIZE:
page_order = A_SIZE_FIX(temp)->page_order;
break;
case LVL2_APER_SIZE:
/* The generic routines can't deal with 2 level gatt's */
return -EINVAL;
default:
page_order = 0;
break;
}
/* Do not worry about freeing memory, because if this is
* called, then all agp memory is deallocated and removed
* from the table. */
#ifdef CONFIG_X86
set_memory_wb((unsigned long)bridge->gatt_table, 1 << page_order);
#else
iounmap(bridge->gatt_table);
#endif
table = (char *) bridge->gatt_table_real;
table_end = table + ((PAGE_SIZE * (1 << page_order)) - 1);
for (page = virt_to_page(table); page <= virt_to_page(table_end); page++)
ClearPageReserved(page);
free_gatt_pages(bridge->gatt_table_real, page_order);
agp_gatt_table = NULL;
bridge->gatt_table = NULL;
bridge->gatt_table_real = NULL;
bridge->gatt_bus_addr = 0;
return 0;
}
EXPORT_SYMBOL(agp_generic_free_gatt_table);
int agp_generic_insert_memory(struct agp_memory * mem, off_t pg_start, int type)
{
int num_entries;
size_t i;
off_t j;
void *temp;
struct agp_bridge_data *bridge;
int mask_type;
bridge = mem->bridge;
if (!bridge)
return -EINVAL;
if (mem->page_count == 0)
return 0;
temp = bridge->current_size;
switch (bridge->driver->size_type) {
case U8_APER_SIZE:
num_entries = A_SIZE_8(temp)->num_entries;
break;
case U16_APER_SIZE:
num_entries = A_SIZE_16(temp)->num_entries;
break;
case U32_APER_SIZE:
num_entries = A_SIZE_32(temp)->num_entries;
break;
case FIXED_APER_SIZE:
num_entries = A_SIZE_FIX(temp)->num_entries;
break;
case LVL2_APER_SIZE:
/* The generic routines can't deal with 2 level gatt's */
return -EINVAL;
default:
num_entries = 0;
break;
}
num_entries -= agp_memory_reserved/PAGE_SIZE;
if (num_entries < 0) num_entries = 0;
if (type != mem->type)
return -EINVAL;
mask_type = bridge->driver->agp_type_to_mask_type(bridge, type);
if (mask_type != 0) {
/* The generic routines know nothing of memory types */
return -EINVAL;
}
if (((pg_start + mem->page_count) > num_entries) ||
((pg_start + mem->page_count) < pg_start))
return -EINVAL;
j = pg_start;
while (j < (pg_start + mem->page_count)) {
if (!PGE_EMPTY(bridge, readl(bridge->gatt_table+j)))
return -EBUSY;
j++;
}
if (!mem->is_flushed) {
bridge->driver->cache_flush();
mem->is_flushed = true;
}
for (i = 0, j = pg_start; i < mem->page_count; i++, j++) {
writel(bridge->driver->mask_memory(bridge,
page_to_phys(mem->pages[i]),
mask_type),
bridge->gatt_table+j);
}
readl(bridge->gatt_table+j-1); /* PCI Posting. */
bridge->driver->tlb_flush(mem);
return 0;
}
EXPORT_SYMBOL(agp_generic_insert_memory);
int agp_generic_remove_memory(struct agp_memory *mem, off_t pg_start, int type)
{
size_t i;
struct agp_bridge_data *bridge;
int mask_type, num_entries;
bridge = mem->bridge;
if (!bridge)
return -EINVAL;
if (mem->page_count == 0)
return 0;
if (type != mem->type)
return -EINVAL;
num_entries = agp_num_entries();
if (((pg_start + mem->page_count) > num_entries) ||
((pg_start + mem->page_count) < pg_start))
return -EINVAL;
mask_type = bridge->driver->agp_type_to_mask_type(bridge, type);
if (mask_type != 0) {
/* The generic routines know nothing of memory types */
return -EINVAL;
}
/* AK: bogus, should encode addresses > 4GB */
for (i = pg_start; i < (mem->page_count + pg_start); i++) {
writel(bridge->scratch_page, bridge->gatt_table+i);
}
readl(bridge->gatt_table+i-1); /* PCI Posting. */
bridge->driver->tlb_flush(mem);
return 0;
}
EXPORT_SYMBOL(agp_generic_remove_memory);
struct agp_memory *agp_generic_alloc_by_type(size_t page_count, int type)
{
return NULL;
}
EXPORT_SYMBOL(agp_generic_alloc_by_type);
void agp_generic_free_by_type(struct agp_memory *curr)
{
agp_free_page_array(curr);
agp_free_key(curr->key);
kfree(curr);
}
EXPORT_SYMBOL(agp_generic_free_by_type);
struct agp_memory *agp_generic_alloc_user(size_t page_count, int type)
{
struct agp_memory *new;
int i;
int pages;
pages = (page_count + ENTRIES_PER_PAGE - 1) / ENTRIES_PER_PAGE;
new = agp_create_user_memory(page_count);
if (new == NULL)
return NULL;
for (i = 0; i < page_count; i++)
new->pages[i] = NULL;
new->page_count = 0;
new->type = type;
new->num_scratch_pages = pages;
return new;
}
EXPORT_SYMBOL(agp_generic_alloc_user);
/*
* Basic Page Allocation Routines -
* These routines handle page allocation and by default they reserve the allocated
* memory. They also handle incrementing the current_memory_agp value, Which is checked
* against a maximum value.
*/
int agp_generic_alloc_pages(struct agp_bridge_data *bridge, struct agp_memory *mem, size_t num_pages)
{
struct page * page;
int i, ret = -ENOMEM;
for (i = 0; i < num_pages; i++) {
page = alloc_page(GFP_KERNEL | GFP_DMA32 | __GFP_ZERO);
/* agp_free_memory() needs gart address */
if (page == NULL)
goto out;
#ifndef CONFIG_X86
map_page_into_agp(page);
#endif
get_page(page);
atomic_inc(&agp_bridge->current_memory_agp);
mem->pages[i] = page;
mem->page_count++;
}
#ifdef CONFIG_X86
set_pages_array_uc(mem->pages, num_pages);
#endif
ret = 0;
out:
return ret;
}
EXPORT_SYMBOL(agp_generic_alloc_pages);
struct page *agp_generic_alloc_page(struct agp_bridge_data *bridge)
{
struct page * page;
page = alloc_page(GFP_KERNEL | GFP_DMA32 | __GFP_ZERO);
if (page == NULL)
return NULL;
map_page_into_agp(page);
get_page(page);
atomic_inc(&agp_bridge->current_memory_agp);
return page;
}
EXPORT_SYMBOL(agp_generic_alloc_page);
void agp_generic_destroy_pages(struct agp_memory *mem)
{
int i;
struct page *page;
if (!mem)
return;
#ifdef CONFIG_X86
set_pages_array_wb(mem->pages, mem->page_count);
#endif
for (i = 0; i < mem->page_count; i++) {
page = mem->pages[i];
#ifndef CONFIG_X86
unmap_page_from_agp(page);
#endif
put_page(page);
__free_page(page);
atomic_dec(&agp_bridge->current_memory_agp);
mem->pages[i] = NULL;
}
}
EXPORT_SYMBOL(agp_generic_destroy_pages);
void agp_generic_destroy_page(struct page *page, int flags)
{
if (page == NULL)
return;
if (flags & AGP_PAGE_DESTROY_UNMAP)
unmap_page_from_agp(page);
if (flags & AGP_PAGE_DESTROY_FREE) {
put_page(page);
__free_page(page);
atomic_dec(&agp_bridge->current_memory_agp);
}
}
EXPORT_SYMBOL(agp_generic_destroy_page);
/* End Basic Page Allocation Routines */
/**
* agp_enable - initialise the agp point-to-point connection.
*
* @mode: agp mode register value to configure with.
*/
void agp_enable(struct agp_bridge_data *bridge, u32 mode)
{
if (!bridge)
return;
bridge->driver->agp_enable(bridge, mode);
}
EXPORT_SYMBOL(agp_enable);
/* When we remove the global variable agp_bridge from all drivers
* then agp_alloc_bridge and agp_generic_find_bridge need to be updated
*/
struct agp_bridge_data *agp_generic_find_bridge(struct pci_dev *pdev)
{
if (list_empty(&agp_bridges))
return NULL;
return agp_bridge;
}
static void ipi_handler(void *null)
{
flush_agp_cache();
}
void global_cache_flush(void)
{
if (on_each_cpu(ipi_handler, NULL, 1) != 0)
panic(PFX "timed out waiting for the other CPUs!\n");
}
EXPORT_SYMBOL(global_cache_flush);
unsigned long agp_generic_mask_memory(struct agp_bridge_data *bridge,
dma_addr_t addr, int type)
{
/* memory type is ignored in the generic routine */
if (bridge->driver->masks)
return addr | bridge->driver->masks[0].mask;
else
return addr;
}
EXPORT_SYMBOL(agp_generic_mask_memory);
int agp_generic_type_to_mask_type(struct agp_bridge_data *bridge,
int type)
{
if (type >= AGP_USER_TYPES)
return 0;
return type;
}
EXPORT_SYMBOL(agp_generic_type_to_mask_type);
/*
* These functions are implemented according to the AGPv3 spec,
* which covers implementation details that had previously been
* left open.
*/
int agp3_generic_fetch_size(void)
{
u16 temp_size;
int i;
struct aper_size_info_16 *values;
pci_read_config_word(agp_bridge->dev, agp_bridge->capndx+AGPAPSIZE, &temp_size);
values = A_SIZE_16(agp_bridge->driver->aperture_sizes);
for (i = 0; i < agp_bridge->driver->num_aperture_sizes; i++) {
if (temp_size == values[i].size_value) {
agp_bridge->previous_size =
agp_bridge->current_size = (void *) (values + i);
agp_bridge->aperture_size_idx = i;
return values[i].size;
}
}
return 0;
}
EXPORT_SYMBOL(agp3_generic_fetch_size);
void agp3_generic_tlbflush(struct agp_memory *mem)
{
u32 ctrl;
pci_read_config_dword(agp_bridge->dev, agp_bridge->capndx+AGPCTRL, &ctrl);
pci_write_config_dword(agp_bridge->dev, agp_bridge->capndx+AGPCTRL, ctrl & ~AGPCTRL_GTLBEN);
pci_write_config_dword(agp_bridge->dev, agp_bridge->capndx+AGPCTRL, ctrl);
}
EXPORT_SYMBOL(agp3_generic_tlbflush);
int agp3_generic_configure(void)
{
u32 temp;
struct aper_size_info_16 *current_size;
current_size = A_SIZE_16(agp_bridge->current_size);
pci_read_config_dword(agp_bridge->dev, AGP_APBASE, &temp);
agp_bridge->gart_bus_addr = (temp & PCI_BASE_ADDRESS_MEM_MASK);
/* set aperture size */
pci_write_config_word(agp_bridge->dev, agp_bridge->capndx+AGPAPSIZE, current_size->size_value);
/* set gart pointer */
pci_write_config_dword(agp_bridge->dev, agp_bridge->capndx+AGPGARTLO, agp_bridge->gatt_bus_addr);
/* enable aperture and GTLB */
pci_read_config_dword(agp_bridge->dev, agp_bridge->capndx+AGPCTRL, &temp);
pci_write_config_dword(agp_bridge->dev, agp_bridge->capndx+AGPCTRL, temp | AGPCTRL_APERENB | AGPCTRL_GTLBEN);
return 0;
}
EXPORT_SYMBOL(agp3_generic_configure);
void agp3_generic_cleanup(void)
{
u32 ctrl;
pci_read_config_dword(agp_bridge->dev, agp_bridge->capndx+AGPCTRL, &ctrl);
pci_write_config_dword(agp_bridge->dev, agp_bridge->capndx+AGPCTRL, ctrl & ~AGPCTRL_APERENB);
}
EXPORT_SYMBOL(agp3_generic_cleanup);
const struct aper_size_info_16 agp3_generic_sizes[AGP_GENERIC_SIZES_ENTRIES] =
{
{4096, 1048576, 10,0x000},
{2048, 524288, 9, 0x800},
{1024, 262144, 8, 0xc00},
{ 512, 131072, 7, 0xe00},
{ 256, 65536, 6, 0xf00},
{ 128, 32768, 5, 0xf20},
{ 64, 16384, 4, 0xf30},
{ 32, 8192, 3, 0xf38},
{ 16, 4096, 2, 0xf3c},
{ 8, 2048, 1, 0xf3e},
{ 4, 1024, 0, 0xf3f}
};
EXPORT_SYMBOL(agp3_generic_sizes);
| gpl-2.0 |
SystemTera/SystemTera.Server-V-3.2-Kernel | drivers/staging/tidspbridge/pmgr/cod.c | 3182 | 14323 | /*
* cod.c
*
* DSP-BIOS Bridge driver support functions for TI OMAP processors.
*
* This module implements DSP code management for the DSP/BIOS Bridge
* environment. It is mostly a thin wrapper.
*
* This module provides an interface for loading both static and
* dynamic code objects onto DSP systems.
*
* Copyright (C) 2005-2006 Texas Instruments, Inc.
*
* This package is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include <linux/types.h>
/* ----------------------------------- Host OS */
#include <dspbridge/host_os.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
/* ----------------------------------- DSP/BIOS Bridge */
#include <dspbridge/dbdefs.h>
/* ----------------------------------- Trace & Debug */
#include <dspbridge/dbc.h>
/* ----------------------------------- Platform Manager */
/* Include appropriate loader header file */
#include <dspbridge/dbll.h>
/* ----------------------------------- This */
#include <dspbridge/cod.h>
/*
* ======== cod_manager ========
*/
struct cod_manager {
struct dbll_tar_obj *target;
struct dbll_library_obj *base_lib;
bool loaded; /* Base library loaded? */
u32 entry;
struct dbll_fxns fxns;
struct dbll_attrs attrs;
char sz_zl_file[COD_MAXPATHLENGTH];
};
/*
* ======== cod_libraryobj ========
*/
struct cod_libraryobj {
struct dbll_library_obj *dbll_lib;
struct cod_manager *cod_mgr;
};
static u32 refs = 0L;
static struct dbll_fxns ldr_fxns = {
(dbll_close_fxn) dbll_close,
(dbll_create_fxn) dbll_create,
(dbll_delete_fxn) dbll_delete,
(dbll_exit_fxn) dbll_exit,
(dbll_get_attrs_fxn) dbll_get_attrs,
(dbll_get_addr_fxn) dbll_get_addr,
(dbll_get_c_addr_fxn) dbll_get_c_addr,
(dbll_get_sect_fxn) dbll_get_sect,
(dbll_init_fxn) dbll_init,
(dbll_load_fxn) dbll_load,
(dbll_open_fxn) dbll_open,
(dbll_read_sect_fxn) dbll_read_sect,
(dbll_unload_fxn) dbll_unload,
};
static bool no_op(void);
/*
* File operations (originally were under kfile.c)
*/
static s32 cod_f_close(struct file *filp)
{
/* Check for valid handle */
if (!filp)
return -EFAULT;
filp_close(filp, NULL);
/* we can't use 0 here */
return 0;
}
static struct file *cod_f_open(const char *psz_file_name, const char *sz_mode)
{
mm_segment_t fs;
struct file *filp;
fs = get_fs();
set_fs(get_ds());
/* ignore given mode and open file as read-only */
filp = filp_open(psz_file_name, O_RDONLY, 0);
if (IS_ERR(filp))
filp = NULL;
set_fs(fs);
return filp;
}
static s32 cod_f_read(void __user *pbuffer, s32 size, s32 count,
struct file *filp)
{
/* check for valid file handle */
if (!filp)
return -EFAULT;
if ((size > 0) && (count > 0) && pbuffer) {
u32 dw_bytes_read;
mm_segment_t fs;
/* read from file */
fs = get_fs();
set_fs(get_ds());
dw_bytes_read = filp->f_op->read(filp, pbuffer, size * count,
&(filp->f_pos));
set_fs(fs);
if (!dw_bytes_read)
return -EBADF;
return dw_bytes_read / size;
}
return -EINVAL;
}
static s32 cod_f_seek(struct file *filp, s32 offset, s32 origin)
{
loff_t dw_cur_pos;
/* check for valid file handle */
if (!filp)
return -EFAULT;
/* based on the origin flag, move the internal pointer */
dw_cur_pos = filp->f_op->llseek(filp, offset, origin);
if ((s32) dw_cur_pos < 0)
return -EPERM;
/* we can't use 0 here */
return 0;
}
static s32 cod_f_tell(struct file *filp)
{
loff_t dw_cur_pos;
if (!filp)
return -EFAULT;
/* Get current position */
dw_cur_pos = filp->f_op->llseek(filp, 0, SEEK_CUR);
if ((s32) dw_cur_pos < 0)
return -EPERM;
return dw_cur_pos;
}
/*
* ======== cod_close ========
*/
void cod_close(struct cod_libraryobj *lib)
{
struct cod_manager *hmgr;
DBC_REQUIRE(refs > 0);
DBC_REQUIRE(lib != NULL);
DBC_REQUIRE(lib->cod_mgr);
hmgr = lib->cod_mgr;
hmgr->fxns.close_fxn(lib->dbll_lib);
kfree(lib);
}
/*
* ======== cod_create ========
* Purpose:
* Create an object to manage code on a DSP system.
* This object can be used to load an initial program image with
* arguments that can later be expanded with
* dynamically loaded object files.
*
*/
int cod_create(struct cod_manager **mgr, char *str_zl_file)
{
struct cod_manager *mgr_new;
struct dbll_attrs zl_attrs;
int status = 0;
DBC_REQUIRE(refs > 0);
DBC_REQUIRE(mgr != NULL);
/* assume failure */
*mgr = NULL;
mgr_new = kzalloc(sizeof(struct cod_manager), GFP_KERNEL);
if (mgr_new == NULL)
return -ENOMEM;
/* Set up loader functions */
mgr_new->fxns = ldr_fxns;
/* initialize the ZL module */
mgr_new->fxns.init_fxn();
zl_attrs.alloc = (dbll_alloc_fxn) no_op;
zl_attrs.free = (dbll_free_fxn) no_op;
zl_attrs.fread = (dbll_read_fxn) cod_f_read;
zl_attrs.fseek = (dbll_seek_fxn) cod_f_seek;
zl_attrs.ftell = (dbll_tell_fxn) cod_f_tell;
zl_attrs.fclose = (dbll_f_close_fxn) cod_f_close;
zl_attrs.fopen = (dbll_f_open_fxn) cod_f_open;
zl_attrs.sym_lookup = NULL;
zl_attrs.base_image = true;
zl_attrs.log_write = NULL;
zl_attrs.log_write_handle = NULL;
zl_attrs.write = NULL;
zl_attrs.rmm_handle = NULL;
zl_attrs.input_params = NULL;
zl_attrs.sym_handle = NULL;
zl_attrs.sym_arg = NULL;
mgr_new->attrs = zl_attrs;
status = mgr_new->fxns.create_fxn(&mgr_new->target, &zl_attrs);
if (status) {
cod_delete(mgr_new);
return -ESPIPE;
}
/* return the new manager */
*mgr = mgr_new;
return 0;
}
/*
* ======== cod_delete ========
* Purpose:
* Delete a code manager object.
*/
void cod_delete(struct cod_manager *cod_mgr_obj)
{
DBC_REQUIRE(refs > 0);
DBC_REQUIRE(cod_mgr_obj);
if (cod_mgr_obj->base_lib) {
if (cod_mgr_obj->loaded)
cod_mgr_obj->fxns.unload_fxn(cod_mgr_obj->base_lib,
&cod_mgr_obj->attrs);
cod_mgr_obj->fxns.close_fxn(cod_mgr_obj->base_lib);
}
if (cod_mgr_obj->target) {
cod_mgr_obj->fxns.delete_fxn(cod_mgr_obj->target);
cod_mgr_obj->fxns.exit_fxn();
}
kfree(cod_mgr_obj);
}
/*
* ======== cod_exit ========
* Purpose:
* Discontinue usage of the COD module.
*
*/
void cod_exit(void)
{
DBC_REQUIRE(refs > 0);
refs--;
DBC_ENSURE(refs >= 0);
}
/*
* ======== cod_get_base_lib ========
* Purpose:
* Get handle to the base image DBL library.
*/
int cod_get_base_lib(struct cod_manager *cod_mgr_obj,
struct dbll_library_obj **plib)
{
int status = 0;
DBC_REQUIRE(refs > 0);
DBC_REQUIRE(cod_mgr_obj);
DBC_REQUIRE(plib != NULL);
*plib = (struct dbll_library_obj *)cod_mgr_obj->base_lib;
return status;
}
/*
* ======== cod_get_base_name ========
*/
int cod_get_base_name(struct cod_manager *cod_mgr_obj, char *sz_name,
u32 usize)
{
int status = 0;
DBC_REQUIRE(refs > 0);
DBC_REQUIRE(cod_mgr_obj);
DBC_REQUIRE(sz_name != NULL);
if (usize <= COD_MAXPATHLENGTH)
strncpy(sz_name, cod_mgr_obj->sz_zl_file, usize);
else
status = -EPERM;
return status;
}
/*
* ======== cod_get_entry ========
* Purpose:
* Retrieve the entry point of a loaded DSP program image
*
*/
int cod_get_entry(struct cod_manager *cod_mgr_obj, u32 *entry_pt)
{
DBC_REQUIRE(refs > 0);
DBC_REQUIRE(cod_mgr_obj);
DBC_REQUIRE(entry_pt != NULL);
*entry_pt = cod_mgr_obj->entry;
return 0;
}
/*
* ======== cod_get_loader ========
* Purpose:
* Get handle to the DBLL loader.
*/
int cod_get_loader(struct cod_manager *cod_mgr_obj,
struct dbll_tar_obj **loader)
{
int status = 0;
DBC_REQUIRE(refs > 0);
DBC_REQUIRE(cod_mgr_obj);
DBC_REQUIRE(loader != NULL);
*loader = (struct dbll_tar_obj *)cod_mgr_obj->target;
return status;
}
/*
* ======== cod_get_section ========
* Purpose:
* Retrieve the starting address and length of a section in the COFF file
* given the section name.
*/
int cod_get_section(struct cod_libraryobj *lib, char *str_sect,
u32 *addr, u32 *len)
{
struct cod_manager *cod_mgr_obj;
int status = 0;
DBC_REQUIRE(refs > 0);
DBC_REQUIRE(lib != NULL);
DBC_REQUIRE(lib->cod_mgr);
DBC_REQUIRE(str_sect != NULL);
DBC_REQUIRE(addr != NULL);
DBC_REQUIRE(len != NULL);
*addr = 0;
*len = 0;
if (lib != NULL) {
cod_mgr_obj = lib->cod_mgr;
status = cod_mgr_obj->fxns.get_sect_fxn(lib->dbll_lib, str_sect,
addr, len);
} else {
status = -ESPIPE;
}
DBC_ENSURE(!status || ((*addr == 0) && (*len == 0)));
return status;
}
/*
* ======== cod_get_sym_value ========
* Purpose:
* Retrieve the value for the specified symbol. The symbol is first
* searched for literally and then, if not found, searched for as a
* C symbol.
*
*/
int cod_get_sym_value(struct cod_manager *cod_mgr_obj, char *str_sym,
u32 *pul_value)
{
struct dbll_sym_val *dbll_sym;
DBC_REQUIRE(refs > 0);
DBC_REQUIRE(cod_mgr_obj);
DBC_REQUIRE(str_sym != NULL);
DBC_REQUIRE(pul_value != NULL);
dev_dbg(bridge, "%s: cod_mgr_obj: %p str_sym: %s pul_value: %p\n",
__func__, cod_mgr_obj, str_sym, pul_value);
if (cod_mgr_obj->base_lib) {
if (!cod_mgr_obj->fxns.
get_addr_fxn(cod_mgr_obj->base_lib, str_sym, &dbll_sym)) {
if (!cod_mgr_obj->fxns.
get_c_addr_fxn(cod_mgr_obj->base_lib, str_sym,
&dbll_sym))
return -ESPIPE;
}
} else {
return -ESPIPE;
}
*pul_value = dbll_sym->value;
return 0;
}
/*
* ======== cod_init ========
* Purpose:
* Initialize the COD module's private state.
*
*/
bool cod_init(void)
{
bool ret = true;
DBC_REQUIRE(refs >= 0);
if (ret)
refs++;
DBC_ENSURE((ret && refs > 0) || (!ret && refs >= 0));
return ret;
}
/*
* ======== cod_load_base ========
* Purpose:
* Load the initial program image, optionally with command-line arguments,
* on the DSP system managed by the supplied handle. The program to be
* loaded must be the first element of the args array and must be a fully
* qualified pathname.
* Details:
* if num_argc doesn't match the number of arguments in the args array, the
* args array is searched for a NULL terminating entry, and argc is
* recalculated to reflect this. In this way, we can support NULL
* terminating args arrays, if num_argc is very large.
*/
int cod_load_base(struct cod_manager *cod_mgr_obj, u32 num_argc, char *args[],
cod_writefxn pfn_write, void *arb, char *envp[])
{
dbll_flags flags;
struct dbll_attrs save_attrs;
struct dbll_attrs new_attrs;
int status;
u32 i;
DBC_REQUIRE(refs > 0);
DBC_REQUIRE(cod_mgr_obj);
DBC_REQUIRE(num_argc > 0);
DBC_REQUIRE(args != NULL);
DBC_REQUIRE(args[0] != NULL);
DBC_REQUIRE(pfn_write != NULL);
DBC_REQUIRE(cod_mgr_obj->base_lib != NULL);
/*
* Make sure every argv[] stated in argc has a value, or change argc to
* reflect true number in NULL terminated argv array.
*/
for (i = 0; i < num_argc; i++) {
if (args[i] == NULL) {
num_argc = i;
break;
}
}
/* set the write function for this operation */
cod_mgr_obj->fxns.get_attrs_fxn(cod_mgr_obj->target, &save_attrs);
new_attrs = save_attrs;
new_attrs.write = (dbll_write_fxn) pfn_write;
new_attrs.input_params = arb;
new_attrs.alloc = (dbll_alloc_fxn) no_op;
new_attrs.free = (dbll_free_fxn) no_op;
new_attrs.log_write = NULL;
new_attrs.log_write_handle = NULL;
/* Load the image */
flags = DBLL_CODE | DBLL_DATA | DBLL_SYMB;
status = cod_mgr_obj->fxns.load_fxn(cod_mgr_obj->base_lib, flags,
&new_attrs,
&cod_mgr_obj->entry);
if (status)
cod_mgr_obj->fxns.close_fxn(cod_mgr_obj->base_lib);
if (!status)
cod_mgr_obj->loaded = true;
else
cod_mgr_obj->base_lib = NULL;
return status;
}
/*
* ======== cod_open ========
* Open library for reading sections.
*/
int cod_open(struct cod_manager *hmgr, char *sz_coff_path,
u32 flags, struct cod_libraryobj **lib_obj)
{
int status = 0;
struct cod_libraryobj *lib = NULL;
DBC_REQUIRE(refs > 0);
DBC_REQUIRE(hmgr);
DBC_REQUIRE(sz_coff_path != NULL);
DBC_REQUIRE(flags == COD_NOLOAD || flags == COD_SYMB);
DBC_REQUIRE(lib_obj != NULL);
*lib_obj = NULL;
lib = kzalloc(sizeof(struct cod_libraryobj), GFP_KERNEL);
if (lib == NULL)
status = -ENOMEM;
if (!status) {
lib->cod_mgr = hmgr;
status = hmgr->fxns.open_fxn(hmgr->target, sz_coff_path, flags,
&lib->dbll_lib);
if (!status)
*lib_obj = lib;
}
if (status)
pr_err("%s: error status 0x%x, sz_coff_path: %s flags: 0x%x\n",
__func__, status, sz_coff_path, flags);
return status;
}
/*
* ======== cod_open_base ========
* Purpose:
* Open base image for reading sections.
*/
int cod_open_base(struct cod_manager *hmgr, char *sz_coff_path,
dbll_flags flags)
{
int status = 0;
struct dbll_library_obj *lib;
DBC_REQUIRE(refs > 0);
DBC_REQUIRE(hmgr);
DBC_REQUIRE(sz_coff_path != NULL);
/* if we previously opened a base image, close it now */
if (hmgr->base_lib) {
if (hmgr->loaded) {
hmgr->fxns.unload_fxn(hmgr->base_lib, &hmgr->attrs);
hmgr->loaded = false;
}
hmgr->fxns.close_fxn(hmgr->base_lib);
hmgr->base_lib = NULL;
}
status = hmgr->fxns.open_fxn(hmgr->target, sz_coff_path, flags, &lib);
if (!status) {
/* hang onto the library for subsequent sym table usage */
hmgr->base_lib = lib;
strncpy(hmgr->sz_zl_file, sz_coff_path, COD_MAXPATHLENGTH - 1);
hmgr->sz_zl_file[COD_MAXPATHLENGTH - 1] = '\0';
}
if (status)
pr_err("%s: error status 0x%x sz_coff_path: %s\n", __func__,
status, sz_coff_path);
return status;
}
/*
* ======== cod_read_section ========
* Purpose:
* Retrieve the content of a code section given the section name.
*/
int cod_read_section(struct cod_libraryobj *lib, char *str_sect,
char *str_content, u32 content_size)
{
int status = 0;
DBC_REQUIRE(refs > 0);
DBC_REQUIRE(lib != NULL);
DBC_REQUIRE(lib->cod_mgr);
DBC_REQUIRE(str_sect != NULL);
DBC_REQUIRE(str_content != NULL);
if (lib != NULL)
status =
lib->cod_mgr->fxns.read_sect_fxn(lib->dbll_lib, str_sect,
str_content, content_size);
else
status = -ESPIPE;
return status;
}
/*
* ======== no_op ========
* Purpose:
* No Operation.
*
*/
static bool no_op(void)
{
return true;
}
| gpl-2.0 |
phenomx4/android_kernel_zte_warplte | drivers/i2c/busses/i2c-designware-core.c | 3438 | 18610 | /*
* Synopsys DesignWare I2C adapter driver (master only).
*
* Based on the TI DAVINCI I2C adapter driver.
*
* Copyright (C) 2006 Texas Instruments.
* Copyright (C) 2007 MontaVista Software Inc.
* Copyright (C) 2009 Provigent Ltd.
*
* ----------------------------------------------------------------------------
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
* ----------------------------------------------------------------------------
*
*/
#include <linux/clk.h>
#include <linux/errno.h>
#include <linux/err.h>
#include <linux/i2c.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/pm_runtime.h>
#include <linux/delay.h>
#include "i2c-designware-core.h"
/*
* Registers offset
*/
#define DW_IC_CON 0x0
#define DW_IC_TAR 0x4
#define DW_IC_DATA_CMD 0x10
#define DW_IC_SS_SCL_HCNT 0x14
#define DW_IC_SS_SCL_LCNT 0x18
#define DW_IC_FS_SCL_HCNT 0x1c
#define DW_IC_FS_SCL_LCNT 0x20
#define DW_IC_INTR_STAT 0x2c
#define DW_IC_INTR_MASK 0x30
#define DW_IC_RAW_INTR_STAT 0x34
#define DW_IC_RX_TL 0x38
#define DW_IC_TX_TL 0x3c
#define DW_IC_CLR_INTR 0x40
#define DW_IC_CLR_RX_UNDER 0x44
#define DW_IC_CLR_RX_OVER 0x48
#define DW_IC_CLR_TX_OVER 0x4c
#define DW_IC_CLR_RD_REQ 0x50
#define DW_IC_CLR_TX_ABRT 0x54
#define DW_IC_CLR_RX_DONE 0x58
#define DW_IC_CLR_ACTIVITY 0x5c
#define DW_IC_CLR_STOP_DET 0x60
#define DW_IC_CLR_START_DET 0x64
#define DW_IC_CLR_GEN_CALL 0x68
#define DW_IC_ENABLE 0x6c
#define DW_IC_STATUS 0x70
#define DW_IC_TXFLR 0x74
#define DW_IC_RXFLR 0x78
#define DW_IC_TX_ABRT_SOURCE 0x80
#define DW_IC_COMP_PARAM_1 0xf4
#define DW_IC_COMP_TYPE 0xfc
#define DW_IC_COMP_TYPE_VALUE 0x44570140
#define DW_IC_INTR_RX_UNDER 0x001
#define DW_IC_INTR_RX_OVER 0x002
#define DW_IC_INTR_RX_FULL 0x004
#define DW_IC_INTR_TX_OVER 0x008
#define DW_IC_INTR_TX_EMPTY 0x010
#define DW_IC_INTR_RD_REQ 0x020
#define DW_IC_INTR_TX_ABRT 0x040
#define DW_IC_INTR_RX_DONE 0x080
#define DW_IC_INTR_ACTIVITY 0x100
#define DW_IC_INTR_STOP_DET 0x200
#define DW_IC_INTR_START_DET 0x400
#define DW_IC_INTR_GEN_CALL 0x800
#define DW_IC_INTR_DEFAULT_MASK (DW_IC_INTR_RX_FULL | \
DW_IC_INTR_TX_EMPTY | \
DW_IC_INTR_TX_ABRT | \
DW_IC_INTR_STOP_DET)
#define DW_IC_STATUS_ACTIVITY 0x1
#define DW_IC_ERR_TX_ABRT 0x1
/*
* status codes
*/
#define STATUS_IDLE 0x0
#define STATUS_WRITE_IN_PROGRESS 0x1
#define STATUS_READ_IN_PROGRESS 0x2
#define TIMEOUT 20 /* ms */
/*
* hardware abort codes from the DW_IC_TX_ABRT_SOURCE register
*
* only expected abort codes are listed here
* refer to the datasheet for the full list
*/
#define ABRT_7B_ADDR_NOACK 0
#define ABRT_10ADDR1_NOACK 1
#define ABRT_10ADDR2_NOACK 2
#define ABRT_TXDATA_NOACK 3
#define ABRT_GCALL_NOACK 4
#define ABRT_GCALL_READ 5
#define ABRT_SBYTE_ACKDET 7
#define ABRT_SBYTE_NORSTRT 9
#define ABRT_10B_RD_NORSTRT 10
#define ABRT_MASTER_DIS 11
#define ARB_LOST 12
#define DW_IC_TX_ABRT_7B_ADDR_NOACK (1UL << ABRT_7B_ADDR_NOACK)
#define DW_IC_TX_ABRT_10ADDR1_NOACK (1UL << ABRT_10ADDR1_NOACK)
#define DW_IC_TX_ABRT_10ADDR2_NOACK (1UL << ABRT_10ADDR2_NOACK)
#define DW_IC_TX_ABRT_TXDATA_NOACK (1UL << ABRT_TXDATA_NOACK)
#define DW_IC_TX_ABRT_GCALL_NOACK (1UL << ABRT_GCALL_NOACK)
#define DW_IC_TX_ABRT_GCALL_READ (1UL << ABRT_GCALL_READ)
#define DW_IC_TX_ABRT_SBYTE_ACKDET (1UL << ABRT_SBYTE_ACKDET)
#define DW_IC_TX_ABRT_SBYTE_NORSTRT (1UL << ABRT_SBYTE_NORSTRT)
#define DW_IC_TX_ABRT_10B_RD_NORSTRT (1UL << ABRT_10B_RD_NORSTRT)
#define DW_IC_TX_ABRT_MASTER_DIS (1UL << ABRT_MASTER_DIS)
#define DW_IC_TX_ARB_LOST (1UL << ARB_LOST)
#define DW_IC_TX_ABRT_NOACK (DW_IC_TX_ABRT_7B_ADDR_NOACK | \
DW_IC_TX_ABRT_10ADDR1_NOACK | \
DW_IC_TX_ABRT_10ADDR2_NOACK | \
DW_IC_TX_ABRT_TXDATA_NOACK | \
DW_IC_TX_ABRT_GCALL_NOACK)
static char *abort_sources[] = {
[ABRT_7B_ADDR_NOACK] =
"slave address not acknowledged (7bit mode)",
[ABRT_10ADDR1_NOACK] =
"first address byte not acknowledged (10bit mode)",
[ABRT_10ADDR2_NOACK] =
"second address byte not acknowledged (10bit mode)",
[ABRT_TXDATA_NOACK] =
"data not acknowledged",
[ABRT_GCALL_NOACK] =
"no acknowledgement for a general call",
[ABRT_GCALL_READ] =
"read after general call",
[ABRT_SBYTE_ACKDET] =
"start byte acknowledged",
[ABRT_SBYTE_NORSTRT] =
"trying to send start byte when restart is disabled",
[ABRT_10B_RD_NORSTRT] =
"trying to read when restart is disabled (10bit mode)",
[ABRT_MASTER_DIS] =
"trying to use disabled adapter",
[ARB_LOST] =
"lost arbitration",
};
u32 dw_readl(struct dw_i2c_dev *dev, int offset)
{
u32 value = readl(dev->base + offset);
if (dev->swab)
return swab32(value);
else
return value;
}
void dw_writel(struct dw_i2c_dev *dev, u32 b, int offset)
{
if (dev->swab)
b = swab32(b);
writel(b, dev->base + offset);
}
static u32
i2c_dw_scl_hcnt(u32 ic_clk, u32 tSYMBOL, u32 tf, int cond, int offset)
{
/*
* DesignWare I2C core doesn't seem to have solid strategy to meet
* the tHD;STA timing spec. Configuring _HCNT based on tHIGH spec
* will result in violation of the tHD;STA spec.
*/
if (cond)
/*
* Conditional expression:
*
* IC_[FS]S_SCL_HCNT + (1+4+3) >= IC_CLK * tHIGH
*
* This is based on the DW manuals, and represents an ideal
* configuration. The resulting I2C bus speed will be
* faster than any of the others.
*
* If your hardware is free from tHD;STA issue, try this one.
*/
return (ic_clk * tSYMBOL + 5000) / 10000 - 8 + offset;
else
/*
* Conditional expression:
*
* IC_[FS]S_SCL_HCNT + 3 >= IC_CLK * (tHD;STA + tf)
*
* This is just experimental rule; the tHD;STA period turned
* out to be proportinal to (_HCNT + 3). With this setting,
* we could meet both tHIGH and tHD;STA timing specs.
*
* If unsure, you'd better to take this alternative.
*
* The reason why we need to take into account "tf" here,
* is the same as described in i2c_dw_scl_lcnt().
*/
return (ic_clk * (tSYMBOL + tf) + 5000) / 10000 - 3 + offset;
}
static u32 i2c_dw_scl_lcnt(u32 ic_clk, u32 tLOW, u32 tf, int offset)
{
/*
* Conditional expression:
*
* IC_[FS]S_SCL_LCNT + 1 >= IC_CLK * (tLOW + tf)
*
* DW I2C core starts counting the SCL CNTs for the LOW period
* of the SCL clock (tLOW) as soon as it pulls the SCL line.
* In order to meet the tLOW timing spec, we need to take into
* account the fall time of SCL signal (tf). Default tf value
* should be 0.3 us, for safety.
*/
return ((ic_clk * (tLOW + tf) + 5000) / 10000) - 1 + offset;
}
/**
* i2c_dw_init() - initialize the designware i2c master hardware
* @dev: device private data
*
* This functions configures and enables the I2C master.
* This function is called during I2C init function, and in case of timeout at
* run time.
*/
int i2c_dw_init(struct dw_i2c_dev *dev)
{
u32 input_clock_khz;
u32 hcnt, lcnt;
u32 reg;
input_clock_khz = dev->get_clk_rate_khz(dev);
/* Configure register endianess access */
reg = dw_readl(dev, DW_IC_COMP_TYPE);
if (reg == ___constant_swab32(DW_IC_COMP_TYPE_VALUE)) {
dev->swab = 1;
reg = DW_IC_COMP_TYPE_VALUE;
}
if (reg != DW_IC_COMP_TYPE_VALUE) {
dev_err(dev->dev, "Unknown Synopsys component type: "
"0x%08x\n", reg);
return -ENODEV;
}
/* Disable the adapter */
dw_writel(dev, 0, DW_IC_ENABLE);
/* set standard and fast speed deviders for high/low periods */
/* Standard-mode */
hcnt = i2c_dw_scl_hcnt(input_clock_khz,
40, /* tHD;STA = tHIGH = 4.0 us */
3, /* tf = 0.3 us */
0, /* 0: DW default, 1: Ideal */
0); /* No offset */
lcnt = i2c_dw_scl_lcnt(input_clock_khz,
47, /* tLOW = 4.7 us */
3, /* tf = 0.3 us */
0); /* No offset */
dw_writel(dev, hcnt, DW_IC_SS_SCL_HCNT);
dw_writel(dev, lcnt, DW_IC_SS_SCL_LCNT);
dev_dbg(dev->dev, "Standard-mode HCNT:LCNT = %d:%d\n", hcnt, lcnt);
/* Fast-mode */
hcnt = i2c_dw_scl_hcnt(input_clock_khz,
6, /* tHD;STA = tHIGH = 0.6 us */
3, /* tf = 0.3 us */
0, /* 0: DW default, 1: Ideal */
0); /* No offset */
lcnt = i2c_dw_scl_lcnt(input_clock_khz,
13, /* tLOW = 1.3 us */
3, /* tf = 0.3 us */
0); /* No offset */
dw_writel(dev, hcnt, DW_IC_FS_SCL_HCNT);
dw_writel(dev, lcnt, DW_IC_FS_SCL_LCNT);
dev_dbg(dev->dev, "Fast-mode HCNT:LCNT = %d:%d\n", hcnt, lcnt);
/* Configure Tx/Rx FIFO threshold levels */
dw_writel(dev, dev->tx_fifo_depth - 1, DW_IC_TX_TL);
dw_writel(dev, 0, DW_IC_RX_TL);
/* configure the i2c master */
dw_writel(dev, dev->master_cfg , DW_IC_CON);
return 0;
}
/*
* Waiting for bus not busy
*/
static int i2c_dw_wait_bus_not_busy(struct dw_i2c_dev *dev)
{
int timeout = TIMEOUT;
while (dw_readl(dev, DW_IC_STATUS) & DW_IC_STATUS_ACTIVITY) {
if (timeout <= 0) {
dev_warn(dev->dev, "timeout waiting for bus ready\n");
return -ETIMEDOUT;
}
timeout--;
mdelay(1);
}
return 0;
}
static void i2c_dw_xfer_init(struct dw_i2c_dev *dev)
{
struct i2c_msg *msgs = dev->msgs;
u32 ic_con;
/* Disable the adapter */
dw_writel(dev, 0, DW_IC_ENABLE);
/* set the slave (target) address */
dw_writel(dev, msgs[dev->msg_write_idx].addr, DW_IC_TAR);
/* if the slave address is ten bit address, enable 10BITADDR */
ic_con = dw_readl(dev, DW_IC_CON);
if (msgs[dev->msg_write_idx].flags & I2C_M_TEN)
ic_con |= DW_IC_CON_10BITADDR_MASTER;
else
ic_con &= ~DW_IC_CON_10BITADDR_MASTER;
dw_writel(dev, ic_con, DW_IC_CON);
/* Enable the adapter */
dw_writel(dev, 1, DW_IC_ENABLE);
/* Enable interrupts */
dw_writel(dev, DW_IC_INTR_DEFAULT_MASK, DW_IC_INTR_MASK);
}
/*
* Initiate (and continue) low level master read/write transaction.
* This function is only called from i2c_dw_isr, and pumping i2c_msg
* messages into the tx buffer. Even if the size of i2c_msg data is
* longer than the size of the tx buffer, it handles everything.
*/
void
i2c_dw_xfer_msg(struct dw_i2c_dev *dev)
{
struct i2c_msg *msgs = dev->msgs;
u32 intr_mask;
int tx_limit, rx_limit;
u32 addr = msgs[dev->msg_write_idx].addr;
u32 buf_len = dev->tx_buf_len;
u8 *buf = dev->tx_buf;
intr_mask = DW_IC_INTR_DEFAULT_MASK;
for (; dev->msg_write_idx < dev->msgs_num; dev->msg_write_idx++) {
/*
* if target address has changed, we need to
* reprogram the target address in the i2c
* adapter when we are done with this transfer
*/
if (msgs[dev->msg_write_idx].addr != addr) {
dev_err(dev->dev,
"%s: invalid target address\n", __func__);
dev->msg_err = -EINVAL;
break;
}
if (msgs[dev->msg_write_idx].len == 0) {
dev_err(dev->dev,
"%s: invalid message length\n", __func__);
dev->msg_err = -EINVAL;
break;
}
if (!(dev->status & STATUS_WRITE_IN_PROGRESS)) {
/* new i2c_msg */
buf = msgs[dev->msg_write_idx].buf;
buf_len = msgs[dev->msg_write_idx].len;
}
tx_limit = dev->tx_fifo_depth - dw_readl(dev, DW_IC_TXFLR);
rx_limit = dev->rx_fifo_depth - dw_readl(dev, DW_IC_RXFLR);
while (buf_len > 0 && tx_limit > 0 && rx_limit > 0) {
if (msgs[dev->msg_write_idx].flags & I2C_M_RD) {
dw_writel(dev, 0x100, DW_IC_DATA_CMD);
rx_limit--;
} else
dw_writel(dev, *buf++, DW_IC_DATA_CMD);
tx_limit--; buf_len--;
}
dev->tx_buf = buf;
dev->tx_buf_len = buf_len;
if (buf_len > 0) {
/* more bytes to be written */
dev->status |= STATUS_WRITE_IN_PROGRESS;
break;
} else
dev->status &= ~STATUS_WRITE_IN_PROGRESS;
}
/*
* If i2c_msg index search is completed, we don't need TX_EMPTY
* interrupt any more.
*/
if (dev->msg_write_idx == dev->msgs_num)
intr_mask &= ~DW_IC_INTR_TX_EMPTY;
if (dev->msg_err)
intr_mask = 0;
dw_writel(dev, intr_mask, DW_IC_INTR_MASK);
}
static void
i2c_dw_read(struct dw_i2c_dev *dev)
{
struct i2c_msg *msgs = dev->msgs;
int rx_valid;
for (; dev->msg_read_idx < dev->msgs_num; dev->msg_read_idx++) {
u32 len;
u8 *buf;
if (!(msgs[dev->msg_read_idx].flags & I2C_M_RD))
continue;
if (!(dev->status & STATUS_READ_IN_PROGRESS)) {
len = msgs[dev->msg_read_idx].len;
buf = msgs[dev->msg_read_idx].buf;
} else {
len = dev->rx_buf_len;
buf = dev->rx_buf;
}
rx_valid = dw_readl(dev, DW_IC_RXFLR);
for (; len > 0 && rx_valid > 0; len--, rx_valid--)
*buf++ = dw_readl(dev, DW_IC_DATA_CMD);
if (len > 0) {
dev->status |= STATUS_READ_IN_PROGRESS;
dev->rx_buf_len = len;
dev->rx_buf = buf;
return;
} else
dev->status &= ~STATUS_READ_IN_PROGRESS;
}
}
static int i2c_dw_handle_tx_abort(struct dw_i2c_dev *dev)
{
unsigned long abort_source = dev->abort_source;
int i;
if (abort_source & DW_IC_TX_ABRT_NOACK) {
for_each_set_bit(i, &abort_source, ARRAY_SIZE(abort_sources))
dev_dbg(dev->dev,
"%s: %s\n", __func__, abort_sources[i]);
return -EREMOTEIO;
}
for_each_set_bit(i, &abort_source, ARRAY_SIZE(abort_sources))
dev_err(dev->dev, "%s: %s\n", __func__, abort_sources[i]);
if (abort_source & DW_IC_TX_ARB_LOST)
return -EAGAIN;
else if (abort_source & DW_IC_TX_ABRT_GCALL_READ)
return -EINVAL; /* wrong msgs[] data */
else
return -EIO;
}
/*
* Prepare controller for a transaction and call i2c_dw_xfer_msg
*/
int
i2c_dw_xfer(struct i2c_adapter *adap, struct i2c_msg msgs[], int num)
{
struct dw_i2c_dev *dev = i2c_get_adapdata(adap);
int ret;
dev_dbg(dev->dev, "%s: msgs: %d\n", __func__, num);
mutex_lock(&dev->lock);
pm_runtime_get_sync(dev->dev);
INIT_COMPLETION(dev->cmd_complete);
dev->msgs = msgs;
dev->msgs_num = num;
dev->cmd_err = 0;
dev->msg_write_idx = 0;
dev->msg_read_idx = 0;
dev->msg_err = 0;
dev->status = STATUS_IDLE;
dev->abort_source = 0;
ret = i2c_dw_wait_bus_not_busy(dev);
if (ret < 0)
goto done;
/* start the transfers */
i2c_dw_xfer_init(dev);
/* wait for tx to complete */
ret = wait_for_completion_interruptible_timeout(&dev->cmd_complete, HZ);
if (ret == 0) {
dev_err(dev->dev, "controller timed out\n");
i2c_dw_init(dev);
ret = -ETIMEDOUT;
goto done;
} else if (ret < 0)
goto done;
if (dev->msg_err) {
ret = dev->msg_err;
goto done;
}
/* no error */
if (likely(!dev->cmd_err)) {
/* Disable the adapter */
dw_writel(dev, 0, DW_IC_ENABLE);
ret = num;
goto done;
}
/* We have an error */
if (dev->cmd_err == DW_IC_ERR_TX_ABRT) {
ret = i2c_dw_handle_tx_abort(dev);
goto done;
}
ret = -EIO;
done:
pm_runtime_put(dev->dev);
mutex_unlock(&dev->lock);
return ret;
}
u32 i2c_dw_func(struct i2c_adapter *adap)
{
struct dw_i2c_dev *dev = i2c_get_adapdata(adap);
return dev->functionality;
}
static u32 i2c_dw_read_clear_intrbits(struct dw_i2c_dev *dev)
{
u32 stat;
/*
* The IC_INTR_STAT register just indicates "enabled" interrupts.
* Ths unmasked raw version of interrupt status bits are available
* in the IC_RAW_INTR_STAT register.
*
* That is,
* stat = dw_readl(IC_INTR_STAT);
* equals to,
* stat = dw_readl(IC_RAW_INTR_STAT) & dw_readl(IC_INTR_MASK);
*
* The raw version might be useful for debugging purposes.
*/
stat = dw_readl(dev, DW_IC_INTR_STAT);
/*
* Do not use the IC_CLR_INTR register to clear interrupts, or
* you'll miss some interrupts, triggered during the period from
* dw_readl(IC_INTR_STAT) to dw_readl(IC_CLR_INTR).
*
* Instead, use the separately-prepared IC_CLR_* registers.
*/
if (stat & DW_IC_INTR_RX_UNDER)
dw_readl(dev, DW_IC_CLR_RX_UNDER);
if (stat & DW_IC_INTR_RX_OVER)
dw_readl(dev, DW_IC_CLR_RX_OVER);
if (stat & DW_IC_INTR_TX_OVER)
dw_readl(dev, DW_IC_CLR_TX_OVER);
if (stat & DW_IC_INTR_RD_REQ)
dw_readl(dev, DW_IC_CLR_RD_REQ);
if (stat & DW_IC_INTR_TX_ABRT) {
/*
* The IC_TX_ABRT_SOURCE register is cleared whenever
* the IC_CLR_TX_ABRT is read. Preserve it beforehand.
*/
dev->abort_source = dw_readl(dev, DW_IC_TX_ABRT_SOURCE);
dw_readl(dev, DW_IC_CLR_TX_ABRT);
}
if (stat & DW_IC_INTR_RX_DONE)
dw_readl(dev, DW_IC_CLR_RX_DONE);
if (stat & DW_IC_INTR_ACTIVITY)
dw_readl(dev, DW_IC_CLR_ACTIVITY);
if (stat & DW_IC_INTR_STOP_DET)
dw_readl(dev, DW_IC_CLR_STOP_DET);
if (stat & DW_IC_INTR_START_DET)
dw_readl(dev, DW_IC_CLR_START_DET);
if (stat & DW_IC_INTR_GEN_CALL)
dw_readl(dev, DW_IC_CLR_GEN_CALL);
return stat;
}
/*
* Interrupt service routine. This gets called whenever an I2C interrupt
* occurs.
*/
irqreturn_t i2c_dw_isr(int this_irq, void *dev_id)
{
struct dw_i2c_dev *dev = dev_id;
u32 stat, enabled;
enabled = dw_readl(dev, DW_IC_ENABLE);
stat = dw_readl(dev, DW_IC_RAW_INTR_STAT);
dev_dbg(dev->dev, "%s: %s enabled= 0x%x stat=0x%x\n", __func__,
dev->adapter.name, enabled, stat);
if (!enabled || !(stat & ~DW_IC_INTR_ACTIVITY))
return IRQ_NONE;
stat = i2c_dw_read_clear_intrbits(dev);
if (stat & DW_IC_INTR_TX_ABRT) {
dev->cmd_err |= DW_IC_ERR_TX_ABRT;
dev->status = STATUS_IDLE;
/*
* Anytime TX_ABRT is set, the contents of the tx/rx
* buffers are flushed. Make sure to skip them.
*/
dw_writel(dev, 0, DW_IC_INTR_MASK);
goto tx_aborted;
}
if (stat & DW_IC_INTR_RX_FULL)
i2c_dw_read(dev);
if (stat & DW_IC_INTR_TX_EMPTY)
i2c_dw_xfer_msg(dev);
/*
* No need to modify or disable the interrupt mask here.
* i2c_dw_xfer_msg() will take care of it according to
* the current transmit status.
*/
tx_aborted:
if ((stat & (DW_IC_INTR_TX_ABRT | DW_IC_INTR_STOP_DET)) || dev->msg_err)
complete(&dev->cmd_complete);
return IRQ_HANDLED;
}
void i2c_dw_enable(struct dw_i2c_dev *dev)
{
/* Enable the adapter */
dw_writel(dev, 1, DW_IC_ENABLE);
}
u32 i2c_dw_is_enabled(struct dw_i2c_dev *dev)
{
return dw_readl(dev, DW_IC_ENABLE);
}
void i2c_dw_disable(struct dw_i2c_dev *dev)
{
/* Disable controller */
dw_writel(dev, 0, DW_IC_ENABLE);
/* Disable all interupts */
dw_writel(dev, 0, DW_IC_INTR_MASK);
dw_readl(dev, DW_IC_CLR_INTR);
}
void i2c_dw_clear_int(struct dw_i2c_dev *dev)
{
dw_readl(dev, DW_IC_CLR_INTR);
}
void i2c_dw_disable_int(struct dw_i2c_dev *dev)
{
dw_writel(dev, 0, DW_IC_INTR_MASK);
}
u32 i2c_dw_read_comp_param(struct dw_i2c_dev *dev)
{
return dw_readl(dev, DW_IC_COMP_PARAM_1);
}
| gpl-2.0 |
MassStash/htc_m8whl_kernel_sense | kernel/delayacct.c | 5742 | 5126 | /* delayacct.c - per-task delay accounting
*
* Copyright (C) Shailabh Nagar, IBM Corp. 2006
*
* 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 would be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU General Public License for more details.
*/
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/taskstats.h>
#include <linux/time.h>
#include <linux/sysctl.h>
#include <linux/delayacct.h>
#include <linux/module.h>
int delayacct_on __read_mostly = 1; /* Delay accounting turned on/off */
EXPORT_SYMBOL_GPL(delayacct_on);
struct kmem_cache *delayacct_cache;
static int __init delayacct_setup_disable(char *str)
{
delayacct_on = 0;
return 1;
}
__setup("nodelayacct", delayacct_setup_disable);
void delayacct_init(void)
{
delayacct_cache = KMEM_CACHE(task_delay_info, SLAB_PANIC);
delayacct_tsk_init(&init_task);
}
void __delayacct_tsk_init(struct task_struct *tsk)
{
tsk->delays = kmem_cache_zalloc(delayacct_cache, GFP_KERNEL);
if (tsk->delays)
spin_lock_init(&tsk->delays->lock);
}
/*
* Start accounting for a delay statistic using
* its starting timestamp (@start)
*/
static inline void delayacct_start(struct timespec *start)
{
do_posix_clock_monotonic_gettime(start);
}
/*
* Finish delay accounting for a statistic using
* its timestamps (@start, @end), accumalator (@total) and @count
*/
static void delayacct_end(struct timespec *start, struct timespec *end,
u64 *total, u32 *count)
{
struct timespec ts;
s64 ns;
unsigned long flags;
do_posix_clock_monotonic_gettime(end);
ts = timespec_sub(*end, *start);
ns = timespec_to_ns(&ts);
if (ns < 0)
return;
spin_lock_irqsave(¤t->delays->lock, flags);
*total += ns;
(*count)++;
spin_unlock_irqrestore(¤t->delays->lock, flags);
}
void __delayacct_blkio_start(void)
{
delayacct_start(¤t->delays->blkio_start);
}
void __delayacct_blkio_end(void)
{
if (current->delays->flags & DELAYACCT_PF_SWAPIN)
/* Swapin block I/O */
delayacct_end(¤t->delays->blkio_start,
¤t->delays->blkio_end,
¤t->delays->swapin_delay,
¤t->delays->swapin_count);
else /* Other block I/O */
delayacct_end(¤t->delays->blkio_start,
¤t->delays->blkio_end,
¤t->delays->blkio_delay,
¤t->delays->blkio_count);
}
int __delayacct_add_tsk(struct taskstats *d, struct task_struct *tsk)
{
s64 tmp;
unsigned long t1;
unsigned long long t2, t3;
unsigned long flags;
struct timespec ts;
/* Though tsk->delays accessed later, early exit avoids
* unnecessary returning of other data
*/
if (!tsk->delays)
goto done;
tmp = (s64)d->cpu_run_real_total;
cputime_to_timespec(tsk->utime + tsk->stime, &ts);
tmp += timespec_to_ns(&ts);
d->cpu_run_real_total = (tmp < (s64)d->cpu_run_real_total) ? 0 : tmp;
tmp = (s64)d->cpu_scaled_run_real_total;
cputime_to_timespec(tsk->utimescaled + tsk->stimescaled, &ts);
tmp += timespec_to_ns(&ts);
d->cpu_scaled_run_real_total =
(tmp < (s64)d->cpu_scaled_run_real_total) ? 0 : tmp;
/*
* No locking available for sched_info (and too expensive to add one)
* Mitigate by taking snapshot of values
*/
t1 = tsk->sched_info.pcount;
t2 = tsk->sched_info.run_delay;
t3 = tsk->se.sum_exec_runtime;
d->cpu_count += t1;
tmp = (s64)d->cpu_delay_total + t2;
d->cpu_delay_total = (tmp < (s64)d->cpu_delay_total) ? 0 : tmp;
tmp = (s64)d->cpu_run_virtual_total + t3;
d->cpu_run_virtual_total =
(tmp < (s64)d->cpu_run_virtual_total) ? 0 : tmp;
/* zero XXX_total, non-zero XXX_count implies XXX stat overflowed */
spin_lock_irqsave(&tsk->delays->lock, flags);
tmp = d->blkio_delay_total + tsk->delays->blkio_delay;
d->blkio_delay_total = (tmp < d->blkio_delay_total) ? 0 : tmp;
tmp = d->swapin_delay_total + tsk->delays->swapin_delay;
d->swapin_delay_total = (tmp < d->swapin_delay_total) ? 0 : tmp;
tmp = d->freepages_delay_total + tsk->delays->freepages_delay;
d->freepages_delay_total = (tmp < d->freepages_delay_total) ? 0 : tmp;
d->blkio_count += tsk->delays->blkio_count;
d->swapin_count += tsk->delays->swapin_count;
d->freepages_count += tsk->delays->freepages_count;
spin_unlock_irqrestore(&tsk->delays->lock, flags);
done:
return 0;
}
__u64 __delayacct_blkio_ticks(struct task_struct *tsk)
{
__u64 ret;
unsigned long flags;
spin_lock_irqsave(&tsk->delays->lock, flags);
ret = nsec_to_clock_t(tsk->delays->blkio_delay +
tsk->delays->swapin_delay);
spin_unlock_irqrestore(&tsk->delays->lock, flags);
return ret;
}
void __delayacct_freepages_start(void)
{
delayacct_start(¤t->delays->freepages_start);
}
void __delayacct_freepages_end(void)
{
delayacct_end(¤t->delays->freepages_start,
¤t->delays->freepages_end,
¤t->delays->freepages_delay,
¤t->delays->freepages_count);
}
| gpl-2.0 |
GuneetAtwal/Blaze.Kernel-MT6589 | arch/mn10300/kernel/signal.c | 7534 | 15098 | /* MN10300 Signal handling
*
* Copyright (C) 2007 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public Licence
* as published by the Free Software Foundation; either version
* 2 of the Licence, or (at your option) any later version.
*/
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/smp.h>
#include <linux/kernel.h>
#include <linux/signal.h>
#include <linux/errno.h>
#include <linux/wait.h>
#include <linux/ptrace.h>
#include <linux/unistd.h>
#include <linux/stddef.h>
#include <linux/tty.h>
#include <linux/personality.h>
#include <linux/suspend.h>
#include <linux/tracehook.h>
#include <asm/cacheflush.h>
#include <asm/ucontext.h>
#include <asm/uaccess.h>
#include <asm/fpu.h>
#include "sigframe.h"
#define DEBUG_SIG 0
#define _BLOCKABLE (~(sigmask(SIGKILL) | sigmask(SIGSTOP)))
/*
* atomically swap in the new signal mask, and wait for a signal.
*/
asmlinkage long sys_sigsuspend(int history0, int history1, old_sigset_t mask)
{
mask &= _BLOCKABLE;
spin_lock_irq(¤t->sighand->siglock);
current->saved_sigmask = current->blocked;
siginitset(¤t->blocked, mask);
recalc_sigpending();
spin_unlock_irq(¤t->sighand->siglock);
current->state = TASK_INTERRUPTIBLE;
schedule();
set_thread_flag(TIF_RESTORE_SIGMASK);
return -ERESTARTNOHAND;
}
/*
* set signal action syscall
*/
asmlinkage long sys_sigaction(int sig,
const struct old_sigaction __user *act,
struct old_sigaction __user *oact)
{
struct k_sigaction new_ka, old_ka;
int ret;
if (act) {
old_sigset_t mask;
if (verify_area(VERIFY_READ, act, sizeof(*act)) ||
__get_user(new_ka.sa.sa_handler, &act->sa_handler) ||
__get_user(new_ka.sa.sa_restorer, &act->sa_restorer) ||
__get_user(new_ka.sa.sa_flags, &act->sa_flags) ||
__get_user(mask, &act->sa_mask))
return -EFAULT;
siginitset(&new_ka.sa.sa_mask, mask);
}
ret = do_sigaction(sig, act ? &new_ka : NULL, oact ? &old_ka : NULL);
if (!ret && oact) {
if (verify_area(VERIFY_WRITE, oact, sizeof(*oact)) ||
__put_user(old_ka.sa.sa_handler, &oact->sa_handler) ||
__put_user(old_ka.sa.sa_restorer, &oact->sa_restorer) ||
__put_user(old_ka.sa.sa_flags, &oact->sa_flags) ||
__put_user(old_ka.sa.sa_mask.sig[0], &oact->sa_mask))
return -EFAULT;
}
return ret;
}
/*
* set alternate signal stack syscall
*/
asmlinkage long sys_sigaltstack(const stack_t __user *uss, stack_t *uoss)
{
return do_sigaltstack(uss, uoss, current_frame()->sp);
}
/*
* do a signal return; undo the signal stack.
*/
static int restore_sigcontext(struct pt_regs *regs,
struct sigcontext __user *sc, long *_d0)
{
unsigned int err = 0;
/* Always make any pending restarted system calls return -EINTR */
current_thread_info()->restart_block.fn = do_no_restart_syscall;
if (is_using_fpu(current))
fpu_kill_state(current);
#define COPY(x) err |= __get_user(regs->x, &sc->x)
COPY(d1); COPY(d2); COPY(d3);
COPY(a0); COPY(a1); COPY(a2); COPY(a3);
COPY(e0); COPY(e1); COPY(e2); COPY(e3);
COPY(e4); COPY(e5); COPY(e6); COPY(e7);
COPY(lar); COPY(lir);
COPY(mdr); COPY(mdrq);
COPY(mcvf); COPY(mcrl); COPY(mcrh);
COPY(sp); COPY(pc);
#undef COPY
{
unsigned int tmpflags;
#ifndef CONFIG_MN10300_USING_JTAG
#define USER_EPSW (EPSW_FLAG_Z | EPSW_FLAG_N | EPSW_FLAG_C | EPSW_FLAG_V | \
EPSW_T | EPSW_nAR)
#else
#define USER_EPSW (EPSW_FLAG_Z | EPSW_FLAG_N | EPSW_FLAG_C | EPSW_FLAG_V | \
EPSW_nAR)
#endif
err |= __get_user(tmpflags, &sc->epsw);
regs->epsw = (regs->epsw & ~USER_EPSW) |
(tmpflags & USER_EPSW);
regs->orig_d0 = -1; /* disable syscall checks */
}
{
struct fpucontext *buf;
err |= __get_user(buf, &sc->fpucontext);
if (buf) {
if (verify_area(VERIFY_READ, buf, sizeof(*buf)))
goto badframe;
err |= fpu_restore_sigcontext(buf);
}
}
err |= __get_user(*_d0, &sc->d0);
return err;
badframe:
return 1;
}
/*
* standard signal return syscall
*/
asmlinkage long sys_sigreturn(void)
{
struct sigframe __user *frame;
sigset_t set;
long d0;
frame = (struct sigframe __user *) current_frame()->sp;
if (verify_area(VERIFY_READ, frame, sizeof(*frame)))
goto badframe;
if (__get_user(set.sig[0], &frame->sc.oldmask))
goto badframe;
if (_NSIG_WORDS > 1 &&
__copy_from_user(&set.sig[1], &frame->extramask,
sizeof(frame->extramask)))
goto badframe;
sigdelsetmask(&set, ~_BLOCKABLE);
spin_lock_irq(¤t->sighand->siglock);
current->blocked = set;
recalc_sigpending();
spin_unlock_irq(¤t->sighand->siglock);
if (restore_sigcontext(current_frame(), &frame->sc, &d0))
goto badframe;
return d0;
badframe:
force_sig(SIGSEGV, current);
return 0;
}
/*
* realtime signal return syscall
*/
asmlinkage long sys_rt_sigreturn(void)
{
struct rt_sigframe __user *frame;
sigset_t set;
long d0;
frame = (struct rt_sigframe __user *) current_frame()->sp;
if (verify_area(VERIFY_READ, frame, sizeof(*frame)))
goto badframe;
if (__copy_from_user(&set, &frame->uc.uc_sigmask, sizeof(set)))
goto badframe;
sigdelsetmask(&set, ~_BLOCKABLE);
spin_lock_irq(¤t->sighand->siglock);
current->blocked = set;
recalc_sigpending();
spin_unlock_irq(¤t->sighand->siglock);
if (restore_sigcontext(current_frame(), &frame->uc.uc_mcontext, &d0))
goto badframe;
if (do_sigaltstack(&frame->uc.uc_stack, NULL, current_frame()->sp) ==
-EFAULT)
goto badframe;
return d0;
badframe:
force_sig(SIGSEGV, current);
return 0;
}
/*
* store the userspace context into a signal frame
*/
static int setup_sigcontext(struct sigcontext __user *sc,
struct fpucontext *fpuctx,
struct pt_regs *regs,
unsigned long mask)
{
int tmp, err = 0;
#define COPY(x) err |= __put_user(regs->x, &sc->x)
COPY(d0); COPY(d1); COPY(d2); COPY(d3);
COPY(a0); COPY(a1); COPY(a2); COPY(a3);
COPY(e0); COPY(e1); COPY(e2); COPY(e3);
COPY(e4); COPY(e5); COPY(e6); COPY(e7);
COPY(lar); COPY(lir);
COPY(mdr); COPY(mdrq);
COPY(mcvf); COPY(mcrl); COPY(mcrh);
COPY(sp); COPY(epsw); COPY(pc);
#undef COPY
tmp = fpu_setup_sigcontext(fpuctx);
if (tmp < 0)
err = 1;
else
err |= __put_user(tmp ? fpuctx : NULL, &sc->fpucontext);
/* non-iBCS2 extensions.. */
err |= __put_user(mask, &sc->oldmask);
return err;
}
/*
* determine which stack to use..
*/
static inline void __user *get_sigframe(struct k_sigaction *ka,
struct pt_regs *regs,
size_t frame_size)
{
unsigned long sp;
/* default to using normal stack */
sp = regs->sp;
/* this is the X/Open sanctioned signal stack switching. */
if (ka->sa.sa_flags & SA_ONSTACK) {
if (sas_ss_flags(sp) == 0)
sp = current->sas_ss_sp + current->sas_ss_size;
}
return (void __user *) ((sp - frame_size) & ~7UL);
}
/*
* set up a normal signal frame
*/
static int setup_frame(int sig, struct k_sigaction *ka, sigset_t *set,
struct pt_regs *regs)
{
struct sigframe __user *frame;
int rsig;
frame = get_sigframe(ka, regs, sizeof(*frame));
if (!access_ok(VERIFY_WRITE, frame, sizeof(*frame)))
goto give_sigsegv;
rsig = sig;
if (sig < 32 &&
current_thread_info()->exec_domain &&
current_thread_info()->exec_domain->signal_invmap)
rsig = current_thread_info()->exec_domain->signal_invmap[sig];
if (__put_user(rsig, &frame->sig) < 0 ||
__put_user(&frame->sc, &frame->psc) < 0)
goto give_sigsegv;
if (setup_sigcontext(&frame->sc, &frame->fpuctx, regs, set->sig[0]))
goto give_sigsegv;
if (_NSIG_WORDS > 1) {
if (__copy_to_user(frame->extramask, &set->sig[1],
sizeof(frame->extramask)))
goto give_sigsegv;
}
/* set up to return from userspace. If provided, use a stub already in
* userspace */
if (ka->sa.sa_flags & SA_RESTORER) {
if (__put_user(ka->sa.sa_restorer, &frame->pretcode))
goto give_sigsegv;
} else {
if (__put_user((void (*)(void))frame->retcode,
&frame->pretcode))
goto give_sigsegv;
/* this is mov $,d0; syscall 0 */
if (__put_user(0x2c, (char *)(frame->retcode + 0)) ||
__put_user(__NR_sigreturn, (char *)(frame->retcode + 1)) ||
__put_user(0x00, (char *)(frame->retcode + 2)) ||
__put_user(0xf0, (char *)(frame->retcode + 3)) ||
__put_user(0xe0, (char *)(frame->retcode + 4)))
goto give_sigsegv;
flush_icache_range((unsigned long) frame->retcode,
(unsigned long) frame->retcode + 5);
}
/* set up registers for signal handler */
regs->sp = (unsigned long) frame;
regs->pc = (unsigned long) ka->sa.sa_handler;
regs->d0 = sig;
regs->d1 = (unsigned long) &frame->sc;
/* the tracer may want to single-step inside the handler */
if (test_thread_flag(TIF_SINGLESTEP))
ptrace_notify(SIGTRAP);
#if DEBUG_SIG
printk(KERN_DEBUG "SIG deliver %d (%s:%d): sp=%p pc=%lx ra=%p\n",
sig, current->comm, current->pid, frame, regs->pc,
frame->pretcode);
#endif
return 0;
give_sigsegv:
force_sigsegv(sig, current);
return -EFAULT;
}
/*
* set up a realtime signal frame
*/
static int setup_rt_frame(int sig, struct k_sigaction *ka, siginfo_t *info,
sigset_t *set, struct pt_regs *regs)
{
struct rt_sigframe __user *frame;
int rsig;
frame = get_sigframe(ka, regs, sizeof(*frame));
if (!access_ok(VERIFY_WRITE, frame, sizeof(*frame)))
goto give_sigsegv;
rsig = sig;
if (sig < 32 &&
current_thread_info()->exec_domain &&
current_thread_info()->exec_domain->signal_invmap)
rsig = current_thread_info()->exec_domain->signal_invmap[sig];
if (__put_user(rsig, &frame->sig) ||
__put_user(&frame->info, &frame->pinfo) ||
__put_user(&frame->uc, &frame->puc) ||
copy_siginfo_to_user(&frame->info, info))
goto give_sigsegv;
/* create the ucontext. */
if (__put_user(0, &frame->uc.uc_flags) ||
__put_user(0, &frame->uc.uc_link) ||
__put_user((void *)current->sas_ss_sp, &frame->uc.uc_stack.ss_sp) ||
__put_user(sas_ss_flags(regs->sp), &frame->uc.uc_stack.ss_flags) ||
__put_user(current->sas_ss_size, &frame->uc.uc_stack.ss_size) ||
setup_sigcontext(&frame->uc.uc_mcontext,
&frame->fpuctx, regs, set->sig[0]) ||
__copy_to_user(&frame->uc.uc_sigmask, set, sizeof(*set)))
goto give_sigsegv;
/* set up to return from userspace. If provided, use a stub already in
* userspace */
if (ka->sa.sa_flags & SA_RESTORER) {
if (__put_user(ka->sa.sa_restorer, &frame->pretcode))
goto give_sigsegv;
} else {
if (__put_user((void(*)(void))frame->retcode,
&frame->pretcode) ||
/* This is mov $,d0; syscall 0 */
__put_user(0x2c, (char *)(frame->retcode + 0)) ||
__put_user(__NR_rt_sigreturn,
(char *)(frame->retcode + 1)) ||
__put_user(0x00, (char *)(frame->retcode + 2)) ||
__put_user(0xf0, (char *)(frame->retcode + 3)) ||
__put_user(0xe0, (char *)(frame->retcode + 4)))
goto give_sigsegv;
flush_icache_range((u_long) frame->retcode,
(u_long) frame->retcode + 5);
}
/* Set up registers for signal handler */
regs->sp = (unsigned long) frame;
regs->pc = (unsigned long) ka->sa.sa_handler;
regs->d0 = sig;
regs->d1 = (long) &frame->info;
/* the tracer may want to single-step inside the handler */
if (test_thread_flag(TIF_SINGLESTEP))
ptrace_notify(SIGTRAP);
#if DEBUG_SIG
printk(KERN_DEBUG "SIG deliver %d (%s:%d): sp=%p pc=%lx ra=%p\n",
sig, current->comm, current->pid, frame, regs->pc,
frame->pretcode);
#endif
return 0;
give_sigsegv:
force_sigsegv(sig, current);
return -EFAULT;
}
static inline void stepback(struct pt_regs *regs)
{
regs->pc -= 2;
regs->orig_d0 = -1;
}
/*
* handle the actual delivery of a signal to userspace
*/
static int handle_signal(int sig,
siginfo_t *info, struct k_sigaction *ka,
sigset_t *oldset, struct pt_regs *regs)
{
int ret;
/* Are we from a system call? */
if (regs->orig_d0 >= 0) {
/* If so, check system call restarting.. */
switch (regs->d0) {
case -ERESTART_RESTARTBLOCK:
case -ERESTARTNOHAND:
regs->d0 = -EINTR;
break;
case -ERESTARTSYS:
if (!(ka->sa.sa_flags & SA_RESTART)) {
regs->d0 = -EINTR;
break;
}
/* fallthrough */
case -ERESTARTNOINTR:
regs->d0 = regs->orig_d0;
stepback(regs);
}
}
/* Set up the stack frame */
if (ka->sa.sa_flags & SA_SIGINFO)
ret = setup_rt_frame(sig, ka, info, oldset, regs);
else
ret = setup_frame(sig, ka, oldset, regs);
if (ret == 0) {
spin_lock_irq(¤t->sighand->siglock);
sigorsets(¤t->blocked, ¤t->blocked,
&ka->sa.sa_mask);
if (!(ka->sa.sa_flags & SA_NODEFER))
sigaddset(¤t->blocked, sig);
recalc_sigpending();
spin_unlock_irq(¤t->sighand->siglock);
}
return ret;
}
/*
* handle a potential signal
*/
static void do_signal(struct pt_regs *regs)
{
struct k_sigaction ka;
siginfo_t info;
sigset_t *oldset;
int signr;
/* we want the common case to go fast, which is why we may in certain
* cases get here from kernel mode */
if (!user_mode(regs))
return;
if (test_thread_flag(TIF_RESTORE_SIGMASK))
oldset = ¤t->saved_sigmask;
else
oldset = ¤t->blocked;
signr = get_signal_to_deliver(&info, &ka, regs, NULL);
if (signr > 0) {
if (handle_signal(signr, &info, &ka, oldset, regs) == 0) {
/* a signal was successfully delivered; the saved
* sigmask will have been stored in the signal frame,
* and will be restored by sigreturn, so we can simply
* clear the TIF_RESTORE_SIGMASK flag */
if (test_thread_flag(TIF_RESTORE_SIGMASK))
clear_thread_flag(TIF_RESTORE_SIGMASK);
tracehook_signal_handler(signr, &info, &ka, regs,
test_thread_flag(TIF_SINGLESTEP));
}
return;
}
/* did we come from a system call? */
if (regs->orig_d0 >= 0) {
/* restart the system call - no handlers present */
switch (regs->d0) {
case -ERESTARTNOHAND:
case -ERESTARTSYS:
case -ERESTARTNOINTR:
regs->d0 = regs->orig_d0;
stepback(regs);
break;
case -ERESTART_RESTARTBLOCK:
regs->d0 = __NR_restart_syscall;
stepback(regs);
break;
}
}
/* if there's no signal to deliver, we just put the saved sigmask
* back */
if (test_thread_flag(TIF_RESTORE_SIGMASK)) {
clear_thread_flag(TIF_RESTORE_SIGMASK);
sigprocmask(SIG_SETMASK, ¤t->saved_sigmask, NULL);
}
}
/*
* notification of userspace execution resumption
* - triggered by current->work.notify_resume
*/
asmlinkage void do_notify_resume(struct pt_regs *regs, u32 thread_info_flags)
{
/* Pending single-step? */
if (thread_info_flags & _TIF_SINGLESTEP) {
#ifndef CONFIG_MN10300_USING_JTAG
regs->epsw |= EPSW_T;
clear_thread_flag(TIF_SINGLESTEP);
#else
BUG(); /* no h/w single-step if using JTAG unit */
#endif
}
/* deal with pending signal delivery */
if (thread_info_flags & (_TIF_SIGPENDING | _TIF_RESTORE_SIGMASK))
do_signal(regs);
if (thread_info_flags & _TIF_NOTIFY_RESUME) {
clear_thread_flag(TIF_NOTIFY_RESUME);
tracehook_notify_resume(current_frame());
if (current->replacement_session_keyring)
key_replace_session_keyring();
}
}
| gpl-2.0 |
KhasMek/kernel_matricom_mx2 | net/sunrpc/auth_gss/gss_krb5_seqnum.c | 11630 | 4619 | /*
* linux/net/sunrpc/gss_krb5_seqnum.c
*
* Adapted from MIT Kerberos 5-1.2.1 lib/gssapi/krb5/util_seqnum.c
*
* Copyright (c) 2000 The Regents of the University of Michigan.
* All rights reserved.
*
* Andy Adamson <andros@umich.edu>
*/
/*
* Copyright 1993 by OpenVision Technologies, Inc.
*
* Permission to use, copy, modify, distribute, and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appears in all copies and
* that both that copyright notice and this permission notice appear in
* supporting documentation, and that the name of OpenVision not be used
* in advertising or publicity pertaining to distribution of the software
* without specific, written prior permission. OpenVision makes no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied warranty.
*
* OPENVISION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
* EVENT SHALL OPENVISION BE LIABLE FOR ANY SPECIAL, INDIRECT OR
* CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
* USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
#include <linux/types.h>
#include <linux/sunrpc/gss_krb5.h>
#include <linux/crypto.h>
#ifdef RPC_DEBUG
# define RPCDBG_FACILITY RPCDBG_AUTH
#endif
static s32
krb5_make_rc4_seq_num(struct krb5_ctx *kctx, int direction, s32 seqnum,
unsigned char *cksum, unsigned char *buf)
{
struct crypto_blkcipher *cipher;
unsigned char plain[8];
s32 code;
dprintk("RPC: %s:\n", __func__);
cipher = crypto_alloc_blkcipher(kctx->gk5e->encrypt_name, 0,
CRYPTO_ALG_ASYNC);
if (IS_ERR(cipher))
return PTR_ERR(cipher);
plain[0] = (unsigned char) ((seqnum >> 24) & 0xff);
plain[1] = (unsigned char) ((seqnum >> 16) & 0xff);
plain[2] = (unsigned char) ((seqnum >> 8) & 0xff);
plain[3] = (unsigned char) ((seqnum >> 0) & 0xff);
plain[4] = direction;
plain[5] = direction;
plain[6] = direction;
plain[7] = direction;
code = krb5_rc4_setup_seq_key(kctx, cipher, cksum);
if (code)
goto out;
code = krb5_encrypt(cipher, cksum, plain, buf, 8);
out:
crypto_free_blkcipher(cipher);
return code;
}
s32
krb5_make_seq_num(struct krb5_ctx *kctx,
struct crypto_blkcipher *key,
int direction,
u32 seqnum,
unsigned char *cksum, unsigned char *buf)
{
unsigned char plain[8];
if (kctx->enctype == ENCTYPE_ARCFOUR_HMAC)
return krb5_make_rc4_seq_num(kctx, direction, seqnum,
cksum, buf);
plain[0] = (unsigned char) (seqnum & 0xff);
plain[1] = (unsigned char) ((seqnum >> 8) & 0xff);
plain[2] = (unsigned char) ((seqnum >> 16) & 0xff);
plain[3] = (unsigned char) ((seqnum >> 24) & 0xff);
plain[4] = direction;
plain[5] = direction;
plain[6] = direction;
plain[7] = direction;
return krb5_encrypt(key, cksum, plain, buf, 8);
}
static s32
krb5_get_rc4_seq_num(struct krb5_ctx *kctx, unsigned char *cksum,
unsigned char *buf, int *direction, s32 *seqnum)
{
struct crypto_blkcipher *cipher;
unsigned char plain[8];
s32 code;
dprintk("RPC: %s:\n", __func__);
cipher = crypto_alloc_blkcipher(kctx->gk5e->encrypt_name, 0,
CRYPTO_ALG_ASYNC);
if (IS_ERR(cipher))
return PTR_ERR(cipher);
code = krb5_rc4_setup_seq_key(kctx, cipher, cksum);
if (code)
goto out;
code = krb5_decrypt(cipher, cksum, buf, plain, 8);
if (code)
goto out;
if ((plain[4] != plain[5]) || (plain[4] != plain[6])
|| (plain[4] != plain[7])) {
code = (s32)KG_BAD_SEQ;
goto out;
}
*direction = plain[4];
*seqnum = ((plain[0] << 24) | (plain[1] << 16) |
(plain[2] << 8) | (plain[3]));
out:
crypto_free_blkcipher(cipher);
return code;
}
s32
krb5_get_seq_num(struct krb5_ctx *kctx,
unsigned char *cksum,
unsigned char *buf,
int *direction, u32 *seqnum)
{
s32 code;
unsigned char plain[8];
struct crypto_blkcipher *key = kctx->seq;
dprintk("RPC: krb5_get_seq_num:\n");
if (kctx->enctype == ENCTYPE_ARCFOUR_HMAC)
return krb5_get_rc4_seq_num(kctx, cksum, buf,
direction, seqnum);
if ((code = krb5_decrypt(key, cksum, buf, plain, 8)))
return code;
if ((plain[4] != plain[5]) || (plain[4] != plain[6]) ||
(plain[4] != plain[7]))
return (s32)KG_BAD_SEQ;
*direction = plain[4];
*seqnum = ((plain[0]) |
(plain[1] << 8) | (plain[2] << 16) | (plain[3] << 24));
return 0;
}
| gpl-2.0 |
mazen912/rk30_r-box_kernel | drivers/infiniband/hw/qib/qib_pio_copy.c | 14702 | 2273 | /*
* Copyright (c) 2009 QLogic Corporation. 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 "qib.h"
/**
* qib_pio_copy - copy data to MMIO space, in multiples of 32-bits
* @to: destination, in MMIO space (must be 64-bit aligned)
* @from: source (must be 64-bit aligned)
* @count: number of 32-bit quantities to copy
*
* Copy data from kernel space to MMIO space, in multiples of 32 bits at a
* time. Order of access is not guaranteed, nor is a memory barrier
* performed afterwards.
*/
void qib_pio_copy(void __iomem *to, const void *from, size_t count)
{
#ifdef CONFIG_64BIT
u64 __iomem *dst = to;
const u64 *src = from;
const u64 *end = src + (count >> 1);
while (src < end)
__raw_writeq(*src++, dst++);
if (count & 1)
__raw_writel(*(const u32 *)src, dst);
#else
u32 __iomem *dst = to;
const u32 *src = from;
const u32 *end = src + count;
while (src < end)
__raw_writel(*src++, dst++);
#endif
}
| gpl-2.0 |
mageec/mageec-gcc | gcc/testsuite/gcc.target/mips/mips-3d-2.c | 111 | 10025 | /* { dg-do run } */
/* { dg-options "-mips3d" } */
/* Test MIPS-3D branch-if-any-two builtin functions */
#include <stdlib.h>
#include <stdio.h>
typedef float v2sf __attribute__ ((vector_size(8)));
NOMIPS16 int test0 (v2sf a, v2sf b);
NOMIPS16 int test1 (v2sf a, v2sf b);
NOMIPS16 int test2 (v2sf a, v2sf b);
NOMIPS16 int test3 (v2sf a, v2sf b);
NOMIPS16 int test4 (v2sf a, v2sf b);
NOMIPS16 int test5 (v2sf a, v2sf b);
NOMIPS16 int test6 (v2sf a, v2sf b);
NOMIPS16 int test7 (v2sf a, v2sf b);
NOMIPS16 int test8 (v2sf a, v2sf b);
NOMIPS16 int test9 (v2sf a, v2sf b);
NOMIPS16 int test10 (v2sf a, v2sf b);
NOMIPS16 int test11 (v2sf a, v2sf b);
NOMIPS16 int test12 (v2sf a, v2sf b);
NOMIPS16 int test13 (v2sf a, v2sf b);
NOMIPS16 int test14 (v2sf a, v2sf b);
NOMIPS16 int test15 (v2sf a, v2sf b);
NOMIPS16 int test16 (v2sf a, v2sf b);
NOMIPS16 int test17 (v2sf a, v2sf b);
NOMIPS16 int test18 (v2sf a, v2sf b);
NOMIPS16 int test19 (v2sf a, v2sf b);
NOMIPS16 int test20 (v2sf a, v2sf b);
NOMIPS16 int test21 (v2sf a, v2sf b);
NOMIPS16 int test22 (v2sf a, v2sf b);
NOMIPS16 int test23 (v2sf a, v2sf b);
NOMIPS16 int test24 (v2sf a, v2sf b);
NOMIPS16 int test25 (v2sf a, v2sf b);
NOMIPS16 int test26 (v2sf a, v2sf b);
NOMIPS16 int test27 (v2sf a, v2sf b);
NOMIPS16 int test28 (v2sf a, v2sf b);
NOMIPS16 int test29 (v2sf a, v2sf b);
NOMIPS16 int test30 (v2sf a, v2sf b);
NOMIPS16 int test31 (v2sf a, v2sf b);
float qnan = 1.0f/0.0f - 1.0f/0.0f;
NOMIPS16 int main ()
{
v2sf a, b, c, d;
int i, j;
/* c.eq.ps */
a = (v2sf) {12, 34};
b = (v2sf) {56, 78};
i = 0;
j = 0;
if (__builtin_mips_any_c_eq_ps(a, b) != i)
abort ();
if (__builtin_mips_all_c_eq_ps(a, b) != j)
abort ();
/* c.eq.ps */
a = (v2sf) {12, 34};
b = (v2sf) {12, 78};
i = 1;
j = 0;
if (__builtin_mips_any_c_eq_ps(a, b) != i)
abort ();
if (__builtin_mips_all_c_eq_ps(a, b) != j)
abort ();
/* c.eq.ps */
a = (v2sf) {12, 34};
b = (v2sf) {56, 34};
i = 1;
j = 0;
if (__builtin_mips_any_c_eq_ps(a, b) != i)
abort ();
if (__builtin_mips_all_c_eq_ps(a, b) != j)
abort ();
/* c.eq.ps */
a = (v2sf) {12, 34};
b = (v2sf) {12, 34};
i = 1;
j = 1;
if (__builtin_mips_any_c_eq_ps(a, b) != i)
abort ();
if (__builtin_mips_all_c_eq_ps(a, b) != j)
abort ();
/* Test with 16 operators */
a = (v2sf) {10.58, 1984.0};
b = (v2sf) {567.345, 1984.0};
i = test0 (a, b);
if (i != 0)
abort ();
i = test1 (a, b);
if (i != 0)
abort ();
i = test2 (a, b);
if (i != 0)
abort ();
i = test3 (a, b);
if (i != 0)
abort ();
i = test4 (a, b);
if (i != 1)
abort ();
i = test5 (a, b);
if (i != 0)
abort ();
i = test6 (a, b);
if (i != 1)
abort ();
i = test7 (a, b);
if (i != 0)
abort ();
i = test8 (a, b);
if (i != 1)
abort ();
i = test9 (a, b);
if (i != 0)
abort ();
i = test10 (a, b);
if (i != 1)
abort ();
i = test11 (a, b);
if (i != 0)
abort ();
i = test12 (a, b);
if (i != 1)
abort ();
i = test13 (a, b);
if (i != 1)
abort ();
i = test14 (a, b);
if (i != 1)
abort ();
i = test15 (a, b);
if (i != 1)
abort ();
i = test16 (a, b);
if (i != 0)
abort ();
i = test17 (a, b);
if (i != 0)
abort ();
i = test18 (a, b);
if (i != 0)
abort ();
i = test19 (a, b);
if (i != 0)
abort ();
i = test20 (a, b);
if (i != 1)
abort ();
i = test21 (a, b);
if (i != 0)
abort ();
i = test22 (a, b);
if (i != 1)
abort ();
i = test23 (a, b);
if (i != 0)
abort ();
i = test24 (a, b);
if (i != 1)
abort ();
i = test25 (a, b);
if (i != 0)
abort ();
i = test26 (a, b);
if (i != 1)
abort ();
i = test27 (a, b);
if (i != 0)
abort ();
i = test28 (a, b);
if (i != 1)
abort ();
i = test29 (a, b);
if (i != 1)
abort ();
i = test30 (a, b);
if (i != 1)
abort ();
i = test31 (a, b);
if (i != 1)
abort ();
/* Reverse arguments */
i = test0 (b, a);
if (i != 0)
abort ();
i = test1 (b, a);
if (i != 0)
abort ();
i = test2 (b, a);
if (i != 0)
abort ();
i = test3 (b, a);
if (i != 0)
abort ();
i = test4 (b, a);
if (i != 1)
abort ();
i = test5 (b, a);
if (i != 0)
abort ();
i = test6 (b, a);
if (i != 1)
abort ();
i = test7 (b, a);
if (i != 0)
abort ();
i = test8 (b, a);
if (i != 0)
abort ();
i = test9 (b, a);
if (i != 0)
abort ();
i = test10 (b, a);
if (i != 0)
abort ();
i = test11 (b, a);
if (i != 0)
abort ();
i = test12 (b, a);
if (i != 1)
abort ();
i = test13 (b, a);
if (i != 0)
abort ();
i = test14 (b, a);
if (i != 1)
abort ();
i = test15 (b, a);
if (i != 0)
abort ();
i = test16 (b, a);
if (i != 0)
abort ();
i = test17 (b, a);
if (i != 0)
abort ();
i = test18 (b, a);
if (i != 0)
abort ();
i = test19 (b, a);
if (i != 0)
abort ();
i = test20 (b, a);
if (i != 1)
abort ();
i = test21 (b, a);
if (i != 0)
abort ();
i = test22 (b, a);
if (i != 1)
abort ();
i = test23 (b, a);
if (i != 0)
abort ();
i = test24 (b, a);
if (i != 0)
abort ();
i = test25 (b, a);
if (i != 0)
abort ();
i = test26 (b, a);
if (i != 0)
abort ();
i = test27 (b, a);
if (i != 0)
abort ();
i = test28 (b, a);
if (i != 1)
abort ();
i = test29 (b, a);
if (i != 0)
abort ();
i = test30 (b, a);
if (i != 1)
abort ();
i = test31 (b, a);
if (i != 0)
abort ();
#ifndef __FAST_MATH__
/* Test with 16 operators */
a = (v2sf) {qnan, qnan};
b = (v2sf) {567.345, 1984.0};
i = test0 (a, b);
if (i != 0)
abort ();
i = test1 (a, b);
if (i != 0)
abort ();
i = test2 (a, b);
if (i != 1)
abort ();
i = test3 (a, b);
if (i != 1)
abort ();
i = test4 (a, b);
if (i != 0)
abort ();
i = test5 (a, b);
if (i != 0)
abort ();
i = test6 (a, b);
if (i != 1)
abort ();
i = test7 (a, b);
if (i != 1)
abort ();
i = test8 (a, b);
if (i != 0)
abort ();
i = test9 (a, b);
if (i != 0)
abort ();
i = test10 (a, b);
if (i != 1)
abort ();
i = test11 (a, b);
if (i != 1)
abort ();
i = test12 (a, b);
if (i != 0)
abort ();
i = test13 (a, b);
if (i != 0)
abort ();
i = test14 (a, b);
if (i != 1)
abort ();
i = test15 (a, b);
if (i != 1)
abort ();
i = test16 (a, b);
if (i != 0)
abort ();
i = test17 (a, b);
if (i != 0)
abort ();
i = test18 (a, b);
if (i != 1)
abort ();
i = test19 (a, b);
if (i != 1)
abort ();
i = test20 (a, b);
if (i != 0)
abort ();
i = test21 (a, b);
if (i != 0)
abort ();
i = test22 (a, b);
if (i != 1)
abort ();
i = test23 (a, b);
if (i != 1)
abort ();
i = test24 (a, b);
if (i != 0)
abort ();
i = test25 (a, b);
if (i != 0)
abort ();
i = test26 (a, b);
if (i != 1)
abort ();
i = test27 (a, b);
if (i != 1)
abort ();
i = test28 (a, b);
if (i != 0)
abort ();
i = test29 (a, b);
if (i != 0)
abort ();
i = test30 (a, b);
if (i != 1)
abort ();
i = test31 (a, b);
if (i != 1)
abort ();
#endif
printf ("Test Passes\n");
exit (0);
}
NOMIPS16 int test0 (v2sf a, v2sf b)
{
return __builtin_mips_any_c_f_ps (a, b);
}
NOMIPS16 int test1 (v2sf a, v2sf b)
{
return __builtin_mips_all_c_f_ps (a, b);
}
NOMIPS16 int test2 (v2sf a, v2sf b)
{
return __builtin_mips_any_c_un_ps (a, b);
}
NOMIPS16 int test3 (v2sf a, v2sf b)
{
return __builtin_mips_all_c_un_ps (a, b);
}
NOMIPS16 int test4 (v2sf a, v2sf b)
{
return __builtin_mips_any_c_eq_ps (a, b);
}
NOMIPS16 int test5 (v2sf a, v2sf b)
{
return __builtin_mips_all_c_eq_ps (a, b);
}
NOMIPS16 int test6 (v2sf a, v2sf b)
{
return __builtin_mips_any_c_ueq_ps (a, b);
}
NOMIPS16 int test7 (v2sf a, v2sf b)
{
return __builtin_mips_all_c_ueq_ps (a, b);
}
NOMIPS16 int test8 (v2sf a, v2sf b)
{
return __builtin_mips_any_c_olt_ps (a, b);
}
NOMIPS16 int test9 (v2sf a, v2sf b)
{
return __builtin_mips_all_c_olt_ps (a, b);
}
NOMIPS16 int test10 (v2sf a, v2sf b)
{
return __builtin_mips_any_c_ult_ps (a, b);
}
NOMIPS16 int test11 (v2sf a, v2sf b)
{
return __builtin_mips_all_c_ult_ps (a, b);
}
NOMIPS16 int test12 (v2sf a, v2sf b)
{
return __builtin_mips_any_c_ole_ps (a, b);
}
NOMIPS16 int test13 (v2sf a, v2sf b)
{
return __builtin_mips_all_c_ole_ps (a, b);
}
NOMIPS16 int test14 (v2sf a, v2sf b)
{
return __builtin_mips_any_c_ule_ps (a, b);
}
NOMIPS16 int test15 (v2sf a, v2sf b)
{
return __builtin_mips_all_c_ule_ps (a, b);
}
NOMIPS16 int test16 (v2sf a, v2sf b)
{
return __builtin_mips_any_c_sf_ps (a, b);
}
NOMIPS16 int test17 (v2sf a, v2sf b)
{
return __builtin_mips_all_c_sf_ps (a, b);
}
NOMIPS16 int test18 (v2sf a, v2sf b)
{
return __builtin_mips_any_c_ngle_ps (a, b);
}
NOMIPS16 int test19 (v2sf a, v2sf b)
{
return __builtin_mips_all_c_ngle_ps (a, b);
}
NOMIPS16 int test20 (v2sf a, v2sf b)
{
return __builtin_mips_any_c_seq_ps (a, b);
}
NOMIPS16 int test21 (v2sf a, v2sf b)
{
return __builtin_mips_all_c_seq_ps (a, b);
}
NOMIPS16 int test22 (v2sf a, v2sf b)
{
return __builtin_mips_any_c_ngl_ps (a, b);
}
NOMIPS16 int test23 (v2sf a, v2sf b)
{
return __builtin_mips_all_c_ngl_ps (a, b);
}
NOMIPS16 int test24 (v2sf a, v2sf b)
{
return __builtin_mips_any_c_lt_ps (a, b);
}
NOMIPS16 int test25 (v2sf a, v2sf b)
{
return __builtin_mips_all_c_lt_ps (a, b);
}
NOMIPS16 int test26 (v2sf a, v2sf b)
{
return __builtin_mips_any_c_nge_ps (a, b);
}
NOMIPS16 int test27 (v2sf a, v2sf b)
{
return __builtin_mips_all_c_nge_ps (a, b);
}
NOMIPS16 int test28 (v2sf a, v2sf b)
{
return __builtin_mips_any_c_le_ps (a, b);
}
NOMIPS16 int test29 (v2sf a, v2sf b)
{
return __builtin_mips_all_c_le_ps (a, b);
}
NOMIPS16 int test30 (v2sf a, v2sf b)
{
return __builtin_mips_any_c_ngt_ps (a, b);
}
NOMIPS16 int test31 (v2sf a, v2sf b)
{
return __builtin_mips_all_c_ngt_ps (a, b);
}
| gpl-2.0 |
HuChundong/endeavoru_3.18 | arch/x86/kernel/process_64.c | 111 | 16402 | /*
* Copyright (C) 1995 Linus Torvalds
*
* Pentium III FXSR, SSE support
* Gareth Hughes <gareth@valinux.com>, May 2000
*
* X86-64 port
* Andi Kleen.
*
* CPU hotplug support - ashok.raj@intel.com
*/
/*
* This file handles the architecture-dependent parts of process handling..
*/
#include <linux/stackprotector.h>
#include <linux/cpu.h>
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/elfcore.h>
#include <linux/smp.h>
#include <linux/slab.h>
#include <linux/user.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/module.h>
#include <linux/ptrace.h>
#include <linux/notifier.h>
#include <linux/kprobes.h>
#include <linux/kdebug.h>
#include <linux/tick.h>
#include <linux/prctl.h>
#include <linux/uaccess.h>
#include <linux/io.h>
#include <linux/ftrace.h>
#include <linux/cpuidle.h>
#include <asm/pgtable.h>
#include <asm/system.h>
#include <asm/processor.h>
#include <asm/i387.h>
#include <asm/mmu_context.h>
#include <asm/prctl.h>
#include <asm/desc.h>
#include <asm/proto.h>
#include <asm/ia32.h>
#include <asm/idle.h>
#include <asm/syscalls.h>
#include <asm/debugreg.h>
asmlinkage extern void ret_from_fork(void);
DEFINE_PER_CPU(unsigned long, old_rsp);
static DEFINE_PER_CPU(unsigned char, is_idle);
static ATOMIC_NOTIFIER_HEAD(idle_notifier);
void idle_notifier_register(struct notifier_block *n)
{
atomic_notifier_chain_register(&idle_notifier, n);
}
EXPORT_SYMBOL_GPL(idle_notifier_register);
void idle_notifier_unregister(struct notifier_block *n)
{
atomic_notifier_chain_unregister(&idle_notifier, n);
}
EXPORT_SYMBOL_GPL(idle_notifier_unregister);
void enter_idle(void)
{
percpu_write(is_idle, 1);
atomic_notifier_call_chain(&idle_notifier, IDLE_START, NULL);
}
static void __exit_idle(void)
{
if (x86_test_and_clear_bit_percpu(0, is_idle) == 0)
return;
atomic_notifier_call_chain(&idle_notifier, IDLE_END, NULL);
}
/* Called from interrupts to signify idle end */
void exit_idle(void)
{
/* idle loop has pid 0 */
if (current->pid)
return;
__exit_idle();
}
#ifndef CONFIG_SMP
static inline void play_dead(void)
{
BUG();
}
#endif
/*
* The idle thread. There's no useful work to be
* done, so just try to conserve power and have a
* low exit latency (ie sit in a loop waiting for
* somebody to say that they'd like to reschedule)
*/
void cpu_idle(void)
{
current_thread_info()->status |= TS_POLLING;
/*
* If we're the non-boot CPU, nothing set the stack canary up
* for us. CPU0 already has it initialized but no harm in
* doing it again. This is a good place for updating it, as
* we wont ever return from this function (so the invalid
* canaries already on the stack wont ever trigger).
*/
boot_init_stack_canary();
/* endless idle loop with no priority at all */
while (1) {
tick_nohz_stop_sched_tick(1);
while (!need_resched()) {
rmb();
if (cpu_is_offline(smp_processor_id()))
play_dead();
/*
* Idle routines should keep interrupts disabled
* from here on, until they go to idle.
* Otherwise, idle callbacks can misfire.
*/
local_irq_disable();
enter_idle();
/* Don't trace irqs off for idle */
stop_critical_timings();
if (cpuidle_idle_call())
pm_idle();
start_critical_timings();
/* In many cases the interrupt that ended idle
has already called exit_idle. But some idle
loops can be woken up without interrupt. */
__exit_idle();
}
tick_nohz_restart_sched_tick();
preempt_enable_no_resched();
schedule();
preempt_disable();
}
}
/* Prints also some state that isn't saved in the pt_regs */
void __show_regs(struct pt_regs *regs, int all)
{
unsigned long cr0 = 0L, cr2 = 0L, cr3 = 0L, cr4 = 0L, fs, gs, shadowgs;
unsigned long d0, d1, d2, d3, d6, d7;
unsigned int fsindex, gsindex;
unsigned int ds, cs, es;
show_regs_common();
printk(KERN_DEFAULT "RIP: %04lx:[<%016lx>] ", regs->cs & 0xffff, regs->ip);
printk_address(regs->ip, 1);
printk(KERN_DEFAULT "RSP: %04lx:%016lx EFLAGS: %08lx\n", regs->ss,
regs->sp, regs->flags);
printk(KERN_DEFAULT "RAX: %016lx RBX: %016lx RCX: %016lx\n",
regs->ax, regs->bx, regs->cx);
printk(KERN_DEFAULT "RDX: %016lx RSI: %016lx RDI: %016lx\n",
regs->dx, regs->si, regs->di);
printk(KERN_DEFAULT "RBP: %016lx R08: %016lx R09: %016lx\n",
regs->bp, regs->r8, regs->r9);
printk(KERN_DEFAULT "R10: %016lx R11: %016lx R12: %016lx\n",
regs->r10, regs->r11, regs->r12);
printk(KERN_DEFAULT "R13: %016lx R14: %016lx R15: %016lx\n",
regs->r13, regs->r14, regs->r15);
asm("movl %%ds,%0" : "=r" (ds));
asm("movl %%cs,%0" : "=r" (cs));
asm("movl %%es,%0" : "=r" (es));
asm("movl %%fs,%0" : "=r" (fsindex));
asm("movl %%gs,%0" : "=r" (gsindex));
rdmsrl(MSR_FS_BASE, fs);
rdmsrl(MSR_GS_BASE, gs);
rdmsrl(MSR_KERNEL_GS_BASE, shadowgs);
if (!all)
return;
cr0 = read_cr0();
cr2 = read_cr2();
cr3 = read_cr3();
cr4 = read_cr4();
printk(KERN_DEFAULT "FS: %016lx(%04x) GS:%016lx(%04x) knlGS:%016lx\n",
fs, fsindex, gs, gsindex, shadowgs);
printk(KERN_DEFAULT "CS: %04x DS: %04x ES: %04x CR0: %016lx\n", cs, ds,
es, cr0);
printk(KERN_DEFAULT "CR2: %016lx CR3: %016lx CR4: %016lx\n", cr2, cr3,
cr4);
get_debugreg(d0, 0);
get_debugreg(d1, 1);
get_debugreg(d2, 2);
printk(KERN_DEFAULT "DR0: %016lx DR1: %016lx DR2: %016lx\n", d0, d1, d2);
get_debugreg(d3, 3);
get_debugreg(d6, 6);
get_debugreg(d7, 7);
printk(KERN_DEFAULT "DR3: %016lx DR6: %016lx DR7: %016lx\n", d3, d6, d7);
}
void release_thread(struct task_struct *dead_task)
{
if (dead_task->mm) {
if (dead_task->mm->context.size) {
printk("WARNING: dead process %8s still has LDT? <%p/%d>\n",
dead_task->comm,
dead_task->mm->context.ldt,
dead_task->mm->context.size);
BUG();
}
}
}
static inline void set_32bit_tls(struct task_struct *t, int tls, u32 addr)
{
struct user_desc ud = {
.base_addr = addr,
.limit = 0xfffff,
.seg_32bit = 1,
.limit_in_pages = 1,
.useable = 1,
};
struct desc_struct *desc = t->thread.tls_array;
desc += tls;
fill_ldt(desc, &ud);
}
static inline u32 read_32bit_tls(struct task_struct *t, int tls)
{
return get_desc_base(&t->thread.tls_array[tls]);
}
/*
* This gets called before we allocate a new thread and copy
* the current task into it.
*/
void prepare_to_copy(struct task_struct *tsk)
{
unlazy_fpu(tsk);
}
int copy_thread(unsigned long clone_flags, unsigned long sp,
unsigned long unused,
struct task_struct *p, struct pt_regs *regs)
{
int err;
struct pt_regs *childregs;
struct task_struct *me = current;
childregs = ((struct pt_regs *)
(THREAD_SIZE + task_stack_page(p))) - 1;
*childregs = *regs;
childregs->ax = 0;
if (user_mode(regs))
childregs->sp = sp;
else
childregs->sp = (unsigned long)childregs;
p->thread.sp = (unsigned long) childregs;
p->thread.sp0 = (unsigned long) (childregs+1);
p->thread.usersp = me->thread.usersp;
set_tsk_thread_flag(p, TIF_FORK);
p->thread.io_bitmap_ptr = NULL;
savesegment(gs, p->thread.gsindex);
p->thread.gs = p->thread.gsindex ? 0 : me->thread.gs;
savesegment(fs, p->thread.fsindex);
p->thread.fs = p->thread.fsindex ? 0 : me->thread.fs;
savesegment(es, p->thread.es);
savesegment(ds, p->thread.ds);
err = -ENOMEM;
memset(p->thread.ptrace_bps, 0, sizeof(p->thread.ptrace_bps));
if (unlikely(test_tsk_thread_flag(me, TIF_IO_BITMAP))) {
p->thread.io_bitmap_ptr = kmalloc(IO_BITMAP_BYTES, GFP_KERNEL);
if (!p->thread.io_bitmap_ptr) {
p->thread.io_bitmap_max = 0;
return -ENOMEM;
}
memcpy(p->thread.io_bitmap_ptr, me->thread.io_bitmap_ptr,
IO_BITMAP_BYTES);
set_tsk_thread_flag(p, TIF_IO_BITMAP);
}
/*
* Set a new TLS for the child thread?
*/
if (clone_flags & CLONE_SETTLS) {
#ifdef CONFIG_IA32_EMULATION
if (test_thread_flag(TIF_IA32))
err = do_set_thread_area(p, -1,
(struct user_desc __user *)childregs->si, 0);
else
#endif
err = do_arch_prctl(p, ARCH_SET_FS, childregs->r8);
if (err)
goto out;
}
err = 0;
out:
if (err && p->thread.io_bitmap_ptr) {
kfree(p->thread.io_bitmap_ptr);
p->thread.io_bitmap_max = 0;
}
return err;
}
static void
start_thread_common(struct pt_regs *regs, unsigned long new_ip,
unsigned long new_sp,
unsigned int _cs, unsigned int _ss, unsigned int _ds)
{
loadsegment(fs, 0);
loadsegment(es, _ds);
loadsegment(ds, _ds);
load_gs_index(0);
regs->ip = new_ip;
regs->sp = new_sp;
percpu_write(old_rsp, new_sp);
regs->cs = _cs;
regs->ss = _ss;
regs->flags = X86_EFLAGS_IF;
/*
* Free the old FP and other extended state
*/
free_thread_xstate(current);
}
void
start_thread(struct pt_regs *regs, unsigned long new_ip, unsigned long new_sp)
{
start_thread_common(regs, new_ip, new_sp,
__USER_CS, __USER_DS, 0);
}
#ifdef CONFIG_IA32_EMULATION
void start_thread_ia32(struct pt_regs *regs, u32 new_ip, u32 new_sp)
{
start_thread_common(regs, new_ip, new_sp,
__USER32_CS, __USER32_DS, __USER32_DS);
}
#endif
/*
* switch_to(x,y) should switch tasks from x to y.
*
* This could still be optimized:
* - fold all the options into a flag word and test it with a single test.
* - could test fs/gs bitsliced
*
* Kprobes not supported here. Set the probe on schedule instead.
* Function graph tracer not supported too.
*/
__notrace_funcgraph struct task_struct *
__switch_to(struct task_struct *prev_p, struct task_struct *next_p)
{
struct thread_struct *prev = &prev_p->thread;
struct thread_struct *next = &next_p->thread;
int cpu = smp_processor_id();
struct tss_struct *tss = &per_cpu(init_tss, cpu);
unsigned fsindex, gsindex;
bool preload_fpu;
/*
* If the task has used fpu the last 5 timeslices, just do a full
* restore of the math state immediately to avoid the trap; the
* chances of needing FPU soon are obviously high now
*/
preload_fpu = tsk_used_math(next_p) && next_p->fpu_counter > 5;
/* we're going to use this soon, after a few expensive things */
if (preload_fpu)
prefetch(next->fpu.state);
/*
* Reload esp0, LDT and the page table pointer:
*/
load_sp0(tss, next);
/*
* Switch DS and ES.
* This won't pick up thread selector changes, but I guess that is ok.
*/
savesegment(es, prev->es);
if (unlikely(next->es | prev->es))
loadsegment(es, next->es);
savesegment(ds, prev->ds);
if (unlikely(next->ds | prev->ds))
loadsegment(ds, next->ds);
/* We must save %fs and %gs before load_TLS() because
* %fs and %gs may be cleared by load_TLS().
*
* (e.g. xen_load_tls())
*/
savesegment(fs, fsindex);
savesegment(gs, gsindex);
load_TLS(next, cpu);
/* Must be after DS reload */
__unlazy_fpu(prev_p);
/* Make sure cpu is ready for new context */
if (preload_fpu)
clts();
/*
* Leave lazy mode, flushing any hypercalls made here.
* This must be done before restoring TLS segments so
* the GDT and LDT are properly updated, and must be
* done before math_state_restore, so the TS bit is up
* to date.
*/
arch_end_context_switch(next_p);
/*
* Switch FS and GS.
*
* Segment register != 0 always requires a reload. Also
* reload when it has changed. When prev process used 64bit
* base always reload to avoid an information leak.
*/
if (unlikely(fsindex | next->fsindex | prev->fs)) {
loadsegment(fs, next->fsindex);
/*
* Check if the user used a selector != 0; if yes
* clear 64bit base, since overloaded base is always
* mapped to the Null selector
*/
if (fsindex)
prev->fs = 0;
}
/* when next process has a 64bit base use it */
if (next->fs)
wrmsrl(MSR_FS_BASE, next->fs);
prev->fsindex = fsindex;
if (unlikely(gsindex | next->gsindex | prev->gs)) {
load_gs_index(next->gsindex);
if (gsindex)
prev->gs = 0;
}
if (next->gs)
wrmsrl(MSR_KERNEL_GS_BASE, next->gs);
prev->gsindex = gsindex;
/*
* Switch the PDA and FPU contexts.
*/
prev->usersp = percpu_read(old_rsp);
percpu_write(old_rsp, next->usersp);
percpu_write(current_task, next_p);
percpu_write(kernel_stack,
(unsigned long)task_stack_page(next_p) +
THREAD_SIZE - KERNEL_STACK_OFFSET);
/*
* Now maybe reload the debug registers and handle I/O bitmaps
*/
if (unlikely(task_thread_info(next_p)->flags & _TIF_WORK_CTXSW_NEXT ||
task_thread_info(prev_p)->flags & _TIF_WORK_CTXSW_PREV))
__switch_to_xtra(prev_p, next_p, tss);
/*
* Preload the FPU context, now that we've determined that the
* task is likely to be using it.
*/
if (preload_fpu)
__math_state_restore();
return prev_p;
}
void set_personality_64bit(void)
{
/* inherit personality from parent */
/* Make sure to be in 64bit mode */
clear_thread_flag(TIF_IA32);
/* Ensure the corresponding mm is not marked. */
if (current->mm)
current->mm->context.ia32_compat = 0;
/* TBD: overwrites user setup. Should have two bits.
But 64bit processes have always behaved this way,
so it's not too bad. The main problem is just that
32bit childs are affected again. */
current->personality &= ~READ_IMPLIES_EXEC;
}
void set_personality_ia32(void)
{
/* inherit personality from parent */
/* Make sure to be in 32bit mode */
set_thread_flag(TIF_IA32);
current->personality |= force_personality32;
/* Mark the associated mm as containing 32-bit tasks. */
if (current->mm)
current->mm->context.ia32_compat = 1;
/* Prepare the first "return" to user space */
current_thread_info()->status |= TS_COMPAT;
}
unsigned long get_wchan(struct task_struct *p)
{
unsigned long stack;
u64 fp, ip;
int count = 0;
if (!p || p == current || p->state == TASK_RUNNING)
return 0;
stack = (unsigned long)task_stack_page(p);
if (p->thread.sp < stack || p->thread.sp >= stack+THREAD_SIZE)
return 0;
fp = *(u64 *)(p->thread.sp);
do {
if (fp < (unsigned long)stack ||
fp >= (unsigned long)stack+THREAD_SIZE)
return 0;
ip = *(u64 *)(fp+8);
if (!in_sched_functions(ip))
return ip;
fp = *(u64 *)fp;
} while (count++ < 16);
return 0;
}
long do_arch_prctl(struct task_struct *task, int code, unsigned long addr)
{
int ret = 0;
int doit = task == current;
int cpu;
switch (code) {
case ARCH_SET_GS:
if (addr >= TASK_SIZE_OF(task))
return -EPERM;
cpu = get_cpu();
/* handle small bases via the GDT because that's faster to
switch. */
if (addr <= 0xffffffff) {
set_32bit_tls(task, GS_TLS, addr);
if (doit) {
load_TLS(&task->thread, cpu);
load_gs_index(GS_TLS_SEL);
}
task->thread.gsindex = GS_TLS_SEL;
task->thread.gs = 0;
} else {
task->thread.gsindex = 0;
task->thread.gs = addr;
if (doit) {
load_gs_index(0);
ret = checking_wrmsrl(MSR_KERNEL_GS_BASE, addr);
}
}
put_cpu();
break;
case ARCH_SET_FS:
/* Not strictly needed for fs, but do it for symmetry
with gs */
if (addr >= TASK_SIZE_OF(task))
return -EPERM;
cpu = get_cpu();
/* handle small bases via the GDT because that's faster to
switch. */
if (addr <= 0xffffffff) {
set_32bit_tls(task, FS_TLS, addr);
if (doit) {
load_TLS(&task->thread, cpu);
loadsegment(fs, FS_TLS_SEL);
}
task->thread.fsindex = FS_TLS_SEL;
task->thread.fs = 0;
} else {
task->thread.fsindex = 0;
task->thread.fs = addr;
if (doit) {
/* set the selector to 0 to not confuse
__switch_to */
loadsegment(fs, 0);
ret = checking_wrmsrl(MSR_FS_BASE, addr);
}
}
put_cpu();
break;
case ARCH_GET_FS: {
unsigned long base;
if (task->thread.fsindex == FS_TLS_SEL)
base = read_32bit_tls(task, FS_TLS);
else if (doit)
rdmsrl(MSR_FS_BASE, base);
else
base = task->thread.fs;
ret = put_user(base, (unsigned long __user *)addr);
break;
}
case ARCH_GET_GS: {
unsigned long base;
unsigned gsindex;
if (task->thread.gsindex == GS_TLS_SEL)
base = read_32bit_tls(task, GS_TLS);
else if (doit) {
savesegment(gs, gsindex);
if (gsindex)
rdmsrl(MSR_KERNEL_GS_BASE, base);
else
base = task->thread.gs;
} else
base = task->thread.gs;
ret = put_user(base, (unsigned long __user *)addr);
break;
}
default:
ret = -EINVAL;
break;
}
return ret;
}
long sys_arch_prctl(int code, unsigned long addr)
{
return do_arch_prctl(current, code, addr);
}
unsigned long KSTK_ESP(struct task_struct *task)
{
return (test_tsk_thread_flag(task, TIF_IA32)) ?
(task_pt_regs(task)->sp) : ((task)->thread.usersp);
}
| gpl-2.0 |
fqrouter/openwrt-trunk | target/linux/ramips/files/arch/mips/ralink/common/setup.c | 111 | 2070 | /*
* Ralink SoC common setup
*
* Copyright (C) 2008-2009 Gabor Juhos <juhosg@openwrt.org>
* Copyright (C) 2008 Imre Kaloz <kaloz@openwrt.org>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/serial_8250.h>
#include <asm/bootinfo.h>
#include <asm/addrspace.h>
#include <asm/mach-ralink/common.h>
#include <asm/mach-ralink/machine.h>
unsigned char ramips_sys_type[RAMIPS_SYS_TYPE_LEN];
unsigned long (*ramips_get_mem_size)(void);
const char *get_system_type(void)
{
return ramips_sys_type;
}
static void __init detect_mem_size(void)
{
unsigned long size;
if (ramips_get_mem_size) {
size = ramips_get_mem_size();
} else {
void *base;
base = (void *) KSEG1ADDR(detect_mem_size);
for (size = ramips_mem_size_min; size < ramips_mem_size_max;
size <<= 1 ) {
if (!memcmp(base, base + size, 1024))
break;
}
}
add_memory_region(ramips_mem_base, size, BOOT_MEM_RAM);
}
void __init ramips_early_serial_setup(int line, unsigned base, unsigned freq,
unsigned irq)
{
struct uart_port p;
int err;
memset(&p, 0, sizeof(p));
p.flags = UPF_SKIP_TEST | UPF_FIXED_TYPE;
p.iotype = UPIO_AU;
p.uartclk = freq;
p.regshift = 2;
p.type = PORT_16550A;
p.mapbase = base;
p.membase = ioremap_nocache(p.mapbase, PAGE_SIZE);
p.line = line;
p.irq = irq;
err = early_serial_setup(&p);
if (err)
printk(KERN_ERR "early serial%d registration failed %d\n",
line, err);
}
void __init plat_mem_setup(void)
{
set_io_port_base(KSEG1);
detect_mem_size();
ramips_soc_setup();
}
__setup("board=", mips_machtype_setup);
static int __init ramips_machine_setup(void)
{
mips_machine_setup();
return 0;
}
arch_initcall(ramips_machine_setup);
static void __init ramips_generic_init(void)
{
}
MIPS_MACHINE(RAMIPS_MACH_GENERIC, "Generic", "Generic Ralink board",
ramips_generic_init);
| gpl-2.0 |
telf/TDR_watchdog_RFC_1 | drivers/iio/pressure/hid-sensor-press.c | 111 | 10791 | /*
* HID Sensors Driver
* Copyright (c) 2014, 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.
*
*/
#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/sysfs.h>
#include <linux/iio/buffer.h>
#include <linux/iio/trigger_consumer.h>
#include <linux/iio/triggered_buffer.h>
#include "../common/hid-sensors/hid-sensor-trigger.h"
#define CHANNEL_SCAN_INDEX_PRESSURE 0
struct press_state {
struct hid_sensor_hub_callbacks callbacks;
struct hid_sensor_common common_attributes;
struct hid_sensor_hub_attribute_info press_attr;
u32 press_data;
int scale_pre_decml;
int scale_post_decml;
int scale_precision;
int value_offset;
};
/* Channel definitions */
static const struct iio_chan_spec press_channels[] = {
{
.type = IIO_PRESSURE,
.modified = 1,
.channel2 = IIO_NO_MOD,
.info_mask_separate = BIT(IIO_CHAN_INFO_RAW),
.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_OFFSET) |
BIT(IIO_CHAN_INFO_SCALE) |
BIT(IIO_CHAN_INFO_SAMP_FREQ) |
BIT(IIO_CHAN_INFO_HYSTERESIS),
.scan_index = CHANNEL_SCAN_INDEX_PRESSURE,
}
};
/* Adjust channel real bits based on report descriptor */
static void press_adjust_channel_bit_mask(struct iio_chan_spec *channels,
int channel, int size)
{
channels[channel].scan_type.sign = 's';
/* Real storage bits will change based on the report desc. */
channels[channel].scan_type.realbits = size * 8;
/* Maximum size of a sample to capture is u32 */
channels[channel].scan_type.storagebits = sizeof(u32) * 8;
}
/* Channel read_raw handler */
static int press_read_raw(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan,
int *val, int *val2,
long mask)
{
struct press_state *press_state = iio_priv(indio_dev);
int report_id = -1;
u32 address;
int ret_type;
*val = 0;
*val2 = 0;
switch (mask) {
case IIO_CHAN_INFO_RAW:
switch (chan->scan_index) {
case CHANNEL_SCAN_INDEX_PRESSURE:
report_id = press_state->press_attr.report_id;
address =
HID_USAGE_SENSOR_ATMOSPHERIC_PRESSURE;
break;
default:
report_id = -1;
break;
}
if (report_id >= 0) {
hid_sensor_power_state(&press_state->common_attributes,
true);
*val = sensor_hub_input_attr_get_raw_value(
press_state->common_attributes.hsdev,
HID_USAGE_SENSOR_PRESSURE, address,
report_id);
hid_sensor_power_state(&press_state->common_attributes,
false);
} else {
*val = 0;
return -EINVAL;
}
ret_type = IIO_VAL_INT;
break;
case IIO_CHAN_INFO_SCALE:
*val = press_state->scale_pre_decml;
*val2 = press_state->scale_post_decml;
ret_type = press_state->scale_precision;
break;
case IIO_CHAN_INFO_OFFSET:
*val = press_state->value_offset;
ret_type = IIO_VAL_INT;
break;
case IIO_CHAN_INFO_SAMP_FREQ:
ret_type = hid_sensor_read_samp_freq_value(
&press_state->common_attributes, val, val2);
break;
case IIO_CHAN_INFO_HYSTERESIS:
ret_type = hid_sensor_read_raw_hyst_value(
&press_state->common_attributes, val, val2);
break;
default:
ret_type = -EINVAL;
break;
}
return ret_type;
}
/* Channel write_raw handler */
static int press_write_raw(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan,
int val,
int val2,
long mask)
{
struct press_state *press_state = iio_priv(indio_dev);
int ret = 0;
switch (mask) {
case IIO_CHAN_INFO_SAMP_FREQ:
ret = hid_sensor_write_samp_freq_value(
&press_state->common_attributes, val, val2);
break;
case IIO_CHAN_INFO_HYSTERESIS:
ret = hid_sensor_write_raw_hyst_value(
&press_state->common_attributes, val, val2);
break;
default:
ret = -EINVAL;
}
return ret;
}
static const struct iio_info press_info = {
.driver_module = THIS_MODULE,
.read_raw = &press_read_raw,
.write_raw = &press_write_raw,
};
/* Function to push data to buffer */
static void hid_sensor_push_data(struct iio_dev *indio_dev, const void *data,
int len)
{
dev_dbg(&indio_dev->dev, "hid_sensor_push_data\n");
iio_push_to_buffers(indio_dev, data);
}
/* Callback handler to send event after all samples are received and captured */
static int press_proc_event(struct hid_sensor_hub_device *hsdev,
unsigned usage_id,
void *priv)
{
struct iio_dev *indio_dev = platform_get_drvdata(priv);
struct press_state *press_state = iio_priv(indio_dev);
dev_dbg(&indio_dev->dev, "press_proc_event\n");
if (atomic_read(&press_state->common_attributes.data_ready))
hid_sensor_push_data(indio_dev,
&press_state->press_data,
sizeof(press_state->press_data));
return 0;
}
/* Capture samples in local storage */
static int press_capture_sample(struct hid_sensor_hub_device *hsdev,
unsigned usage_id,
size_t raw_len, char *raw_data,
void *priv)
{
struct iio_dev *indio_dev = platform_get_drvdata(priv);
struct press_state *press_state = iio_priv(indio_dev);
int ret = -EINVAL;
switch (usage_id) {
case HID_USAGE_SENSOR_ATMOSPHERIC_PRESSURE:
press_state->press_data = *(u32 *)raw_data;
ret = 0;
break;
default:
break;
}
return ret;
}
/* Parse report which is specific to an usage id*/
static int press_parse_report(struct platform_device *pdev,
struct hid_sensor_hub_device *hsdev,
struct iio_chan_spec *channels,
unsigned usage_id,
struct press_state *st)
{
int ret;
ret = sensor_hub_input_get_attribute_info(hsdev, HID_INPUT_REPORT,
usage_id,
HID_USAGE_SENSOR_ATMOSPHERIC_PRESSURE,
&st->press_attr);
if (ret < 0)
return ret;
press_adjust_channel_bit_mask(channels, CHANNEL_SCAN_INDEX_PRESSURE,
st->press_attr.size);
dev_dbg(&pdev->dev, "press %x:%x\n", st->press_attr.index,
st->press_attr.report_id);
st->scale_precision = hid_sensor_format_scale(
HID_USAGE_SENSOR_PRESSURE,
&st->press_attr,
&st->scale_pre_decml, &st->scale_post_decml);
/* Set Sensitivity field ids, when there is no individual modifier */
if (st->common_attributes.sensitivity.index < 0) {
sensor_hub_input_get_attribute_info(hsdev,
HID_FEATURE_REPORT, usage_id,
HID_USAGE_SENSOR_DATA_MOD_CHANGE_SENSITIVITY_ABS |
HID_USAGE_SENSOR_DATA_ATMOSPHERIC_PRESSURE,
&st->common_attributes.sensitivity);
dev_dbg(&pdev->dev, "Sensitivity index:report %d:%d\n",
st->common_attributes.sensitivity.index,
st->common_attributes.sensitivity.report_id);
}
return ret;
}
/* Function to initialize the processing for usage id */
static int hid_press_probe(struct platform_device *pdev)
{
int ret = 0;
static const char *name = "press";
struct iio_dev *indio_dev;
struct press_state *press_state;
struct hid_sensor_hub_device *hsdev = pdev->dev.platform_data;
struct iio_chan_spec *channels;
indio_dev = devm_iio_device_alloc(&pdev->dev,
sizeof(struct press_state));
if (!indio_dev)
return -ENOMEM;
platform_set_drvdata(pdev, indio_dev);
press_state = iio_priv(indio_dev);
press_state->common_attributes.hsdev = hsdev;
press_state->common_attributes.pdev = pdev;
ret = hid_sensor_parse_common_attributes(hsdev,
HID_USAGE_SENSOR_PRESSURE,
&press_state->common_attributes);
if (ret) {
dev_err(&pdev->dev, "failed to setup common attributes\n");
return ret;
}
channels = kmemdup(press_channels, sizeof(press_channels), GFP_KERNEL);
if (!channels) {
dev_err(&pdev->dev, "failed to duplicate channels\n");
return -ENOMEM;
}
ret = press_parse_report(pdev, hsdev, channels,
HID_USAGE_SENSOR_PRESSURE, press_state);
if (ret) {
dev_err(&pdev->dev, "failed to setup attributes\n");
goto error_free_dev_mem;
}
indio_dev->channels = channels;
indio_dev->num_channels =
ARRAY_SIZE(press_channels);
indio_dev->dev.parent = &pdev->dev;
indio_dev->info = &press_info;
indio_dev->name = name;
indio_dev->modes = INDIO_DIRECT_MODE;
ret = iio_triggered_buffer_setup(indio_dev, &iio_pollfunc_store_time,
NULL, NULL);
if (ret) {
dev_err(&pdev->dev, "failed to initialize trigger buffer\n");
goto error_free_dev_mem;
}
atomic_set(&press_state->common_attributes.data_ready, 0);
ret = hid_sensor_setup_trigger(indio_dev, name,
&press_state->common_attributes);
if (ret) {
dev_err(&pdev->dev, "trigger setup failed\n");
goto error_unreg_buffer_funcs;
}
ret = iio_device_register(indio_dev);
if (ret) {
dev_err(&pdev->dev, "device register failed\n");
goto error_remove_trigger;
}
press_state->callbacks.send_event = press_proc_event;
press_state->callbacks.capture_sample = press_capture_sample;
press_state->callbacks.pdev = pdev;
ret = sensor_hub_register_callback(hsdev, HID_USAGE_SENSOR_PRESSURE,
&press_state->callbacks);
if (ret < 0) {
dev_err(&pdev->dev, "callback reg failed\n");
goto error_iio_unreg;
}
return ret;
error_iio_unreg:
iio_device_unregister(indio_dev);
error_remove_trigger:
hid_sensor_remove_trigger(&press_state->common_attributes);
error_unreg_buffer_funcs:
iio_triggered_buffer_cleanup(indio_dev);
error_free_dev_mem:
kfree(indio_dev->channels);
return ret;
}
/* Function to deinitialize the processing for usage id */
static int hid_press_remove(struct platform_device *pdev)
{
struct hid_sensor_hub_device *hsdev = pdev->dev.platform_data;
struct iio_dev *indio_dev = platform_get_drvdata(pdev);
struct press_state *press_state = iio_priv(indio_dev);
sensor_hub_remove_callback(hsdev, HID_USAGE_SENSOR_PRESSURE);
iio_device_unregister(indio_dev);
hid_sensor_remove_trigger(&press_state->common_attributes);
iio_triggered_buffer_cleanup(indio_dev);
kfree(indio_dev->channels);
return 0;
}
static struct platform_device_id hid_press_ids[] = {
{
/* Format: HID-SENSOR-usage_id_in_hex_lowercase */
.name = "HID-SENSOR-200031",
},
{ /* sentinel */ }
};
MODULE_DEVICE_TABLE(platform, hid_press_ids);
static struct platform_driver hid_press_platform_driver = {
.id_table = hid_press_ids,
.driver = {
.name = KBUILD_MODNAME,
.pm = &hid_sensor_pm_ops,
},
.probe = hid_press_probe,
.remove = hid_press_remove,
};
module_platform_driver(hid_press_platform_driver);
MODULE_DESCRIPTION("HID Sensor Pressure");
MODULE_AUTHOR("Archana Patni <archana.patni@intel.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
thoemy/android_kernel_htc_endeavoru | drivers/net/macvlan.c | 367 | 22619 | /*
* Copyright (c) 2007 Patrick McHardy <kaber@trash.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.
*
* The code this is based on carried the following copyright notice:
* ---
* (C) Copyright 2001-2006
* Alex Zeffertt, Cambridge Broadband Ltd, ajz@cambridgebroadband.com
* Re-worked by Ben Greear <greearb@candelatech.com>
* ---
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/rculist.h>
#include <linux/notifier.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/if_arp.h>
#include <linux/if_link.h>
#include <linux/if_macvlan.h>
#include <net/rtnetlink.h>
#include <net/xfrm.h>
#define MACVLAN_HASH_SIZE (1 << BITS_PER_BYTE)
struct macvlan_port {
struct net_device *dev;
struct hlist_head vlan_hash[MACVLAN_HASH_SIZE];
struct list_head vlans;
struct rcu_head rcu;
bool passthru;
int count;
};
static void macvlan_port_destroy(struct net_device *dev);
#define macvlan_port_get_rcu(dev) \
((struct macvlan_port *) rcu_dereference(dev->rx_handler_data))
#define macvlan_port_get(dev) ((struct macvlan_port *) dev->rx_handler_data)
#define macvlan_port_exists(dev) (dev->priv_flags & IFF_MACVLAN_PORT)
static struct macvlan_dev *macvlan_hash_lookup(const struct macvlan_port *port,
const unsigned char *addr)
{
struct macvlan_dev *vlan;
struct hlist_node *n;
hlist_for_each_entry_rcu(vlan, n, &port->vlan_hash[addr[5]], hlist) {
if (!compare_ether_addr_64bits(vlan->dev->dev_addr, addr))
return vlan;
}
return NULL;
}
static void macvlan_hash_add(struct macvlan_dev *vlan)
{
struct macvlan_port *port = vlan->port;
const unsigned char *addr = vlan->dev->dev_addr;
hlist_add_head_rcu(&vlan->hlist, &port->vlan_hash[addr[5]]);
}
static void macvlan_hash_del(struct macvlan_dev *vlan, bool sync)
{
hlist_del_rcu(&vlan->hlist);
if (sync)
synchronize_rcu();
}
static void macvlan_hash_change_addr(struct macvlan_dev *vlan,
const unsigned char *addr)
{
macvlan_hash_del(vlan, true);
/* Now that we are unhashed it is safe to change the device
* address without confusing packet delivery.
*/
memcpy(vlan->dev->dev_addr, addr, ETH_ALEN);
macvlan_hash_add(vlan);
}
static int macvlan_addr_busy(const struct macvlan_port *port,
const unsigned char *addr)
{
/* Test to see if the specified multicast address is
* currently in use by the underlying device or
* another macvlan.
*/
if (!compare_ether_addr_64bits(port->dev->dev_addr, addr))
return 1;
if (macvlan_hash_lookup(port, addr))
return 1;
return 0;
}
static int macvlan_broadcast_one(struct sk_buff *skb,
const struct macvlan_dev *vlan,
const struct ethhdr *eth, bool local)
{
struct net_device *dev = vlan->dev;
if (!skb)
return NET_RX_DROP;
if (local)
return vlan->forward(dev, skb);
skb->dev = dev;
if (!compare_ether_addr_64bits(eth->h_dest,
dev->broadcast))
skb->pkt_type = PACKET_BROADCAST;
else
skb->pkt_type = PACKET_MULTICAST;
return vlan->receive(skb);
}
static void macvlan_broadcast(struct sk_buff *skb,
const struct macvlan_port *port,
struct net_device *src,
enum macvlan_mode mode)
{
const struct ethhdr *eth = eth_hdr(skb);
const struct macvlan_dev *vlan;
struct hlist_node *n;
struct sk_buff *nskb;
unsigned int i;
int err;
if (skb->protocol == htons(ETH_P_PAUSE))
return;
for (i = 0; i < MACVLAN_HASH_SIZE; i++) {
hlist_for_each_entry_rcu(vlan, n, &port->vlan_hash[i], hlist) {
if (vlan->dev == src || !(vlan->mode & mode))
continue;
nskb = skb_clone(skb, GFP_ATOMIC);
err = macvlan_broadcast_one(nskb, vlan, eth,
mode == MACVLAN_MODE_BRIDGE);
macvlan_count_rx(vlan, skb->len + ETH_HLEN,
err == NET_RX_SUCCESS, 1);
}
}
}
/* called under rcu_read_lock() from netif_receive_skb */
static rx_handler_result_t macvlan_handle_frame(struct sk_buff **pskb)
{
struct macvlan_port *port;
struct sk_buff *skb = *pskb;
const struct ethhdr *eth = eth_hdr(skb);
const struct macvlan_dev *vlan;
const struct macvlan_dev *src;
struct net_device *dev;
unsigned int len = 0;
int ret = NET_RX_DROP;
port = macvlan_port_get_rcu(skb->dev);
if (is_multicast_ether_addr(eth->h_dest)) {
src = macvlan_hash_lookup(port, eth->h_source);
if (!src)
/* frame comes from an external address */
macvlan_broadcast(skb, port, NULL,
MACVLAN_MODE_PRIVATE |
MACVLAN_MODE_VEPA |
MACVLAN_MODE_PASSTHRU|
MACVLAN_MODE_BRIDGE);
else if (src->mode == MACVLAN_MODE_VEPA)
/* flood to everyone except source */
macvlan_broadcast(skb, port, src->dev,
MACVLAN_MODE_VEPA |
MACVLAN_MODE_BRIDGE);
else if (src->mode == MACVLAN_MODE_BRIDGE)
/*
* flood only to VEPA ports, bridge ports
* already saw the frame on the way out.
*/
macvlan_broadcast(skb, port, src->dev,
MACVLAN_MODE_VEPA);
return RX_HANDLER_PASS;
}
if (port->passthru)
vlan = list_first_entry(&port->vlans, struct macvlan_dev, list);
else
vlan = macvlan_hash_lookup(port, eth->h_dest);
if (vlan == NULL)
return RX_HANDLER_PASS;
dev = vlan->dev;
if (unlikely(!(dev->flags & IFF_UP))) {
kfree_skb(skb);
return RX_HANDLER_CONSUMED;
}
len = skb->len + ETH_HLEN;
skb = skb_share_check(skb, GFP_ATOMIC);
if (!skb)
goto out;
skb->dev = dev;
skb->pkt_type = PACKET_HOST;
ret = vlan->receive(skb);
out:
macvlan_count_rx(vlan, len, ret == NET_RX_SUCCESS, 0);
return RX_HANDLER_CONSUMED;
}
static int macvlan_queue_xmit(struct sk_buff *skb, struct net_device *dev)
{
const struct macvlan_dev *vlan = netdev_priv(dev);
const struct macvlan_port *port = vlan->port;
const struct macvlan_dev *dest;
__u8 ip_summed = skb->ip_summed;
if (vlan->mode == MACVLAN_MODE_BRIDGE) {
const struct ethhdr *eth = (void *)skb->data;
skb->ip_summed = CHECKSUM_UNNECESSARY;
/* send to other bridge ports directly */
if (is_multicast_ether_addr(eth->h_dest)) {
macvlan_broadcast(skb, port, dev, MACVLAN_MODE_BRIDGE);
goto xmit_world;
}
dest = macvlan_hash_lookup(port, eth->h_dest);
if (dest && dest->mode == MACVLAN_MODE_BRIDGE) {
/* send to lowerdev first for its network taps */
dev_forward_skb(vlan->lowerdev, skb);
return NET_XMIT_SUCCESS;
}
}
xmit_world:
skb->ip_summed = ip_summed;
skb_set_dev(skb, vlan->lowerdev);
return dev_queue_xmit(skb);
}
netdev_tx_t macvlan_start_xmit(struct sk_buff *skb,
struct net_device *dev)
{
unsigned int len = skb->len;
int ret;
const struct macvlan_dev *vlan = netdev_priv(dev);
ret = macvlan_queue_xmit(skb, dev);
if (likely(ret == NET_XMIT_SUCCESS || ret == NET_XMIT_CN)) {
struct macvlan_pcpu_stats *pcpu_stats;
pcpu_stats = this_cpu_ptr(vlan->pcpu_stats);
u64_stats_update_begin(&pcpu_stats->syncp);
pcpu_stats->tx_packets++;
pcpu_stats->tx_bytes += len;
u64_stats_update_end(&pcpu_stats->syncp);
} else {
this_cpu_inc(vlan->pcpu_stats->tx_dropped);
}
return ret;
}
EXPORT_SYMBOL_GPL(macvlan_start_xmit);
static int macvlan_hard_header(struct sk_buff *skb, struct net_device *dev,
unsigned short type, const void *daddr,
const void *saddr, unsigned len)
{
const struct macvlan_dev *vlan = netdev_priv(dev);
struct net_device *lowerdev = vlan->lowerdev;
return dev_hard_header(skb, lowerdev, type, daddr,
saddr ? : dev->dev_addr, len);
}
static const struct header_ops macvlan_hard_header_ops = {
.create = macvlan_hard_header,
.rebuild = eth_rebuild_header,
.parse = eth_header_parse,
.cache = eth_header_cache,
.cache_update = eth_header_cache_update,
};
static int macvlan_open(struct net_device *dev)
{
struct macvlan_dev *vlan = netdev_priv(dev);
struct net_device *lowerdev = vlan->lowerdev;
int err;
if (vlan->port->passthru) {
dev_set_promiscuity(lowerdev, 1);
goto hash_add;
}
err = -EBUSY;
if (macvlan_addr_busy(vlan->port, dev->dev_addr))
goto out;
err = dev_uc_add(lowerdev, dev->dev_addr);
if (err < 0)
goto out;
if (dev->flags & IFF_ALLMULTI) {
err = dev_set_allmulti(lowerdev, 1);
if (err < 0)
goto del_unicast;
}
hash_add:
macvlan_hash_add(vlan);
return 0;
del_unicast:
dev_uc_del(lowerdev, dev->dev_addr);
out:
return err;
}
static int macvlan_stop(struct net_device *dev)
{
struct macvlan_dev *vlan = netdev_priv(dev);
struct net_device *lowerdev = vlan->lowerdev;
if (vlan->port->passthru) {
dev_set_promiscuity(lowerdev, -1);
goto hash_del;
}
dev_mc_unsync(lowerdev, dev);
if (dev->flags & IFF_ALLMULTI)
dev_set_allmulti(lowerdev, -1);
dev_uc_del(lowerdev, dev->dev_addr);
hash_del:
macvlan_hash_del(vlan, !dev->dismantle);
return 0;
}
static int macvlan_set_mac_address(struct net_device *dev, void *p)
{
struct macvlan_dev *vlan = netdev_priv(dev);
struct net_device *lowerdev = vlan->lowerdev;
struct sockaddr *addr = p;
int err;
if (!is_valid_ether_addr(addr->sa_data))
return -EADDRNOTAVAIL;
if (!(dev->flags & IFF_UP)) {
/* Just copy in the new address */
memcpy(dev->dev_addr, addr->sa_data, ETH_ALEN);
} else {
/* Rehash and update the device filters */
if (macvlan_addr_busy(vlan->port, addr->sa_data))
return -EBUSY;
err = dev_uc_add(lowerdev, addr->sa_data);
if (err)
return err;
dev_uc_del(lowerdev, dev->dev_addr);
macvlan_hash_change_addr(vlan, addr->sa_data);
}
return 0;
}
static void macvlan_change_rx_flags(struct net_device *dev, int change)
{
struct macvlan_dev *vlan = netdev_priv(dev);
struct net_device *lowerdev = vlan->lowerdev;
if (change & IFF_ALLMULTI)
dev_set_allmulti(lowerdev, dev->flags & IFF_ALLMULTI ? 1 : -1);
}
static void macvlan_set_multicast_list(struct net_device *dev)
{
struct macvlan_dev *vlan = netdev_priv(dev);
dev_mc_sync(vlan->lowerdev, dev);
}
static int macvlan_change_mtu(struct net_device *dev, int new_mtu)
{
struct macvlan_dev *vlan = netdev_priv(dev);
if (new_mtu < 68 || vlan->lowerdev->mtu < new_mtu)
return -EINVAL;
dev->mtu = new_mtu;
return 0;
}
/*
* macvlan network devices have devices nesting below it and are a special
* "super class" of normal network devices; split their locks off into a
* separate class since they always nest.
*/
static struct lock_class_key macvlan_netdev_xmit_lock_key;
static struct lock_class_key macvlan_netdev_addr_lock_key;
#define MACVLAN_FEATURES \
(NETIF_F_SG | NETIF_F_ALL_CSUM | NETIF_F_HIGHDMA | NETIF_F_FRAGLIST | \
NETIF_F_GSO | NETIF_F_TSO | NETIF_F_UFO | NETIF_F_GSO_ROBUST | \
NETIF_F_TSO_ECN | NETIF_F_TSO6 | NETIF_F_GRO | NETIF_F_RXCSUM | \
NETIF_F_HW_VLAN_FILTER)
#define MACVLAN_STATE_MASK \
((1<<__LINK_STATE_NOCARRIER) | (1<<__LINK_STATE_DORMANT))
static void macvlan_set_lockdep_class_one(struct net_device *dev,
struct netdev_queue *txq,
void *_unused)
{
lockdep_set_class(&txq->_xmit_lock,
&macvlan_netdev_xmit_lock_key);
}
static void macvlan_set_lockdep_class(struct net_device *dev)
{
lockdep_set_class(&dev->addr_list_lock,
&macvlan_netdev_addr_lock_key);
netdev_for_each_tx_queue(dev, macvlan_set_lockdep_class_one, NULL);
}
static int macvlan_init(struct net_device *dev)
{
struct macvlan_dev *vlan = netdev_priv(dev);
const struct net_device *lowerdev = vlan->lowerdev;
dev->state = (dev->state & ~MACVLAN_STATE_MASK) |
(lowerdev->state & MACVLAN_STATE_MASK);
dev->features = lowerdev->features & MACVLAN_FEATURES;
dev->features |= NETIF_F_LLTX;
dev->gso_max_size = lowerdev->gso_max_size;
dev->iflink = lowerdev->ifindex;
dev->hard_header_len = lowerdev->hard_header_len;
macvlan_set_lockdep_class(dev);
vlan->pcpu_stats = alloc_percpu(struct macvlan_pcpu_stats);
if (!vlan->pcpu_stats)
return -ENOMEM;
return 0;
}
static void macvlan_uninit(struct net_device *dev)
{
struct macvlan_dev *vlan = netdev_priv(dev);
struct macvlan_port *port = vlan->port;
free_percpu(vlan->pcpu_stats);
port->count -= 1;
if (!port->count)
macvlan_port_destroy(port->dev);
}
static struct rtnl_link_stats64 *macvlan_dev_get_stats64(struct net_device *dev,
struct rtnl_link_stats64 *stats)
{
struct macvlan_dev *vlan = netdev_priv(dev);
if (vlan->pcpu_stats) {
struct macvlan_pcpu_stats *p;
u64 rx_packets, rx_bytes, rx_multicast, tx_packets, tx_bytes;
u32 rx_errors = 0, tx_dropped = 0;
unsigned int start;
int i;
for_each_possible_cpu(i) {
p = per_cpu_ptr(vlan->pcpu_stats, i);
do {
start = u64_stats_fetch_begin_bh(&p->syncp);
rx_packets = p->rx_packets;
rx_bytes = p->rx_bytes;
rx_multicast = p->rx_multicast;
tx_packets = p->tx_packets;
tx_bytes = p->tx_bytes;
} while (u64_stats_fetch_retry_bh(&p->syncp, start));
stats->rx_packets += rx_packets;
stats->rx_bytes += rx_bytes;
stats->multicast += rx_multicast;
stats->tx_packets += tx_packets;
stats->tx_bytes += tx_bytes;
/* rx_errors & tx_dropped are u32, updated
* without syncp protection.
*/
rx_errors += p->rx_errors;
tx_dropped += p->tx_dropped;
}
stats->rx_errors = rx_errors;
stats->rx_dropped = rx_errors;
stats->tx_dropped = tx_dropped;
}
return stats;
}
static void macvlan_vlan_rx_add_vid(struct net_device *dev,
unsigned short vid)
{
struct macvlan_dev *vlan = netdev_priv(dev);
struct net_device *lowerdev = vlan->lowerdev;
const struct net_device_ops *ops = lowerdev->netdev_ops;
if (ops->ndo_vlan_rx_add_vid)
ops->ndo_vlan_rx_add_vid(lowerdev, vid);
}
static void macvlan_vlan_rx_kill_vid(struct net_device *dev,
unsigned short vid)
{
struct macvlan_dev *vlan = netdev_priv(dev);
struct net_device *lowerdev = vlan->lowerdev;
const struct net_device_ops *ops = lowerdev->netdev_ops;
if (ops->ndo_vlan_rx_kill_vid)
ops->ndo_vlan_rx_kill_vid(lowerdev, vid);
}
static void macvlan_ethtool_get_drvinfo(struct net_device *dev,
struct ethtool_drvinfo *drvinfo)
{
snprintf(drvinfo->driver, 32, "macvlan");
snprintf(drvinfo->version, 32, "0.1");
}
static int macvlan_ethtool_get_settings(struct net_device *dev,
struct ethtool_cmd *cmd)
{
const struct macvlan_dev *vlan = netdev_priv(dev);
return dev_ethtool_get_settings(vlan->lowerdev, cmd);
}
static const struct ethtool_ops macvlan_ethtool_ops = {
.get_link = ethtool_op_get_link,
.get_settings = macvlan_ethtool_get_settings,
.get_drvinfo = macvlan_ethtool_get_drvinfo,
};
static const struct net_device_ops macvlan_netdev_ops = {
.ndo_init = macvlan_init,
.ndo_uninit = macvlan_uninit,
.ndo_open = macvlan_open,
.ndo_stop = macvlan_stop,
.ndo_start_xmit = macvlan_start_xmit,
.ndo_change_mtu = macvlan_change_mtu,
.ndo_change_rx_flags = macvlan_change_rx_flags,
.ndo_set_mac_address = macvlan_set_mac_address,
.ndo_set_multicast_list = macvlan_set_multicast_list,
.ndo_get_stats64 = macvlan_dev_get_stats64,
.ndo_validate_addr = eth_validate_addr,
.ndo_vlan_rx_add_vid = macvlan_vlan_rx_add_vid,
.ndo_vlan_rx_kill_vid = macvlan_vlan_rx_kill_vid,
};
void macvlan_common_setup(struct net_device *dev)
{
ether_setup(dev);
dev->priv_flags &= ~(IFF_XMIT_DST_RELEASE | IFF_TX_SKB_SHARING);
dev->netdev_ops = &macvlan_netdev_ops;
dev->destructor = free_netdev;
dev->header_ops = &macvlan_hard_header_ops,
dev->ethtool_ops = &macvlan_ethtool_ops;
}
EXPORT_SYMBOL_GPL(macvlan_common_setup);
static void macvlan_setup(struct net_device *dev)
{
macvlan_common_setup(dev);
dev->tx_queue_len = 0;
}
static int macvlan_port_create(struct net_device *dev)
{
struct macvlan_port *port;
unsigned int i;
int err;
if (dev->type != ARPHRD_ETHER || dev->flags & IFF_LOOPBACK)
return -EINVAL;
port = kzalloc(sizeof(*port), GFP_KERNEL);
if (port == NULL)
return -ENOMEM;
port->passthru = false;
port->dev = dev;
INIT_LIST_HEAD(&port->vlans);
for (i = 0; i < MACVLAN_HASH_SIZE; i++)
INIT_HLIST_HEAD(&port->vlan_hash[i]);
err = netdev_rx_handler_register(dev, macvlan_handle_frame, port);
if (err)
kfree(port);
else
dev->priv_flags |= IFF_MACVLAN_PORT;
return err;
}
static void macvlan_port_destroy(struct net_device *dev)
{
struct macvlan_port *port = macvlan_port_get(dev);
dev->priv_flags &= ~IFF_MACVLAN_PORT;
netdev_rx_handler_unregister(dev);
kfree_rcu(port, rcu);
}
static int macvlan_validate(struct nlattr *tb[], struct nlattr *data[])
{
if (tb[IFLA_ADDRESS]) {
if (nla_len(tb[IFLA_ADDRESS]) != ETH_ALEN)
return -EINVAL;
if (!is_valid_ether_addr(nla_data(tb[IFLA_ADDRESS])))
return -EADDRNOTAVAIL;
}
if (data && data[IFLA_MACVLAN_MODE]) {
switch (nla_get_u32(data[IFLA_MACVLAN_MODE])) {
case MACVLAN_MODE_PRIVATE:
case MACVLAN_MODE_VEPA:
case MACVLAN_MODE_BRIDGE:
case MACVLAN_MODE_PASSTHRU:
break;
default:
return -EINVAL;
}
}
return 0;
}
int macvlan_common_newlink(struct net *src_net, struct net_device *dev,
struct nlattr *tb[], struct nlattr *data[],
int (*receive)(struct sk_buff *skb),
int (*forward)(struct net_device *dev,
struct sk_buff *skb))
{
struct macvlan_dev *vlan = netdev_priv(dev);
struct macvlan_port *port;
struct net_device *lowerdev;
int err;
if (!tb[IFLA_LINK])
return -EINVAL;
lowerdev = __dev_get_by_index(src_net, nla_get_u32(tb[IFLA_LINK]));
if (lowerdev == NULL)
return -ENODEV;
/* When creating macvlans on top of other macvlans - use
* the real device as the lowerdev.
*/
if (lowerdev->rtnl_link_ops == dev->rtnl_link_ops) {
struct macvlan_dev *lowervlan = netdev_priv(lowerdev);
lowerdev = lowervlan->lowerdev;
}
if (!tb[IFLA_MTU])
dev->mtu = lowerdev->mtu;
else if (dev->mtu > lowerdev->mtu)
return -EINVAL;
if (!tb[IFLA_ADDRESS])
random_ether_addr(dev->dev_addr);
if (!macvlan_port_exists(lowerdev)) {
err = macvlan_port_create(lowerdev);
if (err < 0)
return err;
}
port = macvlan_port_get(lowerdev);
/* Only 1 macvlan device can be created in passthru mode */
if (port->passthru)
return -EINVAL;
vlan->lowerdev = lowerdev;
vlan->dev = dev;
vlan->port = port;
vlan->receive = receive;
vlan->forward = forward;
vlan->mode = MACVLAN_MODE_VEPA;
if (data && data[IFLA_MACVLAN_MODE])
vlan->mode = nla_get_u32(data[IFLA_MACVLAN_MODE]);
if (vlan->mode == MACVLAN_MODE_PASSTHRU) {
if (port->count)
return -EINVAL;
port->passthru = true;
memcpy(dev->dev_addr, lowerdev->dev_addr, ETH_ALEN);
}
port->count += 1;
err = register_netdevice(dev);
if (err < 0)
goto destroy_port;
list_add_tail(&vlan->list, &port->vlans);
netif_stacked_transfer_operstate(lowerdev, dev);
return 0;
destroy_port:
port->count -= 1;
if (!port->count)
macvlan_port_destroy(lowerdev);
return err;
}
EXPORT_SYMBOL_GPL(macvlan_common_newlink);
static int macvlan_newlink(struct net *src_net, struct net_device *dev,
struct nlattr *tb[], struct nlattr *data[])
{
return macvlan_common_newlink(src_net, dev, tb, data,
netif_rx,
dev_forward_skb);
}
void macvlan_dellink(struct net_device *dev, struct list_head *head)
{
struct macvlan_dev *vlan = netdev_priv(dev);
list_del(&vlan->list);
unregister_netdevice_queue(dev, head);
}
EXPORT_SYMBOL_GPL(macvlan_dellink);
static int macvlan_changelink(struct net_device *dev,
struct nlattr *tb[], struct nlattr *data[])
{
struct macvlan_dev *vlan = netdev_priv(dev);
if (data && data[IFLA_MACVLAN_MODE])
vlan->mode = nla_get_u32(data[IFLA_MACVLAN_MODE]);
return 0;
}
static size_t macvlan_get_size(const struct net_device *dev)
{
return nla_total_size(4);
}
static int macvlan_fill_info(struct sk_buff *skb,
const struct net_device *dev)
{
struct macvlan_dev *vlan = netdev_priv(dev);
NLA_PUT_U32(skb, IFLA_MACVLAN_MODE, vlan->mode);
return 0;
nla_put_failure:
return -EMSGSIZE;
}
static const struct nla_policy macvlan_policy[IFLA_MACVLAN_MAX + 1] = {
[IFLA_MACVLAN_MODE] = { .type = NLA_U32 },
};
int macvlan_link_register(struct rtnl_link_ops *ops)
{
/* common fields */
ops->priv_size = sizeof(struct macvlan_dev);
ops->validate = macvlan_validate;
ops->maxtype = IFLA_MACVLAN_MAX;
ops->policy = macvlan_policy;
ops->changelink = macvlan_changelink;
ops->get_size = macvlan_get_size;
ops->fill_info = macvlan_fill_info;
return rtnl_link_register(ops);
};
EXPORT_SYMBOL_GPL(macvlan_link_register);
static struct rtnl_link_ops macvlan_link_ops = {
.kind = "macvlan",
.setup = macvlan_setup,
.newlink = macvlan_newlink,
.dellink = macvlan_dellink,
};
static int macvlan_device_event(struct notifier_block *unused,
unsigned long event, void *ptr)
{
struct net_device *dev = ptr;
struct macvlan_dev *vlan, *next;
struct macvlan_port *port;
LIST_HEAD(list_kill);
if (!macvlan_port_exists(dev))
return NOTIFY_DONE;
port = macvlan_port_get(dev);
switch (event) {
case NETDEV_CHANGE:
list_for_each_entry(vlan, &port->vlans, list)
netif_stacked_transfer_operstate(vlan->lowerdev,
vlan->dev);
break;
case NETDEV_FEAT_CHANGE:
list_for_each_entry(vlan, &port->vlans, list) {
vlan->dev->features = dev->features & MACVLAN_FEATURES;
vlan->dev->gso_max_size = dev->gso_max_size;
netdev_features_change(vlan->dev);
}
break;
case NETDEV_UNREGISTER:
/* twiddle thumbs on netns device moves */
if (dev->reg_state != NETREG_UNREGISTERING)
break;
list_for_each_entry_safe(vlan, next, &port->vlans, list)
vlan->dev->rtnl_link_ops->dellink(vlan->dev, &list_kill);
unregister_netdevice_many(&list_kill);
list_del(&list_kill);
break;
case NETDEV_PRE_TYPE_CHANGE:
/* Forbid underlaying device to change its type. */
return NOTIFY_BAD;
}
return NOTIFY_DONE;
}
static struct notifier_block macvlan_notifier_block __read_mostly = {
.notifier_call = macvlan_device_event,
};
static int __init macvlan_init_module(void)
{
int err;
register_netdevice_notifier(&macvlan_notifier_block);
err = macvlan_link_register(&macvlan_link_ops);
if (err < 0)
goto err1;
return 0;
err1:
unregister_netdevice_notifier(&macvlan_notifier_block);
return err;
}
static void __exit macvlan_cleanup_module(void)
{
rtnl_link_unregister(&macvlan_link_ops);
unregister_netdevice_notifier(&macvlan_notifier_block);
}
module_init(macvlan_init_module);
module_exit(macvlan_cleanup_module);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Patrick McHardy <kaber@trash.net>");
MODULE_DESCRIPTION("Driver for MAC address based VLANs");
MODULE_ALIAS_RTNL_LINK("macvlan");
| gpl-2.0 |
Electrex/Electroactive-N5 | arch/arm/mach-msm/qdsp5/audio_pcm.c | 367 | 45361 |
/* audio_pcm.c - pcm audio decoder driver
*
* Copyright (c) 2009-2012, The Linux Foundation. All rights reserved.
*
* Based on the mp3 decoder driver in arch/arm/mach-msm/qdsp5/audio_mp3.c
*
* Copyright (C) 2008 Google, Inc.
* Copyright (C) 2008 HTC Corporation
*
* All source code in this file is licensed under the following license except
* where indicated.
*
* 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, you can find it at http://www.fsf.org
*/
#include <asm/atomic.h>
#include <asm/ioctls.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/miscdevice.h>
#include <linux/uaccess.h>
#include <linux/kthread.h>
#include <linux/wait.h>
#include <linux/dma-mapping.h>
#include <linux/debugfs.h>
#include <linux/delay.h>
#include <linux/earlysuspend.h>
#include <linux/list.h>
#include <linux/msm_ion.h>
#include <linux/slab.h>
#include <linux/msm_audio.h>
#include <mach/msm_adsp.h>
#include <mach/iommu.h>
#include <mach/iommu_domains.h>
#include <mach/qdsp5/qdsp5audppcmdi.h>
#include <mach/qdsp5/qdsp5audppmsg.h>
#include <mach/qdsp5/qdsp5audpp.h>
#include <mach/qdsp5/qdsp5audplaycmdi.h>
#include <mach/qdsp5/qdsp5audplaymsg.h>
#include <mach/qdsp5/qdsp5rmtcmdi.h>
#include <mach/debug_mm.h>
#include <linux/memory_alloc.h>
#include <mach/msm_memtypes.h>
#include "audmgr.h"
/* for queue ids - should be relative to module number*/
#include "adsp.h"
#define ADRV_STATUS_AIO_INTF 0x00000001
#define ADRV_STATUS_OBUF_GIVEN 0x00000002
#define ADRV_STATUS_IBUF_GIVEN 0x00000004
#define ADRV_STATUS_FSYNC 0x00000008
/* Size must be power of 2 */
#define BUFSZ_MAX 32768
#define BUFSZ_MIN 4096
#define DMASZ_MAX (BUFSZ_MAX * 2)
#define DMASZ_MIN (BUFSZ_MIN * 2)
#define AUDDEC_DEC_PCM 0
/* Decoder status received from AUDPPTASK */
#define AUDPP_DEC_STATUS_SLEEP 0
#define AUDPP_DEC_STATUS_INIT 1
#define AUDPP_DEC_STATUS_CFG 2
#define AUDPP_DEC_STATUS_PLAY 3
#define AUDPCM_EVENT_NUM 10 /* Default number of pre-allocated event packets */
#define __CONTAINS(r, v, l) ({ \
typeof(r) __r = r; \
typeof(v) __v = v; \
typeof(v) __e = __v + l; \
int res = ((__v >= __r->vaddr) && \
(__e <= __r->vaddr + __r->len)); \
res; \
})
#define CONTAINS(r1, r2) ({ \
typeof(r2) __r2 = r2; \
__CONTAINS(r1, __r2->vaddr, __r2->len); \
})
#define IN_RANGE(r, v) ({ \
typeof(r) __r = r; \
typeof(v) __vv = v; \
int res = ((__vv >= __r->vaddr) && \
(__vv < (__r->vaddr + __r->len))); \
res; \
})
#define OVERLAPS(r1, r2) ({ \
typeof(r1) __r1 = r1; \
typeof(r2) __r2 = r2; \
typeof(__r2->vaddr) __v = __r2->vaddr; \
typeof(__v) __e = __v + __r2->len - 1; \
int res = (IN_RANGE(__r1, __v) || IN_RANGE(__r1, __e)); \
res; \
})
struct audio;
struct buffer {
void *data;
unsigned size;
unsigned used; /* Input usage actual DSP produced PCM size */
unsigned addr;
};
#ifdef CONFIG_HAS_EARLYSUSPEND
struct audpcm_suspend_ctl {
struct early_suspend node;
struct audio *audio;
};
#endif
struct audpcm_event {
struct list_head list;
int event_type;
union msm_audio_event_payload payload;
};
struct audpcm_ion_region {
struct list_head list;
struct ion_handle *handle;
int fd;
void *vaddr;
unsigned long paddr;
unsigned long kvaddr;
unsigned long len;
unsigned ref_cnt;
};
struct audpcm_buffer_node {
struct list_head list;
struct msm_audio_aio_buf buf;
unsigned long paddr;
};
struct audpcm_drv_operations {
void (*send_data)(struct audio *, unsigned);
void (*out_flush)(struct audio *);
int (*fsync)(struct audio *);
};
struct audio {
struct buffer out[2];
spinlock_t dsp_lock;
uint8_t out_head;
uint8_t out_tail;
uint8_t out_needed; /* number of buffers the dsp is waiting for */
unsigned out_dma_sz;
struct list_head out_queue; /* queue to retain output buffers */
atomic_t out_bytes;
struct mutex lock;
struct mutex write_lock;
wait_queue_head_t write_wait;
struct msm_adsp_module *audplay;
/* configuration to use on next enable */
uint32_t out_sample_rate;
uint32_t out_channel_mode;
uint32_t out_bits; /* bits per sample */
struct audmgr audmgr;
/* data allocated for various buffers */
char *data;
int32_t phys;
void *map_v_write;
uint32_t drv_status;
int wflush; /* Write flush */
int opened;
int enabled;
int running;
int stopped; /* set when stopped, cleared on flush */
int teos; /* valid only if tunnel mode & no data left for decoder */
int rmt_resource_released;
enum msm_aud_decoder_state dec_state; /* Represents decoder state */
int reserved; /* A byte is being reserved */
char rsv_byte; /* Handle odd length user data */
const char *module_name;
unsigned queue_id;
unsigned volume;
uint16_t dec_id;
#ifdef CONFIG_HAS_EARLYSUSPEND
struct audpcm_suspend_ctl suspend_ctl;
#endif
#ifdef CONFIG_DEBUG_FS
struct dentry *dentry;
#endif
wait_queue_head_t wait;
struct list_head free_event_queue;
struct list_head event_queue;
wait_queue_head_t event_wait;
spinlock_t event_queue_lock;
struct mutex get_event_lock;
int event_abort;
struct list_head ion_region_queue;
struct audpcm_drv_operations drv_ops;
struct ion_client *client;
struct ion_handle *output_buff_handle;
};
static int auddec_dsp_config(struct audio *audio, int enable);
static void audpp_cmd_cfg_adec_params(struct audio *audio);
static void audplay_send_data(struct audio *audio, unsigned needed);
static void audio_dsp_event(void *private, unsigned id, uint16_t *msg);
static void audpcm_post_event(struct audio *audio, int type,
union msm_audio_event_payload payload);
static unsigned long audpcm_ion_fixup(struct audio *audio, void *addr,
unsigned long len, int ref_up);
static int rmt_put_resource(struct audio *audio)
{
struct aud_codec_config_cmd cmd;
unsigned short client_idx;
cmd.cmd_id = RM_CMD_AUD_CODEC_CFG;
cmd.client_id = RM_AUD_CLIENT_ID;
cmd.task_id = audio->dec_id;
cmd.enable = RMT_DISABLE;
cmd.dec_type = AUDDEC_DEC_PCM;
client_idx = ((cmd.client_id << 8) | cmd.task_id);
return put_adsp_resource(client_idx, &cmd, sizeof(cmd));
}
static int rmt_get_resource(struct audio *audio)
{
struct aud_codec_config_cmd cmd;
unsigned short client_idx;
cmd.cmd_id = RM_CMD_AUD_CODEC_CFG;
cmd.client_id = RM_AUD_CLIENT_ID;
cmd.task_id = audio->dec_id;
cmd.enable = RMT_ENABLE;
cmd.dec_type = AUDDEC_DEC_PCM;
client_idx = ((cmd.client_id << 8) | cmd.task_id);
return get_adsp_resource(client_idx, &cmd, sizeof(cmd));
}
/* must be called with audio->lock held */
static int audio_enable(struct audio *audio)
{
struct audmgr_config cfg;
int rc;
MM_DBG("\n"); /* Macro prints the file name and function */
if (audio->enabled)
return 0;
if (audio->rmt_resource_released == 1) {
audio->rmt_resource_released = 0;
rc = rmt_get_resource(audio);
if (rc) {
MM_ERR("ADSP resources are not available for PCM \
session 0x%08x on decoder: %d\n Ignoring \
error and going ahead with the playback\n",
(int)audio, audio->dec_id);
}
}
audio->dec_state = MSM_AUD_DECODER_STATE_NONE;
audio->out_tail = 0;
audio->out_needed = 0;
cfg.tx_rate = RPC_AUD_DEF_SAMPLE_RATE_NONE;
cfg.rx_rate = RPC_AUD_DEF_SAMPLE_RATE_48000;
cfg.def_method = RPC_AUD_DEF_METHOD_PLAYBACK;
cfg.codec = RPC_AUD_DEF_CODEC_PCM;
cfg.snd_method = RPC_SND_METHOD_MIDI;
rc = audmgr_enable(&audio->audmgr, &cfg);
if (rc < 0) {
msm_adsp_dump(audio->audplay);
return rc;
}
if (msm_adsp_enable(audio->audplay)) {
MM_ERR("msm_adsp_enable(audplay) failed\n");
audmgr_disable(&audio->audmgr);
return -ENODEV;
}
if (audpp_enable(audio->dec_id, audio_dsp_event, audio)) {
MM_ERR("audpp_enable() failed\n");
msm_adsp_disable(audio->audplay);
audmgr_disable(&audio->audmgr);
return -ENODEV;
}
audio->enabled = 1;
return 0;
}
/* must be called with audio->lock held */
static int audio_disable(struct audio *audio)
{
int rc = 0;
MM_DBG("\n"); /* Macro prints the file name and function */
if (audio->enabled) {
audio->enabled = 0;
audio->dec_state = MSM_AUD_DECODER_STATE_NONE;
auddec_dsp_config(audio, 0);
rc = wait_event_interruptible_timeout(audio->wait,
audio->dec_state != MSM_AUD_DECODER_STATE_NONE,
msecs_to_jiffies(MSM_AUD_DECODER_WAIT_MS));
if (rc == 0)
rc = -ETIMEDOUT;
else if (audio->dec_state != MSM_AUD_DECODER_STATE_CLOSE)
rc = -EFAULT;
else
rc = 0;
audio->stopped = 1;
wake_up(&audio->write_wait);
msm_adsp_disable(audio->audplay);
audpp_disable(audio->dec_id, audio);
rc = audmgr_disable(&audio->audmgr);
if (rc < 0)
msm_adsp_dump(audio->audplay);
audio->out_needed = 0;
rmt_put_resource(audio);
audio->rmt_resource_released = 1;
}
return rc;
}
/* ------------------- dsp --------------------- */
static void audplay_dsp_event(void *data, unsigned id, size_t len,
void (*getevent) (void *ptr, size_t len))
{
struct audio *audio = data;
uint32_t msg[28];
getevent(msg, sizeof(msg));
MM_DBG("msg_id=%x\n", id);
switch (id) {
case AUDPLAY_MSG_DEC_NEEDS_DATA:
audio->drv_ops.send_data(audio, 1);
break;
case ADSP_MESSAGE_ID:
MM_DBG("Received ADSP event: module enable(audplaytask)\n");
break;
default:
MM_ERR("unexpected message from decoder \n");
break;
}
}
static void audio_dsp_event(void *private, unsigned id, uint16_t *msg)
{
struct audio *audio = private;
switch (id) {
case AUDPP_MSG_STATUS_MSG:{
unsigned status = msg[1];
switch (status) {
case AUDPP_DEC_STATUS_SLEEP: {
uint16_t reason = msg[2];
MM_DBG("decoder status: sleep reason = \
0x%04x\n", reason);
if ((reason == AUDPP_MSG_REASON_MEM)
|| (reason ==
AUDPP_MSG_REASON_NODECODER)) {
audio->dec_state =
MSM_AUD_DECODER_STATE_FAILURE;
wake_up(&audio->wait);
} else if (reason == AUDPP_MSG_REASON_NONE) {
/* decoder is in disable state */
audio->dec_state =
MSM_AUD_DECODER_STATE_CLOSE;
wake_up(&audio->wait);
}
break;
}
case AUDPP_DEC_STATUS_INIT:
MM_DBG("decoder status: init\n");
audpp_cmd_cfg_adec_params(audio);
break;
case AUDPP_DEC_STATUS_CFG:
MM_DBG("decoder status: cfg \n");
break;
case AUDPP_DEC_STATUS_PLAY:
MM_DBG("decoder status: play \n");
audio->dec_state =
MSM_AUD_DECODER_STATE_SUCCESS;
wake_up(&audio->wait);
break;
default:
MM_ERR("unknown decoder status \n");
break;
}
break;
}
case AUDPP_MSG_CFG_MSG:
if (msg[0] == AUDPP_MSG_ENA_ENA) {
MM_DBG("CFG_MSG ENABLE\n");
auddec_dsp_config(audio, 1);
audio->out_needed = 0;
audio->running = 1;
audpp_set_volume_and_pan(audio->dec_id, audio->volume,
0);
} else if (msg[0] == AUDPP_MSG_ENA_DIS) {
MM_DBG("CFG_MSG DISABLE\n");
audio->running = 0;
} else {
MM_ERR("CFG_MSG %d?\n", msg[0]);
}
break;
case AUDPP_MSG_FLUSH_ACK:
MM_DBG("FLUSH_ACK\n");
audio->wflush = 0;
wake_up(&audio->write_wait);
break;
case AUDPP_MSG_PCMDMAMISSED:
MM_DBG("PCMDMAMISSED\n");
audio->teos = 1;
wake_up(&audio->write_wait);
break;
default:
MM_ERR("UNKNOWN (%d)\n", id);
}
}
struct msm_adsp_ops audpcmdec_adsp_ops = {
.event = audplay_dsp_event,
};
#define audplay_send_queue0(audio, cmd, len) \
msm_adsp_write(audio->audplay, audio->queue_id, \
cmd, len)
static int auddec_dsp_config(struct audio *audio, int enable)
{
u16 cfg_dec_cmd[AUDPP_CMD_CFG_DEC_TYPE_LEN / sizeof(unsigned short)];
memset(cfg_dec_cmd, 0, sizeof(cfg_dec_cmd));
cfg_dec_cmd[0] = AUDPP_CMD_CFG_DEC_TYPE;
if (enable)
cfg_dec_cmd[1 + audio->dec_id] = AUDPP_CMD_UPDATDE_CFG_DEC |
AUDPP_CMD_ENA_DEC_V | AUDDEC_DEC_PCM;
else
cfg_dec_cmd[1 + audio->dec_id] = AUDPP_CMD_UPDATDE_CFG_DEC |
AUDPP_CMD_DIS_DEC_V;
return audpp_send_queue1(&cfg_dec_cmd, sizeof(cfg_dec_cmd));
}
static void audpp_cmd_cfg_adec_params(struct audio *audio)
{
audpp_cmd_cfg_adec_params_wav cmd;
memset(&cmd, 0, sizeof(cmd));
cmd.common.cmd_id = AUDPP_CMD_CFG_ADEC_PARAMS;
cmd.common.length = AUDPP_CMD_CFG_ADEC_PARAMS_WAV_LEN;
cmd.common.dec_id = audio->dec_id;
cmd.common.input_sampling_frequency = audio->out_sample_rate;
cmd.stereo_cfg = audio->out_channel_mode;
cmd.pcm_width = audio->out_bits;
cmd.sign = 0;
audpp_send_queue2(&cmd, sizeof(cmd));
}
static int audplay_dsp_send_data_avail(struct audio *audio,
unsigned idx, unsigned len)
{
audplay_cmd_bitstream_data_avail cmd;
cmd.cmd_id = AUDPLAY_CMD_BITSTREAM_DATA_AVAIL;
cmd.decoder_id = audio->dec_id;
cmd.buf_ptr = audio->out[idx].addr;
cmd.buf_size = len/2;
cmd.partition_number = 0;
/* complete writes to the input buffer */
wmb();
return audplay_send_queue0(audio, &cmd, sizeof(cmd));
}
static void audpcm_async_send_data(struct audio *audio, unsigned needed)
{
unsigned long flags;
if (!audio->running)
return;
spin_lock_irqsave(&audio->dsp_lock, flags);
if (needed && !audio->wflush) {
audio->out_needed = 1;
if (audio->drv_status & ADRV_STATUS_OBUF_GIVEN) {
/* pop one node out of queue */
union msm_audio_event_payload payload;
struct audpcm_buffer_node *used_buf;
MM_DBG("consumed\n");
BUG_ON(list_empty(&audio->out_queue));
used_buf = list_first_entry(&audio->out_queue,
struct audpcm_buffer_node, list);
list_del(&used_buf->list);
payload.aio_buf = used_buf->buf;
audpcm_post_event(audio, AUDIO_EVENT_WRITE_DONE,
payload);
kfree(used_buf);
audio->drv_status &= ~ADRV_STATUS_OBUF_GIVEN;
}
}
if (audio->out_needed) {
struct audpcm_buffer_node *next_buf;
audplay_cmd_bitstream_data_avail cmd;
if (!list_empty(&audio->out_queue)) {
next_buf = list_first_entry(&audio->out_queue,
struct audpcm_buffer_node, list);
MM_DBG("next_buf %p\n", next_buf);
if (next_buf) {
MM_DBG("next buf phy %lx len %d\n",
next_buf->paddr, next_buf->buf.data_len);
cmd.cmd_id = AUDPLAY_CMD_BITSTREAM_DATA_AVAIL;
if (next_buf->buf.data_len)
cmd.decoder_id = audio->dec_id;
else {
cmd.decoder_id = -1;
MM_DBG("input EOS signaled\n");
}
cmd.buf_ptr = (unsigned) next_buf->paddr;
cmd.buf_size = next_buf->buf.data_len >> 1;
cmd.partition_number = 0;
/* complete writes to the input buffer */
wmb();
audplay_send_queue0(audio, &cmd, sizeof(cmd));
audio->out_needed = 0;
audio->drv_status |= ADRV_STATUS_OBUF_GIVEN;
}
}
}
spin_unlock_irqrestore(&audio->dsp_lock, flags);
}
static void audplay_send_data(struct audio *audio, unsigned needed)
{
struct buffer *frame;
unsigned long flags;
if (!audio->running)
return;
spin_lock_irqsave(&audio->dsp_lock, flags);
if (needed && !audio->wflush) {
/* We were called from the callback because the DSP
* requested more data. Note that the DSP does want
* more data, and if a buffer was in-flight, mark it
* as available (since the DSP must now be done with
* it).
*/
audio->out_needed = 1;
frame = audio->out + audio->out_tail;
if (frame->used == 0xffffffff) {
MM_DBG("frame %d free\n", audio->out_tail);
frame->used = 0;
audio->out_tail ^= 1;
wake_up(&audio->write_wait);
}
}
if (audio->out_needed) {
/* If the DSP currently wants data and we have a
* buffer available, we will send it and reset
* the needed flag. We'll mark the buffer as in-flight
* so that it won't be recycled until the next buffer
* is requested
*/
frame = audio->out + audio->out_tail;
if (frame->used) {
BUG_ON(frame->used == 0xffffffff);
MM_DBG("frame %d busy\n", audio->out_tail);
audplay_dsp_send_data_avail(audio, audio->out_tail,
frame->used);
frame->used = 0xffffffff;
audio->out_needed = 0;
}
}
spin_unlock_irqrestore(&audio->dsp_lock, flags);
}
/* ------------------- device --------------------- */
static void audpcm_async_flush(struct audio *audio)
{
struct audpcm_buffer_node *buf_node;
struct list_head *ptr, *next;
union msm_audio_event_payload payload;
MM_DBG("\n"); /* Macro prints the file name and function */
list_for_each_safe(ptr, next, &audio->out_queue) {
buf_node = list_entry(ptr, struct audpcm_buffer_node, list);
list_del(&buf_node->list);
payload.aio_buf = buf_node->buf;
audpcm_post_event(audio, AUDIO_EVENT_WRITE_DONE,
payload);
kfree(buf_node);
}
audio->drv_status &= ~ADRV_STATUS_OBUF_GIVEN;
audio->out_needed = 0;
atomic_set(&audio->out_bytes, 0);
}
static void audio_flush(struct audio *audio)
{
unsigned long flags;
spin_lock_irqsave(&audio->dsp_lock, flags);
audio->out[0].used = 0;
audio->out[1].used = 0;
audio->out_head = 0;
audio->out_tail = 0;
audio->reserved = 0;
audio->out_needed = 0;
spin_unlock_irqrestore(&audio->dsp_lock, flags);
atomic_set(&audio->out_bytes, 0);
}
static void audio_ioport_reset(struct audio *audio)
{
if (audio->drv_status & ADRV_STATUS_AIO_INTF) {
/* If fsync is in progress, make sure
* return value of fsync indicates
* abort due to flush
*/
if (audio->drv_status & ADRV_STATUS_FSYNC) {
MM_DBG("fsync in progress\n");
wake_up(&audio->write_wait);
mutex_lock(&audio->write_lock);
audio->drv_ops.out_flush(audio);
mutex_unlock(&audio->write_lock);
} else
audio->drv_ops.out_flush(audio);
} else {
/* Make sure read/write thread are free from
* sleep and knowing that system is not able
* to process io request at the moment
*/
wake_up(&audio->write_wait);
mutex_lock(&audio->write_lock);
audio->drv_ops.out_flush(audio);
mutex_unlock(&audio->write_lock);
}
}
static int audpcm_events_pending(struct audio *audio)
{
unsigned long flags;
int empty;
spin_lock_irqsave(&audio->event_queue_lock, flags);
empty = !list_empty(&audio->event_queue);
spin_unlock_irqrestore(&audio->event_queue_lock, flags);
return empty || audio->event_abort;
}
static void audpcm_reset_event_queue(struct audio *audio)
{
unsigned long flags;
struct audpcm_event *drv_evt;
struct list_head *ptr, *next;
spin_lock_irqsave(&audio->event_queue_lock, flags);
list_for_each_safe(ptr, next, &audio->event_queue) {
drv_evt = list_first_entry(&audio->event_queue,
struct audpcm_event, list);
list_del(&drv_evt->list);
kfree(drv_evt);
}
list_for_each_safe(ptr, next, &audio->free_event_queue) {
drv_evt = list_first_entry(&audio->free_event_queue,
struct audpcm_event, list);
list_del(&drv_evt->list);
kfree(drv_evt);
}
spin_unlock_irqrestore(&audio->event_queue_lock, flags);
return;
}
static long audpcm_process_event_req(struct audio *audio, void __user *arg)
{
long rc;
struct msm_audio_event usr_evt;
struct audpcm_event *drv_evt = NULL;
int timeout;
unsigned long flags;
if (copy_from_user(&usr_evt, arg, sizeof(struct msm_audio_event)))
return -EFAULT;
timeout = (int) usr_evt.timeout_ms;
if (timeout > 0) {
rc = wait_event_interruptible_timeout(
audio->event_wait, audpcm_events_pending(audio),
msecs_to_jiffies(timeout));
if (rc == 0)
return -ETIMEDOUT;
} else {
rc = wait_event_interruptible(
audio->event_wait, audpcm_events_pending(audio));
}
if (rc < 0)
return rc;
if (audio->event_abort) {
audio->event_abort = 0;
return -ENODEV;
}
spin_lock_irqsave(&audio->event_queue_lock, flags);
if (!list_empty(&audio->event_queue)) {
drv_evt = list_first_entry(&audio->event_queue,
struct audpcm_event, list);
list_del(&drv_evt->list);
}
if (drv_evt) {
usr_evt.event_type = drv_evt->event_type;
usr_evt.event_payload = drv_evt->payload;
list_add_tail(&drv_evt->list, &audio->free_event_queue);
} else
rc = -1;
spin_unlock_irqrestore(&audio->event_queue_lock, flags);
if (drv_evt && drv_evt->event_type == AUDIO_EVENT_WRITE_DONE) {
mutex_lock(&audio->lock);
audpcm_ion_fixup(audio, drv_evt->payload.aio_buf.buf_addr,
drv_evt->payload.aio_buf.buf_len, 0);
mutex_unlock(&audio->lock);
}
if (!rc && copy_to_user(arg, &usr_evt, sizeof(usr_evt)))
rc = -EFAULT;
return rc;
}
static int audpcm_ion_check(struct audio *audio,
void *vaddr, unsigned long len)
{
struct audpcm_ion_region *region_elt;
struct audpcm_ion_region t = {.vaddr = vaddr, .len = len };
list_for_each_entry(region_elt, &audio->ion_region_queue, list) {
if (CONTAINS(region_elt, &t) || CONTAINS(&t, region_elt) ||
OVERLAPS(region_elt, &t)) {
MM_ERR("[%p]:region (vaddr %p len %ld)"
" clashes with registered region"
" (vaddr %p paddr %p len %ld)\n",
audio, vaddr, len,
region_elt->vaddr,
(void *)region_elt->paddr, region_elt->len);
return -EINVAL;
}
}
return 0;
}
static int audpcm_ion_add(struct audio *audio,
struct msm_audio_ion_info *info)
{
ion_phys_addr_t paddr;
size_t len;
unsigned long kvaddr;
struct audpcm_ion_region *region;
int rc = -EINVAL;
struct ion_handle *handle;
unsigned long ionflag;
MM_ERR("\n"); /* Macro prints the file name and function */
region = kmalloc(sizeof(*region), GFP_KERNEL);
if (!region) {
rc = -ENOMEM;
goto end;
}
handle = ion_import_dma_buf(audio->client, info->fd);
if (IS_ERR_OR_NULL(handle)) {
pr_err("%s: could not get handle of the given fd\n", __func__);
goto import_error;
}
rc = ion_handle_get_flags(audio->client, handle, &ionflag);
if (rc) {
pr_err("%s: could not get flags for the handle\n", __func__);
goto flag_error;
}
kvaddr = (unsigned long)ion_map_kernel(audio->client, handle);
if (IS_ERR_OR_NULL((void *)kvaddr)) {
pr_err("%s: could not get virtual address\n", __func__);
goto map_error;
}
rc = ion_phys(audio->client, handle, &paddr, &len);
if (rc) {
pr_err("%s: could not get physical address\n", __func__);
goto ion_error;
}
rc = audpcm_ion_check(audio, info->vaddr, len);
if (rc < 0) {
MM_ERR("audpcm_ion_check failed\n");
goto ion_error;
}
region->handle = handle;
region->vaddr = info->vaddr;
region->fd = info->fd;
region->paddr = paddr;
region->kvaddr = kvaddr;
region->len = len;
region->ref_cnt = 0;
MM_DBG("[%p]:add region paddr %lx vaddr %p, len %lu kvaddr %lx\n",
audio, region->paddr, region->vaddr,
region->len, region->kvaddr);
list_add_tail(®ion->list, &audio->ion_region_queue);
return rc;
ion_error:
ion_unmap_kernel(audio->client, handle);
map_error:
flag_error:
ion_free(audio->client, handle);
import_error:
kfree(region);
end:
return rc;
}
static int audpcm_ion_remove(struct audio *audio,
struct msm_audio_ion_info *info)
{
struct audpcm_ion_region *region;
struct list_head *ptr, *next;
int rc = -EINVAL;
list_for_each_safe(ptr, next, &audio->ion_region_queue) {
region = list_entry(ptr, struct audpcm_ion_region, list);
if (region != NULL && (region->fd == info->fd) &&
(region->vaddr == info->vaddr)) {
if (region->ref_cnt) {
MM_DBG("%s[%p]:region %p in use ref_cnt %d\n",
__func__, audio, region,
region->ref_cnt);
break;
}
MM_DBG("remove region fd %d vaddr %p\n",
info->fd, info->vaddr);
list_del(®ion->list);
ion_unmap_kernel(audio->client, region->handle);
ion_free(audio->client, region->handle);
kfree(region);
rc = 0;
break;
}
}
return rc;
}
static int audpcm_ion_lookup_vaddr(struct audio *audio, void *addr,
unsigned long len, struct audpcm_ion_region **region)
{
struct audpcm_ion_region *region_elt;
int match_count = 0;
*region = NULL;
/* returns physical address or zero */
list_for_each_entry(region_elt, &audio->ion_region_queue, list) {
if (addr >= region_elt->vaddr &&
addr < region_elt->vaddr + region_elt->len &&
addr + len <= region_elt->vaddr + region_elt->len) {
/* offset since we could pass vaddr inside a registerd
* ion buffer
*/
match_count++;
if (!*region)
*region = region_elt;
}
}
if (match_count > 1) {
MM_ERR("%s[%p]:multiple hits for vaddr %p, len %ld\n",
__func__, audio, addr, len);
list_for_each_entry(region_elt, &audio->ion_region_queue,
list) {
if (addr >= region_elt->vaddr &&
addr < region_elt->vaddr + region_elt->len &&
addr + len <= region_elt->vaddr + region_elt->len)
MM_ERR("\t%s[%p]:%p, %ld --> %p\n",
__func__, audio,
region_elt->vaddr,
region_elt->len,
(void *)region_elt->paddr);
}
}
return *region ? 0 : -1;
}
static unsigned long audpcm_ion_fixup(struct audio *audio, void *addr,
unsigned long len, int ref_up)
{
struct audpcm_ion_region *region;
unsigned long paddr;
int ret;
ret = audpcm_ion_lookup_vaddr(audio, addr, len, ®ion);
if (ret) {
MM_ERR("%s[%p]:lookup (%p, %ld) failed\n",
__func__, audio, addr, len);
return 0;
}
if (ref_up)
region->ref_cnt++;
else
region->ref_cnt--;
MM_DBG("found region %p ref_cnt %d\n", region, region->ref_cnt);
paddr = region->paddr + (addr - region->vaddr);
return paddr;
}
/* audio -> lock must be held at this point */
static int audpcm_aio_buf_add(struct audio *audio, unsigned dir,
void __user *arg)
{
unsigned long flags;
struct audpcm_buffer_node *buf_node;
buf_node = kmalloc(sizeof(*buf_node), GFP_KERNEL);
if (!buf_node)
return -ENOMEM;
if (copy_from_user(&buf_node->buf, arg, sizeof(buf_node->buf))) {
kfree(buf_node);
return -EFAULT;
}
MM_DBG("node %p dir %x buf_addr %p buf_len %d data_len %d\n",
buf_node, dir, buf_node->buf.buf_addr,
buf_node->buf.buf_len, buf_node->buf.data_len);
buf_node->paddr = audpcm_ion_fixup(
audio, buf_node->buf.buf_addr,
buf_node->buf.buf_len, 1);
if (dir) {
/* write */
if (!buf_node->paddr ||
(buf_node->paddr & 0x1) ||
(buf_node->buf.data_len & 0x1) ||
(!buf_node->buf.data_len)) {
kfree(buf_node);
return -EINVAL;
}
spin_lock_irqsave(&audio->dsp_lock, flags);
list_add_tail(&buf_node->list, &audio->out_queue);
spin_unlock_irqrestore(&audio->dsp_lock, flags);
audio->drv_ops.send_data(audio, 0);
}
MM_DBG("Add buf_node %p paddr %lx\n", buf_node, buf_node->paddr);
return 0;
}
static long audio_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
struct audio *audio = file->private_data;
int rc = 0;
MM_DBG("cmd = %d\n", cmd);
if (cmd == AUDIO_GET_STATS) {
struct msm_audio_stats stats;
stats.byte_count = audpp_avsync_byte_count(audio->dec_id);
stats.sample_count = audpp_avsync_sample_count(audio->dec_id);
if (copy_to_user((void *) arg, &stats, sizeof(stats)))
return -EFAULT;
return 0;
}
if (cmd == AUDIO_SET_VOLUME) {
unsigned long flags;
spin_lock_irqsave(&audio->dsp_lock, flags);
audio->volume = arg;
if (audio->running)
audpp_set_volume_and_pan(audio->dec_id, arg, 0);
spin_unlock_irqrestore(&audio->dsp_lock, flags);
return 0;
}
if (cmd == AUDIO_GET_EVENT) {
MM_DBG("AUDIO_GET_EVENT\n");
if (mutex_trylock(&audio->get_event_lock)) {
rc = audpcm_process_event_req(audio,
(void __user *) arg);
mutex_unlock(&audio->get_event_lock);
} else
rc = -EBUSY;
return rc;
}
if (cmd == AUDIO_ABORT_GET_EVENT) {
audio->event_abort = 1;
wake_up(&audio->event_wait);
return 0;
}
mutex_lock(&audio->lock);
switch (cmd) {
case AUDIO_START:
MM_DBG("AUDIO_START\n");
rc = audio_enable(audio);
if (!rc) {
rc = wait_event_interruptible_timeout(audio->wait,
audio->dec_state != MSM_AUD_DECODER_STATE_NONE,
msecs_to_jiffies(MSM_AUD_DECODER_WAIT_MS));
MM_INFO("dec_state %d rc = %d\n", audio->dec_state, rc);
if (audio->dec_state != MSM_AUD_DECODER_STATE_SUCCESS)
rc = -ENODEV;
else
rc = 0;
}
break;
case AUDIO_STOP:
MM_DBG("AUDIO_STOP\n");
rc = audio_disable(audio);
audio_ioport_reset(audio);
audio->stopped = 0;
break;
case AUDIO_FLUSH:
MM_DBG("AUDIO_FLUSH\n");
audio->wflush = 1;
audio_ioport_reset(audio);
if (audio->running) {
audpp_flush(audio->dec_id);
rc = wait_event_interruptible(audio->write_wait,
!audio->wflush);
if (rc < 0) {
MM_ERR("AUDIO_FLUSH interrupted\n");
rc = -EINTR;
}
} else {
audio->wflush = 0;
}
break;
case AUDIO_SET_CONFIG: {
struct msm_audio_config config;
if (copy_from_user(&config, (void *) arg, sizeof(config))) {
rc = -EFAULT;
break;
}
if (config.channel_count == 1) {
config.channel_count = AUDPP_CMD_PCM_INTF_MONO_V;
} else if (config.channel_count == 2) {
config.channel_count = AUDPP_CMD_PCM_INTF_STEREO_V;
} else {
rc = -EINVAL;
break;
}
if (config.bits == 8)
config.bits = AUDPP_CMD_WAV_PCM_WIDTH_8;
else if (config.bits == 16)
config.bits = AUDPP_CMD_WAV_PCM_WIDTH_16;
else if (config.bits == 24)
config.bits = AUDPP_CMD_WAV_PCM_WIDTH_24;
else {
rc = -EINVAL;
break;
}
audio->out_sample_rate = config.sample_rate;
audio->out_channel_mode = config.channel_count;
audio->out_bits = config.bits;
break;
}
case AUDIO_GET_CONFIG: {
struct msm_audio_config config;
config.buffer_size = (audio->out_dma_sz >> 1);
config.buffer_count = 2;
config.sample_rate = audio->out_sample_rate;
if (audio->out_channel_mode == AUDPP_CMD_PCM_INTF_MONO_V)
config.channel_count = 1;
else
config.channel_count = 2;
if (audio->out_bits == AUDPP_CMD_WAV_PCM_WIDTH_8)
config.bits = 8;
else if (audio->out_bits == AUDPP_CMD_WAV_PCM_WIDTH_24)
config.bits = 24;
else
config.bits = 16;
config.unused[0] = 0;
config.unused[1] = 0;
if (copy_to_user((void *) arg, &config, sizeof(config)))
rc = -EFAULT;
else
rc = 0;
break;
}
case AUDIO_PAUSE:
MM_DBG("AUDIO_PAUSE %ld\n", arg);
rc = audpp_pause(audio->dec_id, (int) arg);
break;
case AUDIO_REGISTER_ION: {
struct msm_audio_ion_info info;
MM_ERR("AUDIO_REGISTER_ION\n");
if (copy_from_user(&info, (void *) arg, sizeof(info)))
rc = -EFAULT;
else
rc = audpcm_ion_add(audio, &info);
break;
}
case AUDIO_DEREGISTER_ION: {
struct msm_audio_ion_info info;
MM_ERR("AUDIO_DEREGISTER_ION\n");
if (copy_from_user(&info, (void *) arg, sizeof(info)))
rc = -EFAULT;
else
rc = audpcm_ion_remove(audio, &info);
break;
}
case AUDIO_ASYNC_WRITE:
if (audio->drv_status & ADRV_STATUS_FSYNC)
rc = -EBUSY;
else
rc = audpcm_aio_buf_add(audio, 1, (void __user *) arg);
break;
case AUDIO_ASYNC_READ:
MM_ERR("AUDIO_ASYNC_READ not supported\n");
rc = -EPERM;
break;
default:
rc = -EINVAL;
}
mutex_unlock(&audio->lock);
return rc;
}
/* Only useful in tunnel-mode */
int audpcm_async_fsync(struct audio *audio)
{
int rc = 0;
MM_DBG("\n"); /* Macro prints the file name and function */
/* Blocking client sends more data */
mutex_lock(&audio->lock);
audio->drv_status |= ADRV_STATUS_FSYNC;
mutex_unlock(&audio->lock);
mutex_lock(&audio->write_lock);
/* pcm dmamiss message is sent continously
* when decoder is starved so no race
* condition concern
*/
audio->teos = 0;
rc = wait_event_interruptible(audio->write_wait,
(audio->teos && audio->out_needed &&
list_empty(&audio->out_queue))
|| audio->wflush || audio->stopped);
if (audio->stopped || audio->wflush)
rc = -EBUSY;
mutex_unlock(&audio->write_lock);
mutex_lock(&audio->lock);
audio->drv_status &= ~ADRV_STATUS_FSYNC;
mutex_unlock(&audio->lock);
return rc;
}
int audpcm_sync_fsync(struct audio *audio)
{
struct buffer *frame;
int rc = 0;
MM_DBG("\n"); /* Macro prints the file name and function */
mutex_lock(&audio->write_lock);
rc = wait_event_interruptible(audio->write_wait,
(!audio->out[0].used &&
!audio->out[1].used &&
audio->out_needed) || audio->wflush);
if (rc < 0)
goto done;
else if (audio->wflush) {
rc = -EBUSY;
goto done;
}
if (audio->reserved) {
MM_DBG("send reserved byte\n");
frame = audio->out + audio->out_tail;
((char *) frame->data)[0] = audio->rsv_byte;
((char *) frame->data)[1] = 0;
frame->used = 2;
audio->drv_ops.send_data(audio, 0);
rc = wait_event_interruptible(audio->write_wait,
(!audio->out[0].used &&
!audio->out[1].used &&
audio->out_needed) || audio->wflush);
if (rc < 0)
goto done;
else if (audio->wflush) {
rc = -EBUSY;
goto done;
}
}
/* pcm dmamiss message is sent continously
* when decoder is starved so no race
* condition concern
*/
audio->teos = 0;
rc = wait_event_interruptible(audio->write_wait,
audio->teos || audio->wflush);
if (audio->wflush)
rc = -EBUSY;
done:
mutex_unlock(&audio->write_lock);
return rc;
}
int audpcm_fsync(struct file *file, loff_t a, loff_t b, int datasync)
{
struct audio *audio = file->private_data;
if (!audio->running)
return -EINVAL;
return audio->drv_ops.fsync(audio);
}
static ssize_t audio_write(struct file *file, const char __user *buf,
size_t count, loff_t *pos)
{
struct audio *audio = file->private_data;
const char __user *start = buf;
struct buffer *frame;
size_t xfer;
char *cpy_ptr;
int rc = 0;
unsigned dsize;
if (audio->drv_status & ADRV_STATUS_AIO_INTF)
return -EPERM;
MM_DBG("cnt=%d\n", count);
mutex_lock(&audio->write_lock);
while (count > 0) {
frame = audio->out + audio->out_head;
cpy_ptr = frame->data;
dsize = 0;
rc = wait_event_interruptible(audio->write_wait,
(frame->used == 0)
|| (audio->stopped)
|| (audio->wflush));
if (rc < 0)
break;
if (audio->stopped || audio->wflush) {
rc = -EBUSY;
break;
}
if (audio->reserved) {
MM_DBG("append reserved byte %x\n", audio->rsv_byte);
*cpy_ptr = audio->rsv_byte;
xfer = (count > (frame->size - 1)) ?
frame->size - 1 : count;
cpy_ptr++;
dsize = 1;
audio->reserved = 0;
} else
xfer = (count > frame->size) ? frame->size : count;
if (copy_from_user(cpy_ptr, buf, xfer)) {
rc = -EFAULT;
break;
}
dsize += xfer;
if (dsize & 1) {
audio->rsv_byte = ((char *) frame->data)[dsize - 1];
MM_DBG("odd length buf reserve last byte %x\n",
audio->rsv_byte);
audio->reserved = 1;
dsize--;
}
count -= xfer;
buf += xfer;
if (dsize > 0) {
audio->out_head ^= 1;
frame->used = dsize;
audio->drv_ops.send_data(audio, 0);
}
}
mutex_unlock(&audio->write_lock);
if (buf > start)
return buf - start;
return rc;
}
static void audpcm_reset_ion_region(struct audio *audio)
{
struct audpcm_ion_region *region;
struct list_head *ptr, *next;
list_for_each_safe(ptr, next, &audio->ion_region_queue) {
region = list_entry(ptr, struct audpcm_ion_region, list);
list_del(®ion->list);
ion_unmap_kernel(audio->client, region->handle);
ion_free(audio->client, region->handle);
kfree(region);
}
return;
}
static int audio_release(struct inode *inode, struct file *file)
{
struct audio *audio = file->private_data;
MM_DBG("audio instance 0x%08x freeing\n", (int)audio);
mutex_lock(&audio->lock);
audio_disable(audio);
if (audio->rmt_resource_released == 0)
rmt_put_resource(audio);
audio->drv_ops.out_flush(audio);
audpcm_reset_ion_region(audio);
msm_adsp_put(audio->audplay);
audpp_adec_free(audio->dec_id);
#ifdef CONFIG_HAS_EARLYSUSPEND
unregister_early_suspend(&audio->suspend_ctl.node);
#endif
audio->opened = 0;
audio->event_abort = 1;
wake_up(&audio->event_wait);
audpcm_reset_event_queue(audio);
mutex_unlock(&audio->lock);
#ifdef CONFIG_DEBUG_FS
if (audio->dentry)
debugfs_remove(audio->dentry);
#endif
ion_client_destroy(audio->client);
kfree(audio);
return 0;
}
static void audpcm_post_event(struct audio *audio, int type,
union msm_audio_event_payload payload)
{
struct audpcm_event *e_node = NULL;
unsigned long flags;
spin_lock_irqsave(&audio->event_queue_lock, flags);
if (!list_empty(&audio->free_event_queue)) {
e_node = list_first_entry(&audio->free_event_queue,
struct audpcm_event, list);
list_del(&e_node->list);
} else {
e_node = kmalloc(sizeof(struct audpcm_event), GFP_ATOMIC);
if (!e_node) {
MM_ERR("No mem to post event %d\n", type);
spin_unlock_irqrestore(&audio->event_queue_lock, flags);
return;
}
}
e_node->event_type = type;
e_node->payload = payload;
list_add_tail(&e_node->list, &audio->event_queue);
spin_unlock_irqrestore(&audio->event_queue_lock, flags);
wake_up(&audio->event_wait);
}
#ifdef CONFIG_HAS_EARLYSUSPEND
static void audpcm_suspend(struct early_suspend *h)
{
struct audpcm_suspend_ctl *ctl =
container_of(h, struct audpcm_suspend_ctl, node);
union msm_audio_event_payload payload;
MM_DBG("\n"); /* Macro prints the file name and function */
audpcm_post_event(ctl->audio, AUDIO_EVENT_SUSPEND, payload);
}
static void audpcm_resume(struct early_suspend *h)
{
struct audpcm_suspend_ctl *ctl =
container_of(h, struct audpcm_suspend_ctl, node);
union msm_audio_event_payload payload;
MM_DBG("\n"); /* Macro prints the file name and function */
audpcm_post_event(ctl->audio, AUDIO_EVENT_RESUME, payload);
}
#endif
#ifdef CONFIG_DEBUG_FS
static ssize_t audpcm_debug_open(struct inode *inode, struct file *file)
{
file->private_data = inode->i_private;
return 0;
}
static ssize_t audpcm_debug_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
const int debug_bufmax = 4096;
static char buffer[4096];
int n = 0;
struct audio *audio = file->private_data;
mutex_lock(&audio->lock);
n = scnprintf(buffer, debug_bufmax, "opened %d\n", audio->opened);
n += scnprintf(buffer + n, debug_bufmax - n,
"enabled %d\n", audio->enabled);
n += scnprintf(buffer + n, debug_bufmax - n,
"stopped %d\n", audio->stopped);
n += scnprintf(buffer + n, debug_bufmax - n,
"out_buf_sz %d\n", audio->out[0].size);
n += scnprintf(buffer + n, debug_bufmax - n,
"volume %x \n", audio->volume);
n += scnprintf(buffer + n, debug_bufmax - n,
"sample rate %d \n", audio->out_sample_rate);
n += scnprintf(buffer + n, debug_bufmax - n,
"channel mode %d \n", audio->out_channel_mode);
mutex_unlock(&audio->lock);
/* Following variables are only useful for debugging when
* when playback halts unexpectedly. Thus, no mutual exclusion
* enforced
*/
n += scnprintf(buffer + n, debug_bufmax - n,
"wflush %d\n", audio->wflush);
n += scnprintf(buffer + n, debug_bufmax - n,
"running %d \n", audio->running);
n += scnprintf(buffer + n, debug_bufmax - n,
"dec state %d \n", audio->dec_state);
n += scnprintf(buffer + n, debug_bufmax - n,
"out_needed %d \n", audio->out_needed);
n += scnprintf(buffer + n, debug_bufmax - n,
"out_head %d \n", audio->out_head);
n += scnprintf(buffer + n, debug_bufmax - n,
"out_tail %d \n", audio->out_tail);
n += scnprintf(buffer + n, debug_bufmax - n,
"out[0].used %d \n", audio->out[0].used);
n += scnprintf(buffer + n, debug_bufmax - n,
"out[1].used %d \n", audio->out[1].used);
buffer[n] = 0;
return simple_read_from_buffer(buf, count, ppos, buffer, n);
}
static const struct file_operations audpcm_debug_fops = {
.read = audpcm_debug_read,
.open = audpcm_debug_open,
};
#endif
static int audio_open(struct inode *inode, struct file *file)
{
struct audio *audio = NULL;
int rc, i, dec_attrb, decid;
struct audpcm_event *e_node = NULL;
unsigned mem_sz = DMASZ_MAX;
unsigned long ionflag = 0;
ion_phys_addr_t addr = 0;
struct ion_handle *handle = NULL;
struct ion_client *client = NULL;
int len = 0;
#ifdef CONFIG_DEBUG_FS
/* 4 bytes represents decoder number, 1 byte for terminate string */
char name[sizeof "msm_pcm_dec_" + 5];
#endif
/* Allocate audio instance, set to zero */
audio = kzalloc(sizeof(struct audio), GFP_KERNEL);
if (!audio) {
MM_ERR("no memory to allocate audio instance \n");
rc = -ENOMEM;
goto done;
}
MM_DBG("audio instance 0x%08x created\n", (int)audio);
/* Allocate the decoder */
dec_attrb = AUDDEC_DEC_PCM;
if (file->f_mode & FMODE_READ) {
MM_ERR("Non-Tunneled mode not supported\n");
rc = -EPERM;
kfree(audio);
goto done;
} else
dec_attrb |= MSM_AUD_MODE_TUNNEL;
decid = audpp_adec_alloc(dec_attrb, &audio->module_name,
&audio->queue_id);
if (decid < 0) {
MM_ERR("No free decoder available\n");
rc = -ENODEV;
MM_DBG("audio instance 0x%08x freeing\n", (int)audio);
kfree(audio);
goto done;
}
audio->dec_id = decid & MSM_AUD_DECODER_MASK;
client = msm_ion_client_create(UINT_MAX, "Audio_PCM_Client");
if (IS_ERR_OR_NULL(client)) {
pr_err("Unable to create ION client\n");
rc = -ENOMEM;
goto client_create_error;
}
audio->client = client;
/* Non AIO interface */
if (!(file->f_flags & O_NONBLOCK)) {
MM_DBG("memsz = %d\n", mem_sz);
handle = ion_alloc(client, mem_sz, SZ_4K,
ION_HEAP(ION_AUDIO_HEAP_ID), 0);
if (IS_ERR_OR_NULL(handle)) {
MM_ERR("Unable to create allocate O/P buffers\n");
rc = -ENOMEM;
goto output_buff_alloc_error;
}
audio->output_buff_handle = handle;
rc = ion_phys(client , handle, &addr, &len);
if (rc) {
MM_ERR("O/P buffers:Invalid phy: %x sz: %x\n",
(unsigned int) addr, (unsigned int) len);
goto output_buff_get_phys_error;
} else {
MM_INFO("O/P buffers:valid phy: %x sz: %x\n",
(unsigned int) addr, (unsigned int) len);
}
audio->phys = (int32_t)addr;
rc = ion_handle_get_flags(client, handle, &ionflag);
if (rc) {
MM_ERR("could not get flags for the handle\n");
goto output_buff_get_flags_error;
}
audio->map_v_write = ion_map_kernel(client, handle);
if (IS_ERR(audio->map_v_write)) {
MM_ERR("could not map write buffers\n");
rc = -ENOMEM;
goto output_buff_map_error;
}
audio->data = audio->map_v_write;
MM_DBG("write buf: phy addr 0x%08x kernel addr 0x%08x\n",
audio->phys, (int)audio->data);
audio->out_dma_sz = mem_sz;
}
rc = audmgr_open(&audio->audmgr);
if (rc)
goto err;
rc = msm_adsp_get(audio->module_name, &audio->audplay,
&audpcmdec_adsp_ops, audio);
if (rc) {
MM_ERR("failed to get %s module\n", audio->module_name);
audmgr_close(&audio->audmgr);
goto err;
}
rc = rmt_get_resource(audio);
if (rc) {
MM_ERR("ADSP resources are not available for PCM session \
0x%08x on decoder: %d\n", (int)audio, audio->dec_id);
audmgr_close(&audio->audmgr);
msm_adsp_put(audio->audplay);
goto err;
}
if (file->f_flags & O_NONBLOCK) {
MM_DBG("set to aio interface\n");
audio->drv_status |= ADRV_STATUS_AIO_INTF;
audio->drv_ops.send_data = audpcm_async_send_data;
audio->drv_ops.out_flush = audpcm_async_flush;
audio->drv_ops.fsync = audpcm_async_fsync;
} else {
MM_DBG("set to std io interface\n");
audio->drv_ops.send_data = audplay_send_data;
audio->drv_ops.out_flush = audio_flush;
audio->drv_ops.fsync = audpcm_sync_fsync;
audio->out[0].data = audio->data + 0;
audio->out[0].addr = audio->phys + 0;
audio->out[0].size = (audio->out_dma_sz >> 1);
audio->out[1].data = audio->data + audio->out[0].size;
audio->out[1].addr = audio->phys + audio->out[0].size;
audio->out[1].size = audio->out[0].size;
}
/* Initialize all locks of audio instance */
mutex_init(&audio->lock);
mutex_init(&audio->write_lock);
mutex_init(&audio->get_event_lock);
spin_lock_init(&audio->dsp_lock);
init_waitqueue_head(&audio->write_wait);
INIT_LIST_HEAD(&audio->out_queue);
INIT_LIST_HEAD(&audio->ion_region_queue);
INIT_LIST_HEAD(&audio->free_event_queue);
INIT_LIST_HEAD(&audio->event_queue);
init_waitqueue_head(&audio->wait);
init_waitqueue_head(&audio->event_wait);
spin_lock_init(&audio->event_queue_lock);
audio->out_sample_rate = 44100;
audio->out_channel_mode = AUDPP_CMD_PCM_INTF_STEREO_V;
audio->out_bits = AUDPP_CMD_WAV_PCM_WIDTH_16;
audio->volume = 0x2000;
audio->drv_ops.out_flush(audio);
file->private_data = audio;
audio->opened = 1;
#ifdef CONFIG_DEBUG_FS
snprintf(name, sizeof name, "msm_pcm_dec_%04x", audio->dec_id);
audio->dentry = debugfs_create_file(name, S_IFREG | S_IRUGO,
NULL, (void *) audio, &audpcm_debug_fops);
if (IS_ERR(audio->dentry))
MM_DBG("debugfs_create_file failed\n");
#endif
#ifdef CONFIG_HAS_EARLYSUSPEND
audio->suspend_ctl.node.level = EARLY_SUSPEND_LEVEL_DISABLE_FB;
audio->suspend_ctl.node.resume = audpcm_resume;
audio->suspend_ctl.node.suspend = audpcm_suspend;
audio->suspend_ctl.audio = audio;
register_early_suspend(&audio->suspend_ctl.node);
#endif
for (i = 0; i < AUDPCM_EVENT_NUM; i++) {
e_node = kmalloc(sizeof(struct audpcm_event), GFP_KERNEL);
if (e_node)
list_add_tail(&e_node->list, &audio->free_event_queue);
else {
MM_ERR("event pkt alloc failed\n");
break;
}
}
done:
return rc;
err:
ion_unmap_kernel(client, audio->output_buff_handle);
output_buff_map_error:
output_buff_get_flags_error:
output_buff_get_phys_error:
ion_free(client, audio->output_buff_handle);
output_buff_alloc_error:
ion_client_destroy(client);
client_create_error:
audpp_adec_free(audio->dec_id);
MM_DBG("audio instance 0x%08x freeing\n", (int)audio);
kfree(audio);
return rc;
}
static const struct file_operations audio_pcm_fops = {
.owner = THIS_MODULE,
.open = audio_open,
.release = audio_release,
.write = audio_write,
.unlocked_ioctl = audio_ioctl,
.fsync = audpcm_fsync,
};
struct miscdevice audio_pcm_misc = {
.minor = MISC_DYNAMIC_MINOR,
.name = "msm_pcm_dec",
.fops = &audio_pcm_fops,
};
static int __init audio_init(void)
{
return misc_register(&audio_pcm_misc);
}
device_initcall(audio_init);
| gpl-2.0 |
segment-routing/sr-ipv6 | arch/microblaze/kernel/intc.c | 623 | 5073 | /*
* Copyright (C) 2007-2013 Michal Simek <monstr@monstr.eu>
* Copyright (C) 2012-2013 Xilinx, Inc.
* Copyright (C) 2007-2009 PetaLogix
* Copyright (C) 2006 Atmark Techno, Inc.
*
* 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/irqdomain.h>
#include <linux/irq.h>
#include <linux/irqchip.h>
#include <linux/of_address.h>
#include <linux/io.h>
#include <linux/bug.h>
static void __iomem *intc_baseaddr;
/* No one else should require these constants, so define them locally here. */
#define ISR 0x00 /* Interrupt Status Register */
#define IPR 0x04 /* Interrupt Pending Register */
#define IER 0x08 /* Interrupt Enable Register */
#define IAR 0x0c /* Interrupt Acknowledge Register */
#define SIE 0x10 /* Set Interrupt Enable bits */
#define CIE 0x14 /* Clear Interrupt Enable bits */
#define IVR 0x18 /* Interrupt Vector Register */
#define MER 0x1c /* Master Enable Register */
#define MER_ME (1<<0)
#define MER_HIE (1<<1)
static unsigned int (*read_fn)(void __iomem *);
static void (*write_fn)(u32, void __iomem *);
static void intc_write32(u32 val, void __iomem *addr)
{
iowrite32(val, addr);
}
static unsigned int intc_read32(void __iomem *addr)
{
return ioread32(addr);
}
static void intc_write32_be(u32 val, void __iomem *addr)
{
iowrite32be(val, addr);
}
static unsigned int intc_read32_be(void __iomem *addr)
{
return ioread32be(addr);
}
static void intc_enable_or_unmask(struct irq_data *d)
{
unsigned long mask = 1 << d->hwirq;
pr_debug("enable_or_unmask: %ld\n", d->hwirq);
/* ack level irqs because they can't be acked during
* ack function since the handle_level_irq function
* acks the irq before calling the interrupt handler
*/
if (irqd_is_level_type(d))
write_fn(mask, intc_baseaddr + IAR);
write_fn(mask, intc_baseaddr + SIE);
}
static void intc_disable_or_mask(struct irq_data *d)
{
pr_debug("disable: %ld\n", d->hwirq);
write_fn(1 << d->hwirq, intc_baseaddr + CIE);
}
static void intc_ack(struct irq_data *d)
{
pr_debug("ack: %ld\n", d->hwirq);
write_fn(1 << d->hwirq, intc_baseaddr + IAR);
}
static void intc_mask_ack(struct irq_data *d)
{
unsigned long mask = 1 << d->hwirq;
pr_debug("disable_and_ack: %ld\n", d->hwirq);
write_fn(mask, intc_baseaddr + CIE);
write_fn(mask, intc_baseaddr + IAR);
}
static struct irq_chip intc_dev = {
.name = "Xilinx INTC",
.irq_unmask = intc_enable_or_unmask,
.irq_mask = intc_disable_or_mask,
.irq_ack = intc_ack,
.irq_mask_ack = intc_mask_ack,
};
static struct irq_domain *root_domain;
unsigned int get_irq(void)
{
unsigned int hwirq, irq = -1;
hwirq = read_fn(intc_baseaddr + IVR);
if (hwirq != -1U)
irq = irq_find_mapping(root_domain, hwirq);
pr_debug("get_irq: hwirq=%d, irq=%d\n", hwirq, irq);
return irq;
}
static int xintc_map(struct irq_domain *d, unsigned int irq, irq_hw_number_t hw)
{
u32 intr_mask = (u32)d->host_data;
if (intr_mask & (1 << hw)) {
irq_set_chip_and_handler_name(irq, &intc_dev,
handle_edge_irq, "edge");
irq_clear_status_flags(irq, IRQ_LEVEL);
} else {
irq_set_chip_and_handler_name(irq, &intc_dev,
handle_level_irq, "level");
irq_set_status_flags(irq, IRQ_LEVEL);
}
return 0;
}
static const struct irq_domain_ops xintc_irq_domain_ops = {
.xlate = irq_domain_xlate_onetwocell,
.map = xintc_map,
};
static int __init xilinx_intc_of_init(struct device_node *intc,
struct device_node *parent)
{
u32 nr_irq, intr_mask;
int ret;
intc_baseaddr = of_iomap(intc, 0);
BUG_ON(!intc_baseaddr);
ret = of_property_read_u32(intc, "xlnx,num-intr-inputs", &nr_irq);
if (ret < 0) {
pr_err("%s: unable to read xlnx,num-intr-inputs\n", __func__);
return ret;
}
ret = of_property_read_u32(intc, "xlnx,kind-of-intr", &intr_mask);
if (ret < 0) {
pr_err("%s: unable to read xlnx,kind-of-intr\n", __func__);
return ret;
}
if (intr_mask >> nr_irq)
pr_warn("%s: mismatch in kind-of-intr param\n", __func__);
pr_info("%s: num_irq=%d, edge=0x%x\n",
intc->full_name, nr_irq, intr_mask);
write_fn = intc_write32;
read_fn = intc_read32;
/*
* Disable all external interrupts until they are
* explicity requested.
*/
write_fn(0, intc_baseaddr + IER);
/* Acknowledge any pending interrupts just in case. */
write_fn(0xffffffff, intc_baseaddr + IAR);
/* Turn on the Master Enable. */
write_fn(MER_HIE | MER_ME, intc_baseaddr + MER);
if (!(read_fn(intc_baseaddr + MER) & (MER_HIE | MER_ME))) {
write_fn = intc_write32_be;
read_fn = intc_read32_be;
write_fn(MER_HIE | MER_ME, intc_baseaddr + MER);
}
/* Yeah, okay, casting the intr_mask to a void* is butt-ugly, but I'm
* lazy and Michal can clean it up to something nicer when he tests
* and commits this patch. ~~gcl */
root_domain = irq_domain_add_linear(intc, nr_irq, &xintc_irq_domain_ops,
(void *)intr_mask);
irq_set_default_host(root_domain);
return 0;
}
IRQCHIP_DECLARE(xilinx_intc, "xlnx,xps-intc-1.00.a", xilinx_intc_of_init);
| gpl-2.0 |
PoonKang/Kernel_GT-N8013_ICS | block/scsi_ioctl.c | 1903 | 18752 | /*
* Copyright (C) 2001 Jens Axboe <axboe@suse.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 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 Licens
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-
*
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/module.h>
#include <linux/blkdev.h>
#include <linux/capability.h>
#include <linux/completion.h>
#include <linux/cdrom.h>
#include <linux/slab.h>
#include <linux/times.h>
#include <asm/uaccess.h>
#include <scsi/scsi.h>
#include <scsi/scsi_ioctl.h>
#include <scsi/scsi_cmnd.h>
struct blk_cmd_filter {
unsigned long read_ok[BLK_SCSI_CMD_PER_LONG];
unsigned long write_ok[BLK_SCSI_CMD_PER_LONG];
};
static struct blk_cmd_filter blk_default_cmd_filter;
/* Command group 3 is reserved and should never be used. */
const unsigned char scsi_command_size_tbl[8] =
{
6, 10, 10, 12,
16, 12, 10, 10
};
EXPORT_SYMBOL(scsi_command_size_tbl);
#include <scsi/sg.h>
static int sg_get_version(int __user *p)
{
static const int sg_version_num = 30527;
return put_user(sg_version_num, p);
}
static int scsi_get_idlun(struct request_queue *q, int __user *p)
{
return put_user(0, p);
}
static int scsi_get_bus(struct request_queue *q, int __user *p)
{
return put_user(0, p);
}
static int sg_get_timeout(struct request_queue *q)
{
return jiffies_to_clock_t(q->sg_timeout);
}
static int sg_set_timeout(struct request_queue *q, int __user *p)
{
int timeout, err = get_user(timeout, p);
if (!err)
q->sg_timeout = clock_t_to_jiffies(timeout);
return err;
}
static int sg_get_reserved_size(struct request_queue *q, int __user *p)
{
unsigned val = min(q->sg_reserved_size, queue_max_sectors(q) << 9);
return put_user(val, p);
}
static int sg_set_reserved_size(struct request_queue *q, int __user *p)
{
int size, err = get_user(size, p);
if (err)
return err;
if (size < 0)
return -EINVAL;
if (size > (queue_max_sectors(q) << 9))
size = queue_max_sectors(q) << 9;
q->sg_reserved_size = size;
return 0;
}
/*
* will always return that we are ATAPI even for a real SCSI drive, I'm not
* so sure this is worth doing anything about (why would you care??)
*/
static int sg_emulated_host(struct request_queue *q, int __user *p)
{
return put_user(1, p);
}
static void blk_set_cmd_filter_defaults(struct blk_cmd_filter *filter)
{
/* Basic read-only commands */
__set_bit(TEST_UNIT_READY, filter->read_ok);
__set_bit(REQUEST_SENSE, filter->read_ok);
__set_bit(READ_6, filter->read_ok);
__set_bit(READ_10, filter->read_ok);
__set_bit(READ_12, filter->read_ok);
__set_bit(READ_16, filter->read_ok);
__set_bit(READ_BUFFER, filter->read_ok);
__set_bit(READ_DEFECT_DATA, filter->read_ok);
__set_bit(READ_CAPACITY, filter->read_ok);
__set_bit(READ_LONG, filter->read_ok);
__set_bit(INQUIRY, filter->read_ok);
__set_bit(MODE_SENSE, filter->read_ok);
__set_bit(MODE_SENSE_10, filter->read_ok);
__set_bit(LOG_SENSE, filter->read_ok);
__set_bit(START_STOP, filter->read_ok);
__set_bit(GPCMD_VERIFY_10, filter->read_ok);
__set_bit(VERIFY_16, filter->read_ok);
__set_bit(REPORT_LUNS, filter->read_ok);
__set_bit(SERVICE_ACTION_IN, filter->read_ok);
__set_bit(RECEIVE_DIAGNOSTIC, filter->read_ok);
__set_bit(MAINTENANCE_IN, filter->read_ok);
__set_bit(GPCMD_READ_BUFFER_CAPACITY, filter->read_ok);
/* Audio CD commands */
__set_bit(GPCMD_PLAY_CD, filter->read_ok);
__set_bit(GPCMD_PLAY_AUDIO_10, filter->read_ok);
__set_bit(GPCMD_PLAY_AUDIO_MSF, filter->read_ok);
__set_bit(GPCMD_PLAY_AUDIO_TI, filter->read_ok);
__set_bit(GPCMD_PAUSE_RESUME, filter->read_ok);
/* CD/DVD data reading */
__set_bit(GPCMD_READ_CD, filter->read_ok);
__set_bit(GPCMD_READ_CD_MSF, filter->read_ok);
__set_bit(GPCMD_READ_DISC_INFO, filter->read_ok);
__set_bit(GPCMD_READ_CDVD_CAPACITY, filter->read_ok);
__set_bit(GPCMD_READ_DVD_STRUCTURE, filter->read_ok);
__set_bit(GPCMD_READ_HEADER, filter->read_ok);
__set_bit(GPCMD_READ_TRACK_RZONE_INFO, filter->read_ok);
__set_bit(GPCMD_READ_SUBCHANNEL, filter->read_ok);
__set_bit(GPCMD_READ_TOC_PMA_ATIP, filter->read_ok);
__set_bit(GPCMD_REPORT_KEY, filter->read_ok);
__set_bit(GPCMD_SCAN, filter->read_ok);
__set_bit(GPCMD_GET_CONFIGURATION, filter->read_ok);
__set_bit(GPCMD_READ_FORMAT_CAPACITIES, filter->read_ok);
__set_bit(GPCMD_GET_EVENT_STATUS_NOTIFICATION, filter->read_ok);
__set_bit(GPCMD_GET_PERFORMANCE, filter->read_ok);
__set_bit(GPCMD_SEEK, filter->read_ok);
__set_bit(GPCMD_STOP_PLAY_SCAN, filter->read_ok);
/* Basic writing commands */
__set_bit(WRITE_6, filter->write_ok);
__set_bit(WRITE_10, filter->write_ok);
__set_bit(WRITE_VERIFY, filter->write_ok);
__set_bit(WRITE_12, filter->write_ok);
__set_bit(WRITE_VERIFY_12, filter->write_ok);
__set_bit(WRITE_16, filter->write_ok);
__set_bit(WRITE_LONG, filter->write_ok);
__set_bit(WRITE_LONG_2, filter->write_ok);
__set_bit(ERASE, filter->write_ok);
__set_bit(GPCMD_MODE_SELECT_10, filter->write_ok);
__set_bit(MODE_SELECT, filter->write_ok);
__set_bit(LOG_SELECT, filter->write_ok);
__set_bit(GPCMD_BLANK, filter->write_ok);
__set_bit(GPCMD_CLOSE_TRACK, filter->write_ok);
__set_bit(GPCMD_FLUSH_CACHE, filter->write_ok);
__set_bit(GPCMD_FORMAT_UNIT, filter->write_ok);
__set_bit(GPCMD_REPAIR_RZONE_TRACK, filter->write_ok);
__set_bit(GPCMD_RESERVE_RZONE_TRACK, filter->write_ok);
__set_bit(GPCMD_SEND_DVD_STRUCTURE, filter->write_ok);
__set_bit(GPCMD_SEND_EVENT, filter->write_ok);
__set_bit(GPCMD_SEND_KEY, filter->write_ok);
__set_bit(GPCMD_SEND_OPC, filter->write_ok);
__set_bit(GPCMD_SEND_CUE_SHEET, filter->write_ok);
__set_bit(GPCMD_SET_SPEED, filter->write_ok);
__set_bit(GPCMD_PREVENT_ALLOW_MEDIUM_REMOVAL, filter->write_ok);
__set_bit(GPCMD_LOAD_UNLOAD, filter->write_ok);
__set_bit(GPCMD_SET_STREAMING, filter->write_ok);
__set_bit(GPCMD_SET_READ_AHEAD, filter->write_ok);
}
int blk_verify_command(unsigned char *cmd, fmode_t has_write_perm)
{
struct blk_cmd_filter *filter = &blk_default_cmd_filter;
/* root can do any command. */
if (capable(CAP_SYS_RAWIO))
return 0;
/* if there's no filter set, assume we're filtering everything out */
if (!filter)
return -EPERM;
/* Anybody who can open the device can do a read-safe command */
if (test_bit(cmd[0], filter->read_ok))
return 0;
/* Write-safe commands require a writable open */
if (test_bit(cmd[0], filter->write_ok) && has_write_perm)
return 0;
return -EPERM;
}
EXPORT_SYMBOL(blk_verify_command);
static int blk_fill_sghdr_rq(struct request_queue *q, struct request *rq,
struct sg_io_hdr *hdr, fmode_t mode)
{
if (copy_from_user(rq->cmd, hdr->cmdp, hdr->cmd_len))
return -EFAULT;
if (blk_verify_command(rq->cmd, mode & FMODE_WRITE))
return -EPERM;
/*
* fill in request structure
*/
rq->cmd_len = hdr->cmd_len;
rq->cmd_type = REQ_TYPE_BLOCK_PC;
rq->timeout = msecs_to_jiffies(hdr->timeout);
if (!rq->timeout)
rq->timeout = q->sg_timeout;
if (!rq->timeout)
rq->timeout = BLK_DEFAULT_SG_TIMEOUT;
if (rq->timeout < BLK_MIN_SG_TIMEOUT)
rq->timeout = BLK_MIN_SG_TIMEOUT;
return 0;
}
static int blk_complete_sghdr_rq(struct request *rq, struct sg_io_hdr *hdr,
struct bio *bio)
{
int r, ret = 0;
/*
* fill in all the output members
*/
hdr->status = rq->errors & 0xff;
hdr->masked_status = status_byte(rq->errors);
hdr->msg_status = msg_byte(rq->errors);
hdr->host_status = host_byte(rq->errors);
hdr->driver_status = driver_byte(rq->errors);
hdr->info = 0;
if (hdr->masked_status || hdr->host_status || hdr->driver_status)
hdr->info |= SG_INFO_CHECK;
hdr->resid = rq->resid_len;
hdr->sb_len_wr = 0;
if (rq->sense_len && hdr->sbp) {
int len = min((unsigned int) hdr->mx_sb_len, rq->sense_len);
if (!copy_to_user(hdr->sbp, rq->sense, len))
hdr->sb_len_wr = len;
else
ret = -EFAULT;
}
r = blk_rq_unmap_user(bio);
if (!ret)
ret = r;
blk_put_request(rq);
return ret;
}
static int sg_io(struct request_queue *q, struct gendisk *bd_disk,
struct sg_io_hdr *hdr, fmode_t mode)
{
unsigned long start_time;
int writing = 0, ret = 0;
struct request *rq;
char sense[SCSI_SENSE_BUFFERSIZE];
struct bio *bio;
if (hdr->interface_id != 'S')
return -EINVAL;
if (hdr->cmd_len > BLK_MAX_CDB)
return -EINVAL;
if (hdr->dxfer_len > (queue_max_hw_sectors(q) << 9))
return -EIO;
if (hdr->dxfer_len)
switch (hdr->dxfer_direction) {
default:
return -EINVAL;
case SG_DXFER_TO_DEV:
writing = 1;
break;
case SG_DXFER_TO_FROM_DEV:
case SG_DXFER_FROM_DEV:
break;
}
rq = blk_get_request(q, writing ? WRITE : READ, GFP_KERNEL);
if (!rq)
return -ENOMEM;
if (blk_fill_sghdr_rq(q, rq, hdr, mode)) {
blk_put_request(rq);
return -EFAULT;
}
if (hdr->iovec_count) {
const int size = sizeof(struct sg_iovec) * hdr->iovec_count;
size_t iov_data_len;
struct sg_iovec *sg_iov;
struct iovec *iov;
int i;
sg_iov = kmalloc(size, GFP_KERNEL);
if (!sg_iov) {
ret = -ENOMEM;
goto out;
}
if (copy_from_user(sg_iov, hdr->dxferp, size)) {
kfree(sg_iov);
ret = -EFAULT;
goto out;
}
/*
* Sum up the vecs, making sure they don't overflow
*/
iov = (struct iovec *) sg_iov;
iov_data_len = 0;
for (i = 0; i < hdr->iovec_count; i++) {
if (iov_data_len + iov[i].iov_len < iov_data_len) {
kfree(sg_iov);
ret = -EINVAL;
goto out;
}
iov_data_len += iov[i].iov_len;
}
/* SG_IO howto says that the shorter of the two wins */
if (hdr->dxfer_len < iov_data_len) {
hdr->iovec_count = iov_shorten(iov,
hdr->iovec_count,
hdr->dxfer_len);
iov_data_len = hdr->dxfer_len;
}
ret = blk_rq_map_user_iov(q, rq, NULL, sg_iov, hdr->iovec_count,
iov_data_len, GFP_KERNEL);
kfree(sg_iov);
} else if (hdr->dxfer_len)
ret = blk_rq_map_user(q, rq, NULL, hdr->dxferp, hdr->dxfer_len,
GFP_KERNEL);
if (ret)
goto out;
bio = rq->bio;
memset(sense, 0, sizeof(sense));
rq->sense = sense;
rq->sense_len = 0;
rq->retries = 0;
start_time = jiffies;
/* ignore return value. All information is passed back to caller
* (if he doesn't check that is his problem).
* N.B. a non-zero SCSI status is _not_ necessarily an error.
*/
blk_execute_rq(q, bd_disk, rq, 0);
hdr->duration = jiffies_to_msecs(jiffies - start_time);
return blk_complete_sghdr_rq(rq, hdr, bio);
out:
blk_put_request(rq);
return ret;
}
/**
* sg_scsi_ioctl -- handle deprecated SCSI_IOCTL_SEND_COMMAND ioctl
* @file: file this ioctl operates on (optional)
* @q: request queue to send scsi commands down
* @disk: gendisk to operate on (option)
* @sic: userspace structure describing the command to perform
*
* Send down the scsi command described by @sic to the device below
* the request queue @q. If @file is non-NULL it's used to perform
* fine-grained permission checks that allow users to send down
* non-destructive SCSI commands. If the caller has a struct gendisk
* available it should be passed in as @disk to allow the low level
* driver to use the information contained in it. A non-NULL @disk
* is only allowed if the caller knows that the low level driver doesn't
* need it (e.g. in the scsi subsystem).
*
* Notes:
* - This interface is deprecated - users should use the SG_IO
* interface instead, as this is a more flexible approach to
* performing SCSI commands on a device.
* - The SCSI command length is determined by examining the 1st byte
* of the given command. There is no way to override this.
* - Data transfers are limited to PAGE_SIZE
* - The length (x + y) must be at least OMAX_SB_LEN bytes long to
* accommodate the sense buffer when an error occurs.
* The sense buffer is truncated to OMAX_SB_LEN (16) bytes so that
* old code will not be surprised.
* - If a Unix error occurs (e.g. ENOMEM) then the user will receive
* a negative return and the Unix error code in 'errno'.
* If the SCSI command succeeds then 0 is returned.
* Positive numbers returned are the compacted SCSI error codes (4
* bytes in one int) where the lowest byte is the SCSI status.
*/
#define OMAX_SB_LEN 16 /* For backward compatibility */
int sg_scsi_ioctl(struct request_queue *q, struct gendisk *disk, fmode_t mode,
struct scsi_ioctl_command __user *sic)
{
struct request *rq;
int err;
unsigned int in_len, out_len, bytes, opcode, cmdlen;
char *buffer = NULL, sense[SCSI_SENSE_BUFFERSIZE];
if (!sic)
return -EINVAL;
/*
* get in an out lengths, verify they don't exceed a page worth of data
*/
if (get_user(in_len, &sic->inlen))
return -EFAULT;
if (get_user(out_len, &sic->outlen))
return -EFAULT;
if (in_len > PAGE_SIZE || out_len > PAGE_SIZE)
return -EINVAL;
if (get_user(opcode, sic->data))
return -EFAULT;
bytes = max(in_len, out_len);
if (bytes) {
buffer = kzalloc(bytes, q->bounce_gfp | GFP_USER| __GFP_NOWARN);
if (!buffer)
return -ENOMEM;
}
rq = blk_get_request(q, in_len ? WRITE : READ, __GFP_WAIT);
cmdlen = COMMAND_SIZE(opcode);
/*
* get command and data to send to device, if any
*/
err = -EFAULT;
rq->cmd_len = cmdlen;
if (copy_from_user(rq->cmd, sic->data, cmdlen))
goto error;
if (in_len && copy_from_user(buffer, sic->data + cmdlen, in_len))
goto error;
err = blk_verify_command(rq->cmd, mode & FMODE_WRITE);
if (err)
goto error;
/* default. possible overriden later */
rq->retries = 5;
switch (opcode) {
case SEND_DIAGNOSTIC:
case FORMAT_UNIT:
rq->timeout = FORMAT_UNIT_TIMEOUT;
rq->retries = 1;
break;
case START_STOP:
rq->timeout = START_STOP_TIMEOUT;
break;
case MOVE_MEDIUM:
rq->timeout = MOVE_MEDIUM_TIMEOUT;
break;
case READ_ELEMENT_STATUS:
rq->timeout = READ_ELEMENT_STATUS_TIMEOUT;
break;
case READ_DEFECT_DATA:
rq->timeout = READ_DEFECT_DATA_TIMEOUT;
rq->retries = 1;
break;
default:
rq->timeout = BLK_DEFAULT_SG_TIMEOUT;
break;
}
if (bytes && blk_rq_map_kern(q, rq, buffer, bytes, __GFP_WAIT)) {
err = DRIVER_ERROR << 24;
goto out;
}
memset(sense, 0, sizeof(sense));
rq->sense = sense;
rq->sense_len = 0;
rq->cmd_type = REQ_TYPE_BLOCK_PC;
blk_execute_rq(q, disk, rq, 0);
out:
err = rq->errors & 0xff; /* only 8 bit SCSI status */
if (err) {
if (rq->sense_len && rq->sense) {
bytes = (OMAX_SB_LEN > rq->sense_len) ?
rq->sense_len : OMAX_SB_LEN;
if (copy_to_user(sic->data, rq->sense, bytes))
err = -EFAULT;
}
} else {
if (copy_to_user(sic->data, buffer, out_len))
err = -EFAULT;
}
error:
kfree(buffer);
blk_put_request(rq);
return err;
}
EXPORT_SYMBOL_GPL(sg_scsi_ioctl);
/* Send basic block requests */
static int __blk_send_generic(struct request_queue *q, struct gendisk *bd_disk,
int cmd, int data)
{
struct request *rq;
int err;
rq = blk_get_request(q, WRITE, __GFP_WAIT);
rq->cmd_type = REQ_TYPE_BLOCK_PC;
rq->timeout = BLK_DEFAULT_SG_TIMEOUT;
rq->cmd[0] = cmd;
rq->cmd[4] = data;
rq->cmd_len = 6;
err = blk_execute_rq(q, bd_disk, rq, 0);
blk_put_request(rq);
return err;
}
static inline int blk_send_start_stop(struct request_queue *q,
struct gendisk *bd_disk, int data)
{
return __blk_send_generic(q, bd_disk, GPCMD_START_STOP_UNIT, data);
}
int scsi_cmd_ioctl(struct request_queue *q, struct gendisk *bd_disk, fmode_t mode,
unsigned int cmd, void __user *arg)
{
int err;
if (!q || blk_get_queue(q))
return -ENXIO;
switch (cmd) {
/*
* new sgv3 interface
*/
case SG_GET_VERSION_NUM:
err = sg_get_version(arg);
break;
case SCSI_IOCTL_GET_IDLUN:
err = scsi_get_idlun(q, arg);
break;
case SCSI_IOCTL_GET_BUS_NUMBER:
err = scsi_get_bus(q, arg);
break;
case SG_SET_TIMEOUT:
err = sg_set_timeout(q, arg);
break;
case SG_GET_TIMEOUT:
err = sg_get_timeout(q);
break;
case SG_GET_RESERVED_SIZE:
err = sg_get_reserved_size(q, arg);
break;
case SG_SET_RESERVED_SIZE:
err = sg_set_reserved_size(q, arg);
break;
case SG_EMULATED_HOST:
err = sg_emulated_host(q, arg);
break;
case SG_IO: {
struct sg_io_hdr hdr;
err = -EFAULT;
if (copy_from_user(&hdr, arg, sizeof(hdr)))
break;
err = sg_io(q, bd_disk, &hdr, mode);
if (err == -EFAULT)
break;
if (copy_to_user(arg, &hdr, sizeof(hdr)))
err = -EFAULT;
break;
}
case CDROM_SEND_PACKET: {
struct cdrom_generic_command cgc;
struct sg_io_hdr hdr;
err = -EFAULT;
if (copy_from_user(&cgc, arg, sizeof(cgc)))
break;
cgc.timeout = clock_t_to_jiffies(cgc.timeout);
memset(&hdr, 0, sizeof(hdr));
hdr.interface_id = 'S';
hdr.cmd_len = sizeof(cgc.cmd);
hdr.dxfer_len = cgc.buflen;
err = 0;
switch (cgc.data_direction) {
case CGC_DATA_UNKNOWN:
hdr.dxfer_direction = SG_DXFER_UNKNOWN;
break;
case CGC_DATA_WRITE:
hdr.dxfer_direction = SG_DXFER_TO_DEV;
break;
case CGC_DATA_READ:
hdr.dxfer_direction = SG_DXFER_FROM_DEV;
break;
case CGC_DATA_NONE:
hdr.dxfer_direction = SG_DXFER_NONE;
break;
default:
err = -EINVAL;
}
if (err)
break;
hdr.dxferp = cgc.buffer;
hdr.sbp = cgc.sense;
if (hdr.sbp)
hdr.mx_sb_len = sizeof(struct request_sense);
hdr.timeout = jiffies_to_msecs(cgc.timeout);
hdr.cmdp = ((struct cdrom_generic_command __user*) arg)->cmd;
hdr.cmd_len = sizeof(cgc.cmd);
err = sg_io(q, bd_disk, &hdr, mode);
if (err == -EFAULT)
break;
if (hdr.status)
err = -EIO;
cgc.stat = err;
cgc.buflen = hdr.resid;
if (copy_to_user(arg, &cgc, sizeof(cgc)))
err = -EFAULT;
break;
}
/*
* old junk scsi send command ioctl
*/
case SCSI_IOCTL_SEND_COMMAND:
printk(KERN_WARNING "program %s is using a deprecated SCSI ioctl, please convert it to SG_IO\n", current->comm);
err = -EINVAL;
if (!arg)
break;
err = sg_scsi_ioctl(q, bd_disk, mode, arg);
break;
case CDROMCLOSETRAY:
err = blk_send_start_stop(q, bd_disk, 0x03);
break;
case CDROMEJECT:
err = blk_send_start_stop(q, bd_disk, 0x02);
break;
default:
err = -ENOTTY;
}
blk_put_queue(q);
return err;
}
EXPORT_SYMBOL(scsi_cmd_ioctl);
static int __init blk_scsi_ioctl_init(void)
{
blk_set_cmd_filter_defaults(&blk_default_cmd_filter);
return 0;
}
fs_initcall(blk_scsi_ioctl_init);
| gpl-2.0 |
samno1607/Xperia-Z-Source-Differences-JB | drivers/of/base.c | 1903 | 33589 | /*
* Procedures for creating, accessing and interpreting the device tree.
*
* Paul Mackerras August 1996.
* Copyright (C) 1996-2005 Paul Mackerras.
*
* Adapted for 64bit PowerPC by Dave Engebretsen and Peter Bergner.
* {engebret|bergner}@us.ibm.com
*
* Adapted for sparc and sparc64 by David S. Miller davem@davemloft.net
*
* Reconsolidated from arch/x/kernel/prom.c by Stephen Rothwell and
* Grant Likely.
*
* 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/ctype.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/spinlock.h>
#include <linux/slab.h>
#include <linux/proc_fs.h>
/**
* struct alias_prop - Alias property in 'aliases' node
* @link: List node to link the structure in aliases_lookup list
* @alias: Alias property name
* @np: Pointer to device_node that the alias stands for
* @id: Index value from end of alias name
* @stem: Alias string without the index
*
* The structure represents one alias property of 'aliases' node as
* an entry in aliases_lookup list.
*/
struct alias_prop {
struct list_head link;
const char *alias;
struct device_node *np;
int id;
char stem[0];
};
static LIST_HEAD(aliases_lookup);
struct device_node *allnodes;
struct device_node *of_chosen;
struct device_node *of_aliases;
static DEFINE_MUTEX(of_aliases_mutex);
/* use when traversing tree through the allnext, child, sibling,
* or parent members of struct device_node.
*/
DEFINE_RWLOCK(devtree_lock);
int of_n_addr_cells(struct device_node *np)
{
const __be32 *ip;
do {
if (np->parent)
np = np->parent;
ip = of_get_property(np, "#address-cells", NULL);
if (ip)
return be32_to_cpup(ip);
} while (np->parent);
/* No #address-cells property for the root node */
return OF_ROOT_NODE_ADDR_CELLS_DEFAULT;
}
EXPORT_SYMBOL(of_n_addr_cells);
int of_n_size_cells(struct device_node *np)
{
const __be32 *ip;
do {
if (np->parent)
np = np->parent;
ip = of_get_property(np, "#size-cells", NULL);
if (ip)
return be32_to_cpup(ip);
} while (np->parent);
/* No #size-cells property for the root node */
return OF_ROOT_NODE_SIZE_CELLS_DEFAULT;
}
EXPORT_SYMBOL(of_n_size_cells);
#if defined(CONFIG_OF_DYNAMIC)
/**
* of_node_get - Increment refcount of a node
* @node: Node to inc refcount, NULL is supported to
* simplify writing of callers
*
* Returns node.
*/
struct device_node *of_node_get(struct device_node *node)
{
if (node)
kref_get(&node->kref);
return node;
}
EXPORT_SYMBOL(of_node_get);
static inline struct device_node *kref_to_device_node(struct kref *kref)
{
return container_of(kref, struct device_node, kref);
}
/**
* of_node_release - release a dynamically allocated node
* @kref: kref element of the node to be released
*
* In of_node_put() this function is passed to kref_put()
* as the destructor.
*/
static void of_node_release(struct kref *kref)
{
struct device_node *node = kref_to_device_node(kref);
struct property *prop = node->properties;
/* We should never be releasing nodes that haven't been detached. */
if (!of_node_check_flag(node, OF_DETACHED)) {
pr_err("ERROR: Bad of_node_put() on %s\n", node->full_name);
dump_stack();
kref_init(&node->kref);
return;
}
if (!of_node_check_flag(node, OF_DYNAMIC))
return;
while (prop) {
struct property *next = prop->next;
kfree(prop->name);
kfree(prop->value);
kfree(prop);
prop = next;
if (!prop) {
prop = node->deadprops;
node->deadprops = NULL;
}
}
kfree(node->full_name);
kfree(node->data);
kfree(node);
}
/**
* of_node_put - Decrement refcount of a node
* @node: Node to dec refcount, NULL is supported to
* simplify writing of callers
*
*/
void of_node_put(struct device_node *node)
{
if (node)
kref_put(&node->kref, of_node_release);
}
EXPORT_SYMBOL(of_node_put);
#endif /* CONFIG_OF_DYNAMIC */
struct property *of_find_property(const struct device_node *np,
const char *name,
int *lenp)
{
struct property *pp;
if (!np)
return NULL;
read_lock(&devtree_lock);
for (pp = np->properties; pp != 0; pp = pp->next) {
if (of_prop_cmp(pp->name, name) == 0) {
if (lenp != 0)
*lenp = pp->length;
break;
}
}
read_unlock(&devtree_lock);
return pp;
}
EXPORT_SYMBOL(of_find_property);
/**
* of_find_all_nodes - Get next node in global list
* @prev: Previous node or NULL to start iteration
* of_node_put() will be called on it
*
* Returns a node pointer with refcount incremented, use
* of_node_put() on it when done.
*/
struct device_node *of_find_all_nodes(struct device_node *prev)
{
struct device_node *np;
read_lock(&devtree_lock);
np = prev ? prev->allnext : allnodes;
for (; np != NULL; np = np->allnext)
if (of_node_get(np))
break;
of_node_put(prev);
read_unlock(&devtree_lock);
return np;
}
EXPORT_SYMBOL(of_find_all_nodes);
/*
* Find a property with a given name for a given node
* and return the value.
*/
const void *of_get_property(const struct device_node *np, const char *name,
int *lenp)
{
struct property *pp = of_find_property(np, name, lenp);
return pp ? pp->value : NULL;
}
EXPORT_SYMBOL(of_get_property);
/** Checks if the given "compat" string matches one of the strings in
* the device's "compatible" property
*/
int of_device_is_compatible(const struct device_node *device,
const char *compat)
{
const char* cp;
int cplen, l;
cp = of_get_property(device, "compatible", &cplen);
if (cp == NULL)
return 0;
while (cplen > 0) {
if (of_compat_cmp(cp, compat, strlen(compat)) == 0)
return 1;
l = strlen(cp) + 1;
cp += l;
cplen -= l;
}
return 0;
}
EXPORT_SYMBOL(of_device_is_compatible);
/**
* of_machine_is_compatible - Test root of device tree for a given compatible value
* @compat: compatible string to look for in root node's compatible property.
*
* Returns true if the root node has the given value in its
* compatible property.
*/
int of_machine_is_compatible(const char *compat)
{
struct device_node *root;
int rc = 0;
root = of_find_node_by_path("/");
if (root) {
rc = of_device_is_compatible(root, compat);
of_node_put(root);
}
return rc;
}
EXPORT_SYMBOL(of_machine_is_compatible);
/**
* of_device_is_available - check if a device is available for use
*
* @device: Node to check for availability
*
* Returns 1 if the status property is absent or set to "okay" or "ok",
* 0 otherwise
*/
int of_device_is_available(const struct device_node *device)
{
const char *status;
int statlen;
status = of_get_property(device, "status", &statlen);
if (status == NULL)
return 1;
if (statlen > 0) {
if (!strcmp(status, "okay") || !strcmp(status, "ok"))
return 1;
}
return 0;
}
EXPORT_SYMBOL(of_device_is_available);
/**
* of_get_parent - Get a node's parent if any
* @node: Node to get parent
*
* Returns a node pointer with refcount incremented, use
* of_node_put() on it when done.
*/
struct device_node *of_get_parent(const struct device_node *node)
{
struct device_node *np;
if (!node)
return NULL;
read_lock(&devtree_lock);
np = of_node_get(node->parent);
read_unlock(&devtree_lock);
return np;
}
EXPORT_SYMBOL(of_get_parent);
/**
* of_get_next_parent - Iterate to a node's parent
* @node: Node to get parent of
*
* This is like of_get_parent() except that it drops the
* refcount on the passed node, making it suitable for iterating
* through a node's parents.
*
* Returns a node pointer with refcount incremented, use
* of_node_put() on it when done.
*/
struct device_node *of_get_next_parent(struct device_node *node)
{
struct device_node *parent;
if (!node)
return NULL;
read_lock(&devtree_lock);
parent = of_node_get(node->parent);
of_node_put(node);
read_unlock(&devtree_lock);
return parent;
}
/**
* of_get_next_child - Iterate a node childs
* @node: parent node
* @prev: previous child of the parent node, or NULL to get first
*
* Returns a node pointer with refcount incremented, use
* of_node_put() on it when done.
*/
struct device_node *of_get_next_child(const struct device_node *node,
struct device_node *prev)
{
struct device_node *next;
read_lock(&devtree_lock);
next = prev ? prev->sibling : node->child;
for (; next; next = next->sibling)
if (of_node_get(next))
break;
of_node_put(prev);
read_unlock(&devtree_lock);
return next;
}
EXPORT_SYMBOL(of_get_next_child);
/**
* of_find_node_by_path - Find a node matching a full OF path
* @path: The full path to match
*
* Returns a node pointer with refcount incremented, use
* of_node_put() on it when done.
*/
struct device_node *of_find_node_by_path(const char *path)
{
struct device_node *np = allnodes;
read_lock(&devtree_lock);
for (; np; np = np->allnext) {
if (np->full_name && (of_node_cmp(np->full_name, path) == 0)
&& of_node_get(np))
break;
}
read_unlock(&devtree_lock);
return np;
}
EXPORT_SYMBOL(of_find_node_by_path);
/**
* of_find_node_by_name - Find a node by its "name" property
* @from: The node to start searching from or NULL, the node
* you pass will not be searched, only the next one
* will; typically, you pass what the previous call
* returned. of_node_put() will be called on it
* @name: The name string to match against
*
* Returns a node pointer with refcount incremented, use
* of_node_put() on it when done.
*/
struct device_node *of_find_node_by_name(struct device_node *from,
const char *name)
{
struct device_node *np;
read_lock(&devtree_lock);
np = from ? from->allnext : allnodes;
for (; np; np = np->allnext)
if (np->name && (of_node_cmp(np->name, name) == 0)
&& of_node_get(np))
break;
of_node_put(from);
read_unlock(&devtree_lock);
return np;
}
EXPORT_SYMBOL(of_find_node_by_name);
/**
* of_find_node_by_type - Find a node by its "device_type" property
* @from: The node to start searching from, or NULL to start searching
* the entire device tree. The node you pass will not be
* searched, only the next one will; typically, you pass
* what the previous call returned. of_node_put() will be
* called on from for you.
* @type: The type string to match against
*
* Returns a node pointer with refcount incremented, use
* of_node_put() on it when done.
*/
struct device_node *of_find_node_by_type(struct device_node *from,
const char *type)
{
struct device_node *np;
read_lock(&devtree_lock);
np = from ? from->allnext : allnodes;
for (; np; np = np->allnext)
if (np->type && (of_node_cmp(np->type, type) == 0)
&& of_node_get(np))
break;
of_node_put(from);
read_unlock(&devtree_lock);
return np;
}
EXPORT_SYMBOL(of_find_node_by_type);
/**
* of_find_compatible_node - Find a node based on type and one of the
* tokens in its "compatible" property
* @from: The node to start searching from or NULL, the node
* you pass will not be searched, only the next one
* will; typically, you pass what the previous call
* returned. of_node_put() will be called on it
* @type: The type string to match "device_type" or NULL to ignore
* @compatible: The string to match to one of the tokens in the device
* "compatible" list.
*
* Returns a node pointer with refcount incremented, use
* of_node_put() on it when done.
*/
struct device_node *of_find_compatible_node(struct device_node *from,
const char *type, const char *compatible)
{
struct device_node *np;
read_lock(&devtree_lock);
np = from ? from->allnext : allnodes;
for (; np; np = np->allnext) {
if (type
&& !(np->type && (of_node_cmp(np->type, type) == 0)))
continue;
if (of_device_is_compatible(np, compatible) && of_node_get(np))
break;
}
of_node_put(from);
read_unlock(&devtree_lock);
return np;
}
EXPORT_SYMBOL(of_find_compatible_node);
/**
* of_find_node_with_property - Find a node which has a property with
* the given name.
* @from: The node to start searching from or NULL, the node
* you pass will not be searched, only the next one
* will; typically, you pass what the previous call
* returned. of_node_put() will be called on it
* @prop_name: The name of the property to look for.
*
* Returns a node pointer with refcount incremented, use
* of_node_put() on it when done.
*/
struct device_node *of_find_node_with_property(struct device_node *from,
const char *prop_name)
{
struct device_node *np;
struct property *pp;
read_lock(&devtree_lock);
np = from ? from->allnext : allnodes;
for (; np; np = np->allnext) {
for (pp = np->properties; pp != 0; pp = pp->next) {
if (of_prop_cmp(pp->name, prop_name) == 0) {
of_node_get(np);
goto out;
}
}
}
out:
of_node_put(from);
read_unlock(&devtree_lock);
return np;
}
EXPORT_SYMBOL(of_find_node_with_property);
/**
* of_match_node - Tell if an device_node has a matching of_match structure
* @matches: array of of device match structures to search in
* @node: the of device structure to match against
*
* Low level utility function used by device matching.
*/
const struct of_device_id *of_match_node(const struct of_device_id *matches,
const struct device_node *node)
{
if (!matches)
return NULL;
while (matches->name[0] || matches->type[0] || matches->compatible[0]) {
int match = 1;
if (matches->name[0])
match &= node->name
&& !strcmp(matches->name, node->name);
if (matches->type[0])
match &= node->type
&& !strcmp(matches->type, node->type);
if (matches->compatible[0])
match &= of_device_is_compatible(node,
matches->compatible);
if (match)
return matches;
matches++;
}
return NULL;
}
EXPORT_SYMBOL(of_match_node);
/**
* of_find_matching_node - Find a node based on an of_device_id match
* table.
* @from: The node to start searching from or NULL, the node
* you pass will not be searched, only the next one
* will; typically, you pass what the previous call
* returned. of_node_put() will be called on it
* @matches: array of of device match structures to search in
*
* Returns a node pointer with refcount incremented, use
* of_node_put() on it when done.
*/
struct device_node *of_find_matching_node(struct device_node *from,
const struct of_device_id *matches)
{
struct device_node *np;
read_lock(&devtree_lock);
np = from ? from->allnext : allnodes;
for (; np; np = np->allnext) {
if (of_match_node(matches, np) && of_node_get(np))
break;
}
of_node_put(from);
read_unlock(&devtree_lock);
return np;
}
EXPORT_SYMBOL(of_find_matching_node);
/**
* of_modalias_node - Lookup appropriate modalias for a device node
* @node: pointer to a device tree node
* @modalias: Pointer to buffer that modalias value will be copied into
* @len: Length of modalias value
*
* Based on the value of the compatible property, this routine will attempt
* to choose an appropriate modalias value for a particular device tree node.
* It does this by stripping the manufacturer prefix (as delimited by a ',')
* from the first entry in the compatible list property.
*
* This routine returns 0 on success, <0 on failure.
*/
int of_modalias_node(struct device_node *node, char *modalias, int len)
{
const char *compatible, *p;
int cplen;
compatible = of_get_property(node, "compatible", &cplen);
if (!compatible || strlen(compatible) > cplen)
return -ENODEV;
p = strchr(compatible, ',');
strlcpy(modalias, p ? p + 1 : compatible, len);
return 0;
}
EXPORT_SYMBOL_GPL(of_modalias_node);
/**
* of_find_node_by_phandle - Find a node given a phandle
* @handle: phandle of the node to find
*
* Returns a node pointer with refcount incremented, use
* of_node_put() on it when done.
*/
struct device_node *of_find_node_by_phandle(phandle handle)
{
struct device_node *np;
read_lock(&devtree_lock);
for (np = allnodes; np; np = np->allnext)
if (np->phandle == handle)
break;
of_node_get(np);
read_unlock(&devtree_lock);
return np;
}
EXPORT_SYMBOL(of_find_node_by_phandle);
/**
* of_property_read_u32_array - Find and read an array of 32 bit integers
* from a property.
*
* @np: device node from which the property value is to be read.
* @propname: name of the property to be searched.
* @out_value: pointer to return value, modified only if return value is 0.
*
* Search for a property in a device node and read 32-bit value(s) from
* it. Returns 0 on success, -EINVAL if the property does not exist,
* -ENODATA if property does not have a value, and -EOVERFLOW if the
* property data isn't large enough.
*
* The out_value is modified only if a valid u32 value can be decoded.
*/
int of_property_read_u32_array(const struct device_node *np,
const char *propname, u32 *out_values,
size_t sz)
{
struct property *prop = of_find_property(np, propname, NULL);
const __be32 *val;
if (!prop)
return -EINVAL;
if (!prop->value)
return -ENODATA;
if ((sz * sizeof(*out_values)) > prop->length)
return -EOVERFLOW;
val = prop->value;
while (sz--)
*out_values++ = be32_to_cpup(val++);
return 0;
}
EXPORT_SYMBOL_GPL(of_property_read_u32_array);
/**
* of_property_read_u64 - Find and read a 64 bit integer from a property
* @np: device node from which the property value is to be read.
* @propname: name of the property to be searched.
* @out_value: pointer to return value, modified only if return value is 0.
*
* Search for a property in a device node and read a 64-bit value from
* it. Returns 0 on success, -EINVAL if the property does not exist,
* -ENODATA if property does not have a value, and -EOVERFLOW if the
* property data isn't large enough.
*
* The out_value is modified only if a valid u64 value can be decoded.
*/
int of_property_read_u64(const struct device_node *np, const char *propname,
u64 *out_value)
{
struct property *prop = of_find_property(np, propname, NULL);
if (!prop)
return -EINVAL;
if (!prop->value)
return -ENODATA;
if (sizeof(*out_value) > prop->length)
return -EOVERFLOW;
*out_value = of_read_number(prop->value, 2);
return 0;
}
EXPORT_SYMBOL_GPL(of_property_read_u64);
/**
* of_property_read_string - Find and read a string from a property
* @np: device node from which the property value is to be read.
* @propname: name of the property to be searched.
* @out_string: pointer to null terminated return string, modified only if
* return value is 0.
*
* Search for a property in a device tree node and retrieve a null
* terminated string value (pointer to data, not a copy). Returns 0 on
* success, -EINVAL if the property does not exist, -ENODATA if property
* does not have a value, and -EILSEQ if the string is not null-terminated
* within the length of the property data.
*
* The out_string pointer is modified only if a valid string can be decoded.
*/
int of_property_read_string(struct device_node *np, const char *propname,
const char **out_string)
{
struct property *prop = of_find_property(np, propname, NULL);
if (!prop)
return -EINVAL;
if (!prop->value)
return -ENODATA;
if (strnlen(prop->value, prop->length) >= prop->length)
return -EILSEQ;
*out_string = prop->value;
return 0;
}
EXPORT_SYMBOL_GPL(of_property_read_string);
/**
* of_property_read_string_index - Find and read a string from a multiple
* strings property.
* @np: device node from which the property value is to be read.
* @propname: name of the property to be searched.
* @index: index of the string in the list of strings
* @out_string: pointer to null terminated return string, modified only if
* return value is 0.
*
* Search for a property in a device tree node and retrieve a null
* terminated string value (pointer to data, not a copy) in the list of strings
* contained in that property.
* Returns 0 on success, -EINVAL if the property does not exist, -ENODATA if
* property does not have a value, and -EILSEQ if the string is not
* null-terminated within the length of the property data.
*
* The out_string pointer is modified only if a valid string can be decoded.
*/
int of_property_read_string_index(struct device_node *np, const char *propname,
int index, const char **output)
{
struct property *prop = of_find_property(np, propname, NULL);
int i = 0;
size_t l = 0, total = 0;
const char *p;
if (!prop)
return -EINVAL;
if (!prop->value)
return -ENODATA;
if (strnlen(prop->value, prop->length) >= prop->length)
return -EILSEQ;
p = prop->value;
for (i = 0; total < prop->length; total += l, p += l) {
l = strlen(p) + 1;
if (i++ == index) {
*output = p;
return 0;
}
}
return -ENODATA;
}
EXPORT_SYMBOL_GPL(of_property_read_string_index);
/**
* of_property_match_string() - Find string in a list and return index
* @np: pointer to node containing string list property
* @propname: string list property name
* @string: pointer to string to search for in string list
*
* This function searches a string list property and returns the index
* of a specific string value.
*/
int of_property_match_string(struct device_node *np, const char *propname,
const char *string)
{
struct property *prop = of_find_property(np, propname, NULL);
size_t l;
int i;
const char *p, *end;
if (!prop)
return -EINVAL;
if (!prop->value)
return -ENODATA;
p = prop->value;
end = p + prop->length;
for (i = 0; p < end; i++, p += l) {
l = strlen(p) + 1;
if (p + l > end)
return -EILSEQ;
pr_debug("comparing %s with %s\n", string, p);
if (strcmp(string, p) == 0)
return i; /* Found it; return index */
}
return -ENODATA;
}
EXPORT_SYMBOL_GPL(of_property_match_string);
/**
* of_property_count_strings - Find and return the number of strings from a
* multiple strings property.
* @np: device node from which the property value is to be read.
* @propname: name of the property to be searched.
*
* Search for a property in a device tree node and retrieve the number of null
* terminated string contain in it. Returns the number of strings on
* success, -EINVAL if the property does not exist, -ENODATA if property
* does not have a value, and -EILSEQ if the string is not null-terminated
* within the length of the property data.
*/
int of_property_count_strings(struct device_node *np, const char *propname)
{
struct property *prop = of_find_property(np, propname, NULL);
int i = 0;
size_t l = 0, total = 0;
const char *p;
if (!prop)
return -EINVAL;
if (!prop->value)
return -ENODATA;
if (strnlen(prop->value, prop->length) >= prop->length)
return -EILSEQ;
p = prop->value;
for (i = 0; total < prop->length; total += l, p += l, i++)
l = strlen(p) + 1;
return i;
}
EXPORT_SYMBOL_GPL(of_property_count_strings);
/**
* of_parse_phandle - Resolve a phandle property to a device_node pointer
* @np: Pointer to device node holding phandle property
* @phandle_name: Name of property holding a phandle value
* @index: For properties holding a table of phandles, this is the index into
* the table
*
* Returns the device_node pointer with refcount incremented. Use
* of_node_put() on it when done.
*/
struct device_node *
of_parse_phandle(struct device_node *np, const char *phandle_name, int index)
{
const __be32 *phandle;
int size;
phandle = of_get_property(np, phandle_name, &size);
if ((!phandle) || (size < sizeof(*phandle) * (index + 1)))
return NULL;
return of_find_node_by_phandle(be32_to_cpup(phandle + index));
}
EXPORT_SYMBOL(of_parse_phandle);
/**
* of_parse_phandle_with_args() - Find a node pointed by phandle in a list
* @np: pointer to a device tree node containing a list
* @list_name: property name that contains a list
* @cells_name: property name that specifies phandles' arguments count
* @index: index of a phandle to parse out
* @out_args: optional pointer to output arguments structure (will be filled)
*
* This function is useful to parse lists of phandles and their arguments.
* Returns 0 on success and fills out_args, on error returns appropriate
* errno value.
*
* Caller is responsible to call of_node_put() on the returned out_args->node
* pointer.
*
* Example:
*
* phandle1: node1 {
* #list-cells = <2>;
* }
*
* phandle2: node2 {
* #list-cells = <1>;
* }
*
* node3 {
* list = <&phandle1 1 2 &phandle2 3>;
* }
*
* To get a device_node of the `node2' node you may call this:
* of_parse_phandle_with_args(node3, "list", "#list-cells", 1, &args);
*/
int of_parse_phandle_with_args(struct device_node *np, const char *list_name,
const char *cells_name, int index,
struct of_phandle_args *out_args)
{
const __be32 *list, *list_end;
int size, cur_index = 0;
uint32_t count = 0;
struct device_node *node = NULL;
phandle phandle;
/* Retrieve the phandle list property */
list = of_get_property(np, list_name, &size);
if (!list)
return -EINVAL;
list_end = list + size / sizeof(*list);
/* Loop over the phandles until all the requested entry is found */
while (list < list_end) {
count = 0;
/*
* If phandle is 0, then it is an empty entry with no
* arguments. Skip forward to the next entry.
*/
phandle = be32_to_cpup(list++);
if (phandle) {
/*
* Find the provider node and parse the #*-cells
* property to determine the argument length
*/
node = of_find_node_by_phandle(phandle);
if (!node) {
pr_err("%s: could not find phandle\n",
np->full_name);
break;
}
if (of_property_read_u32(node, cells_name, &count)) {
pr_err("%s: could not get %s for %s\n",
np->full_name, cells_name,
node->full_name);
break;
}
/*
* Make sure that the arguments actually fit in the
* remaining property data length
*/
if (list + count > list_end) {
pr_err("%s: arguments longer than property\n",
np->full_name);
break;
}
}
/*
* All of the error cases above bail out of the loop, so at
* this point, the parsing is successful. If the requested
* index matches, then fill the out_args structure and return,
* or return -ENOENT for an empty entry.
*/
if (cur_index == index) {
if (!phandle)
return -ENOENT;
if (out_args) {
int i;
if (WARN_ON(count > MAX_PHANDLE_ARGS))
count = MAX_PHANDLE_ARGS;
out_args->np = node;
out_args->args_count = count;
for (i = 0; i < count; i++)
out_args->args[i] = be32_to_cpup(list++);
}
return 0;
}
of_node_put(node);
node = NULL;
list += count;
cur_index++;
}
/* Loop exited without finding a valid entry; return an error */
if (node)
of_node_put(node);
return -EINVAL;
}
EXPORT_SYMBOL(of_parse_phandle_with_args);
/**
* prom_add_property - Add a property to a node
*/
int prom_add_property(struct device_node *np, struct property *prop)
{
struct property **next;
unsigned long flags;
prop->next = NULL;
write_lock_irqsave(&devtree_lock, flags);
next = &np->properties;
while (*next) {
if (strcmp(prop->name, (*next)->name) == 0) {
/* duplicate ! don't insert it */
write_unlock_irqrestore(&devtree_lock, flags);
return -1;
}
next = &(*next)->next;
}
*next = prop;
write_unlock_irqrestore(&devtree_lock, flags);
#ifdef CONFIG_PROC_DEVICETREE
/* try to add to proc as well if it was initialized */
if (np->pde)
proc_device_tree_add_prop(np->pde, prop);
#endif /* CONFIG_PROC_DEVICETREE */
return 0;
}
/**
* prom_remove_property - Remove a property from a node.
*
* Note that we don't actually remove it, since we have given out
* who-knows-how-many pointers to the data using get-property.
* Instead we just move the property to the "dead properties"
* list, so it won't be found any more.
*/
int prom_remove_property(struct device_node *np, struct property *prop)
{
struct property **next;
unsigned long flags;
int found = 0;
write_lock_irqsave(&devtree_lock, flags);
next = &np->properties;
while (*next) {
if (*next == prop) {
/* found the node */
*next = prop->next;
prop->next = np->deadprops;
np->deadprops = prop;
found = 1;
break;
}
next = &(*next)->next;
}
write_unlock_irqrestore(&devtree_lock, flags);
if (!found)
return -ENODEV;
#ifdef CONFIG_PROC_DEVICETREE
/* try to remove the proc node as well */
if (np->pde)
proc_device_tree_remove_prop(np->pde, prop);
#endif /* CONFIG_PROC_DEVICETREE */
return 0;
}
/*
* prom_update_property - Update a property in a node.
*
* Note that we don't actually remove it, since we have given out
* who-knows-how-many pointers to the data using get-property.
* Instead we just move the property to the "dead properties" list,
* and add the new property to the property list
*/
int prom_update_property(struct device_node *np,
struct property *newprop,
struct property *oldprop)
{
struct property **next;
unsigned long flags;
int found = 0;
write_lock_irqsave(&devtree_lock, flags);
next = &np->properties;
while (*next) {
if (*next == oldprop) {
/* found the node */
newprop->next = oldprop->next;
*next = newprop;
oldprop->next = np->deadprops;
np->deadprops = oldprop;
found = 1;
break;
}
next = &(*next)->next;
}
write_unlock_irqrestore(&devtree_lock, flags);
if (!found)
return -ENODEV;
#ifdef CONFIG_PROC_DEVICETREE
/* try to add to proc as well if it was initialized */
if (np->pde)
proc_device_tree_update_prop(np->pde, newprop, oldprop);
#endif /* CONFIG_PROC_DEVICETREE */
return 0;
}
#if defined(CONFIG_OF_DYNAMIC)
/*
* Support for dynamic device trees.
*
* On some platforms, the device tree can be manipulated at runtime.
* The routines in this section support adding, removing and changing
* device tree nodes.
*/
/**
* of_attach_node - Plug a device node into the tree and global list.
*/
void of_attach_node(struct device_node *np)
{
unsigned long flags;
write_lock_irqsave(&devtree_lock, flags);
np->sibling = np->parent->child;
np->allnext = allnodes;
np->parent->child = np;
allnodes = np;
write_unlock_irqrestore(&devtree_lock, flags);
}
/**
* of_detach_node - "Unplug" a node from the device tree.
*
* The caller must hold a reference to the node. The memory associated with
* the node is not freed until its refcount goes to zero.
*/
void of_detach_node(struct device_node *np)
{
struct device_node *parent;
unsigned long flags;
write_lock_irqsave(&devtree_lock, flags);
parent = np->parent;
if (!parent)
goto out_unlock;
if (allnodes == np)
allnodes = np->allnext;
else {
struct device_node *prev;
for (prev = allnodes;
prev->allnext != np;
prev = prev->allnext)
;
prev->allnext = np->allnext;
}
if (parent->child == np)
parent->child = np->sibling;
else {
struct device_node *prevsib;
for (prevsib = np->parent->child;
prevsib->sibling != np;
prevsib = prevsib->sibling)
;
prevsib->sibling = np->sibling;
}
of_node_set_flag(np, OF_DETACHED);
out_unlock:
write_unlock_irqrestore(&devtree_lock, flags);
}
#endif /* defined(CONFIG_OF_DYNAMIC) */
static void of_alias_add(struct alias_prop *ap, struct device_node *np,
int id, const char *stem, int stem_len)
{
ap->np = np;
ap->id = id;
strncpy(ap->stem, stem, stem_len);
ap->stem[stem_len] = 0;
list_add_tail(&ap->link, &aliases_lookup);
pr_debug("adding DT alias:%s: stem=%s id=%i node=%s\n",
ap->alias, ap->stem, ap->id, np ? np->full_name : NULL);
}
/**
* of_alias_scan - Scan all properties of 'aliases' node
*
* The function scans all the properties of 'aliases' node and populate
* the the global lookup table with the properties. It returns the
* number of alias_prop found, or error code in error case.
*
* @dt_alloc: An allocator that provides a virtual address to memory
* for the resulting tree
*/
void of_alias_scan(void * (*dt_alloc)(u64 size, u64 align))
{
struct property *pp;
of_chosen = of_find_node_by_path("/chosen");
if (of_chosen == NULL)
of_chosen = of_find_node_by_path("/chosen@0");
of_aliases = of_find_node_by_path("/aliases");
if (!of_aliases)
return;
for_each_property_of_node(of_aliases, pp) {
const char *start = pp->name;
const char *end = start + strlen(start);
struct device_node *np;
struct alias_prop *ap;
int id, len;
/* Skip those we do not want to proceed */
if (!strcmp(pp->name, "name") ||
!strcmp(pp->name, "phandle") ||
!strcmp(pp->name, "linux,phandle"))
continue;
np = of_find_node_by_path(pp->value);
if (!np)
continue;
/* walk the alias backwards to extract the id and work out
* the 'stem' string */
while (isdigit(*(end-1)) && end > start)
end--;
len = end - start;
if (kstrtoint(end, 10, &id) < 0)
continue;
/* Allocate an alias_prop with enough space for the stem */
ap = dt_alloc(sizeof(*ap) + len + 1, 4);
if (!ap)
continue;
ap->alias = start;
of_alias_add(ap, np, id, start, len);
}
}
/**
* of_alias_get_id - Get alias id for the given device_node
* @np: Pointer to the given device_node
* @stem: Alias stem of the given device_node
*
* The function travels the lookup table to get alias id for the given
* device_node and alias stem. It returns the alias id if find it.
*/
int of_alias_get_id(struct device_node *np, const char *stem)
{
struct alias_prop *app;
int id = -ENODEV;
mutex_lock(&of_aliases_mutex);
list_for_each_entry(app, &aliases_lookup, link) {
if (strcmp(app->stem, stem) != 0)
continue;
if (np == app->np) {
id = app->id;
break;
}
}
mutex_unlock(&of_aliases_mutex);
return id;
}
EXPORT_SYMBOL_GPL(of_alias_get_id);
| gpl-2.0 |
Demon000/libra | drivers/mtd/maps/autcpu12-nvram.c | 2159 | 3518 | /*
* NV-RAM memory access on autcpu12
* (C) 2002 Thomas Gleixner (gleixner@autronix.de)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/err.h>
#include <linux/sizes.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/map.h>
struct autcpu12_nvram_priv {
struct mtd_info *mtd;
struct map_info map;
};
static int autcpu12_nvram_probe(struct platform_device *pdev)
{
map_word tmp, save0, save1;
struct resource *res;
struct autcpu12_nvram_priv *priv;
priv = devm_kzalloc(&pdev->dev,
sizeof(struct autcpu12_nvram_priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
platform_set_drvdata(pdev, priv);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
dev_err(&pdev->dev, "failed to get memory resource\n");
return -ENOENT;
}
priv->map.bankwidth = 4;
priv->map.phys = res->start;
priv->map.size = resource_size(res);
priv->map.virt = devm_ioremap_resource(&pdev->dev, res);
strcpy((char *)priv->map.name, res->name);
if (IS_ERR(priv->map.virt))
return PTR_ERR(priv->map.virt);
simple_map_init(&priv->map);
/*
* Check for 32K/128K
* read ofs 0
* read ofs 0x10000
* Write complement to ofs 0x100000
* Read and check result on ofs 0x0
* Restore contents
*/
save0 = map_read(&priv->map, 0);
save1 = map_read(&priv->map, 0x10000);
tmp.x[0] = ~save0.x[0];
map_write(&priv->map, tmp, 0x10000);
tmp = map_read(&priv->map, 0);
/* if we find this pattern on 0x0, we have 32K size */
if (!map_word_equal(&priv->map, tmp, save0)) {
map_write(&priv->map, save0, 0x0);
priv->map.size = SZ_32K;
} else
map_write(&priv->map, save1, 0x10000);
priv->mtd = do_map_probe("map_ram", &priv->map);
if (!priv->mtd) {
dev_err(&pdev->dev, "probing failed\n");
return -ENXIO;
}
priv->mtd->owner = THIS_MODULE;
priv->mtd->erasesize = 16;
priv->mtd->dev.parent = &pdev->dev;
if (!mtd_device_register(priv->mtd, NULL, 0)) {
dev_info(&pdev->dev,
"NV-RAM device size %ldKiB registered on AUTCPU12\n",
priv->map.size / SZ_1K);
return 0;
}
map_destroy(priv->mtd);
dev_err(&pdev->dev, "NV-RAM device addition failed\n");
return -ENOMEM;
}
static int autcpu12_nvram_remove(struct platform_device *pdev)
{
struct autcpu12_nvram_priv *priv = platform_get_drvdata(pdev);
mtd_device_unregister(priv->mtd);
map_destroy(priv->mtd);
return 0;
}
static struct platform_driver autcpu12_nvram_driver = {
.driver = {
.name = "autcpu12_nvram",
.owner = THIS_MODULE,
},
.probe = autcpu12_nvram_probe,
.remove = autcpu12_nvram_remove,
};
module_platform_driver(autcpu12_nvram_driver);
MODULE_AUTHOR("Thomas Gleixner");
MODULE_DESCRIPTION("autcpu12 NVRAM map driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
ElectryDev/android_kernel_lenovo_msm8974_dv | drivers/power/bq28400_battery.c | 2159 | 25268 | /* Copyright (c) 2012-2013 The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
/*
* High Level description:
* http://www.ti.com/lit/ds/symlink/bq28400.pdf
* Thechnical Reference:
* http://www.ti.com/lit/ug/sluu431/sluu431.pdf
*/
#define pr_fmt(fmt) "%s: " fmt, __func__
#include <linux/i2c.h>
#include <linux/gpio.h>
#include <linux/errno.h>
#include <linux/delay.h>
#include <linux/module.h>
#include <linux/debugfs.h>
#include <linux/workqueue.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include <linux/power_supply.h>
#include <linux/bitops.h>
#include <linux/regulator/consumer.h>
#include <linux/printk.h>
#define BQ28400_NAME "bq28400"
#define BQ28400_REV "1.0"
/* SBS Commands (page 63) */
#define SBS_MANUFACTURER_ACCESS 0x00
#define SBS_BATTERY_MODE 0x03
#define SBS_TEMPERATURE 0x08
#define SBS_VOLTAGE 0x09
#define SBS_CURRENT 0x0A
#define SBS_AVG_CURRENT 0x0B
#define SBS_MAX_ERROR 0x0C
#define SBS_RSOC 0x0D /* Relative State Of Charge */
#define SBS_REMAIN_CAPACITY 0x0F
#define SBS_FULL_CAPACITY 0x10
#define SBS_CHG_CURRENT 0x14
#define SBS_CHG_VOLTAGE 0x15
#define SBS_BATTERY_STATUS 0x16
#define SBS_CYCLE_COUNT 0x17
#define SBS_DESIGN_CAPACITY 0x18
#define SBS_DESIGN_VOLTAGE 0x19
#define SBS_SPEC_INFO 0x1A
#define SBS_MANUFACTURE_DATE 0x1B
#define SBS_SERIAL_NUMBER 0x1C
#define SBS_MANUFACTURER_NAME 0x20
#define SBS_DEVICE_NAME 0x21
#define SBS_DEVICE_CHEMISTRY 0x22
#define SBS_MANUFACTURER_DATA 0x23
#define SBS_AUTHENTICATE 0x2F
#define SBS_CELL_VOLTAGE1 0x3E
#define SBS_CELL_VOLTAGE2 0x3F
/* Extended SBS Commands (page 71) */
#define SBS_FET_CONTROL 0x46
#define SBS_SAFETY_ALERT 0x50
#define SBS_SAFETY_STATUS 0x51
#define SBS_PE_ALERT 0x52
#define SBS_PE_STATUS 0x53
#define SBS_OPERATION_STATUS 0x54
#define SBS_CHARGING_STATUS 0x55
#define SBS_FET_STATUS 0x56
#define SBS_PACK_VOLTAGE 0x5A
#define SBS_TS0_TEMPERATURE 0x5E
#define SBS_FULL_ACCESS_KEY 0x61
#define SBS_PF_KEY 0x62
#define SBS_AUTH_KEY3 0x63
#define SBS_AUTH_KEY2 0x64
#define SBS_AUTH_KEY1 0x65
#define SBS_AUTH_KEY0 0x66
#define SBS_MANUFACTURER_INFO 0x70
#define SBS_SENSE_RESISTOR 0x71
#define SBS_TEMP_RANGE 0x72
/* SBS Sub-Commands (16 bits) */
/* SBS_MANUFACTURER_ACCESS CMD */
#define SUBCMD_DEVICE_TYPE 0x01
#define SUBCMD_FIRMWARE_VERSION 0x02
#define SUBCMD_HARDWARE_VERSION 0x03
#define SUBCMD_DF_CHECKSUM 0x04
#define SUBCMD_EDV 0x05
#define SUBCMD_CHEMISTRY_ID 0x08
/* SBS_CHARGING_STATUS */
#define CHG_STATUS_BATTERY_DEPLETED BIT(0)
#define CHG_STATUS_OVERCHARGE BIT(1)
#define CHG_STATUS_OVERCHARGE_CURRENT BIT(2)
#define CHG_STATUS_OVERCHARGE_VOLTAGE BIT(3)
#define CHG_STATUS_CELL_BALANCING BIT(6)
#define CHG_STATUS_HOT_TEMP_CHARGING BIT(8)
#define CHG_STATUS_STD1_TEMP_CHARGING BIT(9)
#define CHG_STATUS_STD2_TEMP_CHARGING BIT(10)
#define CHG_STATUS_LOW_TEMP_CHARGING BIT(11)
#define CHG_STATUS_PRECHARGING_EXIT BIT(13)
#define CHG_STATUS_SUSPENDED BIT(14)
#define CHG_STATUS_DISABLED BIT(15)
/* SBS_FET_STATUS */
#define FET_STATUS_DISCHARGE BIT(1)
#define FET_STATUS_CHARGE BIT(2)
#define FET_STATUS_PRECHARGE BIT(3)
/* SBS_BATTERY_STATUS */
#define BAT_STATUS_SBS_ERROR 0x0F
#define BAT_STATUS_EMPTY BIT(4)
#define BAT_STATUS_FULL BIT(5)
#define BAT_STATUS_DISCHARGING BIT(6)
#define BAT_STATUS_OVER_TEMPERATURE BIT(12)
#define BAT_STATUS_OVER_CHARGED BIT(15)
#define ZERO_DEGREE_CELSIUS_IN_TENTH_KELVIN (-2731)
#define BQ_TERMINATION_CURRENT_MA 200
#define BQ_MAX_STR_LEN 32
struct bq28400_device {
struct i2c_client *client;
struct delayed_work periodic_user_space_update_work;
struct dentry *dent;
struct power_supply batt_psy;
struct power_supply *dc_psy;
bool is_charging_enabled;
u32 temp_cold; /* in degree celsius */
u32 temp_hot; /* in degree celsius */
};
static struct bq28400_device *bq28400_dev;
static enum power_supply_property pm_power_props[] = {
POWER_SUPPLY_PROP_STATUS,
POWER_SUPPLY_PROP_CHARGE_TYPE,
POWER_SUPPLY_PROP_PRESENT,
POWER_SUPPLY_PROP_TECHNOLOGY,
POWER_SUPPLY_PROP_VOLTAGE_NOW,
POWER_SUPPLY_PROP_CAPACITY,
POWER_SUPPLY_PROP_CURRENT_NOW,
POWER_SUPPLY_PROP_CURRENT_AVG,
POWER_SUPPLY_PROP_TEMP,
POWER_SUPPLY_PROP_CHARGE_FULL,
POWER_SUPPLY_PROP_CHARGE_NOW,
POWER_SUPPLY_PROP_MODEL_NAME,
POWER_SUPPLY_PROP_MANUFACTURER,
};
struct debug_reg {
char *name;
u8 reg;
u16 subcmd;
};
static int fake_battery = -EINVAL;
module_param(fake_battery, int, 0644);
#define BQ28400_DEBUG_REG(x) {#x, SBS_##x, 0}
#define BQ28400_DEBUG_SUBREG(x, y) {#y, SBS_##x, SUBCMD_##y}
/* Note: Some register can be read only in Unsealed mode */
static struct debug_reg bq28400_debug_regs[] = {
BQ28400_DEBUG_REG(MANUFACTURER_ACCESS),
BQ28400_DEBUG_REG(BATTERY_MODE),
BQ28400_DEBUG_REG(TEMPERATURE),
BQ28400_DEBUG_REG(VOLTAGE),
BQ28400_DEBUG_REG(CURRENT),
BQ28400_DEBUG_REG(AVG_CURRENT),
BQ28400_DEBUG_REG(MAX_ERROR),
BQ28400_DEBUG_REG(RSOC),
BQ28400_DEBUG_REG(REMAIN_CAPACITY),
BQ28400_DEBUG_REG(FULL_CAPACITY),
BQ28400_DEBUG_REG(CHG_CURRENT),
BQ28400_DEBUG_REG(CHG_VOLTAGE),
BQ28400_DEBUG_REG(BATTERY_STATUS),
BQ28400_DEBUG_REG(CYCLE_COUNT),
BQ28400_DEBUG_REG(DESIGN_CAPACITY),
BQ28400_DEBUG_REG(DESIGN_VOLTAGE),
BQ28400_DEBUG_REG(SPEC_INFO),
BQ28400_DEBUG_REG(MANUFACTURE_DATE),
BQ28400_DEBUG_REG(SERIAL_NUMBER),
BQ28400_DEBUG_REG(MANUFACTURER_NAME),
BQ28400_DEBUG_REG(DEVICE_NAME),
BQ28400_DEBUG_REG(DEVICE_CHEMISTRY),
BQ28400_DEBUG_REG(MANUFACTURER_DATA),
BQ28400_DEBUG_REG(AUTHENTICATE),
BQ28400_DEBUG_REG(CELL_VOLTAGE1),
BQ28400_DEBUG_REG(CELL_VOLTAGE2),
BQ28400_DEBUG_REG(SAFETY_ALERT),
BQ28400_DEBUG_REG(SAFETY_STATUS),
BQ28400_DEBUG_REG(PE_ALERT),
BQ28400_DEBUG_REG(PE_STATUS),
BQ28400_DEBUG_REG(OPERATION_STATUS),
BQ28400_DEBUG_REG(CHARGING_STATUS),
BQ28400_DEBUG_REG(FET_STATUS),
BQ28400_DEBUG_REG(FULL_ACCESS_KEY),
BQ28400_DEBUG_REG(PF_KEY),
BQ28400_DEBUG_REG(MANUFACTURER_INFO),
BQ28400_DEBUG_REG(SENSE_RESISTOR),
BQ28400_DEBUG_REG(TEMP_RANGE),
BQ28400_DEBUG_SUBREG(MANUFACTURER_ACCESS, DEVICE_TYPE),
BQ28400_DEBUG_SUBREG(MANUFACTURER_ACCESS, FIRMWARE_VERSION),
BQ28400_DEBUG_SUBREG(MANUFACTURER_ACCESS, HARDWARE_VERSION),
BQ28400_DEBUG_SUBREG(MANUFACTURER_ACCESS, DF_CHECKSUM),
BQ28400_DEBUG_SUBREG(MANUFACTURER_ACCESS, EDV),
BQ28400_DEBUG_SUBREG(MANUFACTURER_ACCESS, CHEMISTRY_ID),
};
static int bq28400_read_reg(struct i2c_client *client, u8 reg)
{
int val;
val = i2c_smbus_read_word_data(client, reg);
if (val < 0)
pr_err("i2c read fail. reg = 0x%x.ret = %d.\n", reg, val);
else
pr_debug("reg = 0x%02X.val = 0x%04X.\n", reg , val);
return val;
}
static int bq28400_write_reg(struct i2c_client *client, u8 reg, u16 val)
{
int ret;
ret = i2c_smbus_write_word_data(client, reg, val);
if (ret < 0)
pr_err("i2c read fail. reg = 0x%x.val = 0x%x.ret = %d.\n",
reg, val, ret);
else
pr_debug("reg = 0x%02X.val = 0x%02X.\n", reg , val);
return ret;
}
static int bq28400_read_subcmd(struct i2c_client *client, u8 reg, u16 subcmd)
{
int ret;
u8 buf[4];
u16 val = 0;
buf[0] = reg;
buf[1] = subcmd & 0xFF;
buf[2] = (subcmd >> 8) & 0xFF;
/* Control sub-command */
ret = i2c_master_send(client, buf, 3);
if (ret < 0) {
pr_err("i2c tx fail. reg = 0x%x.ret = %d.\n", reg, ret);
return ret;
}
udelay(66);
/* Read Result of subcmd */
ret = i2c_master_send(client, buf, 1);
memset(buf, 0xAA, sizeof(buf));
ret = i2c_master_recv(client, buf, 2);
if (ret < 0) {
pr_err("i2c rx fail. reg = 0x%x.ret = %d.\n", reg, ret);
return ret;
}
val = (buf[1] << 8) + buf[0];
pr_debug("reg = 0x%02X.subcmd = 0x%x.val = 0x%04X.\n",
reg , subcmd, val);
return val;
}
static int bq28400_read_block(struct i2c_client *client, u8 reg,
u8 len, u8 *buf)
{
int ret;
u32 val;
ret = i2c_smbus_read_i2c_block_data(client, reg, len, buf);
val = buf[0] + (buf[1] << 8) + (buf[2] << 16) + (buf[3] << 24);
if (ret < 0)
pr_err("i2c read fail. reg = 0x%x.ret = %d.\n", reg, ret);
else
pr_debug("reg = 0x%02X.val = 0x%04X.\n", reg , val);
return val;
}
/*
* Read a string from a device.
* Returns string length on success or error on failure (negative value).
*/
static int bq28400_read_string(struct i2c_client *client, u8 reg, char *str,
u8 max_len)
{
int ret;
int len;
ret = bq28400_read_block(client, reg, max_len, str);
if (ret < 0)
return ret;
len = str[0]; /* Actual length */
if (len > max_len - 2) { /* reduce len byte and null */
pr_err("len = %d invalid.\n", len);
return -EINVAL;
}
memcpy(&str[0], &str[1], len); /* Move sting to the start */
str[len] = 0; /* put NULL after actual size */
pr_debug("len = %d.str = %s.\n", len, str);
return len;
}
#define BQ28400_INVALID_TEMPERATURE -999
/*
* Return the battery temperature in tenths of degree Celsius
* Or -99.9 C if something fails.
*/
static int bq28400_read_temperature(struct i2c_client *client)
{
int temp;
/* temperature resolution 0.1 Kelvin */
temp = bq28400_read_reg(client, SBS_TEMPERATURE);
if (temp < 0)
return BQ28400_INVALID_TEMPERATURE;
temp = temp + ZERO_DEGREE_CELSIUS_IN_TENTH_KELVIN;
pr_debug("temp = %d C\n", temp/10);
return temp;
}
/*
* Return the battery Voltage in milivolts 0..20 V
* Or < 0 if something fails.
*/
static int bq28400_read_voltage(struct i2c_client *client)
{
int mvolt = 0;
mvolt = bq28400_read_reg(client, SBS_VOLTAGE);
if (mvolt < 0)
return mvolt;
pr_debug("volt = %d mV.\n", mvolt);
return mvolt;
}
/*
* Return the battery Current in miliamps
* Or 0 if something fails.
* Positive current indicates charging
* Negative current indicates discharging.
* Current-now is calculated every second.
*/
static int bq28400_read_current(struct i2c_client *client)
{
s16 current_ma = 0;
current_ma = bq28400_read_reg(client, SBS_CURRENT);
pr_debug("current = %d mA.\n", current_ma);
return current_ma;
}
/*
* Return the Average battery Current in miliamps
* Or 0 if something fails.
* Positive current indicates charging
* Negative current indicates discharging.
* Average Current is the rolling 1 minute average current.
*/
static int bq28400_read_avg_current(struct i2c_client *client)
{
s16 current_ma = 0;
current_ma = bq28400_read_reg(client, SBS_AVG_CURRENT);
pr_debug("avg_current=%d mA.\n", current_ma);
return current_ma;
}
/*
* Return the battery Relative-State-Of-Charge 0..100 %
* Or negative value if something fails.
*/
static int bq28400_read_rsoc(struct i2c_client *client)
{
int percentage = 0;
if (fake_battery != -EINVAL) {
pr_debug("Reporting Fake SOC = %d\n", fake_battery);
return fake_battery;
}
/* This register is only 1 byte */
percentage = i2c_smbus_read_byte_data(client, SBS_RSOC);
if (percentage < 0) {
pr_err("I2C failure when reading rsoc.\n");
return percentage;
}
pr_debug("percentage = %d.\n", percentage);
return percentage;
}
/*
* Return the battery Capacity in mAh.
* Or 0 if something fails.
*/
static int bq28400_read_full_capacity(struct i2c_client *client)
{
int capacity = 0;
capacity = bq28400_read_reg(client, SBS_FULL_CAPACITY);
if (capacity < 0)
return 0;
pr_debug("full-capacity = %d mAh.\n", capacity);
return capacity;
}
/*
* Return the battery Capacity in mAh.
* Or 0 if something fails.
*/
static int bq28400_read_remain_capacity(struct i2c_client *client)
{
int capacity = 0;
capacity = bq28400_read_reg(client, SBS_REMAIN_CAPACITY);
if (capacity < 0)
return 0;
pr_debug("remain-capacity = %d mAh.\n", capacity);
return capacity;
}
static int bq28400_enable_charging(struct bq28400_device *bq28400_dev,
bool enable)
{
int ret;
static bool is_charging_enabled;
if (bq28400_dev->dc_psy == NULL) {
bq28400_dev->dc_psy = power_supply_get_by_name("dc");
if (bq28400_dev->dc_psy == NULL) {
pr_err("fail to get dc-psy.\n");
return -ENODEV;
}
}
if (is_charging_enabled == enable) {
pr_debug("Charging enable already = %d.\n", enable);
return 0;
}
ret = power_supply_set_online(bq28400_dev->dc_psy, enable);
if (ret < 0) {
pr_err("fail to set dc-psy online to %d.\n", enable);
return ret;
}
is_charging_enabled = enable;
pr_debug("Charging enable = %d.\n", enable);
return 0;
}
static int bq28400_get_prop_status(struct i2c_client *client)
{
int status = POWER_SUPPLY_STATUS_UNKNOWN;
int rsoc;
s16 current_ma = 0;
u16 battery_status;
int temperature;
struct bq28400_device *dev = i2c_get_clientdata(client);
battery_status = bq28400_read_reg(client, SBS_BATTERY_STATUS);
rsoc = bq28400_read_rsoc(client);
current_ma = bq28400_read_current(client);
temperature = bq28400_read_temperature(client);
temperature = temperature / 10; /* in degree celsius */
if (battery_status & BAT_STATUS_EMPTY)
pr_debug("Battery report Empty.\n");
/* Battery may report FULL before rsoc is 100%
* for protection and cell-balancing.
* The FULL report may remain when rsoc drops from 100%.
* If battery is full but DC-Jack is removed then report discahrging.
*/
if (battery_status & BAT_STATUS_FULL) {
pr_debug("Battery report Full.\n");
bq28400_enable_charging(bq28400_dev, false);
if (current_ma < 0)
return POWER_SUPPLY_STATUS_DISCHARGING;
return POWER_SUPPLY_STATUS_FULL;
}
if (rsoc == 100) {
bq28400_enable_charging(bq28400_dev, false);
pr_debug("Full.\n");
return POWER_SUPPLY_STATUS_FULL;
}
/* Enable charging when battery is not full and temperature is ok */
if ((temperature > dev->temp_cold) && (temperature < dev->temp_hot))
bq28400_enable_charging(bq28400_dev, true);
else
bq28400_enable_charging(bq28400_dev, false);
/*
* Positive current indicates charging
* Negative current indicates discharging.
* Charging is stopped at termination-current.
*/
if (current_ma < 0) {
pr_debug("Discharging.\n");
status = POWER_SUPPLY_STATUS_DISCHARGING;
} else if (current_ma > BQ_TERMINATION_CURRENT_MA) {
pr_debug("Charging.\n");
status = POWER_SUPPLY_STATUS_CHARGING;
} else {
pr_debug("Not Charging.\n");
status = POWER_SUPPLY_STATUS_NOT_CHARGING;
}
return status;
}
static int bq28400_get_prop_charge_type(struct i2c_client *client)
{
u16 battery_status;
u16 chg_status;
u16 fet_status;
battery_status = bq28400_read_reg(client, SBS_BATTERY_STATUS);
chg_status = bq28400_read_reg(client, SBS_CHARGING_STATUS);
fet_status = bq28400_read_reg(client, SBS_FET_STATUS);
if (battery_status & BAT_STATUS_DISCHARGING) {
pr_debug("Discharging.\n");
return POWER_SUPPLY_CHARGE_TYPE_NONE;
}
if (fet_status & FET_STATUS_PRECHARGE) {
pr_debug("Pre-Charging.\n");
return POWER_SUPPLY_CHARGE_TYPE_TRICKLE;
}
if (chg_status & CHG_STATUS_HOT_TEMP_CHARGING) {
pr_debug("Hot-Temp-Charging.\n");
return POWER_SUPPLY_CHARGE_TYPE_FAST;
}
if (chg_status & CHG_STATUS_LOW_TEMP_CHARGING) {
pr_debug("Low-Temp-Charging.\n");
return POWER_SUPPLY_CHARGE_TYPE_FAST;
}
if (chg_status & CHG_STATUS_STD1_TEMP_CHARGING) {
pr_debug("STD1-Temp-Charging.\n");
return POWER_SUPPLY_CHARGE_TYPE_FAST;
}
if (chg_status & CHG_STATUS_STD2_TEMP_CHARGING) {
pr_debug("STD2-Temp-Charging.\n");
return POWER_SUPPLY_CHARGE_TYPE_FAST;
}
if (chg_status & CHG_STATUS_BATTERY_DEPLETED)
pr_debug("battery_depleted.\n");
if (chg_status & CHG_STATUS_CELL_BALANCING)
pr_debug("cell_balancing.\n");
if (chg_status & CHG_STATUS_OVERCHARGE) {
pr_err("overcharge fault.\n");
return POWER_SUPPLY_CHARGE_TYPE_NONE;
}
if (chg_status & CHG_STATUS_SUSPENDED) {
pr_info("Suspended.\n");
return POWER_SUPPLY_CHARGE_TYPE_NONE;
}
if (chg_status & CHG_STATUS_DISABLED) {
pr_info("Disabled.\n");
return POWER_SUPPLY_CHARGE_TYPE_NONE;
}
return POWER_SUPPLY_CHARGE_TYPE_UNKNOWN;
}
static bool bq28400_get_prop_present(struct i2c_client *client)
{
int val;
val = bq28400_read_reg(client, SBS_BATTERY_STATUS);
/* If the bq28400 is inside the battery pack
* then when battery is removed the i2c transfer will fail.
*/
if (val < 0)
return false;
/* TODO - support when bq28400 is not embedded in battery pack */
return true;
}
/*
* User sapce read the battery info.
* Get data online via I2C from the battery gauge.
*/
static int bq28400_get_property(struct power_supply *psy,
enum power_supply_property psp,
union power_supply_propval *val)
{
int ret = 0;
struct bq28400_device *dev = container_of(psy,
struct bq28400_device,
batt_psy);
struct i2c_client *client = dev->client;
static char str[BQ_MAX_STR_LEN];
switch (psp) {
case POWER_SUPPLY_PROP_STATUS:
val->intval = bq28400_get_prop_status(client);
break;
case POWER_SUPPLY_PROP_CHARGE_TYPE:
val->intval = bq28400_get_prop_charge_type(client);
break;
case POWER_SUPPLY_PROP_PRESENT:
val->intval = bq28400_get_prop_present(client);
break;
case POWER_SUPPLY_PROP_VOLTAGE_NOW:
val->intval = bq28400_read_voltage(client);
val->intval *= 1000; /* mV to uV */
break;
case POWER_SUPPLY_PROP_CAPACITY:
val->intval = bq28400_read_rsoc(client);
if (val->intval < 0)
ret = -EINVAL;
break;
case POWER_SUPPLY_PROP_CURRENT_NOW:
/* Positive current indicates drawing */
val->intval = -bq28400_read_current(client);
val->intval *= 1000; /* mA to uA */
break;
case POWER_SUPPLY_PROP_CURRENT_AVG:
/* Positive current indicates drawing */
val->intval = -bq28400_read_avg_current(client);
val->intval *= 1000; /* mA to uA */
break;
case POWER_SUPPLY_PROP_TEMP:
val->intval = bq28400_read_temperature(client);
break;
case POWER_SUPPLY_PROP_CHARGE_FULL:
val->intval = bq28400_read_full_capacity(client);
break;
case POWER_SUPPLY_PROP_CHARGE_NOW:
val->intval = bq28400_read_remain_capacity(client);
break;
case POWER_SUPPLY_PROP_TECHNOLOGY:
val->intval = POWER_SUPPLY_TECHNOLOGY_LION;
break;
case POWER_SUPPLY_PROP_MODEL_NAME:
bq28400_read_string(client, SBS_DEVICE_NAME, str, 20);
val->strval = str;
break;
case POWER_SUPPLY_PROP_MANUFACTURER:
bq28400_read_string(client, SBS_MANUFACTURER_NAME, str, 20);
val->strval = str;
break;
default:
pr_err(" psp %d Not supoprted.\n", psp);
ret = -EINVAL;
break;
}
return ret;
}
static int bq28400_set_reg(void *data, u64 val)
{
struct debug_reg *dbg = data;
u8 reg = dbg->reg;
int ret;
struct i2c_client *client = bq28400_dev->client;
ret = bq28400_write_reg(client, reg, val);
return ret;
}
static int bq28400_get_reg(void *data, u64 *val)
{
struct debug_reg *dbg = data;
u8 reg = dbg->reg;
u16 subcmd = dbg->subcmd;
int ret;
struct i2c_client *client = bq28400_dev->client;
if (subcmd)
ret = bq28400_read_subcmd(client, reg, subcmd);
else
ret = bq28400_read_reg(client, reg);
if (ret < 0)
return ret;
*val = ret;
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(reg_fops, bq28400_get_reg, bq28400_set_reg,
"0x%04llx\n");
static int bq28400_create_debugfs_entries(struct bq28400_device *bq28400_dev)
{
int i;
bq28400_dev->dent = debugfs_create_dir(BQ28400_NAME, NULL);
if (IS_ERR(bq28400_dev->dent)) {
pr_err("bq28400 driver couldn't create debugfs dir\n");
return -EFAULT;
}
for (i = 0 ; i < ARRAY_SIZE(bq28400_debug_regs) ; i++) {
char *name = bq28400_debug_regs[i].name;
struct dentry *file;
void *data = &bq28400_debug_regs[i];
file = debugfs_create_file(name, 0644, bq28400_dev->dent,
data, ®_fops);
if (IS_ERR(file)) {
pr_err("debugfs_create_file %s failed.\n", name);
return -EFAULT;
}
}
return 0;
}
static int bq28400_set_property(struct power_supply *psy,
enum power_supply_property psp,
const union power_supply_propval *val)
{
pr_debug("psp = %d.val = %d.\n", psp, val->intval);
return -EINVAL;
}
static void bq28400_external_power_changed(struct power_supply *psy)
{
pr_debug("Notify power_supply_changed.\n");
/* The battery gauge monitors the current and voltage every 1 second.
* Therefore a delay from the time that the charger start/stop charging
* until the battery gauge detects it.
*/
msleep(1000);
/* Update LEDs and notify uevents */
power_supply_changed(&bq28400_dev->batt_psy);
}
static int __devinit bq28400_register_psy(struct bq28400_device *bq28400_dev)
{
int ret;
bq28400_dev->batt_psy.name = "battery";
bq28400_dev->batt_psy.type = POWER_SUPPLY_TYPE_BATTERY;
bq28400_dev->batt_psy.num_supplicants = 0;
bq28400_dev->batt_psy.properties = pm_power_props;
bq28400_dev->batt_psy.num_properties = ARRAY_SIZE(pm_power_props);
bq28400_dev->batt_psy.get_property = bq28400_get_property;
bq28400_dev->batt_psy.set_property = bq28400_set_property;
bq28400_dev->batt_psy.external_power_changed =
bq28400_external_power_changed;
ret = power_supply_register(&bq28400_dev->client->dev,
&bq28400_dev->batt_psy);
if (ret) {
pr_err("failed to register power_supply. ret=%d.\n", ret);
return ret;
}
return 0;
}
/**
* Update userspace every 1 minute.
* Normally it takes more than 120 minutes (two hours) to
* charge/discahrge the battery,
* so updating every 1 minute should be enough for 1% change
* detection.
* Any immidiate change detected by the DC charger is notified
* by the bq28400_external_power_changed callback, which notify
* the user space.
*/
static void bq28400_periodic_user_space_update_worker(struct work_struct *work)
{
u32 delay_msec = 60*1000;
pr_debug("Notify user space.\n");
/* Notify user space via kobject_uevent change notification */
power_supply_changed(&bq28400_dev->batt_psy);
schedule_delayed_work(&bq28400_dev->periodic_user_space_update_work,
round_jiffies_relative(msecs_to_jiffies
(delay_msec)));
}
static int __devinit bq28400_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
int ret = 0;
struct device_node *dev_node = client->dev.of_node;
if (dev_node == NULL) {
pr_err("Device Tree node doesn't exist.\n");
return -ENODEV;
}
if (!i2c_check_functionality(client->adapter,
I2C_FUNC_SMBUS_BYTE_DATA)) {
pr_err(" i2c func fail.\n");
return -EIO;
}
if (bq28400_read_reg(client, SBS_BATTERY_STATUS) < 0) {
pr_err("Device doesn't exist.\n");
return -ENODEV;
}
bq28400_dev = kzalloc(sizeof(*bq28400_dev), GFP_KERNEL);
if (!bq28400_dev) {
pr_err(" alloc fail.\n");
return -ENOMEM;
}
/* Note: Lithium-ion battery normal temperature range 0..40 C */
ret = of_property_read_u32(dev_node, "ti,temp-cold",
&(bq28400_dev->temp_cold));
if (ret) {
pr_err("Unable to read cold temperature. ret=%d.\n", ret);
goto err_dev_node;
}
pr_debug("cold temperature limit = %d C.\n", bq28400_dev->temp_cold);
ret = of_property_read_u32(dev_node, "ti,temp-hot",
&(bq28400_dev->temp_hot));
if (ret) {
pr_err("Unable to read hot temperature. ret=%d.\n", ret);
goto err_dev_node;
}
pr_debug("hot temperature limit = %d C.\n", bq28400_dev->temp_hot);
bq28400_dev->client = client;
i2c_set_clientdata(client, bq28400_dev);
ret = bq28400_register_psy(bq28400_dev);
if (ret) {
pr_err(" bq28400_register_psy fail.\n");
goto err_register_psy;
}
ret = bq28400_create_debugfs_entries(bq28400_dev);
if (ret) {
pr_err(" bq28400_create_debugfs_entries fail.\n");
goto err_debugfs;
}
INIT_DELAYED_WORK(&bq28400_dev->periodic_user_space_update_work,
bq28400_periodic_user_space_update_worker);
schedule_delayed_work(&bq28400_dev->periodic_user_space_update_work,
msecs_to_jiffies(1000));
pr_debug("Device is ready.\n");
return 0;
err_debugfs:
if (bq28400_dev->dent)
debugfs_remove_recursive(bq28400_dev->dent);
power_supply_unregister(&bq28400_dev->batt_psy);
err_register_psy:
err_dev_node:
kfree(bq28400_dev);
bq28400_dev = NULL;
pr_info("FAIL.\n");
return ret;
}
static int __devexit bq28400_remove(struct i2c_client *client)
{
struct bq28400_device *bq28400_dev = i2c_get_clientdata(client);
power_supply_unregister(&bq28400_dev->batt_psy);
if (bq28400_dev->dent)
debugfs_remove_recursive(bq28400_dev->dent);
kfree(bq28400_dev);
bq28400_dev = NULL;
return 0;
}
static const struct of_device_id bq28400_match[] = {
{ .compatible = "ti,bq28400-battery" },
{ .compatible = "ti,bq30z55-battery" },
{ },
};
static const struct i2c_device_id bq28400_id[] = {
{BQ28400_NAME, 0},
{},
};
MODULE_DEVICE_TABLE(i2c, bq28400_id);
static struct i2c_driver bq28400_driver = {
.driver = {
.name = BQ28400_NAME,
.owner = THIS_MODULE,
.of_match_table = of_match_ptr(bq28400_match),
},
.probe = bq28400_probe,
.remove = __devexit_p(bq28400_remove),
.id_table = bq28400_id,
};
static int __init bq28400_init(void)
{
pr_info(" bq28400 driver rev %s.\n", BQ28400_REV);
return i2c_add_driver(&bq28400_driver);
}
module_init(bq28400_init);
static void __exit bq28400_exit(void)
{
return i2c_del_driver(&bq28400_driver);
}
module_exit(bq28400_exit);
MODULE_DESCRIPTION("Driver for BQ28400 charger chip");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("i2c:" BQ28400_NAME);
| gpl-2.0 |
linuxvom/linux | drivers/media/usb/gspca/jeilinj.c | 2159 | 13905 | /*
* Jeilinj subdriver
*
* Supports some Jeilin dual-mode cameras which use bulk transport and
* download raw JPEG data.
*
* Copyright (C) 2009 Theodore Kilgore
*
* Sportscam DV15 support and control settings are
* Copyright (C) 2011 Patrice Chotard
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#define MODULE_NAME "jeilinj"
#include <linux/slab.h>
#include "gspca.h"
#include "jpeg.h"
MODULE_AUTHOR("Theodore Kilgore <kilgota@auburn.edu>");
MODULE_DESCRIPTION("GSPCA/JEILINJ USB Camera Driver");
MODULE_LICENSE("GPL");
/* Default timeouts, in ms */
#define JEILINJ_CMD_TIMEOUT 500
#define JEILINJ_CMD_DELAY 160
#define JEILINJ_DATA_TIMEOUT 1000
/* Maximum transfer size to use. */
#define JEILINJ_MAX_TRANSFER 0x200
#define FRAME_HEADER_LEN 0x10
#define FRAME_START 0xFFFFFFFF
enum {
SAKAR_57379,
SPORTSCAM_DV15,
};
#define CAMQUALITY_MIN 0 /* highest cam quality */
#define CAMQUALITY_MAX 97 /* lowest cam quality */
/* Structure to hold all of our device specific stuff */
struct sd {
struct gspca_dev gspca_dev; /* !! must be the first item */
int blocks_left;
const struct v4l2_pix_format *cap_mode;
struct v4l2_ctrl *freq;
struct v4l2_ctrl *jpegqual;
/* Driver stuff */
u8 type;
u8 quality; /* image quality */
#define QUALITY_MIN 35
#define QUALITY_MAX 85
#define QUALITY_DEF 85
u8 jpeg_hdr[JPEG_HDR_SZ];
};
struct jlj_command {
unsigned char instruction[2];
unsigned char ack_wanted;
unsigned char delay;
};
/* AFAICT these cameras will only do 320x240. */
static struct v4l2_pix_format jlj_mode[] = {
{ 320, 240, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE,
.bytesperline = 320,
.sizeimage = 320 * 240,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 0},
{ 640, 480, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE,
.bytesperline = 640,
.sizeimage = 640 * 480,
.colorspace = V4L2_COLORSPACE_JPEG,
.priv = 0}
};
/*
* cam uses endpoint 0x03 to send commands, 0x84 for read commands,
* and 0x82 for bulk transfer.
*/
/* All commands are two bytes only */
static void jlj_write2(struct gspca_dev *gspca_dev, unsigned char *command)
{
int retval;
if (gspca_dev->usb_err < 0)
return;
memcpy(gspca_dev->usb_buf, command, 2);
retval = usb_bulk_msg(gspca_dev->dev,
usb_sndbulkpipe(gspca_dev->dev, 3),
gspca_dev->usb_buf, 2, NULL, 500);
if (retval < 0) {
pr_err("command write [%02x] error %d\n",
gspca_dev->usb_buf[0], retval);
gspca_dev->usb_err = retval;
}
}
/* Responses are one byte only */
static void jlj_read1(struct gspca_dev *gspca_dev, unsigned char *response)
{
int retval;
if (gspca_dev->usb_err < 0)
return;
retval = usb_bulk_msg(gspca_dev->dev,
usb_rcvbulkpipe(gspca_dev->dev, 0x84),
gspca_dev->usb_buf, 1, NULL, 500);
*response = gspca_dev->usb_buf[0];
if (retval < 0) {
pr_err("read command [%02x] error %d\n",
gspca_dev->usb_buf[0], retval);
gspca_dev->usb_err = retval;
}
}
static void setfreq(struct gspca_dev *gspca_dev, s32 val)
{
u8 freq_commands[][2] = {
{0x71, 0x80},
{0x70, 0x07}
};
freq_commands[0][1] |= val >> 1;
jlj_write2(gspca_dev, freq_commands[0]);
jlj_write2(gspca_dev, freq_commands[1]);
}
static void setcamquality(struct gspca_dev *gspca_dev, s32 val)
{
u8 quality_commands[][2] = {
{0x71, 0x1E},
{0x70, 0x06}
};
u8 camquality;
/* adapt camera quality from jpeg quality */
camquality = ((QUALITY_MAX - val) * CAMQUALITY_MAX)
/ (QUALITY_MAX - QUALITY_MIN);
quality_commands[0][1] += camquality;
jlj_write2(gspca_dev, quality_commands[0]);
jlj_write2(gspca_dev, quality_commands[1]);
}
static void setautogain(struct gspca_dev *gspca_dev, s32 val)
{
u8 autogain_commands[][2] = {
{0x94, 0x02},
{0xcf, 0x00}
};
autogain_commands[1][1] = val << 4;
jlj_write2(gspca_dev, autogain_commands[0]);
jlj_write2(gspca_dev, autogain_commands[1]);
}
static void setred(struct gspca_dev *gspca_dev, s32 val)
{
u8 setred_commands[][2] = {
{0x94, 0x02},
{0xe6, 0x00}
};
setred_commands[1][1] = val;
jlj_write2(gspca_dev, setred_commands[0]);
jlj_write2(gspca_dev, setred_commands[1]);
}
static void setgreen(struct gspca_dev *gspca_dev, s32 val)
{
u8 setgreen_commands[][2] = {
{0x94, 0x02},
{0xe7, 0x00}
};
setgreen_commands[1][1] = val;
jlj_write2(gspca_dev, setgreen_commands[0]);
jlj_write2(gspca_dev, setgreen_commands[1]);
}
static void setblue(struct gspca_dev *gspca_dev, s32 val)
{
u8 setblue_commands[][2] = {
{0x94, 0x02},
{0xe9, 0x00}
};
setblue_commands[1][1] = val;
jlj_write2(gspca_dev, setblue_commands[0]);
jlj_write2(gspca_dev, setblue_commands[1]);
}
static int jlj_start(struct gspca_dev *gspca_dev)
{
int i;
int start_commands_size;
u8 response = 0xff;
struct sd *sd = (struct sd *) gspca_dev;
struct jlj_command start_commands[] = {
{{0x71, 0x81}, 0, 0},
{{0x70, 0x05}, 0, JEILINJ_CMD_DELAY},
{{0x95, 0x70}, 1, 0},
{{0x71, 0x81 - gspca_dev->curr_mode}, 0, 0},
{{0x70, 0x04}, 0, JEILINJ_CMD_DELAY},
{{0x95, 0x70}, 1, 0},
{{0x71, 0x00}, 0, 0}, /* start streaming ??*/
{{0x70, 0x08}, 0, JEILINJ_CMD_DELAY},
{{0x95, 0x70}, 1, 0},
#define SPORTSCAM_DV15_CMD_SIZE 9
{{0x94, 0x02}, 0, 0},
{{0xde, 0x24}, 0, 0},
{{0x94, 0x02}, 0, 0},
{{0xdd, 0xf0}, 0, 0},
{{0x94, 0x02}, 0, 0},
{{0xe3, 0x2c}, 0, 0},
{{0x94, 0x02}, 0, 0},
{{0xe4, 0x00}, 0, 0},
{{0x94, 0x02}, 0, 0},
{{0xe5, 0x00}, 0, 0},
{{0x94, 0x02}, 0, 0},
{{0xe6, 0x2c}, 0, 0},
{{0x94, 0x03}, 0, 0},
{{0xaa, 0x00}, 0, 0}
};
sd->blocks_left = 0;
/* Under Windows, USB spy shows that only the 9 first start
* commands are used for SPORTSCAM_DV15 webcam
*/
if (sd->type == SPORTSCAM_DV15)
start_commands_size = SPORTSCAM_DV15_CMD_SIZE;
else
start_commands_size = ARRAY_SIZE(start_commands);
for (i = 0; i < start_commands_size; i++) {
jlj_write2(gspca_dev, start_commands[i].instruction);
if (start_commands[i].delay)
msleep(start_commands[i].delay);
if (start_commands[i].ack_wanted)
jlj_read1(gspca_dev, &response);
}
setcamquality(gspca_dev, v4l2_ctrl_g_ctrl(sd->jpegqual));
msleep(2);
setfreq(gspca_dev, v4l2_ctrl_g_ctrl(sd->freq));
if (gspca_dev->usb_err < 0)
PERR("Start streaming command failed");
return gspca_dev->usb_err;
}
static void sd_pkt_scan(struct gspca_dev *gspca_dev,
u8 *data, int len)
{
struct sd *sd = (struct sd *) gspca_dev;
int packet_type;
u32 header_marker;
PDEBUG(D_STREAM, "Got %d bytes out of %d for Block 0",
len, JEILINJ_MAX_TRANSFER);
if (len != JEILINJ_MAX_TRANSFER) {
PDEBUG(D_PACK, "bad length");
goto discard;
}
/* check if it's start of frame */
header_marker = ((u32 *)data)[0];
if (header_marker == FRAME_START) {
sd->blocks_left = data[0x0a] - 1;
PDEBUG(D_STREAM, "blocks_left = 0x%x", sd->blocks_left);
/* Start a new frame, and add the JPEG header, first thing */
gspca_frame_add(gspca_dev, FIRST_PACKET,
sd->jpeg_hdr, JPEG_HDR_SZ);
/* Toss line 0 of data block 0, keep the rest. */
gspca_frame_add(gspca_dev, INTER_PACKET,
data + FRAME_HEADER_LEN,
JEILINJ_MAX_TRANSFER - FRAME_HEADER_LEN);
} else if (sd->blocks_left > 0) {
PDEBUG(D_STREAM, "%d blocks remaining for frame",
sd->blocks_left);
sd->blocks_left -= 1;
if (sd->blocks_left == 0)
packet_type = LAST_PACKET;
else
packet_type = INTER_PACKET;
gspca_frame_add(gspca_dev, packet_type,
data, JEILINJ_MAX_TRANSFER);
} else
goto discard;
return;
discard:
/* Discard data until a new frame starts. */
gspca_dev->last_packet_type = DISCARD_PACKET;
}
/* This function is called at probe time just before sd_init */
static int sd_config(struct gspca_dev *gspca_dev,
const struct usb_device_id *id)
{
struct cam *cam = &gspca_dev->cam;
struct sd *dev = (struct sd *) gspca_dev;
dev->type = id->driver_info;
dev->quality = QUALITY_DEF;
cam->cam_mode = jlj_mode;
cam->nmodes = ARRAY_SIZE(jlj_mode);
cam->bulk = 1;
cam->bulk_nurbs = 1;
cam->bulk_size = JEILINJ_MAX_TRANSFER;
return 0;
}
static void sd_stopN(struct gspca_dev *gspca_dev)
{
int i;
u8 *buf;
static u8 stop_commands[][2] = {
{0x71, 0x00},
{0x70, 0x09},
{0x71, 0x80},
{0x70, 0x05}
};
for (;;) {
/* get the image remaining blocks */
usb_bulk_msg(gspca_dev->dev,
gspca_dev->urb[0]->pipe,
gspca_dev->urb[0]->transfer_buffer,
JEILINJ_MAX_TRANSFER, NULL,
JEILINJ_DATA_TIMEOUT);
/* search for 0xff 0xd9 (EOF for JPEG) */
i = 0;
buf = gspca_dev->urb[0]->transfer_buffer;
while ((i < (JEILINJ_MAX_TRANSFER - 1)) &&
((buf[i] != 0xff) || (buf[i+1] != 0xd9)))
i++;
if (i != (JEILINJ_MAX_TRANSFER - 1))
/* last remaining block found */
break;
}
for (i = 0; i < ARRAY_SIZE(stop_commands); i++)
jlj_write2(gspca_dev, stop_commands[i]);
}
/* this function is called at probe and resume time */
static int sd_init(struct gspca_dev *gspca_dev)
{
return gspca_dev->usb_err;
}
/* Set up for getting frames. */
static int sd_start(struct gspca_dev *gspca_dev)
{
struct sd *dev = (struct sd *) gspca_dev;
/* create the JPEG header */
jpeg_define(dev->jpeg_hdr, gspca_dev->pixfmt.height,
gspca_dev->pixfmt.width,
0x21); /* JPEG 422 */
jpeg_set_qual(dev->jpeg_hdr, dev->quality);
PDEBUG(D_STREAM, "Start streaming at %dx%d",
gspca_dev->pixfmt.height, gspca_dev->pixfmt.width);
jlj_start(gspca_dev);
return gspca_dev->usb_err;
}
/* Table of supported USB devices */
static const struct usb_device_id device_table[] = {
{USB_DEVICE(0x0979, 0x0280), .driver_info = SAKAR_57379},
{USB_DEVICE(0x0979, 0x0270), .driver_info = SPORTSCAM_DV15},
{}
};
MODULE_DEVICE_TABLE(usb, device_table);
static int sd_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct gspca_dev *gspca_dev =
container_of(ctrl->handler, struct gspca_dev, ctrl_handler);
struct sd *sd = (struct sd *)gspca_dev;
gspca_dev->usb_err = 0;
if (!gspca_dev->streaming)
return 0;
switch (ctrl->id) {
case V4L2_CID_POWER_LINE_FREQUENCY:
setfreq(gspca_dev, ctrl->val);
break;
case V4L2_CID_RED_BALANCE:
setred(gspca_dev, ctrl->val);
break;
case V4L2_CID_GAIN:
setgreen(gspca_dev, ctrl->val);
break;
case V4L2_CID_BLUE_BALANCE:
setblue(gspca_dev, ctrl->val);
break;
case V4L2_CID_AUTOGAIN:
setautogain(gspca_dev, ctrl->val);
break;
case V4L2_CID_JPEG_COMPRESSION_QUALITY:
jpeg_set_qual(sd->jpeg_hdr, ctrl->val);
setcamquality(gspca_dev, ctrl->val);
break;
}
return gspca_dev->usb_err;
}
static const struct v4l2_ctrl_ops sd_ctrl_ops = {
.s_ctrl = sd_s_ctrl,
};
static int sd_init_controls(struct gspca_dev *gspca_dev)
{
struct sd *sd = (struct sd *)gspca_dev;
struct v4l2_ctrl_handler *hdl = &gspca_dev->ctrl_handler;
static const struct v4l2_ctrl_config custom_autogain = {
.ops = &sd_ctrl_ops,
.id = V4L2_CID_AUTOGAIN,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Automatic Gain (and Exposure)",
.max = 3,
.step = 1,
.def = 0,
};
gspca_dev->vdev.ctrl_handler = hdl;
v4l2_ctrl_handler_init(hdl, 6);
sd->freq = v4l2_ctrl_new_std_menu(hdl, &sd_ctrl_ops,
V4L2_CID_POWER_LINE_FREQUENCY,
V4L2_CID_POWER_LINE_FREQUENCY_60HZ, 1,
V4L2_CID_POWER_LINE_FREQUENCY_60HZ);
v4l2_ctrl_new_custom(hdl, &custom_autogain, NULL);
v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_RED_BALANCE, 0, 3, 1, 2);
v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_GAIN, 0, 3, 1, 2);
v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_BLUE_BALANCE, 0, 3, 1, 2);
sd->jpegqual = v4l2_ctrl_new_std(hdl, &sd_ctrl_ops,
V4L2_CID_JPEG_COMPRESSION_QUALITY,
QUALITY_MIN, QUALITY_MAX, 1, QUALITY_DEF);
if (hdl->error) {
pr_err("Could not initialize controls\n");
return hdl->error;
}
return 0;
}
static int sd_set_jcomp(struct gspca_dev *gspca_dev,
const struct v4l2_jpegcompression *jcomp)
{
struct sd *sd = (struct sd *) gspca_dev;
v4l2_ctrl_s_ctrl(sd->jpegqual, jcomp->quality);
return 0;
}
static int sd_get_jcomp(struct gspca_dev *gspca_dev,
struct v4l2_jpegcompression *jcomp)
{
struct sd *sd = (struct sd *) gspca_dev;
memset(jcomp, 0, sizeof *jcomp);
jcomp->quality = v4l2_ctrl_g_ctrl(sd->jpegqual);
jcomp->jpeg_markers = V4L2_JPEG_MARKER_DHT
| V4L2_JPEG_MARKER_DQT;
return 0;
}
/* sub-driver description */
static const struct sd_desc sd_desc_sakar_57379 = {
.name = MODULE_NAME,
.config = sd_config,
.init = sd_init,
.start = sd_start,
.stopN = sd_stopN,
.pkt_scan = sd_pkt_scan,
};
/* sub-driver description */
static const struct sd_desc sd_desc_sportscam_dv15 = {
.name = MODULE_NAME,
.config = sd_config,
.init = sd_init,
.init_controls = sd_init_controls,
.start = sd_start,
.stopN = sd_stopN,
.pkt_scan = sd_pkt_scan,
.get_jcomp = sd_get_jcomp,
.set_jcomp = sd_set_jcomp,
};
static const struct sd_desc *sd_desc[2] = {
&sd_desc_sakar_57379,
&sd_desc_sportscam_dv15
};
/* -- device connect -- */
static int sd_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
return gspca_dev_probe(intf, id,
sd_desc[id->driver_info],
sizeof(struct sd),
THIS_MODULE);
}
static struct usb_driver sd_driver = {
.name = MODULE_NAME,
.id_table = device_table,
.probe = sd_probe,
.disconnect = gspca_disconnect,
#ifdef CONFIG_PM
.suspend = gspca_suspend,
.resume = gspca_resume,
.reset_resume = gspca_resume,
#endif
};
module_usb_driver(sd_driver);
| gpl-2.0 |
am2012/android_kernel_motorola_msm8610 | drivers/power/bq28400_battery.c | 2159 | 25268 | /* Copyright (c) 2012-2013 The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
/*
* High Level description:
* http://www.ti.com/lit/ds/symlink/bq28400.pdf
* Thechnical Reference:
* http://www.ti.com/lit/ug/sluu431/sluu431.pdf
*/
#define pr_fmt(fmt) "%s: " fmt, __func__
#include <linux/i2c.h>
#include <linux/gpio.h>
#include <linux/errno.h>
#include <linux/delay.h>
#include <linux/module.h>
#include <linux/debugfs.h>
#include <linux/workqueue.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include <linux/power_supply.h>
#include <linux/bitops.h>
#include <linux/regulator/consumer.h>
#include <linux/printk.h>
#define BQ28400_NAME "bq28400"
#define BQ28400_REV "1.0"
/* SBS Commands (page 63) */
#define SBS_MANUFACTURER_ACCESS 0x00
#define SBS_BATTERY_MODE 0x03
#define SBS_TEMPERATURE 0x08
#define SBS_VOLTAGE 0x09
#define SBS_CURRENT 0x0A
#define SBS_AVG_CURRENT 0x0B
#define SBS_MAX_ERROR 0x0C
#define SBS_RSOC 0x0D /* Relative State Of Charge */
#define SBS_REMAIN_CAPACITY 0x0F
#define SBS_FULL_CAPACITY 0x10
#define SBS_CHG_CURRENT 0x14
#define SBS_CHG_VOLTAGE 0x15
#define SBS_BATTERY_STATUS 0x16
#define SBS_CYCLE_COUNT 0x17
#define SBS_DESIGN_CAPACITY 0x18
#define SBS_DESIGN_VOLTAGE 0x19
#define SBS_SPEC_INFO 0x1A
#define SBS_MANUFACTURE_DATE 0x1B
#define SBS_SERIAL_NUMBER 0x1C
#define SBS_MANUFACTURER_NAME 0x20
#define SBS_DEVICE_NAME 0x21
#define SBS_DEVICE_CHEMISTRY 0x22
#define SBS_MANUFACTURER_DATA 0x23
#define SBS_AUTHENTICATE 0x2F
#define SBS_CELL_VOLTAGE1 0x3E
#define SBS_CELL_VOLTAGE2 0x3F
/* Extended SBS Commands (page 71) */
#define SBS_FET_CONTROL 0x46
#define SBS_SAFETY_ALERT 0x50
#define SBS_SAFETY_STATUS 0x51
#define SBS_PE_ALERT 0x52
#define SBS_PE_STATUS 0x53
#define SBS_OPERATION_STATUS 0x54
#define SBS_CHARGING_STATUS 0x55
#define SBS_FET_STATUS 0x56
#define SBS_PACK_VOLTAGE 0x5A
#define SBS_TS0_TEMPERATURE 0x5E
#define SBS_FULL_ACCESS_KEY 0x61
#define SBS_PF_KEY 0x62
#define SBS_AUTH_KEY3 0x63
#define SBS_AUTH_KEY2 0x64
#define SBS_AUTH_KEY1 0x65
#define SBS_AUTH_KEY0 0x66
#define SBS_MANUFACTURER_INFO 0x70
#define SBS_SENSE_RESISTOR 0x71
#define SBS_TEMP_RANGE 0x72
/* SBS Sub-Commands (16 bits) */
/* SBS_MANUFACTURER_ACCESS CMD */
#define SUBCMD_DEVICE_TYPE 0x01
#define SUBCMD_FIRMWARE_VERSION 0x02
#define SUBCMD_HARDWARE_VERSION 0x03
#define SUBCMD_DF_CHECKSUM 0x04
#define SUBCMD_EDV 0x05
#define SUBCMD_CHEMISTRY_ID 0x08
/* SBS_CHARGING_STATUS */
#define CHG_STATUS_BATTERY_DEPLETED BIT(0)
#define CHG_STATUS_OVERCHARGE BIT(1)
#define CHG_STATUS_OVERCHARGE_CURRENT BIT(2)
#define CHG_STATUS_OVERCHARGE_VOLTAGE BIT(3)
#define CHG_STATUS_CELL_BALANCING BIT(6)
#define CHG_STATUS_HOT_TEMP_CHARGING BIT(8)
#define CHG_STATUS_STD1_TEMP_CHARGING BIT(9)
#define CHG_STATUS_STD2_TEMP_CHARGING BIT(10)
#define CHG_STATUS_LOW_TEMP_CHARGING BIT(11)
#define CHG_STATUS_PRECHARGING_EXIT BIT(13)
#define CHG_STATUS_SUSPENDED BIT(14)
#define CHG_STATUS_DISABLED BIT(15)
/* SBS_FET_STATUS */
#define FET_STATUS_DISCHARGE BIT(1)
#define FET_STATUS_CHARGE BIT(2)
#define FET_STATUS_PRECHARGE BIT(3)
/* SBS_BATTERY_STATUS */
#define BAT_STATUS_SBS_ERROR 0x0F
#define BAT_STATUS_EMPTY BIT(4)
#define BAT_STATUS_FULL BIT(5)
#define BAT_STATUS_DISCHARGING BIT(6)
#define BAT_STATUS_OVER_TEMPERATURE BIT(12)
#define BAT_STATUS_OVER_CHARGED BIT(15)
#define ZERO_DEGREE_CELSIUS_IN_TENTH_KELVIN (-2731)
#define BQ_TERMINATION_CURRENT_MA 200
#define BQ_MAX_STR_LEN 32
struct bq28400_device {
struct i2c_client *client;
struct delayed_work periodic_user_space_update_work;
struct dentry *dent;
struct power_supply batt_psy;
struct power_supply *dc_psy;
bool is_charging_enabled;
u32 temp_cold; /* in degree celsius */
u32 temp_hot; /* in degree celsius */
};
static struct bq28400_device *bq28400_dev;
static enum power_supply_property pm_power_props[] = {
POWER_SUPPLY_PROP_STATUS,
POWER_SUPPLY_PROP_CHARGE_TYPE,
POWER_SUPPLY_PROP_PRESENT,
POWER_SUPPLY_PROP_TECHNOLOGY,
POWER_SUPPLY_PROP_VOLTAGE_NOW,
POWER_SUPPLY_PROP_CAPACITY,
POWER_SUPPLY_PROP_CURRENT_NOW,
POWER_SUPPLY_PROP_CURRENT_AVG,
POWER_SUPPLY_PROP_TEMP,
POWER_SUPPLY_PROP_CHARGE_FULL,
POWER_SUPPLY_PROP_CHARGE_NOW,
POWER_SUPPLY_PROP_MODEL_NAME,
POWER_SUPPLY_PROP_MANUFACTURER,
};
struct debug_reg {
char *name;
u8 reg;
u16 subcmd;
};
static int fake_battery = -EINVAL;
module_param(fake_battery, int, 0644);
#define BQ28400_DEBUG_REG(x) {#x, SBS_##x, 0}
#define BQ28400_DEBUG_SUBREG(x, y) {#y, SBS_##x, SUBCMD_##y}
/* Note: Some register can be read only in Unsealed mode */
static struct debug_reg bq28400_debug_regs[] = {
BQ28400_DEBUG_REG(MANUFACTURER_ACCESS),
BQ28400_DEBUG_REG(BATTERY_MODE),
BQ28400_DEBUG_REG(TEMPERATURE),
BQ28400_DEBUG_REG(VOLTAGE),
BQ28400_DEBUG_REG(CURRENT),
BQ28400_DEBUG_REG(AVG_CURRENT),
BQ28400_DEBUG_REG(MAX_ERROR),
BQ28400_DEBUG_REG(RSOC),
BQ28400_DEBUG_REG(REMAIN_CAPACITY),
BQ28400_DEBUG_REG(FULL_CAPACITY),
BQ28400_DEBUG_REG(CHG_CURRENT),
BQ28400_DEBUG_REG(CHG_VOLTAGE),
BQ28400_DEBUG_REG(BATTERY_STATUS),
BQ28400_DEBUG_REG(CYCLE_COUNT),
BQ28400_DEBUG_REG(DESIGN_CAPACITY),
BQ28400_DEBUG_REG(DESIGN_VOLTAGE),
BQ28400_DEBUG_REG(SPEC_INFO),
BQ28400_DEBUG_REG(MANUFACTURE_DATE),
BQ28400_DEBUG_REG(SERIAL_NUMBER),
BQ28400_DEBUG_REG(MANUFACTURER_NAME),
BQ28400_DEBUG_REG(DEVICE_NAME),
BQ28400_DEBUG_REG(DEVICE_CHEMISTRY),
BQ28400_DEBUG_REG(MANUFACTURER_DATA),
BQ28400_DEBUG_REG(AUTHENTICATE),
BQ28400_DEBUG_REG(CELL_VOLTAGE1),
BQ28400_DEBUG_REG(CELL_VOLTAGE2),
BQ28400_DEBUG_REG(SAFETY_ALERT),
BQ28400_DEBUG_REG(SAFETY_STATUS),
BQ28400_DEBUG_REG(PE_ALERT),
BQ28400_DEBUG_REG(PE_STATUS),
BQ28400_DEBUG_REG(OPERATION_STATUS),
BQ28400_DEBUG_REG(CHARGING_STATUS),
BQ28400_DEBUG_REG(FET_STATUS),
BQ28400_DEBUG_REG(FULL_ACCESS_KEY),
BQ28400_DEBUG_REG(PF_KEY),
BQ28400_DEBUG_REG(MANUFACTURER_INFO),
BQ28400_DEBUG_REG(SENSE_RESISTOR),
BQ28400_DEBUG_REG(TEMP_RANGE),
BQ28400_DEBUG_SUBREG(MANUFACTURER_ACCESS, DEVICE_TYPE),
BQ28400_DEBUG_SUBREG(MANUFACTURER_ACCESS, FIRMWARE_VERSION),
BQ28400_DEBUG_SUBREG(MANUFACTURER_ACCESS, HARDWARE_VERSION),
BQ28400_DEBUG_SUBREG(MANUFACTURER_ACCESS, DF_CHECKSUM),
BQ28400_DEBUG_SUBREG(MANUFACTURER_ACCESS, EDV),
BQ28400_DEBUG_SUBREG(MANUFACTURER_ACCESS, CHEMISTRY_ID),
};
static int bq28400_read_reg(struct i2c_client *client, u8 reg)
{
int val;
val = i2c_smbus_read_word_data(client, reg);
if (val < 0)
pr_err("i2c read fail. reg = 0x%x.ret = %d.\n", reg, val);
else
pr_debug("reg = 0x%02X.val = 0x%04X.\n", reg , val);
return val;
}
static int bq28400_write_reg(struct i2c_client *client, u8 reg, u16 val)
{
int ret;
ret = i2c_smbus_write_word_data(client, reg, val);
if (ret < 0)
pr_err("i2c read fail. reg = 0x%x.val = 0x%x.ret = %d.\n",
reg, val, ret);
else
pr_debug("reg = 0x%02X.val = 0x%02X.\n", reg , val);
return ret;
}
static int bq28400_read_subcmd(struct i2c_client *client, u8 reg, u16 subcmd)
{
int ret;
u8 buf[4];
u16 val = 0;
buf[0] = reg;
buf[1] = subcmd & 0xFF;
buf[2] = (subcmd >> 8) & 0xFF;
/* Control sub-command */
ret = i2c_master_send(client, buf, 3);
if (ret < 0) {
pr_err("i2c tx fail. reg = 0x%x.ret = %d.\n", reg, ret);
return ret;
}
udelay(66);
/* Read Result of subcmd */
ret = i2c_master_send(client, buf, 1);
memset(buf, 0xAA, sizeof(buf));
ret = i2c_master_recv(client, buf, 2);
if (ret < 0) {
pr_err("i2c rx fail. reg = 0x%x.ret = %d.\n", reg, ret);
return ret;
}
val = (buf[1] << 8) + buf[0];
pr_debug("reg = 0x%02X.subcmd = 0x%x.val = 0x%04X.\n",
reg , subcmd, val);
return val;
}
static int bq28400_read_block(struct i2c_client *client, u8 reg,
u8 len, u8 *buf)
{
int ret;
u32 val;
ret = i2c_smbus_read_i2c_block_data(client, reg, len, buf);
val = buf[0] + (buf[1] << 8) + (buf[2] << 16) + (buf[3] << 24);
if (ret < 0)
pr_err("i2c read fail. reg = 0x%x.ret = %d.\n", reg, ret);
else
pr_debug("reg = 0x%02X.val = 0x%04X.\n", reg , val);
return val;
}
/*
* Read a string from a device.
* Returns string length on success or error on failure (negative value).
*/
static int bq28400_read_string(struct i2c_client *client, u8 reg, char *str,
u8 max_len)
{
int ret;
int len;
ret = bq28400_read_block(client, reg, max_len, str);
if (ret < 0)
return ret;
len = str[0]; /* Actual length */
if (len > max_len - 2) { /* reduce len byte and null */
pr_err("len = %d invalid.\n", len);
return -EINVAL;
}
memcpy(&str[0], &str[1], len); /* Move sting to the start */
str[len] = 0; /* put NULL after actual size */
pr_debug("len = %d.str = %s.\n", len, str);
return len;
}
#define BQ28400_INVALID_TEMPERATURE -999
/*
* Return the battery temperature in tenths of degree Celsius
* Or -99.9 C if something fails.
*/
static int bq28400_read_temperature(struct i2c_client *client)
{
int temp;
/* temperature resolution 0.1 Kelvin */
temp = bq28400_read_reg(client, SBS_TEMPERATURE);
if (temp < 0)
return BQ28400_INVALID_TEMPERATURE;
temp = temp + ZERO_DEGREE_CELSIUS_IN_TENTH_KELVIN;
pr_debug("temp = %d C\n", temp/10);
return temp;
}
/*
* Return the battery Voltage in milivolts 0..20 V
* Or < 0 if something fails.
*/
static int bq28400_read_voltage(struct i2c_client *client)
{
int mvolt = 0;
mvolt = bq28400_read_reg(client, SBS_VOLTAGE);
if (mvolt < 0)
return mvolt;
pr_debug("volt = %d mV.\n", mvolt);
return mvolt;
}
/*
* Return the battery Current in miliamps
* Or 0 if something fails.
* Positive current indicates charging
* Negative current indicates discharging.
* Current-now is calculated every second.
*/
static int bq28400_read_current(struct i2c_client *client)
{
s16 current_ma = 0;
current_ma = bq28400_read_reg(client, SBS_CURRENT);
pr_debug("current = %d mA.\n", current_ma);
return current_ma;
}
/*
* Return the Average battery Current in miliamps
* Or 0 if something fails.
* Positive current indicates charging
* Negative current indicates discharging.
* Average Current is the rolling 1 minute average current.
*/
static int bq28400_read_avg_current(struct i2c_client *client)
{
s16 current_ma = 0;
current_ma = bq28400_read_reg(client, SBS_AVG_CURRENT);
pr_debug("avg_current=%d mA.\n", current_ma);
return current_ma;
}
/*
* Return the battery Relative-State-Of-Charge 0..100 %
* Or negative value if something fails.
*/
static int bq28400_read_rsoc(struct i2c_client *client)
{
int percentage = 0;
if (fake_battery != -EINVAL) {
pr_debug("Reporting Fake SOC = %d\n", fake_battery);
return fake_battery;
}
/* This register is only 1 byte */
percentage = i2c_smbus_read_byte_data(client, SBS_RSOC);
if (percentage < 0) {
pr_err("I2C failure when reading rsoc.\n");
return percentage;
}
pr_debug("percentage = %d.\n", percentage);
return percentage;
}
/*
* Return the battery Capacity in mAh.
* Or 0 if something fails.
*/
static int bq28400_read_full_capacity(struct i2c_client *client)
{
int capacity = 0;
capacity = bq28400_read_reg(client, SBS_FULL_CAPACITY);
if (capacity < 0)
return 0;
pr_debug("full-capacity = %d mAh.\n", capacity);
return capacity;
}
/*
* Return the battery Capacity in mAh.
* Or 0 if something fails.
*/
static int bq28400_read_remain_capacity(struct i2c_client *client)
{
int capacity = 0;
capacity = bq28400_read_reg(client, SBS_REMAIN_CAPACITY);
if (capacity < 0)
return 0;
pr_debug("remain-capacity = %d mAh.\n", capacity);
return capacity;
}
static int bq28400_enable_charging(struct bq28400_device *bq28400_dev,
bool enable)
{
int ret;
static bool is_charging_enabled;
if (bq28400_dev->dc_psy == NULL) {
bq28400_dev->dc_psy = power_supply_get_by_name("dc");
if (bq28400_dev->dc_psy == NULL) {
pr_err("fail to get dc-psy.\n");
return -ENODEV;
}
}
if (is_charging_enabled == enable) {
pr_debug("Charging enable already = %d.\n", enable);
return 0;
}
ret = power_supply_set_online(bq28400_dev->dc_psy, enable);
if (ret < 0) {
pr_err("fail to set dc-psy online to %d.\n", enable);
return ret;
}
is_charging_enabled = enable;
pr_debug("Charging enable = %d.\n", enable);
return 0;
}
static int bq28400_get_prop_status(struct i2c_client *client)
{
int status = POWER_SUPPLY_STATUS_UNKNOWN;
int rsoc;
s16 current_ma = 0;
u16 battery_status;
int temperature;
struct bq28400_device *dev = i2c_get_clientdata(client);
battery_status = bq28400_read_reg(client, SBS_BATTERY_STATUS);
rsoc = bq28400_read_rsoc(client);
current_ma = bq28400_read_current(client);
temperature = bq28400_read_temperature(client);
temperature = temperature / 10; /* in degree celsius */
if (battery_status & BAT_STATUS_EMPTY)
pr_debug("Battery report Empty.\n");
/* Battery may report FULL before rsoc is 100%
* for protection and cell-balancing.
* The FULL report may remain when rsoc drops from 100%.
* If battery is full but DC-Jack is removed then report discahrging.
*/
if (battery_status & BAT_STATUS_FULL) {
pr_debug("Battery report Full.\n");
bq28400_enable_charging(bq28400_dev, false);
if (current_ma < 0)
return POWER_SUPPLY_STATUS_DISCHARGING;
return POWER_SUPPLY_STATUS_FULL;
}
if (rsoc == 100) {
bq28400_enable_charging(bq28400_dev, false);
pr_debug("Full.\n");
return POWER_SUPPLY_STATUS_FULL;
}
/* Enable charging when battery is not full and temperature is ok */
if ((temperature > dev->temp_cold) && (temperature < dev->temp_hot))
bq28400_enable_charging(bq28400_dev, true);
else
bq28400_enable_charging(bq28400_dev, false);
/*
* Positive current indicates charging
* Negative current indicates discharging.
* Charging is stopped at termination-current.
*/
if (current_ma < 0) {
pr_debug("Discharging.\n");
status = POWER_SUPPLY_STATUS_DISCHARGING;
} else if (current_ma > BQ_TERMINATION_CURRENT_MA) {
pr_debug("Charging.\n");
status = POWER_SUPPLY_STATUS_CHARGING;
} else {
pr_debug("Not Charging.\n");
status = POWER_SUPPLY_STATUS_NOT_CHARGING;
}
return status;
}
static int bq28400_get_prop_charge_type(struct i2c_client *client)
{
u16 battery_status;
u16 chg_status;
u16 fet_status;
battery_status = bq28400_read_reg(client, SBS_BATTERY_STATUS);
chg_status = bq28400_read_reg(client, SBS_CHARGING_STATUS);
fet_status = bq28400_read_reg(client, SBS_FET_STATUS);
if (battery_status & BAT_STATUS_DISCHARGING) {
pr_debug("Discharging.\n");
return POWER_SUPPLY_CHARGE_TYPE_NONE;
}
if (fet_status & FET_STATUS_PRECHARGE) {
pr_debug("Pre-Charging.\n");
return POWER_SUPPLY_CHARGE_TYPE_TRICKLE;
}
if (chg_status & CHG_STATUS_HOT_TEMP_CHARGING) {
pr_debug("Hot-Temp-Charging.\n");
return POWER_SUPPLY_CHARGE_TYPE_FAST;
}
if (chg_status & CHG_STATUS_LOW_TEMP_CHARGING) {
pr_debug("Low-Temp-Charging.\n");
return POWER_SUPPLY_CHARGE_TYPE_FAST;
}
if (chg_status & CHG_STATUS_STD1_TEMP_CHARGING) {
pr_debug("STD1-Temp-Charging.\n");
return POWER_SUPPLY_CHARGE_TYPE_FAST;
}
if (chg_status & CHG_STATUS_STD2_TEMP_CHARGING) {
pr_debug("STD2-Temp-Charging.\n");
return POWER_SUPPLY_CHARGE_TYPE_FAST;
}
if (chg_status & CHG_STATUS_BATTERY_DEPLETED)
pr_debug("battery_depleted.\n");
if (chg_status & CHG_STATUS_CELL_BALANCING)
pr_debug("cell_balancing.\n");
if (chg_status & CHG_STATUS_OVERCHARGE) {
pr_err("overcharge fault.\n");
return POWER_SUPPLY_CHARGE_TYPE_NONE;
}
if (chg_status & CHG_STATUS_SUSPENDED) {
pr_info("Suspended.\n");
return POWER_SUPPLY_CHARGE_TYPE_NONE;
}
if (chg_status & CHG_STATUS_DISABLED) {
pr_info("Disabled.\n");
return POWER_SUPPLY_CHARGE_TYPE_NONE;
}
return POWER_SUPPLY_CHARGE_TYPE_UNKNOWN;
}
static bool bq28400_get_prop_present(struct i2c_client *client)
{
int val;
val = bq28400_read_reg(client, SBS_BATTERY_STATUS);
/* If the bq28400 is inside the battery pack
* then when battery is removed the i2c transfer will fail.
*/
if (val < 0)
return false;
/* TODO - support when bq28400 is not embedded in battery pack */
return true;
}
/*
* User sapce read the battery info.
* Get data online via I2C from the battery gauge.
*/
static int bq28400_get_property(struct power_supply *psy,
enum power_supply_property psp,
union power_supply_propval *val)
{
int ret = 0;
struct bq28400_device *dev = container_of(psy,
struct bq28400_device,
batt_psy);
struct i2c_client *client = dev->client;
static char str[BQ_MAX_STR_LEN];
switch (psp) {
case POWER_SUPPLY_PROP_STATUS:
val->intval = bq28400_get_prop_status(client);
break;
case POWER_SUPPLY_PROP_CHARGE_TYPE:
val->intval = bq28400_get_prop_charge_type(client);
break;
case POWER_SUPPLY_PROP_PRESENT:
val->intval = bq28400_get_prop_present(client);
break;
case POWER_SUPPLY_PROP_VOLTAGE_NOW:
val->intval = bq28400_read_voltage(client);
val->intval *= 1000; /* mV to uV */
break;
case POWER_SUPPLY_PROP_CAPACITY:
val->intval = bq28400_read_rsoc(client);
if (val->intval < 0)
ret = -EINVAL;
break;
case POWER_SUPPLY_PROP_CURRENT_NOW:
/* Positive current indicates drawing */
val->intval = -bq28400_read_current(client);
val->intval *= 1000; /* mA to uA */
break;
case POWER_SUPPLY_PROP_CURRENT_AVG:
/* Positive current indicates drawing */
val->intval = -bq28400_read_avg_current(client);
val->intval *= 1000; /* mA to uA */
break;
case POWER_SUPPLY_PROP_TEMP:
val->intval = bq28400_read_temperature(client);
break;
case POWER_SUPPLY_PROP_CHARGE_FULL:
val->intval = bq28400_read_full_capacity(client);
break;
case POWER_SUPPLY_PROP_CHARGE_NOW:
val->intval = bq28400_read_remain_capacity(client);
break;
case POWER_SUPPLY_PROP_TECHNOLOGY:
val->intval = POWER_SUPPLY_TECHNOLOGY_LION;
break;
case POWER_SUPPLY_PROP_MODEL_NAME:
bq28400_read_string(client, SBS_DEVICE_NAME, str, 20);
val->strval = str;
break;
case POWER_SUPPLY_PROP_MANUFACTURER:
bq28400_read_string(client, SBS_MANUFACTURER_NAME, str, 20);
val->strval = str;
break;
default:
pr_err(" psp %d Not supoprted.\n", psp);
ret = -EINVAL;
break;
}
return ret;
}
static int bq28400_set_reg(void *data, u64 val)
{
struct debug_reg *dbg = data;
u8 reg = dbg->reg;
int ret;
struct i2c_client *client = bq28400_dev->client;
ret = bq28400_write_reg(client, reg, val);
return ret;
}
static int bq28400_get_reg(void *data, u64 *val)
{
struct debug_reg *dbg = data;
u8 reg = dbg->reg;
u16 subcmd = dbg->subcmd;
int ret;
struct i2c_client *client = bq28400_dev->client;
if (subcmd)
ret = bq28400_read_subcmd(client, reg, subcmd);
else
ret = bq28400_read_reg(client, reg);
if (ret < 0)
return ret;
*val = ret;
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(reg_fops, bq28400_get_reg, bq28400_set_reg,
"0x%04llx\n");
static int bq28400_create_debugfs_entries(struct bq28400_device *bq28400_dev)
{
int i;
bq28400_dev->dent = debugfs_create_dir(BQ28400_NAME, NULL);
if (IS_ERR(bq28400_dev->dent)) {
pr_err("bq28400 driver couldn't create debugfs dir\n");
return -EFAULT;
}
for (i = 0 ; i < ARRAY_SIZE(bq28400_debug_regs) ; i++) {
char *name = bq28400_debug_regs[i].name;
struct dentry *file;
void *data = &bq28400_debug_regs[i];
file = debugfs_create_file(name, 0644, bq28400_dev->dent,
data, ®_fops);
if (IS_ERR(file)) {
pr_err("debugfs_create_file %s failed.\n", name);
return -EFAULT;
}
}
return 0;
}
static int bq28400_set_property(struct power_supply *psy,
enum power_supply_property psp,
const union power_supply_propval *val)
{
pr_debug("psp = %d.val = %d.\n", psp, val->intval);
return -EINVAL;
}
static void bq28400_external_power_changed(struct power_supply *psy)
{
pr_debug("Notify power_supply_changed.\n");
/* The battery gauge monitors the current and voltage every 1 second.
* Therefore a delay from the time that the charger start/stop charging
* until the battery gauge detects it.
*/
msleep(1000);
/* Update LEDs and notify uevents */
power_supply_changed(&bq28400_dev->batt_psy);
}
static int __devinit bq28400_register_psy(struct bq28400_device *bq28400_dev)
{
int ret;
bq28400_dev->batt_psy.name = "battery";
bq28400_dev->batt_psy.type = POWER_SUPPLY_TYPE_BATTERY;
bq28400_dev->batt_psy.num_supplicants = 0;
bq28400_dev->batt_psy.properties = pm_power_props;
bq28400_dev->batt_psy.num_properties = ARRAY_SIZE(pm_power_props);
bq28400_dev->batt_psy.get_property = bq28400_get_property;
bq28400_dev->batt_psy.set_property = bq28400_set_property;
bq28400_dev->batt_psy.external_power_changed =
bq28400_external_power_changed;
ret = power_supply_register(&bq28400_dev->client->dev,
&bq28400_dev->batt_psy);
if (ret) {
pr_err("failed to register power_supply. ret=%d.\n", ret);
return ret;
}
return 0;
}
/**
* Update userspace every 1 minute.
* Normally it takes more than 120 minutes (two hours) to
* charge/discahrge the battery,
* so updating every 1 minute should be enough for 1% change
* detection.
* Any immidiate change detected by the DC charger is notified
* by the bq28400_external_power_changed callback, which notify
* the user space.
*/
static void bq28400_periodic_user_space_update_worker(struct work_struct *work)
{
u32 delay_msec = 60*1000;
pr_debug("Notify user space.\n");
/* Notify user space via kobject_uevent change notification */
power_supply_changed(&bq28400_dev->batt_psy);
schedule_delayed_work(&bq28400_dev->periodic_user_space_update_work,
round_jiffies_relative(msecs_to_jiffies
(delay_msec)));
}
static int __devinit bq28400_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
int ret = 0;
struct device_node *dev_node = client->dev.of_node;
if (dev_node == NULL) {
pr_err("Device Tree node doesn't exist.\n");
return -ENODEV;
}
if (!i2c_check_functionality(client->adapter,
I2C_FUNC_SMBUS_BYTE_DATA)) {
pr_err(" i2c func fail.\n");
return -EIO;
}
if (bq28400_read_reg(client, SBS_BATTERY_STATUS) < 0) {
pr_err("Device doesn't exist.\n");
return -ENODEV;
}
bq28400_dev = kzalloc(sizeof(*bq28400_dev), GFP_KERNEL);
if (!bq28400_dev) {
pr_err(" alloc fail.\n");
return -ENOMEM;
}
/* Note: Lithium-ion battery normal temperature range 0..40 C */
ret = of_property_read_u32(dev_node, "ti,temp-cold",
&(bq28400_dev->temp_cold));
if (ret) {
pr_err("Unable to read cold temperature. ret=%d.\n", ret);
goto err_dev_node;
}
pr_debug("cold temperature limit = %d C.\n", bq28400_dev->temp_cold);
ret = of_property_read_u32(dev_node, "ti,temp-hot",
&(bq28400_dev->temp_hot));
if (ret) {
pr_err("Unable to read hot temperature. ret=%d.\n", ret);
goto err_dev_node;
}
pr_debug("hot temperature limit = %d C.\n", bq28400_dev->temp_hot);
bq28400_dev->client = client;
i2c_set_clientdata(client, bq28400_dev);
ret = bq28400_register_psy(bq28400_dev);
if (ret) {
pr_err(" bq28400_register_psy fail.\n");
goto err_register_psy;
}
ret = bq28400_create_debugfs_entries(bq28400_dev);
if (ret) {
pr_err(" bq28400_create_debugfs_entries fail.\n");
goto err_debugfs;
}
INIT_DELAYED_WORK(&bq28400_dev->periodic_user_space_update_work,
bq28400_periodic_user_space_update_worker);
schedule_delayed_work(&bq28400_dev->periodic_user_space_update_work,
msecs_to_jiffies(1000));
pr_debug("Device is ready.\n");
return 0;
err_debugfs:
if (bq28400_dev->dent)
debugfs_remove_recursive(bq28400_dev->dent);
power_supply_unregister(&bq28400_dev->batt_psy);
err_register_psy:
err_dev_node:
kfree(bq28400_dev);
bq28400_dev = NULL;
pr_info("FAIL.\n");
return ret;
}
static int __devexit bq28400_remove(struct i2c_client *client)
{
struct bq28400_device *bq28400_dev = i2c_get_clientdata(client);
power_supply_unregister(&bq28400_dev->batt_psy);
if (bq28400_dev->dent)
debugfs_remove_recursive(bq28400_dev->dent);
kfree(bq28400_dev);
bq28400_dev = NULL;
return 0;
}
static const struct of_device_id bq28400_match[] = {
{ .compatible = "ti,bq28400-battery" },
{ .compatible = "ti,bq30z55-battery" },
{ },
};
static const struct i2c_device_id bq28400_id[] = {
{BQ28400_NAME, 0},
{},
};
MODULE_DEVICE_TABLE(i2c, bq28400_id);
static struct i2c_driver bq28400_driver = {
.driver = {
.name = BQ28400_NAME,
.owner = THIS_MODULE,
.of_match_table = of_match_ptr(bq28400_match),
},
.probe = bq28400_probe,
.remove = __devexit_p(bq28400_remove),
.id_table = bq28400_id,
};
static int __init bq28400_init(void)
{
pr_info(" bq28400 driver rev %s.\n", BQ28400_REV);
return i2c_add_driver(&bq28400_driver);
}
module_init(bq28400_init);
static void __exit bq28400_exit(void)
{
return i2c_del_driver(&bq28400_driver);
}
module_exit(bq28400_exit);
MODULE_DESCRIPTION("Driver for BQ28400 charger chip");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("i2c:" BQ28400_NAME);
| gpl-2.0 |
AppliedMicro/ENGLinuxLatest | drivers/usb/misc/emi62.c | 2159 | 8013 | /*
* Emagic EMI 2|6 usb audio interface firmware loader.
* Copyright (C) 2002
* Tapio Laxström (tapio.laxstrom@iptime.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, version 2.
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/usb.h>
#include <linux/delay.h>
#include <linux/firmware.h>
#include <linux/ihex.h>
/* include firmware (variables)*/
/* FIXME: This is quick and dirty solution! */
#define SPDIF /* if you want SPDIF comment next line */
//#undef SPDIF /* if you want MIDI uncomment this line */
#ifdef SPDIF
#define FIRMWARE_FW "emi62/spdif.fw"
#else
#define FIRMWARE_FW "emi62/midi.fw"
#endif
#define EMI62_VENDOR_ID 0x086a /* Emagic Soft-und Hardware GmBH */
#define EMI62_PRODUCT_ID 0x0110 /* EMI 6|2m without firmware */
#define ANCHOR_LOAD_INTERNAL 0xA0 /* Vendor specific request code for Anchor Upload/Download (This one is implemented in the core) */
#define ANCHOR_LOAD_EXTERNAL 0xA3 /* This command is not implemented in the core. Requires firmware */
#define ANCHOR_LOAD_FPGA 0xA5 /* This command is not implemented in the core. Requires firmware. Emagic extension */
#define MAX_INTERNAL_ADDRESS 0x1B3F /* This is the highest internal RAM address for the AN2131Q */
#define CPUCS_REG 0x7F92 /* EZ-USB Control and Status Register. Bit 0 controls 8051 reset */
#define INTERNAL_RAM(address) (address <= MAX_INTERNAL_ADDRESS)
static int emi62_writememory(struct usb_device *dev, int address,
const unsigned char *data, int length,
__u8 bRequest);
static int emi62_set_reset(struct usb_device *dev, unsigned char reset_bit);
static int emi62_load_firmware (struct usb_device *dev);
static int emi62_probe(struct usb_interface *intf, const struct usb_device_id *id);
static void emi62_disconnect(struct usb_interface *intf);
/* thanks to drivers/usb/serial/keyspan_pda.c code */
static int emi62_writememory(struct usb_device *dev, int address,
const unsigned char *data, int length,
__u8 request)
{
int result;
unsigned char *buffer = kmemdup(data, length, GFP_KERNEL);
if (!buffer) {
dev_err(&dev->dev, "kmalloc(%d) failed.\n", length);
return -ENOMEM;
}
/* Note: usb_control_msg returns negative value on error or length of the
* data that was written! */
result = usb_control_msg (dev, usb_sndctrlpipe(dev, 0), request, 0x40, address, 0, buffer, length, 300);
kfree (buffer);
return result;
}
/* thanks to drivers/usb/serial/keyspan_pda.c code */
static int emi62_set_reset (struct usb_device *dev, unsigned char reset_bit)
{
int response;
dev_info(&dev->dev, "%s - %d\n", __func__, reset_bit);
response = emi62_writememory (dev, CPUCS_REG, &reset_bit, 1, 0xa0);
if (response < 0)
dev_err(&dev->dev, "set_reset (%d) failed\n", reset_bit);
return response;
}
#define FW_LOAD_SIZE 1023
static int emi62_load_firmware (struct usb_device *dev)
{
const struct firmware *loader_fw = NULL;
const struct firmware *bitstream_fw = NULL;
const struct firmware *firmware_fw = NULL;
const struct ihex_binrec *rec;
int err = -ENOMEM;
int i;
__u32 addr; /* Address to write */
__u8 *buf;
dev_dbg(&dev->dev, "load_firmware\n");
buf = kmalloc(FW_LOAD_SIZE, GFP_KERNEL);
if (!buf)
goto wraperr;
err = request_ihex_firmware(&loader_fw, "emi62/loader.fw", &dev->dev);
if (err)
goto nofw;
err = request_ihex_firmware(&bitstream_fw, "emi62/bitstream.fw",
&dev->dev);
if (err)
goto nofw;
err = request_ihex_firmware(&firmware_fw, FIRMWARE_FW, &dev->dev);
if (err) {
nofw:
goto wraperr;
}
/* Assert reset (stop the CPU in the EMI) */
err = emi62_set_reset(dev,1);
if (err < 0)
goto wraperr;
rec = (const struct ihex_binrec *)loader_fw->data;
/* 1. We need to put the loader for the FPGA into the EZ-USB */
while (rec) {
err = emi62_writememory(dev, be32_to_cpu(rec->addr),
rec->data, be16_to_cpu(rec->len),
ANCHOR_LOAD_INTERNAL);
if (err < 0)
goto wraperr;
rec = ihex_next_binrec(rec);
}
/* De-assert reset (let the CPU run) */
err = emi62_set_reset(dev,0);
if (err < 0)
goto wraperr;
msleep(250); /* let device settle */
/* 2. We upload the FPGA firmware into the EMI
* Note: collect up to 1023 (yes!) bytes and send them with
* a single request. This is _much_ faster! */
rec = (const struct ihex_binrec *)bitstream_fw->data;
do {
i = 0;
addr = be32_to_cpu(rec->addr);
/* intel hex records are terminated with type 0 element */
while (rec && (i + be16_to_cpu(rec->len) < FW_LOAD_SIZE)) {
memcpy(buf + i, rec->data, be16_to_cpu(rec->len));
i += be16_to_cpu(rec->len);
rec = ihex_next_binrec(rec);
}
err = emi62_writememory(dev, addr, buf, i, ANCHOR_LOAD_FPGA);
if (err < 0)
goto wraperr;
} while (rec);
/* Assert reset (stop the CPU in the EMI) */
err = emi62_set_reset(dev,1);
if (err < 0)
goto wraperr;
/* 3. We need to put the loader for the firmware into the EZ-USB (again...) */
for (rec = (const struct ihex_binrec *)loader_fw->data;
rec; rec = ihex_next_binrec(rec)) {
err = emi62_writememory(dev, be32_to_cpu(rec->addr),
rec->data, be16_to_cpu(rec->len),
ANCHOR_LOAD_INTERNAL);
if (err < 0)
goto wraperr;
}
/* De-assert reset (let the CPU run) */
err = emi62_set_reset(dev,0);
if (err < 0)
goto wraperr;
msleep(250); /* let device settle */
/* 4. We put the part of the firmware that lies in the external RAM into the EZ-USB */
for (rec = (const struct ihex_binrec *)firmware_fw->data;
rec; rec = ihex_next_binrec(rec)) {
if (!INTERNAL_RAM(be32_to_cpu(rec->addr))) {
err = emi62_writememory(dev, be32_to_cpu(rec->addr),
rec->data, be16_to_cpu(rec->len),
ANCHOR_LOAD_EXTERNAL);
if (err < 0)
goto wraperr;
}
}
/* Assert reset (stop the CPU in the EMI) */
err = emi62_set_reset(dev,1);
if (err < 0)
goto wraperr;
for (rec = (const struct ihex_binrec *)firmware_fw->data;
rec; rec = ihex_next_binrec(rec)) {
if (INTERNAL_RAM(be32_to_cpu(rec->addr))) {
err = emi62_writememory(dev, be32_to_cpu(rec->addr),
rec->data, be16_to_cpu(rec->len),
ANCHOR_LOAD_EXTERNAL);
if (err < 0)
goto wraperr;
}
}
/* De-assert reset (let the CPU run) */
err = emi62_set_reset(dev,0);
if (err < 0)
goto wraperr;
msleep(250); /* let device settle */
release_firmware(loader_fw);
release_firmware(bitstream_fw);
release_firmware(firmware_fw);
kfree(buf);
/* return 1 to fail the driver inialization
* and give real driver change to load */
return 1;
wraperr:
if (err < 0)
dev_err(&dev->dev,"%s - error loading firmware: error = %d\n",
__func__, err);
release_firmware(loader_fw);
release_firmware(bitstream_fw);
release_firmware(firmware_fw);
kfree(buf);
dev_err(&dev->dev, "Error\n");
return err;
}
static const struct usb_device_id id_table[] = {
{ USB_DEVICE(EMI62_VENDOR_ID, EMI62_PRODUCT_ID) },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE (usb, id_table);
static int emi62_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
struct usb_device *dev = interface_to_usbdev(intf);
dev_dbg(&intf->dev, "emi62_probe\n");
dev_info(&intf->dev, "%s start\n", __func__);
emi62_load_firmware(dev);
/* do not return the driver context, let real audio driver do that */
return -EIO;
}
static void emi62_disconnect(struct usb_interface *intf)
{
}
static struct usb_driver emi62_driver = {
.name = "emi62 - firmware loader",
.probe = emi62_probe,
.disconnect = emi62_disconnect,
.id_table = id_table,
};
module_usb_driver(emi62_driver);
MODULE_AUTHOR("Tapio Laxström");
MODULE_DESCRIPTION("Emagic EMI 6|2m firmware loader.");
MODULE_LICENSE("GPL");
MODULE_FIRMWARE("emi62/loader.fw");
MODULE_FIRMWARE("emi62/bitstream.fw");
MODULE_FIRMWARE(FIRMWARE_FW);
/* vi:ai:syntax=c:sw=8:ts=8:tw=80
*/
| gpl-2.0 |
weera00/linux-sunxi | drivers/staging/comedi/drivers/s626.c | 2159 | 108784 | /*
comedi/drivers/s626.c
Sensoray s626 Comedi driver
COMEDI - Linux Control and Measurement Device Interface
Copyright (C) 2000 David A. Schleef <ds@schleef.org>
Based on Sensoray Model 626 Linux driver Version 0.2
Copyright (C) 2002-2004 Sensoray Co., Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
Driver: s626
Description: Sensoray 626 driver
Devices: [Sensoray] 626 (s626)
Authors: Gianluca Palli <gpalli@deis.unibo.it>,
Updated: Fri, 15 Feb 2008 10:28:42 +0000
Status: experimental
Configuration options:
[0] - PCI bus of device (optional)
[1] - PCI slot of device (optional)
If bus/slot is not specified, the first supported
PCI device found will be used.
INSN_CONFIG instructions:
analog input:
none
analog output:
none
digital channel:
s626 has 3 dio subdevices (2,3 and 4) each with 16 i/o channels
supported configuration options:
INSN_CONFIG_DIO_QUERY
COMEDI_INPUT
COMEDI_OUTPUT
encoder:
Every channel must be configured before reading.
Example code
insn.insn=INSN_CONFIG; //configuration instruction
insn.n=1; //number of operation (must be 1)
insn.data=&initialvalue; //initial value loaded into encoder
//during configuration
insn.subdev=5; //encoder subdevice
insn.chanspec=CR_PACK(encoder_channel,0,AREF_OTHER); //encoder_channel
//to configure
comedi_do_insn(cf,&insn); //executing configuration
*/
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include "../comedidev.h"
#include "comedi_pci.h"
#include "comedi_fc.h"
#include "s626.h"
MODULE_AUTHOR("Gianluca Palli <gpalli@deis.unibo.it>");
MODULE_DESCRIPTION("Sensoray 626 Comedi driver module");
MODULE_LICENSE("GPL");
struct s626_board {
const char *name;
int ai_chans;
int ai_bits;
int ao_chans;
int ao_bits;
int dio_chans;
int dio_banks;
int enc_chans;
};
static const struct s626_board s626_boards[] = {
{
.name = "s626",
.ai_chans = S626_ADC_CHANNELS,
.ai_bits = 14,
.ao_chans = S626_DAC_CHANNELS,
.ao_bits = 13,
.dio_chans = S626_DIO_CHANNELS,
.dio_banks = S626_DIO_BANKS,
.enc_chans = S626_ENCODER_CHANNELS,
}
};
#define thisboard ((const struct s626_board *)dev->board_ptr)
#define PCI_VENDOR_ID_S626 0x1131
#define PCI_DEVICE_ID_S626 0x7146
/*
* For devices with vendor:device id == 0x1131:0x7146 you must specify
* also subvendor:subdevice ids, because otherwise it will conflict with
* Philips SAA7146 media/dvb based cards.
*/
static DEFINE_PCI_DEVICE_TABLE(s626_pci_table) = {
{PCI_VENDOR_ID_S626, PCI_DEVICE_ID_S626, 0x6000, 0x0272, 0, 0, 0},
{0}
};
MODULE_DEVICE_TABLE(pci, s626_pci_table);
static int s626_attach(struct comedi_device *dev, struct comedi_devconfig *it);
static int s626_detach(struct comedi_device *dev);
static struct comedi_driver driver_s626 = {
.driver_name = "s626",
.module = THIS_MODULE,
.attach = s626_attach,
.detach = s626_detach,
};
struct s626_private {
struct pci_dev *pdev;
void *base_addr;
int got_regions;
short allocatedBuf;
uint8_t ai_cmd_running; /* ai_cmd is running */
uint8_t ai_continous; /* continous acquisition */
int ai_sample_count; /* number of samples to acquire */
unsigned int ai_sample_timer;
/* time between samples in units of the timer */
int ai_convert_count; /* conversion counter */
unsigned int ai_convert_timer;
/* time between conversion in units of the timer */
uint16_t CounterIntEnabs;
/* Counter interrupt enable mask for MISC2 register. */
uint8_t AdcItems; /* Number of items in ADC poll list. */
struct bufferDMA RPSBuf; /* DMA buffer used to hold ADC (RPS1) program. */
struct bufferDMA ANABuf;
/* DMA buffer used to receive ADC data and hold DAC data. */
uint32_t *pDacWBuf;
/* Pointer to logical adrs of DMA buffer used to hold DAC data. */
uint16_t Dacpol; /* Image of DAC polarity register. */
uint8_t TrimSetpoint[12]; /* Images of TrimDAC setpoints */
uint16_t ChargeEnabled; /* Image of MISC2 Battery */
/* Charge Enabled (0 or WRMISC2_CHARGE_ENABLE). */
uint16_t WDInterval; /* Image of MISC2 watchdog interval control bits. */
uint32_t I2CAdrs;
/* I2C device address for onboard EEPROM (board rev dependent). */
/* short I2Cards; */
unsigned int ao_readback[S626_DAC_CHANNELS];
};
struct dio_private {
uint16_t RDDIn;
uint16_t WRDOut;
uint16_t RDEdgSel;
uint16_t WREdgSel;
uint16_t RDCapSel;
uint16_t WRCapSel;
uint16_t RDCapFlg;
uint16_t RDIntSel;
uint16_t WRIntSel;
};
static struct dio_private dio_private_A = {
.RDDIn = LP_RDDINA,
.WRDOut = LP_WRDOUTA,
.RDEdgSel = LP_RDEDGSELA,
.WREdgSel = LP_WREDGSELA,
.RDCapSel = LP_RDCAPSELA,
.WRCapSel = LP_WRCAPSELA,
.RDCapFlg = LP_RDCAPFLGA,
.RDIntSel = LP_RDINTSELA,
.WRIntSel = LP_WRINTSELA,
};
static struct dio_private dio_private_B = {
.RDDIn = LP_RDDINB,
.WRDOut = LP_WRDOUTB,
.RDEdgSel = LP_RDEDGSELB,
.WREdgSel = LP_WREDGSELB,
.RDCapSel = LP_RDCAPSELB,
.WRCapSel = LP_WRCAPSELB,
.RDCapFlg = LP_RDCAPFLGB,
.RDIntSel = LP_RDINTSELB,
.WRIntSel = LP_WRINTSELB,
};
static struct dio_private dio_private_C = {
.RDDIn = LP_RDDINC,
.WRDOut = LP_WRDOUTC,
.RDEdgSel = LP_RDEDGSELC,
.WREdgSel = LP_WREDGSELC,
.RDCapSel = LP_RDCAPSELC,
.WRCapSel = LP_WRCAPSELC,
.RDCapFlg = LP_RDCAPFLGC,
.RDIntSel = LP_RDINTSELC,
.WRIntSel = LP_WRINTSELC,
};
/* to group dio devices (48 bits mask and data are not allowed ???)
static struct dio_private *dio_private_word[]={
&dio_private_A,
&dio_private_B,
&dio_private_C,
};
*/
#define devpriv ((struct s626_private *)dev->private)
#define diopriv ((struct dio_private *)s->private)
static int __devinit driver_s626_pci_probe(struct pci_dev *dev,
const struct pci_device_id *ent)
{
return comedi_pci_auto_config(dev, driver_s626.driver_name);
}
static void __devexit driver_s626_pci_remove(struct pci_dev *dev)
{
comedi_pci_auto_unconfig(dev);
}
static struct pci_driver driver_s626_pci_driver = {
.id_table = s626_pci_table,
.probe = &driver_s626_pci_probe,
.remove = __devexit_p(&driver_s626_pci_remove)
};
static int __init driver_s626_init_module(void)
{
int retval;
retval = comedi_driver_register(&driver_s626);
if (retval < 0)
return retval;
driver_s626_pci_driver.name = (char *)driver_s626.driver_name;
return pci_register_driver(&driver_s626_pci_driver);
}
static void __exit driver_s626_cleanup_module(void)
{
pci_unregister_driver(&driver_s626_pci_driver);
comedi_driver_unregister(&driver_s626);
}
module_init(driver_s626_init_module);
module_exit(driver_s626_cleanup_module);
/* ioctl routines */
static int s626_ai_insn_config(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
/* static int s626_ai_rinsn(struct comedi_device *dev,struct comedi_subdevice *s,struct comedi_insn *insn,unsigned int *data); */
static int s626_ai_insn_read(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int s626_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s);
static int s626_ai_cmdtest(struct comedi_device *dev,
struct comedi_subdevice *s, struct comedi_cmd *cmd);
static int s626_ai_cancel(struct comedi_device *dev,
struct comedi_subdevice *s);
static int s626_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int s626_ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int s626_dio_insn_bits(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int s626_dio_insn_config(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int s626_dio_set_irq(struct comedi_device *dev, unsigned int chan);
static int s626_dio_reset_irq(struct comedi_device *dev, unsigned int gruop,
unsigned int mask);
static int s626_dio_clear_irq(struct comedi_device *dev);
static int s626_enc_insn_config(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int s626_enc_insn_read(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int s626_enc_insn_write(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int s626_ns_to_timer(int *nanosec, int round_mode);
static int s626_ai_load_polllist(uint8_t *ppl, struct comedi_cmd *cmd);
static int s626_ai_inttrig(struct comedi_device *dev,
struct comedi_subdevice *s, unsigned int trignum);
static irqreturn_t s626_irq_handler(int irq, void *d);
static unsigned int s626_ai_reg_to_uint(int data);
/* static unsigned int s626_uint_to_reg(struct comedi_subdevice *s, int data); */
/* end ioctl routines */
/* internal routines */
static void s626_dio_init(struct comedi_device *dev);
static void ResetADC(struct comedi_device *dev, uint8_t * ppl);
static void LoadTrimDACs(struct comedi_device *dev);
static void WriteTrimDAC(struct comedi_device *dev, uint8_t LogicalChan,
uint8_t DacData);
static uint8_t I2Cread(struct comedi_device *dev, uint8_t addr);
static uint32_t I2Chandshake(struct comedi_device *dev, uint32_t val);
static void SetDAC(struct comedi_device *dev, uint16_t chan, short dacdata);
static void SendDAC(struct comedi_device *dev, uint32_t val);
static void WriteMISC2(struct comedi_device *dev, uint16_t NewImage);
static void DEBItransfer(struct comedi_device *dev);
static uint16_t DEBIread(struct comedi_device *dev, uint16_t addr);
static void DEBIwrite(struct comedi_device *dev, uint16_t addr, uint16_t wdata);
static void DEBIreplace(struct comedi_device *dev, uint16_t addr, uint16_t mask,
uint16_t wdata);
static void CloseDMAB(struct comedi_device *dev, struct bufferDMA *pdma,
size_t bsize);
/* COUNTER OBJECT ------------------------------------------------ */
struct enc_private {
/* Pointers to functions that differ for A and B counters: */
uint16_t(*GetEnable) (struct comedi_device *dev, struct enc_private *); /* Return clock enable. */
uint16_t(*GetIntSrc) (struct comedi_device *dev, struct enc_private *); /* Return interrupt source. */
uint16_t(*GetLoadTrig) (struct comedi_device *dev, struct enc_private *); /* Return preload trigger source. */
uint16_t(*GetMode) (struct comedi_device *dev, struct enc_private *); /* Return standardized operating mode. */
void (*PulseIndex) (struct comedi_device *dev, struct enc_private *); /* Generate soft index strobe. */
void (*SetEnable) (struct comedi_device *dev, struct enc_private *, uint16_t enab); /* Program clock enable. */
void (*SetIntSrc) (struct comedi_device *dev, struct enc_private *, uint16_t IntSource); /* Program interrupt source. */
void (*SetLoadTrig) (struct comedi_device *dev, struct enc_private *, uint16_t Trig); /* Program preload trigger source. */
void (*SetMode) (struct comedi_device *dev, struct enc_private *, uint16_t Setup, uint16_t DisableIntSrc); /* Program standardized operating mode. */
void (*ResetCapFlags) (struct comedi_device *dev, struct enc_private *); /* Reset event capture flags. */
uint16_t MyCRA; /* Address of CRA register. */
uint16_t MyCRB; /* Address of CRB register. */
uint16_t MyLatchLsw; /* Address of Latch least-significant-word */
/* register. */
uint16_t MyEventBits[4]; /* Bit translations for IntSrc -->RDMISC2. */
};
#define encpriv ((struct enc_private *)(dev->subdevices+5)->private)
/* counters routines */
static void s626_timer_load(struct comedi_device *dev, struct enc_private *k,
int tick);
static uint32_t ReadLatch(struct comedi_device *dev, struct enc_private *k);
static void ResetCapFlags_A(struct comedi_device *dev, struct enc_private *k);
static void ResetCapFlags_B(struct comedi_device *dev, struct enc_private *k);
static uint16_t GetMode_A(struct comedi_device *dev, struct enc_private *k);
static uint16_t GetMode_B(struct comedi_device *dev, struct enc_private *k);
static void SetMode_A(struct comedi_device *dev, struct enc_private *k,
uint16_t Setup, uint16_t DisableIntSrc);
static void SetMode_B(struct comedi_device *dev, struct enc_private *k,
uint16_t Setup, uint16_t DisableIntSrc);
static void SetEnable_A(struct comedi_device *dev, struct enc_private *k,
uint16_t enab);
static void SetEnable_B(struct comedi_device *dev, struct enc_private *k,
uint16_t enab);
static uint16_t GetEnable_A(struct comedi_device *dev, struct enc_private *k);
static uint16_t GetEnable_B(struct comedi_device *dev, struct enc_private *k);
static void SetLatchSource(struct comedi_device *dev, struct enc_private *k,
uint16_t value);
/* static uint16_t GetLatchSource(struct comedi_device *dev, struct enc_private *k ); */
static void SetLoadTrig_A(struct comedi_device *dev, struct enc_private *k,
uint16_t Trig);
static void SetLoadTrig_B(struct comedi_device *dev, struct enc_private *k,
uint16_t Trig);
static uint16_t GetLoadTrig_A(struct comedi_device *dev, struct enc_private *k);
static uint16_t GetLoadTrig_B(struct comedi_device *dev, struct enc_private *k);
static void SetIntSrc_B(struct comedi_device *dev, struct enc_private *k,
uint16_t IntSource);
static void SetIntSrc_A(struct comedi_device *dev, struct enc_private *k,
uint16_t IntSource);
static uint16_t GetIntSrc_A(struct comedi_device *dev, struct enc_private *k);
static uint16_t GetIntSrc_B(struct comedi_device *dev, struct enc_private *k);
/* static void SetClkMult(struct comedi_device *dev, struct enc_private *k, uint16_t value ) ; */
/* static uint16_t GetClkMult(struct comedi_device *dev, struct enc_private *k ) ; */
/* static void SetIndexPol(struct comedi_device *dev, struct enc_private *k, uint16_t value ); */
/* static uint16_t GetClkPol(struct comedi_device *dev, struct enc_private *k ) ; */
/* static void SetIndexSrc( struct comedi_device *dev,struct enc_private *k, uint16_t value ); */
/* static uint16_t GetClkSrc( struct comedi_device *dev,struct enc_private *k ); */
/* static void SetIndexSrc( struct comedi_device *dev,struct enc_private *k, uint16_t value ); */
/* static uint16_t GetIndexSrc( struct comedi_device *dev,struct enc_private *k ); */
static void PulseIndex_A(struct comedi_device *dev, struct enc_private *k);
static void PulseIndex_B(struct comedi_device *dev, struct enc_private *k);
static void Preload(struct comedi_device *dev, struct enc_private *k,
uint32_t value);
static void CountersInit(struct comedi_device *dev);
/* end internal routines */
/* Counter objects constructor. */
/* Counter overflow/index event flag masks for RDMISC2. */
#define INDXMASK(C) (1 << (((C) > 2) ? ((C) * 2 - 1) : ((C) * 2 + 4)))
#define OVERMASK(C) (1 << (((C) > 2) ? ((C) * 2 + 5) : ((C) * 2 + 10)))
#define EVBITS(C) { 0, OVERMASK(C), INDXMASK(C), OVERMASK(C) | INDXMASK(C) }
/* Translation table to map IntSrc into equivalent RDMISC2 event flag bits. */
/* static const uint16_t EventBits[][4] = { EVBITS(0), EVBITS(1), EVBITS(2), EVBITS(3), EVBITS(4), EVBITS(5) }; */
/* struct enc_private; */
static struct enc_private enc_private_data[] = {
{
.GetEnable = GetEnable_A,
.GetIntSrc = GetIntSrc_A,
.GetLoadTrig = GetLoadTrig_A,
.GetMode = GetMode_A,
.PulseIndex = PulseIndex_A,
.SetEnable = SetEnable_A,
.SetIntSrc = SetIntSrc_A,
.SetLoadTrig = SetLoadTrig_A,
.SetMode = SetMode_A,
.ResetCapFlags = ResetCapFlags_A,
.MyCRA = LP_CR0A,
.MyCRB = LP_CR0B,
.MyLatchLsw = LP_CNTR0ALSW,
.MyEventBits = EVBITS(0),
},
{
.GetEnable = GetEnable_A,
.GetIntSrc = GetIntSrc_A,
.GetLoadTrig = GetLoadTrig_A,
.GetMode = GetMode_A,
.PulseIndex = PulseIndex_A,
.SetEnable = SetEnable_A,
.SetIntSrc = SetIntSrc_A,
.SetLoadTrig = SetLoadTrig_A,
.SetMode = SetMode_A,
.ResetCapFlags = ResetCapFlags_A,
.MyCRA = LP_CR1A,
.MyCRB = LP_CR1B,
.MyLatchLsw = LP_CNTR1ALSW,
.MyEventBits = EVBITS(1),
},
{
.GetEnable = GetEnable_A,
.GetIntSrc = GetIntSrc_A,
.GetLoadTrig = GetLoadTrig_A,
.GetMode = GetMode_A,
.PulseIndex = PulseIndex_A,
.SetEnable = SetEnable_A,
.SetIntSrc = SetIntSrc_A,
.SetLoadTrig = SetLoadTrig_A,
.SetMode = SetMode_A,
.ResetCapFlags = ResetCapFlags_A,
.MyCRA = LP_CR2A,
.MyCRB = LP_CR2B,
.MyLatchLsw = LP_CNTR2ALSW,
.MyEventBits = EVBITS(2),
},
{
.GetEnable = GetEnable_B,
.GetIntSrc = GetIntSrc_B,
.GetLoadTrig = GetLoadTrig_B,
.GetMode = GetMode_B,
.PulseIndex = PulseIndex_B,
.SetEnable = SetEnable_B,
.SetIntSrc = SetIntSrc_B,
.SetLoadTrig = SetLoadTrig_B,
.SetMode = SetMode_B,
.ResetCapFlags = ResetCapFlags_B,
.MyCRA = LP_CR0A,
.MyCRB = LP_CR0B,
.MyLatchLsw = LP_CNTR0BLSW,
.MyEventBits = EVBITS(3),
},
{
.GetEnable = GetEnable_B,
.GetIntSrc = GetIntSrc_B,
.GetLoadTrig = GetLoadTrig_B,
.GetMode = GetMode_B,
.PulseIndex = PulseIndex_B,
.SetEnable = SetEnable_B,
.SetIntSrc = SetIntSrc_B,
.SetLoadTrig = SetLoadTrig_B,
.SetMode = SetMode_B,
.ResetCapFlags = ResetCapFlags_B,
.MyCRA = LP_CR1A,
.MyCRB = LP_CR1B,
.MyLatchLsw = LP_CNTR1BLSW,
.MyEventBits = EVBITS(4),
},
{
.GetEnable = GetEnable_B,
.GetIntSrc = GetIntSrc_B,
.GetLoadTrig = GetLoadTrig_B,
.GetMode = GetMode_B,
.PulseIndex = PulseIndex_B,
.SetEnable = SetEnable_B,
.SetIntSrc = SetIntSrc_B,
.SetLoadTrig = SetLoadTrig_B,
.SetMode = SetMode_B,
.ResetCapFlags = ResetCapFlags_B,
.MyCRA = LP_CR2A,
.MyCRB = LP_CR2B,
.MyLatchLsw = LP_CNTR2BLSW,
.MyEventBits = EVBITS(5),
},
};
/* enab/disable a function or test status bit(s) that are accessed */
/* through Main Control Registers 1 or 2. */
#define MC_ENABLE(REGADRS, CTRLWORD) writel(((uint32_t)(CTRLWORD) << 16) | (uint32_t)(CTRLWORD), devpriv->base_addr+(REGADRS))
#define MC_DISABLE(REGADRS, CTRLWORD) writel((uint32_t)(CTRLWORD) << 16 , devpriv->base_addr+(REGADRS))
#define MC_TEST(REGADRS, CTRLWORD) ((readl(devpriv->base_addr+(REGADRS)) & CTRLWORD) != 0)
/* #define WR7146(REGARDS,CTRLWORD)
writel(CTRLWORD,(uint32_t)(devpriv->base_addr+(REGARDS))) */
#define WR7146(REGARDS, CTRLWORD) writel(CTRLWORD, devpriv->base_addr+(REGARDS))
/* #define RR7146(REGARDS)
readl((uint32_t)(devpriv->base_addr+(REGARDS))) */
#define RR7146(REGARDS) readl(devpriv->base_addr+(REGARDS))
#define BUGFIX_STREG(REGADRS) (REGADRS - 4)
/* Write a time slot control record to TSL2. */
#define VECTPORT(VECTNUM) (P_TSL2 + ((VECTNUM) << 2))
#define SETVECT(VECTNUM, VECTVAL) WR7146(VECTPORT(VECTNUM), (VECTVAL))
/* Code macros used for constructing I2C command bytes. */
#define I2C_B2(ATTR, VAL) (((ATTR) << 6) | ((VAL) << 24))
#define I2C_B1(ATTR, VAL) (((ATTR) << 4) | ((VAL) << 16))
#define I2C_B0(ATTR, VAL) (((ATTR) << 2) | ((VAL) << 8))
static const struct comedi_lrange s626_range_table = { 2, {
RANGE(-5, 5),
RANGE(-10, 10),
}
};
static int s626_attach(struct comedi_device *dev, struct comedi_devconfig *it)
{
/* uint8_t PollList; */
/* uint16_t AdcData; */
/* uint16_t StartVal; */
/* uint16_t index; */
/* unsigned int data[16]; */
int result;
int i;
int ret;
resource_size_t resourceStart;
dma_addr_t appdma;
struct comedi_subdevice *s;
const struct pci_device_id *ids;
struct pci_dev *pdev = NULL;
if (alloc_private(dev, sizeof(struct s626_private)) < 0)
return -ENOMEM;
for (i = 0; i < (ARRAY_SIZE(s626_pci_table) - 1) && !pdev; i++) {
ids = &s626_pci_table[i];
do {
pdev = pci_get_subsys(ids->vendor, ids->device,
ids->subvendor, ids->subdevice,
pdev);
if ((it->options[0] || it->options[1]) && pdev) {
/* matches requested bus/slot */
if (pdev->bus->number == it->options[0] &&
PCI_SLOT(pdev->devfn) == it->options[1])
break;
} else
break;
} while (1);
}
devpriv->pdev = pdev;
if (pdev == NULL) {
printk(KERN_ERR "s626_attach: Board not present!!!\n");
return -ENODEV;
}
result = comedi_pci_enable(pdev, "s626");
if (result < 0) {
printk(KERN_ERR "s626_attach: comedi_pci_enable fails\n");
return -ENODEV;
}
devpriv->got_regions = 1;
resourceStart = pci_resource_start(devpriv->pdev, 0);
devpriv->base_addr = ioremap(resourceStart, SIZEOF_ADDRESS_SPACE);
if (devpriv->base_addr == NULL) {
printk(KERN_ERR "s626_attach: IOREMAP failed\n");
return -ENODEV;
}
if (devpriv->base_addr) {
/* disable master interrupt */
writel(0, devpriv->base_addr + P_IER);
/* soft reset */
writel(MC1_SOFT_RESET, devpriv->base_addr + P_MC1);
/* DMA FIXME DMA// */
DEBUG("s626_attach: DMA ALLOCATION\n");
/* adc buffer allocation */
devpriv->allocatedBuf = 0;
devpriv->ANABuf.LogicalBase =
pci_alloc_consistent(devpriv->pdev, DMABUF_SIZE, &appdma);
if (devpriv->ANABuf.LogicalBase == NULL) {
printk(KERN_ERR "s626_attach: DMA Memory mapping error\n");
return -ENOMEM;
}
devpriv->ANABuf.PhysicalBase = appdma;
DEBUG
("s626_attach: AllocDMAB ADC Logical=%p, bsize=%d, Physical=0x%x\n",
devpriv->ANABuf.LogicalBase, DMABUF_SIZE,
(uint32_t) devpriv->ANABuf.PhysicalBase);
devpriv->allocatedBuf++;
devpriv->RPSBuf.LogicalBase =
pci_alloc_consistent(devpriv->pdev, DMABUF_SIZE, &appdma);
if (devpriv->RPSBuf.LogicalBase == NULL) {
printk(KERN_ERR "s626_attach: DMA Memory mapping error\n");
return -ENOMEM;
}
devpriv->RPSBuf.PhysicalBase = appdma;
DEBUG
("s626_attach: AllocDMAB RPS Logical=%p, bsize=%d, Physical=0x%x\n",
devpriv->RPSBuf.LogicalBase, DMABUF_SIZE,
(uint32_t) devpriv->RPSBuf.PhysicalBase);
devpriv->allocatedBuf++;
}
dev->board_ptr = s626_boards;
dev->board_name = thisboard->name;
if (alloc_subdevices(dev, 6) < 0)
return -ENOMEM;
dev->iobase = (unsigned long)devpriv->base_addr;
dev->irq = devpriv->pdev->irq;
/* set up interrupt handler */
if (dev->irq == 0) {
printk(KERN_ERR " unknown irq (bad)\n");
} else {
ret = request_irq(dev->irq, s626_irq_handler, IRQF_SHARED,
"s626", dev);
if (ret < 0) {
printk(KERN_ERR " irq not available\n");
dev->irq = 0;
}
}
DEBUG("s626_attach: -- it opts %d,%d --\n",
it->options[0], it->options[1]);
s = dev->subdevices + 0;
/* analog input subdevice */
dev->read_subdev = s;
/* we support single-ended (ground) and differential */
s->type = COMEDI_SUBD_AI;
s->subdev_flags = SDF_READABLE | SDF_DIFF | SDF_CMD_READ;
s->n_chan = thisboard->ai_chans;
s->maxdata = (0xffff >> 2);
s->range_table = &s626_range_table;
s->len_chanlist = thisboard->ai_chans; /* This is the maximum chanlist
length that the board can
handle */
s->insn_config = s626_ai_insn_config;
s->insn_read = s626_ai_insn_read;
s->do_cmd = s626_ai_cmd;
s->do_cmdtest = s626_ai_cmdtest;
s->cancel = s626_ai_cancel;
s = dev->subdevices + 1;
/* analog output subdevice */
s->type = COMEDI_SUBD_AO;
s->subdev_flags = SDF_WRITABLE | SDF_READABLE;
s->n_chan = thisboard->ao_chans;
s->maxdata = (0x3fff);
s->range_table = &range_bipolar10;
s->insn_write = s626_ao_winsn;
s->insn_read = s626_ao_rinsn;
s = dev->subdevices + 2;
/* digital I/O subdevice */
s->type = COMEDI_SUBD_DIO;
s->subdev_flags = SDF_WRITABLE | SDF_READABLE;
s->n_chan = S626_DIO_CHANNELS;
s->maxdata = 1;
s->io_bits = 0xffff;
s->private = &dio_private_A;
s->range_table = &range_digital;
s->insn_config = s626_dio_insn_config;
s->insn_bits = s626_dio_insn_bits;
s = dev->subdevices + 3;
/* digital I/O subdevice */
s->type = COMEDI_SUBD_DIO;
s->subdev_flags = SDF_WRITABLE | SDF_READABLE;
s->n_chan = 16;
s->maxdata = 1;
s->io_bits = 0xffff;
s->private = &dio_private_B;
s->range_table = &range_digital;
s->insn_config = s626_dio_insn_config;
s->insn_bits = s626_dio_insn_bits;
s = dev->subdevices + 4;
/* digital I/O subdevice */
s->type = COMEDI_SUBD_DIO;
s->subdev_flags = SDF_WRITABLE | SDF_READABLE;
s->n_chan = 16;
s->maxdata = 1;
s->io_bits = 0xffff;
s->private = &dio_private_C;
s->range_table = &range_digital;
s->insn_config = s626_dio_insn_config;
s->insn_bits = s626_dio_insn_bits;
s = dev->subdevices + 5;
/* encoder (counter) subdevice */
s->type = COMEDI_SUBD_COUNTER;
s->subdev_flags = SDF_WRITABLE | SDF_READABLE | SDF_LSAMPL;
s->n_chan = thisboard->enc_chans;
s->private = enc_private_data;
s->insn_config = s626_enc_insn_config;
s->insn_read = s626_enc_insn_read;
s->insn_write = s626_enc_insn_write;
s->maxdata = 0xffffff;
s->range_table = &range_unknown;
/* stop ai_command */
devpriv->ai_cmd_running = 0;
if (devpriv->base_addr && (devpriv->allocatedBuf == 2)) {
dma_addr_t pPhysBuf;
uint16_t chan;
/* enab DEBI and audio pins, enable I2C interface. */
MC_ENABLE(P_MC1, MC1_DEBI | MC1_AUDIO | MC1_I2C);
/* Configure DEBI operating mode. */
WR7146(P_DEBICFG, DEBI_CFG_SLAVE16 /* Local bus is 16 */
/* bits wide. */
| (DEBI_TOUT << DEBI_CFG_TOUT_BIT)
/* Declare DEBI */
/* transfer timeout */
/* interval. */
|DEBI_SWAP /* Set up byte lane */
/* steering. */
| DEBI_CFG_INTEL); /* Intel-compatible */
/* local bus (DEBI */
/* never times out). */
DEBUG("s626_attach: %d debi init -- %d\n",
DEBI_CFG_SLAVE16 | (DEBI_TOUT << DEBI_CFG_TOUT_BIT) |
DEBI_SWAP | DEBI_CFG_INTEL,
DEBI_CFG_INTEL | DEBI_CFG_TOQ | DEBI_CFG_INCQ |
DEBI_CFG_16Q);
/* DEBI INIT S626 WR7146( P_DEBICFG, DEBI_CFG_INTEL | DEBI_CFG_TOQ */
/* | DEBI_CFG_INCQ| DEBI_CFG_16Q); //end */
/* Paging is disabled. */
WR7146(P_DEBIPAGE, DEBI_PAGE_DISABLE); /* Disable MMU paging. */
/* Init GPIO so that ADC Start* is negated. */
WR7146(P_GPIO, GPIO_BASE | GPIO1_HI);
/* IsBoardRevA is a boolean that indicates whether the board is RevA.
*
* VERSION 2.01 CHANGE: REV A & B BOARDS NOW SUPPORTED BY DYNAMIC
* EEPROM ADDRESS SELECTION. Initialize the I2C interface, which
* is used to access the onboard serial EEPROM. The EEPROM's I2C
* DeviceAddress is hardwired to a value that is dependent on the
* 626 board revision. On all board revisions, the EEPROM stores
* TrimDAC calibration constants for analog I/O. On RevB and
* higher boards, the DeviceAddress is hardwired to 0 to enable
* the EEPROM to also store the PCI SubVendorID and SubDeviceID;
* this is the address at which the SAA7146 expects a
* configuration EEPROM to reside. On RevA boards, the EEPROM
* device address, which is hardwired to 4, prevents the SAA7146
* from retrieving PCI sub-IDs, so the SAA7146 uses its built-in
* default values, instead.
*/
/* devpriv->I2Cards= IsBoardRevA ? 0xA8 : 0xA0; // Set I2C EEPROM */
/* DeviceType (0xA0) */
/* and DeviceAddress<<1. */
devpriv->I2CAdrs = 0xA0; /* I2C device address for onboard */
/* eeprom(revb) */
/* Issue an I2C ABORT command to halt any I2C operation in */
/* progress and reset BUSY flag. */
WR7146(P_I2CSTAT, I2C_CLKSEL | I2C_ABORT);
/* Write I2C control: abort any I2C activity. */
MC_ENABLE(P_MC2, MC2_UPLD_IIC);
/* Invoke command upload */
while ((RR7146(P_MC2) & MC2_UPLD_IIC) == 0)
;
/* and wait for upload to complete. */
/* Per SAA7146 data sheet, write to STATUS reg twice to
* reset all I2C error flags. */
for (i = 0; i < 2; i++) {
WR7146(P_I2CSTAT, I2C_CLKSEL);
/* Write I2C control: reset error flags. */
MC_ENABLE(P_MC2, MC2_UPLD_IIC); /* Invoke command upload */
while (!MC_TEST(P_MC2, MC2_UPLD_IIC))
;
/* and wait for upload to complete. */
}
/* Init audio interface functional attributes: set DAC/ADC
* serial clock rates, invert DAC serial clock so that
* DAC data setup times are satisfied, enable DAC serial
* clock out.
*/
WR7146(P_ACON2, ACON2_INIT);
/* Set up TSL1 slot list, which is used to control the
* accumulation of ADC data: RSD1 = shift data in on SD1.
* SIB_A1 = store data uint8_t at next available location in
* FB BUFFER1 register. */
WR7146(P_TSL1, RSD1 | SIB_A1);
/* Fetch ADC high data uint8_t. */
WR7146(P_TSL1 + 4, RSD1 | SIB_A1 | EOS);
/* Fetch ADC low data uint8_t; end of TSL1. */
/* enab TSL1 slot list so that it executes all the time. */
WR7146(P_ACON1, ACON1_ADCSTART);
/* Initialize RPS registers used for ADC. */
/* Physical start of RPS program. */
WR7146(P_RPSADDR1, (uint32_t) devpriv->RPSBuf.PhysicalBase);
WR7146(P_RPSPAGE1, 0);
/* RPS program performs no explicit mem writes. */
WR7146(P_RPS1_TOUT, 0); /* Disable RPS timeouts. */
/* SAA7146 BUG WORKAROUND. Initialize SAA7146 ADC interface
* to a known state by invoking ADCs until FB BUFFER 1
* register shows that it is correctly receiving ADC data.
* This is necessary because the SAA7146 ADC interface does
* not start up in a defined state after a PCI reset.
*/
/* PollList = EOPL; // Create a simple polling */
/* // list for analog input */
/* // channel 0. */
/* ResetADC( dev, &PollList ); */
/* s626_ai_rinsn(dev,dev->subdevices,NULL,data); //( &AdcData ); // */
/* //Get initial ADC */
/* //value. */
/* StartVal = data[0]; */
/* // VERSION 2.01 CHANGE: TIMEOUT ADDED TO PREVENT HANGED EXECUTION. */
/* // Invoke ADCs until the new ADC value differs from the initial */
/* // value or a timeout occurs. The timeout protects against the */
/* // possibility that the driver is restarting and the ADC data is a */
/* // fixed value resulting from the applied ADC analog input being */
/* // unusually quiet or at the rail. */
/* for ( index = 0; index < 500; index++ ) */
/* { */
/* s626_ai_rinsn(dev,dev->subdevices,NULL,data); */
/* AdcData = data[0]; //ReadADC( &AdcData ); */
/* if ( AdcData != StartVal ) */
/* break; */
/* } */
/* end initADC */
/* init the DAC interface */
/* Init Audio2's output DMAC attributes: burst length = 1
* DWORD, threshold = 1 DWORD.
*/
WR7146(P_PCI_BT_A, 0);
/* Init Audio2's output DMA physical addresses. The protection
* address is set to 1 DWORD past the base address so that a
* single DWORD will be transferred each time a DMA transfer is
* enabled. */
pPhysBuf =
devpriv->ANABuf.PhysicalBase +
(DAC_WDMABUF_OS * sizeof(uint32_t));
WR7146(P_BASEA2_OUT, (uint32_t) pPhysBuf); /* Buffer base adrs. */
WR7146(P_PROTA2_OUT, (uint32_t) (pPhysBuf + sizeof(uint32_t))); /* Protection address. */
/* Cache Audio2's output DMA buffer logical address. This is
* where DAC data is buffered for A2 output DMA transfers. */
devpriv->pDacWBuf =
(uint32_t *) devpriv->ANABuf.LogicalBase + DAC_WDMABUF_OS;
/* Audio2's output channels does not use paging. The protection
* violation handling bit is set so that the DMAC will
* automatically halt and its PCI address pointer will be reset
* when the protection address is reached. */
WR7146(P_PAGEA2_OUT, 8);
/* Initialize time slot list 2 (TSL2), which is used to control
* the clock generation for and serialization of data to be sent
* to the DAC devices. Slot 0 is a NOP that is used to trap TSL
* execution; this permits other slots to be safely modified
* without first turning off the TSL sequencer (which is
* apparently impossible to do). Also, SD3 (which is driven by a
* pull-up resistor) is shifted in and stored to the MSB of
* FB_BUFFER2 to be used as evidence that the slot sequence has
* not yet finished executing.
*/
SETVECT(0, XSD2 | RSD3 | SIB_A2 | EOS);
/* Slot 0: Trap TSL execution, shift 0xFF into FB_BUFFER2. */
/* Initialize slot 1, which is constant. Slot 1 causes a
* DWORD to be transferred from audio channel 2's output FIFO
* to the FIFO's output buffer so that it can be serialized
* and sent to the DAC during subsequent slots. All remaining
* slots are dynamically populated as required by the target
* DAC device.
*/
SETVECT(1, LF_A2);
/* Slot 1: Fetch DWORD from Audio2's output FIFO. */
/* Start DAC's audio interface (TSL2) running. */
WR7146(P_ACON1, ACON1_DACSTART);
/* end init DAC interface */
/* Init Trim DACs to calibrated values. Do it twice because the
* SAA7146 audio channel does not always reset properly and
* sometimes causes the first few TrimDAC writes to malfunction.
*/
LoadTrimDACs(dev);
LoadTrimDACs(dev); /* Insurance. */
/* Manually init all gate array hardware in case this is a soft
* reset (we have no way of determining whether this is a warm
* or cold start). This is necessary because the gate array will
* reset only in response to a PCI hard reset; there is no soft
* reset function. */
/* Init all DAC outputs to 0V and init all DAC setpoint and
* polarity images.
*/
for (chan = 0; chan < S626_DAC_CHANNELS; chan++)
SetDAC(dev, chan, 0);
/* Init image of WRMISC2 Battery Charger Enabled control bit.
* This image is used when the state of the charger control bit,
* which has no direct hardware readback mechanism, is queried.
*/
devpriv->ChargeEnabled = 0;
/* Init image of watchdog timer interval in WRMISC2. This image
* maintains the value of the control bits of MISC2 are
* continuously reset to zero as long as the WD timer is disabled.
*/
devpriv->WDInterval = 0;
/* Init Counter Interrupt enab mask for RDMISC2. This mask is
* applied against MISC2 when testing to determine which timer
* events are requesting interrupt service.
*/
devpriv->CounterIntEnabs = 0;
/* Init counters. */
CountersInit(dev);
/* Without modifying the state of the Battery Backup enab, disable
* the watchdog timer, set DIO channels 0-5 to operate in the
* standard DIO (vs. counter overflow) mode, disable the battery
* charger, and reset the watchdog interval selector to zero.
*/
WriteMISC2(dev, (uint16_t) (DEBIread(dev,
LP_RDMISC2) &
MISC2_BATT_ENABLE));
/* Initialize the digital I/O subsystem. */
s626_dio_init(dev);
/* enable interrupt test */
/* writel(IRQ_GPIO3 | IRQ_RPS1,devpriv->base_addr+P_IER); */
}
DEBUG("s626_attach: comedi%d s626 attached %04x\n", dev->minor,
(uint32_t) devpriv->base_addr);
return 1;
}
static unsigned int s626_ai_reg_to_uint(int data)
{
unsigned int tempdata;
tempdata = (data >> 18);
if (tempdata & 0x2000)
tempdata &= 0x1fff;
else
tempdata += (1 << 13);
return tempdata;
}
/* static unsigned int s626_uint_to_reg(struct comedi_subdevice *s, int data){ */
/* return 0; */
/* } */
static irqreturn_t s626_irq_handler(int irq, void *d)
{
struct comedi_device *dev = d;
struct comedi_subdevice *s;
struct comedi_cmd *cmd;
struct enc_private *k;
unsigned long flags;
int32_t *readaddr;
uint32_t irqtype, irqstatus;
int i = 0;
short tempdata;
uint8_t group;
uint16_t irqbit;
DEBUG("s626_irq_handler: interrupt request received!!!\n");
if (dev->attached == 0)
return IRQ_NONE;
/* lock to avoid race with comedi_poll */
spin_lock_irqsave(&dev->spinlock, flags);
/* save interrupt enable register state */
irqstatus = readl(devpriv->base_addr + P_IER);
/* read interrupt type */
irqtype = readl(devpriv->base_addr + P_ISR);
/* disable master interrupt */
writel(0, devpriv->base_addr + P_IER);
/* clear interrupt */
writel(irqtype, devpriv->base_addr + P_ISR);
/* do somethings */
DEBUG("s626_irq_handler: interrupt type %d\n", irqtype);
switch (irqtype) {
case IRQ_RPS1: /* end_of_scan occurs */
DEBUG("s626_irq_handler: RPS1 irq detected\n");
/* manage ai subdevice */
s = dev->subdevices;
cmd = &(s->async->cmd);
/* Init ptr to DMA buffer that holds new ADC data. We skip the
* first uint16_t in the buffer because it contains junk data from
* the final ADC of the previous poll list scan.
*/
readaddr = (int32_t *) devpriv->ANABuf.LogicalBase + 1;
/* get the data and hand it over to comedi */
for (i = 0; i < (s->async->cmd.chanlist_len); i++) {
/* Convert ADC data to 16-bit integer values and copy to application */
/* buffer. */
tempdata = s626_ai_reg_to_uint((int)*readaddr);
readaddr++;
/* put data into read buffer */
/* comedi_buf_put(s->async, tempdata); */
if (cfc_write_to_buffer(s, tempdata) == 0)
printk
("s626_irq_handler: cfc_write_to_buffer error!\n");
DEBUG("s626_irq_handler: ai channel %d acquired: %d\n",
i, tempdata);
}
/* end of scan occurs */
s->async->events |= COMEDI_CB_EOS;
if (!(devpriv->ai_continous))
devpriv->ai_sample_count--;
if (devpriv->ai_sample_count <= 0) {
devpriv->ai_cmd_running = 0;
/* Stop RPS program. */
MC_DISABLE(P_MC1, MC1_ERPS1);
/* send end of acquisition */
s->async->events |= COMEDI_CB_EOA;
/* disable master interrupt */
irqstatus = 0;
}
if (devpriv->ai_cmd_running && cmd->scan_begin_src == TRIG_EXT) {
DEBUG
("s626_irq_handler: enable interrupt on dio channel %d\n",
cmd->scan_begin_arg);
s626_dio_set_irq(dev, cmd->scan_begin_arg);
DEBUG("s626_irq_handler: External trigger is set!!!\n");
}
/* tell comedi that data is there */
DEBUG("s626_irq_handler: events %d\n", s->async->events);
comedi_event(dev, s);
break;
case IRQ_GPIO3: /* check dio and conter interrupt */
DEBUG("s626_irq_handler: GPIO3 irq detected\n");
/* manage ai subdevice */
s = dev->subdevices;
cmd = &(s->async->cmd);
/* s626_dio_clear_irq(dev); */
for (group = 0; group < S626_DIO_BANKS; group++) {
irqbit = 0;
/* read interrupt type */
irqbit = DEBIread(dev,
((struct dio_private *)(dev->
subdevices +
2 +
group)->
private)->RDCapFlg);
/* check if interrupt is generated from dio channels */
if (irqbit) {
s626_dio_reset_irq(dev, group, irqbit);
DEBUG
("s626_irq_handler: check interrupt on dio group %d %d\n",
group, i);
if (devpriv->ai_cmd_running) {
/* check if interrupt is an ai acquisition start trigger */
if ((irqbit >> (cmd->start_arg -
(16 * group)))
== 1 && cmd->start_src == TRIG_EXT) {
DEBUG
("s626_irq_handler: Edge capture interrupt received from channel %d\n",
cmd->start_arg);
/* Start executing the RPS program. */
MC_ENABLE(P_MC1, MC1_ERPS1);
DEBUG
("s626_irq_handler: acquisition start triggered!!!\n");
if (cmd->scan_begin_src ==
TRIG_EXT) {
DEBUG
("s626_ai_cmd: enable interrupt on dio channel %d\n",
cmd->
scan_begin_arg);
s626_dio_set_irq(dev,
cmd->scan_begin_arg);
DEBUG
("s626_irq_handler: External scan trigger is set!!!\n");
}
}
if ((irqbit >> (cmd->scan_begin_arg -
(16 * group)))
== 1
&& cmd->scan_begin_src ==
TRIG_EXT) {
DEBUG
("s626_irq_handler: Edge capture interrupt received from channel %d\n",
cmd->scan_begin_arg);
/* Trigger ADC scan loop start by setting RPS Signal 0. */
MC_ENABLE(P_MC2, MC2_ADC_RPS);
DEBUG
("s626_irq_handler: scan triggered!!! %d\n",
devpriv->ai_sample_count);
if (cmd->convert_src ==
TRIG_EXT) {
DEBUG
("s626_ai_cmd: enable interrupt on dio channel %d group %d\n",
cmd->convert_arg -
(16 * group),
group);
devpriv->ai_convert_count
= cmd->chanlist_len;
s626_dio_set_irq(dev,
cmd->convert_arg);
DEBUG
("s626_irq_handler: External convert trigger is set!!!\n");
}
if (cmd->convert_src ==
TRIG_TIMER) {
k = &encpriv[5];
devpriv->ai_convert_count
= cmd->chanlist_len;
k->SetEnable(dev, k,
CLKENAB_ALWAYS);
}
}
if ((irqbit >> (cmd->convert_arg -
(16 * group)))
== 1
&& cmd->convert_src == TRIG_EXT) {
DEBUG
("s626_irq_handler: Edge capture interrupt received from channel %d\n",
cmd->convert_arg);
/* Trigger ADC scan loop start by setting RPS Signal 0. */
MC_ENABLE(P_MC2, MC2_ADC_RPS);
DEBUG
("s626_irq_handler: adc convert triggered!!!\n");
devpriv->ai_convert_count--;
if (devpriv->ai_convert_count >
0) {
DEBUG
("s626_ai_cmd: enable interrupt on dio channel %d group %d\n",
cmd->convert_arg -
(16 * group),
group);
s626_dio_set_irq(dev,
cmd->convert_arg);
DEBUG
("s626_irq_handler: External trigger is set!!!\n");
}
}
}
break;
}
}
/* read interrupt type */
irqbit = DEBIread(dev, LP_RDMISC2);
/* check interrupt on counters */
DEBUG("s626_irq_handler: check counters interrupt %d\n",
irqbit);
if (irqbit & IRQ_COINT1A) {
DEBUG
("s626_irq_handler: interrupt on counter 1A overflow\n");
k = &encpriv[0];
/* clear interrupt capture flag */
k->ResetCapFlags(dev, k);
}
if (irqbit & IRQ_COINT2A) {
DEBUG
("s626_irq_handler: interrupt on counter 2A overflow\n");
k = &encpriv[1];
/* clear interrupt capture flag */
k->ResetCapFlags(dev, k);
}
if (irqbit & IRQ_COINT3A) {
DEBUG
("s626_irq_handler: interrupt on counter 3A overflow\n");
k = &encpriv[2];
/* clear interrupt capture flag */
k->ResetCapFlags(dev, k);
}
if (irqbit & IRQ_COINT1B) {
DEBUG
("s626_irq_handler: interrupt on counter 1B overflow\n");
k = &encpriv[3];
/* clear interrupt capture flag */
k->ResetCapFlags(dev, k);
}
if (irqbit & IRQ_COINT2B) {
DEBUG
("s626_irq_handler: interrupt on counter 2B overflow\n");
k = &encpriv[4];
/* clear interrupt capture flag */
k->ResetCapFlags(dev, k);
if (devpriv->ai_convert_count > 0) {
devpriv->ai_convert_count--;
if (devpriv->ai_convert_count == 0)
k->SetEnable(dev, k, CLKENAB_INDEX);
if (cmd->convert_src == TRIG_TIMER) {
DEBUG
("s626_irq_handler: conver timer trigger!!! %d\n",
devpriv->ai_convert_count);
/* Trigger ADC scan loop start by setting RPS Signal 0. */
MC_ENABLE(P_MC2, MC2_ADC_RPS);
}
}
}
if (irqbit & IRQ_COINT3B) {
DEBUG
("s626_irq_handler: interrupt on counter 3B overflow\n");
k = &encpriv[5];
/* clear interrupt capture flag */
k->ResetCapFlags(dev, k);
if (cmd->scan_begin_src == TRIG_TIMER) {
DEBUG
("s626_irq_handler: scan timer trigger!!!\n");
/* Trigger ADC scan loop start by setting RPS Signal 0. */
MC_ENABLE(P_MC2, MC2_ADC_RPS);
}
if (cmd->convert_src == TRIG_TIMER) {
DEBUG
("s626_irq_handler: convert timer trigger is set\n");
k = &encpriv[4];
devpriv->ai_convert_count = cmd->chanlist_len;
k->SetEnable(dev, k, CLKENAB_ALWAYS);
}
}
}
/* enable interrupt */
writel(irqstatus, devpriv->base_addr + P_IER);
DEBUG("s626_irq_handler: exit interrupt service routine.\n");
spin_unlock_irqrestore(&dev->spinlock, flags);
return IRQ_HANDLED;
}
static int s626_detach(struct comedi_device *dev)
{
if (devpriv) {
/* stop ai_command */
devpriv->ai_cmd_running = 0;
if (devpriv->base_addr) {
/* interrupt mask */
WR7146(P_IER, 0); /* Disable master interrupt. */
WR7146(P_ISR, IRQ_GPIO3 | IRQ_RPS1); /* Clear board's IRQ status flag. */
/* Disable the watchdog timer and battery charger. */
WriteMISC2(dev, 0);
/* Close all interfaces on 7146 device. */
WR7146(P_MC1, MC1_SHUTDOWN);
WR7146(P_ACON1, ACON1_BASE);
CloseDMAB(dev, &devpriv->RPSBuf, DMABUF_SIZE);
CloseDMAB(dev, &devpriv->ANABuf, DMABUF_SIZE);
}
if (dev->irq)
free_irq(dev->irq, dev);
if (devpriv->base_addr)
iounmap(devpriv->base_addr);
if (devpriv->pdev) {
if (devpriv->got_regions)
comedi_pci_disable(devpriv->pdev);
pci_dev_put(devpriv->pdev);
}
}
DEBUG("s626_detach: S626 detached!\n");
return 0;
}
/*
* this functions build the RPS program for hardware driven acquistion
*/
void ResetADC(struct comedi_device *dev, uint8_t * ppl)
{
register uint32_t *pRPS;
uint32_t JmpAdrs;
uint16_t i;
uint16_t n;
uint32_t LocalPPL;
struct comedi_cmd *cmd = &(dev->subdevices->async->cmd);
/* Stop RPS program in case it is currently running. */
MC_DISABLE(P_MC1, MC1_ERPS1);
/* Set starting logical address to write RPS commands. */
pRPS = (uint32_t *) devpriv->RPSBuf.LogicalBase;
/* Initialize RPS instruction pointer. */
WR7146(P_RPSADDR1, (uint32_t) devpriv->RPSBuf.PhysicalBase);
/* Construct RPS program in RPSBuf DMA buffer */
if (cmd != NULL && cmd->scan_begin_src != TRIG_FOLLOW) {
DEBUG("ResetADC: scan_begin pause inserted\n");
/* Wait for Start trigger. */
*pRPS++ = RPS_PAUSE | RPS_SIGADC;
*pRPS++ = RPS_CLRSIGNAL | RPS_SIGADC;
}
/* SAA7146 BUG WORKAROUND Do a dummy DEBI Write. This is necessary
* because the first RPS DEBI Write following a non-RPS DEBI write
* seems to always fail. If we don't do this dummy write, the ADC
* gain might not be set to the value required for the first slot in
* the poll list; the ADC gain would instead remain unchanged from
* the previously programmed value.
*/
*pRPS++ = RPS_LDREG | (P_DEBICMD >> 2);
/* Write DEBI Write command and address to shadow RAM. */
*pRPS++ = DEBI_CMD_WRWORD | LP_GSEL;
*pRPS++ = RPS_LDREG | (P_DEBIAD >> 2);
/* Write DEBI immediate data to shadow RAM: */
*pRPS++ = GSEL_BIPOLAR5V;
/* arbitrary immediate data value. */
*pRPS++ = RPS_CLRSIGNAL | RPS_DEBI;
/* Reset "shadow RAM uploaded" flag. */
*pRPS++ = RPS_UPLOAD | RPS_DEBI; /* Invoke shadow RAM upload. */
*pRPS++ = RPS_PAUSE | RPS_DEBI; /* Wait for shadow upload to finish. */
/* Digitize all slots in the poll list. This is implemented as a
* for loop to limit the slot count to 16 in case the application
* forgot to set the EOPL flag in the final slot.
*/
for (devpriv->AdcItems = 0; devpriv->AdcItems < 16; devpriv->AdcItems++) {
/* Convert application's poll list item to private board class
* format. Each app poll list item is an uint8_t with form
* (EOPL,x,x,RANGE,CHAN<3:0>), where RANGE code indicates 0 =
* +-10V, 1 = +-5V, and EOPL = End of Poll List marker.
*/
LocalPPL =
(*ppl << 8) | (*ppl & 0x10 ? GSEL_BIPOLAR5V :
GSEL_BIPOLAR10V);
/* Switch ADC analog gain. */
*pRPS++ = RPS_LDREG | (P_DEBICMD >> 2); /* Write DEBI command */
/* and address to */
/* shadow RAM. */
*pRPS++ = DEBI_CMD_WRWORD | LP_GSEL;
*pRPS++ = RPS_LDREG | (P_DEBIAD >> 2); /* Write DEBI */
/* immediate data to */
/* shadow RAM. */
*pRPS++ = LocalPPL;
*pRPS++ = RPS_CLRSIGNAL | RPS_DEBI; /* Reset "shadow RAM uploaded" */
/* flag. */
*pRPS++ = RPS_UPLOAD | RPS_DEBI; /* Invoke shadow RAM upload. */
*pRPS++ = RPS_PAUSE | RPS_DEBI; /* Wait for shadow upload to */
/* finish. */
/* Select ADC analog input channel. */
*pRPS++ = RPS_LDREG | (P_DEBICMD >> 2);
/* Write DEBI command and address to shadow RAM. */
*pRPS++ = DEBI_CMD_WRWORD | LP_ISEL;
*pRPS++ = RPS_LDREG | (P_DEBIAD >> 2);
/* Write DEBI immediate data to shadow RAM. */
*pRPS++ = LocalPPL;
*pRPS++ = RPS_CLRSIGNAL | RPS_DEBI;
/* Reset "shadow RAM uploaded" flag. */
*pRPS++ = RPS_UPLOAD | RPS_DEBI;
/* Invoke shadow RAM upload. */
*pRPS++ = RPS_PAUSE | RPS_DEBI;
/* Wait for shadow upload to finish. */
/* Delay at least 10 microseconds for analog input settling.
* Instead of padding with NOPs, we use RPS_JUMP instructions
* here; this allows us to produce a longer delay than is
* possible with NOPs because each RPS_JUMP flushes the RPS'
* instruction prefetch pipeline.
*/
JmpAdrs =
(uint32_t) devpriv->RPSBuf.PhysicalBase +
(uint32_t) ((unsigned long)pRPS -
(unsigned long)devpriv->RPSBuf.LogicalBase);
for (i = 0; i < (10 * RPSCLK_PER_US / 2); i++) {
JmpAdrs += 8; /* Repeat to implement time delay: */
*pRPS++ = RPS_JUMP; /* Jump to next RPS instruction. */
*pRPS++ = JmpAdrs;
}
if (cmd != NULL && cmd->convert_src != TRIG_NOW) {
DEBUG("ResetADC: convert pause inserted\n");
/* Wait for Start trigger. */
*pRPS++ = RPS_PAUSE | RPS_SIGADC;
*pRPS++ = RPS_CLRSIGNAL | RPS_SIGADC;
}
/* Start ADC by pulsing GPIO1. */
*pRPS++ = RPS_LDREG | (P_GPIO >> 2); /* Begin ADC Start pulse. */
*pRPS++ = GPIO_BASE | GPIO1_LO;
*pRPS++ = RPS_NOP;
/* VERSION 2.03 CHANGE: STRETCH OUT ADC START PULSE. */
*pRPS++ = RPS_LDREG | (P_GPIO >> 2); /* End ADC Start pulse. */
*pRPS++ = GPIO_BASE | GPIO1_HI;
/* Wait for ADC to complete (GPIO2 is asserted high when ADC not
* busy) and for data from previous conversion to shift into FB
* BUFFER 1 register.
*/
*pRPS++ = RPS_PAUSE | RPS_GPIO2; /* Wait for ADC done. */
/* Transfer ADC data from FB BUFFER 1 register to DMA buffer. */
*pRPS++ = RPS_STREG | (BUGFIX_STREG(P_FB_BUFFER1) >> 2);
*pRPS++ =
(uint32_t) devpriv->ANABuf.PhysicalBase +
(devpriv->AdcItems << 2);
/* If this slot's EndOfPollList flag is set, all channels have */
/* now been processed. */
if (*ppl++ & EOPL) {
devpriv->AdcItems++; /* Adjust poll list item count. */
break; /* Exit poll list processing loop. */
}
}
DEBUG("ResetADC: ADC items %d\n", devpriv->AdcItems);
/* VERSION 2.01 CHANGE: DELAY CHANGED FROM 250NS to 2US. Allow the
* ADC to stabilize for 2 microseconds before starting the final
* (dummy) conversion. This delay is necessary to allow sufficient
* time between last conversion finished and the start of the dummy
* conversion. Without this delay, the last conversion's data value
* is sometimes set to the previous conversion's data value.
*/
for (n = 0; n < (2 * RPSCLK_PER_US); n++)
*pRPS++ = RPS_NOP;
/* Start a dummy conversion to cause the data from the last
* conversion of interest to be shifted in.
*/
*pRPS++ = RPS_LDREG | (P_GPIO >> 2); /* Begin ADC Start pulse. */
*pRPS++ = GPIO_BASE | GPIO1_LO;
*pRPS++ = RPS_NOP;
/* VERSION 2.03 CHANGE: STRETCH OUT ADC START PULSE. */
*pRPS++ = RPS_LDREG | (P_GPIO >> 2); /* End ADC Start pulse. */
*pRPS++ = GPIO_BASE | GPIO1_HI;
/* Wait for the data from the last conversion of interest to arrive
* in FB BUFFER 1 register.
*/
*pRPS++ = RPS_PAUSE | RPS_GPIO2; /* Wait for ADC done. */
/* Transfer final ADC data from FB BUFFER 1 register to DMA buffer. */
*pRPS++ = RPS_STREG | (BUGFIX_STREG(P_FB_BUFFER1) >> 2); /* */
*pRPS++ =
(uint32_t) devpriv->ANABuf.PhysicalBase + (devpriv->AdcItems << 2);
/* Indicate ADC scan loop is finished. */
/* *pRPS++= RPS_CLRSIGNAL | RPS_SIGADC ; // Signal ReadADC() that scan is done. */
/* invoke interrupt */
if (devpriv->ai_cmd_running == 1) {
DEBUG("ResetADC: insert irq in ADC RPS task\n");
*pRPS++ = RPS_IRQ;
}
/* Restart RPS program at its beginning. */
*pRPS++ = RPS_JUMP; /* Branch to start of RPS program. */
*pRPS++ = (uint32_t) devpriv->RPSBuf.PhysicalBase;
/* End of RPS program build */
}
/* TO COMPLETE, IF NECESSARY */
static int s626_ai_insn_config(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
return -EINVAL;
}
/* static int s626_ai_rinsn(struct comedi_device *dev,struct comedi_subdevice *s,struct comedi_insn *insn,unsigned int *data) */
/* { */
/* register uint8_t i; */
/* register int32_t *readaddr; */
/* DEBUG("as626_ai_rinsn: ai_rinsn enter\n"); */
/* Trigger ADC scan loop start by setting RPS Signal 0. */
/* MC_ENABLE( P_MC2, MC2_ADC_RPS ); */
/* Wait until ADC scan loop is finished (RPS Signal 0 reset). */
/* while ( MC_TEST( P_MC2, MC2_ADC_RPS ) ); */
/* Init ptr to DMA buffer that holds new ADC data. We skip the
* first uint16_t in the buffer because it contains junk data from
* the final ADC of the previous poll list scan.
*/
/* readaddr = (uint32_t *)devpriv->ANABuf.LogicalBase + 1; */
/* Convert ADC data to 16-bit integer values and copy to application buffer. */
/* for ( i = 0; i < devpriv->AdcItems; i++ ) { */
/* *data = s626_ai_reg_to_uint( *readaddr++ ); */
/* DEBUG("s626_ai_rinsn: data %d\n",*data); */
/* data++; */
/* } */
/* DEBUG("s626_ai_rinsn: ai_rinsn escape\n"); */
/* return i; */
/* } */
static int s626_ai_insn_read(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
uint16_t chan = CR_CHAN(insn->chanspec);
uint16_t range = CR_RANGE(insn->chanspec);
uint16_t AdcSpec = 0;
uint32_t GpioImage;
int n;
/* interrupt call test */
/* writel(IRQ_GPIO3,devpriv->base_addr+P_PSR); */
/* Writing a logical 1 into any of the RPS_PSR bits causes the
* corresponding interrupt to be generated if enabled
*/
DEBUG("s626_ai_insn_read: entering\n");
/* Convert application's ADC specification into form
* appropriate for register programming.
*/
if (range == 0)
AdcSpec = (chan << 8) | (GSEL_BIPOLAR5V);
else
AdcSpec = (chan << 8) | (GSEL_BIPOLAR10V);
/* Switch ADC analog gain. */
DEBIwrite(dev, LP_GSEL, AdcSpec); /* Set gain. */
/* Select ADC analog input channel. */
DEBIwrite(dev, LP_ISEL, AdcSpec); /* Select channel. */
for (n = 0; n < insn->n; n++) {
/* Delay 10 microseconds for analog input settling. */
udelay(10);
/* Start ADC by pulsing GPIO1 low. */
GpioImage = RR7146(P_GPIO);
/* Assert ADC Start command */
WR7146(P_GPIO, GpioImage & ~GPIO1_HI);
/* and stretch it out. */
WR7146(P_GPIO, GpioImage & ~GPIO1_HI);
WR7146(P_GPIO, GpioImage & ~GPIO1_HI);
/* Negate ADC Start command. */
WR7146(P_GPIO, GpioImage | GPIO1_HI);
/* Wait for ADC to complete (GPIO2 is asserted high when */
/* ADC not busy) and for data from previous conversion to */
/* shift into FB BUFFER 1 register. */
/* Wait for ADC done. */
while (!(RR7146(P_PSR) & PSR_GPIO2))
;
/* Fetch ADC data. */
if (n != 0)
data[n - 1] = s626_ai_reg_to_uint(RR7146(P_FB_BUFFER1));
/* Allow the ADC to stabilize for 4 microseconds before
* starting the next (final) conversion. This delay is
* necessary to allow sufficient time between last
* conversion finished and the start of the next
* conversion. Without this delay, the last conversion's
* data value is sometimes set to the previous
* conversion's data value.
*/
udelay(4);
}
/* Start a dummy conversion to cause the data from the
* previous conversion to be shifted in. */
GpioImage = RR7146(P_GPIO);
/* Assert ADC Start command */
WR7146(P_GPIO, GpioImage & ~GPIO1_HI);
/* and stretch it out. */
WR7146(P_GPIO, GpioImage & ~GPIO1_HI);
WR7146(P_GPIO, GpioImage & ~GPIO1_HI);
/* Negate ADC Start command. */
WR7146(P_GPIO, GpioImage | GPIO1_HI);
/* Wait for the data to arrive in FB BUFFER 1 register. */
/* Wait for ADC done. */
while (!(RR7146(P_PSR) & PSR_GPIO2))
;
/* Fetch ADC data from audio interface's input shift register. */
/* Fetch ADC data. */
if (n != 0)
data[n - 1] = s626_ai_reg_to_uint(RR7146(P_FB_BUFFER1));
DEBUG("s626_ai_insn_read: samples %d, data %d\n", n, data[n - 1]);
return n;
}
static int s626_ai_load_polllist(uint8_t *ppl, struct comedi_cmd *cmd)
{
int n;
for (n = 0; n < cmd->chanlist_len; n++) {
if (CR_RANGE((cmd->chanlist)[n]) == 0)
ppl[n] = (CR_CHAN((cmd->chanlist)[n])) | (RANGE_5V);
else
ppl[n] = (CR_CHAN((cmd->chanlist)[n])) | (RANGE_10V);
}
if (n != 0)
ppl[n - 1] |= EOPL;
return n;
}
static int s626_ai_inttrig(struct comedi_device *dev,
struct comedi_subdevice *s, unsigned int trignum)
{
if (trignum != 0)
return -EINVAL;
DEBUG("s626_ai_inttrig: trigger adc start...");
/* Start executing the RPS program. */
MC_ENABLE(P_MC1, MC1_ERPS1);
s->async->inttrig = NULL;
DEBUG(" done\n");
return 1;
}
/* TO COMPLETE */
static int s626_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
{
uint8_t ppl[16];
struct comedi_cmd *cmd = &s->async->cmd;
struct enc_private *k;
int tick;
DEBUG("s626_ai_cmd: entering command function\n");
if (devpriv->ai_cmd_running) {
printk(KERN_ERR "s626_ai_cmd: Another ai_cmd is running %d\n",
dev->minor);
return -EBUSY;
}
/* disable interrupt */
writel(0, devpriv->base_addr + P_IER);
/* clear interrupt request */
writel(IRQ_RPS1 | IRQ_GPIO3, devpriv->base_addr + P_ISR);
/* clear any pending interrupt */
s626_dio_clear_irq(dev);
/* s626_enc_clear_irq(dev); */
/* reset ai_cmd_running flag */
devpriv->ai_cmd_running = 0;
/* test if cmd is valid */
if (cmd == NULL) {
DEBUG("s626_ai_cmd: NULL command\n");
return -EINVAL;
} else {
DEBUG("s626_ai_cmd: command received!!!\n");
}
if (dev->irq == 0) {
comedi_error(dev,
"s626_ai_cmd: cannot run command without an irq");
return -EIO;
}
s626_ai_load_polllist(ppl, cmd);
devpriv->ai_cmd_running = 1;
devpriv->ai_convert_count = 0;
switch (cmd->scan_begin_src) {
case TRIG_FOLLOW:
break;
case TRIG_TIMER:
/* set a conter to generate adc trigger at scan_begin_arg interval */
k = &encpriv[5];
tick = s626_ns_to_timer((int *)&cmd->scan_begin_arg,
cmd->flags & TRIG_ROUND_MASK);
/* load timer value and enable interrupt */
s626_timer_load(dev, k, tick);
k->SetEnable(dev, k, CLKENAB_ALWAYS);
DEBUG("s626_ai_cmd: scan trigger timer is set with value %d\n",
tick);
break;
case TRIG_EXT:
/* set the digital line and interrupt for scan trigger */
if (cmd->start_src != TRIG_EXT)
s626_dio_set_irq(dev, cmd->scan_begin_arg);
DEBUG("s626_ai_cmd: External scan trigger is set!!!\n");
break;
}
switch (cmd->convert_src) {
case TRIG_NOW:
break;
case TRIG_TIMER:
/* set a conter to generate adc trigger at convert_arg interval */
k = &encpriv[4];
tick = s626_ns_to_timer((int *)&cmd->convert_arg,
cmd->flags & TRIG_ROUND_MASK);
/* load timer value and enable interrupt */
s626_timer_load(dev, k, tick);
k->SetEnable(dev, k, CLKENAB_INDEX);
DEBUG
("s626_ai_cmd: convert trigger timer is set with value %d\n",
tick);
break;
case TRIG_EXT:
/* set the digital line and interrupt for convert trigger */
if (cmd->scan_begin_src != TRIG_EXT
&& cmd->start_src == TRIG_EXT)
s626_dio_set_irq(dev, cmd->convert_arg);
DEBUG("s626_ai_cmd: External convert trigger is set!!!\n");
break;
}
switch (cmd->stop_src) {
case TRIG_COUNT:
/* data arrives as one packet */
devpriv->ai_sample_count = cmd->stop_arg;
devpriv->ai_continous = 0;
break;
case TRIG_NONE:
/* continous acquisition */
devpriv->ai_continous = 1;
devpriv->ai_sample_count = 1;
break;
}
ResetADC(dev, ppl);
switch (cmd->start_src) {
case TRIG_NOW:
/* Trigger ADC scan loop start by setting RPS Signal 0. */
/* MC_ENABLE( P_MC2, MC2_ADC_RPS ); */
/* Start executing the RPS program. */
MC_ENABLE(P_MC1, MC1_ERPS1);
DEBUG("s626_ai_cmd: ADC triggered\n");
s->async->inttrig = NULL;
break;
case TRIG_EXT:
/* configure DIO channel for acquisition trigger */
s626_dio_set_irq(dev, cmd->start_arg);
DEBUG("s626_ai_cmd: External start trigger is set!!!\n");
s->async->inttrig = NULL;
break;
case TRIG_INT:
s->async->inttrig = s626_ai_inttrig;
break;
}
/* enable interrupt */
writel(IRQ_GPIO3 | IRQ_RPS1, devpriv->base_addr + P_IER);
DEBUG("s626_ai_cmd: command function terminated\n");
return 0;
}
static int s626_ai_cmdtest(struct comedi_device *dev,
struct comedi_subdevice *s, struct comedi_cmd *cmd)
{
int err = 0;
int tmp;
/* cmdtest tests a particular command to see if it is valid. Using
* the cmdtest ioctl, a user can create a valid cmd and then have it
* executes by the cmd ioctl.
*
* cmdtest returns 1,2,3,4 or 0, depending on which tests the
* command passes. */
/* step 1: make sure trigger sources are trivially valid */
tmp = cmd->start_src;
cmd->start_src &= TRIG_NOW | TRIG_INT | TRIG_EXT;
if (!cmd->start_src || tmp != cmd->start_src)
err++;
tmp = cmd->scan_begin_src;
cmd->scan_begin_src &= TRIG_TIMER | TRIG_EXT | TRIG_FOLLOW;
if (!cmd->scan_begin_src || tmp != cmd->scan_begin_src)
err++;
tmp = cmd->convert_src;
cmd->convert_src &= TRIG_TIMER | TRIG_EXT | TRIG_NOW;
if (!cmd->convert_src || tmp != cmd->convert_src)
err++;
tmp = cmd->scan_end_src;
cmd->scan_end_src &= TRIG_COUNT;
if (!cmd->scan_end_src || tmp != cmd->scan_end_src)
err++;
tmp = cmd->stop_src;
cmd->stop_src &= TRIG_COUNT | TRIG_NONE;
if (!cmd->stop_src || tmp != cmd->stop_src)
err++;
if (err)
return 1;
/* step 2: make sure trigger sources are unique and mutually
compatible */
/* note that mutual compatibility is not an issue here */
if (cmd->scan_begin_src != TRIG_TIMER &&
cmd->scan_begin_src != TRIG_EXT
&& cmd->scan_begin_src != TRIG_FOLLOW)
err++;
if (cmd->convert_src != TRIG_TIMER &&
cmd->convert_src != TRIG_EXT && cmd->convert_src != TRIG_NOW)
err++;
if (cmd->stop_src != TRIG_COUNT && cmd->stop_src != TRIG_NONE)
err++;
if (err)
return 2;
/* step 3: make sure arguments are trivially compatible */
if (cmd->start_src != TRIG_EXT && cmd->start_arg != 0) {
cmd->start_arg = 0;
err++;
}
if (cmd->start_src == TRIG_EXT && cmd->start_arg > 39) {
cmd->start_arg = 39;
err++;
}
if (cmd->scan_begin_src == TRIG_EXT && cmd->scan_begin_arg > 39) {
cmd->scan_begin_arg = 39;
err++;
}
if (cmd->convert_src == TRIG_EXT && cmd->convert_arg > 39) {
cmd->convert_arg = 39;
err++;
}
#define MAX_SPEED 200000 /* in nanoseconds */
#define MIN_SPEED 2000000000 /* in nanoseconds */
if (cmd->scan_begin_src == TRIG_TIMER) {
if (cmd->scan_begin_arg < MAX_SPEED) {
cmd->scan_begin_arg = MAX_SPEED;
err++;
}
if (cmd->scan_begin_arg > MIN_SPEED) {
cmd->scan_begin_arg = MIN_SPEED;
err++;
}
} else {
/* external trigger */
/* should be level/edge, hi/lo specification here */
/* should specify multiple external triggers */
/* if(cmd->scan_begin_arg>9){ */
/* cmd->scan_begin_arg=9; */
/* err++; */
/* } */
}
if (cmd->convert_src == TRIG_TIMER) {
if (cmd->convert_arg < MAX_SPEED) {
cmd->convert_arg = MAX_SPEED;
err++;
}
if (cmd->convert_arg > MIN_SPEED) {
cmd->convert_arg = MIN_SPEED;
err++;
}
} else {
/* external trigger */
/* see above */
/* if(cmd->convert_arg>9){ */
/* cmd->convert_arg=9; */
/* err++; */
/* } */
}
if (cmd->scan_end_arg != cmd->chanlist_len) {
cmd->scan_end_arg = cmd->chanlist_len;
err++;
}
if (cmd->stop_src == TRIG_COUNT) {
if (cmd->stop_arg > 0x00ffffff) {
cmd->stop_arg = 0x00ffffff;
err++;
}
} else {
/* TRIG_NONE */
if (cmd->stop_arg != 0) {
cmd->stop_arg = 0;
err++;
}
}
if (err)
return 3;
/* step 4: fix up any arguments */
if (cmd->scan_begin_src == TRIG_TIMER) {
tmp = cmd->scan_begin_arg;
s626_ns_to_timer((int *)&cmd->scan_begin_arg,
cmd->flags & TRIG_ROUND_MASK);
if (tmp != cmd->scan_begin_arg)
err++;
}
if (cmd->convert_src == TRIG_TIMER) {
tmp = cmd->convert_arg;
s626_ns_to_timer((int *)&cmd->convert_arg,
cmd->flags & TRIG_ROUND_MASK);
if (tmp != cmd->convert_arg)
err++;
if (cmd->scan_begin_src == TRIG_TIMER &&
cmd->scan_begin_arg <
cmd->convert_arg * cmd->scan_end_arg) {
cmd->scan_begin_arg =
cmd->convert_arg * cmd->scan_end_arg;
err++;
}
}
if (err)
return 4;
return 0;
}
static int s626_ai_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
{
/* Stop RPS program in case it is currently running. */
MC_DISABLE(P_MC1, MC1_ERPS1);
/* disable master interrupt */
writel(0, devpriv->base_addr + P_IER);
devpriv->ai_cmd_running = 0;
return 0;
}
/* This function doesn't require a particular form, this is just what
* happens to be used in some of the drivers. It should convert ns
* nanoseconds to a counter value suitable for programming the device.
* Also, it should adjust ns so that it cooresponds to the actual time
* that the device will use. */
static int s626_ns_to_timer(int *nanosec, int round_mode)
{
int divider, base;
base = 500; /* 2MHz internal clock */
switch (round_mode) {
case TRIG_ROUND_NEAREST:
default:
divider = (*nanosec + base / 2) / base;
break;
case TRIG_ROUND_DOWN:
divider = (*nanosec) / base;
break;
case TRIG_ROUND_UP:
divider = (*nanosec + base - 1) / base;
break;
}
*nanosec = base * divider;
return divider - 1;
}
static int s626_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int i;
uint16_t chan = CR_CHAN(insn->chanspec);
int16_t dacdata;
for (i = 0; i < insn->n; i++) {
dacdata = (int16_t) data[i];
devpriv->ao_readback[CR_CHAN(insn->chanspec)] = data[i];
dacdata -= (0x1fff);
SetDAC(dev, chan, dacdata);
}
return i;
}
static int s626_ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int i;
for (i = 0; i < insn->n; i++)
data[i] = devpriv->ao_readback[CR_CHAN(insn->chanspec)];
return i;
}
/* *************** DIGITAL I/O FUNCTIONS ***************
* All DIO functions address a group of DIO channels by means of
* "group" argument. group may be 0, 1 or 2, which correspond to DIO
* ports A, B and C, respectively.
*/
static void s626_dio_init(struct comedi_device *dev)
{
uint16_t group;
struct comedi_subdevice *s;
/* Prepare to treat writes to WRCapSel as capture disables. */
DEBIwrite(dev, LP_MISC1, MISC1_NOEDCAP);
/* For each group of sixteen channels ... */
for (group = 0; group < S626_DIO_BANKS; group++) {
s = dev->subdevices + 2 + group;
DEBIwrite(dev, diopriv->WRIntSel, 0); /* Disable all interrupts. */
DEBIwrite(dev, diopriv->WRCapSel, 0xFFFF); /* Disable all event */
/* captures. */
DEBIwrite(dev, diopriv->WREdgSel, 0); /* Init all DIOs to */
/* default edge */
/* polarity. */
DEBIwrite(dev, diopriv->WRDOut, 0); /* Program all outputs */
/* to inactive state. */
}
DEBUG("s626_dio_init: DIO initialized\n");
}
/* DIO devices are slightly special. Although it is possible to
* implement the insn_read/insn_write interface, it is much more
* useful to applications if you implement the insn_bits interface.
* This allows packed reading/writing of the DIO channels. The comedi
* core can convert between insn_bits and insn_read/write */
static int s626_dio_insn_bits(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
/* Length of data must be 2 (mask and new data, see below) */
if (insn->n == 0)
return 0;
if (insn->n != 2) {
printk
("comedi%d: s626: s626_dio_insn_bits(): Invalid instruction length\n",
dev->minor);
return -EINVAL;
}
/*
* The insn data consists of a mask in data[0] and the new data in
* data[1]. The mask defines which bits we are concerning about.
* The new data must be anded with the mask. Each channel
* corresponds to a bit.
*/
if (data[0]) {
/* Check if requested ports are configured for output */
if ((s->io_bits & data[0]) != data[0])
return -EIO;
s->state &= ~data[0];
s->state |= data[0] & data[1];
/* Write out the new digital output lines */
DEBIwrite(dev, diopriv->WRDOut, s->state);
}
data[1] = DEBIread(dev, diopriv->RDDIn);
return 2;
}
static int s626_dio_insn_config(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
switch (data[0]) {
case INSN_CONFIG_DIO_QUERY:
data[1] =
(s->
io_bits & (1 << CR_CHAN(insn->chanspec))) ? COMEDI_OUTPUT :
COMEDI_INPUT;
return insn->n;
break;
case COMEDI_INPUT:
s->io_bits &= ~(1 << CR_CHAN(insn->chanspec));
break;
case COMEDI_OUTPUT:
s->io_bits |= 1 << CR_CHAN(insn->chanspec);
break;
default:
return -EINVAL;
break;
}
DEBIwrite(dev, diopriv->WRDOut, s->io_bits);
return 1;
}
static int s626_dio_set_irq(struct comedi_device *dev, unsigned int chan)
{
unsigned int group;
unsigned int bitmask;
unsigned int status;
/* select dio bank */
group = chan / 16;
bitmask = 1 << (chan - (16 * group));
DEBUG("s626_dio_set_irq: enable interrupt on dio channel %d group %d\n",
chan - (16 * group), group);
/* set channel to capture positive edge */
status = DEBIread(dev,
((struct dio_private *)(dev->subdevices + 2 +
group)->private)->RDEdgSel);
DEBIwrite(dev,
((struct dio_private *)(dev->subdevices + 2 +
group)->private)->WREdgSel,
bitmask | status);
/* enable interrupt on selected channel */
status = DEBIread(dev,
((struct dio_private *)(dev->subdevices + 2 +
group)->private)->RDIntSel);
DEBIwrite(dev,
((struct dio_private *)(dev->subdevices + 2 +
group)->private)->WRIntSel,
bitmask | status);
/* enable edge capture write command */
DEBIwrite(dev, LP_MISC1, MISC1_EDCAP);
/* enable edge capture on selected channel */
status = DEBIread(dev,
((struct dio_private *)(dev->subdevices + 2 +
group)->private)->RDCapSel);
DEBIwrite(dev,
((struct dio_private *)(dev->subdevices + 2 +
group)->private)->WRCapSel,
bitmask | status);
return 0;
}
static int s626_dio_reset_irq(struct comedi_device *dev, unsigned int group,
unsigned int mask)
{
DEBUG
("s626_dio_reset_irq: disable interrupt on dio channel %d group %d\n",
mask, group);
/* disable edge capture write command */
DEBIwrite(dev, LP_MISC1, MISC1_NOEDCAP);
/* enable edge capture on selected channel */
DEBIwrite(dev,
((struct dio_private *)(dev->subdevices + 2 +
group)->private)->WRCapSel, mask);
return 0;
}
static int s626_dio_clear_irq(struct comedi_device *dev)
{
unsigned int group;
/* disable edge capture write command */
DEBIwrite(dev, LP_MISC1, MISC1_NOEDCAP);
for (group = 0; group < S626_DIO_BANKS; group++) {
/* clear pending events and interrupt */
DEBIwrite(dev,
((struct dio_private *)(dev->subdevices + 2 +
group)->private)->WRCapSel,
0xffff);
}
return 0;
}
/* Now this function initializes the value of the counter (data[0])
and set the subdevice. To complete with trigger and interrupt
configuration */
static int s626_enc_insn_config(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
uint16_t Setup = (LOADSRC_INDX << BF_LOADSRC) | /* Preload upon */
/* index. */
(INDXSRC_SOFT << BF_INDXSRC) | /* Disable hardware index. */
(CLKSRC_COUNTER << BF_CLKSRC) | /* Operating mode is Counter. */
(CLKPOL_POS << BF_CLKPOL) | /* Active high clock. */
/* ( CNTDIR_UP << BF_CLKPOL ) | // Count direction is Down. */
(CLKMULT_1X << BF_CLKMULT) | /* Clock multiplier is 1x. */
(CLKENAB_INDEX << BF_CLKENAB);
/* uint16_t DisableIntSrc=TRUE; */
/* uint32_t Preloadvalue; //Counter initial value */
uint16_t valueSrclatch = LATCHSRC_AB_READ;
uint16_t enab = CLKENAB_ALWAYS;
struct enc_private *k = &encpriv[CR_CHAN(insn->chanspec)];
DEBUG("s626_enc_insn_config: encoder config\n");
/* (data==NULL) ? (Preloadvalue=0) : (Preloadvalue=data[0]); */
k->SetMode(dev, k, Setup, TRUE);
Preload(dev, k, data[0]);
k->PulseIndex(dev, k);
SetLatchSource(dev, k, valueSrclatch);
k->SetEnable(dev, k, (uint16_t) (enab != 0));
return insn->n;
}
static int s626_enc_insn_read(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int n;
struct enc_private *k = &encpriv[CR_CHAN(insn->chanspec)];
DEBUG("s626_enc_insn_read: encoder read channel %d\n",
CR_CHAN(insn->chanspec));
for (n = 0; n < insn->n; n++)
data[n] = ReadLatch(dev, k);
DEBUG("s626_enc_insn_read: encoder sample %d\n", data[n]);
return n;
}
static int s626_enc_insn_write(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
struct enc_private *k = &encpriv[CR_CHAN(insn->chanspec)];
DEBUG("s626_enc_insn_write: encoder write channel %d\n",
CR_CHAN(insn->chanspec));
/* Set the preload register */
Preload(dev, k, data[0]);
/* Software index pulse forces the preload register to load */
/* into the counter */
k->SetLoadTrig(dev, k, 0);
k->PulseIndex(dev, k);
k->SetLoadTrig(dev, k, 2);
DEBUG("s626_enc_insn_write: End encoder write\n");
return 1;
}
static void s626_timer_load(struct comedi_device *dev, struct enc_private *k,
int tick)
{
uint16_t Setup = (LOADSRC_INDX << BF_LOADSRC) | /* Preload upon */
/* index. */
(INDXSRC_SOFT << BF_INDXSRC) | /* Disable hardware index. */
(CLKSRC_TIMER << BF_CLKSRC) | /* Operating mode is Timer. */
(CLKPOL_POS << BF_CLKPOL) | /* Active high clock. */
(CNTDIR_DOWN << BF_CLKPOL) | /* Count direction is Down. */
(CLKMULT_1X << BF_CLKMULT) | /* Clock multiplier is 1x. */
(CLKENAB_INDEX << BF_CLKENAB);
uint16_t valueSrclatch = LATCHSRC_A_INDXA;
/* uint16_t enab=CLKENAB_ALWAYS; */
k->SetMode(dev, k, Setup, FALSE);
/* Set the preload register */
Preload(dev, k, tick);
/* Software index pulse forces the preload register to load */
/* into the counter */
k->SetLoadTrig(dev, k, 0);
k->PulseIndex(dev, k);
/* set reload on counter overflow */
k->SetLoadTrig(dev, k, 1);
/* set interrupt on overflow */
k->SetIntSrc(dev, k, INTSRC_OVER);
SetLatchSource(dev, k, valueSrclatch);
/* k->SetEnable(dev,k,(uint16_t)(enab != 0)); */
}
/* *********** DAC FUNCTIONS *********** */
/* Slot 0 base settings. */
#define VECT0 (XSD2 | RSD3 | SIB_A2)
/* Slot 0 always shifts in 0xFF and store it to FB_BUFFER2. */
/* TrimDac LogicalChan-to-PhysicalChan mapping table. */
static uint8_t trimchan[] = { 10, 9, 8, 3, 2, 7, 6, 1, 0, 5, 4 };
/* TrimDac LogicalChan-to-EepromAdrs mapping table. */
static uint8_t trimadrs[] = { 0x40, 0x41, 0x42, 0x50, 0x51, 0x52, 0x53, 0x60, 0x61, 0x62, 0x63 };
static void LoadTrimDACs(struct comedi_device *dev)
{
register uint8_t i;
/* Copy TrimDac setpoint values from EEPROM to TrimDacs. */
for (i = 0; i < ARRAY_SIZE(trimchan); i++)
WriteTrimDAC(dev, i, I2Cread(dev, trimadrs[i]));
}
static void WriteTrimDAC(struct comedi_device *dev, uint8_t LogicalChan,
uint8_t DacData)
{
uint32_t chan;
/* Save the new setpoint in case the application needs to read it back later. */
devpriv->TrimSetpoint[LogicalChan] = (uint8_t) DacData;
/* Map logical channel number to physical channel number. */
chan = (uint32_t) trimchan[LogicalChan];
/* Set up TSL2 records for TrimDac write operation. All slots shift
* 0xFF in from pulled-up SD3 so that the end of the slot sequence
* can be detected.
*/
SETVECT(2, XSD2 | XFIFO_1 | WS3);
/* Slot 2: Send high uint8_t to target TrimDac. */
SETVECT(3, XSD2 | XFIFO_0 | WS3);
/* Slot 3: Send low uint8_t to target TrimDac. */
SETVECT(4, XSD2 | XFIFO_3 | WS1);
/* Slot 4: Send NOP high uint8_t to DAC0 to keep clock running. */
SETVECT(5, XSD2 | XFIFO_2 | WS1 | EOS);
/* Slot 5: Send NOP low uint8_t to DAC0. */
/* Construct and transmit target DAC's serial packet:
* ( 0000 AAAA ), ( DDDD DDDD ),( 0x00 ),( 0x00 ) where A<3:0> is the
* DAC channel's address, and D<7:0> is the DAC setpoint. Append a
* WORD value (that writes a channel 0 NOP command to a non-existent
* main DAC channel) that serves to keep the clock running after the
* packet has been sent to the target DAC.
*/
/* Address the DAC channel within the trimdac device. */
SendDAC(dev, ((uint32_t) chan << 8)
| (uint32_t) DacData); /* Include DAC setpoint data. */
}
/* ************** EEPROM ACCESS FUNCTIONS ************** */
/* Read uint8_t from EEPROM. */
static uint8_t I2Cread(struct comedi_device *dev, uint8_t addr)
{
uint8_t rtnval;
/* Send EEPROM target address. */
if (I2Chandshake(dev, I2C_B2(I2C_ATTRSTART, I2CW)
/* Byte2 = I2C command: write to I2C EEPROM device. */
| I2C_B1(I2C_ATTRSTOP, addr)
/* Byte1 = EEPROM internal target address. */
| I2C_B0(I2C_ATTRNOP, 0))) { /* Byte0 = Not sent. */
/* Abort function and declare error if handshake failed. */
DEBUG("I2Cread: error handshake I2Cread a\n");
return 0;
}
/* Execute EEPROM read. */
if (I2Chandshake(dev, I2C_B2(I2C_ATTRSTART, I2CR)
/* Byte2 = I2C */
/* command: read */
/* from I2C EEPROM */
/* device. */
|I2C_B1(I2C_ATTRSTOP, 0)
/* Byte1 receives */
/* uint8_t from */
/* EEPROM. */
|I2C_B0(I2C_ATTRNOP, 0))) { /* Byte0 = Not sent. */
/* Abort function and declare error if handshake failed. */
DEBUG("I2Cread: error handshake I2Cread b\n");
return 0;
}
/* Return copy of EEPROM value. */
rtnval = (uint8_t) (RR7146(P_I2CCTRL) >> 16);
return rtnval;
}
static uint32_t I2Chandshake(struct comedi_device *dev, uint32_t val)
{
/* Write I2C command to I2C Transfer Control shadow register. */
WR7146(P_I2CCTRL, val);
/* Upload I2C shadow registers into working registers and wait for */
/* upload confirmation. */
MC_ENABLE(P_MC2, MC2_UPLD_IIC);
while (!MC_TEST(P_MC2, MC2_UPLD_IIC))
;
/* Wait until I2C bus transfer is finished or an error occurs. */
while ((RR7146(P_I2CCTRL) & (I2C_BUSY | I2C_ERR)) == I2C_BUSY)
;
/* Return non-zero if I2C error occurred. */
return RR7146(P_I2CCTRL) & I2C_ERR;
}
/* Private helper function: Write setpoint to an application DAC channel. */
static void SetDAC(struct comedi_device *dev, uint16_t chan, short dacdata)
{
register uint16_t signmask;
register uint32_t WSImage;
/* Adjust DAC data polarity and set up Polarity Control Register */
/* image. */
signmask = 1 << chan;
if (dacdata < 0) {
dacdata = -dacdata;
devpriv->Dacpol |= signmask;
} else
devpriv->Dacpol &= ~signmask;
/* Limit DAC setpoint value to valid range. */
if ((uint16_t) dacdata > 0x1FFF)
dacdata = 0x1FFF;
/* Set up TSL2 records (aka "vectors") for DAC update. Vectors V2
* and V3 transmit the setpoint to the target DAC. V4 and V5 send
* data to a non-existent TrimDac channel just to keep the clock
* running after sending data to the target DAC. This is necessary
* to eliminate the clock glitch that would otherwise occur at the
* end of the target DAC's serial data stream. When the sequence
* restarts at V0 (after executing V5), the gate array automatically
* disables gating for the DAC clock and all DAC chip selects.
*/
WSImage = (chan & 2) ? WS1 : WS2;
/* Choose DAC chip select to be asserted. */
SETVECT(2, XSD2 | XFIFO_1 | WSImage);
/* Slot 2: Transmit high data byte to target DAC. */
SETVECT(3, XSD2 | XFIFO_0 | WSImage);
/* Slot 3: Transmit low data byte to target DAC. */
SETVECT(4, XSD2 | XFIFO_3 | WS3);
/* Slot 4: Transmit to non-existent TrimDac channel to keep clock */
SETVECT(5, XSD2 | XFIFO_2 | WS3 | EOS);
/* Slot 5: running after writing target DAC's low data byte. */
/* Construct and transmit target DAC's serial packet:
* ( A10D DDDD ),( DDDD DDDD ),( 0x0F ),( 0x00 ) where A is chan<0>,
* and D<12:0> is the DAC setpoint. Append a WORD value (that writes
* to a non-existent TrimDac channel) that serves to keep the clock
* running after the packet has been sent to the target DAC.
*/
SendDAC(dev, 0x0F000000
/* Continue clock after target DAC data (write to non-existent trimdac). */
| 0x00004000
/* Address the two main dual-DAC devices (TSL's chip select enables
* target device). */
| ((uint32_t) (chan & 1) << 15)
/* Address the DAC channel within the device. */
| (uint32_t) dacdata); /* Include DAC setpoint data. */
}
/* Private helper function: Transmit serial data to DAC via Audio
* channel 2. Assumes: (1) TSL2 slot records initialized, and (2)
* Dacpol contains valid target image.
*/
static void SendDAC(struct comedi_device *dev, uint32_t val)
{
/* START THE SERIAL CLOCK RUNNING ------------- */
/* Assert DAC polarity control and enable gating of DAC serial clock
* and audio bit stream signals. At this point in time we must be
* assured of being in time slot 0. If we are not in slot 0, the
* serial clock and audio stream signals will be disabled; this is
* because the following DEBIwrite statement (which enables signals
* to be passed through the gate array) would execute before the
* trailing edge of WS1/WS3 (which turns off the signals), thus
* causing the signals to be inactive during the DAC write.
*/
DEBIwrite(dev, LP_DACPOL, devpriv->Dacpol);
/* TRANSFER OUTPUT DWORD VALUE INTO A2'S OUTPUT FIFO ---------------- */
/* Copy DAC setpoint value to DAC's output DMA buffer. */
/* WR7146( (uint32_t)devpriv->pDacWBuf, val ); */
*devpriv->pDacWBuf = val;
/* enab the output DMA transfer. This will cause the DMAC to copy
* the DAC's data value to A2's output FIFO. The DMA transfer will
* then immediately terminate because the protection address is
* reached upon transfer of the first DWORD value.
*/
MC_ENABLE(P_MC1, MC1_A2OUT);
/* While the DMA transfer is executing ... */
/* Reset Audio2 output FIFO's underflow flag (along with any other
* FIFO underflow/overflow flags). When set, this flag will
* indicate that we have emerged from slot 0.
*/
WR7146(P_ISR, ISR_AFOU);
/* Wait for the DMA transfer to finish so that there will be data
* available in the FIFO when time slot 1 tries to transfer a DWORD
* from the FIFO to the output buffer register. We test for DMA
* Done by polling the DMAC enable flag; this flag is automatically
* cleared when the transfer has finished.
*/
while ((RR7146(P_MC1) & MC1_A2OUT) != 0)
;
/* START THE OUTPUT STREAM TO THE TARGET DAC -------------------- */
/* FIFO data is now available, so we enable execution of time slots
* 1 and higher by clearing the EOS flag in slot 0. Note that SD3
* will be shifted in and stored in FB_BUFFER2 for end-of-slot-list
* detection.
*/
SETVECT(0, XSD2 | RSD3 | SIB_A2);
/* Wait for slot 1 to execute to ensure that the Packet will be
* transmitted. This is detected by polling the Audio2 output FIFO
* underflow flag, which will be set when slot 1 execution has
* finished transferring the DAC's data DWORD from the output FIFO
* to the output buffer register.
*/
while ((RR7146(P_SSR) & SSR_AF2_OUT) == 0)
;
/* Set up to trap execution at slot 0 when the TSL sequencer cycles
* back to slot 0 after executing the EOS in slot 5. Also,
* simultaneously shift out and in the 0x00 that is ALWAYS the value
* stored in the last byte to be shifted out of the FIFO's DWORD
* buffer register.
*/
SETVECT(0, XSD2 | XFIFO_2 | RSD2 | SIB_A2 | EOS);
/* WAIT FOR THE TRANSACTION TO FINISH ----------------------- */
/* Wait for the TSL to finish executing all time slots before
* exiting this function. We must do this so that the next DAC
* write doesn't start, thereby enabling clock/chip select signals:
*
* 1. Before the TSL sequence cycles back to slot 0, which disables
* the clock/cs signal gating and traps slot // list execution.
* we have not yet finished slot 5 then the clock/cs signals are
* still gated and we have not finished transmitting the stream.
*
* 2. While slots 2-5 are executing due to a late slot 0 trap. In
* this case, the slot sequence is currently repeating, but with
* clock/cs signals disabled. We must wait for slot 0 to trap
* execution before setting up the next DAC setpoint DMA transfer
* and enabling the clock/cs signals. To detect the end of slot 5,
* we test for the FB_BUFFER2 MSB contents to be equal to 0xFF. If
* the TSL has not yet finished executing slot 5 ...
*/
if ((RR7146(P_FB_BUFFER2) & 0xFF000000) != 0) {
/* The trap was set on time and we are still executing somewhere
* in slots 2-5, so we now wait for slot 0 to execute and trap
* TSL execution. This is detected when FB_BUFFER2 MSB changes
* from 0xFF to 0x00, which slot 0 causes to happen by shifting
* out/in on SD2 the 0x00 that is always referenced by slot 5.
*/
while ((RR7146(P_FB_BUFFER2) & 0xFF000000) != 0)
;
}
/* Either (1) we were too late setting the slot 0 trap; the TSL
* sequencer restarted slot 0 before we could set the EOS trap flag,
* or (2) we were not late and execution is now trapped at slot 0.
* In either case, we must now change slot 0 so that it will store
* value 0xFF (instead of 0x00) to FB_BUFFER2 next time it executes.
* In order to do this, we reprogram slot 0 so that it will shift in
* SD3, which is driven only by a pull-up resistor.
*/
SETVECT(0, RSD3 | SIB_A2 | EOS);
/* Wait for slot 0 to execute, at which time the TSL is setup for
* the next DAC write. This is detected when FB_BUFFER2 MSB changes
* from 0x00 to 0xFF.
*/
while ((RR7146(P_FB_BUFFER2) & 0xFF000000) == 0)
;
}
static void WriteMISC2(struct comedi_device *dev, uint16_t NewImage)
{
DEBIwrite(dev, LP_MISC1, MISC1_WENABLE); /* enab writes to */
/* MISC2 register. */
DEBIwrite(dev, LP_WRMISC2, NewImage); /* Write new image to MISC2. */
DEBIwrite(dev, LP_MISC1, MISC1_WDISABLE); /* Disable writes to MISC2. */
}
/* Initialize the DEBI interface for all transfers. */
static uint16_t DEBIread(struct comedi_device *dev, uint16_t addr)
{
uint16_t retval;
/* Set up DEBI control register value in shadow RAM. */
WR7146(P_DEBICMD, DEBI_CMD_RDWORD | addr);
/* Execute the DEBI transfer. */
DEBItransfer(dev);
/* Fetch target register value. */
retval = (uint16_t) RR7146(P_DEBIAD);
/* Return register value. */
return retval;
}
/* Execute a DEBI transfer. This must be called from within a */
/* critical section. */
static void DEBItransfer(struct comedi_device *dev)
{
/* Initiate upload of shadow RAM to DEBI control register. */
MC_ENABLE(P_MC2, MC2_UPLD_DEBI);
/* Wait for completion of upload from shadow RAM to DEBI control */
/* register. */
while (!MC_TEST(P_MC2, MC2_UPLD_DEBI))
;
/* Wait until DEBI transfer is done. */
while (RR7146(P_PSR) & PSR_DEBI_S)
;
}
/* Write a value to a gate array register. */
static void DEBIwrite(struct comedi_device *dev, uint16_t addr, uint16_t wdata)
{
/* Set up DEBI control register value in shadow RAM. */
WR7146(P_DEBICMD, DEBI_CMD_WRWORD | addr);
WR7146(P_DEBIAD, wdata);
/* Execute the DEBI transfer. */
DEBItransfer(dev);
}
/* Replace the specified bits in a gate array register. Imports: mask
* specifies bits that are to be preserved, wdata is new value to be
* or'd with the masked original.
*/
static void DEBIreplace(struct comedi_device *dev, uint16_t addr, uint16_t mask,
uint16_t wdata)
{
/* Copy target gate array register into P_DEBIAD register. */
WR7146(P_DEBICMD, DEBI_CMD_RDWORD | addr);
/* Set up DEBI control reg value in shadow RAM. */
DEBItransfer(dev); /* Execute the DEBI Read transfer. */
/* Write back the modified image. */
WR7146(P_DEBICMD, DEBI_CMD_WRWORD | addr);
/* Set up DEBI control reg value in shadow RAM. */
WR7146(P_DEBIAD, wdata | ((uint16_t) RR7146(P_DEBIAD) & mask));
/* Modify the register image. */
DEBItransfer(dev); /* Execute the DEBI Write transfer. */
}
static void CloseDMAB(struct comedi_device *dev, struct bufferDMA *pdma,
size_t bsize)
{
void *vbptr;
dma_addr_t vpptr;
DEBUG("CloseDMAB: Entering S626DRV_CloseDMAB():\n");
if (pdma == NULL)
return;
/* find the matching allocation from the board struct */
vbptr = pdma->LogicalBase;
vpptr = pdma->PhysicalBase;
if (vbptr) {
pci_free_consistent(devpriv->pdev, bsize, vbptr, vpptr);
pdma->LogicalBase = 0;
pdma->PhysicalBase = 0;
DEBUG("CloseDMAB(): Logical=%p, bsize=%d, Physical=0x%x\n",
vbptr, bsize, (uint32_t) vpptr);
}
}
/* ****** COUNTER FUNCTIONS ******* */
/* All counter functions address a specific counter by means of the
* "Counter" argument, which is a logical counter number. The Counter
* argument may have any of the following legal values: 0=0A, 1=1A,
* 2=2A, 3=0B, 4=1B, 5=2B.
*/
/* Forward declarations for functions that are common to both A and B counters: */
/* ****** PRIVATE COUNTER FUNCTIONS ****** */
/* Read a counter's output latch. */
static uint32_t ReadLatch(struct comedi_device *dev, struct enc_private *k)
{
register uint32_t value;
/* DEBUG FIXME DEBUG("ReadLatch: Read Latch enter\n"); */
/* Latch counts and fetch LSW of latched counts value. */
value = (uint32_t) DEBIread(dev, k->MyLatchLsw);
/* Fetch MSW of latched counts and combine with LSW. */
value |= ((uint32_t) DEBIread(dev, k->MyLatchLsw + 2) << 16);
/* DEBUG FIXME DEBUG("ReadLatch: Read Latch exit\n"); */
/* Return latched counts. */
return value;
}
/* Reset a counter's index and overflow event capture flags. */
static void ResetCapFlags_A(struct comedi_device *dev, struct enc_private *k)
{
DEBIreplace(dev, k->MyCRB, (uint16_t) (~CRBMSK_INTCTRL),
CRBMSK_INTRESETCMD | CRBMSK_INTRESET_A);
}
static void ResetCapFlags_B(struct comedi_device *dev, struct enc_private *k)
{
DEBIreplace(dev, k->MyCRB, (uint16_t) (~CRBMSK_INTCTRL),
CRBMSK_INTRESETCMD | CRBMSK_INTRESET_B);
}
/* Return counter setup in a format (COUNTER_SETUP) that is consistent */
/* for both A and B counters. */
static uint16_t GetMode_A(struct comedi_device *dev, struct enc_private *k)
{
register uint16_t cra;
register uint16_t crb;
register uint16_t setup;
/* Fetch CRA and CRB register images. */
cra = DEBIread(dev, k->MyCRA);
crb = DEBIread(dev, k->MyCRB);
/* Populate the standardized counter setup bit fields. Note: */
/* IndexSrc is restricted to ENC_X or IndxPol. */
setup = ((cra & STDMSK_LOADSRC) /* LoadSrc = LoadSrcA. */
|((crb << (STDBIT_LATCHSRC - CRBBIT_LATCHSRC)) & STDMSK_LATCHSRC) /* LatchSrc = LatchSrcA. */
|((cra << (STDBIT_INTSRC - CRABIT_INTSRC_A)) & STDMSK_INTSRC) /* IntSrc = IntSrcA. */
|((cra << (STDBIT_INDXSRC - (CRABIT_INDXSRC_A + 1))) & STDMSK_INDXSRC) /* IndxSrc = IndxSrcA<1>. */
|((cra >> (CRABIT_INDXPOL_A - STDBIT_INDXPOL)) & STDMSK_INDXPOL) /* IndxPol = IndxPolA. */
|((crb >> (CRBBIT_CLKENAB_A - STDBIT_CLKENAB)) & STDMSK_CLKENAB)); /* ClkEnab = ClkEnabA. */
/* Adjust mode-dependent parameters. */
if (cra & (2 << CRABIT_CLKSRC_A)) /* If Timer mode (ClkSrcA<1> == 1): */
setup |= ((CLKSRC_TIMER << STDBIT_CLKSRC) /* Indicate Timer mode. */
|((cra << (STDBIT_CLKPOL - CRABIT_CLKSRC_A)) & STDMSK_CLKPOL) /* Set ClkPol to indicate count direction (ClkSrcA<0>). */
|(MULT_X1 << STDBIT_CLKMULT)); /* ClkMult must be 1x in Timer mode. */
else /* If Counter mode (ClkSrcA<1> == 0): */
setup |= ((CLKSRC_COUNTER << STDBIT_CLKSRC) /* Indicate Counter mode. */
|((cra >> (CRABIT_CLKPOL_A - STDBIT_CLKPOL)) & STDMSK_CLKPOL) /* Pass through ClkPol. */
|(((cra & CRAMSK_CLKMULT_A) == (MULT_X0 << CRABIT_CLKMULT_A)) ? /* Force ClkMult to 1x if not legal, else pass through. */
(MULT_X1 << STDBIT_CLKMULT) :
((cra >> (CRABIT_CLKMULT_A -
STDBIT_CLKMULT)) & STDMSK_CLKMULT)));
/* Return adjusted counter setup. */
return setup;
}
static uint16_t GetMode_B(struct comedi_device *dev, struct enc_private *k)
{
register uint16_t cra;
register uint16_t crb;
register uint16_t setup;
/* Fetch CRA and CRB register images. */
cra = DEBIread(dev, k->MyCRA);
crb = DEBIread(dev, k->MyCRB);
/* Populate the standardized counter setup bit fields. Note: */
/* IndexSrc is restricted to ENC_X or IndxPol. */
setup = (((crb << (STDBIT_INTSRC - CRBBIT_INTSRC_B)) & STDMSK_INTSRC) /* IntSrc = IntSrcB. */
|((crb << (STDBIT_LATCHSRC - CRBBIT_LATCHSRC)) & STDMSK_LATCHSRC) /* LatchSrc = LatchSrcB. */
|((crb << (STDBIT_LOADSRC - CRBBIT_LOADSRC_B)) & STDMSK_LOADSRC) /* LoadSrc = LoadSrcB. */
|((crb << (STDBIT_INDXPOL - CRBBIT_INDXPOL_B)) & STDMSK_INDXPOL) /* IndxPol = IndxPolB. */
|((crb >> (CRBBIT_CLKENAB_B - STDBIT_CLKENAB)) & STDMSK_CLKENAB) /* ClkEnab = ClkEnabB. */
|((cra >> ((CRABIT_INDXSRC_B + 1) - STDBIT_INDXSRC)) & STDMSK_INDXSRC)); /* IndxSrc = IndxSrcB<1>. */
/* Adjust mode-dependent parameters. */
if ((crb & CRBMSK_CLKMULT_B) == (MULT_X0 << CRBBIT_CLKMULT_B)) /* If Extender mode (ClkMultB == MULT_X0): */
setup |= ((CLKSRC_EXTENDER << STDBIT_CLKSRC) /* Indicate Extender mode. */
|(MULT_X1 << STDBIT_CLKMULT) /* Indicate multiplier is 1x. */
|((cra >> (CRABIT_CLKSRC_B - STDBIT_CLKPOL)) & STDMSK_CLKPOL)); /* Set ClkPol equal to Timer count direction (ClkSrcB<0>). */
else if (cra & (2 << CRABIT_CLKSRC_B)) /* If Timer mode (ClkSrcB<1> == 1): */
setup |= ((CLKSRC_TIMER << STDBIT_CLKSRC) /* Indicate Timer mode. */
|(MULT_X1 << STDBIT_CLKMULT) /* Indicate multiplier is 1x. */
|((cra >> (CRABIT_CLKSRC_B - STDBIT_CLKPOL)) & STDMSK_CLKPOL)); /* Set ClkPol equal to Timer count direction (ClkSrcB<0>). */
else /* If Counter mode (ClkSrcB<1> == 0): */
setup |= ((CLKSRC_COUNTER << STDBIT_CLKSRC) /* Indicate Timer mode. */
|((crb >> (CRBBIT_CLKMULT_B - STDBIT_CLKMULT)) & STDMSK_CLKMULT) /* Clock multiplier is passed through. */
|((crb << (STDBIT_CLKPOL - CRBBIT_CLKPOL_B)) & STDMSK_CLKPOL)); /* Clock polarity is passed through. */
/* Return adjusted counter setup. */
return setup;
}
/*
* Set the operating mode for the specified counter. The setup
* parameter is treated as a COUNTER_SETUP data type. The following
* parameters are programmable (all other parms are ignored): ClkMult,
* ClkPol, ClkEnab, IndexSrc, IndexPol, LoadSrc.
*/
static void SetMode_A(struct comedi_device *dev, struct enc_private *k,
uint16_t Setup, uint16_t DisableIntSrc)
{
register uint16_t cra;
register uint16_t crb;
register uint16_t setup = Setup; /* Cache the Standard Setup. */
/* Initialize CRA and CRB images. */
cra = ((setup & CRAMSK_LOADSRC_A) /* Preload trigger is passed through. */
|((setup & STDMSK_INDXSRC) >> (STDBIT_INDXSRC - (CRABIT_INDXSRC_A + 1)))); /* IndexSrc is restricted to ENC_X or IndxPol. */
crb = (CRBMSK_INTRESETCMD | CRBMSK_INTRESET_A /* Reset any pending CounterA event captures. */
| ((setup & STDMSK_CLKENAB) << (CRBBIT_CLKENAB_A - STDBIT_CLKENAB))); /* Clock enable is passed through. */
/* Force IntSrc to Disabled if DisableIntSrc is asserted. */
if (!DisableIntSrc)
cra |= ((setup & STDMSK_INTSRC) >> (STDBIT_INTSRC -
CRABIT_INTSRC_A));
/* Populate all mode-dependent attributes of CRA & CRB images. */
switch ((setup & STDMSK_CLKSRC) >> STDBIT_CLKSRC) {
case CLKSRC_EXTENDER: /* Extender Mode: Force to Timer mode */
/* (Extender valid only for B counters). */
case CLKSRC_TIMER: /* Timer Mode: */
cra |= ((2 << CRABIT_CLKSRC_A) /* ClkSrcA<1> selects system clock */
|((setup & STDMSK_CLKPOL) >> (STDBIT_CLKPOL - CRABIT_CLKSRC_A)) /* with count direction (ClkSrcA<0>) obtained from ClkPol. */
|(1 << CRABIT_CLKPOL_A) /* ClkPolA behaves as always-on clock enable. */
|(MULT_X1 << CRABIT_CLKMULT_A)); /* ClkMult must be 1x. */
break;
default: /* Counter Mode: */
cra |= (CLKSRC_COUNTER /* Select ENC_C and ENC_D as clock/direction inputs. */
| ((setup & STDMSK_CLKPOL) << (CRABIT_CLKPOL_A - STDBIT_CLKPOL)) /* Clock polarity is passed through. */
|(((setup & STDMSK_CLKMULT) == (MULT_X0 << STDBIT_CLKMULT)) ? /* Force multiplier to x1 if not legal, otherwise pass through. */
(MULT_X1 << CRABIT_CLKMULT_A) :
((setup & STDMSK_CLKMULT) << (CRABIT_CLKMULT_A -
STDBIT_CLKMULT))));
}
/* Force positive index polarity if IndxSrc is software-driven only, */
/* otherwise pass it through. */
if (~setup & STDMSK_INDXSRC)
cra |= ((setup & STDMSK_INDXPOL) << (CRABIT_INDXPOL_A -
STDBIT_INDXPOL));
/* If IntSrc has been forced to Disabled, update the MISC2 interrupt */
/* enable mask to indicate the counter interrupt is disabled. */
if (DisableIntSrc)
devpriv->CounterIntEnabs &= ~k->MyEventBits[3];
/* While retaining CounterB and LatchSrc configurations, program the */
/* new counter operating mode. */
DEBIreplace(dev, k->MyCRA, CRAMSK_INDXSRC_B | CRAMSK_CLKSRC_B, cra);
DEBIreplace(dev, k->MyCRB,
(uint16_t) (~(CRBMSK_INTCTRL | CRBMSK_CLKENAB_A)), crb);
}
static void SetMode_B(struct comedi_device *dev, struct enc_private *k,
uint16_t Setup, uint16_t DisableIntSrc)
{
register uint16_t cra;
register uint16_t crb;
register uint16_t setup = Setup; /* Cache the Standard Setup. */
/* Initialize CRA and CRB images. */
cra = ((setup & STDMSK_INDXSRC) << ((CRABIT_INDXSRC_B + 1) - STDBIT_INDXSRC)); /* IndexSrc field is restricted to ENC_X or IndxPol. */
crb = (CRBMSK_INTRESETCMD | CRBMSK_INTRESET_B /* Reset event captures and disable interrupts. */
| ((setup & STDMSK_CLKENAB) << (CRBBIT_CLKENAB_B - STDBIT_CLKENAB)) /* Clock enable is passed through. */
|((setup & STDMSK_LOADSRC) >> (STDBIT_LOADSRC - CRBBIT_LOADSRC_B))); /* Preload trigger source is passed through. */
/* Force IntSrc to Disabled if DisableIntSrc is asserted. */
if (!DisableIntSrc)
crb |= ((setup & STDMSK_INTSRC) >> (STDBIT_INTSRC -
CRBBIT_INTSRC_B));
/* Populate all mode-dependent attributes of CRA & CRB images. */
switch ((setup & STDMSK_CLKSRC) >> STDBIT_CLKSRC) {
case CLKSRC_TIMER: /* Timer Mode: */
cra |= ((2 << CRABIT_CLKSRC_B) /* ClkSrcB<1> selects system clock */
|((setup & STDMSK_CLKPOL) << (CRABIT_CLKSRC_B - STDBIT_CLKPOL))); /* with direction (ClkSrcB<0>) obtained from ClkPol. */
crb |= ((1 << CRBBIT_CLKPOL_B) /* ClkPolB behaves as always-on clock enable. */
|(MULT_X1 << CRBBIT_CLKMULT_B)); /* ClkMultB must be 1x. */
break;
case CLKSRC_EXTENDER: /* Extender Mode: */
cra |= ((2 << CRABIT_CLKSRC_B) /* ClkSrcB source is OverflowA (same as "timer") */
|((setup & STDMSK_CLKPOL) << (CRABIT_CLKSRC_B - STDBIT_CLKPOL))); /* with direction obtained from ClkPol. */
crb |= ((1 << CRBBIT_CLKPOL_B) /* ClkPolB controls IndexB -- always set to active. */
|(MULT_X0 << CRBBIT_CLKMULT_B)); /* ClkMultB selects OverflowA as the clock source. */
break;
default: /* Counter Mode: */
cra |= (CLKSRC_COUNTER << CRABIT_CLKSRC_B); /* Select ENC_C and ENC_D as clock/direction inputs. */
crb |= (((setup & STDMSK_CLKPOL) >> (STDBIT_CLKPOL - CRBBIT_CLKPOL_B)) /* ClkPol is passed through. */
|(((setup & STDMSK_CLKMULT) == (MULT_X0 << STDBIT_CLKMULT)) ? /* Force ClkMult to x1 if not legal, otherwise pass through. */
(MULT_X1 << CRBBIT_CLKMULT_B) :
((setup & STDMSK_CLKMULT) << (CRBBIT_CLKMULT_B -
STDBIT_CLKMULT))));
}
/* Force positive index polarity if IndxSrc is software-driven only, */
/* otherwise pass it through. */
if (~setup & STDMSK_INDXSRC)
crb |= ((setup & STDMSK_INDXPOL) >> (STDBIT_INDXPOL -
CRBBIT_INDXPOL_B));
/* If IntSrc has been forced to Disabled, update the MISC2 interrupt */
/* enable mask to indicate the counter interrupt is disabled. */
if (DisableIntSrc)
devpriv->CounterIntEnabs &= ~k->MyEventBits[3];
/* While retaining CounterA and LatchSrc configurations, program the */
/* new counter operating mode. */
DEBIreplace(dev, k->MyCRA,
(uint16_t) (~(CRAMSK_INDXSRC_B | CRAMSK_CLKSRC_B)), cra);
DEBIreplace(dev, k->MyCRB, CRBMSK_CLKENAB_A | CRBMSK_LATCHSRC, crb);
}
/* Return/set a counter's enable. enab: 0=always enabled, 1=enabled by index. */
static void SetEnable_A(struct comedi_device *dev, struct enc_private *k,
uint16_t enab)
{
DEBUG("SetEnable_A: SetEnable_A enter 3541\n");
DEBIreplace(dev, k->MyCRB,
(uint16_t) (~(CRBMSK_INTCTRL | CRBMSK_CLKENAB_A)),
(uint16_t) (enab << CRBBIT_CLKENAB_A));
}
static void SetEnable_B(struct comedi_device *dev, struct enc_private *k,
uint16_t enab)
{
DEBIreplace(dev, k->MyCRB,
(uint16_t) (~(CRBMSK_INTCTRL | CRBMSK_CLKENAB_B)),
(uint16_t) (enab << CRBBIT_CLKENAB_B));
}
static uint16_t GetEnable_A(struct comedi_device *dev, struct enc_private *k)
{
return (DEBIread(dev, k->MyCRB) >> CRBBIT_CLKENAB_A) & 1;
}
static uint16_t GetEnable_B(struct comedi_device *dev, struct enc_private *k)
{
return (DEBIread(dev, k->MyCRB) >> CRBBIT_CLKENAB_B) & 1;
}
/* Return/set a counter pair's latch trigger source. 0: On read
* access, 1: A index latches A, 2: B index latches B, 3: A overflow
* latches B.
*/
static void SetLatchSource(struct comedi_device *dev, struct enc_private *k,
uint16_t value)
{
DEBUG("SetLatchSource: SetLatchSource enter 3550\n");
DEBIreplace(dev, k->MyCRB,
(uint16_t) (~(CRBMSK_INTCTRL | CRBMSK_LATCHSRC)),
(uint16_t) (value << CRBBIT_LATCHSRC));
DEBUG("SetLatchSource: SetLatchSource exit\n");
}
/*
* static uint16_t GetLatchSource(struct comedi_device *dev, struct enc_private *k )
* {
* return ( DEBIread( dev, k->MyCRB) >> CRBBIT_LATCHSRC ) & 3;
* }
*/
/*
* Return/set the event that will trigger transfer of the preload
* register into the counter. 0=ThisCntr_Index, 1=ThisCntr_Overflow,
* 2=OverflowA (B counters only), 3=disabled.
*/
static void SetLoadTrig_A(struct comedi_device *dev, struct enc_private *k,
uint16_t Trig)
{
DEBIreplace(dev, k->MyCRA, (uint16_t) (~CRAMSK_LOADSRC_A),
(uint16_t) (Trig << CRABIT_LOADSRC_A));
}
static void SetLoadTrig_B(struct comedi_device *dev, struct enc_private *k,
uint16_t Trig)
{
DEBIreplace(dev, k->MyCRB,
(uint16_t) (~(CRBMSK_LOADSRC_B | CRBMSK_INTCTRL)),
(uint16_t) (Trig << CRBBIT_LOADSRC_B));
}
static uint16_t GetLoadTrig_A(struct comedi_device *dev, struct enc_private *k)
{
return (DEBIread(dev, k->MyCRA) >> CRABIT_LOADSRC_A) & 3;
}
static uint16_t GetLoadTrig_B(struct comedi_device *dev, struct enc_private *k)
{
return (DEBIread(dev, k->MyCRB) >> CRBBIT_LOADSRC_B) & 3;
}
/* Return/set counter interrupt source and clear any captured
* index/overflow events. IntSource: 0=Disabled, 1=OverflowOnly,
* 2=IndexOnly, 3=IndexAndOverflow.
*/
static void SetIntSrc_A(struct comedi_device *dev, struct enc_private *k,
uint16_t IntSource)
{
/* Reset any pending counter overflow or index captures. */
DEBIreplace(dev, k->MyCRB, (uint16_t) (~CRBMSK_INTCTRL),
CRBMSK_INTRESETCMD | CRBMSK_INTRESET_A);
/* Program counter interrupt source. */
DEBIreplace(dev, k->MyCRA, ~CRAMSK_INTSRC_A,
(uint16_t) (IntSource << CRABIT_INTSRC_A));
/* Update MISC2 interrupt enable mask. */
devpriv->CounterIntEnabs =
(devpriv->CounterIntEnabs & ~k->
MyEventBits[3]) | k->MyEventBits[IntSource];
}
static void SetIntSrc_B(struct comedi_device *dev, struct enc_private *k,
uint16_t IntSource)
{
uint16_t crb;
/* Cache writeable CRB register image. */
crb = DEBIread(dev, k->MyCRB) & ~CRBMSK_INTCTRL;
/* Reset any pending counter overflow or index captures. */
DEBIwrite(dev, k->MyCRB,
(uint16_t) (crb | CRBMSK_INTRESETCMD | CRBMSK_INTRESET_B));
/* Program counter interrupt source. */
DEBIwrite(dev, k->MyCRB,
(uint16_t) ((crb & ~CRBMSK_INTSRC_B) | (IntSource <<
CRBBIT_INTSRC_B)));
/* Update MISC2 interrupt enable mask. */
devpriv->CounterIntEnabs =
(devpriv->CounterIntEnabs & ~k->
MyEventBits[3]) | k->MyEventBits[IntSource];
}
static uint16_t GetIntSrc_A(struct comedi_device *dev, struct enc_private *k)
{
return (DEBIread(dev, k->MyCRA) >> CRABIT_INTSRC_A) & 3;
}
static uint16_t GetIntSrc_B(struct comedi_device *dev, struct enc_private *k)
{
return (DEBIread(dev, k->MyCRB) >> CRBBIT_INTSRC_B) & 3;
}
/* Return/set the clock multiplier. */
/* static void SetClkMult(struct comedi_device *dev, struct enc_private *k, uint16_t value ) */
/* { */
/* k->SetMode(dev, k, (uint16_t)( ( k->GetMode(dev, k ) & ~STDMSK_CLKMULT ) | ( value << STDBIT_CLKMULT ) ), FALSE ); */
/* } */
/* static uint16_t GetClkMult(struct comedi_device *dev, struct enc_private *k ) */
/* { */
/* return ( k->GetMode(dev, k ) >> STDBIT_CLKMULT ) & 3; */
/* } */
/* Return/set the clock polarity. */
/* static void SetClkPol( struct comedi_device *dev,struct enc_private *k, uint16_t value ) */
/* { */
/* k->SetMode(dev, k, (uint16_t)( ( k->GetMode(dev, k ) & ~STDMSK_CLKPOL ) | ( value << STDBIT_CLKPOL ) ), FALSE ); */
/* } */
/* static uint16_t GetClkPol(struct comedi_device *dev, struct enc_private *k ) */
/* { */
/* return ( k->GetMode(dev, k ) >> STDBIT_CLKPOL ) & 1; */
/* } */
/* Return/set the clock source. */
/* static void SetClkSrc( struct comedi_device *dev,struct enc_private *k, uint16_t value ) */
/* { */
/* k->SetMode(dev, k, (uint16_t)( ( k->GetMode(dev, k ) & ~STDMSK_CLKSRC ) | ( value << STDBIT_CLKSRC ) ), FALSE ); */
/* } */
/* static uint16_t GetClkSrc( struct comedi_device *dev,struct enc_private *k ) */
/* { */
/* return ( k->GetMode(dev, k ) >> STDBIT_CLKSRC ) & 3; */
/* } */
/* Return/set the index polarity. */
/* static void SetIndexPol(struct comedi_device *dev, struct enc_private *k, uint16_t value ) */
/* { */
/* k->SetMode(dev, k, (uint16_t)( ( k->GetMode(dev, k ) & ~STDMSK_INDXPOL ) | ( (value != 0) << STDBIT_INDXPOL ) ), FALSE ); */
/* } */
/* static uint16_t GetIndexPol(struct comedi_device *dev, struct enc_private *k ) */
/* { */
/* return ( k->GetMode(dev, k ) >> STDBIT_INDXPOL ) & 1; */
/* } */
/* Return/set the index source. */
/* static void SetIndexSrc(struct comedi_device *dev, struct enc_private *k, uint16_t value ) */
/* { */
/* DEBUG("SetIndexSrc: set index src enter 3700\n"); */
/* k->SetMode(dev, k, (uint16_t)( ( k->GetMode(dev, k ) & ~STDMSK_INDXSRC ) | ( (value != 0) << STDBIT_INDXSRC ) ), FALSE ); */
/* } */
/* static uint16_t GetIndexSrc(struct comedi_device *dev, struct enc_private *k ) */
/* { */
/* return ( k->GetMode(dev, k ) >> STDBIT_INDXSRC ) & 1; */
/* } */
/* Generate an index pulse. */
static void PulseIndex_A(struct comedi_device *dev, struct enc_private *k)
{
register uint16_t cra;
DEBUG("PulseIndex_A: pulse index enter\n");
cra = DEBIread(dev, k->MyCRA); /* Pulse index. */
DEBIwrite(dev, k->MyCRA, (uint16_t) (cra ^ CRAMSK_INDXPOL_A));
DEBUG("PulseIndex_A: pulse index step1\n");
DEBIwrite(dev, k->MyCRA, cra);
}
static void PulseIndex_B(struct comedi_device *dev, struct enc_private *k)
{
register uint16_t crb;
crb = DEBIread(dev, k->MyCRB) & ~CRBMSK_INTCTRL; /* Pulse index. */
DEBIwrite(dev, k->MyCRB, (uint16_t) (crb ^ CRBMSK_INDXPOL_B));
DEBIwrite(dev, k->MyCRB, crb);
}
/* Write value into counter preload register. */
static void Preload(struct comedi_device *dev, struct enc_private *k,
uint32_t value)
{
DEBUG("Preload: preload enter\n");
DEBIwrite(dev, (uint16_t) (k->MyLatchLsw), (uint16_t) value); /* Write value to preload register. */
DEBUG("Preload: preload step 1\n");
DEBIwrite(dev, (uint16_t) (k->MyLatchLsw + 2),
(uint16_t) (value >> 16));
}
static void CountersInit(struct comedi_device *dev)
{
int chan;
struct enc_private *k;
uint16_t Setup = (LOADSRC_INDX << BF_LOADSRC) | /* Preload upon */
/* index. */
(INDXSRC_SOFT << BF_INDXSRC) | /* Disable hardware index. */
(CLKSRC_COUNTER << BF_CLKSRC) | /* Operating mode is counter. */
(CLKPOL_POS << BF_CLKPOL) | /* Active high clock. */
(CNTDIR_UP << BF_CLKPOL) | /* Count direction is up. */
(CLKMULT_1X << BF_CLKMULT) | /* Clock multiplier is 1x. */
(CLKENAB_INDEX << BF_CLKENAB); /* Enabled by index */
/* Disable all counter interrupts and clear any captured counter events. */
for (chan = 0; chan < S626_ENCODER_CHANNELS; chan++) {
k = &encpriv[chan];
k->SetMode(dev, k, Setup, TRUE);
k->SetIntSrc(dev, k, 0);
k->ResetCapFlags(dev, k);
k->SetEnable(dev, k, CLKENAB_ALWAYS);
}
DEBUG("CountersInit: counters initialized\n");
}
| gpl-2.0 |
shminer/android_kernel_flounder | arch/mips/mti-malta/malta-memory.c | 2415 | 3329 | /*
* 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.
*
* PROM library functions for acquiring/using memory descriptors given to
* us from the YAMON.
*
* Copyright (C) 1999,2000,2012 MIPS Technologies, Inc.
* All rights reserved.
* Authors: Carsten Langgaard <carstenl@mips.com>
* Steven J. Hill <sjhill@mips.com>
*/
#include <linux/init.h>
#include <linux/bootmem.h>
#include <linux/string.h>
#include <asm/bootinfo.h>
#include <asm/sections.h>
#include <asm/fw/fw.h>
static fw_memblock_t mdesc[FW_MAX_MEMBLOCKS];
/* determined physical memory size, not overridden by command line args */
unsigned long physical_memsize = 0L;
fw_memblock_t * __init fw_getmdesc(void)
{
char *memsize_str, *ptr;
unsigned int memsize;
static char cmdline[COMMAND_LINE_SIZE] __initdata;
long val;
int tmp;
/* otherwise look in the environment */
memsize_str = fw_getenv("memsize");
if (!memsize_str) {
pr_warn("memsize not set in YAMON, set to default (32Mb)\n");
physical_memsize = 0x02000000;
} else {
tmp = kstrtol(memsize_str, 0, &val);
physical_memsize = (unsigned long)val;
}
#ifdef CONFIG_CPU_BIG_ENDIAN
/* SOC-it swaps, or perhaps doesn't swap, when DMA'ing the last
word of physical memory */
physical_memsize -= PAGE_SIZE;
#endif
/* Check the command line for a memsize directive that overrides
the physical/default amount */
strcpy(cmdline, arcs_cmdline);
ptr = strstr(cmdline, "memsize=");
if (ptr && (ptr != cmdline) && (*(ptr - 1) != ' '))
ptr = strstr(ptr, " memsize=");
if (ptr)
memsize = memparse(ptr + 8, &ptr);
else
memsize = physical_memsize;
memset(mdesc, 0, sizeof(mdesc));
mdesc[0].type = fw_dontuse;
mdesc[0].base = 0x00000000;
mdesc[0].size = 0x00001000;
mdesc[1].type = fw_code;
mdesc[1].base = 0x00001000;
mdesc[1].size = 0x000ef000;
/*
* The area 0x000f0000-0x000fffff is allocated for BIOS memory by the
* south bridge and PCI access always forwarded to the ISA Bus and
* BIOSCS# is always generated.
* This mean that this area can't be used as DMA memory for PCI
* devices.
*/
mdesc[2].type = fw_dontuse;
mdesc[2].base = 0x000f0000;
mdesc[2].size = 0x00010000;
mdesc[3].type = fw_dontuse;
mdesc[3].base = 0x00100000;
mdesc[3].size = CPHYSADDR(PFN_ALIGN((unsigned long)&_end)) -
mdesc[3].base;
mdesc[4].type = fw_free;
mdesc[4].base = CPHYSADDR(PFN_ALIGN(&_end));
mdesc[4].size = memsize - mdesc[4].base;
return &mdesc[0];
}
static int __init fw_memtype_classify(unsigned int type)
{
switch (type) {
case fw_free:
return BOOT_MEM_RAM;
case fw_code:
return BOOT_MEM_ROM_DATA;
default:
return BOOT_MEM_RESERVED;
}
}
void __init fw_meminit(void)
{
fw_memblock_t *p;
p = fw_getmdesc();
while (p->size) {
long type;
unsigned long base, size;
type = fw_memtype_classify(p->type);
base = p->base;
size = p->size;
add_memory_region(base, size, type);
p++;
}
}
void __init prom_free_prom_memory(void)
{
unsigned long addr;
int i;
for (i = 0; i < boot_mem_map.nr_map; i++) {
if (boot_mem_map.map[i].type != BOOT_MEM_ROM_DATA)
continue;
addr = boot_mem_map.map[i].addr;
free_init_pages("YAMON memory",
addr, addr + boot_mem_map.map[i].size);
}
}
| gpl-2.0 |
surdupetru/tf300t-4.1bl | drivers/misc/hmc6352.c | 3183 | 4307 | /*
* hmc6352.c - Honeywell Compass Driver
*
* Copyright (C) 2009 Intel Corp
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/i2c.h>
#include <linux/err.h>
#include <linux/delay.h>
#include <linux/sysfs.h>
static DEFINE_MUTEX(compass_mutex);
static int compass_command(struct i2c_client *c, u8 cmd)
{
int ret = i2c_master_send(c, &cmd, 1);
if (ret < 0)
dev_warn(&c->dev, "command '%c' failed.\n", cmd);
return ret;
}
static int compass_store(struct device *dev, const char *buf, size_t count,
const char *map)
{
struct i2c_client *c = to_i2c_client(dev);
int ret;
unsigned long val;
if (strict_strtoul(buf, 10, &val))
return -EINVAL;
if (val >= strlen(map))
return -EINVAL;
mutex_lock(&compass_mutex);
ret = compass_command(c, map[val]);
mutex_unlock(&compass_mutex);
if (ret < 0)
return ret;
return count;
}
static ssize_t compass_calibration_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
return compass_store(dev, buf, count, "EC");
}
static ssize_t compass_power_mode_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
return compass_store(dev, buf, count, "SW");
}
static ssize_t compass_heading_data_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct i2c_client *client = to_i2c_client(dev);
unsigned char i2c_data[2];
int ret;
mutex_lock(&compass_mutex);
ret = compass_command(client, 'A');
if (ret != 1) {
mutex_unlock(&compass_mutex);
return ret;
}
msleep(10); /* sending 'A' cmd we need to wait for 7-10 millisecs */
ret = i2c_master_recv(client, i2c_data, 2);
mutex_unlock(&compass_mutex);
if (ret < 0) {
dev_warn(dev, "i2c read data cmd failed\n");
return ret;
}
ret = (i2c_data[0] << 8) | i2c_data[1];
return sprintf(buf, "%d.%d\n", ret/10, ret%10);
}
static DEVICE_ATTR(heading0_input, S_IRUGO, compass_heading_data_show, NULL);
static DEVICE_ATTR(calibration, S_IWUSR, NULL, compass_calibration_store);
static DEVICE_ATTR(power_state, S_IWUSR, NULL, compass_power_mode_store);
static struct attribute *mid_att_compass[] = {
&dev_attr_heading0_input.attr,
&dev_attr_calibration.attr,
&dev_attr_power_state.attr,
NULL
};
static const struct attribute_group m_compass_gr = {
.name = "hmc6352",
.attrs = mid_att_compass
};
static int hmc6352_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
int res;
res = sysfs_create_group(&client->dev.kobj, &m_compass_gr);
if (res) {
dev_err(&client->dev, "device_create_file failed\n");
return res;
}
dev_info(&client->dev, "%s HMC6352 compass chip found\n",
client->name);
return 0;
}
static int hmc6352_remove(struct i2c_client *client)
{
sysfs_remove_group(&client->dev.kobj, &m_compass_gr);
return 0;
}
static struct i2c_device_id hmc6352_id[] = {
{ "hmc6352", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, hmc6352_id);
static struct i2c_driver hmc6352_driver = {
.driver = {
.name = "hmc6352",
},
.probe = hmc6352_probe,
.remove = hmc6352_remove,
.id_table = hmc6352_id,
};
static int __init sensor_hmc6352_init(void)
{
return i2c_add_driver(&hmc6352_driver);
}
static void __exit sensor_hmc6352_exit(void)
{
i2c_del_driver(&hmc6352_driver);
}
module_init(sensor_hmc6352_init);
module_exit(sensor_hmc6352_exit);
MODULE_AUTHOR("Kalhan Trisal <kalhan.trisal@intel.com");
MODULE_DESCRIPTION("hmc6352 Compass Driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
apascual89/android_kernel_oneplus_msm8996-1 | arch/mn10300/unit-asb2305/pci-iomap.c | 3183 | 1047 | /* ASB2305 PCI I/O mapping handler
*
* Copyright (C) 2007 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public Licence
* as published by the Free Software Foundation; either version
* 2 of the Licence, or (at your option) any later version.
*/
#include <linux/pci.h>
#include <linux/module.h>
/*
* Create a virtual mapping cookie for a PCI BAR (memory or IO)
*/
void __iomem *pci_iomap(struct pci_dev *dev, int bar, unsigned long maxlen)
{
resource_size_t start = pci_resource_start(dev, bar);
resource_size_t len = pci_resource_len(dev, bar);
unsigned long flags = pci_resource_flags(dev, bar);
if (!len || !start)
return NULL;
if ((flags & IORESOURCE_IO) || (flags & IORESOURCE_MEM)) {
if (flags & IORESOURCE_CACHEABLE && !(flags & IORESOURCE_IO))
return ioremap(start, len);
else
return ioremap_nocache(start, len);
}
return NULL;
}
EXPORT_SYMBOL(pci_iomap);
| gpl-2.0 |
zeroblade1984/Xiaomi-MSM8226 | drivers/lguest/page_tables.c | 5743 | 36260 | /*P:700
* The pagetable code, on the other hand, still shows the scars of
* previous encounters. It's functional, and as neat as it can be in the
* circumstances, but be wary, for these things are subtle and break easily.
* The Guest provides a virtual to physical mapping, but we can neither trust
* it nor use it: we verify and convert it here then point the CPU to the
* converted Guest pages when running the Guest.
:*/
/* Copyright (C) Rusty Russell IBM Corporation 2006.
* GPL v2 and any later version */
#include <linux/mm.h>
#include <linux/gfp.h>
#include <linux/types.h>
#include <linux/spinlock.h>
#include <linux/random.h>
#include <linux/percpu.h>
#include <asm/tlbflush.h>
#include <asm/uaccess.h>
#include "lg.h"
/*M:008
* We hold reference to pages, which prevents them from being swapped.
* It'd be nice to have a callback in the "struct mm_struct" when Linux wants
* to swap out. If we had this, and a shrinker callback to trim PTE pages, we
* could probably consider launching Guests as non-root.
:*/
/*H:300
* The Page Table Code
*
* We use two-level page tables for the Guest, or three-level with PAE. If
* you're not entirely comfortable with virtual addresses, physical addresses
* and page tables then I recommend you review arch/x86/lguest/boot.c's "Page
* Table Handling" (with diagrams!).
*
* The Guest keeps page tables, but we maintain the actual ones here: these are
* called "shadow" page tables. Which is a very Guest-centric name: these are
* the real page tables the CPU uses, although we keep them up to date to
* reflect the Guest's. (See what I mean about weird naming? Since when do
* shadows reflect anything?)
*
* Anyway, this is the most complicated part of the Host code. There are seven
* parts to this:
* (i) Looking up a page table entry when the Guest faults,
* (ii) Making sure the Guest stack is mapped,
* (iii) Setting up a page table entry when the Guest tells us one has changed,
* (iv) Switching page tables,
* (v) Flushing (throwing away) page tables,
* (vi) Mapping the Switcher when the Guest is about to run,
* (vii) Setting up the page tables initially.
:*/
/*
* The Switcher uses the complete top PTE page. That's 1024 PTE entries (4MB)
* or 512 PTE entries with PAE (2MB).
*/
#define SWITCHER_PGD_INDEX (PTRS_PER_PGD - 1)
/*
* For PAE we need the PMD index as well. We use the last 2MB, so we
* will need the last pmd entry of the last pmd page.
*/
#ifdef CONFIG_X86_PAE
#define SWITCHER_PMD_INDEX (PTRS_PER_PMD - 1)
#define RESERVE_MEM 2U
#define CHECK_GPGD_MASK _PAGE_PRESENT
#else
#define RESERVE_MEM 4U
#define CHECK_GPGD_MASK _PAGE_TABLE
#endif
/*
* We actually need a separate PTE page for each CPU. Remember that after the
* Switcher code itself comes two pages for each CPU, and we don't want this
* CPU's guest to see the pages of any other CPU.
*/
static DEFINE_PER_CPU(pte_t *, switcher_pte_pages);
#define switcher_pte_page(cpu) per_cpu(switcher_pte_pages, cpu)
/*H:320
* The page table code is curly enough to need helper functions to keep it
* clear and clean. The kernel itself provides many of them; one advantage
* of insisting that the Guest and Host use the same CONFIG_PAE setting.
*
* There are two functions which return pointers to the shadow (aka "real")
* page tables.
*
* spgd_addr() takes the virtual address and returns a pointer to the top-level
* page directory entry (PGD) for that address. Since we keep track of several
* page tables, the "i" argument tells us which one we're interested in (it's
* usually the current one).
*/
static pgd_t *spgd_addr(struct lg_cpu *cpu, u32 i, unsigned long vaddr)
{
unsigned int index = pgd_index(vaddr);
#ifndef CONFIG_X86_PAE
/* We kill any Guest trying to touch the Switcher addresses. */
if (index >= SWITCHER_PGD_INDEX) {
kill_guest(cpu, "attempt to access switcher pages");
index = 0;
}
#endif
/* Return a pointer index'th pgd entry for the i'th page table. */
return &cpu->lg->pgdirs[i].pgdir[index];
}
#ifdef CONFIG_X86_PAE
/*
* This routine then takes the PGD entry given above, which contains the
* address of the PMD page. It then returns a pointer to the PMD entry for the
* given address.
*/
static pmd_t *spmd_addr(struct lg_cpu *cpu, pgd_t spgd, unsigned long vaddr)
{
unsigned int index = pmd_index(vaddr);
pmd_t *page;
/* We kill any Guest trying to touch the Switcher addresses. */
if (pgd_index(vaddr) == SWITCHER_PGD_INDEX &&
index >= SWITCHER_PMD_INDEX) {
kill_guest(cpu, "attempt to access switcher pages");
index = 0;
}
/* You should never call this if the PGD entry wasn't valid */
BUG_ON(!(pgd_flags(spgd) & _PAGE_PRESENT));
page = __va(pgd_pfn(spgd) << PAGE_SHIFT);
return &page[index];
}
#endif
/*
* This routine then takes the page directory entry returned above, which
* contains the address of the page table entry (PTE) page. It then returns a
* pointer to the PTE entry for the given address.
*/
static pte_t *spte_addr(struct lg_cpu *cpu, pgd_t spgd, unsigned long vaddr)
{
#ifdef CONFIG_X86_PAE
pmd_t *pmd = spmd_addr(cpu, spgd, vaddr);
pte_t *page = __va(pmd_pfn(*pmd) << PAGE_SHIFT);
/* You should never call this if the PMD entry wasn't valid */
BUG_ON(!(pmd_flags(*pmd) & _PAGE_PRESENT));
#else
pte_t *page = __va(pgd_pfn(spgd) << PAGE_SHIFT);
/* You should never call this if the PGD entry wasn't valid */
BUG_ON(!(pgd_flags(spgd) & _PAGE_PRESENT));
#endif
return &page[pte_index(vaddr)];
}
/*
* These functions are just like the above, except they access the Guest
* page tables. Hence they return a Guest address.
*/
static unsigned long gpgd_addr(struct lg_cpu *cpu, unsigned long vaddr)
{
unsigned int index = vaddr >> (PGDIR_SHIFT);
return cpu->lg->pgdirs[cpu->cpu_pgd].gpgdir + index * sizeof(pgd_t);
}
#ifdef CONFIG_X86_PAE
/* Follow the PGD to the PMD. */
static unsigned long gpmd_addr(pgd_t gpgd, unsigned long vaddr)
{
unsigned long gpage = pgd_pfn(gpgd) << PAGE_SHIFT;
BUG_ON(!(pgd_flags(gpgd) & _PAGE_PRESENT));
return gpage + pmd_index(vaddr) * sizeof(pmd_t);
}
/* Follow the PMD to the PTE. */
static unsigned long gpte_addr(struct lg_cpu *cpu,
pmd_t gpmd, unsigned long vaddr)
{
unsigned long gpage = pmd_pfn(gpmd) << PAGE_SHIFT;
BUG_ON(!(pmd_flags(gpmd) & _PAGE_PRESENT));
return gpage + pte_index(vaddr) * sizeof(pte_t);
}
#else
/* Follow the PGD to the PTE (no mid-level for !PAE). */
static unsigned long gpte_addr(struct lg_cpu *cpu,
pgd_t gpgd, unsigned long vaddr)
{
unsigned long gpage = pgd_pfn(gpgd) << PAGE_SHIFT;
BUG_ON(!(pgd_flags(gpgd) & _PAGE_PRESENT));
return gpage + pte_index(vaddr) * sizeof(pte_t);
}
#endif
/*:*/
/*M:007
* get_pfn is slow: we could probably try to grab batches of pages here as
* an optimization (ie. pre-faulting).
:*/
/*H:350
* This routine takes a page number given by the Guest and converts it to
* an actual, physical page number. It can fail for several reasons: the
* virtual address might not be mapped by the Launcher, the write flag is set
* and the page is read-only, or the write flag was set and the page was
* shared so had to be copied, but we ran out of memory.
*
* This holds a reference to the page, so release_pte() is careful to put that
* back.
*/
static unsigned long get_pfn(unsigned long virtpfn, int write)
{
struct page *page;
/* gup me one page at this address please! */
if (get_user_pages_fast(virtpfn << PAGE_SHIFT, 1, write, &page) == 1)
return page_to_pfn(page);
/* This value indicates failure. */
return -1UL;
}
/*H:340
* Converting a Guest page table entry to a shadow (ie. real) page table
* entry can be a little tricky. The flags are (almost) the same, but the
* Guest PTE contains a virtual page number: the CPU needs the real page
* number.
*/
static pte_t gpte_to_spte(struct lg_cpu *cpu, pte_t gpte, int write)
{
unsigned long pfn, base, flags;
/*
* The Guest sets the global flag, because it thinks that it is using
* PGE. We only told it to use PGE so it would tell us whether it was
* flushing a kernel mapping or a userspace mapping. We don't actually
* use the global bit, so throw it away.
*/
flags = (pte_flags(gpte) & ~_PAGE_GLOBAL);
/* The Guest's pages are offset inside the Launcher. */
base = (unsigned long)cpu->lg->mem_base / PAGE_SIZE;
/*
* We need a temporary "unsigned long" variable to hold the answer from
* get_pfn(), because it returns 0xFFFFFFFF on failure, which wouldn't
* fit in spte.pfn. get_pfn() finds the real physical number of the
* page, given the virtual number.
*/
pfn = get_pfn(base + pte_pfn(gpte), write);
if (pfn == -1UL) {
kill_guest(cpu, "failed to get page %lu", pte_pfn(gpte));
/*
* When we destroy the Guest, we'll go through the shadow page
* tables and release_pte() them. Make sure we don't think
* this one is valid!
*/
flags = 0;
}
/* Now we assemble our shadow PTE from the page number and flags. */
return pfn_pte(pfn, __pgprot(flags));
}
/*H:460 And to complete the chain, release_pte() looks like this: */
static void release_pte(pte_t pte)
{
/*
* Remember that get_user_pages_fast() took a reference to the page, in
* get_pfn()? We have to put it back now.
*/
if (pte_flags(pte) & _PAGE_PRESENT)
put_page(pte_page(pte));
}
/*:*/
static void check_gpte(struct lg_cpu *cpu, pte_t gpte)
{
if ((pte_flags(gpte) & _PAGE_PSE) ||
pte_pfn(gpte) >= cpu->lg->pfn_limit)
kill_guest(cpu, "bad page table entry");
}
static void check_gpgd(struct lg_cpu *cpu, pgd_t gpgd)
{
if ((pgd_flags(gpgd) & ~CHECK_GPGD_MASK) ||
(pgd_pfn(gpgd) >= cpu->lg->pfn_limit))
kill_guest(cpu, "bad page directory entry");
}
#ifdef CONFIG_X86_PAE
static void check_gpmd(struct lg_cpu *cpu, pmd_t gpmd)
{
if ((pmd_flags(gpmd) & ~_PAGE_TABLE) ||
(pmd_pfn(gpmd) >= cpu->lg->pfn_limit))
kill_guest(cpu, "bad page middle directory entry");
}
#endif
/*H:330
* (i) Looking up a page table entry when the Guest faults.
*
* We saw this call in run_guest(): when we see a page fault in the Guest, we
* come here. That's because we only set up the shadow page tables lazily as
* they're needed, so we get page faults all the time and quietly fix them up
* and return to the Guest without it knowing.
*
* If we fixed up the fault (ie. we mapped the address), this routine returns
* true. Otherwise, it was a real fault and we need to tell the Guest.
*/
bool demand_page(struct lg_cpu *cpu, unsigned long vaddr, int errcode)
{
pgd_t gpgd;
pgd_t *spgd;
unsigned long gpte_ptr;
pte_t gpte;
pte_t *spte;
/* Mid level for PAE. */
#ifdef CONFIG_X86_PAE
pmd_t *spmd;
pmd_t gpmd;
#endif
/* First step: get the top-level Guest page table entry. */
if (unlikely(cpu->linear_pages)) {
/* Faking up a linear mapping. */
gpgd = __pgd(CHECK_GPGD_MASK);
} else {
gpgd = lgread(cpu, gpgd_addr(cpu, vaddr), pgd_t);
/* Toplevel not present? We can't map it in. */
if (!(pgd_flags(gpgd) & _PAGE_PRESENT))
return false;
}
/* Now look at the matching shadow entry. */
spgd = spgd_addr(cpu, cpu->cpu_pgd, vaddr);
if (!(pgd_flags(*spgd) & _PAGE_PRESENT)) {
/* No shadow entry: allocate a new shadow PTE page. */
unsigned long ptepage = get_zeroed_page(GFP_KERNEL);
/*
* This is not really the Guest's fault, but killing it is
* simple for this corner case.
*/
if (!ptepage) {
kill_guest(cpu, "out of memory allocating pte page");
return false;
}
/* We check that the Guest pgd is OK. */
check_gpgd(cpu, gpgd);
/*
* And we copy the flags to the shadow PGD entry. The page
* number in the shadow PGD is the page we just allocated.
*/
set_pgd(spgd, __pgd(__pa(ptepage) | pgd_flags(gpgd)));
}
#ifdef CONFIG_X86_PAE
if (unlikely(cpu->linear_pages)) {
/* Faking up a linear mapping. */
gpmd = __pmd(_PAGE_TABLE);
} else {
gpmd = lgread(cpu, gpmd_addr(gpgd, vaddr), pmd_t);
/* Middle level not present? We can't map it in. */
if (!(pmd_flags(gpmd) & _PAGE_PRESENT))
return false;
}
/* Now look at the matching shadow entry. */
spmd = spmd_addr(cpu, *spgd, vaddr);
if (!(pmd_flags(*spmd) & _PAGE_PRESENT)) {
/* No shadow entry: allocate a new shadow PTE page. */
unsigned long ptepage = get_zeroed_page(GFP_KERNEL);
/*
* This is not really the Guest's fault, but killing it is
* simple for this corner case.
*/
if (!ptepage) {
kill_guest(cpu, "out of memory allocating pte page");
return false;
}
/* We check that the Guest pmd is OK. */
check_gpmd(cpu, gpmd);
/*
* And we copy the flags to the shadow PMD entry. The page
* number in the shadow PMD is the page we just allocated.
*/
set_pmd(spmd, __pmd(__pa(ptepage) | pmd_flags(gpmd)));
}
/*
* OK, now we look at the lower level in the Guest page table: keep its
* address, because we might update it later.
*/
gpte_ptr = gpte_addr(cpu, gpmd, vaddr);
#else
/*
* OK, now we look at the lower level in the Guest page table: keep its
* address, because we might update it later.
*/
gpte_ptr = gpte_addr(cpu, gpgd, vaddr);
#endif
if (unlikely(cpu->linear_pages)) {
/* Linear? Make up a PTE which points to same page. */
gpte = __pte((vaddr & PAGE_MASK) | _PAGE_RW | _PAGE_PRESENT);
} else {
/* Read the actual PTE value. */
gpte = lgread(cpu, gpte_ptr, pte_t);
}
/* If this page isn't in the Guest page tables, we can't page it in. */
if (!(pte_flags(gpte) & _PAGE_PRESENT))
return false;
/*
* Check they're not trying to write to a page the Guest wants
* read-only (bit 2 of errcode == write).
*/
if ((errcode & 2) && !(pte_flags(gpte) & _PAGE_RW))
return false;
/* User access to a kernel-only page? (bit 3 == user access) */
if ((errcode & 4) && !(pte_flags(gpte) & _PAGE_USER))
return false;
/*
* Check that the Guest PTE flags are OK, and the page number is below
* the pfn_limit (ie. not mapping the Launcher binary).
*/
check_gpte(cpu, gpte);
/* Add the _PAGE_ACCESSED and (for a write) _PAGE_DIRTY flag */
gpte = pte_mkyoung(gpte);
if (errcode & 2)
gpte = pte_mkdirty(gpte);
/* Get the pointer to the shadow PTE entry we're going to set. */
spte = spte_addr(cpu, *spgd, vaddr);
/*
* If there was a valid shadow PTE entry here before, we release it.
* This can happen with a write to a previously read-only entry.
*/
release_pte(*spte);
/*
* If this is a write, we insist that the Guest page is writable (the
* final arg to gpte_to_spte()).
*/
if (pte_dirty(gpte))
*spte = gpte_to_spte(cpu, gpte, 1);
else
/*
* If this is a read, don't set the "writable" bit in the page
* table entry, even if the Guest says it's writable. That way
* we will come back here when a write does actually occur, so
* we can update the Guest's _PAGE_DIRTY flag.
*/
set_pte(spte, gpte_to_spte(cpu, pte_wrprotect(gpte), 0));
/*
* Finally, we write the Guest PTE entry back: we've set the
* _PAGE_ACCESSED and maybe the _PAGE_DIRTY flags.
*/
if (likely(!cpu->linear_pages))
lgwrite(cpu, gpte_ptr, pte_t, gpte);
/*
* The fault is fixed, the page table is populated, the mapping
* manipulated, the result returned and the code complete. A small
* delay and a trace of alliteration are the only indications the Guest
* has that a page fault occurred at all.
*/
return true;
}
/*H:360
* (ii) Making sure the Guest stack is mapped.
*
* Remember that direct traps into the Guest need a mapped Guest kernel stack.
* pin_stack_pages() calls us here: we could simply call demand_page(), but as
* we've seen that logic is quite long, and usually the stack pages are already
* mapped, so it's overkill.
*
* This is a quick version which answers the question: is this virtual address
* mapped by the shadow page tables, and is it writable?
*/
static bool page_writable(struct lg_cpu *cpu, unsigned long vaddr)
{
pgd_t *spgd;
unsigned long flags;
#ifdef CONFIG_X86_PAE
pmd_t *spmd;
#endif
/* Look at the current top level entry: is it present? */
spgd = spgd_addr(cpu, cpu->cpu_pgd, vaddr);
if (!(pgd_flags(*spgd) & _PAGE_PRESENT))
return false;
#ifdef CONFIG_X86_PAE
spmd = spmd_addr(cpu, *spgd, vaddr);
if (!(pmd_flags(*spmd) & _PAGE_PRESENT))
return false;
#endif
/*
* Check the flags on the pte entry itself: it must be present and
* writable.
*/
flags = pte_flags(*(spte_addr(cpu, *spgd, vaddr)));
return (flags & (_PAGE_PRESENT|_PAGE_RW)) == (_PAGE_PRESENT|_PAGE_RW);
}
/*
* So, when pin_stack_pages() asks us to pin a page, we check if it's already
* in the page tables, and if not, we call demand_page() with error code 2
* (meaning "write").
*/
void pin_page(struct lg_cpu *cpu, unsigned long vaddr)
{
if (!page_writable(cpu, vaddr) && !demand_page(cpu, vaddr, 2))
kill_guest(cpu, "bad stack page %#lx", vaddr);
}
/*:*/
#ifdef CONFIG_X86_PAE
static void release_pmd(pmd_t *spmd)
{
/* If the entry's not present, there's nothing to release. */
if (pmd_flags(*spmd) & _PAGE_PRESENT) {
unsigned int i;
pte_t *ptepage = __va(pmd_pfn(*spmd) << PAGE_SHIFT);
/* For each entry in the page, we might need to release it. */
for (i = 0; i < PTRS_PER_PTE; i++)
release_pte(ptepage[i]);
/* Now we can free the page of PTEs */
free_page((long)ptepage);
/* And zero out the PMD entry so we never release it twice. */
set_pmd(spmd, __pmd(0));
}
}
static void release_pgd(pgd_t *spgd)
{
/* If the entry's not present, there's nothing to release. */
if (pgd_flags(*spgd) & _PAGE_PRESENT) {
unsigned int i;
pmd_t *pmdpage = __va(pgd_pfn(*spgd) << PAGE_SHIFT);
for (i = 0; i < PTRS_PER_PMD; i++)
release_pmd(&pmdpage[i]);
/* Now we can free the page of PMDs */
free_page((long)pmdpage);
/* And zero out the PGD entry so we never release it twice. */
set_pgd(spgd, __pgd(0));
}
}
#else /* !CONFIG_X86_PAE */
/*H:450
* If we chase down the release_pgd() code, the non-PAE version looks like
* this. The PAE version is almost identical, but instead of calling
* release_pte it calls release_pmd(), which looks much like this.
*/
static void release_pgd(pgd_t *spgd)
{
/* If the entry's not present, there's nothing to release. */
if (pgd_flags(*spgd) & _PAGE_PRESENT) {
unsigned int i;
/*
* Converting the pfn to find the actual PTE page is easy: turn
* the page number into a physical address, then convert to a
* virtual address (easy for kernel pages like this one).
*/
pte_t *ptepage = __va(pgd_pfn(*spgd) << PAGE_SHIFT);
/* For each entry in the page, we might need to release it. */
for (i = 0; i < PTRS_PER_PTE; i++)
release_pte(ptepage[i]);
/* Now we can free the page of PTEs */
free_page((long)ptepage);
/* And zero out the PGD entry so we never release it twice. */
*spgd = __pgd(0);
}
}
#endif
/*H:445
* We saw flush_user_mappings() twice: once from the flush_user_mappings()
* hypercall and once in new_pgdir() when we re-used a top-level pgdir page.
* It simply releases every PTE page from 0 up to the Guest's kernel address.
*/
static void flush_user_mappings(struct lguest *lg, int idx)
{
unsigned int i;
/* Release every pgd entry up to the kernel's address. */
for (i = 0; i < pgd_index(lg->kernel_address); i++)
release_pgd(lg->pgdirs[idx].pgdir + i);
}
/*H:440
* (v) Flushing (throwing away) page tables,
*
* The Guest has a hypercall to throw away the page tables: it's used when a
* large number of mappings have been changed.
*/
void guest_pagetable_flush_user(struct lg_cpu *cpu)
{
/* Drop the userspace part of the current page table. */
flush_user_mappings(cpu->lg, cpu->cpu_pgd);
}
/*:*/
/* We walk down the guest page tables to get a guest-physical address */
unsigned long guest_pa(struct lg_cpu *cpu, unsigned long vaddr)
{
pgd_t gpgd;
pte_t gpte;
#ifdef CONFIG_X86_PAE
pmd_t gpmd;
#endif
/* Still not set up? Just map 1:1. */
if (unlikely(cpu->linear_pages))
return vaddr;
/* First step: get the top-level Guest page table entry. */
gpgd = lgread(cpu, gpgd_addr(cpu, vaddr), pgd_t);
/* Toplevel not present? We can't map it in. */
if (!(pgd_flags(gpgd) & _PAGE_PRESENT)) {
kill_guest(cpu, "Bad address %#lx", vaddr);
return -1UL;
}
#ifdef CONFIG_X86_PAE
gpmd = lgread(cpu, gpmd_addr(gpgd, vaddr), pmd_t);
if (!(pmd_flags(gpmd) & _PAGE_PRESENT))
kill_guest(cpu, "Bad address %#lx", vaddr);
gpte = lgread(cpu, gpte_addr(cpu, gpmd, vaddr), pte_t);
#else
gpte = lgread(cpu, gpte_addr(cpu, gpgd, vaddr), pte_t);
#endif
if (!(pte_flags(gpte) & _PAGE_PRESENT))
kill_guest(cpu, "Bad address %#lx", vaddr);
return pte_pfn(gpte) * PAGE_SIZE | (vaddr & ~PAGE_MASK);
}
/*
* We keep several page tables. This is a simple routine to find the page
* table (if any) corresponding to this top-level address the Guest has given
* us.
*/
static unsigned int find_pgdir(struct lguest *lg, unsigned long pgtable)
{
unsigned int i;
for (i = 0; i < ARRAY_SIZE(lg->pgdirs); i++)
if (lg->pgdirs[i].pgdir && lg->pgdirs[i].gpgdir == pgtable)
break;
return i;
}
/*H:435
* And this is us, creating the new page directory. If we really do
* allocate a new one (and so the kernel parts are not there), we set
* blank_pgdir.
*/
static unsigned int new_pgdir(struct lg_cpu *cpu,
unsigned long gpgdir,
int *blank_pgdir)
{
unsigned int next;
#ifdef CONFIG_X86_PAE
pmd_t *pmd_table;
#endif
/*
* We pick one entry at random to throw out. Choosing the Least
* Recently Used might be better, but this is easy.
*/
next = random32() % ARRAY_SIZE(cpu->lg->pgdirs);
/* If it's never been allocated at all before, try now. */
if (!cpu->lg->pgdirs[next].pgdir) {
cpu->lg->pgdirs[next].pgdir =
(pgd_t *)get_zeroed_page(GFP_KERNEL);
/* If the allocation fails, just keep using the one we have */
if (!cpu->lg->pgdirs[next].pgdir)
next = cpu->cpu_pgd;
else {
#ifdef CONFIG_X86_PAE
/*
* In PAE mode, allocate a pmd page and populate the
* last pgd entry.
*/
pmd_table = (pmd_t *)get_zeroed_page(GFP_KERNEL);
if (!pmd_table) {
free_page((long)cpu->lg->pgdirs[next].pgdir);
set_pgd(cpu->lg->pgdirs[next].pgdir, __pgd(0));
next = cpu->cpu_pgd;
} else {
set_pgd(cpu->lg->pgdirs[next].pgdir +
SWITCHER_PGD_INDEX,
__pgd(__pa(pmd_table) | _PAGE_PRESENT));
/*
* This is a blank page, so there are no kernel
* mappings: caller must map the stack!
*/
*blank_pgdir = 1;
}
#else
*blank_pgdir = 1;
#endif
}
}
/* Record which Guest toplevel this shadows. */
cpu->lg->pgdirs[next].gpgdir = gpgdir;
/* Release all the non-kernel mappings. */
flush_user_mappings(cpu->lg, next);
return next;
}
/*H:470
* Finally, a routine which throws away everything: all PGD entries in all
* the shadow page tables, including the Guest's kernel mappings. This is used
* when we destroy the Guest.
*/
static void release_all_pagetables(struct lguest *lg)
{
unsigned int i, j;
/* Every shadow pagetable this Guest has */
for (i = 0; i < ARRAY_SIZE(lg->pgdirs); i++)
if (lg->pgdirs[i].pgdir) {
#ifdef CONFIG_X86_PAE
pgd_t *spgd;
pmd_t *pmdpage;
unsigned int k;
/* Get the last pmd page. */
spgd = lg->pgdirs[i].pgdir + SWITCHER_PGD_INDEX;
pmdpage = __va(pgd_pfn(*spgd) << PAGE_SHIFT);
/*
* And release the pmd entries of that pmd page,
* except for the switcher pmd.
*/
for (k = 0; k < SWITCHER_PMD_INDEX; k++)
release_pmd(&pmdpage[k]);
#endif
/* Every PGD entry except the Switcher at the top */
for (j = 0; j < SWITCHER_PGD_INDEX; j++)
release_pgd(lg->pgdirs[i].pgdir + j);
}
}
/*
* We also throw away everything when a Guest tells us it's changed a kernel
* mapping. Since kernel mappings are in every page table, it's easiest to
* throw them all away. This traps the Guest in amber for a while as
* everything faults back in, but it's rare.
*/
void guest_pagetable_clear_all(struct lg_cpu *cpu)
{
release_all_pagetables(cpu->lg);
/* We need the Guest kernel stack mapped again. */
pin_stack_pages(cpu);
}
/*H:430
* (iv) Switching page tables
*
* Now we've seen all the page table setting and manipulation, let's see
* what happens when the Guest changes page tables (ie. changes the top-level
* pgdir). This occurs on almost every context switch.
*/
void guest_new_pagetable(struct lg_cpu *cpu, unsigned long pgtable)
{
int newpgdir, repin = 0;
/*
* The very first time they call this, we're actually running without
* any page tables; we've been making it up. Throw them away now.
*/
if (unlikely(cpu->linear_pages)) {
release_all_pagetables(cpu->lg);
cpu->linear_pages = false;
/* Force allocation of a new pgdir. */
newpgdir = ARRAY_SIZE(cpu->lg->pgdirs);
} else {
/* Look to see if we have this one already. */
newpgdir = find_pgdir(cpu->lg, pgtable);
}
/*
* If not, we allocate or mug an existing one: if it's a fresh one,
* repin gets set to 1.
*/
if (newpgdir == ARRAY_SIZE(cpu->lg->pgdirs))
newpgdir = new_pgdir(cpu, pgtable, &repin);
/* Change the current pgd index to the new one. */
cpu->cpu_pgd = newpgdir;
/* If it was completely blank, we map in the Guest kernel stack */
if (repin)
pin_stack_pages(cpu);
}
/*:*/
/*M:009
* Since we throw away all mappings when a kernel mapping changes, our
* performance sucks for guests using highmem. In fact, a guest with
* PAGE_OFFSET 0xc0000000 (the default) and more than about 700MB of RAM is
* usually slower than a Guest with less memory.
*
* This, of course, cannot be fixed. It would take some kind of... well, I
* don't know, but the term "puissant code-fu" comes to mind.
:*/
/*H:420
* This is the routine which actually sets the page table entry for then
* "idx"'th shadow page table.
*
* Normally, we can just throw out the old entry and replace it with 0: if they
* use it demand_page() will put the new entry in. We need to do this anyway:
* The Guest expects _PAGE_ACCESSED to be set on its PTE the first time a page
* is read from, and _PAGE_DIRTY when it's written to.
*
* But Avi Kivity pointed out that most Operating Systems (Linux included) set
* these bits on PTEs immediately anyway. This is done to save the CPU from
* having to update them, but it helps us the same way: if they set
* _PAGE_ACCESSED then we can put a read-only PTE entry in immediately, and if
* they set _PAGE_DIRTY then we can put a writable PTE entry in immediately.
*/
static void do_set_pte(struct lg_cpu *cpu, int idx,
unsigned long vaddr, pte_t gpte)
{
/* Look up the matching shadow page directory entry. */
pgd_t *spgd = spgd_addr(cpu, idx, vaddr);
#ifdef CONFIG_X86_PAE
pmd_t *spmd;
#endif
/* If the top level isn't present, there's no entry to update. */
if (pgd_flags(*spgd) & _PAGE_PRESENT) {
#ifdef CONFIG_X86_PAE
spmd = spmd_addr(cpu, *spgd, vaddr);
if (pmd_flags(*spmd) & _PAGE_PRESENT) {
#endif
/* Otherwise, start by releasing the existing entry. */
pte_t *spte = spte_addr(cpu, *spgd, vaddr);
release_pte(*spte);
/*
* If they're setting this entry as dirty or accessed,
* we might as well put that entry they've given us in
* now. This shaves 10% off a copy-on-write
* micro-benchmark.
*/
if (pte_flags(gpte) & (_PAGE_DIRTY | _PAGE_ACCESSED)) {
check_gpte(cpu, gpte);
set_pte(spte,
gpte_to_spte(cpu, gpte,
pte_flags(gpte) & _PAGE_DIRTY));
} else {
/*
* Otherwise kill it and we can demand_page()
* it in later.
*/
set_pte(spte, __pte(0));
}
#ifdef CONFIG_X86_PAE
}
#endif
}
}
/*H:410
* Updating a PTE entry is a little trickier.
*
* We keep track of several different page tables (the Guest uses one for each
* process, so it makes sense to cache at least a few). Each of these have
* identical kernel parts: ie. every mapping above PAGE_OFFSET is the same for
* all processes. So when the page table above that address changes, we update
* all the page tables, not just the current one. This is rare.
*
* The benefit is that when we have to track a new page table, we can keep all
* the kernel mappings. This speeds up context switch immensely.
*/
void guest_set_pte(struct lg_cpu *cpu,
unsigned long gpgdir, unsigned long vaddr, pte_t gpte)
{
/*
* Kernel mappings must be changed on all top levels. Slow, but doesn't
* happen often.
*/
if (vaddr >= cpu->lg->kernel_address) {
unsigned int i;
for (i = 0; i < ARRAY_SIZE(cpu->lg->pgdirs); i++)
if (cpu->lg->pgdirs[i].pgdir)
do_set_pte(cpu, i, vaddr, gpte);
} else {
/* Is this page table one we have a shadow for? */
int pgdir = find_pgdir(cpu->lg, gpgdir);
if (pgdir != ARRAY_SIZE(cpu->lg->pgdirs))
/* If so, do the update. */
do_set_pte(cpu, pgdir, vaddr, gpte);
}
}
/*H:400
* (iii) Setting up a page table entry when the Guest tells us one has changed.
*
* Just like we did in interrupts_and_traps.c, it makes sense for us to deal
* with the other side of page tables while we're here: what happens when the
* Guest asks for a page table to be updated?
*
* We already saw that demand_page() will fill in the shadow page tables when
* needed, so we can simply remove shadow page table entries whenever the Guest
* tells us they've changed. When the Guest tries to use the new entry it will
* fault and demand_page() will fix it up.
*
* So with that in mind here's our code to update a (top-level) PGD entry:
*/
void guest_set_pgd(struct lguest *lg, unsigned long gpgdir, u32 idx)
{
int pgdir;
if (idx >= SWITCHER_PGD_INDEX)
return;
/* If they're talking about a page table we have a shadow for... */
pgdir = find_pgdir(lg, gpgdir);
if (pgdir < ARRAY_SIZE(lg->pgdirs))
/* ... throw it away. */
release_pgd(lg->pgdirs[pgdir].pgdir + idx);
}
#ifdef CONFIG_X86_PAE
/* For setting a mid-level, we just throw everything away. It's easy. */
void guest_set_pmd(struct lguest *lg, unsigned long pmdp, u32 idx)
{
guest_pagetable_clear_all(&lg->cpus[0]);
}
#endif
/*H:500
* (vii) Setting up the page tables initially.
*
* When a Guest is first created, set initialize a shadow page table which
* we will populate on future faults. The Guest doesn't have any actual
* pagetables yet, so we set linear_pages to tell demand_page() to fake it
* for the moment.
*/
int init_guest_pagetable(struct lguest *lg)
{
struct lg_cpu *cpu = &lg->cpus[0];
int allocated = 0;
/* lg (and lg->cpus[]) starts zeroed: this allocates a new pgdir */
cpu->cpu_pgd = new_pgdir(cpu, 0, &allocated);
if (!allocated)
return -ENOMEM;
/* We start with a linear mapping until the initialize. */
cpu->linear_pages = true;
return 0;
}
/*H:508 When the Guest calls LHCALL_LGUEST_INIT we do more setup. */
void page_table_guest_data_init(struct lg_cpu *cpu)
{
/* We get the kernel address: above this is all kernel memory. */
if (get_user(cpu->lg->kernel_address,
&cpu->lg->lguest_data->kernel_address)
/*
* We tell the Guest that it can't use the top 2 or 4 MB
* of virtual addresses used by the Switcher.
*/
|| put_user(RESERVE_MEM * 1024 * 1024,
&cpu->lg->lguest_data->reserve_mem)) {
kill_guest(cpu, "bad guest page %p", cpu->lg->lguest_data);
return;
}
/*
* In flush_user_mappings() we loop from 0 to
* "pgd_index(lg->kernel_address)". This assumes it won't hit the
* Switcher mappings, so check that now.
*/
#ifdef CONFIG_X86_PAE
if (pgd_index(cpu->lg->kernel_address) == SWITCHER_PGD_INDEX &&
pmd_index(cpu->lg->kernel_address) == SWITCHER_PMD_INDEX)
#else
if (pgd_index(cpu->lg->kernel_address) >= SWITCHER_PGD_INDEX)
#endif
kill_guest(cpu, "bad kernel address %#lx",
cpu->lg->kernel_address);
}
/* When a Guest dies, our cleanup is fairly simple. */
void free_guest_pagetable(struct lguest *lg)
{
unsigned int i;
/* Throw away all page table pages. */
release_all_pagetables(lg);
/* Now free the top levels: free_page() can handle 0 just fine. */
for (i = 0; i < ARRAY_SIZE(lg->pgdirs); i++)
free_page((long)lg->pgdirs[i].pgdir);
}
/*H:480
* (vi) Mapping the Switcher when the Guest is about to run.
*
* The Switcher and the two pages for this CPU need to be visible in the
* Guest (and not the pages for other CPUs). We have the appropriate PTE pages
* for each CPU already set up, we just need to hook them in now we know which
* Guest is about to run on this CPU.
*/
void map_switcher_in_guest(struct lg_cpu *cpu, struct lguest_pages *pages)
{
pte_t *switcher_pte_page = __this_cpu_read(switcher_pte_pages);
pte_t regs_pte;
#ifdef CONFIG_X86_PAE
pmd_t switcher_pmd;
pmd_t *pmd_table;
switcher_pmd = pfn_pmd(__pa(switcher_pte_page) >> PAGE_SHIFT,
PAGE_KERNEL_EXEC);
/* Figure out where the pmd page is, by reading the PGD, and converting
* it to a virtual address. */
pmd_table = __va(pgd_pfn(cpu->lg->
pgdirs[cpu->cpu_pgd].pgdir[SWITCHER_PGD_INDEX])
<< PAGE_SHIFT);
/* Now write it into the shadow page table. */
set_pmd(&pmd_table[SWITCHER_PMD_INDEX], switcher_pmd);
#else
pgd_t switcher_pgd;
/*
* Make the last PGD entry for this Guest point to the Switcher's PTE
* page for this CPU (with appropriate flags).
*/
switcher_pgd = __pgd(__pa(switcher_pte_page) | __PAGE_KERNEL_EXEC);
cpu->lg->pgdirs[cpu->cpu_pgd].pgdir[SWITCHER_PGD_INDEX] = switcher_pgd;
#endif
/*
* We also change the Switcher PTE page. When we're running the Guest,
* we want the Guest's "regs" page to appear where the first Switcher
* page for this CPU is. This is an optimization: when the Switcher
* saves the Guest registers, it saves them into the first page of this
* CPU's "struct lguest_pages": if we make sure the Guest's register
* page is already mapped there, we don't have to copy them out
* again.
*/
regs_pte = pfn_pte(__pa(cpu->regs_page) >> PAGE_SHIFT, PAGE_KERNEL);
set_pte(&switcher_pte_page[pte_index((unsigned long)pages)], regs_pte);
}
/*:*/
static void free_switcher_pte_pages(void)
{
unsigned int i;
for_each_possible_cpu(i)
free_page((long)switcher_pte_page(i));
}
/*H:520
* Setting up the Switcher PTE page for given CPU is fairly easy, given
* the CPU number and the "struct page"s for the Switcher code itself.
*
* Currently the Switcher is less than a page long, so "pages" is always 1.
*/
static __init void populate_switcher_pte_page(unsigned int cpu,
struct page *switcher_page[],
unsigned int pages)
{
unsigned int i;
pte_t *pte = switcher_pte_page(cpu);
/* The first entries are easy: they map the Switcher code. */
for (i = 0; i < pages; i++) {
set_pte(&pte[i], mk_pte(switcher_page[i],
__pgprot(_PAGE_PRESENT|_PAGE_ACCESSED)));
}
/* The only other thing we map is this CPU's pair of pages. */
i = pages + cpu*2;
/* First page (Guest registers) is writable from the Guest */
set_pte(&pte[i], pfn_pte(page_to_pfn(switcher_page[i]),
__pgprot(_PAGE_PRESENT|_PAGE_ACCESSED|_PAGE_RW)));
/*
* The second page contains the "struct lguest_ro_state", and is
* read-only.
*/
set_pte(&pte[i+1], pfn_pte(page_to_pfn(switcher_page[i+1]),
__pgprot(_PAGE_PRESENT|_PAGE_ACCESSED)));
}
/*
* We've made it through the page table code. Perhaps our tired brains are
* still processing the details, or perhaps we're simply glad it's over.
*
* If nothing else, note that all this complexity in juggling shadow page tables
* in sync with the Guest's page tables is for one reason: for most Guests this
* page table dance determines how bad performance will be. This is why Xen
* uses exotic direct Guest pagetable manipulation, and why both Intel and AMD
* have implemented shadow page table support directly into hardware.
*
* There is just one file remaining in the Host.
*/
/*H:510
* At boot or module load time, init_pagetables() allocates and populates
* the Switcher PTE page for each CPU.
*/
__init int init_pagetables(struct page **switcher_page, unsigned int pages)
{
unsigned int i;
for_each_possible_cpu(i) {
switcher_pte_page(i) = (pte_t *)get_zeroed_page(GFP_KERNEL);
if (!switcher_pte_page(i)) {
free_switcher_pte_pages();
return -ENOMEM;
}
populate_switcher_pte_page(i, switcher_page, pages);
}
return 0;
}
/*:*/
/* Cleaning up simply involves freeing the PTE page for each CPU. */
void free_pagetables(void)
{
free_switcher_pte_pages();
}
| gpl-2.0 |
Nokius/android_kernel_oppo_n1 | arch/powerpc/perf/power4-pmu.c | 7279 | 17303 | /*
* Performance counter support for POWER4 (GP) and POWER4+ (GQ) processors.
*
* Copyright 2009 Paul Mackerras, IBM Corporation.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/kernel.h>
#include <linux/perf_event.h>
#include <linux/string.h>
#include <asm/reg.h>
#include <asm/cputable.h>
/*
* Bits in event code for POWER4
*/
#define PM_PMC_SH 12 /* PMC number (1-based) for direct events */
#define PM_PMC_MSK 0xf
#define PM_UNIT_SH 8 /* TTMMUX number and setting - unit select */
#define PM_UNIT_MSK 0xf
#define PM_LOWER_SH 6
#define PM_LOWER_MSK 1
#define PM_LOWER_MSKS 0x40
#define PM_BYTE_SH 4 /* Byte number of event bus to use */
#define PM_BYTE_MSK 3
#define PM_PMCSEL_MSK 7
/*
* Unit code values
*/
#define PM_FPU 1
#define PM_ISU1 2
#define PM_IFU 3
#define PM_IDU0 4
#define PM_ISU1_ALT 6
#define PM_ISU2 7
#define PM_IFU_ALT 8
#define PM_LSU0 9
#define PM_LSU1 0xc
#define PM_GPS 0xf
/*
* Bits in MMCR0 for POWER4
*/
#define MMCR0_PMC1SEL_SH 8
#define MMCR0_PMC2SEL_SH 1
#define MMCR_PMCSEL_MSK 0x1f
/*
* Bits in MMCR1 for POWER4
*/
#define MMCR1_TTM0SEL_SH 62
#define MMCR1_TTC0SEL_SH 61
#define MMCR1_TTM1SEL_SH 59
#define MMCR1_TTC1SEL_SH 58
#define MMCR1_TTM2SEL_SH 56
#define MMCR1_TTC2SEL_SH 55
#define MMCR1_TTM3SEL_SH 53
#define MMCR1_TTC3SEL_SH 52
#define MMCR1_TTMSEL_MSK 3
#define MMCR1_TD_CP_DBG0SEL_SH 50
#define MMCR1_TD_CP_DBG1SEL_SH 48
#define MMCR1_TD_CP_DBG2SEL_SH 46
#define MMCR1_TD_CP_DBG3SEL_SH 44
#define MMCR1_DEBUG0SEL_SH 43
#define MMCR1_DEBUG1SEL_SH 42
#define MMCR1_DEBUG2SEL_SH 41
#define MMCR1_DEBUG3SEL_SH 40
#define MMCR1_PMC1_ADDER_SEL_SH 39
#define MMCR1_PMC2_ADDER_SEL_SH 38
#define MMCR1_PMC6_ADDER_SEL_SH 37
#define MMCR1_PMC5_ADDER_SEL_SH 36
#define MMCR1_PMC8_ADDER_SEL_SH 35
#define MMCR1_PMC7_ADDER_SEL_SH 34
#define MMCR1_PMC3_ADDER_SEL_SH 33
#define MMCR1_PMC4_ADDER_SEL_SH 32
#define MMCR1_PMC3SEL_SH 27
#define MMCR1_PMC4SEL_SH 22
#define MMCR1_PMC5SEL_SH 17
#define MMCR1_PMC6SEL_SH 12
#define MMCR1_PMC7SEL_SH 7
#define MMCR1_PMC8SEL_SH 2 /* note bit 0 is in MMCRA for GP */
static short mmcr1_adder_bits[8] = {
MMCR1_PMC1_ADDER_SEL_SH,
MMCR1_PMC2_ADDER_SEL_SH,
MMCR1_PMC3_ADDER_SEL_SH,
MMCR1_PMC4_ADDER_SEL_SH,
MMCR1_PMC5_ADDER_SEL_SH,
MMCR1_PMC6_ADDER_SEL_SH,
MMCR1_PMC7_ADDER_SEL_SH,
MMCR1_PMC8_ADDER_SEL_SH
};
/*
* Bits in MMCRA
*/
#define MMCRA_PMC8SEL0_SH 17 /* PMC8SEL bit 0 for GP */
/*
* Layout of constraint bits:
* 6666555555555544444444443333333333222222222211111111110000000000
* 3210987654321098765432109876543210987654321098765432109876543210
* |[ >[ >[ >|||[ >[ >< >< >< >< ><><><><><><><><>
* | UC1 UC2 UC3 ||| PS1 PS2 B0 B1 B2 B3 P1P2P3P4P5P6P7P8
* \SMPL ||\TTC3SEL
* |\TTC_IFU_SEL
* \TTM2SEL0
*
* SMPL - SAMPLE_ENABLE constraint
* 56: SAMPLE_ENABLE value 0x0100_0000_0000_0000
*
* UC1 - unit constraint 1: can't have all three of FPU/ISU1/IDU0|ISU2
* 55: UC1 error 0x0080_0000_0000_0000
* 54: FPU events needed 0x0040_0000_0000_0000
* 53: ISU1 events needed 0x0020_0000_0000_0000
* 52: IDU0|ISU2 events needed 0x0010_0000_0000_0000
*
* UC2 - unit constraint 2: can't have all three of FPU/IFU/LSU0
* 51: UC2 error 0x0008_0000_0000_0000
* 50: FPU events needed 0x0004_0000_0000_0000
* 49: IFU events needed 0x0002_0000_0000_0000
* 48: LSU0 events needed 0x0001_0000_0000_0000
*
* UC3 - unit constraint 3: can't have all four of LSU0/IFU/IDU0|ISU2/ISU1
* 47: UC3 error 0x8000_0000_0000
* 46: LSU0 events needed 0x4000_0000_0000
* 45: IFU events needed 0x2000_0000_0000
* 44: IDU0|ISU2 events needed 0x1000_0000_0000
* 43: ISU1 events needed 0x0800_0000_0000
*
* TTM2SEL0
* 42: 0 = IDU0 events needed
* 1 = ISU2 events needed 0x0400_0000_0000
*
* TTC_IFU_SEL
* 41: 0 = IFU.U events needed
* 1 = IFU.L events needed 0x0200_0000_0000
*
* TTC3SEL
* 40: 0 = LSU1.U events needed
* 1 = LSU1.L events needed 0x0100_0000_0000
*
* PS1
* 39: PS1 error 0x0080_0000_0000
* 36-38: count of events needing PMC1/2/5/6 0x0070_0000_0000
*
* PS2
* 35: PS2 error 0x0008_0000_0000
* 32-34: count of events needing PMC3/4/7/8 0x0007_0000_0000
*
* B0
* 28-31: Byte 0 event source 0xf000_0000
* 1 = FPU
* 2 = ISU1
* 3 = IFU
* 4 = IDU0
* 7 = ISU2
* 9 = LSU0
* c = LSU1
* f = GPS
*
* B1, B2, B3
* 24-27, 20-23, 16-19: Byte 1, 2, 3 event sources
*
* P8
* 15: P8 error 0x8000
* 14-15: Count of events needing PMC8
*
* P1..P7
* 0-13: Count of events needing PMC1..PMC7
*
* Note: this doesn't allow events using IFU.U to be combined with events
* using IFU.L, though that is feasible (using TTM0 and TTM2). However
* there are no listed events for IFU.L (they are debug events not
* verified for performance monitoring) so this shouldn't cause a
* problem.
*/
static struct unitinfo {
unsigned long value, mask;
int unit;
int lowerbit;
} p4_unitinfo[16] = {
[PM_FPU] = { 0x44000000000000ul, 0x88000000000000ul, PM_FPU, 0 },
[PM_ISU1] = { 0x20080000000000ul, 0x88000000000000ul, PM_ISU1, 0 },
[PM_ISU1_ALT] =
{ 0x20080000000000ul, 0x88000000000000ul, PM_ISU1, 0 },
[PM_IFU] = { 0x02200000000000ul, 0x08820000000000ul, PM_IFU, 41 },
[PM_IFU_ALT] =
{ 0x02200000000000ul, 0x08820000000000ul, PM_IFU, 41 },
[PM_IDU0] = { 0x10100000000000ul, 0x80840000000000ul, PM_IDU0, 1 },
[PM_ISU2] = { 0x10140000000000ul, 0x80840000000000ul, PM_ISU2, 0 },
[PM_LSU0] = { 0x01400000000000ul, 0x08800000000000ul, PM_LSU0, 0 },
[PM_LSU1] = { 0x00000000000000ul, 0x00010000000000ul, PM_LSU1, 40 },
[PM_GPS] = { 0x00000000000000ul, 0x00000000000000ul, PM_GPS, 0 }
};
static unsigned char direct_marked_event[8] = {
(1<<2) | (1<<3), /* PMC1: PM_MRK_GRP_DISP, PM_MRK_ST_CMPL */
(1<<3) | (1<<5), /* PMC2: PM_THRESH_TIMEO, PM_MRK_BRU_FIN */
(1<<3), /* PMC3: PM_MRK_ST_CMPL_INT */
(1<<4) | (1<<5), /* PMC4: PM_MRK_GRP_CMPL, PM_MRK_CRU_FIN */
(1<<4) | (1<<5), /* PMC5: PM_MRK_GRP_TIMEO */
(1<<3) | (1<<4) | (1<<5),
/* PMC6: PM_MRK_ST_GPS, PM_MRK_FXU_FIN, PM_MRK_GRP_ISSUED */
(1<<4) | (1<<5), /* PMC7: PM_MRK_FPU_FIN, PM_MRK_INST_FIN */
(1<<4), /* PMC8: PM_MRK_LSU_FIN */
};
/*
* Returns 1 if event counts things relating to marked instructions
* and thus needs the MMCRA_SAMPLE_ENABLE bit set, or 0 if not.
*/
static int p4_marked_instr_event(u64 event)
{
int pmc, psel, unit, byte, bit;
unsigned int mask;
pmc = (event >> PM_PMC_SH) & PM_PMC_MSK;
psel = event & PM_PMCSEL_MSK;
if (pmc) {
if (direct_marked_event[pmc - 1] & (1 << psel))
return 1;
if (psel == 0) /* add events */
bit = (pmc <= 4)? pmc - 1: 8 - pmc;
else if (psel == 6) /* decode events */
bit = 4;
else
return 0;
} else
bit = psel;
byte = (event >> PM_BYTE_SH) & PM_BYTE_MSK;
unit = (event >> PM_UNIT_SH) & PM_UNIT_MSK;
mask = 0;
switch (unit) {
case PM_LSU1:
if (event & PM_LOWER_MSKS)
mask = 1 << 28; /* byte 7 bit 4 */
else
mask = 6 << 24; /* byte 3 bits 1 and 2 */
break;
case PM_LSU0:
/* byte 3, bit 3; byte 2 bits 0,2,3,4,5; byte 1 */
mask = 0x083dff00;
}
return (mask >> (byte * 8 + bit)) & 1;
}
static int p4_get_constraint(u64 event, unsigned long *maskp,
unsigned long *valp)
{
int pmc, byte, unit, lower, sh;
unsigned long mask = 0, value = 0;
int grp = -1;
pmc = (event >> PM_PMC_SH) & PM_PMC_MSK;
if (pmc) {
if (pmc > 8)
return -1;
sh = (pmc - 1) * 2;
mask |= 2 << sh;
value |= 1 << sh;
grp = ((pmc - 1) >> 1) & 1;
}
unit = (event >> PM_UNIT_SH) & PM_UNIT_MSK;
byte = (event >> PM_BYTE_SH) & PM_BYTE_MSK;
if (unit) {
lower = (event >> PM_LOWER_SH) & PM_LOWER_MSK;
/*
* Bus events on bytes 0 and 2 can be counted
* on PMC1/2/5/6; bytes 1 and 3 on PMC3/4/7/8.
*/
if (!pmc)
grp = byte & 1;
if (!p4_unitinfo[unit].unit)
return -1;
mask |= p4_unitinfo[unit].mask;
value |= p4_unitinfo[unit].value;
sh = p4_unitinfo[unit].lowerbit;
if (sh > 1)
value |= (unsigned long)lower << sh;
else if (lower != sh)
return -1;
unit = p4_unitinfo[unit].unit;
/* Set byte lane select field */
mask |= 0xfULL << (28 - 4 * byte);
value |= (unsigned long)unit << (28 - 4 * byte);
}
if (grp == 0) {
/* increment PMC1/2/5/6 field */
mask |= 0x8000000000ull;
value |= 0x1000000000ull;
} else {
/* increment PMC3/4/7/8 field */
mask |= 0x800000000ull;
value |= 0x100000000ull;
}
/* Marked instruction events need sample_enable set */
if (p4_marked_instr_event(event)) {
mask |= 1ull << 56;
value |= 1ull << 56;
}
/* PMCSEL=6 decode events on byte 2 need sample_enable clear */
if (pmc && (event & PM_PMCSEL_MSK) == 6 && byte == 2)
mask |= 1ull << 56;
*maskp = mask;
*valp = value;
return 0;
}
static unsigned int ppc_inst_cmpl[] = {
0x1001, 0x4001, 0x6001, 0x7001, 0x8001
};
static int p4_get_alternatives(u64 event, unsigned int flags, u64 alt[])
{
int i, j, na;
alt[0] = event;
na = 1;
/* 2 possibilities for PM_GRP_DISP_REJECT */
if (event == 0x8003 || event == 0x0224) {
alt[1] = event ^ (0x8003 ^ 0x0224);
return 2;
}
/* 2 possibilities for PM_ST_MISS_L1 */
if (event == 0x0c13 || event == 0x0c23) {
alt[1] = event ^ (0x0c13 ^ 0x0c23);
return 2;
}
/* several possibilities for PM_INST_CMPL */
for (i = 0; i < ARRAY_SIZE(ppc_inst_cmpl); ++i) {
if (event == ppc_inst_cmpl[i]) {
for (j = 0; j < ARRAY_SIZE(ppc_inst_cmpl); ++j)
if (j != i)
alt[na++] = ppc_inst_cmpl[j];
break;
}
}
return na;
}
static int p4_compute_mmcr(u64 event[], int n_ev,
unsigned int hwc[], unsigned long mmcr[])
{
unsigned long mmcr0 = 0, mmcr1 = 0, mmcra = 0;
unsigned int pmc, unit, byte, psel, lower;
unsigned int ttm, grp;
unsigned int pmc_inuse = 0;
unsigned int pmc_grp_use[2];
unsigned char busbyte[4];
unsigned char unituse[16];
unsigned int unitlower = 0;
int i;
if (n_ev > 8)
return -1;
/* First pass to count resource use */
pmc_grp_use[0] = pmc_grp_use[1] = 0;
memset(busbyte, 0, sizeof(busbyte));
memset(unituse, 0, sizeof(unituse));
for (i = 0; i < n_ev; ++i) {
pmc = (event[i] >> PM_PMC_SH) & PM_PMC_MSK;
if (pmc) {
if (pmc_inuse & (1 << (pmc - 1)))
return -1;
pmc_inuse |= 1 << (pmc - 1);
/* count 1/2/5/6 vs 3/4/7/8 use */
++pmc_grp_use[((pmc - 1) >> 1) & 1];
}
unit = (event[i] >> PM_UNIT_SH) & PM_UNIT_MSK;
byte = (event[i] >> PM_BYTE_SH) & PM_BYTE_MSK;
lower = (event[i] >> PM_LOWER_SH) & PM_LOWER_MSK;
if (unit) {
if (!pmc)
++pmc_grp_use[byte & 1];
if (unit == 6 || unit == 8)
/* map alt ISU1/IFU codes: 6->2, 8->3 */
unit = (unit >> 1) - 1;
if (busbyte[byte] && busbyte[byte] != unit)
return -1;
busbyte[byte] = unit;
lower <<= unit;
if (unituse[unit] && lower != (unitlower & lower))
return -1;
unituse[unit] = 1;
unitlower |= lower;
}
}
if (pmc_grp_use[0] > 4 || pmc_grp_use[1] > 4)
return -1;
/*
* Assign resources and set multiplexer selects.
*
* Units 1,2,3 are on TTM0, 4,6,7 on TTM1, 8,10 on TTM2.
* Each TTMx can only select one unit, but since
* units 2 and 6 are both ISU1, and 3 and 8 are both IFU,
* we have some choices.
*/
if (unituse[2] & (unituse[1] | (unituse[3] & unituse[9]))) {
unituse[6] = 1; /* Move 2 to 6 */
unituse[2] = 0;
}
if (unituse[3] & (unituse[1] | unituse[2])) {
unituse[8] = 1; /* Move 3 to 8 */
unituse[3] = 0;
unitlower = (unitlower & ~8) | ((unitlower & 8) << 5);
}
/* Check only one unit per TTMx */
if (unituse[1] + unituse[2] + unituse[3] > 1 ||
unituse[4] + unituse[6] + unituse[7] > 1 ||
unituse[8] + unituse[9] > 1 ||
(unituse[5] | unituse[10] | unituse[11] |
unituse[13] | unituse[14]))
return -1;
/* Set TTMxSEL fields. Note, units 1-3 => TTM0SEL codes 0-2 */
mmcr1 |= (unsigned long)(unituse[3] * 2 + unituse[2])
<< MMCR1_TTM0SEL_SH;
mmcr1 |= (unsigned long)(unituse[7] * 3 + unituse[6] * 2)
<< MMCR1_TTM1SEL_SH;
mmcr1 |= (unsigned long)unituse[9] << MMCR1_TTM2SEL_SH;
/* Set TTCxSEL fields. */
if (unitlower & 0xe)
mmcr1 |= 1ull << MMCR1_TTC0SEL_SH;
if (unitlower & 0xf0)
mmcr1 |= 1ull << MMCR1_TTC1SEL_SH;
if (unitlower & 0xf00)
mmcr1 |= 1ull << MMCR1_TTC2SEL_SH;
if (unitlower & 0x7000)
mmcr1 |= 1ull << MMCR1_TTC3SEL_SH;
/* Set byte lane select fields. */
for (byte = 0; byte < 4; ++byte) {
unit = busbyte[byte];
if (!unit)
continue;
if (unit == 0xf) {
/* special case for GPS */
mmcr1 |= 1ull << (MMCR1_DEBUG0SEL_SH - byte);
} else {
if (!unituse[unit])
ttm = unit - 1; /* 2->1, 3->2 */
else
ttm = unit >> 2;
mmcr1 |= (unsigned long)ttm
<< (MMCR1_TD_CP_DBG0SEL_SH - 2 * byte);
}
}
/* Second pass: assign PMCs, set PMCxSEL and PMCx_ADDER_SEL fields */
for (i = 0; i < n_ev; ++i) {
pmc = (event[i] >> PM_PMC_SH) & PM_PMC_MSK;
unit = (event[i] >> PM_UNIT_SH) & PM_UNIT_MSK;
byte = (event[i] >> PM_BYTE_SH) & PM_BYTE_MSK;
psel = event[i] & PM_PMCSEL_MSK;
if (!pmc) {
/* Bus event or 00xxx direct event (off or cycles) */
if (unit)
psel |= 0x10 | ((byte & 2) << 2);
for (pmc = 0; pmc < 8; ++pmc) {
if (pmc_inuse & (1 << pmc))
continue;
grp = (pmc >> 1) & 1;
if (unit) {
if (grp == (byte & 1))
break;
} else if (pmc_grp_use[grp] < 4) {
++pmc_grp_use[grp];
break;
}
}
pmc_inuse |= 1 << pmc;
} else {
/* Direct event */
--pmc;
if (psel == 0 && (byte & 2))
/* add events on higher-numbered bus */
mmcr1 |= 1ull << mmcr1_adder_bits[pmc];
else if (psel == 6 && byte == 3)
/* seem to need to set sample_enable here */
mmcra |= MMCRA_SAMPLE_ENABLE;
psel |= 8;
}
if (pmc <= 1)
mmcr0 |= psel << (MMCR0_PMC1SEL_SH - 7 * pmc);
else
mmcr1 |= psel << (MMCR1_PMC3SEL_SH - 5 * (pmc - 2));
if (pmc == 7) /* PMC8 */
mmcra |= (psel & 1) << MMCRA_PMC8SEL0_SH;
hwc[i] = pmc;
if (p4_marked_instr_event(event[i]))
mmcra |= MMCRA_SAMPLE_ENABLE;
}
if (pmc_inuse & 1)
mmcr0 |= MMCR0_PMC1CE;
if (pmc_inuse & 0xfe)
mmcr0 |= MMCR0_PMCjCE;
mmcra |= 0x2000; /* mark only one IOP per PPC instruction */
/* Return MMCRx values */
mmcr[0] = mmcr0;
mmcr[1] = mmcr1;
mmcr[2] = mmcra;
return 0;
}
static void p4_disable_pmc(unsigned int pmc, unsigned long mmcr[])
{
/*
* Setting the PMCxSEL field to 0 disables PMC x.
* (Note that pmc is 0-based here, not 1-based.)
*/
if (pmc <= 1) {
mmcr[0] &= ~(0x1fUL << (MMCR0_PMC1SEL_SH - 7 * pmc));
} else {
mmcr[1] &= ~(0x1fUL << (MMCR1_PMC3SEL_SH - 5 * (pmc - 2)));
if (pmc == 7)
mmcr[2] &= ~(1UL << MMCRA_PMC8SEL0_SH);
}
}
static int p4_generic_events[] = {
[PERF_COUNT_HW_CPU_CYCLES] = 7,
[PERF_COUNT_HW_INSTRUCTIONS] = 0x1001,
[PERF_COUNT_HW_CACHE_REFERENCES] = 0x8c10, /* PM_LD_REF_L1 */
[PERF_COUNT_HW_CACHE_MISSES] = 0x3c10, /* PM_LD_MISS_L1 */
[PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = 0x330, /* PM_BR_ISSUED */
[PERF_COUNT_HW_BRANCH_MISSES] = 0x331, /* PM_BR_MPRED_CR */
};
#define C(x) PERF_COUNT_HW_CACHE_##x
/*
* Table of generalized cache-related events.
* 0 means not supported, -1 means nonsensical, other values
* are event codes.
*/
static int power4_cache_events[C(MAX)][C(OP_MAX)][C(RESULT_MAX)] = {
[C(L1D)] = { /* RESULT_ACCESS RESULT_MISS */
[C(OP_READ)] = { 0x8c10, 0x3c10 },
[C(OP_WRITE)] = { 0x7c10, 0xc13 },
[C(OP_PREFETCH)] = { 0xc35, 0 },
},
[C(L1I)] = { /* RESULT_ACCESS RESULT_MISS */
[C(OP_READ)] = { 0, 0 },
[C(OP_WRITE)] = { -1, -1 },
[C(OP_PREFETCH)] = { 0, 0 },
},
[C(LL)] = { /* RESULT_ACCESS RESULT_MISS */
[C(OP_READ)] = { 0, 0 },
[C(OP_WRITE)] = { 0, 0 },
[C(OP_PREFETCH)] = { 0xc34, 0 },
},
[C(DTLB)] = { /* RESULT_ACCESS RESULT_MISS */
[C(OP_READ)] = { 0, 0x904 },
[C(OP_WRITE)] = { -1, -1 },
[C(OP_PREFETCH)] = { -1, -1 },
},
[C(ITLB)] = { /* RESULT_ACCESS RESULT_MISS */
[C(OP_READ)] = { 0, 0x900 },
[C(OP_WRITE)] = { -1, -1 },
[C(OP_PREFETCH)] = { -1, -1 },
},
[C(BPU)] = { /* RESULT_ACCESS RESULT_MISS */
[C(OP_READ)] = { 0x330, 0x331 },
[C(OP_WRITE)] = { -1, -1 },
[C(OP_PREFETCH)] = { -1, -1 },
},
[C(NODE)] = { /* RESULT_ACCESS RESULT_MISS */
[C(OP_READ)] = { -1, -1 },
[C(OP_WRITE)] = { -1, -1 },
[C(OP_PREFETCH)] = { -1, -1 },
},
};
static struct power_pmu power4_pmu = {
.name = "POWER4/4+",
.n_counter = 8,
.max_alternatives = 5,
.add_fields = 0x0000001100005555ul,
.test_adder = 0x0011083300000000ul,
.compute_mmcr = p4_compute_mmcr,
.get_constraint = p4_get_constraint,
.get_alternatives = p4_get_alternatives,
.disable_pmc = p4_disable_pmc,
.n_generic = ARRAY_SIZE(p4_generic_events),
.generic_events = p4_generic_events,
.cache_events = &power4_cache_events,
.flags = PPMU_NO_SIPR | PPMU_NO_CONT_SAMPLING,
};
static int __init init_power4_pmu(void)
{
if (!cur_cpu_spec->oprofile_cpu_type ||
strcmp(cur_cpu_spec->oprofile_cpu_type, "ppc64/power4"))
return -ENODEV;
return register_power_pmu(&power4_pmu);
}
early_initcall(init_power4_pmu);
| gpl-2.0 |
shankarathi07/linux_lg_jb | sound/core/seq/seq_clientmgr.c | 7535 | 67346 | /*
* ALSA sequencer Client Manager
* Copyright (c) 1998-2001 by Frank van de Pol <fvdpol@coil.demon.nl>
* Jaroslav Kysela <perex@perex.cz>
* Takashi Iwai <tiwai@suse.de>
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/init.h>
#include <linux/export.h>
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/minors.h>
#include <linux/kmod.h>
#include <sound/seq_kernel.h>
#include "seq_clientmgr.h"
#include "seq_memory.h"
#include "seq_queue.h"
#include "seq_timer.h"
#include "seq_info.h"
#include "seq_system.h"
#include <sound/seq_device.h>
#ifdef CONFIG_COMPAT
#include <linux/compat.h>
#endif
/* Client Manager
* this module handles the connections of userland and kernel clients
*
*/
/*
* There are four ranges of client numbers (last two shared):
* 0..15: global clients
* 16..127: statically allocated client numbers for cards 0..27
* 128..191: dynamically allocated client numbers for cards 28..31
* 128..191: dynamically allocated client numbers for applications
*/
/* number of kernel non-card clients */
#define SNDRV_SEQ_GLOBAL_CLIENTS 16
/* clients per cards, for static clients */
#define SNDRV_SEQ_CLIENTS_PER_CARD 4
/* dynamically allocated client numbers (both kernel drivers and user space) */
#define SNDRV_SEQ_DYNAMIC_CLIENTS_BEGIN 128
#define SNDRV_SEQ_LFLG_INPUT 0x0001
#define SNDRV_SEQ_LFLG_OUTPUT 0x0002
#define SNDRV_SEQ_LFLG_OPEN (SNDRV_SEQ_LFLG_INPUT|SNDRV_SEQ_LFLG_OUTPUT)
static DEFINE_SPINLOCK(clients_lock);
static DEFINE_MUTEX(register_mutex);
/*
* client table
*/
static char clienttablock[SNDRV_SEQ_MAX_CLIENTS];
static struct snd_seq_client *clienttab[SNDRV_SEQ_MAX_CLIENTS];
static struct snd_seq_usage client_usage;
/*
* prototypes
*/
static int bounce_error_event(struct snd_seq_client *client,
struct snd_seq_event *event,
int err, int atomic, int hop);
static int snd_seq_deliver_single_event(struct snd_seq_client *client,
struct snd_seq_event *event,
int filter, int atomic, int hop);
/*
*/
static inline mm_segment_t snd_enter_user(void)
{
mm_segment_t fs = get_fs();
set_fs(get_ds());
return fs;
}
static inline void snd_leave_user(mm_segment_t fs)
{
set_fs(fs);
}
/*
*/
static inline unsigned short snd_seq_file_flags(struct file *file)
{
switch (file->f_mode & (FMODE_READ | FMODE_WRITE)) {
case FMODE_WRITE:
return SNDRV_SEQ_LFLG_OUTPUT;
case FMODE_READ:
return SNDRV_SEQ_LFLG_INPUT;
default:
return SNDRV_SEQ_LFLG_OPEN;
}
}
static inline int snd_seq_write_pool_allocated(struct snd_seq_client *client)
{
return snd_seq_total_cells(client->pool) > 0;
}
/* return pointer to client structure for specified id */
static struct snd_seq_client *clientptr(int clientid)
{
if (clientid < 0 || clientid >= SNDRV_SEQ_MAX_CLIENTS) {
snd_printd("Seq: oops. Trying to get pointer to client %d\n",
clientid);
return NULL;
}
return clienttab[clientid];
}
struct snd_seq_client *snd_seq_client_use_ptr(int clientid)
{
unsigned long flags;
struct snd_seq_client *client;
if (clientid < 0 || clientid >= SNDRV_SEQ_MAX_CLIENTS) {
snd_printd("Seq: oops. Trying to get pointer to client %d\n",
clientid);
return NULL;
}
spin_lock_irqsave(&clients_lock, flags);
client = clientptr(clientid);
if (client)
goto __lock;
if (clienttablock[clientid]) {
spin_unlock_irqrestore(&clients_lock, flags);
return NULL;
}
spin_unlock_irqrestore(&clients_lock, flags);
#ifdef CONFIG_MODULES
if (!in_interrupt()) {
static char client_requested[SNDRV_SEQ_GLOBAL_CLIENTS];
static char card_requested[SNDRV_CARDS];
if (clientid < SNDRV_SEQ_GLOBAL_CLIENTS) {
int idx;
if (!client_requested[clientid]) {
client_requested[clientid] = 1;
for (idx = 0; idx < 15; idx++) {
if (seq_client_load[idx] < 0)
break;
if (seq_client_load[idx] == clientid) {
request_module("snd-seq-client-%i",
clientid);
break;
}
}
}
} else if (clientid < SNDRV_SEQ_DYNAMIC_CLIENTS_BEGIN) {
int card = (clientid - SNDRV_SEQ_GLOBAL_CLIENTS) /
SNDRV_SEQ_CLIENTS_PER_CARD;
if (card < snd_ecards_limit) {
if (! card_requested[card]) {
card_requested[card] = 1;
snd_request_card(card);
}
snd_seq_device_load_drivers();
}
}
spin_lock_irqsave(&clients_lock, flags);
client = clientptr(clientid);
if (client)
goto __lock;
spin_unlock_irqrestore(&clients_lock, flags);
}
#endif
return NULL;
__lock:
snd_use_lock_use(&client->use_lock);
spin_unlock_irqrestore(&clients_lock, flags);
return client;
}
static void usage_alloc(struct snd_seq_usage *res, int num)
{
res->cur += num;
if (res->cur > res->peak)
res->peak = res->cur;
}
static void usage_free(struct snd_seq_usage *res, int num)
{
res->cur -= num;
}
/* initialise data structures */
int __init client_init_data(void)
{
/* zap out the client table */
memset(&clienttablock, 0, sizeof(clienttablock));
memset(&clienttab, 0, sizeof(clienttab));
return 0;
}
static struct snd_seq_client *seq_create_client1(int client_index, int poolsize)
{
unsigned long flags;
int c;
struct snd_seq_client *client;
/* init client data */
client = kzalloc(sizeof(*client), GFP_KERNEL);
if (client == NULL)
return NULL;
client->pool = snd_seq_pool_new(poolsize);
if (client->pool == NULL) {
kfree(client);
return NULL;
}
client->type = NO_CLIENT;
snd_use_lock_init(&client->use_lock);
rwlock_init(&client->ports_lock);
mutex_init(&client->ports_mutex);
INIT_LIST_HEAD(&client->ports_list_head);
/* find free slot in the client table */
spin_lock_irqsave(&clients_lock, flags);
if (client_index < 0) {
for (c = SNDRV_SEQ_DYNAMIC_CLIENTS_BEGIN;
c < SNDRV_SEQ_MAX_CLIENTS;
c++) {
if (clienttab[c] || clienttablock[c])
continue;
clienttab[client->number = c] = client;
spin_unlock_irqrestore(&clients_lock, flags);
return client;
}
} else {
if (clienttab[client_index] == NULL && !clienttablock[client_index]) {
clienttab[client->number = client_index] = client;
spin_unlock_irqrestore(&clients_lock, flags);
return client;
}
}
spin_unlock_irqrestore(&clients_lock, flags);
snd_seq_pool_delete(&client->pool);
kfree(client);
return NULL; /* no free slot found or busy, return failure code */
}
static int seq_free_client1(struct snd_seq_client *client)
{
unsigned long flags;
if (!client)
return 0;
snd_seq_delete_all_ports(client);
snd_seq_queue_client_leave(client->number);
spin_lock_irqsave(&clients_lock, flags);
clienttablock[client->number] = 1;
clienttab[client->number] = NULL;
spin_unlock_irqrestore(&clients_lock, flags);
snd_use_lock_sync(&client->use_lock);
snd_seq_queue_client_termination(client->number);
if (client->pool)
snd_seq_pool_delete(&client->pool);
spin_lock_irqsave(&clients_lock, flags);
clienttablock[client->number] = 0;
spin_unlock_irqrestore(&clients_lock, flags);
return 0;
}
static void seq_free_client(struct snd_seq_client * client)
{
mutex_lock(®ister_mutex);
switch (client->type) {
case NO_CLIENT:
snd_printk(KERN_WARNING "Seq: Trying to free unused client %d\n",
client->number);
break;
case USER_CLIENT:
case KERNEL_CLIENT:
seq_free_client1(client);
usage_free(&client_usage, 1);
break;
default:
snd_printk(KERN_ERR "Seq: Trying to free client %d with undefined type = %d\n",
client->number, client->type);
}
mutex_unlock(®ister_mutex);
snd_seq_system_client_ev_client_exit(client->number);
}
/* -------------------------------------------------------- */
/* create a user client */
static int snd_seq_open(struct inode *inode, struct file *file)
{
int c, mode; /* client id */
struct snd_seq_client *client;
struct snd_seq_user_client *user;
int err;
err = nonseekable_open(inode, file);
if (err < 0)
return err;
if (mutex_lock_interruptible(®ister_mutex))
return -ERESTARTSYS;
client = seq_create_client1(-1, SNDRV_SEQ_DEFAULT_EVENTS);
if (client == NULL) {
mutex_unlock(®ister_mutex);
return -ENOMEM; /* failure code */
}
mode = snd_seq_file_flags(file);
if (mode & SNDRV_SEQ_LFLG_INPUT)
client->accept_input = 1;
if (mode & SNDRV_SEQ_LFLG_OUTPUT)
client->accept_output = 1;
user = &client->data.user;
user->fifo = NULL;
user->fifo_pool_size = 0;
if (mode & SNDRV_SEQ_LFLG_INPUT) {
user->fifo_pool_size = SNDRV_SEQ_DEFAULT_CLIENT_EVENTS;
user->fifo = snd_seq_fifo_new(user->fifo_pool_size);
if (user->fifo == NULL) {
seq_free_client1(client);
kfree(client);
mutex_unlock(®ister_mutex);
return -ENOMEM;
}
}
usage_alloc(&client_usage, 1);
client->type = USER_CLIENT;
mutex_unlock(®ister_mutex);
c = client->number;
file->private_data = client;
/* fill client data */
user->file = file;
sprintf(client->name, "Client-%d", c);
/* make others aware this new client */
snd_seq_system_client_ev_client_start(c);
return 0;
}
/* delete a user client */
static int snd_seq_release(struct inode *inode, struct file *file)
{
struct snd_seq_client *client = file->private_data;
if (client) {
seq_free_client(client);
if (client->data.user.fifo)
snd_seq_fifo_delete(&client->data.user.fifo);
kfree(client);
}
return 0;
}
/* handle client read() */
/* possible error values:
* -ENXIO invalid client or file open mode
* -ENOSPC FIFO overflow (the flag is cleared after this error report)
* -EINVAL no enough user-space buffer to write the whole event
* -EFAULT seg. fault during copy to user space
*/
static ssize_t snd_seq_read(struct file *file, char __user *buf, size_t count,
loff_t *offset)
{
struct snd_seq_client *client = file->private_data;
struct snd_seq_fifo *fifo;
int err;
long result = 0;
struct snd_seq_event_cell *cell;
if (!(snd_seq_file_flags(file) & SNDRV_SEQ_LFLG_INPUT))
return -ENXIO;
if (!access_ok(VERIFY_WRITE, buf, count))
return -EFAULT;
/* check client structures are in place */
if (snd_BUG_ON(!client))
return -ENXIO;
if (!client->accept_input || (fifo = client->data.user.fifo) == NULL)
return -ENXIO;
if (atomic_read(&fifo->overflow) > 0) {
/* buffer overflow is detected */
snd_seq_fifo_clear(fifo);
/* return error code */
return -ENOSPC;
}
cell = NULL;
err = 0;
snd_seq_fifo_lock(fifo);
/* while data available in queue */
while (count >= sizeof(struct snd_seq_event)) {
int nonblock;
nonblock = (file->f_flags & O_NONBLOCK) || result > 0;
if ((err = snd_seq_fifo_cell_out(fifo, &cell, nonblock)) < 0) {
break;
}
if (snd_seq_ev_is_variable(&cell->event)) {
struct snd_seq_event tmpev;
tmpev = cell->event;
tmpev.data.ext.len &= ~SNDRV_SEQ_EXT_MASK;
if (copy_to_user(buf, &tmpev, sizeof(struct snd_seq_event))) {
err = -EFAULT;
break;
}
count -= sizeof(struct snd_seq_event);
buf += sizeof(struct snd_seq_event);
err = snd_seq_expand_var_event(&cell->event, count,
(char __force *)buf, 0,
sizeof(struct snd_seq_event));
if (err < 0)
break;
result += err;
count -= err;
buf += err;
} else {
if (copy_to_user(buf, &cell->event, sizeof(struct snd_seq_event))) {
err = -EFAULT;
break;
}
count -= sizeof(struct snd_seq_event);
buf += sizeof(struct snd_seq_event);
}
snd_seq_cell_free(cell);
cell = NULL; /* to be sure */
result += sizeof(struct snd_seq_event);
}
if (err < 0) {
if (cell)
snd_seq_fifo_cell_putback(fifo, cell);
if (err == -EAGAIN && result > 0)
err = 0;
}
snd_seq_fifo_unlock(fifo);
return (err < 0) ? err : result;
}
/*
* check access permission to the port
*/
static int check_port_perm(struct snd_seq_client_port *port, unsigned int flags)
{
if ((port->capability & flags) != flags)
return 0;
return flags;
}
/*
* check if the destination client is available, and return the pointer
* if filter is non-zero, client filter bitmap is tested.
*/
static struct snd_seq_client *get_event_dest_client(struct snd_seq_event *event,
int filter)
{
struct snd_seq_client *dest;
dest = snd_seq_client_use_ptr(event->dest.client);
if (dest == NULL)
return NULL;
if (! dest->accept_input)
goto __not_avail;
if ((dest->filter & SNDRV_SEQ_FILTER_USE_EVENT) &&
! test_bit(event->type, dest->event_filter))
goto __not_avail;
if (filter && !(dest->filter & filter))
goto __not_avail;
return dest; /* ok - accessible */
__not_avail:
snd_seq_client_unlock(dest);
return NULL;
}
/*
* Return the error event.
*
* If the receiver client is a user client, the original event is
* encapsulated in SNDRV_SEQ_EVENT_BOUNCE as variable length event. If
* the original event is also variable length, the external data is
* copied after the event record.
* If the receiver client is a kernel client, the original event is
* quoted in SNDRV_SEQ_EVENT_KERNEL_ERROR, since this requires no extra
* kmalloc.
*/
static int bounce_error_event(struct snd_seq_client *client,
struct snd_seq_event *event,
int err, int atomic, int hop)
{
struct snd_seq_event bounce_ev;
int result;
if (client == NULL ||
! (client->filter & SNDRV_SEQ_FILTER_BOUNCE) ||
! client->accept_input)
return 0; /* ignored */
/* set up quoted error */
memset(&bounce_ev, 0, sizeof(bounce_ev));
bounce_ev.type = SNDRV_SEQ_EVENT_KERNEL_ERROR;
bounce_ev.flags = SNDRV_SEQ_EVENT_LENGTH_FIXED;
bounce_ev.queue = SNDRV_SEQ_QUEUE_DIRECT;
bounce_ev.source.client = SNDRV_SEQ_CLIENT_SYSTEM;
bounce_ev.source.port = SNDRV_SEQ_PORT_SYSTEM_ANNOUNCE;
bounce_ev.dest.client = client->number;
bounce_ev.dest.port = event->source.port;
bounce_ev.data.quote.origin = event->dest;
bounce_ev.data.quote.event = event;
bounce_ev.data.quote.value = -err; /* use positive value */
result = snd_seq_deliver_single_event(NULL, &bounce_ev, 0, atomic, hop + 1);
if (result < 0) {
client->event_lost++;
return result;
}
return result;
}
/*
* rewrite the time-stamp of the event record with the curren time
* of the given queue.
* return non-zero if updated.
*/
static int update_timestamp_of_queue(struct snd_seq_event *event,
int queue, int real_time)
{
struct snd_seq_queue *q;
q = queueptr(queue);
if (! q)
return 0;
event->queue = queue;
event->flags &= ~SNDRV_SEQ_TIME_STAMP_MASK;
if (real_time) {
event->time.time = snd_seq_timer_get_cur_time(q->timer);
event->flags |= SNDRV_SEQ_TIME_STAMP_REAL;
} else {
event->time.tick = snd_seq_timer_get_cur_tick(q->timer);
event->flags |= SNDRV_SEQ_TIME_STAMP_TICK;
}
queuefree(q);
return 1;
}
/*
* deliver an event to the specified destination.
* if filter is non-zero, client filter bitmap is tested.
*
* RETURN VALUE: 0 : if succeeded
* <0 : error
*/
static int snd_seq_deliver_single_event(struct snd_seq_client *client,
struct snd_seq_event *event,
int filter, int atomic, int hop)
{
struct snd_seq_client *dest = NULL;
struct snd_seq_client_port *dest_port = NULL;
int result = -ENOENT;
int direct;
direct = snd_seq_ev_is_direct(event);
dest = get_event_dest_client(event, filter);
if (dest == NULL)
goto __skip;
dest_port = snd_seq_port_use_ptr(dest, event->dest.port);
if (dest_port == NULL)
goto __skip;
/* check permission */
if (! check_port_perm(dest_port, SNDRV_SEQ_PORT_CAP_WRITE)) {
result = -EPERM;
goto __skip;
}
if (dest_port->timestamping)
update_timestamp_of_queue(event, dest_port->time_queue,
dest_port->time_real);
switch (dest->type) {
case USER_CLIENT:
if (dest->data.user.fifo)
result = snd_seq_fifo_event_in(dest->data.user.fifo, event);
break;
case KERNEL_CLIENT:
if (dest_port->event_input == NULL)
break;
result = dest_port->event_input(event, direct,
dest_port->private_data,
atomic, hop);
break;
default:
break;
}
__skip:
if (dest_port)
snd_seq_port_unlock(dest_port);
if (dest)
snd_seq_client_unlock(dest);
if (result < 0 && !direct) {
result = bounce_error_event(client, event, result, atomic, hop);
}
return result;
}
/*
* send the event to all subscribers:
*/
static int deliver_to_subscribers(struct snd_seq_client *client,
struct snd_seq_event *event,
int atomic, int hop)
{
struct snd_seq_subscribers *subs;
int err = 0, num_ev = 0;
struct snd_seq_event event_saved;
struct snd_seq_client_port *src_port;
struct snd_seq_port_subs_info *grp;
src_port = snd_seq_port_use_ptr(client, event->source.port);
if (src_port == NULL)
return -EINVAL; /* invalid source port */
/* save original event record */
event_saved = *event;
grp = &src_port->c_src;
/* lock list */
if (atomic)
read_lock(&grp->list_lock);
else
down_read(&grp->list_mutex);
list_for_each_entry(subs, &grp->list_head, src_list) {
event->dest = subs->info.dest;
if (subs->info.flags & SNDRV_SEQ_PORT_SUBS_TIMESTAMP)
/* convert time according to flag with subscription */
update_timestamp_of_queue(event, subs->info.queue,
subs->info.flags & SNDRV_SEQ_PORT_SUBS_TIME_REAL);
err = snd_seq_deliver_single_event(client, event,
0, atomic, hop);
if (err < 0)
break;
num_ev++;
/* restore original event record */
*event = event_saved;
}
if (atomic)
read_unlock(&grp->list_lock);
else
up_read(&grp->list_mutex);
*event = event_saved; /* restore */
snd_seq_port_unlock(src_port);
return (err < 0) ? err : num_ev;
}
#ifdef SUPPORT_BROADCAST
/*
* broadcast to all ports:
*/
static int port_broadcast_event(struct snd_seq_client *client,
struct snd_seq_event *event,
int atomic, int hop)
{
int num_ev = 0, err = 0;
struct snd_seq_client *dest_client;
struct snd_seq_client_port *port;
dest_client = get_event_dest_client(event, SNDRV_SEQ_FILTER_BROADCAST);
if (dest_client == NULL)
return 0; /* no matching destination */
read_lock(&dest_client->ports_lock);
list_for_each_entry(port, &dest_client->ports_list_head, list) {
event->dest.port = port->addr.port;
/* pass NULL as source client to avoid error bounce */
err = snd_seq_deliver_single_event(NULL, event,
SNDRV_SEQ_FILTER_BROADCAST,
atomic, hop);
if (err < 0)
break;
num_ev++;
}
read_unlock(&dest_client->ports_lock);
snd_seq_client_unlock(dest_client);
event->dest.port = SNDRV_SEQ_ADDRESS_BROADCAST; /* restore */
return (err < 0) ? err : num_ev;
}
/*
* send the event to all clients:
* if destination port is also ADDRESS_BROADCAST, deliver to all ports.
*/
static int broadcast_event(struct snd_seq_client *client,
struct snd_seq_event *event, int atomic, int hop)
{
int err = 0, num_ev = 0;
int dest;
struct snd_seq_addr addr;
addr = event->dest; /* save */
for (dest = 0; dest < SNDRV_SEQ_MAX_CLIENTS; dest++) {
/* don't send to itself */
if (dest == client->number)
continue;
event->dest.client = dest;
event->dest.port = addr.port;
if (addr.port == SNDRV_SEQ_ADDRESS_BROADCAST)
err = port_broadcast_event(client, event, atomic, hop);
else
/* pass NULL as source client to avoid error bounce */
err = snd_seq_deliver_single_event(NULL, event,
SNDRV_SEQ_FILTER_BROADCAST,
atomic, hop);
if (err < 0)
break;
num_ev += err;
}
event->dest = addr; /* restore */
return (err < 0) ? err : num_ev;
}
/* multicast - not supported yet */
static int multicast_event(struct snd_seq_client *client, struct snd_seq_event *event,
int atomic, int hop)
{
snd_printd("seq: multicast not supported yet.\n");
return 0; /* ignored */
}
#endif /* SUPPORT_BROADCAST */
/* deliver an event to the destination port(s).
* if the event is to subscribers or broadcast, the event is dispatched
* to multiple targets.
*
* RETURN VALUE: n > 0 : the number of delivered events.
* n == 0 : the event was not passed to any client.
* n < 0 : error - event was not processed.
*/
static int snd_seq_deliver_event(struct snd_seq_client *client, struct snd_seq_event *event,
int atomic, int hop)
{
int result;
hop++;
if (hop >= SNDRV_SEQ_MAX_HOPS) {
snd_printd("too long delivery path (%d:%d->%d:%d)\n",
event->source.client, event->source.port,
event->dest.client, event->dest.port);
return -EMLINK;
}
if (event->queue == SNDRV_SEQ_ADDRESS_SUBSCRIBERS ||
event->dest.client == SNDRV_SEQ_ADDRESS_SUBSCRIBERS)
result = deliver_to_subscribers(client, event, atomic, hop);
#ifdef SUPPORT_BROADCAST
else if (event->queue == SNDRV_SEQ_ADDRESS_BROADCAST ||
event->dest.client == SNDRV_SEQ_ADDRESS_BROADCAST)
result = broadcast_event(client, event, atomic, hop);
else if (event->dest.client >= SNDRV_SEQ_MAX_CLIENTS)
result = multicast_event(client, event, atomic, hop);
else if (event->dest.port == SNDRV_SEQ_ADDRESS_BROADCAST)
result = port_broadcast_event(client, event, atomic, hop);
#endif
else
result = snd_seq_deliver_single_event(client, event, 0, atomic, hop);
return result;
}
/*
* dispatch an event cell:
* This function is called only from queue check routines in timer
* interrupts or after enqueued.
* The event cell shall be released or re-queued in this function.
*
* RETURN VALUE: n > 0 : the number of delivered events.
* n == 0 : the event was not passed to any client.
* n < 0 : error - event was not processed.
*/
int snd_seq_dispatch_event(struct snd_seq_event_cell *cell, int atomic, int hop)
{
struct snd_seq_client *client;
int result;
if (snd_BUG_ON(!cell))
return -EINVAL;
client = snd_seq_client_use_ptr(cell->event.source.client);
if (client == NULL) {
snd_seq_cell_free(cell); /* release this cell */
return -EINVAL;
}
if (cell->event.type == SNDRV_SEQ_EVENT_NOTE) {
/* NOTE event:
* the event cell is re-used as a NOTE-OFF event and
* enqueued again.
*/
struct snd_seq_event tmpev, *ev;
/* reserve this event to enqueue note-off later */
tmpev = cell->event;
tmpev.type = SNDRV_SEQ_EVENT_NOTEON;
result = snd_seq_deliver_event(client, &tmpev, atomic, hop);
/*
* This was originally a note event. We now re-use the
* cell for the note-off event.
*/
ev = &cell->event;
ev->type = SNDRV_SEQ_EVENT_NOTEOFF;
ev->flags |= SNDRV_SEQ_PRIORITY_HIGH;
/* add the duration time */
switch (ev->flags & SNDRV_SEQ_TIME_STAMP_MASK) {
case SNDRV_SEQ_TIME_STAMP_TICK:
ev->time.tick += ev->data.note.duration;
break;
case SNDRV_SEQ_TIME_STAMP_REAL:
/* unit for duration is ms */
ev->time.time.tv_nsec += 1000000 * (ev->data.note.duration % 1000);
ev->time.time.tv_sec += ev->data.note.duration / 1000 +
ev->time.time.tv_nsec / 1000000000;
ev->time.time.tv_nsec %= 1000000000;
break;
}
ev->data.note.velocity = ev->data.note.off_velocity;
/* Now queue this cell as the note off event */
if (snd_seq_enqueue_event(cell, atomic, hop) < 0)
snd_seq_cell_free(cell); /* release this cell */
} else {
/* Normal events:
* event cell is freed after processing the event
*/
result = snd_seq_deliver_event(client, &cell->event, atomic, hop);
snd_seq_cell_free(cell);
}
snd_seq_client_unlock(client);
return result;
}
/* Allocate a cell from client pool and enqueue it to queue:
* if pool is empty and blocking is TRUE, sleep until a new cell is
* available.
*/
static int snd_seq_client_enqueue_event(struct snd_seq_client *client,
struct snd_seq_event *event,
struct file *file, int blocking,
int atomic, int hop)
{
struct snd_seq_event_cell *cell;
int err;
/* special queue values - force direct passing */
if (event->queue == SNDRV_SEQ_ADDRESS_SUBSCRIBERS) {
event->dest.client = SNDRV_SEQ_ADDRESS_SUBSCRIBERS;
event->queue = SNDRV_SEQ_QUEUE_DIRECT;
} else
#ifdef SUPPORT_BROADCAST
if (event->queue == SNDRV_SEQ_ADDRESS_BROADCAST) {
event->dest.client = SNDRV_SEQ_ADDRESS_BROADCAST;
event->queue = SNDRV_SEQ_QUEUE_DIRECT;
}
#endif
if (event->dest.client == SNDRV_SEQ_ADDRESS_SUBSCRIBERS) {
/* check presence of source port */
struct snd_seq_client_port *src_port = snd_seq_port_use_ptr(client, event->source.port);
if (src_port == NULL)
return -EINVAL;
snd_seq_port_unlock(src_port);
}
/* direct event processing without enqueued */
if (snd_seq_ev_is_direct(event)) {
if (event->type == SNDRV_SEQ_EVENT_NOTE)
return -EINVAL; /* this event must be enqueued! */
return snd_seq_deliver_event(client, event, atomic, hop);
}
/* Not direct, normal queuing */
if (snd_seq_queue_is_used(event->queue, client->number) <= 0)
return -EINVAL; /* invalid queue */
if (! snd_seq_write_pool_allocated(client))
return -ENXIO; /* queue is not allocated */
/* allocate an event cell */
err = snd_seq_event_dup(client->pool, event, &cell, !blocking || atomic, file);
if (err < 0)
return err;
/* we got a cell. enqueue it. */
if ((err = snd_seq_enqueue_event(cell, atomic, hop)) < 0) {
snd_seq_cell_free(cell);
return err;
}
return 0;
}
/*
* check validity of event type and data length.
* return non-zero if invalid.
*/
static int check_event_type_and_length(struct snd_seq_event *ev)
{
switch (snd_seq_ev_length_type(ev)) {
case SNDRV_SEQ_EVENT_LENGTH_FIXED:
if (snd_seq_ev_is_variable_type(ev))
return -EINVAL;
break;
case SNDRV_SEQ_EVENT_LENGTH_VARIABLE:
if (! snd_seq_ev_is_variable_type(ev) ||
(ev->data.ext.len & ~SNDRV_SEQ_EXT_MASK) >= SNDRV_SEQ_MAX_EVENT_LEN)
return -EINVAL;
break;
case SNDRV_SEQ_EVENT_LENGTH_VARUSR:
if (! snd_seq_ev_is_direct(ev))
return -EINVAL;
break;
}
return 0;
}
/* handle write() */
/* possible error values:
* -ENXIO invalid client or file open mode
* -ENOMEM malloc failed
* -EFAULT seg. fault during copy from user space
* -EINVAL invalid event
* -EAGAIN no space in output pool
* -EINTR interrupts while sleep
* -EMLINK too many hops
* others depends on return value from driver callback
*/
static ssize_t snd_seq_write(struct file *file, const char __user *buf,
size_t count, loff_t *offset)
{
struct snd_seq_client *client = file->private_data;
int written = 0, len;
int err = -EINVAL;
struct snd_seq_event event;
if (!(snd_seq_file_flags(file) & SNDRV_SEQ_LFLG_OUTPUT))
return -ENXIO;
/* check client structures are in place */
if (snd_BUG_ON(!client))
return -ENXIO;
if (!client->accept_output || client->pool == NULL)
return -ENXIO;
/* allocate the pool now if the pool is not allocated yet */
if (client->pool->size > 0 && !snd_seq_write_pool_allocated(client)) {
if (snd_seq_pool_init(client->pool) < 0)
return -ENOMEM;
}
/* only process whole events */
while (count >= sizeof(struct snd_seq_event)) {
/* Read in the event header from the user */
len = sizeof(event);
if (copy_from_user(&event, buf, len)) {
err = -EFAULT;
break;
}
event.source.client = client->number; /* fill in client number */
/* Check for extension data length */
if (check_event_type_and_length(&event)) {
err = -EINVAL;
break;
}
/* check for special events */
if (event.type == SNDRV_SEQ_EVENT_NONE)
goto __skip_event;
else if (snd_seq_ev_is_reserved(&event)) {
err = -EINVAL;
break;
}
if (snd_seq_ev_is_variable(&event)) {
int extlen = event.data.ext.len & ~SNDRV_SEQ_EXT_MASK;
if ((size_t)(extlen + len) > count) {
/* back out, will get an error this time or next */
err = -EINVAL;
break;
}
/* set user space pointer */
event.data.ext.len = extlen | SNDRV_SEQ_EXT_USRPTR;
event.data.ext.ptr = (char __force *)buf
+ sizeof(struct snd_seq_event);
len += extlen; /* increment data length */
} else {
#ifdef CONFIG_COMPAT
if (client->convert32 && snd_seq_ev_is_varusr(&event)) {
void *ptr = (void __force *)compat_ptr(event.data.raw32.d[1]);
event.data.ext.ptr = ptr;
}
#endif
}
/* ok, enqueue it */
err = snd_seq_client_enqueue_event(client, &event, file,
!(file->f_flags & O_NONBLOCK),
0, 0);
if (err < 0)
break;
__skip_event:
/* Update pointers and counts */
count -= len;
buf += len;
written += len;
}
return written ? written : err;
}
/*
* handle polling
*/
static unsigned int snd_seq_poll(struct file *file, poll_table * wait)
{
struct snd_seq_client *client = file->private_data;
unsigned int mask = 0;
/* check client structures are in place */
if (snd_BUG_ON(!client))
return -ENXIO;
if ((snd_seq_file_flags(file) & SNDRV_SEQ_LFLG_INPUT) &&
client->data.user.fifo) {
/* check if data is available in the outqueue */
if (snd_seq_fifo_poll_wait(client->data.user.fifo, file, wait))
mask |= POLLIN | POLLRDNORM;
}
if (snd_seq_file_flags(file) & SNDRV_SEQ_LFLG_OUTPUT) {
/* check if data is available in the pool */
if (!snd_seq_write_pool_allocated(client) ||
snd_seq_pool_poll_wait(client->pool, file, wait))
mask |= POLLOUT | POLLWRNORM;
}
return mask;
}
/*-----------------------------------------------------*/
/* SYSTEM_INFO ioctl() */
static int snd_seq_ioctl_system_info(struct snd_seq_client *client, void __user *arg)
{
struct snd_seq_system_info info;
memset(&info, 0, sizeof(info));
/* fill the info fields */
info.queues = SNDRV_SEQ_MAX_QUEUES;
info.clients = SNDRV_SEQ_MAX_CLIENTS;
info.ports = 256; /* fixed limit */
info.channels = 256; /* fixed limit */
info.cur_clients = client_usage.cur;
info.cur_queues = snd_seq_queue_get_cur_queues();
if (copy_to_user(arg, &info, sizeof(info)))
return -EFAULT;
return 0;
}
/* RUNNING_MODE ioctl() */
static int snd_seq_ioctl_running_mode(struct snd_seq_client *client, void __user *arg)
{
struct snd_seq_running_info info;
struct snd_seq_client *cptr;
int err = 0;
if (copy_from_user(&info, arg, sizeof(info)))
return -EFAULT;
/* requested client number */
cptr = snd_seq_client_use_ptr(info.client);
if (cptr == NULL)
return -ENOENT; /* don't change !!! */
#ifdef SNDRV_BIG_ENDIAN
if (! info.big_endian) {
err = -EINVAL;
goto __err;
}
#else
if (info.big_endian) {
err = -EINVAL;
goto __err;
}
#endif
if (info.cpu_mode > sizeof(long)) {
err = -EINVAL;
goto __err;
}
cptr->convert32 = (info.cpu_mode < sizeof(long));
__err:
snd_seq_client_unlock(cptr);
return err;
}
/* CLIENT_INFO ioctl() */
static void get_client_info(struct snd_seq_client *cptr,
struct snd_seq_client_info *info)
{
info->client = cptr->number;
/* fill the info fields */
info->type = cptr->type;
strcpy(info->name, cptr->name);
info->filter = cptr->filter;
info->event_lost = cptr->event_lost;
memcpy(info->event_filter, cptr->event_filter, 32);
info->num_ports = cptr->num_ports;
memset(info->reserved, 0, sizeof(info->reserved));
}
static int snd_seq_ioctl_get_client_info(struct snd_seq_client *client,
void __user *arg)
{
struct snd_seq_client *cptr;
struct snd_seq_client_info client_info;
if (copy_from_user(&client_info, arg, sizeof(client_info)))
return -EFAULT;
/* requested client number */
cptr = snd_seq_client_use_ptr(client_info.client);
if (cptr == NULL)
return -ENOENT; /* don't change !!! */
get_client_info(cptr, &client_info);
snd_seq_client_unlock(cptr);
if (copy_to_user(arg, &client_info, sizeof(client_info)))
return -EFAULT;
return 0;
}
/* CLIENT_INFO ioctl() */
static int snd_seq_ioctl_set_client_info(struct snd_seq_client *client,
void __user *arg)
{
struct snd_seq_client_info client_info;
if (copy_from_user(&client_info, arg, sizeof(client_info)))
return -EFAULT;
/* it is not allowed to set the info fields for an another client */
if (client->number != client_info.client)
return -EPERM;
/* also client type must be set now */
if (client->type != client_info.type)
return -EINVAL;
/* fill the info fields */
if (client_info.name[0])
strlcpy(client->name, client_info.name, sizeof(client->name));
client->filter = client_info.filter;
client->event_lost = client_info.event_lost;
memcpy(client->event_filter, client_info.event_filter, 32);
return 0;
}
/*
* CREATE PORT ioctl()
*/
static int snd_seq_ioctl_create_port(struct snd_seq_client *client,
void __user *arg)
{
struct snd_seq_client_port *port;
struct snd_seq_port_info info;
struct snd_seq_port_callback *callback;
if (copy_from_user(&info, arg, sizeof(info)))
return -EFAULT;
/* it is not allowed to create the port for an another client */
if (info.addr.client != client->number)
return -EPERM;
port = snd_seq_create_port(client, (info.flags & SNDRV_SEQ_PORT_FLG_GIVEN_PORT) ? info.addr.port : -1);
if (port == NULL)
return -ENOMEM;
if (client->type == USER_CLIENT && info.kernel) {
snd_seq_delete_port(client, port->addr.port);
return -EINVAL;
}
if (client->type == KERNEL_CLIENT) {
if ((callback = info.kernel) != NULL) {
if (callback->owner)
port->owner = callback->owner;
port->private_data = callback->private_data;
port->private_free = callback->private_free;
port->callback_all = callback->callback_all;
port->event_input = callback->event_input;
port->c_src.open = callback->subscribe;
port->c_src.close = callback->unsubscribe;
port->c_dest.open = callback->use;
port->c_dest.close = callback->unuse;
}
}
info.addr = port->addr;
snd_seq_set_port_info(port, &info);
snd_seq_system_client_ev_port_start(port->addr.client, port->addr.port);
if (copy_to_user(arg, &info, sizeof(info)))
return -EFAULT;
return 0;
}
/*
* DELETE PORT ioctl()
*/
static int snd_seq_ioctl_delete_port(struct snd_seq_client *client,
void __user *arg)
{
struct snd_seq_port_info info;
int err;
/* set passed parameters */
if (copy_from_user(&info, arg, sizeof(info)))
return -EFAULT;
/* it is not allowed to remove the port for an another client */
if (info.addr.client != client->number)
return -EPERM;
err = snd_seq_delete_port(client, info.addr.port);
if (err >= 0)
snd_seq_system_client_ev_port_exit(client->number, info.addr.port);
return err;
}
/*
* GET_PORT_INFO ioctl() (on any client)
*/
static int snd_seq_ioctl_get_port_info(struct snd_seq_client *client,
void __user *arg)
{
struct snd_seq_client *cptr;
struct snd_seq_client_port *port;
struct snd_seq_port_info info;
if (copy_from_user(&info, arg, sizeof(info)))
return -EFAULT;
cptr = snd_seq_client_use_ptr(info.addr.client);
if (cptr == NULL)
return -ENXIO;
port = snd_seq_port_use_ptr(cptr, info.addr.port);
if (port == NULL) {
snd_seq_client_unlock(cptr);
return -ENOENT; /* don't change */
}
/* get port info */
snd_seq_get_port_info(port, &info);
snd_seq_port_unlock(port);
snd_seq_client_unlock(cptr);
if (copy_to_user(arg, &info, sizeof(info)))
return -EFAULT;
return 0;
}
/*
* SET_PORT_INFO ioctl() (only ports on this/own client)
*/
static int snd_seq_ioctl_set_port_info(struct snd_seq_client *client,
void __user *arg)
{
struct snd_seq_client_port *port;
struct snd_seq_port_info info;
if (copy_from_user(&info, arg, sizeof(info)))
return -EFAULT;
if (info.addr.client != client->number) /* only set our own ports ! */
return -EPERM;
port = snd_seq_port_use_ptr(client, info.addr.port);
if (port) {
snd_seq_set_port_info(port, &info);
snd_seq_port_unlock(port);
}
return 0;
}
/*
* port subscription (connection)
*/
#define PERM_RD (SNDRV_SEQ_PORT_CAP_READ|SNDRV_SEQ_PORT_CAP_SUBS_READ)
#define PERM_WR (SNDRV_SEQ_PORT_CAP_WRITE|SNDRV_SEQ_PORT_CAP_SUBS_WRITE)
static int check_subscription_permission(struct snd_seq_client *client,
struct snd_seq_client_port *sport,
struct snd_seq_client_port *dport,
struct snd_seq_port_subscribe *subs)
{
if (client->number != subs->sender.client &&
client->number != subs->dest.client) {
/* connection by third client - check export permission */
if (check_port_perm(sport, SNDRV_SEQ_PORT_CAP_NO_EXPORT))
return -EPERM;
if (check_port_perm(dport, SNDRV_SEQ_PORT_CAP_NO_EXPORT))
return -EPERM;
}
/* check read permission */
/* if sender or receiver is the subscribing client itself,
* no permission check is necessary
*/
if (client->number != subs->sender.client) {
if (! check_port_perm(sport, PERM_RD))
return -EPERM;
}
/* check write permission */
if (client->number != subs->dest.client) {
if (! check_port_perm(dport, PERM_WR))
return -EPERM;
}
return 0;
}
/*
* send an subscription notify event to user client:
* client must be user client.
*/
int snd_seq_client_notify_subscription(int client, int port,
struct snd_seq_port_subscribe *info,
int evtype)
{
struct snd_seq_event event;
memset(&event, 0, sizeof(event));
event.type = evtype;
event.data.connect.dest = info->dest;
event.data.connect.sender = info->sender;
return snd_seq_system_notify(client, port, &event); /* non-atomic */
}
/*
* add to port's subscription list IOCTL interface
*/
static int snd_seq_ioctl_subscribe_port(struct snd_seq_client *client,
void __user *arg)
{
int result = -EINVAL;
struct snd_seq_client *receiver = NULL, *sender = NULL;
struct snd_seq_client_port *sport = NULL, *dport = NULL;
struct snd_seq_port_subscribe subs;
if (copy_from_user(&subs, arg, sizeof(subs)))
return -EFAULT;
if ((receiver = snd_seq_client_use_ptr(subs.dest.client)) == NULL)
goto __end;
if ((sender = snd_seq_client_use_ptr(subs.sender.client)) == NULL)
goto __end;
if ((sport = snd_seq_port_use_ptr(sender, subs.sender.port)) == NULL)
goto __end;
if ((dport = snd_seq_port_use_ptr(receiver, subs.dest.port)) == NULL)
goto __end;
result = check_subscription_permission(client, sport, dport, &subs);
if (result < 0)
goto __end;
/* connect them */
result = snd_seq_port_connect(client, sender, sport, receiver, dport, &subs);
if (! result) /* broadcast announce */
snd_seq_client_notify_subscription(SNDRV_SEQ_ADDRESS_SUBSCRIBERS, 0,
&subs, SNDRV_SEQ_EVENT_PORT_SUBSCRIBED);
__end:
if (sport)
snd_seq_port_unlock(sport);
if (dport)
snd_seq_port_unlock(dport);
if (sender)
snd_seq_client_unlock(sender);
if (receiver)
snd_seq_client_unlock(receiver);
return result;
}
/*
* remove from port's subscription list
*/
static int snd_seq_ioctl_unsubscribe_port(struct snd_seq_client *client,
void __user *arg)
{
int result = -ENXIO;
struct snd_seq_client *receiver = NULL, *sender = NULL;
struct snd_seq_client_port *sport = NULL, *dport = NULL;
struct snd_seq_port_subscribe subs;
if (copy_from_user(&subs, arg, sizeof(subs)))
return -EFAULT;
if ((receiver = snd_seq_client_use_ptr(subs.dest.client)) == NULL)
goto __end;
if ((sender = snd_seq_client_use_ptr(subs.sender.client)) == NULL)
goto __end;
if ((sport = snd_seq_port_use_ptr(sender, subs.sender.port)) == NULL)
goto __end;
if ((dport = snd_seq_port_use_ptr(receiver, subs.dest.port)) == NULL)
goto __end;
result = check_subscription_permission(client, sport, dport, &subs);
if (result < 0)
goto __end;
result = snd_seq_port_disconnect(client, sender, sport, receiver, dport, &subs);
if (! result) /* broadcast announce */
snd_seq_client_notify_subscription(SNDRV_SEQ_ADDRESS_SUBSCRIBERS, 0,
&subs, SNDRV_SEQ_EVENT_PORT_UNSUBSCRIBED);
__end:
if (sport)
snd_seq_port_unlock(sport);
if (dport)
snd_seq_port_unlock(dport);
if (sender)
snd_seq_client_unlock(sender);
if (receiver)
snd_seq_client_unlock(receiver);
return result;
}
/* CREATE_QUEUE ioctl() */
static int snd_seq_ioctl_create_queue(struct snd_seq_client *client,
void __user *arg)
{
struct snd_seq_queue_info info;
int result;
struct snd_seq_queue *q;
if (copy_from_user(&info, arg, sizeof(info)))
return -EFAULT;
result = snd_seq_queue_alloc(client->number, info.locked, info.flags);
if (result < 0)
return result;
q = queueptr(result);
if (q == NULL)
return -EINVAL;
info.queue = q->queue;
info.locked = q->locked;
info.owner = q->owner;
/* set queue name */
if (! info.name[0])
snprintf(info.name, sizeof(info.name), "Queue-%d", q->queue);
strlcpy(q->name, info.name, sizeof(q->name));
queuefree(q);
if (copy_to_user(arg, &info, sizeof(info)))
return -EFAULT;
return 0;
}
/* DELETE_QUEUE ioctl() */
static int snd_seq_ioctl_delete_queue(struct snd_seq_client *client,
void __user *arg)
{
struct snd_seq_queue_info info;
if (copy_from_user(&info, arg, sizeof(info)))
return -EFAULT;
return snd_seq_queue_delete(client->number, info.queue);
}
/* GET_QUEUE_INFO ioctl() */
static int snd_seq_ioctl_get_queue_info(struct snd_seq_client *client,
void __user *arg)
{
struct snd_seq_queue_info info;
struct snd_seq_queue *q;
if (copy_from_user(&info, arg, sizeof(info)))
return -EFAULT;
q = queueptr(info.queue);
if (q == NULL)
return -EINVAL;
memset(&info, 0, sizeof(info));
info.queue = q->queue;
info.owner = q->owner;
info.locked = q->locked;
strlcpy(info.name, q->name, sizeof(info.name));
queuefree(q);
if (copy_to_user(arg, &info, sizeof(info)))
return -EFAULT;
return 0;
}
/* SET_QUEUE_INFO ioctl() */
static int snd_seq_ioctl_set_queue_info(struct snd_seq_client *client,
void __user *arg)
{
struct snd_seq_queue_info info;
struct snd_seq_queue *q;
if (copy_from_user(&info, arg, sizeof(info)))
return -EFAULT;
if (info.owner != client->number)
return -EINVAL;
/* change owner/locked permission */
if (snd_seq_queue_check_access(info.queue, client->number)) {
if (snd_seq_queue_set_owner(info.queue, client->number, info.locked) < 0)
return -EPERM;
if (info.locked)
snd_seq_queue_use(info.queue, client->number, 1);
} else {
return -EPERM;
}
q = queueptr(info.queue);
if (! q)
return -EINVAL;
if (q->owner != client->number) {
queuefree(q);
return -EPERM;
}
strlcpy(q->name, info.name, sizeof(q->name));
queuefree(q);
return 0;
}
/* GET_NAMED_QUEUE ioctl() */
static int snd_seq_ioctl_get_named_queue(struct snd_seq_client *client, void __user *arg)
{
struct snd_seq_queue_info info;
struct snd_seq_queue *q;
if (copy_from_user(&info, arg, sizeof(info)))
return -EFAULT;
q = snd_seq_queue_find_name(info.name);
if (q == NULL)
return -EINVAL;
info.queue = q->queue;
info.owner = q->owner;
info.locked = q->locked;
queuefree(q);
if (copy_to_user(arg, &info, sizeof(info)))
return -EFAULT;
return 0;
}
/* GET_QUEUE_STATUS ioctl() */
static int snd_seq_ioctl_get_queue_status(struct snd_seq_client *client,
void __user *arg)
{
struct snd_seq_queue_status status;
struct snd_seq_queue *queue;
struct snd_seq_timer *tmr;
if (copy_from_user(&status, arg, sizeof(status)))
return -EFAULT;
queue = queueptr(status.queue);
if (queue == NULL)
return -EINVAL;
memset(&status, 0, sizeof(status));
status.queue = queue->queue;
tmr = queue->timer;
status.events = queue->tickq->cells + queue->timeq->cells;
status.time = snd_seq_timer_get_cur_time(tmr);
status.tick = snd_seq_timer_get_cur_tick(tmr);
status.running = tmr->running;
status.flags = queue->flags;
queuefree(queue);
if (copy_to_user(arg, &status, sizeof(status)))
return -EFAULT;
return 0;
}
/* GET_QUEUE_TEMPO ioctl() */
static int snd_seq_ioctl_get_queue_tempo(struct snd_seq_client *client,
void __user *arg)
{
struct snd_seq_queue_tempo tempo;
struct snd_seq_queue *queue;
struct snd_seq_timer *tmr;
if (copy_from_user(&tempo, arg, sizeof(tempo)))
return -EFAULT;
queue = queueptr(tempo.queue);
if (queue == NULL)
return -EINVAL;
memset(&tempo, 0, sizeof(tempo));
tempo.queue = queue->queue;
tmr = queue->timer;
tempo.tempo = tmr->tempo;
tempo.ppq = tmr->ppq;
tempo.skew_value = tmr->skew;
tempo.skew_base = tmr->skew_base;
queuefree(queue);
if (copy_to_user(arg, &tempo, sizeof(tempo)))
return -EFAULT;
return 0;
}
/* SET_QUEUE_TEMPO ioctl() */
int snd_seq_set_queue_tempo(int client, struct snd_seq_queue_tempo *tempo)
{
if (!snd_seq_queue_check_access(tempo->queue, client))
return -EPERM;
return snd_seq_queue_timer_set_tempo(tempo->queue, client, tempo);
}
EXPORT_SYMBOL(snd_seq_set_queue_tempo);
static int snd_seq_ioctl_set_queue_tempo(struct snd_seq_client *client,
void __user *arg)
{
int result;
struct snd_seq_queue_tempo tempo;
if (copy_from_user(&tempo, arg, sizeof(tempo)))
return -EFAULT;
result = snd_seq_set_queue_tempo(client->number, &tempo);
return result < 0 ? result : 0;
}
/* GET_QUEUE_TIMER ioctl() */
static int snd_seq_ioctl_get_queue_timer(struct snd_seq_client *client,
void __user *arg)
{
struct snd_seq_queue_timer timer;
struct snd_seq_queue *queue;
struct snd_seq_timer *tmr;
if (copy_from_user(&timer, arg, sizeof(timer)))
return -EFAULT;
queue = queueptr(timer.queue);
if (queue == NULL)
return -EINVAL;
if (mutex_lock_interruptible(&queue->timer_mutex)) {
queuefree(queue);
return -ERESTARTSYS;
}
tmr = queue->timer;
memset(&timer, 0, sizeof(timer));
timer.queue = queue->queue;
timer.type = tmr->type;
if (tmr->type == SNDRV_SEQ_TIMER_ALSA) {
timer.u.alsa.id = tmr->alsa_id;
timer.u.alsa.resolution = tmr->preferred_resolution;
}
mutex_unlock(&queue->timer_mutex);
queuefree(queue);
if (copy_to_user(arg, &timer, sizeof(timer)))
return -EFAULT;
return 0;
}
/* SET_QUEUE_TIMER ioctl() */
static int snd_seq_ioctl_set_queue_timer(struct snd_seq_client *client,
void __user *arg)
{
int result = 0;
struct snd_seq_queue_timer timer;
if (copy_from_user(&timer, arg, sizeof(timer)))
return -EFAULT;
if (timer.type != SNDRV_SEQ_TIMER_ALSA)
return -EINVAL;
if (snd_seq_queue_check_access(timer.queue, client->number)) {
struct snd_seq_queue *q;
struct snd_seq_timer *tmr;
q = queueptr(timer.queue);
if (q == NULL)
return -ENXIO;
if (mutex_lock_interruptible(&q->timer_mutex)) {
queuefree(q);
return -ERESTARTSYS;
}
tmr = q->timer;
snd_seq_queue_timer_close(timer.queue);
tmr->type = timer.type;
if (tmr->type == SNDRV_SEQ_TIMER_ALSA) {
tmr->alsa_id = timer.u.alsa.id;
tmr->preferred_resolution = timer.u.alsa.resolution;
}
result = snd_seq_queue_timer_open(timer.queue);
mutex_unlock(&q->timer_mutex);
queuefree(q);
} else {
return -EPERM;
}
return result;
}
/* GET_QUEUE_CLIENT ioctl() */
static int snd_seq_ioctl_get_queue_client(struct snd_seq_client *client,
void __user *arg)
{
struct snd_seq_queue_client info;
int used;
if (copy_from_user(&info, arg, sizeof(info)))
return -EFAULT;
used = snd_seq_queue_is_used(info.queue, client->number);
if (used < 0)
return -EINVAL;
info.used = used;
info.client = client->number;
if (copy_to_user(arg, &info, sizeof(info)))
return -EFAULT;
return 0;
}
/* SET_QUEUE_CLIENT ioctl() */
static int snd_seq_ioctl_set_queue_client(struct snd_seq_client *client,
void __user *arg)
{
int err;
struct snd_seq_queue_client info;
if (copy_from_user(&info, arg, sizeof(info)))
return -EFAULT;
if (info.used >= 0) {
err = snd_seq_queue_use(info.queue, client->number, info.used);
if (err < 0)
return err;
}
return snd_seq_ioctl_get_queue_client(client, arg);
}
/* GET_CLIENT_POOL ioctl() */
static int snd_seq_ioctl_get_client_pool(struct snd_seq_client *client,
void __user *arg)
{
struct snd_seq_client_pool info;
struct snd_seq_client *cptr;
if (copy_from_user(&info, arg, sizeof(info)))
return -EFAULT;
cptr = snd_seq_client_use_ptr(info.client);
if (cptr == NULL)
return -ENOENT;
memset(&info, 0, sizeof(info));
info.output_pool = cptr->pool->size;
info.output_room = cptr->pool->room;
info.output_free = info.output_pool;
info.output_free = snd_seq_unused_cells(cptr->pool);
if (cptr->type == USER_CLIENT) {
info.input_pool = cptr->data.user.fifo_pool_size;
info.input_free = info.input_pool;
if (cptr->data.user.fifo)
info.input_free = snd_seq_unused_cells(cptr->data.user.fifo->pool);
} else {
info.input_pool = 0;
info.input_free = 0;
}
snd_seq_client_unlock(cptr);
if (copy_to_user(arg, &info, sizeof(info)))
return -EFAULT;
return 0;
}
/* SET_CLIENT_POOL ioctl() */
static int snd_seq_ioctl_set_client_pool(struct snd_seq_client *client,
void __user *arg)
{
struct snd_seq_client_pool info;
int rc;
if (copy_from_user(&info, arg, sizeof(info)))
return -EFAULT;
if (client->number != info.client)
return -EINVAL; /* can't change other clients */
if (info.output_pool >= 1 && info.output_pool <= SNDRV_SEQ_MAX_EVENTS &&
(! snd_seq_write_pool_allocated(client) ||
info.output_pool != client->pool->size)) {
if (snd_seq_write_pool_allocated(client)) {
/* remove all existing cells */
snd_seq_queue_client_leave_cells(client->number);
snd_seq_pool_done(client->pool);
}
client->pool->size = info.output_pool;
rc = snd_seq_pool_init(client->pool);
if (rc < 0)
return rc;
}
if (client->type == USER_CLIENT && client->data.user.fifo != NULL &&
info.input_pool >= 1 &&
info.input_pool <= SNDRV_SEQ_MAX_CLIENT_EVENTS &&
info.input_pool != client->data.user.fifo_pool_size) {
/* change pool size */
rc = snd_seq_fifo_resize(client->data.user.fifo, info.input_pool);
if (rc < 0)
return rc;
client->data.user.fifo_pool_size = info.input_pool;
}
if (info.output_room >= 1 &&
info.output_room <= client->pool->size) {
client->pool->room = info.output_room;
}
return snd_seq_ioctl_get_client_pool(client, arg);
}
/* REMOVE_EVENTS ioctl() */
static int snd_seq_ioctl_remove_events(struct snd_seq_client *client,
void __user *arg)
{
struct snd_seq_remove_events info;
if (copy_from_user(&info, arg, sizeof(info)))
return -EFAULT;
/*
* Input mostly not implemented XXX.
*/
if (info.remove_mode & SNDRV_SEQ_REMOVE_INPUT) {
/*
* No restrictions so for a user client we can clear
* the whole fifo
*/
if (client->type == USER_CLIENT)
snd_seq_fifo_clear(client->data.user.fifo);
}
if (info.remove_mode & SNDRV_SEQ_REMOVE_OUTPUT)
snd_seq_queue_remove_cells(client->number, &info);
return 0;
}
/*
* get subscription info
*/
static int snd_seq_ioctl_get_subscription(struct snd_seq_client *client,
void __user *arg)
{
int result;
struct snd_seq_client *sender = NULL;
struct snd_seq_client_port *sport = NULL;
struct snd_seq_port_subscribe subs;
struct snd_seq_subscribers *p;
if (copy_from_user(&subs, arg, sizeof(subs)))
return -EFAULT;
result = -EINVAL;
if ((sender = snd_seq_client_use_ptr(subs.sender.client)) == NULL)
goto __end;
if ((sport = snd_seq_port_use_ptr(sender, subs.sender.port)) == NULL)
goto __end;
p = snd_seq_port_get_subscription(&sport->c_src, &subs.dest);
if (p) {
result = 0;
subs = p->info;
} else
result = -ENOENT;
__end:
if (sport)
snd_seq_port_unlock(sport);
if (sender)
snd_seq_client_unlock(sender);
if (result >= 0) {
if (copy_to_user(arg, &subs, sizeof(subs)))
return -EFAULT;
}
return result;
}
/*
* get subscription info - check only its presence
*/
static int snd_seq_ioctl_query_subs(struct snd_seq_client *client,
void __user *arg)
{
int result = -ENXIO;
struct snd_seq_client *cptr = NULL;
struct snd_seq_client_port *port = NULL;
struct snd_seq_query_subs subs;
struct snd_seq_port_subs_info *group;
struct list_head *p;
int i;
if (copy_from_user(&subs, arg, sizeof(subs)))
return -EFAULT;
if ((cptr = snd_seq_client_use_ptr(subs.root.client)) == NULL)
goto __end;
if ((port = snd_seq_port_use_ptr(cptr, subs.root.port)) == NULL)
goto __end;
switch (subs.type) {
case SNDRV_SEQ_QUERY_SUBS_READ:
group = &port->c_src;
break;
case SNDRV_SEQ_QUERY_SUBS_WRITE:
group = &port->c_dest;
break;
default:
goto __end;
}
down_read(&group->list_mutex);
/* search for the subscriber */
subs.num_subs = group->count;
i = 0;
result = -ENOENT;
list_for_each(p, &group->list_head) {
if (i++ == subs.index) {
/* found! */
struct snd_seq_subscribers *s;
if (subs.type == SNDRV_SEQ_QUERY_SUBS_READ) {
s = list_entry(p, struct snd_seq_subscribers, src_list);
subs.addr = s->info.dest;
} else {
s = list_entry(p, struct snd_seq_subscribers, dest_list);
subs.addr = s->info.sender;
}
subs.flags = s->info.flags;
subs.queue = s->info.queue;
result = 0;
break;
}
}
up_read(&group->list_mutex);
__end:
if (port)
snd_seq_port_unlock(port);
if (cptr)
snd_seq_client_unlock(cptr);
if (result >= 0) {
if (copy_to_user(arg, &subs, sizeof(subs)))
return -EFAULT;
}
return result;
}
/*
* query next client
*/
static int snd_seq_ioctl_query_next_client(struct snd_seq_client *client,
void __user *arg)
{
struct snd_seq_client *cptr = NULL;
struct snd_seq_client_info info;
if (copy_from_user(&info, arg, sizeof(info)))
return -EFAULT;
/* search for next client */
info.client++;
if (info.client < 0)
info.client = 0;
for (; info.client < SNDRV_SEQ_MAX_CLIENTS; info.client++) {
cptr = snd_seq_client_use_ptr(info.client);
if (cptr)
break; /* found */
}
if (cptr == NULL)
return -ENOENT;
get_client_info(cptr, &info);
snd_seq_client_unlock(cptr);
if (copy_to_user(arg, &info, sizeof(info)))
return -EFAULT;
return 0;
}
/*
* query next port
*/
static int snd_seq_ioctl_query_next_port(struct snd_seq_client *client,
void __user *arg)
{
struct snd_seq_client *cptr;
struct snd_seq_client_port *port = NULL;
struct snd_seq_port_info info;
if (copy_from_user(&info, arg, sizeof(info)))
return -EFAULT;
cptr = snd_seq_client_use_ptr(info.addr.client);
if (cptr == NULL)
return -ENXIO;
/* search for next port */
info.addr.port++;
port = snd_seq_port_query_nearest(cptr, &info);
if (port == NULL) {
snd_seq_client_unlock(cptr);
return -ENOENT;
}
/* get port info */
info.addr = port->addr;
snd_seq_get_port_info(port, &info);
snd_seq_port_unlock(port);
snd_seq_client_unlock(cptr);
if (copy_to_user(arg, &info, sizeof(info)))
return -EFAULT;
return 0;
}
/* -------------------------------------------------------- */
static struct seq_ioctl_table {
unsigned int cmd;
int (*func)(struct snd_seq_client *client, void __user * arg);
} ioctl_tables[] = {
{ SNDRV_SEQ_IOCTL_SYSTEM_INFO, snd_seq_ioctl_system_info },
{ SNDRV_SEQ_IOCTL_RUNNING_MODE, snd_seq_ioctl_running_mode },
{ SNDRV_SEQ_IOCTL_GET_CLIENT_INFO, snd_seq_ioctl_get_client_info },
{ SNDRV_SEQ_IOCTL_SET_CLIENT_INFO, snd_seq_ioctl_set_client_info },
{ SNDRV_SEQ_IOCTL_CREATE_PORT, snd_seq_ioctl_create_port },
{ SNDRV_SEQ_IOCTL_DELETE_PORT, snd_seq_ioctl_delete_port },
{ SNDRV_SEQ_IOCTL_GET_PORT_INFO, snd_seq_ioctl_get_port_info },
{ SNDRV_SEQ_IOCTL_SET_PORT_INFO, snd_seq_ioctl_set_port_info },
{ SNDRV_SEQ_IOCTL_SUBSCRIBE_PORT, snd_seq_ioctl_subscribe_port },
{ SNDRV_SEQ_IOCTL_UNSUBSCRIBE_PORT, snd_seq_ioctl_unsubscribe_port },
{ SNDRV_SEQ_IOCTL_CREATE_QUEUE, snd_seq_ioctl_create_queue },
{ SNDRV_SEQ_IOCTL_DELETE_QUEUE, snd_seq_ioctl_delete_queue },
{ SNDRV_SEQ_IOCTL_GET_QUEUE_INFO, snd_seq_ioctl_get_queue_info },
{ SNDRV_SEQ_IOCTL_SET_QUEUE_INFO, snd_seq_ioctl_set_queue_info },
{ SNDRV_SEQ_IOCTL_GET_NAMED_QUEUE, snd_seq_ioctl_get_named_queue },
{ SNDRV_SEQ_IOCTL_GET_QUEUE_STATUS, snd_seq_ioctl_get_queue_status },
{ SNDRV_SEQ_IOCTL_GET_QUEUE_TEMPO, snd_seq_ioctl_get_queue_tempo },
{ SNDRV_SEQ_IOCTL_SET_QUEUE_TEMPO, snd_seq_ioctl_set_queue_tempo },
{ SNDRV_SEQ_IOCTL_GET_QUEUE_TIMER, snd_seq_ioctl_get_queue_timer },
{ SNDRV_SEQ_IOCTL_SET_QUEUE_TIMER, snd_seq_ioctl_set_queue_timer },
{ SNDRV_SEQ_IOCTL_GET_QUEUE_CLIENT, snd_seq_ioctl_get_queue_client },
{ SNDRV_SEQ_IOCTL_SET_QUEUE_CLIENT, snd_seq_ioctl_set_queue_client },
{ SNDRV_SEQ_IOCTL_GET_CLIENT_POOL, snd_seq_ioctl_get_client_pool },
{ SNDRV_SEQ_IOCTL_SET_CLIENT_POOL, snd_seq_ioctl_set_client_pool },
{ SNDRV_SEQ_IOCTL_GET_SUBSCRIPTION, snd_seq_ioctl_get_subscription },
{ SNDRV_SEQ_IOCTL_QUERY_NEXT_CLIENT, snd_seq_ioctl_query_next_client },
{ SNDRV_SEQ_IOCTL_QUERY_NEXT_PORT, snd_seq_ioctl_query_next_port },
{ SNDRV_SEQ_IOCTL_REMOVE_EVENTS, snd_seq_ioctl_remove_events },
{ SNDRV_SEQ_IOCTL_QUERY_SUBS, snd_seq_ioctl_query_subs },
{ 0, NULL },
};
static int snd_seq_do_ioctl(struct snd_seq_client *client, unsigned int cmd,
void __user *arg)
{
struct seq_ioctl_table *p;
switch (cmd) {
case SNDRV_SEQ_IOCTL_PVERSION:
/* return sequencer version number */
return put_user(SNDRV_SEQ_VERSION, (int __user *)arg) ? -EFAULT : 0;
case SNDRV_SEQ_IOCTL_CLIENT_ID:
/* return the id of this client */
return put_user(client->number, (int __user *)arg) ? -EFAULT : 0;
}
if (! arg)
return -EFAULT;
for (p = ioctl_tables; p->cmd; p++) {
if (p->cmd == cmd)
return p->func(client, arg);
}
snd_printd("seq unknown ioctl() 0x%x (type='%c', number=0x%02x)\n",
cmd, _IOC_TYPE(cmd), _IOC_NR(cmd));
return -ENOTTY;
}
static long snd_seq_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
struct snd_seq_client *client = file->private_data;
if (snd_BUG_ON(!client))
return -ENXIO;
return snd_seq_do_ioctl(client, cmd, (void __user *) arg);
}
#ifdef CONFIG_COMPAT
#include "seq_compat.c"
#else
#define snd_seq_ioctl_compat NULL
#endif
/* -------------------------------------------------------- */
/* exported to kernel modules */
int snd_seq_create_kernel_client(struct snd_card *card, int client_index,
const char *name_fmt, ...)
{
struct snd_seq_client *client;
va_list args;
if (snd_BUG_ON(in_interrupt()))
return -EBUSY;
if (card && client_index >= SNDRV_SEQ_CLIENTS_PER_CARD)
return -EINVAL;
if (card == NULL && client_index >= SNDRV_SEQ_GLOBAL_CLIENTS)
return -EINVAL;
if (mutex_lock_interruptible(®ister_mutex))
return -ERESTARTSYS;
if (card) {
client_index += SNDRV_SEQ_GLOBAL_CLIENTS
+ card->number * SNDRV_SEQ_CLIENTS_PER_CARD;
if (client_index >= SNDRV_SEQ_DYNAMIC_CLIENTS_BEGIN)
client_index = -1;
}
/* empty write queue as default */
client = seq_create_client1(client_index, 0);
if (client == NULL) {
mutex_unlock(®ister_mutex);
return -EBUSY; /* failure code */
}
usage_alloc(&client_usage, 1);
client->accept_input = 1;
client->accept_output = 1;
va_start(args, name_fmt);
vsnprintf(client->name, sizeof(client->name), name_fmt, args);
va_end(args);
client->type = KERNEL_CLIENT;
mutex_unlock(®ister_mutex);
/* make others aware this new client */
snd_seq_system_client_ev_client_start(client->number);
/* return client number to caller */
return client->number;
}
EXPORT_SYMBOL(snd_seq_create_kernel_client);
/* exported to kernel modules */
int snd_seq_delete_kernel_client(int client)
{
struct snd_seq_client *ptr;
if (snd_BUG_ON(in_interrupt()))
return -EBUSY;
ptr = clientptr(client);
if (ptr == NULL)
return -EINVAL;
seq_free_client(ptr);
kfree(ptr);
return 0;
}
EXPORT_SYMBOL(snd_seq_delete_kernel_client);
/* skeleton to enqueue event, called from snd_seq_kernel_client_enqueue
* and snd_seq_kernel_client_enqueue_blocking
*/
static int kernel_client_enqueue(int client, struct snd_seq_event *ev,
struct file *file, int blocking,
int atomic, int hop)
{
struct snd_seq_client *cptr;
int result;
if (snd_BUG_ON(!ev))
return -EINVAL;
if (ev->type == SNDRV_SEQ_EVENT_NONE)
return 0; /* ignore this */
if (ev->type == SNDRV_SEQ_EVENT_KERNEL_ERROR)
return -EINVAL; /* quoted events can't be enqueued */
/* fill in client number */
ev->source.client = client;
if (check_event_type_and_length(ev))
return -EINVAL;
cptr = snd_seq_client_use_ptr(client);
if (cptr == NULL)
return -EINVAL;
if (! cptr->accept_output)
result = -EPERM;
else /* send it */
result = snd_seq_client_enqueue_event(cptr, ev, file, blocking, atomic, hop);
snd_seq_client_unlock(cptr);
return result;
}
/*
* exported, called by kernel clients to enqueue events (w/o blocking)
*
* RETURN VALUE: zero if succeed, negative if error
*/
int snd_seq_kernel_client_enqueue(int client, struct snd_seq_event * ev,
int atomic, int hop)
{
return kernel_client_enqueue(client, ev, NULL, 0, atomic, hop);
}
EXPORT_SYMBOL(snd_seq_kernel_client_enqueue);
/*
* exported, called by kernel clients to enqueue events (with blocking)
*
* RETURN VALUE: zero if succeed, negative if error
*/
int snd_seq_kernel_client_enqueue_blocking(int client, struct snd_seq_event * ev,
struct file *file,
int atomic, int hop)
{
return kernel_client_enqueue(client, ev, file, 1, atomic, hop);
}
EXPORT_SYMBOL(snd_seq_kernel_client_enqueue_blocking);
/*
* exported, called by kernel clients to dispatch events directly to other
* clients, bypassing the queues. Event time-stamp will be updated.
*
* RETURN VALUE: negative = delivery failed,
* zero, or positive: the number of delivered events
*/
int snd_seq_kernel_client_dispatch(int client, struct snd_seq_event * ev,
int atomic, int hop)
{
struct snd_seq_client *cptr;
int result;
if (snd_BUG_ON(!ev))
return -EINVAL;
/* fill in client number */
ev->queue = SNDRV_SEQ_QUEUE_DIRECT;
ev->source.client = client;
if (check_event_type_and_length(ev))
return -EINVAL;
cptr = snd_seq_client_use_ptr(client);
if (cptr == NULL)
return -EINVAL;
if (!cptr->accept_output)
result = -EPERM;
else
result = snd_seq_deliver_event(cptr, ev, atomic, hop);
snd_seq_client_unlock(cptr);
return result;
}
EXPORT_SYMBOL(snd_seq_kernel_client_dispatch);
/*
* exported, called by kernel clients to perform same functions as with
* userland ioctl()
*/
int snd_seq_kernel_client_ctl(int clientid, unsigned int cmd, void *arg)
{
struct snd_seq_client *client;
mm_segment_t fs;
int result;
client = clientptr(clientid);
if (client == NULL)
return -ENXIO;
fs = snd_enter_user();
result = snd_seq_do_ioctl(client, cmd, (void __force __user *)arg);
snd_leave_user(fs);
return result;
}
EXPORT_SYMBOL(snd_seq_kernel_client_ctl);
/* exported (for OSS emulator) */
int snd_seq_kernel_client_write_poll(int clientid, struct file *file, poll_table *wait)
{
struct snd_seq_client *client;
client = clientptr(clientid);
if (client == NULL)
return -ENXIO;
if (! snd_seq_write_pool_allocated(client))
return 1;
if (snd_seq_pool_poll_wait(client->pool, file, wait))
return 1;
return 0;
}
EXPORT_SYMBOL(snd_seq_kernel_client_write_poll);
/*---------------------------------------------------------------------------*/
#ifdef CONFIG_PROC_FS
/*
* /proc interface
*/
static void snd_seq_info_dump_subscribers(struct snd_info_buffer *buffer,
struct snd_seq_port_subs_info *group,
int is_src, char *msg)
{
struct list_head *p;
struct snd_seq_subscribers *s;
int count = 0;
down_read(&group->list_mutex);
if (list_empty(&group->list_head)) {
up_read(&group->list_mutex);
return;
}
snd_iprintf(buffer, msg);
list_for_each(p, &group->list_head) {
if (is_src)
s = list_entry(p, struct snd_seq_subscribers, src_list);
else
s = list_entry(p, struct snd_seq_subscribers, dest_list);
if (count++)
snd_iprintf(buffer, ", ");
snd_iprintf(buffer, "%d:%d",
is_src ? s->info.dest.client : s->info.sender.client,
is_src ? s->info.dest.port : s->info.sender.port);
if (s->info.flags & SNDRV_SEQ_PORT_SUBS_TIMESTAMP)
snd_iprintf(buffer, "[%c:%d]", ((s->info.flags & SNDRV_SEQ_PORT_SUBS_TIME_REAL) ? 'r' : 't'), s->info.queue);
if (group->exclusive)
snd_iprintf(buffer, "[ex]");
}
up_read(&group->list_mutex);
snd_iprintf(buffer, "\n");
}
#define FLAG_PERM_RD(perm) ((perm) & SNDRV_SEQ_PORT_CAP_READ ? ((perm) & SNDRV_SEQ_PORT_CAP_SUBS_READ ? 'R' : 'r') : '-')
#define FLAG_PERM_WR(perm) ((perm) & SNDRV_SEQ_PORT_CAP_WRITE ? ((perm) & SNDRV_SEQ_PORT_CAP_SUBS_WRITE ? 'W' : 'w') : '-')
#define FLAG_PERM_EX(perm) ((perm) & SNDRV_SEQ_PORT_CAP_NO_EXPORT ? '-' : 'e')
#define FLAG_PERM_DUPLEX(perm) ((perm) & SNDRV_SEQ_PORT_CAP_DUPLEX ? 'X' : '-')
static void snd_seq_info_dump_ports(struct snd_info_buffer *buffer,
struct snd_seq_client *client)
{
struct snd_seq_client_port *p;
mutex_lock(&client->ports_mutex);
list_for_each_entry(p, &client->ports_list_head, list) {
snd_iprintf(buffer, " Port %3d : \"%s\" (%c%c%c%c)\n",
p->addr.port, p->name,
FLAG_PERM_RD(p->capability),
FLAG_PERM_WR(p->capability),
FLAG_PERM_EX(p->capability),
FLAG_PERM_DUPLEX(p->capability));
snd_seq_info_dump_subscribers(buffer, &p->c_src, 1, " Connecting To: ");
snd_seq_info_dump_subscribers(buffer, &p->c_dest, 0, " Connected From: ");
}
mutex_unlock(&client->ports_mutex);
}
/* exported to seq_info.c */
void snd_seq_info_clients_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
int c;
struct snd_seq_client *client;
snd_iprintf(buffer, "Client info\n");
snd_iprintf(buffer, " cur clients : %d\n", client_usage.cur);
snd_iprintf(buffer, " peak clients : %d\n", client_usage.peak);
snd_iprintf(buffer, " max clients : %d\n", SNDRV_SEQ_MAX_CLIENTS);
snd_iprintf(buffer, "\n");
/* list the client table */
for (c = 0; c < SNDRV_SEQ_MAX_CLIENTS; c++) {
client = snd_seq_client_use_ptr(c);
if (client == NULL)
continue;
if (client->type == NO_CLIENT) {
snd_seq_client_unlock(client);
continue;
}
snd_iprintf(buffer, "Client %3d : \"%s\" [%s]\n",
c, client->name,
client->type == USER_CLIENT ? "User" : "Kernel");
snd_seq_info_dump_ports(buffer, client);
if (snd_seq_write_pool_allocated(client)) {
snd_iprintf(buffer, " Output pool :\n");
snd_seq_info_pool(buffer, client->pool, " ");
}
if (client->type == USER_CLIENT && client->data.user.fifo &&
client->data.user.fifo->pool) {
snd_iprintf(buffer, " Input pool :\n");
snd_seq_info_pool(buffer, client->data.user.fifo->pool, " ");
}
snd_seq_client_unlock(client);
}
}
#endif /* CONFIG_PROC_FS */
/*---------------------------------------------------------------------------*/
/*
* REGISTRATION PART
*/
static const struct file_operations snd_seq_f_ops =
{
.owner = THIS_MODULE,
.read = snd_seq_read,
.write = snd_seq_write,
.open = snd_seq_open,
.release = snd_seq_release,
.llseek = no_llseek,
.poll = snd_seq_poll,
.unlocked_ioctl = snd_seq_ioctl,
.compat_ioctl = snd_seq_ioctl_compat,
};
/*
* register sequencer device
*/
int __init snd_sequencer_device_init(void)
{
int err;
if (mutex_lock_interruptible(®ister_mutex))
return -ERESTARTSYS;
if ((err = snd_register_device(SNDRV_DEVICE_TYPE_SEQUENCER, NULL, 0,
&snd_seq_f_ops, NULL, "seq")) < 0) {
mutex_unlock(®ister_mutex);
return err;
}
mutex_unlock(®ister_mutex);
return 0;
}
/*
* unregister sequencer device
*/
void __exit snd_sequencer_device_done(void)
{
snd_unregister_device(SNDRV_DEVICE_TYPE_SEQUENCER, NULL, 0);
}
| gpl-2.0 |
doslab/mool | sound/arm/pxa2xx-pcm-lib.c | 7535 | 7486 | /*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/dma-mapping.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/pxa2xx-lib.h>
#include <mach/dma.h>
#include "pxa2xx-pcm.h"
static const struct snd_pcm_hardware pxa2xx_pcm_hardware = {
.info = SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_PAUSE |
SNDRV_PCM_INFO_RESUME,
.formats = SNDRV_PCM_FMTBIT_S16_LE |
SNDRV_PCM_FMTBIT_S24_LE |
SNDRV_PCM_FMTBIT_S32_LE,
.period_bytes_min = 32,
.period_bytes_max = 8192 - 32,
.periods_min = 1,
.periods_max = PAGE_SIZE/sizeof(pxa_dma_desc),
.buffer_bytes_max = 128 * 1024,
.fifo_size = 32,
};
int __pxa2xx_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct pxa2xx_runtime_data *rtd = runtime->private_data;
size_t totsize = params_buffer_bytes(params);
size_t period = params_period_bytes(params);
pxa_dma_desc *dma_desc;
dma_addr_t dma_buff_phys, next_desc_phys;
snd_pcm_set_runtime_buffer(substream, &substream->dma_buffer);
runtime->dma_bytes = totsize;
dma_desc = rtd->dma_desc_array;
next_desc_phys = rtd->dma_desc_array_phys;
dma_buff_phys = runtime->dma_addr;
do {
next_desc_phys += sizeof(pxa_dma_desc);
dma_desc->ddadr = next_desc_phys;
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
dma_desc->dsadr = dma_buff_phys;
dma_desc->dtadr = rtd->params->dev_addr;
} else {
dma_desc->dsadr = rtd->params->dev_addr;
dma_desc->dtadr = dma_buff_phys;
}
if (period > totsize)
period = totsize;
dma_desc->dcmd = rtd->params->dcmd | period | DCMD_ENDIRQEN;
dma_desc++;
dma_buff_phys += period;
} while (totsize -= period);
dma_desc[-1].ddadr = rtd->dma_desc_array_phys;
return 0;
}
EXPORT_SYMBOL(__pxa2xx_pcm_hw_params);
int __pxa2xx_pcm_hw_free(struct snd_pcm_substream *substream)
{
struct pxa2xx_runtime_data *rtd = substream->runtime->private_data;
if (rtd && rtd->params && rtd->params->drcmr)
*rtd->params->drcmr = 0;
snd_pcm_set_runtime_buffer(substream, NULL);
return 0;
}
EXPORT_SYMBOL(__pxa2xx_pcm_hw_free);
int pxa2xx_pcm_trigger(struct snd_pcm_substream *substream, int cmd)
{
struct pxa2xx_runtime_data *prtd = substream->runtime->private_data;
int ret = 0;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
DDADR(prtd->dma_ch) = prtd->dma_desc_array_phys;
DCSR(prtd->dma_ch) = DCSR_RUN;
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
DCSR(prtd->dma_ch) &= ~DCSR_RUN;
break;
case SNDRV_PCM_TRIGGER_RESUME:
DCSR(prtd->dma_ch) |= DCSR_RUN;
break;
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
DDADR(prtd->dma_ch) = prtd->dma_desc_array_phys;
DCSR(prtd->dma_ch) |= DCSR_RUN;
break;
default:
ret = -EINVAL;
}
return ret;
}
EXPORT_SYMBOL(pxa2xx_pcm_trigger);
snd_pcm_uframes_t
pxa2xx_pcm_pointer(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct pxa2xx_runtime_data *prtd = runtime->private_data;
dma_addr_t ptr = (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) ?
DSADR(prtd->dma_ch) : DTADR(prtd->dma_ch);
snd_pcm_uframes_t x = bytes_to_frames(runtime, ptr - runtime->dma_addr);
if (x == runtime->buffer_size)
x = 0;
return x;
}
EXPORT_SYMBOL(pxa2xx_pcm_pointer);
int __pxa2xx_pcm_prepare(struct snd_pcm_substream *substream)
{
struct pxa2xx_runtime_data *prtd = substream->runtime->private_data;
if (!prtd || !prtd->params)
return 0;
if (prtd->dma_ch == -1)
return -EINVAL;
DCSR(prtd->dma_ch) &= ~DCSR_RUN;
DCSR(prtd->dma_ch) = 0;
DCMD(prtd->dma_ch) = 0;
*prtd->params->drcmr = prtd->dma_ch | DRCMR_MAPVLD;
return 0;
}
EXPORT_SYMBOL(__pxa2xx_pcm_prepare);
void pxa2xx_pcm_dma_irq(int dma_ch, void *dev_id)
{
struct snd_pcm_substream *substream = dev_id;
struct pxa2xx_runtime_data *rtd = substream->runtime->private_data;
int dcsr;
dcsr = DCSR(dma_ch);
DCSR(dma_ch) = dcsr & ~DCSR_STOPIRQEN;
if (dcsr & DCSR_ENDINTR) {
snd_pcm_period_elapsed(substream);
} else {
printk(KERN_ERR "%s: DMA error on channel %d (DCSR=%#x)\n",
rtd->params->name, dma_ch, dcsr);
snd_pcm_stop(substream, SNDRV_PCM_STATE_XRUN);
}
}
EXPORT_SYMBOL(pxa2xx_pcm_dma_irq);
int __pxa2xx_pcm_open(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct pxa2xx_runtime_data *rtd;
int ret;
runtime->hw = pxa2xx_pcm_hardware;
/*
* For mysterious reasons (and despite what the manual says)
* playback samples are lost if the DMA count is not a multiple
* of the DMA burst size. Let's add a rule to enforce that.
*/
ret = snd_pcm_hw_constraint_step(runtime, 0,
SNDRV_PCM_HW_PARAM_PERIOD_BYTES, 32);
if (ret)
goto out;
ret = snd_pcm_hw_constraint_step(runtime, 0,
SNDRV_PCM_HW_PARAM_BUFFER_BYTES, 32);
if (ret)
goto out;
ret = snd_pcm_hw_constraint_integer(runtime,
SNDRV_PCM_HW_PARAM_PERIODS);
if (ret < 0)
goto out;
ret = -ENOMEM;
rtd = kzalloc(sizeof(*rtd), GFP_KERNEL);
if (!rtd)
goto out;
rtd->dma_desc_array =
dma_alloc_writecombine(substream->pcm->card->dev, PAGE_SIZE,
&rtd->dma_desc_array_phys, GFP_KERNEL);
if (!rtd->dma_desc_array)
goto err1;
rtd->dma_ch = -1;
runtime->private_data = rtd;
return 0;
err1:
kfree(rtd);
out:
return ret;
}
EXPORT_SYMBOL(__pxa2xx_pcm_open);
int __pxa2xx_pcm_close(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct pxa2xx_runtime_data *rtd = runtime->private_data;
dma_free_writecombine(substream->pcm->card->dev, PAGE_SIZE,
rtd->dma_desc_array, rtd->dma_desc_array_phys);
kfree(rtd);
return 0;
}
EXPORT_SYMBOL(__pxa2xx_pcm_close);
int pxa2xx_pcm_mmap(struct snd_pcm_substream *substream,
struct vm_area_struct *vma)
{
struct snd_pcm_runtime *runtime = substream->runtime;
return dma_mmap_writecombine(substream->pcm->card->dev, vma,
runtime->dma_area,
runtime->dma_addr,
runtime->dma_bytes);
}
EXPORT_SYMBOL(pxa2xx_pcm_mmap);
int pxa2xx_pcm_preallocate_dma_buffer(struct snd_pcm *pcm, int stream)
{
struct snd_pcm_substream *substream = pcm->streams[stream].substream;
struct snd_dma_buffer *buf = &substream->dma_buffer;
size_t size = pxa2xx_pcm_hardware.buffer_bytes_max;
buf->dev.type = SNDRV_DMA_TYPE_DEV;
buf->dev.dev = pcm->card->dev;
buf->private_data = NULL;
buf->area = dma_alloc_writecombine(pcm->card->dev, size,
&buf->addr, GFP_KERNEL);
if (!buf->area)
return -ENOMEM;
buf->bytes = size;
return 0;
}
EXPORT_SYMBOL(pxa2xx_pcm_preallocate_dma_buffer);
void pxa2xx_pcm_free_dma_buffers(struct snd_pcm *pcm)
{
struct snd_pcm_substream *substream;
struct snd_dma_buffer *buf;
int stream;
for (stream = 0; stream < 2; stream++) {
substream = pcm->streams[stream].substream;
if (!substream)
continue;
buf = &substream->dma_buffer;
if (!buf->area)
continue;
dma_free_writecombine(pcm->card->dev, buf->bytes,
buf->area, buf->addr);
buf->area = NULL;
}
}
EXPORT_SYMBOL(pxa2xx_pcm_free_dma_buffers);
MODULE_AUTHOR("Nicolas Pitre");
MODULE_DESCRIPTION("Intel PXA2xx sound library");
MODULE_LICENSE("GPL");
| gpl-2.0 |
supersonicninja/CAF-Kernel | arch/sh/mm/tlb-debugfs.c | 12399 | 3927 | /*
* arch/sh/mm/tlb-debugfs.c
*
* debugfs ops for SH-4 ITLB/UTLBs.
*
* Copyright (C) 2010 Matt Fleming
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/debugfs.h>
#include <linux/seq_file.h>
#include <asm/processor.h>
#include <asm/mmu_context.h>
#include <asm/tlbflush.h>
enum tlb_type {
TLB_TYPE_ITLB,
TLB_TYPE_UTLB,
};
static struct {
int bits;
const char *size;
} tlb_sizes[] = {
{ 0x0, " 1KB" },
{ 0x1, " 4KB" },
{ 0x2, " 8KB" },
{ 0x4, " 64KB" },
{ 0x5, "256KB" },
{ 0x7, " 1MB" },
{ 0x8, " 4MB" },
{ 0xc, " 64MB" },
};
static int tlb_seq_show(struct seq_file *file, void *iter)
{
unsigned int tlb_type = (unsigned int)file->private;
unsigned long addr1, addr2, data1, data2;
unsigned long flags;
unsigned long mmucr;
unsigned int nentries, entry;
unsigned int urb;
mmucr = __raw_readl(MMUCR);
if ((mmucr & 0x1) == 0) {
seq_printf(file, "address translation disabled\n");
return 0;
}
if (tlb_type == TLB_TYPE_ITLB) {
addr1 = MMU_ITLB_ADDRESS_ARRAY;
addr2 = MMU_ITLB_ADDRESS_ARRAY2;
data1 = MMU_ITLB_DATA_ARRAY;
data2 = MMU_ITLB_DATA_ARRAY2;
nentries = 4;
} else {
addr1 = MMU_UTLB_ADDRESS_ARRAY;
addr2 = MMU_UTLB_ADDRESS_ARRAY2;
data1 = MMU_UTLB_DATA_ARRAY;
data2 = MMU_UTLB_DATA_ARRAY2;
nentries = 64;
}
local_irq_save(flags);
jump_to_uncached();
urb = (mmucr & MMUCR_URB) >> MMUCR_URB_SHIFT;
/* Make the "entry >= urb" test fail. */
if (urb == 0)
urb = MMUCR_URB_NENTRIES + 1;
if (tlb_type == TLB_TYPE_ITLB) {
addr1 = MMU_ITLB_ADDRESS_ARRAY;
addr2 = MMU_ITLB_ADDRESS_ARRAY2;
data1 = MMU_ITLB_DATA_ARRAY;
data2 = MMU_ITLB_DATA_ARRAY2;
nentries = 4;
} else {
addr1 = MMU_UTLB_ADDRESS_ARRAY;
addr2 = MMU_UTLB_ADDRESS_ARRAY2;
data1 = MMU_UTLB_DATA_ARRAY;
data2 = MMU_UTLB_DATA_ARRAY2;
nentries = 64;
}
seq_printf(file, "entry: vpn ppn asid size valid wired\n");
for (entry = 0; entry < nentries; entry++) {
unsigned long vpn, ppn, asid, size;
unsigned long valid;
unsigned long val;
const char *sz = " ?";
int i;
val = __raw_readl(addr1 | (entry << MMU_TLB_ENTRY_SHIFT));
ctrl_barrier();
vpn = val & 0xfffffc00;
valid = val & 0x100;
val = __raw_readl(addr2 | (entry << MMU_TLB_ENTRY_SHIFT));
ctrl_barrier();
asid = val & MMU_CONTEXT_ASID_MASK;
val = __raw_readl(data1 | (entry << MMU_TLB_ENTRY_SHIFT));
ctrl_barrier();
ppn = (val & 0x0ffffc00) << 4;
val = __raw_readl(data2 | (entry << MMU_TLB_ENTRY_SHIFT));
ctrl_barrier();
size = (val & 0xf0) >> 4;
for (i = 0; i < ARRAY_SIZE(tlb_sizes); i++) {
if (tlb_sizes[i].bits == size)
break;
}
if (i != ARRAY_SIZE(tlb_sizes))
sz = tlb_sizes[i].size;
seq_printf(file, "%2d: 0x%08lx 0x%08lx %5lu %s %s %s\n",
entry, vpn, ppn, asid,
sz, valid ? "V" : "-",
(urb <= entry) ? "W" : "-");
}
back_to_cached();
local_irq_restore(flags);
return 0;
}
static int tlb_debugfs_open(struct inode *inode, struct file *file)
{
return single_open(file, tlb_seq_show, inode->i_private);
}
static const struct file_operations tlb_debugfs_fops = {
.owner = THIS_MODULE,
.open = tlb_debugfs_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int __init tlb_debugfs_init(void)
{
struct dentry *itlb, *utlb;
itlb = debugfs_create_file("itlb", S_IRUSR, arch_debugfs_dir,
(unsigned int *)TLB_TYPE_ITLB,
&tlb_debugfs_fops);
if (unlikely(!itlb))
return -ENOMEM;
utlb = debugfs_create_file("utlb", S_IRUSR, arch_debugfs_dir,
(unsigned int *)TLB_TYPE_UTLB,
&tlb_debugfs_fops);
if (unlikely(!utlb)) {
debugfs_remove(itlb);
return -ENOMEM;
}
return 0;
}
module_init(tlb_debugfs_init);
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
DSMKexec/kexec-kernel | arch/s390/kernel/audit.c | 13935 | 1686 | #include <linux/init.h>
#include <linux/types.h>
#include <linux/audit.h>
#include <asm/unistd.h>
#include "audit.h"
static unsigned dir_class[] = {
#include <asm-generic/audit_dir_write.h>
~0U
};
static unsigned read_class[] = {
#include <asm-generic/audit_read.h>
~0U
};
static unsigned write_class[] = {
#include <asm-generic/audit_write.h>
~0U
};
static unsigned chattr_class[] = {
#include <asm-generic/audit_change_attr.h>
~0U
};
static unsigned signal_class[] = {
#include <asm-generic/audit_signal.h>
~0U
};
int audit_classify_arch(int arch)
{
#ifdef CONFIG_COMPAT
if (arch == AUDIT_ARCH_S390)
return 1;
#endif
return 0;
}
int audit_classify_syscall(int abi, unsigned syscall)
{
#ifdef CONFIG_COMPAT
if (abi == AUDIT_ARCH_S390)
return s390_classify_syscall(syscall);
#endif
switch(syscall) {
case __NR_open:
return 2;
case __NR_openat:
return 3;
case __NR_socketcall:
return 4;
case __NR_execve:
return 5;
default:
return 0;
}
}
static int __init audit_classes_init(void)
{
#ifdef CONFIG_COMPAT
audit_register_class(AUDIT_CLASS_WRITE_32, s390_write_class);
audit_register_class(AUDIT_CLASS_READ_32, s390_read_class);
audit_register_class(AUDIT_CLASS_DIR_WRITE_32, s390_dir_class);
audit_register_class(AUDIT_CLASS_CHATTR_32, s390_chattr_class);
audit_register_class(AUDIT_CLASS_SIGNAL_32, s390_signal_class);
#endif
audit_register_class(AUDIT_CLASS_WRITE, write_class);
audit_register_class(AUDIT_CLASS_READ, read_class);
audit_register_class(AUDIT_CLASS_DIR_WRITE, dir_class);
audit_register_class(AUDIT_CLASS_CHATTR, chattr_class);
audit_register_class(AUDIT_CLASS_SIGNAL, signal_class);
return 0;
}
__initcall(audit_classes_init);
| gpl-2.0 |
morfic/dow-t959 | arch/s390/kernel/audit.c | 13935 | 1686 | #include <linux/init.h>
#include <linux/types.h>
#include <linux/audit.h>
#include <asm/unistd.h>
#include "audit.h"
static unsigned dir_class[] = {
#include <asm-generic/audit_dir_write.h>
~0U
};
static unsigned read_class[] = {
#include <asm-generic/audit_read.h>
~0U
};
static unsigned write_class[] = {
#include <asm-generic/audit_write.h>
~0U
};
static unsigned chattr_class[] = {
#include <asm-generic/audit_change_attr.h>
~0U
};
static unsigned signal_class[] = {
#include <asm-generic/audit_signal.h>
~0U
};
int audit_classify_arch(int arch)
{
#ifdef CONFIG_COMPAT
if (arch == AUDIT_ARCH_S390)
return 1;
#endif
return 0;
}
int audit_classify_syscall(int abi, unsigned syscall)
{
#ifdef CONFIG_COMPAT
if (abi == AUDIT_ARCH_S390)
return s390_classify_syscall(syscall);
#endif
switch(syscall) {
case __NR_open:
return 2;
case __NR_openat:
return 3;
case __NR_socketcall:
return 4;
case __NR_execve:
return 5;
default:
return 0;
}
}
static int __init audit_classes_init(void)
{
#ifdef CONFIG_COMPAT
audit_register_class(AUDIT_CLASS_WRITE_32, s390_write_class);
audit_register_class(AUDIT_CLASS_READ_32, s390_read_class);
audit_register_class(AUDIT_CLASS_DIR_WRITE_32, s390_dir_class);
audit_register_class(AUDIT_CLASS_CHATTR_32, s390_chattr_class);
audit_register_class(AUDIT_CLASS_SIGNAL_32, s390_signal_class);
#endif
audit_register_class(AUDIT_CLASS_WRITE, write_class);
audit_register_class(AUDIT_CLASS_READ, read_class);
audit_register_class(AUDIT_CLASS_DIR_WRITE, dir_class);
audit_register_class(AUDIT_CLASS_CHATTR, chattr_class);
audit_register_class(AUDIT_CLASS_SIGNAL, signal_class);
return 0;
}
__initcall(audit_classes_init);
| gpl-2.0 |
manabian/linux-lpc | fs/binfmt_misc.c | 112 | 18689 | /*
* binfmt_misc.c
*
* Copyright (C) 1997 Richard Günther
*
* binfmt_misc detects binaries via a magic or filename extension and invokes
* a specified wrapper. See Documentation/binfmt_misc.txt for more details.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/magic.h>
#include <linux/binfmts.h>
#include <linux/slab.h>
#include <linux/ctype.h>
#include <linux/string_helpers.h>
#include <linux/file.h>
#include <linux/pagemap.h>
#include <linux/namei.h>
#include <linux/mount.h>
#include <linux/syscalls.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#include "internal.h"
#ifdef DEBUG
# define USE_DEBUG 1
#else
# define USE_DEBUG 0
#endif
enum {
VERBOSE_STATUS = 1 /* make it zero to save 400 bytes kernel memory */
};
static LIST_HEAD(entries);
static int enabled = 1;
enum {Enabled, Magic};
#define MISC_FMT_PRESERVE_ARGV0 (1 << 31)
#define MISC_FMT_OPEN_BINARY (1 << 30)
#define MISC_FMT_CREDENTIALS (1 << 29)
#define MISC_FMT_OPEN_FILE (1 << 28)
typedef struct {
struct list_head list;
unsigned long flags; /* type, status, etc. */
int offset; /* offset of magic */
int size; /* size of magic/mask */
char *magic; /* magic or filename extension */
char *mask; /* mask, NULL for exact match */
char *interpreter; /* filename of interpreter */
char *name;
struct dentry *dentry;
struct file *interp_file;
} Node;
static DEFINE_RWLOCK(entries_lock);
static struct file_system_type bm_fs_type;
static struct vfsmount *bm_mnt;
static int entry_count;
/*
* Max length of the register string. Determined by:
* - 7 delimiters
* - name: ~50 bytes
* - type: 1 byte
* - offset: 3 bytes (has to be smaller than BINPRM_BUF_SIZE)
* - magic: 128 bytes (512 in escaped form)
* - mask: 128 bytes (512 in escaped form)
* - interp: ~50 bytes
* - flags: 5 bytes
* Round that up a bit, and then back off to hold the internal data
* (like struct Node).
*/
#define MAX_REGISTER_LENGTH 1920
/*
* Check if we support the binfmt
* if we do, return the node, else NULL
* locking is done in load_misc_binary
*/
static Node *check_file(struct linux_binprm *bprm)
{
char *p = strrchr(bprm->interp, '.');
struct list_head *l;
/* Walk all the registered handlers. */
list_for_each(l, &entries) {
Node *e = list_entry(l, Node, list);
char *s;
int j;
/* Make sure this one is currently enabled. */
if (!test_bit(Enabled, &e->flags))
continue;
/* Do matching based on extension if applicable. */
if (!test_bit(Magic, &e->flags)) {
if (p && !strcmp(e->magic, p + 1))
return e;
continue;
}
/* Do matching based on magic & mask. */
s = bprm->buf + e->offset;
if (e->mask) {
for (j = 0; j < e->size; j++)
if ((*s++ ^ e->magic[j]) & e->mask[j])
break;
} else {
for (j = 0; j < e->size; j++)
if ((*s++ ^ e->magic[j]))
break;
}
if (j == e->size)
return e;
}
return NULL;
}
/*
* the loader itself
*/
static int load_misc_binary(struct linux_binprm *bprm)
{
Node *fmt;
struct file *interp_file = NULL;
char iname[BINPRM_BUF_SIZE];
const char *iname_addr = iname;
int retval;
int fd_binary = -1;
retval = -ENOEXEC;
if (!enabled)
goto ret;
/* to keep locking time low, we copy the interpreter string */
read_lock(&entries_lock);
fmt = check_file(bprm);
if (fmt)
strlcpy(iname, fmt->interpreter, BINPRM_BUF_SIZE);
read_unlock(&entries_lock);
if (!fmt)
goto ret;
/* Need to be able to load the file after exec */
if (bprm->interp_flags & BINPRM_FLAGS_PATH_INACCESSIBLE)
return -ENOENT;
if (!(fmt->flags & MISC_FMT_PRESERVE_ARGV0)) {
retval = remove_arg_zero(bprm);
if (retval)
goto ret;
}
if (fmt->flags & MISC_FMT_OPEN_BINARY) {
/* if the binary should be opened on behalf of the
* interpreter than keep it open and assign descriptor
* to it
*/
fd_binary = get_unused_fd_flags(0);
if (fd_binary < 0) {
retval = fd_binary;
goto ret;
}
fd_install(fd_binary, bprm->file);
/* if the binary is not readable than enforce mm->dumpable=0
regardless of the interpreter's permissions */
would_dump(bprm, bprm->file);
allow_write_access(bprm->file);
bprm->file = NULL;
/* mark the bprm that fd should be passed to interp */
bprm->interp_flags |= BINPRM_FLAGS_EXECFD;
bprm->interp_data = fd_binary;
} else {
allow_write_access(bprm->file);
fput(bprm->file);
bprm->file = NULL;
}
/* make argv[1] be the path to the binary */
retval = copy_strings_kernel(1, &bprm->interp, bprm);
if (retval < 0)
goto error;
bprm->argc++;
/* add the interp as argv[0] */
retval = copy_strings_kernel(1, &iname_addr, bprm);
if (retval < 0)
goto error;
bprm->argc++;
/* Update interp in case binfmt_script needs it. */
retval = bprm_change_interp(iname, bprm);
if (retval < 0)
goto error;
if (fmt->flags & MISC_FMT_OPEN_FILE && fmt->interp_file) {
interp_file = filp_clone_open(fmt->interp_file);
if (!IS_ERR(interp_file))
deny_write_access(interp_file);
} else {
interp_file = open_exec(iname);
}
retval = PTR_ERR(interp_file);
if (IS_ERR(interp_file))
goto error;
bprm->file = interp_file;
if (fmt->flags & MISC_FMT_CREDENTIALS) {
/*
* No need to call prepare_binprm(), it's already been
* done. bprm->buf is stale, update from interp_file.
*/
memset(bprm->buf, 0, BINPRM_BUF_SIZE);
retval = kernel_read(bprm->file, 0, bprm->buf, BINPRM_BUF_SIZE);
} else
retval = prepare_binprm(bprm);
if (retval < 0)
goto error;
retval = search_binary_handler(bprm);
if (retval < 0)
goto error;
ret:
return retval;
error:
if (fd_binary > 0)
sys_close(fd_binary);
bprm->interp_flags = 0;
bprm->interp_data = 0;
goto ret;
}
/* Command parsers */
/*
* parses and copies one argument enclosed in del from *sp to *dp,
* recognising the \x special.
* returns pointer to the copied argument or NULL in case of an
* error (and sets err) or null argument length.
*/
static char *scanarg(char *s, char del)
{
char c;
while ((c = *s++) != del) {
if (c == '\\' && *s == 'x') {
s++;
if (!isxdigit(*s++))
return NULL;
if (!isxdigit(*s++))
return NULL;
}
}
s[-1] ='\0';
return s;
}
static char *check_special_flags(char *sfs, Node *e)
{
char *p = sfs;
int cont = 1;
/* special flags */
while (cont) {
switch (*p) {
case 'P':
pr_debug("register: flag: P (preserve argv0)\n");
p++;
e->flags |= MISC_FMT_PRESERVE_ARGV0;
break;
case 'O':
pr_debug("register: flag: O (open binary)\n");
p++;
e->flags |= MISC_FMT_OPEN_BINARY;
break;
case 'C':
pr_debug("register: flag: C (preserve creds)\n");
p++;
/* this flags also implies the
open-binary flag */
e->flags |= (MISC_FMT_CREDENTIALS |
MISC_FMT_OPEN_BINARY);
break;
case 'F':
pr_debug("register: flag: F: open interpreter file now\n");
p++;
e->flags |= MISC_FMT_OPEN_FILE;
break;
default:
cont = 0;
}
}
return p;
}
/*
* This registers a new binary format, it recognises the syntax
* ':name:type:offset:magic:mask:interpreter:flags'
* where the ':' is the IFS, that can be chosen with the first char
*/
static Node *create_entry(const char __user *buffer, size_t count)
{
Node *e;
int memsize, err;
char *buf, *p;
char del;
pr_debug("register: received %zu bytes\n", count);
/* some sanity checks */
err = -EINVAL;
if ((count < 11) || (count > MAX_REGISTER_LENGTH))
goto out;
err = -ENOMEM;
memsize = sizeof(Node) + count + 8;
e = kmalloc(memsize, GFP_KERNEL);
if (!e)
goto out;
p = buf = (char *)e + sizeof(Node);
memset(e, 0, sizeof(Node));
if (copy_from_user(buf, buffer, count))
goto efault;
del = *p++; /* delimeter */
pr_debug("register: delim: %#x {%c}\n", del, del);
/* Pad the buffer with the delim to simplify parsing below. */
memset(buf + count, del, 8);
/* Parse the 'name' field. */
e->name = p;
p = strchr(p, del);
if (!p)
goto einval;
*p++ = '\0';
if (!e->name[0] ||
!strcmp(e->name, ".") ||
!strcmp(e->name, "..") ||
strchr(e->name, '/'))
goto einval;
pr_debug("register: name: {%s}\n", e->name);
/* Parse the 'type' field. */
switch (*p++) {
case 'E':
pr_debug("register: type: E (extension)\n");
e->flags = 1 << Enabled;
break;
case 'M':
pr_debug("register: type: M (magic)\n");
e->flags = (1 << Enabled) | (1 << Magic);
break;
default:
goto einval;
}
if (*p++ != del)
goto einval;
if (test_bit(Magic, &e->flags)) {
/* Handle the 'M' (magic) format. */
char *s;
/* Parse the 'offset' field. */
s = strchr(p, del);
if (!s)
goto einval;
*s++ = '\0';
e->offset = simple_strtoul(p, &p, 10);
if (*p++)
goto einval;
pr_debug("register: offset: %#x\n", e->offset);
/* Parse the 'magic' field. */
e->magic = p;
p = scanarg(p, del);
if (!p)
goto einval;
if (!e->magic[0])
goto einval;
if (USE_DEBUG)
print_hex_dump_bytes(
KBUILD_MODNAME ": register: magic[raw]: ",
DUMP_PREFIX_NONE, e->magic, p - e->magic);
/* Parse the 'mask' field. */
e->mask = p;
p = scanarg(p, del);
if (!p)
goto einval;
if (!e->mask[0]) {
e->mask = NULL;
pr_debug("register: mask[raw]: none\n");
} else if (USE_DEBUG)
print_hex_dump_bytes(
KBUILD_MODNAME ": register: mask[raw]: ",
DUMP_PREFIX_NONE, e->mask, p - e->mask);
/*
* Decode the magic & mask fields.
* Note: while we might have accepted embedded NUL bytes from
* above, the unescape helpers here will stop at the first one
* it encounters.
*/
e->size = string_unescape_inplace(e->magic, UNESCAPE_HEX);
if (e->mask &&
string_unescape_inplace(e->mask, UNESCAPE_HEX) != e->size)
goto einval;
if (e->size + e->offset > BINPRM_BUF_SIZE)
goto einval;
pr_debug("register: magic/mask length: %i\n", e->size);
if (USE_DEBUG) {
print_hex_dump_bytes(
KBUILD_MODNAME ": register: magic[decoded]: ",
DUMP_PREFIX_NONE, e->magic, e->size);
if (e->mask) {
int i;
char *masked = kmalloc(e->size, GFP_KERNEL);
print_hex_dump_bytes(
KBUILD_MODNAME ": register: mask[decoded]: ",
DUMP_PREFIX_NONE, e->mask, e->size);
if (masked) {
for (i = 0; i < e->size; ++i)
masked[i] = e->magic[i] & e->mask[i];
print_hex_dump_bytes(
KBUILD_MODNAME ": register: magic[masked]: ",
DUMP_PREFIX_NONE, masked, e->size);
kfree(masked);
}
}
}
} else {
/* Handle the 'E' (extension) format. */
/* Skip the 'offset' field. */
p = strchr(p, del);
if (!p)
goto einval;
*p++ = '\0';
/* Parse the 'magic' field. */
e->magic = p;
p = strchr(p, del);
if (!p)
goto einval;
*p++ = '\0';
if (!e->magic[0] || strchr(e->magic, '/'))
goto einval;
pr_debug("register: extension: {%s}\n", e->magic);
/* Skip the 'mask' field. */
p = strchr(p, del);
if (!p)
goto einval;
*p++ = '\0';
}
/* Parse the 'interpreter' field. */
e->interpreter = p;
p = strchr(p, del);
if (!p)
goto einval;
*p++ = '\0';
if (!e->interpreter[0])
goto einval;
pr_debug("register: interpreter: {%s}\n", e->interpreter);
/* Parse the 'flags' field. */
p = check_special_flags(p, e);
if (*p == '\n')
p++;
if (p != buf + count)
goto einval;
return e;
out:
return ERR_PTR(err);
efault:
kfree(e);
return ERR_PTR(-EFAULT);
einval:
kfree(e);
return ERR_PTR(-EINVAL);
}
/*
* Set status of entry/binfmt_misc:
* '1' enables, '0' disables and '-1' clears entry/binfmt_misc
*/
static int parse_command(const char __user *buffer, size_t count)
{
char s[4];
if (count > 3)
return -EINVAL;
if (copy_from_user(s, buffer, count))
return -EFAULT;
if (!count)
return 0;
if (s[count - 1] == '\n')
count--;
if (count == 1 && s[0] == '0')
return 1;
if (count == 1 && s[0] == '1')
return 2;
if (count == 2 && s[0] == '-' && s[1] == '1')
return 3;
return -EINVAL;
}
/* generic stuff */
static void entry_status(Node *e, char *page)
{
char *dp = page;
const char *status = "disabled";
if (test_bit(Enabled, &e->flags))
status = "enabled";
if (!VERBOSE_STATUS) {
sprintf(page, "%s\n", status);
return;
}
dp += sprintf(dp, "%s\ninterpreter %s\n", status, e->interpreter);
/* print the special flags */
dp += sprintf(dp, "flags: ");
if (e->flags & MISC_FMT_PRESERVE_ARGV0)
*dp++ = 'P';
if (e->flags & MISC_FMT_OPEN_BINARY)
*dp++ = 'O';
if (e->flags & MISC_FMT_CREDENTIALS)
*dp++ = 'C';
if (e->flags & MISC_FMT_OPEN_FILE)
*dp++ = 'F';
*dp++ = '\n';
if (!test_bit(Magic, &e->flags)) {
sprintf(dp, "extension .%s\n", e->magic);
} else {
dp += sprintf(dp, "offset %i\nmagic ", e->offset);
dp = bin2hex(dp, e->magic, e->size);
if (e->mask) {
dp += sprintf(dp, "\nmask ");
dp = bin2hex(dp, e->mask, e->size);
}
*dp++ = '\n';
*dp = '\0';
}
}
static struct inode *bm_get_inode(struct super_block *sb, int mode)
{
struct inode *inode = new_inode(sb);
if (inode) {
inode->i_ino = get_next_ino();
inode->i_mode = mode;
inode->i_atime = inode->i_mtime = inode->i_ctime =
current_time(inode);
}
return inode;
}
static void bm_evict_inode(struct inode *inode)
{
clear_inode(inode);
kfree(inode->i_private);
}
static void kill_node(Node *e)
{
struct dentry *dentry;
write_lock(&entries_lock);
dentry = e->dentry;
if (dentry) {
list_del_init(&e->list);
e->dentry = NULL;
}
write_unlock(&entries_lock);
if ((e->flags & MISC_FMT_OPEN_FILE) && e->interp_file) {
filp_close(e->interp_file, NULL);
e->interp_file = NULL;
}
if (dentry) {
drop_nlink(d_inode(dentry));
d_drop(dentry);
dput(dentry);
simple_release_fs(&bm_mnt, &entry_count);
}
}
/* /<entry> */
static ssize_t
bm_entry_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
{
Node *e = file_inode(file)->i_private;
ssize_t res;
char *page;
page = (char *) __get_free_page(GFP_KERNEL);
if (!page)
return -ENOMEM;
entry_status(e, page);
res = simple_read_from_buffer(buf, nbytes, ppos, page, strlen(page));
free_page((unsigned long) page);
return res;
}
static ssize_t bm_entry_write(struct file *file, const char __user *buffer,
size_t count, loff_t *ppos)
{
struct dentry *root;
Node *e = file_inode(file)->i_private;
int res = parse_command(buffer, count);
switch (res) {
case 1:
/* Disable this handler. */
clear_bit(Enabled, &e->flags);
break;
case 2:
/* Enable this handler. */
set_bit(Enabled, &e->flags);
break;
case 3:
/* Delete this handler. */
root = file_inode(file)->i_sb->s_root;
inode_lock(d_inode(root));
kill_node(e);
inode_unlock(d_inode(root));
break;
default:
return res;
}
return count;
}
static const struct file_operations bm_entry_operations = {
.read = bm_entry_read,
.write = bm_entry_write,
.llseek = default_llseek,
};
/* /register */
static ssize_t bm_register_write(struct file *file, const char __user *buffer,
size_t count, loff_t *ppos)
{
Node *e;
struct inode *inode;
struct super_block *sb = file_inode(file)->i_sb;
struct dentry *root = sb->s_root, *dentry;
int err = 0;
e = create_entry(buffer, count);
if (IS_ERR(e))
return PTR_ERR(e);
inode_lock(d_inode(root));
dentry = lookup_one_len(e->name, root, strlen(e->name));
err = PTR_ERR(dentry);
if (IS_ERR(dentry))
goto out;
err = -EEXIST;
if (d_really_is_positive(dentry))
goto out2;
inode = bm_get_inode(sb, S_IFREG | 0644);
err = -ENOMEM;
if (!inode)
goto out2;
err = simple_pin_fs(&bm_fs_type, &bm_mnt, &entry_count);
if (err) {
iput(inode);
inode = NULL;
goto out2;
}
if (e->flags & MISC_FMT_OPEN_FILE) {
struct file *f;
f = open_exec(e->interpreter);
if (IS_ERR(f)) {
err = PTR_ERR(f);
pr_notice("register: failed to install interpreter file %s\n", e->interpreter);
simple_release_fs(&bm_mnt, &entry_count);
iput(inode);
inode = NULL;
goto out2;
}
e->interp_file = f;
}
e->dentry = dget(dentry);
inode->i_private = e;
inode->i_fop = &bm_entry_operations;
d_instantiate(dentry, inode);
write_lock(&entries_lock);
list_add(&e->list, &entries);
write_unlock(&entries_lock);
err = 0;
out2:
dput(dentry);
out:
inode_unlock(d_inode(root));
if (err) {
kfree(e);
return err;
}
return count;
}
static const struct file_operations bm_register_operations = {
.write = bm_register_write,
.llseek = noop_llseek,
};
/* /status */
static ssize_t
bm_status_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
{
char *s = enabled ? "enabled\n" : "disabled\n";
return simple_read_from_buffer(buf, nbytes, ppos, s, strlen(s));
}
static ssize_t bm_status_write(struct file *file, const char __user *buffer,
size_t count, loff_t *ppos)
{
int res = parse_command(buffer, count);
struct dentry *root;
switch (res) {
case 1:
/* Disable all handlers. */
enabled = 0;
break;
case 2:
/* Enable all handlers. */
enabled = 1;
break;
case 3:
/* Delete all handlers. */
root = file_inode(file)->i_sb->s_root;
inode_lock(d_inode(root));
while (!list_empty(&entries))
kill_node(list_entry(entries.next, Node, list));
inode_unlock(d_inode(root));
break;
default:
return res;
}
return count;
}
static const struct file_operations bm_status_operations = {
.read = bm_status_read,
.write = bm_status_write,
.llseek = default_llseek,
};
/* Superblock handling */
static const struct super_operations s_ops = {
.statfs = simple_statfs,
.evict_inode = bm_evict_inode,
};
static int bm_fill_super(struct super_block *sb, void *data, int silent)
{
int err;
static struct tree_descr bm_files[] = {
[2] = {"status", &bm_status_operations, S_IWUSR|S_IRUGO},
[3] = {"register", &bm_register_operations, S_IWUSR},
/* last one */ {""}
};
err = simple_fill_super(sb, BINFMTFS_MAGIC, bm_files);
if (!err)
sb->s_op = &s_ops;
return err;
}
static struct dentry *bm_mount(struct file_system_type *fs_type,
int flags, const char *dev_name, void *data)
{
return mount_single(fs_type, flags, data, bm_fill_super);
}
static struct linux_binfmt misc_format = {
.module = THIS_MODULE,
.load_binary = load_misc_binary,
};
static struct file_system_type bm_fs_type = {
.owner = THIS_MODULE,
.name = "binfmt_misc",
.mount = bm_mount,
.kill_sb = kill_litter_super,
};
MODULE_ALIAS_FS("binfmt_misc");
static int __init init_misc_binfmt(void)
{
int err = register_filesystem(&bm_fs_type);
if (!err)
insert_binfmt(&misc_format);
return err;
}
static void __exit exit_misc_binfmt(void)
{
unregister_binfmt(&misc_format);
unregister_filesystem(&bm_fs_type);
}
core_initcall(init_misc_binfmt);
module_exit(exit_misc_binfmt);
MODULE_LICENSE("GPL");
| gpl-2.0 |
huwan/linux-buffer-debug | kernel/ksysfs.c | 112 | 4434 | /*
* kernel/ksysfs.c - sysfs attributes in /sys/kernel, which
* are not related to any other subsystem
*
* Copyright (C) 2004 Kay Sievers <kay.sievers@vrfy.org>
*
* This file is release under the GPLv2
*
*/
#include <linux/kobject.h>
#include <linux/string.h>
#include <linux/sysfs.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kexec.h>
#include <linux/profile.h>
#include <linux/sched.h>
#define KERNEL_ATTR_RO(_name) \
static struct kobj_attribute _name##_attr = __ATTR_RO(_name)
#define KERNEL_ATTR_RW(_name) \
static struct kobj_attribute _name##_attr = \
__ATTR(_name, 0644, _name##_show, _name##_store)
#if defined(CONFIG_HOTPLUG)
/* current uevent sequence number */
static ssize_t uevent_seqnum_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
return sprintf(buf, "%llu\n", (unsigned long long)uevent_seqnum);
}
KERNEL_ATTR_RO(uevent_seqnum);
/* uevent helper program, used during early boo */
static ssize_t uevent_helper_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
return sprintf(buf, "%s\n", uevent_helper);
}
static ssize_t uevent_helper_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t count)
{
if (count+1 > UEVENT_HELPER_PATH_LEN)
return -ENOENT;
memcpy(uevent_helper, buf, count);
uevent_helper[count] = '\0';
if (count && uevent_helper[count-1] == '\n')
uevent_helper[count-1] = '\0';
return count;
}
KERNEL_ATTR_RW(uevent_helper);
#endif
#ifdef CONFIG_PROFILING
static ssize_t profiling_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
return sprintf(buf, "%d\n", prof_on);
}
static ssize_t profiling_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t count)
{
int ret;
if (prof_on)
return -EEXIST;
/*
* This eventually calls into get_option() which
* has a ton of callers and is not const. It is
* easiest to cast it away here.
*/
profile_setup((char *)buf);
ret = profile_init();
if (ret)
return ret;
ret = create_proc_profile();
if (ret)
return ret;
return count;
}
KERNEL_ATTR_RW(profiling);
#endif
#ifdef CONFIG_KEXEC
static ssize_t kexec_loaded_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
return sprintf(buf, "%d\n", !!kexec_image);
}
KERNEL_ATTR_RO(kexec_loaded);
static ssize_t kexec_crash_loaded_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
return sprintf(buf, "%d\n", !!kexec_crash_image);
}
KERNEL_ATTR_RO(kexec_crash_loaded);
static ssize_t vmcoreinfo_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
return sprintf(buf, "%lx %x\n",
paddr_vmcoreinfo_note(),
(unsigned int)vmcoreinfo_max_size);
}
KERNEL_ATTR_RO(vmcoreinfo);
#endif /* CONFIG_KEXEC */
/*
* Make /sys/kernel/notes give the raw contents of our kernel .notes section.
*/
extern const void __start_notes __attribute__((weak));
extern const void __stop_notes __attribute__((weak));
#define notes_size (&__stop_notes - &__start_notes)
static ssize_t notes_read(struct kobject *kobj, struct bin_attribute *bin_attr,
char *buf, loff_t off, size_t count)
{
memcpy(buf, &__start_notes + off, count);
return count;
}
static struct bin_attribute notes_attr = {
.attr = {
.name = "notes",
.mode = S_IRUGO,
},
.read = ¬es_read,
};
struct kobject *kernel_kobj;
EXPORT_SYMBOL_GPL(kernel_kobj);
static struct attribute * kernel_attrs[] = {
#if defined(CONFIG_HOTPLUG)
&uevent_seqnum_attr.attr,
&uevent_helper_attr.attr,
#endif
#ifdef CONFIG_PROFILING
&profiling_attr.attr,
#endif
#ifdef CONFIG_KEXEC
&kexec_loaded_attr.attr,
&kexec_crash_loaded_attr.attr,
&vmcoreinfo_attr.attr,
#endif
NULL
};
static struct attribute_group kernel_attr_group = {
.attrs = kernel_attrs,
};
static int __init ksysfs_init(void)
{
int error;
kernel_kobj = kobject_create_and_add("kernel", NULL);
if (!kernel_kobj) {
error = -ENOMEM;
goto exit;
}
error = sysfs_create_group(kernel_kobj, &kernel_attr_group);
if (error)
goto kset_exit;
if (notes_size > 0) {
notes_attr.size = notes_size;
error = sysfs_create_bin_file(kernel_kobj, ¬es_attr);
if (error)
goto group_exit;
}
return 0;
group_exit:
sysfs_remove_group(kernel_kobj, &kernel_attr_group);
kset_exit:
kobject_put(kernel_kobj);
exit:
return error;
}
core_initcall(ksysfs_init);
| gpl-2.0 |
rock12/ALPS.L1.MP6.V2.19_CENON6580_WE_1_L_KERNEL | drivers/misc/mediatek/masp/asf/core/sec_usif.c | 112 | 2811 | #include "sec_osal_light.h"
#include "sec_boot_lib.h"
#include "sec_boot.h"
#include "sec_error.h"
#include "sec_typedef.h"
#include "sec_log.h"
/**************************************************************************
* MACRO
**************************************************************************/
#define MOD "ASF.USIF"
/**************************************************************************
* EXTERNAL VARIABLES
*************************************************************************/
extern SECURE_INFO sec_info;
/**************************************************************************
* FIND DEVICE PARTITION
**************************************************************************/
int sec_usif_check(void)
{
int ret = SEC_OK;
ASF_FILE fd;
const uint32 buf_len = 2048;
char *buf = ASF_MALLOC(buf_len);
char *pmtdbufp;
uint32 rn = 0;
ssize_t pm_sz;
int cnt;
ASF_GET_DS
/* -------------------------- */
/* open proc device */
/* -------------------------- */
SMSG(TRUE,"[%s] open /proc/dumchar_info\n",MOD);
fd = ASF_OPEN("/proc/dumchar_info");
if (ASF_FILE_ERROR(fd))
{
SMSG(TRUE,"[%s] open /proc/dumchar_info fail\n",MOD);
goto _usif_dis;
}
buf[buf_len - 1] = '\0';
pm_sz = ASF_READ(fd, buf, buf_len - 1);
pmtdbufp = buf;
/* -------------------------- */
/* parsing proc device */
/* -------------------------- */
while (pm_sz > 0)
{
int m_num, m_sz, mtd_e_sz;
char m_name[16];
m_name[0] = '\0';
m_num = -1;
m_num ++;
/* -------------------------- */
/* parsing proc/dumchar_info */
/* -------------------------- */
cnt = sscanf(pmtdbufp, "%15s %x %x %x",m_name, &m_sz, &mtd_e_sz, &rn);
if ((4 == cnt) && (2 == rn))
{
SMSG(TRUE,"[%s] RN = 2\n",MOD);
goto _usif_en;
}
else if ((4 == cnt) && (1 == rn))
{
SMSG(TRUE,"[%s] RN = 1\n",MOD);
goto _usif_dis;
}
while (pm_sz > 0 && *pmtdbufp != '\n')
{
pmtdbufp++;
pm_sz--;
}
if (pm_sz > 0)
{
pmtdbufp++;
pm_sz--;
}
}
SMSG(TRUE,"[%s] usif RN not found\n",MOD);
ret = ERR_USIF_PROC_RN_NOT_FOUND;
goto _exit;
_usif_en:
SMSG(TRUE,"[%s] usif enabled\n",MOD);
sec_info.bUsifEn = TRUE;
goto _exit;
_usif_dis:
SMSG(TRUE,"[%s] usif disabled\n",MOD);
sec_info.bUsifEn = FALSE;
_exit:
ASF_CLOSE(fd);
ASF_FREE(buf);
ASF_PUT_DS
return ret;
}
| gpl-2.0 |
fredericgermain/linux-sunxi | drivers/staging/tidspbridge/dynload/tramp.c | 112 | 35670 | /*
* tramp.c
*
* DSP-BIOS Bridge driver support functions for TI OMAP processors.
*
* Copyright (C) 2009 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 "header.h"
#if TMS32060
#include "tramp_table_c6000.c"
#endif
#define MAX_RELOS_PER_PASS 4
/*
* Function: priv_tramp_sect_tgt_alloc
* Description: Allocate target memory for the trampoline section. The
* target mem size is easily obtained as the next available address.
*/
static int priv_tramp_sect_tgt_alloc(struct dload_state *dlthis)
{
int ret_val = 0;
struct ldr_section_info *sect_info;
/* Populate the trampoline loader section and allocate it on the
* target. The section name is ALWAYS the first string in the final
* string table for trampolines. The trampoline section is always
* 1 beyond the total number of allocated sections. */
sect_info = &dlthis->ldr_sections[dlthis->allocated_secn_count];
sect_info->name = dlthis->tramp.final_string_table;
sect_info->size = dlthis->tramp.tramp_sect_next_addr;
sect_info->context = 0;
sect_info->type =
(4 << 8) | DLOAD_TEXT | DS_ALLOCATE_MASK | DS_DOWNLOAD_MASK;
sect_info->page = 0;
sect_info->run_addr = 0;
sect_info->load_addr = 0;
ret_val = dlthis->myalloc->dload_allocate(dlthis->myalloc,
sect_info,
ds_alignment
(sect_info->type));
if (ret_val == 0)
dload_error(dlthis, "Failed to allocate target memory for"
" trampoline");
return ret_val;
}
/*
* Function: priv_h2a
* Description: Helper function to convert a hex value to its ASCII
* representation. Used for trampoline symbol name generation.
*/
static u8 priv_h2a(u8 value)
{
if (value > 0xF)
return 0xFF;
if (value <= 9)
value += 0x30;
else
value += 0x37;
return value;
}
/*
* Function: priv_tramp_sym_gen_name
* Description: Generate a trampoline symbol name (ASCII) using the value
* of the symbol. This places the new name into the user buffer.
* The name is fixed in length and of the form: __$dbTR__xxxxxxxx
* (where "xxxxxxxx" is the hex value).
*/
static void priv_tramp_sym_gen_name(u32 value, char *dst)
{
u32 i;
char *prefix = TRAMP_SYM_PREFIX;
char *dst_local = dst;
u8 tmp;
/* Clear out the destination, including the ending NULL */
for (i = 0; i < (TRAMP_SYM_PREFIX_LEN + TRAMP_SYM_HEX_ASCII_LEN); i++)
*(dst_local + i) = 0;
/* Copy the prefix to start */
for (i = 0; i < strlen(TRAMP_SYM_PREFIX); i++) {
*dst_local = *(prefix + i);
dst_local++;
}
/* Now convert the value passed in to a string equiv of the hex */
for (i = 0; i < sizeof(value); i++) {
#ifndef _BIG_ENDIAN
tmp = *(((u8 *) &value) + (sizeof(value) - 1) - i);
*dst_local = priv_h2a((tmp & 0xF0) >> 4);
dst_local++;
*dst_local = priv_h2a(tmp & 0x0F);
dst_local++;
#else
tmp = *(((u8 *) &value) + i);
*dst_local = priv_h2a((tmp & 0xF0) >> 4);
dst_local++;
*dst_local = priv_h2a(tmp & 0x0F);
dst_local++;
#endif
}
/* NULL terminate */
*dst_local = 0;
}
/*
* Function: priv_tramp_string_create
* Description: Create a new string specific to the trampoline loading and add
* it to the trampoline string list. This list contains the
* trampoline section name and trampoline point symbols.
*/
static struct tramp_string *priv_tramp_string_create(struct dload_state *dlthis,
u32 str_len, char *str)
{
struct tramp_string *new_string = NULL;
u32 i;
/* Create a new string object with the specified size. */
new_string =
(struct tramp_string *)dlthis->mysym->dload_allocate(dlthis->mysym,
(sizeof
(struct
tramp_string)
+ str_len +
1));
if (new_string != NULL) {
/* Clear the string first. This ensures the ending NULL is
* present and the optimizer won't touch it. */
for (i = 0; i < (sizeof(struct tramp_string) + str_len + 1);
i++)
*((u8 *) new_string + i) = 0;
/* Add this string to our virtual table by assigning it the
* next index and pushing it to the tail of the list. */
new_string->index = dlthis->tramp.tramp_string_next_index;
dlthis->tramp.tramp_string_next_index++;
dlthis->tramp.tramp_string_size += str_len + 1;
new_string->next = NULL;
if (dlthis->tramp.string_head == NULL)
dlthis->tramp.string_head = new_string;
else
dlthis->tramp.string_tail->next = new_string;
dlthis->tramp.string_tail = new_string;
/* Copy the string over to the new object */
for (i = 0; i < str_len; i++)
new_string->str[i] = str[i];
}
return new_string;
}
/*
* Function: priv_tramp_string_find
* Description: Walk the trampoline string list and find a match for the
* provided string. If not match is found, NULL is returned.
*/
static struct tramp_string *priv_tramp_string_find(struct dload_state *dlthis,
char *str)
{
struct tramp_string *cur_str = NULL;
struct tramp_string *ret_val = NULL;
u32 i;
u32 str_len = strlen(str);
for (cur_str = dlthis->tramp.string_head;
(ret_val == NULL) && (cur_str != NULL); cur_str = cur_str->next) {
/* If the string lengths aren't equal, don't bother
* comparing */
if (str_len != strlen(cur_str->str))
continue;
/* Walk the strings until one of them ends */
for (i = 0; i < str_len; i++) {
/* If they don't match in the current position then
* break out now, no sense in continuing to look at
* this string. */
if (str[i] != cur_str->str[i])
break;
}
if (i == str_len)
ret_val = cur_str;
}
return ret_val;
}
/*
* Function: priv_string_tbl_finalize
* Description: Flatten the trampoline string list into a table of NULL
* terminated strings. This is the same format of string table
* as used by the COFF/DOFF file.
*/
static int priv_string_tbl_finalize(struct dload_state *dlthis)
{
int ret_val = 0;
struct tramp_string *cur_string;
char *cur_loc;
char *tmp;
/* Allocate enough space for all strings that have been created. The
* table is simply all strings concatenated together will NULL
* endings. */
dlthis->tramp.final_string_table =
(char *)dlthis->mysym->dload_allocate(dlthis->mysym,
dlthis->tramp.
tramp_string_size);
if (dlthis->tramp.final_string_table != NULL) {
/* We got our buffer, walk the list and release the nodes as*
* we go */
cur_loc = dlthis->tramp.final_string_table;
cur_string = dlthis->tramp.string_head;
while (cur_string != NULL) {
/* Move the head/tail pointers */
dlthis->tramp.string_head = cur_string->next;
if (dlthis->tramp.string_tail == cur_string)
dlthis->tramp.string_tail = NULL;
/* Copy the string contents */
for (tmp = cur_string->str;
*tmp != '\0'; tmp++, cur_loc++)
*cur_loc = *tmp;
/* Pick up the NULL termination since it was missed by
* breaking using it to end the above loop. */
*cur_loc = '\0';
cur_loc++;
/* Free the string node, we don't need it any more. */
dlthis->mysym->dload_deallocate(dlthis->mysym,
cur_string);
/* Move our pointer to the next one */
cur_string = dlthis->tramp.string_head;
}
/* Update our return value to success */
ret_val = 1;
} else
dload_error(dlthis, "Failed to allocate trampoline "
"string table");
return ret_val;
}
/*
* Function: priv_tramp_sect_alloc
* Description: Virtually allocate space from the trampoline section. This
* function returns the next offset within the trampoline section
* that is available and moved the next available offset by the
* requested size. NO TARGET ALLOCATION IS DONE AT THIS TIME.
*/
static u32 priv_tramp_sect_alloc(struct dload_state *dlthis, u32 tramp_size)
{
u32 ret_val;
/* If the next available address is 0, this is our first allocation.
* Create a section name string to go into the string table . */
if (dlthis->tramp.tramp_sect_next_addr == 0) {
dload_syms_error(dlthis->mysym, "*** WARNING *** created "
"dynamic TRAMPOLINE section for module %s",
dlthis->str_head);
}
/* Reserve space for the new trampoline */
ret_val = dlthis->tramp.tramp_sect_next_addr;
dlthis->tramp.tramp_sect_next_addr += tramp_size;
return ret_val;
}
/*
* Function: priv_tramp_sym_create
* Description: Allocate and create a new trampoline specific symbol and add
* it to the trampoline symbol list. These symbols will include
* trampoline points as well as the external symbols they
* reference.
*/
static struct tramp_sym *priv_tramp_sym_create(struct dload_state *dlthis,
u32 str_index,
struct local_symbol *tmp_sym)
{
struct tramp_sym *new_sym = NULL;
u32 i;
/* Allocate new space for the symbol in the symbol table. */
new_sym =
(struct tramp_sym *)dlthis->mysym->dload_allocate(dlthis->mysym,
sizeof(struct tramp_sym));
if (new_sym != NULL) {
for (i = 0; i != sizeof(struct tramp_sym); i++)
*((char *)new_sym + i) = 0;
/* Assign this symbol the next symbol index for easier
* reference later during relocation. */
new_sym->index = dlthis->tramp.tramp_sym_next_index;
dlthis->tramp.tramp_sym_next_index++;
/* Populate the symbol information. At this point any
* trampoline symbols will be the offset location, not the
* final. Copy over the symbol info to start, then be sure to
* get the string index from the trampoline string table. */
new_sym->sym_info = *tmp_sym;
new_sym->str_index = str_index;
/* Push the new symbol to the tail of the symbol table list */
new_sym->next = NULL;
if (dlthis->tramp.symbol_head == NULL)
dlthis->tramp.symbol_head = new_sym;
else
dlthis->tramp.symbol_tail->next = new_sym;
dlthis->tramp.symbol_tail = new_sym;
}
return new_sym;
}
/*
* Function: priv_tramp_sym_get
* Description: Search for the symbol with the matching string index (from
* the trampoline string table) and return the trampoline
* symbol object, if found. Otherwise return NULL.
*/
static struct tramp_sym *priv_tramp_sym_get(struct dload_state *dlthis,
u32 string_index)
{
struct tramp_sym *sym_found = NULL;
/* Walk the symbol table list and search vs. the string index */
for (sym_found = dlthis->tramp.symbol_head;
sym_found != NULL; sym_found = sym_found->next) {
if (sym_found->str_index == string_index)
break;
}
return sym_found;
}
/*
* Function: priv_tramp_sym_find
* Description: Search for a trampoline symbol based on the string name of
* the symbol. Return the symbol object, if found, otherwise
* return NULL.
*/
static struct tramp_sym *priv_tramp_sym_find(struct dload_state *dlthis,
char *string)
{
struct tramp_sym *sym_found = NULL;
struct tramp_string *str_found = NULL;
/* First, search for the string, then search for the sym based on the
string index. */
str_found = priv_tramp_string_find(dlthis, string);
if (str_found != NULL)
sym_found = priv_tramp_sym_get(dlthis, str_found->index);
return sym_found;
}
/*
* Function: priv_tramp_sym_finalize
* Description: Allocate a flat symbol table for the trampoline section,
* put each trampoline symbol into the table, adjust the
* symbol value based on the section address on the target and
* free the trampoline symbol list nodes.
*/
static int priv_tramp_sym_finalize(struct dload_state *dlthis)
{
int ret_val = 0;
struct tramp_sym *cur_sym;
struct ldr_section_info *tramp_sect =
&dlthis->ldr_sections[dlthis->allocated_secn_count];
struct local_symbol *new_sym;
/* Allocate a table to hold a flattened version of all symbols
* created. */
dlthis->tramp.final_sym_table =
(struct local_symbol *)dlthis->mysym->dload_allocate(dlthis->mysym,
(sizeof(struct local_symbol) * dlthis->tramp.
tramp_sym_next_index));
if (dlthis->tramp.final_sym_table != NULL) {
/* Walk the list of all symbols, copy it over to the flattened
* table. After it has been copied, the node can be freed as
* it is no longer needed. */
new_sym = dlthis->tramp.final_sym_table;
cur_sym = dlthis->tramp.symbol_head;
while (cur_sym != NULL) {
/* Pop it off the list */
dlthis->tramp.symbol_head = cur_sym->next;
if (cur_sym == dlthis->tramp.symbol_tail)
dlthis->tramp.symbol_tail = NULL;
/* Copy the symbol contents into the flat table */
*new_sym = cur_sym->sym_info;
/* Now finalize the symbol. If it is in the tramp
* section, we need to adjust for the section start.
* If it is external then we don't need to adjust at
* all.
* NOTE: THIS CODE ASSUMES THAT THE TRAMPOLINE IS
* REFERENCED LIKE A CALL TO AN EXTERNAL SO VALUE AND
* DELTA ARE THE SAME. SEE THE FUNCTION dload_symbols
* WHERE DN_UNDEF IS HANDLED FOR MORE REFERENCE. */
if (new_sym->secnn < 0) {
new_sym->value += tramp_sect->load_addr;
new_sym->delta = new_sym->value;
}
/* Let go of the symbol node */
dlthis->mysym->dload_deallocate(dlthis->mysym, cur_sym);
/* Move to the next node */
cur_sym = dlthis->tramp.symbol_head;
new_sym++;
}
ret_val = 1;
} else
dload_error(dlthis, "Failed to alloc trampoline sym table");
return ret_val;
}
/*
* Function: priv_tgt_img_gen
* Description: Allocate storage for and copy the target specific image data
* and fix up its relocations for the new external symbol. If
* a trampoline image packet was successfully created it is added
* to the trampoline list.
*/
static int priv_tgt_img_gen(struct dload_state *dlthis, u32 base,
u32 gen_index, struct tramp_sym *new_ext_sym)
{
struct tramp_img_pkt *new_img_pkt = NULL;
u32 i;
u32 pkt_size = tramp_img_pkt_size_get();
u8 *gen_tbl_entry;
u8 *pkt_data;
struct reloc_record_t *cur_relo;
int ret_val = 0;
/* Allocate a new image packet and set it up. */
new_img_pkt =
(struct tramp_img_pkt *)dlthis->mysym->dload_allocate(dlthis->mysym,
pkt_size);
if (new_img_pkt != NULL) {
/* Save the base, this is where it goes in the section */
new_img_pkt->base = base;
/* Copy over the image data and relos from the target table */
pkt_data = (u8 *) &new_img_pkt->hdr;
gen_tbl_entry = (u8 *) &tramp_gen_info[gen_index];
for (i = 0; i < pkt_size; i++) {
*pkt_data = *gen_tbl_entry;
pkt_data++;
gen_tbl_entry++;
}
/* Update the relocations to point to the external symbol */
cur_relo =
(struct reloc_record_t *)((u8 *) &new_img_pkt->hdr +
new_img_pkt->hdr.relo_offset);
for (i = 0; i < new_img_pkt->hdr.num_relos; i++)
cur_relo[i].SYMNDX = new_ext_sym->index;
/* Add it to the trampoline list. */
new_img_pkt->next = dlthis->tramp.tramp_pkts;
dlthis->tramp.tramp_pkts = new_img_pkt;
ret_val = 1;
}
return ret_val;
}
/*
* Function: priv_pkt_relo
* Description: Take the provided image data and the collection of relocations
* for it and perform the relocations. Note that all relocations
* at this stage are considered SECOND PASS since the original
* image has already been processed in the first pass. This means
* TRAMPOLINES ARE TREATED AS 2ND PASS even though this is really
* the first (and only) relocation that will be performed on them.
*/
static int priv_pkt_relo(struct dload_state *dlthis, tgt_au_t *data,
struct reloc_record_t *rp[], u32 relo_count)
{
int ret_val = 1;
u32 i;
bool tmp;
/* Walk through all of the relos and process them. This function is
* the equivalent of relocate_packet() from cload.c, but specialized
* for trampolines and 2nd phase relocations. */
for (i = 0; i < relo_count; i++)
dload_relocate(dlthis, data, rp[i], &tmp, true);
return ret_val;
}
/*
* Function: priv_tramp_pkt_finalize
* Description: Walk the list of all trampoline packets and finalize them.
* Each trampoline image packet will be relocated now that the
* trampoline section has been allocated on the target. Once
* all of the relocations are done the trampoline image data
* is written into target memory and the trampoline packet
* is freed: it is no longer needed after this point.
*/
static int priv_tramp_pkt_finalize(struct dload_state *dlthis)
{
int ret_val = 1;
struct tramp_img_pkt *cur_pkt = NULL;
struct reloc_record_t *relos[MAX_RELOS_PER_PASS];
u32 relos_done;
u32 i;
struct reloc_record_t *cur_relo;
struct ldr_section_info *sect_info =
&dlthis->ldr_sections[dlthis->allocated_secn_count];
/* Walk the list of trampoline packets and relocate each packet. This
* function is the trampoline equivalent of dload_data() from
* cload.c. */
cur_pkt = dlthis->tramp.tramp_pkts;
while ((ret_val != 0) && (cur_pkt != NULL)) {
/* Remove the pkt from the list */
dlthis->tramp.tramp_pkts = cur_pkt->next;
/* Setup section and image offset information for the relo */
dlthis->image_secn = sect_info;
dlthis->image_offset = cur_pkt->base;
dlthis->delta_runaddr = sect_info->run_addr;
/* Walk through all relos for the packet */
relos_done = 0;
cur_relo = (struct reloc_record_t *)((u8 *) &cur_pkt->hdr +
cur_pkt->hdr.relo_offset);
while (relos_done < cur_pkt->hdr.num_relos) {
#ifdef ENABLE_TRAMP_DEBUG
dload_syms_error(dlthis->mysym,
"===> Trampoline %x branches to %x",
sect_info->run_addr +
dlthis->image_offset,
dlthis->
tramp.final_sym_table[cur_relo->
SYMNDX].value);
#endif
for (i = 0;
((i < MAX_RELOS_PER_PASS) &&
((i + relos_done) < cur_pkt->hdr.num_relos)); i++)
relos[i] = cur_relo + i;
/* Do the actual relo */
ret_val = priv_pkt_relo(dlthis,
(tgt_au_t *) &cur_pkt->payload,
relos, i);
if (ret_val == 0) {
dload_error(dlthis,
"Relocation of trampoline pkt at %x"
" failed", cur_pkt->base +
sect_info->run_addr);
break;
}
relos_done += i;
cur_relo += i;
}
/* Make sure we didn't hit a problem */
if (ret_val != 0) {
/* Relos are done for the packet, write it to the
* target */
ret_val = dlthis->myio->writemem(dlthis->myio,
&cur_pkt->payload,
sect_info->load_addr +
cur_pkt->base,
sect_info,
BYTE_TO_HOST
(cur_pkt->hdr.
tramp_code_size));
if (ret_val == 0) {
dload_error(dlthis,
"Write to " FMT_UI32 " failed",
sect_info->load_addr +
cur_pkt->base);
}
/* Done with the pkt, let it go */
dlthis->mysym->dload_deallocate(dlthis->mysym, cur_pkt);
/* Get the next packet to process */
cur_pkt = dlthis->tramp.tramp_pkts;
}
}
return ret_val;
}
/*
* Function: priv_dup_pkt_finalize
* Description: Walk the list of duplicate image packets and finalize them.
* Each duplicate packet will be relocated again for the
* relocations that previously failed and have been adjusted
* to point at a trampoline. Once all relocations for a packet
* have been done, write the packet into target memory. The
* duplicate packet and its relocation chain are all freed
* after use here as they are no longer needed after this.
*/
static int priv_dup_pkt_finalize(struct dload_state *dlthis)
{
int ret_val = 1;
struct tramp_img_dup_pkt *cur_pkt;
struct tramp_img_dup_relo *cur_relo;
struct reloc_record_t *relos[MAX_RELOS_PER_PASS];
struct doff_scnhdr_t *sect_hdr = NULL;
s32 i;
/* Similar to the trampoline pkt finalize, this function walks each dup
* pkt that was generated and performs all relocations that were
* deferred to a 2nd pass. This is the equivalent of dload_data() from
* cload.c, but does not need the additional reorder and checksum
* processing as it has already been done. */
cur_pkt = dlthis->tramp.dup_pkts;
while ((ret_val != 0) && (cur_pkt != NULL)) {
/* Remove the node from the list, we'll be freeing it
* shortly */
dlthis->tramp.dup_pkts = cur_pkt->next;
/* Setup the section and image offset for relocation */
dlthis->image_secn = &dlthis->ldr_sections[cur_pkt->secnn];
dlthis->image_offset = cur_pkt->offset;
/* In order to get the delta run address, we need to reference
* the original section header. It's a bit ugly, but needed
* for relo. */
i = (s32) (dlthis->image_secn - dlthis->ldr_sections);
sect_hdr = dlthis->sect_hdrs + i;
dlthis->delta_runaddr = sect_hdr->ds_paddr;
/* Walk all relos in the chain and process each. */
cur_relo = cur_pkt->relo_chain;
while (cur_relo != NULL) {
/* Process them a chunk at a time to be efficient */
for (i = 0; (i < MAX_RELOS_PER_PASS)
&& (cur_relo != NULL);
i++, cur_relo = cur_relo->next) {
relos[i] = &cur_relo->relo;
cur_pkt->relo_chain = cur_relo->next;
}
/* Do the actual relo */
ret_val = priv_pkt_relo(dlthis,
cur_pkt->img_pkt.img_data,
relos, i);
if (ret_val == 0) {
dload_error(dlthis,
"Relocation of dup pkt at %x"
" failed", cur_pkt->offset +
dlthis->image_secn->run_addr);
break;
}
/* Release all of these relos, we're done with them */
while (i > 0) {
dlthis->mysym->dload_deallocate(dlthis->mysym,
GET_CONTAINER
(relos[i - 1],
struct tramp_img_dup_relo,
relo));
i--;
}
/* DO NOT ADVANCE cur_relo, IT IS ALREADY READY TO
* GO! */
}
/* Done with all relos. Make sure we didn't have a problem and
* write it out to the target */
if (ret_val != 0) {
ret_val = dlthis->myio->writemem(dlthis->myio,
cur_pkt->img_pkt.
img_data,
dlthis->image_secn->
load_addr +
cur_pkt->offset,
dlthis->image_secn,
BYTE_TO_HOST
(cur_pkt->img_pkt.
packet_size));
if (ret_val == 0) {
dload_error(dlthis,
"Write to " FMT_UI32 " failed",
dlthis->image_secn->load_addr +
cur_pkt->offset);
}
dlthis->mysym->dload_deallocate(dlthis->mysym, cur_pkt);
/* Advance to the next packet */
cur_pkt = dlthis->tramp.dup_pkts;
}
}
return ret_val;
}
/*
* Function: priv_dup_find
* Description: Walk the list of existing duplicate packets and find a
* match based on the section number and image offset. Return
* the duplicate packet if found, otherwise NULL.
*/
static struct tramp_img_dup_pkt *priv_dup_find(struct dload_state *dlthis,
s16 secnn, u32 image_offset)
{
struct tramp_img_dup_pkt *cur_pkt = NULL;
for (cur_pkt = dlthis->tramp.dup_pkts;
cur_pkt != NULL; cur_pkt = cur_pkt->next) {
if ((cur_pkt->secnn == secnn) &&
(cur_pkt->offset == image_offset)) {
/* Found a match, break out */
break;
}
}
return cur_pkt;
}
/*
* Function: priv_img_pkt_dup
* Description: Duplicate the original image packet. If this is the first
* time this image packet has been seen (based on section number
* and image offset), create a new duplicate packet and add it
* to the dup packet list. If not, just get the existing one and
* update it with the current packet contents (since relocation
* on the packet is still ongoing in first pass.) Create a
* duplicate of the provided relocation, but update it to point
* to the new trampoline symbol. Add the new relocation dup to
* the dup packet's relo chain for 2nd pass relocation later.
*/
static int priv_img_pkt_dup(struct dload_state *dlthis,
s16 secnn, u32 image_offset,
struct image_packet_t *ipacket,
struct reloc_record_t *rp,
struct tramp_sym *new_tramp_sym)
{
struct tramp_img_dup_pkt *dup_pkt = NULL;
u32 new_dup_size;
s32 i;
int ret_val = 0;
struct tramp_img_dup_relo *dup_relo = NULL;
/* Determine if this image packet is already being tracked in the
dup list for other trampolines. */
dup_pkt = priv_dup_find(dlthis, secnn, image_offset);
if (dup_pkt == NULL) {
/* This image packet does not exist in our tracking, so create
* a new one and add it to the head of the list. */
new_dup_size = sizeof(struct tramp_img_dup_pkt) +
ipacket->packet_size;
dup_pkt = (struct tramp_img_dup_pkt *)
dlthis->mysym->dload_allocate(dlthis->mysym, new_dup_size);
if (dup_pkt != NULL) {
/* Save off the section and offset information */
dup_pkt->secnn = secnn;
dup_pkt->offset = image_offset;
dup_pkt->relo_chain = NULL;
/* Copy the original packet content */
dup_pkt->img_pkt = *ipacket;
dup_pkt->img_pkt.img_data = (u8 *) (dup_pkt + 1);
for (i = 0; i < ipacket->packet_size; i++)
*(dup_pkt->img_pkt.img_data + i) =
*(ipacket->img_data + i);
/* Add the packet to the dup list */
dup_pkt->next = dlthis->tramp.dup_pkts;
dlthis->tramp.dup_pkts = dup_pkt;
} else
dload_error(dlthis, "Failed to create dup packet!");
} else {
/* The image packet contents could have changed since
* trampoline detection happens during relocation of the image
* packets. So, we need to update the image packet contents
* before adding relo information. */
for (i = 0; i < dup_pkt->img_pkt.packet_size; i++)
*(dup_pkt->img_pkt.img_data + i) =
*(ipacket->img_data + i);
}
/* Since the previous code may have allocated a new dup packet for us,
double check that we actually have one. */
if (dup_pkt != NULL) {
/* Allocate a new node for the relo chain. Each image packet
* can potentially have multiple relocations that cause a
* trampoline to be generated. So, we keep them in a chain,
* order is not important. */
dup_relo = dlthis->mysym->dload_allocate(dlthis->mysym,
sizeof(struct tramp_img_dup_relo));
if (dup_relo != NULL) {
/* Copy the relo contents, adjust for the new
* trampoline and add it to the list. */
dup_relo->relo = *rp;
dup_relo->relo.SYMNDX = new_tramp_sym->index;
dup_relo->next = dup_pkt->relo_chain;
dup_pkt->relo_chain = dup_relo;
/* That's it, we're done. Make sure we update our
* return value to be success since everything finished
* ok */
ret_val = 1;
} else
dload_error(dlthis, "Unable to alloc dup relo");
}
return ret_val;
}
/*
* Function: dload_tramp_avail
* Description: Check to see if the target supports a trampoline for this type
* of relocation. Return true if it does, otherwise false.
*/
bool dload_tramp_avail(struct dload_state *dlthis, struct reloc_record_t *rp)
{
bool ret_val = false;
u16 map_index;
u16 gen_index;
/* Check type hash vs. target tramp table */
map_index = HASH_FUNC(rp->TYPE);
gen_index = tramp_map[map_index];
if (gen_index != TRAMP_NO_GEN_AVAIL)
ret_val = true;
return ret_val;
}
/*
* Function: dload_tramp_generate
* Description: Create a new trampoline for the provided image packet and
* relocation causing problems. This will create the trampoline
* as well as duplicate/update the image packet and relocation
* causing the problem, which will be relo'd again during
* finalization.
*/
int dload_tramp_generate(struct dload_state *dlthis, s16 secnn,
u32 image_offset, struct image_packet_t *ipacket,
struct reloc_record_t *rp)
{
u16 map_index;
u16 gen_index;
int ret_val = 1;
char tramp_sym_str[TRAMP_SYM_PREFIX_LEN + TRAMP_SYM_HEX_ASCII_LEN];
struct local_symbol *ref_sym;
struct tramp_sym *new_tramp_sym;
struct tramp_sym *new_ext_sym;
struct tramp_string *new_tramp_str;
u32 new_tramp_base;
struct local_symbol tmp_sym;
struct local_symbol ext_tmp_sym;
/* Hash the relo type to get our generator information */
map_index = HASH_FUNC(rp->TYPE);
gen_index = tramp_map[map_index];
if (gen_index != TRAMP_NO_GEN_AVAIL) {
/* If this is the first trampoline, create the section name in
* our string table for debug help later. */
if (dlthis->tramp.string_head == NULL) {
priv_tramp_string_create(dlthis,
strlen(TRAMP_SECT_NAME),
TRAMP_SECT_NAME);
}
#ifdef ENABLE_TRAMP_DEBUG
dload_syms_error(dlthis->mysym,
"Trampoline at img loc %x, references %x",
dlthis->ldr_sections[secnn].run_addr +
image_offset + rp->vaddr,
dlthis->local_symtab[rp->SYMNDX].value);
#endif
/* Generate the trampoline string, check if already defined.
* If the relo symbol index is -1, it means we need the section
* info for relo later. To do this we'll dummy up a symbol
* with the section delta and run addresses. */
if (rp->SYMNDX == -1) {
ext_tmp_sym.value =
dlthis->ldr_sections[secnn].run_addr;
ext_tmp_sym.delta = dlthis->sect_hdrs[secnn].ds_paddr;
ref_sym = &ext_tmp_sym;
} else
ref_sym = &(dlthis->local_symtab[rp->SYMNDX]);
priv_tramp_sym_gen_name(ref_sym->value, tramp_sym_str);
new_tramp_sym = priv_tramp_sym_find(dlthis, tramp_sym_str);
if (new_tramp_sym == NULL) {
/* If tramp string not defined, create it and a new
* string, and symbol for it as well as the original
* symbol which caused the trampoline. */
new_tramp_str = priv_tramp_string_create(dlthis,
strlen
(tramp_sym_str),
tramp_sym_str);
if (new_tramp_str == NULL) {
dload_error(dlthis, "Failed to create new "
"trampoline string\n");
ret_val = 0;
} else {
/* Allocate tramp section space for the new
* tramp from the target */
new_tramp_base = priv_tramp_sect_alloc(dlthis,
tramp_size_get());
/* We have a string, create the new symbol and
* duplicate the external. */
tmp_sym.value = new_tramp_base;
tmp_sym.delta = 0;
tmp_sym.secnn = -1;
tmp_sym.sclass = 0;
new_tramp_sym = priv_tramp_sym_create(dlthis,
new_tramp_str->
index,
&tmp_sym);
new_ext_sym = priv_tramp_sym_create(dlthis, -1,
ref_sym);
if ((new_tramp_sym != NULL) &&
(new_ext_sym != NULL)) {
/* Call the image generator to get the
* new image data and fix up its
* relocations for the external
* symbol. */
ret_val = priv_tgt_img_gen(dlthis,
new_tramp_base,
gen_index,
new_ext_sym);
/* Add generated image data to tramp
* image list */
if (ret_val != 1) {
dload_error(dlthis, "Failed to "
"create img pkt for"
" trampoline\n");
}
} else {
dload_error(dlthis, "Failed to create "
"new tramp syms "
"(%8.8X, %8.8X)\n",
new_tramp_sym, new_ext_sym);
ret_val = 0;
}
}
}
/* Duplicate the image data and relo record that caused the
* tramp, including update the relo data to point to the tramp
* symbol. */
if (ret_val == 1) {
ret_val = priv_img_pkt_dup(dlthis, secnn, image_offset,
ipacket, rp, new_tramp_sym);
if (ret_val != 1) {
dload_error(dlthis, "Failed to create dup of "
"original img pkt\n");
}
}
}
return ret_val;
}
/*
* Function: dload_tramp_pkt_update
* Description: Update the duplicate copy of this image packet, which the
* trampoline layer is already tracking. This call is critical
* to make if trampolines were generated anywhere within the
* packet and first pass relo continued on the remainder. The
* trampoline layer needs the updates image data so when 2nd
* pass relo is done during finalize the image packet can be
* written to the target since all relo is done.
*/
int dload_tramp_pkt_udpate(struct dload_state *dlthis, s16 secnn,
u32 image_offset, struct image_packet_t *ipacket)
{
struct tramp_img_dup_pkt *dup_pkt = NULL;
s32 i;
int ret_val = 0;
/* Find the image packet in question, the caller needs us to update it
since a trampoline was previously generated. */
dup_pkt = priv_dup_find(dlthis, secnn, image_offset);
if (dup_pkt != NULL) {
for (i = 0; i < dup_pkt->img_pkt.packet_size; i++)
*(dup_pkt->img_pkt.img_data + i) =
*(ipacket->img_data + i);
ret_val = 1;
} else {
dload_error(dlthis,
"Unable to find existing DUP pkt for %x, offset %x",
secnn, image_offset);
}
return ret_val;
}
/*
* Function: dload_tramp_finalize
* Description: If any trampolines were created, finalize everything on the
* target by allocating the trampoline section on the target,
* finalizing the trampoline symbols, finalizing the trampoline
* packets (write the new section to target memory) and finalize
* the duplicate packets by doing 2nd pass relo over them.
*/
int dload_tramp_finalize(struct dload_state *dlthis)
{
int ret_val = 1;
if (dlthis->tramp.tramp_sect_next_addr != 0) {
/* Finalize strings into a flat table. This is needed so it
* can be added to the debug string table later. */
ret_val = priv_string_tbl_finalize(dlthis);
/* Do target allocation for section BEFORE finalizing
* symbols. */
if (ret_val != 0)
ret_val = priv_tramp_sect_tgt_alloc(dlthis);
/* Finalize symbols with their correct target information and
* flatten */
if (ret_val != 0)
ret_val = priv_tramp_sym_finalize(dlthis);
/* Finalize all trampoline packets. This performs the
* relocation on the packets as well as writing them to target
* memory. */
if (ret_val != 0)
ret_val = priv_tramp_pkt_finalize(dlthis);
/* Perform a 2nd pass relocation on the dup list. */
if (ret_val != 0)
ret_val = priv_dup_pkt_finalize(dlthis);
}
return ret_val;
}
/*
* Function: dload_tramp_cleanup
* Description: Release all temporary resources used in the trampoline layer.
* Note that the target memory which may have been allocated and
* written to store the trampolines is NOT RELEASED HERE since it
* is potentially still in use. It is automatically released
* when the module is unloaded.
*/
void dload_tramp_cleanup(struct dload_state *dlthis)
{
struct tramp_info *tramp = &dlthis->tramp;
struct tramp_sym *cur_sym;
struct tramp_string *cur_string;
struct tramp_img_pkt *cur_tramp_pkt;
struct tramp_img_dup_pkt *cur_dup_pkt;
struct tramp_img_dup_relo *cur_dup_relo;
/* If there were no tramps generated, just return */
if (tramp->tramp_sect_next_addr == 0)
return;
/* Destroy all tramp information */
for (cur_sym = tramp->symbol_head;
cur_sym != NULL; cur_sym = tramp->symbol_head) {
tramp->symbol_head = cur_sym->next;
if (tramp->symbol_tail == cur_sym)
tramp->symbol_tail = NULL;
dlthis->mysym->dload_deallocate(dlthis->mysym, cur_sym);
}
if (tramp->final_sym_table != NULL)
dlthis->mysym->dload_deallocate(dlthis->mysym,
tramp->final_sym_table);
for (cur_string = tramp->string_head;
cur_string != NULL; cur_string = tramp->string_head) {
tramp->string_head = cur_string->next;
if (tramp->string_tail == cur_string)
tramp->string_tail = NULL;
dlthis->mysym->dload_deallocate(dlthis->mysym, cur_string);
}
if (tramp->final_string_table != NULL)
dlthis->mysym->dload_deallocate(dlthis->mysym,
tramp->final_string_table);
for (cur_tramp_pkt = tramp->tramp_pkts;
cur_tramp_pkt != NULL; cur_tramp_pkt = tramp->tramp_pkts) {
tramp->tramp_pkts = cur_tramp_pkt->next;
dlthis->mysym->dload_deallocate(dlthis->mysym, cur_tramp_pkt);
}
for (cur_dup_pkt = tramp->dup_pkts;
cur_dup_pkt != NULL; cur_dup_pkt = tramp->dup_pkts) {
tramp->dup_pkts = cur_dup_pkt->next;
for (cur_dup_relo = cur_dup_pkt->relo_chain;
cur_dup_relo != NULL;
cur_dup_relo = cur_dup_pkt->relo_chain) {
cur_dup_pkt->relo_chain = cur_dup_relo->next;
dlthis->mysym->dload_deallocate(dlthis->mysym,
cur_dup_relo);
}
dlthis->mysym->dload_deallocate(dlthis->mysym, cur_dup_pkt);
}
}
| gpl-2.0 |
kula85/perf-sqlite3 | drivers/staging/android/timed_gpio.c | 368 | 4138 | /* drivers/misc/timed_gpio.c
*
* Copyright (C) 2008 Google, Inc.
* Author: Mike Lockwood <lockwood@android.com>
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/hrtimer.h>
#include <linux/err.h>
#include <linux/gpio.h>
#include <linux/ktime.h>
#include "timed_output.h"
#include "timed_gpio.h"
struct timed_gpio_data {
struct timed_output_dev dev;
struct hrtimer timer;
spinlock_t lock;
unsigned gpio;
int max_timeout;
u8 active_low;
};
static enum hrtimer_restart gpio_timer_func(struct hrtimer *timer)
{
struct timed_gpio_data *data =
container_of(timer, struct timed_gpio_data, timer);
gpio_direction_output(data->gpio, data->active_low ? 1 : 0);
return HRTIMER_NORESTART;
}
static int gpio_get_time(struct timed_output_dev *dev)
{
struct timed_gpio_data *data;
ktime_t t;
data = container_of(dev, struct timed_gpio_data, dev);
if (!hrtimer_active(&data->timer))
return 0;
t = hrtimer_get_remaining(&data->timer);
return ktime_to_ms(t);
}
static void gpio_enable(struct timed_output_dev *dev, int value)
{
struct timed_gpio_data *data =
container_of(dev, struct timed_gpio_data, dev);
unsigned long flags;
spin_lock_irqsave(&data->lock, flags);
/* cancel previous timer and set GPIO according to value */
hrtimer_cancel(&data->timer);
gpio_direction_output(data->gpio, data->active_low ? !value : !!value);
if (value > 0) {
if (value > data->max_timeout)
value = data->max_timeout;
hrtimer_start(&data->timer,
ktime_set(value / 1000, (value % 1000) * 1000000),
HRTIMER_MODE_REL);
}
spin_unlock_irqrestore(&data->lock, flags);
}
static int timed_gpio_probe(struct platform_device *pdev)
{
struct timed_gpio_platform_data *pdata = pdev->dev.platform_data;
struct timed_gpio *cur_gpio;
struct timed_gpio_data *gpio_data, *gpio_dat;
int i, ret;
if (!pdata)
return -EBUSY;
gpio_data = devm_kzalloc(&pdev->dev,
sizeof(struct timed_gpio_data) * pdata->num_gpios,
GFP_KERNEL);
if (!gpio_data)
return -ENOMEM;
for (i = 0; i < pdata->num_gpios; i++) {
cur_gpio = &pdata->gpios[i];
gpio_dat = &gpio_data[i];
hrtimer_init(&gpio_dat->timer, CLOCK_MONOTONIC,
HRTIMER_MODE_REL);
gpio_dat->timer.function = gpio_timer_func;
spin_lock_init(&gpio_dat->lock);
gpio_dat->dev.name = cur_gpio->name;
gpio_dat->dev.get_time = gpio_get_time;
gpio_dat->dev.enable = gpio_enable;
ret = gpio_request(cur_gpio->gpio, cur_gpio->name);
if (ret < 0)
goto err_out;
ret = timed_output_dev_register(&gpio_dat->dev);
if (ret < 0) {
gpio_free(cur_gpio->gpio);
goto err_out;
}
gpio_dat->gpio = cur_gpio->gpio;
gpio_dat->max_timeout = cur_gpio->max_timeout;
gpio_dat->active_low = cur_gpio->active_low;
gpio_direction_output(gpio_dat->gpio, gpio_dat->active_low);
}
platform_set_drvdata(pdev, gpio_data);
return 0;
err_out:
while (--i >= 0) {
timed_output_dev_unregister(&gpio_data[i].dev);
gpio_free(gpio_data[i].gpio);
}
return ret;
}
static int timed_gpio_remove(struct platform_device *pdev)
{
struct timed_gpio_platform_data *pdata = pdev->dev.platform_data;
struct timed_gpio_data *gpio_data = platform_get_drvdata(pdev);
int i;
for (i = 0; i < pdata->num_gpios; i++) {
timed_output_dev_unregister(&gpio_data[i].dev);
gpio_free(gpio_data[i].gpio);
}
return 0;
}
static struct platform_driver timed_gpio_driver = {
.probe = timed_gpio_probe,
.remove = timed_gpio_remove,
.driver = {
.name = TIMED_GPIO_NAME,
},
};
module_platform_driver(timed_gpio_driver);
MODULE_AUTHOR("Mike Lockwood <lockwood@android.com>");
MODULE_DESCRIPTION("timed gpio driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
krash86/android_kernel_google_pixel | fs/ext3/balloc.c | 1136 | 63485 | /*
* linux/fs/ext3/balloc.c
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card (card@masi.ibp.fr)
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* Enhanced block allocation by Stephen Tweedie (sct@redhat.com), 1993
* Big-endian to little-endian byte-swapping/bitmaps by
* David S. Miller (davem@caip.rutgers.edu), 1995
*/
#include <linux/quotaops.h>
#include <linux/blkdev.h>
#include "ext3.h"
/*
* balloc.c contains the blocks allocation and deallocation routines
*/
/*
* The free blocks are managed by bitmaps. A file system contains several
* blocks groups. Each group contains 1 bitmap block for blocks, 1 bitmap
* block for inodes, N blocks for the inode table and data blocks.
*
* The file system contains group descriptors which are located after the
* super block. Each descriptor contains the number of the bitmap block and
* the free blocks count in the block. The descriptors are loaded in memory
* when a file system is mounted (see ext3_fill_super).
*/
#define in_range(b, first, len) ((b) >= (first) && (b) <= (first) + (len) - 1)
/*
* Calculate the block group number and offset, given a block number
*/
static void ext3_get_group_no_and_offset(struct super_block *sb,
ext3_fsblk_t blocknr, unsigned long *blockgrpp, ext3_grpblk_t *offsetp)
{
struct ext3_super_block *es = EXT3_SB(sb)->s_es;
blocknr = blocknr - le32_to_cpu(es->s_first_data_block);
if (offsetp)
*offsetp = blocknr % EXT3_BLOCKS_PER_GROUP(sb);
if (blockgrpp)
*blockgrpp = blocknr / EXT3_BLOCKS_PER_GROUP(sb);
}
/**
* ext3_get_group_desc() -- load group descriptor from disk
* @sb: super block
* @block_group: given block group
* @bh: pointer to the buffer head to store the block
* group descriptor
*/
struct ext3_group_desc * ext3_get_group_desc(struct super_block * sb,
unsigned int block_group,
struct buffer_head ** bh)
{
unsigned long group_desc;
unsigned long offset;
struct ext3_group_desc * desc;
struct ext3_sb_info *sbi = EXT3_SB(sb);
if (block_group >= sbi->s_groups_count) {
ext3_error (sb, "ext3_get_group_desc",
"block_group >= groups_count - "
"block_group = %d, groups_count = %lu",
block_group, sbi->s_groups_count);
return NULL;
}
smp_rmb();
group_desc = block_group >> EXT3_DESC_PER_BLOCK_BITS(sb);
offset = block_group & (EXT3_DESC_PER_BLOCK(sb) - 1);
if (!sbi->s_group_desc[group_desc]) {
ext3_error (sb, "ext3_get_group_desc",
"Group descriptor not loaded - "
"block_group = %d, group_desc = %lu, desc = %lu",
block_group, group_desc, offset);
return NULL;
}
desc = (struct ext3_group_desc *) sbi->s_group_desc[group_desc]->b_data;
if (bh)
*bh = sbi->s_group_desc[group_desc];
return desc + offset;
}
static int ext3_valid_block_bitmap(struct super_block *sb,
struct ext3_group_desc *desc,
unsigned int block_group,
struct buffer_head *bh)
{
ext3_grpblk_t offset;
ext3_grpblk_t next_zero_bit;
ext3_fsblk_t bitmap_blk;
ext3_fsblk_t group_first_block;
group_first_block = ext3_group_first_block_no(sb, block_group);
/* check whether block bitmap block number is set */
bitmap_blk = le32_to_cpu(desc->bg_block_bitmap);
offset = bitmap_blk - group_first_block;
if (!ext3_test_bit(offset, bh->b_data))
/* bad block bitmap */
goto err_out;
/* check whether the inode bitmap block number is set */
bitmap_blk = le32_to_cpu(desc->bg_inode_bitmap);
offset = bitmap_blk - group_first_block;
if (!ext3_test_bit(offset, bh->b_data))
/* bad block bitmap */
goto err_out;
/* check whether the inode table block number is set */
bitmap_blk = le32_to_cpu(desc->bg_inode_table);
offset = bitmap_blk - group_first_block;
next_zero_bit = ext3_find_next_zero_bit(bh->b_data,
offset + EXT3_SB(sb)->s_itb_per_group,
offset);
if (next_zero_bit >= offset + EXT3_SB(sb)->s_itb_per_group)
/* good bitmap for inode tables */
return 1;
err_out:
ext3_error(sb, __func__,
"Invalid block bitmap - "
"block_group = %d, block = %lu",
block_group, bitmap_blk);
return 0;
}
/**
* read_block_bitmap()
* @sb: super block
* @block_group: given block group
*
* Read the bitmap for a given block_group,and validate the
* bits for block/inode/inode tables are set in the bitmaps
*
* Return buffer_head on success or NULL in case of failure.
*/
static struct buffer_head *
read_block_bitmap(struct super_block *sb, unsigned int block_group)
{
struct ext3_group_desc * desc;
struct buffer_head * bh = NULL;
ext3_fsblk_t bitmap_blk;
desc = ext3_get_group_desc(sb, block_group, NULL);
if (!desc)
return NULL;
trace_ext3_read_block_bitmap(sb, block_group);
bitmap_blk = le32_to_cpu(desc->bg_block_bitmap);
bh = sb_getblk(sb, bitmap_blk);
if (unlikely(!bh)) {
ext3_error(sb, __func__,
"Cannot read block bitmap - "
"block_group = %d, block_bitmap = %u",
block_group, le32_to_cpu(desc->bg_block_bitmap));
return NULL;
}
if (likely(bh_uptodate_or_lock(bh)))
return bh;
if (bh_submit_read(bh) < 0) {
brelse(bh);
ext3_error(sb, __func__,
"Cannot read block bitmap - "
"block_group = %d, block_bitmap = %u",
block_group, le32_to_cpu(desc->bg_block_bitmap));
return NULL;
}
ext3_valid_block_bitmap(sb, desc, block_group, bh);
/*
* file system mounted not to panic on error, continue with corrupt
* bitmap
*/
return bh;
}
/*
* The reservation window structure operations
* --------------------------------------------
* Operations include:
* dump, find, add, remove, is_empty, find_next_reservable_window, etc.
*
* We use a red-black tree to represent per-filesystem reservation
* windows.
*
*/
/**
* __rsv_window_dump() -- Dump the filesystem block allocation reservation map
* @rb_root: root of per-filesystem reservation rb tree
* @verbose: verbose mode
* @fn: function which wishes to dump the reservation map
*
* If verbose is turned on, it will print the whole block reservation
* windows(start, end). Otherwise, it will only print out the "bad" windows,
* those windows that overlap with their immediate neighbors.
*/
#if 1
static void __rsv_window_dump(struct rb_root *root, int verbose,
const char *fn)
{
struct rb_node *n;
struct ext3_reserve_window_node *rsv, *prev;
int bad;
restart:
n = rb_first(root);
bad = 0;
prev = NULL;
printk("Block Allocation Reservation Windows Map (%s):\n", fn);
while (n) {
rsv = rb_entry(n, struct ext3_reserve_window_node, rsv_node);
if (verbose)
printk("reservation window 0x%p "
"start: %lu, end: %lu\n",
rsv, rsv->rsv_start, rsv->rsv_end);
if (rsv->rsv_start && rsv->rsv_start >= rsv->rsv_end) {
printk("Bad reservation %p (start >= end)\n",
rsv);
bad = 1;
}
if (prev && prev->rsv_end >= rsv->rsv_start) {
printk("Bad reservation %p (prev->end >= start)\n",
rsv);
bad = 1;
}
if (bad) {
if (!verbose) {
printk("Restarting reservation walk in verbose mode\n");
verbose = 1;
goto restart;
}
}
n = rb_next(n);
prev = rsv;
}
printk("Window map complete.\n");
BUG_ON(bad);
}
#define rsv_window_dump(root, verbose) \
__rsv_window_dump((root), (verbose), __func__)
#else
#define rsv_window_dump(root, verbose) do {} while (0)
#endif
/**
* goal_in_my_reservation()
* @rsv: inode's reservation window
* @grp_goal: given goal block relative to the allocation block group
* @group: the current allocation block group
* @sb: filesystem super block
*
* Test if the given goal block (group relative) is within the file's
* own block reservation window range.
*
* If the reservation window is outside the goal allocation group, return 0;
* grp_goal (given goal block) could be -1, which means no specific
* goal block. In this case, always return 1.
* If the goal block is within the reservation window, return 1;
* otherwise, return 0;
*/
static int
goal_in_my_reservation(struct ext3_reserve_window *rsv, ext3_grpblk_t grp_goal,
unsigned int group, struct super_block * sb)
{
ext3_fsblk_t group_first_block, group_last_block;
group_first_block = ext3_group_first_block_no(sb, group);
group_last_block = group_first_block + (EXT3_BLOCKS_PER_GROUP(sb) - 1);
if ((rsv->_rsv_start > group_last_block) ||
(rsv->_rsv_end < group_first_block))
return 0;
if ((grp_goal >= 0) && ((grp_goal + group_first_block < rsv->_rsv_start)
|| (grp_goal + group_first_block > rsv->_rsv_end)))
return 0;
return 1;
}
/**
* search_reserve_window()
* @rb_root: root of reservation tree
* @goal: target allocation block
*
* Find the reserved window which includes the goal, or the previous one
* if the goal is not in any window.
* Returns NULL if there are no windows or if all windows start after the goal.
*/
static struct ext3_reserve_window_node *
search_reserve_window(struct rb_root *root, ext3_fsblk_t goal)
{
struct rb_node *n = root->rb_node;
struct ext3_reserve_window_node *rsv;
if (!n)
return NULL;
do {
rsv = rb_entry(n, struct ext3_reserve_window_node, rsv_node);
if (goal < rsv->rsv_start)
n = n->rb_left;
else if (goal > rsv->rsv_end)
n = n->rb_right;
else
return rsv;
} while (n);
/*
* We've fallen off the end of the tree: the goal wasn't inside
* any particular node. OK, the previous node must be to one
* side of the interval containing the goal. If it's the RHS,
* we need to back up one.
*/
if (rsv->rsv_start > goal) {
n = rb_prev(&rsv->rsv_node);
rsv = rb_entry(n, struct ext3_reserve_window_node, rsv_node);
}
return rsv;
}
/**
* ext3_rsv_window_add() -- Insert a window to the block reservation rb tree.
* @sb: super block
* @rsv: reservation window to add
*
* Must be called with rsv_lock hold.
*/
void ext3_rsv_window_add(struct super_block *sb,
struct ext3_reserve_window_node *rsv)
{
struct rb_root *root = &EXT3_SB(sb)->s_rsv_window_root;
struct rb_node *node = &rsv->rsv_node;
ext3_fsblk_t start = rsv->rsv_start;
struct rb_node ** p = &root->rb_node;
struct rb_node * parent = NULL;
struct ext3_reserve_window_node *this;
trace_ext3_rsv_window_add(sb, rsv);
while (*p)
{
parent = *p;
this = rb_entry(parent, struct ext3_reserve_window_node, rsv_node);
if (start < this->rsv_start)
p = &(*p)->rb_left;
else if (start > this->rsv_end)
p = &(*p)->rb_right;
else {
rsv_window_dump(root, 1);
BUG();
}
}
rb_link_node(node, parent, p);
rb_insert_color(node, root);
}
/**
* ext3_rsv_window_remove() -- unlink a window from the reservation rb tree
* @sb: super block
* @rsv: reservation window to remove
*
* Mark the block reservation window as not allocated, and unlink it
* from the filesystem reservation window rb tree. Must be called with
* rsv_lock hold.
*/
static void rsv_window_remove(struct super_block *sb,
struct ext3_reserve_window_node *rsv)
{
rsv->rsv_start = EXT3_RESERVE_WINDOW_NOT_ALLOCATED;
rsv->rsv_end = EXT3_RESERVE_WINDOW_NOT_ALLOCATED;
rsv->rsv_alloc_hit = 0;
rb_erase(&rsv->rsv_node, &EXT3_SB(sb)->s_rsv_window_root);
}
/*
* rsv_is_empty() -- Check if the reservation window is allocated.
* @rsv: given reservation window to check
*
* returns 1 if the end block is EXT3_RESERVE_WINDOW_NOT_ALLOCATED.
*/
static inline int rsv_is_empty(struct ext3_reserve_window *rsv)
{
/* a valid reservation end block could not be 0 */
return rsv->_rsv_end == EXT3_RESERVE_WINDOW_NOT_ALLOCATED;
}
/**
* ext3_init_block_alloc_info()
* @inode: file inode structure
*
* Allocate and initialize the reservation window structure, and
* link the window to the ext3 inode structure at last
*
* The reservation window structure is only dynamically allocated
* and linked to ext3 inode the first time the open file
* needs a new block. So, before every ext3_new_block(s) call, for
* regular files, we should check whether the reservation window
* structure exists or not. In the latter case, this function is called.
* Fail to do so will result in block reservation being turned off for that
* open file.
*
* This function is called from ext3_get_blocks_handle(), also called
* when setting the reservation window size through ioctl before the file
* is open for write (needs block allocation).
*
* Needs truncate_mutex protection prior to call this function.
*/
void ext3_init_block_alloc_info(struct inode *inode)
{
struct ext3_inode_info *ei = EXT3_I(inode);
struct ext3_block_alloc_info *block_i;
struct super_block *sb = inode->i_sb;
block_i = kmalloc(sizeof(*block_i), GFP_NOFS);
if (block_i) {
struct ext3_reserve_window_node *rsv = &block_i->rsv_window_node;
rsv->rsv_start = EXT3_RESERVE_WINDOW_NOT_ALLOCATED;
rsv->rsv_end = EXT3_RESERVE_WINDOW_NOT_ALLOCATED;
/*
* if filesystem is mounted with NORESERVATION, the goal
* reservation window size is set to zero to indicate
* block reservation is off
*/
if (!test_opt(sb, RESERVATION))
rsv->rsv_goal_size = 0;
else
rsv->rsv_goal_size = EXT3_DEFAULT_RESERVE_BLOCKS;
rsv->rsv_alloc_hit = 0;
block_i->last_alloc_logical_block = 0;
block_i->last_alloc_physical_block = 0;
}
ei->i_block_alloc_info = block_i;
}
/**
* ext3_discard_reservation()
* @inode: inode
*
* Discard(free) block reservation window on last file close, or truncate
* or at last iput().
*
* It is being called in three cases:
* ext3_release_file(): last writer close the file
* ext3_clear_inode(): last iput(), when nobody link to this file.
* ext3_truncate(): when the block indirect map is about to change.
*
*/
void ext3_discard_reservation(struct inode *inode)
{
struct ext3_inode_info *ei = EXT3_I(inode);
struct ext3_block_alloc_info *block_i = ei->i_block_alloc_info;
struct ext3_reserve_window_node *rsv;
spinlock_t *rsv_lock = &EXT3_SB(inode->i_sb)->s_rsv_window_lock;
if (!block_i)
return;
rsv = &block_i->rsv_window_node;
if (!rsv_is_empty(&rsv->rsv_window)) {
spin_lock(rsv_lock);
if (!rsv_is_empty(&rsv->rsv_window)) {
trace_ext3_discard_reservation(inode, rsv);
rsv_window_remove(inode->i_sb, rsv);
}
spin_unlock(rsv_lock);
}
}
/**
* ext3_free_blocks_sb() -- Free given blocks and update quota
* @handle: handle to this transaction
* @sb: super block
* @block: start physical block to free
* @count: number of blocks to free
* @pdquot_freed_blocks: pointer to quota
*/
void ext3_free_blocks_sb(handle_t *handle, struct super_block *sb,
ext3_fsblk_t block, unsigned long count,
unsigned long *pdquot_freed_blocks)
{
struct buffer_head *bitmap_bh = NULL;
struct buffer_head *gd_bh;
unsigned long block_group;
ext3_grpblk_t bit;
unsigned long i;
unsigned long overflow;
struct ext3_group_desc * desc;
struct ext3_super_block * es;
struct ext3_sb_info *sbi;
int err = 0, ret;
ext3_grpblk_t group_freed;
*pdquot_freed_blocks = 0;
sbi = EXT3_SB(sb);
es = sbi->s_es;
if (block < le32_to_cpu(es->s_first_data_block) ||
block + count < block ||
block + count > le32_to_cpu(es->s_blocks_count)) {
ext3_error (sb, "ext3_free_blocks",
"Freeing blocks not in datazone - "
"block = "E3FSBLK", count = %lu", block, count);
goto error_return;
}
ext3_debug ("freeing block(s) %lu-%lu\n", block, block + count - 1);
do_more:
overflow = 0;
block_group = (block - le32_to_cpu(es->s_first_data_block)) /
EXT3_BLOCKS_PER_GROUP(sb);
bit = (block - le32_to_cpu(es->s_first_data_block)) %
EXT3_BLOCKS_PER_GROUP(sb);
/*
* Check to see if we are freeing blocks across a group
* boundary.
*/
if (bit + count > EXT3_BLOCKS_PER_GROUP(sb)) {
overflow = bit + count - EXT3_BLOCKS_PER_GROUP(sb);
count -= overflow;
}
brelse(bitmap_bh);
bitmap_bh = read_block_bitmap(sb, block_group);
if (!bitmap_bh)
goto error_return;
desc = ext3_get_group_desc (sb, block_group, &gd_bh);
if (!desc)
goto error_return;
if (in_range (le32_to_cpu(desc->bg_block_bitmap), block, count) ||
in_range (le32_to_cpu(desc->bg_inode_bitmap), block, count) ||
in_range (block, le32_to_cpu(desc->bg_inode_table),
sbi->s_itb_per_group) ||
in_range (block + count - 1, le32_to_cpu(desc->bg_inode_table),
sbi->s_itb_per_group)) {
ext3_error (sb, "ext3_free_blocks",
"Freeing blocks in system zones - "
"Block = "E3FSBLK", count = %lu",
block, count);
goto error_return;
}
/*
* We are about to start releasing blocks in the bitmap,
* so we need undo access.
*/
/* @@@ check errors */
BUFFER_TRACE(bitmap_bh, "getting undo access");
err = ext3_journal_get_undo_access(handle, bitmap_bh);
if (err)
goto error_return;
/*
* We are about to modify some metadata. Call the journal APIs
* to unshare ->b_data if a currently-committing transaction is
* using it
*/
BUFFER_TRACE(gd_bh, "get_write_access");
err = ext3_journal_get_write_access(handle, gd_bh);
if (err)
goto error_return;
jbd_lock_bh_state(bitmap_bh);
for (i = 0, group_freed = 0; i < count; i++) {
/*
* An HJ special. This is expensive...
*/
#ifdef CONFIG_JBD_DEBUG
jbd_unlock_bh_state(bitmap_bh);
{
struct buffer_head *debug_bh;
debug_bh = sb_find_get_block(sb, block + i);
if (debug_bh) {
BUFFER_TRACE(debug_bh, "Deleted!");
if (!bh2jh(bitmap_bh)->b_committed_data)
BUFFER_TRACE(debug_bh,
"No committed data in bitmap");
BUFFER_TRACE2(debug_bh, bitmap_bh, "bitmap");
__brelse(debug_bh);
}
}
jbd_lock_bh_state(bitmap_bh);
#endif
if (need_resched()) {
jbd_unlock_bh_state(bitmap_bh);
cond_resched();
jbd_lock_bh_state(bitmap_bh);
}
/* @@@ This prevents newly-allocated data from being
* freed and then reallocated within the same
* transaction.
*
* Ideally we would want to allow that to happen, but to
* do so requires making journal_forget() capable of
* revoking the queued write of a data block, which
* implies blocking on the journal lock. *forget()
* cannot block due to truncate races.
*
* Eventually we can fix this by making journal_forget()
* return a status indicating whether or not it was able
* to revoke the buffer. On successful revoke, it is
* safe not to set the allocation bit in the committed
* bitmap, because we know that there is no outstanding
* activity on the buffer any more and so it is safe to
* reallocate it.
*/
BUFFER_TRACE(bitmap_bh, "set in b_committed_data");
J_ASSERT_BH(bitmap_bh,
bh2jh(bitmap_bh)->b_committed_data != NULL);
ext3_set_bit_atomic(sb_bgl_lock(sbi, block_group), bit + i,
bh2jh(bitmap_bh)->b_committed_data);
/*
* We clear the bit in the bitmap after setting the committed
* data bit, because this is the reverse order to that which
* the allocator uses.
*/
BUFFER_TRACE(bitmap_bh, "clear bit");
if (!ext3_clear_bit_atomic(sb_bgl_lock(sbi, block_group),
bit + i, bitmap_bh->b_data)) {
jbd_unlock_bh_state(bitmap_bh);
ext3_error(sb, __func__,
"bit already cleared for block "E3FSBLK,
block + i);
jbd_lock_bh_state(bitmap_bh);
BUFFER_TRACE(bitmap_bh, "bit already cleared");
} else {
group_freed++;
}
}
jbd_unlock_bh_state(bitmap_bh);
spin_lock(sb_bgl_lock(sbi, block_group));
le16_add_cpu(&desc->bg_free_blocks_count, group_freed);
spin_unlock(sb_bgl_lock(sbi, block_group));
percpu_counter_add(&sbi->s_freeblocks_counter, count);
/* We dirtied the bitmap block */
BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
err = ext3_journal_dirty_metadata(handle, bitmap_bh);
/* And the group descriptor block */
BUFFER_TRACE(gd_bh, "dirtied group descriptor block");
ret = ext3_journal_dirty_metadata(handle, gd_bh);
if (!err) err = ret;
*pdquot_freed_blocks += group_freed;
if (overflow && !err) {
block += count;
count = overflow;
goto do_more;
}
error_return:
brelse(bitmap_bh);
ext3_std_error(sb, err);
return;
}
/**
* ext3_free_blocks() -- Free given blocks and update quota
* @handle: handle for this transaction
* @inode: inode
* @block: start physical block to free
* @count: number of blocks to count
*/
void ext3_free_blocks(handle_t *handle, struct inode *inode,
ext3_fsblk_t block, unsigned long count)
{
struct super_block *sb = inode->i_sb;
unsigned long dquot_freed_blocks;
trace_ext3_free_blocks(inode, block, count);
ext3_free_blocks_sb(handle, sb, block, count, &dquot_freed_blocks);
if (dquot_freed_blocks)
dquot_free_block(inode, dquot_freed_blocks);
return;
}
/**
* ext3_test_allocatable()
* @nr: given allocation block group
* @bh: bufferhead contains the bitmap of the given block group
*
* For ext3 allocations, we must not reuse any blocks which are
* allocated in the bitmap buffer's "last committed data" copy. This
* prevents deletes from freeing up the page for reuse until we have
* committed the delete transaction.
*
* If we didn't do this, then deleting something and reallocating it as
* data would allow the old block to be overwritten before the
* transaction committed (because we force data to disk before commit).
* This would lead to corruption if we crashed between overwriting the
* data and committing the delete.
*
* @@@ We may want to make this allocation behaviour conditional on
* data-writes at some point, and disable it for metadata allocations or
* sync-data inodes.
*/
static int ext3_test_allocatable(ext3_grpblk_t nr, struct buffer_head *bh)
{
int ret;
struct journal_head *jh = bh2jh(bh);
if (ext3_test_bit(nr, bh->b_data))
return 0;
jbd_lock_bh_state(bh);
if (!jh->b_committed_data)
ret = 1;
else
ret = !ext3_test_bit(nr, jh->b_committed_data);
jbd_unlock_bh_state(bh);
return ret;
}
/**
* bitmap_search_next_usable_block()
* @start: the starting block (group relative) of the search
* @bh: bufferhead contains the block group bitmap
* @maxblocks: the ending block (group relative) of the reservation
*
* The bitmap search --- search forward alternately through the actual
* bitmap on disk and the last-committed copy in journal, until we find a
* bit free in both bitmaps.
*/
static ext3_grpblk_t
bitmap_search_next_usable_block(ext3_grpblk_t start, struct buffer_head *bh,
ext3_grpblk_t maxblocks)
{
ext3_grpblk_t next;
struct journal_head *jh = bh2jh(bh);
while (start < maxblocks) {
next = ext3_find_next_zero_bit(bh->b_data, maxblocks, start);
if (next >= maxblocks)
return -1;
if (ext3_test_allocatable(next, bh))
return next;
jbd_lock_bh_state(bh);
if (jh->b_committed_data)
start = ext3_find_next_zero_bit(jh->b_committed_data,
maxblocks, next);
jbd_unlock_bh_state(bh);
}
return -1;
}
/**
* find_next_usable_block()
* @start: the starting block (group relative) to find next
* allocatable block in bitmap.
* @bh: bufferhead contains the block group bitmap
* @maxblocks: the ending block (group relative) for the search
*
* Find an allocatable block in a bitmap. We honor both the bitmap and
* its last-committed copy (if that exists), and perform the "most
* appropriate allocation" algorithm of looking for a free block near
* the initial goal; then for a free byte somewhere in the bitmap; then
* for any free bit in the bitmap.
*/
static ext3_grpblk_t
find_next_usable_block(ext3_grpblk_t start, struct buffer_head *bh,
ext3_grpblk_t maxblocks)
{
ext3_grpblk_t here, next;
char *p, *r;
if (start > 0) {
/*
* The goal was occupied; search forward for a free
* block within the next XX blocks.
*
* end_goal is more or less random, but it has to be
* less than EXT3_BLOCKS_PER_GROUP. Aligning up to the
* next 64-bit boundary is simple..
*/
ext3_grpblk_t end_goal = (start + 63) & ~63;
if (end_goal > maxblocks)
end_goal = maxblocks;
here = ext3_find_next_zero_bit(bh->b_data, end_goal, start);
if (here < end_goal && ext3_test_allocatable(here, bh))
return here;
ext3_debug("Bit not found near goal\n");
}
here = start;
if (here < 0)
here = 0;
p = bh->b_data + (here >> 3);
r = memscan(p, 0, ((maxblocks + 7) >> 3) - (here >> 3));
next = (r - bh->b_data) << 3;
if (next < maxblocks && next >= start && ext3_test_allocatable(next, bh))
return next;
/*
* The bitmap search --- search forward alternately through the actual
* bitmap and the last-committed copy until we find a bit free in
* both
*/
here = bitmap_search_next_usable_block(here, bh, maxblocks);
return here;
}
/**
* claim_block()
* @lock: the spin lock for this block group
* @block: the free block (group relative) to allocate
* @bh: the buffer_head contains the block group bitmap
*
* We think we can allocate this block in this bitmap. Try to set the bit.
* If that succeeds then check that nobody has allocated and then freed the
* block since we saw that is was not marked in b_committed_data. If it _was_
* allocated and freed then clear the bit in the bitmap again and return
* zero (failure).
*/
static inline int
claim_block(spinlock_t *lock, ext3_grpblk_t block, struct buffer_head *bh)
{
struct journal_head *jh = bh2jh(bh);
int ret;
if (ext3_set_bit_atomic(lock, block, bh->b_data))
return 0;
jbd_lock_bh_state(bh);
if (jh->b_committed_data && ext3_test_bit(block,jh->b_committed_data)) {
ext3_clear_bit_atomic(lock, block, bh->b_data);
ret = 0;
} else {
ret = 1;
}
jbd_unlock_bh_state(bh);
return ret;
}
/**
* ext3_try_to_allocate()
* @sb: superblock
* @handle: handle to this transaction
* @group: given allocation block group
* @bitmap_bh: bufferhead holds the block bitmap
* @grp_goal: given target block within the group
* @count: target number of blocks to allocate
* @my_rsv: reservation window
*
* Attempt to allocate blocks within a give range. Set the range of allocation
* first, then find the first free bit(s) from the bitmap (within the range),
* and at last, allocate the blocks by claiming the found free bit as allocated.
*
* To set the range of this allocation:
* if there is a reservation window, only try to allocate block(s) from the
* file's own reservation window;
* Otherwise, the allocation range starts from the give goal block, ends at
* the block group's last block.
*
* If we failed to allocate the desired block then we may end up crossing to a
* new bitmap. In that case we must release write access to the old one via
* ext3_journal_release_buffer(), else we'll run out of credits.
*/
static ext3_grpblk_t
ext3_try_to_allocate(struct super_block *sb, handle_t *handle, int group,
struct buffer_head *bitmap_bh, ext3_grpblk_t grp_goal,
unsigned long *count, struct ext3_reserve_window *my_rsv)
{
ext3_fsblk_t group_first_block;
ext3_grpblk_t start, end;
unsigned long num = 0;
/* we do allocation within the reservation window if we have a window */
if (my_rsv) {
group_first_block = ext3_group_first_block_no(sb, group);
if (my_rsv->_rsv_start >= group_first_block)
start = my_rsv->_rsv_start - group_first_block;
else
/* reservation window cross group boundary */
start = 0;
end = my_rsv->_rsv_end - group_first_block + 1;
if (end > EXT3_BLOCKS_PER_GROUP(sb))
/* reservation window crosses group boundary */
end = EXT3_BLOCKS_PER_GROUP(sb);
if ((start <= grp_goal) && (grp_goal < end))
start = grp_goal;
else
grp_goal = -1;
} else {
if (grp_goal > 0)
start = grp_goal;
else
start = 0;
end = EXT3_BLOCKS_PER_GROUP(sb);
}
BUG_ON(start > EXT3_BLOCKS_PER_GROUP(sb));
repeat:
if (grp_goal < 0 || !ext3_test_allocatable(grp_goal, bitmap_bh)) {
grp_goal = find_next_usable_block(start, bitmap_bh, end);
if (grp_goal < 0)
goto fail_access;
if (!my_rsv) {
int i;
for (i = 0; i < 7 && grp_goal > start &&
ext3_test_allocatable(grp_goal - 1,
bitmap_bh);
i++, grp_goal--)
;
}
}
start = grp_goal;
if (!claim_block(sb_bgl_lock(EXT3_SB(sb), group),
grp_goal, bitmap_bh)) {
/*
* The block was allocated by another thread, or it was
* allocated and then freed by another thread
*/
start++;
grp_goal++;
if (start >= end)
goto fail_access;
goto repeat;
}
num++;
grp_goal++;
while (num < *count && grp_goal < end
&& ext3_test_allocatable(grp_goal, bitmap_bh)
&& claim_block(sb_bgl_lock(EXT3_SB(sb), group),
grp_goal, bitmap_bh)) {
num++;
grp_goal++;
}
*count = num;
return grp_goal - num;
fail_access:
*count = num;
return -1;
}
/**
* find_next_reservable_window():
* find a reservable space within the given range.
* It does not allocate the reservation window for now:
* alloc_new_reservation() will do the work later.
*
* @search_head: the head of the searching list;
* This is not necessarily the list head of the whole filesystem
*
* We have both head and start_block to assist the search
* for the reservable space. The list starts from head,
* but we will shift to the place where start_block is,
* then start from there, when looking for a reservable space.
*
* @my_rsv: the reservation window
*
* @sb: the super block
*
* @start_block: the first block we consider to start
* the real search from
*
* @last_block:
* the maximum block number that our goal reservable space
* could start from. This is normally the last block in this
* group. The search will end when we found the start of next
* possible reservable space is out of this boundary.
* This could handle the cross boundary reservation window
* request.
*
* basically we search from the given range, rather than the whole
* reservation double linked list, (start_block, last_block)
* to find a free region that is of my size and has not
* been reserved.
*
*/
static int find_next_reservable_window(
struct ext3_reserve_window_node *search_head,
struct ext3_reserve_window_node *my_rsv,
struct super_block * sb,
ext3_fsblk_t start_block,
ext3_fsblk_t last_block)
{
struct rb_node *next;
struct ext3_reserve_window_node *rsv, *prev;
ext3_fsblk_t cur;
int size = my_rsv->rsv_goal_size;
/* TODO: make the start of the reservation window byte-aligned */
/* cur = *start_block & ~7;*/
cur = start_block;
rsv = search_head;
if (!rsv)
return -1;
while (1) {
if (cur <= rsv->rsv_end)
cur = rsv->rsv_end + 1;
/* TODO?
* in the case we could not find a reservable space
* that is what is expected, during the re-search, we could
* remember what's the largest reservable space we could have
* and return that one.
*
* For now it will fail if we could not find the reservable
* space with expected-size (or more)...
*/
if (cur > last_block)
return -1; /* fail */
prev = rsv;
next = rb_next(&rsv->rsv_node);
rsv = rb_entry(next,struct ext3_reserve_window_node,rsv_node);
/*
* Reached the last reservation, we can just append to the
* previous one.
*/
if (!next)
break;
if (cur + size <= rsv->rsv_start) {
/*
* Found a reserveable space big enough. We could
* have a reservation across the group boundary here
*/
break;
}
}
/*
* we come here either :
* when we reach the end of the whole list,
* and there is empty reservable space after last entry in the list.
* append it to the end of the list.
*
* or we found one reservable space in the middle of the list,
* return the reservation window that we could append to.
* succeed.
*/
if ((prev != my_rsv) && (!rsv_is_empty(&my_rsv->rsv_window)))
rsv_window_remove(sb, my_rsv);
/*
* Let's book the whole available window for now. We will check the
* disk bitmap later and then, if there are free blocks then we adjust
* the window size if it's larger than requested.
* Otherwise, we will remove this node from the tree next time
* call find_next_reservable_window.
*/
my_rsv->rsv_start = cur;
my_rsv->rsv_end = cur + size - 1;
my_rsv->rsv_alloc_hit = 0;
if (prev != my_rsv)
ext3_rsv_window_add(sb, my_rsv);
return 0;
}
/**
* alloc_new_reservation()--allocate a new reservation window
*
* To make a new reservation, we search part of the filesystem
* reservation list (the list that inside the group). We try to
* allocate a new reservation window near the allocation goal,
* or the beginning of the group, if there is no goal.
*
* We first find a reservable space after the goal, then from
* there, we check the bitmap for the first free block after
* it. If there is no free block until the end of group, then the
* whole group is full, we failed. Otherwise, check if the free
* block is inside the expected reservable space, if so, we
* succeed.
* If the first free block is outside the reservable space, then
* start from the first free block, we search for next available
* space, and go on.
*
* on succeed, a new reservation will be found and inserted into the list
* It contains at least one free block, and it does not overlap with other
* reservation windows.
*
* failed: we failed to find a reservation window in this group
*
* @my_rsv: the reservation window
*
* @grp_goal: The goal (group-relative). It is where the search for a
* free reservable space should start from.
* if we have a grp_goal(grp_goal >0 ), then start from there,
* no grp_goal(grp_goal = -1), we start from the first block
* of the group.
*
* @sb: the super block
* @group: the group we are trying to allocate in
* @bitmap_bh: the block group block bitmap
*
*/
static int alloc_new_reservation(struct ext3_reserve_window_node *my_rsv,
ext3_grpblk_t grp_goal, struct super_block *sb,
unsigned int group, struct buffer_head *bitmap_bh)
{
struct ext3_reserve_window_node *search_head;
ext3_fsblk_t group_first_block, group_end_block, start_block;
ext3_grpblk_t first_free_block;
struct rb_root *fs_rsv_root = &EXT3_SB(sb)->s_rsv_window_root;
unsigned long size;
int ret;
spinlock_t *rsv_lock = &EXT3_SB(sb)->s_rsv_window_lock;
group_first_block = ext3_group_first_block_no(sb, group);
group_end_block = group_first_block + (EXT3_BLOCKS_PER_GROUP(sb) - 1);
if (grp_goal < 0)
start_block = group_first_block;
else
start_block = grp_goal + group_first_block;
trace_ext3_alloc_new_reservation(sb, start_block);
size = my_rsv->rsv_goal_size;
if (!rsv_is_empty(&my_rsv->rsv_window)) {
/*
* if the old reservation is cross group boundary
* and if the goal is inside the old reservation window,
* we will come here when we just failed to allocate from
* the first part of the window. We still have another part
* that belongs to the next group. In this case, there is no
* point to discard our window and try to allocate a new one
* in this group(which will fail). we should
* keep the reservation window, just simply move on.
*
* Maybe we could shift the start block of the reservation
* window to the first block of next group.
*/
if ((my_rsv->rsv_start <= group_end_block) &&
(my_rsv->rsv_end > group_end_block) &&
(start_block >= my_rsv->rsv_start))
return -1;
if ((my_rsv->rsv_alloc_hit >
(my_rsv->rsv_end - my_rsv->rsv_start + 1) / 2)) {
/*
* if the previously allocation hit ratio is
* greater than 1/2, then we double the size of
* the reservation window the next time,
* otherwise we keep the same size window
*/
size = size * 2;
if (size > EXT3_MAX_RESERVE_BLOCKS)
size = EXT3_MAX_RESERVE_BLOCKS;
my_rsv->rsv_goal_size= size;
}
}
spin_lock(rsv_lock);
/*
* shift the search start to the window near the goal block
*/
search_head = search_reserve_window(fs_rsv_root, start_block);
/*
* find_next_reservable_window() simply finds a reservable window
* inside the given range(start_block, group_end_block).
*
* To make sure the reservation window has a free bit inside it, we
* need to check the bitmap after we found a reservable window.
*/
retry:
ret = find_next_reservable_window(search_head, my_rsv, sb,
start_block, group_end_block);
if (ret == -1) {
if (!rsv_is_empty(&my_rsv->rsv_window))
rsv_window_remove(sb, my_rsv);
spin_unlock(rsv_lock);
return -1;
}
/*
* On success, find_next_reservable_window() returns the
* reservation window where there is a reservable space after it.
* Before we reserve this reservable space, we need
* to make sure there is at least a free block inside this region.
*
* searching the first free bit on the block bitmap and copy of
* last committed bitmap alternatively, until we found a allocatable
* block. Search start from the start block of the reservable space
* we just found.
*/
spin_unlock(rsv_lock);
first_free_block = bitmap_search_next_usable_block(
my_rsv->rsv_start - group_first_block,
bitmap_bh, group_end_block - group_first_block + 1);
if (first_free_block < 0) {
/*
* no free block left on the bitmap, no point
* to reserve the space. return failed.
*/
spin_lock(rsv_lock);
if (!rsv_is_empty(&my_rsv->rsv_window))
rsv_window_remove(sb, my_rsv);
spin_unlock(rsv_lock);
return -1; /* failed */
}
start_block = first_free_block + group_first_block;
/*
* check if the first free block is within the
* free space we just reserved
*/
if (start_block >= my_rsv->rsv_start &&
start_block <= my_rsv->rsv_end) {
trace_ext3_reserved(sb, start_block, my_rsv);
return 0; /* success */
}
/*
* if the first free bit we found is out of the reservable space
* continue search for next reservable space,
* start from where the free block is,
* we also shift the list head to where we stopped last time
*/
search_head = my_rsv;
spin_lock(rsv_lock);
goto retry;
}
/**
* try_to_extend_reservation()
* @my_rsv: given reservation window
* @sb: super block
* @size: the delta to extend
*
* Attempt to expand the reservation window large enough to have
* required number of free blocks
*
* Since ext3_try_to_allocate() will always allocate blocks within
* the reservation window range, if the window size is too small,
* multiple blocks allocation has to stop at the end of the reservation
* window. To make this more efficient, given the total number of
* blocks needed and the current size of the window, we try to
* expand the reservation window size if necessary on a best-effort
* basis before ext3_new_blocks() tries to allocate blocks,
*/
static void try_to_extend_reservation(struct ext3_reserve_window_node *my_rsv,
struct super_block *sb, int size)
{
struct ext3_reserve_window_node *next_rsv;
struct rb_node *next;
spinlock_t *rsv_lock = &EXT3_SB(sb)->s_rsv_window_lock;
if (!spin_trylock(rsv_lock))
return;
next = rb_next(&my_rsv->rsv_node);
if (!next)
my_rsv->rsv_end += size;
else {
next_rsv = rb_entry(next, struct ext3_reserve_window_node, rsv_node);
if ((next_rsv->rsv_start - my_rsv->rsv_end - 1) >= size)
my_rsv->rsv_end += size;
else
my_rsv->rsv_end = next_rsv->rsv_start - 1;
}
spin_unlock(rsv_lock);
}
/**
* ext3_try_to_allocate_with_rsv()
* @sb: superblock
* @handle: handle to this transaction
* @group: given allocation block group
* @bitmap_bh: bufferhead holds the block bitmap
* @grp_goal: given target block within the group
* @my_rsv: reservation window
* @count: target number of blocks to allocate
* @errp: pointer to store the error code
*
* This is the main function used to allocate a new block and its reservation
* window.
*
* Each time when a new block allocation is need, first try to allocate from
* its own reservation. If it does not have a reservation window, instead of
* looking for a free bit on bitmap first, then look up the reservation list to
* see if it is inside somebody else's reservation window, we try to allocate a
* reservation window for it starting from the goal first. Then do the block
* allocation within the reservation window.
*
* This will avoid keeping on searching the reservation list again and
* again when somebody is looking for a free block (without
* reservation), and there are lots of free blocks, but they are all
* being reserved.
*
* We use a red-black tree for the per-filesystem reservation list.
*
*/
static ext3_grpblk_t
ext3_try_to_allocate_with_rsv(struct super_block *sb, handle_t *handle,
unsigned int group, struct buffer_head *bitmap_bh,
ext3_grpblk_t grp_goal,
struct ext3_reserve_window_node * my_rsv,
unsigned long *count, int *errp)
{
ext3_fsblk_t group_first_block, group_last_block;
ext3_grpblk_t ret = 0;
int fatal;
unsigned long num = *count;
*errp = 0;
/*
* Make sure we use undo access for the bitmap, because it is critical
* that we do the frozen_data COW on bitmap buffers in all cases even
* if the buffer is in BJ_Forget state in the committing transaction.
*/
BUFFER_TRACE(bitmap_bh, "get undo access for new block");
fatal = ext3_journal_get_undo_access(handle, bitmap_bh);
if (fatal) {
*errp = fatal;
return -1;
}
/*
* we don't deal with reservation when
* filesystem is mounted without reservation
* or the file is not a regular file
* or last attempt to allocate a block with reservation turned on failed
*/
if (my_rsv == NULL ) {
ret = ext3_try_to_allocate(sb, handle, group, bitmap_bh,
grp_goal, count, NULL);
goto out;
}
/*
* grp_goal is a group relative block number (if there is a goal)
* 0 <= grp_goal < EXT3_BLOCKS_PER_GROUP(sb)
* first block is a filesystem wide block number
* first block is the block number of the first block in this group
*/
group_first_block = ext3_group_first_block_no(sb, group);
group_last_block = group_first_block + (EXT3_BLOCKS_PER_GROUP(sb) - 1);
/*
* Basically we will allocate a new block from inode's reservation
* window.
*
* We need to allocate a new reservation window, if:
* a) inode does not have a reservation window; or
* b) last attempt to allocate a block from existing reservation
* failed; or
* c) we come here with a goal and with a reservation window
*
* We do not need to allocate a new reservation window if we come here
* at the beginning with a goal and the goal is inside the window, or
* we don't have a goal but already have a reservation window.
* then we could go to allocate from the reservation window directly.
*/
while (1) {
if (rsv_is_empty(&my_rsv->rsv_window) || (ret < 0) ||
!goal_in_my_reservation(&my_rsv->rsv_window,
grp_goal, group, sb)) {
if (my_rsv->rsv_goal_size < *count)
my_rsv->rsv_goal_size = *count;
ret = alloc_new_reservation(my_rsv, grp_goal, sb,
group, bitmap_bh);
if (ret < 0)
break; /* failed */
if (!goal_in_my_reservation(&my_rsv->rsv_window,
grp_goal, group, sb))
grp_goal = -1;
} else if (grp_goal >= 0) {
int curr = my_rsv->rsv_end -
(grp_goal + group_first_block) + 1;
if (curr < *count)
try_to_extend_reservation(my_rsv, sb,
*count - curr);
}
if ((my_rsv->rsv_start > group_last_block) ||
(my_rsv->rsv_end < group_first_block)) {
rsv_window_dump(&EXT3_SB(sb)->s_rsv_window_root, 1);
BUG();
}
ret = ext3_try_to_allocate(sb, handle, group, bitmap_bh,
grp_goal, &num, &my_rsv->rsv_window);
if (ret >= 0) {
my_rsv->rsv_alloc_hit += num;
*count = num;
break; /* succeed */
}
num = *count;
}
out:
if (ret >= 0) {
BUFFER_TRACE(bitmap_bh, "journal_dirty_metadata for "
"bitmap block");
fatal = ext3_journal_dirty_metadata(handle, bitmap_bh);
if (fatal) {
*errp = fatal;
return -1;
}
return ret;
}
BUFFER_TRACE(bitmap_bh, "journal_release_buffer");
ext3_journal_release_buffer(handle, bitmap_bh);
return ret;
}
/**
* ext3_has_free_blocks()
* @sbi: in-core super block structure.
*
* Check if filesystem has at least 1 free block available for allocation.
*/
static int ext3_has_free_blocks(struct ext3_sb_info *sbi, int use_reservation)
{
ext3_fsblk_t free_blocks, root_blocks;
free_blocks = percpu_counter_read_positive(&sbi->s_freeblocks_counter);
root_blocks = le32_to_cpu(sbi->s_es->s_r_blocks_count);
if (free_blocks < root_blocks + 1 && !capable(CAP_SYS_RESOURCE) &&
!use_reservation && !uid_eq(sbi->s_resuid, current_fsuid()) &&
(gid_eq(sbi->s_resgid, GLOBAL_ROOT_GID) ||
!in_group_p (sbi->s_resgid))) {
return 0;
}
return 1;
}
/**
* ext3_should_retry_alloc()
* @sb: super block
* @retries number of attemps has been made
*
* ext3_should_retry_alloc() is called when ENOSPC is returned, and if
* it is profitable to retry the operation, this function will wait
* for the current or committing transaction to complete, and then
* return TRUE.
*
* if the total number of retries exceed three times, return FALSE.
*/
int ext3_should_retry_alloc(struct super_block *sb, int *retries)
{
if (!ext3_has_free_blocks(EXT3_SB(sb), 0) || (*retries)++ > 3)
return 0;
jbd_debug(1, "%s: retrying operation after ENOSPC\n", sb->s_id);
return journal_force_commit_nested(EXT3_SB(sb)->s_journal);
}
/**
* ext3_new_blocks() -- core block(s) allocation function
* @handle: handle to this transaction
* @inode: file inode
* @goal: given target block(filesystem wide)
* @count: target number of blocks to allocate
* @errp: error code
*
* ext3_new_blocks uses a goal block to assist allocation. It tries to
* allocate block(s) from the block group contains the goal block first. If that
* fails, it will try to allocate block(s) from other block groups without
* any specific goal block.
*
*/
ext3_fsblk_t ext3_new_blocks(handle_t *handle, struct inode *inode,
ext3_fsblk_t goal, unsigned long *count, int *errp)
{
struct buffer_head *bitmap_bh = NULL;
struct buffer_head *gdp_bh;
int group_no;
int goal_group;
ext3_grpblk_t grp_target_blk; /* blockgroup relative goal block */
ext3_grpblk_t grp_alloc_blk; /* blockgroup-relative allocated block*/
ext3_fsblk_t ret_block; /* filesyetem-wide allocated block */
int bgi; /* blockgroup iteration index */
int fatal = 0, err;
int performed_allocation = 0;
ext3_grpblk_t free_blocks; /* number of free blocks in a group */
struct super_block *sb;
struct ext3_group_desc *gdp;
struct ext3_super_block *es;
struct ext3_sb_info *sbi;
struct ext3_reserve_window_node *my_rsv = NULL;
struct ext3_block_alloc_info *block_i;
unsigned short windowsz = 0;
#ifdef EXT3FS_DEBUG
static int goal_hits, goal_attempts;
#endif
unsigned long ngroups;
unsigned long num = *count;
*errp = -ENOSPC;
sb = inode->i_sb;
/*
* Check quota for allocation of this block.
*/
err = dquot_alloc_block(inode, num);
if (err) {
*errp = err;
return 0;
}
trace_ext3_request_blocks(inode, goal, num);
sbi = EXT3_SB(sb);
es = sbi->s_es;
ext3_debug("goal=%lu.\n", goal);
/*
* Allocate a block from reservation only when
* filesystem is mounted with reservation(default,-o reservation), and
* it's a regular file, and
* the desired window size is greater than 0 (One could use ioctl
* command EXT3_IOC_SETRSVSZ to set the window size to 0 to turn off
* reservation on that particular file)
*/
block_i = EXT3_I(inode)->i_block_alloc_info;
if (block_i && ((windowsz = block_i->rsv_window_node.rsv_goal_size) > 0))
my_rsv = &block_i->rsv_window_node;
if (!ext3_has_free_blocks(sbi, IS_NOQUOTA(inode))) {
*errp = -ENOSPC;
goto out;
}
/*
* First, test whether the goal block is free.
*/
if (goal < le32_to_cpu(es->s_first_data_block) ||
goal >= le32_to_cpu(es->s_blocks_count))
goal = le32_to_cpu(es->s_first_data_block);
group_no = (goal - le32_to_cpu(es->s_first_data_block)) /
EXT3_BLOCKS_PER_GROUP(sb);
goal_group = group_no;
retry_alloc:
gdp = ext3_get_group_desc(sb, group_no, &gdp_bh);
if (!gdp)
goto io_error;
free_blocks = le16_to_cpu(gdp->bg_free_blocks_count);
/*
* if there is not enough free blocks to make a new resevation
* turn off reservation for this allocation
*/
if (my_rsv && (free_blocks < windowsz)
&& (free_blocks > 0)
&& (rsv_is_empty(&my_rsv->rsv_window)))
my_rsv = NULL;
if (free_blocks > 0) {
grp_target_blk = ((goal - le32_to_cpu(es->s_first_data_block)) %
EXT3_BLOCKS_PER_GROUP(sb));
bitmap_bh = read_block_bitmap(sb, group_no);
if (!bitmap_bh)
goto io_error;
grp_alloc_blk = ext3_try_to_allocate_with_rsv(sb, handle,
group_no, bitmap_bh, grp_target_blk,
my_rsv, &num, &fatal);
if (fatal)
goto out;
if (grp_alloc_blk >= 0)
goto allocated;
}
ngroups = EXT3_SB(sb)->s_groups_count;
smp_rmb();
/*
* Now search the rest of the groups. We assume that
* group_no and gdp correctly point to the last group visited.
*/
for (bgi = 0; bgi < ngroups; bgi++) {
group_no++;
if (group_no >= ngroups)
group_no = 0;
gdp = ext3_get_group_desc(sb, group_no, &gdp_bh);
if (!gdp)
goto io_error;
free_blocks = le16_to_cpu(gdp->bg_free_blocks_count);
/*
* skip this group (and avoid loading bitmap) if there
* are no free blocks
*/
if (!free_blocks)
continue;
/*
* skip this group if the number of
* free blocks is less than half of the reservation
* window size.
*/
if (my_rsv && (free_blocks <= (windowsz/2)))
continue;
brelse(bitmap_bh);
bitmap_bh = read_block_bitmap(sb, group_no);
if (!bitmap_bh)
goto io_error;
/*
* try to allocate block(s) from this group, without a goal(-1).
*/
grp_alloc_blk = ext3_try_to_allocate_with_rsv(sb, handle,
group_no, bitmap_bh, -1, my_rsv,
&num, &fatal);
if (fatal)
goto out;
if (grp_alloc_blk >= 0)
goto allocated;
}
/*
* We may end up a bogus earlier ENOSPC error due to
* filesystem is "full" of reservations, but
* there maybe indeed free blocks available on disk
* In this case, we just forget about the reservations
* just do block allocation as without reservations.
*/
if (my_rsv) {
my_rsv = NULL;
windowsz = 0;
group_no = goal_group;
goto retry_alloc;
}
/* No space left on the device */
*errp = -ENOSPC;
goto out;
allocated:
ext3_debug("using block group %d(%d)\n",
group_no, gdp->bg_free_blocks_count);
BUFFER_TRACE(gdp_bh, "get_write_access");
fatal = ext3_journal_get_write_access(handle, gdp_bh);
if (fatal)
goto out;
ret_block = grp_alloc_blk + ext3_group_first_block_no(sb, group_no);
if (in_range(le32_to_cpu(gdp->bg_block_bitmap), ret_block, num) ||
in_range(le32_to_cpu(gdp->bg_inode_bitmap), ret_block, num) ||
in_range(ret_block, le32_to_cpu(gdp->bg_inode_table),
EXT3_SB(sb)->s_itb_per_group) ||
in_range(ret_block + num - 1, le32_to_cpu(gdp->bg_inode_table),
EXT3_SB(sb)->s_itb_per_group)) {
ext3_error(sb, "ext3_new_block",
"Allocating block in system zone - "
"blocks from "E3FSBLK", length %lu",
ret_block, num);
/*
* claim_block() marked the blocks we allocated as in use. So we
* may want to selectively mark some of the blocks as free.
*/
goto retry_alloc;
}
performed_allocation = 1;
#ifdef CONFIG_JBD_DEBUG
{
struct buffer_head *debug_bh;
/* Record bitmap buffer state in the newly allocated block */
debug_bh = sb_find_get_block(sb, ret_block);
if (debug_bh) {
BUFFER_TRACE(debug_bh, "state when allocated");
BUFFER_TRACE2(debug_bh, bitmap_bh, "bitmap state");
brelse(debug_bh);
}
}
jbd_lock_bh_state(bitmap_bh);
spin_lock(sb_bgl_lock(sbi, group_no));
if (buffer_jbd(bitmap_bh) && bh2jh(bitmap_bh)->b_committed_data) {
int i;
for (i = 0; i < num; i++) {
if (ext3_test_bit(grp_alloc_blk+i,
bh2jh(bitmap_bh)->b_committed_data)) {
printk("%s: block was unexpectedly set in "
"b_committed_data\n", __func__);
}
}
}
ext3_debug("found bit %d\n", grp_alloc_blk);
spin_unlock(sb_bgl_lock(sbi, group_no));
jbd_unlock_bh_state(bitmap_bh);
#endif
if (ret_block + num - 1 >= le32_to_cpu(es->s_blocks_count)) {
ext3_error(sb, "ext3_new_block",
"block("E3FSBLK") >= blocks count(%d) - "
"block_group = %d, es == %p ", ret_block,
le32_to_cpu(es->s_blocks_count), group_no, es);
goto out;
}
/*
* It is up to the caller to add the new buffer to a journal
* list of some description. We don't know in advance whether
* the caller wants to use it as metadata or data.
*/
ext3_debug("allocating block %lu. Goal hits %d of %d.\n",
ret_block, goal_hits, goal_attempts);
spin_lock(sb_bgl_lock(sbi, group_no));
le16_add_cpu(&gdp->bg_free_blocks_count, -num);
spin_unlock(sb_bgl_lock(sbi, group_no));
percpu_counter_sub(&sbi->s_freeblocks_counter, num);
BUFFER_TRACE(gdp_bh, "journal_dirty_metadata for group descriptor");
fatal = ext3_journal_dirty_metadata(handle, gdp_bh);
if (fatal)
goto out;
*errp = 0;
brelse(bitmap_bh);
if (num < *count) {
dquot_free_block(inode, *count-num);
*count = num;
}
trace_ext3_allocate_blocks(inode, goal, num,
(unsigned long long)ret_block);
return ret_block;
io_error:
*errp = -EIO;
out:
if (fatal) {
*errp = fatal;
ext3_std_error(sb, fatal);
}
/*
* Undo the block allocation
*/
if (!performed_allocation)
dquot_free_block(inode, *count);
brelse(bitmap_bh);
return 0;
}
ext3_fsblk_t ext3_new_block(handle_t *handle, struct inode *inode,
ext3_fsblk_t goal, int *errp)
{
unsigned long count = 1;
return ext3_new_blocks(handle, inode, goal, &count, errp);
}
/**
* ext3_count_free_blocks() -- count filesystem free blocks
* @sb: superblock
*
* Adds up the number of free blocks from each block group.
*/
ext3_fsblk_t ext3_count_free_blocks(struct super_block *sb)
{
ext3_fsblk_t desc_count;
struct ext3_group_desc *gdp;
int i;
unsigned long ngroups = EXT3_SB(sb)->s_groups_count;
#ifdef EXT3FS_DEBUG
struct ext3_super_block *es;
ext3_fsblk_t bitmap_count;
unsigned long x;
struct buffer_head *bitmap_bh = NULL;
es = EXT3_SB(sb)->s_es;
desc_count = 0;
bitmap_count = 0;
gdp = NULL;
smp_rmb();
for (i = 0; i < ngroups; i++) {
gdp = ext3_get_group_desc(sb, i, NULL);
if (!gdp)
continue;
desc_count += le16_to_cpu(gdp->bg_free_blocks_count);
brelse(bitmap_bh);
bitmap_bh = read_block_bitmap(sb, i);
if (bitmap_bh == NULL)
continue;
x = ext3_count_free(bitmap_bh, sb->s_blocksize);
printk("group %d: stored = %d, counted = %lu\n",
i, le16_to_cpu(gdp->bg_free_blocks_count), x);
bitmap_count += x;
}
brelse(bitmap_bh);
printk("ext3_count_free_blocks: stored = "E3FSBLK
", computed = "E3FSBLK", "E3FSBLK"\n",
(ext3_fsblk_t)le32_to_cpu(es->s_free_blocks_count),
desc_count, bitmap_count);
return bitmap_count;
#else
desc_count = 0;
smp_rmb();
for (i = 0; i < ngroups; i++) {
gdp = ext3_get_group_desc(sb, i, NULL);
if (!gdp)
continue;
desc_count += le16_to_cpu(gdp->bg_free_blocks_count);
}
return desc_count;
#endif
}
static inline int test_root(int a, int b)
{
int num = b;
while (a > num)
num *= b;
return num == a;
}
static int ext3_group_sparse(int group)
{
if (group <= 1)
return 1;
if (!(group & 1))
return 0;
return (test_root(group, 7) || test_root(group, 5) ||
test_root(group, 3));
}
/**
* ext3_bg_has_super - number of blocks used by the superblock in group
* @sb: superblock for filesystem
* @group: group number to check
*
* Return the number of blocks used by the superblock (primary or backup)
* in this group. Currently this will be only 0 or 1.
*/
int ext3_bg_has_super(struct super_block *sb, int group)
{
if (EXT3_HAS_RO_COMPAT_FEATURE(sb,
EXT3_FEATURE_RO_COMPAT_SPARSE_SUPER) &&
!ext3_group_sparse(group))
return 0;
return 1;
}
static unsigned long ext3_bg_num_gdb_meta(struct super_block *sb, int group)
{
unsigned long metagroup = group / EXT3_DESC_PER_BLOCK(sb);
unsigned long first = metagroup * EXT3_DESC_PER_BLOCK(sb);
unsigned long last = first + EXT3_DESC_PER_BLOCK(sb) - 1;
if (group == first || group == first + 1 || group == last)
return 1;
return 0;
}
static unsigned long ext3_bg_num_gdb_nometa(struct super_block *sb, int group)
{
return ext3_bg_has_super(sb, group) ? EXT3_SB(sb)->s_gdb_count : 0;
}
/**
* ext3_bg_num_gdb - number of blocks used by the group table in group
* @sb: superblock for filesystem
* @group: group number to check
*
* Return the number of blocks used by the group descriptor table
* (primary or backup) in this group. In the future there may be a
* different number of descriptor blocks in each group.
*/
unsigned long ext3_bg_num_gdb(struct super_block *sb, int group)
{
unsigned long first_meta_bg =
le32_to_cpu(EXT3_SB(sb)->s_es->s_first_meta_bg);
unsigned long metagroup = group / EXT3_DESC_PER_BLOCK(sb);
if (!EXT3_HAS_INCOMPAT_FEATURE(sb,EXT3_FEATURE_INCOMPAT_META_BG) ||
metagroup < first_meta_bg)
return ext3_bg_num_gdb_nometa(sb,group);
return ext3_bg_num_gdb_meta(sb,group);
}
/**
* ext3_trim_all_free -- function to trim all free space in alloc. group
* @sb: super block for file system
* @group: allocation group to trim
* @start: first group block to examine
* @max: last group block to examine
* @gdp: allocation group description structure
* @minblocks: minimum extent block count
*
* ext3_trim_all_free walks through group's block bitmap searching for free
* blocks. When the free block is found, it tries to allocate this block and
* consequent free block to get the biggest free extent possible, until it
* reaches any used block. Then issue a TRIM command on this extent and free
* the extent in the block bitmap. This is done until whole group is scanned.
*/
static ext3_grpblk_t ext3_trim_all_free(struct super_block *sb,
unsigned int group,
ext3_grpblk_t start, ext3_grpblk_t max,
ext3_grpblk_t minblocks)
{
handle_t *handle;
ext3_grpblk_t next, free_blocks, bit, freed, count = 0;
ext3_fsblk_t discard_block;
struct ext3_sb_info *sbi;
struct buffer_head *gdp_bh, *bitmap_bh = NULL;
struct ext3_group_desc *gdp;
int err = 0, ret = 0;
/*
* We will update one block bitmap, and one group descriptor
*/
handle = ext3_journal_start_sb(sb, 2);
if (IS_ERR(handle))
return PTR_ERR(handle);
bitmap_bh = read_block_bitmap(sb, group);
if (!bitmap_bh) {
err = -EIO;
goto err_out;
}
BUFFER_TRACE(bitmap_bh, "getting undo access");
err = ext3_journal_get_undo_access(handle, bitmap_bh);
if (err)
goto err_out;
gdp = ext3_get_group_desc(sb, group, &gdp_bh);
if (!gdp) {
err = -EIO;
goto err_out;
}
BUFFER_TRACE(gdp_bh, "get_write_access");
err = ext3_journal_get_write_access(handle, gdp_bh);
if (err)
goto err_out;
free_blocks = le16_to_cpu(gdp->bg_free_blocks_count);
sbi = EXT3_SB(sb);
/* Walk through the whole group */
while (start <= max) {
start = bitmap_search_next_usable_block(start, bitmap_bh, max);
if (start < 0)
break;
next = start;
/*
* Allocate contiguous free extents by setting bits in the
* block bitmap
*/
while (next <= max
&& claim_block(sb_bgl_lock(sbi, group),
next, bitmap_bh)) {
next++;
}
/* We did not claim any blocks */
if (next == start)
continue;
discard_block = (ext3_fsblk_t)start +
ext3_group_first_block_no(sb, group);
/* Update counters */
spin_lock(sb_bgl_lock(sbi, group));
le16_add_cpu(&gdp->bg_free_blocks_count, start - next);
spin_unlock(sb_bgl_lock(sbi, group));
percpu_counter_sub(&sbi->s_freeblocks_counter, next - start);
free_blocks -= next - start;
/* Do not issue a TRIM on extents smaller than minblocks */
if ((next - start) < minblocks)
goto free_extent;
trace_ext3_discard_blocks(sb, discard_block, next - start);
/* Send the TRIM command down to the device */
err = sb_issue_discard(sb, discard_block, next - start,
GFP_NOFS, 0);
count += (next - start);
free_extent:
freed = 0;
/*
* Clear bits in the bitmap
*/
for (bit = start; bit < next; bit++) {
BUFFER_TRACE(bitmap_bh, "clear bit");
if (!ext3_clear_bit_atomic(sb_bgl_lock(sbi, group),
bit, bitmap_bh->b_data)) {
ext3_error(sb, __func__,
"bit already cleared for block "E3FSBLK,
(unsigned long)bit);
BUFFER_TRACE(bitmap_bh, "bit already cleared");
} else {
freed++;
}
}
/* Update couters */
spin_lock(sb_bgl_lock(sbi, group));
le16_add_cpu(&gdp->bg_free_blocks_count, freed);
spin_unlock(sb_bgl_lock(sbi, group));
percpu_counter_add(&sbi->s_freeblocks_counter, freed);
start = next;
if (err < 0) {
if (err != -EOPNOTSUPP)
ext3_warning(sb, __func__, "Discard command "
"returned error %d\n", err);
break;
}
if (fatal_signal_pending(current)) {
err = -ERESTARTSYS;
break;
}
cond_resched();
/* No more suitable extents */
if (free_blocks < minblocks)
break;
}
/* We dirtied the bitmap block */
BUFFER_TRACE(bitmap_bh, "dirtied bitmap block");
ret = ext3_journal_dirty_metadata(handle, bitmap_bh);
if (!err)
err = ret;
/* And the group descriptor block */
BUFFER_TRACE(gdp_bh, "dirtied group descriptor block");
ret = ext3_journal_dirty_metadata(handle, gdp_bh);
if (!err)
err = ret;
ext3_debug("trimmed %d blocks in the group %d\n",
count, group);
err_out:
if (err)
count = err;
ext3_journal_stop(handle);
brelse(bitmap_bh);
return count;
}
/**
* ext3_trim_fs() -- trim ioctl handle function
* @sb: superblock for filesystem
* @start: First Byte to trim
* @len: number of Bytes to trim from start
* @minlen: minimum extent length in Bytes
*
* ext3_trim_fs goes through all allocation groups containing Bytes from
* start to start+len. For each such a group ext3_trim_all_free function
* is invoked to trim all free space.
*/
int ext3_trim_fs(struct super_block *sb, struct fstrim_range *range)
{
ext3_grpblk_t last_block, first_block;
unsigned long group, first_group, last_group;
struct ext3_group_desc *gdp;
struct ext3_super_block *es = EXT3_SB(sb)->s_es;
uint64_t start, minlen, end, trimmed = 0;
ext3_fsblk_t first_data_blk =
le32_to_cpu(EXT3_SB(sb)->s_es->s_first_data_block);
ext3_fsblk_t max_blks = le32_to_cpu(es->s_blocks_count);
int ret = 0;
start = range->start >> sb->s_blocksize_bits;
end = start + (range->len >> sb->s_blocksize_bits) - 1;
minlen = range->minlen >> sb->s_blocksize_bits;
if (minlen > EXT3_BLOCKS_PER_GROUP(sb) ||
start >= max_blks ||
range->len < sb->s_blocksize)
return -EINVAL;
if (end >= max_blks)
end = max_blks - 1;
if (end <= first_data_blk)
goto out;
if (start < first_data_blk)
start = first_data_blk;
smp_rmb();
/* Determine first and last group to examine based on start and len */
ext3_get_group_no_and_offset(sb, (ext3_fsblk_t) start,
&first_group, &first_block);
ext3_get_group_no_and_offset(sb, (ext3_fsblk_t) end,
&last_group, &last_block);
/* end now represents the last block to discard in this group */
end = EXT3_BLOCKS_PER_GROUP(sb) - 1;
for (group = first_group; group <= last_group; group++) {
gdp = ext3_get_group_desc(sb, group, NULL);
if (!gdp)
break;
/*
* For all the groups except the last one, last block will
* always be EXT3_BLOCKS_PER_GROUP(sb)-1, so we only need to
* change it for the last group, note that last_block is
* already computed earlier by ext3_get_group_no_and_offset()
*/
if (group == last_group)
end = last_block;
if (le16_to_cpu(gdp->bg_free_blocks_count) >= minlen) {
ret = ext3_trim_all_free(sb, group, first_block,
end, minlen);
if (ret < 0)
break;
trimmed += ret;
}
/*
* For every group except the first one, we are sure
* that the first block to discard will be block #0.
*/
first_block = 0;
}
if (ret > 0)
ret = 0;
out:
range->len = trimmed * sb->s_blocksize;
return ret;
}
| gpl-2.0 |
Dinjesk/android_kernel_oneplus_msm8996 | drivers/gpio/gpio-rdc321x.c | 1392 | 6080 | /*
* RDC321x GPIO driver
*
* Copyright (C) 2008, Volker Weiss <dev@tintuc.de>
* Copyright (C) 2007-2010 Florian Fainelli <florian@openwrt.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/spinlock.h>
#include <linux/platform_device.h>
#include <linux/pci.h>
#include <linux/gpio.h>
#include <linux/mfd/rdc321x.h>
#include <linux/slab.h>
struct rdc321x_gpio {
spinlock_t lock;
struct pci_dev *sb_pdev;
u32 data_reg[2];
int reg1_ctrl_base;
int reg1_data_base;
int reg2_ctrl_base;
int reg2_data_base;
struct gpio_chip chip;
};
/* read GPIO pin */
static int rdc_gpio_get_value(struct gpio_chip *chip, unsigned gpio)
{
struct rdc321x_gpio *gpch;
u32 value = 0;
int reg;
gpch = container_of(chip, struct rdc321x_gpio, chip);
reg = gpio < 32 ? gpch->reg1_data_base : gpch->reg2_data_base;
spin_lock(&gpch->lock);
pci_write_config_dword(gpch->sb_pdev, reg,
gpch->data_reg[gpio < 32 ? 0 : 1]);
pci_read_config_dword(gpch->sb_pdev, reg, &value);
spin_unlock(&gpch->lock);
return (1 << (gpio & 0x1f)) & value ? 1 : 0;
}
static void rdc_gpio_set_value_impl(struct gpio_chip *chip,
unsigned gpio, int value)
{
struct rdc321x_gpio *gpch;
int reg = (gpio < 32) ? 0 : 1;
gpch = container_of(chip, struct rdc321x_gpio, chip);
if (value)
gpch->data_reg[reg] |= 1 << (gpio & 0x1f);
else
gpch->data_reg[reg] &= ~(1 << (gpio & 0x1f));
pci_write_config_dword(gpch->sb_pdev,
reg ? gpch->reg2_data_base : gpch->reg1_data_base,
gpch->data_reg[reg]);
}
/* set GPIO pin to value */
static void rdc_gpio_set_value(struct gpio_chip *chip,
unsigned gpio, int value)
{
struct rdc321x_gpio *gpch;
gpch = container_of(chip, struct rdc321x_gpio, chip);
spin_lock(&gpch->lock);
rdc_gpio_set_value_impl(chip, gpio, value);
spin_unlock(&gpch->lock);
}
static int rdc_gpio_config(struct gpio_chip *chip,
unsigned gpio, int value)
{
struct rdc321x_gpio *gpch;
int err;
u32 reg;
gpch = container_of(chip, struct rdc321x_gpio, chip);
spin_lock(&gpch->lock);
err = pci_read_config_dword(gpch->sb_pdev, gpio < 32 ?
gpch->reg1_ctrl_base : gpch->reg2_ctrl_base, ®);
if (err)
goto unlock;
reg |= 1 << (gpio & 0x1f);
err = pci_write_config_dword(gpch->sb_pdev, gpio < 32 ?
gpch->reg1_ctrl_base : gpch->reg2_ctrl_base, reg);
if (err)
goto unlock;
rdc_gpio_set_value_impl(chip, gpio, value);
unlock:
spin_unlock(&gpch->lock);
return err;
}
/* configure GPIO pin as input */
static int rdc_gpio_direction_input(struct gpio_chip *chip, unsigned gpio)
{
return rdc_gpio_config(chip, gpio, 1);
}
/*
* Cache the initial value of both GPIO data registers
*/
static int rdc321x_gpio_probe(struct platform_device *pdev)
{
int err;
struct resource *r;
struct rdc321x_gpio *rdc321x_gpio_dev;
struct rdc321x_gpio_pdata *pdata;
pdata = dev_get_platdata(&pdev->dev);
if (!pdata) {
dev_err(&pdev->dev, "no platform data supplied\n");
return -ENODEV;
}
rdc321x_gpio_dev = devm_kzalloc(&pdev->dev, sizeof(struct rdc321x_gpio),
GFP_KERNEL);
if (!rdc321x_gpio_dev)
return -ENOMEM;
r = platform_get_resource_byname(pdev, IORESOURCE_IO, "gpio-reg1");
if (!r) {
dev_err(&pdev->dev, "failed to get gpio-reg1 resource\n");
return -ENODEV;
}
spin_lock_init(&rdc321x_gpio_dev->lock);
rdc321x_gpio_dev->sb_pdev = pdata->sb_pdev;
rdc321x_gpio_dev->reg1_ctrl_base = r->start;
rdc321x_gpio_dev->reg1_data_base = r->start + 0x4;
r = platform_get_resource_byname(pdev, IORESOURCE_IO, "gpio-reg2");
if (!r) {
dev_err(&pdev->dev, "failed to get gpio-reg2 resource\n");
return -ENODEV;
}
rdc321x_gpio_dev->reg2_ctrl_base = r->start;
rdc321x_gpio_dev->reg2_data_base = r->start + 0x4;
rdc321x_gpio_dev->chip.label = "rdc321x-gpio";
rdc321x_gpio_dev->chip.owner = THIS_MODULE;
rdc321x_gpio_dev->chip.direction_input = rdc_gpio_direction_input;
rdc321x_gpio_dev->chip.direction_output = rdc_gpio_config;
rdc321x_gpio_dev->chip.get = rdc_gpio_get_value;
rdc321x_gpio_dev->chip.set = rdc_gpio_set_value;
rdc321x_gpio_dev->chip.base = 0;
rdc321x_gpio_dev->chip.ngpio = pdata->max_gpios;
platform_set_drvdata(pdev, rdc321x_gpio_dev);
/* This might not be, what others (BIOS, bootloader, etc.)
wrote to these registers before, but it's a good guess. Still
better than just using 0xffffffff. */
err = pci_read_config_dword(rdc321x_gpio_dev->sb_pdev,
rdc321x_gpio_dev->reg1_data_base,
&rdc321x_gpio_dev->data_reg[0]);
if (err)
return err;
err = pci_read_config_dword(rdc321x_gpio_dev->sb_pdev,
rdc321x_gpio_dev->reg2_data_base,
&rdc321x_gpio_dev->data_reg[1]);
if (err)
return err;
dev_info(&pdev->dev, "registering %d GPIOs\n",
rdc321x_gpio_dev->chip.ngpio);
return gpiochip_add(&rdc321x_gpio_dev->chip);
}
static int rdc321x_gpio_remove(struct platform_device *pdev)
{
struct rdc321x_gpio *rdc321x_gpio_dev = platform_get_drvdata(pdev);
gpiochip_remove(&rdc321x_gpio_dev->chip);
return 0;
}
static struct platform_driver rdc321x_gpio_driver = {
.driver.name = "rdc321x-gpio",
.driver.owner = THIS_MODULE,
.probe = rdc321x_gpio_probe,
.remove = rdc321x_gpio_remove,
};
module_platform_driver(rdc321x_gpio_driver);
MODULE_AUTHOR("Florian Fainelli <florian@openwrt.org>");
MODULE_DESCRIPTION("RDC321x GPIO driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:rdc321x-gpio");
| gpl-2.0 |
jakew02/sp3-linux | drivers/block/rsxx/cregs.c | 2416 | 18574 | /*
* Filename: cregs.c
*
*
* Authors: Joshua Morris <josh.h.morris@us.ibm.com>
* Philip Kelleher <pjk1939@linux.vnet.ibm.com>
*
* (C) Copyright 2013 IBM Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/completion.h>
#include <linux/slab.h>
#include "rsxx_priv.h"
#define CREG_TIMEOUT_MSEC 10000
typedef void (*creg_cmd_cb)(struct rsxx_cardinfo *card,
struct creg_cmd *cmd,
int st);
struct creg_cmd {
struct list_head list;
creg_cmd_cb cb;
void *cb_private;
unsigned int op;
unsigned int addr;
int cnt8;
void *buf;
unsigned int stream;
unsigned int status;
};
static struct kmem_cache *creg_cmd_pool;
/*------------ Private Functions --------------*/
#if defined(__LITTLE_ENDIAN)
#define LITTLE_ENDIAN 1
#elif defined(__BIG_ENDIAN)
#define LITTLE_ENDIAN 0
#else
#error Unknown endianess!!! Aborting...
#endif
static int copy_to_creg_data(struct rsxx_cardinfo *card,
int cnt8,
void *buf,
unsigned int stream)
{
int i = 0;
u32 *data = buf;
if (unlikely(card->eeh_state))
return -EIO;
for (i = 0; cnt8 > 0; i++, cnt8 -= 4) {
/*
* Firmware implementation makes it necessary to byte swap on
* little endian processors.
*/
if (LITTLE_ENDIAN && stream)
iowrite32be(data[i], card->regmap + CREG_DATA(i));
else
iowrite32(data[i], card->regmap + CREG_DATA(i));
}
return 0;
}
static int copy_from_creg_data(struct rsxx_cardinfo *card,
int cnt8,
void *buf,
unsigned int stream)
{
int i = 0;
u32 *data = buf;
if (unlikely(card->eeh_state))
return -EIO;
for (i = 0; cnt8 > 0; i++, cnt8 -= 4) {
/*
* Firmware implementation makes it necessary to byte swap on
* little endian processors.
*/
if (LITTLE_ENDIAN && stream)
data[i] = ioread32be(card->regmap + CREG_DATA(i));
else
data[i] = ioread32(card->regmap + CREG_DATA(i));
}
return 0;
}
static void creg_issue_cmd(struct rsxx_cardinfo *card, struct creg_cmd *cmd)
{
int st;
if (unlikely(card->eeh_state))
return;
iowrite32(cmd->addr, card->regmap + CREG_ADD);
iowrite32(cmd->cnt8, card->regmap + CREG_CNT);
if (cmd->op == CREG_OP_WRITE) {
if (cmd->buf) {
st = copy_to_creg_data(card, cmd->cnt8,
cmd->buf, cmd->stream);
if (st)
return;
}
}
if (unlikely(card->eeh_state))
return;
/* Setting the valid bit will kick off the command. */
iowrite32(cmd->op, card->regmap + CREG_CMD);
}
static void creg_kick_queue(struct rsxx_cardinfo *card)
{
if (card->creg_ctrl.active || list_empty(&card->creg_ctrl.queue))
return;
card->creg_ctrl.active = 1;
card->creg_ctrl.active_cmd = list_first_entry(&card->creg_ctrl.queue,
struct creg_cmd, list);
list_del(&card->creg_ctrl.active_cmd->list);
card->creg_ctrl.q_depth--;
/*
* We have to set the timer before we push the new command. Otherwise,
* we could create a race condition that would occur if the timer
* was not canceled, and expired after the new command was pushed,
* but before the command was issued to hardware.
*/
mod_timer(&card->creg_ctrl.cmd_timer,
jiffies + msecs_to_jiffies(CREG_TIMEOUT_MSEC));
creg_issue_cmd(card, card->creg_ctrl.active_cmd);
}
static int creg_queue_cmd(struct rsxx_cardinfo *card,
unsigned int op,
unsigned int addr,
unsigned int cnt8,
void *buf,
int stream,
creg_cmd_cb callback,
void *cb_private)
{
struct creg_cmd *cmd;
/* Don't queue stuff up if we're halted. */
if (unlikely(card->halt))
return -EINVAL;
if (card->creg_ctrl.reset)
return -EAGAIN;
if (cnt8 > MAX_CREG_DATA8)
return -EINVAL;
cmd = kmem_cache_alloc(creg_cmd_pool, GFP_KERNEL);
if (!cmd)
return -ENOMEM;
INIT_LIST_HEAD(&cmd->list);
cmd->op = op;
cmd->addr = addr;
cmd->cnt8 = cnt8;
cmd->buf = buf;
cmd->stream = stream;
cmd->cb = callback;
cmd->cb_private = cb_private;
cmd->status = 0;
spin_lock_bh(&card->creg_ctrl.lock);
list_add_tail(&cmd->list, &card->creg_ctrl.queue);
card->creg_ctrl.q_depth++;
creg_kick_queue(card);
spin_unlock_bh(&card->creg_ctrl.lock);
return 0;
}
static void creg_cmd_timed_out(unsigned long data)
{
struct rsxx_cardinfo *card = (struct rsxx_cardinfo *) data;
struct creg_cmd *cmd;
spin_lock(&card->creg_ctrl.lock);
cmd = card->creg_ctrl.active_cmd;
card->creg_ctrl.active_cmd = NULL;
spin_unlock(&card->creg_ctrl.lock);
if (cmd == NULL) {
card->creg_ctrl.creg_stats.creg_timeout++;
dev_warn(CARD_TO_DEV(card),
"No active command associated with timeout!\n");
return;
}
if (cmd->cb)
cmd->cb(card, cmd, -ETIMEDOUT);
kmem_cache_free(creg_cmd_pool, cmd);
spin_lock(&card->creg_ctrl.lock);
card->creg_ctrl.active = 0;
creg_kick_queue(card);
spin_unlock(&card->creg_ctrl.lock);
}
static void creg_cmd_done(struct work_struct *work)
{
struct rsxx_cardinfo *card;
struct creg_cmd *cmd;
int st = 0;
card = container_of(work, struct rsxx_cardinfo,
creg_ctrl.done_work);
/*
* The timer could not be cancelled for some reason,
* race to pop the active command.
*/
if (del_timer_sync(&card->creg_ctrl.cmd_timer) == 0)
card->creg_ctrl.creg_stats.failed_cancel_timer++;
spin_lock_bh(&card->creg_ctrl.lock);
cmd = card->creg_ctrl.active_cmd;
card->creg_ctrl.active_cmd = NULL;
spin_unlock_bh(&card->creg_ctrl.lock);
if (cmd == NULL) {
dev_err(CARD_TO_DEV(card),
"Spurious creg interrupt!\n");
return;
}
card->creg_ctrl.creg_stats.stat = ioread32(card->regmap + CREG_STAT);
cmd->status = card->creg_ctrl.creg_stats.stat;
if ((cmd->status & CREG_STAT_STATUS_MASK) == 0) {
dev_err(CARD_TO_DEV(card),
"Invalid status on creg command\n");
/*
* At this point we're probably reading garbage from HW. Don't
* do anything else that could mess up the system and let
* the sync function return an error.
*/
st = -EIO;
goto creg_done;
} else if (cmd->status & CREG_STAT_ERROR) {
st = -EIO;
}
if ((cmd->op == CREG_OP_READ)) {
unsigned int cnt8 = ioread32(card->regmap + CREG_CNT);
/* Paranoid Sanity Checks */
if (!cmd->buf) {
dev_err(CARD_TO_DEV(card),
"Buffer not given for read.\n");
st = -EIO;
goto creg_done;
}
if (cnt8 != cmd->cnt8) {
dev_err(CARD_TO_DEV(card),
"count mismatch\n");
st = -EIO;
goto creg_done;
}
st = copy_from_creg_data(card, cnt8, cmd->buf, cmd->stream);
}
creg_done:
if (cmd->cb)
cmd->cb(card, cmd, st);
kmem_cache_free(creg_cmd_pool, cmd);
spin_lock_bh(&card->creg_ctrl.lock);
card->creg_ctrl.active = 0;
creg_kick_queue(card);
spin_unlock_bh(&card->creg_ctrl.lock);
}
static void creg_reset(struct rsxx_cardinfo *card)
{
struct creg_cmd *cmd = NULL;
struct creg_cmd *tmp;
unsigned long flags;
/*
* mutex_trylock is used here because if reset_lock is taken then a
* reset is already happening. So, we can just go ahead and return.
*/
if (!mutex_trylock(&card->creg_ctrl.reset_lock))
return;
card->creg_ctrl.reset = 1;
spin_lock_irqsave(&card->irq_lock, flags);
rsxx_disable_ier_and_isr(card, CR_INTR_CREG | CR_INTR_EVENT);
spin_unlock_irqrestore(&card->irq_lock, flags);
dev_warn(CARD_TO_DEV(card),
"Resetting creg interface for recovery\n");
/* Cancel outstanding commands */
spin_lock_bh(&card->creg_ctrl.lock);
list_for_each_entry_safe(cmd, tmp, &card->creg_ctrl.queue, list) {
list_del(&cmd->list);
card->creg_ctrl.q_depth--;
if (cmd->cb)
cmd->cb(card, cmd, -ECANCELED);
kmem_cache_free(creg_cmd_pool, cmd);
}
cmd = card->creg_ctrl.active_cmd;
card->creg_ctrl.active_cmd = NULL;
if (cmd) {
if (timer_pending(&card->creg_ctrl.cmd_timer))
del_timer_sync(&card->creg_ctrl.cmd_timer);
if (cmd->cb)
cmd->cb(card, cmd, -ECANCELED);
kmem_cache_free(creg_cmd_pool, cmd);
card->creg_ctrl.active = 0;
}
spin_unlock_bh(&card->creg_ctrl.lock);
card->creg_ctrl.reset = 0;
spin_lock_irqsave(&card->irq_lock, flags);
rsxx_enable_ier_and_isr(card, CR_INTR_CREG | CR_INTR_EVENT);
spin_unlock_irqrestore(&card->irq_lock, flags);
mutex_unlock(&card->creg_ctrl.reset_lock);
}
/* Used for synchronous accesses */
struct creg_completion {
struct completion *cmd_done;
int st;
u32 creg_status;
};
static void creg_cmd_done_cb(struct rsxx_cardinfo *card,
struct creg_cmd *cmd,
int st)
{
struct creg_completion *cmd_completion;
cmd_completion = cmd->cb_private;
BUG_ON(!cmd_completion);
cmd_completion->st = st;
cmd_completion->creg_status = cmd->status;
complete(cmd_completion->cmd_done);
}
static int __issue_creg_rw(struct rsxx_cardinfo *card,
unsigned int op,
unsigned int addr,
unsigned int cnt8,
void *buf,
int stream,
unsigned int *hw_stat)
{
DECLARE_COMPLETION_ONSTACK(cmd_done);
struct creg_completion completion;
unsigned long timeout;
int st;
completion.cmd_done = &cmd_done;
completion.st = 0;
completion.creg_status = 0;
st = creg_queue_cmd(card, op, addr, cnt8, buf, stream, creg_cmd_done_cb,
&completion);
if (st)
return st;
/*
* This timeout is necessary for unresponsive hardware. The additional
* 20 seconds to used to guarantee that each cregs requests has time to
* complete.
*/
timeout = msecs_to_jiffies(CREG_TIMEOUT_MSEC *
card->creg_ctrl.q_depth + 20000);
/*
* The creg interface is guaranteed to complete. It has a timeout
* mechanism that will kick in if hardware does not respond.
*/
st = wait_for_completion_timeout(completion.cmd_done, timeout);
if (st == 0) {
/*
* This is really bad, because the kernel timer did not
* expire and notify us of a timeout!
*/
dev_crit(CARD_TO_DEV(card),
"cregs timer failed\n");
creg_reset(card);
return -EIO;
}
*hw_stat = completion.creg_status;
if (completion.st) {
/*
* This read is needed to verify that there has not been any
* extreme errors that might have occurred, i.e. EEH. The
* function iowrite32 will not detect EEH errors, so it is
* necessary that we recover if such an error is the reason
* for the timeout. This is a dummy read.
*/
ioread32(card->regmap + SCRATCH);
dev_warn(CARD_TO_DEV(card),
"creg command failed(%d x%08x)\n",
completion.st, addr);
return completion.st;
}
return 0;
}
static int issue_creg_rw(struct rsxx_cardinfo *card,
u32 addr,
unsigned int size8,
void *data,
int stream,
int read)
{
unsigned int hw_stat;
unsigned int xfer;
unsigned int op;
int st;
op = read ? CREG_OP_READ : CREG_OP_WRITE;
do {
xfer = min_t(unsigned int, size8, MAX_CREG_DATA8);
st = __issue_creg_rw(card, op, addr, xfer,
data, stream, &hw_stat);
if (st)
return st;
data = (char *)data + xfer;
addr += xfer;
size8 -= xfer;
} while (size8);
return 0;
}
/* ---------------------------- Public API ---------------------------------- */
int rsxx_creg_write(struct rsxx_cardinfo *card,
u32 addr,
unsigned int size8,
void *data,
int byte_stream)
{
return issue_creg_rw(card, addr, size8, data, byte_stream, 0);
}
int rsxx_creg_read(struct rsxx_cardinfo *card,
u32 addr,
unsigned int size8,
void *data,
int byte_stream)
{
return issue_creg_rw(card, addr, size8, data, byte_stream, 1);
}
int rsxx_get_card_state(struct rsxx_cardinfo *card, unsigned int *state)
{
return rsxx_creg_read(card, CREG_ADD_CARD_STATE,
sizeof(*state), state, 0);
}
int rsxx_get_card_size8(struct rsxx_cardinfo *card, u64 *size8)
{
unsigned int size;
int st;
st = rsxx_creg_read(card, CREG_ADD_CARD_SIZE,
sizeof(size), &size, 0);
if (st)
return st;
*size8 = (u64)size * RSXX_HW_BLK_SIZE;
return 0;
}
int rsxx_get_num_targets(struct rsxx_cardinfo *card,
unsigned int *n_targets)
{
return rsxx_creg_read(card, CREG_ADD_NUM_TARGETS,
sizeof(*n_targets), n_targets, 0);
}
int rsxx_get_card_capabilities(struct rsxx_cardinfo *card,
u32 *capabilities)
{
return rsxx_creg_read(card, CREG_ADD_CAPABILITIES,
sizeof(*capabilities), capabilities, 0);
}
int rsxx_issue_card_cmd(struct rsxx_cardinfo *card, u32 cmd)
{
return rsxx_creg_write(card, CREG_ADD_CARD_CMD,
sizeof(cmd), &cmd, 0);
}
/*----------------- HW Log Functions -------------------*/
static void hw_log_msg(struct rsxx_cardinfo *card, const char *str, int len)
{
static char level;
/*
* New messages start with "<#>", where # is the log level. Messages
* that extend past the log buffer will use the previous level
*/
if ((len > 3) && (str[0] == '<') && (str[2] == '>')) {
level = str[1];
str += 3; /* Skip past the log level. */
len -= 3;
}
switch (level) {
case '0':
dev_emerg(CARD_TO_DEV(card), "HW: %.*s", len, str);
break;
case '1':
dev_alert(CARD_TO_DEV(card), "HW: %.*s", len, str);
break;
case '2':
dev_crit(CARD_TO_DEV(card), "HW: %.*s", len, str);
break;
case '3':
dev_err(CARD_TO_DEV(card), "HW: %.*s", len, str);
break;
case '4':
dev_warn(CARD_TO_DEV(card), "HW: %.*s", len, str);
break;
case '5':
dev_notice(CARD_TO_DEV(card), "HW: %.*s", len, str);
break;
case '6':
dev_info(CARD_TO_DEV(card), "HW: %.*s", len, str);
break;
case '7':
dev_dbg(CARD_TO_DEV(card), "HW: %.*s", len, str);
break;
default:
dev_info(CARD_TO_DEV(card), "HW: %.*s", len, str);
break;
}
}
/*
* The substrncpy function copies the src string (which includes the
* terminating '\0' character), up to the count into the dest pointer.
* Returns the number of bytes copied to dest.
*/
static int substrncpy(char *dest, const char *src, int count)
{
int max_cnt = count;
while (count) {
count--;
*dest = *src;
if (*dest == '\0')
break;
src++;
dest++;
}
return max_cnt - count;
}
static void read_hw_log_done(struct rsxx_cardinfo *card,
struct creg_cmd *cmd,
int st)
{
char *buf;
char *log_str;
int cnt;
int len;
int off;
buf = cmd->buf;
off = 0;
/* Failed getting the log message */
if (st)
return;
while (off < cmd->cnt8) {
log_str = &card->log.buf[card->log.buf_len];
cnt = min(cmd->cnt8 - off, LOG_BUF_SIZE8 - card->log.buf_len);
len = substrncpy(log_str, &buf[off], cnt);
off += len;
card->log.buf_len += len;
/*
* Flush the log if we've hit the end of a message or if we've
* run out of buffer space.
*/
if ((log_str[len - 1] == '\0') ||
(card->log.buf_len == LOG_BUF_SIZE8)) {
if (card->log.buf_len != 1) /* Don't log blank lines. */
hw_log_msg(card, card->log.buf,
card->log.buf_len);
card->log.buf_len = 0;
}
}
if (cmd->status & CREG_STAT_LOG_PENDING)
rsxx_read_hw_log(card);
}
int rsxx_read_hw_log(struct rsxx_cardinfo *card)
{
int st;
st = creg_queue_cmd(card, CREG_OP_READ, CREG_ADD_LOG,
sizeof(card->log.tmp), card->log.tmp,
1, read_hw_log_done, NULL);
if (st)
dev_err(CARD_TO_DEV(card),
"Failed getting log text\n");
return st;
}
/*-------------- IOCTL REG Access ------------------*/
static int issue_reg_cmd(struct rsxx_cardinfo *card,
struct rsxx_reg_access *cmd,
int read)
{
unsigned int op = read ? CREG_OP_READ : CREG_OP_WRITE;
return __issue_creg_rw(card, op, cmd->addr, cmd->cnt, cmd->data,
cmd->stream, &cmd->stat);
}
int rsxx_reg_access(struct rsxx_cardinfo *card,
struct rsxx_reg_access __user *ucmd,
int read)
{
struct rsxx_reg_access cmd;
int st;
st = copy_from_user(&cmd, ucmd, sizeof(cmd));
if (st)
return -EFAULT;
if (cmd.cnt > RSXX_MAX_REG_CNT)
return -EFAULT;
st = issue_reg_cmd(card, &cmd, read);
if (st)
return st;
st = put_user(cmd.stat, &ucmd->stat);
if (st)
return -EFAULT;
if (read) {
st = copy_to_user(ucmd->data, cmd.data, cmd.cnt);
if (st)
return -EFAULT;
}
return 0;
}
void rsxx_eeh_save_issued_creg(struct rsxx_cardinfo *card)
{
struct creg_cmd *cmd = NULL;
cmd = card->creg_ctrl.active_cmd;
card->creg_ctrl.active_cmd = NULL;
if (cmd) {
del_timer_sync(&card->creg_ctrl.cmd_timer);
spin_lock_bh(&card->creg_ctrl.lock);
list_add(&cmd->list, &card->creg_ctrl.queue);
card->creg_ctrl.q_depth++;
card->creg_ctrl.active = 0;
spin_unlock_bh(&card->creg_ctrl.lock);
}
}
void rsxx_kick_creg_queue(struct rsxx_cardinfo *card)
{
spin_lock_bh(&card->creg_ctrl.lock);
if (!list_empty(&card->creg_ctrl.queue))
creg_kick_queue(card);
spin_unlock_bh(&card->creg_ctrl.lock);
}
/*------------ Initialization & Setup --------------*/
int rsxx_creg_setup(struct rsxx_cardinfo *card)
{
card->creg_ctrl.active_cmd = NULL;
card->creg_ctrl.creg_wq =
create_singlethread_workqueue(DRIVER_NAME"_creg");
if (!card->creg_ctrl.creg_wq)
return -ENOMEM;
INIT_WORK(&card->creg_ctrl.done_work, creg_cmd_done);
mutex_init(&card->creg_ctrl.reset_lock);
INIT_LIST_HEAD(&card->creg_ctrl.queue);
spin_lock_init(&card->creg_ctrl.lock);
setup_timer(&card->creg_ctrl.cmd_timer, creg_cmd_timed_out,
(unsigned long) card);
return 0;
}
void rsxx_creg_destroy(struct rsxx_cardinfo *card)
{
struct creg_cmd *cmd;
struct creg_cmd *tmp;
int cnt = 0;
/* Cancel outstanding commands */
spin_lock_bh(&card->creg_ctrl.lock);
list_for_each_entry_safe(cmd, tmp, &card->creg_ctrl.queue, list) {
list_del(&cmd->list);
if (cmd->cb)
cmd->cb(card, cmd, -ECANCELED);
kmem_cache_free(creg_cmd_pool, cmd);
cnt++;
}
if (cnt)
dev_info(CARD_TO_DEV(card),
"Canceled %d queue creg commands\n", cnt);
cmd = card->creg_ctrl.active_cmd;
card->creg_ctrl.active_cmd = NULL;
if (cmd) {
if (timer_pending(&card->creg_ctrl.cmd_timer))
del_timer_sync(&card->creg_ctrl.cmd_timer);
if (cmd->cb)
cmd->cb(card, cmd, -ECANCELED);
dev_info(CARD_TO_DEV(card),
"Canceled active creg command\n");
kmem_cache_free(creg_cmd_pool, cmd);
}
spin_unlock_bh(&card->creg_ctrl.lock);
cancel_work_sync(&card->creg_ctrl.done_work);
}
int rsxx_creg_init(void)
{
creg_cmd_pool = KMEM_CACHE(creg_cmd, SLAB_HWCACHE_ALIGN);
if (!creg_cmd_pool)
return -ENOMEM;
return 0;
}
void rsxx_creg_cleanup(void)
{
kmem_cache_destroy(creg_cmd_pool);
}
| gpl-2.0 |
PrestigeMod/SHW-M440S | net/caif/cfveil.c | 2672 | 2713 | /*
* Copyright (C) ST-Ericsson AB 2010
* Author: Sjur Brendeland/sjur.brandeland@stericsson.com
* License terms: GNU General Public License (GPL) version 2
*/
#define pr_fmt(fmt) KBUILD_MODNAME ":%s(): " fmt, __func__
#include <linux/stddef.h>
#include <linux/slab.h>
#include <net/caif/caif_layer.h>
#include <net/caif/cfsrvl.h>
#include <net/caif/cfpkt.h>
#define VEI_PAYLOAD 0x00
#define VEI_CMD_BIT 0x80
#define VEI_FLOW_OFF 0x81
#define VEI_FLOW_ON 0x80
#define VEI_SET_PIN 0x82
#define container_obj(layr) container_of(layr, struct cfsrvl, layer)
static int cfvei_receive(struct cflayer *layr, struct cfpkt *pkt);
static int cfvei_transmit(struct cflayer *layr, struct cfpkt *pkt);
struct cflayer *cfvei_create(u8 channel_id, struct dev_info *dev_info)
{
struct cfsrvl *vei = kmalloc(sizeof(struct cfsrvl), GFP_ATOMIC);
if (!vei) {
pr_warn("Out of memory\n");
return NULL;
}
caif_assert(offsetof(struct cfsrvl, layer) == 0);
memset(vei, 0, sizeof(struct cfsrvl));
cfsrvl_init(vei, channel_id, dev_info, true);
vei->layer.receive = cfvei_receive;
vei->layer.transmit = cfvei_transmit;
snprintf(vei->layer.name, CAIF_LAYER_NAME_SZ - 1, "vei%d", channel_id);
return &vei->layer;
}
static int cfvei_receive(struct cflayer *layr, struct cfpkt *pkt)
{
u8 cmd;
int ret;
caif_assert(layr->up != NULL);
caif_assert(layr->receive != NULL);
caif_assert(layr->ctrlcmd != NULL);
if (cfpkt_extr_head(pkt, &cmd, 1) < 0) {
pr_err("Packet is erroneous!\n");
cfpkt_destroy(pkt);
return -EPROTO;
}
switch (cmd) {
case VEI_PAYLOAD:
ret = layr->up->receive(layr->up, pkt);
return ret;
case VEI_FLOW_OFF:
layr->ctrlcmd(layr, CAIF_CTRLCMD_FLOW_OFF_IND, 0);
cfpkt_destroy(pkt);
return 0;
case VEI_FLOW_ON:
layr->ctrlcmd(layr, CAIF_CTRLCMD_FLOW_ON_IND, 0);
cfpkt_destroy(pkt);
return 0;
case VEI_SET_PIN: /* SET RS232 PIN */
cfpkt_destroy(pkt);
return 0;
default: /* SET RS232 PIN */
pr_warn("Unknown VEI control packet %d (0x%x)!\n", cmd, cmd);
cfpkt_destroy(pkt);
return -EPROTO;
}
}
static int cfvei_transmit(struct cflayer *layr, struct cfpkt *pkt)
{
u8 tmp = 0;
struct caif_payload_info *info;
int ret;
struct cfsrvl *service = container_obj(layr);
if (!cfsrvl_ready(service, &ret))
goto err;
caif_assert(layr->dn != NULL);
caif_assert(layr->dn->transmit != NULL);
if (cfpkt_add_head(pkt, &tmp, 1) < 0) {
pr_err("Packet is erroneous!\n");
ret = -EPROTO;
goto err;
}
/* Add info-> for MUX-layer to route the packet out. */
info = cfpkt_info(pkt);
info->channel_id = service->layer.id;
info->hdr_len = 1;
info->dev_info = &service->dev_info;
return layr->dn->transmit(layr->dn, pkt);
err:
cfpkt_destroy(pkt);
return ret;
}
| gpl-2.0 |
GameTheory-/android_kernel_lge_f6mt | arch/arm/mach-at91/at91sam9263_devices.c | 3184 | 38761 | /*
* arch/arm/mach-at91/at91sam9263_devices.c
*
* Copyright (C) 2007 Atmel Corporation.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
*/
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <linux/dma-mapping.h>
#include <linux/gpio.h>
#include <linux/platform_device.h>
#include <linux/i2c-gpio.h>
#include <linux/fb.h>
#include <video/atmel_lcdc.h>
#include <mach/board.h>
#include <mach/at91sam9263.h>
#include <mach/at91sam9263_matrix.h>
#include <mach/at91_matrix.h>
#include <mach/at91sam9_smc.h>
#include "generic.h"
/* --------------------------------------------------------------------
* USB Host
* -------------------------------------------------------------------- */
#if defined(CONFIG_USB_OHCI_HCD) || defined(CONFIG_USB_OHCI_HCD_MODULE)
static u64 ohci_dmamask = DMA_BIT_MASK(32);
static struct at91_usbh_data usbh_data;
static struct resource usbh_resources[] = {
[0] = {
.start = AT91SAM9263_UHP_BASE,
.end = AT91SAM9263_UHP_BASE + SZ_1M - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9263_ID_UHP,
.end = AT91SAM9263_ID_UHP,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device at91_usbh_device = {
.name = "at91_ohci",
.id = -1,
.dev = {
.dma_mask = &ohci_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
.platform_data = &usbh_data,
},
.resource = usbh_resources,
.num_resources = ARRAY_SIZE(usbh_resources),
};
void __init at91_add_device_usbh(struct at91_usbh_data *data)
{
int i;
if (!data)
return;
/* Enable VBus control for UHP ports */
for (i = 0; i < data->ports; i++) {
if (gpio_is_valid(data->vbus_pin[i]))
at91_set_gpio_output(data->vbus_pin[i],
data->vbus_pin_active_low[i]);
}
/* Enable overcurrent notification */
for (i = 0; i < data->ports; i++) {
if (data->overcurrent_pin[i])
at91_set_gpio_input(data->overcurrent_pin[i], 1);
}
usbh_data = *data;
platform_device_register(&at91_usbh_device);
}
#else
void __init at91_add_device_usbh(struct at91_usbh_data *data) {}
#endif
/* --------------------------------------------------------------------
* USB Device (Gadget)
* -------------------------------------------------------------------- */
#if defined(CONFIG_USB_AT91) || defined(CONFIG_USB_AT91_MODULE)
static struct at91_udc_data udc_data;
static struct resource udc_resources[] = {
[0] = {
.start = AT91SAM9263_BASE_UDP,
.end = AT91SAM9263_BASE_UDP + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9263_ID_UDP,
.end = AT91SAM9263_ID_UDP,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device at91_udc_device = {
.name = "at91_udc",
.id = -1,
.dev = {
.platform_data = &udc_data,
},
.resource = udc_resources,
.num_resources = ARRAY_SIZE(udc_resources),
};
void __init at91_add_device_udc(struct at91_udc_data *data)
{
if (!data)
return;
if (gpio_is_valid(data->vbus_pin)) {
at91_set_gpio_input(data->vbus_pin, 0);
at91_set_deglitch(data->vbus_pin, 1);
}
/* Pullup pin is handled internally by USB device peripheral */
udc_data = *data;
platform_device_register(&at91_udc_device);
}
#else
void __init at91_add_device_udc(struct at91_udc_data *data) {}
#endif
/* --------------------------------------------------------------------
* Ethernet
* -------------------------------------------------------------------- */
#if defined(CONFIG_MACB) || defined(CONFIG_MACB_MODULE)
static u64 eth_dmamask = DMA_BIT_MASK(32);
static struct macb_platform_data eth_data;
static struct resource eth_resources[] = {
[0] = {
.start = AT91SAM9263_BASE_EMAC,
.end = AT91SAM9263_BASE_EMAC + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9263_ID_EMAC,
.end = AT91SAM9263_ID_EMAC,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device at91sam9263_eth_device = {
.name = "macb",
.id = -1,
.dev = {
.dma_mask = ð_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
.platform_data = ð_data,
},
.resource = eth_resources,
.num_resources = ARRAY_SIZE(eth_resources),
};
void __init at91_add_device_eth(struct macb_platform_data *data)
{
if (!data)
return;
if (gpio_is_valid(data->phy_irq_pin)) {
at91_set_gpio_input(data->phy_irq_pin, 0);
at91_set_deglitch(data->phy_irq_pin, 1);
}
/* Pins used for MII and RMII */
at91_set_A_periph(AT91_PIN_PE21, 0); /* ETXCK_EREFCK */
at91_set_B_periph(AT91_PIN_PC25, 0); /* ERXDV */
at91_set_A_periph(AT91_PIN_PE25, 0); /* ERX0 */
at91_set_A_periph(AT91_PIN_PE26, 0); /* ERX1 */
at91_set_A_periph(AT91_PIN_PE27, 0); /* ERXER */
at91_set_A_periph(AT91_PIN_PE28, 0); /* ETXEN */
at91_set_A_periph(AT91_PIN_PE23, 0); /* ETX0 */
at91_set_A_periph(AT91_PIN_PE24, 0); /* ETX1 */
at91_set_A_periph(AT91_PIN_PE30, 0); /* EMDIO */
at91_set_A_periph(AT91_PIN_PE29, 0); /* EMDC */
if (!data->is_rmii) {
at91_set_A_periph(AT91_PIN_PE22, 0); /* ECRS */
at91_set_B_periph(AT91_PIN_PC26, 0); /* ECOL */
at91_set_B_periph(AT91_PIN_PC22, 0); /* ERX2 */
at91_set_B_periph(AT91_PIN_PC23, 0); /* ERX3 */
at91_set_B_periph(AT91_PIN_PC27, 0); /* ERXCK */
at91_set_B_periph(AT91_PIN_PC20, 0); /* ETX2 */
at91_set_B_periph(AT91_PIN_PC21, 0); /* ETX3 */
at91_set_B_periph(AT91_PIN_PC24, 0); /* ETXER */
}
eth_data = *data;
platform_device_register(&at91sam9263_eth_device);
}
#else
void __init at91_add_device_eth(struct macb_platform_data *data) {}
#endif
/* --------------------------------------------------------------------
* MMC / SD
* -------------------------------------------------------------------- */
#if defined(CONFIG_MMC_AT91) || defined(CONFIG_MMC_AT91_MODULE)
static u64 mmc_dmamask = DMA_BIT_MASK(32);
static struct at91_mmc_data mmc0_data, mmc1_data;
static struct resource mmc0_resources[] = {
[0] = {
.start = AT91SAM9263_BASE_MCI0,
.end = AT91SAM9263_BASE_MCI0 + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9263_ID_MCI0,
.end = AT91SAM9263_ID_MCI0,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device at91sam9263_mmc0_device = {
.name = "at91_mci",
.id = 0,
.dev = {
.dma_mask = &mmc_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
.platform_data = &mmc0_data,
},
.resource = mmc0_resources,
.num_resources = ARRAY_SIZE(mmc0_resources),
};
static struct resource mmc1_resources[] = {
[0] = {
.start = AT91SAM9263_BASE_MCI1,
.end = AT91SAM9263_BASE_MCI1 + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9263_ID_MCI1,
.end = AT91SAM9263_ID_MCI1,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device at91sam9263_mmc1_device = {
.name = "at91_mci",
.id = 1,
.dev = {
.dma_mask = &mmc_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
.platform_data = &mmc1_data,
},
.resource = mmc1_resources,
.num_resources = ARRAY_SIZE(mmc1_resources),
};
void __init at91_add_device_mmc(short mmc_id, struct at91_mmc_data *data)
{
if (!data)
return;
/* input/irq */
if (gpio_is_valid(data->det_pin)) {
at91_set_gpio_input(data->det_pin, 1);
at91_set_deglitch(data->det_pin, 1);
}
if (gpio_is_valid(data->wp_pin))
at91_set_gpio_input(data->wp_pin, 1);
if (gpio_is_valid(data->vcc_pin))
at91_set_gpio_output(data->vcc_pin, 0);
if (mmc_id == 0) { /* MCI0 */
/* CLK */
at91_set_A_periph(AT91_PIN_PA12, 0);
if (data->slot_b) {
/* CMD */
at91_set_A_periph(AT91_PIN_PA16, 1);
/* DAT0, maybe DAT1..DAT3 */
at91_set_A_periph(AT91_PIN_PA17, 1);
if (data->wire4) {
at91_set_A_periph(AT91_PIN_PA18, 1);
at91_set_A_periph(AT91_PIN_PA19, 1);
at91_set_A_periph(AT91_PIN_PA20, 1);
}
} else {
/* CMD */
at91_set_A_periph(AT91_PIN_PA1, 1);
/* DAT0, maybe DAT1..DAT3 */
at91_set_A_periph(AT91_PIN_PA0, 1);
if (data->wire4) {
at91_set_A_periph(AT91_PIN_PA3, 1);
at91_set_A_periph(AT91_PIN_PA4, 1);
at91_set_A_periph(AT91_PIN_PA5, 1);
}
}
mmc0_data = *data;
platform_device_register(&at91sam9263_mmc0_device);
} else { /* MCI1 */
/* CLK */
at91_set_A_periph(AT91_PIN_PA6, 0);
if (data->slot_b) {
/* CMD */
at91_set_A_periph(AT91_PIN_PA21, 1);
/* DAT0, maybe DAT1..DAT3 */
at91_set_A_periph(AT91_PIN_PA22, 1);
if (data->wire4) {
at91_set_A_periph(AT91_PIN_PA23, 1);
at91_set_A_periph(AT91_PIN_PA24, 1);
at91_set_A_periph(AT91_PIN_PA25, 1);
}
} else {
/* CMD */
at91_set_A_periph(AT91_PIN_PA7, 1);
/* DAT0, maybe DAT1..DAT3 */
at91_set_A_periph(AT91_PIN_PA8, 1);
if (data->wire4) {
at91_set_A_periph(AT91_PIN_PA9, 1);
at91_set_A_periph(AT91_PIN_PA10, 1);
at91_set_A_periph(AT91_PIN_PA11, 1);
}
}
mmc1_data = *data;
platform_device_register(&at91sam9263_mmc1_device);
}
}
#else
void __init at91_add_device_mmc(short mmc_id, struct at91_mmc_data *data) {}
#endif
/* --------------------------------------------------------------------
* Compact Flash (PCMCIA or IDE)
* -------------------------------------------------------------------- */
#if defined(CONFIG_PATA_AT91) || defined(CONFIG_PATA_AT91_MODULE) || \
defined(CONFIG_AT91_CF) || defined(CONFIG_AT91_CF_MODULE)
static struct at91_cf_data cf0_data;
static struct resource cf0_resources[] = {
[0] = {
.start = AT91_CHIPSELECT_4,
.end = AT91_CHIPSELECT_4 + SZ_256M - 1,
.flags = IORESOURCE_MEM | IORESOURCE_MEM_8AND16BIT,
}
};
static struct platform_device cf0_device = {
.id = 0,
.dev = {
.platform_data = &cf0_data,
},
.resource = cf0_resources,
.num_resources = ARRAY_SIZE(cf0_resources),
};
static struct at91_cf_data cf1_data;
static struct resource cf1_resources[] = {
[0] = {
.start = AT91_CHIPSELECT_5,
.end = AT91_CHIPSELECT_5 + SZ_256M - 1,
.flags = IORESOURCE_MEM | IORESOURCE_MEM_8AND16BIT,
}
};
static struct platform_device cf1_device = {
.id = 1,
.dev = {
.platform_data = &cf1_data,
},
.resource = cf1_resources,
.num_resources = ARRAY_SIZE(cf1_resources),
};
void __init at91_add_device_cf(struct at91_cf_data *data)
{
unsigned long ebi0_csa;
struct platform_device *pdev;
if (!data)
return;
/*
* assign CS4 or CS5 to SMC with Compact Flash logic support,
* we assume SMC timings are configured by board code,
* except True IDE where timings are controlled by driver
*/
ebi0_csa = at91_matrix_read(AT91_MATRIX_EBI0CSA);
switch (data->chipselect) {
case 4:
at91_set_A_periph(AT91_PIN_PD6, 0); /* EBI0_NCS4/CFCS0 */
ebi0_csa |= AT91_MATRIX_EBI0_CS4A_SMC_CF1;
cf0_data = *data;
pdev = &cf0_device;
break;
case 5:
at91_set_A_periph(AT91_PIN_PD7, 0); /* EBI0_NCS5/CFCS1 */
ebi0_csa |= AT91_MATRIX_EBI0_CS5A_SMC_CF2;
cf1_data = *data;
pdev = &cf1_device;
break;
default:
printk(KERN_ERR "AT91 CF: bad chip-select requested (%u)\n",
data->chipselect);
return;
}
at91_matrix_write(AT91_MATRIX_EBI0CSA, ebi0_csa);
if (gpio_is_valid(data->det_pin)) {
at91_set_gpio_input(data->det_pin, 1);
at91_set_deglitch(data->det_pin, 1);
}
if (gpio_is_valid(data->irq_pin)) {
at91_set_gpio_input(data->irq_pin, 1);
at91_set_deglitch(data->irq_pin, 1);
}
if (gpio_is_valid(data->vcc_pin))
/* initially off */
at91_set_gpio_output(data->vcc_pin, 0);
/* enable EBI controlled pins */
at91_set_A_periph(AT91_PIN_PD5, 1); /* NWAIT */
at91_set_A_periph(AT91_PIN_PD8, 0); /* CFCE1 */
at91_set_A_periph(AT91_PIN_PD9, 0); /* CFCE2 */
at91_set_A_periph(AT91_PIN_PD14, 0); /* CFNRW */
pdev->name = (data->flags & AT91_CF_TRUE_IDE) ? "pata_at91" : "at91_cf";
platform_device_register(pdev);
}
#else
void __init at91_add_device_cf(struct at91_cf_data *data) {}
#endif
/* --------------------------------------------------------------------
* NAND / SmartMedia
* -------------------------------------------------------------------- */
#if defined(CONFIG_MTD_NAND_ATMEL) || defined(CONFIG_MTD_NAND_ATMEL_MODULE)
static struct atmel_nand_data nand_data;
#define NAND_BASE AT91_CHIPSELECT_3
static struct resource nand_resources[] = {
[0] = {
.start = NAND_BASE,
.end = NAND_BASE + SZ_256M - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9263_BASE_ECC0,
.end = AT91SAM9263_BASE_ECC0 + SZ_512 - 1,
.flags = IORESOURCE_MEM,
}
};
static struct platform_device at91sam9263_nand_device = {
.name = "atmel_nand",
.id = -1,
.dev = {
.platform_data = &nand_data,
},
.resource = nand_resources,
.num_resources = ARRAY_SIZE(nand_resources),
};
void __init at91_add_device_nand(struct atmel_nand_data *data)
{
unsigned long csa;
if (!data)
return;
csa = at91_matrix_read(AT91_MATRIX_EBI0CSA);
at91_matrix_write(AT91_MATRIX_EBI0CSA, csa | AT91_MATRIX_EBI0_CS3A_SMC_SMARTMEDIA);
/* enable pin */
if (gpio_is_valid(data->enable_pin))
at91_set_gpio_output(data->enable_pin, 1);
/* ready/busy pin */
if (gpio_is_valid(data->rdy_pin))
at91_set_gpio_input(data->rdy_pin, 1);
/* card detect pin */
if (gpio_is_valid(data->det_pin))
at91_set_gpio_input(data->det_pin, 1);
nand_data = *data;
platform_device_register(&at91sam9263_nand_device);
}
#else
void __init at91_add_device_nand(struct atmel_nand_data *data) {}
#endif
/* --------------------------------------------------------------------
* TWI (i2c)
* -------------------------------------------------------------------- */
/*
* Prefer the GPIO code since the TWI controller isn't robust
* (gets overruns and underruns under load) and can only issue
* repeated STARTs in one scenario (the driver doesn't yet handle them).
*/
#if defined(CONFIG_I2C_GPIO) || defined(CONFIG_I2C_GPIO_MODULE)
static struct i2c_gpio_platform_data pdata = {
.sda_pin = AT91_PIN_PB4,
.sda_is_open_drain = 1,
.scl_pin = AT91_PIN_PB5,
.scl_is_open_drain = 1,
.udelay = 2, /* ~100 kHz */
};
static struct platform_device at91sam9263_twi_device = {
.name = "i2c-gpio",
.id = -1,
.dev.platform_data = &pdata,
};
void __init at91_add_device_i2c(struct i2c_board_info *devices, int nr_devices)
{
at91_set_GPIO_periph(AT91_PIN_PB4, 1); /* TWD (SDA) */
at91_set_multi_drive(AT91_PIN_PB4, 1);
at91_set_GPIO_periph(AT91_PIN_PB5, 1); /* TWCK (SCL) */
at91_set_multi_drive(AT91_PIN_PB5, 1);
i2c_register_board_info(0, devices, nr_devices);
platform_device_register(&at91sam9263_twi_device);
}
#elif defined(CONFIG_I2C_AT91) || defined(CONFIG_I2C_AT91_MODULE)
static struct resource twi_resources[] = {
[0] = {
.start = AT91SAM9263_BASE_TWI,
.end = AT91SAM9263_BASE_TWI + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9263_ID_TWI,
.end = AT91SAM9263_ID_TWI,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device at91sam9263_twi_device = {
.name = "at91_i2c",
.id = -1,
.resource = twi_resources,
.num_resources = ARRAY_SIZE(twi_resources),
};
void __init at91_add_device_i2c(struct i2c_board_info *devices, int nr_devices)
{
/* pins used for TWI interface */
at91_set_A_periph(AT91_PIN_PB4, 0); /* TWD */
at91_set_multi_drive(AT91_PIN_PB4, 1);
at91_set_A_periph(AT91_PIN_PB5, 0); /* TWCK */
at91_set_multi_drive(AT91_PIN_PB5, 1);
i2c_register_board_info(0, devices, nr_devices);
platform_device_register(&at91sam9263_twi_device);
}
#else
void __init at91_add_device_i2c(struct i2c_board_info *devices, int nr_devices) {}
#endif
/* --------------------------------------------------------------------
* SPI
* -------------------------------------------------------------------- */
#if defined(CONFIG_SPI_ATMEL) || defined(CONFIG_SPI_ATMEL_MODULE)
static u64 spi_dmamask = DMA_BIT_MASK(32);
static struct resource spi0_resources[] = {
[0] = {
.start = AT91SAM9263_BASE_SPI0,
.end = AT91SAM9263_BASE_SPI0 + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9263_ID_SPI0,
.end = AT91SAM9263_ID_SPI0,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device at91sam9263_spi0_device = {
.name = "atmel_spi",
.id = 0,
.dev = {
.dma_mask = &spi_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
},
.resource = spi0_resources,
.num_resources = ARRAY_SIZE(spi0_resources),
};
static const unsigned spi0_standard_cs[4] = { AT91_PIN_PA5, AT91_PIN_PA3, AT91_PIN_PA4, AT91_PIN_PB11 };
static struct resource spi1_resources[] = {
[0] = {
.start = AT91SAM9263_BASE_SPI1,
.end = AT91SAM9263_BASE_SPI1 + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9263_ID_SPI1,
.end = AT91SAM9263_ID_SPI1,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device at91sam9263_spi1_device = {
.name = "atmel_spi",
.id = 1,
.dev = {
.dma_mask = &spi_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
},
.resource = spi1_resources,
.num_resources = ARRAY_SIZE(spi1_resources),
};
static const unsigned spi1_standard_cs[4] = { AT91_PIN_PB15, AT91_PIN_PB16, AT91_PIN_PB17, AT91_PIN_PB18 };
void __init at91_add_device_spi(struct spi_board_info *devices, int nr_devices)
{
int i;
unsigned long cs_pin;
short enable_spi0 = 0;
short enable_spi1 = 0;
/* Choose SPI chip-selects */
for (i = 0; i < nr_devices; i++) {
if (devices[i].controller_data)
cs_pin = (unsigned long) devices[i].controller_data;
else if (devices[i].bus_num == 0)
cs_pin = spi0_standard_cs[devices[i].chip_select];
else
cs_pin = spi1_standard_cs[devices[i].chip_select];
if (!gpio_is_valid(cs_pin))
continue;
if (devices[i].bus_num == 0)
enable_spi0 = 1;
else
enable_spi1 = 1;
/* enable chip-select pin */
at91_set_gpio_output(cs_pin, 1);
/* pass chip-select pin to driver */
devices[i].controller_data = (void *) cs_pin;
}
spi_register_board_info(devices, nr_devices);
/* Configure SPI bus(es) */
if (enable_spi0) {
at91_set_B_periph(AT91_PIN_PA0, 0); /* SPI0_MISO */
at91_set_B_periph(AT91_PIN_PA1, 0); /* SPI0_MOSI */
at91_set_B_periph(AT91_PIN_PA2, 0); /* SPI0_SPCK */
platform_device_register(&at91sam9263_spi0_device);
}
if (enable_spi1) {
at91_set_A_periph(AT91_PIN_PB12, 0); /* SPI1_MISO */
at91_set_A_periph(AT91_PIN_PB13, 0); /* SPI1_MOSI */
at91_set_A_periph(AT91_PIN_PB14, 0); /* SPI1_SPCK */
platform_device_register(&at91sam9263_spi1_device);
}
}
#else
void __init at91_add_device_spi(struct spi_board_info *devices, int nr_devices) {}
#endif
/* --------------------------------------------------------------------
* AC97
* -------------------------------------------------------------------- */
#if defined(CONFIG_SND_ATMEL_AC97C) || defined(CONFIG_SND_ATMEL_AC97C_MODULE)
static u64 ac97_dmamask = DMA_BIT_MASK(32);
static struct ac97c_platform_data ac97_data;
static struct resource ac97_resources[] = {
[0] = {
.start = AT91SAM9263_BASE_AC97C,
.end = AT91SAM9263_BASE_AC97C + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9263_ID_AC97C,
.end = AT91SAM9263_ID_AC97C,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device at91sam9263_ac97_device = {
.name = "atmel_ac97c",
.id = 0,
.dev = {
.dma_mask = &ac97_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
.platform_data = &ac97_data,
},
.resource = ac97_resources,
.num_resources = ARRAY_SIZE(ac97_resources),
};
void __init at91_add_device_ac97(struct ac97c_platform_data *data)
{
if (!data)
return;
at91_set_A_periph(AT91_PIN_PB0, 0); /* AC97FS */
at91_set_A_periph(AT91_PIN_PB1, 0); /* AC97CK */
at91_set_A_periph(AT91_PIN_PB2, 0); /* AC97TX */
at91_set_A_periph(AT91_PIN_PB3, 0); /* AC97RX */
/* reset */
if (gpio_is_valid(data->reset_pin))
at91_set_gpio_output(data->reset_pin, 0);
ac97_data = *data;
platform_device_register(&at91sam9263_ac97_device);
}
#else
void __init at91_add_device_ac97(struct ac97c_platform_data *data) {}
#endif
/* --------------------------------------------------------------------
* CAN Controller
* -------------------------------------------------------------------- */
#if defined(CONFIG_CAN_AT91) || defined(CONFIG_CAN_AT91_MODULE)
static struct resource can_resources[] = {
[0] = {
.start = AT91SAM9263_BASE_CAN,
.end = AT91SAM9263_BASE_CAN + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9263_ID_CAN,
.end = AT91SAM9263_ID_CAN,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device at91sam9263_can_device = {
.name = "at91_can",
.id = -1,
.resource = can_resources,
.num_resources = ARRAY_SIZE(can_resources),
};
void __init at91_add_device_can(struct at91_can_data *data)
{
at91_set_A_periph(AT91_PIN_PA13, 0); /* CANTX */
at91_set_A_periph(AT91_PIN_PA14, 0); /* CANRX */
at91sam9263_can_device.dev.platform_data = data;
platform_device_register(&at91sam9263_can_device);
}
#else
void __init at91_add_device_can(struct at91_can_data *data) {}
#endif
/* --------------------------------------------------------------------
* LCD Controller
* -------------------------------------------------------------------- */
#if defined(CONFIG_FB_ATMEL) || defined(CONFIG_FB_ATMEL_MODULE)
static u64 lcdc_dmamask = DMA_BIT_MASK(32);
static struct atmel_lcdfb_info lcdc_data;
static struct resource lcdc_resources[] = {
[0] = {
.start = AT91SAM9263_LCDC_BASE,
.end = AT91SAM9263_LCDC_BASE + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9263_ID_LCDC,
.end = AT91SAM9263_ID_LCDC,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device at91_lcdc_device = {
.name = "atmel_lcdfb",
.id = 0,
.dev = {
.dma_mask = &lcdc_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
.platform_data = &lcdc_data,
},
.resource = lcdc_resources,
.num_resources = ARRAY_SIZE(lcdc_resources),
};
void __init at91_add_device_lcdc(struct atmel_lcdfb_info *data)
{
if (!data)
return;
at91_set_A_periph(AT91_PIN_PC1, 0); /* LCDHSYNC */
at91_set_A_periph(AT91_PIN_PC2, 0); /* LCDDOTCK */
at91_set_A_periph(AT91_PIN_PC3, 0); /* LCDDEN */
at91_set_B_periph(AT91_PIN_PB9, 0); /* LCDCC */
at91_set_A_periph(AT91_PIN_PC6, 0); /* LCDD2 */
at91_set_A_periph(AT91_PIN_PC7, 0); /* LCDD3 */
at91_set_A_periph(AT91_PIN_PC8, 0); /* LCDD4 */
at91_set_A_periph(AT91_PIN_PC9, 0); /* LCDD5 */
at91_set_A_periph(AT91_PIN_PC10, 0); /* LCDD6 */
at91_set_A_periph(AT91_PIN_PC11, 0); /* LCDD7 */
at91_set_A_periph(AT91_PIN_PC14, 0); /* LCDD10 */
at91_set_A_periph(AT91_PIN_PC15, 0); /* LCDD11 */
at91_set_A_periph(AT91_PIN_PC16, 0); /* LCDD12 */
at91_set_B_periph(AT91_PIN_PC12, 0); /* LCDD13 */
at91_set_A_periph(AT91_PIN_PC18, 0); /* LCDD14 */
at91_set_A_periph(AT91_PIN_PC19, 0); /* LCDD15 */
at91_set_A_periph(AT91_PIN_PC22, 0); /* LCDD18 */
at91_set_A_periph(AT91_PIN_PC23, 0); /* LCDD19 */
at91_set_A_periph(AT91_PIN_PC24, 0); /* LCDD20 */
at91_set_B_periph(AT91_PIN_PC17, 0); /* LCDD21 */
at91_set_A_periph(AT91_PIN_PC26, 0); /* LCDD22 */
at91_set_A_periph(AT91_PIN_PC27, 0); /* LCDD23 */
lcdc_data = *data;
platform_device_register(&at91_lcdc_device);
}
#else
void __init at91_add_device_lcdc(struct atmel_lcdfb_info *data) {}
#endif
/* --------------------------------------------------------------------
* Image Sensor Interface
* -------------------------------------------------------------------- */
#if defined(CONFIG_VIDEO_AT91_ISI) || defined(CONFIG_VIDEO_AT91_ISI_MODULE)
struct resource isi_resources[] = {
[0] = {
.start = AT91SAM9263_BASE_ISI,
.end = AT91SAM9263_BASE_ISI + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9263_ID_ISI,
.end = AT91SAM9263_ID_ISI,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device at91sam9263_isi_device = {
.name = "at91_isi",
.id = -1,
.resource = isi_resources,
.num_resources = ARRAY_SIZE(isi_resources),
};
void __init at91_add_device_isi(struct isi_platform_data *data,
bool use_pck_as_mck)
{
at91_set_A_periph(AT91_PIN_PE0, 0); /* ISI_D0 */
at91_set_A_periph(AT91_PIN_PE1, 0); /* ISI_D1 */
at91_set_A_periph(AT91_PIN_PE2, 0); /* ISI_D2 */
at91_set_A_periph(AT91_PIN_PE3, 0); /* ISI_D3 */
at91_set_A_periph(AT91_PIN_PE4, 0); /* ISI_D4 */
at91_set_A_periph(AT91_PIN_PE5, 0); /* ISI_D5 */
at91_set_A_periph(AT91_PIN_PE6, 0); /* ISI_D6 */
at91_set_A_periph(AT91_PIN_PE7, 0); /* ISI_D7 */
at91_set_A_periph(AT91_PIN_PE8, 0); /* ISI_PCK */
at91_set_A_periph(AT91_PIN_PE9, 0); /* ISI_HSYNC */
at91_set_A_periph(AT91_PIN_PE10, 0); /* ISI_VSYNC */
at91_set_B_periph(AT91_PIN_PE12, 0); /* ISI_PD8 */
at91_set_B_periph(AT91_PIN_PE13, 0); /* ISI_PD9 */
at91_set_B_periph(AT91_PIN_PE14, 0); /* ISI_PD10 */
at91_set_B_periph(AT91_PIN_PE15, 0); /* ISI_PD11 */
if (use_pck_as_mck) {
at91_set_B_periph(AT91_PIN_PE11, 0); /* ISI_MCK (PCK3) */
/* TODO: register the PCK for ISI_MCK and set its parent */
}
}
#else
void __init at91_add_device_isi(struct isi_platform_data *data,
bool use_pck_as_mck) {}
#endif
/* --------------------------------------------------------------------
* Timer/Counter block
* -------------------------------------------------------------------- */
#ifdef CONFIG_ATMEL_TCLIB
static struct resource tcb_resources[] = {
[0] = {
.start = AT91SAM9263_BASE_TCB0,
.end = AT91SAM9263_BASE_TCB0 + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9263_ID_TCB,
.end = AT91SAM9263_ID_TCB,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device at91sam9263_tcb_device = {
.name = "atmel_tcb",
.id = 0,
.resource = tcb_resources,
.num_resources = ARRAY_SIZE(tcb_resources),
};
static void __init at91_add_device_tc(void)
{
platform_device_register(&at91sam9263_tcb_device);
}
#else
static void __init at91_add_device_tc(void) { }
#endif
/* --------------------------------------------------------------------
* RTT
* -------------------------------------------------------------------- */
static struct resource rtt0_resources[] = {
{
.start = AT91SAM9263_BASE_RTT0,
.end = AT91SAM9263_BASE_RTT0 + SZ_16 - 1,
.flags = IORESOURCE_MEM,
}, {
.flags = IORESOURCE_MEM,
}
};
static struct platform_device at91sam9263_rtt0_device = {
.name = "at91_rtt",
.id = 0,
.resource = rtt0_resources,
};
static struct resource rtt1_resources[] = {
{
.start = AT91SAM9263_BASE_RTT1,
.end = AT91SAM9263_BASE_RTT1 + SZ_16 - 1,
.flags = IORESOURCE_MEM,
}, {
.flags = IORESOURCE_MEM,
}
};
static struct platform_device at91sam9263_rtt1_device = {
.name = "at91_rtt",
.id = 1,
.resource = rtt1_resources,
};
#if IS_ENABLED(CONFIG_RTC_DRV_AT91SAM9)
static void __init at91_add_device_rtt_rtc(void)
{
struct platform_device *pdev;
struct resource *r;
switch (CONFIG_RTC_DRV_AT91SAM9_RTT) {
case 0:
/*
* The second resource is needed only for the chosen RTT:
* GPBR will serve as the storage for RTC time offset
*/
at91sam9263_rtt0_device.num_resources = 2;
at91sam9263_rtt1_device.num_resources = 1;
pdev = &at91sam9263_rtt0_device;
r = rtt0_resources;
break;
case 1:
at91sam9263_rtt0_device.num_resources = 1;
at91sam9263_rtt1_device.num_resources = 2;
pdev = &at91sam9263_rtt1_device;
r = rtt1_resources;
break;
default:
pr_err("at91sam9263: only supports 2 RTT (%d)\n",
CONFIG_RTC_DRV_AT91SAM9_RTT);
return;
}
pdev->name = "rtc-at91sam9";
r[1].start = AT91SAM9263_BASE_GPBR + 4 * CONFIG_RTC_DRV_AT91SAM9_GPBR;
r[1].end = r[1].start + 3;
}
#else
static void __init at91_add_device_rtt_rtc(void)
{
/* Only one resource is needed: RTT not used as RTC */
at91sam9263_rtt0_device.num_resources = 1;
at91sam9263_rtt1_device.num_resources = 1;
}
#endif
static void __init at91_add_device_rtt(void)
{
at91_add_device_rtt_rtc();
platform_device_register(&at91sam9263_rtt0_device);
platform_device_register(&at91sam9263_rtt1_device);
}
/* --------------------------------------------------------------------
* Watchdog
* -------------------------------------------------------------------- */
#if defined(CONFIG_AT91SAM9X_WATCHDOG) || defined(CONFIG_AT91SAM9X_WATCHDOG_MODULE)
static struct resource wdt_resources[] = {
{
.start = AT91SAM9263_BASE_WDT,
.end = AT91SAM9263_BASE_WDT + SZ_16 - 1,
.flags = IORESOURCE_MEM,
}
};
static struct platform_device at91sam9263_wdt_device = {
.name = "at91_wdt",
.id = -1,
.resource = wdt_resources,
.num_resources = ARRAY_SIZE(wdt_resources),
};
static void __init at91_add_device_watchdog(void)
{
platform_device_register(&at91sam9263_wdt_device);
}
#else
static void __init at91_add_device_watchdog(void) {}
#endif
/* --------------------------------------------------------------------
* PWM
* --------------------------------------------------------------------*/
#if defined(CONFIG_ATMEL_PWM)
static u32 pwm_mask;
static struct resource pwm_resources[] = {
[0] = {
.start = AT91SAM9263_BASE_PWMC,
.end = AT91SAM9263_BASE_PWMC + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9263_ID_PWMC,
.end = AT91SAM9263_ID_PWMC,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device at91sam9263_pwm0_device = {
.name = "atmel_pwm",
.id = -1,
.dev = {
.platform_data = &pwm_mask,
},
.resource = pwm_resources,
.num_resources = ARRAY_SIZE(pwm_resources),
};
void __init at91_add_device_pwm(u32 mask)
{
if (mask & (1 << AT91_PWM0))
at91_set_B_periph(AT91_PIN_PB7, 1); /* enable PWM0 */
if (mask & (1 << AT91_PWM1))
at91_set_B_periph(AT91_PIN_PB8, 1); /* enable PWM1 */
if (mask & (1 << AT91_PWM2))
at91_set_B_periph(AT91_PIN_PC29, 1); /* enable PWM2 */
if (mask & (1 << AT91_PWM3))
at91_set_B_periph(AT91_PIN_PB29, 1); /* enable PWM3 */
pwm_mask = mask;
platform_device_register(&at91sam9263_pwm0_device);
}
#else
void __init at91_add_device_pwm(u32 mask) {}
#endif
/* --------------------------------------------------------------------
* SSC -- Synchronous Serial Controller
* -------------------------------------------------------------------- */
#if defined(CONFIG_ATMEL_SSC) || defined(CONFIG_ATMEL_SSC_MODULE)
static u64 ssc0_dmamask = DMA_BIT_MASK(32);
static struct resource ssc0_resources[] = {
[0] = {
.start = AT91SAM9263_BASE_SSC0,
.end = AT91SAM9263_BASE_SSC0 + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9263_ID_SSC0,
.end = AT91SAM9263_ID_SSC0,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device at91sam9263_ssc0_device = {
.name = "ssc",
.id = 0,
.dev = {
.dma_mask = &ssc0_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
},
.resource = ssc0_resources,
.num_resources = ARRAY_SIZE(ssc0_resources),
};
static inline void configure_ssc0_pins(unsigned pins)
{
if (pins & ATMEL_SSC_TF)
at91_set_B_periph(AT91_PIN_PB0, 1);
if (pins & ATMEL_SSC_TK)
at91_set_B_periph(AT91_PIN_PB1, 1);
if (pins & ATMEL_SSC_TD)
at91_set_B_periph(AT91_PIN_PB2, 1);
if (pins & ATMEL_SSC_RD)
at91_set_B_periph(AT91_PIN_PB3, 1);
if (pins & ATMEL_SSC_RK)
at91_set_B_periph(AT91_PIN_PB4, 1);
if (pins & ATMEL_SSC_RF)
at91_set_B_periph(AT91_PIN_PB5, 1);
}
static u64 ssc1_dmamask = DMA_BIT_MASK(32);
static struct resource ssc1_resources[] = {
[0] = {
.start = AT91SAM9263_BASE_SSC1,
.end = AT91SAM9263_BASE_SSC1 + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9263_ID_SSC1,
.end = AT91SAM9263_ID_SSC1,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device at91sam9263_ssc1_device = {
.name = "ssc",
.id = 1,
.dev = {
.dma_mask = &ssc1_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
},
.resource = ssc1_resources,
.num_resources = ARRAY_SIZE(ssc1_resources),
};
static inline void configure_ssc1_pins(unsigned pins)
{
if (pins & ATMEL_SSC_TF)
at91_set_A_periph(AT91_PIN_PB6, 1);
if (pins & ATMEL_SSC_TK)
at91_set_A_periph(AT91_PIN_PB7, 1);
if (pins & ATMEL_SSC_TD)
at91_set_A_periph(AT91_PIN_PB8, 1);
if (pins & ATMEL_SSC_RD)
at91_set_A_periph(AT91_PIN_PB9, 1);
if (pins & ATMEL_SSC_RK)
at91_set_A_periph(AT91_PIN_PB10, 1);
if (pins & ATMEL_SSC_RF)
at91_set_A_periph(AT91_PIN_PB11, 1);
}
/*
* SSC controllers are accessed through library code, instead of any
* kind of all-singing/all-dancing driver. For example one could be
* used by a particular I2S audio codec's driver, while another one
* on the same system might be used by a custom data capture driver.
*/
void __init at91_add_device_ssc(unsigned id, unsigned pins)
{
struct platform_device *pdev;
/*
* NOTE: caller is responsible for passing information matching
* "pins" to whatever will be using each particular controller.
*/
switch (id) {
case AT91SAM9263_ID_SSC0:
pdev = &at91sam9263_ssc0_device;
configure_ssc0_pins(pins);
break;
case AT91SAM9263_ID_SSC1:
pdev = &at91sam9263_ssc1_device;
configure_ssc1_pins(pins);
break;
default:
return;
}
platform_device_register(pdev);
}
#else
void __init at91_add_device_ssc(unsigned id, unsigned pins) {}
#endif
/* --------------------------------------------------------------------
* UART
* -------------------------------------------------------------------- */
#if defined(CONFIG_SERIAL_ATMEL)
static struct resource dbgu_resources[] = {
[0] = {
.start = AT91SAM9263_BASE_DBGU,
.end = AT91SAM9263_BASE_DBGU + SZ_512 - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91_ID_SYS,
.end = AT91_ID_SYS,
.flags = IORESOURCE_IRQ,
},
};
static struct atmel_uart_data dbgu_data = {
.use_dma_tx = 0,
.use_dma_rx = 0, /* DBGU not capable of receive DMA */
};
static u64 dbgu_dmamask = DMA_BIT_MASK(32);
static struct platform_device at91sam9263_dbgu_device = {
.name = "atmel_usart",
.id = 0,
.dev = {
.dma_mask = &dbgu_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
.platform_data = &dbgu_data,
},
.resource = dbgu_resources,
.num_resources = ARRAY_SIZE(dbgu_resources),
};
static inline void configure_dbgu_pins(void)
{
at91_set_A_periph(AT91_PIN_PC30, 0); /* DRXD */
at91_set_A_periph(AT91_PIN_PC31, 1); /* DTXD */
}
static struct resource uart0_resources[] = {
[0] = {
.start = AT91SAM9263_BASE_US0,
.end = AT91SAM9263_BASE_US0 + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9263_ID_US0,
.end = AT91SAM9263_ID_US0,
.flags = IORESOURCE_IRQ,
},
};
static struct atmel_uart_data uart0_data = {
.use_dma_tx = 1,
.use_dma_rx = 1,
};
static u64 uart0_dmamask = DMA_BIT_MASK(32);
static struct platform_device at91sam9263_uart0_device = {
.name = "atmel_usart",
.id = 1,
.dev = {
.dma_mask = &uart0_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
.platform_data = &uart0_data,
},
.resource = uart0_resources,
.num_resources = ARRAY_SIZE(uart0_resources),
};
static inline void configure_usart0_pins(unsigned pins)
{
at91_set_A_periph(AT91_PIN_PA26, 1); /* TXD0 */
at91_set_A_periph(AT91_PIN_PA27, 0); /* RXD0 */
if (pins & ATMEL_UART_RTS)
at91_set_A_periph(AT91_PIN_PA28, 0); /* RTS0 */
if (pins & ATMEL_UART_CTS)
at91_set_A_periph(AT91_PIN_PA29, 0); /* CTS0 */
}
static struct resource uart1_resources[] = {
[0] = {
.start = AT91SAM9263_BASE_US1,
.end = AT91SAM9263_BASE_US1 + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9263_ID_US1,
.end = AT91SAM9263_ID_US1,
.flags = IORESOURCE_IRQ,
},
};
static struct atmel_uart_data uart1_data = {
.use_dma_tx = 1,
.use_dma_rx = 1,
};
static u64 uart1_dmamask = DMA_BIT_MASK(32);
static struct platform_device at91sam9263_uart1_device = {
.name = "atmel_usart",
.id = 2,
.dev = {
.dma_mask = &uart1_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
.platform_data = &uart1_data,
},
.resource = uart1_resources,
.num_resources = ARRAY_SIZE(uart1_resources),
};
static inline void configure_usart1_pins(unsigned pins)
{
at91_set_A_periph(AT91_PIN_PD0, 1); /* TXD1 */
at91_set_A_periph(AT91_PIN_PD1, 0); /* RXD1 */
if (pins & ATMEL_UART_RTS)
at91_set_B_periph(AT91_PIN_PD7, 0); /* RTS1 */
if (pins & ATMEL_UART_CTS)
at91_set_B_periph(AT91_PIN_PD8, 0); /* CTS1 */
}
static struct resource uart2_resources[] = {
[0] = {
.start = AT91SAM9263_BASE_US2,
.end = AT91SAM9263_BASE_US2 + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91SAM9263_ID_US2,
.end = AT91SAM9263_ID_US2,
.flags = IORESOURCE_IRQ,
},
};
static struct atmel_uart_data uart2_data = {
.use_dma_tx = 1,
.use_dma_rx = 1,
};
static u64 uart2_dmamask = DMA_BIT_MASK(32);
static struct platform_device at91sam9263_uart2_device = {
.name = "atmel_usart",
.id = 3,
.dev = {
.dma_mask = &uart2_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
.platform_data = &uart2_data,
},
.resource = uart2_resources,
.num_resources = ARRAY_SIZE(uart2_resources),
};
static inline void configure_usart2_pins(unsigned pins)
{
at91_set_A_periph(AT91_PIN_PD2, 1); /* TXD2 */
at91_set_A_periph(AT91_PIN_PD3, 0); /* RXD2 */
if (pins & ATMEL_UART_RTS)
at91_set_B_periph(AT91_PIN_PD5, 0); /* RTS2 */
if (pins & ATMEL_UART_CTS)
at91_set_B_periph(AT91_PIN_PD6, 0); /* CTS2 */
}
static struct platform_device *__initdata at91_uarts[ATMEL_MAX_UART]; /* the UARTs to use */
void __init at91_register_uart(unsigned id, unsigned portnr, unsigned pins)
{
struct platform_device *pdev;
struct atmel_uart_data *pdata;
switch (id) {
case 0: /* DBGU */
pdev = &at91sam9263_dbgu_device;
configure_dbgu_pins();
break;
case AT91SAM9263_ID_US0:
pdev = &at91sam9263_uart0_device;
configure_usart0_pins(pins);
break;
case AT91SAM9263_ID_US1:
pdev = &at91sam9263_uart1_device;
configure_usart1_pins(pins);
break;
case AT91SAM9263_ID_US2:
pdev = &at91sam9263_uart2_device;
configure_usart2_pins(pins);
break;
default:
return;
}
pdata = pdev->dev.platform_data;
pdata->num = portnr; /* update to mapped ID */
if (portnr < ATMEL_MAX_UART)
at91_uarts[portnr] = pdev;
}
void __init at91_set_serial_console(unsigned portnr)
{
if (portnr < ATMEL_MAX_UART) {
atmel_default_console_device = at91_uarts[portnr];
at91sam9263_set_console_clock(at91_uarts[portnr]->id);
}
}
void __init at91_add_device_serial(void)
{
int i;
for (i = 0; i < ATMEL_MAX_UART; i++) {
if (at91_uarts[i])
platform_device_register(at91_uarts[i]);
}
if (!atmel_default_console_device)
printk(KERN_INFO "AT91: No default serial console defined.\n");
}
#else
void __init at91_register_uart(unsigned id, unsigned portnr, unsigned pins) {}
void __init at91_set_serial_console(unsigned portnr) {}
void __init at91_add_device_serial(void) {}
#endif
/* -------------------------------------------------------------------- */
/*
* These devices are always present and don't need any board-specific
* setup.
*/
static int __init at91_add_standard_devices(void)
{
at91_add_device_rtt();
at91_add_device_watchdog();
at91_add_device_tc();
return 0;
}
arch_initcall(at91_add_standard_devices);
| gpl-2.0 |
atniptw/PonyBuntu | drivers/net/ethernet/ibm/emac/tah.c | 3184 | 4144 | /*
* drivers/net/ibm_newemac/tah.c
*
* Driver for PowerPC 4xx on-chip ethernet controller, TAH support.
*
* Copyright 2007 Benjamin Herrenschmidt, IBM Corp.
* <benh@kernel.crashing.org>
*
* Based on the arch/ppc version of the driver:
*
* Copyright 2004 MontaVista Software, Inc.
* Matt Porter <mporter@kernel.crashing.org>
*
* Copyright (c) 2005 Eugene Surovegin <ebs@ebshome.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.
*/
#include <asm/io.h>
#include "emac.h"
#include "core.h"
int __devinit tah_attach(struct platform_device *ofdev, int channel)
{
struct tah_instance *dev = dev_get_drvdata(&ofdev->dev);
mutex_lock(&dev->lock);
/* Reset has been done at probe() time... nothing else to do for now */
++dev->users;
mutex_unlock(&dev->lock);
return 0;
}
void tah_detach(struct platform_device *ofdev, int channel)
{
struct tah_instance *dev = dev_get_drvdata(&ofdev->dev);
mutex_lock(&dev->lock);
--dev->users;
mutex_unlock(&dev->lock);
}
void tah_reset(struct platform_device *ofdev)
{
struct tah_instance *dev = dev_get_drvdata(&ofdev->dev);
struct tah_regs __iomem *p = dev->base;
int n;
/* Reset TAH */
out_be32(&p->mr, TAH_MR_SR);
n = 100;
while ((in_be32(&p->mr) & TAH_MR_SR) && n)
--n;
if (unlikely(!n))
printk(KERN_ERR "%s: reset timeout\n",
ofdev->dev.of_node->full_name);
/* 10KB TAH TX FIFO accommodates the max MTU of 9000 */
out_be32(&p->mr,
TAH_MR_CVR | TAH_MR_ST_768 | TAH_MR_TFS_10KB | TAH_MR_DTFP |
TAH_MR_DIG);
}
int tah_get_regs_len(struct platform_device *ofdev)
{
return sizeof(struct emac_ethtool_regs_subhdr) +
sizeof(struct tah_regs);
}
void *tah_dump_regs(struct platform_device *ofdev, void *buf)
{
struct tah_instance *dev = dev_get_drvdata(&ofdev->dev);
struct emac_ethtool_regs_subhdr *hdr = buf;
struct tah_regs *regs = (struct tah_regs *)(hdr + 1);
hdr->version = 0;
hdr->index = 0; /* for now, are there chips with more than one
* zmii ? if yes, then we'll add a cell_index
* like we do for emac
*/
memcpy_fromio(regs, dev->base, sizeof(struct tah_regs));
return regs + 1;
}
static int __devinit tah_probe(struct platform_device *ofdev)
{
struct device_node *np = ofdev->dev.of_node;
struct tah_instance *dev;
struct resource regs;
int rc;
rc = -ENOMEM;
dev = kzalloc(sizeof(struct tah_instance), GFP_KERNEL);
if (dev == NULL) {
printk(KERN_ERR "%s: could not allocate TAH device!\n",
np->full_name);
goto err_gone;
}
mutex_init(&dev->lock);
dev->ofdev = ofdev;
rc = -ENXIO;
if (of_address_to_resource(np, 0, ®s)) {
printk(KERN_ERR "%s: Can't get registers address\n",
np->full_name);
goto err_free;
}
rc = -ENOMEM;
dev->base = (struct tah_regs __iomem *)ioremap(regs.start,
sizeof(struct tah_regs));
if (dev->base == NULL) {
printk(KERN_ERR "%s: Can't map device registers!\n",
np->full_name);
goto err_free;
}
dev_set_drvdata(&ofdev->dev, dev);
/* Initialize TAH and enable IPv4 checksum verification, no TSO yet */
tah_reset(ofdev);
printk(KERN_INFO
"TAH %s initialized\n", ofdev->dev.of_node->full_name);
wmb();
return 0;
err_free:
kfree(dev);
err_gone:
return rc;
}
static int __devexit tah_remove(struct platform_device *ofdev)
{
struct tah_instance *dev = dev_get_drvdata(&ofdev->dev);
dev_set_drvdata(&ofdev->dev, NULL);
WARN_ON(dev->users != 0);
iounmap(dev->base);
kfree(dev);
return 0;
}
static struct of_device_id tah_match[] =
{
{
.compatible = "ibm,tah",
},
/* For backward compat with old DT */
{
.type = "tah",
},
{},
};
static struct platform_driver tah_driver = {
.driver = {
.name = "emac-tah",
.owner = THIS_MODULE,
.of_match_table = tah_match,
},
.probe = tah_probe,
.remove = tah_remove,
};
int __init tah_init(void)
{
return platform_driver_register(&tah_driver);
}
void tah_exit(void)
{
platform_driver_unregister(&tah_driver);
}
| gpl-2.0 |
elbermu/cerux_kernel-touchwiz | drivers/staging/vt6656/baseband.c | 3184 | 71577 | /*
* Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*
* File: baseband.c
*
* Purpose: Implement functions to access baseband
*
* Author: Jerry Chen
*
* Date: Jun. 5, 2002
*
* Functions:
* BBuGetFrameTime - Calculate data frame transmitting time
* BBvCaculateParameter - Caculate PhyLength, PhyService and Phy Signal parameter for baseband Tx
* BBbVT3184Init - VIA VT3184 baseband chip init code
* BBvLoopbackOn - Turn on BaseBand Loopback mode
* BBvLoopbackOff - Turn off BaseBand Loopback mode
*
* Revision History:
*
*
*/
#include "tmacro.h"
#include "tether.h"
#include "mac.h"
#include "baseband.h"
#include "rf.h"
#include "srom.h"
#include "control.h"
#include "datarate.h"
#include "rndis.h"
/*--------------------- Static Definitions -------------------------*/
static int msglevel =MSG_LEVEL_INFO;
//static int msglevel =MSG_LEVEL_DEBUG;
/*--------------------- Static Classes ----------------------------*/
/*--------------------- Static Variables --------------------------*/
/*--------------------- Static Functions --------------------------*/
/*--------------------- Export Variables --------------------------*/
/*--------------------- Static Definitions -------------------------*/
/*--------------------- Static Classes ----------------------------*/
/*--------------------- Static Variables --------------------------*/
BYTE abyVT3184_AGC[] = {
0x00, //0
0x00, //1
0x02, //2
0x02, //3 //RobertYu:20060505, 0x04, //3
0x04, //4
0x04, //5 //RobertYu:20060505, 0x06, //5
0x06, //6
0x06, //7
0x08, //8
0x08, //9
0x0A, //A
0x0A, //B
0x0C, //C
0x0C, //D
0x0E, //E
0x0E, //F
0x10, //10
0x10, //11
0x12, //12
0x12, //13
0x14, //14
0x14, //15
0x16, //16
0x16, //17
0x18, //18
0x18, //19
0x1A, //1A
0x1A, //1B
0x1C, //1C
0x1C, //1D
0x1E, //1E
0x1E, //1F
0x20, //20
0x20, //21
0x22, //22
0x22, //23
0x24, //24
0x24, //25
0x26, //26
0x26, //27
0x28, //28
0x28, //29
0x2A, //2A
0x2A, //2B
0x2C, //2C
0x2C, //2D
0x2E, //2E
0x2E, //2F
0x30, //30
0x30, //31
0x32, //32
0x32, //33
0x34, //34
0x34, //35
0x36, //36
0x36, //37
0x38, //38
0x38, //39
0x3A, //3A
0x3A, //3B
0x3C, //3C
0x3C, //3D
0x3E, //3E
0x3E //3F
};
BYTE abyVT3184_AL2230[] = {
0x31,//00
0x00,
0x00,
0x00,
0x00,
0x80,
0x00,
0x00,
0x70,
0x45,//tx //0x64 for FPGA
0x2A,
0x76,
0x00,
0x00,
0x80,
0x00,
0x00,//10
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x8e, //RobertYu:20060522, //0x8d,
0x0a, //RobertYu:20060515, //0x09,
0x00,
0x00,
0x00,
0x00,//20
0x00,
0x00,
0x00,
0x00,
0x4a,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x4a,
0x00,
0x0c, //RobertYu:20060522, //0x10,
0x26,//30
0x5b,
0x00,
0x00,
0x00,
0x00,
0xaa,
0xaa,
0xff,
0xff,
0x79,
0x00,
0x00,
0x0b,
0x48,
0x04,
0x00,//40
0x08,
0x00,
0x08,
0x08,
0x14,
0x05,
0x09,
0x00,
0x00,
0x00,
0x00,
0x09,
0x73,
0x00,
0xc5,
0x00,//50 //RobertYu:20060505, //0x15,//50
0x19,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xd0, //RobertYu:20060505, //0xb0,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xe4,//60
0x80,
0x00,
0x00,
0x00,
0x00,
0x98,
0x0a,
0x00,
0x00,
0x00,
0x00,
0x00, //0x80 for FPGA
0x03,
0x01,
0x00,
0x00,//70
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x8c,//80
0x01,
0x09,
0x00,
0x00,
0x00,
0x00,
0x00,
0x08,
0x00,
0x1f, //RobertYu:20060516, //0x0f,
0xb7,
0x88,
0x47,
0xaa,
0x00, //RobertYu:20060505, //0x02,
0x20,//90 //RobertYu:20060505, //0x22,//90
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xeb,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x01,
0x00,//a0
0x00,
0x00,
0x00,
0x00,
0x00,
0x10,
0x00,
0x18,
0x00,
0x00,
0x00,
0x00,
0x15, //RobertYu:20060516, //0x00,
0x00,
0x18,
0x38,//b0
0x30,
0x00,
0x00,
0xff,
0x0f,
0xe4,
0xe2,
0x00,
0x00,
0x00,
0x03,
0x01,
0x00,
0x00,
0x00,
0x18,//c0
0x20,
0x07,
0x18,
0xff,
0xff, //RobertYu:20060509, //0x2c,
0x0e, //RobertYu:20060530, //0x0c,
0x0a,
0x0e,
0x00, //RobertYu:20060505, //0x01,
0x82, //RobertYu:20060516, //0x8f,
0xa7,
0x3c,
0x10,
0x30, //RobertYu:20060627, //0x0b,
0x05, //RobertYu:20060516, //0x25,
0x40,//d0
0x12,
0x00,
0x00,
0x10,
0x28,
0x80,
0x2A,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,//e0
0xf3, //RobertYu:20060516, //0xd3,
0x00,
0x00,
0x00,
0x10,
0x00,
0x12, //RobertYu:20060627, //0x10,
0x00,
0xf4,
0x00,
0xff,
0x79,
0x20,
0x30,
0x05, //RobertYu:20060516, //0x0c,
0x00,//f0
0x3e,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00
};
//{{RobertYu:20060515, new BB setting for VT3226D0
BYTE abyVT3184_VT3226D0[] = {
0x31,//00
0x00,
0x00,
0x00,
0x00,
0x80,
0x00,
0x00,
0x70,
0x45,//tx //0x64 for FPGA
0x2A,
0x76,
0x00,
0x00,
0x80,
0x00,
0x00,//10
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x8e, //RobertYu:20060525, //0x8d,
0x0a, //RobertYu:20060515, //0x09,
0x00,
0x00,
0x00,
0x00,//20
0x00,
0x00,
0x00,
0x00,
0x4a,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x4a,
0x00,
0x0c, //RobertYu:20060525, //0x10,
0x26,//30
0x5b,
0x00,
0x00,
0x00,
0x00,
0xaa,
0xaa,
0xff,
0xff,
0x79,
0x00,
0x00,
0x0b,
0x48,
0x04,
0x00,//40
0x08,
0x00,
0x08,
0x08,
0x14,
0x05,
0x09,
0x00,
0x00,
0x00,
0x00,
0x09,
0x73,
0x00,
0xc5,
0x00,//50 //RobertYu:20060505, //0x15,//50
0x19,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xd0, //RobertYu:20060505, //0xb0,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xe4,//60
0x80,
0x00,
0x00,
0x00,
0x00,
0x98,
0x0a,
0x00,
0x00,
0x00,
0x00,
0x00, //0x80 for FPGA
0x03,
0x01,
0x00,
0x00,//70
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x8c,//80
0x01,
0x09,
0x00,
0x00,
0x00,
0x00,
0x00,
0x08,
0x00,
0x1f, //RobertYu:20060515, //0x0f,
0xb7,
0x88,
0x47,
0xaa,
0x00, //RobertYu:20060505, //0x02,
0x20,//90 //RobertYu:20060505, //0x22,//90
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xeb,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x01,
0x00,//a0
0x00,
0x00,
0x00,
0x00,
0x00,
0x10,
0x00,
0x18,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x18,
0x38,//b0
0x30,
0x00,
0x00,
0xff,
0x0f,
0xe4,
0xe2,
0x00,
0x00,
0x00,
0x03,
0x01,
0x00,
0x00,
0x00,
0x18,//c0
0x20,
0x07,
0x18,
0xff,
0xff, //RobertYu:20060509, //0x2c,
0x10, //RobertYu:20060525, //0x0c,
0x0a,
0x0e,
0x00, //RobertYu:20060505, //0x01,
0x84, //RobertYu:20060525, //0x8f,
0xa7,
0x3c,
0x10,
0x24, //RobertYu:20060627, //0x18,
0x05, //RobertYu:20060515, //0x25,
0x40,//d0
0x12,
0x00,
0x00,
0x10,
0x28,
0x80,
0x2A,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,//e0
0xf3, //RobertYu:20060515, //0xd3,
0x00,
0x00,
0x00,
0x10,
0x00,
0x10, //RobertYu:20060627, //0x0e,
0x00,
0xf4,
0x00,
0xff,
0x79,
0x20,
0x30,
0x08, //RobertYu:20060515, //0x0c,
0x00,//f0
0x3e,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
};
const WORD awcFrameTime[MAX_RATE] =
{10, 20, 55, 110, 24, 36, 48, 72, 96, 144, 192, 216};
/*--------------------- Static Functions --------------------------*/
/*
static
unsigned long
s_ulGetLowSQ3(PSDevice pDevice);
static
unsigned long
s_ulGetRatio(PSDevice pDevice);
static
void
s_vClearSQ3Value(PSDevice pDevice);
*/
/*--------------------- Export Variables --------------------------*/
/*
* Description: Calculate data frame transmitting time
*
* Parameters:
* In:
* byPreambleType - Preamble Type
* byPktType - PK_TYPE_11A, PK_TYPE_11B, PK_TYPE_11GB, PK_TYPE_11GA
* cbFrameLength - Baseband Type
* wRate - Tx Rate
* Out:
*
* Return Value: FrameTime
*
*/
unsigned int
BBuGetFrameTime (
BYTE byPreambleType,
BYTE byPktType,
unsigned int cbFrameLength,
WORD wRate
)
{
unsigned int uFrameTime;
unsigned int uPreamble;
unsigned int uTmp;
unsigned int uRateIdx = (unsigned int)wRate;
unsigned int uRate = 0;
if (uRateIdx > RATE_54M) {
ASSERT(0);
return 0;
}
uRate = (unsigned int)awcFrameTime[uRateIdx];
if (uRateIdx <= 3) { //CCK mode
if (byPreambleType == 1) {//Short
uPreamble = 96;
} else {
uPreamble = 192;
}
uFrameTime = (cbFrameLength * 80) / uRate; //?????
uTmp = (uFrameTime * uRate) / 80;
if (cbFrameLength != uTmp) {
uFrameTime ++;
}
return (uPreamble + uFrameTime);
}
else {
uFrameTime = (cbFrameLength * 8 + 22) / uRate; //????????
uTmp = ((uFrameTime * uRate) - 22) / 8;
if(cbFrameLength != uTmp) {
uFrameTime ++;
}
uFrameTime = uFrameTime * 4; //???????
if(byPktType != PK_TYPE_11A) {
uFrameTime += 6;
}
return (20 + uFrameTime); //??????
}
}
/*
* Description: Caculate Length, Service, and Signal fields of Phy for Tx
*
* Parameters:
* In:
* pDevice - Device Structure
* cbFrameLength - Tx Frame Length
* wRate - Tx Rate
* Out:
* pwPhyLen - pointer to Phy Length field
* pbyPhySrv - pointer to Phy Service field
* pbyPhySgn - pointer to Phy Signal field
*
* Return Value: none
*
*/
void
BBvCaculateParameter (
PSDevice pDevice,
unsigned int cbFrameLength,
WORD wRate,
BYTE byPacketType,
PWORD pwPhyLen,
PBYTE pbyPhySrv,
PBYTE pbyPhySgn
)
{
unsigned int cbBitCount;
unsigned int cbUsCount = 0;
unsigned int cbTmp;
BOOL bExtBit;
BYTE byPreambleType = pDevice->byPreambleType;
BOOL bCCK = pDevice->bCCK;
cbBitCount = cbFrameLength * 8;
bExtBit = FALSE;
switch (wRate) {
case RATE_1M :
cbUsCount = cbBitCount;
*pbyPhySgn = 0x00;
break;
case RATE_2M :
cbUsCount = cbBitCount / 2;
if (byPreambleType == 1)
*pbyPhySgn = 0x09;
else // long preamble
*pbyPhySgn = 0x01;
break;
case RATE_5M :
if (bCCK == FALSE)
cbBitCount ++;
cbUsCount = (cbBitCount * 10) / 55;
cbTmp = (cbUsCount * 55) / 10;
if (cbTmp != cbBitCount)
cbUsCount ++;
if (byPreambleType == 1)
*pbyPhySgn = 0x0a;
else // long preamble
*pbyPhySgn = 0x02;
break;
case RATE_11M :
if (bCCK == FALSE)
cbBitCount ++;
cbUsCount = cbBitCount / 11;
cbTmp = cbUsCount * 11;
if (cbTmp != cbBitCount) {
cbUsCount ++;
if ((cbBitCount - cbTmp) <= 3)
bExtBit = TRUE;
}
if (byPreambleType == 1)
*pbyPhySgn = 0x0b;
else // long preamble
*pbyPhySgn = 0x03;
break;
case RATE_6M :
if(byPacketType == PK_TYPE_11A) {//11a, 5GHZ
*pbyPhySgn = 0x9B; //1001 1011
}
else {//11g, 2.4GHZ
*pbyPhySgn = 0x8B; //1000 1011
}
break;
case RATE_9M :
if(byPacketType == PK_TYPE_11A) {//11a, 5GHZ
*pbyPhySgn = 0x9F; //1001 1111
}
else {//11g, 2.4GHZ
*pbyPhySgn = 0x8F; //1000 1111
}
break;
case RATE_12M :
if(byPacketType == PK_TYPE_11A) {//11a, 5GHZ
*pbyPhySgn = 0x9A; //1001 1010
}
else {//11g, 2.4GHZ
*pbyPhySgn = 0x8A; //1000 1010
}
break;
case RATE_18M :
if(byPacketType == PK_TYPE_11A) {//11a, 5GHZ
*pbyPhySgn = 0x9E; //1001 1110
}
else {//11g, 2.4GHZ
*pbyPhySgn = 0x8E; //1000 1110
}
break;
case RATE_24M :
if(byPacketType == PK_TYPE_11A) {//11a, 5GHZ
*pbyPhySgn = 0x99; //1001 1001
}
else {//11g, 2.4GHZ
*pbyPhySgn = 0x89; //1000 1001
}
break;
case RATE_36M :
if(byPacketType == PK_TYPE_11A) {//11a, 5GHZ
*pbyPhySgn = 0x9D; //1001 1101
}
else {//11g, 2.4GHZ
*pbyPhySgn = 0x8D; //1000 1101
}
break;
case RATE_48M :
if(byPacketType == PK_TYPE_11A) {//11a, 5GHZ
*pbyPhySgn = 0x98; //1001 1000
}
else {//11g, 2.4GHZ
*pbyPhySgn = 0x88; //1000 1000
}
break;
case RATE_54M :
if (byPacketType == PK_TYPE_11A) {//11a, 5GHZ
*pbyPhySgn = 0x9C; //1001 1100
}
else {//11g, 2.4GHZ
*pbyPhySgn = 0x8C; //1000 1100
}
break;
default :
if (byPacketType == PK_TYPE_11A) {//11a, 5GHZ
*pbyPhySgn = 0x9C; //1001 1100
}
else {//11g, 2.4GHZ
*pbyPhySgn = 0x8C; //1000 1100
}
break;
}
if (byPacketType == PK_TYPE_11B) {
*pbyPhySrv = 0x00;
if (bExtBit)
*pbyPhySrv = *pbyPhySrv | 0x80;
*pwPhyLen = (WORD) cbUsCount;
}
else {
*pbyPhySrv = 0x00;
*pwPhyLen = (WORD)cbFrameLength;
}
}
/*
* Description: Set Antenna mode
*
* Parameters:
* In:
* pDevice - Device Structure
* byAntennaMode - Antenna Mode
* Out:
* none
*
* Return Value: none
*
*/
void
BBvSetAntennaMode (PSDevice pDevice, BYTE byAntennaMode)
{
//{{ RobertYu: 20041124, ABG Mode, VC1/VC2 define, make the ANT_A, ANT_B inverted
/*if ( (pDevice->byRFType == RF_MAXIM2829) ||
(pDevice->byRFType == RF_UW2452) ||
(pDevice->byRFType == RF_AIROHA7230) ) { // RobertYu: 20041210, 20050104
switch (byAntennaMode) {
case ANT_TXA:
byAntennaMode = ANT_TXB;
break;
case ANT_TXB:
byAntennaMode = ANT_TXA;
break;
case ANT_RXA:
byAntennaMode = ANT_RXB;
break;
case ANT_RXB:
byAntennaMode = ANT_RXA;
break;
}
}*/
switch (byAntennaMode) {
case ANT_TXA:
break;
case ANT_TXB:
break;
case ANT_RXA:
pDevice->byBBRxConf &= 0xFC;
break;
case ANT_RXB:
pDevice->byBBRxConf &= 0xFE;
pDevice->byBBRxConf |= 0x02;
break;
}
CONTROLnsRequestOut(pDevice,
MESSAGE_TYPE_SET_ANTMD,
(WORD) byAntennaMode,
0,
0,
NULL);
}
/*
* Description: Set Antenna mode
*
* Parameters:
* In:
* pDevice - Device Structure
* byAntennaMode - Antenna Mode
* Out:
* none
*
* Return Value: none
*
*/
BOOL BBbVT3184Init(PSDevice pDevice)
{
int ntStatus;
WORD wLength;
PBYTE pbyAddr;
PBYTE pbyAgc;
WORD wLengthAgc;
BYTE abyArray[256];
ntStatus = CONTROLnsRequestIn(pDevice,
MESSAGE_TYPE_READ,
0,
MESSAGE_REQUEST_EEPROM,
EEP_MAX_CONTEXT_SIZE,
pDevice->abyEEPROM);
if (ntStatus != STATUS_SUCCESS) {
return FALSE;
}
// if ((pDevice->abyEEPROM[EEP_OFS_RADIOCTL]&0x06)==0x04)
// return FALSE;
//zonetype initial
pDevice->byOriginalZonetype = pDevice->abyEEPROM[EEP_OFS_ZONETYPE];
if(pDevice->config_file.ZoneType >= 0) { //read zonetype file ok!
if ((pDevice->config_file.ZoneType == 0)&&
(pDevice->abyEEPROM[EEP_OFS_ZONETYPE] !=0x00)){ //for USA
pDevice->abyEEPROM[EEP_OFS_ZONETYPE] = 0;
pDevice->abyEEPROM[EEP_OFS_MAXCHANNEL] = 0x0B;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Init Zone Type :USA\n");
}
else if((pDevice->config_file.ZoneType == 1)&&
(pDevice->abyEEPROM[EEP_OFS_ZONETYPE]!=0x01)){ //for Japan
pDevice->abyEEPROM[EEP_OFS_ZONETYPE] = 0x01;
pDevice->abyEEPROM[EEP_OFS_MAXCHANNEL] = 0x0D;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Init Zone Type :Japan\n");
}
else if((pDevice->config_file.ZoneType == 2)&&
(pDevice->abyEEPROM[EEP_OFS_ZONETYPE]!=0x02)){ //for Europe
pDevice->abyEEPROM[EEP_OFS_ZONETYPE] = 0x02;
pDevice->abyEEPROM[EEP_OFS_MAXCHANNEL] = 0x0D;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Init Zone Type :Europe\n");
}
else {
if(pDevice->config_file.ZoneType !=pDevice->abyEEPROM[EEP_OFS_ZONETYPE])
printk("zonetype in file[%02x] mismatch with in EEPROM[%02x]\n",pDevice->config_file.ZoneType,pDevice->abyEEPROM[EEP_OFS_ZONETYPE]);
else
printk("Read Zonetype file success,use default zonetype setting[%02x]\n",pDevice->config_file.ZoneType);
}
}
if ( !pDevice->bZoneRegExist ) {
pDevice->byZoneType = pDevice->abyEEPROM[EEP_OFS_ZONETYPE];
}
pDevice->byRFType = pDevice->abyEEPROM[EEP_OFS_RFTYPE];
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"Zone Type %x\n", pDevice->byZoneType);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"RF Type %d\n", pDevice->byRFType);
if ((pDevice->byRFType == RF_AL2230) || (pDevice->byRFType == RF_AL2230S)) {
pDevice->byBBRxConf = abyVT3184_AL2230[10];
wLength = sizeof(abyVT3184_AL2230);
pbyAddr = abyVT3184_AL2230;
pbyAgc = abyVT3184_AGC;
wLengthAgc = sizeof(abyVT3184_AGC);
pDevice->abyBBVGA[0] = 0x1C;
pDevice->abyBBVGA[1] = 0x10;
pDevice->abyBBVGA[2] = 0x0;
pDevice->abyBBVGA[3] = 0x0;
pDevice->ldBmThreshold[0] = -70;
pDevice->ldBmThreshold[1] = -48;
pDevice->ldBmThreshold[2] = 0;
pDevice->ldBmThreshold[3] = 0;
}
else if (pDevice->byRFType == RF_AIROHA7230) {
pDevice->byBBRxConf = abyVT3184_AL2230[10];
wLength = sizeof(abyVT3184_AL2230);
pbyAddr = abyVT3184_AL2230;
pbyAgc = abyVT3184_AGC;
wLengthAgc = sizeof(abyVT3184_AGC);
// Init ANT B select,TX Config CR09 = 0x61->0x45, 0x45->0x41(VC1/VC2 define, make the ANT_A, ANT_B inverted)
//pbyAddr[0x09] = 0x41;
// Init ANT B select,RX Config CR10 = 0x28->0x2A, 0x2A->0x28(VC1/VC2 define, make the ANT_A, ANT_B inverted)
//pbyAddr[0x0a] = 0x28;
// Select VC1/VC2, CR215 = 0x02->0x06
pbyAddr[0xd7] = 0x06;
pDevice->abyBBVGA[0] = 0x1C;
pDevice->abyBBVGA[1] = 0x10;
pDevice->abyBBVGA[2] = 0x0;
pDevice->abyBBVGA[3] = 0x0;
pDevice->ldBmThreshold[0] = -70;
pDevice->ldBmThreshold[1] = -48;
pDevice->ldBmThreshold[2] = 0;
pDevice->ldBmThreshold[3] = 0;
}
else if ( (pDevice->byRFType == RF_VT3226) || (pDevice->byRFType == RF_VT3226D0) ) {
pDevice->byBBRxConf = abyVT3184_VT3226D0[10]; //RobertYu:20060515
wLength = sizeof(abyVT3184_VT3226D0); //RobertYu:20060515
pbyAddr = abyVT3184_VT3226D0; //RobertYu:20060515
pbyAgc = abyVT3184_AGC;
wLengthAgc = sizeof(abyVT3184_AGC);
pDevice->abyBBVGA[0] = 0x20; //RobertYu:20060104, reguest by Jack
pDevice->abyBBVGA[1] = 0x10;
pDevice->abyBBVGA[2] = 0x0;
pDevice->abyBBVGA[3] = 0x0;
pDevice->ldBmThreshold[0] = -70;
pDevice->ldBmThreshold[1] = -48;
pDevice->ldBmThreshold[2] = 0;
pDevice->ldBmThreshold[3] = 0;
// Fix VT3226 DFC system timing issue
MACvRegBitsOn(pDevice, MAC_REG_SOFTPWRCTL2, SOFTPWRCTL_RFLEOPT);
//}}
//{{RobertYu:20060609
} else if ( (pDevice->byRFType == RF_VT3342A0) ) {
pDevice->byBBRxConf = abyVT3184_VT3226D0[10];
wLength = sizeof(abyVT3184_VT3226D0);
pbyAddr = abyVT3184_VT3226D0;
pbyAgc = abyVT3184_AGC;
wLengthAgc = sizeof(abyVT3184_AGC);
pDevice->abyBBVGA[0] = 0x20;
pDevice->abyBBVGA[1] = 0x10;
pDevice->abyBBVGA[2] = 0x0;
pDevice->abyBBVGA[3] = 0x0;
pDevice->ldBmThreshold[0] = -70;
pDevice->ldBmThreshold[1] = -48;
pDevice->ldBmThreshold[2] = 0;
pDevice->ldBmThreshold[3] = 0;
// Fix VT3226 DFC system timing issue
MACvRegBitsOn(pDevice, MAC_REG_SOFTPWRCTL2, SOFTPWRCTL_RFLEOPT);
//}}
} else {
return TRUE;
}
memcpy(abyArray, pbyAddr, wLength);
CONTROLnsRequestOut(pDevice,
MESSAGE_TYPE_WRITE,
0,
MESSAGE_REQUEST_BBREG,
wLength,
abyArray
);
memcpy(abyArray, pbyAgc, wLengthAgc);
CONTROLnsRequestOut(pDevice,
MESSAGE_TYPE_WRITE,
0,
MESSAGE_REQUEST_BBAGC,
wLengthAgc,
abyArray
);
if ((pDevice->byRFType == RF_VT3226) || //RobertYu:20051116, 20060111 remove VT3226D0
(pDevice->byRFType == RF_VT3342A0) //RobertYu:20060609
) {
ControlvWriteByte(pDevice,MESSAGE_REQUEST_MACREG,MAC_REG_ITRTMSET,0x23);
MACvRegBitsOn(pDevice,MAC_REG_PAPEDELAY,0x01);
}
else if (pDevice->byRFType == RF_VT3226D0)
{
ControlvWriteByte(pDevice,MESSAGE_REQUEST_MACREG,MAC_REG_ITRTMSET,0x11);
MACvRegBitsOn(pDevice,MAC_REG_PAPEDELAY,0x01);
}
ControlvWriteByte(pDevice,MESSAGE_REQUEST_BBREG,0x04,0x7F);
ControlvWriteByte(pDevice,MESSAGE_REQUEST_BBREG,0x0D,0x01);
RFbRFTableDownload(pDevice);
return TRUE;//ntStatus;
}
/*
* Description: Turn on BaseBand Loopback mode
*
* Parameters:
* In:
* pDevice - Device Structure
*
* Out:
* none
*
* Return Value: none
*
*/
void BBvLoopbackOn (PSDevice pDevice)
{
BYTE byData;
//CR C9 = 0x00
ControlvReadByte (pDevice, MESSAGE_REQUEST_BBREG, 0xC9, &pDevice->byBBCRc9);//CR201
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0);
ControlvReadByte (pDevice, MESSAGE_REQUEST_BBREG, 0x4D, &pDevice->byBBCR4d);//CR77
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0x4D, 0x90);
//CR 88 = 0x02(CCK), 0x03(OFDM)
ControlvReadByte (pDevice, MESSAGE_REQUEST_BBREG, 0x88, &pDevice->byBBCR88);//CR136
if (pDevice->wCurrentRate <= RATE_11M) { //CCK
// Enable internal digital loopback: CR33 |= 0000 0001
ControlvReadByte (pDevice, MESSAGE_REQUEST_BBREG, 0x21, &byData);//CR33
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0x21, (BYTE)(byData | 0x01));//CR33
// CR154 = 0x00
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0x9A, 0); //CR154
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0x88, 0x02);//CR239
}
else { //OFDM
// Enable internal digital loopback:CR154 |= 0000 0001
ControlvReadByte (pDevice, MESSAGE_REQUEST_BBREG, 0x9A, &byData);//CR154
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0x9A, (BYTE)(byData | 0x01));//CR154
// CR33 = 0x00
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0x21, 0); //CR33
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0x88, 0x03);//CR239
}
//CR14 = 0x00
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0x0E, 0);//CR14
// Disable TX_IQUN
ControlvReadByte (pDevice, MESSAGE_REQUEST_BBREG, 0x09, &pDevice->byBBCR09);
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0x09, (BYTE)(pDevice->byBBCR09 & 0xDE));
}
/*
* Description: Turn off BaseBand Loopback mode
*
* Parameters:
* In:
* pDevice - Device Structure
*
* Out:
* none
*
* Return Value: none
*
*/
void BBvLoopbackOff (PSDevice pDevice)
{
BYTE byData;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, pDevice->byBBCRc9);//CR201
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0x88, pDevice->byBBCR88);//CR136
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0x09, pDevice->byBBCR09);//CR136
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0x4D, pDevice->byBBCR4d);//CR77
if (pDevice->wCurrentRate <= RATE_11M) { // CCK
// Set the CR33 Bit2 to disable internal Loopback.
ControlvReadByte (pDevice, MESSAGE_REQUEST_BBREG, 0x21, &byData);//CR33
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0x21, (BYTE)(byData & 0xFE));//CR33
}
else { // OFDM
ControlvReadByte (pDevice, MESSAGE_REQUEST_BBREG, 0x9A, &byData);//CR154
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0x9A, (BYTE)(byData & 0xFE));//CR154
}
ControlvReadByte (pDevice, MESSAGE_REQUEST_BBREG, 0x0E, &byData);//CR14
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0x0E, (BYTE)(byData | 0x80));//CR14
}
/*
* Description: Set ShortSlotTime mode
*
* Parameters:
* In:
* pDevice - Device Structure
* Out:
* none
*
* Return Value: none
*
*/
void
BBvSetShortSlotTime (PSDevice pDevice)
{
BYTE byBBVGA=0;
if (pDevice->bShortSlotTime) {
pDevice->byBBRxConf &= 0xDF;//1101 1111
} else {
pDevice->byBBRxConf |= 0x20;//0010 0000
}
ControlvReadByte (pDevice, MESSAGE_REQUEST_BBREG, 0xE7, &byBBVGA);
if (byBBVGA == pDevice->abyBBVGA[0]) {
pDevice->byBBRxConf |= 0x20;//0010 0000
}
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0x0A, pDevice->byBBRxConf);
}
void BBvSetVGAGainOffset(PSDevice pDevice, BYTE byData)
{
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xE7, byData);
// patch for 3253B0 Baseband with Cardbus module
if (byData == pDevice->abyBBVGA[0]) {
pDevice->byBBRxConf |= 0x20;//0010 0000
} else if (pDevice->bShortSlotTime) {
pDevice->byBBRxConf &= 0xDF;//1101 1111
} else {
pDevice->byBBRxConf |= 0x20;//0010 0000
}
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0x0A, pDevice->byBBRxConf);//CR10
}
/*
* Description: Baseband SoftwareReset
*
* Parameters:
* In:
* dwIoBase - I/O base address
* Out:
* none
*
* Return Value: none
*
*/
void
BBvSoftwareReset (PSDevice pDevice)
{
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0x50, 0x40);
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0x50, 0);
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0x9C, 0x01);
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0x9C, 0);
}
/*
* Description: BBvSetDeepSleep
*
* Parameters:
* In:
* pDevice - Device Structure
* Out:
* none
*
* Return Value: none
*
*/
void
BBvSetDeepSleep (PSDevice pDevice)
{
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0x0c, 0x17);//CR12
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0x0D, 0xB9);//CR13
}
void
BBvExitDeepSleep (PSDevice pDevice)
{
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0x0C, 0x00);//CR12
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0x0D, 0x01);//CR13
}
static unsigned long s_ulGetLowSQ3(PSDevice pDevice)
{
int ii;
unsigned long ulSQ3 = 0;
unsigned long ulMaxPacket;
ulMaxPacket = pDevice->aulPktNum[RATE_54M];
if ( pDevice->aulPktNum[RATE_54M] != 0 ) {
ulSQ3 = pDevice->aulSQ3Val[RATE_54M] / pDevice->aulPktNum[RATE_54M];
}
for ( ii=RATE_48M;ii>=RATE_6M;ii-- ) {
if ( pDevice->aulPktNum[ii] > ulMaxPacket ) {
ulMaxPacket = pDevice->aulPktNum[ii];
ulSQ3 = pDevice->aulSQ3Val[ii] / pDevice->aulPktNum[ii];
}
}
return ulSQ3;
}
static unsigned long s_ulGetRatio(PSDevice pDevice)
{
int ii, jj;
unsigned long ulRatio = 0;
unsigned long ulMaxPacket;
unsigned long ulPacketNum;
//This is a thousand-ratio
ulMaxPacket = pDevice->aulPktNum[RATE_54M];
if ( pDevice->aulPktNum[RATE_54M] != 0 ) {
ulPacketNum = pDevice->aulPktNum[RATE_54M];
ulRatio = (ulPacketNum * 1000 / pDevice->uDiversityCnt);
ulRatio += TOP_RATE_54M;
}
for ( ii=RATE_48M;ii>=RATE_1M;ii-- ) {
if ( pDevice->aulPktNum[ii] > ulMaxPacket ) {
ulPacketNum = 0;
for ( jj=RATE_54M;jj>=ii;jj--)
ulPacketNum += pDevice->aulPktNum[jj];
ulRatio = (ulPacketNum * 1000 / pDevice->uDiversityCnt);
ulRatio += TOP_RATE_48M;
ulMaxPacket = pDevice->aulPktNum[ii];
}
}
return ulRatio;
}
static
void
s_vClearSQ3Value (PSDevice pDevice)
{
int ii;
pDevice->uDiversityCnt = 0;
for ( ii=RATE_1M;ii<MAX_RATE;ii++) {
pDevice->aulPktNum[ii] = 0;
pDevice->aulSQ3Val[ii] = 0;
}
}
/*
* Description: Antenna Diversity
*
* Parameters:
* In:
* pDevice - Device Structure
* byRSR - RSR from received packet
* bySQ3 - SQ3 value from received packet
* Out:
* none
*
* Return Value: none
*
*/
void
BBvAntennaDiversity (PSDevice pDevice, BYTE byRxRate, BYTE bySQ3)
{
pDevice->uDiversityCnt++;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"pDevice->uDiversityCnt = %d\n", (int)pDevice->uDiversityCnt);
if (byRxRate == 2) {
pDevice->aulPktNum[RATE_1M]++;
}
else if (byRxRate==4) {
pDevice->aulPktNum[RATE_2M]++;
}
else if (byRxRate==11) {
pDevice->aulPktNum[RATE_5M]++;
}
else if (byRxRate==22) {
pDevice->aulPktNum[RATE_11M]++;
}
else if(byRxRate==12){
pDevice->aulPktNum[RATE_6M]++;
pDevice->aulSQ3Val[RATE_6M] += bySQ3;
}
else if(byRxRate==18){
pDevice->aulPktNum[RATE_9M]++;
pDevice->aulSQ3Val[RATE_9M] += bySQ3;
}
else if(byRxRate==24){
pDevice->aulPktNum[RATE_12M]++;
pDevice->aulSQ3Val[RATE_12M] += bySQ3;
}
else if(byRxRate==36){
pDevice->aulPktNum[RATE_18M]++;
pDevice->aulSQ3Val[RATE_18M] += bySQ3;
}
else if(byRxRate==48){
pDevice->aulPktNum[RATE_24M]++;
pDevice->aulSQ3Val[RATE_24M] += bySQ3;
}
else if(byRxRate==72){
pDevice->aulPktNum[RATE_36M]++;
pDevice->aulSQ3Val[RATE_36M] += bySQ3;
}
else if(byRxRate==96){
pDevice->aulPktNum[RATE_48M]++;
pDevice->aulSQ3Val[RATE_48M] += bySQ3;
}
else if(byRxRate==108){
pDevice->aulPktNum[RATE_54M]++;
pDevice->aulSQ3Val[RATE_54M] += bySQ3;
}
if (pDevice->byAntennaState == 0) {
if (pDevice->uDiversityCnt > pDevice->ulDiversityNValue) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"ulDiversityNValue=[%d],54M-[%d]\n",(int)pDevice->ulDiversityNValue, (int)pDevice->aulPktNum[RATE_54M]);
pDevice->ulSQ3_State0 = s_ulGetLowSQ3(pDevice);
pDevice->ulRatio_State0 = s_ulGetRatio(pDevice);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"SQ3_State0, SQ3= [%08x] rate = [%08x]\n",(int)pDevice->ulSQ3_State0,(int)pDevice->ulRatio_State0);
if ( ((pDevice->aulPktNum[RATE_54M] < pDevice->ulDiversityNValue/2) &&
(pDevice->ulSQ3_State0 > pDevice->ulSQ3TH) ) ||
(pDevice->ulSQ3_State0 == 0 ) ) {
if ( pDevice->byTMax == 0 )
return;
bScheduleCommand((void *) pDevice,
WLAN_CMD_CHANGE_ANTENNA,
NULL);
pDevice->byAntennaState = 1;
del_timer(&pDevice->TimerSQ3Tmax3);
del_timer(&pDevice->TimerSQ3Tmax2);
pDevice->TimerSQ3Tmax1.expires = RUN_AT(pDevice->byTMax * HZ);
add_timer(&pDevice->TimerSQ3Tmax1);
} else {
pDevice->TimerSQ3Tmax3.expires = RUN_AT(pDevice->byTMax3 * HZ);
add_timer(&pDevice->TimerSQ3Tmax3);
}
s_vClearSQ3Value(pDevice);
}
} else { //byAntennaState == 1
if (pDevice->uDiversityCnt > pDevice->ulDiversityMValue) {
del_timer(&pDevice->TimerSQ3Tmax1);
pDevice->ulSQ3_State1 = s_ulGetLowSQ3(pDevice);
pDevice->ulRatio_State1 = s_ulGetRatio(pDevice);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"SQ3_State1, rate0 = %08x,rate1 = %08x\n",(int)pDevice->ulRatio_State0,(int)pDevice->ulRatio_State1);
if ( ((pDevice->ulSQ3_State1 == 0) && (pDevice->ulSQ3_State0 != 0)) ||
((pDevice->ulSQ3_State1 == 0) && (pDevice->ulSQ3_State0 == 0) && (pDevice->ulRatio_State1 < pDevice->ulRatio_State0)) ||
((pDevice->ulSQ3_State1 != 0) && (pDevice->ulSQ3_State0 != 0) && (pDevice->ulSQ3_State0 < pDevice->ulSQ3_State1))
) {
bScheduleCommand((void *) pDevice,
WLAN_CMD_CHANGE_ANTENNA,
NULL);
pDevice->TimerSQ3Tmax3.expires = RUN_AT(pDevice->byTMax3 * HZ);
pDevice->TimerSQ3Tmax2.expires = RUN_AT(pDevice->byTMax2 * HZ);
add_timer(&pDevice->TimerSQ3Tmax3);
add_timer(&pDevice->TimerSQ3Tmax2);
}
pDevice->byAntennaState = 0;
s_vClearSQ3Value(pDevice);
}
} //byAntennaState
}
/*+
*
* Description:
* Timer for SQ3 antenna diversity
*
* Parameters:
* In:
* pvSysSpec1
* hDeviceContext - Pointer to the adapter
* pvSysSpec2
* pvSysSpec3
* Out:
* none
*
* Return Value: none
*
-*/
void TimerSQ3CallBack(void *hDeviceContext)
{
PSDevice pDevice = (PSDevice)hDeviceContext;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"TimerSQ3CallBack...");
spin_lock_irq(&pDevice->lock);
bScheduleCommand((void *) pDevice, WLAN_CMD_CHANGE_ANTENNA, NULL);
pDevice->byAntennaState = 0;
s_vClearSQ3Value(pDevice);
pDevice->TimerSQ3Tmax3.expires = RUN_AT(pDevice->byTMax3 * HZ);
pDevice->TimerSQ3Tmax2.expires = RUN_AT(pDevice->byTMax2 * HZ);
add_timer(&pDevice->TimerSQ3Tmax3);
add_timer(&pDevice->TimerSQ3Tmax2);
spin_unlock_irq(&pDevice->lock);
return;
}
/*+
*
* Description:
* Timer for SQ3 antenna diversity
*
* Parameters:
* In:
* pvSysSpec1
* hDeviceContext - Pointer to the adapter
* pvSysSpec2
* pvSysSpec3
* Out:
* none
*
* Return Value: none
*
-*/
void TimerSQ3Tmax3CallBack(void *hDeviceContext)
{
PSDevice pDevice = (PSDevice)hDeviceContext;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"TimerSQ3Tmax3CallBack...");
spin_lock_irq(&pDevice->lock);
pDevice->ulRatio_State0 = s_ulGetRatio(pDevice);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"SQ3_State0 = [%08x]\n",(int)pDevice->ulRatio_State0);
s_vClearSQ3Value(pDevice);
if ( pDevice->byTMax == 0 ) {
pDevice->TimerSQ3Tmax3.expires = RUN_AT(pDevice->byTMax3 * HZ);
add_timer(&pDevice->TimerSQ3Tmax3);
spin_unlock_irq(&pDevice->lock);
return;
}
bScheduleCommand((void *) pDevice, WLAN_CMD_CHANGE_ANTENNA, NULL);
pDevice->byAntennaState = 1;
del_timer(&pDevice->TimerSQ3Tmax3);
del_timer(&pDevice->TimerSQ3Tmax2);
pDevice->TimerSQ3Tmax1.expires = RUN_AT(pDevice->byTMax * HZ);
add_timer(&pDevice->TimerSQ3Tmax1);
spin_unlock_irq(&pDevice->lock);
return;
}
void
BBvUpdatePreEDThreshold(
PSDevice pDevice,
BOOL bScanning)
{
switch(pDevice->byRFType)
{
case RF_AL2230:
case RF_AL2230S:
case RF_AIROHA7230:
//RobertYu:20060627, update new table
if( bScanning )
{ // need Max sensitivity //RSSI -69, -70,....
if(pDevice->byBBPreEDIndex == 0) break;
pDevice->byBBPreEDIndex = 0;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x00); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x30); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -69, -70, -71,...\n");
break;
}
if(pDevice->byBBPreEDRSSI <= 45) { // RSSI 0, -1,-2,....-45
if(pDevice->byBBPreEDIndex == 20) break;
pDevice->byBBPreEDIndex = 20;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0xFF); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x00); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI 0, -1,-2,..-45\n");
} else if(pDevice->byBBPreEDRSSI <= 46) { //RSSI -46
if(pDevice->byBBPreEDIndex == 19) break;
pDevice->byBBPreEDIndex = 19;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x1A); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x00); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -46\n");
} else if(pDevice->byBBPreEDRSSI <= 47) { //RSSI -47
if(pDevice->byBBPreEDIndex == 18) break;
pDevice->byBBPreEDIndex = 18;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x15); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x00); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -47\n");
} else if(pDevice->byBBPreEDRSSI <= 49) { //RSSI -48, -49
if(pDevice->byBBPreEDIndex == 17) break;
pDevice->byBBPreEDIndex = 17;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x0E); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x00); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -48,-49\n");
} else if(pDevice->byBBPreEDRSSI <= 51) { //RSSI -50, -51
if(pDevice->byBBPreEDIndex == 16) break;
pDevice->byBBPreEDIndex = 16;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x09); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x00); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -50,-51\n");
} else if(pDevice->byBBPreEDRSSI <= 53) { //RSSI -52, -53
if(pDevice->byBBPreEDIndex == 15) break;
pDevice->byBBPreEDIndex = 15;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x06); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x00); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -52,-53\n");
} else if(pDevice->byBBPreEDRSSI <= 55) { //RSSI -54, -55
if(pDevice->byBBPreEDIndex == 14) break;
pDevice->byBBPreEDIndex = 14;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x03); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x00); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -54,-55\n");
} else if(pDevice->byBBPreEDRSSI <= 56) { //RSSI -56
if(pDevice->byBBPreEDIndex == 13) break;
pDevice->byBBPreEDIndex = 13;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x02); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0xA0); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -56\n");
} else if(pDevice->byBBPreEDRSSI <= 57) { //RSSI -57
if(pDevice->byBBPreEDIndex == 12) break;
pDevice->byBBPreEDIndex = 12;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x02); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x20); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -57\n");
} else if(pDevice->byBBPreEDRSSI <= 58) { //RSSI -58
if(pDevice->byBBPreEDIndex == 11) break;
pDevice->byBBPreEDIndex = 11;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x01); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0xA0); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -58\n");
} else if(pDevice->byBBPreEDRSSI <= 59) { //RSSI -59
if(pDevice->byBBPreEDIndex == 10) break;
pDevice->byBBPreEDIndex = 10;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x01); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x54); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -59\n");
} else if(pDevice->byBBPreEDRSSI <= 60) { //RSSI -60
if(pDevice->byBBPreEDIndex == 9) break;
pDevice->byBBPreEDIndex = 9;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x01); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x18); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -60\n");
} else if(pDevice->byBBPreEDRSSI <= 61) { //RSSI -61
if(pDevice->byBBPreEDIndex == 8) break;
pDevice->byBBPreEDIndex = 8;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x00); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0xE3); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -61\n");
} else if(pDevice->byBBPreEDRSSI <= 62) { //RSSI -62
if(pDevice->byBBPreEDIndex == 7) break;
pDevice->byBBPreEDIndex = 7;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x00); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0xB9); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -62\n");
} else if(pDevice->byBBPreEDRSSI <= 63) { //RSSI -63
if(pDevice->byBBPreEDIndex == 6) break;
pDevice->byBBPreEDIndex = 6;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x00); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x93); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -63\n");
} else if(pDevice->byBBPreEDRSSI <= 64) { //RSSI -64
if(pDevice->byBBPreEDIndex == 5) break;
pDevice->byBBPreEDIndex = 5;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x00); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x79); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -64\n");
} else if(pDevice->byBBPreEDRSSI <= 65) { //RSSI -65
if(pDevice->byBBPreEDIndex == 4) break;
pDevice->byBBPreEDIndex = 4;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x00); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x62); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -65\n");
} else if(pDevice->byBBPreEDRSSI <= 66) { //RSSI -66
if(pDevice->byBBPreEDIndex == 3) break;
pDevice->byBBPreEDIndex = 3;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x00); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x51); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -66\n");
} else if(pDevice->byBBPreEDRSSI <= 67) { //RSSI -67
if(pDevice->byBBPreEDIndex == 2) break;
pDevice->byBBPreEDIndex = 2;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x00); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x43); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -67\n");
} else if(pDevice->byBBPreEDRSSI <= 68) { //RSSI -68
if(pDevice->byBBPreEDIndex == 1) break;
pDevice->byBBPreEDIndex = 1;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x00); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x36); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -68\n");
} else { //RSSI -69, -70,....
if(pDevice->byBBPreEDIndex == 0) break;
pDevice->byBBPreEDIndex = 0;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x00); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x30); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -69, -70,...\n");
}
break;
case RF_VT3226:
case RF_VT3226D0:
//RobertYu:20060627, update new table
if( bScanning )
{ // need Max sensitivity //RSSI -69, -70, ...
if(pDevice->byBBPreEDIndex == 0) break;
pDevice->byBBPreEDIndex = 0;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x00); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x24); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -69, -70,..\n");
break;
}
if(pDevice->byBBPreEDRSSI <= 41) { // RSSI 0, -1,-2,....-41
if(pDevice->byBBPreEDIndex == 22) break;
pDevice->byBBPreEDIndex = 22;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0xFF); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x00); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI 0, -1,-2,..-41\n");
} else if(pDevice->byBBPreEDRSSI <= 42) { //RSSI -42
if(pDevice->byBBPreEDIndex == 21) break;
pDevice->byBBPreEDIndex = 21;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x36); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x00); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -42\n");
} else if(pDevice->byBBPreEDRSSI <= 43) { //RSSI -43
if(pDevice->byBBPreEDIndex == 20) break;
pDevice->byBBPreEDIndex = 20;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x26); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x00); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -43\n");
} else if(pDevice->byBBPreEDRSSI <= 45) { //RSSI -44, -45
if(pDevice->byBBPreEDIndex == 19) break;
pDevice->byBBPreEDIndex = 19;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x18); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x00); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -44,-45\n");
} else if(pDevice->byBBPreEDRSSI <= 47) { //RSSI -46, -47
if(pDevice->byBBPreEDIndex == 18) break;
pDevice->byBBPreEDIndex = 18;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x11); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x00); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -46,-47\n");
} else if(pDevice->byBBPreEDRSSI <= 49) { //RSSI -48, -49
if(pDevice->byBBPreEDIndex == 17) break;
pDevice->byBBPreEDIndex = 17;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x0a); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x00); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -48,-49\n");
} else if(pDevice->byBBPreEDRSSI <= 51) { //RSSI -50, -51
if(pDevice->byBBPreEDIndex == 16) break;
pDevice->byBBPreEDIndex = 16;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x07); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x00); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -50,-51\n");
} else if(pDevice->byBBPreEDRSSI <= 53) { //RSSI -52, -53
if(pDevice->byBBPreEDIndex == 15) break;
pDevice->byBBPreEDIndex = 15;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x04); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x00); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -52,-53\n");
} else if(pDevice->byBBPreEDRSSI <= 55) { //RSSI -54, -55
if(pDevice->byBBPreEDIndex == 14) break;
pDevice->byBBPreEDIndex = 14;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x02); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0xC0); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -54,-55\n");
} else if(pDevice->byBBPreEDRSSI <= 56) { //RSSI -56
if(pDevice->byBBPreEDIndex == 13) break;
pDevice->byBBPreEDIndex = 13;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x02); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x30); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -56\n");
} else if(pDevice->byBBPreEDRSSI <= 57) { //RSSI -57
if(pDevice->byBBPreEDIndex == 12) break;
pDevice->byBBPreEDIndex = 12;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x01); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0xB0); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -57\n");
} else if(pDevice->byBBPreEDRSSI <= 58) { //RSSI -58
if(pDevice->byBBPreEDIndex == 11) break;
pDevice->byBBPreEDIndex = 11;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x01); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x70); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -58\n");
} else if(pDevice->byBBPreEDRSSI <= 59) { //RSSI -59
if(pDevice->byBBPreEDIndex == 10) break;
pDevice->byBBPreEDIndex = 10;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x01); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x30); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -59\n");
} else if(pDevice->byBBPreEDRSSI <= 60) { //RSSI -60
if(pDevice->byBBPreEDIndex == 9) break;
pDevice->byBBPreEDIndex = 9;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x00); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0xEA); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -60\n");
} else if(pDevice->byBBPreEDRSSI <= 61) { //RSSI -61
if(pDevice->byBBPreEDIndex == 8) break;
pDevice->byBBPreEDIndex = 8;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x00); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0xC0); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -61\n");
} else if(pDevice->byBBPreEDRSSI <= 62) { //RSSI -62
if(pDevice->byBBPreEDIndex == 7) break;
pDevice->byBBPreEDIndex = 7;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x00); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x9C); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -62\n");
} else if(pDevice->byBBPreEDRSSI <= 63) { //RSSI -63
if(pDevice->byBBPreEDIndex == 6) break;
pDevice->byBBPreEDIndex = 6;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x00); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x80); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -63\n");
} else if(pDevice->byBBPreEDRSSI <= 64) { //RSSI -64
if(pDevice->byBBPreEDIndex == 5) break;
pDevice->byBBPreEDIndex = 5;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x00); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x68); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -64\n");
} else if(pDevice->byBBPreEDRSSI <= 65) { //RSSI -65
if(pDevice->byBBPreEDIndex == 4) break;
pDevice->byBBPreEDIndex = 4;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x00); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x52); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -65\n");
} else if(pDevice->byBBPreEDRSSI <= 66) { //RSSI -66
if(pDevice->byBBPreEDIndex == 3) break;
pDevice->byBBPreEDIndex = 3;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x00); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x43); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -66\n");
} else if(pDevice->byBBPreEDRSSI <= 67) { //RSSI -67
if(pDevice->byBBPreEDIndex == 2) break;
pDevice->byBBPreEDIndex = 2;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x00); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x36); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -67\n");
} else if(pDevice->byBBPreEDRSSI <= 68) { //RSSI -68
if(pDevice->byBBPreEDIndex == 1) break;
pDevice->byBBPreEDIndex = 1;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x00); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x2D); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -68\n");
} else { //RSSI -69, -70, ...
if(pDevice->byBBPreEDIndex == 0) break;
pDevice->byBBPreEDIndex = 0;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x00); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x24); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -69, -70,..\n");
}
break;
case RF_VT3342A0: //RobertYu:20060627, testing table
if( bScanning )
{ // need Max sensitivity //RSSI -67, -68, ...
if(pDevice->byBBPreEDIndex == 0) break;
pDevice->byBBPreEDIndex = 0;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x00); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x38); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -67, -68,..\n");
break;
}
if(pDevice->byBBPreEDRSSI <= 41) { // RSSI 0, -1,-2,....-41
if(pDevice->byBBPreEDIndex == 20) break;
pDevice->byBBPreEDIndex = 20;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0xFF); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x00); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI 0, -1,-2,..-41\n");
} else if(pDevice->byBBPreEDRSSI <= 42) { //RSSI -42
if(pDevice->byBBPreEDIndex == 19) break;
pDevice->byBBPreEDIndex = 19;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x36); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x00); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -42\n");
} else if(pDevice->byBBPreEDRSSI <= 43) { //RSSI -43
if(pDevice->byBBPreEDIndex == 18) break;
pDevice->byBBPreEDIndex = 18;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x26); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x00); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -43\n");
} else if(pDevice->byBBPreEDRSSI <= 45) { //RSSI -44, -45
if(pDevice->byBBPreEDIndex == 17) break;
pDevice->byBBPreEDIndex = 17;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x18); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x00); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -44,-45\n");
} else if(pDevice->byBBPreEDRSSI <= 47) { //RSSI -46, -47
if(pDevice->byBBPreEDIndex == 16) break;
pDevice->byBBPreEDIndex = 16;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x11); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x00); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -46,-47\n");
} else if(pDevice->byBBPreEDRSSI <= 49) { //RSSI -48, -49
if(pDevice->byBBPreEDIndex == 15) break;
pDevice->byBBPreEDIndex = 15;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x0a); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x00); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -48,-49\n");
} else if(pDevice->byBBPreEDRSSI <= 51) { //RSSI -50, -51
if(pDevice->byBBPreEDIndex == 14) break;
pDevice->byBBPreEDIndex = 14;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x07); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x00); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -50,-51\n");
} else if(pDevice->byBBPreEDRSSI <= 53) { //RSSI -52, -53
if(pDevice->byBBPreEDIndex == 13) break;
pDevice->byBBPreEDIndex = 13;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x04); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x00); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -52,-53\n");
} else if(pDevice->byBBPreEDRSSI <= 55) { //RSSI -54, -55
if(pDevice->byBBPreEDIndex == 12) break;
pDevice->byBBPreEDIndex = 12;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x02); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0xC0); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -54,-55\n");
} else if(pDevice->byBBPreEDRSSI <= 56) { //RSSI -56
if(pDevice->byBBPreEDIndex == 11) break;
pDevice->byBBPreEDIndex = 11;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x02); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x30); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -56\n");
} else if(pDevice->byBBPreEDRSSI <= 57) { //RSSI -57
if(pDevice->byBBPreEDIndex == 10) break;
pDevice->byBBPreEDIndex = 10;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x01); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0xB0); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -57\n");
} else if(pDevice->byBBPreEDRSSI <= 58) { //RSSI -58
if(pDevice->byBBPreEDIndex == 9) break;
pDevice->byBBPreEDIndex = 9;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x01); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x70); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -58\n");
} else if(pDevice->byBBPreEDRSSI <= 59) { //RSSI -59
if(pDevice->byBBPreEDIndex == 8) break;
pDevice->byBBPreEDIndex = 8;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x01); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x30); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -59\n");
} else if(pDevice->byBBPreEDRSSI <= 60) { //RSSI -60
if(pDevice->byBBPreEDIndex == 7) break;
pDevice->byBBPreEDIndex = 7;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x00); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0xEA); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -60\n");
} else if(pDevice->byBBPreEDRSSI <= 61) { //RSSI -61
if(pDevice->byBBPreEDIndex == 6) break;
pDevice->byBBPreEDIndex = 6;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x00); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0xC0); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -61\n");
} else if(pDevice->byBBPreEDRSSI <= 62) { //RSSI -62
if(pDevice->byBBPreEDIndex == 5) break;
pDevice->byBBPreEDIndex = 5;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x00); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x9C); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -62\n");
} else if(pDevice->byBBPreEDRSSI <= 63) { //RSSI -63
if(pDevice->byBBPreEDIndex == 4) break;
pDevice->byBBPreEDIndex = 4;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x00); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x80); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -63\n");
} else if(pDevice->byBBPreEDRSSI <= 64) { //RSSI -64
if(pDevice->byBBPreEDIndex == 3) break;
pDevice->byBBPreEDIndex = 3;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x00); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x68); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -64\n");
} else if(pDevice->byBBPreEDRSSI <= 65) { //RSSI -65
if(pDevice->byBBPreEDIndex == 2) break;
pDevice->byBBPreEDIndex = 2;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x00); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x52); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -65\n");
} else if(pDevice->byBBPreEDRSSI <= 66) { //RSSI -66
if(pDevice->byBBPreEDIndex == 1) break;
pDevice->byBBPreEDIndex = 1;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x00); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x43); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -66\n");
} else { //RSSI -67, -68, ...
if(pDevice->byBBPreEDIndex == 0) break;
pDevice->byBBPreEDIndex = 0;
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xC9, 0x00); //CR201(0xC9)
ControlvWriteByte(pDevice, MESSAGE_REQUEST_BBREG, 0xCE, 0x38); //CR206(0xCE)
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" pDevice->byBBPreEDRSSI -67, -68,..\n");
}
break;
}
}
| gpl-2.0 |
AndroidGX/SimpleGX-KK-4.4.4_G901F | kernel/rtmutex-tester.c | 3696 | 8925 | /*
* RT-Mutex-tester: scriptable tester for rt mutexes
*
* started by Thomas Gleixner:
*
* Copyright (C) 2006, Timesys Corp., Thomas Gleixner <tglx@timesys.com>
*
*/
#include <linux/device.h>
#include <linux/kthread.h>
#include <linux/export.h>
#include <linux/sched.h>
#include <linux/sched/rt.h>
#include <linux/spinlock.h>
#include <linux/timer.h>
#include <linux/freezer.h>
#include <linux/stat.h>
#include "rtmutex.h"
#define MAX_RT_TEST_THREADS 8
#define MAX_RT_TEST_MUTEXES 8
static spinlock_t rttest_lock;
static atomic_t rttest_event;
struct test_thread_data {
int opcode;
int opdata;
int mutexes[MAX_RT_TEST_MUTEXES];
int event;
struct device dev;
};
static struct test_thread_data thread_data[MAX_RT_TEST_THREADS];
static struct task_struct *threads[MAX_RT_TEST_THREADS];
static struct rt_mutex mutexes[MAX_RT_TEST_MUTEXES];
enum test_opcodes {
RTTEST_NOP = 0,
RTTEST_SCHEDOT, /* 1 Sched other, data = nice */
RTTEST_SCHEDRT, /* 2 Sched fifo, data = prio */
RTTEST_LOCK, /* 3 Lock uninterruptible, data = lockindex */
RTTEST_LOCKNOWAIT, /* 4 Lock uninterruptible no wait in wakeup, data = lockindex */
RTTEST_LOCKINT, /* 5 Lock interruptible, data = lockindex */
RTTEST_LOCKINTNOWAIT, /* 6 Lock interruptible no wait in wakeup, data = lockindex */
RTTEST_LOCKCONT, /* 7 Continue locking after the wakeup delay */
RTTEST_UNLOCK, /* 8 Unlock, data = lockindex */
/* 9, 10 - reserved for BKL commemoration */
RTTEST_SIGNAL = 11, /* 11 Signal other test thread, data = thread id */
RTTEST_RESETEVENT = 98, /* 98 Reset event counter */
RTTEST_RESET = 99, /* 99 Reset all pending operations */
};
static int handle_op(struct test_thread_data *td, int lockwakeup)
{
int i, id, ret = -EINVAL;
switch(td->opcode) {
case RTTEST_NOP:
return 0;
case RTTEST_LOCKCONT:
td->mutexes[td->opdata] = 1;
td->event = atomic_add_return(1, &rttest_event);
return 0;
case RTTEST_RESET:
for (i = 0; i < MAX_RT_TEST_MUTEXES; i++) {
if (td->mutexes[i] == 4) {
rt_mutex_unlock(&mutexes[i]);
td->mutexes[i] = 0;
}
}
return 0;
case RTTEST_RESETEVENT:
atomic_set(&rttest_event, 0);
return 0;
default:
if (lockwakeup)
return ret;
}
switch(td->opcode) {
case RTTEST_LOCK:
case RTTEST_LOCKNOWAIT:
id = td->opdata;
if (id < 0 || id >= MAX_RT_TEST_MUTEXES)
return ret;
td->mutexes[id] = 1;
td->event = atomic_add_return(1, &rttest_event);
rt_mutex_lock(&mutexes[id]);
td->event = atomic_add_return(1, &rttest_event);
td->mutexes[id] = 4;
return 0;
case RTTEST_LOCKINT:
case RTTEST_LOCKINTNOWAIT:
id = td->opdata;
if (id < 0 || id >= MAX_RT_TEST_MUTEXES)
return ret;
td->mutexes[id] = 1;
td->event = atomic_add_return(1, &rttest_event);
ret = rt_mutex_lock_interruptible(&mutexes[id], 0);
td->event = atomic_add_return(1, &rttest_event);
td->mutexes[id] = ret ? 0 : 4;
return ret ? -EINTR : 0;
case RTTEST_UNLOCK:
id = td->opdata;
if (id < 0 || id >= MAX_RT_TEST_MUTEXES || td->mutexes[id] != 4)
return ret;
td->event = atomic_add_return(1, &rttest_event);
rt_mutex_unlock(&mutexes[id]);
td->event = atomic_add_return(1, &rttest_event);
td->mutexes[id] = 0;
return 0;
default:
break;
}
return ret;
}
/*
* Schedule replacement for rtsem_down(). Only called for threads with
* PF_MUTEX_TESTER set.
*
* This allows us to have finegrained control over the event flow.
*
*/
void schedule_rt_mutex_test(struct rt_mutex *mutex)
{
int tid, op, dat;
struct test_thread_data *td;
/* We have to lookup the task */
for (tid = 0; tid < MAX_RT_TEST_THREADS; tid++) {
if (threads[tid] == current)
break;
}
BUG_ON(tid == MAX_RT_TEST_THREADS);
td = &thread_data[tid];
op = td->opcode;
dat = td->opdata;
switch (op) {
case RTTEST_LOCK:
case RTTEST_LOCKINT:
case RTTEST_LOCKNOWAIT:
case RTTEST_LOCKINTNOWAIT:
if (mutex != &mutexes[dat])
break;
if (td->mutexes[dat] != 1)
break;
td->mutexes[dat] = 2;
td->event = atomic_add_return(1, &rttest_event);
break;
default:
break;
}
schedule();
switch (op) {
case RTTEST_LOCK:
case RTTEST_LOCKINT:
if (mutex != &mutexes[dat])
return;
if (td->mutexes[dat] != 2)
return;
td->mutexes[dat] = 3;
td->event = atomic_add_return(1, &rttest_event);
break;
case RTTEST_LOCKNOWAIT:
case RTTEST_LOCKINTNOWAIT:
if (mutex != &mutexes[dat])
return;
if (td->mutexes[dat] != 2)
return;
td->mutexes[dat] = 1;
td->event = atomic_add_return(1, &rttest_event);
return;
default:
return;
}
td->opcode = 0;
for (;;) {
set_current_state(TASK_INTERRUPTIBLE);
if (td->opcode > 0) {
int ret;
set_current_state(TASK_RUNNING);
ret = handle_op(td, 1);
set_current_state(TASK_INTERRUPTIBLE);
if (td->opcode == RTTEST_LOCKCONT)
break;
td->opcode = ret;
}
/* Wait for the next command to be executed */
schedule();
}
/* Restore previous command and data */
td->opcode = op;
td->opdata = dat;
}
static int test_func(void *data)
{
struct test_thread_data *td = data;
int ret;
current->flags |= PF_MUTEX_TESTER;
set_freezable();
allow_signal(SIGHUP);
for(;;) {
set_current_state(TASK_INTERRUPTIBLE);
if (td->opcode > 0) {
set_current_state(TASK_RUNNING);
ret = handle_op(td, 0);
set_current_state(TASK_INTERRUPTIBLE);
td->opcode = ret;
}
/* Wait for the next command to be executed */
schedule();
try_to_freeze();
if (signal_pending(current))
flush_signals(current);
if(kthread_should_stop())
break;
}
return 0;
}
/**
* sysfs_test_command - interface for test commands
* @dev: thread reference
* @buf: command for actual step
* @count: length of buffer
*
* command syntax:
*
* opcode:data
*/
static ssize_t sysfs_test_command(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct sched_param schedpar;
struct test_thread_data *td;
char cmdbuf[32];
int op, dat, tid, ret;
td = container_of(dev, struct test_thread_data, dev);
tid = td->dev.id;
/* strings from sysfs write are not 0 terminated! */
if (count >= sizeof(cmdbuf))
return -EINVAL;
/* strip of \n: */
if (buf[count-1] == '\n')
count--;
if (count < 1)
return -EINVAL;
memcpy(cmdbuf, buf, count);
cmdbuf[count] = 0;
if (sscanf(cmdbuf, "%d:%d", &op, &dat) != 2)
return -EINVAL;
switch (op) {
case RTTEST_SCHEDOT:
schedpar.sched_priority = 0;
ret = sched_setscheduler(threads[tid], SCHED_NORMAL, &schedpar);
if (ret)
return ret;
set_user_nice(current, 0);
break;
case RTTEST_SCHEDRT:
schedpar.sched_priority = dat;
ret = sched_setscheduler(threads[tid], SCHED_FIFO, &schedpar);
if (ret)
return ret;
break;
case RTTEST_SIGNAL:
send_sig(SIGHUP, threads[tid], 0);
break;
default:
if (td->opcode > 0)
return -EBUSY;
td->opdata = dat;
td->opcode = op;
wake_up_process(threads[tid]);
}
return count;
}
/**
* sysfs_test_status - sysfs interface for rt tester
* @dev: thread to query
* @buf: char buffer to be filled with thread status info
*/
static ssize_t sysfs_test_status(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct test_thread_data *td;
struct task_struct *tsk;
char *curr = buf;
int i;
td = container_of(dev, struct test_thread_data, dev);
tsk = threads[td->dev.id];
spin_lock(&rttest_lock);
curr += sprintf(curr,
"O: %4d, E:%8d, S: 0x%08lx, P: %4d, N: %4d, B: %p, M:",
td->opcode, td->event, tsk->state,
(MAX_RT_PRIO - 1) - tsk->prio,
(MAX_RT_PRIO - 1) - tsk->normal_prio,
tsk->pi_blocked_on);
for (i = MAX_RT_TEST_MUTEXES - 1; i >=0 ; i--)
curr += sprintf(curr, "%d", td->mutexes[i]);
spin_unlock(&rttest_lock);
curr += sprintf(curr, ", T: %p, R: %p\n", tsk,
mutexes[td->dev.id].owner);
return curr - buf;
}
static DEVICE_ATTR(status, S_IRUSR, sysfs_test_status, NULL);
static DEVICE_ATTR(command, S_IWUSR, NULL, sysfs_test_command);
static struct bus_type rttest_subsys = {
.name = "rttest",
.dev_name = "rttest",
};
static int init_test_thread(int id)
{
thread_data[id].dev.bus = &rttest_subsys;
thread_data[id].dev.id = id;
threads[id] = kthread_run(test_func, &thread_data[id], "rt-test-%d", id);
if (IS_ERR(threads[id]))
return PTR_ERR(threads[id]);
return device_register(&thread_data[id].dev);
}
static int init_rttest(void)
{
int ret, i;
spin_lock_init(&rttest_lock);
for (i = 0; i < MAX_RT_TEST_MUTEXES; i++)
rt_mutex_init(&mutexes[i]);
ret = subsys_system_register(&rttest_subsys, NULL);
if (ret)
return ret;
for (i = 0; i < MAX_RT_TEST_THREADS; i++) {
ret = init_test_thread(i);
if (ret)
break;
ret = device_create_file(&thread_data[i].dev, &dev_attr_status);
if (ret)
break;
ret = device_create_file(&thread_data[i].dev, &dev_attr_command);
if (ret)
break;
}
printk("Initializing RT-Tester: %s\n", ret ? "Failed" : "OK" );
return ret;
}
device_initcall(init_rttest);
| gpl-2.0 |
Zoldyck07/Evolution | drivers/video/backlight/da9052_bl.c | 4976 | 4280 | /*
* Backlight Driver for Dialog DA9052 PMICs
*
* Copyright(c) 2012 Dialog Semiconductor Ltd.
*
* Author: David Dajun Chen <dchen@diasemi.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/backlight.h>
#include <linux/delay.h>
#include <linux/fb.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/mfd/da9052/da9052.h>
#include <linux/mfd/da9052/reg.h>
#define DA9052_MAX_BRIGHTNESS 0xFF
enum {
DA9052_WLEDS_OFF,
DA9052_WLEDS_ON,
};
enum {
DA9052_TYPE_WLED1,
DA9052_TYPE_WLED2,
DA9052_TYPE_WLED3,
};
static unsigned char wled_bank[] = {
DA9052_LED1_CONF_REG,
DA9052_LED2_CONF_REG,
DA9052_LED3_CONF_REG,
};
struct da9052_bl {
struct da9052 *da9052;
uint brightness;
uint state;
uint led_reg;
};
static int da9052_adjust_wled_brightness(struct da9052_bl *wleds)
{
unsigned char boost_en;
unsigned char i_sink;
int ret;
boost_en = 0x3F;
i_sink = 0xFF;
if (wleds->state == DA9052_WLEDS_OFF) {
boost_en = 0x00;
i_sink = 0x00;
}
ret = da9052_reg_write(wleds->da9052, DA9052_BOOST_REG, boost_en);
if (ret < 0)
return ret;
ret = da9052_reg_write(wleds->da9052, DA9052_LED_CONT_REG, i_sink);
if (ret < 0)
return ret;
ret = da9052_reg_write(wleds->da9052, wled_bank[wleds->led_reg], 0x0);
if (ret < 0)
return ret;
msleep(10);
if (wleds->brightness) {
ret = da9052_reg_write(wleds->da9052, wled_bank[wleds->led_reg],
wleds->brightness);
if (ret < 0)
return ret;
}
return 0;
}
static int da9052_backlight_update_status(struct backlight_device *bl)
{
int brightness = bl->props.brightness;
struct da9052_bl *wleds = bl_get_data(bl);
wleds->brightness = brightness;
wleds->state = DA9052_WLEDS_ON;
return da9052_adjust_wled_brightness(wleds);
}
static int da9052_backlight_get_brightness(struct backlight_device *bl)
{
struct da9052_bl *wleds = bl_get_data(bl);
return wleds->brightness;
}
static const struct backlight_ops da9052_backlight_ops = {
.update_status = da9052_backlight_update_status,
.get_brightness = da9052_backlight_get_brightness,
};
static int da9052_backlight_probe(struct platform_device *pdev)
{
struct backlight_device *bl;
struct backlight_properties props;
struct da9052_bl *wleds;
wleds = devm_kzalloc(&pdev->dev, sizeof(struct da9052_bl), GFP_KERNEL);
if (!wleds)
return -ENOMEM;
wleds->da9052 = dev_get_drvdata(pdev->dev.parent);
wleds->brightness = 0;
wleds->led_reg = platform_get_device_id(pdev)->driver_data;
wleds->state = DA9052_WLEDS_OFF;
props.type = BACKLIGHT_RAW;
props.max_brightness = DA9052_MAX_BRIGHTNESS;
bl = backlight_device_register(pdev->name, wleds->da9052->dev, wleds,
&da9052_backlight_ops, &props);
if (IS_ERR(bl)) {
dev_err(&pdev->dev, "Failed to register backlight\n");
devm_kfree(&pdev->dev, wleds);
return PTR_ERR(bl);
}
bl->props.max_brightness = DA9052_MAX_BRIGHTNESS;
bl->props.brightness = 0;
platform_set_drvdata(pdev, bl);
return da9052_adjust_wled_brightness(wleds);
}
static int da9052_backlight_remove(struct platform_device *pdev)
{
struct backlight_device *bl = platform_get_drvdata(pdev);
struct da9052_bl *wleds = bl_get_data(bl);
wleds->brightness = 0;
wleds->state = DA9052_WLEDS_OFF;
da9052_adjust_wled_brightness(wleds);
backlight_device_unregister(bl);
devm_kfree(&pdev->dev, wleds);
return 0;
}
static struct platform_device_id da9052_wled_ids[] = {
{
.name = "da9052-wled1",
.driver_data = DA9052_TYPE_WLED1,
},
{
.name = "da9052-wled2",
.driver_data = DA9052_TYPE_WLED2,
},
{
.name = "da9052-wled3",
.driver_data = DA9052_TYPE_WLED3,
},
};
static struct platform_driver da9052_wled_driver = {
.probe = da9052_backlight_probe,
.remove = da9052_backlight_remove,
.id_table = da9052_wled_ids,
.driver = {
.name = "da9052-wled",
.owner = THIS_MODULE,
},
};
module_platform_driver(da9052_wled_driver);
MODULE_AUTHOR("David Dajun Chen <dchen@diasemi.com>");
MODULE_DESCRIPTION("Backlight driver for DA9052 PMIC");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:da9052-backlight");
| gpl-2.0 |
touchpro/android_kernel_lge_msm8226 | fs/jbd/recovery.c | 4976 | 14708 | /*
* linux/fs/jbd/recovery.c
*
* Written by Stephen C. Tweedie <sct@redhat.com>, 1999
*
* Copyright 1999-2000 Red Hat Software --- All Rights Reserved
*
* This file is part of the Linux kernel and is made available under
* the terms of the GNU General Public License, version 2, or at your
* option, any later version, incorporated herein by reference.
*
* Journal recovery routines for the generic filesystem journaling code;
* part of the ext2fs journaling system.
*/
#ifndef __KERNEL__
#include "jfs_user.h"
#else
#include <linux/time.h>
#include <linux/fs.h>
#include <linux/jbd.h>
#include <linux/errno.h>
#include <linux/blkdev.h>
#endif
/*
* Maintain information about the progress of the recovery job, so that
* the different passes can carry information between them.
*/
struct recovery_info
{
tid_t start_transaction;
tid_t end_transaction;
int nr_replays;
int nr_revokes;
int nr_revoke_hits;
};
enum passtype {PASS_SCAN, PASS_REVOKE, PASS_REPLAY};
static int do_one_pass(journal_t *journal,
struct recovery_info *info, enum passtype pass);
static int scan_revoke_records(journal_t *, struct buffer_head *,
tid_t, struct recovery_info *);
#ifdef __KERNEL__
/* Release readahead buffers after use */
static void journal_brelse_array(struct buffer_head *b[], int n)
{
while (--n >= 0)
brelse (b[n]);
}
/*
* When reading from the journal, we are going through the block device
* layer directly and so there is no readahead being done for us. We
* need to implement any readahead ourselves if we want it to happen at
* all. Recovery is basically one long sequential read, so make sure we
* do the IO in reasonably large chunks.
*
* This is not so critical that we need to be enormously clever about
* the readahead size, though. 128K is a purely arbitrary, good-enough
* fixed value.
*/
#define MAXBUF 8
static int do_readahead(journal_t *journal, unsigned int start)
{
int err;
unsigned int max, nbufs, next;
unsigned int blocknr;
struct buffer_head *bh;
struct buffer_head * bufs[MAXBUF];
/* Do up to 128K of readahead */
max = start + (128 * 1024 / journal->j_blocksize);
if (max > journal->j_maxlen)
max = journal->j_maxlen;
/* Do the readahead itself. We'll submit MAXBUF buffer_heads at
* a time to the block device IO layer. */
nbufs = 0;
for (next = start; next < max; next++) {
err = journal_bmap(journal, next, &blocknr);
if (err) {
printk (KERN_ERR "JBD: bad block at offset %u\n",
next);
goto failed;
}
bh = __getblk(journal->j_dev, blocknr, journal->j_blocksize);
if (!bh) {
err = -ENOMEM;
goto failed;
}
if (!buffer_uptodate(bh) && !buffer_locked(bh)) {
bufs[nbufs++] = bh;
if (nbufs == MAXBUF) {
ll_rw_block(READ, nbufs, bufs);
journal_brelse_array(bufs, nbufs);
nbufs = 0;
}
} else
brelse(bh);
}
if (nbufs)
ll_rw_block(READ, nbufs, bufs);
err = 0;
failed:
if (nbufs)
journal_brelse_array(bufs, nbufs);
return err;
}
#endif /* __KERNEL__ */
/*
* Read a block from the journal
*/
static int jread(struct buffer_head **bhp, journal_t *journal,
unsigned int offset)
{
int err;
unsigned int blocknr;
struct buffer_head *bh;
*bhp = NULL;
if (offset >= journal->j_maxlen) {
printk(KERN_ERR "JBD: corrupted journal superblock\n");
return -EIO;
}
err = journal_bmap(journal, offset, &blocknr);
if (err) {
printk (KERN_ERR "JBD: bad block at offset %u\n",
offset);
return err;
}
bh = __getblk(journal->j_dev, blocknr, journal->j_blocksize);
if (!bh)
return -ENOMEM;
if (!buffer_uptodate(bh)) {
/* If this is a brand new buffer, start readahead.
Otherwise, we assume we are already reading it. */
if (!buffer_req(bh))
do_readahead(journal, offset);
wait_on_buffer(bh);
}
if (!buffer_uptodate(bh)) {
printk (KERN_ERR "JBD: Failed to read block at offset %u\n",
offset);
brelse(bh);
return -EIO;
}
*bhp = bh;
return 0;
}
/*
* Count the number of in-use tags in a journal descriptor block.
*/
static int count_tags(struct buffer_head *bh, int size)
{
char * tagp;
journal_block_tag_t * tag;
int nr = 0;
tagp = &bh->b_data[sizeof(journal_header_t)];
while ((tagp - bh->b_data + sizeof(journal_block_tag_t)) <= size) {
tag = (journal_block_tag_t *) tagp;
nr++;
tagp += sizeof(journal_block_tag_t);
if (!(tag->t_flags & cpu_to_be32(JFS_FLAG_SAME_UUID)))
tagp += 16;
if (tag->t_flags & cpu_to_be32(JFS_FLAG_LAST_TAG))
break;
}
return nr;
}
/* Make sure we wrap around the log correctly! */
#define wrap(journal, var) \
do { \
if (var >= (journal)->j_last) \
var -= ((journal)->j_last - (journal)->j_first); \
} while (0)
/**
* journal_recover - recovers a on-disk journal
* @journal: the journal to recover
*
* The primary function for recovering the log contents when mounting a
* journaled device.
*
* Recovery is done in three passes. In the first pass, we look for the
* end of the log. In the second, we assemble the list of revoke
* blocks. In the third and final pass, we replay any un-revoked blocks
* in the log.
*/
int journal_recover(journal_t *journal)
{
int err, err2;
journal_superblock_t * sb;
struct recovery_info info;
memset(&info, 0, sizeof(info));
sb = journal->j_superblock;
/*
* The journal superblock's s_start field (the current log head)
* is always zero if, and only if, the journal was cleanly
* unmounted.
*/
if (!sb->s_start) {
jbd_debug(1, "No recovery required, last transaction %d\n",
be32_to_cpu(sb->s_sequence));
journal->j_transaction_sequence = be32_to_cpu(sb->s_sequence) + 1;
return 0;
}
err = do_one_pass(journal, &info, PASS_SCAN);
if (!err)
err = do_one_pass(journal, &info, PASS_REVOKE);
if (!err)
err = do_one_pass(journal, &info, PASS_REPLAY);
jbd_debug(1, "JBD: recovery, exit status %d, "
"recovered transactions %u to %u\n",
err, info.start_transaction, info.end_transaction);
jbd_debug(1, "JBD: Replayed %d and revoked %d/%d blocks\n",
info.nr_replays, info.nr_revoke_hits, info.nr_revokes);
/* Restart the log at the next transaction ID, thus invalidating
* any existing commit records in the log. */
journal->j_transaction_sequence = ++info.end_transaction;
journal_clear_revoke(journal);
err2 = sync_blockdev(journal->j_fs_dev);
if (!err)
err = err2;
/* Flush disk caches to get replayed data on the permanent storage */
if (journal->j_flags & JFS_BARRIER)
blkdev_issue_flush(journal->j_fs_dev, GFP_KERNEL, NULL);
return err;
}
/**
* journal_skip_recovery - Start journal and wipe exiting records
* @journal: journal to startup
*
* Locate any valid recovery information from the journal and set up the
* journal structures in memory to ignore it (presumably because the
* caller has evidence that it is out of date).
* This function does'nt appear to be exorted..
*
* We perform one pass over the journal to allow us to tell the user how
* much recovery information is being erased, and to let us initialise
* the journal transaction sequence numbers to the next unused ID.
*/
int journal_skip_recovery(journal_t *journal)
{
int err;
struct recovery_info info;
memset (&info, 0, sizeof(info));
err = do_one_pass(journal, &info, PASS_SCAN);
if (err) {
printk(KERN_ERR "JBD: error %d scanning journal\n", err);
++journal->j_transaction_sequence;
} else {
#ifdef CONFIG_JBD_DEBUG
int dropped = info.end_transaction -
be32_to_cpu(journal->j_superblock->s_sequence);
jbd_debug(1,
"JBD: ignoring %d transaction%s from the journal.\n",
dropped, (dropped == 1) ? "" : "s");
#endif
journal->j_transaction_sequence = ++info.end_transaction;
}
journal->j_tail = 0;
return err;
}
static int do_one_pass(journal_t *journal,
struct recovery_info *info, enum passtype pass)
{
unsigned int first_commit_ID, next_commit_ID;
unsigned int next_log_block;
int err, success = 0;
journal_superblock_t * sb;
journal_header_t * tmp;
struct buffer_head * bh;
unsigned int sequence;
int blocktype;
/*
* First thing is to establish what we expect to find in the log
* (in terms of transaction IDs), and where (in terms of log
* block offsets): query the superblock.
*/
sb = journal->j_superblock;
next_commit_ID = be32_to_cpu(sb->s_sequence);
next_log_block = be32_to_cpu(sb->s_start);
first_commit_ID = next_commit_ID;
if (pass == PASS_SCAN)
info->start_transaction = first_commit_ID;
jbd_debug(1, "Starting recovery pass %d\n", pass);
/*
* Now we walk through the log, transaction by transaction,
* making sure that each transaction has a commit block in the
* expected place. Each complete transaction gets replayed back
* into the main filesystem.
*/
while (1) {
int flags;
char * tagp;
journal_block_tag_t * tag;
struct buffer_head * obh;
struct buffer_head * nbh;
cond_resched();
/* If we already know where to stop the log traversal,
* check right now that we haven't gone past the end of
* the log. */
if (pass != PASS_SCAN)
if (tid_geq(next_commit_ID, info->end_transaction))
break;
jbd_debug(2, "Scanning for sequence ID %u at %u/%u\n",
next_commit_ID, next_log_block, journal->j_last);
/* Skip over each chunk of the transaction looking
* either the next descriptor block or the final commit
* record. */
jbd_debug(3, "JBD: checking block %u\n", next_log_block);
err = jread(&bh, journal, next_log_block);
if (err)
goto failed;
next_log_block++;
wrap(journal, next_log_block);
/* What kind of buffer is it?
*
* If it is a descriptor block, check that it has the
* expected sequence number. Otherwise, we're all done
* here. */
tmp = (journal_header_t *)bh->b_data;
if (tmp->h_magic != cpu_to_be32(JFS_MAGIC_NUMBER)) {
brelse(bh);
break;
}
blocktype = be32_to_cpu(tmp->h_blocktype);
sequence = be32_to_cpu(tmp->h_sequence);
jbd_debug(3, "Found magic %d, sequence %d\n",
blocktype, sequence);
if (sequence != next_commit_ID) {
brelse(bh);
break;
}
/* OK, we have a valid descriptor block which matches
* all of the sequence number checks. What are we going
* to do with it? That depends on the pass... */
switch(blocktype) {
case JFS_DESCRIPTOR_BLOCK:
/* If it is a valid descriptor block, replay it
* in pass REPLAY; otherwise, just skip over the
* blocks it describes. */
if (pass != PASS_REPLAY) {
next_log_block +=
count_tags(bh, journal->j_blocksize);
wrap(journal, next_log_block);
brelse(bh);
continue;
}
/* A descriptor block: we can now write all of
* the data blocks. Yay, useful work is finally
* getting done here! */
tagp = &bh->b_data[sizeof(journal_header_t)];
while ((tagp - bh->b_data +sizeof(journal_block_tag_t))
<= journal->j_blocksize) {
unsigned int io_block;
tag = (journal_block_tag_t *) tagp;
flags = be32_to_cpu(tag->t_flags);
io_block = next_log_block++;
wrap(journal, next_log_block);
err = jread(&obh, journal, io_block);
if (err) {
/* Recover what we can, but
* report failure at the end. */
success = err;
printk (KERN_ERR
"JBD: IO error %d recovering "
"block %u in log\n",
err, io_block);
} else {
unsigned int blocknr;
J_ASSERT(obh != NULL);
blocknr = be32_to_cpu(tag->t_blocknr);
/* If the block has been
* revoked, then we're all done
* here. */
if (journal_test_revoke
(journal, blocknr,
next_commit_ID)) {
brelse(obh);
++info->nr_revoke_hits;
goto skip_write;
}
/* Find a buffer for the new
* data being restored */
nbh = __getblk(journal->j_fs_dev,
blocknr,
journal->j_blocksize);
if (nbh == NULL) {
printk(KERN_ERR
"JBD: Out of memory "
"during recovery.\n");
err = -ENOMEM;
brelse(bh);
brelse(obh);
goto failed;
}
lock_buffer(nbh);
memcpy(nbh->b_data, obh->b_data,
journal->j_blocksize);
if (flags & JFS_FLAG_ESCAPE) {
*((__be32 *)nbh->b_data) =
cpu_to_be32(JFS_MAGIC_NUMBER);
}
BUFFER_TRACE(nbh, "marking dirty");
set_buffer_uptodate(nbh);
mark_buffer_dirty(nbh);
BUFFER_TRACE(nbh, "marking uptodate");
++info->nr_replays;
/* ll_rw_block(WRITE, 1, &nbh); */
unlock_buffer(nbh);
brelse(obh);
brelse(nbh);
}
skip_write:
tagp += sizeof(journal_block_tag_t);
if (!(flags & JFS_FLAG_SAME_UUID))
tagp += 16;
if (flags & JFS_FLAG_LAST_TAG)
break;
}
brelse(bh);
continue;
case JFS_COMMIT_BLOCK:
/* Found an expected commit block: not much to
* do other than move on to the next sequence
* number. */
brelse(bh);
next_commit_ID++;
continue;
case JFS_REVOKE_BLOCK:
/* If we aren't in the REVOKE pass, then we can
* just skip over this block. */
if (pass != PASS_REVOKE) {
brelse(bh);
continue;
}
err = scan_revoke_records(journal, bh,
next_commit_ID, info);
brelse(bh);
if (err)
goto failed;
continue;
default:
jbd_debug(3, "Unrecognised magic %d, end of scan.\n",
blocktype);
brelse(bh);
goto done;
}
}
done:
/*
* We broke out of the log scan loop: either we came to the
* known end of the log or we found an unexpected block in the
* log. If the latter happened, then we know that the "current"
* transaction marks the end of the valid log.
*/
if (pass == PASS_SCAN)
info->end_transaction = next_commit_ID;
else {
/* It's really bad news if different passes end up at
* different places (but possible due to IO errors). */
if (info->end_transaction != next_commit_ID) {
printk (KERN_ERR "JBD: recovery pass %d ended at "
"transaction %u, expected %u\n",
pass, next_commit_ID, info->end_transaction);
if (!success)
success = -EIO;
}
}
return success;
failed:
return err;
}
/* Scan a revoke record, marking all blocks mentioned as revoked. */
static int scan_revoke_records(journal_t *journal, struct buffer_head *bh,
tid_t sequence, struct recovery_info *info)
{
journal_revoke_header_t *header;
int offset, max;
header = (journal_revoke_header_t *) bh->b_data;
offset = sizeof(journal_revoke_header_t);
max = be32_to_cpu(header->r_count);
while (offset < max) {
unsigned int blocknr;
int err;
blocknr = be32_to_cpu(* ((__be32 *) (bh->b_data+offset)));
offset += 4;
err = journal_set_revoke(journal, blocknr, sequence);
if (err)
return err;
++info->nr_revokes;
}
return 0;
}
| gpl-2.0 |
jeehyn/NewWorld_kernel_ef52 | drivers/uwb/reset.c | 5232 | 11232 | /*
* Ultra Wide Band
* UWB basic command support and radio reset
*
* Copyright (C) 2005-2006 Intel Corporation
* Inaky Perez-Gonzalez <inaky.perez-gonzalez@intel.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*
*
* FIXME:
*
* - docs
*
* - Now we are serializing (using the uwb_dev->mutex) the command
* execution; it should be parallelized as much as possible some
* day.
*/
#include <linux/kernel.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/export.h>
#include "uwb-internal.h"
/**
* Command result codes (WUSB1.0[T8-69])
*/
static
const char *__strerror[] = {
"success",
"failure",
"hardware failure",
"no more slots",
"beacon is too large",
"invalid parameter",
"unsupported power level",
"time out (wa) or invalid ie data (whci)",
"beacon size exceeded",
"cancelled",
"invalid state",
"invalid size",
"ack not received",
"no more asie notification",
};
/** Return a string matching the given error code */
const char *uwb_rc_strerror(unsigned code)
{
if (code == 255)
return "time out";
if (code >= ARRAY_SIZE(__strerror))
return "unknown error";
return __strerror[code];
}
int uwb_rc_cmd_async(struct uwb_rc *rc, const char *cmd_name,
struct uwb_rccb *cmd, size_t cmd_size,
u8 expected_type, u16 expected_event,
uwb_rc_cmd_cb_f cb, void *arg)
{
struct device *dev = &rc->uwb_dev.dev;
struct uwb_rc_neh *neh;
int needtofree = 0;
int result;
uwb_dev_lock(&rc->uwb_dev); /* Protect against rc->priv being removed */
if (rc->priv == NULL) {
uwb_dev_unlock(&rc->uwb_dev);
return -ESHUTDOWN;
}
if (rc->filter_cmd) {
needtofree = rc->filter_cmd(rc, &cmd, &cmd_size);
if (needtofree < 0 && needtofree != -ENOANO) {
dev_err(dev, "%s: filter error: %d\n",
cmd_name, needtofree);
uwb_dev_unlock(&rc->uwb_dev);
return needtofree;
}
}
neh = uwb_rc_neh_add(rc, cmd, expected_type, expected_event, cb, arg);
if (IS_ERR(neh)) {
result = PTR_ERR(neh);
goto out;
}
result = rc->cmd(rc, cmd, cmd_size);
uwb_dev_unlock(&rc->uwb_dev);
if (result < 0)
uwb_rc_neh_rm(rc, neh);
else
uwb_rc_neh_arm(rc, neh);
uwb_rc_neh_put(neh);
out:
if (needtofree == 1)
kfree(cmd);
return result < 0 ? result : 0;
}
EXPORT_SYMBOL_GPL(uwb_rc_cmd_async);
struct uwb_rc_cmd_done_params {
struct completion completion;
struct uwb_rceb *reply;
ssize_t reply_size;
};
static void uwb_rc_cmd_done(struct uwb_rc *rc, void *arg,
struct uwb_rceb *reply, ssize_t reply_size)
{
struct uwb_rc_cmd_done_params *p = (struct uwb_rc_cmd_done_params *)arg;
if (reply_size > 0) {
if (p->reply)
reply_size = min(p->reply_size, reply_size);
else
p->reply = kmalloc(reply_size, GFP_ATOMIC);
if (p->reply)
memcpy(p->reply, reply, reply_size);
else
reply_size = -ENOMEM;
}
p->reply_size = reply_size;
complete(&p->completion);
}
/**
* Generic function for issuing commands to the Radio Control Interface
*
* @rc: UWB Radio Control descriptor
* @cmd_name: Name of the command being issued (for error messages)
* @cmd: Pointer to rccb structure containing the command;
* normally you embed this structure as the first member of
* the full command structure.
* @cmd_size: Size of the whole command buffer pointed to by @cmd.
* @reply: Pointer to where to store the reply
* @reply_size: @reply's size
* @expected_type: Expected type in the return event
* @expected_event: Expected event code in the return event
* @preply: Here a pointer to where the event data is received will
* be stored. Once done with the data, free with kfree().
*
* This function is generic; it works for commands that return a fixed
* and known size or for commands that return a variable amount of data.
*
* If a buffer is provided, that is used, although it could be chopped
* to the maximum size of the buffer. If the buffer is NULL, then one
* be allocated in *preply with the whole contents of the reply.
*
* @rc needs to be referenced
*/
static
ssize_t __uwb_rc_cmd(struct uwb_rc *rc, const char *cmd_name,
struct uwb_rccb *cmd, size_t cmd_size,
struct uwb_rceb *reply, size_t reply_size,
u8 expected_type, u16 expected_event,
struct uwb_rceb **preply)
{
ssize_t result = 0;
struct device *dev = &rc->uwb_dev.dev;
struct uwb_rc_cmd_done_params params;
init_completion(¶ms.completion);
params.reply = reply;
params.reply_size = reply_size;
result = uwb_rc_cmd_async(rc, cmd_name, cmd, cmd_size,
expected_type, expected_event,
uwb_rc_cmd_done, ¶ms);
if (result)
return result;
wait_for_completion(¶ms.completion);
if (preply)
*preply = params.reply;
if (params.reply_size < 0)
dev_err(dev, "%s: confirmation event 0x%02x/%04x/%02x "
"reception failed: %d\n", cmd_name,
expected_type, expected_event, cmd->bCommandContext,
(int)params.reply_size);
return params.reply_size;
}
/**
* Generic function for issuing commands to the Radio Control Interface
*
* @rc: UWB Radio Control descriptor
* @cmd_name: Name of the command being issued (for error messages)
* @cmd: Pointer to rccb structure containing the command;
* normally you embed this structure as the first member of
* the full command structure.
* @cmd_size: Size of the whole command buffer pointed to by @cmd.
* @reply: Pointer to the beginning of the confirmation event
* buffer. Normally bigger than an 'struct hwarc_rceb'.
* You need to fill out reply->bEventType and reply->wEvent (in
* cpu order) as the function will use them to verify the
* confirmation event.
* @reply_size: Size of the reply buffer
*
* The function checks that the length returned in the reply is at
* least as big as @reply_size; if not, it will be deemed an error and
* -EIO returned.
*
* @rc needs to be referenced
*/
ssize_t uwb_rc_cmd(struct uwb_rc *rc, const char *cmd_name,
struct uwb_rccb *cmd, size_t cmd_size,
struct uwb_rceb *reply, size_t reply_size)
{
struct device *dev = &rc->uwb_dev.dev;
ssize_t result;
result = __uwb_rc_cmd(rc, cmd_name,
cmd, cmd_size, reply, reply_size,
reply->bEventType, reply->wEvent, NULL);
if (result > 0 && result < reply_size) {
dev_err(dev, "%s: not enough data returned for decoding reply "
"(%zu bytes received vs at least %zu needed)\n",
cmd_name, result, reply_size);
result = -EIO;
}
return result;
}
EXPORT_SYMBOL_GPL(uwb_rc_cmd);
/**
* Generic function for issuing commands to the Radio Control
* Interface that return an unknown amount of data
*
* @rc: UWB Radio Control descriptor
* @cmd_name: Name of the command being issued (for error messages)
* @cmd: Pointer to rccb structure containing the command;
* normally you embed this structure as the first member of
* the full command structure.
* @cmd_size: Size of the whole command buffer pointed to by @cmd.
* @expected_type: Expected type in the return event
* @expected_event: Expected event code in the return event
* @preply: Here a pointer to where the event data is received will
* be stored. Once done with the data, free with kfree().
*
* The function checks that the length returned in the reply is at
* least as big as a 'struct uwb_rceb *'; if not, it will be deemed an
* error and -EIO returned.
*
* @rc needs to be referenced
*/
ssize_t uwb_rc_vcmd(struct uwb_rc *rc, const char *cmd_name,
struct uwb_rccb *cmd, size_t cmd_size,
u8 expected_type, u16 expected_event,
struct uwb_rceb **preply)
{
return __uwb_rc_cmd(rc, cmd_name, cmd, cmd_size, NULL, 0,
expected_type, expected_event, preply);
}
EXPORT_SYMBOL_GPL(uwb_rc_vcmd);
/**
* Reset a UWB Host Controller (and all radio settings)
*
* @rc: Host Controller descriptor
* @returns: 0 if ok, < 0 errno code on error
*
* We put the command on kmalloc'ed memory as some arches cannot do
* USB from the stack. The reply event is copied from an stage buffer,
* so it can be in the stack. See WUSB1.0[8.6.2.4] for more details.
*/
int uwb_rc_reset(struct uwb_rc *rc)
{
int result = -ENOMEM;
struct uwb_rc_evt_confirm reply;
struct uwb_rccb *cmd;
size_t cmd_size = sizeof(*cmd);
mutex_lock(&rc->uwb_dev.mutex);
cmd = kzalloc(sizeof(*cmd), GFP_KERNEL);
if (cmd == NULL)
goto error_kzalloc;
cmd->bCommandType = UWB_RC_CET_GENERAL;
cmd->wCommand = cpu_to_le16(UWB_RC_CMD_RESET);
reply.rceb.bEventType = UWB_RC_CET_GENERAL;
reply.rceb.wEvent = UWB_RC_CMD_RESET;
result = uwb_rc_cmd(rc, "RESET", cmd, cmd_size,
&reply.rceb, sizeof(reply));
if (result < 0)
goto error_cmd;
if (reply.bResultCode != UWB_RC_RES_SUCCESS) {
dev_err(&rc->uwb_dev.dev,
"RESET: command execution failed: %s (%d)\n",
uwb_rc_strerror(reply.bResultCode), reply.bResultCode);
result = -EIO;
}
error_cmd:
kfree(cmd);
error_kzalloc:
mutex_unlock(&rc->uwb_dev.mutex);
return result;
}
int uwbd_msg_handle_reset(struct uwb_event *evt)
{
struct uwb_rc *rc = evt->rc;
int ret;
dev_info(&rc->uwb_dev.dev, "resetting radio controller\n");
ret = rc->reset(rc);
if (ret < 0) {
dev_err(&rc->uwb_dev.dev, "failed to reset hardware: %d\n", ret);
goto error;
}
return 0;
error:
/* Nothing can be done except try the reset again. Wait a bit
to avoid reset loops during probe() or remove(). */
msleep(1000);
uwb_rc_reset_all(rc);
return ret;
}
/**
* uwb_rc_reset_all - request a reset of the radio controller and PALs
* @rc: the radio controller of the hardware device to be reset.
*
* The full hardware reset of the radio controller and all the PALs
* will be scheduled.
*/
void uwb_rc_reset_all(struct uwb_rc *rc)
{
struct uwb_event *evt;
evt = kzalloc(sizeof(struct uwb_event), GFP_ATOMIC);
if (unlikely(evt == NULL))
return;
evt->rc = __uwb_rc_get(rc); /* will be put by uwbd's uwbd_event_handle() */
evt->ts_jiffies = jiffies;
evt->type = UWB_EVT_TYPE_MSG;
evt->message = UWB_EVT_MSG_RESET;
uwbd_event_queue(evt);
}
EXPORT_SYMBOL_GPL(uwb_rc_reset_all);
void uwb_rc_pre_reset(struct uwb_rc *rc)
{
rc->stop(rc);
uwbd_flush(rc);
uwb_radio_reset_state(rc);
uwb_rsv_remove_all(rc);
}
EXPORT_SYMBOL_GPL(uwb_rc_pre_reset);
int uwb_rc_post_reset(struct uwb_rc *rc)
{
int ret;
ret = rc->start(rc);
if (ret)
goto out;
ret = uwb_rc_mac_addr_set(rc, &rc->uwb_dev.mac_addr);
if (ret)
goto out;
ret = uwb_rc_dev_addr_set(rc, &rc->uwb_dev.dev_addr);
if (ret)
goto out;
out:
return ret;
}
EXPORT_SYMBOL_GPL(uwb_rc_post_reset);
| gpl-2.0 |
HazyTeam/android_kernel_lge_hammerhead | arch/m68k/platform/5249/intc2.c | 7536 | 1527 | /*
* intc2.c -- support for the 2nd INTC controller of the 5249
*
* (C) Copyright 2009, Greg Ungerer <gerg@snapgear.com>
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of this archive
* for more details.
*/
#include <linux/types.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/io.h>
#include <asm/coldfire.h>
#include <asm/mcfsim.h>
static void intc2_irq_gpio_mask(struct irq_data *d)
{
u32 imr;
imr = readl(MCF_MBAR2 + MCFSIM2_GPIOINTENABLE);
imr &= ~(0x1 << (d->irq - MCFINTC2_GPIOIRQ0));
writel(imr, MCF_MBAR2 + MCFSIM2_GPIOINTENABLE);
}
static void intc2_irq_gpio_unmask(struct irq_data *d)
{
u32 imr;
imr = readl(MCF_MBAR2 + MCFSIM2_GPIOINTENABLE);
imr |= (0x1 << (d->irq - MCFINTC2_GPIOIRQ0));
writel(imr, MCF_MBAR2 + MCFSIM2_GPIOINTENABLE);
}
static void intc2_irq_gpio_ack(struct irq_data *d)
{
writel(0x1 << (d->irq - MCFINTC2_GPIOIRQ0), MCF_MBAR2 + MCFSIM2_GPIOINTCLEAR);
}
static struct irq_chip intc2_irq_gpio_chip = {
.name = "CF-INTC2",
.irq_mask = intc2_irq_gpio_mask,
.irq_unmask = intc2_irq_gpio_unmask,
.irq_ack = intc2_irq_gpio_ack,
};
static int __init mcf_intc2_init(void)
{
int irq;
/* GPIO interrupt sources */
for (irq = MCFINTC2_GPIOIRQ0; (irq <= MCFINTC2_GPIOIRQ7); irq++) {
irq_set_chip(irq, &intc2_irq_gpio_chip);
irq_set_handler(irq, handle_edge_irq);
}
return 0;
}
arch_initcall(mcf_intc2_init);
| gpl-2.0 |
major91/HTC_X515E_major-kernel | arch/arm/plat-mxc/devices/platform-mxc_nand.c | 8048 | 2388 | /*
* Copyright (C) 2009-2010 Pengutronix
* Uwe Kleine-Koenig <u.kleine-koenig@pengutronix.de>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
*/
#include <asm/sizes.h>
#include <mach/hardware.h>
#include <mach/devices-common.h>
#define imx_mxc_nand_data_entry_single(soc, _size) \
{ \
.iobase = soc ## _NFC_BASE_ADDR, \
.iosize = _size, \
.irq = soc ## _INT_NFC \
}
#define imx_mxc_nandv3_data_entry_single(soc, _size) \
{ \
.id = -1, \
.iobase = soc ## _NFC_BASE_ADDR, \
.iosize = _size, \
.axibase = soc ## _NFC_AXI_BASE_ADDR, \
.irq = soc ## _INT_NFC \
}
#ifdef CONFIG_SOC_IMX21
const struct imx_mxc_nand_data imx21_mxc_nand_data __initconst =
imx_mxc_nand_data_entry_single(MX21, SZ_4K);
#endif /* ifdef CONFIG_SOC_IMX21 */
#ifdef CONFIG_SOC_IMX25
const struct imx_mxc_nand_data imx25_mxc_nand_data __initconst =
imx_mxc_nand_data_entry_single(MX25, SZ_8K);
#endif /* ifdef CONFIG_SOC_IMX25 */
#ifdef CONFIG_SOC_IMX27
const struct imx_mxc_nand_data imx27_mxc_nand_data __initconst =
imx_mxc_nand_data_entry_single(MX27, SZ_4K);
#endif /* ifdef CONFIG_SOC_IMX27 */
#ifdef CONFIG_SOC_IMX31
const struct imx_mxc_nand_data imx31_mxc_nand_data __initconst =
imx_mxc_nand_data_entry_single(MX31, SZ_4K);
#endif
#ifdef CONFIG_SOC_IMX35
const struct imx_mxc_nand_data imx35_mxc_nand_data __initconst =
imx_mxc_nand_data_entry_single(MX35, SZ_8K);
#endif
#ifdef CONFIG_SOC_IMX51
const struct imx_mxc_nand_data imx51_mxc_nand_data __initconst =
imx_mxc_nandv3_data_entry_single(MX51, SZ_16K);
#endif
struct platform_device *__init imx_add_mxc_nand(
const struct imx_mxc_nand_data *data,
const struct mxc_nand_platform_data *pdata)
{
/* AXI has to come first, that's how the mxc_nand driver expect it */
struct resource res[] = {
{
.start = data->axibase,
.end = data->axibase + SZ_16K - 1,
.flags = IORESOURCE_MEM,
}, {
.start = data->iobase,
.end = data->iobase + data->iosize - 1,
.flags = IORESOURCE_MEM,
}, {
.start = data->irq,
.end = data->irq,
.flags = IORESOURCE_IRQ,
},
};
return imx_add_platform_device("mxc_nand", data->id,
res + !data->axibase,
ARRAY_SIZE(res) - !data->axibase,
pdata, sizeof(*pdata));
}
| gpl-2.0 |
arm10c/linux-stable | drivers/input/joystick/gamecon.c | 12400 | 25356 | /*
* NES, SNES, N64, MultiSystem, PSX gamepad driver for Linux
*
* Copyright (c) 1999-2004 Vojtech Pavlik <vojtech@suse.cz>
* Copyright (c) 2004 Peter Nelson <rufus-kernel@hackish.org>
*
* Based on the work of:
* Andree Borrmann John Dahlstrom
* David Kuder Nathan Hand
* Raphael Assenat
*/
/*
* 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
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/parport.h>
#include <linux/input.h>
#include <linux/mutex.h>
#include <linux/slab.h>
MODULE_AUTHOR("Vojtech Pavlik <vojtech@ucw.cz>");
MODULE_DESCRIPTION("NES, SNES, N64, MultiSystem, PSX gamepad driver");
MODULE_LICENSE("GPL");
#define GC_MAX_PORTS 3
#define GC_MAX_DEVICES 5
struct gc_config {
int args[GC_MAX_DEVICES + 1];
unsigned int nargs;
};
static struct gc_config gc_cfg[GC_MAX_PORTS] __initdata;
module_param_array_named(map, gc_cfg[0].args, int, &gc_cfg[0].nargs, 0);
MODULE_PARM_DESC(map, "Describes first set of devices (<parport#>,<pad1>,<pad2>,..<pad5>)");
module_param_array_named(map2, gc_cfg[1].args, int, &gc_cfg[1].nargs, 0);
MODULE_PARM_DESC(map2, "Describes second set of devices");
module_param_array_named(map3, gc_cfg[2].args, int, &gc_cfg[2].nargs, 0);
MODULE_PARM_DESC(map3, "Describes third set of devices");
/* see also gs_psx_delay parameter in PSX support section */
enum gc_type {
GC_NONE = 0,
GC_SNES,
GC_NES,
GC_NES4,
GC_MULTI,
GC_MULTI2,
GC_N64,
GC_PSX,
GC_DDR,
GC_SNESMOUSE,
GC_MAX
};
#define GC_REFRESH_TIME HZ/100
struct gc_pad {
struct input_dev *dev;
enum gc_type type;
char phys[32];
};
struct gc {
struct pardevice *pd;
struct gc_pad pads[GC_MAX_DEVICES];
struct timer_list timer;
int pad_count[GC_MAX];
int used;
struct mutex mutex;
};
struct gc_subdev {
unsigned int idx;
};
static struct gc *gc_base[3];
static const int gc_status_bit[] = { 0x40, 0x80, 0x20, 0x10, 0x08 };
static const char *gc_names[] = {
NULL, "SNES pad", "NES pad", "NES FourPort", "Multisystem joystick",
"Multisystem 2-button joystick", "N64 controller", "PSX controller",
"PSX DDR controller", "SNES mouse"
};
/*
* N64 support.
*/
static const unsigned char gc_n64_bytes[] = { 0, 1, 13, 15, 14, 12, 10, 11, 2, 3 };
static const short gc_n64_btn[] = {
BTN_A, BTN_B, BTN_C, BTN_X, BTN_Y, BTN_Z,
BTN_TL, BTN_TR, BTN_TRIGGER, BTN_START
};
#define GC_N64_LENGTH 32 /* N64 bit length, not including stop bit */
#define GC_N64_STOP_LENGTH 5 /* Length of encoded stop bit */
#define GC_N64_CMD_00 0x11111111UL
#define GC_N64_CMD_01 0xd1111111UL
#define GC_N64_CMD_03 0xdd111111UL
#define GC_N64_CMD_1b 0xdd1dd111UL
#define GC_N64_CMD_c0 0x111111ddUL
#define GC_N64_CMD_80 0x1111111dUL
#define GC_N64_STOP_BIT 0x1d /* Encoded stop bit */
#define GC_N64_REQUEST_DATA GC_N64_CMD_01 /* the request data command */
#define GC_N64_DELAY 133 /* delay between transmit request, and response ready (us) */
#define GC_N64_DWS 3 /* delay between write segments (required for sound playback because of ISA DMA) */
/* GC_N64_DWS > 24 is known to fail */
#define GC_N64_POWER_W 0xe2 /* power during write (transmit request) */
#define GC_N64_POWER_R 0xfd /* power during read */
#define GC_N64_OUT 0x1d /* output bits to the 4 pads */
/* Reading the main axes of any N64 pad is known to fail if the corresponding bit */
/* in GC_N64_OUT is pulled low on the output port (by any routine) for more */
/* than 123 us */
#define GC_N64_CLOCK 0x02 /* clock bits for read */
/*
* Used for rumble code.
*/
/* Send encoded command */
static void gc_n64_send_command(struct gc *gc, unsigned long cmd,
unsigned char target)
{
struct parport *port = gc->pd->port;
int i;
for (i = 0; i < GC_N64_LENGTH; i++) {
unsigned char data = (cmd >> i) & 1 ? target : 0;
parport_write_data(port, GC_N64_POWER_W | data);
udelay(GC_N64_DWS);
}
}
/* Send stop bit */
static void gc_n64_send_stop_bit(struct gc *gc, unsigned char target)
{
struct parport *port = gc->pd->port;
int i;
for (i = 0; i < GC_N64_STOP_LENGTH; i++) {
unsigned char data = (GC_N64_STOP_BIT >> i) & 1 ? target : 0;
parport_write_data(port, GC_N64_POWER_W | data);
udelay(GC_N64_DWS);
}
}
/*
* gc_n64_read_packet() reads an N64 packet.
* Each pad uses one bit per byte. So all pads connected to this port
* are read in parallel.
*/
static void gc_n64_read_packet(struct gc *gc, unsigned char *data)
{
int i;
unsigned long flags;
/*
* Request the pad to transmit data
*/
local_irq_save(flags);
gc_n64_send_command(gc, GC_N64_REQUEST_DATA, GC_N64_OUT);
gc_n64_send_stop_bit(gc, GC_N64_OUT);
local_irq_restore(flags);
/*
* Wait for the pad response to be loaded into the 33-bit register
* of the adapter.
*/
udelay(GC_N64_DELAY);
/*
* Grab data (ignoring the last bit, which is a stop bit)
*/
for (i = 0; i < GC_N64_LENGTH; i++) {
parport_write_data(gc->pd->port, GC_N64_POWER_R);
udelay(2);
data[i] = parport_read_status(gc->pd->port);
parport_write_data(gc->pd->port, GC_N64_POWER_R | GC_N64_CLOCK);
}
/*
* We must wait 200 ms here for the controller to reinitialize before
* the next read request. No worries as long as gc_read is polled less
* frequently than this.
*/
}
static void gc_n64_process_packet(struct gc *gc)
{
unsigned char data[GC_N64_LENGTH];
struct input_dev *dev;
int i, j, s;
signed char x, y;
gc_n64_read_packet(gc, data);
for (i = 0; i < GC_MAX_DEVICES; i++) {
if (gc->pads[i].type != GC_N64)
continue;
dev = gc->pads[i].dev;
s = gc_status_bit[i];
if (s & ~(data[8] | data[9])) {
x = y = 0;
for (j = 0; j < 8; j++) {
if (data[23 - j] & s)
x |= 1 << j;
if (data[31 - j] & s)
y |= 1 << j;
}
input_report_abs(dev, ABS_X, x);
input_report_abs(dev, ABS_Y, -y);
input_report_abs(dev, ABS_HAT0X,
!(s & data[6]) - !(s & data[7]));
input_report_abs(dev, ABS_HAT0Y,
!(s & data[4]) - !(s & data[5]));
for (j = 0; j < 10; j++)
input_report_key(dev, gc_n64_btn[j],
s & data[gc_n64_bytes[j]]);
input_sync(dev);
}
}
}
static int gc_n64_play_effect(struct input_dev *dev, void *data,
struct ff_effect *effect)
{
int i;
unsigned long flags;
struct gc *gc = input_get_drvdata(dev);
struct gc_subdev *sdev = data;
unsigned char target = 1 << sdev->idx; /* select desired pin */
if (effect->type == FF_RUMBLE) {
struct ff_rumble_effect *rumble = &effect->u.rumble;
unsigned int cmd =
rumble->strong_magnitude || rumble->weak_magnitude ?
GC_N64_CMD_01 : GC_N64_CMD_00;
local_irq_save(flags);
/* Init Rumble - 0x03, 0x80, 0x01, (34)0x80 */
gc_n64_send_command(gc, GC_N64_CMD_03, target);
gc_n64_send_command(gc, GC_N64_CMD_80, target);
gc_n64_send_command(gc, GC_N64_CMD_01, target);
for (i = 0; i < 32; i++)
gc_n64_send_command(gc, GC_N64_CMD_80, target);
gc_n64_send_stop_bit(gc, target);
udelay(GC_N64_DELAY);
/* Now start or stop it - 0x03, 0xc0, 0zx1b, (32)0x01/0x00 */
gc_n64_send_command(gc, GC_N64_CMD_03, target);
gc_n64_send_command(gc, GC_N64_CMD_c0, target);
gc_n64_send_command(gc, GC_N64_CMD_1b, target);
for (i = 0; i < 32; i++)
gc_n64_send_command(gc, cmd, target);
gc_n64_send_stop_bit(gc, target);
local_irq_restore(flags);
}
return 0;
}
static int __init gc_n64_init_ff(struct input_dev *dev, int i)
{
struct gc_subdev *sdev;
int err;
sdev = kmalloc(sizeof(*sdev), GFP_KERNEL);
if (!sdev)
return -ENOMEM;
sdev->idx = i;
input_set_capability(dev, EV_FF, FF_RUMBLE);
err = input_ff_create_memless(dev, sdev, gc_n64_play_effect);
if (err) {
kfree(sdev);
return err;
}
return 0;
}
/*
* NES/SNES support.
*/
#define GC_NES_DELAY 6 /* Delay between bits - 6us */
#define GC_NES_LENGTH 8 /* The NES pads use 8 bits of data */
#define GC_SNES_LENGTH 12 /* The SNES true length is 16, but the
last 4 bits are unused */
#define GC_SNESMOUSE_LENGTH 32 /* The SNES mouse uses 32 bits, the first
16 bits are equivalent to a gamepad */
#define GC_NES_POWER 0xfc
#define GC_NES_CLOCK 0x01
#define GC_NES_LATCH 0x02
static const unsigned char gc_nes_bytes[] = { 0, 1, 2, 3 };
static const unsigned char gc_snes_bytes[] = { 8, 0, 2, 3, 9, 1, 10, 11 };
static const short gc_snes_btn[] = {
BTN_A, BTN_B, BTN_SELECT, BTN_START, BTN_X, BTN_Y, BTN_TL, BTN_TR
};
/*
* gc_nes_read_packet() reads a NES/SNES packet.
* Each pad uses one bit per byte. So all pads connected to
* this port are read in parallel.
*/
static void gc_nes_read_packet(struct gc *gc, int length, unsigned char *data)
{
int i;
parport_write_data(gc->pd->port, GC_NES_POWER | GC_NES_CLOCK | GC_NES_LATCH);
udelay(GC_NES_DELAY * 2);
parport_write_data(gc->pd->port, GC_NES_POWER | GC_NES_CLOCK);
for (i = 0; i < length; i++) {
udelay(GC_NES_DELAY);
parport_write_data(gc->pd->port, GC_NES_POWER);
data[i] = parport_read_status(gc->pd->port) ^ 0x7f;
udelay(GC_NES_DELAY);
parport_write_data(gc->pd->port, GC_NES_POWER | GC_NES_CLOCK);
}
}
static void gc_nes_process_packet(struct gc *gc)
{
unsigned char data[GC_SNESMOUSE_LENGTH];
struct gc_pad *pad;
struct input_dev *dev;
int i, j, s, len;
char x_rel, y_rel;
len = gc->pad_count[GC_SNESMOUSE] ? GC_SNESMOUSE_LENGTH :
(gc->pad_count[GC_SNES] ? GC_SNES_LENGTH : GC_NES_LENGTH);
gc_nes_read_packet(gc, len, data);
for (i = 0; i < GC_MAX_DEVICES; i++) {
pad = &gc->pads[i];
dev = pad->dev;
s = gc_status_bit[i];
switch (pad->type) {
case GC_NES:
input_report_abs(dev, ABS_X, !(s & data[6]) - !(s & data[7]));
input_report_abs(dev, ABS_Y, !(s & data[4]) - !(s & data[5]));
for (j = 0; j < 4; j++)
input_report_key(dev, gc_snes_btn[j],
s & data[gc_nes_bytes[j]]);
input_sync(dev);
break;
case GC_SNES:
input_report_abs(dev, ABS_X, !(s & data[6]) - !(s & data[7]));
input_report_abs(dev, ABS_Y, !(s & data[4]) - !(s & data[5]));
for (j = 0; j < 8; j++)
input_report_key(dev, gc_snes_btn[j],
s & data[gc_snes_bytes[j]]);
input_sync(dev);
break;
case GC_SNESMOUSE:
/*
* The 4 unused bits from SNES controllers appear
* to be ID bits so use them to make sure we are
* dealing with a mouse.
* gamepad is connected. This is important since
* my SNES gamepad sends 1's for bits 16-31, which
* cause the mouse pointer to quickly move to the
* upper left corner of the screen.
*/
if (!(s & data[12]) && !(s & data[13]) &&
!(s & data[14]) && (s & data[15])) {
input_report_key(dev, BTN_LEFT, s & data[9]);
input_report_key(dev, BTN_RIGHT, s & data[8]);
x_rel = y_rel = 0;
for (j = 0; j < 7; j++) {
x_rel <<= 1;
if (data[25 + j] & s)
x_rel |= 1;
y_rel <<= 1;
if (data[17 + j] & s)
y_rel |= 1;
}
if (x_rel) {
if (data[24] & s)
x_rel = -x_rel;
input_report_rel(dev, REL_X, x_rel);
}
if (y_rel) {
if (data[16] & s)
y_rel = -y_rel;
input_report_rel(dev, REL_Y, y_rel);
}
input_sync(dev);
}
break;
default:
break;
}
}
}
/*
* Multisystem joystick support
*/
#define GC_MULTI_LENGTH 5 /* Multi system joystick packet length is 5 */
#define GC_MULTI2_LENGTH 6 /* One more bit for one more button */
/*
* gc_multi_read_packet() reads a Multisystem joystick packet.
*/
static void gc_multi_read_packet(struct gc *gc, int length, unsigned char *data)
{
int i;
for (i = 0; i < length; i++) {
parport_write_data(gc->pd->port, ~(1 << i));
data[i] = parport_read_status(gc->pd->port) ^ 0x7f;
}
}
static void gc_multi_process_packet(struct gc *gc)
{
unsigned char data[GC_MULTI2_LENGTH];
int data_len = gc->pad_count[GC_MULTI2] ? GC_MULTI2_LENGTH : GC_MULTI_LENGTH;
struct gc_pad *pad;
struct input_dev *dev;
int i, s;
gc_multi_read_packet(gc, data_len, data);
for (i = 0; i < GC_MAX_DEVICES; i++) {
pad = &gc->pads[i];
dev = pad->dev;
s = gc_status_bit[i];
switch (pad->type) {
case GC_MULTI2:
input_report_key(dev, BTN_THUMB, s & data[5]);
/* fall through */
case GC_MULTI:
input_report_abs(dev, ABS_X,
!(s & data[2]) - !(s & data[3]));
input_report_abs(dev, ABS_Y,
!(s & data[0]) - !(s & data[1]));
input_report_key(dev, BTN_TRIGGER, s & data[4]);
input_sync(dev);
break;
default:
break;
}
}
}
/*
* PSX support
*
* See documentation at:
* http://www.geocities.co.jp/Playtown/2004/psx/ps_eng.txt
* http://www.gamesx.com/controldata/psxcont/psxcont.htm
*
*/
#define GC_PSX_DELAY 25 /* 25 usec */
#define GC_PSX_LENGTH 8 /* talk to the controller in bits */
#define GC_PSX_BYTES 6 /* the maximum number of bytes to read off the controller */
#define GC_PSX_MOUSE 1 /* Mouse */
#define GC_PSX_NEGCON 2 /* NegCon */
#define GC_PSX_NORMAL 4 /* Digital / Analog or Rumble in Digital mode */
#define GC_PSX_ANALOG 5 /* Analog in Analog mode / Rumble in Green mode */
#define GC_PSX_RUMBLE 7 /* Rumble in Red mode */
#define GC_PSX_CLOCK 0x04 /* Pin 4 */
#define GC_PSX_COMMAND 0x01 /* Pin 2 */
#define GC_PSX_POWER 0xf8 /* Pins 5-9 */
#define GC_PSX_SELECT 0x02 /* Pin 3 */
#define GC_PSX_ID(x) ((x) >> 4) /* High nibble is device type */
#define GC_PSX_LEN(x) (((x) & 0xf) << 1) /* Low nibble is length in bytes/2 */
static int gc_psx_delay = GC_PSX_DELAY;
module_param_named(psx_delay, gc_psx_delay, uint, 0);
MODULE_PARM_DESC(psx_delay, "Delay when accessing Sony PSX controller (usecs)");
static const short gc_psx_abs[] = {
ABS_X, ABS_Y, ABS_RX, ABS_RY, ABS_HAT0X, ABS_HAT0Y
};
static const short gc_psx_btn[] = {
BTN_TL, BTN_TR, BTN_TL2, BTN_TR2, BTN_A, BTN_B, BTN_X, BTN_Y,
BTN_START, BTN_SELECT, BTN_THUMBL, BTN_THUMBR
};
static const short gc_psx_ddr_btn[] = { BTN_0, BTN_1, BTN_2, BTN_3 };
/*
* gc_psx_command() writes 8bit command and reads 8bit data from
* the psx pad.
*/
static void gc_psx_command(struct gc *gc, int b, unsigned char *data)
{
struct parport *port = gc->pd->port;
int i, j, cmd, read;
memset(data, 0, GC_MAX_DEVICES);
for (i = 0; i < GC_PSX_LENGTH; i++, b >>= 1) {
cmd = (b & 1) ? GC_PSX_COMMAND : 0;
parport_write_data(port, cmd | GC_PSX_POWER);
udelay(gc_psx_delay);
read = parport_read_status(port) ^ 0x80;
for (j = 0; j < GC_MAX_DEVICES; j++) {
struct gc_pad *pad = &gc->pads[j];
if (pad->type == GC_PSX || pad->type == GC_DDR)
data[j] |= (read & gc_status_bit[j]) ? (1 << i) : 0;
}
parport_write_data(gc->pd->port, cmd | GC_PSX_CLOCK | GC_PSX_POWER);
udelay(gc_psx_delay);
}
}
/*
* gc_psx_read_packet() reads a whole psx packet and returns
* device identifier code.
*/
static void gc_psx_read_packet(struct gc *gc,
unsigned char data[GC_MAX_DEVICES][GC_PSX_BYTES],
unsigned char id[GC_MAX_DEVICES])
{
int i, j, max_len = 0;
unsigned long flags;
unsigned char data2[GC_MAX_DEVICES];
/* Select pad */
parport_write_data(gc->pd->port, GC_PSX_CLOCK | GC_PSX_SELECT | GC_PSX_POWER);
udelay(gc_psx_delay);
/* Deselect, begin command */
parport_write_data(gc->pd->port, GC_PSX_CLOCK | GC_PSX_POWER);
udelay(gc_psx_delay);
local_irq_save(flags);
gc_psx_command(gc, 0x01, data2); /* Access pad */
gc_psx_command(gc, 0x42, id); /* Get device ids */
gc_psx_command(gc, 0, data2); /* Dump status */
/* Find the longest pad */
for (i = 0; i < GC_MAX_DEVICES; i++) {
struct gc_pad *pad = &gc->pads[i];
if ((pad->type == GC_PSX || pad->type == GC_DDR) &&
GC_PSX_LEN(id[i]) > max_len &&
GC_PSX_LEN(id[i]) <= GC_PSX_BYTES) {
max_len = GC_PSX_LEN(id[i]);
}
}
/* Read in all the data */
for (i = 0; i < max_len; i++) {
gc_psx_command(gc, 0, data2);
for (j = 0; j < GC_MAX_DEVICES; j++)
data[j][i] = data2[j];
}
local_irq_restore(flags);
parport_write_data(gc->pd->port, GC_PSX_CLOCK | GC_PSX_SELECT | GC_PSX_POWER);
/* Set id's to the real value */
for (i = 0; i < GC_MAX_DEVICES; i++)
id[i] = GC_PSX_ID(id[i]);
}
static void gc_psx_report_one(struct gc_pad *pad, unsigned char psx_type,
unsigned char *data)
{
struct input_dev *dev = pad->dev;
int i;
switch (psx_type) {
case GC_PSX_RUMBLE:
input_report_key(dev, BTN_THUMBL, ~data[0] & 0x04);
input_report_key(dev, BTN_THUMBR, ~data[0] & 0x02);
case GC_PSX_NEGCON:
case GC_PSX_ANALOG:
if (pad->type == GC_DDR) {
for (i = 0; i < 4; i++)
input_report_key(dev, gc_psx_ddr_btn[i],
~data[0] & (0x10 << i));
} else {
for (i = 0; i < 4; i++)
input_report_abs(dev, gc_psx_abs[i + 2],
data[i + 2]);
input_report_abs(dev, ABS_X,
!!(data[0] & 0x80) * 128 + !(data[0] & 0x20) * 127);
input_report_abs(dev, ABS_Y,
!!(data[0] & 0x10) * 128 + !(data[0] & 0x40) * 127);
}
for (i = 0; i < 8; i++)
input_report_key(dev, gc_psx_btn[i], ~data[1] & (1 << i));
input_report_key(dev, BTN_START, ~data[0] & 0x08);
input_report_key(dev, BTN_SELECT, ~data[0] & 0x01);
input_sync(dev);
break;
case GC_PSX_NORMAL:
if (pad->type == GC_DDR) {
for (i = 0; i < 4; i++)
input_report_key(dev, gc_psx_ddr_btn[i],
~data[0] & (0x10 << i));
} else {
input_report_abs(dev, ABS_X,
!!(data[0] & 0x80) * 128 + !(data[0] & 0x20) * 127);
input_report_abs(dev, ABS_Y,
!!(data[0] & 0x10) * 128 + !(data[0] & 0x40) * 127);
/*
* For some reason if the extra axes are left unset
* they drift.
* for (i = 0; i < 4; i++)
input_report_abs(dev, gc_psx_abs[i + 2], 128);
* This needs to be debugged properly,
* maybe fuzz processing needs to be done
* in input_sync()
* --vojtech
*/
}
for (i = 0; i < 8; i++)
input_report_key(dev, gc_psx_btn[i], ~data[1] & (1 << i));
input_report_key(dev, BTN_START, ~data[0] & 0x08);
input_report_key(dev, BTN_SELECT, ~data[0] & 0x01);
input_sync(dev);
break;
default: /* not a pad, ignore */
break;
}
}
static void gc_psx_process_packet(struct gc *gc)
{
unsigned char data[GC_MAX_DEVICES][GC_PSX_BYTES];
unsigned char id[GC_MAX_DEVICES];
struct gc_pad *pad;
int i;
gc_psx_read_packet(gc, data, id);
for (i = 0; i < GC_MAX_DEVICES; i++) {
pad = &gc->pads[i];
if (pad->type == GC_PSX || pad->type == GC_DDR)
gc_psx_report_one(pad, id[i], data[i]);
}
}
/*
* gc_timer() initiates reads of console pads data.
*/
static void gc_timer(unsigned long private)
{
struct gc *gc = (void *) private;
/*
* N64 pads - must be read first, any read confuses them for 200 us
*/
if (gc->pad_count[GC_N64])
gc_n64_process_packet(gc);
/*
* NES and SNES pads or mouse
*/
if (gc->pad_count[GC_NES] ||
gc->pad_count[GC_SNES] ||
gc->pad_count[GC_SNESMOUSE]) {
gc_nes_process_packet(gc);
}
/*
* Multi and Multi2 joysticks
*/
if (gc->pad_count[GC_MULTI] || gc->pad_count[GC_MULTI2])
gc_multi_process_packet(gc);
/*
* PSX controllers
*/
if (gc->pad_count[GC_PSX] || gc->pad_count[GC_DDR])
gc_psx_process_packet(gc);
mod_timer(&gc->timer, jiffies + GC_REFRESH_TIME);
}
static int gc_open(struct input_dev *dev)
{
struct gc *gc = input_get_drvdata(dev);
int err;
err = mutex_lock_interruptible(&gc->mutex);
if (err)
return err;
if (!gc->used++) {
parport_claim(gc->pd);
parport_write_control(gc->pd->port, 0x04);
mod_timer(&gc->timer, jiffies + GC_REFRESH_TIME);
}
mutex_unlock(&gc->mutex);
return 0;
}
static void gc_close(struct input_dev *dev)
{
struct gc *gc = input_get_drvdata(dev);
mutex_lock(&gc->mutex);
if (!--gc->used) {
del_timer_sync(&gc->timer);
parport_write_control(gc->pd->port, 0x00);
parport_release(gc->pd);
}
mutex_unlock(&gc->mutex);
}
static int __init gc_setup_pad(struct gc *gc, int idx, int pad_type)
{
struct gc_pad *pad = &gc->pads[idx];
struct input_dev *input_dev;
int i;
int err;
if (pad_type < 1 || pad_type >= GC_MAX) {
pr_err("Pad type %d unknown\n", pad_type);
return -EINVAL;
}
pad->dev = input_dev = input_allocate_device();
if (!input_dev) {
pr_err("Not enough memory for input device\n");
return -ENOMEM;
}
pad->type = pad_type;
snprintf(pad->phys, sizeof(pad->phys),
"%s/input%d", gc->pd->port->name, idx);
input_dev->name = gc_names[pad_type];
input_dev->phys = pad->phys;
input_dev->id.bustype = BUS_PARPORT;
input_dev->id.vendor = 0x0001;
input_dev->id.product = pad_type;
input_dev->id.version = 0x0100;
input_set_drvdata(input_dev, gc);
input_dev->open = gc_open;
input_dev->close = gc_close;
if (pad_type != GC_SNESMOUSE) {
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
for (i = 0; i < 2; i++)
input_set_abs_params(input_dev, ABS_X + i, -1, 1, 0, 0);
} else
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REL);
gc->pad_count[pad_type]++;
switch (pad_type) {
case GC_N64:
for (i = 0; i < 10; i++)
__set_bit(gc_n64_btn[i], input_dev->keybit);
for (i = 0; i < 2; i++) {
input_set_abs_params(input_dev, ABS_X + i, -127, 126, 0, 2);
input_set_abs_params(input_dev, ABS_HAT0X + i, -1, 1, 0, 0);
}
err = gc_n64_init_ff(input_dev, idx);
if (err) {
pr_warning("Failed to initiate rumble for N64 device %d\n", idx);
goto err_free_dev;
}
break;
case GC_SNESMOUSE:
__set_bit(BTN_LEFT, input_dev->keybit);
__set_bit(BTN_RIGHT, input_dev->keybit);
__set_bit(REL_X, input_dev->relbit);
__set_bit(REL_Y, input_dev->relbit);
break;
case GC_SNES:
for (i = 4; i < 8; i++)
__set_bit(gc_snes_btn[i], input_dev->keybit);
case GC_NES:
for (i = 0; i < 4; i++)
__set_bit(gc_snes_btn[i], input_dev->keybit);
break;
case GC_MULTI2:
__set_bit(BTN_THUMB, input_dev->keybit);
case GC_MULTI:
__set_bit(BTN_TRIGGER, input_dev->keybit);
break;
case GC_PSX:
for (i = 0; i < 6; i++)
input_set_abs_params(input_dev,
gc_psx_abs[i], 4, 252, 0, 2);
for (i = 0; i < 12; i++)
__set_bit(gc_psx_btn[i], input_dev->keybit);
break;
case GC_DDR:
for (i = 0; i < 4; i++)
__set_bit(gc_psx_ddr_btn[i], input_dev->keybit);
for (i = 0; i < 12; i++)
__set_bit(gc_psx_btn[i], input_dev->keybit);
break;
}
err = input_register_device(pad->dev);
if (err)
goto err_free_dev;
return 0;
err_free_dev:
input_free_device(pad->dev);
pad->dev = NULL;
return err;
}
static struct gc __init *gc_probe(int parport, int *pads, int n_pads)
{
struct gc *gc;
struct parport *pp;
struct pardevice *pd;
int i;
int count = 0;
int err;
pp = parport_find_number(parport);
if (!pp) {
pr_err("no such parport %d\n", parport);
err = -EINVAL;
goto err_out;
}
pd = parport_register_device(pp, "gamecon", NULL, NULL, NULL, PARPORT_DEV_EXCL, NULL);
if (!pd) {
pr_err("parport busy already - lp.o loaded?\n");
err = -EBUSY;
goto err_put_pp;
}
gc = kzalloc(sizeof(struct gc), GFP_KERNEL);
if (!gc) {
pr_err("Not enough memory\n");
err = -ENOMEM;
goto err_unreg_pardev;
}
mutex_init(&gc->mutex);
gc->pd = pd;
setup_timer(&gc->timer, gc_timer, (long) gc);
for (i = 0; i < n_pads && i < GC_MAX_DEVICES; i++) {
if (!pads[i])
continue;
err = gc_setup_pad(gc, i, pads[i]);
if (err)
goto err_unreg_devs;
count++;
}
if (count == 0) {
pr_err("No valid devices specified\n");
err = -EINVAL;
goto err_free_gc;
}
parport_put_port(pp);
return gc;
err_unreg_devs:
while (--i >= 0)
if (gc->pads[i].dev)
input_unregister_device(gc->pads[i].dev);
err_free_gc:
kfree(gc);
err_unreg_pardev:
parport_unregister_device(pd);
err_put_pp:
parport_put_port(pp);
err_out:
return ERR_PTR(err);
}
static void gc_remove(struct gc *gc)
{
int i;
for (i = 0; i < GC_MAX_DEVICES; i++)
if (gc->pads[i].dev)
input_unregister_device(gc->pads[i].dev);
parport_unregister_device(gc->pd);
kfree(gc);
}
static int __init gc_init(void)
{
int i;
int have_dev = 0;
int err = 0;
for (i = 0; i < GC_MAX_PORTS; i++) {
if (gc_cfg[i].nargs == 0 || gc_cfg[i].args[0] < 0)
continue;
if (gc_cfg[i].nargs < 2) {
pr_err("at least one device must be specified\n");
err = -EINVAL;
break;
}
gc_base[i] = gc_probe(gc_cfg[i].args[0],
gc_cfg[i].args + 1, gc_cfg[i].nargs - 1);
if (IS_ERR(gc_base[i])) {
err = PTR_ERR(gc_base[i]);
break;
}
have_dev = 1;
}
if (err) {
while (--i >= 0)
if (gc_base[i])
gc_remove(gc_base[i]);
return err;
}
return have_dev ? 0 : -ENODEV;
}
static void __exit gc_exit(void)
{
int i;
for (i = 0; i < GC_MAX_PORTS; i++)
if (gc_base[i])
gc_remove(gc_base[i]);
}
module_init(gc_init);
module_exit(gc_exit);
| gpl-2.0 |
syhost/android_kernel_pantech_ef52l | drivers/switch/switch_sky.c | 113 | 5640 | /*
* drivers/switch/switch_class.c
*
* Copyright (C) 2008 Google, Inc.
* Author: Mike Lockwood <lockwood@android.com>
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* 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/types.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/fs.h>
#include <linux/err.h>
#include <linux/switch.h>
//ps1 team shs : add driver
struct class *sky_class;
static struct switch_dev sky_switch_dev;
static atomic_t device_count;
#define apr_dbg(fmt, args...) printk("[SWITCH SKY] " fmt, ##args)
void sky_set_state(struct switch_dev *sdev, int state);
static ssize_t state_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct switch_dev *sdev = (struct switch_dev *)
dev_get_drvdata(dev);
if (sdev->print_state) {
int ret = sdev->print_state(sdev, buf);
if (ret >= 0)
return ret;
}
return sprintf(buf, "%d\n", sdev->state);
}
static ssize_t name_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct switch_dev *sdev = (struct switch_dev *)
dev_get_drvdata(dev);
if (sdev->print_name) {
int ret = sdev->print_name(sdev, buf);
if (ret >= 0)
return ret;
}
return sprintf(buf, "%s\n", sdev->name);
}
static ssize_t event_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct switch_dev *sdev = (struct switch_dev *)
dev_get_drvdata(dev);
if (sdev->print_name) {
int ret = sdev->print_name(sdev, buf);
if (ret >= 0)
return ret;
}
return sprintf(buf, "%s\n", sdev->name);
}
static ssize_t event_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
u32 akey = simple_strtoul(buf, NULL, 10);
struct switch_dev *sdev = (struct switch_dev *)
dev_get_drvdata(dev);
apr_dbg("event_store CALLING\n");
if(akey==0xF23F)
{
sky_set_state(&sky_switch_dev,1);
sdev->state = 0;
}
return count;
}
static DEVICE_ATTR(state, S_IRUGO | S_IWUSR, state_show, NULL);
static DEVICE_ATTR(name, S_IRUGO | S_IWUSR, name_show, NULL);
static DEVICE_ATTR(event, S_IRUGO | S_IWUSR, event_show, event_store);
void sky_set_state(struct switch_dev *sdev, int state)
{
char name_buf[120];
char state_buf[120];
char *prop_buf;
char *envp[3];
int env_offset = 0;
int length;
if (sdev->state != state) {
sdev->state = state;
prop_buf = (char *)get_zeroed_page(GFP_KERNEL);
if (prop_buf) {
length = name_show(sdev->dev, NULL, prop_buf);
if (length > 0) {
if (prop_buf[length - 1] == '\n')
prop_buf[length - 1] = 0;
snprintf(name_buf, sizeof(name_buf),
"APR_NAME=%s", prop_buf);
envp[env_offset++] = name_buf;
}
length = state_show(sdev->dev, NULL, prop_buf);
if (length > 0) {
if (prop_buf[length - 1] == '\n')
prop_buf[length - 1] = 0;
snprintf(state_buf, sizeof(state_buf),
"APR_STATE=%s", prop_buf);
envp[env_offset++] = state_buf;
}
envp[env_offset] = NULL;
apr_dbg("kobject_uevent_env calling");
kobject_uevent_env(&sdev->dev->kobj, KOBJ_CHANGE, envp);
free_page((unsigned long)prop_buf);
} else {
printk(KERN_ERR "out of memory in sky_set_state\n");
kobject_uevent(&sdev->dev->kobj, KOBJ_CHANGE);
}
}
}
static int create_sky_class(void)
{
if (!sky_class) {
sky_class = class_create(THIS_MODULE, "sky");
if (IS_ERR(sky_class))
return PTR_ERR(sky_class);
atomic_set(&device_count, 0);
}
return 0;
}
static int sky_dev_register(struct switch_dev *sdev)
{
int ret;
if (!sky_class) {
ret = create_sky_class();
if (ret < 0)
return ret;
}
sdev->index = atomic_inc_return(&device_count);
sdev->dev = device_create(sky_class, NULL,
MKDEV(0, sdev->index), NULL, sdev->name);
if (IS_ERR(sdev->dev))
return PTR_ERR(sdev->dev);
ret = device_create_file(sdev->dev, &dev_attr_state);
if (ret < 0)
goto err_create_file_1;
ret = device_create_file(sdev->dev, &dev_attr_name);
if (ret < 0)
goto err_create_file_2;
ret = device_create_file(sdev->dev, &dev_attr_event);
if (ret < 0)
goto err_create_file_3;
dev_set_drvdata(sdev->dev, sdev);
sdev->state = 0;
return 0;
err_create_file_3:
device_remove_file(sdev->dev, &dev_attr_name);
device_remove_file(sdev->dev, &dev_attr_state);
err_create_file_2:
device_remove_file(sdev->dev, &dev_attr_state);
err_create_file_1:
device_destroy(sky_class, MKDEV(0, sdev->index));
printk(KERN_ERR "switch: Failed to register driver %s\n", sdev->name);
return ret;
}
void sky_switch_dev_unregister(struct switch_dev *sdev)
{
device_remove_file(sdev->dev, &dev_attr_name);
device_remove_file(sdev->dev, &dev_attr_state);
device_remove_file(sdev->dev, &dev_attr_event);
atomic_dec(&device_count);
dev_set_drvdata(sdev->dev, NULL);
device_destroy(sky_class, MKDEV(0, sdev->index));
}
static int __init sky_switch_class_init(void)
{
int ret;
sky_switch_dev.name="apr";
ret=sky_dev_register(&sky_switch_dev);
return ret;
}
static void __exit sky_switch_class_exit(void)
{
sky_switch_dev_unregister(&sky_switch_dev);
class_destroy(sky_class);
}
module_init(sky_switch_class_init);
module_exit(sky_switch_class_exit);
MODULE_AUTHOR("shin hyung sik<shin.hyungsik@pantech.com>");
MODULE_DESCRIPTION("Sky Switch class driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
Zoldyck07/Zapdos-Kernel | drivers/mmc/card/queue.c | 369 | 9321 | /*
* linux/drivers/mmc/card/queue.c
*
* Copyright (C) 2003 Russell King, All Rights Reserved.
* Copyright 2006-2007 Pierre Ossman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/blkdev.h>
#include <linux/freezer.h>
#include <linux/kthread.h>
#include <linux/scatterlist.h>
#include <linux/mmc/card.h>
#include <linux/mmc/host.h>
#include "queue.h"
#define MMC_QUEUE_BOUNCESZ 65536
#define MMC_QUEUE_SUSPENDED (1 << 0)
/*
* Prepare a MMC request. This just filters out odd stuff.
*/
static int mmc_prep_request(struct request_queue *q, struct request *req)
{
struct mmc_queue *mq = q->queuedata;
/*
* We only like normal block requests and discards.
*/
if (req->cmd_type != REQ_TYPE_FS && !(req->cmd_flags & REQ_DISCARD)) {
blk_dump_rq_flags(req, "MMC bad request");
return BLKPREP_KILL;
}
if (mq && mmc_card_removed(mq->card))
return BLKPREP_KILL;
req->cmd_flags |= REQ_DONTPREP;
return BLKPREP_OK;
}
static int mmc_queue_thread(void *d)
{
struct mmc_queue *mq = d;
struct request_queue *q = mq->queue;
struct request *req;
#ifdef CONFIG_MMC_PERF_PROFILING
ktime_t start, diff;
struct mmc_host *host = mq->card->host;
unsigned long bytes_xfer;
#endif
current->flags |= PF_MEMALLOC;
down(&mq->thread_sem);
do {
req = NULL; /* Must be set to NULL at each iteration */
spin_lock_irq(q->queue_lock);
set_current_state(TASK_INTERRUPTIBLE);
req = blk_fetch_request(q);
mq->req = req;
spin_unlock_irq(q->queue_lock);
if (!req) {
if (kthread_should_stop()) {
set_current_state(TASK_RUNNING);
break;
}
up(&mq->thread_sem);
schedule();
down(&mq->thread_sem);
continue;
}
set_current_state(TASK_RUNNING);
#ifdef CONFIG_MMC_PERF_PROFILING
if (host->perf_enable) {
bytes_xfer = blk_rq_bytes(req);
if (rq_data_dir(req) == READ) {
start = ktime_get();
mq->issue_fn(mq, req);
diff = ktime_sub(ktime_get(), start);
host->perf.rbytes_mmcq += bytes_xfer;
host->perf.rtime_mmcq =
ktime_add(host->perf.rtime_mmcq, diff);
} else {
start = ktime_get();
mq->issue_fn(mq, req);
diff = ktime_sub(ktime_get(), start);
host->perf.wbytes_mmcq += bytes_xfer;
host->perf.wtime_mmcq =
ktime_add(host->perf.wtime_mmcq, diff);
}
} else {
mq->issue_fn(mq, req);
}
#else
mq->issue_fn(mq, req);
#endif
} while (1);
up(&mq->thread_sem);
return 0;
}
/*
* Generic MMC request handler. This is called for any queue on a
* particular host. When the host is not busy, we look for a request
* on any queue on this host, and attempt to issue it. This may
* not be the queue we were asked to process.
*/
static void mmc_request(struct request_queue *q)
{
struct mmc_queue *mq = q->queuedata;
struct request *req;
if (!mq) {
while ((req = blk_fetch_request(q)) != NULL) {
req->cmd_flags |= REQ_QUIET;
__blk_end_request_all(req, -EIO);
}
return;
}
if (!mq->req)
wake_up_process(mq->thread);
}
/**
* mmc_init_queue - initialise a queue structure.
* @mq: mmc queue
* @card: mmc card to attach this queue
* @lock: queue lock
* @subname: partition subname
*
* Initialise a MMC card request queue.
*/
int mmc_init_queue(struct mmc_queue *mq, struct mmc_card *card,
spinlock_t *lock, const char *subname)
{
struct mmc_host *host = card->host;
u64 limit = BLK_BOUNCE_HIGH;
int ret;
if (mmc_dev(host)->dma_mask && *mmc_dev(host)->dma_mask)
limit = *mmc_dev(host)->dma_mask;
mq->card = card;
mq->queue = blk_init_queue(mmc_request, lock);
if (!mq->queue)
return -ENOMEM;
mq->queue->queuedata = mq;
mq->req = NULL;
blk_queue_prep_rq(mq->queue, mmc_prep_request);
queue_flag_set_unlocked(QUEUE_FLAG_NONROT, mq->queue);
if (mmc_can_erase(card)) {
queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, mq->queue);
mq->queue->limits.max_discard_sectors = UINT_MAX;
if (card->erased_byte == 0)
mq->queue->limits.discard_zeroes_data = 1;
mq->queue->limits.discard_granularity = card->pref_erase << 9;
if (mmc_can_secure_erase_trim(card))
queue_flag_set_unlocked(QUEUE_FLAG_SECDISCARD,
mq->queue);
}
#ifdef CONFIG_MMC_BLOCK_BOUNCE
if (host->max_segs == 1) {
unsigned int bouncesz;
bouncesz = MMC_QUEUE_BOUNCESZ;
if (bouncesz > host->max_req_size)
bouncesz = host->max_req_size;
if (bouncesz > host->max_seg_size)
bouncesz = host->max_seg_size;
if (bouncesz > (host->max_blk_count * 512))
bouncesz = host->max_blk_count * 512;
if (bouncesz > 512) {
mq->bounce_buf = kmalloc(bouncesz, GFP_KERNEL);
if (!mq->bounce_buf) {
printk(KERN_WARNING "%s: unable to "
"allocate bounce buffer\n",
mmc_card_name(card));
}
}
if (mq->bounce_buf) {
blk_queue_bounce_limit(mq->queue, BLK_BOUNCE_ANY);
blk_queue_max_hw_sectors(mq->queue, bouncesz / 512);
blk_queue_max_segments(mq->queue, bouncesz / 512);
blk_queue_max_segment_size(mq->queue, bouncesz);
mq->sg = kmalloc(sizeof(struct scatterlist),
GFP_KERNEL);
if (!mq->sg) {
ret = -ENOMEM;
goto cleanup_queue;
}
sg_init_table(mq->sg, 1);
mq->bounce_sg = kmalloc(sizeof(struct scatterlist) *
bouncesz / 512, GFP_KERNEL);
if (!mq->bounce_sg) {
ret = -ENOMEM;
goto cleanup_queue;
}
sg_init_table(mq->bounce_sg, bouncesz / 512);
}
}
#endif
if (!mq->bounce_buf) {
blk_queue_bounce_limit(mq->queue, limit);
blk_queue_max_hw_sectors(mq->queue,
min(host->max_blk_count, host->max_req_size / 512));
blk_queue_max_segments(mq->queue, host->max_segs);
blk_queue_max_segment_size(mq->queue, host->max_seg_size);
mq->sg = kmalloc(sizeof(struct scatterlist) *
host->max_segs, GFP_KERNEL);
if (!mq->sg) {
ret = -ENOMEM;
goto cleanup_queue;
}
sg_init_table(mq->sg, host->max_segs);
}
sema_init(&mq->thread_sem, 1);
mq->thread = kthread_run(mmc_queue_thread, mq, "mmcqd/%d%s",
host->index, subname ? subname : "");
if (IS_ERR(mq->thread)) {
ret = PTR_ERR(mq->thread);
goto free_bounce_sg;
}
return 0;
free_bounce_sg:
if (mq->bounce_sg)
kfree(mq->bounce_sg);
mq->bounce_sg = NULL;
cleanup_queue:
if (mq->sg)
kfree(mq->sg);
mq->sg = NULL;
if (mq->bounce_buf)
kfree(mq->bounce_buf);
mq->bounce_buf = NULL;
blk_cleanup_queue(mq->queue);
return ret;
}
void mmc_cleanup_queue(struct mmc_queue *mq)
{
struct request_queue *q = mq->queue;
unsigned long flags;
/* Make sure the queue isn't suspended, as that will deadlock */
mmc_queue_resume(mq);
/* Then terminate our worker thread */
kthread_stop(mq->thread);
/* Empty the queue */
spin_lock_irqsave(q->queue_lock, flags);
q->queuedata = NULL;
blk_start_queue(q);
spin_unlock_irqrestore(q->queue_lock, flags);
if (mq->bounce_sg)
kfree(mq->bounce_sg);
mq->bounce_sg = NULL;
kfree(mq->sg);
mq->sg = NULL;
if (mq->bounce_buf)
kfree(mq->bounce_buf);
mq->bounce_buf = NULL;
mq->card = NULL;
}
EXPORT_SYMBOL(mmc_cleanup_queue);
/**
* mmc_queue_suspend - suspend a MMC request queue
* @mq: MMC queue to suspend
*
* Stop the block request queue, and wait for our thread to
* complete any outstanding requests. This ensures that we
* won't suspend while a request is being processed.
*/
void mmc_queue_suspend(struct mmc_queue *mq)
{
struct request_queue *q = mq->queue;
unsigned long flags;
if (!(mq->flags & MMC_QUEUE_SUSPENDED)) {
mq->flags |= MMC_QUEUE_SUSPENDED;
spin_lock_irqsave(q->queue_lock, flags);
blk_stop_queue(q);
spin_unlock_irqrestore(q->queue_lock, flags);
down(&mq->thread_sem);
}
}
/**
* mmc_queue_resume - resume a previously suspended MMC request queue
* @mq: MMC queue to resume
*/
void mmc_queue_resume(struct mmc_queue *mq)
{
struct request_queue *q = mq->queue;
unsigned long flags;
if (mq->flags & MMC_QUEUE_SUSPENDED) {
mq->flags &= ~MMC_QUEUE_SUSPENDED;
up(&mq->thread_sem);
spin_lock_irqsave(q->queue_lock, flags);
blk_start_queue(q);
spin_unlock_irqrestore(q->queue_lock, flags);
}
}
/*
* Prepare the sg list(s) to be handed of to the host driver
*/
unsigned int mmc_queue_map_sg(struct mmc_queue *mq)
{
unsigned int sg_len;
size_t buflen;
struct scatterlist *sg;
int i;
if (!mq->bounce_buf)
return blk_rq_map_sg(mq->queue, mq->req, mq->sg);
BUG_ON(!mq->bounce_sg);
sg_len = blk_rq_map_sg(mq->queue, mq->req, mq->bounce_sg);
mq->bounce_sg_len = sg_len;
buflen = 0;
for_each_sg(mq->bounce_sg, sg, sg_len, i)
buflen += sg->length;
sg_init_one(mq->sg, mq->bounce_buf, buflen);
return 1;
}
/*
* If writing, bounce the data to the buffer before the request
* is sent to the host driver
*/
void mmc_queue_bounce_pre(struct mmc_queue *mq)
{
if (!mq->bounce_buf)
return;
if (rq_data_dir(mq->req) != WRITE)
return;
sg_copy_to_buffer(mq->bounce_sg, mq->bounce_sg_len,
mq->bounce_buf, mq->sg[0].length);
}
/*
* If reading, bounce the data from the buffer after the request
* has been handled by the host driver
*/
void mmc_queue_bounce_post(struct mmc_queue *mq)
{
if (!mq->bounce_buf)
return;
if (rq_data_dir(mq->req) != READ)
return;
sg_copy_from_buffer(mq->bounce_sg, mq->bounce_sg_len,
mq->bounce_buf, mq->sg[0].length);
}
| gpl-2.0 |
ArtVandelae/steamos_kernel | mm/migrate.c | 369 | 45568 | /*
* Memory Migration functionality - linux/mm/migration.c
*
* Copyright (C) 2006 Silicon Graphics, Inc., Christoph Lameter
*
* Page migration was first developed in the context of the memory hotplug
* project. The main authors of the migration code are:
*
* IWAMOTO Toshihiro <iwamoto@valinux.co.jp>
* Hirokazu Takahashi <taka@valinux.co.jp>
* Dave Hansen <haveblue@us.ibm.com>
* Christoph Lameter
*/
#include <linux/migrate.h>
#include <linux/export.h>
#include <linux/swap.h>
#include <linux/swapops.h>
#include <linux/pagemap.h>
#include <linux/buffer_head.h>
#include <linux/mm_inline.h>
#include <linux/nsproxy.h>
#include <linux/pagevec.h>
#include <linux/ksm.h>
#include <linux/rmap.h>
#include <linux/topology.h>
#include <linux/cpu.h>
#include <linux/cpuset.h>
#include <linux/writeback.h>
#include <linux/mempolicy.h>
#include <linux/vmalloc.h>
#include <linux/security.h>
#include <linux/memcontrol.h>
#include <linux/syscalls.h>
#include <linux/hugetlb.h>
#include <linux/hugetlb_cgroup.h>
#include <linux/gfp.h>
#include <linux/balloon_compaction.h>
#include <asm/tlbflush.h>
#define CREATE_TRACE_POINTS
#include <trace/events/migrate.h>
#include "internal.h"
/*
* migrate_prep() needs to be called before we start compiling a list of pages
* to be migrated using isolate_lru_page(). If scheduling work on other CPUs is
* undesirable, use migrate_prep_local()
*/
int migrate_prep(void)
{
/*
* Clear the LRU lists so pages can be isolated.
* Note that pages may be moved off the LRU after we have
* drained them. Those pages will fail to migrate like other
* pages that may be busy.
*/
lru_add_drain_all();
return 0;
}
/* Do the necessary work of migrate_prep but not if it involves other CPUs */
int migrate_prep_local(void)
{
lru_add_drain();
return 0;
}
/*
* Add isolated pages on the list back to the LRU under page lock
* to avoid leaking evictable pages back onto unevictable list.
*/
void putback_lru_pages(struct list_head *l)
{
struct page *page;
struct page *page2;
list_for_each_entry_safe(page, page2, l, lru) {
list_del(&page->lru);
dec_zone_page_state(page, NR_ISOLATED_ANON +
page_is_file_cache(page));
putback_lru_page(page);
}
}
/*
* Put previously isolated pages back onto the appropriate lists
* from where they were once taken off for compaction/migration.
*
* This function shall be used instead of putback_lru_pages(),
* whenever the isolated pageset has been built by isolate_migratepages_range()
*/
void putback_movable_pages(struct list_head *l)
{
struct page *page;
struct page *page2;
list_for_each_entry_safe(page, page2, l, lru) {
list_del(&page->lru);
dec_zone_page_state(page, NR_ISOLATED_ANON +
page_is_file_cache(page));
if (unlikely(isolated_balloon_page(page)))
balloon_page_putback(page);
else
putback_lru_page(page);
}
}
/*
* Restore a potential migration pte to a working pte entry
*/
static int remove_migration_pte(struct page *new, struct vm_area_struct *vma,
unsigned long addr, void *old)
{
struct mm_struct *mm = vma->vm_mm;
swp_entry_t entry;
pmd_t *pmd;
pte_t *ptep, pte;
spinlock_t *ptl;
if (unlikely(PageHuge(new))) {
ptep = huge_pte_offset(mm, addr);
if (!ptep)
goto out;
ptl = &mm->page_table_lock;
} else {
pmd = mm_find_pmd(mm, addr);
if (!pmd)
goto out;
if (pmd_trans_huge(*pmd))
goto out;
ptep = pte_offset_map(pmd, addr);
/*
* Peek to check is_swap_pte() before taking ptlock? No, we
* can race mremap's move_ptes(), which skips anon_vma lock.
*/
ptl = pte_lockptr(mm, pmd);
}
spin_lock(ptl);
pte = *ptep;
if (!is_swap_pte(pte))
goto unlock;
entry = pte_to_swp_entry(pte);
if (!is_migration_entry(entry) ||
migration_entry_to_page(entry) != old)
goto unlock;
get_page(new);
pte = pte_mkold(mk_pte(new, vma->vm_page_prot));
if (is_write_migration_entry(entry))
pte = pte_mkwrite(pte);
#ifdef CONFIG_HUGETLB_PAGE
if (PageHuge(new)) {
pte = pte_mkhuge(pte);
pte = arch_make_huge_pte(pte, vma, new, 0);
}
#endif
flush_dcache_page(new);
set_pte_at(mm, addr, ptep, pte);
if (PageHuge(new)) {
if (PageAnon(new))
hugepage_add_anon_rmap(new, vma, addr);
else
page_dup_rmap(new);
} else if (PageAnon(new))
page_add_anon_rmap(new, vma, addr);
else
page_add_file_rmap(new);
/* No need to invalidate - it was non-present before */
update_mmu_cache(vma, addr, ptep);
unlock:
pte_unmap_unlock(ptep, ptl);
out:
return SWAP_AGAIN;
}
/*
* Get rid of all migration entries and replace them by
* references to the indicated page.
*/
static void remove_migration_ptes(struct page *old, struct page *new)
{
rmap_walk(new, remove_migration_pte, old);
}
/*
* Something used the pte of a page under migration. We need to
* get to the page and wait until migration is finished.
* When we return from this function the fault will be retried.
*/
static void __migration_entry_wait(struct mm_struct *mm, pte_t *ptep,
spinlock_t *ptl)
{
pte_t pte;
swp_entry_t entry;
struct page *page;
spin_lock(ptl);
pte = *ptep;
if (!is_swap_pte(pte))
goto out;
entry = pte_to_swp_entry(pte);
if (!is_migration_entry(entry))
goto out;
page = migration_entry_to_page(entry);
/*
* Once radix-tree replacement of page migration started, page_count
* *must* be zero. And, we don't want to call wait_on_page_locked()
* against a page without get_page().
* So, we use get_page_unless_zero(), here. Even failed, page fault
* will occur again.
*/
if (!get_page_unless_zero(page))
goto out;
pte_unmap_unlock(ptep, ptl);
wait_on_page_locked(page);
put_page(page);
return;
out:
pte_unmap_unlock(ptep, ptl);
}
void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd,
unsigned long address)
{
spinlock_t *ptl = pte_lockptr(mm, pmd);
pte_t *ptep = pte_offset_map(pmd, address);
__migration_entry_wait(mm, ptep, ptl);
}
void migration_entry_wait_huge(struct mm_struct *mm, pte_t *pte)
{
spinlock_t *ptl = &(mm)->page_table_lock;
__migration_entry_wait(mm, pte, ptl);
}
#ifdef CONFIG_BLOCK
/* Returns true if all buffers are successfully locked */
static bool buffer_migrate_lock_buffers(struct buffer_head *head,
enum migrate_mode mode)
{
struct buffer_head *bh = head;
/* Simple case, sync compaction */
if (mode != MIGRATE_ASYNC) {
do {
get_bh(bh);
lock_buffer(bh);
bh = bh->b_this_page;
} while (bh != head);
return true;
}
/* async case, we cannot block on lock_buffer so use trylock_buffer */
do {
get_bh(bh);
if (!trylock_buffer(bh)) {
/*
* We failed to lock the buffer and cannot stall in
* async migration. Release the taken locks
*/
struct buffer_head *failed_bh = bh;
put_bh(failed_bh);
bh = head;
while (bh != failed_bh) {
unlock_buffer(bh);
put_bh(bh);
bh = bh->b_this_page;
}
return false;
}
bh = bh->b_this_page;
} while (bh != head);
return true;
}
#else
static inline bool buffer_migrate_lock_buffers(struct buffer_head *head,
enum migrate_mode mode)
{
return true;
}
#endif /* CONFIG_BLOCK */
/*
* Replace the page in the mapping.
*
* The number of remaining references must be:
* 1 for anonymous pages without a mapping
* 2 for pages with a mapping
* 3 for pages with a mapping and PagePrivate/PagePrivate2 set.
*/
static int migrate_page_move_mapping(struct address_space *mapping,
struct page *newpage, struct page *page,
struct buffer_head *head, enum migrate_mode mode)
{
int expected_count = 0;
void **pslot;
if (!mapping) {
/* Anonymous page without mapping */
if (page_count(page) != 1)
return -EAGAIN;
return MIGRATEPAGE_SUCCESS;
}
spin_lock_irq(&mapping->tree_lock);
pslot = radix_tree_lookup_slot(&mapping->page_tree,
page_index(page));
expected_count = 2 + page_has_private(page);
if (page_count(page) != expected_count ||
radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) {
spin_unlock_irq(&mapping->tree_lock);
return -EAGAIN;
}
if (!page_freeze_refs(page, expected_count)) {
spin_unlock_irq(&mapping->tree_lock);
return -EAGAIN;
}
/*
* In the async migration case of moving a page with buffers, lock the
* buffers using trylock before the mapping is moved. If the mapping
* was moved, we later failed to lock the buffers and could not move
* the mapping back due to an elevated page count, we would have to
* block waiting on other references to be dropped.
*/
if (mode == MIGRATE_ASYNC && head &&
!buffer_migrate_lock_buffers(head, mode)) {
page_unfreeze_refs(page, expected_count);
spin_unlock_irq(&mapping->tree_lock);
return -EAGAIN;
}
/*
* Now we know that no one else is looking at the page.
*/
get_page(newpage); /* add cache reference */
if (PageSwapCache(page)) {
SetPageSwapCache(newpage);
set_page_private(newpage, page_private(page));
}
radix_tree_replace_slot(pslot, newpage);
/*
* Drop cache reference from old page by unfreezing
* to one less reference.
* We know this isn't the last reference.
*/
page_unfreeze_refs(page, expected_count - 1);
/*
* If moved to a different zone then also account
* the page for that zone. Other VM counters will be
* taken care of when we establish references to the
* new page and drop references to the old page.
*
* Note that anonymous pages are accounted for
* via NR_FILE_PAGES and NR_ANON_PAGES if they
* are mapped to swap space.
*/
__dec_zone_page_state(page, NR_FILE_PAGES);
__inc_zone_page_state(newpage, NR_FILE_PAGES);
if (!PageSwapCache(page) && PageSwapBacked(page)) {
__dec_zone_page_state(page, NR_SHMEM);
__inc_zone_page_state(newpage, NR_SHMEM);
}
spin_unlock_irq(&mapping->tree_lock);
return MIGRATEPAGE_SUCCESS;
}
/*
* The expected number of remaining references is the same as that
* of migrate_page_move_mapping().
*/
int migrate_huge_page_move_mapping(struct address_space *mapping,
struct page *newpage, struct page *page)
{
int expected_count;
void **pslot;
if (!mapping) {
if (page_count(page) != 1)
return -EAGAIN;
return MIGRATEPAGE_SUCCESS;
}
spin_lock_irq(&mapping->tree_lock);
pslot = radix_tree_lookup_slot(&mapping->page_tree,
page_index(page));
expected_count = 2 + page_has_private(page);
if (page_count(page) != expected_count ||
radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) {
spin_unlock_irq(&mapping->tree_lock);
return -EAGAIN;
}
if (!page_freeze_refs(page, expected_count)) {
spin_unlock_irq(&mapping->tree_lock);
return -EAGAIN;
}
get_page(newpage);
radix_tree_replace_slot(pslot, newpage);
page_unfreeze_refs(page, expected_count - 1);
spin_unlock_irq(&mapping->tree_lock);
return MIGRATEPAGE_SUCCESS;
}
/*
* Copy the page to its new location
*/
void migrate_page_copy(struct page *newpage, struct page *page)
{
if (PageHuge(page) || PageTransHuge(page))
copy_huge_page(newpage, page);
else
copy_highpage(newpage, page);
if (PageError(page))
SetPageError(newpage);
if (PageReferenced(page))
SetPageReferenced(newpage);
if (PageUptodate(page))
SetPageUptodate(newpage);
if (TestClearPageActive(page)) {
VM_BUG_ON(PageUnevictable(page));
SetPageActive(newpage);
} else if (TestClearPageUnevictable(page))
SetPageUnevictable(newpage);
if (PageChecked(page))
SetPageChecked(newpage);
if (PageMappedToDisk(page))
SetPageMappedToDisk(newpage);
if (PageDirty(page)) {
clear_page_dirty_for_io(page);
/*
* Want to mark the page and the radix tree as dirty, and
* redo the accounting that clear_page_dirty_for_io undid,
* but we can't use set_page_dirty because that function
* is actually a signal that all of the page has become dirty.
* Whereas only part of our page may be dirty.
*/
if (PageSwapBacked(page))
SetPageDirty(newpage);
else
__set_page_dirty_nobuffers(newpage);
}
mlock_migrate_page(newpage, page);
ksm_migrate_page(newpage, page);
/*
* Please do not reorder this without considering how mm/ksm.c's
* get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache().
*/
ClearPageSwapCache(page);
ClearPagePrivate(page);
set_page_private(page, 0);
/*
* If any waiters have accumulated on the new page then
* wake them up.
*/
if (PageWriteback(newpage))
end_page_writeback(newpage);
}
/************************************************************
* Migration functions
***********************************************************/
/* Always fail migration. Used for mappings that are not movable */
int fail_migrate_page(struct address_space *mapping,
struct page *newpage, struct page *page)
{
return -EIO;
}
EXPORT_SYMBOL(fail_migrate_page);
/*
* Common logic to directly migrate a single page suitable for
* pages that do not use PagePrivate/PagePrivate2.
*
* Pages are locked upon entry and exit.
*/
int migrate_page(struct address_space *mapping,
struct page *newpage, struct page *page,
enum migrate_mode mode)
{
int rc;
BUG_ON(PageWriteback(page)); /* Writeback must be complete */
rc = migrate_page_move_mapping(mapping, newpage, page, NULL, mode);
if (rc != MIGRATEPAGE_SUCCESS)
return rc;
migrate_page_copy(newpage, page);
return MIGRATEPAGE_SUCCESS;
}
EXPORT_SYMBOL(migrate_page);
#ifdef CONFIG_BLOCK
/*
* Migration function for pages with buffers. This function can only be used
* if the underlying filesystem guarantees that no other references to "page"
* exist.
*/
int buffer_migrate_page(struct address_space *mapping,
struct page *newpage, struct page *page, enum migrate_mode mode)
{
struct buffer_head *bh, *head;
int rc;
if (!page_has_buffers(page))
return migrate_page(mapping, newpage, page, mode);
head = page_buffers(page);
rc = migrate_page_move_mapping(mapping, newpage, page, head, mode);
if (rc != MIGRATEPAGE_SUCCESS)
return rc;
/*
* In the async case, migrate_page_move_mapping locked the buffers
* with an IRQ-safe spinlock held. In the sync case, the buffers
* need to be locked now
*/
if (mode != MIGRATE_ASYNC)
BUG_ON(!buffer_migrate_lock_buffers(head, mode));
ClearPagePrivate(page);
set_page_private(newpage, page_private(page));
set_page_private(page, 0);
put_page(page);
get_page(newpage);
bh = head;
do {
set_bh_page(bh, newpage, bh_offset(bh));
bh = bh->b_this_page;
} while (bh != head);
SetPagePrivate(newpage);
migrate_page_copy(newpage, page);
bh = head;
do {
unlock_buffer(bh);
put_bh(bh);
bh = bh->b_this_page;
} while (bh != head);
return MIGRATEPAGE_SUCCESS;
}
EXPORT_SYMBOL(buffer_migrate_page);
#endif
/*
* Writeback a page to clean the dirty state
*/
static int writeout(struct address_space *mapping, struct page *page)
{
struct writeback_control wbc = {
.sync_mode = WB_SYNC_NONE,
.nr_to_write = 1,
.range_start = 0,
.range_end = LLONG_MAX,
.for_reclaim = 1
};
int rc;
if (!mapping->a_ops->writepage)
/* No write method for the address space */
return -EINVAL;
if (!clear_page_dirty_for_io(page))
/* Someone else already triggered a write */
return -EAGAIN;
/*
* A dirty page may imply that the underlying filesystem has
* the page on some queue. So the page must be clean for
* migration. Writeout may mean we loose the lock and the
* page state is no longer what we checked for earlier.
* At this point we know that the migration attempt cannot
* be successful.
*/
remove_migration_ptes(page, page);
rc = mapping->a_ops->writepage(page, &wbc);
if (rc != AOP_WRITEPAGE_ACTIVATE)
/* unlocked. Relock */
lock_page(page);
return (rc < 0) ? -EIO : -EAGAIN;
}
/*
* Default handling if a filesystem does not provide a migration function.
*/
static int fallback_migrate_page(struct address_space *mapping,
struct page *newpage, struct page *page, enum migrate_mode mode)
{
if (PageDirty(page)) {
/* Only writeback pages in full synchronous migration */
if (mode != MIGRATE_SYNC)
return -EBUSY;
return writeout(mapping, page);
}
/*
* Buffers may be managed in a filesystem specific way.
* We must have no buffers or drop them.
*/
if (page_has_private(page) &&
!try_to_release_page(page, GFP_KERNEL))
return -EAGAIN;
return migrate_page(mapping, newpage, page, mode);
}
/*
* Move a page to a newly allocated page
* The page is locked and all ptes have been successfully removed.
*
* The new page will have replaced the old page if this function
* is successful.
*
* Return value:
* < 0 - error code
* MIGRATEPAGE_SUCCESS - success
*/
static int move_to_new_page(struct page *newpage, struct page *page,
int remap_swapcache, enum migrate_mode mode)
{
struct address_space *mapping;
int rc;
/*
* Block others from accessing the page when we get around to
* establishing additional references. We are the only one
* holding a reference to the new page at this point.
*/
if (!trylock_page(newpage))
BUG();
/* Prepare mapping for the new page.*/
newpage->index = page->index;
newpage->mapping = page->mapping;
if (PageSwapBacked(page))
SetPageSwapBacked(newpage);
mapping = page_mapping(page);
if (!mapping)
rc = migrate_page(mapping, newpage, page, mode);
else if (mapping->a_ops->migratepage)
/*
* Most pages have a mapping and most filesystems provide a
* migratepage callback. Anonymous pages are part of swap
* space which also has its own migratepage callback. This
* is the most common path for page migration.
*/
rc = mapping->a_ops->migratepage(mapping,
newpage, page, mode);
else
rc = fallback_migrate_page(mapping, newpage, page, mode);
if (rc != MIGRATEPAGE_SUCCESS) {
newpage->mapping = NULL;
} else {
if (remap_swapcache)
remove_migration_ptes(page, newpage);
page->mapping = NULL;
}
unlock_page(newpage);
return rc;
}
static int __unmap_and_move(struct page *page, struct page *newpage,
int force, enum migrate_mode mode)
{
int rc = -EAGAIN;
int remap_swapcache = 1;
struct mem_cgroup *mem;
struct anon_vma *anon_vma = NULL;
if (!trylock_page(page)) {
if (!force || mode == MIGRATE_ASYNC)
goto out;
/*
* It's not safe for direct compaction to call lock_page.
* For example, during page readahead pages are added locked
* to the LRU. Later, when the IO completes the pages are
* marked uptodate and unlocked. However, the queueing
* could be merging multiple pages for one bio (e.g.
* mpage_readpages). If an allocation happens for the
* second or third page, the process can end up locking
* the same page twice and deadlocking. Rather than
* trying to be clever about what pages can be locked,
* avoid the use of lock_page for direct compaction
* altogether.
*/
if (current->flags & PF_MEMALLOC)
goto out;
lock_page(page);
}
/* charge against new page */
mem_cgroup_prepare_migration(page, newpage, &mem);
if (PageWriteback(page)) {
/*
* Only in the case of a full synchronous migration is it
* necessary to wait for PageWriteback. In the async case,
* the retry loop is too short and in the sync-light case,
* the overhead of stalling is too much
*/
if (mode != MIGRATE_SYNC) {
rc = -EBUSY;
goto uncharge;
}
if (!force)
goto uncharge;
wait_on_page_writeback(page);
}
/*
* By try_to_unmap(), page->mapcount goes down to 0 here. In this case,
* we cannot notice that anon_vma is freed while we migrates a page.
* This get_anon_vma() delays freeing anon_vma pointer until the end
* of migration. File cache pages are no problem because of page_lock()
* File Caches may use write_page() or lock_page() in migration, then,
* just care Anon page here.
*/
if (PageAnon(page) && !PageKsm(page)) {
/*
* Only page_lock_anon_vma_read() understands the subtleties of
* getting a hold on an anon_vma from outside one of its mms.
*/
anon_vma = page_get_anon_vma(page);
if (anon_vma) {
/*
* Anon page
*/
} else if (PageSwapCache(page)) {
/*
* We cannot be sure that the anon_vma of an unmapped
* swapcache page is safe to use because we don't
* know in advance if the VMA that this page belonged
* to still exists. If the VMA and others sharing the
* data have been freed, then the anon_vma could
* already be invalid.
*
* To avoid this possibility, swapcache pages get
* migrated but are not remapped when migration
* completes
*/
remap_swapcache = 0;
} else {
goto uncharge;
}
}
if (unlikely(balloon_page_movable(page))) {
/*
* A ballooned page does not need any special attention from
* physical to virtual reverse mapping procedures.
* Skip any attempt to unmap PTEs or to remap swap cache,
* in order to avoid burning cycles at rmap level, and perform
* the page migration right away (proteced by page lock).
*/
rc = balloon_page_migrate(newpage, page, mode);
goto uncharge;
}
/*
* Corner case handling:
* 1. When a new swap-cache page is read into, it is added to the LRU
* and treated as swapcache but it has no rmap yet.
* Calling try_to_unmap() against a page->mapping==NULL page will
* trigger a BUG. So handle it here.
* 2. An orphaned page (see truncate_complete_page) might have
* fs-private metadata. The page can be picked up due to memory
* offlining. Everywhere else except page reclaim, the page is
* invisible to the vm, so the page can not be migrated. So try to
* free the metadata, so the page can be freed.
*/
if (!page->mapping) {
VM_BUG_ON(PageAnon(page));
if (page_has_private(page)) {
try_to_free_buffers(page);
goto uncharge;
}
goto skip_unmap;
}
/* Establish migration ptes or remove ptes */
try_to_unmap(page, TTU_MIGRATION|TTU_IGNORE_MLOCK|TTU_IGNORE_ACCESS);
skip_unmap:
if (!page_mapped(page))
rc = move_to_new_page(newpage, page, remap_swapcache, mode);
if (rc && remap_swapcache)
remove_migration_ptes(page, page);
/* Drop an anon_vma reference if we took one */
if (anon_vma)
put_anon_vma(anon_vma);
uncharge:
mem_cgroup_end_migration(mem, page, newpage,
(rc == MIGRATEPAGE_SUCCESS ||
rc == MIGRATEPAGE_BALLOON_SUCCESS));
unlock_page(page);
out:
return rc;
}
/*
* Obtain the lock on page, remove all ptes and migrate the page
* to the newly allocated page in newpage.
*/
static int unmap_and_move(new_page_t get_new_page, unsigned long private,
struct page *page, int force, enum migrate_mode mode)
{
int rc = 0;
int *result = NULL;
struct page *newpage = get_new_page(page, private, &result);
if (!newpage)
return -ENOMEM;
if (page_count(page) == 1) {
/* page was freed from under us. So we are done. */
goto out;
}
if (unlikely(PageTransHuge(page)))
if (unlikely(split_huge_page(page)))
goto out;
rc = __unmap_and_move(page, newpage, force, mode);
if (unlikely(rc == MIGRATEPAGE_BALLOON_SUCCESS)) {
/*
* A ballooned page has been migrated already.
* Now, it's the time to wrap-up counters,
* handle the page back to Buddy and return.
*/
dec_zone_page_state(page, NR_ISOLATED_ANON +
page_is_file_cache(page));
balloon_page_free(page);
return MIGRATEPAGE_SUCCESS;
}
out:
if (rc != -EAGAIN) {
/*
* A page that has been migrated has all references
* removed and will be freed. A page that has not been
* migrated will have kepts its references and be
* restored.
*/
list_del(&page->lru);
dec_zone_page_state(page, NR_ISOLATED_ANON +
page_is_file_cache(page));
putback_lru_page(page);
}
/*
* Move the new page to the LRU. If migration was not successful
* then this will free the page.
*/
putback_lru_page(newpage);
if (result) {
if (rc)
*result = rc;
else
*result = page_to_nid(newpage);
}
return rc;
}
/*
* Counterpart of unmap_and_move_page() for hugepage migration.
*
* This function doesn't wait the completion of hugepage I/O
* because there is no race between I/O and migration for hugepage.
* Note that currently hugepage I/O occurs only in direct I/O
* where no lock is held and PG_writeback is irrelevant,
* and writeback status of all subpages are counted in the reference
* count of the head page (i.e. if all subpages of a 2MB hugepage are
* under direct I/O, the reference of the head page is 512 and a bit more.)
* This means that when we try to migrate hugepage whose subpages are
* doing direct I/O, some references remain after try_to_unmap() and
* hugepage migration fails without data corruption.
*
* There is also no race when direct I/O is issued on the page under migration,
* because then pte is replaced with migration swap entry and direct I/O code
* will wait in the page fault for migration to complete.
*/
static int unmap_and_move_huge_page(new_page_t get_new_page,
unsigned long private, struct page *hpage,
int force, enum migrate_mode mode)
{
int rc = 0;
int *result = NULL;
struct page *new_hpage = get_new_page(hpage, private, &result);
struct anon_vma *anon_vma = NULL;
if (!new_hpage)
return -ENOMEM;
rc = -EAGAIN;
if (!trylock_page(hpage)) {
if (!force || mode != MIGRATE_SYNC)
goto out;
lock_page(hpage);
}
if (PageAnon(hpage))
anon_vma = page_get_anon_vma(hpage);
try_to_unmap(hpage, TTU_MIGRATION|TTU_IGNORE_MLOCK|TTU_IGNORE_ACCESS);
if (!page_mapped(hpage))
rc = move_to_new_page(new_hpage, hpage, 1, mode);
if (rc)
remove_migration_ptes(hpage, hpage);
if (anon_vma)
put_anon_vma(anon_vma);
if (!rc)
hugetlb_cgroup_migrate(hpage, new_hpage);
unlock_page(hpage);
out:
put_page(new_hpage);
if (result) {
if (rc)
*result = rc;
else
*result = page_to_nid(new_hpage);
}
return rc;
}
/*
* migrate_pages - migrate the pages specified in a list, to the free pages
* supplied as the target for the page migration
*
* @from: The list of pages to be migrated.
* @get_new_page: The function used to allocate free pages to be used
* as the target of the page migration.
* @private: Private data to be passed on to get_new_page()
* @mode: The migration mode that specifies the constraints for
* page migration, if any.
* @reason: The reason for page migration.
*
* The function returns after 10 attempts or if no pages are movable any more
* because the list has become empty or no retryable pages exist any more.
* The caller should call putback_lru_pages() to return pages to the LRU
* or free list only if ret != 0.
*
* Returns the number of pages that were not migrated, or an error code.
*/
int migrate_pages(struct list_head *from, new_page_t get_new_page,
unsigned long private, enum migrate_mode mode, int reason)
{
int retry = 1;
int nr_failed = 0;
int nr_succeeded = 0;
int pass = 0;
struct page *page;
struct page *page2;
int swapwrite = current->flags & PF_SWAPWRITE;
int rc;
if (!swapwrite)
current->flags |= PF_SWAPWRITE;
for(pass = 0; pass < 10 && retry; pass++) {
retry = 0;
list_for_each_entry_safe(page, page2, from, lru) {
cond_resched();
rc = unmap_and_move(get_new_page, private,
page, pass > 2, mode);
switch(rc) {
case -ENOMEM:
goto out;
case -EAGAIN:
retry++;
break;
case MIGRATEPAGE_SUCCESS:
nr_succeeded++;
break;
default:
/* Permanent failure */
nr_failed++;
break;
}
}
}
rc = nr_failed + retry;
out:
if (nr_succeeded)
count_vm_events(PGMIGRATE_SUCCESS, nr_succeeded);
if (nr_failed)
count_vm_events(PGMIGRATE_FAIL, nr_failed);
trace_mm_migrate_pages(nr_succeeded, nr_failed, mode, reason);
if (!swapwrite)
current->flags &= ~PF_SWAPWRITE;
return rc;
}
int migrate_huge_page(struct page *hpage, new_page_t get_new_page,
unsigned long private, enum migrate_mode mode)
{
int pass, rc;
for (pass = 0; pass < 10; pass++) {
rc = unmap_and_move_huge_page(get_new_page, private,
hpage, pass > 2, mode);
switch (rc) {
case -ENOMEM:
goto out;
case -EAGAIN:
/* try again */
cond_resched();
break;
case MIGRATEPAGE_SUCCESS:
goto out;
default:
rc = -EIO;
goto out;
}
}
out:
return rc;
}
#ifdef CONFIG_NUMA
/*
* Move a list of individual pages
*/
struct page_to_node {
unsigned long addr;
struct page *page;
int node;
int status;
};
static struct page *new_page_node(struct page *p, unsigned long private,
int **result)
{
struct page_to_node *pm = (struct page_to_node *)private;
while (pm->node != MAX_NUMNODES && pm->page != p)
pm++;
if (pm->node == MAX_NUMNODES)
return NULL;
*result = &pm->status;
return alloc_pages_exact_node(pm->node,
GFP_HIGHUSER_MOVABLE | GFP_THISNODE, 0);
}
/*
* Move a set of pages as indicated in the pm array. The addr
* field must be set to the virtual address of the page to be moved
* and the node number must contain a valid target node.
* The pm array ends with node = MAX_NUMNODES.
*/
static int do_move_page_to_node_array(struct mm_struct *mm,
struct page_to_node *pm,
int migrate_all)
{
int err;
struct page_to_node *pp;
LIST_HEAD(pagelist);
down_read(&mm->mmap_sem);
/*
* Build a list of pages to migrate
*/
for (pp = pm; pp->node != MAX_NUMNODES; pp++) {
struct vm_area_struct *vma;
struct page *page;
err = -EFAULT;
vma = find_vma(mm, pp->addr);
if (!vma || pp->addr < vma->vm_start || !vma_migratable(vma))
goto set_status;
page = follow_page(vma, pp->addr, FOLL_GET|FOLL_SPLIT);
err = PTR_ERR(page);
if (IS_ERR(page))
goto set_status;
err = -ENOENT;
if (!page)
goto set_status;
/* Use PageReserved to check for zero page */
if (PageReserved(page))
goto put_and_set;
pp->page = page;
err = page_to_nid(page);
if (err == pp->node)
/*
* Node already in the right place
*/
goto put_and_set;
err = -EACCES;
if (page_mapcount(page) > 1 &&
!migrate_all)
goto put_and_set;
err = isolate_lru_page(page);
if (!err) {
list_add_tail(&page->lru, &pagelist);
inc_zone_page_state(page, NR_ISOLATED_ANON +
page_is_file_cache(page));
}
put_and_set:
/*
* Either remove the duplicate refcount from
* isolate_lru_page() or drop the page ref if it was
* not isolated.
*/
put_page(page);
set_status:
pp->status = err;
}
err = 0;
if (!list_empty(&pagelist)) {
err = migrate_pages(&pagelist, new_page_node,
(unsigned long)pm, MIGRATE_SYNC, MR_SYSCALL);
if (err)
putback_lru_pages(&pagelist);
}
up_read(&mm->mmap_sem);
return err;
}
/*
* Migrate an array of page address onto an array of nodes and fill
* the corresponding array of status.
*/
static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes,
unsigned long nr_pages,
const void __user * __user *pages,
const int __user *nodes,
int __user *status, int flags)
{
struct page_to_node *pm;
unsigned long chunk_nr_pages;
unsigned long chunk_start;
int err;
err = -ENOMEM;
pm = (struct page_to_node *)__get_free_page(GFP_KERNEL);
if (!pm)
goto out;
migrate_prep();
/*
* Store a chunk of page_to_node array in a page,
* but keep the last one as a marker
*/
chunk_nr_pages = (PAGE_SIZE / sizeof(struct page_to_node)) - 1;
for (chunk_start = 0;
chunk_start < nr_pages;
chunk_start += chunk_nr_pages) {
int j;
if (chunk_start + chunk_nr_pages > nr_pages)
chunk_nr_pages = nr_pages - chunk_start;
/* fill the chunk pm with addrs and nodes from user-space */
for (j = 0; j < chunk_nr_pages; j++) {
const void __user *p;
int node;
err = -EFAULT;
if (get_user(p, pages + j + chunk_start))
goto out_pm;
pm[j].addr = (unsigned long) p;
if (get_user(node, nodes + j + chunk_start))
goto out_pm;
err = -ENODEV;
if (node < 0 || node >= MAX_NUMNODES)
goto out_pm;
if (!node_state(node, N_MEMORY))
goto out_pm;
err = -EACCES;
if (!node_isset(node, task_nodes))
goto out_pm;
pm[j].node = node;
}
/* End marker for this chunk */
pm[chunk_nr_pages].node = MAX_NUMNODES;
/* Migrate this chunk */
err = do_move_page_to_node_array(mm, pm,
flags & MPOL_MF_MOVE_ALL);
if (err < 0)
goto out_pm;
/* Return status information */
for (j = 0; j < chunk_nr_pages; j++)
if (put_user(pm[j].status, status + j + chunk_start)) {
err = -EFAULT;
goto out_pm;
}
}
err = 0;
out_pm:
free_page((unsigned long)pm);
out:
return err;
}
/*
* Determine the nodes of an array of pages and store it in an array of status.
*/
static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages,
const void __user **pages, int *status)
{
unsigned long i;
down_read(&mm->mmap_sem);
for (i = 0; i < nr_pages; i++) {
unsigned long addr = (unsigned long)(*pages);
struct vm_area_struct *vma;
struct page *page;
int err = -EFAULT;
vma = find_vma(mm, addr);
if (!vma || addr < vma->vm_start)
goto set_status;
page = follow_page(vma, addr, 0);
err = PTR_ERR(page);
if (IS_ERR(page))
goto set_status;
err = -ENOENT;
/* Use PageReserved to check for zero page */
if (!page || PageReserved(page))
goto set_status;
err = page_to_nid(page);
set_status:
*status = err;
pages++;
status++;
}
up_read(&mm->mmap_sem);
}
/*
* Determine the nodes of a user array of pages and store it in
* a user array of status.
*/
static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages,
const void __user * __user *pages,
int __user *status)
{
#define DO_PAGES_STAT_CHUNK_NR 16
const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR];
int chunk_status[DO_PAGES_STAT_CHUNK_NR];
while (nr_pages) {
unsigned long chunk_nr;
chunk_nr = nr_pages;
if (chunk_nr > DO_PAGES_STAT_CHUNK_NR)
chunk_nr = DO_PAGES_STAT_CHUNK_NR;
if (copy_from_user(chunk_pages, pages, chunk_nr * sizeof(*chunk_pages)))
break;
do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status);
if (copy_to_user(status, chunk_status, chunk_nr * sizeof(*status)))
break;
pages += chunk_nr;
status += chunk_nr;
nr_pages -= chunk_nr;
}
return nr_pages ? -EFAULT : 0;
}
/*
* Move a list of pages in the address space of the currently executing
* process.
*/
SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages,
const void __user * __user *, pages,
const int __user *, nodes,
int __user *, status, int, flags)
{
const struct cred *cred = current_cred(), *tcred;
struct task_struct *task;
struct mm_struct *mm;
int err;
nodemask_t task_nodes;
/* Check flags */
if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL))
return -EINVAL;
if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE))
return -EPERM;
/* Find the mm_struct */
rcu_read_lock();
task = pid ? find_task_by_vpid(pid) : current;
if (!task) {
rcu_read_unlock();
return -ESRCH;
}
get_task_struct(task);
/*
* Check if this process has the right to modify the specified
* process. The right exists if the process has administrative
* capabilities, superuser privileges or the same
* userid as the target process.
*/
tcred = __task_cred(task);
if (!uid_eq(cred->euid, tcred->suid) && !uid_eq(cred->euid, tcred->uid) &&
!uid_eq(cred->uid, tcred->suid) && !uid_eq(cred->uid, tcred->uid) &&
!capable(CAP_SYS_NICE)) {
rcu_read_unlock();
err = -EPERM;
goto out;
}
rcu_read_unlock();
err = security_task_movememory(task);
if (err)
goto out;
task_nodes = cpuset_mems_allowed(task);
mm = get_task_mm(task);
put_task_struct(task);
if (!mm)
return -EINVAL;
if (nodes)
err = do_pages_move(mm, task_nodes, nr_pages, pages,
nodes, status, flags);
else
err = do_pages_stat(mm, nr_pages, pages, status);
mmput(mm);
return err;
out:
put_task_struct(task);
return err;
}
/*
* Call migration functions in the vma_ops that may prepare
* memory in a vm for migration. migration functions may perform
* the migration for vmas that do not have an underlying page struct.
*/
int migrate_vmas(struct mm_struct *mm, const nodemask_t *to,
const nodemask_t *from, unsigned long flags)
{
struct vm_area_struct *vma;
int err = 0;
for (vma = mm->mmap; vma && !err; vma = vma->vm_next) {
if (vma->vm_ops && vma->vm_ops->migrate) {
err = vma->vm_ops->migrate(vma, to, from, flags);
if (err)
break;
}
}
return err;
}
#ifdef CONFIG_NUMA_BALANCING
/*
* Returns true if this is a safe migration target node for misplaced NUMA
* pages. Currently it only checks the watermarks which crude
*/
static bool migrate_balanced_pgdat(struct pglist_data *pgdat,
unsigned long nr_migrate_pages)
{
int z;
for (z = pgdat->nr_zones - 1; z >= 0; z--) {
struct zone *zone = pgdat->node_zones + z;
if (!populated_zone(zone))
continue;
if (zone->all_unreclaimable)
continue;
/* Avoid waking kswapd by allocating pages_to_migrate pages. */
if (!zone_watermark_ok(zone, 0,
high_wmark_pages(zone) +
nr_migrate_pages,
0, 0))
continue;
return true;
}
return false;
}
static struct page *alloc_misplaced_dst_page(struct page *page,
unsigned long data,
int **result)
{
int nid = (int) data;
struct page *newpage;
newpage = alloc_pages_exact_node(nid,
(GFP_HIGHUSER_MOVABLE | GFP_THISNODE |
__GFP_NOMEMALLOC | __GFP_NORETRY |
__GFP_NOWARN) &
~GFP_IOFS, 0);
if (newpage)
page_nid_xchg_last(newpage, page_nid_last(page));
return newpage;
}
/*
* page migration rate limiting control.
* Do not migrate more than @pages_to_migrate in a @migrate_interval_millisecs
* window of time. Default here says do not migrate more than 1280M per second.
* If a node is rate-limited then PTE NUMA updates are also rate-limited. However
* as it is faults that reset the window, pte updates will happen unconditionally
* if there has not been a fault since @pteupdate_interval_millisecs after the
* throttle window closed.
*/
static unsigned int migrate_interval_millisecs __read_mostly = 100;
static unsigned int pteupdate_interval_millisecs __read_mostly = 1000;
static unsigned int ratelimit_pages __read_mostly = 128 << (20 - PAGE_SHIFT);
/* Returns true if NUMA migration is currently rate limited */
bool migrate_ratelimited(int node)
{
pg_data_t *pgdat = NODE_DATA(node);
if (time_after(jiffies, pgdat->numabalancing_migrate_next_window +
msecs_to_jiffies(pteupdate_interval_millisecs)))
return false;
if (pgdat->numabalancing_migrate_nr_pages < ratelimit_pages)
return false;
return true;
}
/* Returns true if the node is migrate rate-limited after the update */
bool numamigrate_update_ratelimit(pg_data_t *pgdat, unsigned long nr_pages)
{
bool rate_limited = false;
/*
* Rate-limit the amount of data that is being migrated to a node.
* Optimal placement is no good if the memory bus is saturated and
* all the time is being spent migrating!
*/
spin_lock(&pgdat->numabalancing_migrate_lock);
if (time_after(jiffies, pgdat->numabalancing_migrate_next_window)) {
pgdat->numabalancing_migrate_nr_pages = 0;
pgdat->numabalancing_migrate_next_window = jiffies +
msecs_to_jiffies(migrate_interval_millisecs);
}
if (pgdat->numabalancing_migrate_nr_pages > ratelimit_pages)
rate_limited = true;
else
pgdat->numabalancing_migrate_nr_pages += nr_pages;
spin_unlock(&pgdat->numabalancing_migrate_lock);
return rate_limited;
}
int numamigrate_isolate_page(pg_data_t *pgdat, struct page *page)
{
int page_lru;
VM_BUG_ON(compound_order(page) && !PageTransHuge(page));
/* Avoid migrating to a node that is nearly full */
if (!migrate_balanced_pgdat(pgdat, 1UL << compound_order(page)))
return 0;
if (isolate_lru_page(page))
return 0;
/*
* migrate_misplaced_transhuge_page() skips page migration's usual
* check on page_count(), so we must do it here, now that the page
* has been isolated: a GUP pin, or any other pin, prevents migration.
* The expected page count is 3: 1 for page's mapcount and 1 for the
* caller's pin and 1 for the reference taken by isolate_lru_page().
*/
if (PageTransHuge(page) && page_count(page) != 3) {
putback_lru_page(page);
return 0;
}
page_lru = page_is_file_cache(page);
mod_zone_page_state(page_zone(page), NR_ISOLATED_ANON + page_lru,
hpage_nr_pages(page));
/*
* Isolating the page has taken another reference, so the
* caller's reference can be safely dropped without the page
* disappearing underneath us during migration.
*/
put_page(page);
return 1;
}
/*
* Attempt to migrate a misplaced page to the specified destination
* node. Caller is expected to have an elevated reference count on
* the page that will be dropped by this function before returning.
*/
int migrate_misplaced_page(struct page *page, int node)
{
pg_data_t *pgdat = NODE_DATA(node);
int isolated;
int nr_remaining;
LIST_HEAD(migratepages);
/*
* Don't migrate pages that are mapped in multiple processes.
* TODO: Handle false sharing detection instead of this hammer
*/
if (page_mapcount(page) != 1)
goto out;
/*
* Rate-limit the amount of data that is being migrated to a node.
* Optimal placement is no good if the memory bus is saturated and
* all the time is being spent migrating!
*/
if (numamigrate_update_ratelimit(pgdat, 1))
goto out;
isolated = numamigrate_isolate_page(pgdat, page);
if (!isolated)
goto out;
list_add(&page->lru, &migratepages);
nr_remaining = migrate_pages(&migratepages, alloc_misplaced_dst_page,
node, MIGRATE_ASYNC, MR_NUMA_MISPLACED);
if (nr_remaining) {
putback_lru_pages(&migratepages);
isolated = 0;
} else
count_vm_numa_event(NUMA_PAGE_MIGRATE);
BUG_ON(!list_empty(&migratepages));
return isolated;
out:
put_page(page);
return 0;
}
#endif /* CONFIG_NUMA_BALANCING */
#if defined(CONFIG_NUMA_BALANCING) && defined(CONFIG_TRANSPARENT_HUGEPAGE)
/*
* Migrates a THP to a given target node. page must be locked and is unlocked
* before returning.
*/
int migrate_misplaced_transhuge_page(struct mm_struct *mm,
struct vm_area_struct *vma,
pmd_t *pmd, pmd_t entry,
unsigned long address,
struct page *page, int node)
{
unsigned long haddr = address & HPAGE_PMD_MASK;
pg_data_t *pgdat = NODE_DATA(node);
int isolated = 0;
struct page *new_page = NULL;
struct mem_cgroup *memcg = NULL;
int page_lru = page_is_file_cache(page);
/*
* Don't migrate pages that are mapped in multiple processes.
* TODO: Handle false sharing detection instead of this hammer
*/
if (page_mapcount(page) != 1)
goto out_dropref;
/*
* Rate-limit the amount of data that is being migrated to a node.
* Optimal placement is no good if the memory bus is saturated and
* all the time is being spent migrating!
*/
if (numamigrate_update_ratelimit(pgdat, HPAGE_PMD_NR))
goto out_dropref;
new_page = alloc_pages_node(node,
(GFP_TRANSHUGE | GFP_THISNODE) & ~__GFP_WAIT, HPAGE_PMD_ORDER);
if (!new_page)
goto out_fail;
page_nid_xchg_last(new_page, page_nid_last(page));
isolated = numamigrate_isolate_page(pgdat, page);
if (!isolated) {
put_page(new_page);
goto out_fail;
}
/* Prepare a page as a migration target */
__set_page_locked(new_page);
SetPageSwapBacked(new_page);
/* anon mapping, we can simply copy page->mapping to the new page: */
new_page->mapping = page->mapping;
new_page->index = page->index;
migrate_page_copy(new_page, page);
WARN_ON(PageLRU(new_page));
/* Recheck the target PMD */
spin_lock(&mm->page_table_lock);
if (unlikely(!pmd_same(*pmd, entry))) {
spin_unlock(&mm->page_table_lock);
/* Reverse changes made by migrate_page_copy() */
if (TestClearPageActive(new_page))
SetPageActive(page);
if (TestClearPageUnevictable(new_page))
SetPageUnevictable(page);
mlock_migrate_page(page, new_page);
unlock_page(new_page);
put_page(new_page); /* Free it */
/* Retake the callers reference and putback on LRU */
get_page(page);
putback_lru_page(page);
mod_zone_page_state(page_zone(page),
NR_ISOLATED_ANON + page_lru, -HPAGE_PMD_NR);
goto out_unlock;
}
/*
* Traditional migration needs to prepare the memcg charge
* transaction early to prevent the old page from being
* uncharged when installing migration entries. Here we can
* save the potential rollback and start the charge transfer
* only when migration is already known to end successfully.
*/
mem_cgroup_prepare_migration(page, new_page, &memcg);
entry = mk_pmd(new_page, vma->vm_page_prot);
entry = pmd_mknonnuma(entry);
entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
entry = pmd_mkhuge(entry);
pmdp_clear_flush(vma, haddr, pmd);
set_pmd_at(mm, haddr, pmd, entry);
page_add_new_anon_rmap(new_page, vma, haddr);
update_mmu_cache_pmd(vma, address, &entry);
page_remove_rmap(page);
/*
* Finish the charge transaction under the page table lock to
* prevent split_huge_page() from dividing up the charge
* before it's fully transferred to the new page.
*/
mem_cgroup_end_migration(memcg, page, new_page, true);
spin_unlock(&mm->page_table_lock);
unlock_page(new_page);
unlock_page(page);
put_page(page); /* Drop the rmap reference */
put_page(page); /* Drop the LRU isolation reference */
count_vm_events(PGMIGRATE_SUCCESS, HPAGE_PMD_NR);
count_vm_numa_events(NUMA_PAGE_MIGRATE, HPAGE_PMD_NR);
mod_zone_page_state(page_zone(page),
NR_ISOLATED_ANON + page_lru,
-HPAGE_PMD_NR);
return isolated;
out_fail:
count_vm_events(PGMIGRATE_FAIL, HPAGE_PMD_NR);
out_dropref:
entry = pmd_mknonnuma(entry);
set_pmd_at(mm, haddr, pmd, entry);
update_mmu_cache_pmd(vma, address, &entry);
out_unlock:
unlock_page(page);
put_page(page);
return 0;
}
#endif /* CONFIG_NUMA_BALANCING */
#endif /* CONFIG_NUMA */
| gpl-2.0 |
Defector/lu6200_kernel | fs/notify/fanotify/fanotify.c | 881 | 6227 | #include <linux/fanotify.h>
#include <linux/fdtable.h>
#include <linux/fsnotify_backend.h>
#include <linux/init.h>
#include <linux/jiffies.h>
#include <linux/kernel.h> /* UINT_MAX */
#include <linux/mount.h>
#include <linux/sched.h>
#include <linux/types.h>
#include <linux/wait.h>
static bool should_merge(struct fsnotify_event *old, struct fsnotify_event *new)
{
pr_debug("%s: old=%p new=%p\n", __func__, old, new);
if (old->to_tell == new->to_tell &&
old->data_type == new->data_type &&
old->tgid == new->tgid) {
switch (old->data_type) {
case (FSNOTIFY_EVENT_PATH):
if ((old->path.mnt == new->path.mnt) &&
(old->path.dentry == new->path.dentry))
return true;
break;
case (FSNOTIFY_EVENT_NONE):
return true;
default:
BUG();
};
}
return false;
}
/* and the list better be locked by something too! */
static struct fsnotify_event *fanotify_merge(struct list_head *list,
struct fsnotify_event *event)
{
struct fsnotify_event_holder *test_holder;
struct fsnotify_event *test_event = NULL;
struct fsnotify_event *new_event;
pr_debug("%s: list=%p event=%p\n", __func__, list, event);
list_for_each_entry_reverse(test_holder, list, event_list) {
if (should_merge(test_holder->event, event)) {
test_event = test_holder->event;
break;
}
}
if (!test_event)
return NULL;
fsnotify_get_event(test_event);
/* if they are exactly the same we are done */
if (test_event->mask == event->mask)
return test_event;
/*
* if the refcnt == 2 this is the only queue
* for this event and so we can update the mask
* in place.
*/
if (atomic_read(&test_event->refcnt) == 2) {
test_event->mask |= event->mask;
return test_event;
}
new_event = fsnotify_clone_event(test_event);
/* done with test_event */
fsnotify_put_event(test_event);
/* couldn't allocate memory, merge was not possible */
if (unlikely(!new_event))
return ERR_PTR(-ENOMEM);
/* build new event and replace it on the list */
new_event->mask = (test_event->mask | event->mask);
fsnotify_replace_event(test_holder, new_event);
/* we hold a reference on new_event from clone_event */
return new_event;
}
#ifdef CONFIG_FANOTIFY_ACCESS_PERMISSIONS
static int fanotify_get_response_from_access(struct fsnotify_group *group,
struct fsnotify_event *event)
{
int ret;
pr_debug("%s: group=%p event=%p\n", __func__, group, event);
wait_event(group->fanotify_data.access_waitq, event->response ||
atomic_read(&group->fanotify_data.bypass_perm));
if (!event->response) /* bypass_perm set */
return 0;
/* userspace responded, convert to something usable */
spin_lock(&event->lock);
switch (event->response) {
case FAN_ALLOW:
ret = 0;
break;
case FAN_DENY:
default:
ret = -EPERM;
}
event->response = 0;
spin_unlock(&event->lock);
pr_debug("%s: group=%p event=%p about to return ret=%d\n", __func__,
group, event, ret);
return ret;
}
#endif
static int fanotify_handle_event(struct fsnotify_group *group,
struct fsnotify_mark *inode_mark,
struct fsnotify_mark *fanotify_mark,
struct fsnotify_event *event)
{
int ret = 0;
struct fsnotify_event *notify_event = NULL;
BUILD_BUG_ON(FAN_ACCESS != FS_ACCESS);
BUILD_BUG_ON(FAN_MODIFY != FS_MODIFY);
BUILD_BUG_ON(FAN_CLOSE_NOWRITE != FS_CLOSE_NOWRITE);
BUILD_BUG_ON(FAN_CLOSE_WRITE != FS_CLOSE_WRITE);
BUILD_BUG_ON(FAN_OPEN != FS_OPEN);
BUILD_BUG_ON(FAN_EVENT_ON_CHILD != FS_EVENT_ON_CHILD);
BUILD_BUG_ON(FAN_Q_OVERFLOW != FS_Q_OVERFLOW);
BUILD_BUG_ON(FAN_OPEN_PERM != FS_OPEN_PERM);
BUILD_BUG_ON(FAN_ACCESS_PERM != FS_ACCESS_PERM);
BUILD_BUG_ON(FAN_ONDIR != FS_ISDIR);
pr_debug("%s: group=%p event=%p\n", __func__, group, event);
notify_event = fsnotify_add_notify_event(group, event, NULL, fanotify_merge);
if (IS_ERR(notify_event))
return PTR_ERR(notify_event);
#ifdef CONFIG_FANOTIFY_ACCESS_PERMISSIONS
if (event->mask & FAN_ALL_PERM_EVENTS) {
/* if we merged we need to wait on the new event */
if (notify_event)
event = notify_event;
ret = fanotify_get_response_from_access(group, event);
}
#endif
if (notify_event)
fsnotify_put_event(notify_event);
return ret;
}
static bool fanotify_should_send_event(struct fsnotify_group *group,
struct inode *to_tell,
struct fsnotify_mark *inode_mark,
struct fsnotify_mark *vfsmnt_mark,
__u32 event_mask, void *data, int data_type)
{
__u32 marks_mask, marks_ignored_mask;
struct path *path = data;
pr_debug("%s: group=%p to_tell=%p inode_mark=%p vfsmnt_mark=%p "
"mask=%x data=%p data_type=%d\n", __func__, group, to_tell,
inode_mark, vfsmnt_mark, event_mask, data, data_type);
/* if we don't have enough info to send an event to userspace say no */
if (data_type != FSNOTIFY_EVENT_PATH)
return false;
/* sorry, fanotify only gives a damn about files and dirs */
if (!S_ISREG(path->dentry->d_inode->i_mode) &&
!S_ISDIR(path->dentry->d_inode->i_mode))
return false;
if (inode_mark && vfsmnt_mark) {
marks_mask = (vfsmnt_mark->mask | inode_mark->mask);
marks_ignored_mask = (vfsmnt_mark->ignored_mask | inode_mark->ignored_mask);
} else if (inode_mark) {
/*
* if the event is for a child and this inode doesn't care about
* events on the child, don't send it!
*/
if ((event_mask & FS_EVENT_ON_CHILD) &&
!(inode_mark->mask & FS_EVENT_ON_CHILD))
return false;
marks_mask = inode_mark->mask;
marks_ignored_mask = inode_mark->ignored_mask;
} else if (vfsmnt_mark) {
marks_mask = vfsmnt_mark->mask;
marks_ignored_mask = vfsmnt_mark->ignored_mask;
} else {
BUG();
}
if (S_ISDIR(path->dentry->d_inode->i_mode) &&
(marks_ignored_mask & FS_ISDIR))
return false;
if (event_mask & marks_mask & ~marks_ignored_mask)
return true;
return false;
}
static void fanotify_free_group_priv(struct fsnotify_group *group)
{
struct user_struct *user;
user = group->fanotify_data.user;
atomic_dec(&user->fanotify_listeners);
free_uid(user);
}
const struct fsnotify_ops fanotify_fsnotify_ops = {
.handle_event = fanotify_handle_event,
.should_send_event = fanotify_should_send_event,
.free_group_priv = fanotify_free_group_priv,
.free_event_priv = NULL,
.freeing_mark = NULL,
};
| gpl-2.0 |
CAF-MSM8610/kernel-msm | drivers/pinctrl/pinmux.c | 1905 | 16360 | /*
* Core driver for the pin muxing portions of the pin control subsystem
*
* Copyright (C) 2011-2012 ST-Ericsson SA
* Written on behalf of Linaro for ST-Ericsson
* Based on bits of regulator core, gpio core and clk core
*
* Author: Linus Walleij <linus.walleij@linaro.org>
*
* Copyright (C) 2012 NVIDIA CORPORATION. All rights reserved.
*
* License terms: GNU General Public License (GPL) version 2
*/
#define pr_fmt(fmt) "pinmux core: " fmt
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/slab.h>
#include <linux/radix-tree.h>
#include <linux/err.h>
#include <linux/list.h>
#include <linux/string.h>
#include <linux/sysfs.h>
#include <linux/debugfs.h>
#include <linux/seq_file.h>
#include <linux/pinctrl/machine.h>
#include <linux/pinctrl/pinmux.h>
#include "core.h"
#include "pinmux.h"
int pinmux_check_ops(struct pinctrl_dev *pctldev)
{
const struct pinmux_ops *ops = pctldev->desc->pmxops;
unsigned nfuncs;
unsigned selector = 0;
/* Check that we implement required operations */
if (!ops ||
!ops->get_functions_count ||
!ops->get_function_name ||
!ops->get_function_groups ||
!ops->enable) {
dev_err(pctldev->dev, "pinmux ops lacks necessary functions\n");
return -EINVAL;
}
/* Check that all functions registered have names */
nfuncs = ops->get_functions_count(pctldev);
while (selector < nfuncs) {
const char *fname = ops->get_function_name(pctldev,
selector);
if (!fname) {
dev_err(pctldev->dev, "pinmux ops has no name for function%u\n",
selector);
return -EINVAL;
}
selector++;
}
return 0;
}
int pinmux_validate_map(struct pinctrl_map const *map, int i)
{
if (!map->data.mux.function) {
pr_err("failed to register map %s (%d): no function given\n",
map->name, i);
return -EINVAL;
}
return 0;
}
/**
* pin_request() - request a single pin to be muxed in, typically for GPIO
* @pin: the pin number in the global pin space
* @owner: a representation of the owner of this pin; typically the device
* name that controls its mux function, or the requested GPIO name
* @gpio_range: the range matching the GPIO pin if this is a request for a
* single GPIO pin
*/
static int pin_request(struct pinctrl_dev *pctldev,
int pin, const char *owner,
struct pinctrl_gpio_range *gpio_range)
{
struct pin_desc *desc;
const struct pinmux_ops *ops = pctldev->desc->pmxops;
int status = -EINVAL;
desc = pin_desc_get(pctldev, pin);
if (desc == NULL) {
dev_err(pctldev->dev,
"pin %d is not registered so it cannot be requested\n",
pin);
goto out;
}
dev_dbg(pctldev->dev, "request pin %d (%s) for %s\n",
pin, desc->name, owner);
if (gpio_range) {
/* There's no need to support multiple GPIO requests */
if (desc->gpio_owner) {
dev_err(pctldev->dev,
"pin %s already requested by %s; cannot claim for %s\n",
desc->name, desc->gpio_owner, owner);
goto out;
}
desc->gpio_owner = owner;
} else {
if (desc->mux_usecount && strcmp(desc->mux_owner, owner)) {
dev_err(pctldev->dev,
"pin %s already requested by %s; cannot claim for %s\n",
desc->name, desc->mux_owner, owner);
goto out;
}
desc->mux_usecount++;
if (desc->mux_usecount > 1)
return 0;
desc->mux_owner = owner;
}
/* Let each pin increase references to this module */
if (!try_module_get(pctldev->owner)) {
dev_err(pctldev->dev,
"could not increase module refcount for pin %d\n",
pin);
status = -EINVAL;
goto out_free_pin;
}
/*
* If there is no kind of request function for the pin we just assume
* we got it by default and proceed.
*/
if (gpio_range && ops->gpio_request_enable)
/* This requests and enables a single GPIO pin */
status = ops->gpio_request_enable(pctldev, gpio_range, pin);
else if (ops->request)
status = ops->request(pctldev, pin);
else
status = 0;
if (status) {
dev_err(pctldev->dev, "request() failed for pin %d\n", pin);
module_put(pctldev->owner);
}
out_free_pin:
if (status) {
if (gpio_range) {
desc->gpio_owner = NULL;
} else {
desc->mux_usecount--;
if (!desc->mux_usecount)
desc->mux_owner = NULL;
}
}
out:
if (status)
dev_err(pctldev->dev, "pin-%d (%s) status %d\n",
pin, owner, status);
return status;
}
/**
* pin_free() - release a single muxed in pin so something else can be muxed
* @pctldev: pin controller device handling this pin
* @pin: the pin to free
* @gpio_range: the range matching the GPIO pin if this is a request for a
* single GPIO pin
*
* This function returns a pointer to the previous owner. This is used
* for callers that dynamically allocate an owner name so it can be freed
* once the pin is free. This is done for GPIO request functions.
*/
static const char *pin_free(struct pinctrl_dev *pctldev, int pin,
struct pinctrl_gpio_range *gpio_range)
{
const struct pinmux_ops *ops = pctldev->desc->pmxops;
struct pin_desc *desc;
const char *owner;
desc = pin_desc_get(pctldev, pin);
if (desc == NULL) {
dev_err(pctldev->dev,
"pin is not registered so it cannot be freed\n");
return NULL;
}
if (!gpio_range) {
/*
* A pin should not be freed more times than allocated.
*/
if (WARN_ON(!desc->mux_usecount))
return NULL;
desc->mux_usecount--;
if (desc->mux_usecount)
return NULL;
}
/*
* If there is no kind of request function for the pin we just assume
* we got it by default and proceed.
*/
if (gpio_range && ops->gpio_disable_free)
ops->gpio_disable_free(pctldev, gpio_range, pin);
else if (ops->free)
ops->free(pctldev, pin);
if (gpio_range) {
owner = desc->gpio_owner;
desc->gpio_owner = NULL;
} else {
owner = desc->mux_owner;
desc->mux_owner = NULL;
desc->mux_setting = NULL;
}
module_put(pctldev->owner);
return owner;
}
/**
* pinmux_request_gpio() - request pinmuxing for a GPIO pin
* @pctldev: pin controller device affected
* @pin: the pin to mux in for GPIO
* @range: the applicable GPIO range
*/
int pinmux_request_gpio(struct pinctrl_dev *pctldev,
struct pinctrl_gpio_range *range,
unsigned pin, unsigned gpio)
{
const char *owner;
int ret;
/* Conjure some name stating what chip and pin this is taken by */
owner = kasprintf(GFP_KERNEL, "%s:%d", range->name, gpio);
if (!owner)
return -EINVAL;
ret = pin_request(pctldev, pin, owner, range);
if (ret < 0)
kfree(owner);
return ret;
}
/**
* pinmux_free_gpio() - release a pin from GPIO muxing
* @pctldev: the pin controller device for the pin
* @pin: the affected currently GPIO-muxed in pin
* @range: applicable GPIO range
*/
void pinmux_free_gpio(struct pinctrl_dev *pctldev, unsigned pin,
struct pinctrl_gpio_range *range)
{
const char *owner;
owner = pin_free(pctldev, pin, range);
kfree(owner);
}
/**
* pinmux_gpio_direction() - set the direction of a single muxed-in GPIO pin
* @pctldev: the pin controller handling this pin
* @range: applicable GPIO range
* @pin: the affected GPIO pin in this controller
* @input: true if we set the pin as input, false for output
*/
int pinmux_gpio_direction(struct pinctrl_dev *pctldev,
struct pinctrl_gpio_range *range,
unsigned pin, bool input)
{
const struct pinmux_ops *ops;
int ret;
ops = pctldev->desc->pmxops;
if (ops->gpio_set_direction)
ret = ops->gpio_set_direction(pctldev, range, pin, input);
else
ret = 0;
return ret;
}
static int pinmux_func_name_to_selector(struct pinctrl_dev *pctldev,
const char *function)
{
const struct pinmux_ops *ops = pctldev->desc->pmxops;
unsigned nfuncs = ops->get_functions_count(pctldev);
unsigned selector = 0;
/* See if this pctldev has this function */
while (selector < nfuncs) {
const char *fname = ops->get_function_name(pctldev,
selector);
if (!strcmp(function, fname))
return selector;
selector++;
}
pr_err("%s does not support function %s\n",
pinctrl_dev_get_name(pctldev), function);
return -EINVAL;
}
int pinmux_map_to_setting(struct pinctrl_map const *map,
struct pinctrl_setting *setting)
{
struct pinctrl_dev *pctldev = setting->pctldev;
const struct pinmux_ops *pmxops = pctldev->desc->pmxops;
char const * const *groups;
unsigned num_groups;
int ret;
const char *group;
int i;
if (!pmxops) {
dev_err(pctldev->dev, "does not support mux function\n");
return -EINVAL;
}
ret = pinmux_func_name_to_selector(pctldev, map->data.mux.function);
if (ret < 0) {
dev_err(pctldev->dev, "invalid function %s in map table\n",
map->data.mux.function);
return ret;
}
setting->data.mux.func = ret;
ret = pmxops->get_function_groups(pctldev, setting->data.mux.func,
&groups, &num_groups);
if (ret < 0) {
dev_err(pctldev->dev, "can't query groups for function %s\n",
map->data.mux.function);
return ret;
}
if (!num_groups) {
dev_err(pctldev->dev,
"function %s can't be selected on any group\n",
map->data.mux.function);
return -EINVAL;
}
if (map->data.mux.group) {
bool found = false;
group = map->data.mux.group;
for (i = 0; i < num_groups; i++) {
if (!strcmp(group, groups[i])) {
found = true;
break;
}
}
if (!found) {
dev_err(pctldev->dev,
"invalid group \"%s\" for function \"%s\"\n",
group, map->data.mux.function);
return -EINVAL;
}
} else {
group = groups[0];
}
ret = pinctrl_get_group_selector(pctldev, group);
if (ret < 0) {
dev_err(pctldev->dev, "invalid group %s in map table\n",
map->data.mux.group);
return ret;
}
setting->data.mux.group = ret;
return 0;
}
void pinmux_free_setting(struct pinctrl_setting const *setting)
{
/* This function is currently unused */
}
int pinmux_enable_setting(struct pinctrl_setting const *setting)
{
struct pinctrl_dev *pctldev = setting->pctldev;
const struct pinctrl_ops *pctlops = pctldev->desc->pctlops;
const struct pinmux_ops *ops = pctldev->desc->pmxops;
int ret;
const unsigned *pins;
unsigned num_pins;
int i;
struct pin_desc *desc;
ret = pctlops->get_group_pins(pctldev, setting->data.mux.group,
&pins, &num_pins);
if (ret) {
/* errors only affect debug data, so just warn */
dev_warn(pctldev->dev,
"could not get pins for group selector %d\n",
setting->data.mux.group);
num_pins = 0;
}
/* Try to allocate all pins in this group, one by one */
for (i = 0; i < num_pins; i++) {
ret = pin_request(pctldev, pins[i], setting->dev_name, NULL);
if (ret) {
dev_err(pctldev->dev,
"could not request pin %d on device %s\n",
pins[i], pinctrl_dev_get_name(pctldev));
goto err_pin_request;
}
}
/* Now that we have acquired the pins, encode the mux setting */
for (i = 0; i < num_pins; i++) {
desc = pin_desc_get(pctldev, pins[i]);
if (desc == NULL) {
dev_warn(pctldev->dev,
"could not get pin desc for pin %d\n",
pins[i]);
continue;
}
desc->mux_setting = &(setting->data.mux);
}
ret = ops->enable(pctldev, setting->data.mux.func,
setting->data.mux.group);
if (ret)
goto err_enable;
return 0;
err_enable:
for (i = 0; i < num_pins; i++) {
desc = pin_desc_get(pctldev, pins[i]);
if (desc)
desc->mux_setting = NULL;
}
err_pin_request:
/* On error release all taken pins */
while (--i >= 0)
pin_free(pctldev, pins[i], NULL);
return ret;
}
void pinmux_disable_setting(struct pinctrl_setting const *setting)
{
struct pinctrl_dev *pctldev = setting->pctldev;
const struct pinctrl_ops *pctlops = pctldev->desc->pctlops;
const struct pinmux_ops *ops = pctldev->desc->pmxops;
int ret;
const unsigned *pins;
unsigned num_pins;
int i;
struct pin_desc *desc;
ret = pctlops->get_group_pins(pctldev, setting->data.mux.group,
&pins, &num_pins);
if (ret) {
/* errors only affect debug data, so just warn */
dev_warn(pctldev->dev,
"could not get pins for group selector %d\n",
setting->data.mux.group);
num_pins = 0;
}
/* Flag the descs that no setting is active */
for (i = 0; i < num_pins; i++) {
desc = pin_desc_get(pctldev, pins[i]);
if (desc == NULL) {
dev_warn(pctldev->dev,
"could not get pin desc for pin %d\n",
pins[i]);
continue;
}
desc->mux_setting = NULL;
}
/* And release the pins */
for (i = 0; i < num_pins; i++)
pin_free(pctldev, pins[i], NULL);
if (ops->disable)
ops->disable(pctldev, setting->data.mux.func, setting->data.mux.group);
}
#ifdef CONFIG_DEBUG_FS
/* Called from pincontrol core */
static int pinmux_functions_show(struct seq_file *s, void *what)
{
struct pinctrl_dev *pctldev = s->private;
const struct pinmux_ops *pmxops = pctldev->desc->pmxops;
unsigned nfuncs;
unsigned func_selector = 0;
if (!pmxops)
return 0;
mutex_lock(&pinctrl_mutex);
nfuncs = pmxops->get_functions_count(pctldev);
while (func_selector < nfuncs) {
const char *func = pmxops->get_function_name(pctldev,
func_selector);
const char * const *groups;
unsigned num_groups;
int ret;
int i;
ret = pmxops->get_function_groups(pctldev, func_selector,
&groups, &num_groups);
if (ret)
seq_printf(s, "function %s: COULD NOT GET GROUPS\n",
func);
seq_printf(s, "function: %s, groups = [ ", func);
for (i = 0; i < num_groups; i++)
seq_printf(s, "%s ", groups[i]);
seq_puts(s, "]\n");
func_selector++;
}
mutex_unlock(&pinctrl_mutex);
return 0;
}
static int pinmux_pins_show(struct seq_file *s, void *what)
{
struct pinctrl_dev *pctldev = s->private;
const struct pinctrl_ops *pctlops = pctldev->desc->pctlops;
const struct pinmux_ops *pmxops = pctldev->desc->pmxops;
unsigned i, pin;
if (!pmxops)
return 0;
seq_puts(s, "Pinmux settings per pin\n");
seq_puts(s, "Format: pin (name): mux_owner gpio_owner hog?\n");
mutex_lock(&pinctrl_mutex);
/* The pin number can be retrived from the pin controller descriptor */
for (i = 0; i < pctldev->desc->npins; i++) {
struct pin_desc *desc;
bool is_hog = false;
pin = pctldev->desc->pins[i].number;
desc = pin_desc_get(pctldev, pin);
/* Skip if we cannot search the pin */
if (desc == NULL)
continue;
if (desc->mux_owner &&
!strcmp(desc->mux_owner, pinctrl_dev_get_name(pctldev)))
is_hog = true;
seq_printf(s, "pin %d (%s): %s %s%s", pin,
desc->name ? desc->name : "unnamed",
desc->mux_owner ? desc->mux_owner
: "(MUX UNCLAIMED)",
desc->gpio_owner ? desc->gpio_owner
: "(GPIO UNCLAIMED)",
is_hog ? " (HOG)" : "");
if (desc->mux_setting)
seq_printf(s, " function %s group %s\n",
pmxops->get_function_name(pctldev,
desc->mux_setting->func),
pctlops->get_group_name(pctldev,
desc->mux_setting->group));
else
seq_printf(s, "\n");
}
mutex_unlock(&pinctrl_mutex);
return 0;
}
void pinmux_show_map(struct seq_file *s, struct pinctrl_map const *map)
{
seq_printf(s, "group %s\nfunction %s\n",
map->data.mux.group ? map->data.mux.group : "(default)",
map->data.mux.function);
}
void pinmux_show_setting(struct seq_file *s,
struct pinctrl_setting const *setting)
{
struct pinctrl_dev *pctldev = setting->pctldev;
const struct pinmux_ops *pmxops = pctldev->desc->pmxops;
const struct pinctrl_ops *pctlops = pctldev->desc->pctlops;
seq_printf(s, "group: %s (%u) function: %s (%u)\n",
pctlops->get_group_name(pctldev, setting->data.mux.group),
setting->data.mux.group,
pmxops->get_function_name(pctldev, setting->data.mux.func),
setting->data.mux.func);
}
static int pinmux_functions_open(struct inode *inode, struct file *file)
{
return single_open(file, pinmux_functions_show, inode->i_private);
}
static int pinmux_pins_open(struct inode *inode, struct file *file)
{
return single_open(file, pinmux_pins_show, inode->i_private);
}
static const struct file_operations pinmux_functions_ops = {
.open = pinmux_functions_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static const struct file_operations pinmux_pins_ops = {
.open = pinmux_pins_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
void pinmux_init_device_debugfs(struct dentry *devroot,
struct pinctrl_dev *pctldev)
{
debugfs_create_file("pinmux-functions", S_IFREG | S_IRUGO,
devroot, pctldev, &pinmux_functions_ops);
debugfs_create_file("pinmux-pins", S_IFREG | S_IRUGO,
devroot, pctldev, &pinmux_pins_ops);
}
#endif /* CONFIG_DEBUG_FS */
| gpl-2.0 |
xenserver/linux-3.x | drivers/media/pci/dm1105/dm1105.c | 2161 | 30088 | /*
* dm1105.c - driver for DVB cards based on SDMC DM1105 PCI chip
*
* Copyright (C) 2008 Igor M. Liplianin <liplianin@me.by>
*
* 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/i2c.h>
#include <linux/i2c-algo-bit.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/pci.h>
#include <linux/dma-mapping.h>
#include <linux/slab.h>
#include <media/rc-core.h>
#include "demux.h"
#include "dmxdev.h"
#include "dvb_demux.h"
#include "dvb_frontend.h"
#include "dvb_net.h"
#include "dvbdev.h"
#include "dvb-pll.h"
#include "stv0299.h"
#include "stv0288.h"
#include "stb6000.h"
#include "si21xx.h"
#include "cx24116.h"
#include "z0194a.h"
#include "ts2020.h"
#include "ds3000.h"
#define MODULE_NAME "dm1105"
#define UNSET (-1U)
#define DM1105_BOARD_NOAUTO UNSET
#define DM1105_BOARD_UNKNOWN 0
#define DM1105_BOARD_DVBWORLD_2002 1
#define DM1105_BOARD_DVBWORLD_2004 2
#define DM1105_BOARD_AXESS_DM05 3
#define DM1105_BOARD_UNBRANDED_I2C_ON_GPIO 4
/* ----------------------------------------------- */
/*
* PCI ID's
*/
#ifndef PCI_VENDOR_ID_TRIGEM
#define PCI_VENDOR_ID_TRIGEM 0x109f
#endif
#ifndef PCI_VENDOR_ID_AXESS
#define PCI_VENDOR_ID_AXESS 0x195d
#endif
#ifndef PCI_DEVICE_ID_DM1105
#define PCI_DEVICE_ID_DM1105 0x036f
#endif
#ifndef PCI_DEVICE_ID_DW2002
#define PCI_DEVICE_ID_DW2002 0x2002
#endif
#ifndef PCI_DEVICE_ID_DW2004
#define PCI_DEVICE_ID_DW2004 0x2004
#endif
#ifndef PCI_DEVICE_ID_DM05
#define PCI_DEVICE_ID_DM05 0x1105
#endif
/* ----------------------------------------------- */
/* sdmc dm1105 registers */
/* TS Control */
#define DM1105_TSCTR 0x00
#define DM1105_DTALENTH 0x04
/* GPIO Interface */
#define DM1105_GPIOVAL 0x08
#define DM1105_GPIOCTR 0x0c
/* PID serial number */
#define DM1105_PIDN 0x10
/* Odd-even secret key select */
#define DM1105_CWSEL 0x14
/* Host Command Interface */
#define DM1105_HOST_CTR 0x18
#define DM1105_HOST_AD 0x1c
/* PCI Interface */
#define DM1105_CR 0x30
#define DM1105_RST 0x34
#define DM1105_STADR 0x38
#define DM1105_RLEN 0x3c
#define DM1105_WRP 0x40
#define DM1105_INTCNT 0x44
#define DM1105_INTMAK 0x48
#define DM1105_INTSTS 0x4c
/* CW Value */
#define DM1105_ODD 0x50
#define DM1105_EVEN 0x58
/* PID Value */
#define DM1105_PID 0x60
/* IR Control */
#define DM1105_IRCTR 0x64
#define DM1105_IRMODE 0x68
#define DM1105_SYSTEMCODE 0x6c
#define DM1105_IRCODE 0x70
/* Unknown Values */
#define DM1105_ENCRYPT 0x74
#define DM1105_VER 0x7c
/* I2C Interface */
#define DM1105_I2CCTR 0x80
#define DM1105_I2CSTS 0x81
#define DM1105_I2CDAT 0x82
#define DM1105_I2C_RA 0x83
/* ----------------------------------------------- */
/* Interrupt Mask Bits */
#define INTMAK_TSIRQM 0x01
#define INTMAK_HIRQM 0x04
#define INTMAK_IRM 0x08
#define INTMAK_ALLMASK (INTMAK_TSIRQM | \
INTMAK_HIRQM | \
INTMAK_IRM)
#define INTMAK_NONEMASK 0x00
/* Interrupt Status Bits */
#define INTSTS_TSIRQ 0x01
#define INTSTS_HIRQ 0x04
#define INTSTS_IR 0x08
/* IR Control Bits */
#define DM1105_IR_EN 0x01
#define DM1105_SYS_CHK 0x02
#define DM1105_REP_FLG 0x08
/* EEPROM addr */
#define IIC_24C01_addr 0xa0
/* Max board count */
#define DM1105_MAX 0x04
#define DRIVER_NAME "dm1105"
#define DM1105_I2C_GPIO_NAME "dm1105-gpio"
#define DM1105_DMA_PACKETS 47
#define DM1105_DMA_PACKET_LENGTH (128*4)
#define DM1105_DMA_BYTES (128 * 4 * DM1105_DMA_PACKETS)
/* */
#define GPIO08 (1 << 8)
#define GPIO13 (1 << 13)
#define GPIO14 (1 << 14)
#define GPIO15 (1 << 15)
#define GPIO16 (1 << 16)
#define GPIO17 (1 << 17)
#define GPIO_ALL 0x03ffff
/* GPIO's for LNB power control */
#define DM1105_LNB_MASK (GPIO_ALL & ~(GPIO14 | GPIO13))
#define DM1105_LNB_OFF GPIO17
#define DM1105_LNB_13V (GPIO16 | GPIO08)
#define DM1105_LNB_18V GPIO08
/* GPIO's for LNB power control for Axess DM05 */
#define DM05_LNB_MASK (GPIO_ALL & ~(GPIO14 | GPIO13))
#define DM05_LNB_OFF GPIO17/* actually 13v */
#define DM05_LNB_13V GPIO17
#define DM05_LNB_18V (GPIO17 | GPIO16)
/* GPIO's for LNB power control for unbranded with I2C on GPIO */
#define UNBR_LNB_MASK (GPIO17 | GPIO16)
#define UNBR_LNB_OFF 0
#define UNBR_LNB_13V GPIO17
#define UNBR_LNB_18V (GPIO17 | GPIO16)
static unsigned int card[] = {[0 ... 3] = UNSET };
module_param_array(card, int, NULL, 0444);
MODULE_PARM_DESC(card, "card type");
static int ir_debug;
module_param(ir_debug, int, 0644);
MODULE_PARM_DESC(ir_debug, "enable debugging information for IR decoding");
static unsigned int dm1105_devcount;
DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr);
struct dm1105_board {
char *name;
struct {
u32 mask, off, v13, v18;
} lnb;
u32 gpio_scl, gpio_sda;
};
struct dm1105_subid {
u16 subvendor;
u16 subdevice;
u32 card;
};
static const struct dm1105_board dm1105_boards[] = {
[DM1105_BOARD_UNKNOWN] = {
.name = "UNKNOWN/GENERIC",
.lnb = {
.mask = DM1105_LNB_MASK,
.off = DM1105_LNB_OFF,
.v13 = DM1105_LNB_13V,
.v18 = DM1105_LNB_18V,
},
},
[DM1105_BOARD_DVBWORLD_2002] = {
.name = "DVBWorld PCI 2002",
.lnb = {
.mask = DM1105_LNB_MASK,
.off = DM1105_LNB_OFF,
.v13 = DM1105_LNB_13V,
.v18 = DM1105_LNB_18V,
},
},
[DM1105_BOARD_DVBWORLD_2004] = {
.name = "DVBWorld PCI 2004",
.lnb = {
.mask = DM1105_LNB_MASK,
.off = DM1105_LNB_OFF,
.v13 = DM1105_LNB_13V,
.v18 = DM1105_LNB_18V,
},
},
[DM1105_BOARD_AXESS_DM05] = {
.name = "Axess/EasyTv DM05",
.lnb = {
.mask = DM05_LNB_MASK,
.off = DM05_LNB_OFF,
.v13 = DM05_LNB_13V,
.v18 = DM05_LNB_18V,
},
},
[DM1105_BOARD_UNBRANDED_I2C_ON_GPIO] = {
.name = "Unbranded DM1105 with i2c on GPIOs",
.lnb = {
.mask = UNBR_LNB_MASK,
.off = UNBR_LNB_OFF,
.v13 = UNBR_LNB_13V,
.v18 = UNBR_LNB_18V,
},
.gpio_scl = GPIO14,
.gpio_sda = GPIO13,
},
};
static const struct dm1105_subid dm1105_subids[] = {
{
.subvendor = 0x0000,
.subdevice = 0x2002,
.card = DM1105_BOARD_DVBWORLD_2002,
}, {
.subvendor = 0x0001,
.subdevice = 0x2002,
.card = DM1105_BOARD_DVBWORLD_2002,
}, {
.subvendor = 0x0000,
.subdevice = 0x2004,
.card = DM1105_BOARD_DVBWORLD_2004,
}, {
.subvendor = 0x0001,
.subdevice = 0x2004,
.card = DM1105_BOARD_DVBWORLD_2004,
}, {
.subvendor = 0x195d,
.subdevice = 0x1105,
.card = DM1105_BOARD_AXESS_DM05,
},
};
static void dm1105_card_list(struct pci_dev *pci)
{
int i;
if (0 == pci->subsystem_vendor &&
0 == pci->subsystem_device) {
printk(KERN_ERR
"dm1105: Your board has no valid PCI Subsystem ID\n"
"dm1105: and thus can't be autodetected\n"
"dm1105: Please pass card=<n> insmod option to\n"
"dm1105: workaround that. Redirect complaints to\n"
"dm1105: the vendor of the TV card. Best regards,\n"
"dm1105: -- tux\n");
} else {
printk(KERN_ERR
"dm1105: Your board isn't known (yet) to the driver.\n"
"dm1105: You can try to pick one of the existing\n"
"dm1105: card configs via card=<n> insmod option.\n"
"dm1105: Updating to the latest version might help\n"
"dm1105: as well.\n");
}
printk(KERN_ERR "Here is a list of valid choices for the card=<n> "
"insmod option:\n");
for (i = 0; i < ARRAY_SIZE(dm1105_boards); i++)
printk(KERN_ERR "dm1105: card=%d -> %s\n",
i, dm1105_boards[i].name);
}
/* infrared remote control */
struct infrared {
struct rc_dev *dev;
char input_phys[32];
struct work_struct work;
u32 ir_command;
};
struct dm1105_dev {
/* pci */
struct pci_dev *pdev;
u8 __iomem *io_mem;
/* ir */
struct infrared ir;
/* dvb */
struct dmx_frontend hw_frontend;
struct dmx_frontend mem_frontend;
struct dmxdev dmxdev;
struct dvb_adapter dvb_adapter;
struct dvb_demux demux;
struct dvb_frontend *fe;
struct dvb_net dvbnet;
unsigned int full_ts_users;
unsigned int boardnr;
int nr;
/* i2c */
struct i2c_adapter i2c_adap;
struct i2c_adapter i2c_bb_adap;
struct i2c_algo_bit_data i2c_bit;
/* irq */
struct work_struct work;
struct workqueue_struct *wq;
char wqn[16];
/* dma */
dma_addr_t dma_addr;
unsigned char *ts_buf;
u32 wrp;
u32 nextwrp;
u32 buffer_size;
unsigned int PacketErrorCount;
unsigned int dmarst;
spinlock_t lock;
};
#define dm_io_mem(reg) ((unsigned long)(&dev->io_mem[reg]))
#define dm_readb(reg) inb(dm_io_mem(reg))
#define dm_writeb(reg, value) outb((value), (dm_io_mem(reg)))
#define dm_readw(reg) inw(dm_io_mem(reg))
#define dm_writew(reg, value) outw((value), (dm_io_mem(reg)))
#define dm_readl(reg) inl(dm_io_mem(reg))
#define dm_writel(reg, value) outl((value), (dm_io_mem(reg)))
#define dm_andorl(reg, mask, value) \
outl((inl(dm_io_mem(reg)) & ~(mask)) |\
((value) & (mask)), (dm_io_mem(reg)))
#define dm_setl(reg, bit) dm_andorl((reg), (bit), (bit))
#define dm_clearl(reg, bit) dm_andorl((reg), (bit), 0)
/* The chip has 18 GPIOs. In HOST mode GPIO's used as 15 bit address lines,
so we can use only 3 GPIO's from GPIO15 to GPIO17.
Here I don't check whether HOST is enebled as it is not implemented yet.
*/
static void dm1105_gpio_set(struct dm1105_dev *dev, u32 mask)
{
if (mask & 0xfffc0000)
printk(KERN_ERR "%s: Only 18 GPIO's are allowed\n", __func__);
if (mask & 0x0003ffff)
dm_setl(DM1105_GPIOVAL, mask & 0x0003ffff);
}
static void dm1105_gpio_clear(struct dm1105_dev *dev, u32 mask)
{
if (mask & 0xfffc0000)
printk(KERN_ERR "%s: Only 18 GPIO's are allowed\n", __func__);
if (mask & 0x0003ffff)
dm_clearl(DM1105_GPIOVAL, mask & 0x0003ffff);
}
static void dm1105_gpio_andor(struct dm1105_dev *dev, u32 mask, u32 val)
{
if (mask & 0xfffc0000)
printk(KERN_ERR "%s: Only 18 GPIO's are allowed\n", __func__);
if (mask & 0x0003ffff)
dm_andorl(DM1105_GPIOVAL, mask & 0x0003ffff, val);
}
static u32 dm1105_gpio_get(struct dm1105_dev *dev, u32 mask)
{
if (mask & 0xfffc0000)
printk(KERN_ERR "%s: Only 18 GPIO's are allowed\n", __func__);
if (mask & 0x0003ffff)
return dm_readl(DM1105_GPIOVAL) & mask & 0x0003ffff;
return 0;
}
static void dm1105_gpio_enable(struct dm1105_dev *dev, u32 mask, int asoutput)
{
if (mask & 0xfffc0000)
printk(KERN_ERR "%s: Only 18 GPIO's are allowed\n", __func__);
if ((mask & 0x0003ffff) && asoutput)
dm_clearl(DM1105_GPIOCTR, mask & 0x0003ffff);
else if ((mask & 0x0003ffff) && !asoutput)
dm_setl(DM1105_GPIOCTR, mask & 0x0003ffff);
}
static void dm1105_setline(struct dm1105_dev *dev, u32 line, int state)
{
if (state)
dm1105_gpio_enable(dev, line, 0);
else {
dm1105_gpio_enable(dev, line, 1);
dm1105_gpio_clear(dev, line);
}
}
static void dm1105_setsda(void *data, int state)
{
struct dm1105_dev *dev = data;
dm1105_setline(dev, dm1105_boards[dev->boardnr].gpio_sda, state);
}
static void dm1105_setscl(void *data, int state)
{
struct dm1105_dev *dev = data;
dm1105_setline(dev, dm1105_boards[dev->boardnr].gpio_scl, state);
}
static int dm1105_getsda(void *data)
{
struct dm1105_dev *dev = data;
return dm1105_gpio_get(dev, dm1105_boards[dev->boardnr].gpio_sda)
? 1 : 0;
}
static int dm1105_getscl(void *data)
{
struct dm1105_dev *dev = data;
return dm1105_gpio_get(dev, dm1105_boards[dev->boardnr].gpio_scl)
? 1 : 0;
}
static int dm1105_i2c_xfer(struct i2c_adapter *i2c_adap,
struct i2c_msg *msgs, int num)
{
struct dm1105_dev *dev ;
int addr, rc, i, j, k, len, byte, data;
u8 status;
dev = i2c_adap->algo_data;
for (i = 0; i < num; i++) {
dm_writeb(DM1105_I2CCTR, 0x00);
if (msgs[i].flags & I2C_M_RD) {
/* read bytes */
addr = msgs[i].addr << 1;
addr |= 1;
dm_writeb(DM1105_I2CDAT, addr);
for (byte = 0; byte < msgs[i].len; byte++)
dm_writeb(DM1105_I2CDAT + byte + 1, 0);
dm_writeb(DM1105_I2CCTR, 0x81 + msgs[i].len);
for (j = 0; j < 55; j++) {
mdelay(10);
status = dm_readb(DM1105_I2CSTS);
if ((status & 0xc0) == 0x40)
break;
}
if (j >= 55)
return -1;
for (byte = 0; byte < msgs[i].len; byte++) {
rc = dm_readb(DM1105_I2CDAT + byte + 1);
if (rc < 0)
goto err;
msgs[i].buf[byte] = rc;
}
} else if ((msgs[i].buf[0] == 0xf7) && (msgs[i].addr == 0x55)) {
/* prepaired for cx24116 firmware */
/* Write in small blocks */
len = msgs[i].len - 1;
k = 1;
do {
dm_writeb(DM1105_I2CDAT, msgs[i].addr << 1);
dm_writeb(DM1105_I2CDAT + 1, 0xf7);
for (byte = 0; byte < (len > 48 ? 48 : len); byte++) {
data = msgs[i].buf[k + byte];
dm_writeb(DM1105_I2CDAT + byte + 2, data);
}
dm_writeb(DM1105_I2CCTR, 0x82 + (len > 48 ? 48 : len));
for (j = 0; j < 25; j++) {
mdelay(10);
status = dm_readb(DM1105_I2CSTS);
if ((status & 0xc0) == 0x40)
break;
}
if (j >= 25)
return -1;
k += 48;
len -= 48;
} while (len > 0);
} else {
/* write bytes */
dm_writeb(DM1105_I2CDAT, msgs[i].addr << 1);
for (byte = 0; byte < msgs[i].len; byte++) {
data = msgs[i].buf[byte];
dm_writeb(DM1105_I2CDAT + byte + 1, data);
}
dm_writeb(DM1105_I2CCTR, 0x81 + msgs[i].len);
for (j = 0; j < 25; j++) {
mdelay(10);
status = dm_readb(DM1105_I2CSTS);
if ((status & 0xc0) == 0x40)
break;
}
if (j >= 25)
return -1;
}
}
return num;
err:
return rc;
}
static u32 functionality(struct i2c_adapter *adap)
{
return I2C_FUNC_I2C;
}
static struct i2c_algorithm dm1105_algo = {
.master_xfer = dm1105_i2c_xfer,
.functionality = functionality,
};
static inline struct dm1105_dev *feed_to_dm1105_dev(struct dvb_demux_feed *feed)
{
return container_of(feed->demux, struct dm1105_dev, demux);
}
static inline struct dm1105_dev *frontend_to_dm1105_dev(struct dvb_frontend *fe)
{
return container_of(fe->dvb, struct dm1105_dev, dvb_adapter);
}
static int dm1105_set_voltage(struct dvb_frontend *fe, fe_sec_voltage_t voltage)
{
struct dm1105_dev *dev = frontend_to_dm1105_dev(fe);
dm1105_gpio_enable(dev, dm1105_boards[dev->boardnr].lnb.mask, 1);
if (voltage == SEC_VOLTAGE_18)
dm1105_gpio_andor(dev,
dm1105_boards[dev->boardnr].lnb.mask,
dm1105_boards[dev->boardnr].lnb.v18);
else if (voltage == SEC_VOLTAGE_13)
dm1105_gpio_andor(dev,
dm1105_boards[dev->boardnr].lnb.mask,
dm1105_boards[dev->boardnr].lnb.v13);
else
dm1105_gpio_andor(dev,
dm1105_boards[dev->boardnr].lnb.mask,
dm1105_boards[dev->boardnr].lnb.off);
return 0;
}
static void dm1105_set_dma_addr(struct dm1105_dev *dev)
{
dm_writel(DM1105_STADR, cpu_to_le32(dev->dma_addr));
}
static int dm1105_dma_map(struct dm1105_dev *dev)
{
dev->ts_buf = pci_alloc_consistent(dev->pdev,
6 * DM1105_DMA_BYTES,
&dev->dma_addr);
return !dev->ts_buf;
}
static void dm1105_dma_unmap(struct dm1105_dev *dev)
{
pci_free_consistent(dev->pdev,
6 * DM1105_DMA_BYTES,
dev->ts_buf,
dev->dma_addr);
}
static void dm1105_enable_irqs(struct dm1105_dev *dev)
{
dm_writeb(DM1105_INTMAK, INTMAK_ALLMASK);
dm_writeb(DM1105_CR, 1);
}
static void dm1105_disable_irqs(struct dm1105_dev *dev)
{
dm_writeb(DM1105_INTMAK, INTMAK_IRM);
dm_writeb(DM1105_CR, 0);
}
static int dm1105_start_feed(struct dvb_demux_feed *f)
{
struct dm1105_dev *dev = feed_to_dm1105_dev(f);
if (dev->full_ts_users++ == 0)
dm1105_enable_irqs(dev);
return 0;
}
static int dm1105_stop_feed(struct dvb_demux_feed *f)
{
struct dm1105_dev *dev = feed_to_dm1105_dev(f);
if (--dev->full_ts_users == 0)
dm1105_disable_irqs(dev);
return 0;
}
/* ir work handler */
static void dm1105_emit_key(struct work_struct *work)
{
struct infrared *ir = container_of(work, struct infrared, work);
u32 ircom = ir->ir_command;
u8 data;
if (ir_debug)
printk(KERN_INFO "%s: received byte 0x%04x\n", __func__, ircom);
data = (ircom >> 8) & 0x7f;
rc_keydown(ir->dev, data, 0);
}
/* work handler */
static void dm1105_dmx_buffer(struct work_struct *work)
{
struct dm1105_dev *dev = container_of(work, struct dm1105_dev, work);
unsigned int nbpackets;
u32 oldwrp = dev->wrp;
u32 nextwrp = dev->nextwrp;
if (!((dev->ts_buf[oldwrp] == 0x47) &&
(dev->ts_buf[oldwrp + 188] == 0x47) &&
(dev->ts_buf[oldwrp + 188 * 2] == 0x47))) {
dev->PacketErrorCount++;
/* bad packet found */
if ((dev->PacketErrorCount >= 2) &&
(dev->dmarst == 0)) {
dm_writeb(DM1105_RST, 1);
dev->wrp = 0;
dev->PacketErrorCount = 0;
dev->dmarst = 0;
return;
}
}
if (nextwrp < oldwrp) {
memcpy(dev->ts_buf + dev->buffer_size, dev->ts_buf, nextwrp);
nbpackets = ((dev->buffer_size - oldwrp) + nextwrp) / 188;
} else
nbpackets = (nextwrp - oldwrp) / 188;
dev->wrp = nextwrp;
dvb_dmx_swfilter_packets(&dev->demux, &dev->ts_buf[oldwrp], nbpackets);
}
static irqreturn_t dm1105_irq(int irq, void *dev_id)
{
struct dm1105_dev *dev = dev_id;
/* Read-Write INSTS Ack's Interrupt for DM1105 chip 16.03.2008 */
unsigned int intsts = dm_readb(DM1105_INTSTS);
dm_writeb(DM1105_INTSTS, intsts);
switch (intsts) {
case INTSTS_TSIRQ:
case (INTSTS_TSIRQ | INTSTS_IR):
dev->nextwrp = dm_readl(DM1105_WRP) - dm_readl(DM1105_STADR);
queue_work(dev->wq, &dev->work);
break;
case INTSTS_IR:
dev->ir.ir_command = dm_readl(DM1105_IRCODE);
schedule_work(&dev->ir.work);
break;
}
return IRQ_HANDLED;
}
static int dm1105_ir_init(struct dm1105_dev *dm1105)
{
struct rc_dev *dev;
int err = -ENOMEM;
dev = rc_allocate_device();
if (!dev)
return -ENOMEM;
snprintf(dm1105->ir.input_phys, sizeof(dm1105->ir.input_phys),
"pci-%s/ir0", pci_name(dm1105->pdev));
dev->driver_name = MODULE_NAME;
dev->map_name = RC_MAP_DM1105_NEC;
dev->driver_type = RC_DRIVER_SCANCODE;
dev->input_name = "DVB on-card IR receiver";
dev->input_phys = dm1105->ir.input_phys;
dev->input_id.bustype = BUS_PCI;
dev->input_id.version = 1;
if (dm1105->pdev->subsystem_vendor) {
dev->input_id.vendor = dm1105->pdev->subsystem_vendor;
dev->input_id.product = dm1105->pdev->subsystem_device;
} else {
dev->input_id.vendor = dm1105->pdev->vendor;
dev->input_id.product = dm1105->pdev->device;
}
dev->dev.parent = &dm1105->pdev->dev;
INIT_WORK(&dm1105->ir.work, dm1105_emit_key);
err = rc_register_device(dev);
if (err < 0) {
rc_free_device(dev);
return err;
}
dm1105->ir.dev = dev;
return 0;
}
static void dm1105_ir_exit(struct dm1105_dev *dm1105)
{
rc_unregister_device(dm1105->ir.dev);
}
static int dm1105_hw_init(struct dm1105_dev *dev)
{
dm1105_disable_irqs(dev);
dm_writeb(DM1105_HOST_CTR, 0);
/*DATALEN 188,*/
dm_writeb(DM1105_DTALENTH, 188);
/*TS_STRT TS_VALP MSBFIRST TS_MODE ALPAS TSPES*/
dm_writew(DM1105_TSCTR, 0xc10a);
/* map DMA and set address */
dm1105_dma_map(dev);
dm1105_set_dma_addr(dev);
/* big buffer */
dm_writel(DM1105_RLEN, 5 * DM1105_DMA_BYTES);
dm_writeb(DM1105_INTCNT, 47);
/* IR NEC mode enable */
dm_writeb(DM1105_IRCTR, (DM1105_IR_EN | DM1105_SYS_CHK));
dm_writeb(DM1105_IRMODE, 0);
dm_writew(DM1105_SYSTEMCODE, 0);
return 0;
}
static void dm1105_hw_exit(struct dm1105_dev *dev)
{
dm1105_disable_irqs(dev);
/* IR disable */
dm_writeb(DM1105_IRCTR, 0);
dm_writeb(DM1105_INTMAK, INTMAK_NONEMASK);
dm1105_dma_unmap(dev);
}
static struct stv0299_config sharp_z0194a_config = {
.demod_address = 0x68,
.inittab = sharp_z0194a_inittab,
.mclk = 88000000UL,
.invert = 1,
.skip_reinit = 0,
.lock_output = STV0299_LOCKOUTPUT_1,
.volt13_op0_op1 = STV0299_VOLT13_OP1,
.min_delay_ms = 100,
.set_symbol_rate = sharp_z0194a_set_symbol_rate,
};
static struct stv0288_config earda_config = {
.demod_address = 0x68,
.min_delay_ms = 100,
};
static struct si21xx_config serit_config = {
.demod_address = 0x68,
.min_delay_ms = 100,
};
static struct cx24116_config serit_sp2633_config = {
.demod_address = 0x55,
};
static struct ds3000_config dvbworld_ds3000_config = {
.demod_address = 0x68,
};
static struct ts2020_config dvbworld_ts2020_config = {
.tuner_address = 0x60,
.clk_out_div = 1,
};
static int frontend_init(struct dm1105_dev *dev)
{
int ret;
switch (dev->boardnr) {
case DM1105_BOARD_UNBRANDED_I2C_ON_GPIO:
dm1105_gpio_enable(dev, GPIO15, 1);
dm1105_gpio_clear(dev, GPIO15);
msleep(100);
dm1105_gpio_set(dev, GPIO15);
msleep(200);
dev->fe = dvb_attach(
stv0299_attach, &sharp_z0194a_config,
&dev->i2c_bb_adap);
if (dev->fe) {
dev->fe->ops.set_voltage = dm1105_set_voltage;
dvb_attach(dvb_pll_attach, dev->fe, 0x60,
&dev->i2c_bb_adap, DVB_PLL_OPERA1);
break;
}
dev->fe = dvb_attach(
stv0288_attach, &earda_config,
&dev->i2c_bb_adap);
if (dev->fe) {
dev->fe->ops.set_voltage = dm1105_set_voltage;
dvb_attach(stb6000_attach, dev->fe, 0x61,
&dev->i2c_bb_adap);
break;
}
dev->fe = dvb_attach(
si21xx_attach, &serit_config,
&dev->i2c_bb_adap);
if (dev->fe)
dev->fe->ops.set_voltage = dm1105_set_voltage;
break;
case DM1105_BOARD_DVBWORLD_2004:
dev->fe = dvb_attach(
cx24116_attach, &serit_sp2633_config,
&dev->i2c_adap);
if (dev->fe) {
dev->fe->ops.set_voltage = dm1105_set_voltage;
break;
}
dev->fe = dvb_attach(
ds3000_attach, &dvbworld_ds3000_config,
&dev->i2c_adap);
if (dev->fe) {
dvb_attach(ts2020_attach, dev->fe,
&dvbworld_ts2020_config, &dev->i2c_adap);
dev->fe->ops.set_voltage = dm1105_set_voltage;
}
break;
case DM1105_BOARD_DVBWORLD_2002:
case DM1105_BOARD_AXESS_DM05:
default:
dev->fe = dvb_attach(
stv0299_attach, &sharp_z0194a_config,
&dev->i2c_adap);
if (dev->fe) {
dev->fe->ops.set_voltage = dm1105_set_voltage;
dvb_attach(dvb_pll_attach, dev->fe, 0x60,
&dev->i2c_adap, DVB_PLL_OPERA1);
break;
}
dev->fe = dvb_attach(
stv0288_attach, &earda_config,
&dev->i2c_adap);
if (dev->fe) {
dev->fe->ops.set_voltage = dm1105_set_voltage;
dvb_attach(stb6000_attach, dev->fe, 0x61,
&dev->i2c_adap);
break;
}
dev->fe = dvb_attach(
si21xx_attach, &serit_config,
&dev->i2c_adap);
if (dev->fe)
dev->fe->ops.set_voltage = dm1105_set_voltage;
}
if (!dev->fe) {
dev_err(&dev->pdev->dev, "could not attach frontend\n");
return -ENODEV;
}
ret = dvb_register_frontend(&dev->dvb_adapter, dev->fe);
if (ret < 0) {
if (dev->fe->ops.release)
dev->fe->ops.release(dev->fe);
dev->fe = NULL;
return ret;
}
return 0;
}
static void dm1105_read_mac(struct dm1105_dev *dev, u8 *mac)
{
static u8 command[1] = { 0x28 };
struct i2c_msg msg[] = {
{
.addr = IIC_24C01_addr >> 1,
.flags = 0,
.buf = command,
.len = 1
}, {
.addr = IIC_24C01_addr >> 1,
.flags = I2C_M_RD,
.buf = mac,
.len = 6
},
};
dm1105_i2c_xfer(&dev->i2c_adap, msg , 2);
dev_info(&dev->pdev->dev, "MAC %pM\n", mac);
}
static int dm1105_probe(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct dm1105_dev *dev;
struct dvb_adapter *dvb_adapter;
struct dvb_demux *dvbdemux;
struct dmx_demux *dmx;
int ret = -ENOMEM;
int i;
dev = kzalloc(sizeof(struct dm1105_dev), GFP_KERNEL);
if (!dev)
return -ENOMEM;
/* board config */
dev->nr = dm1105_devcount;
dev->boardnr = UNSET;
if (card[dev->nr] < ARRAY_SIZE(dm1105_boards))
dev->boardnr = card[dev->nr];
for (i = 0; UNSET == dev->boardnr &&
i < ARRAY_SIZE(dm1105_subids); i++)
if (pdev->subsystem_vendor ==
dm1105_subids[i].subvendor &&
pdev->subsystem_device ==
dm1105_subids[i].subdevice)
dev->boardnr = dm1105_subids[i].card;
if (UNSET == dev->boardnr) {
dev->boardnr = DM1105_BOARD_UNKNOWN;
dm1105_card_list(pdev);
}
dm1105_devcount++;
dev->pdev = pdev;
dev->buffer_size = 5 * DM1105_DMA_BYTES;
dev->PacketErrorCount = 0;
dev->dmarst = 0;
ret = pci_enable_device(pdev);
if (ret < 0)
goto err_kfree;
ret = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
if (ret < 0)
goto err_pci_disable_device;
pci_set_master(pdev);
ret = pci_request_regions(pdev, DRIVER_NAME);
if (ret < 0)
goto err_pci_disable_device;
dev->io_mem = pci_iomap(pdev, 0, pci_resource_len(pdev, 0));
if (!dev->io_mem) {
ret = -EIO;
goto err_pci_release_regions;
}
spin_lock_init(&dev->lock);
pci_set_drvdata(pdev, dev);
ret = dm1105_hw_init(dev);
if (ret < 0)
goto err_pci_iounmap;
/* i2c */
i2c_set_adapdata(&dev->i2c_adap, dev);
strcpy(dev->i2c_adap.name, DRIVER_NAME);
dev->i2c_adap.owner = THIS_MODULE;
dev->i2c_adap.dev.parent = &pdev->dev;
dev->i2c_adap.algo = &dm1105_algo;
dev->i2c_adap.algo_data = dev;
ret = i2c_add_adapter(&dev->i2c_adap);
if (ret < 0)
goto err_dm1105_hw_exit;
i2c_set_adapdata(&dev->i2c_bb_adap, dev);
strcpy(dev->i2c_bb_adap.name, DM1105_I2C_GPIO_NAME);
dev->i2c_bb_adap.owner = THIS_MODULE;
dev->i2c_bb_adap.dev.parent = &pdev->dev;
dev->i2c_bb_adap.algo_data = &dev->i2c_bit;
dev->i2c_bit.data = dev;
dev->i2c_bit.setsda = dm1105_setsda;
dev->i2c_bit.setscl = dm1105_setscl;
dev->i2c_bit.getsda = dm1105_getsda;
dev->i2c_bit.getscl = dm1105_getscl;
dev->i2c_bit.udelay = 10;
dev->i2c_bit.timeout = 10;
/* Raise SCL and SDA */
dm1105_setsda(dev, 1);
dm1105_setscl(dev, 1);
ret = i2c_bit_add_bus(&dev->i2c_bb_adap);
if (ret < 0)
goto err_i2c_del_adapter;
/* dvb */
ret = dvb_register_adapter(&dev->dvb_adapter, DRIVER_NAME,
THIS_MODULE, &pdev->dev, adapter_nr);
if (ret < 0)
goto err_i2c_del_adapters;
dvb_adapter = &dev->dvb_adapter;
dm1105_read_mac(dev, dvb_adapter->proposed_mac);
dvbdemux = &dev->demux;
dvbdemux->filternum = 256;
dvbdemux->feednum = 256;
dvbdemux->start_feed = dm1105_start_feed;
dvbdemux->stop_feed = dm1105_stop_feed;
dvbdemux->dmx.capabilities = (DMX_TS_FILTERING |
DMX_SECTION_FILTERING | DMX_MEMORY_BASED_FILTERING);
ret = dvb_dmx_init(dvbdemux);
if (ret < 0)
goto err_dvb_unregister_adapter;
dmx = &dvbdemux->dmx;
dev->dmxdev.filternum = 256;
dev->dmxdev.demux = dmx;
dev->dmxdev.capabilities = 0;
ret = dvb_dmxdev_init(&dev->dmxdev, dvb_adapter);
if (ret < 0)
goto err_dvb_dmx_release;
dev->hw_frontend.source = DMX_FRONTEND_0;
ret = dmx->add_frontend(dmx, &dev->hw_frontend);
if (ret < 0)
goto err_dvb_dmxdev_release;
dev->mem_frontend.source = DMX_MEMORY_FE;
ret = dmx->add_frontend(dmx, &dev->mem_frontend);
if (ret < 0)
goto err_remove_hw_frontend;
ret = dmx->connect_frontend(dmx, &dev->hw_frontend);
if (ret < 0)
goto err_remove_mem_frontend;
ret = dvb_net_init(dvb_adapter, &dev->dvbnet, dmx);
if (ret < 0)
goto err_disconnect_frontend;
ret = frontend_init(dev);
if (ret < 0)
goto err_dvb_net;
dm1105_ir_init(dev);
INIT_WORK(&dev->work, dm1105_dmx_buffer);
sprintf(dev->wqn, "%s/%d", dvb_adapter->name, dvb_adapter->num);
dev->wq = create_singlethread_workqueue(dev->wqn);
if (!dev->wq) {
ret = -ENOMEM;
goto err_dvb_net;
}
ret = request_irq(pdev->irq, dm1105_irq, IRQF_SHARED,
DRIVER_NAME, dev);
if (ret < 0)
goto err_workqueue;
return 0;
err_workqueue:
destroy_workqueue(dev->wq);
err_dvb_net:
dvb_net_release(&dev->dvbnet);
err_disconnect_frontend:
dmx->disconnect_frontend(dmx);
err_remove_mem_frontend:
dmx->remove_frontend(dmx, &dev->mem_frontend);
err_remove_hw_frontend:
dmx->remove_frontend(dmx, &dev->hw_frontend);
err_dvb_dmxdev_release:
dvb_dmxdev_release(&dev->dmxdev);
err_dvb_dmx_release:
dvb_dmx_release(dvbdemux);
err_dvb_unregister_adapter:
dvb_unregister_adapter(dvb_adapter);
err_i2c_del_adapters:
i2c_del_adapter(&dev->i2c_bb_adap);
err_i2c_del_adapter:
i2c_del_adapter(&dev->i2c_adap);
err_dm1105_hw_exit:
dm1105_hw_exit(dev);
err_pci_iounmap:
pci_iounmap(pdev, dev->io_mem);
err_pci_release_regions:
pci_release_regions(pdev);
err_pci_disable_device:
pci_disable_device(pdev);
err_kfree:
pci_set_drvdata(pdev, NULL);
kfree(dev);
return ret;
}
static void dm1105_remove(struct pci_dev *pdev)
{
struct dm1105_dev *dev = pci_get_drvdata(pdev);
struct dvb_adapter *dvb_adapter = &dev->dvb_adapter;
struct dvb_demux *dvbdemux = &dev->demux;
struct dmx_demux *dmx = &dvbdemux->dmx;
dm1105_ir_exit(dev);
dmx->close(dmx);
dvb_net_release(&dev->dvbnet);
if (dev->fe)
dvb_unregister_frontend(dev->fe);
dmx->disconnect_frontend(dmx);
dmx->remove_frontend(dmx, &dev->mem_frontend);
dmx->remove_frontend(dmx, &dev->hw_frontend);
dvb_dmxdev_release(&dev->dmxdev);
dvb_dmx_release(dvbdemux);
dvb_unregister_adapter(dvb_adapter);
if (&dev->i2c_adap)
i2c_del_adapter(&dev->i2c_adap);
dm1105_hw_exit(dev);
synchronize_irq(pdev->irq);
free_irq(pdev->irq, dev);
pci_iounmap(pdev, dev->io_mem);
pci_release_regions(pdev);
pci_disable_device(pdev);
pci_set_drvdata(pdev, NULL);
dm1105_devcount--;
kfree(dev);
}
static struct pci_device_id dm1105_id_table[] = {
{
.vendor = PCI_VENDOR_ID_TRIGEM,
.device = PCI_DEVICE_ID_DM1105,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
}, {
.vendor = PCI_VENDOR_ID_AXESS,
.device = PCI_DEVICE_ID_DM05,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
}, {
/* empty */
},
};
MODULE_DEVICE_TABLE(pci, dm1105_id_table);
static struct pci_driver dm1105_driver = {
.name = DRIVER_NAME,
.id_table = dm1105_id_table,
.probe = dm1105_probe,
.remove = dm1105_remove,
};
static int __init dm1105_init(void)
{
return pci_register_driver(&dm1105_driver);
}
static void __exit dm1105_exit(void)
{
pci_unregister_driver(&dm1105_driver);
}
module_init(dm1105_init);
module_exit(dm1105_exit);
MODULE_AUTHOR("Igor M. Liplianin <liplianin@me.by>");
MODULE_DESCRIPTION("SDMC DM1105 DVB driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
DJSteve/kernel_j5nlte_mm | arch/s390/oprofile/hwsampler.c | 2161 | 25105 | /*
* Copyright IBM Corp. 2010
* Author: Heinz Graalfs <graalfs@de.ibm.com>
*/
#include <linux/kernel_stat.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/smp.h>
#include <linux/errno.h>
#include <linux/workqueue.h>
#include <linux/interrupt.h>
#include <linux/notifier.h>
#include <linux/cpu.h>
#include <linux/semaphore.h>
#include <linux/oom.h>
#include <linux/oprofile.h>
#include <asm/facility.h>
#include <asm/cpu_mf.h>
#include <asm/irq.h>
#include "hwsampler.h"
#include "op_counter.h"
#define MAX_NUM_SDB 511
#define MIN_NUM_SDB 1
#define ALERT_REQ_MASK 0x4000000000000000ul
#define BUFFER_FULL_MASK 0x8000000000000000ul
DECLARE_PER_CPU(struct hws_cpu_buffer, sampler_cpu_buffer);
struct hws_execute_parms {
void *buffer;
signed int rc;
};
DEFINE_PER_CPU(struct hws_cpu_buffer, sampler_cpu_buffer);
EXPORT_PER_CPU_SYMBOL(sampler_cpu_buffer);
static DEFINE_MUTEX(hws_sem);
static DEFINE_MUTEX(hws_sem_oom);
static unsigned char hws_flush_all;
static unsigned int hws_oom;
static struct workqueue_struct *hws_wq;
static unsigned int hws_state;
enum {
HWS_INIT = 1,
HWS_DEALLOCATED,
HWS_STOPPED,
HWS_STARTED,
HWS_STOPPING };
/* set to 1 if called by kernel during memory allocation */
static unsigned char oom_killer_was_active;
/* size of SDBT and SDB as of allocate API */
static unsigned long num_sdbt = 100;
static unsigned long num_sdb = 511;
/* sampling interval (machine cycles) */
static unsigned long interval;
static unsigned long min_sampler_rate;
static unsigned long max_sampler_rate;
static int ssctl(void *buffer)
{
int cc;
/* set in order to detect a program check */
cc = 1;
asm volatile(
"0: .insn s,0xB2870000,0(%1)\n"
"1: ipm %0\n"
" srl %0,28\n"
"2:\n"
EX_TABLE(0b, 2b) EX_TABLE(1b, 2b)
: "+d" (cc), "+a" (buffer)
: "m" (*((struct hws_ssctl_request_block *)buffer))
: "cc", "memory");
return cc ? -EINVAL : 0 ;
}
static int qsi(void *buffer)
{
int cc;
cc = 1;
asm volatile(
"0: .insn s,0xB2860000,0(%1)\n"
"1: lhi %0,0\n"
"2:\n"
EX_TABLE(0b, 2b) EX_TABLE(1b, 2b)
: "=d" (cc), "+a" (buffer)
: "m" (*((struct hws_qsi_info_block *)buffer))
: "cc", "memory");
return cc ? -EINVAL : 0;
}
static void execute_qsi(void *parms)
{
struct hws_execute_parms *ep = parms;
ep->rc = qsi(ep->buffer);
}
static void execute_ssctl(void *parms)
{
struct hws_execute_parms *ep = parms;
ep->rc = ssctl(ep->buffer);
}
static int smp_ctl_ssctl_stop(int cpu)
{
int rc;
struct hws_execute_parms ep;
struct hws_cpu_buffer *cb;
cb = &per_cpu(sampler_cpu_buffer, cpu);
cb->ssctl.es = 0;
cb->ssctl.cs = 0;
ep.buffer = &cb->ssctl;
smp_call_function_single(cpu, execute_ssctl, &ep, 1);
rc = ep.rc;
if (rc) {
printk(KERN_ERR "hwsampler: CPU %d CPUMF SSCTL failed.\n", cpu);
dump_stack();
}
ep.buffer = &cb->qsi;
smp_call_function_single(cpu, execute_qsi, &ep, 1);
if (cb->qsi.es || cb->qsi.cs) {
printk(KERN_EMERG "CPUMF sampling did not stop properly.\n");
dump_stack();
}
return rc;
}
static int smp_ctl_ssctl_deactivate(int cpu)
{
int rc;
struct hws_execute_parms ep;
struct hws_cpu_buffer *cb;
cb = &per_cpu(sampler_cpu_buffer, cpu);
cb->ssctl.es = 1;
cb->ssctl.cs = 0;
ep.buffer = &cb->ssctl;
smp_call_function_single(cpu, execute_ssctl, &ep, 1);
rc = ep.rc;
if (rc)
printk(KERN_ERR "hwsampler: CPU %d CPUMF SSCTL failed.\n", cpu);
ep.buffer = &cb->qsi;
smp_call_function_single(cpu, execute_qsi, &ep, 1);
if (cb->qsi.cs)
printk(KERN_EMERG "CPUMF sampling was not set inactive.\n");
return rc;
}
static int smp_ctl_ssctl_enable_activate(int cpu, unsigned long interval)
{
int rc;
struct hws_execute_parms ep;
struct hws_cpu_buffer *cb;
cb = &per_cpu(sampler_cpu_buffer, cpu);
cb->ssctl.h = 1;
cb->ssctl.tear = cb->first_sdbt;
cb->ssctl.dear = *(unsigned long *) cb->first_sdbt;
cb->ssctl.interval = interval;
cb->ssctl.es = 1;
cb->ssctl.cs = 1;
ep.buffer = &cb->ssctl;
smp_call_function_single(cpu, execute_ssctl, &ep, 1);
rc = ep.rc;
if (rc)
printk(KERN_ERR "hwsampler: CPU %d CPUMF SSCTL failed.\n", cpu);
ep.buffer = &cb->qsi;
smp_call_function_single(cpu, execute_qsi, &ep, 1);
if (ep.rc)
printk(KERN_ERR "hwsampler: CPU %d CPUMF QSI failed.\n", cpu);
return rc;
}
static int smp_ctl_qsi(int cpu)
{
struct hws_execute_parms ep;
struct hws_cpu_buffer *cb;
cb = &per_cpu(sampler_cpu_buffer, cpu);
ep.buffer = &cb->qsi;
smp_call_function_single(cpu, execute_qsi, &ep, 1);
return ep.rc;
}
static inline unsigned long *trailer_entry_ptr(unsigned long v)
{
void *ret;
ret = (void *)v;
ret += PAGE_SIZE;
ret -= sizeof(struct hws_trailer_entry);
return (unsigned long *) ret;
}
static void hws_ext_handler(struct ext_code ext_code,
unsigned int param32, unsigned long param64)
{
struct hws_cpu_buffer *cb = &__get_cpu_var(sampler_cpu_buffer);
if (!(param32 & CPU_MF_INT_SF_MASK))
return;
inc_irq_stat(IRQEXT_CMS);
atomic_xchg(&cb->ext_params, atomic_read(&cb->ext_params) | param32);
if (hws_wq)
queue_work(hws_wq, &cb->worker);
}
static void worker(struct work_struct *work);
static void add_samples_to_oprofile(unsigned cpu, unsigned long *,
unsigned long *dear);
static void init_all_cpu_buffers(void)
{
int cpu;
struct hws_cpu_buffer *cb;
for_each_online_cpu(cpu) {
cb = &per_cpu(sampler_cpu_buffer, cpu);
memset(cb, 0, sizeof(struct hws_cpu_buffer));
}
}
static int is_link_entry(unsigned long *s)
{
return *s & 0x1ul ? 1 : 0;
}
static unsigned long *get_next_sdbt(unsigned long *s)
{
return (unsigned long *) (*s & ~0x1ul);
}
static int prepare_cpu_buffers(void)
{
int cpu;
int rc;
struct hws_cpu_buffer *cb;
rc = 0;
for_each_online_cpu(cpu) {
cb = &per_cpu(sampler_cpu_buffer, cpu);
atomic_set(&cb->ext_params, 0);
cb->worker_entry = 0;
cb->sample_overflow = 0;
cb->req_alert = 0;
cb->incorrect_sdbt_entry = 0;
cb->invalid_entry_address = 0;
cb->loss_of_sample_data = 0;
cb->sample_auth_change_alert = 0;
cb->finish = 0;
cb->oom = 0;
cb->stop_mode = 0;
}
return rc;
}
/*
* allocate_sdbt() - allocate sampler memory
* @cpu: the cpu for which sampler memory is allocated
*
* A 4K page is allocated for each requested SDBT.
* A maximum of 511 4K pages are allocated for the SDBs in each of the SDBTs.
* Set ALERT_REQ mask in each SDBs trailer.
* Returns zero if successful, <0 otherwise.
*/
static int allocate_sdbt(int cpu)
{
int j, k, rc;
unsigned long *sdbt;
unsigned long sdb;
unsigned long *tail;
unsigned long *trailer;
struct hws_cpu_buffer *cb;
cb = &per_cpu(sampler_cpu_buffer, cpu);
if (cb->first_sdbt)
return -EINVAL;
sdbt = NULL;
tail = sdbt;
for (j = 0; j < num_sdbt; j++) {
sdbt = (unsigned long *)get_zeroed_page(GFP_KERNEL);
mutex_lock(&hws_sem_oom);
/* OOM killer might have been activated */
barrier();
if (oom_killer_was_active || !sdbt) {
if (sdbt)
free_page((unsigned long)sdbt);
goto allocate_sdbt_error;
}
if (cb->first_sdbt == 0)
cb->first_sdbt = (unsigned long)sdbt;
/* link current page to tail of chain */
if (tail)
*tail = (unsigned long)(void *)sdbt + 1;
mutex_unlock(&hws_sem_oom);
for (k = 0; k < num_sdb; k++) {
/* get and set SDB page */
sdb = get_zeroed_page(GFP_KERNEL);
mutex_lock(&hws_sem_oom);
/* OOM killer might have been activated */
barrier();
if (oom_killer_was_active || !sdb) {
if (sdb)
free_page(sdb);
goto allocate_sdbt_error;
}
*sdbt = sdb;
trailer = trailer_entry_ptr(*sdbt);
*trailer = ALERT_REQ_MASK;
sdbt++;
mutex_unlock(&hws_sem_oom);
}
tail = sdbt;
}
mutex_lock(&hws_sem_oom);
if (oom_killer_was_active)
goto allocate_sdbt_error;
rc = 0;
if (tail)
*tail = (unsigned long)
((void *)cb->first_sdbt) + 1;
allocate_sdbt_exit:
mutex_unlock(&hws_sem_oom);
return rc;
allocate_sdbt_error:
rc = -ENOMEM;
goto allocate_sdbt_exit;
}
/*
* deallocate_sdbt() - deallocate all sampler memory
*
* For each online CPU all SDBT trees are deallocated.
* Returns the number of freed pages.
*/
static int deallocate_sdbt(void)
{
int cpu;
int counter;
counter = 0;
for_each_online_cpu(cpu) {
unsigned long start;
unsigned long sdbt;
unsigned long *curr;
struct hws_cpu_buffer *cb;
cb = &per_cpu(sampler_cpu_buffer, cpu);
if (!cb->first_sdbt)
continue;
sdbt = cb->first_sdbt;
curr = (unsigned long *) sdbt;
start = sdbt;
/* we'll free the SDBT after all SDBs are processed... */
while (1) {
if (!*curr || !sdbt)
break;
/* watch for link entry reset if found */
if (is_link_entry(curr)) {
curr = get_next_sdbt(curr);
if (sdbt)
free_page(sdbt);
/* we are done if we reach the start */
if ((unsigned long) curr == start)
break;
else
sdbt = (unsigned long) curr;
} else {
/* process SDB pointer */
if (*curr) {
free_page(*curr);
curr++;
}
}
counter++;
}
cb->first_sdbt = 0;
}
return counter;
}
static int start_sampling(int cpu)
{
int rc;
struct hws_cpu_buffer *cb;
cb = &per_cpu(sampler_cpu_buffer, cpu);
rc = smp_ctl_ssctl_enable_activate(cpu, interval);
if (rc) {
printk(KERN_INFO "hwsampler: CPU %d ssctl failed.\n", cpu);
goto start_exit;
}
rc = -EINVAL;
if (!cb->qsi.es) {
printk(KERN_INFO "hwsampler: CPU %d ssctl not enabled.\n", cpu);
goto start_exit;
}
if (!cb->qsi.cs) {
printk(KERN_INFO "hwsampler: CPU %d ssctl not active.\n", cpu);
goto start_exit;
}
printk(KERN_INFO
"hwsampler: CPU %d, CPUMF Sampling started, interval %lu.\n",
cpu, interval);
rc = 0;
start_exit:
return rc;
}
static int stop_sampling(int cpu)
{
unsigned long v;
int rc;
struct hws_cpu_buffer *cb;
rc = smp_ctl_qsi(cpu);
WARN_ON(rc);
cb = &per_cpu(sampler_cpu_buffer, cpu);
if (!rc && !cb->qsi.es)
printk(KERN_INFO "hwsampler: CPU %d, already stopped.\n", cpu);
rc = smp_ctl_ssctl_stop(cpu);
if (rc) {
printk(KERN_INFO "hwsampler: CPU %d, ssctl stop error %d.\n",
cpu, rc);
goto stop_exit;
}
printk(KERN_INFO "hwsampler: CPU %d, CPUMF Sampling stopped.\n", cpu);
stop_exit:
v = cb->req_alert;
if (v)
printk(KERN_ERR "hwsampler: CPU %d CPUMF Request alert,"
" count=%lu.\n", cpu, v);
v = cb->loss_of_sample_data;
if (v)
printk(KERN_ERR "hwsampler: CPU %d CPUMF Loss of sample data,"
" count=%lu.\n", cpu, v);
v = cb->invalid_entry_address;
if (v)
printk(KERN_ERR "hwsampler: CPU %d CPUMF Invalid entry address,"
" count=%lu.\n", cpu, v);
v = cb->incorrect_sdbt_entry;
if (v)
printk(KERN_ERR
"hwsampler: CPU %d CPUMF Incorrect SDBT address,"
" count=%lu.\n", cpu, v);
v = cb->sample_auth_change_alert;
if (v)
printk(KERN_ERR
"hwsampler: CPU %d CPUMF Sample authorization change,"
" count=%lu.\n", cpu, v);
return rc;
}
static int check_hardware_prerequisites(void)
{
if (!test_facility(68))
return -EOPNOTSUPP;
return 0;
}
/*
* hws_oom_callback() - the OOM callback function
*
* In case the callback is invoked during memory allocation for the
* hw sampler, all obtained memory is deallocated and a flag is set
* so main sampler memory allocation can exit with a failure code.
* In case the callback is invoked during sampling the hw sampler
* is deactivated for all CPUs.
*/
static int hws_oom_callback(struct notifier_block *nfb,
unsigned long dummy, void *parm)
{
unsigned long *freed;
int cpu;
struct hws_cpu_buffer *cb;
freed = parm;
mutex_lock(&hws_sem_oom);
if (hws_state == HWS_DEALLOCATED) {
/* during memory allocation */
if (oom_killer_was_active == 0) {
oom_killer_was_active = 1;
*freed += deallocate_sdbt();
}
} else {
int i;
cpu = get_cpu();
cb = &per_cpu(sampler_cpu_buffer, cpu);
if (!cb->oom) {
for_each_online_cpu(i) {
smp_ctl_ssctl_deactivate(i);
cb->oom = 1;
}
cb->finish = 1;
printk(KERN_INFO
"hwsampler: CPU %d, OOM notify during CPUMF Sampling.\n",
cpu);
}
}
mutex_unlock(&hws_sem_oom);
return NOTIFY_OK;
}
static struct notifier_block hws_oom_notifier = {
.notifier_call = hws_oom_callback
};
static int hws_cpu_callback(struct notifier_block *nfb,
unsigned long action, void *hcpu)
{
/* We do not have sampler space available for all possible CPUs.
All CPUs should be online when hw sampling is activated. */
return (hws_state <= HWS_DEALLOCATED) ? NOTIFY_OK : NOTIFY_BAD;
}
static struct notifier_block hws_cpu_notifier = {
.notifier_call = hws_cpu_callback
};
/**
* hwsampler_deactivate() - set hardware sampling temporarily inactive
* @cpu: specifies the CPU to be set inactive.
*
* Returns 0 on success, !0 on failure.
*/
int hwsampler_deactivate(unsigned int cpu)
{
/*
* Deactivate hw sampling temporarily and flush the buffer
* by pushing all the pending samples to oprofile buffer.
*
* This function can be called under one of the following conditions:
* Memory unmap, task is exiting.
*/
int rc;
struct hws_cpu_buffer *cb;
rc = 0;
mutex_lock(&hws_sem);
cb = &per_cpu(sampler_cpu_buffer, cpu);
if (hws_state == HWS_STARTED) {
rc = smp_ctl_qsi(cpu);
WARN_ON(rc);
if (cb->qsi.cs) {
rc = smp_ctl_ssctl_deactivate(cpu);
if (rc) {
printk(KERN_INFO
"hwsampler: CPU %d, CPUMF Deactivation failed.\n", cpu);
cb->finish = 1;
hws_state = HWS_STOPPING;
} else {
hws_flush_all = 1;
/* Add work to queue to read pending samples.*/
queue_work_on(cpu, hws_wq, &cb->worker);
}
}
}
mutex_unlock(&hws_sem);
if (hws_wq)
flush_workqueue(hws_wq);
return rc;
}
/**
* hwsampler_activate() - activate/resume hardware sampling which was deactivated
* @cpu: specifies the CPU to be set active.
*
* Returns 0 on success, !0 on failure.
*/
int hwsampler_activate(unsigned int cpu)
{
/*
* Re-activate hw sampling. This should be called in pair with
* hwsampler_deactivate().
*/
int rc;
struct hws_cpu_buffer *cb;
rc = 0;
mutex_lock(&hws_sem);
cb = &per_cpu(sampler_cpu_buffer, cpu);
if (hws_state == HWS_STARTED) {
rc = smp_ctl_qsi(cpu);
WARN_ON(rc);
if (!cb->qsi.cs) {
hws_flush_all = 0;
rc = smp_ctl_ssctl_enable_activate(cpu, interval);
if (rc) {
printk(KERN_ERR
"CPU %d, CPUMF activate sampling failed.\n",
cpu);
}
}
}
mutex_unlock(&hws_sem);
return rc;
}
static int check_qsi_on_setup(void)
{
int rc;
unsigned int cpu;
struct hws_cpu_buffer *cb;
for_each_online_cpu(cpu) {
cb = &per_cpu(sampler_cpu_buffer, cpu);
rc = smp_ctl_qsi(cpu);
WARN_ON(rc);
if (rc)
return -EOPNOTSUPP;
if (!cb->qsi.as) {
printk(KERN_INFO "hwsampler: CPUMF sampling is not authorized.\n");
return -EINVAL;
}
if (cb->qsi.es) {
printk(KERN_WARNING "hwsampler: CPUMF is still enabled.\n");
rc = smp_ctl_ssctl_stop(cpu);
if (rc)
return -EINVAL;
printk(KERN_INFO
"CPU %d, CPUMF Sampling stopped now.\n", cpu);
}
}
return 0;
}
static int check_qsi_on_start(void)
{
unsigned int cpu;
int rc;
struct hws_cpu_buffer *cb;
for_each_online_cpu(cpu) {
cb = &per_cpu(sampler_cpu_buffer, cpu);
rc = smp_ctl_qsi(cpu);
WARN_ON(rc);
if (!cb->qsi.as)
return -EINVAL;
if (cb->qsi.es)
return -EINVAL;
if (cb->qsi.cs)
return -EINVAL;
}
return 0;
}
static void worker_on_start(unsigned int cpu)
{
struct hws_cpu_buffer *cb;
cb = &per_cpu(sampler_cpu_buffer, cpu);
cb->worker_entry = cb->first_sdbt;
}
static int worker_check_error(unsigned int cpu, int ext_params)
{
int rc;
unsigned long *sdbt;
struct hws_cpu_buffer *cb;
rc = 0;
cb = &per_cpu(sampler_cpu_buffer, cpu);
sdbt = (unsigned long *) cb->worker_entry;
if (!sdbt || !*sdbt)
return -EINVAL;
if (ext_params & CPU_MF_INT_SF_PRA)
cb->req_alert++;
if (ext_params & CPU_MF_INT_SF_LSDA)
cb->loss_of_sample_data++;
if (ext_params & CPU_MF_INT_SF_IAE) {
cb->invalid_entry_address++;
rc = -EINVAL;
}
if (ext_params & CPU_MF_INT_SF_ISE) {
cb->incorrect_sdbt_entry++;
rc = -EINVAL;
}
if (ext_params & CPU_MF_INT_SF_SACA) {
cb->sample_auth_change_alert++;
rc = -EINVAL;
}
return rc;
}
static void worker_on_finish(unsigned int cpu)
{
int rc, i;
struct hws_cpu_buffer *cb;
cb = &per_cpu(sampler_cpu_buffer, cpu);
if (cb->finish) {
rc = smp_ctl_qsi(cpu);
WARN_ON(rc);
if (cb->qsi.es) {
printk(KERN_INFO
"hwsampler: CPU %d, CPUMF Stop/Deactivate sampling.\n",
cpu);
rc = smp_ctl_ssctl_stop(cpu);
if (rc)
printk(KERN_INFO
"hwsampler: CPU %d, CPUMF Deactivation failed.\n",
cpu);
for_each_online_cpu(i) {
if (i == cpu)
continue;
if (!cb->finish) {
cb->finish = 1;
queue_work_on(i, hws_wq,
&cb->worker);
}
}
}
}
}
static void worker_on_interrupt(unsigned int cpu)
{
unsigned long *sdbt;
unsigned char done;
struct hws_cpu_buffer *cb;
cb = &per_cpu(sampler_cpu_buffer, cpu);
sdbt = (unsigned long *) cb->worker_entry;
done = 0;
/* do not proceed if stop was entered,
* forget the buffers not yet processed */
while (!done && !cb->stop_mode) {
unsigned long *trailer;
struct hws_trailer_entry *te;
unsigned long *dear = 0;
trailer = trailer_entry_ptr(*sdbt);
/* leave loop if no more work to do */
if (!(*trailer & BUFFER_FULL_MASK)) {
done = 1;
if (!hws_flush_all)
continue;
}
te = (struct hws_trailer_entry *)trailer;
cb->sample_overflow += te->overflow;
add_samples_to_oprofile(cpu, sdbt, dear);
/* reset trailer */
xchg((unsigned char *) te, 0x40);
/* advance to next sdb slot in current sdbt */
sdbt++;
/* in case link bit is set use address w/o link bit */
if (is_link_entry(sdbt))
sdbt = get_next_sdbt(sdbt);
cb->worker_entry = (unsigned long)sdbt;
}
}
static void add_samples_to_oprofile(unsigned int cpu, unsigned long *sdbt,
unsigned long *dear)
{
struct hws_data_entry *sample_data_ptr;
unsigned long *trailer;
trailer = trailer_entry_ptr(*sdbt);
if (dear) {
if (dear > trailer)
return;
trailer = dear;
}
sample_data_ptr = (struct hws_data_entry *)(*sdbt);
while ((unsigned long *)sample_data_ptr < trailer) {
struct pt_regs *regs = NULL;
struct task_struct *tsk = NULL;
/*
* Check sampling mode, 1 indicates basic (=customer) sampling
* mode.
*/
if (sample_data_ptr->def != 1) {
/* sample slot is not yet written */
break;
} else {
/* make sure we don't use it twice,
* the next time the sampler will set it again */
sample_data_ptr->def = 0;
}
/* Get pt_regs. */
if (sample_data_ptr->P == 1) {
/* userspace sample */
unsigned int pid = sample_data_ptr->prim_asn;
if (!counter_config.user)
goto skip_sample;
rcu_read_lock();
tsk = pid_task(find_vpid(pid), PIDTYPE_PID);
if (tsk)
regs = task_pt_regs(tsk);
rcu_read_unlock();
} else {
/* kernelspace sample */
if (!counter_config.kernel)
goto skip_sample;
regs = task_pt_regs(current);
}
mutex_lock(&hws_sem);
oprofile_add_ext_hw_sample(sample_data_ptr->ia, regs, 0,
!sample_data_ptr->P, tsk);
mutex_unlock(&hws_sem);
skip_sample:
sample_data_ptr++;
}
}
static void worker(struct work_struct *work)
{
unsigned int cpu;
int ext_params;
struct hws_cpu_buffer *cb;
cb = container_of(work, struct hws_cpu_buffer, worker);
cpu = smp_processor_id();
ext_params = atomic_xchg(&cb->ext_params, 0);
if (!cb->worker_entry)
worker_on_start(cpu);
if (worker_check_error(cpu, ext_params))
return;
if (!cb->finish)
worker_on_interrupt(cpu);
if (cb->finish)
worker_on_finish(cpu);
}
/**
* hwsampler_allocate() - allocate memory for the hardware sampler
* @sdbt: number of SDBTs per online CPU (must be > 0)
* @sdb: number of SDBs per SDBT (minimum 1, maximum 511)
*
* Returns 0 on success, !0 on failure.
*/
int hwsampler_allocate(unsigned long sdbt, unsigned long sdb)
{
int cpu, rc;
mutex_lock(&hws_sem);
rc = -EINVAL;
if (hws_state != HWS_DEALLOCATED)
goto allocate_exit;
if (sdbt < 1)
goto allocate_exit;
if (sdb > MAX_NUM_SDB || sdb < MIN_NUM_SDB)
goto allocate_exit;
num_sdbt = sdbt;
num_sdb = sdb;
oom_killer_was_active = 0;
register_oom_notifier(&hws_oom_notifier);
for_each_online_cpu(cpu) {
if (allocate_sdbt(cpu)) {
unregister_oom_notifier(&hws_oom_notifier);
goto allocate_error;
}
}
unregister_oom_notifier(&hws_oom_notifier);
if (oom_killer_was_active)
goto allocate_error;
hws_state = HWS_STOPPED;
rc = 0;
allocate_exit:
mutex_unlock(&hws_sem);
return rc;
allocate_error:
rc = -ENOMEM;
printk(KERN_ERR "hwsampler: CPUMF Memory allocation failed.\n");
goto allocate_exit;
}
/**
* hwsampler_deallocate() - deallocate hardware sampler memory
*
* Returns 0 on success, !0 on failure.
*/
int hwsampler_deallocate(void)
{
int rc;
mutex_lock(&hws_sem);
rc = -EINVAL;
if (hws_state != HWS_STOPPED)
goto deallocate_exit;
measurement_alert_subclass_unregister();
deallocate_sdbt();
hws_state = HWS_DEALLOCATED;
rc = 0;
deallocate_exit:
mutex_unlock(&hws_sem);
return rc;
}
unsigned long hwsampler_query_min_interval(void)
{
return min_sampler_rate;
}
unsigned long hwsampler_query_max_interval(void)
{
return max_sampler_rate;
}
unsigned long hwsampler_get_sample_overflow_count(unsigned int cpu)
{
struct hws_cpu_buffer *cb;
cb = &per_cpu(sampler_cpu_buffer, cpu);
return cb->sample_overflow;
}
int hwsampler_setup(void)
{
int rc;
int cpu;
struct hws_cpu_buffer *cb;
mutex_lock(&hws_sem);
rc = -EINVAL;
if (hws_state)
goto setup_exit;
hws_state = HWS_INIT;
init_all_cpu_buffers();
rc = check_hardware_prerequisites();
if (rc)
goto setup_exit;
rc = check_qsi_on_setup();
if (rc)
goto setup_exit;
rc = -EINVAL;
hws_wq = create_workqueue("hwsampler");
if (!hws_wq)
goto setup_exit;
register_cpu_notifier(&hws_cpu_notifier);
for_each_online_cpu(cpu) {
cb = &per_cpu(sampler_cpu_buffer, cpu);
INIT_WORK(&cb->worker, worker);
rc = smp_ctl_qsi(cpu);
WARN_ON(rc);
if (min_sampler_rate != cb->qsi.min_sampl_rate) {
if (min_sampler_rate) {
printk(KERN_WARNING
"hwsampler: different min sampler rate values.\n");
if (min_sampler_rate < cb->qsi.min_sampl_rate)
min_sampler_rate =
cb->qsi.min_sampl_rate;
} else
min_sampler_rate = cb->qsi.min_sampl_rate;
}
if (max_sampler_rate != cb->qsi.max_sampl_rate) {
if (max_sampler_rate) {
printk(KERN_WARNING
"hwsampler: different max sampler rate values.\n");
if (max_sampler_rate > cb->qsi.max_sampl_rate)
max_sampler_rate =
cb->qsi.max_sampl_rate;
} else
max_sampler_rate = cb->qsi.max_sampl_rate;
}
}
register_external_interrupt(0x1407, hws_ext_handler);
hws_state = HWS_DEALLOCATED;
rc = 0;
setup_exit:
mutex_unlock(&hws_sem);
return rc;
}
int hwsampler_shutdown(void)
{
int rc;
mutex_lock(&hws_sem);
rc = -EINVAL;
if (hws_state == HWS_DEALLOCATED || hws_state == HWS_STOPPED) {
mutex_unlock(&hws_sem);
if (hws_wq)
flush_workqueue(hws_wq);
mutex_lock(&hws_sem);
if (hws_state == HWS_STOPPED) {
measurement_alert_subclass_unregister();
deallocate_sdbt();
}
if (hws_wq) {
destroy_workqueue(hws_wq);
hws_wq = NULL;
}
unregister_external_interrupt(0x1407, hws_ext_handler);
hws_state = HWS_INIT;
rc = 0;
}
mutex_unlock(&hws_sem);
unregister_cpu_notifier(&hws_cpu_notifier);
return rc;
}
/**
* hwsampler_start_all() - start hardware sampling on all online CPUs
* @rate: specifies the used interval when samples are taken
*
* Returns 0 on success, !0 on failure.
*/
int hwsampler_start_all(unsigned long rate)
{
int rc, cpu;
mutex_lock(&hws_sem);
hws_oom = 0;
rc = -EINVAL;
if (hws_state != HWS_STOPPED)
goto start_all_exit;
interval = rate;
/* fail if rate is not valid */
if (interval < min_sampler_rate || interval > max_sampler_rate)
goto start_all_exit;
rc = check_qsi_on_start();
if (rc)
goto start_all_exit;
rc = prepare_cpu_buffers();
if (rc)
goto start_all_exit;
for_each_online_cpu(cpu) {
rc = start_sampling(cpu);
if (rc)
break;
}
if (rc) {
for_each_online_cpu(cpu) {
stop_sampling(cpu);
}
goto start_all_exit;
}
hws_state = HWS_STARTED;
rc = 0;
start_all_exit:
mutex_unlock(&hws_sem);
if (rc)
return rc;
register_oom_notifier(&hws_oom_notifier);
hws_oom = 1;
hws_flush_all = 0;
/* now let them in, 1407 CPUMF external interrupts */
measurement_alert_subclass_register();
return 0;
}
/**
* hwsampler_stop_all() - stop hardware sampling on all online CPUs
*
* Returns 0 on success, !0 on failure.
*/
int hwsampler_stop_all(void)
{
int tmp_rc, rc, cpu;
struct hws_cpu_buffer *cb;
mutex_lock(&hws_sem);
rc = 0;
if (hws_state == HWS_INIT) {
mutex_unlock(&hws_sem);
return rc;
}
hws_state = HWS_STOPPING;
mutex_unlock(&hws_sem);
for_each_online_cpu(cpu) {
cb = &per_cpu(sampler_cpu_buffer, cpu);
cb->stop_mode = 1;
tmp_rc = stop_sampling(cpu);
if (tmp_rc)
rc = tmp_rc;
}
if (hws_wq)
flush_workqueue(hws_wq);
mutex_lock(&hws_sem);
if (hws_oom) {
unregister_oom_notifier(&hws_oom_notifier);
hws_oom = 0;
}
hws_state = HWS_STOPPED;
mutex_unlock(&hws_sem);
return rc;
}
| gpl-2.0 |
tiagormk/linux-vitamins-odroidxu | arch/powerpc/platforms/82xx/km82xx.c | 2673 | 6341 | /*
* Keymile km82xx support
* Copyright 2008-2011 DENX Software Engineering GmbH
* Author: Heiko Schocher <hs@denx.de>
*
* based on code from:
* Copyright 2007 Freescale Semiconductor, Inc.
* Author: Scott Wood <scottwood@freescale.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/fsl_devices.h>
#include <linux/of_platform.h>
#include <linux/io.h>
#include <asm/cpm2.h>
#include <asm/udbg.h>
#include <asm/machdep.h>
#include <linux/time.h>
#include <asm/mpc8260.h>
#include <asm/prom.h>
#include <sysdev/fsl_soc.h>
#include <sysdev/cpm2_pic.h>
#include "pq2.h"
static void __init km82xx_pic_init(void)
{
struct device_node *np = of_find_compatible_node(NULL, NULL,
"fsl,pq2-pic");
if (!np) {
pr_err("PIC init: can not find cpm-pic node\n");
return;
}
cpm2_pic_init(np);
of_node_put(np);
}
struct cpm_pin {
int port, pin, flags;
};
static __initdata struct cpm_pin km82xx_pins[] = {
/* SMC1 */
{2, 4, CPM_PIN_INPUT | CPM_PIN_PRIMARY},
{2, 5, CPM_PIN_OUTPUT | CPM_PIN_PRIMARY},
/* SMC2 */
{0, 8, CPM_PIN_INPUT | CPM_PIN_PRIMARY},
{0, 9, CPM_PIN_OUTPUT | CPM_PIN_PRIMARY},
/* SCC1 */
{2, 21, CPM_PIN_INPUT | CPM_PIN_PRIMARY},
{2, 15, CPM_PIN_INPUT | CPM_PIN_PRIMARY},
{3, 31, CPM_PIN_INPUT | CPM_PIN_PRIMARY},
{3, 30, CPM_PIN_OUTPUT | CPM_PIN_SECONDARY},
/* SCC4 */
{2, 25, CPM_PIN_INPUT | CPM_PIN_PRIMARY},
{2, 24, CPM_PIN_INPUT | CPM_PIN_PRIMARY},
{2, 9, CPM_PIN_INPUT | CPM_PIN_PRIMARY},
{2, 8, CPM_PIN_INPUT | CPM_PIN_PRIMARY},
{3, 22, CPM_PIN_INPUT | CPM_PIN_PRIMARY},
{3, 21, CPM_PIN_OUTPUT | CPM_PIN_PRIMARY},
/* FCC1 */
{0, 14, CPM_PIN_INPUT | CPM_PIN_PRIMARY},
{0, 15, CPM_PIN_INPUT | CPM_PIN_PRIMARY},
{0, 16, CPM_PIN_INPUT | CPM_PIN_PRIMARY},
{0, 17, CPM_PIN_INPUT | CPM_PIN_PRIMARY},
{0, 18, CPM_PIN_OUTPUT | CPM_PIN_PRIMARY},
{0, 19, CPM_PIN_OUTPUT | CPM_PIN_PRIMARY},
{0, 20, CPM_PIN_OUTPUT | CPM_PIN_PRIMARY},
{0, 21, CPM_PIN_OUTPUT | CPM_PIN_PRIMARY},
{0, 26, CPM_PIN_INPUT | CPM_PIN_SECONDARY},
{0, 27, CPM_PIN_INPUT | CPM_PIN_SECONDARY},
{0, 28, CPM_PIN_OUTPUT | CPM_PIN_SECONDARY},
{0, 29, CPM_PIN_OUTPUT | CPM_PIN_SECONDARY},
{0, 30, CPM_PIN_INPUT | CPM_PIN_SECONDARY},
{0, 31, CPM_PIN_INPUT | CPM_PIN_SECONDARY},
{2, 22, CPM_PIN_INPUT | CPM_PIN_PRIMARY},
{2, 23, CPM_PIN_INPUT | CPM_PIN_PRIMARY},
/* FCC2 */
{1, 18, CPM_PIN_INPUT | CPM_PIN_PRIMARY},
{1, 19, CPM_PIN_INPUT | CPM_PIN_PRIMARY},
{1, 20, CPM_PIN_INPUT | CPM_PIN_PRIMARY},
{1, 21, CPM_PIN_INPUT | CPM_PIN_PRIMARY},
{1, 22, CPM_PIN_OUTPUT | CPM_PIN_PRIMARY},
{1, 23, CPM_PIN_OUTPUT | CPM_PIN_PRIMARY},
{1, 24, CPM_PIN_OUTPUT | CPM_PIN_PRIMARY},
{1, 25, CPM_PIN_OUTPUT | CPM_PIN_PRIMARY},
{1, 26, CPM_PIN_INPUT | CPM_PIN_PRIMARY},
{1, 27, CPM_PIN_INPUT | CPM_PIN_PRIMARY},
{1, 28, CPM_PIN_INPUT | CPM_PIN_PRIMARY},
{1, 29, CPM_PIN_OUTPUT | CPM_PIN_SECONDARY},
{1, 30, CPM_PIN_INPUT | CPM_PIN_PRIMARY},
{1, 31, CPM_PIN_OUTPUT | CPM_PIN_PRIMARY},
{2, 18, CPM_PIN_INPUT | CPM_PIN_PRIMARY},
{2, 19, CPM_PIN_INPUT | CPM_PIN_PRIMARY},
/* MDC */
{0, 13, CPM_PIN_OUTPUT | CPM_PIN_GPIO},
#if defined(CONFIG_I2C_CPM)
/* I2C */
{3, 14, CPM_PIN_INPUT | CPM_PIN_SECONDARY | CPM_PIN_OPENDRAIN},
{3, 15, CPM_PIN_INPUT | CPM_PIN_SECONDARY | CPM_PIN_OPENDRAIN},
#endif
/* USB */
{0, 10, CPM_PIN_OUTPUT | CPM_PIN_GPIO}, /* FULL_SPEED */
{0, 11, CPM_PIN_OUTPUT | CPM_PIN_GPIO}, /*/SLAVE */
{2, 10, CPM_PIN_INPUT | CPM_PIN_PRIMARY}, /* RXN */
{2, 11, CPM_PIN_INPUT | CPM_PIN_PRIMARY}, /* RXP */
{2, 20, CPM_PIN_OUTPUT | CPM_PIN_PRIMARY}, /* /OE */
{2, 27, CPM_PIN_INPUT | CPM_PIN_PRIMARY}, /* RXCLK */
{3, 23, CPM_PIN_OUTPUT | CPM_PIN_PRIMARY}, /* TXP */
{3, 24, CPM_PIN_OUTPUT | CPM_PIN_PRIMARY}, /* TXN */
{3, 25, CPM_PIN_INPUT | CPM_PIN_PRIMARY}, /* RXD */
/* SPI */
{3, 16, CPM_PIN_INPUT | CPM_PIN_SECONDARY},/* SPI_MISO PD16 */
{3, 17, CPM_PIN_INPUT | CPM_PIN_SECONDARY},/* SPI_MOSI PD17 */
{3, 18, CPM_PIN_INPUT | CPM_PIN_SECONDARY},/* SPI_CLK PD18 */
};
static void __init init_ioports(void)
{
int i;
for (i = 0; i < ARRAY_SIZE(km82xx_pins); i++) {
const struct cpm_pin *pin = &km82xx_pins[i];
cpm2_set_pin(pin->port, pin->pin, pin->flags);
}
cpm2_smc_clk_setup(CPM_CLK_SMC2, CPM_BRG8);
cpm2_smc_clk_setup(CPM_CLK_SMC1, CPM_BRG7);
cpm2_clk_setup(CPM_CLK_SCC1, CPM_CLK11, CPM_CLK_RX);
cpm2_clk_setup(CPM_CLK_SCC1, CPM_CLK11, CPM_CLK_TX);
cpm2_clk_setup(CPM_CLK_SCC3, CPM_CLK5, CPM_CLK_RTX);
cpm2_clk_setup(CPM_CLK_SCC4, CPM_CLK7, CPM_CLK_RX);
cpm2_clk_setup(CPM_CLK_SCC4, CPM_CLK8, CPM_CLK_TX);
cpm2_clk_setup(CPM_CLK_FCC1, CPM_CLK10, CPM_CLK_RX);
cpm2_clk_setup(CPM_CLK_FCC1, CPM_CLK9, CPM_CLK_TX);
cpm2_clk_setup(CPM_CLK_FCC2, CPM_CLK13, CPM_CLK_RX);
cpm2_clk_setup(CPM_CLK_FCC2, CPM_CLK14, CPM_CLK_TX);
/* Force USB FULL SPEED bit to '1' */
setbits32(&cpm2_immr->im_ioport.iop_pdata, 1 << (31 - 10));
/* clear USB_SLAVE */
clrbits32(&cpm2_immr->im_ioport.iop_pdata, 1 << (31 - 11));
}
static void __init km82xx_setup_arch(void)
{
if (ppc_md.progress)
ppc_md.progress("km82xx_setup_arch()", 0);
cpm2_reset();
/* When this is set, snooping CPM DMA from RAM causes
* machine checks. See erratum SIU18.
*/
clrbits32(&cpm2_immr->im_siu_conf.siu_82xx.sc_bcr, MPC82XX_BCR_PLDP);
init_ioports();
if (ppc_md.progress)
ppc_md.progress("km82xx_setup_arch(), finish", 0);
}
static __initdata struct of_device_id of_bus_ids[] = {
{ .compatible = "simple-bus", },
{},
};
static int __init declare_of_platform_devices(void)
{
of_platform_bus_probe(NULL, of_bus_ids, NULL);
return 0;
}
machine_device_initcall(km82xx, declare_of_platform_devices);
/*
* Called very early, device-tree isn't unflattened
*/
static int __init km82xx_probe(void)
{
unsigned long root = of_get_flat_dt_root();
return of_flat_dt_is_compatible(root, "keymile,km82xx");
}
define_machine(km82xx)
{
.name = "Keymile km82xx",
.probe = km82xx_probe,
.setup_arch = km82xx_setup_arch,
.init_IRQ = km82xx_pic_init,
.get_irq = cpm2_get_irq,
.calibrate_decr = generic_calibrate_decr,
.restart = pq2_restart,
.progress = udbg_progress,
};
| gpl-2.0 |
LeeDroid-/LeeDrOiD-Hima-M9 | drivers/s390/cio/device_fsm.c | 2673 | 31222 | /*
* finite state machine for device handling
*
* Copyright IBM Corp. 2002, 2008
* Author(s): Cornelia Huck (cornelia.huck@de.ibm.com)
* Martin Schwidefsky (schwidefsky@de.ibm.com)
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/jiffies.h>
#include <linux/string.h>
#include <asm/ccwdev.h>
#include <asm/cio.h>
#include <asm/chpid.h>
#include "cio.h"
#include "cio_debug.h"
#include "css.h"
#include "device.h"
#include "chsc.h"
#include "ioasm.h"
#include "chp.h"
static int timeout_log_enabled;
static int __init ccw_timeout_log_setup(char *unused)
{
timeout_log_enabled = 1;
return 1;
}
__setup("ccw_timeout_log", ccw_timeout_log_setup);
static void ccw_timeout_log(struct ccw_device *cdev)
{
struct schib schib;
struct subchannel *sch;
struct io_subchannel_private *private;
union orb *orb;
int cc;
sch = to_subchannel(cdev->dev.parent);
private = to_io_private(sch);
orb = &private->orb;
cc = stsch_err(sch->schid, &schib);
printk(KERN_WARNING "cio: ccw device timeout occurred at %llx, "
"device information:\n", get_tod_clock());
printk(KERN_WARNING "cio: orb:\n");
print_hex_dump(KERN_WARNING, "cio: ", DUMP_PREFIX_NONE, 16, 1,
orb, sizeof(*orb), 0);
printk(KERN_WARNING "cio: ccw device bus id: %s\n",
dev_name(&cdev->dev));
printk(KERN_WARNING "cio: subchannel bus id: %s\n",
dev_name(&sch->dev));
printk(KERN_WARNING "cio: subchannel lpm: %02x, opm: %02x, "
"vpm: %02x\n", sch->lpm, sch->opm, sch->vpm);
if (orb->tm.b) {
printk(KERN_WARNING "cio: orb indicates transport mode\n");
printk(KERN_WARNING "cio: last tcw:\n");
print_hex_dump(KERN_WARNING, "cio: ", DUMP_PREFIX_NONE, 16, 1,
(void *)(addr_t)orb->tm.tcw,
sizeof(struct tcw), 0);
} else {
printk(KERN_WARNING "cio: orb indicates command mode\n");
if ((void *)(addr_t)orb->cmd.cpa == &private->sense_ccw ||
(void *)(addr_t)orb->cmd.cpa == cdev->private->iccws)
printk(KERN_WARNING "cio: last channel program "
"(intern):\n");
else
printk(KERN_WARNING "cio: last channel program:\n");
print_hex_dump(KERN_WARNING, "cio: ", DUMP_PREFIX_NONE, 16, 1,
(void *)(addr_t)orb->cmd.cpa,
sizeof(struct ccw1), 0);
}
printk(KERN_WARNING "cio: ccw device state: %d\n",
cdev->private->state);
printk(KERN_WARNING "cio: store subchannel returned: cc=%d\n", cc);
printk(KERN_WARNING "cio: schib:\n");
print_hex_dump(KERN_WARNING, "cio: ", DUMP_PREFIX_NONE, 16, 1,
&schib, sizeof(schib), 0);
printk(KERN_WARNING "cio: ccw device flags:\n");
print_hex_dump(KERN_WARNING, "cio: ", DUMP_PREFIX_NONE, 16, 1,
&cdev->private->flags, sizeof(cdev->private->flags), 0);
}
/*
* Timeout function. It just triggers a DEV_EVENT_TIMEOUT.
*/
static void
ccw_device_timeout(unsigned long data)
{
struct ccw_device *cdev;
cdev = (struct ccw_device *) data;
spin_lock_irq(cdev->ccwlock);
if (timeout_log_enabled)
ccw_timeout_log(cdev);
dev_fsm_event(cdev, DEV_EVENT_TIMEOUT);
spin_unlock_irq(cdev->ccwlock);
}
/*
* Set timeout
*/
void
ccw_device_set_timeout(struct ccw_device *cdev, int expires)
{
if (expires == 0) {
del_timer(&cdev->private->timer);
return;
}
if (timer_pending(&cdev->private->timer)) {
if (mod_timer(&cdev->private->timer, jiffies + expires))
return;
}
cdev->private->timer.function = ccw_device_timeout;
cdev->private->timer.data = (unsigned long) cdev;
cdev->private->timer.expires = jiffies + expires;
add_timer(&cdev->private->timer);
}
/*
* Cancel running i/o. This is called repeatedly since halt/clear are
* asynchronous operations. We do one try with cio_cancel, two tries
* with cio_halt, 255 tries with cio_clear. If everythings fails panic.
* Returns 0 if device now idle, -ENODEV for device not operational and
* -EBUSY if an interrupt is expected (either from halt/clear or from a
* status pending).
*/
int
ccw_device_cancel_halt_clear(struct ccw_device *cdev)
{
struct subchannel *sch;
int ret;
sch = to_subchannel(cdev->dev.parent);
if (cio_update_schib(sch))
return -ENODEV;
if (!sch->schib.pmcw.ena)
/* Not operational -> done. */
return 0;
/* Stage 1: cancel io. */
if (!(scsw_actl(&sch->schib.scsw) & SCSW_ACTL_HALT_PEND) &&
!(scsw_actl(&sch->schib.scsw) & SCSW_ACTL_CLEAR_PEND)) {
if (!scsw_is_tm(&sch->schib.scsw)) {
ret = cio_cancel(sch);
if (ret != -EINVAL)
return ret;
}
/* cancel io unsuccessful or not applicable (transport mode).
* Continue with asynchronous instructions. */
cdev->private->iretry = 3; /* 3 halt retries. */
}
if (!(scsw_actl(&sch->schib.scsw) & SCSW_ACTL_CLEAR_PEND)) {
/* Stage 2: halt io. */
if (cdev->private->iretry) {
cdev->private->iretry--;
ret = cio_halt(sch);
if (ret != -EBUSY)
return (ret == 0) ? -EBUSY : ret;
}
/* halt io unsuccessful. */
cdev->private->iretry = 255; /* 255 clear retries. */
}
/* Stage 3: clear io. */
if (cdev->private->iretry) {
cdev->private->iretry--;
ret = cio_clear (sch);
return (ret == 0) ? -EBUSY : ret;
}
/* Function was unsuccessful */
CIO_MSG_EVENT(0, "0.%x.%04x: could not stop I/O\n",
cdev->private->dev_id.ssid, cdev->private->dev_id.devno);
return -EIO;
}
void ccw_device_update_sense_data(struct ccw_device *cdev)
{
memset(&cdev->id, 0, sizeof(cdev->id));
cdev->id.cu_type = cdev->private->senseid.cu_type;
cdev->id.cu_model = cdev->private->senseid.cu_model;
cdev->id.dev_type = cdev->private->senseid.dev_type;
cdev->id.dev_model = cdev->private->senseid.dev_model;
}
int ccw_device_test_sense_data(struct ccw_device *cdev)
{
return cdev->id.cu_type == cdev->private->senseid.cu_type &&
cdev->id.cu_model == cdev->private->senseid.cu_model &&
cdev->id.dev_type == cdev->private->senseid.dev_type &&
cdev->id.dev_model == cdev->private->senseid.dev_model;
}
/*
* The machine won't give us any notification by machine check if a chpid has
* been varied online on the SE so we have to find out by magic (i. e. driving
* the channel subsystem to device selection and updating our path masks).
*/
static void
__recover_lost_chpids(struct subchannel *sch, int old_lpm)
{
int mask, i;
struct chp_id chpid;
chp_id_init(&chpid);
for (i = 0; i<8; i++) {
mask = 0x80 >> i;
if (!(sch->lpm & mask))
continue;
if (old_lpm & mask)
continue;
chpid.id = sch->schib.pmcw.chpid[i];
if (!chp_is_registered(chpid))
css_schedule_eval_all();
}
}
/*
* Stop device recognition.
*/
static void
ccw_device_recog_done(struct ccw_device *cdev, int state)
{
struct subchannel *sch;
int old_lpm;
sch = to_subchannel(cdev->dev.parent);
if (cio_disable_subchannel(sch))
state = DEV_STATE_NOT_OPER;
/*
* Now that we tried recognition, we have performed device selection
* through ssch() and the path information is up to date.
*/
old_lpm = sch->lpm;
/* Check since device may again have become not operational. */
if (cio_update_schib(sch))
state = DEV_STATE_NOT_OPER;
else
sch->lpm = sch->schib.pmcw.pam & sch->opm;
if (cdev->private->state == DEV_STATE_DISCONNECTED_SENSE_ID)
/* Force reprobe on all chpids. */
old_lpm = 0;
if (sch->lpm != old_lpm)
__recover_lost_chpids(sch, old_lpm);
if (cdev->private->state == DEV_STATE_DISCONNECTED_SENSE_ID &&
(state == DEV_STATE_NOT_OPER || state == DEV_STATE_BOXED)) {
cdev->private->flags.recog_done = 1;
cdev->private->state = DEV_STATE_DISCONNECTED;
wake_up(&cdev->private->wait_q);
return;
}
if (cdev->private->flags.resuming) {
cdev->private->state = state;
cdev->private->flags.recog_done = 1;
wake_up(&cdev->private->wait_q);
return;
}
switch (state) {
case DEV_STATE_NOT_OPER:
break;
case DEV_STATE_OFFLINE:
if (!cdev->online) {
ccw_device_update_sense_data(cdev);
break;
}
cdev->private->state = DEV_STATE_OFFLINE;
cdev->private->flags.recog_done = 1;
if (ccw_device_test_sense_data(cdev)) {
cdev->private->flags.donotify = 1;
ccw_device_online(cdev);
wake_up(&cdev->private->wait_q);
} else {
ccw_device_update_sense_data(cdev);
ccw_device_sched_todo(cdev, CDEV_TODO_REBIND);
}
return;
case DEV_STATE_BOXED:
if (cdev->id.cu_type != 0) { /* device was recognized before */
cdev->private->flags.recog_done = 1;
cdev->private->state = DEV_STATE_BOXED;
wake_up(&cdev->private->wait_q);
return;
}
break;
}
cdev->private->state = state;
io_subchannel_recog_done(cdev);
wake_up(&cdev->private->wait_q);
}
/*
* Function called from device_id.c after sense id has completed.
*/
void
ccw_device_sense_id_done(struct ccw_device *cdev, int err)
{
switch (err) {
case 0:
ccw_device_recog_done(cdev, DEV_STATE_OFFLINE);
break;
case -ETIME: /* Sense id stopped by timeout. */
ccw_device_recog_done(cdev, DEV_STATE_BOXED);
break;
default:
ccw_device_recog_done(cdev, DEV_STATE_NOT_OPER);
break;
}
}
/**
* ccw_device_notify() - inform the device's driver about an event
* @cdev: device for which an event occurred
* @event: event that occurred
*
* Returns:
* -%EINVAL if the device is offline or has no driver.
* -%EOPNOTSUPP if the device's driver has no notifier registered.
* %NOTIFY_OK if the driver wants to keep the device.
* %NOTIFY_BAD if the driver doesn't want to keep the device.
*/
int ccw_device_notify(struct ccw_device *cdev, int event)
{
int ret = -EINVAL;
if (!cdev->drv)
goto out;
if (!cdev->online)
goto out;
CIO_MSG_EVENT(2, "notify called for 0.%x.%04x, event=%d\n",
cdev->private->dev_id.ssid, cdev->private->dev_id.devno,
event);
if (!cdev->drv->notify) {
ret = -EOPNOTSUPP;
goto out;
}
if (cdev->drv->notify(cdev, event))
ret = NOTIFY_OK;
else
ret = NOTIFY_BAD;
out:
return ret;
}
static void ccw_device_oper_notify(struct ccw_device *cdev)
{
struct subchannel *sch = to_subchannel(cdev->dev.parent);
if (ccw_device_notify(cdev, CIO_OPER) == NOTIFY_OK) {
/* Reenable channel measurements, if needed. */
ccw_device_sched_todo(cdev, CDEV_TODO_ENABLE_CMF);
/* Save indication for new paths. */
cdev->private->path_new_mask = sch->vpm;
return;
}
/* Driver doesn't want device back. */
ccw_device_set_notoper(cdev);
ccw_device_sched_todo(cdev, CDEV_TODO_REBIND);
}
/*
* Finished with online/offline processing.
*/
static void
ccw_device_done(struct ccw_device *cdev, int state)
{
struct subchannel *sch;
sch = to_subchannel(cdev->dev.parent);
ccw_device_set_timeout(cdev, 0);
if (state != DEV_STATE_ONLINE)
cio_disable_subchannel(sch);
/* Reset device status. */
memset(&cdev->private->irb, 0, sizeof(struct irb));
cdev->private->state = state;
switch (state) {
case DEV_STATE_BOXED:
CIO_MSG_EVENT(0, "Boxed device %04x on subchannel %04x\n",
cdev->private->dev_id.devno, sch->schid.sch_no);
if (cdev->online &&
ccw_device_notify(cdev, CIO_BOXED) != NOTIFY_OK)
ccw_device_sched_todo(cdev, CDEV_TODO_UNREG);
cdev->private->flags.donotify = 0;
break;
case DEV_STATE_NOT_OPER:
CIO_MSG_EVENT(0, "Device %04x gone on subchannel %04x\n",
cdev->private->dev_id.devno, sch->schid.sch_no);
if (ccw_device_notify(cdev, CIO_GONE) != NOTIFY_OK)
ccw_device_sched_todo(cdev, CDEV_TODO_UNREG);
else
ccw_device_set_disconnected(cdev);
cdev->private->flags.donotify = 0;
break;
case DEV_STATE_DISCONNECTED:
CIO_MSG_EVENT(0, "Disconnected device %04x on subchannel "
"%04x\n", cdev->private->dev_id.devno,
sch->schid.sch_no);
if (ccw_device_notify(cdev, CIO_NO_PATH) != NOTIFY_OK) {
cdev->private->state = DEV_STATE_NOT_OPER;
ccw_device_sched_todo(cdev, CDEV_TODO_UNREG);
} else
ccw_device_set_disconnected(cdev);
cdev->private->flags.donotify = 0;
break;
default:
break;
}
if (cdev->private->flags.donotify) {
cdev->private->flags.donotify = 0;
ccw_device_oper_notify(cdev);
}
wake_up(&cdev->private->wait_q);
}
/*
* Start device recognition.
*/
void ccw_device_recognition(struct ccw_device *cdev)
{
struct subchannel *sch = to_subchannel(cdev->dev.parent);
/*
* We used to start here with a sense pgid to find out whether a device
* is locked by someone else. Unfortunately, the sense pgid command
* code has other meanings on devices predating the path grouping
* algorithm, so we start with sense id and box the device after an
* timeout (or if sense pgid during path verification detects the device
* is locked, as may happen on newer devices).
*/
cdev->private->flags.recog_done = 0;
cdev->private->state = DEV_STATE_SENSE_ID;
if (cio_enable_subchannel(sch, (u32) (addr_t) sch)) {
ccw_device_recog_done(cdev, DEV_STATE_NOT_OPER);
return;
}
ccw_device_sense_id_start(cdev);
}
/*
* Handle events for states that use the ccw request infrastructure.
*/
static void ccw_device_request_event(struct ccw_device *cdev, enum dev_event e)
{
switch (e) {
case DEV_EVENT_NOTOPER:
ccw_request_notoper(cdev);
break;
case DEV_EVENT_INTERRUPT:
ccw_request_handler(cdev);
break;
case DEV_EVENT_TIMEOUT:
ccw_request_timeout(cdev);
break;
default:
break;
}
}
static void ccw_device_report_path_events(struct ccw_device *cdev)
{
struct subchannel *sch = to_subchannel(cdev->dev.parent);
int path_event[8];
int chp, mask;
for (chp = 0, mask = 0x80; chp < 8; chp++, mask >>= 1) {
path_event[chp] = PE_NONE;
if (mask & cdev->private->path_gone_mask & ~(sch->vpm))
path_event[chp] |= PE_PATH_GONE;
if (mask & cdev->private->path_new_mask & sch->vpm)
path_event[chp] |= PE_PATH_AVAILABLE;
if (mask & cdev->private->pgid_reset_mask & sch->vpm)
path_event[chp] |= PE_PATHGROUP_ESTABLISHED;
}
if (cdev->online && cdev->drv->path_event)
cdev->drv->path_event(cdev, path_event);
}
static void ccw_device_reset_path_events(struct ccw_device *cdev)
{
cdev->private->path_gone_mask = 0;
cdev->private->path_new_mask = 0;
cdev->private->pgid_reset_mask = 0;
}
static void create_fake_irb(struct irb *irb, int type)
{
memset(irb, 0, sizeof(*irb));
if (type == FAKE_CMD_IRB) {
struct cmd_scsw *scsw = &irb->scsw.cmd;
scsw->cc = 1;
scsw->fctl = SCSW_FCTL_START_FUNC;
scsw->actl = SCSW_ACTL_START_PEND;
scsw->stctl = SCSW_STCTL_STATUS_PEND;
} else if (type == FAKE_TM_IRB) {
struct tm_scsw *scsw = &irb->scsw.tm;
scsw->x = 1;
scsw->cc = 1;
scsw->fctl = SCSW_FCTL_START_FUNC;
scsw->actl = SCSW_ACTL_START_PEND;
scsw->stctl = SCSW_STCTL_STATUS_PEND;
}
}
void ccw_device_verify_done(struct ccw_device *cdev, int err)
{
struct subchannel *sch;
sch = to_subchannel(cdev->dev.parent);
/* Update schib - pom may have changed. */
if (cio_update_schib(sch)) {
err = -ENODEV;
goto callback;
}
/* Update lpm with verified path mask. */
sch->lpm = sch->vpm;
/* Repeat path verification? */
if (cdev->private->flags.doverify) {
ccw_device_verify_start(cdev);
return;
}
callback:
switch (err) {
case 0:
ccw_device_done(cdev, DEV_STATE_ONLINE);
/* Deliver fake irb to device driver, if needed. */
if (cdev->private->flags.fake_irb) {
create_fake_irb(&cdev->private->irb,
cdev->private->flags.fake_irb);
cdev->private->flags.fake_irb = 0;
if (cdev->handler)
cdev->handler(cdev, cdev->private->intparm,
&cdev->private->irb);
memset(&cdev->private->irb, 0, sizeof(struct irb));
}
ccw_device_report_path_events(cdev);
break;
case -ETIME:
case -EUSERS:
/* Reset oper notify indication after verify error. */
cdev->private->flags.donotify = 0;
ccw_device_done(cdev, DEV_STATE_BOXED);
break;
case -EACCES:
/* Reset oper notify indication after verify error. */
cdev->private->flags.donotify = 0;
ccw_device_done(cdev, DEV_STATE_DISCONNECTED);
break;
default:
/* Reset oper notify indication after verify error. */
cdev->private->flags.donotify = 0;
ccw_device_done(cdev, DEV_STATE_NOT_OPER);
break;
}
ccw_device_reset_path_events(cdev);
}
/*
* Get device online.
*/
int
ccw_device_online(struct ccw_device *cdev)
{
struct subchannel *sch;
int ret;
if ((cdev->private->state != DEV_STATE_OFFLINE) &&
(cdev->private->state != DEV_STATE_BOXED))
return -EINVAL;
sch = to_subchannel(cdev->dev.parent);
ret = cio_enable_subchannel(sch, (u32)(addr_t)sch);
if (ret != 0) {
/* Couldn't enable the subchannel for i/o. Sick device. */
if (ret == -ENODEV)
dev_fsm_event(cdev, DEV_EVENT_NOTOPER);
return ret;
}
/* Start initial path verification. */
cdev->private->state = DEV_STATE_VERIFY;
ccw_device_verify_start(cdev);
return 0;
}
void
ccw_device_disband_done(struct ccw_device *cdev, int err)
{
switch (err) {
case 0:
ccw_device_done(cdev, DEV_STATE_OFFLINE);
break;
case -ETIME:
ccw_device_done(cdev, DEV_STATE_BOXED);
break;
default:
cdev->private->flags.donotify = 0;
ccw_device_done(cdev, DEV_STATE_NOT_OPER);
break;
}
}
/*
* Shutdown device.
*/
int
ccw_device_offline(struct ccw_device *cdev)
{
struct subchannel *sch;
/* Allow ccw_device_offline while disconnected. */
if (cdev->private->state == DEV_STATE_DISCONNECTED ||
cdev->private->state == DEV_STATE_NOT_OPER) {
cdev->private->flags.donotify = 0;
ccw_device_done(cdev, DEV_STATE_NOT_OPER);
return 0;
}
if (cdev->private->state == DEV_STATE_BOXED) {
ccw_device_done(cdev, DEV_STATE_BOXED);
return 0;
}
if (ccw_device_is_orphan(cdev)) {
ccw_device_done(cdev, DEV_STATE_OFFLINE);
return 0;
}
sch = to_subchannel(cdev->dev.parent);
if (cio_update_schib(sch))
return -ENODEV;
if (scsw_actl(&sch->schib.scsw) != 0)
return -EBUSY;
if (cdev->private->state != DEV_STATE_ONLINE)
return -EINVAL;
/* Are we doing path grouping? */
if (!cdev->private->flags.pgroup) {
/* No, set state offline immediately. */
ccw_device_done(cdev, DEV_STATE_OFFLINE);
return 0;
}
/* Start Set Path Group commands. */
cdev->private->state = DEV_STATE_DISBAND_PGID;
ccw_device_disband_start(cdev);
return 0;
}
/*
* Handle not operational event in non-special state.
*/
static void ccw_device_generic_notoper(struct ccw_device *cdev,
enum dev_event dev_event)
{
if (ccw_device_notify(cdev, CIO_GONE) != NOTIFY_OK)
ccw_device_sched_todo(cdev, CDEV_TODO_UNREG);
else
ccw_device_set_disconnected(cdev);
}
/*
* Handle path verification event in offline state.
*/
static void ccw_device_offline_verify(struct ccw_device *cdev,
enum dev_event dev_event)
{
struct subchannel *sch = to_subchannel(cdev->dev.parent);
css_schedule_eval(sch->schid);
}
/*
* Handle path verification event.
*/
static void
ccw_device_online_verify(struct ccw_device *cdev, enum dev_event dev_event)
{
struct subchannel *sch;
if (cdev->private->state == DEV_STATE_W4SENSE) {
cdev->private->flags.doverify = 1;
return;
}
sch = to_subchannel(cdev->dev.parent);
/*
* Since we might not just be coming from an interrupt from the
* subchannel we have to update the schib.
*/
if (cio_update_schib(sch)) {
ccw_device_verify_done(cdev, -ENODEV);
return;
}
if (scsw_actl(&sch->schib.scsw) != 0 ||
(scsw_stctl(&sch->schib.scsw) & SCSW_STCTL_STATUS_PEND) ||
(scsw_stctl(&cdev->private->irb.scsw) & SCSW_STCTL_STATUS_PEND)) {
/*
* No final status yet or final status not yet delivered
* to the device driver. Can't do path verification now,
* delay until final status was delivered.
*/
cdev->private->flags.doverify = 1;
return;
}
/* Device is idle, we can do the path verification. */
cdev->private->state = DEV_STATE_VERIFY;
ccw_device_verify_start(cdev);
}
/*
* Handle path verification event in boxed state.
*/
static void ccw_device_boxed_verify(struct ccw_device *cdev,
enum dev_event dev_event)
{
struct subchannel *sch = to_subchannel(cdev->dev.parent);
if (cdev->online) {
if (cio_enable_subchannel(sch, (u32) (addr_t) sch))
ccw_device_done(cdev, DEV_STATE_NOT_OPER);
else
ccw_device_online_verify(cdev, dev_event);
} else
css_schedule_eval(sch->schid);
}
/*
* Got an interrupt for a normal io (state online).
*/
static void
ccw_device_irq(struct ccw_device *cdev, enum dev_event dev_event)
{
struct irb *irb;
int is_cmd;
irb = (struct irb *)&S390_lowcore.irb;
is_cmd = !scsw_is_tm(&irb->scsw);
/* Check for unsolicited interrupt. */
if (!scsw_is_solicited(&irb->scsw)) {
if (is_cmd && (irb->scsw.cmd.dstat & DEV_STAT_UNIT_CHECK) &&
!irb->esw.esw0.erw.cons) {
/* Unit check but no sense data. Need basic sense. */
if (ccw_device_do_sense(cdev, irb) != 0)
goto call_handler_unsol;
memcpy(&cdev->private->irb, irb, sizeof(struct irb));
cdev->private->state = DEV_STATE_W4SENSE;
cdev->private->intparm = 0;
return;
}
call_handler_unsol:
if (cdev->handler)
cdev->handler (cdev, 0, irb);
if (cdev->private->flags.doverify)
ccw_device_online_verify(cdev, 0);
return;
}
/* Accumulate status and find out if a basic sense is needed. */
ccw_device_accumulate_irb(cdev, irb);
if (is_cmd && cdev->private->flags.dosense) {
if (ccw_device_do_sense(cdev, irb) == 0) {
cdev->private->state = DEV_STATE_W4SENSE;
}
return;
}
/* Call the handler. */
if (ccw_device_call_handler(cdev) && cdev->private->flags.doverify)
/* Start delayed path verification. */
ccw_device_online_verify(cdev, 0);
}
/*
* Got an timeout in online state.
*/
static void
ccw_device_online_timeout(struct ccw_device *cdev, enum dev_event dev_event)
{
int ret;
ccw_device_set_timeout(cdev, 0);
cdev->private->iretry = 255;
ret = ccw_device_cancel_halt_clear(cdev);
if (ret == -EBUSY) {
ccw_device_set_timeout(cdev, 3*HZ);
cdev->private->state = DEV_STATE_TIMEOUT_KILL;
return;
}
if (ret)
dev_fsm_event(cdev, DEV_EVENT_NOTOPER);
else if (cdev->handler)
cdev->handler(cdev, cdev->private->intparm,
ERR_PTR(-ETIMEDOUT));
}
/*
* Got an interrupt for a basic sense.
*/
static void
ccw_device_w4sense(struct ccw_device *cdev, enum dev_event dev_event)
{
struct irb *irb;
irb = (struct irb *)&S390_lowcore.irb;
/* Check for unsolicited interrupt. */
if (scsw_stctl(&irb->scsw) ==
(SCSW_STCTL_STATUS_PEND | SCSW_STCTL_ALERT_STATUS)) {
if (scsw_cc(&irb->scsw) == 1)
/* Basic sense hasn't started. Try again. */
ccw_device_do_sense(cdev, irb);
else {
CIO_MSG_EVENT(0, "0.%x.%04x: unsolicited "
"interrupt during w4sense...\n",
cdev->private->dev_id.ssid,
cdev->private->dev_id.devno);
if (cdev->handler)
cdev->handler (cdev, 0, irb);
}
return;
}
/*
* Check if a halt or clear has been issued in the meanwhile. If yes,
* only deliver the halt/clear interrupt to the device driver as if it
* had killed the original request.
*/
if (scsw_fctl(&irb->scsw) &
(SCSW_FCTL_CLEAR_FUNC | SCSW_FCTL_HALT_FUNC)) {
cdev->private->flags.dosense = 0;
memset(&cdev->private->irb, 0, sizeof(struct irb));
ccw_device_accumulate_irb(cdev, irb);
goto call_handler;
}
/* Add basic sense info to irb. */
ccw_device_accumulate_basic_sense(cdev, irb);
if (cdev->private->flags.dosense) {
/* Another basic sense is needed. */
ccw_device_do_sense(cdev, irb);
return;
}
call_handler:
cdev->private->state = DEV_STATE_ONLINE;
/* In case sensing interfered with setting the device online */
wake_up(&cdev->private->wait_q);
/* Call the handler. */
if (ccw_device_call_handler(cdev) && cdev->private->flags.doverify)
/* Start delayed path verification. */
ccw_device_online_verify(cdev, 0);
}
static void
ccw_device_killing_irq(struct ccw_device *cdev, enum dev_event dev_event)
{
ccw_device_set_timeout(cdev, 0);
/* Start delayed path verification. */
ccw_device_online_verify(cdev, 0);
/* OK, i/o is dead now. Call interrupt handler. */
if (cdev->handler)
cdev->handler(cdev, cdev->private->intparm,
ERR_PTR(-EIO));
}
static void
ccw_device_killing_timeout(struct ccw_device *cdev, enum dev_event dev_event)
{
int ret;
ret = ccw_device_cancel_halt_clear(cdev);
if (ret == -EBUSY) {
ccw_device_set_timeout(cdev, 3*HZ);
return;
}
/* Start delayed path verification. */
ccw_device_online_verify(cdev, 0);
if (cdev->handler)
cdev->handler(cdev, cdev->private->intparm,
ERR_PTR(-EIO));
}
void ccw_device_kill_io(struct ccw_device *cdev)
{
int ret;
cdev->private->iretry = 255;
ret = ccw_device_cancel_halt_clear(cdev);
if (ret == -EBUSY) {
ccw_device_set_timeout(cdev, 3*HZ);
cdev->private->state = DEV_STATE_TIMEOUT_KILL;
return;
}
/* Start delayed path verification. */
ccw_device_online_verify(cdev, 0);
if (cdev->handler)
cdev->handler(cdev, cdev->private->intparm,
ERR_PTR(-EIO));
}
static void
ccw_device_delay_verify(struct ccw_device *cdev, enum dev_event dev_event)
{
/* Start verification after current task finished. */
cdev->private->flags.doverify = 1;
}
static void
ccw_device_start_id(struct ccw_device *cdev, enum dev_event dev_event)
{
struct subchannel *sch;
sch = to_subchannel(cdev->dev.parent);
if (cio_enable_subchannel(sch, (u32)(addr_t)sch) != 0)
/* Couldn't enable the subchannel for i/o. Sick device. */
return;
cdev->private->state = DEV_STATE_DISCONNECTED_SENSE_ID;
ccw_device_sense_id_start(cdev);
}
void ccw_device_trigger_reprobe(struct ccw_device *cdev)
{
struct subchannel *sch;
if (cdev->private->state != DEV_STATE_DISCONNECTED)
return;
sch = to_subchannel(cdev->dev.parent);
/* Update some values. */
if (cio_update_schib(sch))
return;
/*
* The pim, pam, pom values may not be accurate, but they are the best
* we have before performing device selection :/
*/
sch->lpm = sch->schib.pmcw.pam & sch->opm;
/*
* Use the initial configuration since we can't be shure that the old
* paths are valid.
*/
io_subchannel_init_config(sch);
if (cio_commit_config(sch))
return;
/* We should also udate ssd info, but this has to wait. */
/* Check if this is another device which appeared on the same sch. */
if (sch->schib.pmcw.dev != cdev->private->dev_id.devno)
css_schedule_eval(sch->schid);
else
ccw_device_start_id(cdev, 0);
}
static void ccw_device_disabled_irq(struct ccw_device *cdev,
enum dev_event dev_event)
{
struct subchannel *sch;
sch = to_subchannel(cdev->dev.parent);
/*
* An interrupt in a disabled state means a previous disable was not
* successful - should not happen, but we try to disable again.
*/
cio_disable_subchannel(sch);
}
static void
ccw_device_change_cmfstate(struct ccw_device *cdev, enum dev_event dev_event)
{
retry_set_schib(cdev);
cdev->private->state = DEV_STATE_ONLINE;
dev_fsm_event(cdev, dev_event);
}
static void ccw_device_update_cmfblock(struct ccw_device *cdev,
enum dev_event dev_event)
{
cmf_retry_copy_block(cdev);
cdev->private->state = DEV_STATE_ONLINE;
dev_fsm_event(cdev, dev_event);
}
static void
ccw_device_quiesce_done(struct ccw_device *cdev, enum dev_event dev_event)
{
ccw_device_set_timeout(cdev, 0);
cdev->private->state = DEV_STATE_NOT_OPER;
wake_up(&cdev->private->wait_q);
}
static void
ccw_device_quiesce_timeout(struct ccw_device *cdev, enum dev_event dev_event)
{
int ret;
ret = ccw_device_cancel_halt_clear(cdev);
if (ret == -EBUSY) {
ccw_device_set_timeout(cdev, HZ/10);
} else {
cdev->private->state = DEV_STATE_NOT_OPER;
wake_up(&cdev->private->wait_q);
}
}
/*
* No operation action. This is used e.g. to ignore a timeout event in
* state offline.
*/
static void
ccw_device_nop(struct ccw_device *cdev, enum dev_event dev_event)
{
}
/*
* device statemachine
*/
fsm_func_t *dev_jumptable[NR_DEV_STATES][NR_DEV_EVENTS] = {
[DEV_STATE_NOT_OPER] = {
[DEV_EVENT_NOTOPER] = ccw_device_nop,
[DEV_EVENT_INTERRUPT] = ccw_device_disabled_irq,
[DEV_EVENT_TIMEOUT] = ccw_device_nop,
[DEV_EVENT_VERIFY] = ccw_device_nop,
},
[DEV_STATE_SENSE_PGID] = {
[DEV_EVENT_NOTOPER] = ccw_device_request_event,
[DEV_EVENT_INTERRUPT] = ccw_device_request_event,
[DEV_EVENT_TIMEOUT] = ccw_device_request_event,
[DEV_EVENT_VERIFY] = ccw_device_nop,
},
[DEV_STATE_SENSE_ID] = {
[DEV_EVENT_NOTOPER] = ccw_device_request_event,
[DEV_EVENT_INTERRUPT] = ccw_device_request_event,
[DEV_EVENT_TIMEOUT] = ccw_device_request_event,
[DEV_EVENT_VERIFY] = ccw_device_nop,
},
[DEV_STATE_OFFLINE] = {
[DEV_EVENT_NOTOPER] = ccw_device_generic_notoper,
[DEV_EVENT_INTERRUPT] = ccw_device_disabled_irq,
[DEV_EVENT_TIMEOUT] = ccw_device_nop,
[DEV_EVENT_VERIFY] = ccw_device_offline_verify,
},
[DEV_STATE_VERIFY] = {
[DEV_EVENT_NOTOPER] = ccw_device_request_event,
[DEV_EVENT_INTERRUPT] = ccw_device_request_event,
[DEV_EVENT_TIMEOUT] = ccw_device_request_event,
[DEV_EVENT_VERIFY] = ccw_device_delay_verify,
},
[DEV_STATE_ONLINE] = {
[DEV_EVENT_NOTOPER] = ccw_device_generic_notoper,
[DEV_EVENT_INTERRUPT] = ccw_device_irq,
[DEV_EVENT_TIMEOUT] = ccw_device_online_timeout,
[DEV_EVENT_VERIFY] = ccw_device_online_verify,
},
[DEV_STATE_W4SENSE] = {
[DEV_EVENT_NOTOPER] = ccw_device_generic_notoper,
[DEV_EVENT_INTERRUPT] = ccw_device_w4sense,
[DEV_EVENT_TIMEOUT] = ccw_device_nop,
[DEV_EVENT_VERIFY] = ccw_device_online_verify,
},
[DEV_STATE_DISBAND_PGID] = {
[DEV_EVENT_NOTOPER] = ccw_device_request_event,
[DEV_EVENT_INTERRUPT] = ccw_device_request_event,
[DEV_EVENT_TIMEOUT] = ccw_device_request_event,
[DEV_EVENT_VERIFY] = ccw_device_nop,
},
[DEV_STATE_BOXED] = {
[DEV_EVENT_NOTOPER] = ccw_device_generic_notoper,
[DEV_EVENT_INTERRUPT] = ccw_device_nop,
[DEV_EVENT_TIMEOUT] = ccw_device_nop,
[DEV_EVENT_VERIFY] = ccw_device_boxed_verify,
},
/* states to wait for i/o completion before doing something */
[DEV_STATE_TIMEOUT_KILL] = {
[DEV_EVENT_NOTOPER] = ccw_device_generic_notoper,
[DEV_EVENT_INTERRUPT] = ccw_device_killing_irq,
[DEV_EVENT_TIMEOUT] = ccw_device_killing_timeout,
[DEV_EVENT_VERIFY] = ccw_device_nop, //FIXME
},
[DEV_STATE_QUIESCE] = {
[DEV_EVENT_NOTOPER] = ccw_device_quiesce_done,
[DEV_EVENT_INTERRUPT] = ccw_device_quiesce_done,
[DEV_EVENT_TIMEOUT] = ccw_device_quiesce_timeout,
[DEV_EVENT_VERIFY] = ccw_device_nop,
},
/* special states for devices gone not operational */
[DEV_STATE_DISCONNECTED] = {
[DEV_EVENT_NOTOPER] = ccw_device_nop,
[DEV_EVENT_INTERRUPT] = ccw_device_start_id,
[DEV_EVENT_TIMEOUT] = ccw_device_nop,
[DEV_EVENT_VERIFY] = ccw_device_start_id,
},
[DEV_STATE_DISCONNECTED_SENSE_ID] = {
[DEV_EVENT_NOTOPER] = ccw_device_request_event,
[DEV_EVENT_INTERRUPT] = ccw_device_request_event,
[DEV_EVENT_TIMEOUT] = ccw_device_request_event,
[DEV_EVENT_VERIFY] = ccw_device_nop,
},
[DEV_STATE_CMFCHANGE] = {
[DEV_EVENT_NOTOPER] = ccw_device_change_cmfstate,
[DEV_EVENT_INTERRUPT] = ccw_device_change_cmfstate,
[DEV_EVENT_TIMEOUT] = ccw_device_change_cmfstate,
[DEV_EVENT_VERIFY] = ccw_device_change_cmfstate,
},
[DEV_STATE_CMFUPDATE] = {
[DEV_EVENT_NOTOPER] = ccw_device_update_cmfblock,
[DEV_EVENT_INTERRUPT] = ccw_device_update_cmfblock,
[DEV_EVENT_TIMEOUT] = ccw_device_update_cmfblock,
[DEV_EVENT_VERIFY] = ccw_device_update_cmfblock,
},
[DEV_STATE_STEAL_LOCK] = {
[DEV_EVENT_NOTOPER] = ccw_device_request_event,
[DEV_EVENT_INTERRUPT] = ccw_device_request_event,
[DEV_EVENT_TIMEOUT] = ccw_device_request_event,
[DEV_EVENT_VERIFY] = ccw_device_nop,
},
};
EXPORT_SYMBOL_GPL(ccw_device_set_timeout);
| gpl-2.0 |
sch2307/android_kernel_samsung_aries-kor | sound/soc/davinci/davinci-i2s.c | 2929 | 23741 | /*
* ALSA SoC I2S (McBSP) Audio Layer for TI DAVINCI processor
*
* Author: Vladimir Barinov, <vbarinov@embeddedalley.com>
* Copyright: (C) 2007 MontaVista Software, Inc., <source@mvista.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/init.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/io.h>
#include <linux/clk.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/initval.h>
#include <sound/soc.h>
#include <mach/asp.h>
#include "davinci-pcm.h"
#include "davinci-i2s.h"
/*
* NOTE: terminology here is confusing.
*
* - This driver supports the "Audio Serial Port" (ASP),
* found on dm6446, dm355, and other DaVinci chips.
*
* - But it labels it a "Multi-channel Buffered Serial Port"
* (McBSP) as on older chips like the dm642 ... which was
* backward-compatible, possibly explaining that confusion.
*
* - OMAP chips have a controller called McBSP, which is
* incompatible with the DaVinci flavor of McBSP.
*
* - Newer DaVinci chips have a controller called McASP,
* incompatible with ASP and with either McBSP.
*
* In short: this uses ASP to implement I2S, not McBSP.
* And it won't be the only DaVinci implemention of I2S.
*/
#define DAVINCI_MCBSP_DRR_REG 0x00
#define DAVINCI_MCBSP_DXR_REG 0x04
#define DAVINCI_MCBSP_SPCR_REG 0x08
#define DAVINCI_MCBSP_RCR_REG 0x0c
#define DAVINCI_MCBSP_XCR_REG 0x10
#define DAVINCI_MCBSP_SRGR_REG 0x14
#define DAVINCI_MCBSP_PCR_REG 0x24
#define DAVINCI_MCBSP_SPCR_RRST (1 << 0)
#define DAVINCI_MCBSP_SPCR_RINTM(v) ((v) << 4)
#define DAVINCI_MCBSP_SPCR_XRST (1 << 16)
#define DAVINCI_MCBSP_SPCR_XINTM(v) ((v) << 20)
#define DAVINCI_MCBSP_SPCR_GRST (1 << 22)
#define DAVINCI_MCBSP_SPCR_FRST (1 << 23)
#define DAVINCI_MCBSP_SPCR_FREE (1 << 25)
#define DAVINCI_MCBSP_RCR_RWDLEN1(v) ((v) << 5)
#define DAVINCI_MCBSP_RCR_RFRLEN1(v) ((v) << 8)
#define DAVINCI_MCBSP_RCR_RDATDLY(v) ((v) << 16)
#define DAVINCI_MCBSP_RCR_RFIG (1 << 18)
#define DAVINCI_MCBSP_RCR_RWDLEN2(v) ((v) << 21)
#define DAVINCI_MCBSP_RCR_RFRLEN2(v) ((v) << 24)
#define DAVINCI_MCBSP_RCR_RPHASE BIT(31)
#define DAVINCI_MCBSP_XCR_XWDLEN1(v) ((v) << 5)
#define DAVINCI_MCBSP_XCR_XFRLEN1(v) ((v) << 8)
#define DAVINCI_MCBSP_XCR_XDATDLY(v) ((v) << 16)
#define DAVINCI_MCBSP_XCR_XFIG (1 << 18)
#define DAVINCI_MCBSP_XCR_XWDLEN2(v) ((v) << 21)
#define DAVINCI_MCBSP_XCR_XFRLEN2(v) ((v) << 24)
#define DAVINCI_MCBSP_XCR_XPHASE BIT(31)
#define DAVINCI_MCBSP_SRGR_FWID(v) ((v) << 8)
#define DAVINCI_MCBSP_SRGR_FPER(v) ((v) << 16)
#define DAVINCI_MCBSP_SRGR_FSGM (1 << 28)
#define DAVINCI_MCBSP_SRGR_CLKSM BIT(29)
#define DAVINCI_MCBSP_PCR_CLKRP (1 << 0)
#define DAVINCI_MCBSP_PCR_CLKXP (1 << 1)
#define DAVINCI_MCBSP_PCR_FSRP (1 << 2)
#define DAVINCI_MCBSP_PCR_FSXP (1 << 3)
#define DAVINCI_MCBSP_PCR_SCLKME (1 << 7)
#define DAVINCI_MCBSP_PCR_CLKRM (1 << 8)
#define DAVINCI_MCBSP_PCR_CLKXM (1 << 9)
#define DAVINCI_MCBSP_PCR_FSRM (1 << 10)
#define DAVINCI_MCBSP_PCR_FSXM (1 << 11)
enum {
DAVINCI_MCBSP_WORD_8 = 0,
DAVINCI_MCBSP_WORD_12,
DAVINCI_MCBSP_WORD_16,
DAVINCI_MCBSP_WORD_20,
DAVINCI_MCBSP_WORD_24,
DAVINCI_MCBSP_WORD_32,
};
static const unsigned char data_type[SNDRV_PCM_FORMAT_S32_LE + 1] = {
[SNDRV_PCM_FORMAT_S8] = 1,
[SNDRV_PCM_FORMAT_S16_LE] = 2,
[SNDRV_PCM_FORMAT_S32_LE] = 4,
};
static const unsigned char asp_word_length[SNDRV_PCM_FORMAT_S32_LE + 1] = {
[SNDRV_PCM_FORMAT_S8] = DAVINCI_MCBSP_WORD_8,
[SNDRV_PCM_FORMAT_S16_LE] = DAVINCI_MCBSP_WORD_16,
[SNDRV_PCM_FORMAT_S32_LE] = DAVINCI_MCBSP_WORD_32,
};
static const unsigned char double_fmt[SNDRV_PCM_FORMAT_S32_LE + 1] = {
[SNDRV_PCM_FORMAT_S8] = SNDRV_PCM_FORMAT_S16_LE,
[SNDRV_PCM_FORMAT_S16_LE] = SNDRV_PCM_FORMAT_S32_LE,
};
struct davinci_mcbsp_dev {
struct device *dev;
struct davinci_pcm_dma_params dma_params[2];
void __iomem *base;
#define MOD_DSP_A 0
#define MOD_DSP_B 1
int mode;
u32 pcr;
struct clk *clk;
/*
* Combining both channels into 1 element will at least double the
* amount of time between servicing the dma channel, increase
* effiency, and reduce the chance of overrun/underrun. But,
* it will result in the left & right channels being swapped.
*
* If relabeling the left and right channels is not possible,
* you may want to let the codec know to swap them back.
*
* It may allow x10 the amount of time to service dma requests,
* if the codec is master and is using an unnecessarily fast bit clock
* (ie. tlvaic23b), independent of the sample rate. So, having an
* entire frame at once means it can be serviced at the sample rate
* instead of the bit clock rate.
*
* In the now unlikely case that an underrun still
* occurs, both the left and right samples will be repeated
* so that no pops are heard, and the left and right channels
* won't end up being swapped because of the underrun.
*/
unsigned enable_channel_combine:1;
unsigned int fmt;
int clk_div;
int clk_input_pin;
bool i2s_accurate_sck;
};
static inline void davinci_mcbsp_write_reg(struct davinci_mcbsp_dev *dev,
int reg, u32 val)
{
__raw_writel(val, dev->base + reg);
}
static inline u32 davinci_mcbsp_read_reg(struct davinci_mcbsp_dev *dev, int reg)
{
return __raw_readl(dev->base + reg);
}
static void toggle_clock(struct davinci_mcbsp_dev *dev, int playback)
{
u32 m = playback ? DAVINCI_MCBSP_PCR_CLKXP : DAVINCI_MCBSP_PCR_CLKRP;
/* The clock needs to toggle to complete reset.
* So, fake it by toggling the clk polarity.
*/
davinci_mcbsp_write_reg(dev, DAVINCI_MCBSP_PCR_REG, dev->pcr ^ m);
davinci_mcbsp_write_reg(dev, DAVINCI_MCBSP_PCR_REG, dev->pcr);
}
static void davinci_mcbsp_start(struct davinci_mcbsp_dev *dev,
struct snd_pcm_substream *substream)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_platform *platform = rtd->platform;
int playback = (substream->stream == SNDRV_PCM_STREAM_PLAYBACK);
u32 spcr;
u32 mask = playback ? DAVINCI_MCBSP_SPCR_XRST : DAVINCI_MCBSP_SPCR_RRST;
spcr = davinci_mcbsp_read_reg(dev, DAVINCI_MCBSP_SPCR_REG);
if (spcr & mask) {
/* start off disabled */
davinci_mcbsp_write_reg(dev, DAVINCI_MCBSP_SPCR_REG,
spcr & ~mask);
toggle_clock(dev, playback);
}
if (dev->pcr & (DAVINCI_MCBSP_PCR_FSXM | DAVINCI_MCBSP_PCR_FSRM |
DAVINCI_MCBSP_PCR_CLKXM | DAVINCI_MCBSP_PCR_CLKRM)) {
/* Start the sample generator */
spcr |= DAVINCI_MCBSP_SPCR_GRST;
davinci_mcbsp_write_reg(dev, DAVINCI_MCBSP_SPCR_REG, spcr);
}
if (playback) {
/* Stop the DMA to avoid data loss */
/* while the transmitter is out of reset to handle XSYNCERR */
if (platform->driver->ops->trigger) {
int ret = platform->driver->ops->trigger(substream,
SNDRV_PCM_TRIGGER_STOP);
if (ret < 0)
printk(KERN_DEBUG "Playback DMA stop failed\n");
}
/* Enable the transmitter */
spcr = davinci_mcbsp_read_reg(dev, DAVINCI_MCBSP_SPCR_REG);
spcr |= DAVINCI_MCBSP_SPCR_XRST;
davinci_mcbsp_write_reg(dev, DAVINCI_MCBSP_SPCR_REG, spcr);
/* wait for any unexpected frame sync error to occur */
udelay(100);
/* Disable the transmitter to clear any outstanding XSYNCERR */
spcr = davinci_mcbsp_read_reg(dev, DAVINCI_MCBSP_SPCR_REG);
spcr &= ~DAVINCI_MCBSP_SPCR_XRST;
davinci_mcbsp_write_reg(dev, DAVINCI_MCBSP_SPCR_REG, spcr);
toggle_clock(dev, playback);
/* Restart the DMA */
if (platform->driver->ops->trigger) {
int ret = platform->driver->ops->trigger(substream,
SNDRV_PCM_TRIGGER_START);
if (ret < 0)
printk(KERN_DEBUG "Playback DMA start failed\n");
}
}
/* Enable transmitter or receiver */
spcr = davinci_mcbsp_read_reg(dev, DAVINCI_MCBSP_SPCR_REG);
spcr |= mask;
if (dev->pcr & (DAVINCI_MCBSP_PCR_FSXM | DAVINCI_MCBSP_PCR_FSRM)) {
/* Start frame sync */
spcr |= DAVINCI_MCBSP_SPCR_FRST;
}
davinci_mcbsp_write_reg(dev, DAVINCI_MCBSP_SPCR_REG, spcr);
}
static void davinci_mcbsp_stop(struct davinci_mcbsp_dev *dev, int playback)
{
u32 spcr;
/* Reset transmitter/receiver and sample rate/frame sync generators */
spcr = davinci_mcbsp_read_reg(dev, DAVINCI_MCBSP_SPCR_REG);
spcr &= ~(DAVINCI_MCBSP_SPCR_GRST | DAVINCI_MCBSP_SPCR_FRST);
spcr &= playback ? ~DAVINCI_MCBSP_SPCR_XRST : ~DAVINCI_MCBSP_SPCR_RRST;
davinci_mcbsp_write_reg(dev, DAVINCI_MCBSP_SPCR_REG, spcr);
toggle_clock(dev, playback);
}
#define DEFAULT_BITPERSAMPLE 16
static int davinci_i2s_set_dai_fmt(struct snd_soc_dai *cpu_dai,
unsigned int fmt)
{
struct davinci_mcbsp_dev *dev = snd_soc_dai_get_drvdata(cpu_dai);
unsigned int pcr;
unsigned int srgr;
/* Attention srgr is updated by hw_params! */
srgr = DAVINCI_MCBSP_SRGR_FSGM |
DAVINCI_MCBSP_SRGR_FPER(DEFAULT_BITPERSAMPLE * 2 - 1) |
DAVINCI_MCBSP_SRGR_FWID(DEFAULT_BITPERSAMPLE - 1);
dev->fmt = fmt;
/* set master/slave audio interface */
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBS_CFS:
/* cpu is master */
pcr = DAVINCI_MCBSP_PCR_FSXM |
DAVINCI_MCBSP_PCR_FSRM |
DAVINCI_MCBSP_PCR_CLKXM |
DAVINCI_MCBSP_PCR_CLKRM;
break;
case SND_SOC_DAIFMT_CBM_CFS:
pcr = DAVINCI_MCBSP_PCR_FSRM | DAVINCI_MCBSP_PCR_FSXM;
/*
* Selection of the clock input pin that is the
* input for the Sample Rate Generator.
* McBSP FSR and FSX are driven by the Sample Rate
* Generator.
*/
switch (dev->clk_input_pin) {
case MCBSP_CLKS:
pcr |= DAVINCI_MCBSP_PCR_CLKXM |
DAVINCI_MCBSP_PCR_CLKRM;
break;
case MCBSP_CLKR:
pcr |= DAVINCI_MCBSP_PCR_SCLKME;
break;
default:
dev_err(dev->dev, "bad clk_input_pin\n");
return -EINVAL;
}
break;
case SND_SOC_DAIFMT_CBM_CFM:
/* codec is master */
pcr = 0;
break;
default:
printk(KERN_ERR "%s:bad master\n", __func__);
return -EINVAL;
}
/* interface format */
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_I2S:
/* Davinci doesn't support TRUE I2S, but some codecs will have
* the left and right channels contiguous. This allows
* dsp_a mode to be used with an inverted normal frame clk.
* If your codec is master and does not have contiguous
* channels, then you will have sound on only one channel.
* Try using a different mode, or codec as slave.
*
* The TLV320AIC33 is an example of a codec where this works.
* It has a variable bit clock frequency allowing it to have
* valid data on every bit clock.
*
* The TLV320AIC23 is an example of a codec where this does not
* work. It has a fixed bit clock frequency with progressively
* more empty bit clock slots between channels as the sample
* rate is lowered.
*/
fmt ^= SND_SOC_DAIFMT_NB_IF;
case SND_SOC_DAIFMT_DSP_A:
dev->mode = MOD_DSP_A;
break;
case SND_SOC_DAIFMT_DSP_B:
dev->mode = MOD_DSP_B;
break;
default:
printk(KERN_ERR "%s:bad format\n", __func__);
return -EINVAL;
}
switch (fmt & SND_SOC_DAIFMT_INV_MASK) {
case SND_SOC_DAIFMT_NB_NF:
/* CLKRP Receive clock polarity,
* 1 - sampled on rising edge of CLKR
* valid on rising edge
* CLKXP Transmit clock polarity,
* 1 - clocked on falling edge of CLKX
* valid on rising edge
* FSRP Receive frame sync pol, 0 - active high
* FSXP Transmit frame sync pol, 0 - active high
*/
pcr |= (DAVINCI_MCBSP_PCR_CLKXP | DAVINCI_MCBSP_PCR_CLKRP);
break;
case SND_SOC_DAIFMT_IB_IF:
/* CLKRP Receive clock polarity,
* 0 - sampled on falling edge of CLKR
* valid on falling edge
* CLKXP Transmit clock polarity,
* 0 - clocked on rising edge of CLKX
* valid on falling edge
* FSRP Receive frame sync pol, 1 - active low
* FSXP Transmit frame sync pol, 1 - active low
*/
pcr |= (DAVINCI_MCBSP_PCR_FSXP | DAVINCI_MCBSP_PCR_FSRP);
break;
case SND_SOC_DAIFMT_NB_IF:
/* CLKRP Receive clock polarity,
* 1 - sampled on rising edge of CLKR
* valid on rising edge
* CLKXP Transmit clock polarity,
* 1 - clocked on falling edge of CLKX
* valid on rising edge
* FSRP Receive frame sync pol, 1 - active low
* FSXP Transmit frame sync pol, 1 - active low
*/
pcr |= (DAVINCI_MCBSP_PCR_CLKXP | DAVINCI_MCBSP_PCR_CLKRP |
DAVINCI_MCBSP_PCR_FSXP | DAVINCI_MCBSP_PCR_FSRP);
break;
case SND_SOC_DAIFMT_IB_NF:
/* CLKRP Receive clock polarity,
* 0 - sampled on falling edge of CLKR
* valid on falling edge
* CLKXP Transmit clock polarity,
* 0 - clocked on rising edge of CLKX
* valid on falling edge
* FSRP Receive frame sync pol, 0 - active high
* FSXP Transmit frame sync pol, 0 - active high
*/
break;
default:
return -EINVAL;
}
davinci_mcbsp_write_reg(dev, DAVINCI_MCBSP_SRGR_REG, srgr);
dev->pcr = pcr;
davinci_mcbsp_write_reg(dev, DAVINCI_MCBSP_PCR_REG, pcr);
return 0;
}
static int davinci_i2s_dai_set_clkdiv(struct snd_soc_dai *cpu_dai,
int div_id, int div)
{
struct davinci_mcbsp_dev *dev = snd_soc_dai_get_drvdata(cpu_dai);
if (div_id != DAVINCI_MCBSP_CLKGDV)
return -ENODEV;
dev->clk_div = div;
return 0;
}
static int davinci_i2s_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct davinci_mcbsp_dev *dev = snd_soc_dai_get_drvdata(dai);
struct davinci_pcm_dma_params *dma_params =
&dev->dma_params[substream->stream];
struct snd_interval *i = NULL;
int mcbsp_word_length, master;
unsigned int rcr, xcr, srgr, clk_div, freq, framesize;
u32 spcr;
snd_pcm_format_t fmt;
unsigned element_cnt = 1;
/* general line settings */
spcr = davinci_mcbsp_read_reg(dev, DAVINCI_MCBSP_SPCR_REG);
if (substream->stream == SNDRV_PCM_STREAM_CAPTURE) {
spcr |= DAVINCI_MCBSP_SPCR_RINTM(3) | DAVINCI_MCBSP_SPCR_FREE;
davinci_mcbsp_write_reg(dev, DAVINCI_MCBSP_SPCR_REG, spcr);
} else {
spcr |= DAVINCI_MCBSP_SPCR_XINTM(3) | DAVINCI_MCBSP_SPCR_FREE;
davinci_mcbsp_write_reg(dev, DAVINCI_MCBSP_SPCR_REG, spcr);
}
master = dev->fmt & SND_SOC_DAIFMT_MASTER_MASK;
fmt = params_format(params);
mcbsp_word_length = asp_word_length[fmt];
switch (master) {
case SND_SOC_DAIFMT_CBS_CFS:
freq = clk_get_rate(dev->clk);
srgr = DAVINCI_MCBSP_SRGR_FSGM |
DAVINCI_MCBSP_SRGR_CLKSM;
srgr |= DAVINCI_MCBSP_SRGR_FWID(mcbsp_word_length *
8 - 1);
if (dev->i2s_accurate_sck) {
clk_div = 256;
do {
framesize = (freq / (--clk_div)) /
params->rate_num *
params->rate_den;
} while (((framesize < 33) || (framesize > 4095)) &&
(clk_div));
clk_div--;
srgr |= DAVINCI_MCBSP_SRGR_FPER(framesize - 1);
} else {
/* symmetric waveforms */
clk_div = freq / (mcbsp_word_length * 16) /
params->rate_num * params->rate_den;
srgr |= DAVINCI_MCBSP_SRGR_FPER(mcbsp_word_length *
16 - 1);
}
clk_div &= 0xFF;
srgr |= clk_div;
break;
case SND_SOC_DAIFMT_CBM_CFS:
srgr = DAVINCI_MCBSP_SRGR_FSGM;
clk_div = dev->clk_div - 1;
srgr |= DAVINCI_MCBSP_SRGR_FWID(mcbsp_word_length * 8 - 1);
srgr |= DAVINCI_MCBSP_SRGR_FPER(mcbsp_word_length * 16 - 1);
clk_div &= 0xFF;
srgr |= clk_div;
break;
case SND_SOC_DAIFMT_CBM_CFM:
/* Clock and frame sync given from external sources */
i = hw_param_interval(params, SNDRV_PCM_HW_PARAM_SAMPLE_BITS);
srgr = DAVINCI_MCBSP_SRGR_FSGM;
srgr |= DAVINCI_MCBSP_SRGR_FWID(snd_interval_value(i) - 1);
pr_debug("%s - %d FWID set: re-read srgr = %X\n",
__func__, __LINE__, snd_interval_value(i) - 1);
i = hw_param_interval(params, SNDRV_PCM_HW_PARAM_FRAME_BITS);
srgr |= DAVINCI_MCBSP_SRGR_FPER(snd_interval_value(i) - 1);
break;
default:
return -EINVAL;
}
davinci_mcbsp_write_reg(dev, DAVINCI_MCBSP_SRGR_REG, srgr);
rcr = DAVINCI_MCBSP_RCR_RFIG;
xcr = DAVINCI_MCBSP_XCR_XFIG;
if (dev->mode == MOD_DSP_B) {
rcr |= DAVINCI_MCBSP_RCR_RDATDLY(0);
xcr |= DAVINCI_MCBSP_XCR_XDATDLY(0);
} else {
rcr |= DAVINCI_MCBSP_RCR_RDATDLY(1);
xcr |= DAVINCI_MCBSP_XCR_XDATDLY(1);
}
/* Determine xfer data type */
fmt = params_format(params);
if ((fmt > SNDRV_PCM_FORMAT_S32_LE) || !data_type[fmt]) {
printk(KERN_WARNING "davinci-i2s: unsupported PCM format\n");
return -EINVAL;
}
if (params_channels(params) == 2) {
element_cnt = 2;
if (double_fmt[fmt] && dev->enable_channel_combine) {
element_cnt = 1;
fmt = double_fmt[fmt];
}
switch (master) {
case SND_SOC_DAIFMT_CBS_CFS:
case SND_SOC_DAIFMT_CBS_CFM:
rcr |= DAVINCI_MCBSP_RCR_RFRLEN2(0);
xcr |= DAVINCI_MCBSP_XCR_XFRLEN2(0);
rcr |= DAVINCI_MCBSP_RCR_RPHASE;
xcr |= DAVINCI_MCBSP_XCR_XPHASE;
break;
case SND_SOC_DAIFMT_CBM_CFM:
case SND_SOC_DAIFMT_CBM_CFS:
rcr |= DAVINCI_MCBSP_RCR_RFRLEN2(element_cnt - 1);
xcr |= DAVINCI_MCBSP_XCR_XFRLEN2(element_cnt - 1);
break;
default:
return -EINVAL;
}
}
dma_params->acnt = dma_params->data_type = data_type[fmt];
dma_params->fifo_level = 0;
mcbsp_word_length = asp_word_length[fmt];
switch (master) {
case SND_SOC_DAIFMT_CBS_CFS:
case SND_SOC_DAIFMT_CBS_CFM:
rcr |= DAVINCI_MCBSP_RCR_RFRLEN1(0);
xcr |= DAVINCI_MCBSP_XCR_XFRLEN1(0);
break;
case SND_SOC_DAIFMT_CBM_CFM:
case SND_SOC_DAIFMT_CBM_CFS:
rcr |= DAVINCI_MCBSP_RCR_RFRLEN1(element_cnt - 1);
xcr |= DAVINCI_MCBSP_XCR_XFRLEN1(element_cnt - 1);
break;
default:
return -EINVAL;
}
rcr |= DAVINCI_MCBSP_RCR_RWDLEN1(mcbsp_word_length) |
DAVINCI_MCBSP_RCR_RWDLEN2(mcbsp_word_length);
xcr |= DAVINCI_MCBSP_XCR_XWDLEN1(mcbsp_word_length) |
DAVINCI_MCBSP_XCR_XWDLEN2(mcbsp_word_length);
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
davinci_mcbsp_write_reg(dev, DAVINCI_MCBSP_XCR_REG, xcr);
else
davinci_mcbsp_write_reg(dev, DAVINCI_MCBSP_RCR_REG, rcr);
pr_debug("%s - %d srgr=%X\n", __func__, __LINE__, srgr);
pr_debug("%s - %d xcr=%X\n", __func__, __LINE__, xcr);
pr_debug("%s - %d rcr=%X\n", __func__, __LINE__, rcr);
return 0;
}
static int davinci_i2s_prepare(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct davinci_mcbsp_dev *dev = snd_soc_dai_get_drvdata(dai);
int playback = (substream->stream == SNDRV_PCM_STREAM_PLAYBACK);
davinci_mcbsp_stop(dev, playback);
return 0;
}
static int davinci_i2s_trigger(struct snd_pcm_substream *substream, int cmd,
struct snd_soc_dai *dai)
{
struct davinci_mcbsp_dev *dev = snd_soc_dai_get_drvdata(dai);
int ret = 0;
int playback = (substream->stream == SNDRV_PCM_STREAM_PLAYBACK);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
davinci_mcbsp_start(dev, substream);
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
davinci_mcbsp_stop(dev, playback);
break;
default:
ret = -EINVAL;
}
return ret;
}
static int davinci_i2s_startup(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct davinci_mcbsp_dev *dev = snd_soc_dai_get_drvdata(dai);
snd_soc_dai_set_dma_data(dai, substream, dev->dma_params);
return 0;
}
static void davinci_i2s_shutdown(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct davinci_mcbsp_dev *dev = snd_soc_dai_get_drvdata(dai);
int playback = (substream->stream == SNDRV_PCM_STREAM_PLAYBACK);
davinci_mcbsp_stop(dev, playback);
}
#define DAVINCI_I2S_RATES SNDRV_PCM_RATE_8000_96000
static struct snd_soc_dai_ops davinci_i2s_dai_ops = {
.startup = davinci_i2s_startup,
.shutdown = davinci_i2s_shutdown,
.prepare = davinci_i2s_prepare,
.trigger = davinci_i2s_trigger,
.hw_params = davinci_i2s_hw_params,
.set_fmt = davinci_i2s_set_dai_fmt,
.set_clkdiv = davinci_i2s_dai_set_clkdiv,
};
static struct snd_soc_dai_driver davinci_i2s_dai = {
.playback = {
.channels_min = 2,
.channels_max = 2,
.rates = DAVINCI_I2S_RATES,
.formats = SNDRV_PCM_FMTBIT_S16_LE,},
.capture = {
.channels_min = 2,
.channels_max = 2,
.rates = DAVINCI_I2S_RATES,
.formats = SNDRV_PCM_FMTBIT_S16_LE,},
.ops = &davinci_i2s_dai_ops,
};
static int davinci_i2s_probe(struct platform_device *pdev)
{
struct snd_platform_data *pdata = pdev->dev.platform_data;
struct davinci_mcbsp_dev *dev;
struct resource *mem, *ioarea, *res;
enum dma_event_q asp_chan_q = EVENTQ_0;
enum dma_event_q ram_chan_q = EVENTQ_1;
int ret;
mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!mem) {
dev_err(&pdev->dev, "no mem resource?\n");
return -ENODEV;
}
ioarea = request_mem_region(mem->start, resource_size(mem),
pdev->name);
if (!ioarea) {
dev_err(&pdev->dev, "McBSP region already claimed\n");
return -EBUSY;
}
dev = kzalloc(sizeof(struct davinci_mcbsp_dev), GFP_KERNEL);
if (!dev) {
ret = -ENOMEM;
goto err_release_region;
}
if (pdata) {
dev->enable_channel_combine = pdata->enable_channel_combine;
dev->dma_params[SNDRV_PCM_STREAM_PLAYBACK].sram_size =
pdata->sram_size_playback;
dev->dma_params[SNDRV_PCM_STREAM_CAPTURE].sram_size =
pdata->sram_size_capture;
dev->clk_input_pin = pdata->clk_input_pin;
dev->i2s_accurate_sck = pdata->i2s_accurate_sck;
asp_chan_q = pdata->asp_chan_q;
ram_chan_q = pdata->ram_chan_q;
}
dev->dma_params[SNDRV_PCM_STREAM_PLAYBACK].asp_chan_q = asp_chan_q;
dev->dma_params[SNDRV_PCM_STREAM_PLAYBACK].ram_chan_q = ram_chan_q;
dev->dma_params[SNDRV_PCM_STREAM_CAPTURE].asp_chan_q = asp_chan_q;
dev->dma_params[SNDRV_PCM_STREAM_CAPTURE].ram_chan_q = ram_chan_q;
dev->clk = clk_get(&pdev->dev, NULL);
if (IS_ERR(dev->clk)) {
ret = -ENODEV;
goto err_free_mem;
}
clk_enable(dev->clk);
dev->base = ioremap(mem->start, resource_size(mem));
if (!dev->base) {
dev_err(&pdev->dev, "ioremap failed\n");
ret = -ENOMEM;
goto err_release_clk;
}
dev->dma_params[SNDRV_PCM_STREAM_PLAYBACK].dma_addr =
(dma_addr_t)(mem->start + DAVINCI_MCBSP_DXR_REG);
dev->dma_params[SNDRV_PCM_STREAM_CAPTURE].dma_addr =
(dma_addr_t)(mem->start + DAVINCI_MCBSP_DRR_REG);
/* first TX, then RX */
res = platform_get_resource(pdev, IORESOURCE_DMA, 0);
if (!res) {
dev_err(&pdev->dev, "no DMA resource\n");
ret = -ENXIO;
goto err_iounmap;
}
dev->dma_params[SNDRV_PCM_STREAM_PLAYBACK].channel = res->start;
res = platform_get_resource(pdev, IORESOURCE_DMA, 1);
if (!res) {
dev_err(&pdev->dev, "no DMA resource\n");
ret = -ENXIO;
goto err_iounmap;
}
dev->dma_params[SNDRV_PCM_STREAM_CAPTURE].channel = res->start;
dev->dev = &pdev->dev;
dev_set_drvdata(&pdev->dev, dev);
ret = snd_soc_register_dai(&pdev->dev, &davinci_i2s_dai);
if (ret != 0)
goto err_iounmap;
return 0;
err_iounmap:
iounmap(dev->base);
err_release_clk:
clk_disable(dev->clk);
clk_put(dev->clk);
err_free_mem:
kfree(dev);
err_release_region:
release_mem_region(mem->start, resource_size(mem));
return ret;
}
static int davinci_i2s_remove(struct platform_device *pdev)
{
struct davinci_mcbsp_dev *dev = dev_get_drvdata(&pdev->dev);
struct resource *mem;
snd_soc_unregister_dai(&pdev->dev);
clk_disable(dev->clk);
clk_put(dev->clk);
dev->clk = NULL;
kfree(dev);
mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
release_mem_region(mem->start, resource_size(mem));
return 0;
}
static struct platform_driver davinci_mcbsp_driver = {
.probe = davinci_i2s_probe,
.remove = davinci_i2s_remove,
.driver = {
.name = "davinci-mcbsp",
.owner = THIS_MODULE,
},
};
static int __init davinci_i2s_init(void)
{
return platform_driver_register(&davinci_mcbsp_driver);
}
module_init(davinci_i2s_init);
static void __exit davinci_i2s_exit(void)
{
platform_driver_unregister(&davinci_mcbsp_driver);
}
module_exit(davinci_i2s_exit);
MODULE_AUTHOR("Vladimir Barinov");
MODULE_DESCRIPTION("TI DAVINCI I2S (McBSP) SoC Interface");
MODULE_LICENSE("GPL");
| gpl-2.0 |
templetontsai/nexus7-grouper-kernel | drivers/pcmcia/xxs1500_ss.c | 3185 | 8292 | /*
* PCMCIA socket code for the MyCable XXS1500 system.
*
* Copyright (c) 2009 Manuel Lauss <manuel.lauss@gmail.com>
*
*/
#include <linux/delay.h>
#include <linux/gpio.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/ioport.h>
#include <linux/mm.h>
#include <linux/platform_device.h>
#include <linux/pm.h>
#include <linux/resource.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <pcmcia/ss.h>
#include <pcmcia/cistpl.h>
#include <asm/irq.h>
#include <asm/system.h>
#include <asm/mach-au1x00/au1000.h>
#define MEM_MAP_SIZE 0x400000
#define IO_MAP_SIZE 0x1000
/*
* 3.3V cards only; all interfacing is done via gpios:
*
* 0/1: carddetect (00 = card present, xx = huh)
* 4: card irq
* 204: reset (high-act)
* 205: buffer enable (low-act)
* 208/209: card voltage key (00,01,10,11)
* 210: battwarn
* 211: batdead
* 214: power (low-act)
*/
#define GPIO_CDA 0
#define GPIO_CDB 1
#define GPIO_CARDIRQ 4
#define GPIO_RESET 204
#define GPIO_OUTEN 205
#define GPIO_VSL 208
#define GPIO_VSH 209
#define GPIO_BATTDEAD 210
#define GPIO_BATTWARN 211
#define GPIO_POWER 214
struct xxs1500_pcmcia_sock {
struct pcmcia_socket socket;
void *virt_io;
phys_addr_t phys_io;
phys_addr_t phys_attr;
phys_addr_t phys_mem;
/* previous flags for set_socket() */
unsigned int old_flags;
};
#define to_xxs_socket(x) container_of(x, struct xxs1500_pcmcia_sock, socket)
static irqreturn_t cdirq(int irq, void *data)
{
struct xxs1500_pcmcia_sock *sock = data;
pcmcia_parse_events(&sock->socket, SS_DETECT);
return IRQ_HANDLED;
}
static int xxs1500_pcmcia_configure(struct pcmcia_socket *skt,
struct socket_state_t *state)
{
struct xxs1500_pcmcia_sock *sock = to_xxs_socket(skt);
unsigned int changed;
/* power control */
switch (state->Vcc) {
case 0:
gpio_set_value(GPIO_POWER, 1); /* power off */
break;
case 33:
gpio_set_value(GPIO_POWER, 0); /* power on */
break;
case 50:
default:
return -EINVAL;
}
changed = state->flags ^ sock->old_flags;
if (changed & SS_RESET) {
if (state->flags & SS_RESET) {
gpio_set_value(GPIO_RESET, 1); /* assert reset */
gpio_set_value(GPIO_OUTEN, 1); /* buffers off */
} else {
gpio_set_value(GPIO_RESET, 0); /* deassert reset */
gpio_set_value(GPIO_OUTEN, 0); /* buffers on */
msleep(500);
}
}
sock->old_flags = state->flags;
return 0;
}
static int xxs1500_pcmcia_get_status(struct pcmcia_socket *skt,
unsigned int *value)
{
unsigned int status;
int i;
status = 0;
/* check carddetects: GPIO[0:1] must both be low */
if (!gpio_get_value(GPIO_CDA) && !gpio_get_value(GPIO_CDB))
status |= SS_DETECT;
/* determine card voltage: GPIO[208:209] binary value */
i = (!!gpio_get_value(GPIO_VSL)) | ((!!gpio_get_value(GPIO_VSH)) << 1);
switch (i) {
case 0:
case 1:
case 2:
status |= SS_3VCARD; /* 3V card */
break;
case 3: /* 5V card, unsupported */
default:
status |= SS_XVCARD; /* treated as unsupported in core */
}
/* GPIO214: low active power switch */
status |= gpio_get_value(GPIO_POWER) ? 0 : SS_POWERON;
/* GPIO204: high-active reset line */
status |= gpio_get_value(GPIO_RESET) ? SS_RESET : SS_READY;
/* other stuff */
status |= gpio_get_value(GPIO_BATTDEAD) ? 0 : SS_BATDEAD;
status |= gpio_get_value(GPIO_BATTWARN) ? 0 : SS_BATWARN;
*value = status;
return 0;
}
static int xxs1500_pcmcia_sock_init(struct pcmcia_socket *skt)
{
gpio_direction_input(GPIO_CDA);
gpio_direction_input(GPIO_CDB);
gpio_direction_input(GPIO_VSL);
gpio_direction_input(GPIO_VSH);
gpio_direction_input(GPIO_BATTDEAD);
gpio_direction_input(GPIO_BATTWARN);
gpio_direction_output(GPIO_RESET, 1); /* assert reset */
gpio_direction_output(GPIO_OUTEN, 1); /* disable buffers */
gpio_direction_output(GPIO_POWER, 1); /* power off */
return 0;
}
static int xxs1500_pcmcia_sock_suspend(struct pcmcia_socket *skt)
{
return 0;
}
static int au1x00_pcmcia_set_io_map(struct pcmcia_socket *skt,
struct pccard_io_map *map)
{
struct xxs1500_pcmcia_sock *sock = to_xxs_socket(skt);
map->start = (u32)sock->virt_io;
map->stop = map->start + IO_MAP_SIZE;
return 0;
}
static int au1x00_pcmcia_set_mem_map(struct pcmcia_socket *skt,
struct pccard_mem_map *map)
{
struct xxs1500_pcmcia_sock *sock = to_xxs_socket(skt);
if (map->flags & MAP_ATTRIB)
map->static_start = sock->phys_attr + map->card_start;
else
map->static_start = sock->phys_mem + map->card_start;
return 0;
}
static struct pccard_operations xxs1500_pcmcia_operations = {
.init = xxs1500_pcmcia_sock_init,
.suspend = xxs1500_pcmcia_sock_suspend,
.get_status = xxs1500_pcmcia_get_status,
.set_socket = xxs1500_pcmcia_configure,
.set_io_map = au1x00_pcmcia_set_io_map,
.set_mem_map = au1x00_pcmcia_set_mem_map,
};
static int __devinit xxs1500_pcmcia_probe(struct platform_device *pdev)
{
struct xxs1500_pcmcia_sock *sock;
struct resource *r;
int ret, irq;
sock = kzalloc(sizeof(struct xxs1500_pcmcia_sock), GFP_KERNEL);
if (!sock)
return -ENOMEM;
ret = -ENODEV;
/* 36bit PCMCIA Attribute area address */
r = platform_get_resource_byname(pdev, IORESOURCE_MEM, "pcmcia-attr");
if (!r) {
dev_err(&pdev->dev, "missing 'pcmcia-attr' resource!\n");
goto out0;
}
sock->phys_attr = r->start;
/* 36bit PCMCIA Memory area address */
r = platform_get_resource_byname(pdev, IORESOURCE_MEM, "pcmcia-mem");
if (!r) {
dev_err(&pdev->dev, "missing 'pcmcia-mem' resource!\n");
goto out0;
}
sock->phys_mem = r->start;
/* 36bit PCMCIA IO area address */
r = platform_get_resource_byname(pdev, IORESOURCE_MEM, "pcmcia-io");
if (!r) {
dev_err(&pdev->dev, "missing 'pcmcia-io' resource!\n");
goto out0;
}
sock->phys_io = r->start;
/*
* PCMCIA client drivers use the inb/outb macros to access
* the IO registers. Since mips_io_port_base is added
* to the access address of the mips implementation of
* inb/outb, we need to subtract it here because we want
* to access the I/O or MEM address directly, without
* going through this "mips_io_port_base" mechanism.
*/
sock->virt_io = (void *)(ioremap(sock->phys_io, IO_MAP_SIZE) -
mips_io_port_base);
if (!sock->virt_io) {
dev_err(&pdev->dev, "cannot remap IO area\n");
ret = -ENOMEM;
goto out0;
}
sock->socket.ops = &xxs1500_pcmcia_operations;
sock->socket.owner = THIS_MODULE;
sock->socket.pci_irq = gpio_to_irq(GPIO_CARDIRQ);
sock->socket.features = SS_CAP_STATIC_MAP | SS_CAP_PCCARD;
sock->socket.map_size = MEM_MAP_SIZE;
sock->socket.io_offset = (unsigned long)sock->virt_io;
sock->socket.dev.parent = &pdev->dev;
sock->socket.resource_ops = &pccard_static_ops;
platform_set_drvdata(pdev, sock);
/* setup carddetect irq: use one of the 2 GPIOs as an
* edge detector.
*/
irq = gpio_to_irq(GPIO_CDA);
irq_set_irq_type(irq, IRQ_TYPE_EDGE_BOTH);
ret = request_irq(irq, cdirq, 0, "pcmcia_carddetect", sock);
if (ret) {
dev_err(&pdev->dev, "cannot setup cd irq\n");
goto out1;
}
ret = pcmcia_register_socket(&sock->socket);
if (ret) {
dev_err(&pdev->dev, "failed to register\n");
goto out2;
}
printk(KERN_INFO "MyCable XXS1500 PCMCIA socket services\n");
return 0;
out2:
free_irq(gpio_to_irq(GPIO_CDA), sock);
out1:
iounmap((void *)(sock->virt_io + (u32)mips_io_port_base));
out0:
kfree(sock);
return ret;
}
static int __devexit xxs1500_pcmcia_remove(struct platform_device *pdev)
{
struct xxs1500_pcmcia_sock *sock = platform_get_drvdata(pdev);
pcmcia_unregister_socket(&sock->socket);
free_irq(gpio_to_irq(GPIO_CDA), sock);
iounmap((void *)(sock->virt_io + (u32)mips_io_port_base));
kfree(sock);
return 0;
}
static struct platform_driver xxs1500_pcmcia_socket_driver = {
.driver = {
.name = "xxs1500_pcmcia",
.owner = THIS_MODULE,
},
.probe = xxs1500_pcmcia_probe,
.remove = __devexit_p(xxs1500_pcmcia_remove),
};
int __init xxs1500_pcmcia_socket_load(void)
{
return platform_driver_register(&xxs1500_pcmcia_socket_driver);
}
void __exit xxs1500_pcmcia_socket_unload(void)
{
platform_driver_unregister(&xxs1500_pcmcia_socket_driver);
}
module_init(xxs1500_pcmcia_socket_load);
module_exit(xxs1500_pcmcia_socket_unload);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("PCMCIA Socket Services for MyCable XXS1500 systems");
MODULE_AUTHOR("Manuel Lauss");
| gpl-2.0 |
vickyvca/MindEater-dior | sound/soc/codecs/max98088.c | 3697 | 76616 | /*
* max98088.c -- MAX98088 ALSA SoC Audio driver
*
* Copyright 2010 Maxim Integrated Products
*
* 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/moduleparam.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/pm.h>
#include <linux/i2c.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include <sound/initval.h>
#include <sound/tlv.h>
#include <linux/slab.h>
#include <asm/div64.h>
#include <sound/max98088.h>
#include "max98088.h"
enum max98088_type {
MAX98088,
MAX98089,
};
struct max98088_cdata {
unsigned int rate;
unsigned int fmt;
int eq_sel;
};
struct max98088_priv {
enum max98088_type devtype;
struct max98088_pdata *pdata;
unsigned int sysclk;
struct max98088_cdata dai[2];
int eq_textcnt;
const char **eq_texts;
struct soc_enum eq_enum;
u8 ina_state;
u8 inb_state;
unsigned int ex_mode;
unsigned int digmic;
unsigned int mic1pre;
unsigned int mic2pre;
unsigned int extmic_mode;
};
static const u8 max98088_reg[M98088_REG_CNT] = {
0x00, /* 00 IRQ status */
0x00, /* 01 MIC status */
0x00, /* 02 jack status */
0x00, /* 03 battery voltage */
0x00, /* 04 */
0x00, /* 05 */
0x00, /* 06 */
0x00, /* 07 */
0x00, /* 08 */
0x00, /* 09 */
0x00, /* 0A */
0x00, /* 0B */
0x00, /* 0C */
0x00, /* 0D */
0x00, /* 0E */
0x00, /* 0F interrupt enable */
0x00, /* 10 master clock */
0x00, /* 11 DAI1 clock mode */
0x00, /* 12 DAI1 clock control */
0x00, /* 13 DAI1 clock control */
0x00, /* 14 DAI1 format */
0x00, /* 15 DAI1 clock */
0x00, /* 16 DAI1 config */
0x00, /* 17 DAI1 TDM */
0x00, /* 18 DAI1 filters */
0x00, /* 19 DAI2 clock mode */
0x00, /* 1A DAI2 clock control */
0x00, /* 1B DAI2 clock control */
0x00, /* 1C DAI2 format */
0x00, /* 1D DAI2 clock */
0x00, /* 1E DAI2 config */
0x00, /* 1F DAI2 TDM */
0x00, /* 20 DAI2 filters */
0x00, /* 21 data config */
0x00, /* 22 DAC mixer */
0x00, /* 23 left ADC mixer */
0x00, /* 24 right ADC mixer */
0x00, /* 25 left HP mixer */
0x00, /* 26 right HP mixer */
0x00, /* 27 HP control */
0x00, /* 28 left REC mixer */
0x00, /* 29 right REC mixer */
0x00, /* 2A REC control */
0x00, /* 2B left SPK mixer */
0x00, /* 2C right SPK mixer */
0x00, /* 2D SPK control */
0x00, /* 2E sidetone */
0x00, /* 2F DAI1 playback level */
0x00, /* 30 DAI1 playback level */
0x00, /* 31 DAI2 playback level */
0x00, /* 32 DAI2 playbakc level */
0x00, /* 33 left ADC level */
0x00, /* 34 right ADC level */
0x00, /* 35 MIC1 level */
0x00, /* 36 MIC2 level */
0x00, /* 37 INA level */
0x00, /* 38 INB level */
0x00, /* 39 left HP volume */
0x00, /* 3A right HP volume */
0x00, /* 3B left REC volume */
0x00, /* 3C right REC volume */
0x00, /* 3D left SPK volume */
0x00, /* 3E right SPK volume */
0x00, /* 3F MIC config */
0x00, /* 40 MIC threshold */
0x00, /* 41 excursion limiter filter */
0x00, /* 42 excursion limiter threshold */
0x00, /* 43 ALC */
0x00, /* 44 power limiter threshold */
0x00, /* 45 power limiter config */
0x00, /* 46 distortion limiter config */
0x00, /* 47 audio input */
0x00, /* 48 microphone */
0x00, /* 49 level control */
0x00, /* 4A bypass switches */
0x00, /* 4B jack detect */
0x00, /* 4C input enable */
0x00, /* 4D output enable */
0xF0, /* 4E bias control */
0x00, /* 4F DAC power */
0x0F, /* 50 DAC power */
0x00, /* 51 system */
0x00, /* 52 DAI1 EQ1 */
0x00, /* 53 DAI1 EQ1 */
0x00, /* 54 DAI1 EQ1 */
0x00, /* 55 DAI1 EQ1 */
0x00, /* 56 DAI1 EQ1 */
0x00, /* 57 DAI1 EQ1 */
0x00, /* 58 DAI1 EQ1 */
0x00, /* 59 DAI1 EQ1 */
0x00, /* 5A DAI1 EQ1 */
0x00, /* 5B DAI1 EQ1 */
0x00, /* 5C DAI1 EQ2 */
0x00, /* 5D DAI1 EQ2 */
0x00, /* 5E DAI1 EQ2 */
0x00, /* 5F DAI1 EQ2 */
0x00, /* 60 DAI1 EQ2 */
0x00, /* 61 DAI1 EQ2 */
0x00, /* 62 DAI1 EQ2 */
0x00, /* 63 DAI1 EQ2 */
0x00, /* 64 DAI1 EQ2 */
0x00, /* 65 DAI1 EQ2 */
0x00, /* 66 DAI1 EQ3 */
0x00, /* 67 DAI1 EQ3 */
0x00, /* 68 DAI1 EQ3 */
0x00, /* 69 DAI1 EQ3 */
0x00, /* 6A DAI1 EQ3 */
0x00, /* 6B DAI1 EQ3 */
0x00, /* 6C DAI1 EQ3 */
0x00, /* 6D DAI1 EQ3 */
0x00, /* 6E DAI1 EQ3 */
0x00, /* 6F DAI1 EQ3 */
0x00, /* 70 DAI1 EQ4 */
0x00, /* 71 DAI1 EQ4 */
0x00, /* 72 DAI1 EQ4 */
0x00, /* 73 DAI1 EQ4 */
0x00, /* 74 DAI1 EQ4 */
0x00, /* 75 DAI1 EQ4 */
0x00, /* 76 DAI1 EQ4 */
0x00, /* 77 DAI1 EQ4 */
0x00, /* 78 DAI1 EQ4 */
0x00, /* 79 DAI1 EQ4 */
0x00, /* 7A DAI1 EQ5 */
0x00, /* 7B DAI1 EQ5 */
0x00, /* 7C DAI1 EQ5 */
0x00, /* 7D DAI1 EQ5 */
0x00, /* 7E DAI1 EQ5 */
0x00, /* 7F DAI1 EQ5 */
0x00, /* 80 DAI1 EQ5 */
0x00, /* 81 DAI1 EQ5 */
0x00, /* 82 DAI1 EQ5 */
0x00, /* 83 DAI1 EQ5 */
0x00, /* 84 DAI2 EQ1 */
0x00, /* 85 DAI2 EQ1 */
0x00, /* 86 DAI2 EQ1 */
0x00, /* 87 DAI2 EQ1 */
0x00, /* 88 DAI2 EQ1 */
0x00, /* 89 DAI2 EQ1 */
0x00, /* 8A DAI2 EQ1 */
0x00, /* 8B DAI2 EQ1 */
0x00, /* 8C DAI2 EQ1 */
0x00, /* 8D DAI2 EQ1 */
0x00, /* 8E DAI2 EQ2 */
0x00, /* 8F DAI2 EQ2 */
0x00, /* 90 DAI2 EQ2 */
0x00, /* 91 DAI2 EQ2 */
0x00, /* 92 DAI2 EQ2 */
0x00, /* 93 DAI2 EQ2 */
0x00, /* 94 DAI2 EQ2 */
0x00, /* 95 DAI2 EQ2 */
0x00, /* 96 DAI2 EQ2 */
0x00, /* 97 DAI2 EQ2 */
0x00, /* 98 DAI2 EQ3 */
0x00, /* 99 DAI2 EQ3 */
0x00, /* 9A DAI2 EQ3 */
0x00, /* 9B DAI2 EQ3 */
0x00, /* 9C DAI2 EQ3 */
0x00, /* 9D DAI2 EQ3 */
0x00, /* 9E DAI2 EQ3 */
0x00, /* 9F DAI2 EQ3 */
0x00, /* A0 DAI2 EQ3 */
0x00, /* A1 DAI2 EQ3 */
0x00, /* A2 DAI2 EQ4 */
0x00, /* A3 DAI2 EQ4 */
0x00, /* A4 DAI2 EQ4 */
0x00, /* A5 DAI2 EQ4 */
0x00, /* A6 DAI2 EQ4 */
0x00, /* A7 DAI2 EQ4 */
0x00, /* A8 DAI2 EQ4 */
0x00, /* A9 DAI2 EQ4 */
0x00, /* AA DAI2 EQ4 */
0x00, /* AB DAI2 EQ4 */
0x00, /* AC DAI2 EQ5 */
0x00, /* AD DAI2 EQ5 */
0x00, /* AE DAI2 EQ5 */
0x00, /* AF DAI2 EQ5 */
0x00, /* B0 DAI2 EQ5 */
0x00, /* B1 DAI2 EQ5 */
0x00, /* B2 DAI2 EQ5 */
0x00, /* B3 DAI2 EQ5 */
0x00, /* B4 DAI2 EQ5 */
0x00, /* B5 DAI2 EQ5 */
0x00, /* B6 DAI1 biquad */
0x00, /* B7 DAI1 biquad */
0x00, /* B8 DAI1 biquad */
0x00, /* B9 DAI1 biquad */
0x00, /* BA DAI1 biquad */
0x00, /* BB DAI1 biquad */
0x00, /* BC DAI1 biquad */
0x00, /* BD DAI1 biquad */
0x00, /* BE DAI1 biquad */
0x00, /* BF DAI1 biquad */
0x00, /* C0 DAI2 biquad */
0x00, /* C1 DAI2 biquad */
0x00, /* C2 DAI2 biquad */
0x00, /* C3 DAI2 biquad */
0x00, /* C4 DAI2 biquad */
0x00, /* C5 DAI2 biquad */
0x00, /* C6 DAI2 biquad */
0x00, /* C7 DAI2 biquad */
0x00, /* C8 DAI2 biquad */
0x00, /* C9 DAI2 biquad */
0x00, /* CA */
0x00, /* CB */
0x00, /* CC */
0x00, /* CD */
0x00, /* CE */
0x00, /* CF */
0x00, /* D0 */
0x00, /* D1 */
0x00, /* D2 */
0x00, /* D3 */
0x00, /* D4 */
0x00, /* D5 */
0x00, /* D6 */
0x00, /* D7 */
0x00, /* D8 */
0x00, /* D9 */
0x00, /* DA */
0x70, /* DB */
0x00, /* DC */
0x00, /* DD */
0x00, /* DE */
0x00, /* DF */
0x00, /* E0 */
0x00, /* E1 */
0x00, /* E2 */
0x00, /* E3 */
0x00, /* E4 */
0x00, /* E5 */
0x00, /* E6 */
0x00, /* E7 */
0x00, /* E8 */
0x00, /* E9 */
0x00, /* EA */
0x00, /* EB */
0x00, /* EC */
0x00, /* ED */
0x00, /* EE */
0x00, /* EF */
0x00, /* F0 */
0x00, /* F1 */
0x00, /* F2 */
0x00, /* F3 */
0x00, /* F4 */
0x00, /* F5 */
0x00, /* F6 */
0x00, /* F7 */
0x00, /* F8 */
0x00, /* F9 */
0x00, /* FA */
0x00, /* FB */
0x00, /* FC */
0x00, /* FD */
0x00, /* FE */
0x00, /* FF */
};
static struct {
int readable;
int writable;
int vol;
} max98088_access[M98088_REG_CNT] = {
{ 0xFF, 0xFF, 1 }, /* 00 IRQ status */
{ 0xFF, 0x00, 1 }, /* 01 MIC status */
{ 0xFF, 0x00, 1 }, /* 02 jack status */
{ 0x1F, 0x1F, 1 }, /* 03 battery voltage */
{ 0xFF, 0xFF, 0 }, /* 04 */
{ 0xFF, 0xFF, 0 }, /* 05 */
{ 0xFF, 0xFF, 0 }, /* 06 */
{ 0xFF, 0xFF, 0 }, /* 07 */
{ 0xFF, 0xFF, 0 }, /* 08 */
{ 0xFF, 0xFF, 0 }, /* 09 */
{ 0xFF, 0xFF, 0 }, /* 0A */
{ 0xFF, 0xFF, 0 }, /* 0B */
{ 0xFF, 0xFF, 0 }, /* 0C */
{ 0xFF, 0xFF, 0 }, /* 0D */
{ 0xFF, 0xFF, 0 }, /* 0E */
{ 0xFF, 0xFF, 0 }, /* 0F interrupt enable */
{ 0xFF, 0xFF, 0 }, /* 10 master clock */
{ 0xFF, 0xFF, 0 }, /* 11 DAI1 clock mode */
{ 0xFF, 0xFF, 0 }, /* 12 DAI1 clock control */
{ 0xFF, 0xFF, 0 }, /* 13 DAI1 clock control */
{ 0xFF, 0xFF, 0 }, /* 14 DAI1 format */
{ 0xFF, 0xFF, 0 }, /* 15 DAI1 clock */
{ 0xFF, 0xFF, 0 }, /* 16 DAI1 config */
{ 0xFF, 0xFF, 0 }, /* 17 DAI1 TDM */
{ 0xFF, 0xFF, 0 }, /* 18 DAI1 filters */
{ 0xFF, 0xFF, 0 }, /* 19 DAI2 clock mode */
{ 0xFF, 0xFF, 0 }, /* 1A DAI2 clock control */
{ 0xFF, 0xFF, 0 }, /* 1B DAI2 clock control */
{ 0xFF, 0xFF, 0 }, /* 1C DAI2 format */
{ 0xFF, 0xFF, 0 }, /* 1D DAI2 clock */
{ 0xFF, 0xFF, 0 }, /* 1E DAI2 config */
{ 0xFF, 0xFF, 0 }, /* 1F DAI2 TDM */
{ 0xFF, 0xFF, 0 }, /* 20 DAI2 filters */
{ 0xFF, 0xFF, 0 }, /* 21 data config */
{ 0xFF, 0xFF, 0 }, /* 22 DAC mixer */
{ 0xFF, 0xFF, 0 }, /* 23 left ADC mixer */
{ 0xFF, 0xFF, 0 }, /* 24 right ADC mixer */
{ 0xFF, 0xFF, 0 }, /* 25 left HP mixer */
{ 0xFF, 0xFF, 0 }, /* 26 right HP mixer */
{ 0xFF, 0xFF, 0 }, /* 27 HP control */
{ 0xFF, 0xFF, 0 }, /* 28 left REC mixer */
{ 0xFF, 0xFF, 0 }, /* 29 right REC mixer */
{ 0xFF, 0xFF, 0 }, /* 2A REC control */
{ 0xFF, 0xFF, 0 }, /* 2B left SPK mixer */
{ 0xFF, 0xFF, 0 }, /* 2C right SPK mixer */
{ 0xFF, 0xFF, 0 }, /* 2D SPK control */
{ 0xFF, 0xFF, 0 }, /* 2E sidetone */
{ 0xFF, 0xFF, 0 }, /* 2F DAI1 playback level */
{ 0xFF, 0xFF, 0 }, /* 30 DAI1 playback level */
{ 0xFF, 0xFF, 0 }, /* 31 DAI2 playback level */
{ 0xFF, 0xFF, 0 }, /* 32 DAI2 playbakc level */
{ 0xFF, 0xFF, 0 }, /* 33 left ADC level */
{ 0xFF, 0xFF, 0 }, /* 34 right ADC level */
{ 0xFF, 0xFF, 0 }, /* 35 MIC1 level */
{ 0xFF, 0xFF, 0 }, /* 36 MIC2 level */
{ 0xFF, 0xFF, 0 }, /* 37 INA level */
{ 0xFF, 0xFF, 0 }, /* 38 INB level */
{ 0xFF, 0xFF, 0 }, /* 39 left HP volume */
{ 0xFF, 0xFF, 0 }, /* 3A right HP volume */
{ 0xFF, 0xFF, 0 }, /* 3B left REC volume */
{ 0xFF, 0xFF, 0 }, /* 3C right REC volume */
{ 0xFF, 0xFF, 0 }, /* 3D left SPK volume */
{ 0xFF, 0xFF, 0 }, /* 3E right SPK volume */
{ 0xFF, 0xFF, 0 }, /* 3F MIC config */
{ 0xFF, 0xFF, 0 }, /* 40 MIC threshold */
{ 0xFF, 0xFF, 0 }, /* 41 excursion limiter filter */
{ 0xFF, 0xFF, 0 }, /* 42 excursion limiter threshold */
{ 0xFF, 0xFF, 0 }, /* 43 ALC */
{ 0xFF, 0xFF, 0 }, /* 44 power limiter threshold */
{ 0xFF, 0xFF, 0 }, /* 45 power limiter config */
{ 0xFF, 0xFF, 0 }, /* 46 distortion limiter config */
{ 0xFF, 0xFF, 0 }, /* 47 audio input */
{ 0xFF, 0xFF, 0 }, /* 48 microphone */
{ 0xFF, 0xFF, 0 }, /* 49 level control */
{ 0xFF, 0xFF, 0 }, /* 4A bypass switches */
{ 0xFF, 0xFF, 0 }, /* 4B jack detect */
{ 0xFF, 0xFF, 0 }, /* 4C input enable */
{ 0xFF, 0xFF, 0 }, /* 4D output enable */
{ 0xFF, 0xFF, 0 }, /* 4E bias control */
{ 0xFF, 0xFF, 0 }, /* 4F DAC power */
{ 0xFF, 0xFF, 0 }, /* 50 DAC power */
{ 0xFF, 0xFF, 0 }, /* 51 system */
{ 0xFF, 0xFF, 0 }, /* 52 DAI1 EQ1 */
{ 0xFF, 0xFF, 0 }, /* 53 DAI1 EQ1 */
{ 0xFF, 0xFF, 0 }, /* 54 DAI1 EQ1 */
{ 0xFF, 0xFF, 0 }, /* 55 DAI1 EQ1 */
{ 0xFF, 0xFF, 0 }, /* 56 DAI1 EQ1 */
{ 0xFF, 0xFF, 0 }, /* 57 DAI1 EQ1 */
{ 0xFF, 0xFF, 0 }, /* 58 DAI1 EQ1 */
{ 0xFF, 0xFF, 0 }, /* 59 DAI1 EQ1 */
{ 0xFF, 0xFF, 0 }, /* 5A DAI1 EQ1 */
{ 0xFF, 0xFF, 0 }, /* 5B DAI1 EQ1 */
{ 0xFF, 0xFF, 0 }, /* 5C DAI1 EQ2 */
{ 0xFF, 0xFF, 0 }, /* 5D DAI1 EQ2 */
{ 0xFF, 0xFF, 0 }, /* 5E DAI1 EQ2 */
{ 0xFF, 0xFF, 0 }, /* 5F DAI1 EQ2 */
{ 0xFF, 0xFF, 0 }, /* 60 DAI1 EQ2 */
{ 0xFF, 0xFF, 0 }, /* 61 DAI1 EQ2 */
{ 0xFF, 0xFF, 0 }, /* 62 DAI1 EQ2 */
{ 0xFF, 0xFF, 0 }, /* 63 DAI1 EQ2 */
{ 0xFF, 0xFF, 0 }, /* 64 DAI1 EQ2 */
{ 0xFF, 0xFF, 0 }, /* 65 DAI1 EQ2 */
{ 0xFF, 0xFF, 0 }, /* 66 DAI1 EQ3 */
{ 0xFF, 0xFF, 0 }, /* 67 DAI1 EQ3 */
{ 0xFF, 0xFF, 0 }, /* 68 DAI1 EQ3 */
{ 0xFF, 0xFF, 0 }, /* 69 DAI1 EQ3 */
{ 0xFF, 0xFF, 0 }, /* 6A DAI1 EQ3 */
{ 0xFF, 0xFF, 0 }, /* 6B DAI1 EQ3 */
{ 0xFF, 0xFF, 0 }, /* 6C DAI1 EQ3 */
{ 0xFF, 0xFF, 0 }, /* 6D DAI1 EQ3 */
{ 0xFF, 0xFF, 0 }, /* 6E DAI1 EQ3 */
{ 0xFF, 0xFF, 0 }, /* 6F DAI1 EQ3 */
{ 0xFF, 0xFF, 0 }, /* 70 DAI1 EQ4 */
{ 0xFF, 0xFF, 0 }, /* 71 DAI1 EQ4 */
{ 0xFF, 0xFF, 0 }, /* 72 DAI1 EQ4 */
{ 0xFF, 0xFF, 0 }, /* 73 DAI1 EQ4 */
{ 0xFF, 0xFF, 0 }, /* 74 DAI1 EQ4 */
{ 0xFF, 0xFF, 0 }, /* 75 DAI1 EQ4 */
{ 0xFF, 0xFF, 0 }, /* 76 DAI1 EQ4 */
{ 0xFF, 0xFF, 0 }, /* 77 DAI1 EQ4 */
{ 0xFF, 0xFF, 0 }, /* 78 DAI1 EQ4 */
{ 0xFF, 0xFF, 0 }, /* 79 DAI1 EQ4 */
{ 0xFF, 0xFF, 0 }, /* 7A DAI1 EQ5 */
{ 0xFF, 0xFF, 0 }, /* 7B DAI1 EQ5 */
{ 0xFF, 0xFF, 0 }, /* 7C DAI1 EQ5 */
{ 0xFF, 0xFF, 0 }, /* 7D DAI1 EQ5 */
{ 0xFF, 0xFF, 0 }, /* 7E DAI1 EQ5 */
{ 0xFF, 0xFF, 0 }, /* 7F DAI1 EQ5 */
{ 0xFF, 0xFF, 0 }, /* 80 DAI1 EQ5 */
{ 0xFF, 0xFF, 0 }, /* 81 DAI1 EQ5 */
{ 0xFF, 0xFF, 0 }, /* 82 DAI1 EQ5 */
{ 0xFF, 0xFF, 0 }, /* 83 DAI1 EQ5 */
{ 0xFF, 0xFF, 0 }, /* 84 DAI2 EQ1 */
{ 0xFF, 0xFF, 0 }, /* 85 DAI2 EQ1 */
{ 0xFF, 0xFF, 0 }, /* 86 DAI2 EQ1 */
{ 0xFF, 0xFF, 0 }, /* 87 DAI2 EQ1 */
{ 0xFF, 0xFF, 0 }, /* 88 DAI2 EQ1 */
{ 0xFF, 0xFF, 0 }, /* 89 DAI2 EQ1 */
{ 0xFF, 0xFF, 0 }, /* 8A DAI2 EQ1 */
{ 0xFF, 0xFF, 0 }, /* 8B DAI2 EQ1 */
{ 0xFF, 0xFF, 0 }, /* 8C DAI2 EQ1 */
{ 0xFF, 0xFF, 0 }, /* 8D DAI2 EQ1 */
{ 0xFF, 0xFF, 0 }, /* 8E DAI2 EQ2 */
{ 0xFF, 0xFF, 0 }, /* 8F DAI2 EQ2 */
{ 0xFF, 0xFF, 0 }, /* 90 DAI2 EQ2 */
{ 0xFF, 0xFF, 0 }, /* 91 DAI2 EQ2 */
{ 0xFF, 0xFF, 0 }, /* 92 DAI2 EQ2 */
{ 0xFF, 0xFF, 0 }, /* 93 DAI2 EQ2 */
{ 0xFF, 0xFF, 0 }, /* 94 DAI2 EQ2 */
{ 0xFF, 0xFF, 0 }, /* 95 DAI2 EQ2 */
{ 0xFF, 0xFF, 0 }, /* 96 DAI2 EQ2 */
{ 0xFF, 0xFF, 0 }, /* 97 DAI2 EQ2 */
{ 0xFF, 0xFF, 0 }, /* 98 DAI2 EQ3 */
{ 0xFF, 0xFF, 0 }, /* 99 DAI2 EQ3 */
{ 0xFF, 0xFF, 0 }, /* 9A DAI2 EQ3 */
{ 0xFF, 0xFF, 0 }, /* 9B DAI2 EQ3 */
{ 0xFF, 0xFF, 0 }, /* 9C DAI2 EQ3 */
{ 0xFF, 0xFF, 0 }, /* 9D DAI2 EQ3 */
{ 0xFF, 0xFF, 0 }, /* 9E DAI2 EQ3 */
{ 0xFF, 0xFF, 0 }, /* 9F DAI2 EQ3 */
{ 0xFF, 0xFF, 0 }, /* A0 DAI2 EQ3 */
{ 0xFF, 0xFF, 0 }, /* A1 DAI2 EQ3 */
{ 0xFF, 0xFF, 0 }, /* A2 DAI2 EQ4 */
{ 0xFF, 0xFF, 0 }, /* A3 DAI2 EQ4 */
{ 0xFF, 0xFF, 0 }, /* A4 DAI2 EQ4 */
{ 0xFF, 0xFF, 0 }, /* A5 DAI2 EQ4 */
{ 0xFF, 0xFF, 0 }, /* A6 DAI2 EQ4 */
{ 0xFF, 0xFF, 0 }, /* A7 DAI2 EQ4 */
{ 0xFF, 0xFF, 0 }, /* A8 DAI2 EQ4 */
{ 0xFF, 0xFF, 0 }, /* A9 DAI2 EQ4 */
{ 0xFF, 0xFF, 0 }, /* AA DAI2 EQ4 */
{ 0xFF, 0xFF, 0 }, /* AB DAI2 EQ4 */
{ 0xFF, 0xFF, 0 }, /* AC DAI2 EQ5 */
{ 0xFF, 0xFF, 0 }, /* AD DAI2 EQ5 */
{ 0xFF, 0xFF, 0 }, /* AE DAI2 EQ5 */
{ 0xFF, 0xFF, 0 }, /* AF DAI2 EQ5 */
{ 0xFF, 0xFF, 0 }, /* B0 DAI2 EQ5 */
{ 0xFF, 0xFF, 0 }, /* B1 DAI2 EQ5 */
{ 0xFF, 0xFF, 0 }, /* B2 DAI2 EQ5 */
{ 0xFF, 0xFF, 0 }, /* B3 DAI2 EQ5 */
{ 0xFF, 0xFF, 0 }, /* B4 DAI2 EQ5 */
{ 0xFF, 0xFF, 0 }, /* B5 DAI2 EQ5 */
{ 0xFF, 0xFF, 0 }, /* B6 DAI1 biquad */
{ 0xFF, 0xFF, 0 }, /* B7 DAI1 biquad */
{ 0xFF, 0xFF, 0 }, /* B8 DAI1 biquad */
{ 0xFF, 0xFF, 0 }, /* B9 DAI1 biquad */
{ 0xFF, 0xFF, 0 }, /* BA DAI1 biquad */
{ 0xFF, 0xFF, 0 }, /* BB DAI1 biquad */
{ 0xFF, 0xFF, 0 }, /* BC DAI1 biquad */
{ 0xFF, 0xFF, 0 }, /* BD DAI1 biquad */
{ 0xFF, 0xFF, 0 }, /* BE DAI1 biquad */
{ 0xFF, 0xFF, 0 }, /* BF DAI1 biquad */
{ 0xFF, 0xFF, 0 }, /* C0 DAI2 biquad */
{ 0xFF, 0xFF, 0 }, /* C1 DAI2 biquad */
{ 0xFF, 0xFF, 0 }, /* C2 DAI2 biquad */
{ 0xFF, 0xFF, 0 }, /* C3 DAI2 biquad */
{ 0xFF, 0xFF, 0 }, /* C4 DAI2 biquad */
{ 0xFF, 0xFF, 0 }, /* C5 DAI2 biquad */
{ 0xFF, 0xFF, 0 }, /* C6 DAI2 biquad */
{ 0xFF, 0xFF, 0 }, /* C7 DAI2 biquad */
{ 0xFF, 0xFF, 0 }, /* C8 DAI2 biquad */
{ 0xFF, 0xFF, 0 }, /* C9 DAI2 biquad */
{ 0x00, 0x00, 0 }, /* CA */
{ 0x00, 0x00, 0 }, /* CB */
{ 0x00, 0x00, 0 }, /* CC */
{ 0x00, 0x00, 0 }, /* CD */
{ 0x00, 0x00, 0 }, /* CE */
{ 0x00, 0x00, 0 }, /* CF */
{ 0x00, 0x00, 0 }, /* D0 */
{ 0x00, 0x00, 0 }, /* D1 */
{ 0x00, 0x00, 0 }, /* D2 */
{ 0x00, 0x00, 0 }, /* D3 */
{ 0x00, 0x00, 0 }, /* D4 */
{ 0x00, 0x00, 0 }, /* D5 */
{ 0x00, 0x00, 0 }, /* D6 */
{ 0x00, 0x00, 0 }, /* D7 */
{ 0x00, 0x00, 0 }, /* D8 */
{ 0x00, 0x00, 0 }, /* D9 */
{ 0x00, 0x00, 0 }, /* DA */
{ 0x00, 0x00, 0 }, /* DB */
{ 0x00, 0x00, 0 }, /* DC */
{ 0x00, 0x00, 0 }, /* DD */
{ 0x00, 0x00, 0 }, /* DE */
{ 0x00, 0x00, 0 }, /* DF */
{ 0x00, 0x00, 0 }, /* E0 */
{ 0x00, 0x00, 0 }, /* E1 */
{ 0x00, 0x00, 0 }, /* E2 */
{ 0x00, 0x00, 0 }, /* E3 */
{ 0x00, 0x00, 0 }, /* E4 */
{ 0x00, 0x00, 0 }, /* E5 */
{ 0x00, 0x00, 0 }, /* E6 */
{ 0x00, 0x00, 0 }, /* E7 */
{ 0x00, 0x00, 0 }, /* E8 */
{ 0x00, 0x00, 0 }, /* E9 */
{ 0x00, 0x00, 0 }, /* EA */
{ 0x00, 0x00, 0 }, /* EB */
{ 0x00, 0x00, 0 }, /* EC */
{ 0x00, 0x00, 0 }, /* ED */
{ 0x00, 0x00, 0 }, /* EE */
{ 0x00, 0x00, 0 }, /* EF */
{ 0x00, 0x00, 0 }, /* F0 */
{ 0x00, 0x00, 0 }, /* F1 */
{ 0x00, 0x00, 0 }, /* F2 */
{ 0x00, 0x00, 0 }, /* F3 */
{ 0x00, 0x00, 0 }, /* F4 */
{ 0x00, 0x00, 0 }, /* F5 */
{ 0x00, 0x00, 0 }, /* F6 */
{ 0x00, 0x00, 0 }, /* F7 */
{ 0x00, 0x00, 0 }, /* F8 */
{ 0x00, 0x00, 0 }, /* F9 */
{ 0x00, 0x00, 0 }, /* FA */
{ 0x00, 0x00, 0 }, /* FB */
{ 0x00, 0x00, 0 }, /* FC */
{ 0x00, 0x00, 0 }, /* FD */
{ 0x00, 0x00, 0 }, /* FE */
{ 0xFF, 0x00, 1 }, /* FF */
};
static int max98088_volatile_register(struct snd_soc_codec *codec, unsigned int reg)
{
return max98088_access[reg].vol;
}
/*
* Load equalizer DSP coefficient configurations registers
*/
static void m98088_eq_band(struct snd_soc_codec *codec, unsigned int dai,
unsigned int band, u16 *coefs)
{
unsigned int eq_reg;
unsigned int i;
BUG_ON(band > 4);
BUG_ON(dai > 1);
/* Load the base register address */
eq_reg = dai ? M98088_REG_84_DAI2_EQ_BASE : M98088_REG_52_DAI1_EQ_BASE;
/* Add the band address offset, note adjustment for word address */
eq_reg += band * (M98088_COEFS_PER_BAND << 1);
/* Step through the registers and coefs */
for (i = 0; i < M98088_COEFS_PER_BAND; i++) {
snd_soc_write(codec, eq_reg++, M98088_BYTE1(coefs[i]));
snd_soc_write(codec, eq_reg++, M98088_BYTE0(coefs[i]));
}
}
/*
* Excursion limiter modes
*/
static const char *max98088_exmode_texts[] = {
"Off", "100Hz", "400Hz", "600Hz", "800Hz", "1000Hz", "200-400Hz",
"400-600Hz", "400-800Hz",
};
static const unsigned int max98088_exmode_values[] = {
0x00, 0x43, 0x10, 0x20, 0x30, 0x40, 0x11, 0x22, 0x32
};
static const struct soc_enum max98088_exmode_enum =
SOC_VALUE_ENUM_SINGLE(M98088_REG_41_SPKDHP, 0, 127,
ARRAY_SIZE(max98088_exmode_texts),
max98088_exmode_texts,
max98088_exmode_values);
static const char *max98088_ex_thresh[] = { /* volts PP */
"0.6", "1.2", "1.8", "2.4", "3.0", "3.6", "4.2", "4.8"};
static const struct soc_enum max98088_ex_thresh_enum[] = {
SOC_ENUM_SINGLE(M98088_REG_42_SPKDHP_THRESH, 0, 8,
max98088_ex_thresh),
};
static const char *max98088_fltr_mode[] = {"Voice", "Music" };
static const struct soc_enum max98088_filter_mode_enum[] = {
SOC_ENUM_SINGLE(M98088_REG_18_DAI1_FILTERS, 7, 2, max98088_fltr_mode),
};
static const char *max98088_extmic_text[] = { "None", "MIC1", "MIC2" };
static const struct soc_enum max98088_extmic_enum =
SOC_ENUM_SINGLE(M98088_REG_48_CFG_MIC, 0, 3, max98088_extmic_text);
static const struct snd_kcontrol_new max98088_extmic_mux =
SOC_DAPM_ENUM("External MIC Mux", max98088_extmic_enum);
static const char *max98088_dai1_fltr[] = {
"Off", "fc=258/fs=16k", "fc=500/fs=16k",
"fc=258/fs=8k", "fc=500/fs=8k", "fc=200"};
static const struct soc_enum max98088_dai1_dac_filter_enum[] = {
SOC_ENUM_SINGLE(M98088_REG_18_DAI1_FILTERS, 0, 6, max98088_dai1_fltr),
};
static const struct soc_enum max98088_dai1_adc_filter_enum[] = {
SOC_ENUM_SINGLE(M98088_REG_18_DAI1_FILTERS, 4, 6, max98088_dai1_fltr),
};
static int max98088_mic1pre_set(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec);
unsigned int sel = ucontrol->value.integer.value[0];
max98088->mic1pre = sel;
snd_soc_update_bits(codec, M98088_REG_35_LVL_MIC1, M98088_MICPRE_MASK,
(1+sel)<<M98088_MICPRE_SHIFT);
return 0;
}
static int max98088_mic1pre_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec);
ucontrol->value.integer.value[0] = max98088->mic1pre;
return 0;
}
static int max98088_mic2pre_set(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec);
unsigned int sel = ucontrol->value.integer.value[0];
max98088->mic2pre = sel;
snd_soc_update_bits(codec, M98088_REG_36_LVL_MIC2, M98088_MICPRE_MASK,
(1+sel)<<M98088_MICPRE_SHIFT);
return 0;
}
static int max98088_mic2pre_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec);
ucontrol->value.integer.value[0] = max98088->mic2pre;
return 0;
}
static const unsigned int max98088_micboost_tlv[] = {
TLV_DB_RANGE_HEAD(2),
0, 1, TLV_DB_SCALE_ITEM(0, 2000, 0),
2, 2, TLV_DB_SCALE_ITEM(3000, 0, 0),
};
static const struct snd_kcontrol_new max98088_snd_controls[] = {
SOC_DOUBLE_R("Headphone Volume", M98088_REG_39_LVL_HP_L,
M98088_REG_3A_LVL_HP_R, 0, 31, 0),
SOC_DOUBLE_R("Speaker Volume", M98088_REG_3D_LVL_SPK_L,
M98088_REG_3E_LVL_SPK_R, 0, 31, 0),
SOC_DOUBLE_R("Receiver Volume", M98088_REG_3B_LVL_REC_L,
M98088_REG_3C_LVL_REC_R, 0, 31, 0),
SOC_DOUBLE_R("Headphone Switch", M98088_REG_39_LVL_HP_L,
M98088_REG_3A_LVL_HP_R, 7, 1, 1),
SOC_DOUBLE_R("Speaker Switch", M98088_REG_3D_LVL_SPK_L,
M98088_REG_3E_LVL_SPK_R, 7, 1, 1),
SOC_DOUBLE_R("Receiver Switch", M98088_REG_3B_LVL_REC_L,
M98088_REG_3C_LVL_REC_R, 7, 1, 1),
SOC_SINGLE("MIC1 Volume", M98088_REG_35_LVL_MIC1, 0, 31, 1),
SOC_SINGLE("MIC2 Volume", M98088_REG_36_LVL_MIC2, 0, 31, 1),
SOC_SINGLE_EXT_TLV("MIC1 Boost Volume",
M98088_REG_35_LVL_MIC1, 5, 2, 0,
max98088_mic1pre_get, max98088_mic1pre_set,
max98088_micboost_tlv),
SOC_SINGLE_EXT_TLV("MIC2 Boost Volume",
M98088_REG_36_LVL_MIC2, 5, 2, 0,
max98088_mic2pre_get, max98088_mic2pre_set,
max98088_micboost_tlv),
SOC_SINGLE("INA Volume", M98088_REG_37_LVL_INA, 0, 7, 1),
SOC_SINGLE("INB Volume", M98088_REG_38_LVL_INB, 0, 7, 1),
SOC_SINGLE("ADCL Volume", M98088_REG_33_LVL_ADC_L, 0, 15, 0),
SOC_SINGLE("ADCR Volume", M98088_REG_34_LVL_ADC_R, 0, 15, 0),
SOC_SINGLE("ADCL Boost Volume", M98088_REG_33_LVL_ADC_L, 4, 3, 0),
SOC_SINGLE("ADCR Boost Volume", M98088_REG_34_LVL_ADC_R, 4, 3, 0),
SOC_SINGLE("EQ1 Switch", M98088_REG_49_CFG_LEVEL, 0, 1, 0),
SOC_SINGLE("EQ2 Switch", M98088_REG_49_CFG_LEVEL, 1, 1, 0),
SOC_ENUM("EX Limiter Mode", max98088_exmode_enum),
SOC_ENUM("EX Limiter Threshold", max98088_ex_thresh_enum),
SOC_ENUM("DAI1 Filter Mode", max98088_filter_mode_enum),
SOC_ENUM("DAI1 DAC Filter", max98088_dai1_dac_filter_enum),
SOC_ENUM("DAI1 ADC Filter", max98088_dai1_adc_filter_enum),
SOC_SINGLE("DAI2 DC Block Switch", M98088_REG_20_DAI2_FILTERS,
0, 1, 0),
SOC_SINGLE("ALC Switch", M98088_REG_43_SPKALC_COMP, 7, 1, 0),
SOC_SINGLE("ALC Threshold", M98088_REG_43_SPKALC_COMP, 0, 7, 0),
SOC_SINGLE("ALC Multiband", M98088_REG_43_SPKALC_COMP, 3, 1, 0),
SOC_SINGLE("ALC Release Time", M98088_REG_43_SPKALC_COMP, 4, 7, 0),
SOC_SINGLE("PWR Limiter Threshold", M98088_REG_44_PWRLMT_CFG,
4, 15, 0),
SOC_SINGLE("PWR Limiter Weight", M98088_REG_44_PWRLMT_CFG, 0, 7, 0),
SOC_SINGLE("PWR Limiter Time1", M98088_REG_45_PWRLMT_TIME, 0, 15, 0),
SOC_SINGLE("PWR Limiter Time2", M98088_REG_45_PWRLMT_TIME, 4, 15, 0),
SOC_SINGLE("THD Limiter Threshold", M98088_REG_46_THDLMT_CFG, 4, 15, 0),
SOC_SINGLE("THD Limiter Time", M98088_REG_46_THDLMT_CFG, 0, 7, 0),
};
/* Left speaker mixer switch */
static const struct snd_kcontrol_new max98088_left_speaker_mixer_controls[] = {
SOC_DAPM_SINGLE("Left DAC1 Switch", M98088_REG_2B_MIX_SPK_LEFT, 0, 1, 0),
SOC_DAPM_SINGLE("Right DAC1 Switch", M98088_REG_2B_MIX_SPK_LEFT, 7, 1, 0),
SOC_DAPM_SINGLE("Left DAC2 Switch", M98088_REG_2B_MIX_SPK_LEFT, 0, 1, 0),
SOC_DAPM_SINGLE("Right DAC2 Switch", M98088_REG_2B_MIX_SPK_LEFT, 7, 1, 0),
SOC_DAPM_SINGLE("MIC1 Switch", M98088_REG_2B_MIX_SPK_LEFT, 5, 1, 0),
SOC_DAPM_SINGLE("MIC2 Switch", M98088_REG_2B_MIX_SPK_LEFT, 6, 1, 0),
SOC_DAPM_SINGLE("INA1 Switch", M98088_REG_2B_MIX_SPK_LEFT, 1, 1, 0),
SOC_DAPM_SINGLE("INA2 Switch", M98088_REG_2B_MIX_SPK_LEFT, 2, 1, 0),
SOC_DAPM_SINGLE("INB1 Switch", M98088_REG_2B_MIX_SPK_LEFT, 3, 1, 0),
SOC_DAPM_SINGLE("INB2 Switch", M98088_REG_2B_MIX_SPK_LEFT, 4, 1, 0),
};
/* Right speaker mixer switch */
static const struct snd_kcontrol_new max98088_right_speaker_mixer_controls[] = {
SOC_DAPM_SINGLE("Left DAC1 Switch", M98088_REG_2C_MIX_SPK_RIGHT, 7, 1, 0),
SOC_DAPM_SINGLE("Right DAC1 Switch", M98088_REG_2C_MIX_SPK_RIGHT, 0, 1, 0),
SOC_DAPM_SINGLE("Left DAC2 Switch", M98088_REG_2C_MIX_SPK_RIGHT, 7, 1, 0),
SOC_DAPM_SINGLE("Right DAC2 Switch", M98088_REG_2C_MIX_SPK_RIGHT, 0, 1, 0),
SOC_DAPM_SINGLE("MIC1 Switch", M98088_REG_2C_MIX_SPK_RIGHT, 5, 1, 0),
SOC_DAPM_SINGLE("MIC2 Switch", M98088_REG_2C_MIX_SPK_RIGHT, 6, 1, 0),
SOC_DAPM_SINGLE("INA1 Switch", M98088_REG_2C_MIX_SPK_RIGHT, 1, 1, 0),
SOC_DAPM_SINGLE("INA2 Switch", M98088_REG_2C_MIX_SPK_RIGHT, 2, 1, 0),
SOC_DAPM_SINGLE("INB1 Switch", M98088_REG_2C_MIX_SPK_RIGHT, 3, 1, 0),
SOC_DAPM_SINGLE("INB2 Switch", M98088_REG_2C_MIX_SPK_RIGHT, 4, 1, 0),
};
/* Left headphone mixer switch */
static const struct snd_kcontrol_new max98088_left_hp_mixer_controls[] = {
SOC_DAPM_SINGLE("Left DAC1 Switch", M98088_REG_25_MIX_HP_LEFT, 0, 1, 0),
SOC_DAPM_SINGLE("Right DAC1 Switch", M98088_REG_25_MIX_HP_LEFT, 7, 1, 0),
SOC_DAPM_SINGLE("Left DAC2 Switch", M98088_REG_25_MIX_HP_LEFT, 0, 1, 0),
SOC_DAPM_SINGLE("Right DAC2 Switch", M98088_REG_25_MIX_HP_LEFT, 7, 1, 0),
SOC_DAPM_SINGLE("MIC1 Switch", M98088_REG_25_MIX_HP_LEFT, 5, 1, 0),
SOC_DAPM_SINGLE("MIC2 Switch", M98088_REG_25_MIX_HP_LEFT, 6, 1, 0),
SOC_DAPM_SINGLE("INA1 Switch", M98088_REG_25_MIX_HP_LEFT, 1, 1, 0),
SOC_DAPM_SINGLE("INA2 Switch", M98088_REG_25_MIX_HP_LEFT, 2, 1, 0),
SOC_DAPM_SINGLE("INB1 Switch", M98088_REG_25_MIX_HP_LEFT, 3, 1, 0),
SOC_DAPM_SINGLE("INB2 Switch", M98088_REG_25_MIX_HP_LEFT, 4, 1, 0),
};
/* Right headphone mixer switch */
static const struct snd_kcontrol_new max98088_right_hp_mixer_controls[] = {
SOC_DAPM_SINGLE("Left DAC1 Switch", M98088_REG_26_MIX_HP_RIGHT, 7, 1, 0),
SOC_DAPM_SINGLE("Right DAC1 Switch", M98088_REG_26_MIX_HP_RIGHT, 0, 1, 0),
SOC_DAPM_SINGLE("Left DAC2 Switch", M98088_REG_26_MIX_HP_RIGHT, 7, 1, 0),
SOC_DAPM_SINGLE("Right DAC2 Switch", M98088_REG_26_MIX_HP_RIGHT, 0, 1, 0),
SOC_DAPM_SINGLE("MIC1 Switch", M98088_REG_26_MIX_HP_RIGHT, 5, 1, 0),
SOC_DAPM_SINGLE("MIC2 Switch", M98088_REG_26_MIX_HP_RIGHT, 6, 1, 0),
SOC_DAPM_SINGLE("INA1 Switch", M98088_REG_26_MIX_HP_RIGHT, 1, 1, 0),
SOC_DAPM_SINGLE("INA2 Switch", M98088_REG_26_MIX_HP_RIGHT, 2, 1, 0),
SOC_DAPM_SINGLE("INB1 Switch", M98088_REG_26_MIX_HP_RIGHT, 3, 1, 0),
SOC_DAPM_SINGLE("INB2 Switch", M98088_REG_26_MIX_HP_RIGHT, 4, 1, 0),
};
/* Left earpiece/receiver mixer switch */
static const struct snd_kcontrol_new max98088_left_rec_mixer_controls[] = {
SOC_DAPM_SINGLE("Left DAC1 Switch", M98088_REG_28_MIX_REC_LEFT, 0, 1, 0),
SOC_DAPM_SINGLE("Right DAC1 Switch", M98088_REG_28_MIX_REC_LEFT, 7, 1, 0),
SOC_DAPM_SINGLE("Left DAC2 Switch", M98088_REG_28_MIX_REC_LEFT, 0, 1, 0),
SOC_DAPM_SINGLE("Right DAC2 Switch", M98088_REG_28_MIX_REC_LEFT, 7, 1, 0),
SOC_DAPM_SINGLE("MIC1 Switch", M98088_REG_28_MIX_REC_LEFT, 5, 1, 0),
SOC_DAPM_SINGLE("MIC2 Switch", M98088_REG_28_MIX_REC_LEFT, 6, 1, 0),
SOC_DAPM_SINGLE("INA1 Switch", M98088_REG_28_MIX_REC_LEFT, 1, 1, 0),
SOC_DAPM_SINGLE("INA2 Switch", M98088_REG_28_MIX_REC_LEFT, 2, 1, 0),
SOC_DAPM_SINGLE("INB1 Switch", M98088_REG_28_MIX_REC_LEFT, 3, 1, 0),
SOC_DAPM_SINGLE("INB2 Switch", M98088_REG_28_MIX_REC_LEFT, 4, 1, 0),
};
/* Right earpiece/receiver mixer switch */
static const struct snd_kcontrol_new max98088_right_rec_mixer_controls[] = {
SOC_DAPM_SINGLE("Left DAC1 Switch", M98088_REG_29_MIX_REC_RIGHT, 7, 1, 0),
SOC_DAPM_SINGLE("Right DAC1 Switch", M98088_REG_29_MIX_REC_RIGHT, 0, 1, 0),
SOC_DAPM_SINGLE("Left DAC2 Switch", M98088_REG_29_MIX_REC_RIGHT, 7, 1, 0),
SOC_DAPM_SINGLE("Right DAC2 Switch", M98088_REG_29_MIX_REC_RIGHT, 0, 1, 0),
SOC_DAPM_SINGLE("MIC1 Switch", M98088_REG_29_MIX_REC_RIGHT, 5, 1, 0),
SOC_DAPM_SINGLE("MIC2 Switch", M98088_REG_29_MIX_REC_RIGHT, 6, 1, 0),
SOC_DAPM_SINGLE("INA1 Switch", M98088_REG_29_MIX_REC_RIGHT, 1, 1, 0),
SOC_DAPM_SINGLE("INA2 Switch", M98088_REG_29_MIX_REC_RIGHT, 2, 1, 0),
SOC_DAPM_SINGLE("INB1 Switch", M98088_REG_29_MIX_REC_RIGHT, 3, 1, 0),
SOC_DAPM_SINGLE("INB2 Switch", M98088_REG_29_MIX_REC_RIGHT, 4, 1, 0),
};
/* Left ADC mixer switch */
static const struct snd_kcontrol_new max98088_left_ADC_mixer_controls[] = {
SOC_DAPM_SINGLE("MIC1 Switch", M98088_REG_23_MIX_ADC_LEFT, 7, 1, 0),
SOC_DAPM_SINGLE("MIC2 Switch", M98088_REG_23_MIX_ADC_LEFT, 6, 1, 0),
SOC_DAPM_SINGLE("INA1 Switch", M98088_REG_23_MIX_ADC_LEFT, 3, 1, 0),
SOC_DAPM_SINGLE("INA2 Switch", M98088_REG_23_MIX_ADC_LEFT, 2, 1, 0),
SOC_DAPM_SINGLE("INB1 Switch", M98088_REG_23_MIX_ADC_LEFT, 1, 1, 0),
SOC_DAPM_SINGLE("INB2 Switch", M98088_REG_23_MIX_ADC_LEFT, 0, 1, 0),
};
/* Right ADC mixer switch */
static const struct snd_kcontrol_new max98088_right_ADC_mixer_controls[] = {
SOC_DAPM_SINGLE("MIC1 Switch", M98088_REG_24_MIX_ADC_RIGHT, 7, 1, 0),
SOC_DAPM_SINGLE("MIC2 Switch", M98088_REG_24_MIX_ADC_RIGHT, 6, 1, 0),
SOC_DAPM_SINGLE("INA1 Switch", M98088_REG_24_MIX_ADC_RIGHT, 3, 1, 0),
SOC_DAPM_SINGLE("INA2 Switch", M98088_REG_24_MIX_ADC_RIGHT, 2, 1, 0),
SOC_DAPM_SINGLE("INB1 Switch", M98088_REG_24_MIX_ADC_RIGHT, 1, 1, 0),
SOC_DAPM_SINGLE("INB2 Switch", M98088_REG_24_MIX_ADC_RIGHT, 0, 1, 0),
};
static int max98088_mic_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec);
switch (event) {
case SND_SOC_DAPM_POST_PMU:
if (w->reg == M98088_REG_35_LVL_MIC1) {
snd_soc_update_bits(codec, w->reg, M98088_MICPRE_MASK,
(1+max98088->mic1pre)<<M98088_MICPRE_SHIFT);
} else {
snd_soc_update_bits(codec, w->reg, M98088_MICPRE_MASK,
(1+max98088->mic2pre)<<M98088_MICPRE_SHIFT);
}
break;
case SND_SOC_DAPM_POST_PMD:
snd_soc_update_bits(codec, w->reg, M98088_MICPRE_MASK, 0);
break;
default:
return -EINVAL;
}
return 0;
}
/*
* The line inputs are 2-channel stereo inputs with the left
* and right channels sharing a common PGA power control signal.
*/
static int max98088_line_pga(struct snd_soc_dapm_widget *w,
int event, int line, u8 channel)
{
struct snd_soc_codec *codec = w->codec;
struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec);
u8 *state;
BUG_ON(!((channel == 1) || (channel == 2)));
switch (line) {
case LINE_INA:
state = &max98088->ina_state;
break;
case LINE_INB:
state = &max98088->inb_state;
break;
default:
return -EINVAL;
}
switch (event) {
case SND_SOC_DAPM_POST_PMU:
*state |= channel;
snd_soc_update_bits(codec, w->reg,
(1 << w->shift), (1 << w->shift));
break;
case SND_SOC_DAPM_POST_PMD:
*state &= ~channel;
if (*state == 0) {
snd_soc_update_bits(codec, w->reg,
(1 << w->shift), 0);
}
break;
default:
return -EINVAL;
}
return 0;
}
static int max98088_pga_ina1_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *k, int event)
{
return max98088_line_pga(w, event, LINE_INA, 1);
}
static int max98088_pga_ina2_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *k, int event)
{
return max98088_line_pga(w, event, LINE_INA, 2);
}
static int max98088_pga_inb1_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *k, int event)
{
return max98088_line_pga(w, event, LINE_INB, 1);
}
static int max98088_pga_inb2_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *k, int event)
{
return max98088_line_pga(w, event, LINE_INB, 2);
}
static const struct snd_soc_dapm_widget max98088_dapm_widgets[] = {
SND_SOC_DAPM_ADC("ADCL", "HiFi Capture", M98088_REG_4C_PWR_EN_IN, 1, 0),
SND_SOC_DAPM_ADC("ADCR", "HiFi Capture", M98088_REG_4C_PWR_EN_IN, 0, 0),
SND_SOC_DAPM_DAC("DACL1", "HiFi Playback",
M98088_REG_4D_PWR_EN_OUT, 1, 0),
SND_SOC_DAPM_DAC("DACR1", "HiFi Playback",
M98088_REG_4D_PWR_EN_OUT, 0, 0),
SND_SOC_DAPM_DAC("DACL2", "Aux Playback",
M98088_REG_4D_PWR_EN_OUT, 1, 0),
SND_SOC_DAPM_DAC("DACR2", "Aux Playback",
M98088_REG_4D_PWR_EN_OUT, 0, 0),
SND_SOC_DAPM_PGA("HP Left Out", M98088_REG_4D_PWR_EN_OUT,
7, 0, NULL, 0),
SND_SOC_DAPM_PGA("HP Right Out", M98088_REG_4D_PWR_EN_OUT,
6, 0, NULL, 0),
SND_SOC_DAPM_PGA("SPK Left Out", M98088_REG_4D_PWR_EN_OUT,
5, 0, NULL, 0),
SND_SOC_DAPM_PGA("SPK Right Out", M98088_REG_4D_PWR_EN_OUT,
4, 0, NULL, 0),
SND_SOC_DAPM_PGA("REC Left Out", M98088_REG_4D_PWR_EN_OUT,
3, 0, NULL, 0),
SND_SOC_DAPM_PGA("REC Right Out", M98088_REG_4D_PWR_EN_OUT,
2, 0, NULL, 0),
SND_SOC_DAPM_MUX("External MIC", SND_SOC_NOPM, 0, 0,
&max98088_extmic_mux),
SND_SOC_DAPM_MIXER("Left HP Mixer", SND_SOC_NOPM, 0, 0,
&max98088_left_hp_mixer_controls[0],
ARRAY_SIZE(max98088_left_hp_mixer_controls)),
SND_SOC_DAPM_MIXER("Right HP Mixer", SND_SOC_NOPM, 0, 0,
&max98088_right_hp_mixer_controls[0],
ARRAY_SIZE(max98088_right_hp_mixer_controls)),
SND_SOC_DAPM_MIXER("Left SPK Mixer", SND_SOC_NOPM, 0, 0,
&max98088_left_speaker_mixer_controls[0],
ARRAY_SIZE(max98088_left_speaker_mixer_controls)),
SND_SOC_DAPM_MIXER("Right SPK Mixer", SND_SOC_NOPM, 0, 0,
&max98088_right_speaker_mixer_controls[0],
ARRAY_SIZE(max98088_right_speaker_mixer_controls)),
SND_SOC_DAPM_MIXER("Left REC Mixer", SND_SOC_NOPM, 0, 0,
&max98088_left_rec_mixer_controls[0],
ARRAY_SIZE(max98088_left_rec_mixer_controls)),
SND_SOC_DAPM_MIXER("Right REC Mixer", SND_SOC_NOPM, 0, 0,
&max98088_right_rec_mixer_controls[0],
ARRAY_SIZE(max98088_right_rec_mixer_controls)),
SND_SOC_DAPM_MIXER("Left ADC Mixer", SND_SOC_NOPM, 0, 0,
&max98088_left_ADC_mixer_controls[0],
ARRAY_SIZE(max98088_left_ADC_mixer_controls)),
SND_SOC_DAPM_MIXER("Right ADC Mixer", SND_SOC_NOPM, 0, 0,
&max98088_right_ADC_mixer_controls[0],
ARRAY_SIZE(max98088_right_ADC_mixer_controls)),
SND_SOC_DAPM_PGA_E("MIC1 Input", M98088_REG_35_LVL_MIC1,
5, 0, NULL, 0, max98088_mic_event,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_PGA_E("MIC2 Input", M98088_REG_36_LVL_MIC2,
5, 0, NULL, 0, max98088_mic_event,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_PGA_E("INA1 Input", M98088_REG_4C_PWR_EN_IN,
7, 0, NULL, 0, max98088_pga_ina1_event,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_PGA_E("INA2 Input", M98088_REG_4C_PWR_EN_IN,
7, 0, NULL, 0, max98088_pga_ina2_event,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_PGA_E("INB1 Input", M98088_REG_4C_PWR_EN_IN,
6, 0, NULL, 0, max98088_pga_inb1_event,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_PGA_E("INB2 Input", M98088_REG_4C_PWR_EN_IN,
6, 0, NULL, 0, max98088_pga_inb2_event,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS("MICBIAS", M98088_REG_4C_PWR_EN_IN, 3, 0),
SND_SOC_DAPM_OUTPUT("HPL"),
SND_SOC_DAPM_OUTPUT("HPR"),
SND_SOC_DAPM_OUTPUT("SPKL"),
SND_SOC_DAPM_OUTPUT("SPKR"),
SND_SOC_DAPM_OUTPUT("RECL"),
SND_SOC_DAPM_OUTPUT("RECR"),
SND_SOC_DAPM_INPUT("MIC1"),
SND_SOC_DAPM_INPUT("MIC2"),
SND_SOC_DAPM_INPUT("INA1"),
SND_SOC_DAPM_INPUT("INA2"),
SND_SOC_DAPM_INPUT("INB1"),
SND_SOC_DAPM_INPUT("INB2"),
};
static const struct snd_soc_dapm_route max98088_audio_map[] = {
/* Left headphone output mixer */
{"Left HP Mixer", "Left DAC1 Switch", "DACL1"},
{"Left HP Mixer", "Left DAC2 Switch", "DACL2"},
{"Left HP Mixer", "Right DAC1 Switch", "DACR1"},
{"Left HP Mixer", "Right DAC2 Switch", "DACR2"},
{"Left HP Mixer", "MIC1 Switch", "MIC1 Input"},
{"Left HP Mixer", "MIC2 Switch", "MIC2 Input"},
{"Left HP Mixer", "INA1 Switch", "INA1 Input"},
{"Left HP Mixer", "INA2 Switch", "INA2 Input"},
{"Left HP Mixer", "INB1 Switch", "INB1 Input"},
{"Left HP Mixer", "INB2 Switch", "INB2 Input"},
/* Right headphone output mixer */
{"Right HP Mixer", "Left DAC1 Switch", "DACL1"},
{"Right HP Mixer", "Left DAC2 Switch", "DACL2" },
{"Right HP Mixer", "Right DAC1 Switch", "DACR1"},
{"Right HP Mixer", "Right DAC2 Switch", "DACR2"},
{"Right HP Mixer", "MIC1 Switch", "MIC1 Input"},
{"Right HP Mixer", "MIC2 Switch", "MIC2 Input"},
{"Right HP Mixer", "INA1 Switch", "INA1 Input"},
{"Right HP Mixer", "INA2 Switch", "INA2 Input"},
{"Right HP Mixer", "INB1 Switch", "INB1 Input"},
{"Right HP Mixer", "INB2 Switch", "INB2 Input"},
/* Left speaker output mixer */
{"Left SPK Mixer", "Left DAC1 Switch", "DACL1"},
{"Left SPK Mixer", "Left DAC2 Switch", "DACL2"},
{"Left SPK Mixer", "Right DAC1 Switch", "DACR1"},
{"Left SPK Mixer", "Right DAC2 Switch", "DACR2"},
{"Left SPK Mixer", "MIC1 Switch", "MIC1 Input"},
{"Left SPK Mixer", "MIC2 Switch", "MIC2 Input"},
{"Left SPK Mixer", "INA1 Switch", "INA1 Input"},
{"Left SPK Mixer", "INA2 Switch", "INA2 Input"},
{"Left SPK Mixer", "INB1 Switch", "INB1 Input"},
{"Left SPK Mixer", "INB2 Switch", "INB2 Input"},
/* Right speaker output mixer */
{"Right SPK Mixer", "Left DAC1 Switch", "DACL1"},
{"Right SPK Mixer", "Left DAC2 Switch", "DACL2"},
{"Right SPK Mixer", "Right DAC1 Switch", "DACR1"},
{"Right SPK Mixer", "Right DAC2 Switch", "DACR2"},
{"Right SPK Mixer", "MIC1 Switch", "MIC1 Input"},
{"Right SPK Mixer", "MIC2 Switch", "MIC2 Input"},
{"Right SPK Mixer", "INA1 Switch", "INA1 Input"},
{"Right SPK Mixer", "INA2 Switch", "INA2 Input"},
{"Right SPK Mixer", "INB1 Switch", "INB1 Input"},
{"Right SPK Mixer", "INB2 Switch", "INB2 Input"},
/* Earpiece/Receiver output mixer */
{"Left REC Mixer", "Left DAC1 Switch", "DACL1"},
{"Left REC Mixer", "Left DAC2 Switch", "DACL2"},
{"Left REC Mixer", "Right DAC1 Switch", "DACR1"},
{"Left REC Mixer", "Right DAC2 Switch", "DACR2"},
{"Left REC Mixer", "MIC1 Switch", "MIC1 Input"},
{"Left REC Mixer", "MIC2 Switch", "MIC2 Input"},
{"Left REC Mixer", "INA1 Switch", "INA1 Input"},
{"Left REC Mixer", "INA2 Switch", "INA2 Input"},
{"Left REC Mixer", "INB1 Switch", "INB1 Input"},
{"Left REC Mixer", "INB2 Switch", "INB2 Input"},
/* Earpiece/Receiver output mixer */
{"Right REC Mixer", "Left DAC1 Switch", "DACL1"},
{"Right REC Mixer", "Left DAC2 Switch", "DACL2"},
{"Right REC Mixer", "Right DAC1 Switch", "DACR1"},
{"Right REC Mixer", "Right DAC2 Switch", "DACR2"},
{"Right REC Mixer", "MIC1 Switch", "MIC1 Input"},
{"Right REC Mixer", "MIC2 Switch", "MIC2 Input"},
{"Right REC Mixer", "INA1 Switch", "INA1 Input"},
{"Right REC Mixer", "INA2 Switch", "INA2 Input"},
{"Right REC Mixer", "INB1 Switch", "INB1 Input"},
{"Right REC Mixer", "INB2 Switch", "INB2 Input"},
{"HP Left Out", NULL, "Left HP Mixer"},
{"HP Right Out", NULL, "Right HP Mixer"},
{"SPK Left Out", NULL, "Left SPK Mixer"},
{"SPK Right Out", NULL, "Right SPK Mixer"},
{"REC Left Out", NULL, "Left REC Mixer"},
{"REC Right Out", NULL, "Right REC Mixer"},
{"HPL", NULL, "HP Left Out"},
{"HPR", NULL, "HP Right Out"},
{"SPKL", NULL, "SPK Left Out"},
{"SPKR", NULL, "SPK Right Out"},
{"RECL", NULL, "REC Left Out"},
{"RECR", NULL, "REC Right Out"},
/* Left ADC input mixer */
{"Left ADC Mixer", "MIC1 Switch", "MIC1 Input"},
{"Left ADC Mixer", "MIC2 Switch", "MIC2 Input"},
{"Left ADC Mixer", "INA1 Switch", "INA1 Input"},
{"Left ADC Mixer", "INA2 Switch", "INA2 Input"},
{"Left ADC Mixer", "INB1 Switch", "INB1 Input"},
{"Left ADC Mixer", "INB2 Switch", "INB2 Input"},
/* Right ADC input mixer */
{"Right ADC Mixer", "MIC1 Switch", "MIC1 Input"},
{"Right ADC Mixer", "MIC2 Switch", "MIC2 Input"},
{"Right ADC Mixer", "INA1 Switch", "INA1 Input"},
{"Right ADC Mixer", "INA2 Switch", "INA2 Input"},
{"Right ADC Mixer", "INB1 Switch", "INB1 Input"},
{"Right ADC Mixer", "INB2 Switch", "INB2 Input"},
/* Inputs */
{"ADCL", NULL, "Left ADC Mixer"},
{"ADCR", NULL, "Right ADC Mixer"},
{"INA1 Input", NULL, "INA1"},
{"INA2 Input", NULL, "INA2"},
{"INB1 Input", NULL, "INB1"},
{"INB2 Input", NULL, "INB2"},
{"MIC1 Input", NULL, "MIC1"},
{"MIC2 Input", NULL, "MIC2"},
};
/* codec mclk clock divider coefficients */
static const struct {
u32 rate;
u8 sr;
} rate_table[] = {
{8000, 0x10},
{11025, 0x20},
{16000, 0x30},
{22050, 0x40},
{24000, 0x50},
{32000, 0x60},
{44100, 0x70},
{48000, 0x80},
{88200, 0x90},
{96000, 0xA0},
};
static inline int rate_value(int rate, u8 *value)
{
int i;
for (i = 0; i < ARRAY_SIZE(rate_table); i++) {
if (rate_table[i].rate >= rate) {
*value = rate_table[i].sr;
return 0;
}
}
*value = rate_table[0].sr;
return -EINVAL;
}
static int max98088_dai1_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct snd_soc_codec *codec = dai->codec;
struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec);
struct max98088_cdata *cdata;
unsigned long long ni;
unsigned int rate;
u8 regval;
cdata = &max98088->dai[0];
rate = params_rate(params);
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S16_LE:
snd_soc_update_bits(codec, M98088_REG_14_DAI1_FORMAT,
M98088_DAI_WS, 0);
break;
case SNDRV_PCM_FORMAT_S24_LE:
snd_soc_update_bits(codec, M98088_REG_14_DAI1_FORMAT,
M98088_DAI_WS, M98088_DAI_WS);
break;
default:
return -EINVAL;
}
snd_soc_update_bits(codec, M98088_REG_51_PWR_SYS, M98088_SHDNRUN, 0);
if (rate_value(rate, ®val))
return -EINVAL;
snd_soc_update_bits(codec, M98088_REG_11_DAI1_CLKMODE,
M98088_CLKMODE_MASK, regval);
cdata->rate = rate;
/* Configure NI when operating as master */
if (snd_soc_read(codec, M98088_REG_14_DAI1_FORMAT)
& M98088_DAI_MAS) {
if (max98088->sysclk == 0) {
dev_err(codec->dev, "Invalid system clock frequency\n");
return -EINVAL;
}
ni = 65536ULL * (rate < 50000 ? 96ULL : 48ULL)
* (unsigned long long int)rate;
do_div(ni, (unsigned long long int)max98088->sysclk);
snd_soc_write(codec, M98088_REG_12_DAI1_CLKCFG_HI,
(ni >> 8) & 0x7F);
snd_soc_write(codec, M98088_REG_13_DAI1_CLKCFG_LO,
ni & 0xFF);
}
/* Update sample rate mode */
if (rate < 50000)
snd_soc_update_bits(codec, M98088_REG_18_DAI1_FILTERS,
M98088_DAI_DHF, 0);
else
snd_soc_update_bits(codec, M98088_REG_18_DAI1_FILTERS,
M98088_DAI_DHF, M98088_DAI_DHF);
snd_soc_update_bits(codec, M98088_REG_51_PWR_SYS, M98088_SHDNRUN,
M98088_SHDNRUN);
return 0;
}
static int max98088_dai2_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct snd_soc_codec *codec = dai->codec;
struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec);
struct max98088_cdata *cdata;
unsigned long long ni;
unsigned int rate;
u8 regval;
cdata = &max98088->dai[1];
rate = params_rate(params);
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S16_LE:
snd_soc_update_bits(codec, M98088_REG_1C_DAI2_FORMAT,
M98088_DAI_WS, 0);
break;
case SNDRV_PCM_FORMAT_S24_LE:
snd_soc_update_bits(codec, M98088_REG_1C_DAI2_FORMAT,
M98088_DAI_WS, M98088_DAI_WS);
break;
default:
return -EINVAL;
}
snd_soc_update_bits(codec, M98088_REG_51_PWR_SYS, M98088_SHDNRUN, 0);
if (rate_value(rate, ®val))
return -EINVAL;
snd_soc_update_bits(codec, M98088_REG_19_DAI2_CLKMODE,
M98088_CLKMODE_MASK, regval);
cdata->rate = rate;
/* Configure NI when operating as master */
if (snd_soc_read(codec, M98088_REG_1C_DAI2_FORMAT)
& M98088_DAI_MAS) {
if (max98088->sysclk == 0) {
dev_err(codec->dev, "Invalid system clock frequency\n");
return -EINVAL;
}
ni = 65536ULL * (rate < 50000 ? 96ULL : 48ULL)
* (unsigned long long int)rate;
do_div(ni, (unsigned long long int)max98088->sysclk);
snd_soc_write(codec, M98088_REG_1A_DAI2_CLKCFG_HI,
(ni >> 8) & 0x7F);
snd_soc_write(codec, M98088_REG_1B_DAI2_CLKCFG_LO,
ni & 0xFF);
}
/* Update sample rate mode */
if (rate < 50000)
snd_soc_update_bits(codec, M98088_REG_20_DAI2_FILTERS,
M98088_DAI_DHF, 0);
else
snd_soc_update_bits(codec, M98088_REG_20_DAI2_FILTERS,
M98088_DAI_DHF, M98088_DAI_DHF);
snd_soc_update_bits(codec, M98088_REG_51_PWR_SYS, M98088_SHDNRUN,
M98088_SHDNRUN);
return 0;
}
static int max98088_dai_set_sysclk(struct snd_soc_dai *dai,
int clk_id, unsigned int freq, int dir)
{
struct snd_soc_codec *codec = dai->codec;
struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec);
/* Requested clock frequency is already setup */
if (freq == max98088->sysclk)
return 0;
/* Setup clocks for slave mode, and using the PLL
* PSCLK = 0x01 (when master clk is 10MHz to 20MHz)
* 0x02 (when master clk is 20MHz to 30MHz)..
*/
if ((freq >= 10000000) && (freq < 20000000)) {
snd_soc_write(codec, M98088_REG_10_SYS_CLK, 0x10);
} else if ((freq >= 20000000) && (freq < 30000000)) {
snd_soc_write(codec, M98088_REG_10_SYS_CLK, 0x20);
} else {
dev_err(codec->dev, "Invalid master clock frequency\n");
return -EINVAL;
}
if (snd_soc_read(codec, M98088_REG_51_PWR_SYS) & M98088_SHDNRUN) {
snd_soc_update_bits(codec, M98088_REG_51_PWR_SYS,
M98088_SHDNRUN, 0);
snd_soc_update_bits(codec, M98088_REG_51_PWR_SYS,
M98088_SHDNRUN, M98088_SHDNRUN);
}
dev_dbg(dai->dev, "Clock source is %d at %uHz\n", clk_id, freq);
max98088->sysclk = freq;
return 0;
}
static int max98088_dai1_set_fmt(struct snd_soc_dai *codec_dai,
unsigned int fmt)
{
struct snd_soc_codec *codec = codec_dai->codec;
struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec);
struct max98088_cdata *cdata;
u8 reg15val;
u8 reg14val = 0;
cdata = &max98088->dai[0];
if (fmt != cdata->fmt) {
cdata->fmt = fmt;
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBS_CFS:
/* Slave mode PLL */
snd_soc_write(codec, M98088_REG_12_DAI1_CLKCFG_HI,
0x80);
snd_soc_write(codec, M98088_REG_13_DAI1_CLKCFG_LO,
0x00);
break;
case SND_SOC_DAIFMT_CBM_CFM:
/* Set to master mode */
reg14val |= M98088_DAI_MAS;
break;
case SND_SOC_DAIFMT_CBS_CFM:
case SND_SOC_DAIFMT_CBM_CFS:
default:
dev_err(codec->dev, "Clock mode unsupported");
return -EINVAL;
}
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_I2S:
reg14val |= M98088_DAI_DLY;
break;
case SND_SOC_DAIFMT_LEFT_J:
break;
default:
return -EINVAL;
}
switch (fmt & SND_SOC_DAIFMT_INV_MASK) {
case SND_SOC_DAIFMT_NB_NF:
break;
case SND_SOC_DAIFMT_NB_IF:
reg14val |= M98088_DAI_WCI;
break;
case SND_SOC_DAIFMT_IB_NF:
reg14val |= M98088_DAI_BCI;
break;
case SND_SOC_DAIFMT_IB_IF:
reg14val |= M98088_DAI_BCI|M98088_DAI_WCI;
break;
default:
return -EINVAL;
}
snd_soc_update_bits(codec, M98088_REG_14_DAI1_FORMAT,
M98088_DAI_MAS | M98088_DAI_DLY | M98088_DAI_BCI |
M98088_DAI_WCI, reg14val);
reg15val = M98088_DAI_BSEL64;
if (max98088->digmic)
reg15val |= M98088_DAI_OSR64;
snd_soc_write(codec, M98088_REG_15_DAI1_CLOCK, reg15val);
}
return 0;
}
static int max98088_dai2_set_fmt(struct snd_soc_dai *codec_dai,
unsigned int fmt)
{
struct snd_soc_codec *codec = codec_dai->codec;
struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec);
struct max98088_cdata *cdata;
u8 reg1Cval = 0;
cdata = &max98088->dai[1];
if (fmt != cdata->fmt) {
cdata->fmt = fmt;
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBS_CFS:
/* Slave mode PLL */
snd_soc_write(codec, M98088_REG_1A_DAI2_CLKCFG_HI,
0x80);
snd_soc_write(codec, M98088_REG_1B_DAI2_CLKCFG_LO,
0x00);
break;
case SND_SOC_DAIFMT_CBM_CFM:
/* Set to master mode */
reg1Cval |= M98088_DAI_MAS;
break;
case SND_SOC_DAIFMT_CBS_CFM:
case SND_SOC_DAIFMT_CBM_CFS:
default:
dev_err(codec->dev, "Clock mode unsupported");
return -EINVAL;
}
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_I2S:
reg1Cval |= M98088_DAI_DLY;
break;
case SND_SOC_DAIFMT_LEFT_J:
break;
default:
return -EINVAL;
}
switch (fmt & SND_SOC_DAIFMT_INV_MASK) {
case SND_SOC_DAIFMT_NB_NF:
break;
case SND_SOC_DAIFMT_NB_IF:
reg1Cval |= M98088_DAI_WCI;
break;
case SND_SOC_DAIFMT_IB_NF:
reg1Cval |= M98088_DAI_BCI;
break;
case SND_SOC_DAIFMT_IB_IF:
reg1Cval |= M98088_DAI_BCI|M98088_DAI_WCI;
break;
default:
return -EINVAL;
}
snd_soc_update_bits(codec, M98088_REG_1C_DAI2_FORMAT,
M98088_DAI_MAS | M98088_DAI_DLY | M98088_DAI_BCI |
M98088_DAI_WCI, reg1Cval);
snd_soc_write(codec, M98088_REG_1D_DAI2_CLOCK,
M98088_DAI_BSEL64);
}
return 0;
}
static int max98088_dai1_digital_mute(struct snd_soc_dai *codec_dai, int mute)
{
struct snd_soc_codec *codec = codec_dai->codec;
int reg;
if (mute)
reg = M98088_DAI_MUTE;
else
reg = 0;
snd_soc_update_bits(codec, M98088_REG_2F_LVL_DAI1_PLAY,
M98088_DAI_MUTE_MASK, reg);
return 0;
}
static int max98088_dai2_digital_mute(struct snd_soc_dai *codec_dai, int mute)
{
struct snd_soc_codec *codec = codec_dai->codec;
int reg;
if (mute)
reg = M98088_DAI_MUTE;
else
reg = 0;
snd_soc_update_bits(codec, M98088_REG_31_LVL_DAI2_PLAY,
M98088_DAI_MUTE_MASK, reg);
return 0;
}
static void max98088_sync_cache(struct snd_soc_codec *codec)
{
u16 *reg_cache = codec->reg_cache;
int i;
if (!codec->cache_sync)
return;
codec->cache_only = 0;
/* write back cached values if they're writeable and
* different from the hardware default.
*/
for (i = 1; i < codec->driver->reg_cache_size; i++) {
if (!max98088_access[i].writable)
continue;
if (reg_cache[i] == max98088_reg[i])
continue;
snd_soc_write(codec, i, reg_cache[i]);
}
codec->cache_sync = 0;
}
static int max98088_set_bias_level(struct snd_soc_codec *codec,
enum snd_soc_bias_level level)
{
switch (level) {
case SND_SOC_BIAS_ON:
break;
case SND_SOC_BIAS_PREPARE:
break;
case SND_SOC_BIAS_STANDBY:
if (codec->dapm.bias_level == SND_SOC_BIAS_OFF)
max98088_sync_cache(codec);
snd_soc_update_bits(codec, M98088_REG_4C_PWR_EN_IN,
M98088_MBEN, M98088_MBEN);
break;
case SND_SOC_BIAS_OFF:
snd_soc_update_bits(codec, M98088_REG_4C_PWR_EN_IN,
M98088_MBEN, 0);
codec->cache_sync = 1;
break;
}
codec->dapm.bias_level = level;
return 0;
}
#define MAX98088_RATES SNDRV_PCM_RATE_8000_96000
#define MAX98088_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S24_LE)
static const struct snd_soc_dai_ops max98088_dai1_ops = {
.set_sysclk = max98088_dai_set_sysclk,
.set_fmt = max98088_dai1_set_fmt,
.hw_params = max98088_dai1_hw_params,
.digital_mute = max98088_dai1_digital_mute,
};
static const struct snd_soc_dai_ops max98088_dai2_ops = {
.set_sysclk = max98088_dai_set_sysclk,
.set_fmt = max98088_dai2_set_fmt,
.hw_params = max98088_dai2_hw_params,
.digital_mute = max98088_dai2_digital_mute,
};
static struct snd_soc_dai_driver max98088_dai[] = {
{
.name = "HiFi",
.playback = {
.stream_name = "HiFi Playback",
.channels_min = 1,
.channels_max = 2,
.rates = MAX98088_RATES,
.formats = MAX98088_FORMATS,
},
.capture = {
.stream_name = "HiFi Capture",
.channels_min = 1,
.channels_max = 2,
.rates = MAX98088_RATES,
.formats = MAX98088_FORMATS,
},
.ops = &max98088_dai1_ops,
},
{
.name = "Aux",
.playback = {
.stream_name = "Aux Playback",
.channels_min = 1,
.channels_max = 2,
.rates = MAX98088_RATES,
.formats = MAX98088_FORMATS,
},
.ops = &max98088_dai2_ops,
}
};
static const char *eq_mode_name[] = {"EQ1 Mode", "EQ2 Mode"};
static int max98088_get_channel(struct snd_soc_codec *codec, const char *name)
{
int i;
for (i = 0; i < ARRAY_SIZE(eq_mode_name); i++)
if (strcmp(name, eq_mode_name[i]) == 0)
return i;
/* Shouldn't happen */
dev_err(codec->dev, "Bad EQ channel name '%s'\n", name);
return -EINVAL;
}
static void max98088_setup_eq1(struct snd_soc_codec *codec)
{
struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec);
struct max98088_pdata *pdata = max98088->pdata;
struct max98088_eq_cfg *coef_set;
int best, best_val, save, i, sel, fs;
struct max98088_cdata *cdata;
cdata = &max98088->dai[0];
if (!pdata || !max98088->eq_textcnt)
return;
/* Find the selected configuration with nearest sample rate */
fs = cdata->rate;
sel = cdata->eq_sel;
best = 0;
best_val = INT_MAX;
for (i = 0; i < pdata->eq_cfgcnt; i++) {
if (strcmp(pdata->eq_cfg[i].name, max98088->eq_texts[sel]) == 0 &&
abs(pdata->eq_cfg[i].rate - fs) < best_val) {
best = i;
best_val = abs(pdata->eq_cfg[i].rate - fs);
}
}
dev_dbg(codec->dev, "Selected %s/%dHz for %dHz sample rate\n",
pdata->eq_cfg[best].name,
pdata->eq_cfg[best].rate, fs);
/* Disable EQ while configuring, and save current on/off state */
save = snd_soc_read(codec, M98088_REG_49_CFG_LEVEL);
snd_soc_update_bits(codec, M98088_REG_49_CFG_LEVEL, M98088_EQ1EN, 0);
coef_set = &pdata->eq_cfg[sel];
m98088_eq_band(codec, 0, 0, coef_set->band1);
m98088_eq_band(codec, 0, 1, coef_set->band2);
m98088_eq_band(codec, 0, 2, coef_set->band3);
m98088_eq_band(codec, 0, 3, coef_set->band4);
m98088_eq_band(codec, 0, 4, coef_set->band5);
/* Restore the original on/off state */
snd_soc_update_bits(codec, M98088_REG_49_CFG_LEVEL, M98088_EQ1EN, save);
}
static void max98088_setup_eq2(struct snd_soc_codec *codec)
{
struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec);
struct max98088_pdata *pdata = max98088->pdata;
struct max98088_eq_cfg *coef_set;
int best, best_val, save, i, sel, fs;
struct max98088_cdata *cdata;
cdata = &max98088->dai[1];
if (!pdata || !max98088->eq_textcnt)
return;
/* Find the selected configuration with nearest sample rate */
fs = cdata->rate;
sel = cdata->eq_sel;
best = 0;
best_val = INT_MAX;
for (i = 0; i < pdata->eq_cfgcnt; i++) {
if (strcmp(pdata->eq_cfg[i].name, max98088->eq_texts[sel]) == 0 &&
abs(pdata->eq_cfg[i].rate - fs) < best_val) {
best = i;
best_val = abs(pdata->eq_cfg[i].rate - fs);
}
}
dev_dbg(codec->dev, "Selected %s/%dHz for %dHz sample rate\n",
pdata->eq_cfg[best].name,
pdata->eq_cfg[best].rate, fs);
/* Disable EQ while configuring, and save current on/off state */
save = snd_soc_read(codec, M98088_REG_49_CFG_LEVEL);
snd_soc_update_bits(codec, M98088_REG_49_CFG_LEVEL, M98088_EQ2EN, 0);
coef_set = &pdata->eq_cfg[sel];
m98088_eq_band(codec, 1, 0, coef_set->band1);
m98088_eq_band(codec, 1, 1, coef_set->band2);
m98088_eq_band(codec, 1, 2, coef_set->band3);
m98088_eq_band(codec, 1, 3, coef_set->band4);
m98088_eq_band(codec, 1, 4, coef_set->band5);
/* Restore the original on/off state */
snd_soc_update_bits(codec, M98088_REG_49_CFG_LEVEL, M98088_EQ2EN,
save);
}
static int max98088_put_eq_enum(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec);
struct max98088_pdata *pdata = max98088->pdata;
int channel = max98088_get_channel(codec, kcontrol->id.name);
struct max98088_cdata *cdata;
int sel = ucontrol->value.integer.value[0];
if (channel < 0)
return channel;
cdata = &max98088->dai[channel];
if (sel >= pdata->eq_cfgcnt)
return -EINVAL;
cdata->eq_sel = sel;
switch (channel) {
case 0:
max98088_setup_eq1(codec);
break;
case 1:
max98088_setup_eq2(codec);
break;
}
return 0;
}
static int max98088_get_eq_enum(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec);
int channel = max98088_get_channel(codec, kcontrol->id.name);
struct max98088_cdata *cdata;
if (channel < 0)
return channel;
cdata = &max98088->dai[channel];
ucontrol->value.enumerated.item[0] = cdata->eq_sel;
return 0;
}
static void max98088_handle_eq_pdata(struct snd_soc_codec *codec)
{
struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec);
struct max98088_pdata *pdata = max98088->pdata;
struct max98088_eq_cfg *cfg;
unsigned int cfgcnt;
int i, j;
const char **t;
int ret;
struct snd_kcontrol_new controls[] = {
SOC_ENUM_EXT((char *)eq_mode_name[0],
max98088->eq_enum,
max98088_get_eq_enum,
max98088_put_eq_enum),
SOC_ENUM_EXT((char *)eq_mode_name[1],
max98088->eq_enum,
max98088_get_eq_enum,
max98088_put_eq_enum),
};
BUILD_BUG_ON(ARRAY_SIZE(controls) != ARRAY_SIZE(eq_mode_name));
cfg = pdata->eq_cfg;
cfgcnt = pdata->eq_cfgcnt;
/* Setup an array of texts for the equalizer enum.
* This is based on Mark Brown's equalizer driver code.
*/
max98088->eq_textcnt = 0;
max98088->eq_texts = NULL;
for (i = 0; i < cfgcnt; i++) {
for (j = 0; j < max98088->eq_textcnt; j++) {
if (strcmp(cfg[i].name, max98088->eq_texts[j]) == 0)
break;
}
if (j != max98088->eq_textcnt)
continue;
/* Expand the array */
t = krealloc(max98088->eq_texts,
sizeof(char *) * (max98088->eq_textcnt + 1),
GFP_KERNEL);
if (t == NULL)
continue;
/* Store the new entry */
t[max98088->eq_textcnt] = cfg[i].name;
max98088->eq_textcnt++;
max98088->eq_texts = t;
}
/* Now point the soc_enum to .texts array items */
max98088->eq_enum.texts = max98088->eq_texts;
max98088->eq_enum.max = max98088->eq_textcnt;
ret = snd_soc_add_codec_controls(codec, controls, ARRAY_SIZE(controls));
if (ret != 0)
dev_err(codec->dev, "Failed to add EQ control: %d\n", ret);
}
static void max98088_handle_pdata(struct snd_soc_codec *codec)
{
struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec);
struct max98088_pdata *pdata = max98088->pdata;
u8 regval = 0;
if (!pdata) {
dev_dbg(codec->dev, "No platform data\n");
return;
}
/* Configure mic for analog/digital mic mode */
if (pdata->digmic_left_mode)
regval |= M98088_DIGMIC_L;
if (pdata->digmic_right_mode)
regval |= M98088_DIGMIC_R;
max98088->digmic = (regval ? 1 : 0);
snd_soc_write(codec, M98088_REG_48_CFG_MIC, regval);
/* Configure receiver output */
regval = ((pdata->receiver_mode) ? M98088_REC_LINEMODE : 0);
snd_soc_update_bits(codec, M98088_REG_2A_MIC_REC_CNTL,
M98088_REC_LINEMODE_MASK, regval);
/* Configure equalizers */
if (pdata->eq_cfgcnt)
max98088_handle_eq_pdata(codec);
}
#ifdef CONFIG_PM
static int max98088_suspend(struct snd_soc_codec *codec)
{
max98088_set_bias_level(codec, SND_SOC_BIAS_OFF);
return 0;
}
static int max98088_resume(struct snd_soc_codec *codec)
{
max98088_set_bias_level(codec, SND_SOC_BIAS_STANDBY);
return 0;
}
#else
#define max98088_suspend NULL
#define max98088_resume NULL
#endif
static int max98088_probe(struct snd_soc_codec *codec)
{
struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec);
struct max98088_cdata *cdata;
int ret = 0;
codec->cache_sync = 1;
ret = snd_soc_codec_set_cache_io(codec, 8, 8, SND_SOC_I2C);
if (ret != 0) {
dev_err(codec->dev, "Failed to set cache I/O: %d\n", ret);
return ret;
}
/* initialize private data */
max98088->sysclk = (unsigned)-1;
max98088->eq_textcnt = 0;
cdata = &max98088->dai[0];
cdata->rate = (unsigned)-1;
cdata->fmt = (unsigned)-1;
cdata->eq_sel = 0;
cdata = &max98088->dai[1];
cdata->rate = (unsigned)-1;
cdata->fmt = (unsigned)-1;
cdata->eq_sel = 0;
max98088->ina_state = 0;
max98088->inb_state = 0;
max98088->ex_mode = 0;
max98088->digmic = 0;
max98088->mic1pre = 0;
max98088->mic2pre = 0;
ret = snd_soc_read(codec, M98088_REG_FF_REV_ID);
if (ret < 0) {
dev_err(codec->dev, "Failed to read device revision: %d\n",
ret);
goto err_access;
}
dev_info(codec->dev, "revision %c\n", ret + 'A');
snd_soc_write(codec, M98088_REG_51_PWR_SYS, M98088_PWRSV);
/* initialize registers cache to hardware default */
max98088_set_bias_level(codec, SND_SOC_BIAS_STANDBY);
snd_soc_write(codec, M98088_REG_0F_IRQ_ENABLE, 0x00);
snd_soc_write(codec, M98088_REG_22_MIX_DAC,
M98088_DAI1L_TO_DACL|M98088_DAI2L_TO_DACL|
M98088_DAI1R_TO_DACR|M98088_DAI2R_TO_DACR);
snd_soc_write(codec, M98088_REG_4E_BIAS_CNTL, 0xF0);
snd_soc_write(codec, M98088_REG_50_DAC_BIAS2, 0x0F);
snd_soc_write(codec, M98088_REG_16_DAI1_IOCFG,
M98088_S1NORMAL|M98088_SDATA);
snd_soc_write(codec, M98088_REG_1E_DAI2_IOCFG,
M98088_S2NORMAL|M98088_SDATA);
max98088_handle_pdata(codec);
snd_soc_add_codec_controls(codec, max98088_snd_controls,
ARRAY_SIZE(max98088_snd_controls));
err_access:
return ret;
}
static int max98088_remove(struct snd_soc_codec *codec)
{
struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec);
max98088_set_bias_level(codec, SND_SOC_BIAS_OFF);
kfree(max98088->eq_texts);
return 0;
}
static struct snd_soc_codec_driver soc_codec_dev_max98088 = {
.probe = max98088_probe,
.remove = max98088_remove,
.suspend = max98088_suspend,
.resume = max98088_resume,
.set_bias_level = max98088_set_bias_level,
.reg_cache_size = ARRAY_SIZE(max98088_reg),
.reg_word_size = sizeof(u8),
.reg_cache_default = max98088_reg,
.volatile_register = max98088_volatile_register,
.dapm_widgets = max98088_dapm_widgets,
.num_dapm_widgets = ARRAY_SIZE(max98088_dapm_widgets),
.dapm_routes = max98088_audio_map,
.num_dapm_routes = ARRAY_SIZE(max98088_audio_map),
};
static int max98088_i2c_probe(struct i2c_client *i2c,
const struct i2c_device_id *id)
{
struct max98088_priv *max98088;
int ret;
max98088 = devm_kzalloc(&i2c->dev, sizeof(struct max98088_priv),
GFP_KERNEL);
if (max98088 == NULL)
return -ENOMEM;
max98088->devtype = id->driver_data;
i2c_set_clientdata(i2c, max98088);
max98088->pdata = i2c->dev.platform_data;
ret = snd_soc_register_codec(&i2c->dev,
&soc_codec_dev_max98088, &max98088_dai[0], 2);
return ret;
}
static int __devexit max98088_i2c_remove(struct i2c_client *client)
{
snd_soc_unregister_codec(&client->dev);
return 0;
}
static const struct i2c_device_id max98088_i2c_id[] = {
{ "max98088", MAX98088 },
{ "max98089", MAX98089 },
{ }
};
MODULE_DEVICE_TABLE(i2c, max98088_i2c_id);
static struct i2c_driver max98088_i2c_driver = {
.driver = {
.name = "max98088",
.owner = THIS_MODULE,
},
.probe = max98088_i2c_probe,
.remove = __devexit_p(max98088_i2c_remove),
.id_table = max98088_i2c_id,
};
static int __init max98088_init(void)
{
int ret;
ret = i2c_add_driver(&max98088_i2c_driver);
if (ret)
pr_err("Failed to register max98088 I2C driver: %d\n", ret);
return ret;
}
module_init(max98088_init);
static void __exit max98088_exit(void)
{
i2c_del_driver(&max98088_i2c_driver);
}
module_exit(max98088_exit);
MODULE_DESCRIPTION("ALSA SoC MAX98088 driver");
MODULE_AUTHOR("Peter Hsiang, Jesse Marroquin");
MODULE_LICENSE("GPL");
| gpl-2.0 |
CYB0RG97/kernel_nvidia_s8515 | arch/c6x/kernel/soc.c | 4465 | 2077 | /*
* Miscellaneous SoC-specific hooks.
*
* Copyright (C) 2011 Texas Instruments Incorporated
* Author: Mark Salter <msalter@redhat.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/module.h>
#include <linux/ctype.h>
#include <linux/etherdevice.h>
#include <asm/setup.h>
#include <asm/soc.h>
struct soc_ops soc_ops;
int soc_get_exception(void)
{
if (!soc_ops.get_exception)
return -1;
return soc_ops.get_exception();
}
void soc_assert_event(unsigned int evt)
{
if (soc_ops.assert_event)
soc_ops.assert_event(evt);
}
static u8 cmdline_mac[6];
static int __init get_mac_addr_from_cmdline(char *str)
{
int count, i, val;
for (count = 0; count < 6 && *str; count++, str += 3) {
if (!isxdigit(str[0]) || !isxdigit(str[1]))
return 0;
if (str[2] != ((count < 5) ? ':' : '\0'))
return 0;
for (i = 0, val = 0; i < 2; i++) {
val = val << 4;
val |= isdigit(str[i]) ?
str[i] - '0' : toupper(str[i]) - 'A' + 10;
}
cmdline_mac[count] = val;
}
return 1;
}
__setup("emac_addr=", get_mac_addr_from_cmdline);
/*
* Setup the MAC address for SoC ethernet devices.
*
* Before calling this function, the ethernet driver will have
* initialized the addr with local-mac-address from the device
* tree (if found). Allow command line to override, but not
* the fused address.
*/
int soc_mac_addr(unsigned int index, u8 *addr)
{
int i, have_dt_mac = 0, have_cmdline_mac = 0, have_fuse_mac = 0;
for (i = 0; i < 6; i++) {
if (cmdline_mac[i])
have_cmdline_mac = 1;
if (c6x_fuse_mac[i])
have_fuse_mac = 1;
if (addr[i])
have_dt_mac = 1;
}
/* cmdline overrides all */
if (have_cmdline_mac)
memcpy(addr, cmdline_mac, 6);
else if (!have_dt_mac) {
if (have_fuse_mac)
memcpy(addr, c6x_fuse_mac, 6);
else
random_ether_addr(addr);
}
/* adjust for specific EMAC device */
addr[5] += index * c6x_num_cores;
return 1;
}
EXPORT_SYMBOL_GPL(soc_mac_addr);
| gpl-2.0 |
sub-b/android_kernel_samsung_matissewifi-old | fs/jfs/jfs_txnmgr.c | 4977 | 77277 | /*
* Copyright (C) International Business Machines Corp., 2000-2005
* Portions Copyright (C) Christoph Hellwig, 2001-2002
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* jfs_txnmgr.c: transaction manager
*
* notes:
* transaction starts with txBegin() and ends with txCommit()
* or txAbort().
*
* tlock is acquired at the time of update;
* (obviate scan at commit time for xtree and dtree)
* tlock and mp points to each other;
* (no hashlist for mp -> tlock).
*
* special cases:
* tlock on in-memory inode:
* in-place tlock in the in-memory inode itself;
* converted to page lock by iWrite() at commit time.
*
* tlock during write()/mmap() under anonymous transaction (tid = 0):
* transferred (?) to transaction at commit time.
*
* use the page itself to update allocation maps
* (obviate intermediate replication of allocation/deallocation data)
* hold on to mp+lock thru update of maps
*/
#include <linux/fs.h>
#include <linux/vmalloc.h>
#include <linux/completion.h>
#include <linux/freezer.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kthread.h>
#include <linux/seq_file.h>
#include "jfs_incore.h"
#include "jfs_inode.h"
#include "jfs_filsys.h"
#include "jfs_metapage.h"
#include "jfs_dinode.h"
#include "jfs_imap.h"
#include "jfs_dmap.h"
#include "jfs_superblock.h"
#include "jfs_debug.h"
/*
* transaction management structures
*/
static struct {
int freetid; /* index of a free tid structure */
int freelock; /* index first free lock word */
wait_queue_head_t freewait; /* eventlist of free tblock */
wait_queue_head_t freelockwait; /* eventlist of free tlock */
wait_queue_head_t lowlockwait; /* eventlist of ample tlocks */
int tlocksInUse; /* Number of tlocks in use */
spinlock_t LazyLock; /* synchronize sync_queue & unlock_queue */
/* struct tblock *sync_queue; * Transactions waiting for data sync */
struct list_head unlock_queue; /* Txns waiting to be released */
struct list_head anon_list; /* inodes having anonymous txns */
struct list_head anon_list2; /* inodes having anonymous txns
that couldn't be sync'ed */
} TxAnchor;
int jfs_tlocks_low; /* Indicates low number of available tlocks */
#ifdef CONFIG_JFS_STATISTICS
static struct {
uint txBegin;
uint txBegin_barrier;
uint txBegin_lockslow;
uint txBegin_freetid;
uint txBeginAnon;
uint txBeginAnon_barrier;
uint txBeginAnon_lockslow;
uint txLockAlloc;
uint txLockAlloc_freelock;
} TxStat;
#endif
static int nTxBlock = -1; /* number of transaction blocks */
module_param(nTxBlock, int, 0);
MODULE_PARM_DESC(nTxBlock,
"Number of transaction blocks (max:65536)");
static int nTxLock = -1; /* number of transaction locks */
module_param(nTxLock, int, 0);
MODULE_PARM_DESC(nTxLock,
"Number of transaction locks (max:65536)");
struct tblock *TxBlock; /* transaction block table */
static int TxLockLWM; /* Low water mark for number of txLocks used */
static int TxLockHWM; /* High water mark for number of txLocks used */
static int TxLockVHWM; /* Very High water mark */
struct tlock *TxLock; /* transaction lock table */
/*
* transaction management lock
*/
static DEFINE_SPINLOCK(jfsTxnLock);
#define TXN_LOCK() spin_lock(&jfsTxnLock)
#define TXN_UNLOCK() spin_unlock(&jfsTxnLock)
#define LAZY_LOCK_INIT() spin_lock_init(&TxAnchor.LazyLock);
#define LAZY_LOCK(flags) spin_lock_irqsave(&TxAnchor.LazyLock, flags)
#define LAZY_UNLOCK(flags) spin_unlock_irqrestore(&TxAnchor.LazyLock, flags)
static DECLARE_WAIT_QUEUE_HEAD(jfs_commit_thread_wait);
static int jfs_commit_thread_waking;
/*
* Retry logic exist outside these macros to protect from spurrious wakeups.
*/
static inline void TXN_SLEEP_DROP_LOCK(wait_queue_head_t * event)
{
DECLARE_WAITQUEUE(wait, current);
add_wait_queue(event, &wait);
set_current_state(TASK_UNINTERRUPTIBLE);
TXN_UNLOCK();
io_schedule();
__set_current_state(TASK_RUNNING);
remove_wait_queue(event, &wait);
}
#define TXN_SLEEP(event)\
{\
TXN_SLEEP_DROP_LOCK(event);\
TXN_LOCK();\
}
#define TXN_WAKEUP(event) wake_up_all(event)
/*
* statistics
*/
static struct {
tid_t maxtid; /* 4: biggest tid ever used */
lid_t maxlid; /* 4: biggest lid ever used */
int ntid; /* 4: # of transactions performed */
int nlid; /* 4: # of tlocks acquired */
int waitlock; /* 4: # of tlock wait */
} stattx;
/*
* forward references
*/
static int diLog(struct jfs_log * log, struct tblock * tblk, struct lrd * lrd,
struct tlock * tlck, struct commit * cd);
static int dataLog(struct jfs_log * log, struct tblock * tblk, struct lrd * lrd,
struct tlock * tlck);
static void dtLog(struct jfs_log * log, struct tblock * tblk, struct lrd * lrd,
struct tlock * tlck);
static void mapLog(struct jfs_log * log, struct tblock * tblk, struct lrd * lrd,
struct tlock * tlck);
static void txAllocPMap(struct inode *ip, struct maplock * maplock,
struct tblock * tblk);
static void txForce(struct tblock * tblk);
static int txLog(struct jfs_log * log, struct tblock * tblk,
struct commit * cd);
static void txUpdateMap(struct tblock * tblk);
static void txRelease(struct tblock * tblk);
static void xtLog(struct jfs_log * log, struct tblock * tblk, struct lrd * lrd,
struct tlock * tlck);
static void LogSyncRelease(struct metapage * mp);
/*
* transaction block/lock management
* ---------------------------------
*/
/*
* Get a transaction lock from the free list. If the number in use is
* greater than the high water mark, wake up the sync daemon. This should
* free some anonymous transaction locks. (TXN_LOCK must be held.)
*/
static lid_t txLockAlloc(void)
{
lid_t lid;
INCREMENT(TxStat.txLockAlloc);
if (!TxAnchor.freelock) {
INCREMENT(TxStat.txLockAlloc_freelock);
}
while (!(lid = TxAnchor.freelock))
TXN_SLEEP(&TxAnchor.freelockwait);
TxAnchor.freelock = TxLock[lid].next;
HIGHWATERMARK(stattx.maxlid, lid);
if ((++TxAnchor.tlocksInUse > TxLockHWM) && (jfs_tlocks_low == 0)) {
jfs_info("txLockAlloc tlocks low");
jfs_tlocks_low = 1;
wake_up_process(jfsSyncThread);
}
return lid;
}
static void txLockFree(lid_t lid)
{
TxLock[lid].tid = 0;
TxLock[lid].next = TxAnchor.freelock;
TxAnchor.freelock = lid;
TxAnchor.tlocksInUse--;
if (jfs_tlocks_low && (TxAnchor.tlocksInUse < TxLockLWM)) {
jfs_info("txLockFree jfs_tlocks_low no more");
jfs_tlocks_low = 0;
TXN_WAKEUP(&TxAnchor.lowlockwait);
}
TXN_WAKEUP(&TxAnchor.freelockwait);
}
/*
* NAME: txInit()
*
* FUNCTION: initialize transaction management structures
*
* RETURN:
*
* serialization: single thread at jfs_init()
*/
int txInit(void)
{
int k, size;
struct sysinfo si;
/* Set defaults for nTxLock and nTxBlock if unset */
if (nTxLock == -1) {
if (nTxBlock == -1) {
/* Base default on memory size */
si_meminfo(&si);
if (si.totalram > (256 * 1024)) /* 1 GB */
nTxLock = 64 * 1024;
else
nTxLock = si.totalram >> 2;
} else if (nTxBlock > (8 * 1024))
nTxLock = 64 * 1024;
else
nTxLock = nTxBlock << 3;
}
if (nTxBlock == -1)
nTxBlock = nTxLock >> 3;
/* Verify tunable parameters */
if (nTxBlock < 16)
nTxBlock = 16; /* No one should set it this low */
if (nTxBlock > 65536)
nTxBlock = 65536;
if (nTxLock < 256)
nTxLock = 256; /* No one should set it this low */
if (nTxLock > 65536)
nTxLock = 65536;
printk(KERN_INFO "JFS: nTxBlock = %d, nTxLock = %d\n",
nTxBlock, nTxLock);
/*
* initialize transaction block (tblock) table
*
* transaction id (tid) = tblock index
* tid = 0 is reserved.
*/
TxLockLWM = (nTxLock * 4) / 10;
TxLockHWM = (nTxLock * 7) / 10;
TxLockVHWM = (nTxLock * 8) / 10;
size = sizeof(struct tblock) * nTxBlock;
TxBlock = vmalloc(size);
if (TxBlock == NULL)
return -ENOMEM;
for (k = 1; k < nTxBlock - 1; k++) {
TxBlock[k].next = k + 1;
init_waitqueue_head(&TxBlock[k].gcwait);
init_waitqueue_head(&TxBlock[k].waitor);
}
TxBlock[k].next = 0;
init_waitqueue_head(&TxBlock[k].gcwait);
init_waitqueue_head(&TxBlock[k].waitor);
TxAnchor.freetid = 1;
init_waitqueue_head(&TxAnchor.freewait);
stattx.maxtid = 1; /* statistics */
/*
* initialize transaction lock (tlock) table
*
* transaction lock id = tlock index
* tlock id = 0 is reserved.
*/
size = sizeof(struct tlock) * nTxLock;
TxLock = vmalloc(size);
if (TxLock == NULL) {
vfree(TxBlock);
return -ENOMEM;
}
/* initialize tlock table */
for (k = 1; k < nTxLock - 1; k++)
TxLock[k].next = k + 1;
TxLock[k].next = 0;
init_waitqueue_head(&TxAnchor.freelockwait);
init_waitqueue_head(&TxAnchor.lowlockwait);
TxAnchor.freelock = 1;
TxAnchor.tlocksInUse = 0;
INIT_LIST_HEAD(&TxAnchor.anon_list);
INIT_LIST_HEAD(&TxAnchor.anon_list2);
LAZY_LOCK_INIT();
INIT_LIST_HEAD(&TxAnchor.unlock_queue);
stattx.maxlid = 1; /* statistics */
return 0;
}
/*
* NAME: txExit()
*
* FUNCTION: clean up when module is unloaded
*/
void txExit(void)
{
vfree(TxLock);
TxLock = NULL;
vfree(TxBlock);
TxBlock = NULL;
}
/*
* NAME: txBegin()
*
* FUNCTION: start a transaction.
*
* PARAMETER: sb - superblock
* flag - force for nested tx;
*
* RETURN: tid - transaction id
*
* note: flag force allows to start tx for nested tx
* to prevent deadlock on logsync barrier;
*/
tid_t txBegin(struct super_block *sb, int flag)
{
tid_t t;
struct tblock *tblk;
struct jfs_log *log;
jfs_info("txBegin: flag = 0x%x", flag);
log = JFS_SBI(sb)->log;
TXN_LOCK();
INCREMENT(TxStat.txBegin);
retry:
if (!(flag & COMMIT_FORCE)) {
/*
* synchronize with logsync barrier
*/
if (test_bit(log_SYNCBARRIER, &log->flag) ||
test_bit(log_QUIESCE, &log->flag)) {
INCREMENT(TxStat.txBegin_barrier);
TXN_SLEEP(&log->syncwait);
goto retry;
}
}
if (flag == 0) {
/*
* Don't begin transaction if we're getting starved for tlocks
* unless COMMIT_FORCE or COMMIT_INODE (which may ultimately
* free tlocks)
*/
if (TxAnchor.tlocksInUse > TxLockVHWM) {
INCREMENT(TxStat.txBegin_lockslow);
TXN_SLEEP(&TxAnchor.lowlockwait);
goto retry;
}
}
/*
* allocate transaction id/block
*/
if ((t = TxAnchor.freetid) == 0) {
jfs_info("txBegin: waiting for free tid");
INCREMENT(TxStat.txBegin_freetid);
TXN_SLEEP(&TxAnchor.freewait);
goto retry;
}
tblk = tid_to_tblock(t);
if ((tblk->next == 0) && !(flag & COMMIT_FORCE)) {
/* Don't let a non-forced transaction take the last tblk */
jfs_info("txBegin: waiting for free tid");
INCREMENT(TxStat.txBegin_freetid);
TXN_SLEEP(&TxAnchor.freewait);
goto retry;
}
TxAnchor.freetid = tblk->next;
/*
* initialize transaction
*/
/*
* We can't zero the whole thing or we screw up another thread being
* awakened after sleeping on tblk->waitor
*
* memset(tblk, 0, sizeof(struct tblock));
*/
tblk->next = tblk->last = tblk->xflag = tblk->flag = tblk->lsn = 0;
tblk->sb = sb;
++log->logtid;
tblk->logtid = log->logtid;
++log->active;
HIGHWATERMARK(stattx.maxtid, t); /* statistics */
INCREMENT(stattx.ntid); /* statistics */
TXN_UNLOCK();
jfs_info("txBegin: returning tid = %d", t);
return t;
}
/*
* NAME: txBeginAnon()
*
* FUNCTION: start an anonymous transaction.
* Blocks if logsync or available tlocks are low to prevent
* anonymous tlocks from depleting supply.
*
* PARAMETER: sb - superblock
*
* RETURN: none
*/
void txBeginAnon(struct super_block *sb)
{
struct jfs_log *log;
log = JFS_SBI(sb)->log;
TXN_LOCK();
INCREMENT(TxStat.txBeginAnon);
retry:
/*
* synchronize with logsync barrier
*/
if (test_bit(log_SYNCBARRIER, &log->flag) ||
test_bit(log_QUIESCE, &log->flag)) {
INCREMENT(TxStat.txBeginAnon_barrier);
TXN_SLEEP(&log->syncwait);
goto retry;
}
/*
* Don't begin transaction if we're getting starved for tlocks
*/
if (TxAnchor.tlocksInUse > TxLockVHWM) {
INCREMENT(TxStat.txBeginAnon_lockslow);
TXN_SLEEP(&TxAnchor.lowlockwait);
goto retry;
}
TXN_UNLOCK();
}
/*
* txEnd()
*
* function: free specified transaction block.
*
* logsync barrier processing:
*
* serialization:
*/
void txEnd(tid_t tid)
{
struct tblock *tblk = tid_to_tblock(tid);
struct jfs_log *log;
jfs_info("txEnd: tid = %d", tid);
TXN_LOCK();
/*
* wakeup transactions waiting on the page locked
* by the current transaction
*/
TXN_WAKEUP(&tblk->waitor);
log = JFS_SBI(tblk->sb)->log;
/*
* Lazy commit thread can't free this guy until we mark it UNLOCKED,
* otherwise, we would be left with a transaction that may have been
* reused.
*
* Lazy commit thread will turn off tblkGC_LAZY before calling this
* routine.
*/
if (tblk->flag & tblkGC_LAZY) {
jfs_info("txEnd called w/lazy tid: %d, tblk = 0x%p", tid, tblk);
TXN_UNLOCK();
spin_lock_irq(&log->gclock); // LOGGC_LOCK
tblk->flag |= tblkGC_UNLOCKED;
spin_unlock_irq(&log->gclock); // LOGGC_UNLOCK
return;
}
jfs_info("txEnd: tid: %d, tblk = 0x%p", tid, tblk);
assert(tblk->next == 0);
/*
* insert tblock back on freelist
*/
tblk->next = TxAnchor.freetid;
TxAnchor.freetid = tid;
/*
* mark the tblock not active
*/
if (--log->active == 0) {
clear_bit(log_FLUSH, &log->flag);
/*
* synchronize with logsync barrier
*/
if (test_bit(log_SYNCBARRIER, &log->flag)) {
TXN_UNLOCK();
/* write dirty metadata & forward log syncpt */
jfs_syncpt(log, 1);
jfs_info("log barrier off: 0x%x", log->lsn);
/* enable new transactions start */
clear_bit(log_SYNCBARRIER, &log->flag);
/* wakeup all waitors for logsync barrier */
TXN_WAKEUP(&log->syncwait);
goto wakeup;
}
}
TXN_UNLOCK();
wakeup:
/*
* wakeup all waitors for a free tblock
*/
TXN_WAKEUP(&TxAnchor.freewait);
}
/*
* txLock()
*
* function: acquire a transaction lock on the specified <mp>
*
* parameter:
*
* return: transaction lock id
*
* serialization:
*/
struct tlock *txLock(tid_t tid, struct inode *ip, struct metapage * mp,
int type)
{
struct jfs_inode_info *jfs_ip = JFS_IP(ip);
int dir_xtree = 0;
lid_t lid;
tid_t xtid;
struct tlock *tlck;
struct xtlock *xtlck;
struct linelock *linelock;
xtpage_t *p;
struct tblock *tblk;
TXN_LOCK();
if (S_ISDIR(ip->i_mode) && (type & tlckXTREE) &&
!(mp->xflag & COMMIT_PAGE)) {
/*
* Directory inode is special. It can have both an xtree tlock
* and a dtree tlock associated with it.
*/
dir_xtree = 1;
lid = jfs_ip->xtlid;
} else
lid = mp->lid;
/* is page not locked by a transaction ? */
if (lid == 0)
goto allocateLock;
jfs_info("txLock: tid:%d ip:0x%p mp:0x%p lid:%d", tid, ip, mp, lid);
/* is page locked by the requester transaction ? */
tlck = lid_to_tlock(lid);
if ((xtid = tlck->tid) == tid) {
TXN_UNLOCK();
goto grantLock;
}
/*
* is page locked by anonymous transaction/lock ?
*
* (page update without transaction (i.e., file write) is
* locked under anonymous transaction tid = 0:
* anonymous tlocks maintained on anonymous tlock list of
* the inode of the page and available to all anonymous
* transactions until txCommit() time at which point
* they are transferred to the transaction tlock list of
* the committing transaction of the inode)
*/
if (xtid == 0) {
tlck->tid = tid;
TXN_UNLOCK();
tblk = tid_to_tblock(tid);
/*
* The order of the tlocks in the transaction is important
* (during truncate, child xtree pages must be freed before
* parent's tlocks change the working map).
* Take tlock off anonymous list and add to tail of
* transaction list
*
* Note: We really need to get rid of the tid & lid and
* use list_head's. This code is getting UGLY!
*/
if (jfs_ip->atlhead == lid) {
if (jfs_ip->atltail == lid) {
/* only anonymous txn.
* Remove from anon_list
*/
TXN_LOCK();
list_del_init(&jfs_ip->anon_inode_list);
TXN_UNLOCK();
}
jfs_ip->atlhead = tlck->next;
} else {
lid_t last;
for (last = jfs_ip->atlhead;
lid_to_tlock(last)->next != lid;
last = lid_to_tlock(last)->next) {
assert(last);
}
lid_to_tlock(last)->next = tlck->next;
if (jfs_ip->atltail == lid)
jfs_ip->atltail = last;
}
/* insert the tlock at tail of transaction tlock list */
if (tblk->next)
lid_to_tlock(tblk->last)->next = lid;
else
tblk->next = lid;
tlck->next = 0;
tblk->last = lid;
goto grantLock;
}
goto waitLock;
/*
* allocate a tlock
*/
allocateLock:
lid = txLockAlloc();
tlck = lid_to_tlock(lid);
/*
* initialize tlock
*/
tlck->tid = tid;
TXN_UNLOCK();
/* mark tlock for meta-data page */
if (mp->xflag & COMMIT_PAGE) {
tlck->flag = tlckPAGELOCK;
/* mark the page dirty and nohomeok */
metapage_nohomeok(mp);
jfs_info("locking mp = 0x%p, nohomeok = %d tid = %d tlck = 0x%p",
mp, mp->nohomeok, tid, tlck);
/* if anonymous transaction, and buffer is on the group
* commit synclist, mark inode to show this. This will
* prevent the buffer from being marked nohomeok for too
* long a time.
*/
if ((tid == 0) && mp->lsn)
set_cflag(COMMIT_Synclist, ip);
}
/* mark tlock for in-memory inode */
else
tlck->flag = tlckINODELOCK;
if (S_ISDIR(ip->i_mode))
tlck->flag |= tlckDIRECTORY;
tlck->type = 0;
/* bind the tlock and the page */
tlck->ip = ip;
tlck->mp = mp;
if (dir_xtree)
jfs_ip->xtlid = lid;
else
mp->lid = lid;
/*
* enqueue transaction lock to transaction/inode
*/
/* insert the tlock at tail of transaction tlock list */
if (tid) {
tblk = tid_to_tblock(tid);
if (tblk->next)
lid_to_tlock(tblk->last)->next = lid;
else
tblk->next = lid;
tlck->next = 0;
tblk->last = lid;
}
/* anonymous transaction:
* insert the tlock at head of inode anonymous tlock list
*/
else {
tlck->next = jfs_ip->atlhead;
jfs_ip->atlhead = lid;
if (tlck->next == 0) {
/* This inode's first anonymous transaction */
jfs_ip->atltail = lid;
TXN_LOCK();
list_add_tail(&jfs_ip->anon_inode_list,
&TxAnchor.anon_list);
TXN_UNLOCK();
}
}
/* initialize type dependent area for linelock */
linelock = (struct linelock *) & tlck->lock;
linelock->next = 0;
linelock->flag = tlckLINELOCK;
linelock->maxcnt = TLOCKSHORT;
linelock->index = 0;
switch (type & tlckTYPE) {
case tlckDTREE:
linelock->l2linesize = L2DTSLOTSIZE;
break;
case tlckXTREE:
linelock->l2linesize = L2XTSLOTSIZE;
xtlck = (struct xtlock *) linelock;
xtlck->header.offset = 0;
xtlck->header.length = 2;
if (type & tlckNEW) {
xtlck->lwm.offset = XTENTRYSTART;
} else {
if (mp->xflag & COMMIT_PAGE)
p = (xtpage_t *) mp->data;
else
p = &jfs_ip->i_xtroot;
xtlck->lwm.offset =
le16_to_cpu(p->header.nextindex);
}
xtlck->lwm.length = 0; /* ! */
xtlck->twm.offset = 0;
xtlck->hwm.offset = 0;
xtlck->index = 2;
break;
case tlckINODE:
linelock->l2linesize = L2INODESLOTSIZE;
break;
case tlckDATA:
linelock->l2linesize = L2DATASLOTSIZE;
break;
default:
jfs_err("UFO tlock:0x%p", tlck);
}
/*
* update tlock vector
*/
grantLock:
tlck->type |= type;
return tlck;
/*
* page is being locked by another transaction:
*/
waitLock:
/* Only locks on ipimap or ipaimap should reach here */
/* assert(jfs_ip->fileset == AGGREGATE_I); */
if (jfs_ip->fileset != AGGREGATE_I) {
printk(KERN_ERR "txLock: trying to lock locked page!");
print_hex_dump(KERN_ERR, "ip: ", DUMP_PREFIX_ADDRESS, 16, 4,
ip, sizeof(*ip), 0);
print_hex_dump(KERN_ERR, "mp: ", DUMP_PREFIX_ADDRESS, 16, 4,
mp, sizeof(*mp), 0);
print_hex_dump(KERN_ERR, "Locker's tblock: ",
DUMP_PREFIX_ADDRESS, 16, 4, tid_to_tblock(tid),
sizeof(struct tblock), 0);
print_hex_dump(KERN_ERR, "Tlock: ", DUMP_PREFIX_ADDRESS, 16, 4,
tlck, sizeof(*tlck), 0);
BUG();
}
INCREMENT(stattx.waitlock); /* statistics */
TXN_UNLOCK();
release_metapage(mp);
TXN_LOCK();
xtid = tlck->tid; /* reacquire after dropping TXN_LOCK */
jfs_info("txLock: in waitLock, tid = %d, xtid = %d, lid = %d",
tid, xtid, lid);
/* Recheck everything since dropping TXN_LOCK */
if (xtid && (tlck->mp == mp) && (mp->lid == lid))
TXN_SLEEP_DROP_LOCK(&tid_to_tblock(xtid)->waitor);
else
TXN_UNLOCK();
jfs_info("txLock: awakened tid = %d, lid = %d", tid, lid);
return NULL;
}
/*
* NAME: txRelease()
*
* FUNCTION: Release buffers associated with transaction locks, but don't
* mark homeok yet. The allows other transactions to modify
* buffers, but won't let them go to disk until commit record
* actually gets written.
*
* PARAMETER:
* tblk -
*
* RETURN: Errors from subroutines.
*/
static void txRelease(struct tblock * tblk)
{
struct metapage *mp;
lid_t lid;
struct tlock *tlck;
TXN_LOCK();
for (lid = tblk->next; lid; lid = tlck->next) {
tlck = lid_to_tlock(lid);
if ((mp = tlck->mp) != NULL &&
(tlck->type & tlckBTROOT) == 0) {
assert(mp->xflag & COMMIT_PAGE);
mp->lid = 0;
}
}
/*
* wakeup transactions waiting on a page locked
* by the current transaction
*/
TXN_WAKEUP(&tblk->waitor);
TXN_UNLOCK();
}
/*
* NAME: txUnlock()
*
* FUNCTION: Initiates pageout of pages modified by tid in journalled
* objects and frees their lockwords.
*/
static void txUnlock(struct tblock * tblk)
{
struct tlock *tlck;
struct linelock *linelock;
lid_t lid, next, llid, k;
struct metapage *mp;
struct jfs_log *log;
int difft, diffp;
unsigned long flags;
jfs_info("txUnlock: tblk = 0x%p", tblk);
log = JFS_SBI(tblk->sb)->log;
/*
* mark page under tlock homeok (its log has been written):
*/
for (lid = tblk->next; lid; lid = next) {
tlck = lid_to_tlock(lid);
next = tlck->next;
jfs_info("unlocking lid = %d, tlck = 0x%p", lid, tlck);
/* unbind page from tlock */
if ((mp = tlck->mp) != NULL &&
(tlck->type & tlckBTROOT) == 0) {
assert(mp->xflag & COMMIT_PAGE);
/* hold buffer
*/
hold_metapage(mp);
assert(mp->nohomeok > 0);
_metapage_homeok(mp);
/* inherit younger/larger clsn */
LOGSYNC_LOCK(log, flags);
if (mp->clsn) {
logdiff(difft, tblk->clsn, log);
logdiff(diffp, mp->clsn, log);
if (difft > diffp)
mp->clsn = tblk->clsn;
} else
mp->clsn = tblk->clsn;
LOGSYNC_UNLOCK(log, flags);
assert(!(tlck->flag & tlckFREEPAGE));
put_metapage(mp);
}
/* insert tlock, and linelock(s) of the tlock if any,
* at head of freelist
*/
TXN_LOCK();
llid = ((struct linelock *) & tlck->lock)->next;
while (llid) {
linelock = (struct linelock *) lid_to_tlock(llid);
k = linelock->next;
txLockFree(llid);
llid = k;
}
txLockFree(lid);
TXN_UNLOCK();
}
tblk->next = tblk->last = 0;
/*
* remove tblock from logsynclist
* (allocation map pages inherited lsn of tblk and
* has been inserted in logsync list at txUpdateMap())
*/
if (tblk->lsn) {
LOGSYNC_LOCK(log, flags);
log->count--;
list_del(&tblk->synclist);
LOGSYNC_UNLOCK(log, flags);
}
}
/*
* txMaplock()
*
* function: allocate a transaction lock for freed page/entry;
* for freed page, maplock is used as xtlock/dtlock type;
*/
struct tlock *txMaplock(tid_t tid, struct inode *ip, int type)
{
struct jfs_inode_info *jfs_ip = JFS_IP(ip);
lid_t lid;
struct tblock *tblk;
struct tlock *tlck;
struct maplock *maplock;
TXN_LOCK();
/*
* allocate a tlock
*/
lid = txLockAlloc();
tlck = lid_to_tlock(lid);
/*
* initialize tlock
*/
tlck->tid = tid;
/* bind the tlock and the object */
tlck->flag = tlckINODELOCK;
if (S_ISDIR(ip->i_mode))
tlck->flag |= tlckDIRECTORY;
tlck->ip = ip;
tlck->mp = NULL;
tlck->type = type;
/*
* enqueue transaction lock to transaction/inode
*/
/* insert the tlock at tail of transaction tlock list */
if (tid) {
tblk = tid_to_tblock(tid);
if (tblk->next)
lid_to_tlock(tblk->last)->next = lid;
else
tblk->next = lid;
tlck->next = 0;
tblk->last = lid;
}
/* anonymous transaction:
* insert the tlock at head of inode anonymous tlock list
*/
else {
tlck->next = jfs_ip->atlhead;
jfs_ip->atlhead = lid;
if (tlck->next == 0) {
/* This inode's first anonymous transaction */
jfs_ip->atltail = lid;
list_add_tail(&jfs_ip->anon_inode_list,
&TxAnchor.anon_list);
}
}
TXN_UNLOCK();
/* initialize type dependent area for maplock */
maplock = (struct maplock *) & tlck->lock;
maplock->next = 0;
maplock->maxcnt = 0;
maplock->index = 0;
return tlck;
}
/*
* txLinelock()
*
* function: allocate a transaction lock for log vector list
*/
struct linelock *txLinelock(struct linelock * tlock)
{
lid_t lid;
struct tlock *tlck;
struct linelock *linelock;
TXN_LOCK();
/* allocate a TxLock structure */
lid = txLockAlloc();
tlck = lid_to_tlock(lid);
TXN_UNLOCK();
/* initialize linelock */
linelock = (struct linelock *) tlck;
linelock->next = 0;
linelock->flag = tlckLINELOCK;
linelock->maxcnt = TLOCKLONG;
linelock->index = 0;
if (tlck->flag & tlckDIRECTORY)
linelock->flag |= tlckDIRECTORY;
/* append linelock after tlock */
linelock->next = tlock->next;
tlock->next = lid;
return linelock;
}
/*
* transaction commit management
* -----------------------------
*/
/*
* NAME: txCommit()
*
* FUNCTION: commit the changes to the objects specified in
* clist. For journalled segments only the
* changes of the caller are committed, ie by tid.
* for non-journalled segments the data are flushed to
* disk and then the change to the disk inode and indirect
* blocks committed (so blocks newly allocated to the
* segment will be made a part of the segment atomically).
*
* all of the segments specified in clist must be in
* one file system. no more than 6 segments are needed
* to handle all unix svcs.
*
* if the i_nlink field (i.e. disk inode link count)
* is zero, and the type of inode is a regular file or
* directory, or symbolic link , the inode is truncated
* to zero length. the truncation is committed but the
* VM resources are unaffected until it is closed (see
* iput and iclose).
*
* PARAMETER:
*
* RETURN:
*
* serialization:
* on entry the inode lock on each segment is assumed
* to be held.
*
* i/o error:
*/
int txCommit(tid_t tid, /* transaction identifier */
int nip, /* number of inodes to commit */
struct inode **iplist, /* list of inode to commit */
int flag)
{
int rc = 0;
struct commit cd;
struct jfs_log *log;
struct tblock *tblk;
struct lrd *lrd;
struct inode *ip;
struct jfs_inode_info *jfs_ip;
int k, n;
ino_t top;
struct super_block *sb;
jfs_info("txCommit, tid = %d, flag = %d", tid, flag);
/* is read-only file system ? */
if (isReadOnly(iplist[0])) {
rc = -EROFS;
goto TheEnd;
}
sb = cd.sb = iplist[0]->i_sb;
cd.tid = tid;
if (tid == 0)
tid = txBegin(sb, 0);
tblk = tid_to_tblock(tid);
/*
* initialize commit structure
*/
log = JFS_SBI(sb)->log;
cd.log = log;
/* initialize log record descriptor in commit */
lrd = &cd.lrd;
lrd->logtid = cpu_to_le32(tblk->logtid);
lrd->backchain = 0;
tblk->xflag |= flag;
if ((flag & (COMMIT_FORCE | COMMIT_SYNC)) == 0)
tblk->xflag |= COMMIT_LAZY;
/*
* prepare non-journaled objects for commit
*
* flush data pages of non-journaled file
* to prevent the file getting non-initialized disk blocks
* in case of crash.
* (new blocks - )
*/
cd.iplist = iplist;
cd.nip = nip;
/*
* acquire transaction lock on (on-disk) inodes
*
* update on-disk inode from in-memory inode
* acquiring transaction locks for AFTER records
* on the on-disk inode of file object
*
* sort the inodes array by inode number in descending order
* to prevent deadlock when acquiring transaction lock
* of on-disk inodes on multiple on-disk inode pages by
* multiple concurrent transactions
*/
for (k = 0; k < cd.nip; k++) {
top = (cd.iplist[k])->i_ino;
for (n = k + 1; n < cd.nip; n++) {
ip = cd.iplist[n];
if (ip->i_ino > top) {
top = ip->i_ino;
cd.iplist[n] = cd.iplist[k];
cd.iplist[k] = ip;
}
}
ip = cd.iplist[k];
jfs_ip = JFS_IP(ip);
/*
* BUGBUG - This code has temporarily been removed. The
* intent is to ensure that any file data is written before
* the metadata is committed to the journal. This prevents
* uninitialized data from appearing in a file after the
* journal has been replayed. (The uninitialized data
* could be sensitive data removed by another user.)
*
* The problem now is that we are holding the IWRITELOCK
* on the inode, and calling filemap_fdatawrite on an
* unmapped page will cause a deadlock in jfs_get_block.
*
* The long term solution is to pare down the use of
* IWRITELOCK. We are currently holding it too long.
* We could also be smarter about which data pages need
* to be written before the transaction is committed and
* when we don't need to worry about it at all.
*
* if ((!S_ISDIR(ip->i_mode))
* && (tblk->flag & COMMIT_DELETE) == 0)
* filemap_write_and_wait(ip->i_mapping);
*/
/*
* Mark inode as not dirty. It will still be on the dirty
* inode list, but we'll know not to commit it again unless
* it gets marked dirty again
*/
clear_cflag(COMMIT_Dirty, ip);
/* inherit anonymous tlock(s) of inode */
if (jfs_ip->atlhead) {
lid_to_tlock(jfs_ip->atltail)->next = tblk->next;
tblk->next = jfs_ip->atlhead;
if (!tblk->last)
tblk->last = jfs_ip->atltail;
jfs_ip->atlhead = jfs_ip->atltail = 0;
TXN_LOCK();
list_del_init(&jfs_ip->anon_inode_list);
TXN_UNLOCK();
}
/*
* acquire transaction lock on on-disk inode page
* (become first tlock of the tblk's tlock list)
*/
if (((rc = diWrite(tid, ip))))
goto out;
}
/*
* write log records from transaction locks
*
* txUpdateMap() resets XAD_NEW in XAD.
*/
if ((rc = txLog(log, tblk, &cd)))
goto TheEnd;
/*
* Ensure that inode isn't reused before
* lazy commit thread finishes processing
*/
if (tblk->xflag & COMMIT_DELETE) {
ihold(tblk->u.ip);
/*
* Avoid a rare deadlock
*
* If the inode is locked, we may be blocked in
* jfs_commit_inode. If so, we don't want the
* lazy_commit thread doing the last iput() on the inode
* since that may block on the locked inode. Instead,
* commit the transaction synchronously, so the last iput
* will be done by the calling thread (or later)
*/
/*
* I believe this code is no longer needed. Splitting I_LOCK
* into two bits, I_NEW and I_SYNC should prevent this
* deadlock as well. But since I don't have a JFS testload
* to verify this, only a trivial s/I_LOCK/I_SYNC/ was done.
* Joern
*/
if (tblk->u.ip->i_state & I_SYNC)
tblk->xflag &= ~COMMIT_LAZY;
}
ASSERT((!(tblk->xflag & COMMIT_DELETE)) ||
((tblk->u.ip->i_nlink == 0) &&
!test_cflag(COMMIT_Nolink, tblk->u.ip)));
/*
* write COMMIT log record
*/
lrd->type = cpu_to_le16(LOG_COMMIT);
lrd->length = 0;
lmLog(log, tblk, lrd, NULL);
lmGroupCommit(log, tblk);
/*
* - transaction is now committed -
*/
/*
* force pages in careful update
* (imap addressing structure update)
*/
if (flag & COMMIT_FORCE)
txForce(tblk);
/*
* update allocation map.
*
* update inode allocation map and inode:
* free pager lock on memory object of inode if any.
* update block allocation map.
*
* txUpdateMap() resets XAD_NEW in XAD.
*/
if (tblk->xflag & COMMIT_FORCE)
txUpdateMap(tblk);
/*
* free transaction locks and pageout/free pages
*/
txRelease(tblk);
if ((tblk->flag & tblkGC_LAZY) == 0)
txUnlock(tblk);
/*
* reset in-memory object state
*/
for (k = 0; k < cd.nip; k++) {
ip = cd.iplist[k];
jfs_ip = JFS_IP(ip);
/*
* reset in-memory inode state
*/
jfs_ip->bxflag = 0;
jfs_ip->blid = 0;
}
out:
if (rc != 0)
txAbort(tid, 1);
TheEnd:
jfs_info("txCommit: tid = %d, returning %d", tid, rc);
return rc;
}
/*
* NAME: txLog()
*
* FUNCTION: Writes AFTER log records for all lines modified
* by tid for segments specified by inodes in comdata.
* Code assumes only WRITELOCKS are recorded in lockwords.
*
* PARAMETERS:
*
* RETURN :
*/
static int txLog(struct jfs_log * log, struct tblock * tblk, struct commit * cd)
{
int rc = 0;
struct inode *ip;
lid_t lid;
struct tlock *tlck;
struct lrd *lrd = &cd->lrd;
/*
* write log record(s) for each tlock of transaction,
*/
for (lid = tblk->next; lid; lid = tlck->next) {
tlck = lid_to_tlock(lid);
tlck->flag |= tlckLOG;
/* initialize lrd common */
ip = tlck->ip;
lrd->aggregate = cpu_to_le32(JFS_SBI(ip->i_sb)->aggregate);
lrd->log.redopage.fileset = cpu_to_le32(JFS_IP(ip)->fileset);
lrd->log.redopage.inode = cpu_to_le32(ip->i_ino);
/* write log record of page from the tlock */
switch (tlck->type & tlckTYPE) {
case tlckXTREE:
xtLog(log, tblk, lrd, tlck);
break;
case tlckDTREE:
dtLog(log, tblk, lrd, tlck);
break;
case tlckINODE:
diLog(log, tblk, lrd, tlck, cd);
break;
case tlckMAP:
mapLog(log, tblk, lrd, tlck);
break;
case tlckDATA:
dataLog(log, tblk, lrd, tlck);
break;
default:
jfs_err("UFO tlock:0x%p", tlck);
}
}
return rc;
}
/*
* diLog()
*
* function: log inode tlock and format maplock to update bmap;
*/
static int diLog(struct jfs_log * log, struct tblock * tblk, struct lrd * lrd,
struct tlock * tlck, struct commit * cd)
{
int rc = 0;
struct metapage *mp;
pxd_t *pxd;
struct pxd_lock *pxdlock;
mp = tlck->mp;
/* initialize as REDOPAGE record format */
lrd->log.redopage.type = cpu_to_le16(LOG_INODE);
lrd->log.redopage.l2linesize = cpu_to_le16(L2INODESLOTSIZE);
pxd = &lrd->log.redopage.pxd;
/*
* inode after image
*/
if (tlck->type & tlckENTRY) {
/* log after-image for logredo(): */
lrd->type = cpu_to_le16(LOG_REDOPAGE);
PXDaddress(pxd, mp->index);
PXDlength(pxd,
mp->logical_size >> tblk->sb->s_blocksize_bits);
lrd->backchain = cpu_to_le32(lmLog(log, tblk, lrd, tlck));
/* mark page as homeward bound */
tlck->flag |= tlckWRITEPAGE;
} else if (tlck->type & tlckFREE) {
/*
* free inode extent
*
* (pages of the freed inode extent have been invalidated and
* a maplock for free of the extent has been formatted at
* txLock() time);
*
* the tlock had been acquired on the inode allocation map page
* (iag) that specifies the freed extent, even though the map
* page is not itself logged, to prevent pageout of the map
* page before the log;
*/
/* log LOG_NOREDOINOEXT of the freed inode extent for
* logredo() to start NoRedoPage filters, and to update
* imap and bmap for free of the extent;
*/
lrd->type = cpu_to_le16(LOG_NOREDOINOEXT);
/*
* For the LOG_NOREDOINOEXT record, we need
* to pass the IAG number and inode extent
* index (within that IAG) from which the
* the extent being released. These have been
* passed to us in the iplist[1] and iplist[2].
*/
lrd->log.noredoinoext.iagnum =
cpu_to_le32((u32) (size_t) cd->iplist[1]);
lrd->log.noredoinoext.inoext_idx =
cpu_to_le32((u32) (size_t) cd->iplist[2]);
pxdlock = (struct pxd_lock *) & tlck->lock;
*pxd = pxdlock->pxd;
lrd->backchain = cpu_to_le32(lmLog(log, tblk, lrd, NULL));
/* update bmap */
tlck->flag |= tlckUPDATEMAP;
/* mark page as homeward bound */
tlck->flag |= tlckWRITEPAGE;
} else
jfs_err("diLog: UFO type tlck:0x%p", tlck);
#ifdef _JFS_WIP
/*
* alloc/free external EA extent
*
* a maplock for txUpdateMap() to update bPWMAP for alloc/free
* of the extent has been formatted at txLock() time;
*/
else {
assert(tlck->type & tlckEA);
/* log LOG_UPDATEMAP for logredo() to update bmap for
* alloc of new (and free of old) external EA extent;
*/
lrd->type = cpu_to_le16(LOG_UPDATEMAP);
pxdlock = (struct pxd_lock *) & tlck->lock;
nlock = pxdlock->index;
for (i = 0; i < nlock; i++, pxdlock++) {
if (pxdlock->flag & mlckALLOCPXD)
lrd->log.updatemap.type =
cpu_to_le16(LOG_ALLOCPXD);
else
lrd->log.updatemap.type =
cpu_to_le16(LOG_FREEPXD);
lrd->log.updatemap.nxd = cpu_to_le16(1);
lrd->log.updatemap.pxd = pxdlock->pxd;
lrd->backchain =
cpu_to_le32(lmLog(log, tblk, lrd, NULL));
}
/* update bmap */
tlck->flag |= tlckUPDATEMAP;
}
#endif /* _JFS_WIP */
return rc;
}
/*
* dataLog()
*
* function: log data tlock
*/
static int dataLog(struct jfs_log * log, struct tblock * tblk, struct lrd * lrd,
struct tlock * tlck)
{
struct metapage *mp;
pxd_t *pxd;
mp = tlck->mp;
/* initialize as REDOPAGE record format */
lrd->log.redopage.type = cpu_to_le16(LOG_DATA);
lrd->log.redopage.l2linesize = cpu_to_le16(L2DATASLOTSIZE);
pxd = &lrd->log.redopage.pxd;
/* log after-image for logredo(): */
lrd->type = cpu_to_le16(LOG_REDOPAGE);
if (jfs_dirtable_inline(tlck->ip)) {
/*
* The table has been truncated, we've must have deleted
* the last entry, so don't bother logging this
*/
mp->lid = 0;
grab_metapage(mp);
metapage_homeok(mp);
discard_metapage(mp);
tlck->mp = NULL;
return 0;
}
PXDaddress(pxd, mp->index);
PXDlength(pxd, mp->logical_size >> tblk->sb->s_blocksize_bits);
lrd->backchain = cpu_to_le32(lmLog(log, tblk, lrd, tlck));
/* mark page as homeward bound */
tlck->flag |= tlckWRITEPAGE;
return 0;
}
/*
* dtLog()
*
* function: log dtree tlock and format maplock to update bmap;
*/
static void dtLog(struct jfs_log * log, struct tblock * tblk, struct lrd * lrd,
struct tlock * tlck)
{
struct metapage *mp;
struct pxd_lock *pxdlock;
pxd_t *pxd;
mp = tlck->mp;
/* initialize as REDOPAGE/NOREDOPAGE record format */
lrd->log.redopage.type = cpu_to_le16(LOG_DTREE);
lrd->log.redopage.l2linesize = cpu_to_le16(L2DTSLOTSIZE);
pxd = &lrd->log.redopage.pxd;
if (tlck->type & tlckBTROOT)
lrd->log.redopage.type |= cpu_to_le16(LOG_BTROOT);
/*
* page extension via relocation: entry insertion;
* page extension in-place: entry insertion;
* new right page from page split, reinitialized in-line
* root from root page split: entry insertion;
*/
if (tlck->type & (tlckNEW | tlckEXTEND)) {
/* log after-image of the new page for logredo():
* mark log (LOG_NEW) for logredo() to initialize
* freelist and update bmap for alloc of the new page;
*/
lrd->type = cpu_to_le16(LOG_REDOPAGE);
if (tlck->type & tlckEXTEND)
lrd->log.redopage.type |= cpu_to_le16(LOG_EXTEND);
else
lrd->log.redopage.type |= cpu_to_le16(LOG_NEW);
PXDaddress(pxd, mp->index);
PXDlength(pxd,
mp->logical_size >> tblk->sb->s_blocksize_bits);
lrd->backchain = cpu_to_le32(lmLog(log, tblk, lrd, tlck));
/* format a maplock for txUpdateMap() to update bPMAP for
* alloc of the new page;
*/
if (tlck->type & tlckBTROOT)
return;
tlck->flag |= tlckUPDATEMAP;
pxdlock = (struct pxd_lock *) & tlck->lock;
pxdlock->flag = mlckALLOCPXD;
pxdlock->pxd = *pxd;
pxdlock->index = 1;
/* mark page as homeward bound */
tlck->flag |= tlckWRITEPAGE;
return;
}
/*
* entry insertion/deletion,
* sibling page link update (old right page before split);
*/
if (tlck->type & (tlckENTRY | tlckRELINK)) {
/* log after-image for logredo(): */
lrd->type = cpu_to_le16(LOG_REDOPAGE);
PXDaddress(pxd, mp->index);
PXDlength(pxd,
mp->logical_size >> tblk->sb->s_blocksize_bits);
lrd->backchain = cpu_to_le32(lmLog(log, tblk, lrd, tlck));
/* mark page as homeward bound */
tlck->flag |= tlckWRITEPAGE;
return;
}
/*
* page deletion: page has been invalidated
* page relocation: source extent
*
* a maplock for free of the page has been formatted
* at txLock() time);
*/
if (tlck->type & (tlckFREE | tlckRELOCATE)) {
/* log LOG_NOREDOPAGE of the deleted page for logredo()
* to start NoRedoPage filter and to update bmap for free
* of the deletd page
*/
lrd->type = cpu_to_le16(LOG_NOREDOPAGE);
pxdlock = (struct pxd_lock *) & tlck->lock;
*pxd = pxdlock->pxd;
lrd->backchain = cpu_to_le32(lmLog(log, tblk, lrd, NULL));
/* a maplock for txUpdateMap() for free of the page
* has been formatted at txLock() time;
*/
tlck->flag |= tlckUPDATEMAP;
}
return;
}
/*
* xtLog()
*
* function: log xtree tlock and format maplock to update bmap;
*/
static void xtLog(struct jfs_log * log, struct tblock * tblk, struct lrd * lrd,
struct tlock * tlck)
{
struct inode *ip;
struct metapage *mp;
xtpage_t *p;
struct xtlock *xtlck;
struct maplock *maplock;
struct xdlistlock *xadlock;
struct pxd_lock *pxdlock;
pxd_t *page_pxd;
int next, lwm, hwm;
ip = tlck->ip;
mp = tlck->mp;
/* initialize as REDOPAGE/NOREDOPAGE record format */
lrd->log.redopage.type = cpu_to_le16(LOG_XTREE);
lrd->log.redopage.l2linesize = cpu_to_le16(L2XTSLOTSIZE);
page_pxd = &lrd->log.redopage.pxd;
if (tlck->type & tlckBTROOT) {
lrd->log.redopage.type |= cpu_to_le16(LOG_BTROOT);
p = &JFS_IP(ip)->i_xtroot;
if (S_ISDIR(ip->i_mode))
lrd->log.redopage.type |=
cpu_to_le16(LOG_DIR_XTREE);
} else
p = (xtpage_t *) mp->data;
next = le16_to_cpu(p->header.nextindex);
xtlck = (struct xtlock *) & tlck->lock;
maplock = (struct maplock *) & tlck->lock;
xadlock = (struct xdlistlock *) maplock;
/*
* entry insertion/extension;
* sibling page link update (old right page before split);
*/
if (tlck->type & (tlckNEW | tlckGROW | tlckRELINK)) {
/* log after-image for logredo():
* logredo() will update bmap for alloc of new/extended
* extents (XAD_NEW|XAD_EXTEND) of XAD[lwm:next) from
* after-image of XADlist;
* logredo() resets (XAD_NEW|XAD_EXTEND) flag when
* applying the after-image to the meta-data page.
*/
lrd->type = cpu_to_le16(LOG_REDOPAGE);
PXDaddress(page_pxd, mp->index);
PXDlength(page_pxd,
mp->logical_size >> tblk->sb->s_blocksize_bits);
lrd->backchain = cpu_to_le32(lmLog(log, tblk, lrd, tlck));
/* format a maplock for txUpdateMap() to update bPMAP
* for alloc of new/extended extents of XAD[lwm:next)
* from the page itself;
* txUpdateMap() resets (XAD_NEW|XAD_EXTEND) flag.
*/
lwm = xtlck->lwm.offset;
if (lwm == 0)
lwm = XTPAGEMAXSLOT;
if (lwm == next)
goto out;
if (lwm > next) {
jfs_err("xtLog: lwm > next\n");
goto out;
}
tlck->flag |= tlckUPDATEMAP;
xadlock->flag = mlckALLOCXADLIST;
xadlock->count = next - lwm;
if ((xadlock->count <= 4) && (tblk->xflag & COMMIT_LAZY)) {
int i;
pxd_t *pxd;
/*
* Lazy commit may allow xtree to be modified before
* txUpdateMap runs. Copy xad into linelock to
* preserve correct data.
*
* We can fit twice as may pxd's as xads in the lock
*/
xadlock->flag = mlckALLOCPXDLIST;
pxd = xadlock->xdlist = &xtlck->pxdlock;
for (i = 0; i < xadlock->count; i++) {
PXDaddress(pxd, addressXAD(&p->xad[lwm + i]));
PXDlength(pxd, lengthXAD(&p->xad[lwm + i]));
p->xad[lwm + i].flag &=
~(XAD_NEW | XAD_EXTENDED);
pxd++;
}
} else {
/*
* xdlist will point to into inode's xtree, ensure
* that transaction is not committed lazily.
*/
xadlock->flag = mlckALLOCXADLIST;
xadlock->xdlist = &p->xad[lwm];
tblk->xflag &= ~COMMIT_LAZY;
}
jfs_info("xtLog: alloc ip:0x%p mp:0x%p tlck:0x%p lwm:%d "
"count:%d", tlck->ip, mp, tlck, lwm, xadlock->count);
maplock->index = 1;
out:
/* mark page as homeward bound */
tlck->flag |= tlckWRITEPAGE;
return;
}
/*
* page deletion: file deletion/truncation (ref. xtTruncate())
*
* (page will be invalidated after log is written and bmap
* is updated from the page);
*/
if (tlck->type & tlckFREE) {
/* LOG_NOREDOPAGE log for NoRedoPage filter:
* if page free from file delete, NoRedoFile filter from
* inode image of zero link count will subsume NoRedoPage
* filters for each page;
* if page free from file truncattion, write NoRedoPage
* filter;
*
* upadte of block allocation map for the page itself:
* if page free from deletion and truncation, LOG_UPDATEMAP
* log for the page itself is generated from processing
* its parent page xad entries;
*/
/* if page free from file truncation, log LOG_NOREDOPAGE
* of the deleted page for logredo() to start NoRedoPage
* filter for the page;
*/
if (tblk->xflag & COMMIT_TRUNCATE) {
/* write NOREDOPAGE for the page */
lrd->type = cpu_to_le16(LOG_NOREDOPAGE);
PXDaddress(page_pxd, mp->index);
PXDlength(page_pxd,
mp->logical_size >> tblk->sb->
s_blocksize_bits);
lrd->backchain =
cpu_to_le32(lmLog(log, tblk, lrd, NULL));
if (tlck->type & tlckBTROOT) {
/* Empty xtree must be logged */
lrd->type = cpu_to_le16(LOG_REDOPAGE);
lrd->backchain =
cpu_to_le32(lmLog(log, tblk, lrd, tlck));
}
}
/* init LOG_UPDATEMAP of the freed extents
* XAD[XTENTRYSTART:hwm) from the deleted page itself
* for logredo() to update bmap;
*/
lrd->type = cpu_to_le16(LOG_UPDATEMAP);
lrd->log.updatemap.type = cpu_to_le16(LOG_FREEXADLIST);
xtlck = (struct xtlock *) & tlck->lock;
hwm = xtlck->hwm.offset;
lrd->log.updatemap.nxd =
cpu_to_le16(hwm - XTENTRYSTART + 1);
/* reformat linelock for lmLog() */
xtlck->header.offset = XTENTRYSTART;
xtlck->header.length = hwm - XTENTRYSTART + 1;
xtlck->index = 1;
lrd->backchain = cpu_to_le32(lmLog(log, tblk, lrd, tlck));
/* format a maplock for txUpdateMap() to update bmap
* to free extents of XAD[XTENTRYSTART:hwm) from the
* deleted page itself;
*/
tlck->flag |= tlckUPDATEMAP;
xadlock->count = hwm - XTENTRYSTART + 1;
if ((xadlock->count <= 4) && (tblk->xflag & COMMIT_LAZY)) {
int i;
pxd_t *pxd;
/*
* Lazy commit may allow xtree to be modified before
* txUpdateMap runs. Copy xad into linelock to
* preserve correct data.
*
* We can fit twice as may pxd's as xads in the lock
*/
xadlock->flag = mlckFREEPXDLIST;
pxd = xadlock->xdlist = &xtlck->pxdlock;
for (i = 0; i < xadlock->count; i++) {
PXDaddress(pxd,
addressXAD(&p->xad[XTENTRYSTART + i]));
PXDlength(pxd,
lengthXAD(&p->xad[XTENTRYSTART + i]));
pxd++;
}
} else {
/*
* xdlist will point to into inode's xtree, ensure
* that transaction is not committed lazily.
*/
xadlock->flag = mlckFREEXADLIST;
xadlock->xdlist = &p->xad[XTENTRYSTART];
tblk->xflag &= ~COMMIT_LAZY;
}
jfs_info("xtLog: free ip:0x%p mp:0x%p count:%d lwm:2",
tlck->ip, mp, xadlock->count);
maplock->index = 1;
/* mark page as invalid */
if (((tblk->xflag & COMMIT_PWMAP) || S_ISDIR(ip->i_mode))
&& !(tlck->type & tlckBTROOT))
tlck->flag |= tlckFREEPAGE;
/*
else (tblk->xflag & COMMIT_PMAP)
? release the page;
*/
return;
}
/*
* page/entry truncation: file truncation (ref. xtTruncate())
*
* |----------+------+------+---------------|
* | | |
* | | hwm - hwm before truncation
* | next - truncation point
* lwm - lwm before truncation
* header ?
*/
if (tlck->type & tlckTRUNCATE) {
/* This odd declaration suppresses a bogus gcc warning */
pxd_t pxd = pxd; /* truncated extent of xad */
int twm;
/*
* For truncation the entire linelock may be used, so it would
* be difficult to store xad list in linelock itself.
* Therefore, we'll just force transaction to be committed
* synchronously, so that xtree pages won't be changed before
* txUpdateMap runs.
*/
tblk->xflag &= ~COMMIT_LAZY;
lwm = xtlck->lwm.offset;
if (lwm == 0)
lwm = XTPAGEMAXSLOT;
hwm = xtlck->hwm.offset;
twm = xtlck->twm.offset;
/*
* write log records
*/
/* log after-image for logredo():
*
* logredo() will update bmap for alloc of new/extended
* extents (XAD_NEW|XAD_EXTEND) of XAD[lwm:next) from
* after-image of XADlist;
* logredo() resets (XAD_NEW|XAD_EXTEND) flag when
* applying the after-image to the meta-data page.
*/
lrd->type = cpu_to_le16(LOG_REDOPAGE);
PXDaddress(page_pxd, mp->index);
PXDlength(page_pxd,
mp->logical_size >> tblk->sb->s_blocksize_bits);
lrd->backchain = cpu_to_le32(lmLog(log, tblk, lrd, tlck));
/*
* truncate entry XAD[twm == next - 1]:
*/
if (twm == next - 1) {
/* init LOG_UPDATEMAP for logredo() to update bmap for
* free of truncated delta extent of the truncated
* entry XAD[next - 1]:
* (xtlck->pxdlock = truncated delta extent);
*/
pxdlock = (struct pxd_lock *) & xtlck->pxdlock;
/* assert(pxdlock->type & tlckTRUNCATE); */
lrd->type = cpu_to_le16(LOG_UPDATEMAP);
lrd->log.updatemap.type = cpu_to_le16(LOG_FREEPXD);
lrd->log.updatemap.nxd = cpu_to_le16(1);
lrd->log.updatemap.pxd = pxdlock->pxd;
pxd = pxdlock->pxd; /* save to format maplock */
lrd->backchain =
cpu_to_le32(lmLog(log, tblk, lrd, NULL));
}
/*
* free entries XAD[next:hwm]:
*/
if (hwm >= next) {
/* init LOG_UPDATEMAP of the freed extents
* XAD[next:hwm] from the deleted page itself
* for logredo() to update bmap;
*/
lrd->type = cpu_to_le16(LOG_UPDATEMAP);
lrd->log.updatemap.type =
cpu_to_le16(LOG_FREEXADLIST);
xtlck = (struct xtlock *) & tlck->lock;
hwm = xtlck->hwm.offset;
lrd->log.updatemap.nxd =
cpu_to_le16(hwm - next + 1);
/* reformat linelock for lmLog() */
xtlck->header.offset = next;
xtlck->header.length = hwm - next + 1;
xtlck->index = 1;
lrd->backchain =
cpu_to_le32(lmLog(log, tblk, lrd, tlck));
}
/*
* format maplock(s) for txUpdateMap() to update bmap
*/
maplock->index = 0;
/*
* allocate entries XAD[lwm:next):
*/
if (lwm < next) {
/* format a maplock for txUpdateMap() to update bPMAP
* for alloc of new/extended extents of XAD[lwm:next)
* from the page itself;
* txUpdateMap() resets (XAD_NEW|XAD_EXTEND) flag.
*/
tlck->flag |= tlckUPDATEMAP;
xadlock->flag = mlckALLOCXADLIST;
xadlock->count = next - lwm;
xadlock->xdlist = &p->xad[lwm];
jfs_info("xtLog: alloc ip:0x%p mp:0x%p count:%d "
"lwm:%d next:%d",
tlck->ip, mp, xadlock->count, lwm, next);
maplock->index++;
xadlock++;
}
/*
* truncate entry XAD[twm == next - 1]:
*/
if (twm == next - 1) {
/* format a maplock for txUpdateMap() to update bmap
* to free truncated delta extent of the truncated
* entry XAD[next - 1];
* (xtlck->pxdlock = truncated delta extent);
*/
tlck->flag |= tlckUPDATEMAP;
pxdlock = (struct pxd_lock *) xadlock;
pxdlock->flag = mlckFREEPXD;
pxdlock->count = 1;
pxdlock->pxd = pxd;
jfs_info("xtLog: truncate ip:0x%p mp:0x%p count:%d "
"hwm:%d", ip, mp, pxdlock->count, hwm);
maplock->index++;
xadlock++;
}
/*
* free entries XAD[next:hwm]:
*/
if (hwm >= next) {
/* format a maplock for txUpdateMap() to update bmap
* to free extents of XAD[next:hwm] from thedeleted
* page itself;
*/
tlck->flag |= tlckUPDATEMAP;
xadlock->flag = mlckFREEXADLIST;
xadlock->count = hwm - next + 1;
xadlock->xdlist = &p->xad[next];
jfs_info("xtLog: free ip:0x%p mp:0x%p count:%d "
"next:%d hwm:%d",
tlck->ip, mp, xadlock->count, next, hwm);
maplock->index++;
}
/* mark page as homeward bound */
tlck->flag |= tlckWRITEPAGE;
}
return;
}
/*
* mapLog()
*
* function: log from maplock of freed data extents;
*/
static void mapLog(struct jfs_log * log, struct tblock * tblk, struct lrd * lrd,
struct tlock * tlck)
{
struct pxd_lock *pxdlock;
int i, nlock;
pxd_t *pxd;
/*
* page relocation: free the source page extent
*
* a maplock for txUpdateMap() for free of the page
* has been formatted at txLock() time saving the src
* relocated page address;
*/
if (tlck->type & tlckRELOCATE) {
/* log LOG_NOREDOPAGE of the old relocated page
* for logredo() to start NoRedoPage filter;
*/
lrd->type = cpu_to_le16(LOG_NOREDOPAGE);
pxdlock = (struct pxd_lock *) & tlck->lock;
pxd = &lrd->log.redopage.pxd;
*pxd = pxdlock->pxd;
lrd->backchain = cpu_to_le32(lmLog(log, tblk, lrd, NULL));
/* (N.B. currently, logredo() does NOT update bmap
* for free of the page itself for (LOG_XTREE|LOG_NOREDOPAGE);
* if page free from relocation, LOG_UPDATEMAP log is
* specifically generated now for logredo()
* to update bmap for free of src relocated page;
* (new flag LOG_RELOCATE may be introduced which will
* inform logredo() to start NORedoPage filter and also
* update block allocation map at the same time, thus
* avoiding an extra log write);
*/
lrd->type = cpu_to_le16(LOG_UPDATEMAP);
lrd->log.updatemap.type = cpu_to_le16(LOG_FREEPXD);
lrd->log.updatemap.nxd = cpu_to_le16(1);
lrd->log.updatemap.pxd = pxdlock->pxd;
lrd->backchain = cpu_to_le32(lmLog(log, tblk, lrd, NULL));
/* a maplock for txUpdateMap() for free of the page
* has been formatted at txLock() time;
*/
tlck->flag |= tlckUPDATEMAP;
return;
}
/*
* Otherwise it's not a relocate request
*
*/
else {
/* log LOG_UPDATEMAP for logredo() to update bmap for
* free of truncated/relocated delta extent of the data;
* e.g.: external EA extent, relocated/truncated extent
* from xtTailgate();
*/
lrd->type = cpu_to_le16(LOG_UPDATEMAP);
pxdlock = (struct pxd_lock *) & tlck->lock;
nlock = pxdlock->index;
for (i = 0; i < nlock; i++, pxdlock++) {
if (pxdlock->flag & mlckALLOCPXD)
lrd->log.updatemap.type =
cpu_to_le16(LOG_ALLOCPXD);
else
lrd->log.updatemap.type =
cpu_to_le16(LOG_FREEPXD);
lrd->log.updatemap.nxd = cpu_to_le16(1);
lrd->log.updatemap.pxd = pxdlock->pxd;
lrd->backchain =
cpu_to_le32(lmLog(log, tblk, lrd, NULL));
jfs_info("mapLog: xaddr:0x%lx xlen:0x%x",
(ulong) addressPXD(&pxdlock->pxd),
lengthPXD(&pxdlock->pxd));
}
/* update bmap */
tlck->flag |= tlckUPDATEMAP;
}
}
/*
* txEA()
*
* function: acquire maplock for EA/ACL extents or
* set COMMIT_INLINE flag;
*/
void txEA(tid_t tid, struct inode *ip, dxd_t * oldea, dxd_t * newea)
{
struct tlock *tlck = NULL;
struct pxd_lock *maplock = NULL, *pxdlock = NULL;
/*
* format maplock for alloc of new EA extent
*/
if (newea) {
/* Since the newea could be a completely zeroed entry we need to
* check for the two flags which indicate we should actually
* commit new EA data
*/
if (newea->flag & DXD_EXTENT) {
tlck = txMaplock(tid, ip, tlckMAP);
maplock = (struct pxd_lock *) & tlck->lock;
pxdlock = (struct pxd_lock *) maplock;
pxdlock->flag = mlckALLOCPXD;
PXDaddress(&pxdlock->pxd, addressDXD(newea));
PXDlength(&pxdlock->pxd, lengthDXD(newea));
pxdlock++;
maplock->index = 1;
} else if (newea->flag & DXD_INLINE) {
tlck = NULL;
set_cflag(COMMIT_Inlineea, ip);
}
}
/*
* format maplock for free of old EA extent
*/
if (!test_cflag(COMMIT_Nolink, ip) && oldea->flag & DXD_EXTENT) {
if (tlck == NULL) {
tlck = txMaplock(tid, ip, tlckMAP);
maplock = (struct pxd_lock *) & tlck->lock;
pxdlock = (struct pxd_lock *) maplock;
maplock->index = 0;
}
pxdlock->flag = mlckFREEPXD;
PXDaddress(&pxdlock->pxd, addressDXD(oldea));
PXDlength(&pxdlock->pxd, lengthDXD(oldea));
maplock->index++;
}
}
/*
* txForce()
*
* function: synchronously write pages locked by transaction
* after txLog() but before txUpdateMap();
*/
static void txForce(struct tblock * tblk)
{
struct tlock *tlck;
lid_t lid, next;
struct metapage *mp;
/*
* reverse the order of transaction tlocks in
* careful update order of address index pages
* (right to left, bottom up)
*/
tlck = lid_to_tlock(tblk->next);
lid = tlck->next;
tlck->next = 0;
while (lid) {
tlck = lid_to_tlock(lid);
next = tlck->next;
tlck->next = tblk->next;
tblk->next = lid;
lid = next;
}
/*
* synchronously write the page, and
* hold the page for txUpdateMap();
*/
for (lid = tblk->next; lid; lid = next) {
tlck = lid_to_tlock(lid);
next = tlck->next;
if ((mp = tlck->mp) != NULL &&
(tlck->type & tlckBTROOT) == 0) {
assert(mp->xflag & COMMIT_PAGE);
if (tlck->flag & tlckWRITEPAGE) {
tlck->flag &= ~tlckWRITEPAGE;
/* do not release page to freelist */
force_metapage(mp);
#if 0
/*
* The "right" thing to do here is to
* synchronously write the metadata.
* With the current implementation this
* is hard since write_metapage requires
* us to kunmap & remap the page. If we
* have tlocks pointing into the metadata
* pages, we don't want to do this. I think
* we can get by with synchronously writing
* the pages when they are released.
*/
assert(mp->nohomeok);
set_bit(META_dirty, &mp->flag);
set_bit(META_sync, &mp->flag);
#endif
}
}
}
}
/*
* txUpdateMap()
*
* function: update persistent allocation map (and working map
* if appropriate);
*
* parameter:
*/
static void txUpdateMap(struct tblock * tblk)
{
struct inode *ip;
struct inode *ipimap;
lid_t lid;
struct tlock *tlck;
struct maplock *maplock;
struct pxd_lock pxdlock;
int maptype;
int k, nlock;
struct metapage *mp = NULL;
ipimap = JFS_SBI(tblk->sb)->ipimap;
maptype = (tblk->xflag & COMMIT_PMAP) ? COMMIT_PMAP : COMMIT_PWMAP;
/*
* update block allocation map
*
* update allocation state in pmap (and wmap) and
* update lsn of the pmap page;
*/
/*
* scan each tlock/page of transaction for block allocation/free:
*
* for each tlock/page of transaction, update map.
* ? are there tlock for pmap and pwmap at the same time ?
*/
for (lid = tblk->next; lid; lid = tlck->next) {
tlck = lid_to_tlock(lid);
if ((tlck->flag & tlckUPDATEMAP) == 0)
continue;
if (tlck->flag & tlckFREEPAGE) {
/*
* Another thread may attempt to reuse freed space
* immediately, so we want to get rid of the metapage
* before anyone else has a chance to get it.
* Lock metapage, update maps, then invalidate
* the metapage.
*/
mp = tlck->mp;
ASSERT(mp->xflag & COMMIT_PAGE);
grab_metapage(mp);
}
/*
* extent list:
* . in-line PXD list:
* . out-of-line XAD list:
*/
maplock = (struct maplock *) & tlck->lock;
nlock = maplock->index;
for (k = 0; k < nlock; k++, maplock++) {
/*
* allocate blocks in persistent map:
*
* blocks have been allocated from wmap at alloc time;
*/
if (maplock->flag & mlckALLOC) {
txAllocPMap(ipimap, maplock, tblk);
}
/*
* free blocks in persistent and working map:
* blocks will be freed in pmap and then in wmap;
*
* ? tblock specifies the PMAP/PWMAP based upon
* transaction
*
* free blocks in persistent map:
* blocks will be freed from wmap at last reference
* release of the object for regular files;
*
* Alway free blocks from both persistent & working
* maps for directories
*/
else { /* (maplock->flag & mlckFREE) */
if (tlck->flag & tlckDIRECTORY)
txFreeMap(ipimap, maplock,
tblk, COMMIT_PWMAP);
else
txFreeMap(ipimap, maplock,
tblk, maptype);
}
}
if (tlck->flag & tlckFREEPAGE) {
if (!(tblk->flag & tblkGC_LAZY)) {
/* This is equivalent to txRelease */
ASSERT(mp->lid == lid);
tlck->mp->lid = 0;
}
assert(mp->nohomeok == 1);
metapage_homeok(mp);
discard_metapage(mp);
tlck->mp = NULL;
}
}
/*
* update inode allocation map
*
* update allocation state in pmap and
* update lsn of the pmap page;
* update in-memory inode flag/state
*
* unlock mapper/write lock
*/
if (tblk->xflag & COMMIT_CREATE) {
diUpdatePMap(ipimap, tblk->ino, false, tblk);
/* update persistent block allocation map
* for the allocation of inode extent;
*/
pxdlock.flag = mlckALLOCPXD;
pxdlock.pxd = tblk->u.ixpxd;
pxdlock.index = 1;
txAllocPMap(ipimap, (struct maplock *) & pxdlock, tblk);
} else if (tblk->xflag & COMMIT_DELETE) {
ip = tblk->u.ip;
diUpdatePMap(ipimap, ip->i_ino, true, tblk);
iput(ip);
}
}
/*
* txAllocPMap()
*
* function: allocate from persistent map;
*
* parameter:
* ipbmap -
* malock -
* xad list:
* pxd:
*
* maptype -
* allocate from persistent map;
* free from persistent map;
* (e.g., tmp file - free from working map at releae
* of last reference);
* free from persistent and working map;
*
* lsn - log sequence number;
*/
static void txAllocPMap(struct inode *ip, struct maplock * maplock,
struct tblock * tblk)
{
struct inode *ipbmap = JFS_SBI(ip->i_sb)->ipbmap;
struct xdlistlock *xadlistlock;
xad_t *xad;
s64 xaddr;
int xlen;
struct pxd_lock *pxdlock;
struct xdlistlock *pxdlistlock;
pxd_t *pxd;
int n;
/*
* allocate from persistent map;
*/
if (maplock->flag & mlckALLOCXADLIST) {
xadlistlock = (struct xdlistlock *) maplock;
xad = xadlistlock->xdlist;
for (n = 0; n < xadlistlock->count; n++, xad++) {
if (xad->flag & (XAD_NEW | XAD_EXTENDED)) {
xaddr = addressXAD(xad);
xlen = lengthXAD(xad);
dbUpdatePMap(ipbmap, false, xaddr,
(s64) xlen, tblk);
xad->flag &= ~(XAD_NEW | XAD_EXTENDED);
jfs_info("allocPMap: xaddr:0x%lx xlen:%d",
(ulong) xaddr, xlen);
}
}
} else if (maplock->flag & mlckALLOCPXD) {
pxdlock = (struct pxd_lock *) maplock;
xaddr = addressPXD(&pxdlock->pxd);
xlen = lengthPXD(&pxdlock->pxd);
dbUpdatePMap(ipbmap, false, xaddr, (s64) xlen, tblk);
jfs_info("allocPMap: xaddr:0x%lx xlen:%d", (ulong) xaddr, xlen);
} else { /* (maplock->flag & mlckALLOCPXDLIST) */
pxdlistlock = (struct xdlistlock *) maplock;
pxd = pxdlistlock->xdlist;
for (n = 0; n < pxdlistlock->count; n++, pxd++) {
xaddr = addressPXD(pxd);
xlen = lengthPXD(pxd);
dbUpdatePMap(ipbmap, false, xaddr, (s64) xlen,
tblk);
jfs_info("allocPMap: xaddr:0x%lx xlen:%d",
(ulong) xaddr, xlen);
}
}
}
/*
* txFreeMap()
*
* function: free from persistent and/or working map;
*
* todo: optimization
*/
void txFreeMap(struct inode *ip,
struct maplock * maplock, struct tblock * tblk, int maptype)
{
struct inode *ipbmap = JFS_SBI(ip->i_sb)->ipbmap;
struct xdlistlock *xadlistlock;
xad_t *xad;
s64 xaddr;
int xlen;
struct pxd_lock *pxdlock;
struct xdlistlock *pxdlistlock;
pxd_t *pxd;
int n;
jfs_info("txFreeMap: tblk:0x%p maplock:0x%p maptype:0x%x",
tblk, maplock, maptype);
/*
* free from persistent map;
*/
if (maptype == COMMIT_PMAP || maptype == COMMIT_PWMAP) {
if (maplock->flag & mlckFREEXADLIST) {
xadlistlock = (struct xdlistlock *) maplock;
xad = xadlistlock->xdlist;
for (n = 0; n < xadlistlock->count; n++, xad++) {
if (!(xad->flag & XAD_NEW)) {
xaddr = addressXAD(xad);
xlen = lengthXAD(xad);
dbUpdatePMap(ipbmap, true, xaddr,
(s64) xlen, tblk);
jfs_info("freePMap: xaddr:0x%lx "
"xlen:%d",
(ulong) xaddr, xlen);
}
}
} else if (maplock->flag & mlckFREEPXD) {
pxdlock = (struct pxd_lock *) maplock;
xaddr = addressPXD(&pxdlock->pxd);
xlen = lengthPXD(&pxdlock->pxd);
dbUpdatePMap(ipbmap, true, xaddr, (s64) xlen,
tblk);
jfs_info("freePMap: xaddr:0x%lx xlen:%d",
(ulong) xaddr, xlen);
} else { /* (maplock->flag & mlckALLOCPXDLIST) */
pxdlistlock = (struct xdlistlock *) maplock;
pxd = pxdlistlock->xdlist;
for (n = 0; n < pxdlistlock->count; n++, pxd++) {
xaddr = addressPXD(pxd);
xlen = lengthPXD(pxd);
dbUpdatePMap(ipbmap, true, xaddr,
(s64) xlen, tblk);
jfs_info("freePMap: xaddr:0x%lx xlen:%d",
(ulong) xaddr, xlen);
}
}
}
/*
* free from working map;
*/
if (maptype == COMMIT_PWMAP || maptype == COMMIT_WMAP) {
if (maplock->flag & mlckFREEXADLIST) {
xadlistlock = (struct xdlistlock *) maplock;
xad = xadlistlock->xdlist;
for (n = 0; n < xadlistlock->count; n++, xad++) {
xaddr = addressXAD(xad);
xlen = lengthXAD(xad);
dbFree(ip, xaddr, (s64) xlen);
xad->flag = 0;
jfs_info("freeWMap: xaddr:0x%lx xlen:%d",
(ulong) xaddr, xlen);
}
} else if (maplock->flag & mlckFREEPXD) {
pxdlock = (struct pxd_lock *) maplock;
xaddr = addressPXD(&pxdlock->pxd);
xlen = lengthPXD(&pxdlock->pxd);
dbFree(ip, xaddr, (s64) xlen);
jfs_info("freeWMap: xaddr:0x%lx xlen:%d",
(ulong) xaddr, xlen);
} else { /* (maplock->flag & mlckFREEPXDLIST) */
pxdlistlock = (struct xdlistlock *) maplock;
pxd = pxdlistlock->xdlist;
for (n = 0; n < pxdlistlock->count; n++, pxd++) {
xaddr = addressPXD(pxd);
xlen = lengthPXD(pxd);
dbFree(ip, xaddr, (s64) xlen);
jfs_info("freeWMap: xaddr:0x%lx xlen:%d",
(ulong) xaddr, xlen);
}
}
}
}
/*
* txFreelock()
*
* function: remove tlock from inode anonymous locklist
*/
void txFreelock(struct inode *ip)
{
struct jfs_inode_info *jfs_ip = JFS_IP(ip);
struct tlock *xtlck, *tlck;
lid_t xlid = 0, lid;
if (!jfs_ip->atlhead)
return;
TXN_LOCK();
xtlck = (struct tlock *) &jfs_ip->atlhead;
while ((lid = xtlck->next) != 0) {
tlck = lid_to_tlock(lid);
if (tlck->flag & tlckFREELOCK) {
xtlck->next = tlck->next;
txLockFree(lid);
} else {
xtlck = tlck;
xlid = lid;
}
}
if (jfs_ip->atlhead)
jfs_ip->atltail = xlid;
else {
jfs_ip->atltail = 0;
/*
* If inode was on anon_list, remove it
*/
list_del_init(&jfs_ip->anon_inode_list);
}
TXN_UNLOCK();
}
/*
* txAbort()
*
* function: abort tx before commit;
*
* frees line-locks and segment locks for all
* segments in comdata structure.
* Optionally sets state of file-system to FM_DIRTY in super-block.
* log age of page-frames in memory for which caller has
* are reset to 0 (to avoid logwarap).
*/
void txAbort(tid_t tid, int dirty)
{
lid_t lid, next;
struct metapage *mp;
struct tblock *tblk = tid_to_tblock(tid);
struct tlock *tlck;
/*
* free tlocks of the transaction
*/
for (lid = tblk->next; lid; lid = next) {
tlck = lid_to_tlock(lid);
next = tlck->next;
mp = tlck->mp;
JFS_IP(tlck->ip)->xtlid = 0;
if (mp) {
mp->lid = 0;
/*
* reset lsn of page to avoid logwarap:
*
* (page may have been previously committed by another
* transaction(s) but has not been paged, i.e.,
* it may be on logsync list even though it has not
* been logged for the current tx.)
*/
if (mp->xflag & COMMIT_PAGE && mp->lsn)
LogSyncRelease(mp);
}
/* insert tlock at head of freelist */
TXN_LOCK();
txLockFree(lid);
TXN_UNLOCK();
}
/* caller will free the transaction block */
tblk->next = tblk->last = 0;
/*
* mark filesystem dirty
*/
if (dirty)
jfs_error(tblk->sb, "txAbort");
return;
}
/*
* txLazyCommit(void)
*
* All transactions except those changing ipimap (COMMIT_FORCE) are
* processed by this routine. This insures that the inode and block
* allocation maps are updated in order. For synchronous transactions,
* let the user thread finish processing after txUpdateMap() is called.
*/
static void txLazyCommit(struct tblock * tblk)
{
struct jfs_log *log;
while (((tblk->flag & tblkGC_READY) == 0) &&
((tblk->flag & tblkGC_UNLOCKED) == 0)) {
/* We must have gotten ahead of the user thread
*/
jfs_info("jfs_lazycommit: tblk 0x%p not unlocked", tblk);
yield();
}
jfs_info("txLazyCommit: processing tblk 0x%p", tblk);
txUpdateMap(tblk);
log = (struct jfs_log *) JFS_SBI(tblk->sb)->log;
spin_lock_irq(&log->gclock); // LOGGC_LOCK
tblk->flag |= tblkGC_COMMITTED;
if (tblk->flag & tblkGC_READY)
log->gcrtc--;
wake_up_all(&tblk->gcwait); // LOGGC_WAKEUP
/*
* Can't release log->gclock until we've tested tblk->flag
*/
if (tblk->flag & tblkGC_LAZY) {
spin_unlock_irq(&log->gclock); // LOGGC_UNLOCK
txUnlock(tblk);
tblk->flag &= ~tblkGC_LAZY;
txEnd(tblk - TxBlock); /* Convert back to tid */
} else
spin_unlock_irq(&log->gclock); // LOGGC_UNLOCK
jfs_info("txLazyCommit: done: tblk = 0x%p", tblk);
}
/*
* jfs_lazycommit(void)
*
* To be run as a kernel daemon. If lbmIODone is called in an interrupt
* context, or where blocking is not wanted, this routine will process
* committed transactions from the unlock queue.
*/
int jfs_lazycommit(void *arg)
{
int WorkDone;
struct tblock *tblk;
unsigned long flags;
struct jfs_sb_info *sbi;
do {
LAZY_LOCK(flags);
jfs_commit_thread_waking = 0; /* OK to wake another thread */
while (!list_empty(&TxAnchor.unlock_queue)) {
WorkDone = 0;
list_for_each_entry(tblk, &TxAnchor.unlock_queue,
cqueue) {
sbi = JFS_SBI(tblk->sb);
/*
* For each volume, the transactions must be
* handled in order. If another commit thread
* is handling a tblk for this superblock,
* skip it
*/
if (sbi->commit_state & IN_LAZYCOMMIT)
continue;
sbi->commit_state |= IN_LAZYCOMMIT;
WorkDone = 1;
/*
* Remove transaction from queue
*/
list_del(&tblk->cqueue);
LAZY_UNLOCK(flags);
txLazyCommit(tblk);
LAZY_LOCK(flags);
sbi->commit_state &= ~IN_LAZYCOMMIT;
/*
* Don't continue in the for loop. (We can't
* anyway, it's unsafe!) We want to go back to
* the beginning of the list.
*/
break;
}
/* If there was nothing to do, don't continue */
if (!WorkDone)
break;
}
/* In case a wakeup came while all threads were active */
jfs_commit_thread_waking = 0;
if (freezing(current)) {
LAZY_UNLOCK(flags);
try_to_freeze();
} else {
DECLARE_WAITQUEUE(wq, current);
add_wait_queue(&jfs_commit_thread_wait, &wq);
set_current_state(TASK_INTERRUPTIBLE);
LAZY_UNLOCK(flags);
schedule();
__set_current_state(TASK_RUNNING);
remove_wait_queue(&jfs_commit_thread_wait, &wq);
}
} while (!kthread_should_stop());
if (!list_empty(&TxAnchor.unlock_queue))
jfs_err("jfs_lazycommit being killed w/pending transactions!");
else
jfs_info("jfs_lazycommit being killed\n");
return 0;
}
void txLazyUnlock(struct tblock * tblk)
{
unsigned long flags;
LAZY_LOCK(flags);
list_add_tail(&tblk->cqueue, &TxAnchor.unlock_queue);
/*
* Don't wake up a commit thread if there is already one servicing
* this superblock, or if the last one we woke up hasn't started yet.
*/
if (!(JFS_SBI(tblk->sb)->commit_state & IN_LAZYCOMMIT) &&
!jfs_commit_thread_waking) {
jfs_commit_thread_waking = 1;
wake_up(&jfs_commit_thread_wait);
}
LAZY_UNLOCK(flags);
}
static void LogSyncRelease(struct metapage * mp)
{
struct jfs_log *log = mp->log;
assert(mp->nohomeok);
assert(log);
metapage_homeok(mp);
}
/*
* txQuiesce
*
* Block all new transactions and push anonymous transactions to
* completion
*
* This does almost the same thing as jfs_sync below. We don't
* worry about deadlocking when jfs_tlocks_low is set, since we would
* expect jfs_sync to get us out of that jam.
*/
void txQuiesce(struct super_block *sb)
{
struct inode *ip;
struct jfs_inode_info *jfs_ip;
struct jfs_log *log = JFS_SBI(sb)->log;
tid_t tid;
set_bit(log_QUIESCE, &log->flag);
TXN_LOCK();
restart:
while (!list_empty(&TxAnchor.anon_list)) {
jfs_ip = list_entry(TxAnchor.anon_list.next,
struct jfs_inode_info,
anon_inode_list);
ip = &jfs_ip->vfs_inode;
/*
* inode will be removed from anonymous list
* when it is committed
*/
TXN_UNLOCK();
tid = txBegin(ip->i_sb, COMMIT_INODE | COMMIT_FORCE);
mutex_lock(&jfs_ip->commit_mutex);
txCommit(tid, 1, &ip, 0);
txEnd(tid);
mutex_unlock(&jfs_ip->commit_mutex);
/*
* Just to be safe. I don't know how
* long we can run without blocking
*/
cond_resched();
TXN_LOCK();
}
/*
* If jfs_sync is running in parallel, there could be some inodes
* on anon_list2. Let's check.
*/
if (!list_empty(&TxAnchor.anon_list2)) {
list_splice(&TxAnchor.anon_list2, &TxAnchor.anon_list);
INIT_LIST_HEAD(&TxAnchor.anon_list2);
goto restart;
}
TXN_UNLOCK();
/*
* We may need to kick off the group commit
*/
jfs_flush_journal(log, 0);
}
/*
* txResume()
*
* Allows transactions to start again following txQuiesce
*/
void txResume(struct super_block *sb)
{
struct jfs_log *log = JFS_SBI(sb)->log;
clear_bit(log_QUIESCE, &log->flag);
TXN_WAKEUP(&log->syncwait);
}
/*
* jfs_sync(void)
*
* To be run as a kernel daemon. This is awakened when tlocks run low.
* We write any inodes that have anonymous tlocks so they will become
* available.
*/
int jfs_sync(void *arg)
{
struct inode *ip;
struct jfs_inode_info *jfs_ip;
tid_t tid;
do {
/*
* write each inode on the anonymous inode list
*/
TXN_LOCK();
while (jfs_tlocks_low && !list_empty(&TxAnchor.anon_list)) {
jfs_ip = list_entry(TxAnchor.anon_list.next,
struct jfs_inode_info,
anon_inode_list);
ip = &jfs_ip->vfs_inode;
if (! igrab(ip)) {
/*
* Inode is being freed
*/
list_del_init(&jfs_ip->anon_inode_list);
} else if (mutex_trylock(&jfs_ip->commit_mutex)) {
/*
* inode will be removed from anonymous list
* when it is committed
*/
TXN_UNLOCK();
tid = txBegin(ip->i_sb, COMMIT_INODE);
txCommit(tid, 1, &ip, 0);
txEnd(tid);
mutex_unlock(&jfs_ip->commit_mutex);
iput(ip);
/*
* Just to be safe. I don't know how
* long we can run without blocking
*/
cond_resched();
TXN_LOCK();
} else {
/* We can't get the commit mutex. It may
* be held by a thread waiting for tlock's
* so let's not block here. Save it to
* put back on the anon_list.
*/
/* Take off anon_list */
list_del(&jfs_ip->anon_inode_list);
/* Put on anon_list2 */
list_add(&jfs_ip->anon_inode_list,
&TxAnchor.anon_list2);
TXN_UNLOCK();
iput(ip);
TXN_LOCK();
}
}
/* Add anon_list2 back to anon_list */
list_splice_init(&TxAnchor.anon_list2, &TxAnchor.anon_list);
if (freezing(current)) {
TXN_UNLOCK();
try_to_freeze();
} else {
set_current_state(TASK_INTERRUPTIBLE);
TXN_UNLOCK();
schedule();
__set_current_state(TASK_RUNNING);
}
} while (!kthread_should_stop());
jfs_info("jfs_sync being killed");
return 0;
}
#if defined(CONFIG_PROC_FS) && defined(CONFIG_JFS_DEBUG)
static int jfs_txanchor_proc_show(struct seq_file *m, void *v)
{
char *freewait;
char *freelockwait;
char *lowlockwait;
freewait =
waitqueue_active(&TxAnchor.freewait) ? "active" : "empty";
freelockwait =
waitqueue_active(&TxAnchor.freelockwait) ? "active" : "empty";
lowlockwait =
waitqueue_active(&TxAnchor.lowlockwait) ? "active" : "empty";
seq_printf(m,
"JFS TxAnchor\n"
"============\n"
"freetid = %d\n"
"freewait = %s\n"
"freelock = %d\n"
"freelockwait = %s\n"
"lowlockwait = %s\n"
"tlocksInUse = %d\n"
"jfs_tlocks_low = %d\n"
"unlock_queue is %sempty\n",
TxAnchor.freetid,
freewait,
TxAnchor.freelock,
freelockwait,
lowlockwait,
TxAnchor.tlocksInUse,
jfs_tlocks_low,
list_empty(&TxAnchor.unlock_queue) ? "" : "not ");
return 0;
}
static int jfs_txanchor_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, jfs_txanchor_proc_show, NULL);
}
const struct file_operations jfs_txanchor_proc_fops = {
.owner = THIS_MODULE,
.open = jfs_txanchor_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
#endif
#if defined(CONFIG_PROC_FS) && defined(CONFIG_JFS_STATISTICS)
static int jfs_txstats_proc_show(struct seq_file *m, void *v)
{
seq_printf(m,
"JFS TxStats\n"
"===========\n"
"calls to txBegin = %d\n"
"txBegin blocked by sync barrier = %d\n"
"txBegin blocked by tlocks low = %d\n"
"txBegin blocked by no free tid = %d\n"
"calls to txBeginAnon = %d\n"
"txBeginAnon blocked by sync barrier = %d\n"
"txBeginAnon blocked by tlocks low = %d\n"
"calls to txLockAlloc = %d\n"
"tLockAlloc blocked by no free lock = %d\n",
TxStat.txBegin,
TxStat.txBegin_barrier,
TxStat.txBegin_lockslow,
TxStat.txBegin_freetid,
TxStat.txBeginAnon,
TxStat.txBeginAnon_barrier,
TxStat.txBeginAnon_lockslow,
TxStat.txLockAlloc,
TxStat.txLockAlloc_freelock);
return 0;
}
static int jfs_txstats_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, jfs_txstats_proc_show, NULL);
}
const struct file_operations jfs_txstats_proc_fops = {
.owner = THIS_MODULE,
.open = jfs_txstats_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
#endif
| gpl-2.0 |
computersforpeace/UBIFS-backports | drivers/gpu/drm/nouveau/nouveau_temp.c | 5489 | 8090 | /*
* Copyright 2010 PathScale inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors: Martin Peres
*/
#include <linux/module.h>
#include "drmP.h"
#include "nouveau_drv.h"
#include "nouveau_pm.h"
static void
nouveau_temp_vbios_parse(struct drm_device *dev, u8 *temp)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_pm_engine *pm = &dev_priv->engine.pm;
struct nouveau_pm_temp_sensor_constants *sensor = &pm->sensor_constants;
struct nouveau_pm_threshold_temp *temps = &pm->threshold_temp;
int i, headerlen, recordlen, entries;
if (!temp) {
NV_DEBUG(dev, "temperature table pointer invalid\n");
return;
}
/* Set the default sensor's contants */
sensor->offset_constant = 0;
sensor->offset_mult = 0;
sensor->offset_div = 1;
sensor->slope_mult = 1;
sensor->slope_div = 1;
/* Set the default temperature thresholds */
temps->critical = 110;
temps->down_clock = 100;
temps->fan_boost = 90;
/* Set the default range for the pwm fan */
pm->fan.min_duty = 30;
pm->fan.max_duty = 100;
/* Set the known default values to setup the temperature sensor */
if (dev_priv->card_type >= NV_40) {
switch (dev_priv->chipset) {
case 0x43:
sensor->offset_mult = 32060;
sensor->offset_div = 1000;
sensor->slope_mult = 792;
sensor->slope_div = 1000;
break;
case 0x44:
case 0x47:
case 0x4a:
sensor->offset_mult = 27839;
sensor->offset_div = 1000;
sensor->slope_mult = 780;
sensor->slope_div = 1000;
break;
case 0x46:
sensor->offset_mult = -24775;
sensor->offset_div = 100;
sensor->slope_mult = 467;
sensor->slope_div = 10000;
break;
case 0x49:
sensor->offset_mult = -25051;
sensor->offset_div = 100;
sensor->slope_mult = 458;
sensor->slope_div = 10000;
break;
case 0x4b:
sensor->offset_mult = -24088;
sensor->offset_div = 100;
sensor->slope_mult = 442;
sensor->slope_div = 10000;
break;
case 0x50:
sensor->offset_mult = -22749;
sensor->offset_div = 100;
sensor->slope_mult = 431;
sensor->slope_div = 10000;
break;
case 0x67:
sensor->offset_mult = -26149;
sensor->offset_div = 100;
sensor->slope_mult = 484;
sensor->slope_div = 10000;
break;
}
}
headerlen = temp[1];
recordlen = temp[2];
entries = temp[3];
temp = temp + headerlen;
/* Read the entries from the table */
for (i = 0; i < entries; i++) {
s16 value = ROM16(temp[1]);
switch (temp[0]) {
case 0x01:
if ((value & 0x8f) == 0)
sensor->offset_constant = (value >> 9) & 0x7f;
break;
case 0x04:
if ((value & 0xf00f) == 0xa000) /* core */
temps->critical = (value&0x0ff0) >> 4;
break;
case 0x07:
if ((value & 0xf00f) == 0xa000) /* core */
temps->down_clock = (value&0x0ff0) >> 4;
break;
case 0x08:
if ((value & 0xf00f) == 0xa000) /* core */
temps->fan_boost = (value&0x0ff0) >> 4;
break;
case 0x10:
sensor->offset_mult = value;
break;
case 0x11:
sensor->offset_div = value;
break;
case 0x12:
sensor->slope_mult = value;
break;
case 0x13:
sensor->slope_div = value;
break;
case 0x22:
pm->fan.min_duty = value & 0xff;
pm->fan.max_duty = (value & 0xff00) >> 8;
break;
case 0x26:
pm->fan.pwm_freq = value;
break;
}
temp += recordlen;
}
nouveau_temp_safety_checks(dev);
/* check the fan min/max settings */
if (pm->fan.min_duty < 10)
pm->fan.min_duty = 10;
if (pm->fan.max_duty > 100)
pm->fan.max_duty = 100;
if (pm->fan.max_duty < pm->fan.min_duty)
pm->fan.max_duty = pm->fan.min_duty;
}
static int
nv40_sensor_setup(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_pm_engine *pm = &dev_priv->engine.pm;
struct nouveau_pm_temp_sensor_constants *sensor = &pm->sensor_constants;
s32 offset = sensor->offset_mult / sensor->offset_div;
s32 sensor_calibration;
/* set up the sensors */
sensor_calibration = 120 - offset - sensor->offset_constant;
sensor_calibration = sensor_calibration * sensor->slope_div /
sensor->slope_mult;
if (dev_priv->chipset >= 0x46)
sensor_calibration |= 0x80000000;
else
sensor_calibration |= 0x10000000;
nv_wr32(dev, 0x0015b0, sensor_calibration);
/* Wait for the sensor to update */
msleep(5);
/* read */
return nv_rd32(dev, 0x0015b4) & 0x1fff;
}
int
nv40_temp_get(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_pm_engine *pm = &dev_priv->engine.pm;
struct nouveau_pm_temp_sensor_constants *sensor = &pm->sensor_constants;
int offset = sensor->offset_mult / sensor->offset_div;
int core_temp;
if (dev_priv->card_type >= NV_50) {
core_temp = nv_rd32(dev, 0x20008);
} else {
core_temp = nv_rd32(dev, 0x0015b4) & 0x1fff;
/* Setup the sensor if the temperature is 0 */
if (core_temp == 0)
core_temp = nv40_sensor_setup(dev);
}
core_temp = core_temp * sensor->slope_mult / sensor->slope_div;
core_temp = core_temp + offset + sensor->offset_constant;
return core_temp;
}
int
nv84_temp_get(struct drm_device *dev)
{
return nv_rd32(dev, 0x20400);
}
void
nouveau_temp_safety_checks(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_pm_engine *pm = &dev_priv->engine.pm;
struct nouveau_pm_threshold_temp *temps = &pm->threshold_temp;
if (temps->critical > 120)
temps->critical = 120;
else if (temps->critical < 80)
temps->critical = 80;
if (temps->down_clock > 110)
temps->down_clock = 110;
else if (temps->down_clock < 60)
temps->down_clock = 60;
if (temps->fan_boost > 100)
temps->fan_boost = 100;
else if (temps->fan_boost < 40)
temps->fan_boost = 40;
}
static bool
probe_monitoring_device(struct nouveau_i2c_chan *i2c,
struct i2c_board_info *info)
{
struct i2c_client *client;
request_module("%s%s", I2C_MODULE_PREFIX, info->type);
client = i2c_new_device(&i2c->adapter, info);
if (!client)
return false;
if (!client->driver || client->driver->detect(client, info)) {
i2c_unregister_device(client);
return false;
}
return true;
}
static void
nouveau_temp_probe_i2c(struct drm_device *dev)
{
struct i2c_board_info info[] = {
{ I2C_BOARD_INFO("w83l785ts", 0x2d) },
{ I2C_BOARD_INFO("w83781d", 0x2d) },
{ I2C_BOARD_INFO("adt7473", 0x2e) },
{ I2C_BOARD_INFO("f75375", 0x2e) },
{ I2C_BOARD_INFO("lm99", 0x4c) },
{ }
};
nouveau_i2c_identify(dev, "monitoring device", info,
probe_monitoring_device, NV_I2C_DEFAULT(0));
}
void
nouveau_temp_init(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nvbios *bios = &dev_priv->vbios;
struct bit_entry P;
u8 *temp = NULL;
if (bios->type == NVBIOS_BIT) {
if (bit_table(dev, 'P', &P))
return;
if (P.version == 1)
temp = ROMPTR(dev, P.data[12]);
else if (P.version == 2)
temp = ROMPTR(dev, P.data[16]);
else
NV_WARN(dev, "unknown temp for BIT P %d\n", P.version);
nouveau_temp_vbios_parse(dev, temp);
}
nouveau_temp_probe_i2c(dev);
}
void
nouveau_temp_fini(struct drm_device *dev)
{
}
| gpl-2.0 |
KonstaT/android_kernel_zte_msm7x27a | fs/nilfs2/direct.c | 11633 | 9161 | /*
* direct.c - NILFS direct block pointer.
*
* Copyright (C) 2006-2008 Nippon Telegraph and Telephone Corporation.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Written by Koji Sato <koji@osrg.net>.
*/
#include <linux/errno.h>
#include "nilfs.h"
#include "page.h"
#include "direct.h"
#include "alloc.h"
#include "dat.h"
static inline __le64 *nilfs_direct_dptrs(const struct nilfs_bmap *direct)
{
return (__le64 *)
((struct nilfs_direct_node *)direct->b_u.u_data + 1);
}
static inline __u64
nilfs_direct_get_ptr(const struct nilfs_bmap *direct, __u64 key)
{
return le64_to_cpu(*(nilfs_direct_dptrs(direct) + key));
}
static inline void nilfs_direct_set_ptr(struct nilfs_bmap *direct,
__u64 key, __u64 ptr)
{
*(nilfs_direct_dptrs(direct) + key) = cpu_to_le64(ptr);
}
static int nilfs_direct_lookup(const struct nilfs_bmap *direct,
__u64 key, int level, __u64 *ptrp)
{
__u64 ptr;
if (key > NILFS_DIRECT_KEY_MAX || level != 1)
return -ENOENT;
ptr = nilfs_direct_get_ptr(direct, key);
if (ptr == NILFS_BMAP_INVALID_PTR)
return -ENOENT;
*ptrp = ptr;
return 0;
}
static int nilfs_direct_lookup_contig(const struct nilfs_bmap *direct,
__u64 key, __u64 *ptrp,
unsigned maxblocks)
{
struct inode *dat = NULL;
__u64 ptr, ptr2;
sector_t blocknr;
int ret, cnt;
if (key > NILFS_DIRECT_KEY_MAX)
return -ENOENT;
ptr = nilfs_direct_get_ptr(direct, key);
if (ptr == NILFS_BMAP_INVALID_PTR)
return -ENOENT;
if (NILFS_BMAP_USE_VBN(direct)) {
dat = nilfs_bmap_get_dat(direct);
ret = nilfs_dat_translate(dat, ptr, &blocknr);
if (ret < 0)
return ret;
ptr = blocknr;
}
maxblocks = min_t(unsigned, maxblocks, NILFS_DIRECT_KEY_MAX - key + 1);
for (cnt = 1; cnt < maxblocks &&
(ptr2 = nilfs_direct_get_ptr(direct, key + cnt)) !=
NILFS_BMAP_INVALID_PTR;
cnt++) {
if (dat) {
ret = nilfs_dat_translate(dat, ptr2, &blocknr);
if (ret < 0)
return ret;
ptr2 = blocknr;
}
if (ptr2 != ptr + cnt)
break;
}
*ptrp = ptr;
return cnt;
}
static __u64
nilfs_direct_find_target_v(const struct nilfs_bmap *direct, __u64 key)
{
__u64 ptr;
ptr = nilfs_bmap_find_target_seq(direct, key);
if (ptr != NILFS_BMAP_INVALID_PTR)
/* sequential access */
return ptr;
else
/* block group */
return nilfs_bmap_find_target_in_group(direct);
}
static int nilfs_direct_insert(struct nilfs_bmap *bmap, __u64 key, __u64 ptr)
{
union nilfs_bmap_ptr_req req;
struct inode *dat = NULL;
struct buffer_head *bh;
int ret;
if (key > NILFS_DIRECT_KEY_MAX)
return -ENOENT;
if (nilfs_direct_get_ptr(bmap, key) != NILFS_BMAP_INVALID_PTR)
return -EEXIST;
if (NILFS_BMAP_USE_VBN(bmap)) {
req.bpr_ptr = nilfs_direct_find_target_v(bmap, key);
dat = nilfs_bmap_get_dat(bmap);
}
ret = nilfs_bmap_prepare_alloc_ptr(bmap, &req, dat);
if (!ret) {
/* ptr must be a pointer to a buffer head. */
bh = (struct buffer_head *)((unsigned long)ptr);
set_buffer_nilfs_volatile(bh);
nilfs_bmap_commit_alloc_ptr(bmap, &req, dat);
nilfs_direct_set_ptr(bmap, key, req.bpr_ptr);
if (!nilfs_bmap_dirty(bmap))
nilfs_bmap_set_dirty(bmap);
if (NILFS_BMAP_USE_VBN(bmap))
nilfs_bmap_set_target_v(bmap, key, req.bpr_ptr);
nilfs_inode_add_blocks(bmap->b_inode, 1);
}
return ret;
}
static int nilfs_direct_delete(struct nilfs_bmap *bmap, __u64 key)
{
union nilfs_bmap_ptr_req req;
struct inode *dat;
int ret;
if (key > NILFS_DIRECT_KEY_MAX ||
nilfs_direct_get_ptr(bmap, key) == NILFS_BMAP_INVALID_PTR)
return -ENOENT;
dat = NILFS_BMAP_USE_VBN(bmap) ? nilfs_bmap_get_dat(bmap) : NULL;
req.bpr_ptr = nilfs_direct_get_ptr(bmap, key);
ret = nilfs_bmap_prepare_end_ptr(bmap, &req, dat);
if (!ret) {
nilfs_bmap_commit_end_ptr(bmap, &req, dat);
nilfs_direct_set_ptr(bmap, key, NILFS_BMAP_INVALID_PTR);
nilfs_inode_sub_blocks(bmap->b_inode, 1);
}
return ret;
}
static int nilfs_direct_last_key(const struct nilfs_bmap *direct, __u64 *keyp)
{
__u64 key, lastkey;
lastkey = NILFS_DIRECT_KEY_MAX + 1;
for (key = NILFS_DIRECT_KEY_MIN; key <= NILFS_DIRECT_KEY_MAX; key++)
if (nilfs_direct_get_ptr(direct, key) !=
NILFS_BMAP_INVALID_PTR)
lastkey = key;
if (lastkey == NILFS_DIRECT_KEY_MAX + 1)
return -ENOENT;
*keyp = lastkey;
return 0;
}
static int nilfs_direct_check_insert(const struct nilfs_bmap *bmap, __u64 key)
{
return key > NILFS_DIRECT_KEY_MAX;
}
static int nilfs_direct_gather_data(struct nilfs_bmap *direct,
__u64 *keys, __u64 *ptrs, int nitems)
{
__u64 key;
__u64 ptr;
int n;
if (nitems > NILFS_DIRECT_NBLOCKS)
nitems = NILFS_DIRECT_NBLOCKS;
n = 0;
for (key = 0; key < nitems; key++) {
ptr = nilfs_direct_get_ptr(direct, key);
if (ptr != NILFS_BMAP_INVALID_PTR) {
keys[n] = key;
ptrs[n] = ptr;
n++;
}
}
return n;
}
int nilfs_direct_delete_and_convert(struct nilfs_bmap *bmap,
__u64 key, __u64 *keys, __u64 *ptrs, int n)
{
__le64 *dptrs;
int ret, i, j;
/* no need to allocate any resource for conversion */
/* delete */
ret = bmap->b_ops->bop_delete(bmap, key);
if (ret < 0)
return ret;
/* free resources */
if (bmap->b_ops->bop_clear != NULL)
bmap->b_ops->bop_clear(bmap);
/* convert */
dptrs = nilfs_direct_dptrs(bmap);
for (i = 0, j = 0; i < NILFS_DIRECT_NBLOCKS; i++) {
if ((j < n) && (i == keys[j])) {
dptrs[i] = (i != key) ?
cpu_to_le64(ptrs[j]) :
NILFS_BMAP_INVALID_PTR;
j++;
} else
dptrs[i] = NILFS_BMAP_INVALID_PTR;
}
nilfs_direct_init(bmap);
return 0;
}
static int nilfs_direct_propagate(struct nilfs_bmap *bmap,
struct buffer_head *bh)
{
struct nilfs_palloc_req oldreq, newreq;
struct inode *dat;
__u64 key;
__u64 ptr;
int ret;
if (!NILFS_BMAP_USE_VBN(bmap))
return 0;
dat = nilfs_bmap_get_dat(bmap);
key = nilfs_bmap_data_get_key(bmap, bh);
ptr = nilfs_direct_get_ptr(bmap, key);
if (!buffer_nilfs_volatile(bh)) {
oldreq.pr_entry_nr = ptr;
newreq.pr_entry_nr = ptr;
ret = nilfs_dat_prepare_update(dat, &oldreq, &newreq);
if (ret < 0)
return ret;
nilfs_dat_commit_update(dat, &oldreq, &newreq,
bmap->b_ptr_type == NILFS_BMAP_PTR_VS);
set_buffer_nilfs_volatile(bh);
nilfs_direct_set_ptr(bmap, key, newreq.pr_entry_nr);
} else
ret = nilfs_dat_mark_dirty(dat, ptr);
return ret;
}
static int nilfs_direct_assign_v(struct nilfs_bmap *direct,
__u64 key, __u64 ptr,
struct buffer_head **bh,
sector_t blocknr,
union nilfs_binfo *binfo)
{
struct inode *dat = nilfs_bmap_get_dat(direct);
union nilfs_bmap_ptr_req req;
int ret;
req.bpr_ptr = ptr;
ret = nilfs_dat_prepare_start(dat, &req.bpr_req);
if (!ret) {
nilfs_dat_commit_start(dat, &req.bpr_req, blocknr);
binfo->bi_v.bi_vblocknr = cpu_to_le64(ptr);
binfo->bi_v.bi_blkoff = cpu_to_le64(key);
}
return ret;
}
static int nilfs_direct_assign_p(struct nilfs_bmap *direct,
__u64 key, __u64 ptr,
struct buffer_head **bh,
sector_t blocknr,
union nilfs_binfo *binfo)
{
nilfs_direct_set_ptr(direct, key, blocknr);
binfo->bi_dat.bi_blkoff = cpu_to_le64(key);
binfo->bi_dat.bi_level = 0;
return 0;
}
static int nilfs_direct_assign(struct nilfs_bmap *bmap,
struct buffer_head **bh,
sector_t blocknr,
union nilfs_binfo *binfo)
{
__u64 key;
__u64 ptr;
key = nilfs_bmap_data_get_key(bmap, *bh);
if (unlikely(key > NILFS_DIRECT_KEY_MAX)) {
printk(KERN_CRIT "%s: invalid key: %llu\n", __func__,
(unsigned long long)key);
return -EINVAL;
}
ptr = nilfs_direct_get_ptr(bmap, key);
if (unlikely(ptr == NILFS_BMAP_INVALID_PTR)) {
printk(KERN_CRIT "%s: invalid pointer: %llu\n", __func__,
(unsigned long long)ptr);
return -EINVAL;
}
return NILFS_BMAP_USE_VBN(bmap) ?
nilfs_direct_assign_v(bmap, key, ptr, bh, blocknr, binfo) :
nilfs_direct_assign_p(bmap, key, ptr, bh, blocknr, binfo);
}
static const struct nilfs_bmap_operations nilfs_direct_ops = {
.bop_lookup = nilfs_direct_lookup,
.bop_lookup_contig = nilfs_direct_lookup_contig,
.bop_insert = nilfs_direct_insert,
.bop_delete = nilfs_direct_delete,
.bop_clear = NULL,
.bop_propagate = nilfs_direct_propagate,
.bop_lookup_dirty_buffers = NULL,
.bop_assign = nilfs_direct_assign,
.bop_mark = NULL,
.bop_last_key = nilfs_direct_last_key,
.bop_check_insert = nilfs_direct_check_insert,
.bop_check_delete = NULL,
.bop_gather_data = nilfs_direct_gather_data,
};
int nilfs_direct_init(struct nilfs_bmap *bmap)
{
bmap->b_ops = &nilfs_direct_ops;
return 0;
}
| gpl-2.0 |
zjgeer/linux-80211n-csitool | arch/mn10300/kernel/rtc.c | 11889 | 3963 | /* MN10300 RTC management
*
* Copyright (C) 2007 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public Licence
* as published by the Free Software Foundation; either version
* 2 of the Licence, or (at your option) any later version.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/mc146818rtc.h>
#include <linux/bcd.h>
#include <linux/timex.h>
#include <asm/rtc-regs.h>
#include <asm/rtc.h>
DEFINE_SPINLOCK(rtc_lock);
EXPORT_SYMBOL(rtc_lock);
/*
* Read the current RTC time
*/
void read_persistent_clock(struct timespec *ts)
{
struct rtc_time tm;
get_rtc_time(&tm);
ts->tv_nsec = 0;
ts->tv_sec = mktime(tm.tm_year, tm.tm_mon, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec);
/* if rtc is way off in the past, set something reasonable */
if (ts->tv_sec < 0)
ts->tv_sec = mktime(2009, 1, 1, 12, 0, 0);
}
/*
* In order to set the CMOS clock precisely, set_rtc_mmss has to be called 500
* ms after the second nowtime has started, because when nowtime is written
* into the registers of the CMOS clock, it will jump to the next second
* precisely 500 ms later. Check the Motorola MC146818A or Dallas DS12887 data
* sheet for details.
*
* BUG: This routine does not handle hour overflow properly; it just
* sets the minutes. Usually you'll only notice that after reboot!
*/
static int set_rtc_mmss(unsigned long nowtime)
{
unsigned char save_control, save_freq_select;
int retval = 0;
int real_seconds, real_minutes, cmos_minutes;
/* gets recalled with irq locally disabled */
spin_lock(&rtc_lock);
save_control = CMOS_READ(RTC_CONTROL); /* tell the clock it's being
* set */
CMOS_WRITE(save_control | RTC_SET, RTC_CONTROL);
save_freq_select = CMOS_READ(RTC_FREQ_SELECT); /* stop and reset
* prescaler */
CMOS_WRITE(save_freq_select | RTC_DIV_RESET2, RTC_FREQ_SELECT);
cmos_minutes = CMOS_READ(RTC_MINUTES);
if (!(save_control & RTC_DM_BINARY) || RTC_ALWAYS_BCD)
cmos_minutes = bcd2bin(cmos_minutes);
/*
* since we're only adjusting minutes and seconds,
* don't interfere with hour overflow. This avoids
* messing with unknown time zones but requires your
* RTC not to be off by more than 15 minutes
*/
real_seconds = nowtime % 60;
real_minutes = nowtime / 60;
if (((abs(real_minutes - cmos_minutes) + 15) / 30) & 1)
/* correct for half hour time zone */
real_minutes += 30;
real_minutes %= 60;
if (abs(real_minutes - cmos_minutes) < 30) {
if (!(save_control & RTC_DM_BINARY) || RTC_ALWAYS_BCD) {
real_seconds = bin2bcd(real_seconds);
real_minutes = bin2bcd(real_minutes);
}
CMOS_WRITE(real_seconds, RTC_SECONDS);
CMOS_WRITE(real_minutes, RTC_MINUTES);
} else {
printk_once(KERN_NOTICE
"set_rtc_mmss: can't update from %d to %d\n",
cmos_minutes, real_minutes);
retval = -1;
}
/* The following flags have to be released exactly in this order,
* otherwise the DS12887 (popular MC146818A clone with integrated
* battery and quartz) will not reset the oscillator and will not
* update precisely 500 ms later. You won't find this mentioned in
* the Dallas Semiconductor data sheets, but who believes data
* sheets anyway ... -- Markus Kuhn
*/
CMOS_WRITE(save_control, RTC_CONTROL);
CMOS_WRITE(save_freq_select, RTC_FREQ_SELECT);
spin_unlock(&rtc_lock);
return retval;
}
int update_persistent_clock(struct timespec now)
{
return set_rtc_mmss(now.tv_sec);
}
/*
* calibrate the TSC clock against the RTC
*/
void __init calibrate_clock(void)
{
unsigned char status;
/* make sure the RTC is running and is set to operate in 24hr mode */
status = RTSRC;
RTCRB |= RTCRB_SET;
RTCRB |= RTCRB_TM_24HR;
RTCRB &= ~RTCRB_DM_BINARY;
RTCRA |= RTCRA_DVR;
RTCRA &= ~RTCRA_DVR;
RTCRB &= ~RTCRB_SET;
}
| gpl-2.0 |
hiteshradia/android_kernel_Lenovo_Kraft_A6000 | drivers/input/mouse/touchkit_ps2.c | 13169 | 3147 | /* ----------------------------------------------------------------------------
* touchkit_ps2.c -- Driver for eGalax TouchKit PS/2 Touchscreens
*
* Copyright (C) 2005 by Stefan Lucke
* Copyright (C) 2004 by Daniel Ritz
* Copyright (C) by Todd E. Johnson (mtouchusb.c)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* 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.
*
* Based upon touchkitusb.c
*
* Vendor documentation is available at:
* http://home.eeti.com.tw/web20/drivers/Software%20Programming%20Guide_v2.0.pdf
*/
#include <linux/kernel.h>
#include <linux/input.h>
#include <linux/serio.h>
#include <linux/libps2.h>
#include "psmouse.h"
#include "touchkit_ps2.h"
#define TOUCHKIT_MAX_XC 0x07ff
#define TOUCHKIT_MAX_YC 0x07ff
#define TOUCHKIT_CMD 0x0a
#define TOUCHKIT_CMD_LENGTH 1
#define TOUCHKIT_CMD_ACTIVE 'A'
#define TOUCHKIT_CMD_FIRMWARE_VERSION 'D'
#define TOUCHKIT_CMD_CONTROLLER_TYPE 'E'
#define TOUCHKIT_SEND_PARMS(s, r, c) ((s) << 12 | (r) << 8 | (c))
#define TOUCHKIT_GET_TOUCHED(packet) (((packet)[0]) & 0x01)
#define TOUCHKIT_GET_X(packet) (((packet)[1] << 7) | (packet)[2])
#define TOUCHKIT_GET_Y(packet) (((packet)[3] << 7) | (packet)[4])
static psmouse_ret_t touchkit_ps2_process_byte(struct psmouse *psmouse)
{
unsigned char *packet = psmouse->packet;
struct input_dev *dev = psmouse->dev;
if (psmouse->pktcnt != 5)
return PSMOUSE_GOOD_DATA;
input_report_abs(dev, ABS_X, TOUCHKIT_GET_X(packet));
input_report_abs(dev, ABS_Y, TOUCHKIT_GET_Y(packet));
input_report_key(dev, BTN_TOUCH, TOUCHKIT_GET_TOUCHED(packet));
input_sync(dev);
return PSMOUSE_FULL_PACKET;
}
int touchkit_ps2_detect(struct psmouse *psmouse, bool set_properties)
{
struct input_dev *dev = psmouse->dev;
unsigned char param[3];
int command;
param[0] = TOUCHKIT_CMD_LENGTH;
param[1] = TOUCHKIT_CMD_ACTIVE;
command = TOUCHKIT_SEND_PARMS(2, 3, TOUCHKIT_CMD);
if (ps2_command(&psmouse->ps2dev, param, command))
return -ENODEV;
if (param[0] != TOUCHKIT_CMD || param[1] != 0x01 ||
param[2] != TOUCHKIT_CMD_ACTIVE)
return -ENODEV;
if (set_properties) {
dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
dev->keybit[BIT_WORD(BTN_MOUSE)] = 0;
dev->keybit[BIT_WORD(BTN_TOUCH)] = BIT_MASK(BTN_TOUCH);
input_set_abs_params(dev, ABS_X, 0, TOUCHKIT_MAX_XC, 0, 0);
input_set_abs_params(dev, ABS_Y, 0, TOUCHKIT_MAX_YC, 0, 0);
psmouse->vendor = "eGalax";
psmouse->name = "Touchscreen";
psmouse->protocol_handler = touchkit_ps2_process_byte;
psmouse->pktsize = 5;
}
return 0;
}
| gpl-2.0 |
digsig-ng/linux-digsig | arch/mips/cobalt/pci.c | 13937 | 1194 | /*
* Register PCI controller.
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*
* Copyright (C) 1996, 1997, 2004, 05 by Ralf Baechle (ralf@linux-mips.org)
* Copyright (C) 2001, 2002, 2003 by Liam Davies (ldavies@agile.tv)
*
*/
#include <linux/init.h>
#include <linux/pci.h>
#include <asm/gt64120.h>
extern struct pci_ops gt64xxx_pci0_ops;
static struct resource cobalt_mem_resource = {
.start = GT_DEF_PCI0_MEM0_BASE,
.end = GT_DEF_PCI0_MEM0_BASE + GT_DEF_PCI0_MEM0_SIZE - 1,
.name = "PCI memory",
.flags = IORESOURCE_MEM,
};
static struct resource cobalt_io_resource = {
.start = 0x1000,
.end = 0xffffffUL,
.name = "PCI I/O",
.flags = IORESOURCE_IO,
};
static struct pci_controller cobalt_pci_controller = {
.pci_ops = >64xxx_pci0_ops,
.mem_resource = &cobalt_mem_resource,
.io_resource = &cobalt_io_resource,
.io_offset = 0 - GT_DEF_PCI0_IO_BASE,
.io_map_base = CKSEG1ADDR(GT_DEF_PCI0_IO_BASE),
};
static int __init cobalt_pci_init(void)
{
register_pci_controller(&cobalt_pci_controller);
return 0;
}
arch_initcall(cobalt_pci_init);
| gpl-2.0 |
evilp/android_kernel_hp_phobos | drivers/macintosh/windfarm_pid.c | 14961 | 3751 | /*
* Windfarm PowerMac thermal control. Generic PID helpers
*
* (c) Copyright 2005 Benjamin Herrenschmidt, IBM Corp.
* <benh@kernel.crashing.org>
*
* Released under the term of the GNU GPL v2.
*/
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/module.h>
#include "windfarm_pid.h"
#undef DEBUG
#ifdef DEBUG
#define DBG(args...) printk(args)
#else
#define DBG(args...) do { } while(0)
#endif
void wf_pid_init(struct wf_pid_state *st, struct wf_pid_param *param)
{
memset(st, 0, sizeof(struct wf_pid_state));
st->param = *param;
st->first = 1;
}
EXPORT_SYMBOL_GPL(wf_pid_init);
s32 wf_pid_run(struct wf_pid_state *st, s32 new_sample)
{
s64 error, integ, deriv;
s32 target;
int i, hlen = st->param.history_len;
/* Calculate error term */
error = new_sample - st->param.itarget;
/* Get samples into our history buffer */
if (st->first) {
for (i = 0; i < hlen; i++) {
st->samples[i] = new_sample;
st->errors[i] = error;
}
st->first = 0;
st->index = 0;
} else {
st->index = (st->index + 1) % hlen;
st->samples[st->index] = new_sample;
st->errors[st->index] = error;
}
/* Calculate integral term */
for (i = 0, integ = 0; i < hlen; i++)
integ += st->errors[(st->index + hlen - i) % hlen];
integ *= st->param.interval;
/* Calculate derivative term */
deriv = st->errors[st->index] -
st->errors[(st->index + hlen - 1) % hlen];
deriv /= st->param.interval;
/* Calculate target */
target = (s32)((integ * (s64)st->param.gr + deriv * (s64)st->param.gd +
error * (s64)st->param.gp) >> 36);
if (st->param.additive)
target += st->target;
target = max(target, st->param.min);
target = min(target, st->param.max);
st->target = target;
return st->target;
}
EXPORT_SYMBOL_GPL(wf_pid_run);
void wf_cpu_pid_init(struct wf_cpu_pid_state *st,
struct wf_cpu_pid_param *param)
{
memset(st, 0, sizeof(struct wf_cpu_pid_state));
st->param = *param;
st->first = 1;
}
EXPORT_SYMBOL_GPL(wf_cpu_pid_init);
s32 wf_cpu_pid_run(struct wf_cpu_pid_state *st, s32 new_power, s32 new_temp)
{
s64 integ, deriv, prop;
s32 error, target, sval, adj;
int i, hlen = st->param.history_len;
/* Calculate error term */
error = st->param.pmaxadj - new_power;
/* Get samples into our history buffer */
if (st->first) {
for (i = 0; i < hlen; i++) {
st->powers[i] = new_power;
st->errors[i] = error;
}
st->temps[0] = st->temps[1] = new_temp;
st->first = 0;
st->index = st->tindex = 0;
} else {
st->index = (st->index + 1) % hlen;
st->powers[st->index] = new_power;
st->errors[st->index] = error;
st->tindex = (st->tindex + 1) % 2;
st->temps[st->tindex] = new_temp;
}
/* Calculate integral term */
for (i = 0, integ = 0; i < hlen; i++)
integ += st->errors[(st->index + hlen - i) % hlen];
integ *= st->param.interval;
integ *= st->param.gr;
sval = st->param.tmax - (s32)(integ >> 20);
adj = min(st->param.ttarget, sval);
DBG("integ: %lx, sval: %lx, adj: %lx\n", integ, sval, adj);
/* Calculate derivative term */
deriv = st->temps[st->tindex] -
st->temps[(st->tindex + 2 - 1) % 2];
deriv /= st->param.interval;
deriv *= st->param.gd;
/* Calculate proportional term */
prop = st->last_delta = (new_temp - adj);
prop *= st->param.gp;
DBG("deriv: %lx, prop: %lx\n", deriv, prop);
/* Calculate target */
target = st->target + (s32)((deriv + prop) >> 36);
target = max(target, st->param.min);
target = min(target, st->param.max);
st->target = target;
return st->target;
}
EXPORT_SYMBOL_GPL(wf_cpu_pid_run);
MODULE_AUTHOR("Benjamin Herrenschmidt <benh@kernel.crashing.org>");
MODULE_DESCRIPTION("PID algorithm for PowerMacs thermal control");
MODULE_LICENSE("GPL");
| gpl-2.0 |
kykdev/lolliwiz_lentislte | drivers/mfd/max77803-irq.c | 114 | 11530 | /*
* max77803-irq.c - Interrupt controller support for MAX77803
*
* Copyright (C) 2011 Samsung Electronics Co.Ltd
* SangYoung Son <hello.son@samsung.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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
*
* This driver is based on max77803-irq.c
*/
#include <linux/err.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <linux/gpio.h>
#include <linux/mfd/max77803.h>
#include <linux/mfd/max77803-private.h>
static const u8 max77803_mask_reg[] = {
[LED_INT] = MAX77803_LED_REG_FLASH_INT_MASK,
[TOPSYS_INT] = MAX77803_PMIC_REG_TOPSYS_INT_MASK,
[CHG_INT] = MAX77803_CHG_REG_CHG_INT_MASK,
[MUIC_INT1] = MAX77803_MUIC_REG_INTMASK1,
[MUIC_INT2] = MAX77803_MUIC_REG_INTMASK2,
[MUIC_INT3] = MAX77803_MUIC_REG_INTMASK3,
};
static struct i2c_client *get_i2c(struct max77803_dev *max77803,
enum max77803_irq_source src)
{
switch (src) {
case LED_INT ... CHG_INT:
return max77803->i2c;
case MUIC_INT1 ... MUIC_INT3:
return max77803->muic;
default:
return ERR_PTR(-EINVAL);
}
}
struct max77803_irq_data {
int mask;
enum max77803_irq_source group;
};
#define DECLARE_IRQ(idx, _group, _mask) \
[(idx)] = { .group = (_group), .mask = (_mask) }
static const struct max77803_irq_data max77803_irqs[] = {
DECLARE_IRQ(MAX77803_LED_IRQ_FLED2_OPEN, LED_INT, 1 << 0),
DECLARE_IRQ(MAX77803_LED_IRQ_FLED2_SHORT, LED_INT, 1 << 1),
DECLARE_IRQ(MAX77803_LED_IRQ_FLED1_OPEN, LED_INT, 1 << 2),
DECLARE_IRQ(MAX77803_LED_IRQ_FLED1_SHORT, LED_INT, 1 << 3),
DECLARE_IRQ(MAX77803_LED_IRQ_MAX_FLASH, LED_INT, 1 << 4),
DECLARE_IRQ(MAX77803_TOPSYS_IRQ_T120C_INT, TOPSYS_INT, 1 << 0),
DECLARE_IRQ(MAX77803_TOPSYS_IRQ_T140C_INT, TOPSYS_INT, 1 << 1),
DECLARE_IRQ(MAX77803_TOPSYS_IRQLOWSYS_INT, TOPSYS_INT, 1 << 3),
DECLARE_IRQ(MAX77803_CHG_IRQ_BYP_I, CHG_INT, 1 << 0),
#if defined(CONFIG_CHARGER_MAX77803)
DECLARE_IRQ(MAX77803_CHG_IRQ_BATP_I, CHG_INT, 1 << 2),
#else
//DECLARE_IRQ(MAX77803_CHG_IRQ_THM_I, CHG_INT, 1 << 2),
#endif
DECLARE_IRQ(MAX77803_CHG_IRQ_BAT_I, CHG_INT, 1 << 3),
DECLARE_IRQ(MAX77803_CHG_IRQ_CHG_I, CHG_INT, 1 << 4),
#if defined(CONFIG_CHARGER_MAX77803)
DECLARE_IRQ(MAX77803_CHG_IRQ_WCIN_I, CHG_INT, 1 << 5),
#endif
DECLARE_IRQ(MAX77803_CHG_IRQ_CHGIN_I, CHG_INT, 1 << 6),
DECLARE_IRQ(MAX77803_MUIC_IRQ_INT1_ADC, MUIC_INT1, 1 << 0),
DECLARE_IRQ(MAX77803_MUIC_IRQ_INT1_ADCLOW, MUIC_INT1, 1 << 1),
DECLARE_IRQ(MAX77803_MUIC_IRQ_INT1_ADCERR, MUIC_INT1, 1 << 2),
DECLARE_IRQ(MAX77803_MUIC_IRQ_INT1_ADC1K, MUIC_INT1, 1 << 3),
DECLARE_IRQ(MAX77803_MUIC_IRQ_INT2_CHGTYP, MUIC_INT2, 1 << 0),
DECLARE_IRQ(MAX77803_MUIC_IRQ_INT2_CHGDETREUN, MUIC_INT2, 1 << 1),
DECLARE_IRQ(MAX77803_MUIC_IRQ_INT2_DCDTMR, MUIC_INT2, 1 << 2),
DECLARE_IRQ(MAX77803_MUIC_IRQ_INT2_DXOVP, MUIC_INT2, 1 << 3),
DECLARE_IRQ(MAX77803_MUIC_IRQ_INT2_VBVOLT, MUIC_INT2, 1 << 4),
DECLARE_IRQ(MAX77803_MUIC_IRQ_INT2_VIDRM, MUIC_INT2, 1 << 5),
DECLARE_IRQ(MAX77803_MUIC_IRQ_INT3_EOC, MUIC_INT3, 1 << 0),
DECLARE_IRQ(MAX77803_MUIC_IRQ_INT3_CGMBC, MUIC_INT3, 1 << 1),
DECLARE_IRQ(MAX77803_MUIC_IRQ_INT3_OVP, MUIC_INT3, 1 << 2),
DECLARE_IRQ(MAX77803_MUIC_IRQ_INT3_MBCCHGERR, MUIC_INT3, 1 << 3),
DECLARE_IRQ(MAX77803_MUIC_IRQ_INT3_CHGENABLED, MUIC_INT3, 1 << 4),
DECLARE_IRQ(MAX77803_MUIC_IRQ_INT3_BATDET, MUIC_INT3, 1 << 5),
};
static void max77803_irq_lock(struct irq_data *data)
{
struct max77803_dev *max77803 = irq_get_chip_data(data->irq);
mutex_lock(&max77803->irqlock);
}
static void max77803_irq_sync_unlock(struct irq_data *data)
{
struct max77803_dev *max77803 = irq_get_chip_data(data->irq);
int i;
for (i = 0; i < MAX77803_IRQ_GROUP_NR; i++) {
u8 mask_reg = max77803_mask_reg[i];
struct i2c_client *i2c = get_i2c(max77803, i);
if (mask_reg == MAX77803_REG_INVALID ||
IS_ERR_OR_NULL(i2c))
continue;
max77803->irq_masks_cache[i] = max77803->irq_masks_cur[i];
max77803_write_reg(i2c, max77803_mask_reg[i],
max77803->irq_masks_cur[i]);
}
mutex_unlock(&max77803->irqlock);
}
static const inline struct max77803_irq_data *
irq_to_max77803_irq(struct max77803_dev *max77803, int irq)
{
return &max77803_irqs[irq - max77803->irq_base];
}
static void max77803_irq_mask(struct irq_data *data)
{
struct max77803_dev *max77803 = irq_get_chip_data(data->irq);
const struct max77803_irq_data *irq_data =
irq_to_max77803_irq(max77803, data->irq);
if (irq_data->group >= MAX77803_IRQ_GROUP_NR)
return;
if (irq_data->group >= MUIC_INT1 && irq_data->group <= MUIC_INT3)
max77803->irq_masks_cur[irq_data->group] &= ~irq_data->mask;
else
max77803->irq_masks_cur[irq_data->group] |= irq_data->mask;
}
static void max77803_irq_unmask(struct irq_data *data)
{
struct max77803_dev *max77803 = irq_get_chip_data(data->irq);
const struct max77803_irq_data *irq_data =
irq_to_max77803_irq(max77803, data->irq);
if (irq_data->group >= MAX77803_IRQ_GROUP_NR)
return;
if (irq_data->group >= MUIC_INT1 && irq_data->group <= MUIC_INT3)
max77803->irq_masks_cur[irq_data->group] |= irq_data->mask;
else
max77803->irq_masks_cur[irq_data->group] &= ~irq_data->mask;
}
static void max77803_irq_ack(struct irq_data *data)
{
}
static struct irq_chip max77803_irq_chip = {
.name = "max77803",
.irq_bus_lock = max77803_irq_lock,
.irq_bus_sync_unlock = max77803_irq_sync_unlock,
.irq_mask = max77803_irq_mask,
.irq_unmask = max77803_irq_unmask,
.irq_ack = max77803_irq_ack,
};
static irqreturn_t max77803_irq_thread(int irq, void *data)
{
struct max77803_dev *max77803 = data;
u8 irq_reg[MAX77803_IRQ_GROUP_NR] = {};
u8 irq_src;
int ret;
int i;
pr_debug("%s: irq gpio pre-state(0x%02x)\n", __func__,
gpio_get_value(max77803->irq_gpio));
clear_retry:
ret = max77803_read_reg(max77803->i2c,
MAX77803_PMIC_REG_INTSRC, &irq_src);
if (ret < 0) {
dev_err(max77803->dev, "Failed to read interrupt source: %d\n",
ret);
return IRQ_NONE;
}
pr_info("%s: interrupt source(0x%02x)\n", __func__, irq_src);
if (irq_src & MAX77803_IRQSRC_CHG) {
/* CHG_INT */
ret = max77803_read_reg(max77803->i2c, MAX77803_CHG_REG_CHG_INT,
&irq_reg[CHG_INT]);
pr_info("%s: charger interrupt(0x%02x)\n",
__func__, irq_reg[CHG_INT]);
/* mask chgin to prevent chgin infinite interrupt
* chgin is unmasked chgin isr
*/
if (irq_reg[CHG_INT] & max77803_irqs[MAX77803_CHG_IRQ_CHGIN_I].mask) {
u8 reg_data;
max77803_read_reg(max77803->i2c,
MAX77803_CHG_REG_CHG_INT_MASK, ®_data);
reg_data |= (1 << 6);
max77803_write_reg(max77803->i2c,
MAX77803_CHG_REG_CHG_INT_MASK, reg_data);
}
}
if (irq_src & MAX77803_IRQSRC_TOP) {
/* TOPSYS_INT */
ret = max77803_read_reg(max77803->i2c,
MAX77803_PMIC_REG_TOPSYS_INT,
&irq_reg[TOPSYS_INT]);
pr_info("%s: topsys interrupt(0x%02x)\n",
__func__, irq_reg[TOPSYS_INT]);
}
if (irq_src & MAX77803_IRQSRC_FLASH) {
/* LED_INT */
ret = max77803_read_reg(max77803->i2c,
MAX77803_LED_REG_FLASH_INT,
&irq_reg[LED_INT]);
pr_info("%s: led interrupt(0x%02x)\n",
__func__, irq_reg[LED_INT]);
}
if (irq_src & MAX77803_IRQSRC_MUIC) {
/* MUIC INT1 ~ INT3 */
max77803_bulk_read(max77803->muic,
MAX77803_MUIC_REG_INT1,
MAX77803_NUM_IRQ_MUIC_REGS,
&irq_reg[MUIC_INT1]);
pr_info("%s: muic interrupt(0x%02x, 0x%02x, 0x%02x)\n",
__func__, irq_reg[MUIC_INT1],
irq_reg[MUIC_INT2], irq_reg[MUIC_INT3]);
}
pr_debug("%s: irq gpio post-state(0x%02x)\n", __func__,
gpio_get_value(max77803->irq_gpio));
if (gpio_get_value(max77803->irq_gpio) == 0) {
pr_warn("%s: irq_gpio is not High!\n", __func__);
goto clear_retry;
}
#if 0
/* Apply masking */
for (i = 0; i < MAX77803_IRQ_GROUP_NR; i++) {
if (i >= MUIC_INT1 && i <= MUIC_INT3)
irq_reg[i] &= max77803->irq_masks_cur[i];
else
irq_reg[i] &= ~max77803->irq_masks_cur[i];
}
#endif
/* Report */
for (i = 0; i < MAX77803_IRQ_NR; i++) {
if (irq_reg[max77803_irqs[i].group] & max77803_irqs[i].mask)
handle_nested_irq(max77803->irq_base + i);
}
return IRQ_HANDLED;
}
int max77803_irq_resume(struct max77803_dev *max77803)
{
int ret = 0;
if (max77803->irq && max77803->irq_base)
ret = max77803_irq_thread(max77803->irq_base, max77803);
dev_info(max77803->dev, "%s: irq_resume ret=%d", __func__, ret);
return ret >= 0 ? 0 : ret;
}
int max77803_irq_init(struct max77803_dev *max77803)
{
int i;
int cur_irq;
int ret;
u8 i2c_data;
pr_info("func: %s, irq_gpio: %d, irq_base: %d\n", __func__,
max77803->irq_gpio, max77803->irq_base);
if (!max77803->irq_gpio) {
dev_warn(max77803->dev, "No interrupt specified.\n");
max77803->irq_base = 0;
return 0;
}
if (!max77803->irq_base) {
dev_err(max77803->dev, "No interrupt base specified.\n");
return 0;
}
mutex_init(&max77803->irqlock);
max77803->irq = gpio_to_irq(max77803->irq_gpio);
ret = gpio_request(max77803->irq_gpio, "if_pmic_irq");
if (ret) {
dev_err(max77803->dev, "%s: failed requesting gpio %d\n",
__func__, max77803->irq_gpio);
return ret;
}
gpio_direction_input(max77803->irq_gpio);
gpio_free(max77803->irq_gpio);
/* Mask individual interrupt sources */
for (i = 0; i < MAX77803_IRQ_GROUP_NR; i++) {
struct i2c_client *i2c;
/* MUIC IRQ 0:MASK 1:NOT MASK */
/* Other IRQ 1:MASK 0:NOT MASK */
if (i >= MUIC_INT1 && i <= MUIC_INT3) {
max77803->irq_masks_cur[i] = 0x00;
max77803->irq_masks_cache[i] = 0x00;
} else {
max77803->irq_masks_cur[i] = 0xff;
max77803->irq_masks_cache[i] = 0xff;
}
i2c = get_i2c(max77803, i);
if (IS_ERR_OR_NULL(i2c))
continue;
if (max77803_mask_reg[i] == MAX77803_REG_INVALID)
continue;
if (i >= MUIC_INT1 && i <= MUIC_INT3)
max77803_write_reg(i2c, max77803_mask_reg[i], 0x00);
else
max77803_write_reg(i2c, max77803_mask_reg[i], 0xff);
}
/* Register with genirq */
for (i = 0; i < MAX77803_IRQ_NR; i++) {
cur_irq = i + max77803->irq_base;
irq_set_chip_data(cur_irq, max77803);
irq_set_chip_and_handler(cur_irq, &max77803_irq_chip,
handle_edge_irq);
irq_set_nested_thread(cur_irq, 1);
#ifdef CONFIG_ARM
set_irq_flags(cur_irq, IRQF_VALID);
#else
irq_set_noprobe(cur_irq);
#endif
}
/* Unmask max77803 interrupt */
ret = max77803_read_reg(max77803->i2c, MAX77803_PMIC_REG_INTSRC_MASK,
&i2c_data);
if (ret) {
dev_err(max77803->dev, "%s: fail to read muic reg\n", __func__);
return ret;
}
i2c_data &= ~(MAX77803_IRQSRC_CHG); /* Unmask charger interrupt */
i2c_data &= ~(MAX77803_IRQSRC_MUIC); /* Unmask muic interrupt */
max77803_write_reg(max77803->i2c, MAX77803_PMIC_REG_INTSRC_MASK,
i2c_data);
ret = request_threaded_irq(max77803->irq, NULL, max77803_irq_thread,
IRQF_TRIGGER_FALLING | IRQF_ONESHOT,
"max77803-irq", max77803);
if (ret) {
dev_err(max77803->dev, "Failed to request IRQ %d: %d\n",
max77803->irq, ret);
return ret;
}
return 0;
}
void max77803_irq_exit(struct max77803_dev *max77803)
{
if (max77803->irq)
free_irq(max77803->irq, max77803);
}
| gpl-2.0 |
iains/darwin-gcc-4-8 | gcc/testsuite/gfortran.dg/intrinsic_std_6.f90 | 114 | 1372 | ! { dg-do compile }
! { dg-options "-std=f95 -Wintrinsics-std -fdump-tree-original" }
!
! See intrinsic_std_1.f90 for more compile-time checks
!
! PR fortran/33141
! Check for the expected behaviour when an intrinsic function/subroutine is
! called that is not available in the defined standard or that is a GNU
! extension:
! There should be a warning emitted on the call, and the reference should be
! treated like an external call.
! For declaring a non-standard intrinsic INTRINSIC, a hard error should be
! generated, of course.
SUBROUTINE no_implicit
IMPLICIT NONE
REAL :: asinh ! { dg-warning "Fortran 2008" }
! abort is a GNU extension
CALL abort () ! { dg-warning "extension" }
! ASINH is an intrinsic of F2008
! The warning should be issued in the declaration above where it is declared
! EXTERNAL.
WRITE (*,*) ASINH (1.) ! { dg-warning "Fortran 2008" }
END SUBROUTINE no_implicit
SUBROUTINE implicit_type
! acosh has implicit type
WRITE (*,*) ACOSH (1.) ! { dg-warning "Fortran 2008" }
WRITE (*,*) ACOSH (1.) ! { dg-bogus "Fortran 2008" }
END SUBROUTINE implicit_type
! Scan that really external functions are called.
! { dg-final { scan-tree-dump " abort " "original" } }
! { dg-final { scan-tree-dump " asinh " "original" } }
! { dg-final { scan-tree-dump " acosh " "original" } }
! { dg-final { cleanup-tree-dump "original" } }
| gpl-2.0 |
Andy1911/Andy_Onepone | sound/soc/codecs/wcd9310.c | 114 | 293886 | /* Copyright (c) 2011-2014, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/firmware.h>
#include <linux/slab.h>
#include <linux/platform_device.h>
#include <linux/device.h>
#include <linux/printk.h>
#include <linux/ratelimit.h>
#include <linux/debugfs.h>
#include <linux/wait.h>
#include <linux/mfd/wcd9xxx/core.h>
#include <linux/mfd/wcd9xxx/wcd9xxx_registers.h>
#include <linux/mfd/wcd9xxx/wcd9310_registers.h>
#include <linux/mfd/wcd9xxx/pdata.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include <sound/soc-dapm.h>
#include <sound/tlv.h>
#include <linux/bitops.h>
#include <linux/delay.h>
#include <linux/pm_runtime.h>
#include <linux/kernel.h>
#include <linux/gpio.h>
#include <linux/irq.h>
#include <linux/wakelock.h>
#include <linux/suspend.h>
#include "wcd9310.h"
static int cfilt_adjust_ms = 10;
module_param(cfilt_adjust_ms, int, 0644);
MODULE_PARM_DESC(cfilt_adjust_ms, "delay after adjusting cfilt voltage in ms");
#define WCD9310_RATES (SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_16000 |\
SNDRV_PCM_RATE_32000 | SNDRV_PCM_RATE_48000 |\
SNDRV_PCM_RATE_96000 | SNDRV_PCM_RATE_192000)
#define NUM_DECIMATORS 10
#define NUM_INTERPOLATORS 7
#define BITS_PER_REG 8
#define TABLA_CFILT_FAST_MODE 0x00
#define TABLA_CFILT_SLOW_MODE 0x40
#define MBHC_FW_READ_ATTEMPTS 15
#define MBHC_FW_READ_TIMEOUT 2000000
#define MBHC_VDDIO_SWITCH_WAIT_MS 10
#define COMP_DIGITAL_DB_GAIN_APPLY(a, b) \
(((a) <= 0) ? ((a) - b) : (a))
#define SLIM_CLOSE_TIMEOUT 1000
/* The wait time value comes from codec HW specification */
#define COMP_BRINGUP_WAIT_TIME 2000
enum {
MBHC_USE_HPHL_TRIGGER = 1,
MBHC_USE_MB_TRIGGER = 2
};
#define MBHC_NUM_DCE_PLUG_DETECT 3
#define NUM_ATTEMPTS_INSERT_DETECT 25
#define NUM_ATTEMPTS_TO_REPORT 5
#define TABLA_JACK_MASK (SND_JACK_HEADSET | SND_JACK_OC_HPHL | \
SND_JACK_OC_HPHR | SND_JACK_LINEOUT | \
SND_JACK_UNSUPPORTED)
#define TABLA_I2S_MASTER_MODE_MASK 0x08
#define TABLA_OCP_ATTEMPT 1
enum {
AIF1_PB = 0,
AIF1_CAP,
AIF2_PB,
AIF2_CAP,
AIF3_PB,
AIF3_CAP,
NUM_CODEC_DAIS,
};
enum {
RX_MIX1_INP_SEL_ZERO = 0,
RX_MIX1_INP_SEL_SRC1,
RX_MIX1_INP_SEL_SRC2,
RX_MIX1_INP_SEL_IIR1,
RX_MIX1_INP_SEL_IIR2,
RX_MIX1_INP_SEL_RX1,
RX_MIX1_INP_SEL_RX2,
RX_MIX1_INP_SEL_RX3,
RX_MIX1_INP_SEL_RX4,
RX_MIX1_INP_SEL_RX5,
RX_MIX1_INP_SEL_RX6,
RX_MIX1_INP_SEL_RX7,
};
#define MAX_PA_GAIN_OPTIONS 13
#define TABLA_MCLK_RATE_12288KHZ 12288000
#define TABLA_MCLK_RATE_9600KHZ 9600000
#define TABLA_FAKE_INS_THRESHOLD_MS 2500
#define TABLA_FAKE_REMOVAL_MIN_PERIOD_MS 50
#define TABLA_MBHC_BUTTON_MIN 0x8000
#define TABLA_MBHC_FAKE_INSERT_LOW 10
#define TABLA_MBHC_FAKE_INSERT_HIGH 80
#define TABLA_MBHC_FAKE_INS_HIGH_NO_GPIO 150
#define TABLA_MBHC_STATUS_REL_DETECTION 0x0C
#define TABLA_MBHC_GPIO_REL_DEBOUNCE_TIME_MS 50
#define TABLA_MBHC_FAKE_INS_DELTA_MV 200
#define TABLA_MBHC_FAKE_INS_DELTA_SCALED_MV 300
#define TABLA_HS_DETECT_PLUG_TIME_MS (5 * 1000)
#define TABLA_HS_DETECT_PLUG_INERVAL_MS 100
#define TABLA_GPIO_IRQ_DEBOUNCE_TIME_US 5000
#define TABLA_MBHC_GND_MIC_SWAP_THRESHOLD 2
#define TABLA_RX_PORT_START_NUMBER 10
#define TABLA_ACQUIRE_LOCK(x) do { \
mutex_lock_nested(&x, SINGLE_DEPTH_NESTING); \
} while (0)
#define TABLA_RELEASE_LOCK(x) do { mutex_unlock(&x); } while (0)
static const DECLARE_TLV_DB_SCALE(digital_gain, 0, 1, 0);
static const DECLARE_TLV_DB_SCALE(line_gain, 0, 7, 1);
static const DECLARE_TLV_DB_SCALE(analog_gain, 0, 25, 1);
static struct snd_soc_dai_driver tabla_dai[];
static const DECLARE_TLV_DB_SCALE(aux_pga_gain, 0, 2, 0);
static int tabla_codec_enable_slimrx(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event);
static int tabla_codec_enable_slimtx(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event);
enum tabla_bandgap_type {
TABLA_BANDGAP_OFF = 0,
TABLA_BANDGAP_AUDIO_MODE,
TABLA_BANDGAP_MBHC_MODE,
};
struct mbhc_micbias_regs {
u16 cfilt_val;
u16 cfilt_ctl;
u16 mbhc_reg;
u16 int_rbias;
u16 ctl_reg;
u8 cfilt_sel;
};
/* Codec supports 2 IIR filters */
enum {
IIR1 = 0,
IIR2,
IIR_MAX,
};
/* Codec supports 5 bands */
enum {
BAND1 = 0,
BAND2,
BAND3,
BAND4,
BAND5,
BAND_MAX,
};
enum {
COMPANDER_1 = 0,
COMPANDER_2,
COMPANDER_MAX,
};
enum {
COMPANDER_FS_8KHZ = 0,
COMPANDER_FS_16KHZ,
COMPANDER_FS_32KHZ,
COMPANDER_FS_48KHZ,
COMPANDER_FS_96KHZ,
COMPANDER_FS_192KHZ,
COMPANDER_FS_MAX,
};
enum {
COMP_SHUTDWN_TIMEOUT_PCM_1 = 0,
COMP_SHUTDWN_TIMEOUT_PCM_240,
COMP_SHUTDWN_TIMEOUT_PCM_480,
COMP_SHUTDWN_TIMEOUT_PCM_960,
COMP_SHUTDWN_TIMEOUT_PCM_1440,
COMP_SHUTDWN_TIMEOUT_PCM_2880,
COMP_SHUTDWN_TIMEOUT_PCM_5760,
};
/* Flags to track of PA and DAC state.
* PA and DAC should be tracked separately as AUXPGA loopback requires
* only PA to be turned on without DAC being on. */
enum tabla_priv_ack_flags {
TABLA_HPHL_PA_OFF_ACK = 0,
TABLA_HPHR_PA_OFF_ACK,
TABLA_HPHL_DAC_OFF_ACK,
TABLA_HPHR_DAC_OFF_ACK
};
struct comp_sample_dependent_params {
u32 peak_det_timeout;
u32 rms_meter_div_fact;
u32 rms_meter_resamp_fact;
u32 shutdown_timeout;
};
struct comp_dgtl_gain_offset {
u8 whole_db_gain;
u8 half_db_gain;
};
static const struct comp_dgtl_gain_offset
comp_dgtl_gain[MAX_PA_GAIN_OPTIONS] = {
{0, 0},
{1, 1},
{3, 0},
{4, 1},
{6, 0},
{7, 1},
{9, 0},
{10, 1},
{12, 0},
{13, 1},
{15, 0},
{16, 1},
{18, 0},
};
/* Data used by MBHC */
struct mbhc_internal_cal_data {
u16 dce_z;
u16 dce_mb;
u16 sta_z;
u16 sta_mb;
u32 t_sta_dce;
u32 t_dce;
u32 t_sta;
u32 micb_mv;
u16 v_ins_hu;
u16 v_ins_h;
u16 v_b1_hu;
u16 v_b1_h;
u16 v_b1_huc;
u16 v_brh;
u16 v_brl;
u16 v_no_mic;
u8 npoll;
u8 nbounce_wait;
s16 adj_v_hs_max;
u16 adj_v_ins_hu;
u16 adj_v_ins_h;
s16 v_inval_ins_low;
s16 v_inval_ins_high;
};
struct tabla_reg_address {
u16 micb_4_ctl;
u16 micb_4_int_rbias;
u16 micb_4_mbhc;
};
enum tabla_mbhc_plug_type {
PLUG_TYPE_INVALID = -1,
PLUG_TYPE_NONE,
PLUG_TYPE_HEADSET,
PLUG_TYPE_HEADPHONE,
PLUG_TYPE_HIGH_HPH,
PLUG_TYPE_GND_MIC_SWAP,
};
enum tabla_mbhc_state {
MBHC_STATE_NONE = -1,
MBHC_STATE_POTENTIAL,
MBHC_STATE_POTENTIAL_RECOVERY,
MBHC_STATE_RELEASE,
};
struct hpf_work {
struct tabla_priv *tabla;
u32 decimator;
u8 tx_hpf_cut_of_freq;
struct delayed_work dwork;
};
static struct hpf_work tx_hpf_work[NUM_DECIMATORS];
static const struct wcd9xxx_ch tabla_rx_chs[TABLA_RX_MAX] = {
WCD9XXX_CH(TABLA_RX_PORT_START_NUMBER, 0),
WCD9XXX_CH(TABLA_RX_PORT_START_NUMBER + 1, 1),
WCD9XXX_CH(TABLA_RX_PORT_START_NUMBER + 2, 2),
WCD9XXX_CH(TABLA_RX_PORT_START_NUMBER + 3, 3),
WCD9XXX_CH(TABLA_RX_PORT_START_NUMBER + 4, 4),
WCD9XXX_CH(TABLA_RX_PORT_START_NUMBER + 5, 5),
WCD9XXX_CH(TABLA_RX_PORT_START_NUMBER + 6, 6)
};
static const struct wcd9xxx_ch tabla_tx_chs[TABLA_TX_MAX] = {
WCD9XXX_CH(0, 0),
WCD9XXX_CH(1, 1),
WCD9XXX_CH(2, 2),
WCD9XXX_CH(3, 3),
WCD9XXX_CH(4, 4),
WCD9XXX_CH(5, 5),
WCD9XXX_CH(6, 6),
WCD9XXX_CH(7, 7),
WCD9XXX_CH(8, 8),
WCD9XXX_CH(9, 9)
};
static const u32 vport_check_table[NUM_CODEC_DAIS] = {
0, /* AIF1_PB */
(1 << AIF2_CAP) | (1 << AIF3_CAP), /* AIF1_CAP */
0, /* AIF2_PB */
(1 << AIF1_CAP) | (1 << AIF3_CAP), /* AIF2_CAP */
0, /* AIF2_PB */
(1 << AIF1_CAP) | (1 << AIF2_CAP), /* AIF2_CAP */
};
static const u32 vport_i2s_check_table[NUM_CODEC_DAIS] = {
0, /* AIF1_PB */
0, /* AIF1_CAP */
};
struct tabla_priv {
struct snd_soc_codec *codec;
struct tabla_reg_address reg_addr;
u32 adc_count;
u32 cfilt1_cnt;
u32 cfilt2_cnt;
u32 cfilt3_cnt;
u32 rx_bias_count;
s32 dmic_1_2_clk_cnt;
s32 dmic_3_4_clk_cnt;
s32 dmic_5_6_clk_cnt;
enum tabla_bandgap_type bandgap_type;
bool mclk_enabled;
bool clock_active;
bool config_mode_active;
bool mbhc_polling_active;
unsigned long mbhc_fake_ins_start;
int buttons_pressed;
enum tabla_mbhc_state mbhc_state;
struct tabla_mbhc_config mbhc_cfg;
struct mbhc_internal_cal_data mbhc_data;
u32 ldo_h_count;
u32 micbias_enable_count[TABLA_NUM_MICBIAS];
struct wcd9xxx_pdata *pdata;
u32 anc_slot;
bool anc_func;
bool no_mic_headset_override;
/* Delayed work to report long button press */
struct delayed_work mbhc_btn_dwork;
struct mbhc_micbias_regs mbhc_bias_regs;
bool mbhc_micbias_switched;
/* track PA/DAC state */
unsigned long hph_pa_dac_state;
/*track tabla interface type*/
u8 intf_type;
u32 hph_status; /* track headhpone status */
/* define separate work for left and right headphone OCP to avoid
* additional checking on which OCP event to report so no locking
* to ensure synchronization is required
*/
struct work_struct hphlocp_work; /* reporting left hph ocp off */
struct work_struct hphrocp_work; /* reporting right hph ocp off */
u8 hphlocp_cnt; /* headphone left ocp retry */
u8 hphrocp_cnt; /* headphone right ocp retry */
/* Work to perform MBHC Firmware Read */
struct delayed_work mbhc_firmware_dwork;
const struct firmware *mbhc_fw;
/* num of slim ports required */
struct wcd9xxx_codec_dai_data dai[NUM_CODEC_DAIS];
/*compander*/
int comp_enabled[COMPANDER_MAX];
u32 comp_fs[COMPANDER_MAX];
u8 comp_gain_offset[TABLA_SB_PGD_MAX_NUMBER_OF_RX_SLAVE_DEV_PORTS - 1];
/* Maintain the status of AUX PGA */
int aux_pga_cnt;
u8 aux_l_gain;
u8 aux_r_gain;
struct delayed_work mbhc_insert_dwork;
unsigned long mbhc_last_resume; /* in jiffies */
u8 current_plug;
struct work_struct hs_correct_plug_work;
bool hs_detect_work_stop;
bool hs_polling_irq_prepared;
bool lpi_enabled; /* low power insertion detection */
bool in_gpio_handler;
/* Currently, only used for mbhc purpose, to protect
* concurrent execution of mbhc threaded irq handlers and
* kill race between DAPM and MBHC.But can serve as a
* general lock to protect codec resource
*/
struct mutex codec_resource_lock;
/* Work to perform polling on microphone voltage
* in order to correct plug type once plug type
* is detected as headphone
*/
struct work_struct hs_correct_plug_work_nogpio;
bool gpio_irq_resend;
struct wake_lock irq_resend_wlock;
#ifdef CONFIG_DEBUG_FS
struct dentry *debugfs_poke;
struct dentry *debugfs_mbhc;
#endif
};
static const u32 comp_shift[] = {
0,
1,
};
static const int comp_rx_path[] = {
COMPANDER_1,
COMPANDER_1,
COMPANDER_2,
COMPANDER_2,
COMPANDER_2,
COMPANDER_2,
COMPANDER_MAX,
};
static const struct comp_sample_dependent_params
comp_samp_params[COMPANDER_FS_MAX] = {
{
.peak_det_timeout = 0x6,
.rms_meter_div_fact = 0x9 << 4,
.rms_meter_resamp_fact = 0x06,
.shutdown_timeout = COMP_SHUTDWN_TIMEOUT_PCM_240 << 3,
},
{
.peak_det_timeout = 0x7,
.rms_meter_div_fact = 0xA << 4,
.rms_meter_resamp_fact = 0x0C,
.shutdown_timeout = COMP_SHUTDWN_TIMEOUT_PCM_480 << 3,
},
{
.peak_det_timeout = 0x8,
.rms_meter_div_fact = 0xB << 4,
.rms_meter_resamp_fact = 0x30,
.shutdown_timeout = COMP_SHUTDWN_TIMEOUT_PCM_960 << 3,
},
{
.peak_det_timeout = 0x9,
.rms_meter_div_fact = 0xB << 4,
.rms_meter_resamp_fact = 0x28,
.shutdown_timeout = COMP_SHUTDWN_TIMEOUT_PCM_1440 << 3,
},
{
.peak_det_timeout = 0xA,
.rms_meter_div_fact = 0xC << 4,
.rms_meter_resamp_fact = 0x50,
.shutdown_timeout = COMP_SHUTDWN_TIMEOUT_PCM_2880 << 3,
},
{
.peak_det_timeout = 0xB,
.rms_meter_div_fact = 0xC << 4,
.rms_meter_resamp_fact = 0x50,
.shutdown_timeout = COMP_SHUTDWN_TIMEOUT_PCM_5760 << 3,
},
};
static unsigned short rx_digital_gain_reg[] = {
TABLA_A_CDC_RX1_VOL_CTL_B2_CTL,
TABLA_A_CDC_RX2_VOL_CTL_B2_CTL,
TABLA_A_CDC_RX3_VOL_CTL_B2_CTL,
TABLA_A_CDC_RX4_VOL_CTL_B2_CTL,
TABLA_A_CDC_RX5_VOL_CTL_B2_CTL,
TABLA_A_CDC_RX6_VOL_CTL_B2_CTL,
TABLA_A_CDC_RX7_VOL_CTL_B2_CTL,
};
static unsigned short tx_digital_gain_reg[] = {
TABLA_A_CDC_TX1_VOL_CTL_GAIN,
TABLA_A_CDC_TX2_VOL_CTL_GAIN,
TABLA_A_CDC_TX3_VOL_CTL_GAIN,
TABLA_A_CDC_TX4_VOL_CTL_GAIN,
TABLA_A_CDC_TX5_VOL_CTL_GAIN,
TABLA_A_CDC_TX6_VOL_CTL_GAIN,
TABLA_A_CDC_TX7_VOL_CTL_GAIN,
TABLA_A_CDC_TX8_VOL_CTL_GAIN,
TABLA_A_CDC_TX9_VOL_CTL_GAIN,
TABLA_A_CDC_TX10_VOL_CTL_GAIN,
};
static int tabla_codec_enable_charge_pump(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
pr_debug("%s %d\n", __func__, event);
switch (event) {
case SND_SOC_DAPM_POST_PMU:
snd_soc_update_bits(codec, TABLA_A_CDC_CLK_OTHR_CTL, 0x01,
0x01);
snd_soc_update_bits(codec, TABLA_A_CDC_CLSG_CTL, 0x08, 0x08);
usleep_range(200, 200);
snd_soc_update_bits(codec, TABLA_A_CP_STATIC, 0x10, 0x00);
break;
case SND_SOC_DAPM_PRE_PMD:
snd_soc_update_bits(codec, TABLA_A_CDC_CLK_OTHR_RESET_CTL, 0x10,
0x10);
usleep_range(20, 20);
snd_soc_update_bits(codec, TABLA_A_CP_STATIC, 0x08, 0x08);
snd_soc_update_bits(codec, TABLA_A_CP_STATIC, 0x10, 0x10);
snd_soc_update_bits(codec, TABLA_A_CDC_CLSG_CTL, 0x08, 0x00);
snd_soc_update_bits(codec, TABLA_A_CDC_CLK_OTHR_CTL, 0x01,
0x00);
snd_soc_update_bits(codec, TABLA_A_CDC_CLK_OTHR_RESET_CTL, 0x10,
0x00);
snd_soc_update_bits(codec, TABLA_A_CP_STATIC, 0x08, 0x00);
break;
}
return 0;
}
static int tabla_get_anc_slot(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
ucontrol->value.integer.value[0] = tabla->anc_slot;
return 0;
}
static int tabla_put_anc_slot(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
tabla->anc_slot = ucontrol->value.integer.value[0];
return 0;
}
static int tabla_get_anc_func(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
mutex_lock(&codec->dapm.codec->mutex);
ucontrol->value.integer.value[0] = (tabla->anc_func == true ? 1 : 0);
mutex_unlock(&codec->dapm.codec->mutex);
return 0;
}
static int tabla_put_anc_func(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
struct snd_soc_dapm_context *dapm = &codec->dapm;
mutex_lock(&dapm->codec->mutex);
tabla->anc_func = (!ucontrol->value.integer.value[0] ? false : true);
dev_dbg(codec->dev, "%s: anc_func %x", __func__, tabla->anc_func);
if (tabla->anc_func == true) {
snd_soc_dapm_enable_pin(dapm, "ANC HPHR");
snd_soc_dapm_enable_pin(dapm, "ANC HPHL");
snd_soc_dapm_enable_pin(dapm, "ANC HEADPHONE");
snd_soc_dapm_disable_pin(dapm, "HPHR");
snd_soc_dapm_disable_pin(dapm, "HPHL");
snd_soc_dapm_disable_pin(dapm, "HEADPHONE");
} else {
snd_soc_dapm_disable_pin(dapm, "ANC HPHR");
snd_soc_dapm_disable_pin(dapm, "ANC HPHL");
snd_soc_dapm_disable_pin(dapm, "ANC HEADPHONE");
snd_soc_dapm_enable_pin(dapm, "HPHR");
snd_soc_dapm_enable_pin(dapm, "HPHL");
snd_soc_dapm_enable_pin(dapm, "HEADPHONE");
}
snd_soc_dapm_sync(dapm);
mutex_unlock(&dapm->codec->mutex);
return 0;
}
static int tabla_pa_gain_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
u8 ear_pa_gain;
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
ear_pa_gain = snd_soc_read(codec, TABLA_A_RX_EAR_GAIN);
ear_pa_gain = ear_pa_gain >> 5;
if (ear_pa_gain == 0x00) {
ucontrol->value.integer.value[0] = 0;
} else if (ear_pa_gain == 0x04) {
ucontrol->value.integer.value[0] = 1;
} else {
pr_err("%s: ERROR: Unsupported Ear Gain = 0x%x\n",
__func__, ear_pa_gain);
return -EINVAL;
}
pr_debug("%s: ear_pa_gain = 0x%x\n", __func__, ear_pa_gain);
return 0;
}
static int tabla_pa_gain_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
u8 ear_pa_gain;
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
pr_debug("%s: ucontrol->value.integer.value[0] = %ld\n", __func__,
ucontrol->value.integer.value[0]);
switch (ucontrol->value.integer.value[0]) {
case 0:
ear_pa_gain = 0x00;
break;
case 1:
ear_pa_gain = 0x80;
break;
default:
return -EINVAL;
}
snd_soc_update_bits(codec, TABLA_A_RX_EAR_GAIN, 0xE0, ear_pa_gain);
return 0;
}
static int tabla_get_iir_enable_audio_mixer(
struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
int iir_idx = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->reg;
int band_idx = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->shift;
ucontrol->value.integer.value[0] =
snd_soc_read(codec, (TABLA_A_CDC_IIR1_CTL + 16 * iir_idx)) &
(1 << band_idx);
pr_debug("%s: IIR #%d band #%d enable %d\n", __func__,
iir_idx, band_idx,
(uint32_t)ucontrol->value.integer.value[0]);
return 0;
}
static int tabla_put_iir_enable_audio_mixer(
struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
int iir_idx = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->reg;
int band_idx = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->shift;
int value = ucontrol->value.integer.value[0];
/* Mask first 5 bits, 6-8 are reserved */
snd_soc_update_bits(codec, (TABLA_A_CDC_IIR1_CTL + 16 * iir_idx),
(1 << band_idx), (value << band_idx));
pr_debug("%s: IIR #%d band #%d enable %d\n", __func__,
iir_idx, band_idx, value);
return 0;
}
static uint32_t get_iir_band_coeff(struct snd_soc_codec *codec,
int iir_idx, int band_idx,
int coeff_idx)
{
/* Address does not automatically update if reading */
snd_soc_write(codec,
(TABLA_A_CDC_IIR1_COEF_B1_CTL + 16 * iir_idx),
(band_idx * BAND_MAX + coeff_idx) & 0x1F);
/* Mask bits top 2 bits since they are reserved */
return ((snd_soc_read(codec,
(TABLA_A_CDC_IIR1_COEF_B2_CTL + 16 * iir_idx)) << 24) |
(snd_soc_read(codec,
(TABLA_A_CDC_IIR1_COEF_B3_CTL + 16 * iir_idx)) << 16) |
(snd_soc_read(codec,
(TABLA_A_CDC_IIR1_COEF_B4_CTL + 16 * iir_idx)) << 8) |
(snd_soc_read(codec,
(TABLA_A_CDC_IIR1_COEF_B5_CTL + 16 * iir_idx)))) &
0x3FFFFFFF;
}
static int tabla_get_iir_band_audio_mixer(
struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
int iir_idx = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->reg;
int band_idx = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->shift;
ucontrol->value.integer.value[0] =
get_iir_band_coeff(codec, iir_idx, band_idx, 0);
ucontrol->value.integer.value[1] =
get_iir_band_coeff(codec, iir_idx, band_idx, 1);
ucontrol->value.integer.value[2] =
get_iir_band_coeff(codec, iir_idx, band_idx, 2);
ucontrol->value.integer.value[3] =
get_iir_band_coeff(codec, iir_idx, band_idx, 3);
ucontrol->value.integer.value[4] =
get_iir_band_coeff(codec, iir_idx, band_idx, 4);
pr_debug("%s: IIR #%d band #%d b0 = 0x%x\n"
"%s: IIR #%d band #%d b1 = 0x%x\n"
"%s: IIR #%d band #%d b2 = 0x%x\n"
"%s: IIR #%d band #%d a1 = 0x%x\n"
"%s: IIR #%d band #%d a2 = 0x%x\n",
__func__, iir_idx, band_idx,
(uint32_t)ucontrol->value.integer.value[0],
__func__, iir_idx, band_idx,
(uint32_t)ucontrol->value.integer.value[1],
__func__, iir_idx, band_idx,
(uint32_t)ucontrol->value.integer.value[2],
__func__, iir_idx, band_idx,
(uint32_t)ucontrol->value.integer.value[3],
__func__, iir_idx, band_idx,
(uint32_t)ucontrol->value.integer.value[4]);
return 0;
}
static void set_iir_band_coeff(struct snd_soc_codec *codec,
int iir_idx, int band_idx,
int coeff_idx, uint32_t value)
{
/* Mask top 3 bits, 6-8 are reserved */
/* Update address manually each time */
snd_soc_write(codec,
(TABLA_A_CDC_IIR1_COEF_B1_CTL + 16 * iir_idx),
(band_idx * BAND_MAX + coeff_idx) & 0x1F);
/* Mask top 2 bits, 7-8 are reserved */
snd_soc_write(codec,
(TABLA_A_CDC_IIR1_COEF_B2_CTL + 16 * iir_idx),
(value >> 24) & 0x3F);
/* Isolate 8bits at a time */
snd_soc_write(codec,
(TABLA_A_CDC_IIR1_COEF_B3_CTL + 16 * iir_idx),
(value >> 16) & 0xFF);
snd_soc_write(codec,
(TABLA_A_CDC_IIR1_COEF_B4_CTL + 16 * iir_idx),
(value >> 8) & 0xFF);
snd_soc_write(codec,
(TABLA_A_CDC_IIR1_COEF_B5_CTL + 16 * iir_idx),
value & 0xFF);
}
static int tabla_put_iir_band_audio_mixer(
struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
int iir_idx = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->reg;
int band_idx = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->shift;
set_iir_band_coeff(codec, iir_idx, band_idx, 0,
ucontrol->value.integer.value[0]);
set_iir_band_coeff(codec, iir_idx, band_idx, 1,
ucontrol->value.integer.value[1]);
set_iir_band_coeff(codec, iir_idx, band_idx, 2,
ucontrol->value.integer.value[2]);
set_iir_band_coeff(codec, iir_idx, band_idx, 3,
ucontrol->value.integer.value[3]);
set_iir_band_coeff(codec, iir_idx, band_idx, 4,
ucontrol->value.integer.value[4]);
pr_debug("%s: IIR #%d band #%d b0 = 0x%x\n"
"%s: IIR #%d band #%d b1 = 0x%x\n"
"%s: IIR #%d band #%d b2 = 0x%x\n"
"%s: IIR #%d band #%d a1 = 0x%x\n"
"%s: IIR #%d band #%d a2 = 0x%x\n",
__func__, iir_idx, band_idx,
get_iir_band_coeff(codec, iir_idx, band_idx, 0),
__func__, iir_idx, band_idx,
get_iir_band_coeff(codec, iir_idx, band_idx, 1),
__func__, iir_idx, band_idx,
get_iir_band_coeff(codec, iir_idx, band_idx, 2),
__func__, iir_idx, band_idx,
get_iir_band_coeff(codec, iir_idx, band_idx, 3),
__func__, iir_idx, band_idx,
get_iir_band_coeff(codec, iir_idx, band_idx, 4));
return 0;
}
static int tabla_compander_gain_offset(
struct snd_soc_codec *codec, u32 enable,
unsigned int pa_reg, unsigned int vol_reg,
int mask, int event,
struct comp_dgtl_gain_offset *gain_offset,
int index)
{
unsigned int pa_gain = snd_soc_read(codec, pa_reg);
unsigned int digital_vol = snd_soc_read(codec, vol_reg);
int pa_mode = pa_gain & mask;
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
pr_debug("%s: pa_gain(0x%x=0x%x)digital_vol(0x%x=0x%x)event(0x%x) index(%d)\n",
__func__, pa_reg, pa_gain, vol_reg, digital_vol, event, index);
if (((pa_gain & 0xF) + 1) > ARRAY_SIZE(comp_dgtl_gain) ||
(index >= ARRAY_SIZE(tabla->comp_gain_offset))) {
pr_err("%s: Out of array boundary\n", __func__);
return -EINVAL;
}
if (SND_SOC_DAPM_EVENT_ON(event) && (enable != 0)) {
gain_offset->whole_db_gain = COMP_DIGITAL_DB_GAIN_APPLY(
(digital_vol - comp_dgtl_gain[pa_gain & 0xF].whole_db_gain),
comp_dgtl_gain[pa_gain & 0xF].half_db_gain);
pr_debug("%s: listed whole_db_gain:0x%x, adjusted whole_db_gain:0x%x\n",
__func__, comp_dgtl_gain[pa_gain & 0xF].whole_db_gain,
gain_offset->whole_db_gain);
gain_offset->half_db_gain =
comp_dgtl_gain[pa_gain & 0xF].half_db_gain;
tabla->comp_gain_offset[index] = digital_vol -
gain_offset->whole_db_gain ;
}
if (SND_SOC_DAPM_EVENT_OFF(event) && (pa_mode == 0)) {
gain_offset->whole_db_gain = digital_vol +
tabla->comp_gain_offset[index];
pr_debug("%s: listed whole_db_gain:0x%x, adjusted whole_db_gain:0x%x\n",
__func__, comp_dgtl_gain[pa_gain & 0xF].whole_db_gain,
gain_offset->whole_db_gain);
gain_offset->half_db_gain = 0;
}
pr_debug("%s: half_db_gain(%d)whole_db_gain(%d)comp_gain_offset[%d](%d)\n",
__func__, gain_offset->half_db_gain,
gain_offset->whole_db_gain, index,
tabla->comp_gain_offset[index]);
return 0;
}
static int tabla_config_gain_compander(
struct snd_soc_codec *codec,
u32 compander, u32 enable, int event)
{
int value = 0;
int mask = 1 << 4;
struct comp_dgtl_gain_offset gain_offset = {0, 0};
if (compander >= COMPANDER_MAX) {
pr_err("%s: Error, invalid compander channel\n", __func__);
return -EINVAL;
}
if ((enable == 0) || SND_SOC_DAPM_EVENT_OFF(event))
value = 1 << 4;
if (compander == COMPANDER_1) {
tabla_compander_gain_offset(codec, enable,
TABLA_A_RX_HPH_L_GAIN,
TABLA_A_CDC_RX1_VOL_CTL_B2_CTL,
mask, event, &gain_offset, 0);
snd_soc_update_bits(codec, TABLA_A_RX_HPH_L_GAIN, mask, value);
snd_soc_update_bits(codec, TABLA_A_CDC_RX1_VOL_CTL_B2_CTL,
0xFF, gain_offset.whole_db_gain);
snd_soc_update_bits(codec, TABLA_A_CDC_RX1_B6_CTL,
0x02, gain_offset.half_db_gain);
tabla_compander_gain_offset(codec, enable,
TABLA_A_RX_HPH_R_GAIN,
TABLA_A_CDC_RX2_VOL_CTL_B2_CTL,
mask, event, &gain_offset, 1);
snd_soc_update_bits(codec, TABLA_A_RX_HPH_R_GAIN, mask, value);
snd_soc_update_bits(codec, TABLA_A_CDC_RX2_VOL_CTL_B2_CTL,
0xFF, gain_offset.whole_db_gain);
snd_soc_update_bits(codec, TABLA_A_CDC_RX2_B6_CTL,
0x02, gain_offset.half_db_gain);
} else if (compander == COMPANDER_2) {
tabla_compander_gain_offset(codec, enable,
TABLA_A_RX_LINE_1_GAIN,
TABLA_A_CDC_RX3_VOL_CTL_B2_CTL,
mask, event, &gain_offset, 2);
snd_soc_update_bits(codec, TABLA_A_RX_LINE_1_GAIN, mask, value);
snd_soc_update_bits(codec, TABLA_A_CDC_RX3_VOL_CTL_B2_CTL,
0xFF, gain_offset.whole_db_gain);
snd_soc_update_bits(codec, TABLA_A_CDC_RX3_B6_CTL,
0x02, gain_offset.half_db_gain);
tabla_compander_gain_offset(codec, enable,
TABLA_A_RX_LINE_3_GAIN,
TABLA_A_CDC_RX4_VOL_CTL_B2_CTL,
mask, event, &gain_offset, 3);
snd_soc_update_bits(codec, TABLA_A_RX_LINE_3_GAIN, mask, value);
snd_soc_update_bits(codec, TABLA_A_CDC_RX4_VOL_CTL_B2_CTL,
0xFF, gain_offset.whole_db_gain);
snd_soc_update_bits(codec, TABLA_A_CDC_RX4_B6_CTL,
0x02, gain_offset.half_db_gain);
tabla_compander_gain_offset(codec, enable,
TABLA_A_RX_LINE_2_GAIN,
TABLA_A_CDC_RX5_VOL_CTL_B2_CTL,
mask, event, &gain_offset, 4);
snd_soc_update_bits(codec, TABLA_A_RX_LINE_2_GAIN, mask, value);
snd_soc_update_bits(codec, TABLA_A_CDC_RX5_VOL_CTL_B2_CTL,
0xFF, gain_offset.whole_db_gain);
snd_soc_update_bits(codec, TABLA_A_CDC_RX5_B6_CTL,
0x02, gain_offset.half_db_gain);
tabla_compander_gain_offset(codec, enable,
TABLA_A_RX_LINE_4_GAIN,
TABLA_A_CDC_RX6_VOL_CTL_B2_CTL,
mask, event, &gain_offset, 5);
snd_soc_update_bits(codec, TABLA_A_RX_LINE_4_GAIN, mask, value);
snd_soc_update_bits(codec, TABLA_A_CDC_RX6_VOL_CTL_B2_CTL,
0xFF, gain_offset.whole_db_gain);
snd_soc_update_bits(codec, TABLA_A_CDC_RX6_B6_CTL,
0x02, gain_offset.half_db_gain);
}
return 0;
}
static int tabla_get_compander(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
int comp = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->max;
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
ucontrol->value.integer.value[0] = tabla->comp_enabled[comp];
return 0;
}
static int tabla_set_compander(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
int comp = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->max;
int value = ucontrol->value.integer.value[0];
pr_debug("%s: compander #%d enable %d\n",
__func__, comp + 1, value);
if (value == tabla->comp_enabled[comp]) {
pr_debug("%s: compander #%d enable %d no change\n",
__func__, comp + 1, value);
return 0;
}
tabla->comp_enabled[comp] = value;
return 0;
}
static int tabla_config_compander(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol,
int event)
{
struct snd_soc_codec *codec = w->codec;
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
u32 rate = tabla->comp_fs[w->shift];
pr_debug("%s: compander #%d enable %d event %d widget name %s\n",
__func__, w->shift + 1,
tabla->comp_enabled[w->shift], event , w->name);
if (tabla->comp_enabled[w->shift] == 0)
goto rtn;
if ((w->shift == COMPANDER_1) && (tabla->anc_func)) {
pr_debug("%s: ANC is enabled so compander #%d cannot be enabled\n",
__func__, w->shift + 1);
goto rtn;
}
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
/* Update compander sample rate */
snd_soc_update_bits(codec, TABLA_A_CDC_COMP1_FS_CFG +
w->shift * 8, 0x07, rate);
/* Enable both L/R compander clocks */
snd_soc_update_bits(codec,
TABLA_A_CDC_CLK_RX_B2_CTL,
1 << comp_shift[w->shift],
1 << comp_shift[w->shift]);
/* Toggle compander reset bits */
snd_soc_update_bits(codec,
TABLA_A_CDC_CLK_OTHR_RESET_CTL,
1 << comp_shift[w->shift],
1 << comp_shift[w->shift]);
snd_soc_update_bits(codec,
TABLA_A_CDC_CLK_OTHR_RESET_CTL,
1 << comp_shift[w->shift], 0);
tabla_config_gain_compander(codec, w->shift, 1, event);
/* Compander enable -> 0x370/0x378 */
snd_soc_update_bits(codec, TABLA_A_CDC_COMP1_B1_CTL +
w->shift * 8, 0x03, 0x03);
/* Update the RMS meter resampling */
snd_soc_update_bits(codec,
TABLA_A_CDC_COMP1_B3_CTL +
w->shift * 8, 0xFF, 0x01);
snd_soc_update_bits(codec,
TABLA_A_CDC_COMP1_B2_CTL +
w->shift * 8, 0xF0, 0x50);
usleep_range(COMP_BRINGUP_WAIT_TIME, COMP_BRINGUP_WAIT_TIME);
break;
case SND_SOC_DAPM_POST_PMU:
/* Set sample rate dependent paramater */
if (w->shift == COMPANDER_1) {
snd_soc_update_bits(codec,
TABLA_A_CDC_CLSG_CTL,
0x11, 0x00);
snd_soc_write(codec,
TABLA_A_CDC_CONN_CLSG_CTL, 0x11);
}
snd_soc_update_bits(codec, TABLA_A_CDC_COMP1_B2_CTL +
w->shift * 8, 0x0F,
comp_samp_params[rate].peak_det_timeout);
snd_soc_update_bits(codec, TABLA_A_CDC_COMP1_B2_CTL +
w->shift * 8, 0xF0,
comp_samp_params[rate].rms_meter_div_fact);
snd_soc_update_bits(codec, TABLA_A_CDC_COMP1_B3_CTL +
w->shift * 8, 0xFF,
comp_samp_params[rate].rms_meter_resamp_fact);
snd_soc_update_bits(codec, TABLA_A_CDC_COMP1_B1_CTL +
w->shift * 8, 0x38,
comp_samp_params[rate].shutdown_timeout);
break;
case SND_SOC_DAPM_PRE_PMD:
break;
case SND_SOC_DAPM_POST_PMD:
/* Disable the compander */
snd_soc_update_bits(codec, TABLA_A_CDC_COMP1_B1_CTL +
w->shift * 8, 0x03, 0x00);
/* Toggle compander reset bits */
snd_soc_update_bits(codec,
TABLA_A_CDC_CLK_OTHR_RESET_CTL,
1 << comp_shift[w->shift],
1 << comp_shift[w->shift]);
snd_soc_update_bits(codec,
TABLA_A_CDC_CLK_OTHR_RESET_CTL,
1 << comp_shift[w->shift], 0);
/* Turn off the clock for compander in pair */
snd_soc_update_bits(codec, TABLA_A_CDC_CLK_RX_B2_CTL,
0x03 << comp_shift[w->shift], 0);
/* Restore the gain */
tabla_config_gain_compander(codec, w->shift,
tabla->comp_enabled[w->shift],
event);
if (w->shift == COMPANDER_1) {
snd_soc_update_bits(codec,
TABLA_A_CDC_CLSG_CTL,
0x11, 0x11);
snd_soc_write(codec,
TABLA_A_CDC_CONN_CLSG_CTL, 0x14);
}
break;
}
rtn:
return 0;
}
static int tabla_codec_hphr_dem_input_selection(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol,
int event)
{
struct snd_soc_codec *codec = w->codec;
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
pr_debug("%s: compander#1->enable(%d) reg(0x%x = 0x%x) event(%d)\n",
__func__, tabla->comp_enabled[COMPANDER_1],
TABLA_A_CDC_RX1_B6_CTL,
snd_soc_read(codec, TABLA_A_CDC_RX1_B6_CTL), event);
switch (event) {
case SND_SOC_DAPM_POST_PMU:
if (tabla->comp_enabled[COMPANDER_1] && !tabla->anc_func)
snd_soc_update_bits(codec, TABLA_A_CDC_RX1_B6_CTL,
1 << w->shift, 0);
else
snd_soc_update_bits(codec, TABLA_A_CDC_RX1_B6_CTL,
1 << w->shift, 1 << w->shift);
break;
case SND_SOC_DAPM_POST_PMD:
snd_soc_update_bits(codec, TABLA_A_CDC_RX1_B6_CTL,
1 << w->shift, 0);
break;
default:
return -EINVAL;
}
return 0;
}
static int tabla_codec_hphl_dem_input_selection(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol,
int event)
{
struct snd_soc_codec *codec = w->codec;
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
pr_debug("%s: compander#1->enable(%d) reg(0x%x = 0x%x) event(%d)\n",
__func__, tabla->comp_enabled[COMPANDER_1],
TABLA_A_CDC_RX2_B6_CTL,
snd_soc_read(codec, TABLA_A_CDC_RX2_B6_CTL), event);
switch (event) {
case SND_SOC_DAPM_POST_PMU:
if (tabla->comp_enabled[COMPANDER_1] && !tabla->anc_func)
snd_soc_update_bits(codec, TABLA_A_CDC_RX2_B6_CTL,
1 << w->shift, 0);
else
snd_soc_update_bits(codec, TABLA_A_CDC_RX2_B6_CTL,
1 << w->shift, 1 << w->shift);
break;
case SND_SOC_DAPM_POST_PMD:
snd_soc_update_bits(codec, TABLA_A_CDC_RX2_B6_CTL,
1 << w->shift, 0);
break;
default:
return -EINVAL;
}
return 0;
}
static const char *const tabla_anc_func_text[] = {"OFF", "ON"};
static const struct soc_enum tabla_anc_func_enum =
SOC_ENUM_SINGLE_EXT(2, tabla_anc_func_text);
static const char *tabla_ear_pa_gain_text[] = {"POS_6_DB", "POS_2_DB"};
static const struct soc_enum tabla_ear_pa_gain_enum[] = {
SOC_ENUM_SINGLE_EXT(2, tabla_ear_pa_gain_text),
};
/*cut of frequency for high pass filter*/
static const char *cf_text[] = {
"MIN_3DB_4Hz", "MIN_3DB_75Hz", "MIN_3DB_150Hz"
};
static const struct soc_enum cf_dec1_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_TX1_MUX_CTL, 4, 3, cf_text);
static const struct soc_enum cf_dec2_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_TX2_MUX_CTL, 4, 3, cf_text);
static const struct soc_enum cf_dec3_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_TX3_MUX_CTL, 4, 3, cf_text);
static const struct soc_enum cf_dec4_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_TX4_MUX_CTL, 4, 3, cf_text);
static const struct soc_enum cf_dec5_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_TX5_MUX_CTL, 4, 3, cf_text);
static const struct soc_enum cf_dec6_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_TX6_MUX_CTL, 4, 3, cf_text);
static const struct soc_enum cf_dec7_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_TX7_MUX_CTL, 4, 3, cf_text);
static const struct soc_enum cf_dec8_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_TX8_MUX_CTL, 4, 3, cf_text);
static const struct soc_enum cf_dec9_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_TX9_MUX_CTL, 4, 3, cf_text);
static const struct soc_enum cf_dec10_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_TX10_MUX_CTL, 4, 3, cf_text);
static const struct soc_enum cf_rxmix1_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_RX1_B4_CTL, 1, 3, cf_text);
static const struct soc_enum cf_rxmix2_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_RX2_B4_CTL, 1, 3, cf_text);
static const struct soc_enum cf_rxmix3_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_RX3_B4_CTL, 1, 3, cf_text);
static const struct soc_enum cf_rxmix4_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_RX4_B4_CTL, 1, 3, cf_text);
static const struct soc_enum cf_rxmix5_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_RX5_B4_CTL, 1, 3, cf_text)
;
static const struct soc_enum cf_rxmix6_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_RX6_B4_CTL, 1, 3, cf_text);
static const struct soc_enum cf_rxmix7_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_RX7_B4_CTL, 1, 3, cf_text);
static const struct snd_kcontrol_new tabla_snd_controls[] = {
SOC_ENUM_EXT("EAR PA Gain", tabla_ear_pa_gain_enum[0],
tabla_pa_gain_get, tabla_pa_gain_put),
SOC_SINGLE_TLV("LINEOUT1 Volume", TABLA_A_RX_LINE_1_GAIN, 0, 12, 1,
line_gain),
SOC_SINGLE_TLV("LINEOUT2 Volume", TABLA_A_RX_LINE_2_GAIN, 0, 12, 1,
line_gain),
SOC_SINGLE_TLV("LINEOUT3 Volume", TABLA_A_RX_LINE_3_GAIN, 0, 12, 1,
line_gain),
SOC_SINGLE_TLV("LINEOUT4 Volume", TABLA_A_RX_LINE_4_GAIN, 0, 12, 1,
line_gain),
SOC_SINGLE_TLV("LINEOUT5 Volume", TABLA_A_RX_LINE_5_GAIN, 0, 12, 1,
line_gain),
SOC_SINGLE_TLV("HPHL Volume", TABLA_A_RX_HPH_L_GAIN, 0, 12, 1,
line_gain),
SOC_SINGLE_TLV("HPHR Volume", TABLA_A_RX_HPH_R_GAIN, 0, 12, 1,
line_gain),
SOC_SINGLE_SX_TLV("RX1 Digital Volume", TABLA_A_CDC_RX1_VOL_CTL_B2_CTL,
0, -84, 40, digital_gain),
SOC_SINGLE_SX_TLV("RX2 Digital Volume", TABLA_A_CDC_RX2_VOL_CTL_B2_CTL,
0, -84, 40, digital_gain),
SOC_SINGLE_SX_TLV("RX3 Digital Volume", TABLA_A_CDC_RX3_VOL_CTL_B2_CTL,
0, -84, 40, digital_gain),
SOC_SINGLE_SX_TLV("RX4 Digital Volume", TABLA_A_CDC_RX4_VOL_CTL_B2_CTL,
0, -84, 40, digital_gain),
SOC_SINGLE_SX_TLV("RX5 Digital Volume", TABLA_A_CDC_RX5_VOL_CTL_B2_CTL,
0, -84, 40, digital_gain),
SOC_SINGLE_SX_TLV("RX6 Digital Volume", TABLA_A_CDC_RX6_VOL_CTL_B2_CTL,
0, -84, 40, digital_gain),
SOC_SINGLE_SX_TLV("RX7 Digital Volume", TABLA_A_CDC_RX7_VOL_CTL_B2_CTL,
0, -84, 40, digital_gain),
SOC_SINGLE_SX_TLV("DEC1 Volume", TABLA_A_CDC_TX1_VOL_CTL_GAIN, 0, -84,
40, digital_gain),
SOC_SINGLE_SX_TLV("DEC2 Volume", TABLA_A_CDC_TX2_VOL_CTL_GAIN, 0, -84,
40, digital_gain),
SOC_SINGLE_SX_TLV("DEC3 Volume", TABLA_A_CDC_TX3_VOL_CTL_GAIN, 0, -84,
40, digital_gain),
SOC_SINGLE_SX_TLV("DEC4 Volume", TABLA_A_CDC_TX4_VOL_CTL_GAIN, 0, -84,
40, digital_gain),
SOC_SINGLE_SX_TLV("DEC5 Volume", TABLA_A_CDC_TX5_VOL_CTL_GAIN, 0, -84,
40, digital_gain),
SOC_SINGLE_SX_TLV("DEC6 Volume", TABLA_A_CDC_TX6_VOL_CTL_GAIN, 0, -84,
40, digital_gain),
SOC_SINGLE_SX_TLV("DEC7 Volume", TABLA_A_CDC_TX7_VOL_CTL_GAIN, 0, -84,
40, digital_gain),
SOC_SINGLE_SX_TLV("DEC8 Volume", TABLA_A_CDC_TX8_VOL_CTL_GAIN, 0, -84,
40, digital_gain),
SOC_SINGLE_SX_TLV("DEC9 Volume", TABLA_A_CDC_TX9_VOL_CTL_GAIN, 0, -84,
40, digital_gain),
SOC_SINGLE_SX_TLV("DEC10 Volume", TABLA_A_CDC_TX10_VOL_CTL_GAIN, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("IIR1 INP1 Volume", TABLA_A_CDC_IIR1_GAIN_B1_CTL, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("IIR1 INP2 Volume", TABLA_A_CDC_IIR1_GAIN_B2_CTL, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("IIR1 INP3 Volume", TABLA_A_CDC_IIR1_GAIN_B3_CTL, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("IIR1 INP4 Volume", TABLA_A_CDC_IIR1_GAIN_B4_CTL, 0,
-84, 40, digital_gain),
SOC_SINGLE_TLV("ADC1 Volume", TABLA_A_TX_1_2_EN, 5, 3, 0, analog_gain),
SOC_SINGLE_TLV("ADC2 Volume", TABLA_A_TX_1_2_EN, 1, 3, 0, analog_gain),
SOC_SINGLE_TLV("ADC3 Volume", TABLA_A_TX_3_4_EN, 5, 3, 0, analog_gain),
SOC_SINGLE_TLV("ADC4 Volume", TABLA_A_TX_3_4_EN, 1, 3, 0, analog_gain),
SOC_SINGLE_TLV("ADC5 Volume", TABLA_A_TX_5_6_EN, 5, 3, 0, analog_gain),
SOC_SINGLE_TLV("ADC6 Volume", TABLA_A_TX_5_6_EN, 1, 3, 0, analog_gain),
SOC_SINGLE_TLV("AUX_PGA_LEFT Volume", TABLA_A_AUX_L_GAIN, 0, 39, 0,
aux_pga_gain),
SOC_SINGLE_TLV("AUX_PGA_RIGHT Volume", TABLA_A_AUX_R_GAIN, 0, 39, 0,
aux_pga_gain),
SOC_SINGLE("MICBIAS1 CAPLESS Switch", TABLA_A_MICB_1_CTL, 4, 1, 1),
SOC_SINGLE("MICBIAS2 CAPLESS Switch", TABLA_A_MICB_2_CTL, 4, 1, 1),
SOC_SINGLE("MICBIAS3 CAPLESS Switch", TABLA_A_MICB_3_CTL, 4, 1, 1),
SOC_SINGLE_EXT("ANC Slot", SND_SOC_NOPM, 0, 0, 100, tabla_get_anc_slot,
tabla_put_anc_slot),
SOC_ENUM_EXT("ANC Function", tabla_anc_func_enum, tabla_get_anc_func,
tabla_put_anc_func),
SOC_ENUM("TX1 HPF cut off", cf_dec1_enum),
SOC_ENUM("TX2 HPF cut off", cf_dec2_enum),
SOC_ENUM("TX3 HPF cut off", cf_dec3_enum),
SOC_ENUM("TX4 HPF cut off", cf_dec4_enum),
SOC_ENUM("TX5 HPF cut off", cf_dec5_enum),
SOC_ENUM("TX6 HPF cut off", cf_dec6_enum),
SOC_ENUM("TX7 HPF cut off", cf_dec7_enum),
SOC_ENUM("TX8 HPF cut off", cf_dec8_enum),
SOC_ENUM("TX9 HPF cut off", cf_dec9_enum),
SOC_ENUM("TX10 HPF cut off", cf_dec10_enum),
SOC_SINGLE("TX1 HPF Switch", TABLA_A_CDC_TX1_MUX_CTL, 3, 1, 0),
SOC_SINGLE("TX2 HPF Switch", TABLA_A_CDC_TX2_MUX_CTL, 3, 1, 0),
SOC_SINGLE("TX3 HPF Switch", TABLA_A_CDC_TX3_MUX_CTL, 3, 1, 0),
SOC_SINGLE("TX4 HPF Switch", TABLA_A_CDC_TX4_MUX_CTL, 3, 1, 0),
SOC_SINGLE("TX5 HPF Switch", TABLA_A_CDC_TX5_MUX_CTL, 3, 1, 0),
SOC_SINGLE("TX6 HPF Switch", TABLA_A_CDC_TX6_MUX_CTL, 3, 1, 0),
SOC_SINGLE("TX7 HPF Switch", TABLA_A_CDC_TX7_MUX_CTL, 3, 1, 0),
SOC_SINGLE("TX8 HPF Switch", TABLA_A_CDC_TX8_MUX_CTL, 3, 1, 0),
SOC_SINGLE("TX9 HPF Switch", TABLA_A_CDC_TX9_MUX_CTL, 3, 1, 0),
SOC_SINGLE("TX10 HPF Switch", TABLA_A_CDC_TX10_MUX_CTL, 3, 1, 0),
SOC_SINGLE("RX1 HPF Switch", TABLA_A_CDC_RX1_B5_CTL, 2, 1, 0),
SOC_SINGLE("RX2 HPF Switch", TABLA_A_CDC_RX2_B5_CTL, 2, 1, 0),
SOC_SINGLE("RX3 HPF Switch", TABLA_A_CDC_RX3_B5_CTL, 2, 1, 0),
SOC_SINGLE("RX4 HPF Switch", TABLA_A_CDC_RX4_B5_CTL, 2, 1, 0),
SOC_SINGLE("RX5 HPF Switch", TABLA_A_CDC_RX5_B5_CTL, 2, 1, 0),
SOC_SINGLE("RX6 HPF Switch", TABLA_A_CDC_RX6_B5_CTL, 2, 1, 0),
SOC_SINGLE("RX7 HPF Switch", TABLA_A_CDC_RX7_B5_CTL, 2, 1, 0),
SOC_ENUM("RX1 HPF cut off", cf_rxmix1_enum),
SOC_ENUM("RX2 HPF cut off", cf_rxmix2_enum),
SOC_ENUM("RX3 HPF cut off", cf_rxmix3_enum),
SOC_ENUM("RX4 HPF cut off", cf_rxmix4_enum),
SOC_ENUM("RX5 HPF cut off", cf_rxmix5_enum),
SOC_ENUM("RX6 HPF cut off", cf_rxmix6_enum),
SOC_ENUM("RX7 HPF cut off", cf_rxmix7_enum),
SOC_SINGLE_EXT("IIR1 Enable Band1", IIR1, BAND1, 1, 0,
tabla_get_iir_enable_audio_mixer, tabla_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR1 Enable Band2", IIR1, BAND2, 1, 0,
tabla_get_iir_enable_audio_mixer, tabla_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR1 Enable Band3", IIR1, BAND3, 1, 0,
tabla_get_iir_enable_audio_mixer, tabla_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR1 Enable Band4", IIR1, BAND4, 1, 0,
tabla_get_iir_enable_audio_mixer, tabla_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR1 Enable Band5", IIR1, BAND5, 1, 0,
tabla_get_iir_enable_audio_mixer, tabla_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR2 Enable Band1", IIR2, BAND1, 1, 0,
tabla_get_iir_enable_audio_mixer, tabla_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR2 Enable Band2", IIR2, BAND2, 1, 0,
tabla_get_iir_enable_audio_mixer, tabla_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR2 Enable Band3", IIR2, BAND3, 1, 0,
tabla_get_iir_enable_audio_mixer, tabla_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR2 Enable Band4", IIR2, BAND4, 1, 0,
tabla_get_iir_enable_audio_mixer, tabla_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR2 Enable Band5", IIR2, BAND5, 1, 0,
tabla_get_iir_enable_audio_mixer, tabla_put_iir_enable_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR1 Band1", IIR1, BAND1, 255, 0, 5,
tabla_get_iir_band_audio_mixer, tabla_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR1 Band2", IIR1, BAND2, 255, 0, 5,
tabla_get_iir_band_audio_mixer, tabla_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR1 Band3", IIR1, BAND3, 255, 0, 5,
tabla_get_iir_band_audio_mixer, tabla_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR1 Band4", IIR1, BAND4, 255, 0, 5,
tabla_get_iir_band_audio_mixer, tabla_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR1 Band5", IIR1, BAND5, 255, 0, 5,
tabla_get_iir_band_audio_mixer, tabla_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR2 Band1", IIR2, BAND1, 255, 0, 5,
tabla_get_iir_band_audio_mixer, tabla_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR2 Band2", IIR2, BAND2, 255, 0, 5,
tabla_get_iir_band_audio_mixer, tabla_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR2 Band3", IIR2, BAND3, 255, 0, 5,
tabla_get_iir_band_audio_mixer, tabla_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR2 Band4", IIR2, BAND4, 255, 0, 5,
tabla_get_iir_band_audio_mixer, tabla_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR2 Band5", IIR2, BAND5, 255, 0, 5,
tabla_get_iir_band_audio_mixer, tabla_put_iir_band_audio_mixer),
SOC_SINGLE_EXT("COMP1 Switch", SND_SOC_NOPM, 1, COMPANDER_1, 0,
tabla_get_compander, tabla_set_compander),
SOC_SINGLE_EXT("COMP2 Switch", SND_SOC_NOPM, 0, COMPANDER_2, 0,
tabla_get_compander, tabla_set_compander),
};
static const struct snd_kcontrol_new tabla_1_x_snd_controls[] = {
SOC_SINGLE("MICBIAS4 CAPLESS Switch", TABLA_1_A_MICB_4_CTL, 4, 1, 1),
};
static const struct snd_kcontrol_new tabla_2_higher_snd_controls[] = {
SOC_SINGLE("MICBIAS4 CAPLESS Switch", TABLA_2_A_MICB_4_CTL, 4, 1, 1),
};
static const char *rx_mix1_text[] = {
"ZERO", "SRC1", "SRC2", "IIR1", "IIR2", "RX1", "RX2", "RX3", "RX4",
"RX5", "RX6", "RX7"
};
static const char *rx_mix2_text[] = {
"ZERO", "SRC1", "SRC2", "IIR1", "IIR2"
};
static const char *rx_dsm_text[] = {
"CIC_OUT", "DSM_INV"
};
static const char *sb_tx1_mux_text[] = {
"ZERO", "RMIX1", "RMIX2", "RMIX3", "RMIX4", "RMIX5", "RMIX6", "RMIX7",
"DEC1"
};
static const char *sb_tx2_mux_text[] = {
"ZERO", "RMIX1", "RMIX2", "RMIX3", "RMIX4", "RMIX5", "RMIX6", "RMIX7",
"DEC2"
};
static const char *sb_tx3_mux_text[] = {
"ZERO", "RMIX1", "RMIX2", "RMIX3", "RMIX4", "RMIX5", "RMIX6", "RMIX7",
"DEC3"
};
static const char *sb_tx4_mux_text[] = {
"ZERO", "RMIX1", "RMIX2", "RMIX3", "RMIX4", "RMIX5", "RMIX6", "RMIX7",
"DEC4"
};
static const char *sb_tx5_mux_text[] = {
"ZERO", "RMIX1", "RMIX2", "RMIX3", "RMIX4", "RMIX5", "RMIX6", "RMIX7",
"DEC5"
};
static const char *sb_tx6_mux_text[] = {
"ZERO", "RMIX1", "RMIX2", "RMIX3", "RMIX4", "RMIX5", "RMIX6", "RMIX7",
"DEC6"
};
static const char const *sb_tx7_to_tx10_mux_text[] = {
"ZERO", "RMIX1", "RMIX2", "RMIX3", "RMIX4", "RMIX5", "RMIX6", "RMIX7",
"DEC1", "DEC2", "DEC3", "DEC4", "DEC5", "DEC6", "DEC7", "DEC8",
"DEC9", "DEC10"
};
static const char *dec1_mux_text[] = {
"ZERO", "DMIC1", "ADC6",
};
static const char *dec2_mux_text[] = {
"ZERO", "DMIC2", "ADC5",
};
static const char *dec3_mux_text[] = {
"ZERO", "DMIC3", "ADC4",
};
static const char *dec4_mux_text[] = {
"ZERO", "DMIC4", "ADC3",
};
static const char *dec5_mux_text[] = {
"ZERO", "DMIC5", "ADC2",
};
static const char *dec6_mux_text[] = {
"ZERO", "DMIC6", "ADC1",
};
static const char const *dec7_mux_text[] = {
"ZERO", "DMIC1", "DMIC6", "ADC1", "ADC6", "ANC1_FB", "ANC2_FB",
};
static const char *dec8_mux_text[] = {
"ZERO", "DMIC2", "DMIC5", "ADC2", "ADC5",
};
static const char *dec9_mux_text[] = {
"ZERO", "DMIC4", "DMIC5", "ADC2", "ADC3", "ADCMB", "ANC1_FB", "ANC2_FB",
};
static const char *dec10_mux_text[] = {
"ZERO", "DMIC3", "DMIC6", "ADC1", "ADC4", "ADCMB", "ANC1_FB", "ANC2_FB",
};
static const char const *anc_mux_text[] = {
"ZERO", "ADC1", "ADC2", "ADC3", "ADC4", "ADC5", "ADC6", "ADC_MB",
"RSVD_1", "DMIC1", "DMIC2", "DMIC3", "DMIC4", "DMIC5", "DMIC6"
};
static const char const *anc1_fb_mux_text[] = {
"ZERO", "EAR_HPH_L", "EAR_LINE_1",
};
static const char *const iir_inp1_text[] = {
"ZERO", "DEC1", "DEC2", "DEC3", "DEC4", "DEC5", "DEC6", "DEC7", "DEC8",
"DEC9", "DEC10", "RX1", "RX2", "RX3", "RX4", "RX5", "RX6", "RX7"
};
static const struct soc_enum rx_mix1_inp1_chain_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_RX1_B1_CTL, 0, 12, rx_mix1_text);
static const struct soc_enum rx_mix1_inp2_chain_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_RX1_B1_CTL, 4, 12, rx_mix1_text);
static const struct soc_enum rx_mix1_inp3_chain_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_RX1_B2_CTL, 0, 12, rx_mix1_text);
static const struct soc_enum rx2_mix1_inp1_chain_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_RX2_B1_CTL, 0, 12, rx_mix1_text);
static const struct soc_enum rx2_mix1_inp2_chain_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_RX2_B1_CTL, 4, 12, rx_mix1_text);
static const struct soc_enum rx3_mix1_inp1_chain_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_RX3_B1_CTL, 0, 12, rx_mix1_text);
static const struct soc_enum rx3_mix1_inp2_chain_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_RX3_B1_CTL, 4, 12, rx_mix1_text);
static const struct soc_enum rx4_mix1_inp1_chain_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_RX4_B1_CTL, 0, 12, rx_mix1_text);
static const struct soc_enum rx4_mix1_inp2_chain_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_RX4_B1_CTL, 4, 12, rx_mix1_text);
static const struct soc_enum rx5_mix1_inp1_chain_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_RX5_B1_CTL, 0, 12, rx_mix1_text);
static const struct soc_enum rx5_mix1_inp2_chain_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_RX5_B1_CTL, 4, 12, rx_mix1_text);
static const struct soc_enum rx6_mix1_inp1_chain_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_RX6_B1_CTL, 0, 12, rx_mix1_text);
static const struct soc_enum rx6_mix1_inp2_chain_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_RX6_B1_CTL, 4, 12, rx_mix1_text);
static const struct soc_enum rx7_mix1_inp1_chain_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_RX7_B1_CTL, 0, 12, rx_mix1_text);
static const struct soc_enum rx7_mix1_inp2_chain_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_RX7_B1_CTL, 4, 12, rx_mix1_text);
static const struct soc_enum rx1_mix2_inp1_chain_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_RX1_B3_CTL, 0, 5, rx_mix2_text);
static const struct soc_enum rx1_mix2_inp2_chain_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_RX1_B3_CTL, 3, 5, rx_mix2_text);
static const struct soc_enum rx2_mix2_inp1_chain_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_RX2_B3_CTL, 0, 5, rx_mix2_text);
static const struct soc_enum rx2_mix2_inp2_chain_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_RX2_B3_CTL, 3, 5, rx_mix2_text);
static const struct soc_enum rx3_mix2_inp1_chain_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_RX3_B3_CTL, 0, 5, rx_mix2_text);
static const struct soc_enum rx3_mix2_inp2_chain_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_RX3_B3_CTL, 3, 5, rx_mix2_text);
static const struct soc_enum rx4_dsm_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_RX4_B6_CTL, 4, 2, rx_dsm_text);
static const struct soc_enum rx6_dsm_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_RX6_B6_CTL, 4, 2, rx_dsm_text);
static const struct soc_enum sb_tx1_mux_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_TX_SB_B1_CTL, 0, 9, sb_tx1_mux_text);
static const struct soc_enum sb_tx2_mux_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_TX_SB_B2_CTL, 0, 9, sb_tx2_mux_text);
static const struct soc_enum sb_tx3_mux_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_TX_SB_B3_CTL, 0, 9, sb_tx3_mux_text);
static const struct soc_enum sb_tx4_mux_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_TX_SB_B4_CTL, 0, 9, sb_tx4_mux_text);
static const struct soc_enum sb_tx5_mux_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_TX_SB_B5_CTL, 0, 9, sb_tx5_mux_text);
static const struct soc_enum sb_tx6_mux_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_TX_SB_B6_CTL, 0, 9, sb_tx6_mux_text);
static const struct soc_enum sb_tx7_mux_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_TX_SB_B7_CTL, 0, 18,
sb_tx7_to_tx10_mux_text);
static const struct soc_enum sb_tx8_mux_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_TX_SB_B8_CTL, 0, 18,
sb_tx7_to_tx10_mux_text);
static const struct soc_enum sb_tx9_mux_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_TX_SB_B9_CTL, 0, 18,
sb_tx7_to_tx10_mux_text);
static const struct soc_enum sb_tx10_mux_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_TX_SB_B10_CTL, 0, 18,
sb_tx7_to_tx10_mux_text);
static const struct soc_enum dec1_mux_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_TX_B1_CTL, 0, 3, dec1_mux_text);
static const struct soc_enum dec2_mux_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_TX_B1_CTL, 2, 3, dec2_mux_text);
static const struct soc_enum dec3_mux_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_TX_B1_CTL, 4, 3, dec3_mux_text);
static const struct soc_enum dec4_mux_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_TX_B1_CTL, 6, 3, dec4_mux_text);
static const struct soc_enum dec5_mux_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_TX_B2_CTL, 0, 3, dec5_mux_text);
static const struct soc_enum dec6_mux_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_TX_B2_CTL, 2, 3, dec6_mux_text);
static const struct soc_enum dec7_mux_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_TX_B2_CTL, 4, 7, dec7_mux_text);
static const struct soc_enum dec8_mux_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_TX_B3_CTL, 0, 7, dec8_mux_text);
static const struct soc_enum dec9_mux_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_TX_B3_CTL, 3, 8, dec9_mux_text);
static const struct soc_enum dec10_mux_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_TX_B4_CTL, 0, 8, dec10_mux_text);
static const struct soc_enum anc1_mux_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_ANC_B1_CTL, 0, 16, anc_mux_text);
static const struct soc_enum anc2_mux_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_ANC_B1_CTL, 4, 16, anc_mux_text);
static const struct soc_enum anc1_fb_mux_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_ANC_B2_CTL, 0, 3, anc1_fb_mux_text);
static const struct soc_enum iir1_inp1_mux_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_EQ1_B1_CTL, 0, 18, iir_inp1_text);
static const struct soc_enum iir2_inp1_mux_enum =
SOC_ENUM_SINGLE(TABLA_A_CDC_CONN_EQ2_B1_CTL, 0, 18, iir_inp1_text);
static const struct snd_kcontrol_new rx_mix1_inp1_mux =
SOC_DAPM_ENUM("RX1 MIX1 INP1 Mux", rx_mix1_inp1_chain_enum);
static const struct snd_kcontrol_new rx_mix1_inp2_mux =
SOC_DAPM_ENUM("RX1 MIX1 INP2 Mux", rx_mix1_inp2_chain_enum);
static const struct snd_kcontrol_new rx_mix1_inp3_mux =
SOC_DAPM_ENUM("RX1 MIX1 INP3 Mux", rx_mix1_inp3_chain_enum);
static const struct snd_kcontrol_new rx2_mix1_inp1_mux =
SOC_DAPM_ENUM("RX2 MIX1 INP1 Mux", rx2_mix1_inp1_chain_enum);
static const struct snd_kcontrol_new rx2_mix1_inp2_mux =
SOC_DAPM_ENUM("RX2 MIX1 INP2 Mux", rx2_mix1_inp2_chain_enum);
static const struct snd_kcontrol_new rx3_mix1_inp1_mux =
SOC_DAPM_ENUM("RX3 MIX1 INP1 Mux", rx3_mix1_inp1_chain_enum);
static const struct snd_kcontrol_new rx3_mix1_inp2_mux =
SOC_DAPM_ENUM("RX3 MIX1 INP2 Mux", rx3_mix1_inp2_chain_enum);
static const struct snd_kcontrol_new rx4_mix1_inp1_mux =
SOC_DAPM_ENUM("RX4 MIX1 INP1 Mux", rx4_mix1_inp1_chain_enum);
static const struct snd_kcontrol_new rx4_mix1_inp2_mux =
SOC_DAPM_ENUM("RX4 MIX1 INP2 Mux", rx4_mix1_inp2_chain_enum);
static const struct snd_kcontrol_new rx5_mix1_inp1_mux =
SOC_DAPM_ENUM("RX5 MIX1 INP1 Mux", rx5_mix1_inp1_chain_enum);
static const struct snd_kcontrol_new rx5_mix1_inp2_mux =
SOC_DAPM_ENUM("RX5 MIX1 INP2 Mux", rx5_mix1_inp2_chain_enum);
static const struct snd_kcontrol_new rx6_mix1_inp1_mux =
SOC_DAPM_ENUM("RX6 MIX1 INP1 Mux", rx6_mix1_inp1_chain_enum);
static const struct snd_kcontrol_new rx6_mix1_inp2_mux =
SOC_DAPM_ENUM("RX6 MIX1 INP2 Mux", rx6_mix1_inp2_chain_enum);
static const struct snd_kcontrol_new rx7_mix1_inp1_mux =
SOC_DAPM_ENUM("RX7 MIX1 INP1 Mux", rx7_mix1_inp1_chain_enum);
static const struct snd_kcontrol_new rx7_mix1_inp2_mux =
SOC_DAPM_ENUM("RX7 MIX1 INP2 Mux", rx7_mix1_inp2_chain_enum);
static const struct snd_kcontrol_new rx1_mix2_inp1_mux =
SOC_DAPM_ENUM("RX1 MIX2 INP1 Mux", rx1_mix2_inp1_chain_enum);
static const struct snd_kcontrol_new rx1_mix2_inp2_mux =
SOC_DAPM_ENUM("RX1 MIX2 INP2 Mux", rx1_mix2_inp2_chain_enum);
static const struct snd_kcontrol_new rx2_mix2_inp1_mux =
SOC_DAPM_ENUM("RX2 MIX2 INP1 Mux", rx2_mix2_inp1_chain_enum);
static const struct snd_kcontrol_new rx2_mix2_inp2_mux =
SOC_DAPM_ENUM("RX2 MIX2 INP2 Mux", rx2_mix2_inp2_chain_enum);
static const struct snd_kcontrol_new rx3_mix2_inp1_mux =
SOC_DAPM_ENUM("RX3 MIX2 INP1 Mux", rx3_mix2_inp1_chain_enum);
static const struct snd_kcontrol_new rx3_mix2_inp2_mux =
SOC_DAPM_ENUM("RX3 MIX2 INP2 Mux", rx3_mix2_inp2_chain_enum);
static const struct snd_kcontrol_new rx4_dsm_mux =
SOC_DAPM_ENUM("RX4 DSM MUX Mux", rx4_dsm_enum);
static const struct snd_kcontrol_new rx6_dsm_mux =
SOC_DAPM_ENUM("RX6 DSM MUX Mux", rx6_dsm_enum);
static const struct snd_kcontrol_new sb_tx1_mux =
SOC_DAPM_ENUM("SLIM TX1 MUX Mux", sb_tx1_mux_enum);
static const struct snd_kcontrol_new sb_tx2_mux =
SOC_DAPM_ENUM("SLIM TX2 MUX Mux", sb_tx2_mux_enum);
static const struct snd_kcontrol_new sb_tx3_mux =
SOC_DAPM_ENUM("SLIM TX3 MUX Mux", sb_tx3_mux_enum);
static const struct snd_kcontrol_new sb_tx4_mux =
SOC_DAPM_ENUM("SLIM TX4 MUX Mux", sb_tx4_mux_enum);
static const struct snd_kcontrol_new sb_tx5_mux =
SOC_DAPM_ENUM("SLIM TX5 MUX Mux", sb_tx5_mux_enum);
static const struct snd_kcontrol_new sb_tx6_mux =
SOC_DAPM_ENUM("SLIM TX6 MUX Mux", sb_tx6_mux_enum);
static const struct snd_kcontrol_new sb_tx7_mux =
SOC_DAPM_ENUM("SLIM TX7 MUX Mux", sb_tx7_mux_enum);
static const struct snd_kcontrol_new sb_tx8_mux =
SOC_DAPM_ENUM("SLIM TX8 MUX Mux", sb_tx8_mux_enum);
static const struct snd_kcontrol_new sb_tx9_mux =
SOC_DAPM_ENUM("SLIM TX9 MUX Mux", sb_tx9_mux_enum);
static const struct snd_kcontrol_new sb_tx10_mux =
SOC_DAPM_ENUM("SLIM TX10 MUX Mux", sb_tx10_mux_enum);
static int wcd9310_put_dec_enum(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol);
struct snd_soc_dapm_widget *w = wlist->widgets[0];
struct snd_soc_codec *codec = w->codec;
struct soc_enum *e = (struct soc_enum *)kcontrol->private_value;
unsigned int dec_mux, decimator;
char *dec_name = NULL;
char *widget_name = NULL;
char *temp;
u16 tx_mux_ctl_reg;
u8 adc_dmic_sel = 0x0;
int ret = 0;
if (ucontrol->value.enumerated.item[0] > e->max - 1)
return -EINVAL;
dec_mux = ucontrol->value.enumerated.item[0];
widget_name = kstrndup(w->name, 15, GFP_KERNEL);
if (!widget_name)
return -ENOMEM;
temp = widget_name;
dec_name = strsep(&widget_name, " ");
widget_name = temp;
if (!dec_name) {
pr_err("%s: Invalid decimator = %s\n", __func__, w->name);
ret = -EINVAL;
goto out;
}
ret = kstrtouint(strpbrk(dec_name, "123456789"), 10, &decimator);
if (ret < 0) {
pr_err("%s: Invalid decimator = %s\n", __func__, dec_name);
ret = -EINVAL;
goto out;
}
dev_dbg(w->dapm->dev, "%s(): widget = %s dec_name = %s decimator = %u"
" dec_mux = %u\n", __func__, w->name, dec_name, decimator,
dec_mux);
switch (decimator) {
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
if (dec_mux == 1)
adc_dmic_sel = 0x1;
else
adc_dmic_sel = 0x0;
break;
case 7:
case 8:
case 9:
case 10:
if ((dec_mux == 1) || (dec_mux == 2))
adc_dmic_sel = 0x1;
else
adc_dmic_sel = 0x0;
break;
default:
pr_err("%s: Invalid Decimator = %u\n", __func__, decimator);
ret = -EINVAL;
goto out;
}
tx_mux_ctl_reg = TABLA_A_CDC_TX1_MUX_CTL + 8 * (decimator - 1);
snd_soc_update_bits(codec, tx_mux_ctl_reg, 0x1, adc_dmic_sel);
ret = snd_soc_dapm_put_enum_double(kcontrol, ucontrol);
out:
kfree(widget_name);
return ret;
}
#define WCD9310_DEC_ENUM(xname, xenum) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
.info = snd_soc_info_enum_double, \
.get = snd_soc_dapm_get_enum_double, \
.put = wcd9310_put_dec_enum, \
.private_value = (unsigned long)&xenum }
static const struct snd_kcontrol_new dec1_mux =
WCD9310_DEC_ENUM("DEC1 MUX Mux", dec1_mux_enum);
static const struct snd_kcontrol_new dec2_mux =
WCD9310_DEC_ENUM("DEC2 MUX Mux", dec2_mux_enum);
static const struct snd_kcontrol_new dec3_mux =
WCD9310_DEC_ENUM("DEC3 MUX Mux", dec3_mux_enum);
static const struct snd_kcontrol_new dec4_mux =
WCD9310_DEC_ENUM("DEC4 MUX Mux", dec4_mux_enum);
static const struct snd_kcontrol_new dec5_mux =
WCD9310_DEC_ENUM("DEC5 MUX Mux", dec5_mux_enum);
static const struct snd_kcontrol_new dec6_mux =
WCD9310_DEC_ENUM("DEC6 MUX Mux", dec6_mux_enum);
static const struct snd_kcontrol_new dec7_mux =
WCD9310_DEC_ENUM("DEC7 MUX Mux", dec7_mux_enum);
static const struct snd_kcontrol_new dec8_mux =
WCD9310_DEC_ENUM("DEC8 MUX Mux", dec8_mux_enum);
static const struct snd_kcontrol_new dec9_mux =
WCD9310_DEC_ENUM("DEC9 MUX Mux", dec9_mux_enum);
static const struct snd_kcontrol_new dec10_mux =
WCD9310_DEC_ENUM("DEC10 MUX Mux", dec10_mux_enum);
static const struct snd_kcontrol_new iir1_inp1_mux =
SOC_DAPM_ENUM("IIR1 INP1 Mux", iir1_inp1_mux_enum);
static const struct snd_kcontrol_new iir2_inp1_mux =
SOC_DAPM_ENUM("IIR2 INP1 Mux", iir2_inp1_mux_enum);
static const struct snd_kcontrol_new anc1_mux =
SOC_DAPM_ENUM("ANC1 MUX Mux", anc1_mux_enum);
static const struct snd_kcontrol_new anc2_mux =
SOC_DAPM_ENUM("ANC2 MUX Mux", anc2_mux_enum);
static const struct snd_kcontrol_new anc1_fb_mux =
SOC_DAPM_ENUM("ANC1 FB MUX Mux", anc1_fb_mux_enum);
static const struct snd_kcontrol_new dac1_switch[] = {
SOC_DAPM_SINGLE("Switch", TABLA_A_RX_EAR_EN, 5, 1, 0)
};
static const struct snd_kcontrol_new hphl_switch[] = {
SOC_DAPM_SINGLE("Switch", TABLA_A_RX_HPH_L_DAC_CTL, 6, 1, 0)
};
static const struct snd_kcontrol_new hphl_pa_mix[] = {
SOC_DAPM_SINGLE("AUX_PGA_L Switch", TABLA_A_AUX_L_PA_CONN,
7, 1, 0),
SOC_DAPM_SINGLE("AUX_PGA_R Switch", TABLA_A_AUX_R_PA_CONN,
7, 1, 0),
SOC_DAPM_SINGLE("AUX_PGA_L_INV Switch",
TABLA_A_AUX_L_PA_CONN_INV, 7, 1, 0),
SOC_DAPM_SINGLE("AUX_PGA_R_INV Switch",
TABLA_A_AUX_R_PA_CONN_INV, 7, 1, 0),
};
static const struct snd_kcontrol_new hphr_pa_mix[] = {
SOC_DAPM_SINGLE("AUX_PGA_L Switch", TABLA_A_AUX_L_PA_CONN,
6, 1, 0),
SOC_DAPM_SINGLE("AUX_PGA_R Switch", TABLA_A_AUX_R_PA_CONN,
6, 1, 0),
SOC_DAPM_SINGLE("AUX_PGA_L_INV Switch",
TABLA_A_AUX_L_PA_CONN_INV, 6, 1, 0),
SOC_DAPM_SINGLE("AUX_PGA_R_INV Switch",
TABLA_A_AUX_R_PA_CONN_INV, 6, 1, 0),
};
static const struct snd_kcontrol_new lineout1_pa_mix[] = {
SOC_DAPM_SINGLE("AUX_PGA_L Switch", TABLA_A_AUX_L_PA_CONN,
5, 1, 0),
SOC_DAPM_SINGLE("AUX_PGA_R Switch", TABLA_A_AUX_R_PA_CONN,
5, 1, 0),
SOC_DAPM_SINGLE("AUX_PGA_L_INV Switch",
TABLA_A_AUX_L_PA_CONN_INV, 5, 1, 0),
SOC_DAPM_SINGLE("AUX_PGA_R_INV Switch",
TABLA_A_AUX_R_PA_CONN_INV, 5, 1, 0),
};
static const struct snd_kcontrol_new lineout2_pa_mix[] = {
SOC_DAPM_SINGLE("AUX_PGA_L Switch", TABLA_A_AUX_L_PA_CONN,
4, 1, 0),
SOC_DAPM_SINGLE("AUX_PGA_R Switch", TABLA_A_AUX_R_PA_CONN,
4, 1, 0),
SOC_DAPM_SINGLE("AUX_PGA_L_INV Switch",
TABLA_A_AUX_L_PA_CONN_INV, 4, 1, 0),
SOC_DAPM_SINGLE("AUX_PGA_R_INV Switch",
TABLA_A_AUX_R_PA_CONN_INV, 4, 1, 0),
};
static const struct snd_kcontrol_new lineout3_pa_mix[] = {
SOC_DAPM_SINGLE("AUX_PGA_L Switch", TABLA_A_AUX_L_PA_CONN,
3, 1, 0),
SOC_DAPM_SINGLE("AUX_PGA_R Switch", TABLA_A_AUX_R_PA_CONN,
3, 1, 0),
SOC_DAPM_SINGLE("AUX_PGA_L_INV Switch",
TABLA_A_AUX_L_PA_CONN_INV, 3, 1, 0),
SOC_DAPM_SINGLE("AUX_PGA_R_INV Switch",
TABLA_A_AUX_R_PA_CONN_INV, 3, 1, 0),
};
static const struct snd_kcontrol_new lineout4_pa_mix[] = {
SOC_DAPM_SINGLE("AUX_PGA_L Switch", TABLA_A_AUX_L_PA_CONN,
2, 1, 0),
SOC_DAPM_SINGLE("AUX_PGA_R Switch", TABLA_A_AUX_R_PA_CONN,
2, 1, 0),
SOC_DAPM_SINGLE("AUX_PGA_L_INV Switch",
TABLA_A_AUX_L_PA_CONN_INV, 2, 1, 0),
SOC_DAPM_SINGLE("AUX_PGA_R_INV Switch",
TABLA_A_AUX_R_PA_CONN_INV, 2, 1, 0),
};
static const struct snd_kcontrol_new lineout5_pa_mix[] = {
SOC_DAPM_SINGLE("AUX_PGA_L Switch", TABLA_A_AUX_L_PA_CONN,
1, 1, 0),
SOC_DAPM_SINGLE("AUX_PGA_R Switch", TABLA_A_AUX_R_PA_CONN,
1, 1, 0),
SOC_DAPM_SINGLE("AUX_PGA_L_INV Switch",
TABLA_A_AUX_L_PA_CONN_INV, 1, 1, 0),
SOC_DAPM_SINGLE("AUX_PGA_R_INV Switch",
TABLA_A_AUX_R_PA_CONN_INV, 1, 1, 0),
};
static const struct snd_kcontrol_new ear_pa_mix[] = {
SOC_DAPM_SINGLE("AUX_PGA_L Switch", TABLA_A_AUX_L_PA_CONN,
0, 1, 0),
SOC_DAPM_SINGLE("AUX_PGA_R Switch", TABLA_A_AUX_R_PA_CONN,
0, 1, 0),
SOC_DAPM_SINGLE("AUX_PGA_L_INV Switch",
TABLA_A_AUX_L_PA_CONN_INV, 0, 1, 0),
SOC_DAPM_SINGLE("AUX_PGA_R_INV Switch",
TABLA_A_AUX_R_PA_CONN_INV, 0, 1, 0),
};
static const struct snd_kcontrol_new lineout3_ground_switch =
SOC_DAPM_SINGLE("Switch", TABLA_A_RX_LINE_3_DAC_CTL, 6, 1, 0);
static const struct snd_kcontrol_new lineout4_ground_switch =
SOC_DAPM_SINGLE("Switch", TABLA_A_RX_LINE_4_DAC_CTL, 6, 1, 0);
/* virtual port entries */
static int slim_tx_mixer_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol);
struct snd_soc_dapm_widget *widget = wlist->widgets[0];
ucontrol->value.integer.value[0] = widget->value;
return 0;
}
static int slim_tx_mixer_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol);
struct snd_soc_dapm_widget *widget = wlist->widgets[0];
struct snd_soc_codec *codec = widget->codec;
struct tabla_priv *tabla_p = snd_soc_codec_get_drvdata(codec);
struct wcd9xxx *core = dev_get_drvdata(codec->dev->parent);
struct soc_multi_mixer_control *mixer =
((struct soc_multi_mixer_control *)kcontrol->private_value);
u32 dai_id = widget->shift;
u32 port_id = mixer->shift;
u32 enable = ucontrol->value.integer.value[0];
u32 vtable = vport_check_table[dai_id];
pr_debug("%s: wname %s cname %s value %u shift %d item %ld\n", __func__,
widget->name, ucontrol->id.name, widget->value, widget->shift,
ucontrol->value.integer.value[0]);
mutex_lock(&codec->mutex);
if (tabla_p->intf_type != WCD9XXX_INTERFACE_TYPE_SLIMBUS) {
if (dai_id != AIF1_CAP) {
dev_err(codec->dev, "%s: invalid AIF for I2C mode\n",
__func__);
mutex_unlock(&codec->mutex);
return -EINVAL;
}
}
switch (dai_id) {
case AIF1_CAP:
case AIF2_CAP:
case AIF3_CAP:
/* only add to the list if value not set
*/
if (enable && !(widget->value & 1 << port_id)) {
if (tabla_p->intf_type ==
WCD9XXX_INTERFACE_TYPE_SLIMBUS)
vtable = vport_check_table[dai_id];
if (tabla_p->intf_type == WCD9XXX_INTERFACE_TYPE_I2C)
vtable = vport_i2s_check_table[dai_id];
if (wcd9xxx_tx_vport_validation(
vtable,
port_id,
tabla_p->dai, NUM_CODEC_DAIS)) {
dev_dbg(codec->dev, "%s: TX%u is used by other virtual port\n",
__func__, port_id + 1);
mutex_unlock(&codec->mutex);
return 0;
}
widget->value |= 1 << port_id;
list_add_tail(&core->tx_chs[port_id].list,
&tabla_p->dai[dai_id].wcd9xxx_ch_list
);
} else if (!enable && (widget->value & 1 << port_id)) {
widget->value &= ~(1 << port_id);
list_del_init(&core->tx_chs[port_id].list);
} else {
if (enable)
dev_dbg(codec->dev, "%s: TX%u port is used by this virtual port\n",
__func__, port_id + 1);
else
dev_dbg(codec->dev, "%s: TX%u port is not used by this virtual port\n",
__func__, port_id + 1);
/* avoid update power function */
mutex_unlock(&codec->mutex);
return 0;
}
break;
default:
pr_err("Unknown AIF %d\n", dai_id);
mutex_unlock(&codec->mutex);
return -EINVAL;
}
pr_debug("%s: name %s sname %s updated value %u shift %d\n", __func__,
widget->name, widget->sname, widget->value, widget->shift);
snd_soc_dapm_mixer_update_power(widget, kcontrol, enable);
mutex_unlock(&codec->mutex);
return 0;
}
static int slim_rx_mux_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol);
struct snd_soc_dapm_widget *widget = wlist->widgets[0];
ucontrol->value.enumerated.item[0] = widget->value;
return 0;
}
static const char *const slim_rx_mux_text[] = {
"ZERO", "AIF1_PB", "AIF2_PB", "AIF3_PB"
};
static int slim_rx_mux_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol);
struct snd_soc_dapm_widget *widget = wlist->widgets[0];
struct snd_soc_codec *codec = widget->codec;
struct tabla_priv *tabla_p = snd_soc_codec_get_drvdata(codec);
struct wcd9xxx *core = dev_get_drvdata(codec->dev->parent);
struct soc_enum *e = (struct soc_enum *)kcontrol->private_value;
u32 port_id = widget->shift;
pr_debug("%s: wname %s cname %s value %u shift %d item %u\n", __func__,
widget->name, ucontrol->id.name, widget->value, widget->shift,
ucontrol->value.enumerated.item[0]);
widget->value = ucontrol->value.enumerated.item[0];
mutex_lock(&codec->mutex);
if (tabla_p->intf_type != WCD9XXX_INTERFACE_TYPE_SLIMBUS) {
if (widget->value > 1) {
dev_err(codec->dev, "%s: invalid AIF for I2C mode\n",
__func__);
goto err;
}
}
/* value need to match the Virtual port and AIF number
*/
switch (widget->value) {
case 0:
list_del_init(&core->rx_chs[port_id].list);
break;
case 1:
if (wcd9xxx_rx_vport_validation(port_id +
TABLA_RX_PORT_START_NUMBER,
&tabla_p->dai[AIF1_PB].wcd9xxx_ch_list)) {
dev_dbg(codec->dev, "%s: RX%u is used by current requesting AIF_PB itself\n",
__func__, port_id + 1);
goto rtn;
}
list_add_tail(&core->rx_chs[port_id].list,
&tabla_p->dai[AIF1_PB].wcd9xxx_ch_list);
break;
case 2:
if (wcd9xxx_rx_vport_validation(port_id +
TABLA_RX_PORT_START_NUMBER,
&tabla_p->dai[AIF1_PB].wcd9xxx_ch_list)) {
dev_dbg(codec->dev, "%s: RX%u is used by current requesting AIF_PB itself\n",
__func__, port_id + 1);
goto rtn;
}
list_add_tail(&core->rx_chs[port_id].list,
&tabla_p->dai[AIF2_PB].wcd9xxx_ch_list);
break;
case 3:
if (wcd9xxx_rx_vport_validation(port_id +
TABLA_RX_PORT_START_NUMBER,
&tabla_p->dai[AIF1_PB].wcd9xxx_ch_list)) {
dev_dbg(codec->dev, "%s: RX%u is used by current requesting AIF_PB itself\n",
__func__, port_id + 1);
goto rtn;
}
list_add_tail(&core->rx_chs[port_id].list,
&tabla_p->dai[AIF3_PB].wcd9xxx_ch_list);
break;
default:
pr_err("Unknown AIF %d\n", widget->value);
goto err;
}
rtn:
snd_soc_dapm_mux_update_power(widget, kcontrol, widget->value, e);
mutex_unlock(&codec->mutex);
return 0;
err:
mutex_unlock(&codec->mutex);
return -EINVAL;
}
static const struct soc_enum slim_rx_mux_enum =
SOC_ENUM_SINGLE_EXT(ARRAY_SIZE(slim_rx_mux_text), slim_rx_mux_text);
static const struct snd_kcontrol_new slim_rx_mux[TABLA_RX_MAX] = {
SOC_DAPM_ENUM_EXT("SLIM RX1 Mux", slim_rx_mux_enum,
slim_rx_mux_get, slim_rx_mux_put),
SOC_DAPM_ENUM_EXT("SLIM RX2 Mux", slim_rx_mux_enum,
slim_rx_mux_get, slim_rx_mux_put),
SOC_DAPM_ENUM_EXT("SLIM RX3 Mux", slim_rx_mux_enum,
slim_rx_mux_get, slim_rx_mux_put),
SOC_DAPM_ENUM_EXT("SLIM RX4 Mux", slim_rx_mux_enum,
slim_rx_mux_get, slim_rx_mux_put),
SOC_DAPM_ENUM_EXT("SLIM RX5 Mux", slim_rx_mux_enum,
slim_rx_mux_get, slim_rx_mux_put),
SOC_DAPM_ENUM_EXT("SLIM RX6 Mux", slim_rx_mux_enum,
slim_rx_mux_get, slim_rx_mux_put),
SOC_DAPM_ENUM_EXT("SLIM RX7 Mux", slim_rx_mux_enum,
slim_rx_mux_get, slim_rx_mux_put),
};
static const struct snd_kcontrol_new aif_cap_mixer[] = {
SOC_SINGLE_EXT("SLIM TX1", SND_SOC_NOPM, TABLA_TX1, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX2", SND_SOC_NOPM, TABLA_TX2, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX3", SND_SOC_NOPM, TABLA_TX3, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX4", SND_SOC_NOPM, TABLA_TX4, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX5", SND_SOC_NOPM, TABLA_TX5, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX6", SND_SOC_NOPM, TABLA_TX6, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX7", SND_SOC_NOPM, TABLA_TX7, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX8", SND_SOC_NOPM, TABLA_TX8, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX9", SND_SOC_NOPM, TABLA_TX9, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX10", SND_SOC_NOPM, TABLA_TX10, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
};
static void tabla_codec_enable_adc_block(struct snd_soc_codec *codec,
int enable)
{
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
pr_debug("%s %d\n", __func__, enable);
if (enable) {
tabla->adc_count++;
snd_soc_update_bits(codec, TABLA_A_CDC_CLK_OTHR_CTL, 0x2, 0x2);
} else {
tabla->adc_count--;
if (!tabla->adc_count)
snd_soc_update_bits(codec, TABLA_A_CDC_CLK_OTHR_CTL,
0x2, 0x0);
}
}
static int tabla_codec_enable_adc(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
u16 adc_reg;
u8 init_bit_shift;
pr_debug("%s %d\n", __func__, event);
if (w->reg == TABLA_A_TX_1_2_EN)
adc_reg = TABLA_A_TX_1_2_TEST_CTL;
else if (w->reg == TABLA_A_TX_3_4_EN)
adc_reg = TABLA_A_TX_3_4_TEST_CTL;
else if (w->reg == TABLA_A_TX_5_6_EN)
adc_reg = TABLA_A_TX_5_6_TEST_CTL;
else {
pr_err("%s: Error, invalid adc register\n", __func__);
return -EINVAL;
}
if (w->shift == 3)
init_bit_shift = 6;
else if (w->shift == 7)
init_bit_shift = 7;
else {
pr_err("%s: Error, invalid init bit postion adc register\n",
__func__);
return -EINVAL;
}
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
tabla_codec_enable_adc_block(codec, 1);
snd_soc_update_bits(codec, adc_reg, 1 << init_bit_shift,
1 << init_bit_shift);
break;
case SND_SOC_DAPM_POST_PMU:
snd_soc_update_bits(codec, adc_reg, 1 << init_bit_shift, 0x00);
break;
case SND_SOC_DAPM_POST_PMD:
tabla_codec_enable_adc_block(codec, 0);
break;
}
return 0;
}
static void tabla_codec_enable_audio_mode_bandgap(struct snd_soc_codec *codec)
{
snd_soc_update_bits(codec, TABLA_A_BIAS_CENTRAL_BG_CTL, 0x80,
0x80);
snd_soc_update_bits(codec, TABLA_A_BIAS_CENTRAL_BG_CTL, 0x04,
0x04);
snd_soc_update_bits(codec, TABLA_A_BIAS_CENTRAL_BG_CTL, 0x01,
0x01);
usleep_range(1000, 1000);
snd_soc_update_bits(codec, TABLA_A_BIAS_CENTRAL_BG_CTL, 0x80,
0x00);
}
static void tabla_codec_enable_bandgap(struct snd_soc_codec *codec,
enum tabla_bandgap_type choice)
{
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
/* TODO lock resources accessed by audio streams and threaded
* interrupt handlers
*/
pr_debug("%s, choice is %d, current is %d\n", __func__, choice,
tabla->bandgap_type);
if (tabla->bandgap_type == choice)
return;
if ((tabla->bandgap_type == TABLA_BANDGAP_OFF) &&
(choice == TABLA_BANDGAP_AUDIO_MODE)) {
tabla_codec_enable_audio_mode_bandgap(codec);
} else if (choice == TABLA_BANDGAP_MBHC_MODE) {
/* bandgap mode becomes fast,
* mclk should be off or clk buff source souldn't be VBG
* Let's turn off mclk always */
WARN_ON(snd_soc_read(codec, TABLA_A_CLK_BUFF_EN2) & (1 << 2));
snd_soc_update_bits(codec, TABLA_A_BIAS_CENTRAL_BG_CTL, 0x2,
0x2);
snd_soc_update_bits(codec, TABLA_A_BIAS_CENTRAL_BG_CTL, 0x80,
0x80);
snd_soc_update_bits(codec, TABLA_A_BIAS_CENTRAL_BG_CTL, 0x4,
0x4);
snd_soc_update_bits(codec, TABLA_A_BIAS_CENTRAL_BG_CTL, 0x01,
0x01);
usleep_range(1000, 1000);
snd_soc_update_bits(codec, TABLA_A_BIAS_CENTRAL_BG_CTL, 0x80,
0x00);
} else if ((tabla->bandgap_type == TABLA_BANDGAP_MBHC_MODE) &&
(choice == TABLA_BANDGAP_AUDIO_MODE)) {
snd_soc_write(codec, TABLA_A_BIAS_CENTRAL_BG_CTL, 0x50);
usleep_range(100, 100);
tabla_codec_enable_audio_mode_bandgap(codec);
} else if (choice == TABLA_BANDGAP_OFF) {
snd_soc_write(codec, TABLA_A_BIAS_CENTRAL_BG_CTL, 0x50);
} else {
pr_err("%s: Error, Invalid bandgap settings\n", __func__);
}
tabla->bandgap_type = choice;
}
static void tabla_codec_disable_clock_block(struct snd_soc_codec *codec)
{
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
pr_debug("%s\n", __func__);
snd_soc_update_bits(codec, TABLA_A_CLK_BUFF_EN2, 0x04, 0x00);
usleep_range(50, 50);
snd_soc_update_bits(codec, TABLA_A_CLK_BUFF_EN2, 0x02, 0x02);
snd_soc_update_bits(codec, TABLA_A_CLK_BUFF_EN1, 0x05, 0x00);
usleep_range(50, 50);
tabla->clock_active = false;
}
static int tabla_codec_mclk_index(const struct tabla_priv *tabla)
{
if (tabla->mbhc_cfg.mclk_rate == TABLA_MCLK_RATE_12288KHZ)
return 0;
else if (tabla->mbhc_cfg.mclk_rate == TABLA_MCLK_RATE_9600KHZ)
return 1;
else {
BUG_ON(1);
return -EINVAL;
}
}
static void tabla_enable_rx_bias(struct snd_soc_codec *codec, u32 enable)
{
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
if (enable) {
tabla->rx_bias_count++;
if (tabla->rx_bias_count == 1)
snd_soc_update_bits(codec, TABLA_A_RX_COM_BIAS,
0x80, 0x80);
} else {
tabla->rx_bias_count--;
if (!tabla->rx_bias_count)
snd_soc_update_bits(codec, TABLA_A_RX_COM_BIAS,
0x80, 0x00);
}
}
static int tabla_codec_enable_config_mode(struct snd_soc_codec *codec,
int enable)
{
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
pr_debug("%s: enable = %d\n", __func__, enable);
if (enable) {
snd_soc_update_bits(codec, TABLA_A_CONFIG_MODE_FREQ, 0x10, 0);
/* bandgap mode to fast */
snd_soc_write(codec, TABLA_A_BIAS_CONFIG_MODE_BG_CTL, 0x17);
usleep_range(5, 5);
snd_soc_update_bits(codec, TABLA_A_CONFIG_MODE_FREQ, 0x80,
0x80);
snd_soc_update_bits(codec, TABLA_A_CONFIG_MODE_TEST, 0x80,
0x80);
usleep_range(10, 10);
snd_soc_update_bits(codec, TABLA_A_CONFIG_MODE_TEST, 0x80, 0);
usleep_range(10000, 10000);
snd_soc_update_bits(codec, TABLA_A_CLK_BUFF_EN1, 0x08, 0x08);
} else {
snd_soc_update_bits(codec, TABLA_A_BIAS_CONFIG_MODE_BG_CTL, 0x1,
0);
snd_soc_update_bits(codec, TABLA_A_CONFIG_MODE_FREQ, 0x80, 0);
/* clk source to ext clk and clk buff ref to VBG */
snd_soc_update_bits(codec, TABLA_A_CLK_BUFF_EN1, 0x0C, 0x04);
}
tabla->config_mode_active = enable ? true : false;
return 0;
}
static int tabla_codec_enable_clock_block(struct snd_soc_codec *codec,
int config_mode)
{
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
pr_debug("%s: config_mode = %d\n", __func__, config_mode);
/* transit to RCO requires mclk off */
WARN_ON(snd_soc_read(codec, TABLA_A_CLK_BUFF_EN2) & (1 << 2));
if (config_mode) {
/* enable RCO and switch to it */
tabla_codec_enable_config_mode(codec, 1);
snd_soc_write(codec, TABLA_A_CLK_BUFF_EN2, 0x02);
usleep_range(1000, 1000);
} else {
/* switch to MCLK */
snd_soc_update_bits(codec, TABLA_A_CLK_BUFF_EN1, 0x08, 0x00);
if (tabla->mbhc_polling_active) {
snd_soc_write(codec, TABLA_A_CLK_BUFF_EN2, 0x02);
tabla_codec_enable_config_mode(codec, 0);
}
}
snd_soc_update_bits(codec, TABLA_A_CLK_BUFF_EN1, 0x01, 0x01);
snd_soc_update_bits(codec, TABLA_A_CLK_BUFF_EN2, 0x02, 0x00);
/* on MCLK */
snd_soc_update_bits(codec, TABLA_A_CLK_BUFF_EN2, 0x04, 0x04);
snd_soc_update_bits(codec, TABLA_A_CDC_CLK_MCLK_CTL, 0x01, 0x01);
usleep_range(50, 50);
tabla->clock_active = true;
return 0;
}
static int tabla_codec_enable_aux_pga(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
pr_debug("%s: %d\n", __func__, event);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
tabla_codec_enable_bandgap(codec,
TABLA_BANDGAP_AUDIO_MODE);
tabla_enable_rx_bias(codec, 1);
snd_soc_update_bits(codec, TABLA_A_AUX_COM_CTL,
0x08, 0x08);
/* Enable Zero Cross detect for AUX PGA channel
* and set the initial AUX PGA gain to NEG_0P0_DB
* to avoid glitches.
*/
if (w->reg == TABLA_A_AUX_L_EN) {
snd_soc_update_bits(codec, TABLA_A_AUX_L_EN,
0x20, 0x20);
tabla->aux_l_gain = snd_soc_read(codec,
TABLA_A_AUX_L_GAIN);
snd_soc_write(codec, TABLA_A_AUX_L_GAIN, 0x1F);
} else {
snd_soc_update_bits(codec, TABLA_A_AUX_R_EN,
0x20, 0x20);
tabla->aux_r_gain = snd_soc_read(codec,
TABLA_A_AUX_R_GAIN);
snd_soc_write(codec, TABLA_A_AUX_R_GAIN, 0x1F);
}
if (tabla->aux_pga_cnt++ == 1
&& !tabla->mclk_enabled) {
tabla_codec_enable_clock_block(codec, 1);
pr_debug("AUX PGA enabled RC osc\n");
}
break;
case SND_SOC_DAPM_POST_PMU:
if (w->reg == TABLA_A_AUX_L_EN)
snd_soc_write(codec, TABLA_A_AUX_L_GAIN,
tabla->aux_l_gain);
else
snd_soc_write(codec, TABLA_A_AUX_R_GAIN,
tabla->aux_r_gain);
break;
case SND_SOC_DAPM_PRE_PMD:
/* Mute AUX PGA channel in use before disabling AUX PGA */
if (w->reg == TABLA_A_AUX_L_EN) {
tabla->aux_l_gain = snd_soc_read(codec,
TABLA_A_AUX_L_GAIN);
snd_soc_write(codec, TABLA_A_AUX_L_GAIN, 0x1F);
} else {
tabla->aux_r_gain = snd_soc_read(codec,
TABLA_A_AUX_R_GAIN);
snd_soc_write(codec, TABLA_A_AUX_R_GAIN, 0x1F);
}
break;
case SND_SOC_DAPM_POST_PMD:
tabla_enable_rx_bias(codec, 0);
snd_soc_update_bits(codec, TABLA_A_AUX_COM_CTL,
0x08, 0x00);
if (w->reg == TABLA_A_AUX_L_EN) {
snd_soc_write(codec, TABLA_A_AUX_L_GAIN,
tabla->aux_l_gain);
snd_soc_update_bits(codec, TABLA_A_AUX_L_EN,
0x20, 0x00);
} else {
snd_soc_write(codec, TABLA_A_AUX_R_GAIN,
tabla->aux_r_gain);
snd_soc_update_bits(codec, TABLA_A_AUX_R_EN,
0x20, 0x00);
}
if (tabla->aux_pga_cnt-- == 0) {
if (tabla->mbhc_polling_active)
tabla_codec_enable_bandgap(codec,
TABLA_BANDGAP_MBHC_MODE);
else
tabla_codec_enable_bandgap(codec,
TABLA_BANDGAP_OFF);
if (!tabla->mclk_enabled &&
!tabla->mbhc_polling_active) {
tabla_codec_enable_clock_block(codec, 0);
}
}
break;
}
return 0;
}
static int tabla_codec_enable_lineout(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
u16 lineout_gain_reg;
pr_debug("%s %d %s\n", __func__, event, w->name);
switch (w->shift) {
case 0:
lineout_gain_reg = TABLA_A_RX_LINE_1_GAIN;
break;
case 1:
lineout_gain_reg = TABLA_A_RX_LINE_2_GAIN;
break;
case 2:
lineout_gain_reg = TABLA_A_RX_LINE_3_GAIN;
break;
case 3:
lineout_gain_reg = TABLA_A_RX_LINE_4_GAIN;
break;
case 4:
lineout_gain_reg = TABLA_A_RX_LINE_5_GAIN;
break;
default:
pr_err("%s: Error, incorrect lineout register value\n",
__func__);
return -EINVAL;
}
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
snd_soc_update_bits(codec, lineout_gain_reg, 0x40, 0x40);
break;
case SND_SOC_DAPM_POST_PMU:
pr_debug("%s: sleeping 16 ms after %s PA turn on\n",
__func__, w->name);
usleep_range(16000, 16000);
break;
case SND_SOC_DAPM_POST_PMD:
snd_soc_update_bits(codec, lineout_gain_reg, 0x40, 0x00);
break;
}
return 0;
}
static int tabla_codec_enable_dmic(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
u8 dmic_clk_en;
s32 *dmic_clk_cnt;
unsigned int dmic;
int ret;
ret = kstrtouint(strpbrk(w->name, "123456"), 10, &dmic);
if (ret < 0) {
pr_err("%s: Invalid DMIC line on the codec\n", __func__);
return -EINVAL;
}
switch (dmic) {
case 1:
case 2:
dmic_clk_en = 0x01;
dmic_clk_cnt = &(tabla->dmic_1_2_clk_cnt);
pr_debug("%s() event %d DMIC%d dmic_1_2_clk_cnt %d\n",
__func__, event, dmic, *dmic_clk_cnt);
break;
case 3:
case 4:
dmic_clk_en = 0x04;
dmic_clk_cnt = &(tabla->dmic_3_4_clk_cnt);
pr_debug("%s() event %d DMIC%d dmic_3_4_clk_cnt %d\n",
__func__, event, dmic, *dmic_clk_cnt);
break;
case 5:
case 6:
dmic_clk_en = 0x10;
dmic_clk_cnt = &(tabla->dmic_5_6_clk_cnt);
pr_debug("%s() event %d DMIC%d dmic_5_6_clk_cnt %d\n",
__func__, event, dmic, *dmic_clk_cnt);
break;
default:
pr_err("%s: Invalid DMIC Selection\n", __func__);
return -EINVAL;
}
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
(*dmic_clk_cnt)++;
if (*dmic_clk_cnt == 1) {
snd_soc_update_bits(codec,
TABLA_A_CDC_DMIC_CLK0_MODE, 0x7, 0x0);
snd_soc_update_bits(codec,
TABLA_A_CDC_DMIC_CLK1_MODE, 0x7, 0x0);
snd_soc_update_bits(codec,
TABLA_A_CDC_DMIC_CLK2_MODE, 0x7, 0x0);
snd_soc_update_bits(codec, TABLA_A_CDC_CLK_DMIC_CTL,
dmic_clk_en, dmic_clk_en);
}
break;
case SND_SOC_DAPM_POST_PMD:
(*dmic_clk_cnt)--;
if (*dmic_clk_cnt == 0) {
snd_soc_update_bits(codec, TABLA_A_CDC_CLK_DMIC_CTL,
dmic_clk_en, 0);
snd_soc_update_bits(codec,
TABLA_A_CDC_DMIC_CLK0_MODE, 0x7, 0x4);
snd_soc_update_bits(codec,
TABLA_A_CDC_DMIC_CLK1_MODE, 0x7, 0x4);
snd_soc_update_bits(codec,
TABLA_A_CDC_DMIC_CLK2_MODE, 0x7, 0x4);
}
break;
}
return 0;
}
/* called under codec_resource_lock acquisition */
static void tabla_codec_start_hs_polling(struct snd_soc_codec *codec)
{
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
struct wcd9xxx *tabla_core = dev_get_drvdata(codec->dev->parent);
int mbhc_state = tabla->mbhc_state;
pr_debug("%s: enter\n", __func__);
if (!tabla->mbhc_polling_active) {
pr_debug("Polling is not active, do not start polling\n");
return;
}
snd_soc_write(codec, TABLA_A_MBHC_SCALING_MUX_1, 0x84);
if (tabla->no_mic_headset_override) {
pr_debug("%s setting button threshold to min", __func__);
/* set to min */
snd_soc_write(codec, TABLA_A_CDC_MBHC_VOLT_B4_CTL, 0x80);
snd_soc_write(codec, TABLA_A_CDC_MBHC_VOLT_B3_CTL, 0x00);
snd_soc_write(codec, TABLA_A_CDC_MBHC_VOLT_B6_CTL, 0x80);
snd_soc_write(codec, TABLA_A_CDC_MBHC_VOLT_B5_CTL, 0x00);
} else if (unlikely(mbhc_state == MBHC_STATE_POTENTIAL)) {
pr_debug("%s recovering MBHC state machine\n", __func__);
tabla->mbhc_state = MBHC_STATE_POTENTIAL_RECOVERY;
/* set to max button press threshold */
snd_soc_write(codec, TABLA_A_CDC_MBHC_VOLT_B2_CTL, 0x7F);
snd_soc_write(codec, TABLA_A_CDC_MBHC_VOLT_B1_CTL, 0xFF);
snd_soc_write(codec, TABLA_A_CDC_MBHC_VOLT_B4_CTL,
(TABLA_IS_1_X(tabla_core->version) ?
0x07 : 0x7F));
snd_soc_write(codec, TABLA_A_CDC_MBHC_VOLT_B3_CTL, 0xFF);
/* set to max */
snd_soc_write(codec, TABLA_A_CDC_MBHC_VOLT_B6_CTL, 0x7F);
snd_soc_write(codec, TABLA_A_CDC_MBHC_VOLT_B5_CTL, 0xFF);
}
snd_soc_write(codec, TABLA_A_CDC_MBHC_EN_CTL, 0x1);
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_CLK_CTL, 0x8, 0x0);
snd_soc_write(codec, TABLA_A_CDC_MBHC_EN_CTL, 0x1);
pr_debug("%s: leave\n", __func__);
}
/* called under codec_resource_lock acquisition */
static void tabla_codec_pause_hs_polling(struct snd_soc_codec *codec)
{
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
pr_debug("%s: enter\n", __func__);
if (!tabla->mbhc_polling_active) {
pr_debug("polling not active, nothing to pause\n");
return;
}
snd_soc_update_bits(codec, tabla->mbhc_bias_regs.ctl_reg, 0x01, 0x01);
msleep(20);
snd_soc_update_bits(codec, tabla->mbhc_bias_regs.ctl_reg, 0x01, 0x00);
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_CLK_CTL, 0x8, 0x8);
pr_debug("%s: leave\n", __func__);
}
static void tabla_codec_switch_cfilt_mode(struct snd_soc_codec *codec, int mode)
{
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
u8 reg_mode_val, cur_mode_val;
bool mbhc_was_polling = false;
if (mode)
reg_mode_val = TABLA_CFILT_FAST_MODE;
else
reg_mode_val = TABLA_CFILT_SLOW_MODE;
cur_mode_val = snd_soc_read(codec,
tabla->mbhc_bias_regs.cfilt_ctl) & 0x40;
if (cur_mode_val != reg_mode_val) {
TABLA_ACQUIRE_LOCK(tabla->codec_resource_lock);
if (tabla->mbhc_polling_active) {
tabla_codec_pause_hs_polling(codec);
mbhc_was_polling = true;
}
snd_soc_update_bits(codec,
tabla->mbhc_bias_regs.cfilt_ctl, 0x40, reg_mode_val);
if (mbhc_was_polling)
tabla_codec_start_hs_polling(codec);
TABLA_RELEASE_LOCK(tabla->codec_resource_lock);
pr_debug("%s: CFILT mode change (%x to %x)\n", __func__,
cur_mode_val, reg_mode_val);
} else {
pr_debug("%s: CFILT Value is already %x\n",
__func__, cur_mode_val);
}
}
static void tabla_codec_update_cfilt_usage(struct snd_soc_codec *codec,
u8 cfilt_sel, int inc)
{
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
u32 *cfilt_cnt_ptr = NULL;
u16 micb_cfilt_reg;
switch (cfilt_sel) {
case TABLA_CFILT1_SEL:
cfilt_cnt_ptr = &tabla->cfilt1_cnt;
micb_cfilt_reg = TABLA_A_MICB_CFILT_1_CTL;
break;
case TABLA_CFILT2_SEL:
cfilt_cnt_ptr = &tabla->cfilt2_cnt;
micb_cfilt_reg = TABLA_A_MICB_CFILT_2_CTL;
break;
case TABLA_CFILT3_SEL:
cfilt_cnt_ptr = &tabla->cfilt3_cnt;
micb_cfilt_reg = TABLA_A_MICB_CFILT_3_CTL;
break;
default:
return; /* should not happen */
}
if (inc) {
if (!(*cfilt_cnt_ptr)++) {
/* Switch CFILT to slow mode if MBHC CFILT being used */
if (cfilt_sel == tabla->mbhc_bias_regs.cfilt_sel)
tabla_codec_switch_cfilt_mode(codec, 0);
snd_soc_update_bits(codec, micb_cfilt_reg, 0x80, 0x80);
}
} else {
/* check if count not zero, decrement
* then check if zero, go ahead disable cfilter
*/
if ((*cfilt_cnt_ptr) && !--(*cfilt_cnt_ptr)) {
snd_soc_update_bits(codec, micb_cfilt_reg, 0x80, 0);
/* Switch CFILT to fast mode if MBHC CFILT being used */
if (cfilt_sel == tabla->mbhc_bias_regs.cfilt_sel)
tabla_codec_switch_cfilt_mode(codec, 1);
}
}
}
static int tabla_find_k_value(unsigned int ldoh_v, unsigned int cfilt_mv)
{
int rc = -EINVAL;
unsigned min_mv, max_mv;
switch (ldoh_v) {
case TABLA_LDOH_1P95_V:
min_mv = 160;
max_mv = 1800;
break;
case TABLA_LDOH_2P35_V:
min_mv = 200;
max_mv = 2200;
break;
case TABLA_LDOH_2P75_V:
min_mv = 240;
max_mv = 2600;
break;
case TABLA_LDOH_2P85_V:
min_mv = 250;
max_mv = 2700;
break;
default:
goto done;
}
if (cfilt_mv < min_mv || cfilt_mv > max_mv)
goto done;
for (rc = 4; rc <= 44; rc++) {
min_mv = max_mv * (rc) / 44;
if (min_mv >= cfilt_mv) {
rc -= 4;
break;
}
}
done:
return rc;
}
static bool tabla_is_hph_pa_on(struct snd_soc_codec *codec)
{
u8 hph_reg_val = 0;
hph_reg_val = snd_soc_read(codec, TABLA_A_RX_HPH_CNP_EN);
return (hph_reg_val & 0x30) ? true : false;
}
static bool tabla_is_hph_dac_on(struct snd_soc_codec *codec, int left)
{
u8 hph_reg_val = 0;
if (left)
hph_reg_val = snd_soc_read(codec,
TABLA_A_RX_HPH_L_DAC_CTL);
else
hph_reg_val = snd_soc_read(codec,
TABLA_A_RX_HPH_R_DAC_CTL);
return (hph_reg_val & 0xC0) ? true : false;
}
static void tabla_turn_onoff_override(struct snd_soc_codec *codec, bool on)
{
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_B1_CTL, 0x04, on << 2);
}
/* called under codec_resource_lock acquisition */
static void tabla_codec_drive_v_to_micbias(struct snd_soc_codec *codec,
int usec)
{
int cfilt_k_val;
bool set = true;
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
if (tabla->mbhc_data.micb_mv != VDDIO_MICBIAS_MV &&
tabla->mbhc_micbias_switched) {
pr_debug("%s: set mic V to micbias V\n", __func__);
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_CLK_CTL, 0x2, 0x2);
tabla_turn_onoff_override(codec, true);
while (1) {
cfilt_k_val = tabla_find_k_value(
tabla->pdata->micbias.ldoh_v,
set ? tabla->mbhc_data.micb_mv :
VDDIO_MICBIAS_MV);
snd_soc_update_bits(codec,
tabla->mbhc_bias_regs.cfilt_val,
0xFC, (cfilt_k_val << 2));
if (!set)
break;
usleep_range(usec, usec);
set = false;
}
tabla_turn_onoff_override(codec, false);
}
}
/* called under codec_resource_lock acquisition */
static void __tabla_codec_switch_micbias(struct snd_soc_codec *codec,
int vddio_switch, bool restartpolling,
bool checkpolling)
{
int cfilt_k_val;
bool override;
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
if (vddio_switch && !tabla->mbhc_micbias_switched &&
(!checkpolling || tabla->mbhc_polling_active)) {
if (restartpolling)
tabla_codec_pause_hs_polling(codec);
override = snd_soc_read(codec, TABLA_A_CDC_MBHC_B1_CTL) & 0x04;
if (!override)
tabla_turn_onoff_override(codec, true);
/* Adjust threshold if Mic Bias voltage changes */
if (tabla->mbhc_data.micb_mv != VDDIO_MICBIAS_MV) {
cfilt_k_val = tabla_find_k_value(
tabla->pdata->micbias.ldoh_v,
VDDIO_MICBIAS_MV);
snd_soc_update_bits(codec,
tabla->mbhc_bias_regs.cfilt_val,
0xFC, (cfilt_k_val << 2));
usleep_range(cfilt_adjust_ms * 1000,
cfilt_adjust_ms * 1000);
snd_soc_write(codec, TABLA_A_CDC_MBHC_VOLT_B1_CTL,
tabla->mbhc_data.adj_v_ins_hu & 0xFF);
snd_soc_write(codec, TABLA_A_CDC_MBHC_VOLT_B2_CTL,
(tabla->mbhc_data.adj_v_ins_hu >> 8) &
0xFF);
pr_debug("%s: Programmed MBHC thresholds to VDDIO\n",
__func__);
}
/* enable MIC BIAS Switch to VDDIO */
snd_soc_update_bits(codec, tabla->mbhc_bias_regs.mbhc_reg,
0x80, 0x80);
snd_soc_update_bits(codec, tabla->mbhc_bias_regs.mbhc_reg,
0x10, 0x00);
if (!override)
tabla_turn_onoff_override(codec, false);
if (restartpolling)
tabla_codec_start_hs_polling(codec);
tabla->mbhc_micbias_switched = true;
pr_debug("%s: VDDIO switch enabled\n", __func__);
} else if (!vddio_switch && tabla->mbhc_micbias_switched) {
if ((!checkpolling || tabla->mbhc_polling_active) &&
restartpolling)
tabla_codec_pause_hs_polling(codec);
/* Reprogram thresholds */
if (tabla->mbhc_data.micb_mv != VDDIO_MICBIAS_MV) {
cfilt_k_val = tabla_find_k_value(
tabla->pdata->micbias.ldoh_v,
tabla->mbhc_data.micb_mv);
snd_soc_update_bits(codec,
tabla->mbhc_bias_regs.cfilt_val,
0xFC, (cfilt_k_val << 2));
usleep_range(cfilt_adjust_ms * 1000,
cfilt_adjust_ms * 1000);
snd_soc_write(codec, TABLA_A_CDC_MBHC_VOLT_B1_CTL,
tabla->mbhc_data.v_ins_hu & 0xFF);
snd_soc_write(codec, TABLA_A_CDC_MBHC_VOLT_B2_CTL,
(tabla->mbhc_data.v_ins_hu >> 8) & 0xFF);
pr_debug("%s: Programmed MBHC thresholds to MICBIAS\n",
__func__);
}
/* Disable MIC BIAS Switch to VDDIO */
snd_soc_update_bits(codec, tabla->mbhc_bias_regs.mbhc_reg,
0x80, 0x00);
snd_soc_update_bits(codec, tabla->mbhc_bias_regs.mbhc_reg,
0x10, 0x00);
if ((!checkpolling || tabla->mbhc_polling_active) &&
restartpolling)
tabla_codec_start_hs_polling(codec);
tabla->mbhc_micbias_switched = false;
pr_debug("%s: VDDIO switch disabled\n", __func__);
}
}
static void tabla_codec_switch_micbias(struct snd_soc_codec *codec,
int vddio_switch)
{
return __tabla_codec_switch_micbias(codec, vddio_switch, true, true);
}
static int tabla_codec_enable_micbias(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
u16 micb_int_reg;
int micb_line;
u8 cfilt_sel_val = 0;
char *internal1_text = "Internal1";
char *internal2_text = "Internal2";
char *internal3_text = "Internal3";
const char *micbias1_text = "MIC BIAS1 ";
const char *micbias2_text = "MIC BIAS2 ";
const char *micbias3_text = "MIC BIAS3 ";
const char *micbias4_text = "MIC BIAS4 ";
u32 *micbias_enable_count;
u16 wreg;
pr_debug("%s %d\n", __func__, event);
if (strnstr(w->name, micbias1_text, strlen(micbias1_text))) {
wreg = TABLA_A_MICB_1_CTL;
micb_int_reg = TABLA_A_MICB_1_INT_RBIAS;
cfilt_sel_val = tabla->pdata->micbias.bias1_cfilt_sel;
micb_line = TABLA_MICBIAS1;
} else if (strnstr(w->name, micbias2_text, strlen(micbias2_text))) {
wreg = TABLA_A_MICB_2_CTL;
micb_int_reg = TABLA_A_MICB_2_INT_RBIAS;
cfilt_sel_val = tabla->pdata->micbias.bias2_cfilt_sel;
micb_line = TABLA_MICBIAS2;
} else if (strnstr(w->name, micbias3_text, strlen(micbias3_text))) {
wreg = TABLA_A_MICB_3_CTL;
micb_int_reg = TABLA_A_MICB_3_INT_RBIAS;
cfilt_sel_val = tabla->pdata->micbias.bias3_cfilt_sel;
micb_line = TABLA_MICBIAS3;
} else if (strnstr(w->name, micbias4_text, strlen(micbias4_text))) {
wreg = tabla->reg_addr.micb_4_ctl;
micb_int_reg = tabla->reg_addr.micb_4_int_rbias;
cfilt_sel_val = tabla->pdata->micbias.bias4_cfilt_sel;
micb_line = TABLA_MICBIAS4;
} else {
pr_err("%s: Error, invalid micbias register\n", __func__);
return -EINVAL;
}
micbias_enable_count = &tabla->micbias_enable_count[micb_line];
pr_debug("%s: counter %d\n", __func__, *micbias_enable_count);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
if (++*micbias_enable_count > 1) {
pr_debug("%s: do nothing, counter %d\n",
__func__, *micbias_enable_count);
break;
}
/* Decide whether to switch the micbias for MBHC */
if (wreg == tabla->mbhc_bias_regs.ctl_reg) {
TABLA_ACQUIRE_LOCK(tabla->codec_resource_lock);
tabla_codec_switch_micbias(codec, 0);
TABLA_RELEASE_LOCK(tabla->codec_resource_lock);
}
snd_soc_update_bits(codec, wreg, 0x0E, 0x0A);
tabla_codec_update_cfilt_usage(codec, cfilt_sel_val, 1);
if (strnstr(w->name, internal1_text, 30))
snd_soc_update_bits(codec, micb_int_reg, 0xE0, 0xE0);
else if (strnstr(w->name, internal2_text, 30))
snd_soc_update_bits(codec, micb_int_reg, 0x1C, 0x1C);
else if (strnstr(w->name, internal3_text, 30))
snd_soc_update_bits(codec, micb_int_reg, 0x3, 0x3);
snd_soc_update_bits(codec, wreg, 1 << 7, 1 << 7);
break;
case SND_SOC_DAPM_POST_PMU:
if (*micbias_enable_count > 1) {
pr_debug("%s: do nothing, counter %d\n",
__func__, *micbias_enable_count);
break;
}
usleep_range(20000, 20000);
if (tabla->mbhc_polling_active &&
tabla->mbhc_cfg.micbias == micb_line) {
TABLA_ACQUIRE_LOCK(tabla->codec_resource_lock);
tabla_codec_pause_hs_polling(codec);
tabla_codec_start_hs_polling(codec);
TABLA_RELEASE_LOCK(tabla->codec_resource_lock);
}
break;
case SND_SOC_DAPM_POST_PMD:
if (--*micbias_enable_count > 0) {
pr_debug("%s: do nothing, counter %d\n",
__func__, *micbias_enable_count);
break;
}
snd_soc_update_bits(codec, wreg, 1 << 7, 0);
if ((wreg == tabla->mbhc_bias_regs.ctl_reg) &&
tabla_is_hph_pa_on(codec)) {
TABLA_ACQUIRE_LOCK(tabla->codec_resource_lock);
tabla_codec_switch_micbias(codec, 1);
TABLA_RELEASE_LOCK(tabla->codec_resource_lock);
}
if (strnstr(w->name, internal1_text, 30))
snd_soc_update_bits(codec, micb_int_reg, 0x80, 0x00);
else if (strnstr(w->name, internal2_text, 30))
snd_soc_update_bits(codec, micb_int_reg, 0x10, 0x00);
else if (strnstr(w->name, internal3_text, 30))
snd_soc_update_bits(codec, micb_int_reg, 0x2, 0x0);
tabla_codec_update_cfilt_usage(codec, cfilt_sel_val, 0);
break;
}
return 0;
}
static void tx_hpf_corner_freq_callback(struct work_struct *work)
{
struct delayed_work *hpf_delayed_work;
struct hpf_work *hpf_work;
struct tabla_priv *tabla;
struct snd_soc_codec *codec;
u16 tx_mux_ctl_reg;
u8 hpf_cut_of_freq;
hpf_delayed_work = to_delayed_work(work);
hpf_work = container_of(hpf_delayed_work, struct hpf_work, dwork);
tabla = hpf_work->tabla;
codec = hpf_work->tabla->codec;
hpf_cut_of_freq = hpf_work->tx_hpf_cut_of_freq;
tx_mux_ctl_reg = TABLA_A_CDC_TX1_MUX_CTL +
(hpf_work->decimator - 1) * 8;
pr_debug("%s(): decimator %u hpf_cut_of_freq 0x%x\n", __func__,
hpf_work->decimator, (unsigned int)hpf_cut_of_freq);
snd_soc_update_bits(codec, tx_mux_ctl_reg, 0x30, hpf_cut_of_freq << 4);
}
#define TX_MUX_CTL_CUT_OFF_FREQ_MASK 0x30
#define CF_MIN_3DB_4HZ 0x0
#define CF_MIN_3DB_75HZ 0x1
#define CF_MIN_3DB_150HZ 0x2
static int tabla_codec_enable_ldo_h(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event);
static int tabla_codec_enable_micbias_power(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol,
int event)
{
struct snd_soc_codec *codec = w->codec;
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
pr_debug("%s %d\n", __func__, event);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
tabla->mbhc_cfg.mclk_cb_fn(codec, 1, true);
tabla_codec_enable_ldo_h(w, kcontrol, event);
tabla_codec_enable_micbias(w, kcontrol, event);
break;
case SND_SOC_DAPM_POST_PMU:
tabla->mbhc_cfg.mclk_cb_fn(codec, 0, true);
break;
case SND_SOC_DAPM_POST_PMD:
tabla_codec_enable_micbias(w, kcontrol, event);
tabla_codec_enable_ldo_h(w, kcontrol, event);
break;
}
return 0;
}
static int tabla_codec_enable_dec(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
unsigned int decimator;
char *dec_name = NULL;
char *widget_name = NULL;
char *temp;
int ret = 0;
u16 dec_reset_reg, tx_vol_ctl_reg, tx_mux_ctl_reg;
u8 dec_hpf_cut_of_freq;
int offset;
pr_debug("%s %d\n", __func__, event);
widget_name = kstrndup(w->name, 15, GFP_KERNEL);
if (!widget_name)
return -ENOMEM;
temp = widget_name;
dec_name = strsep(&widget_name, " ");
widget_name = temp;
if (!dec_name) {
pr_err("%s: Invalid decimator = %s\n", __func__, w->name);
ret = -EINVAL;
goto out;
}
ret = kstrtouint(strpbrk(dec_name, "123456789"), 10, &decimator);
if (ret < 0) {
pr_err("%s: Invalid decimator = %s\n", __func__, dec_name);
ret = -EINVAL;
goto out;
}
pr_debug("%s(): widget = %s dec_name = %s decimator = %u\n", __func__,
w->name, dec_name, decimator);
if (w->reg == TABLA_A_CDC_CLK_TX_CLK_EN_B1_CTL) {
dec_reset_reg = TABLA_A_CDC_CLK_TX_RESET_B1_CTL;
offset = 0;
} else if (w->reg == TABLA_A_CDC_CLK_TX_CLK_EN_B2_CTL) {
dec_reset_reg = TABLA_A_CDC_CLK_TX_RESET_B2_CTL;
offset = 8;
} else {
pr_err("%s: Error, incorrect dec\n", __func__);
return -EINVAL;
}
tx_vol_ctl_reg = TABLA_A_CDC_TX1_VOL_CTL_CFG + 8 * (decimator -1);
tx_mux_ctl_reg = TABLA_A_CDC_TX1_MUX_CTL + 8 * (decimator - 1);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
// Enableable TX digital mute */
snd_soc_update_bits(codec, tx_vol_ctl_reg, 0x01, 0x01);
snd_soc_update_bits(codec, dec_reset_reg, 1 << w->shift,
1 << w->shift);
snd_soc_update_bits(codec, dec_reset_reg, 1 << w->shift, 0x0);
dec_hpf_cut_of_freq = snd_soc_read(codec, tx_mux_ctl_reg);
dec_hpf_cut_of_freq = (dec_hpf_cut_of_freq & 0x30) >> 4;
tx_hpf_work[decimator - 1].tx_hpf_cut_of_freq =
dec_hpf_cut_of_freq;
if ((dec_hpf_cut_of_freq != CF_MIN_3DB_150HZ)) {
/* set cut of freq to CF_MIN_3DB_150HZ (0x1); */
snd_soc_update_bits(codec, tx_mux_ctl_reg, 0x30,
CF_MIN_3DB_150HZ << 4);
}
/* enable HPF */
snd_soc_update_bits(codec, tx_mux_ctl_reg , 0x08, 0x00);
break;
case SND_SOC_DAPM_POST_PMU:
/* Disable TX digital mute */
snd_soc_update_bits(codec, tx_vol_ctl_reg, 0x01, 0x00);
if (tx_hpf_work[decimator - 1].tx_hpf_cut_of_freq !=
CF_MIN_3DB_150HZ) {
schedule_delayed_work(&tx_hpf_work[decimator - 1].dwork,
msecs_to_jiffies(300));
}
/* apply the digital gain after the decimator is enabled*/
if ((w->shift + offset) < ARRAY_SIZE(tx_digital_gain_reg))
snd_soc_write(codec,
tx_digital_gain_reg[w->shift + offset],
snd_soc_read(codec,
tx_digital_gain_reg[w->shift + offset])
);
break;
case SND_SOC_DAPM_PRE_PMD:
snd_soc_update_bits(codec, tx_vol_ctl_reg, 0x01, 0x01);
cancel_delayed_work_sync(&tx_hpf_work[decimator - 1].dwork);
break;
case SND_SOC_DAPM_POST_PMD:
snd_soc_update_bits(codec, tx_mux_ctl_reg, 0x08, 0x08);
snd_soc_update_bits(codec, tx_mux_ctl_reg, 0x30,
(tx_hpf_work[decimator - 1].tx_hpf_cut_of_freq) << 4);
break;
}
out:
kfree(widget_name);
return ret;
}
static int tabla_codec_reset_interpolator(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
pr_debug("%s %d %s\n", __func__, event, w->name);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
snd_soc_update_bits(codec, TABLA_A_CDC_CLK_RX_RESET_CTL,
1 << w->shift, 1 << w->shift);
snd_soc_update_bits(codec, TABLA_A_CDC_CLK_RX_RESET_CTL,
1 << w->shift, 0x0);
break;
case SND_SOC_DAPM_POST_PMU:
/* apply the digital gain after the interpolator is enabled*/
if ((w->shift) < ARRAY_SIZE(rx_digital_gain_reg))
snd_soc_write(codec,
rx_digital_gain_reg[w->shift],
snd_soc_read(codec,
rx_digital_gain_reg[w->shift])
);
break;
}
return 0;
}
static void tabla_enable_ldo_h(struct snd_soc_codec *codec, u32 enable)
{
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
if (enable) {
if (++tabla->ldo_h_count == 1)
snd_soc_update_bits(codec, TABLA_A_LDO_H_MODE_1,
0x80, 0x80);
} else {
if (--tabla->ldo_h_count == 0)
snd_soc_update_bits(codec, TABLA_A_LDO_H_MODE_1,
0x80, 0x00);
}
}
static int tabla_codec_enable_ldo_h(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
pr_debug("%s %d\n", __func__, event);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
tabla_enable_ldo_h(codec, 1);
usleep_range(1000, 1000);
break;
case SND_SOC_DAPM_POST_PMD:
tabla_enable_ldo_h(codec, 0);
usleep_range(1000, 1000);
break;
}
return 0;
}
static int tabla_codec_enable_rx_bias(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
pr_debug("%s %d\n", __func__, event);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
tabla_enable_rx_bias(codec, 1);
break;
case SND_SOC_DAPM_POST_PMD:
tabla_enable_rx_bias(codec, 0);
break;
}
return 0;
}
static int tabla_hphr_dac_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
pr_debug("%s %s %d\n", __func__, w->name, event);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
snd_soc_update_bits(codec, w->reg, 0x40, 0x40);
break;
case SND_SOC_DAPM_POST_PMD:
snd_soc_update_bits(codec, w->reg, 0x40, 0x00);
break;
}
return 0;
}
static void tabla_snd_soc_jack_report(struct tabla_priv *tabla,
struct snd_soc_jack *jack, int status,
int mask)
{
/* XXX: wake_lock_timeout()? */
snd_soc_jack_report_no_dapm(jack, status, mask);
}
static void hphocp_off_report(struct tabla_priv *tabla,
u32 jack_status, int irq)
{
struct snd_soc_codec *codec;
if (!tabla) {
pr_err("%s: Bad tabla private data\n", __func__);
return;
}
pr_debug("%s: clear ocp status %x\n", __func__, jack_status);
codec = tabla->codec;
if (tabla->hph_status & jack_status) {
tabla->hph_status &= ~jack_status;
if (tabla->mbhc_cfg.headset_jack)
tabla_snd_soc_jack_report(tabla,
tabla->mbhc_cfg.headset_jack,
tabla->hph_status,
TABLA_JACK_MASK);
snd_soc_update_bits(codec, TABLA_A_RX_HPH_OCP_CTL, 0x10, 0x00);
snd_soc_update_bits(codec, TABLA_A_RX_HPH_OCP_CTL, 0x10, 0x10);
/* reset retry counter as PA is turned off signifying
* start of new OCP detection session
*/
if (WCD9XXX_IRQ_HPH_PA_OCPL_FAULT)
tabla->hphlocp_cnt = 0;
else
tabla->hphrocp_cnt = 0;
wcd9xxx_enable_irq(codec->control_data, irq);
}
}
static void hphlocp_off_report(struct work_struct *work)
{
struct tabla_priv *tabla = container_of(work, struct tabla_priv,
hphlocp_work);
hphocp_off_report(tabla, SND_JACK_OC_HPHL,
WCD9XXX_IRQ_HPH_PA_OCPL_FAULT);
}
static void hphrocp_off_report(struct work_struct *work)
{
struct tabla_priv *tabla = container_of(work, struct tabla_priv,
hphrocp_work);
hphocp_off_report(tabla, SND_JACK_OC_HPHR,
WCD9XXX_IRQ_HPH_PA_OCPR_FAULT);
}
static int tabla_codec_enable_anc(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
const char *filename;
const struct firmware *fw;
int i;
int ret;
int num_anc_slots;
struct anc_header *anc_head;
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
u32 anc_writes_size = 0;
int anc_size_remaining;
u32 *anc_ptr;
u16 reg;
u8 mask, val, old_val;
u8 mbhc_micb_ctl_val;
pr_debug("%s: DAPM Event %d ANC func is %d\n",
__func__, event, tabla->anc_func);
if (tabla->anc_func == 0)
return 0;
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
mbhc_micb_ctl_val = snd_soc_read(codec,
tabla->mbhc_bias_regs.ctl_reg);
if (!(mbhc_micb_ctl_val & 0x80)) {
TABLA_ACQUIRE_LOCK(tabla->codec_resource_lock);
tabla_codec_switch_micbias(codec, 1);
TABLA_RELEASE_LOCK(tabla->codec_resource_lock);
}
filename = "wcd9310/wcd9310_anc.bin";
ret = request_firmware(&fw, filename, codec->dev);
if (ret != 0) {
dev_err(codec->dev, "Failed to acquire ANC data: %d\n",
ret);
return -ENODEV;
}
if (fw->size < sizeof(struct anc_header)) {
dev_err(codec->dev, "Not enough data\n");
release_firmware(fw);
return -ENOMEM;
}
/* First number is the number of register writes */
anc_head = (struct anc_header *)(fw->data);
anc_ptr = (u32 *)((u32)fw->data + sizeof(struct anc_header));
anc_size_remaining = fw->size - sizeof(struct anc_header);
num_anc_slots = anc_head->num_anc_slots;
if (tabla->anc_slot >= num_anc_slots) {
dev_err(codec->dev, "Invalid ANC slot selected\n");
release_firmware(fw);
return -EINVAL;
}
for (i = 0; i < num_anc_slots; i++) {
if (anc_size_remaining < TABLA_PACKED_REG_SIZE) {
dev_err(codec->dev, "Invalid register format\n");
release_firmware(fw);
return -EINVAL;
}
anc_writes_size = (u32)(*anc_ptr);
anc_size_remaining -= sizeof(u32);
anc_ptr += 1;
if (anc_writes_size * TABLA_PACKED_REG_SIZE
> anc_size_remaining) {
dev_err(codec->dev, "Invalid register format\n");
release_firmware(fw);
return -ENOMEM;
}
if (tabla->anc_slot == i)
break;
anc_size_remaining -= (anc_writes_size *
TABLA_PACKED_REG_SIZE);
anc_ptr += anc_writes_size;
}
if (i == num_anc_slots) {
dev_err(codec->dev, "Selected ANC slot not present\n");
release_firmware(fw);
return -ENOMEM;
}
for (i = 0; i < anc_writes_size; i++) {
TABLA_CODEC_UNPACK_ENTRY(anc_ptr[i], reg,
mask, val);
old_val = snd_soc_read(codec, reg);
snd_soc_write(codec, reg, (old_val & ~mask) |
(val & mask));
}
usleep_range(10000, 10000);
snd_soc_update_bits(codec, TABLA_A_RX_HPH_CNP_EN, 0x30, 0x30);
msleep(30);
release_firmware(fw);
TABLA_ACQUIRE_LOCK(tabla->codec_resource_lock);
/* if MBHC polling is active, set TX7_MBHC_EN bit 7 */
if (tabla->mbhc_polling_active)
snd_soc_update_bits(codec, TABLA_A_TX_7_MBHC_EN, 0x80,
0x80);
TABLA_RELEASE_LOCK(tabla->codec_resource_lock);
break;
case SND_SOC_DAPM_POST_PMD:
/* schedule work is required because at the time HPH PA DAPM
* event callback is called by DAPM framework, CODEC dapm mutex
* would have been locked while snd_soc_jack_report also
* attempts to acquire same lock.
*/
if (w->shift == 5) {
clear_bit(TABLA_HPHL_PA_OFF_ACK,
&tabla->hph_pa_dac_state);
clear_bit(TABLA_HPHL_DAC_OFF_ACK,
&tabla->hph_pa_dac_state);
if (tabla->hph_status & SND_JACK_OC_HPHL)
schedule_work(&tabla->hphlocp_work);
} else if (w->shift == 4) {
clear_bit(TABLA_HPHR_PA_OFF_ACK,
&tabla->hph_pa_dac_state);
clear_bit(TABLA_HPHR_DAC_OFF_ACK,
&tabla->hph_pa_dac_state);
if (tabla->hph_status & SND_JACK_OC_HPHR)
schedule_work(&tabla->hphrocp_work);
}
TABLA_ACQUIRE_LOCK(tabla->codec_resource_lock);
tabla_codec_switch_micbias(codec, 0);
TABLA_RELEASE_LOCK(tabla->codec_resource_lock);
break;
case SND_SOC_DAPM_PRE_PMD:
snd_soc_update_bits(codec, TABLA_A_RX_HPH_CNP_EN, 0x30, 0x00);
msleep(40);
/* unset TX7_MBHC_EN bit 7 */
snd_soc_update_bits(codec, TABLA_A_TX_7_MBHC_EN, 0x80, 0x00);
snd_soc_update_bits(codec, TABLA_A_CDC_ANC1_CTL, 0x01, 0x00);
snd_soc_update_bits(codec, TABLA_A_CDC_ANC2_CTL, 0x01, 0x00);
msleep(20);
snd_soc_write(codec, TABLA_A_CDC_CLK_ANC_RESET_CTL, 0x0F);
snd_soc_write(codec, TABLA_A_CDC_CLK_ANC_CLK_EN_CTL, 0);
snd_soc_write(codec, TABLA_A_CDC_CLK_ANC_RESET_CTL, 0xFF);
break;
}
return 0;
}
static int tabla_hph_pa_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
u8 mbhc_micb_ctl_val;
pr_debug("%s: event = %d\n", __func__, event);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
mbhc_micb_ctl_val = snd_soc_read(codec,
tabla->mbhc_bias_regs.ctl_reg);
if (!(mbhc_micb_ctl_val & 0x80)) {
TABLA_ACQUIRE_LOCK(tabla->codec_resource_lock);
tabla_codec_switch_micbias(codec, 1);
TABLA_RELEASE_LOCK(tabla->codec_resource_lock);
}
break;
case SND_SOC_DAPM_POST_PMD:
/* schedule work is required because at the time HPH PA DAPM
* event callback is called by DAPM framework, CODEC dapm mutex
* would have been locked while snd_soc_jack_report also
* attempts to acquire same lock.
*/
if (w->shift == 5) {
clear_bit(TABLA_HPHL_PA_OFF_ACK,
&tabla->hph_pa_dac_state);
clear_bit(TABLA_HPHL_DAC_OFF_ACK,
&tabla->hph_pa_dac_state);
if (tabla->hph_status & SND_JACK_OC_HPHL)
schedule_work(&tabla->hphlocp_work);
} else if (w->shift == 4) {
clear_bit(TABLA_HPHR_PA_OFF_ACK,
&tabla->hph_pa_dac_state);
clear_bit(TABLA_HPHR_DAC_OFF_ACK,
&tabla->hph_pa_dac_state);
if (tabla->hph_status & SND_JACK_OC_HPHR)
schedule_work(&tabla->hphrocp_work);
}
TABLA_ACQUIRE_LOCK(tabla->codec_resource_lock);
tabla_codec_switch_micbias(codec, 0);
TABLA_RELEASE_LOCK(tabla->codec_resource_lock);
pr_debug("%s: sleep 10 ms after %s PA disable.\n", __func__,
w->name);
usleep_range(10000, 10000);
break;
}
return 0;
}
static void tabla_get_mbhc_micbias_regs(struct snd_soc_codec *codec,
struct mbhc_micbias_regs *micbias_regs)
{
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
unsigned int cfilt;
switch (tabla->mbhc_cfg.micbias) {
case TABLA_MICBIAS1:
cfilt = tabla->pdata->micbias.bias1_cfilt_sel;
micbias_regs->mbhc_reg = TABLA_A_MICB_1_MBHC;
micbias_regs->int_rbias = TABLA_A_MICB_1_INT_RBIAS;
micbias_regs->ctl_reg = TABLA_A_MICB_1_CTL;
break;
case TABLA_MICBIAS2:
cfilt = tabla->pdata->micbias.bias2_cfilt_sel;
micbias_regs->mbhc_reg = TABLA_A_MICB_2_MBHC;
micbias_regs->int_rbias = TABLA_A_MICB_2_INT_RBIAS;
micbias_regs->ctl_reg = TABLA_A_MICB_2_CTL;
break;
case TABLA_MICBIAS3:
cfilt = tabla->pdata->micbias.bias3_cfilt_sel;
micbias_regs->mbhc_reg = TABLA_A_MICB_3_MBHC;
micbias_regs->int_rbias = TABLA_A_MICB_3_INT_RBIAS;
micbias_regs->ctl_reg = TABLA_A_MICB_3_CTL;
break;
case TABLA_MICBIAS4:
cfilt = tabla->pdata->micbias.bias4_cfilt_sel;
micbias_regs->mbhc_reg = tabla->reg_addr.micb_4_mbhc;
micbias_regs->int_rbias = tabla->reg_addr.micb_4_int_rbias;
micbias_regs->ctl_reg = tabla->reg_addr.micb_4_ctl;
break;
default:
/* Should never reach here */
pr_err("%s: Invalid MIC BIAS for MBHC\n", __func__);
return;
}
micbias_regs->cfilt_sel = cfilt;
switch (cfilt) {
case TABLA_CFILT1_SEL:
micbias_regs->cfilt_val = TABLA_A_MICB_CFILT_1_VAL;
micbias_regs->cfilt_ctl = TABLA_A_MICB_CFILT_1_CTL;
tabla->mbhc_data.micb_mv = tabla->pdata->micbias.cfilt1_mv;
break;
case TABLA_CFILT2_SEL:
micbias_regs->cfilt_val = TABLA_A_MICB_CFILT_2_VAL;
micbias_regs->cfilt_ctl = TABLA_A_MICB_CFILT_2_CTL;
tabla->mbhc_data.micb_mv = tabla->pdata->micbias.cfilt2_mv;
break;
case TABLA_CFILT3_SEL:
micbias_regs->cfilt_val = TABLA_A_MICB_CFILT_3_VAL;
micbias_regs->cfilt_ctl = TABLA_A_MICB_CFILT_3_CTL;
tabla->mbhc_data.micb_mv = tabla->pdata->micbias.cfilt3_mv;
break;
}
}
static const struct snd_soc_dapm_widget tabla_dapm_i2s_widgets[] = {
SND_SOC_DAPM_SUPPLY("RX_I2S_CLK", TABLA_A_CDC_CLK_RX_I2S_CTL,
4, 0, NULL, 0),
SND_SOC_DAPM_SUPPLY("TX_I2S_CLK", TABLA_A_CDC_CLK_TX_I2S_CTL, 4,
0, NULL, 0),
};
static int tabla_lineout_dac_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
pr_debug("%s %s %d\n", __func__, w->name, event);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
snd_soc_update_bits(codec, w->reg, 0x40, 0x40);
break;
case SND_SOC_DAPM_POST_PMD:
snd_soc_update_bits(codec, w->reg, 0x40, 0x00);
break;
}
return 0;
}
static int tabla_ear_pa_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
pr_debug("%s %d\n", __func__, event);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
snd_soc_update_bits(codec, TABLA_A_RX_EAR_EN, 0x50, 0x50);
break;
case SND_SOC_DAPM_PRE_PMD:
snd_soc_update_bits(codec, TABLA_A_RX_EAR_EN, 0x10, 0x00);
snd_soc_update_bits(codec, TABLA_A_RX_EAR_EN, 0x40, 0x00);
break;
}
return 0;
}
static const struct snd_soc_dapm_widget tabla_1_x_dapm_widgets[] = {
SND_SOC_DAPM_MICBIAS_E("MIC BIAS4 External", SND_SOC_NOPM, 0,
0, tabla_codec_enable_micbias,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_POST_PMD),
};
static const struct snd_soc_dapm_widget tabla_2_higher_dapm_widgets[] = {
SND_SOC_DAPM_MICBIAS_E("MIC BIAS4 External", SND_SOC_NOPM, 0,
0, tabla_codec_enable_micbias,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_POST_PMD),
};
static const struct snd_soc_dapm_route audio_i2s_map[] = {
{"RX_I2S_CLK", NULL, "CDC_CONN"},
{"SLIM RX1", NULL, "RX_I2S_CLK"},
{"SLIM RX2", NULL, "RX_I2S_CLK"},
{"SLIM RX3", NULL, "RX_I2S_CLK"},
{"SLIM RX4", NULL, "RX_I2S_CLK"},
{"SLIM TX7", NULL, "TX_I2S_CLK"},
{"SLIM TX8", NULL, "TX_I2S_CLK"},
{"SLIM TX9", NULL, "TX_I2S_CLK"},
{"SLIM TX10", NULL, "TX_I2S_CLK"},
};
static const struct snd_soc_dapm_route audio_map[] = {
/* SLIMBUS Connections */
{"AIF1 CAP", NULL, "AIF1_CAP Mixer"},
{"AIF2 CAP", NULL, "AIF2_CAP Mixer"},
{"AIF3 CAP", NULL, "AIF3_CAP Mixer"},
/* SLIM_MIXER("AIF1_CAP Mixer"),*/
{"AIF1_CAP Mixer", "SLIM TX1", "SLIM TX1 MUX"},
{"AIF1_CAP Mixer", "SLIM TX2", "SLIM TX2 MUX"},
{"AIF1_CAP Mixer", "SLIM TX3", "SLIM TX3 MUX"},
{"AIF1_CAP Mixer", "SLIM TX4", "SLIM TX4 MUX"},
{"AIF1_CAP Mixer", "SLIM TX5", "SLIM TX5 MUX"},
{"AIF1_CAP Mixer", "SLIM TX6", "SLIM TX6 MUX"},
{"AIF1_CAP Mixer", "SLIM TX7", "SLIM TX7 MUX"},
{"AIF1_CAP Mixer", "SLIM TX8", "SLIM TX8 MUX"},
{"AIF1_CAP Mixer", "SLIM TX9", "SLIM TX9 MUX"},
{"AIF1_CAP Mixer", "SLIM TX10", "SLIM TX10 MUX"},
/* SLIM_MIXER("AIF2_CAP Mixer"),*/
{"AIF2_CAP Mixer", "SLIM TX1", "SLIM TX1 MUX"},
{"AIF2_CAP Mixer", "SLIM TX2", "SLIM TX2 MUX"},
{"AIF2_CAP Mixer", "SLIM TX3", "SLIM TX3 MUX"},
{"AIF2_CAP Mixer", "SLIM TX4", "SLIM TX4 MUX"},
{"AIF2_CAP Mixer", "SLIM TX5", "SLIM TX5 MUX"},
{"AIF2_CAP Mixer", "SLIM TX6", "SLIM TX6 MUX"},
{"AIF2_CAP Mixer", "SLIM TX7", "SLIM TX7 MUX"},
{"AIF2_CAP Mixer", "SLIM TX8", "SLIM TX8 MUX"},
{"AIF2_CAP Mixer", "SLIM TX9", "SLIM TX9 MUX"},
{"AIF2_CAP Mixer", "SLIM TX10", "SLIM TX10 MUX"},
/* SLIM_MIXER("AIF3_CAP Mixer"),*/
{"AIF3_CAP Mixer", "SLIM TX1", "SLIM TX1 MUX"},
{"AIF3_CAP Mixer", "SLIM TX2", "SLIM TX2 MUX"},
{"AIF3_CAP Mixer", "SLIM TX3", "SLIM TX3 MUX"},
{"AIF3_CAP Mixer", "SLIM TX4", "SLIM TX4 MUX"},
{"AIF3_CAP Mixer", "SLIM TX5", "SLIM TX5 MUX"},
{"AIF3_CAP Mixer", "SLIM TX6", "SLIM TX6 MUX"},
{"AIF3_CAP Mixer", "SLIM TX7", "SLIM TX7 MUX"},
{"AIF3_CAP Mixer", "SLIM TX8", "SLIM TX8 MUX"},
{"AIF3_CAP Mixer", "SLIM TX9", "SLIM TX9 MUX"},
{"AIF3_CAP Mixer", "SLIM TX10", "SLIM TX10 MUX"},
{"SLIM TX1 MUX", "DEC1", "DEC1 MUX"},
{"SLIM TX2 MUX", "DEC2", "DEC2 MUX"},
{"SLIM TX3 MUX", "DEC3", "DEC3 MUX"},
{"SLIM TX3 MUX", "RMIX1", "RX1 MIX1"},
{"SLIM TX3 MUX", "RMIX2", "RX2 MIX1"},
{"SLIM TX3 MUX", "RMIX3", "RX3 MIX1"},
{"SLIM TX3 MUX", "RMIX4", "RX4 MIX1"},
{"SLIM TX3 MUX", "RMIX5", "RX5 MIX1"},
{"SLIM TX3 MUX", "RMIX6", "RX6 MIX1"},
{"SLIM TX3 MUX", "RMIX7", "RX7 MIX1"},
{"SLIM TX4 MUX", "DEC4", "DEC4 MUX"},
{"SLIM TX5 MUX", "DEC5", "DEC5 MUX"},
{"SLIM TX5 MUX", "RMIX1", "RX1 MIX1"},
{"SLIM TX5 MUX", "RMIX2", "RX2 MIX1"},
{"SLIM TX5 MUX", "RMIX3", "RX3 MIX1"},
{"SLIM TX5 MUX", "RMIX4", "RX4 MIX1"},
{"SLIM TX5 MUX", "RMIX5", "RX5 MIX1"},
{"SLIM TX5 MUX", "RMIX6", "RX6 MIX1"},
{"SLIM TX5 MUX", "RMIX7", "RX7 MIX1"},
{"SLIM TX6 MUX", "DEC6", "DEC6 MUX"},
{"SLIM TX7 MUX", "DEC1", "DEC1 MUX"},
{"SLIM TX7 MUX", "DEC2", "DEC2 MUX"},
{"SLIM TX7 MUX", "DEC3", "DEC3 MUX"},
{"SLIM TX7 MUX", "DEC4", "DEC4 MUX"},
{"SLIM TX7 MUX", "DEC5", "DEC5 MUX"},
{"SLIM TX7 MUX", "DEC6", "DEC6 MUX"},
{"SLIM TX7 MUX", "DEC7", "DEC7 MUX"},
{"SLIM TX7 MUX", "DEC8", "DEC8 MUX"},
{"SLIM TX7 MUX", "DEC9", "DEC9 MUX"},
{"SLIM TX7 MUX", "DEC10", "DEC10 MUX"},
{"SLIM TX7 MUX", "RMIX1", "RX1 MIX1"},
{"SLIM TX7 MUX", "RMIX2", "RX2 MIX1"},
{"SLIM TX7 MUX", "RMIX3", "RX3 MIX1"},
{"SLIM TX7 MUX", "RMIX4", "RX4 MIX1"},
{"SLIM TX7 MUX", "RMIX5", "RX5 MIX1"},
{"SLIM TX7 MUX", "RMIX6", "RX6 MIX1"},
{"SLIM TX7 MUX", "RMIX7", "RX7 MIX1"},
{"SLIM TX8 MUX", "DEC1", "DEC1 MUX"},
{"SLIM TX8 MUX", "DEC2", "DEC2 MUX"},
{"SLIM TX8 MUX", "DEC3", "DEC3 MUX"},
{"SLIM TX8 MUX", "DEC4", "DEC4 MUX"},
{"SLIM TX8 MUX", "DEC5", "DEC5 MUX"},
{"SLIM TX8 MUX", "DEC6", "DEC6 MUX"},
{"SLIM TX8 MUX", "DEC7", "DEC7 MUX"},
{"SLIM TX8 MUX", "DEC8", "DEC8 MUX"},
{"SLIM TX8 MUX", "DEC9", "DEC9 MUX"},
{"SLIM TX8 MUX", "DEC10", "DEC10 MUX"},
{"SLIM TX9 MUX", "DEC1", "DEC1 MUX"},
{"SLIM TX9 MUX", "DEC2", "DEC2 MUX"},
{"SLIM TX9 MUX", "DEC3", "DEC3 MUX"},
{"SLIM TX9 MUX", "DEC4", "DEC4 MUX"},
{"SLIM TX9 MUX", "DEC5", "DEC5 MUX"},
{"SLIM TX9 MUX", "DEC6", "DEC6 MUX"},
{"SLIM TX9 MUX", "DEC7", "DEC7 MUX"},
{"SLIM TX9 MUX", "DEC8", "DEC8 MUX"},
{"SLIM TX9 MUX", "DEC9", "DEC9 MUX"},
{"SLIM TX9 MUX", "DEC10", "DEC10 MUX"},
{"SLIM TX10 MUX", "DEC1", "DEC1 MUX"},
{"SLIM TX10 MUX", "DEC2", "DEC2 MUX"},
{"SLIM TX10 MUX", "DEC3", "DEC3 MUX"},
{"SLIM TX10 MUX", "DEC4", "DEC4 MUX"},
{"SLIM TX10 MUX", "DEC5", "DEC5 MUX"},
{"SLIM TX10 MUX", "DEC6", "DEC6 MUX"},
{"SLIM TX10 MUX", "DEC7", "DEC7 MUX"},
{"SLIM TX10 MUX", "DEC8", "DEC8 MUX"},
{"SLIM TX10 MUX", "DEC9", "DEC9 MUX"},
{"SLIM TX10 MUX", "DEC10", "DEC10 MUX"},
/* Earpiece (RX MIX1) */
{"EAR", NULL, "EAR PA"},
{"EAR PA", NULL, "EAR_PA_MIXER"},
{"EAR_PA_MIXER", NULL, "DAC1"},
{"DAC1", NULL, "CP"},
{"ANC1 FB MUX", "EAR_HPH_L", "RX1 MIX2"},
{"ANC1 FB MUX", "EAR_LINE_1", "RX2 MIX2"},
/* Headset (RX MIX1 and RX MIX2) */
{"HEADPHONE", NULL, "HPHL"},
{"HEADPHONE", NULL, "HPHR"},
{"HPHL", NULL, "HPHL_PA_MIXER"},
{"HPHL_PA_MIXER", NULL, "HPHL DAC"},
{"HPHR", NULL, "HPHR_PA_MIXER"},
{"HPHR_PA_MIXER", NULL, "HPHR DAC"},
{"HPHL DAC", NULL, "CP"},
{"HPHR DAC", NULL, "CP"},
{"ANC HEADPHONE", NULL, "ANC HPHL"},
{"ANC HEADPHONE", NULL, "ANC HPHR"},
{"ANC HPHL", NULL, "HPHL_PA_MIXER"},
{"ANC HPHR", NULL, "HPHR_PA_MIXER"},
{"ANC1 MUX", "ADC1", "ADC1"},
{"ANC1 MUX", "ADC2", "ADC2"},
{"ANC1 MUX", "ADC3", "ADC3"},
{"ANC1 MUX", "ADC4", "ADC4"},
{"ANC1 MUX", "DMIC1", "DMIC1"},
{"ANC1 MUX", "DMIC2", "DMIC2"},
{"ANC1 MUX", "DMIC3", "DMIC3"},
{"ANC1 MUX", "DMIC4", "DMIC4"},
{"ANC2 MUX", "ADC1", "ADC1"},
{"ANC2 MUX", "ADC2", "ADC2"},
{"ANC2 MUX", "ADC3", "ADC3"},
{"ANC2 MUX", "ADC4", "ADC4"},
{"ANC HPHR", NULL, "CDC_CONN"},
{"DAC1", "Switch", "RX1 CHAIN"},
{"HPHL DAC", "Switch", "RX1 CHAIN"},
{"HPHR DAC", NULL, "RX2 CHAIN"},
{"LINEOUT1", NULL, "LINEOUT1 PA"},
{"LINEOUT2", NULL, "LINEOUT2 PA"},
{"LINEOUT3", NULL, "LINEOUT3 PA"},
{"LINEOUT4", NULL, "LINEOUT4 PA"},
{"LINEOUT5", NULL, "LINEOUT5 PA"},
{"LINEOUT1 PA", NULL, "LINEOUT1_PA_MIXER"},
{"LINEOUT1_PA_MIXER", NULL, "LINEOUT1 DAC"},
{"LINEOUT2 PA", NULL, "LINEOUT2_PA_MIXER"},
{"LINEOUT2_PA_MIXER", NULL, "LINEOUT2 DAC"},
{"LINEOUT3 PA", NULL, "LINEOUT3_PA_MIXER"},
{"LINEOUT3_PA_MIXER", NULL, "LINEOUT3 DAC"},
{"LINEOUT4 PA", NULL, "LINEOUT4_PA_MIXER"},
{"LINEOUT4_PA_MIXER", NULL, "LINEOUT4 DAC"},
{"LINEOUT5 PA", NULL, "LINEOUT5_PA_MIXER"},
{"LINEOUT5_PA_MIXER", NULL, "LINEOUT5 DAC"},
{"LINEOUT1 DAC", NULL, "RX3 MIX2"},
{"LINEOUT5 DAC", NULL, "RX7 MIX1"},
{"RX1 CHAIN", NULL, "RX1 MIX2"},
{"RX2 CHAIN", NULL, "RX2 MIX2"},
{"RX1 MIX2", NULL, "ANC1 MUX"},
{"RX2 MIX2", NULL, "ANC2 MUX"},
{"CP", NULL, "RX_BIAS"},
{"LINEOUT1 DAC", NULL, "RX_BIAS"},
{"LINEOUT2 DAC", NULL, "RX_BIAS"},
{"LINEOUT3 DAC", NULL, "RX_BIAS"},
{"LINEOUT4 DAC", NULL, "RX_BIAS"},
{"LINEOUT5 DAC", NULL, "RX_BIAS"},
{"RX1 MIX1", NULL, "COMP1_CLK"},
{"RX2 MIX1", NULL, "COMP1_CLK"},
{"RX3 MIX1", NULL, "COMP2_CLK"},
{"RX5 MIX1", NULL, "COMP2_CLK"},
{"RX1 MIX1", NULL, "RX1 MIX1 INP1"},
{"RX1 MIX1", NULL, "RX1 MIX1 INP2"},
{"RX1 MIX1", NULL, "RX1 MIX1 INP3"},
{"RX2 MIX1", NULL, "RX2 MIX1 INP1"},
{"RX2 MIX1", NULL, "RX2 MIX1 INP2"},
{"RX3 MIX1", NULL, "RX3 MIX1 INP1"},
{"RX3 MIX1", NULL, "RX3 MIX1 INP2"},
{"RX4 MIX1", NULL, "RX4 MIX1 INP1"},
{"RX4 MIX1", NULL, "RX4 MIX1 INP2"},
{"RX5 MIX1", NULL, "RX5 MIX1 INP1"},
{"RX5 MIX1", NULL, "RX5 MIX1 INP2"},
{"RX6 MIX1", NULL, "RX6 MIX1 INP1"},
{"RX6 MIX1", NULL, "RX6 MIX1 INP2"},
{"RX7 MIX1", NULL, "RX7 MIX1 INP1"},
{"RX7 MIX1", NULL, "RX7 MIX1 INP2"},
{"RX1 MIX2", NULL, "RX1 MIX1"},
{"RX1 MIX2", NULL, "RX1 MIX2 INP1"},
{"RX1 MIX2", NULL, "RX1 MIX2 INP2"},
{"RX2 MIX2", NULL, "RX2 MIX1"},
{"RX2 MIX2", NULL, "RX2 MIX2 INP1"},
{"RX2 MIX2", NULL, "RX2 MIX2 INP2"},
{"RX3 MIX2", NULL, "RX3 MIX1"},
{"RX3 MIX2", NULL, "RX3 MIX2 INP1"},
{"RX3 MIX2", NULL, "RX3 MIX2 INP2"},
/* SLIM_MUX("AIF1_PB", "AIF1 PB"),*/
{"SLIM RX1 MUX", "AIF1_PB", "AIF1 PB"},
{"SLIM RX2 MUX", "AIF1_PB", "AIF1 PB"},
{"SLIM RX3 MUX", "AIF1_PB", "AIF1 PB"},
{"SLIM RX4 MUX", "AIF1_PB", "AIF1 PB"},
{"SLIM RX5 MUX", "AIF1_PB", "AIF1 PB"},
{"SLIM RX6 MUX", "AIF1_PB", "AIF1 PB"},
{"SLIM RX7 MUX", "AIF1_PB", "AIF1 PB"},
/* SLIM_MUX("AIF2_PB", "AIF2 PB"),*/
{"SLIM RX1 MUX", "AIF2_PB", "AIF2 PB"},
{"SLIM RX2 MUX", "AIF2_PB", "AIF2 PB"},
{"SLIM RX3 MUX", "AIF2_PB", "AIF2 PB"},
{"SLIM RX4 MUX", "AIF2_PB", "AIF2 PB"},
{"SLIM RX5 MUX", "AIF2_PB", "AIF2 PB"},
{"SLIM RX6 MUX", "AIF2_PB", "AIF2 PB"},
{"SLIM RX7 MUX", "AIF2_PB", "AIF2 PB"},
/* SLIM_MUX("AIF3_PB", "AIF3 PB"),*/
{"SLIM RX1 MUX", "AIF3_PB", "AIF3 PB"},
{"SLIM RX2 MUX", "AIF3_PB", "AIF3 PB"},
{"SLIM RX3 MUX", "AIF3_PB", "AIF3 PB"},
{"SLIM RX4 MUX", "AIF3_PB", "AIF3 PB"},
{"SLIM RX5 MUX", "AIF3_PB", "AIF3 PB"},
{"SLIM RX6 MUX", "AIF3_PB", "AIF3 PB"},
{"SLIM RX7 MUX", "AIF3_PB", "AIF3 PB"},
{"SLIM RX1", NULL, "SLIM RX1 MUX"},
{"SLIM RX2", NULL, "SLIM RX2 MUX"},
{"SLIM RX3", NULL, "SLIM RX3 MUX"},
{"SLIM RX4", NULL, "SLIM RX4 MUX"},
{"SLIM RX5", NULL, "SLIM RX5 MUX"},
{"SLIM RX6", NULL, "SLIM RX6 MUX"},
{"SLIM RX7", NULL, "SLIM RX7 MUX"},
/* Mixer control for output path */
{"RX1 MIX1 INP1", "RX1", "SLIM RX1"},
{"RX1 MIX1 INP1", "RX2", "SLIM RX2"},
{"RX1 MIX1 INP1", "RX3", "SLIM RX3"},
{"RX1 MIX1 INP1", "RX4", "SLIM RX4"},
{"RX1 MIX1 INP1", "RX5", "SLIM RX5"},
{"RX1 MIX1 INP1", "RX6", "SLIM RX6"},
{"RX1 MIX1 INP1", "RX7", "SLIM RX7"},
{"RX1 MIX1 INP1", "IIR1", "IIR1"},
{"RX1 MIX1 INP1", "IIR2", "IIR2"},
{"RX1 MIX1 INP2", "RX1", "SLIM RX1"},
{"RX1 MIX1 INP2", "RX2", "SLIM RX2"},
{"RX1 MIX1 INP2", "RX3", "SLIM RX3"},
{"RX1 MIX1 INP2", "RX4", "SLIM RX4"},
{"RX1 MIX1 INP2", "RX5", "SLIM RX5"},
{"RX1 MIX1 INP2", "RX6", "SLIM RX6"},
{"RX1 MIX1 INP2", "RX7", "SLIM RX7"},
{"RX1 MIX1 INP2", "IIR1", "IIR1"},
{"RX1 MIX1 INP2", "IIR2", "IIR2"},
{"RX1 MIX1 INP3", "RX1", "SLIM RX1"},
{"RX1 MIX1 INP3", "RX2", "SLIM RX2"},
{"RX1 MIX1 INP3", "RX3", "SLIM RX3"},
{"RX1 MIX1 INP3", "RX4", "SLIM RX4"},
{"RX1 MIX1 INP3", "RX5", "SLIM RX5"},
{"RX1 MIX1 INP3", "RX6", "SLIM RX6"},
{"RX1 MIX1 INP3", "RX7", "SLIM RX7"},
{"RX2 MIX1 INP1", "RX1", "SLIM RX1"},
{"RX2 MIX1 INP1", "RX2", "SLIM RX2"},
{"RX2 MIX1 INP1", "RX3", "SLIM RX3"},
{"RX2 MIX1 INP1", "RX4", "SLIM RX4"},
{"RX2 MIX1 INP1", "RX5", "SLIM RX5"},
{"RX2 MIX1 INP1", "RX6", "SLIM RX6"},
{"RX2 MIX1 INP1", "RX7", "SLIM RX7"},
{"RX2 MIX1 INP1", "IIR1", "IIR1"},
{"RX2 MIX1 INP1", "IIR2", "IIR2"},
{"RX2 MIX1 INP2", "RX1", "SLIM RX1"},
{"RX2 MIX1 INP2", "RX2", "SLIM RX2"},
{"RX2 MIX1 INP2", "RX3", "SLIM RX3"},
{"RX2 MIX1 INP2", "RX4", "SLIM RX4"},
{"RX2 MIX1 INP2", "RX5", "SLIM RX5"},
{"RX2 MIX1 INP2", "RX6", "SLIM RX6"},
{"RX2 MIX1 INP2", "RX7", "SLIM RX7"},
{"RX2 MIX1 INP2", "IIR1", "IIR1"},
{"RX2 MIX1 INP2", "IIR2", "IIR2"},
{"RX3 MIX1 INP1", "RX1", "SLIM RX1"},
{"RX3 MIX1 INP1", "RX2", "SLIM RX2"},
{"RX3 MIX1 INP1", "RX3", "SLIM RX3"},
{"RX3 MIX1 INP1", "RX4", "SLIM RX4"},
{"RX3 MIX1 INP1", "RX5", "SLIM RX5"},
{"RX3 MIX1 INP1", "RX6", "SLIM RX6"},
{"RX3 MIX1 INP1", "RX7", "SLIM RX7"},
{"RX3 MIX1 INP1", "IIR1", "IIR1"},
{"RX3 MIX1 INP1", "IIR2", "IIR2"},
{"RX3 MIX1 INP2", "RX1", "SLIM RX1"},
{"RX3 MIX1 INP2", "RX2", "SLIM RX2"},
{"RX3 MIX1 INP2", "RX3", "SLIM RX3"},
{"RX3 MIX1 INP2", "RX4", "SLIM RX4"},
{"RX3 MIX1 INP2", "RX5", "SLIM RX5"},
{"RX3 MIX1 INP2", "RX6", "SLIM RX6"},
{"RX3 MIX1 INP2", "RX7", "SLIM RX7"},
{"RX3 MIX1 INP2", "IIR1", "IIR1"},
{"RX3 MIX1 INP2", "IIR2", "IIR2"},
{"RX4 MIX1 INP1", "RX1", "SLIM RX1"},
{"RX4 MIX1 INP1", "RX2", "SLIM RX2"},
{"RX4 MIX1 INP1", "RX3", "SLIM RX3"},
{"RX4 MIX1 INP1", "RX4", "SLIM RX4"},
{"RX4 MIX1 INP1", "RX5", "SLIM RX5"},
{"RX4 MIX1 INP1", "RX6", "SLIM RX6"},
{"RX4 MIX1 INP1", "RX7", "SLIM RX7"},
{"RX4 MIX1 INP1", "IIR1", "IIR1"},
{"RX4 MIX1 INP1", "IIR2", "IIR2"},
{"RX4 MIX1 INP2", "RX1", "SLIM RX1"},
{"RX4 MIX1 INP2", "RX2", "SLIM RX2"},
{"RX4 MIX1 INP2", "RX3", "SLIM RX3"},
{"RX4 MIX1 INP2", "RX5", "SLIM RX5"},
{"RX4 MIX1 INP2", "RX4", "SLIM RX4"},
{"RX4 MIX1 INP2", "RX6", "SLIM RX6"},
{"RX4 MIX1 INP2", "RX7", "SLIM RX7"},
{"RX4 MIX1 INP2", "IIR1", "IIR1"},
{"RX4 MIX1 INP2", "IIR2", "IIR2"},
{"RX5 MIX1 INP1", "RX1", "SLIM RX1"},
{"RX5 MIX1 INP1", "RX2", "SLIM RX2"},
{"RX5 MIX1 INP1", "RX3", "SLIM RX3"},
{"RX5 MIX1 INP1", "RX4", "SLIM RX4"},
{"RX5 MIX1 INP1", "RX5", "SLIM RX5"},
{"RX5 MIX1 INP1", "RX6", "SLIM RX6"},
{"RX5 MIX1 INP1", "RX7", "SLIM RX7"},
{"RX5 MIX1 INP1", "IIR1", "IIR1"},
{"RX5 MIX1 INP1", "IIR2", "IIR2"},
{"RX5 MIX1 INP2", "RX1", "SLIM RX1"},
{"RX5 MIX1 INP2", "RX2", "SLIM RX2"},
{"RX5 MIX1 INP2", "RX3", "SLIM RX3"},
{"RX5 MIX1 INP2", "RX4", "SLIM RX4"},
{"RX5 MIX1 INP2", "RX5", "SLIM RX5"},
{"RX5 MIX1 INP2", "RX6", "SLIM RX6"},
{"RX5 MIX1 INP2", "RX7", "SLIM RX7"},
{"RX5 MIX1 INP2", "IIR1", "IIR1"},
{"RX5 MIX1 INP2", "IIR2", "IIR2"},
{"RX6 MIX1 INP1", "RX1", "SLIM RX1"},
{"RX6 MIX1 INP1", "RX2", "SLIM RX2"},
{"RX6 MIX1 INP1", "RX3", "SLIM RX3"},
{"RX6 MIX1 INP1", "RX4", "SLIM RX4"},
{"RX6 MIX1 INP1", "RX5", "SLIM RX5"},
{"RX6 MIX1 INP1", "RX6", "SLIM RX6"},
{"RX6 MIX1 INP1", "RX7", "SLIM RX7"},
{"RX6 MIX1 INP1", "IIR1", "IIR1"},
{"RX6 MIX1 INP1", "IIR2", "IIR2"},
{"RX6 MIX1 INP2", "RX1", "SLIM RX1"},
{"RX6 MIX1 INP2", "RX2", "SLIM RX2"},
{"RX6 MIX1 INP2", "RX3", "SLIM RX3"},
{"RX6 MIX1 INP2", "RX4", "SLIM RX4"},
{"RX6 MIX1 INP2", "RX5", "SLIM RX5"},
{"RX6 MIX1 INP2", "RX6", "SLIM RX6"},
{"RX6 MIX1 INP2", "RX7", "SLIM RX7"},
{"RX6 MIX1 INP2", "IIR1", "IIR1"},
{"RX6 MIX1 INP2", "IIR2", "IIR2"},
{"RX7 MIX1 INP1", "RX1", "SLIM RX1"},
{"RX7 MIX1 INP1", "RX2", "SLIM RX2"},
{"RX7 MIX1 INP1", "RX3", "SLIM RX3"},
{"RX7 MIX1 INP1", "RX4", "SLIM RX4"},
{"RX7 MIX1 INP1", "RX5", "SLIM RX5"},
{"RX7 MIX1 INP1", "RX6", "SLIM RX6"},
{"RX7 MIX1 INP1", "RX7", "SLIM RX7"},
{"RX7 MIX1 INP1", "IIR1", "IIR1"},
{"RX7 MIX1 INP1", "IIR2", "IIR2"},
{"RX7 MIX1 INP2", "RX1", "SLIM RX1"},
{"RX7 MIX1 INP2", "RX2", "SLIM RX2"},
{"RX7 MIX1 INP2", "RX3", "SLIM RX3"},
{"RX7 MIX1 INP2", "RX4", "SLIM RX4"},
{"RX7 MIX1 INP2", "RX5", "SLIM RX5"},
{"RX7 MIX1 INP2", "RX6", "SLIM RX6"},
{"RX7 MIX1 INP2", "RX7", "SLIM RX7"},
{"RX7 MIX1 INP2", "IIR1", "IIR1"},
{"RX7 MIX1 INP2", "IIR2", "IIR2"},
{"RX1 MIX2 INP1", "IIR1", "IIR1"},
{"RX1 MIX2 INP1", "IIR2", "IIR2"},
{"RX1 MIX2 INP2", "IIR1", "IIR1"},
{"RX1 MIX2 INP2", "IIR2", "IIR2"},
{"RX2 MIX2 INP1", "IIR1", "IIR1"},
{"RX2 MIX2 INP1", "IIR2", "IIR2"},
{"RX2 MIX2 INP2", "IIR1", "IIR1"},
{"RX2 MIX2 INP2", "IIR2", "IIR2"},
{"RX3 MIX2 INP1", "IIR1", "IIR1"},
{"RX3 MIX2 INP1", "IIR2", "IIR2"},
{"RX3 MIX2 INP2", "IIR1", "IIR1"},
{"RX3 MIX2 INP2", "IIR2", "IIR2"},
/* Decimator Inputs */
{"DEC1 MUX", "DMIC1", "DMIC1"},
{"DEC1 MUX", "ADC6", "ADC6"},
{"DEC1 MUX", NULL, "CDC_CONN"},
{"DEC2 MUX", "DMIC2", "DMIC2"},
{"DEC2 MUX", "ADC5", "ADC5"},
{"DEC2 MUX", NULL, "CDC_CONN"},
{"DEC3 MUX", "DMIC3", "DMIC3"},
{"DEC3 MUX", "ADC4", "ADC4"},
{"DEC3 MUX", NULL, "CDC_CONN"},
{"DEC4 MUX", "DMIC4", "DMIC4"},
{"DEC4 MUX", "ADC3", "ADC3"},
{"DEC4 MUX", NULL, "CDC_CONN"},
{"DEC5 MUX", "DMIC5", "DMIC5"},
{"DEC5 MUX", "ADC2", "ADC2"},
{"DEC5 MUX", NULL, "CDC_CONN"},
{"DEC6 MUX", "DMIC6", "DMIC6"},
{"DEC6 MUX", "ADC1", "ADC1"},
{"DEC6 MUX", NULL, "CDC_CONN"},
{"DEC7 MUX", "DMIC1", "DMIC1"},
{"DEC7 MUX", "DMIC6", "DMIC6"},
{"DEC7 MUX", "ADC1", "ADC1"},
{"DEC7 MUX", "ADC6", "ADC6"},
{"DEC7 MUX", NULL, "CDC_CONN"},
{"DEC8 MUX", "DMIC2", "DMIC2"},
{"DEC8 MUX", "DMIC5", "DMIC5"},
{"DEC8 MUX", "ADC2", "ADC2"},
{"DEC8 MUX", "ADC5", "ADC5"},
{"DEC8 MUX", NULL, "CDC_CONN"},
{"DEC9 MUX", "DMIC4", "DMIC4"},
{"DEC9 MUX", "DMIC5", "DMIC5"},
{"DEC9 MUX", "ADC2", "ADC2"},
{"DEC9 MUX", "ADC3", "ADC3"},
{"DEC9 MUX", NULL, "CDC_CONN"},
{"DEC10 MUX", "DMIC3", "DMIC3"},
{"DEC10 MUX", "DMIC6", "DMIC6"},
{"DEC10 MUX", "ADC1", "ADC1"},
{"DEC10 MUX", "ADC4", "ADC4"},
{"DEC10 MUX", NULL, "CDC_CONN"},
/* ADC Connections */
{"ADC1", NULL, "AMIC1"},
{"ADC2", NULL, "AMIC2"},
{"ADC3", NULL, "AMIC3"},
{"ADC4", NULL, "AMIC4"},
{"ADC5", NULL, "AMIC5"},
{"ADC6", NULL, "AMIC6"},
/* AUX PGA Connections */
{"HPHL_PA_MIXER", "AUX_PGA_L Switch", "AUX_PGA_Left"},
{"HPHL_PA_MIXER", "AUX_PGA_R Switch", "AUX_PGA_Right"},
{"HPHL_PA_MIXER", "AUX_PGA_L_INV Switch", "AUX_PGA_Left"},
{"HPHL_PA_MIXER", "AUX_PGA_R_INV Switch", "AUX_PGA_Right"},
{"HPHR_PA_MIXER", "AUX_PGA_L Switch", "AUX_PGA_Left"},
{"HPHR_PA_MIXER", "AUX_PGA_R Switch", "AUX_PGA_Right"},
{"HPHR_PA_MIXER", "AUX_PGA_L_INV Switch", "AUX_PGA_Left"},
{"HPHR_PA_MIXER", "AUX_PGA_R_INV Switch", "AUX_PGA_Right"},
{"LINEOUT1_PA_MIXER", "AUX_PGA_L Switch", "AUX_PGA_Left"},
{"LINEOUT1_PA_MIXER", "AUX_PGA_R Switch", "AUX_PGA_Right"},
{"LINEOUT1_PA_MIXER", "AUX_PGA_L_INV Switch", "AUX_PGA_Left"},
{"LINEOUT1_PA_MIXER", "AUX_PGA_R_INV Switch", "AUX_PGA_Right"},
{"LINEOUT2_PA_MIXER", "AUX_PGA_L Switch", "AUX_PGA_Left"},
{"LINEOUT2_PA_MIXER", "AUX_PGA_R Switch", "AUX_PGA_Right"},
{"LINEOUT2_PA_MIXER", "AUX_PGA_L_INV Switch", "AUX_PGA_Left"},
{"LINEOUT2_PA_MIXER", "AUX_PGA_R_INV Switch", "AUX_PGA_Right"},
{"LINEOUT3_PA_MIXER", "AUX_PGA_L Switch", "AUX_PGA_Left"},
{"LINEOUT3_PA_MIXER", "AUX_PGA_R Switch", "AUX_PGA_Right"},
{"LINEOUT3_PA_MIXER", "AUX_PGA_L_INV Switch", "AUX_PGA_Left"},
{"LINEOUT3_PA_MIXER", "AUX_PGA_R_INV Switch", "AUX_PGA_Right"},
{"LINEOUT4_PA_MIXER", "AUX_PGA_L Switch", "AUX_PGA_Left"},
{"LINEOUT4_PA_MIXER", "AUX_PGA_R Switch", "AUX_PGA_Right"},
{"LINEOUT4_PA_MIXER", "AUX_PGA_L_INV Switch", "AUX_PGA_Left"},
{"LINEOUT4_PA_MIXER", "AUX_PGA_R_INV Switch", "AUX_PGA_Right"},
{"LINEOUT5_PA_MIXER", "AUX_PGA_L Switch", "AUX_PGA_Left"},
{"LINEOUT5_PA_MIXER", "AUX_PGA_R Switch", "AUX_PGA_Right"},
{"LINEOUT5_PA_MIXER", "AUX_PGA_L_INV Switch", "AUX_PGA_Left"},
{"LINEOUT5_PA_MIXER", "AUX_PGA_R_INV Switch", "AUX_PGA_Right"},
{"EAR_PA_MIXER", "AUX_PGA_L Switch", "AUX_PGA_Left"},
{"EAR_PA_MIXER", "AUX_PGA_R Switch", "AUX_PGA_Right"},
{"EAR_PA_MIXER", "AUX_PGA_L_INV Switch", "AUX_PGA_Left"},
{"EAR_PA_MIXER", "AUX_PGA_R_INV Switch", "AUX_PGA_Right"},
{"AUX_PGA_Left", NULL, "AMIC5"},
{"AUX_PGA_Right", NULL, "AMIC6"},
{"IIR1", NULL, "IIR1 INP1 MUX"},
{"IIR1 INP1 MUX", "DEC1", "DEC1 MUX"},
{"IIR1 INP1 MUX", "DEC2", "DEC2 MUX"},
{"IIR1 INP1 MUX", "DEC3", "DEC3 MUX"},
{"IIR1 INP1 MUX", "DEC4", "DEC4 MUX"},
{"IIR1 INP1 MUX", "DEC5", "DEC5 MUX"},
{"IIR1 INP1 MUX", "DEC6", "DEC6 MUX"},
{"IIR1 INP1 MUX", "DEC7", "DEC7 MUX"},
{"IIR1 INP1 MUX", "DEC8", "DEC8 MUX"},
{"IIR1 INP1 MUX", "DEC9", "DEC9 MUX"},
{"IIR1 INP1 MUX", "DEC10", "DEC10 MUX"},
{"IIR2", NULL, "IIR2 INP1 MUX"},
{"IIR2 INP1 MUX", "DEC1", "DEC1 MUX"},
{"IIR2 INP1 MUX", "DEC2", "DEC2 MUX"},
{"IIR2 INP1 MUX", "DEC3", "DEC3 MUX"},
{"IIR2 INP1 MUX", "DEC4", "DEC4 MUX"},
{"IIR2 INP1 MUX", "DEC5", "DEC5 MUX"},
{"IIR2 INP1 MUX", "DEC6", "DEC6 MUX"},
{"IIR2 INP1 MUX", "DEC7", "DEC7 MUX"},
{"IIR2 INP1 MUX", "DEC8", "DEC8 MUX"},
{"IIR2 INP1 MUX", "DEC9", "DEC9 MUX"},
{"IIR2 INP1 MUX", "DEC10", "DEC10 MUX"},
{"MIC BIAS1 Internal1", NULL, "LDO_H"},
{"MIC BIAS1 Internal2", NULL, "LDO_H"},
{"MIC BIAS1 External", NULL, "LDO_H"},
{"MIC BIAS2 Internal1", NULL, "LDO_H"},
{"MIC BIAS2 Internal2", NULL, "LDO_H"},
{"MIC BIAS2 Internal3", NULL, "LDO_H"},
{"MIC BIAS2 External", NULL, "LDO_H"},
{"MIC BIAS3 Internal1", NULL, "LDO_H"},
{"MIC BIAS3 Internal2", NULL, "LDO_H"},
{"MIC BIAS3 External", NULL, "LDO_H"},
{"MIC BIAS4 External", NULL, "LDO_H"},
};
static const struct snd_soc_dapm_route tabla_1_x_lineout_2_to_4_map[] = {
{"RX4 DSM MUX", "DSM_INV", "RX3 MIX2"},
{"RX4 DSM MUX", "CIC_OUT", "RX4 MIX1"},
{"LINEOUT2 DAC", NULL, "RX4 DSM MUX"},
{"LINEOUT3 DAC", NULL, "RX5 MIX1"},
{"LINEOUT3 DAC GROUND", "Switch", "RX3 MIX2"},
{"LINEOUT3 DAC", NULL, "LINEOUT3 DAC GROUND"},
{"RX6 DSM MUX", "DSM_INV", "RX5 MIX1"},
{"RX6 DSM MUX", "CIC_OUT", "RX6 MIX1"},
{"LINEOUT4 DAC", NULL, "RX6 DSM MUX"},
{"LINEOUT4 DAC GROUND", "Switch", "RX4 DSM MUX"},
{"LINEOUT4 DAC", NULL, "LINEOUT4 DAC GROUND"},
};
static const struct snd_soc_dapm_route tabla_2_x_lineout_2_to_4_map[] = {
{"RX4 DSM MUX", "DSM_INV", "RX3 MIX2"},
{"RX4 DSM MUX", "CIC_OUT", "RX4 MIX1"},
{"LINEOUT3 DAC", NULL, "RX4 DSM MUX"},
{"LINEOUT2 DAC", NULL, "RX5 MIX1"},
{"RX6 DSM MUX", "DSM_INV", "RX5 MIX1"},
{"RX6 DSM MUX", "CIC_OUT", "RX6 MIX1"},
{"LINEOUT4 DAC", NULL, "RX6 DSM MUX"},
};
static int tabla_readable(struct snd_soc_codec *ssc, unsigned int reg)
{
int i;
struct wcd9xxx *tabla_core = dev_get_drvdata(ssc->dev->parent);
if (TABLA_IS_1_X(tabla_core->version)) {
for (i = 0; i < ARRAY_SIZE(tabla_1_reg_readable); i++) {
if (tabla_1_reg_readable[i] == reg)
return 1;
}
} else {
for (i = 0; i < ARRAY_SIZE(tabla_2_reg_readable); i++) {
if (tabla_2_reg_readable[i] == reg)
return 1;
}
}
return tabla_reg_readable[reg];
}
static bool tabla_is_digital_gain_register(unsigned int reg)
{
bool rtn = false;
switch (reg) {
case TABLA_A_CDC_RX1_VOL_CTL_B2_CTL:
case TABLA_A_CDC_RX2_VOL_CTL_B2_CTL:
case TABLA_A_CDC_RX3_VOL_CTL_B2_CTL:
case TABLA_A_CDC_RX4_VOL_CTL_B2_CTL:
case TABLA_A_CDC_RX5_VOL_CTL_B2_CTL:
case TABLA_A_CDC_RX6_VOL_CTL_B2_CTL:
case TABLA_A_CDC_RX7_VOL_CTL_B2_CTL:
case TABLA_A_CDC_TX1_VOL_CTL_GAIN:
case TABLA_A_CDC_TX2_VOL_CTL_GAIN:
case TABLA_A_CDC_TX3_VOL_CTL_GAIN:
case TABLA_A_CDC_TX4_VOL_CTL_GAIN:
case TABLA_A_CDC_TX5_VOL_CTL_GAIN:
case TABLA_A_CDC_TX6_VOL_CTL_GAIN:
case TABLA_A_CDC_TX7_VOL_CTL_GAIN:
case TABLA_A_CDC_TX8_VOL_CTL_GAIN:
case TABLA_A_CDC_TX9_VOL_CTL_GAIN:
case TABLA_A_CDC_TX10_VOL_CTL_GAIN:
rtn = true;
break;
default:
break;
}
return rtn;
}
static int tabla_volatile(struct snd_soc_codec *ssc, unsigned int reg)
{
/* Registers lower than 0x100 are top level registers which can be
* written by the Tabla core driver.
*/
if ((reg >= TABLA_A_CDC_MBHC_EN_CTL) || (reg < 0x100))
return 1;
/* IIR Coeff registers are not cacheable */
if ((reg >= TABLA_A_CDC_IIR1_COEF_B1_CTL) &&
(reg <= TABLA_A_CDC_IIR2_COEF_B5_CTL))
return 1;
/* ANC filter registers are not cacheable */
if ((reg >= TABLA_A_CDC_ANC1_FILT1_B1_CTL) &&
(reg <= TABLA_A_CDC_ANC1_FILT2_B3_CTL))
return 1;
if ((reg >= TABLA_A_CDC_ANC2_FILT1_B1_CTL) &&
(reg <= TABLA_A_CDC_ANC2_FILT2_B3_CTL))
return 1;
/* Digital gain register is not cacheable so we have to write
* the setting even it is the same
*/
if (tabla_is_digital_gain_register(reg))
return 1;
/* HPH status registers */
if (reg == TABLA_A_RX_HPH_L_STATUS || reg == TABLA_A_RX_HPH_R_STATUS)
return 1;
if (reg == TABLA_A_CDC_COMP1_SHUT_DOWN_STATUS ||
reg == TABLA_A_CDC_COMP2_SHUT_DOWN_STATUS)
return 1;
return 0;
}
#define TABLA_FORMATS (SNDRV_PCM_FMTBIT_S16_LE)
static int tabla_write(struct snd_soc_codec *codec, unsigned int reg,
unsigned int value)
{
int ret;
if (reg == SND_SOC_NOPM)
return 0;
BUG_ON(reg > TABLA_MAX_REGISTER);
if (!tabla_volatile(codec, reg)) {
ret = snd_soc_cache_write(codec, reg, value);
if (ret != 0)
dev_err(codec->dev, "Cache write to %x failed: %d\n",
reg, ret);
}
return wcd9xxx_reg_write(codec->control_data, reg, value);
}
static unsigned int tabla_read(struct snd_soc_codec *codec,
unsigned int reg)
{
unsigned int val;
int ret;
if (reg == SND_SOC_NOPM)
return 0;
BUG_ON(reg > TABLA_MAX_REGISTER);
if (!tabla_volatile(codec, reg) && tabla_readable(codec, reg) &&
reg < codec->driver->reg_cache_size) {
ret = snd_soc_cache_read(codec, reg, &val);
if (ret >= 0) {
return val;
} else
dev_err(codec->dev, "Cache read from %x failed: %d\n",
reg, ret);
}
val = wcd9xxx_reg_read(codec->control_data, reg);
return val;
}
static s16 tabla_get_current_v_ins(struct tabla_priv *tabla, bool hu)
{
s16 v_ins;
if ((tabla->mbhc_data.micb_mv != VDDIO_MICBIAS_MV) &&
tabla->mbhc_micbias_switched)
v_ins = hu ? (s16)tabla->mbhc_data.adj_v_ins_hu :
(s16)tabla->mbhc_data.adj_v_ins_h;
else
v_ins = hu ? (s16)tabla->mbhc_data.v_ins_hu :
(s16)tabla->mbhc_data.v_ins_h;
return v_ins;
}
static s16 tabla_get_current_v_hs_max(struct tabla_priv *tabla)
{
s16 v_hs_max;
struct tabla_mbhc_plug_type_cfg *plug_type;
plug_type = TABLA_MBHC_CAL_PLUG_TYPE_PTR(tabla->mbhc_cfg.calibration);
if ((tabla->mbhc_data.micb_mv != VDDIO_MICBIAS_MV) &&
tabla->mbhc_micbias_switched)
v_hs_max = tabla->mbhc_data.adj_v_hs_max;
else
v_hs_max = plug_type->v_hs_max;
return v_hs_max;
}
static void tabla_codec_calibrate_rel(struct snd_soc_codec *codec)
{
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
snd_soc_write(codec, TABLA_A_CDC_MBHC_VOLT_B3_CTL,
tabla->mbhc_data.v_b1_hu & 0xFF);
snd_soc_write(codec, TABLA_A_CDC_MBHC_VOLT_B4_CTL,
(tabla->mbhc_data.v_b1_hu >> 8) & 0xFF);
snd_soc_write(codec, TABLA_A_CDC_MBHC_VOLT_B5_CTL,
tabla->mbhc_data.v_b1_h & 0xFF);
snd_soc_write(codec, TABLA_A_CDC_MBHC_VOLT_B6_CTL,
(tabla->mbhc_data.v_b1_h >> 8) & 0xFF);
snd_soc_write(codec, TABLA_A_CDC_MBHC_VOLT_B9_CTL,
tabla->mbhc_data.v_brh & 0xFF);
snd_soc_write(codec, TABLA_A_CDC_MBHC_VOLT_B10_CTL,
(tabla->mbhc_data.v_brh >> 8) & 0xFF);
snd_soc_write(codec, TABLA_A_CDC_MBHC_VOLT_B11_CTL,
tabla->mbhc_data.v_brl & 0xFF);
snd_soc_write(codec, TABLA_A_CDC_MBHC_VOLT_B12_CTL,
(tabla->mbhc_data.v_brl >> 8) & 0xFF);
}
static void tabla_codec_calibrate_hs_polling(struct snd_soc_codec *codec)
{
u8 *n_ready, *n_cic;
struct tabla_mbhc_btn_detect_cfg *btn_det;
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
const s16 v_ins_hu = tabla_get_current_v_ins(tabla, true);
btn_det = TABLA_MBHC_CAL_BTN_DET_PTR(tabla->mbhc_cfg.calibration);
snd_soc_write(codec, TABLA_A_CDC_MBHC_VOLT_B1_CTL,
v_ins_hu & 0xFF);
snd_soc_write(codec, TABLA_A_CDC_MBHC_VOLT_B2_CTL,
(v_ins_hu >> 8) & 0xFF);
tabla_codec_calibrate_rel(codec);
n_ready = tabla_mbhc_cal_btn_det_mp(btn_det, TABLA_BTN_DET_N_READY);
snd_soc_write(codec, TABLA_A_CDC_MBHC_TIMER_B1_CTL,
n_ready[tabla_codec_mclk_index(tabla)]);
snd_soc_write(codec, TABLA_A_CDC_MBHC_TIMER_B2_CTL,
tabla->mbhc_data.npoll);
snd_soc_write(codec, TABLA_A_CDC_MBHC_TIMER_B3_CTL,
tabla->mbhc_data.nbounce_wait);
n_cic = tabla_mbhc_cal_btn_det_mp(btn_det, TABLA_BTN_DET_N_CIC);
snd_soc_write(codec, TABLA_A_CDC_MBHC_TIMER_B6_CTL,
n_cic[tabla_codec_mclk_index(tabla)]);
}
static int tabla_startup(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct wcd9xxx *tabla_core = dev_get_drvdata(dai->codec->dev->parent);
pr_debug("%s(): substream = %s stream = %d\n" , __func__,
substream->name, substream->stream);
if ((tabla_core != NULL) &&
(tabla_core->dev != NULL) &&
(tabla_core->dev->parent != NULL))
pm_runtime_get_sync(tabla_core->dev->parent);
return 0;
}
static void tabla_shutdown(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct wcd9xxx *tabla_core = dev_get_drvdata(dai->codec->dev->parent);
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(dai->codec);
u32 active = 0;
pr_debug("%s(): substream = %s stream = %d\n" , __func__,
substream->name, substream->stream);
if (tabla->intf_type != WCD9XXX_INTERFACE_TYPE_SLIMBUS)
return;
if (dai->id <= NUM_CODEC_DAIS) {
if (tabla->dai[dai->id].ch_mask) {
active = 1;
pr_debug("%s(): Codec DAI: chmask[%d] = 0x%lx\n",
__func__, dai->id, tabla->dai[dai->id].ch_mask);
}
}
if ((tabla_core != NULL) &&
(tabla_core->dev != NULL) &&
(tabla_core->dev->parent != NULL) &&
(active == 0)) {
pm_runtime_mark_last_busy(tabla_core->dev->parent);
pm_runtime_put(tabla_core->dev->parent);
}
}
int tabla_mclk_enable(struct snd_soc_codec *codec, int mclk_enable, bool dapm)
{
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
pr_debug("%s: mclk_enable = %u, dapm = %d\n", __func__, mclk_enable,
dapm);
if (dapm)
TABLA_ACQUIRE_LOCK(tabla->codec_resource_lock);
if (mclk_enable) {
tabla->mclk_enabled = true;
if (tabla->mbhc_polling_active) {
tabla_codec_pause_hs_polling(codec);
tabla_codec_disable_clock_block(codec);
tabla_codec_enable_bandgap(codec,
TABLA_BANDGAP_AUDIO_MODE);
tabla_codec_enable_clock_block(codec, 0);
tabla_codec_calibrate_hs_polling(codec);
tabla_codec_start_hs_polling(codec);
} else {
tabla_codec_disable_clock_block(codec);
tabla_codec_enable_bandgap(codec,
TABLA_BANDGAP_AUDIO_MODE);
tabla_codec_enable_clock_block(codec, 0);
}
} else {
if (!tabla->mclk_enabled) {
if (dapm)
TABLA_RELEASE_LOCK(tabla->codec_resource_lock);
pr_err("Error, MCLK already diabled\n");
return -EINVAL;
}
tabla->mclk_enabled = false;
if (tabla->mbhc_polling_active) {
tabla_codec_pause_hs_polling(codec);
tabla_codec_disable_clock_block(codec);
tabla_codec_enable_bandgap(codec,
TABLA_BANDGAP_MBHC_MODE);
tabla_enable_rx_bias(codec, 1);
tabla_codec_enable_clock_block(codec, 1);
tabla_codec_calibrate_hs_polling(codec);
tabla_codec_start_hs_polling(codec);
snd_soc_update_bits(codec, TABLA_A_CLK_BUFF_EN1,
0x05, 0x01);
} else {
tabla_codec_disable_clock_block(codec);
tabla_codec_enable_bandgap(codec,
TABLA_BANDGAP_OFF);
}
}
if (dapm)
TABLA_RELEASE_LOCK(tabla->codec_resource_lock);
return 0;
}
static int tabla_set_dai_sysclk(struct snd_soc_dai *dai,
int clk_id, unsigned int freq, int dir)
{
pr_debug("%s\n", __func__);
return 0;
}
static int tabla_set_dai_fmt(struct snd_soc_dai *dai, unsigned int fmt)
{
u8 val = 0;
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(dai->codec);
pr_debug("%s\n", __func__);
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBS_CFS:
/* CPU is master */
if (tabla->intf_type == WCD9XXX_INTERFACE_TYPE_I2C) {
if (dai->id == AIF1_CAP)
snd_soc_update_bits(dai->codec,
TABLA_A_CDC_CLK_TX_I2S_CTL,
TABLA_I2S_MASTER_MODE_MASK, 0);
else if (dai->id == AIF1_PB)
snd_soc_update_bits(dai->codec,
TABLA_A_CDC_CLK_RX_I2S_CTL,
TABLA_I2S_MASTER_MODE_MASK, 0);
}
break;
case SND_SOC_DAIFMT_CBM_CFM:
/* CPU is slave */
if (tabla->intf_type == WCD9XXX_INTERFACE_TYPE_I2C) {
val = TABLA_I2S_MASTER_MODE_MASK;
if (dai->id == AIF1_CAP)
snd_soc_update_bits(dai->codec,
TABLA_A_CDC_CLK_TX_I2S_CTL, val, val);
else if (dai->id == AIF1_PB)
snd_soc_update_bits(dai->codec,
TABLA_A_CDC_CLK_RX_I2S_CTL, val, val);
}
break;
default:
return -EINVAL;
}
return 0;
}
static int tabla_set_channel_map(struct snd_soc_dai *dai,
unsigned int tx_num, unsigned int *tx_slot,
unsigned int rx_num, unsigned int *rx_slot)
{
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(dai->codec);
struct wcd9xxx *core = dev_get_drvdata(dai->codec->dev->parent);
if (!tx_slot && !rx_slot) {
pr_err("%s: Invalid\n", __func__);
return -EINVAL;
}
pr_debug("%s(): dai_name = %s DAI-ID %x tx_ch %d rx_ch %d\n"
"tabla->intf_type %d\n",
__func__, dai->name, dai->id, tx_num, rx_num,
tabla->intf_type);
if (tabla->intf_type == WCD9XXX_INTERFACE_TYPE_SLIMBUS)
wcd9xxx_init_slimslave(core, core->slim->laddr,
tx_num, tx_slot, rx_num, rx_slot);
return 0;
}
static int tabla_get_channel_map(struct snd_soc_dai *dai,
unsigned int *tx_num, unsigned int *tx_slot,
unsigned int *rx_num, unsigned int *rx_slot)
{
struct tabla_priv *tabla_p = snd_soc_codec_get_drvdata(dai->codec);
u32 i = 0;
struct wcd9xxx_ch *ch;
switch (dai->id) {
case AIF1_PB:
case AIF2_PB:
case AIF3_PB:
if (!rx_slot || !rx_num) {
pr_err("%s: Invalid rx_slot %d or rx_num %d\n",
__func__, (u32) rx_slot, (u32) rx_num);
return -EINVAL;
}
list_for_each_entry(ch, &tabla_p->dai[dai->id].wcd9xxx_ch_list,
list) {
rx_slot[i++] = ch->ch_num;
}
*rx_num = i;
break;
case AIF1_CAP:
case AIF2_CAP:
case AIF3_CAP:
if (!tx_slot || !tx_num) {
pr_err("%s: Invalid tx_slot %d or tx_num %d\n",
__func__, (u32) tx_slot, (u32) tx_num);
return -EINVAL;
}
list_for_each_entry(ch, &tabla_p->dai[dai->id].wcd9xxx_ch_list,
list) {
tx_slot[i++] = ch->ch_num;
}
*tx_num = i;
break;
default:
pr_err("%s: Invalid DAI ID %x\n", __func__, dai->id);
break;
}
return 0;
}
static int tabla_set_interpolator_rate(struct snd_soc_dai *dai,
u8 rx_fs_rate_reg_val,
u32 compander_fs,
u32 sample_rate)
{
u32 j;
u8 rx_mix1_inp;
u16 rx_mix_1_reg_1, rx_mix_1_reg_2;
u16 rx_fs_reg;
u8 rx_mix_1_reg_1_val, rx_mix_1_reg_2_val;
struct snd_soc_codec *codec = dai->codec;
struct wcd9xxx_ch *ch;
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
list_for_each_entry(ch, &tabla->dai[dai->id].wcd9xxx_ch_list, list) {
rx_mix1_inp = ch->port - RX_MIX1_INP_SEL_RX1;
if ((rx_mix1_inp < RX_MIX1_INP_SEL_RX1) ||
(rx_mix1_inp > RX_MIX1_INP_SEL_RX7)) {
pr_err("%s: Invalid TABLA_RX%u port. Dai ID is %d\n",
__func__, rx_mix1_inp - 5 , dai->id);
return -EINVAL;
}
rx_mix_1_reg_1 = TABLA_A_CDC_CONN_RX1_B1_CTL;
for (j = 0; j < NUM_INTERPOLATORS; j++) {
rx_mix_1_reg_2 = rx_mix_1_reg_1 + 1;
rx_mix_1_reg_1_val = snd_soc_read(codec,
rx_mix_1_reg_1);
rx_mix_1_reg_2_val = snd_soc_read(codec,
rx_mix_1_reg_2);
if (((rx_mix_1_reg_1_val & 0x0F) == rx_mix1_inp) ||
(((rx_mix_1_reg_1_val >> 4) & 0x0F) == rx_mix1_inp) ||
((rx_mix_1_reg_2_val & 0x0F) == rx_mix1_inp)) {
rx_fs_reg = TABLA_A_CDC_RX1_B5_CTL + 8 * j;
pr_debug("%s: AIF_PB DAI(%d) connected to RX%u\n",
__func__, dai->id, j + 1);
pr_debug("%s: set RX%u sample rate to %u\n",
__func__, j + 1, sample_rate);
snd_soc_update_bits(codec, rx_fs_reg,
0xE0, rx_fs_rate_reg_val);
if (comp_rx_path[j] < COMPANDER_MAX)
tabla->comp_fs[comp_rx_path[j]]
= compander_fs;
}
if (j <= 2)
rx_mix_1_reg_1 += 3;
else
rx_mix_1_reg_1 += 2;
}
}
return 0;
}
static int tabla_set_decimator_rate(struct snd_soc_dai *dai,
u8 tx_fs_rate_reg_val,
u32 sample_rate)
{
struct snd_soc_codec *codec = dai->codec;
struct wcd9xxx_ch *ch;
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
u32 tx_port;
u16 tx_port_reg, tx_fs_reg;
u8 tx_port_reg_val;
s8 decimator;
list_for_each_entry(ch, &tabla->dai[dai->id].wcd9xxx_ch_list, list) {
tx_port = ch->port + 1;
pr_debug("%s: dai->id = %d, tx_port = %d",
__func__, dai->id, tx_port);
if ((tx_port < 1) || (tx_port > NUM_DECIMATORS)) {
pr_err("%s: Invalid SLIM TX%u port. DAI ID is %d\n",
__func__, tx_port, dai->id);
return -EINVAL;
}
tx_port_reg = TABLA_A_CDC_CONN_TX_SB_B1_CTL + (tx_port - 1);
tx_port_reg_val = snd_soc_read(codec, tx_port_reg);
decimator = 0;
if ((tx_port >= 1) && (tx_port <= 6)) {
tx_port_reg_val = tx_port_reg_val & 0x0F;
if (tx_port_reg_val == 0x8)
decimator = tx_port;
} else if ((tx_port >= 7) && (tx_port <= NUM_DECIMATORS)) {
tx_port_reg_val = tx_port_reg_val & 0x1F;
if ((tx_port_reg_val >= 0x8) &&
(tx_port_reg_val <= 0x11)) {
decimator = (tx_port_reg_val - 0x8) + 1;
}
}
if (decimator) { /* SLIM_TX port has a DEC as input */
tx_fs_reg = TABLA_A_CDC_TX1_CLK_FS_CTL +
8 * (decimator - 1);
pr_debug("%s: set DEC%u (-> SLIM_TX%u) rate to %u\n",
__func__, decimator, tx_port, sample_rate);
snd_soc_update_bits(codec, tx_fs_reg, 0x07,
tx_fs_rate_reg_val);
} else {
if ((tx_port_reg_val >= 0x1) &&
(tx_port_reg_val <= 0x7)) {
pr_debug("%s: RMIX%u going to SLIM TX%u\n",
__func__, tx_port_reg_val, tx_port);
} else if ((tx_port_reg_val >= 0x8) &&
(tx_port_reg_val <= 0x11)) {
pr_err("%s: ERROR: Should not be here\n",
__func__);
pr_err("%s: ERROR: DEC connected to SLIM TX%u\n",
__func__, tx_port);
return -EINVAL;
} else if (tx_port_reg_val == 0) {
pr_debug("%s: no signal to SLIM TX%u\n",
__func__, tx_port);
} else {
pr_err("%s: ERROR: wrong signal to SLIM TX%u\n",
__func__, tx_port);
pr_err("%s: ERROR: wrong signal = %u\n",
__func__, tx_port_reg_val);
return -EINVAL;
}
}
}
return 0;
}
static int tabla_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct snd_soc_codec *codec = dai->codec;
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(dai->codec);
u8 tx_fs_rate_reg_val, rx_fs_rate_reg_val;
u32 compander_fs;
int ret;
pr_debug("%s: dai_name = %s DAI-ID %x rate %d num_ch %d\n", __func__,
dai->name, dai->id, params_rate(params),
params_channels(params));
switch (params_rate(params)) {
case 8000:
tx_fs_rate_reg_val = 0x00;
rx_fs_rate_reg_val = 0x00;
compander_fs = COMPANDER_FS_8KHZ;
break;
case 16000:
tx_fs_rate_reg_val = 0x01;
rx_fs_rate_reg_val = 0x20;
compander_fs = COMPANDER_FS_16KHZ;
break;
case 32000:
tx_fs_rate_reg_val = 0x02;
rx_fs_rate_reg_val = 0x40;
compander_fs = COMPANDER_FS_32KHZ;
break;
case 48000:
tx_fs_rate_reg_val = 0x03;
rx_fs_rate_reg_val = 0x60;
compander_fs = COMPANDER_FS_48KHZ;
break;
case 96000:
tx_fs_rate_reg_val = 0x04;
rx_fs_rate_reg_val = 0x80;
compander_fs = COMPANDER_FS_96KHZ;
break;
case 192000:
tx_fs_rate_reg_val = 0x05;
rx_fs_rate_reg_val = 0xA0;
compander_fs = COMPANDER_FS_192KHZ;
break;
default:
pr_err("%s: Invalid sampling rate %d\n", __func__,
params_rate(params));
return -EINVAL;
}
switch (substream->stream) {
case SNDRV_PCM_STREAM_CAPTURE:
ret = tabla_set_decimator_rate(dai, tx_fs_rate_reg_val,
params_rate(params));
if (ret < 0) {
pr_err("%s: set decimator rate failed %d\n", __func__,
ret);
return ret;
}
if (tabla->intf_type == WCD9XXX_INTERFACE_TYPE_I2C) {
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S16_LE:
snd_soc_update_bits(codec,
TABLA_A_CDC_CLK_TX_I2S_CTL, 0x20, 0x20);
break;
case SNDRV_PCM_FORMAT_S32_LE:
snd_soc_update_bits(codec,
TABLA_A_CDC_CLK_TX_I2S_CTL, 0x20, 0x00);
break;
default:
pr_err("%s: Invalid format %d\n", __func__,
params_format(params));
return -EINVAL;
}
snd_soc_update_bits(codec, TABLA_A_CDC_CLK_TX_I2S_CTL,
0x07, tx_fs_rate_reg_val);
} else {
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S16_LE:
tabla->dai[dai->id].bit_width = 16;
break;
default:
pr_err("%s: Invalid TX format %d\n", __func__,
params_format(params));
return -EINVAL;
}
tabla->dai[dai->id].rate = params_rate(params);
}
break;
case SNDRV_PCM_STREAM_PLAYBACK:
ret = tabla_set_interpolator_rate(dai, rx_fs_rate_reg_val,
compander_fs,
params_rate(params));
if (ret < 0) {
pr_err("%s: set decimator rate failed %d\n", __func__,
ret);
return ret;
}
if (tabla->intf_type == WCD9XXX_INTERFACE_TYPE_I2C) {
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S16_LE:
snd_soc_update_bits(codec,
TABLA_A_CDC_CLK_RX_I2S_CTL, 0x20, 0x20);
break;
case SNDRV_PCM_FORMAT_S32_LE:
snd_soc_update_bits(codec,
TABLA_A_CDC_CLK_RX_I2S_CTL, 0x20, 0x00);
break;
default:
pr_err("%s: Invalid RX format %d\n", __func__,
params_format(params));
return -EINVAL;
}
snd_soc_update_bits(codec, TABLA_A_CDC_CLK_RX_I2S_CTL,
0x03, (rx_fs_rate_reg_val >> 0x05));
} else {
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S16_LE:
tabla->dai[dai->id].bit_width = 16;
break;
default:
pr_err("%s: Invalid format %d\n", __func__,
params_format(params));
return -EINVAL;
}
tabla->dai[dai->id].rate = params_rate(params);
}
break;
default:
pr_err("%s: Invalid stream type %d\n", __func__,
substream->stream);
return -EINVAL;
}
return 0;
}
static struct snd_soc_dai_ops tabla_dai_ops = {
.startup = tabla_startup,
.shutdown = tabla_shutdown,
.hw_params = tabla_hw_params,
.set_sysclk = tabla_set_dai_sysclk,
.set_fmt = tabla_set_dai_fmt,
.set_channel_map = tabla_set_channel_map,
.get_channel_map = tabla_get_channel_map,
};
static struct snd_soc_dai_driver tabla_dai[] = {
{
.name = "tabla_rx1",
.id = AIF1_PB,
.playback = {
.stream_name = "AIF1 Playback",
.rates = WCD9310_RATES,
.formats = TABLA_FORMATS,
.rate_max = 192000,
.rate_min = 8000,
.channels_min = 1,
.channels_max = 2,
},
.ops = &tabla_dai_ops,
},
{
.name = "tabla_tx1",
.id = AIF1_CAP,
.capture = {
.stream_name = "AIF1 Capture",
.rates = WCD9310_RATES,
.formats = TABLA_FORMATS,
.rate_max = 192000,
.rate_min = 8000,
.channels_min = 1,
.channels_max = 4,
},
.ops = &tabla_dai_ops,
},
{
.name = "tabla_rx2",
.id = AIF2_PB,
.playback = {
.stream_name = "AIF2 Playback",
.rates = WCD9310_RATES,
.formats = TABLA_FORMATS,
.rate_min = 8000,
.rate_max = 192000,
.channels_min = 1,
.channels_max = 2,
},
.ops = &tabla_dai_ops,
},
{
.name = "tabla_tx2",
.id = AIF2_CAP,
.capture = {
.stream_name = "AIF2 Capture",
.rates = WCD9310_RATES,
.formats = TABLA_FORMATS,
.rate_max = 192000,
.rate_min = 8000,
.channels_min = 1,
.channels_max = 4,
},
.ops = &tabla_dai_ops,
},
{
.name = "tabla_rx3",
.id = AIF3_PB,
.playback = {
.stream_name = "AIF3 Playback",
.rates = WCD9310_RATES,
.formats = TABLA_FORMATS,
.rate_min = 8000,
.rate_max = 192000,
.channels_min = 1,
.channels_max = 2,
},
.ops = &tabla_dai_ops,
},
{
.name = "tabla_tx3",
.id = AIF3_CAP,
.capture = {
.stream_name = "AIF3 Capture",
.rates = WCD9310_RATES,
.formats = TABLA_FORMATS,
.rate_max = 48000,
.rate_min = 8000,
.channels_min = 1,
.channels_max = 2,
},
.ops = &tabla_dai_ops,
},
};
static struct snd_soc_dai_driver tabla_i2s_dai[] = {
{
.name = "tabla_i2s_rx1",
.id = AIF1_PB,
.playback = {
.stream_name = "AIF1 Playback",
.rates = WCD9310_RATES,
.formats = TABLA_FORMATS,
.rate_max = 192000,
.rate_min = 8000,
.channels_min = 1,
.channels_max = 4,
},
.ops = &tabla_dai_ops,
},
{
.name = "tabla_i2s_tx1",
.id = AIF1_CAP,
.capture = {
.stream_name = "AIF1 Capture",
.rates = WCD9310_RATES,
.formats = TABLA_FORMATS,
.rate_max = 192000,
.rate_min = 8000,
.channels_min = 1,
.channels_max = 4,
},
.ops = &tabla_dai_ops,
},
};
static int tabla_codec_enable_chmask(struct tabla_priv *tabla_p,
int event, int index)
{
int ret = 0;
struct wcd9xxx_ch *ch;
switch (event) {
case SND_SOC_DAPM_POST_PMU:
list_for_each_entry(ch,
&tabla_p->dai[index].wcd9xxx_ch_list, list) {
ret = wcd9xxx_get_slave_port(ch->ch_num);
if (ret < 0) {
pr_err("%s: Invalid slave port ID: %d\n",
__func__, ret);
ret = -EINVAL;
break;
}
tabla_p->dai[index].ch_mask |= 1 << ret;
}
break;
case SND_SOC_DAPM_POST_PMD:
ret = wait_event_timeout(tabla_p->dai[index].dai_wait,
(tabla_p->dai[index].ch_mask == 0),
msecs_to_jiffies(SLIM_CLOSE_TIMEOUT));
if (!ret) {
pr_err("%s: Slim close tx/rx wait timeout\n",
__func__);
ret = -EINVAL;
}
break;
}
return ret;
}
static int tabla_codec_enable_slimrx(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol,
int event)
{
struct wcd9xxx *core;
struct snd_soc_codec *codec = w->codec;
struct tabla_priv *tabla_p = snd_soc_codec_get_drvdata(codec);
u32 ret = 0;
struct wcd9xxx_codec_dai_data *dai;
core = dev_get_drvdata(codec->dev->parent);
pr_debug("%s: event called! codec name %s num_dai %d\n"
"stream name %s event %d\n",
__func__, w->codec->name, w->codec->num_dai,
w->sname, event);
/* Execute the callback only if interface type is slimbus */
if (tabla_p->intf_type != WCD9XXX_INTERFACE_TYPE_SLIMBUS) {
if (event == SND_SOC_DAPM_POST_PMD && (core != NULL) &&
(core->dev != NULL) &&
(core->dev->parent != NULL)) {
pm_runtime_mark_last_busy(core->dev->parent);
pm_runtime_put(core->dev->parent);
}
return 0;
}
pr_debug("%s: w->name %s w->shift %d event %d\n",
__func__, w->name, w->shift, event);
dai = &tabla_p->dai[w->shift];
switch (event) {
case SND_SOC_DAPM_POST_PMU:
ret = tabla_codec_enable_chmask(tabla_p, SND_SOC_DAPM_POST_PMU,
w->shift);
ret = wcd9xxx_cfg_slim_sch_rx(core, &dai->wcd9xxx_ch_list,
dai->rate, dai->bit_width,
&dai->grph);
break;
case SND_SOC_DAPM_POST_PMD:
ret = wcd9xxx_close_slim_sch_rx(core,
&dai->wcd9xxx_ch_list,
dai->grph);
ret = tabla_codec_enable_chmask(tabla_p, SND_SOC_DAPM_POST_PMD,
w->shift);
if (ret < 0) {
ret = wcd9xxx_disconnect_port(core,
&dai->wcd9xxx_ch_list,
dai->grph);
pr_info("%s: Disconnect RX port, ret = %d\n",
__func__, ret);
}
if ((core != NULL) &&
(core->dev != NULL) &&
(core->dev->parent != NULL)) {
pm_runtime_mark_last_busy(core->dev->parent);
pm_runtime_put(core->dev->parent);
}
break;
}
return ret;
}
static int tabla_codec_enable_slimtx(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol,
int event)
{
struct wcd9xxx *core;
struct snd_soc_codec *codec = w->codec;
struct tabla_priv *tabla_p = snd_soc_codec_get_drvdata(codec);
u32 ret = 0;
struct wcd9xxx_codec_dai_data *dai;
core = dev_get_drvdata(codec->dev->parent);
pr_debug("%s: event called! codec name %s num_dai %d\n"
"stream name %s\n", __func__, w->codec->name,
w->codec->num_dai, w->sname);
/* Execute the callback only if interface type is slimbus */
if (tabla_p->intf_type != WCD9XXX_INTERFACE_TYPE_SLIMBUS) {
if (event == SND_SOC_DAPM_POST_PMD && (core != NULL) &&
(core->dev != NULL) &&
(core->dev->parent != NULL)) {
pm_runtime_mark_last_busy(core->dev->parent);
pm_runtime_put(core->dev->parent);
}
return 0;
}
pr_debug("%s(): %s %d\n", __func__, w->name, event);
dai = &tabla_p->dai[w->shift];
switch (event) {
case SND_SOC_DAPM_POST_PMU:
ret = tabla_codec_enable_chmask(tabla_p, SND_SOC_DAPM_POST_PMU,
w->shift);
ret = wcd9xxx_cfg_slim_sch_tx(core, &dai->wcd9xxx_ch_list,
dai->rate,
dai->bit_width,
&dai->grph);
break;
case SND_SOC_DAPM_POST_PMD:
ret = wcd9xxx_close_slim_sch_tx(core, &dai->wcd9xxx_ch_list,
dai->grph);
ret = tabla_codec_enable_chmask(tabla_p, SND_SOC_DAPM_POST_PMD,
w->shift);
if (ret < 0) {
ret = wcd9xxx_disconnect_port(core,
&dai->wcd9xxx_ch_list,
dai->grph);
pr_info("%s: Disconnect TX port, ret = %d\n",
__func__, ret);
}
if ((core != NULL) &&
(core->dev != NULL) &&
(core->dev->parent != NULL)) {
pm_runtime_mark_last_busy(core->dev->parent);
pm_runtime_put(core->dev->parent);
}
break;
}
return ret;
}
/* Todo: Have seperate dapm widgets for I2S and Slimbus.
* Might Need to have callbacks registered only for slimbus
*/
static const struct snd_soc_dapm_widget tabla_dapm_widgets[] = {
/*RX stuff */
SND_SOC_DAPM_OUTPUT("EAR"),
SND_SOC_DAPM_PGA_E("EAR PA", SND_SOC_NOPM, 0, 0, NULL,
0, tabla_ear_pa_event, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_PRE_PMD),
SND_SOC_DAPM_MIXER("DAC1", SND_SOC_NOPM, 0, 0, dac1_switch,
ARRAY_SIZE(dac1_switch)),
SND_SOC_DAPM_AIF_IN_E("AIF1 PB", "AIF1 Playback", 0, SND_SOC_NOPM,
AIF1_PB, 0, tabla_codec_enable_slimrx,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_AIF_IN_E("AIF2 PB", "AIF2 Playback", 0, SND_SOC_NOPM,
AIF2_PB, 0, tabla_codec_enable_slimrx,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_AIF_IN_E("AIF3 PB", "AIF3 Playback", 0, SND_SOC_NOPM,
AIF3_PB, 0, tabla_codec_enable_slimrx,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX("SLIM RX1 MUX", SND_SOC_NOPM, TABLA_RX1, 0,
&slim_rx_mux[TABLA_RX1]),
SND_SOC_DAPM_MUX("SLIM RX2 MUX", SND_SOC_NOPM, TABLA_RX2, 0,
&slim_rx_mux[TABLA_RX2]),
SND_SOC_DAPM_MUX("SLIM RX3 MUX", SND_SOC_NOPM, TABLA_RX3, 0,
&slim_rx_mux[TABLA_RX3]),
SND_SOC_DAPM_MUX("SLIM RX4 MUX", SND_SOC_NOPM, TABLA_RX4, 0,
&slim_rx_mux[TABLA_RX4]),
SND_SOC_DAPM_MUX("SLIM RX5 MUX", SND_SOC_NOPM, TABLA_RX5, 0,
&slim_rx_mux[TABLA_RX5]),
SND_SOC_DAPM_MUX("SLIM RX6 MUX", SND_SOC_NOPM, TABLA_RX6, 0,
&slim_rx_mux[TABLA_RX6]),
SND_SOC_DAPM_MUX("SLIM RX7 MUX", SND_SOC_NOPM, TABLA_RX7, 0,
&slim_rx_mux[TABLA_RX7]),
SND_SOC_DAPM_MIXER("SLIM RX1", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("SLIM RX2", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("SLIM RX3", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("SLIM RX4", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("SLIM RX5", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("SLIM RX6", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("SLIM RX7", SND_SOC_NOPM, 0, 0, NULL, 0),
/* Headphone */
SND_SOC_DAPM_OUTPUT("HEADPHONE"),
SND_SOC_DAPM_PGA_E("HPHL", TABLA_A_RX_HPH_CNP_EN, 5, 0, NULL, 0,
tabla_hph_pa_event, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MIXER("HPHL DAC", TABLA_A_RX_HPH_L_DAC_CTL, 7, 0,
hphl_switch, ARRAY_SIZE(hphl_switch)),
SND_SOC_DAPM_PGA_E("HPHR", TABLA_A_RX_HPH_CNP_EN, 4, 0, NULL, 0,
tabla_hph_pa_event, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_DAC_E("HPHR DAC", NULL, TABLA_A_RX_HPH_R_DAC_CTL, 7, 0,
tabla_hphr_dac_event,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
/* Speaker */
SND_SOC_DAPM_OUTPUT("LINEOUT1"),
SND_SOC_DAPM_OUTPUT("LINEOUT2"),
SND_SOC_DAPM_OUTPUT("LINEOUT3"),
SND_SOC_DAPM_OUTPUT("LINEOUT4"),
SND_SOC_DAPM_OUTPUT("LINEOUT5"),
SND_SOC_DAPM_PGA_E("LINEOUT1 PA", TABLA_A_RX_LINE_CNP_EN, 0, 0, NULL,
0, tabla_codec_enable_lineout, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_PGA_E("LINEOUT2 PA", TABLA_A_RX_LINE_CNP_EN, 1, 0, NULL,
0, tabla_codec_enable_lineout, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_PGA_E("LINEOUT3 PA", TABLA_A_RX_LINE_CNP_EN, 2, 0, NULL,
0, tabla_codec_enable_lineout, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_PGA_E("LINEOUT4 PA", TABLA_A_RX_LINE_CNP_EN, 3, 0, NULL,
0, tabla_codec_enable_lineout, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_PGA_E("LINEOUT5 PA", TABLA_A_RX_LINE_CNP_EN, 4, 0, NULL, 0,
tabla_codec_enable_lineout, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_DAC_E("LINEOUT1 DAC", NULL, TABLA_A_RX_LINE_1_DAC_CTL, 7, 0
, tabla_lineout_dac_event,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_DAC_E("LINEOUT2 DAC", NULL, TABLA_A_RX_LINE_2_DAC_CTL, 7, 0
, tabla_lineout_dac_event,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_DAC_E("LINEOUT3 DAC", NULL, TABLA_A_RX_LINE_3_DAC_CTL, 7, 0
, tabla_lineout_dac_event,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_SWITCH("LINEOUT3 DAC GROUND", SND_SOC_NOPM, 0, 0,
&lineout3_ground_switch),
SND_SOC_DAPM_DAC_E("LINEOUT4 DAC", NULL, TABLA_A_RX_LINE_4_DAC_CTL, 7, 0
, tabla_lineout_dac_event,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_SWITCH("LINEOUT4 DAC GROUND", SND_SOC_NOPM, 0, 0,
&lineout4_ground_switch),
SND_SOC_DAPM_DAC_E("LINEOUT5 DAC", NULL, TABLA_A_RX_LINE_5_DAC_CTL, 7, 0
, tabla_lineout_dac_event,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MIXER_E("RX1 MIX2", TABLA_A_CDC_CLK_RX_B1_CTL, 0, 0, NULL,
0, tabla_codec_reset_interpolator, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_MIXER_E("RX2 MIX2", TABLA_A_CDC_CLK_RX_B1_CTL, 1, 0, NULL,
0, tabla_codec_reset_interpolator, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_MIXER_E("RX3 MIX2", TABLA_A_CDC_CLK_RX_B1_CTL, 2, 0, NULL,
0, tabla_codec_reset_interpolator, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_MIXER_E("RX4 MIX1", TABLA_A_CDC_CLK_RX_B1_CTL, 3, 0, NULL,
0, tabla_codec_reset_interpolator, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_MIXER_E("RX5 MIX1", TABLA_A_CDC_CLK_RX_B1_CTL, 4, 0, NULL,
0, tabla_codec_reset_interpolator, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_MIXER_E("RX6 MIX1", TABLA_A_CDC_CLK_RX_B1_CTL, 5, 0, NULL,
0, tabla_codec_reset_interpolator, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_MIXER_E("RX7 MIX1", TABLA_A_CDC_CLK_RX_B1_CTL, 6, 0, NULL,
0, tabla_codec_reset_interpolator, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_MIXER("RX1 MIX1", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("RX2 MIX1", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("RX3 MIX1", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MUX_E("RX4 DSM MUX", TABLA_A_CDC_CLK_RX_B1_CTL, 3, 0,
&rx4_dsm_mux, tabla_codec_reset_interpolator,
SND_SOC_DAPM_PRE_PMU),
SND_SOC_DAPM_MUX_E("RX6 DSM MUX", TABLA_A_CDC_CLK_RX_B1_CTL, 5, 0,
&rx6_dsm_mux, tabla_codec_reset_interpolator,
SND_SOC_DAPM_PRE_PMU),
SND_SOC_DAPM_MIXER_E("RX1 CHAIN", SND_SOC_NOPM, 5, 0, NULL,
0, tabla_codec_hphr_dem_input_selection,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_POST_PMD),
SND_SOC_DAPM_MIXER_E("RX2 CHAIN", SND_SOC_NOPM, 5, 0, NULL,
0, tabla_codec_hphl_dem_input_selection,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_POST_PMD),
SND_SOC_DAPM_MUX("RX1 MIX1 INP1", SND_SOC_NOPM, 0, 0,
&rx_mix1_inp1_mux),
SND_SOC_DAPM_MUX("RX1 MIX1 INP2", SND_SOC_NOPM, 0, 0,
&rx_mix1_inp2_mux),
SND_SOC_DAPM_MUX("RX1 MIX1 INP3", SND_SOC_NOPM, 0, 0,
&rx_mix1_inp3_mux),
SND_SOC_DAPM_MUX("RX2 MIX1 INP1", SND_SOC_NOPM, 0, 0,
&rx2_mix1_inp1_mux),
SND_SOC_DAPM_MUX("RX2 MIX1 INP2", SND_SOC_NOPM, 0, 0,
&rx2_mix1_inp2_mux),
SND_SOC_DAPM_MUX("RX3 MIX1 INP1", SND_SOC_NOPM, 0, 0,
&rx3_mix1_inp1_mux),
SND_SOC_DAPM_MUX("RX3 MIX1 INP2", SND_SOC_NOPM, 0, 0,
&rx3_mix1_inp2_mux),
SND_SOC_DAPM_MUX("RX4 MIX1 INP1", SND_SOC_NOPM, 0, 0,
&rx4_mix1_inp1_mux),
SND_SOC_DAPM_MUX("RX4 MIX1 INP2", SND_SOC_NOPM, 0, 0,
&rx4_mix1_inp2_mux),
SND_SOC_DAPM_MUX("RX5 MIX1 INP1", SND_SOC_NOPM, 0, 0,
&rx5_mix1_inp1_mux),
SND_SOC_DAPM_MUX("RX5 MIX1 INP2", SND_SOC_NOPM, 0, 0,
&rx5_mix1_inp2_mux),
SND_SOC_DAPM_MUX("RX6 MIX1 INP1", SND_SOC_NOPM, 0, 0,
&rx6_mix1_inp1_mux),
SND_SOC_DAPM_MUX("RX6 MIX1 INP2", SND_SOC_NOPM, 0, 0,
&rx6_mix1_inp2_mux),
SND_SOC_DAPM_MUX("RX7 MIX1 INP1", SND_SOC_NOPM, 0, 0,
&rx7_mix1_inp1_mux),
SND_SOC_DAPM_MUX("RX7 MIX1 INP2", SND_SOC_NOPM, 0, 0,
&rx7_mix1_inp2_mux),
SND_SOC_DAPM_MUX("RX1 MIX2 INP1", SND_SOC_NOPM, 0, 0,
&rx1_mix2_inp1_mux),
SND_SOC_DAPM_MUX("RX1 MIX2 INP2", SND_SOC_NOPM, 0, 0,
&rx1_mix2_inp2_mux),
SND_SOC_DAPM_MUX("RX2 MIX2 INP1", SND_SOC_NOPM, 0, 0,
&rx2_mix2_inp1_mux),
SND_SOC_DAPM_MUX("RX2 MIX2 INP2", SND_SOC_NOPM, 0, 0,
&rx2_mix2_inp2_mux),
SND_SOC_DAPM_MUX("RX3 MIX2 INP1", SND_SOC_NOPM, 0, 0,
&rx3_mix2_inp1_mux),
SND_SOC_DAPM_MUX("RX3 MIX2 INP2", SND_SOC_NOPM, 0, 0,
&rx3_mix2_inp2_mux),
SND_SOC_DAPM_SUPPLY("CP", TABLA_A_CP_EN, 0, 0,
tabla_codec_enable_charge_pump, SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD),
SND_SOC_DAPM_SUPPLY("RX_BIAS", SND_SOC_NOPM, 0, 0,
tabla_codec_enable_rx_bias, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
/* TX */
SND_SOC_DAPM_SUPPLY("CDC_CONN", TABLA_A_CDC_CLK_OTHR_CTL, 2, 0, NULL,
0),
SND_SOC_DAPM_SUPPLY("LDO_H", SND_SOC_NOPM, 0, 0,
tabla_codec_enable_ldo_h, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_SUPPLY("COMP1_CLK", SND_SOC_NOPM, 0, 0,
tabla_config_compander, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_POST_PMD),
SND_SOC_DAPM_SUPPLY("COMP2_CLK", SND_SOC_NOPM, 1, 0,
tabla_config_compander, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_POST_PMD),
SND_SOC_DAPM_INPUT("AMIC1"),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS1 External", SND_SOC_NOPM, 0, 0,
tabla_codec_enable_micbias, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS1 Internal1", SND_SOC_NOPM, 0, 0,
tabla_codec_enable_micbias, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS1 Internal2", SND_SOC_NOPM, 0, 0,
tabla_codec_enable_micbias, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("ADC1", NULL, TABLA_A_TX_1_2_EN, 7, 0,
tabla_codec_enable_adc, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_INPUT("AMIC3"),
SND_SOC_DAPM_ADC_E("ADC3", NULL, TABLA_A_TX_3_4_EN, 7, 0,
tabla_codec_enable_adc, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_INPUT("AMIC4"),
SND_SOC_DAPM_ADC_E("ADC4", NULL, TABLA_A_TX_3_4_EN, 3, 0,
tabla_codec_enable_adc, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_INPUT("AMIC5"),
SND_SOC_DAPM_ADC_E("ADC5", NULL, TABLA_A_TX_5_6_EN, 7, 0,
tabla_codec_enable_adc, SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_INPUT("AMIC6"),
SND_SOC_DAPM_ADC_E("ADC6", NULL, TABLA_A_TX_5_6_EN, 3, 0,
tabla_codec_enable_adc, SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_MUX_E("DEC1 MUX", TABLA_A_CDC_CLK_TX_CLK_EN_B1_CTL, 0, 0,
&dec1_mux, tabla_codec_enable_dec,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("DEC2 MUX", TABLA_A_CDC_CLK_TX_CLK_EN_B1_CTL, 1, 0,
&dec2_mux, tabla_codec_enable_dec,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("DEC3 MUX", TABLA_A_CDC_CLK_TX_CLK_EN_B1_CTL, 2, 0,
&dec3_mux, tabla_codec_enable_dec,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("DEC4 MUX", TABLA_A_CDC_CLK_TX_CLK_EN_B1_CTL, 3, 0,
&dec4_mux, tabla_codec_enable_dec,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("DEC5 MUX", TABLA_A_CDC_CLK_TX_CLK_EN_B1_CTL, 4, 0,
&dec5_mux, tabla_codec_enable_dec,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("DEC6 MUX", TABLA_A_CDC_CLK_TX_CLK_EN_B1_CTL, 5, 0,
&dec6_mux, tabla_codec_enable_dec,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("DEC7 MUX", TABLA_A_CDC_CLK_TX_CLK_EN_B1_CTL, 6, 0,
&dec7_mux, tabla_codec_enable_dec,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("DEC8 MUX", TABLA_A_CDC_CLK_TX_CLK_EN_B1_CTL, 7, 0,
&dec8_mux, tabla_codec_enable_dec,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("DEC9 MUX", TABLA_A_CDC_CLK_TX_CLK_EN_B2_CTL, 0, 0,
&dec9_mux, tabla_codec_enable_dec,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("DEC10 MUX", TABLA_A_CDC_CLK_TX_CLK_EN_B2_CTL, 1, 0,
&dec10_mux, tabla_codec_enable_dec,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX("ANC1 MUX", SND_SOC_NOPM, 0, 0, &anc1_mux),
SND_SOC_DAPM_MUX("ANC2 MUX", SND_SOC_NOPM, 0, 0, &anc2_mux),
SND_SOC_DAPM_OUTPUT("ANC HEADPHONE"),
SND_SOC_DAPM_PGA_E("ANC HPHL", SND_SOC_NOPM, 0, 0, NULL, 0,
tabla_codec_enable_anc,
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_PGA_E("ANC HPHR", SND_SOC_NOPM, 0, 0, NULL, 0,
tabla_codec_enable_anc, SND_SOC_DAPM_PRE_PMU),
SND_SOC_DAPM_MUX("ANC1 FB MUX", SND_SOC_NOPM, 0, 0, &anc1_fb_mux),
SND_SOC_DAPM_INPUT("AMIC2"),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS2 External", SND_SOC_NOPM, 0, 0,
tabla_codec_enable_micbias, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS2 Power External",
TABLA_A_MICB_2_CTL, 7, 0,
tabla_codec_enable_micbias_power,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS2 Internal1", SND_SOC_NOPM, 0, 0,
tabla_codec_enable_micbias, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS2 Internal2", SND_SOC_NOPM, 0, 0,
tabla_codec_enable_micbias, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS2 Internal3", SND_SOC_NOPM, 0, 0,
tabla_codec_enable_micbias, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS3 External", SND_SOC_NOPM, 0, 0,
tabla_codec_enable_micbias, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS3 Internal1", SND_SOC_NOPM, 0, 0,
tabla_codec_enable_micbias, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS3 Internal2", SND_SOC_NOPM, 0, 0,
tabla_codec_enable_micbias, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("ADC2", NULL, TABLA_A_TX_1_2_EN, 3, 0,
tabla_codec_enable_adc, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_AIF_OUT_E("AIF1 CAP", "AIF1 Capture", 0, SND_SOC_NOPM,
AIF1_CAP, 0, tabla_codec_enable_slimtx,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_AIF_OUT_E("AIF2 CAP", "AIF2 Capture", 0, SND_SOC_NOPM,
AIF2_CAP, 0, tabla_codec_enable_slimtx,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_AIF_OUT_E("AIF3 CAP", "AIF3 Capture", 0, SND_SOC_NOPM,
AIF3_CAP, 0, tabla_codec_enable_slimtx,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MIXER("AIF1_CAP Mixer", SND_SOC_NOPM, AIF1_CAP, 0,
aif_cap_mixer, ARRAY_SIZE(aif_cap_mixer)),
SND_SOC_DAPM_MIXER("AIF2_CAP Mixer", SND_SOC_NOPM, AIF2_CAP, 0,
aif_cap_mixer, ARRAY_SIZE(aif_cap_mixer)),
SND_SOC_DAPM_MIXER("AIF3_CAP Mixer", SND_SOC_NOPM, AIF3_CAP, 0,
aif_cap_mixer, ARRAY_SIZE(aif_cap_mixer)),
SND_SOC_DAPM_MUX("SLIM TX1 MUX", SND_SOC_NOPM, TABLA_TX1, 0,
&sb_tx1_mux),
SND_SOC_DAPM_MUX("SLIM TX2 MUX", SND_SOC_NOPM, TABLA_TX2, 0,
&sb_tx2_mux),
SND_SOC_DAPM_MUX("SLIM TX3 MUX", SND_SOC_NOPM, TABLA_TX3, 0,
&sb_tx3_mux),
SND_SOC_DAPM_MUX("SLIM TX4 MUX", SND_SOC_NOPM, TABLA_TX4, 0,
&sb_tx4_mux),
SND_SOC_DAPM_MUX("SLIM TX5 MUX", SND_SOC_NOPM, TABLA_TX5, 0,
&sb_tx5_mux),
SND_SOC_DAPM_MUX("SLIM TX6 MUX", SND_SOC_NOPM, TABLA_TX6, 0,
&sb_tx6_mux),
SND_SOC_DAPM_MUX("SLIM TX7 MUX", SND_SOC_NOPM, TABLA_TX7, 0,
&sb_tx7_mux),
SND_SOC_DAPM_MUX("SLIM TX8 MUX", SND_SOC_NOPM, TABLA_TX8, 0,
&sb_tx8_mux),
SND_SOC_DAPM_MUX("SLIM TX9 MUX", SND_SOC_NOPM, TABLA_TX9, 0,
&sb_tx9_mux),
SND_SOC_DAPM_MUX("SLIM TX10 MUX", SND_SOC_NOPM, TABLA_TX10, 0,
&sb_tx10_mux),
/* Digital Mic Inputs */
SND_SOC_DAPM_ADC_E("DMIC1", NULL, SND_SOC_NOPM, 0, 0,
tabla_codec_enable_dmic, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("DMIC2", NULL, SND_SOC_NOPM, 0, 0,
tabla_codec_enable_dmic, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("DMIC3", NULL, SND_SOC_NOPM, 0, 0,
tabla_codec_enable_dmic, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("DMIC4", NULL, SND_SOC_NOPM, 0, 0,
tabla_codec_enable_dmic, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("DMIC5", NULL, SND_SOC_NOPM, 0, 0,
tabla_codec_enable_dmic, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("DMIC6", NULL, SND_SOC_NOPM, 0, 0,
tabla_codec_enable_dmic, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
/* Sidetone */
SND_SOC_DAPM_MUX("IIR1 INP1 MUX", SND_SOC_NOPM, 0, 0, &iir1_inp1_mux),
SND_SOC_DAPM_PGA("IIR1", TABLA_A_CDC_CLK_SD_CTL, 0, 0, NULL, 0),
SND_SOC_DAPM_MUX("IIR2 INP1 MUX", SND_SOC_NOPM, 0, 0, &iir2_inp1_mux),
SND_SOC_DAPM_PGA("IIR2", TABLA_A_CDC_CLK_SD_CTL, 1, 0, NULL, 0),
/* AUX PGA */
SND_SOC_DAPM_ADC_E("AUX_PGA_Left", NULL, TABLA_A_AUX_L_EN, 7, 0,
tabla_codec_enable_aux_pga, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_PMD |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("AUX_PGA_Right", NULL, TABLA_A_AUX_R_EN, 7, 0,
tabla_codec_enable_aux_pga, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_PMD |
SND_SOC_DAPM_POST_PMD),
/* Lineout, ear and HPH PA Mixers */
SND_SOC_DAPM_MIXER("HPHL_PA_MIXER", SND_SOC_NOPM, 0, 0,
hphl_pa_mix, ARRAY_SIZE(hphl_pa_mix)),
SND_SOC_DAPM_MIXER("HPHR_PA_MIXER", SND_SOC_NOPM, 0, 0,
hphr_pa_mix, ARRAY_SIZE(hphr_pa_mix)),
SND_SOC_DAPM_MIXER("LINEOUT1_PA_MIXER", SND_SOC_NOPM, 0, 0,
lineout1_pa_mix, ARRAY_SIZE(lineout1_pa_mix)),
SND_SOC_DAPM_MIXER("LINEOUT2_PA_MIXER", SND_SOC_NOPM, 0, 0,
lineout2_pa_mix, ARRAY_SIZE(lineout2_pa_mix)),
SND_SOC_DAPM_MIXER("LINEOUT3_PA_MIXER", SND_SOC_NOPM, 0, 0,
lineout3_pa_mix, ARRAY_SIZE(lineout3_pa_mix)),
SND_SOC_DAPM_MIXER("LINEOUT4_PA_MIXER", SND_SOC_NOPM, 0, 0,
lineout4_pa_mix, ARRAY_SIZE(lineout4_pa_mix)),
SND_SOC_DAPM_MIXER("LINEOUT5_PA_MIXER", SND_SOC_NOPM, 0, 0,
lineout5_pa_mix, ARRAY_SIZE(lineout5_pa_mix)),
SND_SOC_DAPM_MIXER("EAR_PA_MIXER", SND_SOC_NOPM, 0, 0,
ear_pa_mix, ARRAY_SIZE(ear_pa_mix)),
};
static short tabla_codec_read_sta_result(struct snd_soc_codec *codec)
{
u8 bias_msb, bias_lsb;
short bias_value;
bias_msb = snd_soc_read(codec, TABLA_A_CDC_MBHC_B3_STATUS);
bias_lsb = snd_soc_read(codec, TABLA_A_CDC_MBHC_B2_STATUS);
bias_value = (bias_msb << 8) | bias_lsb;
return bias_value;
}
static short tabla_codec_read_dce_result(struct snd_soc_codec *codec)
{
u8 bias_msb, bias_lsb;
short bias_value;
bias_msb = snd_soc_read(codec, TABLA_A_CDC_MBHC_B5_STATUS);
bias_lsb = snd_soc_read(codec, TABLA_A_CDC_MBHC_B4_STATUS);
bias_value = (bias_msb << 8) | bias_lsb;
return bias_value;
}
static void tabla_turn_onoff_rel_detection(struct snd_soc_codec *codec, bool on)
{
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_B1_CTL, 0x02, on << 1);
}
static short __tabla_codec_sta_dce(struct snd_soc_codec *codec, int dce,
bool override_bypass, bool noreldetection)
{
short bias_value;
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
wcd9xxx_disable_irq(codec->control_data, WCD9XXX_IRQ_MBHC_POTENTIAL);
if (noreldetection)
tabla_turn_onoff_rel_detection(codec, false);
/* Turn on the override */
if (!override_bypass)
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_B1_CTL, 0x4, 0x4);
if (dce) {
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_CLK_CTL, 0x8, 0x8);
snd_soc_write(codec, TABLA_A_CDC_MBHC_EN_CTL, 0x4);
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_CLK_CTL, 0x8, 0x0);
usleep_range(tabla->mbhc_data.t_sta_dce,
tabla->mbhc_data.t_sta_dce);
snd_soc_write(codec, TABLA_A_CDC_MBHC_EN_CTL, 0x4);
usleep_range(tabla->mbhc_data.t_dce,
tabla->mbhc_data.t_dce);
bias_value = tabla_codec_read_dce_result(codec);
} else {
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_CLK_CTL, 0x8, 0x8);
snd_soc_write(codec, TABLA_A_CDC_MBHC_EN_CTL, 0x2);
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_CLK_CTL, 0x8, 0x0);
usleep_range(tabla->mbhc_data.t_sta_dce,
tabla->mbhc_data.t_sta_dce);
snd_soc_write(codec, TABLA_A_CDC_MBHC_EN_CTL, 0x2);
usleep_range(tabla->mbhc_data.t_sta,
tabla->mbhc_data.t_sta);
bias_value = tabla_codec_read_sta_result(codec);
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_CLK_CTL, 0x8, 0x8);
snd_soc_write(codec, TABLA_A_CDC_MBHC_EN_CTL, 0x0);
}
/* Turn off the override after measuring mic voltage */
if (!override_bypass)
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_B1_CTL, 0x04, 0x00);
if (noreldetection)
tabla_turn_onoff_rel_detection(codec, true);
wcd9xxx_enable_irq(codec->control_data, WCD9XXX_IRQ_MBHC_POTENTIAL);
return bias_value;
}
static short tabla_codec_sta_dce(struct snd_soc_codec *codec, int dce,
bool norel)
{
return __tabla_codec_sta_dce(codec, dce, false, norel);
}
/* called only from interrupt which is under codec_resource_lock acquisition */
static short tabla_codec_setup_hs_polling(struct snd_soc_codec *codec)
{
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
short bias_value;
u8 cfilt_mode = 0;
pr_debug("%s: enter, mclk_enabled %d\n", __func__, tabla->mclk_enabled);
if (!tabla->mbhc_cfg.calibration) {
pr_err("Error, no tabla calibration\n");
return -ENODEV;
}
if (!tabla->mclk_enabled) {
tabla_codec_disable_clock_block(codec);
tabla_codec_enable_bandgap(codec, TABLA_BANDGAP_MBHC_MODE);
tabla_enable_rx_bias(codec, 1);
tabla_codec_enable_clock_block(codec, 1);
}
snd_soc_update_bits(codec, TABLA_A_CLK_BUFF_EN1, 0x05, 0x01);
if (!tabla->mbhc_cfg.micbias_always_on) {
/* Make sure CFILT is in fast mode, save current mode */
cfilt_mode = snd_soc_read(codec,
tabla->mbhc_bias_regs.cfilt_ctl);
snd_soc_update_bits(codec, tabla->mbhc_bias_regs.cfilt_ctl,
0x70, 0x00);
}
snd_soc_update_bits(codec, tabla->mbhc_bias_regs.ctl_reg, 0x1F, 0x16);
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_CLK_CTL, 0x2, 0x2);
snd_soc_write(codec, TABLA_A_MBHC_SCALING_MUX_1, 0x84);
snd_soc_update_bits(codec, TABLA_A_TX_7_MBHC_EN, 0x80, 0x80);
snd_soc_update_bits(codec, TABLA_A_TX_7_MBHC_EN, 0x1F, 0x1C);
snd_soc_update_bits(codec, TABLA_A_TX_7_MBHC_TEST_CTL, 0x40, 0x40);
snd_soc_update_bits(codec, TABLA_A_TX_7_MBHC_EN, 0x80, 0x00);
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_CLK_CTL, 0x8, 0x8);
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_CLK_CTL, 0x8, 0x00);
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_B1_CTL, 0x2, 0x2);
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_CLK_CTL, 0x8, 0x8);
tabla_codec_calibrate_hs_polling(codec);
/* don't flip override */
bias_value = __tabla_codec_sta_dce(codec, 1, true, true);
if (!tabla->mbhc_cfg.micbias_always_on)
snd_soc_update_bits(codec, tabla->mbhc_bias_regs.cfilt_ctl,
0x40, cfilt_mode);
snd_soc_update_bits(codec, TABLA_A_MBHC_HPH, 0x13, 0x00);
return bias_value;
}
static int tabla_cancel_btn_work(struct tabla_priv *tabla)
{
int r = 0;
struct wcd9xxx *core = dev_get_drvdata(tabla->codec->dev->parent);
struct wcd9xxx_core_resource *core_res = &core->core_res;
if (cancel_delayed_work_sync(&tabla->mbhc_btn_dwork)) {
/* if scheduled mbhc_btn_dwork is canceled from here,
* we have to unlock from here instead btn_work */
wcd9xxx_unlock_sleep(core_res);
r = 1;
}
return r;
}
/* called under codec_resource_lock acquisition */
void tabla_set_and_turnoff_hph_padac(struct snd_soc_codec *codec)
{
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
u8 wg_time;
wg_time = snd_soc_read(codec, TABLA_A_RX_HPH_CNP_WG_TIME) ;
wg_time += 1;
/* If headphone PA is on, check if userspace receives
* removal event to sync-up PA's state */
if (tabla_is_hph_pa_on(codec)) {
pr_debug("%s PA is on, setting PA_OFF_ACK\n", __func__);
set_bit(TABLA_HPHL_PA_OFF_ACK, &tabla->hph_pa_dac_state);
set_bit(TABLA_HPHR_PA_OFF_ACK, &tabla->hph_pa_dac_state);
} else {
pr_debug("%s PA is off\n", __func__);
}
if (tabla_is_hph_dac_on(codec, 1))
set_bit(TABLA_HPHL_DAC_OFF_ACK, &tabla->hph_pa_dac_state);
if (tabla_is_hph_dac_on(codec, 0))
set_bit(TABLA_HPHR_DAC_OFF_ACK, &tabla->hph_pa_dac_state);
snd_soc_update_bits(codec, TABLA_A_RX_HPH_CNP_EN, 0x30, 0x00);
snd_soc_update_bits(codec, TABLA_A_RX_HPH_L_DAC_CTL,
0x80, 0x00);
snd_soc_update_bits(codec, TABLA_A_RX_HPH_R_DAC_CTL,
0xC0, 0x00);
usleep_range(wg_time * 1000, wg_time * 1000);
}
static void tabla_clr_and_turnon_hph_padac(struct tabla_priv *tabla)
{
bool pa_turned_on = false;
struct snd_soc_codec *codec = tabla->codec;
u8 wg_time;
wg_time = snd_soc_read(codec, TABLA_A_RX_HPH_CNP_WG_TIME) ;
wg_time += 1;
if (test_and_clear_bit(TABLA_HPHR_DAC_OFF_ACK,
&tabla->hph_pa_dac_state)) {
pr_debug("%s: HPHR clear flag and enable DAC\n", __func__);
snd_soc_update_bits(tabla->codec, TABLA_A_RX_HPH_R_DAC_CTL,
0xC0, 0xC0);
}
if (test_and_clear_bit(TABLA_HPHL_DAC_OFF_ACK,
&tabla->hph_pa_dac_state)) {
pr_debug("%s: HPHL clear flag and enable DAC\n", __func__);
snd_soc_update_bits(tabla->codec, TABLA_A_RX_HPH_L_DAC_CTL,
0xC0, 0xC0);
}
if (test_and_clear_bit(TABLA_HPHR_PA_OFF_ACK,
&tabla->hph_pa_dac_state)) {
pr_debug("%s: HPHR clear flag and enable PA\n", __func__);
snd_soc_update_bits(tabla->codec, TABLA_A_RX_HPH_CNP_EN, 0x10,
1 << 4);
pa_turned_on = true;
}
if (test_and_clear_bit(TABLA_HPHL_PA_OFF_ACK,
&tabla->hph_pa_dac_state)) {
pr_debug("%s: HPHL clear flag and enable PA\n", __func__);
snd_soc_update_bits(tabla->codec, TABLA_A_RX_HPH_CNP_EN, 0x20,
1 << 5);
pa_turned_on = true;
}
if (pa_turned_on) {
pr_debug("%s: PA was turned off by MBHC and not by DAPM\n",
__func__);
usleep_range(wg_time * 1000, wg_time * 1000);
}
}
/* called under codec_resource_lock acquisition */
static void tabla_codec_enable_mbhc_micbias(struct snd_soc_codec *codec,
bool enable)
{
int r;
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
if (!tabla->mbhc_cfg.micbias_always_on)
return;
if (enable) {
TABLA_RELEASE_LOCK(tabla->codec_resource_lock);
tabla_codec_update_cfilt_usage(codec,
tabla->mbhc_bias_regs.cfilt_sel, 1);
r = snd_soc_dapm_force_enable_pin(&codec->dapm,
"MIC BIAS2 Power External");
snd_soc_dapm_sync(&codec->dapm);
TABLA_ACQUIRE_LOCK(tabla->codec_resource_lock);
pr_debug("%s: Turning on MICBIAS2 r %d\n", __func__, r);
} else {
TABLA_RELEASE_LOCK(tabla->codec_resource_lock);
r = snd_soc_dapm_disable_pin(&codec->dapm,
"MIC BIAS2 Power External");
snd_soc_dapm_sync(&codec->dapm);
tabla_codec_update_cfilt_usage(codec,
tabla->mbhc_bias_regs.cfilt_sel, 0);
TABLA_ACQUIRE_LOCK(tabla->codec_resource_lock);
pr_debug("%s: Turning off MICBIAS2 r %d\n", __func__, r);
}
}
/* called under codec_resource_lock acquisition */
static void tabla_codec_report_plug(struct snd_soc_codec *codec, int insertion,
enum snd_jack_types jack_type)
{
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
pr_debug("%s: enter insertion %d hph_status %x\n",
__func__, insertion, tabla->hph_status);
if (!insertion) {
/* Report removal */
tabla->hph_status &= ~jack_type;
if (tabla->mbhc_cfg.headset_jack) {
/* cancel possibly scheduled btn work and
* report release if we reported button press */
if (tabla_cancel_btn_work(tabla)) {
pr_debug("%s: button press is canceled\n",
__func__);
} else if (tabla->buttons_pressed) {
pr_debug("%s: Reporting release for reported "
"button press %d\n", __func__,
jack_type);
tabla_snd_soc_jack_report(tabla,
tabla->mbhc_cfg.button_jack, 0,
tabla->buttons_pressed);
tabla->buttons_pressed &=
~TABLA_JACK_BUTTON_MASK;
}
if (jack_type == SND_JACK_HEADSET)
tabla_codec_enable_mbhc_micbias(codec, false);
pr_debug("%s: Reporting removal %d(%x)\n", __func__,
jack_type, tabla->hph_status);
tabla_snd_soc_jack_report(tabla,
tabla->mbhc_cfg.headset_jack,
tabla->hph_status,
TABLA_JACK_MASK);
}
tabla_set_and_turnoff_hph_padac(codec);
hphocp_off_report(tabla, SND_JACK_OC_HPHR,
WCD9XXX_IRQ_HPH_PA_OCPR_FAULT);
hphocp_off_report(tabla, SND_JACK_OC_HPHL,
WCD9XXX_IRQ_HPH_PA_OCPL_FAULT);
tabla->current_plug = PLUG_TYPE_NONE;
tabla->mbhc_polling_active = false;
} else {
if (tabla->mbhc_cfg.detect_extn_cable) {
/* Report removal of current jack type */
if (tabla->hph_status != jack_type &&
tabla->mbhc_cfg.headset_jack) {
pr_debug("%s: Reporting removal (%x)\n",
__func__, tabla->hph_status);
tabla_snd_soc_jack_report(tabla,
tabla->mbhc_cfg.headset_jack,
0, TABLA_JACK_MASK);
tabla->hph_status = 0;
}
}
/* Report insertion */
tabla->hph_status |= jack_type;
if (jack_type == SND_JACK_HEADPHONE)
tabla->current_plug = PLUG_TYPE_HEADPHONE;
else if (jack_type == SND_JACK_UNSUPPORTED)
tabla->current_plug = PLUG_TYPE_GND_MIC_SWAP;
else if (jack_type == SND_JACK_HEADSET) {
tabla->mbhc_polling_active = true;
tabla->current_plug = PLUG_TYPE_HEADSET;
tabla_codec_enable_mbhc_micbias(codec, true);
} else if (jack_type == SND_JACK_LINEOUT)
tabla->current_plug = PLUG_TYPE_HIGH_HPH;
if (tabla->mbhc_cfg.headset_jack) {
pr_debug("%s: Reporting insertion %d(%x)\n", __func__,
jack_type, tabla->hph_status);
tabla_snd_soc_jack_report(tabla,
tabla->mbhc_cfg.headset_jack,
tabla->hph_status,
TABLA_JACK_MASK);
}
tabla_clr_and_turnon_hph_padac(tabla);
}
pr_debug("%s: leave hph_status %x\n", __func__, tabla->hph_status);
}
static int tabla_codec_enable_hs_detect(struct snd_soc_codec *codec,
int insertion, int trigger,
bool padac_off)
{
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
int central_bias_enabled = 0;
const struct tabla_mbhc_general_cfg *generic =
TABLA_MBHC_CAL_GENERAL_PTR(tabla->mbhc_cfg.calibration);
const struct tabla_mbhc_plug_detect_cfg *plug_det =
TABLA_MBHC_CAL_PLUG_DET_PTR(tabla->mbhc_cfg.calibration);
pr_debug("%s: enter insertion(%d) trigger(0x%x)\n",
__func__, insertion, trigger);
if (!tabla->mbhc_cfg.calibration) {
pr_err("Error, no tabla calibration\n");
return -EINVAL;
}
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_INT_CTL, 0x1, 0);
/* Make sure mic bias and Mic line schmitt trigger
* are turned OFF
*/
snd_soc_update_bits(codec, tabla->mbhc_bias_regs.ctl_reg, 0x01, 0x01);
snd_soc_update_bits(codec, tabla->mbhc_bias_regs.mbhc_reg, 0x90, 0x00);
if (insertion) {
pr_debug("%s: setup for insertion\n", __func__);
tabla_codec_switch_micbias(codec, 0);
/* DAPM can manipulate PA/DAC bits concurrently */
if (padac_off == true) {
tabla_set_and_turnoff_hph_padac(codec);
}
if (trigger & MBHC_USE_HPHL_TRIGGER) {
/* Enable HPH Schmitt Trigger */
snd_soc_update_bits(codec, TABLA_A_MBHC_HPH, 0x11,
0x11);
snd_soc_update_bits(codec, TABLA_A_MBHC_HPH, 0x0C,
plug_det->hph_current << 2);
snd_soc_update_bits(codec, TABLA_A_MBHC_HPH, 0x02,
0x02);
}
if (trigger & MBHC_USE_MB_TRIGGER) {
/* enable the mic line schmitt trigger */
snd_soc_update_bits(codec,
tabla->mbhc_bias_regs.mbhc_reg,
0x60, plug_det->mic_current << 5);
snd_soc_update_bits(codec,
tabla->mbhc_bias_regs.mbhc_reg,
0x80, 0x80);
usleep_range(plug_det->t_mic_pid, plug_det->t_mic_pid);
snd_soc_update_bits(codec,
tabla->mbhc_bias_regs.ctl_reg, 0x01,
0x00);
snd_soc_update_bits(codec,
tabla->mbhc_bias_regs.mbhc_reg,
0x10, 0x10);
}
/* setup for insetion detection */
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_INT_CTL, 0x2, 0);
} else {
pr_debug("setup for removal detection\n");
/* Make sure the HPH schmitt trigger is OFF */
snd_soc_update_bits(codec, TABLA_A_MBHC_HPH, 0x12, 0x00);
/* enable the mic line schmitt trigger */
snd_soc_update_bits(codec, tabla->mbhc_bias_regs.ctl_reg,
0x01, 0x00);
snd_soc_update_bits(codec, tabla->mbhc_bias_regs.mbhc_reg, 0x60,
plug_det->mic_current << 5);
snd_soc_update_bits(codec, tabla->mbhc_bias_regs.mbhc_reg,
0x80, 0x80);
usleep_range(plug_det->t_mic_pid, plug_det->t_mic_pid);
snd_soc_update_bits(codec, tabla->mbhc_bias_regs.mbhc_reg,
0x10, 0x10);
/* Setup for low power removal detection */
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_INT_CTL, 0x2, 0x2);
}
if (snd_soc_read(codec, TABLA_A_CDC_MBHC_B1_CTL) & 0x4) {
/* called called by interrupt */
if (!(tabla->clock_active)) {
tabla_codec_enable_config_mode(codec, 1);
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_B1_CTL,
0x06, 0);
usleep_range(generic->t_shutdown_plug_rem,
generic->t_shutdown_plug_rem);
tabla_codec_enable_config_mode(codec, 0);
} else
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_B1_CTL,
0x06, 0);
}
snd_soc_update_bits(codec, tabla->mbhc_bias_regs.int_rbias, 0x80, 0);
/* If central bandgap disabled */
if (!(snd_soc_read(codec, TABLA_A_PIN_CTL_OE1) & 1)) {
snd_soc_update_bits(codec, TABLA_A_PIN_CTL_OE1, 0x3, 0x3);
usleep_range(generic->t_bg_fast_settle,
generic->t_bg_fast_settle);
central_bias_enabled = 1;
}
/* If LDO_H disabled */
if (snd_soc_read(codec, TABLA_A_PIN_CTL_OE0) & 0x80) {
snd_soc_update_bits(codec, TABLA_A_PIN_CTL_OE0, 0x10, 0);
snd_soc_update_bits(codec, TABLA_A_PIN_CTL_OE0, 0x80, 0x80);
usleep_range(generic->t_ldoh, generic->t_ldoh);
snd_soc_update_bits(codec, TABLA_A_PIN_CTL_OE0, 0x80, 0);
if (central_bias_enabled)
snd_soc_update_bits(codec, TABLA_A_PIN_CTL_OE1, 0x1, 0);
}
snd_soc_update_bits(codec, tabla->reg_addr.micb_4_mbhc, 0x3,
tabla->mbhc_cfg.micbias);
wcd9xxx_enable_irq(codec->control_data, WCD9XXX_IRQ_MBHC_INSERTION);
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_INT_CTL, 0x1, 0x1);
pr_debug("%s: leave\n", __func__);
return 0;
}
static u16 tabla_codec_v_sta_dce(struct snd_soc_codec *codec, bool dce,
s16 vin_mv)
{
struct tabla_priv *tabla;
s16 diff, zero;
u32 mb_mv, in;
u16 value;
tabla = snd_soc_codec_get_drvdata(codec);
mb_mv = tabla->mbhc_data.micb_mv;
if (mb_mv == 0) {
pr_err("%s: Mic Bias voltage is set to zero\n", __func__);
return -EINVAL;
}
if (dce) {
diff = (tabla->mbhc_data.dce_mb) - (tabla->mbhc_data.dce_z);
zero = (tabla->mbhc_data.dce_z);
} else {
diff = (tabla->mbhc_data.sta_mb) - (tabla->mbhc_data.sta_z);
zero = (tabla->mbhc_data.sta_z);
}
in = (u32) diff * vin_mv;
value = (u16) (in / mb_mv) + zero;
return value;
}
static s32 tabla_codec_sta_dce_v(struct snd_soc_codec *codec, s8 dce,
u16 bias_value)
{
struct tabla_priv *tabla;
s16 value, z, mb;
s32 mv;
tabla = snd_soc_codec_get_drvdata(codec);
value = bias_value;
if (dce) {
z = (tabla->mbhc_data.dce_z);
mb = (tabla->mbhc_data.dce_mb);
mv = (value - z) * (s32)tabla->mbhc_data.micb_mv / (mb - z);
} else {
z = (tabla->mbhc_data.sta_z);
mb = (tabla->mbhc_data.sta_mb);
mv = (value - z) * (s32)tabla->mbhc_data.micb_mv / (mb - z);
}
return mv;
}
static void btn_lpress_fn(struct work_struct *work)
{
struct delayed_work *delayed_work;
struct tabla_priv *tabla;
short bias_value;
int dce_mv, sta_mv;
struct wcd9xxx *core;
struct wcd9xxx_core_resource *core_res;
pr_debug("%s:\n", __func__);
delayed_work = to_delayed_work(work);
tabla = container_of(delayed_work, struct tabla_priv, mbhc_btn_dwork);
core = dev_get_drvdata(tabla->codec->dev->parent);
core_res = &core->core_res;
if (tabla) {
if (tabla->mbhc_cfg.button_jack) {
bias_value = tabla_codec_read_sta_result(tabla->codec);
sta_mv = tabla_codec_sta_dce_v(tabla->codec, 0,
bias_value);
bias_value = tabla_codec_read_dce_result(tabla->codec);
dce_mv = tabla_codec_sta_dce_v(tabla->codec, 1,
bias_value);
pr_debug("%s: Reporting long button press event"
" STA: %d, DCE: %d\n", __func__,
sta_mv, dce_mv);
tabla_snd_soc_jack_report(tabla,
tabla->mbhc_cfg.button_jack,
tabla->buttons_pressed,
tabla->buttons_pressed);
}
} else {
pr_err("%s: Bad tabla private data\n", __func__);
}
pr_debug("%s: leave\n", __func__);
wcd9xxx_unlock_sleep(core_res);
}
static u16 tabla_get_cfilt_reg(struct snd_soc_codec *codec, u8 cfilt)
{
u16 reg;
switch (cfilt) {
case TABLA_CFILT1_SEL:
reg = TABLA_A_MICB_CFILT_1_CTL;
break;
case TABLA_CFILT2_SEL:
reg = TABLA_A_MICB_CFILT_2_CTL;
break;
case TABLA_CFILT3_SEL:
reg = TABLA_A_MICB_CFILT_3_CTL;
break;
default:
BUG();
}
return reg;
}
void tabla_mbhc_cal(struct snd_soc_codec *codec)
{
struct tabla_priv *tabla;
struct tabla_mbhc_btn_detect_cfg *btn_det;
u8 cfilt_mode, micbias2_cfilt_mode, bg_mode;
u8 ncic, nmeas, navg;
u32 mclk_rate;
u32 dce_wait, sta_wait;
u8 *n_cic;
void *calibration;
u16 bias2_ctl;
tabla = snd_soc_codec_get_drvdata(codec);
calibration = tabla->mbhc_cfg.calibration;
wcd9xxx_disable_irq(codec->control_data, WCD9XXX_IRQ_MBHC_POTENTIAL);
tabla_turn_onoff_rel_detection(codec, false);
/* First compute the DCE / STA wait times
* depending on tunable parameters.
* The value is computed in microseconds
*/
btn_det = TABLA_MBHC_CAL_BTN_DET_PTR(calibration);
n_cic = tabla_mbhc_cal_btn_det_mp(btn_det, TABLA_BTN_DET_N_CIC);
ncic = n_cic[tabla_codec_mclk_index(tabla)];
nmeas = TABLA_MBHC_CAL_BTN_DET_PTR(calibration)->n_meas;
navg = TABLA_MBHC_CAL_GENERAL_PTR(calibration)->mbhc_navg;
mclk_rate = tabla->mbhc_cfg.mclk_rate;
dce_wait = (1000 * 512 * ncic * (nmeas + 1)) / (mclk_rate / 1000);
sta_wait = (1000 * 128 * (navg + 1)) / (mclk_rate / 1000);
tabla->mbhc_data.t_dce = dce_wait;
tabla->mbhc_data.t_sta = sta_wait;
/* LDOH and CFILT are already configured during pdata handling.
* Only need to make sure CFILT and bandgap are in Fast mode.
* Need to restore defaults once calculation is done.
*/
cfilt_mode = snd_soc_read(codec, tabla->mbhc_bias_regs.cfilt_ctl);
micbias2_cfilt_mode =
snd_soc_read(codec, tabla_get_cfilt_reg(codec,
tabla->pdata->micbias.bias2_cfilt_sel));
snd_soc_update_bits(codec, tabla->mbhc_bias_regs.cfilt_ctl, 0x40,
TABLA_CFILT_FAST_MODE);
snd_soc_update_bits(codec,
tabla_get_cfilt_reg(codec,
tabla->pdata->micbias.bias2_cfilt_sel),
0x40, TABLA_CFILT_FAST_MODE);
bg_mode = snd_soc_update_bits(codec, TABLA_A_BIAS_CENTRAL_BG_CTL, 0x02,
0x02);
/* Micbias, CFILT, LDOH, MBHC MUX mode settings
* to perform ADC calibration
*/
snd_soc_update_bits(codec, tabla->mbhc_bias_regs.ctl_reg, 0x60,
tabla->mbhc_cfg.micbias << 5);
snd_soc_update_bits(codec, tabla->mbhc_bias_regs.ctl_reg, 0x01, 0x00);
snd_soc_update_bits(codec, TABLA_A_LDO_H_MODE_1, 0x60, 0x60);
snd_soc_write(codec, TABLA_A_TX_7_MBHC_TEST_CTL, 0x78);
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_B1_CTL, 0x04, 0x04);
/* MICBIAS2 routing for calibration */
bias2_ctl = snd_soc_read(codec, TABLA_A_MICB_2_CTL);
snd_soc_update_bits(codec, TABLA_A_MICB_1_MBHC, 0x03, TABLA_MICBIAS2);
snd_soc_write(codec, TABLA_A_MICB_2_CTL,
snd_soc_read(codec, tabla->mbhc_bias_regs.ctl_reg));
/* DCE measurement for 0 volts */
snd_soc_write(codec, TABLA_A_CDC_MBHC_CLK_CTL, 0x0A);
snd_soc_write(codec, TABLA_A_CDC_MBHC_EN_CTL, 0x04);
snd_soc_write(codec, TABLA_A_CDC_MBHC_CLK_CTL, 0x02);
snd_soc_write(codec, TABLA_A_MBHC_SCALING_MUX_1, 0x81);
usleep_range(100, 100);
snd_soc_write(codec, TABLA_A_CDC_MBHC_EN_CTL, 0x04);
usleep_range(tabla->mbhc_data.t_dce, tabla->mbhc_data.t_dce);
tabla->mbhc_data.dce_z = tabla_codec_read_dce_result(codec);
/* DCE measurment for MB voltage */
snd_soc_write(codec, TABLA_A_CDC_MBHC_CLK_CTL, 0x0A);
snd_soc_write(codec, TABLA_A_CDC_MBHC_CLK_CTL, 0x02);
snd_soc_write(codec, TABLA_A_MBHC_SCALING_MUX_1, 0x82);
usleep_range(100, 100);
snd_soc_write(codec, TABLA_A_CDC_MBHC_EN_CTL, 0x04);
usleep_range(tabla->mbhc_data.t_dce, tabla->mbhc_data.t_dce);
tabla->mbhc_data.dce_mb = tabla_codec_read_dce_result(codec);
/* Sta measuremnt for 0 volts */
snd_soc_write(codec, TABLA_A_CDC_MBHC_CLK_CTL, 0x0A);
snd_soc_write(codec, TABLA_A_CDC_MBHC_EN_CTL, 0x02);
snd_soc_write(codec, TABLA_A_CDC_MBHC_CLK_CTL, 0x02);
snd_soc_write(codec, TABLA_A_MBHC_SCALING_MUX_1, 0x81);
usleep_range(100, 100);
snd_soc_write(codec, TABLA_A_CDC_MBHC_EN_CTL, 0x02);
usleep_range(tabla->mbhc_data.t_sta, tabla->mbhc_data.t_sta);
tabla->mbhc_data.sta_z = tabla_codec_read_sta_result(codec);
/* STA Measurement for MB Voltage */
snd_soc_write(codec, TABLA_A_MBHC_SCALING_MUX_1, 0x82);
usleep_range(100, 100);
snd_soc_write(codec, TABLA_A_CDC_MBHC_EN_CTL, 0x02);
usleep_range(tabla->mbhc_data.t_sta, tabla->mbhc_data.t_sta);
tabla->mbhc_data.sta_mb = tabla_codec_read_sta_result(codec);
/* Restore default settings. */
snd_soc_write(codec, TABLA_A_MICB_2_CTL, bias2_ctl);
snd_soc_update_bits(codec, TABLA_A_MICB_1_MBHC, 0x03,
tabla->mbhc_cfg.micbias);
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_B1_CTL, 0x04, 0x00);
snd_soc_update_bits(codec,
tabla_get_cfilt_reg(codec,
tabla->pdata->micbias.bias2_cfilt_sel), 0x40,
micbias2_cfilt_mode);
snd_soc_update_bits(codec, tabla->mbhc_bias_regs.cfilt_ctl, 0x40,
cfilt_mode);
snd_soc_update_bits(codec, TABLA_A_BIAS_CENTRAL_BG_CTL, 0x02, bg_mode);
snd_soc_write(codec, TABLA_A_MBHC_SCALING_MUX_1, 0x84);
usleep_range(100, 100);
wcd9xxx_enable_irq(codec->control_data, WCD9XXX_IRQ_MBHC_POTENTIAL);
tabla_turn_onoff_rel_detection(codec, true);
}
void *tabla_mbhc_cal_btn_det_mp(const struct tabla_mbhc_btn_detect_cfg* btn_det,
const enum tabla_mbhc_btn_det_mem mem)
{
void *ret = &btn_det->_v_btn_low;
switch (mem) {
case TABLA_BTN_DET_GAIN:
ret += sizeof(btn_det->_n_cic);
case TABLA_BTN_DET_N_CIC:
ret += sizeof(btn_det->_n_ready);
case TABLA_BTN_DET_N_READY:
ret += sizeof(btn_det->_v_btn_high[0]) * btn_det->num_btn;
case TABLA_BTN_DET_V_BTN_HIGH:
ret += sizeof(btn_det->_v_btn_low[0]) * btn_det->num_btn;
case TABLA_BTN_DET_V_BTN_LOW:
/* do nothing */
break;
default:
ret = NULL;
}
return ret;
}
static s16 tabla_scale_v_micb_vddio(struct tabla_priv *tabla, int v,
bool tovddio)
{
int r;
int vddio_k, mb_k;
vddio_k = tabla_find_k_value(tabla->pdata->micbias.ldoh_v,
VDDIO_MICBIAS_MV);
mb_k = tabla_find_k_value(tabla->pdata->micbias.ldoh_v,
tabla->mbhc_data.micb_mv);
if (tovddio)
r = v * vddio_k / mb_k;
else
r = v * mb_k / vddio_k;
return r;
}
static void tabla_mbhc_calc_rel_thres(struct snd_soc_codec *codec, s16 mv)
{
s16 deltamv;
struct tabla_priv *tabla;
struct tabla_mbhc_btn_detect_cfg *btn_det;
tabla = snd_soc_codec_get_drvdata(codec);
btn_det = TABLA_MBHC_CAL_BTN_DET_PTR(tabla->mbhc_cfg.calibration);
tabla->mbhc_data.v_b1_h =
tabla_codec_v_sta_dce(codec, DCE,
mv + btn_det->v_btn_press_delta_cic);
tabla->mbhc_data.v_brh = tabla->mbhc_data.v_b1_h;
tabla->mbhc_data.v_brl = TABLA_MBHC_BUTTON_MIN;
deltamv = mv + btn_det->v_btn_press_delta_sta;
tabla->mbhc_data.v_b1_hu = tabla_codec_v_sta_dce(codec, STA, deltamv);
deltamv = mv + btn_det->v_btn_press_delta_cic;
tabla->mbhc_data.v_b1_huc = tabla_codec_v_sta_dce(codec, DCE, deltamv);
}
static void tabla_mbhc_set_rel_thres(struct snd_soc_codec *codec, s16 mv)
{
tabla_mbhc_calc_rel_thres(codec, mv);
tabla_codec_calibrate_rel(codec);
}
static s16 tabla_mbhc_highest_btn_mv(struct snd_soc_codec *codec)
{
struct tabla_priv *tabla;
struct tabla_mbhc_btn_detect_cfg *btn_det;
u16 *btn_high;
tabla = snd_soc_codec_get_drvdata(codec);
btn_det = TABLA_MBHC_CAL_BTN_DET_PTR(tabla->mbhc_cfg.calibration);
btn_high = tabla_mbhc_cal_btn_det_mp(btn_det, TABLA_BTN_DET_V_BTN_HIGH);
return btn_high[btn_det->num_btn - 1];
}
static void tabla_mbhc_calc_thres(struct snd_soc_codec *codec)
{
struct tabla_priv *tabla;
struct tabla_mbhc_btn_detect_cfg *btn_det;
struct tabla_mbhc_plug_type_cfg *plug_type;
u8 *n_ready;
tabla = snd_soc_codec_get_drvdata(codec);
btn_det = TABLA_MBHC_CAL_BTN_DET_PTR(tabla->mbhc_cfg.calibration);
plug_type = TABLA_MBHC_CAL_PLUG_TYPE_PTR(tabla->mbhc_cfg.calibration);
n_ready = tabla_mbhc_cal_btn_det_mp(btn_det, TABLA_BTN_DET_N_READY);
if (tabla->mbhc_cfg.mclk_rate == TABLA_MCLK_RATE_12288KHZ) {
tabla->mbhc_data.npoll = 4;
tabla->mbhc_data.nbounce_wait = 30;
} else if (tabla->mbhc_cfg.mclk_rate == TABLA_MCLK_RATE_9600KHZ) {
tabla->mbhc_data.npoll = 7;
tabla->mbhc_data.nbounce_wait = 23;
}
tabla->mbhc_data.t_sta_dce = ((1000 * 256) /
(tabla->mbhc_cfg.mclk_rate / 1000) *
n_ready[tabla_codec_mclk_index(tabla)]) +
10;
tabla->mbhc_data.v_ins_hu =
tabla_codec_v_sta_dce(codec, STA, plug_type->v_hs_max);
tabla->mbhc_data.v_ins_h =
tabla_codec_v_sta_dce(codec, DCE, plug_type->v_hs_max);
tabla->mbhc_data.v_inval_ins_low = TABLA_MBHC_FAKE_INSERT_LOW;
if (tabla->mbhc_cfg.gpio)
tabla->mbhc_data.v_inval_ins_high =
TABLA_MBHC_FAKE_INSERT_HIGH;
else
tabla->mbhc_data.v_inval_ins_high =
TABLA_MBHC_FAKE_INS_HIGH_NO_GPIO;
if (tabla->mbhc_data.micb_mv != VDDIO_MICBIAS_MV) {
tabla->mbhc_data.adj_v_hs_max =
tabla_scale_v_micb_vddio(tabla, plug_type->v_hs_max, true);
tabla->mbhc_data.adj_v_ins_hu =
tabla_codec_v_sta_dce(codec, STA,
tabla->mbhc_data.adj_v_hs_max);
tabla->mbhc_data.adj_v_ins_h =
tabla_codec_v_sta_dce(codec, DCE,
tabla->mbhc_data.adj_v_hs_max);
tabla->mbhc_data.v_inval_ins_low =
tabla_scale_v_micb_vddio(tabla,
tabla->mbhc_data.v_inval_ins_low,
false);
tabla->mbhc_data.v_inval_ins_high =
tabla_scale_v_micb_vddio(tabla,
tabla->mbhc_data.v_inval_ins_high,
false);
}
tabla_mbhc_calc_rel_thres(codec, tabla_mbhc_highest_btn_mv(codec));
tabla->mbhc_data.v_no_mic =
tabla_codec_v_sta_dce(codec, STA, plug_type->v_no_mic);
}
void tabla_mbhc_init(struct snd_soc_codec *codec)
{
struct tabla_priv *tabla;
struct tabla_mbhc_general_cfg *generic;
struct tabla_mbhc_btn_detect_cfg *btn_det;
int n;
u8 *n_cic, *gain;
struct wcd9xxx *tabla_core = dev_get_drvdata(codec->dev->parent);
tabla = snd_soc_codec_get_drvdata(codec);
generic = TABLA_MBHC_CAL_GENERAL_PTR(tabla->mbhc_cfg.calibration);
btn_det = TABLA_MBHC_CAL_BTN_DET_PTR(tabla->mbhc_cfg.calibration);
for (n = 0; n < 8; n++) {
if ((!TABLA_IS_1_X(tabla_core->version)) || n != 7) {
snd_soc_update_bits(codec,
TABLA_A_CDC_MBHC_FEATURE_B1_CFG,
0x07, n);
snd_soc_write(codec, TABLA_A_CDC_MBHC_FEATURE_B2_CFG,
btn_det->c[n]);
}
}
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_B2_CTL, 0x07,
btn_det->nc);
n_cic = tabla_mbhc_cal_btn_det_mp(btn_det, TABLA_BTN_DET_N_CIC);
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_TIMER_B6_CTL, 0xFF,
n_cic[tabla_codec_mclk_index(tabla)]);
gain = tabla_mbhc_cal_btn_det_mp(btn_det, TABLA_BTN_DET_GAIN);
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_B2_CTL, 0x78,
gain[tabla_codec_mclk_index(tabla)] << 3);
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_TIMER_B4_CTL, 0x70,
generic->mbhc_nsa << 4);
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_TIMER_B4_CTL, 0x0F,
btn_det->n_meas);
snd_soc_write(codec, TABLA_A_CDC_MBHC_TIMER_B5_CTL, generic->mbhc_navg);
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_B1_CTL, 0x80, 0x80);
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_B1_CTL, 0x78,
btn_det->mbhc_nsc << 3);
snd_soc_update_bits(codec, tabla->reg_addr.micb_4_mbhc, 0x03,
TABLA_MICBIAS2);
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_B1_CTL, 0x02, 0x02);
snd_soc_update_bits(codec, TABLA_A_MBHC_SCALING_MUX_2, 0xF0, 0xF0);
/* override mbhc's micbias */
snd_soc_update_bits(codec, TABLA_A_MICB_1_MBHC, 0x03,
tabla->mbhc_cfg.micbias);
}
static bool tabla_mbhc_fw_validate(const struct firmware *fw)
{
u32 cfg_offset;
struct tabla_mbhc_imped_detect_cfg *imped_cfg;
struct tabla_mbhc_btn_detect_cfg *btn_cfg;
if (fw->size < TABLA_MBHC_CAL_MIN_SIZE)
return false;
/* previous check guarantees that there is enough fw data up
* to num_btn
*/
btn_cfg = TABLA_MBHC_CAL_BTN_DET_PTR(fw->data);
cfg_offset = (u32) ((void *) btn_cfg - (void *) fw->data);
if (fw->size < (cfg_offset + TABLA_MBHC_CAL_BTN_SZ(btn_cfg)))
return false;
/* previous check guarantees that there is enough fw data up
* to start of impedance detection configuration
*/
imped_cfg = TABLA_MBHC_CAL_IMPED_DET_PTR(fw->data);
cfg_offset = (u32) ((void *) imped_cfg - (void *) fw->data);
if (fw->size < (cfg_offset + TABLA_MBHC_CAL_IMPED_MIN_SZ))
return false;
if (fw->size < (cfg_offset + TABLA_MBHC_CAL_IMPED_SZ(imped_cfg)))
return false;
return true;
}
/* called under codec_resource_lock acquisition */
static int tabla_determine_button(const struct tabla_priv *priv,
const s32 micmv)
{
s16 *v_btn_low, *v_btn_high;
struct tabla_mbhc_btn_detect_cfg *btn_det;
int i, btn = -1;
btn_det = TABLA_MBHC_CAL_BTN_DET_PTR(priv->mbhc_cfg.calibration);
v_btn_low = tabla_mbhc_cal_btn_det_mp(btn_det, TABLA_BTN_DET_V_BTN_LOW);
v_btn_high = tabla_mbhc_cal_btn_det_mp(btn_det,
TABLA_BTN_DET_V_BTN_HIGH);
for (i = 0; i < btn_det->num_btn; i++) {
if ((v_btn_low[i] <= micmv) && (v_btn_high[i] >= micmv)) {
btn = i;
break;
}
}
if (btn == -1)
pr_debug("%s: couldn't find button number for mic mv %d\n",
__func__, micmv);
return btn;
}
static int tabla_get_button_mask(const int btn)
{
int mask = 0;
switch (btn) {
case 0:
mask = SND_JACK_BTN_0;
break;
case 1:
mask = SND_JACK_BTN_1;
break;
case 2:
mask = SND_JACK_BTN_2;
break;
case 3:
mask = SND_JACK_BTN_3;
break;
case 4:
mask = SND_JACK_BTN_4;
break;
case 5:
mask = SND_JACK_BTN_5;
break;
case 6:
mask = SND_JACK_BTN_6;
break;
case 7:
mask = SND_JACK_BTN_7;
break;
}
return mask;
}
static irqreturn_t tabla_dce_handler(int irq, void *data)
{
int i, mask;
short dce, sta;
s32 mv, mv_s, stamv, stamv_s;
bool vddio;
u16 *btn_high;
int btn = -1, meas = 0;
struct tabla_priv *priv = data;
const struct tabla_mbhc_btn_detect_cfg *d =
TABLA_MBHC_CAL_BTN_DET_PTR(priv->mbhc_cfg.calibration);
short btnmeas[d->n_btn_meas + 1];
struct snd_soc_codec *codec = priv->codec;
struct wcd9xxx *core = dev_get_drvdata(priv->codec->dev->parent);
struct wcd9xxx_core_resource *core_res = &core->core_res;
int n_btn_meas = d->n_btn_meas;
u8 mbhc_status = snd_soc_read(codec, TABLA_A_CDC_MBHC_B1_STATUS) & 0x3E;
pr_debug("%s: enter\n", __func__);
btn_high = tabla_mbhc_cal_btn_det_mp(d, TABLA_BTN_DET_V_BTN_HIGH);
TABLA_ACQUIRE_LOCK(priv->codec_resource_lock);
if (priv->mbhc_state == MBHC_STATE_POTENTIAL_RECOVERY) {
pr_debug("%s: mbhc is being recovered, skip button press\n",
__func__);
goto done;
}
priv->mbhc_state = MBHC_STATE_POTENTIAL;
if (!priv->mbhc_polling_active) {
pr_warn("%s: mbhc polling is not active, skip button press\n",
__func__);
goto done;
}
dce = tabla_codec_read_dce_result(codec);
mv = tabla_codec_sta_dce_v(codec, 1, dce);
/* If GPIO interrupt already kicked in, ignore button press */
if (priv->in_gpio_handler) {
pr_debug("%s: GPIO State Changed, ignore button press\n",
__func__);
btn = -1;
goto done;
}
vddio = !priv->mbhc_cfg.micbias_always_on &&
(priv->mbhc_data.micb_mv != VDDIO_MICBIAS_MV &&
priv->mbhc_micbias_switched);
mv_s = vddio ? tabla_scale_v_micb_vddio(priv, mv, false) : mv;
if (mbhc_status != TABLA_MBHC_STATUS_REL_DETECTION) {
if (priv->mbhc_last_resume &&
!time_after(jiffies, priv->mbhc_last_resume + HZ)) {
pr_debug("%s: Button is already released shortly after "
"resume\n", __func__);
n_btn_meas = 0;
}
}
/* save hw dce */
btnmeas[meas++] = tabla_determine_button(priv, mv_s);
pr_debug("%s: meas HW - DCE %x,%d,%d button %d\n", __func__,
dce, mv, mv_s, btnmeas[0]);
if (n_btn_meas == 0) {
sta = tabla_codec_read_sta_result(codec);
stamv_s = stamv = tabla_codec_sta_dce_v(codec, 0, sta);
if (vddio)
stamv_s = tabla_scale_v_micb_vddio(priv, stamv, false);
btn = tabla_determine_button(priv, stamv_s);
pr_debug("%s: meas HW - STA %x,%d,%d button %d\n", __func__,
sta, stamv, stamv_s, btn);
BUG_ON(meas != 1);
if (btnmeas[0] != btn)
btn = -1;
}
/* determine pressed button */
for (; ((d->n_btn_meas) && (meas < (d->n_btn_meas + 1))); meas++) {
dce = tabla_codec_sta_dce(codec, 1, false);
mv = tabla_codec_sta_dce_v(codec, 1, dce);
mv_s = vddio ? tabla_scale_v_micb_vddio(priv, mv, false) : mv;
btnmeas[meas] = tabla_determine_button(priv, mv_s);
pr_debug("%s: meas %d - DCE %x,%d,%d button %d\n",
__func__, meas, dce, mv, mv_s, btnmeas[meas]);
/* if large enough measurements are collected,
* start to check if last all n_btn_con measurements were
* in same button low/high range */
if (meas + 1 >= d->n_btn_con) {
for (i = 0; i < d->n_btn_con; i++)
if ((btnmeas[meas] < 0) ||
(btnmeas[meas] != btnmeas[meas - i]))
break;
if (i == d->n_btn_con) {
/* button pressed */
btn = btnmeas[meas];
break;
} else if ((n_btn_meas - meas) < (d->n_btn_con - 1)) {
/* if left measurements are less than n_btn_con,
* it's impossible to find button number */
break;
}
}
}
if (btn >= 0) {
if (priv->in_gpio_handler) {
pr_debug("%s: GPIO already triggered, ignore button "
"press\n", __func__);
goto done;
}
/* narrow down release threshold */
tabla_mbhc_set_rel_thres(codec, btn_high[btn]);
mask = tabla_get_button_mask(btn);
priv->buttons_pressed |= mask;
wcd9xxx_lock_sleep(core_res);
if (schedule_delayed_work(&priv->mbhc_btn_dwork,
msecs_to_jiffies(400)) == 0) {
WARN(1, "Button pressed twice without release"
"event\n");
wcd9xxx_unlock_sleep(core_res);
}
} else {
pr_debug("%s: bogus button press, too short press?\n",
__func__);
}
done:
pr_debug("%s: leave\n", __func__);
TABLA_RELEASE_LOCK(priv->codec_resource_lock);
return IRQ_HANDLED;
}
static int tabla_is_fake_press(struct tabla_priv *priv)
{
int i;
int r = 0;
struct snd_soc_codec *codec = priv->codec;
const int dces = MBHC_NUM_DCE_PLUG_DETECT;
s16 mb_v, v_ins_hu, v_ins_h;
v_ins_hu = tabla_get_current_v_ins(priv, true);
v_ins_h = tabla_get_current_v_ins(priv, false);
for (i = 0; i < dces; i++) {
usleep_range(10000, 10000);
if (i == 0) {
mb_v = tabla_codec_sta_dce(codec, 0, true);
pr_debug("%s: STA[0]: %d,%d\n", __func__, mb_v,
tabla_codec_sta_dce_v(codec, 0, mb_v));
if (mb_v < (s16)priv->mbhc_data.v_b1_hu ||
mb_v > v_ins_hu) {
r = 1;
break;
}
} else {
mb_v = tabla_codec_sta_dce(codec, 1, true);
pr_debug("%s: DCE[%d]: %d,%d\n", __func__, i, mb_v,
tabla_codec_sta_dce_v(codec, 1, mb_v));
if (mb_v < (s16)priv->mbhc_data.v_b1_h ||
mb_v > v_ins_h) {
r = 1;
break;
}
}
}
return r;
}
static irqreturn_t tabla_release_handler(int irq, void *data)
{
int ret;
struct tabla_priv *priv = data;
struct snd_soc_codec *codec = priv->codec;
pr_debug("%s: enter\n", __func__);
TABLA_ACQUIRE_LOCK(priv->codec_resource_lock);
priv->mbhc_state = MBHC_STATE_RELEASE;
tabla_codec_drive_v_to_micbias(codec, 10000);
if (priv->buttons_pressed & TABLA_JACK_BUTTON_MASK) {
ret = tabla_cancel_btn_work(priv);
if (ret == 0) {
pr_debug("%s: Reporting long button release event\n",
__func__);
if (priv->mbhc_cfg.button_jack)
tabla_snd_soc_jack_report(priv,
priv->mbhc_cfg.button_jack, 0,
priv->buttons_pressed);
} else {
if (tabla_is_fake_press(priv)) {
pr_debug("%s: Fake button press interrupt\n",
__func__);
} else if (priv->mbhc_cfg.button_jack) {
if (priv->in_gpio_handler) {
pr_debug("%s: GPIO kicked in, ignore\n",
__func__);
} else {
pr_debug("%s: Reporting short button "
"press and release\n",
__func__);
tabla_snd_soc_jack_report(priv,
priv->mbhc_cfg.button_jack,
priv->buttons_pressed,
priv->buttons_pressed);
tabla_snd_soc_jack_report(priv,
priv->mbhc_cfg.button_jack, 0,
priv->buttons_pressed);
}
}
}
priv->buttons_pressed &= ~TABLA_JACK_BUTTON_MASK;
}
/* revert narrowed release threshold */
tabla_mbhc_calc_rel_thres(codec, tabla_mbhc_highest_btn_mv(codec));
tabla_codec_calibrate_hs_polling(codec);
if (priv->mbhc_cfg.gpio)
msleep(TABLA_MBHC_GPIO_REL_DEBOUNCE_TIME_MS);
tabla_codec_start_hs_polling(codec);
pr_debug("%s: leave\n", __func__);
TABLA_RELEASE_LOCK(priv->codec_resource_lock);
return IRQ_HANDLED;
}
static void tabla_codec_shutdown_hs_removal_detect(struct snd_soc_codec *codec)
{
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
const struct tabla_mbhc_general_cfg *generic =
TABLA_MBHC_CAL_GENERAL_PTR(tabla->mbhc_cfg.calibration);
if (!tabla->mclk_enabled && !tabla->mbhc_polling_active)
tabla_codec_enable_config_mode(codec, 1);
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_CLK_CTL, 0x2, 0x2);
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_B1_CTL, 0x6, 0x0);
snd_soc_update_bits(codec, tabla->mbhc_bias_regs.mbhc_reg, 0x80, 0x00);
usleep_range(generic->t_shutdown_plug_rem,
generic->t_shutdown_plug_rem);
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_CLK_CTL, 0xA, 0x8);
if (!tabla->mclk_enabled && !tabla->mbhc_polling_active)
tabla_codec_enable_config_mode(codec, 0);
snd_soc_write(codec, TABLA_A_MBHC_SCALING_MUX_1, 0x00);
}
static void tabla_codec_cleanup_hs_polling(struct snd_soc_codec *codec)
{
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
tabla_codec_shutdown_hs_removal_detect(codec);
if (!tabla->mclk_enabled) {
tabla_codec_disable_clock_block(codec);
tabla_codec_enable_bandgap(codec, TABLA_BANDGAP_OFF);
}
tabla->mbhc_polling_active = false;
tabla->mbhc_state = MBHC_STATE_NONE;
}
static irqreturn_t tabla_hphl_ocp_irq(int irq, void *data)
{
struct tabla_priv *tabla = data;
struct snd_soc_codec *codec;
pr_info("%s: received HPHL OCP irq\n", __func__);
if (tabla) {
codec = tabla->codec;
if ((tabla->hphlocp_cnt < TABLA_OCP_ATTEMPT) &&
(!tabla->hphrocp_cnt)) {
pr_info("%s: retry\n", __func__);
tabla->hphlocp_cnt++;
snd_soc_update_bits(codec, TABLA_A_RX_HPH_OCP_CTL, 0x10,
0x00);
snd_soc_update_bits(codec, TABLA_A_RX_HPH_OCP_CTL, 0x10,
0x10);
} else {
wcd9xxx_disable_irq(codec->control_data,
WCD9XXX_IRQ_HPH_PA_OCPL_FAULT);
tabla->hph_status |= SND_JACK_OC_HPHL;
if (tabla->mbhc_cfg.headset_jack)
tabla_snd_soc_jack_report(tabla,
tabla->mbhc_cfg.headset_jack,
tabla->hph_status,
TABLA_JACK_MASK);
}
} else {
pr_err("%s: Bad tabla private data\n", __func__);
}
return IRQ_HANDLED;
}
static irqreturn_t tabla_hphr_ocp_irq(int irq, void *data)
{
struct tabla_priv *tabla = data;
struct snd_soc_codec *codec;
pr_info("%s: received HPHR OCP irq\n", __func__);
if (tabla) {
codec = tabla->codec;
if ((tabla->hphrocp_cnt < TABLA_OCP_ATTEMPT) &&
(!tabla->hphlocp_cnt)) {
pr_info("%s: retry\n", __func__);
tabla->hphrocp_cnt++;
snd_soc_update_bits(codec, TABLA_A_RX_HPH_OCP_CTL, 0x10,
0x00);
snd_soc_update_bits(codec, TABLA_A_RX_HPH_OCP_CTL, 0x10,
0x10);
} else {
wcd9xxx_disable_irq(codec->control_data,
WCD9XXX_IRQ_HPH_PA_OCPR_FAULT);
tabla->hph_status |= SND_JACK_OC_HPHR;
if (tabla->mbhc_cfg.headset_jack)
tabla_snd_soc_jack_report(tabla,
tabla->mbhc_cfg.headset_jack,
tabla->hph_status,
TABLA_JACK_MASK);
}
} else {
pr_err("%s: Bad tabla private data\n", __func__);
}
return IRQ_HANDLED;
}
static bool tabla_is_inval_ins_range(struct snd_soc_codec *codec,
s32 mic_volt, bool highhph, bool *highv)
{
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
bool invalid = false;
s16 v_hs_max;
/* Perform this check only when the high voltage headphone
* needs to be considered as invalid
*/
v_hs_max = tabla_get_current_v_hs_max(tabla);
*highv = mic_volt > v_hs_max;
if (!highhph && *highv)
invalid = true;
else if (mic_volt < tabla->mbhc_data.v_inval_ins_high &&
(mic_volt > tabla->mbhc_data.v_inval_ins_low))
invalid = true;
return invalid;
}
static bool tabla_is_inval_ins_delta(struct snd_soc_codec *codec,
int mic_volt, int mic_volt_prev,
int threshold)
{
return abs(mic_volt - mic_volt_prev) > threshold;
}
/* called under codec_resource_lock acquisition */
void tabla_find_plug_and_report(struct snd_soc_codec *codec,
enum tabla_mbhc_plug_type plug_type)
{
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
pr_debug("%s: enter current_plug(%d) new_plug(%d)\n",
__func__, tabla->current_plug, plug_type);
if (plug_type == PLUG_TYPE_HEADPHONE &&
tabla->current_plug == PLUG_TYPE_NONE) {
/* Nothing was reported previously
* report a headphone or unsupported
*/
tabla_codec_report_plug(codec, 1, SND_JACK_HEADPHONE);
tabla_codec_cleanup_hs_polling(codec);
} else if (plug_type == PLUG_TYPE_GND_MIC_SWAP) {
if (!tabla->mbhc_cfg.detect_extn_cable) {
if (tabla->current_plug == PLUG_TYPE_HEADSET)
tabla_codec_report_plug(codec, 0,
SND_JACK_HEADSET);
else if (tabla->current_plug == PLUG_TYPE_HEADPHONE)
tabla_codec_report_plug(codec, 0,
SND_JACK_HEADPHONE);
}
tabla_codec_report_plug(codec, 1, SND_JACK_UNSUPPORTED);
tabla_codec_cleanup_hs_polling(codec);
} else if (plug_type == PLUG_TYPE_HEADSET) {
/* If Headphone was reported previously, this will
* only report the mic line
*/
tabla_codec_report_plug(codec, 1, SND_JACK_HEADSET);
if (!tabla->mbhc_micbias_switched &&
tabla_is_hph_pa_on(codec)) {
/*If the headphone path is on, switch the micbias
to VDDIO to avoid noise due to button polling */
tabla_codec_switch_micbias(codec, 1);
pr_debug("%s: HPH path is still up\n", __func__);
}
msleep(100);
tabla_codec_start_hs_polling(codec);
} else if (plug_type == PLUG_TYPE_HIGH_HPH) {
if (tabla->mbhc_cfg.detect_extn_cable) {
/* High impedance device found. Report as LINEOUT*/
tabla_codec_report_plug(codec, 1, SND_JACK_LINEOUT);
tabla_codec_cleanup_hs_polling(codec);
pr_debug("%s: setup mic trigger for further detection\n",
__func__);
tabla->lpi_enabled = true;
/*
* Do not enable HPHL trigger. If playback is active,
* it might lead to continuous false HPHL triggers
*/
tabla_codec_enable_hs_detect(codec, 1,
MBHC_USE_MB_TRIGGER,
false);
} else {
if (tabla->current_plug == PLUG_TYPE_NONE)
tabla_codec_report_plug(codec, 1,
SND_JACK_HEADPHONE);
tabla_codec_cleanup_hs_polling(codec);
pr_debug("setup mic trigger for further detection\n");
tabla->lpi_enabled = true;
tabla_codec_enable_hs_detect(codec, 1,
MBHC_USE_MB_TRIGGER |
MBHC_USE_HPHL_TRIGGER,
false);
}
} else {
WARN(1, "Unexpected current plug_type %d, plug_type %d\n",
tabla->current_plug, plug_type);
}
pr_debug("%s: leave\n", __func__);
}
/* should be called under interrupt context that hold suspend */
static void tabla_schedule_hs_detect_plug(struct tabla_priv *tabla,
struct work_struct *correct_plug_work)
{
struct wcd9xxx *core = tabla->codec->control_data;
struct wcd9xxx_core_resource *core_res = &core->core_res;
pr_debug("%s: scheduling tabla_hs_correct_gpio_plug\n", __func__);
tabla->hs_detect_work_stop = false;
wcd9xxx_lock_sleep(core_res);
schedule_work(correct_plug_work);
}
/* called under codec_resource_lock acquisition */
static void tabla_cancel_hs_detect_plug(struct tabla_priv *tabla,
struct work_struct *correct_plug_work)
{
struct wcd9xxx *core = tabla->codec->control_data;
struct wcd9xxx_core_resource *core_res = &core->core_res;
pr_debug("%s: canceling hs_correct_plug_work\n", __func__);
tabla->hs_detect_work_stop = true;
wmb();
TABLA_RELEASE_LOCK(tabla->codec_resource_lock);
if (cancel_work_sync(correct_plug_work)) {
pr_debug("%s: hs_correct_plug_work is canceled\n", __func__);
wcd9xxx_unlock_sleep(core_res);
}
TABLA_ACQUIRE_LOCK(tabla->codec_resource_lock);
}
static bool tabla_hs_gpio_level_remove(struct tabla_priv *tabla)
{
return (gpio_get_value_cansleep(tabla->mbhc_cfg.gpio) !=
tabla->mbhc_cfg.gpio_level_insert);
}
/* called under codec_resource_lock acquisition */
static void tabla_codec_hphr_gnd_switch(struct snd_soc_codec *codec, bool on)
{
snd_soc_update_bits(codec, TABLA_A_MBHC_HPH, 0x01, on);
if (on)
usleep_range(5000, 5000);
}
static void tabla_codec_onoff_vddio_switch(struct snd_soc_codec *codec, bool on)
{
bool override;
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
pr_debug("%s: enter\n", __func__);
if (on) {
override = snd_soc_read(codec, TABLA_A_CDC_MBHC_B1_CTL) & 0x04;
if (!override)
tabla_turn_onoff_override(codec, true);
/* enable the vddio switch */
snd_soc_update_bits(codec, tabla->mbhc_bias_regs.mbhc_reg,
0x91, 0x81);
/* deroute the override from MicBias2 to MicBias4 */
snd_soc_update_bits(codec, TABLA_A_MICB_1_MBHC,
0x03, 0x03);
usleep_range(MBHC_VDDIO_SWITCH_WAIT_MS * 1000,
MBHC_VDDIO_SWITCH_WAIT_MS * 1000);
if (!override)
tabla_turn_onoff_override(codec, false);
tabla->mbhc_micbias_switched = true;
pr_debug("%s: VDDIO switch enabled\n", __func__);
} else {
snd_soc_update_bits(codec, tabla->mbhc_bias_regs.mbhc_reg,
0x91, 0x00);
/* reroute the override to MicBias2 */
snd_soc_update_bits(codec, TABLA_A_MICB_1_MBHC,
0x03, 0x01);
tabla->mbhc_micbias_switched = false;
pr_debug("%s: VDDIO switch disabled\n", __func__);
}
}
/* called under codec_resource_lock acquisition and mbhc override = 1 */
static enum tabla_mbhc_plug_type
tabla_codec_get_plug_type(struct snd_soc_codec *codec, bool highhph)
{
int i;
bool gndswitch, vddioswitch;
int scaled;
struct tabla_mbhc_plug_type_cfg *plug_type_ptr;
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
const bool vddio = !tabla->mbhc_cfg.micbias_always_on &&
(tabla->mbhc_data.micb_mv != VDDIO_MICBIAS_MV);
int num_det = (MBHC_NUM_DCE_PLUG_DETECT + vddio);
enum tabla_mbhc_plug_type plug_type[num_det];
s16 mb_v[num_det];
s32 mic_mv[num_det];
bool inval;
bool highdelta = false;
bool ahighv = false, highv;
bool gndmicswapped = false;
pr_debug("%s: enter\n", __func__);
/* make sure override is on */
WARN_ON(!(snd_soc_read(codec, TABLA_A_CDC_MBHC_B1_CTL) & 0x04));
/* GND and MIC swap detection requires at least 2 rounds of DCE */
BUG_ON(num_det < 2);
plug_type_ptr =
TABLA_MBHC_CAL_PLUG_TYPE_PTR(tabla->mbhc_cfg.calibration);
plug_type[0] = PLUG_TYPE_INVALID;
/* performs DCEs for N times
* 1st: check if voltage is in invalid range
* 2nd - N-2nd: check voltage range and delta
* N-1st: check voltage range, delta with HPHR GND switch
* Nth: check voltage range with VDDIO switch */
for (i = 0; i < num_det; i++) {
gndswitch = (i == (num_det - 2));
vddioswitch = (i == (num_det - 1));
if (i == 0) {
mb_v[i] = tabla_codec_setup_hs_polling(codec);
mic_mv[i] = tabla_codec_sta_dce_v(codec, 1 , mb_v[i]);
inval = tabla_is_inval_ins_range(codec, mic_mv[i],
highhph, &highv);
ahighv |= highv;
scaled = mic_mv[i];
} else {
if (vddioswitch)
tabla_codec_onoff_vddio_switch(codec, true);
if (gndswitch)
tabla_codec_hphr_gnd_switch(codec, true);
mb_v[i] = __tabla_codec_sta_dce(codec, 1, true, true);
mic_mv[i] = tabla_codec_sta_dce_v(codec, 1 , mb_v[i]);
if (vddioswitch)
scaled = tabla_scale_v_micb_vddio(tabla,
mic_mv[i],
false);
else
scaled = mic_mv[i];
/* !gndswitch & vddioswitch means the previous DCE
* was done with gndswitch, don't compare with DCE
* with gndswitch */
highdelta = tabla_is_inval_ins_delta(codec, scaled,
mic_mv[i - 1],
TABLA_MBHC_FAKE_INS_DELTA_SCALED_MV);
inval = (tabla_is_inval_ins_range(codec, mic_mv[i],
highhph, &highv) ||
highdelta);
ahighv |= highv;
if (gndswitch)
tabla_codec_hphr_gnd_switch(codec, false);
if (vddioswitch)
tabla_codec_onoff_vddio_switch(codec, false);
}
pr_debug("%s: DCE #%d, %04x, V %d, scaled V %d, GND %d, "
"VDDIO %d, inval %d\n", __func__,
i + 1, mb_v[i] & 0xffff, mic_mv[i], scaled, gndswitch,
vddioswitch, inval);
/* don't need to run further DCEs */
if ((ahighv || !vddioswitch) && inval)
break;
mic_mv[i] = scaled;
/*
* claim UNSUPPORTED plug insertion when
* good headset is detected but HPHR GND switch makes
* delta difference
*/
if (i == (num_det - 2) && highdelta && !ahighv)
gndmicswapped = true;
else if (i == (num_det - 1) && inval) {
if (gndmicswapped)
plug_type[0] = PLUG_TYPE_GND_MIC_SWAP;
else
plug_type[0] = PLUG_TYPE_INVALID;
}
}
for (i = 0; (plug_type[0] != PLUG_TYPE_GND_MIC_SWAP && !inval) &&
i < num_det; i++) {
/*
* If we are here, means none of the all
* measurements are fake, continue plug type detection.
* If all three measurements do not produce same
* plug type, restart insertion detection
*/
if (mic_mv[i] < plug_type_ptr->v_no_mic) {
plug_type[i] = PLUG_TYPE_HEADPHONE;
pr_debug("%s: Detect attempt %d, detected Headphone\n",
__func__, i);
} else if (highhph && (mic_mv[i] > plug_type_ptr->v_hs_max)) {
plug_type[i] = PLUG_TYPE_HIGH_HPH;
pr_debug("%s: Detect attempt %d, detected High "
"Headphone\n", __func__, i);
} else {
plug_type[i] = PLUG_TYPE_HEADSET;
pr_debug("%s: Detect attempt %d, detected Headset\n",
__func__, i);
}
if (i > 0 && (plug_type[i - 1] != plug_type[i])) {
pr_err("%s: Detect attempt %d and %d are not same",
__func__, i - 1, i);
plug_type[0] = PLUG_TYPE_INVALID;
inval = true;
break;
}
}
pr_debug("%s: Detected plug type %d\n", __func__, plug_type[0]);
pr_debug("%s: leave\n", __func__);
return plug_type[0];
}
static void tabla_hs_correct_gpio_plug(struct work_struct *work)
{
struct tabla_priv *tabla;
struct snd_soc_codec *codec;
int retry = 0, pt_gnd_mic_swap_cnt = 0;
bool correction = false;
enum tabla_mbhc_plug_type plug_type = PLUG_TYPE_INVALID;
unsigned long timeout;
struct wcd9xxx *core;
struct wcd9xxx_core_resource *core_res;
tabla = container_of(work, struct tabla_priv, hs_correct_plug_work);
codec = tabla->codec;
core = tabla->codec->control_data;
core_res = &core->core_res;
pr_debug("%s: enter\n", __func__);
tabla->mbhc_cfg.mclk_cb_fn(codec, 1, false);
/* Keep override on during entire plug type correction work.
*
* This is okay under the assumption that any GPIO irqs which use
* MBHC block cancel and sync this work so override is off again
* prior to GPIO interrupt handler's MBHC block usage.
* Also while this correction work is running, we can guarantee
* DAPM doesn't use any MBHC block as this work only runs with
* headphone detection.
*/
tabla_turn_onoff_override(codec, true);
timeout = jiffies + msecs_to_jiffies(TABLA_HS_DETECT_PLUG_TIME_MS);
while (!time_after(jiffies, timeout)) {
++retry;
rmb();
if (tabla->hs_detect_work_stop) {
pr_debug("%s: stop requested\n", __func__);
break;
}
msleep(TABLA_HS_DETECT_PLUG_INERVAL_MS);
if (tabla_hs_gpio_level_remove(tabla)) {
pr_debug("%s: GPIO value is low\n", __func__);
break;
}
/* can race with removal interrupt */
TABLA_ACQUIRE_LOCK(tabla->codec_resource_lock);
plug_type = tabla_codec_get_plug_type(codec, true);
TABLA_RELEASE_LOCK(tabla->codec_resource_lock);
pr_debug("%s: attempt(%d) current_plug(%d) new_plug(%d)\n",
__func__, retry, tabla->current_plug, plug_type);
if (plug_type == PLUG_TYPE_INVALID) {
pr_debug("Invalid plug in attempt # %d\n", retry);
if (!tabla->mbhc_cfg.detect_extn_cable &&
retry == NUM_ATTEMPTS_TO_REPORT &&
tabla->current_plug == PLUG_TYPE_NONE) {
tabla_codec_report_plug(codec, 1,
SND_JACK_HEADPHONE);
}
} else if (plug_type == PLUG_TYPE_HEADPHONE) {
pr_debug("Good headphone detected, continue polling mic\n");
if (tabla->mbhc_cfg.detect_extn_cable) {
if (tabla->current_plug != plug_type)
tabla_codec_report_plug(codec, 1,
SND_JACK_HEADPHONE);
} else if (tabla->current_plug == PLUG_TYPE_NONE)
tabla_codec_report_plug(codec, 1,
SND_JACK_HEADPHONE);
} else {
if (plug_type == PLUG_TYPE_GND_MIC_SWAP) {
pt_gnd_mic_swap_cnt++;
if (pt_gnd_mic_swap_cnt <
TABLA_MBHC_GND_MIC_SWAP_THRESHOLD)
continue;
else if (pt_gnd_mic_swap_cnt >
TABLA_MBHC_GND_MIC_SWAP_THRESHOLD) {
/* This is due to GND/MIC switch didn't
* work, Report unsupported plug */
} else if (tabla->mbhc_cfg.swap_gnd_mic) {
/* if switch is toggled, check again,
* otherwise report unsupported plug */
if (tabla->mbhc_cfg.swap_gnd_mic(codec))
continue;
}
} else
pt_gnd_mic_swap_cnt = 0;
TABLA_ACQUIRE_LOCK(tabla->codec_resource_lock);
/* Turn off override */
tabla_turn_onoff_override(codec, false);
/* The valid plug also includes PLUG_TYPE_GND_MIC_SWAP
*/
tabla_find_plug_and_report(codec, plug_type);
TABLA_RELEASE_LOCK(tabla->codec_resource_lock);
pr_debug("Attempt %d found correct plug %d\n", retry,
plug_type);
correction = true;
break;
}
}
/* Turn off override */
if (!correction)
tabla_turn_onoff_override(codec, false);
tabla->mbhc_cfg.mclk_cb_fn(codec, 0, false);
if (tabla->mbhc_cfg.detect_extn_cable) {
TABLA_ACQUIRE_LOCK(tabla->codec_resource_lock);
if (tabla->current_plug == PLUG_TYPE_HEADPHONE ||
tabla->current_plug == PLUG_TYPE_GND_MIC_SWAP ||
tabla->current_plug == PLUG_TYPE_INVALID ||
plug_type == PLUG_TYPE_INVALID) {
/* Enable removal detection */
tabla_codec_cleanup_hs_polling(codec);
tabla_codec_enable_hs_detect(codec, 0, 0, false);
}
TABLA_RELEASE_LOCK(tabla->codec_resource_lock);
}
pr_debug("%s: leave current_plug(%d)\n",
__func__, tabla->current_plug);
/* unlock sleep */
wcd9xxx_unlock_sleep(core_res);
}
/* called under codec_resource_lock acquisition */
static void tabla_codec_decide_gpio_plug(struct snd_soc_codec *codec)
{
enum tabla_mbhc_plug_type plug_type;
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
pr_debug("%s: enter\n", __func__);
tabla_turn_onoff_override(codec, true);
plug_type = tabla_codec_get_plug_type(codec, true);
tabla_turn_onoff_override(codec, false);
if (tabla_hs_gpio_level_remove(tabla)) {
pr_debug("%s: GPIO value is low when determining plug\n",
__func__);
return;
}
if (plug_type == PLUG_TYPE_INVALID ||
plug_type == PLUG_TYPE_GND_MIC_SWAP) {
tabla_schedule_hs_detect_plug(tabla,
&tabla->hs_correct_plug_work);
} else if (plug_type == PLUG_TYPE_HEADPHONE) {
tabla_codec_report_plug(codec, 1, SND_JACK_HEADPHONE);
tabla_schedule_hs_detect_plug(tabla,
&tabla->hs_correct_plug_work);
} else {
pr_debug("%s: Valid plug found, determine plug type %d\n",
__func__, plug_type);
tabla_find_plug_and_report(codec, plug_type);
}
pr_debug("%s: leave\n", __func__);
}
/* called under codec_resource_lock acquisition */
static void tabla_codec_detect_plug_type(struct snd_soc_codec *codec)
{
enum tabla_mbhc_plug_type plug_type;
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
const struct tabla_mbhc_plug_detect_cfg *plug_det =
TABLA_MBHC_CAL_PLUG_DET_PTR(tabla->mbhc_cfg.calibration);
pr_debug("%s: enter\n", __func__);
/* Turn on the override,
* tabla_codec_setup_hs_polling requires override on */
tabla_turn_onoff_override(codec, true);
if (plug_det->t_ins_complete > 20)
msleep(plug_det->t_ins_complete);
else
usleep_range(plug_det->t_ins_complete * 1000,
plug_det->t_ins_complete * 1000);
if (tabla->mbhc_cfg.gpio) {
/* Turn off the override */
tabla_turn_onoff_override(codec, false);
if (tabla_hs_gpio_level_remove(tabla))
pr_debug("%s: GPIO value is low when determining "
"plug\n", __func__);
else
tabla_codec_decide_gpio_plug(codec);
pr_debug("%s: leave\n", __func__);
return;
}
plug_type = tabla_codec_get_plug_type(codec, false);
tabla_turn_onoff_override(codec, false);
if (plug_type == PLUG_TYPE_INVALID) {
pr_debug("%s: Invalid plug type detected\n", __func__);
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_B1_CTL, 0x02, 0x02);
tabla_codec_cleanup_hs_polling(codec);
tabla_codec_enable_hs_detect(codec, 1,
MBHC_USE_MB_TRIGGER |
MBHC_USE_HPHL_TRIGGER, false);
} else if (plug_type == PLUG_TYPE_GND_MIC_SWAP) {
pr_debug("%s: GND-MIC swapped plug type detected\n", __func__);
tabla_codec_report_plug(codec, 1, SND_JACK_UNSUPPORTED);
tabla_codec_cleanup_hs_polling(codec);
tabla_codec_enable_hs_detect(codec, 0, 0, false);
} else if (plug_type == PLUG_TYPE_HEADPHONE) {
pr_debug("%s: Headphone Detected\n", __func__);
tabla_codec_report_plug(codec, 1, SND_JACK_HEADPHONE);
tabla_codec_cleanup_hs_polling(codec);
tabla_schedule_hs_detect_plug(tabla,
&tabla->hs_correct_plug_work_nogpio);
} else if (plug_type == PLUG_TYPE_HEADSET) {
pr_debug("%s: Headset detected\n", __func__);
tabla_codec_report_plug(codec, 1, SND_JACK_HEADSET);
/* avoid false button press detect */
msleep(50);
tabla_codec_start_hs_polling(codec);
} else if (tabla->mbhc_cfg.detect_extn_cable &&
plug_type == PLUG_TYPE_HIGH_HPH) {
pr_debug("%s: High impedance plug type detected\n", __func__);
tabla_codec_report_plug(codec, 1, SND_JACK_LINEOUT);
/* Enable insertion detection on the other end of cable */
tabla_codec_cleanup_hs_polling(codec);
tabla_codec_enable_hs_detect(codec, 1,
MBHC_USE_MB_TRIGGER, false);
}
pr_debug("%s: leave\n", __func__);
}
/* called only from interrupt which is under codec_resource_lock acquisition */
static void tabla_hs_insert_irq_gpio(struct tabla_priv *priv, bool is_removal)
{
struct snd_soc_codec *codec = priv->codec;
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
if (!is_removal) {
pr_debug("%s: MIC trigger insertion interrupt\n", __func__);
rmb();
if (priv->lpi_enabled)
msleep(100);
rmb();
if (!priv->lpi_enabled) {
pr_debug("%s: lpi is disabled\n", __func__);
} else if (gpio_get_value_cansleep(priv->mbhc_cfg.gpio) ==
priv->mbhc_cfg.gpio_level_insert) {
pr_debug("%s: Valid insertion, "
"detect plug type\n", __func__);
tabla_codec_decide_gpio_plug(codec);
} else {
pr_debug("%s: Invalid insertion, "
"stop plug detection\n", __func__);
}
} else if (tabla->mbhc_cfg.detect_extn_cable) {
pr_debug("%s: Removal\n", __func__);
if (!tabla_hs_gpio_level_remove(tabla)) {
/*
* gpio says, something is still inserted, could be
* extension cable i.e. headset is removed from
* extension cable
*/
/* cancel detect plug */
tabla_cancel_hs_detect_plug(tabla,
&tabla->hs_correct_plug_work);
tabla_codec_decide_gpio_plug(codec);
}
} else {
pr_err("%s: GPIO used, invalid MBHC Removal\n", __func__);
}
}
/* called only from interrupt which is under codec_resource_lock acquisition */
static void tabla_hs_insert_irq_nogpio(struct tabla_priv *priv, bool is_removal,
bool is_mb_trigger)
{
int ret;
struct snd_soc_codec *codec = priv->codec;
struct wcd9xxx *core = dev_get_drvdata(priv->codec->dev->parent);
struct wcd9xxx_core_resource *core_res = &core->core_res;
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
/* Cancel possibly running hs_detect_work */
tabla_cancel_hs_detect_plug(tabla,
&tabla->hs_correct_plug_work_nogpio);
if (is_removal) {
/*
* If headphone is removed while playback is in progress,
* it is possible that micbias will be switched to VDDIO.
*/
tabla_codec_switch_micbias(codec, 0);
if (priv->current_plug == PLUG_TYPE_HEADPHONE)
tabla_codec_report_plug(codec, 0, SND_JACK_HEADPHONE);
else if (priv->current_plug == PLUG_TYPE_GND_MIC_SWAP)
tabla_codec_report_plug(codec, 0, SND_JACK_UNSUPPORTED);
else
WARN(1, "%s: Unexpected current plug type %d\n",
__func__, priv->current_plug);
tabla_codec_shutdown_hs_removal_detect(codec);
tabla_codec_enable_hs_detect(codec, 1,
MBHC_USE_MB_TRIGGER |
MBHC_USE_HPHL_TRIGGER,
true);
} else if (is_mb_trigger && !is_removal) {
pr_debug("%s: Waiting for Headphone left trigger\n",
__func__);
wcd9xxx_lock_sleep(core_res);
if (schedule_delayed_work(&priv->mbhc_insert_dwork,
usecs_to_jiffies(1000000)) == 0) {
pr_err("%s: mbhc_insert_dwork is already scheduled\n",
__func__);
wcd9xxx_unlock_sleep(core_res);
}
tabla_codec_enable_hs_detect(codec, 1, MBHC_USE_HPHL_TRIGGER,
false);
} else {
ret = cancel_delayed_work(&priv->mbhc_insert_dwork);
if (ret != 0) {
pr_debug("%s: Complete plug insertion, Detecting plug "
"type\n", __func__);
tabla_codec_detect_plug_type(codec);
wcd9xxx_unlock_sleep(core_res);
} else {
wcd9xxx_enable_irq(codec->control_data,
WCD9XXX_IRQ_MBHC_INSERTION);
pr_err("%s: Error detecting plug insertion\n",
__func__);
}
}
}
/* called only from interrupt which is under codec_resource_lock acquisition */
static void tabla_hs_insert_irq_extn(struct tabla_priv *priv,
bool is_mb_trigger)
{
struct snd_soc_codec *codec = priv->codec;
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
/* Cancel possibly running hs_detect_work */
tabla_cancel_hs_detect_plug(tabla,
&tabla->hs_correct_plug_work);
if (is_mb_trigger) {
pr_debug("%s: Waiting for Headphone left trigger\n",
__func__);
tabla_codec_enable_hs_detect(codec, 1, MBHC_USE_HPHL_TRIGGER,
false);
} else {
pr_debug("%s: HPHL trigger received, detecting plug type\n",
__func__);
tabla_codec_detect_plug_type(codec);
}
}
static irqreturn_t tabla_hs_insert_irq(int irq, void *data)
{
bool is_mb_trigger, is_removal;
struct tabla_priv *priv = data;
struct snd_soc_codec *codec = priv->codec;
pr_debug("%s: enter\n", __func__);
TABLA_ACQUIRE_LOCK(priv->codec_resource_lock);
wcd9xxx_disable_irq(codec->control_data, WCD9XXX_IRQ_MBHC_INSERTION);
is_mb_trigger = !!(snd_soc_read(codec, priv->mbhc_bias_regs.mbhc_reg) &
0x10);
is_removal = !!(snd_soc_read(codec, TABLA_A_CDC_MBHC_INT_CTL) & 0x02);
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_INT_CTL, 0x03, 0x00);
/* Turn off both HPH and MIC line schmitt triggers */
snd_soc_update_bits(codec, priv->mbhc_bias_regs.mbhc_reg, 0x90, 0x00);
snd_soc_update_bits(codec, TABLA_A_MBHC_HPH, 0x13, 0x00);
snd_soc_update_bits(codec, priv->mbhc_bias_regs.ctl_reg, 0x01, 0x00);
if (priv->mbhc_cfg.detect_extn_cable &&
priv->current_plug == PLUG_TYPE_HIGH_HPH)
tabla_hs_insert_irq_extn(priv, is_mb_trigger);
else if (priv->mbhc_cfg.gpio)
tabla_hs_insert_irq_gpio(priv, is_removal);
else
tabla_hs_insert_irq_nogpio(priv, is_removal, is_mb_trigger);
TABLA_RELEASE_LOCK(priv->codec_resource_lock);
return IRQ_HANDLED;
}
static bool is_valid_mic_voltage(struct snd_soc_codec *codec, s32 mic_mv)
{
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
const struct tabla_mbhc_plug_type_cfg *plug_type =
TABLA_MBHC_CAL_PLUG_TYPE_PTR(tabla->mbhc_cfg.calibration);
const s16 v_hs_max = tabla_get_current_v_hs_max(tabla);
return (!(mic_mv > 10 && mic_mv < 80) && (mic_mv > plug_type->v_no_mic)
&& (mic_mv < v_hs_max)) ? true : false;
}
/* called under codec_resource_lock acquisition
* returns true if mic voltage range is back to normal insertion
* returns false either if timedout or removed */
static bool tabla_hs_remove_settle(struct snd_soc_codec *codec)
{
int i;
bool timedout, settled = false;
s32 mic_mv[MBHC_NUM_DCE_PLUG_DETECT];
short mb_v[MBHC_NUM_DCE_PLUG_DETECT];
unsigned long retry = 0, timeout;
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
const s16 v_hs_max = tabla_get_current_v_hs_max(tabla);
timeout = jiffies + msecs_to_jiffies(TABLA_HS_DETECT_PLUG_TIME_MS);
while (!(timedout = time_after(jiffies, timeout))) {
retry++;
if (tabla->mbhc_cfg.gpio && tabla_hs_gpio_level_remove(tabla)) {
pr_debug("%s: GPIO indicates removal\n", __func__);
break;
}
if (tabla->mbhc_cfg.gpio) {
if (retry > 1)
msleep(250);
else
msleep(50);
}
if (tabla->mbhc_cfg.gpio && tabla_hs_gpio_level_remove(tabla)) {
pr_debug("%s: GPIO indicates removal\n", __func__);
break;
}
for (i = 0; i < MBHC_NUM_DCE_PLUG_DETECT; i++) {
mb_v[i] = tabla_codec_sta_dce(codec, 1, true);
mic_mv[i] = tabla_codec_sta_dce_v(codec, 1 , mb_v[i]);
pr_debug("%s : DCE run %lu, mic_mv = %d(%x)\n",
__func__, retry, mic_mv[i], mb_v[i]);
}
if (tabla->mbhc_cfg.gpio && tabla_hs_gpio_level_remove(tabla)) {
pr_debug("%s: GPIO indicates removal\n", __func__);
break;
}
if (tabla->current_plug == PLUG_TYPE_NONE) {
pr_debug("%s : headset/headphone is removed\n",
__func__);
break;
}
for (i = 0; i < MBHC_NUM_DCE_PLUG_DETECT; i++)
if (!is_valid_mic_voltage(codec, mic_mv[i]))
break;
if (i == MBHC_NUM_DCE_PLUG_DETECT) {
pr_debug("%s: MIC voltage settled\n", __func__);
settled = true;
msleep(200);
break;
}
/* only for non-GPIO remove irq */
if (!tabla->mbhc_cfg.gpio) {
for (i = 0; i < MBHC_NUM_DCE_PLUG_DETECT; i++)
if (mic_mv[i] < v_hs_max)
break;
if (i == MBHC_NUM_DCE_PLUG_DETECT) {
pr_debug("%s: Headset is removed\n", __func__);
break;
}
}
}
if (timedout)
pr_debug("%s: Microphone did not settle in %d seconds\n",
__func__, TABLA_HS_DETECT_PLUG_TIME_MS);
return settled;
}
/* called only from interrupt which is under codec_resource_lock acquisition */
static void tabla_hs_remove_irq_gpio(struct tabla_priv *priv)
{
struct snd_soc_codec *codec = priv->codec;
pr_debug("%s: enter\n", __func__);
if (tabla_hs_remove_settle(codec))
tabla_codec_start_hs_polling(codec);
pr_debug("%s: leave\n", __func__);
}
/* called only from interrupt which is under codec_resource_lock acquisition */
static void tabla_hs_remove_irq_nogpio(struct tabla_priv *priv)
{
short bias_value;
bool removed = true;
struct snd_soc_codec *codec = priv->codec;
const struct tabla_mbhc_general_cfg *generic =
TABLA_MBHC_CAL_GENERAL_PTR(priv->mbhc_cfg.calibration);
int min_us = TABLA_FAKE_REMOVAL_MIN_PERIOD_MS * 1000;
pr_debug("%s: enter\n", __func__);
if (priv->current_plug != PLUG_TYPE_HEADSET) {
pr_debug("%s(): Headset is not inserted, ignore removal\n",
__func__);
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_CLK_CTL,
0x08, 0x08);
return;
}
usleep_range(generic->t_shutdown_plug_rem,
generic->t_shutdown_plug_rem);
do {
bias_value = tabla_codec_sta_dce(codec, 1, true);
pr_debug("%s: DCE %d,%d, %d us left\n", __func__, bias_value,
tabla_codec_sta_dce_v(codec, 1, bias_value), min_us);
if (bias_value < tabla_get_current_v_ins(priv, false)) {
pr_debug("%s: checking false removal\n", __func__);
msleep(500);
removed = !tabla_hs_remove_settle(codec);
pr_debug("%s: headset %sactually removed\n", __func__,
removed ? "" : "not ");
break;
}
min_us -= priv->mbhc_data.t_dce;
} while (min_us > 0);
if (removed) {
if (priv->mbhc_cfg.detect_extn_cable) {
if (!tabla_hs_gpio_level_remove(priv)) {
/*
* extension cable is still plugged in
* report it as LINEOUT device
*/
tabla_codec_report_plug(codec, 1,
SND_JACK_LINEOUT);
tabla_codec_cleanup_hs_polling(codec);
tabla_codec_enable_hs_detect(codec, 1,
MBHC_USE_MB_TRIGGER,
false);
}
} else {
/* Cancel possibly running hs_detect_work */
tabla_cancel_hs_detect_plug(priv,
&priv->hs_correct_plug_work_nogpio);
/*
* If this removal is not false, first check the micbias
* switch status and switch it to LDOH if it is already
* switched to VDDIO.
*/
tabla_codec_switch_micbias(codec, 0);
tabla_codec_report_plug(codec, 0, SND_JACK_HEADSET);
tabla_codec_cleanup_hs_polling(codec);
tabla_codec_enable_hs_detect(codec, 1,
MBHC_USE_MB_TRIGGER |
MBHC_USE_HPHL_TRIGGER,
true);
}
} else {
tabla_codec_start_hs_polling(codec);
}
pr_debug("%s: leave\n", __func__);
}
static irqreturn_t tabla_hs_remove_irq(int irq, void *data)
{
struct tabla_priv *priv = data;
bool vddio;
pr_debug("%s: enter, removal interrupt\n", __func__);
TABLA_ACQUIRE_LOCK(priv->codec_resource_lock);
vddio = !priv->mbhc_cfg.micbias_always_on &&
(priv->mbhc_data.micb_mv != VDDIO_MICBIAS_MV &&
priv->mbhc_micbias_switched);
if (vddio)
__tabla_codec_switch_micbias(priv->codec, 0, false, true);
if ((priv->mbhc_cfg.detect_extn_cable &&
!tabla_hs_gpio_level_remove(priv)) ||
!priv->mbhc_cfg.gpio) {
tabla_hs_remove_irq_nogpio(priv);
} else
tabla_hs_remove_irq_gpio(priv);
/* if driver turned off vddio switch and headset is not removed,
* turn on the vddio switch back, if headset is removed then vddio
* switch is off by time now and shouldn't be turn on again from here */
if (vddio && priv->current_plug == PLUG_TYPE_HEADSET)
__tabla_codec_switch_micbias(priv->codec, 1, true, true);
TABLA_RELEASE_LOCK(priv->codec_resource_lock);
return IRQ_HANDLED;
}
void mbhc_insert_work(struct work_struct *work)
{
struct delayed_work *dwork;
struct tabla_priv *tabla;
struct snd_soc_codec *codec;
struct wcd9xxx *tabla_core;
struct wcd9xxx_core_resource *core_res;
dwork = to_delayed_work(work);
tabla = container_of(dwork, struct tabla_priv, mbhc_insert_dwork);
codec = tabla->codec;
tabla_core = dev_get_drvdata(codec->dev->parent);
core_res = &tabla_core->core_res;
pr_debug("%s:\n", __func__);
/* Turn off both HPH and MIC line schmitt triggers */
snd_soc_update_bits(codec, tabla->mbhc_bias_regs.mbhc_reg, 0x90, 0x00);
snd_soc_update_bits(codec, TABLA_A_MBHC_HPH, 0x13, 0x00);
snd_soc_update_bits(codec, tabla->mbhc_bias_regs.ctl_reg, 0x01, 0x00);
wcd9xxx_disable_irq_sync(codec->control_data,
WCD9XXX_IRQ_MBHC_INSERTION);
tabla_codec_detect_plug_type(codec);
wcd9xxx_unlock_sleep(core_res);
}
static void tabla_hs_gpio_handler(struct snd_soc_codec *codec)
{
bool insert;
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
struct wcd9xxx *core = dev_get_drvdata(codec->dev->parent);
bool is_removed = false;
pr_debug("%s: enter\n", __func__);
tabla->in_gpio_handler = true;
/* Wait here for debounce time */
usleep_range(TABLA_GPIO_IRQ_DEBOUNCE_TIME_US,
TABLA_GPIO_IRQ_DEBOUNCE_TIME_US);
wcd9xxx_nested_irq_lock(&core->core_res);
TABLA_ACQUIRE_LOCK(tabla->codec_resource_lock);
/* cancel pending button press */
if (tabla_cancel_btn_work(tabla))
pr_debug("%s: button press is canceled\n", __func__);
insert = (gpio_get_value_cansleep(tabla->mbhc_cfg.gpio) ==
tabla->mbhc_cfg.gpio_level_insert);
if ((tabla->current_plug == PLUG_TYPE_NONE) && insert) {
tabla->lpi_enabled = false;
wmb();
/* cancel detect plug */
tabla_cancel_hs_detect_plug(tabla,
&tabla->hs_correct_plug_work);
/* Disable Mic Bias pull down and HPH Switch to GND */
snd_soc_update_bits(codec, tabla->mbhc_bias_regs.ctl_reg, 0x01,
0x00);
snd_soc_update_bits(codec, TABLA_A_MBHC_HPH, 0x01, 0x00);
tabla_codec_detect_plug_type(codec);
} else if ((tabla->current_plug != PLUG_TYPE_NONE) && !insert) {
tabla->lpi_enabled = false;
wmb();
/* cancel detect plug */
tabla_cancel_hs_detect_plug(tabla,
&tabla->hs_correct_plug_work);
if (tabla->current_plug == PLUG_TYPE_HEADPHONE) {
tabla_codec_report_plug(codec, 0, SND_JACK_HEADPHONE);
is_removed = true;
} else if (tabla->current_plug == PLUG_TYPE_GND_MIC_SWAP) {
tabla_codec_report_plug(codec, 0, SND_JACK_UNSUPPORTED);
is_removed = true;
} else if (tabla->current_plug == PLUG_TYPE_HEADSET) {
tabla_codec_pause_hs_polling(codec);
tabla_codec_cleanup_hs_polling(codec);
tabla_codec_report_plug(codec, 0, SND_JACK_HEADSET);
is_removed = true;
} else if (tabla->current_plug == PLUG_TYPE_HIGH_HPH) {
tabla_codec_report_plug(codec, 0, SND_JACK_LINEOUT);
is_removed = true;
}
if (is_removed) {
/* Enable Mic Bias pull down and HPH Switch to GND */
snd_soc_update_bits(codec,
tabla->mbhc_bias_regs.ctl_reg, 0x01,
0x01);
snd_soc_update_bits(codec, TABLA_A_MBHC_HPH, 0x01,
0x01);
/* Make sure mic trigger is turned off */
snd_soc_update_bits(codec,
tabla->mbhc_bias_regs.ctl_reg,
0x01, 0x01);
snd_soc_update_bits(codec,
tabla->mbhc_bias_regs.mbhc_reg,
0x90, 0x00);
/* Reset MBHC State Machine */
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_CLK_CTL,
0x08, 0x08);
snd_soc_update_bits(codec, TABLA_A_CDC_MBHC_CLK_CTL,
0x08, 0x00);
/* Turn off override */
tabla_turn_onoff_override(codec, false);
tabla_codec_switch_micbias(codec, 0);
}
}
tabla->in_gpio_handler = false;
TABLA_RELEASE_LOCK(tabla->codec_resource_lock);
wcd9xxx_nested_irq_unlock(&core->core_res);
pr_debug("%s: leave\n", __func__);
}
static irqreturn_t tabla_mechanical_plug_detect_irq(int irq, void *data)
{
int r = IRQ_HANDLED;
struct snd_soc_codec *codec = data;
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
struct wcd9xxx *core = codec->control_data;
struct wcd9xxx_core_resource *core_res = &core->core_res;
if (unlikely(wcd9xxx_lock_sleep(core_res) == false)) {
pr_warn("%s: failed to hold suspend\n", __func__);
/*
* Give up this IRQ for now and resend this IRQ so IRQ can be
* handled after system resume
*/
TABLA_ACQUIRE_LOCK(tabla->codec_resource_lock);
tabla->gpio_irq_resend = true;
TABLA_RELEASE_LOCK(tabla->codec_resource_lock);
wake_lock_timeout(&tabla->irq_resend_wlock, HZ);
r = IRQ_NONE;
} else {
tabla_hs_gpio_handler(codec);
wcd9xxx_unlock_sleep(core_res);
}
return r;
}
static void tabla_hs_correct_plug_nogpio(struct work_struct *work)
{
struct tabla_priv *tabla;
struct snd_soc_codec *codec;
unsigned long timeout;
int retry = 0;
enum tabla_mbhc_plug_type plug_type;
bool is_headset = false;
struct wcd9xxx *core;
struct wcd9xxx_core_resource *core_res;
pr_debug("%s(): Poll Microphone voltage for %d seconds\n",
__func__, TABLA_HS_DETECT_PLUG_TIME_MS / 1000);
tabla = container_of(work, struct tabla_priv,
hs_correct_plug_work_nogpio);
codec = tabla->codec;
core = codec->control_data;
core_res = &core->core_res;
/* Make sure the MBHC mux is connected to MIC Path */
snd_soc_write(codec, TABLA_A_MBHC_SCALING_MUX_1, 0x84);
/* setup for microphone polling */
tabla_turn_onoff_override(codec, true);
tabla->mbhc_cfg.mclk_cb_fn(codec, 1, false);
timeout = jiffies + msecs_to_jiffies(TABLA_HS_DETECT_PLUG_TIME_MS);
while (!time_after(jiffies, timeout)) {
++retry;
msleep(TABLA_HS_DETECT_PLUG_INERVAL_MS);
TABLA_ACQUIRE_LOCK(tabla->codec_resource_lock);
plug_type = tabla_codec_get_plug_type(codec, false);
TABLA_RELEASE_LOCK(tabla->codec_resource_lock);
if (plug_type == PLUG_TYPE_HIGH_HPH
|| plug_type == PLUG_TYPE_INVALID) {
/* this means the plug is removed
* End microphone polling and setup
* for low power removal detection.
*/
pr_debug("%s(): Plug may be removed, setup removal\n",
__func__);
break;
} else if (plug_type == PLUG_TYPE_HEADSET) {
/* Plug is corrected from headphone to headset,
* report headset and end the polling
*/
is_headset = true;
TABLA_ACQUIRE_LOCK(tabla->codec_resource_lock);
tabla_turn_onoff_override(codec, false);
tabla_codec_report_plug(codec, 1, SND_JACK_HEADSET);
tabla_codec_start_hs_polling(codec);
TABLA_RELEASE_LOCK(tabla->codec_resource_lock);
pr_debug("%s(): corrected from headphone to headset\n",
__func__);
break;
}
}
/* Undo setup for microphone polling depending
* result from polling
*/
tabla->mbhc_cfg.mclk_cb_fn(codec, 0, false);
if (!is_headset) {
pr_debug("%s: Inserted headphone is not a headset\n",
__func__);
tabla_turn_onoff_override(codec, false);
tabla_codec_cleanup_hs_polling(codec);
tabla_codec_enable_hs_detect(codec, 0, 0, false);
}
wcd9xxx_unlock_sleep(core_res);
}
static int tabla_mbhc_init_and_calibrate(struct tabla_priv *tabla)
{
int ret = 0;
struct snd_soc_codec *codec = tabla->codec;
tabla->mbhc_cfg.mclk_cb_fn(codec, 1, false);
tabla_mbhc_init(codec);
tabla_mbhc_cal(codec);
tabla_mbhc_calc_thres(codec);
tabla->mbhc_cfg.mclk_cb_fn(codec, 0, false);
tabla_codec_calibrate_hs_polling(codec);
if (!tabla->mbhc_cfg.gpio) {
INIT_WORK(&tabla->hs_correct_plug_work_nogpio,
tabla_hs_correct_plug_nogpio);
ret = tabla_codec_enable_hs_detect(codec, 1,
MBHC_USE_MB_TRIGGER |
MBHC_USE_HPHL_TRIGGER,
false);
if (IS_ERR_VALUE(ret))
pr_err("%s: Failed to setup MBHC detection\n",
__func__);
} else {
/* Enable Mic Bias pull down and HPH Switch to GND */
snd_soc_update_bits(codec, tabla->mbhc_bias_regs.ctl_reg,
0x01, 0x01);
snd_soc_update_bits(codec, TABLA_A_MBHC_HPH, 0x01, 0x01);
INIT_WORK(&tabla->hs_correct_plug_work,
tabla_hs_correct_gpio_plug);
}
if (!IS_ERR_VALUE(ret)) {
snd_soc_update_bits(codec, TABLA_A_RX_HPH_OCP_CTL, 0x10, 0x10);
wcd9xxx_enable_irq(codec->control_data,
WCD9XXX_IRQ_HPH_PA_OCPL_FAULT);
wcd9xxx_enable_irq(codec->control_data,
WCD9XXX_IRQ_HPH_PA_OCPR_FAULT);
if (tabla->mbhc_cfg.gpio) {
ret = request_threaded_irq(tabla->mbhc_cfg.gpio_irq,
NULL,
tabla_mechanical_plug_detect_irq,
(IRQF_TRIGGER_RISING |
IRQF_TRIGGER_FALLING),
"tabla-gpio", codec);
if (!IS_ERR_VALUE(ret)) {
ret = enable_irq_wake(tabla->mbhc_cfg.gpio_irq);
/* Bootup time detection */
tabla_hs_gpio_handler(codec);
}
}
}
return ret;
}
static void mbhc_fw_read(struct work_struct *work)
{
struct delayed_work *dwork;
struct tabla_priv *tabla;
struct snd_soc_codec *codec;
const struct firmware *fw;
int ret = -1, retry = 0;
dwork = to_delayed_work(work);
tabla = container_of(dwork, struct tabla_priv, mbhc_firmware_dwork);
codec = tabla->codec;
while (retry < MBHC_FW_READ_ATTEMPTS) {
retry++;
pr_info("%s:Attempt %d to request MBHC firmware\n",
__func__, retry);
ret = request_firmware(&fw, "wcd9310/wcd9310_mbhc.bin",
codec->dev);
if (ret != 0) {
usleep_range(MBHC_FW_READ_TIMEOUT,
MBHC_FW_READ_TIMEOUT);
} else {
pr_info("%s: MBHC Firmware read succesful\n", __func__);
break;
}
}
if (ret != 0) {
pr_err("%s: Cannot load MBHC firmware use default cal\n",
__func__);
} else if (tabla_mbhc_fw_validate(fw) == false) {
pr_err("%s: Invalid MBHC cal data size use default cal\n",
__func__);
release_firmware(fw);
} else {
tabla->mbhc_cfg.calibration = (void *)fw->data;
tabla->mbhc_fw = fw;
}
(void) tabla_mbhc_init_and_calibrate(tabla);
}
int tabla_hs_detect(struct snd_soc_codec *codec,
const struct tabla_mbhc_config *cfg)
{
struct tabla_priv *tabla;
int rc = 0;
if (!codec || !cfg->calibration) {
pr_err("Error: no codec or calibration\n");
return -EINVAL;
}
if (cfg->mclk_rate != TABLA_MCLK_RATE_12288KHZ) {
if (cfg->mclk_rate == TABLA_MCLK_RATE_9600KHZ)
pr_err("Error: clock rate %dHz is not yet supported\n",
cfg->mclk_rate);
else
pr_err("Error: unsupported clock rate %d\n",
cfg->mclk_rate);
return -EINVAL;
}
tabla = snd_soc_codec_get_drvdata(codec);
tabla->mbhc_cfg = *cfg;
tabla->in_gpio_handler = false;
tabla->current_plug = PLUG_TYPE_NONE;
tabla->lpi_enabled = false;
tabla_get_mbhc_micbias_regs(codec, &tabla->mbhc_bias_regs);
/* Put CFILT in fast mode by default */
if (!tabla->mbhc_cfg.micbias_always_on)
snd_soc_update_bits(codec, tabla->mbhc_bias_regs.cfilt_ctl,
0x40, TABLA_CFILT_FAST_MODE);
INIT_DELAYED_WORK(&tabla->mbhc_firmware_dwork, mbhc_fw_read);
INIT_DELAYED_WORK(&tabla->mbhc_btn_dwork, btn_lpress_fn);
INIT_WORK(&tabla->hphlocp_work, hphlocp_off_report);
INIT_WORK(&tabla->hphrocp_work, hphrocp_off_report);
INIT_DELAYED_WORK(&tabla->mbhc_insert_dwork, mbhc_insert_work);
if (!tabla->mbhc_cfg.read_fw_bin)
rc = tabla_mbhc_init_and_calibrate(tabla);
else
schedule_delayed_work(&tabla->mbhc_firmware_dwork,
usecs_to_jiffies(MBHC_FW_READ_TIMEOUT));
return rc;
}
EXPORT_SYMBOL_GPL(tabla_hs_detect);
static irqreturn_t tabla_slimbus_irq(int irq, void *data)
{
struct tabla_priv *priv = data;
struct snd_soc_codec *codec = priv->codec;
struct tabla_priv *tabla_p = snd_soc_codec_get_drvdata(codec);
int i, j, port_id, k, ch_mask_temp;
unsigned long slimbus_value;
u8 val;
for (i = 0; i < WCD9XXX_SLIM_NUM_PORT_REG; i++) {
slimbus_value = wcd9xxx_interface_reg_read(codec->control_data,
TABLA_SLIM_PGD_PORT_INT_STATUS0 + i);
for_each_set_bit(j, &slimbus_value, BITS_PER_BYTE) {
val = wcd9xxx_interface_reg_read(codec->control_data,
TABLA_SLIM_PGD_PORT_INT_SOURCE0 + i*8 + j);
if (val & 0x1)
pr_err_ratelimited("overflow error on port %x,"
" value %x\n", i*8 + j, val);
if (val & 0x2)
pr_err_ratelimited("underflow error on port %x,"
" value %x\n", i*8 + j, val);
if (val & 0x4) {
port_id = i*8 + j;
for (k = 0; k < ARRAY_SIZE(tabla_dai); k++) {
ch_mask_temp = 1 << port_id;
pr_debug("%s: tabla_p->dai[%d].ch_mask = 0x%lx\n",
__func__, k,
tabla_p->dai[k].ch_mask);
if (ch_mask_temp &
tabla_p->dai[k].ch_mask) {
tabla_p->dai[k].ch_mask &=
~ch_mask_temp;
if (!tabla_p->dai[k].ch_mask)
wake_up(
&tabla_p->dai[k].dai_wait);
}
}
}
}
wcd9xxx_interface_reg_write(codec->control_data,
TABLA_SLIM_PGD_PORT_INT_CLR0 + i, slimbus_value);
val = 0x0;
}
return IRQ_HANDLED;
}
static int tabla_handle_pdata(struct tabla_priv *tabla)
{
struct snd_soc_codec *codec = tabla->codec;
struct wcd9xxx_pdata *pdata = tabla->pdata;
int k1, k2, k3, rc = 0;
u8 leg_mode = pdata->amic_settings.legacy_mode;
u8 txfe_bypass = pdata->amic_settings.txfe_enable;
u8 txfe_buff = pdata->amic_settings.txfe_buff;
u8 flag = pdata->amic_settings.use_pdata;
u8 i = 0, j = 0;
u8 val_txfe = 0, value = 0;
if (!pdata) {
rc = -ENODEV;
goto done;
}
/* Make sure settings are correct */
if ((pdata->micbias.ldoh_v > TABLA_LDOH_2P85_V) ||
(pdata->micbias.bias1_cfilt_sel > TABLA_CFILT3_SEL) ||
(pdata->micbias.bias2_cfilt_sel > TABLA_CFILT3_SEL) ||
(pdata->micbias.bias3_cfilt_sel > TABLA_CFILT3_SEL) ||
(pdata->micbias.bias4_cfilt_sel > TABLA_CFILT3_SEL)) {
rc = -EINVAL;
goto done;
}
/* figure out k value */
k1 = tabla_find_k_value(pdata->micbias.ldoh_v,
pdata->micbias.cfilt1_mv);
k2 = tabla_find_k_value(pdata->micbias.ldoh_v,
pdata->micbias.cfilt2_mv);
k3 = tabla_find_k_value(pdata->micbias.ldoh_v,
pdata->micbias.cfilt3_mv);
if (IS_ERR_VALUE(k1) || IS_ERR_VALUE(k2) || IS_ERR_VALUE(k3)) {
rc = -EINVAL;
goto done;
}
/* Set voltage level and always use LDO */
snd_soc_update_bits(codec, TABLA_A_LDO_H_MODE_1, 0x0C,
(pdata->micbias.ldoh_v << 2));
snd_soc_update_bits(codec, TABLA_A_MICB_CFILT_1_VAL, 0xFC,
(k1 << 2));
snd_soc_update_bits(codec, TABLA_A_MICB_CFILT_2_VAL, 0xFC,
(k2 << 2));
snd_soc_update_bits(codec, TABLA_A_MICB_CFILT_3_VAL, 0xFC,
(k3 << 2));
snd_soc_update_bits(codec, TABLA_A_MICB_1_CTL, 0x60,
(pdata->micbias.bias1_cfilt_sel << 5));
snd_soc_update_bits(codec, TABLA_A_MICB_2_CTL, 0x60,
(pdata->micbias.bias2_cfilt_sel << 5));
snd_soc_update_bits(codec, TABLA_A_MICB_3_CTL, 0x60,
(pdata->micbias.bias3_cfilt_sel << 5));
snd_soc_update_bits(codec, tabla->reg_addr.micb_4_ctl, 0x60,
(pdata->micbias.bias4_cfilt_sel << 5));
for (i = 0; i < 6; j++, i += 2) {
if (flag & (0x01 << i)) {
value = (leg_mode & (0x01 << i)) ? 0x10 : 0x00;
val_txfe = (txfe_bypass & (0x01 << i)) ? 0x20 : 0x00;
val_txfe = val_txfe |
((txfe_buff & (0x01 << i)) ? 0x10 : 0x00);
snd_soc_update_bits(codec, TABLA_A_TX_1_2_EN + j * 10,
0x10, value);
snd_soc_update_bits(codec,
TABLA_A_TX_1_2_TEST_EN + j * 10,
0x30, val_txfe);
}
if (flag & (0x01 << (i + 1))) {
value = (leg_mode & (0x01 << (i + 1))) ? 0x01 : 0x00;
val_txfe = (txfe_bypass &
(0x01 << (i + 1))) ? 0x02 : 0x00;
val_txfe |= (txfe_buff &
(0x01 << (i + 1))) ? 0x01 : 0x00;
snd_soc_update_bits(codec, TABLA_A_TX_1_2_EN + j * 10,
0x01, value);
snd_soc_update_bits(codec,
TABLA_A_TX_1_2_TEST_EN + j * 10,
0x03, val_txfe);
}
}
if (flag & 0x40) {
value = (leg_mode & 0x40) ? 0x10 : 0x00;
value = value | ((txfe_bypass & 0x40) ? 0x02 : 0x00);
value = value | ((txfe_buff & 0x40) ? 0x01 : 0x00);
snd_soc_update_bits(codec, TABLA_A_TX_7_MBHC_EN,
0x13, value);
}
if (pdata->ocp.use_pdata) {
/* not defined in CODEC specification */
if (pdata->ocp.hph_ocp_limit == 1 ||
pdata->ocp.hph_ocp_limit == 5) {
rc = -EINVAL;
goto done;
}
snd_soc_update_bits(codec, TABLA_A_RX_COM_OCP_CTL,
0x0F, pdata->ocp.num_attempts);
snd_soc_write(codec, TABLA_A_RX_COM_OCP_COUNT,
((pdata->ocp.run_time << 4) | pdata->ocp.wait_time));
snd_soc_update_bits(codec, TABLA_A_RX_HPH_OCP_CTL,
0xE0, (pdata->ocp.hph_ocp_limit << 5));
}
for (i = 0; i < ARRAY_SIZE(pdata->regulator); i++) {
if (!strncmp(pdata->regulator[i].name, "CDC_VDDA_RX", 11)) {
if (pdata->regulator[i].min_uV == 1800000 &&
pdata->regulator[i].max_uV == 1800000) {
snd_soc_write(codec, TABLA_A_BIAS_REF_CTL,
0x1C);
} else if (pdata->regulator[i].min_uV == 2200000 &&
pdata->regulator[i].max_uV == 2200000) {
snd_soc_write(codec, TABLA_A_BIAS_REF_CTL,
0x1E);
} else {
pr_err("%s: unsupported CDC_VDDA_RX voltage "
"min %d, max %d\n", __func__,
pdata->regulator[i].min_uV,
pdata->regulator[i].max_uV);
rc = -EINVAL;
}
break;
}
}
done:
return rc;
}
static const struct tabla_reg_mask_val tabla_1_1_reg_defaults[] = {
/* Tabla 1.1 MICBIAS changes */
TABLA_REG_VAL(TABLA_A_MICB_1_INT_RBIAS, 0x24),
TABLA_REG_VAL(TABLA_A_MICB_2_INT_RBIAS, 0x24),
TABLA_REG_VAL(TABLA_A_MICB_3_INT_RBIAS, 0x24),
/* Tabla 1.1 HPH changes */
TABLA_REG_VAL(TABLA_A_RX_HPH_BIAS_PA, 0x57),
TABLA_REG_VAL(TABLA_A_RX_HPH_BIAS_LDO, 0x56),
/* Tabla 1.1 EAR PA changes */
TABLA_REG_VAL(TABLA_A_RX_EAR_BIAS_PA, 0xA6),
TABLA_REG_VAL(TABLA_A_RX_EAR_GAIN, 0x02),
TABLA_REG_VAL(TABLA_A_RX_EAR_VCM, 0x03),
/* Tabla 1.1 Lineout_5 Changes */
TABLA_REG_VAL(TABLA_A_RX_LINE_5_GAIN, 0x10),
/* Tabla 1.1 RX Changes */
TABLA_REG_VAL(TABLA_A_CDC_RX1_B5_CTL, 0x78),
TABLA_REG_VAL(TABLA_A_CDC_RX2_B5_CTL, 0x78),
TABLA_REG_VAL(TABLA_A_CDC_RX3_B5_CTL, 0x78),
TABLA_REG_VAL(TABLA_A_CDC_RX4_B5_CTL, 0x78),
TABLA_REG_VAL(TABLA_A_CDC_RX5_B5_CTL, 0x78),
TABLA_REG_VAL(TABLA_A_CDC_RX6_B5_CTL, 0x78),
TABLA_REG_VAL(TABLA_A_CDC_RX7_B5_CTL, 0x78),
/* Tabla 1.1 RX1 and RX2 Changes */
TABLA_REG_VAL(TABLA_A_CDC_RX1_B6_CTL, 0xA0),
TABLA_REG_VAL(TABLA_A_CDC_RX2_B6_CTL, 0xA0),
/* Tabla 1.1 RX3 to RX7 Changes */
TABLA_REG_VAL(TABLA_A_CDC_RX3_B6_CTL, 0x80),
TABLA_REG_VAL(TABLA_A_CDC_RX4_B6_CTL, 0x80),
TABLA_REG_VAL(TABLA_A_CDC_RX5_B6_CTL, 0x80),
TABLA_REG_VAL(TABLA_A_CDC_RX6_B6_CTL, 0x80),
TABLA_REG_VAL(TABLA_A_CDC_RX7_B6_CTL, 0x80),
/* Tabla 1.1 CLASSG Changes */
TABLA_REG_VAL(TABLA_A_CDC_CLSG_FREQ_THRESH_B3_CTL, 0x1B),
};
static const struct tabla_reg_mask_val tabla_2_0_reg_defaults[] = {
/* Tabla 2.0 MICBIAS changes */
TABLA_REG_VAL(TABLA_A_MICB_2_MBHC, 0x02),
};
static const struct tabla_reg_mask_val tabla_1_x_only_reg_2_0_defaults[] = {
TABLA_REG_VAL(TABLA_1_A_MICB_4_INT_RBIAS, 0x24),
};
static const struct tabla_reg_mask_val tabla_2_only_reg_2_0_defaults[] = {
TABLA_REG_VAL(TABLA_2_A_MICB_4_INT_RBIAS, 0x24),
};
static void tabla_update_reg_defaults(struct snd_soc_codec *codec)
{
u32 i;
struct wcd9xxx *tabla_core = dev_get_drvdata(codec->dev->parent);
for (i = 0; i < ARRAY_SIZE(tabla_1_1_reg_defaults); i++)
snd_soc_write(codec, tabla_1_1_reg_defaults[i].reg,
tabla_1_1_reg_defaults[i].val);
for (i = 0; i < ARRAY_SIZE(tabla_2_0_reg_defaults); i++)
snd_soc_write(codec, tabla_2_0_reg_defaults[i].reg,
tabla_2_0_reg_defaults[i].val);
if (TABLA_IS_1_X(tabla_core->version)) {
for (i = 0; i < ARRAY_SIZE(tabla_1_x_only_reg_2_0_defaults);
i++)
snd_soc_write(codec,
tabla_1_x_only_reg_2_0_defaults[i].reg,
tabla_1_x_only_reg_2_0_defaults[i].val);
} else {
for (i = 0; i < ARRAY_SIZE(tabla_2_only_reg_2_0_defaults); i++)
snd_soc_write(codec,
tabla_2_only_reg_2_0_defaults[i].reg,
tabla_2_only_reg_2_0_defaults[i].val);
}
}
static const struct tabla_reg_mask_val tabla_codec_reg_init_val[] = {
/* Initialize current threshold to 350MA
* number of wait and run cycles to 4096
*/
{TABLA_A_RX_HPH_OCP_CTL, 0xE0, 0x60},
{TABLA_A_RX_COM_OCP_COUNT, 0xFF, 0xFF},
{TABLA_A_QFUSE_CTL, 0xFF, 0x03},
/* Initialize gain registers to use register gain */
{TABLA_A_RX_HPH_L_GAIN, 0x10, 0x10},
{TABLA_A_RX_HPH_R_GAIN, 0x10, 0x10},
{TABLA_A_RX_LINE_1_GAIN, 0x10, 0x10},
{TABLA_A_RX_LINE_2_GAIN, 0x10, 0x10},
{TABLA_A_RX_LINE_3_GAIN, 0x10, 0x10},
{TABLA_A_RX_LINE_4_GAIN, 0x10, 0x10},
/* Set the MICBIAS default output as pull down*/
{TABLA_A_MICB_1_CTL, 0x01, 0x01},
{TABLA_A_MICB_2_CTL, 0x01, 0x01},
{TABLA_A_MICB_3_CTL, 0x01, 0x01},
/* Initialize mic biases to differential mode */
{TABLA_A_MICB_1_INT_RBIAS, 0x24, 0x24},
{TABLA_A_MICB_2_INT_RBIAS, 0x24, 0x24},
{TABLA_A_MICB_3_INT_RBIAS, 0x24, 0x24},
{TABLA_A_CDC_CONN_CLSG_CTL, 0x3C, 0x14},
/* Use 16 bit sample size for TX1 to TX6 */
{TABLA_A_CDC_CONN_TX_SB_B1_CTL, 0x30, 0x20},
{TABLA_A_CDC_CONN_TX_SB_B2_CTL, 0x30, 0x20},
{TABLA_A_CDC_CONN_TX_SB_B3_CTL, 0x30, 0x20},
{TABLA_A_CDC_CONN_TX_SB_B4_CTL, 0x30, 0x20},
{TABLA_A_CDC_CONN_TX_SB_B5_CTL, 0x30, 0x20},
{TABLA_A_CDC_CONN_TX_SB_B6_CTL, 0x30, 0x20},
/* Use 16 bit sample size for TX7 to TX10 */
{TABLA_A_CDC_CONN_TX_SB_B7_CTL, 0x60, 0x40},
{TABLA_A_CDC_CONN_TX_SB_B8_CTL, 0x60, 0x40},
{TABLA_A_CDC_CONN_TX_SB_B9_CTL, 0x60, 0x40},
{TABLA_A_CDC_CONN_TX_SB_B10_CTL, 0x60, 0x40},
/* Use 16 bit sample size for RX */
{TABLA_A_CDC_CONN_RX_SB_B1_CTL, 0xFF, 0xAA},
{TABLA_A_CDC_CONN_RX_SB_B2_CTL, 0xFF, 0xAA},
/*enable HPF filter for TX paths */
{TABLA_A_CDC_TX1_MUX_CTL, 0x8, 0x0},
{TABLA_A_CDC_TX2_MUX_CTL, 0x8, 0x0},
{TABLA_A_CDC_TX3_MUX_CTL, 0x8, 0x0},
{TABLA_A_CDC_TX4_MUX_CTL, 0x8, 0x0},
{TABLA_A_CDC_TX5_MUX_CTL, 0x8, 0x0},
{TABLA_A_CDC_TX6_MUX_CTL, 0x8, 0x0},
{TABLA_A_CDC_TX7_MUX_CTL, 0x8, 0x0},
{TABLA_A_CDC_TX8_MUX_CTL, 0x8, 0x0},
{TABLA_A_CDC_TX9_MUX_CTL, 0x8, 0x0},
{TABLA_A_CDC_TX10_MUX_CTL, 0x8, 0x0},
/* config Decimator for DMIC CLK_MODE_1(3.072Mhz@12.88Mhz mclk) */
{TABLA_A_CDC_TX1_DMIC_CTL, 0x1, 0x1},
{TABLA_A_CDC_TX2_DMIC_CTL, 0x1, 0x1},
{TABLA_A_CDC_TX3_DMIC_CTL, 0x1, 0x1},
{TABLA_A_CDC_TX4_DMIC_CTL, 0x1, 0x1},
{TABLA_A_CDC_TX5_DMIC_CTL, 0x1, 0x1},
{TABLA_A_CDC_TX6_DMIC_CTL, 0x1, 0x1},
{TABLA_A_CDC_TX7_DMIC_CTL, 0x1, 0x1},
{TABLA_A_CDC_TX8_DMIC_CTL, 0x1, 0x1},
{TABLA_A_CDC_TX9_DMIC_CTL, 0x1, 0x1},
{TABLA_A_CDC_TX10_DMIC_CTL, 0x1, 0x1},
/* config DMIC clk to CLK_MODE_1 (3.072Mhz@12.88Mhz mclk) */
{TABLA_A_CDC_CLK_DMIC_CTL, 0x2A, 0x2A},
};
static const struct tabla_reg_mask_val tabla_1_x_codec_reg_init_val[] = {
/* Set the MICBIAS default output as pull down*/
{TABLA_1_A_MICB_4_CTL, 0x01, 0x01},
/* Initialize mic biases to differential mode */
{TABLA_1_A_MICB_4_INT_RBIAS, 0x24, 0x24},
};
static const struct tabla_reg_mask_val tabla_2_higher_codec_reg_init_val[] = {
/* Set the MICBIAS default output as pull down*/
{TABLA_2_A_MICB_4_CTL, 0x01, 0x01},
/* Initialize mic biases to differential mode */
{TABLA_2_A_MICB_4_INT_RBIAS, 0x24, 0x24},
};
static void tabla_codec_init_reg(struct snd_soc_codec *codec)
{
u32 i;
struct wcd9xxx *tabla_core = dev_get_drvdata(codec->dev->parent);
for (i = 0; i < ARRAY_SIZE(tabla_codec_reg_init_val); i++)
snd_soc_update_bits(codec, tabla_codec_reg_init_val[i].reg,
tabla_codec_reg_init_val[i].mask,
tabla_codec_reg_init_val[i].val);
if (TABLA_IS_1_X(tabla_core->version)) {
for (i = 0; i < ARRAY_SIZE(tabla_1_x_codec_reg_init_val); i++)
snd_soc_update_bits(codec,
tabla_1_x_codec_reg_init_val[i].reg,
tabla_1_x_codec_reg_init_val[i].mask,
tabla_1_x_codec_reg_init_val[i].val);
} else {
for (i = 0; i < ARRAY_SIZE(tabla_2_higher_codec_reg_init_val);
i++)
snd_soc_update_bits(codec,
tabla_2_higher_codec_reg_init_val[i].reg,
tabla_2_higher_codec_reg_init_val[i].mask,
tabla_2_higher_codec_reg_init_val[i].val);
}
snd_soc_update_bits(codec, TABLA_A_CDC_DMIC_CLK0_MODE, 0x7, 0x4);
snd_soc_update_bits(codec, TABLA_A_CDC_DMIC_CLK1_MODE, 0x7, 0x4);
snd_soc_update_bits(codec, TABLA_A_CDC_DMIC_CLK2_MODE, 0x7, 0x4);
snd_soc_update_bits(codec, TABLA_A_PIN_CTL_OE0, 0x90, 0x90);
snd_soc_update_bits(codec, TABLA_A_PIN_CTL_OE1, 0x8, 0x8);
snd_soc_update_bits(codec, TABLA_A_PIN_CTL_DATA0, 0x90, 0x0);
snd_soc_update_bits(codec, TABLA_A_PIN_CTL_DATA1, 0x8, 0x0);
}
static void tabla_update_reg_address(struct tabla_priv *priv)
{
struct wcd9xxx *tabla_core = dev_get_drvdata(priv->codec->dev->parent);
struct tabla_reg_address *reg_addr = &priv->reg_addr;
if (TABLA_IS_1_X(tabla_core->version)) {
reg_addr->micb_4_mbhc = TABLA_1_A_MICB_4_MBHC;
reg_addr->micb_4_int_rbias = TABLA_1_A_MICB_4_INT_RBIAS;
reg_addr->micb_4_ctl = TABLA_1_A_MICB_4_CTL;
} else if (TABLA_IS_2_0(tabla_core->version)) {
reg_addr->micb_4_mbhc = TABLA_2_A_MICB_4_MBHC;
reg_addr->micb_4_int_rbias = TABLA_2_A_MICB_4_INT_RBIAS;
reg_addr->micb_4_ctl = TABLA_2_A_MICB_4_CTL;
}
}
#ifdef CONFIG_DEBUG_FS
static int codec_debug_open(struct inode *inode, struct file *file)
{
file->private_data = inode->i_private;
return 0;
}
static ssize_t codec_debug_write(struct file *filp,
const char __user *ubuf, size_t cnt, loff_t *ppos)
{
char lbuf[32];
char *buf;
int rc;
struct tabla_priv *tabla = filp->private_data;
if (cnt > sizeof(lbuf) - 1)
return -EINVAL;
rc = copy_from_user(lbuf, ubuf, cnt);
if (rc)
return -EFAULT;
lbuf[cnt] = '\0';
buf = (char *)lbuf;
TABLA_ACQUIRE_LOCK(tabla->codec_resource_lock);
tabla->no_mic_headset_override =
(*strsep(&buf, " ") == '0') ? false : true;
if (tabla->no_mic_headset_override && tabla->mbhc_polling_active) {
tabla_codec_pause_hs_polling(tabla->codec);
tabla_codec_start_hs_polling(tabla->codec);
}
TABLA_RELEASE_LOCK(tabla->codec_resource_lock);
return cnt;
}
static ssize_t codec_mbhc_debug_read(struct file *file, char __user *buf,
size_t count, loff_t *pos)
{
const int size = 768;
char buffer[size];
int n = 0;
struct tabla_priv *tabla = file->private_data;
struct snd_soc_codec *codec = tabla->codec;
const struct mbhc_internal_cal_data *p = &tabla->mbhc_data;
const s16 v_ins_hu_cur = tabla_get_current_v_ins(tabla, true);
const s16 v_ins_h_cur = tabla_get_current_v_ins(tabla, false);
n = scnprintf(buffer, size - n, "dce_z = %x(%dmv)\n", p->dce_z,
tabla_codec_sta_dce_v(codec, 1, p->dce_z));
n += scnprintf(buffer + n, size - n, "dce_mb = %x(%dmv)\n",
p->dce_mb, tabla_codec_sta_dce_v(codec, 1, p->dce_mb));
n += scnprintf(buffer + n, size - n, "sta_z = %x(%dmv)\n",
p->sta_z, tabla_codec_sta_dce_v(codec, 0, p->sta_z));
n += scnprintf(buffer + n, size - n, "sta_mb = %x(%dmv)\n",
p->sta_mb, tabla_codec_sta_dce_v(codec, 0, p->sta_mb));
n += scnprintf(buffer + n, size - n, "t_dce = %x\n", p->t_dce);
n += scnprintf(buffer + n, size - n, "t_sta = %x\n", p->t_sta);
n += scnprintf(buffer + n, size - n, "micb_mv = %dmv\n",
p->micb_mv);
n += scnprintf(buffer + n, size - n, "v_ins_hu = %x(%dmv)%s\n",
p->v_ins_hu,
tabla_codec_sta_dce_v(codec, 0, p->v_ins_hu),
p->v_ins_hu == v_ins_hu_cur ? "*" : "");
n += scnprintf(buffer + n, size - n, "v_ins_h = %x(%dmv)%s\n",
p->v_ins_h, tabla_codec_sta_dce_v(codec, 1, p->v_ins_h),
p->v_ins_h == v_ins_h_cur ? "*" : "");
n += scnprintf(buffer + n, size - n, "adj_v_ins_hu = %x(%dmv)%s\n",
p->adj_v_ins_hu,
tabla_codec_sta_dce_v(codec, 0, p->adj_v_ins_hu),
p->adj_v_ins_hu == v_ins_hu_cur ? "*" : "");
n += scnprintf(buffer + n, size - n, "adj_v_ins_h = %x(%dmv)%s\n",
p->adj_v_ins_h,
tabla_codec_sta_dce_v(codec, 1, p->adj_v_ins_h),
p->adj_v_ins_h == v_ins_h_cur ? "*" : "");
n += scnprintf(buffer + n, size - n, "v_b1_hu = %x(%dmv)\n",
p->v_b1_hu, tabla_codec_sta_dce_v(codec, 0, p->v_b1_hu));
n += scnprintf(buffer + n, size - n, "v_b1_h = %x(%dmv)\n",
p->v_b1_h, tabla_codec_sta_dce_v(codec, 1, p->v_b1_h));
n += scnprintf(buffer + n, size - n, "v_b1_huc = %x(%dmv)\n",
p->v_b1_huc,
tabla_codec_sta_dce_v(codec, 1, p->v_b1_huc));
n += scnprintf(buffer + n, size - n, "v_brh = %x(%dmv)\n",
p->v_brh, tabla_codec_sta_dce_v(codec, 1, p->v_brh));
n += scnprintf(buffer + n, size - n, "v_brl = %x(%dmv)\n", p->v_brl,
tabla_codec_sta_dce_v(codec, 0, p->v_brl));
n += scnprintf(buffer + n, size - n, "v_no_mic = %x(%dmv)\n",
p->v_no_mic,
tabla_codec_sta_dce_v(codec, 0, p->v_no_mic));
n += scnprintf(buffer + n, size - n, "npoll = %d\n", p->npoll);
n += scnprintf(buffer + n, size - n, "nbounce_wait = %d\n",
p->nbounce_wait);
n += scnprintf(buffer + n, size - n, "v_inval_ins_low = %d\n",
p->v_inval_ins_low);
n += scnprintf(buffer + n, size - n, "v_inval_ins_high = %d\n",
p->v_inval_ins_high);
if (tabla->mbhc_cfg.gpio)
n += scnprintf(buffer + n, size - n, "GPIO insert = %d\n",
tabla_hs_gpio_level_remove(tabla));
buffer[n] = 0;
return simple_read_from_buffer(buf, count, pos, buffer, n);
}
static const struct file_operations codec_debug_ops = {
.open = codec_debug_open,
.write = codec_debug_write,
};
static const struct file_operations codec_mbhc_debug_ops = {
.open = codec_debug_open,
.read = codec_mbhc_debug_read,
};
#endif
static int tabla_codec_probe(struct snd_soc_codec *codec)
{
struct wcd9xxx *control;
struct tabla_priv *tabla;
struct snd_soc_dapm_context *dapm = &codec->dapm;
int ret = 0;
int i;
void *ptr = NULL;
struct wcd9xxx_core_resource *core_res;
codec->control_data = dev_get_drvdata(codec->dev->parent);
control = codec->control_data;
core_res = &control->core_res;
tabla = kzalloc(sizeof(struct tabla_priv), GFP_KERNEL);
if (!tabla) {
dev_err(codec->dev, "Failed to allocate private data\n");
return -ENOMEM;
}
for (i = 0 ; i < NUM_DECIMATORS; i++) {
tx_hpf_work[i].tabla = tabla;
tx_hpf_work[i].decimator = i + 1;
INIT_DELAYED_WORK(&tx_hpf_work[i].dwork,
tx_hpf_corner_freq_callback);
}
/* Make sure mbhc micbias register addresses are zeroed out */
memset(&tabla->mbhc_bias_regs, 0,
sizeof(struct mbhc_micbias_regs));
tabla->mbhc_micbias_switched = false;
/* Make sure mbhc intenal calibration data is zeroed out */
memset(&tabla->mbhc_data, 0,
sizeof(struct mbhc_internal_cal_data));
tabla->mbhc_data.t_sta_dce = DEFAULT_DCE_STA_WAIT;
tabla->mbhc_data.t_dce = DEFAULT_DCE_WAIT;
tabla->mbhc_data.t_sta = DEFAULT_STA_WAIT;
snd_soc_codec_set_drvdata(codec, tabla);
tabla->mclk_enabled = false;
tabla->bandgap_type = TABLA_BANDGAP_OFF;
tabla->clock_active = false;
tabla->config_mode_active = false;
tabla->mbhc_polling_active = false;
tabla->mbhc_fake_ins_start = 0;
tabla->no_mic_headset_override = false;
tabla->hs_polling_irq_prepared = false;
mutex_init(&tabla->codec_resource_lock);
tabla->codec = codec;
tabla->mbhc_state = MBHC_STATE_NONE;
tabla->mbhc_last_resume = 0;
for (i = 0; i < COMPANDER_MAX; i++) {
tabla->comp_enabled[i] = 0;
tabla->comp_fs[i] = COMPANDER_FS_48KHZ;
}
tabla->pdata = dev_get_platdata(codec->dev->parent);
tabla->intf_type = wcd9xxx_get_intf_type();
tabla->aux_pga_cnt = 0;
tabla->aux_l_gain = 0x1F;
tabla->aux_r_gain = 0x1F;
tabla_update_reg_address(tabla);
tabla_update_reg_defaults(codec);
tabla_codec_init_reg(codec);
ret = tabla_handle_pdata(tabla);
if (IS_ERR_VALUE(ret)) {
pr_err("%s: bad pdata\n", __func__);
goto err_pdata;
}
if (TABLA_IS_1_X(control->version))
snd_soc_add_codec_controls(codec, tabla_1_x_snd_controls,
ARRAY_SIZE(tabla_1_x_snd_controls));
else
snd_soc_add_codec_controls(codec, tabla_2_higher_snd_controls,
ARRAY_SIZE(tabla_2_higher_snd_controls));
if (TABLA_IS_1_X(control->version))
snd_soc_dapm_new_controls(dapm, tabla_1_x_dapm_widgets,
ARRAY_SIZE(tabla_1_x_dapm_widgets));
else
snd_soc_dapm_new_controls(dapm, tabla_2_higher_dapm_widgets,
ARRAY_SIZE(tabla_2_higher_dapm_widgets));
ptr = kmalloc((sizeof(tabla_rx_chs) +
sizeof(tabla_tx_chs)), GFP_KERNEL);
if (!ptr) {
pr_err("%s: no mem for slim chan ctl data\n", __func__);
ret = -ENOMEM;
goto err_nomem_slimch;
}
if (tabla->intf_type == WCD9XXX_INTERFACE_TYPE_I2C) {
snd_soc_dapm_new_controls(dapm, tabla_dapm_i2s_widgets,
ARRAY_SIZE(tabla_dapm_i2s_widgets));
snd_soc_dapm_add_routes(dapm, audio_i2s_map,
ARRAY_SIZE(audio_i2s_map));
for (i = 0; i < ARRAY_SIZE(tabla_i2s_dai); i++)
INIT_LIST_HEAD(&tabla->dai[i].wcd9xxx_ch_list);
} else if (tabla->intf_type == WCD9XXX_INTERFACE_TYPE_SLIMBUS) {
for (i = 0; i < NUM_CODEC_DAIS; i++) {
INIT_LIST_HEAD(&tabla->dai[i].wcd9xxx_ch_list);
init_waitqueue_head(&tabla->dai[i].dai_wait);
}
}
control->num_rx_port = TABLA_RX_MAX;
control->rx_chs = ptr;
memcpy(control->rx_chs, tabla_rx_chs, sizeof(tabla_rx_chs));
control->num_tx_port = TABLA_TX_MAX;
control->tx_chs = ptr + sizeof(tabla_rx_chs);
memcpy(control->tx_chs, tabla_tx_chs, sizeof(tabla_tx_chs));
if (TABLA_IS_1_X(control->version)) {
snd_soc_dapm_add_routes(dapm, tabla_1_x_lineout_2_to_4_map,
ARRAY_SIZE(tabla_1_x_lineout_2_to_4_map));
} else if (TABLA_IS_2_0(control->version)) {
snd_soc_dapm_add_routes(dapm, tabla_2_x_lineout_2_to_4_map,
ARRAY_SIZE(tabla_2_x_lineout_2_to_4_map));
} else {
pr_err("%s : ERROR. Unsupported Tabla version 0x%2x\n",
__func__, control->version);
goto err_pdata;
}
snd_soc_dapm_sync(dapm);
ret = wcd9xxx_request_irq(core_res,
WCD9XXX_IRQ_MBHC_INSERTION,
tabla_hs_insert_irq, "Headset insert detect", tabla);
if (ret) {
pr_err("%s: Failed to request irq %d\n", __func__,
WCD9XXX_IRQ_MBHC_INSERTION);
goto err_insert_irq;
}
wcd9xxx_disable_irq(core_res, WCD9XXX_IRQ_MBHC_INSERTION);
ret = wcd9xxx_request_irq(core_res,
WCD9XXX_IRQ_MBHC_REMOVAL,
tabla_hs_remove_irq,
"Headset remove detect", tabla);
if (ret) {
pr_err("%s: Failed to request irq %d\n", __func__,
WCD9XXX_IRQ_MBHC_REMOVAL);
goto err_remove_irq;
}
ret = wcd9xxx_request_irq(core_res,
WCD9XXX_IRQ_MBHC_POTENTIAL,
tabla_dce_handler, "DC Estimation detect",
tabla);
if (ret) {
pr_err("%s: Failed to request irq %d\n", __func__,
WCD9XXX_IRQ_MBHC_POTENTIAL);
goto err_potential_irq;
}
ret = wcd9xxx_request_irq(core_res, WCD9XXX_IRQ_MBHC_RELEASE,
tabla_release_handler,
"Button Release detect", tabla);
if (ret) {
pr_err("%s: Failed to request irq %d\n", __func__,
WCD9XXX_IRQ_MBHC_RELEASE);
goto err_release_irq;
}
ret = wcd9xxx_request_irq(core_res, WCD9XXX_IRQ_SLIMBUS,
tabla_slimbus_irq, "SLIMBUS Slave", tabla);
if (ret) {
pr_err("%s: Failed to request irq %d\n", __func__,
WCD9XXX_IRQ_SLIMBUS);
goto err_slimbus_irq;
}
for (i = 0; i < WCD9XXX_SLIM_NUM_PORT_REG; i++)
wcd9xxx_interface_reg_write(control,
TABLA_SLIM_PGD_PORT_INT_EN0 + i, 0xFF);
ret = wcd9xxx_request_irq(core_res,
WCD9XXX_IRQ_HPH_PA_OCPL_FAULT,
tabla_hphl_ocp_irq,
"HPH_L OCP detect", tabla);
if (ret) {
pr_err("%s: Failed to request irq %d\n", __func__,
WCD9XXX_IRQ_HPH_PA_OCPL_FAULT);
goto err_hphl_ocp_irq;
}
wcd9xxx_disable_irq(core_res, WCD9XXX_IRQ_HPH_PA_OCPL_FAULT);
ret = wcd9xxx_request_irq(core_res,
WCD9XXX_IRQ_HPH_PA_OCPR_FAULT,
tabla_hphr_ocp_irq,
"HPH_R OCP detect", tabla);
if (ret) {
pr_err("%s: Failed to request irq %d\n", __func__,
WCD9XXX_IRQ_HPH_PA_OCPR_FAULT);
goto err_hphr_ocp_irq;
}
wcd9xxx_disable_irq(core_res, WCD9XXX_IRQ_HPH_PA_OCPR_FAULT);
/*
* Register suspend lock and notifier to resend edge triggered
* gpio IRQs
*/
wake_lock_init(&tabla->irq_resend_wlock, WAKE_LOCK_SUSPEND,
"tabla_gpio_irq_resend");
tabla->gpio_irq_resend = false;
mutex_lock(&dapm->codec->mutex);
snd_soc_dapm_disable_pin(dapm, "ANC HPHL");
snd_soc_dapm_disable_pin(dapm, "ANC HPHR");
snd_soc_dapm_disable_pin(dapm, "ANC HEADPHONE");
snd_soc_dapm_sync(dapm);
mutex_unlock(&dapm->codec->mutex);
#ifdef CONFIG_DEBUG_FS
if (ret == 0) {
tabla->debugfs_poke =
debugfs_create_file("TRRS", S_IFREG | S_IRUGO, NULL, tabla,
&codec_debug_ops);
tabla->debugfs_mbhc =
debugfs_create_file("tabla_mbhc", S_IFREG | S_IRUGO,
NULL, tabla, &codec_mbhc_debug_ops);
}
#endif
codec->ignore_pmdown_time = 1;
return ret;
err_hphr_ocp_irq:
wcd9xxx_free_irq(core_res,
WCD9XXX_IRQ_HPH_PA_OCPL_FAULT, tabla);
err_hphl_ocp_irq:
wcd9xxx_free_irq(core_res, WCD9XXX_IRQ_SLIMBUS, tabla);
err_slimbus_irq:
wcd9xxx_free_irq(core_res, WCD9XXX_IRQ_MBHC_RELEASE, tabla);
err_release_irq:
wcd9xxx_free_irq(core_res, WCD9XXX_IRQ_MBHC_POTENTIAL,
tabla);
err_potential_irq:
wcd9xxx_free_irq(core_res, WCD9XXX_IRQ_MBHC_REMOVAL, tabla);
err_remove_irq:
wcd9xxx_free_irq(core_res, WCD9XXX_IRQ_MBHC_INSERTION,
tabla);
err_insert_irq:
err_pdata:
kfree(ptr);
err_nomem_slimch:
mutex_destroy(&tabla->codec_resource_lock);
kfree(tabla);
return ret;
}
static int tabla_codec_remove(struct snd_soc_codec *codec)
{
struct tabla_priv *tabla = snd_soc_codec_get_drvdata(codec);
wake_lock_destroy(&tabla->irq_resend_wlock);
wcd9xxx_free_irq(codec->control_data, WCD9XXX_IRQ_SLIMBUS, tabla);
wcd9xxx_free_irq(codec->control_data, WCD9XXX_IRQ_MBHC_RELEASE, tabla);
wcd9xxx_free_irq(codec->control_data, WCD9XXX_IRQ_MBHC_POTENTIAL,
tabla);
wcd9xxx_free_irq(codec->control_data, WCD9XXX_IRQ_MBHC_REMOVAL, tabla);
wcd9xxx_free_irq(codec->control_data, WCD9XXX_IRQ_MBHC_INSERTION,
tabla);
TABLA_ACQUIRE_LOCK(tabla->codec_resource_lock);
tabla_codec_disable_clock_block(codec);
TABLA_RELEASE_LOCK(tabla->codec_resource_lock);
tabla_codec_enable_bandgap(codec, TABLA_BANDGAP_OFF);
if (tabla->mbhc_fw)
release_firmware(tabla->mbhc_fw);
mutex_destroy(&tabla->codec_resource_lock);
#ifdef CONFIG_DEBUG_FS
debugfs_remove(tabla->debugfs_poke);
debugfs_remove(tabla->debugfs_mbhc);
#endif
kfree(tabla);
return 0;
}
static struct snd_soc_codec_driver soc_codec_dev_tabla = {
.probe = tabla_codec_probe,
.remove = tabla_codec_remove,
.read = tabla_read,
.write = tabla_write,
.readable_register = tabla_readable,
.volatile_register = tabla_volatile,
.reg_cache_size = TABLA_CACHE_SIZE,
.reg_cache_default = tabla_reg_defaults,
.reg_word_size = 1,
.controls = tabla_snd_controls,
.num_controls = ARRAY_SIZE(tabla_snd_controls),
.dapm_widgets = tabla_dapm_widgets,
.num_dapm_widgets = ARRAY_SIZE(tabla_dapm_widgets),
.dapm_routes = audio_map,
.num_dapm_routes = ARRAY_SIZE(audio_map),
};
#ifdef CONFIG_PM
static int tabla_suspend(struct device *dev)
{
dev_dbg(dev, "%s: system suspend\n", __func__);
return 0;
}
static int tabla_resume(struct device *dev)
{
int irq;
struct platform_device *pdev = to_platform_device(dev);
struct tabla_priv *tabla = platform_get_drvdata(pdev);
dev_dbg(dev, "%s: system resume tabla %p\n", __func__, tabla);
if (tabla) {
TABLA_ACQUIRE_LOCK(tabla->codec_resource_lock);
tabla->mbhc_last_resume = jiffies;
if (tabla->gpio_irq_resend) {
WARN_ON(!tabla->mbhc_cfg.gpio_irq);
tabla->gpio_irq_resend = false;
irq = tabla->mbhc_cfg.gpio_irq;
pr_debug("%s: Resending GPIO IRQ %d\n", __func__, irq);
irq_set_pending(irq);
check_irq_resend(irq_to_desc(irq), irq);
/* release suspend lock */
wake_unlock(&tabla->irq_resend_wlock);
}
TABLA_RELEASE_LOCK(tabla->codec_resource_lock);
}
return 0;
}
static const struct dev_pm_ops tabla_pm_ops = {
.suspend = tabla_suspend,
.resume = tabla_resume,
};
#endif
static int __devinit tabla_probe(struct platform_device *pdev)
{
int ret = 0;
pr_err("tabla_probe\n");
if (wcd9xxx_get_intf_type() == WCD9XXX_INTERFACE_TYPE_SLIMBUS)
ret = snd_soc_register_codec(&pdev->dev, &soc_codec_dev_tabla,
tabla_dai, ARRAY_SIZE(tabla_dai));
else if (wcd9xxx_get_intf_type() == WCD9XXX_INTERFACE_TYPE_I2C)
ret = snd_soc_register_codec(&pdev->dev, &soc_codec_dev_tabla,
tabla_i2s_dai, ARRAY_SIZE(tabla_i2s_dai));
return ret;
}
static int __devexit tabla_remove(struct platform_device *pdev)
{
snd_soc_unregister_codec(&pdev->dev);
return 0;
}
static struct platform_driver tabla_codec_driver = {
.probe = tabla_probe,
.remove = tabla_remove,
.driver = {
.name = "tabla_codec",
.owner = THIS_MODULE,
#ifdef CONFIG_PM
.pm = &tabla_pm_ops,
#endif
},
};
static struct platform_driver tabla1x_codec_driver = {
.probe = tabla_probe,
.remove = tabla_remove,
.driver = {
.name = "tabla1x_codec",
.owner = THIS_MODULE,
#ifdef CONFIG_PM
.pm = &tabla_pm_ops,
#endif
},
};
static int __init tabla_codec_init(void)
{
int rtn = platform_driver_register(&tabla_codec_driver);
if (rtn == 0) {
rtn = platform_driver_register(&tabla1x_codec_driver);
if (rtn != 0)
platform_driver_unregister(&tabla_codec_driver);
}
return rtn;
}
static void __exit tabla_codec_exit(void)
{
platform_driver_unregister(&tabla1x_codec_driver);
platform_driver_unregister(&tabla_codec_driver);
}
module_init(tabla_codec_init);
module_exit(tabla_codec_exit);
MODULE_DESCRIPTION("Tabla codec driver");
MODULE_VERSION("1.0");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
Gawainli/HelloCocos2dx | cocos2d/cocos/renderer/CCGroupCommand.cpp | 114 | 2748 | /****************************************************************************
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, 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 "renderer/CCGroupCommand.h"
#include "renderer/CCRenderer.h"
#include "base/CCDirector.h"
NS_CC_BEGIN
GroupCommandManager::GroupCommandManager()
{
}
GroupCommandManager::~GroupCommandManager()
{
}
bool GroupCommandManager::init()
{
//0 is the default render group
_groupMapping[0] = true;
return true;
}
int GroupCommandManager::getGroupID()
{
//Reuse old id
for(auto it = _groupMapping.begin(); it != _groupMapping.end(); ++it)
{
if(!it->second)
{
_groupMapping[it->first] = true;
return it->first;
}
}
//Create new ID
// int newID = _groupMapping.size();
int newID = Director::getInstance()->getRenderer()->createRenderQueue();
_groupMapping[newID] = true;
return newID;
}
void GroupCommandManager::releaseGroupID(int groupID)
{
_groupMapping[groupID] = false;
}
GroupCommand::GroupCommand()
{
_type = RenderCommand::Type::GROUP_COMMAND;
_renderQueueID = Director::getInstance()->getRenderer()->getGroupCommandManager()->getGroupID();
}
void GroupCommand::init(float globalOrder)
{
_globalOrder = globalOrder;
auto manager = Director::getInstance()->getRenderer()->getGroupCommandManager();
manager->releaseGroupID(_renderQueueID);
_renderQueueID = manager->getGroupID();
}
GroupCommand::~GroupCommand()
{
Director::getInstance()->getRenderer()->getGroupCommandManager()->releaseGroupID(_renderQueueID);
}
NS_CC_END
| gpl-2.0 |
admiralspark/NT-sparkkernel | arch/x86/kernel/uv_irq.c | 882 | 7291 | /*
* 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.
*
* SGI UV IRQ functions
*
* Copyright (C) 2008 Silicon Graphics, Inc. All rights reserved.
*/
#include <linux/module.h>
#include <linux/rbtree.h>
#include <linux/slab.h>
#include <linux/irq.h>
#include <asm/apic.h>
#include <asm/uv/uv_irq.h>
#include <asm/uv/uv_hub.h>
/* MMR offset and pnode of hub sourcing interrupts for a given irq */
struct uv_irq_2_mmr_pnode{
struct rb_node list;
unsigned long offset;
int pnode;
int irq;
};
static spinlock_t uv_irq_lock;
static struct rb_root uv_irq_root;
static int uv_set_irq_affinity(unsigned int, const struct cpumask *);
static void uv_noop(unsigned int irq)
{
}
static unsigned int uv_noop_ret(unsigned int irq)
{
return 0;
}
static void uv_ack_apic(unsigned int irq)
{
ack_APIC_irq();
}
static struct irq_chip uv_irq_chip = {
.name = "UV-CORE",
.startup = uv_noop_ret,
.shutdown = uv_noop,
.enable = uv_noop,
.disable = uv_noop,
.ack = uv_noop,
.mask = uv_noop,
.unmask = uv_noop,
.eoi = uv_ack_apic,
.end = uv_noop,
.set_affinity = uv_set_irq_affinity,
};
/*
* Add offset and pnode information of the hub sourcing interrupts to the
* rb tree for a specific irq.
*/
static int uv_set_irq_2_mmr_info(int irq, unsigned long offset, unsigned blade)
{
struct rb_node **link = &uv_irq_root.rb_node;
struct rb_node *parent = NULL;
struct uv_irq_2_mmr_pnode *n;
struct uv_irq_2_mmr_pnode *e;
unsigned long irqflags;
n = kmalloc_node(sizeof(struct uv_irq_2_mmr_pnode), GFP_KERNEL,
uv_blade_to_memory_nid(blade));
if (!n)
return -ENOMEM;
n->irq = irq;
n->offset = offset;
n->pnode = uv_blade_to_pnode(blade);
spin_lock_irqsave(&uv_irq_lock, irqflags);
/* Find the right place in the rbtree: */
while (*link) {
parent = *link;
e = rb_entry(parent, struct uv_irq_2_mmr_pnode, list);
if (unlikely(irq == e->irq)) {
/* irq entry exists */
e->pnode = uv_blade_to_pnode(blade);
e->offset = offset;
spin_unlock_irqrestore(&uv_irq_lock, irqflags);
kfree(n);
return 0;
}
if (irq < e->irq)
link = &(*link)->rb_left;
else
link = &(*link)->rb_right;
}
/* Insert the node into the rbtree. */
rb_link_node(&n->list, parent, link);
rb_insert_color(&n->list, &uv_irq_root);
spin_unlock_irqrestore(&uv_irq_lock, irqflags);
return 0;
}
/* Retrieve offset and pnode information from the rb tree for a specific irq */
int uv_irq_2_mmr_info(int irq, unsigned long *offset, int *pnode)
{
struct uv_irq_2_mmr_pnode *e;
struct rb_node *n;
unsigned long irqflags;
spin_lock_irqsave(&uv_irq_lock, irqflags);
n = uv_irq_root.rb_node;
while (n) {
e = rb_entry(n, struct uv_irq_2_mmr_pnode, list);
if (e->irq == irq) {
*offset = e->offset;
*pnode = e->pnode;
spin_unlock_irqrestore(&uv_irq_lock, irqflags);
return 0;
}
if (irq < e->irq)
n = n->rb_left;
else
n = n->rb_right;
}
spin_unlock_irqrestore(&uv_irq_lock, irqflags);
return -1;
}
/*
* Re-target the irq to the specified CPU and enable the specified MMR located
* on the specified blade to allow the sending of MSIs to the specified CPU.
*/
static int
arch_enable_uv_irq(char *irq_name, unsigned int irq, int cpu, int mmr_blade,
unsigned long mmr_offset, int limit)
{
const struct cpumask *eligible_cpu = cpumask_of(cpu);
struct irq_desc *desc = irq_to_desc(irq);
struct irq_cfg *cfg;
int mmr_pnode;
unsigned long mmr_value;
struct uv_IO_APIC_route_entry *entry;
int err;
BUILD_BUG_ON(sizeof(struct uv_IO_APIC_route_entry) !=
sizeof(unsigned long));
cfg = irq_cfg(irq);
err = assign_irq_vector(irq, cfg, eligible_cpu);
if (err != 0)
return err;
if (limit == UV_AFFINITY_CPU)
desc->status |= IRQ_NO_BALANCING;
else
desc->status |= IRQ_MOVE_PCNTXT;
set_irq_chip_and_handler_name(irq, &uv_irq_chip, handle_percpu_irq,
irq_name);
mmr_value = 0;
entry = (struct uv_IO_APIC_route_entry *)&mmr_value;
entry->vector = cfg->vector;
entry->delivery_mode = apic->irq_delivery_mode;
entry->dest_mode = apic->irq_dest_mode;
entry->polarity = 0;
entry->trigger = 0;
entry->mask = 0;
entry->dest = apic->cpu_mask_to_apicid(eligible_cpu);
mmr_pnode = uv_blade_to_pnode(mmr_blade);
uv_write_global_mmr64(mmr_pnode, mmr_offset, mmr_value);
if (cfg->move_in_progress)
send_cleanup_vector(cfg);
return irq;
}
/*
* Disable the specified MMR located on the specified blade so that MSIs are
* longer allowed to be sent.
*/
static void arch_disable_uv_irq(int mmr_pnode, unsigned long mmr_offset)
{
unsigned long mmr_value;
struct uv_IO_APIC_route_entry *entry;
BUILD_BUG_ON(sizeof(struct uv_IO_APIC_route_entry) !=
sizeof(unsigned long));
mmr_value = 0;
entry = (struct uv_IO_APIC_route_entry *)&mmr_value;
entry->mask = 1;
uv_write_global_mmr64(mmr_pnode, mmr_offset, mmr_value);
}
static int uv_set_irq_affinity(unsigned int irq, const struct cpumask *mask)
{
struct irq_desc *desc = irq_to_desc(irq);
struct irq_cfg *cfg = desc->chip_data;
unsigned int dest;
unsigned long mmr_value;
struct uv_IO_APIC_route_entry *entry;
unsigned long mmr_offset;
int mmr_pnode;
if (set_desc_affinity(desc, mask, &dest))
return -1;
mmr_value = 0;
entry = (struct uv_IO_APIC_route_entry *)&mmr_value;
entry->vector = cfg->vector;
entry->delivery_mode = apic->irq_delivery_mode;
entry->dest_mode = apic->irq_dest_mode;
entry->polarity = 0;
entry->trigger = 0;
entry->mask = 0;
entry->dest = dest;
/* Get previously stored MMR and pnode of hub sourcing interrupts */
if (uv_irq_2_mmr_info(irq, &mmr_offset, &mmr_pnode))
return -1;
uv_write_global_mmr64(mmr_pnode, mmr_offset, mmr_value);
if (cfg->move_in_progress)
send_cleanup_vector(cfg);
return 0;
}
/*
* Set up a mapping of an available irq and vector, and enable the specified
* MMR that defines the MSI that is to be sent to the specified CPU when an
* interrupt is raised.
*/
int uv_setup_irq(char *irq_name, int cpu, int mmr_blade,
unsigned long mmr_offset, int limit)
{
int irq, ret;
irq = create_irq_nr(NR_IRQS_LEGACY, uv_blade_to_memory_nid(mmr_blade));
if (irq <= 0)
return -EBUSY;
ret = arch_enable_uv_irq(irq_name, irq, cpu, mmr_blade, mmr_offset,
limit);
if (ret == irq)
uv_set_irq_2_mmr_info(irq, mmr_offset, mmr_blade);
else
destroy_irq(irq);
return ret;
}
EXPORT_SYMBOL_GPL(uv_setup_irq);
/*
* Tear down a mapping of an irq and vector, and disable the specified MMR that
* defined the MSI that was to be sent to the specified CPU when an interrupt
* was raised.
*
* Set mmr_blade and mmr_offset to what was passed in on uv_setup_irq().
*/
void uv_teardown_irq(unsigned int irq)
{
struct uv_irq_2_mmr_pnode *e;
struct rb_node *n;
unsigned long irqflags;
spin_lock_irqsave(&uv_irq_lock, irqflags);
n = uv_irq_root.rb_node;
while (n) {
e = rb_entry(n, struct uv_irq_2_mmr_pnode, list);
if (e->irq == irq) {
arch_disable_uv_irq(e->pnode, e->offset);
rb_erase(n, &uv_irq_root);
kfree(e);
break;
}
if (irq < e->irq)
n = n->rb_left;
else
n = n->rb_right;
}
spin_unlock_irqrestore(&uv_irq_lock, irqflags);
destroy_irq(irq);
}
EXPORT_SYMBOL_GPL(uv_teardown_irq);
| gpl-2.0 |
Marvell-Semi/PXA168_kernel | drivers/net/wireless/prism54/oid_mgt.c | 1394 | 25229 | /*
* Copyright (C) 2003,2004 Aurelien Alleaume <slts@free.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License
*
* 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 <linux/kernel.h>
#include <linux/slab.h>
#include "prismcompat.h"
#include "islpci_dev.h"
#include "islpci_mgt.h"
#include "isl_oid.h"
#include "oid_mgt.h"
#include "isl_ioctl.h"
/* to convert between channel and freq */
static const int frequency_list_bg[] = { 2412, 2417, 2422, 2427, 2432,
2437, 2442, 2447, 2452, 2457, 2462, 2467, 2472, 2484
};
int
channel_of_freq(int f)
{
int c = 0;
if ((f >= 2412) && (f <= 2484)) {
while ((c < 14) && (f != frequency_list_bg[c]))
c++;
return (c >= 14) ? 0 : ++c;
} else if ((f >= (int) 5000) && (f <= (int) 6000)) {
return ( (f - 5000) / 5 );
} else
return 0;
}
#define OID_STRUCT(name,oid,s,t) [name] = {oid, 0, sizeof(s), t}
#define OID_STRUCT_C(name,oid,s,t) OID_STRUCT(name,oid,s,t | OID_FLAG_CACHED)
#define OID_U32(name,oid) OID_STRUCT(name,oid,u32,OID_TYPE_U32)
#define OID_U32_C(name,oid) OID_STRUCT_C(name,oid,u32,OID_TYPE_U32)
#define OID_STRUCT_MLME(name,oid) OID_STRUCT(name,oid,struct obj_mlme,OID_TYPE_MLME)
#define OID_STRUCT_MLMEEX(name,oid) OID_STRUCT(name,oid,struct obj_mlmeex,OID_TYPE_MLMEEX)
#define OID_UNKNOWN(name,oid) OID_STRUCT(name,oid,0,0)
struct oid_t isl_oid[] = {
OID_STRUCT(GEN_OID_MACADDRESS, 0x00000000, u8[6], OID_TYPE_ADDR),
OID_U32(GEN_OID_LINKSTATE, 0x00000001),
OID_UNKNOWN(GEN_OID_WATCHDOG, 0x00000002),
OID_UNKNOWN(GEN_OID_MIBOP, 0x00000003),
OID_UNKNOWN(GEN_OID_OPTIONS, 0x00000004),
OID_UNKNOWN(GEN_OID_LEDCONFIG, 0x00000005),
/* 802.11 */
OID_U32_C(DOT11_OID_BSSTYPE, 0x10000000),
OID_STRUCT_C(DOT11_OID_BSSID, 0x10000001, u8[6], OID_TYPE_RAW),
OID_STRUCT_C(DOT11_OID_SSID, 0x10000002, struct obj_ssid,
OID_TYPE_SSID),
OID_U32(DOT11_OID_STATE, 0x10000003),
OID_U32(DOT11_OID_AID, 0x10000004),
OID_STRUCT(DOT11_OID_COUNTRYSTRING, 0x10000005, u8[4], OID_TYPE_RAW),
OID_STRUCT_C(DOT11_OID_SSIDOVERRIDE, 0x10000006, struct obj_ssid,
OID_TYPE_SSID),
OID_U32(DOT11_OID_MEDIUMLIMIT, 0x11000000),
OID_U32_C(DOT11_OID_BEACONPERIOD, 0x11000001),
OID_U32(DOT11_OID_DTIMPERIOD, 0x11000002),
OID_U32(DOT11_OID_ATIMWINDOW, 0x11000003),
OID_U32(DOT11_OID_LISTENINTERVAL, 0x11000004),
OID_U32(DOT11_OID_CFPPERIOD, 0x11000005),
OID_U32(DOT11_OID_CFPDURATION, 0x11000006),
OID_U32_C(DOT11_OID_AUTHENABLE, 0x12000000),
OID_U32_C(DOT11_OID_PRIVACYINVOKED, 0x12000001),
OID_U32_C(DOT11_OID_EXUNENCRYPTED, 0x12000002),
OID_U32_C(DOT11_OID_DEFKEYID, 0x12000003),
[DOT11_OID_DEFKEYX] = {0x12000004, 3, sizeof (struct obj_key),
OID_FLAG_CACHED | OID_TYPE_KEY}, /* DOT11_OID_DEFKEY1,...DOT11_OID_DEFKEY4 */
OID_UNKNOWN(DOT11_OID_STAKEY, 0x12000008),
OID_U32(DOT11_OID_REKEYTHRESHOLD, 0x12000009),
OID_UNKNOWN(DOT11_OID_STASC, 0x1200000a),
OID_U32(DOT11_OID_PRIVTXREJECTED, 0x1a000000),
OID_U32(DOT11_OID_PRIVRXPLAIN, 0x1a000001),
OID_U32(DOT11_OID_PRIVRXFAILED, 0x1a000002),
OID_U32(DOT11_OID_PRIVRXNOKEY, 0x1a000003),
OID_U32_C(DOT11_OID_RTSTHRESH, 0x13000000),
OID_U32_C(DOT11_OID_FRAGTHRESH, 0x13000001),
OID_U32_C(DOT11_OID_SHORTRETRIES, 0x13000002),
OID_U32_C(DOT11_OID_LONGRETRIES, 0x13000003),
OID_U32_C(DOT11_OID_MAXTXLIFETIME, 0x13000004),
OID_U32(DOT11_OID_MAXRXLIFETIME, 0x13000005),
OID_U32(DOT11_OID_AUTHRESPTIMEOUT, 0x13000006),
OID_U32(DOT11_OID_ASSOCRESPTIMEOUT, 0x13000007),
OID_UNKNOWN(DOT11_OID_ALOFT_TABLE, 0x1d000000),
OID_UNKNOWN(DOT11_OID_ALOFT_CTRL_TABLE, 0x1d000001),
OID_UNKNOWN(DOT11_OID_ALOFT_RETREAT, 0x1d000002),
OID_UNKNOWN(DOT11_OID_ALOFT_PROGRESS, 0x1d000003),
OID_U32(DOT11_OID_ALOFT_FIXEDRATE, 0x1d000004),
OID_UNKNOWN(DOT11_OID_ALOFT_RSSIGRAPH, 0x1d000005),
OID_UNKNOWN(DOT11_OID_ALOFT_CONFIG, 0x1d000006),
[DOT11_OID_VDCFX] = {0x1b000000, 7, 0, 0},
OID_U32(DOT11_OID_MAXFRAMEBURST, 0x1b000008),
OID_U32(DOT11_OID_PSM, 0x14000000),
OID_U32(DOT11_OID_CAMTIMEOUT, 0x14000001),
OID_U32(DOT11_OID_RECEIVEDTIMS, 0x14000002),
OID_U32(DOT11_OID_ROAMPREFERENCE, 0x14000003),
OID_U32(DOT11_OID_BRIDGELOCAL, 0x15000000),
OID_U32(DOT11_OID_CLIENTS, 0x15000001),
OID_U32(DOT11_OID_CLIENTSASSOCIATED, 0x15000002),
[DOT11_OID_CLIENTX] = {0x15000003, 2006, 0, 0}, /* DOT11_OID_CLIENTX,...DOT11_OID_CLIENT2007 */
OID_STRUCT(DOT11_OID_CLIENTFIND, 0x150007DB, u8[6], OID_TYPE_ADDR),
OID_STRUCT(DOT11_OID_WDSLINKADD, 0x150007DC, u8[6], OID_TYPE_ADDR),
OID_STRUCT(DOT11_OID_WDSLINKREMOVE, 0x150007DD, u8[6], OID_TYPE_ADDR),
OID_STRUCT(DOT11_OID_EAPAUTHSTA, 0x150007DE, u8[6], OID_TYPE_ADDR),
OID_STRUCT(DOT11_OID_EAPUNAUTHSTA, 0x150007DF, u8[6], OID_TYPE_ADDR),
OID_U32_C(DOT11_OID_DOT1XENABLE, 0x150007E0),
OID_UNKNOWN(DOT11_OID_MICFAILURE, 0x150007E1),
OID_UNKNOWN(DOT11_OID_REKEYINDICATE, 0x150007E2),
OID_U32(DOT11_OID_MPDUTXSUCCESSFUL, 0x16000000),
OID_U32(DOT11_OID_MPDUTXONERETRY, 0x16000001),
OID_U32(DOT11_OID_MPDUTXMULTIPLERETRIES, 0x16000002),
OID_U32(DOT11_OID_MPDUTXFAILED, 0x16000003),
OID_U32(DOT11_OID_MPDURXSUCCESSFUL, 0x16000004),
OID_U32(DOT11_OID_MPDURXDUPS, 0x16000005),
OID_U32(DOT11_OID_RTSSUCCESSFUL, 0x16000006),
OID_U32(DOT11_OID_RTSFAILED, 0x16000007),
OID_U32(DOT11_OID_ACKFAILED, 0x16000008),
OID_U32(DOT11_OID_FRAMERECEIVES, 0x16000009),
OID_U32(DOT11_OID_FRAMEERRORS, 0x1600000A),
OID_U32(DOT11_OID_FRAMEABORTS, 0x1600000B),
OID_U32(DOT11_OID_FRAMEABORTSPHY, 0x1600000C),
OID_U32(DOT11_OID_SLOTTIME, 0x17000000),
OID_U32(DOT11_OID_CWMIN, 0x17000001),
OID_U32(DOT11_OID_CWMAX, 0x17000002),
OID_U32(DOT11_OID_ACKWINDOW, 0x17000003),
OID_U32(DOT11_OID_ANTENNARX, 0x17000004),
OID_U32(DOT11_OID_ANTENNATX, 0x17000005),
OID_U32(DOT11_OID_ANTENNADIVERSITY, 0x17000006),
OID_U32_C(DOT11_OID_CHANNEL, 0x17000007),
OID_U32_C(DOT11_OID_EDTHRESHOLD, 0x17000008),
OID_U32(DOT11_OID_PREAMBLESETTINGS, 0x17000009),
OID_STRUCT(DOT11_OID_RATES, 0x1700000A, u8[IWMAX_BITRATES + 1],
OID_TYPE_RAW),
OID_U32(DOT11_OID_CCAMODESUPPORTED, 0x1700000B),
OID_U32(DOT11_OID_CCAMODE, 0x1700000C),
OID_UNKNOWN(DOT11_OID_RSSIVECTOR, 0x1700000D),
OID_UNKNOWN(DOT11_OID_OUTPUTPOWERTABLE, 0x1700000E),
OID_U32(DOT11_OID_OUTPUTPOWER, 0x1700000F),
OID_STRUCT(DOT11_OID_SUPPORTEDRATES, 0x17000010,
u8[IWMAX_BITRATES + 1], OID_TYPE_RAW),
OID_U32_C(DOT11_OID_FREQUENCY, 0x17000011),
[DOT11_OID_SUPPORTEDFREQUENCIES] =
{0x17000012, 0, sizeof (struct obj_frequencies)
+ sizeof (u16) * IWMAX_FREQ, OID_TYPE_FREQUENCIES},
OID_U32(DOT11_OID_NOISEFLOOR, 0x17000013),
OID_STRUCT(DOT11_OID_FREQUENCYACTIVITY, 0x17000014, u8[IWMAX_FREQ + 1],
OID_TYPE_RAW),
OID_UNKNOWN(DOT11_OID_IQCALIBRATIONTABLE, 0x17000015),
OID_U32(DOT11_OID_NONERPPROTECTION, 0x17000016),
OID_U32(DOT11_OID_SLOTSETTINGS, 0x17000017),
OID_U32(DOT11_OID_NONERPTIMEOUT, 0x17000018),
OID_U32(DOT11_OID_PROFILES, 0x17000019),
OID_STRUCT(DOT11_OID_EXTENDEDRATES, 0x17000020,
u8[IWMAX_BITRATES + 1], OID_TYPE_RAW),
OID_STRUCT_MLME(DOT11_OID_DEAUTHENTICATE, 0x18000000),
OID_STRUCT_MLME(DOT11_OID_AUTHENTICATE, 0x18000001),
OID_STRUCT_MLME(DOT11_OID_DISASSOCIATE, 0x18000002),
OID_STRUCT_MLME(DOT11_OID_ASSOCIATE, 0x18000003),
OID_UNKNOWN(DOT11_OID_SCAN, 0x18000004),
OID_STRUCT_MLMEEX(DOT11_OID_BEACON, 0x18000005),
OID_STRUCT_MLMEEX(DOT11_OID_PROBE, 0x18000006),
OID_STRUCT_MLMEEX(DOT11_OID_DEAUTHENTICATEEX, 0x18000007),
OID_STRUCT_MLMEEX(DOT11_OID_AUTHENTICATEEX, 0x18000008),
OID_STRUCT_MLMEEX(DOT11_OID_DISASSOCIATEEX, 0x18000009),
OID_STRUCT_MLMEEX(DOT11_OID_ASSOCIATEEX, 0x1800000A),
OID_STRUCT_MLMEEX(DOT11_OID_REASSOCIATE, 0x1800000B),
OID_STRUCT_MLMEEX(DOT11_OID_REASSOCIATEEX, 0x1800000C),
OID_U32(DOT11_OID_NONERPSTATUS, 0x1E000000),
OID_U32(DOT11_OID_STATIMEOUT, 0x19000000),
OID_U32_C(DOT11_OID_MLMEAUTOLEVEL, 0x19000001),
OID_U32(DOT11_OID_BSSTIMEOUT, 0x19000002),
[DOT11_OID_ATTACHMENT] = {0x19000003, 0,
sizeof(struct obj_attachment), OID_TYPE_ATTACH},
OID_STRUCT_C(DOT11_OID_PSMBUFFER, 0x19000004, struct obj_buffer,
OID_TYPE_BUFFER),
OID_U32(DOT11_OID_BSSS, 0x1C000000),
[DOT11_OID_BSSX] = {0x1C000001, 63, sizeof (struct obj_bss),
OID_TYPE_BSS}, /*DOT11_OID_BSS1,...,DOT11_OID_BSS64 */
OID_STRUCT(DOT11_OID_BSSFIND, 0x1C000042, struct obj_bss, OID_TYPE_BSS),
[DOT11_OID_BSSLIST] = {0x1C000043, 0, sizeof (struct
obj_bsslist) +
sizeof (struct obj_bss[IWMAX_BSS]),
OID_TYPE_BSSLIST},
OID_UNKNOWN(OID_INL_TUNNEL, 0xFF020000),
OID_UNKNOWN(OID_INL_MEMADDR, 0xFF020001),
OID_UNKNOWN(OID_INL_MEMORY, 0xFF020002),
OID_U32_C(OID_INL_MODE, 0xFF020003),
OID_UNKNOWN(OID_INL_COMPONENT_NR, 0xFF020004),
OID_STRUCT(OID_INL_VERSION, 0xFF020005, u8[8], OID_TYPE_RAW),
OID_UNKNOWN(OID_INL_INTERFACE_ID, 0xFF020006),
OID_UNKNOWN(OID_INL_COMPONENT_ID, 0xFF020007),
OID_U32_C(OID_INL_CONFIG, 0xFF020008),
OID_U32_C(OID_INL_DOT11D_CONFORMANCE, 0xFF02000C),
OID_U32(OID_INL_PHYCAPABILITIES, 0xFF02000D),
OID_U32_C(OID_INL_OUTPUTPOWER, 0xFF02000F),
};
int
mgt_init(islpci_private *priv)
{
int i;
priv->mib = kcalloc(OID_NUM_LAST, sizeof (void *), GFP_KERNEL);
if (!priv->mib)
return -ENOMEM;
/* Alloc the cache */
for (i = 0; i < OID_NUM_LAST; i++) {
if (isl_oid[i].flags & OID_FLAG_CACHED) {
priv->mib[i] = kzalloc(isl_oid[i].size *
(isl_oid[i].range + 1),
GFP_KERNEL);
if (!priv->mib[i])
return -ENOMEM;
} else
priv->mib[i] = NULL;
}
init_rwsem(&priv->mib_sem);
prism54_mib_init(priv);
return 0;
}
void
mgt_clean(islpci_private *priv)
{
int i;
if (!priv->mib)
return;
for (i = 0; i < OID_NUM_LAST; i++) {
kfree(priv->mib[i]);
priv->mib[i] = NULL;
}
kfree(priv->mib);
priv->mib = NULL;
}
void
mgt_le_to_cpu(int type, void *data)
{
switch (type) {
case OID_TYPE_U32:
*(u32 *) data = le32_to_cpu(*(u32 *) data);
break;
case OID_TYPE_BUFFER:{
struct obj_buffer *buff = data;
buff->size = le32_to_cpu(buff->size);
buff->addr = le32_to_cpu(buff->addr);
break;
}
case OID_TYPE_BSS:{
struct obj_bss *bss = data;
bss->age = le16_to_cpu(bss->age);
bss->channel = le16_to_cpu(bss->channel);
bss->capinfo = le16_to_cpu(bss->capinfo);
bss->rates = le16_to_cpu(bss->rates);
bss->basic_rates = le16_to_cpu(bss->basic_rates);
break;
}
case OID_TYPE_BSSLIST:{
struct obj_bsslist *list = data;
int i;
list->nr = le32_to_cpu(list->nr);
for (i = 0; i < list->nr; i++)
mgt_le_to_cpu(OID_TYPE_BSS, &list->bsslist[i]);
break;
}
case OID_TYPE_FREQUENCIES:{
struct obj_frequencies *freq = data;
int i;
freq->nr = le16_to_cpu(freq->nr);
for (i = 0; i < freq->nr; i++)
freq->mhz[i] = le16_to_cpu(freq->mhz[i]);
break;
}
case OID_TYPE_MLME:{
struct obj_mlme *mlme = data;
mlme->id = le16_to_cpu(mlme->id);
mlme->state = le16_to_cpu(mlme->state);
mlme->code = le16_to_cpu(mlme->code);
break;
}
case OID_TYPE_MLMEEX:{
struct obj_mlmeex *mlme = data;
mlme->id = le16_to_cpu(mlme->id);
mlme->state = le16_to_cpu(mlme->state);
mlme->code = le16_to_cpu(mlme->code);
mlme->size = le16_to_cpu(mlme->size);
break;
}
case OID_TYPE_ATTACH:{
struct obj_attachment *attach = data;
attach->id = le16_to_cpu(attach->id);
attach->size = le16_to_cpu(attach->size);
break;
}
case OID_TYPE_SSID:
case OID_TYPE_KEY:
case OID_TYPE_ADDR:
case OID_TYPE_RAW:
break;
default:
BUG();
}
}
static void
mgt_cpu_to_le(int type, void *data)
{
switch (type) {
case OID_TYPE_U32:
*(u32 *) data = cpu_to_le32(*(u32 *) data);
break;
case OID_TYPE_BUFFER:{
struct obj_buffer *buff = data;
buff->size = cpu_to_le32(buff->size);
buff->addr = cpu_to_le32(buff->addr);
break;
}
case OID_TYPE_BSS:{
struct obj_bss *bss = data;
bss->age = cpu_to_le16(bss->age);
bss->channel = cpu_to_le16(bss->channel);
bss->capinfo = cpu_to_le16(bss->capinfo);
bss->rates = cpu_to_le16(bss->rates);
bss->basic_rates = cpu_to_le16(bss->basic_rates);
break;
}
case OID_TYPE_BSSLIST:{
struct obj_bsslist *list = data;
int i;
list->nr = cpu_to_le32(list->nr);
for (i = 0; i < list->nr; i++)
mgt_cpu_to_le(OID_TYPE_BSS, &list->bsslist[i]);
break;
}
case OID_TYPE_FREQUENCIES:{
struct obj_frequencies *freq = data;
int i;
freq->nr = cpu_to_le16(freq->nr);
for (i = 0; i < freq->nr; i++)
freq->mhz[i] = cpu_to_le16(freq->mhz[i]);
break;
}
case OID_TYPE_MLME:{
struct obj_mlme *mlme = data;
mlme->id = cpu_to_le16(mlme->id);
mlme->state = cpu_to_le16(mlme->state);
mlme->code = cpu_to_le16(mlme->code);
break;
}
case OID_TYPE_MLMEEX:{
struct obj_mlmeex *mlme = data;
mlme->id = cpu_to_le16(mlme->id);
mlme->state = cpu_to_le16(mlme->state);
mlme->code = cpu_to_le16(mlme->code);
mlme->size = cpu_to_le16(mlme->size);
break;
}
case OID_TYPE_ATTACH:{
struct obj_attachment *attach = data;
attach->id = cpu_to_le16(attach->id);
attach->size = cpu_to_le16(attach->size);
break;
}
case OID_TYPE_SSID:
case OID_TYPE_KEY:
case OID_TYPE_ADDR:
case OID_TYPE_RAW:
break;
default:
BUG();
}
}
/* Note : data is modified during this function */
int
mgt_set_request(islpci_private *priv, enum oid_num_t n, int extra, void *data)
{
int ret = 0;
struct islpci_mgmtframe *response = NULL;
int response_op = PIMFOR_OP_ERROR;
int dlen;
void *cache, *_data = data;
u32 oid;
BUG_ON(OID_NUM_LAST <= n);
BUG_ON(extra > isl_oid[n].range);
if (!priv->mib)
/* memory has been freed */
return -1;
dlen = isl_oid[n].size;
cache = priv->mib[n];
cache += (cache ? extra * dlen : 0);
oid = isl_oid[n].oid + extra;
if (_data == NULL)
/* we are requested to re-set a cached value */
_data = cache;
else
mgt_cpu_to_le(isl_oid[n].flags & OID_FLAG_TYPE, _data);
/* If we are going to write to the cache, we don't want anyone to read
* it -> acquire write lock.
* Else we could acquire a read lock to be sure we don't bother the
* commit process (which takes a write lock). But I'm not sure if it's
* needed.
*/
if (cache)
down_write(&priv->mib_sem);
if (islpci_get_state(priv) >= PRV_STATE_READY) {
ret = islpci_mgt_transaction(priv->ndev, PIMFOR_OP_SET, oid,
_data, dlen, &response);
if (!ret) {
response_op = response->header->operation;
islpci_mgt_release(response);
}
if (ret || response_op == PIMFOR_OP_ERROR)
ret = -EIO;
} else if (!cache)
ret = -EIO;
if (cache) {
if (!ret && data)
memcpy(cache, _data, dlen);
up_write(&priv->mib_sem);
}
/* re-set given data to what it was */
if (data)
mgt_le_to_cpu(isl_oid[n].flags & OID_FLAG_TYPE, data);
return ret;
}
/* None of these are cached */
int
mgt_set_varlen(islpci_private *priv, enum oid_num_t n, void *data, int extra_len)
{
int ret = 0;
struct islpci_mgmtframe *response;
int response_op = PIMFOR_OP_ERROR;
int dlen;
u32 oid;
BUG_ON(OID_NUM_LAST <= n);
dlen = isl_oid[n].size;
oid = isl_oid[n].oid;
mgt_cpu_to_le(isl_oid[n].flags & OID_FLAG_TYPE, data);
if (islpci_get_state(priv) >= PRV_STATE_READY) {
ret = islpci_mgt_transaction(priv->ndev, PIMFOR_OP_SET, oid,
data, dlen + extra_len, &response);
if (!ret) {
response_op = response->header->operation;
islpci_mgt_release(response);
}
if (ret || response_op == PIMFOR_OP_ERROR)
ret = -EIO;
} else
ret = -EIO;
/* re-set given data to what it was */
if (data)
mgt_le_to_cpu(isl_oid[n].flags & OID_FLAG_TYPE, data);
return ret;
}
int
mgt_get_request(islpci_private *priv, enum oid_num_t n, int extra, void *data,
union oid_res_t *res)
{
int ret = -EIO;
int reslen = 0;
struct islpci_mgmtframe *response = NULL;
int dlen;
void *cache, *_res = NULL;
u32 oid;
BUG_ON(OID_NUM_LAST <= n);
BUG_ON(extra > isl_oid[n].range);
res->ptr = NULL;
if (!priv->mib)
/* memory has been freed */
return -1;
dlen = isl_oid[n].size;
cache = priv->mib[n];
cache += cache ? extra * dlen : 0;
oid = isl_oid[n].oid + extra;
reslen = dlen;
if (cache)
down_read(&priv->mib_sem);
if (islpci_get_state(priv) >= PRV_STATE_READY) {
ret = islpci_mgt_transaction(priv->ndev, PIMFOR_OP_GET,
oid, data, dlen, &response);
if (ret || !response ||
response->header->operation == PIMFOR_OP_ERROR) {
if (response)
islpci_mgt_release(response);
ret = -EIO;
}
if (!ret) {
_res = response->data;
reslen = response->header->length;
}
} else if (cache) {
_res = cache;
ret = 0;
}
if ((isl_oid[n].flags & OID_FLAG_TYPE) == OID_TYPE_U32)
res->u = ret ? 0 : le32_to_cpu(*(u32 *) _res);
else {
res->ptr = kmalloc(reslen, GFP_KERNEL);
BUG_ON(res->ptr == NULL);
if (ret)
memset(res->ptr, 0, reslen);
else {
memcpy(res->ptr, _res, reslen);
mgt_le_to_cpu(isl_oid[n].flags & OID_FLAG_TYPE,
res->ptr);
}
}
if (cache)
up_read(&priv->mib_sem);
if (response && !ret)
islpci_mgt_release(response);
if (reslen > isl_oid[n].size)
printk(KERN_DEBUG
"mgt_get_request(0x%x): received data length was bigger "
"than expected (%d > %d). Memory is probably corrupted...",
oid, reslen, isl_oid[n].size);
return ret;
}
/* lock outside */
int
mgt_commit_list(islpci_private *priv, enum oid_num_t *l, int n)
{
int i, ret = 0;
struct islpci_mgmtframe *response;
for (i = 0; i < n; i++) {
struct oid_t *t = &(isl_oid[l[i]]);
void *data = priv->mib[l[i]];
int j = 0;
u32 oid = t->oid;
BUG_ON(data == NULL);
while (j <= t->range) {
int r = islpci_mgt_transaction(priv->ndev, PIMFOR_OP_SET,
oid, data, t->size,
&response);
if (response) {
r |= (response->header->operation == PIMFOR_OP_ERROR);
islpci_mgt_release(response);
}
if (r)
printk(KERN_ERR "%s: mgt_commit_list: failure. "
"oid=%08x err=%d\n",
priv->ndev->name, oid, r);
ret |= r;
j++;
oid++;
data += t->size;
}
}
return ret;
}
/* Lock outside */
void
mgt_set(islpci_private *priv, enum oid_num_t n, void *data)
{
BUG_ON(OID_NUM_LAST <= n);
BUG_ON(priv->mib[n] == NULL);
memcpy(priv->mib[n], data, isl_oid[n].size);
mgt_cpu_to_le(isl_oid[n].flags & OID_FLAG_TYPE, priv->mib[n]);
}
void
mgt_get(islpci_private *priv, enum oid_num_t n, void *res)
{
BUG_ON(OID_NUM_LAST <= n);
BUG_ON(priv->mib[n] == NULL);
BUG_ON(res == NULL);
memcpy(res, priv->mib[n], isl_oid[n].size);
mgt_le_to_cpu(isl_oid[n].flags & OID_FLAG_TYPE, res);
}
/* Commits the cache. Lock outside. */
static enum oid_num_t commit_part1[] = {
OID_INL_CONFIG,
OID_INL_MODE,
DOT11_OID_BSSTYPE,
DOT11_OID_CHANNEL,
DOT11_OID_MLMEAUTOLEVEL
};
static enum oid_num_t commit_part2[] = {
DOT11_OID_SSID,
DOT11_OID_PSMBUFFER,
DOT11_OID_AUTHENABLE,
DOT11_OID_PRIVACYINVOKED,
DOT11_OID_EXUNENCRYPTED,
DOT11_OID_DEFKEYX, /* MULTIPLE */
DOT11_OID_DEFKEYID,
DOT11_OID_DOT1XENABLE,
OID_INL_DOT11D_CONFORMANCE,
/* Do not initialize this - fw < 1.0.4.3 rejects it
OID_INL_OUTPUTPOWER,
*/
};
/* update the MAC addr. */
static int
mgt_update_addr(islpci_private *priv)
{
struct islpci_mgmtframe *res;
int ret;
ret = islpci_mgt_transaction(priv->ndev, PIMFOR_OP_GET,
isl_oid[GEN_OID_MACADDRESS].oid, NULL,
isl_oid[GEN_OID_MACADDRESS].size, &res);
if ((ret == 0) && res && (res->header->operation != PIMFOR_OP_ERROR))
memcpy(priv->ndev->dev_addr, res->data, ETH_ALEN);
else
ret = -EIO;
if (res)
islpci_mgt_release(res);
if (ret)
printk(KERN_ERR "%s: mgt_update_addr: failure\n", priv->ndev->name);
return ret;
}
int
mgt_commit(islpci_private *priv)
{
int rvalue;
enum oid_num_t u;
if (islpci_get_state(priv) < PRV_STATE_INIT)
return 0;
rvalue = mgt_commit_list(priv, commit_part1, ARRAY_SIZE(commit_part1));
if (priv->iw_mode != IW_MODE_MONITOR)
rvalue |= mgt_commit_list(priv, commit_part2, ARRAY_SIZE(commit_part2));
u = OID_INL_MODE;
rvalue |= mgt_commit_list(priv, &u, 1);
rvalue |= mgt_update_addr(priv);
if (rvalue) {
/* some request have failed. The device might be in an
incoherent state. We should reset it ! */
printk(KERN_DEBUG "%s: mgt_commit: failure\n", priv->ndev->name);
}
return rvalue;
}
/* The following OIDs need to be "unlatched":
*
* MEDIUMLIMIT,BEACONPERIOD,DTIMPERIOD,ATIMWINDOW,LISTENINTERVAL
* FREQUENCY,EXTENDEDRATES.
*
* The way to do this is to set ESSID. Note though that they may get
* unlatch before though by setting another OID. */
#if 0
void
mgt_unlatch_all(islpci_private *priv)
{
u32 u;
int rvalue = 0;
if (islpci_get_state(priv) < PRV_STATE_INIT)
return;
u = DOT11_OID_SSID;
rvalue = mgt_commit_list(priv, &u, 1);
/* Necessary if in MANUAL RUN mode? */
#if 0
u = OID_INL_MODE;
rvalue |= mgt_commit_list(priv, &u, 1);
u = DOT11_OID_MLMEAUTOLEVEL;
rvalue |= mgt_commit_list(priv, &u, 1);
u = OID_INL_MODE;
rvalue |= mgt_commit_list(priv, &u, 1);
#endif
if (rvalue)
printk(KERN_DEBUG "%s: Unlatching OIDs failed\n", priv->ndev->name);
}
#endif
/* This will tell you if you are allowed to answer a mlme(ex) request .*/
int
mgt_mlme_answer(islpci_private *priv)
{
u32 mlmeautolevel;
/* Acquire a read lock because if we are in a mode change, it's
* possible to answer true, while the card is leaving master to managed
* mode. Answering to a mlme in this situation could hang the card.
*/
down_read(&priv->mib_sem);
mlmeautolevel =
le32_to_cpu(*(u32 *) priv->mib[DOT11_OID_MLMEAUTOLEVEL]);
up_read(&priv->mib_sem);
return ((priv->iw_mode == IW_MODE_MASTER) &&
(mlmeautolevel >= DOT11_MLME_INTERMEDIATE));
}
enum oid_num_t
mgt_oidtonum(u32 oid)
{
int i;
for (i = 0; i < OID_NUM_LAST; i++)
if (isl_oid[i].oid == oid)
return i;
printk(KERN_DEBUG "looking for an unknown oid 0x%x", oid);
return OID_NUM_LAST;
}
int
mgt_response_to_str(enum oid_num_t n, union oid_res_t *r, char *str)
{
switch (isl_oid[n].flags & OID_FLAG_TYPE) {
case OID_TYPE_U32:
return snprintf(str, PRIV_STR_SIZE, "%u\n", r->u);
case OID_TYPE_BUFFER:{
struct obj_buffer *buff = r->ptr;
return snprintf(str, PRIV_STR_SIZE,
"size=%u\naddr=0x%X\n", buff->size,
buff->addr);
}
break;
case OID_TYPE_BSS:{
struct obj_bss *bss = r->ptr;
return snprintf(str, PRIV_STR_SIZE,
"age=%u\nchannel=%u\n"
"capinfo=0x%X\nrates=0x%X\n"
"basic_rates=0x%X\n", bss->age,
bss->channel, bss->capinfo,
bss->rates, bss->basic_rates);
}
break;
case OID_TYPE_BSSLIST:{
struct obj_bsslist *list = r->ptr;
int i, k;
k = snprintf(str, PRIV_STR_SIZE, "nr=%u\n", list->nr);
for (i = 0; i < list->nr; i++)
k += snprintf(str + k, PRIV_STR_SIZE - k,
"bss[%u] :\nage=%u\nchannel=%u\n"
"capinfo=0x%X\nrates=0x%X\n"
"basic_rates=0x%X\n",
i, list->bsslist[i].age,
list->bsslist[i].channel,
list->bsslist[i].capinfo,
list->bsslist[i].rates,
list->bsslist[i].basic_rates);
return k;
}
break;
case OID_TYPE_FREQUENCIES:{
struct obj_frequencies *freq = r->ptr;
int i, t;
printk("nr : %u\n", freq->nr);
t = snprintf(str, PRIV_STR_SIZE, "nr=%u\n", freq->nr);
for (i = 0; i < freq->nr; i++)
t += snprintf(str + t, PRIV_STR_SIZE - t,
"mhz[%u]=%u\n", i, freq->mhz[i]);
return t;
}
break;
case OID_TYPE_MLME:{
struct obj_mlme *mlme = r->ptr;
return snprintf(str, PRIV_STR_SIZE,
"id=0x%X\nstate=0x%X\ncode=0x%X\n",
mlme->id, mlme->state, mlme->code);
}
break;
case OID_TYPE_MLMEEX:{
struct obj_mlmeex *mlme = r->ptr;
return snprintf(str, PRIV_STR_SIZE,
"id=0x%X\nstate=0x%X\n"
"code=0x%X\nsize=0x%X\n", mlme->id,
mlme->state, mlme->code, mlme->size);
}
break;
case OID_TYPE_ATTACH:{
struct obj_attachment *attach = r->ptr;
return snprintf(str, PRIV_STR_SIZE,
"id=%d\nsize=%d\n",
attach->id,
attach->size);
}
break;
case OID_TYPE_SSID:{
struct obj_ssid *ssid = r->ptr;
return snprintf(str, PRIV_STR_SIZE,
"length=%u\noctets=%.*s\n",
ssid->length, ssid->length,
ssid->octets);
}
break;
case OID_TYPE_KEY:{
struct obj_key *key = r->ptr;
int t, i;
t = snprintf(str, PRIV_STR_SIZE,
"type=0x%X\nlength=0x%X\nkey=0x",
key->type, key->length);
for (i = 0; i < key->length; i++)
t += snprintf(str + t, PRIV_STR_SIZE - t,
"%02X:", key->key[i]);
t += snprintf(str + t, PRIV_STR_SIZE - t, "\n");
return t;
}
break;
case OID_TYPE_RAW:
case OID_TYPE_ADDR:{
unsigned char *buff = r->ptr;
int t, i;
t = snprintf(str, PRIV_STR_SIZE, "hex data=");
for (i = 0; i < isl_oid[n].size; i++)
t += snprintf(str + t, PRIV_STR_SIZE - t,
"%02X:", buff[i]);
t += snprintf(str + t, PRIV_STR_SIZE - t, "\n");
return t;
}
break;
default:
BUG();
}
return 0;
}
| gpl-2.0 |
GolovanovSrg/au-linux-kernel-spring-2016 | linux/drivers/net/ethernet/qualcomm/qca_framing.c | 1650 | 3909 | /*
* Copyright (c) 2011, 2012, Atheros Communications Inc.
* Copyright (c) 2014, I2SE GmbH
*
* 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.
*/
/* Atheros ethernet framing. Every Ethernet frame is surrounded
* by an atheros frame while transmitted over a serial channel;
*/
#include <linux/kernel.h>
#include "qca_framing.h"
u16
qcafrm_create_header(u8 *buf, u16 length)
{
__le16 len;
if (!buf)
return 0;
len = cpu_to_le16(length);
buf[0] = 0xAA;
buf[1] = 0xAA;
buf[2] = 0xAA;
buf[3] = 0xAA;
buf[4] = len & 0xff;
buf[5] = (len >> 8) & 0xff;
buf[6] = 0;
buf[7] = 0;
return QCAFRM_HEADER_LEN;
}
u16
qcafrm_create_footer(u8 *buf)
{
if (!buf)
return 0;
buf[0] = 0x55;
buf[1] = 0x55;
return QCAFRM_FOOTER_LEN;
}
/* Gather received bytes and try to extract a full ethernet frame by
* following a simple state machine.
*
* Return: QCAFRM_GATHER No ethernet frame fully received yet.
* QCAFRM_NOHEAD Header expected but not found.
* QCAFRM_INVLEN Atheros frame length is invalid
* QCAFRM_NOTAIL Footer expected but not found.
* > 0 Number of byte in the fully received
* Ethernet frame
*/
s32
qcafrm_fsm_decode(struct qcafrm_handle *handle, u8 *buf, u16 buf_len, u8 recv_byte)
{
s32 ret = QCAFRM_GATHER;
u16 len;
switch (handle->state) {
case QCAFRM_HW_LEN0:
case QCAFRM_HW_LEN1:
/* by default, just go to next state */
handle->state--;
if (recv_byte != 0x00) {
/* first two bytes of length must be 0 */
handle->state = QCAFRM_HW_LEN0;
}
break;
case QCAFRM_HW_LEN2:
case QCAFRM_HW_LEN3:
handle->state--;
break;
/* 4 bytes header pattern */
case QCAFRM_WAIT_AA1:
case QCAFRM_WAIT_AA2:
case QCAFRM_WAIT_AA3:
case QCAFRM_WAIT_AA4:
if (recv_byte != 0xAA) {
ret = QCAFRM_NOHEAD;
handle->state = QCAFRM_HW_LEN0;
} else {
handle->state--;
}
break;
/* 2 bytes length. */
/* Borrow offset field to hold length for now. */
case QCAFRM_WAIT_LEN_BYTE0:
handle->offset = recv_byte;
handle->state = QCAFRM_WAIT_LEN_BYTE1;
break;
case QCAFRM_WAIT_LEN_BYTE1:
handle->offset = handle->offset | (recv_byte << 8);
handle->state = QCAFRM_WAIT_RSVD_BYTE1;
break;
case QCAFRM_WAIT_RSVD_BYTE1:
handle->state = QCAFRM_WAIT_RSVD_BYTE2;
break;
case QCAFRM_WAIT_RSVD_BYTE2:
len = handle->offset;
if (len > buf_len || len < QCAFRM_ETHMINLEN) {
ret = QCAFRM_INVLEN;
handle->state = QCAFRM_HW_LEN0;
} else {
handle->state = (enum qcafrm_state)(len + 1);
/* Remaining number of bytes. */
handle->offset = 0;
}
break;
default:
/* Receiving Ethernet frame itself. */
buf[handle->offset] = recv_byte;
handle->offset++;
handle->state--;
break;
case QCAFRM_WAIT_551:
if (recv_byte != 0x55) {
ret = QCAFRM_NOTAIL;
handle->state = QCAFRM_HW_LEN0;
} else {
handle->state = QCAFRM_WAIT_552;
}
break;
case QCAFRM_WAIT_552:
if (recv_byte != 0x55) {
ret = QCAFRM_NOTAIL;
handle->state = QCAFRM_HW_LEN0;
} else {
ret = handle->offset;
/* Frame is fully received. */
handle->state = QCAFRM_HW_LEN0;
}
break;
}
return ret;
}
| gpl-2.0 |
ghanashyamprabhu/linux | drivers/media/rc/keymaps/rc-manli.c | 1906 | 3386 | /* manli.h - Keytable for manli Remote Controller
*
* keymap imported from ir-keymaps.c
*
* Copyright (c) 2010 by Mauro Carvalho Chehab
*
* 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 <media/rc-map.h>
#include <linux/module.h>
/* Michael Tokarev <mjt@tls.msk.ru>
keytable is used by MANLI MTV00[0x0c] and BeholdTV 40[13] at
least, and probably other cards too.
The "ascii-art picture" below (in comments, first row
is the keycode in hex, and subsequent row(s) shows
the button labels (several variants when appropriate)
helps to descide which keycodes to assign to the buttons.
*/
static struct rc_map_table manli[] = {
/* 0x1c 0x12 *
* FUNCTION POWER *
* FM (|) *
* */
{ 0x1c, KEY_RADIO }, /*XXX*/
{ 0x12, KEY_POWER },
/* 0x01 0x02 0x03 *
* 1 2 3 *
* *
* 0x04 0x05 0x06 *
* 4 5 6 *
* *
* 0x07 0x08 0x09 *
* 7 8 9 *
* */
{ 0x01, KEY_1 },
{ 0x02, KEY_2 },
{ 0x03, KEY_3 },
{ 0x04, KEY_4 },
{ 0x05, KEY_5 },
{ 0x06, KEY_6 },
{ 0x07, KEY_7 },
{ 0x08, KEY_8 },
{ 0x09, KEY_9 },
/* 0x0a 0x00 0x17 *
* RECALL 0 +100 *
* PLUS *
* */
{ 0x0a, KEY_AGAIN }, /*XXX KEY_REWIND? */
{ 0x00, KEY_0 },
{ 0x17, KEY_DIGITS }, /*XXX*/
/* 0x14 0x10 *
* MENU INFO *
* OSD */
{ 0x14, KEY_MENU },
{ 0x10, KEY_INFO },
/* 0x0b *
* Up *
* *
* 0x18 0x16 0x0c *
* Left Ok Right *
* *
* 0x015 *
* Down *
* */
{ 0x0b, KEY_UP },
{ 0x18, KEY_LEFT },
{ 0x16, KEY_OK }, /*XXX KEY_SELECT? KEY_ENTER? */
{ 0x0c, KEY_RIGHT },
{ 0x15, KEY_DOWN },
/* 0x11 0x0d *
* TV/AV MODE *
* SOURCE STEREO *
* */
{ 0x11, KEY_TV }, /*XXX*/
{ 0x0d, KEY_MODE }, /*XXX there's no KEY_STEREO */
/* 0x0f 0x1b 0x1a *
* AUDIO Vol+ Chan+ *
* TIMESHIFT??? *
* *
* 0x0e 0x1f 0x1e *
* SLEEP Vol- Chan- *
* */
{ 0x0f, KEY_AUDIO },
{ 0x1b, KEY_VOLUMEUP },
{ 0x1a, KEY_CHANNELUP },
{ 0x0e, KEY_TIME },
{ 0x1f, KEY_VOLUMEDOWN },
{ 0x1e, KEY_CHANNELDOWN },
/* 0x13 0x19 *
* MUTE SNAPSHOT*
* */
{ 0x13, KEY_MUTE },
{ 0x19, KEY_CAMERA },
/* 0x1d unused ? */
};
static struct rc_map_list manli_map = {
.map = {
.scan = manli,
.size = ARRAY_SIZE(manli),
.rc_type = RC_TYPE_UNKNOWN, /* Legacy IR type */
.name = RC_MAP_MANLI,
}
};
static int __init init_rc_map_manli(void)
{
return rc_map_register(&manli_map);
}
static void __exit exit_rc_map_manli(void)
{
rc_map_unregister(&manli_map);
}
module_init(init_rc_map_manli)
module_exit(exit_rc_map_manli)
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Mauro Carvalho Chehab");
| gpl-2.0 |
chrisw957/gumstix-linux | drivers/media/rc/keymaps/rc-dntv-live-dvbt-pro.c | 1906 | 2538 | /* dntv-live-dvbt-pro.h - Keytable for dntv_live_dvbt_pro Remote Controller
*
* keymap imported from ir-keymaps.c
*
* Copyright (c) 2010 by Mauro Carvalho Chehab
*
* 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 <media/rc-map.h>
#include <linux/module.h>
/* DigitalNow DNTV Live! DVB-T Pro Remote */
static struct rc_map_table dntv_live_dvbt_pro[] = {
{ 0x16, KEY_POWER },
{ 0x5b, KEY_HOME },
{ 0x55, KEY_TV }, /* live tv */
{ 0x58, KEY_TUNER }, /* digital Radio */
{ 0x5a, KEY_RADIO }, /* FM radio */
{ 0x59, KEY_DVD }, /* dvd menu */
{ 0x03, KEY_1 },
{ 0x01, KEY_2 },
{ 0x06, KEY_3 },
{ 0x09, KEY_4 },
{ 0x1d, KEY_5 },
{ 0x1f, KEY_6 },
{ 0x0d, KEY_7 },
{ 0x19, KEY_8 },
{ 0x1b, KEY_9 },
{ 0x0c, KEY_CANCEL },
{ 0x15, KEY_0 },
{ 0x4a, KEY_CLEAR },
{ 0x13, KEY_BACK },
{ 0x00, KEY_TAB },
{ 0x4b, KEY_UP },
{ 0x4e, KEY_LEFT },
{ 0x4f, KEY_OK },
{ 0x52, KEY_RIGHT },
{ 0x51, KEY_DOWN },
{ 0x1e, KEY_VOLUMEUP },
{ 0x0a, KEY_VOLUMEDOWN },
{ 0x02, KEY_CHANNELDOWN },
{ 0x05, KEY_CHANNELUP },
{ 0x11, KEY_RECORD },
{ 0x14, KEY_PLAY },
{ 0x4c, KEY_PAUSE },
{ 0x1a, KEY_STOP },
{ 0x40, KEY_REWIND },
{ 0x12, KEY_FASTFORWARD },
{ 0x41, KEY_PREVIOUSSONG }, /* replay |< */
{ 0x42, KEY_NEXTSONG }, /* skip >| */
{ 0x54, KEY_CAMERA }, /* capture */
{ 0x50, KEY_LANGUAGE }, /* sap */
{ 0x47, KEY_TV2 }, /* pip */
{ 0x4d, KEY_SCREEN },
{ 0x43, KEY_SUBTITLE },
{ 0x10, KEY_MUTE },
{ 0x49, KEY_AUDIO }, /* l/r */
{ 0x07, KEY_SLEEP },
{ 0x08, KEY_VIDEO }, /* a/v */
{ 0x0e, KEY_PREVIOUS }, /* recall */
{ 0x45, KEY_ZOOM }, /* zoom + */
{ 0x46, KEY_ANGLE }, /* zoom - */
{ 0x56, KEY_RED },
{ 0x57, KEY_GREEN },
{ 0x5c, KEY_YELLOW },
{ 0x5d, KEY_BLUE },
};
static struct rc_map_list dntv_live_dvbt_pro_map = {
.map = {
.scan = dntv_live_dvbt_pro,
.size = ARRAY_SIZE(dntv_live_dvbt_pro),
.rc_type = RC_TYPE_UNKNOWN, /* Legacy IR type */
.name = RC_MAP_DNTV_LIVE_DVBT_PRO,
}
};
static int __init init_rc_map_dntv_live_dvbt_pro(void)
{
return rc_map_register(&dntv_live_dvbt_pro_map);
}
static void __exit exit_rc_map_dntv_live_dvbt_pro(void)
{
rc_map_unregister(&dntv_live_dvbt_pro_map);
}
module_init(init_rc_map_dntv_live_dvbt_pro)
module_exit(exit_rc_map_dntv_live_dvbt_pro)
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Mauro Carvalho Chehab");
| gpl-2.0 |
MasterSS/linux | tools/usb/ffs-aio-example/multibuff/device_app/aio_multibuff.c | 2162 | 9268 | /*
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* 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 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.
*
* For more information, please refer to <http://unlicense.org/>
*/
#define _BSD_SOURCE /* for endian.h */
#include <endian.h>
#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/poll.h>
#include <unistd.h>
#include <stdbool.h>
#include <sys/eventfd.h>
#include "libaio.h"
#define IOCB_FLAG_RESFD (1 << 0)
#include <linux/usb/functionfs.h>
#define BUF_LEN 8192
#define BUFS_MAX 128
#define AIO_MAX (BUFS_MAX*2)
/******************** Descriptors and Strings *******************************/
static const struct {
struct usb_functionfs_descs_head_v2 header;
__le32 fs_count;
__le32 hs_count;
struct {
struct usb_interface_descriptor intf;
struct usb_endpoint_descriptor_no_audio bulk_sink;
struct usb_endpoint_descriptor_no_audio bulk_source;
} __attribute__ ((__packed__)) fs_descs, hs_descs;
} __attribute__ ((__packed__)) descriptors = {
.header = {
.magic = htole32(FUNCTIONFS_DESCRIPTORS_MAGIC_V2),
.flags = htole32(FUNCTIONFS_HAS_FS_DESC |
FUNCTIONFS_HAS_HS_DESC),
.length = htole32(sizeof(descriptors)),
},
.fs_count = htole32(3),
.fs_descs = {
.intf = {
.bLength = sizeof(descriptors.fs_descs.intf),
.bDescriptorType = USB_DT_INTERFACE,
.bNumEndpoints = 2,
.bInterfaceClass = USB_CLASS_VENDOR_SPEC,
.iInterface = 1,
},
.bulk_sink = {
.bLength = sizeof(descriptors.fs_descs.bulk_sink),
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = 1 | USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
},
.bulk_source = {
.bLength = sizeof(descriptors.fs_descs.bulk_source),
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = 2 | USB_DIR_OUT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
},
},
.hs_count = htole32(3),
.hs_descs = {
.intf = {
.bLength = sizeof(descriptors.hs_descs.intf),
.bDescriptorType = USB_DT_INTERFACE,
.bNumEndpoints = 2,
.bInterfaceClass = USB_CLASS_VENDOR_SPEC,
.iInterface = 1,
},
.bulk_sink = {
.bLength = sizeof(descriptors.hs_descs.bulk_sink),
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = 1 | USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = htole16(512),
},
.bulk_source = {
.bLength = sizeof(descriptors.hs_descs.bulk_source),
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = 2 | USB_DIR_OUT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = htole16(512),
},
},
};
#define STR_INTERFACE "AIO Test"
static const struct {
struct usb_functionfs_strings_head header;
struct {
__le16 code;
const char str1[sizeof(STR_INTERFACE)];
} __attribute__ ((__packed__)) lang0;
} __attribute__ ((__packed__)) strings = {
.header = {
.magic = htole32(FUNCTIONFS_STRINGS_MAGIC),
.length = htole32(sizeof(strings)),
.str_count = htole32(1),
.lang_count = htole32(1),
},
.lang0 = {
htole16(0x0409), /* en-us */
STR_INTERFACE,
},
};
/********************** Buffer structure *******************************/
struct io_buffer {
struct iocb **iocb;
unsigned char **buf;
unsigned cnt;
unsigned len;
unsigned requested;
};
/******************** Endpoints handling *******************************/
static void display_event(struct usb_functionfs_event *event)
{
static const char *const names[] = {
[FUNCTIONFS_BIND] = "BIND",
[FUNCTIONFS_UNBIND] = "UNBIND",
[FUNCTIONFS_ENABLE] = "ENABLE",
[FUNCTIONFS_DISABLE] = "DISABLE",
[FUNCTIONFS_SETUP] = "SETUP",
[FUNCTIONFS_SUSPEND] = "SUSPEND",
[FUNCTIONFS_RESUME] = "RESUME",
};
switch (event->type) {
case FUNCTIONFS_BIND:
case FUNCTIONFS_UNBIND:
case FUNCTIONFS_ENABLE:
case FUNCTIONFS_DISABLE:
case FUNCTIONFS_SETUP:
case FUNCTIONFS_SUSPEND:
case FUNCTIONFS_RESUME:
printf("Event %s\n", names[event->type]);
}
}
static void handle_ep0(int ep0, bool *ready)
{
int ret;
struct usb_functionfs_event event;
ret = read(ep0, &event, sizeof(event));
if (!ret) {
perror("unable to read event from ep0");
return;
}
display_event(&event);
switch (event.type) {
case FUNCTIONFS_SETUP:
if (event.u.setup.bRequestType & USB_DIR_IN)
write(ep0, NULL, 0);
else
read(ep0, NULL, 0);
break;
case FUNCTIONFS_ENABLE:
*ready = true;
break;
case FUNCTIONFS_DISABLE:
*ready = false;
break;
default:
break;
}
}
void init_bufs(struct io_buffer *iobuf, unsigned n, unsigned len)
{
unsigned i;
iobuf->buf = malloc(n*sizeof(*iobuf->buf));
iobuf->iocb = malloc(n*sizeof(*iobuf->iocb));
iobuf->cnt = n;
iobuf->len = len;
iobuf->requested = 0;
for (i = 0; i < n; ++i) {
iobuf->buf[i] = malloc(len*sizeof(**iobuf->buf));
iobuf->iocb[i] = malloc(sizeof(**iobuf->iocb));
}
iobuf->cnt = n;
}
void delete_bufs(struct io_buffer *iobuf)
{
unsigned i;
for (i = 0; i < iobuf->cnt; ++i) {
free(iobuf->buf[i]);
free(iobuf->iocb[i]);
}
free(iobuf->buf);
free(iobuf->iocb);
}
int main(int argc, char *argv[])
{
int ret;
unsigned i, j;
char *ep_path;
int ep0, ep1;
io_context_t ctx;
int evfd;
fd_set rfds;
struct io_buffer iobuf[2];
int actual = 0;
bool ready;
if (argc != 2) {
printf("ffs directory not specified!\n");
return 1;
}
ep_path = malloc(strlen(argv[1]) + 4 /* "/ep#" */ + 1 /* '\0' */);
if (!ep_path) {
perror("malloc");
return 1;
}
/* open endpoint files */
sprintf(ep_path, "%s/ep0", argv[1]);
ep0 = open(ep_path, O_RDWR);
if (ep0 < 0) {
perror("unable to open ep0");
return 1;
}
if (write(ep0, &descriptors, sizeof(descriptors)) < 0) {
perror("unable do write descriptors");
return 1;
}
if (write(ep0, &strings, sizeof(strings)) < 0) {
perror("unable to write strings");
return 1;
}
sprintf(ep_path, "%s/ep1", argv[1]);
ep1 = open(ep_path, O_RDWR);
if (ep1 < 0) {
perror("unable to open ep1");
return 1;
}
free(ep_path);
memset(&ctx, 0, sizeof(ctx));
/* setup aio context to handle up to AIO_MAX requests */
if (io_setup(AIO_MAX, &ctx) < 0) {
perror("unable to setup aio");
return 1;
}
evfd = eventfd(0, 0);
if (evfd < 0) {
perror("unable to open eventfd");
return 1;
}
for (i = 0; i < sizeof(iobuf)/sizeof(*iobuf); ++i)
init_bufs(&iobuf[i], BUFS_MAX, BUF_LEN);
while (1) {
FD_ZERO(&rfds);
FD_SET(ep0, &rfds);
FD_SET(evfd, &rfds);
ret = select(((ep0 > evfd) ? ep0 : evfd)+1,
&rfds, NULL, NULL, NULL);
if (ret < 0) {
if (errno == EINTR)
continue;
perror("select");
break;
}
if (FD_ISSET(ep0, &rfds))
handle_ep0(ep0, &ready);
/* we are waiting for function ENABLE */
if (!ready)
continue;
/*
* when we're preparing new data to submit,
* second buffer being transmitted
*/
for (i = 0; i < sizeof(iobuf)/sizeof(*iobuf); ++i) {
if (iobuf[i].requested)
continue;
/* prepare requests */
for (j = 0; j < iobuf[i].cnt; ++j) {
io_prep_pwrite(iobuf[i].iocb[j], ep1,
iobuf[i].buf[j],
iobuf[i].len, 0);
/* enable eventfd notification */
iobuf[i].iocb[j]->u.c.flags |= IOCB_FLAG_RESFD;
iobuf[i].iocb[j]->u.c.resfd = evfd;
}
/* submit table of requests */
ret = io_submit(ctx, iobuf[i].cnt, iobuf[i].iocb);
if (ret >= 0) {
iobuf[i].requested = ret;
printf("submit: %d requests buf: %d\n", ret, i);
} else
perror("unable to submit requests");
}
/* if event is ready to read */
if (!FD_ISSET(evfd, &rfds))
continue;
uint64_t ev_cnt;
ret = read(evfd, &ev_cnt, sizeof(ev_cnt));
if (ret < 0) {
perror("unable to read eventfd");
break;
}
struct io_event e[BUFS_MAX];
/* we read aio events */
ret = io_getevents(ctx, 1, BUFS_MAX, e, NULL);
if (ret > 0) /* if we got events */
iobuf[actual].requested -= ret;
/* if all req's from iocb completed */
if (!iobuf[actual].requested)
actual = (actual + 1)%(sizeof(iobuf)/sizeof(*iobuf));
}
/* free resources */
for (i = 0; i < sizeof(iobuf)/sizeof(*iobuf); ++i)
delete_bufs(&iobuf[i]);
io_destroy(ctx);
close(ep1);
close(ep0);
return 0;
}
| gpl-2.0 |
coinlake/xperia-tipo-kernel | fs/ocfs2/cluster/tcp.c | 2930 | 59417 | /* -*- mode: c; c-basic-offset: 8; -*-
*
* vim: noexpandtab sw=8 ts=8 sts=0:
*
* Copyright (C) 2004 Oracle. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 021110-1307, USA.
*
* ----
*
* Callers for this were originally written against a very simple synchronus
* API. This implementation reflects those simple callers. Some day I'm sure
* we'll need to move to a more robust posting/callback mechanism.
*
* Transmit calls pass in kernel virtual addresses and block copying this into
* the socket's tx buffers via a usual blocking sendmsg. They'll block waiting
* for a failed socket to timeout. TX callers can also pass in a poniter to an
* 'int' which gets filled with an errno off the wire in response to the
* message they send.
*
* Handlers for unsolicited messages are registered. Each socket has a page
* that incoming data is copied into. First the header, then the data.
* Handlers are called from only one thread with a reference to this per-socket
* page. This page is destroyed after the handler call, so it can't be
* referenced beyond the call. Handlers may block but are discouraged from
* doing so.
*
* Any framing errors (bad magic, large payload lengths) close a connection.
*
* Our sock_container holds the state we associate with a socket. It's current
* framing state is held there as well as the refcounting we do around when it
* is safe to tear down the socket. The socket is only finally torn down from
* the container when the container loses all of its references -- so as long
* as you hold a ref on the container you can trust that the socket is valid
* for use with kernel socket APIs.
*
* Connections are initiated between a pair of nodes when the node with the
* higher node number gets a heartbeat callback which indicates that the lower
* numbered node has started heartbeating. The lower numbered node is passive
* and only accepts the connection if the higher numbered node is heartbeating.
*/
#include <linux/kernel.h>
#include <linux/jiffies.h>
#include <linux/slab.h>
#include <linux/idr.h>
#include <linux/kref.h>
#include <linux/net.h>
#include <net/tcp.h>
#include <asm/uaccess.h>
#include "heartbeat.h"
#include "tcp.h"
#include "nodemanager.h"
#define MLOG_MASK_PREFIX ML_TCP
#include "masklog.h"
#include "quorum.h"
#include "tcp_internal.h"
#define SC_NODEF_FMT "node %s (num %u) at %pI4:%u"
#define SC_NODEF_ARGS(sc) sc->sc_node->nd_name, sc->sc_node->nd_num, \
&sc->sc_node->nd_ipv4_address, \
ntohs(sc->sc_node->nd_ipv4_port)
/*
* In the following two log macros, the whitespace after the ',' just
* before ##args is intentional. Otherwise, gcc 2.95 will eat the
* previous token if args expands to nothing.
*/
#define msglog(hdr, fmt, args...) do { \
typeof(hdr) __hdr = (hdr); \
mlog(ML_MSG, "[mag %u len %u typ %u stat %d sys_stat %d " \
"key %08x num %u] " fmt, \
be16_to_cpu(__hdr->magic), be16_to_cpu(__hdr->data_len), \
be16_to_cpu(__hdr->msg_type), be32_to_cpu(__hdr->status), \
be32_to_cpu(__hdr->sys_status), be32_to_cpu(__hdr->key), \
be32_to_cpu(__hdr->msg_num) , ##args); \
} while (0)
#define sclog(sc, fmt, args...) do { \
typeof(sc) __sc = (sc); \
mlog(ML_SOCKET, "[sc %p refs %d sock %p node %u page %p " \
"pg_off %zu] " fmt, __sc, \
atomic_read(&__sc->sc_kref.refcount), __sc->sc_sock, \
__sc->sc_node->nd_num, __sc->sc_page, __sc->sc_page_off , \
##args); \
} while (0)
static DEFINE_RWLOCK(o2net_handler_lock);
static struct rb_root o2net_handler_tree = RB_ROOT;
static struct o2net_node o2net_nodes[O2NM_MAX_NODES];
/* XXX someday we'll need better accounting */
static struct socket *o2net_listen_sock = NULL;
/*
* listen work is only queued by the listening socket callbacks on the
* o2net_wq. teardown detaches the callbacks before destroying the workqueue.
* quorum work is queued as sock containers are shutdown.. stop_listening
* tears down all the node's sock containers, preventing future shutdowns
* and queued quroum work, before canceling delayed quorum work and
* destroying the work queue.
*/
static struct workqueue_struct *o2net_wq;
static struct work_struct o2net_listen_work;
static struct o2hb_callback_func o2net_hb_up, o2net_hb_down;
#define O2NET_HB_PRI 0x1
static struct o2net_handshake *o2net_hand;
static struct o2net_msg *o2net_keep_req, *o2net_keep_resp;
static int o2net_sys_err_translations[O2NET_ERR_MAX] =
{[O2NET_ERR_NONE] = 0,
[O2NET_ERR_NO_HNDLR] = -ENOPROTOOPT,
[O2NET_ERR_OVERFLOW] = -EOVERFLOW,
[O2NET_ERR_DIED] = -EHOSTDOWN,};
/* can't quite avoid *all* internal declarations :/ */
static void o2net_sc_connect_completed(struct work_struct *work);
static void o2net_rx_until_empty(struct work_struct *work);
static void o2net_shutdown_sc(struct work_struct *work);
static void o2net_listen_data_ready(struct sock *sk, int bytes);
static void o2net_sc_send_keep_req(struct work_struct *work);
static void o2net_idle_timer(unsigned long data);
static void o2net_sc_postpone_idle(struct o2net_sock_container *sc);
static void o2net_sc_reset_idle_timer(struct o2net_sock_container *sc);
#ifdef CONFIG_DEBUG_FS
static void o2net_init_nst(struct o2net_send_tracking *nst, u32 msgtype,
u32 msgkey, struct task_struct *task, u8 node)
{
INIT_LIST_HEAD(&nst->st_net_debug_item);
nst->st_task = task;
nst->st_msg_type = msgtype;
nst->st_msg_key = msgkey;
nst->st_node = node;
}
static inline void o2net_set_nst_sock_time(struct o2net_send_tracking *nst)
{
nst->st_sock_time = ktime_get();
}
static inline void o2net_set_nst_send_time(struct o2net_send_tracking *nst)
{
nst->st_send_time = ktime_get();
}
static inline void o2net_set_nst_status_time(struct o2net_send_tracking *nst)
{
nst->st_status_time = ktime_get();
}
static inline void o2net_set_nst_sock_container(struct o2net_send_tracking *nst,
struct o2net_sock_container *sc)
{
nst->st_sc = sc;
}
static inline void o2net_set_nst_msg_id(struct o2net_send_tracking *nst,
u32 msg_id)
{
nst->st_id = msg_id;
}
static inline void o2net_set_sock_timer(struct o2net_sock_container *sc)
{
sc->sc_tv_timer = ktime_get();
}
static inline void o2net_set_data_ready_time(struct o2net_sock_container *sc)
{
sc->sc_tv_data_ready = ktime_get();
}
static inline void o2net_set_advance_start_time(struct o2net_sock_container *sc)
{
sc->sc_tv_advance_start = ktime_get();
}
static inline void o2net_set_advance_stop_time(struct o2net_sock_container *sc)
{
sc->sc_tv_advance_stop = ktime_get();
}
static inline void o2net_set_func_start_time(struct o2net_sock_container *sc)
{
sc->sc_tv_func_start = ktime_get();
}
static inline void o2net_set_func_stop_time(struct o2net_sock_container *sc)
{
sc->sc_tv_func_stop = ktime_get();
}
#else /* CONFIG_DEBUG_FS */
# define o2net_init_nst(a, b, c, d, e)
# define o2net_set_nst_sock_time(a)
# define o2net_set_nst_send_time(a)
# define o2net_set_nst_status_time(a)
# define o2net_set_nst_sock_container(a, b)
# define o2net_set_nst_msg_id(a, b)
# define o2net_set_sock_timer(a)
# define o2net_set_data_ready_time(a)
# define o2net_set_advance_start_time(a)
# define o2net_set_advance_stop_time(a)
# define o2net_set_func_start_time(a)
# define o2net_set_func_stop_time(a)
#endif /* CONFIG_DEBUG_FS */
#ifdef CONFIG_OCFS2_FS_STATS
static ktime_t o2net_get_func_run_time(struct o2net_sock_container *sc)
{
return ktime_sub(sc->sc_tv_func_stop, sc->sc_tv_func_start);
}
static void o2net_update_send_stats(struct o2net_send_tracking *nst,
struct o2net_sock_container *sc)
{
sc->sc_tv_status_total = ktime_add(sc->sc_tv_status_total,
ktime_sub(ktime_get(),
nst->st_status_time));
sc->sc_tv_send_total = ktime_add(sc->sc_tv_send_total,
ktime_sub(nst->st_status_time,
nst->st_send_time));
sc->sc_tv_acquiry_total = ktime_add(sc->sc_tv_acquiry_total,
ktime_sub(nst->st_send_time,
nst->st_sock_time));
sc->sc_send_count++;
}
static void o2net_update_recv_stats(struct o2net_sock_container *sc)
{
sc->sc_tv_process_total = ktime_add(sc->sc_tv_process_total,
o2net_get_func_run_time(sc));
sc->sc_recv_count++;
}
#else
# define o2net_update_send_stats(a, b)
# define o2net_update_recv_stats(sc)
#endif /* CONFIG_OCFS2_FS_STATS */
static inline int o2net_reconnect_delay(void)
{
return o2nm_single_cluster->cl_reconnect_delay_ms;
}
static inline int o2net_keepalive_delay(void)
{
return o2nm_single_cluster->cl_keepalive_delay_ms;
}
static inline int o2net_idle_timeout(void)
{
return o2nm_single_cluster->cl_idle_timeout_ms;
}
static inline int o2net_sys_err_to_errno(enum o2net_system_error err)
{
int trans;
BUG_ON(err >= O2NET_ERR_MAX);
trans = o2net_sys_err_translations[err];
/* Just in case we mess up the translation table above */
BUG_ON(err != O2NET_ERR_NONE && trans == 0);
return trans;
}
static struct o2net_node * o2net_nn_from_num(u8 node_num)
{
BUG_ON(node_num >= ARRAY_SIZE(o2net_nodes));
return &o2net_nodes[node_num];
}
static u8 o2net_num_from_nn(struct o2net_node *nn)
{
BUG_ON(nn == NULL);
return nn - o2net_nodes;
}
/* ------------------------------------------------------------ */
static int o2net_prep_nsw(struct o2net_node *nn, struct o2net_status_wait *nsw)
{
int ret = 0;
do {
if (!idr_pre_get(&nn->nn_status_idr, GFP_ATOMIC)) {
ret = -EAGAIN;
break;
}
spin_lock(&nn->nn_lock);
ret = idr_get_new(&nn->nn_status_idr, nsw, &nsw->ns_id);
if (ret == 0)
list_add_tail(&nsw->ns_node_item,
&nn->nn_status_list);
spin_unlock(&nn->nn_lock);
} while (ret == -EAGAIN);
if (ret == 0) {
init_waitqueue_head(&nsw->ns_wq);
nsw->ns_sys_status = O2NET_ERR_NONE;
nsw->ns_status = 0;
}
return ret;
}
static void o2net_complete_nsw_locked(struct o2net_node *nn,
struct o2net_status_wait *nsw,
enum o2net_system_error sys_status,
s32 status)
{
assert_spin_locked(&nn->nn_lock);
if (!list_empty(&nsw->ns_node_item)) {
list_del_init(&nsw->ns_node_item);
nsw->ns_sys_status = sys_status;
nsw->ns_status = status;
idr_remove(&nn->nn_status_idr, nsw->ns_id);
wake_up(&nsw->ns_wq);
}
}
static void o2net_complete_nsw(struct o2net_node *nn,
struct o2net_status_wait *nsw,
u64 id, enum o2net_system_error sys_status,
s32 status)
{
spin_lock(&nn->nn_lock);
if (nsw == NULL) {
if (id > INT_MAX)
goto out;
nsw = idr_find(&nn->nn_status_idr, id);
if (nsw == NULL)
goto out;
}
o2net_complete_nsw_locked(nn, nsw, sys_status, status);
out:
spin_unlock(&nn->nn_lock);
return;
}
static void o2net_complete_nodes_nsw(struct o2net_node *nn)
{
struct o2net_status_wait *nsw, *tmp;
unsigned int num_kills = 0;
assert_spin_locked(&nn->nn_lock);
list_for_each_entry_safe(nsw, tmp, &nn->nn_status_list, ns_node_item) {
o2net_complete_nsw_locked(nn, nsw, O2NET_ERR_DIED, 0);
num_kills++;
}
mlog(0, "completed %d messages for node %u\n", num_kills,
o2net_num_from_nn(nn));
}
static int o2net_nsw_completed(struct o2net_node *nn,
struct o2net_status_wait *nsw)
{
int completed;
spin_lock(&nn->nn_lock);
completed = list_empty(&nsw->ns_node_item);
spin_unlock(&nn->nn_lock);
return completed;
}
/* ------------------------------------------------------------ */
static void sc_kref_release(struct kref *kref)
{
struct o2net_sock_container *sc = container_of(kref,
struct o2net_sock_container, sc_kref);
BUG_ON(timer_pending(&sc->sc_idle_timeout));
sclog(sc, "releasing\n");
if (sc->sc_sock) {
sock_release(sc->sc_sock);
sc->sc_sock = NULL;
}
o2nm_undepend_item(&sc->sc_node->nd_item);
o2nm_node_put(sc->sc_node);
sc->sc_node = NULL;
o2net_debug_del_sc(sc);
kfree(sc);
}
static void sc_put(struct o2net_sock_container *sc)
{
sclog(sc, "put\n");
kref_put(&sc->sc_kref, sc_kref_release);
}
static void sc_get(struct o2net_sock_container *sc)
{
sclog(sc, "get\n");
kref_get(&sc->sc_kref);
}
static struct o2net_sock_container *sc_alloc(struct o2nm_node *node)
{
struct o2net_sock_container *sc, *ret = NULL;
struct page *page = NULL;
int status = 0;
page = alloc_page(GFP_NOFS);
sc = kzalloc(sizeof(*sc), GFP_NOFS);
if (sc == NULL || page == NULL)
goto out;
kref_init(&sc->sc_kref);
o2nm_node_get(node);
sc->sc_node = node;
/* pin the node item of the remote node */
status = o2nm_depend_item(&node->nd_item);
if (status) {
mlog_errno(status);
o2nm_node_put(node);
goto out;
}
INIT_WORK(&sc->sc_connect_work, o2net_sc_connect_completed);
INIT_WORK(&sc->sc_rx_work, o2net_rx_until_empty);
INIT_WORK(&sc->sc_shutdown_work, o2net_shutdown_sc);
INIT_DELAYED_WORK(&sc->sc_keepalive_work, o2net_sc_send_keep_req);
init_timer(&sc->sc_idle_timeout);
sc->sc_idle_timeout.function = o2net_idle_timer;
sc->sc_idle_timeout.data = (unsigned long)sc;
sclog(sc, "alloced\n");
ret = sc;
sc->sc_page = page;
o2net_debug_add_sc(sc);
sc = NULL;
page = NULL;
out:
if (page)
__free_page(page);
kfree(sc);
return ret;
}
/* ------------------------------------------------------------ */
static void o2net_sc_queue_work(struct o2net_sock_container *sc,
struct work_struct *work)
{
sc_get(sc);
if (!queue_work(o2net_wq, work))
sc_put(sc);
}
static void o2net_sc_queue_delayed_work(struct o2net_sock_container *sc,
struct delayed_work *work,
int delay)
{
sc_get(sc);
if (!queue_delayed_work(o2net_wq, work, delay))
sc_put(sc);
}
static void o2net_sc_cancel_delayed_work(struct o2net_sock_container *sc,
struct delayed_work *work)
{
if (cancel_delayed_work(work))
sc_put(sc);
}
static atomic_t o2net_connected_peers = ATOMIC_INIT(0);
int o2net_num_connected_peers(void)
{
return atomic_read(&o2net_connected_peers);
}
static void o2net_set_nn_state(struct o2net_node *nn,
struct o2net_sock_container *sc,
unsigned valid, int err)
{
int was_valid = nn->nn_sc_valid;
int was_err = nn->nn_persistent_error;
struct o2net_sock_container *old_sc = nn->nn_sc;
assert_spin_locked(&nn->nn_lock);
if (old_sc && !sc)
atomic_dec(&o2net_connected_peers);
else if (!old_sc && sc)
atomic_inc(&o2net_connected_peers);
/* the node num comparison and single connect/accept path should stop
* an non-null sc from being overwritten with another */
BUG_ON(sc && nn->nn_sc && nn->nn_sc != sc);
mlog_bug_on_msg(err && valid, "err %d valid %u\n", err, valid);
mlog_bug_on_msg(valid && !sc, "valid %u sc %p\n", valid, sc);
if (was_valid && !valid && err == 0)
err = -ENOTCONN;
mlog(ML_CONN, "node %u sc: %p -> %p, valid %u -> %u, err %d -> %d\n",
o2net_num_from_nn(nn), nn->nn_sc, sc, nn->nn_sc_valid, valid,
nn->nn_persistent_error, err);
nn->nn_sc = sc;
nn->nn_sc_valid = valid ? 1 : 0;
nn->nn_persistent_error = err;
/* mirrors o2net_tx_can_proceed() */
if (nn->nn_persistent_error || nn->nn_sc_valid)
wake_up(&nn->nn_sc_wq);
if (!was_err && nn->nn_persistent_error) {
o2quo_conn_err(o2net_num_from_nn(nn));
queue_delayed_work(o2net_wq, &nn->nn_still_up,
msecs_to_jiffies(O2NET_QUORUM_DELAY_MS));
}
if (was_valid && !valid) {
printk(KERN_NOTICE "o2net: no longer connected to "
SC_NODEF_FMT "\n", SC_NODEF_ARGS(old_sc));
o2net_complete_nodes_nsw(nn);
}
if (!was_valid && valid) {
o2quo_conn_up(o2net_num_from_nn(nn));
cancel_delayed_work(&nn->nn_connect_expired);
printk(KERN_NOTICE "o2net: %s " SC_NODEF_FMT "\n",
o2nm_this_node() > sc->sc_node->nd_num ?
"connected to" : "accepted connection from",
SC_NODEF_ARGS(sc));
}
/* trigger the connecting worker func as long as we're not valid,
* it will back off if it shouldn't connect. This can be called
* from node config teardown and so needs to be careful about
* the work queue actually being up. */
if (!valid && o2net_wq) {
unsigned long delay;
/* delay if we're within a RECONNECT_DELAY of the
* last attempt */
delay = (nn->nn_last_connect_attempt +
msecs_to_jiffies(o2net_reconnect_delay()))
- jiffies;
if (delay > msecs_to_jiffies(o2net_reconnect_delay()))
delay = 0;
mlog(ML_CONN, "queueing conn attempt in %lu jiffies\n", delay);
queue_delayed_work(o2net_wq, &nn->nn_connect_work, delay);
/*
* Delay the expired work after idle timeout.
*
* We might have lots of failed connection attempts that run
* through here but we only cancel the connect_expired work when
* a connection attempt succeeds. So only the first enqueue of
* the connect_expired work will do anything. The rest will see
* that it's already queued and do nothing.
*/
delay += msecs_to_jiffies(o2net_idle_timeout());
queue_delayed_work(o2net_wq, &nn->nn_connect_expired, delay);
}
/* keep track of the nn's sc ref for the caller */
if ((old_sc == NULL) && sc)
sc_get(sc);
if (old_sc && (old_sc != sc)) {
o2net_sc_queue_work(old_sc, &old_sc->sc_shutdown_work);
sc_put(old_sc);
}
}
/* see o2net_register_callbacks() */
static void o2net_data_ready(struct sock *sk, int bytes)
{
void (*ready)(struct sock *sk, int bytes);
read_lock(&sk->sk_callback_lock);
if (sk->sk_user_data) {
struct o2net_sock_container *sc = sk->sk_user_data;
sclog(sc, "data_ready hit\n");
o2net_set_data_ready_time(sc);
o2net_sc_queue_work(sc, &sc->sc_rx_work);
ready = sc->sc_data_ready;
} else {
ready = sk->sk_data_ready;
}
read_unlock(&sk->sk_callback_lock);
ready(sk, bytes);
}
/* see o2net_register_callbacks() */
static void o2net_state_change(struct sock *sk)
{
void (*state_change)(struct sock *sk);
struct o2net_sock_container *sc;
read_lock(&sk->sk_callback_lock);
sc = sk->sk_user_data;
if (sc == NULL) {
state_change = sk->sk_state_change;
goto out;
}
sclog(sc, "state_change to %d\n", sk->sk_state);
state_change = sc->sc_state_change;
switch(sk->sk_state) {
/* ignore connecting sockets as they make progress */
case TCP_SYN_SENT:
case TCP_SYN_RECV:
break;
case TCP_ESTABLISHED:
o2net_sc_queue_work(sc, &sc->sc_connect_work);
break;
default:
printk(KERN_INFO "o2net: connection to " SC_NODEF_FMT
" shutdown, state %d\n",
SC_NODEF_ARGS(sc), sk->sk_state);
o2net_sc_queue_work(sc, &sc->sc_shutdown_work);
break;
}
out:
read_unlock(&sk->sk_callback_lock);
state_change(sk);
}
/*
* we register callbacks so we can queue work on events before calling
* the original callbacks. our callbacks our careful to test user_data
* to discover when they've reaced with o2net_unregister_callbacks().
*/
static void o2net_register_callbacks(struct sock *sk,
struct o2net_sock_container *sc)
{
write_lock_bh(&sk->sk_callback_lock);
/* accepted sockets inherit the old listen socket data ready */
if (sk->sk_data_ready == o2net_listen_data_ready) {
sk->sk_data_ready = sk->sk_user_data;
sk->sk_user_data = NULL;
}
BUG_ON(sk->sk_user_data != NULL);
sk->sk_user_data = sc;
sc_get(sc);
sc->sc_data_ready = sk->sk_data_ready;
sc->sc_state_change = sk->sk_state_change;
sk->sk_data_ready = o2net_data_ready;
sk->sk_state_change = o2net_state_change;
mutex_init(&sc->sc_send_lock);
write_unlock_bh(&sk->sk_callback_lock);
}
static int o2net_unregister_callbacks(struct sock *sk,
struct o2net_sock_container *sc)
{
int ret = 0;
write_lock_bh(&sk->sk_callback_lock);
if (sk->sk_user_data == sc) {
ret = 1;
sk->sk_user_data = NULL;
sk->sk_data_ready = sc->sc_data_ready;
sk->sk_state_change = sc->sc_state_change;
}
write_unlock_bh(&sk->sk_callback_lock);
return ret;
}
/*
* this is a little helper that is called by callers who have seen a problem
* with an sc and want to detach it from the nn if someone already hasn't beat
* them to it. if an error is given then the shutdown will be persistent
* and pending transmits will be canceled.
*/
static void o2net_ensure_shutdown(struct o2net_node *nn,
struct o2net_sock_container *sc,
int err)
{
spin_lock(&nn->nn_lock);
if (nn->nn_sc == sc)
o2net_set_nn_state(nn, NULL, 0, err);
spin_unlock(&nn->nn_lock);
}
/*
* This work queue function performs the blocking parts of socket shutdown. A
* few paths lead here. set_nn_state will trigger this callback if it sees an
* sc detached from the nn. state_change will also trigger this callback
* directly when it sees errors. In that case we need to call set_nn_state
* ourselves as state_change couldn't get the nn_lock and call set_nn_state
* itself.
*/
static void o2net_shutdown_sc(struct work_struct *work)
{
struct o2net_sock_container *sc =
container_of(work, struct o2net_sock_container,
sc_shutdown_work);
struct o2net_node *nn = o2net_nn_from_num(sc->sc_node->nd_num);
sclog(sc, "shutting down\n");
/* drop the callbacks ref and call shutdown only once */
if (o2net_unregister_callbacks(sc->sc_sock->sk, sc)) {
/* we shouldn't flush as we're in the thread, the
* races with pending sc work structs are harmless */
del_timer_sync(&sc->sc_idle_timeout);
o2net_sc_cancel_delayed_work(sc, &sc->sc_keepalive_work);
sc_put(sc);
kernel_sock_shutdown(sc->sc_sock, SHUT_RDWR);
}
/* not fatal so failed connects before the other guy has our
* heartbeat can be retried */
o2net_ensure_shutdown(nn, sc, 0);
sc_put(sc);
}
/* ------------------------------------------------------------ */
static int o2net_handler_cmp(struct o2net_msg_handler *nmh, u32 msg_type,
u32 key)
{
int ret = memcmp(&nmh->nh_key, &key, sizeof(key));
if (ret == 0)
ret = memcmp(&nmh->nh_msg_type, &msg_type, sizeof(msg_type));
return ret;
}
static struct o2net_msg_handler *
o2net_handler_tree_lookup(u32 msg_type, u32 key, struct rb_node ***ret_p,
struct rb_node **ret_parent)
{
struct rb_node **p = &o2net_handler_tree.rb_node;
struct rb_node *parent = NULL;
struct o2net_msg_handler *nmh, *ret = NULL;
int cmp;
while (*p) {
parent = *p;
nmh = rb_entry(parent, struct o2net_msg_handler, nh_node);
cmp = o2net_handler_cmp(nmh, msg_type, key);
if (cmp < 0)
p = &(*p)->rb_left;
else if (cmp > 0)
p = &(*p)->rb_right;
else {
ret = nmh;
break;
}
}
if (ret_p != NULL)
*ret_p = p;
if (ret_parent != NULL)
*ret_parent = parent;
return ret;
}
static void o2net_handler_kref_release(struct kref *kref)
{
struct o2net_msg_handler *nmh;
nmh = container_of(kref, struct o2net_msg_handler, nh_kref);
kfree(nmh);
}
static void o2net_handler_put(struct o2net_msg_handler *nmh)
{
kref_put(&nmh->nh_kref, o2net_handler_kref_release);
}
/* max_len is protection for the handler func. incoming messages won't
* be given to the handler if their payload is longer than the max. */
int o2net_register_handler(u32 msg_type, u32 key, u32 max_len,
o2net_msg_handler_func *func, void *data,
o2net_post_msg_handler_func *post_func,
struct list_head *unreg_list)
{
struct o2net_msg_handler *nmh = NULL;
struct rb_node **p, *parent;
int ret = 0;
if (max_len > O2NET_MAX_PAYLOAD_BYTES) {
mlog(0, "max_len for message handler out of range: %u\n",
max_len);
ret = -EINVAL;
goto out;
}
if (!msg_type) {
mlog(0, "no message type provided: %u, %p\n", msg_type, func);
ret = -EINVAL;
goto out;
}
if (!func) {
mlog(0, "no message handler provided: %u, %p\n",
msg_type, func);
ret = -EINVAL;
goto out;
}
nmh = kzalloc(sizeof(struct o2net_msg_handler), GFP_NOFS);
if (nmh == NULL) {
ret = -ENOMEM;
goto out;
}
nmh->nh_func = func;
nmh->nh_func_data = data;
nmh->nh_post_func = post_func;
nmh->nh_msg_type = msg_type;
nmh->nh_max_len = max_len;
nmh->nh_key = key;
/* the tree and list get this ref.. they're both removed in
* unregister when this ref is dropped */
kref_init(&nmh->nh_kref);
INIT_LIST_HEAD(&nmh->nh_unregister_item);
write_lock(&o2net_handler_lock);
if (o2net_handler_tree_lookup(msg_type, key, &p, &parent))
ret = -EEXIST;
else {
rb_link_node(&nmh->nh_node, parent, p);
rb_insert_color(&nmh->nh_node, &o2net_handler_tree);
list_add_tail(&nmh->nh_unregister_item, unreg_list);
mlog(ML_TCP, "registered handler func %p type %u key %08x\n",
func, msg_type, key);
/* we've had some trouble with handlers seemingly vanishing. */
mlog_bug_on_msg(o2net_handler_tree_lookup(msg_type, key, &p,
&parent) == NULL,
"couldn't find handler we *just* registerd "
"for type %u key %08x\n", msg_type, key);
}
write_unlock(&o2net_handler_lock);
if (ret)
goto out;
out:
if (ret)
kfree(nmh);
return ret;
}
EXPORT_SYMBOL_GPL(o2net_register_handler);
void o2net_unregister_handler_list(struct list_head *list)
{
struct o2net_msg_handler *nmh, *n;
write_lock(&o2net_handler_lock);
list_for_each_entry_safe(nmh, n, list, nh_unregister_item) {
mlog(ML_TCP, "unregistering handler func %p type %u key %08x\n",
nmh->nh_func, nmh->nh_msg_type, nmh->nh_key);
rb_erase(&nmh->nh_node, &o2net_handler_tree);
list_del_init(&nmh->nh_unregister_item);
kref_put(&nmh->nh_kref, o2net_handler_kref_release);
}
write_unlock(&o2net_handler_lock);
}
EXPORT_SYMBOL_GPL(o2net_unregister_handler_list);
static struct o2net_msg_handler *o2net_handler_get(u32 msg_type, u32 key)
{
struct o2net_msg_handler *nmh;
read_lock(&o2net_handler_lock);
nmh = o2net_handler_tree_lookup(msg_type, key, NULL, NULL);
if (nmh)
kref_get(&nmh->nh_kref);
read_unlock(&o2net_handler_lock);
return nmh;
}
/* ------------------------------------------------------------ */
static int o2net_recv_tcp_msg(struct socket *sock, void *data, size_t len)
{
int ret;
mm_segment_t oldfs;
struct kvec vec = {
.iov_len = len,
.iov_base = data,
};
struct msghdr msg = {
.msg_iovlen = 1,
.msg_iov = (struct iovec *)&vec,
.msg_flags = MSG_DONTWAIT,
};
oldfs = get_fs();
set_fs(get_ds());
ret = sock_recvmsg(sock, &msg, len, msg.msg_flags);
set_fs(oldfs);
return ret;
}
static int o2net_send_tcp_msg(struct socket *sock, struct kvec *vec,
size_t veclen, size_t total)
{
int ret;
mm_segment_t oldfs;
struct msghdr msg = {
.msg_iov = (struct iovec *)vec,
.msg_iovlen = veclen,
};
if (sock == NULL) {
ret = -EINVAL;
goto out;
}
oldfs = get_fs();
set_fs(get_ds());
ret = sock_sendmsg(sock, &msg, total);
set_fs(oldfs);
if (ret != total) {
mlog(ML_ERROR, "sendmsg returned %d instead of %zu\n", ret,
total);
if (ret >= 0)
ret = -EPIPE; /* should be smarter, I bet */
goto out;
}
ret = 0;
out:
if (ret < 0)
mlog(0, "returning error: %d\n", ret);
return ret;
}
static void o2net_sendpage(struct o2net_sock_container *sc,
void *kmalloced_virt,
size_t size)
{
struct o2net_node *nn = o2net_nn_from_num(sc->sc_node->nd_num);
ssize_t ret;
while (1) {
mutex_lock(&sc->sc_send_lock);
ret = sc->sc_sock->ops->sendpage(sc->sc_sock,
virt_to_page(kmalloced_virt),
(long)kmalloced_virt & ~PAGE_MASK,
size, MSG_DONTWAIT);
mutex_unlock(&sc->sc_send_lock);
if (ret == size)
break;
if (ret == (ssize_t)-EAGAIN) {
mlog(0, "sendpage of size %zu to " SC_NODEF_FMT
" returned EAGAIN\n", size, SC_NODEF_ARGS(sc));
cond_resched();
continue;
}
mlog(ML_ERROR, "sendpage of size %zu to " SC_NODEF_FMT
" failed with %zd\n", size, SC_NODEF_ARGS(sc), ret);
o2net_ensure_shutdown(nn, sc, 0);
break;
}
}
static void o2net_init_msg(struct o2net_msg *msg, u16 data_len, u16 msg_type, u32 key)
{
memset(msg, 0, sizeof(struct o2net_msg));
msg->magic = cpu_to_be16(O2NET_MSG_MAGIC);
msg->data_len = cpu_to_be16(data_len);
msg->msg_type = cpu_to_be16(msg_type);
msg->sys_status = cpu_to_be32(O2NET_ERR_NONE);
msg->status = 0;
msg->key = cpu_to_be32(key);
}
static int o2net_tx_can_proceed(struct o2net_node *nn,
struct o2net_sock_container **sc_ret,
int *error)
{
int ret = 0;
spin_lock(&nn->nn_lock);
if (nn->nn_persistent_error) {
ret = 1;
*sc_ret = NULL;
*error = nn->nn_persistent_error;
} else if (nn->nn_sc_valid) {
kref_get(&nn->nn_sc->sc_kref);
ret = 1;
*sc_ret = nn->nn_sc;
*error = 0;
}
spin_unlock(&nn->nn_lock);
return ret;
}
int o2net_send_message_vec(u32 msg_type, u32 key, struct kvec *caller_vec,
size_t caller_veclen, u8 target_node, int *status)
{
int ret = 0;
struct o2net_msg *msg = NULL;
size_t veclen, caller_bytes = 0;
struct kvec *vec = NULL;
struct o2net_sock_container *sc = NULL;
struct o2net_node *nn = o2net_nn_from_num(target_node);
struct o2net_status_wait nsw = {
.ns_node_item = LIST_HEAD_INIT(nsw.ns_node_item),
};
struct o2net_send_tracking nst;
o2net_init_nst(&nst, msg_type, key, current, target_node);
if (o2net_wq == NULL) {
mlog(0, "attempt to tx without o2netd running\n");
ret = -ESRCH;
goto out;
}
if (caller_veclen == 0) {
mlog(0, "bad kvec array length\n");
ret = -EINVAL;
goto out;
}
caller_bytes = iov_length((struct iovec *)caller_vec, caller_veclen);
if (caller_bytes > O2NET_MAX_PAYLOAD_BYTES) {
mlog(0, "total payload len %zu too large\n", caller_bytes);
ret = -EINVAL;
goto out;
}
if (target_node == o2nm_this_node()) {
ret = -ELOOP;
goto out;
}
o2net_debug_add_nst(&nst);
o2net_set_nst_sock_time(&nst);
wait_event(nn->nn_sc_wq, o2net_tx_can_proceed(nn, &sc, &ret));
if (ret)
goto out;
o2net_set_nst_sock_container(&nst, sc);
veclen = caller_veclen + 1;
vec = kmalloc(sizeof(struct kvec) * veclen, GFP_ATOMIC);
if (vec == NULL) {
mlog(0, "failed to %zu element kvec!\n", veclen);
ret = -ENOMEM;
goto out;
}
msg = kmalloc(sizeof(struct o2net_msg), GFP_ATOMIC);
if (!msg) {
mlog(0, "failed to allocate a o2net_msg!\n");
ret = -ENOMEM;
goto out;
}
o2net_init_msg(msg, caller_bytes, msg_type, key);
vec[0].iov_len = sizeof(struct o2net_msg);
vec[0].iov_base = msg;
memcpy(&vec[1], caller_vec, caller_veclen * sizeof(struct kvec));
ret = o2net_prep_nsw(nn, &nsw);
if (ret)
goto out;
msg->msg_num = cpu_to_be32(nsw.ns_id);
o2net_set_nst_msg_id(&nst, nsw.ns_id);
o2net_set_nst_send_time(&nst);
/* finally, convert the message header to network byte-order
* and send */
mutex_lock(&sc->sc_send_lock);
ret = o2net_send_tcp_msg(sc->sc_sock, vec, veclen,
sizeof(struct o2net_msg) + caller_bytes);
mutex_unlock(&sc->sc_send_lock);
msglog(msg, "sending returned %d\n", ret);
if (ret < 0) {
mlog(0, "error returned from o2net_send_tcp_msg=%d\n", ret);
goto out;
}
/* wait on other node's handler */
o2net_set_nst_status_time(&nst);
wait_event(nsw.ns_wq, o2net_nsw_completed(nn, &nsw));
o2net_update_send_stats(&nst, sc);
/* Note that we avoid overwriting the callers status return
* variable if a system error was reported on the other
* side. Callers beware. */
ret = o2net_sys_err_to_errno(nsw.ns_sys_status);
if (status && !ret)
*status = nsw.ns_status;
mlog(0, "woken, returning system status %d, user status %d\n",
ret, nsw.ns_status);
out:
o2net_debug_del_nst(&nst); /* must be before dropping sc and node */
if (sc)
sc_put(sc);
if (vec)
kfree(vec);
if (msg)
kfree(msg);
o2net_complete_nsw(nn, &nsw, 0, 0, 0);
return ret;
}
EXPORT_SYMBOL_GPL(o2net_send_message_vec);
int o2net_send_message(u32 msg_type, u32 key, void *data, u32 len,
u8 target_node, int *status)
{
struct kvec vec = {
.iov_base = data,
.iov_len = len,
};
return o2net_send_message_vec(msg_type, key, &vec, 1,
target_node, status);
}
EXPORT_SYMBOL_GPL(o2net_send_message);
static int o2net_send_status_magic(struct socket *sock, struct o2net_msg *hdr,
enum o2net_system_error syserr, int err)
{
struct kvec vec = {
.iov_base = hdr,
.iov_len = sizeof(struct o2net_msg),
};
BUG_ON(syserr >= O2NET_ERR_MAX);
/* leave other fields intact from the incoming message, msg_num
* in particular */
hdr->sys_status = cpu_to_be32(syserr);
hdr->status = cpu_to_be32(err);
hdr->magic = cpu_to_be16(O2NET_MSG_STATUS_MAGIC); // twiddle the magic
hdr->data_len = 0;
msglog(hdr, "about to send status magic %d\n", err);
/* hdr has been in host byteorder this whole time */
return o2net_send_tcp_msg(sock, &vec, 1, sizeof(struct o2net_msg));
}
/* this returns -errno if the header was unknown or too large, etc.
* after this is called the buffer us reused for the next message */
static int o2net_process_message(struct o2net_sock_container *sc,
struct o2net_msg *hdr)
{
struct o2net_node *nn = o2net_nn_from_num(sc->sc_node->nd_num);
int ret = 0, handler_status;
enum o2net_system_error syserr;
struct o2net_msg_handler *nmh = NULL;
void *ret_data = NULL;
msglog(hdr, "processing message\n");
o2net_sc_postpone_idle(sc);
switch(be16_to_cpu(hdr->magic)) {
case O2NET_MSG_STATUS_MAGIC:
/* special type for returning message status */
o2net_complete_nsw(nn, NULL,
be32_to_cpu(hdr->msg_num),
be32_to_cpu(hdr->sys_status),
be32_to_cpu(hdr->status));
goto out;
case O2NET_MSG_KEEP_REQ_MAGIC:
o2net_sendpage(sc, o2net_keep_resp,
sizeof(*o2net_keep_resp));
goto out;
case O2NET_MSG_KEEP_RESP_MAGIC:
goto out;
case O2NET_MSG_MAGIC:
break;
default:
msglog(hdr, "bad magic\n");
ret = -EINVAL;
goto out;
break;
}
/* find a handler for it */
handler_status = 0;
nmh = o2net_handler_get(be16_to_cpu(hdr->msg_type),
be32_to_cpu(hdr->key));
if (!nmh) {
mlog(ML_TCP, "couldn't find handler for type %u key %08x\n",
be16_to_cpu(hdr->msg_type), be32_to_cpu(hdr->key));
syserr = O2NET_ERR_NO_HNDLR;
goto out_respond;
}
syserr = O2NET_ERR_NONE;
if (be16_to_cpu(hdr->data_len) > nmh->nh_max_len)
syserr = O2NET_ERR_OVERFLOW;
if (syserr != O2NET_ERR_NONE)
goto out_respond;
o2net_set_func_start_time(sc);
sc->sc_msg_key = be32_to_cpu(hdr->key);
sc->sc_msg_type = be16_to_cpu(hdr->msg_type);
handler_status = (nmh->nh_func)(hdr, sizeof(struct o2net_msg) +
be16_to_cpu(hdr->data_len),
nmh->nh_func_data, &ret_data);
o2net_set_func_stop_time(sc);
o2net_update_recv_stats(sc);
out_respond:
/* this destroys the hdr, so don't use it after this */
mutex_lock(&sc->sc_send_lock);
ret = o2net_send_status_magic(sc->sc_sock, hdr, syserr,
handler_status);
mutex_unlock(&sc->sc_send_lock);
hdr = NULL;
mlog(0, "sending handler status %d, syserr %d returned %d\n",
handler_status, syserr, ret);
if (nmh) {
BUG_ON(ret_data != NULL && nmh->nh_post_func == NULL);
if (nmh->nh_post_func)
(nmh->nh_post_func)(handler_status, nmh->nh_func_data,
ret_data);
}
out:
if (nmh)
o2net_handler_put(nmh);
return ret;
}
static int o2net_check_handshake(struct o2net_sock_container *sc)
{
struct o2net_handshake *hand = page_address(sc->sc_page);
struct o2net_node *nn = o2net_nn_from_num(sc->sc_node->nd_num);
if (hand->protocol_version != cpu_to_be64(O2NET_PROTOCOL_VERSION)) {
mlog(ML_NOTICE, SC_NODEF_FMT " advertised net protocol "
"version %llu but %llu is required, disconnecting\n",
SC_NODEF_ARGS(sc),
(unsigned long long)be64_to_cpu(hand->protocol_version),
O2NET_PROTOCOL_VERSION);
/* don't bother reconnecting if its the wrong version. */
o2net_ensure_shutdown(nn, sc, -ENOTCONN);
return -1;
}
/*
* Ensure timeouts are consistent with other nodes, otherwise
* we can end up with one node thinking that the other must be down,
* but isn't. This can ultimately cause corruption.
*/
if (be32_to_cpu(hand->o2net_idle_timeout_ms) !=
o2net_idle_timeout()) {
mlog(ML_NOTICE, SC_NODEF_FMT " uses a network idle timeout of "
"%u ms, but we use %u ms locally. disconnecting\n",
SC_NODEF_ARGS(sc),
be32_to_cpu(hand->o2net_idle_timeout_ms),
o2net_idle_timeout());
o2net_ensure_shutdown(nn, sc, -ENOTCONN);
return -1;
}
if (be32_to_cpu(hand->o2net_keepalive_delay_ms) !=
o2net_keepalive_delay()) {
mlog(ML_NOTICE, SC_NODEF_FMT " uses a keepalive delay of "
"%u ms, but we use %u ms locally. disconnecting\n",
SC_NODEF_ARGS(sc),
be32_to_cpu(hand->o2net_keepalive_delay_ms),
o2net_keepalive_delay());
o2net_ensure_shutdown(nn, sc, -ENOTCONN);
return -1;
}
if (be32_to_cpu(hand->o2hb_heartbeat_timeout_ms) !=
O2HB_MAX_WRITE_TIMEOUT_MS) {
mlog(ML_NOTICE, SC_NODEF_FMT " uses a heartbeat timeout of "
"%u ms, but we use %u ms locally. disconnecting\n",
SC_NODEF_ARGS(sc),
be32_to_cpu(hand->o2hb_heartbeat_timeout_ms),
O2HB_MAX_WRITE_TIMEOUT_MS);
o2net_ensure_shutdown(nn, sc, -ENOTCONN);
return -1;
}
sc->sc_handshake_ok = 1;
spin_lock(&nn->nn_lock);
/* set valid and queue the idle timers only if it hasn't been
* shut down already */
if (nn->nn_sc == sc) {
o2net_sc_reset_idle_timer(sc);
atomic_set(&nn->nn_timeout, 0);
o2net_set_nn_state(nn, sc, 1, 0);
}
spin_unlock(&nn->nn_lock);
/* shift everything up as though it wasn't there */
sc->sc_page_off -= sizeof(struct o2net_handshake);
if (sc->sc_page_off)
memmove(hand, hand + 1, sc->sc_page_off);
return 0;
}
/* this demuxes the queued rx bytes into header or payload bits and calls
* handlers as each full message is read off the socket. it returns -error,
* == 0 eof, or > 0 for progress made.*/
static int o2net_advance_rx(struct o2net_sock_container *sc)
{
struct o2net_msg *hdr;
int ret = 0;
void *data;
size_t datalen;
sclog(sc, "receiving\n");
o2net_set_advance_start_time(sc);
if (unlikely(sc->sc_handshake_ok == 0)) {
if(sc->sc_page_off < sizeof(struct o2net_handshake)) {
data = page_address(sc->sc_page) + sc->sc_page_off;
datalen = sizeof(struct o2net_handshake) - sc->sc_page_off;
ret = o2net_recv_tcp_msg(sc->sc_sock, data, datalen);
if (ret > 0)
sc->sc_page_off += ret;
}
if (sc->sc_page_off == sizeof(struct o2net_handshake)) {
o2net_check_handshake(sc);
if (unlikely(sc->sc_handshake_ok == 0))
ret = -EPROTO;
}
goto out;
}
/* do we need more header? */
if (sc->sc_page_off < sizeof(struct o2net_msg)) {
data = page_address(sc->sc_page) + sc->sc_page_off;
datalen = sizeof(struct o2net_msg) - sc->sc_page_off;
ret = o2net_recv_tcp_msg(sc->sc_sock, data, datalen);
if (ret > 0) {
sc->sc_page_off += ret;
/* only swab incoming here.. we can
* only get here once as we cross from
* being under to over */
if (sc->sc_page_off == sizeof(struct o2net_msg)) {
hdr = page_address(sc->sc_page);
if (be16_to_cpu(hdr->data_len) >
O2NET_MAX_PAYLOAD_BYTES)
ret = -EOVERFLOW;
}
}
if (ret <= 0)
goto out;
}
if (sc->sc_page_off < sizeof(struct o2net_msg)) {
/* oof, still don't have a header */
goto out;
}
/* this was swabbed above when we first read it */
hdr = page_address(sc->sc_page);
msglog(hdr, "at page_off %zu\n", sc->sc_page_off);
/* do we need more payload? */
if (sc->sc_page_off - sizeof(struct o2net_msg) < be16_to_cpu(hdr->data_len)) {
/* need more payload */
data = page_address(sc->sc_page) + sc->sc_page_off;
datalen = (sizeof(struct o2net_msg) + be16_to_cpu(hdr->data_len)) -
sc->sc_page_off;
ret = o2net_recv_tcp_msg(sc->sc_sock, data, datalen);
if (ret > 0)
sc->sc_page_off += ret;
if (ret <= 0)
goto out;
}
if (sc->sc_page_off - sizeof(struct o2net_msg) == be16_to_cpu(hdr->data_len)) {
/* we can only get here once, the first time we read
* the payload.. so set ret to progress if the handler
* works out. after calling this the message is toast */
ret = o2net_process_message(sc, hdr);
if (ret == 0)
ret = 1;
sc->sc_page_off = 0;
}
out:
sclog(sc, "ret = %d\n", ret);
o2net_set_advance_stop_time(sc);
return ret;
}
/* this work func is triggerd by data ready. it reads until it can read no
* more. it interprets 0, eof, as fatal. if data_ready hits while we're doing
* our work the work struct will be marked and we'll be called again. */
static void o2net_rx_until_empty(struct work_struct *work)
{
struct o2net_sock_container *sc =
container_of(work, struct o2net_sock_container, sc_rx_work);
int ret;
do {
ret = o2net_advance_rx(sc);
} while (ret > 0);
if (ret <= 0 && ret != -EAGAIN) {
struct o2net_node *nn = o2net_nn_from_num(sc->sc_node->nd_num);
sclog(sc, "saw error %d, closing\n", ret);
/* not permanent so read failed handshake can retry */
o2net_ensure_shutdown(nn, sc, 0);
}
sc_put(sc);
}
static int o2net_set_nodelay(struct socket *sock)
{
int ret, val = 1;
mm_segment_t oldfs;
oldfs = get_fs();
set_fs(KERNEL_DS);
/*
* Dear unsuspecting programmer,
*
* Don't use sock_setsockopt() for SOL_TCP. It doesn't check its level
* argument and assumes SOL_SOCKET so, say, your TCP_NODELAY will
* silently turn into SO_DEBUG.
*
* Yours,
* Keeper of hilariously fragile interfaces.
*/
ret = sock->ops->setsockopt(sock, SOL_TCP, TCP_NODELAY,
(char __user *)&val, sizeof(val));
set_fs(oldfs);
return ret;
}
static void o2net_initialize_handshake(void)
{
o2net_hand->o2hb_heartbeat_timeout_ms = cpu_to_be32(
O2HB_MAX_WRITE_TIMEOUT_MS);
o2net_hand->o2net_idle_timeout_ms = cpu_to_be32(o2net_idle_timeout());
o2net_hand->o2net_keepalive_delay_ms = cpu_to_be32(
o2net_keepalive_delay());
o2net_hand->o2net_reconnect_delay_ms = cpu_to_be32(
o2net_reconnect_delay());
}
/* ------------------------------------------------------------ */
/* called when a connect completes and after a sock is accepted. the
* rx path will see the response and mark the sc valid */
static void o2net_sc_connect_completed(struct work_struct *work)
{
struct o2net_sock_container *sc =
container_of(work, struct o2net_sock_container,
sc_connect_work);
mlog(ML_MSG, "sc sending handshake with ver %llu id %llx\n",
(unsigned long long)O2NET_PROTOCOL_VERSION,
(unsigned long long)be64_to_cpu(o2net_hand->connector_id));
o2net_initialize_handshake();
o2net_sendpage(sc, o2net_hand, sizeof(*o2net_hand));
sc_put(sc);
}
/* this is called as a work_struct func. */
static void o2net_sc_send_keep_req(struct work_struct *work)
{
struct o2net_sock_container *sc =
container_of(work, struct o2net_sock_container,
sc_keepalive_work.work);
o2net_sendpage(sc, o2net_keep_req, sizeof(*o2net_keep_req));
sc_put(sc);
}
/* socket shutdown does a del_timer_sync against this as it tears down.
* we can't start this timer until we've got to the point in sc buildup
* where shutdown is going to be involved */
static void o2net_idle_timer(unsigned long data)
{
struct o2net_sock_container *sc = (struct o2net_sock_container *)data;
struct o2net_node *nn = o2net_nn_from_num(sc->sc_node->nd_num);
#ifdef CONFIG_DEBUG_FS
ktime_t now = ktime_get();
#endif
printk(KERN_NOTICE "o2net: connection to " SC_NODEF_FMT " has been idle for %u.%u "
"seconds, shutting it down.\n", SC_NODEF_ARGS(sc),
o2net_idle_timeout() / 1000,
o2net_idle_timeout() % 1000);
#ifdef CONFIG_DEBUG_FS
mlog(ML_NOTICE, "Here are some times that might help debug the "
"situation: (Timer: %lld, Now %lld, DataReady %lld, Advance %lld-%lld, "
"Key 0x%08x, Func %u, FuncTime %lld-%lld)\n",
(long long)ktime_to_us(sc->sc_tv_timer), (long long)ktime_to_us(now),
(long long)ktime_to_us(sc->sc_tv_data_ready),
(long long)ktime_to_us(sc->sc_tv_advance_start),
(long long)ktime_to_us(sc->sc_tv_advance_stop),
sc->sc_msg_key, sc->sc_msg_type,
(long long)ktime_to_us(sc->sc_tv_func_start),
(long long)ktime_to_us(sc->sc_tv_func_stop));
#endif
/*
* Initialize the nn_timeout so that the next connection attempt
* will continue in o2net_start_connect.
*/
atomic_set(&nn->nn_timeout, 1);
o2net_sc_queue_work(sc, &sc->sc_shutdown_work);
}
static void o2net_sc_reset_idle_timer(struct o2net_sock_container *sc)
{
o2net_sc_cancel_delayed_work(sc, &sc->sc_keepalive_work);
o2net_sc_queue_delayed_work(sc, &sc->sc_keepalive_work,
msecs_to_jiffies(o2net_keepalive_delay()));
o2net_set_sock_timer(sc);
mod_timer(&sc->sc_idle_timeout,
jiffies + msecs_to_jiffies(o2net_idle_timeout()));
}
static void o2net_sc_postpone_idle(struct o2net_sock_container *sc)
{
/* Only push out an existing timer */
if (timer_pending(&sc->sc_idle_timeout))
o2net_sc_reset_idle_timer(sc);
}
/* this work func is kicked whenever a path sets the nn state which doesn't
* have valid set. This includes seeing hb come up, losing a connection,
* having a connect attempt fail, etc. This centralizes the logic which decides
* if a connect attempt should be made or if we should give up and all future
* transmit attempts should fail */
static void o2net_start_connect(struct work_struct *work)
{
struct o2net_node *nn =
container_of(work, struct o2net_node, nn_connect_work.work);
struct o2net_sock_container *sc = NULL;
struct o2nm_node *node = NULL, *mynode = NULL;
struct socket *sock = NULL;
struct sockaddr_in myaddr = {0, }, remoteaddr = {0, };
int ret = 0, stop;
unsigned int timeout;
/* if we're greater we initiate tx, otherwise we accept */
if (o2nm_this_node() <= o2net_num_from_nn(nn))
goto out;
/* watch for racing with tearing a node down */
node = o2nm_get_node_by_num(o2net_num_from_nn(nn));
if (node == NULL) {
ret = 0;
goto out;
}
mynode = o2nm_get_node_by_num(o2nm_this_node());
if (mynode == NULL) {
ret = 0;
goto out;
}
spin_lock(&nn->nn_lock);
/*
* see if we already have one pending or have given up.
* For nn_timeout, it is set when we close the connection
* because of the idle time out. So it means that we have
* at least connected to that node successfully once,
* now try to connect to it again.
*/
timeout = atomic_read(&nn->nn_timeout);
stop = (nn->nn_sc ||
(nn->nn_persistent_error &&
(nn->nn_persistent_error != -ENOTCONN || timeout == 0)));
spin_unlock(&nn->nn_lock);
if (stop)
goto out;
nn->nn_last_connect_attempt = jiffies;
sc = sc_alloc(node);
if (sc == NULL) {
mlog(0, "couldn't allocate sc\n");
ret = -ENOMEM;
goto out;
}
ret = sock_create(PF_INET, SOCK_STREAM, IPPROTO_TCP, &sock);
if (ret < 0) {
mlog(0, "can't create socket: %d\n", ret);
goto out;
}
sc->sc_sock = sock; /* freed by sc_kref_release */
sock->sk->sk_allocation = GFP_ATOMIC;
myaddr.sin_family = AF_INET;
myaddr.sin_addr.s_addr = mynode->nd_ipv4_address;
myaddr.sin_port = htons(0); /* any port */
ret = sock->ops->bind(sock, (struct sockaddr *)&myaddr,
sizeof(myaddr));
if (ret) {
mlog(ML_ERROR, "bind failed with %d at address %pI4\n",
ret, &mynode->nd_ipv4_address);
goto out;
}
ret = o2net_set_nodelay(sc->sc_sock);
if (ret) {
mlog(ML_ERROR, "setting TCP_NODELAY failed with %d\n", ret);
goto out;
}
o2net_register_callbacks(sc->sc_sock->sk, sc);
spin_lock(&nn->nn_lock);
/* handshake completion will set nn->nn_sc_valid */
o2net_set_nn_state(nn, sc, 0, 0);
spin_unlock(&nn->nn_lock);
remoteaddr.sin_family = AF_INET;
remoteaddr.sin_addr.s_addr = node->nd_ipv4_address;
remoteaddr.sin_port = node->nd_ipv4_port;
ret = sc->sc_sock->ops->connect(sc->sc_sock,
(struct sockaddr *)&remoteaddr,
sizeof(remoteaddr),
O_NONBLOCK);
if (ret == -EINPROGRESS)
ret = 0;
out:
if (ret) {
mlog(ML_NOTICE, "connect attempt to " SC_NODEF_FMT " failed "
"with errno %d\n", SC_NODEF_ARGS(sc), ret);
/* 0 err so that another will be queued and attempted
* from set_nn_state */
if (sc)
o2net_ensure_shutdown(nn, sc, 0);
}
if (sc)
sc_put(sc);
if (node)
o2nm_node_put(node);
if (mynode)
o2nm_node_put(mynode);
return;
}
static void o2net_connect_expired(struct work_struct *work)
{
struct o2net_node *nn =
container_of(work, struct o2net_node, nn_connect_expired.work);
spin_lock(&nn->nn_lock);
if (!nn->nn_sc_valid) {
mlog(ML_ERROR, "no connection established with node %u after "
"%u.%u seconds, giving up and returning errors.\n",
o2net_num_from_nn(nn),
o2net_idle_timeout() / 1000,
o2net_idle_timeout() % 1000);
o2net_set_nn_state(nn, NULL, 0, -ENOTCONN);
}
spin_unlock(&nn->nn_lock);
}
static void o2net_still_up(struct work_struct *work)
{
struct o2net_node *nn =
container_of(work, struct o2net_node, nn_still_up.work);
o2quo_hb_still_up(o2net_num_from_nn(nn));
}
/* ------------------------------------------------------------ */
void o2net_disconnect_node(struct o2nm_node *node)
{
struct o2net_node *nn = o2net_nn_from_num(node->nd_num);
/* don't reconnect until it's heartbeating again */
spin_lock(&nn->nn_lock);
atomic_set(&nn->nn_timeout, 0);
o2net_set_nn_state(nn, NULL, 0, -ENOTCONN);
spin_unlock(&nn->nn_lock);
if (o2net_wq) {
cancel_delayed_work(&nn->nn_connect_expired);
cancel_delayed_work(&nn->nn_connect_work);
cancel_delayed_work(&nn->nn_still_up);
flush_workqueue(o2net_wq);
}
}
static void o2net_hb_node_down_cb(struct o2nm_node *node, int node_num,
void *data)
{
o2quo_hb_down(node_num);
if (!node)
return;
if (node_num != o2nm_this_node())
o2net_disconnect_node(node);
BUG_ON(atomic_read(&o2net_connected_peers) < 0);
}
static void o2net_hb_node_up_cb(struct o2nm_node *node, int node_num,
void *data)
{
struct o2net_node *nn = o2net_nn_from_num(node_num);
o2quo_hb_up(node_num);
BUG_ON(!node);
/* ensure an immediate connect attempt */
nn->nn_last_connect_attempt = jiffies -
(msecs_to_jiffies(o2net_reconnect_delay()) + 1);
if (node_num != o2nm_this_node()) {
/* believe it or not, accept and node hearbeating testing
* can succeed for this node before we got here.. so
* only use set_nn_state to clear the persistent error
* if that hasn't already happened */
spin_lock(&nn->nn_lock);
atomic_set(&nn->nn_timeout, 0);
if (nn->nn_persistent_error)
o2net_set_nn_state(nn, NULL, 0, 0);
spin_unlock(&nn->nn_lock);
}
}
void o2net_unregister_hb_callbacks(void)
{
o2hb_unregister_callback(NULL, &o2net_hb_up);
o2hb_unregister_callback(NULL, &o2net_hb_down);
}
int o2net_register_hb_callbacks(void)
{
int ret;
o2hb_setup_callback(&o2net_hb_down, O2HB_NODE_DOWN_CB,
o2net_hb_node_down_cb, NULL, O2NET_HB_PRI);
o2hb_setup_callback(&o2net_hb_up, O2HB_NODE_UP_CB,
o2net_hb_node_up_cb, NULL, O2NET_HB_PRI);
ret = o2hb_register_callback(NULL, &o2net_hb_up);
if (ret == 0)
ret = o2hb_register_callback(NULL, &o2net_hb_down);
if (ret)
o2net_unregister_hb_callbacks();
return ret;
}
/* ------------------------------------------------------------ */
static int o2net_accept_one(struct socket *sock)
{
int ret, slen;
struct sockaddr_in sin;
struct socket *new_sock = NULL;
struct o2nm_node *node = NULL;
struct o2nm_node *local_node = NULL;
struct o2net_sock_container *sc = NULL;
struct o2net_node *nn;
BUG_ON(sock == NULL);
ret = sock_create_lite(sock->sk->sk_family, sock->sk->sk_type,
sock->sk->sk_protocol, &new_sock);
if (ret)
goto out;
new_sock->type = sock->type;
new_sock->ops = sock->ops;
ret = sock->ops->accept(sock, new_sock, O_NONBLOCK);
if (ret < 0)
goto out;
new_sock->sk->sk_allocation = GFP_ATOMIC;
ret = o2net_set_nodelay(new_sock);
if (ret) {
mlog(ML_ERROR, "setting TCP_NODELAY failed with %d\n", ret);
goto out;
}
slen = sizeof(sin);
ret = new_sock->ops->getname(new_sock, (struct sockaddr *) &sin,
&slen, 1);
if (ret < 0)
goto out;
node = o2nm_get_node_by_ip(sin.sin_addr.s_addr);
if (node == NULL) {
mlog(ML_NOTICE, "attempt to connect from unknown node at %pI4:%d\n",
&sin.sin_addr.s_addr, ntohs(sin.sin_port));
ret = -EINVAL;
goto out;
}
if (o2nm_this_node() >= node->nd_num) {
local_node = o2nm_get_node_by_num(o2nm_this_node());
mlog(ML_NOTICE, "unexpected connect attempt seen at node '%s' ("
"%u, %pI4:%d) from node '%s' (%u, %pI4:%d)\n",
local_node->nd_name, local_node->nd_num,
&(local_node->nd_ipv4_address),
ntohs(local_node->nd_ipv4_port),
node->nd_name, node->nd_num, &sin.sin_addr.s_addr,
ntohs(sin.sin_port));
ret = -EINVAL;
goto out;
}
/* this happens all the time when the other node sees our heartbeat
* and tries to connect before we see their heartbeat */
if (!o2hb_check_node_heartbeating_from_callback(node->nd_num)) {
mlog(ML_CONN, "attempt to connect from node '%s' at "
"%pI4:%d but it isn't heartbeating\n",
node->nd_name, &sin.sin_addr.s_addr,
ntohs(sin.sin_port));
ret = -EINVAL;
goto out;
}
nn = o2net_nn_from_num(node->nd_num);
spin_lock(&nn->nn_lock);
if (nn->nn_sc)
ret = -EBUSY;
else
ret = 0;
spin_unlock(&nn->nn_lock);
if (ret) {
mlog(ML_NOTICE, "attempt to connect from node '%s' at "
"%pI4:%d but it already has an open connection\n",
node->nd_name, &sin.sin_addr.s_addr,
ntohs(sin.sin_port));
goto out;
}
sc = sc_alloc(node);
if (sc == NULL) {
ret = -ENOMEM;
goto out;
}
sc->sc_sock = new_sock;
new_sock = NULL;
spin_lock(&nn->nn_lock);
atomic_set(&nn->nn_timeout, 0);
o2net_set_nn_state(nn, sc, 0, 0);
spin_unlock(&nn->nn_lock);
o2net_register_callbacks(sc->sc_sock->sk, sc);
o2net_sc_queue_work(sc, &sc->sc_rx_work);
o2net_initialize_handshake();
o2net_sendpage(sc, o2net_hand, sizeof(*o2net_hand));
out:
if (new_sock)
sock_release(new_sock);
if (node)
o2nm_node_put(node);
if (local_node)
o2nm_node_put(local_node);
if (sc)
sc_put(sc);
return ret;
}
static void o2net_accept_many(struct work_struct *work)
{
struct socket *sock = o2net_listen_sock;
while (o2net_accept_one(sock) == 0)
cond_resched();
}
static void o2net_listen_data_ready(struct sock *sk, int bytes)
{
void (*ready)(struct sock *sk, int bytes);
read_lock(&sk->sk_callback_lock);
ready = sk->sk_user_data;
if (ready == NULL) { /* check for teardown race */
ready = sk->sk_data_ready;
goto out;
}
/* ->sk_data_ready is also called for a newly established child socket
* before it has been accepted and the acceptor has set up their
* data_ready.. we only want to queue listen work for our listening
* socket */
if (sk->sk_state == TCP_LISTEN) {
mlog(ML_TCP, "bytes: %d\n", bytes);
queue_work(o2net_wq, &o2net_listen_work);
}
out:
read_unlock(&sk->sk_callback_lock);
ready(sk, bytes);
}
static int o2net_open_listening_sock(__be32 addr, __be16 port)
{
struct socket *sock = NULL;
int ret;
struct sockaddr_in sin = {
.sin_family = PF_INET,
.sin_addr = { .s_addr = addr },
.sin_port = port,
};
ret = sock_create(PF_INET, SOCK_STREAM, IPPROTO_TCP, &sock);
if (ret < 0) {
mlog(ML_ERROR, "unable to create socket, ret=%d\n", ret);
goto out;
}
sock->sk->sk_allocation = GFP_ATOMIC;
write_lock_bh(&sock->sk->sk_callback_lock);
sock->sk->sk_user_data = sock->sk->sk_data_ready;
sock->sk->sk_data_ready = o2net_listen_data_ready;
write_unlock_bh(&sock->sk->sk_callback_lock);
o2net_listen_sock = sock;
INIT_WORK(&o2net_listen_work, o2net_accept_many);
sock->sk->sk_reuse = 1;
ret = sock->ops->bind(sock, (struct sockaddr *)&sin, sizeof(sin));
if (ret < 0) {
mlog(ML_ERROR, "unable to bind socket at %pI4:%u, "
"ret=%d\n", &addr, ntohs(port), ret);
goto out;
}
ret = sock->ops->listen(sock, 64);
if (ret < 0) {
mlog(ML_ERROR, "unable to listen on %pI4:%u, ret=%d\n",
&addr, ntohs(port), ret);
}
out:
if (ret) {
o2net_listen_sock = NULL;
if (sock)
sock_release(sock);
}
return ret;
}
/*
* called from node manager when we should bring up our network listening
* socket. node manager handles all the serialization to only call this
* once and to match it with o2net_stop_listening(). note,
* o2nm_this_node() doesn't work yet as we're being called while it
* is being set up.
*/
int o2net_start_listening(struct o2nm_node *node)
{
int ret = 0;
BUG_ON(o2net_wq != NULL);
BUG_ON(o2net_listen_sock != NULL);
mlog(ML_KTHREAD, "starting o2net thread...\n");
o2net_wq = create_singlethread_workqueue("o2net");
if (o2net_wq == NULL) {
mlog(ML_ERROR, "unable to launch o2net thread\n");
return -ENOMEM; /* ? */
}
ret = o2net_open_listening_sock(node->nd_ipv4_address,
node->nd_ipv4_port);
if (ret) {
destroy_workqueue(o2net_wq);
o2net_wq = NULL;
} else
o2quo_conn_up(node->nd_num);
return ret;
}
/* again, o2nm_this_node() doesn't work here as we're involved in
* tearing it down */
void o2net_stop_listening(struct o2nm_node *node)
{
struct socket *sock = o2net_listen_sock;
size_t i;
BUG_ON(o2net_wq == NULL);
BUG_ON(o2net_listen_sock == NULL);
/* stop the listening socket from generating work */
write_lock_bh(&sock->sk->sk_callback_lock);
sock->sk->sk_data_ready = sock->sk->sk_user_data;
sock->sk->sk_user_data = NULL;
write_unlock_bh(&sock->sk->sk_callback_lock);
for (i = 0; i < ARRAY_SIZE(o2net_nodes); i++) {
struct o2nm_node *node = o2nm_get_node_by_num(i);
if (node) {
o2net_disconnect_node(node);
o2nm_node_put(node);
}
}
/* finish all work and tear down the work queue */
mlog(ML_KTHREAD, "waiting for o2net thread to exit....\n");
destroy_workqueue(o2net_wq);
o2net_wq = NULL;
sock_release(o2net_listen_sock);
o2net_listen_sock = NULL;
o2quo_conn_err(node->nd_num);
}
/* ------------------------------------------------------------ */
int o2net_init(void)
{
unsigned long i;
o2quo_init();
if (o2net_debugfs_init())
return -ENOMEM;
o2net_hand = kzalloc(sizeof(struct o2net_handshake), GFP_KERNEL);
o2net_keep_req = kzalloc(sizeof(struct o2net_msg), GFP_KERNEL);
o2net_keep_resp = kzalloc(sizeof(struct o2net_msg), GFP_KERNEL);
if (!o2net_hand || !o2net_keep_req || !o2net_keep_resp) {
kfree(o2net_hand);
kfree(o2net_keep_req);
kfree(o2net_keep_resp);
return -ENOMEM;
}
o2net_hand->protocol_version = cpu_to_be64(O2NET_PROTOCOL_VERSION);
o2net_hand->connector_id = cpu_to_be64(1);
o2net_keep_req->magic = cpu_to_be16(O2NET_MSG_KEEP_REQ_MAGIC);
o2net_keep_resp->magic = cpu_to_be16(O2NET_MSG_KEEP_RESP_MAGIC);
for (i = 0; i < ARRAY_SIZE(o2net_nodes); i++) {
struct o2net_node *nn = o2net_nn_from_num(i);
atomic_set(&nn->nn_timeout, 0);
spin_lock_init(&nn->nn_lock);
INIT_DELAYED_WORK(&nn->nn_connect_work, o2net_start_connect);
INIT_DELAYED_WORK(&nn->nn_connect_expired,
o2net_connect_expired);
INIT_DELAYED_WORK(&nn->nn_still_up, o2net_still_up);
/* until we see hb from a node we'll return einval */
nn->nn_persistent_error = -ENOTCONN;
init_waitqueue_head(&nn->nn_sc_wq);
idr_init(&nn->nn_status_idr);
INIT_LIST_HEAD(&nn->nn_status_list);
}
return 0;
}
void o2net_exit(void)
{
o2quo_exit();
kfree(o2net_hand);
kfree(o2net_keep_req);
kfree(o2net_keep_resp);
o2net_debugfs_exit();
}
| gpl-2.0 |
xcstacy/kernel-N8000 | drivers/net/ibm_newemac/rgmii.c | 3186 | 7965 | /*
* drivers/net/ibm_newemac/rgmii.c
*
* Driver for PowerPC 4xx on-chip ethernet controller, RGMII bridge support.
*
* Copyright 2007 Benjamin Herrenschmidt, IBM Corp.
* <benh@kernel.crashing.org>
*
* Based on the arch/ppc version of the driver:
*
* Copyright (c) 2004, 2005 Zultys Technologies.
* Eugene Surovegin <eugene.surovegin@zultys.com> or <ebs@ebshome.net>
*
* Based on original work by
* Matt Porter <mporter@kernel.crashing.org>
* Copyright 2004 MontaVista Software, Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
*/
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/ethtool.h>
#include <asm/io.h>
#include "emac.h"
#include "debug.h"
// XXX FIXME: Axon seems to support a subset of the RGMII, we
// thus need to take that into account and possibly change some
// of the bit settings below that don't seem to quite match the
// AXON spec
/* RGMIIx_FER */
#define RGMII_FER_MASK(idx) (0x7 << ((idx) * 4))
#define RGMII_FER_RTBI(idx) (0x4 << ((idx) * 4))
#define RGMII_FER_RGMII(idx) (0x5 << ((idx) * 4))
#define RGMII_FER_TBI(idx) (0x6 << ((idx) * 4))
#define RGMII_FER_GMII(idx) (0x7 << ((idx) * 4))
#define RGMII_FER_MII(idx) RGMII_FER_GMII(idx)
/* RGMIIx_SSR */
#define RGMII_SSR_MASK(idx) (0x7 << ((idx) * 8))
#define RGMII_SSR_100(idx) (0x2 << ((idx) * 8))
#define RGMII_SSR_1000(idx) (0x4 << ((idx) * 8))
/* RGMII bridge supports only GMII/TBI and RGMII/RTBI PHYs */
static inline int rgmii_valid_mode(int phy_mode)
{
return phy_mode == PHY_MODE_GMII ||
phy_mode == PHY_MODE_MII ||
phy_mode == PHY_MODE_RGMII ||
phy_mode == PHY_MODE_TBI ||
phy_mode == PHY_MODE_RTBI;
}
static inline const char *rgmii_mode_name(int mode)
{
switch (mode) {
case PHY_MODE_RGMII:
return "RGMII";
case PHY_MODE_TBI:
return "TBI";
case PHY_MODE_GMII:
return "GMII";
case PHY_MODE_MII:
return "MII";
case PHY_MODE_RTBI:
return "RTBI";
default:
BUG();
}
}
static inline u32 rgmii_mode_mask(int mode, int input)
{
switch (mode) {
case PHY_MODE_RGMII:
return RGMII_FER_RGMII(input);
case PHY_MODE_TBI:
return RGMII_FER_TBI(input);
case PHY_MODE_GMII:
return RGMII_FER_GMII(input);
case PHY_MODE_MII:
return RGMII_FER_MII(input);
case PHY_MODE_RTBI:
return RGMII_FER_RTBI(input);
default:
BUG();
}
}
int __devinit rgmii_attach(struct platform_device *ofdev, int input, int mode)
{
struct rgmii_instance *dev = dev_get_drvdata(&ofdev->dev);
struct rgmii_regs __iomem *p = dev->base;
RGMII_DBG(dev, "attach(%d)" NL, input);
/* Check if we need to attach to a RGMII */
if (input < 0 || !rgmii_valid_mode(mode)) {
printk(KERN_ERR "%s: unsupported settings !\n",
ofdev->dev.of_node->full_name);
return -ENODEV;
}
mutex_lock(&dev->lock);
/* Enable this input */
out_be32(&p->fer, in_be32(&p->fer) | rgmii_mode_mask(mode, input));
printk(KERN_NOTICE "%s: input %d in %s mode\n",
ofdev->dev.of_node->full_name, input, rgmii_mode_name(mode));
++dev->users;
mutex_unlock(&dev->lock);
return 0;
}
void rgmii_set_speed(struct platform_device *ofdev, int input, int speed)
{
struct rgmii_instance *dev = dev_get_drvdata(&ofdev->dev);
struct rgmii_regs __iomem *p = dev->base;
u32 ssr;
mutex_lock(&dev->lock);
ssr = in_be32(&p->ssr) & ~RGMII_SSR_MASK(input);
RGMII_DBG(dev, "speed(%d, %d)" NL, input, speed);
if (speed == SPEED_1000)
ssr |= RGMII_SSR_1000(input);
else if (speed == SPEED_100)
ssr |= RGMII_SSR_100(input);
out_be32(&p->ssr, ssr);
mutex_unlock(&dev->lock);
}
void rgmii_get_mdio(struct platform_device *ofdev, int input)
{
struct rgmii_instance *dev = dev_get_drvdata(&ofdev->dev);
struct rgmii_regs __iomem *p = dev->base;
u32 fer;
RGMII_DBG2(dev, "get_mdio(%d)" NL, input);
if (!(dev->flags & EMAC_RGMII_FLAG_HAS_MDIO))
return;
mutex_lock(&dev->lock);
fer = in_be32(&p->fer);
fer |= 0x00080000u >> input;
out_be32(&p->fer, fer);
(void)in_be32(&p->fer);
DBG2(dev, " fer = 0x%08x\n", fer);
}
void rgmii_put_mdio(struct platform_device *ofdev, int input)
{
struct rgmii_instance *dev = dev_get_drvdata(&ofdev->dev);
struct rgmii_regs __iomem *p = dev->base;
u32 fer;
RGMII_DBG2(dev, "put_mdio(%d)" NL, input);
if (!(dev->flags & EMAC_RGMII_FLAG_HAS_MDIO))
return;
fer = in_be32(&p->fer);
fer &= ~(0x00080000u >> input);
out_be32(&p->fer, fer);
(void)in_be32(&p->fer);
DBG2(dev, " fer = 0x%08x\n", fer);
mutex_unlock(&dev->lock);
}
void rgmii_detach(struct platform_device *ofdev, int input)
{
struct rgmii_instance *dev = dev_get_drvdata(&ofdev->dev);
struct rgmii_regs __iomem *p;
BUG_ON(!dev || dev->users == 0);
p = dev->base;
mutex_lock(&dev->lock);
RGMII_DBG(dev, "detach(%d)" NL, input);
/* Disable this input */
out_be32(&p->fer, in_be32(&p->fer) & ~RGMII_FER_MASK(input));
--dev->users;
mutex_unlock(&dev->lock);
}
int rgmii_get_regs_len(struct platform_device *ofdev)
{
return sizeof(struct emac_ethtool_regs_subhdr) +
sizeof(struct rgmii_regs);
}
void *rgmii_dump_regs(struct platform_device *ofdev, void *buf)
{
struct rgmii_instance *dev = dev_get_drvdata(&ofdev->dev);
struct emac_ethtool_regs_subhdr *hdr = buf;
struct rgmii_regs *regs = (struct rgmii_regs *)(hdr + 1);
hdr->version = 0;
hdr->index = 0; /* for now, are there chips with more than one
* rgmii ? if yes, then we'll add a cell_index
* like we do for emac
*/
memcpy_fromio(regs, dev->base, sizeof(struct rgmii_regs));
return regs + 1;
}
static int __devinit rgmii_probe(struct platform_device *ofdev)
{
struct device_node *np = ofdev->dev.of_node;
struct rgmii_instance *dev;
struct resource regs;
int rc;
rc = -ENOMEM;
dev = kzalloc(sizeof(struct rgmii_instance), GFP_KERNEL);
if (dev == NULL) {
printk(KERN_ERR "%s: could not allocate RGMII device!\n",
np->full_name);
goto err_gone;
}
mutex_init(&dev->lock);
dev->ofdev = ofdev;
rc = -ENXIO;
if (of_address_to_resource(np, 0, ®s)) {
printk(KERN_ERR "%s: Can't get registers address\n",
np->full_name);
goto err_free;
}
rc = -ENOMEM;
dev->base = (struct rgmii_regs __iomem *)ioremap(regs.start,
sizeof(struct rgmii_regs));
if (dev->base == NULL) {
printk(KERN_ERR "%s: Can't map device registers!\n",
np->full_name);
goto err_free;
}
/* Check for RGMII flags */
if (of_get_property(ofdev->dev.of_node, "has-mdio", NULL))
dev->flags |= EMAC_RGMII_FLAG_HAS_MDIO;
/* CAB lacks the right properties, fix this up */
if (of_device_is_compatible(ofdev->dev.of_node, "ibm,rgmii-axon"))
dev->flags |= EMAC_RGMII_FLAG_HAS_MDIO;
DBG2(dev, " Boot FER = 0x%08x, SSR = 0x%08x\n",
in_be32(&dev->base->fer), in_be32(&dev->base->ssr));
/* Disable all inputs by default */
out_be32(&dev->base->fer, 0);
printk(KERN_INFO
"RGMII %s initialized with%s MDIO support\n",
ofdev->dev.of_node->full_name,
(dev->flags & EMAC_RGMII_FLAG_HAS_MDIO) ? "" : "out");
wmb();
dev_set_drvdata(&ofdev->dev, dev);
return 0;
err_free:
kfree(dev);
err_gone:
return rc;
}
static int __devexit rgmii_remove(struct platform_device *ofdev)
{
struct rgmii_instance *dev = dev_get_drvdata(&ofdev->dev);
dev_set_drvdata(&ofdev->dev, NULL);
WARN_ON(dev->users != 0);
iounmap(dev->base);
kfree(dev);
return 0;
}
static struct of_device_id rgmii_match[] =
{
{
.compatible = "ibm,rgmii",
},
{
.type = "emac-rgmii",
},
{},
};
static struct platform_driver rgmii_driver = {
.driver = {
.name = "emac-rgmii",
.owner = THIS_MODULE,
.of_match_table = rgmii_match,
},
.probe = rgmii_probe,
.remove = rgmii_remove,
};
int __init rgmii_init(void)
{
return platform_driver_register(&rgmii_driver);
}
void rgmii_exit(void)
{
platform_driver_unregister(&rgmii_driver);
}
| gpl-2.0 |
playfulgod/kernel_lge_zee | drivers/mtd/tests/mtd_erasepart.c | 3442 | 4017 | /*
* Copyright (c) 2010, The Linux Foundation. All rights reserved.
* Copyright (C) 2006-2008 Nokia Corporation
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; see the file COPYING. If not, write to the Free Software
* Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Erase the given MTD partition.
*
*/
#include <asm/div64.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/err.h>
#include <linux/mtd/mtd.h>
#include <linux/sched.h>
#include <linux/slab.h>
#define PRINT_PREF KERN_INFO "mtd_erasepart: "
static int dev;
module_param(dev, int, S_IRUGO);
MODULE_PARM_DESC(dev, "MTD device number to use");
static struct mtd_info *mtd;
static unsigned char *bbt;
static int ebcnt;
static int erase_eraseblock(int ebnum)
{
int err;
struct erase_info ei;
loff_t addr = ebnum * mtd->erasesize;
memset(&ei, 0, sizeof(struct erase_info));
ei.mtd = mtd;
ei.addr = addr;
ei.len = mtd->erasesize;
err = mtd_erase(mtd, &ei);
if (err) {
printk(PRINT_PREF "error %d while erasing EB %d\n", err, ebnum);
return err;
}
if (ei.state == MTD_ERASE_FAILED) {
printk(PRINT_PREF "some erase error occurred at EB %d\n",
ebnum);
return -EIO;
}
return 0;
}
static int erase_whole_device(void)
{
int err;
unsigned int i;
printk(PRINT_PREF "erasing whole device\n");
for (i = 0; i < ebcnt; ++i) {
if (bbt[i])
continue;
err = erase_eraseblock(i);
if (err)
return err;
cond_resched();
}
printk(PRINT_PREF "erased %u eraseblocks\n", i);
return 0;
}
static int is_block_bad(int ebnum)
{
int ret;
loff_t addr = ebnum * mtd->erasesize;
ret = mtd_block_isbad(mtd, addr);
if (ret)
printk(PRINT_PREF "block %d is bad\n", ebnum);
return ret;
}
static int scan_for_bad_eraseblocks(void)
{
int i, bad = 0;
bbt = kmalloc(ebcnt, GFP_KERNEL);
if (!bbt) {
printk(PRINT_PREF "error: cannot allocate memory\n");
return -ENOMEM;
}
memset(bbt, 0 , ebcnt);
printk(PRINT_PREF "scanning for bad eraseblocks\n");
for (i = 0; i < ebcnt; ++i) {
bbt[i] = is_block_bad(i) ? 1 : 0;
if (bbt[i])
bad += 1;
cond_resched();
}
printk(PRINT_PREF "scanned %d eraseblocks, %d are bad\n", i, bad);
return 0;
}
static int __init mtd_erasepart_init(void)
{
int err = 0;
uint64_t tmp;
printk(KERN_INFO "\n");
printk(KERN_INFO "=================================================\n");
printk(PRINT_PREF "MTD device: %d\n", dev);
mtd = get_mtd_device(NULL, dev);
if (IS_ERR(mtd)) {
err = PTR_ERR(mtd);
printk(PRINT_PREF "error: cannot get MTD device\n");
return err;
}
if (mtd->type != MTD_NANDFLASH) {
printk(PRINT_PREF "this test requires NAND flash\n");
err = -ENODEV;
goto out2;
}
tmp = mtd->size;
do_div(tmp, mtd->erasesize);
ebcnt = tmp;
printk(PRINT_PREF "MTD device size %llu, eraseblock size %u, "
"page size %u, count of eraseblocks %u",
(unsigned long long)mtd->size, mtd->erasesize,
mtd->writesize, ebcnt);
err = scan_for_bad_eraseblocks();
if (err)
goto out1;
printk(PRINT_PREF "Erasing the whole mtd partition\n");
err = erase_whole_device();
out1:
kfree(bbt);
out2:
put_mtd_device(mtd);
if (err)
printk(PRINT_PREF "error %d occurred\n", err);
printk(KERN_INFO "=================================================\n");
return err;
}
module_init(mtd_erasepart_init);
static void __exit mtd_erasepart_exit(void)
{
return;
}
module_exit(mtd_erasepart_exit);
MODULE_DESCRIPTION("Erase a given MTD partition");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
schlund/2.6.35-photonic-kernel | arch/arm/mach-orion5x/pci.c | 3442 | 15022 | /*
* arch/arm/mach-orion5x/pci.c
*
* PCI and PCIe functions for Marvell Orion System On Chip
*
* Maintainer: Tzachi Perelstein <tzachi@marvell.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/kernel.h>
#include <linux/pci.h>
#include <linux/slab.h>
#include <linux/mbus.h>
#include <asm/irq.h>
#include <asm/mach/pci.h>
#include <plat/pcie.h>
#include "common.h"
/*****************************************************************************
* Orion has one PCIe controller and one PCI controller.
*
* Note1: The local PCIe bus number is '0'. The local PCI bus number
* follows the scanned PCIe bridged busses, if any.
*
* Note2: It is possible for PCI/PCIe agents to access many subsystem's
* space, by configuring BARs and Address Decode Windows, e.g. flashes on
* device bus, Orion registers, etc. However this code only enable the
* access to DDR banks.
****************************************************************************/
/*****************************************************************************
* PCIe controller
****************************************************************************/
#define PCIE_BASE ((void __iomem *)ORION5X_PCIE_VIRT_BASE)
void __init orion5x_pcie_id(u32 *dev, u32 *rev)
{
*dev = orion_pcie_dev_id(PCIE_BASE);
*rev = orion_pcie_rev(PCIE_BASE);
}
static int pcie_valid_config(int bus, int dev)
{
/*
* Don't go out when trying to access --
* 1. nonexisting device on local bus
* 2. where there's no device connected (no link)
*/
if (bus == 0 && dev == 0)
return 1;
if (!orion_pcie_link_up(PCIE_BASE))
return 0;
if (bus == 0 && dev != 1)
return 0;
return 1;
}
/*
* PCIe config cycles are done by programming the PCIE_CONF_ADDR register
* and then reading the PCIE_CONF_DATA register. Need to make sure these
* transactions are atomic.
*/
static DEFINE_SPINLOCK(orion5x_pcie_lock);
static int pcie_rd_conf(struct pci_bus *bus, u32 devfn, int where,
int size, u32 *val)
{
unsigned long flags;
int ret;
if (pcie_valid_config(bus->number, PCI_SLOT(devfn)) == 0) {
*val = 0xffffffff;
return PCIBIOS_DEVICE_NOT_FOUND;
}
spin_lock_irqsave(&orion5x_pcie_lock, flags);
ret = orion_pcie_rd_conf(PCIE_BASE, bus, devfn, where, size, val);
spin_unlock_irqrestore(&orion5x_pcie_lock, flags);
return ret;
}
static int pcie_rd_conf_wa(struct pci_bus *bus, u32 devfn,
int where, int size, u32 *val)
{
int ret;
if (pcie_valid_config(bus->number, PCI_SLOT(devfn)) == 0) {
*val = 0xffffffff;
return PCIBIOS_DEVICE_NOT_FOUND;
}
/*
* We only support access to the non-extended configuration
* space when using the WA access method (or we would have to
* sacrifice 256M of CPU virtual address space.)
*/
if (where >= 0x100) {
*val = 0xffffffff;
return PCIBIOS_DEVICE_NOT_FOUND;
}
ret = orion_pcie_rd_conf_wa((void __iomem *)ORION5X_PCIE_WA_VIRT_BASE,
bus, devfn, where, size, val);
return ret;
}
static int pcie_wr_conf(struct pci_bus *bus, u32 devfn,
int where, int size, u32 val)
{
unsigned long flags;
int ret;
if (pcie_valid_config(bus->number, PCI_SLOT(devfn)) == 0)
return PCIBIOS_DEVICE_NOT_FOUND;
spin_lock_irqsave(&orion5x_pcie_lock, flags);
ret = orion_pcie_wr_conf(PCIE_BASE, bus, devfn, where, size, val);
spin_unlock_irqrestore(&orion5x_pcie_lock, flags);
return ret;
}
static struct pci_ops pcie_ops = {
.read = pcie_rd_conf,
.write = pcie_wr_conf,
};
static int __init pcie_setup(struct pci_sys_data *sys)
{
struct resource *res;
int dev;
/*
* Generic PCIe unit setup.
*/
orion_pcie_setup(PCIE_BASE, &orion5x_mbus_dram_info);
/*
* Check whether to apply Orion-1/Orion-NAS PCIe config
* read transaction workaround.
*/
dev = orion_pcie_dev_id(PCIE_BASE);
if (dev == MV88F5181_DEV_ID || dev == MV88F5182_DEV_ID) {
printk(KERN_NOTICE "Applying Orion-1/Orion-NAS PCIe config "
"read transaction workaround\n");
orion5x_setup_pcie_wa_win(ORION5X_PCIE_WA_PHYS_BASE,
ORION5X_PCIE_WA_SIZE);
pcie_ops.read = pcie_rd_conf_wa;
}
/*
* Request resources.
*/
res = kzalloc(sizeof(struct resource) * 2, GFP_KERNEL);
if (!res)
panic("pcie_setup unable to alloc resources");
/*
* IORESOURCE_IO
*/
res[0].name = "PCIe I/O Space";
res[0].flags = IORESOURCE_IO;
res[0].start = ORION5X_PCIE_IO_BUS_BASE;
res[0].end = res[0].start + ORION5X_PCIE_IO_SIZE - 1;
if (request_resource(&ioport_resource, &res[0]))
panic("Request PCIe IO resource failed\n");
sys->resource[0] = &res[0];
/*
* IORESOURCE_MEM
*/
res[1].name = "PCIe Memory Space";
res[1].flags = IORESOURCE_MEM;
res[1].start = ORION5X_PCIE_MEM_PHYS_BASE;
res[1].end = res[1].start + ORION5X_PCIE_MEM_SIZE - 1;
if (request_resource(&iomem_resource, &res[1]))
panic("Request PCIe Memory resource failed\n");
sys->resource[1] = &res[1];
sys->resource[2] = NULL;
sys->io_offset = 0;
return 1;
}
/*****************************************************************************
* PCI controller
****************************************************************************/
#define ORION5X_PCI_REG(x) (ORION5X_PCI_VIRT_BASE | (x))
#define PCI_MODE ORION5X_PCI_REG(0xd00)
#define PCI_CMD ORION5X_PCI_REG(0xc00)
#define PCI_P2P_CONF ORION5X_PCI_REG(0x1d14)
#define PCI_CONF_ADDR ORION5X_PCI_REG(0xc78)
#define PCI_CONF_DATA ORION5X_PCI_REG(0xc7c)
/*
* PCI_MODE bits
*/
#define PCI_MODE_64BIT (1 << 2)
#define PCI_MODE_PCIX ((1 << 4) | (1 << 5))
/*
* PCI_CMD bits
*/
#define PCI_CMD_HOST_REORDER (1 << 29)
/*
* PCI_P2P_CONF bits
*/
#define PCI_P2P_BUS_OFFS 16
#define PCI_P2P_BUS_MASK (0xff << PCI_P2P_BUS_OFFS)
#define PCI_P2P_DEV_OFFS 24
#define PCI_P2P_DEV_MASK (0x1f << PCI_P2P_DEV_OFFS)
/*
* PCI_CONF_ADDR bits
*/
#define PCI_CONF_REG(reg) ((reg) & 0xfc)
#define PCI_CONF_FUNC(func) (((func) & 0x3) << 8)
#define PCI_CONF_DEV(dev) (((dev) & 0x1f) << 11)
#define PCI_CONF_BUS(bus) (((bus) & 0xff) << 16)
#define PCI_CONF_ADDR_EN (1 << 31)
/*
* Internal configuration space
*/
#define PCI_CONF_FUNC_STAT_CMD 0
#define PCI_CONF_REG_STAT_CMD 4
#define PCIX_STAT 0x64
#define PCIX_STAT_BUS_OFFS 8
#define PCIX_STAT_BUS_MASK (0xff << PCIX_STAT_BUS_OFFS)
/*
* PCI Address Decode Windows registers
*/
#define PCI_BAR_SIZE_DDR_CS(n) (((n) == 0) ? ORION5X_PCI_REG(0xc08) : \
((n) == 1) ? ORION5X_PCI_REG(0xd08) : \
((n) == 2) ? ORION5X_PCI_REG(0xc0c) : \
((n) == 3) ? ORION5X_PCI_REG(0xd0c) : 0)
#define PCI_BAR_REMAP_DDR_CS(n) (((n) == 0) ? ORION5X_PCI_REG(0xc48) : \
((n) == 1) ? ORION5X_PCI_REG(0xd48) : \
((n) == 2) ? ORION5X_PCI_REG(0xc4c) : \
((n) == 3) ? ORION5X_PCI_REG(0xd4c) : 0)
#define PCI_BAR_ENABLE ORION5X_PCI_REG(0xc3c)
#define PCI_ADDR_DECODE_CTRL ORION5X_PCI_REG(0xd3c)
/*
* PCI configuration helpers for BAR settings
*/
#define PCI_CONF_FUNC_BAR_CS(n) ((n) >> 1)
#define PCI_CONF_REG_BAR_LO_CS(n) (((n) & 1) ? 0x18 : 0x10)
#define PCI_CONF_REG_BAR_HI_CS(n) (((n) & 1) ? 0x1c : 0x14)
/*
* PCI config cycles are done by programming the PCI_CONF_ADDR register
* and then reading the PCI_CONF_DATA register. Need to make sure these
* transactions are atomic.
*/
static DEFINE_SPINLOCK(orion5x_pci_lock);
static int orion5x_pci_cardbus_mode;
static int orion5x_pci_local_bus_nr(void)
{
u32 conf = readl(PCI_P2P_CONF);
return((conf & PCI_P2P_BUS_MASK) >> PCI_P2P_BUS_OFFS);
}
static int orion5x_pci_hw_rd_conf(int bus, int dev, u32 func,
u32 where, u32 size, u32 *val)
{
unsigned long flags;
spin_lock_irqsave(&orion5x_pci_lock, flags);
writel(PCI_CONF_BUS(bus) |
PCI_CONF_DEV(dev) | PCI_CONF_REG(where) |
PCI_CONF_FUNC(func) | PCI_CONF_ADDR_EN, PCI_CONF_ADDR);
*val = readl(PCI_CONF_DATA);
if (size == 1)
*val = (*val >> (8*(where & 0x3))) & 0xff;
else if (size == 2)
*val = (*val >> (8*(where & 0x3))) & 0xffff;
spin_unlock_irqrestore(&orion5x_pci_lock, flags);
return PCIBIOS_SUCCESSFUL;
}
static int orion5x_pci_hw_wr_conf(int bus, int dev, u32 func,
u32 where, u32 size, u32 val)
{
unsigned long flags;
int ret = PCIBIOS_SUCCESSFUL;
spin_lock_irqsave(&orion5x_pci_lock, flags);
writel(PCI_CONF_BUS(bus) |
PCI_CONF_DEV(dev) | PCI_CONF_REG(where) |
PCI_CONF_FUNC(func) | PCI_CONF_ADDR_EN, PCI_CONF_ADDR);
if (size == 4) {
__raw_writel(val, PCI_CONF_DATA);
} else if (size == 2) {
__raw_writew(val, PCI_CONF_DATA + (where & 0x3));
} else if (size == 1) {
__raw_writeb(val, PCI_CONF_DATA + (where & 0x3));
} else {
ret = PCIBIOS_BAD_REGISTER_NUMBER;
}
spin_unlock_irqrestore(&orion5x_pci_lock, flags);
return ret;
}
static int orion5x_pci_valid_config(int bus, u32 devfn)
{
if (bus == orion5x_pci_local_bus_nr()) {
/*
* Don't go out for local device
*/
if (PCI_SLOT(devfn) == 0 && PCI_FUNC(devfn) != 0)
return 0;
/*
* When the PCI signals are directly connected to a
* Cardbus slot, ignore all but device IDs 0 and 1.
*/
if (orion5x_pci_cardbus_mode && PCI_SLOT(devfn) > 1)
return 0;
}
return 1;
}
static int orion5x_pci_rd_conf(struct pci_bus *bus, u32 devfn,
int where, int size, u32 *val)
{
if (!orion5x_pci_valid_config(bus->number, devfn)) {
*val = 0xffffffff;
return PCIBIOS_DEVICE_NOT_FOUND;
}
return orion5x_pci_hw_rd_conf(bus->number, PCI_SLOT(devfn),
PCI_FUNC(devfn), where, size, val);
}
static int orion5x_pci_wr_conf(struct pci_bus *bus, u32 devfn,
int where, int size, u32 val)
{
if (!orion5x_pci_valid_config(bus->number, devfn))
return PCIBIOS_DEVICE_NOT_FOUND;
return orion5x_pci_hw_wr_conf(bus->number, PCI_SLOT(devfn),
PCI_FUNC(devfn), where, size, val);
}
static struct pci_ops pci_ops = {
.read = orion5x_pci_rd_conf,
.write = orion5x_pci_wr_conf,
};
static void __init orion5x_pci_set_bus_nr(int nr)
{
u32 p2p = readl(PCI_P2P_CONF);
if (readl(PCI_MODE) & PCI_MODE_PCIX) {
/*
* PCI-X mode
*/
u32 pcix_status, bus, dev;
bus = (p2p & PCI_P2P_BUS_MASK) >> PCI_P2P_BUS_OFFS;
dev = (p2p & PCI_P2P_DEV_MASK) >> PCI_P2P_DEV_OFFS;
orion5x_pci_hw_rd_conf(bus, dev, 0, PCIX_STAT, 4, &pcix_status);
pcix_status &= ~PCIX_STAT_BUS_MASK;
pcix_status |= (nr << PCIX_STAT_BUS_OFFS);
orion5x_pci_hw_wr_conf(bus, dev, 0, PCIX_STAT, 4, pcix_status);
} else {
/*
* PCI Conventional mode
*/
p2p &= ~PCI_P2P_BUS_MASK;
p2p |= (nr << PCI_P2P_BUS_OFFS);
writel(p2p, PCI_P2P_CONF);
}
}
static void __init orion5x_pci_master_slave_enable(void)
{
int bus_nr, func, reg;
u32 val;
bus_nr = orion5x_pci_local_bus_nr();
func = PCI_CONF_FUNC_STAT_CMD;
reg = PCI_CONF_REG_STAT_CMD;
orion5x_pci_hw_rd_conf(bus_nr, 0, func, reg, 4, &val);
val |= (PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER);
orion5x_pci_hw_wr_conf(bus_nr, 0, func, reg, 4, val | 0x7);
}
static void __init orion5x_setup_pci_wins(struct mbus_dram_target_info *dram)
{
u32 win_enable;
int bus;
int i;
/*
* First, disable windows.
*/
win_enable = 0xffffffff;
writel(win_enable, PCI_BAR_ENABLE);
/*
* Setup windows for DDR banks.
*/
bus = orion5x_pci_local_bus_nr();
for (i = 0; i < dram->num_cs; i++) {
struct mbus_dram_window *cs = dram->cs + i;
u32 func = PCI_CONF_FUNC_BAR_CS(cs->cs_index);
u32 reg;
u32 val;
/*
* Write DRAM bank base address register.
*/
reg = PCI_CONF_REG_BAR_LO_CS(cs->cs_index);
orion5x_pci_hw_rd_conf(bus, 0, func, reg, 4, &val);
val = (cs->base & 0xfffff000) | (val & 0xfff);
orion5x_pci_hw_wr_conf(bus, 0, func, reg, 4, val);
/*
* Write DRAM bank size register.
*/
reg = PCI_CONF_REG_BAR_HI_CS(cs->cs_index);
orion5x_pci_hw_wr_conf(bus, 0, func, reg, 4, 0);
writel((cs->size - 1) & 0xfffff000,
PCI_BAR_SIZE_DDR_CS(cs->cs_index));
writel(cs->base & 0xfffff000,
PCI_BAR_REMAP_DDR_CS(cs->cs_index));
/*
* Enable decode window for this chip select.
*/
win_enable &= ~(1 << cs->cs_index);
}
/*
* Re-enable decode windows.
*/
writel(win_enable, PCI_BAR_ENABLE);
/*
* Disable automatic update of address remapping when writing to BARs.
*/
orion5x_setbits(PCI_ADDR_DECODE_CTRL, 1);
}
static int __init pci_setup(struct pci_sys_data *sys)
{
struct resource *res;
/*
* Point PCI unit MBUS decode windows to DRAM space.
*/
orion5x_setup_pci_wins(&orion5x_mbus_dram_info);
/*
* Master + Slave enable
*/
orion5x_pci_master_slave_enable();
/*
* Force ordering
*/
orion5x_setbits(PCI_CMD, PCI_CMD_HOST_REORDER);
/*
* Request resources
*/
res = kzalloc(sizeof(struct resource) * 2, GFP_KERNEL);
if (!res)
panic("pci_setup unable to alloc resources");
/*
* IORESOURCE_IO
*/
res[0].name = "PCI I/O Space";
res[0].flags = IORESOURCE_IO;
res[0].start = ORION5X_PCI_IO_BUS_BASE;
res[0].end = res[0].start + ORION5X_PCI_IO_SIZE - 1;
if (request_resource(&ioport_resource, &res[0]))
panic("Request PCI IO resource failed\n");
sys->resource[0] = &res[0];
/*
* IORESOURCE_MEM
*/
res[1].name = "PCI Memory Space";
res[1].flags = IORESOURCE_MEM;
res[1].start = ORION5X_PCI_MEM_PHYS_BASE;
res[1].end = res[1].start + ORION5X_PCI_MEM_SIZE - 1;
if (request_resource(&iomem_resource, &res[1]))
panic("Request PCI Memory resource failed\n");
sys->resource[1] = &res[1];
sys->resource[2] = NULL;
sys->io_offset = 0;
return 1;
}
/*****************************************************************************
* General PCIe + PCI
****************************************************************************/
static void __devinit rc_pci_fixup(struct pci_dev *dev)
{
/*
* Prevent enumeration of root complex.
*/
if (dev->bus->parent == NULL && dev->devfn == 0) {
int i;
for (i = 0; i < DEVICE_COUNT_RESOURCE; i++) {
dev->resource[i].start = 0;
dev->resource[i].end = 0;
dev->resource[i].flags = 0;
}
}
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_MARVELL, PCI_ANY_ID, rc_pci_fixup);
static int orion5x_pci_disabled __initdata;
void __init orion5x_pci_disable(void)
{
orion5x_pci_disabled = 1;
}
void __init orion5x_pci_set_cardbus_mode(void)
{
orion5x_pci_cardbus_mode = 1;
}
int __init orion5x_pci_sys_setup(int nr, struct pci_sys_data *sys)
{
int ret = 0;
if (nr == 0) {
orion_pcie_set_local_bus_nr(PCIE_BASE, sys->busnr);
ret = pcie_setup(sys);
} else if (nr == 1 && !orion5x_pci_disabled) {
orion5x_pci_set_bus_nr(sys->busnr);
ret = pci_setup(sys);
}
return ret;
}
struct pci_bus __init *orion5x_pci_sys_scan_bus(int nr, struct pci_sys_data *sys)
{
struct pci_bus *bus;
if (nr == 0) {
bus = pci_scan_bus(sys->busnr, &pcie_ops, sys);
} else if (nr == 1 && !orion5x_pci_disabled) {
bus = pci_scan_bus(sys->busnr, &pci_ops, sys);
} else {
bus = NULL;
BUG();
}
return bus;
}
int __init orion5x_pci_map_irq(struct pci_dev *dev, u8 slot, u8 pin)
{
int bus = dev->bus->number;
/*
* PCIe endpoint?
*/
if (orion5x_pci_disabled || bus < orion5x_pci_local_bus_nr())
return IRQ_ORION5X_PCIE0_INT;
return -1;
}
| gpl-2.0 |
j4y4r/SebastianFM-kernel | arch/s390/kvm/sigp.c | 4466 | 10740 | /*
* sigp.c - handlinge interprocessor communication
*
* Copyright IBM Corp. 2008,2009
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License (version 2 only)
* as published by the Free Software Foundation.
*
* Author(s): Carsten Otte <cotte@de.ibm.com>
* Christian Borntraeger <borntraeger@de.ibm.com>
* Christian Ehrhardt <ehrhardt@de.ibm.com>
*/
#include <linux/kvm.h>
#include <linux/kvm_host.h>
#include <linux/slab.h>
#include "gaccess.h"
#include "kvm-s390.h"
/* sigp order codes */
#define SIGP_SENSE 0x01
#define SIGP_EXTERNAL_CALL 0x02
#define SIGP_EMERGENCY 0x03
#define SIGP_START 0x04
#define SIGP_STOP 0x05
#define SIGP_RESTART 0x06
#define SIGP_STOP_STORE_STATUS 0x09
#define SIGP_INITIAL_CPU_RESET 0x0b
#define SIGP_CPU_RESET 0x0c
#define SIGP_SET_PREFIX 0x0d
#define SIGP_STORE_STATUS_ADDR 0x0e
#define SIGP_SET_ARCH 0x12
#define SIGP_SENSE_RUNNING 0x15
/* cpu status bits */
#define SIGP_STAT_EQUIPMENT_CHECK 0x80000000UL
#define SIGP_STAT_NOT_RUNNING 0x00000400UL
#define SIGP_STAT_INCORRECT_STATE 0x00000200UL
#define SIGP_STAT_INVALID_PARAMETER 0x00000100UL
#define SIGP_STAT_EXT_CALL_PENDING 0x00000080UL
#define SIGP_STAT_STOPPED 0x00000040UL
#define SIGP_STAT_OPERATOR_INTERV 0x00000020UL
#define SIGP_STAT_CHECK_STOP 0x00000010UL
#define SIGP_STAT_INOPERATIVE 0x00000004UL
#define SIGP_STAT_INVALID_ORDER 0x00000002UL
#define SIGP_STAT_RECEIVER_CHECK 0x00000001UL
static int __sigp_sense(struct kvm_vcpu *vcpu, u16 cpu_addr,
u64 *reg)
{
struct kvm_s390_float_interrupt *fi = &vcpu->kvm->arch.float_int;
int rc;
if (cpu_addr >= KVM_MAX_VCPUS)
return 3; /* not operational */
spin_lock(&fi->lock);
if (fi->local_int[cpu_addr] == NULL)
rc = 3; /* not operational */
else if (!(atomic_read(fi->local_int[cpu_addr]->cpuflags)
& CPUSTAT_STOPPED)) {
*reg &= 0xffffffff00000000UL;
rc = 1; /* status stored */
} else {
*reg &= 0xffffffff00000000UL;
*reg |= SIGP_STAT_STOPPED;
rc = 1; /* status stored */
}
spin_unlock(&fi->lock);
VCPU_EVENT(vcpu, 4, "sensed status of cpu %x rc %x", cpu_addr, rc);
return rc;
}
static int __sigp_emergency(struct kvm_vcpu *vcpu, u16 cpu_addr)
{
struct kvm_s390_float_interrupt *fi = &vcpu->kvm->arch.float_int;
struct kvm_s390_local_interrupt *li;
struct kvm_s390_interrupt_info *inti;
int rc;
if (cpu_addr >= KVM_MAX_VCPUS)
return 3; /* not operational */
inti = kzalloc(sizeof(*inti), GFP_KERNEL);
if (!inti)
return -ENOMEM;
inti->type = KVM_S390_INT_EMERGENCY;
inti->emerg.code = vcpu->vcpu_id;
spin_lock(&fi->lock);
li = fi->local_int[cpu_addr];
if (li == NULL) {
rc = 3; /* not operational */
kfree(inti);
goto unlock;
}
spin_lock_bh(&li->lock);
list_add_tail(&inti->list, &li->list);
atomic_set(&li->active, 1);
atomic_set_mask(CPUSTAT_EXT_INT, li->cpuflags);
if (waitqueue_active(&li->wq))
wake_up_interruptible(&li->wq);
spin_unlock_bh(&li->lock);
rc = 0; /* order accepted */
VCPU_EVENT(vcpu, 4, "sent sigp emerg to cpu %x", cpu_addr);
unlock:
spin_unlock(&fi->lock);
return rc;
}
static int __sigp_external_call(struct kvm_vcpu *vcpu, u16 cpu_addr)
{
struct kvm_s390_float_interrupt *fi = &vcpu->kvm->arch.float_int;
struct kvm_s390_local_interrupt *li;
struct kvm_s390_interrupt_info *inti;
int rc;
if (cpu_addr >= KVM_MAX_VCPUS)
return 3; /* not operational */
inti = kzalloc(sizeof(*inti), GFP_KERNEL);
if (!inti)
return -ENOMEM;
inti->type = KVM_S390_INT_EXTERNAL_CALL;
inti->extcall.code = vcpu->vcpu_id;
spin_lock(&fi->lock);
li = fi->local_int[cpu_addr];
if (li == NULL) {
rc = 3; /* not operational */
kfree(inti);
goto unlock;
}
spin_lock_bh(&li->lock);
list_add_tail(&inti->list, &li->list);
atomic_set(&li->active, 1);
atomic_set_mask(CPUSTAT_EXT_INT, li->cpuflags);
if (waitqueue_active(&li->wq))
wake_up_interruptible(&li->wq);
spin_unlock_bh(&li->lock);
rc = 0; /* order accepted */
VCPU_EVENT(vcpu, 4, "sent sigp ext call to cpu %x", cpu_addr);
unlock:
spin_unlock(&fi->lock);
return rc;
}
static int __inject_sigp_stop(struct kvm_s390_local_interrupt *li, int action)
{
struct kvm_s390_interrupt_info *inti;
inti = kzalloc(sizeof(*inti), GFP_ATOMIC);
if (!inti)
return -ENOMEM;
inti->type = KVM_S390_SIGP_STOP;
spin_lock_bh(&li->lock);
if ((atomic_read(li->cpuflags) & CPUSTAT_STOPPED))
goto out;
list_add_tail(&inti->list, &li->list);
atomic_set(&li->active, 1);
atomic_set_mask(CPUSTAT_STOP_INT, li->cpuflags);
li->action_bits |= action;
if (waitqueue_active(&li->wq))
wake_up_interruptible(&li->wq);
out:
spin_unlock_bh(&li->lock);
return 0; /* order accepted */
}
static int __sigp_stop(struct kvm_vcpu *vcpu, u16 cpu_addr, int action)
{
struct kvm_s390_float_interrupt *fi = &vcpu->kvm->arch.float_int;
struct kvm_s390_local_interrupt *li;
int rc;
if (cpu_addr >= KVM_MAX_VCPUS)
return 3; /* not operational */
spin_lock(&fi->lock);
li = fi->local_int[cpu_addr];
if (li == NULL) {
rc = 3; /* not operational */
goto unlock;
}
rc = __inject_sigp_stop(li, action);
unlock:
spin_unlock(&fi->lock);
VCPU_EVENT(vcpu, 4, "sent sigp stop to cpu %x", cpu_addr);
return rc;
}
int kvm_s390_inject_sigp_stop(struct kvm_vcpu *vcpu, int action)
{
struct kvm_s390_local_interrupt *li = &vcpu->arch.local_int;
return __inject_sigp_stop(li, action);
}
static int __sigp_set_arch(struct kvm_vcpu *vcpu, u32 parameter)
{
int rc;
switch (parameter & 0xff) {
case 0:
rc = 3; /* not operational */
break;
case 1:
case 2:
rc = 0; /* order accepted */
break;
default:
rc = -EOPNOTSUPP;
}
return rc;
}
static int __sigp_set_prefix(struct kvm_vcpu *vcpu, u16 cpu_addr, u32 address,
u64 *reg)
{
struct kvm_s390_float_interrupt *fi = &vcpu->kvm->arch.float_int;
struct kvm_s390_local_interrupt *li = NULL;
struct kvm_s390_interrupt_info *inti;
int rc;
u8 tmp;
/* make sure that the new value is valid memory */
address = address & 0x7fffe000u;
if (copy_from_guest_absolute(vcpu, &tmp, address, 1) ||
copy_from_guest_absolute(vcpu, &tmp, address + PAGE_SIZE, 1)) {
*reg |= SIGP_STAT_INVALID_PARAMETER;
return 1; /* invalid parameter */
}
inti = kzalloc(sizeof(*inti), GFP_KERNEL);
if (!inti)
return 2; /* busy */
spin_lock(&fi->lock);
if (cpu_addr < KVM_MAX_VCPUS)
li = fi->local_int[cpu_addr];
if (li == NULL) {
rc = 1; /* incorrect state */
*reg &= SIGP_STAT_INCORRECT_STATE;
kfree(inti);
goto out_fi;
}
spin_lock_bh(&li->lock);
/* cpu must be in stopped state */
if (!(atomic_read(li->cpuflags) & CPUSTAT_STOPPED)) {
rc = 1; /* incorrect state */
*reg &= SIGP_STAT_INCORRECT_STATE;
kfree(inti);
goto out_li;
}
inti->type = KVM_S390_SIGP_SET_PREFIX;
inti->prefix.address = address;
list_add_tail(&inti->list, &li->list);
atomic_set(&li->active, 1);
if (waitqueue_active(&li->wq))
wake_up_interruptible(&li->wq);
rc = 0; /* order accepted */
VCPU_EVENT(vcpu, 4, "set prefix of cpu %02x to %x", cpu_addr, address);
out_li:
spin_unlock_bh(&li->lock);
out_fi:
spin_unlock(&fi->lock);
return rc;
}
static int __sigp_sense_running(struct kvm_vcpu *vcpu, u16 cpu_addr,
u64 *reg)
{
int rc;
struct kvm_s390_float_interrupt *fi = &vcpu->kvm->arch.float_int;
if (cpu_addr >= KVM_MAX_VCPUS)
return 3; /* not operational */
spin_lock(&fi->lock);
if (fi->local_int[cpu_addr] == NULL)
rc = 3; /* not operational */
else {
if (atomic_read(fi->local_int[cpu_addr]->cpuflags)
& CPUSTAT_RUNNING) {
/* running */
rc = 1;
} else {
/* not running */
*reg &= 0xffffffff00000000UL;
*reg |= SIGP_STAT_NOT_RUNNING;
rc = 0;
}
}
spin_unlock(&fi->lock);
VCPU_EVENT(vcpu, 4, "sensed running status of cpu %x rc %x", cpu_addr,
rc);
return rc;
}
static int __sigp_restart(struct kvm_vcpu *vcpu, u16 cpu_addr)
{
int rc = 0;
struct kvm_s390_float_interrupt *fi = &vcpu->kvm->arch.float_int;
struct kvm_s390_local_interrupt *li;
if (cpu_addr >= KVM_MAX_VCPUS)
return 3; /* not operational */
spin_lock(&fi->lock);
li = fi->local_int[cpu_addr];
if (li == NULL) {
rc = 3; /* not operational */
goto out;
}
spin_lock_bh(&li->lock);
if (li->action_bits & ACTION_STOP_ON_STOP)
rc = 2; /* busy */
else
VCPU_EVENT(vcpu, 4, "sigp restart %x to handle userspace",
cpu_addr);
spin_unlock_bh(&li->lock);
out:
spin_unlock(&fi->lock);
return rc;
}
int kvm_s390_handle_sigp(struct kvm_vcpu *vcpu)
{
int r1 = (vcpu->arch.sie_block->ipa & 0x00f0) >> 4;
int r3 = vcpu->arch.sie_block->ipa & 0x000f;
int base2 = vcpu->arch.sie_block->ipb >> 28;
int disp2 = ((vcpu->arch.sie_block->ipb & 0x0fff0000) >> 16);
u32 parameter;
u16 cpu_addr = vcpu->run->s.regs.gprs[r3];
u8 order_code;
int rc;
/* sigp in userspace can exit */
if (vcpu->arch.sie_block->gpsw.mask & PSW_MASK_PSTATE)
return kvm_s390_inject_program_int(vcpu,
PGM_PRIVILEGED_OPERATION);
order_code = disp2;
if (base2)
order_code += vcpu->run->s.regs.gprs[base2];
if (r1 % 2)
parameter = vcpu->run->s.regs.gprs[r1];
else
parameter = vcpu->run->s.regs.gprs[r1 + 1];
switch (order_code) {
case SIGP_SENSE:
vcpu->stat.instruction_sigp_sense++;
rc = __sigp_sense(vcpu, cpu_addr,
&vcpu->run->s.regs.gprs[r1]);
break;
case SIGP_EXTERNAL_CALL:
vcpu->stat.instruction_sigp_external_call++;
rc = __sigp_external_call(vcpu, cpu_addr);
break;
case SIGP_EMERGENCY:
vcpu->stat.instruction_sigp_emergency++;
rc = __sigp_emergency(vcpu, cpu_addr);
break;
case SIGP_STOP:
vcpu->stat.instruction_sigp_stop++;
rc = __sigp_stop(vcpu, cpu_addr, ACTION_STOP_ON_STOP);
break;
case SIGP_STOP_STORE_STATUS:
vcpu->stat.instruction_sigp_stop++;
rc = __sigp_stop(vcpu, cpu_addr, ACTION_STORE_ON_STOP |
ACTION_STOP_ON_STOP);
break;
case SIGP_SET_ARCH:
vcpu->stat.instruction_sigp_arch++;
rc = __sigp_set_arch(vcpu, parameter);
break;
case SIGP_SET_PREFIX:
vcpu->stat.instruction_sigp_prefix++;
rc = __sigp_set_prefix(vcpu, cpu_addr, parameter,
&vcpu->run->s.regs.gprs[r1]);
break;
case SIGP_SENSE_RUNNING:
vcpu->stat.instruction_sigp_sense_running++;
rc = __sigp_sense_running(vcpu, cpu_addr,
&vcpu->run->s.regs.gprs[r1]);
break;
case SIGP_RESTART:
vcpu->stat.instruction_sigp_restart++;
rc = __sigp_restart(vcpu, cpu_addr);
if (rc == 2) /* busy */
break;
/* user space must know about restart */
default:
return -EOPNOTSUPP;
}
if (rc < 0)
return rc;
vcpu->arch.sie_block->gpsw.mask &= ~(3ul << 44);
vcpu->arch.sie_block->gpsw.mask |= (rc & 3ul) << 44;
return 0;
}
| gpl-2.0 |
NamelessRom/android_kernel_google_msm | drivers/mtd/maps/plat-ram.c | 4978 | 6435 | /* drivers/mtd/maps/plat-ram.c
*
* (c) 2004-2005 Simtec Electronics
* http://www.simtec.co.uk/products/SWLINUX/
* Ben Dooks <ben@simtec.co.uk>
*
* Generic platform device based RAM map
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/ioport.h>
#include <linux/device.h>
#include <linux/slab.h>
#include <linux/platform_device.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/map.h>
#include <linux/mtd/partitions.h>
#include <linux/mtd/plat-ram.h>
#include <asm/io.h>
/* private structure for each mtd platform ram device created */
struct platram_info {
struct device *dev;
struct mtd_info *mtd;
struct map_info map;
struct resource *area;
struct platdata_mtd_ram *pdata;
};
/* to_platram_info()
*
* device private data to struct platram_info conversion
*/
static inline struct platram_info *to_platram_info(struct platform_device *dev)
{
return (struct platram_info *)platform_get_drvdata(dev);
}
/* platram_setrw
*
* call the platform device's set rw/ro control
*
* to = 0 => read-only
* = 1 => read-write
*/
static inline void platram_setrw(struct platram_info *info, int to)
{
if (info->pdata == NULL)
return;
if (info->pdata->set_rw != NULL)
(info->pdata->set_rw)(info->dev, to);
}
/* platram_remove
*
* called to remove the device from the driver's control
*/
static int platram_remove(struct platform_device *pdev)
{
struct platram_info *info = to_platram_info(pdev);
platform_set_drvdata(pdev, NULL);
dev_dbg(&pdev->dev, "removing device\n");
if (info == NULL)
return 0;
if (info->mtd) {
mtd_device_unregister(info->mtd);
map_destroy(info->mtd);
}
/* ensure ram is left read-only */
platram_setrw(info, PLATRAM_RO);
/* release resources */
if (info->area) {
release_resource(info->area);
kfree(info->area);
}
if (info->map.virt != NULL)
iounmap(info->map.virt);
kfree(info);
return 0;
}
/* platram_probe
*
* called from device drive system when a device matching our
* driver is found.
*/
static int platram_probe(struct platform_device *pdev)
{
struct platdata_mtd_ram *pdata;
struct platram_info *info;
struct resource *res;
int err = 0;
dev_dbg(&pdev->dev, "probe entered\n");
if (pdev->dev.platform_data == NULL) {
dev_err(&pdev->dev, "no platform data supplied\n");
err = -ENOENT;
goto exit_error;
}
pdata = pdev->dev.platform_data;
info = kzalloc(sizeof(*info), GFP_KERNEL);
if (info == NULL) {
dev_err(&pdev->dev, "no memory for flash info\n");
err = -ENOMEM;
goto exit_error;
}
platform_set_drvdata(pdev, info);
info->dev = &pdev->dev;
info->pdata = pdata;
/* get the resource for the memory mapping */
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (res == NULL) {
dev_err(&pdev->dev, "no memory resource specified\n");
err = -ENOENT;
goto exit_free;
}
dev_dbg(&pdev->dev, "got platform resource %p (0x%llx)\n", res,
(unsigned long long)res->start);
/* setup map parameters */
info->map.phys = res->start;
info->map.size = resource_size(res);
info->map.name = pdata->mapname != NULL ?
(char *)pdata->mapname : (char *)pdev->name;
info->map.bankwidth = pdata->bankwidth;
/* register our usage of the memory area */
info->area = request_mem_region(res->start, info->map.size, pdev->name);
if (info->area == NULL) {
dev_err(&pdev->dev, "failed to request memory region\n");
err = -EIO;
goto exit_free;
}
/* remap the memory area */
info->map.virt = ioremap(res->start, info->map.size);
dev_dbg(&pdev->dev, "virt %p, %lu bytes\n", info->map.virt, info->map.size);
if (info->map.virt == NULL) {
dev_err(&pdev->dev, "failed to ioremap() region\n");
err = -EIO;
goto exit_free;
}
simple_map_init(&info->map);
dev_dbg(&pdev->dev, "initialised map, probing for mtd\n");
/* probe for the right mtd map driver
* supplied by the platform_data struct */
if (pdata->map_probes) {
const char **map_probes = pdata->map_probes;
for ( ; !info->mtd && *map_probes; map_probes++)
info->mtd = do_map_probe(*map_probes , &info->map);
}
/* fallback to map_ram */
else
info->mtd = do_map_probe("map_ram", &info->map);
if (info->mtd == NULL) {
dev_err(&pdev->dev, "failed to probe for map_ram\n");
err = -ENOMEM;
goto exit_free;
}
info->mtd->owner = THIS_MODULE;
info->mtd->dev.parent = &pdev->dev;
platram_setrw(info, PLATRAM_RW);
/* check to see if there are any available partitions, or wether
* to add this device whole */
err = mtd_device_parse_register(info->mtd, pdata->probes, NULL,
pdata->partitions,
pdata->nr_partitions);
if (!err)
dev_info(&pdev->dev, "registered mtd device\n");
if (pdata->nr_partitions) {
/* add the whole device. */
err = mtd_device_register(info->mtd, NULL, 0);
if (err) {
dev_err(&pdev->dev,
"failed to register the entire device\n");
}
}
return err;
exit_free:
platram_remove(pdev);
exit_error:
return err;
}
/* device driver info */
/* work with hotplug and coldplug */
MODULE_ALIAS("platform:mtd-ram");
static struct platform_driver platram_driver = {
.probe = platram_probe,
.remove = platram_remove,
.driver = {
.name = "mtd-ram",
.owner = THIS_MODULE,
},
};
/* module init/exit */
static int __init platram_init(void)
{
printk("Generic platform RAM MTD, (c) 2004 Simtec Electronics\n");
return platform_driver_register(&platram_driver);
}
static void __exit platram_exit(void)
{
platform_driver_unregister(&platram_driver);
}
module_init(platram_init);
module_exit(platram_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Ben Dooks <ben@simtec.co.uk>");
MODULE_DESCRIPTION("MTD platform RAM map driver");
| gpl-2.0 |
thornbirdblue/8974_kernel | arch/frv/mb93090-mb00/pci-dma-nommu.c | 8562 | 3486 | /* pci-dma-nommu.c: Dynamic DMA mapping support for the FRV
*
* Copyright (C) 2004 Red Hat, Inc. All Rights Reserved.
* Written by David Woodhouse (dwmw2@infradead.org)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/dma-mapping.h>
#include <linux/list.h>
#include <linux/pci.h>
#include <asm/io.h>
#if 1
#define DMA_SRAM_START dma_coherent_mem_start
#define DMA_SRAM_END dma_coherent_mem_end
#else // Use video RAM on Matrox
#define DMA_SRAM_START 0xe8900000
#define DMA_SRAM_END 0xe8a00000
#endif
struct dma_alloc_record {
struct list_head list;
unsigned long ofs;
unsigned long len;
};
static DEFINE_SPINLOCK(dma_alloc_lock);
static LIST_HEAD(dma_alloc_list);
void *dma_alloc_coherent(struct device *hwdev, size_t size, dma_addr_t *dma_handle, gfp_t gfp)
{
struct dma_alloc_record *new;
struct list_head *this = &dma_alloc_list;
unsigned long flags;
unsigned long start = DMA_SRAM_START;
unsigned long end;
if (!DMA_SRAM_START) {
printk("%s called without any DMA area reserved!\n", __func__);
return NULL;
}
new = kmalloc(sizeof (*new), GFP_ATOMIC);
if (!new)
return NULL;
/* Round up to a reasonable alignment */
new->len = (size + 31) & ~31;
spin_lock_irqsave(&dma_alloc_lock, flags);
list_for_each (this, &dma_alloc_list) {
struct dma_alloc_record *this_r = list_entry(this, struct dma_alloc_record, list);
end = this_r->ofs;
if (end - start >= size)
goto gotone;
start = this_r->ofs + this_r->len;
}
/* Reached end of list. */
end = DMA_SRAM_END;
this = &dma_alloc_list;
if (end - start >= size) {
gotone:
new->ofs = start;
list_add_tail(&new->list, this);
spin_unlock_irqrestore(&dma_alloc_lock, flags);
*dma_handle = start;
return (void *)start;
}
kfree(new);
spin_unlock_irqrestore(&dma_alloc_lock, flags);
return NULL;
}
EXPORT_SYMBOL(dma_alloc_coherent);
void dma_free_coherent(struct device *hwdev, size_t size, void *vaddr, dma_addr_t dma_handle)
{
struct dma_alloc_record *rec;
unsigned long flags;
spin_lock_irqsave(&dma_alloc_lock, flags);
list_for_each_entry(rec, &dma_alloc_list, list) {
if (rec->ofs == dma_handle) {
list_del(&rec->list);
kfree(rec);
spin_unlock_irqrestore(&dma_alloc_lock, flags);
return;
}
}
spin_unlock_irqrestore(&dma_alloc_lock, flags);
BUG();
}
EXPORT_SYMBOL(dma_free_coherent);
dma_addr_t dma_map_single(struct device *dev, void *ptr, size_t size,
enum dma_data_direction direction)
{
BUG_ON(direction == DMA_NONE);
frv_cache_wback_inv((unsigned long) ptr, (unsigned long) ptr + size);
return virt_to_bus(ptr);
}
EXPORT_SYMBOL(dma_map_single);
int dma_map_sg(struct device *dev, struct scatterlist *sg, int nents,
enum dma_data_direction direction)
{
int i;
for (i=0; i<nents; i++)
frv_cache_wback_inv(sg_dma_address(&sg[i]),
sg_dma_address(&sg[i]) + sg_dma_len(&sg[i]));
BUG_ON(direction == DMA_NONE);
return nents;
}
EXPORT_SYMBOL(dma_map_sg);
dma_addr_t dma_map_page(struct device *dev, struct page *page, unsigned long offset,
size_t size, enum dma_data_direction direction)
{
BUG_ON(direction == DMA_NONE);
flush_dcache_page(page);
return (dma_addr_t) page_to_phys(page) + offset;
}
EXPORT_SYMBOL(dma_map_page);
| gpl-2.0 |
MoKee/android_kernel_samsung_sc03e | arch/sh/kernel/cpu/sh4a/pinmux-sh7786.c | 9330 | 30981 | /*
* SH7786 Pinmux
*
* Copyright (C) 2008, 2009 Renesas Solutions Corp.
* Kuninori Morimoto <morimoto.kuninori@renesas.com>
*
* Based on SH7785 pinmux
*
* Copyright (C) 2008 Magnus Damm
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/gpio.h>
#include <cpu/sh7786.h>
enum {
PINMUX_RESERVED = 0,
PINMUX_DATA_BEGIN,
PA7_DATA, PA6_DATA, PA5_DATA, PA4_DATA,
PA3_DATA, PA2_DATA, PA1_DATA, PA0_DATA,
PB7_DATA, PB6_DATA, PB5_DATA, PB4_DATA,
PB3_DATA, PB2_DATA, PB1_DATA, PB0_DATA,
PC7_DATA, PC6_DATA, PC5_DATA, PC4_DATA,
PC3_DATA, PC2_DATA, PC1_DATA, PC0_DATA,
PD7_DATA, PD6_DATA, PD5_DATA, PD4_DATA,
PD3_DATA, PD2_DATA, PD1_DATA, PD0_DATA,
PE7_DATA, PE6_DATA,
PF7_DATA, PF6_DATA, PF5_DATA, PF4_DATA,
PF3_DATA, PF2_DATA, PF1_DATA, PF0_DATA,
PG7_DATA, PG6_DATA, PG5_DATA,
PH7_DATA, PH6_DATA, PH5_DATA, PH4_DATA,
PH3_DATA, PH2_DATA, PH1_DATA, PH0_DATA,
PJ7_DATA, PJ6_DATA, PJ5_DATA, PJ4_DATA,
PJ3_DATA, PJ2_DATA, PJ1_DATA,
PINMUX_DATA_END,
PINMUX_INPUT_BEGIN,
PA7_IN, PA6_IN, PA5_IN, PA4_IN,
PA3_IN, PA2_IN, PA1_IN, PA0_IN,
PB7_IN, PB6_IN, PB5_IN, PB4_IN,
PB3_IN, PB2_IN, PB1_IN, PB0_IN,
PC7_IN, PC6_IN, PC5_IN, PC4_IN,
PC3_IN, PC2_IN, PC1_IN, PC0_IN,
PD7_IN, PD6_IN, PD5_IN, PD4_IN,
PD3_IN, PD2_IN, PD1_IN, PD0_IN,
PE7_IN, PE6_IN,
PF7_IN, PF6_IN, PF5_IN, PF4_IN,
PF3_IN, PF2_IN, PF1_IN, PF0_IN,
PG7_IN, PG6_IN, PG5_IN,
PH7_IN, PH6_IN, PH5_IN, PH4_IN,
PH3_IN, PH2_IN, PH1_IN, PH0_IN,
PJ7_IN, PJ6_IN, PJ5_IN, PJ4_IN,
PJ3_IN, PJ2_IN, PJ1_IN,
PINMUX_INPUT_END,
PINMUX_INPUT_PULLUP_BEGIN,
PA7_IN_PU, PA6_IN_PU, PA5_IN_PU, PA4_IN_PU,
PA3_IN_PU, PA2_IN_PU, PA1_IN_PU, PA0_IN_PU,
PB7_IN_PU, PB6_IN_PU, PB5_IN_PU, PB4_IN_PU,
PB3_IN_PU, PB2_IN_PU, PB1_IN_PU, PB0_IN_PU,
PC7_IN_PU, PC6_IN_PU, PC5_IN_PU, PC4_IN_PU,
PC3_IN_PU, PC2_IN_PU, PC1_IN_PU, PC0_IN_PU,
PD7_IN_PU, PD6_IN_PU, PD5_IN_PU, PD4_IN_PU,
PD3_IN_PU, PD2_IN_PU, PD1_IN_PU, PD0_IN_PU,
PE7_IN_PU, PE6_IN_PU,
PF7_IN_PU, PF6_IN_PU, PF5_IN_PU, PF4_IN_PU,
PF3_IN_PU, PF2_IN_PU, PF1_IN_PU, PF0_IN_PU,
PG7_IN_PU, PG6_IN_PU, PG5_IN_PU,
PH7_IN_PU, PH6_IN_PU, PH5_IN_PU, PH4_IN_PU,
PH3_IN_PU, PH2_IN_PU, PH1_IN_PU, PH0_IN_PU,
PJ7_IN_PU, PJ6_IN_PU, PJ5_IN_PU, PJ4_IN_PU,
PJ3_IN_PU, PJ2_IN_PU, PJ1_IN_PU,
PINMUX_INPUT_PULLUP_END,
PINMUX_OUTPUT_BEGIN,
PA7_OUT, PA6_OUT, PA5_OUT, PA4_OUT,
PA3_OUT, PA2_OUT, PA1_OUT, PA0_OUT,
PB7_OUT, PB6_OUT, PB5_OUT, PB4_OUT,
PB3_OUT, PB2_OUT, PB1_OUT, PB0_OUT,
PC7_OUT, PC6_OUT, PC5_OUT, PC4_OUT,
PC3_OUT, PC2_OUT, PC1_OUT, PC0_OUT,
PD7_OUT, PD6_OUT, PD5_OUT, PD4_OUT,
PD3_OUT, PD2_OUT, PD1_OUT, PD0_OUT,
PE7_OUT, PE6_OUT,
PF7_OUT, PF6_OUT, PF5_OUT, PF4_OUT,
PF3_OUT, PF2_OUT, PF1_OUT, PF0_OUT,
PG7_OUT, PG6_OUT, PG5_OUT,
PH7_OUT, PH6_OUT, PH5_OUT, PH4_OUT,
PH3_OUT, PH2_OUT, PH1_OUT, PH0_OUT,
PJ7_OUT, PJ6_OUT, PJ5_OUT, PJ4_OUT,
PJ3_OUT, PJ2_OUT, PJ1_OUT,
PINMUX_OUTPUT_END,
PINMUX_FUNCTION_BEGIN,
PA7_FN, PA6_FN, PA5_FN, PA4_FN,
PA3_FN, PA2_FN, PA1_FN, PA0_FN,
PB7_FN, PB6_FN, PB5_FN, PB4_FN,
PB3_FN, PB2_FN, PB1_FN, PB0_FN,
PC7_FN, PC6_FN, PC5_FN, PC4_FN,
PC3_FN, PC2_FN, PC1_FN, PC0_FN,
PD7_FN, PD6_FN, PD5_FN, PD4_FN,
PD3_FN, PD2_FN, PD1_FN, PD0_FN,
PE7_FN, PE6_FN,
PF7_FN, PF6_FN, PF5_FN, PF4_FN,
PF3_FN, PF2_FN, PF1_FN, PF0_FN,
PG7_FN, PG6_FN, PG5_FN,
PH7_FN, PH6_FN, PH5_FN, PH4_FN,
PH3_FN, PH2_FN, PH1_FN, PH0_FN,
PJ7_FN, PJ6_FN, PJ5_FN, PJ4_FN,
PJ3_FN, PJ2_FN, PJ1_FN,
P1MSEL14_0, P1MSEL14_1,
P1MSEL13_0, P1MSEL13_1,
P1MSEL12_0, P1MSEL12_1,
P1MSEL11_0, P1MSEL11_1,
P1MSEL10_0, P1MSEL10_1,
P1MSEL9_0, P1MSEL9_1,
P1MSEL8_0, P1MSEL8_1,
P1MSEL7_0, P1MSEL7_1,
P1MSEL6_0, P1MSEL6_1,
P1MSEL5_0, P1MSEL5_1,
P1MSEL4_0, P1MSEL4_1,
P1MSEL3_0, P1MSEL3_1,
P1MSEL2_0, P1MSEL2_1,
P1MSEL1_0, P1MSEL1_1,
P1MSEL0_0, P1MSEL0_1,
P2MSEL15_0, P2MSEL15_1,
P2MSEL14_0, P2MSEL14_1,
P2MSEL13_0, P2MSEL13_1,
P2MSEL12_0, P2MSEL12_1,
P2MSEL11_0, P2MSEL11_1,
P2MSEL10_0, P2MSEL10_1,
P2MSEL9_0, P2MSEL9_1,
P2MSEL8_0, P2MSEL8_1,
P2MSEL7_0, P2MSEL7_1,
P2MSEL6_0, P2MSEL6_1,
P2MSEL5_0, P2MSEL5_1,
P2MSEL4_0, P2MSEL4_1,
P2MSEL3_0, P2MSEL3_1,
P2MSEL2_0, P2MSEL2_1,
P2MSEL1_0, P2MSEL1_1,
P2MSEL0_0, P2MSEL0_1,
PINMUX_FUNCTION_END,
PINMUX_MARK_BEGIN,
DCLKIN_MARK, DCLKOUT_MARK, ODDF_MARK,
VSYNC_MARK, HSYNC_MARK, CDE_MARK, DISP_MARK,
DR0_MARK, DR1_MARK, DR2_MARK, DR3_MARK, DR4_MARK, DR5_MARK,
DG0_MARK, DG1_MARK, DG2_MARK, DG3_MARK, DG4_MARK, DG5_MARK,
DB0_MARK, DB1_MARK, DB2_MARK, DB3_MARK, DB4_MARK, DB5_MARK,
ETH_MAGIC_MARK, ETH_LINK_MARK, ETH_TX_ER_MARK, ETH_TX_EN_MARK,
ETH_MDIO_MARK, ETH_RX_CLK_MARK, ETH_MDC_MARK, ETH_COL_MARK,
ETH_TX_CLK_MARK, ETH_CRS_MARK, ETH_RX_DV_MARK, ETH_RX_ER_MARK,
ETH_TXD3_MARK, ETH_TXD2_MARK, ETH_TXD1_MARK, ETH_TXD0_MARK,
ETH_RXD3_MARK, ETH_RXD2_MARK, ETH_RXD1_MARK, ETH_RXD0_MARK,
HSPI_CLK_MARK, HSPI_CS_MARK, HSPI_RX_MARK, HSPI_TX_MARK,
SCIF0_CTS_MARK, SCIF0_RTS_MARK,
SCIF0_SCK_MARK, SCIF0_RXD_MARK, SCIF0_TXD_MARK,
SCIF1_SCK_MARK, SCIF1_RXD_MARK, SCIF1_TXD_MARK,
SCIF3_SCK_MARK, SCIF3_RXD_MARK, SCIF3_TXD_MARK,
SCIF4_SCK_MARK, SCIF4_RXD_MARK, SCIF4_TXD_MARK,
SCIF5_SCK_MARK, SCIF5_RXD_MARK, SCIF5_TXD_MARK,
BREQ_MARK, IOIS16_MARK, CE2B_MARK, CE2A_MARK, BACK_MARK,
FALE_MARK, FRB_MARK, FSTATUS_MARK,
FSE_MARK, FCLE_MARK,
DACK0_MARK, DACK1_MARK, DACK2_MARK, DACK3_MARK,
DREQ0_MARK, DREQ1_MARK, DREQ2_MARK, DREQ3_MARK,
DRAK0_MARK, DRAK1_MARK, DRAK2_MARK, DRAK3_MARK,
USB_OVC1_MARK, USB_OVC0_MARK,
USB_PENC1_MARK, USB_PENC0_MARK,
HAC_RES_MARK,
HAC1_SDOUT_MARK, HAC1_SDIN_MARK, HAC1_SYNC_MARK, HAC1_BITCLK_MARK,
HAC0_SDOUT_MARK, HAC0_SDIN_MARK, HAC0_SYNC_MARK, HAC0_BITCLK_MARK,
SSI0_SDATA_MARK, SSI0_SCK_MARK, SSI0_WS_MARK, SSI0_CLK_MARK,
SSI1_SDATA_MARK, SSI1_SCK_MARK, SSI1_WS_MARK, SSI1_CLK_MARK,
SSI2_SDATA_MARK, SSI2_SCK_MARK, SSI2_WS_MARK,
SSI3_SDATA_MARK, SSI3_SCK_MARK, SSI3_WS_MARK,
SDIF1CMD_MARK, SDIF1CD_MARK, SDIF1WP_MARK, SDIF1CLK_MARK,
SDIF1D3_MARK, SDIF1D2_MARK, SDIF1D1_MARK, SDIF1D0_MARK,
SDIF0CMD_MARK, SDIF0CD_MARK, SDIF0WP_MARK, SDIF0CLK_MARK,
SDIF0D3_MARK, SDIF0D2_MARK, SDIF0D1_MARK, SDIF0D0_MARK,
TCLK_MARK,
IRL7_MARK, IRL6_MARK, IRL5_MARK, IRL4_MARK,
PINMUX_MARK_END,
};
static pinmux_enum_t pinmux_data[] = {
/* PA GPIO */
PINMUX_DATA(PA7_DATA, PA7_IN, PA7_OUT, PA7_IN_PU),
PINMUX_DATA(PA6_DATA, PA6_IN, PA6_OUT, PA6_IN_PU),
PINMUX_DATA(PA5_DATA, PA5_IN, PA5_OUT, PA5_IN_PU),
PINMUX_DATA(PA4_DATA, PA4_IN, PA4_OUT, PA4_IN_PU),
PINMUX_DATA(PA3_DATA, PA3_IN, PA3_OUT, PA3_IN_PU),
PINMUX_DATA(PA2_DATA, PA2_IN, PA2_OUT, PA2_IN_PU),
PINMUX_DATA(PA1_DATA, PA1_IN, PA1_OUT, PA1_IN_PU),
PINMUX_DATA(PA0_DATA, PA0_IN, PA0_OUT, PA0_IN_PU),
/* PB GPIO */
PINMUX_DATA(PB7_DATA, PB7_IN, PB7_OUT, PB7_IN_PU),
PINMUX_DATA(PB6_DATA, PB6_IN, PB6_OUT, PB6_IN_PU),
PINMUX_DATA(PB5_DATA, PB5_IN, PB5_OUT, PB5_IN_PU),
PINMUX_DATA(PB4_DATA, PB4_IN, PB4_OUT, PB4_IN_PU),
PINMUX_DATA(PB3_DATA, PB3_IN, PB3_OUT, PB3_IN_PU),
PINMUX_DATA(PB2_DATA, PB2_IN, PB2_OUT, PB2_IN_PU),
PINMUX_DATA(PB1_DATA, PB1_IN, PB1_OUT, PB1_IN_PU),
PINMUX_DATA(PB0_DATA, PB0_IN, PB0_OUT, PB0_IN_PU),
/* PC GPIO */
PINMUX_DATA(PC7_DATA, PC7_IN, PC7_OUT, PC7_IN_PU),
PINMUX_DATA(PC6_DATA, PC6_IN, PC6_OUT, PC6_IN_PU),
PINMUX_DATA(PC5_DATA, PC5_IN, PC5_OUT, PC5_IN_PU),
PINMUX_DATA(PC4_DATA, PC4_IN, PC4_OUT, PC4_IN_PU),
PINMUX_DATA(PC3_DATA, PC3_IN, PC3_OUT, PC3_IN_PU),
PINMUX_DATA(PC2_DATA, PC2_IN, PC2_OUT, PC2_IN_PU),
PINMUX_DATA(PC1_DATA, PC1_IN, PC1_OUT, PC1_IN_PU),
PINMUX_DATA(PC0_DATA, PC0_IN, PC0_OUT, PC0_IN_PU),
/* PD GPIO */
PINMUX_DATA(PD7_DATA, PD7_IN, PD7_OUT, PD7_IN_PU),
PINMUX_DATA(PD6_DATA, PD6_IN, PD6_OUT, PD6_IN_PU),
PINMUX_DATA(PD5_DATA, PD5_IN, PD5_OUT, PD5_IN_PU),
PINMUX_DATA(PD4_DATA, PD4_IN, PD4_OUT, PD4_IN_PU),
PINMUX_DATA(PD3_DATA, PD3_IN, PD3_OUT, PD3_IN_PU),
PINMUX_DATA(PD2_DATA, PD2_IN, PD2_OUT, PD2_IN_PU),
PINMUX_DATA(PD1_DATA, PD1_IN, PD1_OUT, PD1_IN_PU),
PINMUX_DATA(PD0_DATA, PD0_IN, PD0_OUT, PD0_IN_PU),
/* PE GPIO */
PINMUX_DATA(PE7_DATA, PE7_IN, PE7_OUT, PE7_IN_PU),
PINMUX_DATA(PE6_DATA, PE6_IN, PE6_OUT, PE6_IN_PU),
/* PF GPIO */
PINMUX_DATA(PF7_DATA, PF7_IN, PF7_OUT, PF7_IN_PU),
PINMUX_DATA(PF6_DATA, PF6_IN, PF6_OUT, PF6_IN_PU),
PINMUX_DATA(PF5_DATA, PF5_IN, PF5_OUT, PF5_IN_PU),
PINMUX_DATA(PF4_DATA, PF4_IN, PF4_OUT, PF4_IN_PU),
PINMUX_DATA(PF3_DATA, PF3_IN, PF3_OUT, PF3_IN_PU),
PINMUX_DATA(PF2_DATA, PF2_IN, PF2_OUT, PF2_IN_PU),
PINMUX_DATA(PF1_DATA, PF1_IN, PF1_OUT, PF1_IN_PU),
PINMUX_DATA(PF0_DATA, PF0_IN, PF0_OUT, PF0_IN_PU),
/* PG GPIO */
PINMUX_DATA(PG7_DATA, PG7_IN, PG7_OUT, PG7_IN_PU),
PINMUX_DATA(PG6_DATA, PG6_IN, PG6_OUT, PG6_IN_PU),
PINMUX_DATA(PG5_DATA, PG5_IN, PG5_OUT, PG5_IN_PU),
/* PH GPIO */
PINMUX_DATA(PH7_DATA, PH7_IN, PH7_OUT, PH7_IN_PU),
PINMUX_DATA(PH6_DATA, PH6_IN, PH6_OUT, PH6_IN_PU),
PINMUX_DATA(PH5_DATA, PH5_IN, PH5_OUT, PH5_IN_PU),
PINMUX_DATA(PH4_DATA, PH4_IN, PH4_OUT, PH4_IN_PU),
PINMUX_DATA(PH3_DATA, PH3_IN, PH3_OUT, PH3_IN_PU),
PINMUX_DATA(PH2_DATA, PH2_IN, PH2_OUT, PH2_IN_PU),
PINMUX_DATA(PH1_DATA, PH1_IN, PH1_OUT, PH1_IN_PU),
PINMUX_DATA(PH0_DATA, PH0_IN, PH0_OUT, PH0_IN_PU),
/* PJ GPIO */
PINMUX_DATA(PJ7_DATA, PJ7_IN, PJ7_OUT, PJ7_IN_PU),
PINMUX_DATA(PJ6_DATA, PJ6_IN, PJ6_OUT, PJ6_IN_PU),
PINMUX_DATA(PJ5_DATA, PJ5_IN, PJ5_OUT, PJ5_IN_PU),
PINMUX_DATA(PJ4_DATA, PJ4_IN, PJ4_OUT, PJ4_IN_PU),
PINMUX_DATA(PJ3_DATA, PJ3_IN, PJ3_OUT, PJ3_IN_PU),
PINMUX_DATA(PJ2_DATA, PJ2_IN, PJ2_OUT, PJ2_IN_PU),
PINMUX_DATA(PJ1_DATA, PJ1_IN, PJ1_OUT, PJ1_IN_PU),
/* PA FN */
PINMUX_DATA(CDE_MARK, P1MSEL2_0, PA7_FN),
PINMUX_DATA(DISP_MARK, P1MSEL2_0, PA6_FN),
PINMUX_DATA(DR5_MARK, P1MSEL2_0, PA5_FN),
PINMUX_DATA(DR4_MARK, P1MSEL2_0, PA4_FN),
PINMUX_DATA(DR3_MARK, P1MSEL2_0, PA3_FN),
PINMUX_DATA(DR2_MARK, P1MSEL2_0, PA2_FN),
PINMUX_DATA(DR1_MARK, P1MSEL2_0, PA1_FN),
PINMUX_DATA(DR0_MARK, P1MSEL2_0, PA0_FN),
PINMUX_DATA(ETH_MAGIC_MARK, P1MSEL2_1, PA7_FN),
PINMUX_DATA(ETH_LINK_MARK, P1MSEL2_1, PA6_FN),
PINMUX_DATA(ETH_TX_ER_MARK, P1MSEL2_1, PA5_FN),
PINMUX_DATA(ETH_TX_EN_MARK, P1MSEL2_1, PA4_FN),
PINMUX_DATA(ETH_TXD3_MARK, P1MSEL2_1, PA3_FN),
PINMUX_DATA(ETH_TXD2_MARK, P1MSEL2_1, PA2_FN),
PINMUX_DATA(ETH_TXD1_MARK, P1MSEL2_1, PA1_FN),
PINMUX_DATA(ETH_TXD0_MARK, P1MSEL2_1, PA0_FN),
/* PB FN */
PINMUX_DATA(VSYNC_MARK, P1MSEL3_0, PB7_FN),
PINMUX_DATA(ODDF_MARK, P1MSEL3_0, PB6_FN),
PINMUX_DATA(DG5_MARK, P1MSEL2_0, PB5_FN),
PINMUX_DATA(DG4_MARK, P1MSEL2_0, PB4_FN),
PINMUX_DATA(DG3_MARK, P1MSEL2_0, PB3_FN),
PINMUX_DATA(DG2_MARK, P1MSEL2_0, PB2_FN),
PINMUX_DATA(DG1_MARK, P1MSEL2_0, PB1_FN),
PINMUX_DATA(DG0_MARK, P1MSEL2_0, PB0_FN),
PINMUX_DATA(HSPI_CLK_MARK, P1MSEL3_1, PB7_FN),
PINMUX_DATA(HSPI_CS_MARK, P1MSEL3_1, PB6_FN),
PINMUX_DATA(ETH_MDIO_MARK, P1MSEL2_1, PB5_FN),
PINMUX_DATA(ETH_RX_CLK_MARK, P1MSEL2_1, PB4_FN),
PINMUX_DATA(ETH_MDC_MARK, P1MSEL2_1, PB3_FN),
PINMUX_DATA(ETH_COL_MARK, P1MSEL2_1, PB2_FN),
PINMUX_DATA(ETH_TX_CLK_MARK, P1MSEL2_1, PB1_FN),
PINMUX_DATA(ETH_CRS_MARK, P1MSEL2_1, PB0_FN),
/* PC FN */
PINMUX_DATA(DCLKIN_MARK, P1MSEL3_0, PC7_FN),
PINMUX_DATA(HSYNC_MARK, P1MSEL3_0, PC6_FN),
PINMUX_DATA(DB5_MARK, P1MSEL2_0, PC5_FN),
PINMUX_DATA(DB4_MARK, P1MSEL2_0, PC4_FN),
PINMUX_DATA(DB3_MARK, P1MSEL2_0, PC3_FN),
PINMUX_DATA(DB2_MARK, P1MSEL2_0, PC2_FN),
PINMUX_DATA(DB1_MARK, P1MSEL2_0, PC1_FN),
PINMUX_DATA(DB0_MARK, P1MSEL2_0, PC0_FN),
PINMUX_DATA(HSPI_RX_MARK, P1MSEL3_1, PC7_FN),
PINMUX_DATA(HSPI_TX_MARK, P1MSEL3_1, PC6_FN),
PINMUX_DATA(ETH_RXD3_MARK, P1MSEL2_1, PC5_FN),
PINMUX_DATA(ETH_RXD2_MARK, P1MSEL2_1, PC4_FN),
PINMUX_DATA(ETH_RXD1_MARK, P1MSEL2_1, PC3_FN),
PINMUX_DATA(ETH_RXD0_MARK, P1MSEL2_1, PC2_FN),
PINMUX_DATA(ETH_RX_DV_MARK, P1MSEL2_1, PC1_FN),
PINMUX_DATA(ETH_RX_ER_MARK, P1MSEL2_1, PC0_FN),
/* PD FN */
PINMUX_DATA(DCLKOUT_MARK, PD7_FN),
PINMUX_DATA(SCIF1_SCK_MARK, PD6_FN),
PINMUX_DATA(SCIF1_RXD_MARK, PD5_FN),
PINMUX_DATA(SCIF1_TXD_MARK, PD4_FN),
PINMUX_DATA(DACK1_MARK, P1MSEL13_1, P1MSEL12_0, PD3_FN),
PINMUX_DATA(BACK_MARK, P1MSEL13_0, P1MSEL12_1, PD3_FN),
PINMUX_DATA(FALE_MARK, P1MSEL13_0, P1MSEL12_0, PD3_FN),
PINMUX_DATA(DACK0_MARK, P1MSEL14_1, PD2_FN),
PINMUX_DATA(FCLE_MARK, P1MSEL14_0, PD2_FN),
PINMUX_DATA(DREQ1_MARK, P1MSEL10_0, P1MSEL9_1, PD1_FN),
PINMUX_DATA(BREQ_MARK, P1MSEL10_1, P1MSEL9_0, PD1_FN),
PINMUX_DATA(USB_OVC1_MARK, P1MSEL10_0, P1MSEL9_0, PD1_FN),
PINMUX_DATA(DREQ0_MARK, P1MSEL11_1, PD0_FN),
PINMUX_DATA(USB_OVC0_MARK, P1MSEL11_0, PD0_FN),
/* PE FN */
PINMUX_DATA(USB_PENC1_MARK, PE7_FN),
PINMUX_DATA(USB_PENC0_MARK, PE6_FN),
/* PF FN */
PINMUX_DATA(HAC1_SDOUT_MARK, P2MSEL15_0, P2MSEL14_0, PF7_FN),
PINMUX_DATA(HAC1_SDIN_MARK, P2MSEL15_0, P2MSEL14_0, PF6_FN),
PINMUX_DATA(HAC1_SYNC_MARK, P2MSEL15_0, P2MSEL14_0, PF5_FN),
PINMUX_DATA(HAC1_BITCLK_MARK, P2MSEL15_0, P2MSEL14_0, PF4_FN),
PINMUX_DATA(HAC0_SDOUT_MARK, P2MSEL13_0, P2MSEL12_0, PF3_FN),
PINMUX_DATA(HAC0_SDIN_MARK, P2MSEL13_0, P2MSEL12_0, PF2_FN),
PINMUX_DATA(HAC0_SYNC_MARK, P2MSEL13_0, P2MSEL12_0, PF1_FN),
PINMUX_DATA(HAC0_BITCLK_MARK, P2MSEL13_0, P2MSEL12_0, PF0_FN),
PINMUX_DATA(SSI1_SDATA_MARK, P2MSEL15_0, P2MSEL14_1, PF7_FN),
PINMUX_DATA(SSI1_SCK_MARK, P2MSEL15_0, P2MSEL14_1, PF6_FN),
PINMUX_DATA(SSI1_WS_MARK, P2MSEL15_0, P2MSEL14_1, PF5_FN),
PINMUX_DATA(SSI1_CLK_MARK, P2MSEL15_0, P2MSEL14_1, PF4_FN),
PINMUX_DATA(SSI0_SDATA_MARK, P2MSEL13_0, P2MSEL12_1, PF3_FN),
PINMUX_DATA(SSI0_SCK_MARK, P2MSEL13_0, P2MSEL12_1, PF2_FN),
PINMUX_DATA(SSI0_WS_MARK, P2MSEL13_0, P2MSEL12_1, PF1_FN),
PINMUX_DATA(SSI0_CLK_MARK, P2MSEL13_0, P2MSEL12_1, PF0_FN),
PINMUX_DATA(SDIF1CMD_MARK, P2MSEL15_1, P2MSEL14_0, PF7_FN),
PINMUX_DATA(SDIF1CD_MARK, P2MSEL15_1, P2MSEL14_0, PF6_FN),
PINMUX_DATA(SDIF1WP_MARK, P2MSEL15_1, P2MSEL14_0, PF5_FN),
PINMUX_DATA(SDIF1CLK_MARK, P2MSEL15_1, P2MSEL14_0, PF4_FN),
PINMUX_DATA(SDIF1D3_MARK, P2MSEL13_1, P2MSEL12_0, PF3_FN),
PINMUX_DATA(SDIF1D2_MARK, P2MSEL13_1, P2MSEL12_0, PF2_FN),
PINMUX_DATA(SDIF1D1_MARK, P2MSEL13_1, P2MSEL12_0, PF1_FN),
PINMUX_DATA(SDIF1D0_MARK, P2MSEL13_1, P2MSEL12_0, PF0_FN),
/* PG FN */
PINMUX_DATA(SCIF3_SCK_MARK, P1MSEL8_0, PG7_FN),
PINMUX_DATA(SSI2_SDATA_MARK, P1MSEL8_1, PG7_FN),
PINMUX_DATA(SCIF3_RXD_MARK, P1MSEL7_0, P1MSEL6_0, PG6_FN),
PINMUX_DATA(SSI2_SCK_MARK, P1MSEL7_1, P1MSEL6_0, PG6_FN),
PINMUX_DATA(TCLK_MARK, P1MSEL7_0, P1MSEL6_1, PG6_FN),
PINMUX_DATA(SCIF3_TXD_MARK, P1MSEL5_0, P1MSEL4_0, PG5_FN),
PINMUX_DATA(SSI2_WS_MARK, P1MSEL5_1, P1MSEL4_0, PG5_FN),
PINMUX_DATA(HAC_RES_MARK, P1MSEL5_0, P1MSEL4_1, PG5_FN),
/* PH FN */
PINMUX_DATA(DACK3_MARK, P2MSEL4_0, PH7_FN),
PINMUX_DATA(SDIF0CMD_MARK, P2MSEL4_1, PH7_FN),
PINMUX_DATA(DACK2_MARK, P2MSEL4_0, PH6_FN),
PINMUX_DATA(SDIF0CD_MARK, P2MSEL4_1, PH6_FN),
PINMUX_DATA(DREQ3_MARK, P2MSEL4_0, PH5_FN),
PINMUX_DATA(SDIF0WP_MARK, P2MSEL4_1, PH5_FN),
PINMUX_DATA(DREQ2_MARK, P2MSEL3_0, P2MSEL2_1, PH4_FN),
PINMUX_DATA(SDIF0CLK_MARK, P2MSEL3_1, P2MSEL2_0, PH4_FN),
PINMUX_DATA(SCIF0_CTS_MARK, P2MSEL3_0, P2MSEL2_0, PH4_FN),
PINMUX_DATA(SDIF0D3_MARK, P2MSEL1_1, P2MSEL0_0, PH3_FN),
PINMUX_DATA(SCIF0_RTS_MARK, P2MSEL1_0, P2MSEL0_0, PH3_FN),
PINMUX_DATA(IRL7_MARK, P2MSEL1_0, P2MSEL0_1, PH3_FN),
PINMUX_DATA(SDIF0D2_MARK, P2MSEL1_1, P2MSEL0_0, PH2_FN),
PINMUX_DATA(SCIF0_SCK_MARK, P2MSEL1_0, P2MSEL0_0, PH2_FN),
PINMUX_DATA(IRL6_MARK, P2MSEL1_0, P2MSEL0_1, PH2_FN),
PINMUX_DATA(SDIF0D1_MARK, P2MSEL1_1, P2MSEL0_0, PH1_FN),
PINMUX_DATA(SCIF0_RXD_MARK, P2MSEL1_0, P2MSEL0_0, PH1_FN),
PINMUX_DATA(IRL5_MARK, P2MSEL1_0, P2MSEL0_1, PH1_FN),
PINMUX_DATA(SDIF0D0_MARK, P2MSEL1_1, P2MSEL0_0, PH0_FN),
PINMUX_DATA(SCIF0_TXD_MARK, P2MSEL1_0, P2MSEL0_0, PH0_FN),
PINMUX_DATA(IRL4_MARK, P2MSEL1_0, P2MSEL0_1, PH0_FN),
/* PJ FN */
PINMUX_DATA(SCIF5_SCK_MARK, P2MSEL11_1, PJ7_FN),
PINMUX_DATA(FRB_MARK, P2MSEL11_0, PJ7_FN),
PINMUX_DATA(SCIF5_RXD_MARK, P2MSEL10_0, PJ6_FN),
PINMUX_DATA(IOIS16_MARK, P2MSEL10_1, PJ6_FN),
PINMUX_DATA(SCIF5_TXD_MARK, P2MSEL10_0, PJ5_FN),
PINMUX_DATA(CE2B_MARK, P2MSEL10_1, PJ5_FN),
PINMUX_DATA(DRAK3_MARK, P2MSEL7_0, PJ4_FN),
PINMUX_DATA(CE2A_MARK, P2MSEL7_1, PJ4_FN),
PINMUX_DATA(SCIF4_SCK_MARK, P2MSEL9_0, P2MSEL8_0, PJ3_FN),
PINMUX_DATA(DRAK2_MARK, P2MSEL9_0, P2MSEL8_1, PJ3_FN),
PINMUX_DATA(SSI3_WS_MARK, P2MSEL9_1, P2MSEL8_0, PJ3_FN),
PINMUX_DATA(SCIF4_RXD_MARK, P2MSEL6_1, P2MSEL5_0, PJ2_FN),
PINMUX_DATA(DRAK1_MARK, P2MSEL6_0, P2MSEL5_1, PJ2_FN),
PINMUX_DATA(FSTATUS_MARK, P2MSEL6_0, P2MSEL5_0, PJ2_FN),
PINMUX_DATA(SSI3_SDATA_MARK, P2MSEL6_1, P2MSEL5_1, PJ2_FN),
PINMUX_DATA(SCIF4_TXD_MARK, P2MSEL6_1, P2MSEL5_0, PJ1_FN),
PINMUX_DATA(DRAK0_MARK, P2MSEL6_0, P2MSEL5_1, PJ1_FN),
PINMUX_DATA(FSE_MARK, P2MSEL6_0, P2MSEL5_0, PJ1_FN),
PINMUX_DATA(SSI3_SCK_MARK, P2MSEL6_1, P2MSEL5_1, PJ1_FN),
};
static struct pinmux_gpio pinmux_gpios[] = {
/* PA */
PINMUX_GPIO(GPIO_PA7, PA7_DATA),
PINMUX_GPIO(GPIO_PA6, PA6_DATA),
PINMUX_GPIO(GPIO_PA5, PA5_DATA),
PINMUX_GPIO(GPIO_PA4, PA4_DATA),
PINMUX_GPIO(GPIO_PA3, PA3_DATA),
PINMUX_GPIO(GPIO_PA2, PA2_DATA),
PINMUX_GPIO(GPIO_PA1, PA1_DATA),
PINMUX_GPIO(GPIO_PA0, PA0_DATA),
/* PB */
PINMUX_GPIO(GPIO_PB7, PB7_DATA),
PINMUX_GPIO(GPIO_PB6, PB6_DATA),
PINMUX_GPIO(GPIO_PB5, PB5_DATA),
PINMUX_GPIO(GPIO_PB4, PB4_DATA),
PINMUX_GPIO(GPIO_PB3, PB3_DATA),
PINMUX_GPIO(GPIO_PB2, PB2_DATA),
PINMUX_GPIO(GPIO_PB1, PB1_DATA),
PINMUX_GPIO(GPIO_PB0, PB0_DATA),
/* PC */
PINMUX_GPIO(GPIO_PC7, PC7_DATA),
PINMUX_GPIO(GPIO_PC6, PC6_DATA),
PINMUX_GPIO(GPIO_PC5, PC5_DATA),
PINMUX_GPIO(GPIO_PC4, PC4_DATA),
PINMUX_GPIO(GPIO_PC3, PC3_DATA),
PINMUX_GPIO(GPIO_PC2, PC2_DATA),
PINMUX_GPIO(GPIO_PC1, PC1_DATA),
PINMUX_GPIO(GPIO_PC0, PC0_DATA),
/* PD */
PINMUX_GPIO(GPIO_PD7, PD7_DATA),
PINMUX_GPIO(GPIO_PD6, PD6_DATA),
PINMUX_GPIO(GPIO_PD5, PD5_DATA),
PINMUX_GPIO(GPIO_PD4, PD4_DATA),
PINMUX_GPIO(GPIO_PD3, PD3_DATA),
PINMUX_GPIO(GPIO_PD2, PD2_DATA),
PINMUX_GPIO(GPIO_PD1, PD1_DATA),
PINMUX_GPIO(GPIO_PD0, PD0_DATA),
/* PE */
PINMUX_GPIO(GPIO_PE5, PE7_DATA),
PINMUX_GPIO(GPIO_PE4, PE6_DATA),
/* PF */
PINMUX_GPIO(GPIO_PF7, PF7_DATA),
PINMUX_GPIO(GPIO_PF6, PF6_DATA),
PINMUX_GPIO(GPIO_PF5, PF5_DATA),
PINMUX_GPIO(GPIO_PF4, PF4_DATA),
PINMUX_GPIO(GPIO_PF3, PF3_DATA),
PINMUX_GPIO(GPIO_PF2, PF2_DATA),
PINMUX_GPIO(GPIO_PF1, PF1_DATA),
PINMUX_GPIO(GPIO_PF0, PF0_DATA),
/* PG */
PINMUX_GPIO(GPIO_PG7, PG7_DATA),
PINMUX_GPIO(GPIO_PG6, PG6_DATA),
PINMUX_GPIO(GPIO_PG5, PG5_DATA),
/* PH */
PINMUX_GPIO(GPIO_PH7, PH7_DATA),
PINMUX_GPIO(GPIO_PH6, PH6_DATA),
PINMUX_GPIO(GPIO_PH5, PH5_DATA),
PINMUX_GPIO(GPIO_PH4, PH4_DATA),
PINMUX_GPIO(GPIO_PH3, PH3_DATA),
PINMUX_GPIO(GPIO_PH2, PH2_DATA),
PINMUX_GPIO(GPIO_PH1, PH1_DATA),
PINMUX_GPIO(GPIO_PH0, PH0_DATA),
/* PJ */
PINMUX_GPIO(GPIO_PJ7, PJ7_DATA),
PINMUX_GPIO(GPIO_PJ6, PJ6_DATA),
PINMUX_GPIO(GPIO_PJ5, PJ5_DATA),
PINMUX_GPIO(GPIO_PJ4, PJ4_DATA),
PINMUX_GPIO(GPIO_PJ3, PJ3_DATA),
PINMUX_GPIO(GPIO_PJ2, PJ2_DATA),
PINMUX_GPIO(GPIO_PJ1, PJ1_DATA),
/* FN */
PINMUX_GPIO(GPIO_FN_CDE, CDE_MARK),
PINMUX_GPIO(GPIO_FN_ETH_MAGIC, ETH_MAGIC_MARK),
PINMUX_GPIO(GPIO_FN_DISP, DISP_MARK),
PINMUX_GPIO(GPIO_FN_ETH_LINK, ETH_LINK_MARK),
PINMUX_GPIO(GPIO_FN_DR5, DR5_MARK),
PINMUX_GPIO(GPIO_FN_ETH_TX_ER, ETH_TX_ER_MARK),
PINMUX_GPIO(GPIO_FN_DR4, DR4_MARK),
PINMUX_GPIO(GPIO_FN_ETH_TX_EN, ETH_TX_EN_MARK),
PINMUX_GPIO(GPIO_FN_DR3, DR3_MARK),
PINMUX_GPIO(GPIO_FN_ETH_TXD3, ETH_TXD3_MARK),
PINMUX_GPIO(GPIO_FN_DR2, DR2_MARK),
PINMUX_GPIO(GPIO_FN_ETH_TXD2, ETH_TXD2_MARK),
PINMUX_GPIO(GPIO_FN_DR1, DR1_MARK),
PINMUX_GPIO(GPIO_FN_ETH_TXD1, ETH_TXD1_MARK),
PINMUX_GPIO(GPIO_FN_DR0, DR0_MARK),
PINMUX_GPIO(GPIO_FN_ETH_TXD0, ETH_TXD0_MARK),
PINMUX_GPIO(GPIO_FN_VSYNC, VSYNC_MARK),
PINMUX_GPIO(GPIO_FN_HSPI_CLK, HSPI_CLK_MARK),
PINMUX_GPIO(GPIO_FN_ODDF, ODDF_MARK),
PINMUX_GPIO(GPIO_FN_HSPI_CS, HSPI_CS_MARK),
PINMUX_GPIO(GPIO_FN_DG5, DG5_MARK),
PINMUX_GPIO(GPIO_FN_ETH_MDIO, ETH_MDIO_MARK),
PINMUX_GPIO(GPIO_FN_DG4, DG4_MARK),
PINMUX_GPIO(GPIO_FN_ETH_RX_CLK, ETH_RX_CLK_MARK),
PINMUX_GPIO(GPIO_FN_DG3, DG3_MARK),
PINMUX_GPIO(GPIO_FN_ETH_MDC, ETH_MDC_MARK),
PINMUX_GPIO(GPIO_FN_DG2, DG2_MARK),
PINMUX_GPIO(GPIO_FN_ETH_COL, ETH_COL_MARK),
PINMUX_GPIO(GPIO_FN_DG1, DG1_MARK),
PINMUX_GPIO(GPIO_FN_ETH_TX_CLK, ETH_TX_CLK_MARK),
PINMUX_GPIO(GPIO_FN_DG0, DG0_MARK),
PINMUX_GPIO(GPIO_FN_ETH_CRS, ETH_CRS_MARK),
PINMUX_GPIO(GPIO_FN_DCLKIN, DCLKIN_MARK),
PINMUX_GPIO(GPIO_FN_HSPI_RX, HSPI_RX_MARK),
PINMUX_GPIO(GPIO_FN_HSYNC, HSYNC_MARK),
PINMUX_GPIO(GPIO_FN_HSPI_TX, HSPI_TX_MARK),
PINMUX_GPIO(GPIO_FN_DB5, DB5_MARK),
PINMUX_GPIO(GPIO_FN_ETH_RXD3, ETH_RXD3_MARK),
PINMUX_GPIO(GPIO_FN_DB4, DB4_MARK),
PINMUX_GPIO(GPIO_FN_ETH_RXD2, ETH_RXD2_MARK),
PINMUX_GPIO(GPIO_FN_DB3, DB3_MARK),
PINMUX_GPIO(GPIO_FN_ETH_RXD1, ETH_RXD1_MARK),
PINMUX_GPIO(GPIO_FN_DB2, DB2_MARK),
PINMUX_GPIO(GPIO_FN_ETH_RXD0, ETH_RXD0_MARK),
PINMUX_GPIO(GPIO_FN_DB1, DB1_MARK),
PINMUX_GPIO(GPIO_FN_ETH_RX_DV, ETH_RX_DV_MARK),
PINMUX_GPIO(GPIO_FN_DB0, DB0_MARK),
PINMUX_GPIO(GPIO_FN_ETH_RX_ER, ETH_RX_ER_MARK),
PINMUX_GPIO(GPIO_FN_DCLKOUT, DCLKOUT_MARK),
PINMUX_GPIO(GPIO_FN_SCIF1_SCK, SCIF1_SCK_MARK),
PINMUX_GPIO(GPIO_FN_SCIF1_RXD, SCIF1_RXD_MARK),
PINMUX_GPIO(GPIO_FN_SCIF1_TXD, SCIF1_TXD_MARK),
PINMUX_GPIO(GPIO_FN_DACK1, DACK1_MARK),
PINMUX_GPIO(GPIO_FN_BACK, BACK_MARK),
PINMUX_GPIO(GPIO_FN_FALE, FALE_MARK),
PINMUX_GPIO(GPIO_FN_DACK0, DACK0_MARK),
PINMUX_GPIO(GPIO_FN_FCLE, FCLE_MARK),
PINMUX_GPIO(GPIO_FN_DREQ1, DREQ1_MARK),
PINMUX_GPIO(GPIO_FN_BREQ, BREQ_MARK),
PINMUX_GPIO(GPIO_FN_USB_OVC1, USB_OVC1_MARK),
PINMUX_GPIO(GPIO_FN_DREQ0, DREQ0_MARK),
PINMUX_GPIO(GPIO_FN_USB_OVC0, USB_OVC0_MARK),
PINMUX_GPIO(GPIO_FN_USB_PENC1, USB_PENC1_MARK),
PINMUX_GPIO(GPIO_FN_USB_PENC0, USB_PENC0_MARK),
PINMUX_GPIO(GPIO_FN_HAC1_SDOUT, HAC1_SDOUT_MARK),
PINMUX_GPIO(GPIO_FN_SSI1_SDATA, SSI1_SDATA_MARK),
PINMUX_GPIO(GPIO_FN_SDIF1CMD, SDIF1CMD_MARK),
PINMUX_GPIO(GPIO_FN_HAC1_SDIN, HAC1_SDIN_MARK),
PINMUX_GPIO(GPIO_FN_SSI1_SCK, SSI1_SCK_MARK),
PINMUX_GPIO(GPIO_FN_SDIF1CD, SDIF1CD_MARK),
PINMUX_GPIO(GPIO_FN_HAC1_SYNC, HAC1_SYNC_MARK),
PINMUX_GPIO(GPIO_FN_SSI1_WS, SSI1_WS_MARK),
PINMUX_GPIO(GPIO_FN_SDIF1WP, SDIF1WP_MARK),
PINMUX_GPIO(GPIO_FN_HAC1_BITCLK, HAC1_BITCLK_MARK),
PINMUX_GPIO(GPIO_FN_SSI1_CLK, SSI1_CLK_MARK),
PINMUX_GPIO(GPIO_FN_SDIF1CLK, SDIF1CLK_MARK),
PINMUX_GPIO(GPIO_FN_HAC0_SDOUT, HAC0_SDOUT_MARK),
PINMUX_GPIO(GPIO_FN_SSI0_SDATA, SSI0_SDATA_MARK),
PINMUX_GPIO(GPIO_FN_SDIF1D3, SDIF1D3_MARK),
PINMUX_GPIO(GPIO_FN_HAC0_SDIN, HAC0_SDIN_MARK),
PINMUX_GPIO(GPIO_FN_SSI0_SCK, SSI0_SCK_MARK),
PINMUX_GPIO(GPIO_FN_SDIF1D2, SDIF1D2_MARK),
PINMUX_GPIO(GPIO_FN_HAC0_SYNC, HAC0_SYNC_MARK),
PINMUX_GPIO(GPIO_FN_SSI0_WS, SSI0_WS_MARK),
PINMUX_GPIO(GPIO_FN_SDIF1D1, SDIF1D1_MARK),
PINMUX_GPIO(GPIO_FN_HAC0_BITCLK, HAC0_BITCLK_MARK),
PINMUX_GPIO(GPIO_FN_SSI0_CLK, SSI0_CLK_MARK),
PINMUX_GPIO(GPIO_FN_SDIF1D0, SDIF1D0_MARK),
PINMUX_GPIO(GPIO_FN_SCIF3_SCK, SCIF3_SCK_MARK),
PINMUX_GPIO(GPIO_FN_SSI2_SDATA, SSI2_SDATA_MARK),
PINMUX_GPIO(GPIO_FN_SCIF3_RXD, SCIF3_RXD_MARK),
PINMUX_GPIO(GPIO_FN_TCLK, TCLK_MARK),
PINMUX_GPIO(GPIO_FN_SSI2_SCK, SSI2_SCK_MARK),
PINMUX_GPIO(GPIO_FN_SCIF3_TXD, SCIF3_TXD_MARK),
PINMUX_GPIO(GPIO_FN_HAC_RES, HAC_RES_MARK),
PINMUX_GPIO(GPIO_FN_SSI2_WS, SSI2_WS_MARK),
PINMUX_GPIO(GPIO_FN_DACK3, DACK3_MARK),
PINMUX_GPIO(GPIO_FN_SDIF0CMD, SDIF0CMD_MARK),
PINMUX_GPIO(GPIO_FN_DACK2, DACK2_MARK),
PINMUX_GPIO(GPIO_FN_SDIF0CD, SDIF0CD_MARK),
PINMUX_GPIO(GPIO_FN_DREQ3, DREQ3_MARK),
PINMUX_GPIO(GPIO_FN_SDIF0WP, SDIF0WP_MARK),
PINMUX_GPIO(GPIO_FN_SCIF0_CTS, SCIF0_CTS_MARK),
PINMUX_GPIO(GPIO_FN_DREQ2, DREQ2_MARK),
PINMUX_GPIO(GPIO_FN_SDIF0CLK, SDIF0CLK_MARK),
PINMUX_GPIO(GPIO_FN_SCIF0_RTS, SCIF0_RTS_MARK),
PINMUX_GPIO(GPIO_FN_IRL7, IRL7_MARK),
PINMUX_GPIO(GPIO_FN_SDIF0D3, SDIF0D3_MARK),
PINMUX_GPIO(GPIO_FN_SCIF0_SCK, SCIF0_SCK_MARK),
PINMUX_GPIO(GPIO_FN_IRL6, IRL6_MARK),
PINMUX_GPIO(GPIO_FN_SDIF0D2, SDIF0D2_MARK),
PINMUX_GPIO(GPIO_FN_SCIF0_RXD, SCIF0_RXD_MARK),
PINMUX_GPIO(GPIO_FN_IRL5, IRL5_MARK),
PINMUX_GPIO(GPIO_FN_SDIF0D1, SDIF0D1_MARK),
PINMUX_GPIO(GPIO_FN_SCIF0_TXD, SCIF0_TXD_MARK),
PINMUX_GPIO(GPIO_FN_IRL4, IRL4_MARK),
PINMUX_GPIO(GPIO_FN_SDIF0D0, SDIF0D0_MARK),
PINMUX_GPIO(GPIO_FN_SCIF5_SCK, SCIF5_SCK_MARK),
PINMUX_GPIO(GPIO_FN_FRB, FRB_MARK),
PINMUX_GPIO(GPIO_FN_SCIF5_RXD, SCIF5_RXD_MARK),
PINMUX_GPIO(GPIO_FN_IOIS16, IOIS16_MARK),
PINMUX_GPIO(GPIO_FN_SCIF5_TXD, SCIF5_TXD_MARK),
PINMUX_GPIO(GPIO_FN_CE2B, CE2B_MARK),
PINMUX_GPIO(GPIO_FN_DRAK3, DRAK3_MARK),
PINMUX_GPIO(GPIO_FN_CE2A, CE2A_MARK),
PINMUX_GPIO(GPIO_FN_SCIF4_SCK, SCIF4_SCK_MARK),
PINMUX_GPIO(GPIO_FN_DRAK2, DRAK2_MARK),
PINMUX_GPIO(GPIO_FN_SSI3_WS, SSI3_WS_MARK),
PINMUX_GPIO(GPIO_FN_SCIF4_RXD, SCIF4_RXD_MARK),
PINMUX_GPIO(GPIO_FN_DRAK1, DRAK1_MARK),
PINMUX_GPIO(GPIO_FN_SSI3_SDATA, SSI3_SDATA_MARK),
PINMUX_GPIO(GPIO_FN_FSTATUS, FSTATUS_MARK),
PINMUX_GPIO(GPIO_FN_SCIF4_TXD, SCIF4_TXD_MARK),
PINMUX_GPIO(GPIO_FN_DRAK0, DRAK0_MARK),
PINMUX_GPIO(GPIO_FN_SSI3_SCK, SSI3_SCK_MARK),
PINMUX_GPIO(GPIO_FN_FSE, FSE_MARK),
};
static struct pinmux_cfg_reg pinmux_config_regs[] = {
{ PINMUX_CFG_REG("PACR", 0xffcc0000, 16, 2) {
PA7_FN, PA7_OUT, PA7_IN, PA7_IN_PU,
PA6_FN, PA6_OUT, PA6_IN, PA6_IN_PU,
PA5_FN, PA5_OUT, PA5_IN, PA5_IN_PU,
PA4_FN, PA4_OUT, PA4_IN, PA4_IN_PU,
PA3_FN, PA3_OUT, PA3_IN, PA3_IN_PU,
PA2_FN, PA2_OUT, PA2_IN, PA2_IN_PU,
PA1_FN, PA1_OUT, PA1_IN, PA1_IN_PU,
PA0_FN, PA0_OUT, PA0_IN, PA0_IN_PU }
},
{ PINMUX_CFG_REG("PBCR", 0xffcc0002, 16, 2) {
PB7_FN, PB7_OUT, PB7_IN, PB7_IN_PU,
PB6_FN, PB6_OUT, PB6_IN, PB6_IN_PU,
PB5_FN, PB5_OUT, PB5_IN, PB5_IN_PU,
PB4_FN, PB4_OUT, PB4_IN, PB4_IN_PU,
PB3_FN, PB3_OUT, PB3_IN, PB3_IN_PU,
PB2_FN, PB2_OUT, PB2_IN, PB2_IN_PU,
PB1_FN, PB1_OUT, PB1_IN, PB1_IN_PU,
PB0_FN, PB0_OUT, PB0_IN, PB0_IN_PU }
},
{ PINMUX_CFG_REG("PCCR", 0xffcc0004, 16, 2) {
PC7_FN, PC7_OUT, PC7_IN, PC7_IN_PU,
PC6_FN, PC6_OUT, PC6_IN, PC6_IN_PU,
PC5_FN, PC5_OUT, PC5_IN, PC5_IN_PU,
PC4_FN, PC4_OUT, PC4_IN, PC4_IN_PU,
PC3_FN, PC3_OUT, PC3_IN, PC3_IN_PU,
PC2_FN, PC2_OUT, PC2_IN, PC2_IN_PU,
PC1_FN, PC1_OUT, PC1_IN, PC1_IN_PU,
PC0_FN, PC0_OUT, PC0_IN, PC0_IN_PU }
},
{ PINMUX_CFG_REG("PDCR", 0xffcc0006, 16, 2) {
PD7_FN, PD7_OUT, PD7_IN, PD7_IN_PU,
PD6_FN, PD6_OUT, PD6_IN, PD6_IN_PU,
PD5_FN, PD5_OUT, PD5_IN, PD5_IN_PU,
PD4_FN, PD4_OUT, PD4_IN, PD4_IN_PU,
PD3_FN, PD3_OUT, PD3_IN, PD3_IN_PU,
PD2_FN, PD2_OUT, PD2_IN, PD2_IN_PU,
PD1_FN, PD1_OUT, PD1_IN, PD1_IN_PU,
PD0_FN, PD0_OUT, PD0_IN, PD0_IN_PU }
},
{ PINMUX_CFG_REG("PECR", 0xffcc0008, 16, 2) {
PE7_FN, PE7_OUT, PE7_IN, PE7_IN_PU,
PE6_FN, PE6_OUT, PE6_IN, PE6_IN_PU,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0, }
},
{ PINMUX_CFG_REG("PFCR", 0xffcc000a, 16, 2) {
PF7_FN, PF7_OUT, PF7_IN, PF7_IN_PU,
PF6_FN, PF6_OUT, PF6_IN, PF6_IN_PU,
PF5_FN, PF5_OUT, PF5_IN, PF5_IN_PU,
PF4_FN, PF4_OUT, PF4_IN, PF4_IN_PU,
PF3_FN, PF3_OUT, PF3_IN, PF3_IN_PU,
PF2_FN, PF2_OUT, PF2_IN, PF2_IN_PU,
PF1_FN, PF1_OUT, PF1_IN, PF1_IN_PU,
PF0_FN, PF0_OUT, PF0_IN, PF0_IN_PU }
},
{ PINMUX_CFG_REG("PGCR", 0xffcc000c, 16, 2) {
PG7_FN, PG7_OUT, PG7_IN, PG7_IN_PU,
PG6_FN, PG6_OUT, PG6_IN, PG6_IN_PU,
PG5_FN, PG5_OUT, PG5_IN, PG5_IN_PU,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0, }
},
{ PINMUX_CFG_REG("PHCR", 0xffcc000e, 16, 2) {
PH7_FN, PH7_OUT, PH7_IN, PH7_IN_PU,
PH6_FN, PH6_OUT, PH6_IN, PH6_IN_PU,
PH5_FN, PH5_OUT, PH5_IN, PH5_IN_PU,
PH4_FN, PH4_OUT, PH4_IN, PH4_IN_PU,
PH3_FN, PH3_OUT, PH3_IN, PH3_IN_PU,
PH2_FN, PH2_OUT, PH2_IN, PH2_IN_PU,
PH1_FN, PH1_OUT, PH1_IN, PH1_IN_PU,
PH0_FN, PH0_OUT, PH0_IN, PH0_IN_PU }
},
{ PINMUX_CFG_REG("PJCR", 0xffcc0010, 16, 2) {
PJ7_FN, PJ7_OUT, PJ7_IN, PJ7_IN_PU,
PJ6_FN, PJ6_OUT, PJ6_IN, PJ6_IN_PU,
PJ5_FN, PJ5_OUT, PJ5_IN, PJ5_IN_PU,
PJ4_FN, PJ4_OUT, PJ4_IN, PJ4_IN_PU,
PJ3_FN, PJ3_OUT, PJ3_IN, PJ3_IN_PU,
PJ2_FN, PJ2_OUT, PJ2_IN, PJ2_IN_PU,
PJ1_FN, PJ1_OUT, PJ1_IN, PJ1_IN_PU,
0, 0, 0, 0, }
},
{ PINMUX_CFG_REG("P1MSELR", 0xffcc0080, 16, 1) {
0, 0,
P1MSEL14_0, P1MSEL14_1,
P1MSEL13_0, P1MSEL13_1,
P1MSEL12_0, P1MSEL12_1,
P1MSEL11_0, P1MSEL11_1,
P1MSEL10_0, P1MSEL10_1,
P1MSEL9_0, P1MSEL9_1,
P1MSEL8_0, P1MSEL8_1,
P1MSEL7_0, P1MSEL7_1,
P1MSEL6_0, P1MSEL6_1,
P1MSEL5_0, P1MSEL5_1,
P1MSEL4_0, P1MSEL4_1,
P1MSEL3_0, P1MSEL3_1,
P1MSEL2_0, P1MSEL2_1,
P1MSEL1_0, P1MSEL1_1,
P1MSEL0_0, P1MSEL0_1 }
},
{ PINMUX_CFG_REG("P2MSELR", 0xffcc0082, 16, 1) {
P2MSEL15_0, P2MSEL15_1,
P2MSEL14_0, P2MSEL14_1,
P2MSEL13_0, P2MSEL13_1,
P2MSEL12_0, P2MSEL12_1,
P2MSEL11_0, P2MSEL11_1,
P2MSEL10_0, P2MSEL10_1,
P2MSEL9_0, P2MSEL9_1,
P2MSEL8_0, P2MSEL8_1,
P2MSEL7_0, P2MSEL7_1,
P2MSEL6_0, P2MSEL6_1,
P2MSEL5_0, P2MSEL5_1,
P2MSEL4_0, P2MSEL4_1,
P2MSEL3_0, P2MSEL3_1,
P2MSEL2_0, P2MSEL2_1,
P2MSEL1_0, P2MSEL1_1,
P2MSEL0_0, P2MSEL0_1 }
},
{}
};
static struct pinmux_data_reg pinmux_data_regs[] = {
{ PINMUX_DATA_REG("PADR", 0xffcc0020, 8) {
PA7_DATA, PA6_DATA, PA5_DATA, PA4_DATA,
PA3_DATA, PA2_DATA, PA1_DATA, PA0_DATA }
},
{ PINMUX_DATA_REG("PBDR", 0xffcc0022, 8) {
PB7_DATA, PB6_DATA, PB5_DATA, PB4_DATA,
PB3_DATA, PB2_DATA, PB1_DATA, PB0_DATA }
},
{ PINMUX_DATA_REG("PCDR", 0xffcc0024, 8) {
PC7_DATA, PC6_DATA, PC5_DATA, PC4_DATA,
PC3_DATA, PC2_DATA, PC1_DATA, PC0_DATA }
},
{ PINMUX_DATA_REG("PDDR", 0xffcc0026, 8) {
PD7_DATA, PD6_DATA, PD5_DATA, PD4_DATA,
PD3_DATA, PD2_DATA, PD1_DATA, PD0_DATA }
},
{ PINMUX_DATA_REG("PEDR", 0xffcc0028, 8) {
PE7_DATA, PE6_DATA,
0, 0, 0, 0, 0, 0 }
},
{ PINMUX_DATA_REG("PFDR", 0xffcc002a, 8) {
PF7_DATA, PF6_DATA, PF5_DATA, PF4_DATA,
PF3_DATA, PF2_DATA, PF1_DATA, PF0_DATA }
},
{ PINMUX_DATA_REG("PGDR", 0xffcc002c, 8) {
PG7_DATA, PG6_DATA, PG5_DATA, 0,
0, 0, 0, 0 }
},
{ PINMUX_DATA_REG("PHDR", 0xffcc002e, 8) {
PH7_DATA, PH6_DATA, PH5_DATA, PH4_DATA,
PH3_DATA, PH2_DATA, PH1_DATA, PH0_DATA }
},
{ PINMUX_DATA_REG("PJDR", 0xffcc0030, 8) {
PJ7_DATA, PJ6_DATA, PJ5_DATA, PJ4_DATA,
PJ3_DATA, PJ2_DATA, PJ1_DATA, 0 }
},
{ },
};
static struct pinmux_info sh7786_pinmux_info = {
.name = "sh7786_pfc",
.reserved_id = PINMUX_RESERVED,
.data = { PINMUX_DATA_BEGIN, PINMUX_DATA_END },
.input = { PINMUX_INPUT_BEGIN, PINMUX_INPUT_END },
.input_pu = { PINMUX_INPUT_PULLUP_BEGIN, PINMUX_INPUT_PULLUP_END },
.output = { PINMUX_OUTPUT_BEGIN, PINMUX_OUTPUT_END },
.mark = { PINMUX_MARK_BEGIN, PINMUX_MARK_END },
.function = { PINMUX_FUNCTION_BEGIN, PINMUX_FUNCTION_END },
.first_gpio = GPIO_PA7,
.last_gpio = GPIO_FN_FSE,
.gpios = pinmux_gpios,
.cfg_regs = pinmux_config_regs,
.data_regs = pinmux_data_regs,
.gpio_data = pinmux_data,
.gpio_data_size = ARRAY_SIZE(pinmux_data),
};
static int __init plat_pinmux_setup(void)
{
return register_pinmux(&sh7786_pinmux_info);
}
arch_initcall(plat_pinmux_setup);
| gpl-2.0 |
wkhtmltopdf/qtwebkit | Source/WebCore/loader/icon/IconDatabase.cpp | 115 | 92999 | /*
* Copyright (C) 2006, 2007, 2008, 2009, 2011 Apple Inc. All rights reserved.
* Copyright (C) 2007 Justin Haygood (jhaygood@reaktix.com)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "IconDatabase.h"
#if ENABLE(ICONDATABASE)
#include "DocumentLoader.h"
#include "FileSystem.h"
#include "IconDatabaseClient.h"
#include "IconRecord.h"
#include "Image.h"
#include "IntSize.h"
#include "Logging.h"
#include "SQLiteStatement.h"
#include "SQLiteTransaction.h"
#include "SuddenTermination.h"
#include <wtf/AutodrainedPool.h>
#include <wtf/CurrentTime.h>
#include <wtf/MainThread.h>
#include <wtf/StdLibExtras.h>
#include <wtf/text/CString.h>
// For methods that are meant to support API from the main thread - should not be called internally
#define ASSERT_NOT_SYNC_THREAD() ASSERT(!m_syncThreadRunning || !IS_ICON_SYNC_THREAD())
// For methods that are meant to support the sync thread ONLY
#define IS_ICON_SYNC_THREAD() (m_syncThread == currentThread())
#define ASSERT_ICON_SYNC_THREAD() ASSERT(IS_ICON_SYNC_THREAD())
#if PLATFORM(QT) || PLATFORM(GTK)
#define CAN_THEME_URL_ICON
#endif
namespace WebCore {
static int databaseCleanupCounter = 0;
// This version number is in the DB and marks the current generation of the schema
// Currently, a mismatched schema causes the DB to be wiped and reset. This isn't
// so bad during development but in the future, we would need to write a conversion
// function to advance older released schemas to "current"
static const int currentDatabaseVersion = 6;
// Icons expire once every 4 days
static const int iconExpirationTime = 60*60*24*4;
static const int updateTimerDelay = 5;
static bool checkIntegrityOnOpen = false;
#if PLATFORM(GTK)
// We are not interested in icons that have been unused for more than
// 30 days, delete them even if they have not been explicitly released.
static const int notUsedIconExpirationTime = 60*60*24*30;
#endif
#if !LOG_DISABLED || !ERROR_DISABLED
static String urlForLogging(const String& url)
{
static unsigned urlTruncationLength = 120;
if (url.length() < urlTruncationLength)
return url;
return url.substring(0, urlTruncationLength) + "...";
}
#endif
class DefaultIconDatabaseClient : public IconDatabaseClient {
WTF_MAKE_FAST_ALLOCATED;
public:
virtual void didImportIconURLForPageURL(const String&) { }
virtual void didImportIconDataForPageURL(const String&) { }
virtual void didChangeIconForPageURL(const String&) { }
virtual void didRemoveAllIcons() { }
virtual void didFinishURLImport() { }
};
static IconDatabaseClient* defaultClient()
{
static IconDatabaseClient* defaultClient = new DefaultIconDatabaseClient();
return defaultClient;
}
// ************************
// *** Main Thread Only ***
// ************************
void IconDatabase::setClient(IconDatabaseClient* client)
{
// We don't allow a null client, because we never null check it anywhere in this code
// Also don't allow a client change after the thread has already began
// (setting the client should occur before the database is opened)
ASSERT(client);
ASSERT(!m_syncThreadRunning);
if (!client || m_syncThreadRunning)
return;
m_client = client;
}
bool IconDatabase::open(const String& directory, const String& filename)
{
ASSERT_NOT_SYNC_THREAD();
if (!m_isEnabled)
return false;
if (isOpen()) {
LOG_ERROR("Attempt to reopen the IconDatabase which is already open. Must close it first.");
return false;
}
m_databaseDirectory = directory.isolatedCopy();
// Formulate the full path for the database file
m_completeDatabasePath = pathByAppendingComponent(m_databaseDirectory, filename);
// Lock here as well as first thing in the thread so the thread doesn't actually commence until the createThread() call
// completes and m_syncThreadRunning is properly set
m_syncLock.lock();
m_syncThread = createThread(IconDatabase::iconDatabaseSyncThreadStart, this, "WebCore: IconDatabase");
m_syncThreadRunning = m_syncThread;
m_syncLock.unlock();
if (!m_syncThread)
return false;
return true;
}
void IconDatabase::close()
{
ASSERT_NOT_SYNC_THREAD();
if (m_syncThreadRunning) {
// Set the flag to tell the sync thread to wrap it up
m_threadTerminationRequested = true;
// Wake up the sync thread if it's waiting
wakeSyncThread();
// Wait for the sync thread to terminate
waitForThreadCompletion(m_syncThread);
}
m_syncThreadRunning = false;
m_threadTerminationRequested = false;
m_removeIconsRequested = false;
m_syncDB.close();
ASSERT(!isOpen());
}
void IconDatabase::removeAllIcons()
{
ASSERT_NOT_SYNC_THREAD();
if (!isOpen())
return;
LOG(IconDatabase, "Requesting background thread to remove all icons");
// Clear the in-memory record of every IconRecord, anything waiting to be read from disk, and anything waiting to be written to disk
{
MutexLocker locker(m_urlAndIconLock);
// Clear the IconRecords for every page URL - RefCounting will cause the IconRecords themselves to be deleted
// We don't delete the actual PageRecords because we have the "retain icon for url" count to keep track of
HashMap<String, PageURLRecord*>::iterator iter = m_pageURLToRecordMap.begin();
HashMap<String, PageURLRecord*>::iterator end = m_pageURLToRecordMap.end();
for (; iter != end; ++iter)
(*iter).value->setIconRecord(0);
// Clear the iconURL -> IconRecord map
m_iconURLToRecordMap.clear();
// Clear all in-memory records of things that need to be synced out to disk
{
MutexLocker locker(m_pendingSyncLock);
m_pageURLsPendingSync.clear();
m_iconsPendingSync.clear();
}
// Clear all in-memory records of things that need to be read in from disk
{
MutexLocker locker(m_pendingReadingLock);
m_pageURLsPendingImport.clear();
m_pageURLsInterestedInIcons.clear();
m_iconsPendingReading.clear();
m_loadersPendingDecision.clear();
}
}
m_removeIconsRequested = true;
wakeSyncThread();
}
Image* IconDatabase::synchronousIconForPageURL(const String& pageURLOriginal, const IntSize& size)
{
ASSERT_NOT_SYNC_THREAD();
// pageURLOriginal cannot be stored without being deep copied first.
// We should go our of our way to only copy it if we have to store it
if (!isOpen() || !documentCanHaveIcon(pageURLOriginal))
return 0;
MutexLocker locker(m_urlAndIconLock);
performPendingRetainAndReleaseOperations();
String pageURLCopy; // Creates a null string for easy testing
PageURLRecord* pageRecord = m_pageURLToRecordMap.get(pageURLOriginal);
if (!pageRecord) {
pageURLCopy = pageURLOriginal.isolatedCopy();
pageRecord = getOrCreatePageURLRecord(pageURLCopy);
}
// If pageRecord is NULL, one of two things is true -
// 1 - The initial url import is incomplete and this pageURL was marked to be notified once it is complete if an iconURL exists
// 2 - The initial url import IS complete and this pageURL has no icon
if (!pageRecord) {
MutexLocker locker(m_pendingReadingLock);
// Import is ongoing, there might be an icon. In this case, register to be notified when the icon comes in
// If we ever reach this condition, we know we've already made the pageURL copy
if (!m_iconURLImportComplete)
m_pageURLsInterestedInIcons.add(pageURLCopy);
return 0;
}
IconRecord* iconRecord = pageRecord->iconRecord();
// If the initial URL import isn't complete, it's possible to have a PageURL record without an associated icon
// In this case, the pageURL is already in the set to alert the client when the iconURL mapping is complete so
// we can just bail now
if (!m_iconURLImportComplete && !iconRecord)
return 0;
// The only way we should *not* have an icon record is if this pageURL is retained but has no icon yet - make sure of that
ASSERT(iconRecord || m_retainedPageURLs.contains(pageURLOriginal));
if (!iconRecord)
return 0;
// If it's a new IconRecord object that doesn't have its imageData set yet,
// mark it to be read by the background thread
if (iconRecord->imageDataStatus() == ImageDataStatusUnknown) {
if (pageURLCopy.isNull())
pageURLCopy = pageURLOriginal.isolatedCopy();
MutexLocker locker(m_pendingReadingLock);
m_pageURLsInterestedInIcons.add(pageURLCopy);
m_iconsPendingReading.add(iconRecord);
wakeSyncThread();
return 0;
}
// If the size parameter was (0, 0) that means the caller of this method just wanted the read from disk to be kicked off
// and isn't actually interested in the image return value
if (size == IntSize(0, 0))
return 0;
// PARANOID DISCUSSION: This method makes some assumptions. It returns a WebCore::image which the icon database might dispose of at anytime in the future,
// and Images aren't ref counted. So there is no way for the client to guarantee continued existence of the image.
// This has *always* been the case, but in practice clients would always create some other platform specific representation of the image
// and drop the raw Image*. On Mac an NSImage, and on windows drawing into an HBITMAP.
// The async aspect adds a huge question - what if the image is deleted before the platform specific API has a chance to create its own
// representation out of it?
// If an image is read in from the icondatabase, we do *not* overwrite any image data that exists in the in-memory cache.
// This is because we make the assumption that anything in memory is newer than whatever is in the database.
// So the only time the data will be set from the second thread is when it is INITIALLY being read in from the database, but we would never
// delete the image on the secondary thread if the image already exists.
return iconRecord->image(size);
}
PassNativeImagePtr IconDatabase::synchronousNativeIconForPageURL(const String& pageURLOriginal, const IntSize& size)
{
Image* icon = synchronousIconForPageURL(pageURLOriginal, size);
if (!icon)
return 0;
MutexLocker locker(m_urlAndIconLock);
return icon->nativeImageForCurrentFrame();
}
void IconDatabase::readIconForPageURLFromDisk(const String& pageURL)
{
// The effect of asking for an Icon for a pageURL automatically queues it to be read from disk
// if it hasn't already been set in memory. The special IntSize (0, 0) is a special way of telling
// that method "I don't care about the actual Image, i just want you to make sure you're getting it from disk.
synchronousIconForPageURL(pageURL, IntSize(0, 0));
}
String IconDatabase::synchronousIconURLForPageURL(const String& pageURLOriginal)
{
ASSERT_NOT_SYNC_THREAD();
// Cannot do anything with pageURLOriginal that would end up storing it without deep copying first
// Also, in the case we have a real answer for the caller, we must deep copy that as well
if (!isOpen() || !documentCanHaveIcon(pageURLOriginal))
return String();
MutexLocker locker(m_urlAndIconLock);
PageURLRecord* pageRecord = m_pageURLToRecordMap.get(pageURLOriginal);
if (!pageRecord)
pageRecord = getOrCreatePageURLRecord(pageURLOriginal.isolatedCopy());
// If pageRecord is NULL, one of two things is true -
// 1 - The initial url import is incomplete and this pageURL has already been marked to be notified once it is complete if an iconURL exists
// 2 - The initial url import IS complete and this pageURL has no icon
if (!pageRecord)
return String();
// Possible the pageRecord is around because it's a retained pageURL with no iconURL, so we have to check
return pageRecord->iconRecord() ? pageRecord->iconRecord()->iconURL().isolatedCopy() : String();
}
#ifdef CAN_THEME_URL_ICON
static inline void loadDefaultIconRecord(IconRecord* defaultIconRecord)
{
defaultIconRecord->loadImageFromResource("urlIcon");
}
#else
static inline void loadDefaultIconRecord(IconRecord* defaultIconRecord)
{
static const unsigned char defaultIconData[] = { 0x4D, 0x4D, 0x00, 0x2A, 0x00, 0x00, 0x03, 0x32, 0x80, 0x00, 0x20, 0x50, 0x38, 0x24, 0x16, 0x0D, 0x07, 0x84, 0x42, 0x61, 0x50, 0xB8,
0x64, 0x08, 0x18, 0x0D, 0x0A, 0x0B, 0x84, 0xA2, 0xA1, 0xE2, 0x08, 0x5E, 0x39, 0x28, 0xAF, 0x48, 0x24, 0xD3, 0x53, 0x9A, 0x37, 0x1D, 0x18, 0x0E, 0x8A, 0x4B, 0xD1, 0x38,
0xB0, 0x7C, 0x82, 0x07, 0x03, 0x82, 0xA2, 0xE8, 0x6C, 0x2C, 0x03, 0x2F, 0x02, 0x82, 0x41, 0xA1, 0xE2, 0xF8, 0xC8, 0x84, 0x68, 0x6D, 0x1C, 0x11, 0x0A, 0xB7, 0xFA, 0x91,
0x6E, 0xD1, 0x7F, 0xAF, 0x9A, 0x4E, 0x87, 0xFB, 0x19, 0xB0, 0xEA, 0x7F, 0xA4, 0x95, 0x8C, 0xB7, 0xF9, 0xA9, 0x0A, 0xA9, 0x7F, 0x8C, 0x88, 0x66, 0x96, 0xD4, 0xCA, 0x69,
0x2F, 0x00, 0x81, 0x65, 0xB0, 0x29, 0x90, 0x7C, 0xBA, 0x2B, 0x21, 0x1E, 0x5C, 0xE6, 0xB4, 0xBD, 0x31, 0xB6, 0xE7, 0x7A, 0xBF, 0xDD, 0x6F, 0x37, 0xD3, 0xFD, 0xD8, 0xF2,
0xB6, 0xDB, 0xED, 0xAC, 0xF7, 0x03, 0xC5, 0xFE, 0x77, 0x53, 0xB6, 0x1F, 0xE6, 0x24, 0x8B, 0x1D, 0xFE, 0x26, 0x20, 0x9E, 0x1C, 0xE0, 0x80, 0x65, 0x7A, 0x18, 0x02, 0x01,
0x82, 0xC5, 0xA0, 0xC0, 0xF1, 0x89, 0xBA, 0x23, 0x30, 0xAD, 0x1F, 0xE7, 0xE5, 0x5B, 0x6D, 0xFE, 0xE7, 0x78, 0x3E, 0x1F, 0xEE, 0x97, 0x8B, 0xE7, 0x37, 0x9D, 0xCF, 0xE7,
0x92, 0x8B, 0x87, 0x0B, 0xFC, 0xA0, 0x8E, 0x68, 0x3F, 0xC6, 0x27, 0xA6, 0x33, 0xFC, 0x36, 0x5B, 0x59, 0x3F, 0xC1, 0x02, 0x63, 0x3B, 0x74, 0x00, 0x03, 0x07, 0x0B, 0x61,
0x00, 0x20, 0x60, 0xC9, 0x08, 0x00, 0x1C, 0x25, 0x9F, 0xE0, 0x12, 0x8A, 0xD5, 0xFE, 0x6B, 0x4F, 0x35, 0x9F, 0xED, 0xD7, 0x4B, 0xD9, 0xFE, 0x8A, 0x59, 0xB8, 0x1F, 0xEC,
0x56, 0xD3, 0xC1, 0xFE, 0x63, 0x4D, 0xF2, 0x83, 0xC6, 0xB6, 0x1B, 0xFC, 0x34, 0x68, 0x61, 0x3F, 0xC1, 0xA6, 0x25, 0xEB, 0xFC, 0x06, 0x58, 0x5C, 0x3F, 0xC0, 0x03, 0xE4,
0xC3, 0xFC, 0x04, 0x0F, 0x1A, 0x6F, 0xE0, 0xE0, 0x20, 0xF9, 0x61, 0x7A, 0x02, 0x28, 0x2B, 0xBC, 0x46, 0x25, 0xF3, 0xFC, 0x66, 0x3D, 0x99, 0x27, 0xF9, 0x7E, 0x6B, 0x1D,
0xC7, 0xF9, 0x2C, 0x5E, 0x1C, 0x87, 0xF8, 0xC0, 0x4D, 0x9A, 0xE7, 0xF8, 0xDA, 0x51, 0xB2, 0xC1, 0x68, 0xF2, 0x64, 0x1F, 0xE1, 0x50, 0xED, 0x0A, 0x04, 0x23, 0x79, 0x8A,
0x7F, 0x82, 0xA3, 0x39, 0x80, 0x7F, 0x80, 0xC2, 0xB1, 0x5E, 0xF7, 0x04, 0x2F, 0xB2, 0x10, 0x02, 0x86, 0x63, 0xC9, 0xCC, 0x07, 0xBF, 0x87, 0xF8, 0x4A, 0x38, 0xAF, 0xC1,
0x88, 0xF8, 0x66, 0x1F, 0xE1, 0xD9, 0x08, 0xD4, 0x8F, 0x25, 0x5B, 0x4A, 0x49, 0x97, 0x87, 0x39, 0xFE, 0x25, 0x12, 0x10, 0x68, 0xAA, 0x4A, 0x2F, 0x42, 0x29, 0x12, 0x69,
0x9F, 0xE1, 0xC1, 0x00, 0x67, 0x1F, 0xE1, 0x58, 0xED, 0x00, 0x83, 0x23, 0x49, 0x82, 0x7F, 0x81, 0x21, 0xE0, 0xFC, 0x73, 0x21, 0x00, 0x50, 0x7D, 0x2B, 0x84, 0x03, 0x83,
0xC2, 0x1B, 0x90, 0x06, 0x69, 0xFE, 0x23, 0x91, 0xAE, 0x50, 0x9A, 0x49, 0x32, 0xC2, 0x89, 0x30, 0xE9, 0x0A, 0xC4, 0xD9, 0xC4, 0x7F, 0x94, 0xA6, 0x51, 0xDE, 0x7F, 0x9D,
0x07, 0x89, 0xF6, 0x7F, 0x91, 0x85, 0xCA, 0x88, 0x25, 0x11, 0xEE, 0x50, 0x7C, 0x43, 0x35, 0x21, 0x60, 0xF1, 0x0D, 0x82, 0x62, 0x39, 0x07, 0x2C, 0x20, 0xE0, 0x80, 0x72,
0x34, 0x17, 0xA1, 0x80, 0xEE, 0xF0, 0x89, 0x24, 0x74, 0x1A, 0x2C, 0x93, 0xB3, 0x78, 0xCC, 0x52, 0x9D, 0x6A, 0x69, 0x56, 0xBB, 0x0D, 0x85, 0x69, 0xE6, 0x7F, 0x9E, 0x27,
0xB9, 0xFD, 0x50, 0x54, 0x47, 0xF9, 0xCC, 0x78, 0x9F, 0x87, 0xF9, 0x98, 0x70, 0xB9, 0xC2, 0x91, 0x2C, 0x6D, 0x1F, 0xE1, 0xE1, 0x00, 0xBF, 0x02, 0xC1, 0xF5, 0x18, 0x84,
0x01, 0xE1, 0x48, 0x8C, 0x42, 0x07, 0x43, 0xC9, 0x76, 0x7F, 0x8B, 0x04, 0xE4, 0xDE, 0x35, 0x95, 0xAB, 0xB0, 0xF0, 0x5C, 0x55, 0x23, 0xF9, 0x7E, 0x7E, 0x9F, 0xE4, 0x0C,
0xA7, 0x55, 0x47, 0xC7, 0xF9, 0xE6, 0xCF, 0x1F, 0xE7, 0x93, 0x35, 0x52, 0x54, 0x63, 0x19, 0x46, 0x73, 0x1F, 0xE2, 0x61, 0x08, 0xF0, 0x82, 0xE1, 0x80, 0x92, 0xF9, 0x20,
0xC0, 0x28, 0x18, 0x0A, 0x05, 0xA1, 0xA2, 0xF8, 0x6E, 0xDB, 0x47, 0x49, 0xFE, 0x3E, 0x17, 0xB6, 0x61, 0x13, 0x1A, 0x29, 0x26, 0xA9, 0xFE, 0x7F, 0x92, 0x70, 0x69, 0xFE,
0x4C, 0x2F, 0x55, 0x01, 0xF1, 0x54, 0xD4, 0x35, 0x49, 0x4A, 0x69, 0x59, 0x83, 0x81, 0x58, 0x76, 0x9F, 0xE2, 0x20, 0xD6, 0x4C, 0x9B, 0xA0, 0x48, 0x1E, 0x0B, 0xB7, 0x48,
0x58, 0x26, 0x11, 0x06, 0x42, 0xE8, 0xA4, 0x40, 0x17, 0x27, 0x39, 0x00, 0x60, 0x2D, 0xA4, 0xC3, 0x2C, 0x7F, 0x94, 0x56, 0xE4, 0xE1, 0x77, 0x1F, 0xE5, 0xB9, 0xD7, 0x66,
0x1E, 0x07, 0xB3, 0x3C, 0x63, 0x1D, 0x35, 0x49, 0x0E, 0x63, 0x2D, 0xA2, 0xF1, 0x12, 0x60, 0x1C, 0xE0, 0xE0, 0x52, 0x1B, 0x8B, 0xAC, 0x38, 0x0E, 0x07, 0x03, 0x60, 0x28,
0x1C, 0x0E, 0x87, 0x00, 0xF0, 0x66, 0x27, 0x11, 0xA2, 0xC1, 0x02, 0x5A, 0x1C, 0xE4, 0x21, 0x83, 0x1F, 0x13, 0x86, 0xFA, 0xD2, 0x55, 0x1D, 0xD6, 0x61, 0xBC, 0x77, 0xD3,
0xE6, 0x91, 0xCB, 0x4C, 0x90, 0xA6, 0x25, 0xB8, 0x2F, 0x90, 0xC5, 0xA9, 0xCE, 0x12, 0x07, 0x02, 0x91, 0x1B, 0x9F, 0x68, 0x00, 0x16, 0x76, 0x0D, 0xA1, 0x00, 0x08, 0x06,
0x03, 0x81, 0xA0, 0x20, 0x1A, 0x0D, 0x06, 0x80, 0x30, 0x24, 0x12, 0x89, 0x20, 0x98, 0x4A, 0x1F, 0x0F, 0x21, 0xA0, 0x9E, 0x36, 0x16, 0xC2, 0x88, 0xE6, 0x48, 0x9B, 0x83,
0x31, 0x1C, 0x55, 0x1E, 0x43, 0x59, 0x1A, 0x56, 0x1E, 0x42, 0xF0, 0xFA, 0x4D, 0x1B, 0x9B, 0x08, 0xDC, 0x5B, 0x02, 0xA1, 0x30, 0x7E, 0x3C, 0xEE, 0x5B, 0xA6, 0xDD, 0xB8,
0x6D, 0x5B, 0x62, 0xB7, 0xCD, 0xF3, 0x9C, 0xEA, 0x04, 0x80, 0x80, 0x00, 0x00, 0x0E, 0x01, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x10, 0x00, 0x00, 0x01, 0x01,
0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x10, 0x00, 0x00, 0x01, 0x02, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x03, 0xE0, 0x01, 0x03, 0x00, 0x03, 0x00, 0x00,
0x00, 0x01, 0x00, 0x05, 0x00, 0x00, 0x01, 0x06, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00, 0x01, 0x11, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
0x00, 0x08, 0x01, 0x15, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x00, 0x00, 0x01, 0x16, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x02, 0x00, 0x01, 0x17,
0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x03, 0x29, 0x01, 0x1A, 0x00, 0x05, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x03, 0xE8, 0x01, 0x1B, 0x00, 0x05, 0x00, 0x00,
0x00, 0x01, 0x00, 0x00, 0x03, 0xF0, 0x01, 0x1C, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x01, 0x28, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02,
0x00, 0x00, 0x01, 0x52, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x08, 0x00, 0x08, 0x00, 0x08, 0x00, 0x0A,
0xFC, 0x80, 0x00, 0x00, 0x27, 0x10, 0x00, 0x0A, 0xFC, 0x80, 0x00, 0x00, 0x27, 0x10 };
DEFINE_STATIC_LOCAL(RefPtr<SharedBuffer>, defaultIconBuffer, (SharedBuffer::create(defaultIconData, sizeof(defaultIconData))));
defaultIconRecord->setImageData(defaultIconBuffer);
}
#endif
Image* IconDatabase::defaultIcon(const IntSize& size)
{
ASSERT_NOT_SYNC_THREAD();
if (!m_defaultIconRecord) {
m_defaultIconRecord = IconRecord::create("urlIcon");
m_defaultIconRecord->setMutexForVerifier(m_urlAndIconLock);
loadDefaultIconRecord(m_defaultIconRecord.get());
}
return m_defaultIconRecord->image(size);
}
void IconDatabase::retainIconForPageURL(const String& pageURL)
{
ASSERT_NOT_SYNC_THREAD();
if (!isEnabled() || !documentCanHaveIcon(pageURL))
return;
{
MutexLocker locker(m_urlsToRetainOrReleaseLock);
m_urlsToRetain.add(pageURL.isolatedCopy());
m_retainOrReleaseIconRequested = true;
}
scheduleOrDeferSyncTimer();
}
void IconDatabase::performRetainIconForPageURL(const String& pageURLOriginal, int retainCount)
{
PageURLRecord* record = m_pageURLToRecordMap.get(pageURLOriginal);
String pageURL;
if (!record) {
pageURL = pageURLOriginal.isolatedCopy();
record = new PageURLRecord(pageURL);
m_pageURLToRecordMap.set(pageURL, record);
}
if (!record->retain(retainCount)) {
if (pageURL.isNull())
pageURL = pageURLOriginal.isolatedCopy();
// This page just had its retain count bumped from 0 to 1 - Record that fact
m_retainedPageURLs.add(pageURL);
// If we read the iconURLs yet, we want to avoid any pageURL->iconURL lookups and the pageURLsPendingDeletion is moot,
// so we bail here and skip those steps
if (!m_iconURLImportComplete)
return;
MutexLocker locker(m_pendingSyncLock);
// If this pageURL waiting to be sync'ed, update the sync record
// This saves us in the case where a page was ready to be deleted from the database but was just retained - so theres no need to delete it!
if (!m_privateBrowsingEnabled && m_pageURLsPendingSync.contains(pageURL)) {
LOG(IconDatabase, "Bringing %s back from the brink", pageURL.ascii().data());
m_pageURLsPendingSync.set(pageURL, record->snapshot());
}
}
}
void IconDatabase::releaseIconForPageURL(const String& pageURL)
{
ASSERT_NOT_SYNC_THREAD();
// Cannot do anything with pageURLOriginal that would end up storing it without deep copying first
if (!isEnabled() || !documentCanHaveIcon(pageURL))
return;
{
MutexLocker locker(m_urlsToRetainOrReleaseLock);
m_urlsToRelease.add(pageURL.isolatedCopy());
m_retainOrReleaseIconRequested = true;
}
scheduleOrDeferSyncTimer();
}
void IconDatabase::performReleaseIconForPageURL(const String& pageURLOriginal, int releaseCount)
{
// Check if this pageURL is actually retained
if (!m_retainedPageURLs.contains(pageURLOriginal)) {
LOG_ERROR("Attempting to release icon for URL %s which is not retained", urlForLogging(pageURLOriginal).ascii().data());
return;
}
// Get its retain count - if it's retained, we'd better have a PageURLRecord for it
PageURLRecord* pageRecord = m_pageURLToRecordMap.get(pageURLOriginal);
ASSERT(pageRecord);
LOG(IconDatabase, "Releasing pageURL %s to a retain count of %i", urlForLogging(pageURLOriginal).ascii().data(), pageRecord->retainCount() - 1);
ASSERT(pageRecord->retainCount() > 0);
// If it still has a positive retain count, store the new count and bail
if (pageRecord->release(releaseCount))
return;
// This pageRecord has now been fully released. Do the appropriate cleanup
LOG(IconDatabase, "No more retainers for PageURL %s", urlForLogging(pageURLOriginal).ascii().data());
m_pageURLToRecordMap.remove(pageURLOriginal);
m_retainedPageURLs.remove(pageURLOriginal);
// Grab the iconRecord for later use (and do a sanity check on it for kicks)
IconRecord* iconRecord = pageRecord->iconRecord();
ASSERT(!iconRecord || (iconRecord && m_iconURLToRecordMap.get(iconRecord->iconURL()) == iconRecord));
{
MutexLocker locker(m_pendingReadingLock);
// Since this pageURL is going away, there's no reason anyone would ever be interested in its read results
if (!m_iconURLImportComplete)
m_pageURLsPendingImport.remove(pageURLOriginal);
m_pageURLsInterestedInIcons.remove(pageURLOriginal);
// If this icon is down to it's last retainer, we don't care about reading it in from disk anymore
if (iconRecord && iconRecord->hasOneRef()) {
m_iconURLToRecordMap.remove(iconRecord->iconURL());
m_iconsPendingReading.remove(iconRecord);
}
}
// Mark stuff for deletion from the database only if we're not in private browsing
if (!m_privateBrowsingEnabled) {
MutexLocker locker(m_pendingSyncLock);
m_pageURLsPendingSync.set(pageURLOriginal.isolatedCopy(), pageRecord->snapshot(true));
// If this page is the last page to refer to a particular IconRecord, that IconRecord needs to
// be marked for deletion
if (iconRecord && iconRecord->hasOneRef())
m_iconsPendingSync.set(iconRecord->iconURL(), iconRecord->snapshot(true));
}
delete pageRecord;
}
void IconDatabase::setIconDataForIconURL(PassRefPtr<SharedBuffer> dataOriginal, const String& iconURLOriginal)
{
ASSERT_NOT_SYNC_THREAD();
// Cannot do anything with dataOriginal or iconURLOriginal that would end up storing them without deep copying first
if (!isOpen() || iconURLOriginal.isEmpty())
return;
RefPtr<SharedBuffer> data = dataOriginal ? dataOriginal->copy() : PassRefPtr<SharedBuffer>(0);
if (data)
data->setMutexForVerifier(m_urlAndIconLock);
String iconURL = iconURLOriginal.isolatedCopy();
Vector<String> pageURLs;
{
MutexLocker locker(m_urlAndIconLock);
// If this icon was pending a read, remove it from that set because this new data should override what is on disk
RefPtr<IconRecord> icon = m_iconURLToRecordMap.get(iconURL);
if (icon) {
MutexLocker locker(m_pendingReadingLock);
m_iconsPendingReading.remove(icon.get());
} else
icon = getOrCreateIconRecord(iconURL);
// Update the data and set the time stamp
icon->setImageData(data.release());
icon->setTimestamp((int)currentTime());
// Copy the current retaining pageURLs - if any - to notify them of the change
pageURLs.appendRange(icon->retainingPageURLs().begin(), icon->retainingPageURLs().end());
// Mark the IconRecord as requiring an update to the database only if private browsing is disabled
if (!m_privateBrowsingEnabled) {
MutexLocker locker(m_pendingSyncLock);
m_iconsPendingSync.set(iconURL, icon->snapshot());
}
if (icon->hasOneRef()) {
ASSERT(icon->retainingPageURLs().isEmpty());
LOG(IconDatabase, "Icon for icon url %s is about to be destroyed - removing mapping for it", urlForLogging(icon->iconURL()).ascii().data());
m_iconURLToRecordMap.remove(icon->iconURL());
}
}
// Send notification out regarding all PageURLs that retain this icon
// But not if we're on the sync thread because that implies this mapping
// comes from the initial import which we don't want notifications for
if (!IS_ICON_SYNC_THREAD()) {
// Start the timer to commit this change - or further delay the timer if it was already started
scheduleOrDeferSyncTimer();
for (unsigned i = 0; i < pageURLs.size(); ++i) {
AutodrainedPool pool;
LOG(IconDatabase, "Dispatching notification that retaining pageURL %s has a new icon", urlForLogging(pageURLs[i]).ascii().data());
m_client->didChangeIconForPageURL(pageURLs[i]);
}
}
}
void IconDatabase::setIconURLForPageURL(const String& iconURLOriginal, const String& pageURLOriginal)
{
ASSERT_NOT_SYNC_THREAD();
// Cannot do anything with iconURLOriginal or pageURLOriginal that would end up storing them without deep copying first
ASSERT(!iconURLOriginal.isEmpty());
if (!isOpen() || !documentCanHaveIcon(pageURLOriginal))
return;
String iconURL, pageURL;
{
MutexLocker locker(m_urlAndIconLock);
PageURLRecord* pageRecord = m_pageURLToRecordMap.get(pageURLOriginal);
// If the urls already map to each other, bail.
// This happens surprisingly often, and seems to cream iBench performance
if (pageRecord && pageRecord->iconRecord() && pageRecord->iconRecord()->iconURL() == iconURLOriginal)
return;
pageURL = pageURLOriginal.isolatedCopy();
iconURL = iconURLOriginal.isolatedCopy();
if (!pageRecord) {
pageRecord = new PageURLRecord(pageURL);
m_pageURLToRecordMap.set(pageURL, pageRecord);
}
RefPtr<IconRecord> iconRecord = pageRecord->iconRecord();
// Otherwise, set the new icon record for this page
pageRecord->setIconRecord(getOrCreateIconRecord(iconURL));
// If the current icon has only a single ref left, it is about to get wiped out.
// Remove it from the in-memory records and don't bother reading it in from disk anymore
if (iconRecord && iconRecord->hasOneRef()) {
ASSERT(iconRecord->retainingPageURLs().size() == 0);
LOG(IconDatabase, "Icon for icon url %s is about to be destroyed - removing mapping for it", urlForLogging(iconRecord->iconURL()).ascii().data());
m_iconURLToRecordMap.remove(iconRecord->iconURL());
MutexLocker locker(m_pendingReadingLock);
m_iconsPendingReading.remove(iconRecord.get());
}
// And mark this mapping to be added to the database
if (!m_privateBrowsingEnabled) {
MutexLocker locker(m_pendingSyncLock);
m_pageURLsPendingSync.set(pageURL, pageRecord->snapshot());
// If the icon is on its last ref, mark it for deletion
if (iconRecord && iconRecord->hasOneRef())
m_iconsPendingSync.set(iconRecord->iconURL(), iconRecord->snapshot(true));
}
}
// Since this mapping is new, send the notification out - but not if we're on the sync thread because that implies this mapping
// comes from the initial import which we don't want notifications for
if (!IS_ICON_SYNC_THREAD()) {
// Start the timer to commit this change - or further delay the timer if it was already started
scheduleOrDeferSyncTimer();
LOG(IconDatabase, "Dispatching notification that we changed an icon mapping for url %s", urlForLogging(pageURL).ascii().data());
AutodrainedPool pool;
m_client->didChangeIconForPageURL(pageURL);
}
}
IconLoadDecision IconDatabase::synchronousLoadDecisionForIconURL(const String& iconURL, DocumentLoader* notificationDocumentLoader)
{
ASSERT_NOT_SYNC_THREAD();
if (!isOpen() || iconURL.isEmpty())
return IconLoadNo;
// If we have a IconRecord, it should also have its timeStamp marked because there is only two times when we create the IconRecord:
// 1 - When we read the icon urls from disk, getting the timeStamp at the same time
// 2 - When we get a new icon from the loader, in which case the timestamp is set at that time
{
MutexLocker locker(m_urlAndIconLock);
if (IconRecord* icon = m_iconURLToRecordMap.get(iconURL)) {
LOG(IconDatabase, "Found expiration time on a present icon based on existing IconRecord");
return static_cast<int>(currentTime()) - static_cast<int>(icon->getTimestamp()) > iconExpirationTime ? IconLoadYes : IconLoadNo;
}
}
// If we don't have a record for it, but we *have* imported all iconURLs from disk, then we should load it now
MutexLocker readingLocker(m_pendingReadingLock);
if (m_iconURLImportComplete)
return IconLoadYes;
// Otherwise - since we refuse to perform I/O on the main thread to find out for sure - we return the answer that says
// "You might be asked to load this later, so flag that"
LOG(IconDatabase, "Don't know if we should load %s or not - adding %p to the set of document loaders waiting on a decision", iconURL.ascii().data(), notificationDocumentLoader);
if (notificationDocumentLoader)
m_loadersPendingDecision.add(notificationDocumentLoader);
return IconLoadUnknown;
}
bool IconDatabase::synchronousIconDataKnownForIconURL(const String& iconURL)
{
ASSERT_NOT_SYNC_THREAD();
MutexLocker locker(m_urlAndIconLock);
if (IconRecord* icon = m_iconURLToRecordMap.get(iconURL))
return icon->imageDataStatus() != ImageDataStatusUnknown;
return false;
}
void IconDatabase::setEnabled(bool enabled)
{
ASSERT_NOT_SYNC_THREAD();
if (!enabled && isOpen())
close();
m_isEnabled = enabled;
}
bool IconDatabase::isEnabled() const
{
ASSERT_NOT_SYNC_THREAD();
return m_isEnabled;
}
void IconDatabase::setPrivateBrowsingEnabled(bool flag)
{
m_privateBrowsingEnabled = flag;
}
bool IconDatabase::isPrivateBrowsingEnabled() const
{
return m_privateBrowsingEnabled;
}
void IconDatabase::delayDatabaseCleanup()
{
++databaseCleanupCounter;
if (databaseCleanupCounter == 1)
LOG(IconDatabase, "Database cleanup is now DISABLED");
}
void IconDatabase::allowDatabaseCleanup()
{
if (--databaseCleanupCounter < 0)
databaseCleanupCounter = 0;
if (databaseCleanupCounter == 0)
LOG(IconDatabase, "Database cleanup is now ENABLED");
}
void IconDatabase::checkIntegrityBeforeOpening()
{
checkIntegrityOnOpen = true;
}
size_t IconDatabase::pageURLMappingCount()
{
MutexLocker locker(m_urlAndIconLock);
return m_pageURLToRecordMap.size();
}
size_t IconDatabase::retainedPageURLCount()
{
MutexLocker locker(m_urlAndIconLock);
performPendingRetainAndReleaseOperations();
return m_retainedPageURLs.size();
}
size_t IconDatabase::iconRecordCount()
{
MutexLocker locker(m_urlAndIconLock);
return m_iconURLToRecordMap.size();
}
size_t IconDatabase::iconRecordCountWithData()
{
MutexLocker locker(m_urlAndIconLock);
size_t result = 0;
HashMap<String, IconRecord*>::iterator i = m_iconURLToRecordMap.begin();
HashMap<String, IconRecord*>::iterator end = m_iconURLToRecordMap.end();
for (; i != end; ++i)
result += ((*i).value->imageDataStatus() == ImageDataStatusPresent);
return result;
}
IconDatabase::IconDatabase()
: m_syncTimer(this, &IconDatabase::syncTimerFired)
, m_syncThreadRunning(false)
, m_scheduleOrDeferSyncTimerRequested(false)
, m_isEnabled(false)
, m_privateBrowsingEnabled(false)
, m_threadTerminationRequested(false)
, m_removeIconsRequested(false)
, m_iconURLImportComplete(false)
, m_syncThreadHasWorkToDo(false)
, m_disabledSuddenTerminationForSyncThread(false)
, m_retainOrReleaseIconRequested(false)
, m_initialPruningComplete(false)
, m_client(defaultClient())
{
LOG(IconDatabase, "Creating IconDatabase %p", this);
ASSERT(isMainThread());
}
IconDatabase::~IconDatabase()
{
ASSERT(!isOpen());
}
void IconDatabase::notifyPendingLoadDecisionsOnMainThread(void* context)
{
static_cast<IconDatabase*>(context)->notifyPendingLoadDecisions();
}
void IconDatabase::notifyPendingLoadDecisions()
{
ASSERT_NOT_SYNC_THREAD();
// This method should only be called upon completion of the initial url import from the database
ASSERT(m_iconURLImportComplete);
LOG(IconDatabase, "Notifying all DocumentLoaders that were waiting on a load decision for their icons");
HashSet<RefPtr<DocumentLoader> >::iterator i = m_loadersPendingDecision.begin();
HashSet<RefPtr<DocumentLoader> >::iterator end = m_loadersPendingDecision.end();
for (; i != end; ++i)
if ((*i)->refCount() > 1)
(*i)->iconLoadDecisionAvailable();
m_loadersPendingDecision.clear();
}
void IconDatabase::wakeSyncThread()
{
MutexLocker locker(m_syncLock);
if (!m_disabledSuddenTerminationForSyncThread) {
m_disabledSuddenTerminationForSyncThread = true;
// The following is balanced by the call to enableSuddenTermination in the
// syncThreadMainLoop function.
// FIXME: It would be better to only disable sudden termination if we have
// something to write, not just if we have something to read.
disableSuddenTermination();
}
m_syncThreadHasWorkToDo = true;
m_syncCondition.signal();
}
void IconDatabase::performScheduleOrDeferSyncTimer()
{
m_syncTimer.startOneShot(updateTimerDelay);
m_scheduleOrDeferSyncTimerRequested = false;
}
void IconDatabase::performScheduleOrDeferSyncTimerOnMainThread(void* context)
{
static_cast<IconDatabase*>(context)->performScheduleOrDeferSyncTimer();
}
void IconDatabase::scheduleOrDeferSyncTimer()
{
ASSERT_NOT_SYNC_THREAD();
if (m_scheduleOrDeferSyncTimerRequested)
return;
// The following is balanced by the call to enableSuddenTermination in the
// syncTimerFired function.
disableSuddenTermination();
m_scheduleOrDeferSyncTimerRequested = true;
callOnMainThread(performScheduleOrDeferSyncTimerOnMainThread, this);
}
void IconDatabase::syncTimerFired(Timer<IconDatabase>*)
{
ASSERT_NOT_SYNC_THREAD();
wakeSyncThread();
// The following is balanced by the call to disableSuddenTermination in the
// scheduleOrDeferSyncTimer function.
enableSuddenTermination();
}
// ******************
// *** Any Thread ***
// ******************
bool IconDatabase::isOpen() const
{
MutexLocker locker(m_syncLock);
return m_syncDB.isOpen();
}
String IconDatabase::databasePath() const
{
MutexLocker locker(m_syncLock);
return m_completeDatabasePath.isolatedCopy();
}
String IconDatabase::defaultDatabaseFilename()
{
DEFINE_STATIC_LOCAL(String, defaultDatabaseFilename, (ASCIILiteral("WebpageIcons.db")));
return defaultDatabaseFilename.isolatedCopy();
}
// Unlike getOrCreatePageURLRecord(), getOrCreateIconRecord() does not mark the icon as "interested in import"
PassRefPtr<IconRecord> IconDatabase::getOrCreateIconRecord(const String& iconURL)
{
// Clients of getOrCreateIconRecord() are required to acquire the m_urlAndIconLock before calling this method
ASSERT(!m_urlAndIconLock.tryLock());
if (IconRecord* icon = m_iconURLToRecordMap.get(iconURL))
return icon;
RefPtr<IconRecord> newIcon = IconRecord::create(iconURL);
newIcon->setMutexForVerifier(m_urlAndIconLock);
m_iconURLToRecordMap.set(iconURL, newIcon.get());
return newIcon.release();
}
// This method retrieves the existing PageURLRecord, or creates a new one and marks it as "interested in the import" for later notification
PageURLRecord* IconDatabase::getOrCreatePageURLRecord(const String& pageURL)
{
// Clients of getOrCreatePageURLRecord() are required to acquire the m_urlAndIconLock before calling this method
ASSERT(!m_urlAndIconLock.tryLock());
if (!documentCanHaveIcon(pageURL))
return 0;
PageURLRecord* pageRecord = m_pageURLToRecordMap.get(pageURL);
MutexLocker locker(m_pendingReadingLock);
if (!m_iconURLImportComplete) {
// If the initial import of all URLs hasn't completed and we have no page record, we assume we *might* know about this later and create a record for it
if (!pageRecord) {
LOG(IconDatabase, "Creating new PageURLRecord for pageURL %s", urlForLogging(pageURL).ascii().data());
pageRecord = new PageURLRecord(pageURL);
m_pageURLToRecordMap.set(pageURL, pageRecord);
}
// If the pageRecord for this page does not have an iconRecord attached to it, then it is a new pageRecord still awaiting the initial import
// Mark the URL as "interested in the result of the import" then bail
if (!pageRecord->iconRecord()) {
m_pageURLsPendingImport.add(pageURL);
return 0;
}
}
// We've done the initial import of all URLs known in the database. If this record doesn't exist now, it never will
return pageRecord;
}
// ************************
// *** Sync Thread Only ***
// ************************
bool IconDatabase::shouldStopThreadActivity() const
{
ASSERT_ICON_SYNC_THREAD();
return m_threadTerminationRequested || m_removeIconsRequested;
}
void IconDatabase::iconDatabaseSyncThreadStart(void* vIconDatabase)
{
IconDatabase* iconDB = static_cast<IconDatabase*>(vIconDatabase);
iconDB->iconDatabaseSyncThread();
}
void IconDatabase::iconDatabaseSyncThread()
{
// The call to create this thread might not complete before the thread actually starts, so we might fail this ASSERT_ICON_SYNC_THREAD() because the pointer
// to our thread structure hasn't been filled in yet.
// To fix this, the main thread acquires this lock before creating us, then releases the lock after creation is complete. A quick lock/unlock cycle here will
// prevent us from running before that call completes
m_syncLock.lock();
m_syncLock.unlock();
ASSERT_ICON_SYNC_THREAD();
LOG(IconDatabase, "(THREAD) IconDatabase sync thread started");
#if !LOG_DISABLED
double startTime = currentTime();
#endif
// Need to create the database path if it doesn't already exist
makeAllDirectories(m_databaseDirectory);
// Existence of a journal file is evidence of a previous crash/force quit and automatically qualifies
// us to do an integrity check
String journalFilename = m_completeDatabasePath + "-journal";
if (!checkIntegrityOnOpen) {
AutodrainedPool pool;
checkIntegrityOnOpen = fileExists(journalFilename);
}
{
MutexLocker locker(m_syncLock);
if (!m_syncDB.open(m_completeDatabasePath)) {
LOG_ERROR("Unable to open icon database at path %s - %s", m_completeDatabasePath.ascii().data(), m_syncDB.lastErrorMsg());
return;
}
}
if (shouldStopThreadActivity()) {
syncThreadMainLoop();
return;
}
#if !LOG_DISABLED
double timeStamp = currentTime();
LOG(IconDatabase, "(THREAD) Open took %.4f seconds", timeStamp - startTime);
#endif
performOpenInitialization();
if (shouldStopThreadActivity()) {
syncThreadMainLoop();
return;
}
#if !LOG_DISABLED
double newStamp = currentTime();
LOG(IconDatabase, "(THREAD) performOpenInitialization() took %.4f seconds, now %.4f seconds from thread start", newStamp - timeStamp, newStamp - startTime);
timeStamp = newStamp;
#endif
// Uncomment the following line to simulate a long lasting URL import (*HUGE* icon databases, or network home directories)
// while (currentTime() - timeStamp < 10);
// Read in URL mappings from the database
LOG(IconDatabase, "(THREAD) Starting iconURL import");
performURLImport();
if (shouldStopThreadActivity()) {
syncThreadMainLoop();
return;
}
#if !LOG_DISABLED
newStamp = currentTime();
LOG(IconDatabase, "(THREAD) performURLImport() took %.4f seconds. Entering main loop %.4f seconds from thread start", newStamp - timeStamp, newStamp - startTime);
#endif
LOG(IconDatabase, "(THREAD) Beginning sync");
syncThreadMainLoop();
}
static int databaseVersionNumber(SQLiteDatabase& db)
{
return SQLiteStatement(db, "SELECT value FROM IconDatabaseInfo WHERE key = 'Version';").getColumnInt(0);
}
static bool isValidDatabase(SQLiteDatabase& db)
{
// These four tables should always exist in a valid db
if (!db.tableExists("IconInfo") || !db.tableExists("IconData") || !db.tableExists("PageURL") || !db.tableExists("IconDatabaseInfo"))
return false;
if (databaseVersionNumber(db) < currentDatabaseVersion) {
LOG(IconDatabase, "DB version is not found or below expected valid version");
return false;
}
return true;
}
static void createDatabaseTables(SQLiteDatabase& db)
{
if (!db.executeCommand("CREATE TABLE PageURL (url TEXT NOT NULL ON CONFLICT FAIL UNIQUE ON CONFLICT REPLACE,iconID INTEGER NOT NULL ON CONFLICT FAIL);")) {
LOG_ERROR("Could not create PageURL table in database (%i) - %s", db.lastError(), db.lastErrorMsg());
db.close();
return;
}
if (!db.executeCommand("CREATE INDEX PageURLIndex ON PageURL (url);")) {
LOG_ERROR("Could not create PageURL index in database (%i) - %s", db.lastError(), db.lastErrorMsg());
db.close();
return;
}
if (!db.executeCommand("CREATE TABLE IconInfo (iconID INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE ON CONFLICT REPLACE, url TEXT NOT NULL ON CONFLICT FAIL UNIQUE ON CONFLICT FAIL, stamp INTEGER);")) {
LOG_ERROR("Could not create IconInfo table in database (%i) - %s", db.lastError(), db.lastErrorMsg());
db.close();
return;
}
if (!db.executeCommand("CREATE INDEX IconInfoIndex ON IconInfo (url, iconID);")) {
LOG_ERROR("Could not create PageURL index in database (%i) - %s", db.lastError(), db.lastErrorMsg());
db.close();
return;
}
if (!db.executeCommand("CREATE TABLE IconData (iconID INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE ON CONFLICT REPLACE, data BLOB);")) {
LOG_ERROR("Could not create IconData table in database (%i) - %s", db.lastError(), db.lastErrorMsg());
db.close();
return;
}
if (!db.executeCommand("CREATE INDEX IconDataIndex ON IconData (iconID);")) {
LOG_ERROR("Could not create PageURL index in database (%i) - %s", db.lastError(), db.lastErrorMsg());
db.close();
return;
}
if (!db.executeCommand("CREATE TABLE IconDatabaseInfo (key TEXT NOT NULL ON CONFLICT FAIL UNIQUE ON CONFLICT REPLACE,value TEXT NOT NULL ON CONFLICT FAIL);")) {
LOG_ERROR("Could not create IconDatabaseInfo table in database (%i) - %s", db.lastError(), db.lastErrorMsg());
db.close();
return;
}
if (!db.executeCommand(String("INSERT INTO IconDatabaseInfo VALUES ('Version', ") + String::number(currentDatabaseVersion) + ");")) {
LOG_ERROR("Could not insert icon database version into IconDatabaseInfo table (%i) - %s", db.lastError(), db.lastErrorMsg());
db.close();
return;
}
}
void IconDatabase::performOpenInitialization()
{
ASSERT_ICON_SYNC_THREAD();
if (!isOpen())
return;
if (checkIntegrityOnOpen) {
checkIntegrityOnOpen = false;
if (!checkIntegrity()) {
LOG(IconDatabase, "Integrity check was bad - dumping IconDatabase");
m_syncDB.close();
{
MutexLocker locker(m_syncLock);
// Should've been consumed by SQLite, delete just to make sure we don't see it again in the future;
deleteFile(m_completeDatabasePath + "-journal");
deleteFile(m_completeDatabasePath);
}
// Reopen the write database, creating it from scratch
if (!m_syncDB.open(m_completeDatabasePath)) {
LOG_ERROR("Unable to open icon database at path %s - %s", m_completeDatabasePath.ascii().data(), m_syncDB.lastErrorMsg());
return;
}
}
}
int version = databaseVersionNumber(m_syncDB);
if (version > currentDatabaseVersion) {
LOG(IconDatabase, "Database version number %i is greater than our current version number %i - closing the database to prevent overwriting newer versions", version, currentDatabaseVersion);
m_syncDB.close();
m_threadTerminationRequested = true;
return;
}
if (!isValidDatabase(m_syncDB)) {
LOG(IconDatabase, "%s is missing or in an invalid state - reconstructing", m_completeDatabasePath.ascii().data());
m_syncDB.clearAllTables();
createDatabaseTables(m_syncDB);
}
// Reduce sqlite RAM cache size from default 2000 pages (~1.5kB per page). 3MB of cache for icon database is overkill
if (!SQLiteStatement(m_syncDB, "PRAGMA cache_size = 200;").executeCommand())
LOG_ERROR("SQLite database could not set cache_size");
// Tell backup software (i.e., Time Machine) to never back up the icon database, because
// it's a large file that changes frequently, thus using a lot of backup disk space, and
// it's unlikely that many users would be upset about it not being backed up. We could
// make this configurable on a per-client basis some day if some clients don't want this.
if (canExcludeFromBackup() && !wasExcludedFromBackup() && excludeFromBackup(m_completeDatabasePath))
setWasExcludedFromBackup();
}
bool IconDatabase::checkIntegrity()
{
ASSERT_ICON_SYNC_THREAD();
SQLiteStatement integrity(m_syncDB, "PRAGMA integrity_check;");
if (integrity.prepare() != SQLResultOk) {
LOG_ERROR("checkIntegrity failed to execute");
return false;
}
int resultCode = integrity.step();
if (resultCode == SQLResultOk)
return true;
if (resultCode != SQLResultRow)
return false;
int columns = integrity.columnCount();
if (columns != 1) {
LOG_ERROR("Received %i columns performing integrity check, should be 1", columns);
return false;
}
String resultText = integrity.getColumnText(0);
// A successful, no-error integrity check will be "ok" - all other strings imply failure
if (resultText == "ok")
return true;
LOG_ERROR("Icon database integrity check failed - \n%s", resultText.ascii().data());
return false;
}
void IconDatabase::performURLImport()
{
ASSERT_ICON_SYNC_THREAD();
# if PLATFORM(GTK)
// Do not import icons not used in the last 30 days. They will be automatically pruned later if nobody retains them.
// Note that IconInfo.stamp is only set when the icon data is retrieved from the server (and thus is not updated whether
// we use it or not). This code works anyway because the IconDatabase downloads icons again if they are older than 4 days,
// so if the timestamp goes back in time more than those 30 days we can be sure that the icon was not used at all.
String importQuery = String::format("SELECT PageURL.url, IconInfo.url, IconInfo.stamp FROM PageURL INNER JOIN IconInfo ON PageURL.iconID=IconInfo.iconID WHERE IconInfo.stamp > %.0f;", floor(currentTime() - notUsedIconExpirationTime));
#else
String importQuery("SELECT PageURL.url, IconInfo.url, IconInfo.stamp FROM PageURL INNER JOIN IconInfo ON PageURL.iconID=IconInfo.iconID;");
#endif
SQLiteStatement query(m_syncDB, importQuery);
if (query.prepare() != SQLResultOk) {
LOG_ERROR("Unable to prepare icon url import query");
return;
}
int result = query.step();
while (result == SQLResultRow) {
AutodrainedPool pool;
String pageURL = query.getColumnText(0);
String iconURL = query.getColumnText(1);
{
MutexLocker locker(m_urlAndIconLock);
PageURLRecord* pageRecord = m_pageURLToRecordMap.get(pageURL);
// If the pageRecord doesn't exist in this map, then no one has retained this pageURL
// If the s_databaseCleanupCounter count is non-zero, then we're not supposed to be pruning the database in any manner,
// so go ahead and actually create a pageURLRecord for this url even though it's not retained.
// If database cleanup *is* allowed, we don't want to bother pulling in a page url from disk that noone is actually interested
// in - we'll prune it later instead!
if (!pageRecord && databaseCleanupCounter && documentCanHaveIcon(pageURL)) {
pageRecord = new PageURLRecord(pageURL);
m_pageURLToRecordMap.set(pageURL, pageRecord);
}
if (pageRecord) {
IconRecord* currentIcon = pageRecord->iconRecord();
if (!currentIcon || currentIcon->iconURL() != iconURL) {
pageRecord->setIconRecord(getOrCreateIconRecord(iconURL));
currentIcon = pageRecord->iconRecord();
}
// Regardless, the time stamp from disk still takes precedence. Until we read this icon from disk, we didn't think we'd seen it before
// so we marked the timestamp as "now", but it's really much older
currentIcon->setTimestamp(query.getColumnInt(2));
}
}
// FIXME: Currently the WebKit API supports 1 type of notification that is sent whenever we get an Icon URL for a Page URL. We might want to re-purpose it to work for
// getting the actually icon itself also (so each pageurl would get this notification twice) or we might want to add a second type of notification -
// one for the URL and one for the Image itself
// Note that WebIconDatabase is not neccessarily API so we might be able to make this change
{
MutexLocker locker(m_pendingReadingLock);
if (m_pageURLsPendingImport.contains(pageURL)) {
dispatchDidImportIconURLForPageURLOnMainThread(pageURL);
m_pageURLsPendingImport.remove(pageURL);
}
}
// Stop the import at any time of the thread has been asked to shutdown
if (shouldStopThreadActivity()) {
LOG(IconDatabase, "IconDatabase asked to terminate during performURLImport()");
return;
}
result = query.step();
}
if (result != SQLResultDone)
LOG(IconDatabase, "Error reading page->icon url mappings from database");
// Clear the m_pageURLsPendingImport set - either the page URLs ended up with an iconURL (that we'll notify about) or not,
// but after m_iconURLImportComplete is set to true, we don't care about this set anymore
Vector<String> urls;
{
MutexLocker locker(m_pendingReadingLock);
urls.appendRange(m_pageURLsPendingImport.begin(), m_pageURLsPendingImport.end());
m_pageURLsPendingImport.clear();
m_iconURLImportComplete = true;
}
Vector<String> urlsToNotify;
// Loop through the urls pending import
// Remove unretained ones if database cleanup is allowed
// Keep a set of ones that are retained and pending notification
{
MutexLocker locker(m_urlAndIconLock);
performPendingRetainAndReleaseOperations();
for (unsigned i = 0; i < urls.size(); ++i) {
if (!m_retainedPageURLs.contains(urls[i])) {
PageURLRecord* record = m_pageURLToRecordMap.get(urls[i]);
if (record && !databaseCleanupCounter) {
m_pageURLToRecordMap.remove(urls[i]);
IconRecord* iconRecord = record->iconRecord();
// If this page is the only remaining retainer of its icon, mark that icon for deletion and don't bother
// reading anything related to it
if (iconRecord && iconRecord->hasOneRef()) {
m_iconURLToRecordMap.remove(iconRecord->iconURL());
{
MutexLocker locker(m_pendingReadingLock);
m_pageURLsInterestedInIcons.remove(urls[i]);
m_iconsPendingReading.remove(iconRecord);
}
{
MutexLocker locker(m_pendingSyncLock);
m_iconsPendingSync.set(iconRecord->iconURL(), iconRecord->snapshot(true));
}
}
delete record;
}
} else {
urlsToNotify.append(urls[i]);
}
}
}
LOG(IconDatabase, "Notifying %lu interested page URLs that their icon URL is known due to the import", static_cast<unsigned long>(urlsToNotify.size()));
// Now that we don't hold any locks, perform the actual notifications
for (unsigned i = 0; i < urlsToNotify.size(); ++i) {
AutodrainedPool pool;
LOG(IconDatabase, "Notifying icon info known for pageURL %s", urlsToNotify[i].ascii().data());
dispatchDidImportIconURLForPageURLOnMainThread(urlsToNotify[i]);
if (shouldStopThreadActivity())
return;
}
// Notify the client that the URL import is complete in case it's managing its own pending notifications.
dispatchDidFinishURLImportOnMainThread();
// Notify all DocumentLoaders that were waiting for an icon load decision on the main thread
callOnMainThread(notifyPendingLoadDecisionsOnMainThread, this);
}
void IconDatabase::syncThreadMainLoop()
{
ASSERT_ICON_SYNC_THREAD();
m_syncLock.lock();
bool shouldReenableSuddenTermination = m_disabledSuddenTerminationForSyncThread;
m_disabledSuddenTerminationForSyncThread = false;
// We'll either do any pending work on our first pass through the loop, or we'll terminate
// without doing any work. Either way we're dealing with any currently-pending work.
m_syncThreadHasWorkToDo = false;
// It's possible thread termination is requested before the main loop even starts - in that case, just skip straight to cleanup
while (!m_threadTerminationRequested) {
m_syncLock.unlock();
#if !LOG_DISABLED
double timeStamp = currentTime();
#endif
LOG(IconDatabase, "(THREAD) Main work loop starting");
// If we should remove all icons, do it now. This is an uninteruptible procedure that we will always do before quitting if it is requested
if (m_removeIconsRequested) {
removeAllIconsOnThread();
m_removeIconsRequested = false;
}
// Then, if the thread should be quitting, quit now!
if (m_threadTerminationRequested)
break;
{
MutexLocker locker(m_urlAndIconLock);
performPendingRetainAndReleaseOperations();
}
bool didAnyWork = true;
while (didAnyWork) {
bool didWrite = writeToDatabase();
if (shouldStopThreadActivity())
break;
didAnyWork = readFromDatabase();
if (shouldStopThreadActivity())
break;
// Prune unretained icons after the first time we sync anything out to the database
// This way, pruning won't be the only operation we perform to the database by itself
// We also don't want to bother doing this if the thread should be terminating (the user is quitting)
// or if private browsing is enabled
// We also don't want to prune if the m_databaseCleanupCounter count is non-zero - that means someone
// has asked to delay pruning
static bool prunedUnretainedIcons = false;
if (didWrite && !m_privateBrowsingEnabled && !prunedUnretainedIcons && !databaseCleanupCounter) {
#if !LOG_DISABLED
double time = currentTime();
#endif
LOG(IconDatabase, "(THREAD) Starting pruneUnretainedIcons()");
pruneUnretainedIcons();
LOG(IconDatabase, "(THREAD) pruneUnretainedIcons() took %.4f seconds", currentTime() - time);
// If pruneUnretainedIcons() returned early due to requested thread termination, its still okay
// to mark prunedUnretainedIcons true because we're about to terminate anyway
prunedUnretainedIcons = true;
}
didAnyWork = didAnyWork || didWrite;
if (shouldStopThreadActivity())
break;
}
#if !LOG_DISABLED
double newstamp = currentTime();
LOG(IconDatabase, "(THREAD) Main work loop ran for %.4f seconds, %s requested to terminate", newstamp - timeStamp, shouldStopThreadActivity() ? "was" : "was not");
#endif
m_syncLock.lock();
// There is some condition that is asking us to stop what we're doing now and handle a special case
// This is either removing all icons, or shutting down the thread to quit the app
// We handle those at the top of this main loop so continue to jump back up there
if (shouldStopThreadActivity())
continue;
if (shouldReenableSuddenTermination) {
// The following is balanced by the call to disableSuddenTermination in the
// wakeSyncThread function. Any time we wait on the condition, we also have
// to enableSuddenTermation, after doing the next batch of work.
enableSuddenTermination();
}
while (!m_syncThreadHasWorkToDo)
m_syncCondition.wait(m_syncLock);
m_syncThreadHasWorkToDo = false;
ASSERT(m_disabledSuddenTerminationForSyncThread);
shouldReenableSuddenTermination = true;
m_disabledSuddenTerminationForSyncThread = false;
}
m_syncLock.unlock();
// Thread is terminating at this point
cleanupSyncThread();
if (shouldReenableSuddenTermination) {
// The following is balanced by the call to disableSuddenTermination in the
// wakeSyncThread function. Any time we wait on the condition, we also have
// to enableSuddenTermation, after doing the next batch of work.
enableSuddenTermination();
MutexLocker locker(m_syncLock);
m_disabledSuddenTerminationForSyncThread = false;
}
}
void IconDatabase::performPendingRetainAndReleaseOperations()
{
// NOTE: The caller is assumed to hold m_urlAndIconLock.
ASSERT(!m_urlAndIconLock.tryLock());
HashCountedSet<String> toRetain;
HashCountedSet<String> toRelease;
{
MutexLocker pendingWorkLocker(m_urlsToRetainOrReleaseLock);
if (!m_retainOrReleaseIconRequested)
return;
// Make a copy of the URLs to retain and/or release so we can release m_urlsToRetainOrReleaseLock ASAP.
// Holding m_urlAndIconLock protects this function from being re-entered.
toRetain.swap(m_urlsToRetain);
toRelease.swap(m_urlsToRelease);
m_retainOrReleaseIconRequested = false;
}
for (HashCountedSet<String>::const_iterator it = toRetain.begin(), end = toRetain.end(); it != end; ++it) {
ASSERT(!it->key.impl() || it->key.impl()->hasOneRef());
performRetainIconForPageURL(it->key, it->value);
}
for (HashCountedSet<String>::const_iterator it = toRelease.begin(), end = toRelease.end(); it != end; ++it) {
ASSERT(!it->key.impl() || it->key.impl()->hasOneRef());
performReleaseIconForPageURL(it->key, it->value);
}
}
bool IconDatabase::readFromDatabase()
{
ASSERT_ICON_SYNC_THREAD();
#if !LOG_DISABLED
double timeStamp = currentTime();
#endif
bool didAnyWork = false;
// We'll make a copy of the sets of things that need to be read. Then we'll verify at the time of updating the record that it still wants to be updated
// This way we won't hold the lock for a long period of time
Vector<IconRecord*> icons;
{
MutexLocker locker(m_pendingReadingLock);
icons.appendRange(m_iconsPendingReading.begin(), m_iconsPendingReading.end());
}
// Keep track of icons we actually read to notify them of the new icon
HashSet<String> urlsToNotify;
for (unsigned i = 0; i < icons.size(); ++i) {
didAnyWork = true;
RefPtr<SharedBuffer> imageData = getImageDataForIconURLFromSQLDatabase(icons[i]->iconURL());
imageData->setMutexForVerifier(m_urlAndIconLock);
// Verify this icon still wants to be read from disk
{
MutexLocker urlLocker(m_urlAndIconLock);
{
MutexLocker readLocker(m_pendingReadingLock);
if (m_iconsPendingReading.contains(icons[i])) {
// Set the new data
icons[i]->setImageData(imageData.release());
// Remove this icon from the set that needs to be read
m_iconsPendingReading.remove(icons[i]);
// We have a set of all Page URLs that retain this icon as well as all PageURLs waiting for an icon
// We want to find the intersection of these two sets to notify them
// Check the sizes of these two sets to minimize the number of iterations
const HashSet<String>* outerHash;
const HashSet<String>* innerHash;
if (icons[i]->retainingPageURLs().size() > m_pageURLsInterestedInIcons.size()) {
outerHash = &m_pageURLsInterestedInIcons;
innerHash = &(icons[i]->retainingPageURLs());
} else {
innerHash = &m_pageURLsInterestedInIcons;
outerHash = &(icons[i]->retainingPageURLs());
}
HashSet<String>::const_iterator iter = outerHash->begin();
HashSet<String>::const_iterator end = outerHash->end();
for (; iter != end; ++iter) {
if (innerHash->contains(*iter)) {
LOG(IconDatabase, "%s is interested in the icon we just read. Adding it to the notification list and removing it from the interested set", urlForLogging(*iter).ascii().data());
urlsToNotify.add(*iter);
}
// If we ever get to the point were we've seen every url interested in this icon, break early
if (urlsToNotify.size() == m_pageURLsInterestedInIcons.size())
break;
}
// We don't need to notify a PageURL twice, so all the ones we're about to notify can be removed from the interested set
if (urlsToNotify.size() == m_pageURLsInterestedInIcons.size())
m_pageURLsInterestedInIcons.clear();
else {
iter = urlsToNotify.begin();
end = urlsToNotify.end();
for (; iter != end; ++iter)
m_pageURLsInterestedInIcons.remove(*iter);
}
}
}
}
if (shouldStopThreadActivity())
return didAnyWork;
// Now that we don't hold any locks, perform the actual notifications
for (HashSet<String>::const_iterator it = urlsToNotify.begin(), end = urlsToNotify.end(); it != end; ++it) {
AutodrainedPool pool;
LOG(IconDatabase, "Notifying icon received for pageURL %s", urlForLogging(*it).ascii().data());
dispatchDidImportIconDataForPageURLOnMainThread(*it);
if (shouldStopThreadActivity())
return didAnyWork;
}
LOG(IconDatabase, "Done notifying %i pageURLs who just received their icons", urlsToNotify.size());
urlsToNotify.clear();
if (shouldStopThreadActivity())
return didAnyWork;
}
LOG(IconDatabase, "Reading from database took %.4f seconds", currentTime() - timeStamp);
return didAnyWork;
}
bool IconDatabase::writeToDatabase()
{
ASSERT_ICON_SYNC_THREAD();
#if !LOG_DISABLED
double timeStamp = currentTime();
#endif
bool didAnyWork = false;
// We can copy the current work queue then clear it out - If any new work comes in while we're writing out,
// we'll pick it up on the next pass. This greatly simplifies the locking strategy for this method and remains cohesive with changes
// asked for by the database on the main thread
{
MutexLocker locker(m_urlAndIconLock);
Vector<IconSnapshot> iconSnapshots;
Vector<PageURLSnapshot> pageSnapshots;
{
MutexLocker locker(m_pendingSyncLock);
iconSnapshots.appendRange(m_iconsPendingSync.begin().values(), m_iconsPendingSync.end().values());
m_iconsPendingSync.clear();
pageSnapshots.appendRange(m_pageURLsPendingSync.begin().values(), m_pageURLsPendingSync.end().values());
m_pageURLsPendingSync.clear();
}
if (iconSnapshots.size() || pageSnapshots.size())
didAnyWork = true;
SQLiteTransaction syncTransaction(m_syncDB);
syncTransaction.begin();
for (unsigned i = 0; i < iconSnapshots.size(); ++i) {
writeIconSnapshotToSQLDatabase(iconSnapshots[i]);
LOG(IconDatabase, "Wrote IconRecord for IconURL %s with timeStamp of %i to the DB", urlForLogging(iconSnapshots[i].iconURL()).ascii().data(), iconSnapshots[i].timestamp());
}
for (unsigned i = 0; i < pageSnapshots.size(); ++i) {
// If the icon URL is empty, this page is meant to be deleted
// ASSERTs are sanity checks to make sure the mappings exist if they should and don't if they shouldn't
if (pageSnapshots[i].iconURL().isEmpty())
removePageURLFromSQLDatabase(pageSnapshots[i].pageURL());
else
setIconURLForPageURLInSQLDatabase(pageSnapshots[i].iconURL(), pageSnapshots[i].pageURL());
LOG(IconDatabase, "Committed IconURL for PageURL %s to database", urlForLogging(pageSnapshots[i].pageURL()).ascii().data());
}
syncTransaction.commit();
}
// Check to make sure there are no dangling PageURLs - If there are, we want to output one log message but not spam the console potentially every few seconds
if (didAnyWork)
checkForDanglingPageURLs(false);
LOG(IconDatabase, "Updating the database took %.4f seconds", currentTime() - timeStamp);
return didAnyWork;
}
void IconDatabase::pruneUnretainedIcons()
{
ASSERT_ICON_SYNC_THREAD();
if (!isOpen())
return;
// This method should only be called once per run
ASSERT(!m_initialPruningComplete);
// This method relies on having read in all page URLs from the database earlier.
ASSERT(m_iconURLImportComplete);
// Get the known PageURLs from the db, and record the ID of any that are not in the retain count set.
Vector<int64_t> pageIDsToDelete;
SQLiteStatement pageSQL(m_syncDB, "SELECT rowid, url FROM PageURL;");
pageSQL.prepare();
int result;
while ((result = pageSQL.step()) == SQLResultRow) {
MutexLocker locker(m_urlAndIconLock);
if (!m_pageURLToRecordMap.contains(pageSQL.getColumnText(1)))
pageIDsToDelete.append(pageSQL.getColumnInt64(0));
}
if (result != SQLResultDone)
LOG_ERROR("Error reading PageURL table from on-disk DB");
pageSQL.finalize();
// Delete page URLs that were in the table, but not in our retain count set.
size_t numToDelete = pageIDsToDelete.size();
if (numToDelete) {
SQLiteTransaction pruningTransaction(m_syncDB);
pruningTransaction.begin();
SQLiteStatement pageDeleteSQL(m_syncDB, "DELETE FROM PageURL WHERE rowid = (?);");
pageDeleteSQL.prepare();
for (size_t i = 0; i < numToDelete; ++i) {
#if OS(WINDOWS)
LOG(IconDatabase, "Pruning page with rowid %I64i from disk", static_cast<long long>(pageIDsToDelete[i]));
#else
LOG(IconDatabase, "Pruning page with rowid %lli from disk", static_cast<long long>(pageIDsToDelete[i]));
#endif
pageDeleteSQL.bindInt64(1, pageIDsToDelete[i]);
int result = pageDeleteSQL.step();
if (result != SQLResultDone)
#if OS(WINDOWS)
LOG_ERROR("Unabled to delete page with id %I64i from disk", static_cast<long long>(pageIDsToDelete[i]));
#else
LOG_ERROR("Unabled to delete page with id %lli from disk", static_cast<long long>(pageIDsToDelete[i]));
#endif
pageDeleteSQL.reset();
// If the thread was asked to terminate, we should commit what pruning we've done so far, figuring we can
// finish the rest later (hopefully)
if (shouldStopThreadActivity()) {
pruningTransaction.commit();
return;
}
}
pruningTransaction.commit();
pageDeleteSQL.finalize();
}
// Deleting unreferenced icons from the Icon tables has to be atomic -
// If the user quits while these are taking place, they might have to wait. Thankfully this will rarely be an issue
// A user on a network home directory with a wildly inconsistent database might see quite a pause...
SQLiteTransaction pruningTransaction(m_syncDB);
pruningTransaction.begin();
// Wipe Icons that aren't retained
if (!m_syncDB.executeCommand("DELETE FROM IconData WHERE iconID NOT IN (SELECT iconID FROM PageURL);"))
LOG_ERROR("Failed to execute SQL to prune unretained icons from the on-disk IconData table");
if (!m_syncDB.executeCommand("DELETE FROM IconInfo WHERE iconID NOT IN (SELECT iconID FROM PageURL);"))
LOG_ERROR("Failed to execute SQL to prune unretained icons from the on-disk IconInfo table");
pruningTransaction.commit();
checkForDanglingPageURLs(true);
m_initialPruningComplete = true;
}
void IconDatabase::checkForDanglingPageURLs(bool pruneIfFound)
{
ASSERT_ICON_SYNC_THREAD();
// This check can be relatively expensive so we don't do it in a release build unless the caller has asked us to prune any dangling
// entries. We also don't want to keep performing this check and reporting this error if it has already found danglers before so we
// keep track of whether we've found any. We skip the check in the release build pretending to have already found danglers already.
#ifndef NDEBUG
static bool danglersFound = true;
#else
static bool danglersFound = false;
#endif
if ((pruneIfFound || !danglersFound) && SQLiteStatement(m_syncDB, "SELECT url FROM PageURL WHERE PageURL.iconID NOT IN (SELECT iconID FROM IconInfo) LIMIT 1;").returnsAtLeastOneResult()) {
danglersFound = true;
LOG(IconDatabase, "Dangling PageURL entries found");
if (pruneIfFound && !m_syncDB.executeCommand("DELETE FROM PageURL WHERE iconID NOT IN (SELECT iconID FROM IconInfo);"))
LOG(IconDatabase, "Unable to prune dangling PageURLs");
}
}
void IconDatabase::removeAllIconsOnThread()
{
ASSERT_ICON_SYNC_THREAD();
LOG(IconDatabase, "Removing all icons on the sync thread");
// Delete all the prepared statements so they can start over
deleteAllPreparedStatements();
// To reset the on-disk database, we'll wipe all its tables then vacuum it
// This is easier and safer than closing it, deleting the file, and recreating from scratch
m_syncDB.clearAllTables();
m_syncDB.runVacuumCommand();
createDatabaseTables(m_syncDB);
LOG(IconDatabase, "Dispatching notification that we removed all icons");
dispatchDidRemoveAllIconsOnMainThread();
}
void IconDatabase::deleteAllPreparedStatements()
{
ASSERT_ICON_SYNC_THREAD();
m_setIconIDForPageURLStatement.clear();
m_removePageURLStatement.clear();
m_getIconIDForIconURLStatement.clear();
m_getImageDataForIconURLStatement.clear();
m_addIconToIconInfoStatement.clear();
m_addIconToIconDataStatement.clear();
m_getImageDataStatement.clear();
m_deletePageURLsForIconURLStatement.clear();
m_deleteIconFromIconInfoStatement.clear();
m_deleteIconFromIconDataStatement.clear();
m_updateIconInfoStatement.clear();
m_updateIconDataStatement.clear();
m_setIconInfoStatement.clear();
m_setIconDataStatement.clear();
}
void* IconDatabase::cleanupSyncThread()
{
ASSERT_ICON_SYNC_THREAD();
#if !LOG_DISABLED
double timeStamp = currentTime();
#endif
// If the removeIcons flag is set, remove all icons from the db.
if (m_removeIconsRequested)
removeAllIconsOnThread();
// Sync remaining icons out
LOG(IconDatabase, "(THREAD) Doing final writeout and closure of sync thread");
writeToDatabase();
// Close the database
MutexLocker locker(m_syncLock);
m_databaseDirectory = String();
m_completeDatabasePath = String();
deleteAllPreparedStatements();
m_syncDB.close();
#if !LOG_DISABLED
LOG(IconDatabase, "(THREAD) Final closure took %.4f seconds", currentTime() - timeStamp);
#endif
m_syncThreadRunning = false;
return 0;
}
// readySQLiteStatement() handles two things
// 1 - If the SQLDatabase& argument is different, the statement must be destroyed and remade. This happens when the user
// switches to and from private browsing
// 2 - Lazy construction of the Statement in the first place, in case we've never made this query before
inline void readySQLiteStatement(OwnPtr<SQLiteStatement>& statement, SQLiteDatabase& db, const String& str)
{
if (statement && (statement->database() != &db || statement->isExpired())) {
if (statement->isExpired())
LOG(IconDatabase, "SQLiteStatement associated with %s is expired", str.ascii().data());
statement.clear();
}
if (!statement) {
statement = adoptPtr(new SQLiteStatement(db, str));
if (statement->prepare() != SQLResultOk)
LOG_ERROR("Preparing statement %s failed", str.ascii().data());
}
}
void IconDatabase::setIconURLForPageURLInSQLDatabase(const String& iconURL, const String& pageURL)
{
ASSERT_ICON_SYNC_THREAD();
int64_t iconID = getIconIDForIconURLFromSQLDatabase(iconURL);
if (!iconID)
iconID = addIconURLToSQLDatabase(iconURL);
if (!iconID) {
LOG_ERROR("Failed to establish an ID for iconURL %s", urlForLogging(iconURL).ascii().data());
ASSERT_NOT_REACHED();
return;
}
setIconIDForPageURLInSQLDatabase(iconID, pageURL);
}
void IconDatabase::setIconIDForPageURLInSQLDatabase(int64_t iconID, const String& pageURL)
{
ASSERT_ICON_SYNC_THREAD();
readySQLiteStatement(m_setIconIDForPageURLStatement, m_syncDB, "INSERT INTO PageURL (url, iconID) VALUES ((?), ?);");
m_setIconIDForPageURLStatement->bindText(1, pageURL);
m_setIconIDForPageURLStatement->bindInt64(2, iconID);
int result = m_setIconIDForPageURLStatement->step();
if (result != SQLResultDone) {
ASSERT_NOT_REACHED();
LOG_ERROR("setIconIDForPageURLQuery failed for url %s", urlForLogging(pageURL).ascii().data());
}
m_setIconIDForPageURLStatement->reset();
}
void IconDatabase::removePageURLFromSQLDatabase(const String& pageURL)
{
ASSERT_ICON_SYNC_THREAD();
readySQLiteStatement(m_removePageURLStatement, m_syncDB, "DELETE FROM PageURL WHERE url = (?);");
m_removePageURLStatement->bindText(1, pageURL);
if (m_removePageURLStatement->step() != SQLResultDone)
LOG_ERROR("removePageURLFromSQLDatabase failed for url %s", urlForLogging(pageURL).ascii().data());
m_removePageURLStatement->reset();
}
int64_t IconDatabase::getIconIDForIconURLFromSQLDatabase(const String& iconURL)
{
ASSERT_ICON_SYNC_THREAD();
readySQLiteStatement(m_getIconIDForIconURLStatement, m_syncDB, "SELECT IconInfo.iconID FROM IconInfo WHERE IconInfo.url = (?);");
m_getIconIDForIconURLStatement->bindText(1, iconURL);
int64_t result = m_getIconIDForIconURLStatement->step();
if (result == SQLResultRow)
result = m_getIconIDForIconURLStatement->getColumnInt64(0);
else {
if (result != SQLResultDone)
LOG_ERROR("getIconIDForIconURLFromSQLDatabase failed for url %s", urlForLogging(iconURL).ascii().data());
result = 0;
}
m_getIconIDForIconURLStatement->reset();
return result;
}
int64_t IconDatabase::addIconURLToSQLDatabase(const String& iconURL)
{
ASSERT_ICON_SYNC_THREAD();
// There would be a transaction here to make sure these two inserts are atomic
// In practice the only caller of this method is always wrapped in a transaction itself so placing another
// here is unnecessary
readySQLiteStatement(m_addIconToIconInfoStatement, m_syncDB, "INSERT INTO IconInfo (url, stamp) VALUES (?, 0);");
m_addIconToIconInfoStatement->bindText(1, iconURL);
int result = m_addIconToIconInfoStatement->step();
m_addIconToIconInfoStatement->reset();
if (result != SQLResultDone) {
LOG_ERROR("addIconURLToSQLDatabase failed to insert %s into IconInfo", urlForLogging(iconURL).ascii().data());
return 0;
}
int64_t iconID = m_syncDB.lastInsertRowID();
readySQLiteStatement(m_addIconToIconDataStatement, m_syncDB, "INSERT INTO IconData (iconID, data) VALUES (?, ?);");
m_addIconToIconDataStatement->bindInt64(1, iconID);
result = m_addIconToIconDataStatement->step();
m_addIconToIconDataStatement->reset();
if (result != SQLResultDone) {
LOG_ERROR("addIconURLToSQLDatabase failed to insert %s into IconData", urlForLogging(iconURL).ascii().data());
return 0;
}
return iconID;
}
PassRefPtr<SharedBuffer> IconDatabase::getImageDataForIconURLFromSQLDatabase(const String& iconURL)
{
ASSERT_ICON_SYNC_THREAD();
RefPtr<SharedBuffer> imageData;
readySQLiteStatement(m_getImageDataForIconURLStatement, m_syncDB, "SELECT IconData.data FROM IconData WHERE IconData.iconID IN (SELECT iconID FROM IconInfo WHERE IconInfo.url = (?));");
m_getImageDataForIconURLStatement->bindText(1, iconURL);
int result = m_getImageDataForIconURLStatement->step();
if (result == SQLResultRow) {
Vector<char> data;
m_getImageDataForIconURLStatement->getColumnBlobAsVector(0, data);
imageData = SharedBuffer::create(data.data(), data.size());
} else if (result != SQLResultDone)
LOG_ERROR("getImageDataForIconURLFromSQLDatabase failed for url %s", urlForLogging(iconURL).ascii().data());
m_getImageDataForIconURLStatement->reset();
return imageData.release();
}
void IconDatabase::removeIconFromSQLDatabase(const String& iconURL)
{
ASSERT_ICON_SYNC_THREAD();
if (iconURL.isEmpty())
return;
// There would be a transaction here to make sure these removals are atomic
// In practice the only caller of this method is always wrapped in a transaction itself so placing another here is unnecessary
// It's possible this icon is not in the database because of certain rapid browsing patterns (such as a stress test) where the
// icon is marked to be added then marked for removal before it is ever written to disk. No big deal, early return
int64_t iconID = getIconIDForIconURLFromSQLDatabase(iconURL);
if (!iconID)
return;
readySQLiteStatement(m_deletePageURLsForIconURLStatement, m_syncDB, "DELETE FROM PageURL WHERE PageURL.iconID = (?);");
m_deletePageURLsForIconURLStatement->bindInt64(1, iconID);
if (m_deletePageURLsForIconURLStatement->step() != SQLResultDone)
LOG_ERROR("m_deletePageURLsForIconURLStatement failed for url %s", urlForLogging(iconURL).ascii().data());
readySQLiteStatement(m_deleteIconFromIconInfoStatement, m_syncDB, "DELETE FROM IconInfo WHERE IconInfo.iconID = (?);");
m_deleteIconFromIconInfoStatement->bindInt64(1, iconID);
if (m_deleteIconFromIconInfoStatement->step() != SQLResultDone)
LOG_ERROR("m_deleteIconFromIconInfoStatement failed for url %s", urlForLogging(iconURL).ascii().data());
readySQLiteStatement(m_deleteIconFromIconDataStatement, m_syncDB, "DELETE FROM IconData WHERE IconData.iconID = (?);");
m_deleteIconFromIconDataStatement->bindInt64(1, iconID);
if (m_deleteIconFromIconDataStatement->step() != SQLResultDone)
LOG_ERROR("m_deleteIconFromIconDataStatement failed for url %s", urlForLogging(iconURL).ascii().data());
m_deletePageURLsForIconURLStatement->reset();
m_deleteIconFromIconInfoStatement->reset();
m_deleteIconFromIconDataStatement->reset();
}
void IconDatabase::writeIconSnapshotToSQLDatabase(const IconSnapshot& snapshot)
{
ASSERT_ICON_SYNC_THREAD();
if (snapshot.iconURL().isEmpty())
return;
// A nulled out timestamp and data means this icon is destined to be deleted - do that instead of writing it out
if (!snapshot.timestamp() && !snapshot.data()) {
LOG(IconDatabase, "Removing %s from on-disk database", urlForLogging(snapshot.iconURL()).ascii().data());
removeIconFromSQLDatabase(snapshot.iconURL());
return;
}
// There would be a transaction here to make sure these removals are atomic
// In practice the only caller of this method is always wrapped in a transaction itself so placing another here is unnecessary
// Get the iconID for this url
int64_t iconID = getIconIDForIconURLFromSQLDatabase(snapshot.iconURL());
// If there is already an iconID in place, update the database.
// Otherwise, insert new records
if (iconID) {
readySQLiteStatement(m_updateIconInfoStatement, m_syncDB, "UPDATE IconInfo SET stamp = ?, url = ? WHERE iconID = ?;");
m_updateIconInfoStatement->bindInt64(1, snapshot.timestamp());
m_updateIconInfoStatement->bindText(2, snapshot.iconURL());
m_updateIconInfoStatement->bindInt64(3, iconID);
if (m_updateIconInfoStatement->step() != SQLResultDone)
LOG_ERROR("Failed to update icon info for url %s", urlForLogging(snapshot.iconURL()).ascii().data());
m_updateIconInfoStatement->reset();
readySQLiteStatement(m_updateIconDataStatement, m_syncDB, "UPDATE IconData SET data = ? WHERE iconID = ?;");
m_updateIconDataStatement->bindInt64(2, iconID);
// If we *have* image data, bind it to this statement - Otherwise bind "null" for the blob data,
// signifying that this icon doesn't have any data
if (snapshot.data() && snapshot.data()->size())
m_updateIconDataStatement->bindBlob(1, snapshot.data()->data(), snapshot.data()->size());
else
m_updateIconDataStatement->bindNull(1);
if (m_updateIconDataStatement->step() != SQLResultDone)
LOG_ERROR("Failed to update icon data for url %s", urlForLogging(snapshot.iconURL()).ascii().data());
m_updateIconDataStatement->reset();
} else {
readySQLiteStatement(m_setIconInfoStatement, m_syncDB, "INSERT INTO IconInfo (url,stamp) VALUES (?, ?);");
m_setIconInfoStatement->bindText(1, snapshot.iconURL());
m_setIconInfoStatement->bindInt64(2, snapshot.timestamp());
if (m_setIconInfoStatement->step() != SQLResultDone)
LOG_ERROR("Failed to set icon info for url %s", urlForLogging(snapshot.iconURL()).ascii().data());
m_setIconInfoStatement->reset();
int64_t iconID = m_syncDB.lastInsertRowID();
readySQLiteStatement(m_setIconDataStatement, m_syncDB, "INSERT INTO IconData (iconID, data) VALUES (?, ?);");
m_setIconDataStatement->bindInt64(1, iconID);
// If we *have* image data, bind it to this statement - Otherwise bind "null" for the blob data,
// signifying that this icon doesn't have any data
if (snapshot.data() && snapshot.data()->size())
m_setIconDataStatement->bindBlob(2, snapshot.data()->data(), snapshot.data()->size());
else
m_setIconDataStatement->bindNull(2);
if (m_setIconDataStatement->step() != SQLResultDone)
LOG_ERROR("Failed to set icon data for url %s", urlForLogging(snapshot.iconURL()).ascii().data());
m_setIconDataStatement->reset();
}
}
bool IconDatabase::wasExcludedFromBackup()
{
ASSERT_ICON_SYNC_THREAD();
return SQLiteStatement(m_syncDB, "SELECT value FROM IconDatabaseInfo WHERE key = 'ExcludedFromBackup';").getColumnInt(0);
}
void IconDatabase::setWasExcludedFromBackup()
{
ASSERT_ICON_SYNC_THREAD();
SQLiteStatement(m_syncDB, "INSERT INTO IconDatabaseInfo (key, value) VALUES ('ExcludedFromBackup', 1)").executeCommand();
}
class ClientWorkItem {
WTF_MAKE_FAST_ALLOCATED;
public:
ClientWorkItem(IconDatabaseClient* client)
: m_client(client)
{ }
virtual void performWork() = 0;
virtual ~ClientWorkItem() { }
protected:
IconDatabaseClient* m_client;
};
class ImportedIconURLForPageURLWorkItem : public ClientWorkItem {
public:
ImportedIconURLForPageURLWorkItem(IconDatabaseClient* client, const String& pageURL)
: ClientWorkItem(client)
, m_pageURL(new String(pageURL.isolatedCopy()))
{ }
virtual ~ImportedIconURLForPageURLWorkItem()
{
delete m_pageURL;
}
virtual void performWork()
{
ASSERT(m_client);
m_client->didImportIconURLForPageURL(*m_pageURL);
m_client = 0;
}
private:
String* m_pageURL;
};
class ImportedIconDataForPageURLWorkItem : public ClientWorkItem {
public:
ImportedIconDataForPageURLWorkItem(IconDatabaseClient* client, const String& pageURL)
: ClientWorkItem(client)
, m_pageURL(new String(pageURL.isolatedCopy()))
{ }
virtual ~ImportedIconDataForPageURLWorkItem()
{
delete m_pageURL;
}
virtual void performWork()
{
ASSERT(m_client);
m_client->didImportIconDataForPageURL(*m_pageURL);
m_client = 0;
}
private:
String* m_pageURL;
};
class RemovedAllIconsWorkItem : public ClientWorkItem {
public:
RemovedAllIconsWorkItem(IconDatabaseClient* client)
: ClientWorkItem(client)
{ }
virtual void performWork()
{
ASSERT(m_client);
m_client->didRemoveAllIcons();
m_client = 0;
}
};
class FinishedURLImport : public ClientWorkItem {
public:
FinishedURLImport(IconDatabaseClient* client)
: ClientWorkItem(client)
{ }
virtual void performWork()
{
ASSERT(m_client);
m_client->didFinishURLImport();
m_client = 0;
}
};
static void performWorkItem(void* context)
{
ClientWorkItem* item = static_cast<ClientWorkItem*>(context);
item->performWork();
delete item;
}
void IconDatabase::dispatchDidImportIconURLForPageURLOnMainThread(const String& pageURL)
{
ASSERT_ICON_SYNC_THREAD();
ImportedIconURLForPageURLWorkItem* work = new ImportedIconURLForPageURLWorkItem(m_client, pageURL);
callOnMainThread(performWorkItem, work);
}
void IconDatabase::dispatchDidImportIconDataForPageURLOnMainThread(const String& pageURL)
{
ASSERT_ICON_SYNC_THREAD();
ImportedIconDataForPageURLWorkItem* work = new ImportedIconDataForPageURLWorkItem(m_client, pageURL);
callOnMainThread(performWorkItem, work);
}
void IconDatabase::dispatchDidRemoveAllIconsOnMainThread()
{
ASSERT_ICON_SYNC_THREAD();
RemovedAllIconsWorkItem* work = new RemovedAllIconsWorkItem(m_client);
callOnMainThread(performWorkItem, work);
}
void IconDatabase::dispatchDidFinishURLImportOnMainThread()
{
ASSERT_ICON_SYNC_THREAD();
FinishedURLImport* work = new FinishedURLImport(m_client);
callOnMainThread(performWorkItem, work);
}
} // namespace WebCore
#endif // ENABLE(ICONDATABASE)
| gpl-2.0 |
sirgatez/Android-Froyo-Kernel-Source-v2.6.32.9 | drivers/video/omap/lcdc.c | 627 | 21156 | /*
* OMAP1 internal LCD controller
*
* Copyright (C) 2004 Nokia Corporation
* Author: Imre Deak <imre.deak@nokia.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include <linux/module.h>
#include <linux/device.h>
#include <linux/interrupt.h>
#include <linux/spinlock.h>
#include <linux/err.h>
#include <linux/mm.h>
#include <linux/fb.h>
#include <linux/dma-mapping.h>
#include <linux/vmalloc.h>
#include <linux/clk.h>
#include <mach/dma.h>
#include <mach/omapfb.h>
#include <asm/mach-types.h>
#include "lcdc.h"
#define MODULE_NAME "lcdc"
#define OMAP_LCDC_BASE 0xfffec000
#define OMAP_LCDC_SIZE 256
#define OMAP_LCDC_IRQ INT_LCD_CTRL
#define OMAP_LCDC_CONTROL (OMAP_LCDC_BASE + 0x00)
#define OMAP_LCDC_TIMING0 (OMAP_LCDC_BASE + 0x04)
#define OMAP_LCDC_TIMING1 (OMAP_LCDC_BASE + 0x08)
#define OMAP_LCDC_TIMING2 (OMAP_LCDC_BASE + 0x0c)
#define OMAP_LCDC_STATUS (OMAP_LCDC_BASE + 0x10)
#define OMAP_LCDC_SUBPANEL (OMAP_LCDC_BASE + 0x14)
#define OMAP_LCDC_LINE_INT (OMAP_LCDC_BASE + 0x18)
#define OMAP_LCDC_DISPLAY_STATUS (OMAP_LCDC_BASE + 0x1c)
#define OMAP_LCDC_STAT_DONE (1 << 0)
#define OMAP_LCDC_STAT_VSYNC (1 << 1)
#define OMAP_LCDC_STAT_SYNC_LOST (1 << 2)
#define OMAP_LCDC_STAT_ABC (1 << 3)
#define OMAP_LCDC_STAT_LINE_INT (1 << 4)
#define OMAP_LCDC_STAT_FUF (1 << 5)
#define OMAP_LCDC_STAT_LOADED_PALETTE (1 << 6)
#define OMAP_LCDC_CTRL_LCD_EN (1 << 0)
#define OMAP_LCDC_CTRL_LCD_TFT (1 << 7)
#define OMAP_LCDC_CTRL_LINE_IRQ_CLR_SEL (1 << 10)
#define OMAP_LCDC_IRQ_VSYNC (1 << 2)
#define OMAP_LCDC_IRQ_DONE (1 << 3)
#define OMAP_LCDC_IRQ_LOADED_PALETTE (1 << 4)
#define OMAP_LCDC_IRQ_LINE_NIRQ (1 << 5)
#define OMAP_LCDC_IRQ_LINE (1 << 6)
#define OMAP_LCDC_IRQ_MASK (((1 << 5) - 1) << 2)
#define MAX_PALETTE_SIZE PAGE_SIZE
enum lcdc_load_mode {
OMAP_LCDC_LOAD_PALETTE,
OMAP_LCDC_LOAD_FRAME,
OMAP_LCDC_LOAD_PALETTE_AND_FRAME
};
static struct omap_lcd_controller {
enum omapfb_update_mode update_mode;
int ext_mode;
unsigned long frame_offset;
int screen_width;
int xres;
int yres;
enum omapfb_color_format color_mode;
int bpp;
void *palette_virt;
dma_addr_t palette_phys;
int palette_code;
int palette_size;
unsigned int irq_mask;
struct completion last_frame_complete;
struct completion palette_load_complete;
struct clk *lcd_ck;
struct omapfb_device *fbdev;
void (*dma_callback)(void *data);
void *dma_callback_data;
int fbmem_allocated;
dma_addr_t vram_phys;
void *vram_virt;
unsigned long vram_size;
} lcdc;
static void inline enable_irqs(int mask)
{
lcdc.irq_mask |= mask;
}
static void inline disable_irqs(int mask)
{
lcdc.irq_mask &= ~mask;
}
static void set_load_mode(enum lcdc_load_mode mode)
{
u32 l;
l = omap_readl(OMAP_LCDC_CONTROL);
l &= ~(3 << 20);
switch (mode) {
case OMAP_LCDC_LOAD_PALETTE:
l |= 1 << 20;
break;
case OMAP_LCDC_LOAD_FRAME:
l |= 2 << 20;
break;
case OMAP_LCDC_LOAD_PALETTE_AND_FRAME:
break;
default:
BUG();
}
omap_writel(l, OMAP_LCDC_CONTROL);
}
static void enable_controller(void)
{
u32 l;
l = omap_readl(OMAP_LCDC_CONTROL);
l |= OMAP_LCDC_CTRL_LCD_EN;
l &= ~OMAP_LCDC_IRQ_MASK;
l |= lcdc.irq_mask | OMAP_LCDC_IRQ_DONE; /* enabled IRQs */
omap_writel(l, OMAP_LCDC_CONTROL);
}
static void disable_controller_async(void)
{
u32 l;
u32 mask;
l = omap_readl(OMAP_LCDC_CONTROL);
mask = OMAP_LCDC_CTRL_LCD_EN | OMAP_LCDC_IRQ_MASK;
/*
* Preserve the DONE mask, since we still want to get the
* final DONE irq. It will be disabled in the IRQ handler.
*/
mask &= ~OMAP_LCDC_IRQ_DONE;
l &= ~mask;
omap_writel(l, OMAP_LCDC_CONTROL);
}
static void disable_controller(void)
{
init_completion(&lcdc.last_frame_complete);
disable_controller_async();
if (!wait_for_completion_timeout(&lcdc.last_frame_complete,
msecs_to_jiffies(500)))
dev_err(lcdc.fbdev->dev, "timeout waiting for FRAME DONE\n");
}
static void reset_controller(u32 status)
{
static unsigned long reset_count;
static unsigned long last_jiffies;
disable_controller_async();
reset_count++;
if (reset_count == 1 || time_after(jiffies, last_jiffies + HZ)) {
dev_err(lcdc.fbdev->dev,
"resetting (status %#010x,reset count %lu)\n",
status, reset_count);
last_jiffies = jiffies;
}
if (reset_count < 100) {
enable_controller();
} else {
reset_count = 0;
dev_err(lcdc.fbdev->dev,
"too many reset attempts, giving up.\n");
}
}
/*
* Configure the LCD DMA according to the current mode specified by parameters
* in lcdc.fbdev and fbdev->var.
*/
static void setup_lcd_dma(void)
{
static const int dma_elem_type[] = {
0,
OMAP_DMA_DATA_TYPE_S8,
OMAP_DMA_DATA_TYPE_S16,
0,
OMAP_DMA_DATA_TYPE_S32,
};
struct omapfb_plane_struct *plane = lcdc.fbdev->fb_info[0]->par;
struct fb_var_screeninfo *var = &lcdc.fbdev->fb_info[0]->var;
unsigned long src;
int esize, xelem, yelem;
src = lcdc.vram_phys + lcdc.frame_offset;
switch (var->rotate) {
case 0:
if (plane->info.mirror || (src & 3) ||
lcdc.color_mode == OMAPFB_COLOR_YUV420 ||
(lcdc.xres & 1))
esize = 2;
else
esize = 4;
xelem = lcdc.xres * lcdc.bpp / 8 / esize;
yelem = lcdc.yres;
break;
case 90:
case 180:
case 270:
if (cpu_is_omap15xx()) {
BUG();
}
esize = 2;
xelem = lcdc.yres * lcdc.bpp / 16;
yelem = lcdc.xres;
break;
default:
BUG();
return;
}
#ifdef VERBOSE
dev_dbg(lcdc.fbdev->dev,
"setup_dma: src %#010lx esize %d xelem %d yelem %d\n",
src, esize, xelem, yelem);
#endif
omap_set_lcd_dma_b1(src, xelem, yelem, dma_elem_type[esize]);
if (!cpu_is_omap15xx()) {
int bpp = lcdc.bpp;
/*
* YUV support is only for external mode when we have the
* YUV window embedded in a 16bpp frame buffer.
*/
if (lcdc.color_mode == OMAPFB_COLOR_YUV420)
bpp = 16;
/* Set virtual xres elem size */
omap_set_lcd_dma_b1_vxres(
lcdc.screen_width * bpp / 8 / esize);
/* Setup transformations */
omap_set_lcd_dma_b1_rotation(var->rotate);
omap_set_lcd_dma_b1_mirror(plane->info.mirror);
}
omap_setup_lcd_dma();
}
static irqreturn_t lcdc_irq_handler(int irq, void *dev_id)
{
u32 status;
status = omap_readl(OMAP_LCDC_STATUS);
if (status & (OMAP_LCDC_STAT_FUF | OMAP_LCDC_STAT_SYNC_LOST))
reset_controller(status);
else {
if (status & OMAP_LCDC_STAT_DONE) {
u32 l;
/*
* Disable IRQ_DONE. The status bit will be cleared
* only when the controller is reenabled and we don't
* want to get more interrupts.
*/
l = omap_readl(OMAP_LCDC_CONTROL);
l &= ~OMAP_LCDC_IRQ_DONE;
omap_writel(l, OMAP_LCDC_CONTROL);
complete(&lcdc.last_frame_complete);
}
if (status & OMAP_LCDC_STAT_LOADED_PALETTE) {
disable_controller_async();
complete(&lcdc.palette_load_complete);
}
}
/*
* Clear these interrupt status bits.
* Sync_lost, FUF bits were cleared by disabling the LCD controller
* LOADED_PALETTE can be cleared this way only in palette only
* load mode. In other load modes it's cleared by disabling the
* controller.
*/
status &= ~(OMAP_LCDC_STAT_VSYNC |
OMAP_LCDC_STAT_LOADED_PALETTE |
OMAP_LCDC_STAT_ABC |
OMAP_LCDC_STAT_LINE_INT);
omap_writel(status, OMAP_LCDC_STATUS);
return IRQ_HANDLED;
}
/*
* Change to a new video mode. We defer this to a later time to avoid any
* flicker and not to mess up the current LCD DMA context. For this we disable
* the LCD controller, which will generate a DONE irq after the last frame has
* been transferred. Then it'll be safe to reconfigure both the LCD controller
* as well as the LCD DMA.
*/
static int omap_lcdc_setup_plane(int plane, int channel_out,
unsigned long offset, int screen_width,
int pos_x, int pos_y, int width, int height,
int color_mode)
{
struct fb_var_screeninfo *var = &lcdc.fbdev->fb_info[0]->var;
struct lcd_panel *panel = lcdc.fbdev->panel;
int rot_x, rot_y;
if (var->rotate == 0) {
rot_x = panel->x_res;
rot_y = panel->y_res;
} else {
rot_x = panel->y_res;
rot_y = panel->x_res;
}
if (plane != 0 || channel_out != 0 || pos_x != 0 || pos_y != 0 ||
width > rot_x || height > rot_y) {
#ifdef VERBOSE
dev_dbg(lcdc.fbdev->dev,
"invalid plane params plane %d pos_x %d pos_y %d "
"w %d h %d\n", plane, pos_x, pos_y, width, height);
#endif
return -EINVAL;
}
lcdc.frame_offset = offset;
lcdc.xres = width;
lcdc.yres = height;
lcdc.screen_width = screen_width;
lcdc.color_mode = color_mode;
switch (color_mode) {
case OMAPFB_COLOR_CLUT_8BPP:
lcdc.bpp = 8;
lcdc.palette_code = 0x3000;
lcdc.palette_size = 512;
break;
case OMAPFB_COLOR_RGB565:
lcdc.bpp = 16;
lcdc.palette_code = 0x4000;
lcdc.palette_size = 32;
break;
case OMAPFB_COLOR_RGB444:
lcdc.bpp = 16;
lcdc.palette_code = 0x4000;
lcdc.palette_size = 32;
break;
case OMAPFB_COLOR_YUV420:
if (lcdc.ext_mode) {
lcdc.bpp = 12;
break;
}
/* fallthrough */
case OMAPFB_COLOR_YUV422:
if (lcdc.ext_mode) {
lcdc.bpp = 16;
break;
}
/* fallthrough */
default:
/* FIXME: other BPPs.
* bpp1: code 0, size 256
* bpp2: code 0x1000 size 256
* bpp4: code 0x2000 size 256
* bpp12: code 0x4000 size 32
*/
dev_dbg(lcdc.fbdev->dev, "invalid color mode %d\n", color_mode);
BUG();
return -1;
}
if (lcdc.ext_mode) {
setup_lcd_dma();
return 0;
}
if (lcdc.update_mode == OMAPFB_AUTO_UPDATE) {
disable_controller();
omap_stop_lcd_dma();
setup_lcd_dma();
enable_controller();
}
return 0;
}
static int omap_lcdc_enable_plane(int plane, int enable)
{
dev_dbg(lcdc.fbdev->dev,
"plane %d enable %d update_mode %d ext_mode %d\n",
plane, enable, lcdc.update_mode, lcdc.ext_mode);
if (plane != OMAPFB_PLANE_GFX)
return -EINVAL;
return 0;
}
/*
* Configure the LCD DMA for a palette load operation and do the palette
* downloading synchronously. We don't use the frame+palette load mode of
* the controller, since the palette can always be downloaded seperately.
*/
static void load_palette(void)
{
u16 *palette;
palette = (u16 *)lcdc.palette_virt;
*(u16 *)palette &= 0x0fff;
*(u16 *)palette |= lcdc.palette_code;
omap_set_lcd_dma_b1(lcdc.palette_phys,
lcdc.palette_size / 4 + 1, 1, OMAP_DMA_DATA_TYPE_S32);
omap_set_lcd_dma_single_transfer(1);
omap_setup_lcd_dma();
init_completion(&lcdc.palette_load_complete);
enable_irqs(OMAP_LCDC_IRQ_LOADED_PALETTE);
set_load_mode(OMAP_LCDC_LOAD_PALETTE);
enable_controller();
if (!wait_for_completion_timeout(&lcdc.palette_load_complete,
msecs_to_jiffies(500)))
dev_err(lcdc.fbdev->dev, "timeout waiting for FRAME DONE\n");
/* The controller gets disabled in the irq handler */
disable_irqs(OMAP_LCDC_IRQ_LOADED_PALETTE);
omap_stop_lcd_dma();
omap_set_lcd_dma_single_transfer(lcdc.ext_mode);
}
/* Used only in internal controller mode */
static int omap_lcdc_setcolreg(u_int regno, u16 red, u16 green, u16 blue,
u16 transp, int update_hw_pal)
{
u16 *palette;
if (lcdc.color_mode != OMAPFB_COLOR_CLUT_8BPP || regno > 255)
return -EINVAL;
palette = (u16 *)lcdc.palette_virt;
palette[regno] &= ~0x0fff;
palette[regno] |= ((red >> 12) << 8) | ((green >> 12) << 4 ) |
(blue >> 12);
if (update_hw_pal) {
disable_controller();
omap_stop_lcd_dma();
load_palette();
setup_lcd_dma();
set_load_mode(OMAP_LCDC_LOAD_FRAME);
enable_controller();
}
return 0;
}
static void calc_ck_div(int is_tft, int pck, int *pck_div)
{
unsigned long lck;
pck = max(1, pck);
lck = clk_get_rate(lcdc.lcd_ck);
*pck_div = (lck + pck - 1) / pck;
if (is_tft)
*pck_div = max(2, *pck_div);
else
*pck_div = max(3, *pck_div);
if (*pck_div > 255) {
/* FIXME: try to adjust logic clock divider as well */
*pck_div = 255;
dev_warn(lcdc.fbdev->dev, "pixclock %d kHz too low.\n",
pck / 1000);
}
}
static void inline setup_regs(void)
{
u32 l;
struct lcd_panel *panel = lcdc.fbdev->panel;
int is_tft = panel->config & OMAP_LCDC_PANEL_TFT;
unsigned long lck;
int pcd;
l = omap_readl(OMAP_LCDC_CONTROL);
l &= ~OMAP_LCDC_CTRL_LCD_TFT;
l |= is_tft ? OMAP_LCDC_CTRL_LCD_TFT : 0;
#ifdef CONFIG_MACH_OMAP_PALMTE
/* FIXME:if (machine_is_omap_palmte()) { */
/* PalmTE uses alternate TFT setting in 8BPP mode */
l |= (is_tft && panel->bpp == 8) ? 0x810000 : 0;
/* } */
#endif
omap_writel(l, OMAP_LCDC_CONTROL);
l = omap_readl(OMAP_LCDC_TIMING2);
l &= ~(((1 << 6) - 1) << 20);
l |= (panel->config & OMAP_LCDC_SIGNAL_MASK) << 20;
omap_writel(l, OMAP_LCDC_TIMING2);
l = panel->x_res - 1;
l |= (panel->hsw - 1) << 10;
l |= (panel->hfp - 1) << 16;
l |= (panel->hbp - 1) << 24;
omap_writel(l, OMAP_LCDC_TIMING0);
l = panel->y_res - 1;
l |= (panel->vsw - 1) << 10;
l |= panel->vfp << 16;
l |= panel->vbp << 24;
omap_writel(l, OMAP_LCDC_TIMING1);
l = omap_readl(OMAP_LCDC_TIMING2);
l &= ~0xff;
lck = clk_get_rate(lcdc.lcd_ck);
if (!panel->pcd)
calc_ck_div(is_tft, panel->pixel_clock * 1000, &pcd);
else {
dev_warn(lcdc.fbdev->dev,
"Pixel clock divider value is obsolete.\n"
"Try to set pixel_clock to %lu and pcd to 0 "
"in drivers/video/omap/lcd_%s.c and submit a patch.\n",
lck / panel->pcd / 1000, panel->name);
pcd = panel->pcd;
}
l |= pcd & 0xff;
l |= panel->acb << 8;
omap_writel(l, OMAP_LCDC_TIMING2);
/* update panel info with the exact clock */
panel->pixel_clock = lck / pcd / 1000;
}
/*
* Configure the LCD controller, download the color palette and start a looped
* DMA transfer of the frame image data. Called only in internal
* controller mode.
*/
static int omap_lcdc_set_update_mode(enum omapfb_update_mode mode)
{
int r = 0;
if (mode != lcdc.update_mode) {
switch (mode) {
case OMAPFB_AUTO_UPDATE:
setup_regs();
load_palette();
/* Setup and start LCD DMA */
setup_lcd_dma();
set_load_mode(OMAP_LCDC_LOAD_FRAME);
enable_irqs(OMAP_LCDC_IRQ_DONE);
/* This will start the actual DMA transfer */
enable_controller();
lcdc.update_mode = mode;
break;
case OMAPFB_UPDATE_DISABLED:
disable_controller();
omap_stop_lcd_dma();
lcdc.update_mode = mode;
break;
default:
r = -EINVAL;
}
}
return r;
}
static enum omapfb_update_mode omap_lcdc_get_update_mode(void)
{
return lcdc.update_mode;
}
/* PM code called only in internal controller mode */
static void omap_lcdc_suspend(void)
{
if (lcdc.update_mode == OMAPFB_AUTO_UPDATE) {
disable_controller();
omap_stop_lcd_dma();
}
}
static void omap_lcdc_resume(void)
{
if (lcdc.update_mode == OMAPFB_AUTO_UPDATE) {
setup_regs();
load_palette();
setup_lcd_dma();
set_load_mode(OMAP_LCDC_LOAD_FRAME);
enable_irqs(OMAP_LCDC_IRQ_DONE);
enable_controller();
}
}
static void omap_lcdc_get_caps(int plane, struct omapfb_caps *caps)
{
return;
}
int omap_lcdc_set_dma_callback(void (*callback)(void *data), void *data)
{
BUG_ON(callback == NULL);
if (lcdc.dma_callback)
return -EBUSY;
else {
lcdc.dma_callback = callback;
lcdc.dma_callback_data = data;
}
return 0;
}
EXPORT_SYMBOL(omap_lcdc_set_dma_callback);
void omap_lcdc_free_dma_callback(void)
{
lcdc.dma_callback = NULL;
}
EXPORT_SYMBOL(omap_lcdc_free_dma_callback);
static void lcdc_dma_handler(u16 status, void *data)
{
if (lcdc.dma_callback)
lcdc.dma_callback(lcdc.dma_callback_data);
}
static int mmap_kern(void)
{
struct vm_struct *kvma;
struct vm_area_struct vma;
pgprot_t pgprot;
unsigned long vaddr;
kvma = get_vm_area(lcdc.vram_size, VM_IOREMAP);
if (kvma == NULL) {
dev_err(lcdc.fbdev->dev, "can't get kernel vm area\n");
return -ENOMEM;
}
vma.vm_mm = &init_mm;
vaddr = (unsigned long)kvma->addr;
vma.vm_start = vaddr;
vma.vm_end = vaddr + lcdc.vram_size;
pgprot = pgprot_writecombine(pgprot_kernel);
if (io_remap_pfn_range(&vma, vaddr,
lcdc.vram_phys >> PAGE_SHIFT,
lcdc.vram_size, pgprot) < 0) {
dev_err(lcdc.fbdev->dev, "kernel mmap for FB memory failed\n");
return -EAGAIN;
}
lcdc.vram_virt = (void *)vaddr;
return 0;
}
static void unmap_kern(void)
{
vunmap(lcdc.vram_virt);
}
static int alloc_palette_ram(void)
{
lcdc.palette_virt = dma_alloc_writecombine(lcdc.fbdev->dev,
MAX_PALETTE_SIZE, &lcdc.palette_phys, GFP_KERNEL);
if (lcdc.palette_virt == NULL) {
dev_err(lcdc.fbdev->dev, "failed to alloc palette memory\n");
return -ENOMEM;
}
memset(lcdc.palette_virt, 0, MAX_PALETTE_SIZE);
return 0;
}
static void free_palette_ram(void)
{
dma_free_writecombine(lcdc.fbdev->dev, MAX_PALETTE_SIZE,
lcdc.palette_virt, lcdc.palette_phys);
}
static int alloc_fbmem(struct omapfb_mem_region *region)
{
int bpp;
int frame_size;
struct lcd_panel *panel = lcdc.fbdev->panel;
bpp = panel->bpp;
if (bpp == 12)
bpp = 16;
frame_size = PAGE_ALIGN(panel->x_res * bpp / 8 * panel->y_res);
if (region->size > frame_size)
frame_size = region->size;
lcdc.vram_size = frame_size;
lcdc.vram_virt = dma_alloc_writecombine(lcdc.fbdev->dev,
lcdc.vram_size, &lcdc.vram_phys, GFP_KERNEL);
if (lcdc.vram_virt == NULL) {
dev_err(lcdc.fbdev->dev, "unable to allocate FB DMA memory\n");
return -ENOMEM;
}
region->size = frame_size;
region->paddr = lcdc.vram_phys;
region->vaddr = lcdc.vram_virt;
region->alloc = 1;
memset(lcdc.vram_virt, 0, lcdc.vram_size);
return 0;
}
static void free_fbmem(void)
{
dma_free_writecombine(lcdc.fbdev->dev, lcdc.vram_size,
lcdc.vram_virt, lcdc.vram_phys);
}
static int setup_fbmem(struct omapfb_mem_desc *req_md)
{
int r;
if (!req_md->region_cnt) {
dev_err(lcdc.fbdev->dev, "no memory regions defined\n");
return -EINVAL;
}
if (req_md->region_cnt > 1) {
dev_err(lcdc.fbdev->dev, "only one plane is supported\n");
req_md->region_cnt = 1;
}
if (req_md->region[0].paddr == 0) {
lcdc.fbmem_allocated = 1;
if ((r = alloc_fbmem(&req_md->region[0])) < 0)
return r;
return 0;
}
lcdc.vram_phys = req_md->region[0].paddr;
lcdc.vram_size = req_md->region[0].size;
if ((r = mmap_kern()) < 0)
return r;
dev_dbg(lcdc.fbdev->dev, "vram at %08x size %08lx mapped to 0x%p\n",
lcdc.vram_phys, lcdc.vram_size, lcdc.vram_virt);
return 0;
}
static void cleanup_fbmem(void)
{
if (lcdc.fbmem_allocated)
free_fbmem();
else
unmap_kern();
}
static int omap_lcdc_init(struct omapfb_device *fbdev, int ext_mode,
struct omapfb_mem_desc *req_vram)
{
int r;
u32 l;
int rate;
struct clk *tc_ck;
lcdc.irq_mask = 0;
lcdc.fbdev = fbdev;
lcdc.ext_mode = ext_mode;
l = 0;
omap_writel(l, OMAP_LCDC_CONTROL);
/* FIXME:
* According to errata some platforms have a clock rate limitiation
*/
lcdc.lcd_ck = clk_get(fbdev->dev, "lcd_ck");
if (IS_ERR(lcdc.lcd_ck)) {
dev_err(fbdev->dev, "unable to access LCD clock\n");
r = PTR_ERR(lcdc.lcd_ck);
goto fail0;
}
tc_ck = clk_get(fbdev->dev, "tc_ck");
if (IS_ERR(tc_ck)) {
dev_err(fbdev->dev, "unable to access TC clock\n");
r = PTR_ERR(tc_ck);
goto fail1;
}
rate = clk_get_rate(tc_ck);
clk_put(tc_ck);
if (machine_is_ams_delta())
rate /= 4;
if (machine_is_omap_h3())
rate /= 3;
r = clk_set_rate(lcdc.lcd_ck, rate);
if (r) {
dev_err(fbdev->dev, "failed to adjust LCD rate\n");
goto fail1;
}
clk_enable(lcdc.lcd_ck);
r = request_irq(OMAP_LCDC_IRQ, lcdc_irq_handler, 0, MODULE_NAME, fbdev);
if (r) {
dev_err(fbdev->dev, "unable to get IRQ\n");
goto fail2;
}
r = omap_request_lcd_dma(lcdc_dma_handler, NULL);
if (r) {
dev_err(fbdev->dev, "unable to get LCD DMA\n");
goto fail3;
}
omap_set_lcd_dma_single_transfer(ext_mode);
omap_set_lcd_dma_ext_controller(ext_mode);
if (!ext_mode)
if ((r = alloc_palette_ram()) < 0)
goto fail4;
if ((r = setup_fbmem(req_vram)) < 0)
goto fail5;
pr_info("omapfb: LCDC initialized\n");
return 0;
fail5:
if (!ext_mode)
free_palette_ram();
fail4:
omap_free_lcd_dma();
fail3:
free_irq(OMAP_LCDC_IRQ, lcdc.fbdev);
fail2:
clk_disable(lcdc.lcd_ck);
fail1:
clk_put(lcdc.lcd_ck);
fail0:
return r;
}
static void omap_lcdc_cleanup(void)
{
if (!lcdc.ext_mode)
free_palette_ram();
cleanup_fbmem();
omap_free_lcd_dma();
free_irq(OMAP_LCDC_IRQ, lcdc.fbdev);
clk_disable(lcdc.lcd_ck);
clk_put(lcdc.lcd_ck);
}
const struct lcd_ctrl omap1_int_ctrl = {
.name = "internal",
.init = omap_lcdc_init,
.cleanup = omap_lcdc_cleanup,
.get_caps = omap_lcdc_get_caps,
.set_update_mode = omap_lcdc_set_update_mode,
.get_update_mode = omap_lcdc_get_update_mode,
.update_window = NULL,
.suspend = omap_lcdc_suspend,
.resume = omap_lcdc_resume,
.setup_plane = omap_lcdc_setup_plane,
.enable_plane = omap_lcdc_enable_plane,
.setcolreg = omap_lcdc_setcolreg,
};
| gpl-2.0 |
060411121/zcl_linux | security/selinux/netport.c | 1651 | 6770 | /*
* Network port table
*
* SELinux must keep a mapping of network ports to labels/SIDs. This
* mapping is maintained as part of the normal policy but a fast cache is
* needed to reduce the lookup overhead.
*
* Author: Paul Moore <paul@paul-moore.com>
*
* This code is heavily based on the "netif" concept originally developed by
* James Morris <jmorris@redhat.com>
* (see security/selinux/netif.c for more information)
*
*/
/*
* (c) Copyright Hewlett-Packard Development Company, L.P., 2008
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/types.h>
#include <linux/rcupdate.h>
#include <linux/list.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/in.h>
#include <linux/in6.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <net/ip.h>
#include <net/ipv6.h>
#include "netport.h"
#include "objsec.h"
#define SEL_NETPORT_HASH_SIZE 256
#define SEL_NETPORT_HASH_BKT_LIMIT 16
struct sel_netport_bkt {
int size;
struct list_head list;
};
struct sel_netport {
struct netport_security_struct psec;
struct list_head list;
struct rcu_head rcu;
};
/* NOTE: we are using a combined hash table for both IPv4 and IPv6, the reason
* for this is that I suspect most users will not make heavy use of both
* address families at the same time so one table will usually end up wasted,
* if this becomes a problem we can always add a hash table for each address
* family later */
static LIST_HEAD(sel_netport_list);
static DEFINE_SPINLOCK(sel_netport_lock);
static struct sel_netport_bkt sel_netport_hash[SEL_NETPORT_HASH_SIZE];
/**
* sel_netport_hashfn - Hashing function for the port table
* @pnum: port number
*
* Description:
* This is the hashing function for the port table, it returns the bucket
* number for the given port.
*
*/
static unsigned int sel_netport_hashfn(u16 pnum)
{
return (pnum & (SEL_NETPORT_HASH_SIZE - 1));
}
/**
* sel_netport_find - Search for a port record
* @protocol: protocol
* @port: pnum
*
* Description:
* Search the network port table and return the matching record. If an entry
* can not be found in the table return NULL.
*
*/
static struct sel_netport *sel_netport_find(u8 protocol, u16 pnum)
{
unsigned int idx;
struct sel_netport *port;
idx = sel_netport_hashfn(pnum);
list_for_each_entry_rcu(port, &sel_netport_hash[idx].list, list)
if (port->psec.port == pnum && port->psec.protocol == protocol)
return port;
return NULL;
}
/**
* sel_netport_insert - Insert a new port into the table
* @port: the new port record
*
* Description:
* Add a new port record to the network address hash table.
*
*/
static void sel_netport_insert(struct sel_netport *port)
{
unsigned int idx;
/* we need to impose a limit on the growth of the hash table so check
* this bucket to make sure it is within the specified bounds */
idx = sel_netport_hashfn(port->psec.port);
list_add_rcu(&port->list, &sel_netport_hash[idx].list);
if (sel_netport_hash[idx].size == SEL_NETPORT_HASH_BKT_LIMIT) {
struct sel_netport *tail;
tail = list_entry(
rcu_dereference_protected(
sel_netport_hash[idx].list.prev,
lockdep_is_held(&sel_netport_lock)),
struct sel_netport, list);
list_del_rcu(&tail->list);
kfree_rcu(tail, rcu);
} else
sel_netport_hash[idx].size++;
}
/**
* sel_netport_sid_slow - Lookup the SID of a network address using the policy
* @protocol: protocol
* @pnum: port
* @sid: port SID
*
* Description:
* This function determines the SID of a network port by quering the security
* policy. The result is added to the network port table to speedup future
* queries. Returns zero on success, negative values on failure.
*
*/
static int sel_netport_sid_slow(u8 protocol, u16 pnum, u32 *sid)
{
int ret = -ENOMEM;
struct sel_netport *port;
struct sel_netport *new = NULL;
spin_lock_bh(&sel_netport_lock);
port = sel_netport_find(protocol, pnum);
if (port != NULL) {
*sid = port->psec.sid;
spin_unlock_bh(&sel_netport_lock);
return 0;
}
new = kzalloc(sizeof(*new), GFP_ATOMIC);
if (new == NULL)
goto out;
ret = security_port_sid(protocol, pnum, sid);
if (ret != 0)
goto out;
new->psec.port = pnum;
new->psec.protocol = protocol;
new->psec.sid = *sid;
sel_netport_insert(new);
out:
spin_unlock_bh(&sel_netport_lock);
if (unlikely(ret)) {
printk(KERN_WARNING
"SELinux: failure in sel_netport_sid_slow(),"
" unable to determine network port label\n");
kfree(new);
}
return ret;
}
/**
* sel_netport_sid - Lookup the SID of a network port
* @protocol: protocol
* @pnum: port
* @sid: port SID
*
* Description:
* This function determines the SID of a network port using the fastest method
* possible. First the port table is queried, but if an entry can't be found
* then the policy is queried and the result is added to the table to speedup
* future queries. Returns zero on success, negative values on failure.
*
*/
int sel_netport_sid(u8 protocol, u16 pnum, u32 *sid)
{
struct sel_netport *port;
rcu_read_lock();
port = sel_netport_find(protocol, pnum);
if (port != NULL) {
*sid = port->psec.sid;
rcu_read_unlock();
return 0;
}
rcu_read_unlock();
return sel_netport_sid_slow(protocol, pnum, sid);
}
/**
* sel_netport_flush - Flush the entire network port table
*
* Description:
* Remove all entries from the network address table.
*
*/
static void sel_netport_flush(void)
{
unsigned int idx;
struct sel_netport *port, *port_tmp;
spin_lock_bh(&sel_netport_lock);
for (idx = 0; idx < SEL_NETPORT_HASH_SIZE; idx++) {
list_for_each_entry_safe(port, port_tmp,
&sel_netport_hash[idx].list, list) {
list_del_rcu(&port->list);
kfree_rcu(port, rcu);
}
sel_netport_hash[idx].size = 0;
}
spin_unlock_bh(&sel_netport_lock);
}
static int sel_netport_avc_callback(u32 event)
{
if (event == AVC_CALLBACK_RESET) {
sel_netport_flush();
synchronize_net();
}
return 0;
}
static __init int sel_netport_init(void)
{
int iter;
int ret;
if (!selinux_enabled)
return 0;
for (iter = 0; iter < SEL_NETPORT_HASH_SIZE; iter++) {
INIT_LIST_HEAD(&sel_netport_hash[iter].list);
sel_netport_hash[iter].size = 0;
}
ret = avc_add_callback(sel_netport_avc_callback, AVC_CALLBACK_RESET);
if (ret != 0)
panic("avc_add_callback() failed, error %d\n", ret);
return ret;
}
__initcall(sel_netport_init);
| gpl-2.0 |
Kernel-Saram/CLUSTER_Kernel_VR | kernel/kexec.c | 2163 | 39693 | /*
* kexec.c - kexec system call
* Copyright (C) 2002-2004 Eric Biederman <ebiederm@xmission.com>
*
* This source code is licensed under the GNU General Public License,
* Version 2. See the file COPYING for more details.
*/
#include <linux/capability.h>
#include <linux/mm.h>
#include <linux/file.h>
#include <linux/slab.h>
#include <linux/fs.h>
#include <linux/kexec.h>
#include <linux/mutex.h>
#include <linux/list.h>
#include <linux/highmem.h>
#include <linux/syscalls.h>
#include <linux/reboot.h>
#include <linux/ioport.h>
#include <linux/hardirq.h>
#include <linux/elf.h>
#include <linux/elfcore.h>
#include <generated/utsrelease.h>
#include <linux/utsname.h>
#include <linux/numa.h>
#include <linux/suspend.h>
#include <linux/device.h>
#include <linux/freezer.h>
#include <linux/pm.h>
#include <linux/cpu.h>
#include <linux/console.h>
#include <linux/vmalloc.h>
#include <linux/swap.h>
#include <linux/kmsg_dump.h>
#include <linux/syscore_ops.h>
#include <asm/page.h>
#include <asm/uaccess.h>
#include <asm/io.h>
#include <asm/system.h>
#include <asm/sections.h>
/* Per cpu memory for storing cpu states in case of system crash. */
note_buf_t __percpu *crash_notes;
/* vmcoreinfo stuff */
static unsigned char vmcoreinfo_data[VMCOREINFO_BYTES];
u32 vmcoreinfo_note[VMCOREINFO_NOTE_SIZE/4];
size_t vmcoreinfo_size;
size_t vmcoreinfo_max_size = sizeof(vmcoreinfo_data);
/* Location of the reserved area for the crash kernel */
struct resource crashk_res = {
.name = "Crash kernel",
.start = 0,
.end = 0,
.flags = IORESOURCE_BUSY | IORESOURCE_MEM
};
int kexec_should_crash(struct task_struct *p)
{
if (in_interrupt() || !p->pid || is_global_init(p) || panic_on_oops)
return 1;
return 0;
}
/*
* When kexec transitions to the new kernel there is a one-to-one
* mapping between physical and virtual addresses. On processors
* where you can disable the MMU this is trivial, and easy. For
* others it is still a simple predictable page table to setup.
*
* In that environment kexec copies the new kernel to its final
* resting place. This means I can only support memory whose
* physical address can fit in an unsigned long. In particular
* addresses where (pfn << PAGE_SHIFT) > ULONG_MAX cannot be handled.
* If the assembly stub has more restrictive requirements
* KEXEC_SOURCE_MEMORY_LIMIT and KEXEC_DEST_MEMORY_LIMIT can be
* defined more restrictively in <asm/kexec.h>.
*
* The code for the transition from the current kernel to the
* the new kernel is placed in the control_code_buffer, whose size
* is given by KEXEC_CONTROL_PAGE_SIZE. In the best case only a single
* page of memory is necessary, but some architectures require more.
* Because this memory must be identity mapped in the transition from
* virtual to physical addresses it must live in the range
* 0 - TASK_SIZE, as only the user space mappings are arbitrarily
* modifiable.
*
* The assembly stub in the control code buffer is passed a linked list
* of descriptor pages detailing the source pages of the new kernel,
* and the destination addresses of those source pages. As this data
* structure is not used in the context of the current OS, it must
* be self-contained.
*
* The code has been made to work with highmem pages and will use a
* destination page in its final resting place (if it happens
* to allocate it). The end product of this is that most of the
* physical address space, and most of RAM can be used.
*
* Future directions include:
* - allocating a page table with the control code buffer identity
* mapped, to simplify machine_kexec and make kexec_on_panic more
* reliable.
*/
/*
* KIMAGE_NO_DEST is an impossible destination address..., for
* allocating pages whose destination address we do not care about.
*/
#define KIMAGE_NO_DEST (-1UL)
static int kimage_is_destination_range(struct kimage *image,
unsigned long start, unsigned long end);
static struct page *kimage_alloc_page(struct kimage *image,
gfp_t gfp_mask,
unsigned long dest);
static int do_kimage_alloc(struct kimage **rimage, unsigned long entry,
unsigned long nr_segments,
struct kexec_segment __user *segments)
{
size_t segment_bytes;
struct kimage *image;
unsigned long i;
int result;
/* Allocate a controlling structure */
result = -ENOMEM;
image = kzalloc(sizeof(*image), GFP_KERNEL);
if (!image)
goto out;
image->head = 0;
image->entry = &image->head;
image->last_entry = &image->head;
image->control_page = ~0; /* By default this does not apply */
image->start = entry;
image->type = KEXEC_TYPE_DEFAULT;
/* Initialize the list of control pages */
INIT_LIST_HEAD(&image->control_pages);
/* Initialize the list of destination pages */
INIT_LIST_HEAD(&image->dest_pages);
/* Initialize the list of unusable pages */
INIT_LIST_HEAD(&image->unuseable_pages);
/* Read in the segments */
image->nr_segments = nr_segments;
segment_bytes = nr_segments * sizeof(*segments);
result = copy_from_user(image->segment, segments, segment_bytes);
if (result) {
result = -EFAULT;
goto out;
}
/*
* Verify we have good destination addresses. The caller is
* responsible for making certain we don't attempt to load
* the new image into invalid or reserved areas of RAM. This
* just verifies it is an address we can use.
*
* Since the kernel does everything in page size chunks ensure
* the destination addresses are page aligned. Too many
* special cases crop of when we don't do this. The most
* insidious is getting overlapping destination addresses
* simply because addresses are changed to page size
* granularity.
*/
result = -EADDRNOTAVAIL;
for (i = 0; i < nr_segments; i++) {
unsigned long mstart, mend;
mstart = image->segment[i].mem;
mend = mstart + image->segment[i].memsz;
if ((mstart & ~PAGE_MASK) || (mend & ~PAGE_MASK))
goto out;
if (mend >= KEXEC_DESTINATION_MEMORY_LIMIT)
goto out;
}
/* Verify our destination addresses do not overlap.
* If we alloed overlapping destination addresses
* through very weird things can happen with no
* easy explanation as one segment stops on another.
*/
result = -EINVAL;
for (i = 0; i < nr_segments; i++) {
unsigned long mstart, mend;
unsigned long j;
mstart = image->segment[i].mem;
mend = mstart + image->segment[i].memsz;
for (j = 0; j < i; j++) {
unsigned long pstart, pend;
pstart = image->segment[j].mem;
pend = pstart + image->segment[j].memsz;
/* Do the segments overlap ? */
if ((mend > pstart) && (mstart < pend))
goto out;
}
}
/* Ensure our buffer sizes are strictly less than
* our memory sizes. This should always be the case,
* and it is easier to check up front than to be surprised
* later on.
*/
result = -EINVAL;
for (i = 0; i < nr_segments; i++) {
if (image->segment[i].bufsz > image->segment[i].memsz)
goto out;
}
result = 0;
out:
if (result == 0)
*rimage = image;
else
kfree(image);
return result;
}
static int kimage_normal_alloc(struct kimage **rimage, unsigned long entry,
unsigned long nr_segments,
struct kexec_segment __user *segments)
{
int result;
struct kimage *image;
/* Allocate and initialize a controlling structure */
image = NULL;
result = do_kimage_alloc(&image, entry, nr_segments, segments);
if (result)
goto out;
*rimage = image;
/*
* Find a location for the control code buffer, and add it
* the vector of segments so that it's pages will also be
* counted as destination pages.
*/
result = -ENOMEM;
image->control_code_page = kimage_alloc_control_pages(image,
get_order(KEXEC_CONTROL_PAGE_SIZE));
if (!image->control_code_page) {
printk(KERN_ERR "Could not allocate control_code_buffer\n");
goto out;
}
image->swap_page = kimage_alloc_control_pages(image, 0);
if (!image->swap_page) {
printk(KERN_ERR "Could not allocate swap buffer\n");
goto out;
}
result = 0;
out:
if (result == 0)
*rimage = image;
else
kfree(image);
return result;
}
static int kimage_crash_alloc(struct kimage **rimage, unsigned long entry,
unsigned long nr_segments,
struct kexec_segment __user *segments)
{
int result;
struct kimage *image;
unsigned long i;
image = NULL;
/* Verify we have a valid entry point */
if ((entry < crashk_res.start) || (entry > crashk_res.end)) {
result = -EADDRNOTAVAIL;
goto out;
}
/* Allocate and initialize a controlling structure */
result = do_kimage_alloc(&image, entry, nr_segments, segments);
if (result)
goto out;
/* Enable the special crash kernel control page
* allocation policy.
*/
image->control_page = crashk_res.start;
image->type = KEXEC_TYPE_CRASH;
/*
* Verify we have good destination addresses. Normally
* the caller is responsible for making certain we don't
* attempt to load the new image into invalid or reserved
* areas of RAM. But crash kernels are preloaded into a
* reserved area of ram. We must ensure the addresses
* are in the reserved area otherwise preloading the
* kernel could corrupt things.
*/
result = -EADDRNOTAVAIL;
for (i = 0; i < nr_segments; i++) {
unsigned long mstart, mend;
mstart = image->segment[i].mem;
mend = mstart + image->segment[i].memsz - 1;
/* Ensure we are within the crash kernel limits */
if ((mstart < crashk_res.start) || (mend > crashk_res.end))
goto out;
}
/*
* Find a location for the control code buffer, and add
* the vector of segments so that it's pages will also be
* counted as destination pages.
*/
result = -ENOMEM;
image->control_code_page = kimage_alloc_control_pages(image,
get_order(KEXEC_CONTROL_PAGE_SIZE));
if (!image->control_code_page) {
printk(KERN_ERR "Could not allocate control_code_buffer\n");
goto out;
}
result = 0;
out:
if (result == 0)
*rimage = image;
else
kfree(image);
return result;
}
static int kimage_is_destination_range(struct kimage *image,
unsigned long start,
unsigned long end)
{
unsigned long i;
for (i = 0; i < image->nr_segments; i++) {
unsigned long mstart, mend;
mstart = image->segment[i].mem;
mend = mstart + image->segment[i].memsz;
if ((end > mstart) && (start < mend))
return 1;
}
return 0;
}
static struct page *kimage_alloc_pages(gfp_t gfp_mask, unsigned int order)
{
struct page *pages;
pages = alloc_pages(gfp_mask, order);
if (pages) {
unsigned int count, i;
pages->mapping = NULL;
set_page_private(pages, order);
count = 1 << order;
for (i = 0; i < count; i++)
SetPageReserved(pages + i);
}
return pages;
}
static void kimage_free_pages(struct page *page)
{
unsigned int order, count, i;
order = page_private(page);
count = 1 << order;
for (i = 0; i < count; i++)
ClearPageReserved(page + i);
__free_pages(page, order);
}
static void kimage_free_page_list(struct list_head *list)
{
struct list_head *pos, *next;
list_for_each_safe(pos, next, list) {
struct page *page;
page = list_entry(pos, struct page, lru);
list_del(&page->lru);
kimage_free_pages(page);
}
}
static struct page *kimage_alloc_normal_control_pages(struct kimage *image,
unsigned int order)
{
/* Control pages are special, they are the intermediaries
* that are needed while we copy the rest of the pages
* to their final resting place. As such they must
* not conflict with either the destination addresses
* or memory the kernel is already using.
*
* The only case where we really need more than one of
* these are for architectures where we cannot disable
* the MMU and must instead generate an identity mapped
* page table for all of the memory.
*
* At worst this runs in O(N) of the image size.
*/
struct list_head extra_pages;
struct page *pages;
unsigned int count;
count = 1 << order;
INIT_LIST_HEAD(&extra_pages);
/* Loop while I can allocate a page and the page allocated
* is a destination page.
*/
do {
unsigned long pfn, epfn, addr, eaddr;
pages = kimage_alloc_pages(GFP_KERNEL, order);
if (!pages)
break;
pfn = page_to_pfn(pages);
epfn = pfn + count;
addr = pfn << PAGE_SHIFT;
eaddr = epfn << PAGE_SHIFT;
if ((epfn >= (KEXEC_CONTROL_MEMORY_LIMIT >> PAGE_SHIFT)) ||
kimage_is_destination_range(image, addr, eaddr)) {
list_add(&pages->lru, &extra_pages);
pages = NULL;
}
} while (!pages);
if (pages) {
/* Remember the allocated page... */
list_add(&pages->lru, &image->control_pages);
/* Because the page is already in it's destination
* location we will never allocate another page at
* that address. Therefore kimage_alloc_pages
* will not return it (again) and we don't need
* to give it an entry in image->segment[].
*/
}
/* Deal with the destination pages I have inadvertently allocated.
*
* Ideally I would convert multi-page allocations into single
* page allocations, and add everything to image->dest_pages.
*
* For now it is simpler to just free the pages.
*/
kimage_free_page_list(&extra_pages);
return pages;
}
static struct page *kimage_alloc_crash_control_pages(struct kimage *image,
unsigned int order)
{
/* Control pages are special, they are the intermediaries
* that are needed while we copy the rest of the pages
* to their final resting place. As such they must
* not conflict with either the destination addresses
* or memory the kernel is already using.
*
* Control pages are also the only pags we must allocate
* when loading a crash kernel. All of the other pages
* are specified by the segments and we just memcpy
* into them directly.
*
* The only case where we really need more than one of
* these are for architectures where we cannot disable
* the MMU and must instead generate an identity mapped
* page table for all of the memory.
*
* Given the low demand this implements a very simple
* allocator that finds the first hole of the appropriate
* size in the reserved memory region, and allocates all
* of the memory up to and including the hole.
*/
unsigned long hole_start, hole_end, size;
struct page *pages;
pages = NULL;
size = (1 << order) << PAGE_SHIFT;
hole_start = (image->control_page + (size - 1)) & ~(size - 1);
hole_end = hole_start + size - 1;
while (hole_end <= crashk_res.end) {
unsigned long i;
if (hole_end > KEXEC_CONTROL_MEMORY_LIMIT)
break;
if (hole_end > crashk_res.end)
break;
/* See if I overlap any of the segments */
for (i = 0; i < image->nr_segments; i++) {
unsigned long mstart, mend;
mstart = image->segment[i].mem;
mend = mstart + image->segment[i].memsz - 1;
if ((hole_end >= mstart) && (hole_start <= mend)) {
/* Advance the hole to the end of the segment */
hole_start = (mend + (size - 1)) & ~(size - 1);
hole_end = hole_start + size - 1;
break;
}
}
/* If I don't overlap any segments I have found my hole! */
if (i == image->nr_segments) {
pages = pfn_to_page(hole_start >> PAGE_SHIFT);
break;
}
}
if (pages)
image->control_page = hole_end;
return pages;
}
struct page *kimage_alloc_control_pages(struct kimage *image,
unsigned int order)
{
struct page *pages = NULL;
switch (image->type) {
case KEXEC_TYPE_DEFAULT:
pages = kimage_alloc_normal_control_pages(image, order);
break;
case KEXEC_TYPE_CRASH:
pages = kimage_alloc_crash_control_pages(image, order);
break;
}
return pages;
}
static int kimage_add_entry(struct kimage *image, kimage_entry_t entry)
{
if (*image->entry != 0)
image->entry++;
if (image->entry == image->last_entry) {
kimage_entry_t *ind_page;
struct page *page;
page = kimage_alloc_page(image, GFP_KERNEL, KIMAGE_NO_DEST);
if (!page)
return -ENOMEM;
ind_page = page_address(page);
*image->entry = virt_to_phys(ind_page) | IND_INDIRECTION;
image->entry = ind_page;
image->last_entry = ind_page +
((PAGE_SIZE/sizeof(kimage_entry_t)) - 1);
}
*image->entry = entry;
image->entry++;
*image->entry = 0;
return 0;
}
static int kimage_set_destination(struct kimage *image,
unsigned long destination)
{
int result;
destination &= PAGE_MASK;
result = kimage_add_entry(image, destination | IND_DESTINATION);
if (result == 0)
image->destination = destination;
return result;
}
static int kimage_add_page(struct kimage *image, unsigned long page)
{
int result;
page &= PAGE_MASK;
result = kimage_add_entry(image, page | IND_SOURCE);
if (result == 0)
image->destination += PAGE_SIZE;
return result;
}
static void kimage_free_extra_pages(struct kimage *image)
{
/* Walk through and free any extra destination pages I may have */
kimage_free_page_list(&image->dest_pages);
/* Walk through and free any unusable pages I have cached */
kimage_free_page_list(&image->unuseable_pages);
}
static void kimage_terminate(struct kimage *image)
{
if (*image->entry != 0)
image->entry++;
*image->entry = IND_DONE;
}
#define for_each_kimage_entry(image, ptr, entry) \
for (ptr = &image->head; (entry = *ptr) && !(entry & IND_DONE); \
ptr = (entry & IND_INDIRECTION)? \
phys_to_virt((entry & PAGE_MASK)): ptr +1)
static void kimage_free_entry(kimage_entry_t entry)
{
struct page *page;
page = pfn_to_page(entry >> PAGE_SHIFT);
kimage_free_pages(page);
}
static void kimage_free(struct kimage *image)
{
kimage_entry_t *ptr, entry;
kimage_entry_t ind = 0;
if (!image)
return;
kimage_free_extra_pages(image);
for_each_kimage_entry(image, ptr, entry) {
if (entry & IND_INDIRECTION) {
/* Free the previous indirection page */
if (ind & IND_INDIRECTION)
kimage_free_entry(ind);
/* Save this indirection page until we are
* done with it.
*/
ind = entry;
}
else if (entry & IND_SOURCE)
kimage_free_entry(entry);
}
/* Free the final indirection page */
if (ind & IND_INDIRECTION)
kimage_free_entry(ind);
/* Handle any machine specific cleanup */
machine_kexec_cleanup(image);
/* Free the kexec control pages... */
kimage_free_page_list(&image->control_pages);
kfree(image);
}
static kimage_entry_t *kimage_dst_used(struct kimage *image,
unsigned long page)
{
kimage_entry_t *ptr, entry;
unsigned long destination = 0;
for_each_kimage_entry(image, ptr, entry) {
if (entry & IND_DESTINATION)
destination = entry & PAGE_MASK;
else if (entry & IND_SOURCE) {
if (page == destination)
return ptr;
destination += PAGE_SIZE;
}
}
return NULL;
}
static struct page *kimage_alloc_page(struct kimage *image,
gfp_t gfp_mask,
unsigned long destination)
{
/*
* Here we implement safeguards to ensure that a source page
* is not copied to its destination page before the data on
* the destination page is no longer useful.
*
* To do this we maintain the invariant that a source page is
* either its own destination page, or it is not a
* destination page at all.
*
* That is slightly stronger than required, but the proof
* that no problems will not occur is trivial, and the
* implementation is simply to verify.
*
* When allocating all pages normally this algorithm will run
* in O(N) time, but in the worst case it will run in O(N^2)
* time. If the runtime is a problem the data structures can
* be fixed.
*/
struct page *page;
unsigned long addr;
/*
* Walk through the list of destination pages, and see if I
* have a match.
*/
list_for_each_entry(page, &image->dest_pages, lru) {
addr = page_to_pfn(page) << PAGE_SHIFT;
if (addr == destination) {
list_del(&page->lru);
return page;
}
}
page = NULL;
while (1) {
kimage_entry_t *old;
/* Allocate a page, if we run out of memory give up */
page = kimage_alloc_pages(gfp_mask, 0);
if (!page)
return NULL;
/* If the page cannot be used file it away */
if (page_to_pfn(page) >
(KEXEC_SOURCE_MEMORY_LIMIT >> PAGE_SHIFT)) {
list_add(&page->lru, &image->unuseable_pages);
continue;
}
addr = page_to_pfn(page) << PAGE_SHIFT;
/* If it is the destination page we want use it */
if (addr == destination)
break;
/* If the page is not a destination page use it */
if (!kimage_is_destination_range(image, addr,
addr + PAGE_SIZE))
break;
/*
* I know that the page is someones destination page.
* See if there is already a source page for this
* destination page. And if so swap the source pages.
*/
old = kimage_dst_used(image, addr);
if (old) {
/* If so move it */
unsigned long old_addr;
struct page *old_page;
old_addr = *old & PAGE_MASK;
old_page = pfn_to_page(old_addr >> PAGE_SHIFT);
copy_highpage(page, old_page);
*old = addr | (*old & ~PAGE_MASK);
/* The old page I have found cannot be a
* destination page, so return it if it's
* gfp_flags honor the ones passed in.
*/
if (!(gfp_mask & __GFP_HIGHMEM) &&
PageHighMem(old_page)) {
kimage_free_pages(old_page);
continue;
}
addr = old_addr;
page = old_page;
break;
}
else {
/* Place the page on the destination list I
* will use it later.
*/
list_add(&page->lru, &image->dest_pages);
}
}
return page;
}
static int kimage_load_normal_segment(struct kimage *image,
struct kexec_segment *segment)
{
unsigned long maddr;
unsigned long ubytes, mbytes;
int result;
unsigned char __user *buf;
result = 0;
buf = segment->buf;
ubytes = segment->bufsz;
mbytes = segment->memsz;
maddr = segment->mem;
result = kimage_set_destination(image, maddr);
if (result < 0)
goto out;
while (mbytes) {
struct page *page;
char *ptr;
size_t uchunk, mchunk;
page = kimage_alloc_page(image, GFP_HIGHUSER, maddr);
if (!page) {
result = -ENOMEM;
goto out;
}
result = kimage_add_page(image, page_to_pfn(page)
<< PAGE_SHIFT);
if (result < 0)
goto out;
ptr = kmap(page);
/* Start with a clear page */
clear_page(ptr);
ptr += maddr & ~PAGE_MASK;
mchunk = PAGE_SIZE - (maddr & ~PAGE_MASK);
if (mchunk > mbytes)
mchunk = mbytes;
uchunk = mchunk;
if (uchunk > ubytes)
uchunk = ubytes;
result = copy_from_user(ptr, buf, uchunk);
kunmap(page);
if (result) {
result = -EFAULT;
goto out;
}
ubytes -= uchunk;
maddr += mchunk;
buf += mchunk;
mbytes -= mchunk;
}
out:
return result;
}
static int kimage_load_crash_segment(struct kimage *image,
struct kexec_segment *segment)
{
/* For crash dumps kernels we simply copy the data from
* user space to it's destination.
* We do things a page at a time for the sake of kmap.
*/
unsigned long maddr;
unsigned long ubytes, mbytes;
int result;
unsigned char __user *buf;
result = 0;
buf = segment->buf;
ubytes = segment->bufsz;
mbytes = segment->memsz;
maddr = segment->mem;
while (mbytes) {
struct page *page;
char *ptr;
size_t uchunk, mchunk;
page = pfn_to_page(maddr >> PAGE_SHIFT);
if (!page) {
result = -ENOMEM;
goto out;
}
ptr = kmap(page);
ptr += maddr & ~PAGE_MASK;
mchunk = PAGE_SIZE - (maddr & ~PAGE_MASK);
if (mchunk > mbytes)
mchunk = mbytes;
uchunk = mchunk;
if (uchunk > ubytes) {
uchunk = ubytes;
/* Zero the trailing part of the page */
memset(ptr + uchunk, 0, mchunk - uchunk);
}
result = copy_from_user(ptr, buf, uchunk);
kexec_flush_icache_page(page);
kunmap(page);
if (result) {
result = -EFAULT;
goto out;
}
ubytes -= uchunk;
maddr += mchunk;
buf += mchunk;
mbytes -= mchunk;
}
out:
return result;
}
static int kimage_load_segment(struct kimage *image,
struct kexec_segment *segment)
{
int result = -ENOMEM;
switch (image->type) {
case KEXEC_TYPE_DEFAULT:
result = kimage_load_normal_segment(image, segment);
break;
case KEXEC_TYPE_CRASH:
result = kimage_load_crash_segment(image, segment);
break;
}
return result;
}
/*
* Exec Kernel system call: for obvious reasons only root may call it.
*
* This call breaks up into three pieces.
* - A generic part which loads the new kernel from the current
* address space, and very carefully places the data in the
* allocated pages.
*
* - A generic part that interacts with the kernel and tells all of
* the devices to shut down. Preventing on-going dmas, and placing
* the devices in a consistent state so a later kernel can
* reinitialize them.
*
* - A machine specific part that includes the syscall number
* and the copies the image to it's final destination. And
* jumps into the image at entry.
*
* kexec does not sync, or unmount filesystems so if you need
* that to happen you need to do that yourself.
*/
struct kimage *kexec_image;
struct kimage *kexec_crash_image;
static DEFINE_MUTEX(kexec_mutex);
SYSCALL_DEFINE4(kexec_load, unsigned long, entry, unsigned long, nr_segments,
struct kexec_segment __user *, segments, unsigned long, flags)
{
struct kimage **dest_image, *image;
int result;
/* We only trust the superuser with rebooting the system. */
if (!capable(CAP_SYS_BOOT))
return -EPERM;
/*
* Verify we have a legal set of flags
* This leaves us room for future extensions.
*/
if ((flags & KEXEC_FLAGS) != (flags & ~KEXEC_ARCH_MASK))
return -EINVAL;
/* Verify we are on the appropriate architecture */
if (((flags & KEXEC_ARCH_MASK) != KEXEC_ARCH) &&
((flags & KEXEC_ARCH_MASK) != KEXEC_ARCH_DEFAULT))
return -EINVAL;
/* Put an artificial cap on the number
* of segments passed to kexec_load.
*/
if (nr_segments > KEXEC_SEGMENT_MAX)
return -EINVAL;
image = NULL;
result = 0;
/* Because we write directly to the reserved memory
* region when loading crash kernels we need a mutex here to
* prevent multiple crash kernels from attempting to load
* simultaneously, and to prevent a crash kernel from loading
* over the top of a in use crash kernel.
*
* KISS: always take the mutex.
*/
if (!mutex_trylock(&kexec_mutex))
return -EBUSY;
dest_image = &kexec_image;
if (flags & KEXEC_ON_CRASH)
dest_image = &kexec_crash_image;
if (nr_segments > 0) {
unsigned long i;
/* Loading another kernel to reboot into */
if ((flags & KEXEC_ON_CRASH) == 0)
result = kimage_normal_alloc(&image, entry,
nr_segments, segments);
/* Loading another kernel to switch to if this one crashes */
else if (flags & KEXEC_ON_CRASH) {
/* Free any current crash dump kernel before
* we corrupt it.
*/
kimage_free(xchg(&kexec_crash_image, NULL));
result = kimage_crash_alloc(&image, entry,
nr_segments, segments);
}
if (result)
goto out;
if (flags & KEXEC_PRESERVE_CONTEXT)
image->preserve_context = 1;
result = machine_kexec_prepare(image);
if (result)
goto out;
for (i = 0; i < nr_segments; i++) {
result = kimage_load_segment(image, &image->segment[i]);
if (result)
goto out;
}
kimage_terminate(image);
}
/* Install the new kernel, and Uninstall the old */
image = xchg(dest_image, image);
out:
mutex_unlock(&kexec_mutex);
kimage_free(image);
return result;
}
#ifdef CONFIG_COMPAT
asmlinkage long compat_sys_kexec_load(unsigned long entry,
unsigned long nr_segments,
struct compat_kexec_segment __user *segments,
unsigned long flags)
{
struct compat_kexec_segment in;
struct kexec_segment out, __user *ksegments;
unsigned long i, result;
/* Don't allow clients that don't understand the native
* architecture to do anything.
*/
if ((flags & KEXEC_ARCH_MASK) == KEXEC_ARCH_DEFAULT)
return -EINVAL;
if (nr_segments > KEXEC_SEGMENT_MAX)
return -EINVAL;
ksegments = compat_alloc_user_space(nr_segments * sizeof(out));
for (i=0; i < nr_segments; i++) {
result = copy_from_user(&in, &segments[i], sizeof(in));
if (result)
return -EFAULT;
out.buf = compat_ptr(in.buf);
out.bufsz = in.bufsz;
out.mem = in.mem;
out.memsz = in.memsz;
result = copy_to_user(&ksegments[i], &out, sizeof(out));
if (result)
return -EFAULT;
}
return sys_kexec_load(entry, nr_segments, ksegments, flags);
}
#endif
void crash_kexec(struct pt_regs *regs)
{
/* Take the kexec_mutex here to prevent sys_kexec_load
* running on one cpu from replacing the crash kernel
* we are using after a panic on a different cpu.
*
* If the crash kernel was not located in a fixed area
* of memory the xchg(&kexec_crash_image) would be
* sufficient. But since I reuse the memory...
*/
if (mutex_trylock(&kexec_mutex)) {
if (kexec_crash_image) {
struct pt_regs fixed_regs;
kmsg_dump(KMSG_DUMP_KEXEC);
crash_setup_regs(&fixed_regs, regs);
crash_save_vmcoreinfo();
machine_crash_shutdown(&fixed_regs);
machine_kexec(kexec_crash_image);
}
mutex_unlock(&kexec_mutex);
}
}
size_t crash_get_memory_size(void)
{
size_t size = 0;
mutex_lock(&kexec_mutex);
if (crashk_res.end != crashk_res.start)
size = crashk_res.end - crashk_res.start + 1;
mutex_unlock(&kexec_mutex);
return size;
}
void __weak crash_free_reserved_phys_range(unsigned long begin,
unsigned long end)
{
unsigned long addr;
for (addr = begin; addr < end; addr += PAGE_SIZE) {
ClearPageReserved(pfn_to_page(addr >> PAGE_SHIFT));
init_page_count(pfn_to_page(addr >> PAGE_SHIFT));
free_page((unsigned long)__va(addr));
totalram_pages++;
}
}
int crash_shrink_memory(unsigned long new_size)
{
int ret = 0;
unsigned long start, end;
mutex_lock(&kexec_mutex);
if (kexec_crash_image) {
ret = -ENOENT;
goto unlock;
}
start = crashk_res.start;
end = crashk_res.end;
if (new_size >= end - start + 1) {
ret = -EINVAL;
if (new_size == end - start + 1)
ret = 0;
goto unlock;
}
start = roundup(start, PAGE_SIZE);
end = roundup(start + new_size, PAGE_SIZE);
crash_free_reserved_phys_range(end, crashk_res.end);
if ((start == end) && (crashk_res.parent != NULL))
release_resource(&crashk_res);
crashk_res.end = end - 1;
unlock:
mutex_unlock(&kexec_mutex);
return ret;
}
static u32 *append_elf_note(u32 *buf, char *name, unsigned type, void *data,
size_t data_len)
{
struct elf_note note;
note.n_namesz = strlen(name) + 1;
note.n_descsz = data_len;
note.n_type = type;
memcpy(buf, ¬e, sizeof(note));
buf += (sizeof(note) + 3)/4;
memcpy(buf, name, note.n_namesz);
buf += (note.n_namesz + 3)/4;
memcpy(buf, data, note.n_descsz);
buf += (note.n_descsz + 3)/4;
return buf;
}
static void final_note(u32 *buf)
{
struct elf_note note;
note.n_namesz = 0;
note.n_descsz = 0;
note.n_type = 0;
memcpy(buf, ¬e, sizeof(note));
}
void crash_save_cpu(struct pt_regs *regs, int cpu)
{
struct elf_prstatus prstatus;
u32 *buf;
if ((cpu < 0) || (cpu >= nr_cpu_ids))
return;
/* Using ELF notes here is opportunistic.
* I need a well defined structure format
* for the data I pass, and I need tags
* on the data to indicate what information I have
* squirrelled away. ELF notes happen to provide
* all of that, so there is no need to invent something new.
*/
buf = (u32*)per_cpu_ptr(crash_notes, cpu);
if (!buf)
return;
memset(&prstatus, 0, sizeof(prstatus));
prstatus.pr_pid = current->pid;
elf_core_copy_kernel_regs(&prstatus.pr_reg, regs);
buf = append_elf_note(buf, KEXEC_CORE_NOTE_NAME, NT_PRSTATUS,
&prstatus, sizeof(prstatus));
final_note(buf);
}
static int __init crash_notes_memory_init(void)
{
/* Allocate memory for saving cpu registers. */
crash_notes = alloc_percpu(note_buf_t);
if (!crash_notes) {
printk("Kexec: Memory allocation for saving cpu register"
" states failed\n");
return -ENOMEM;
}
return 0;
}
module_init(crash_notes_memory_init)
/*
* parsing the "crashkernel" commandline
*
* this code is intended to be called from architecture specific code
*/
/*
* This function parses command lines in the format
*
* crashkernel=ramsize-range:size[,...][@offset]
*
* The function returns 0 on success and -EINVAL on failure.
*/
static int __init parse_crashkernel_mem(char *cmdline,
unsigned long long system_ram,
unsigned long long *crash_size,
unsigned long long *crash_base)
{
char *cur = cmdline, *tmp;
/* for each entry of the comma-separated list */
do {
unsigned long long start, end = ULLONG_MAX, size;
/* get the start of the range */
start = memparse(cur, &tmp);
if (cur == tmp) {
pr_warning("crashkernel: Memory value expected\n");
return -EINVAL;
}
cur = tmp;
if (*cur != '-') {
pr_warning("crashkernel: '-' expected\n");
return -EINVAL;
}
cur++;
/* if no ':' is here, than we read the end */
if (*cur != ':') {
end = memparse(cur, &tmp);
if (cur == tmp) {
pr_warning("crashkernel: Memory "
"value expected\n");
return -EINVAL;
}
cur = tmp;
if (end <= start) {
pr_warning("crashkernel: end <= start\n");
return -EINVAL;
}
}
if (*cur != ':') {
pr_warning("crashkernel: ':' expected\n");
return -EINVAL;
}
cur++;
size = memparse(cur, &tmp);
if (cur == tmp) {
pr_warning("Memory value expected\n");
return -EINVAL;
}
cur = tmp;
if (size >= system_ram) {
pr_warning("crashkernel: invalid size\n");
return -EINVAL;
}
/* match ? */
if (system_ram >= start && system_ram < end) {
*crash_size = size;
break;
}
} while (*cur++ == ',');
if (*crash_size > 0) {
while (*cur && *cur != ' ' && *cur != '@')
cur++;
if (*cur == '@') {
cur++;
*crash_base = memparse(cur, &tmp);
if (cur == tmp) {
pr_warning("Memory value expected "
"after '@'\n");
return -EINVAL;
}
}
}
return 0;
}
/*
* That function parses "simple" (old) crashkernel command lines like
*
* crashkernel=size[@offset]
*
* It returns 0 on success and -EINVAL on failure.
*/
static int __init parse_crashkernel_simple(char *cmdline,
unsigned long long *crash_size,
unsigned long long *crash_base)
{
char *cur = cmdline;
*crash_size = memparse(cmdline, &cur);
if (cmdline == cur) {
pr_warning("crashkernel: memory value expected\n");
return -EINVAL;
}
if (*cur == '@')
*crash_base = memparse(cur+1, &cur);
return 0;
}
/*
* That function is the entry point for command line parsing and should be
* called from the arch-specific code.
*/
int __init parse_crashkernel(char *cmdline,
unsigned long long system_ram,
unsigned long long *crash_size,
unsigned long long *crash_base)
{
char *p = cmdline, *ck_cmdline = NULL;
char *first_colon, *first_space;
BUG_ON(!crash_size || !crash_base);
*crash_size = 0;
*crash_base = 0;
/* find crashkernel and use the last one if there are more */
p = strstr(p, "crashkernel=");
while (p) {
ck_cmdline = p;
p = strstr(p+1, "crashkernel=");
}
if (!ck_cmdline)
return -EINVAL;
ck_cmdline += 12; /* strlen("crashkernel=") */
/*
* if the commandline contains a ':', then that's the extended
* syntax -- if not, it must be the classic syntax
*/
first_colon = strchr(ck_cmdline, ':');
first_space = strchr(ck_cmdline, ' ');
if (first_colon && (!first_space || first_colon < first_space))
return parse_crashkernel_mem(ck_cmdline, system_ram,
crash_size, crash_base);
else
return parse_crashkernel_simple(ck_cmdline, crash_size,
crash_base);
return 0;
}
void crash_save_vmcoreinfo(void)
{
u32 *buf;
if (!vmcoreinfo_size)
return;
vmcoreinfo_append_str("CRASHTIME=%ld", get_seconds());
buf = (u32 *)vmcoreinfo_note;
buf = append_elf_note(buf, VMCOREINFO_NOTE_NAME, 0, vmcoreinfo_data,
vmcoreinfo_size);
final_note(buf);
}
void vmcoreinfo_append_str(const char *fmt, ...)
{
va_list args;
char buf[0x50];
int r;
va_start(args, fmt);
r = vsnprintf(buf, sizeof(buf), fmt, args);
va_end(args);
if (r + vmcoreinfo_size > vmcoreinfo_max_size)
r = vmcoreinfo_max_size - vmcoreinfo_size;
memcpy(&vmcoreinfo_data[vmcoreinfo_size], buf, r);
vmcoreinfo_size += r;
}
/*
* provide an empty default implementation here -- architecture
* code may override this
*/
void __attribute__ ((weak)) arch_crash_save_vmcoreinfo(void)
{}
unsigned long __attribute__ ((weak)) paddr_vmcoreinfo_note(void)
{
return __pa((unsigned long)(char *)&vmcoreinfo_note);
}
static int __init crash_save_vmcoreinfo_init(void)
{
VMCOREINFO_OSRELEASE(init_uts_ns.name.release);
VMCOREINFO_PAGESIZE(PAGE_SIZE);
VMCOREINFO_SYMBOL(init_uts_ns);
VMCOREINFO_SYMBOL(node_online_map);
VMCOREINFO_SYMBOL(swapper_pg_dir);
VMCOREINFO_SYMBOL(_stext);
VMCOREINFO_SYMBOL(vmlist);
#ifndef CONFIG_NEED_MULTIPLE_NODES
VMCOREINFO_SYMBOL(mem_map);
VMCOREINFO_SYMBOL(contig_page_data);
#endif
#ifdef CONFIG_SPARSEMEM
VMCOREINFO_SYMBOL(mem_section);
VMCOREINFO_LENGTH(mem_section, NR_SECTION_ROOTS);
VMCOREINFO_STRUCT_SIZE(mem_section);
VMCOREINFO_OFFSET(mem_section, section_mem_map);
#endif
VMCOREINFO_STRUCT_SIZE(page);
VMCOREINFO_STRUCT_SIZE(pglist_data);
VMCOREINFO_STRUCT_SIZE(zone);
VMCOREINFO_STRUCT_SIZE(free_area);
VMCOREINFO_STRUCT_SIZE(list_head);
VMCOREINFO_SIZE(nodemask_t);
VMCOREINFO_OFFSET(page, flags);
VMCOREINFO_OFFSET(page, _count);
VMCOREINFO_OFFSET(page, mapping);
VMCOREINFO_OFFSET(page, lru);
VMCOREINFO_OFFSET(pglist_data, node_zones);
VMCOREINFO_OFFSET(pglist_data, nr_zones);
#ifdef CONFIG_FLAT_NODE_MEM_MAP
VMCOREINFO_OFFSET(pglist_data, node_mem_map);
#endif
VMCOREINFO_OFFSET(pglist_data, node_start_pfn);
VMCOREINFO_OFFSET(pglist_data, node_spanned_pages);
VMCOREINFO_OFFSET(pglist_data, node_id);
VMCOREINFO_OFFSET(zone, free_area);
VMCOREINFO_OFFSET(zone, vm_stat);
VMCOREINFO_OFFSET(zone, spanned_pages);
VMCOREINFO_OFFSET(free_area, free_list);
VMCOREINFO_OFFSET(list_head, next);
VMCOREINFO_OFFSET(list_head, prev);
VMCOREINFO_OFFSET(vm_struct, addr);
VMCOREINFO_LENGTH(zone.free_area, MAX_ORDER);
log_buf_kexec_setup();
VMCOREINFO_LENGTH(free_area.free_list, MIGRATE_TYPES);
VMCOREINFO_NUMBER(NR_FREE_PAGES);
VMCOREINFO_NUMBER(PG_lru);
VMCOREINFO_NUMBER(PG_private);
VMCOREINFO_NUMBER(PG_swapcache);
arch_crash_save_vmcoreinfo();
return 0;
}
module_init(crash_save_vmcoreinfo_init)
/*
* Move into place and start executing a preloaded standalone
* executable. If nothing was preloaded return an error.
*/
int kernel_kexec(void)
{
int error = 0;
if (!mutex_trylock(&kexec_mutex))
return -EBUSY;
if (!kexec_image) {
error = -EINVAL;
goto Unlock;
}
#ifdef CONFIG_KEXEC_JUMP
if (kexec_image->preserve_context) {
mutex_lock(&pm_mutex);
pm_prepare_console();
error = freeze_processes();
if (error) {
error = -EBUSY;
goto Restore_console;
}
suspend_console();
error = dpm_suspend_start(PMSG_FREEZE);
if (error)
goto Resume_console;
/* At this point, dpm_suspend_start() has been called,
* but *not* dpm_suspend_noirq(). We *must* call
* dpm_suspend_noirq() now. Otherwise, drivers for
* some devices (e.g. interrupt controllers) become
* desynchronized with the actual state of the
* hardware at resume time, and evil weirdness ensues.
*/
error = dpm_suspend_noirq(PMSG_FREEZE);
if (error)
goto Resume_devices;
error = disable_nonboot_cpus();
if (error)
goto Enable_cpus;
local_irq_disable();
error = syscore_suspend();
if (error)
goto Enable_irqs;
} else
#endif
{
kernel_restart_prepare(NULL);
printk(KERN_EMERG "Starting new kernel\n");
machine_shutdown();
}
machine_kexec(kexec_image);
#ifdef CONFIG_KEXEC_JUMP
if (kexec_image->preserve_context) {
syscore_resume();
Enable_irqs:
local_irq_enable();
Enable_cpus:
enable_nonboot_cpus();
dpm_resume_noirq(PMSG_RESTORE);
Resume_devices:
dpm_resume_end(PMSG_RESTORE);
Resume_console:
resume_console();
thaw_processes();
Restore_console:
pm_restore_console();
mutex_unlock(&pm_mutex);
}
#endif
Unlock:
mutex_unlock(&kexec_mutex);
return error;
}
| gpl-2.0 |
abev66/linux-kernel-vta2-N7 | drivers/misc/sgi-gru/grukservices.c | 2931 | 29833 | /*
* SN Platform GRU Driver
*
* KERNEL SERVICES THAT USE THE GRU
*
* Copyright (c) 2008 Silicon Graphics, Inc. All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; 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/errno.h>
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/spinlock.h>
#include <linux/device.h>
#include <linux/miscdevice.h>
#include <linux/proc_fs.h>
#include <linux/interrupt.h>
#include <linux/uaccess.h>
#include <linux/delay.h>
#include <asm/io_apic.h>
#include "gru.h"
#include "grulib.h"
#include "grutables.h"
#include "grukservices.h"
#include "gru_instructions.h"
#include <asm/uv/uv_hub.h>
/*
* Kernel GRU Usage
*
* The following is an interim algorithm for management of kernel GRU
* resources. This will likely be replaced when we better understand the
* kernel/user requirements.
*
* Blade percpu resources reserved for kernel use. These resources are
* reserved whenever the the kernel context for the blade is loaded. Note
* that the kernel context is not guaranteed to be always available. It is
* loaded on demand & can be stolen by a user if the user demand exceeds the
* kernel demand. The kernel can always reload the kernel context but
* a SLEEP may be required!!!.
*
* Async Overview:
*
* Each blade has one "kernel context" that owns GRU kernel resources
* located on the blade. Kernel drivers use GRU resources in this context
* for sending messages, zeroing memory, etc.
*
* The kernel context is dynamically loaded on demand. If it is not in
* use by the kernel, the kernel context can be unloaded & given to a user.
* The kernel context will be reloaded when needed. This may require that
* a context be stolen from a user.
* NOTE: frequent unloading/reloading of the kernel context is
* expensive. We are depending on batch schedulers, cpusets, sane
* drivers or some other mechanism to prevent the need for frequent
* stealing/reloading.
*
* The kernel context consists of two parts:
* - 1 CB & a few DSRs that are reserved for each cpu on the blade.
* Each cpu has it's own private resources & does not share them
* with other cpus. These resources are used serially, ie,
* locked, used & unlocked on each call to a function in
* grukservices.
* (Now that we have dynamic loading of kernel contexts, I
* may rethink this & allow sharing between cpus....)
*
* - Additional resources can be reserved long term & used directly
* by UV drivers located in the kernel. Drivers using these GRU
* resources can use asynchronous GRU instructions that send
* interrupts on completion.
* - these resources must be explicitly locked/unlocked
* - locked resources prevent (obviously) the kernel
* context from being unloaded.
* - drivers using these resource directly issue their own
* GRU instruction and must wait/check completion.
*
* When these resources are reserved, the caller can optionally
* associate a wait_queue with the resources and use asynchronous
* GRU instructions. When an async GRU instruction completes, the
* driver will do a wakeup on the event.
*
*/
#define ASYNC_HAN_TO_BID(h) ((h) - 1)
#define ASYNC_BID_TO_HAN(b) ((b) + 1)
#define ASYNC_HAN_TO_BS(h) gru_base[ASYNC_HAN_TO_BID(h)]
#define GRU_NUM_KERNEL_CBR 1
#define GRU_NUM_KERNEL_DSR_BYTES 256
#define GRU_NUM_KERNEL_DSR_CL (GRU_NUM_KERNEL_DSR_BYTES / \
GRU_CACHE_LINE_BYTES)
/* GRU instruction attributes for all instructions */
#define IMA IMA_CB_DELAY
/* GRU cacheline size is always 64 bytes - even on arches with 128 byte lines */
#define __gru_cacheline_aligned__ \
__attribute__((__aligned__(GRU_CACHE_LINE_BYTES)))
#define MAGIC 0x1234567887654321UL
/* Default retry count for GRU errors on kernel instructions */
#define EXCEPTION_RETRY_LIMIT 3
/* Status of message queue sections */
#define MQS_EMPTY 0
#define MQS_FULL 1
#define MQS_NOOP 2
/*----------------- RESOURCE MANAGEMENT -------------------------------------*/
/* optimized for x86_64 */
struct message_queue {
union gru_mesqhead head __gru_cacheline_aligned__; /* CL 0 */
int qlines; /* DW 1 */
long hstatus[2];
void *next __gru_cacheline_aligned__;/* CL 1 */
void *limit;
void *start;
void *start2;
char data ____cacheline_aligned; /* CL 2 */
};
/* First word in every message - used by mesq interface */
struct message_header {
char present;
char present2;
char lines;
char fill;
};
#define HSTATUS(mq, h) ((mq) + offsetof(struct message_queue, hstatus[h]))
/*
* Reload the blade's kernel context into a GRU chiplet. Called holding
* the bs_kgts_sema for READ. Will steal user contexts if necessary.
*/
static void gru_load_kernel_context(struct gru_blade_state *bs, int blade_id)
{
struct gru_state *gru;
struct gru_thread_state *kgts;
void *vaddr;
int ctxnum, ncpus;
up_read(&bs->bs_kgts_sema);
down_write(&bs->bs_kgts_sema);
if (!bs->bs_kgts) {
bs->bs_kgts = gru_alloc_gts(NULL, 0, 0, 0, 0, 0);
bs->bs_kgts->ts_user_blade_id = blade_id;
}
kgts = bs->bs_kgts;
if (!kgts->ts_gru) {
STAT(load_kernel_context);
ncpus = uv_blade_nr_possible_cpus(blade_id);
kgts->ts_cbr_au_count = GRU_CB_COUNT_TO_AU(
GRU_NUM_KERNEL_CBR * ncpus + bs->bs_async_cbrs);
kgts->ts_dsr_au_count = GRU_DS_BYTES_TO_AU(
GRU_NUM_KERNEL_DSR_BYTES * ncpus +
bs->bs_async_dsr_bytes);
while (!gru_assign_gru_context(kgts)) {
msleep(1);
gru_steal_context(kgts);
}
gru_load_context(kgts);
gru = bs->bs_kgts->ts_gru;
vaddr = gru->gs_gru_base_vaddr;
ctxnum = kgts->ts_ctxnum;
bs->kernel_cb = get_gseg_base_address_cb(vaddr, ctxnum, 0);
bs->kernel_dsr = get_gseg_base_address_ds(vaddr, ctxnum, 0);
}
downgrade_write(&bs->bs_kgts_sema);
}
/*
* Free all kernel contexts that are not currently in use.
* Returns 0 if all freed, else number of inuse context.
*/
static int gru_free_kernel_contexts(void)
{
struct gru_blade_state *bs;
struct gru_thread_state *kgts;
int bid, ret = 0;
for (bid = 0; bid < GRU_MAX_BLADES; bid++) {
bs = gru_base[bid];
if (!bs)
continue;
/* Ignore busy contexts. Don't want to block here. */
if (down_write_trylock(&bs->bs_kgts_sema)) {
kgts = bs->bs_kgts;
if (kgts && kgts->ts_gru)
gru_unload_context(kgts, 0);
bs->bs_kgts = NULL;
up_write(&bs->bs_kgts_sema);
kfree(kgts);
} else {
ret++;
}
}
return ret;
}
/*
* Lock & load the kernel context for the specified blade.
*/
static struct gru_blade_state *gru_lock_kernel_context(int blade_id)
{
struct gru_blade_state *bs;
int bid;
STAT(lock_kernel_context);
again:
bid = blade_id < 0 ? uv_numa_blade_id() : blade_id;
bs = gru_base[bid];
/* Handle the case where migration occurred while waiting for the sema */
down_read(&bs->bs_kgts_sema);
if (blade_id < 0 && bid != uv_numa_blade_id()) {
up_read(&bs->bs_kgts_sema);
goto again;
}
if (!bs->bs_kgts || !bs->bs_kgts->ts_gru)
gru_load_kernel_context(bs, bid);
return bs;
}
/*
* Unlock the kernel context for the specified blade. Context is not
* unloaded but may be stolen before next use.
*/
static void gru_unlock_kernel_context(int blade_id)
{
struct gru_blade_state *bs;
bs = gru_base[blade_id];
up_read(&bs->bs_kgts_sema);
STAT(unlock_kernel_context);
}
/*
* Reserve & get pointers to the DSR/CBRs reserved for the current cpu.
* - returns with preemption disabled
*/
static int gru_get_cpu_resources(int dsr_bytes, void **cb, void **dsr)
{
struct gru_blade_state *bs;
int lcpu;
BUG_ON(dsr_bytes > GRU_NUM_KERNEL_DSR_BYTES);
preempt_disable();
bs = gru_lock_kernel_context(-1);
lcpu = uv_blade_processor_id();
*cb = bs->kernel_cb + lcpu * GRU_HANDLE_STRIDE;
*dsr = bs->kernel_dsr + lcpu * GRU_NUM_KERNEL_DSR_BYTES;
return 0;
}
/*
* Free the current cpus reserved DSR/CBR resources.
*/
static void gru_free_cpu_resources(void *cb, void *dsr)
{
gru_unlock_kernel_context(uv_numa_blade_id());
preempt_enable();
}
/*
* Reserve GRU resources to be used asynchronously.
* Note: currently supports only 1 reservation per blade.
*
* input:
* blade_id - blade on which resources should be reserved
* cbrs - number of CBRs
* dsr_bytes - number of DSR bytes needed
* output:
* handle to identify resource
* (0 = async resources already reserved)
*/
unsigned long gru_reserve_async_resources(int blade_id, int cbrs, int dsr_bytes,
struct completion *cmp)
{
struct gru_blade_state *bs;
struct gru_thread_state *kgts;
int ret = 0;
bs = gru_base[blade_id];
down_write(&bs->bs_kgts_sema);
/* Verify no resources already reserved */
if (bs->bs_async_dsr_bytes + bs->bs_async_cbrs)
goto done;
bs->bs_async_dsr_bytes = dsr_bytes;
bs->bs_async_cbrs = cbrs;
bs->bs_async_wq = cmp;
kgts = bs->bs_kgts;
/* Resources changed. Unload context if already loaded */
if (kgts && kgts->ts_gru)
gru_unload_context(kgts, 0);
ret = ASYNC_BID_TO_HAN(blade_id);
done:
up_write(&bs->bs_kgts_sema);
return ret;
}
/*
* Release async resources previously reserved.
*
* input:
* han - handle to identify resources
*/
void gru_release_async_resources(unsigned long han)
{
struct gru_blade_state *bs = ASYNC_HAN_TO_BS(han);
down_write(&bs->bs_kgts_sema);
bs->bs_async_dsr_bytes = 0;
bs->bs_async_cbrs = 0;
bs->bs_async_wq = NULL;
up_write(&bs->bs_kgts_sema);
}
/*
* Wait for async GRU instructions to complete.
*
* input:
* han - handle to identify resources
*/
void gru_wait_async_cbr(unsigned long han)
{
struct gru_blade_state *bs = ASYNC_HAN_TO_BS(han);
wait_for_completion(bs->bs_async_wq);
mb();
}
/*
* Lock previous reserved async GRU resources
*
* input:
* han - handle to identify resources
* output:
* cb - pointer to first CBR
* dsr - pointer to first DSR
*/
void gru_lock_async_resource(unsigned long han, void **cb, void **dsr)
{
struct gru_blade_state *bs = ASYNC_HAN_TO_BS(han);
int blade_id = ASYNC_HAN_TO_BID(han);
int ncpus;
gru_lock_kernel_context(blade_id);
ncpus = uv_blade_nr_possible_cpus(blade_id);
if (cb)
*cb = bs->kernel_cb + ncpus * GRU_HANDLE_STRIDE;
if (dsr)
*dsr = bs->kernel_dsr + ncpus * GRU_NUM_KERNEL_DSR_BYTES;
}
/*
* Unlock previous reserved async GRU resources
*
* input:
* han - handle to identify resources
*/
void gru_unlock_async_resource(unsigned long han)
{
int blade_id = ASYNC_HAN_TO_BID(han);
gru_unlock_kernel_context(blade_id);
}
/*----------------------------------------------------------------------*/
int gru_get_cb_exception_detail(void *cb,
struct control_block_extended_exc_detail *excdet)
{
struct gru_control_block_extended *cbe;
struct gru_thread_state *kgts = NULL;
unsigned long off;
int cbrnum, bid;
/*
* Locate kgts for cb. This algorithm is SLOW but
* this function is rarely called (ie., almost never).
* Performance does not matter.
*/
for_each_possible_blade(bid) {
if (!gru_base[bid])
break;
kgts = gru_base[bid]->bs_kgts;
if (!kgts || !kgts->ts_gru)
continue;
off = cb - kgts->ts_gru->gs_gru_base_vaddr;
if (off < GRU_SIZE)
break;
kgts = NULL;
}
BUG_ON(!kgts);
cbrnum = thread_cbr_number(kgts, get_cb_number(cb));
cbe = get_cbe(GRUBASE(cb), cbrnum);
gru_flush_cache(cbe); /* CBE not coherent */
sync_core();
excdet->opc = cbe->opccpy;
excdet->exopc = cbe->exopccpy;
excdet->ecause = cbe->ecause;
excdet->exceptdet0 = cbe->idef1upd;
excdet->exceptdet1 = cbe->idef3upd;
gru_flush_cache(cbe);
return 0;
}
char *gru_get_cb_exception_detail_str(int ret, void *cb,
char *buf, int size)
{
struct gru_control_block_status *gen = (void *)cb;
struct control_block_extended_exc_detail excdet;
if (ret > 0 && gen->istatus == CBS_EXCEPTION) {
gru_get_cb_exception_detail(cb, &excdet);
snprintf(buf, size,
"GRU:%d exception: cb %p, opc %d, exopc %d, ecause 0x%x,"
"excdet0 0x%lx, excdet1 0x%x", smp_processor_id(),
gen, excdet.opc, excdet.exopc, excdet.ecause,
excdet.exceptdet0, excdet.exceptdet1);
} else {
snprintf(buf, size, "No exception");
}
return buf;
}
static int gru_wait_idle_or_exception(struct gru_control_block_status *gen)
{
while (gen->istatus >= CBS_ACTIVE) {
cpu_relax();
barrier();
}
return gen->istatus;
}
static int gru_retry_exception(void *cb)
{
struct gru_control_block_status *gen = (void *)cb;
struct control_block_extended_exc_detail excdet;
int retry = EXCEPTION_RETRY_LIMIT;
while (1) {
if (gru_wait_idle_or_exception(gen) == CBS_IDLE)
return CBS_IDLE;
if (gru_get_cb_message_queue_substatus(cb))
return CBS_EXCEPTION;
gru_get_cb_exception_detail(cb, &excdet);
if ((excdet.ecause & ~EXCEPTION_RETRY_BITS) ||
(excdet.cbrexecstatus & CBR_EXS_ABORT_OCC))
break;
if (retry-- == 0)
break;
gen->icmd = 1;
gru_flush_cache(gen);
}
return CBS_EXCEPTION;
}
int gru_check_status_proc(void *cb)
{
struct gru_control_block_status *gen = (void *)cb;
int ret;
ret = gen->istatus;
if (ret == CBS_EXCEPTION)
ret = gru_retry_exception(cb);
rmb();
return ret;
}
int gru_wait_proc(void *cb)
{
struct gru_control_block_status *gen = (void *)cb;
int ret;
ret = gru_wait_idle_or_exception(gen);
if (ret == CBS_EXCEPTION)
ret = gru_retry_exception(cb);
rmb();
return ret;
}
void gru_abort(int ret, void *cb, char *str)
{
char buf[GRU_EXC_STR_SIZE];
panic("GRU FATAL ERROR: %s - %s\n", str,
gru_get_cb_exception_detail_str(ret, cb, buf, sizeof(buf)));
}
void gru_wait_abort_proc(void *cb)
{
int ret;
ret = gru_wait_proc(cb);
if (ret)
gru_abort(ret, cb, "gru_wait_abort");
}
/*------------------------------ MESSAGE QUEUES -----------------------------*/
/* Internal status . These are NOT returned to the user. */
#define MQIE_AGAIN -1 /* try again */
/*
* Save/restore the "present" flag that is in the second line of 2-line
* messages
*/
static inline int get_present2(void *p)
{
struct message_header *mhdr = p + GRU_CACHE_LINE_BYTES;
return mhdr->present;
}
static inline void restore_present2(void *p, int val)
{
struct message_header *mhdr = p + GRU_CACHE_LINE_BYTES;
mhdr->present = val;
}
/*
* Create a message queue.
* qlines - message queue size in cache lines. Includes 2-line header.
*/
int gru_create_message_queue(struct gru_message_queue_desc *mqd,
void *p, unsigned int bytes, int nasid, int vector, int apicid)
{
struct message_queue *mq = p;
unsigned int qlines;
qlines = bytes / GRU_CACHE_LINE_BYTES - 2;
memset(mq, 0, bytes);
mq->start = &mq->data;
mq->start2 = &mq->data + (qlines / 2 - 1) * GRU_CACHE_LINE_BYTES;
mq->next = &mq->data;
mq->limit = &mq->data + (qlines - 2) * GRU_CACHE_LINE_BYTES;
mq->qlines = qlines;
mq->hstatus[0] = 0;
mq->hstatus[1] = 1;
mq->head = gru_mesq_head(2, qlines / 2 + 1);
mqd->mq = mq;
mqd->mq_gpa = uv_gpa(mq);
mqd->qlines = qlines;
mqd->interrupt_pnode = nasid >> 1;
mqd->interrupt_vector = vector;
mqd->interrupt_apicid = apicid;
return 0;
}
EXPORT_SYMBOL_GPL(gru_create_message_queue);
/*
* Send a NOOP message to a message queue
* Returns:
* 0 - if queue is full after the send. This is the normal case
* but various races can change this.
* -1 - if mesq sent successfully but queue not full
* >0 - unexpected error. MQE_xxx returned
*/
static int send_noop_message(void *cb, struct gru_message_queue_desc *mqd,
void *mesg)
{
const struct message_header noop_header = {
.present = MQS_NOOP, .lines = 1};
unsigned long m;
int substatus, ret;
struct message_header save_mhdr, *mhdr = mesg;
STAT(mesq_noop);
save_mhdr = *mhdr;
*mhdr = noop_header;
gru_mesq(cb, mqd->mq_gpa, gru_get_tri(mhdr), 1, IMA);
ret = gru_wait(cb);
if (ret) {
substatus = gru_get_cb_message_queue_substatus(cb);
switch (substatus) {
case CBSS_NO_ERROR:
STAT(mesq_noop_unexpected_error);
ret = MQE_UNEXPECTED_CB_ERR;
break;
case CBSS_LB_OVERFLOWED:
STAT(mesq_noop_lb_overflow);
ret = MQE_CONGESTION;
break;
case CBSS_QLIMIT_REACHED:
STAT(mesq_noop_qlimit_reached);
ret = 0;
break;
case CBSS_AMO_NACKED:
STAT(mesq_noop_amo_nacked);
ret = MQE_CONGESTION;
break;
case CBSS_PUT_NACKED:
STAT(mesq_noop_put_nacked);
m = mqd->mq_gpa + (gru_get_amo_value_head(cb) << 6);
gru_vstore(cb, m, gru_get_tri(mesg), XTYPE_CL, 1, 1,
IMA);
if (gru_wait(cb) == CBS_IDLE)
ret = MQIE_AGAIN;
else
ret = MQE_UNEXPECTED_CB_ERR;
break;
case CBSS_PAGE_OVERFLOW:
STAT(mesq_noop_page_overflow);
/* fallthru */
default:
BUG();
}
}
*mhdr = save_mhdr;
return ret;
}
/*
* Handle a gru_mesq full.
*/
static int send_message_queue_full(void *cb, struct gru_message_queue_desc *mqd,
void *mesg, int lines)
{
union gru_mesqhead mqh;
unsigned int limit, head;
unsigned long avalue;
int half, qlines;
/* Determine if switching to first/second half of q */
avalue = gru_get_amo_value(cb);
head = gru_get_amo_value_head(cb);
limit = gru_get_amo_value_limit(cb);
qlines = mqd->qlines;
half = (limit != qlines);
if (half)
mqh = gru_mesq_head(qlines / 2 + 1, qlines);
else
mqh = gru_mesq_head(2, qlines / 2 + 1);
/* Try to get lock for switching head pointer */
gru_gamir(cb, EOP_IR_CLR, HSTATUS(mqd->mq_gpa, half), XTYPE_DW, IMA);
if (gru_wait(cb) != CBS_IDLE)
goto cberr;
if (!gru_get_amo_value(cb)) {
STAT(mesq_qf_locked);
return MQE_QUEUE_FULL;
}
/* Got the lock. Send optional NOP if queue not full, */
if (head != limit) {
if (send_noop_message(cb, mqd, mesg)) {
gru_gamir(cb, EOP_IR_INC, HSTATUS(mqd->mq_gpa, half),
XTYPE_DW, IMA);
if (gru_wait(cb) != CBS_IDLE)
goto cberr;
STAT(mesq_qf_noop_not_full);
return MQIE_AGAIN;
}
avalue++;
}
/* Then flip queuehead to other half of queue. */
gru_gamer(cb, EOP_ERR_CSWAP, mqd->mq_gpa, XTYPE_DW, mqh.val, avalue,
IMA);
if (gru_wait(cb) != CBS_IDLE)
goto cberr;
/* If not successfully in swapping queue head, clear the hstatus lock */
if (gru_get_amo_value(cb) != avalue) {
STAT(mesq_qf_switch_head_failed);
gru_gamir(cb, EOP_IR_INC, HSTATUS(mqd->mq_gpa, half), XTYPE_DW,
IMA);
if (gru_wait(cb) != CBS_IDLE)
goto cberr;
}
return MQIE_AGAIN;
cberr:
STAT(mesq_qf_unexpected_error);
return MQE_UNEXPECTED_CB_ERR;
}
/*
* Handle a PUT failure. Note: if message was a 2-line message, one of the
* lines might have successfully have been written. Before sending the
* message, "present" must be cleared in BOTH lines to prevent the receiver
* from prematurely seeing the full message.
*/
static int send_message_put_nacked(void *cb, struct gru_message_queue_desc *mqd,
void *mesg, int lines)
{
unsigned long m, *val = mesg, gpa, save;
int ret;
m = mqd->mq_gpa + (gru_get_amo_value_head(cb) << 6);
if (lines == 2) {
gru_vset(cb, m, 0, XTYPE_CL, lines, 1, IMA);
if (gru_wait(cb) != CBS_IDLE)
return MQE_UNEXPECTED_CB_ERR;
}
gru_vstore(cb, m, gru_get_tri(mesg), XTYPE_CL, lines, 1, IMA);
if (gru_wait(cb) != CBS_IDLE)
return MQE_UNEXPECTED_CB_ERR;
if (!mqd->interrupt_vector)
return MQE_OK;
/*
* Send a cross-partition interrupt to the SSI that contains the target
* message queue. Normally, the interrupt is automatically delivered by
* hardware but some error conditions require explicit delivery.
* Use the GRU to deliver the interrupt. Otherwise partition failures
* could cause unrecovered errors.
*/
gpa = uv_global_gru_mmr_address(mqd->interrupt_pnode, UVH_IPI_INT);
save = *val;
*val = uv_hub_ipi_value(mqd->interrupt_apicid, mqd->interrupt_vector,
dest_Fixed);
gru_vstore_phys(cb, gpa, gru_get_tri(mesg), IAA_REGISTER, IMA);
ret = gru_wait(cb);
*val = save;
if (ret != CBS_IDLE)
return MQE_UNEXPECTED_CB_ERR;
return MQE_OK;
}
/*
* Handle a gru_mesq failure. Some of these failures are software recoverable
* or retryable.
*/
static int send_message_failure(void *cb, struct gru_message_queue_desc *mqd,
void *mesg, int lines)
{
int substatus, ret = 0;
substatus = gru_get_cb_message_queue_substatus(cb);
switch (substatus) {
case CBSS_NO_ERROR:
STAT(mesq_send_unexpected_error);
ret = MQE_UNEXPECTED_CB_ERR;
break;
case CBSS_LB_OVERFLOWED:
STAT(mesq_send_lb_overflow);
ret = MQE_CONGESTION;
break;
case CBSS_QLIMIT_REACHED:
STAT(mesq_send_qlimit_reached);
ret = send_message_queue_full(cb, mqd, mesg, lines);
break;
case CBSS_AMO_NACKED:
STAT(mesq_send_amo_nacked);
ret = MQE_CONGESTION;
break;
case CBSS_PUT_NACKED:
STAT(mesq_send_put_nacked);
ret = send_message_put_nacked(cb, mqd, mesg, lines);
break;
case CBSS_PAGE_OVERFLOW:
STAT(mesq_page_overflow);
/* fallthru */
default:
BUG();
}
return ret;
}
/*
* Send a message to a message queue
* mqd message queue descriptor
* mesg message. ust be vaddr within a GSEG
* bytes message size (<= 2 CL)
*/
int gru_send_message_gpa(struct gru_message_queue_desc *mqd, void *mesg,
unsigned int bytes)
{
struct message_header *mhdr;
void *cb;
void *dsr;
int istatus, clines, ret;
STAT(mesq_send);
BUG_ON(bytes < sizeof(int) || bytes > 2 * GRU_CACHE_LINE_BYTES);
clines = DIV_ROUND_UP(bytes, GRU_CACHE_LINE_BYTES);
if (gru_get_cpu_resources(bytes, &cb, &dsr))
return MQE_BUG_NO_RESOURCES;
memcpy(dsr, mesg, bytes);
mhdr = dsr;
mhdr->present = MQS_FULL;
mhdr->lines = clines;
if (clines == 2) {
mhdr->present2 = get_present2(mhdr);
restore_present2(mhdr, MQS_FULL);
}
do {
ret = MQE_OK;
gru_mesq(cb, mqd->mq_gpa, gru_get_tri(mhdr), clines, IMA);
istatus = gru_wait(cb);
if (istatus != CBS_IDLE)
ret = send_message_failure(cb, mqd, dsr, clines);
} while (ret == MQIE_AGAIN);
gru_free_cpu_resources(cb, dsr);
if (ret)
STAT(mesq_send_failed);
return ret;
}
EXPORT_SYMBOL_GPL(gru_send_message_gpa);
/*
* Advance the receive pointer for the queue to the next message.
*/
void gru_free_message(struct gru_message_queue_desc *mqd, void *mesg)
{
struct message_queue *mq = mqd->mq;
struct message_header *mhdr = mq->next;
void *next, *pnext;
int half = -1;
int lines = mhdr->lines;
if (lines == 2)
restore_present2(mhdr, MQS_EMPTY);
mhdr->present = MQS_EMPTY;
pnext = mq->next;
next = pnext + GRU_CACHE_LINE_BYTES * lines;
if (next == mq->limit) {
next = mq->start;
half = 1;
} else if (pnext < mq->start2 && next >= mq->start2) {
half = 0;
}
if (half >= 0)
mq->hstatus[half] = 1;
mq->next = next;
}
EXPORT_SYMBOL_GPL(gru_free_message);
/*
* Get next message from message queue. Return NULL if no message
* present. User must call next_message() to move to next message.
* rmq message queue
*/
void *gru_get_next_message(struct gru_message_queue_desc *mqd)
{
struct message_queue *mq = mqd->mq;
struct message_header *mhdr = mq->next;
int present = mhdr->present;
/* skip NOOP messages */
while (present == MQS_NOOP) {
gru_free_message(mqd, mhdr);
mhdr = mq->next;
present = mhdr->present;
}
/* Wait for both halves of 2 line messages */
if (present == MQS_FULL && mhdr->lines == 2 &&
get_present2(mhdr) == MQS_EMPTY)
present = MQS_EMPTY;
if (!present) {
STAT(mesq_receive_none);
return NULL;
}
if (mhdr->lines == 2)
restore_present2(mhdr, mhdr->present2);
STAT(mesq_receive);
return mhdr;
}
EXPORT_SYMBOL_GPL(gru_get_next_message);
/* ---------------------- GRU DATA COPY FUNCTIONS ---------------------------*/
/*
* Load a DW from a global GPA. The GPA can be a memory or MMR address.
*/
int gru_read_gpa(unsigned long *value, unsigned long gpa)
{
void *cb;
void *dsr;
int ret, iaa;
STAT(read_gpa);
if (gru_get_cpu_resources(GRU_NUM_KERNEL_DSR_BYTES, &cb, &dsr))
return MQE_BUG_NO_RESOURCES;
iaa = gpa >> 62;
gru_vload_phys(cb, gpa, gru_get_tri(dsr), iaa, IMA);
ret = gru_wait(cb);
if (ret == CBS_IDLE)
*value = *(unsigned long *)dsr;
gru_free_cpu_resources(cb, dsr);
return ret;
}
EXPORT_SYMBOL_GPL(gru_read_gpa);
/*
* Copy a block of data using the GRU resources
*/
int gru_copy_gpa(unsigned long dest_gpa, unsigned long src_gpa,
unsigned int bytes)
{
void *cb;
void *dsr;
int ret;
STAT(copy_gpa);
if (gru_get_cpu_resources(GRU_NUM_KERNEL_DSR_BYTES, &cb, &dsr))
return MQE_BUG_NO_RESOURCES;
gru_bcopy(cb, src_gpa, dest_gpa, gru_get_tri(dsr),
XTYPE_B, bytes, GRU_NUM_KERNEL_DSR_CL, IMA);
ret = gru_wait(cb);
gru_free_cpu_resources(cb, dsr);
return ret;
}
EXPORT_SYMBOL_GPL(gru_copy_gpa);
/* ------------------- KERNEL QUICKTESTS RUN AT STARTUP ----------------*/
/* Temp - will delete after we gain confidence in the GRU */
static int quicktest0(unsigned long arg)
{
unsigned long word0;
unsigned long word1;
void *cb;
void *dsr;
unsigned long *p;
int ret = -EIO;
if (gru_get_cpu_resources(GRU_CACHE_LINE_BYTES, &cb, &dsr))
return MQE_BUG_NO_RESOURCES;
p = dsr;
word0 = MAGIC;
word1 = 0;
gru_vload(cb, uv_gpa(&word0), gru_get_tri(dsr), XTYPE_DW, 1, 1, IMA);
if (gru_wait(cb) != CBS_IDLE) {
printk(KERN_DEBUG "GRU:%d quicktest0: CBR failure 1\n", smp_processor_id());
goto done;
}
if (*p != MAGIC) {
printk(KERN_DEBUG "GRU:%d quicktest0 bad magic 0x%lx\n", smp_processor_id(), *p);
goto done;
}
gru_vstore(cb, uv_gpa(&word1), gru_get_tri(dsr), XTYPE_DW, 1, 1, IMA);
if (gru_wait(cb) != CBS_IDLE) {
printk(KERN_DEBUG "GRU:%d quicktest0: CBR failure 2\n", smp_processor_id());
goto done;
}
if (word0 != word1 || word1 != MAGIC) {
printk(KERN_DEBUG
"GRU:%d quicktest0 err: found 0x%lx, expected 0x%lx\n",
smp_processor_id(), word1, MAGIC);
goto done;
}
ret = 0;
done:
gru_free_cpu_resources(cb, dsr);
return ret;
}
#define ALIGNUP(p, q) ((void *)(((unsigned long)(p) + (q) - 1) & ~(q - 1)))
static int quicktest1(unsigned long arg)
{
struct gru_message_queue_desc mqd;
void *p, *mq;
unsigned long *dw;
int i, ret = -EIO;
char mes[GRU_CACHE_LINE_BYTES], *m;
/* Need 1K cacheline aligned that does not cross page boundary */
p = kmalloc(4096, 0);
if (p == NULL)
return -ENOMEM;
mq = ALIGNUP(p, 1024);
memset(mes, 0xee, sizeof(mes));
dw = mq;
gru_create_message_queue(&mqd, mq, 8 * GRU_CACHE_LINE_BYTES, 0, 0, 0);
for (i = 0; i < 6; i++) {
mes[8] = i;
do {
ret = gru_send_message_gpa(&mqd, mes, sizeof(mes));
} while (ret == MQE_CONGESTION);
if (ret)
break;
}
if (ret != MQE_QUEUE_FULL || i != 4) {
printk(KERN_DEBUG "GRU:%d quicktest1: unexpect status %d, i %d\n",
smp_processor_id(), ret, i);
goto done;
}
for (i = 0; i < 6; i++) {
m = gru_get_next_message(&mqd);
if (!m || m[8] != i)
break;
gru_free_message(&mqd, m);
}
if (i != 4) {
printk(KERN_DEBUG "GRU:%d quicktest2: bad message, i %d, m %p, m8 %d\n",
smp_processor_id(), i, m, m ? m[8] : -1);
goto done;
}
ret = 0;
done:
kfree(p);
return ret;
}
static int quicktest2(unsigned long arg)
{
static DECLARE_COMPLETION(cmp);
unsigned long han;
int blade_id = 0;
int numcb = 4;
int ret = 0;
unsigned long *buf;
void *cb0, *cb;
struct gru_control_block_status *gen;
int i, k, istatus, bytes;
bytes = numcb * 4 * 8;
buf = kmalloc(bytes, GFP_KERNEL);
if (!buf)
return -ENOMEM;
ret = -EBUSY;
han = gru_reserve_async_resources(blade_id, numcb, 0, &cmp);
if (!han)
goto done;
gru_lock_async_resource(han, &cb0, NULL);
memset(buf, 0xee, bytes);
for (i = 0; i < numcb; i++)
gru_vset(cb0 + i * GRU_HANDLE_STRIDE, uv_gpa(&buf[i * 4]), 0,
XTYPE_DW, 4, 1, IMA_INTERRUPT);
ret = 0;
k = numcb;
do {
gru_wait_async_cbr(han);
for (i = 0; i < numcb; i++) {
cb = cb0 + i * GRU_HANDLE_STRIDE;
istatus = gru_check_status(cb);
if (istatus != CBS_ACTIVE && istatus != CBS_CALL_OS)
break;
}
if (i == numcb)
continue;
if (istatus != CBS_IDLE) {
printk(KERN_DEBUG "GRU:%d quicktest2: cb %d, exception\n", smp_processor_id(), i);
ret = -EFAULT;
} else if (buf[4 * i] || buf[4 * i + 1] || buf[4 * i + 2] ||
buf[4 * i + 3]) {
printk(KERN_DEBUG "GRU:%d quicktest2:cb %d, buf 0x%lx, 0x%lx, 0x%lx, 0x%lx\n",
smp_processor_id(), i, buf[4 * i], buf[4 * i + 1], buf[4 * i + 2], buf[4 * i + 3]);
ret = -EIO;
}
k--;
gen = cb;
gen->istatus = CBS_CALL_OS; /* don't handle this CBR again */
} while (k);
BUG_ON(cmp.done);
gru_unlock_async_resource(han);
gru_release_async_resources(han);
done:
kfree(buf);
return ret;
}
#define BUFSIZE 200
static int quicktest3(unsigned long arg)
{
char buf1[BUFSIZE], buf2[BUFSIZE];
int ret = 0;
memset(buf2, 0, sizeof(buf2));
memset(buf1, get_cycles() & 255, sizeof(buf1));
gru_copy_gpa(uv_gpa(buf2), uv_gpa(buf1), BUFSIZE);
if (memcmp(buf1, buf2, BUFSIZE)) {
printk(KERN_DEBUG "GRU:%d quicktest3 error\n", smp_processor_id());
ret = -EIO;
}
return ret;
}
/*
* Debugging only. User hook for various kernel tests
* of driver & gru.
*/
int gru_ktest(unsigned long arg)
{
int ret = -EINVAL;
switch (arg & 0xff) {
case 0:
ret = quicktest0(arg);
break;
case 1:
ret = quicktest1(arg);
break;
case 2:
ret = quicktest2(arg);
break;
case 3:
ret = quicktest3(arg);
break;
case 99:
ret = gru_free_kernel_contexts();
break;
}
return ret;
}
int gru_kservices_init(void)
{
return 0;
}
void gru_kservices_exit(void)
{
if (gru_free_kernel_contexts())
BUG();
}
| gpl-2.0 |
samnazarko/vero-linux | arch/cris/kernel/traps.c | 2931 | 4914 | /*
* linux/arch/cris/traps.c
*
* Here we handle the break vectors not used by the system call
* mechanism, as well as some general stack/register dumping
* things.
*
* Copyright (C) 2000-2007 Axis Communications AB
*
* Authors: Bjorn Wesen
* Hans-Peter Nilsson
*
*/
#include <linux/init.h>
#include <linux/module.h>
#include <asm/pgtable.h>
#include <asm/uaccess.h>
#include <arch/system.h>
extern void arch_enable_nmi(void);
extern void stop_watchdog(void);
extern void reset_watchdog(void);
extern void show_registers(struct pt_regs *regs);
#ifdef CONFIG_DEBUG_BUGVERBOSE
extern void handle_BUG(struct pt_regs *regs);
#else
#define handle_BUG(regs)
#endif
static int kstack_depth_to_print = 24;
void (*nmi_handler)(struct pt_regs *);
void
show_trace(unsigned long *stack)
{
unsigned long addr, module_start, module_end;
extern char _stext, _etext;
int i;
printk("\nCall Trace: ");
i = 1;
module_start = VMALLOC_START;
module_end = VMALLOC_END;
while (((long)stack & (THREAD_SIZE-1)) != 0) {
if (__get_user(addr, stack)) {
/* This message matches "failing address" marked
s390 in ksymoops, so lines containing it will
not be filtered out by ksymoops. */
printk("Failing address 0x%lx\n", (unsigned long)stack);
break;
}
stack++;
/*
* If the address is either in the text segment of the
* kernel, or in the region which contains vmalloc'ed
* memory, it *may* be the address of a calling
* routine; if so, print it so that someone tracing
* down the cause of the crash will be able to figure
* out the call path that was taken.
*/
if (((addr >= (unsigned long)&_stext) &&
(addr <= (unsigned long)&_etext)) ||
((addr >= module_start) && (addr <= module_end))) {
if (i && ((i % 8) == 0))
printk("\n ");
printk("[<%08lx>] ", addr);
i++;
}
}
}
/*
* These constants are for searching for possible module text
* segments. MODULE_RANGE is a guess of how much space is likely
* to be vmalloced.
*/
#define MODULE_RANGE (8*1024*1024)
/*
* The output (format, strings and order) is adjusted to be usable with
* ksymoops-2.4.1 with some necessary CRIS-specific patches. Please don't
* change it unless you're serious about adjusting ksymoops and syncing
* with the ksymoops maintainer.
*/
void
show_stack(struct task_struct *task, unsigned long *sp)
{
unsigned long *stack, addr;
int i;
/*
* debugging aid: "show_stack(NULL);" prints a
* back trace.
*/
if (sp == NULL) {
if (task)
sp = (unsigned long*)task->thread.ksp;
else
sp = (unsigned long*)rdsp();
}
stack = sp;
printk("\nStack from %08lx:\n ", (unsigned long)stack);
for (i = 0; i < kstack_depth_to_print; i++) {
if (((long)stack & (THREAD_SIZE-1)) == 0)
break;
if (i && ((i % 8) == 0))
printk("\n ");
if (__get_user(addr, stack)) {
/* This message matches "failing address" marked
s390 in ksymoops, so lines containing it will
not be filtered out by ksymoops. */
printk("Failing address 0x%lx\n", (unsigned long)stack);
break;
}
stack++;
printk("%08lx ", addr);
}
show_trace(sp);
}
#if 0
/* displays a short stack trace */
int
show_stack(void)
{
unsigned long *sp = (unsigned long *)rdusp();
int i;
printk("Stack dump [0x%08lx]:\n", (unsigned long)sp);
for (i = 0; i < 16; i++)
printk("sp + %d: 0x%08lx\n", i*4, sp[i]);
return 0;
}
#endif
void
set_nmi_handler(void (*handler)(struct pt_regs *))
{
nmi_handler = handler;
arch_enable_nmi();
}
#ifdef CONFIG_DEBUG_NMI_OOPS
void
oops_nmi_handler(struct pt_regs *regs)
{
stop_watchdog();
oops_in_progress = 1;
printk("NMI!\n");
show_registers(regs);
oops_in_progress = 0;
}
static int __init
oops_nmi_register(void)
{
set_nmi_handler(oops_nmi_handler);
return 0;
}
__initcall(oops_nmi_register);
#endif
/*
* This gets called from entry.S when the watchdog has bitten. Show something
* similar to an Oops dump, and if the kernel is configured to be a nice
* doggy, then halt instead of reboot.
*/
void
watchdog_bite_hook(struct pt_regs *regs)
{
#ifdef CONFIG_ETRAX_WATCHDOG_NICE_DOGGY
local_irq_disable();
stop_watchdog();
show_registers(regs);
while (1)
; /* Do nothing. */
#else
show_registers(regs);
#endif
}
/* This is normally the Oops function. */
void
die_if_kernel(const char *str, struct pt_regs *regs, long err)
{
if (user_mode(regs))
return;
#ifdef CONFIG_ETRAX_WATCHDOG_NICE_DOGGY
/*
* This printout might take too long and could trigger
* the watchdog normally. If NICE_DOGGY is set, simply
* stop the watchdog during the printout.
*/
stop_watchdog();
#endif
handle_BUG(regs);
printk("%s: %04lx\n", str, err & 0xffff);
show_registers(regs);
oops_in_progress = 0;
#ifdef CONFIG_ETRAX_WATCHDOG_NICE_DOGGY
reset_watchdog();
#endif
do_exit(SIGSEGV);
}
void __init
trap_init(void)
{
/* Nothing needs to be done */
}
| gpl-2.0 |
nrgmilk/linux | arch/arm/mach-s3c2443/mach-smdk2443.c | 2931 | 3462 | /* linux/arch/arm/mach-s3c2443/mach-smdk2443.c
*
* Copyright (c) 2007 Simtec Electronics
* Ben Dooks <ben@simtec.co.uk>
*
* http://www.fluff.org/ben/smdk2443/
*
* Thanks to Samsung for the loan of an SMDK2443
*
* 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/types.h>
#include <linux/interrupt.h>
#include <linux/list.h>
#include <linux/timer.h>
#include <linux/init.h>
#include <linux/serial_core.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/mach/irq.h>
#include <mach/hardware.h>
#include <asm/irq.h>
#include <asm/mach-types.h>
#include <plat/regs-serial.h>
#include <mach/regs-gpio.h>
#include <mach/regs-lcd.h>
#include <mach/idle.h>
#include <mach/fb.h>
#include <plat/iic.h>
#include <plat/s3c2410.h>
#include <plat/s3c2443.h>
#include <plat/clock.h>
#include <plat/devs.h>
#include <plat/cpu.h>
#include <plat/common-smdk.h>
static struct map_desc smdk2443_iodesc[] __initdata = {
/* ISA IO Space map (memory space selected by A24) */
{
.virtual = (u32)S3C24XX_VA_ISA_WORD,
.pfn = __phys_to_pfn(S3C2410_CS2),
.length = 0x10000,
.type = MT_DEVICE,
}, {
.virtual = (u32)S3C24XX_VA_ISA_WORD + 0x10000,
.pfn = __phys_to_pfn(S3C2410_CS2 + (1<<24)),
.length = SZ_4M,
.type = MT_DEVICE,
}, {
.virtual = (u32)S3C24XX_VA_ISA_BYTE,
.pfn = __phys_to_pfn(S3C2410_CS2),
.length = 0x10000,
.type = MT_DEVICE,
}, {
.virtual = (u32)S3C24XX_VA_ISA_BYTE + 0x10000,
.pfn = __phys_to_pfn(S3C2410_CS2 + (1<<24)),
.length = SZ_4M,
.type = MT_DEVICE,
}
};
#define UCON S3C2410_UCON_DEFAULT | S3C2410_UCON_UCLK
#define ULCON S3C2410_LCON_CS8 | S3C2410_LCON_PNONE | S3C2410_LCON_STOPB
#define UFCON S3C2410_UFCON_RXTRIG8 | S3C2410_UFCON_FIFOMODE
static struct s3c2410_uartcfg smdk2443_uartcfgs[] __initdata = {
[0] = {
.hwport = 0,
.flags = 0,
.ucon = 0x3c5,
.ulcon = 0x03,
.ufcon = 0x51,
},
[1] = {
.hwport = 1,
.flags = 0,
.ucon = 0x3c5,
.ulcon = 0x03,
.ufcon = 0x51,
},
/* IR port */
[2] = {
.hwport = 2,
.flags = 0,
.ucon = 0x3c5,
.ulcon = 0x43,
.ufcon = 0x51,
},
[3] = {
.hwport = 3,
.flags = 0,
.ucon = 0x3c5,
.ulcon = 0x03,
.ufcon = 0x51,
}
};
static struct platform_device *smdk2443_devices[] __initdata = {
&s3c_device_wdt,
&s3c_device_i2c0,
&s3c_device_hsmmc1,
#ifdef CONFIG_SND_SOC_SMDK2443_WM9710
&s3c_device_ac97,
#endif
};
static void __init smdk2443_map_io(void)
{
s3c24xx_init_io(smdk2443_iodesc, ARRAY_SIZE(smdk2443_iodesc));
s3c24xx_init_clocks(12000000);
s3c24xx_init_uarts(smdk2443_uartcfgs, ARRAY_SIZE(smdk2443_uartcfgs));
}
static void __init smdk2443_machine_init(void)
{
s3c_i2c0_set_platdata(NULL);
#ifdef CONFIG_SND_SOC_SMDK2443_WM9710
s3c24xx_ac97_setup_gpio(S3C24XX_AC97_GPE0);
#endif
platform_add_devices(smdk2443_devices, ARRAY_SIZE(smdk2443_devices));
smdk_machine_init();
}
MACHINE_START(SMDK2443, "SMDK2443")
/* Maintainer: Ben Dooks <ben-linux@fluff.org> */
.boot_params = S3C2410_SDRAM_PA + 0x100,
.init_irq = s3c24xx_init_irq,
.map_io = smdk2443_map_io,
.init_machine = smdk2443_machine_init,
.timer = &s3c24xx_timer,
MACHINE_END
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.