repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
detule/linux-msm-d2 | drivers/platform/msm/qpnp-clkdiv.c | 1630 | 6964 | /* Copyright (c) 2012, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#define pr_fmt(fmt) "%s: " fmt, __func__
#include <linux/types.h>
#include <linux/spmi.h>
#include <linux/slab.h>
#include <linux/of.h>
#include <linux/export.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/time.h>
#include <linux/qpnp/clkdiv.h>
#define Q_MAX_DT_PROP_SIZE 32
#define Q_REG_ADDR(q_clkdiv, reg_offset) \
((q_clkdiv)->offset + reg_offset)
#define Q_REG_DIV_CTL1 0x43
#define Q_REG_EN_CTL 0x46
#define Q_SET_EN BIT(7)
#define Q_CXO_PERIOD_NS(_cxo_clk) (NSEC_PER_SEC / _cxo_clk)
#define Q_DIV_PERIOD_NS(_cxo_clk, _div) (NSEC_PER_SEC / (_cxo_clk / _div))
#define Q_ENABLE_DELAY_NS(_cxo_clk, _div) (2 * Q_CXO_PERIOD_NS(_cxo_clk) + \
3 * Q_DIV_PERIOD_NS(_cxo_clk, _div))
#define Q_DISABLE_DELAY_NS(_cxo_clk, _div) (3 * Q_DIV_PERIOD_NS(_cxo_clk, _div))
struct q_clkdiv {
uint32_t cxo_hz;
enum q_clkdiv_cfg cxo_div;
struct device_node *node;
uint16_t offset;
struct spmi_controller *ctrl;
bool enabled;
struct mutex lock;
struct list_head list;
uint8_t slave;
};
static LIST_HEAD(qpnp_clkdiv_devs);
/**
* qpnp_clkdiv_get - get a clkdiv handle
* @dev: client device pointer.
* @name: client specific name for the clock in question.
*
* Return a clkdiv handle given a client specific name. This name be a prefix
* for a property naming that takes a phandle to the actual clkdiv device.
*/
struct q_clkdiv *qpnp_clkdiv_get(struct device *dev, const char *name)
{
struct q_clkdiv *q_clkdiv;
struct device_node *divclk_node;
char prop_name[Q_MAX_DT_PROP_SIZE];
int n;
n = snprintf(prop_name, Q_MAX_DT_PROP_SIZE, "%s-clk", name);
if (n == Q_MAX_DT_PROP_SIZE)
return ERR_PTR(-EINVAL);
divclk_node = of_parse_phandle(dev->of_node, prop_name, 0);
if (divclk_node == NULL)
return ERR_PTR(-ENODEV);
list_for_each_entry(q_clkdiv, &qpnp_clkdiv_devs, list)
if (q_clkdiv->node == divclk_node)
return q_clkdiv;
return ERR_PTR(-EPROBE_DEFER);
}
EXPORT_SYMBOL(qpnp_clkdiv_get);
static int __clkdiv_enable(struct q_clkdiv *q_clkdiv, bool enable)
{
int rc;
char buf[1];
buf[0] = enable ? Q_SET_EN : 0;
mutex_lock(&q_clkdiv->lock);
rc = spmi_ext_register_writel(q_clkdiv->ctrl, q_clkdiv->slave,
Q_REG_ADDR(q_clkdiv, Q_REG_EN_CTL),
&buf[0], 1);
if (!rc)
q_clkdiv->enabled = enable;
mutex_unlock(&q_clkdiv->lock);
if (enable)
ndelay(Q_ENABLE_DELAY_NS(q_clkdiv->cxo_hz, q_clkdiv->cxo_div));
else
ndelay(Q_DISABLE_DELAY_NS(q_clkdiv->cxo_hz, q_clkdiv->cxo_div));
return rc;
}
/**
* qpnp_clkdiv_enable - enable a clkdiv
* @q_clkdiv: pointer to clkdiv handle
*/
int qpnp_clkdiv_enable(struct q_clkdiv *q_clkdiv)
{
return __clkdiv_enable(q_clkdiv, true);
}
EXPORT_SYMBOL(qpnp_clkdiv_enable);
/**
* qpnp_clkdiv_disable - disable a clkdiv
* @q_clkdiv: pointer to clkdiv handle
*/
int qpnp_clkdiv_disable(struct q_clkdiv *q_clkdiv)
{
return __clkdiv_enable(q_clkdiv, false);
}
EXPORT_SYMBOL(qpnp_clkdiv_disable);
/**
* @q_clkdiv: pointer to clkdiv handle
* @cfg: setting used to configure the output frequency
*
* Given a q_clkdiv_cfg setting, configure the corresponding clkdiv device
* for the desired output frequency.
*/
int qpnp_clkdiv_config(struct q_clkdiv *q_clkdiv, enum q_clkdiv_cfg cfg)
{
int rc;
char buf[1];
if (cfg < 0 || cfg >= Q_CLKDIV_INVALID)
return -EINVAL;
buf[0] = cfg;
mutex_lock(&q_clkdiv->lock);
if (q_clkdiv->enabled) {
rc = __clkdiv_enable(q_clkdiv, false);
if (rc) {
pr_err("unable to disable clock\n");
goto cfg_err;
}
}
rc = spmi_ext_register_writel(q_clkdiv->ctrl, q_clkdiv->slave,
Q_REG_ADDR(q_clkdiv, Q_REG_DIV_CTL1), &buf[0], 1);
if (rc) {
pr_err("enable to write config\n");
q_clkdiv->enabled = 0;
goto cfg_err;
}
q_clkdiv->cxo_div = cfg;
if (q_clkdiv->enabled) {
rc = __clkdiv_enable(q_clkdiv, true);
if (rc) {
pr_err("unable to re-enable clock\n");
goto cfg_err;
}
}
cfg_err:
mutex_unlock(&q_clkdiv->lock);
return rc;
}
EXPORT_SYMBOL(qpnp_clkdiv_config);
static int __devinit qpnp_clkdiv_probe(struct spmi_device *spmi)
{
struct q_clkdiv *q_clkdiv;
struct device_node *node = spmi->dev.of_node;
int rc;
uint32_t en;
struct resource *res;
q_clkdiv = devm_kzalloc(&spmi->dev, sizeof(*q_clkdiv), GFP_ATOMIC);
if (!q_clkdiv)
return -ENOMEM;
rc = of_property_read_u32(node, "qcom,cxo-freq",
&q_clkdiv->cxo_hz);
if (rc) {
dev_err(&spmi->dev,
"%s: unable to get qcom,cxo-freq property\n", __func__);
return rc;
}
res = spmi_get_resource(spmi, NULL, IORESOURCE_MEM, 0);
if (!res) {
dev_err(&spmi->dev, "%s: unable to get device reg resource\n",
__func__);
}
q_clkdiv->slave = spmi->sid;
q_clkdiv->offset = res->start;
q_clkdiv->ctrl = spmi->ctrl;
q_clkdiv->node = node;
mutex_init(&q_clkdiv->lock);
rc = of_property_read_u32(node, "qcom,cxo-div",
&q_clkdiv->cxo_div);
if (rc && rc != -EINVAL) {
dev_err(&spmi->dev,
"%s: error getting qcom,cxo-div property\n",
__func__);
return rc;
}
if (!rc) {
rc = qpnp_clkdiv_config(q_clkdiv, q_clkdiv->cxo_div);
if (rc) {
dev_err(&spmi->dev,
"%s: unable to set default divide config\n",
__func__);
return rc;
}
}
rc = of_property_read_u32(node, "qcom,enable", &en);
if (rc && rc != -EINVAL) {
dev_err(&spmi->dev,
"%s: error getting qcom,enable property\n", __func__);
return rc;
}
if (!rc) {
rc = __clkdiv_enable(q_clkdiv, en);
dev_err(&spmi->dev,
"%s: unable to set default config\n", __func__);
return rc;
}
dev_set_drvdata(&spmi->dev, q_clkdiv);
list_add(&q_clkdiv->list, &qpnp_clkdiv_devs);
return 0;
}
static int __devexit qpnp_clkdiv_remove(struct spmi_device *spmi)
{
struct q_clkdiv *q_clkdiv = dev_get_drvdata(&spmi->dev);
list_del(&q_clkdiv->list);
return 0;
}
static struct of_device_id spmi_match_table[] = {
{ .compatible = "qcom,qpnp-clkdiv",
},
{}
};
static struct spmi_driver qpnp_clkdiv_driver = {
.driver = {
.name = "qcom,qpnp-clkdiv",
.of_match_table = spmi_match_table,
},
.probe = qpnp_clkdiv_probe,
.remove = __devexit_p(qpnp_clkdiv_remove),
};
static int __init qpnp_clkdiv_init(void)
{
return spmi_driver_register(&qpnp_clkdiv_driver);
}
static void __exit qpnp_clkdiv_exit(void)
{
return spmi_driver_unregister(&qpnp_clkdiv_driver);
}
MODULE_DESCRIPTION("QPNP PMIC clkdiv driver");
MODULE_LICENSE("GPL v2");
module_init(qpnp_clkdiv_init);
module_exit(qpnp_clkdiv_exit);
| gpl-2.0 |
mina86/linux | drivers/clk/rockchip/clk-rockchip.c | 1630 | 2326 | /*
* Copyright (c) 2013 MundoReader S.L.
* Author: Heiko Stuebner <heiko@sntech.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.
*/
#include <linux/clk-provider.h>
#include <linux/clkdev.h>
#include <linux/of.h>
#include <linux/of_address.h>
static DEFINE_SPINLOCK(clk_lock);
/*
* Gate clocks
*/
static void __init rk2928_gate_clk_init(struct device_node *node)
{
struct clk_onecell_data *clk_data;
const char *clk_parent;
const char *clk_name;
void __iomem *reg;
void __iomem *reg_idx;
int flags;
int qty;
int reg_bit;
int clkflags = CLK_SET_RATE_PARENT;
int i;
qty = of_property_count_strings(node, "clock-output-names");
if (qty < 0) {
pr_err("%s: error in clock-output-names %d\n", __func__, qty);
return;
}
if (qty == 0) {
pr_info("%s: nothing to do\n", __func__);
return;
}
reg = of_iomap(node, 0);
clk_data = kzalloc(sizeof(struct clk_onecell_data), GFP_KERNEL);
if (!clk_data)
return;
clk_data->clks = kzalloc(qty * sizeof(struct clk *), GFP_KERNEL);
if (!clk_data->clks) {
kfree(clk_data);
return;
}
flags = CLK_GATE_HIWORD_MASK | CLK_GATE_SET_TO_DISABLE;
for (i = 0; i < qty; i++) {
of_property_read_string_index(node, "clock-output-names",
i, &clk_name);
/* ignore empty slots */
if (!strcmp("reserved", clk_name))
continue;
clk_parent = of_clk_get_parent_name(node, i);
/* keep all gates untouched for now */
clkflags |= CLK_IGNORE_UNUSED;
reg_idx = reg + (4 * (i / 16));
reg_bit = (i % 16);
clk_data->clks[i] = clk_register_gate(NULL, clk_name,
clk_parent, clkflags,
reg_idx, reg_bit,
flags,
&clk_lock);
WARN_ON(IS_ERR(clk_data->clks[i]));
}
clk_data->clk_num = qty;
of_clk_add_provider(node, of_clk_src_onecell_get, clk_data);
}
CLK_OF_DECLARE(rk2928_gate, "rockchip,rk2928-gate-clk", rk2928_gate_clk_init);
| gpl-2.0 |
nc543/linux-release | sound/core/oss/mulaw.c | 1886 | 10480 | /*
* Mu-Law conversion Plug-In Interface
* Copyright (c) 1999 by Jaroslav Kysela <perex@perex.cz>
* Uros Bizjak <uros@kss-loka.si>
*
* Based on reference implementation by Sun Microsystems, Inc.
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/time.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include "pcm_plugin.h"
#define SIGN_BIT (0x80) /* Sign bit for a u-law byte. */
#define QUANT_MASK (0xf) /* Quantization field mask. */
#define NSEGS (8) /* Number of u-law segments. */
#define SEG_SHIFT (4) /* Left shift for segment number. */
#define SEG_MASK (0x70) /* Segment field mask. */
static inline int val_seg(int val)
{
int r = 0;
val >>= 7;
if (val & 0xf0) {
val >>= 4;
r += 4;
}
if (val & 0x0c) {
val >>= 2;
r += 2;
}
if (val & 0x02)
r += 1;
return r;
}
#define BIAS (0x84) /* Bias for linear code. */
/*
* linear2ulaw() - Convert a linear PCM value to u-law
*
* In order to simplify the encoding process, the original linear magnitude
* is biased by adding 33 which shifts the encoding range from (0 - 8158) to
* (33 - 8191). The result can be seen in the following encoding table:
*
* Biased Linear Input Code Compressed Code
* ------------------------ ---------------
* 00000001wxyza 000wxyz
* 0000001wxyzab 001wxyz
* 000001wxyzabc 010wxyz
* 00001wxyzabcd 011wxyz
* 0001wxyzabcde 100wxyz
* 001wxyzabcdef 101wxyz
* 01wxyzabcdefg 110wxyz
* 1wxyzabcdefgh 111wxyz
*
* Each biased linear code has a leading 1 which identifies the segment
* number. The value of the segment number is equal to 7 minus the number
* of leading 0's. The quantization interval is directly available as the
* four bits wxyz. * The trailing bits (a - h) are ignored.
*
* Ordinarily the complement of the resulting code word is used for
* transmission, and so the code word is complemented before it is returned.
*
* For further information see John C. Bellamy's Digital Telephony, 1982,
* John Wiley & Sons, pps 98-111 and 472-476.
*/
static unsigned char linear2ulaw(int pcm_val) /* 2's complement (16-bit range) */
{
int mask;
int seg;
unsigned char uval;
/* Get the sign and the magnitude of the value. */
if (pcm_val < 0) {
pcm_val = BIAS - pcm_val;
mask = 0x7F;
} else {
pcm_val += BIAS;
mask = 0xFF;
}
if (pcm_val > 0x7FFF)
pcm_val = 0x7FFF;
/* Convert the scaled magnitude to segment number. */
seg = val_seg(pcm_val);
/*
* Combine the sign, segment, quantization bits;
* and complement the code word.
*/
uval = (seg << 4) | ((pcm_val >> (seg + 3)) & 0xF);
return uval ^ mask;
}
/*
* ulaw2linear() - Convert a u-law value to 16-bit linear PCM
*
* First, a biased linear code is derived from the code word. An unbiased
* output can then be obtained by subtracting 33 from the biased code.
*
* Note that this function expects to be passed the complement of the
* original code word. This is in keeping with ISDN conventions.
*/
static int ulaw2linear(unsigned char u_val)
{
int t;
/* Complement to obtain normal u-law value. */
u_val = ~u_val;
/*
* Extract and bias the quantization bits. Then
* shift up by the segment number and subtract out the bias.
*/
t = ((u_val & QUANT_MASK) << 3) + BIAS;
t <<= ((unsigned)u_val & SEG_MASK) >> SEG_SHIFT;
return ((u_val & SIGN_BIT) ? (BIAS - t) : (t - BIAS));
}
/*
* Basic Mu-Law plugin
*/
typedef void (*mulaw_f)(struct snd_pcm_plugin *plugin,
const struct snd_pcm_plugin_channel *src_channels,
struct snd_pcm_plugin_channel *dst_channels,
snd_pcm_uframes_t frames);
struct mulaw_priv {
mulaw_f func;
int cvt_endian; /* need endian conversion? */
unsigned int native_ofs; /* byte offset in native format */
unsigned int copy_ofs; /* byte offset in s16 format */
unsigned int native_bytes; /* byte size of the native format */
unsigned int copy_bytes; /* bytes to copy per conversion */
u16 flip; /* MSB flip for signedness, done after endian conversion */
};
static inline void cvt_s16_to_native(struct mulaw_priv *data,
unsigned char *dst, u16 sample)
{
sample ^= data->flip;
if (data->cvt_endian)
sample = swab16(sample);
if (data->native_bytes > data->copy_bytes)
memset(dst, 0, data->native_bytes);
memcpy(dst + data->native_ofs, (char *)&sample + data->copy_ofs,
data->copy_bytes);
}
static void mulaw_decode(struct snd_pcm_plugin *plugin,
const struct snd_pcm_plugin_channel *src_channels,
struct snd_pcm_plugin_channel *dst_channels,
snd_pcm_uframes_t frames)
{
struct mulaw_priv *data = (struct mulaw_priv *)plugin->extra_data;
int channel;
int nchannels = plugin->src_format.channels;
for (channel = 0; channel < nchannels; ++channel) {
char *src;
char *dst;
int src_step, dst_step;
snd_pcm_uframes_t frames1;
if (!src_channels[channel].enabled) {
if (dst_channels[channel].wanted)
snd_pcm_area_silence(&dst_channels[channel].area, 0, frames, plugin->dst_format.format);
dst_channels[channel].enabled = 0;
continue;
}
dst_channels[channel].enabled = 1;
src = src_channels[channel].area.addr + src_channels[channel].area.first / 8;
dst = dst_channels[channel].area.addr + dst_channels[channel].area.first / 8;
src_step = src_channels[channel].area.step / 8;
dst_step = dst_channels[channel].area.step / 8;
frames1 = frames;
while (frames1-- > 0) {
signed short sample = ulaw2linear(*src);
cvt_s16_to_native(data, dst, sample);
src += src_step;
dst += dst_step;
}
}
}
static inline signed short cvt_native_to_s16(struct mulaw_priv *data,
unsigned char *src)
{
u16 sample = 0;
memcpy((char *)&sample + data->copy_ofs, src + data->native_ofs,
data->copy_bytes);
if (data->cvt_endian)
sample = swab16(sample);
sample ^= data->flip;
return (signed short)sample;
}
static void mulaw_encode(struct snd_pcm_plugin *plugin,
const struct snd_pcm_plugin_channel *src_channels,
struct snd_pcm_plugin_channel *dst_channels,
snd_pcm_uframes_t frames)
{
struct mulaw_priv *data = (struct mulaw_priv *)plugin->extra_data;
int channel;
int nchannels = plugin->src_format.channels;
for (channel = 0; channel < nchannels; ++channel) {
char *src;
char *dst;
int src_step, dst_step;
snd_pcm_uframes_t frames1;
if (!src_channels[channel].enabled) {
if (dst_channels[channel].wanted)
snd_pcm_area_silence(&dst_channels[channel].area, 0, frames, plugin->dst_format.format);
dst_channels[channel].enabled = 0;
continue;
}
dst_channels[channel].enabled = 1;
src = src_channels[channel].area.addr + src_channels[channel].area.first / 8;
dst = dst_channels[channel].area.addr + dst_channels[channel].area.first / 8;
src_step = src_channels[channel].area.step / 8;
dst_step = dst_channels[channel].area.step / 8;
frames1 = frames;
while (frames1-- > 0) {
signed short sample = cvt_native_to_s16(data, src);
*dst = linear2ulaw(sample);
src += src_step;
dst += dst_step;
}
}
}
static snd_pcm_sframes_t mulaw_transfer(struct snd_pcm_plugin *plugin,
const struct snd_pcm_plugin_channel *src_channels,
struct snd_pcm_plugin_channel *dst_channels,
snd_pcm_uframes_t frames)
{
struct mulaw_priv *data;
if (snd_BUG_ON(!plugin || !src_channels || !dst_channels))
return -ENXIO;
if (frames == 0)
return 0;
#ifdef CONFIG_SND_DEBUG
{
unsigned int channel;
for (channel = 0; channel < plugin->src_format.channels; channel++) {
if (snd_BUG_ON(src_channels[channel].area.first % 8 ||
src_channels[channel].area.step % 8))
return -ENXIO;
if (snd_BUG_ON(dst_channels[channel].area.first % 8 ||
dst_channels[channel].area.step % 8))
return -ENXIO;
}
}
#endif
data = (struct mulaw_priv *)plugin->extra_data;
data->func(plugin, src_channels, dst_channels, frames);
return frames;
}
static void init_data(struct mulaw_priv *data, int format)
{
#ifdef SNDRV_LITTLE_ENDIAN
data->cvt_endian = snd_pcm_format_big_endian(format) > 0;
#else
data->cvt_endian = snd_pcm_format_little_endian(format) > 0;
#endif
if (!snd_pcm_format_signed(format))
data->flip = 0x8000;
data->native_bytes = snd_pcm_format_physical_width(format) / 8;
data->copy_bytes = data->native_bytes < 2 ? 1 : 2;
if (snd_pcm_format_little_endian(format)) {
data->native_ofs = data->native_bytes - data->copy_bytes;
data->copy_ofs = 2 - data->copy_bytes;
} else {
/* S24 in 4bytes need an 1 byte offset */
data->native_ofs = data->native_bytes -
snd_pcm_format_width(format) / 8;
}
}
int snd_pcm_plugin_build_mulaw(struct snd_pcm_substream *plug,
struct snd_pcm_plugin_format *src_format,
struct snd_pcm_plugin_format *dst_format,
struct snd_pcm_plugin **r_plugin)
{
int err;
struct mulaw_priv *data;
struct snd_pcm_plugin *plugin;
struct snd_pcm_plugin_format *format;
mulaw_f func;
if (snd_BUG_ON(!r_plugin))
return -ENXIO;
*r_plugin = NULL;
if (snd_BUG_ON(src_format->rate != dst_format->rate))
return -ENXIO;
if (snd_BUG_ON(src_format->channels != dst_format->channels))
return -ENXIO;
if (dst_format->format == SNDRV_PCM_FORMAT_MU_LAW) {
format = src_format;
func = mulaw_encode;
}
else if (src_format->format == SNDRV_PCM_FORMAT_MU_LAW) {
format = dst_format;
func = mulaw_decode;
}
else {
snd_BUG();
return -EINVAL;
}
if (snd_BUG_ON(!snd_pcm_format_linear(format->format)))
return -ENXIO;
err = snd_pcm_plugin_build(plug, "Mu-Law<->linear conversion",
src_format, dst_format,
sizeof(struct mulaw_priv), &plugin);
if (err < 0)
return err;
data = (struct mulaw_priv *)plugin->extra_data;
data->func = func;
init_data(data, format->format);
plugin->transfer = mulaw_transfer;
*r_plugin = plugin;
return 0;
}
| gpl-2.0 |
jcadduono/nethunter_kernel_kccat6 | fs/btrfs/delayed-ref.c | 2142 | 25254 | /*
* Copyright (C) 2009 Oracle. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License v2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 021110-1307, USA.
*/
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/sort.h>
#include "ctree.h"
#include "delayed-ref.h"
#include "transaction.h"
struct kmem_cache *btrfs_delayed_ref_head_cachep;
struct kmem_cache *btrfs_delayed_tree_ref_cachep;
struct kmem_cache *btrfs_delayed_data_ref_cachep;
struct kmem_cache *btrfs_delayed_extent_op_cachep;
/*
* delayed back reference update tracking. For subvolume trees
* we queue up extent allocations and backref maintenance for
* delayed processing. This avoids deep call chains where we
* add extents in the middle of btrfs_search_slot, and it allows
* us to buffer up frequently modified backrefs in an rb tree instead
* of hammering updates on the extent allocation tree.
*/
/*
* compare two delayed tree backrefs with same bytenr and type
*/
static int comp_tree_refs(struct btrfs_delayed_tree_ref *ref2,
struct btrfs_delayed_tree_ref *ref1, int type)
{
if (type == BTRFS_TREE_BLOCK_REF_KEY) {
if (ref1->root < ref2->root)
return -1;
if (ref1->root > ref2->root)
return 1;
} else {
if (ref1->parent < ref2->parent)
return -1;
if (ref1->parent > ref2->parent)
return 1;
}
return 0;
}
/*
* compare two delayed data backrefs with same bytenr and type
*/
static int comp_data_refs(struct btrfs_delayed_data_ref *ref2,
struct btrfs_delayed_data_ref *ref1)
{
if (ref1->node.type == BTRFS_EXTENT_DATA_REF_KEY) {
if (ref1->root < ref2->root)
return -1;
if (ref1->root > ref2->root)
return 1;
if (ref1->objectid < ref2->objectid)
return -1;
if (ref1->objectid > ref2->objectid)
return 1;
if (ref1->offset < ref2->offset)
return -1;
if (ref1->offset > ref2->offset)
return 1;
} else {
if (ref1->parent < ref2->parent)
return -1;
if (ref1->parent > ref2->parent)
return 1;
}
return 0;
}
/*
* entries in the rb tree are ordered by the byte number of the extent,
* type of the delayed backrefs and content of delayed backrefs.
*/
static int comp_entry(struct btrfs_delayed_ref_node *ref2,
struct btrfs_delayed_ref_node *ref1,
bool compare_seq)
{
if (ref1->bytenr < ref2->bytenr)
return -1;
if (ref1->bytenr > ref2->bytenr)
return 1;
if (ref1->is_head && ref2->is_head)
return 0;
if (ref2->is_head)
return -1;
if (ref1->is_head)
return 1;
if (ref1->type < ref2->type)
return -1;
if (ref1->type > ref2->type)
return 1;
/* merging of sequenced refs is not allowed */
if (compare_seq) {
if (ref1->seq < ref2->seq)
return -1;
if (ref1->seq > ref2->seq)
return 1;
}
if (ref1->type == BTRFS_TREE_BLOCK_REF_KEY ||
ref1->type == BTRFS_SHARED_BLOCK_REF_KEY) {
return comp_tree_refs(btrfs_delayed_node_to_tree_ref(ref2),
btrfs_delayed_node_to_tree_ref(ref1),
ref1->type);
} else if (ref1->type == BTRFS_EXTENT_DATA_REF_KEY ||
ref1->type == BTRFS_SHARED_DATA_REF_KEY) {
return comp_data_refs(btrfs_delayed_node_to_data_ref(ref2),
btrfs_delayed_node_to_data_ref(ref1));
}
BUG();
return 0;
}
/*
* insert a new ref into the rbtree. This returns any existing refs
* for the same (bytenr,parent) tuple, or NULL if the new node was properly
* inserted.
*/
static struct btrfs_delayed_ref_node *tree_insert(struct rb_root *root,
struct rb_node *node)
{
struct rb_node **p = &root->rb_node;
struct rb_node *parent_node = NULL;
struct btrfs_delayed_ref_node *entry;
struct btrfs_delayed_ref_node *ins;
int cmp;
ins = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
while (*p) {
parent_node = *p;
entry = rb_entry(parent_node, struct btrfs_delayed_ref_node,
rb_node);
cmp = comp_entry(entry, ins, 1);
if (cmp < 0)
p = &(*p)->rb_left;
else if (cmp > 0)
p = &(*p)->rb_right;
else
return entry;
}
rb_link_node(node, parent_node, p);
rb_insert_color(node, root);
return NULL;
}
/*
* find an head entry based on bytenr. This returns the delayed ref
* head if it was able to find one, or NULL if nothing was in that spot.
* If return_bigger is given, the next bigger entry is returned if no exact
* match is found.
*/
static struct btrfs_delayed_ref_node *find_ref_head(struct rb_root *root,
u64 bytenr,
struct btrfs_delayed_ref_node **last,
int return_bigger)
{
struct rb_node *n;
struct btrfs_delayed_ref_node *entry;
int cmp = 0;
again:
n = root->rb_node;
entry = NULL;
while (n) {
entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
WARN_ON(!entry->in_tree);
if (last)
*last = entry;
if (bytenr < entry->bytenr)
cmp = -1;
else if (bytenr > entry->bytenr)
cmp = 1;
else if (!btrfs_delayed_ref_is_head(entry))
cmp = 1;
else
cmp = 0;
if (cmp < 0)
n = n->rb_left;
else if (cmp > 0)
n = n->rb_right;
else
return entry;
}
if (entry && return_bigger) {
if (cmp > 0) {
n = rb_next(&entry->rb_node);
if (!n)
n = rb_first(root);
entry = rb_entry(n, struct btrfs_delayed_ref_node,
rb_node);
bytenr = entry->bytenr;
return_bigger = 0;
goto again;
}
return entry;
}
return NULL;
}
int btrfs_delayed_ref_lock(struct btrfs_trans_handle *trans,
struct btrfs_delayed_ref_head *head)
{
struct btrfs_delayed_ref_root *delayed_refs;
delayed_refs = &trans->transaction->delayed_refs;
assert_spin_locked(&delayed_refs->lock);
if (mutex_trylock(&head->mutex))
return 0;
atomic_inc(&head->node.refs);
spin_unlock(&delayed_refs->lock);
mutex_lock(&head->mutex);
spin_lock(&delayed_refs->lock);
if (!head->node.in_tree) {
mutex_unlock(&head->mutex);
btrfs_put_delayed_ref(&head->node);
return -EAGAIN;
}
btrfs_put_delayed_ref(&head->node);
return 0;
}
static void inline drop_delayed_ref(struct btrfs_trans_handle *trans,
struct btrfs_delayed_ref_root *delayed_refs,
struct btrfs_delayed_ref_node *ref)
{
rb_erase(&ref->rb_node, &delayed_refs->root);
ref->in_tree = 0;
btrfs_put_delayed_ref(ref);
delayed_refs->num_entries--;
if (trans->delayed_ref_updates)
trans->delayed_ref_updates--;
}
static int merge_ref(struct btrfs_trans_handle *trans,
struct btrfs_delayed_ref_root *delayed_refs,
struct btrfs_delayed_ref_node *ref, u64 seq)
{
struct rb_node *node;
int merged = 0;
int mod = 0;
int done = 0;
node = rb_prev(&ref->rb_node);
while (node) {
struct btrfs_delayed_ref_node *next;
next = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
node = rb_prev(node);
if (next->bytenr != ref->bytenr)
break;
if (seq && next->seq >= seq)
break;
if (comp_entry(ref, next, 0))
continue;
if (ref->action == next->action) {
mod = next->ref_mod;
} else {
if (ref->ref_mod < next->ref_mod) {
struct btrfs_delayed_ref_node *tmp;
tmp = ref;
ref = next;
next = tmp;
done = 1;
}
mod = -next->ref_mod;
}
merged++;
drop_delayed_ref(trans, delayed_refs, next);
ref->ref_mod += mod;
if (ref->ref_mod == 0) {
drop_delayed_ref(trans, delayed_refs, ref);
break;
} else {
/*
* You can't have multiples of the same ref on a tree
* block.
*/
WARN_ON(ref->type == BTRFS_TREE_BLOCK_REF_KEY ||
ref->type == BTRFS_SHARED_BLOCK_REF_KEY);
}
if (done)
break;
node = rb_prev(&ref->rb_node);
}
return merged;
}
void btrfs_merge_delayed_refs(struct btrfs_trans_handle *trans,
struct btrfs_fs_info *fs_info,
struct btrfs_delayed_ref_root *delayed_refs,
struct btrfs_delayed_ref_head *head)
{
struct rb_node *node;
u64 seq = 0;
spin_lock(&fs_info->tree_mod_seq_lock);
if (!list_empty(&fs_info->tree_mod_seq_list)) {
struct seq_list *elem;
elem = list_first_entry(&fs_info->tree_mod_seq_list,
struct seq_list, list);
seq = elem->seq;
}
spin_unlock(&fs_info->tree_mod_seq_lock);
node = rb_prev(&head->node.rb_node);
while (node) {
struct btrfs_delayed_ref_node *ref;
ref = rb_entry(node, struct btrfs_delayed_ref_node,
rb_node);
if (ref->bytenr != head->node.bytenr)
break;
/* We can't merge refs that are outside of our seq count */
if (seq && ref->seq >= seq)
break;
if (merge_ref(trans, delayed_refs, ref, seq))
node = rb_prev(&head->node.rb_node);
else
node = rb_prev(node);
}
}
int btrfs_check_delayed_seq(struct btrfs_fs_info *fs_info,
struct btrfs_delayed_ref_root *delayed_refs,
u64 seq)
{
struct seq_list *elem;
int ret = 0;
spin_lock(&fs_info->tree_mod_seq_lock);
if (!list_empty(&fs_info->tree_mod_seq_list)) {
elem = list_first_entry(&fs_info->tree_mod_seq_list,
struct seq_list, list);
if (seq >= elem->seq) {
pr_debug("holding back delayed_ref %#x.%x, lowest is %#x.%x (%p)\n",
(u32)(seq >> 32), (u32)seq,
(u32)(elem->seq >> 32), (u32)elem->seq,
delayed_refs);
ret = 1;
}
}
spin_unlock(&fs_info->tree_mod_seq_lock);
return ret;
}
int btrfs_find_ref_cluster(struct btrfs_trans_handle *trans,
struct list_head *cluster, u64 start)
{
int count = 0;
struct btrfs_delayed_ref_root *delayed_refs;
struct rb_node *node;
struct btrfs_delayed_ref_node *ref;
struct btrfs_delayed_ref_head *head;
delayed_refs = &trans->transaction->delayed_refs;
if (start == 0) {
node = rb_first(&delayed_refs->root);
} else {
ref = NULL;
find_ref_head(&delayed_refs->root, start + 1, &ref, 1);
if (ref) {
node = &ref->rb_node;
} else
node = rb_first(&delayed_refs->root);
}
again:
while (node && count < 32) {
ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
if (btrfs_delayed_ref_is_head(ref)) {
head = btrfs_delayed_node_to_head(ref);
if (list_empty(&head->cluster)) {
list_add_tail(&head->cluster, cluster);
delayed_refs->run_delayed_start =
head->node.bytenr;
count++;
WARN_ON(delayed_refs->num_heads_ready == 0);
delayed_refs->num_heads_ready--;
} else if (count) {
/* the goal of the clustering is to find extents
* that are likely to end up in the same extent
* leaf on disk. So, we don't want them spread
* all over the tree. Stop now if we've hit
* a head that was already in use
*/
break;
}
}
node = rb_next(node);
}
if (count) {
return 0;
} else if (start) {
/*
* we've gone to the end of the rbtree without finding any
* clusters. start from the beginning and try again
*/
start = 0;
node = rb_first(&delayed_refs->root);
goto again;
}
return 1;
}
void btrfs_release_ref_cluster(struct list_head *cluster)
{
struct list_head *pos, *q;
list_for_each_safe(pos, q, cluster)
list_del_init(pos);
}
/*
* helper function to update an extent delayed ref in the
* rbtree. existing and update must both have the same
* bytenr and parent
*
* This may free existing if the update cancels out whatever
* operation it was doing.
*/
static noinline void
update_existing_ref(struct btrfs_trans_handle *trans,
struct btrfs_delayed_ref_root *delayed_refs,
struct btrfs_delayed_ref_node *existing,
struct btrfs_delayed_ref_node *update)
{
if (update->action != existing->action) {
/*
* this is effectively undoing either an add or a
* drop. We decrement the ref_mod, and if it goes
* down to zero we just delete the entry without
* every changing the extent allocation tree.
*/
existing->ref_mod--;
if (existing->ref_mod == 0)
drop_delayed_ref(trans, delayed_refs, existing);
else
WARN_ON(existing->type == BTRFS_TREE_BLOCK_REF_KEY ||
existing->type == BTRFS_SHARED_BLOCK_REF_KEY);
} else {
WARN_ON(existing->type == BTRFS_TREE_BLOCK_REF_KEY ||
existing->type == BTRFS_SHARED_BLOCK_REF_KEY);
/*
* the action on the existing ref matches
* the action on the ref we're trying to add.
* Bump the ref_mod by one so the backref that
* is eventually added/removed has the correct
* reference count
*/
existing->ref_mod += update->ref_mod;
}
}
/*
* helper function to update the accounting in the head ref
* existing and update must have the same bytenr
*/
static noinline void
update_existing_head_ref(struct btrfs_delayed_ref_node *existing,
struct btrfs_delayed_ref_node *update)
{
struct btrfs_delayed_ref_head *existing_ref;
struct btrfs_delayed_ref_head *ref;
existing_ref = btrfs_delayed_node_to_head(existing);
ref = btrfs_delayed_node_to_head(update);
BUG_ON(existing_ref->is_data != ref->is_data);
if (ref->must_insert_reserved) {
/* if the extent was freed and then
* reallocated before the delayed ref
* entries were processed, we can end up
* with an existing head ref without
* the must_insert_reserved flag set.
* Set it again here
*/
existing_ref->must_insert_reserved = ref->must_insert_reserved;
/*
* update the num_bytes so we make sure the accounting
* is done correctly
*/
existing->num_bytes = update->num_bytes;
}
if (ref->extent_op) {
if (!existing_ref->extent_op) {
existing_ref->extent_op = ref->extent_op;
} else {
if (ref->extent_op->update_key) {
memcpy(&existing_ref->extent_op->key,
&ref->extent_op->key,
sizeof(ref->extent_op->key));
existing_ref->extent_op->update_key = 1;
}
if (ref->extent_op->update_flags) {
existing_ref->extent_op->flags_to_set |=
ref->extent_op->flags_to_set;
existing_ref->extent_op->update_flags = 1;
}
btrfs_free_delayed_extent_op(ref->extent_op);
}
}
/*
* update the reference mod on the head to reflect this new operation
*/
existing->ref_mod += update->ref_mod;
}
/*
* helper function to actually insert a head node into the rbtree.
* this does all the dirty work in terms of maintaining the correct
* overall modification count.
*/
static noinline void add_delayed_ref_head(struct btrfs_fs_info *fs_info,
struct btrfs_trans_handle *trans,
struct btrfs_delayed_ref_node *ref,
u64 bytenr, u64 num_bytes,
int action, int is_data)
{
struct btrfs_delayed_ref_node *existing;
struct btrfs_delayed_ref_head *head_ref = NULL;
struct btrfs_delayed_ref_root *delayed_refs;
int count_mod = 1;
int must_insert_reserved = 0;
/*
* the head node stores the sum of all the mods, so dropping a ref
* should drop the sum in the head node by one.
*/
if (action == BTRFS_UPDATE_DELAYED_HEAD)
count_mod = 0;
else if (action == BTRFS_DROP_DELAYED_REF)
count_mod = -1;
/*
* BTRFS_ADD_DELAYED_EXTENT means that we need to update
* the reserved accounting when the extent is finally added, or
* if a later modification deletes the delayed ref without ever
* inserting the extent into the extent allocation tree.
* ref->must_insert_reserved is the flag used to record
* that accounting mods are required.
*
* Once we record must_insert_reserved, switch the action to
* BTRFS_ADD_DELAYED_REF because other special casing is not required.
*/
if (action == BTRFS_ADD_DELAYED_EXTENT)
must_insert_reserved = 1;
else
must_insert_reserved = 0;
delayed_refs = &trans->transaction->delayed_refs;
/* first set the basic ref node struct up */
atomic_set(&ref->refs, 1);
ref->bytenr = bytenr;
ref->num_bytes = num_bytes;
ref->ref_mod = count_mod;
ref->type = 0;
ref->action = 0;
ref->is_head = 1;
ref->in_tree = 1;
ref->seq = 0;
head_ref = btrfs_delayed_node_to_head(ref);
head_ref->must_insert_reserved = must_insert_reserved;
head_ref->is_data = is_data;
INIT_LIST_HEAD(&head_ref->cluster);
mutex_init(&head_ref->mutex);
trace_btrfs_delayed_ref_head(ref, head_ref, action);
existing = tree_insert(&delayed_refs->root, &ref->rb_node);
if (existing) {
update_existing_head_ref(existing, ref);
/*
* we've updated the existing ref, free the newly
* allocated ref
*/
kmem_cache_free(btrfs_delayed_ref_head_cachep, head_ref);
} else {
delayed_refs->num_heads++;
delayed_refs->num_heads_ready++;
delayed_refs->num_entries++;
trans->delayed_ref_updates++;
}
}
/*
* helper to insert a delayed tree ref into the rbtree.
*/
static noinline void add_delayed_tree_ref(struct btrfs_fs_info *fs_info,
struct btrfs_trans_handle *trans,
struct btrfs_delayed_ref_node *ref,
u64 bytenr, u64 num_bytes, u64 parent,
u64 ref_root, int level, int action,
int for_cow)
{
struct btrfs_delayed_ref_node *existing;
struct btrfs_delayed_tree_ref *full_ref;
struct btrfs_delayed_ref_root *delayed_refs;
u64 seq = 0;
if (action == BTRFS_ADD_DELAYED_EXTENT)
action = BTRFS_ADD_DELAYED_REF;
delayed_refs = &trans->transaction->delayed_refs;
/* first set the basic ref node struct up */
atomic_set(&ref->refs, 1);
ref->bytenr = bytenr;
ref->num_bytes = num_bytes;
ref->ref_mod = 1;
ref->action = action;
ref->is_head = 0;
ref->in_tree = 1;
if (need_ref_seq(for_cow, ref_root))
seq = btrfs_get_tree_mod_seq(fs_info, &trans->delayed_ref_elem);
ref->seq = seq;
full_ref = btrfs_delayed_node_to_tree_ref(ref);
full_ref->parent = parent;
full_ref->root = ref_root;
if (parent)
ref->type = BTRFS_SHARED_BLOCK_REF_KEY;
else
ref->type = BTRFS_TREE_BLOCK_REF_KEY;
full_ref->level = level;
trace_btrfs_delayed_tree_ref(ref, full_ref, action);
existing = tree_insert(&delayed_refs->root, &ref->rb_node);
if (existing) {
update_existing_ref(trans, delayed_refs, existing, ref);
/*
* we've updated the existing ref, free the newly
* allocated ref
*/
kmem_cache_free(btrfs_delayed_tree_ref_cachep, full_ref);
} else {
delayed_refs->num_entries++;
trans->delayed_ref_updates++;
}
}
/*
* helper to insert a delayed data ref into the rbtree.
*/
static noinline void add_delayed_data_ref(struct btrfs_fs_info *fs_info,
struct btrfs_trans_handle *trans,
struct btrfs_delayed_ref_node *ref,
u64 bytenr, u64 num_bytes, u64 parent,
u64 ref_root, u64 owner, u64 offset,
int action, int for_cow)
{
struct btrfs_delayed_ref_node *existing;
struct btrfs_delayed_data_ref *full_ref;
struct btrfs_delayed_ref_root *delayed_refs;
u64 seq = 0;
if (action == BTRFS_ADD_DELAYED_EXTENT)
action = BTRFS_ADD_DELAYED_REF;
delayed_refs = &trans->transaction->delayed_refs;
/* first set the basic ref node struct up */
atomic_set(&ref->refs, 1);
ref->bytenr = bytenr;
ref->num_bytes = num_bytes;
ref->ref_mod = 1;
ref->action = action;
ref->is_head = 0;
ref->in_tree = 1;
if (need_ref_seq(for_cow, ref_root))
seq = btrfs_get_tree_mod_seq(fs_info, &trans->delayed_ref_elem);
ref->seq = seq;
full_ref = btrfs_delayed_node_to_data_ref(ref);
full_ref->parent = parent;
full_ref->root = ref_root;
if (parent)
ref->type = BTRFS_SHARED_DATA_REF_KEY;
else
ref->type = BTRFS_EXTENT_DATA_REF_KEY;
full_ref->objectid = owner;
full_ref->offset = offset;
trace_btrfs_delayed_data_ref(ref, full_ref, action);
existing = tree_insert(&delayed_refs->root, &ref->rb_node);
if (existing) {
update_existing_ref(trans, delayed_refs, existing, ref);
/*
* we've updated the existing ref, free the newly
* allocated ref
*/
kmem_cache_free(btrfs_delayed_data_ref_cachep, full_ref);
} else {
delayed_refs->num_entries++;
trans->delayed_ref_updates++;
}
}
/*
* add a delayed tree ref. This does all of the accounting required
* to make sure the delayed ref is eventually processed before this
* transaction commits.
*/
int btrfs_add_delayed_tree_ref(struct btrfs_fs_info *fs_info,
struct btrfs_trans_handle *trans,
u64 bytenr, u64 num_bytes, u64 parent,
u64 ref_root, int level, int action,
struct btrfs_delayed_extent_op *extent_op,
int for_cow)
{
struct btrfs_delayed_tree_ref *ref;
struct btrfs_delayed_ref_head *head_ref;
struct btrfs_delayed_ref_root *delayed_refs;
BUG_ON(extent_op && extent_op->is_data);
ref = kmem_cache_alloc(btrfs_delayed_tree_ref_cachep, GFP_NOFS);
if (!ref)
return -ENOMEM;
head_ref = kmem_cache_alloc(btrfs_delayed_ref_head_cachep, GFP_NOFS);
if (!head_ref) {
kmem_cache_free(btrfs_delayed_tree_ref_cachep, ref);
return -ENOMEM;
}
head_ref->extent_op = extent_op;
delayed_refs = &trans->transaction->delayed_refs;
spin_lock(&delayed_refs->lock);
/*
* insert both the head node and the new ref without dropping
* the spin lock
*/
add_delayed_ref_head(fs_info, trans, &head_ref->node, bytenr,
num_bytes, action, 0);
add_delayed_tree_ref(fs_info, trans, &ref->node, bytenr,
num_bytes, parent, ref_root, level, action,
for_cow);
spin_unlock(&delayed_refs->lock);
if (need_ref_seq(for_cow, ref_root))
btrfs_qgroup_record_ref(trans, &ref->node, extent_op);
return 0;
}
/*
* add a delayed data ref. it's similar to btrfs_add_delayed_tree_ref.
*/
int btrfs_add_delayed_data_ref(struct btrfs_fs_info *fs_info,
struct btrfs_trans_handle *trans,
u64 bytenr, u64 num_bytes,
u64 parent, u64 ref_root,
u64 owner, u64 offset, int action,
struct btrfs_delayed_extent_op *extent_op,
int for_cow)
{
struct btrfs_delayed_data_ref *ref;
struct btrfs_delayed_ref_head *head_ref;
struct btrfs_delayed_ref_root *delayed_refs;
BUG_ON(extent_op && !extent_op->is_data);
ref = kmem_cache_alloc(btrfs_delayed_data_ref_cachep, GFP_NOFS);
if (!ref)
return -ENOMEM;
head_ref = kmem_cache_alloc(btrfs_delayed_ref_head_cachep, GFP_NOFS);
if (!head_ref) {
kmem_cache_free(btrfs_delayed_data_ref_cachep, ref);
return -ENOMEM;
}
head_ref->extent_op = extent_op;
delayed_refs = &trans->transaction->delayed_refs;
spin_lock(&delayed_refs->lock);
/*
* insert both the head node and the new ref without dropping
* the spin lock
*/
add_delayed_ref_head(fs_info, trans, &head_ref->node, bytenr,
num_bytes, action, 1);
add_delayed_data_ref(fs_info, trans, &ref->node, bytenr,
num_bytes, parent, ref_root, owner, offset,
action, for_cow);
spin_unlock(&delayed_refs->lock);
if (need_ref_seq(for_cow, ref_root))
btrfs_qgroup_record_ref(trans, &ref->node, extent_op);
return 0;
}
int btrfs_add_delayed_extent_op(struct btrfs_fs_info *fs_info,
struct btrfs_trans_handle *trans,
u64 bytenr, u64 num_bytes,
struct btrfs_delayed_extent_op *extent_op)
{
struct btrfs_delayed_ref_head *head_ref;
struct btrfs_delayed_ref_root *delayed_refs;
head_ref = kmem_cache_alloc(btrfs_delayed_ref_head_cachep, GFP_NOFS);
if (!head_ref)
return -ENOMEM;
head_ref->extent_op = extent_op;
delayed_refs = &trans->transaction->delayed_refs;
spin_lock(&delayed_refs->lock);
add_delayed_ref_head(fs_info, trans, &head_ref->node, bytenr,
num_bytes, BTRFS_UPDATE_DELAYED_HEAD,
extent_op->is_data);
spin_unlock(&delayed_refs->lock);
return 0;
}
/*
* this does a simple search for the head node for a given extent.
* It must be called with the delayed ref spinlock held, and it returns
* the head node if any where found, or NULL if not.
*/
struct btrfs_delayed_ref_head *
btrfs_find_delayed_ref_head(struct btrfs_trans_handle *trans, u64 bytenr)
{
struct btrfs_delayed_ref_node *ref;
struct btrfs_delayed_ref_root *delayed_refs;
delayed_refs = &trans->transaction->delayed_refs;
ref = find_ref_head(&delayed_refs->root, bytenr, NULL, 0);
if (ref)
return btrfs_delayed_node_to_head(ref);
return NULL;
}
void btrfs_delayed_ref_exit(void)
{
if (btrfs_delayed_ref_head_cachep)
kmem_cache_destroy(btrfs_delayed_ref_head_cachep);
if (btrfs_delayed_tree_ref_cachep)
kmem_cache_destroy(btrfs_delayed_tree_ref_cachep);
if (btrfs_delayed_data_ref_cachep)
kmem_cache_destroy(btrfs_delayed_data_ref_cachep);
if (btrfs_delayed_extent_op_cachep)
kmem_cache_destroy(btrfs_delayed_extent_op_cachep);
}
int btrfs_delayed_ref_init(void)
{
btrfs_delayed_ref_head_cachep = kmem_cache_create(
"btrfs_delayed_ref_head",
sizeof(struct btrfs_delayed_ref_head), 0,
SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
if (!btrfs_delayed_ref_head_cachep)
goto fail;
btrfs_delayed_tree_ref_cachep = kmem_cache_create(
"btrfs_delayed_tree_ref",
sizeof(struct btrfs_delayed_tree_ref), 0,
SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
if (!btrfs_delayed_tree_ref_cachep)
goto fail;
btrfs_delayed_data_ref_cachep = kmem_cache_create(
"btrfs_delayed_data_ref",
sizeof(struct btrfs_delayed_data_ref), 0,
SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
if (!btrfs_delayed_data_ref_cachep)
goto fail;
btrfs_delayed_extent_op_cachep = kmem_cache_create(
"btrfs_delayed_extent_op",
sizeof(struct btrfs_delayed_extent_op), 0,
SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
if (!btrfs_delayed_extent_op_cachep)
goto fail;
return 0;
fail:
btrfs_delayed_ref_exit();
return -ENOMEM;
}
| gpl-2.0 |
zarboz/EvilZ-Kernel122 | scripts/kconfig/gconf.c | 2398 | 40846 | /* Hey EMACS -*- linux-c -*- */
/*
*
* Copyright (C) 2002-2003 Romain Lievin <roms@tilp.info>
* Released under the terms of the GNU GPL v2.0.
*
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include "lkc.h"
#include "images.c"
#include <glade/glade.h>
#include <gtk/gtk.h>
#include <glib.h>
#include <gdk/gdkkeysyms.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
//#define DEBUG
enum {
SINGLE_VIEW, SPLIT_VIEW, FULL_VIEW
};
enum {
OPT_NORMAL, OPT_ALL, OPT_PROMPT
};
static gint view_mode = FULL_VIEW;
static gboolean show_name = TRUE;
static gboolean show_range = TRUE;
static gboolean show_value = TRUE;
static gboolean resizeable = FALSE;
static int opt_mode = OPT_NORMAL;
GtkWidget *main_wnd = NULL;
GtkWidget *tree1_w = NULL; // left frame
GtkWidget *tree2_w = NULL; // right frame
GtkWidget *text_w = NULL;
GtkWidget *hpaned = NULL;
GtkWidget *vpaned = NULL;
GtkWidget *back_btn = NULL;
GtkWidget *save_btn = NULL;
GtkWidget *save_menu_item = NULL;
GtkTextTag *tag1, *tag2;
GdkColor color;
GtkTreeStore *tree1, *tree2, *tree;
GtkTreeModel *model1, *model2;
static GtkTreeIter *parents[256];
static gint indent;
static struct menu *current; // current node for SINGLE view
static struct menu *browsed; // browsed node for SPLIT view
enum {
COL_OPTION, COL_NAME, COL_NO, COL_MOD, COL_YES, COL_VALUE,
COL_MENU, COL_COLOR, COL_EDIT, COL_PIXBUF,
COL_PIXVIS, COL_BTNVIS, COL_BTNACT, COL_BTNINC, COL_BTNRAD,
COL_NUMBER
};
static void display_list(void);
static void display_tree(struct menu *menu);
static void display_tree_part(void);
static void update_tree(struct menu *src, GtkTreeIter * dst);
static void set_node(GtkTreeIter * node, struct menu *menu, gchar ** row);
static gchar **fill_row(struct menu *menu);
static void conf_changed(void);
/* Helping/Debugging Functions */
const char *dbg_sym_flags(int val)
{
static char buf[256];
bzero(buf, 256);
if (val & SYMBOL_CONST)
strcat(buf, "const/");
if (val & SYMBOL_CHECK)
strcat(buf, "check/");
if (val & SYMBOL_CHOICE)
strcat(buf, "choice/");
if (val & SYMBOL_CHOICEVAL)
strcat(buf, "choiceval/");
if (val & SYMBOL_VALID)
strcat(buf, "valid/");
if (val & SYMBOL_OPTIONAL)
strcat(buf, "optional/");
if (val & SYMBOL_WRITE)
strcat(buf, "write/");
if (val & SYMBOL_CHANGED)
strcat(buf, "changed/");
if (val & SYMBOL_AUTO)
strcat(buf, "auto/");
buf[strlen(buf) - 1] = '\0';
return buf;
}
void replace_button_icon(GladeXML * xml, GdkDrawable * window,
GtkStyle * style, gchar * btn_name, gchar ** xpm)
{
GdkPixmap *pixmap;
GdkBitmap *mask;
GtkToolButton *button;
GtkWidget *image;
pixmap = gdk_pixmap_create_from_xpm_d(window, &mask,
&style->bg[GTK_STATE_NORMAL],
xpm);
button = GTK_TOOL_BUTTON(glade_xml_get_widget(xml, btn_name));
image = gtk_image_new_from_pixmap(pixmap, mask);
gtk_widget_show(image);
gtk_tool_button_set_icon_widget(button, image);
}
/* Main Window Initialization */
void init_main_window(const gchar * glade_file)
{
GladeXML *xml;
GtkWidget *widget;
GtkTextBuffer *txtbuf;
GtkStyle *style;
xml = glade_xml_new(glade_file, "window1", NULL);
if (!xml)
g_error(_("GUI loading failed !\n"));
glade_xml_signal_autoconnect(xml);
main_wnd = glade_xml_get_widget(xml, "window1");
hpaned = glade_xml_get_widget(xml, "hpaned1");
vpaned = glade_xml_get_widget(xml, "vpaned1");
tree1_w = glade_xml_get_widget(xml, "treeview1");
tree2_w = glade_xml_get_widget(xml, "treeview2");
text_w = glade_xml_get_widget(xml, "textview3");
back_btn = glade_xml_get_widget(xml, "button1");
gtk_widget_set_sensitive(back_btn, FALSE);
widget = glade_xml_get_widget(xml, "show_name1");
gtk_check_menu_item_set_active((GtkCheckMenuItem *) widget,
show_name);
widget = glade_xml_get_widget(xml, "show_range1");
gtk_check_menu_item_set_active((GtkCheckMenuItem *) widget,
show_range);
widget = glade_xml_get_widget(xml, "show_data1");
gtk_check_menu_item_set_active((GtkCheckMenuItem *) widget,
show_value);
save_btn = glade_xml_get_widget(xml, "button3");
save_menu_item = glade_xml_get_widget(xml, "save1");
conf_set_changed_callback(conf_changed);
style = gtk_widget_get_style(main_wnd);
widget = glade_xml_get_widget(xml, "toolbar1");
#if 0 /* Use stock Gtk icons instead */
replace_button_icon(xml, main_wnd->window, style,
"button1", (gchar **) xpm_back);
replace_button_icon(xml, main_wnd->window, style,
"button2", (gchar **) xpm_load);
replace_button_icon(xml, main_wnd->window, style,
"button3", (gchar **) xpm_save);
#endif
replace_button_icon(xml, main_wnd->window, style,
"button4", (gchar **) xpm_single_view);
replace_button_icon(xml, main_wnd->window, style,
"button5", (gchar **) xpm_split_view);
replace_button_icon(xml, main_wnd->window, style,
"button6", (gchar **) xpm_tree_view);
#if 0
switch (view_mode) {
case SINGLE_VIEW:
widget = glade_xml_get_widget(xml, "button4");
g_signal_emit_by_name(widget, "clicked");
break;
case SPLIT_VIEW:
widget = glade_xml_get_widget(xml, "button5");
g_signal_emit_by_name(widget, "clicked");
break;
case FULL_VIEW:
widget = glade_xml_get_widget(xml, "button6");
g_signal_emit_by_name(widget, "clicked");
break;
}
#endif
txtbuf = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text_w));
tag1 = gtk_text_buffer_create_tag(txtbuf, "mytag1",
"foreground", "red",
"weight", PANGO_WEIGHT_BOLD,
NULL);
tag2 = gtk_text_buffer_create_tag(txtbuf, "mytag2",
/*"style", PANGO_STYLE_OBLIQUE, */
NULL);
gtk_window_set_title(GTK_WINDOW(main_wnd), rootmenu.prompt->text);
gtk_widget_show(main_wnd);
}
void init_tree_model(void)
{
gint i;
tree = tree2 = gtk_tree_store_new(COL_NUMBER,
G_TYPE_STRING, G_TYPE_STRING,
G_TYPE_STRING, G_TYPE_STRING,
G_TYPE_STRING, G_TYPE_STRING,
G_TYPE_POINTER, GDK_TYPE_COLOR,
G_TYPE_BOOLEAN, GDK_TYPE_PIXBUF,
G_TYPE_BOOLEAN, G_TYPE_BOOLEAN,
G_TYPE_BOOLEAN, G_TYPE_BOOLEAN,
G_TYPE_BOOLEAN);
model2 = GTK_TREE_MODEL(tree2);
for (parents[0] = NULL, i = 1; i < 256; i++)
parents[i] = (GtkTreeIter *) g_malloc(sizeof(GtkTreeIter));
tree1 = gtk_tree_store_new(COL_NUMBER,
G_TYPE_STRING, G_TYPE_STRING,
G_TYPE_STRING, G_TYPE_STRING,
G_TYPE_STRING, G_TYPE_STRING,
G_TYPE_POINTER, GDK_TYPE_COLOR,
G_TYPE_BOOLEAN, GDK_TYPE_PIXBUF,
G_TYPE_BOOLEAN, G_TYPE_BOOLEAN,
G_TYPE_BOOLEAN, G_TYPE_BOOLEAN,
G_TYPE_BOOLEAN);
model1 = GTK_TREE_MODEL(tree1);
}
void init_left_tree(void)
{
GtkTreeView *view = GTK_TREE_VIEW(tree1_w);
GtkCellRenderer *renderer;
GtkTreeSelection *sel;
GtkTreeViewColumn *column;
gtk_tree_view_set_model(view, model1);
gtk_tree_view_set_headers_visible(view, TRUE);
gtk_tree_view_set_rules_hint(view, TRUE);
column = gtk_tree_view_column_new();
gtk_tree_view_append_column(view, column);
gtk_tree_view_column_set_title(column, _("Options"));
renderer = gtk_cell_renderer_toggle_new();
gtk_tree_view_column_pack_start(GTK_TREE_VIEW_COLUMN(column),
renderer, FALSE);
gtk_tree_view_column_set_attributes(GTK_TREE_VIEW_COLUMN(column),
renderer,
"active", COL_BTNACT,
"inconsistent", COL_BTNINC,
"visible", COL_BTNVIS,
"radio", COL_BTNRAD, NULL);
renderer = gtk_cell_renderer_text_new();
gtk_tree_view_column_pack_start(GTK_TREE_VIEW_COLUMN(column),
renderer, FALSE);
gtk_tree_view_column_set_attributes(GTK_TREE_VIEW_COLUMN(column),
renderer,
"text", COL_OPTION,
"foreground-gdk",
COL_COLOR, NULL);
sel = gtk_tree_view_get_selection(view);
gtk_tree_selection_set_mode(sel, GTK_SELECTION_SINGLE);
gtk_widget_realize(tree1_w);
}
static void renderer_edited(GtkCellRendererText * cell,
const gchar * path_string,
const gchar * new_text, gpointer user_data);
static void renderer_toggled(GtkCellRendererToggle * cellrenderertoggle,
gchar * arg1, gpointer user_data);
void init_right_tree(void)
{
GtkTreeView *view = GTK_TREE_VIEW(tree2_w);
GtkCellRenderer *renderer;
GtkTreeSelection *sel;
GtkTreeViewColumn *column;
gint i;
gtk_tree_view_set_model(view, model2);
gtk_tree_view_set_headers_visible(view, TRUE);
gtk_tree_view_set_rules_hint(view, TRUE);
column = gtk_tree_view_column_new();
gtk_tree_view_append_column(view, column);
gtk_tree_view_column_set_title(column, _("Options"));
renderer = gtk_cell_renderer_pixbuf_new();
gtk_tree_view_column_pack_start(GTK_TREE_VIEW_COLUMN(column),
renderer, FALSE);
gtk_tree_view_column_set_attributes(GTK_TREE_VIEW_COLUMN(column),
renderer,
"pixbuf", COL_PIXBUF,
"visible", COL_PIXVIS, NULL);
renderer = gtk_cell_renderer_toggle_new();
gtk_tree_view_column_pack_start(GTK_TREE_VIEW_COLUMN(column),
renderer, FALSE);
gtk_tree_view_column_set_attributes(GTK_TREE_VIEW_COLUMN(column),
renderer,
"active", COL_BTNACT,
"inconsistent", COL_BTNINC,
"visible", COL_BTNVIS,
"radio", COL_BTNRAD, NULL);
/*g_signal_connect(G_OBJECT(renderer), "toggled",
G_CALLBACK(renderer_toggled), NULL); */
renderer = gtk_cell_renderer_text_new();
gtk_tree_view_column_pack_start(GTK_TREE_VIEW_COLUMN(column),
renderer, FALSE);
gtk_tree_view_column_set_attributes(GTK_TREE_VIEW_COLUMN(column),
renderer,
"text", COL_OPTION,
"foreground-gdk",
COL_COLOR, NULL);
renderer = gtk_cell_renderer_text_new();
gtk_tree_view_insert_column_with_attributes(view, -1,
_("Name"), renderer,
"text", COL_NAME,
"foreground-gdk",
COL_COLOR, NULL);
renderer = gtk_cell_renderer_text_new();
gtk_tree_view_insert_column_with_attributes(view, -1,
"N", renderer,
"text", COL_NO,
"foreground-gdk",
COL_COLOR, NULL);
renderer = gtk_cell_renderer_text_new();
gtk_tree_view_insert_column_with_attributes(view, -1,
"M", renderer,
"text", COL_MOD,
"foreground-gdk",
COL_COLOR, NULL);
renderer = gtk_cell_renderer_text_new();
gtk_tree_view_insert_column_with_attributes(view, -1,
"Y", renderer,
"text", COL_YES,
"foreground-gdk",
COL_COLOR, NULL);
renderer = gtk_cell_renderer_text_new();
gtk_tree_view_insert_column_with_attributes(view, -1,
_("Value"), renderer,
"text", COL_VALUE,
"editable",
COL_EDIT,
"foreground-gdk",
COL_COLOR, NULL);
g_signal_connect(G_OBJECT(renderer), "edited",
G_CALLBACK(renderer_edited), NULL);
column = gtk_tree_view_get_column(view, COL_NAME);
gtk_tree_view_column_set_visible(column, show_name);
column = gtk_tree_view_get_column(view, COL_NO);
gtk_tree_view_column_set_visible(column, show_range);
column = gtk_tree_view_get_column(view, COL_MOD);
gtk_tree_view_column_set_visible(column, show_range);
column = gtk_tree_view_get_column(view, COL_YES);
gtk_tree_view_column_set_visible(column, show_range);
column = gtk_tree_view_get_column(view, COL_VALUE);
gtk_tree_view_column_set_visible(column, show_value);
if (resizeable) {
for (i = 0; i < COL_VALUE; i++) {
column = gtk_tree_view_get_column(view, i);
gtk_tree_view_column_set_resizable(column, TRUE);
}
}
sel = gtk_tree_view_get_selection(view);
gtk_tree_selection_set_mode(sel, GTK_SELECTION_SINGLE);
}
/* Utility Functions */
static void text_insert_help(struct menu *menu)
{
GtkTextBuffer *buffer;
GtkTextIter start, end;
const char *prompt = _(menu_get_prompt(menu));
struct gstr help = str_new();
menu_get_ext_help(menu, &help);
buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text_w));
gtk_text_buffer_get_bounds(buffer, &start, &end);
gtk_text_buffer_delete(buffer, &start, &end);
gtk_text_view_set_left_margin(GTK_TEXT_VIEW(text_w), 15);
gtk_text_buffer_get_end_iter(buffer, &end);
gtk_text_buffer_insert_with_tags(buffer, &end, prompt, -1, tag1,
NULL);
gtk_text_buffer_insert_at_cursor(buffer, "\n\n", 2);
gtk_text_buffer_get_end_iter(buffer, &end);
gtk_text_buffer_insert_with_tags(buffer, &end, str_get(&help), -1, tag2,
NULL);
str_free(&help);
}
static void text_insert_msg(const char *title, const char *message)
{
GtkTextBuffer *buffer;
GtkTextIter start, end;
const char *msg = message;
buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text_w));
gtk_text_buffer_get_bounds(buffer, &start, &end);
gtk_text_buffer_delete(buffer, &start, &end);
gtk_text_view_set_left_margin(GTK_TEXT_VIEW(text_w), 15);
gtk_text_buffer_get_end_iter(buffer, &end);
gtk_text_buffer_insert_with_tags(buffer, &end, title, -1, tag1,
NULL);
gtk_text_buffer_insert_at_cursor(buffer, "\n\n", 2);
gtk_text_buffer_get_end_iter(buffer, &end);
gtk_text_buffer_insert_with_tags(buffer, &end, msg, -1, tag2,
NULL);
}
/* Main Windows Callbacks */
void on_save_activate(GtkMenuItem * menuitem, gpointer user_data);
gboolean on_window1_delete_event(GtkWidget * widget, GdkEvent * event,
gpointer user_data)
{
GtkWidget *dialog, *label;
gint result;
if (!conf_get_changed())
return FALSE;
dialog = gtk_dialog_new_with_buttons(_("Warning !"),
GTK_WINDOW(main_wnd),
(GtkDialogFlags)
(GTK_DIALOG_MODAL |
GTK_DIALOG_DESTROY_WITH_PARENT),
GTK_STOCK_OK,
GTK_RESPONSE_YES,
GTK_STOCK_NO,
GTK_RESPONSE_NO,
GTK_STOCK_CANCEL,
GTK_RESPONSE_CANCEL, NULL);
gtk_dialog_set_default_response(GTK_DIALOG(dialog),
GTK_RESPONSE_CANCEL);
label = gtk_label_new(_("\nSave configuration ?\n"));
gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog)->vbox), label);
gtk_widget_show(label);
result = gtk_dialog_run(GTK_DIALOG(dialog));
switch (result) {
case GTK_RESPONSE_YES:
on_save_activate(NULL, NULL);
return FALSE;
case GTK_RESPONSE_NO:
return FALSE;
case GTK_RESPONSE_CANCEL:
case GTK_RESPONSE_DELETE_EVENT:
default:
gtk_widget_destroy(dialog);
return TRUE;
}
return FALSE;
}
void on_window1_destroy(GtkObject * object, gpointer user_data)
{
gtk_main_quit();
}
void
on_window1_size_request(GtkWidget * widget,
GtkRequisition * requisition, gpointer user_data)
{
static gint old_h;
gint w, h;
if (widget->window == NULL)
gtk_window_get_default_size(GTK_WINDOW(main_wnd), &w, &h);
else
gdk_window_get_size(widget->window, &w, &h);
if (h == old_h)
return;
old_h = h;
gtk_paned_set_position(GTK_PANED(vpaned), 2 * h / 3);
}
/* Menu & Toolbar Callbacks */
static void
load_filename(GtkFileSelection * file_selector, gpointer user_data)
{
const gchar *fn;
fn = gtk_file_selection_get_filename(GTK_FILE_SELECTION
(user_data));
if (conf_read(fn))
text_insert_msg(_("Error"), _("Unable to load configuration !"));
else
display_tree(&rootmenu);
}
void on_load1_activate(GtkMenuItem * menuitem, gpointer user_data)
{
GtkWidget *fs;
fs = gtk_file_selection_new(_("Load file..."));
g_signal_connect(GTK_OBJECT(GTK_FILE_SELECTION(fs)->ok_button),
"clicked",
G_CALLBACK(load_filename), (gpointer) fs);
g_signal_connect_swapped(GTK_OBJECT
(GTK_FILE_SELECTION(fs)->ok_button),
"clicked", G_CALLBACK(gtk_widget_destroy),
(gpointer) fs);
g_signal_connect_swapped(GTK_OBJECT
(GTK_FILE_SELECTION(fs)->cancel_button),
"clicked", G_CALLBACK(gtk_widget_destroy),
(gpointer) fs);
gtk_widget_show(fs);
}
void on_save_activate(GtkMenuItem * menuitem, gpointer user_data)
{
if (conf_write(NULL))
text_insert_msg(_("Error"), _("Unable to save configuration !"));
}
static void
store_filename(GtkFileSelection * file_selector, gpointer user_data)
{
const gchar *fn;
fn = gtk_file_selection_get_filename(GTK_FILE_SELECTION
(user_data));
if (conf_write(fn))
text_insert_msg(_("Error"), _("Unable to save configuration !"));
gtk_widget_destroy(GTK_WIDGET(user_data));
}
void on_save_as1_activate(GtkMenuItem * menuitem, gpointer user_data)
{
GtkWidget *fs;
fs = gtk_file_selection_new(_("Save file as..."));
g_signal_connect(GTK_OBJECT(GTK_FILE_SELECTION(fs)->ok_button),
"clicked",
G_CALLBACK(store_filename), (gpointer) fs);
g_signal_connect_swapped(GTK_OBJECT
(GTK_FILE_SELECTION(fs)->ok_button),
"clicked", G_CALLBACK(gtk_widget_destroy),
(gpointer) fs);
g_signal_connect_swapped(GTK_OBJECT
(GTK_FILE_SELECTION(fs)->cancel_button),
"clicked", G_CALLBACK(gtk_widget_destroy),
(gpointer) fs);
gtk_widget_show(fs);
}
void on_quit1_activate(GtkMenuItem * menuitem, gpointer user_data)
{
if (!on_window1_delete_event(NULL, NULL, NULL))
gtk_widget_destroy(GTK_WIDGET(main_wnd));
}
void on_show_name1_activate(GtkMenuItem * menuitem, gpointer user_data)
{
GtkTreeViewColumn *col;
show_name = GTK_CHECK_MENU_ITEM(menuitem)->active;
col = gtk_tree_view_get_column(GTK_TREE_VIEW(tree2_w), COL_NAME);
if (col)
gtk_tree_view_column_set_visible(col, show_name);
}
void on_show_range1_activate(GtkMenuItem * menuitem, gpointer user_data)
{
GtkTreeViewColumn *col;
show_range = GTK_CHECK_MENU_ITEM(menuitem)->active;
col = gtk_tree_view_get_column(GTK_TREE_VIEW(tree2_w), COL_NO);
if (col)
gtk_tree_view_column_set_visible(col, show_range);
col = gtk_tree_view_get_column(GTK_TREE_VIEW(tree2_w), COL_MOD);
if (col)
gtk_tree_view_column_set_visible(col, show_range);
col = gtk_tree_view_get_column(GTK_TREE_VIEW(tree2_w), COL_YES);
if (col)
gtk_tree_view_column_set_visible(col, show_range);
}
void on_show_data1_activate(GtkMenuItem * menuitem, gpointer user_data)
{
GtkTreeViewColumn *col;
show_value = GTK_CHECK_MENU_ITEM(menuitem)->active;
col = gtk_tree_view_get_column(GTK_TREE_VIEW(tree2_w), COL_VALUE);
if (col)
gtk_tree_view_column_set_visible(col, show_value);
}
void
on_set_option_mode1_activate(GtkMenuItem *menuitem, gpointer user_data)
{
opt_mode = OPT_NORMAL;
gtk_tree_store_clear(tree2);
display_tree(&rootmenu); /* instead of update_tree to speed-up */
}
void
on_set_option_mode2_activate(GtkMenuItem *menuitem, gpointer user_data)
{
opt_mode = OPT_ALL;
gtk_tree_store_clear(tree2);
display_tree(&rootmenu); /* instead of update_tree to speed-up */
}
void
on_set_option_mode3_activate(GtkMenuItem *menuitem, gpointer user_data)
{
opt_mode = OPT_PROMPT;
gtk_tree_store_clear(tree2);
display_tree(&rootmenu); /* instead of update_tree to speed-up */
}
void on_introduction1_activate(GtkMenuItem * menuitem, gpointer user_data)
{
GtkWidget *dialog;
const gchar *intro_text = _(
"Welcome to gkc, the GTK+ graphical configuration tool\n"
"For each option, a blank box indicates the feature is disabled, a\n"
"check indicates it is enabled, and a dot indicates that it is to\n"
"be compiled as a module. Clicking on the box will cycle through the three states.\n"
"\n"
"If you do not see an option (e.g., a device driver) that you\n"
"believe should be present, try turning on Show All Options\n"
"under the Options menu.\n"
"Although there is no cross reference yet to help you figure out\n"
"what other options must be enabled to support the option you\n"
"are interested in, you can still view the help of a grayed-out\n"
"option.\n"
"\n"
"Toggling Show Debug Info under the Options menu will show \n"
"the dependencies, which you can then match by examining other options.");
dialog = gtk_message_dialog_new(GTK_WINDOW(main_wnd),
GTK_DIALOG_DESTROY_WITH_PARENT,
GTK_MESSAGE_INFO,
GTK_BUTTONS_CLOSE, intro_text);
g_signal_connect_swapped(GTK_OBJECT(dialog), "response",
G_CALLBACK(gtk_widget_destroy),
GTK_OBJECT(dialog));
gtk_widget_show_all(dialog);
}
void on_about1_activate(GtkMenuItem * menuitem, gpointer user_data)
{
GtkWidget *dialog;
const gchar *about_text =
_("gkc is copyright (c) 2002 Romain Lievin <roms@lpg.ticalc.org>.\n"
"Based on the source code from Roman Zippel.\n");
dialog = gtk_message_dialog_new(GTK_WINDOW(main_wnd),
GTK_DIALOG_DESTROY_WITH_PARENT,
GTK_MESSAGE_INFO,
GTK_BUTTONS_CLOSE, about_text);
g_signal_connect_swapped(GTK_OBJECT(dialog), "response",
G_CALLBACK(gtk_widget_destroy),
GTK_OBJECT(dialog));
gtk_widget_show_all(dialog);
}
void on_license1_activate(GtkMenuItem * menuitem, gpointer user_data)
{
GtkWidget *dialog;
const gchar *license_text =
_("gkc is released under the terms of the GNU GPL v2.\n"
"For more information, please see the source code or\n"
"visit http://www.fsf.org/licenses/licenses.html\n");
dialog = gtk_message_dialog_new(GTK_WINDOW(main_wnd),
GTK_DIALOG_DESTROY_WITH_PARENT,
GTK_MESSAGE_INFO,
GTK_BUTTONS_CLOSE, license_text);
g_signal_connect_swapped(GTK_OBJECT(dialog), "response",
G_CALLBACK(gtk_widget_destroy),
GTK_OBJECT(dialog));
gtk_widget_show_all(dialog);
}
void on_back_clicked(GtkButton * button, gpointer user_data)
{
enum prop_type ptype;
current = current->parent;
ptype = current->prompt ? current->prompt->type : P_UNKNOWN;
if (ptype != P_MENU)
current = current->parent;
display_tree_part();
if (current == &rootmenu)
gtk_widget_set_sensitive(back_btn, FALSE);
}
void on_load_clicked(GtkButton * button, gpointer user_data)
{
on_load1_activate(NULL, user_data);
}
void on_single_clicked(GtkButton * button, gpointer user_data)
{
view_mode = SINGLE_VIEW;
gtk_widget_hide(tree1_w);
current = &rootmenu;
display_tree_part();
}
void on_split_clicked(GtkButton * button, gpointer user_data)
{
gint w, h;
view_mode = SPLIT_VIEW;
gtk_widget_show(tree1_w);
gtk_window_get_default_size(GTK_WINDOW(main_wnd), &w, &h);
gtk_paned_set_position(GTK_PANED(hpaned), w / 2);
if (tree2)
gtk_tree_store_clear(tree2);
display_list();
/* Disable back btn, like in full mode. */
gtk_widget_set_sensitive(back_btn, FALSE);
}
void on_full_clicked(GtkButton * button, gpointer user_data)
{
view_mode = FULL_VIEW;
gtk_widget_hide(tree1_w);
if (tree2)
gtk_tree_store_clear(tree2);
display_tree(&rootmenu);
gtk_widget_set_sensitive(back_btn, FALSE);
}
void on_collapse_clicked(GtkButton * button, gpointer user_data)
{
gtk_tree_view_collapse_all(GTK_TREE_VIEW(tree2_w));
}
void on_expand_clicked(GtkButton * button, gpointer user_data)
{
gtk_tree_view_expand_all(GTK_TREE_VIEW(tree2_w));
}
/* CTree Callbacks */
/* Change hex/int/string value in the cell */
static void renderer_edited(GtkCellRendererText * cell,
const gchar * path_string,
const gchar * new_text, gpointer user_data)
{
GtkTreePath *path = gtk_tree_path_new_from_string(path_string);
GtkTreeIter iter;
const char *old_def, *new_def;
struct menu *menu;
struct symbol *sym;
if (!gtk_tree_model_get_iter(model2, &iter, path))
return;
gtk_tree_model_get(model2, &iter, COL_MENU, &menu, -1);
sym = menu->sym;
gtk_tree_model_get(model2, &iter, COL_VALUE, &old_def, -1);
new_def = new_text;
sym_set_string_value(sym, new_def);
update_tree(&rootmenu, NULL);
gtk_tree_path_free(path);
}
/* Change the value of a symbol and update the tree */
static void change_sym_value(struct menu *menu, gint col)
{
struct symbol *sym = menu->sym;
tristate oldval, newval;
if (!sym)
return;
if (col == COL_NO)
newval = no;
else if (col == COL_MOD)
newval = mod;
else if (col == COL_YES)
newval = yes;
else
return;
switch (sym_get_type(sym)) {
case S_BOOLEAN:
case S_TRISTATE:
oldval = sym_get_tristate_value(sym);
if (!sym_tristate_within_range(sym, newval))
newval = yes;
sym_set_tristate_value(sym, newval);
if (view_mode == FULL_VIEW)
update_tree(&rootmenu, NULL);
else if (view_mode == SPLIT_VIEW) {
update_tree(browsed, NULL);
display_list();
}
else if (view_mode == SINGLE_VIEW)
display_tree_part(); //fixme: keep exp/coll
break;
case S_INT:
case S_HEX:
case S_STRING:
default:
break;
}
}
static void toggle_sym_value(struct menu *menu)
{
if (!menu->sym)
return;
sym_toggle_tristate_value(menu->sym);
if (view_mode == FULL_VIEW)
update_tree(&rootmenu, NULL);
else if (view_mode == SPLIT_VIEW) {
update_tree(browsed, NULL);
display_list();
}
else if (view_mode == SINGLE_VIEW)
display_tree_part(); //fixme: keep exp/coll
}
static void renderer_toggled(GtkCellRendererToggle * cell,
gchar * path_string, gpointer user_data)
{
GtkTreePath *path, *sel_path = NULL;
GtkTreeIter iter, sel_iter;
GtkTreeSelection *sel;
struct menu *menu;
path = gtk_tree_path_new_from_string(path_string);
if (!gtk_tree_model_get_iter(model2, &iter, path))
return;
sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(tree2_w));
if (gtk_tree_selection_get_selected(sel, NULL, &sel_iter))
sel_path = gtk_tree_model_get_path(model2, &sel_iter);
if (!sel_path)
goto out1;
if (gtk_tree_path_compare(path, sel_path))
goto out2;
gtk_tree_model_get(model2, &iter, COL_MENU, &menu, -1);
toggle_sym_value(menu);
out2:
gtk_tree_path_free(sel_path);
out1:
gtk_tree_path_free(path);
}
static gint column2index(GtkTreeViewColumn * column)
{
gint i;
for (i = 0; i < COL_NUMBER; i++) {
GtkTreeViewColumn *col;
col = gtk_tree_view_get_column(GTK_TREE_VIEW(tree2_w), i);
if (col == column)
return i;
}
return -1;
}
/* User click: update choice (full) or goes down (single) */
gboolean
on_treeview2_button_press_event(GtkWidget * widget,
GdkEventButton * event, gpointer user_data)
{
GtkTreeView *view = GTK_TREE_VIEW(widget);
GtkTreePath *path;
GtkTreeViewColumn *column;
GtkTreeIter iter;
struct menu *menu;
gint col;
#if GTK_CHECK_VERSION(2,1,4) // bug in ctree with earlier version of GTK
gint tx = (gint) event->x;
gint ty = (gint) event->y;
gint cx, cy;
gtk_tree_view_get_path_at_pos(view, tx, ty, &path, &column, &cx,
&cy);
#else
gtk_tree_view_get_cursor(view, &path, &column);
#endif
if (path == NULL)
return FALSE;
if (!gtk_tree_model_get_iter(model2, &iter, path))
return FALSE;
gtk_tree_model_get(model2, &iter, COL_MENU, &menu, -1);
col = column2index(column);
if (event->type == GDK_2BUTTON_PRESS) {
enum prop_type ptype;
ptype = menu->prompt ? menu->prompt->type : P_UNKNOWN;
if (ptype == P_MENU && view_mode != FULL_VIEW && col == COL_OPTION) {
// goes down into menu
current = menu;
display_tree_part();
gtk_widget_set_sensitive(back_btn, TRUE);
} else if ((col == COL_OPTION)) {
toggle_sym_value(menu);
gtk_tree_view_expand_row(view, path, TRUE);
}
} else {
if (col == COL_VALUE) {
toggle_sym_value(menu);
gtk_tree_view_expand_row(view, path, TRUE);
} else if (col == COL_NO || col == COL_MOD
|| col == COL_YES) {
change_sym_value(menu, col);
gtk_tree_view_expand_row(view, path, TRUE);
}
}
return FALSE;
}
/* Key pressed: update choice */
gboolean
on_treeview2_key_press_event(GtkWidget * widget,
GdkEventKey * event, gpointer user_data)
{
GtkTreeView *view = GTK_TREE_VIEW(widget);
GtkTreePath *path;
GtkTreeViewColumn *column;
GtkTreeIter iter;
struct menu *menu;
gint col;
gtk_tree_view_get_cursor(view, &path, &column);
if (path == NULL)
return FALSE;
if (event->keyval == GDK_space) {
if (gtk_tree_view_row_expanded(view, path))
gtk_tree_view_collapse_row(view, path);
else
gtk_tree_view_expand_row(view, path, FALSE);
return TRUE;
}
if (event->keyval == GDK_KP_Enter) {
}
if (widget == tree1_w)
return FALSE;
gtk_tree_model_get_iter(model2, &iter, path);
gtk_tree_model_get(model2, &iter, COL_MENU, &menu, -1);
if (!strcasecmp(event->string, "n"))
col = COL_NO;
else if (!strcasecmp(event->string, "m"))
col = COL_MOD;
else if (!strcasecmp(event->string, "y"))
col = COL_YES;
else
col = -1;
change_sym_value(menu, col);
return FALSE;
}
/* Row selection changed: update help */
void
on_treeview2_cursor_changed(GtkTreeView * treeview, gpointer user_data)
{
GtkTreeSelection *selection;
GtkTreeIter iter;
struct menu *menu;
selection = gtk_tree_view_get_selection(treeview);
if (gtk_tree_selection_get_selected(selection, &model2, &iter)) {
gtk_tree_model_get(model2, &iter, COL_MENU, &menu, -1);
text_insert_help(menu);
}
}
/* User click: display sub-tree in the right frame. */
gboolean
on_treeview1_button_press_event(GtkWidget * widget,
GdkEventButton * event, gpointer user_data)
{
GtkTreeView *view = GTK_TREE_VIEW(widget);
GtkTreePath *path;
GtkTreeViewColumn *column;
GtkTreeIter iter;
struct menu *menu;
gint tx = (gint) event->x;
gint ty = (gint) event->y;
gint cx, cy;
gtk_tree_view_get_path_at_pos(view, tx, ty, &path, &column, &cx,
&cy);
if (path == NULL)
return FALSE;
gtk_tree_model_get_iter(model1, &iter, path);
gtk_tree_model_get(model1, &iter, COL_MENU, &menu, -1);
if (event->type == GDK_2BUTTON_PRESS) {
toggle_sym_value(menu);
current = menu;
display_tree_part();
} else {
browsed = menu;
display_tree_part();
}
gtk_widget_realize(tree2_w);
gtk_tree_view_set_cursor(view, path, NULL, FALSE);
gtk_widget_grab_focus(tree2_w);
return FALSE;
}
/* Fill a row of strings */
static gchar **fill_row(struct menu *menu)
{
static gchar *row[COL_NUMBER];
struct symbol *sym = menu->sym;
const char *def;
int stype;
tristate val;
enum prop_type ptype;
int i;
for (i = COL_OPTION; i <= COL_COLOR; i++)
g_free(row[i]);
bzero(row, sizeof(row));
row[COL_OPTION] =
g_strdup_printf("%s %s", _(menu_get_prompt(menu)),
sym && !sym_has_value(sym) ? "(NEW)" : "");
if (opt_mode == OPT_ALL && !menu_is_visible(menu))
row[COL_COLOR] = g_strdup("DarkGray");
else if (opt_mode == OPT_PROMPT &&
menu_has_prompt(menu) && !menu_is_visible(menu))
row[COL_COLOR] = g_strdup("DarkGray");
else
row[COL_COLOR] = g_strdup("Black");
ptype = menu->prompt ? menu->prompt->type : P_UNKNOWN;
switch (ptype) {
case P_MENU:
row[COL_PIXBUF] = (gchar *) xpm_menu;
if (view_mode == SINGLE_VIEW)
row[COL_PIXVIS] = GINT_TO_POINTER(TRUE);
row[COL_BTNVIS] = GINT_TO_POINTER(FALSE);
break;
case P_COMMENT:
row[COL_PIXBUF] = (gchar *) xpm_void;
row[COL_PIXVIS] = GINT_TO_POINTER(FALSE);
row[COL_BTNVIS] = GINT_TO_POINTER(FALSE);
break;
default:
row[COL_PIXBUF] = (gchar *) xpm_void;
row[COL_PIXVIS] = GINT_TO_POINTER(FALSE);
row[COL_BTNVIS] = GINT_TO_POINTER(TRUE);
break;
}
if (!sym)
return row;
row[COL_NAME] = g_strdup(sym->name);
sym_calc_value(sym);
sym->flags &= ~SYMBOL_CHANGED;
if (sym_is_choice(sym)) { // parse childs for getting final value
struct menu *child;
struct symbol *def_sym = sym_get_choice_value(sym);
struct menu *def_menu = NULL;
row[COL_BTNVIS] = GINT_TO_POINTER(FALSE);
for (child = menu->list; child; child = child->next) {
if (menu_is_visible(child)
&& child->sym == def_sym)
def_menu = child;
}
if (def_menu)
row[COL_VALUE] =
g_strdup(_(menu_get_prompt(def_menu)));
}
if (sym->flags & SYMBOL_CHOICEVAL)
row[COL_BTNRAD] = GINT_TO_POINTER(TRUE);
stype = sym_get_type(sym);
switch (stype) {
case S_BOOLEAN:
if (GPOINTER_TO_INT(row[COL_PIXVIS]) == FALSE)
row[COL_BTNVIS] = GINT_TO_POINTER(TRUE);
if (sym_is_choice(sym))
break;
case S_TRISTATE:
val = sym_get_tristate_value(sym);
switch (val) {
case no:
row[COL_NO] = g_strdup("N");
row[COL_VALUE] = g_strdup("N");
row[COL_BTNACT] = GINT_TO_POINTER(FALSE);
row[COL_BTNINC] = GINT_TO_POINTER(FALSE);
break;
case mod:
row[COL_MOD] = g_strdup("M");
row[COL_VALUE] = g_strdup("M");
row[COL_BTNINC] = GINT_TO_POINTER(TRUE);
break;
case yes:
row[COL_YES] = g_strdup("Y");
row[COL_VALUE] = g_strdup("Y");
row[COL_BTNACT] = GINT_TO_POINTER(TRUE);
row[COL_BTNINC] = GINT_TO_POINTER(FALSE);
break;
}
if (val != no && sym_tristate_within_range(sym, no))
row[COL_NO] = g_strdup("_");
if (val != mod && sym_tristate_within_range(sym, mod))
row[COL_MOD] = g_strdup("_");
if (val != yes && sym_tristate_within_range(sym, yes))
row[COL_YES] = g_strdup("_");
break;
case S_INT:
case S_HEX:
case S_STRING:
def = sym_get_string_value(sym);
row[COL_VALUE] = g_strdup(def);
row[COL_EDIT] = GINT_TO_POINTER(TRUE);
row[COL_BTNVIS] = GINT_TO_POINTER(FALSE);
break;
}
return row;
}
/* Set the node content with a row of strings */
static void set_node(GtkTreeIter * node, struct menu *menu, gchar ** row)
{
GdkColor color;
gboolean success;
GdkPixbuf *pix;
pix = gdk_pixbuf_new_from_xpm_data((const char **)
row[COL_PIXBUF]);
gdk_color_parse(row[COL_COLOR], &color);
gdk_colormap_alloc_colors(gdk_colormap_get_system(), &color, 1,
FALSE, FALSE, &success);
gtk_tree_store_set(tree, node,
COL_OPTION, row[COL_OPTION],
COL_NAME, row[COL_NAME],
COL_NO, row[COL_NO],
COL_MOD, row[COL_MOD],
COL_YES, row[COL_YES],
COL_VALUE, row[COL_VALUE],
COL_MENU, (gpointer) menu,
COL_COLOR, &color,
COL_EDIT, GPOINTER_TO_INT(row[COL_EDIT]),
COL_PIXBUF, pix,
COL_PIXVIS, GPOINTER_TO_INT(row[COL_PIXVIS]),
COL_BTNVIS, GPOINTER_TO_INT(row[COL_BTNVIS]),
COL_BTNACT, GPOINTER_TO_INT(row[COL_BTNACT]),
COL_BTNINC, GPOINTER_TO_INT(row[COL_BTNINC]),
COL_BTNRAD, GPOINTER_TO_INT(row[COL_BTNRAD]),
-1);
g_object_unref(pix);
}
/* Add a node to the tree */
static void place_node(struct menu *menu, char **row)
{
GtkTreeIter *parent = parents[indent - 1];
GtkTreeIter *node = parents[indent];
gtk_tree_store_append(tree, node, parent);
set_node(node, menu, row);
}
/* Find a node in the GTK+ tree */
static GtkTreeIter found;
/*
* Find a menu in the GtkTree starting at parent.
*/
GtkTreeIter *gtktree_iter_find_node(GtkTreeIter * parent,
struct menu *tofind)
{
GtkTreeIter iter;
GtkTreeIter *child = &iter;
gboolean valid;
GtkTreeIter *ret;
valid = gtk_tree_model_iter_children(model2, child, parent);
while (valid) {
struct menu *menu;
gtk_tree_model_get(model2, child, 6, &menu, -1);
if (menu == tofind) {
memcpy(&found, child, sizeof(GtkTreeIter));
return &found;
}
ret = gtktree_iter_find_node(child, tofind);
if (ret)
return ret;
valid = gtk_tree_model_iter_next(model2, child);
}
return NULL;
}
/*
* Update the tree by adding/removing entries
* Does not change other nodes
*/
static void update_tree(struct menu *src, GtkTreeIter * dst)
{
struct menu *child1;
GtkTreeIter iter, tmp;
GtkTreeIter *child2 = &iter;
gboolean valid;
GtkTreeIter *sibling;
struct symbol *sym;
struct property *prop;
struct menu *menu1, *menu2;
if (src == &rootmenu)
indent = 1;
valid = gtk_tree_model_iter_children(model2, child2, dst);
for (child1 = src->list; child1; child1 = child1->next) {
prop = child1->prompt;
sym = child1->sym;
reparse:
menu1 = child1;
if (valid)
gtk_tree_model_get(model2, child2, COL_MENU,
&menu2, -1);
else
menu2 = NULL; // force adding of a first child
#ifdef DEBUG
printf("%*c%s | %s\n", indent, ' ',
menu1 ? menu_get_prompt(menu1) : "nil",
menu2 ? menu_get_prompt(menu2) : "nil");
#endif
if ((opt_mode == OPT_NORMAL && !menu_is_visible(child1)) ||
(opt_mode == OPT_PROMPT && !menu_has_prompt(child1)) ||
(opt_mode == OPT_ALL && !menu_get_prompt(child1))) {
/* remove node */
if (gtktree_iter_find_node(dst, menu1) != NULL) {
memcpy(&tmp, child2, sizeof(GtkTreeIter));
valid = gtk_tree_model_iter_next(model2,
child2);
gtk_tree_store_remove(tree2, &tmp);
if (!valid)
return; /* next parent */
else
goto reparse; /* next child */
} else
continue;
}
if (menu1 != menu2) {
if (gtktree_iter_find_node(dst, menu1) == NULL) { // add node
if (!valid && !menu2)
sibling = NULL;
else
sibling = child2;
gtk_tree_store_insert_before(tree2,
child2,
dst, sibling);
set_node(child2, menu1, fill_row(menu1));
if (menu2 == NULL)
valid = TRUE;
} else { // remove node
memcpy(&tmp, child2, sizeof(GtkTreeIter));
valid = gtk_tree_model_iter_next(model2,
child2);
gtk_tree_store_remove(tree2, &tmp);
if (!valid)
return; // next parent
else
goto reparse; // next child
}
} else if (sym && (sym->flags & SYMBOL_CHANGED)) {
set_node(child2, menu1, fill_row(menu1));
}
indent++;
update_tree(child1, child2);
indent--;
valid = gtk_tree_model_iter_next(model2, child2);
}
}
/* Display the whole tree (single/split/full view) */
static void display_tree(struct menu *menu)
{
struct symbol *sym;
struct property *prop;
struct menu *child;
enum prop_type ptype;
if (menu == &rootmenu) {
indent = 1;
current = &rootmenu;
}
for (child = menu->list; child; child = child->next) {
prop = child->prompt;
sym = child->sym;
ptype = prop ? prop->type : P_UNKNOWN;
if (sym)
sym->flags &= ~SYMBOL_CHANGED;
if ((view_mode == SPLIT_VIEW)
&& !(child->flags & MENU_ROOT) && (tree == tree1))
continue;
if ((view_mode == SPLIT_VIEW) && (child->flags & MENU_ROOT)
&& (tree == tree2))
continue;
if ((opt_mode == OPT_NORMAL && menu_is_visible(child)) ||
(opt_mode == OPT_PROMPT && menu_has_prompt(child)) ||
(opt_mode == OPT_ALL && menu_get_prompt(child)))
place_node(child, fill_row(child));
#ifdef DEBUG
printf("%*c%s: ", indent, ' ', menu_get_prompt(child));
printf("%s", child->flags & MENU_ROOT ? "rootmenu | " : "");
printf("%s", prop_get_type_name(ptype));
printf(" | ");
if (sym) {
printf("%s", sym_type_name(sym->type));
printf(" | ");
printf("%s", dbg_sym_flags(sym->flags));
printf("\n");
} else
printf("\n");
#endif
if ((view_mode != FULL_VIEW) && (ptype == P_MENU)
&& (tree == tree2))
continue;
/*
if (((menu != &rootmenu) && !(menu->flags & MENU_ROOT))
|| (view_mode == FULL_VIEW)
|| (view_mode == SPLIT_VIEW))*/
/* Change paned position if the view is not in 'split mode' */
if (view_mode == SINGLE_VIEW || view_mode == FULL_VIEW) {
gtk_paned_set_position(GTK_PANED(hpaned), 0);
}
if (((view_mode == SINGLE_VIEW) && (menu->flags & MENU_ROOT))
|| (view_mode == FULL_VIEW)
|| (view_mode == SPLIT_VIEW)) {
indent++;
display_tree(child);
indent--;
}
}
}
/* Display a part of the tree starting at current node (single/split view) */
static void display_tree_part(void)
{
if (tree2)
gtk_tree_store_clear(tree2);
if (view_mode == SINGLE_VIEW)
display_tree(current);
else if (view_mode == SPLIT_VIEW)
display_tree(browsed);
gtk_tree_view_expand_all(GTK_TREE_VIEW(tree2_w));
}
/* Display the list in the left frame (split view) */
static void display_list(void)
{
if (tree1)
gtk_tree_store_clear(tree1);
tree = tree1;
display_tree(&rootmenu);
gtk_tree_view_expand_all(GTK_TREE_VIEW(tree1_w));
tree = tree2;
}
void fixup_rootmenu(struct menu *menu)
{
struct menu *child;
static int menu_cnt = 0;
menu->flags |= MENU_ROOT;
for (child = menu->list; child; child = child->next) {
if (child->prompt && child->prompt->type == P_MENU) {
menu_cnt++;
fixup_rootmenu(child);
menu_cnt--;
} else if (!menu_cnt)
fixup_rootmenu(child);
}
}
/* Main */
int main(int ac, char *av[])
{
const char *name;
char *env;
gchar *glade_file;
#ifndef LKC_DIRECT_LINK
kconfig_load();
#endif
bindtextdomain(PACKAGE, LOCALEDIR);
bind_textdomain_codeset(PACKAGE, "UTF-8");
textdomain(PACKAGE);
/* GTK stuffs */
gtk_set_locale();
gtk_init(&ac, &av);
glade_init();
//add_pixmap_directory (PACKAGE_DATA_DIR "/" PACKAGE "/pixmaps");
//add_pixmap_directory (PACKAGE_SOURCE_DIR "/pixmaps");
/* Determine GUI path */
env = getenv(SRCTREE);
if (env)
glade_file = g_strconcat(env, "/scripts/kconfig/gconf.glade", NULL);
else if (av[0][0] == '/')
glade_file = g_strconcat(av[0], ".glade", NULL);
else
glade_file = g_strconcat(g_get_current_dir(), "/", av[0], ".glade", NULL);
/* Conf stuffs */
if (ac > 1 && av[1][0] == '-') {
switch (av[1][1]) {
case 'a':
//showAll = 1;
break;
case 'h':
case '?':
printf("%s <config>\n", av[0]);
exit(0);
}
name = av[2];
} else
name = av[1];
conf_parse(name);
fixup_rootmenu(&rootmenu);
conf_read(NULL);
/* Load the interface and connect signals */
init_main_window(glade_file);
init_tree_model();
init_left_tree();
init_right_tree();
switch (view_mode) {
case SINGLE_VIEW:
display_tree_part();
break;
case SPLIT_VIEW:
display_list();
break;
case FULL_VIEW:
display_tree(&rootmenu);
break;
}
gtk_main();
return 0;
}
static void conf_changed(void)
{
bool changed = conf_get_changed();
gtk_widget_set_sensitive(save_btn, changed);
gtk_widget_set_sensitive(save_menu_item, changed);
}
| gpl-2.0 |
halaszk/halaszk-universal5430 | drivers/video/aty/radeon_base.c | 2398 | 76767 | /*
* drivers/video/aty/radeon_base.c
*
* framebuffer driver for ATI Radeon chipset video boards
*
* Copyright 2003 Ben. Herrenschmidt <benh@kernel.crashing.org>
* Copyright 2000 Ani Joshi <ajoshi@kernel.crashing.org>
*
* i2c bits from Luca Tettamanti <kronos@kronoz.cjb.net>
*
* Special thanks to ATI DevRel team for their hardware donations.
*
* ...Insert GPL boilerplate here...
*
* Significant portions of this driver apdated from XFree86 Radeon
* driver which has the following copyright notice:
*
* Copyright 2000 ATI Technologies Inc., Markham, Ontario, and
* VA Linux Systems Inc., Fremont, California.
*
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation on the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NON-INFRINGEMENT. IN NO EVENT SHALL ATI, VA LINUX SYSTEMS AND/OR
* THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* XFree86 driver authors:
*
* Kevin E. Martin <martin@xfree86.org>
* Rickard E. Faith <faith@valinux.com>
* Alan Hourihane <alanh@fairlite.demon.co.uk>
*
*/
#define RADEON_VERSION "0.2.0"
#include "radeonfb.h"
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/ctype.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/time.h>
#include <linux/fb.h>
#include <linux/ioport.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/vmalloc.h>
#include <linux/device.h>
#include <asm/io.h>
#include <linux/uaccess.h>
#ifdef CONFIG_PPC_OF
#include <asm/pci-bridge.h>
#include "../macmodes.h"
#ifdef CONFIG_BOOTX_TEXT
#include <asm/btext.h>
#endif
#endif /* CONFIG_PPC_OF */
#ifdef CONFIG_MTRR
#include <asm/mtrr.h>
#endif
#include <video/radeon.h>
#include <linux/radeonfb.h>
#include "../edid.h" // MOVE THAT TO include/video
#include "ati_ids.h"
#define MAX_MAPPED_VRAM (2048*2048*4)
#define MIN_MAPPED_VRAM (1024*768*1)
#define CHIP_DEF(id, family, flags) \
{ PCI_VENDOR_ID_ATI, id, PCI_ANY_ID, PCI_ANY_ID, 0, 0, (flags) | (CHIP_FAMILY_##family) }
static struct pci_device_id radeonfb_pci_table[] = {
/* Radeon Xpress 200m */
CHIP_DEF(PCI_CHIP_RS480_5955, RS480, CHIP_HAS_CRTC2 | CHIP_IS_IGP | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RS482_5975, RS480, CHIP_HAS_CRTC2 | CHIP_IS_IGP | CHIP_IS_MOBILITY),
/* Mobility M6 */
CHIP_DEF(PCI_CHIP_RADEON_LY, RV100, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RADEON_LZ, RV100, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
/* Radeon VE/7000 */
CHIP_DEF(PCI_CHIP_RV100_QY, RV100, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV100_QZ, RV100, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RN50, RV100, CHIP_HAS_CRTC2),
/* Radeon IGP320M (U1) */
CHIP_DEF(PCI_CHIP_RS100_4336, RS100, CHIP_HAS_CRTC2 | CHIP_IS_IGP | CHIP_IS_MOBILITY),
/* Radeon IGP320 (A3) */
CHIP_DEF(PCI_CHIP_RS100_4136, RS100, CHIP_HAS_CRTC2 | CHIP_IS_IGP),
/* IGP330M/340M/350M (U2) */
CHIP_DEF(PCI_CHIP_RS200_4337, RS200, CHIP_HAS_CRTC2 | CHIP_IS_IGP | CHIP_IS_MOBILITY),
/* IGP330/340/350 (A4) */
CHIP_DEF(PCI_CHIP_RS200_4137, RS200, CHIP_HAS_CRTC2 | CHIP_IS_IGP),
/* Mobility 7000 IGP */
CHIP_DEF(PCI_CHIP_RS250_4437, RS200, CHIP_HAS_CRTC2 | CHIP_IS_IGP | CHIP_IS_MOBILITY),
/* 7000 IGP (A4+) */
CHIP_DEF(PCI_CHIP_RS250_4237, RS200, CHIP_HAS_CRTC2 | CHIP_IS_IGP),
/* 8500 AIW */
CHIP_DEF(PCI_CHIP_R200_BB, R200, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R200_BC, R200, CHIP_HAS_CRTC2),
/* 8700/8800 */
CHIP_DEF(PCI_CHIP_R200_QH, R200, CHIP_HAS_CRTC2),
/* 8500 */
CHIP_DEF(PCI_CHIP_R200_QL, R200, CHIP_HAS_CRTC2),
/* 9100 */
CHIP_DEF(PCI_CHIP_R200_QM, R200, CHIP_HAS_CRTC2),
/* Mobility M7 */
CHIP_DEF(PCI_CHIP_RADEON_LW, RV200, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RADEON_LX, RV200, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
/* 7500 */
CHIP_DEF(PCI_CHIP_RV200_QW, RV200, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV200_QX, RV200, CHIP_HAS_CRTC2),
/* Mobility M9 */
CHIP_DEF(PCI_CHIP_RV250_Ld, RV250, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV250_Le, RV250, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV250_Lf, RV250, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV250_Lg, RV250, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
/* 9000/Pro */
CHIP_DEF(PCI_CHIP_RV250_If, RV250, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV250_Ig, RV250, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RC410_5A62, RC410, CHIP_HAS_CRTC2 | CHIP_IS_IGP | CHIP_IS_MOBILITY),
/* Mobility 9100 IGP (U3) */
CHIP_DEF(PCI_CHIP_RS300_5835, RS300, CHIP_HAS_CRTC2 | CHIP_IS_IGP | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RS350_7835, RS300, CHIP_HAS_CRTC2 | CHIP_IS_IGP | CHIP_IS_MOBILITY),
/* 9100 IGP (A5) */
CHIP_DEF(PCI_CHIP_RS300_5834, RS300, CHIP_HAS_CRTC2 | CHIP_IS_IGP),
CHIP_DEF(PCI_CHIP_RS350_7834, RS300, CHIP_HAS_CRTC2 | CHIP_IS_IGP),
/* Mobility 9200 (M9+) */
CHIP_DEF(PCI_CHIP_RV280_5C61, RV280, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV280_5C63, RV280, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
/* 9200 */
CHIP_DEF(PCI_CHIP_RV280_5960, RV280, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV280_5961, RV280, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV280_5962, RV280, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV280_5964, RV280, CHIP_HAS_CRTC2),
/* 9500 */
CHIP_DEF(PCI_CHIP_R300_AD, R300, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R300_AE, R300, CHIP_HAS_CRTC2),
/* 9600TX / FireGL Z1 */
CHIP_DEF(PCI_CHIP_R300_AF, R300, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R300_AG, R300, CHIP_HAS_CRTC2),
/* 9700/9500/Pro/FireGL X1 */
CHIP_DEF(PCI_CHIP_R300_ND, R300, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R300_NE, R300, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R300_NF, R300, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R300_NG, R300, CHIP_HAS_CRTC2),
/* Mobility M10/M11 */
CHIP_DEF(PCI_CHIP_RV350_NP, RV350, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV350_NQ, RV350, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV350_NR, RV350, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV350_NS, RV350, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV350_NT, RV350, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV350_NV, RV350, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
/* 9600/FireGL T2 */
CHIP_DEF(PCI_CHIP_RV350_AP, RV350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV350_AQ, RV350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV360_AR, RV350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV350_AS, RV350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV350_AT, RV350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV350_AV, RV350, CHIP_HAS_CRTC2),
/* 9800/Pro/FileGL X2 */
CHIP_DEF(PCI_CHIP_R350_AH, R350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R350_AI, R350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R350_AJ, R350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R350_AK, R350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R350_NH, R350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R350_NI, R350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R360_NJ, R350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R350_NK, R350, CHIP_HAS_CRTC2),
/* Newer stuff */
CHIP_DEF(PCI_CHIP_RV380_3E50, RV380, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV380_3E54, RV380, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV380_3150, RV380, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV380_3154, RV380, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV370_5B60, RV380, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV370_5B62, RV380, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV370_5B63, RV380, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV370_5B64, RV380, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV370_5B65, RV380, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV370_5460, RV380, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV370_5464, RV380, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_R420_JH, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R420_JI, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R420_JJ, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R420_JK, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R420_JL, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R420_JM, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R420_JN, R420, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_R420_JP, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R423_UH, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R423_UI, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R423_UJ, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R423_UK, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R423_UQ, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R423_UR, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R423_UT, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R423_5D57, R420, CHIP_HAS_CRTC2),
/* Original Radeon/7200 */
CHIP_DEF(PCI_CHIP_RADEON_QD, RADEON, 0),
CHIP_DEF(PCI_CHIP_RADEON_QE, RADEON, 0),
CHIP_DEF(PCI_CHIP_RADEON_QF, RADEON, 0),
CHIP_DEF(PCI_CHIP_RADEON_QG, RADEON, 0),
{ 0, }
};
MODULE_DEVICE_TABLE(pci, radeonfb_pci_table);
typedef struct {
u16 reg;
u32 val;
} reg_val;
/* these common regs are cleared before mode setting so they do not
* interfere with anything
*/
static reg_val common_regs[] = {
{ OVR_CLR, 0 },
{ OVR_WID_LEFT_RIGHT, 0 },
{ OVR_WID_TOP_BOTTOM, 0 },
{ OV0_SCALE_CNTL, 0 },
{ SUBPIC_CNTL, 0 },
{ VIPH_CONTROL, 0 },
{ I2C_CNTL_1, 0 },
{ GEN_INT_CNTL, 0 },
{ CAP0_TRIG_CNTL, 0 },
{ CAP1_TRIG_CNTL, 0 },
};
/*
* globals
*/
static char *mode_option;
static char *monitor_layout;
static bool noaccel = 0;
static int default_dynclk = -2;
static bool nomodeset = 0;
static bool ignore_edid = 0;
static bool mirror = 0;
static int panel_yres = 0;
static bool force_dfp = 0;
static bool force_measure_pll = 0;
#ifdef CONFIG_MTRR
static bool nomtrr = 0;
#endif
static bool force_sleep;
static bool ignore_devlist;
#ifdef CONFIG_PMAC_BACKLIGHT
static int backlight = 1;
#else
static int backlight = 0;
#endif
/*
* prototypes
*/
static void radeon_unmap_ROM(struct radeonfb_info *rinfo, struct pci_dev *dev)
{
if (!rinfo->bios_seg)
return;
pci_unmap_rom(dev, rinfo->bios_seg);
}
static int radeon_map_ROM(struct radeonfb_info *rinfo, struct pci_dev *dev)
{
void __iomem *rom;
u16 dptr;
u8 rom_type;
size_t rom_size;
/* If this is a primary card, there is a shadow copy of the
* ROM somewhere in the first meg. We will just ignore the copy
* and use the ROM directly.
*/
/* Fix from ATI for problem with Radeon hardware not leaving ROM enabled */
unsigned int temp;
temp = INREG(MPP_TB_CONFIG);
temp &= 0x00ffffffu;
temp |= 0x04 << 24;
OUTREG(MPP_TB_CONFIG, temp);
temp = INREG(MPP_TB_CONFIG);
rom = pci_map_rom(dev, &rom_size);
if (!rom) {
printk(KERN_ERR "radeonfb (%s): ROM failed to map\n",
pci_name(rinfo->pdev));
return -ENOMEM;
}
rinfo->bios_seg = rom;
/* Very simple test to make sure it appeared */
if (BIOS_IN16(0) != 0xaa55) {
printk(KERN_DEBUG "radeonfb (%s): Invalid ROM signature %x "
"should be 0xaa55\n",
pci_name(rinfo->pdev), BIOS_IN16(0));
goto failed;
}
/* Look for the PCI data to check the ROM type */
dptr = BIOS_IN16(0x18);
/* Check the PCI data signature. If it's wrong, we still assume a normal x86 ROM
* for now, until I've verified this works everywhere. The goal here is more
* to phase out Open Firmware images.
*
* Currently, we only look at the first PCI data, we could iteratre and deal with
* them all, and we should use fb_bios_start relative to start of image and not
* relative start of ROM, but so far, I never found a dual-image ATI card
*
* typedef struct {
* u32 signature; + 0x00
* u16 vendor; + 0x04
* u16 device; + 0x06
* u16 reserved_1; + 0x08
* u16 dlen; + 0x0a
* u8 drevision; + 0x0c
* u8 class_hi; + 0x0d
* u16 class_lo; + 0x0e
* u16 ilen; + 0x10
* u16 irevision; + 0x12
* u8 type; + 0x14
* u8 indicator; + 0x15
* u16 reserved_2; + 0x16
* } pci_data_t;
*/
if (BIOS_IN32(dptr) != (('R' << 24) | ('I' << 16) | ('C' << 8) | 'P')) {
printk(KERN_WARNING "radeonfb (%s): PCI DATA signature in ROM"
"incorrect: %08x\n", pci_name(rinfo->pdev), BIOS_IN32(dptr));
goto anyway;
}
rom_type = BIOS_IN8(dptr + 0x14);
switch(rom_type) {
case 0:
printk(KERN_INFO "radeonfb: Found Intel x86 BIOS ROM Image\n");
break;
case 1:
printk(KERN_INFO "radeonfb: Found Open Firmware ROM Image\n");
goto failed;
case 2:
printk(KERN_INFO "radeonfb: Found HP PA-RISC ROM Image\n");
goto failed;
default:
printk(KERN_INFO "radeonfb: Found unknown type %d ROM Image\n", rom_type);
goto failed;
}
anyway:
/* Locate the flat panel infos, do some sanity checking !!! */
rinfo->fp_bios_start = BIOS_IN16(0x48);
return 0;
failed:
rinfo->bios_seg = NULL;
radeon_unmap_ROM(rinfo, dev);
return -ENXIO;
}
#ifdef CONFIG_X86
static int radeon_find_mem_vbios(struct radeonfb_info *rinfo)
{
/* I simplified this code as we used to miss the signatures in
* a lot of case. It's now closer to XFree, we just don't check
* for signatures at all... Something better will have to be done
* if we end up having conflicts
*/
u32 segstart;
void __iomem *rom_base = NULL;
for(segstart=0x000c0000; segstart<0x000f0000; segstart+=0x00001000) {
rom_base = ioremap(segstart, 0x10000);
if (rom_base == NULL)
return -ENOMEM;
if (readb(rom_base) == 0x55 && readb(rom_base + 1) == 0xaa)
break;
iounmap(rom_base);
rom_base = NULL;
}
if (rom_base == NULL)
return -ENXIO;
/* Locate the flat panel infos, do some sanity checking !!! */
rinfo->bios_seg = rom_base;
rinfo->fp_bios_start = BIOS_IN16(0x48);
return 0;
}
#endif
#if defined(CONFIG_PPC_OF) || defined(CONFIG_SPARC)
/*
* Read XTAL (ref clock), SCLK and MCLK from Open Firmware device
* tree. Hopefully, ATI OF driver is kind enough to fill these
*/
static int radeon_read_xtal_OF(struct radeonfb_info *rinfo)
{
struct device_node *dp = rinfo->of_node;
const u32 *val;
if (dp == NULL)
return -ENODEV;
val = of_get_property(dp, "ATY,RefCLK", NULL);
if (!val || !*val) {
printk(KERN_WARNING "radeonfb: No ATY,RefCLK property !\n");
return -EINVAL;
}
rinfo->pll.ref_clk = (*val) / 10;
val = of_get_property(dp, "ATY,SCLK", NULL);
if (val && *val)
rinfo->pll.sclk = (*val) / 10;
val = of_get_property(dp, "ATY,MCLK", NULL);
if (val && *val)
rinfo->pll.mclk = (*val) / 10;
return 0;
}
#endif /* CONFIG_PPC_OF || CONFIG_SPARC */
/*
* Read PLL infos from chip registers
*/
static int radeon_probe_pll_params(struct radeonfb_info *rinfo)
{
unsigned char ppll_div_sel;
unsigned Ns, Nm, M;
unsigned sclk, mclk, tmp, ref_div;
int hTotal, vTotal, num, denom, m, n;
unsigned long long hz, vclk;
long xtal;
struct timeval start_tv, stop_tv;
long total_secs, total_usecs;
int i;
/* Ugh, we cut interrupts, bad bad bad, but we want some precision
* here, so... --BenH
*/
/* Flush PCI buffers ? */
tmp = INREG16(DEVICE_ID);
local_irq_disable();
for(i=0; i<1000000; i++)
if (((INREG(CRTC_VLINE_CRNT_VLINE) >> 16) & 0x3ff) == 0)
break;
do_gettimeofday(&start_tv);
for(i=0; i<1000000; i++)
if (((INREG(CRTC_VLINE_CRNT_VLINE) >> 16) & 0x3ff) != 0)
break;
for(i=0; i<1000000; i++)
if (((INREG(CRTC_VLINE_CRNT_VLINE) >> 16) & 0x3ff) == 0)
break;
do_gettimeofday(&stop_tv);
local_irq_enable();
total_secs = stop_tv.tv_sec - start_tv.tv_sec;
if (total_secs > 10)
return -1;
total_usecs = stop_tv.tv_usec - start_tv.tv_usec;
total_usecs += total_secs * 1000000;
if (total_usecs < 0)
total_usecs = -total_usecs;
hz = 1000000/total_usecs;
hTotal = ((INREG(CRTC_H_TOTAL_DISP) & 0x1ff) + 1) * 8;
vTotal = ((INREG(CRTC_V_TOTAL_DISP) & 0x3ff) + 1);
vclk = (long long)hTotal * (long long)vTotal * hz;
switch((INPLL(PPLL_REF_DIV) & 0x30000) >> 16) {
case 0:
default:
num = 1;
denom = 1;
break;
case 1:
n = ((INPLL(M_SPLL_REF_FB_DIV) >> 16) & 0xff);
m = (INPLL(M_SPLL_REF_FB_DIV) & 0xff);
num = 2*n;
denom = 2*m;
break;
case 2:
n = ((INPLL(M_SPLL_REF_FB_DIV) >> 8) & 0xff);
m = (INPLL(M_SPLL_REF_FB_DIV) & 0xff);
num = 2*n;
denom = 2*m;
break;
}
ppll_div_sel = INREG8(CLOCK_CNTL_INDEX + 1) & 0x3;
radeon_pll_errata_after_index(rinfo);
n = (INPLL(PPLL_DIV_0 + ppll_div_sel) & 0x7ff);
m = (INPLL(PPLL_REF_DIV) & 0x3ff);
num *= n;
denom *= m;
switch ((INPLL(PPLL_DIV_0 + ppll_div_sel) >> 16) & 0x7) {
case 1:
denom *= 2;
break;
case 2:
denom *= 4;
break;
case 3:
denom *= 8;
break;
case 4:
denom *= 3;
break;
case 6:
denom *= 6;
break;
case 7:
denom *= 12;
break;
}
vclk *= denom;
do_div(vclk, 1000 * num);
xtal = vclk;
if ((xtal > 26900) && (xtal < 27100))
xtal = 2700;
else if ((xtal > 14200) && (xtal < 14400))
xtal = 1432;
else if ((xtal > 29400) && (xtal < 29600))
xtal = 2950;
else {
printk(KERN_WARNING "xtal calculation failed: %ld\n", xtal);
return -1;
}
tmp = INPLL(M_SPLL_REF_FB_DIV);
ref_div = INPLL(PPLL_REF_DIV) & 0x3ff;
Ns = (tmp & 0xff0000) >> 16;
Nm = (tmp & 0xff00) >> 8;
M = (tmp & 0xff);
sclk = round_div((2 * Ns * xtal), (2 * M));
mclk = round_div((2 * Nm * xtal), (2 * M));
/* we're done, hopefully these are sane values */
rinfo->pll.ref_clk = xtal;
rinfo->pll.ref_div = ref_div;
rinfo->pll.sclk = sclk;
rinfo->pll.mclk = mclk;
return 0;
}
/*
* Retrieve PLL infos by different means (BIOS, Open Firmware, register probing...)
*/
static void radeon_get_pllinfo(struct radeonfb_info *rinfo)
{
/*
* In the case nothing works, these are defaults; they are mostly
* incomplete, however. It does provide ppll_max and _min values
* even for most other methods, however.
*/
switch (rinfo->chipset) {
case PCI_DEVICE_ID_ATI_RADEON_QW:
case PCI_DEVICE_ID_ATI_RADEON_QX:
rinfo->pll.ppll_max = 35000;
rinfo->pll.ppll_min = 12000;
rinfo->pll.mclk = 23000;
rinfo->pll.sclk = 23000;
rinfo->pll.ref_clk = 2700;
break;
case PCI_DEVICE_ID_ATI_RADEON_QL:
case PCI_DEVICE_ID_ATI_RADEON_QN:
case PCI_DEVICE_ID_ATI_RADEON_QO:
case PCI_DEVICE_ID_ATI_RADEON_Ql:
case PCI_DEVICE_ID_ATI_RADEON_BB:
rinfo->pll.ppll_max = 35000;
rinfo->pll.ppll_min = 12000;
rinfo->pll.mclk = 27500;
rinfo->pll.sclk = 27500;
rinfo->pll.ref_clk = 2700;
break;
case PCI_DEVICE_ID_ATI_RADEON_Id:
case PCI_DEVICE_ID_ATI_RADEON_Ie:
case PCI_DEVICE_ID_ATI_RADEON_If:
case PCI_DEVICE_ID_ATI_RADEON_Ig:
rinfo->pll.ppll_max = 35000;
rinfo->pll.ppll_min = 12000;
rinfo->pll.mclk = 25000;
rinfo->pll.sclk = 25000;
rinfo->pll.ref_clk = 2700;
break;
case PCI_DEVICE_ID_ATI_RADEON_ND:
case PCI_DEVICE_ID_ATI_RADEON_NE:
case PCI_DEVICE_ID_ATI_RADEON_NF:
case PCI_DEVICE_ID_ATI_RADEON_NG:
rinfo->pll.ppll_max = 40000;
rinfo->pll.ppll_min = 20000;
rinfo->pll.mclk = 27000;
rinfo->pll.sclk = 27000;
rinfo->pll.ref_clk = 2700;
break;
case PCI_DEVICE_ID_ATI_RADEON_QD:
case PCI_DEVICE_ID_ATI_RADEON_QE:
case PCI_DEVICE_ID_ATI_RADEON_QF:
case PCI_DEVICE_ID_ATI_RADEON_QG:
default:
rinfo->pll.ppll_max = 35000;
rinfo->pll.ppll_min = 12000;
rinfo->pll.mclk = 16600;
rinfo->pll.sclk = 16600;
rinfo->pll.ref_clk = 2700;
break;
}
rinfo->pll.ref_div = INPLL(PPLL_REF_DIV) & PPLL_REF_DIV_MASK;
#if defined(CONFIG_PPC_OF) || defined(CONFIG_SPARC)
/*
* Retrieve PLL infos from Open Firmware first
*/
if (!force_measure_pll && radeon_read_xtal_OF(rinfo) == 0) {
printk(KERN_INFO "radeonfb: Retrieved PLL infos from Open Firmware\n");
goto found;
}
#endif /* CONFIG_PPC_OF || CONFIG_SPARC */
/*
* Check out if we have an X86 which gave us some PLL informations
* and if yes, retrieve them
*/
if (!force_measure_pll && rinfo->bios_seg) {
u16 pll_info_block = BIOS_IN16(rinfo->fp_bios_start + 0x30);
rinfo->pll.sclk = BIOS_IN16(pll_info_block + 0x08);
rinfo->pll.mclk = BIOS_IN16(pll_info_block + 0x0a);
rinfo->pll.ref_clk = BIOS_IN16(pll_info_block + 0x0e);
rinfo->pll.ref_div = BIOS_IN16(pll_info_block + 0x10);
rinfo->pll.ppll_min = BIOS_IN32(pll_info_block + 0x12);
rinfo->pll.ppll_max = BIOS_IN32(pll_info_block + 0x16);
printk(KERN_INFO "radeonfb: Retrieved PLL infos from BIOS\n");
goto found;
}
/*
* We didn't get PLL parameters from either OF or BIOS, we try to
* probe them
*/
if (radeon_probe_pll_params(rinfo) == 0) {
printk(KERN_INFO "radeonfb: Retrieved PLL infos from registers\n");
goto found;
}
/*
* Fall back to already-set defaults...
*/
printk(KERN_INFO "radeonfb: Used default PLL infos\n");
found:
/*
* Some methods fail to retrieve SCLK and MCLK values, we apply default
* settings in this case (200Mhz). If that really happens often, we
* could fetch from registers instead...
*/
if (rinfo->pll.mclk == 0)
rinfo->pll.mclk = 20000;
if (rinfo->pll.sclk == 0)
rinfo->pll.sclk = 20000;
printk("radeonfb: Reference=%d.%02d MHz (RefDiv=%d) Memory=%d.%02d Mhz, System=%d.%02d MHz\n",
rinfo->pll.ref_clk / 100, rinfo->pll.ref_clk % 100,
rinfo->pll.ref_div,
rinfo->pll.mclk / 100, rinfo->pll.mclk % 100,
rinfo->pll.sclk / 100, rinfo->pll.sclk % 100);
printk("radeonfb: PLL min %d max %d\n", rinfo->pll.ppll_min, rinfo->pll.ppll_max);
}
static int radeonfb_check_var (struct fb_var_screeninfo *var, struct fb_info *info)
{
struct radeonfb_info *rinfo = info->par;
struct fb_var_screeninfo v;
int nom, den;
unsigned int pitch;
if (radeon_match_mode(rinfo, &v, var))
return -EINVAL;
switch (v.bits_per_pixel) {
case 0 ... 8:
v.bits_per_pixel = 8;
break;
case 9 ... 16:
v.bits_per_pixel = 16;
break;
case 17 ... 24:
#if 0 /* Doesn't seem to work */
v.bits_per_pixel = 24;
break;
#endif
return -EINVAL;
case 25 ... 32:
v.bits_per_pixel = 32;
break;
default:
return -EINVAL;
}
switch (var_to_depth(&v)) {
case 8:
nom = den = 1;
v.red.offset = v.green.offset = v.blue.offset = 0;
v.red.length = v.green.length = v.blue.length = 8;
v.transp.offset = v.transp.length = 0;
break;
case 15:
nom = 2;
den = 1;
v.red.offset = 10;
v.green.offset = 5;
v.blue.offset = 0;
v.red.length = v.green.length = v.blue.length = 5;
v.transp.offset = v.transp.length = 0;
break;
case 16:
nom = 2;
den = 1;
v.red.offset = 11;
v.green.offset = 5;
v.blue.offset = 0;
v.red.length = 5;
v.green.length = 6;
v.blue.length = 5;
v.transp.offset = v.transp.length = 0;
break;
case 24:
nom = 4;
den = 1;
v.red.offset = 16;
v.green.offset = 8;
v.blue.offset = 0;
v.red.length = v.blue.length = v.green.length = 8;
v.transp.offset = v.transp.length = 0;
break;
case 32:
nom = 4;
den = 1;
v.red.offset = 16;
v.green.offset = 8;
v.blue.offset = 0;
v.red.length = v.blue.length = v.green.length = 8;
v.transp.offset = 24;
v.transp.length = 8;
break;
default:
printk ("radeonfb: mode %dx%dx%d rejected, color depth invalid\n",
var->xres, var->yres, var->bits_per_pixel);
return -EINVAL;
}
if (v.yres_virtual < v.yres)
v.yres_virtual = v.yres;
if (v.xres_virtual < v.xres)
v.xres_virtual = v.xres;
/* XXX I'm adjusting xres_virtual to the pitch, that may help XFree
* with some panels, though I don't quite like this solution
*/
if (rinfo->info->flags & FBINFO_HWACCEL_DISABLED) {
v.xres_virtual = v.xres_virtual & ~7ul;
} else {
pitch = ((v.xres_virtual * ((v.bits_per_pixel + 1) / 8) + 0x3f)
& ~(0x3f)) >> 6;
v.xres_virtual = (pitch << 6) / ((v.bits_per_pixel + 1) / 8);
}
if (((v.xres_virtual * v.yres_virtual * nom) / den) > rinfo->mapped_vram)
return -EINVAL;
if (v.xres_virtual < v.xres)
v.xres = v.xres_virtual;
if (v.xoffset < 0)
v.xoffset = 0;
if (v.yoffset < 0)
v.yoffset = 0;
if (v.xoffset > v.xres_virtual - v.xres)
v.xoffset = v.xres_virtual - v.xres - 1;
if (v.yoffset > v.yres_virtual - v.yres)
v.yoffset = v.yres_virtual - v.yres - 1;
v.red.msb_right = v.green.msb_right = v.blue.msb_right =
v.transp.offset = v.transp.length =
v.transp.msb_right = 0;
memcpy(var, &v, sizeof(v));
return 0;
}
static int radeonfb_pan_display (struct fb_var_screeninfo *var,
struct fb_info *info)
{
struct radeonfb_info *rinfo = info->par;
if ((var->xoffset + info->var.xres > info->var.xres_virtual)
|| (var->yoffset + info->var.yres > info->var.yres_virtual))
return -EINVAL;
if (rinfo->asleep)
return 0;
radeon_fifo_wait(2);
OUTREG(CRTC_OFFSET, (var->yoffset * info->fix.line_length +
var->xoffset * info->var.bits_per_pixel / 8) & ~7);
return 0;
}
static int radeonfb_ioctl (struct fb_info *info, unsigned int cmd,
unsigned long arg)
{
struct radeonfb_info *rinfo = info->par;
unsigned int tmp;
u32 value = 0;
int rc;
switch (cmd) {
/*
* TODO: set mirror accordingly for non-Mobility chipsets with 2 CRTC's
* and do something better using 2nd CRTC instead of just hackish
* routing to second output
*/
case FBIO_RADEON_SET_MIRROR:
if (!rinfo->is_mobility)
return -EINVAL;
rc = get_user(value, (__u32 __user *)arg);
if (rc)
return rc;
radeon_fifo_wait(2);
if (value & 0x01) {
tmp = INREG(LVDS_GEN_CNTL);
tmp |= (LVDS_ON | LVDS_BLON);
} else {
tmp = INREG(LVDS_GEN_CNTL);
tmp &= ~(LVDS_ON | LVDS_BLON);
}
OUTREG(LVDS_GEN_CNTL, tmp);
if (value & 0x02) {
tmp = INREG(CRTC_EXT_CNTL);
tmp |= CRTC_CRT_ON;
mirror = 1;
} else {
tmp = INREG(CRTC_EXT_CNTL);
tmp &= ~CRTC_CRT_ON;
mirror = 0;
}
OUTREG(CRTC_EXT_CNTL, tmp);
return 0;
case FBIO_RADEON_GET_MIRROR:
if (!rinfo->is_mobility)
return -EINVAL;
tmp = INREG(LVDS_GEN_CNTL);
if ((LVDS_ON | LVDS_BLON) & tmp)
value |= 0x01;
tmp = INREG(CRTC_EXT_CNTL);
if (CRTC_CRT_ON & tmp)
value |= 0x02;
return put_user(value, (__u32 __user *)arg);
default:
return -EINVAL;
}
return -EINVAL;
}
int radeon_screen_blank(struct radeonfb_info *rinfo, int blank, int mode_switch)
{
u32 val;
u32 tmp_pix_clks;
int unblank = 0;
if (rinfo->lock_blank)
return 0;
radeon_engine_idle();
val = INREG(CRTC_EXT_CNTL);
val &= ~(CRTC_DISPLAY_DIS | CRTC_HSYNC_DIS |
CRTC_VSYNC_DIS);
switch (blank) {
case FB_BLANK_VSYNC_SUSPEND:
val |= (CRTC_DISPLAY_DIS | CRTC_VSYNC_DIS);
break;
case FB_BLANK_HSYNC_SUSPEND:
val |= (CRTC_DISPLAY_DIS | CRTC_HSYNC_DIS);
break;
case FB_BLANK_POWERDOWN:
val |= (CRTC_DISPLAY_DIS | CRTC_VSYNC_DIS |
CRTC_HSYNC_DIS);
break;
case FB_BLANK_NORMAL:
val |= CRTC_DISPLAY_DIS;
break;
case FB_BLANK_UNBLANK:
default:
unblank = 1;
}
OUTREG(CRTC_EXT_CNTL, val);
switch (rinfo->mon1_type) {
case MT_DFP:
if (unblank)
OUTREGP(FP_GEN_CNTL, (FP_FPON | FP_TMDS_EN),
~(FP_FPON | FP_TMDS_EN));
else {
if (mode_switch || blank == FB_BLANK_NORMAL)
break;
OUTREGP(FP_GEN_CNTL, 0, ~(FP_FPON | FP_TMDS_EN));
}
break;
case MT_LCD:
del_timer_sync(&rinfo->lvds_timer);
val = INREG(LVDS_GEN_CNTL);
if (unblank) {
u32 target_val = (val & ~LVDS_DISPLAY_DIS) | LVDS_BLON | LVDS_ON
| LVDS_EN | (rinfo->init_state.lvds_gen_cntl
& (LVDS_DIGON | LVDS_BL_MOD_EN));
if ((val ^ target_val) == LVDS_DISPLAY_DIS)
OUTREG(LVDS_GEN_CNTL, target_val);
else if ((val ^ target_val) != 0) {
OUTREG(LVDS_GEN_CNTL, target_val
& ~(LVDS_ON | LVDS_BL_MOD_EN));
rinfo->init_state.lvds_gen_cntl &= ~LVDS_STATE_MASK;
rinfo->init_state.lvds_gen_cntl |=
target_val & LVDS_STATE_MASK;
if (mode_switch) {
radeon_msleep(rinfo->panel_info.pwr_delay);
OUTREG(LVDS_GEN_CNTL, target_val);
}
else {
rinfo->pending_lvds_gen_cntl = target_val;
mod_timer(&rinfo->lvds_timer,
jiffies +
msecs_to_jiffies(rinfo->panel_info.pwr_delay));
}
}
} else {
val |= LVDS_DISPLAY_DIS;
OUTREG(LVDS_GEN_CNTL, val);
/* We don't do a full switch-off on a simple mode switch */
if (mode_switch || blank == FB_BLANK_NORMAL)
break;
/* Asic bug, when turning off LVDS_ON, we have to make sure
* RADEON_PIXCLK_LVDS_ALWAYS_ON bit is off
*/
tmp_pix_clks = INPLL(PIXCLKS_CNTL);
if (rinfo->is_mobility || rinfo->is_IGP)
OUTPLLP(PIXCLKS_CNTL, 0, ~PIXCLK_LVDS_ALWAYS_ONb);
val &= ~(LVDS_BL_MOD_EN);
OUTREG(LVDS_GEN_CNTL, val);
udelay(100);
val &= ~(LVDS_ON | LVDS_EN);
OUTREG(LVDS_GEN_CNTL, val);
val &= ~LVDS_DIGON;
rinfo->pending_lvds_gen_cntl = val;
mod_timer(&rinfo->lvds_timer,
jiffies +
msecs_to_jiffies(rinfo->panel_info.pwr_delay));
rinfo->init_state.lvds_gen_cntl &= ~LVDS_STATE_MASK;
rinfo->init_state.lvds_gen_cntl |= val & LVDS_STATE_MASK;
if (rinfo->is_mobility || rinfo->is_IGP)
OUTPLL(PIXCLKS_CNTL, tmp_pix_clks);
}
break;
case MT_CRT:
// todo: powerdown DAC
default:
break;
}
return 0;
}
static int radeonfb_blank (int blank, struct fb_info *info)
{
struct radeonfb_info *rinfo = info->par;
if (rinfo->asleep)
return 0;
return radeon_screen_blank(rinfo, blank, 0);
}
static int radeon_setcolreg (unsigned regno, unsigned red, unsigned green,
unsigned blue, unsigned transp,
struct radeonfb_info *rinfo)
{
u32 pindex;
unsigned int i;
if (regno > 255)
return -EINVAL;
red >>= 8;
green >>= 8;
blue >>= 8;
rinfo->palette[regno].red = red;
rinfo->palette[regno].green = green;
rinfo->palette[regno].blue = blue;
/* default */
pindex = regno;
if (!rinfo->asleep) {
radeon_fifo_wait(9);
if (rinfo->bpp == 16) {
pindex = regno * 8;
if (rinfo->depth == 16 && regno > 63)
return -EINVAL;
if (rinfo->depth == 15 && regno > 31)
return -EINVAL;
/* For 565, the green component is mixed one order
* below
*/
if (rinfo->depth == 16) {
OUTREG(PALETTE_INDEX, pindex>>1);
OUTREG(PALETTE_DATA,
(rinfo->palette[regno>>1].red << 16) |
(green << 8) |
(rinfo->palette[regno>>1].blue));
green = rinfo->palette[regno<<1].green;
}
}
if (rinfo->depth != 16 || regno < 32) {
OUTREG(PALETTE_INDEX, pindex);
OUTREG(PALETTE_DATA, (red << 16) |
(green << 8) | blue);
}
}
if (regno < 16) {
u32 *pal = rinfo->info->pseudo_palette;
switch (rinfo->depth) {
case 15:
pal[regno] = (regno << 10) | (regno << 5) | regno;
break;
case 16:
pal[regno] = (regno << 11) | (regno << 5) | regno;
break;
case 24:
pal[regno] = (regno << 16) | (regno << 8) | regno;
break;
case 32:
i = (regno << 8) | regno;
pal[regno] = (i << 16) | i;
break;
}
}
return 0;
}
static int radeonfb_setcolreg (unsigned regno, unsigned red, unsigned green,
unsigned blue, unsigned transp,
struct fb_info *info)
{
struct radeonfb_info *rinfo = info->par;
u32 dac_cntl2, vclk_cntl = 0;
int rc;
if (!rinfo->asleep) {
if (rinfo->is_mobility) {
vclk_cntl = INPLL(VCLK_ECP_CNTL);
OUTPLL(VCLK_ECP_CNTL,
vclk_cntl & ~PIXCLK_DAC_ALWAYS_ONb);
}
/* Make sure we are on first palette */
if (rinfo->has_CRTC2) {
dac_cntl2 = INREG(DAC_CNTL2);
dac_cntl2 &= ~DAC2_PALETTE_ACCESS_CNTL;
OUTREG(DAC_CNTL2, dac_cntl2);
}
}
rc = radeon_setcolreg (regno, red, green, blue, transp, rinfo);
if (!rinfo->asleep && rinfo->is_mobility)
OUTPLL(VCLK_ECP_CNTL, vclk_cntl);
return rc;
}
static int radeonfb_setcmap(struct fb_cmap *cmap, struct fb_info *info)
{
struct radeonfb_info *rinfo = info->par;
u16 *red, *green, *blue, *transp;
u32 dac_cntl2, vclk_cntl = 0;
int i, start, rc = 0;
if (!rinfo->asleep) {
if (rinfo->is_mobility) {
vclk_cntl = INPLL(VCLK_ECP_CNTL);
OUTPLL(VCLK_ECP_CNTL,
vclk_cntl & ~PIXCLK_DAC_ALWAYS_ONb);
}
/* Make sure we are on first palette */
if (rinfo->has_CRTC2) {
dac_cntl2 = INREG(DAC_CNTL2);
dac_cntl2 &= ~DAC2_PALETTE_ACCESS_CNTL;
OUTREG(DAC_CNTL2, dac_cntl2);
}
}
red = cmap->red;
green = cmap->green;
blue = cmap->blue;
transp = cmap->transp;
start = cmap->start;
for (i = 0; i < cmap->len; i++) {
u_int hred, hgreen, hblue, htransp = 0xffff;
hred = *red++;
hgreen = *green++;
hblue = *blue++;
if (transp)
htransp = *transp++;
rc = radeon_setcolreg (start++, hred, hgreen, hblue, htransp,
rinfo);
if (rc)
break;
}
if (!rinfo->asleep && rinfo->is_mobility)
OUTPLL(VCLK_ECP_CNTL, vclk_cntl);
return rc;
}
static void radeon_save_state (struct radeonfb_info *rinfo,
struct radeon_regs *save)
{
/* CRTC regs */
save->crtc_gen_cntl = INREG(CRTC_GEN_CNTL);
save->crtc_ext_cntl = INREG(CRTC_EXT_CNTL);
save->crtc_more_cntl = INREG(CRTC_MORE_CNTL);
save->dac_cntl = INREG(DAC_CNTL);
save->crtc_h_total_disp = INREG(CRTC_H_TOTAL_DISP);
save->crtc_h_sync_strt_wid = INREG(CRTC_H_SYNC_STRT_WID);
save->crtc_v_total_disp = INREG(CRTC_V_TOTAL_DISP);
save->crtc_v_sync_strt_wid = INREG(CRTC_V_SYNC_STRT_WID);
save->crtc_pitch = INREG(CRTC_PITCH);
save->surface_cntl = INREG(SURFACE_CNTL);
/* FP regs */
save->fp_crtc_h_total_disp = INREG(FP_CRTC_H_TOTAL_DISP);
save->fp_crtc_v_total_disp = INREG(FP_CRTC_V_TOTAL_DISP);
save->fp_gen_cntl = INREG(FP_GEN_CNTL);
save->fp_h_sync_strt_wid = INREG(FP_H_SYNC_STRT_WID);
save->fp_horz_stretch = INREG(FP_HORZ_STRETCH);
save->fp_v_sync_strt_wid = INREG(FP_V_SYNC_STRT_WID);
save->fp_vert_stretch = INREG(FP_VERT_STRETCH);
save->lvds_gen_cntl = INREG(LVDS_GEN_CNTL);
save->lvds_pll_cntl = INREG(LVDS_PLL_CNTL);
save->tmds_crc = INREG(TMDS_CRC);
save->tmds_transmitter_cntl = INREG(TMDS_TRANSMITTER_CNTL);
save->vclk_ecp_cntl = INPLL(VCLK_ECP_CNTL);
/* PLL regs */
save->clk_cntl_index = INREG(CLOCK_CNTL_INDEX) & ~0x3f;
radeon_pll_errata_after_index(rinfo);
save->ppll_div_3 = INPLL(PPLL_DIV_3);
save->ppll_ref_div = INPLL(PPLL_REF_DIV);
}
static void radeon_write_pll_regs(struct radeonfb_info *rinfo, struct radeon_regs *mode)
{
int i;
radeon_fifo_wait(20);
/* Workaround from XFree */
if (rinfo->is_mobility) {
/* A temporal workaround for the occasional blanking on certain laptop
* panels. This appears to related to the PLL divider registers
* (fail to lock?). It occurs even when all dividers are the same
* with their old settings. In this case we really don't need to
* fiddle with PLL registers. By doing this we can avoid the blanking
* problem with some panels.
*/
if ((mode->ppll_ref_div == (INPLL(PPLL_REF_DIV) & PPLL_REF_DIV_MASK)) &&
(mode->ppll_div_3 == (INPLL(PPLL_DIV_3) &
(PPLL_POST3_DIV_MASK | PPLL_FB3_DIV_MASK)))) {
/* We still have to force a switch to selected PPLL div thanks to
* an XFree86 driver bug which will switch it away in some cases
* even when using UseFDev */
OUTREGP(CLOCK_CNTL_INDEX,
mode->clk_cntl_index & PPLL_DIV_SEL_MASK,
~PPLL_DIV_SEL_MASK);
radeon_pll_errata_after_index(rinfo);
radeon_pll_errata_after_data(rinfo);
return;
}
}
/* Swich VCKL clock input to CPUCLK so it stays fed while PPLL updates*/
OUTPLLP(VCLK_ECP_CNTL, VCLK_SRC_SEL_CPUCLK, ~VCLK_SRC_SEL_MASK);
/* Reset PPLL & enable atomic update */
OUTPLLP(PPLL_CNTL,
PPLL_RESET | PPLL_ATOMIC_UPDATE_EN | PPLL_VGA_ATOMIC_UPDATE_EN,
~(PPLL_RESET | PPLL_ATOMIC_UPDATE_EN | PPLL_VGA_ATOMIC_UPDATE_EN));
/* Switch to selected PPLL divider */
OUTREGP(CLOCK_CNTL_INDEX,
mode->clk_cntl_index & PPLL_DIV_SEL_MASK,
~PPLL_DIV_SEL_MASK);
radeon_pll_errata_after_index(rinfo);
radeon_pll_errata_after_data(rinfo);
/* Set PPLL ref. div */
if (IS_R300_VARIANT(rinfo) ||
rinfo->family == CHIP_FAMILY_RS300 ||
rinfo->family == CHIP_FAMILY_RS400 ||
rinfo->family == CHIP_FAMILY_RS480) {
if (mode->ppll_ref_div & R300_PPLL_REF_DIV_ACC_MASK) {
/* When restoring console mode, use saved PPLL_REF_DIV
* setting.
*/
OUTPLLP(PPLL_REF_DIV, mode->ppll_ref_div, 0);
} else {
/* R300 uses ref_div_acc field as real ref divider */
OUTPLLP(PPLL_REF_DIV,
(mode->ppll_ref_div << R300_PPLL_REF_DIV_ACC_SHIFT),
~R300_PPLL_REF_DIV_ACC_MASK);
}
} else
OUTPLLP(PPLL_REF_DIV, mode->ppll_ref_div, ~PPLL_REF_DIV_MASK);
/* Set PPLL divider 3 & post divider*/
OUTPLLP(PPLL_DIV_3, mode->ppll_div_3, ~PPLL_FB3_DIV_MASK);
OUTPLLP(PPLL_DIV_3, mode->ppll_div_3, ~PPLL_POST3_DIV_MASK);
/* Write update */
while (INPLL(PPLL_REF_DIV) & PPLL_ATOMIC_UPDATE_R)
;
OUTPLLP(PPLL_REF_DIV, PPLL_ATOMIC_UPDATE_W, ~PPLL_ATOMIC_UPDATE_W);
/* Wait read update complete */
/* FIXME: Certain revisions of R300 can't recover here. Not sure of
the cause yet, but this workaround will mask the problem for now.
Other chips usually will pass at the very first test, so the
workaround shouldn't have any effect on them. */
for (i = 0; (i < 10000 && INPLL(PPLL_REF_DIV) & PPLL_ATOMIC_UPDATE_R); i++)
;
OUTPLL(HTOTAL_CNTL, 0);
/* Clear reset & atomic update */
OUTPLLP(PPLL_CNTL, 0,
~(PPLL_RESET | PPLL_SLEEP | PPLL_ATOMIC_UPDATE_EN | PPLL_VGA_ATOMIC_UPDATE_EN));
/* We may want some locking ... oh well */
radeon_msleep(5);
/* Switch back VCLK source to PPLL */
OUTPLLP(VCLK_ECP_CNTL, VCLK_SRC_SEL_PPLLCLK, ~VCLK_SRC_SEL_MASK);
}
/*
* Timer function for delayed LVDS panel power up/down
*/
static void radeon_lvds_timer_func(unsigned long data)
{
struct radeonfb_info *rinfo = (struct radeonfb_info *)data;
radeon_engine_idle();
OUTREG(LVDS_GEN_CNTL, rinfo->pending_lvds_gen_cntl);
}
/*
* Apply a video mode. This will apply the whole register set, including
* the PLL registers, to the card
*/
void radeon_write_mode (struct radeonfb_info *rinfo, struct radeon_regs *mode,
int regs_only)
{
int i;
int primary_mon = PRIMARY_MONITOR(rinfo);
if (nomodeset)
return;
if (!regs_only)
radeon_screen_blank(rinfo, FB_BLANK_NORMAL, 0);
radeon_fifo_wait(31);
for (i=0; i<10; i++)
OUTREG(common_regs[i].reg, common_regs[i].val);
/* Apply surface registers */
for (i=0; i<8; i++) {
OUTREG(SURFACE0_LOWER_BOUND + 0x10*i, mode->surf_lower_bound[i]);
OUTREG(SURFACE0_UPPER_BOUND + 0x10*i, mode->surf_upper_bound[i]);
OUTREG(SURFACE0_INFO + 0x10*i, mode->surf_info[i]);
}
OUTREG(CRTC_GEN_CNTL, mode->crtc_gen_cntl);
OUTREGP(CRTC_EXT_CNTL, mode->crtc_ext_cntl,
~(CRTC_HSYNC_DIS | CRTC_VSYNC_DIS | CRTC_DISPLAY_DIS));
OUTREG(CRTC_MORE_CNTL, mode->crtc_more_cntl);
OUTREGP(DAC_CNTL, mode->dac_cntl, DAC_RANGE_CNTL | DAC_BLANKING);
OUTREG(CRTC_H_TOTAL_DISP, mode->crtc_h_total_disp);
OUTREG(CRTC_H_SYNC_STRT_WID, mode->crtc_h_sync_strt_wid);
OUTREG(CRTC_V_TOTAL_DISP, mode->crtc_v_total_disp);
OUTREG(CRTC_V_SYNC_STRT_WID, mode->crtc_v_sync_strt_wid);
OUTREG(CRTC_OFFSET, 0);
OUTREG(CRTC_OFFSET_CNTL, 0);
OUTREG(CRTC_PITCH, mode->crtc_pitch);
OUTREG(SURFACE_CNTL, mode->surface_cntl);
radeon_write_pll_regs(rinfo, mode);
if ((primary_mon == MT_DFP) || (primary_mon == MT_LCD)) {
radeon_fifo_wait(10);
OUTREG(FP_CRTC_H_TOTAL_DISP, mode->fp_crtc_h_total_disp);
OUTREG(FP_CRTC_V_TOTAL_DISP, mode->fp_crtc_v_total_disp);
OUTREG(FP_H_SYNC_STRT_WID, mode->fp_h_sync_strt_wid);
OUTREG(FP_V_SYNC_STRT_WID, mode->fp_v_sync_strt_wid);
OUTREG(FP_HORZ_STRETCH, mode->fp_horz_stretch);
OUTREG(FP_VERT_STRETCH, mode->fp_vert_stretch);
OUTREG(FP_GEN_CNTL, mode->fp_gen_cntl);
OUTREG(TMDS_CRC, mode->tmds_crc);
OUTREG(TMDS_TRANSMITTER_CNTL, mode->tmds_transmitter_cntl);
}
if (!regs_only)
radeon_screen_blank(rinfo, FB_BLANK_UNBLANK, 0);
radeon_fifo_wait(2);
OUTPLL(VCLK_ECP_CNTL, mode->vclk_ecp_cntl);
return;
}
/*
* Calculate the PLL values for a given mode
*/
static void radeon_calc_pll_regs(struct radeonfb_info *rinfo, struct radeon_regs *regs,
unsigned long freq)
{
const struct {
int divider;
int bitvalue;
} *post_div,
post_divs[] = {
{ 1, 0 },
{ 2, 1 },
{ 4, 2 },
{ 8, 3 },
{ 3, 4 },
{ 16, 5 },
{ 6, 6 },
{ 12, 7 },
{ 0, 0 },
};
int fb_div, pll_output_freq = 0;
int uses_dvo = 0;
/* Check if the DVO port is enabled and sourced from the primary CRTC. I'm
* not sure which model starts having FP2_GEN_CNTL, I assume anything more
* recent than an r(v)100...
*/
#if 1
/* XXX I had reports of flicker happening with the cinema display
* on TMDS1 that seem to be fixed if I also forbit odd dividers in
* this case. This could just be a bandwidth calculation issue, I
* haven't implemented the bandwidth code yet, but in the meantime,
* forcing uses_dvo to 1 fixes it and shouln't have bad side effects,
* I haven't seen a case were were absolutely needed an odd PLL
* divider. I'll find a better fix once I have more infos on the
* real cause of the problem.
*/
while (rinfo->has_CRTC2) {
u32 fp2_gen_cntl = INREG(FP2_GEN_CNTL);
u32 disp_output_cntl;
int source;
/* FP2 path not enabled */
if ((fp2_gen_cntl & FP2_ON) == 0)
break;
/* Not all chip revs have the same format for this register,
* extract the source selection
*/
if (rinfo->family == CHIP_FAMILY_R200 || IS_R300_VARIANT(rinfo)) {
source = (fp2_gen_cntl >> 10) & 0x3;
/* sourced from transform unit, check for transform unit
* own source
*/
if (source == 3) {
disp_output_cntl = INREG(DISP_OUTPUT_CNTL);
source = (disp_output_cntl >> 12) & 0x3;
}
} else
source = (fp2_gen_cntl >> 13) & 0x1;
/* sourced from CRTC2 -> exit */
if (source == 1)
break;
/* so we end up on CRTC1, let's set uses_dvo to 1 now */
uses_dvo = 1;
break;
}
#else
uses_dvo = 1;
#endif
if (freq > rinfo->pll.ppll_max)
freq = rinfo->pll.ppll_max;
if (freq*12 < rinfo->pll.ppll_min)
freq = rinfo->pll.ppll_min / 12;
pr_debug("freq = %lu, PLL min = %u, PLL max = %u\n",
freq, rinfo->pll.ppll_min, rinfo->pll.ppll_max);
for (post_div = &post_divs[0]; post_div->divider; ++post_div) {
pll_output_freq = post_div->divider * freq;
/* If we output to the DVO port (external TMDS), we don't allow an
* odd PLL divider as those aren't supported on this path
*/
if (uses_dvo && (post_div->divider & 1))
continue;
if (pll_output_freq >= rinfo->pll.ppll_min &&
pll_output_freq <= rinfo->pll.ppll_max)
break;
}
/* If we fall through the bottom, try the "default value"
given by the terminal post_div->bitvalue */
if ( !post_div->divider ) {
post_div = &post_divs[post_div->bitvalue];
pll_output_freq = post_div->divider * freq;
}
pr_debug("ref_div = %d, ref_clk = %d, output_freq = %d\n",
rinfo->pll.ref_div, rinfo->pll.ref_clk,
pll_output_freq);
/* If we fall through the bottom, try the "default value"
given by the terminal post_div->bitvalue */
if ( !post_div->divider ) {
post_div = &post_divs[post_div->bitvalue];
pll_output_freq = post_div->divider * freq;
}
pr_debug("ref_div = %d, ref_clk = %d, output_freq = %d\n",
rinfo->pll.ref_div, rinfo->pll.ref_clk,
pll_output_freq);
fb_div = round_div(rinfo->pll.ref_div*pll_output_freq,
rinfo->pll.ref_clk);
regs->ppll_ref_div = rinfo->pll.ref_div;
regs->ppll_div_3 = fb_div | (post_div->bitvalue << 16);
pr_debug("post div = 0x%x\n", post_div->bitvalue);
pr_debug("fb_div = 0x%x\n", fb_div);
pr_debug("ppll_div_3 = 0x%x\n", regs->ppll_div_3);
}
static int radeonfb_set_par(struct fb_info *info)
{
struct radeonfb_info *rinfo = info->par;
struct fb_var_screeninfo *mode = &info->var;
struct radeon_regs *newmode;
int hTotal, vTotal, hSyncStart, hSyncEnd,
hSyncPol, vSyncStart, vSyncEnd, vSyncPol, cSync;
u8 hsync_adj_tab[] = {0, 0x12, 9, 9, 6, 5};
u8 hsync_fudge_fp[] = {2, 2, 0, 0, 5, 5};
u32 sync, h_sync_pol, v_sync_pol, dotClock, pixClock;
int i, freq;
int format = 0;
int nopllcalc = 0;
int hsync_start, hsync_fudge, bytpp, hsync_wid, vsync_wid;
int primary_mon = PRIMARY_MONITOR(rinfo);
int depth = var_to_depth(mode);
int use_rmx = 0;
newmode = kmalloc(sizeof(struct radeon_regs), GFP_KERNEL);
if (!newmode)
return -ENOMEM;
/* We always want engine to be idle on a mode switch, even
* if we won't actually change the mode
*/
radeon_engine_idle();
hSyncStart = mode->xres + mode->right_margin;
hSyncEnd = hSyncStart + mode->hsync_len;
hTotal = hSyncEnd + mode->left_margin;
vSyncStart = mode->yres + mode->lower_margin;
vSyncEnd = vSyncStart + mode->vsync_len;
vTotal = vSyncEnd + mode->upper_margin;
pixClock = mode->pixclock;
sync = mode->sync;
h_sync_pol = sync & FB_SYNC_HOR_HIGH_ACT ? 0 : 1;
v_sync_pol = sync & FB_SYNC_VERT_HIGH_ACT ? 0 : 1;
if (primary_mon == MT_DFP || primary_mon == MT_LCD) {
if (rinfo->panel_info.xres < mode->xres)
mode->xres = rinfo->panel_info.xres;
if (rinfo->panel_info.yres < mode->yres)
mode->yres = rinfo->panel_info.yres;
hTotal = mode->xres + rinfo->panel_info.hblank;
hSyncStart = mode->xres + rinfo->panel_info.hOver_plus;
hSyncEnd = hSyncStart + rinfo->panel_info.hSync_width;
vTotal = mode->yres + rinfo->panel_info.vblank;
vSyncStart = mode->yres + rinfo->panel_info.vOver_plus;
vSyncEnd = vSyncStart + rinfo->panel_info.vSync_width;
h_sync_pol = !rinfo->panel_info.hAct_high;
v_sync_pol = !rinfo->panel_info.vAct_high;
pixClock = 100000000 / rinfo->panel_info.clock;
if (rinfo->panel_info.use_bios_dividers) {
nopllcalc = 1;
newmode->ppll_div_3 = rinfo->panel_info.fbk_divider |
(rinfo->panel_info.post_divider << 16);
newmode->ppll_ref_div = rinfo->panel_info.ref_divider;
}
}
dotClock = 1000000000 / pixClock;
freq = dotClock / 10; /* x100 */
pr_debug("hStart = %d, hEnd = %d, hTotal = %d\n",
hSyncStart, hSyncEnd, hTotal);
pr_debug("vStart = %d, vEnd = %d, vTotal = %d\n",
vSyncStart, vSyncEnd, vTotal);
hsync_wid = (hSyncEnd - hSyncStart) / 8;
vsync_wid = vSyncEnd - vSyncStart;
if (hsync_wid == 0)
hsync_wid = 1;
else if (hsync_wid > 0x3f) /* max */
hsync_wid = 0x3f;
if (vsync_wid == 0)
vsync_wid = 1;
else if (vsync_wid > 0x1f) /* max */
vsync_wid = 0x1f;
hSyncPol = mode->sync & FB_SYNC_HOR_HIGH_ACT ? 0 : 1;
vSyncPol = mode->sync & FB_SYNC_VERT_HIGH_ACT ? 0 : 1;
cSync = mode->sync & FB_SYNC_COMP_HIGH_ACT ? (1 << 4) : 0;
format = radeon_get_dstbpp(depth);
bytpp = mode->bits_per_pixel >> 3;
if ((primary_mon == MT_DFP) || (primary_mon == MT_LCD))
hsync_fudge = hsync_fudge_fp[format-1];
else
hsync_fudge = hsync_adj_tab[format-1];
hsync_start = hSyncStart - 8 + hsync_fudge;
newmode->crtc_gen_cntl = CRTC_EXT_DISP_EN | CRTC_EN |
(format << 8);
/* Clear auto-center etc... */
newmode->crtc_more_cntl = rinfo->init_state.crtc_more_cntl;
newmode->crtc_more_cntl &= 0xfffffff0;
if ((primary_mon == MT_DFP) || (primary_mon == MT_LCD)) {
newmode->crtc_ext_cntl = VGA_ATI_LINEAR | XCRT_CNT_EN;
if (mirror)
newmode->crtc_ext_cntl |= CRTC_CRT_ON;
newmode->crtc_gen_cntl &= ~(CRTC_DBL_SCAN_EN |
CRTC_INTERLACE_EN);
} else {
newmode->crtc_ext_cntl = VGA_ATI_LINEAR | XCRT_CNT_EN |
CRTC_CRT_ON;
}
newmode->dac_cntl = /* INREG(DAC_CNTL) | */ DAC_MASK_ALL | DAC_VGA_ADR_EN |
DAC_8BIT_EN;
newmode->crtc_h_total_disp = ((((hTotal / 8) - 1) & 0x3ff) |
(((mode->xres / 8) - 1) << 16));
newmode->crtc_h_sync_strt_wid = ((hsync_start & 0x1fff) |
(hsync_wid << 16) | (h_sync_pol << 23));
newmode->crtc_v_total_disp = ((vTotal - 1) & 0xffff) |
((mode->yres - 1) << 16);
newmode->crtc_v_sync_strt_wid = (((vSyncStart - 1) & 0xfff) |
(vsync_wid << 16) | (v_sync_pol << 23));
if (!(info->flags & FBINFO_HWACCEL_DISABLED)) {
/* We first calculate the engine pitch */
rinfo->pitch = ((mode->xres_virtual * ((mode->bits_per_pixel + 1) / 8) + 0x3f)
& ~(0x3f)) >> 6;
/* Then, re-multiply it to get the CRTC pitch */
newmode->crtc_pitch = (rinfo->pitch << 3) / ((mode->bits_per_pixel + 1) / 8);
} else
newmode->crtc_pitch = (mode->xres_virtual >> 3);
newmode->crtc_pitch |= (newmode->crtc_pitch << 16);
/*
* It looks like recent chips have a problem with SURFACE_CNTL,
* setting SURF_TRANSLATION_DIS completely disables the
* swapper as well, so we leave it unset now.
*/
newmode->surface_cntl = 0;
#if defined(__BIG_ENDIAN)
/* Setup swapping on both apertures, though we currently
* only use aperture 0, enabling swapper on aperture 1
* won't harm
*/
switch (mode->bits_per_pixel) {
case 16:
newmode->surface_cntl |= NONSURF_AP0_SWP_16BPP;
newmode->surface_cntl |= NONSURF_AP1_SWP_16BPP;
break;
case 24:
case 32:
newmode->surface_cntl |= NONSURF_AP0_SWP_32BPP;
newmode->surface_cntl |= NONSURF_AP1_SWP_32BPP;
break;
}
#endif
/* Clear surface registers */
for (i=0; i<8; i++) {
newmode->surf_lower_bound[i] = 0;
newmode->surf_upper_bound[i] = 0x1f;
newmode->surf_info[i] = 0;
}
pr_debug("h_total_disp = 0x%x\t hsync_strt_wid = 0x%x\n",
newmode->crtc_h_total_disp, newmode->crtc_h_sync_strt_wid);
pr_debug("v_total_disp = 0x%x\t vsync_strt_wid = 0x%x\n",
newmode->crtc_v_total_disp, newmode->crtc_v_sync_strt_wid);
rinfo->bpp = mode->bits_per_pixel;
rinfo->depth = depth;
pr_debug("pixclock = %lu\n", (unsigned long)pixClock);
pr_debug("freq = %lu\n", (unsigned long)freq);
/* We use PPLL_DIV_3 */
newmode->clk_cntl_index = 0x300;
/* Calculate PPLL value if necessary */
if (!nopllcalc)
radeon_calc_pll_regs(rinfo, newmode, freq);
newmode->vclk_ecp_cntl = rinfo->init_state.vclk_ecp_cntl;
if ((primary_mon == MT_DFP) || (primary_mon == MT_LCD)) {
unsigned int hRatio, vRatio;
if (mode->xres > rinfo->panel_info.xres)
mode->xres = rinfo->panel_info.xres;
if (mode->yres > rinfo->panel_info.yres)
mode->yres = rinfo->panel_info.yres;
newmode->fp_horz_stretch = (((rinfo->panel_info.xres / 8) - 1)
<< HORZ_PANEL_SHIFT);
newmode->fp_vert_stretch = ((rinfo->panel_info.yres - 1)
<< VERT_PANEL_SHIFT);
if (mode->xres != rinfo->panel_info.xres) {
hRatio = round_div(mode->xres * HORZ_STRETCH_RATIO_MAX,
rinfo->panel_info.xres);
newmode->fp_horz_stretch = (((((unsigned long)hRatio) & HORZ_STRETCH_RATIO_MASK)) |
(newmode->fp_horz_stretch &
(HORZ_PANEL_SIZE | HORZ_FP_LOOP_STRETCH |
HORZ_AUTO_RATIO_INC)));
newmode->fp_horz_stretch |= (HORZ_STRETCH_BLEND |
HORZ_STRETCH_ENABLE);
use_rmx = 1;
}
newmode->fp_horz_stretch &= ~HORZ_AUTO_RATIO;
if (mode->yres != rinfo->panel_info.yres) {
vRatio = round_div(mode->yres * VERT_STRETCH_RATIO_MAX,
rinfo->panel_info.yres);
newmode->fp_vert_stretch = (((((unsigned long)vRatio) & VERT_STRETCH_RATIO_MASK)) |
(newmode->fp_vert_stretch &
(VERT_PANEL_SIZE | VERT_STRETCH_RESERVED)));
newmode->fp_vert_stretch |= (VERT_STRETCH_BLEND |
VERT_STRETCH_ENABLE);
use_rmx = 1;
}
newmode->fp_vert_stretch &= ~VERT_AUTO_RATIO_EN;
newmode->fp_gen_cntl = (rinfo->init_state.fp_gen_cntl & (u32)
~(FP_SEL_CRTC2 |
FP_RMX_HVSYNC_CONTROL_EN |
FP_DFP_SYNC_SEL |
FP_CRT_SYNC_SEL |
FP_CRTC_LOCK_8DOT |
FP_USE_SHADOW_EN |
FP_CRTC_USE_SHADOW_VEND |
FP_CRT_SYNC_ALT));
newmode->fp_gen_cntl |= (FP_CRTC_DONT_SHADOW_VPAR |
FP_CRTC_DONT_SHADOW_HEND |
FP_PANEL_FORMAT);
if (IS_R300_VARIANT(rinfo) ||
(rinfo->family == CHIP_FAMILY_R200)) {
newmode->fp_gen_cntl &= ~R200_FP_SOURCE_SEL_MASK;
if (use_rmx)
newmode->fp_gen_cntl |= R200_FP_SOURCE_SEL_RMX;
else
newmode->fp_gen_cntl |= R200_FP_SOURCE_SEL_CRTC1;
} else
newmode->fp_gen_cntl |= FP_SEL_CRTC1;
newmode->lvds_gen_cntl = rinfo->init_state.lvds_gen_cntl;
newmode->lvds_pll_cntl = rinfo->init_state.lvds_pll_cntl;
newmode->tmds_crc = rinfo->init_state.tmds_crc;
newmode->tmds_transmitter_cntl = rinfo->init_state.tmds_transmitter_cntl;
if (primary_mon == MT_LCD) {
newmode->lvds_gen_cntl |= (LVDS_ON | LVDS_BLON);
newmode->fp_gen_cntl &= ~(FP_FPON | FP_TMDS_EN);
} else {
/* DFP */
newmode->fp_gen_cntl |= (FP_FPON | FP_TMDS_EN);
newmode->tmds_transmitter_cntl &= ~(TMDS_PLLRST);
/* TMDS_PLL_EN bit is reversed on RV (and mobility) chips */
if (IS_R300_VARIANT(rinfo) ||
(rinfo->family == CHIP_FAMILY_R200) || !rinfo->has_CRTC2)
newmode->tmds_transmitter_cntl &= ~TMDS_PLL_EN;
else
newmode->tmds_transmitter_cntl |= TMDS_PLL_EN;
newmode->crtc_ext_cntl &= ~CRTC_CRT_ON;
}
newmode->fp_crtc_h_total_disp = (((rinfo->panel_info.hblank / 8) & 0x3ff) |
(((mode->xres / 8) - 1) << 16));
newmode->fp_crtc_v_total_disp = (rinfo->panel_info.vblank & 0xffff) |
((mode->yres - 1) << 16);
newmode->fp_h_sync_strt_wid = ((rinfo->panel_info.hOver_plus & 0x1fff) |
(hsync_wid << 16) | (h_sync_pol << 23));
newmode->fp_v_sync_strt_wid = ((rinfo->panel_info.vOver_plus & 0xfff) |
(vsync_wid << 16) | (v_sync_pol << 23));
}
/* do it! */
if (!rinfo->asleep) {
memcpy(&rinfo->state, newmode, sizeof(*newmode));
radeon_write_mode (rinfo, newmode, 0);
/* (re)initialize the engine */
if (!(info->flags & FBINFO_HWACCEL_DISABLED))
radeonfb_engine_init (rinfo);
}
/* Update fix */
if (!(info->flags & FBINFO_HWACCEL_DISABLED))
info->fix.line_length = rinfo->pitch*64;
else
info->fix.line_length = mode->xres_virtual
* ((mode->bits_per_pixel + 1) / 8);
info->fix.visual = rinfo->depth == 8 ? FB_VISUAL_PSEUDOCOLOR
: FB_VISUAL_DIRECTCOLOR;
#ifdef CONFIG_BOOTX_TEXT
/* Update debug text engine */
btext_update_display(rinfo->fb_base_phys, mode->xres, mode->yres,
rinfo->depth, info->fix.line_length);
#endif
kfree(newmode);
return 0;
}
static struct fb_ops radeonfb_ops = {
.owner = THIS_MODULE,
.fb_check_var = radeonfb_check_var,
.fb_set_par = radeonfb_set_par,
.fb_setcolreg = radeonfb_setcolreg,
.fb_setcmap = radeonfb_setcmap,
.fb_pan_display = radeonfb_pan_display,
.fb_blank = radeonfb_blank,
.fb_ioctl = radeonfb_ioctl,
.fb_sync = radeonfb_sync,
.fb_fillrect = radeonfb_fillrect,
.fb_copyarea = radeonfb_copyarea,
.fb_imageblit = radeonfb_imageblit,
};
static int radeon_set_fbinfo(struct radeonfb_info *rinfo)
{
struct fb_info *info = rinfo->info;
info->par = rinfo;
info->pseudo_palette = rinfo->pseudo_palette;
info->flags = FBINFO_DEFAULT
| FBINFO_HWACCEL_COPYAREA
| FBINFO_HWACCEL_FILLRECT
| FBINFO_HWACCEL_XPAN
| FBINFO_HWACCEL_YPAN;
info->fbops = &radeonfb_ops;
info->screen_base = rinfo->fb_base;
info->screen_size = rinfo->mapped_vram;
/* Fill fix common fields */
strlcpy(info->fix.id, rinfo->name, sizeof(info->fix.id));
info->fix.smem_start = rinfo->fb_base_phys;
info->fix.smem_len = rinfo->video_ram;
info->fix.type = FB_TYPE_PACKED_PIXELS;
info->fix.visual = FB_VISUAL_PSEUDOCOLOR;
info->fix.xpanstep = 8;
info->fix.ypanstep = 1;
info->fix.ywrapstep = 0;
info->fix.type_aux = 0;
info->fix.mmio_start = rinfo->mmio_base_phys;
info->fix.mmio_len = RADEON_REGSIZE;
info->fix.accel = FB_ACCEL_ATI_RADEON;
fb_alloc_cmap(&info->cmap, 256, 0);
if (noaccel)
info->flags |= FBINFO_HWACCEL_DISABLED;
return 0;
}
/*
* This reconfigure the card's internal memory map. In theory, we'd like
* to setup the card's memory at the same address as it's PCI bus address,
* and the AGP aperture right after that so that system RAM on 32 bits
* machines at least, is directly accessible. However, doing so would
* conflict with the current XFree drivers...
* Ultimately, I hope XFree, GATOS and ATI binary drivers will all agree
* on the proper way to set this up and duplicate this here. In the meantime,
* I put the card's memory at 0 in card space and AGP at some random high
* local (0xe0000000 for now) that will be changed by XFree/DRI anyway
*/
#ifdef CONFIG_PPC_OF
#undef SET_MC_FB_FROM_APERTURE
static void fixup_memory_mappings(struct radeonfb_info *rinfo)
{
u32 save_crtc_gen_cntl, save_crtc2_gen_cntl = 0;
u32 save_crtc_ext_cntl;
u32 aper_base, aper_size;
u32 agp_base;
/* First, we disable display to avoid interfering */
if (rinfo->has_CRTC2) {
save_crtc2_gen_cntl = INREG(CRTC2_GEN_CNTL);
OUTREG(CRTC2_GEN_CNTL, save_crtc2_gen_cntl | CRTC2_DISP_REQ_EN_B);
}
save_crtc_gen_cntl = INREG(CRTC_GEN_CNTL);
save_crtc_ext_cntl = INREG(CRTC_EXT_CNTL);
OUTREG(CRTC_EXT_CNTL, save_crtc_ext_cntl | CRTC_DISPLAY_DIS);
OUTREG(CRTC_GEN_CNTL, save_crtc_gen_cntl | CRTC_DISP_REQ_EN_B);
mdelay(100);
aper_base = INREG(CNFG_APER_0_BASE);
aper_size = INREG(CNFG_APER_SIZE);
#ifdef SET_MC_FB_FROM_APERTURE
/* Set framebuffer to be at the same address as set in PCI BAR */
OUTREG(MC_FB_LOCATION,
((aper_base + aper_size - 1) & 0xffff0000) | (aper_base >> 16));
rinfo->fb_local_base = aper_base;
#else
OUTREG(MC_FB_LOCATION, 0x7fff0000);
rinfo->fb_local_base = 0;
#endif
agp_base = aper_base + aper_size;
if (agp_base & 0xf0000000)
agp_base = (aper_base | 0x0fffffff) + 1;
/* Set AGP to be just after the framebuffer on a 256Mb boundary. This
* assumes the FB isn't mapped to 0xf0000000 or above, but this is
* always the case on PPCs afaik.
*/
#ifdef SET_MC_FB_FROM_APERTURE
OUTREG(MC_AGP_LOCATION, 0xffff0000 | (agp_base >> 16));
#else
OUTREG(MC_AGP_LOCATION, 0xffffe000);
#endif
/* Fixup the display base addresses & engine offsets while we
* are at it as well
*/
#ifdef SET_MC_FB_FROM_APERTURE
OUTREG(DISPLAY_BASE_ADDR, aper_base);
if (rinfo->has_CRTC2)
OUTREG(CRTC2_DISPLAY_BASE_ADDR, aper_base);
OUTREG(OV0_BASE_ADDR, aper_base);
#else
OUTREG(DISPLAY_BASE_ADDR, 0);
if (rinfo->has_CRTC2)
OUTREG(CRTC2_DISPLAY_BASE_ADDR, 0);
OUTREG(OV0_BASE_ADDR, 0);
#endif
mdelay(100);
/* Restore display settings */
OUTREG(CRTC_GEN_CNTL, save_crtc_gen_cntl);
OUTREG(CRTC_EXT_CNTL, save_crtc_ext_cntl);
if (rinfo->has_CRTC2)
OUTREG(CRTC2_GEN_CNTL, save_crtc2_gen_cntl);
pr_debug("aper_base: %08x MC_FB_LOC to: %08x, MC_AGP_LOC to: %08x\n",
aper_base,
((aper_base + aper_size - 1) & 0xffff0000) | (aper_base >> 16),
0xffff0000 | (agp_base >> 16));
}
#endif /* CONFIG_PPC_OF */
static void radeon_identify_vram(struct radeonfb_info *rinfo)
{
u32 tmp;
/* framebuffer size */
if ((rinfo->family == CHIP_FAMILY_RS100) ||
(rinfo->family == CHIP_FAMILY_RS200) ||
(rinfo->family == CHIP_FAMILY_RS300) ||
(rinfo->family == CHIP_FAMILY_RC410) ||
(rinfo->family == CHIP_FAMILY_RS400) ||
(rinfo->family == CHIP_FAMILY_RS480) ) {
u32 tom = INREG(NB_TOM);
tmp = ((((tom >> 16) - (tom & 0xffff) + 1) << 6) * 1024);
radeon_fifo_wait(6);
OUTREG(MC_FB_LOCATION, tom);
OUTREG(DISPLAY_BASE_ADDR, (tom & 0xffff) << 16);
OUTREG(CRTC2_DISPLAY_BASE_ADDR, (tom & 0xffff) << 16);
OUTREG(OV0_BASE_ADDR, (tom & 0xffff) << 16);
/* This is supposed to fix the crtc2 noise problem. */
OUTREG(GRPH2_BUFFER_CNTL, INREG(GRPH2_BUFFER_CNTL) & ~0x7f0000);
if ((rinfo->family == CHIP_FAMILY_RS100) ||
(rinfo->family == CHIP_FAMILY_RS200)) {
/* This is to workaround the asic bug for RMX, some versions
of BIOS doesn't have this register initialized correctly.
*/
OUTREGP(CRTC_MORE_CNTL, CRTC_H_CUTOFF_ACTIVE_EN,
~CRTC_H_CUTOFF_ACTIVE_EN);
}
} else {
tmp = INREG(CNFG_MEMSIZE);
}
/* mem size is bits [28:0], mask off the rest */
rinfo->video_ram = tmp & CNFG_MEMSIZE_MASK;
/*
* Hack to get around some busted production M6's
* reporting no ram
*/
if (rinfo->video_ram == 0) {
switch (rinfo->pdev->device) {
case PCI_CHIP_RADEON_LY:
case PCI_CHIP_RADEON_LZ:
rinfo->video_ram = 8192 * 1024;
break;
default:
break;
}
}
/*
* Now try to identify VRAM type
*/
if (rinfo->is_IGP || (rinfo->family >= CHIP_FAMILY_R300) ||
(INREG(MEM_SDRAM_MODE_REG) & (1<<30)))
rinfo->vram_ddr = 1;
else
rinfo->vram_ddr = 0;
tmp = INREG(MEM_CNTL);
if (IS_R300_VARIANT(rinfo)) {
tmp &= R300_MEM_NUM_CHANNELS_MASK;
switch (tmp) {
case 0: rinfo->vram_width = 64; break;
case 1: rinfo->vram_width = 128; break;
case 2: rinfo->vram_width = 256; break;
default: rinfo->vram_width = 128; break;
}
} else if ((rinfo->family == CHIP_FAMILY_RV100) ||
(rinfo->family == CHIP_FAMILY_RS100) ||
(rinfo->family == CHIP_FAMILY_RS200)){
if (tmp & RV100_MEM_HALF_MODE)
rinfo->vram_width = 32;
else
rinfo->vram_width = 64;
} else {
if (tmp & MEM_NUM_CHANNELS_MASK)
rinfo->vram_width = 128;
else
rinfo->vram_width = 64;
}
/* This may not be correct, as some cards can have half of channel disabled
* ToDo: identify these cases
*/
pr_debug("radeonfb (%s): Found %ldk of %s %d bits wide videoram\n",
pci_name(rinfo->pdev),
rinfo->video_ram / 1024,
rinfo->vram_ddr ? "DDR" : "SDRAM",
rinfo->vram_width);
}
/*
* Sysfs
*/
static ssize_t radeon_show_one_edid(char *buf, loff_t off, size_t count, const u8 *edid)
{
return memory_read_from_buffer(buf, count, &off, edid, EDID_LENGTH);
}
static ssize_t radeon_show_edid1(struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t off, size_t count)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct pci_dev *pdev = to_pci_dev(dev);
struct fb_info *info = pci_get_drvdata(pdev);
struct radeonfb_info *rinfo = info->par;
return radeon_show_one_edid(buf, off, count, rinfo->mon1_EDID);
}
static ssize_t radeon_show_edid2(struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t off, size_t count)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct pci_dev *pdev = to_pci_dev(dev);
struct fb_info *info = pci_get_drvdata(pdev);
struct radeonfb_info *rinfo = info->par;
return radeon_show_one_edid(buf, off, count, rinfo->mon2_EDID);
}
static struct bin_attribute edid1_attr = {
.attr = {
.name = "edid1",
.mode = 0444,
},
.size = EDID_LENGTH,
.read = radeon_show_edid1,
};
static struct bin_attribute edid2_attr = {
.attr = {
.name = "edid2",
.mode = 0444,
},
.size = EDID_LENGTH,
.read = radeon_show_edid2,
};
static int radeonfb_pci_register(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct fb_info *info;
struct radeonfb_info *rinfo;
int ret;
unsigned char c1, c2;
int err = 0;
pr_debug("radeonfb_pci_register BEGIN\n");
/* Enable device in PCI config */
ret = pci_enable_device(pdev);
if (ret < 0) {
printk(KERN_ERR "radeonfb (%s): Cannot enable PCI device\n",
pci_name(pdev));
goto err_out;
}
info = framebuffer_alloc(sizeof(struct radeonfb_info), &pdev->dev);
if (!info) {
printk (KERN_ERR "radeonfb (%s): could not allocate memory\n",
pci_name(pdev));
ret = -ENOMEM;
goto err_disable;
}
rinfo = info->par;
rinfo->info = info;
rinfo->pdev = pdev;
spin_lock_init(&rinfo->reg_lock);
init_timer(&rinfo->lvds_timer);
rinfo->lvds_timer.function = radeon_lvds_timer_func;
rinfo->lvds_timer.data = (unsigned long)rinfo;
c1 = ent->device >> 8;
c2 = ent->device & 0xff;
if (isprint(c1) && isprint(c2))
snprintf(rinfo->name, sizeof(rinfo->name),
"ATI Radeon %x \"%c%c\"", ent->device & 0xffff, c1, c2);
else
snprintf(rinfo->name, sizeof(rinfo->name),
"ATI Radeon %x", ent->device & 0xffff);
rinfo->family = ent->driver_data & CHIP_FAMILY_MASK;
rinfo->chipset = pdev->device;
rinfo->has_CRTC2 = (ent->driver_data & CHIP_HAS_CRTC2) != 0;
rinfo->is_mobility = (ent->driver_data & CHIP_IS_MOBILITY) != 0;
rinfo->is_IGP = (ent->driver_data & CHIP_IS_IGP) != 0;
/* Set base addrs */
rinfo->fb_base_phys = pci_resource_start (pdev, 0);
rinfo->mmio_base_phys = pci_resource_start (pdev, 2);
/* request the mem regions */
ret = pci_request_region(pdev, 0, "radeonfb framebuffer");
if (ret < 0) {
printk( KERN_ERR "radeonfb (%s): cannot request region 0.\n",
pci_name(rinfo->pdev));
goto err_release_fb;
}
ret = pci_request_region(pdev, 2, "radeonfb mmio");
if (ret < 0) {
printk( KERN_ERR "radeonfb (%s): cannot request region 2.\n",
pci_name(rinfo->pdev));
goto err_release_pci0;
}
/* map the regions */
rinfo->mmio_base = ioremap(rinfo->mmio_base_phys, RADEON_REGSIZE);
if (!rinfo->mmio_base) {
printk(KERN_ERR "radeonfb (%s): cannot map MMIO\n",
pci_name(rinfo->pdev));
ret = -EIO;
goto err_release_pci2;
}
rinfo->fb_local_base = INREG(MC_FB_LOCATION) << 16;
/*
* Check for errata
*/
rinfo->errata = 0;
if (rinfo->family == CHIP_FAMILY_R300 &&
(INREG(CNFG_CNTL) & CFG_ATI_REV_ID_MASK)
== CFG_ATI_REV_A11)
rinfo->errata |= CHIP_ERRATA_R300_CG;
if (rinfo->family == CHIP_FAMILY_RV200 ||
rinfo->family == CHIP_FAMILY_RS200)
rinfo->errata |= CHIP_ERRATA_PLL_DUMMYREADS;
if (rinfo->family == CHIP_FAMILY_RV100 ||
rinfo->family == CHIP_FAMILY_RS100 ||
rinfo->family == CHIP_FAMILY_RS200)
rinfo->errata |= CHIP_ERRATA_PLL_DELAY;
#if defined(CONFIG_PPC_OF) || defined(CONFIG_SPARC)
/* On PPC, we obtain the OF device-node pointer to the firmware
* data for this chip
*/
rinfo->of_node = pci_device_to_OF_node(pdev);
if (rinfo->of_node == NULL)
printk(KERN_WARNING "radeonfb (%s): Cannot match card to OF node !\n",
pci_name(rinfo->pdev));
#endif /* CONFIG_PPC_OF || CONFIG_SPARC */
#ifdef CONFIG_PPC_OF
/* On PPC, the firmware sets up a memory mapping that tends
* to cause lockups when enabling the engine. We reconfigure
* the card internal memory mappings properly
*/
fixup_memory_mappings(rinfo);
#endif /* CONFIG_PPC_OF */
/* Get VRAM size and type */
radeon_identify_vram(rinfo);
rinfo->mapped_vram = min_t(unsigned long, MAX_MAPPED_VRAM, rinfo->video_ram);
do {
rinfo->fb_base = ioremap (rinfo->fb_base_phys,
rinfo->mapped_vram);
} while (rinfo->fb_base == NULL &&
((rinfo->mapped_vram /= 2) >= MIN_MAPPED_VRAM));
if (rinfo->fb_base == NULL) {
printk (KERN_ERR "radeonfb (%s): cannot map FB\n",
pci_name(rinfo->pdev));
ret = -EIO;
goto err_unmap_rom;
}
pr_debug("radeonfb (%s): mapped %ldk videoram\n", pci_name(rinfo->pdev),
rinfo->mapped_vram/1024);
/*
* Map the BIOS ROM if any and retrieve PLL parameters from
* the BIOS. We skip that on mobility chips as the real panel
* values we need aren't in the ROM but in the BIOS image in
* memory. This is definitely not the best meacnism though,
* we really need the arch code to tell us which is the "primary"
* video adapter to use the memory image (or better, the arch
* should provide us a copy of the BIOS image to shield us from
* archs who would store that elsewhere and/or could initialize
* more than one adapter during boot).
*/
if (!rinfo->is_mobility)
radeon_map_ROM(rinfo, pdev);
/*
* On x86, the primary display on laptop may have it's BIOS
* ROM elsewhere, try to locate it at the legacy memory hole.
* We probably need to make sure this is the primary display,
* but that is difficult without some arch support.
*/
#ifdef CONFIG_X86
if (rinfo->bios_seg == NULL)
radeon_find_mem_vbios(rinfo);
#endif
/* If both above failed, try the BIOS ROM again for mobility
* chips
*/
if (rinfo->bios_seg == NULL && rinfo->is_mobility)
radeon_map_ROM(rinfo, pdev);
/* Get informations about the board's PLL */
radeon_get_pllinfo(rinfo);
#ifdef CONFIG_FB_RADEON_I2C
/* Register I2C bus */
radeon_create_i2c_busses(rinfo);
#endif
/* set all the vital stuff */
radeon_set_fbinfo (rinfo);
/* Probe screen types */
radeon_probe_screens(rinfo, monitor_layout, ignore_edid);
/* Build mode list, check out panel native model */
radeon_check_modes(rinfo, mode_option);
/* Register some sysfs stuff (should be done better) */
if (rinfo->mon1_EDID)
err |= sysfs_create_bin_file(&rinfo->pdev->dev.kobj,
&edid1_attr);
if (rinfo->mon2_EDID)
err |= sysfs_create_bin_file(&rinfo->pdev->dev.kobj,
&edid2_attr);
if (err)
pr_warning("%s() Creating sysfs files failed, continuing\n",
__func__);
/* save current mode regs before we switch into the new one
* so we can restore this upon __exit
*/
radeon_save_state (rinfo, &rinfo->init_state);
memcpy(&rinfo->state, &rinfo->init_state, sizeof(struct radeon_regs));
/* Setup Power Management capabilities */
if (default_dynclk < -1) {
/* -2 is special: means ON on mobility chips and do not
* change on others
*/
radeonfb_pm_init(rinfo, rinfo->is_mobility ? 1 : -1, ignore_devlist, force_sleep);
} else
radeonfb_pm_init(rinfo, default_dynclk, ignore_devlist, force_sleep);
pci_set_drvdata(pdev, info);
/* Register with fbdev layer */
ret = register_framebuffer(info);
if (ret < 0) {
printk (KERN_ERR "radeonfb (%s): could not register framebuffer\n",
pci_name(rinfo->pdev));
goto err_unmap_fb;
}
#ifdef CONFIG_MTRR
rinfo->mtrr_hdl = nomtrr ? -1 : mtrr_add(rinfo->fb_base_phys,
rinfo->video_ram,
MTRR_TYPE_WRCOMB, 1);
#endif
if (backlight)
radeonfb_bl_init(rinfo);
printk ("radeonfb (%s): %s\n", pci_name(rinfo->pdev), rinfo->name);
if (rinfo->bios_seg)
radeon_unmap_ROM(rinfo, pdev);
pr_debug("radeonfb_pci_register END\n");
return 0;
err_unmap_fb:
iounmap(rinfo->fb_base);
err_unmap_rom:
kfree(rinfo->mon1_EDID);
kfree(rinfo->mon2_EDID);
if (rinfo->mon1_modedb)
fb_destroy_modedb(rinfo->mon1_modedb);
fb_dealloc_cmap(&info->cmap);
#ifdef CONFIG_FB_RADEON_I2C
radeon_delete_i2c_busses(rinfo);
#endif
if (rinfo->bios_seg)
radeon_unmap_ROM(rinfo, pdev);
iounmap(rinfo->mmio_base);
err_release_pci2:
pci_release_region(pdev, 2);
err_release_pci0:
pci_release_region(pdev, 0);
err_release_fb:
framebuffer_release(info);
err_disable:
err_out:
return ret;
}
static void radeonfb_pci_unregister(struct pci_dev *pdev)
{
struct fb_info *info = pci_get_drvdata(pdev);
struct radeonfb_info *rinfo = info->par;
if (!rinfo)
return;
radeonfb_pm_exit(rinfo);
if (rinfo->mon1_EDID)
sysfs_remove_bin_file(&rinfo->pdev->dev.kobj, &edid1_attr);
if (rinfo->mon2_EDID)
sysfs_remove_bin_file(&rinfo->pdev->dev.kobj, &edid2_attr);
#if 0
/* restore original state
*
* Doesn't quite work yet, I suspect if we come from a legacy
* VGA mode (or worse, text mode), we need to do some VGA black
* magic here that I know nothing about. --BenH
*/
radeon_write_mode (rinfo, &rinfo->init_state, 1);
#endif
del_timer_sync(&rinfo->lvds_timer);
#ifdef CONFIG_MTRR
if (rinfo->mtrr_hdl >= 0)
mtrr_del(rinfo->mtrr_hdl, 0, 0);
#endif
unregister_framebuffer(info);
radeonfb_bl_exit(rinfo);
iounmap(rinfo->mmio_base);
iounmap(rinfo->fb_base);
pci_release_region(pdev, 2);
pci_release_region(pdev, 0);
kfree(rinfo->mon1_EDID);
kfree(rinfo->mon2_EDID);
if (rinfo->mon1_modedb)
fb_destroy_modedb(rinfo->mon1_modedb);
#ifdef CONFIG_FB_RADEON_I2C
radeon_delete_i2c_busses(rinfo);
#endif
fb_dealloc_cmap(&info->cmap);
framebuffer_release(info);
}
static struct pci_driver radeonfb_driver = {
.name = "radeonfb",
.id_table = radeonfb_pci_table,
.probe = radeonfb_pci_register,
.remove = radeonfb_pci_unregister,
#ifdef CONFIG_PM
.suspend = radeonfb_pci_suspend,
.resume = radeonfb_pci_resume,
#endif /* CONFIG_PM */
};
#ifndef MODULE
static int __init radeonfb_setup (char *options)
{
char *this_opt;
if (!options || !*options)
return 0;
while ((this_opt = strsep (&options, ",")) != NULL) {
if (!*this_opt)
continue;
if (!strncmp(this_opt, "noaccel", 7)) {
noaccel = 1;
} else if (!strncmp(this_opt, "mirror", 6)) {
mirror = 1;
} else if (!strncmp(this_opt, "force_dfp", 9)) {
force_dfp = 1;
} else if (!strncmp(this_opt, "panel_yres:", 11)) {
panel_yres = simple_strtoul((this_opt+11), NULL, 0);
} else if (!strncmp(this_opt, "backlight:", 10)) {
backlight = simple_strtoul(this_opt+10, NULL, 0);
#ifdef CONFIG_MTRR
} else if (!strncmp(this_opt, "nomtrr", 6)) {
nomtrr = 1;
#endif
} else if (!strncmp(this_opt, "nomodeset", 9)) {
nomodeset = 1;
} else if (!strncmp(this_opt, "force_measure_pll", 17)) {
force_measure_pll = 1;
} else if (!strncmp(this_opt, "ignore_edid", 11)) {
ignore_edid = 1;
#if defined(CONFIG_PM) && defined(CONFIG_X86)
} else if (!strncmp(this_opt, "force_sleep", 11)) {
force_sleep = 1;
} else if (!strncmp(this_opt, "ignore_devlist", 14)) {
ignore_devlist = 1;
#endif
} else
mode_option = this_opt;
}
return 0;
}
#endif /* MODULE */
static int __init radeonfb_init (void)
{
#ifndef MODULE
char *option = NULL;
if (fb_get_options("radeonfb", &option))
return -ENODEV;
radeonfb_setup(option);
#endif
return pci_register_driver (&radeonfb_driver);
}
static void __exit radeonfb_exit (void)
{
pci_unregister_driver (&radeonfb_driver);
}
module_init(radeonfb_init);
module_exit(radeonfb_exit);
MODULE_AUTHOR("Ani Joshi");
MODULE_DESCRIPTION("framebuffer driver for ATI Radeon chipset");
MODULE_LICENSE("GPL");
module_param(noaccel, bool, 0);
module_param(default_dynclk, int, 0);
MODULE_PARM_DESC(default_dynclk, "int: -2=enable on mobility only,-1=do not change,0=off,1=on");
MODULE_PARM_DESC(noaccel, "bool: disable acceleration");
module_param(nomodeset, bool, 0);
MODULE_PARM_DESC(nomodeset, "bool: disable actual setting of video mode");
module_param(mirror, bool, 0);
MODULE_PARM_DESC(mirror, "bool: mirror the display to both monitors");
module_param(force_dfp, bool, 0);
MODULE_PARM_DESC(force_dfp, "bool: force display to dfp");
module_param(ignore_edid, bool, 0);
MODULE_PARM_DESC(ignore_edid, "bool: Ignore EDID data when doing DDC probe");
module_param(monitor_layout, charp, 0);
MODULE_PARM_DESC(monitor_layout, "Specify monitor mapping (like XFree86)");
module_param(force_measure_pll, bool, 0);
MODULE_PARM_DESC(force_measure_pll, "Force measurement of PLL (debug)");
#ifdef CONFIG_MTRR
module_param(nomtrr, bool, 0);
MODULE_PARM_DESC(nomtrr, "bool: disable use of MTRR registers");
#endif
module_param(panel_yres, int, 0);
MODULE_PARM_DESC(panel_yres, "int: set panel yres");
module_param(mode_option, charp, 0);
MODULE_PARM_DESC(mode_option, "Specify resolution as \"<xres>x<yres>[-<bpp>][@<refresh>]\" ");
#if defined(CONFIG_PM) && defined(CONFIG_X86)
module_param(force_sleep, bool, 0);
MODULE_PARM_DESC(force_sleep, "bool: force D2 sleep mode on all hardware");
module_param(ignore_devlist, bool, 0);
MODULE_PARM_DESC(ignore_devlist, "bool: ignore workarounds for bugs in specific laptops");
#endif
| gpl-2.0 |
longsleep/ubuntu-odroidc | fs/autofs4/inode.c | 2398 | 8437 | /* -*- c -*- --------------------------------------------------------------- *
*
* linux/fs/autofs/inode.c
*
* Copyright 1997-1998 Transmeta Corporation -- All Rights Reserved
* Copyright 2005-2006 Ian Kent <raven@themaw.net>
*
* 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.
*
* ------------------------------------------------------------------------- */
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/file.h>
#include <linux/seq_file.h>
#include <linux/pagemap.h>
#include <linux/parser.h>
#include <linux/bitops.h>
#include <linux/magic.h>
#include "autofs_i.h"
#include <linux/module.h>
struct autofs_info *autofs4_new_ino(struct autofs_sb_info *sbi)
{
struct autofs_info *ino = kzalloc(sizeof(*ino), GFP_KERNEL);
if (ino) {
INIT_LIST_HEAD(&ino->active);
INIT_LIST_HEAD(&ino->expiring);
ino->last_used = jiffies;
ino->sbi = sbi;
}
return ino;
}
void autofs4_clean_ino(struct autofs_info *ino)
{
ino->uid = GLOBAL_ROOT_UID;
ino->gid = GLOBAL_ROOT_GID;
ino->last_used = jiffies;
}
void autofs4_free_ino(struct autofs_info *ino)
{
kfree(ino);
}
void autofs4_kill_sb(struct super_block *sb)
{
struct autofs_sb_info *sbi = autofs4_sbi(sb);
/*
* In the event of a failure in get_sb_nodev the superblock
* info is not present so nothing else has been setup, so
* just call kill_anon_super when we are called from
* deactivate_super.
*/
if (!sbi)
goto out_kill_sb;
/* Free wait queues, close pipe */
autofs4_catatonic_mode(sbi);
sb->s_fs_info = NULL;
kfree(sbi);
out_kill_sb:
DPRINTK("shutting down");
kill_litter_super(sb);
}
static int autofs4_show_options(struct seq_file *m, struct dentry *root)
{
struct autofs_sb_info *sbi = autofs4_sbi(root->d_sb);
struct inode *root_inode = root->d_sb->s_root->d_inode;
if (!sbi)
return 0;
seq_printf(m, ",fd=%d", sbi->pipefd);
if (!uid_eq(root_inode->i_uid, GLOBAL_ROOT_UID))
seq_printf(m, ",uid=%u",
from_kuid_munged(&init_user_ns, root_inode->i_uid));
if (!gid_eq(root_inode->i_gid, GLOBAL_ROOT_GID))
seq_printf(m, ",gid=%u",
from_kgid_munged(&init_user_ns, root_inode->i_gid));
seq_printf(m, ",pgrp=%d", sbi->oz_pgrp);
seq_printf(m, ",timeout=%lu", sbi->exp_timeout/HZ);
seq_printf(m, ",minproto=%d", sbi->min_proto);
seq_printf(m, ",maxproto=%d", sbi->max_proto);
if (autofs_type_offset(sbi->type))
seq_printf(m, ",offset");
else if (autofs_type_direct(sbi->type))
seq_printf(m, ",direct");
else
seq_printf(m, ",indirect");
return 0;
}
static void autofs4_evict_inode(struct inode *inode)
{
clear_inode(inode);
kfree(inode->i_private);
}
static const struct super_operations autofs4_sops = {
.statfs = simple_statfs,
.show_options = autofs4_show_options,
.evict_inode = autofs4_evict_inode,
};
enum {Opt_err, Opt_fd, Opt_uid, Opt_gid, Opt_pgrp, Opt_minproto, Opt_maxproto,
Opt_indirect, Opt_direct, Opt_offset};
static const match_table_t tokens = {
{Opt_fd, "fd=%u"},
{Opt_uid, "uid=%u"},
{Opt_gid, "gid=%u"},
{Opt_pgrp, "pgrp=%u"},
{Opt_minproto, "minproto=%u"},
{Opt_maxproto, "maxproto=%u"},
{Opt_indirect, "indirect"},
{Opt_direct, "direct"},
{Opt_offset, "offset"},
{Opt_err, NULL}
};
static int parse_options(char *options, int *pipefd, kuid_t *uid, kgid_t *gid,
pid_t *pgrp, unsigned int *type, int *minproto, int *maxproto)
{
char *p;
substring_t args[MAX_OPT_ARGS];
int option;
*uid = current_uid();
*gid = current_gid();
*pgrp = task_pgrp_nr(current);
*minproto = AUTOFS_MIN_PROTO_VERSION;
*maxproto = AUTOFS_MAX_PROTO_VERSION;
*pipefd = -1;
if (!options)
return 1;
while ((p = strsep(&options, ",")) != NULL) {
int token;
if (!*p)
continue;
token = match_token(p, tokens, args);
switch (token) {
case Opt_fd:
if (match_int(args, pipefd))
return 1;
break;
case Opt_uid:
if (match_int(args, &option))
return 1;
*uid = make_kuid(current_user_ns(), option);
if (!uid_valid(*uid))
return 1;
break;
case Opt_gid:
if (match_int(args, &option))
return 1;
*gid = make_kgid(current_user_ns(), option);
if (!gid_valid(*gid))
return 1;
break;
case Opt_pgrp:
if (match_int(args, &option))
return 1;
*pgrp = option;
break;
case Opt_minproto:
if (match_int(args, &option))
return 1;
*minproto = option;
break;
case Opt_maxproto:
if (match_int(args, &option))
return 1;
*maxproto = option;
break;
case Opt_indirect:
set_autofs_type_indirect(type);
break;
case Opt_direct:
set_autofs_type_direct(type);
break;
case Opt_offset:
set_autofs_type_offset(type);
break;
default:
return 1;
}
}
return (*pipefd < 0);
}
int autofs4_fill_super(struct super_block *s, void *data, int silent)
{
struct inode * root_inode;
struct dentry * root;
struct file * pipe;
int pipefd;
struct autofs_sb_info *sbi;
struct autofs_info *ino;
sbi = kzalloc(sizeof(*sbi), GFP_KERNEL);
if (!sbi)
goto fail_unlock;
DPRINTK("starting up, sbi = %p",sbi);
s->s_fs_info = sbi;
sbi->magic = AUTOFS_SBI_MAGIC;
sbi->pipefd = -1;
sbi->pipe = NULL;
sbi->catatonic = 1;
sbi->exp_timeout = 0;
sbi->oz_pgrp = task_pgrp_nr(current);
sbi->sb = s;
sbi->version = 0;
sbi->sub_version = 0;
set_autofs_type_indirect(&sbi->type);
sbi->min_proto = 0;
sbi->max_proto = 0;
mutex_init(&sbi->wq_mutex);
mutex_init(&sbi->pipe_mutex);
spin_lock_init(&sbi->fs_lock);
sbi->queues = NULL;
spin_lock_init(&sbi->lookup_lock);
INIT_LIST_HEAD(&sbi->active_list);
INIT_LIST_HEAD(&sbi->expiring_list);
s->s_blocksize = 1024;
s->s_blocksize_bits = 10;
s->s_magic = AUTOFS_SUPER_MAGIC;
s->s_op = &autofs4_sops;
s->s_d_op = &autofs4_dentry_operations;
s->s_time_gran = 1;
/*
* Get the root inode and dentry, but defer checking for errors.
*/
ino = autofs4_new_ino(sbi);
if (!ino)
goto fail_free;
root_inode = autofs4_get_inode(s, S_IFDIR | 0755);
root = d_make_root(root_inode);
if (!root)
goto fail_ino;
pipe = NULL;
root->d_fsdata = ino;
/* Can this call block? */
if (parse_options(data, &pipefd, &root_inode->i_uid, &root_inode->i_gid,
&sbi->oz_pgrp, &sbi->type, &sbi->min_proto,
&sbi->max_proto)) {
printk("autofs: called with bogus options\n");
goto fail_dput;
}
if (autofs_type_trigger(sbi->type))
__managed_dentry_set_managed(root);
root_inode->i_fop = &autofs4_root_operations;
root_inode->i_op = &autofs4_dir_inode_operations;
/* Couldn't this be tested earlier? */
if (sbi->max_proto < AUTOFS_MIN_PROTO_VERSION ||
sbi->min_proto > AUTOFS_MAX_PROTO_VERSION) {
printk("autofs: kernel does not match daemon version "
"daemon (%d, %d) kernel (%d, %d)\n",
sbi->min_proto, sbi->max_proto,
AUTOFS_MIN_PROTO_VERSION, AUTOFS_MAX_PROTO_VERSION);
goto fail_dput;
}
/* Establish highest kernel protocol version */
if (sbi->max_proto > AUTOFS_MAX_PROTO_VERSION)
sbi->version = AUTOFS_MAX_PROTO_VERSION;
else
sbi->version = sbi->max_proto;
sbi->sub_version = AUTOFS_PROTO_SUBVERSION;
DPRINTK("pipe fd = %d, pgrp = %u", pipefd, sbi->oz_pgrp);
pipe = fget(pipefd);
if (!pipe) {
printk("autofs: could not open pipe file descriptor\n");
goto fail_dput;
}
if (autofs_prepare_pipe(pipe) < 0)
goto fail_fput;
sbi->pipe = pipe;
sbi->pipefd = pipefd;
sbi->catatonic = 0;
/*
* Success! Install the root dentry now to indicate completion.
*/
s->s_root = root;
return 0;
/*
* Failure ... clean up.
*/
fail_fput:
printk("autofs: pipe file descriptor does not contain proper ops\n");
fput(pipe);
/* fall through */
fail_dput:
dput(root);
goto fail_free;
fail_ino:
kfree(ino);
fail_free:
kfree(sbi);
s->s_fs_info = NULL;
fail_unlock:
return -EINVAL;
}
struct inode *autofs4_get_inode(struct super_block *sb, umode_t mode)
{
struct inode *inode = new_inode(sb);
if (inode == NULL)
return NULL;
inode->i_mode = mode;
if (sb->s_root) {
inode->i_uid = sb->s_root->d_inode->i_uid;
inode->i_gid = sb->s_root->d_inode->i_gid;
}
inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
inode->i_ino = get_next_ino();
if (S_ISDIR(mode)) {
set_nlink(inode, 2);
inode->i_op = &autofs4_dir_inode_operations;
inode->i_fop = &autofs4_dir_operations;
} else if (S_ISLNK(mode)) {
inode->i_op = &autofs4_symlink_inode_operations;
}
return inode;
}
| gpl-2.0 |
mbadarkhe/davinci-next | arch/h8300/kernel/setup.c | 2398 | 6650 | /*
* linux/arch/h8300/kernel/setup.c
*
* Copyleft ()) 2000 James D. Schettine {james@telos-systems.com}
* Copyright (C) 1999,2000 Greg Ungerer (gerg@snapgear.com)
* Copyright (C) 1998,1999 D. Jeff Dionne <jeff@lineo.ca>
* Copyright (C) 1998 Kenneth Albanowski <kjahds@kjahds.com>
* Copyright (C) 1995 Hamish Macdonald
* Copyright (C) 2000 Lineo Inc. (www.lineo.com)
* Copyright (C) 2001 Lineo, Inc. <www.lineo.com>
*
* H8/300 porting Yoshinori Sato <ysato@users.sourceforge.jp>
*/
/*
* This file handles the architecture-dependent parts of system setup
*/
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/mm.h>
#include <linux/fs.h>
#include <linux/fb.h>
#include <linux/console.h>
#include <linux/genhd.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/major.h>
#include <linux/bootmem.h>
#include <linux/seq_file.h>
#include <linux/init.h>
#include <asm/setup.h>
#include <asm/irq.h>
#include <asm/pgtable.h>
#include <asm/sections.h>
#if defined(__H8300H__)
#define CPU "H8/300H"
#include <asm/regs306x.h>
#endif
#if defined(__H8300S__)
#define CPU "H8S"
#include <asm/regs267x.h>
#endif
#define STUBSIZE 0xc000
unsigned long rom_length;
unsigned long memory_start;
unsigned long memory_end;
char __initdata command_line[COMMAND_LINE_SIZE];
extern int _ramstart, _ramend;
extern char _target_name[];
extern void h8300_gpio_init(void);
#if (defined(CONFIG_H8300H_SIM) || defined(CONFIG_H8S_SIM)) \
&& defined(CONFIG_GDB_MAGICPRINT)
/* printk with gdb service */
static void gdb_console_output(struct console *c, const char *msg, unsigned len)
{
for (; len > 0; len--) {
asm("mov.w %0,r2\n\t"
"jsr @0xc4"::"r"(*msg++):"er2");
}
}
/*
* Setup initial baud/bits/parity. We do two things here:
* - construct a cflag setting for the first rs_open()
* - initialize the serial port
* Return non-zero if we didn't find a serial port.
*/
static int __init gdb_console_setup(struct console *co, char *options)
{
return 0;
}
static const struct console gdb_console = {
.name = "gdb_con",
.write = gdb_console_output,
.device = NULL,
.setup = gdb_console_setup,
.flags = CON_PRINTBUFFER,
.index = -1,
};
#endif
void __init setup_arch(char **cmdline_p)
{
int bootmap_size;
memory_start = (unsigned long) &_ramstart;
/* allow for ROMFS on the end of the kernel */
if (memcmp((void *)memory_start, "-rom1fs-", 8) == 0) {
#if defined(CONFIG_BLK_DEV_INITRD)
initrd_start = memory_start;
initrd_end = memory_start += be32_to_cpu(((unsigned long *) (memory_start))[2]);
#else
memory_start += be32_to_cpu(((unsigned long *) memory_start)[2]);
#endif
}
memory_start = PAGE_ALIGN(memory_start);
#if !defined(CONFIG_BLKDEV_RESERVE)
memory_end = (unsigned long) &_ramend; /* by now the stack is part of the init task */
#if defined(CONFIG_GDB_DEBUG)
memory_end -= STUBSIZE;
#endif
#else
if ((memory_end < CONFIG_BLKDEV_RESERVE_ADDRESS) &&
(memory_end > CONFIG_BLKDEV_RESERVE_ADDRESS))
/* overlap userarea */
memory_end = CONFIG_BLKDEV_RESERVE_ADDRESS;
#endif
init_mm.start_code = (unsigned long) _stext;
init_mm.end_code = (unsigned long) _etext;
init_mm.end_data = (unsigned long) _edata;
init_mm.brk = (unsigned long) 0;
#if (defined(CONFIG_H8300H_SIM) || defined(CONFIG_H8S_SIM)) && defined(CONFIG_GDB_MAGICPRINT)
register_console((struct console *)&gdb_console);
#endif
printk(KERN_INFO "\r\n\nuClinux " CPU "\n");
printk(KERN_INFO "Target Hardware: %s\n",_target_name);
printk(KERN_INFO "Flat model support (C) 1998,1999 Kenneth Albanowski, D. Jeff Dionne\n");
printk(KERN_INFO "H8/300 series support by Yoshinori Sato <ysato@users.sourceforge.jp>\n");
#ifdef DEBUG
printk(KERN_DEBUG "KERNEL -> TEXT=0x%p-0x%p DATA=0x%p-0x%p "
"BSS=0x%p-0x%p\n", _stext, _etext, _sdata, _edata, __bss_start,
__bss_stop);
printk(KERN_DEBUG "KERNEL -> ROMFS=0x%p-0x%06lx MEM=0x%06lx-0x%06lx "
"STACK=0x%06lx-0x%p\n", __bss_stop, memory_start, memory_start,
memory_end, memory_end, &_ramend);
#endif
#ifdef CONFIG_DEFAULT_CMDLINE
/* set from default command line */
if (*command_line == '\0')
strcpy(command_line,CONFIG_KERNEL_COMMAND);
#endif
/* Keep a copy of command line */
*cmdline_p = &command_line[0];
memcpy(boot_command_line, command_line, COMMAND_LINE_SIZE);
boot_command_line[COMMAND_LINE_SIZE-1] = 0;
#ifdef DEBUG
if (strlen(*cmdline_p))
printk(KERN_DEBUG "Command line: '%s'\n", *cmdline_p);
#endif
/*
* give all the memory to the bootmap allocator, tell it to put the
* boot mem_map at the start of memory
*/
bootmap_size = init_bootmem_node(
NODE_DATA(0),
memory_start >> PAGE_SHIFT, /* map goes here */
PAGE_OFFSET >> PAGE_SHIFT, /* 0 on coldfire */
memory_end >> PAGE_SHIFT);
/*
* free the usable memory, we have to make sure we do not free
* the bootmem bitmap so we then reserve it after freeing it :-)
*/
free_bootmem(memory_start, memory_end - memory_start);
reserve_bootmem(memory_start, bootmap_size, BOOTMEM_DEFAULT);
/*
* get kmalloc into gear
*/
paging_init();
h8300_gpio_init();
#if defined(CONFIG_H8300_AKI3068NET) && defined(CONFIG_IDE)
{
#define AREABIT(addr) (1 << (((addr) >> 21) & 7))
/* setup BSC */
volatile unsigned char *abwcr = (volatile unsigned char *)ABWCR;
volatile unsigned char *cscr = (volatile unsigned char *)CSCR;
*abwcr &= ~(AREABIT(CONFIG_H8300_IDE_BASE) | AREABIT(CONFIG_H8300_IDE_ALT));
*cscr |= (AREABIT(CONFIG_H8300_IDE_BASE) | AREABIT(CONFIG_H8300_IDE_ALT)) | 0x0f;
}
#endif
#ifdef DEBUG
printk(KERN_DEBUG "Done setup_arch\n");
#endif
}
/*
* Get CPU information for use by the procfs.
*/
static int show_cpuinfo(struct seq_file *m, void *v)
{
char *cpu;
int mode;
u_long clockfreq;
cpu = CPU;
mode = *(volatile unsigned char *)MDCR & 0x07;
clockfreq = CONFIG_CPU_CLOCK;
seq_printf(m, "CPU:\t\t%s (mode:%d)\n"
"Clock:\t\t%lu.%1luMHz\n"
"BogoMips:\t%lu.%02lu\n"
"Calibration:\t%lu loops\n",
cpu,mode,
clockfreq/1000,clockfreq%1000,
(loops_per_jiffy*HZ)/500000,((loops_per_jiffy*HZ)/5000)%100,
(loops_per_jiffy*HZ));
return 0;
}
static void *c_start(struct seq_file *m, loff_t *pos)
{
return *pos < NR_CPUS ? ((void *) 0x12345678) : NULL;
}
static void *c_next(struct seq_file *m, void *v, loff_t *pos)
{
++*pos;
return c_start(m, pos);
}
static void c_stop(struct seq_file *m, void *v)
{
}
const struct seq_operations cpuinfo_op = {
.start = c_start,
.next = c_next,
.stop = c_stop,
.show = show_cpuinfo,
};
| gpl-2.0 |
hiikezoe/android_kernel_asus_tf300t | drivers/gpu/drm/radeon/radeon_irq.c | 2654 | 10612 | /* radeon_irq.c -- IRQ handling for radeon -*- linux-c -*- */
/*
* Copyright (C) The Weather Channel, Inc. 2002. All Rights Reserved.
*
* The Weather Channel (TM) funded Tungsten Graphics to develop the
* initial release of the Radeon 8500 driver under the XFree86 license.
* This notice must be preserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Authors:
* Keith Whitwell <keith@tungstengraphics.com>
* Michel D�zer <michel@daenzer.net>
*/
#include "drmP.h"
#include "drm.h"
#include "radeon_drm.h"
#include "radeon_drv.h"
void radeon_irq_set_state(struct drm_device *dev, u32 mask, int state)
{
drm_radeon_private_t *dev_priv = dev->dev_private;
if (state)
dev_priv->irq_enable_reg |= mask;
else
dev_priv->irq_enable_reg &= ~mask;
if (dev->irq_enabled)
RADEON_WRITE(RADEON_GEN_INT_CNTL, dev_priv->irq_enable_reg);
}
static void r500_vbl_irq_set_state(struct drm_device *dev, u32 mask, int state)
{
drm_radeon_private_t *dev_priv = dev->dev_private;
if (state)
dev_priv->r500_disp_irq_reg |= mask;
else
dev_priv->r500_disp_irq_reg &= ~mask;
if (dev->irq_enabled)
RADEON_WRITE(R500_DxMODE_INT_MASK, dev_priv->r500_disp_irq_reg);
}
int radeon_enable_vblank(struct drm_device *dev, int crtc)
{
drm_radeon_private_t *dev_priv = dev->dev_private;
if ((dev_priv->flags & RADEON_FAMILY_MASK) >= CHIP_RS600) {
switch (crtc) {
case 0:
r500_vbl_irq_set_state(dev, R500_D1MODE_INT_MASK, 1);
break;
case 1:
r500_vbl_irq_set_state(dev, R500_D2MODE_INT_MASK, 1);
break;
default:
DRM_ERROR("tried to enable vblank on non-existent crtc %d\n",
crtc);
return -EINVAL;
}
} else {
switch (crtc) {
case 0:
radeon_irq_set_state(dev, RADEON_CRTC_VBLANK_MASK, 1);
break;
case 1:
radeon_irq_set_state(dev, RADEON_CRTC2_VBLANK_MASK, 1);
break;
default:
DRM_ERROR("tried to enable vblank on non-existent crtc %d\n",
crtc);
return -EINVAL;
}
}
return 0;
}
void radeon_disable_vblank(struct drm_device *dev, int crtc)
{
drm_radeon_private_t *dev_priv = dev->dev_private;
if ((dev_priv->flags & RADEON_FAMILY_MASK) >= CHIP_RS600) {
switch (crtc) {
case 0:
r500_vbl_irq_set_state(dev, R500_D1MODE_INT_MASK, 0);
break;
case 1:
r500_vbl_irq_set_state(dev, R500_D2MODE_INT_MASK, 0);
break;
default:
DRM_ERROR("tried to enable vblank on non-existent crtc %d\n",
crtc);
break;
}
} else {
switch (crtc) {
case 0:
radeon_irq_set_state(dev, RADEON_CRTC_VBLANK_MASK, 0);
break;
case 1:
radeon_irq_set_state(dev, RADEON_CRTC2_VBLANK_MASK, 0);
break;
default:
DRM_ERROR("tried to enable vblank on non-existent crtc %d\n",
crtc);
break;
}
}
}
static inline u32 radeon_acknowledge_irqs(drm_radeon_private_t *dev_priv, u32 *r500_disp_int)
{
u32 irqs = RADEON_READ(RADEON_GEN_INT_STATUS);
u32 irq_mask = RADEON_SW_INT_TEST;
*r500_disp_int = 0;
if ((dev_priv->flags & RADEON_FAMILY_MASK) >= CHIP_RS600) {
/* vbl interrupts in a different place */
if (irqs & R500_DISPLAY_INT_STATUS) {
/* if a display interrupt */
u32 disp_irq;
disp_irq = RADEON_READ(R500_DISP_INTERRUPT_STATUS);
*r500_disp_int = disp_irq;
if (disp_irq & R500_D1_VBLANK_INTERRUPT)
RADEON_WRITE(R500_D1MODE_VBLANK_STATUS, R500_VBLANK_ACK);
if (disp_irq & R500_D2_VBLANK_INTERRUPT)
RADEON_WRITE(R500_D2MODE_VBLANK_STATUS, R500_VBLANK_ACK);
}
irq_mask |= R500_DISPLAY_INT_STATUS;
} else
irq_mask |= RADEON_CRTC_VBLANK_STAT | RADEON_CRTC2_VBLANK_STAT;
irqs &= irq_mask;
if (irqs)
RADEON_WRITE(RADEON_GEN_INT_STATUS, irqs);
return irqs;
}
/* Interrupts - Used for device synchronization and flushing in the
* following circumstances:
*
* - Exclusive FB access with hw idle:
* - Wait for GUI Idle (?) interrupt, then do normal flush.
*
* - Frame throttling, NV_fence:
* - Drop marker irq's into command stream ahead of time.
* - Wait on irq's with lock *not held*
* - Check each for termination condition
*
* - Internally in cp_getbuffer, etc:
* - as above, but wait with lock held???
*
* NOTE: These functions are misleadingly named -- the irq's aren't
* tied to dma at all, this is just a hangover from dri prehistory.
*/
irqreturn_t radeon_driver_irq_handler(DRM_IRQ_ARGS)
{
struct drm_device *dev = (struct drm_device *) arg;
drm_radeon_private_t *dev_priv =
(drm_radeon_private_t *) dev->dev_private;
u32 stat;
u32 r500_disp_int;
if ((dev_priv->flags & RADEON_FAMILY_MASK) >= CHIP_R600)
return IRQ_NONE;
/* Only consider the bits we're interested in - others could be used
* outside the DRM
*/
stat = radeon_acknowledge_irqs(dev_priv, &r500_disp_int);
if (!stat)
return IRQ_NONE;
stat &= dev_priv->irq_enable_reg;
/* SW interrupt */
if (stat & RADEON_SW_INT_TEST)
DRM_WAKEUP(&dev_priv->swi_queue);
/* VBLANK interrupt */
if ((dev_priv->flags & RADEON_FAMILY_MASK) >= CHIP_RS600) {
if (r500_disp_int & R500_D1_VBLANK_INTERRUPT)
drm_handle_vblank(dev, 0);
if (r500_disp_int & R500_D2_VBLANK_INTERRUPT)
drm_handle_vblank(dev, 1);
} else {
if (stat & RADEON_CRTC_VBLANK_STAT)
drm_handle_vblank(dev, 0);
if (stat & RADEON_CRTC2_VBLANK_STAT)
drm_handle_vblank(dev, 1);
}
return IRQ_HANDLED;
}
static int radeon_emit_irq(struct drm_device * dev)
{
drm_radeon_private_t *dev_priv = dev->dev_private;
unsigned int ret;
RING_LOCALS;
atomic_inc(&dev_priv->swi_emitted);
ret = atomic_read(&dev_priv->swi_emitted);
BEGIN_RING(4);
OUT_RING_REG(RADEON_LAST_SWI_REG, ret);
OUT_RING_REG(RADEON_GEN_INT_STATUS, RADEON_SW_INT_FIRE);
ADVANCE_RING();
COMMIT_RING();
return ret;
}
static int radeon_wait_irq(struct drm_device * dev, int swi_nr)
{
drm_radeon_private_t *dev_priv =
(drm_radeon_private_t *) dev->dev_private;
int ret = 0;
if (RADEON_READ(RADEON_LAST_SWI_REG) >= swi_nr)
return 0;
dev_priv->stats.boxes |= RADEON_BOX_WAIT_IDLE;
DRM_WAIT_ON(ret, dev_priv->swi_queue, 3 * DRM_HZ,
RADEON_READ(RADEON_LAST_SWI_REG) >= swi_nr);
return ret;
}
u32 radeon_get_vblank_counter(struct drm_device *dev, int crtc)
{
drm_radeon_private_t *dev_priv = dev->dev_private;
if (!dev_priv) {
DRM_ERROR("called with no initialization\n");
return -EINVAL;
}
if (crtc < 0 || crtc > 1) {
DRM_ERROR("Invalid crtc %d\n", crtc);
return -EINVAL;
}
if ((dev_priv->flags & RADEON_FAMILY_MASK) >= CHIP_RS600) {
if (crtc == 0)
return RADEON_READ(R500_D1CRTC_FRAME_COUNT);
else
return RADEON_READ(R500_D2CRTC_FRAME_COUNT);
} else {
if (crtc == 0)
return RADEON_READ(RADEON_CRTC_CRNT_FRAME);
else
return RADEON_READ(RADEON_CRTC2_CRNT_FRAME);
}
}
/* Needs the lock as it touches the ring.
*/
int radeon_irq_emit(struct drm_device *dev, void *data, struct drm_file *file_priv)
{
drm_radeon_private_t *dev_priv = dev->dev_private;
drm_radeon_irq_emit_t *emit = data;
int result;
if (!dev_priv) {
DRM_ERROR("called with no initialization\n");
return -EINVAL;
}
if ((dev_priv->flags & RADEON_FAMILY_MASK) >= CHIP_R600)
return -EINVAL;
LOCK_TEST_WITH_RETURN(dev, file_priv);
result = radeon_emit_irq(dev);
if (DRM_COPY_TO_USER(emit->irq_seq, &result, sizeof(int))) {
DRM_ERROR("copy_to_user\n");
return -EFAULT;
}
return 0;
}
/* Doesn't need the hardware lock.
*/
int radeon_irq_wait(struct drm_device *dev, void *data, struct drm_file *file_priv)
{
drm_radeon_private_t *dev_priv = dev->dev_private;
drm_radeon_irq_wait_t *irqwait = data;
if (!dev_priv) {
DRM_ERROR("called with no initialization\n");
return -EINVAL;
}
if ((dev_priv->flags & RADEON_FAMILY_MASK) >= CHIP_R600)
return -EINVAL;
return radeon_wait_irq(dev, irqwait->irq_seq);
}
/* drm_dma.h hooks
*/
void radeon_driver_irq_preinstall(struct drm_device * dev)
{
drm_radeon_private_t *dev_priv =
(drm_radeon_private_t *) dev->dev_private;
u32 dummy;
if ((dev_priv->flags & RADEON_FAMILY_MASK) >= CHIP_R600)
return;
/* Disable *all* interrupts */
if ((dev_priv->flags & RADEON_FAMILY_MASK) >= CHIP_RS600)
RADEON_WRITE(R500_DxMODE_INT_MASK, 0);
RADEON_WRITE(RADEON_GEN_INT_CNTL, 0);
/* Clear bits if they're already high */
radeon_acknowledge_irqs(dev_priv, &dummy);
}
int radeon_driver_irq_postinstall(struct drm_device *dev)
{
drm_radeon_private_t *dev_priv =
(drm_radeon_private_t *) dev->dev_private;
atomic_set(&dev_priv->swi_emitted, 0);
DRM_INIT_WAITQUEUE(&dev_priv->swi_queue);
dev->max_vblank_count = 0x001fffff;
if ((dev_priv->flags & RADEON_FAMILY_MASK) >= CHIP_R600)
return 0;
radeon_irq_set_state(dev, RADEON_SW_INT_ENABLE, 1);
return 0;
}
void radeon_driver_irq_uninstall(struct drm_device * dev)
{
drm_radeon_private_t *dev_priv =
(drm_radeon_private_t *) dev->dev_private;
if (!dev_priv)
return;
if ((dev_priv->flags & RADEON_FAMILY_MASK) >= CHIP_R600)
return;
if ((dev_priv->flags & RADEON_FAMILY_MASK) >= CHIP_RS600)
RADEON_WRITE(R500_DxMODE_INT_MASK, 0);
/* Disable *all* interrupts */
RADEON_WRITE(RADEON_GEN_INT_CNTL, 0);
}
int radeon_vblank_crtc_get(struct drm_device *dev)
{
drm_radeon_private_t *dev_priv = (drm_radeon_private_t *) dev->dev_private;
return dev_priv->vblank_crtc;
}
int radeon_vblank_crtc_set(struct drm_device *dev, int64_t value)
{
drm_radeon_private_t *dev_priv = (drm_radeon_private_t *) dev->dev_private;
if (value & ~(DRM_RADEON_VBLANK_CRTC1 | DRM_RADEON_VBLANK_CRTC2)) {
DRM_ERROR("called with invalid crtc 0x%x\n", (unsigned int)value);
return -EINVAL;
}
dev_priv->vblank_crtc = (unsigned int)value;
return 0;
}
| gpl-2.0 |
MaccKing/CBx | arch/sparc/kernel/perf_event.c | 2910 | 36518 | /* Performance event support for sparc64.
*
* Copyright (C) 2009, 2010 David S. Miller <davem@davemloft.net>
*
* This code is based almost entirely upon the x86 perf event
* code, which is:
*
* Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
* Copyright (C) 2008-2009 Red Hat, Inc., Ingo Molnar
* Copyright (C) 2009 Jaswinder Singh Rajput
* Copyright (C) 2009 Advanced Micro Devices, Inc., Robert Richter
* Copyright (C) 2008-2009 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com>
*/
#include <linux/perf_event.h>
#include <linux/kprobes.h>
#include <linux/ftrace.h>
#include <linux/kernel.h>
#include <linux/kdebug.h>
#include <linux/mutex.h>
#include <asm/stacktrace.h>
#include <asm/cpudata.h>
#include <asm/uaccess.h>
#include <linux/atomic.h>
#include <asm/nmi.h>
#include <asm/pcr.h>
#include <asm/perfctr.h>
#include <asm/cacheflush.h>
#include "kernel.h"
#include "kstack.h"
/* Sparc64 chips have two performance counters, 32-bits each, with
* overflow interrupts generated on transition from 0xffffffff to 0.
* The counters are accessed in one go using a 64-bit register.
*
* Both counters are controlled using a single control register. The
* only way to stop all sampling is to clear all of the context (user,
* supervisor, hypervisor) sampling enable bits. But these bits apply
* to both counters, thus the two counters can't be enabled/disabled
* individually.
*
* The control register has two event fields, one for each of the two
* counters. It's thus nearly impossible to have one counter going
* while keeping the other one stopped. Therefore it is possible to
* get overflow interrupts for counters not currently "in use" and
* that condition must be checked in the overflow interrupt handler.
*
* So we use a hack, in that we program inactive counters with the
* "sw_count0" and "sw_count1" events. These count how many times
* the instruction "sethi %hi(0xfc000), %g0" is executed. It's an
* unusual way to encode a NOP and therefore will not trigger in
* normal code.
*/
#define MAX_HWEVENTS 2
#define MAX_PERIOD ((1UL << 32) - 1)
#define PIC_UPPER_INDEX 0
#define PIC_LOWER_INDEX 1
#define PIC_NO_INDEX -1
struct cpu_hw_events {
/* Number of events currently scheduled onto this cpu.
* This tells how many entries in the arrays below
* are valid.
*/
int n_events;
/* Number of new events added since the last hw_perf_disable().
* This works because the perf event layer always adds new
* events inside of a perf_{disable,enable}() sequence.
*/
int n_added;
/* Array of events current scheduled on this cpu. */
struct perf_event *event[MAX_HWEVENTS];
/* Array of encoded longs, specifying the %pcr register
* encoding and the mask of PIC counters this even can
* be scheduled on. See perf_event_encode() et al.
*/
unsigned long events[MAX_HWEVENTS];
/* The current counter index assigned to an event. When the
* event hasn't been programmed into the cpu yet, this will
* hold PIC_NO_INDEX. The event->hw.idx value tells us where
* we ought to schedule the event.
*/
int current_idx[MAX_HWEVENTS];
/* Software copy of %pcr register on this cpu. */
u64 pcr;
/* Enabled/disable state. */
int enabled;
unsigned int group_flag;
};
DEFINE_PER_CPU(struct cpu_hw_events, cpu_hw_events) = { .enabled = 1, };
/* An event map describes the characteristics of a performance
* counter event. In particular it gives the encoding as well as
* a mask telling which counters the event can be measured on.
*/
struct perf_event_map {
u16 encoding;
u8 pic_mask;
#define PIC_NONE 0x00
#define PIC_UPPER 0x01
#define PIC_LOWER 0x02
};
/* Encode a perf_event_map entry into a long. */
static unsigned long perf_event_encode(const struct perf_event_map *pmap)
{
return ((unsigned long) pmap->encoding << 16) | pmap->pic_mask;
}
static u8 perf_event_get_msk(unsigned long val)
{
return val & 0xff;
}
static u64 perf_event_get_enc(unsigned long val)
{
return val >> 16;
}
#define C(x) PERF_COUNT_HW_CACHE_##x
#define CACHE_OP_UNSUPPORTED 0xfffe
#define CACHE_OP_NONSENSE 0xffff
typedef struct perf_event_map cache_map_t
[PERF_COUNT_HW_CACHE_MAX]
[PERF_COUNT_HW_CACHE_OP_MAX]
[PERF_COUNT_HW_CACHE_RESULT_MAX];
struct sparc_pmu {
const struct perf_event_map *(*event_map)(int);
const cache_map_t *cache_map;
int max_events;
int upper_shift;
int lower_shift;
int event_mask;
int hv_bit;
int irq_bit;
int upper_nop;
int lower_nop;
};
static const struct perf_event_map ultra3_perfmon_event_map[] = {
[PERF_COUNT_HW_CPU_CYCLES] = { 0x0000, PIC_UPPER | PIC_LOWER },
[PERF_COUNT_HW_INSTRUCTIONS] = { 0x0001, PIC_UPPER | PIC_LOWER },
[PERF_COUNT_HW_CACHE_REFERENCES] = { 0x0009, PIC_LOWER },
[PERF_COUNT_HW_CACHE_MISSES] = { 0x0009, PIC_UPPER },
};
static const struct perf_event_map *ultra3_event_map(int event_id)
{
return &ultra3_perfmon_event_map[event_id];
}
static const cache_map_t ultra3_cache_map = {
[C(L1D)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { 0x09, PIC_LOWER, },
[C(RESULT_MISS)] = { 0x09, PIC_UPPER, },
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = { 0x0a, PIC_LOWER },
[C(RESULT_MISS)] = { 0x0a, PIC_UPPER },
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { CACHE_OP_UNSUPPORTED },
},
},
[C(L1I)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { 0x09, PIC_LOWER, },
[C(RESULT_MISS)] = { 0x09, PIC_UPPER, },
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_NONSENSE },
[ C(RESULT_MISS) ] = { CACHE_OP_NONSENSE },
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
},
[C(LL)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { 0x0c, PIC_LOWER, },
[C(RESULT_MISS)] = { 0x0c, PIC_UPPER, },
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = { 0x0c, PIC_LOWER },
[C(RESULT_MISS)] = { 0x0c, PIC_UPPER },
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { CACHE_OP_UNSUPPORTED },
},
},
[C(DTLB)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { 0x12, PIC_UPPER, },
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
},
[C(ITLB)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { 0x11, PIC_UPPER, },
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
},
[C(BPU)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { CACHE_OP_UNSUPPORTED },
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
},
[C(NODE)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
},
};
static const struct sparc_pmu ultra3_pmu = {
.event_map = ultra3_event_map,
.cache_map = &ultra3_cache_map,
.max_events = ARRAY_SIZE(ultra3_perfmon_event_map),
.upper_shift = 11,
.lower_shift = 4,
.event_mask = 0x3f,
.upper_nop = 0x1c,
.lower_nop = 0x14,
};
/* Niagara1 is very limited. The upper PIC is hard-locked to count
* only instructions, so it is free running which creates all kinds of
* problems. Some hardware designs make one wonder if the creator
* even looked at how this stuff gets used by software.
*/
static const struct perf_event_map niagara1_perfmon_event_map[] = {
[PERF_COUNT_HW_CPU_CYCLES] = { 0x00, PIC_UPPER },
[PERF_COUNT_HW_INSTRUCTIONS] = { 0x00, PIC_UPPER },
[PERF_COUNT_HW_CACHE_REFERENCES] = { 0, PIC_NONE },
[PERF_COUNT_HW_CACHE_MISSES] = { 0x03, PIC_LOWER },
};
static const struct perf_event_map *niagara1_event_map(int event_id)
{
return &niagara1_perfmon_event_map[event_id];
}
static const cache_map_t niagara1_cache_map = {
[C(L1D)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { 0x03, PIC_LOWER, },
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { 0x03, PIC_LOWER, },
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { CACHE_OP_UNSUPPORTED },
},
},
[C(L1I)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { 0x00, PIC_UPPER },
[C(RESULT_MISS)] = { 0x02, PIC_LOWER, },
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_NONSENSE },
[ C(RESULT_MISS) ] = { CACHE_OP_NONSENSE },
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
},
[C(LL)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { 0x07, PIC_LOWER, },
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { 0x07, PIC_LOWER, },
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { CACHE_OP_UNSUPPORTED },
},
},
[C(DTLB)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { 0x05, PIC_LOWER, },
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
},
[C(ITLB)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { 0x04, PIC_LOWER, },
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
},
[C(BPU)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { CACHE_OP_UNSUPPORTED },
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
},
[C(NODE)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
},
};
static const struct sparc_pmu niagara1_pmu = {
.event_map = niagara1_event_map,
.cache_map = &niagara1_cache_map,
.max_events = ARRAY_SIZE(niagara1_perfmon_event_map),
.upper_shift = 0,
.lower_shift = 4,
.event_mask = 0x7,
.upper_nop = 0x0,
.lower_nop = 0x0,
};
static const struct perf_event_map niagara2_perfmon_event_map[] = {
[PERF_COUNT_HW_CPU_CYCLES] = { 0x02ff, PIC_UPPER | PIC_LOWER },
[PERF_COUNT_HW_INSTRUCTIONS] = { 0x02ff, PIC_UPPER | PIC_LOWER },
[PERF_COUNT_HW_CACHE_REFERENCES] = { 0x0208, PIC_UPPER | PIC_LOWER },
[PERF_COUNT_HW_CACHE_MISSES] = { 0x0302, PIC_UPPER | PIC_LOWER },
[PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = { 0x0201, PIC_UPPER | PIC_LOWER },
[PERF_COUNT_HW_BRANCH_MISSES] = { 0x0202, PIC_UPPER | PIC_LOWER },
};
static const struct perf_event_map *niagara2_event_map(int event_id)
{
return &niagara2_perfmon_event_map[event_id];
}
static const cache_map_t niagara2_cache_map = {
[C(L1D)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { 0x0208, PIC_UPPER | PIC_LOWER, },
[C(RESULT_MISS)] = { 0x0302, PIC_UPPER | PIC_LOWER, },
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = { 0x0210, PIC_UPPER | PIC_LOWER, },
[C(RESULT_MISS)] = { 0x0302, PIC_UPPER | PIC_LOWER, },
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { CACHE_OP_UNSUPPORTED },
},
},
[C(L1I)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { 0x02ff, PIC_UPPER | PIC_LOWER, },
[C(RESULT_MISS)] = { 0x0301, PIC_UPPER | PIC_LOWER, },
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_NONSENSE },
[ C(RESULT_MISS) ] = { CACHE_OP_NONSENSE },
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
},
[C(LL)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { 0x0208, PIC_UPPER | PIC_LOWER, },
[C(RESULT_MISS)] = { 0x0330, PIC_UPPER | PIC_LOWER, },
},
[C(OP_WRITE)] = {
[C(RESULT_ACCESS)] = { 0x0210, PIC_UPPER | PIC_LOWER, },
[C(RESULT_MISS)] = { 0x0320, PIC_UPPER | PIC_LOWER, },
},
[C(OP_PREFETCH)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { CACHE_OP_UNSUPPORTED },
},
},
[C(DTLB)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { 0x0b08, PIC_UPPER | PIC_LOWER, },
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
},
[C(ITLB)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { 0xb04, PIC_UPPER | PIC_LOWER, },
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
},
[C(BPU)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS)] = { CACHE_OP_UNSUPPORTED },
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
},
[C(NODE)] = {
[C(OP_READ)] = {
[C(RESULT_ACCESS)] = { CACHE_OP_UNSUPPORTED },
[C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = { CACHE_OP_UNSUPPORTED },
[ C(RESULT_MISS) ] = { CACHE_OP_UNSUPPORTED },
},
},
};
static const struct sparc_pmu niagara2_pmu = {
.event_map = niagara2_event_map,
.cache_map = &niagara2_cache_map,
.max_events = ARRAY_SIZE(niagara2_perfmon_event_map),
.upper_shift = 19,
.lower_shift = 6,
.event_mask = 0xfff,
.hv_bit = 0x8,
.irq_bit = 0x30,
.upper_nop = 0x220,
.lower_nop = 0x220,
};
static const struct sparc_pmu *sparc_pmu __read_mostly;
static u64 event_encoding(u64 event_id, int idx)
{
if (idx == PIC_UPPER_INDEX)
event_id <<= sparc_pmu->upper_shift;
else
event_id <<= sparc_pmu->lower_shift;
return event_id;
}
static u64 mask_for_index(int idx)
{
return event_encoding(sparc_pmu->event_mask, idx);
}
static u64 nop_for_index(int idx)
{
return event_encoding(idx == PIC_UPPER_INDEX ?
sparc_pmu->upper_nop :
sparc_pmu->lower_nop, idx);
}
static inline void sparc_pmu_enable_event(struct cpu_hw_events *cpuc, struct hw_perf_event *hwc, int idx)
{
u64 val, mask = mask_for_index(idx);
val = cpuc->pcr;
val &= ~mask;
val |= hwc->config;
cpuc->pcr = val;
pcr_ops->write(cpuc->pcr);
}
static inline void sparc_pmu_disable_event(struct cpu_hw_events *cpuc, struct hw_perf_event *hwc, int idx)
{
u64 mask = mask_for_index(idx);
u64 nop = nop_for_index(idx);
u64 val;
val = cpuc->pcr;
val &= ~mask;
val |= nop;
cpuc->pcr = val;
pcr_ops->write(cpuc->pcr);
}
static u32 read_pmc(int idx)
{
u64 val;
read_pic(val);
if (idx == PIC_UPPER_INDEX)
val >>= 32;
return val & 0xffffffff;
}
static void write_pmc(int idx, u64 val)
{
u64 shift, mask, pic;
shift = 0;
if (idx == PIC_UPPER_INDEX)
shift = 32;
mask = ((u64) 0xffffffff) << shift;
val <<= shift;
read_pic(pic);
pic &= ~mask;
pic |= val;
write_pic(pic);
}
static u64 sparc_perf_event_update(struct perf_event *event,
struct hw_perf_event *hwc, int idx)
{
int shift = 64 - 32;
u64 prev_raw_count, new_raw_count;
s64 delta;
again:
prev_raw_count = local64_read(&hwc->prev_count);
new_raw_count = read_pmc(idx);
if (local64_cmpxchg(&hwc->prev_count, prev_raw_count,
new_raw_count) != prev_raw_count)
goto again;
delta = (new_raw_count << shift) - (prev_raw_count << shift);
delta >>= shift;
local64_add(delta, &event->count);
local64_sub(delta, &hwc->period_left);
return new_raw_count;
}
static int sparc_perf_event_set_period(struct perf_event *event,
struct hw_perf_event *hwc, int idx)
{
s64 left = local64_read(&hwc->period_left);
s64 period = hwc->sample_period;
int ret = 0;
if (unlikely(left <= -period)) {
left = period;
local64_set(&hwc->period_left, left);
hwc->last_period = period;
ret = 1;
}
if (unlikely(left <= 0)) {
left += period;
local64_set(&hwc->period_left, left);
hwc->last_period = period;
ret = 1;
}
if (left > MAX_PERIOD)
left = MAX_PERIOD;
local64_set(&hwc->prev_count, (u64)-left);
write_pmc(idx, (u64)(-left) & 0xffffffff);
perf_event_update_userpage(event);
return ret;
}
/* If performance event entries have been added, move existing
* events around (if necessary) and then assign new entries to
* counters.
*/
static u64 maybe_change_configuration(struct cpu_hw_events *cpuc, u64 pcr)
{
int i;
if (!cpuc->n_added)
goto out;
/* Read in the counters which are moving. */
for (i = 0; i < cpuc->n_events; i++) {
struct perf_event *cp = cpuc->event[i];
if (cpuc->current_idx[i] != PIC_NO_INDEX &&
cpuc->current_idx[i] != cp->hw.idx) {
sparc_perf_event_update(cp, &cp->hw,
cpuc->current_idx[i]);
cpuc->current_idx[i] = PIC_NO_INDEX;
}
}
/* Assign to counters all unassigned events. */
for (i = 0; i < cpuc->n_events; i++) {
struct perf_event *cp = cpuc->event[i];
struct hw_perf_event *hwc = &cp->hw;
int idx = hwc->idx;
u64 enc;
if (cpuc->current_idx[i] != PIC_NO_INDEX)
continue;
sparc_perf_event_set_period(cp, hwc, idx);
cpuc->current_idx[i] = idx;
enc = perf_event_get_enc(cpuc->events[i]);
pcr &= ~mask_for_index(idx);
if (hwc->state & PERF_HES_STOPPED)
pcr |= nop_for_index(idx);
else
pcr |= event_encoding(enc, idx);
}
out:
return pcr;
}
static void sparc_pmu_enable(struct pmu *pmu)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
u64 pcr;
if (cpuc->enabled)
return;
cpuc->enabled = 1;
barrier();
pcr = cpuc->pcr;
if (!cpuc->n_events) {
pcr = 0;
} else {
pcr = maybe_change_configuration(cpuc, pcr);
/* We require that all of the events have the same
* configuration, so just fetch the settings from the
* first entry.
*/
cpuc->pcr = pcr | cpuc->event[0]->hw.config_base;
}
pcr_ops->write(cpuc->pcr);
}
static void sparc_pmu_disable(struct pmu *pmu)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
u64 val;
if (!cpuc->enabled)
return;
cpuc->enabled = 0;
cpuc->n_added = 0;
val = cpuc->pcr;
val &= ~(PCR_UTRACE | PCR_STRACE |
sparc_pmu->hv_bit | sparc_pmu->irq_bit);
cpuc->pcr = val;
pcr_ops->write(cpuc->pcr);
}
static int active_event_index(struct cpu_hw_events *cpuc,
struct perf_event *event)
{
int i;
for (i = 0; i < cpuc->n_events; i++) {
if (cpuc->event[i] == event)
break;
}
BUG_ON(i == cpuc->n_events);
return cpuc->current_idx[i];
}
static void sparc_pmu_start(struct perf_event *event, int flags)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
int idx = active_event_index(cpuc, event);
if (flags & PERF_EF_RELOAD) {
WARN_ON_ONCE(!(event->hw.state & PERF_HES_UPTODATE));
sparc_perf_event_set_period(event, &event->hw, idx);
}
event->hw.state = 0;
sparc_pmu_enable_event(cpuc, &event->hw, idx);
}
static void sparc_pmu_stop(struct perf_event *event, int flags)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
int idx = active_event_index(cpuc, event);
if (!(event->hw.state & PERF_HES_STOPPED)) {
sparc_pmu_disable_event(cpuc, &event->hw, idx);
event->hw.state |= PERF_HES_STOPPED;
}
if (!(event->hw.state & PERF_HES_UPTODATE) && (flags & PERF_EF_UPDATE)) {
sparc_perf_event_update(event, &event->hw, idx);
event->hw.state |= PERF_HES_UPTODATE;
}
}
static void sparc_pmu_del(struct perf_event *event, int _flags)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
unsigned long flags;
int i;
local_irq_save(flags);
perf_pmu_disable(event->pmu);
for (i = 0; i < cpuc->n_events; i++) {
if (event == cpuc->event[i]) {
/* Absorb the final count and turn off the
* event.
*/
sparc_pmu_stop(event, PERF_EF_UPDATE);
/* Shift remaining entries down into
* the existing slot.
*/
while (++i < cpuc->n_events) {
cpuc->event[i - 1] = cpuc->event[i];
cpuc->events[i - 1] = cpuc->events[i];
cpuc->current_idx[i - 1] =
cpuc->current_idx[i];
}
perf_event_update_userpage(event);
cpuc->n_events--;
break;
}
}
perf_pmu_enable(event->pmu);
local_irq_restore(flags);
}
static void sparc_pmu_read(struct perf_event *event)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
int idx = active_event_index(cpuc, event);
struct hw_perf_event *hwc = &event->hw;
sparc_perf_event_update(event, hwc, idx);
}
static atomic_t active_events = ATOMIC_INIT(0);
static DEFINE_MUTEX(pmc_grab_mutex);
static void perf_stop_nmi_watchdog(void *unused)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
stop_nmi_watchdog(NULL);
cpuc->pcr = pcr_ops->read();
}
void perf_event_grab_pmc(void)
{
if (atomic_inc_not_zero(&active_events))
return;
mutex_lock(&pmc_grab_mutex);
if (atomic_read(&active_events) == 0) {
if (atomic_read(&nmi_active) > 0) {
on_each_cpu(perf_stop_nmi_watchdog, NULL, 1);
BUG_ON(atomic_read(&nmi_active) != 0);
}
atomic_inc(&active_events);
}
mutex_unlock(&pmc_grab_mutex);
}
void perf_event_release_pmc(void)
{
if (atomic_dec_and_mutex_lock(&active_events, &pmc_grab_mutex)) {
if (atomic_read(&nmi_active) == 0)
on_each_cpu(start_nmi_watchdog, NULL, 1);
mutex_unlock(&pmc_grab_mutex);
}
}
static const struct perf_event_map *sparc_map_cache_event(u64 config)
{
unsigned int cache_type, cache_op, cache_result;
const struct perf_event_map *pmap;
if (!sparc_pmu->cache_map)
return ERR_PTR(-ENOENT);
cache_type = (config >> 0) & 0xff;
if (cache_type >= PERF_COUNT_HW_CACHE_MAX)
return ERR_PTR(-EINVAL);
cache_op = (config >> 8) & 0xff;
if (cache_op >= PERF_COUNT_HW_CACHE_OP_MAX)
return ERR_PTR(-EINVAL);
cache_result = (config >> 16) & 0xff;
if (cache_result >= PERF_COUNT_HW_CACHE_RESULT_MAX)
return ERR_PTR(-EINVAL);
pmap = &((*sparc_pmu->cache_map)[cache_type][cache_op][cache_result]);
if (pmap->encoding == CACHE_OP_UNSUPPORTED)
return ERR_PTR(-ENOENT);
if (pmap->encoding == CACHE_OP_NONSENSE)
return ERR_PTR(-EINVAL);
return pmap;
}
static void hw_perf_event_destroy(struct perf_event *event)
{
perf_event_release_pmc();
}
/* Make sure all events can be scheduled into the hardware at
* the same time. This is simplified by the fact that we only
* need to support 2 simultaneous HW events.
*
* As a side effect, the evts[]->hw.idx values will be assigned
* on success. These are pending indexes. When the events are
* actually programmed into the chip, these values will propagate
* to the per-cpu cpuc->current_idx[] slots, see the code in
* maybe_change_configuration() for details.
*/
static int sparc_check_constraints(struct perf_event **evts,
unsigned long *events, int n_ev)
{
u8 msk0 = 0, msk1 = 0;
int idx0 = 0;
/* This case is possible when we are invoked from
* hw_perf_group_sched_in().
*/
if (!n_ev)
return 0;
if (n_ev > MAX_HWEVENTS)
return -1;
msk0 = perf_event_get_msk(events[0]);
if (n_ev == 1) {
if (msk0 & PIC_LOWER)
idx0 = 1;
goto success;
}
BUG_ON(n_ev != 2);
msk1 = perf_event_get_msk(events[1]);
/* If both events can go on any counter, OK. */
if (msk0 == (PIC_UPPER | PIC_LOWER) &&
msk1 == (PIC_UPPER | PIC_LOWER))
goto success;
/* If one event is limited to a specific counter,
* and the other can go on both, OK.
*/
if ((msk0 == PIC_UPPER || msk0 == PIC_LOWER) &&
msk1 == (PIC_UPPER | PIC_LOWER)) {
if (msk0 & PIC_LOWER)
idx0 = 1;
goto success;
}
if ((msk1 == PIC_UPPER || msk1 == PIC_LOWER) &&
msk0 == (PIC_UPPER | PIC_LOWER)) {
if (msk1 & PIC_UPPER)
idx0 = 1;
goto success;
}
/* If the events are fixed to different counters, OK. */
if ((msk0 == PIC_UPPER && msk1 == PIC_LOWER) ||
(msk0 == PIC_LOWER && msk1 == PIC_UPPER)) {
if (msk0 & PIC_LOWER)
idx0 = 1;
goto success;
}
/* Otherwise, there is a conflict. */
return -1;
success:
evts[0]->hw.idx = idx0;
if (n_ev == 2)
evts[1]->hw.idx = idx0 ^ 1;
return 0;
}
static int check_excludes(struct perf_event **evts, int n_prev, int n_new)
{
int eu = 0, ek = 0, eh = 0;
struct perf_event *event;
int i, n, first;
n = n_prev + n_new;
if (n <= 1)
return 0;
first = 1;
for (i = 0; i < n; i++) {
event = evts[i];
if (first) {
eu = event->attr.exclude_user;
ek = event->attr.exclude_kernel;
eh = event->attr.exclude_hv;
first = 0;
} else if (event->attr.exclude_user != eu ||
event->attr.exclude_kernel != ek ||
event->attr.exclude_hv != eh) {
return -EAGAIN;
}
}
return 0;
}
static int collect_events(struct perf_event *group, int max_count,
struct perf_event *evts[], unsigned long *events,
int *current_idx)
{
struct perf_event *event;
int n = 0;
if (!is_software_event(group)) {
if (n >= max_count)
return -1;
evts[n] = group;
events[n] = group->hw.event_base;
current_idx[n++] = PIC_NO_INDEX;
}
list_for_each_entry(event, &group->sibling_list, group_entry) {
if (!is_software_event(event) &&
event->state != PERF_EVENT_STATE_OFF) {
if (n >= max_count)
return -1;
evts[n] = event;
events[n] = event->hw.event_base;
current_idx[n++] = PIC_NO_INDEX;
}
}
return n;
}
static int sparc_pmu_add(struct perf_event *event, int ef_flags)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
int n0, ret = -EAGAIN;
unsigned long flags;
local_irq_save(flags);
perf_pmu_disable(event->pmu);
n0 = cpuc->n_events;
if (n0 >= MAX_HWEVENTS)
goto out;
cpuc->event[n0] = event;
cpuc->events[n0] = event->hw.event_base;
cpuc->current_idx[n0] = PIC_NO_INDEX;
event->hw.state = PERF_HES_UPTODATE;
if (!(ef_flags & PERF_EF_START))
event->hw.state |= PERF_HES_STOPPED;
/*
* If group events scheduling transaction was started,
* skip the schedulability test here, it will be performed
* at commit time(->commit_txn) as a whole
*/
if (cpuc->group_flag & PERF_EVENT_TXN)
goto nocheck;
if (check_excludes(cpuc->event, n0, 1))
goto out;
if (sparc_check_constraints(cpuc->event, cpuc->events, n0 + 1))
goto out;
nocheck:
cpuc->n_events++;
cpuc->n_added++;
ret = 0;
out:
perf_pmu_enable(event->pmu);
local_irq_restore(flags);
return ret;
}
static int sparc_pmu_event_init(struct perf_event *event)
{
struct perf_event_attr *attr = &event->attr;
struct perf_event *evts[MAX_HWEVENTS];
struct hw_perf_event *hwc = &event->hw;
unsigned long events[MAX_HWEVENTS];
int current_idx_dmy[MAX_HWEVENTS];
const struct perf_event_map *pmap;
int n;
if (atomic_read(&nmi_active) < 0)
return -ENODEV;
/* does not support taken branch sampling */
if (has_branch_stack(event))
return -EOPNOTSUPP;
switch (attr->type) {
case PERF_TYPE_HARDWARE:
if (attr->config >= sparc_pmu->max_events)
return -EINVAL;
pmap = sparc_pmu->event_map(attr->config);
break;
case PERF_TYPE_HW_CACHE:
pmap = sparc_map_cache_event(attr->config);
if (IS_ERR(pmap))
return PTR_ERR(pmap);
break;
case PERF_TYPE_RAW:
pmap = NULL;
break;
default:
return -ENOENT;
}
if (pmap) {
hwc->event_base = perf_event_encode(pmap);
} else {
/*
* User gives us "(encoding << 16) | pic_mask" for
* PERF_TYPE_RAW events.
*/
hwc->event_base = attr->config;
}
/* We save the enable bits in the config_base. */
hwc->config_base = sparc_pmu->irq_bit;
if (!attr->exclude_user)
hwc->config_base |= PCR_UTRACE;
if (!attr->exclude_kernel)
hwc->config_base |= PCR_STRACE;
if (!attr->exclude_hv)
hwc->config_base |= sparc_pmu->hv_bit;
n = 0;
if (event->group_leader != event) {
n = collect_events(event->group_leader,
MAX_HWEVENTS - 1,
evts, events, current_idx_dmy);
if (n < 0)
return -EINVAL;
}
events[n] = hwc->event_base;
evts[n] = event;
if (check_excludes(evts, n, 1))
return -EINVAL;
if (sparc_check_constraints(evts, events, n + 1))
return -EINVAL;
hwc->idx = PIC_NO_INDEX;
/* Try to do all error checking before this point, as unwinding
* state after grabbing the PMC is difficult.
*/
perf_event_grab_pmc();
event->destroy = hw_perf_event_destroy;
if (!hwc->sample_period) {
hwc->sample_period = MAX_PERIOD;
hwc->last_period = hwc->sample_period;
local64_set(&hwc->period_left, hwc->sample_period);
}
return 0;
}
/*
* Start group events scheduling transaction
* Set the flag to make pmu::enable() not perform the
* schedulability test, it will be performed at commit time
*/
static void sparc_pmu_start_txn(struct pmu *pmu)
{
struct cpu_hw_events *cpuhw = &__get_cpu_var(cpu_hw_events);
perf_pmu_disable(pmu);
cpuhw->group_flag |= PERF_EVENT_TXN;
}
/*
* Stop group events scheduling transaction
* Clear the flag and pmu::enable() will perform the
* schedulability test.
*/
static void sparc_pmu_cancel_txn(struct pmu *pmu)
{
struct cpu_hw_events *cpuhw = &__get_cpu_var(cpu_hw_events);
cpuhw->group_flag &= ~PERF_EVENT_TXN;
perf_pmu_enable(pmu);
}
/*
* Commit group events scheduling transaction
* Perform the group schedulability test as a whole
* Return 0 if success
*/
static int sparc_pmu_commit_txn(struct pmu *pmu)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
int n;
if (!sparc_pmu)
return -EINVAL;
cpuc = &__get_cpu_var(cpu_hw_events);
n = cpuc->n_events;
if (check_excludes(cpuc->event, 0, n))
return -EINVAL;
if (sparc_check_constraints(cpuc->event, cpuc->events, n))
return -EAGAIN;
cpuc->group_flag &= ~PERF_EVENT_TXN;
perf_pmu_enable(pmu);
return 0;
}
static struct pmu pmu = {
.pmu_enable = sparc_pmu_enable,
.pmu_disable = sparc_pmu_disable,
.event_init = sparc_pmu_event_init,
.add = sparc_pmu_add,
.del = sparc_pmu_del,
.start = sparc_pmu_start,
.stop = sparc_pmu_stop,
.read = sparc_pmu_read,
.start_txn = sparc_pmu_start_txn,
.cancel_txn = sparc_pmu_cancel_txn,
.commit_txn = sparc_pmu_commit_txn,
};
void perf_event_print_debug(void)
{
unsigned long flags;
u64 pcr, pic;
int cpu;
if (!sparc_pmu)
return;
local_irq_save(flags);
cpu = smp_processor_id();
pcr = pcr_ops->read();
read_pic(pic);
pr_info("\n");
pr_info("CPU#%d: PCR[%016llx] PIC[%016llx]\n",
cpu, pcr, pic);
local_irq_restore(flags);
}
static int __kprobes perf_event_nmi_handler(struct notifier_block *self,
unsigned long cmd, void *__args)
{
struct die_args *args = __args;
struct perf_sample_data data;
struct cpu_hw_events *cpuc;
struct pt_regs *regs;
int i;
if (!atomic_read(&active_events))
return NOTIFY_DONE;
switch (cmd) {
case DIE_NMI:
break;
default:
return NOTIFY_DONE;
}
regs = args->regs;
perf_sample_data_init(&data, 0);
cpuc = &__get_cpu_var(cpu_hw_events);
/* If the PMU has the TOE IRQ enable bits, we need to do a
* dummy write to the %pcr to clear the overflow bits and thus
* the interrupt.
*
* Do this before we peek at the counters to determine
* overflow so we don't lose any events.
*/
if (sparc_pmu->irq_bit)
pcr_ops->write(cpuc->pcr);
for (i = 0; i < cpuc->n_events; i++) {
struct perf_event *event = cpuc->event[i];
int idx = cpuc->current_idx[i];
struct hw_perf_event *hwc;
u64 val;
hwc = &event->hw;
val = sparc_perf_event_update(event, hwc, idx);
if (val & (1ULL << 31))
continue;
data.period = event->hw.last_period;
if (!sparc_perf_event_set_period(event, hwc, idx))
continue;
if (perf_event_overflow(event, &data, regs))
sparc_pmu_stop(event, 0);
}
return NOTIFY_STOP;
}
static __read_mostly struct notifier_block perf_event_nmi_notifier = {
.notifier_call = perf_event_nmi_handler,
};
static bool __init supported_pmu(void)
{
if (!strcmp(sparc_pmu_type, "ultra3") ||
!strcmp(sparc_pmu_type, "ultra3+") ||
!strcmp(sparc_pmu_type, "ultra3i") ||
!strcmp(sparc_pmu_type, "ultra4+")) {
sparc_pmu = &ultra3_pmu;
return true;
}
if (!strcmp(sparc_pmu_type, "niagara")) {
sparc_pmu = &niagara1_pmu;
return true;
}
if (!strcmp(sparc_pmu_type, "niagara2") ||
!strcmp(sparc_pmu_type, "niagara3")) {
sparc_pmu = &niagara2_pmu;
return true;
}
return false;
}
int __init init_hw_perf_events(void)
{
pr_info("Performance events: ");
if (!supported_pmu()) {
pr_cont("No support for PMU type '%s'\n", sparc_pmu_type);
return 0;
}
pr_cont("Supported PMU type is '%s'\n", sparc_pmu_type);
perf_pmu_register(&pmu, "cpu", PERF_TYPE_RAW);
register_die_notifier(&perf_event_nmi_notifier);
return 0;
}
early_initcall(init_hw_perf_events);
void perf_callchain_kernel(struct perf_callchain_entry *entry,
struct pt_regs *regs)
{
unsigned long ksp, fp;
#ifdef CONFIG_FUNCTION_GRAPH_TRACER
int graph = 0;
#endif
stack_trace_flush();
perf_callchain_store(entry, regs->tpc);
ksp = regs->u_regs[UREG_I6];
fp = ksp + STACK_BIAS;
do {
struct sparc_stackf *sf;
struct pt_regs *regs;
unsigned long pc;
if (!kstack_valid(current_thread_info(), fp))
break;
sf = (struct sparc_stackf *) fp;
regs = (struct pt_regs *) (sf + 1);
if (kstack_is_trap_frame(current_thread_info(), regs)) {
if (user_mode(regs))
break;
pc = regs->tpc;
fp = regs->u_regs[UREG_I6] + STACK_BIAS;
} else {
pc = sf->callers_pc;
fp = (unsigned long)sf->fp + STACK_BIAS;
}
perf_callchain_store(entry, pc);
#ifdef CONFIG_FUNCTION_GRAPH_TRACER
if ((pc + 8UL) == (unsigned long) &return_to_handler) {
int index = current->curr_ret_stack;
if (current->ret_stack && index >= graph) {
pc = current->ret_stack[index - graph].ret;
perf_callchain_store(entry, pc);
graph++;
}
}
#endif
} while (entry->nr < PERF_MAX_STACK_DEPTH);
}
static void perf_callchain_user_64(struct perf_callchain_entry *entry,
struct pt_regs *regs)
{
unsigned long ufp;
perf_callchain_store(entry, regs->tpc);
ufp = regs->u_regs[UREG_I6] + STACK_BIAS;
do {
struct sparc_stackf *usf, sf;
unsigned long pc;
usf = (struct sparc_stackf *) ufp;
if (__copy_from_user_inatomic(&sf, usf, sizeof(sf)))
break;
pc = sf.callers_pc;
ufp = (unsigned long)sf.fp + STACK_BIAS;
perf_callchain_store(entry, pc);
} while (entry->nr < PERF_MAX_STACK_DEPTH);
}
static void perf_callchain_user_32(struct perf_callchain_entry *entry,
struct pt_regs *regs)
{
unsigned long ufp;
perf_callchain_store(entry, regs->tpc);
ufp = regs->u_regs[UREG_I6] & 0xffffffffUL;
do {
struct sparc_stackf32 *usf, sf;
unsigned long pc;
usf = (struct sparc_stackf32 *) ufp;
if (__copy_from_user_inatomic(&sf, usf, sizeof(sf)))
break;
pc = sf.callers_pc;
ufp = (unsigned long)sf.fp;
perf_callchain_store(entry, pc);
} while (entry->nr < PERF_MAX_STACK_DEPTH);
}
void
perf_callchain_user(struct perf_callchain_entry *entry, struct pt_regs *regs)
{
flushw_user();
if (test_thread_flag(TIF_32BIT))
perf_callchain_user_32(entry, regs);
else
perf_callchain_user_64(entry, regs);
}
| gpl-2.0 |
voidz777/android_kernel_samsung_msm8660-common | arch/um/os-Linux/umid.c | 4702 | 8252 | /*
* Copyright (C) 2002 - 2007 Jeff Dike (jdike@{addtoit,linux.intel}.com)
* Licensed under the GPL
*/
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include "init.h"
#include "kern_constants.h"
#include "os.h"
#include "user.h"
#define UML_DIR "~/.uml/"
#define UMID_LEN 64
/* Changed by set_umid, which is run early in boot */
static char umid[UMID_LEN] = { 0 };
/* Changed by set_uml_dir and make_uml_dir, which are run early in boot */
static char *uml_dir = UML_DIR;
static int __init make_uml_dir(void)
{
char dir[512] = { '\0' };
int len, err;
if (*uml_dir == '~') {
char *home = getenv("HOME");
err = -ENOENT;
if (home == NULL) {
printk(UM_KERN_ERR "make_uml_dir : no value in "
"environment for $HOME\n");
goto err;
}
strlcpy(dir, home, sizeof(dir));
uml_dir++;
}
strlcat(dir, uml_dir, sizeof(dir));
len = strlen(dir);
if (len > 0 && dir[len - 1] != '/')
strlcat(dir, "/", sizeof(dir));
err = -ENOMEM;
uml_dir = malloc(strlen(dir) + 1);
if (uml_dir == NULL) {
printf("make_uml_dir : malloc failed, errno = %d\n", errno);
goto err;
}
strcpy(uml_dir, dir);
if ((mkdir(uml_dir, 0777) < 0) && (errno != EEXIST)) {
printf("Failed to mkdir '%s': %s\n", uml_dir, strerror(errno));
err = -errno;
goto err_free;
}
return 0;
err_free:
free(uml_dir);
err:
uml_dir = NULL;
return err;
}
/*
* Unlinks the files contained in @dir and then removes @dir.
* Doesn't handle directory trees, so it's not like rm -rf, but almost such. We
* ignore ENOENT errors for anything (they happen, strangely enough - possibly
* due to races between multiple dying UML threads).
*/
static int remove_files_and_dir(char *dir)
{
DIR *directory;
struct dirent *ent;
int len;
char file[256];
int ret;
directory = opendir(dir);
if (directory == NULL) {
if (errno != ENOENT)
return -errno;
else
return 0;
}
while ((ent = readdir(directory)) != NULL) {
if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, ".."))
continue;
len = strlen(dir) + sizeof("/") + strlen(ent->d_name) + 1;
if (len > sizeof(file)) {
ret = -E2BIG;
goto out;
}
sprintf(file, "%s/%s", dir, ent->d_name);
if (unlink(file) < 0 && errno != ENOENT) {
ret = -errno;
goto out;
}
}
if (rmdir(dir) < 0 && errno != ENOENT) {
ret = -errno;
goto out;
}
ret = 0;
out:
closedir(directory);
return ret;
}
/*
* This says that there isn't already a user of the specified directory even if
* there are errors during the checking. This is because if these errors
* happen, the directory is unusable by the pre-existing UML, so we might as
* well take it over. This could happen either by
* the existing UML somehow corrupting its umid directory
* something other than UML sticking stuff in the directory
* this boot racing with a shutdown of the other UML
* In any of these cases, the directory isn't useful for anything else.
*
* Boolean return: 1 if in use, 0 otherwise.
*/
static inline int is_umdir_used(char *dir)
{
char file[strlen(uml_dir) + UMID_LEN + sizeof("/pid\0")];
char pid[sizeof("nnnnn\0")], *end;
int dead, fd, p, n, err;
n = snprintf(file, sizeof(file), "%s/pid", dir);
if (n >= sizeof(file)) {
printk(UM_KERN_ERR "is_umdir_used - pid filename too long\n");
err = -E2BIG;
goto out;
}
dead = 0;
fd = open(file, O_RDONLY);
if (fd < 0) {
fd = -errno;
if (fd != -ENOENT) {
printk(UM_KERN_ERR "is_umdir_used : couldn't open pid "
"file '%s', err = %d\n", file, -fd);
}
goto out;
}
err = 0;
n = read(fd, pid, sizeof(pid));
if (n < 0) {
printk(UM_KERN_ERR "is_umdir_used : couldn't read pid file "
"'%s', err = %d\n", file, errno);
goto out_close;
} else if (n == 0) {
printk(UM_KERN_ERR "is_umdir_used : couldn't read pid file "
"'%s', 0-byte read\n", file);
goto out_close;
}
p = strtoul(pid, &end, 0);
if (end == pid) {
printk(UM_KERN_ERR "is_umdir_used : couldn't parse pid file "
"'%s', errno = %d\n", file, errno);
goto out_close;
}
if ((kill(p, 0) == 0) || (errno != ESRCH)) {
printk(UM_KERN_ERR "umid \"%s\" is already in use by pid %d\n",
umid, p);
return 1;
}
out_close:
close(fd);
out:
return 0;
}
/*
* Try to remove the directory @dir unless it's in use.
* Precondition: @dir exists.
* Returns 0 for success, < 0 for failure in removal or if the directory is in
* use.
*/
static int umdir_take_if_dead(char *dir)
{
int ret;
if (is_umdir_used(dir))
return -EEXIST;
ret = remove_files_and_dir(dir);
if (ret) {
printk(UM_KERN_ERR "is_umdir_used - remove_files_and_dir "
"failed with err = %d\n", ret);
}
return ret;
}
static void __init create_pid_file(void)
{
char file[strlen(uml_dir) + UMID_LEN + sizeof("/pid\0")];
char pid[sizeof("nnnnn\0")];
int fd, n;
if (umid_file_name("pid", file, sizeof(file)))
return;
fd = open(file, O_RDWR | O_CREAT | O_EXCL, 0644);
if (fd < 0) {
printk(UM_KERN_ERR "Open of machine pid file \"%s\" failed: "
"%s\n", file, strerror(errno));
return;
}
snprintf(pid, sizeof(pid), "%d\n", getpid());
n = write(fd, pid, strlen(pid));
if (n != strlen(pid))
printk(UM_KERN_ERR "Write of pid file failed - err = %d\n",
errno);
close(fd);
}
int __init set_umid(char *name)
{
if (strlen(name) > UMID_LEN - 1)
return -E2BIG;
strlcpy(umid, name, sizeof(umid));
return 0;
}
/* Changed in make_umid, which is called during early boot */
static int umid_setup = 0;
static int __init make_umid(void)
{
int fd, err;
char tmp[256];
if (umid_setup)
return 0;
make_uml_dir();
if (*umid == '\0') {
strlcpy(tmp, uml_dir, sizeof(tmp));
strlcat(tmp, "XXXXXX", sizeof(tmp));
fd = mkstemp(tmp);
if (fd < 0) {
printk(UM_KERN_ERR "make_umid - mkstemp(%s) failed: "
"%s\n", tmp, strerror(errno));
err = -errno;
goto err;
}
close(fd);
set_umid(&tmp[strlen(uml_dir)]);
/*
* There's a nice tiny little race between this unlink and
* the mkdir below. It'd be nice if there were a mkstemp
* for directories.
*/
if (unlink(tmp)) {
err = -errno;
goto err;
}
}
snprintf(tmp, sizeof(tmp), "%s%s", uml_dir, umid);
err = mkdir(tmp, 0777);
if (err < 0) {
err = -errno;
if (err != -EEXIST)
goto err;
if (umdir_take_if_dead(tmp) < 0)
goto err;
err = mkdir(tmp, 0777);
}
if (err) {
err = -errno;
printk(UM_KERN_ERR "Failed to create '%s' - err = %d\n", umid,
errno);
goto err;
}
umid_setup = 1;
create_pid_file();
err = 0;
err:
return err;
}
static int __init make_umid_init(void)
{
if (!make_umid())
return 0;
/*
* If initializing with the given umid failed, then try again with
* a random one.
*/
printk(UM_KERN_ERR "Failed to initialize umid \"%s\", trying with a "
"random umid\n", umid);
*umid = '\0';
make_umid();
return 0;
}
__initcall(make_umid_init);
int __init umid_file_name(char *name, char *buf, int len)
{
int n, err;
err = make_umid();
if (err)
return err;
n = snprintf(buf, len, "%s%s/%s", uml_dir, umid, name);
if (n >= len) {
printk(UM_KERN_ERR "umid_file_name : buffer too short\n");
return -E2BIG;
}
return 0;
}
char *get_umid(void)
{
return umid;
}
static int __init set_uml_dir(char *name, int *add)
{
if (*name == '\0') {
printf("uml_dir can't be an empty string\n");
return 0;
}
if (name[strlen(name) - 1] == '/') {
uml_dir = name;
return 0;
}
uml_dir = malloc(strlen(name) + 2);
if (uml_dir == NULL) {
printf("Failed to malloc uml_dir - error = %d\n", errno);
/*
* Return 0 here because do_initcalls doesn't look at
* the return value.
*/
return 0;
}
sprintf(uml_dir, "%s/", name);
return 0;
}
__uml_setup("uml_dir=", set_uml_dir,
"uml_dir=<directory>\n"
" The location to place the pid and umid files.\n\n"
);
static void remove_umid_dir(void)
{
char dir[strlen(uml_dir) + UMID_LEN + 1], err;
sprintf(dir, "%s%s", uml_dir, umid);
err = remove_files_and_dir(dir);
if (err)
printf("remove_umid_dir - remove_files_and_dir failed with "
"err = %d\n", err);
}
__uml_exitcall(remove_umid_dir);
| gpl-2.0 |
Kato4imoto/armani-kk-kernel | arch/arm/mach-omap2/omap_hwmod_common_data.c | 4958 | 1690 | /*
* omap_hwmod common data structures
*
* Copyright (C) 2010 Texas Instruments, Inc.
* Thara Gopinath <thara@ti.com>
* Benoît Cousson
*
* Copyright (C) 2010 Nokia Corporation
* Paul Walmsley
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This data/structures are to be used while defining OMAP on-chip module
* data and their integration with other OMAP modules and Linux.
*/
#include <plat/omap_hwmod.h>
#include "omap_hwmod_common_data.h"
/**
* struct omap_hwmod_sysc_type1 - TYPE1 sysconfig scheme.
*
* To be used by hwmod structure to specify the sysconfig offsets
* if the device ip is compliant with the original PRCM protocol
* defined for OMAP2420.
*/
struct omap_hwmod_sysc_fields omap_hwmod_sysc_type1 = {
.midle_shift = SYSC_TYPE1_MIDLEMODE_SHIFT,
.clkact_shift = SYSC_TYPE1_CLOCKACTIVITY_SHIFT,
.sidle_shift = SYSC_TYPE1_SIDLEMODE_SHIFT,
.enwkup_shift = SYSC_TYPE1_ENAWAKEUP_SHIFT,
.srst_shift = SYSC_TYPE1_SOFTRESET_SHIFT,
.autoidle_shift = SYSC_TYPE1_AUTOIDLE_SHIFT,
};
/**
* struct omap_hwmod_sysc_type2 - TYPE2 sysconfig scheme.
*
* To be used by hwmod structure to specify the sysconfig offsets if the
* device ip is compliant with the new PRCM protocol defined for new
* OMAP4 IPs.
*/
struct omap_hwmod_sysc_fields omap_hwmod_sysc_type2 = {
.midle_shift = SYSC_TYPE2_MIDLEMODE_SHIFT,
.sidle_shift = SYSC_TYPE2_SIDLEMODE_SHIFT,
.srst_shift = SYSC_TYPE2_SOFTRESET_SHIFT,
};
struct omap_dss_dispc_dev_attr omap2_3_dss_dispc_dev_attr = {
.manager_count = 2,
.has_framedonetv_irq = 0
};
| gpl-2.0 |
android-armv7a-belalang-tempur/Android_SpeedKernel | drivers/usb/host/uhci-pci.c | 7774 | 8353 | /*
* UHCI HCD (Host Controller Driver) PCI Bus Glue.
*
* Extracted from uhci-hcd.c:
* Maintainer: Alan Stern <stern@rowland.harvard.edu>
*
* (C) Copyright 1999 Linus Torvalds
* (C) Copyright 1999-2002 Johannes Erdfelt, johannes@erdfelt.com
* (C) Copyright 1999 Randy Dunlap
* (C) Copyright 1999 Georg Acher, acher@in.tum.de
* (C) Copyright 1999 Deti Fliegl, deti@fliegl.de
* (C) Copyright 1999 Thomas Sailer, sailer@ife.ee.ethz.ch
* (C) Copyright 1999 Roman Weissgaerber, weissg@vienna.at
* (C) Copyright 2000 Yggdrasil Computing, Inc. (port of new PCI interface
* support from usb-ohci.c by Adam Richter, adam@yggdrasil.com).
* (C) Copyright 1999 Gregory P. Smith (from usb-ohci.c)
* (C) Copyright 2004-2007 Alan Stern, stern@rowland.harvard.edu
*/
#include "pci-quirks.h"
/*
* Make sure the controller is completely inactive, unable to
* generate interrupts or do DMA.
*/
static void uhci_pci_reset_hc(struct uhci_hcd *uhci)
{
uhci_reset_hc(to_pci_dev(uhci_dev(uhci)), uhci->io_addr);
}
/*
* Initialize a controller that was newly discovered or has just been
* resumed. In either case we can't be sure of its previous state.
*
* Returns: 1 if the controller was reset, 0 otherwise.
*/
static int uhci_pci_check_and_reset_hc(struct uhci_hcd *uhci)
{
return uhci_check_and_reset_hc(to_pci_dev(uhci_dev(uhci)),
uhci->io_addr);
}
/*
* Store the basic register settings needed by the controller.
* This function is called at the end of configure_hc in uhci-hcd.c.
*/
static void uhci_pci_configure_hc(struct uhci_hcd *uhci)
{
struct pci_dev *pdev = to_pci_dev(uhci_dev(uhci));
/* Enable PIRQ */
pci_write_config_word(pdev, USBLEGSUP, USBLEGSUP_DEFAULT);
/* Disable platform-specific non-PME# wakeup */
if (pdev->vendor == PCI_VENDOR_ID_INTEL)
pci_write_config_byte(pdev, USBRES_INTEL, 0);
}
static int uhci_pci_resume_detect_interrupts_are_broken(struct uhci_hcd *uhci)
{
int port;
switch (to_pci_dev(uhci_dev(uhci))->vendor) {
default:
break;
case PCI_VENDOR_ID_GENESYS:
/* Genesys Logic's GL880S controllers don't generate
* resume-detect interrupts.
*/
return 1;
case PCI_VENDOR_ID_INTEL:
/* Some of Intel's USB controllers have a bug that causes
* resume-detect interrupts if any port has an over-current
* condition. To make matters worse, some motherboards
* hardwire unused USB ports' over-current inputs active!
* To prevent problems, we will not enable resume-detect
* interrupts if any ports are OC.
*/
for (port = 0; port < uhci->rh_numports; ++port) {
if (inw(uhci->io_addr + USBPORTSC1 + port * 2) &
USBPORTSC_OC)
return 1;
}
break;
}
return 0;
}
static int uhci_pci_global_suspend_mode_is_broken(struct uhci_hcd *uhci)
{
int port;
const char *sys_info;
static const char bad_Asus_board[] = "A7V8X";
/* One of Asus's motherboards has a bug which causes it to
* wake up immediately from suspend-to-RAM if any of the ports
* are connected. In such cases we will not set EGSM.
*/
sys_info = dmi_get_system_info(DMI_BOARD_NAME);
if (sys_info && !strcmp(sys_info, bad_Asus_board)) {
for (port = 0; port < uhci->rh_numports; ++port) {
if (inw(uhci->io_addr + USBPORTSC1 + port * 2) &
USBPORTSC_CCS)
return 1;
}
}
return 0;
}
static int uhci_pci_init(struct usb_hcd *hcd)
{
struct uhci_hcd *uhci = hcd_to_uhci(hcd);
uhci->io_addr = (unsigned long) hcd->rsrc_start;
uhci->rh_numports = uhci_count_ports(hcd);
/* Intel controllers report the OverCurrent bit active on.
* VIA controllers report it active off, so we'll adjust the
* bit value. (It's not standardized in the UHCI spec.)
*/
if (to_pci_dev(uhci_dev(uhci))->vendor == PCI_VENDOR_ID_VIA)
uhci->oc_low = 1;
/* HP's server management chip requires a longer port reset delay. */
if (to_pci_dev(uhci_dev(uhci))->vendor == PCI_VENDOR_ID_HP)
uhci->wait_for_hp = 1;
/* Set up pointers to PCI-specific functions */
uhci->reset_hc = uhci_pci_reset_hc;
uhci->check_and_reset_hc = uhci_pci_check_and_reset_hc;
uhci->configure_hc = uhci_pci_configure_hc;
uhci->resume_detect_interrupts_are_broken =
uhci_pci_resume_detect_interrupts_are_broken;
uhci->global_suspend_mode_is_broken =
uhci_pci_global_suspend_mode_is_broken;
/* Kick BIOS off this hardware and reset if the controller
* isn't already safely quiescent.
*/
check_and_reset_hc(uhci);
return 0;
}
/* Make sure the controller is quiescent and that we're not using it
* any more. This is mainly for the benefit of programs which, like kexec,
* expect the hardware to be idle: not doing DMA or generating IRQs.
*
* This routine may be called in a damaged or failing kernel. Hence we
* do not acquire the spinlock before shutting down the controller.
*/
static void uhci_shutdown(struct pci_dev *pdev)
{
struct usb_hcd *hcd = pci_get_drvdata(pdev);
uhci_hc_died(hcd_to_uhci(hcd));
}
#ifdef CONFIG_PM
static int uhci_pci_suspend(struct usb_hcd *hcd, bool do_wakeup)
{
struct uhci_hcd *uhci = hcd_to_uhci(hcd);
struct pci_dev *pdev = to_pci_dev(uhci_dev(uhci));
int rc = 0;
dev_dbg(uhci_dev(uhci), "%s\n", __func__);
spin_lock_irq(&uhci->lock);
if (!HCD_HW_ACCESSIBLE(hcd) || uhci->dead)
goto done_okay; /* Already suspended or dead */
if (uhci->rh_state > UHCI_RH_SUSPENDED) {
dev_warn(uhci_dev(uhci), "Root hub isn't suspended!\n");
rc = -EBUSY;
goto done;
};
/* All PCI host controllers are required to disable IRQ generation
* at the source, so we must turn off PIRQ.
*/
pci_write_config_word(pdev, USBLEGSUP, 0);
clear_bit(HCD_FLAG_POLL_RH, &hcd->flags);
/* Enable platform-specific non-PME# wakeup */
if (do_wakeup) {
if (pdev->vendor == PCI_VENDOR_ID_INTEL)
pci_write_config_byte(pdev, USBRES_INTEL,
USBPORT1EN | USBPORT2EN);
}
done_okay:
clear_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
done:
spin_unlock_irq(&uhci->lock);
return rc;
}
static int uhci_pci_resume(struct usb_hcd *hcd, bool hibernated)
{
struct uhci_hcd *uhci = hcd_to_uhci(hcd);
dev_dbg(uhci_dev(uhci), "%s\n", __func__);
/* Since we aren't in D3 any more, it's safe to set this flag
* even if the controller was dead.
*/
set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
spin_lock_irq(&uhci->lock);
/* Make sure resume from hibernation re-enumerates everything */
if (hibernated) {
uhci->reset_hc(uhci);
finish_reset(uhci);
}
/* The firmware may have changed the controller settings during
* a system wakeup. Check it and reconfigure to avoid problems.
*/
else {
check_and_reset_hc(uhci);
}
configure_hc(uhci);
/* Tell the core if the controller had to be reset */
if (uhci->rh_state == UHCI_RH_RESET)
usb_root_hub_lost_power(hcd->self.root_hub);
spin_unlock_irq(&uhci->lock);
/* If interrupts don't work and remote wakeup is enabled then
* the suspended root hub needs to be polled.
*/
if (!uhci->RD_enable && hcd->self.root_hub->do_remote_wakeup)
set_bit(HCD_FLAG_POLL_RH, &hcd->flags);
/* Does the root hub have a port wakeup pending? */
usb_hcd_poll_rh_status(hcd);
return 0;
}
#endif
static const struct hc_driver uhci_driver = {
.description = hcd_name,
.product_desc = "UHCI Host Controller",
.hcd_priv_size = sizeof(struct uhci_hcd),
/* Generic hardware linkage */
.irq = uhci_irq,
.flags = HCD_USB11,
/* Basic lifecycle operations */
.reset = uhci_pci_init,
.start = uhci_start,
#ifdef CONFIG_PM
.pci_suspend = uhci_pci_suspend,
.pci_resume = uhci_pci_resume,
.bus_suspend = uhci_rh_suspend,
.bus_resume = uhci_rh_resume,
#endif
.stop = uhci_stop,
.urb_enqueue = uhci_urb_enqueue,
.urb_dequeue = uhci_urb_dequeue,
.endpoint_disable = uhci_hcd_endpoint_disable,
.get_frame_number = uhci_hcd_get_frame_number,
.hub_status_data = uhci_hub_status_data,
.hub_control = uhci_hub_control,
};
static DEFINE_PCI_DEVICE_TABLE(uhci_pci_ids) = { {
/* handle any USB UHCI controller */
PCI_DEVICE_CLASS(PCI_CLASS_SERIAL_USB_UHCI, ~0),
.driver_data = (unsigned long) &uhci_driver,
}, { /* end: all zeroes */ }
};
MODULE_DEVICE_TABLE(pci, uhci_pci_ids);
static struct pci_driver uhci_pci_driver = {
.name = (char *)hcd_name,
.id_table = uhci_pci_ids,
.probe = usb_hcd_pci_probe,
.remove = usb_hcd_pci_remove,
.shutdown = uhci_shutdown,
#ifdef CONFIG_PM_SLEEP
.driver = {
.pm = &usb_hcd_pci_pm_ops
},
#endif
};
| gpl-2.0 |
freak07/Kirisakura_Pixel | arch/c6x/kernel/sys_c6x.c | 9054 | 1932 | /*
* Port on Texas Instruments TMS320C6x architecture
*
* Copyright (C) 2004, 2009, 2010, 2011 Texas Instruments Incorporated
* Author: Aurelien Jacquiot (aurelien.jacquiot@jaluna.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/syscalls.h>
#include <linux/uaccess.h>
#include <asm/syscalls.h>
#ifdef CONFIG_ACCESS_CHECK
int _access_ok(unsigned long addr, unsigned long size)
{
if (!size)
return 1;
if (!addr || addr > (0xffffffffUL - (size - 1)))
goto _bad_access;
if (segment_eq(get_fs(), KERNEL_DS))
return 1;
if (memory_start <= addr && (addr + size - 1) < memory_end)
return 1;
_bad_access:
pr_debug("Bad access attempt: pid[%d] addr[%08lx] size[0x%lx]\n",
current->pid, addr, size);
return 0;
}
EXPORT_SYMBOL(_access_ok);
#endif
/* sys_cache_sync -- sync caches over given range */
asmlinkage int sys_cache_sync(unsigned long s, unsigned long e)
{
L1D_cache_block_writeback_invalidate(s, e);
L1P_cache_block_invalidate(s, e);
return 0;
}
/* Provide the actual syscall number to call mapping. */
#undef __SYSCALL
#define __SYSCALL(nr, call) [nr] = (call),
/*
* Use trampolines
*/
#define sys_pread64 sys_pread_c6x
#define sys_pwrite64 sys_pwrite_c6x
#define sys_truncate64 sys_truncate64_c6x
#define sys_ftruncate64 sys_ftruncate64_c6x
#define sys_fadvise64 sys_fadvise64_c6x
#define sys_fadvise64_64 sys_fadvise64_64_c6x
#define sys_fallocate sys_fallocate_c6x
/* Use sys_mmap_pgoff directly */
#define sys_mmap2 sys_mmap_pgoff
/*
* Note that we can't include <linux/unistd.h> here since the header
* guard will defeat us; <asm/unistd.h> checks for __SYSCALL as well.
*/
void *sys_call_table[__NR_syscalls] = {
[0 ... __NR_syscalls-1] = sys_ni_syscall,
#include <asm/unistd.h>
};
| gpl-2.0 |
weritos666/kernel_L7_II_KK | arch/x86/mm/pf_in.c | 12126 | 10785 | /*
* Fault Injection Test harness (FI)
* Copyright (C) Intel Crop.
*
* 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.
*
*/
/* Id: pf_in.c,v 1.1.1.1 2002/11/12 05:56:32 brlock Exp
* Copyright by Intel Crop., 2002
* Louis Zhuang (louis.zhuang@intel.com)
*
* Bjorn Steinbrink (B.Steinbrink@gmx.de), 2007
*/
#include <linux/module.h>
#include <linux/ptrace.h> /* struct pt_regs */
#include "pf_in.h"
#ifdef __i386__
/* IA32 Manual 3, 2-1 */
static unsigned char prefix_codes[] = {
0xF0, 0xF2, 0xF3, 0x2E, 0x36, 0x3E, 0x26, 0x64,
0x65, 0x66, 0x67
};
/* IA32 Manual 3, 3-432*/
static unsigned int reg_rop[] = {
0x8A, 0x8B, 0xB60F, 0xB70F, 0xBE0F, 0xBF0F
};
static unsigned int reg_wop[] = { 0x88, 0x89, 0xAA, 0xAB };
static unsigned int imm_wop[] = { 0xC6, 0xC7 };
/* IA32 Manual 3, 3-432*/
static unsigned int rw8[] = { 0x88, 0x8A, 0xC6, 0xAA };
static unsigned int rw32[] = {
0x89, 0x8B, 0xC7, 0xB60F, 0xB70F, 0xBE0F, 0xBF0F, 0xAB
};
static unsigned int mw8[] = { 0x88, 0x8A, 0xC6, 0xB60F, 0xBE0F, 0xAA };
static unsigned int mw16[] = { 0xB70F, 0xBF0F };
static unsigned int mw32[] = { 0x89, 0x8B, 0xC7, 0xAB };
static unsigned int mw64[] = {};
#else /* not __i386__ */
static unsigned char prefix_codes[] = {
0x66, 0x67, 0x2E, 0x3E, 0x26, 0x64, 0x65, 0x36,
0xF0, 0xF3, 0xF2,
/* REX Prefixes */
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f
};
/* AMD64 Manual 3, Appendix A*/
static unsigned int reg_rop[] = {
0x8A, 0x8B, 0xB60F, 0xB70F, 0xBE0F, 0xBF0F
};
static unsigned int reg_wop[] = { 0x88, 0x89, 0xAA, 0xAB };
static unsigned int imm_wop[] = { 0xC6, 0xC7 };
static unsigned int rw8[] = { 0xC6, 0x88, 0x8A, 0xAA };
static unsigned int rw32[] = {
0xC7, 0x89, 0x8B, 0xB60F, 0xB70F, 0xBE0F, 0xBF0F, 0xAB
};
/* 8 bit only */
static unsigned int mw8[] = { 0xC6, 0x88, 0x8A, 0xB60F, 0xBE0F, 0xAA };
/* 16 bit only */
static unsigned int mw16[] = { 0xB70F, 0xBF0F };
/* 16 or 32 bit */
static unsigned int mw32[] = { 0xC7 };
/* 16, 32 or 64 bit */
static unsigned int mw64[] = { 0x89, 0x8B, 0xAB };
#endif /* not __i386__ */
struct prefix_bits {
unsigned shorted:1;
unsigned enlarged:1;
unsigned rexr:1;
unsigned rex:1;
};
static int skip_prefix(unsigned char *addr, struct prefix_bits *prf)
{
int i;
unsigned char *p = addr;
prf->shorted = 0;
prf->enlarged = 0;
prf->rexr = 0;
prf->rex = 0;
restart:
for (i = 0; i < ARRAY_SIZE(prefix_codes); i++) {
if (*p == prefix_codes[i]) {
if (*p == 0x66)
prf->shorted = 1;
#ifdef __amd64__
if ((*p & 0xf8) == 0x48)
prf->enlarged = 1;
if ((*p & 0xf4) == 0x44)
prf->rexr = 1;
if ((*p & 0xf0) == 0x40)
prf->rex = 1;
#endif
p++;
goto restart;
}
}
return (p - addr);
}
static int get_opcode(unsigned char *addr, unsigned int *opcode)
{
int len;
if (*addr == 0x0F) {
/* 0x0F is extension instruction */
*opcode = *(unsigned short *)addr;
len = 2;
} else {
*opcode = *addr;
len = 1;
}
return len;
}
#define CHECK_OP_TYPE(opcode, array, type) \
for (i = 0; i < ARRAY_SIZE(array); i++) { \
if (array[i] == opcode) { \
rv = type; \
goto exit; \
} \
}
enum reason_type get_ins_type(unsigned long ins_addr)
{
unsigned int opcode;
unsigned char *p;
struct prefix_bits prf;
int i;
enum reason_type rv = OTHERS;
p = (unsigned char *)ins_addr;
p += skip_prefix(p, &prf);
p += get_opcode(p, &opcode);
CHECK_OP_TYPE(opcode, reg_rop, REG_READ);
CHECK_OP_TYPE(opcode, reg_wop, REG_WRITE);
CHECK_OP_TYPE(opcode, imm_wop, IMM_WRITE);
exit:
return rv;
}
#undef CHECK_OP_TYPE
static unsigned int get_ins_reg_width(unsigned long ins_addr)
{
unsigned int opcode;
unsigned char *p;
struct prefix_bits prf;
int i;
p = (unsigned char *)ins_addr;
p += skip_prefix(p, &prf);
p += get_opcode(p, &opcode);
for (i = 0; i < ARRAY_SIZE(rw8); i++)
if (rw8[i] == opcode)
return 1;
for (i = 0; i < ARRAY_SIZE(rw32); i++)
if (rw32[i] == opcode)
return prf.shorted ? 2 : (prf.enlarged ? 8 : 4);
printk(KERN_ERR "mmiotrace: Unknown opcode 0x%02x\n", opcode);
return 0;
}
unsigned int get_ins_mem_width(unsigned long ins_addr)
{
unsigned int opcode;
unsigned char *p;
struct prefix_bits prf;
int i;
p = (unsigned char *)ins_addr;
p += skip_prefix(p, &prf);
p += get_opcode(p, &opcode);
for (i = 0; i < ARRAY_SIZE(mw8); i++)
if (mw8[i] == opcode)
return 1;
for (i = 0; i < ARRAY_SIZE(mw16); i++)
if (mw16[i] == opcode)
return 2;
for (i = 0; i < ARRAY_SIZE(mw32); i++)
if (mw32[i] == opcode)
return prf.shorted ? 2 : 4;
for (i = 0; i < ARRAY_SIZE(mw64); i++)
if (mw64[i] == opcode)
return prf.shorted ? 2 : (prf.enlarged ? 8 : 4);
printk(KERN_ERR "mmiotrace: Unknown opcode 0x%02x\n", opcode);
return 0;
}
/*
* Define register ident in mod/rm byte.
* Note: these are NOT the same as in ptrace-abi.h.
*/
enum {
arg_AL = 0,
arg_CL = 1,
arg_DL = 2,
arg_BL = 3,
arg_AH = 4,
arg_CH = 5,
arg_DH = 6,
arg_BH = 7,
arg_AX = 0,
arg_CX = 1,
arg_DX = 2,
arg_BX = 3,
arg_SP = 4,
arg_BP = 5,
arg_SI = 6,
arg_DI = 7,
#ifdef __amd64__
arg_R8 = 8,
arg_R9 = 9,
arg_R10 = 10,
arg_R11 = 11,
arg_R12 = 12,
arg_R13 = 13,
arg_R14 = 14,
arg_R15 = 15
#endif
};
static unsigned char *get_reg_w8(int no, int rex, struct pt_regs *regs)
{
unsigned char *rv = NULL;
switch (no) {
case arg_AL:
rv = (unsigned char *)®s->ax;
break;
case arg_BL:
rv = (unsigned char *)®s->bx;
break;
case arg_CL:
rv = (unsigned char *)®s->cx;
break;
case arg_DL:
rv = (unsigned char *)®s->dx;
break;
#ifdef __amd64__
case arg_R8:
rv = (unsigned char *)®s->r8;
break;
case arg_R9:
rv = (unsigned char *)®s->r9;
break;
case arg_R10:
rv = (unsigned char *)®s->r10;
break;
case arg_R11:
rv = (unsigned char *)®s->r11;
break;
case arg_R12:
rv = (unsigned char *)®s->r12;
break;
case arg_R13:
rv = (unsigned char *)®s->r13;
break;
case arg_R14:
rv = (unsigned char *)®s->r14;
break;
case arg_R15:
rv = (unsigned char *)®s->r15;
break;
#endif
default:
break;
}
if (rv)
return rv;
if (rex) {
/*
* If REX prefix exists, access low bytes of SI etc.
* instead of AH etc.
*/
switch (no) {
case arg_SI:
rv = (unsigned char *)®s->si;
break;
case arg_DI:
rv = (unsigned char *)®s->di;
break;
case arg_BP:
rv = (unsigned char *)®s->bp;
break;
case arg_SP:
rv = (unsigned char *)®s->sp;
break;
default:
break;
}
} else {
switch (no) {
case arg_AH:
rv = 1 + (unsigned char *)®s->ax;
break;
case arg_BH:
rv = 1 + (unsigned char *)®s->bx;
break;
case arg_CH:
rv = 1 + (unsigned char *)®s->cx;
break;
case arg_DH:
rv = 1 + (unsigned char *)®s->dx;
break;
default:
break;
}
}
if (!rv)
printk(KERN_ERR "mmiotrace: Error reg no# %d\n", no);
return rv;
}
static unsigned long *get_reg_w32(int no, struct pt_regs *regs)
{
unsigned long *rv = NULL;
switch (no) {
case arg_AX:
rv = ®s->ax;
break;
case arg_BX:
rv = ®s->bx;
break;
case arg_CX:
rv = ®s->cx;
break;
case arg_DX:
rv = ®s->dx;
break;
case arg_SP:
rv = ®s->sp;
break;
case arg_BP:
rv = ®s->bp;
break;
case arg_SI:
rv = ®s->si;
break;
case arg_DI:
rv = ®s->di;
break;
#ifdef __amd64__
case arg_R8:
rv = ®s->r8;
break;
case arg_R9:
rv = ®s->r9;
break;
case arg_R10:
rv = ®s->r10;
break;
case arg_R11:
rv = ®s->r11;
break;
case arg_R12:
rv = ®s->r12;
break;
case arg_R13:
rv = ®s->r13;
break;
case arg_R14:
rv = ®s->r14;
break;
case arg_R15:
rv = ®s->r15;
break;
#endif
default:
printk(KERN_ERR "mmiotrace: Error reg no# %d\n", no);
}
return rv;
}
unsigned long get_ins_reg_val(unsigned long ins_addr, struct pt_regs *regs)
{
unsigned int opcode;
int reg;
unsigned char *p;
struct prefix_bits prf;
int i;
p = (unsigned char *)ins_addr;
p += skip_prefix(p, &prf);
p += get_opcode(p, &opcode);
for (i = 0; i < ARRAY_SIZE(reg_rop); i++)
if (reg_rop[i] == opcode)
goto do_work;
for (i = 0; i < ARRAY_SIZE(reg_wop); i++)
if (reg_wop[i] == opcode)
goto do_work;
printk(KERN_ERR "mmiotrace: Not a register instruction, opcode "
"0x%02x\n", opcode);
goto err;
do_work:
/* for STOS, source register is fixed */
if (opcode == 0xAA || opcode == 0xAB) {
reg = arg_AX;
} else {
unsigned char mod_rm = *p;
reg = ((mod_rm >> 3) & 0x7) | (prf.rexr << 3);
}
switch (get_ins_reg_width(ins_addr)) {
case 1:
return *get_reg_w8(reg, prf.rex, regs);
case 2:
return *(unsigned short *)get_reg_w32(reg, regs);
case 4:
return *(unsigned int *)get_reg_w32(reg, regs);
#ifdef __amd64__
case 8:
return *(unsigned long *)get_reg_w32(reg, regs);
#endif
default:
printk(KERN_ERR "mmiotrace: Error width# %d\n", reg);
}
err:
return 0;
}
unsigned long get_ins_imm_val(unsigned long ins_addr)
{
unsigned int opcode;
unsigned char mod_rm;
unsigned char mod;
unsigned char *p;
struct prefix_bits prf;
int i;
p = (unsigned char *)ins_addr;
p += skip_prefix(p, &prf);
p += get_opcode(p, &opcode);
for (i = 0; i < ARRAY_SIZE(imm_wop); i++)
if (imm_wop[i] == opcode)
goto do_work;
printk(KERN_ERR "mmiotrace: Not an immediate instruction, opcode "
"0x%02x\n", opcode);
goto err;
do_work:
mod_rm = *p;
mod = mod_rm >> 6;
p++;
switch (mod) {
case 0:
/* if r/m is 5 we have a 32 disp (IA32 Manual 3, Table 2-2) */
/* AMD64: XXX Check for address size prefix? */
if ((mod_rm & 0x7) == 0x5)
p += 4;
break;
case 1:
p += 1;
break;
case 2:
p += 4;
break;
case 3:
default:
printk(KERN_ERR "mmiotrace: not a memory access instruction "
"at 0x%lx, rm_mod=0x%02x\n",
ins_addr, mod_rm);
}
switch (get_ins_reg_width(ins_addr)) {
case 1:
return *(unsigned char *)p;
case 2:
return *(unsigned short *)p;
case 4:
return *(unsigned int *)p;
#ifdef __amd64__
case 8:
return *(unsigned long *)p;
#endif
default:
printk(KERN_ERR "mmiotrace: Error: width.\n");
}
err:
return 0;
}
| gpl-2.0 |
windyyuan/linux | lib/fonts/font_8x8.c | 14686 | 50858 | /**********************************************/
/* */
/* Font file generated by cpi2fnt */
/* */
/**********************************************/
#include <linux/font.h>
#define FONTDATAMAX 2048
static const unsigned char fontdata_8x8[FONTDATAMAX] = {
/* 0 0x00 '^@' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 1 0x01 '^A' */
0x7e, /* 01111110 */
0x81, /* 10000001 */
0xa5, /* 10100101 */
0x81, /* 10000001 */
0xbd, /* 10111101 */
0x99, /* 10011001 */
0x81, /* 10000001 */
0x7e, /* 01111110 */
/* 2 0x02 '^B' */
0x7e, /* 01111110 */
0xff, /* 11111111 */
0xdb, /* 11011011 */
0xff, /* 11111111 */
0xc3, /* 11000011 */
0xe7, /* 11100111 */
0xff, /* 11111111 */
0x7e, /* 01111110 */
/* 3 0x03 '^C' */
0x6c, /* 01101100 */
0xfe, /* 11111110 */
0xfe, /* 11111110 */
0xfe, /* 11111110 */
0x7c, /* 01111100 */
0x38, /* 00111000 */
0x10, /* 00010000 */
0x00, /* 00000000 */
/* 4 0x04 '^D' */
0x10, /* 00010000 */
0x38, /* 00111000 */
0x7c, /* 01111100 */
0xfe, /* 11111110 */
0x7c, /* 01111100 */
0x38, /* 00111000 */
0x10, /* 00010000 */
0x00, /* 00000000 */
/* 5 0x05 '^E' */
0x38, /* 00111000 */
0x7c, /* 01111100 */
0x38, /* 00111000 */
0xfe, /* 11111110 */
0xfe, /* 11111110 */
0xd6, /* 11010110 */
0x10, /* 00010000 */
0x38, /* 00111000 */
/* 6 0x06 '^F' */
0x10, /* 00010000 */
0x38, /* 00111000 */
0x7c, /* 01111100 */
0xfe, /* 11111110 */
0xfe, /* 11111110 */
0x7c, /* 01111100 */
0x10, /* 00010000 */
0x38, /* 00111000 */
/* 7 0x07 '^G' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 8 0x08 '^H' */
0xff, /* 11111111 */
0xff, /* 11111111 */
0xe7, /* 11100111 */
0xc3, /* 11000011 */
0xc3, /* 11000011 */
0xe7, /* 11100111 */
0xff, /* 11111111 */
0xff, /* 11111111 */
/* 9 0x09 '^I' */
0x00, /* 00000000 */
0x3c, /* 00111100 */
0x66, /* 01100110 */
0x42, /* 01000010 */
0x42, /* 01000010 */
0x66, /* 01100110 */
0x3c, /* 00111100 */
0x00, /* 00000000 */
/* 10 0x0a '^J' */
0xff, /* 11111111 */
0xc3, /* 11000011 */
0x99, /* 10011001 */
0xbd, /* 10111101 */
0xbd, /* 10111101 */
0x99, /* 10011001 */
0xc3, /* 11000011 */
0xff, /* 11111111 */
/* 11 0x0b '^K' */
0x0f, /* 00001111 */
0x07, /* 00000111 */
0x0f, /* 00001111 */
0x7d, /* 01111101 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0x78, /* 01111000 */
/* 12 0x0c '^L' */
0x3c, /* 00111100 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0x7e, /* 01111110 */
0x18, /* 00011000 */
/* 13 0x0d '^M' */
0x3f, /* 00111111 */
0x33, /* 00110011 */
0x3f, /* 00111111 */
0x30, /* 00110000 */
0x30, /* 00110000 */
0x70, /* 01110000 */
0xf0, /* 11110000 */
0xe0, /* 11100000 */
/* 14 0x0e '^N' */
0x7f, /* 01111111 */
0x63, /* 01100011 */
0x7f, /* 01111111 */
0x63, /* 01100011 */
0x63, /* 01100011 */
0x67, /* 01100111 */
0xe6, /* 11100110 */
0xc0, /* 11000000 */
/* 15 0x0f '^O' */
0x18, /* 00011000 */
0xdb, /* 11011011 */
0x3c, /* 00111100 */
0xe7, /* 11100111 */
0xe7, /* 11100111 */
0x3c, /* 00111100 */
0xdb, /* 11011011 */
0x18, /* 00011000 */
/* 16 0x10 '^P' */
0x80, /* 10000000 */
0xe0, /* 11100000 */
0xf8, /* 11111000 */
0xfe, /* 11111110 */
0xf8, /* 11111000 */
0xe0, /* 11100000 */
0x80, /* 10000000 */
0x00, /* 00000000 */
/* 17 0x11 '^Q' */
0x02, /* 00000010 */
0x0e, /* 00001110 */
0x3e, /* 00111110 */
0xfe, /* 11111110 */
0x3e, /* 00111110 */
0x0e, /* 00001110 */
0x02, /* 00000010 */
0x00, /* 00000000 */
/* 18 0x12 '^R' */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x7e, /* 01111110 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x7e, /* 01111110 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
/* 19 0x13 '^S' */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x00, /* 00000000 */
0x66, /* 01100110 */
0x00, /* 00000000 */
/* 20 0x14 '^T' */
0x7f, /* 01111111 */
0xdb, /* 11011011 */
0xdb, /* 11011011 */
0x7b, /* 01111011 */
0x1b, /* 00011011 */
0x1b, /* 00011011 */
0x1b, /* 00011011 */
0x00, /* 00000000 */
/* 21 0x15 '^U' */
0x3e, /* 00111110 */
0x61, /* 01100001 */
0x3c, /* 00111100 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x3c, /* 00111100 */
0x86, /* 10000110 */
0x7c, /* 01111100 */
/* 22 0x16 '^V' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0x7e, /* 01111110 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
/* 23 0x17 '^W' */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x7e, /* 01111110 */
0x18, /* 00011000 */
0x7e, /* 01111110 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0xff, /* 11111111 */
/* 24 0x18 '^X' */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x7e, /* 01111110 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 25 0x19 '^Y' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x7e, /* 01111110 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 26 0x1a '^Z' */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x0c, /* 00001100 */
0xfe, /* 11111110 */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 27 0x1b '^[' */
0x00, /* 00000000 */
0x30, /* 00110000 */
0x60, /* 01100000 */
0xfe, /* 11111110 */
0x60, /* 01100000 */
0x30, /* 00110000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 28 0x1c '^\' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 29 0x1d '^]' */
0x00, /* 00000000 */
0x24, /* 00100100 */
0x66, /* 01100110 */
0xff, /* 11111111 */
0x66, /* 01100110 */
0x24, /* 00100100 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 30 0x1e '^^' */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x7e, /* 01111110 */
0xff, /* 11111111 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 31 0x1f '^_' */
0x00, /* 00000000 */
0xff, /* 11111111 */
0xff, /* 11111111 */
0x7e, /* 01111110 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 32 0x20 ' ' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 33 0x21 '!' */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 34 0x22 '"' */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x24, /* 00100100 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 35 0x23 '#' */
0x6c, /* 01101100 */
0x6c, /* 01101100 */
0xfe, /* 11111110 */
0x6c, /* 01101100 */
0xfe, /* 11111110 */
0x6c, /* 01101100 */
0x6c, /* 01101100 */
0x00, /* 00000000 */
/* 36 0x24 '$' */
0x18, /* 00011000 */
0x3e, /* 00111110 */
0x60, /* 01100000 */
0x3c, /* 00111100 */
0x06, /* 00000110 */
0x7c, /* 01111100 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 37 0x25 '%' */
0x00, /* 00000000 */
0xc6, /* 11000110 */
0xcc, /* 11001100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x66, /* 01100110 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 38 0x26 '&' */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0x38, /* 00111000 */
0x76, /* 01110110 */
0xdc, /* 11011100 */
0xcc, /* 11001100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 39 0x27 ''' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 40 0x28 '(' */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x30, /* 00110000 */
0x30, /* 00110000 */
0x18, /* 00011000 */
0x0c, /* 00001100 */
0x00, /* 00000000 */
/* 41 0x29 ')' */
0x30, /* 00110000 */
0x18, /* 00011000 */
0x0c, /* 00001100 */
0x0c, /* 00001100 */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x00, /* 00000000 */
/* 42 0x2a '*' */
0x00, /* 00000000 */
0x66, /* 01100110 */
0x3c, /* 00111100 */
0xff, /* 11111111 */
0x3c, /* 00111100 */
0x66, /* 01100110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 43 0x2b '+' */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x7e, /* 01111110 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 44 0x2c ',' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x30, /* 00110000 */
/* 45 0x2d '-' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 46 0x2e '.' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 47 0x2f '/' */
0x06, /* 00000110 */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x60, /* 01100000 */
0xc0, /* 11000000 */
0x80, /* 10000000 */
0x00, /* 00000000 */
/* 48 0x30 '0' */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0xc6, /* 11000110 */
0xd6, /* 11010110 */
0xc6, /* 11000110 */
0x6c, /* 01101100 */
0x38, /* 00111000 */
0x00, /* 00000000 */
/* 49 0x31 '1' */
0x18, /* 00011000 */
0x38, /* 00111000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
/* 50 0x32 '2' */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0x06, /* 00000110 */
0x1c, /* 00011100 */
0x30, /* 00110000 */
0x66, /* 01100110 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
/* 51 0x33 '3' */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0x06, /* 00000110 */
0x3c, /* 00111100 */
0x06, /* 00000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 52 0x34 '4' */
0x1c, /* 00011100 */
0x3c, /* 00111100 */
0x6c, /* 01101100 */
0xcc, /* 11001100 */
0xfe, /* 11111110 */
0x0c, /* 00001100 */
0x1e, /* 00011110 */
0x00, /* 00000000 */
/* 53 0x35 '5' */
0xfe, /* 11111110 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xfc, /* 11111100 */
0x06, /* 00000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 54 0x36 '6' */
0x38, /* 00111000 */
0x60, /* 01100000 */
0xc0, /* 11000000 */
0xfc, /* 11111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 55 0x37 '7' */
0xfe, /* 11111110 */
0xc6, /* 11000110 */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x30, /* 00110000 */
0x30, /* 00110000 */
0x00, /* 00000000 */
/* 56 0x38 '8' */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 57 0x39 '9' */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7e, /* 01111110 */
0x06, /* 00000110 */
0x0c, /* 00001100 */
0x78, /* 01111000 */
0x00, /* 00000000 */
/* 58 0x3a ':' */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 59 0x3b ';' */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x30, /* 00110000 */
/* 60 0x3c '<' */
0x06, /* 00000110 */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x18, /* 00011000 */
0x0c, /* 00001100 */
0x06, /* 00000110 */
0x00, /* 00000000 */
/* 61 0x3d '=' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 62 0x3e '>' */
0x60, /* 01100000 */
0x30, /* 00110000 */
0x18, /* 00011000 */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x60, /* 01100000 */
0x00, /* 00000000 */
/* 63 0x3f '?' */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 64 0x40 '@' */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xde, /* 11011110 */
0xde, /* 11011110 */
0xde, /* 11011110 */
0xc0, /* 11000000 */
0x78, /* 01111000 */
0x00, /* 00000000 */
/* 65 0x41 'A' */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 66 0x42 'B' */
0xfc, /* 11111100 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x7c, /* 01111100 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0xfc, /* 11111100 */
0x00, /* 00000000 */
/* 67 0x43 'C' */
0x3c, /* 00111100 */
0x66, /* 01100110 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0x66, /* 01100110 */
0x3c, /* 00111100 */
0x00, /* 00000000 */
/* 68 0x44 'D' */
0xf8, /* 11111000 */
0x6c, /* 01101100 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x6c, /* 01101100 */
0xf8, /* 11111000 */
0x00, /* 00000000 */
/* 69 0x45 'E' */
0xfe, /* 11111110 */
0x62, /* 01100010 */
0x68, /* 01101000 */
0x78, /* 01111000 */
0x68, /* 01101000 */
0x62, /* 01100010 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
/* 70 0x46 'F' */
0xfe, /* 11111110 */
0x62, /* 01100010 */
0x68, /* 01101000 */
0x78, /* 01111000 */
0x68, /* 01101000 */
0x60, /* 01100000 */
0xf0, /* 11110000 */
0x00, /* 00000000 */
/* 71 0x47 'G' */
0x3c, /* 00111100 */
0x66, /* 01100110 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xce, /* 11001110 */
0x66, /* 01100110 */
0x3a, /* 00111010 */
0x00, /* 00000000 */
/* 72 0x48 'H' */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 73 0x49 'I' */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x00, /* 00000000 */
/* 74 0x4a 'J' */
0x1e, /* 00011110 */
0x0c, /* 00001100 */
0x0c, /* 00001100 */
0x0c, /* 00001100 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0x78, /* 01111000 */
0x00, /* 00000000 */
/* 75 0x4b 'K' */
0xe6, /* 11100110 */
0x66, /* 01100110 */
0x6c, /* 01101100 */
0x78, /* 01111000 */
0x6c, /* 01101100 */
0x66, /* 01100110 */
0xe6, /* 11100110 */
0x00, /* 00000000 */
/* 76 0x4c 'L' */
0xf0, /* 11110000 */
0x60, /* 01100000 */
0x60, /* 01100000 */
0x60, /* 01100000 */
0x62, /* 01100010 */
0x66, /* 01100110 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
/* 77 0x4d 'M' */
0xc6, /* 11000110 */
0xee, /* 11101110 */
0xfe, /* 11111110 */
0xfe, /* 11111110 */
0xd6, /* 11010110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 78 0x4e 'N' */
0xc6, /* 11000110 */
0xe6, /* 11100110 */
0xf6, /* 11110110 */
0xde, /* 11011110 */
0xce, /* 11001110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 79 0x4f 'O' */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 80 0x50 'P' */
0xfc, /* 11111100 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x7c, /* 01111100 */
0x60, /* 01100000 */
0x60, /* 01100000 */
0xf0, /* 11110000 */
0x00, /* 00000000 */
/* 81 0x51 'Q' */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xce, /* 11001110 */
0x7c, /* 01111100 */
0x0e, /* 00001110 */
/* 82 0x52 'R' */
0xfc, /* 11111100 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x7c, /* 01111100 */
0x6c, /* 01101100 */
0x66, /* 01100110 */
0xe6, /* 11100110 */
0x00, /* 00000000 */
/* 83 0x53 'S' */
0x3c, /* 00111100 */
0x66, /* 01100110 */
0x30, /* 00110000 */
0x18, /* 00011000 */
0x0c, /* 00001100 */
0x66, /* 01100110 */
0x3c, /* 00111100 */
0x00, /* 00000000 */
/* 84 0x54 'T' */
0x7e, /* 01111110 */
0x7e, /* 01111110 */
0x5a, /* 01011010 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x00, /* 00000000 */
/* 85 0x55 'U' */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 86 0x56 'V' */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x6c, /* 01101100 */
0x38, /* 00111000 */
0x00, /* 00000000 */
/* 87 0x57 'W' */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xd6, /* 11010110 */
0xd6, /* 11010110 */
0xfe, /* 11111110 */
0x6c, /* 01101100 */
0x00, /* 00000000 */
/* 88 0x58 'X' */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x6c, /* 01101100 */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 89 0x59 'Y' */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x00, /* 00000000 */
/* 90 0x5a 'Z' */
0xfe, /* 11111110 */
0xc6, /* 11000110 */
0x8c, /* 10001100 */
0x18, /* 00011000 */
0x32, /* 00110010 */
0x66, /* 01100110 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
/* 91 0x5b '[' */
0x3c, /* 00111100 */
0x30, /* 00110000 */
0x30, /* 00110000 */
0x30, /* 00110000 */
0x30, /* 00110000 */
0x30, /* 00110000 */
0x3c, /* 00111100 */
0x00, /* 00000000 */
/* 92 0x5c '\' */
0xc0, /* 11000000 */
0x60, /* 01100000 */
0x30, /* 00110000 */
0x18, /* 00011000 */
0x0c, /* 00001100 */
0x06, /* 00000110 */
0x02, /* 00000010 */
0x00, /* 00000000 */
/* 93 0x5d ']' */
0x3c, /* 00111100 */
0x0c, /* 00001100 */
0x0c, /* 00001100 */
0x0c, /* 00001100 */
0x0c, /* 00001100 */
0x0c, /* 00001100 */
0x3c, /* 00111100 */
0x00, /* 00000000 */
/* 94 0x5e '^' */
0x10, /* 00010000 */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 95 0x5f '_' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xff, /* 11111111 */
/* 96 0x60 '`' */
0x30, /* 00110000 */
0x18, /* 00011000 */
0x0c, /* 00001100 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 97 0x61 'a' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x78, /* 01111000 */
0x0c, /* 00001100 */
0x7c, /* 01111100 */
0xcc, /* 11001100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 98 0x62 'b' */
0xe0, /* 11100000 */
0x60, /* 01100000 */
0x7c, /* 01111100 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0xdc, /* 11011100 */
0x00, /* 00000000 */
/* 99 0x63 'c' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc0, /* 11000000 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 100 0x64 'd' */
0x1c, /* 00011100 */
0x0c, /* 00001100 */
0x7c, /* 01111100 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 101 0x65 'e' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0xc0, /* 11000000 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 102 0x66 'f' */
0x3c, /* 00111100 */
0x66, /* 01100110 */
0x60, /* 01100000 */
0xf8, /* 11111000 */
0x60, /* 01100000 */
0x60, /* 01100000 */
0xf0, /* 11110000 */
0x00, /* 00000000 */
/* 103 0x67 'g' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x76, /* 01110110 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0x7c, /* 01111100 */
0x0c, /* 00001100 */
0xf8, /* 11111000 */
/* 104 0x68 'h' */
0xe0, /* 11100000 */
0x60, /* 01100000 */
0x6c, /* 01101100 */
0x76, /* 01110110 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0xe6, /* 11100110 */
0x00, /* 00000000 */
/* 105 0x69 'i' */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x38, /* 00111000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x00, /* 00000000 */
/* 106 0x6a 'j' */
0x06, /* 00000110 */
0x00, /* 00000000 */
0x06, /* 00000110 */
0x06, /* 00000110 */
0x06, /* 00000110 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x3c, /* 00111100 */
/* 107 0x6b 'k' */
0xe0, /* 11100000 */
0x60, /* 01100000 */
0x66, /* 01100110 */
0x6c, /* 01101100 */
0x78, /* 01111000 */
0x6c, /* 01101100 */
0xe6, /* 11100110 */
0x00, /* 00000000 */
/* 108 0x6c 'l' */
0x38, /* 00111000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x00, /* 00000000 */
/* 109 0x6d 'm' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xec, /* 11101100 */
0xfe, /* 11111110 */
0xd6, /* 11010110 */
0xd6, /* 11010110 */
0xd6, /* 11010110 */
0x00, /* 00000000 */
/* 110 0x6e 'n' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xdc, /* 11011100 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x00, /* 00000000 */
/* 111 0x6f 'o' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 112 0x70 'p' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xdc, /* 11011100 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x7c, /* 01111100 */
0x60, /* 01100000 */
0xf0, /* 11110000 */
/* 113 0x71 'q' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x76, /* 01110110 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0x7c, /* 01111100 */
0x0c, /* 00001100 */
0x1e, /* 00011110 */
/* 114 0x72 'r' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xdc, /* 11011100 */
0x76, /* 01110110 */
0x60, /* 01100000 */
0x60, /* 01100000 */
0xf0, /* 11110000 */
0x00, /* 00000000 */
/* 115 0x73 's' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0xc0, /* 11000000 */
0x7c, /* 01111100 */
0x06, /* 00000110 */
0xfc, /* 11111100 */
0x00, /* 00000000 */
/* 116 0x74 't' */
0x30, /* 00110000 */
0x30, /* 00110000 */
0xfc, /* 11111100 */
0x30, /* 00110000 */
0x30, /* 00110000 */
0x36, /* 00110110 */
0x1c, /* 00011100 */
0x00, /* 00000000 */
/* 117 0x75 'u' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 118 0x76 'v' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x6c, /* 01101100 */
0x38, /* 00111000 */
0x00, /* 00000000 */
/* 119 0x77 'w' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xc6, /* 11000110 */
0xd6, /* 11010110 */
0xd6, /* 11010110 */
0xfe, /* 11111110 */
0x6c, /* 01101100 */
0x00, /* 00000000 */
/* 120 0x78 'x' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xc6, /* 11000110 */
0x6c, /* 01101100 */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 121 0x79 'y' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7e, /* 01111110 */
0x06, /* 00000110 */
0xfc, /* 11111100 */
/* 122 0x7a 'z' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0x4c, /* 01001100 */
0x18, /* 00011000 */
0x32, /* 00110010 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
/* 123 0x7b '{' */
0x0e, /* 00001110 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x70, /* 01110000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x0e, /* 00001110 */
0x00, /* 00000000 */
/* 124 0x7c '|' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 125 0x7d '}' */
0x70, /* 01110000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x0e, /* 00001110 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x70, /* 01110000 */
0x00, /* 00000000 */
/* 126 0x7e '~' */
0x76, /* 01110110 */
0xdc, /* 11011100 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 127 0x7f '' */
0x00, /* 00000000 */
0x10, /* 00010000 */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
/* 128 0x80 '' */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x0c, /* 00001100 */
0x78, /* 01111000 */
/* 129 0x81 '' */
0xcc, /* 11001100 */
0x00, /* 00000000 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 130 0x82 '' */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0xc0, /* 11000000 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 131 0x83 '' */
0x7c, /* 01111100 */
0x82, /* 10000010 */
0x78, /* 01111000 */
0x0c, /* 00001100 */
0x7c, /* 01111100 */
0xcc, /* 11001100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 132 0x84 '' */
0xc6, /* 11000110 */
0x00, /* 00000000 */
0x78, /* 01111000 */
0x0c, /* 00001100 */
0x7c, /* 01111100 */
0xcc, /* 11001100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 133 0x85 '
' */
0x30, /* 00110000 */
0x18, /* 00011000 */
0x78, /* 01111000 */
0x0c, /* 00001100 */
0x7c, /* 01111100 */
0xcc, /* 11001100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 134 0x86 '' */
0x30, /* 00110000 */
0x30, /* 00110000 */
0x78, /* 01111000 */
0x0c, /* 00001100 */
0x7c, /* 01111100 */
0xcc, /* 11001100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 135 0x87 '' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0x7e, /* 01111110 */
0x0c, /* 00001100 */
0x38, /* 00111000 */
/* 136 0x88 '' */
0x7c, /* 01111100 */
0x82, /* 10000010 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0xc0, /* 11000000 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 137 0x89 '' */
0xc6, /* 11000110 */
0x00, /* 00000000 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0xc0, /* 11000000 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 138 0x8a '' */
0x30, /* 00110000 */
0x18, /* 00011000 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0xc0, /* 11000000 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 139 0x8b '' */
0x66, /* 01100110 */
0x00, /* 00000000 */
0x38, /* 00111000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x00, /* 00000000 */
/* 140 0x8c '' */
0x7c, /* 01111100 */
0x82, /* 10000010 */
0x38, /* 00111000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x00, /* 00000000 */
/* 141 0x8d '' */
0x30, /* 00110000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x38, /* 00111000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x00, /* 00000000 */
/* 142 0x8e '' */
0xc6, /* 11000110 */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 143 0x8f '' */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 144 0x90 '' */
0x18, /* 00011000 */
0x30, /* 00110000 */
0xfe, /* 11111110 */
0xc0, /* 11000000 */
0xf8, /* 11111000 */
0xc0, /* 11000000 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
/* 145 0x91 '' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0x18, /* 00011000 */
0x7e, /* 01111110 */
0xd8, /* 11011000 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
/* 146 0x92 '' */
0x3e, /* 00111110 */
0x6c, /* 01101100 */
0xcc, /* 11001100 */
0xfe, /* 11111110 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xce, /* 11001110 */
0x00, /* 00000000 */
/* 147 0x93 '' */
0x7c, /* 01111100 */
0x82, /* 10000010 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 148 0x94 '' */
0xc6, /* 11000110 */
0x00, /* 00000000 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 149 0x95 '' */
0x30, /* 00110000 */
0x18, /* 00011000 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 150 0x96 '' */
0x78, /* 01111000 */
0x84, /* 10000100 */
0x00, /* 00000000 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 151 0x97 '' */
0x60, /* 01100000 */
0x30, /* 00110000 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 152 0x98 '' */
0xc6, /* 11000110 */
0x00, /* 00000000 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7e, /* 01111110 */
0x06, /* 00000110 */
0xfc, /* 11111100 */
/* 153 0x99 '' */
0xc6, /* 11000110 */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x6c, /* 01101100 */
0x38, /* 00111000 */
0x00, /* 00000000 */
/* 154 0x9a '' */
0xc6, /* 11000110 */
0x00, /* 00000000 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 155 0x9b '' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x7e, /* 01111110 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0x7e, /* 01111110 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 156 0x9c '' */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0x64, /* 01100100 */
0xf0, /* 11110000 */
0x60, /* 01100000 */
0x66, /* 01100110 */
0xfc, /* 11111100 */
0x00, /* 00000000 */
/* 157 0x9d '' */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x3c, /* 00111100 */
0x7e, /* 01111110 */
0x18, /* 00011000 */
0x7e, /* 01111110 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 158 0x9e '' */
0xf8, /* 11111000 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xfa, /* 11111010 */
0xc6, /* 11000110 */
0xcf, /* 11001111 */
0xc6, /* 11000110 */
0xc7, /* 11000111 */
/* 159 0x9f '' */
0x0e, /* 00001110 */
0x1b, /* 00011011 */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0xd8, /* 11011000 */
0x70, /* 01110000 */
0x00, /* 00000000 */
/* 160 0xa0 ' ' */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x78, /* 01111000 */
0x0c, /* 00001100 */
0x7c, /* 01111100 */
0xcc, /* 11001100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 161 0xa1 '¡' */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x38, /* 00111000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x00, /* 00000000 */
/* 162 0xa2 '¢' */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 163 0xa3 '£' */
0x18, /* 00011000 */
0x30, /* 00110000 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 164 0xa4 '¤' */
0x76, /* 01110110 */
0xdc, /* 11011100 */
0x00, /* 00000000 */
0xdc, /* 11011100 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x00, /* 00000000 */
/* 165 0xa5 '¥' */
0x76, /* 01110110 */
0xdc, /* 11011100 */
0x00, /* 00000000 */
0xe6, /* 11100110 */
0xf6, /* 11110110 */
0xde, /* 11011110 */
0xce, /* 11001110 */
0x00, /* 00000000 */
/* 166 0xa6 '¦' */
0x3c, /* 00111100 */
0x6c, /* 01101100 */
0x6c, /* 01101100 */
0x3e, /* 00111110 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 167 0xa7 '§' */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0x6c, /* 01101100 */
0x38, /* 00111000 */
0x00, /* 00000000 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 168 0xa8 '¨' */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x63, /* 01100011 */
0x3e, /* 00111110 */
0x00, /* 00000000 */
/* 169 0xa9 '©' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xfe, /* 11111110 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 170 0xaa 'ª' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xfe, /* 11111110 */
0x06, /* 00000110 */
0x06, /* 00000110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 171 0xab '«' */
0x63, /* 01100011 */
0xe6, /* 11100110 */
0x6c, /* 01101100 */
0x7e, /* 01111110 */
0x33, /* 00110011 */
0x66, /* 01100110 */
0xcc, /* 11001100 */
0x0f, /* 00001111 */
/* 172 0xac '¬' */
0x63, /* 01100011 */
0xe6, /* 11100110 */
0x6c, /* 01101100 */
0x7a, /* 01111010 */
0x36, /* 00110110 */
0x6a, /* 01101010 */
0xdf, /* 11011111 */
0x06, /* 00000110 */
/* 173 0xad '' */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 174 0xae '®' */
0x00, /* 00000000 */
0x33, /* 00110011 */
0x66, /* 01100110 */
0xcc, /* 11001100 */
0x66, /* 01100110 */
0x33, /* 00110011 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 175 0xaf '¯' */
0x00, /* 00000000 */
0xcc, /* 11001100 */
0x66, /* 01100110 */
0x33, /* 00110011 */
0x66, /* 01100110 */
0xcc, /* 11001100 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 176 0xb0 '°' */
0x22, /* 00100010 */
0x88, /* 10001000 */
0x22, /* 00100010 */
0x88, /* 10001000 */
0x22, /* 00100010 */
0x88, /* 10001000 */
0x22, /* 00100010 */
0x88, /* 10001000 */
/* 177 0xb1 '±' */
0x55, /* 01010101 */
0xaa, /* 10101010 */
0x55, /* 01010101 */
0xaa, /* 10101010 */
0x55, /* 01010101 */
0xaa, /* 10101010 */
0x55, /* 01010101 */
0xaa, /* 10101010 */
/* 178 0xb2 '²' */
0x77, /* 01110111 */
0xdd, /* 11011101 */
0x77, /* 01110111 */
0xdd, /* 11011101 */
0x77, /* 01110111 */
0xdd, /* 11011101 */
0x77, /* 01110111 */
0xdd, /* 11011101 */
/* 179 0xb3 '³' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 180 0xb4 '´' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0xf8, /* 11111000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 181 0xb5 'µ' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0xf8, /* 11111000 */
0x18, /* 00011000 */
0xf8, /* 11111000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 182 0xb6 '¶' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0xf6, /* 11110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 183 0xb7 '·' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xfe, /* 11111110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 184 0xb8 '¸' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xf8, /* 11111000 */
0x18, /* 00011000 */
0xf8, /* 11111000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 185 0xb9 '¹' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0xf6, /* 11110110 */
0x06, /* 00000110 */
0xf6, /* 11110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 186 0xba 'º' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 187 0xbb '»' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xfe, /* 11111110 */
0x06, /* 00000110 */
0xf6, /* 11110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 188 0xbc '¼' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0xf6, /* 11110110 */
0x06, /* 00000110 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 189 0xbd '½' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 190 0xbe '¾' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0xf8, /* 11111000 */
0x18, /* 00011000 */
0xf8, /* 11111000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 191 0xbf '¿' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xf8, /* 11111000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 192 0xc0 'À' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x1f, /* 00011111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 193 0xc1 'Á' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 194 0xc2 'Â' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xff, /* 11111111 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 195 0xc3 'Ã' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x1f, /* 00011111 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 196 0xc4 'Ä' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 197 0xc5 'Å' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0xff, /* 11111111 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 198 0xc6 'Æ' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x1f, /* 00011111 */
0x18, /* 00011000 */
0x1f, /* 00011111 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 199 0xc7 'Ç' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x37, /* 00110111 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 200 0xc8 'È' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x37, /* 00110111 */
0x30, /* 00110000 */
0x3f, /* 00111111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 201 0xc9 'É' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x3f, /* 00111111 */
0x30, /* 00110000 */
0x37, /* 00110111 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 202 0xca 'Ê' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0xf7, /* 11110111 */
0x00, /* 00000000 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 203 0xcb 'Ë' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0xf7, /* 11110111 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 204 0xcc 'Ì' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x37, /* 00110111 */
0x30, /* 00110000 */
0x37, /* 00110111 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 205 0xcd 'Í' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 206 0xce 'Î' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0xf7, /* 11110111 */
0x00, /* 00000000 */
0xf7, /* 11110111 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 207 0xcf 'Ï' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 208 0xd0 'Ð' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 209 0xd1 'Ñ' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0xff, /* 11111111 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 210 0xd2 'Ò' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xff, /* 11111111 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 211 0xd3 'Ó' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x3f, /* 00111111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 212 0xd4 'Ô' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x1f, /* 00011111 */
0x18, /* 00011000 */
0x1f, /* 00011111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 213 0xd5 'Õ' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x1f, /* 00011111 */
0x18, /* 00011000 */
0x1f, /* 00011111 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 214 0xd6 'Ö' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x3f, /* 00111111 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 215 0xd7 '×' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0xff, /* 11111111 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 216 0xd8 'Ø' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0xff, /* 11111111 */
0x18, /* 00011000 */
0xff, /* 11111111 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 217 0xd9 'Ù' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0xf8, /* 11111000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 218 0xda 'Ú' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x1f, /* 00011111 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 219 0xdb 'Û' */
0xff, /* 11111111 */
0xff, /* 11111111 */
0xff, /* 11111111 */
0xff, /* 11111111 */
0xff, /* 11111111 */
0xff, /* 11111111 */
0xff, /* 11111111 */
0xff, /* 11111111 */
/* 220 0xdc 'Ü' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xff, /* 11111111 */
0xff, /* 11111111 */
0xff, /* 11111111 */
0xff, /* 11111111 */
/* 221 0xdd 'Ý' */
0xf0, /* 11110000 */
0xf0, /* 11110000 */
0xf0, /* 11110000 */
0xf0, /* 11110000 */
0xf0, /* 11110000 */
0xf0, /* 11110000 */
0xf0, /* 11110000 */
0xf0, /* 11110000 */
/* 222 0xde 'Þ' */
0x0f, /* 00001111 */
0x0f, /* 00001111 */
0x0f, /* 00001111 */
0x0f, /* 00001111 */
0x0f, /* 00001111 */
0x0f, /* 00001111 */
0x0f, /* 00001111 */
0x0f, /* 00001111 */
/* 223 0xdf 'ß' */
0xff, /* 11111111 */
0xff, /* 11111111 */
0xff, /* 11111111 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 224 0xe0 'à' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x76, /* 01110110 */
0xdc, /* 11011100 */
0xc8, /* 11001000 */
0xdc, /* 11011100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 225 0xe1 'á' */
0x78, /* 01111000 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xd8, /* 11011000 */
0xcc, /* 11001100 */
0xc6, /* 11000110 */
0xcc, /* 11001100 */
0x00, /* 00000000 */
/* 226 0xe2 'â' */
0xfe, /* 11111110 */
0xc6, /* 11000110 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0x00, /* 00000000 */
/* 227 0xe3 'ã' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xfe, /* 11111110 */
0x6c, /* 01101100 */
0x6c, /* 01101100 */
0x6c, /* 01101100 */
0x6c, /* 01101100 */
0x00, /* 00000000 */
/* 228 0xe4 'ä' */
0xfe, /* 11111110 */
0xc6, /* 11000110 */
0x60, /* 01100000 */
0x30, /* 00110000 */
0x60, /* 01100000 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
/* 229 0xe5 'å' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0xd8, /* 11011000 */
0xd8, /* 11011000 */
0xd8, /* 11011000 */
0x70, /* 01110000 */
0x00, /* 00000000 */
/* 230 0xe6 'æ' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x7c, /* 01111100 */
0xc0, /* 11000000 */
/* 231 0xe7 'ç' */
0x00, /* 00000000 */
0x76, /* 01110110 */
0xdc, /* 11011100 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 232 0xe8 'è' */
0x7e, /* 01111110 */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0x7e, /* 01111110 */
/* 233 0xe9 'é' */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0xc6, /* 11000110 */
0x6c, /* 01101100 */
0x38, /* 00111000 */
0x00, /* 00000000 */
/* 234 0xea 'ê' */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x6c, /* 01101100 */
0x6c, /* 01101100 */
0xee, /* 11101110 */
0x00, /* 00000000 */
/* 235 0xeb 'ë' */
0x0e, /* 00001110 */
0x18, /* 00011000 */
0x0c, /* 00001100 */
0x3e, /* 00111110 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x3c, /* 00111100 */
0x00, /* 00000000 */
/* 236 0xec 'ì' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0xdb, /* 11011011 */
0xdb, /* 11011011 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 237 0xed 'í' */
0x06, /* 00000110 */
0x0c, /* 00001100 */
0x7e, /* 01111110 */
0xdb, /* 11011011 */
0xdb, /* 11011011 */
0x7e, /* 01111110 */
0x60, /* 01100000 */
0xc0, /* 11000000 */
/* 238 0xee 'î' */
0x1e, /* 00011110 */
0x30, /* 00110000 */
0x60, /* 01100000 */
0x7e, /* 01111110 */
0x60, /* 01100000 */
0x30, /* 00110000 */
0x1e, /* 00011110 */
0x00, /* 00000000 */
/* 239 0xef 'ï' */
0x00, /* 00000000 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 240 0xf0 'ð' */
0x00, /* 00000000 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 241 0xf1 'ñ' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x7e, /* 01111110 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
/* 242 0xf2 'ò' */
0x30, /* 00110000 */
0x18, /* 00011000 */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
/* 243 0xf3 'ó' */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x18, /* 00011000 */
0x0c, /* 00001100 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
/* 244 0xf4 'ô' */
0x0e, /* 00001110 */
0x1b, /* 00011011 */
0x1b, /* 00011011 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 245 0xf5 'õ' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0xd8, /* 11011000 */
0xd8, /* 11011000 */
0x70, /* 01110000 */
/* 246 0xf6 'ö' */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 247 0xf7 '÷' */
0x00, /* 00000000 */
0x76, /* 01110110 */
0xdc, /* 11011100 */
0x00, /* 00000000 */
0x76, /* 01110110 */
0xdc, /* 11011100 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 248 0xf8 'ø' */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0x6c, /* 01101100 */
0x38, /* 00111000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 249 0xf9 'ù' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 250 0xfa 'ú' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 251 0xfb 'û' */
0x0f, /* 00001111 */
0x0c, /* 00001100 */
0x0c, /* 00001100 */
0x0c, /* 00001100 */
0xec, /* 11101100 */
0x6c, /* 01101100 */
0x3c, /* 00111100 */
0x1c, /* 00011100 */
/* 252 0xfc 'ü' */
0x6c, /* 01101100 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 253 0xfd 'ý' */
0x78, /* 01111000 */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 254 0xfe 'þ' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x3c, /* 00111100 */
0x3c, /* 00111100 */
0x3c, /* 00111100 */
0x3c, /* 00111100 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 255 0xff 'ÿ' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
};
const struct font_desc font_vga_8x8 = {
.idx = VGA8x8_IDX,
.name = "VGA8x8",
.width = 8,
.height = 8,
.data = fontdata_8x8,
.pref = 0,
};
| gpl-2.0 |
bbbLinux/kernel | arch/s390/pci/pci.c | 95 | 25717 | /*
* Copyright IBM Corp. 2012
*
* Author(s):
* Jan Glauber <jang@linux.vnet.ibm.com>
*
* The System z PCI code is a rewrite from a prototype by
* the following people (Kudoz!):
* Alexander Schmidt
* Christoph Raisch
* Hannes Hering
* Hoang-Nam Nguyen
* Jan-Bernd Themann
* Stefan Roscher
* Thomas Klein
*/
#define COMPONENT "zPCI"
#define pr_fmt(fmt) COMPONENT ": " fmt
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/err.h>
#include <linux/export.h>
#include <linux/delay.h>
#include <linux/irq.h>
#include <linux/kernel_stat.h>
#include <linux/seq_file.h>
#include <linux/pci.h>
#include <linux/msi.h>
#include <asm/isc.h>
#include <asm/airq.h>
#include <asm/facility.h>
#include <asm/pci_insn.h>
#include <asm/pci_clp.h>
#include <asm/pci_dma.h>
#define DEBUG /* enable pr_debug */
#define SIC_IRQ_MODE_ALL 0
#define SIC_IRQ_MODE_SINGLE 1
#define ZPCI_NR_DMA_SPACES 1
#define ZPCI_MSI_VEC_BITS 6
#define ZPCI_NR_DEVICES CONFIG_PCI_NR_FUNCTIONS
/* list of all detected zpci devices */
LIST_HEAD(zpci_list);
EXPORT_SYMBOL_GPL(zpci_list);
DEFINE_MUTEX(zpci_list_lock);
EXPORT_SYMBOL_GPL(zpci_list_lock);
struct pci_hp_callback_ops hotplug_ops;
EXPORT_SYMBOL_GPL(hotplug_ops);
static DECLARE_BITMAP(zpci_domain, ZPCI_NR_DEVICES);
static DEFINE_SPINLOCK(zpci_domain_lock);
struct callback {
irq_handler_t handler;
void *data;
};
struct zdev_irq_map {
unsigned long aibv; /* AI bit vector */
int msi_vecs; /* consecutive MSI-vectors used */
int __unused;
struct callback cb[ZPCI_NR_MSI_VECS]; /* callback handler array */
spinlock_t lock; /* protect callbacks against de-reg */
};
struct intr_bucket {
/* amap of adapters, one bit per dev, corresponds to one irq nr */
unsigned long *alloc;
/* AI summary bit, global page for all devices */
unsigned long *aisb;
/* pointer to aibv and callback data in zdev */
struct zdev_irq_map *imap[ZPCI_NR_DEVICES];
/* protects the whole bucket struct */
spinlock_t lock;
};
static struct intr_bucket *bucket;
/* Adapter local summary indicator */
static u8 *zpci_irq_si;
static atomic_t irq_retries = ATOMIC_INIT(0);
/* I/O Map */
static DEFINE_SPINLOCK(zpci_iomap_lock);
static DECLARE_BITMAP(zpci_iomap, ZPCI_IOMAP_MAX_ENTRIES);
struct zpci_iomap_entry *zpci_iomap_start;
EXPORT_SYMBOL_GPL(zpci_iomap_start);
/* highest irq summary bit */
static int __read_mostly aisb_max;
static struct kmem_cache *zdev_irq_cache;
static struct kmem_cache *zdev_fmb_cache;
debug_info_t *pci_debug_msg_id;
debug_info_t *pci_debug_err_id;
static inline int irq_to_msi_nr(unsigned int irq)
{
return irq & ZPCI_MSI_MASK;
}
static inline int irq_to_dev_nr(unsigned int irq)
{
return irq >> ZPCI_MSI_VEC_BITS;
}
static inline struct zdev_irq_map *get_imap(unsigned int irq)
{
return bucket->imap[irq_to_dev_nr(irq)];
}
struct zpci_dev *get_zdev(struct pci_dev *pdev)
{
return (struct zpci_dev *) pdev->sysdata;
}
struct zpci_dev *get_zdev_by_fid(u32 fid)
{
struct zpci_dev *tmp, *zdev = NULL;
mutex_lock(&zpci_list_lock);
list_for_each_entry(tmp, &zpci_list, entry) {
if (tmp->fid == fid) {
zdev = tmp;
break;
}
}
mutex_unlock(&zpci_list_lock);
return zdev;
}
bool zpci_fid_present(u32 fid)
{
return (get_zdev_by_fid(fid) != NULL) ? true : false;
}
static struct zpci_dev *get_zdev_by_bus(struct pci_bus *bus)
{
return (bus && bus->sysdata) ? (struct zpci_dev *) bus->sysdata : NULL;
}
int pci_domain_nr(struct pci_bus *bus)
{
return ((struct zpci_dev *) bus->sysdata)->domain;
}
EXPORT_SYMBOL_GPL(pci_domain_nr);
int pci_proc_domain(struct pci_bus *bus)
{
return pci_domain_nr(bus);
}
EXPORT_SYMBOL_GPL(pci_proc_domain);
/* Modify PCI: Register adapter interruptions */
static int zpci_register_airq(struct zpci_dev *zdev, unsigned int aisb,
u64 aibv)
{
u64 req = ZPCI_CREATE_REQ(zdev->fh, 0, ZPCI_MOD_FC_REG_INT);
struct zpci_fib *fib;
int rc;
fib = (void *) get_zeroed_page(GFP_KERNEL);
if (!fib)
return -ENOMEM;
fib->isc = PCI_ISC;
fib->noi = zdev->irq_map->msi_vecs;
fib->sum = 1; /* enable summary notifications */
fib->aibv = aibv;
fib->aibvo = 0; /* every function has its own page */
fib->aisb = (u64) bucket->aisb + aisb / 8;
fib->aisbo = aisb & ZPCI_MSI_MASK;
rc = mpcifc_instr(req, fib);
pr_debug("%s mpcifc returned noi: %d\n", __func__, fib->noi);
free_page((unsigned long) fib);
return rc;
}
struct mod_pci_args {
u64 base;
u64 limit;
u64 iota;
u64 fmb_addr;
};
static int mod_pci(struct zpci_dev *zdev, int fn, u8 dmaas, struct mod_pci_args *args)
{
u64 req = ZPCI_CREATE_REQ(zdev->fh, dmaas, fn);
struct zpci_fib *fib;
int rc;
/* The FIB must be available even if it's not used */
fib = (void *) get_zeroed_page(GFP_KERNEL);
if (!fib)
return -ENOMEM;
fib->pba = args->base;
fib->pal = args->limit;
fib->iota = args->iota;
fib->fmb_addr = args->fmb_addr;
rc = mpcifc_instr(req, fib);
free_page((unsigned long) fib);
return rc;
}
/* Modify PCI: Register I/O address translation parameters */
int zpci_register_ioat(struct zpci_dev *zdev, u8 dmaas,
u64 base, u64 limit, u64 iota)
{
struct mod_pci_args args = { base, limit, iota, 0 };
WARN_ON_ONCE(iota & 0x3fff);
args.iota |= ZPCI_IOTA_RTTO_FLAG;
return mod_pci(zdev, ZPCI_MOD_FC_REG_IOAT, dmaas, &args);
}
/* Modify PCI: Unregister I/O address translation parameters */
int zpci_unregister_ioat(struct zpci_dev *zdev, u8 dmaas)
{
struct mod_pci_args args = { 0, 0, 0, 0 };
return mod_pci(zdev, ZPCI_MOD_FC_DEREG_IOAT, dmaas, &args);
}
/* Modify PCI: Unregister adapter interruptions */
static int zpci_unregister_airq(struct zpci_dev *zdev)
{
struct mod_pci_args args = { 0, 0, 0, 0 };
return mod_pci(zdev, ZPCI_MOD_FC_DEREG_INT, 0, &args);
}
/* Modify PCI: Set PCI function measurement parameters */
int zpci_fmb_enable_device(struct zpci_dev *zdev)
{
struct mod_pci_args args = { 0, 0, 0, 0 };
if (zdev->fmb)
return -EINVAL;
zdev->fmb = kmem_cache_alloc(zdev_fmb_cache, GFP_KERNEL);
if (!zdev->fmb)
return -ENOMEM;
memset(zdev->fmb, 0, sizeof(*zdev->fmb));
WARN_ON((u64) zdev->fmb & 0xf);
args.fmb_addr = virt_to_phys(zdev->fmb);
return mod_pci(zdev, ZPCI_MOD_FC_SET_MEASURE, 0, &args);
}
/* Modify PCI: Disable PCI function measurement */
int zpci_fmb_disable_device(struct zpci_dev *zdev)
{
struct mod_pci_args args = { 0, 0, 0, 0 };
int rc;
if (!zdev->fmb)
return -EINVAL;
/* Function measurement is disabled if fmb address is zero */
rc = mod_pci(zdev, ZPCI_MOD_FC_SET_MEASURE, 0, &args);
kmem_cache_free(zdev_fmb_cache, zdev->fmb);
zdev->fmb = NULL;
return rc;
}
#define ZPCI_PCIAS_CFGSPC 15
static int zpci_cfg_load(struct zpci_dev *zdev, int offset, u32 *val, u8 len)
{
u64 req = ZPCI_CREATE_REQ(zdev->fh, ZPCI_PCIAS_CFGSPC, len);
u64 data;
int rc;
rc = pcilg_instr(&data, req, offset);
data = data << ((8 - len) * 8);
data = le64_to_cpu(data);
if (!rc)
*val = (u32) data;
else
*val = 0xffffffff;
return rc;
}
static int zpci_cfg_store(struct zpci_dev *zdev, int offset, u32 val, u8 len)
{
u64 req = ZPCI_CREATE_REQ(zdev->fh, ZPCI_PCIAS_CFGSPC, len);
u64 data = val;
int rc;
data = cpu_to_le64(data);
data = data >> ((8 - len) * 8);
rc = pcistg_instr(data, req, offset);
return rc;
}
void synchronize_irq(unsigned int irq)
{
/*
* Not needed, the handler is protected by a lock and IRQs that occur
* after the handler is deleted are just NOPs.
*/
}
EXPORT_SYMBOL_GPL(synchronize_irq);
void enable_irq(unsigned int irq)
{
struct msi_desc *msi = irq_get_msi_desc(irq);
zpci_msi_set_mask_bits(msi, 1, 0);
}
EXPORT_SYMBOL_GPL(enable_irq);
void disable_irq(unsigned int irq)
{
struct msi_desc *msi = irq_get_msi_desc(irq);
zpci_msi_set_mask_bits(msi, 1, 1);
}
EXPORT_SYMBOL_GPL(disable_irq);
void disable_irq_nosync(unsigned int irq)
{
disable_irq(irq);
}
EXPORT_SYMBOL_GPL(disable_irq_nosync);
unsigned long probe_irq_on(void)
{
return 0;
}
EXPORT_SYMBOL_GPL(probe_irq_on);
int probe_irq_off(unsigned long val)
{
return 0;
}
EXPORT_SYMBOL_GPL(probe_irq_off);
unsigned int probe_irq_mask(unsigned long val)
{
return val;
}
EXPORT_SYMBOL_GPL(probe_irq_mask);
void pcibios_fixup_bus(struct pci_bus *bus)
{
}
resource_size_t pcibios_align_resource(void *data, const struct resource *res,
resource_size_t size,
resource_size_t align)
{
return 0;
}
/* combine single writes by using store-block insn */
void __iowrite64_copy(void __iomem *to, const void *from, size_t count)
{
zpci_memcpy_toio(to, from, count);
}
/* Create a virtual mapping cookie for a PCI BAR */
void __iomem *pci_iomap(struct pci_dev *pdev, int bar, unsigned long max)
{
struct zpci_dev *zdev = get_zdev(pdev);
u64 addr;
int idx;
if ((bar & 7) != bar)
return NULL;
idx = zdev->bars[bar].map_idx;
spin_lock(&zpci_iomap_lock);
zpci_iomap_start[idx].fh = zdev->fh;
zpci_iomap_start[idx].bar = bar;
spin_unlock(&zpci_iomap_lock);
addr = ZPCI_IOMAP_ADDR_BASE | ((u64) idx << 48);
return (void __iomem *) addr;
}
EXPORT_SYMBOL_GPL(pci_iomap);
void pci_iounmap(struct pci_dev *pdev, void __iomem *addr)
{
unsigned int idx;
idx = (((__force u64) addr) & ~ZPCI_IOMAP_ADDR_BASE) >> 48;
spin_lock(&zpci_iomap_lock);
zpci_iomap_start[idx].fh = 0;
zpci_iomap_start[idx].bar = 0;
spin_unlock(&zpci_iomap_lock);
}
EXPORT_SYMBOL_GPL(pci_iounmap);
static int pci_read(struct pci_bus *bus, unsigned int devfn, int where,
int size, u32 *val)
{
struct zpci_dev *zdev = get_zdev_by_bus(bus);
if (!zdev || devfn != ZPCI_DEVFN)
return 0;
return zpci_cfg_load(zdev, where, val, size);
}
static int pci_write(struct pci_bus *bus, unsigned int devfn, int where,
int size, u32 val)
{
struct zpci_dev *zdev = get_zdev_by_bus(bus);
if (!zdev || devfn != ZPCI_DEVFN)
return 0;
return zpci_cfg_store(zdev, where, val, size);
}
static struct pci_ops pci_root_ops = {
.read = pci_read,
.write = pci_write,
};
/* store the last handled bit to implement fair scheduling of devices */
static DEFINE_PER_CPU(unsigned long, next_sbit);
static void zpci_irq_handler(void *dont, void *need)
{
unsigned long sbit, mbit, last = 0, start = __get_cpu_var(next_sbit);
int rescan = 0, max = aisb_max;
struct zdev_irq_map *imap;
inc_irq_stat(IRQIO_PCI);
sbit = start;
scan:
/* find summary_bit */
for_each_set_bit_left_cont(sbit, bucket->aisb, max) {
clear_bit(63 - (sbit & 63), bucket->aisb + (sbit >> 6));
last = sbit;
/* find vector bit */
imap = bucket->imap[sbit];
for_each_set_bit_left(mbit, &imap->aibv, imap->msi_vecs) {
inc_irq_stat(IRQIO_MSI);
clear_bit(63 - mbit, &imap->aibv);
spin_lock(&imap->lock);
if (imap->cb[mbit].handler)
imap->cb[mbit].handler(mbit,
imap->cb[mbit].data);
spin_unlock(&imap->lock);
}
}
if (rescan)
goto out;
/* scan the skipped bits */
if (start > 0) {
sbit = 0;
max = start;
start = 0;
goto scan;
}
/* enable interrupts again */
sic_instr(SIC_IRQ_MODE_SINGLE, NULL, PCI_ISC);
/* check again to not lose initiative */
rmb();
max = aisb_max;
sbit = find_first_bit_left(bucket->aisb, max);
if (sbit != max) {
atomic_inc(&irq_retries);
rescan++;
goto scan;
}
out:
/* store next device bit to scan */
__get_cpu_var(next_sbit) = (++last >= aisb_max) ? 0 : last;
}
/* msi_vecs - number of requested interrupts, 0 place function to error state */
static int zpci_setup_msi(struct pci_dev *pdev, int msi_vecs)
{
struct zpci_dev *zdev = get_zdev(pdev);
unsigned int aisb, msi_nr;
struct msi_desc *msi;
int rc;
/* store the number of used MSI vectors */
zdev->irq_map->msi_vecs = min(msi_vecs, ZPCI_NR_MSI_VECS);
spin_lock(&bucket->lock);
aisb = find_first_zero_bit(bucket->alloc, PAGE_SIZE);
/* alloc map exhausted? */
if (aisb == PAGE_SIZE) {
spin_unlock(&bucket->lock);
return -EIO;
}
set_bit(aisb, bucket->alloc);
spin_unlock(&bucket->lock);
zdev->aisb = aisb;
if (aisb + 1 > aisb_max)
aisb_max = aisb + 1;
/* wire up IRQ shortcut pointer */
bucket->imap[zdev->aisb] = zdev->irq_map;
pr_debug("%s: imap[%u] linked to %p\n", __func__, zdev->aisb, zdev->irq_map);
/* TODO: irq number 0 wont be found if we return less than requested MSIs.
* ignore it for now and fix in common code.
*/
msi_nr = aisb << ZPCI_MSI_VEC_BITS;
list_for_each_entry(msi, &pdev->msi_list, list) {
rc = zpci_setup_msi_irq(zdev, msi, msi_nr,
aisb << ZPCI_MSI_VEC_BITS);
if (rc)
return rc;
msi_nr++;
}
rc = zpci_register_airq(zdev, aisb, (u64) &zdev->irq_map->aibv);
if (rc) {
clear_bit(aisb, bucket->alloc);
dev_err(&pdev->dev, "register MSI failed with: %d\n", rc);
return rc;
}
return (zdev->irq_map->msi_vecs == msi_vecs) ?
0 : zdev->irq_map->msi_vecs;
}
static void zpci_teardown_msi(struct pci_dev *pdev)
{
struct zpci_dev *zdev = get_zdev(pdev);
struct msi_desc *msi;
int aisb, rc;
rc = zpci_unregister_airq(zdev);
if (rc) {
dev_err(&pdev->dev, "deregister MSI failed with: %d\n", rc);
return;
}
msi = list_first_entry(&pdev->msi_list, struct msi_desc, list);
aisb = irq_to_dev_nr(msi->irq);
list_for_each_entry(msi, &pdev->msi_list, list)
zpci_teardown_msi_irq(zdev, msi);
clear_bit(aisb, bucket->alloc);
if (aisb + 1 == aisb_max)
aisb_max--;
}
int arch_setup_msi_irqs(struct pci_dev *pdev, int nvec, int type)
{
pr_debug("%s: requesting %d MSI-X interrupts...", __func__, nvec);
if (type != PCI_CAP_ID_MSIX && type != PCI_CAP_ID_MSI)
return -EINVAL;
return zpci_setup_msi(pdev, nvec);
}
void arch_teardown_msi_irqs(struct pci_dev *pdev)
{
pr_info("%s: on pdev: %p\n", __func__, pdev);
zpci_teardown_msi(pdev);
}
static void zpci_map_resources(struct zpci_dev *zdev)
{
struct pci_dev *pdev = zdev->pdev;
resource_size_t len;
int i;
for (i = 0; i < PCI_BAR_COUNT; i++) {
len = pci_resource_len(pdev, i);
if (!len)
continue;
pdev->resource[i].start = (resource_size_t) pci_iomap(pdev, i, 0);
pdev->resource[i].end = pdev->resource[i].start + len - 1;
pr_debug("BAR%i: -> start: %Lx end: %Lx\n",
i, pdev->resource[i].start, pdev->resource[i].end);
}
};
static void zpci_unmap_resources(struct pci_dev *pdev)
{
resource_size_t len;
int i;
for (i = 0; i < PCI_BAR_COUNT; i++) {
len = pci_resource_len(pdev, i);
if (!len)
continue;
pci_iounmap(pdev, (void *) pdev->resource[i].start);
}
};
struct zpci_dev *zpci_alloc_device(void)
{
struct zpci_dev *zdev;
/* Alloc memory for our private pci device data */
zdev = kzalloc(sizeof(*zdev), GFP_KERNEL);
if (!zdev)
return ERR_PTR(-ENOMEM);
/* Alloc aibv & callback space */
zdev->irq_map = kmem_cache_zalloc(zdev_irq_cache, GFP_KERNEL);
if (!zdev->irq_map)
goto error;
WARN_ON((u64) zdev->irq_map & 0xff);
return zdev;
error:
kfree(zdev);
return ERR_PTR(-ENOMEM);
}
void zpci_free_device(struct zpci_dev *zdev)
{
kmem_cache_free(zdev_irq_cache, zdev->irq_map);
kfree(zdev);
}
/* Called on removal of pci_dev, leaves zpci and bus device */
static void zpci_remove_device(struct pci_dev *pdev)
{
struct zpci_dev *zdev = get_zdev(pdev);
dev_info(&pdev->dev, "Removing device %u\n", zdev->domain);
zdev->state = ZPCI_FN_STATE_CONFIGURED;
zpci_dma_exit_device(zdev);
zpci_fmb_disable_device(zdev);
zpci_sysfs_remove_device(&pdev->dev);
zpci_unmap_resources(pdev);
list_del(&zdev->entry); /* can be called from init */
zdev->pdev = NULL;
}
static void zpci_scan_devices(void)
{
struct zpci_dev *zdev;
mutex_lock(&zpci_list_lock);
list_for_each_entry(zdev, &zpci_list, entry)
if (zdev->state == ZPCI_FN_STATE_CONFIGURED)
zpci_scan_device(zdev);
mutex_unlock(&zpci_list_lock);
}
/*
* Too late for any s390 specific setup, since interrupts must be set up
* already which requires DMA setup too and the pci scan will access the
* config space, which only works if the function handle is enabled.
*/
int pcibios_enable_device(struct pci_dev *pdev, int mask)
{
struct resource *res;
u16 cmd;
int i;
pci_read_config_word(pdev, PCI_COMMAND, &cmd);
for (i = 0; i < PCI_BAR_COUNT; i++) {
res = &pdev->resource[i];
if (res->flags & IORESOURCE_IO)
return -EINVAL;
if (res->flags & IORESOURCE_MEM)
cmd |= PCI_COMMAND_MEMORY;
}
pci_write_config_word(pdev, PCI_COMMAND, cmd);
return 0;
}
void pcibios_disable_device(struct pci_dev *pdev)
{
zpci_remove_device(pdev);
pdev->sysdata = NULL;
}
int pcibios_add_platform_entries(struct pci_dev *pdev)
{
return zpci_sysfs_add_device(&pdev->dev);
}
int zpci_request_irq(unsigned int irq, irq_handler_t handler, void *data)
{
int msi_nr = irq_to_msi_nr(irq);
struct zdev_irq_map *imap;
struct msi_desc *msi;
msi = irq_get_msi_desc(irq);
if (!msi)
return -EIO;
imap = get_imap(irq);
spin_lock_init(&imap->lock);
pr_debug("%s: register handler for IRQ:MSI %d:%d\n", __func__, irq >> 6, msi_nr);
imap->cb[msi_nr].handler = handler;
imap->cb[msi_nr].data = data;
/*
* The generic MSI code returns with the interrupt disabled on the
* card, using the MSI mask bits. Firmware doesn't appear to unmask
* at that level, so we do it here by hand.
*/
zpci_msi_set_mask_bits(msi, 1, 0);
return 0;
}
void zpci_free_irq(unsigned int irq)
{
struct zdev_irq_map *imap = get_imap(irq);
int msi_nr = irq_to_msi_nr(irq);
unsigned long flags;
pr_debug("%s: for irq: %d\n", __func__, irq);
spin_lock_irqsave(&imap->lock, flags);
imap->cb[msi_nr].handler = NULL;
imap->cb[msi_nr].data = NULL;
spin_unlock_irqrestore(&imap->lock, flags);
}
int request_irq(unsigned int irq, irq_handler_t handler,
unsigned long irqflags, const char *devname, void *dev_id)
{
pr_debug("%s: irq: %d handler: %p flags: %lx dev: %s\n",
__func__, irq, handler, irqflags, devname);
return zpci_request_irq(irq, handler, dev_id);
}
EXPORT_SYMBOL_GPL(request_irq);
void free_irq(unsigned int irq, void *dev_id)
{
zpci_free_irq(irq);
}
EXPORT_SYMBOL_GPL(free_irq);
static int __init zpci_irq_init(void)
{
int cpu, rc;
bucket = kzalloc(sizeof(*bucket), GFP_KERNEL);
if (!bucket)
return -ENOMEM;
bucket->aisb = (unsigned long *) get_zeroed_page(GFP_KERNEL);
if (!bucket->aisb) {
rc = -ENOMEM;
goto out_aisb;
}
bucket->alloc = (unsigned long *) get_zeroed_page(GFP_KERNEL);
if (!bucket->alloc) {
rc = -ENOMEM;
goto out_alloc;
}
isc_register(PCI_ISC);
zpci_irq_si = s390_register_adapter_interrupt(&zpci_irq_handler, NULL, PCI_ISC);
if (IS_ERR(zpci_irq_si)) {
rc = PTR_ERR(zpci_irq_si);
zpci_irq_si = NULL;
goto out_ai;
}
for_each_online_cpu(cpu)
per_cpu(next_sbit, cpu) = 0;
spin_lock_init(&bucket->lock);
/* set summary to 1 to be called every time for the ISC */
*zpci_irq_si = 1;
sic_instr(SIC_IRQ_MODE_SINGLE, NULL, PCI_ISC);
return 0;
out_ai:
isc_unregister(PCI_ISC);
free_page((unsigned long) bucket->alloc);
out_alloc:
free_page((unsigned long) bucket->aisb);
out_aisb:
kfree(bucket);
return rc;
}
static void zpci_irq_exit(void)
{
free_page((unsigned long) bucket->alloc);
free_page((unsigned long) bucket->aisb);
s390_unregister_adapter_interrupt(zpci_irq_si, PCI_ISC);
isc_unregister(PCI_ISC);
kfree(bucket);
}
void zpci_debug_info(struct zpci_dev *zdev, struct seq_file *m)
{
if (!zdev)
return;
seq_printf(m, "global irq retries: %u\n", atomic_read(&irq_retries));
seq_printf(m, "aibv[0]:%016lx aibv[1]:%016lx aisb:%016lx\n",
get_imap(0)->aibv, get_imap(1)->aibv, *bucket->aisb);
}
static struct resource *zpci_alloc_bus_resource(unsigned long start, unsigned long size,
unsigned long flags, int domain)
{
struct resource *r;
char *name;
int rc;
r = kzalloc(sizeof(*r), GFP_KERNEL);
if (!r)
return ERR_PTR(-ENOMEM);
r->start = start;
r->end = r->start + size - 1;
r->flags = flags;
r->parent = &iomem_resource;
name = kmalloc(18, GFP_KERNEL);
if (!name) {
kfree(r);
return ERR_PTR(-ENOMEM);
}
sprintf(name, "PCI Bus: %04x:%02x", domain, ZPCI_BUS_NR);
r->name = name;
rc = request_resource(&iomem_resource, r);
if (rc)
pr_debug("request resource %pR failed\n", r);
return r;
}
static int zpci_alloc_iomap(struct zpci_dev *zdev)
{
int entry;
spin_lock(&zpci_iomap_lock);
entry = find_first_zero_bit(zpci_iomap, ZPCI_IOMAP_MAX_ENTRIES);
if (entry == ZPCI_IOMAP_MAX_ENTRIES) {
spin_unlock(&zpci_iomap_lock);
return -ENOSPC;
}
set_bit(entry, zpci_iomap);
spin_unlock(&zpci_iomap_lock);
return entry;
}
static void zpci_free_iomap(struct zpci_dev *zdev, int entry)
{
spin_lock(&zpci_iomap_lock);
memset(&zpci_iomap_start[entry], 0, sizeof(struct zpci_iomap_entry));
clear_bit(entry, zpci_iomap);
spin_unlock(&zpci_iomap_lock);
}
static int zpci_create_device_bus(struct zpci_dev *zdev)
{
struct resource *res;
LIST_HEAD(resources);
int i;
/* allocate mapping entry for each used bar */
for (i = 0; i < PCI_BAR_COUNT; i++) {
unsigned long addr, size, flags;
int entry;
if (!zdev->bars[i].size)
continue;
entry = zpci_alloc_iomap(zdev);
if (entry < 0)
return entry;
zdev->bars[i].map_idx = entry;
/* only MMIO is supported */
flags = IORESOURCE_MEM;
if (zdev->bars[i].val & 8)
flags |= IORESOURCE_PREFETCH;
if (zdev->bars[i].val & 4)
flags |= IORESOURCE_MEM_64;
addr = ZPCI_IOMAP_ADDR_BASE + ((u64) entry << 48);
size = 1UL << zdev->bars[i].size;
res = zpci_alloc_bus_resource(addr, size, flags, zdev->domain);
if (IS_ERR(res)) {
zpci_free_iomap(zdev, entry);
return PTR_ERR(res);
}
pci_add_resource(&resources, res);
}
zdev->bus = pci_create_root_bus(NULL, ZPCI_BUS_NR, &pci_root_ops,
zdev, &resources);
if (!zdev->bus)
return -EIO;
zdev->bus->max_bus_speed = zdev->max_bus_speed;
return 0;
}
static int zpci_alloc_domain(struct zpci_dev *zdev)
{
spin_lock(&zpci_domain_lock);
zdev->domain = find_first_zero_bit(zpci_domain, ZPCI_NR_DEVICES);
if (zdev->domain == ZPCI_NR_DEVICES) {
spin_unlock(&zpci_domain_lock);
return -ENOSPC;
}
set_bit(zdev->domain, zpci_domain);
spin_unlock(&zpci_domain_lock);
return 0;
}
static void zpci_free_domain(struct zpci_dev *zdev)
{
spin_lock(&zpci_domain_lock);
clear_bit(zdev->domain, zpci_domain);
spin_unlock(&zpci_domain_lock);
}
int zpci_enable_device(struct zpci_dev *zdev)
{
int rc;
rc = clp_enable_fh(zdev, ZPCI_NR_DMA_SPACES);
if (rc)
goto out;
pr_info("Enabled fh: 0x%x fid: 0x%x\n", zdev->fh, zdev->fid);
rc = zpci_dma_init_device(zdev);
if (rc)
goto out_dma;
return 0;
out_dma:
clp_disable_fh(zdev);
out:
return rc;
}
EXPORT_SYMBOL_GPL(zpci_enable_device);
int zpci_create_device(struct zpci_dev *zdev)
{
int rc;
rc = zpci_alloc_domain(zdev);
if (rc)
goto out;
rc = zpci_create_device_bus(zdev);
if (rc)
goto out_bus;
mutex_lock(&zpci_list_lock);
list_add_tail(&zdev->entry, &zpci_list);
if (hotplug_ops.create_slot)
hotplug_ops.create_slot(zdev);
mutex_unlock(&zpci_list_lock);
if (zdev->state == ZPCI_FN_STATE_STANDBY)
return 0;
rc = zpci_enable_device(zdev);
if (rc)
goto out_start;
return 0;
out_start:
mutex_lock(&zpci_list_lock);
list_del(&zdev->entry);
if (hotplug_ops.remove_slot)
hotplug_ops.remove_slot(zdev);
mutex_unlock(&zpci_list_lock);
out_bus:
zpci_free_domain(zdev);
out:
return rc;
}
void zpci_stop_device(struct zpci_dev *zdev)
{
zpci_dma_exit_device(zdev);
/*
* Note: SCLP disables fh via set-pci-fn so don't
* do that here.
*/
}
EXPORT_SYMBOL_GPL(zpci_stop_device);
int zpci_scan_device(struct zpci_dev *zdev)
{
zdev->pdev = pci_scan_single_device(zdev->bus, ZPCI_DEVFN);
if (!zdev->pdev) {
pr_err("pci_scan_single_device failed for fid: 0x%x\n",
zdev->fid);
goto out;
}
zpci_debug_init_device(zdev);
zpci_fmb_enable_device(zdev);
zpci_map_resources(zdev);
pci_bus_add_devices(zdev->bus);
/* now that pdev was added to the bus mark it as used */
zdev->state = ZPCI_FN_STATE_ONLINE;
return 0;
out:
zpci_dma_exit_device(zdev);
clp_disable_fh(zdev);
return -EIO;
}
EXPORT_SYMBOL_GPL(zpci_scan_device);
static inline int barsize(u8 size)
{
return (size) ? (1 << size) >> 10 : 0;
}
static int zpci_mem_init(void)
{
zdev_irq_cache = kmem_cache_create("PCI_IRQ_cache", sizeof(struct zdev_irq_map),
L1_CACHE_BYTES, SLAB_HWCACHE_ALIGN, NULL);
if (!zdev_irq_cache)
goto error_zdev;
zdev_fmb_cache = kmem_cache_create("PCI_FMB_cache", sizeof(struct zpci_fmb),
16, 0, NULL);
if (!zdev_fmb_cache)
goto error_fmb;
/* TODO: use realloc */
zpci_iomap_start = kzalloc(ZPCI_IOMAP_MAX_ENTRIES * sizeof(*zpci_iomap_start),
GFP_KERNEL);
if (!zpci_iomap_start)
goto error_iomap;
return 0;
error_iomap:
kmem_cache_destroy(zdev_fmb_cache);
error_fmb:
kmem_cache_destroy(zdev_irq_cache);
error_zdev:
return -ENOMEM;
}
static void zpci_mem_exit(void)
{
kfree(zpci_iomap_start);
kmem_cache_destroy(zdev_irq_cache);
kmem_cache_destroy(zdev_fmb_cache);
}
unsigned int pci_probe = 1;
EXPORT_SYMBOL_GPL(pci_probe);
char * __init pcibios_setup(char *str)
{
if (!strcmp(str, "off")) {
pci_probe = 0;
return NULL;
}
return str;
}
static int __init pci_base_init(void)
{
int rc;
if (!pci_probe)
return 0;
if (!test_facility(2) || !test_facility(69)
|| !test_facility(71) || !test_facility(72))
return 0;
pr_info("Probing PCI hardware: PCI:%d SID:%d AEN:%d\n",
test_facility(69), test_facility(70),
test_facility(71));
rc = zpci_debug_init();
if (rc)
return rc;
rc = zpci_mem_init();
if (rc)
goto out_mem;
rc = zpci_msihash_init();
if (rc)
goto out_hash;
rc = zpci_irq_init();
if (rc)
goto out_irq;
rc = zpci_dma_init();
if (rc)
goto out_dma;
rc = clp_find_pci_devices();
if (rc)
goto out_find;
zpci_scan_devices();
return 0;
out_find:
zpci_dma_exit();
out_dma:
zpci_irq_exit();
out_irq:
zpci_msihash_exit();
out_hash:
zpci_mem_exit();
out_mem:
zpci_debug_exit();
return rc;
}
subsys_initcall(pci_base_init);
| gpl-2.0 |
rickyzhang82/linux-up2date | drivers/mfd/ab8500-debugfs.c | 95 | 71608 | /*
* Copyright (C) ST-Ericsson SA 2010
*
* Author: Mattias Wallin <mattias.wallin@stericsson.com> for ST-Ericsson.
* License Terms: GNU General Public License v2
*/
/*
* AB8500 register access
* ======================
*
* read:
* # echo BANK > <debugfs>/ab8500/register-bank
* # echo ADDR > <debugfs>/ab8500/register-address
* # cat <debugfs>/ab8500/register-value
*
* write:
* # echo BANK > <debugfs>/ab8500/register-bank
* # echo ADDR > <debugfs>/ab8500/register-address
* # echo VALUE > <debugfs>/ab8500/register-value
*
* read all registers from a bank:
* # echo BANK > <debugfs>/ab8500/register-bank
* # cat <debugfs>/ab8500/all-bank-register
*
* BANK target AB8500 register bank
* ADDR target AB8500 register address
* VALUE decimal or 0x-prefixed hexadecimal
*
*
* User Space notification on AB8500 IRQ
* =====================================
*
* Allows user space entity to be notified when target AB8500 IRQ occurs.
* When subscribed, a sysfs entry is created in ab8500.i2c platform device.
* One can pool this file to get target IRQ occurence information.
*
* subscribe to an AB8500 IRQ:
* # echo IRQ > <debugfs>/ab8500/irq-subscribe
*
* unsubscribe from an AB8500 IRQ:
* # echo IRQ > <debugfs>/ab8500/irq-unsubscribe
*
*
* AB8500 register formated read/write access
* ==========================================
*
* Read: read data, data>>SHIFT, data&=MASK, output data
* [0xABCDEF98] shift=12 mask=0xFFF => 0x00000CDE
* Write: read data, data &= ~(MASK<<SHIFT), data |= (VALUE<<SHIFT), write data
* [0xABCDEF98] shift=12 mask=0xFFF value=0x123 => [0xAB123F98]
*
* Usage:
* # echo "CMD [OPTIONS] BANK ADRESS [VALUE]" > $debugfs/ab8500/hwreg
*
* CMD read read access
* write write access
*
* BANK target reg bank
* ADDRESS target reg address
* VALUE (write) value to be updated
*
* OPTIONS
* -d|-dec (read) output in decimal
* -h|-hexa (read) output in 0x-hexa (default)
* -l|-w|-b 32bit (default), 16bit or 8bit reg access
* -m|-mask MASK 0x-hexa mask (default 0xFFFFFFFF)
* -s|-shift SHIFT bit shift value (read:left, write:right)
* -o|-offset OFFSET address offset to add to ADDRESS value
*
* Warning: bit shift operation is applied to bit-mask.
* Warning: bit shift direction depends on read or right command.
*/
#include <linux/seq_file.h>
#include <linux/uaccess.h>
#include <linux/fs.h>
#include <linux/module.h>
#include <linux/debugfs.h>
#include <linux/platform_device.h>
#include <linux/interrupt.h>
#include <linux/kobject.h>
#include <linux/slab.h>
#include <linux/irq.h>
#include <linux/mfd/abx500.h>
#include <linux/mfd/abx500/ab8500.h>
#include <linux/mfd/abx500/ab8500-gpadc.h>
#ifdef CONFIG_DEBUG_FS
#include <linux/string.h>
#include <linux/ctype.h>
#endif
static u32 debug_bank;
static u32 debug_address;
static int irq_ab8500;
static int irq_first;
static int irq_last;
static u32 *irq_count;
static int num_irqs;
static struct device_attribute **dev_attr;
static char **event_name;
static u8 avg_sample = SAMPLE_16;
static u8 trig_edge = RISING_EDGE;
static u8 conv_type = ADC_SW;
static u8 trig_timer;
/**
* struct ab8500_reg_range
* @first: the first address of the range
* @last: the last address of the range
* @perm: access permissions for the range
*/
struct ab8500_reg_range {
u8 first;
u8 last;
u8 perm;
};
/**
* struct ab8500_prcmu_ranges
* @num_ranges: the number of ranges in the list
* @bankid: bank identifier
* @range: the list of register ranges
*/
struct ab8500_prcmu_ranges {
u8 num_ranges;
u8 bankid;
const struct ab8500_reg_range *range;
};
/* hwreg- "mask" and "shift" entries ressources */
struct hwreg_cfg {
u32 bank; /* target bank */
unsigned long addr; /* target address */
uint fmt; /* format */
unsigned long mask; /* read/write mask, applied before any bit shift */
long shift; /* bit shift (read:right shift, write:left shift */
};
/* fmt bit #0: 0=hexa, 1=dec */
#define REG_FMT_DEC(c) ((c)->fmt & 0x1)
#define REG_FMT_HEX(c) (!REG_FMT_DEC(c))
static struct hwreg_cfg hwreg_cfg = {
.addr = 0, /* default: invalid phys addr */
.fmt = 0, /* default: 32bit access, hex output */
.mask = 0xFFFFFFFF, /* default: no mask */
.shift = 0, /* default: no bit shift */
};
#define AB8500_NAME_STRING "ab8500"
#define AB8500_ADC_NAME_STRING "gpadc"
#define AB8500_NUM_BANKS 24
#define AB8500_REV_REG 0x80
static struct ab8500_prcmu_ranges *debug_ranges;
static struct ab8500_prcmu_ranges ab8500_debug_ranges[AB8500_NUM_BANKS] = {
[0x0] = {
.num_ranges = 0,
.range = NULL,
},
[AB8500_SYS_CTRL1_BLOCK] = {
.num_ranges = 3,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x02,
},
{
.first = 0x42,
.last = 0x42,
},
{
.first = 0x80,
.last = 0x81,
},
},
},
[AB8500_SYS_CTRL2_BLOCK] = {
.num_ranges = 4,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x0D,
},
{
.first = 0x0F,
.last = 0x17,
},
{
.first = 0x30,
.last = 0x30,
},
{
.first = 0x32,
.last = 0x33,
},
},
},
[AB8500_REGU_CTRL1] = {
.num_ranges = 3,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x00,
},
{
.first = 0x03,
.last = 0x10,
},
{
.first = 0x80,
.last = 0x84,
},
},
},
[AB8500_REGU_CTRL2] = {
.num_ranges = 5,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x15,
},
{
.first = 0x17,
.last = 0x19,
},
{
.first = 0x1B,
.last = 0x1D,
},
{
.first = 0x1F,
.last = 0x22,
},
{
.first = 0x40,
.last = 0x44,
},
/*
* 0x80-0x8B are SIM registers and should
* not be accessed from here
*/
},
},
[AB8500_USB] = {
.num_ranges = 2,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x80,
.last = 0x83,
},
{
.first = 0x87,
.last = 0x8A,
},
},
},
[AB8500_TVOUT] = {
.num_ranges = 9,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x12,
},
{
.first = 0x15,
.last = 0x17,
},
{
.first = 0x19,
.last = 0x21,
},
{
.first = 0x27,
.last = 0x2C,
},
{
.first = 0x41,
.last = 0x41,
},
{
.first = 0x45,
.last = 0x5B,
},
{
.first = 0x5D,
.last = 0x5D,
},
{
.first = 0x69,
.last = 0x69,
},
{
.first = 0x80,
.last = 0x81,
},
},
},
[AB8500_DBI] = {
.num_ranges = 0,
.range = NULL,
},
[AB8500_ECI_AV_ACC] = {
.num_ranges = 1,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x80,
.last = 0x82,
},
},
},
[0x9] = {
.num_ranges = 0,
.range = NULL,
},
[AB8500_GPADC] = {
.num_ranges = 1,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x08,
},
},
},
[AB8500_CHARGER] = {
.num_ranges = 9,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x03,
},
{
.first = 0x05,
.last = 0x05,
},
{
.first = 0x40,
.last = 0x40,
},
{
.first = 0x42,
.last = 0x42,
},
{
.first = 0x44,
.last = 0x44,
},
{
.first = 0x50,
.last = 0x55,
},
{
.first = 0x80,
.last = 0x82,
},
{
.first = 0xC0,
.last = 0xC2,
},
{
.first = 0xf5,
.last = 0xf6,
},
},
},
[AB8500_GAS_GAUGE] = {
.num_ranges = 3,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x00,
},
{
.first = 0x07,
.last = 0x0A,
},
{
.first = 0x10,
.last = 0x14,
},
},
},
[AB8500_DEVELOPMENT] = {
.num_ranges = 1,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x00,
},
},
},
[AB8500_DEBUG] = {
.num_ranges = 1,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x05,
.last = 0x07,
},
},
},
[AB8500_AUDIO] = {
.num_ranges = 1,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x6F,
},
},
},
[AB8500_INTERRUPT] = {
.num_ranges = 0,
.range = NULL,
},
[AB8500_RTC] = {
.num_ranges = 1,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x0F,
},
},
},
[AB8500_MISC] = {
.num_ranges = 8,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x05,
},
{
.first = 0x10,
.last = 0x15,
},
{
.first = 0x20,
.last = 0x25,
},
{
.first = 0x30,
.last = 0x35,
},
{
.first = 0x40,
.last = 0x45,
},
{
.first = 0x50,
.last = 0x50,
},
{
.first = 0x60,
.last = 0x67,
},
{
.first = 0x80,
.last = 0x80,
},
},
},
[0x11] = {
.num_ranges = 0,
.range = NULL,
},
[0x12] = {
.num_ranges = 0,
.range = NULL,
},
[0x13] = {
.num_ranges = 0,
.range = NULL,
},
[0x14] = {
.num_ranges = 0,
.range = NULL,
},
[AB8500_OTP_EMUL] = {
.num_ranges = 1,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x01,
.last = 0x0F,
},
},
},
};
static struct ab8500_prcmu_ranges ab8505_debug_ranges[AB8500_NUM_BANKS] = {
[0x0] = {
.num_ranges = 0,
.range = NULL,
},
[AB8500_SYS_CTRL1_BLOCK] = {
.num_ranges = 5,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x04,
},
{
.first = 0x42,
.last = 0x42,
},
{
.first = 0x52,
.last = 0x52,
},
{
.first = 0x54,
.last = 0x57,
},
{
.first = 0x80,
.last = 0x83,
},
},
},
[AB8500_SYS_CTRL2_BLOCK] = {
.num_ranges = 5,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x0D,
},
{
.first = 0x0F,
.last = 0x17,
},
{
.first = 0x20,
.last = 0x20,
},
{
.first = 0x30,
.last = 0x30,
},
{
.first = 0x32,
.last = 0x3A,
},
},
},
[AB8500_REGU_CTRL1] = {
.num_ranges = 3,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x00,
},
{
.first = 0x03,
.last = 0x11,
},
{
.first = 0x80,
.last = 0x86,
},
},
},
[AB8500_REGU_CTRL2] = {
.num_ranges = 6,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x06,
},
{
.first = 0x08,
.last = 0x15,
},
{
.first = 0x17,
.last = 0x19,
},
{
.first = 0x1B,
.last = 0x1D,
},
{
.first = 0x1F,
.last = 0x30,
},
{
.first = 0x40,
.last = 0x48,
},
/*
* 0x80-0x8B are SIM registers and should
* not be accessed from here
*/
},
},
[AB8500_USB] = {
.num_ranges = 3,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x80,
.last = 0x83,
},
{
.first = 0x87,
.last = 0x8A,
},
{
.first = 0x91,
.last = 0x94,
},
},
},
[AB8500_TVOUT] = {
.num_ranges = 0,
.range = NULL,
},
[AB8500_DBI] = {
.num_ranges = 0,
.range = NULL,
},
[AB8500_ECI_AV_ACC] = {
.num_ranges = 1,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x80,
.last = 0x82,
},
},
},
[AB8500_RESERVED] = {
.num_ranges = 0,
.range = NULL,
},
[AB8500_GPADC] = {
.num_ranges = 1,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x08,
},
},
},
[AB8500_CHARGER] = {
.num_ranges = 9,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x02,
.last = 0x03,
},
{
.first = 0x05,
.last = 0x05,
},
{
.first = 0x40,
.last = 0x44,
},
{
.first = 0x50,
.last = 0x57,
},
{
.first = 0x60,
.last = 0x60,
},
{
.first = 0xA0,
.last = 0xA7,
},
{
.first = 0xAF,
.last = 0xB2,
},
{
.first = 0xC0,
.last = 0xC2,
},
{
.first = 0xF5,
.last = 0xF5,
},
},
},
[AB8500_GAS_GAUGE] = {
.num_ranges = 3,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x00,
},
{
.first = 0x07,
.last = 0x0A,
},
{
.first = 0x10,
.last = 0x14,
},
},
},
[AB8500_AUDIO] = {
.num_ranges = 1,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x83,
},
},
},
[AB8500_INTERRUPT] = {
.num_ranges = 11,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x04,
},
{
.first = 0x06,
.last = 0x07,
},
{
.first = 0x09,
.last = 0x09,
},
{
.first = 0x0B,
.last = 0x0C,
},
{
.first = 0x12,
.last = 0x15,
},
{
.first = 0x18,
.last = 0x18,
},
/* Latch registers should not be read here */
{
.first = 0x40,
.last = 0x44,
},
{
.first = 0x46,
.last = 0x49,
},
{
.first = 0x4B,
.last = 0x4D,
},
{
.first = 0x52,
.last = 0x55,
},
{
.first = 0x58,
.last = 0x58,
},
/* LatchHier registers should not be read here */
},
},
[AB8500_RTC] = {
.num_ranges = 2,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x14,
},
{
.first = 0x16,
.last = 0x17,
},
},
},
[AB8500_MISC] = {
.num_ranges = 8,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x06,
},
{
.first = 0x10,
.last = 0x16,
},
{
.first = 0x20,
.last = 0x26,
},
{
.first = 0x30,
.last = 0x36,
},
{
.first = 0x40,
.last = 0x46,
},
{
.first = 0x50,
.last = 0x50,
},
{
.first = 0x60,
.last = 0x6B,
},
{
.first = 0x80,
.last = 0x82,
},
},
},
[AB8500_DEVELOPMENT] = {
.num_ranges = 2,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x00,
},
{
.first = 0x05,
.last = 0x05,
},
},
},
[AB8500_DEBUG] = {
.num_ranges = 1,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x05,
.last = 0x07,
},
},
},
[AB8500_PROD_TEST] = {
.num_ranges = 0,
.range = NULL,
},
[AB8500_STE_TEST] = {
.num_ranges = 0,
.range = NULL,
},
[AB8500_OTP_EMUL] = {
.num_ranges = 1,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x01,
.last = 0x15,
},
},
},
};
static struct ab8500_prcmu_ranges ab8540_debug_ranges[AB8500_NUM_BANKS] = {
[AB8500_M_FSM_RANK] = {
.num_ranges = 1,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x0B,
},
},
},
[AB8500_SYS_CTRL1_BLOCK] = {
.num_ranges = 6,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x04,
},
{
.first = 0x42,
.last = 0x42,
},
{
.first = 0x50,
.last = 0x54,
},
{
.first = 0x57,
.last = 0x57,
},
{
.first = 0x80,
.last = 0x83,
},
{
.first = 0x90,
.last = 0x90,
},
},
},
[AB8500_SYS_CTRL2_BLOCK] = {
.num_ranges = 5,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x0D,
},
{
.first = 0x0F,
.last = 0x10,
},
{
.first = 0x20,
.last = 0x21,
},
{
.first = 0x32,
.last = 0x3C,
},
{
.first = 0x40,
.last = 0x42,
},
},
},
[AB8500_REGU_CTRL1] = {
.num_ranges = 4,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x03,
.last = 0x15,
},
{
.first = 0x20,
.last = 0x20,
},
{
.first = 0x80,
.last = 0x85,
},
{
.first = 0x87,
.last = 0x88,
},
},
},
[AB8500_REGU_CTRL2] = {
.num_ranges = 8,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x06,
},
{
.first = 0x08,
.last = 0x15,
},
{
.first = 0x17,
.last = 0x19,
},
{
.first = 0x1B,
.last = 0x1D,
},
{
.first = 0x1F,
.last = 0x2F,
},
{
.first = 0x31,
.last = 0x3A,
},
{
.first = 0x43,
.last = 0x44,
},
{
.first = 0x48,
.last = 0x49,
},
},
},
[AB8500_USB] = {
.num_ranges = 3,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x80,
.last = 0x83,
},
{
.first = 0x87,
.last = 0x8A,
},
{
.first = 0x91,
.last = 0x94,
},
},
},
[AB8500_TVOUT] = {
.num_ranges = 0,
.range = NULL
},
[AB8500_DBI] = {
.num_ranges = 4,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x07,
},
{
.first = 0x10,
.last = 0x11,
},
{
.first = 0x20,
.last = 0x21,
},
{
.first = 0x30,
.last = 0x43,
},
},
},
[AB8500_ECI_AV_ACC] = {
.num_ranges = 2,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x03,
},
{
.first = 0x80,
.last = 0x82,
},
},
},
[AB8500_RESERVED] = {
.num_ranges = 0,
.range = NULL,
},
[AB8500_GPADC] = {
.num_ranges = 4,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x01,
},
{
.first = 0x04,
.last = 0x06,
},
{
.first = 0x09,
.last = 0x0A,
},
{
.first = 0x10,
.last = 0x14,
},
},
},
[AB8500_CHARGER] = {
.num_ranges = 10,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x00,
},
{
.first = 0x02,
.last = 0x05,
},
{
.first = 0x40,
.last = 0x44,
},
{
.first = 0x50,
.last = 0x57,
},
{
.first = 0x60,
.last = 0x60,
},
{
.first = 0x70,
.last = 0x70,
},
{
.first = 0xA0,
.last = 0xA9,
},
{
.first = 0xAF,
.last = 0xB2,
},
{
.first = 0xC0,
.last = 0xC6,
},
{
.first = 0xF5,
.last = 0xF5,
},
},
},
[AB8500_GAS_GAUGE] = {
.num_ranges = 3,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x00,
},
{
.first = 0x07,
.last = 0x0A,
},
{
.first = 0x10,
.last = 0x14,
},
},
},
[AB8500_AUDIO] = {
.num_ranges = 1,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x9f,
},
},
},
[AB8500_INTERRUPT] = {
.num_ranges = 6,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x05,
},
{
.first = 0x0B,
.last = 0x0D,
},
{
.first = 0x12,
.last = 0x20,
},
/* Latch registers should not be read here */
{
.first = 0x40,
.last = 0x45,
},
{
.first = 0x4B,
.last = 0x4D,
},
{
.first = 0x52,
.last = 0x60,
},
/* LatchHier registers should not be read here */
},
},
[AB8500_RTC] = {
.num_ranges = 3,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x07,
},
{
.first = 0x0B,
.last = 0x18,
},
{
.first = 0x20,
.last = 0x25,
},
},
},
[AB8500_MISC] = {
.num_ranges = 9,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x06,
},
{
.first = 0x10,
.last = 0x16,
},
{
.first = 0x20,
.last = 0x26,
},
{
.first = 0x30,
.last = 0x36,
},
{
.first = 0x40,
.last = 0x49,
},
{
.first = 0x50,
.last = 0x50,
},
{
.first = 0x60,
.last = 0x6B,
},
{
.first = 0x70,
.last = 0x74,
},
{
.first = 0x80,
.last = 0x82,
},
},
},
[AB8500_DEVELOPMENT] = {
.num_ranges = 3,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x01,
},
{
.first = 0x06,
.last = 0x06,
},
{
.first = 0x10,
.last = 0x21,
},
},
},
[AB8500_DEBUG] = {
.num_ranges = 3,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x01,
.last = 0x0C,
},
{
.first = 0x0E,
.last = 0x11,
},
{
.first = 0x80,
.last = 0x81,
},
},
},
[AB8500_PROD_TEST] = {
.num_ranges = 0,
.range = NULL,
},
[AB8500_STE_TEST] = {
.num_ranges = 0,
.range = NULL,
},
[AB8500_OTP_EMUL] = {
.num_ranges = 1,
.range = (struct ab8500_reg_range[]) {
{
.first = 0x00,
.last = 0x3F,
},
},
},
};
static irqreturn_t ab8500_debug_handler(int irq, void *data)
{
char buf[16];
struct kobject *kobj = (struct kobject *)data;
unsigned int irq_abb = irq - irq_first;
if (irq_abb < num_irqs)
irq_count[irq_abb]++;
/*
* This makes it possible to use poll for events (POLLPRI | POLLERR)
* from userspace on sysfs file named <irq-nr>
*/
sprintf(buf, "%d", irq);
sysfs_notify(kobj, NULL, buf);
return IRQ_HANDLED;
}
/* Prints to seq_file or log_buf */
static int ab8500_registers_print(struct device *dev, u32 bank,
struct seq_file *s)
{
unsigned int i;
for (i = 0; i < debug_ranges[bank].num_ranges; i++) {
u32 reg;
for (reg = debug_ranges[bank].range[i].first;
reg <= debug_ranges[bank].range[i].last;
reg++) {
u8 value;
int err;
err = abx500_get_register_interruptible(dev,
(u8)bank, (u8)reg, &value);
if (err < 0) {
dev_err(dev, "ab->read fail %d\n", err);
return err;
}
if (s) {
seq_printf(s, " [0x%02X/0x%02X]: 0x%02X\n",
bank, reg, value);
/*
* Error is not returned here since
* the output is wanted in any case
*/
if (seq_has_overflowed(s))
return 0;
} else {
dev_info(dev, " [0x%02X/0x%02X]: 0x%02X\n",
bank, reg, value);
}
}
}
return 0;
}
static int ab8500_print_bank_registers(struct seq_file *s, void *p)
{
struct device *dev = s->private;
u32 bank = debug_bank;
seq_puts(s, AB8500_NAME_STRING " register values:\n");
seq_printf(s, " bank 0x%02X:\n", bank);
return ab8500_registers_print(dev, bank, s);
}
static int ab8500_registers_open(struct inode *inode, struct file *file)
{
return single_open(file, ab8500_print_bank_registers, inode->i_private);
}
static const struct file_operations ab8500_registers_fops = {
.open = ab8500_registers_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static int ab8500_print_all_banks(struct seq_file *s, void *p)
{
struct device *dev = s->private;
unsigned int i;
seq_puts(s, AB8500_NAME_STRING " register values:\n");
for (i = 0; i < AB8500_NUM_BANKS; i++) {
int err;
seq_printf(s, " bank 0x%02X:\n", i);
err = ab8500_registers_print(dev, i, s);
if (err)
return err;
}
return 0;
}
/* Dump registers to kernel log */
void ab8500_dump_all_banks(struct device *dev)
{
unsigned int i;
dev_info(dev, "ab8500 register values:\n");
for (i = 1; i < AB8500_NUM_BANKS; i++) {
dev_info(dev, " bank 0x%02X:\n", i);
ab8500_registers_print(dev, i, NULL);
}
}
/* Space for 500 registers. */
#define DUMP_MAX_REGS 700
static struct ab8500_register_dump
{
u8 bank;
u8 reg;
u8 value;
} ab8500_complete_register_dump[DUMP_MAX_REGS];
/* This shall only be called upon kernel panic! */
void ab8500_dump_all_banks_to_mem(void)
{
int i, r = 0;
u8 bank;
int err = 0;
pr_info("Saving all ABB registers for crash analysis.\n");
for (bank = 0; bank < AB8500_NUM_BANKS; bank++) {
for (i = 0; i < debug_ranges[bank].num_ranges; i++) {
u8 reg;
for (reg = debug_ranges[bank].range[i].first;
reg <= debug_ranges[bank].range[i].last;
reg++) {
u8 value;
err = prcmu_abb_read(bank, reg, &value, 1);
if (err < 0)
goto out;
ab8500_complete_register_dump[r].bank = bank;
ab8500_complete_register_dump[r].reg = reg;
ab8500_complete_register_dump[r].value = value;
r++;
if (r >= DUMP_MAX_REGS) {
pr_err("%s: too many register to dump!\n",
__func__);
err = -EINVAL;
goto out;
}
}
}
}
out:
if (err >= 0)
pr_info("Saved all ABB registers.\n");
else
pr_info("Failed to save all ABB registers.\n");
}
static int ab8500_all_banks_open(struct inode *inode, struct file *file)
{
struct seq_file *s;
int err;
err = single_open(file, ab8500_print_all_banks, inode->i_private);
if (!err) {
/* Default buf size in seq_read is not enough */
s = (struct seq_file *)file->private_data;
s->size = (PAGE_SIZE * 2);
s->buf = kmalloc(s->size, GFP_KERNEL);
if (!s->buf) {
single_release(inode, file);
err = -ENOMEM;
}
}
return err;
}
static const struct file_operations ab8500_all_banks_fops = {
.open = ab8500_all_banks_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static int ab8500_bank_print(struct seq_file *s, void *p)
{
seq_printf(s, "0x%02X\n", debug_bank);
return 0;
}
static int ab8500_bank_open(struct inode *inode, struct file *file)
{
return single_open(file, ab8500_bank_print, inode->i_private);
}
static ssize_t ab8500_bank_write(struct file *file,
const char __user *user_buf,
size_t count, loff_t *ppos)
{
struct device *dev = ((struct seq_file *)(file->private_data))->private;
unsigned long user_bank;
int err;
err = kstrtoul_from_user(user_buf, count, 0, &user_bank);
if (err)
return err;
if (user_bank >= AB8500_NUM_BANKS) {
dev_err(dev, "debugfs error input > number of banks\n");
return -EINVAL;
}
debug_bank = user_bank;
return count;
}
static int ab8500_address_print(struct seq_file *s, void *p)
{
seq_printf(s, "0x%02X\n", debug_address);
return 0;
}
static int ab8500_address_open(struct inode *inode, struct file *file)
{
return single_open(file, ab8500_address_print, inode->i_private);
}
static ssize_t ab8500_address_write(struct file *file,
const char __user *user_buf,
size_t count, loff_t *ppos)
{
struct device *dev = ((struct seq_file *)(file->private_data))->private;
unsigned long user_address;
int err;
err = kstrtoul_from_user(user_buf, count, 0, &user_address);
if (err)
return err;
if (user_address > 0xff) {
dev_err(dev, "debugfs error input > 0xff\n");
return -EINVAL;
}
debug_address = user_address;
return count;
}
static int ab8500_val_print(struct seq_file *s, void *p)
{
struct device *dev = s->private;
int ret;
u8 regvalue;
ret = abx500_get_register_interruptible(dev,
(u8)debug_bank, (u8)debug_address, ®value);
if (ret < 0) {
dev_err(dev, "abx500_get_reg fail %d, %d\n",
ret, __LINE__);
return -EINVAL;
}
seq_printf(s, "0x%02X\n", regvalue);
return 0;
}
static int ab8500_val_open(struct inode *inode, struct file *file)
{
return single_open(file, ab8500_val_print, inode->i_private);
}
static ssize_t ab8500_val_write(struct file *file,
const char __user *user_buf,
size_t count, loff_t *ppos)
{
struct device *dev = ((struct seq_file *)(file->private_data))->private;
unsigned long user_val;
int err;
err = kstrtoul_from_user(user_buf, count, 0, &user_val);
if (err)
return err;
if (user_val > 0xff) {
dev_err(dev, "debugfs error input > 0xff\n");
return -EINVAL;
}
err = abx500_set_register_interruptible(dev,
(u8)debug_bank, debug_address, (u8)user_val);
if (err < 0) {
pr_err("abx500_set_reg failed %d, %d", err, __LINE__);
return -EINVAL;
}
return count;
}
/*
* Interrupt status
*/
static u32 num_interrupts[AB8500_MAX_NR_IRQS];
static u32 num_wake_interrupts[AB8500_MAX_NR_IRQS];
static int num_interrupt_lines;
bool __attribute__((weak)) suspend_test_wake_cause_interrupt_is_mine(u32 my_int)
{
return false;
}
void ab8500_debug_register_interrupt(int line)
{
if (line < num_interrupt_lines) {
num_interrupts[line]++;
if (suspend_test_wake_cause_interrupt_is_mine(irq_ab8500))
num_wake_interrupts[line]++;
}
}
static int ab8500_interrupts_print(struct seq_file *s, void *p)
{
int line;
seq_puts(s, "name: number: number of: wake:\n");
for (line = 0; line < num_interrupt_lines; line++) {
struct irq_desc *desc = irq_to_desc(line + irq_first);
seq_printf(s, "%3i: %6i %4i",
line,
num_interrupts[line],
num_wake_interrupts[line]);
if (desc && desc->name)
seq_printf(s, "-%-8s", desc->name);
if (desc && desc->action) {
struct irqaction *action = desc->action;
seq_printf(s, " %s", action->name);
while ((action = action->next) != NULL)
seq_printf(s, ", %s", action->name);
}
seq_putc(s, '\n');
}
return 0;
}
static int ab8500_interrupts_open(struct inode *inode, struct file *file)
{
return single_open(file, ab8500_interrupts_print, inode->i_private);
}
/*
* - HWREG DB8500 formated routines
*/
static int ab8500_hwreg_print(struct seq_file *s, void *d)
{
struct device *dev = s->private;
int ret;
u8 regvalue;
ret = abx500_get_register_interruptible(dev,
(u8)hwreg_cfg.bank, (u8)hwreg_cfg.addr, ®value);
if (ret < 0) {
dev_err(dev, "abx500_get_reg fail %d, %d\n",
ret, __LINE__);
return -EINVAL;
}
if (hwreg_cfg.shift >= 0)
regvalue >>= hwreg_cfg.shift;
else
regvalue <<= -hwreg_cfg.shift;
regvalue &= hwreg_cfg.mask;
if (REG_FMT_DEC(&hwreg_cfg))
seq_printf(s, "%d\n", regvalue);
else
seq_printf(s, "0x%02X\n", regvalue);
return 0;
}
static int ab8500_hwreg_open(struct inode *inode, struct file *file)
{
return single_open(file, ab8500_hwreg_print, inode->i_private);
}
#define AB8500_SUPPLY_CONTROL_CONFIG_1 0x01
#define AB8500_SUPPLY_CONTROL_REG 0x00
#define AB8500_FIRST_SIM_REG 0x80
#define AB8500_LAST_SIM_REG 0x8B
#define AB8505_LAST_SIM_REG 0x8C
static int ab8500_print_modem_registers(struct seq_file *s, void *p)
{
struct device *dev = s->private;
struct ab8500 *ab8500;
int err;
u8 value;
u8 orig_value;
u32 bank = AB8500_REGU_CTRL2;
u32 last_sim_reg = AB8500_LAST_SIM_REG;
u32 reg;
ab8500 = dev_get_drvdata(dev->parent);
dev_warn(dev, "WARNING! This operation can interfer with modem side\n"
"and should only be done with care\n");
err = abx500_get_register_interruptible(dev,
AB8500_REGU_CTRL1, AB8500_SUPPLY_CONTROL_REG, &orig_value);
if (err < 0) {
dev_err(dev, "ab->read fail %d\n", err);
return err;
}
/* Config 1 will allow APE side to read SIM registers */
err = abx500_set_register_interruptible(dev,
AB8500_REGU_CTRL1, AB8500_SUPPLY_CONTROL_REG,
AB8500_SUPPLY_CONTROL_CONFIG_1);
if (err < 0) {
dev_err(dev, "ab->write fail %d\n", err);
return err;
}
seq_printf(s, " bank 0x%02X:\n", bank);
if (is_ab9540(ab8500) || is_ab8505(ab8500))
last_sim_reg = AB8505_LAST_SIM_REG;
for (reg = AB8500_FIRST_SIM_REG; reg <= last_sim_reg; reg++) {
err = abx500_get_register_interruptible(dev,
bank, reg, &value);
if (err < 0) {
dev_err(dev, "ab->read fail %d\n", err);
return err;
}
seq_printf(s, " [0x%02X/0x%02X]: 0x%02X\n", bank, reg, value);
}
err = abx500_set_register_interruptible(dev,
AB8500_REGU_CTRL1, AB8500_SUPPLY_CONTROL_REG, orig_value);
if (err < 0) {
dev_err(dev, "ab->write fail %d\n", err);
return err;
}
return 0;
}
static int ab8500_modem_open(struct inode *inode, struct file *file)
{
return single_open(file, ab8500_print_modem_registers,
inode->i_private);
}
static const struct file_operations ab8500_modem_fops = {
.open = ab8500_modem_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static int ab8500_gpadc_bat_ctrl_print(struct seq_file *s, void *p)
{
int bat_ctrl_raw;
int bat_ctrl_convert;
struct ab8500_gpadc *gpadc;
gpadc = ab8500_gpadc_get("ab8500-gpadc.0");
bat_ctrl_raw = ab8500_gpadc_read_raw(gpadc, BAT_CTRL,
avg_sample, trig_edge, trig_timer, conv_type);
bat_ctrl_convert = ab8500_gpadc_ad_to_voltage(gpadc,
BAT_CTRL, bat_ctrl_raw);
seq_printf(s, "%d,0x%X\n", bat_ctrl_convert, bat_ctrl_raw);
return 0;
}
static int ab8500_gpadc_bat_ctrl_open(struct inode *inode, struct file *file)
{
return single_open(file, ab8500_gpadc_bat_ctrl_print,
inode->i_private);
}
static const struct file_operations ab8500_gpadc_bat_ctrl_fops = {
.open = ab8500_gpadc_bat_ctrl_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static int ab8500_gpadc_btemp_ball_print(struct seq_file *s, void *p)
{
int btemp_ball_raw;
int btemp_ball_convert;
struct ab8500_gpadc *gpadc;
gpadc = ab8500_gpadc_get("ab8500-gpadc.0");
btemp_ball_raw = ab8500_gpadc_read_raw(gpadc, BTEMP_BALL,
avg_sample, trig_edge, trig_timer, conv_type);
btemp_ball_convert = ab8500_gpadc_ad_to_voltage(gpadc, BTEMP_BALL,
btemp_ball_raw);
seq_printf(s, "%d,0x%X\n", btemp_ball_convert, btemp_ball_raw);
return 0;
}
static int ab8500_gpadc_btemp_ball_open(struct inode *inode,
struct file *file)
{
return single_open(file, ab8500_gpadc_btemp_ball_print,
inode->i_private);
}
static const struct file_operations ab8500_gpadc_btemp_ball_fops = {
.open = ab8500_gpadc_btemp_ball_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static int ab8500_gpadc_main_charger_v_print(struct seq_file *s, void *p)
{
int main_charger_v_raw;
int main_charger_v_convert;
struct ab8500_gpadc *gpadc;
gpadc = ab8500_gpadc_get("ab8500-gpadc.0");
main_charger_v_raw = ab8500_gpadc_read_raw(gpadc, MAIN_CHARGER_V,
avg_sample, trig_edge, trig_timer, conv_type);
main_charger_v_convert = ab8500_gpadc_ad_to_voltage(gpadc,
MAIN_CHARGER_V, main_charger_v_raw);
seq_printf(s, "%d,0x%X\n", main_charger_v_convert, main_charger_v_raw);
return 0;
}
static int ab8500_gpadc_main_charger_v_open(struct inode *inode,
struct file *file)
{
return single_open(file, ab8500_gpadc_main_charger_v_print,
inode->i_private);
}
static const struct file_operations ab8500_gpadc_main_charger_v_fops = {
.open = ab8500_gpadc_main_charger_v_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static int ab8500_gpadc_acc_detect1_print(struct seq_file *s, void *p)
{
int acc_detect1_raw;
int acc_detect1_convert;
struct ab8500_gpadc *gpadc;
gpadc = ab8500_gpadc_get("ab8500-gpadc.0");
acc_detect1_raw = ab8500_gpadc_read_raw(gpadc, ACC_DETECT1,
avg_sample, trig_edge, trig_timer, conv_type);
acc_detect1_convert = ab8500_gpadc_ad_to_voltage(gpadc, ACC_DETECT1,
acc_detect1_raw);
seq_printf(s, "%d,0x%X\n", acc_detect1_convert, acc_detect1_raw);
return 0;
}
static int ab8500_gpadc_acc_detect1_open(struct inode *inode,
struct file *file)
{
return single_open(file, ab8500_gpadc_acc_detect1_print,
inode->i_private);
}
static const struct file_operations ab8500_gpadc_acc_detect1_fops = {
.open = ab8500_gpadc_acc_detect1_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static int ab8500_gpadc_acc_detect2_print(struct seq_file *s, void *p)
{
int acc_detect2_raw;
int acc_detect2_convert;
struct ab8500_gpadc *gpadc;
gpadc = ab8500_gpadc_get("ab8500-gpadc.0");
acc_detect2_raw = ab8500_gpadc_read_raw(gpadc, ACC_DETECT2,
avg_sample, trig_edge, trig_timer, conv_type);
acc_detect2_convert = ab8500_gpadc_ad_to_voltage(gpadc,
ACC_DETECT2, acc_detect2_raw);
seq_printf(s, "%d,0x%X\n", acc_detect2_convert, acc_detect2_raw);
return 0;
}
static int ab8500_gpadc_acc_detect2_open(struct inode *inode,
struct file *file)
{
return single_open(file, ab8500_gpadc_acc_detect2_print,
inode->i_private);
}
static const struct file_operations ab8500_gpadc_acc_detect2_fops = {
.open = ab8500_gpadc_acc_detect2_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static int ab8500_gpadc_aux1_print(struct seq_file *s, void *p)
{
int aux1_raw;
int aux1_convert;
struct ab8500_gpadc *gpadc;
gpadc = ab8500_gpadc_get("ab8500-gpadc.0");
aux1_raw = ab8500_gpadc_read_raw(gpadc, ADC_AUX1,
avg_sample, trig_edge, trig_timer, conv_type);
aux1_convert = ab8500_gpadc_ad_to_voltage(gpadc, ADC_AUX1,
aux1_raw);
seq_printf(s, "%d,0x%X\n", aux1_convert, aux1_raw);
return 0;
}
static int ab8500_gpadc_aux1_open(struct inode *inode, struct file *file)
{
return single_open(file, ab8500_gpadc_aux1_print, inode->i_private);
}
static const struct file_operations ab8500_gpadc_aux1_fops = {
.open = ab8500_gpadc_aux1_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static int ab8500_gpadc_aux2_print(struct seq_file *s, void *p)
{
int aux2_raw;
int aux2_convert;
struct ab8500_gpadc *gpadc;
gpadc = ab8500_gpadc_get("ab8500-gpadc.0");
aux2_raw = ab8500_gpadc_read_raw(gpadc, ADC_AUX2,
avg_sample, trig_edge, trig_timer, conv_type);
aux2_convert = ab8500_gpadc_ad_to_voltage(gpadc, ADC_AUX2,
aux2_raw);
seq_printf(s, "%d,0x%X\n", aux2_convert, aux2_raw);
return 0;
}
static int ab8500_gpadc_aux2_open(struct inode *inode, struct file *file)
{
return single_open(file, ab8500_gpadc_aux2_print, inode->i_private);
}
static const struct file_operations ab8500_gpadc_aux2_fops = {
.open = ab8500_gpadc_aux2_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static int ab8500_gpadc_main_bat_v_print(struct seq_file *s, void *p)
{
int main_bat_v_raw;
int main_bat_v_convert;
struct ab8500_gpadc *gpadc;
gpadc = ab8500_gpadc_get("ab8500-gpadc.0");
main_bat_v_raw = ab8500_gpadc_read_raw(gpadc, MAIN_BAT_V,
avg_sample, trig_edge, trig_timer, conv_type);
main_bat_v_convert = ab8500_gpadc_ad_to_voltage(gpadc, MAIN_BAT_V,
main_bat_v_raw);
seq_printf(s, "%d,0x%X\n", main_bat_v_convert, main_bat_v_raw);
return 0;
}
static int ab8500_gpadc_main_bat_v_open(struct inode *inode,
struct file *file)
{
return single_open(file, ab8500_gpadc_main_bat_v_print,
inode->i_private);
}
static const struct file_operations ab8500_gpadc_main_bat_v_fops = {
.open = ab8500_gpadc_main_bat_v_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static int ab8500_gpadc_vbus_v_print(struct seq_file *s, void *p)
{
int vbus_v_raw;
int vbus_v_convert;
struct ab8500_gpadc *gpadc;
gpadc = ab8500_gpadc_get("ab8500-gpadc.0");
vbus_v_raw = ab8500_gpadc_read_raw(gpadc, VBUS_V,
avg_sample, trig_edge, trig_timer, conv_type);
vbus_v_convert = ab8500_gpadc_ad_to_voltage(gpadc, VBUS_V,
vbus_v_raw);
seq_printf(s, "%d,0x%X\n", vbus_v_convert, vbus_v_raw);
return 0;
}
static int ab8500_gpadc_vbus_v_open(struct inode *inode, struct file *file)
{
return single_open(file, ab8500_gpadc_vbus_v_print, inode->i_private);
}
static const struct file_operations ab8500_gpadc_vbus_v_fops = {
.open = ab8500_gpadc_vbus_v_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static int ab8500_gpadc_main_charger_c_print(struct seq_file *s, void *p)
{
int main_charger_c_raw;
int main_charger_c_convert;
struct ab8500_gpadc *gpadc;
gpadc = ab8500_gpadc_get("ab8500-gpadc.0");
main_charger_c_raw = ab8500_gpadc_read_raw(gpadc, MAIN_CHARGER_C,
avg_sample, trig_edge, trig_timer, conv_type);
main_charger_c_convert = ab8500_gpadc_ad_to_voltage(gpadc,
MAIN_CHARGER_C, main_charger_c_raw);
seq_printf(s, "%d,0x%X\n", main_charger_c_convert, main_charger_c_raw);
return 0;
}
static int ab8500_gpadc_main_charger_c_open(struct inode *inode,
struct file *file)
{
return single_open(file, ab8500_gpadc_main_charger_c_print,
inode->i_private);
}
static const struct file_operations ab8500_gpadc_main_charger_c_fops = {
.open = ab8500_gpadc_main_charger_c_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static int ab8500_gpadc_usb_charger_c_print(struct seq_file *s, void *p)
{
int usb_charger_c_raw;
int usb_charger_c_convert;
struct ab8500_gpadc *gpadc;
gpadc = ab8500_gpadc_get("ab8500-gpadc.0");
usb_charger_c_raw = ab8500_gpadc_read_raw(gpadc, USB_CHARGER_C,
avg_sample, trig_edge, trig_timer, conv_type);
usb_charger_c_convert = ab8500_gpadc_ad_to_voltage(gpadc,
USB_CHARGER_C, usb_charger_c_raw);
seq_printf(s, "%d,0x%X\n", usb_charger_c_convert, usb_charger_c_raw);
return 0;
}
static int ab8500_gpadc_usb_charger_c_open(struct inode *inode,
struct file *file)
{
return single_open(file, ab8500_gpadc_usb_charger_c_print,
inode->i_private);
}
static const struct file_operations ab8500_gpadc_usb_charger_c_fops = {
.open = ab8500_gpadc_usb_charger_c_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static int ab8500_gpadc_bk_bat_v_print(struct seq_file *s, void *p)
{
int bk_bat_v_raw;
int bk_bat_v_convert;
struct ab8500_gpadc *gpadc;
gpadc = ab8500_gpadc_get("ab8500-gpadc.0");
bk_bat_v_raw = ab8500_gpadc_read_raw(gpadc, BK_BAT_V,
avg_sample, trig_edge, trig_timer, conv_type);
bk_bat_v_convert = ab8500_gpadc_ad_to_voltage(gpadc,
BK_BAT_V, bk_bat_v_raw);
seq_printf(s, "%d,0x%X\n", bk_bat_v_convert, bk_bat_v_raw);
return 0;
}
static int ab8500_gpadc_bk_bat_v_open(struct inode *inode, struct file *file)
{
return single_open(file, ab8500_gpadc_bk_bat_v_print,
inode->i_private);
}
static const struct file_operations ab8500_gpadc_bk_bat_v_fops = {
.open = ab8500_gpadc_bk_bat_v_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static int ab8500_gpadc_die_temp_print(struct seq_file *s, void *p)
{
int die_temp_raw;
int die_temp_convert;
struct ab8500_gpadc *gpadc;
gpadc = ab8500_gpadc_get("ab8500-gpadc.0");
die_temp_raw = ab8500_gpadc_read_raw(gpadc, DIE_TEMP,
avg_sample, trig_edge, trig_timer, conv_type);
die_temp_convert = ab8500_gpadc_ad_to_voltage(gpadc, DIE_TEMP,
die_temp_raw);
seq_printf(s, "%d,0x%X\n", die_temp_convert, die_temp_raw);
return 0;
}
static int ab8500_gpadc_die_temp_open(struct inode *inode, struct file *file)
{
return single_open(file, ab8500_gpadc_die_temp_print,
inode->i_private);
}
static const struct file_operations ab8500_gpadc_die_temp_fops = {
.open = ab8500_gpadc_die_temp_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static int ab8500_gpadc_usb_id_print(struct seq_file *s, void *p)
{
int usb_id_raw;
int usb_id_convert;
struct ab8500_gpadc *gpadc;
gpadc = ab8500_gpadc_get("ab8500-gpadc.0");
usb_id_raw = ab8500_gpadc_read_raw(gpadc, USB_ID,
avg_sample, trig_edge, trig_timer, conv_type);
usb_id_convert = ab8500_gpadc_ad_to_voltage(gpadc, USB_ID,
usb_id_raw);
seq_printf(s, "%d,0x%X\n", usb_id_convert, usb_id_raw);
return 0;
}
static int ab8500_gpadc_usb_id_open(struct inode *inode, struct file *file)
{
return single_open(file, ab8500_gpadc_usb_id_print, inode->i_private);
}
static const struct file_operations ab8500_gpadc_usb_id_fops = {
.open = ab8500_gpadc_usb_id_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static int ab8540_gpadc_xtal_temp_print(struct seq_file *s, void *p)
{
int xtal_temp_raw;
int xtal_temp_convert;
struct ab8500_gpadc *gpadc;
gpadc = ab8500_gpadc_get("ab8500-gpadc.0");
xtal_temp_raw = ab8500_gpadc_read_raw(gpadc, XTAL_TEMP,
avg_sample, trig_edge, trig_timer, conv_type);
xtal_temp_convert = ab8500_gpadc_ad_to_voltage(gpadc, XTAL_TEMP,
xtal_temp_raw);
seq_printf(s, "%d,0x%X\n", xtal_temp_convert, xtal_temp_raw);
return 0;
}
static int ab8540_gpadc_xtal_temp_open(struct inode *inode, struct file *file)
{
return single_open(file, ab8540_gpadc_xtal_temp_print,
inode->i_private);
}
static const struct file_operations ab8540_gpadc_xtal_temp_fops = {
.open = ab8540_gpadc_xtal_temp_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static int ab8540_gpadc_vbat_true_meas_print(struct seq_file *s, void *p)
{
int vbat_true_meas_raw;
int vbat_true_meas_convert;
struct ab8500_gpadc *gpadc;
gpadc = ab8500_gpadc_get("ab8500-gpadc.0");
vbat_true_meas_raw = ab8500_gpadc_read_raw(gpadc, VBAT_TRUE_MEAS,
avg_sample, trig_edge, trig_timer, conv_type);
vbat_true_meas_convert =
ab8500_gpadc_ad_to_voltage(gpadc, VBAT_TRUE_MEAS,
vbat_true_meas_raw);
seq_printf(s, "%d,0x%X\n", vbat_true_meas_convert, vbat_true_meas_raw);
return 0;
}
static int ab8540_gpadc_vbat_true_meas_open(struct inode *inode,
struct file *file)
{
return single_open(file, ab8540_gpadc_vbat_true_meas_print,
inode->i_private);
}
static const struct file_operations ab8540_gpadc_vbat_true_meas_fops = {
.open = ab8540_gpadc_vbat_true_meas_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static int ab8540_gpadc_bat_ctrl_and_ibat_print(struct seq_file *s, void *p)
{
int bat_ctrl_raw;
int bat_ctrl_convert;
int ibat_raw;
int ibat_convert;
struct ab8500_gpadc *gpadc;
gpadc = ab8500_gpadc_get("ab8500-gpadc.0");
bat_ctrl_raw = ab8500_gpadc_double_read_raw(gpadc, BAT_CTRL_AND_IBAT,
avg_sample, trig_edge, trig_timer, conv_type, &ibat_raw);
bat_ctrl_convert = ab8500_gpadc_ad_to_voltage(gpadc, BAT_CTRL,
bat_ctrl_raw);
ibat_convert = ab8500_gpadc_ad_to_voltage(gpadc, IBAT_VIRTUAL_CHANNEL,
ibat_raw);
seq_printf(s,
"%d,0x%X\n"
"%d,0x%X\n",
bat_ctrl_convert, bat_ctrl_raw,
ibat_convert, ibat_raw);
return 0;
}
static int ab8540_gpadc_bat_ctrl_and_ibat_open(struct inode *inode,
struct file *file)
{
return single_open(file, ab8540_gpadc_bat_ctrl_and_ibat_print,
inode->i_private);
}
static const struct file_operations ab8540_gpadc_bat_ctrl_and_ibat_fops = {
.open = ab8540_gpadc_bat_ctrl_and_ibat_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static int ab8540_gpadc_vbat_meas_and_ibat_print(struct seq_file *s, void *p)
{
int vbat_meas_raw;
int vbat_meas_convert;
int ibat_raw;
int ibat_convert;
struct ab8500_gpadc *gpadc;
gpadc = ab8500_gpadc_get("ab8500-gpadc.0");
vbat_meas_raw = ab8500_gpadc_double_read_raw(gpadc, VBAT_MEAS_AND_IBAT,
avg_sample, trig_edge, trig_timer, conv_type, &ibat_raw);
vbat_meas_convert = ab8500_gpadc_ad_to_voltage(gpadc, MAIN_BAT_V,
vbat_meas_raw);
ibat_convert = ab8500_gpadc_ad_to_voltage(gpadc, IBAT_VIRTUAL_CHANNEL,
ibat_raw);
seq_printf(s,
"%d,0x%X\n"
"%d,0x%X\n",
vbat_meas_convert, vbat_meas_raw,
ibat_convert, ibat_raw);
return 0;
}
static int ab8540_gpadc_vbat_meas_and_ibat_open(struct inode *inode,
struct file *file)
{
return single_open(file, ab8540_gpadc_vbat_meas_and_ibat_print,
inode->i_private);
}
static const struct file_operations ab8540_gpadc_vbat_meas_and_ibat_fops = {
.open = ab8540_gpadc_vbat_meas_and_ibat_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static int ab8540_gpadc_vbat_true_meas_and_ibat_print(struct seq_file *s,
void *p)
{
int vbat_true_meas_raw;
int vbat_true_meas_convert;
int ibat_raw;
int ibat_convert;
struct ab8500_gpadc *gpadc;
gpadc = ab8500_gpadc_get("ab8500-gpadc.0");
vbat_true_meas_raw = ab8500_gpadc_double_read_raw(gpadc,
VBAT_TRUE_MEAS_AND_IBAT, avg_sample, trig_edge,
trig_timer, conv_type, &ibat_raw);
vbat_true_meas_convert = ab8500_gpadc_ad_to_voltage(gpadc,
VBAT_TRUE_MEAS, vbat_true_meas_raw);
ibat_convert = ab8500_gpadc_ad_to_voltage(gpadc, IBAT_VIRTUAL_CHANNEL,
ibat_raw);
seq_printf(s,
"%d,0x%X\n"
"%d,0x%X\n",
vbat_true_meas_convert, vbat_true_meas_raw,
ibat_convert, ibat_raw);
return 0;
}
static int ab8540_gpadc_vbat_true_meas_and_ibat_open(struct inode *inode,
struct file *file)
{
return single_open(file, ab8540_gpadc_vbat_true_meas_and_ibat_print,
inode->i_private);
}
static const struct file_operations
ab8540_gpadc_vbat_true_meas_and_ibat_fops = {
.open = ab8540_gpadc_vbat_true_meas_and_ibat_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static int ab8540_gpadc_bat_temp_and_ibat_print(struct seq_file *s, void *p)
{
int bat_temp_raw;
int bat_temp_convert;
int ibat_raw;
int ibat_convert;
struct ab8500_gpadc *gpadc;
gpadc = ab8500_gpadc_get("ab8500-gpadc.0");
bat_temp_raw = ab8500_gpadc_double_read_raw(gpadc, BAT_TEMP_AND_IBAT,
avg_sample, trig_edge, trig_timer, conv_type, &ibat_raw);
bat_temp_convert = ab8500_gpadc_ad_to_voltage(gpadc, BTEMP_BALL,
bat_temp_raw);
ibat_convert = ab8500_gpadc_ad_to_voltage(gpadc, IBAT_VIRTUAL_CHANNEL,
ibat_raw);
seq_printf(s,
"%d,0x%X\n"
"%d,0x%X\n",
bat_temp_convert, bat_temp_raw,
ibat_convert, ibat_raw);
return 0;
}
static int ab8540_gpadc_bat_temp_and_ibat_open(struct inode *inode,
struct file *file)
{
return single_open(file, ab8540_gpadc_bat_temp_and_ibat_print,
inode->i_private);
}
static const struct file_operations ab8540_gpadc_bat_temp_and_ibat_fops = {
.open = ab8540_gpadc_bat_temp_and_ibat_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static int ab8540_gpadc_otp_cal_print(struct seq_file *s, void *p)
{
struct ab8500_gpadc *gpadc;
u16 vmain_l, vmain_h, btemp_l, btemp_h;
u16 vbat_l, vbat_h, ibat_l, ibat_h;
gpadc = ab8500_gpadc_get("ab8500-gpadc.0");
ab8540_gpadc_get_otp(gpadc, &vmain_l, &vmain_h, &btemp_l, &btemp_h,
&vbat_l, &vbat_h, &ibat_l, &ibat_h);
seq_printf(s,
"VMAIN_L:0x%X\n"
"VMAIN_H:0x%X\n"
"BTEMP_L:0x%X\n"
"BTEMP_H:0x%X\n"
"VBAT_L:0x%X\n"
"VBAT_H:0x%X\n"
"IBAT_L:0x%X\n"
"IBAT_H:0x%X\n",
vmain_l, vmain_h, btemp_l, btemp_h,
vbat_l, vbat_h, ibat_l, ibat_h);
return 0;
}
static int ab8540_gpadc_otp_cal_open(struct inode *inode, struct file *file)
{
return single_open(file, ab8540_gpadc_otp_cal_print, inode->i_private);
}
static const struct file_operations ab8540_gpadc_otp_calib_fops = {
.open = ab8540_gpadc_otp_cal_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static int ab8500_gpadc_avg_sample_print(struct seq_file *s, void *p)
{
seq_printf(s, "%d\n", avg_sample);
return 0;
}
static int ab8500_gpadc_avg_sample_open(struct inode *inode, struct file *file)
{
return single_open(file, ab8500_gpadc_avg_sample_print,
inode->i_private);
}
static ssize_t ab8500_gpadc_avg_sample_write(struct file *file,
const char __user *user_buf,
size_t count, loff_t *ppos)
{
struct device *dev = ((struct seq_file *)(file->private_data))->private;
unsigned long user_avg_sample;
int err;
err = kstrtoul_from_user(user_buf, count, 0, &user_avg_sample);
if (err)
return err;
if ((user_avg_sample == SAMPLE_1) || (user_avg_sample == SAMPLE_4)
|| (user_avg_sample == SAMPLE_8)
|| (user_avg_sample == SAMPLE_16)) {
avg_sample = (u8) user_avg_sample;
} else {
dev_err(dev,
"debugfs err input: should be egal to 1, 4, 8 or 16\n");
return -EINVAL;
}
return count;
}
static const struct file_operations ab8500_gpadc_avg_sample_fops = {
.open = ab8500_gpadc_avg_sample_open,
.read = seq_read,
.write = ab8500_gpadc_avg_sample_write,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static int ab8500_gpadc_trig_edge_print(struct seq_file *s, void *p)
{
seq_printf(s, "%d\n", trig_edge);
return 0;
}
static int ab8500_gpadc_trig_edge_open(struct inode *inode, struct file *file)
{
return single_open(file, ab8500_gpadc_trig_edge_print,
inode->i_private);
}
static ssize_t ab8500_gpadc_trig_edge_write(struct file *file,
const char __user *user_buf,
size_t count, loff_t *ppos)
{
struct device *dev = ((struct seq_file *)(file->private_data))->private;
unsigned long user_trig_edge;
int err;
err = kstrtoul_from_user(user_buf, count, 0, &user_trig_edge);
if (err)
return err;
if ((user_trig_edge == RISING_EDGE)
|| (user_trig_edge == FALLING_EDGE)) {
trig_edge = (u8) user_trig_edge;
} else {
dev_err(dev, "Wrong input:\n"
"Enter 0. Rising edge\n"
"Enter 1. Falling edge\n");
return -EINVAL;
}
return count;
}
static const struct file_operations ab8500_gpadc_trig_edge_fops = {
.open = ab8500_gpadc_trig_edge_open,
.read = seq_read,
.write = ab8500_gpadc_trig_edge_write,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static int ab8500_gpadc_trig_timer_print(struct seq_file *s, void *p)
{
seq_printf(s, "%d\n", trig_timer);
return 0;
}
static int ab8500_gpadc_trig_timer_open(struct inode *inode, struct file *file)
{
return single_open(file, ab8500_gpadc_trig_timer_print,
inode->i_private);
}
static ssize_t ab8500_gpadc_trig_timer_write(struct file *file,
const char __user *user_buf,
size_t count, loff_t *ppos)
{
struct device *dev = ((struct seq_file *)(file->private_data))->private;
unsigned long user_trig_timer;
int err;
err = kstrtoul_from_user(user_buf, count, 0, &user_trig_timer);
if (err)
return err;
if (user_trig_timer & ~0xFF) {
dev_err(dev,
"debugfs error input: should be between 0 to 255\n");
return -EINVAL;
}
trig_timer = (u8) user_trig_timer;
return count;
}
static const struct file_operations ab8500_gpadc_trig_timer_fops = {
.open = ab8500_gpadc_trig_timer_open,
.read = seq_read,
.write = ab8500_gpadc_trig_timer_write,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static int ab8500_gpadc_conv_type_print(struct seq_file *s, void *p)
{
seq_printf(s, "%d\n", conv_type);
return 0;
}
static int ab8500_gpadc_conv_type_open(struct inode *inode, struct file *file)
{
return single_open(file, ab8500_gpadc_conv_type_print,
inode->i_private);
}
static ssize_t ab8500_gpadc_conv_type_write(struct file *file,
const char __user *user_buf,
size_t count, loff_t *ppos)
{
struct device *dev = ((struct seq_file *)(file->private_data))->private;
unsigned long user_conv_type;
int err;
err = kstrtoul_from_user(user_buf, count, 0, &user_conv_type);
if (err)
return err;
if ((user_conv_type == ADC_SW)
|| (user_conv_type == ADC_HW)) {
conv_type = (u8) user_conv_type;
} else {
dev_err(dev, "Wrong input:\n"
"Enter 0. ADC SW conversion\n"
"Enter 1. ADC HW conversion\n");
return -EINVAL;
}
return count;
}
static const struct file_operations ab8500_gpadc_conv_type_fops = {
.open = ab8500_gpadc_conv_type_open,
.read = seq_read,
.write = ab8500_gpadc_conv_type_write,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
/*
* return length of an ASCII numerical value, 0 is string is not a
* numerical value.
* string shall start at value 1st char.
* string can be tailed with \0 or space or newline chars only.
* value can be decimal or hexadecimal (prefixed 0x or 0X).
*/
static int strval_len(char *b)
{
char *s = b;
if ((*s == '0') && ((*(s+1) == 'x') || (*(s+1) == 'X'))) {
s += 2;
for (; *s && (*s != ' ') && (*s != '\n'); s++) {
if (!isxdigit(*s))
return 0;
}
} else {
if (*s == '-')
s++;
for (; *s && (*s != ' ') && (*s != '\n'); s++) {
if (!isdigit(*s))
return 0;
}
}
return (int) (s-b);
}
/*
* parse hwreg input data.
* update global hwreg_cfg only if input data syntax is ok.
*/
static ssize_t hwreg_common_write(char *b, struct hwreg_cfg *cfg,
struct device *dev)
{
uint write, val = 0;
u8 regvalue;
int ret;
struct hwreg_cfg loc = {
.bank = 0, /* default: invalid phys addr */
.addr = 0, /* default: invalid phys addr */
.fmt = 0, /* default: 32bit access, hex output */
.mask = 0xFFFFFFFF, /* default: no mask */
.shift = 0, /* default: no bit shift */
};
/* read or write ? */
if (!strncmp(b, "read ", 5)) {
write = 0;
b += 5;
} else if (!strncmp(b, "write ", 6)) {
write = 1;
b += 6;
} else
return -EINVAL;
/* OPTIONS -l|-w|-b -s -m -o */
while ((*b == ' ') || (*b == '-')) {
if (*(b-1) != ' ') {
b++;
continue;
}
if ((!strncmp(b, "-d ", 3)) ||
(!strncmp(b, "-dec ", 5))) {
b += (*(b+2) == ' ') ? 3 : 5;
loc.fmt |= (1<<0);
} else if ((!strncmp(b, "-h ", 3)) ||
(!strncmp(b, "-hex ", 5))) {
b += (*(b+2) == ' ') ? 3 : 5;
loc.fmt &= ~(1<<0);
} else if ((!strncmp(b, "-m ", 3)) ||
(!strncmp(b, "-mask ", 6))) {
b += (*(b+2) == ' ') ? 3 : 6;
if (strval_len(b) == 0)
return -EINVAL;
ret = kstrtoul(b, 0, &loc.mask);
if (ret)
return ret;
} else if ((!strncmp(b, "-s ", 3)) ||
(!strncmp(b, "-shift ", 7))) {
b += (*(b+2) == ' ') ? 3 : 7;
if (strval_len(b) == 0)
return -EINVAL;
ret = kstrtol(b, 0, &loc.shift);
if (ret)
return ret;
} else {
return -EINVAL;
}
}
/* get arg BANK and ADDRESS */
if (strval_len(b) == 0)
return -EINVAL;
ret = kstrtouint(b, 0, &loc.bank);
if (ret)
return ret;
while (*b == ' ')
b++;
if (strval_len(b) == 0)
return -EINVAL;
ret = kstrtoul(b, 0, &loc.addr);
if (ret)
return ret;
if (write) {
while (*b == ' ')
b++;
if (strval_len(b) == 0)
return -EINVAL;
ret = kstrtouint(b, 0, &val);
if (ret)
return ret;
}
/* args are ok, update target cfg (mainly for read) */
*cfg = loc;
#ifdef ABB_HWREG_DEBUG
pr_warn("HWREG request: %s, %s,\n", (write) ? "write" : "read",
REG_FMT_DEC(cfg) ? "decimal" : "hexa");
pr_warn(" addr=0x%08X, mask=0x%X, shift=%d" "value=0x%X\n",
cfg->addr, cfg->mask, cfg->shift, val);
#endif
if (!write)
return 0;
ret = abx500_get_register_interruptible(dev,
(u8)cfg->bank, (u8)cfg->addr, ®value);
if (ret < 0) {
dev_err(dev, "abx500_get_reg fail %d, %d\n",
ret, __LINE__);
return -EINVAL;
}
if (cfg->shift >= 0) {
regvalue &= ~(cfg->mask << (cfg->shift));
val = (val & cfg->mask) << (cfg->shift);
} else {
regvalue &= ~(cfg->mask >> (-cfg->shift));
val = (val & cfg->mask) >> (-cfg->shift);
}
val = val | regvalue;
ret = abx500_set_register_interruptible(dev,
(u8)cfg->bank, (u8)cfg->addr, (u8)val);
if (ret < 0) {
pr_err("abx500_set_reg failed %d, %d", ret, __LINE__);
return -EINVAL;
}
return 0;
}
static ssize_t ab8500_hwreg_write(struct file *file,
const char __user *user_buf, size_t count, loff_t *ppos)
{
struct device *dev = ((struct seq_file *)(file->private_data))->private;
char buf[128];
int buf_size, ret;
/* Get userspace string and assure termination */
buf_size = min(count, (sizeof(buf)-1));
if (copy_from_user(buf, user_buf, buf_size))
return -EFAULT;
buf[buf_size] = 0;
/* get args and process */
ret = hwreg_common_write(buf, &hwreg_cfg, dev);
return (ret) ? ret : buf_size;
}
/*
* - irq subscribe/unsubscribe stuff
*/
static int ab8500_subscribe_unsubscribe_print(struct seq_file *s, void *p)
{
seq_printf(s, "%d\n", irq_first);
return 0;
}
static int ab8500_subscribe_unsubscribe_open(struct inode *inode,
struct file *file)
{
return single_open(file, ab8500_subscribe_unsubscribe_print,
inode->i_private);
}
/*
* Userspace should use poll() on this file. When an event occur
* the blocking poll will be released.
*/
static ssize_t show_irq(struct device *dev,
struct device_attribute *attr, char *buf)
{
unsigned long name;
unsigned int irq_index;
int err;
err = kstrtoul(attr->attr.name, 0, &name);
if (err)
return err;
irq_index = name - irq_first;
if (irq_index >= num_irqs)
return -EINVAL;
return sprintf(buf, "%u\n", irq_count[irq_index]);
}
static ssize_t ab8500_subscribe_write(struct file *file,
const char __user *user_buf,
size_t count, loff_t *ppos)
{
struct device *dev = ((struct seq_file *)(file->private_data))->private;
unsigned long user_val;
int err;
unsigned int irq_index;
err = kstrtoul_from_user(user_buf, count, 0, &user_val);
if (err)
return err;
if (user_val < irq_first) {
dev_err(dev, "debugfs error input < %d\n", irq_first);
return -EINVAL;
}
if (user_val > irq_last) {
dev_err(dev, "debugfs error input > %d\n", irq_last);
return -EINVAL;
}
irq_index = user_val - irq_first;
if (irq_index >= num_irqs)
return -EINVAL;
/*
* This will create a sysfs file named <irq-nr> which userspace can
* use to select or poll and get the AB8500 events
*/
dev_attr[irq_index] = kmalloc(sizeof(struct device_attribute),
GFP_KERNEL);
if (!dev_attr[irq_index])
return -ENOMEM;
event_name[irq_index] = kmalloc(count, GFP_KERNEL);
if (!event_name[irq_index])
return -ENOMEM;
sprintf(event_name[irq_index], "%lu", user_val);
dev_attr[irq_index]->show = show_irq;
dev_attr[irq_index]->store = NULL;
dev_attr[irq_index]->attr.name = event_name[irq_index];
dev_attr[irq_index]->attr.mode = S_IRUGO;
err = sysfs_create_file(&dev->kobj, &dev_attr[irq_index]->attr);
if (err < 0) {
pr_info("sysfs_create_file failed %d\n", err);
return err;
}
err = request_threaded_irq(user_val, NULL, ab8500_debug_handler,
IRQF_SHARED | IRQF_NO_SUSPEND | IRQF_ONESHOT,
"ab8500-debug", &dev->kobj);
if (err < 0) {
pr_info("request_threaded_irq failed %d, %lu\n",
err, user_val);
sysfs_remove_file(&dev->kobj, &dev_attr[irq_index]->attr);
return err;
}
return count;
}
static ssize_t ab8500_unsubscribe_write(struct file *file,
const char __user *user_buf,
size_t count, loff_t *ppos)
{
struct device *dev = ((struct seq_file *)(file->private_data))->private;
unsigned long user_val;
int err;
unsigned int irq_index;
err = kstrtoul_from_user(user_buf, count, 0, &user_val);
if (err)
return err;
if (user_val < irq_first) {
dev_err(dev, "debugfs error input < %d\n", irq_first);
return -EINVAL;
}
if (user_val > irq_last) {
dev_err(dev, "debugfs error input > %d\n", irq_last);
return -EINVAL;
}
irq_index = user_val - irq_first;
if (irq_index >= num_irqs)
return -EINVAL;
/* Set irq count to 0 when unsubscribe */
irq_count[irq_index] = 0;
if (dev_attr[irq_index])
sysfs_remove_file(&dev->kobj, &dev_attr[irq_index]->attr);
free_irq(user_val, &dev->kobj);
kfree(event_name[irq_index]);
kfree(dev_attr[irq_index]);
return count;
}
/*
* - several deubgfs nodes fops
*/
static const struct file_operations ab8500_bank_fops = {
.open = ab8500_bank_open,
.write = ab8500_bank_write,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static const struct file_operations ab8500_address_fops = {
.open = ab8500_address_open,
.write = ab8500_address_write,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static const struct file_operations ab8500_val_fops = {
.open = ab8500_val_open,
.write = ab8500_val_write,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static const struct file_operations ab8500_interrupts_fops = {
.open = ab8500_interrupts_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static const struct file_operations ab8500_subscribe_fops = {
.open = ab8500_subscribe_unsubscribe_open,
.write = ab8500_subscribe_write,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static const struct file_operations ab8500_unsubscribe_fops = {
.open = ab8500_subscribe_unsubscribe_open,
.write = ab8500_unsubscribe_write,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static const struct file_operations ab8500_hwreg_fops = {
.open = ab8500_hwreg_open,
.write = ab8500_hwreg_write,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
static struct dentry *ab8500_dir;
static struct dentry *ab8500_gpadc_dir;
static int ab8500_debug_probe(struct platform_device *plf)
{
struct dentry *file;
struct ab8500 *ab8500;
struct resource *res;
debug_bank = AB8500_MISC;
debug_address = AB8500_REV_REG & 0x00FF;
ab8500 = dev_get_drvdata(plf->dev.parent);
num_irqs = ab8500->mask_size;
irq_count = devm_kzalloc(&plf->dev,
sizeof(*irq_count)*num_irqs, GFP_KERNEL);
if (!irq_count)
return -ENOMEM;
dev_attr = devm_kzalloc(&plf->dev,
sizeof(*dev_attr)*num_irqs, GFP_KERNEL);
if (!dev_attr)
return -ENOMEM;
event_name = devm_kzalloc(&plf->dev,
sizeof(*event_name)*num_irqs, GFP_KERNEL);
if (!event_name)
return -ENOMEM;
res = platform_get_resource_byname(plf, 0, "IRQ_AB8500");
if (!res) {
dev_err(&plf->dev, "AB8500 irq not found, err %d\n", irq_first);
return -ENXIO;
}
irq_ab8500 = res->start;
irq_first = platform_get_irq_byname(plf, "IRQ_FIRST");
if (irq_first < 0) {
dev_err(&plf->dev, "First irq not found, err %d\n", irq_first);
return irq_first;
}
irq_last = platform_get_irq_byname(plf, "IRQ_LAST");
if (irq_last < 0) {
dev_err(&plf->dev, "Last irq not found, err %d\n", irq_last);
return irq_last;
}
ab8500_dir = debugfs_create_dir(AB8500_NAME_STRING, NULL);
if (!ab8500_dir)
goto err;
ab8500_gpadc_dir = debugfs_create_dir(AB8500_ADC_NAME_STRING,
ab8500_dir);
if (!ab8500_gpadc_dir)
goto err;
file = debugfs_create_file("all-bank-registers", S_IRUGO, ab8500_dir,
&plf->dev, &ab8500_registers_fops);
if (!file)
goto err;
file = debugfs_create_file("all-banks", S_IRUGO, ab8500_dir,
&plf->dev, &ab8500_all_banks_fops);
if (!file)
goto err;
file = debugfs_create_file("register-bank",
(S_IRUGO | S_IWUSR | S_IWGRP),
ab8500_dir, &plf->dev, &ab8500_bank_fops);
if (!file)
goto err;
file = debugfs_create_file("register-address",
(S_IRUGO | S_IWUSR | S_IWGRP),
ab8500_dir, &plf->dev, &ab8500_address_fops);
if (!file)
goto err;
file = debugfs_create_file("register-value",
(S_IRUGO | S_IWUSR | S_IWGRP),
ab8500_dir, &plf->dev, &ab8500_val_fops);
if (!file)
goto err;
file = debugfs_create_file("irq-subscribe",
(S_IRUGO | S_IWUSR | S_IWGRP), ab8500_dir,
&plf->dev, &ab8500_subscribe_fops);
if (!file)
goto err;
if (is_ab8500(ab8500)) {
debug_ranges = ab8500_debug_ranges;
num_interrupt_lines = AB8500_NR_IRQS;
} else if (is_ab8505(ab8500)) {
debug_ranges = ab8505_debug_ranges;
num_interrupt_lines = AB8505_NR_IRQS;
} else if (is_ab9540(ab8500)) {
debug_ranges = ab8505_debug_ranges;
num_interrupt_lines = AB9540_NR_IRQS;
} else if (is_ab8540(ab8500)) {
debug_ranges = ab8540_debug_ranges;
num_interrupt_lines = AB8540_NR_IRQS;
}
file = debugfs_create_file("interrupts", (S_IRUGO), ab8500_dir,
&plf->dev, &ab8500_interrupts_fops);
if (!file)
goto err;
file = debugfs_create_file("irq-unsubscribe",
(S_IRUGO | S_IWUSR | S_IWGRP), ab8500_dir,
&plf->dev, &ab8500_unsubscribe_fops);
if (!file)
goto err;
file = debugfs_create_file("hwreg", (S_IRUGO | S_IWUSR | S_IWGRP),
ab8500_dir, &plf->dev, &ab8500_hwreg_fops);
if (!file)
goto err;
file = debugfs_create_file("all-modem-registers",
(S_IRUGO | S_IWUSR | S_IWGRP),
ab8500_dir, &plf->dev, &ab8500_modem_fops);
if (!file)
goto err;
file = debugfs_create_file("bat_ctrl", (S_IRUGO | S_IWUSR | S_IWGRP),
ab8500_gpadc_dir, &plf->dev,
&ab8500_gpadc_bat_ctrl_fops);
if (!file)
goto err;
file = debugfs_create_file("btemp_ball", (S_IRUGO | S_IWUSR | S_IWGRP),
ab8500_gpadc_dir,
&plf->dev, &ab8500_gpadc_btemp_ball_fops);
if (!file)
goto err;
file = debugfs_create_file("main_charger_v",
(S_IRUGO | S_IWUSR | S_IWGRP),
ab8500_gpadc_dir, &plf->dev,
&ab8500_gpadc_main_charger_v_fops);
if (!file)
goto err;
file = debugfs_create_file("acc_detect1",
(S_IRUGO | S_IWUSR | S_IWGRP),
ab8500_gpadc_dir, &plf->dev,
&ab8500_gpadc_acc_detect1_fops);
if (!file)
goto err;
file = debugfs_create_file("acc_detect2",
(S_IRUGO | S_IWUSR | S_IWGRP),
ab8500_gpadc_dir, &plf->dev,
&ab8500_gpadc_acc_detect2_fops);
if (!file)
goto err;
file = debugfs_create_file("adc_aux1", (S_IRUGO | S_IWUSR | S_IWGRP),
ab8500_gpadc_dir, &plf->dev,
&ab8500_gpadc_aux1_fops);
if (!file)
goto err;
file = debugfs_create_file("adc_aux2", (S_IRUGO | S_IWUSR | S_IWGRP),
ab8500_gpadc_dir, &plf->dev,
&ab8500_gpadc_aux2_fops);
if (!file)
goto err;
file = debugfs_create_file("main_bat_v", (S_IRUGO | S_IWUSR | S_IWGRP),
ab8500_gpadc_dir, &plf->dev,
&ab8500_gpadc_main_bat_v_fops);
if (!file)
goto err;
file = debugfs_create_file("vbus_v", (S_IRUGO | S_IWUSR | S_IWGRP),
ab8500_gpadc_dir, &plf->dev,
&ab8500_gpadc_vbus_v_fops);
if (!file)
goto err;
file = debugfs_create_file("main_charger_c",
(S_IRUGO | S_IWUSR | S_IWGRP),
ab8500_gpadc_dir, &plf->dev,
&ab8500_gpadc_main_charger_c_fops);
if (!file)
goto err;
file = debugfs_create_file("usb_charger_c",
(S_IRUGO | S_IWUSR | S_IWGRP),
ab8500_gpadc_dir,
&plf->dev, &ab8500_gpadc_usb_charger_c_fops);
if (!file)
goto err;
file = debugfs_create_file("bk_bat_v", (S_IRUGO | S_IWUSR | S_IWGRP),
ab8500_gpadc_dir, &plf->dev,
&ab8500_gpadc_bk_bat_v_fops);
if (!file)
goto err;
file = debugfs_create_file("die_temp", (S_IRUGO | S_IWUSR | S_IWGRP),
ab8500_gpadc_dir, &plf->dev,
&ab8500_gpadc_die_temp_fops);
if (!file)
goto err;
file = debugfs_create_file("usb_id", (S_IRUGO | S_IWUSR | S_IWGRP),
ab8500_gpadc_dir, &plf->dev,
&ab8500_gpadc_usb_id_fops);
if (!file)
goto err;
if (is_ab8540(ab8500)) {
file = debugfs_create_file("xtal_temp",
(S_IRUGO | S_IWUSR | S_IWGRP),
ab8500_gpadc_dir, &plf->dev,
&ab8540_gpadc_xtal_temp_fops);
if (!file)
goto err;
file = debugfs_create_file("vbattruemeas",
(S_IRUGO | S_IWUSR | S_IWGRP),
ab8500_gpadc_dir, &plf->dev,
&ab8540_gpadc_vbat_true_meas_fops);
if (!file)
goto err;
file = debugfs_create_file("batctrl_and_ibat",
(S_IRUGO | S_IWUGO),
ab8500_gpadc_dir,
&plf->dev,
&ab8540_gpadc_bat_ctrl_and_ibat_fops);
if (!file)
goto err;
file = debugfs_create_file("vbatmeas_and_ibat",
(S_IRUGO | S_IWUGO),
ab8500_gpadc_dir, &plf->dev,
&ab8540_gpadc_vbat_meas_and_ibat_fops);
if (!file)
goto err;
file = debugfs_create_file("vbattruemeas_and_ibat",
(S_IRUGO | S_IWUGO),
ab8500_gpadc_dir,
&plf->dev,
&ab8540_gpadc_vbat_true_meas_and_ibat_fops);
if (!file)
goto err;
file = debugfs_create_file("battemp_and_ibat",
(S_IRUGO | S_IWUGO),
ab8500_gpadc_dir,
&plf->dev, &ab8540_gpadc_bat_temp_and_ibat_fops);
if (!file)
goto err;
file = debugfs_create_file("otp_calib",
(S_IRUGO | S_IWUSR | S_IWGRP),
ab8500_gpadc_dir,
&plf->dev, &ab8540_gpadc_otp_calib_fops);
if (!file)
goto err;
}
file = debugfs_create_file("avg_sample", (S_IRUGO | S_IWUSR | S_IWGRP),
ab8500_gpadc_dir, &plf->dev,
&ab8500_gpadc_avg_sample_fops);
if (!file)
goto err;
file = debugfs_create_file("trig_edge", (S_IRUGO | S_IWUSR | S_IWGRP),
ab8500_gpadc_dir, &plf->dev,
&ab8500_gpadc_trig_edge_fops);
if (!file)
goto err;
file = debugfs_create_file("trig_timer", (S_IRUGO | S_IWUSR | S_IWGRP),
ab8500_gpadc_dir, &plf->dev,
&ab8500_gpadc_trig_timer_fops);
if (!file)
goto err;
file = debugfs_create_file("conv_type", (S_IRUGO | S_IWUSR | S_IWGRP),
ab8500_gpadc_dir, &plf->dev,
&ab8500_gpadc_conv_type_fops);
if (!file)
goto err;
return 0;
err:
debugfs_remove_recursive(ab8500_dir);
dev_err(&plf->dev, "failed to create debugfs entries.\n");
return -ENOMEM;
}
static int ab8500_debug_remove(struct platform_device *plf)
{
debugfs_remove_recursive(ab8500_dir);
return 0;
}
static struct platform_driver ab8500_debug_driver = {
.driver = {
.name = "ab8500-debug",
},
.probe = ab8500_debug_probe,
.remove = ab8500_debug_remove
};
static int __init ab8500_debug_init(void)
{
return platform_driver_register(&ab8500_debug_driver);
}
static void __exit ab8500_debug_exit(void)
{
platform_driver_unregister(&ab8500_debug_driver);
}
subsys_initcall(ab8500_debug_init);
module_exit(ab8500_debug_exit);
MODULE_AUTHOR("Mattias WALLIN <mattias.wallin@stericsson.com");
MODULE_DESCRIPTION("AB8500 DEBUG");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
AntonioPT/u8150-kernel-pulse-port | drivers/message/fusion/mptctl.c | 351 | 86991 | /*
* linux/drivers/message/fusion/mptctl.c
* mpt Ioctl driver.
* For use with LSI PCI chip/adapters
* running LSI Fusion MPT (Message Passing Technology) firmware.
*
* Copyright (c) 1999-2008 LSI Corporation
* (mailto:DL-MPTFusionLinux@lsi.com)
*
*/
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; 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.
NO WARRANTY
THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT
LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT,
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is
solely responsible for determining the appropriateness of using and
distributing the Program and assumes all risks associated with its
exercise of rights under this Agreement, including but not limited to
the risks and costs of program errors, damage to or loss of data,
programs or equipment, and unavailability or interruption of operations.
DISCLAIMER OF LIABILITY
NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/pci.h>
#include <linux/delay.h> /* for mdelay */
#include <linux/miscdevice.h>
#include <linux/smp_lock.h>
#include <linux/compat.h>
#include <asm/io.h>
#include <asm/uaccess.h>
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_tcq.h>
#define COPYRIGHT "Copyright (c) 1999-2008 LSI Corporation"
#define MODULEAUTHOR "LSI Corporation"
#include "mptbase.h"
#include "mptctl.h"
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
#define my_NAME "Fusion MPT misc device (ioctl) driver"
#define my_VERSION MPT_LINUX_VERSION_COMMON
#define MYNAM "mptctl"
MODULE_AUTHOR(MODULEAUTHOR);
MODULE_DESCRIPTION(my_NAME);
MODULE_LICENSE("GPL");
MODULE_VERSION(my_VERSION);
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
static u8 mptctl_id = MPT_MAX_PROTOCOL_DRIVERS;
static u8 mptctl_taskmgmt_id = MPT_MAX_PROTOCOL_DRIVERS;
static DECLARE_WAIT_QUEUE_HEAD ( mptctl_wait );
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
struct buflist {
u8 *kptr;
int len;
};
/*
* Function prototypes. Called from OS entry point mptctl_ioctl.
* arg contents specific to function.
*/
static int mptctl_fw_download(unsigned long arg);
static int mptctl_getiocinfo(unsigned long arg, unsigned int cmd);
static int mptctl_gettargetinfo(unsigned long arg);
static int mptctl_readtest(unsigned long arg);
static int mptctl_mpt_command(unsigned long arg);
static int mptctl_eventquery(unsigned long arg);
static int mptctl_eventenable(unsigned long arg);
static int mptctl_eventreport(unsigned long arg);
static int mptctl_replace_fw(unsigned long arg);
static int mptctl_do_reset(unsigned long arg);
static int mptctl_hp_hostinfo(unsigned long arg, unsigned int cmd);
static int mptctl_hp_targetinfo(unsigned long arg);
static int mptctl_probe(struct pci_dev *, const struct pci_device_id *);
static void mptctl_remove(struct pci_dev *);
#ifdef CONFIG_COMPAT
static long compat_mpctl_ioctl(struct file *f, unsigned cmd, unsigned long arg);
#endif
/*
* Private function calls.
*/
static int mptctl_do_mpt_command(struct mpt_ioctl_command karg, void __user *mfPtr);
static int mptctl_do_fw_download(int ioc, char __user *ufwbuf, size_t fwlen);
static MptSge_t *kbuf_alloc_2_sgl(int bytes, u32 dir, int sge_offset, int *frags,
struct buflist **blp, dma_addr_t *sglbuf_dma, MPT_ADAPTER *ioc);
static void kfree_sgl(MptSge_t *sgl, dma_addr_t sgl_dma,
struct buflist *buflist, MPT_ADAPTER *ioc);
static int mptctl_bus_reset(MPT_ADAPTER *ioc, u8 function);
/*
* Reset Handler cleanup function
*/
static int mptctl_ioc_reset(MPT_ADAPTER *ioc, int reset_phase);
/*
* Event Handler function
*/
static int mptctl_event_process(MPT_ADAPTER *ioc, EventNotificationReply_t *pEvReply);
static struct fasync_struct *async_queue=NULL;
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*
* Scatter gather list (SGL) sizes and limits...
*/
//#define MAX_SCSI_FRAGS 9
#define MAX_FRAGS_SPILL1 9
#define MAX_FRAGS_SPILL2 15
#define FRAGS_PER_BUCKET (MAX_FRAGS_SPILL2 + 1)
//#define MAX_CHAIN_FRAGS 64
//#define MAX_CHAIN_FRAGS (15+15+15+16)
#define MAX_CHAIN_FRAGS (4 * MAX_FRAGS_SPILL2 + 1)
// Define max sg LIST bytes ( == (#frags + #chains) * 8 bytes each)
// Works out to: 592d bytes! (9+1)*8 + 4*(15+1)*8
// ^----------------- 80 + 512
#define MAX_SGL_BYTES ((MAX_FRAGS_SPILL1 + 1 + (4 * FRAGS_PER_BUCKET)) * 8)
/* linux only seems to ever give 128kB MAX contiguous (GFP_USER) mem bytes */
#define MAX_KMALLOC_SZ (128*1024)
#define MPT_IOCTL_DEFAULT_TIMEOUT 10 /* Default timeout value (seconds) */
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* mptctl_syscall_down - Down the MPT adapter syscall semaphore.
* @ioc: Pointer to MPT adapter
* @nonblock: boolean, non-zero if O_NONBLOCK is set
*
* All of the ioctl commands can potentially sleep, which is illegal
* with a spinlock held, thus we perform mutual exclusion here.
*
* Returns negative errno on error, or zero for success.
*/
static inline int
mptctl_syscall_down(MPT_ADAPTER *ioc, int nonblock)
{
int rc = 0;
if (nonblock) {
if (!mutex_trylock(&ioc->ioctl_cmds.mutex))
rc = -EAGAIN;
} else {
if (mutex_lock_interruptible(&ioc->ioctl_cmds.mutex))
rc = -ERESTARTSYS;
}
return rc;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*
* This is the callback for any message we have posted. The message itself
* will be returned to the message pool when we return from the IRQ
*
* This runs in irq context so be short and sweet.
*/
static int
mptctl_reply(MPT_ADAPTER *ioc, MPT_FRAME_HDR *req, MPT_FRAME_HDR *reply)
{
char *sense_data;
int req_index;
int sz;
if (!req)
return 0;
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "completing mpi function "
"(0x%02X), req=%p, reply=%p\n", ioc->name, req->u.hdr.Function,
req, reply));
/*
* Handling continuation of the same reply. Processing the first
* reply, and eating the other replys that come later.
*/
if (ioc->ioctl_cmds.msg_context != req->u.hdr.MsgContext)
goto out_continuation;
ioc->ioctl_cmds.status |= MPT_MGMT_STATUS_COMMAND_GOOD;
if (!reply)
goto out;
ioc->ioctl_cmds.status |= MPT_MGMT_STATUS_RF_VALID;
sz = min(ioc->reply_sz, 4*reply->u.reply.MsgLength);
memcpy(ioc->ioctl_cmds.reply, reply, sz);
if (reply->u.reply.IOCStatus || reply->u.reply.IOCLogInfo)
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"iocstatus (0x%04X), loginfo (0x%08X)\n", ioc->name,
le16_to_cpu(reply->u.reply.IOCStatus),
le32_to_cpu(reply->u.reply.IOCLogInfo)));
if ((req->u.hdr.Function == MPI_FUNCTION_SCSI_IO_REQUEST) ||
(req->u.hdr.Function ==
MPI_FUNCTION_RAID_SCSI_IO_PASSTHROUGH)) {
if (reply->u.sreply.SCSIStatus || reply->u.sreply.SCSIState)
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"scsi_status (0x%02x), scsi_state (0x%02x), "
"tag = (0x%04x), transfer_count (0x%08x)\n", ioc->name,
reply->u.sreply.SCSIStatus,
reply->u.sreply.SCSIState,
le16_to_cpu(reply->u.sreply.TaskTag),
le32_to_cpu(reply->u.sreply.TransferCount)));
if (reply->u.sreply.SCSIState &
MPI_SCSI_STATE_AUTOSENSE_VALID) {
sz = req->u.scsireq.SenseBufferLength;
req_index =
le16_to_cpu(req->u.frame.hwhdr.msgctxu.fld.req_idx);
sense_data = ((u8 *)ioc->sense_buf_pool +
(req_index * MPT_SENSE_BUFFER_ALLOC));
memcpy(ioc->ioctl_cmds.sense, sense_data, sz);
ioc->ioctl_cmds.status |= MPT_MGMT_STATUS_SENSE_VALID;
}
}
out:
/* We are done, issue wake up
*/
if (ioc->ioctl_cmds.status & MPT_MGMT_STATUS_PENDING) {
if (req->u.hdr.Function == MPI_FUNCTION_SCSI_TASK_MGMT)
mpt_clear_taskmgmt_in_progress_flag(ioc);
ioc->ioctl_cmds.status &= ~MPT_MGMT_STATUS_PENDING;
complete(&ioc->ioctl_cmds.done);
}
out_continuation:
if (reply && (reply->u.reply.MsgFlags &
MPI_MSGFLAGS_CONTINUATION_REPLY))
return 0;
return 1;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/* mptctl_timeout_expired
*
* Expecting an interrupt, however timed out.
*
*/
static void
mptctl_timeout_expired(MPT_ADAPTER *ioc, MPT_FRAME_HDR *mf)
{
unsigned long flags;
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT ": %s\n",
ioc->name, __func__));
if (mpt_fwfault_debug)
mpt_halt_firmware(ioc);
spin_lock_irqsave(&ioc->taskmgmt_lock, flags);
if (ioc->ioc_reset_in_progress) {
spin_unlock_irqrestore(&ioc->taskmgmt_lock, flags);
CLEAR_MGMT_PENDING_STATUS(ioc->ioctl_cmds.status)
mpt_free_msg_frame(ioc, mf);
return;
}
spin_unlock_irqrestore(&ioc->taskmgmt_lock, flags);
if (!mptctl_bus_reset(ioc, mf->u.hdr.Function))
return;
/* Issue a reset for this device.
* The IOC is not responding.
*/
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT "Calling HardReset! \n",
ioc->name));
CLEAR_MGMT_PENDING_STATUS(ioc->ioctl_cmds.status)
mpt_HardResetHandler(ioc, CAN_SLEEP);
mpt_free_msg_frame(ioc, mf);
}
static int
mptctl_taskmgmt_reply(MPT_ADAPTER *ioc, MPT_FRAME_HDR *mf, MPT_FRAME_HDR *mr)
{
if (!mf)
return 0;
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"TaskMgmt completed (mf=%p, mr=%p)\n",
ioc->name, mf, mr));
ioc->taskmgmt_cmds.status |= MPT_MGMT_STATUS_COMMAND_GOOD;
if (!mr)
goto out;
ioc->taskmgmt_cmds.status |= MPT_MGMT_STATUS_RF_VALID;
memcpy(ioc->taskmgmt_cmds.reply, mr,
min(MPT_DEFAULT_FRAME_SIZE, 4 * mr->u.reply.MsgLength));
out:
if (ioc->taskmgmt_cmds.status & MPT_MGMT_STATUS_PENDING) {
mpt_clear_taskmgmt_in_progress_flag(ioc);
ioc->taskmgmt_cmds.status &= ~MPT_MGMT_STATUS_PENDING;
complete(&ioc->taskmgmt_cmds.done);
return 1;
}
return 0;
}
/* mptctl_bus_reset
*
* Bus reset code.
*
*/
static int mptctl_bus_reset(MPT_ADAPTER *ioc, u8 function)
{
MPT_FRAME_HDR *mf;
SCSITaskMgmt_t *pScsiTm;
SCSITaskMgmtReply_t *pScsiTmReply;
int ii;
int retval;
unsigned long timeout;
unsigned long time_count;
u16 iocstatus;
/* bus reset is only good for SCSI IO, RAID PASSTHRU */
if (!(function == MPI_FUNCTION_RAID_SCSI_IO_PASSTHROUGH) ||
(function == MPI_FUNCTION_SCSI_IO_REQUEST)) {
dtmprintk(ioc, printk(MYIOC_s_WARN_FMT
"TaskMgmt, not SCSI_IO!!\n", ioc->name));
return -EPERM;
}
mutex_lock(&ioc->taskmgmt_cmds.mutex);
if (mpt_set_taskmgmt_in_progress_flag(ioc) != 0) {
mutex_unlock(&ioc->taskmgmt_cmds.mutex);
return -EPERM;
}
retval = 0;
/* Send request
*/
mf = mpt_get_msg_frame(mptctl_taskmgmt_id, ioc);
if (mf == NULL) {
dtmprintk(ioc, printk(MYIOC_s_WARN_FMT
"TaskMgmt, no msg frames!!\n", ioc->name));
mpt_clear_taskmgmt_in_progress_flag(ioc);
retval = -ENOMEM;
goto mptctl_bus_reset_done;
}
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT "TaskMgmt request (mf=%p)\n",
ioc->name, mf));
pScsiTm = (SCSITaskMgmt_t *) mf;
memset(pScsiTm, 0, sizeof(SCSITaskMgmt_t));
pScsiTm->Function = MPI_FUNCTION_SCSI_TASK_MGMT;
pScsiTm->TaskType = MPI_SCSITASKMGMT_TASKTYPE_RESET_BUS;
pScsiTm->MsgFlags = MPI_SCSITASKMGMT_MSGFLAGS_LIPRESET_RESET_OPTION;
pScsiTm->TargetID = 0;
pScsiTm->Bus = 0;
pScsiTm->ChainOffset = 0;
pScsiTm->Reserved = 0;
pScsiTm->Reserved1 = 0;
pScsiTm->TaskMsgContext = 0;
for (ii= 0; ii < 8; ii++)
pScsiTm->LUN[ii] = 0;
for (ii=0; ii < 7; ii++)
pScsiTm->Reserved2[ii] = 0;
switch (ioc->bus_type) {
case FC:
timeout = 40;
break;
case SAS:
timeout = 30;
break;
case SPI:
default:
timeout = 2;
break;
}
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"TaskMgmt type=%d timeout=%ld\n",
ioc->name, MPI_SCSITASKMGMT_TASKTYPE_RESET_BUS, timeout));
INITIALIZE_MGMT_STATUS(ioc->taskmgmt_cmds.status)
CLEAR_MGMT_STATUS(ioc->taskmgmt_cmds.status)
time_count = jiffies;
if ((ioc->facts.IOCCapabilities & MPI_IOCFACTS_CAPABILITY_HIGH_PRI_Q) &&
(ioc->facts.MsgVersion >= MPI_VERSION_01_05))
mpt_put_msg_frame_hi_pri(mptctl_taskmgmt_id, ioc, mf);
else {
retval = mpt_send_handshake_request(mptctl_taskmgmt_id, ioc,
sizeof(SCSITaskMgmt_t), (u32 *)pScsiTm, CAN_SLEEP);
if (retval != 0) {
dfailprintk(ioc, printk(MYIOC_s_ERR_FMT
"TaskMgmt send_handshake FAILED!"
" (ioc %p, mf %p, rc=%d) \n", ioc->name,
ioc, mf, retval));
mpt_clear_taskmgmt_in_progress_flag(ioc);
goto mptctl_bus_reset_done;
}
}
/* Now wait for the command to complete */
ii = wait_for_completion_timeout(&ioc->taskmgmt_cmds.done, timeout*HZ);
if (!(ioc->taskmgmt_cmds.status & MPT_MGMT_STATUS_COMMAND_GOOD)) {
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"TaskMgmt failed\n", ioc->name));
mpt_free_msg_frame(ioc, mf);
mpt_clear_taskmgmt_in_progress_flag(ioc);
if (ioc->taskmgmt_cmds.status & MPT_MGMT_STATUS_DID_IOCRESET)
retval = 0;
else
retval = -1; /* return failure */
goto mptctl_bus_reset_done;
}
if (!(ioc->taskmgmt_cmds.status & MPT_MGMT_STATUS_RF_VALID)) {
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"TaskMgmt failed\n", ioc->name));
retval = -1; /* return failure */
goto mptctl_bus_reset_done;
}
pScsiTmReply = (SCSITaskMgmtReply_t *) ioc->taskmgmt_cmds.reply;
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"TaskMgmt fw_channel = %d, fw_id = %d, task_type=0x%02X, "
"iocstatus=0x%04X\n\tloginfo=0x%08X, response_code=0x%02X, "
"term_cmnds=%d\n", ioc->name, pScsiTmReply->Bus,
pScsiTmReply->TargetID, MPI_SCSITASKMGMT_TASKTYPE_RESET_BUS,
le16_to_cpu(pScsiTmReply->IOCStatus),
le32_to_cpu(pScsiTmReply->IOCLogInfo),
pScsiTmReply->ResponseCode,
le32_to_cpu(pScsiTmReply->TerminationCount)));
iocstatus = le16_to_cpu(pScsiTmReply->IOCStatus) & MPI_IOCSTATUS_MASK;
if (iocstatus == MPI_IOCSTATUS_SCSI_TASK_TERMINATED ||
iocstatus == MPI_IOCSTATUS_SCSI_IOC_TERMINATED ||
iocstatus == MPI_IOCSTATUS_SUCCESS)
retval = 0;
else {
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"TaskMgmt failed\n", ioc->name));
retval = -1; /* return failure */
}
mptctl_bus_reset_done:
mutex_unlock(&ioc->taskmgmt_cmds.mutex);
CLEAR_MGMT_STATUS(ioc->taskmgmt_cmds.status)
return retval;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/* mptctl_ioc_reset
*
* Clean-up functionality. Used only if there has been a
* reload of the FW due.
*
*/
static int
mptctl_ioc_reset(MPT_ADAPTER *ioc, int reset_phase)
{
switch(reset_phase) {
case MPT_IOC_SETUP_RESET:
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"%s: MPT_IOC_SETUP_RESET\n", ioc->name, __func__));
break;
case MPT_IOC_PRE_RESET:
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"%s: MPT_IOC_PRE_RESET\n", ioc->name, __func__));
break;
case MPT_IOC_POST_RESET:
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"%s: MPT_IOC_POST_RESET\n", ioc->name, __func__));
if (ioc->ioctl_cmds.status & MPT_MGMT_STATUS_PENDING) {
ioc->ioctl_cmds.status |= MPT_MGMT_STATUS_DID_IOCRESET;
complete(&ioc->ioctl_cmds.done);
}
break;
default:
break;
}
return 1;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/* ASYNC Event Notification Support */
static int
mptctl_event_process(MPT_ADAPTER *ioc, EventNotificationReply_t *pEvReply)
{
u8 event;
event = le32_to_cpu(pEvReply->Event) & 0xFF;
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "%s() called\n",
ioc->name, __func__));
if(async_queue == NULL)
return 1;
/* Raise SIGIO for persistent events.
* TODO - this define is not in MPI spec yet,
* but they plan to set it to 0x21
*/
if (event == 0x21 ) {
ioc->aen_event_read_flag=1;
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "Raised SIGIO to application\n",
ioc->name));
devtverboseprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"Raised SIGIO to application\n", ioc->name));
kill_fasync(&async_queue, SIGIO, POLL_IN);
return 1;
}
/* This flag is set after SIGIO was raised, and
* remains set until the application has read
* the event log via ioctl=MPTEVENTREPORT
*/
if(ioc->aen_event_read_flag)
return 1;
/* Signal only for the events that are
* requested for by the application
*/
if (ioc->events && (ioc->eventTypes & ( 1 << event))) {
ioc->aen_event_read_flag=1;
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"Raised SIGIO to application\n", ioc->name));
devtverboseprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"Raised SIGIO to application\n", ioc->name));
kill_fasync(&async_queue, SIGIO, POLL_IN);
}
return 1;
}
static int
mptctl_fasync(int fd, struct file *filep, int mode)
{
MPT_ADAPTER *ioc;
int ret;
lock_kernel();
list_for_each_entry(ioc, &ioc_list, list)
ioc->aen_event_read_flag=0;
ret = fasync_helper(fd, filep, mode, &async_queue);
unlock_kernel();
return ret;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*
* MPT ioctl handler
* cmd - specify the particular IOCTL command to be issued
* arg - data specific to the command. Must not be null.
*/
static long
__mptctl_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
mpt_ioctl_header __user *uhdr = (void __user *) arg;
mpt_ioctl_header khdr;
int iocnum;
unsigned iocnumX;
int nonblock = (file->f_flags & O_NONBLOCK);
int ret;
MPT_ADAPTER *iocp = NULL;
if (copy_from_user(&khdr, uhdr, sizeof(khdr))) {
printk(KERN_ERR MYNAM "%s::mptctl_ioctl() @%d - "
"Unable to copy mpt_ioctl_header data @ %p\n",
__FILE__, __LINE__, uhdr);
return -EFAULT;
}
ret = -ENXIO; /* (-6) No such device or address */
/* Verify intended MPT adapter - set iocnum and the adapter
* pointer (iocp)
*/
iocnumX = khdr.iocnum & 0xFF;
if (((iocnum = mpt_verify_adapter(iocnumX, &iocp)) < 0) ||
(iocp == NULL)) {
printk(KERN_DEBUG MYNAM "%s::mptctl_ioctl() @%d - ioc%d not found!\n",
__FILE__, __LINE__, iocnumX);
return -ENODEV;
}
if (!iocp->active) {
printk(KERN_DEBUG MYNAM "%s::mptctl_ioctl() @%d - Controller disabled.\n",
__FILE__, __LINE__);
return -EFAULT;
}
/* Handle those commands that are just returning
* information stored in the driver.
* These commands should never time out and are unaffected
* by TM and FW reloads.
*/
if ((cmd & ~IOCSIZE_MASK) == (MPTIOCINFO & ~IOCSIZE_MASK)) {
return mptctl_getiocinfo(arg, _IOC_SIZE(cmd));
} else if (cmd == MPTTARGETINFO) {
return mptctl_gettargetinfo(arg);
} else if (cmd == MPTTEST) {
return mptctl_readtest(arg);
} else if (cmd == MPTEVENTQUERY) {
return mptctl_eventquery(arg);
} else if (cmd == MPTEVENTENABLE) {
return mptctl_eventenable(arg);
} else if (cmd == MPTEVENTREPORT) {
return mptctl_eventreport(arg);
} else if (cmd == MPTFWREPLACE) {
return mptctl_replace_fw(arg);
}
/* All of these commands require an interrupt or
* are unknown/illegal.
*/
if ((ret = mptctl_syscall_down(iocp, nonblock)) != 0)
return ret;
if (cmd == MPTFWDOWNLOAD)
ret = mptctl_fw_download(arg);
else if (cmd == MPTCOMMAND)
ret = mptctl_mpt_command(arg);
else if (cmd == MPTHARDRESET)
ret = mptctl_do_reset(arg);
else if ((cmd & ~IOCSIZE_MASK) == (HP_GETHOSTINFO & ~IOCSIZE_MASK))
ret = mptctl_hp_hostinfo(arg, _IOC_SIZE(cmd));
else if (cmd == HP_GETTARGETINFO)
ret = mptctl_hp_targetinfo(arg);
else
ret = -EINVAL;
mutex_unlock(&iocp->ioctl_cmds.mutex);
return ret;
}
static long
mptctl_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
long ret;
lock_kernel();
ret = __mptctl_ioctl(file, cmd, arg);
unlock_kernel();
return ret;
}
static int mptctl_do_reset(unsigned long arg)
{
struct mpt_ioctl_diag_reset __user *urinfo = (void __user *) arg;
struct mpt_ioctl_diag_reset krinfo;
MPT_ADAPTER *iocp;
if (copy_from_user(&krinfo, urinfo, sizeof(struct mpt_ioctl_diag_reset))) {
printk(KERN_ERR MYNAM "%s@%d::mptctl_do_reset - "
"Unable to copy mpt_ioctl_diag_reset struct @ %p\n",
__FILE__, __LINE__, urinfo);
return -EFAULT;
}
if (mpt_verify_adapter(krinfo.hdr.iocnum, &iocp) < 0) {
printk(KERN_DEBUG MYNAM "%s@%d::mptctl_do_reset - ioc%d not found!\n",
__FILE__, __LINE__, krinfo.hdr.iocnum);
return -ENODEV; /* (-6) No such device or address */
}
dctlprintk(iocp, printk(MYIOC_s_DEBUG_FMT "mptctl_do_reset called.\n",
iocp->name));
if (mpt_HardResetHandler(iocp, CAN_SLEEP) != 0) {
printk (MYIOC_s_ERR_FMT "%s@%d::mptctl_do_reset - reset failed.\n",
iocp->name, __FILE__, __LINE__);
return -1;
}
return 0;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*
* MPT FW download function. Cast the arg into the mpt_fw_xfer structure.
* This structure contains: iocnum, firmware length (bytes),
* pointer to user space memory where the fw image is stored.
*
* Outputs: None.
* Return: 0 if successful
* -EFAULT if data unavailable
* -ENXIO if no such device
* -EAGAIN if resource problem
* -ENOMEM if no memory for SGE
* -EMLINK if too many chain buffers required
* -EBADRQC if adapter does not support FW download
* -EBUSY if adapter is busy
* -ENOMSG if FW upload returned bad status
*/
static int
mptctl_fw_download(unsigned long arg)
{
struct mpt_fw_xfer __user *ufwdl = (void __user *) arg;
struct mpt_fw_xfer kfwdl;
if (copy_from_user(&kfwdl, ufwdl, sizeof(struct mpt_fw_xfer))) {
printk(KERN_ERR MYNAM "%s@%d::_ioctl_fwdl - "
"Unable to copy mpt_fw_xfer struct @ %p\n",
__FILE__, __LINE__, ufwdl);
return -EFAULT;
}
return mptctl_do_fw_download(kfwdl.iocnum, kfwdl.bufp, kfwdl.fwlen);
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*
* FW Download engine.
* Outputs: None.
* Return: 0 if successful
* -EFAULT if data unavailable
* -ENXIO if no such device
* -EAGAIN if resource problem
* -ENOMEM if no memory for SGE
* -EMLINK if too many chain buffers required
* -EBADRQC if adapter does not support FW download
* -EBUSY if adapter is busy
* -ENOMSG if FW upload returned bad status
*/
static int
mptctl_do_fw_download(int ioc, char __user *ufwbuf, size_t fwlen)
{
FWDownload_t *dlmsg;
MPT_FRAME_HDR *mf;
MPT_ADAPTER *iocp;
FWDownloadTCSGE_t *ptsge;
MptSge_t *sgl, *sgIn;
char *sgOut;
struct buflist *buflist;
struct buflist *bl;
dma_addr_t sgl_dma;
int ret;
int numfrags = 0;
int maxfrags;
int n = 0;
u32 sgdir;
u32 nib;
int fw_bytes_copied = 0;
int i;
int sge_offset = 0;
u16 iocstat;
pFWDownloadReply_t ReplyMsg = NULL;
unsigned long timeleft;
if (mpt_verify_adapter(ioc, &iocp) < 0) {
printk(KERN_DEBUG MYNAM "ioctl_fwdl - ioc%d not found!\n",
ioc);
return -ENODEV; /* (-6) No such device or address */
} else {
/* Valid device. Get a message frame and construct the FW download message.
*/
if ((mf = mpt_get_msg_frame(mptctl_id, iocp)) == NULL)
return -EAGAIN;
}
dctlprintk(iocp, printk(MYIOC_s_DEBUG_FMT
"mptctl_do_fwdl called. mptctl_id = %xh.\n", iocp->name, mptctl_id));
dctlprintk(iocp, printk(MYIOC_s_DEBUG_FMT "DbG: kfwdl.bufp = %p\n",
iocp->name, ufwbuf));
dctlprintk(iocp, printk(MYIOC_s_DEBUG_FMT "DbG: kfwdl.fwlen = %d\n",
iocp->name, (int)fwlen));
dctlprintk(iocp, printk(MYIOC_s_DEBUG_FMT "DbG: kfwdl.ioc = %04xh\n",
iocp->name, ioc));
dlmsg = (FWDownload_t*) mf;
ptsge = (FWDownloadTCSGE_t *) &dlmsg->SGL;
sgOut = (char *) (ptsge + 1);
/*
* Construct f/w download request
*/
dlmsg->ImageType = MPI_FW_DOWNLOAD_ITYPE_FW;
dlmsg->Reserved = 0;
dlmsg->ChainOffset = 0;
dlmsg->Function = MPI_FUNCTION_FW_DOWNLOAD;
dlmsg->Reserved1[0] = dlmsg->Reserved1[1] = dlmsg->Reserved1[2] = 0;
if (iocp->facts.MsgVersion >= MPI_VERSION_01_05)
dlmsg->MsgFlags = MPI_FW_DOWNLOAD_MSGFLGS_LAST_SEGMENT;
else
dlmsg->MsgFlags = 0;
/* Set up the Transaction SGE.
*/
ptsge->Reserved = 0;
ptsge->ContextSize = 0;
ptsge->DetailsLength = 12;
ptsge->Flags = MPI_SGE_FLAGS_TRANSACTION_ELEMENT;
ptsge->Reserved_0100_Checksum = 0;
ptsge->ImageOffset = 0;
ptsge->ImageSize = cpu_to_le32(fwlen);
/* Add the SGL
*/
/*
* Need to kmalloc area(s) for holding firmware image bytes.
* But we need to do it piece meal, using a proper
* scatter gather list (with 128kB MAX hunks).
*
* A practical limit here might be # of sg hunks that fit into
* a single IOC request frame; 12 or 8 (see below), so:
* For FC9xx: 12 x 128kB == 1.5 mB (max)
* For C1030: 8 x 128kB == 1 mB (max)
* We could support chaining, but things get ugly(ier:)
*
* Set the sge_offset to the start of the sgl (bytes).
*/
sgdir = 0x04000000; /* IOC will READ from sys mem */
sge_offset = sizeof(MPIHeader_t) + sizeof(FWDownloadTCSGE_t);
if ((sgl = kbuf_alloc_2_sgl(fwlen, sgdir, sge_offset,
&numfrags, &buflist, &sgl_dma, iocp)) == NULL)
return -ENOMEM;
/*
* We should only need SGL with 2 simple_32bit entries (up to 256 kB)
* for FC9xx f/w image, but calculate max number of sge hunks
* we can fit into a request frame, and limit ourselves to that.
* (currently no chain support)
* maxfrags = (Request Size - FWdownload Size ) / Size of 32 bit SGE
* Request maxfrags
* 128 12
* 96 8
* 64 4
*/
maxfrags = (iocp->req_sz - sizeof(MPIHeader_t) -
sizeof(FWDownloadTCSGE_t))
/ iocp->SGE_size;
if (numfrags > maxfrags) {
ret = -EMLINK;
goto fwdl_out;
}
dctlprintk(iocp, printk(MYIOC_s_DEBUG_FMT "DbG: sgl buffer = %p, sgfrags = %d\n",
iocp->name, sgl, numfrags));
/*
* Parse SG list, copying sgl itself,
* plus f/w image hunks from user space as we go...
*/
ret = -EFAULT;
sgIn = sgl;
bl = buflist;
for (i=0; i < numfrags; i++) {
/* Get the SGE type: 0 - TCSGE, 3 - Chain, 1 - Simple SGE
* Skip everything but Simple. If simple, copy from
* user space into kernel space.
* Note: we should not have anything but Simple as
* Chain SGE are illegal.
*/
nib = (sgIn->FlagsLength & 0x30000000) >> 28;
if (nib == 0 || nib == 3) {
;
} else if (sgIn->Address) {
iocp->add_sge(sgOut, sgIn->FlagsLength, sgIn->Address);
n++;
if (copy_from_user(bl->kptr, ufwbuf+fw_bytes_copied, bl->len)) {
printk(MYIOC_s_ERR_FMT "%s@%d::_ioctl_fwdl - "
"Unable to copy f/w buffer hunk#%d @ %p\n",
iocp->name, __FILE__, __LINE__, n, ufwbuf);
goto fwdl_out;
}
fw_bytes_copied += bl->len;
}
sgIn++;
bl++;
sgOut += iocp->SGE_size;
}
DBG_DUMP_FW_DOWNLOAD(iocp, (u32 *)mf, numfrags);
/*
* Finally, perform firmware download.
*/
ReplyMsg = NULL;
SET_MGMT_MSG_CONTEXT(iocp->ioctl_cmds.msg_context, dlmsg->MsgContext);
INITIALIZE_MGMT_STATUS(iocp->ioctl_cmds.status)
mpt_put_msg_frame(mptctl_id, iocp, mf);
/* Now wait for the command to complete */
retry_wait:
timeleft = wait_for_completion_timeout(&iocp->ioctl_cmds.done, HZ*60);
if (!(iocp->ioctl_cmds.status & MPT_MGMT_STATUS_COMMAND_GOOD)) {
ret = -ETIME;
printk(MYIOC_s_WARN_FMT "%s: failed\n", iocp->name, __func__);
if (iocp->ioctl_cmds.status & MPT_MGMT_STATUS_DID_IOCRESET) {
mpt_free_msg_frame(iocp, mf);
goto fwdl_out;
}
if (!timeleft)
mptctl_timeout_expired(iocp, mf);
else
goto retry_wait;
goto fwdl_out;
}
if (!(iocp->ioctl_cmds.status & MPT_MGMT_STATUS_RF_VALID)) {
printk(MYIOC_s_WARN_FMT "%s: failed\n", iocp->name, __func__);
mpt_free_msg_frame(iocp, mf);
ret = -ENODATA;
goto fwdl_out;
}
if (sgl)
kfree_sgl(sgl, sgl_dma, buflist, iocp);
ReplyMsg = (pFWDownloadReply_t)iocp->ioctl_cmds.reply;
iocstat = le16_to_cpu(ReplyMsg->IOCStatus) & MPI_IOCSTATUS_MASK;
if (iocstat == MPI_IOCSTATUS_SUCCESS) {
printk(MYIOC_s_INFO_FMT "F/W update successfull!\n", iocp->name);
return 0;
} else if (iocstat == MPI_IOCSTATUS_INVALID_FUNCTION) {
printk(MYIOC_s_WARN_FMT "Hmmm... F/W download not supported!?!\n",
iocp->name);
printk(MYIOC_s_WARN_FMT "(time to go bang on somebodies door)\n",
iocp->name);
return -EBADRQC;
} else if (iocstat == MPI_IOCSTATUS_BUSY) {
printk(MYIOC_s_WARN_FMT "IOC_BUSY!\n", iocp->name);
printk(MYIOC_s_WARN_FMT "(try again later?)\n", iocp->name);
return -EBUSY;
} else {
printk(MYIOC_s_WARN_FMT "ioctl_fwdl() returned [bad] status = %04xh\n",
iocp->name, iocstat);
printk(MYIOC_s_WARN_FMT "(bad VooDoo)\n", iocp->name);
return -ENOMSG;
}
return 0;
fwdl_out:
CLEAR_MGMT_STATUS(iocp->ioctl_cmds.status);
SET_MGMT_MSG_CONTEXT(iocp->ioctl_cmds.msg_context, 0);
kfree_sgl(sgl, sgl_dma, buflist, iocp);
return ret;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*
* SGE Allocation routine
*
* Inputs: bytes - number of bytes to be transferred
* sgdir - data direction
* sge_offset - offset (in bytes) from the start of the request
* frame to the first SGE
* ioc - pointer to the mptadapter
* Outputs: frags - number of scatter gather elements
* blp - point to the buflist pointer
* sglbuf_dma - pointer to the (dma) sgl
* Returns: Null if failes
* pointer to the (virtual) sgl if successful.
*/
static MptSge_t *
kbuf_alloc_2_sgl(int bytes, u32 sgdir, int sge_offset, int *frags,
struct buflist **blp, dma_addr_t *sglbuf_dma, MPT_ADAPTER *ioc)
{
MptSge_t *sglbuf = NULL; /* pointer to array of SGE */
/* and chain buffers */
struct buflist *buflist = NULL; /* kernel routine */
MptSge_t *sgl;
int numfrags = 0;
int fragcnt = 0;
int alloc_sz = min(bytes,MAX_KMALLOC_SZ); // avoid kernel warning msg!
int bytes_allocd = 0;
int this_alloc;
dma_addr_t pa; // phys addr
int i, buflist_ent;
int sg_spill = MAX_FRAGS_SPILL1;
int dir;
/* initialization */
*frags = 0;
*blp = NULL;
/* Allocate and initialize an array of kernel
* structures for the SG elements.
*/
i = MAX_SGL_BYTES / 8;
buflist = kzalloc(i, GFP_USER);
if (!buflist)
return NULL;
buflist_ent = 0;
/* Allocate a single block of memory to store the sg elements and
* the chain buffers. The calling routine is responsible for
* copying the data in this array into the correct place in the
* request and chain buffers.
*/
sglbuf = pci_alloc_consistent(ioc->pcidev, MAX_SGL_BYTES, sglbuf_dma);
if (sglbuf == NULL)
goto free_and_fail;
if (sgdir & 0x04000000)
dir = PCI_DMA_TODEVICE;
else
dir = PCI_DMA_FROMDEVICE;
/* At start:
* sgl = sglbuf = point to beginning of sg buffer
* buflist_ent = 0 = first kernel structure
* sg_spill = number of SGE that can be written before the first
* chain element.
*
*/
sgl = sglbuf;
sg_spill = ((ioc->req_sz - sge_offset)/ioc->SGE_size) - 1;
while (bytes_allocd < bytes) {
this_alloc = min(alloc_sz, bytes-bytes_allocd);
buflist[buflist_ent].len = this_alloc;
buflist[buflist_ent].kptr = pci_alloc_consistent(ioc->pcidev,
this_alloc,
&pa);
if (buflist[buflist_ent].kptr == NULL) {
alloc_sz = alloc_sz / 2;
if (alloc_sz == 0) {
printk(MYIOC_s_WARN_FMT "-SG: No can do - "
"not enough memory! :-(\n", ioc->name);
printk(MYIOC_s_WARN_FMT "-SG: (freeing %d frags)\n",
ioc->name, numfrags);
goto free_and_fail;
}
continue;
} else {
dma_addr_t dma_addr;
bytes_allocd += this_alloc;
sgl->FlagsLength = (0x10000000|sgdir|this_alloc);
dma_addr = pci_map_single(ioc->pcidev,
buflist[buflist_ent].kptr, this_alloc, dir);
sgl->Address = dma_addr;
fragcnt++;
numfrags++;
sgl++;
buflist_ent++;
}
if (bytes_allocd >= bytes)
break;
/* Need to chain? */
if (fragcnt == sg_spill) {
printk(MYIOC_s_WARN_FMT
"-SG: No can do - " "Chain required! :-(\n", ioc->name);
printk(MYIOC_s_WARN_FMT "(freeing %d frags)\n", ioc->name, numfrags);
goto free_and_fail;
}
/* overflow check... */
if (numfrags*8 > MAX_SGL_BYTES){
/* GRRRRR... */
printk(MYIOC_s_WARN_FMT "-SG: No can do - "
"too many SG frags! :-(\n", ioc->name);
printk(MYIOC_s_WARN_FMT "-SG: (freeing %d frags)\n",
ioc->name, numfrags);
goto free_and_fail;
}
}
/* Last sge fixup: set LE+eol+eob bits */
sgl[-1].FlagsLength |= 0xC1000000;
*frags = numfrags;
*blp = buflist;
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "-SG: kbuf_alloc_2_sgl() - "
"%d SG frags generated!\n", ioc->name, numfrags));
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "-SG: kbuf_alloc_2_sgl() - "
"last (big) alloc_sz=%d\n", ioc->name, alloc_sz));
return sglbuf;
free_and_fail:
if (sglbuf != NULL) {
for (i = 0; i < numfrags; i++) {
dma_addr_t dma_addr;
u8 *kptr;
int len;
if ((sglbuf[i].FlagsLength >> 24) == 0x30)
continue;
dma_addr = sglbuf[i].Address;
kptr = buflist[i].kptr;
len = buflist[i].len;
pci_free_consistent(ioc->pcidev, len, kptr, dma_addr);
}
pci_free_consistent(ioc->pcidev, MAX_SGL_BYTES, sglbuf, *sglbuf_dma);
}
kfree(buflist);
return NULL;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*
* Routine to free the SGL elements.
*/
static void
kfree_sgl(MptSge_t *sgl, dma_addr_t sgl_dma, struct buflist *buflist, MPT_ADAPTER *ioc)
{
MptSge_t *sg = sgl;
struct buflist *bl = buflist;
u32 nib;
int dir;
int n = 0;
if (sg->FlagsLength & 0x04000000)
dir = PCI_DMA_TODEVICE;
else
dir = PCI_DMA_FROMDEVICE;
nib = (sg->FlagsLength & 0xF0000000) >> 28;
while (! (nib & 0x4)) { /* eob */
/* skip ignore/chain. */
if (nib == 0 || nib == 3) {
;
} else if (sg->Address) {
dma_addr_t dma_addr;
void *kptr;
int len;
dma_addr = sg->Address;
kptr = bl->kptr;
len = bl->len;
pci_unmap_single(ioc->pcidev, dma_addr, len, dir);
pci_free_consistent(ioc->pcidev, len, kptr, dma_addr);
n++;
}
sg++;
bl++;
nib = (le32_to_cpu(sg->FlagsLength) & 0xF0000000) >> 28;
}
/* we're at eob! */
if (sg->Address) {
dma_addr_t dma_addr;
void *kptr;
int len;
dma_addr = sg->Address;
kptr = bl->kptr;
len = bl->len;
pci_unmap_single(ioc->pcidev, dma_addr, len, dir);
pci_free_consistent(ioc->pcidev, len, kptr, dma_addr);
n++;
}
pci_free_consistent(ioc->pcidev, MAX_SGL_BYTES, sgl, sgl_dma);
kfree(buflist);
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "-SG: Free'd 1 SGL buf + %d kbufs!\n",
ioc->name, n));
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*
* mptctl_getiocinfo - Query the host adapter for IOC information.
* @arg: User space argument
*
* Outputs: None.
* Return: 0 if successful
* -EFAULT if data unavailable
* -ENODEV if no such device/adapter
*/
static int
mptctl_getiocinfo (unsigned long arg, unsigned int data_size)
{
struct mpt_ioctl_iocinfo __user *uarg = (void __user *) arg;
struct mpt_ioctl_iocinfo *karg;
MPT_ADAPTER *ioc;
struct pci_dev *pdev;
int iocnum;
unsigned int port;
int cim_rev;
u8 revision;
struct scsi_device *sdev;
VirtDevice *vdevice;
/* Add of PCI INFO results in unaligned access for
* IA64 and Sparc. Reset long to int. Return no PCI
* data for obsolete format.
*/
if (data_size == sizeof(struct mpt_ioctl_iocinfo_rev0))
cim_rev = 0;
else if (data_size == sizeof(struct mpt_ioctl_iocinfo_rev1))
cim_rev = 1;
else if (data_size == sizeof(struct mpt_ioctl_iocinfo))
cim_rev = 2;
else if (data_size == (sizeof(struct mpt_ioctl_iocinfo_rev0)+12))
cim_rev = 0; /* obsolete */
else
return -EFAULT;
karg = kmalloc(data_size, GFP_KERNEL);
if (karg == NULL) {
printk(KERN_ERR MYNAM "%s::mpt_ioctl_iocinfo() @%d - no memory available!\n",
__FILE__, __LINE__);
return -ENOMEM;
}
if (copy_from_user(karg, uarg, data_size)) {
printk(KERN_ERR MYNAM "%s@%d::mptctl_getiocinfo - "
"Unable to read in mpt_ioctl_iocinfo struct @ %p\n",
__FILE__, __LINE__, uarg);
kfree(karg);
return -EFAULT;
}
if (((iocnum = mpt_verify_adapter(karg->hdr.iocnum, &ioc)) < 0) ||
(ioc == NULL)) {
printk(KERN_DEBUG MYNAM "%s::mptctl_getiocinfo() @%d - ioc%d not found!\n",
__FILE__, __LINE__, iocnum);
kfree(karg);
return -ENODEV;
}
/* Verify the data transfer size is correct. */
if (karg->hdr.maxDataSize != data_size) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_getiocinfo - "
"Structure size mismatch. Command not completed.\n",
ioc->name, __FILE__, __LINE__);
kfree(karg);
return -EFAULT;
}
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "mptctl_getiocinfo called.\n",
ioc->name));
/* Fill in the data and return the structure to the calling
* program
*/
if (ioc->bus_type == SAS)
karg->adapterType = MPT_IOCTL_INTERFACE_SAS;
else if (ioc->bus_type == FC)
karg->adapterType = MPT_IOCTL_INTERFACE_FC;
else
karg->adapterType = MPT_IOCTL_INTERFACE_SCSI;
if (karg->hdr.port > 1)
return -EINVAL;
port = karg->hdr.port;
karg->port = port;
pdev = (struct pci_dev *) ioc->pcidev;
karg->pciId = pdev->device;
pci_read_config_byte(pdev, PCI_CLASS_REVISION, &revision);
karg->hwRev = revision;
karg->subSystemDevice = pdev->subsystem_device;
karg->subSystemVendor = pdev->subsystem_vendor;
if (cim_rev == 1) {
/* Get the PCI bus, device, and function numbers for the IOC
*/
karg->pciInfo.u.bits.busNumber = pdev->bus->number;
karg->pciInfo.u.bits.deviceNumber = PCI_SLOT( pdev->devfn );
karg->pciInfo.u.bits.functionNumber = PCI_FUNC( pdev->devfn );
} else if (cim_rev == 2) {
/* Get the PCI bus, device, function and segment ID numbers
for the IOC */
karg->pciInfo.u.bits.busNumber = pdev->bus->number;
karg->pciInfo.u.bits.deviceNumber = PCI_SLOT( pdev->devfn );
karg->pciInfo.u.bits.functionNumber = PCI_FUNC( pdev->devfn );
karg->pciInfo.segmentID = pci_domain_nr(pdev->bus);
}
/* Get number of devices
*/
karg->numDevices = 0;
if (ioc->sh) {
shost_for_each_device(sdev, ioc->sh) {
vdevice = sdev->hostdata;
if (vdevice->vtarget->tflags &
MPT_TARGET_FLAGS_RAID_COMPONENT)
continue;
karg->numDevices++;
}
}
/* Set the BIOS and FW Version
*/
karg->FWVersion = ioc->facts.FWVersion.Word;
karg->BIOSVersion = ioc->biosVersion;
/* Set the Version Strings.
*/
strncpy (karg->driverVersion, MPT_LINUX_PACKAGE_NAME, MPT_IOCTL_VERSION_LENGTH);
karg->driverVersion[MPT_IOCTL_VERSION_LENGTH-1]='\0';
karg->busChangeEvent = 0;
karg->hostId = ioc->pfacts[port].PortSCSIID;
karg->rsvd[0] = karg->rsvd[1] = 0;
/* Copy the data from kernel memory to user memory
*/
if (copy_to_user((char __user *)arg, karg, data_size)) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_getiocinfo - "
"Unable to write out mpt_ioctl_iocinfo struct @ %p\n",
ioc->name, __FILE__, __LINE__, uarg);
kfree(karg);
return -EFAULT;
}
kfree(karg);
return 0;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*
* mptctl_gettargetinfo - Query the host adapter for target information.
* @arg: User space argument
*
* Outputs: None.
* Return: 0 if successful
* -EFAULT if data unavailable
* -ENODEV if no such device/adapter
*/
static int
mptctl_gettargetinfo (unsigned long arg)
{
struct mpt_ioctl_targetinfo __user *uarg = (void __user *) arg;
struct mpt_ioctl_targetinfo karg;
MPT_ADAPTER *ioc;
VirtDevice *vdevice;
char *pmem;
int *pdata;
int iocnum;
int numDevices = 0;
int lun;
int maxWordsLeft;
int numBytes;
u8 port;
struct scsi_device *sdev;
if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_targetinfo))) {
printk(KERN_ERR MYNAM "%s@%d::mptctl_gettargetinfo - "
"Unable to read in mpt_ioctl_targetinfo struct @ %p\n",
__FILE__, __LINE__, uarg);
return -EFAULT;
}
if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
(ioc == NULL)) {
printk(KERN_DEBUG MYNAM "%s::mptctl_gettargetinfo() @%d - ioc%d not found!\n",
__FILE__, __LINE__, iocnum);
return -ENODEV;
}
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "mptctl_gettargetinfo called.\n",
ioc->name));
/* Get the port number and set the maximum number of bytes
* in the returned structure.
* Ignore the port setting.
*/
numBytes = karg.hdr.maxDataSize - sizeof(mpt_ioctl_header);
maxWordsLeft = numBytes/sizeof(int);
port = karg.hdr.port;
if (maxWordsLeft <= 0) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_gettargetinfo() - no memory available!\n",
ioc->name, __FILE__, __LINE__);
return -ENOMEM;
}
/* Fill in the data and return the structure to the calling
* program
*/
/* struct mpt_ioctl_targetinfo does not contain sufficient space
* for the target structures so when the IOCTL is called, there is
* not sufficient stack space for the structure. Allocate memory,
* populate the memory, copy back to the user, then free memory.
* targetInfo format:
* bits 31-24: reserved
* 23-16: LUN
* 15- 8: Bus Number
* 7- 0: Target ID
*/
pmem = kzalloc(numBytes, GFP_KERNEL);
if (!pmem) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_gettargetinfo() - no memory available!\n",
ioc->name, __FILE__, __LINE__);
return -ENOMEM;
}
pdata = (int *) pmem;
/* Get number of devices
*/
if (ioc->sh){
shost_for_each_device(sdev, ioc->sh) {
if (!maxWordsLeft)
continue;
vdevice = sdev->hostdata;
if (vdevice->vtarget->tflags &
MPT_TARGET_FLAGS_RAID_COMPONENT)
continue;
lun = (vdevice->vtarget->raidVolume) ? 0x80 : vdevice->lun;
*pdata = (((u8)lun << 16) + (vdevice->vtarget->channel << 8) +
(vdevice->vtarget->id ));
pdata++;
numDevices++;
--maxWordsLeft;
}
}
karg.numDevices = numDevices;
/* Copy part of the data from kernel memory to user memory
*/
if (copy_to_user((char __user *)arg, &karg,
sizeof(struct mpt_ioctl_targetinfo))) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_gettargetinfo - "
"Unable to write out mpt_ioctl_targetinfo struct @ %p\n",
ioc->name, __FILE__, __LINE__, uarg);
kfree(pmem);
return -EFAULT;
}
/* Copy the remaining data from kernel memory to user memory
*/
if (copy_to_user(uarg->targetInfo, pmem, numBytes)) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_gettargetinfo - "
"Unable to write out mpt_ioctl_targetinfo struct @ %p\n",
ioc->name, __FILE__, __LINE__, pdata);
kfree(pmem);
return -EFAULT;
}
kfree(pmem);
return 0;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/* MPT IOCTL Test function.
*
* Outputs: None.
* Return: 0 if successful
* -EFAULT if data unavailable
* -ENODEV if no such device/adapter
*/
static int
mptctl_readtest (unsigned long arg)
{
struct mpt_ioctl_test __user *uarg = (void __user *) arg;
struct mpt_ioctl_test karg;
MPT_ADAPTER *ioc;
int iocnum;
if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_test))) {
printk(KERN_ERR MYNAM "%s@%d::mptctl_readtest - "
"Unable to read in mpt_ioctl_test struct @ %p\n",
__FILE__, __LINE__, uarg);
return -EFAULT;
}
if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
(ioc == NULL)) {
printk(KERN_DEBUG MYNAM "%s::mptctl_readtest() @%d - ioc%d not found!\n",
__FILE__, __LINE__, iocnum);
return -ENODEV;
}
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "mptctl_readtest called.\n",
ioc->name));
/* Fill in the data and return the structure to the calling
* program
*/
#ifdef MFCNT
karg.chip_type = ioc->mfcnt;
#else
karg.chip_type = ioc->pcidev->device;
#endif
strncpy (karg.name, ioc->name, MPT_MAX_NAME);
karg.name[MPT_MAX_NAME-1]='\0';
strncpy (karg.product, ioc->prod_name, MPT_PRODUCT_LENGTH);
karg.product[MPT_PRODUCT_LENGTH-1]='\0';
/* Copy the data from kernel memory to user memory
*/
if (copy_to_user((char __user *)arg, &karg, sizeof(struct mpt_ioctl_test))) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_readtest - "
"Unable to write out mpt_ioctl_test struct @ %p\n",
ioc->name, __FILE__, __LINE__, uarg);
return -EFAULT;
}
return 0;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*
* mptctl_eventquery - Query the host adapter for the event types
* that are being logged.
* @arg: User space argument
*
* Outputs: None.
* Return: 0 if successful
* -EFAULT if data unavailable
* -ENODEV if no such device/adapter
*/
static int
mptctl_eventquery (unsigned long arg)
{
struct mpt_ioctl_eventquery __user *uarg = (void __user *) arg;
struct mpt_ioctl_eventquery karg;
MPT_ADAPTER *ioc;
int iocnum;
if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_eventquery))) {
printk(KERN_ERR MYNAM "%s@%d::mptctl_eventquery - "
"Unable to read in mpt_ioctl_eventquery struct @ %p\n",
__FILE__, __LINE__, uarg);
return -EFAULT;
}
if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
(ioc == NULL)) {
printk(KERN_DEBUG MYNAM "%s::mptctl_eventquery() @%d - ioc%d not found!\n",
__FILE__, __LINE__, iocnum);
return -ENODEV;
}
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "mptctl_eventquery called.\n",
ioc->name));
karg.eventEntries = MPTCTL_EVENT_LOG_SIZE;
karg.eventTypes = ioc->eventTypes;
/* Copy the data from kernel memory to user memory
*/
if (copy_to_user((char __user *)arg, &karg, sizeof(struct mpt_ioctl_eventquery))) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_eventquery - "
"Unable to write out mpt_ioctl_eventquery struct @ %p\n",
ioc->name, __FILE__, __LINE__, uarg);
return -EFAULT;
}
return 0;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
static int
mptctl_eventenable (unsigned long arg)
{
struct mpt_ioctl_eventenable __user *uarg = (void __user *) arg;
struct mpt_ioctl_eventenable karg;
MPT_ADAPTER *ioc;
int iocnum;
if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_eventenable))) {
printk(KERN_ERR MYNAM "%s@%d::mptctl_eventenable - "
"Unable to read in mpt_ioctl_eventenable struct @ %p\n",
__FILE__, __LINE__, uarg);
return -EFAULT;
}
if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
(ioc == NULL)) {
printk(KERN_DEBUG MYNAM "%s::mptctl_eventenable() @%d - ioc%d not found!\n",
__FILE__, __LINE__, iocnum);
return -ENODEV;
}
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "mptctl_eventenable called.\n",
ioc->name));
if (ioc->events == NULL) {
/* Have not yet allocated memory - do so now.
*/
int sz = MPTCTL_EVENT_LOG_SIZE * sizeof(MPT_IOCTL_EVENTS);
ioc->events = kzalloc(sz, GFP_KERNEL);
if (!ioc->events) {
printk(MYIOC_s_ERR_FMT
": ERROR - Insufficient memory to add adapter!\n",
ioc->name);
return -ENOMEM;
}
ioc->alloc_total += sz;
ioc->eventContext = 0;
}
/* Update the IOC event logging flag.
*/
ioc->eventTypes = karg.eventTypes;
return 0;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
static int
mptctl_eventreport (unsigned long arg)
{
struct mpt_ioctl_eventreport __user *uarg = (void __user *) arg;
struct mpt_ioctl_eventreport karg;
MPT_ADAPTER *ioc;
int iocnum;
int numBytes, maxEvents, max;
if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_eventreport))) {
printk(KERN_ERR MYNAM "%s@%d::mptctl_eventreport - "
"Unable to read in mpt_ioctl_eventreport struct @ %p\n",
__FILE__, __LINE__, uarg);
return -EFAULT;
}
if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
(ioc == NULL)) {
printk(KERN_DEBUG MYNAM "%s::mptctl_eventreport() @%d - ioc%d not found!\n",
__FILE__, __LINE__, iocnum);
return -ENODEV;
}
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "mptctl_eventreport called.\n",
ioc->name));
numBytes = karg.hdr.maxDataSize - sizeof(mpt_ioctl_header);
maxEvents = numBytes/sizeof(MPT_IOCTL_EVENTS);
max = MPTCTL_EVENT_LOG_SIZE < maxEvents ? MPTCTL_EVENT_LOG_SIZE : maxEvents;
/* If fewer than 1 event is requested, there must have
* been some type of error.
*/
if ((max < 1) || !ioc->events)
return -ENODATA;
/* reset this flag so SIGIO can restart */
ioc->aen_event_read_flag=0;
/* Copy the data from kernel memory to user memory
*/
numBytes = max * sizeof(MPT_IOCTL_EVENTS);
if (copy_to_user(uarg->eventData, ioc->events, numBytes)) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_eventreport - "
"Unable to write out mpt_ioctl_eventreport struct @ %p\n",
ioc->name, __FILE__, __LINE__, ioc->events);
return -EFAULT;
}
return 0;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
static int
mptctl_replace_fw (unsigned long arg)
{
struct mpt_ioctl_replace_fw __user *uarg = (void __user *) arg;
struct mpt_ioctl_replace_fw karg;
MPT_ADAPTER *ioc;
int iocnum;
int newFwSize;
if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_replace_fw))) {
printk(KERN_ERR MYNAM "%s@%d::mptctl_replace_fw - "
"Unable to read in mpt_ioctl_replace_fw struct @ %p\n",
__FILE__, __LINE__, uarg);
return -EFAULT;
}
if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
(ioc == NULL)) {
printk(KERN_DEBUG MYNAM "%s::mptctl_replace_fw() @%d - ioc%d not found!\n",
__FILE__, __LINE__, iocnum);
return -ENODEV;
}
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "mptctl_replace_fw called.\n",
ioc->name));
/* If caching FW, Free the old FW image
*/
if (ioc->cached_fw == NULL)
return 0;
mpt_free_fw_memory(ioc);
/* Allocate memory for the new FW image
*/
newFwSize = karg.newImageSize;
if (newFwSize & 0x01)
newFwSize += 1;
if (newFwSize & 0x02)
newFwSize += 2;
mpt_alloc_fw_memory(ioc, newFwSize);
if (ioc->cached_fw == NULL)
return -ENOMEM;
/* Copy the data from user memory to kernel space
*/
if (copy_from_user(ioc->cached_fw, uarg->newImage, newFwSize)) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_replace_fw - "
"Unable to read in mpt_ioctl_replace_fw image "
"@ %p\n", ioc->name, __FILE__, __LINE__, uarg);
mpt_free_fw_memory(ioc);
return -EFAULT;
}
/* Update IOCFactsReply
*/
ioc->facts.FWImageSize = newFwSize;
return 0;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/* MPT IOCTL MPTCOMMAND function.
* Cast the arg into the mpt_ioctl_mpt_command structure.
*
* Outputs: None.
* Return: 0 if successful
* -EBUSY if previous command timeout and IOC reset is not complete.
* -EFAULT if data unavailable
* -ENODEV if no such device/adapter
* -ETIME if timer expires
* -ENOMEM if memory allocation error
*/
static int
mptctl_mpt_command (unsigned long arg)
{
struct mpt_ioctl_command __user *uarg = (void __user *) arg;
struct mpt_ioctl_command karg;
MPT_ADAPTER *ioc;
int iocnum;
int rc;
if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_command))) {
printk(KERN_ERR MYNAM "%s@%d::mptctl_mpt_command - "
"Unable to read in mpt_ioctl_command struct @ %p\n",
__FILE__, __LINE__, uarg);
return -EFAULT;
}
if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
(ioc == NULL)) {
printk(KERN_DEBUG MYNAM "%s::mptctl_mpt_command() @%d - ioc%d not found!\n",
__FILE__, __LINE__, iocnum);
return -ENODEV;
}
rc = mptctl_do_mpt_command (karg, &uarg->MF);
return rc;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/* Worker routine for the IOCTL MPTCOMMAND and MPTCOMMAND32 (sparc) commands.
*
* Outputs: None.
* Return: 0 if successful
* -EBUSY if previous command timeout and IOC reset is not complete.
* -EFAULT if data unavailable
* -ENODEV if no such device/adapter
* -ETIME if timer expires
* -ENOMEM if memory allocation error
* -EPERM if SCSI I/O and target is untagged
*/
static int
mptctl_do_mpt_command (struct mpt_ioctl_command karg, void __user *mfPtr)
{
MPT_ADAPTER *ioc;
MPT_FRAME_HDR *mf = NULL;
MPIHeader_t *hdr;
char *psge;
struct buflist bufIn; /* data In buffer */
struct buflist bufOut; /* data Out buffer */
dma_addr_t dma_addr_in;
dma_addr_t dma_addr_out;
int sgSize = 0; /* Num SG elements */
int iocnum, flagsLength;
int sz, rc = 0;
int msgContext;
u16 req_idx;
ulong timeout;
unsigned long timeleft;
struct scsi_device *sdev;
unsigned long flags;
u8 function;
/* bufIn and bufOut are used for user to kernel space transfers
*/
bufIn.kptr = bufOut.kptr = NULL;
bufIn.len = bufOut.len = 0;
if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
(ioc == NULL)) {
printk(KERN_DEBUG MYNAM "%s::mptctl_do_mpt_command() @%d - ioc%d not found!\n",
__FILE__, __LINE__, iocnum);
return -ENODEV;
}
spin_lock_irqsave(&ioc->taskmgmt_lock, flags);
if (ioc->ioc_reset_in_progress) {
spin_unlock_irqrestore(&ioc->taskmgmt_lock, flags);
printk(KERN_ERR MYNAM "%s@%d::mptctl_do_mpt_command - "
"Busy with diagnostic reset\n", __FILE__, __LINE__);
return -EBUSY;
}
spin_unlock_irqrestore(&ioc->taskmgmt_lock, flags);
/* Verify that the final request frame will not be too large.
*/
sz = karg.dataSgeOffset * 4;
if (karg.dataInSize > 0)
sz += ioc->SGE_size;
if (karg.dataOutSize > 0)
sz += ioc->SGE_size;
if (sz > ioc->req_sz) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_do_mpt_command - "
"Request frame too large (%d) maximum (%d)\n",
ioc->name, __FILE__, __LINE__, sz, ioc->req_sz);
return -EFAULT;
}
/* Get a free request frame and save the message context.
*/
if ((mf = mpt_get_msg_frame(mptctl_id, ioc)) == NULL)
return -EAGAIN;
hdr = (MPIHeader_t *) mf;
msgContext = le32_to_cpu(hdr->MsgContext);
req_idx = le16_to_cpu(mf->u.frame.hwhdr.msgctxu.fld.req_idx);
/* Copy the request frame
* Reset the saved message context.
* Request frame in user space
*/
if (copy_from_user(mf, mfPtr, karg.dataSgeOffset * 4)) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_do_mpt_command - "
"Unable to read MF from mpt_ioctl_command struct @ %p\n",
ioc->name, __FILE__, __LINE__, mfPtr);
function = -1;
rc = -EFAULT;
goto done_free_mem;
}
hdr->MsgContext = cpu_to_le32(msgContext);
function = hdr->Function;
/* Verify that this request is allowed.
*/
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "sending mpi function (0x%02X), req=%p\n",
ioc->name, hdr->Function, mf));
switch (function) {
case MPI_FUNCTION_IOC_FACTS:
case MPI_FUNCTION_PORT_FACTS:
karg.dataOutSize = karg.dataInSize = 0;
break;
case MPI_FUNCTION_CONFIG:
{
Config_t *config_frame;
config_frame = (Config_t *)mf;
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "\ttype=0x%02x ext_type=0x%02x "
"number=0x%02x action=0x%02x\n", ioc->name,
config_frame->Header.PageType,
config_frame->ExtPageType,
config_frame->Header.PageNumber,
config_frame->Action));
break;
}
case MPI_FUNCTION_FC_COMMON_TRANSPORT_SEND:
case MPI_FUNCTION_FC_EX_LINK_SRVC_SEND:
case MPI_FUNCTION_FW_UPLOAD:
case MPI_FUNCTION_SCSI_ENCLOSURE_PROCESSOR:
case MPI_FUNCTION_FW_DOWNLOAD:
case MPI_FUNCTION_FC_PRIMITIVE_SEND:
case MPI_FUNCTION_TOOLBOX:
case MPI_FUNCTION_SAS_IO_UNIT_CONTROL:
break;
case MPI_FUNCTION_SCSI_IO_REQUEST:
if (ioc->sh) {
SCSIIORequest_t *pScsiReq = (SCSIIORequest_t *) mf;
int qtag = MPI_SCSIIO_CONTROL_UNTAGGED;
int scsidir = 0;
int dataSize;
u32 id;
id = (ioc->devices_per_bus == 0) ? 256 : ioc->devices_per_bus;
if (pScsiReq->TargetID > id) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_do_mpt_command - "
"Target ID out of bounds. \n",
ioc->name, __FILE__, __LINE__);
rc = -ENODEV;
goto done_free_mem;
}
if (pScsiReq->Bus >= ioc->number_of_buses) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_do_mpt_command - "
"Target Bus out of bounds. \n",
ioc->name, __FILE__, __LINE__);
rc = -ENODEV;
goto done_free_mem;
}
pScsiReq->MsgFlags &= ~MPI_SCSIIO_MSGFLGS_SENSE_WIDTH;
pScsiReq->MsgFlags |= mpt_msg_flags(ioc);
/* verify that app has not requested
* more sense data than driver
* can provide, if so, reset this parameter
* set the sense buffer pointer low address
* update the control field to specify Q type
*/
if (karg.maxSenseBytes > MPT_SENSE_BUFFER_SIZE)
pScsiReq->SenseBufferLength = MPT_SENSE_BUFFER_SIZE;
else
pScsiReq->SenseBufferLength = karg.maxSenseBytes;
pScsiReq->SenseBufferLowAddr =
cpu_to_le32(ioc->sense_buf_low_dma
+ (req_idx * MPT_SENSE_BUFFER_ALLOC));
shost_for_each_device(sdev, ioc->sh) {
struct scsi_target *starget = scsi_target(sdev);
VirtTarget *vtarget = starget->hostdata;
if ((pScsiReq->TargetID == vtarget->id) &&
(pScsiReq->Bus == vtarget->channel) &&
(vtarget->tflags & MPT_TARGET_FLAGS_Q_YES))
qtag = MPI_SCSIIO_CONTROL_SIMPLEQ;
}
/* Have the IOCTL driver set the direction based
* on the dataOutSize (ordering issue with Sparc).
*/
if (karg.dataOutSize > 0) {
scsidir = MPI_SCSIIO_CONTROL_WRITE;
dataSize = karg.dataOutSize;
} else {
scsidir = MPI_SCSIIO_CONTROL_READ;
dataSize = karg.dataInSize;
}
pScsiReq->Control = cpu_to_le32(scsidir | qtag);
pScsiReq->DataLength = cpu_to_le32(dataSize);
} else {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_do_mpt_command - "
"SCSI driver is not loaded. \n",
ioc->name, __FILE__, __LINE__);
rc = -EFAULT;
goto done_free_mem;
}
break;
case MPI_FUNCTION_SMP_PASSTHROUGH:
/* Check mf->PassthruFlags to determine if
* transfer is ImmediateMode or not.
* Immediate mode returns data in the ReplyFrame.
* Else, we are sending request and response data
* in two SGLs at the end of the mf.
*/
break;
case MPI_FUNCTION_SATA_PASSTHROUGH:
if (!ioc->sh) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_do_mpt_command - "
"SCSI driver is not loaded. \n",
ioc->name, __FILE__, __LINE__);
rc = -EFAULT;
goto done_free_mem;
}
break;
case MPI_FUNCTION_RAID_ACTION:
/* Just add a SGE
*/
break;
case MPI_FUNCTION_RAID_SCSI_IO_PASSTHROUGH:
if (ioc->sh) {
SCSIIORequest_t *pScsiReq = (SCSIIORequest_t *) mf;
int qtag = MPI_SCSIIO_CONTROL_SIMPLEQ;
int scsidir = MPI_SCSIIO_CONTROL_READ;
int dataSize;
pScsiReq->MsgFlags &= ~MPI_SCSIIO_MSGFLGS_SENSE_WIDTH;
pScsiReq->MsgFlags |= mpt_msg_flags(ioc);
/* verify that app has not requested
* more sense data than driver
* can provide, if so, reset this parameter
* set the sense buffer pointer low address
* update the control field to specify Q type
*/
if (karg.maxSenseBytes > MPT_SENSE_BUFFER_SIZE)
pScsiReq->SenseBufferLength = MPT_SENSE_BUFFER_SIZE;
else
pScsiReq->SenseBufferLength = karg.maxSenseBytes;
pScsiReq->SenseBufferLowAddr =
cpu_to_le32(ioc->sense_buf_low_dma
+ (req_idx * MPT_SENSE_BUFFER_ALLOC));
/* All commands to physical devices are tagged
*/
/* Have the IOCTL driver set the direction based
* on the dataOutSize (ordering issue with Sparc).
*/
if (karg.dataOutSize > 0) {
scsidir = MPI_SCSIIO_CONTROL_WRITE;
dataSize = karg.dataOutSize;
} else {
scsidir = MPI_SCSIIO_CONTROL_READ;
dataSize = karg.dataInSize;
}
pScsiReq->Control = cpu_to_le32(scsidir | qtag);
pScsiReq->DataLength = cpu_to_le32(dataSize);
} else {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_do_mpt_command - "
"SCSI driver is not loaded. \n",
ioc->name, __FILE__, __LINE__);
rc = -EFAULT;
goto done_free_mem;
}
break;
case MPI_FUNCTION_SCSI_TASK_MGMT:
{
SCSITaskMgmt_t *pScsiTm;
pScsiTm = (SCSITaskMgmt_t *)mf;
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"\tTaskType=0x%x MsgFlags=0x%x "
"TaskMsgContext=0x%x id=%d channel=%d\n",
ioc->name, pScsiTm->TaskType, le32_to_cpu
(pScsiTm->TaskMsgContext), pScsiTm->MsgFlags,
pScsiTm->TargetID, pScsiTm->Bus));
break;
}
case MPI_FUNCTION_IOC_INIT:
{
IOCInit_t *pInit = (IOCInit_t *) mf;
u32 high_addr, sense_high;
/* Verify that all entries in the IOC INIT match
* existing setup (and in LE format).
*/
if (sizeof(dma_addr_t) == sizeof(u64)) {
high_addr = cpu_to_le32((u32)((u64)ioc->req_frames_dma >> 32));
sense_high= cpu_to_le32((u32)((u64)ioc->sense_buf_pool_dma >> 32));
} else {
high_addr = 0;
sense_high= 0;
}
if ((pInit->Flags != 0) || (pInit->MaxDevices != ioc->facts.MaxDevices) ||
(pInit->MaxBuses != ioc->facts.MaxBuses) ||
(pInit->ReplyFrameSize != cpu_to_le16(ioc->reply_sz)) ||
(pInit->HostMfaHighAddr != high_addr) ||
(pInit->SenseBufferHighAddr != sense_high)) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_do_mpt_command - "
"IOC_INIT issued with 1 or more incorrect parameters. Rejected.\n",
ioc->name, __FILE__, __LINE__);
rc = -EFAULT;
goto done_free_mem;
}
}
break;
default:
/*
* MPI_FUNCTION_PORT_ENABLE
* MPI_FUNCTION_TARGET_CMD_BUFFER_POST
* MPI_FUNCTION_TARGET_ASSIST
* MPI_FUNCTION_TARGET_STATUS_SEND
* MPI_FUNCTION_TARGET_MODE_ABORT
* MPI_FUNCTION_IOC_MESSAGE_UNIT_RESET
* MPI_FUNCTION_IO_UNIT_RESET
* MPI_FUNCTION_HANDSHAKE
* MPI_FUNCTION_REPLY_FRAME_REMOVAL
* MPI_FUNCTION_EVENT_NOTIFICATION
* (driver handles event notification)
* MPI_FUNCTION_EVENT_ACK
*/
/* What to do with these??? CHECK ME!!!
MPI_FUNCTION_FC_LINK_SRVC_BUF_POST
MPI_FUNCTION_FC_LINK_SRVC_RSP
MPI_FUNCTION_FC_ABORT
MPI_FUNCTION_LAN_SEND
MPI_FUNCTION_LAN_RECEIVE
MPI_FUNCTION_LAN_RESET
*/
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_do_mpt_command - "
"Illegal request (function 0x%x) \n",
ioc->name, __FILE__, __LINE__, hdr->Function);
rc = -EFAULT;
goto done_free_mem;
}
/* Add the SGL ( at most one data in SGE and one data out SGE )
* In the case of two SGE's - the data out (write) will always
* preceede the data in (read) SGE. psgList is used to free the
* allocated memory.
*/
psge = (char *) (((int *) mf) + karg.dataSgeOffset);
flagsLength = 0;
if (karg.dataOutSize > 0)
sgSize ++;
if (karg.dataInSize > 0)
sgSize ++;
if (sgSize > 0) {
/* Set up the dataOut memory allocation */
if (karg.dataOutSize > 0) {
if (karg.dataInSize > 0) {
flagsLength = ( MPI_SGE_FLAGS_SIMPLE_ELEMENT |
MPI_SGE_FLAGS_END_OF_BUFFER |
MPI_SGE_FLAGS_DIRECTION)
<< MPI_SGE_FLAGS_SHIFT;
} else {
flagsLength = MPT_SGE_FLAGS_SSIMPLE_WRITE;
}
flagsLength |= karg.dataOutSize;
bufOut.len = karg.dataOutSize;
bufOut.kptr = pci_alloc_consistent(
ioc->pcidev, bufOut.len, &dma_addr_out);
if (bufOut.kptr == NULL) {
rc = -ENOMEM;
goto done_free_mem;
} else {
/* Set up this SGE.
* Copy to MF and to sglbuf
*/
ioc->add_sge(psge, flagsLength, dma_addr_out);
psge += ioc->SGE_size;
/* Copy user data to kernel space.
*/
if (copy_from_user(bufOut.kptr,
karg.dataOutBufPtr,
bufOut.len)) {
printk(MYIOC_s_ERR_FMT
"%s@%d::mptctl_do_mpt_command - Unable "
"to read user data "
"struct @ %p\n",
ioc->name, __FILE__, __LINE__,karg.dataOutBufPtr);
rc = -EFAULT;
goto done_free_mem;
}
}
}
if (karg.dataInSize > 0) {
flagsLength = MPT_SGE_FLAGS_SSIMPLE_READ;
flagsLength |= karg.dataInSize;
bufIn.len = karg.dataInSize;
bufIn.kptr = pci_alloc_consistent(ioc->pcidev,
bufIn.len, &dma_addr_in);
if (bufIn.kptr == NULL) {
rc = -ENOMEM;
goto done_free_mem;
} else {
/* Set up this SGE
* Copy to MF and to sglbuf
*/
ioc->add_sge(psge, flagsLength, dma_addr_in);
}
}
} else {
/* Add a NULL SGE
*/
ioc->add_sge(psge, flagsLength, (dma_addr_t) -1);
}
SET_MGMT_MSG_CONTEXT(ioc->ioctl_cmds.msg_context, hdr->MsgContext);
INITIALIZE_MGMT_STATUS(ioc->ioctl_cmds.status)
if (hdr->Function == MPI_FUNCTION_SCSI_TASK_MGMT) {
mutex_lock(&ioc->taskmgmt_cmds.mutex);
if (mpt_set_taskmgmt_in_progress_flag(ioc) != 0) {
mutex_unlock(&ioc->taskmgmt_cmds.mutex);
goto done_free_mem;
}
DBG_DUMP_TM_REQUEST_FRAME(ioc, (u32 *)mf);
if ((ioc->facts.IOCCapabilities & MPI_IOCFACTS_CAPABILITY_HIGH_PRI_Q) &&
(ioc->facts.MsgVersion >= MPI_VERSION_01_05))
mpt_put_msg_frame_hi_pri(mptctl_id, ioc, mf);
else {
rc =mpt_send_handshake_request(mptctl_id, ioc,
sizeof(SCSITaskMgmt_t), (u32*)mf, CAN_SLEEP);
if (rc != 0) {
dfailprintk(ioc, printk(MYIOC_s_ERR_FMT
"send_handshake FAILED! (ioc %p, mf %p)\n",
ioc->name, ioc, mf));
mpt_clear_taskmgmt_in_progress_flag(ioc);
rc = -ENODATA;
mutex_unlock(&ioc->taskmgmt_cmds.mutex);
goto done_free_mem;
}
}
} else
mpt_put_msg_frame(mptctl_id, ioc, mf);
/* Now wait for the command to complete */
timeout = (karg.timeout > 0) ? karg.timeout : MPT_IOCTL_DEFAULT_TIMEOUT;
retry_wait:
timeleft = wait_for_completion_timeout(&ioc->ioctl_cmds.done,
HZ*timeout);
if (!(ioc->ioctl_cmds.status & MPT_MGMT_STATUS_COMMAND_GOOD)) {
rc = -ETIME;
dfailprintk(ioc, printk(MYIOC_s_ERR_FMT "%s: TIMED OUT!\n",
ioc->name, __func__));
if (ioc->ioctl_cmds.status & MPT_MGMT_STATUS_DID_IOCRESET) {
if (function == MPI_FUNCTION_SCSI_TASK_MGMT)
mutex_unlock(&ioc->taskmgmt_cmds.mutex);
goto done_free_mem;
}
if (!timeleft) {
if (function == MPI_FUNCTION_SCSI_TASK_MGMT)
mutex_unlock(&ioc->taskmgmt_cmds.mutex);
mptctl_timeout_expired(ioc, mf);
mf = NULL;
} else
goto retry_wait;
goto done_free_mem;
}
if (function == MPI_FUNCTION_SCSI_TASK_MGMT)
mutex_unlock(&ioc->taskmgmt_cmds.mutex);
mf = NULL;
/* If a valid reply frame, copy to the user.
* Offset 2: reply length in U32's
*/
if (ioc->ioctl_cmds.status & MPT_MGMT_STATUS_RF_VALID) {
if (karg.maxReplyBytes < ioc->reply_sz) {
sz = min(karg.maxReplyBytes,
4*ioc->ioctl_cmds.reply[2]);
} else {
sz = min(ioc->reply_sz, 4*ioc->ioctl_cmds.reply[2]);
}
if (sz > 0) {
if (copy_to_user(karg.replyFrameBufPtr,
ioc->ioctl_cmds.reply, sz)){
printk(MYIOC_s_ERR_FMT
"%s@%d::mptctl_do_mpt_command - "
"Unable to write out reply frame %p\n",
ioc->name, __FILE__, __LINE__, karg.replyFrameBufPtr);
rc = -ENODATA;
goto done_free_mem;
}
}
}
/* If valid sense data, copy to user.
*/
if (ioc->ioctl_cmds.status & MPT_MGMT_STATUS_SENSE_VALID) {
sz = min(karg.maxSenseBytes, MPT_SENSE_BUFFER_SIZE);
if (sz > 0) {
if (copy_to_user(karg.senseDataPtr,
ioc->ioctl_cmds.sense, sz)) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_do_mpt_command - "
"Unable to write sense data to user %p\n",
ioc->name, __FILE__, __LINE__,
karg.senseDataPtr);
rc = -ENODATA;
goto done_free_mem;
}
}
}
/* If the overall status is _GOOD and data in, copy data
* to user.
*/
if ((ioc->ioctl_cmds.status & MPT_MGMT_STATUS_COMMAND_GOOD) &&
(karg.dataInSize > 0) && (bufIn.kptr)) {
if (copy_to_user(karg.dataInBufPtr,
bufIn.kptr, karg.dataInSize)) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_do_mpt_command - "
"Unable to write data to user %p\n",
ioc->name, __FILE__, __LINE__,
karg.dataInBufPtr);
rc = -ENODATA;
}
}
done_free_mem:
CLEAR_MGMT_STATUS(ioc->ioctl_cmds.status)
SET_MGMT_MSG_CONTEXT(ioc->ioctl_cmds.msg_context, 0);
/* Free the allocated memory.
*/
if (bufOut.kptr != NULL) {
pci_free_consistent(ioc->pcidev,
bufOut.len, (void *) bufOut.kptr, dma_addr_out);
}
if (bufIn.kptr != NULL) {
pci_free_consistent(ioc->pcidev,
bufIn.len, (void *) bufIn.kptr, dma_addr_in);
}
/* mf is null if command issued successfully
* otherwise, failure occured after mf acquired.
*/
if (mf)
mpt_free_msg_frame(ioc, mf);
return rc;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/* Prototype Routine for the HOST INFO command.
*
* Outputs: None.
* Return: 0 if successful
* -EFAULT if data unavailable
* -EBUSY if previous command timeout and IOC reset is not complete.
* -ENODEV if no such device/adapter
* -ETIME if timer expires
* -ENOMEM if memory allocation error
*/
static int
mptctl_hp_hostinfo(unsigned long arg, unsigned int data_size)
{
hp_host_info_t __user *uarg = (void __user *) arg;
MPT_ADAPTER *ioc;
struct pci_dev *pdev;
char *pbuf=NULL;
dma_addr_t buf_dma;
hp_host_info_t karg;
CONFIGPARMS cfg;
ConfigPageHeader_t hdr;
int iocnum;
int rc, cim_rev;
ToolboxIstwiReadWriteRequest_t *IstwiRWRequest;
MPT_FRAME_HDR *mf = NULL;
MPIHeader_t *mpi_hdr;
unsigned long timeleft;
int retval;
/* Reset long to int. Should affect IA64 and SPARC only
*/
if (data_size == sizeof(hp_host_info_t))
cim_rev = 1;
else if (data_size == sizeof(hp_host_info_rev0_t))
cim_rev = 0; /* obsolete */
else
return -EFAULT;
if (copy_from_user(&karg, uarg, sizeof(hp_host_info_t))) {
printk(KERN_ERR MYNAM "%s@%d::mptctl_hp_host_info - "
"Unable to read in hp_host_info struct @ %p\n",
__FILE__, __LINE__, uarg);
return -EFAULT;
}
if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
(ioc == NULL)) {
printk(KERN_DEBUG MYNAM "%s::mptctl_hp_hostinfo() @%d - ioc%d not found!\n",
__FILE__, __LINE__, iocnum);
return -ENODEV;
}
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT ": mptctl_hp_hostinfo called.\n",
ioc->name));
/* Fill in the data and return the structure to the calling
* program
*/
pdev = (struct pci_dev *) ioc->pcidev;
karg.vendor = pdev->vendor;
karg.device = pdev->device;
karg.subsystem_id = pdev->subsystem_device;
karg.subsystem_vendor = pdev->subsystem_vendor;
karg.devfn = pdev->devfn;
karg.bus = pdev->bus->number;
/* Save the SCSI host no. if
* SCSI driver loaded
*/
if (ioc->sh != NULL)
karg.host_no = ioc->sh->host_no;
else
karg.host_no = -1;
/* Reformat the fw_version into a string
*/
karg.fw_version[0] = ioc->facts.FWVersion.Struct.Major >= 10 ?
((ioc->facts.FWVersion.Struct.Major / 10) + '0') : '0';
karg.fw_version[1] = (ioc->facts.FWVersion.Struct.Major % 10 ) + '0';
karg.fw_version[2] = '.';
karg.fw_version[3] = ioc->facts.FWVersion.Struct.Minor >= 10 ?
((ioc->facts.FWVersion.Struct.Minor / 10) + '0') : '0';
karg.fw_version[4] = (ioc->facts.FWVersion.Struct.Minor % 10 ) + '0';
karg.fw_version[5] = '.';
karg.fw_version[6] = ioc->facts.FWVersion.Struct.Unit >= 10 ?
((ioc->facts.FWVersion.Struct.Unit / 10) + '0') : '0';
karg.fw_version[7] = (ioc->facts.FWVersion.Struct.Unit % 10 ) + '0';
karg.fw_version[8] = '.';
karg.fw_version[9] = ioc->facts.FWVersion.Struct.Dev >= 10 ?
((ioc->facts.FWVersion.Struct.Dev / 10) + '0') : '0';
karg.fw_version[10] = (ioc->facts.FWVersion.Struct.Dev % 10 ) + '0';
karg.fw_version[11] = '\0';
/* Issue a config request to get the device serial number
*/
hdr.PageVersion = 0;
hdr.PageLength = 0;
hdr.PageNumber = 0;
hdr.PageType = MPI_CONFIG_PAGETYPE_MANUFACTURING;
cfg.cfghdr.hdr = &hdr;
cfg.physAddr = -1;
cfg.pageAddr = 0;
cfg.action = MPI_CONFIG_ACTION_PAGE_HEADER;
cfg.dir = 0; /* read */
cfg.timeout = 10;
strncpy(karg.serial_number, " ", 24);
if (mpt_config(ioc, &cfg) == 0) {
if (cfg.cfghdr.hdr->PageLength > 0) {
/* Issue the second config page request */
cfg.action = MPI_CONFIG_ACTION_PAGE_READ_CURRENT;
pbuf = pci_alloc_consistent(ioc->pcidev, hdr.PageLength * 4, &buf_dma);
if (pbuf) {
cfg.physAddr = buf_dma;
if (mpt_config(ioc, &cfg) == 0) {
ManufacturingPage0_t *pdata = (ManufacturingPage0_t *) pbuf;
if (strlen(pdata->BoardTracerNumber) > 1) {
strncpy(karg.serial_number, pdata->BoardTracerNumber, 24);
karg.serial_number[24-1]='\0';
}
}
pci_free_consistent(ioc->pcidev, hdr.PageLength * 4, pbuf, buf_dma);
pbuf = NULL;
}
}
}
rc = mpt_GetIocState(ioc, 1);
switch (rc) {
case MPI_IOC_STATE_OPERATIONAL:
karg.ioc_status = HP_STATUS_OK;
break;
case MPI_IOC_STATE_FAULT:
karg.ioc_status = HP_STATUS_FAILED;
break;
case MPI_IOC_STATE_RESET:
case MPI_IOC_STATE_READY:
default:
karg.ioc_status = HP_STATUS_OTHER;
break;
}
karg.base_io_addr = pci_resource_start(pdev, 0);
if ((ioc->bus_type == SAS) || (ioc->bus_type == FC))
karg.bus_phys_width = HP_BUS_WIDTH_UNK;
else
karg.bus_phys_width = HP_BUS_WIDTH_16;
karg.hard_resets = 0;
karg.soft_resets = 0;
karg.timeouts = 0;
if (ioc->sh != NULL) {
MPT_SCSI_HOST *hd = shost_priv(ioc->sh);
if (hd && (cim_rev == 1)) {
karg.hard_resets = ioc->hard_resets;
karg.soft_resets = ioc->soft_resets;
karg.timeouts = ioc->timeouts;
}
}
/*
* Gather ISTWI(Industry Standard Two Wire Interface) Data
*/
if ((mf = mpt_get_msg_frame(mptctl_id, ioc)) == NULL) {
dfailprintk(ioc, printk(MYIOC_s_WARN_FMT
"%s, no msg frames!!\n", ioc->name, __func__));
goto out;
}
IstwiRWRequest = (ToolboxIstwiReadWriteRequest_t *)mf;
mpi_hdr = (MPIHeader_t *) mf;
memset(IstwiRWRequest,0,sizeof(ToolboxIstwiReadWriteRequest_t));
IstwiRWRequest->Function = MPI_FUNCTION_TOOLBOX;
IstwiRWRequest->Tool = MPI_TOOLBOX_ISTWI_READ_WRITE_TOOL;
IstwiRWRequest->MsgContext = mpi_hdr->MsgContext;
IstwiRWRequest->Flags = MPI_TB_ISTWI_FLAGS_READ;
IstwiRWRequest->NumAddressBytes = 0x01;
IstwiRWRequest->DataLength = cpu_to_le16(0x04);
if (pdev->devfn & 1)
IstwiRWRequest->DeviceAddr = 0xB2;
else
IstwiRWRequest->DeviceAddr = 0xB0;
pbuf = pci_alloc_consistent(ioc->pcidev, 4, &buf_dma);
if (!pbuf)
goto out;
ioc->add_sge((char *)&IstwiRWRequest->SGL,
(MPT_SGE_FLAGS_SSIMPLE_READ|4), buf_dma);
retval = 0;
SET_MGMT_MSG_CONTEXT(ioc->ioctl_cmds.msg_context,
IstwiRWRequest->MsgContext);
INITIALIZE_MGMT_STATUS(ioc->ioctl_cmds.status)
mpt_put_msg_frame(mptctl_id, ioc, mf);
retry_wait:
timeleft = wait_for_completion_timeout(&ioc->ioctl_cmds.done,
HZ*MPT_IOCTL_DEFAULT_TIMEOUT);
if (!(ioc->ioctl_cmds.status & MPT_MGMT_STATUS_COMMAND_GOOD)) {
retval = -ETIME;
printk(MYIOC_s_WARN_FMT "%s: failed\n", ioc->name, __func__);
if (ioc->ioctl_cmds.status & MPT_MGMT_STATUS_DID_IOCRESET) {
mpt_free_msg_frame(ioc, mf);
goto out;
}
if (!timeleft)
mptctl_timeout_expired(ioc, mf);
else
goto retry_wait;
goto out;
}
/*
*ISTWI Data Definition
* pbuf[0] = FW_VERSION = 0x4
* pbuf[1] = Bay Count = 6 or 4 or 2, depending on
* the config, you should be seeing one out of these three values
* pbuf[2] = Drive Installed Map = bit pattern depend on which
* bays have drives in them
* pbuf[3] = Checksum (0x100 = (byte0 + byte2 + byte3)
*/
if (ioc->ioctl_cmds.status & MPT_MGMT_STATUS_RF_VALID)
karg.rsvd = *(u32 *)pbuf;
out:
CLEAR_MGMT_STATUS(ioc->ioctl_cmds.status)
SET_MGMT_MSG_CONTEXT(ioc->ioctl_cmds.msg_context, 0);
if (pbuf)
pci_free_consistent(ioc->pcidev, 4, pbuf, buf_dma);
/* Copy the data from kernel memory to user memory
*/
if (copy_to_user((char __user *)arg, &karg, sizeof(hp_host_info_t))) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_hpgethostinfo - "
"Unable to write out hp_host_info @ %p\n",
ioc->name, __FILE__, __LINE__, uarg);
return -EFAULT;
}
return 0;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/* Prototype Routine for the TARGET INFO command.
*
* Outputs: None.
* Return: 0 if successful
* -EFAULT if data unavailable
* -EBUSY if previous command timeout and IOC reset is not complete.
* -ENODEV if no such device/adapter
* -ETIME if timer expires
* -ENOMEM if memory allocation error
*/
static int
mptctl_hp_targetinfo(unsigned long arg)
{
hp_target_info_t __user *uarg = (void __user *) arg;
SCSIDevicePage0_t *pg0_alloc;
SCSIDevicePage3_t *pg3_alloc;
MPT_ADAPTER *ioc;
MPT_SCSI_HOST *hd = NULL;
hp_target_info_t karg;
int iocnum;
int data_sz;
dma_addr_t page_dma;
CONFIGPARMS cfg;
ConfigPageHeader_t hdr;
int tmp, np, rc = 0;
if (copy_from_user(&karg, uarg, sizeof(hp_target_info_t))) {
printk(KERN_ERR MYNAM "%s@%d::mptctl_hp_targetinfo - "
"Unable to read in hp_host_targetinfo struct @ %p\n",
__FILE__, __LINE__, uarg);
return -EFAULT;
}
if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
(ioc == NULL)) {
printk(KERN_DEBUG MYNAM "%s::mptctl_hp_targetinfo() @%d - ioc%d not found!\n",
__FILE__, __LINE__, iocnum);
return -ENODEV;
}
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "mptctl_hp_targetinfo called.\n",
ioc->name));
/* There is nothing to do for FCP parts.
*/
if ((ioc->bus_type == SAS) || (ioc->bus_type == FC))
return 0;
if ((ioc->spi_data.sdp0length == 0) || (ioc->sh == NULL))
return 0;
if (ioc->sh->host_no != karg.hdr.host)
return -ENODEV;
/* Get the data transfer speeds
*/
data_sz = ioc->spi_data.sdp0length * 4;
pg0_alloc = (SCSIDevicePage0_t *) pci_alloc_consistent(ioc->pcidev, data_sz, &page_dma);
if (pg0_alloc) {
hdr.PageVersion = ioc->spi_data.sdp0version;
hdr.PageLength = data_sz;
hdr.PageNumber = 0;
hdr.PageType = MPI_CONFIG_PAGETYPE_SCSI_DEVICE;
cfg.cfghdr.hdr = &hdr;
cfg.action = MPI_CONFIG_ACTION_PAGE_READ_CURRENT;
cfg.dir = 0;
cfg.timeout = 0;
cfg.physAddr = page_dma;
cfg.pageAddr = (karg.hdr.channel << 8) | karg.hdr.id;
if ((rc = mpt_config(ioc, &cfg)) == 0) {
np = le32_to_cpu(pg0_alloc->NegotiatedParameters);
karg.negotiated_width = np & MPI_SCSIDEVPAGE0_NP_WIDE ?
HP_BUS_WIDTH_16 : HP_BUS_WIDTH_8;
if (np & MPI_SCSIDEVPAGE0_NP_NEG_SYNC_OFFSET_MASK) {
tmp = (np & MPI_SCSIDEVPAGE0_NP_NEG_SYNC_PERIOD_MASK) >> 8;
if (tmp < 0x09)
karg.negotiated_speed = HP_DEV_SPEED_ULTRA320;
else if (tmp <= 0x09)
karg.negotiated_speed = HP_DEV_SPEED_ULTRA160;
else if (tmp <= 0x0A)
karg.negotiated_speed = HP_DEV_SPEED_ULTRA2;
else if (tmp <= 0x0C)
karg.negotiated_speed = HP_DEV_SPEED_ULTRA;
else if (tmp <= 0x25)
karg.negotiated_speed = HP_DEV_SPEED_FAST;
else
karg.negotiated_speed = HP_DEV_SPEED_ASYNC;
} else
karg.negotiated_speed = HP_DEV_SPEED_ASYNC;
}
pci_free_consistent(ioc->pcidev, data_sz, (u8 *) pg0_alloc, page_dma);
}
/* Set defaults
*/
karg.message_rejects = -1;
karg.phase_errors = -1;
karg.parity_errors = -1;
karg.select_timeouts = -1;
/* Get the target error parameters
*/
hdr.PageVersion = 0;
hdr.PageLength = 0;
hdr.PageNumber = 3;
hdr.PageType = MPI_CONFIG_PAGETYPE_SCSI_DEVICE;
cfg.cfghdr.hdr = &hdr;
cfg.action = MPI_CONFIG_ACTION_PAGE_HEADER;
cfg.dir = 0;
cfg.timeout = 0;
cfg.physAddr = -1;
if ((mpt_config(ioc, &cfg) == 0) && (cfg.cfghdr.hdr->PageLength > 0)) {
/* Issue the second config page request */
cfg.action = MPI_CONFIG_ACTION_PAGE_READ_CURRENT;
data_sz = (int) cfg.cfghdr.hdr->PageLength * 4;
pg3_alloc = (SCSIDevicePage3_t *) pci_alloc_consistent(
ioc->pcidev, data_sz, &page_dma);
if (pg3_alloc) {
cfg.physAddr = page_dma;
cfg.pageAddr = (karg.hdr.channel << 8) | karg.hdr.id;
if ((rc = mpt_config(ioc, &cfg)) == 0) {
karg.message_rejects = (u32) le16_to_cpu(pg3_alloc->MsgRejectCount);
karg.phase_errors = (u32) le16_to_cpu(pg3_alloc->PhaseErrorCount);
karg.parity_errors = (u32) le16_to_cpu(pg3_alloc->ParityErrorCount);
}
pci_free_consistent(ioc->pcidev, data_sz, (u8 *) pg3_alloc, page_dma);
}
}
hd = shost_priv(ioc->sh);
if (hd != NULL)
karg.select_timeouts = hd->sel_timeout[karg.hdr.id];
/* Copy the data from kernel memory to user memory
*/
if (copy_to_user((char __user *)arg, &karg, sizeof(hp_target_info_t))) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_hp_target_info - "
"Unable to write out mpt_ioctl_targetinfo struct @ %p\n",
ioc->name, __FILE__, __LINE__, uarg);
return -EFAULT;
}
return 0;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
static const struct file_operations mptctl_fops = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.fasync = mptctl_fasync,
.unlocked_ioctl = mptctl_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = compat_mpctl_ioctl,
#endif
};
static struct miscdevice mptctl_miscdev = {
MPT_MINOR,
MYNAM,
&mptctl_fops
};
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
#ifdef CONFIG_COMPAT
static int
compat_mptfwxfer_ioctl(struct file *filp, unsigned int cmd,
unsigned long arg)
{
struct mpt_fw_xfer32 kfw32;
struct mpt_fw_xfer kfw;
MPT_ADAPTER *iocp = NULL;
int iocnum, iocnumX;
int nonblock = (filp->f_flags & O_NONBLOCK);
int ret;
if (copy_from_user(&kfw32, (char __user *)arg, sizeof(kfw32)))
return -EFAULT;
/* Verify intended MPT adapter */
iocnumX = kfw32.iocnum & 0xFF;
if (((iocnum = mpt_verify_adapter(iocnumX, &iocp)) < 0) ||
(iocp == NULL)) {
printk(KERN_DEBUG MYNAM "::compat_mptfwxfer_ioctl @%d - ioc%d not found!\n",
__LINE__, iocnumX);
return -ENODEV;
}
if ((ret = mptctl_syscall_down(iocp, nonblock)) != 0)
return ret;
dctlprintk(iocp, printk(MYIOC_s_DEBUG_FMT "compat_mptfwxfer_ioctl() called\n",
iocp->name));
kfw.iocnum = iocnum;
kfw.fwlen = kfw32.fwlen;
kfw.bufp = compat_ptr(kfw32.bufp);
ret = mptctl_do_fw_download(kfw.iocnum, kfw.bufp, kfw.fwlen);
mutex_unlock(&iocp->ioctl_cmds.mutex);
return ret;
}
static int
compat_mpt_command(struct file *filp, unsigned int cmd,
unsigned long arg)
{
struct mpt_ioctl_command32 karg32;
struct mpt_ioctl_command32 __user *uarg = (struct mpt_ioctl_command32 __user *) arg;
struct mpt_ioctl_command karg;
MPT_ADAPTER *iocp = NULL;
int iocnum, iocnumX;
int nonblock = (filp->f_flags & O_NONBLOCK);
int ret;
if (copy_from_user(&karg32, (char __user *)arg, sizeof(karg32)))
return -EFAULT;
/* Verify intended MPT adapter */
iocnumX = karg32.hdr.iocnum & 0xFF;
if (((iocnum = mpt_verify_adapter(iocnumX, &iocp)) < 0) ||
(iocp == NULL)) {
printk(KERN_DEBUG MYNAM "::compat_mpt_command @%d - ioc%d not found!\n",
__LINE__, iocnumX);
return -ENODEV;
}
if ((ret = mptctl_syscall_down(iocp, nonblock)) != 0)
return ret;
dctlprintk(iocp, printk(MYIOC_s_DEBUG_FMT "compat_mpt_command() called\n",
iocp->name));
/* Copy data to karg */
karg.hdr.iocnum = karg32.hdr.iocnum;
karg.hdr.port = karg32.hdr.port;
karg.timeout = karg32.timeout;
karg.maxReplyBytes = karg32.maxReplyBytes;
karg.dataInSize = karg32.dataInSize;
karg.dataOutSize = karg32.dataOutSize;
karg.maxSenseBytes = karg32.maxSenseBytes;
karg.dataSgeOffset = karg32.dataSgeOffset;
karg.replyFrameBufPtr = (char __user *)(unsigned long)karg32.replyFrameBufPtr;
karg.dataInBufPtr = (char __user *)(unsigned long)karg32.dataInBufPtr;
karg.dataOutBufPtr = (char __user *)(unsigned long)karg32.dataOutBufPtr;
karg.senseDataPtr = (char __user *)(unsigned long)karg32.senseDataPtr;
/* Pass new structure to do_mpt_command
*/
ret = mptctl_do_mpt_command (karg, &uarg->MF);
mutex_unlock(&iocp->ioctl_cmds.mutex);
return ret;
}
static long compat_mpctl_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
{
long ret;
lock_kernel();
switch (cmd) {
case MPTIOCINFO:
case MPTIOCINFO1:
case MPTIOCINFO2:
case MPTTARGETINFO:
case MPTEVENTQUERY:
case MPTEVENTENABLE:
case MPTEVENTREPORT:
case MPTHARDRESET:
case HP_GETHOSTINFO:
case HP_GETTARGETINFO:
case MPTTEST:
ret = __mptctl_ioctl(f, cmd, arg);
break;
case MPTCOMMAND32:
ret = compat_mpt_command(f, cmd, arg);
break;
case MPTFWDOWNLOAD32:
ret = compat_mptfwxfer_ioctl(f, cmd, arg);
break;
default:
ret = -ENOIOCTLCMD;
break;
}
unlock_kernel();
return ret;
}
#endif
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*
* mptctl_probe - Installs ioctl devices per bus.
* @pdev: Pointer to pci_dev structure
*
* Returns 0 for success, non-zero for failure.
*
*/
static int
mptctl_probe(struct pci_dev *pdev, const struct pci_device_id *id)
{
MPT_ADAPTER *ioc = pci_get_drvdata(pdev);
mutex_init(&ioc->ioctl_cmds.mutex);
init_completion(&ioc->ioctl_cmds.done);
return 0;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*
* mptctl_remove - Removed ioctl devices
* @pdev: Pointer to pci_dev structure
*
*
*/
static void
mptctl_remove(struct pci_dev *pdev)
{
}
static struct mpt_pci_driver mptctl_driver = {
.probe = mptctl_probe,
.remove = mptctl_remove,
};
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
static int __init mptctl_init(void)
{
int err;
int where = 1;
show_mptmod_ver(my_NAME, my_VERSION);
mpt_device_driver_register(&mptctl_driver, MPTCTL_DRIVER);
/* Register this device */
err = misc_register(&mptctl_miscdev);
if (err < 0) {
printk(KERN_ERR MYNAM ": Can't register misc device [minor=%d].\n", MPT_MINOR);
goto out_fail;
}
printk(KERN_INFO MYNAM ": Registered with Fusion MPT base driver\n");
printk(KERN_INFO MYNAM ": /dev/%s @ (major,minor=%d,%d)\n",
mptctl_miscdev.name, MISC_MAJOR, mptctl_miscdev.minor);
/*
* Install our handler
*/
++where;
mptctl_id = mpt_register(mptctl_reply, MPTCTL_DRIVER);
if (!mptctl_id || mptctl_id >= MPT_MAX_PROTOCOL_DRIVERS) {
printk(KERN_ERR MYNAM ": ERROR: Failed to register with Fusion MPT base driver\n");
misc_deregister(&mptctl_miscdev);
err = -EBUSY;
goto out_fail;
}
mptctl_taskmgmt_id = mpt_register(mptctl_taskmgmt_reply, MPTCTL_DRIVER);
mpt_reset_register(mptctl_id, mptctl_ioc_reset);
mpt_event_register(mptctl_id, mptctl_event_process);
return 0;
out_fail:
mpt_device_driver_deregister(MPTCTL_DRIVER);
return err;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
static void mptctl_exit(void)
{
misc_deregister(&mptctl_miscdev);
printk(KERN_INFO MYNAM ": Deregistered /dev/%s @ (major,minor=%d,%d)\n",
mptctl_miscdev.name, MISC_MAJOR, mptctl_miscdev.minor);
/* De-register reset handler from base module */
mpt_reset_deregister(mptctl_id);
/* De-register callback handler from base module */
mpt_deregister(mptctl_id);
mpt_reset_deregister(mptctl_taskmgmt_id);
mpt_device_driver_deregister(MPTCTL_DRIVER);
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
module_init(mptctl_init);
module_exit(mptctl_exit);
| gpl-2.0 |
Team-Hydra/android_kernel_htc_msm8x60 | block/genhd.c | 351 | 44540 | /*
* gendisk handling
*/
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/genhd.h>
#include <linux/kdev_t.h>
#include <linux/kernel.h>
#include <linux/blkdev.h>
#include <linux/init.h>
#include <linux/spinlock.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/slab.h>
#include <linux/kmod.h>
#include <linux/kobj_map.h>
#include <linux/mutex.h>
#include <linux/idr.h>
#include <linux/log2.h>
#include "blk.h"
static DEFINE_MUTEX(block_class_lock);
struct kobject *block_depr;
/* for extended dynamic devt allocation, currently only one major is used */
#define NR_EXT_DEVT (1 << MINORBITS)
/* For extended devt allocation. ext_devt_mutex prevents look up
* results from going away underneath its user.
*/
static DEFINE_MUTEX(ext_devt_mutex);
static DEFINE_IDR(ext_devt_idr);
static struct device_type disk_type;
static void disk_alloc_events(struct gendisk *disk);
static void disk_add_events(struct gendisk *disk);
static void disk_del_events(struct gendisk *disk);
static void disk_release_events(struct gendisk *disk);
/**
* disk_get_part - get partition
* @disk: disk to look partition from
* @partno: partition number
*
* Look for partition @partno from @disk. If found, increment
* reference count and return it.
*
* CONTEXT:
* Don't care.
*
* RETURNS:
* Pointer to the found partition on success, NULL if not found.
*/
struct hd_struct *disk_get_part(struct gendisk *disk, int partno)
{
struct hd_struct *part = NULL;
struct disk_part_tbl *ptbl;
if (unlikely(partno < 0))
return NULL;
rcu_read_lock();
ptbl = rcu_dereference(disk->part_tbl);
if (likely(partno < ptbl->len)) {
part = rcu_dereference(ptbl->part[partno]);
if (part)
get_device(part_to_dev(part));
}
rcu_read_unlock();
return part;
}
EXPORT_SYMBOL_GPL(disk_get_part);
/**
* disk_part_iter_init - initialize partition iterator
* @piter: iterator to initialize
* @disk: disk to iterate over
* @flags: DISK_PITER_* flags
*
* Initialize @piter so that it iterates over partitions of @disk.
*
* CONTEXT:
* Don't care.
*/
void disk_part_iter_init(struct disk_part_iter *piter, struct gendisk *disk,
unsigned int flags)
{
struct disk_part_tbl *ptbl;
rcu_read_lock();
ptbl = rcu_dereference(disk->part_tbl);
piter->disk = disk;
piter->part = NULL;
if (flags & DISK_PITER_REVERSE)
piter->idx = ptbl->len - 1;
else if (flags & (DISK_PITER_INCL_PART0 | DISK_PITER_INCL_EMPTY_PART0))
piter->idx = 0;
else
piter->idx = 1;
piter->flags = flags;
rcu_read_unlock();
}
EXPORT_SYMBOL_GPL(disk_part_iter_init);
/**
* disk_part_iter_next - proceed iterator to the next partition and return it
* @piter: iterator of interest
*
* Proceed @piter to the next partition and return it.
*
* CONTEXT:
* Don't care.
*/
struct hd_struct *disk_part_iter_next(struct disk_part_iter *piter)
{
struct disk_part_tbl *ptbl;
int inc, end;
/* put the last partition */
disk_put_part(piter->part);
piter->part = NULL;
/* get part_tbl */
rcu_read_lock();
ptbl = rcu_dereference(piter->disk->part_tbl);
/* determine iteration parameters */
if (piter->flags & DISK_PITER_REVERSE) {
inc = -1;
if (piter->flags & (DISK_PITER_INCL_PART0 |
DISK_PITER_INCL_EMPTY_PART0))
end = -1;
else
end = 0;
} else {
inc = 1;
end = ptbl->len;
}
/* iterate to the next partition */
for (; piter->idx != end; piter->idx += inc) {
struct hd_struct *part;
part = rcu_dereference(ptbl->part[piter->idx]);
if (!part)
continue;
if (!part->nr_sects &&
!(piter->flags & DISK_PITER_INCL_EMPTY) &&
!(piter->flags & DISK_PITER_INCL_EMPTY_PART0 &&
piter->idx == 0))
continue;
get_device(part_to_dev(part));
piter->part = part;
piter->idx += inc;
break;
}
rcu_read_unlock();
return piter->part;
}
EXPORT_SYMBOL_GPL(disk_part_iter_next);
/**
* disk_part_iter_exit - finish up partition iteration
* @piter: iter of interest
*
* Called when iteration is over. Cleans up @piter.
*
* CONTEXT:
* Don't care.
*/
void disk_part_iter_exit(struct disk_part_iter *piter)
{
disk_put_part(piter->part);
piter->part = NULL;
}
EXPORT_SYMBOL_GPL(disk_part_iter_exit);
static inline int sector_in_part(struct hd_struct *part, sector_t sector)
{
return part->start_sect <= sector &&
sector < part->start_sect + part->nr_sects;
}
/**
* disk_map_sector_rcu - map sector to partition
* @disk: gendisk of interest
* @sector: sector to map
*
* Find out which partition @sector maps to on @disk. This is
* primarily used for stats accounting.
*
* CONTEXT:
* RCU read locked. The returned partition pointer is valid only
* while preemption is disabled.
*
* RETURNS:
* Found partition on success, part0 is returned if no partition matches
*/
struct hd_struct *disk_map_sector_rcu(struct gendisk *disk, sector_t sector)
{
struct disk_part_tbl *ptbl;
struct hd_struct *part;
int i;
ptbl = rcu_dereference(disk->part_tbl);
part = rcu_dereference(ptbl->last_lookup);
if (part && sector_in_part(part, sector))
return part;
for (i = 1; i < ptbl->len; i++) {
part = rcu_dereference(ptbl->part[i]);
if (part && sector_in_part(part, sector)) {
rcu_assign_pointer(ptbl->last_lookup, part);
return part;
}
}
return &disk->part0;
}
EXPORT_SYMBOL_GPL(disk_map_sector_rcu);
/*
* Can be deleted altogether. Later.
*
*/
static struct blk_major_name {
struct blk_major_name *next;
int major;
char name[16];
} *major_names[BLKDEV_MAJOR_HASH_SIZE];
/* index in the above - for now: assume no multimajor ranges */
static inline int major_to_index(unsigned major)
{
return major % BLKDEV_MAJOR_HASH_SIZE;
}
#ifdef CONFIG_PROC_FS
void blkdev_show(struct seq_file *seqf, off_t offset)
{
struct blk_major_name *dp;
if (offset < BLKDEV_MAJOR_HASH_SIZE) {
mutex_lock(&block_class_lock);
for (dp = major_names[offset]; dp; dp = dp->next)
seq_printf(seqf, "%3d %s\n", dp->major, dp->name);
mutex_unlock(&block_class_lock);
}
}
#endif /* CONFIG_PROC_FS */
/**
* register_blkdev - register a new block device
*
* @major: the requested major device number [1..255]. If @major=0, try to
* allocate any unused major number.
* @name: the name of the new block device as a zero terminated string
*
* The @name must be unique within the system.
*
* The return value depends on the @major input parameter.
* - if a major device number was requested in range [1..255] then the
* function returns zero on success, or a negative error code
* - if any unused major number was requested with @major=0 parameter
* then the return value is the allocated major number in range
* [1..255] or a negative error code otherwise
*/
int register_blkdev(unsigned int major, const char *name)
{
struct blk_major_name **n, *p;
int index, ret = 0;
mutex_lock(&block_class_lock);
/* temporary */
if (major == 0) {
for (index = ARRAY_SIZE(major_names)-1; index > 0; index--) {
if (major_names[index] == NULL)
break;
}
if (index == 0) {
printk("register_blkdev: failed to get major for %s\n",
name);
ret = -EBUSY;
goto out;
}
major = index;
ret = major;
}
p = kmalloc(sizeof(struct blk_major_name), GFP_KERNEL);
if (p == NULL) {
ret = -ENOMEM;
goto out;
}
p->major = major;
strlcpy(p->name, name, sizeof(p->name));
p->next = NULL;
index = major_to_index(major);
for (n = &major_names[index]; *n; n = &(*n)->next) {
if ((*n)->major == major)
break;
}
if (!*n)
*n = p;
else
ret = -EBUSY;
if (ret < 0) {
printk("register_blkdev: cannot get major %d for %s\n",
major, name);
kfree(p);
}
out:
mutex_unlock(&block_class_lock);
return ret;
}
EXPORT_SYMBOL(register_blkdev);
void unregister_blkdev(unsigned int major, const char *name)
{
struct blk_major_name **n;
struct blk_major_name *p = NULL;
int index = major_to_index(major);
mutex_lock(&block_class_lock);
for (n = &major_names[index]; *n; n = &(*n)->next)
if ((*n)->major == major)
break;
if (!*n || strcmp((*n)->name, name)) {
WARN_ON(1);
} else {
p = *n;
*n = p->next;
}
mutex_unlock(&block_class_lock);
kfree(p);
}
EXPORT_SYMBOL(unregister_blkdev);
static struct kobj_map *bdev_map;
/**
* blk_mangle_minor - scatter minor numbers apart
* @minor: minor number to mangle
*
* Scatter consecutively allocated @minor number apart if MANGLE_DEVT
* is enabled. Mangling twice gives the original value.
*
* RETURNS:
* Mangled value.
*
* CONTEXT:
* Don't care.
*/
static int blk_mangle_minor(int minor)
{
#ifdef CONFIG_DEBUG_BLOCK_EXT_DEVT
int i;
for (i = 0; i < MINORBITS / 2; i++) {
int low = minor & (1 << i);
int high = minor & (1 << (MINORBITS - 1 - i));
int distance = MINORBITS - 1 - 2 * i;
minor ^= low | high; /* clear both bits */
low <<= distance; /* swap the positions */
high >>= distance;
minor |= low | high; /* and set */
}
#endif
return minor;
}
/**
* blk_alloc_devt - allocate a dev_t for a partition
* @part: partition to allocate dev_t for
* @devt: out parameter for resulting dev_t
*
* Allocate a dev_t for block device.
*
* RETURNS:
* 0 on success, allocated dev_t is returned in *@devt. -errno on
* failure.
*
* CONTEXT:
* Might sleep.
*/
int blk_alloc_devt(struct hd_struct *part, dev_t *devt)
{
struct gendisk *disk = part_to_disk(part);
int idx, rc;
/* in consecutive minor range? */
if (part->partno < disk->minors) {
*devt = MKDEV(disk->major, disk->first_minor + part->partno);
return 0;
}
/* allocate ext devt */
do {
if (!idr_pre_get(&ext_devt_idr, GFP_KERNEL))
return -ENOMEM;
mutex_lock(&ext_devt_mutex);
rc = idr_get_new(&ext_devt_idr, part, &idx);
if (!rc && idx >= NR_EXT_DEVT) {
idr_remove(&ext_devt_idr, idx);
rc = -EBUSY;
}
mutex_unlock(&ext_devt_mutex);
} while (rc == -EAGAIN);
if (rc)
return rc;
*devt = MKDEV(BLOCK_EXT_MAJOR, blk_mangle_minor(idx));
return 0;
}
/**
* blk_free_devt - free a dev_t
* @devt: dev_t to free
*
* Free @devt which was allocated using blk_alloc_devt().
*
* CONTEXT:
* Might sleep.
*/
void blk_free_devt(dev_t devt)
{
might_sleep();
if (devt == MKDEV(0, 0))
return;
if (MAJOR(devt) == BLOCK_EXT_MAJOR) {
mutex_lock(&ext_devt_mutex);
idr_remove(&ext_devt_idr, blk_mangle_minor(MINOR(devt)));
mutex_unlock(&ext_devt_mutex);
}
}
static char *bdevt_str(dev_t devt, char *buf)
{
if (MAJOR(devt) <= 0xff && MINOR(devt) <= 0xff) {
char tbuf[BDEVT_SIZE];
snprintf(tbuf, BDEVT_SIZE, "%02x%02x", MAJOR(devt), MINOR(devt));
snprintf(buf, BDEVT_SIZE, "%-9s", tbuf);
} else
snprintf(buf, BDEVT_SIZE, "%03x:%05x", MAJOR(devt), MINOR(devt));
return buf;
}
/*
* Register device numbers dev..(dev+range-1)
* range must be nonzero
* The hash chain is sorted on range, so that subranges can override.
*/
void blk_register_region(dev_t devt, unsigned long range, struct module *module,
struct kobject *(*probe)(dev_t, int *, void *),
int (*lock)(dev_t, void *), void *data)
{
kobj_map(bdev_map, devt, range, module, probe, lock, data);
}
EXPORT_SYMBOL(blk_register_region);
void blk_unregister_region(dev_t devt, unsigned long range)
{
kobj_unmap(bdev_map, devt, range);
}
EXPORT_SYMBOL(blk_unregister_region);
static struct kobject *exact_match(dev_t devt, int *partno, void *data)
{
struct gendisk *p = data;
return &disk_to_dev(p)->kobj;
}
static int exact_lock(dev_t devt, void *data)
{
struct gendisk *p = data;
if (!get_disk(p))
return -1;
return 0;
}
static void register_disk(struct gendisk *disk)
{
struct device *ddev = disk_to_dev(disk);
struct block_device *bdev;
struct disk_part_iter piter;
struct hd_struct *part;
int err;
ddev->parent = disk->driverfs_dev;
dev_set_name(ddev, "%s", disk->disk_name);
/* delay uevents, until we scanned partition table */
dev_set_uevent_suppress(ddev, 1);
if (device_add(ddev))
return;
if (!sysfs_deprecated) {
err = sysfs_create_link(block_depr, &ddev->kobj,
kobject_name(&ddev->kobj));
if (err) {
device_del(ddev);
return;
}
}
disk->part0.holder_dir = kobject_create_and_add("holders", &ddev->kobj);
disk->slave_dir = kobject_create_and_add("slaves", &ddev->kobj);
/* No minors to use for partitions */
if (!disk_part_scan_enabled(disk))
goto exit;
/* No such device (e.g., media were just removed) */
if (!get_capacity(disk))
goto exit;
bdev = bdget_disk(disk, 0);
if (!bdev)
goto exit;
bdev->bd_invalidated = 1;
err = blkdev_get(bdev, FMODE_READ, NULL);
if (err < 0)
goto exit;
blkdev_put(bdev, FMODE_READ);
exit:
/* announce disk after possible partitions are created */
dev_set_uevent_suppress(ddev, 0);
kobject_uevent(&ddev->kobj, KOBJ_ADD);
/* announce possible partitions */
disk_part_iter_init(&piter, disk, 0);
while ((part = disk_part_iter_next(&piter)))
kobject_uevent(&part_to_dev(part)->kobj, KOBJ_ADD);
disk_part_iter_exit(&piter);
}
/**
* add_disk - add partitioning information to kernel list
* @disk: per-device partitioning information
*
* This function registers the partitioning information in @disk
* with the kernel.
*
* FIXME: error handling
*/
void add_disk(struct gendisk *disk)
{
struct backing_dev_info *bdi;
dev_t devt;
int retval;
/* minors == 0 indicates to use ext devt from part0 and should
* be accompanied with EXT_DEVT flag. Make sure all
* parameters make sense.
*/
WARN_ON(disk->minors && !(disk->major || disk->first_minor));
WARN_ON(!disk->minors && !(disk->flags & GENHD_FL_EXT_DEVT));
disk->flags |= GENHD_FL_UP;
retval = blk_alloc_devt(&disk->part0, &devt);
if (retval) {
WARN_ON(1);
return;
}
disk_to_dev(disk)->devt = devt;
/* ->major and ->first_minor aren't supposed to be
* dereferenced from here on, but set them just in case.
*/
disk->major = MAJOR(devt);
disk->first_minor = MINOR(devt);
disk_alloc_events(disk);
/* Register BDI before referencing it from bdev */
bdi = &disk->queue->backing_dev_info;
bdi_register_dev(bdi, disk_devt(disk));
blk_register_region(disk_devt(disk), disk->minors, NULL,
exact_match, exact_lock, disk);
register_disk(disk);
blk_register_queue(disk);
/*
* Take an extra ref on queue which will be put on disk_release()
* so that it sticks around as long as @disk is there.
*/
WARN_ON_ONCE(!blk_get_queue(disk->queue));
retval = sysfs_create_link(&disk_to_dev(disk)->kobj, &bdi->dev->kobj,
"bdi");
WARN_ON(retval);
disk_add_events(disk);
}
EXPORT_SYMBOL(add_disk);
void del_gendisk(struct gendisk *disk)
{
struct disk_part_iter piter;
struct hd_struct *part;
disk_del_events(disk);
/* invalidate stuff */
disk_part_iter_init(&piter, disk,
DISK_PITER_INCL_EMPTY | DISK_PITER_REVERSE);
while ((part = disk_part_iter_next(&piter))) {
invalidate_partition(disk, part->partno);
delete_partition(disk, part->partno);
}
disk_part_iter_exit(&piter);
invalidate_partition(disk, 0);
set_capacity(disk, 0);
disk->flags &= ~GENHD_FL_UP;
sysfs_remove_link(&disk_to_dev(disk)->kobj, "bdi");
bdi_unregister(&disk->queue->backing_dev_info);
blk_unregister_queue(disk);
blk_unregister_region(disk_devt(disk), disk->minors);
part_stat_set_all(&disk->part0, 0);
disk->part0.stamp = 0;
kobject_put(disk->part0.holder_dir);
kobject_put(disk->slave_dir);
disk->driverfs_dev = NULL;
if (!sysfs_deprecated)
sysfs_remove_link(block_depr, dev_name(disk_to_dev(disk)));
device_del(disk_to_dev(disk));
blk_free_devt(disk_to_dev(disk)->devt);
}
EXPORT_SYMBOL(del_gendisk);
/**
* get_gendisk - get partitioning information for a given device
* @devt: device to get partitioning information for
* @partno: returned partition index
*
* This function gets the structure containing partitioning
* information for the given device @devt.
*/
struct gendisk *get_gendisk(dev_t devt, int *partno)
{
struct gendisk *disk = NULL;
if (MAJOR(devt) != BLOCK_EXT_MAJOR) {
struct kobject *kobj;
kobj = kobj_lookup(bdev_map, devt, partno);
if (kobj)
disk = dev_to_disk(kobj_to_dev(kobj));
} else {
struct hd_struct *part;
mutex_lock(&ext_devt_mutex);
part = idr_find(&ext_devt_idr, blk_mangle_minor(MINOR(devt)));
if (part && get_disk(part_to_disk(part))) {
*partno = part->partno;
disk = part_to_disk(part);
}
mutex_unlock(&ext_devt_mutex);
}
return disk;
}
EXPORT_SYMBOL(get_gendisk);
/**
* bdget_disk - do bdget() by gendisk and partition number
* @disk: gendisk of interest
* @partno: partition number
*
* Find partition @partno from @disk, do bdget() on it.
*
* CONTEXT:
* Don't care.
*
* RETURNS:
* Resulting block_device on success, NULL on failure.
*/
struct block_device *bdget_disk(struct gendisk *disk, int partno)
{
struct hd_struct *part;
struct block_device *bdev = NULL;
part = disk_get_part(disk, partno);
if (part)
bdev = bdget(part_devt(part));
disk_put_part(part);
return bdev;
}
EXPORT_SYMBOL(bdget_disk);
/*
* print a full list of all partitions - intended for places where the root
* filesystem can't be mounted and thus to give the victim some idea of what
* went wrong
*/
void __init printk_all_partitions(void)
{
struct class_dev_iter iter;
struct device *dev;
class_dev_iter_init(&iter, &block_class, NULL, &disk_type);
while ((dev = class_dev_iter_next(&iter))) {
struct gendisk *disk = dev_to_disk(dev);
struct disk_part_iter piter;
struct hd_struct *part;
char name_buf[BDEVNAME_SIZE];
char devt_buf[BDEVT_SIZE];
char uuid_buf[PARTITION_META_INFO_UUIDLTH * 2 + 5];
/*
* Don't show empty devices or things that have been
* suppressed
*/
if (get_capacity(disk) == 0 ||
(disk->flags & GENHD_FL_SUPPRESS_PARTITION_INFO))
continue;
/*
* Note, unlike /proc/partitions, I am showing the
* numbers in hex - the same format as the root=
* option takes.
*/
disk_part_iter_init(&piter, disk, DISK_PITER_INCL_PART0);
while ((part = disk_part_iter_next(&piter))) {
bool is_part0 = part == &disk->part0;
uuid_buf[0] = '\0';
if (part->info)
snprintf(uuid_buf, sizeof(uuid_buf), "%pU",
part->info->uuid);
printk("%s%s %10llu %s %s", is_part0 ? "" : " ",
bdevt_str(part_devt(part), devt_buf),
(unsigned long long)part->nr_sects >> 1,
disk_name(disk, part->partno, name_buf),
uuid_buf);
if (is_part0) {
if (disk->driverfs_dev != NULL &&
disk->driverfs_dev->driver != NULL)
printk(" driver: %s\n",
disk->driverfs_dev->driver->name);
else
printk(" (driver?)\n");
} else
printk("\n");
}
disk_part_iter_exit(&piter);
}
class_dev_iter_exit(&iter);
}
#ifdef CONFIG_PROC_FS
/* iterator */
static void *disk_seqf_start(struct seq_file *seqf, loff_t *pos)
{
loff_t skip = *pos;
struct class_dev_iter *iter;
struct device *dev;
iter = kmalloc(sizeof(*iter), GFP_KERNEL);
if (!iter)
return ERR_PTR(-ENOMEM);
seqf->private = iter;
class_dev_iter_init(iter, &block_class, NULL, &disk_type);
do {
dev = class_dev_iter_next(iter);
if (!dev)
return NULL;
} while (skip--);
return dev_to_disk(dev);
}
static void *disk_seqf_next(struct seq_file *seqf, void *v, loff_t *pos)
{
struct device *dev;
(*pos)++;
dev = class_dev_iter_next(seqf->private);
if (dev)
return dev_to_disk(dev);
return NULL;
}
static void disk_seqf_stop(struct seq_file *seqf, void *v)
{
struct class_dev_iter *iter = seqf->private;
/* stop is called even after start failed :-( */
if (iter) {
class_dev_iter_exit(iter);
kfree(iter);
}
}
static void *show_partition_start(struct seq_file *seqf, loff_t *pos)
{
static void *p;
p = disk_seqf_start(seqf, pos);
if (!IS_ERR_OR_NULL(p) && !*pos)
seq_puts(seqf, "major minor #blocks name\n\n");
return p;
}
static int show_partition(struct seq_file *seqf, void *v)
{
struct gendisk *sgp = v;
struct disk_part_iter piter;
struct hd_struct *part;
char buf[BDEVNAME_SIZE];
/* Don't show non-partitionable removeable devices or empty devices */
if (!get_capacity(sgp) || (!disk_max_parts(sgp) &&
(sgp->flags & GENHD_FL_REMOVABLE)))
return 0;
if (sgp->flags & GENHD_FL_SUPPRESS_PARTITION_INFO)
return 0;
/* show the full disk and all non-0 size partitions of it */
disk_part_iter_init(&piter, sgp, DISK_PITER_INCL_PART0);
while ((part = disk_part_iter_next(&piter)))
seq_printf(seqf, "%4d %7d %10llu %s\n",
MAJOR(part_devt(part)), MINOR(part_devt(part)),
(unsigned long long)part->nr_sects >> 1,
disk_name(sgp, part->partno, buf));
disk_part_iter_exit(&piter);
return 0;
}
static const struct seq_operations partitions_op = {
.start = show_partition_start,
.next = disk_seqf_next,
.stop = disk_seqf_stop,
.show = show_partition
};
static int partitions_open(struct inode *inode, struct file *file)
{
return seq_open(file, &partitions_op);
}
static const struct file_operations proc_partitions_operations = {
.open = partitions_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
#endif
static struct kobject *base_probe(dev_t devt, int *partno, void *data)
{
if (request_module("block-major-%d-%d", MAJOR(devt), MINOR(devt)) > 0)
/* Make old-style 2.4 aliases work */
request_module("block-major-%d", MAJOR(devt));
return NULL;
}
static int __init genhd_device_init(void)
{
int error;
block_class.dev_kobj = sysfs_dev_block_kobj;
error = class_register(&block_class);
if (unlikely(error))
return error;
bdev_map = kobj_map_init(base_probe, &block_class_lock);
blk_dev_init();
register_blkdev(BLOCK_EXT_MAJOR, "blkext");
/* create top-level block dir */
if (!sysfs_deprecated)
block_depr = kobject_create_and_add("block", NULL);
return 0;
}
subsys_initcall(genhd_device_init);
static ssize_t disk_range_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct gendisk *disk = dev_to_disk(dev);
return sprintf(buf, "%d\n", disk->minors);
}
static ssize_t disk_ext_range_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct gendisk *disk = dev_to_disk(dev);
return sprintf(buf, "%d\n", disk_max_parts(disk));
}
static ssize_t disk_removable_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct gendisk *disk = dev_to_disk(dev);
return sprintf(buf, "%d\n",
(disk->flags & GENHD_FL_REMOVABLE ? 1 : 0));
}
static ssize_t disk_ro_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct gendisk *disk = dev_to_disk(dev);
return sprintf(buf, "%d\n", get_disk_ro(disk) ? 1 : 0);
}
static ssize_t disk_capability_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct gendisk *disk = dev_to_disk(dev);
return sprintf(buf, "%x\n", disk->flags);
}
static ssize_t disk_alignment_offset_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct gendisk *disk = dev_to_disk(dev);
return sprintf(buf, "%d\n", queue_alignment_offset(disk->queue));
}
static ssize_t disk_discard_alignment_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct gendisk *disk = dev_to_disk(dev);
return sprintf(buf, "%d\n", queue_discard_alignment(disk->queue));
}
static DEVICE_ATTR(range, S_IRUGO, disk_range_show, NULL);
static DEVICE_ATTR(ext_range, S_IRUGO, disk_ext_range_show, NULL);
static DEVICE_ATTR(removable, S_IRUGO, disk_removable_show, NULL);
static DEVICE_ATTR(ro, S_IRUGO, disk_ro_show, NULL);
static DEVICE_ATTR(size, S_IRUGO, part_size_show, NULL);
static DEVICE_ATTR(alignment_offset, S_IRUGO, disk_alignment_offset_show, NULL);
static DEVICE_ATTR(discard_alignment, S_IRUGO, disk_discard_alignment_show,
NULL);
static DEVICE_ATTR(capability, S_IRUGO, disk_capability_show, NULL);
static DEVICE_ATTR(stat, S_IRUGO, part_stat_show, NULL);
static DEVICE_ATTR(inflight, S_IRUGO, part_inflight_show, NULL);
#ifdef CONFIG_FAIL_MAKE_REQUEST
static struct device_attribute dev_attr_fail =
__ATTR(make-it-fail, S_IRUGO|S_IWUSR, part_fail_show, part_fail_store);
#endif
#ifdef CONFIG_FAIL_IO_TIMEOUT
static struct device_attribute dev_attr_fail_timeout =
__ATTR(io-timeout-fail, S_IRUGO|S_IWUSR, part_timeout_show,
part_timeout_store);
#endif
static struct attribute *disk_attrs[] = {
&dev_attr_range.attr,
&dev_attr_ext_range.attr,
&dev_attr_removable.attr,
&dev_attr_ro.attr,
&dev_attr_size.attr,
&dev_attr_alignment_offset.attr,
&dev_attr_discard_alignment.attr,
&dev_attr_capability.attr,
&dev_attr_stat.attr,
&dev_attr_inflight.attr,
#ifdef CONFIG_FAIL_MAKE_REQUEST
&dev_attr_fail.attr,
#endif
#ifdef CONFIG_FAIL_IO_TIMEOUT
&dev_attr_fail_timeout.attr,
#endif
NULL
};
static struct attribute_group disk_attr_group = {
.attrs = disk_attrs,
};
static const struct attribute_group *disk_attr_groups[] = {
&disk_attr_group,
NULL
};
/**
* disk_replace_part_tbl - replace disk->part_tbl in RCU-safe way
* @disk: disk to replace part_tbl for
* @new_ptbl: new part_tbl to install
*
* Replace disk->part_tbl with @new_ptbl in RCU-safe way. The
* original ptbl is freed using RCU callback.
*
* LOCKING:
* Matching bd_mutx locked.
*/
static void disk_replace_part_tbl(struct gendisk *disk,
struct disk_part_tbl *new_ptbl)
{
struct disk_part_tbl *old_ptbl = disk->part_tbl;
rcu_assign_pointer(disk->part_tbl, new_ptbl);
if (old_ptbl) {
rcu_assign_pointer(old_ptbl->last_lookup, NULL);
kfree_rcu(old_ptbl, rcu_head);
}
}
/**
* disk_expand_part_tbl - expand disk->part_tbl
* @disk: disk to expand part_tbl for
* @partno: expand such that this partno can fit in
*
* Expand disk->part_tbl such that @partno can fit in. disk->part_tbl
* uses RCU to allow unlocked dereferencing for stats and other stuff.
*
* LOCKING:
* Matching bd_mutex locked, might sleep.
*
* RETURNS:
* 0 on success, -errno on failure.
*/
int disk_expand_part_tbl(struct gendisk *disk, int partno)
{
struct disk_part_tbl *old_ptbl = disk->part_tbl;
struct disk_part_tbl *new_ptbl;
int len = old_ptbl ? old_ptbl->len : 0;
int target = partno + 1;
size_t size;
int i;
/* disk_max_parts() is zero during initialization, ignore if so */
if (disk_max_parts(disk) && target > disk_max_parts(disk))
return -EINVAL;
if (target <= len)
return 0;
size = sizeof(*new_ptbl) + target * sizeof(new_ptbl->part[0]);
new_ptbl = kzalloc_node(size, GFP_KERNEL, disk->node_id);
if (!new_ptbl)
return -ENOMEM;
new_ptbl->len = target;
for (i = 0; i < len; i++)
rcu_assign_pointer(new_ptbl->part[i], old_ptbl->part[i]);
disk_replace_part_tbl(disk, new_ptbl);
return 0;
}
static void disk_release(struct device *dev)
{
struct gendisk *disk = dev_to_disk(dev);
disk_release_events(disk);
kfree(disk->random);
disk_replace_part_tbl(disk, NULL);
free_part_stats(&disk->part0);
free_part_info(&disk->part0);
if (disk->queue)
blk_put_queue(disk->queue);
kfree(disk);
}
static int disk_uevent(struct device *dev, struct kobj_uevent_env *env)
{
struct gendisk *disk = dev_to_disk(dev);
struct disk_part_iter piter;
struct hd_struct *part;
int cnt = 0;
disk_part_iter_init(&piter, disk, 0);
while((part = disk_part_iter_next(&piter)))
cnt++;
disk_part_iter_exit(&piter);
add_uevent_var(env, "NPARTS=%u", cnt);
return 0;
}
struct class block_class = {
.name = "block",
};
static char *block_devnode(struct device *dev, umode_t *mode)
{
struct gendisk *disk = dev_to_disk(dev);
if (disk->devnode)
return disk->devnode(disk, mode);
return NULL;
}
static struct device_type disk_type = {
.name = "disk",
.groups = disk_attr_groups,
.release = disk_release,
.devnode = block_devnode,
.uevent = disk_uevent,
};
#ifdef CONFIG_PROC_FS
/*
* aggregate disk stat collector. Uses the same stats that the sysfs
* entries do, above, but makes them available through one seq_file.
*
* The output looks suspiciously like /proc/partitions with a bunch of
* extra fields.
*/
static int diskstats_show(struct seq_file *seqf, void *v)
{
struct gendisk *gp = v;
struct disk_part_iter piter;
struct hd_struct *hd;
char buf[BDEVNAME_SIZE];
int cpu;
/*
if (&disk_to_dev(gp)->kobj.entry == block_class.devices.next)
seq_puts(seqf, "major minor name"
" rio rmerge rsect ruse wio wmerge "
"wsect wuse running use aveq"
"\n\n");
*/
disk_part_iter_init(&piter, gp, DISK_PITER_INCL_EMPTY_PART0);
while ((hd = disk_part_iter_next(&piter))) {
cpu = part_stat_lock();
part_round_stats(cpu, hd);
part_stat_unlock();
seq_printf(seqf, "%4d %7d %s %lu %lu %lu "
"%u %lu %lu %lu %u %u %u %u\n",
MAJOR(part_devt(hd)), MINOR(part_devt(hd)),
disk_name(gp, hd->partno, buf),
part_stat_read(hd, ios[READ]),
part_stat_read(hd, merges[READ]),
part_stat_read(hd, sectors[READ]),
jiffies_to_msecs(part_stat_read(hd, ticks[READ])),
part_stat_read(hd, ios[WRITE]),
part_stat_read(hd, merges[WRITE]),
part_stat_read(hd, sectors[WRITE]),
jiffies_to_msecs(part_stat_read(hd, ticks[WRITE])),
part_in_flight(hd),
jiffies_to_msecs(part_stat_read(hd, io_ticks)),
jiffies_to_msecs(part_stat_read(hd, time_in_queue))
);
}
disk_part_iter_exit(&piter);
return 0;
}
static const struct seq_operations diskstats_op = {
.start = disk_seqf_start,
.next = disk_seqf_next,
.stop = disk_seqf_stop,
.show = diskstats_show
};
static int diskstats_open(struct inode *inode, struct file *file)
{
return seq_open(file, &diskstats_op);
}
static const struct file_operations proc_diskstats_operations = {
.open = diskstats_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
static int __init proc_genhd_init(void)
{
proc_create("diskstats", 0, NULL, &proc_diskstats_operations);
proc_create("partitions", 0, NULL, &proc_partitions_operations);
return 0;
}
module_init(proc_genhd_init);
#endif /* CONFIG_PROC_FS */
dev_t blk_lookup_devt(const char *name, int partno)
{
dev_t devt = MKDEV(0, 0);
struct class_dev_iter iter;
struct device *dev;
class_dev_iter_init(&iter, &block_class, NULL, &disk_type);
while ((dev = class_dev_iter_next(&iter))) {
struct gendisk *disk = dev_to_disk(dev);
struct hd_struct *part;
if (strcmp(dev_name(dev), name))
continue;
if (partno < disk->minors) {
/* We need to return the right devno, even
* if the partition doesn't exist yet.
*/
devt = MKDEV(MAJOR(dev->devt),
MINOR(dev->devt) + partno);
break;
}
part = disk_get_part(disk, partno);
if (part) {
devt = part_devt(part);
disk_put_part(part);
break;
}
disk_put_part(part);
}
class_dev_iter_exit(&iter);
return devt;
}
EXPORT_SYMBOL(blk_lookup_devt);
struct gendisk *alloc_disk(int minors)
{
return alloc_disk_node(minors, -1);
}
EXPORT_SYMBOL(alloc_disk);
struct gendisk *alloc_disk_node(int minors, int node_id)
{
struct gendisk *disk;
disk = kmalloc_node(sizeof(struct gendisk),
GFP_KERNEL | __GFP_ZERO, node_id);
if (disk) {
if (!init_part_stats(&disk->part0)) {
kfree(disk);
return NULL;
}
disk->node_id = node_id;
if (disk_expand_part_tbl(disk, 0)) {
free_part_stats(&disk->part0);
kfree(disk);
return NULL;
}
disk->part_tbl->part[0] = &disk->part0;
hd_ref_init(&disk->part0);
disk->minors = minors;
rand_initialize_disk(disk);
disk_to_dev(disk)->class = &block_class;
disk_to_dev(disk)->type = &disk_type;
device_initialize(disk_to_dev(disk));
}
return disk;
}
EXPORT_SYMBOL(alloc_disk_node);
struct kobject *get_disk(struct gendisk *disk)
{
struct module *owner;
struct kobject *kobj;
if (!disk->fops)
return NULL;
owner = disk->fops->owner;
if (owner && !try_module_get(owner))
return NULL;
kobj = kobject_get(&disk_to_dev(disk)->kobj);
if (kobj == NULL) {
module_put(owner);
return NULL;
}
return kobj;
}
EXPORT_SYMBOL(get_disk);
void put_disk(struct gendisk *disk)
{
if (disk)
kobject_put(&disk_to_dev(disk)->kobj);
}
EXPORT_SYMBOL(put_disk);
static void set_disk_ro_uevent(struct gendisk *gd, int ro)
{
char event[] = "DISK_RO=1";
char *envp[] = { event, NULL };
if (!ro)
event[8] = '0';
kobject_uevent_env(&disk_to_dev(gd)->kobj, KOBJ_CHANGE, envp);
}
void set_device_ro(struct block_device *bdev, int flag)
{
bdev->bd_part->policy = flag;
}
EXPORT_SYMBOL(set_device_ro);
void set_disk_ro(struct gendisk *disk, int flag)
{
struct disk_part_iter piter;
struct hd_struct *part;
if (disk->part0.policy != flag) {
set_disk_ro_uevent(disk, flag);
disk->part0.policy = flag;
}
disk_part_iter_init(&piter, disk, DISK_PITER_INCL_EMPTY);
while ((part = disk_part_iter_next(&piter)))
part->policy = flag;
disk_part_iter_exit(&piter);
}
EXPORT_SYMBOL(set_disk_ro);
int bdev_read_only(struct block_device *bdev)
{
if (!bdev)
return 0;
return bdev->bd_part->policy;
}
EXPORT_SYMBOL(bdev_read_only);
int invalidate_partition(struct gendisk *disk, int partno)
{
int res = 0;
struct block_device *bdev = bdget_disk(disk, partno);
if (bdev) {
fsync_bdev(bdev);
res = __invalidate_device(bdev, true);
bdput(bdev);
}
return res;
}
EXPORT_SYMBOL(invalidate_partition);
/*
* Disk events - monitor disk events like media change and eject request.
*/
struct disk_events {
struct list_head node; /* all disk_event's */
struct gendisk *disk; /* the associated disk */
spinlock_t lock;
struct mutex block_mutex; /* protects blocking */
int block; /* event blocking depth */
unsigned int pending; /* events already sent out */
unsigned int clearing; /* events being cleared */
long poll_msecs; /* interval, -1 for default */
struct delayed_work dwork;
};
static const char *disk_events_strs[] = {
[ilog2(DISK_EVENT_MEDIA_CHANGE)] = "media_change",
[ilog2(DISK_EVENT_EJECT_REQUEST)] = "eject_request",
};
static char *disk_uevents[] = {
[ilog2(DISK_EVENT_MEDIA_CHANGE)] = "DISK_MEDIA_CHANGE=1",
[ilog2(DISK_EVENT_EJECT_REQUEST)] = "DISK_EJECT_REQUEST=1",
};
/* list of all disk_events */
static DEFINE_MUTEX(disk_events_mutex);
static LIST_HEAD(disk_events);
/* disable in-kernel polling by default */
static unsigned long disk_events_dfl_poll_msecs = 0;
static unsigned long disk_events_poll_jiffies(struct gendisk *disk)
{
struct disk_events *ev = disk->ev;
long intv_msecs = 0;
/*
* If device-specific poll interval is set, always use it. If
* the default is being used, poll iff there are events which
* can't be monitored asynchronously.
*/
if (ev->poll_msecs >= 0)
intv_msecs = ev->poll_msecs;
else if (disk->events & ~disk->async_events)
intv_msecs = disk_events_dfl_poll_msecs;
return msecs_to_jiffies(intv_msecs);
}
/**
* disk_block_events - block and flush disk event checking
* @disk: disk to block events for
*
* On return from this function, it is guaranteed that event checking
* isn't in progress and won't happen until unblocked by
* disk_unblock_events(). Events blocking is counted and the actual
* unblocking happens after the matching number of unblocks are done.
*
* Note that this intentionally does not block event checking from
* disk_clear_events().
*
* CONTEXT:
* Might sleep.
*/
void disk_block_events(struct gendisk *disk)
{
struct disk_events *ev = disk->ev;
unsigned long flags;
bool cancel;
if (!ev)
return;
/*
* Outer mutex ensures that the first blocker completes canceling
* the event work before further blockers are allowed to finish.
*/
mutex_lock(&ev->block_mutex);
spin_lock_irqsave(&ev->lock, flags);
cancel = !ev->block++;
spin_unlock_irqrestore(&ev->lock, flags);
if (cancel)
cancel_delayed_work_sync(&disk->ev->dwork);
mutex_unlock(&ev->block_mutex);
}
static void __disk_unblock_events(struct gendisk *disk, bool check_now)
{
struct disk_events *ev = disk->ev;
unsigned long intv;
unsigned long flags;
spin_lock_irqsave(&ev->lock, flags);
if (WARN_ON_ONCE(ev->block <= 0))
goto out_unlock;
if (--ev->block)
goto out_unlock;
/*
* Not exactly a latency critical operation, set poll timer
* slack to 25% and kick event check.
*/
intv = disk_events_poll_jiffies(disk);
set_timer_slack(&ev->dwork.timer, intv / 4);
if (check_now)
queue_delayed_work(system_nrt_freezable_wq, &ev->dwork, 0);
else if (intv)
queue_delayed_work(system_nrt_freezable_wq, &ev->dwork, intv);
out_unlock:
spin_unlock_irqrestore(&ev->lock, flags);
}
/**
* disk_unblock_events - unblock disk event checking
* @disk: disk to unblock events for
*
* Undo disk_block_events(). When the block count reaches zero, it
* starts events polling if configured.
*
* CONTEXT:
* Don't care. Safe to call from irq context.
*/
void disk_unblock_events(struct gendisk *disk)
{
if (disk->ev)
__disk_unblock_events(disk, false);
}
/**
* disk_flush_events - schedule immediate event checking and flushing
* @disk: disk to check and flush events for
* @mask: events to flush
*
* Schedule immediate event checking on @disk if not blocked. Events in
* @mask are scheduled to be cleared from the driver. Note that this
* doesn't clear the events from @disk->ev.
*
* CONTEXT:
* If @mask is non-zero must be called with bdev->bd_mutex held.
*/
void disk_flush_events(struct gendisk *disk, unsigned int mask)
{
struct disk_events *ev = disk->ev;
if (!ev)
return;
spin_lock_irq(&ev->lock);
ev->clearing |= mask;
if (!ev->block) {
cancel_delayed_work(&ev->dwork);
queue_delayed_work(system_nrt_freezable_wq, &ev->dwork, 0);
}
spin_unlock_irq(&ev->lock);
}
/**
* disk_clear_events - synchronously check, clear and return pending events
* @disk: disk to fetch and clear events from
* @mask: mask of events to be fetched and clearted
*
* Disk events are synchronously checked and pending events in @mask
* are cleared and returned. This ignores the block count.
*
* CONTEXT:
* Might sleep.
*/
unsigned int disk_clear_events(struct gendisk *disk, unsigned int mask)
{
const struct block_device_operations *bdops = disk->fops;
struct disk_events *ev = disk->ev;
unsigned int pending;
if (!ev) {
/* for drivers still using the old ->media_changed method */
if ((mask & DISK_EVENT_MEDIA_CHANGE) &&
bdops->media_changed && bdops->media_changed(disk))
return DISK_EVENT_MEDIA_CHANGE;
return 0;
}
/* tell the workfn about the events being cleared */
spin_lock_irq(&ev->lock);
ev->clearing |= mask;
spin_unlock_irq(&ev->lock);
/* uncondtionally schedule event check and wait for it to finish */
disk_block_events(disk);
queue_delayed_work(system_nrt_freezable_wq, &ev->dwork, 0);
flush_delayed_work(&ev->dwork);
__disk_unblock_events(disk, false);
/* then, fetch and clear pending events */
spin_lock_irq(&ev->lock);
WARN_ON_ONCE(ev->clearing & mask); /* cleared by workfn */
pending = ev->pending & mask;
ev->pending &= ~mask;
spin_unlock_irq(&ev->lock);
return pending;
}
static void disk_events_workfn(struct work_struct *work)
{
struct delayed_work *dwork = to_delayed_work(work);
struct disk_events *ev = container_of(dwork, struct disk_events, dwork);
struct gendisk *disk = ev->disk;
char *envp[ARRAY_SIZE(disk_uevents) + 1] = { };
unsigned int clearing = ev->clearing;
unsigned int events;
unsigned long intv;
int nr_events = 0, i;
/* check events */
events = disk->fops->check_events(disk, clearing);
/* accumulate pending events and schedule next poll if necessary */
spin_lock_irq(&ev->lock);
events &= ~ev->pending;
ev->pending |= events;
ev->clearing &= ~clearing;
intv = disk_events_poll_jiffies(disk);
if (!ev->block && intv)
queue_delayed_work(system_nrt_freezable_wq, &ev->dwork, intv);
spin_unlock_irq(&ev->lock);
/*
* Tell userland about new events. Only the events listed in
* @disk->events are reported. Unlisted events are processed the
* same internally but never get reported to userland.
*/
for (i = 0; i < ARRAY_SIZE(disk_uevents); i++)
if (events & disk->events & (1 << i))
envp[nr_events++] = disk_uevents[i];
if (nr_events)
kobject_uevent_env(&disk_to_dev(disk)->kobj, KOBJ_CHANGE, envp);
}
/*
* A disk events enabled device has the following sysfs nodes under
* its /sys/block/X/ directory.
*
* events : list of all supported events
* events_async : list of events which can be detected w/o polling
* events_poll_msecs : polling interval, 0: disable, -1: system default
*/
static ssize_t __disk_events_show(unsigned int events, char *buf)
{
const char *delim = "";
ssize_t pos = 0;
int i;
for (i = 0; i < ARRAY_SIZE(disk_events_strs); i++)
if (events & (1 << i)) {
pos += sprintf(buf + pos, "%s%s",
delim, disk_events_strs[i]);
delim = " ";
}
if (pos)
pos += sprintf(buf + pos, "\n");
return pos;
}
static ssize_t disk_events_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct gendisk *disk = dev_to_disk(dev);
return __disk_events_show(disk->events, buf);
}
static ssize_t disk_events_async_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct gendisk *disk = dev_to_disk(dev);
return __disk_events_show(disk->async_events, buf);
}
static ssize_t disk_events_poll_msecs_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct gendisk *disk = dev_to_disk(dev);
return sprintf(buf, "%ld\n", disk->ev->poll_msecs);
}
static ssize_t disk_events_poll_msecs_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct gendisk *disk = dev_to_disk(dev);
long intv;
if (!count || !sscanf(buf, "%ld", &intv))
return -EINVAL;
if (intv < 0 && intv != -1)
return -EINVAL;
disk_block_events(disk);
disk->ev->poll_msecs = intv;
__disk_unblock_events(disk, true);
return count;
}
static const DEVICE_ATTR(events, S_IRUGO, disk_events_show, NULL);
static const DEVICE_ATTR(events_async, S_IRUGO, disk_events_async_show, NULL);
static const DEVICE_ATTR(events_poll_msecs, S_IRUGO|S_IWUSR,
disk_events_poll_msecs_show,
disk_events_poll_msecs_store);
static const struct attribute *disk_events_attrs[] = {
&dev_attr_events.attr,
&dev_attr_events_async.attr,
&dev_attr_events_poll_msecs.attr,
NULL,
};
/*
* The default polling interval can be specified by the kernel
* parameter block.events_dfl_poll_msecs which defaults to 0
* (disable). This can also be modified runtime by writing to
* /sys/module/block/events_dfl_poll_msecs.
*/
static int disk_events_set_dfl_poll_msecs(const char *val,
const struct kernel_param *kp)
{
struct disk_events *ev;
int ret;
ret = param_set_ulong(val, kp);
if (ret < 0)
return ret;
mutex_lock(&disk_events_mutex);
list_for_each_entry(ev, &disk_events, node)
disk_flush_events(ev->disk, 0);
mutex_unlock(&disk_events_mutex);
return 0;
}
static const struct kernel_param_ops disk_events_dfl_poll_msecs_param_ops = {
.set = disk_events_set_dfl_poll_msecs,
.get = param_get_ulong,
};
#undef MODULE_PARAM_PREFIX
#define MODULE_PARAM_PREFIX "block."
module_param_cb(events_dfl_poll_msecs, &disk_events_dfl_poll_msecs_param_ops,
&disk_events_dfl_poll_msecs, 0644);
/*
* disk_{alloc|add|del|release}_events - initialize and destroy disk_events.
*/
static void disk_alloc_events(struct gendisk *disk)
{
struct disk_events *ev;
if (!disk->fops->check_events)
return;
ev = kzalloc(sizeof(*ev), GFP_KERNEL);
if (!ev) {
pr_warn("%s: failed to initialize events\n", disk->disk_name);
return;
}
INIT_LIST_HEAD(&ev->node);
ev->disk = disk;
spin_lock_init(&ev->lock);
mutex_init(&ev->block_mutex);
ev->block = 1;
ev->poll_msecs = -1;
INIT_DELAYED_WORK(&ev->dwork, disk_events_workfn);
disk->ev = ev;
}
static void disk_add_events(struct gendisk *disk)
{
if (!disk->ev)
return;
/* FIXME: error handling */
if (sysfs_create_files(&disk_to_dev(disk)->kobj, disk_events_attrs) < 0)
pr_warn("%s: failed to create sysfs files for events\n",
disk->disk_name);
mutex_lock(&disk_events_mutex);
list_add_tail(&disk->ev->node, &disk_events);
mutex_unlock(&disk_events_mutex);
/*
* Block count is initialized to 1 and the following initial
* unblock kicks it into action.
*/
__disk_unblock_events(disk, true);
}
static void disk_del_events(struct gendisk *disk)
{
if (!disk->ev)
return;
disk_block_events(disk);
mutex_lock(&disk_events_mutex);
list_del_init(&disk->ev->node);
mutex_unlock(&disk_events_mutex);
sysfs_remove_files(&disk_to_dev(disk)->kobj, disk_events_attrs);
}
static void disk_release_events(struct gendisk *disk)
{
/* the block count should be 1 from disk_del_events() */
WARN_ON_ONCE(disk->ev && disk->ev->block != 1);
kfree(disk->ev);
}
| gpl-2.0 |
jetonbacaj/SomeKernel_G920P_PB6 | drivers/gpu/drm/i915/intel_ringbuffer.c | 607 | 51125 | /*
* Copyright © 2008-2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE 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.
*
* Authors:
* Eric Anholt <eric@anholt.net>
* Zou Nan hai <nanhai.zou@intel.com>
* Xiang Hai hao<haihao.xiang@intel.com>
*
*/
#include <drm/drmP.h>
#include "i915_drv.h"
#include <drm/i915_drm.h>
#include "i915_trace.h"
#include "intel_drv.h"
/*
* 965+ support PIPE_CONTROL commands, which provide finer grained control
* over cache flushing.
*/
struct pipe_control {
struct drm_i915_gem_object *obj;
volatile u32 *cpu_page;
u32 gtt_offset;
};
static inline int ring_space(struct intel_ring_buffer *ring)
{
int space = (ring->head & HEAD_ADDR) - (ring->tail + I915_RING_FREE_SPACE);
if (space < 0)
space += ring->size;
return space;
}
static int
gen2_render_ring_flush(struct intel_ring_buffer *ring,
u32 invalidate_domains,
u32 flush_domains)
{
u32 cmd;
int ret;
cmd = MI_FLUSH;
if (((invalidate_domains|flush_domains) & I915_GEM_DOMAIN_RENDER) == 0)
cmd |= MI_NO_WRITE_FLUSH;
if (invalidate_domains & I915_GEM_DOMAIN_SAMPLER)
cmd |= MI_READ_FLUSH;
ret = intel_ring_begin(ring, 2);
if (ret)
return ret;
intel_ring_emit(ring, cmd);
intel_ring_emit(ring, MI_NOOP);
intel_ring_advance(ring);
return 0;
}
static int
gen4_render_ring_flush(struct intel_ring_buffer *ring,
u32 invalidate_domains,
u32 flush_domains)
{
struct drm_device *dev = ring->dev;
u32 cmd;
int ret;
/*
* read/write caches:
*
* I915_GEM_DOMAIN_RENDER is always invalidated, but is
* only flushed if MI_NO_WRITE_FLUSH is unset. On 965, it is
* also flushed at 2d versus 3d pipeline switches.
*
* read-only caches:
*
* I915_GEM_DOMAIN_SAMPLER is flushed on pre-965 if
* MI_READ_FLUSH is set, and is always flushed on 965.
*
* I915_GEM_DOMAIN_COMMAND may not exist?
*
* I915_GEM_DOMAIN_INSTRUCTION, which exists on 965, is
* invalidated when MI_EXE_FLUSH is set.
*
* I915_GEM_DOMAIN_VERTEX, which exists on 965, is
* invalidated with every MI_FLUSH.
*
* TLBs:
*
* On 965, TLBs associated with I915_GEM_DOMAIN_COMMAND
* and I915_GEM_DOMAIN_CPU in are invalidated at PTE write and
* I915_GEM_DOMAIN_RENDER and I915_GEM_DOMAIN_SAMPLER
* are flushed at any MI_FLUSH.
*/
cmd = MI_FLUSH | MI_NO_WRITE_FLUSH;
if ((invalidate_domains|flush_domains) & I915_GEM_DOMAIN_RENDER)
cmd &= ~MI_NO_WRITE_FLUSH;
if (invalidate_domains & I915_GEM_DOMAIN_INSTRUCTION)
cmd |= MI_EXE_FLUSH;
if (invalidate_domains & I915_GEM_DOMAIN_COMMAND &&
(IS_G4X(dev) || IS_GEN5(dev)))
cmd |= MI_INVALIDATE_ISP;
ret = intel_ring_begin(ring, 2);
if (ret)
return ret;
intel_ring_emit(ring, cmd);
intel_ring_emit(ring, MI_NOOP);
intel_ring_advance(ring);
return 0;
}
/**
* Emits a PIPE_CONTROL with a non-zero post-sync operation, for
* implementing two workarounds on gen6. From section 1.4.7.1
* "PIPE_CONTROL" of the Sandy Bridge PRM volume 2 part 1:
*
* [DevSNB-C+{W/A}] Before any depth stall flush (including those
* produced by non-pipelined state commands), software needs to first
* send a PIPE_CONTROL with no bits set except Post-Sync Operation !=
* 0.
*
* [Dev-SNB{W/A}]: Before a PIPE_CONTROL with Write Cache Flush Enable
* =1, a PIPE_CONTROL with any non-zero post-sync-op is required.
*
* And the workaround for these two requires this workaround first:
*
* [Dev-SNB{W/A}]: Pipe-control with CS-stall bit set must be sent
* BEFORE the pipe-control with a post-sync op and no write-cache
* flushes.
*
* And this last workaround is tricky because of the requirements on
* that bit. From section 1.4.7.2.3 "Stall" of the Sandy Bridge PRM
* volume 2 part 1:
*
* "1 of the following must also be set:
* - Render Target Cache Flush Enable ([12] of DW1)
* - Depth Cache Flush Enable ([0] of DW1)
* - Stall at Pixel Scoreboard ([1] of DW1)
* - Depth Stall ([13] of DW1)
* - Post-Sync Operation ([13] of DW1)
* - Notify Enable ([8] of DW1)"
*
* The cache flushes require the workaround flush that triggered this
* one, so we can't use it. Depth stall would trigger the same.
* Post-sync nonzero is what triggered this second workaround, so we
* can't use that one either. Notify enable is IRQs, which aren't
* really our business. That leaves only stall at scoreboard.
*/
static int
intel_emit_post_sync_nonzero_flush(struct intel_ring_buffer *ring)
{
struct pipe_control *pc = ring->private;
u32 scratch_addr = pc->gtt_offset + 128;
int ret;
ret = intel_ring_begin(ring, 6);
if (ret)
return ret;
intel_ring_emit(ring, GFX_OP_PIPE_CONTROL(5));
intel_ring_emit(ring, PIPE_CONTROL_CS_STALL |
PIPE_CONTROL_STALL_AT_SCOREBOARD);
intel_ring_emit(ring, scratch_addr | PIPE_CONTROL_GLOBAL_GTT); /* address */
intel_ring_emit(ring, 0); /* low dword */
intel_ring_emit(ring, 0); /* high dword */
intel_ring_emit(ring, MI_NOOP);
intel_ring_advance(ring);
ret = intel_ring_begin(ring, 6);
if (ret)
return ret;
intel_ring_emit(ring, GFX_OP_PIPE_CONTROL(5));
intel_ring_emit(ring, PIPE_CONTROL_QW_WRITE);
intel_ring_emit(ring, scratch_addr | PIPE_CONTROL_GLOBAL_GTT); /* address */
intel_ring_emit(ring, 0);
intel_ring_emit(ring, 0);
intel_ring_emit(ring, MI_NOOP);
intel_ring_advance(ring);
return 0;
}
static int
gen6_render_ring_flush(struct intel_ring_buffer *ring,
u32 invalidate_domains, u32 flush_domains)
{
u32 flags = 0;
struct pipe_control *pc = ring->private;
u32 scratch_addr = pc->gtt_offset + 128;
int ret;
/* Force SNB workarounds for PIPE_CONTROL flushes */
ret = intel_emit_post_sync_nonzero_flush(ring);
if (ret)
return ret;
/* Just flush everything. Experiments have shown that reducing the
* number of bits based on the write domains has little performance
* impact.
*/
if (flush_domains) {
flags |= PIPE_CONTROL_RENDER_TARGET_CACHE_FLUSH;
flags |= PIPE_CONTROL_DEPTH_CACHE_FLUSH;
/*
* Ensure that any following seqno writes only happen
* when the render cache is indeed flushed.
*/
flags |= PIPE_CONTROL_CS_STALL;
}
if (invalidate_domains) {
flags |= PIPE_CONTROL_TLB_INVALIDATE;
flags |= PIPE_CONTROL_INSTRUCTION_CACHE_INVALIDATE;
flags |= PIPE_CONTROL_TEXTURE_CACHE_INVALIDATE;
flags |= PIPE_CONTROL_VF_CACHE_INVALIDATE;
flags |= PIPE_CONTROL_CONST_CACHE_INVALIDATE;
flags |= PIPE_CONTROL_STATE_CACHE_INVALIDATE;
/*
* TLB invalidate requires a post-sync write.
*/
flags |= PIPE_CONTROL_QW_WRITE | PIPE_CONTROL_CS_STALL;
}
ret = intel_ring_begin(ring, 4);
if (ret)
return ret;
intel_ring_emit(ring, GFX_OP_PIPE_CONTROL(4));
intel_ring_emit(ring, flags);
intel_ring_emit(ring, scratch_addr | PIPE_CONTROL_GLOBAL_GTT);
intel_ring_emit(ring, 0);
intel_ring_advance(ring);
return 0;
}
static int
gen7_render_ring_cs_stall_wa(struct intel_ring_buffer *ring)
{
int ret;
ret = intel_ring_begin(ring, 4);
if (ret)
return ret;
intel_ring_emit(ring, GFX_OP_PIPE_CONTROL(4));
intel_ring_emit(ring, PIPE_CONTROL_CS_STALL |
PIPE_CONTROL_STALL_AT_SCOREBOARD);
intel_ring_emit(ring, 0);
intel_ring_emit(ring, 0);
intel_ring_advance(ring);
return 0;
}
static int
gen7_render_ring_flush(struct intel_ring_buffer *ring,
u32 invalidate_domains, u32 flush_domains)
{
u32 flags = 0;
struct pipe_control *pc = ring->private;
u32 scratch_addr = pc->gtt_offset + 128;
int ret;
/*
* Ensure that any following seqno writes only happen when the render
* cache is indeed flushed.
*
* Workaround: 4th PIPE_CONTROL command (except the ones with only
* read-cache invalidate bits set) must have the CS_STALL bit set. We
* don't try to be clever and just set it unconditionally.
*/
flags |= PIPE_CONTROL_CS_STALL;
/* Just flush everything. Experiments have shown that reducing the
* number of bits based on the write domains has little performance
* impact.
*/
if (flush_domains) {
flags |= PIPE_CONTROL_RENDER_TARGET_CACHE_FLUSH;
flags |= PIPE_CONTROL_DEPTH_CACHE_FLUSH;
}
if (invalidate_domains) {
flags |= PIPE_CONTROL_TLB_INVALIDATE;
flags |= PIPE_CONTROL_INSTRUCTION_CACHE_INVALIDATE;
flags |= PIPE_CONTROL_TEXTURE_CACHE_INVALIDATE;
flags |= PIPE_CONTROL_VF_CACHE_INVALIDATE;
flags |= PIPE_CONTROL_CONST_CACHE_INVALIDATE;
flags |= PIPE_CONTROL_STATE_CACHE_INVALIDATE;
flags |= PIPE_CONTROL_MEDIA_STATE_CLEAR;
/*
* TLB invalidate requires a post-sync write.
*/
flags |= PIPE_CONTROL_QW_WRITE;
flags |= PIPE_CONTROL_GLOBAL_GTT_IVB;
flags |= PIPE_CONTROL_STALL_AT_SCOREBOARD;
/* Workaround: we must issue a pipe_control with CS-stall bit
* set before a pipe_control command that has the state cache
* invalidate bit set. */
gen7_render_ring_cs_stall_wa(ring);
}
ret = intel_ring_begin(ring, 4);
if (ret)
return ret;
intel_ring_emit(ring, GFX_OP_PIPE_CONTROL(4));
intel_ring_emit(ring, flags);
intel_ring_emit(ring, scratch_addr);
intel_ring_emit(ring, 0);
intel_ring_advance(ring);
return 0;
}
static void ring_write_tail(struct intel_ring_buffer *ring,
u32 value)
{
drm_i915_private_t *dev_priv = ring->dev->dev_private;
I915_WRITE_TAIL(ring, value);
}
u32 intel_ring_get_active_head(struct intel_ring_buffer *ring)
{
drm_i915_private_t *dev_priv = ring->dev->dev_private;
u32 acthd_reg = INTEL_INFO(ring->dev)->gen >= 4 ?
RING_ACTHD(ring->mmio_base) : ACTHD;
return I915_READ(acthd_reg);
}
static int init_ring_common(struct intel_ring_buffer *ring)
{
struct drm_device *dev = ring->dev;
drm_i915_private_t *dev_priv = dev->dev_private;
struct drm_i915_gem_object *obj = ring->obj;
int ret = 0;
u32 head;
if (HAS_FORCE_WAKE(dev))
gen6_gt_force_wake_get(dev_priv);
/* Stop the ring if it's running. */
I915_WRITE_CTL(ring, 0);
I915_WRITE_HEAD(ring, 0);
ring->write_tail(ring, 0);
head = I915_READ_HEAD(ring) & HEAD_ADDR;
/* G45 ring initialization fails to reset head to zero */
if (head != 0) {
DRM_DEBUG_KMS("%s head not reset to zero "
"ctl %08x head %08x tail %08x start %08x\n",
ring->name,
I915_READ_CTL(ring),
I915_READ_HEAD(ring),
I915_READ_TAIL(ring),
I915_READ_START(ring));
I915_WRITE_HEAD(ring, 0);
if (I915_READ_HEAD(ring) & HEAD_ADDR) {
DRM_ERROR("failed to set %s head to zero "
"ctl %08x head %08x tail %08x start %08x\n",
ring->name,
I915_READ_CTL(ring),
I915_READ_HEAD(ring),
I915_READ_TAIL(ring),
I915_READ_START(ring));
}
}
/* Enforce ordering by reading HEAD register back */
I915_READ_HEAD(ring);
/* Initialize the ring. This must happen _after_ we've cleared the ring
* registers with the above sequence (the readback of the HEAD registers
* also enforces ordering), otherwise the hw might lose the new ring
* register values. */
I915_WRITE_START(ring, obj->gtt_offset);
I915_WRITE_CTL(ring,
((ring->size - PAGE_SIZE) & RING_NR_PAGES)
| RING_VALID);
/* If the head is still not zero, the ring is dead */
if (wait_for((I915_READ_CTL(ring) & RING_VALID) != 0 &&
I915_READ_START(ring) == obj->gtt_offset &&
(I915_READ_HEAD(ring) & HEAD_ADDR) == 0, 50)) {
DRM_ERROR("%s initialization failed "
"ctl %08x head %08x tail %08x start %08x\n",
ring->name,
I915_READ_CTL(ring),
I915_READ_HEAD(ring),
I915_READ_TAIL(ring),
I915_READ_START(ring));
ret = -EIO;
goto out;
}
if (!drm_core_check_feature(ring->dev, DRIVER_MODESET))
i915_kernel_lost_context(ring->dev);
else {
ring->head = I915_READ_HEAD(ring);
ring->tail = I915_READ_TAIL(ring) & TAIL_ADDR;
ring->space = ring_space(ring);
ring->last_retired_head = -1;
}
out:
if (HAS_FORCE_WAKE(dev))
gen6_gt_force_wake_put(dev_priv);
return ret;
}
static int
init_pipe_control(struct intel_ring_buffer *ring)
{
struct pipe_control *pc;
struct drm_i915_gem_object *obj;
int ret;
if (ring->private)
return 0;
pc = kmalloc(sizeof(*pc), GFP_KERNEL);
if (!pc)
return -ENOMEM;
obj = i915_gem_alloc_object(ring->dev, 4096);
if (obj == NULL) {
DRM_ERROR("Failed to allocate seqno page\n");
ret = -ENOMEM;
goto err;
}
i915_gem_object_set_cache_level(obj, I915_CACHE_LLC);
ret = i915_gem_object_pin(obj, 4096, true, false);
if (ret)
goto err_unref;
pc->gtt_offset = obj->gtt_offset;
pc->cpu_page = kmap(sg_page(obj->pages->sgl));
if (pc->cpu_page == NULL)
goto err_unpin;
DRM_DEBUG_DRIVER("%s pipe control offset: 0x%08x\n",
ring->name, pc->gtt_offset);
pc->obj = obj;
ring->private = pc;
return 0;
err_unpin:
i915_gem_object_unpin(obj);
err_unref:
drm_gem_object_unreference(&obj->base);
err:
kfree(pc);
return ret;
}
static void
cleanup_pipe_control(struct intel_ring_buffer *ring)
{
struct pipe_control *pc = ring->private;
struct drm_i915_gem_object *obj;
obj = pc->obj;
kunmap(sg_page(obj->pages->sgl));
i915_gem_object_unpin(obj);
drm_gem_object_unreference(&obj->base);
kfree(pc);
}
static int init_render_ring(struct intel_ring_buffer *ring)
{
struct drm_device *dev = ring->dev;
struct drm_i915_private *dev_priv = dev->dev_private;
int ret = init_ring_common(ring);
if (INTEL_INFO(dev)->gen > 3)
I915_WRITE(MI_MODE, _MASKED_BIT_ENABLE(VS_TIMER_DISPATCH));
/* We need to disable the AsyncFlip performance optimisations in order
* to use MI_WAIT_FOR_EVENT within the CS. It should already be
* programmed to '1' on all products.
*/
if (INTEL_INFO(dev)->gen >= 6)
I915_WRITE(MI_MODE, _MASKED_BIT_ENABLE(ASYNC_FLIP_PERF_DISABLE));
/* Required for the hardware to program scanline values for waiting */
if (INTEL_INFO(dev)->gen == 6)
I915_WRITE(GFX_MODE,
_MASKED_BIT_ENABLE(GFX_TLB_INVALIDATE_ALWAYS));
if (IS_GEN7(dev))
I915_WRITE(GFX_MODE_GEN7,
_MASKED_BIT_DISABLE(GFX_TLB_INVALIDATE_ALWAYS) |
_MASKED_BIT_ENABLE(GFX_REPLAY_MODE));
if (INTEL_INFO(dev)->gen >= 5) {
ret = init_pipe_control(ring);
if (ret)
return ret;
}
if (IS_GEN6(dev)) {
/* From the Sandybridge PRM, volume 1 part 3, page 24:
* "If this bit is set, STCunit will have LRA as replacement
* policy. [...] This bit must be reset. LRA replacement
* policy is not supported."
*/
I915_WRITE(CACHE_MODE_0,
_MASKED_BIT_DISABLE(CM0_STC_EVICT_DISABLE_LRA_SNB));
/* This is not explicitly set for GEN6, so read the register.
* see intel_ring_mi_set_context() for why we care.
* TODO: consider explicitly setting the bit for GEN5
*/
ring->itlb_before_ctx_switch =
!!(I915_READ(GFX_MODE) & GFX_TLB_INVALIDATE_ALWAYS);
}
if (INTEL_INFO(dev)->gen >= 6)
I915_WRITE(INSTPM, _MASKED_BIT_ENABLE(INSTPM_FORCE_ORDERING));
if (HAS_L3_GPU_CACHE(dev))
I915_WRITE_IMR(ring, ~GEN6_RENDER_L3_PARITY_ERROR);
return ret;
}
static void render_ring_cleanup(struct intel_ring_buffer *ring)
{
struct drm_device *dev = ring->dev;
if (!ring->private)
return;
if (HAS_BROKEN_CS_TLB(dev))
drm_gem_object_unreference(to_gem_object(ring->private));
if (INTEL_INFO(dev)->gen >= 5)
cleanup_pipe_control(ring);
ring->private = NULL;
}
static void
update_mboxes(struct intel_ring_buffer *ring,
u32 mmio_offset)
{
intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
intel_ring_emit(ring, mmio_offset);
intel_ring_emit(ring, ring->outstanding_lazy_request);
}
/**
* gen6_add_request - Update the semaphore mailbox registers
*
* @ring - ring that is adding a request
* @seqno - return seqno stuck into the ring
*
* Update the mailbox registers in the *other* rings with the current seqno.
* This acts like a signal in the canonical semaphore.
*/
static int
gen6_add_request(struct intel_ring_buffer *ring)
{
u32 mbox1_reg;
u32 mbox2_reg;
int ret;
ret = intel_ring_begin(ring, 10);
if (ret)
return ret;
mbox1_reg = ring->signal_mbox[0];
mbox2_reg = ring->signal_mbox[1];
update_mboxes(ring, mbox1_reg);
update_mboxes(ring, mbox2_reg);
intel_ring_emit(ring, MI_STORE_DWORD_INDEX);
intel_ring_emit(ring, I915_GEM_HWS_INDEX << MI_STORE_DWORD_INDEX_SHIFT);
intel_ring_emit(ring, ring->outstanding_lazy_request);
intel_ring_emit(ring, MI_USER_INTERRUPT);
intel_ring_advance(ring);
return 0;
}
static inline bool i915_gem_has_seqno_wrapped(struct drm_device *dev,
u32 seqno)
{
struct drm_i915_private *dev_priv = dev->dev_private;
return dev_priv->last_seqno < seqno;
}
/**
* intel_ring_sync - sync the waiter to the signaller on seqno
*
* @waiter - ring that is waiting
* @signaller - ring which has, or will signal
* @seqno - seqno which the waiter will block on
*/
static int
gen6_ring_sync(struct intel_ring_buffer *waiter,
struct intel_ring_buffer *signaller,
u32 seqno)
{
int ret;
u32 dw1 = MI_SEMAPHORE_MBOX |
MI_SEMAPHORE_COMPARE |
MI_SEMAPHORE_REGISTER;
/* Throughout all of the GEM code, seqno passed implies our current
* seqno is >= the last seqno executed. However for hardware the
* comparison is strictly greater than.
*/
seqno -= 1;
WARN_ON(signaller->semaphore_register[waiter->id] ==
MI_SEMAPHORE_SYNC_INVALID);
ret = intel_ring_begin(waiter, 4);
if (ret)
return ret;
/* If seqno wrap happened, omit the wait with no-ops */
if (likely(!i915_gem_has_seqno_wrapped(waiter->dev, seqno))) {
intel_ring_emit(waiter,
dw1 |
signaller->semaphore_register[waiter->id]);
intel_ring_emit(waiter, seqno);
intel_ring_emit(waiter, 0);
intel_ring_emit(waiter, MI_NOOP);
} else {
intel_ring_emit(waiter, MI_NOOP);
intel_ring_emit(waiter, MI_NOOP);
intel_ring_emit(waiter, MI_NOOP);
intel_ring_emit(waiter, MI_NOOP);
}
intel_ring_advance(waiter);
return 0;
}
#define PIPE_CONTROL_FLUSH(ring__, addr__) \
do { \
intel_ring_emit(ring__, GFX_OP_PIPE_CONTROL(4) | PIPE_CONTROL_QW_WRITE | \
PIPE_CONTROL_DEPTH_STALL); \
intel_ring_emit(ring__, (addr__) | PIPE_CONTROL_GLOBAL_GTT); \
intel_ring_emit(ring__, 0); \
intel_ring_emit(ring__, 0); \
} while (0)
static int
pc_render_add_request(struct intel_ring_buffer *ring)
{
struct pipe_control *pc = ring->private;
u32 scratch_addr = pc->gtt_offset + 128;
int ret;
/* For Ironlake, MI_USER_INTERRUPT was deprecated and apparently
* incoherent with writes to memory, i.e. completely fubar,
* so we need to use PIPE_NOTIFY instead.
*
* However, we also need to workaround the qword write
* incoherence by flushing the 6 PIPE_NOTIFY buffers out to
* memory before requesting an interrupt.
*/
ret = intel_ring_begin(ring, 32);
if (ret)
return ret;
intel_ring_emit(ring, GFX_OP_PIPE_CONTROL(4) | PIPE_CONTROL_QW_WRITE |
PIPE_CONTROL_WRITE_FLUSH |
PIPE_CONTROL_TEXTURE_CACHE_INVALIDATE);
intel_ring_emit(ring, pc->gtt_offset | PIPE_CONTROL_GLOBAL_GTT);
intel_ring_emit(ring, ring->outstanding_lazy_request);
intel_ring_emit(ring, 0);
PIPE_CONTROL_FLUSH(ring, scratch_addr);
scratch_addr += 128; /* write to separate cachelines */
PIPE_CONTROL_FLUSH(ring, scratch_addr);
scratch_addr += 128;
PIPE_CONTROL_FLUSH(ring, scratch_addr);
scratch_addr += 128;
PIPE_CONTROL_FLUSH(ring, scratch_addr);
scratch_addr += 128;
PIPE_CONTROL_FLUSH(ring, scratch_addr);
scratch_addr += 128;
PIPE_CONTROL_FLUSH(ring, scratch_addr);
intel_ring_emit(ring, GFX_OP_PIPE_CONTROL(4) | PIPE_CONTROL_QW_WRITE |
PIPE_CONTROL_WRITE_FLUSH |
PIPE_CONTROL_TEXTURE_CACHE_INVALIDATE |
PIPE_CONTROL_NOTIFY);
intel_ring_emit(ring, pc->gtt_offset | PIPE_CONTROL_GLOBAL_GTT);
intel_ring_emit(ring, ring->outstanding_lazy_request);
intel_ring_emit(ring, 0);
intel_ring_advance(ring);
return 0;
}
static u32
gen6_ring_get_seqno(struct intel_ring_buffer *ring, bool lazy_coherency)
{
/* Workaround to force correct ordering between irq and seqno writes on
* ivb (and maybe also on snb) by reading from a CS register (like
* ACTHD) before reading the status page. */
if (!lazy_coherency)
intel_ring_get_active_head(ring);
return intel_read_status_page(ring, I915_GEM_HWS_INDEX);
}
static u32
ring_get_seqno(struct intel_ring_buffer *ring, bool lazy_coherency)
{
return intel_read_status_page(ring, I915_GEM_HWS_INDEX);
}
static void
ring_set_seqno(struct intel_ring_buffer *ring, u32 seqno)
{
intel_write_status_page(ring, I915_GEM_HWS_INDEX, seqno);
}
static u32
pc_render_get_seqno(struct intel_ring_buffer *ring, bool lazy_coherency)
{
struct pipe_control *pc = ring->private;
return pc->cpu_page[0];
}
static void
pc_render_set_seqno(struct intel_ring_buffer *ring, u32 seqno)
{
struct pipe_control *pc = ring->private;
pc->cpu_page[0] = seqno;
}
static bool
gen5_ring_get_irq(struct intel_ring_buffer *ring)
{
struct drm_device *dev = ring->dev;
drm_i915_private_t *dev_priv = dev->dev_private;
unsigned long flags;
if (!dev->irq_enabled)
return false;
spin_lock_irqsave(&dev_priv->irq_lock, flags);
if (ring->irq_refcount++ == 0) {
dev_priv->gt_irq_mask &= ~ring->irq_enable_mask;
I915_WRITE(GTIMR, dev_priv->gt_irq_mask);
POSTING_READ(GTIMR);
}
spin_unlock_irqrestore(&dev_priv->irq_lock, flags);
return true;
}
static void
gen5_ring_put_irq(struct intel_ring_buffer *ring)
{
struct drm_device *dev = ring->dev;
drm_i915_private_t *dev_priv = dev->dev_private;
unsigned long flags;
spin_lock_irqsave(&dev_priv->irq_lock, flags);
if (--ring->irq_refcount == 0) {
dev_priv->gt_irq_mask |= ring->irq_enable_mask;
I915_WRITE(GTIMR, dev_priv->gt_irq_mask);
POSTING_READ(GTIMR);
}
spin_unlock_irqrestore(&dev_priv->irq_lock, flags);
}
static bool
i9xx_ring_get_irq(struct intel_ring_buffer *ring)
{
struct drm_device *dev = ring->dev;
drm_i915_private_t *dev_priv = dev->dev_private;
unsigned long flags;
if (!dev->irq_enabled)
return false;
spin_lock_irqsave(&dev_priv->irq_lock, flags);
if (ring->irq_refcount++ == 0) {
dev_priv->irq_mask &= ~ring->irq_enable_mask;
I915_WRITE(IMR, dev_priv->irq_mask);
POSTING_READ(IMR);
}
spin_unlock_irqrestore(&dev_priv->irq_lock, flags);
return true;
}
static void
i9xx_ring_put_irq(struct intel_ring_buffer *ring)
{
struct drm_device *dev = ring->dev;
drm_i915_private_t *dev_priv = dev->dev_private;
unsigned long flags;
spin_lock_irqsave(&dev_priv->irq_lock, flags);
if (--ring->irq_refcount == 0) {
dev_priv->irq_mask |= ring->irq_enable_mask;
I915_WRITE(IMR, dev_priv->irq_mask);
POSTING_READ(IMR);
}
spin_unlock_irqrestore(&dev_priv->irq_lock, flags);
}
static bool
i8xx_ring_get_irq(struct intel_ring_buffer *ring)
{
struct drm_device *dev = ring->dev;
drm_i915_private_t *dev_priv = dev->dev_private;
unsigned long flags;
if (!dev->irq_enabled)
return false;
spin_lock_irqsave(&dev_priv->irq_lock, flags);
if (ring->irq_refcount++ == 0) {
dev_priv->irq_mask &= ~ring->irq_enable_mask;
I915_WRITE16(IMR, dev_priv->irq_mask);
POSTING_READ16(IMR);
}
spin_unlock_irqrestore(&dev_priv->irq_lock, flags);
return true;
}
static void
i8xx_ring_put_irq(struct intel_ring_buffer *ring)
{
struct drm_device *dev = ring->dev;
drm_i915_private_t *dev_priv = dev->dev_private;
unsigned long flags;
spin_lock_irqsave(&dev_priv->irq_lock, flags);
if (--ring->irq_refcount == 0) {
dev_priv->irq_mask |= ring->irq_enable_mask;
I915_WRITE16(IMR, dev_priv->irq_mask);
POSTING_READ16(IMR);
}
spin_unlock_irqrestore(&dev_priv->irq_lock, flags);
}
void intel_ring_setup_status_page(struct intel_ring_buffer *ring)
{
struct drm_device *dev = ring->dev;
drm_i915_private_t *dev_priv = ring->dev->dev_private;
u32 mmio = 0;
/* The ring status page addresses are no longer next to the rest of
* the ring registers as of gen7.
*/
if (IS_GEN7(dev)) {
switch (ring->id) {
case RCS:
mmio = RENDER_HWS_PGA_GEN7;
break;
case BCS:
mmio = BLT_HWS_PGA_GEN7;
break;
case VCS:
mmio = BSD_HWS_PGA_GEN7;
break;
}
} else if (IS_GEN6(ring->dev)) {
mmio = RING_HWS_PGA_GEN6(ring->mmio_base);
} else {
mmio = RING_HWS_PGA(ring->mmio_base);
}
I915_WRITE(mmio, (u32)ring->status_page.gfx_addr);
POSTING_READ(mmio);
/* Flush the TLB for this page */
if (INTEL_INFO(dev)->gen >= 6) {
u32 reg = RING_INSTPM(ring->mmio_base);
I915_WRITE(reg,
_MASKED_BIT_ENABLE(INSTPM_TLB_INVALIDATE |
INSTPM_SYNC_FLUSH));
if (wait_for((I915_READ(reg) & INSTPM_SYNC_FLUSH) == 0,
1000))
DRM_ERROR("%s: wait for SyncFlush to complete for TLB invalidation timed out\n",
ring->name);
}
}
static int
bsd_ring_flush(struct intel_ring_buffer *ring,
u32 invalidate_domains,
u32 flush_domains)
{
int ret;
ret = intel_ring_begin(ring, 2);
if (ret)
return ret;
intel_ring_emit(ring, MI_FLUSH);
intel_ring_emit(ring, MI_NOOP);
intel_ring_advance(ring);
return 0;
}
static int
i9xx_add_request(struct intel_ring_buffer *ring)
{
int ret;
ret = intel_ring_begin(ring, 4);
if (ret)
return ret;
intel_ring_emit(ring, MI_STORE_DWORD_INDEX);
intel_ring_emit(ring, I915_GEM_HWS_INDEX << MI_STORE_DWORD_INDEX_SHIFT);
intel_ring_emit(ring, ring->outstanding_lazy_request);
intel_ring_emit(ring, MI_USER_INTERRUPT);
intel_ring_advance(ring);
return 0;
}
static bool
gen6_ring_get_irq(struct intel_ring_buffer *ring)
{
struct drm_device *dev = ring->dev;
drm_i915_private_t *dev_priv = dev->dev_private;
unsigned long flags;
if (!dev->irq_enabled)
return false;
/* It looks like we need to prevent the gt from suspending while waiting
* for an notifiy irq, otherwise irqs seem to get lost on at least the
* blt/bsd rings on ivb. */
gen6_gt_force_wake_get(dev_priv);
spin_lock_irqsave(&dev_priv->irq_lock, flags);
if (ring->irq_refcount++ == 0) {
if (HAS_L3_GPU_CACHE(dev) && ring->id == RCS)
I915_WRITE_IMR(ring, ~(ring->irq_enable_mask |
GEN6_RENDER_L3_PARITY_ERROR));
else
I915_WRITE_IMR(ring, ~ring->irq_enable_mask);
dev_priv->gt_irq_mask &= ~ring->irq_enable_mask;
I915_WRITE(GTIMR, dev_priv->gt_irq_mask);
POSTING_READ(GTIMR);
}
spin_unlock_irqrestore(&dev_priv->irq_lock, flags);
return true;
}
static void
gen6_ring_put_irq(struct intel_ring_buffer *ring)
{
struct drm_device *dev = ring->dev;
drm_i915_private_t *dev_priv = dev->dev_private;
unsigned long flags;
spin_lock_irqsave(&dev_priv->irq_lock, flags);
if (--ring->irq_refcount == 0) {
if (HAS_L3_GPU_CACHE(dev) && ring->id == RCS)
I915_WRITE_IMR(ring, ~GEN6_RENDER_L3_PARITY_ERROR);
else
I915_WRITE_IMR(ring, ~0);
dev_priv->gt_irq_mask |= ring->irq_enable_mask;
I915_WRITE(GTIMR, dev_priv->gt_irq_mask);
POSTING_READ(GTIMR);
}
spin_unlock_irqrestore(&dev_priv->irq_lock, flags);
gen6_gt_force_wake_put(dev_priv);
}
static int
i965_dispatch_execbuffer(struct intel_ring_buffer *ring,
u32 offset, u32 length,
unsigned flags)
{
int ret;
ret = intel_ring_begin(ring, 2);
if (ret)
return ret;
intel_ring_emit(ring,
MI_BATCH_BUFFER_START |
MI_BATCH_GTT |
(flags & I915_DISPATCH_SECURE ? 0 : MI_BATCH_NON_SECURE_I965));
intel_ring_emit(ring, offset);
intel_ring_advance(ring);
return 0;
}
/* Just userspace ABI convention to limit the wa batch bo to a resonable size */
#define I830_BATCH_LIMIT (256*1024)
static int
i830_dispatch_execbuffer(struct intel_ring_buffer *ring,
u32 offset, u32 len,
unsigned flags)
{
int ret;
if (flags & I915_DISPATCH_PINNED) {
ret = intel_ring_begin(ring, 4);
if (ret)
return ret;
intel_ring_emit(ring, MI_BATCH_BUFFER);
intel_ring_emit(ring, offset | (flags & I915_DISPATCH_SECURE ? 0 : MI_BATCH_NON_SECURE));
intel_ring_emit(ring, offset + len - 8);
intel_ring_emit(ring, MI_NOOP);
intel_ring_advance(ring);
} else {
struct drm_i915_gem_object *obj = ring->private;
u32 cs_offset = obj->gtt_offset;
if (len > I830_BATCH_LIMIT)
return -ENOSPC;
ret = intel_ring_begin(ring, 9+3);
if (ret)
return ret;
/* Blit the batch (which has now all relocs applied) to the stable batch
* scratch bo area (so that the CS never stumbles over its tlb
* invalidation bug) ... */
intel_ring_emit(ring, XY_SRC_COPY_BLT_CMD |
XY_SRC_COPY_BLT_WRITE_ALPHA |
XY_SRC_COPY_BLT_WRITE_RGB);
intel_ring_emit(ring, BLT_DEPTH_32 | BLT_ROP_GXCOPY | 4096);
intel_ring_emit(ring, 0);
intel_ring_emit(ring, (DIV_ROUND_UP(len, 4096) << 16) | 1024);
intel_ring_emit(ring, cs_offset);
intel_ring_emit(ring, 0);
intel_ring_emit(ring, 4096);
intel_ring_emit(ring, offset);
intel_ring_emit(ring, MI_FLUSH);
/* ... and execute it. */
intel_ring_emit(ring, MI_BATCH_BUFFER);
intel_ring_emit(ring, cs_offset | (flags & I915_DISPATCH_SECURE ? 0 : MI_BATCH_NON_SECURE));
intel_ring_emit(ring, cs_offset + len - 8);
intel_ring_advance(ring);
}
return 0;
}
static int
i915_dispatch_execbuffer(struct intel_ring_buffer *ring,
u32 offset, u32 len,
unsigned flags)
{
int ret;
ret = intel_ring_begin(ring, 2);
if (ret)
return ret;
intel_ring_emit(ring, MI_BATCH_BUFFER_START | MI_BATCH_GTT);
intel_ring_emit(ring, offset | (flags & I915_DISPATCH_SECURE ? 0 : MI_BATCH_NON_SECURE));
intel_ring_advance(ring);
return 0;
}
static void cleanup_status_page(struct intel_ring_buffer *ring)
{
struct drm_i915_gem_object *obj;
obj = ring->status_page.obj;
if (obj == NULL)
return;
kunmap(sg_page(obj->pages->sgl));
i915_gem_object_unpin(obj);
drm_gem_object_unreference(&obj->base);
ring->status_page.obj = NULL;
}
static int init_status_page(struct intel_ring_buffer *ring)
{
struct drm_device *dev = ring->dev;
struct drm_i915_gem_object *obj;
int ret;
obj = i915_gem_alloc_object(dev, 4096);
if (obj == NULL) {
DRM_ERROR("Failed to allocate status page\n");
ret = -ENOMEM;
goto err;
}
i915_gem_object_set_cache_level(obj, I915_CACHE_LLC);
ret = i915_gem_object_pin(obj, 4096, true, false);
if (ret != 0) {
goto err_unref;
}
ring->status_page.gfx_addr = obj->gtt_offset;
ring->status_page.page_addr = kmap(sg_page(obj->pages->sgl));
if (ring->status_page.page_addr == NULL) {
ret = -ENOMEM;
goto err_unpin;
}
ring->status_page.obj = obj;
memset(ring->status_page.page_addr, 0, PAGE_SIZE);
intel_ring_setup_status_page(ring);
DRM_DEBUG_DRIVER("%s hws offset: 0x%08x\n",
ring->name, ring->status_page.gfx_addr);
return 0;
err_unpin:
i915_gem_object_unpin(obj);
err_unref:
drm_gem_object_unreference(&obj->base);
err:
return ret;
}
static int init_phys_hws_pga(struct intel_ring_buffer *ring)
{
struct drm_i915_private *dev_priv = ring->dev->dev_private;
u32 addr;
if (!dev_priv->status_page_dmah) {
dev_priv->status_page_dmah =
drm_pci_alloc(ring->dev, PAGE_SIZE, PAGE_SIZE);
if (!dev_priv->status_page_dmah)
return -ENOMEM;
}
addr = dev_priv->status_page_dmah->busaddr;
if (INTEL_INFO(ring->dev)->gen >= 4)
addr |= (dev_priv->status_page_dmah->busaddr >> 28) & 0xf0;
I915_WRITE(HWS_PGA, addr);
ring->status_page.page_addr = dev_priv->status_page_dmah->vaddr;
memset(ring->status_page.page_addr, 0, PAGE_SIZE);
return 0;
}
static int intel_init_ring_buffer(struct drm_device *dev,
struct intel_ring_buffer *ring)
{
struct drm_i915_gem_object *obj;
struct drm_i915_private *dev_priv = dev->dev_private;
int ret;
ring->dev = dev;
INIT_LIST_HEAD(&ring->active_list);
INIT_LIST_HEAD(&ring->request_list);
ring->size = 32 * PAGE_SIZE;
memset(ring->sync_seqno, 0, sizeof(ring->sync_seqno));
init_waitqueue_head(&ring->irq_queue);
if (I915_NEED_GFX_HWS(dev)) {
ret = init_status_page(ring);
if (ret)
return ret;
} else {
BUG_ON(ring->id != RCS);
ret = init_phys_hws_pga(ring);
if (ret)
return ret;
}
obj = NULL;
if (!HAS_LLC(dev))
obj = i915_gem_object_create_stolen(dev, ring->size);
if (obj == NULL)
obj = i915_gem_alloc_object(dev, ring->size);
if (obj == NULL) {
DRM_ERROR("Failed to allocate ringbuffer\n");
ret = -ENOMEM;
goto err_hws;
}
ring->obj = obj;
ret = i915_gem_object_pin(obj, PAGE_SIZE, true, false);
if (ret)
goto err_unref;
ret = i915_gem_object_set_to_gtt_domain(obj, true);
if (ret)
goto err_unpin;
ring->virtual_start =
ioremap_wc(dev_priv->gtt.mappable_base + obj->gtt_offset,
ring->size);
if (ring->virtual_start == NULL) {
DRM_ERROR("Failed to map ringbuffer.\n");
ret = -EINVAL;
goto err_unpin;
}
ret = ring->init(ring);
if (ret)
goto err_unmap;
/* Workaround an erratum on the i830 which causes a hang if
* the TAIL pointer points to within the last 2 cachelines
* of the buffer.
*/
ring->effective_size = ring->size;
if (IS_I830(ring->dev) || IS_845G(ring->dev))
ring->effective_size -= 128;
return 0;
err_unmap:
iounmap(ring->virtual_start);
err_unpin:
i915_gem_object_unpin(obj);
err_unref:
drm_gem_object_unreference(&obj->base);
ring->obj = NULL;
err_hws:
cleanup_status_page(ring);
return ret;
}
void intel_cleanup_ring_buffer(struct intel_ring_buffer *ring)
{
struct drm_i915_private *dev_priv;
int ret;
if (ring->obj == NULL)
return;
/* Disable the ring buffer. The ring must be idle at this point */
dev_priv = ring->dev->dev_private;
ret = intel_ring_idle(ring);
if (ret)
DRM_ERROR("failed to quiesce %s whilst cleaning up: %d\n",
ring->name, ret);
I915_WRITE_CTL(ring, 0);
iounmap(ring->virtual_start);
i915_gem_object_unpin(ring->obj);
drm_gem_object_unreference(&ring->obj->base);
ring->obj = NULL;
if (ring->cleanup)
ring->cleanup(ring);
cleanup_status_page(ring);
}
static int intel_ring_wait_seqno(struct intel_ring_buffer *ring, u32 seqno)
{
int ret;
ret = i915_wait_seqno(ring, seqno);
if (!ret)
i915_gem_retire_requests_ring(ring);
return ret;
}
static int intel_ring_wait_request(struct intel_ring_buffer *ring, int n)
{
struct drm_i915_gem_request *request;
u32 seqno = 0;
int ret;
i915_gem_retire_requests_ring(ring);
if (ring->last_retired_head != -1) {
ring->head = ring->last_retired_head;
ring->last_retired_head = -1;
ring->space = ring_space(ring);
if (ring->space >= n)
return 0;
}
list_for_each_entry(request, &ring->request_list, list) {
int space;
if (request->tail == -1)
continue;
space = request->tail - (ring->tail + I915_RING_FREE_SPACE);
if (space < 0)
space += ring->size;
if (space >= n) {
seqno = request->seqno;
break;
}
/* Consume this request in case we need more space than
* is available and so need to prevent a race between
* updating last_retired_head and direct reads of
* I915_RING_HEAD. It also provides a nice sanity check.
*/
request->tail = -1;
}
if (seqno == 0)
return -ENOSPC;
ret = intel_ring_wait_seqno(ring, seqno);
if (ret)
return ret;
if (WARN_ON(ring->last_retired_head == -1))
return -ENOSPC;
ring->head = ring->last_retired_head;
ring->last_retired_head = -1;
ring->space = ring_space(ring);
if (WARN_ON(ring->space < n))
return -ENOSPC;
return 0;
}
static int ring_wait_for_space(struct intel_ring_buffer *ring, int n)
{
struct drm_device *dev = ring->dev;
struct drm_i915_private *dev_priv = dev->dev_private;
unsigned long end;
int ret;
ret = intel_ring_wait_request(ring, n);
if (ret != -ENOSPC)
return ret;
trace_i915_ring_wait_begin(ring);
/* With GEM the hangcheck timer should kick us out of the loop,
* leaving it early runs the risk of corrupting GEM state (due
* to running on almost untested codepaths). But on resume
* timers don't work yet, so prevent a complete hang in that
* case by choosing an insanely large timeout. */
end = jiffies + 60 * HZ;
do {
ring->head = I915_READ_HEAD(ring);
ring->space = ring_space(ring);
if (ring->space >= n) {
trace_i915_ring_wait_end(ring);
return 0;
}
if (dev->primary->master) {
struct drm_i915_master_private *master_priv = dev->primary->master->driver_priv;
if (master_priv->sarea_priv)
master_priv->sarea_priv->perf_boxes |= I915_BOX_WAIT;
}
msleep(1);
ret = i915_gem_check_wedge(&dev_priv->gpu_error,
dev_priv->mm.interruptible);
if (ret)
return ret;
} while (!time_after(jiffies, end));
trace_i915_ring_wait_end(ring);
return -EBUSY;
}
static int intel_wrap_ring_buffer(struct intel_ring_buffer *ring)
{
uint32_t __iomem *virt;
int rem = ring->size - ring->tail;
if (ring->space < rem) {
int ret = ring_wait_for_space(ring, rem);
if (ret)
return ret;
}
virt = ring->virtual_start + ring->tail;
rem /= 4;
while (rem--)
iowrite32(MI_NOOP, virt++);
ring->tail = 0;
ring->space = ring_space(ring);
return 0;
}
int intel_ring_idle(struct intel_ring_buffer *ring)
{
u32 seqno;
int ret;
/* We need to add any requests required to flush the objects and ring */
if (ring->outstanding_lazy_request) {
ret = i915_add_request(ring, NULL, NULL);
if (ret)
return ret;
}
/* Wait upon the last request to be completed */
if (list_empty(&ring->request_list))
return 0;
seqno = list_entry(ring->request_list.prev,
struct drm_i915_gem_request,
list)->seqno;
return i915_wait_seqno(ring, seqno);
}
static int
intel_ring_alloc_seqno(struct intel_ring_buffer *ring)
{
if (ring->outstanding_lazy_request)
return 0;
return i915_gem_get_seqno(ring->dev, &ring->outstanding_lazy_request);
}
static int __intel_ring_prepare(struct intel_ring_buffer *ring,
int bytes)
{
int ret;
if (unlikely(ring->tail + bytes > ring->effective_size)) {
ret = intel_wrap_ring_buffer(ring);
if (unlikely(ret))
return ret;
}
if (unlikely(ring->space < bytes)) {
ret = ring_wait_for_space(ring, bytes);
if (unlikely(ret))
return ret;
}
return 0;
}
int intel_ring_begin(struct intel_ring_buffer *ring,
int num_dwords)
{
drm_i915_private_t *dev_priv = ring->dev->dev_private;
int ret;
ret = i915_gem_check_wedge(&dev_priv->gpu_error,
dev_priv->mm.interruptible);
if (ret)
return ret;
ret = __intel_ring_prepare(ring, num_dwords * sizeof(uint32_t));
if (ret)
return ret;
/* Preallocate the olr before touching the ring */
ret = intel_ring_alloc_seqno(ring);
if (ret)
return ret;
ring->space -= num_dwords * sizeof(uint32_t);
return 0;
}
void intel_ring_init_seqno(struct intel_ring_buffer *ring, u32 seqno)
{
struct drm_i915_private *dev_priv = ring->dev->dev_private;
BUG_ON(ring->outstanding_lazy_request);
if (INTEL_INFO(ring->dev)->gen >= 6) {
I915_WRITE(RING_SYNC_0(ring->mmio_base), 0);
I915_WRITE(RING_SYNC_1(ring->mmio_base), 0);
}
ring->set_seqno(ring, seqno);
}
void intel_ring_advance(struct intel_ring_buffer *ring)
{
struct drm_i915_private *dev_priv = ring->dev->dev_private;
ring->tail &= ring->size - 1;
if (dev_priv->gpu_error.stop_rings & intel_ring_flag(ring))
return;
ring->write_tail(ring, ring->tail);
}
static void gen6_bsd_ring_write_tail(struct intel_ring_buffer *ring,
u32 value)
{
drm_i915_private_t *dev_priv = ring->dev->dev_private;
/* Every tail move must follow the sequence below */
/* Disable notification that the ring is IDLE. The GT
* will then assume that it is busy and bring it out of rc6.
*/
I915_WRITE(GEN6_BSD_SLEEP_PSMI_CONTROL,
_MASKED_BIT_ENABLE(GEN6_BSD_SLEEP_MSG_DISABLE));
/* Clear the context id. Here be magic! */
I915_WRITE64(GEN6_BSD_RNCID, 0x0);
/* Wait for the ring not to be idle, i.e. for it to wake up. */
if (wait_for((I915_READ(GEN6_BSD_SLEEP_PSMI_CONTROL) &
GEN6_BSD_SLEEP_INDICATOR) == 0,
50))
DRM_ERROR("timed out waiting for the BSD ring to wake up\n");
/* Now that the ring is fully powered up, update the tail */
I915_WRITE_TAIL(ring, value);
POSTING_READ(RING_TAIL(ring->mmio_base));
/* Let the ring send IDLE messages to the GT again,
* and so let it sleep to conserve power when idle.
*/
I915_WRITE(GEN6_BSD_SLEEP_PSMI_CONTROL,
_MASKED_BIT_DISABLE(GEN6_BSD_SLEEP_MSG_DISABLE));
}
static int gen6_ring_flush(struct intel_ring_buffer *ring,
u32 invalidate, u32 flush)
{
uint32_t cmd;
int ret;
ret = intel_ring_begin(ring, 4);
if (ret)
return ret;
cmd = MI_FLUSH_DW;
/*
* Bspec vol 1c.5 - video engine command streamer:
* "If ENABLED, all TLBs will be invalidated once the flush
* operation is complete. This bit is only valid when the
* Post-Sync Operation field is a value of 1h or 3h."
*/
if (invalidate & I915_GEM_GPU_DOMAINS)
cmd |= MI_INVALIDATE_TLB | MI_INVALIDATE_BSD |
MI_FLUSH_DW_STORE_INDEX | MI_FLUSH_DW_OP_STOREDW;
intel_ring_emit(ring, cmd);
intel_ring_emit(ring, I915_GEM_HWS_SCRATCH_ADDR | MI_FLUSH_DW_USE_GTT);
intel_ring_emit(ring, 0);
intel_ring_emit(ring, MI_NOOP);
intel_ring_advance(ring);
return 0;
}
static int
hsw_ring_dispatch_execbuffer(struct intel_ring_buffer *ring,
u32 offset, u32 len,
unsigned flags)
{
int ret;
ret = intel_ring_begin(ring, 2);
if (ret)
return ret;
intel_ring_emit(ring,
MI_BATCH_BUFFER_START | MI_BATCH_PPGTT_HSW |
(flags & I915_DISPATCH_SECURE ? 0 : MI_BATCH_NON_SECURE_HSW));
/* bit0-7 is the length on GEN6+ */
intel_ring_emit(ring, offset);
intel_ring_advance(ring);
return 0;
}
static int
gen6_ring_dispatch_execbuffer(struct intel_ring_buffer *ring,
u32 offset, u32 len,
unsigned flags)
{
int ret;
ret = intel_ring_begin(ring, 2);
if (ret)
return ret;
intel_ring_emit(ring,
MI_BATCH_BUFFER_START |
(flags & I915_DISPATCH_SECURE ? 0 : MI_BATCH_NON_SECURE_I965));
/* bit0-7 is the length on GEN6+ */
intel_ring_emit(ring, offset);
intel_ring_advance(ring);
return 0;
}
/* Blitter support (SandyBridge+) */
static int blt_ring_flush(struct intel_ring_buffer *ring,
u32 invalidate, u32 flush)
{
uint32_t cmd;
int ret;
ret = intel_ring_begin(ring, 4);
if (ret)
return ret;
cmd = MI_FLUSH_DW;
/*
* Bspec vol 1c.3 - blitter engine command streamer:
* "If ENABLED, all TLBs will be invalidated once the flush
* operation is complete. This bit is only valid when the
* Post-Sync Operation field is a value of 1h or 3h."
*/
if (invalidate & I915_GEM_DOMAIN_RENDER)
cmd |= MI_INVALIDATE_TLB | MI_FLUSH_DW_STORE_INDEX |
MI_FLUSH_DW_OP_STOREDW;
intel_ring_emit(ring, cmd);
intel_ring_emit(ring, I915_GEM_HWS_SCRATCH_ADDR | MI_FLUSH_DW_USE_GTT);
intel_ring_emit(ring, 0);
intel_ring_emit(ring, MI_NOOP);
intel_ring_advance(ring);
return 0;
}
int intel_init_render_ring_buffer(struct drm_device *dev)
{
drm_i915_private_t *dev_priv = dev->dev_private;
struct intel_ring_buffer *ring = &dev_priv->ring[RCS];
ring->name = "render ring";
ring->id = RCS;
ring->mmio_base = RENDER_RING_BASE;
if (INTEL_INFO(dev)->gen >= 6) {
ring->add_request = gen6_add_request;
ring->flush = gen7_render_ring_flush;
if (INTEL_INFO(dev)->gen == 6)
ring->flush = gen6_render_ring_flush;
ring->irq_get = gen6_ring_get_irq;
ring->irq_put = gen6_ring_put_irq;
ring->irq_enable_mask = GT_USER_INTERRUPT;
ring->get_seqno = gen6_ring_get_seqno;
ring->set_seqno = ring_set_seqno;
ring->sync_to = gen6_ring_sync;
ring->semaphore_register[0] = MI_SEMAPHORE_SYNC_INVALID;
ring->semaphore_register[1] = MI_SEMAPHORE_SYNC_RV;
ring->semaphore_register[2] = MI_SEMAPHORE_SYNC_RB;
ring->signal_mbox[0] = GEN6_VRSYNC;
ring->signal_mbox[1] = GEN6_BRSYNC;
} else if (IS_GEN5(dev)) {
ring->add_request = pc_render_add_request;
ring->flush = gen4_render_ring_flush;
ring->get_seqno = pc_render_get_seqno;
ring->set_seqno = pc_render_set_seqno;
ring->irq_get = gen5_ring_get_irq;
ring->irq_put = gen5_ring_put_irq;
ring->irq_enable_mask = GT_USER_INTERRUPT | GT_PIPE_NOTIFY;
} else {
ring->add_request = i9xx_add_request;
if (INTEL_INFO(dev)->gen < 4)
ring->flush = gen2_render_ring_flush;
else
ring->flush = gen4_render_ring_flush;
ring->get_seqno = ring_get_seqno;
ring->set_seqno = ring_set_seqno;
if (IS_GEN2(dev)) {
ring->irq_get = i8xx_ring_get_irq;
ring->irq_put = i8xx_ring_put_irq;
} else {
ring->irq_get = i9xx_ring_get_irq;
ring->irq_put = i9xx_ring_put_irq;
}
ring->irq_enable_mask = I915_USER_INTERRUPT;
}
ring->write_tail = ring_write_tail;
if (IS_HASWELL(dev))
ring->dispatch_execbuffer = hsw_ring_dispatch_execbuffer;
else if (INTEL_INFO(dev)->gen >= 6)
ring->dispatch_execbuffer = gen6_ring_dispatch_execbuffer;
else if (INTEL_INFO(dev)->gen >= 4)
ring->dispatch_execbuffer = i965_dispatch_execbuffer;
else if (IS_I830(dev) || IS_845G(dev))
ring->dispatch_execbuffer = i830_dispatch_execbuffer;
else
ring->dispatch_execbuffer = i915_dispatch_execbuffer;
ring->init = init_render_ring;
ring->cleanup = render_ring_cleanup;
/* Workaround batchbuffer to combat CS tlb bug. */
if (HAS_BROKEN_CS_TLB(dev)) {
struct drm_i915_gem_object *obj;
int ret;
obj = i915_gem_alloc_object(dev, I830_BATCH_LIMIT);
if (obj == NULL) {
DRM_ERROR("Failed to allocate batch bo\n");
return -ENOMEM;
}
ret = i915_gem_object_pin(obj, 0, true, false);
if (ret != 0) {
drm_gem_object_unreference(&obj->base);
DRM_ERROR("Failed to ping batch bo\n");
return ret;
}
ring->private = obj;
}
return intel_init_ring_buffer(dev, ring);
}
int intel_render_ring_init_dri(struct drm_device *dev, u64 start, u32 size)
{
drm_i915_private_t *dev_priv = dev->dev_private;
struct intel_ring_buffer *ring = &dev_priv->ring[RCS];
int ret;
ring->name = "render ring";
ring->id = RCS;
ring->mmio_base = RENDER_RING_BASE;
if (INTEL_INFO(dev)->gen >= 6) {
/* non-kms not supported on gen6+ */
return -ENODEV;
}
/* Note: gem is not supported on gen5/ilk without kms (the corresponding
* gem_init ioctl returns with -ENODEV). Hence we do not need to set up
* the special gen5 functions. */
ring->add_request = i9xx_add_request;
if (INTEL_INFO(dev)->gen < 4)
ring->flush = gen2_render_ring_flush;
else
ring->flush = gen4_render_ring_flush;
ring->get_seqno = ring_get_seqno;
ring->set_seqno = ring_set_seqno;
if (IS_GEN2(dev)) {
ring->irq_get = i8xx_ring_get_irq;
ring->irq_put = i8xx_ring_put_irq;
} else {
ring->irq_get = i9xx_ring_get_irq;
ring->irq_put = i9xx_ring_put_irq;
}
ring->irq_enable_mask = I915_USER_INTERRUPT;
ring->write_tail = ring_write_tail;
if (INTEL_INFO(dev)->gen >= 4)
ring->dispatch_execbuffer = i965_dispatch_execbuffer;
else if (IS_I830(dev) || IS_845G(dev))
ring->dispatch_execbuffer = i830_dispatch_execbuffer;
else
ring->dispatch_execbuffer = i915_dispatch_execbuffer;
ring->init = init_render_ring;
ring->cleanup = render_ring_cleanup;
ring->dev = dev;
INIT_LIST_HEAD(&ring->active_list);
INIT_LIST_HEAD(&ring->request_list);
ring->size = size;
ring->effective_size = ring->size;
if (IS_I830(ring->dev) || IS_845G(ring->dev))
ring->effective_size -= 128;
ring->virtual_start = ioremap_wc(start, size);
if (ring->virtual_start == NULL) {
DRM_ERROR("can not ioremap virtual address for"
" ring buffer\n");
return -ENOMEM;
}
if (!I915_NEED_GFX_HWS(dev)) {
ret = init_phys_hws_pga(ring);
if (ret)
return ret;
}
return 0;
}
int intel_init_bsd_ring_buffer(struct drm_device *dev)
{
drm_i915_private_t *dev_priv = dev->dev_private;
struct intel_ring_buffer *ring = &dev_priv->ring[VCS];
ring->name = "bsd ring";
ring->id = VCS;
ring->write_tail = ring_write_tail;
if (IS_GEN6(dev) || IS_GEN7(dev)) {
ring->mmio_base = GEN6_BSD_RING_BASE;
/* gen6 bsd needs a special wa for tail updates */
if (IS_GEN6(dev))
ring->write_tail = gen6_bsd_ring_write_tail;
ring->flush = gen6_ring_flush;
ring->add_request = gen6_add_request;
ring->get_seqno = gen6_ring_get_seqno;
ring->set_seqno = ring_set_seqno;
ring->irq_enable_mask = GEN6_BSD_USER_INTERRUPT;
ring->irq_get = gen6_ring_get_irq;
ring->irq_put = gen6_ring_put_irq;
ring->dispatch_execbuffer = gen6_ring_dispatch_execbuffer;
ring->sync_to = gen6_ring_sync;
ring->semaphore_register[0] = MI_SEMAPHORE_SYNC_VR;
ring->semaphore_register[1] = MI_SEMAPHORE_SYNC_INVALID;
ring->semaphore_register[2] = MI_SEMAPHORE_SYNC_VB;
ring->signal_mbox[0] = GEN6_RVSYNC;
ring->signal_mbox[1] = GEN6_BVSYNC;
} else {
ring->mmio_base = BSD_RING_BASE;
ring->flush = bsd_ring_flush;
ring->add_request = i9xx_add_request;
ring->get_seqno = ring_get_seqno;
ring->set_seqno = ring_set_seqno;
if (IS_GEN5(dev)) {
ring->irq_enable_mask = GT_BSD_USER_INTERRUPT;
ring->irq_get = gen5_ring_get_irq;
ring->irq_put = gen5_ring_put_irq;
} else {
ring->irq_enable_mask = I915_BSD_USER_INTERRUPT;
ring->irq_get = i9xx_ring_get_irq;
ring->irq_put = i9xx_ring_put_irq;
}
ring->dispatch_execbuffer = i965_dispatch_execbuffer;
}
ring->init = init_ring_common;
return intel_init_ring_buffer(dev, ring);
}
int intel_init_blt_ring_buffer(struct drm_device *dev)
{
drm_i915_private_t *dev_priv = dev->dev_private;
struct intel_ring_buffer *ring = &dev_priv->ring[BCS];
ring->name = "blitter ring";
ring->id = BCS;
ring->mmio_base = BLT_RING_BASE;
ring->write_tail = ring_write_tail;
ring->flush = blt_ring_flush;
ring->add_request = gen6_add_request;
ring->get_seqno = gen6_ring_get_seqno;
ring->set_seqno = ring_set_seqno;
ring->irq_enable_mask = GEN6_BLITTER_USER_INTERRUPT;
ring->irq_get = gen6_ring_get_irq;
ring->irq_put = gen6_ring_put_irq;
ring->dispatch_execbuffer = gen6_ring_dispatch_execbuffer;
ring->sync_to = gen6_ring_sync;
ring->semaphore_register[0] = MI_SEMAPHORE_SYNC_BR;
ring->semaphore_register[1] = MI_SEMAPHORE_SYNC_BV;
ring->semaphore_register[2] = MI_SEMAPHORE_SYNC_INVALID;
ring->signal_mbox[0] = GEN6_RBSYNC;
ring->signal_mbox[1] = GEN6_VBSYNC;
ring->init = init_ring_common;
return intel_init_ring_buffer(dev, ring);
}
int
intel_ring_flush_all_caches(struct intel_ring_buffer *ring)
{
int ret;
if (!ring->gpu_caches_dirty)
return 0;
ret = ring->flush(ring, 0, I915_GEM_GPU_DOMAINS);
if (ret)
return ret;
trace_i915_gem_ring_flush(ring, 0, I915_GEM_GPU_DOMAINS);
ring->gpu_caches_dirty = false;
return 0;
}
int
intel_ring_invalidate_all_caches(struct intel_ring_buffer *ring)
{
uint32_t flush_domains;
int ret;
flush_domains = 0;
if (ring->gpu_caches_dirty)
flush_domains = I915_GEM_GPU_DOMAINS;
ret = ring->flush(ring, I915_GEM_GPU_DOMAINS, flush_domains);
if (ret)
return ret;
trace_i915_gem_ring_flush(ring, I915_GEM_GPU_DOMAINS, flush_domains);
ring->gpu_caches_dirty = false;
return 0;
}
| gpl-2.0 |
Split-Screen/android_kernel_huawei_msm8928 | drivers/scsi/ufs/ufshcd-pltfrm.c | 1887 | 4640 | /*
* Universal Flash Storage Host controller Platform bus based glue driver
*
* This code is based on drivers/scsi/ufs/ufshcd-pltfrm.c
* Copyright (C) 2011-2013 Samsung India Software Operations
*
* Authors:
* Santosh Yaraganavi <santosh.sy@samsung.com>
* Vinayak Holikatti <h.vinayak@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.
* See the COPYING file in the top-level directory or visit
* <http://www.gnu.org/licenses/gpl-2.0.html>
*
* 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.
*
* This program is provided "AS IS" and "WITH ALL FAULTS" and
* without warranty of any kind. You are solely responsible for
* determining the appropriateness of using and distributing
* the program and assume all risks associated with your exercise
* of rights with respect to the program, including but not limited
* to infringement of third party rights, the risks and costs of
* program errors, damage to or loss of data, programs or equipment,
* and unavailability or interruption of operations. Under no
* circumstances will the contributor of this Program be liable for
* any damages of any kind arising from your use or distribution of
* this program.
*/
#include <linux/platform_device.h>
#include "ufshcd.h"
#ifdef CONFIG_PM
/**
* ufshcd_pltfrm_suspend - suspend power management function
* @dev: pointer to device handle
*
*
* Returns 0
*/
static int ufshcd_pltfrm_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct ufs_hba *hba = platform_get_drvdata(pdev);
/*
* TODO:
* 1. Call ufshcd_suspend
* 2. Do bus specific power management
*/
disable_irq(hba->irq);
return 0;
}
/**
* ufshcd_pltfrm_resume - resume power management function
* @dev: pointer to device handle
*
* Returns 0
*/
static int ufshcd_pltfrm_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct ufs_hba *hba = platform_get_drvdata(pdev);
/*
* TODO:
* 1. Call ufshcd_resume.
* 2. Do bus specific wake up
*/
enable_irq(hba->irq);
return 0;
}
#else
#define ufshcd_pltfrm_suspend NULL
#define ufshcd_pltfrm_resume NULL
#endif
/**
* ufshcd_pltfrm_probe - probe routine of the driver
* @pdev: pointer to Platform device handle
*
* Returns 0 on success, non-zero value on failure
*/
static int ufshcd_pltfrm_probe(struct platform_device *pdev)
{
struct ufs_hba *hba;
void __iomem *mmio_base;
struct resource *mem_res;
int irq, err;
struct device *dev = &pdev->dev;
mem_res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!mem_res) {
dev_err(dev, "Memory resource not available\n");
err = -ENODEV;
goto out;
}
mmio_base = devm_ioremap_resource(dev, mem_res);
if (IS_ERR(mmio_base)) {
dev_err(dev, "memory map failed\n");
err = PTR_ERR(mmio_base);
goto out;
}
irq = platform_get_irq(pdev, 0);
if (irq < 0) {
dev_err(dev, "IRQ resource not available\n");
err = -ENODEV;
goto out;
}
err = ufshcd_init(dev, &hba, mmio_base, irq);
if (err) {
dev_err(dev, "Intialization failed\n");
goto out;
}
platform_set_drvdata(pdev, hba);
out:
return err;
}
/**
* ufshcd_pltfrm_remove - remove platform driver routine
* @pdev: pointer to platform device handle
*
* Returns 0 on success, non-zero value on failure
*/
static int ufshcd_pltfrm_remove(struct platform_device *pdev)
{
struct ufs_hba *hba = platform_get_drvdata(pdev);
disable_irq(hba->irq);
ufshcd_remove(hba);
return 0;
}
static const struct of_device_id ufs_of_match[] = {
{ .compatible = "jedec,ufs-1.1"},
{},
};
static const struct dev_pm_ops ufshcd_dev_pm_ops = {
.suspend = ufshcd_pltfrm_suspend,
.resume = ufshcd_pltfrm_resume,
};
static struct platform_driver ufshcd_pltfrm_driver = {
.probe = ufshcd_pltfrm_probe,
.remove = ufshcd_pltfrm_remove,
.driver = {
.name = "ufshcd",
.owner = THIS_MODULE,
.pm = &ufshcd_dev_pm_ops,
.of_match_table = ufs_of_match,
},
};
module_platform_driver(ufshcd_pltfrm_driver);
MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
MODULE_DESCRIPTION("UFS host controller Pltform bus based glue driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(UFSHCD_DRIVER_VERSION);
| gpl-2.0 |
sivasankariit/linux-rl | drivers/usb/phy/omap-usb3.c | 2143 | 9069 | /*
* omap-usb3 - USB PHY, talking to dwc3 controller in OMAP.
*
* Copyright (C) 2013 Texas Instruments Incorporated - http://www.ti.com
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Author: Kishon Vijay Abraham I <kishon@ti.com>
*
* 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/usb/omap_usb.h>
#include <linux/of.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/pm_runtime.h>
#include <linux/delay.h>
#include <linux/usb/omap_control_usb.h>
#define NUM_SYS_CLKS 5
#define PLL_STATUS 0x00000004
#define PLL_GO 0x00000008
#define PLL_CONFIGURATION1 0x0000000C
#define PLL_CONFIGURATION2 0x00000010
#define PLL_CONFIGURATION3 0x00000014
#define PLL_CONFIGURATION4 0x00000020
#define PLL_REGM_MASK 0x001FFE00
#define PLL_REGM_SHIFT 0x9
#define PLL_REGM_F_MASK 0x0003FFFF
#define PLL_REGM_F_SHIFT 0x0
#define PLL_REGN_MASK 0x000001FE
#define PLL_REGN_SHIFT 0x1
#define PLL_SELFREQDCO_MASK 0x0000000E
#define PLL_SELFREQDCO_SHIFT 0x1
#define PLL_SD_MASK 0x0003FC00
#define PLL_SD_SHIFT 0x9
#define SET_PLL_GO 0x1
#define PLL_TICOPWDN 0x10000
#define PLL_LOCK 0x2
#define PLL_IDLE 0x1
/*
* This is an Empirical value that works, need to confirm the actual
* value required for the USB3PHY_PLL_CONFIGURATION2.PLL_IDLE status
* to be correctly reflected in the USB3PHY_PLL_STATUS register.
*/
# define PLL_IDLE_TIME 100;
enum sys_clk_rate {
CLK_RATE_UNDEFINED = -1,
CLK_RATE_12MHZ,
CLK_RATE_16MHZ,
CLK_RATE_19MHZ,
CLK_RATE_26MHZ,
CLK_RATE_38MHZ
};
static struct usb_dpll_params omap_usb3_dpll_params[NUM_SYS_CLKS] = {
{1250, 5, 4, 20, 0}, /* 12 MHz */
{3125, 20, 4, 20, 0}, /* 16.8 MHz */
{1172, 8, 4, 20, 65537}, /* 19.2 MHz */
{1250, 12, 4, 20, 0}, /* 26 MHz */
{3125, 47, 4, 20, 92843}, /* 38.4 MHz */
};
static int omap_usb3_suspend(struct usb_phy *x, int suspend)
{
struct omap_usb *phy = phy_to_omapusb(x);
int val;
int timeout = PLL_IDLE_TIME;
if (suspend && !phy->is_suspended) {
val = omap_usb_readl(phy->pll_ctrl_base, PLL_CONFIGURATION2);
val |= PLL_IDLE;
omap_usb_writel(phy->pll_ctrl_base, PLL_CONFIGURATION2, val);
do {
val = omap_usb_readl(phy->pll_ctrl_base, PLL_STATUS);
if (val & PLL_TICOPWDN)
break;
udelay(1);
} while (--timeout);
omap_control_usb3_phy_power(phy->control_dev, 0);
phy->is_suspended = 1;
} else if (!suspend && phy->is_suspended) {
phy->is_suspended = 0;
val = omap_usb_readl(phy->pll_ctrl_base, PLL_CONFIGURATION2);
val &= ~PLL_IDLE;
omap_usb_writel(phy->pll_ctrl_base, PLL_CONFIGURATION2, val);
do {
val = omap_usb_readl(phy->pll_ctrl_base, PLL_STATUS);
if (!(val & PLL_TICOPWDN))
break;
udelay(1);
} while (--timeout);
}
return 0;
}
static inline enum sys_clk_rate __get_sys_clk_index(unsigned long rate)
{
switch (rate) {
case 12000000:
return CLK_RATE_12MHZ;
case 16800000:
return CLK_RATE_16MHZ;
case 19200000:
return CLK_RATE_19MHZ;
case 26000000:
return CLK_RATE_26MHZ;
case 38400000:
return CLK_RATE_38MHZ;
default:
return CLK_RATE_UNDEFINED;
}
}
static void omap_usb_dpll_relock(struct omap_usb *phy)
{
u32 val;
unsigned long timeout;
omap_usb_writel(phy->pll_ctrl_base, PLL_GO, SET_PLL_GO);
timeout = jiffies + msecs_to_jiffies(20);
do {
val = omap_usb_readl(phy->pll_ctrl_base, PLL_STATUS);
if (val & PLL_LOCK)
break;
} while (!WARN_ON(time_after(jiffies, timeout)));
}
static int omap_usb_dpll_lock(struct omap_usb *phy)
{
u32 val;
unsigned long rate;
enum sys_clk_rate clk_index;
rate = clk_get_rate(phy->sys_clk);
clk_index = __get_sys_clk_index(rate);
if (clk_index == CLK_RATE_UNDEFINED) {
pr_err("dpll cannot be locked for sys clk freq:%luHz\n", rate);
return -EINVAL;
}
val = omap_usb_readl(phy->pll_ctrl_base, PLL_CONFIGURATION1);
val &= ~PLL_REGN_MASK;
val |= omap_usb3_dpll_params[clk_index].n << PLL_REGN_SHIFT;
omap_usb_writel(phy->pll_ctrl_base, PLL_CONFIGURATION1, val);
val = omap_usb_readl(phy->pll_ctrl_base, PLL_CONFIGURATION2);
val &= ~PLL_SELFREQDCO_MASK;
val |= omap_usb3_dpll_params[clk_index].freq << PLL_SELFREQDCO_SHIFT;
omap_usb_writel(phy->pll_ctrl_base, PLL_CONFIGURATION2, val);
val = omap_usb_readl(phy->pll_ctrl_base, PLL_CONFIGURATION1);
val &= ~PLL_REGM_MASK;
val |= omap_usb3_dpll_params[clk_index].m << PLL_REGM_SHIFT;
omap_usb_writel(phy->pll_ctrl_base, PLL_CONFIGURATION1, val);
val = omap_usb_readl(phy->pll_ctrl_base, PLL_CONFIGURATION4);
val &= ~PLL_REGM_F_MASK;
val |= omap_usb3_dpll_params[clk_index].mf << PLL_REGM_F_SHIFT;
omap_usb_writel(phy->pll_ctrl_base, PLL_CONFIGURATION4, val);
val = omap_usb_readl(phy->pll_ctrl_base, PLL_CONFIGURATION3);
val &= ~PLL_SD_MASK;
val |= omap_usb3_dpll_params[clk_index].sd << PLL_SD_SHIFT;
omap_usb_writel(phy->pll_ctrl_base, PLL_CONFIGURATION3, val);
omap_usb_dpll_relock(phy);
return 0;
}
static int omap_usb3_init(struct usb_phy *x)
{
struct omap_usb *phy = phy_to_omapusb(x);
omap_usb_dpll_lock(phy);
omap_control_usb3_phy_power(phy->control_dev, 1);
return 0;
}
static int omap_usb3_probe(struct platform_device *pdev)
{
struct omap_usb *phy;
struct resource *res;
phy = devm_kzalloc(&pdev->dev, sizeof(*phy), GFP_KERNEL);
if (!phy) {
dev_err(&pdev->dev, "unable to alloc mem for OMAP USB3 PHY\n");
return -ENOMEM;
}
res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "pll_ctrl");
phy->pll_ctrl_base = devm_ioremap_resource(&pdev->dev, res);
if (IS_ERR(phy->pll_ctrl_base))
return PTR_ERR(phy->pll_ctrl_base);
phy->dev = &pdev->dev;
phy->phy.dev = phy->dev;
phy->phy.label = "omap-usb3";
phy->phy.init = omap_usb3_init;
phy->phy.set_suspend = omap_usb3_suspend;
phy->phy.type = USB_PHY_TYPE_USB3;
phy->is_suspended = 1;
phy->wkupclk = devm_clk_get(phy->dev, "usb_phy_cm_clk32k");
if (IS_ERR(phy->wkupclk)) {
dev_err(&pdev->dev, "unable to get usb_phy_cm_clk32k\n");
return PTR_ERR(phy->wkupclk);
}
clk_prepare(phy->wkupclk);
phy->optclk = devm_clk_get(phy->dev, "usb_otg_ss_refclk960m");
if (IS_ERR(phy->optclk)) {
dev_err(&pdev->dev, "unable to get usb_otg_ss_refclk960m\n");
return PTR_ERR(phy->optclk);
}
clk_prepare(phy->optclk);
phy->sys_clk = devm_clk_get(phy->dev, "sys_clkin");
if (IS_ERR(phy->sys_clk)) {
pr_err("%s: unable to get sys_clkin\n", __func__);
return -EINVAL;
}
phy->control_dev = omap_get_control_dev();
if (IS_ERR(phy->control_dev)) {
dev_dbg(&pdev->dev, "Failed to get control device\n");
return -ENODEV;
}
omap_control_usb3_phy_power(phy->control_dev, 0);
usb_add_phy_dev(&phy->phy);
platform_set_drvdata(pdev, phy);
pm_runtime_enable(phy->dev);
pm_runtime_get(&pdev->dev);
return 0;
}
static int omap_usb3_remove(struct platform_device *pdev)
{
struct omap_usb *phy = platform_get_drvdata(pdev);
clk_unprepare(phy->wkupclk);
clk_unprepare(phy->optclk);
usb_remove_phy(&phy->phy);
if (!pm_runtime_suspended(&pdev->dev))
pm_runtime_put(&pdev->dev);
pm_runtime_disable(&pdev->dev);
return 0;
}
#ifdef CONFIG_PM_RUNTIME
static int omap_usb3_runtime_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct omap_usb *phy = platform_get_drvdata(pdev);
clk_disable(phy->wkupclk);
clk_disable(phy->optclk);
return 0;
}
static int omap_usb3_runtime_resume(struct device *dev)
{
u32 ret = 0;
struct platform_device *pdev = to_platform_device(dev);
struct omap_usb *phy = platform_get_drvdata(pdev);
ret = clk_enable(phy->optclk);
if (ret) {
dev_err(phy->dev, "Failed to enable optclk %d\n", ret);
goto err1;
}
ret = clk_enable(phy->wkupclk);
if (ret) {
dev_err(phy->dev, "Failed to enable wkupclk %d\n", ret);
goto err2;
}
return 0;
err2:
clk_disable(phy->optclk);
err1:
return ret;
}
static const struct dev_pm_ops omap_usb3_pm_ops = {
SET_RUNTIME_PM_OPS(omap_usb3_runtime_suspend, omap_usb3_runtime_resume,
NULL)
};
#define DEV_PM_OPS (&omap_usb3_pm_ops)
#else
#define DEV_PM_OPS NULL
#endif
#ifdef CONFIG_OF
static const struct of_device_id omap_usb3_id_table[] = {
{ .compatible = "ti,omap-usb3" },
{}
};
MODULE_DEVICE_TABLE(of, omap_usb3_id_table);
#endif
static struct platform_driver omap_usb3_driver = {
.probe = omap_usb3_probe,
.remove = omap_usb3_remove,
.driver = {
.name = "omap-usb3",
.owner = THIS_MODULE,
.pm = DEV_PM_OPS,
.of_match_table = of_match_ptr(omap_usb3_id_table),
},
};
module_platform_driver(omap_usb3_driver);
MODULE_ALIAS("platform: omap_usb3");
MODULE_AUTHOR("Texas Instruments Inc.");
MODULE_DESCRIPTION("OMAP USB3 phy driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
Tesla-Redux-Devices/android_kernel_samsung_trlte | block/partitions/msdos.c | 2143 | 16103 | /*
* fs/partitions/msdos.c
*
* Code extracted from drivers/block/genhd.c
* Copyright (C) 1991-1998 Linus Torvalds
*
* Thanks to Branko Lankester, lankeste@fwi.uva.nl, who found a bug
* in the early extended-partition checks and added DM partitions
*
* Support for DiskManager v6.0x added by Mark Lord,
* with information provided by OnTrack. This now works for linux fdisk
* and LILO, as well as loadlin and bootln. Note that disks other than
* /dev/hda *must* have a "DOS" type 0x51 partition in the first slot (hda1).
*
* More flexible handling of extended partitions - aeb, 950831
*
* Check partition table on IDE disks for common CHS translations
*
* Re-organised Feb 1998 Russell King
*/
#include <linux/msdos_fs.h>
#include "check.h"
#include "msdos.h"
#include "efi.h"
/*
* Many architectures don't like unaligned accesses, while
* the nr_sects and start_sect partition table entries are
* at a 2 (mod 4) address.
*/
#include <asm/unaligned.h>
#define SYS_IND(p) get_unaligned(&p->sys_ind)
static inline sector_t nr_sects(struct partition *p)
{
return (sector_t)get_unaligned_le32(&p->nr_sects);
}
static inline sector_t start_sect(struct partition *p)
{
return (sector_t)get_unaligned_le32(&p->start_sect);
}
static inline int is_extended_partition(struct partition *p)
{
return (SYS_IND(p) == DOS_EXTENDED_PARTITION ||
SYS_IND(p) == WIN98_EXTENDED_PARTITION ||
SYS_IND(p) == LINUX_EXTENDED_PARTITION);
}
#define MSDOS_LABEL_MAGIC1 0x55
#define MSDOS_LABEL_MAGIC2 0xAA
static inline int
msdos_magic_present(unsigned char *p)
{
return (p[0] == MSDOS_LABEL_MAGIC1 && p[1] == MSDOS_LABEL_MAGIC2);
}
/* Value is EBCDIC 'IBMA' */
#define AIX_LABEL_MAGIC1 0xC9
#define AIX_LABEL_MAGIC2 0xC2
#define AIX_LABEL_MAGIC3 0xD4
#define AIX_LABEL_MAGIC4 0xC1
static int aix_magic_present(struct parsed_partitions *state, unsigned char *p)
{
struct partition *pt = (struct partition *) (p + 0x1be);
Sector sect;
unsigned char *d;
int slot, ret = 0;
if (!(p[0] == AIX_LABEL_MAGIC1 &&
p[1] == AIX_LABEL_MAGIC2 &&
p[2] == AIX_LABEL_MAGIC3 &&
p[3] == AIX_LABEL_MAGIC4))
return 0;
/* Assume the partition table is valid if Linux partitions exists */
for (slot = 1; slot <= 4; slot++, pt++) {
if (pt->sys_ind == LINUX_SWAP_PARTITION ||
pt->sys_ind == LINUX_RAID_PARTITION ||
pt->sys_ind == LINUX_DATA_PARTITION ||
pt->sys_ind == LINUX_LVM_PARTITION ||
is_extended_partition(pt))
return 0;
}
d = read_part_sector(state, 7, §);
if (d) {
if (d[0] == '_' && d[1] == 'L' && d[2] == 'V' && d[3] == 'M')
ret = 1;
put_dev_sector(sect);
};
return ret;
}
static void set_info(struct parsed_partitions *state, int slot,
u32 disksig)
{
struct partition_meta_info *info = &state->parts[slot].info;
snprintf(info->uuid, sizeof(info->uuid), "%08x-%02x", disksig,
slot);
info->volname[0] = 0;
state->parts[slot].has_info = true;
}
/*
* Create devices for each logical partition in an extended partition.
* The logical partitions form a linked list, with each entry being
* a partition table with two entries. The first entry
* is the real data partition (with a start relative to the partition
* table start). The second is a pointer to the next logical partition
* (with a start relative to the entire extended partition).
* We do not create a Linux partition for the partition tables, but
* only for the actual data partitions.
*/
static void parse_extended(struct parsed_partitions *state,
sector_t first_sector, sector_t first_size,
u32 disksig)
{
struct partition *p;
Sector sect;
unsigned char *data;
sector_t this_sector, this_size;
sector_t sector_size = bdev_logical_block_size(state->bdev) / 512;
int loopct = 0; /* number of links followed
without finding a data partition */
int i;
this_sector = first_sector;
this_size = first_size;
while (1) {
if (++loopct > 100)
return;
if (state->next == state->limit)
return;
data = read_part_sector(state, this_sector, §);
if (!data)
return;
if (!msdos_magic_present(data + 510))
goto done;
p = (struct partition *) (data + 0x1be);
/*
* Usually, the first entry is the real data partition,
* the 2nd entry is the next extended partition, or empty,
* and the 3rd and 4th entries are unused.
* However, DRDOS sometimes has the extended partition as
* the first entry (when the data partition is empty),
* and OS/2 seems to use all four entries.
*/
/*
* First process the data partition(s)
*/
for (i=0; i<4; i++, p++) {
sector_t offs, size, next;
if (!nr_sects(p) || is_extended_partition(p))
continue;
/* Check the 3rd and 4th entries -
these sometimes contain random garbage */
offs = start_sect(p)*sector_size;
size = nr_sects(p)*sector_size;
next = this_sector + offs;
if (i >= 2) {
if (offs + size > this_size)
continue;
if (next < first_sector)
continue;
if (next + size > first_sector + first_size)
continue;
}
put_partition(state, state->next, next, size);
set_info(state, state->next, disksig);
if (SYS_IND(p) == LINUX_RAID_PARTITION)
state->parts[state->next].flags = ADDPART_FLAG_RAID;
loopct = 0;
if (++state->next == state->limit)
goto done;
}
/*
* Next, process the (first) extended partition, if present.
* (So far, there seems to be no reason to make
* parse_extended() recursive and allow a tree
* of extended partitions.)
* It should be a link to the next logical partition.
*/
p -= 4;
for (i=0; i<4; i++, p++)
if (nr_sects(p) && is_extended_partition(p))
break;
if (i == 4)
goto done; /* nothing left to do */
this_sector = first_sector + start_sect(p) * sector_size;
this_size = nr_sects(p) * sector_size;
put_dev_sector(sect);
}
done:
put_dev_sector(sect);
}
/* james@bpgc.com: Solaris has a nasty indicator: 0x82 which also
indicates linux swap. Be careful before believing this is Solaris. */
static void parse_solaris_x86(struct parsed_partitions *state,
sector_t offset, sector_t size, int origin)
{
#ifdef CONFIG_SOLARIS_X86_PARTITION
Sector sect;
struct solaris_x86_vtoc *v;
int i;
short max_nparts;
v = read_part_sector(state, offset + 1, §);
if (!v)
return;
if (le32_to_cpu(v->v_sanity) != SOLARIS_X86_VTOC_SANE) {
put_dev_sector(sect);
return;
}
{
char tmp[1 + BDEVNAME_SIZE + 10 + 11 + 1];
snprintf(tmp, sizeof(tmp), " %s%d: <solaris:", state->name, origin);
strlcat(state->pp_buf, tmp, PAGE_SIZE);
}
if (le32_to_cpu(v->v_version) != 1) {
char tmp[64];
snprintf(tmp, sizeof(tmp), " cannot handle version %d vtoc>\n",
le32_to_cpu(v->v_version));
strlcat(state->pp_buf, tmp, PAGE_SIZE);
put_dev_sector(sect);
return;
}
/* Ensure we can handle previous case of VTOC with 8 entries gracefully */
max_nparts = le16_to_cpu (v->v_nparts) > 8 ? SOLARIS_X86_NUMSLICE : 8;
for (i=0; i<max_nparts && state->next<state->limit; i++) {
struct solaris_x86_slice *s = &v->v_slice[i];
char tmp[3 + 10 + 1 + 1];
if (s->s_size == 0)
continue;
snprintf(tmp, sizeof(tmp), " [s%d]", i);
strlcat(state->pp_buf, tmp, PAGE_SIZE);
/* solaris partitions are relative to current MS-DOS
* one; must add the offset of the current partition */
put_partition(state, state->next++,
le32_to_cpu(s->s_start)+offset,
le32_to_cpu(s->s_size));
}
put_dev_sector(sect);
strlcat(state->pp_buf, " >\n", PAGE_SIZE);
#endif
}
#if defined(CONFIG_BSD_DISKLABEL)
/*
* Create devices for BSD partitions listed in a disklabel, under a
* dos-like partition. See parse_extended() for more information.
*/
static void parse_bsd(struct parsed_partitions *state,
sector_t offset, sector_t size, int origin, char *flavour,
int max_partitions)
{
Sector sect;
struct bsd_disklabel *l;
struct bsd_partition *p;
char tmp[64];
l = read_part_sector(state, offset + 1, §);
if (!l)
return;
if (le32_to_cpu(l->d_magic) != BSD_DISKMAGIC) {
put_dev_sector(sect);
return;
}
snprintf(tmp, sizeof(tmp), " %s%d: <%s:", state->name, origin, flavour);
strlcat(state->pp_buf, tmp, PAGE_SIZE);
if (le16_to_cpu(l->d_npartitions) < max_partitions)
max_partitions = le16_to_cpu(l->d_npartitions);
for (p = l->d_partitions; p - l->d_partitions < max_partitions; p++) {
sector_t bsd_start, bsd_size;
if (state->next == state->limit)
break;
if (p->p_fstype == BSD_FS_UNUSED)
continue;
bsd_start = le32_to_cpu(p->p_offset);
bsd_size = le32_to_cpu(p->p_size);
if (offset == bsd_start && size == bsd_size)
/* full parent partition, we have it already */
continue;
if (offset > bsd_start || offset+size < bsd_start+bsd_size) {
strlcat(state->pp_buf, "bad subpartition - ignored\n", PAGE_SIZE);
continue;
}
put_partition(state, state->next++, bsd_start, bsd_size);
}
put_dev_sector(sect);
if (le16_to_cpu(l->d_npartitions) > max_partitions) {
snprintf(tmp, sizeof(tmp), " (ignored %d more)",
le16_to_cpu(l->d_npartitions) - max_partitions);
strlcat(state->pp_buf, tmp, PAGE_SIZE);
}
strlcat(state->pp_buf, " >\n", PAGE_SIZE);
}
#endif
static void parse_freebsd(struct parsed_partitions *state,
sector_t offset, sector_t size, int origin)
{
#ifdef CONFIG_BSD_DISKLABEL
parse_bsd(state, offset, size, origin, "bsd", BSD_MAXPARTITIONS);
#endif
}
static void parse_netbsd(struct parsed_partitions *state,
sector_t offset, sector_t size, int origin)
{
#ifdef CONFIG_BSD_DISKLABEL
parse_bsd(state, offset, size, origin, "netbsd", BSD_MAXPARTITIONS);
#endif
}
static void parse_openbsd(struct parsed_partitions *state,
sector_t offset, sector_t size, int origin)
{
#ifdef CONFIG_BSD_DISKLABEL
parse_bsd(state, offset, size, origin, "openbsd",
OPENBSD_MAXPARTITIONS);
#endif
}
/*
* Create devices for Unixware partitions listed in a disklabel, under a
* dos-like partition. See parse_extended() for more information.
*/
static void parse_unixware(struct parsed_partitions *state,
sector_t offset, sector_t size, int origin)
{
#ifdef CONFIG_UNIXWARE_DISKLABEL
Sector sect;
struct unixware_disklabel *l;
struct unixware_slice *p;
l = read_part_sector(state, offset + 29, §);
if (!l)
return;
if (le32_to_cpu(l->d_magic) != UNIXWARE_DISKMAGIC ||
le32_to_cpu(l->vtoc.v_magic) != UNIXWARE_DISKMAGIC2) {
put_dev_sector(sect);
return;
}
{
char tmp[1 + BDEVNAME_SIZE + 10 + 12 + 1];
snprintf(tmp, sizeof(tmp), " %s%d: <unixware:", state->name, origin);
strlcat(state->pp_buf, tmp, PAGE_SIZE);
}
p = &l->vtoc.v_slice[1];
/* I omit the 0th slice as it is the same as whole disk. */
while (p - &l->vtoc.v_slice[0] < UNIXWARE_NUMSLICE) {
if (state->next == state->limit)
break;
if (p->s_label != UNIXWARE_FS_UNUSED)
put_partition(state, state->next++,
le32_to_cpu(p->start_sect),
le32_to_cpu(p->nr_sects));
p++;
}
put_dev_sector(sect);
strlcat(state->pp_buf, " >\n", PAGE_SIZE);
#endif
}
/*
* Minix 2.0.0/2.0.2 subpartition support.
* Anand Krishnamurthy <anandk@wiproge.med.ge.com>
* Rajeev V. Pillai <rajeevvp@yahoo.com>
*/
static void parse_minix(struct parsed_partitions *state,
sector_t offset, sector_t size, int origin)
{
#ifdef CONFIG_MINIX_SUBPARTITION
Sector sect;
unsigned char *data;
struct partition *p;
int i;
data = read_part_sector(state, offset, §);
if (!data)
return;
p = (struct partition *)(data + 0x1be);
/* The first sector of a Minix partition can have either
* a secondary MBR describing its subpartitions, or
* the normal boot sector. */
if (msdos_magic_present (data + 510) &&
SYS_IND(p) == MINIX_PARTITION) { /* subpartition table present */
char tmp[1 + BDEVNAME_SIZE + 10 + 9 + 1];
snprintf(tmp, sizeof(tmp), " %s%d: <minix:", state->name, origin);
strlcat(state->pp_buf, tmp, PAGE_SIZE);
for (i = 0; i < MINIX_NR_SUBPARTITIONS; i++, p++) {
if (state->next == state->limit)
break;
/* add each partition in use */
if (SYS_IND(p) == MINIX_PARTITION)
put_partition(state, state->next++,
start_sect(p), nr_sects(p));
}
strlcat(state->pp_buf, " >\n", PAGE_SIZE);
}
put_dev_sector(sect);
#endif /* CONFIG_MINIX_SUBPARTITION */
}
static struct {
unsigned char id;
void (*parse)(struct parsed_partitions *, sector_t, sector_t, int);
} subtypes[] = {
{FREEBSD_PARTITION, parse_freebsd},
{NETBSD_PARTITION, parse_netbsd},
{OPENBSD_PARTITION, parse_openbsd},
{MINIX_PARTITION, parse_minix},
{UNIXWARE_PARTITION, parse_unixware},
{SOLARIS_X86_PARTITION, parse_solaris_x86},
{NEW_SOLARIS_X86_PARTITION, parse_solaris_x86},
{0, NULL},
};
int msdos_partition(struct parsed_partitions *state)
{
sector_t sector_size = bdev_logical_block_size(state->bdev) / 512;
Sector sect;
unsigned char *data;
struct partition *p;
struct fat_boot_sector *fb;
int slot;
u32 disksig;
data = read_part_sector(state, 0, §);
if (!data)
return -1;
/*
* Note order! (some AIX disks, e.g. unbootable kind,
* have no MSDOS 55aa)
*/
if (aix_magic_present(state, data)) {
put_dev_sector(sect);
strlcat(state->pp_buf, " [AIX]", PAGE_SIZE);
return 0;
}
if (!msdos_magic_present(data + 510)) {
put_dev_sector(sect);
return 0;
}
/*
* Now that the 55aa signature is present, this is probably
* either the boot sector of a FAT filesystem or a DOS-type
* partition table. Reject this in case the boot indicator
* is not 0 or 0x80.
*/
p = (struct partition *) (data + 0x1be);
for (slot = 1; slot <= 4; slot++, p++) {
if (p->boot_ind != 0 && p->boot_ind != 0x80) {
/*
* Even without a valid boot inidicator value
* its still possible this is valid FAT filesystem
* without a partition table.
*/
fb = (struct fat_boot_sector *) data;
if (slot == 1 && fb->reserved && fb->fats
&& fat_valid_media(fb->media)) {
strlcat(state->pp_buf, "\n", PAGE_SIZE);
put_dev_sector(sect);
return 1;
} else {
put_dev_sector(sect);
return 0;
}
}
}
#ifdef CONFIG_EFI_PARTITION
p = (struct partition *) (data + 0x1be);
for (slot = 1 ; slot <= 4 ; slot++, p++) {
/* If this is an EFI GPT disk, msdos should ignore it. */
if (SYS_IND(p) == EFI_PMBR_OSTYPE_EFI_GPT) {
put_dev_sector(sect);
return 0;
}
}
#endif
p = (struct partition *) (data + 0x1be);
disksig = le32_to_cpup((__le32 *)(data + 0x1b8));
/*
* Look for partitions in two passes:
* First find the primary and DOS-type extended partitions.
* On the second pass look inside *BSD, Unixware and Solaris partitions.
*/
state->next = 5;
for (slot = 1 ; slot <= 4 ; slot++, p++) {
sector_t start = start_sect(p)*sector_size;
sector_t size = nr_sects(p)*sector_size;
if (!size)
continue;
if (is_extended_partition(p)) {
/*
* prevent someone doing mkfs or mkswap on an
* extended partition, but leave room for LILO
* FIXME: this uses one logical sector for > 512b
* sector, although it may not be enough/proper.
*/
sector_t n = 2;
n = min(size, max(sector_size, n));
put_partition(state, slot, start, n);
strlcat(state->pp_buf, " <", PAGE_SIZE);
parse_extended(state, start, size, disksig);
strlcat(state->pp_buf, " >", PAGE_SIZE);
continue;
}
put_partition(state, slot, start, size);
set_info(state, slot, disksig);
if (SYS_IND(p) == LINUX_RAID_PARTITION)
state->parts[slot].flags = ADDPART_FLAG_RAID;
if (SYS_IND(p) == DM6_PARTITION)
strlcat(state->pp_buf, "[DM]", PAGE_SIZE);
if (SYS_IND(p) == EZD_PARTITION)
strlcat(state->pp_buf, "[EZD]", PAGE_SIZE);
}
strlcat(state->pp_buf, "\n", PAGE_SIZE);
/* second pass - output for each on a separate line */
p = (struct partition *) (0x1be + data);
for (slot = 1 ; slot <= 4 ; slot++, p++) {
unsigned char id = SYS_IND(p);
int n;
if (!nr_sects(p))
continue;
for (n = 0; subtypes[n].parse && id != subtypes[n].id; n++)
;
if (!subtypes[n].parse)
continue;
subtypes[n].parse(state, start_sect(p) * sector_size,
nr_sects(p) * sector_size, slot);
}
put_dev_sector(sect);
return 1;
}
| gpl-2.0 |
saafir7/exynos7420 | drivers/video/pxa168fb.c | 2399 | 20917 | /*
* linux/drivers/video/pxa168fb.c -- Marvell PXA168 LCD Controller
*
* Copyright (C) 2008 Marvell International Ltd.
* All rights reserved.
*
* 2009-02-16 adapted from original version for PXA168/910
* Jun Nie <njun@marvell.com>
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of this archive for
* more details.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/string.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include <linux/fb.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/ioport.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/uaccess.h>
#include <video/pxa168fb.h>
#include "pxa168fb.h"
#define DEFAULT_REFRESH 60 /* Hz */
static int determine_best_pix_fmt(struct fb_var_screeninfo *var)
{
/*
* Pseudocolor mode?
*/
if (var->bits_per_pixel == 8)
return PIX_FMT_PSEUDOCOLOR;
/*
* Check for 565/1555.
*/
if (var->bits_per_pixel == 16 && var->red.length <= 5 &&
var->green.length <= 6 && var->blue.length <= 5) {
if (var->transp.length == 0) {
if (var->red.offset >= var->blue.offset)
return PIX_FMT_RGB565;
else
return PIX_FMT_BGR565;
}
if (var->transp.length == 1 && var->green.length <= 5) {
if (var->red.offset >= var->blue.offset)
return PIX_FMT_RGB1555;
else
return PIX_FMT_BGR1555;
}
/* fall through */
}
/*
* Check for 888/A888.
*/
if (var->bits_per_pixel <= 32 && var->red.length <= 8 &&
var->green.length <= 8 && var->blue.length <= 8) {
if (var->bits_per_pixel == 24 && var->transp.length == 0) {
if (var->red.offset >= var->blue.offset)
return PIX_FMT_RGB888PACK;
else
return PIX_FMT_BGR888PACK;
}
if (var->bits_per_pixel == 32 && var->transp.length == 8) {
if (var->red.offset >= var->blue.offset)
return PIX_FMT_RGBA888;
else
return PIX_FMT_BGRA888;
} else {
if (var->red.offset >= var->blue.offset)
return PIX_FMT_RGB888UNPACK;
else
return PIX_FMT_BGR888UNPACK;
}
/* fall through */
}
return -EINVAL;
}
static void set_pix_fmt(struct fb_var_screeninfo *var, int pix_fmt)
{
switch (pix_fmt) {
case PIX_FMT_RGB565:
var->bits_per_pixel = 16;
var->red.offset = 11; var->red.length = 5;
var->green.offset = 5; var->green.length = 6;
var->blue.offset = 0; var->blue.length = 5;
var->transp.offset = 0; var->transp.length = 0;
break;
case PIX_FMT_BGR565:
var->bits_per_pixel = 16;
var->red.offset = 0; var->red.length = 5;
var->green.offset = 5; var->green.length = 6;
var->blue.offset = 11; var->blue.length = 5;
var->transp.offset = 0; var->transp.length = 0;
break;
case PIX_FMT_RGB1555:
var->bits_per_pixel = 16;
var->red.offset = 10; var->red.length = 5;
var->green.offset = 5; var->green.length = 5;
var->blue.offset = 0; var->blue.length = 5;
var->transp.offset = 15; var->transp.length = 1;
break;
case PIX_FMT_BGR1555:
var->bits_per_pixel = 16;
var->red.offset = 0; var->red.length = 5;
var->green.offset = 5; var->green.length = 5;
var->blue.offset = 10; var->blue.length = 5;
var->transp.offset = 15; var->transp.length = 1;
break;
case PIX_FMT_RGB888PACK:
var->bits_per_pixel = 24;
var->red.offset = 16; var->red.length = 8;
var->green.offset = 8; var->green.length = 8;
var->blue.offset = 0; var->blue.length = 8;
var->transp.offset = 0; var->transp.length = 0;
break;
case PIX_FMT_BGR888PACK:
var->bits_per_pixel = 24;
var->red.offset = 0; var->red.length = 8;
var->green.offset = 8; var->green.length = 8;
var->blue.offset = 16; var->blue.length = 8;
var->transp.offset = 0; var->transp.length = 0;
break;
case PIX_FMT_RGBA888:
var->bits_per_pixel = 32;
var->red.offset = 16; var->red.length = 8;
var->green.offset = 8; var->green.length = 8;
var->blue.offset = 0; var->blue.length = 8;
var->transp.offset = 24; var->transp.length = 8;
break;
case PIX_FMT_BGRA888:
var->bits_per_pixel = 32;
var->red.offset = 0; var->red.length = 8;
var->green.offset = 8; var->green.length = 8;
var->blue.offset = 16; var->blue.length = 8;
var->transp.offset = 24; var->transp.length = 8;
break;
case PIX_FMT_PSEUDOCOLOR:
var->bits_per_pixel = 8;
var->red.offset = 0; var->red.length = 8;
var->green.offset = 0; var->green.length = 8;
var->blue.offset = 0; var->blue.length = 8;
var->transp.offset = 0; var->transp.length = 0;
break;
}
}
static void set_mode(struct pxa168fb_info *fbi, struct fb_var_screeninfo *var,
struct fb_videomode *mode, int pix_fmt, int ystretch)
{
struct fb_info *info = fbi->info;
set_pix_fmt(var, pix_fmt);
var->xres = mode->xres;
var->yres = mode->yres;
var->xres_virtual = max(var->xres, var->xres_virtual);
if (ystretch)
var->yres_virtual = info->fix.smem_len /
(var->xres_virtual * (var->bits_per_pixel >> 3));
else
var->yres_virtual = max(var->yres, var->yres_virtual);
var->grayscale = 0;
var->accel_flags = FB_ACCEL_NONE;
var->pixclock = mode->pixclock;
var->left_margin = mode->left_margin;
var->right_margin = mode->right_margin;
var->upper_margin = mode->upper_margin;
var->lower_margin = mode->lower_margin;
var->hsync_len = mode->hsync_len;
var->vsync_len = mode->vsync_len;
var->sync = mode->sync;
var->vmode = FB_VMODE_NONINTERLACED;
var->rotate = FB_ROTATE_UR;
}
static int pxa168fb_check_var(struct fb_var_screeninfo *var,
struct fb_info *info)
{
struct pxa168fb_info *fbi = info->par;
int pix_fmt;
/*
* Determine which pixel format we're going to use.
*/
pix_fmt = determine_best_pix_fmt(var);
if (pix_fmt < 0)
return pix_fmt;
set_pix_fmt(var, pix_fmt);
fbi->pix_fmt = pix_fmt;
/*
* Basic geometry sanity checks.
*/
if (var->xoffset + var->xres > var->xres_virtual)
return -EINVAL;
if (var->yoffset + var->yres > var->yres_virtual)
return -EINVAL;
if (var->xres + var->right_margin +
var->hsync_len + var->left_margin > 2048)
return -EINVAL;
if (var->yres + var->lower_margin +
var->vsync_len + var->upper_margin > 2048)
return -EINVAL;
/*
* Check size of framebuffer.
*/
if (var->xres_virtual * var->yres_virtual *
(var->bits_per_pixel >> 3) > info->fix.smem_len)
return -EINVAL;
return 0;
}
/*
* The hardware clock divider has an integer and a fractional
* stage:
*
* clk2 = clk_in / integer_divider
* clk_out = clk2 * (1 - (fractional_divider >> 12))
*
* Calculate integer and fractional divider for given clk_in
* and clk_out.
*/
static void set_clock_divider(struct pxa168fb_info *fbi,
const struct fb_videomode *m)
{
int divider_int;
int needed_pixclk;
u64 div_result;
u32 x = 0;
/*
* Notice: The field pixclock is used by linux fb
* is in pixel second. E.g. struct fb_videomode &
* struct fb_var_screeninfo
*/
/*
* Check input values.
*/
if (!m || !m->pixclock || !m->refresh) {
dev_err(fbi->dev, "Input refresh or pixclock is wrong.\n");
return;
}
/*
* Using PLL/AXI clock.
*/
x = 0x80000000;
/*
* Calc divider according to refresh rate.
*/
div_result = 1000000000000ll;
do_div(div_result, m->pixclock);
needed_pixclk = (u32)div_result;
divider_int = clk_get_rate(fbi->clk) / needed_pixclk;
/* check whether divisor is too small. */
if (divider_int < 2) {
dev_warn(fbi->dev, "Warning: clock source is too slow."
"Try smaller resolution\n");
divider_int = 2;
}
/*
* Set setting to reg.
*/
x |= divider_int;
writel(x, fbi->reg_base + LCD_CFG_SCLK_DIV);
}
static void set_dma_control0(struct pxa168fb_info *fbi)
{
u32 x;
/*
* Set bit to enable graphics DMA.
*/
x = readl(fbi->reg_base + LCD_SPU_DMA_CTRL0);
x &= ~CFG_GRA_ENA_MASK;
x |= fbi->active ? CFG_GRA_ENA(1) : CFG_GRA_ENA(0);
/*
* If we are in a pseudo-color mode, we need to enable
* palette lookup.
*/
if (fbi->pix_fmt == PIX_FMT_PSEUDOCOLOR)
x |= 0x10000000;
/*
* Configure hardware pixel format.
*/
x &= ~(0xF << 16);
x |= (fbi->pix_fmt >> 1) << 16;
/*
* Check red and blue pixel swap.
* 1. source data swap
* 2. panel output data swap
*/
x &= ~(1 << 12);
x |= ((fbi->pix_fmt & 1) ^ (fbi->panel_rbswap)) << 12;
writel(x, fbi->reg_base + LCD_SPU_DMA_CTRL0);
}
static void set_dma_control1(struct pxa168fb_info *fbi, int sync)
{
u32 x;
/*
* Configure default bits: vsync triggers DMA, gated clock
* enable, power save enable, configure alpha registers to
* display 100% graphics, and set pixel command.
*/
x = readl(fbi->reg_base + LCD_SPU_DMA_CTRL1);
x |= 0x2032ff81;
/*
* We trigger DMA on the falling edge of vsync if vsync is
* active low, or on the rising edge if vsync is active high.
*/
if (!(sync & FB_SYNC_VERT_HIGH_ACT))
x |= 0x08000000;
writel(x, fbi->reg_base + LCD_SPU_DMA_CTRL1);
}
static void set_graphics_start(struct fb_info *info, int xoffset, int yoffset)
{
struct pxa168fb_info *fbi = info->par;
struct fb_var_screeninfo *var = &info->var;
int pixel_offset;
unsigned long addr;
pixel_offset = (yoffset * var->xres_virtual) + xoffset;
addr = fbi->fb_start_dma + (pixel_offset * (var->bits_per_pixel >> 3));
writel(addr, fbi->reg_base + LCD_CFG_GRA_START_ADDR0);
}
static void set_dumb_panel_control(struct fb_info *info)
{
struct pxa168fb_info *fbi = info->par;
struct pxa168fb_mach_info *mi = fbi->dev->platform_data;
u32 x;
/*
* Preserve enable flag.
*/
x = readl(fbi->reg_base + LCD_SPU_DUMB_CTRL) & 0x00000001;
x |= (fbi->is_blanked ? 0x7 : mi->dumb_mode) << 28;
x |= mi->gpio_output_data << 20;
x |= mi->gpio_output_mask << 12;
x |= mi->panel_rgb_reverse_lanes ? 0x00000080 : 0;
x |= mi->invert_composite_blank ? 0x00000040 : 0;
x |= (info->var.sync & FB_SYNC_COMP_HIGH_ACT) ? 0x00000020 : 0;
x |= mi->invert_pix_val_ena ? 0x00000010 : 0;
x |= (info->var.sync & FB_SYNC_VERT_HIGH_ACT) ? 0 : 0x00000008;
x |= (info->var.sync & FB_SYNC_HOR_HIGH_ACT) ? 0 : 0x00000004;
x |= mi->invert_pixclock ? 0x00000002 : 0;
writel(x, fbi->reg_base + LCD_SPU_DUMB_CTRL);
}
static void set_dumb_screen_dimensions(struct fb_info *info)
{
struct pxa168fb_info *fbi = info->par;
struct fb_var_screeninfo *v = &info->var;
int x;
int y;
x = v->xres + v->right_margin + v->hsync_len + v->left_margin;
y = v->yres + v->lower_margin + v->vsync_len + v->upper_margin;
writel((y << 16) | x, fbi->reg_base + LCD_SPUT_V_H_TOTAL);
}
static int pxa168fb_set_par(struct fb_info *info)
{
struct pxa168fb_info *fbi = info->par;
struct fb_var_screeninfo *var = &info->var;
struct fb_videomode mode;
u32 x;
struct pxa168fb_mach_info *mi;
mi = fbi->dev->platform_data;
/*
* Set additional mode info.
*/
if (fbi->pix_fmt == PIX_FMT_PSEUDOCOLOR)
info->fix.visual = FB_VISUAL_PSEUDOCOLOR;
else
info->fix.visual = FB_VISUAL_TRUECOLOR;
info->fix.line_length = var->xres_virtual * var->bits_per_pixel / 8;
info->fix.ypanstep = var->yres;
/*
* Disable panel output while we setup the display.
*/
x = readl(fbi->reg_base + LCD_SPU_DUMB_CTRL);
writel(x & ~1, fbi->reg_base + LCD_SPU_DUMB_CTRL);
/*
* Configure global panel parameters.
*/
writel((var->yres << 16) | var->xres,
fbi->reg_base + LCD_SPU_V_H_ACTIVE);
/*
* convet var to video mode
*/
fb_var_to_videomode(&mode, &info->var);
/* Calculate clock divisor. */
set_clock_divider(fbi, &mode);
/* Configure dma ctrl regs. */
set_dma_control0(fbi);
set_dma_control1(fbi, info->var.sync);
/*
* Configure graphics DMA parameters.
*/
x = readl(fbi->reg_base + LCD_CFG_GRA_PITCH);
x = (x & ~0xFFFF) | ((var->xres_virtual * var->bits_per_pixel) >> 3);
writel(x, fbi->reg_base + LCD_CFG_GRA_PITCH);
writel((var->yres << 16) | var->xres,
fbi->reg_base + LCD_SPU_GRA_HPXL_VLN);
writel((var->yres << 16) | var->xres,
fbi->reg_base + LCD_SPU_GZM_HPXL_VLN);
/*
* Configure dumb panel ctrl regs & timings.
*/
set_dumb_panel_control(info);
set_dumb_screen_dimensions(info);
writel((var->left_margin << 16) | var->right_margin,
fbi->reg_base + LCD_SPU_H_PORCH);
writel((var->upper_margin << 16) | var->lower_margin,
fbi->reg_base + LCD_SPU_V_PORCH);
/*
* Re-enable panel output.
*/
x = readl(fbi->reg_base + LCD_SPU_DUMB_CTRL);
writel(x | 1, fbi->reg_base + LCD_SPU_DUMB_CTRL);
return 0;
}
static unsigned int chan_to_field(unsigned int chan, struct fb_bitfield *bf)
{
return ((chan & 0xffff) >> (16 - bf->length)) << bf->offset;
}
static u32 to_rgb(u16 red, u16 green, u16 blue)
{
red >>= 8;
green >>= 8;
blue >>= 8;
return (red << 16) | (green << 8) | blue;
}
static int
pxa168fb_setcolreg(unsigned int regno, unsigned int red, unsigned int green,
unsigned int blue, unsigned int trans, struct fb_info *info)
{
struct pxa168fb_info *fbi = info->par;
u32 val;
if (info->var.grayscale)
red = green = blue = (19595 * red + 38470 * green +
7471 * blue) >> 16;
if (info->fix.visual == FB_VISUAL_TRUECOLOR && regno < 16) {
val = chan_to_field(red, &info->var.red);
val |= chan_to_field(green, &info->var.green);
val |= chan_to_field(blue , &info->var.blue);
fbi->pseudo_palette[regno] = val;
}
if (info->fix.visual == FB_VISUAL_PSEUDOCOLOR && regno < 256) {
val = to_rgb(red, green, blue);
writel(val, fbi->reg_base + LCD_SPU_SRAM_WRDAT);
writel(0x8300 | regno, fbi->reg_base + LCD_SPU_SRAM_CTRL);
}
return 0;
}
static int pxa168fb_blank(int blank, struct fb_info *info)
{
struct pxa168fb_info *fbi = info->par;
fbi->is_blanked = (blank == FB_BLANK_UNBLANK) ? 0 : 1;
set_dumb_panel_control(info);
return 0;
}
static int pxa168fb_pan_display(struct fb_var_screeninfo *var,
struct fb_info *info)
{
set_graphics_start(info, var->xoffset, var->yoffset);
return 0;
}
static irqreturn_t pxa168fb_handle_irq(int irq, void *dev_id)
{
struct pxa168fb_info *fbi = dev_id;
u32 isr = readl(fbi->reg_base + SPU_IRQ_ISR);
if ((isr & GRA_FRAME_IRQ0_ENA_MASK)) {
writel(isr & (~GRA_FRAME_IRQ0_ENA_MASK),
fbi->reg_base + SPU_IRQ_ISR);
return IRQ_HANDLED;
}
return IRQ_NONE;
}
static struct fb_ops pxa168fb_ops = {
.owner = THIS_MODULE,
.fb_check_var = pxa168fb_check_var,
.fb_set_par = pxa168fb_set_par,
.fb_setcolreg = pxa168fb_setcolreg,
.fb_blank = pxa168fb_blank,
.fb_pan_display = pxa168fb_pan_display,
.fb_fillrect = cfb_fillrect,
.fb_copyarea = cfb_copyarea,
.fb_imageblit = cfb_imageblit,
};
static int pxa168fb_init_mode(struct fb_info *info,
struct pxa168fb_mach_info *mi)
{
struct pxa168fb_info *fbi = info->par;
struct fb_var_screeninfo *var = &info->var;
int ret = 0;
u32 total_w, total_h, refresh;
u64 div_result;
const struct fb_videomode *m;
/*
* Set default value
*/
refresh = DEFAULT_REFRESH;
/* try to find best video mode. */
m = fb_find_best_mode(&info->var, &info->modelist);
if (m)
fb_videomode_to_var(&info->var, m);
/* Init settings. */
var->xres_virtual = var->xres;
var->yres_virtual = info->fix.smem_len /
(var->xres_virtual * (var->bits_per_pixel >> 3));
dev_dbg(fbi->dev, "pxa168fb: find best mode: res = %dx%d\n",
var->xres, var->yres);
/* correct pixclock. */
total_w = var->xres + var->left_margin + var->right_margin +
var->hsync_len;
total_h = var->yres + var->upper_margin + var->lower_margin +
var->vsync_len;
div_result = 1000000000000ll;
do_div(div_result, total_w * total_h * refresh);
var->pixclock = (u32)div_result;
return ret;
}
static int pxa168fb_probe(struct platform_device *pdev)
{
struct pxa168fb_mach_info *mi;
struct fb_info *info = 0;
struct pxa168fb_info *fbi = 0;
struct resource *res;
struct clk *clk;
int irq, ret;
mi = pdev->dev.platform_data;
if (mi == NULL) {
dev_err(&pdev->dev, "no platform data defined\n");
return -EINVAL;
}
clk = clk_get(&pdev->dev, "LCDCLK");
if (IS_ERR(clk)) {
dev_err(&pdev->dev, "unable to get LCDCLK");
return PTR_ERR(clk);
}
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (res == NULL) {
dev_err(&pdev->dev, "no IO memory defined\n");
ret = -ENOENT;
goto failed_put_clk;
}
irq = platform_get_irq(pdev, 0);
if (irq < 0) {
dev_err(&pdev->dev, "no IRQ defined\n");
ret = -ENOENT;
goto failed_put_clk;
}
info = framebuffer_alloc(sizeof(struct pxa168fb_info), &pdev->dev);
if (info == NULL) {
ret = -ENOMEM;
goto failed_put_clk;
}
/* Initialize private data */
fbi = info->par;
fbi->info = info;
fbi->clk = clk;
fbi->dev = info->dev = &pdev->dev;
fbi->panel_rbswap = mi->panel_rbswap;
fbi->is_blanked = 0;
fbi->active = mi->active;
/*
* Initialise static fb parameters.
*/
info->flags = FBINFO_DEFAULT | FBINFO_PARTIAL_PAN_OK |
FBINFO_HWACCEL_XPAN | FBINFO_HWACCEL_YPAN;
info->node = -1;
strlcpy(info->fix.id, mi->id, 16);
info->fix.type = FB_TYPE_PACKED_PIXELS;
info->fix.type_aux = 0;
info->fix.xpanstep = 0;
info->fix.ypanstep = 0;
info->fix.ywrapstep = 0;
info->fix.mmio_start = res->start;
info->fix.mmio_len = resource_size(res);
info->fix.accel = FB_ACCEL_NONE;
info->fbops = &pxa168fb_ops;
info->pseudo_palette = fbi->pseudo_palette;
/*
* Map LCD controller registers.
*/
fbi->reg_base = devm_ioremap_nocache(&pdev->dev, res->start,
resource_size(res));
if (fbi->reg_base == NULL) {
ret = -ENOMEM;
goto failed_free_info;
}
/*
* Allocate framebuffer memory.
*/
info->fix.smem_len = PAGE_ALIGN(DEFAULT_FB_SIZE);
info->screen_base = dma_alloc_writecombine(fbi->dev, info->fix.smem_len,
&fbi->fb_start_dma, GFP_KERNEL);
if (info->screen_base == NULL) {
ret = -ENOMEM;
goto failed_free_info;
}
info->fix.smem_start = (unsigned long)fbi->fb_start_dma;
set_graphics_start(info, 0, 0);
/*
* Set video mode according to platform data.
*/
set_mode(fbi, &info->var, mi->modes, mi->pix_fmt, 1);
fb_videomode_to_modelist(mi->modes, mi->num_modes, &info->modelist);
/*
* init video mode data.
*/
pxa168fb_init_mode(info, mi);
/*
* Fill in sane defaults.
*/
ret = pxa168fb_check_var(&info->var, info);
if (ret)
goto failed_free_fbmem;
/*
* enable controller clock
*/
clk_enable(fbi->clk);
pxa168fb_set_par(info);
/*
* Configure default register values.
*/
writel(0, fbi->reg_base + LCD_SPU_BLANKCOLOR);
writel(mi->io_pin_allocation_mode, fbi->reg_base + SPU_IOPAD_CONTROL);
writel(0, fbi->reg_base + LCD_CFG_GRA_START_ADDR1);
writel(0, fbi->reg_base + LCD_SPU_GRA_OVSA_HPXL_VLN);
writel(0, fbi->reg_base + LCD_SPU_SRAM_PARA0);
writel(CFG_CSB_256x32(0x1)|CFG_CSB_256x24(0x1)|CFG_CSB_256x8(0x1),
fbi->reg_base + LCD_SPU_SRAM_PARA1);
/*
* Allocate color map.
*/
if (fb_alloc_cmap(&info->cmap, 256, 0) < 0) {
ret = -ENOMEM;
goto failed_free_clk;
}
/*
* Register irq handler.
*/
ret = devm_request_irq(&pdev->dev, irq, pxa168fb_handle_irq,
IRQF_SHARED, info->fix.id, fbi);
if (ret < 0) {
dev_err(&pdev->dev, "unable to request IRQ\n");
ret = -ENXIO;
goto failed_free_cmap;
}
/*
* Enable GFX interrupt
*/
writel(GRA_FRAME_IRQ0_ENA(0x1), fbi->reg_base + SPU_IRQ_ENA);
/*
* Register framebuffer.
*/
ret = register_framebuffer(info);
if (ret < 0) {
dev_err(&pdev->dev, "Failed to register pxa168-fb: %d\n", ret);
ret = -ENXIO;
goto failed_free_cmap;
}
platform_set_drvdata(pdev, fbi);
return 0;
failed_free_cmap:
fb_dealloc_cmap(&info->cmap);
failed_free_clk:
clk_disable(fbi->clk);
failed_free_fbmem:
dma_free_coherent(fbi->dev, info->fix.smem_len,
info->screen_base, fbi->fb_start_dma);
failed_free_info:
kfree(info);
failed_put_clk:
clk_put(clk);
dev_err(&pdev->dev, "frame buffer device init failed with %d\n", ret);
return ret;
}
static int pxa168fb_remove(struct platform_device *pdev)
{
struct pxa168fb_info *fbi = platform_get_drvdata(pdev);
struct fb_info *info;
int irq;
unsigned int data;
if (!fbi)
return 0;
/* disable DMA transfer */
data = readl(fbi->reg_base + LCD_SPU_DMA_CTRL0);
data &= ~CFG_GRA_ENA_MASK;
writel(data, fbi->reg_base + LCD_SPU_DMA_CTRL0);
info = fbi->info;
unregister_framebuffer(info);
writel(GRA_FRAME_IRQ0_ENA(0x0), fbi->reg_base + SPU_IRQ_ENA);
if (info->cmap.len)
fb_dealloc_cmap(&info->cmap);
irq = platform_get_irq(pdev, 0);
dma_free_writecombine(fbi->dev, PAGE_ALIGN(info->fix.smem_len),
info->screen_base, info->fix.smem_start);
clk_disable(fbi->clk);
clk_put(fbi->clk);
framebuffer_release(info);
return 0;
}
static struct platform_driver pxa168fb_driver = {
.driver = {
.name = "pxa168-fb",
.owner = THIS_MODULE,
},
.probe = pxa168fb_probe,
.remove = pxa168fb_remove,
};
module_platform_driver(pxa168fb_driver);
MODULE_AUTHOR("Lennert Buytenhek <buytenh@marvell.com> "
"Green Wan <gwan@marvell.com>");
MODULE_DESCRIPTION("Framebuffer driver for PXA168/910");
MODULE_LICENSE("GPL");
| gpl-2.0 |
PureNexusProject/android_kernel_asus_fugu | drivers/tty/hvc/hvc_opal.c | 2399 | 10705 | /*
* opal driver interface to hvc_console.c
*
* Copyright 2011 Benjamin Herrenschmidt <benh@kernel.crashing.org>, IBM 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; 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
*
*/
#undef DEBUG
#include <linux/types.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/console.h>
#include <linux/of.h>
#include <linux/of_platform.h>
#include <linux/export.h>
#include <asm/hvconsole.h>
#include <asm/prom.h>
#include <asm/firmware.h>
#include <asm/hvsi.h>
#include <asm/udbg.h>
#include <asm/opal.h>
#include "hvc_console.h"
static const char hvc_opal_name[] = "hvc_opal";
static struct of_device_id hvc_opal_match[] = {
{ .name = "serial", .compatible = "ibm,opal-console-raw" },
{ .name = "serial", .compatible = "ibm,opal-console-hvsi" },
{ },
};
typedef enum hv_protocol {
HV_PROTOCOL_RAW,
HV_PROTOCOL_HVSI
} hv_protocol_t;
struct hvc_opal_priv {
hv_protocol_t proto; /* Raw data or HVSI packets */
struct hvsi_priv hvsi; /* HVSI specific data */
};
static struct hvc_opal_priv *hvc_opal_privs[MAX_NR_HVC_CONSOLES];
/* For early boot console */
static struct hvc_opal_priv hvc_opal_boot_priv;
static u32 hvc_opal_boot_termno;
static const struct hv_ops hvc_opal_raw_ops = {
.get_chars = opal_get_chars,
.put_chars = opal_put_chars,
.notifier_add = notifier_add_irq,
.notifier_del = notifier_del_irq,
.notifier_hangup = notifier_hangup_irq,
};
static int hvc_opal_hvsi_get_chars(uint32_t vtermno, char *buf, int count)
{
struct hvc_opal_priv *pv = hvc_opal_privs[vtermno];
if (WARN_ON(!pv))
return -ENODEV;
return hvsilib_get_chars(&pv->hvsi, buf, count);
}
static int hvc_opal_hvsi_put_chars(uint32_t vtermno, const char *buf, int count)
{
struct hvc_opal_priv *pv = hvc_opal_privs[vtermno];
if (WARN_ON(!pv))
return -ENODEV;
return hvsilib_put_chars(&pv->hvsi, buf, count);
}
static int hvc_opal_hvsi_open(struct hvc_struct *hp, int data)
{
struct hvc_opal_priv *pv = hvc_opal_privs[hp->vtermno];
int rc;
pr_devel("HVSI@%x: do open !\n", hp->vtermno);
rc = notifier_add_irq(hp, data);
if (rc)
return rc;
return hvsilib_open(&pv->hvsi, hp);
}
static void hvc_opal_hvsi_close(struct hvc_struct *hp, int data)
{
struct hvc_opal_priv *pv = hvc_opal_privs[hp->vtermno];
pr_devel("HVSI@%x: do close !\n", hp->vtermno);
hvsilib_close(&pv->hvsi, hp);
notifier_del_irq(hp, data);
}
void hvc_opal_hvsi_hangup(struct hvc_struct *hp, int data)
{
struct hvc_opal_priv *pv = hvc_opal_privs[hp->vtermno];
pr_devel("HVSI@%x: do hangup !\n", hp->vtermno);
hvsilib_close(&pv->hvsi, hp);
notifier_hangup_irq(hp, data);
}
static int hvc_opal_hvsi_tiocmget(struct hvc_struct *hp)
{
struct hvc_opal_priv *pv = hvc_opal_privs[hp->vtermno];
if (!pv)
return -EINVAL;
return pv->hvsi.mctrl;
}
static int hvc_opal_hvsi_tiocmset(struct hvc_struct *hp, unsigned int set,
unsigned int clear)
{
struct hvc_opal_priv *pv = hvc_opal_privs[hp->vtermno];
pr_devel("HVSI@%x: Set modem control, set=%x,clr=%x\n",
hp->vtermno, set, clear);
if (set & TIOCM_DTR)
hvsilib_write_mctrl(&pv->hvsi, 1);
else if (clear & TIOCM_DTR)
hvsilib_write_mctrl(&pv->hvsi, 0);
return 0;
}
static const struct hv_ops hvc_opal_hvsi_ops = {
.get_chars = hvc_opal_hvsi_get_chars,
.put_chars = hvc_opal_hvsi_put_chars,
.notifier_add = hvc_opal_hvsi_open,
.notifier_del = hvc_opal_hvsi_close,
.notifier_hangup = hvc_opal_hvsi_hangup,
.tiocmget = hvc_opal_hvsi_tiocmget,
.tiocmset = hvc_opal_hvsi_tiocmset,
};
static int hvc_opal_probe(struct platform_device *dev)
{
const struct hv_ops *ops;
struct hvc_struct *hp;
struct hvc_opal_priv *pv;
hv_protocol_t proto;
unsigned int termno, boot = 0;
const __be32 *reg;
if (of_device_is_compatible(dev->dev.of_node, "ibm,opal-console-raw")) {
proto = HV_PROTOCOL_RAW;
ops = &hvc_opal_raw_ops;
} else if (of_device_is_compatible(dev->dev.of_node,
"ibm,opal-console-hvsi")) {
proto = HV_PROTOCOL_HVSI;
ops = &hvc_opal_hvsi_ops;
} else {
pr_err("hvc_opal: Unknown protocol for %s\n",
dev->dev.of_node->full_name);
return -ENXIO;
}
reg = of_get_property(dev->dev.of_node, "reg", NULL);
termno = reg ? be32_to_cpup(reg) : 0;
/* Is it our boot one ? */
if (hvc_opal_privs[termno] == &hvc_opal_boot_priv) {
pv = hvc_opal_privs[termno];
boot = 1;
} else if (hvc_opal_privs[termno] == NULL) {
pv = kzalloc(sizeof(struct hvc_opal_priv), GFP_KERNEL);
if (!pv)
return -ENOMEM;
pv->proto = proto;
hvc_opal_privs[termno] = pv;
if (proto == HV_PROTOCOL_HVSI)
hvsilib_init(&pv->hvsi, opal_get_chars, opal_put_chars,
termno, 0);
/* Instanciate now to establish a mapping index==vtermno */
hvc_instantiate(termno, termno, ops);
} else {
pr_err("hvc_opal: Device %s has duplicate terminal number #%d\n",
dev->dev.of_node->full_name, termno);
return -ENXIO;
}
pr_info("hvc%d: %s protocol on %s%s\n", termno,
proto == HV_PROTOCOL_RAW ? "raw" : "hvsi",
dev->dev.of_node->full_name,
boot ? " (boot console)" : "");
/* We don't do IRQ yet */
hp = hvc_alloc(termno, 0, ops, MAX_VIO_PUT_CHARS);
if (IS_ERR(hp))
return PTR_ERR(hp);
dev_set_drvdata(&dev->dev, hp);
return 0;
}
static int hvc_opal_remove(struct platform_device *dev)
{
struct hvc_struct *hp = dev_get_drvdata(&dev->dev);
int rc, termno;
termno = hp->vtermno;
rc = hvc_remove(hp);
if (rc == 0) {
if (hvc_opal_privs[termno] != &hvc_opal_boot_priv)
kfree(hvc_opal_privs[termno]);
hvc_opal_privs[termno] = NULL;
}
return rc;
}
static struct platform_driver hvc_opal_driver = {
.probe = hvc_opal_probe,
.remove = hvc_opal_remove,
.driver = {
.name = hvc_opal_name,
.owner = THIS_MODULE,
.of_match_table = hvc_opal_match,
}
};
static int __init hvc_opal_init(void)
{
if (!firmware_has_feature(FW_FEATURE_OPAL))
return -ENODEV;
/* Register as a vio device to receive callbacks */
return platform_driver_register(&hvc_opal_driver);
}
module_init(hvc_opal_init);
static void __exit hvc_opal_exit(void)
{
platform_driver_unregister(&hvc_opal_driver);
}
module_exit(hvc_opal_exit);
static void udbg_opal_putc(char c)
{
unsigned int termno = hvc_opal_boot_termno;
int count = -1;
if (c == '\n')
udbg_opal_putc('\r');
do {
switch(hvc_opal_boot_priv.proto) {
case HV_PROTOCOL_RAW:
count = opal_put_chars(termno, &c, 1);
break;
case HV_PROTOCOL_HVSI:
count = hvc_opal_hvsi_put_chars(termno, &c, 1);
break;
}
} while(count == 0 || count == -EAGAIN);
}
static int udbg_opal_getc_poll(void)
{
unsigned int termno = hvc_opal_boot_termno;
int rc = 0;
char c;
switch(hvc_opal_boot_priv.proto) {
case HV_PROTOCOL_RAW:
rc = opal_get_chars(termno, &c, 1);
break;
case HV_PROTOCOL_HVSI:
rc = hvc_opal_hvsi_get_chars(termno, &c, 1);
break;
}
if (!rc)
return -1;
return c;
}
static int udbg_opal_getc(void)
{
int ch;
for (;;) {
ch = udbg_opal_getc_poll();
if (ch == -1) {
/* This shouldn't be needed...but... */
volatile unsigned long delay;
for (delay=0; delay < 2000000; delay++)
;
} else {
return ch;
}
}
}
static void udbg_init_opal_common(void)
{
udbg_putc = udbg_opal_putc;
udbg_getc = udbg_opal_getc;
udbg_getc_poll = udbg_opal_getc_poll;
tb_ticks_per_usec = 0x200; /* Make udelay not suck */
}
void __init hvc_opal_init_early(void)
{
struct device_node *stdout_node = NULL;
const u32 *termno;
const char *name = NULL;
const struct hv_ops *ops;
u32 index;
/* find the boot console from /chosen/stdout */
if (of_chosen)
name = of_get_property(of_chosen, "linux,stdout-path", NULL);
if (name) {
stdout_node = of_find_node_by_path(name);
if (!stdout_node) {
pr_err("hvc_opal: Failed to locate default console!\n");
return;
}
} else {
struct device_node *opal, *np;
/* Current OPAL takeover doesn't provide the stdout
* path, so we hard wire it
*/
opal = of_find_node_by_path("/ibm,opal/consoles");
if (opal)
pr_devel("hvc_opal: Found consoles in new location\n");
if (!opal) {
opal = of_find_node_by_path("/ibm,opal");
if (opal)
pr_devel("hvc_opal: "
"Found consoles in old location\n");
}
if (!opal)
return;
for_each_child_of_node(opal, np) {
if (!strcmp(np->name, "serial")) {
stdout_node = np;
break;
}
}
of_node_put(opal);
}
if (!stdout_node)
return;
termno = of_get_property(stdout_node, "reg", NULL);
index = termno ? *termno : 0;
if (index >= MAX_NR_HVC_CONSOLES)
return;
hvc_opal_privs[index] = &hvc_opal_boot_priv;
/* Check the protocol */
if (of_device_is_compatible(stdout_node, "ibm,opal-console-raw")) {
hvc_opal_boot_priv.proto = HV_PROTOCOL_RAW;
ops = &hvc_opal_raw_ops;
pr_devel("hvc_opal: Found RAW console\n");
}
else if (of_device_is_compatible(stdout_node,"ibm,opal-console-hvsi")) {
hvc_opal_boot_priv.proto = HV_PROTOCOL_HVSI;
ops = &hvc_opal_hvsi_ops;
hvsilib_init(&hvc_opal_boot_priv.hvsi, opal_get_chars,
opal_put_chars, index, 1);
/* HVSI, perform the handshake now */
hvsilib_establish(&hvc_opal_boot_priv.hvsi);
pr_devel("hvc_opal: Found HVSI console\n");
} else
goto out;
hvc_opal_boot_termno = index;
udbg_init_opal_common();
add_preferred_console("hvc", index, NULL);
hvc_instantiate(index, index, ops);
out:
of_node_put(stdout_node);
}
#ifdef CONFIG_PPC_EARLY_DEBUG_OPAL_RAW
void __init udbg_init_debug_opal_raw(void)
{
u32 index = CONFIG_PPC_EARLY_DEBUG_OPAL_VTERMNO;
hvc_opal_privs[index] = &hvc_opal_boot_priv;
hvc_opal_boot_priv.proto = HV_PROTOCOL_RAW;
hvc_opal_boot_termno = index;
udbg_init_opal_common();
}
#endif /* CONFIG_PPC_EARLY_DEBUG_OPAL_RAW */
#ifdef CONFIG_PPC_EARLY_DEBUG_OPAL_HVSI
void __init udbg_init_debug_opal_hvsi(void)
{
u32 index = CONFIG_PPC_EARLY_DEBUG_OPAL_VTERMNO;
hvc_opal_privs[index] = &hvc_opal_boot_priv;
hvc_opal_boot_termno = index;
udbg_init_opal_common();
hvsilib_init(&hvc_opal_boot_priv.hvsi, opal_get_chars, opal_put_chars,
index, 1);
hvsilib_establish(&hvc_opal_boot_priv.hvsi);
}
#endif /* CONFIG_PPC_EARLY_DEBUG_OPAL_HVSI */
| gpl-2.0 |
zparallax/amplitude_shamu | drivers/clk/ux500/clk-prcc.c | 3167 | 3681 | /*
* PRCC clock implementation for ux500 platform.
*
* Copyright (C) 2012 ST-Ericsson SA
* Author: Ulf Hansson <ulf.hansson@linaro.org>
*
* License terms: GNU General Public License (GPL) version 2
*/
#include <linux/clk-provider.h>
#include <linux/clk-private.h>
#include <linux/slab.h>
#include <linux/io.h>
#include <linux/err.h>
#include <linux/types.h>
#include "clk.h"
#define PRCC_PCKEN 0x000
#define PRCC_PCKDIS 0x004
#define PRCC_KCKEN 0x008
#define PRCC_KCKDIS 0x00C
#define PRCC_PCKSR 0x010
#define PRCC_KCKSR 0x014
#define to_clk_prcc(_hw) container_of(_hw, struct clk_prcc, hw)
struct clk_prcc {
struct clk_hw hw;
void __iomem *base;
u32 cg_sel;
int is_enabled;
};
/* PRCC clock operations. */
static int clk_prcc_pclk_enable(struct clk_hw *hw)
{
struct clk_prcc *clk = to_clk_prcc(hw);
writel(clk->cg_sel, (clk->base + PRCC_PCKEN));
while (!(readl(clk->base + PRCC_PCKSR) & clk->cg_sel))
cpu_relax();
clk->is_enabled = 1;
return 0;
}
static void clk_prcc_pclk_disable(struct clk_hw *hw)
{
struct clk_prcc *clk = to_clk_prcc(hw);
writel(clk->cg_sel, (clk->base + PRCC_PCKDIS));
clk->is_enabled = 0;
}
static int clk_prcc_kclk_enable(struct clk_hw *hw)
{
struct clk_prcc *clk = to_clk_prcc(hw);
writel(clk->cg_sel, (clk->base + PRCC_KCKEN));
while (!(readl(clk->base + PRCC_KCKSR) & clk->cg_sel))
cpu_relax();
clk->is_enabled = 1;
return 0;
}
static void clk_prcc_kclk_disable(struct clk_hw *hw)
{
struct clk_prcc *clk = to_clk_prcc(hw);
writel(clk->cg_sel, (clk->base + PRCC_KCKDIS));
clk->is_enabled = 0;
}
static int clk_prcc_is_enabled(struct clk_hw *hw)
{
struct clk_prcc *clk = to_clk_prcc(hw);
return clk->is_enabled;
}
static struct clk_ops clk_prcc_pclk_ops = {
.enable = clk_prcc_pclk_enable,
.disable = clk_prcc_pclk_disable,
.is_enabled = clk_prcc_is_enabled,
};
static struct clk_ops clk_prcc_kclk_ops = {
.enable = clk_prcc_kclk_enable,
.disable = clk_prcc_kclk_disable,
.is_enabled = clk_prcc_is_enabled,
};
static struct clk *clk_reg_prcc(const char *name,
const char *parent_name,
resource_size_t phy_base,
u32 cg_sel,
unsigned long flags,
struct clk_ops *clk_prcc_ops)
{
struct clk_prcc *clk;
struct clk_init_data clk_prcc_init;
struct clk *clk_reg;
if (!name) {
pr_err("clk_prcc: %s invalid arguments passed\n", __func__);
return ERR_PTR(-EINVAL);
}
clk = kzalloc(sizeof(struct clk_prcc), GFP_KERNEL);
if (!clk) {
pr_err("clk_prcc: %s could not allocate clk\n", __func__);
return ERR_PTR(-ENOMEM);
}
clk->base = ioremap(phy_base, SZ_4K);
if (!clk->base)
goto free_clk;
clk->cg_sel = cg_sel;
clk->is_enabled = 1;
clk_prcc_init.name = name;
clk_prcc_init.ops = clk_prcc_ops;
clk_prcc_init.flags = flags;
clk_prcc_init.parent_names = (parent_name ? &parent_name : NULL);
clk_prcc_init.num_parents = (parent_name ? 1 : 0);
clk->hw.init = &clk_prcc_init;
clk_reg = clk_register(NULL, &clk->hw);
if (IS_ERR_OR_NULL(clk_reg))
goto unmap_clk;
return clk_reg;
unmap_clk:
iounmap(clk->base);
free_clk:
kfree(clk);
pr_err("clk_prcc: %s failed to register clk\n", __func__);
return ERR_PTR(-ENOMEM);
}
struct clk *clk_reg_prcc_pclk(const char *name,
const char *parent_name,
resource_size_t phy_base,
u32 cg_sel,
unsigned long flags)
{
return clk_reg_prcc(name, parent_name, phy_base, cg_sel, flags,
&clk_prcc_pclk_ops);
}
struct clk *clk_reg_prcc_kclk(const char *name,
const char *parent_name,
resource_size_t phy_base,
u32 cg_sel,
unsigned long flags)
{
return clk_reg_prcc(name, parent_name, phy_base, cg_sel, flags,
&clk_prcc_kclk_ops);
}
| gpl-2.0 |
djvoleur/G92XP-R4_COI9 | fs/lockd/host.c | 3679 | 17334 | /*
* linux/fs/lockd/host.c
*
* Management for NLM peer hosts. The nlm_host struct is shared
* between client and server implementation. The only reason to
* do so is to reduce code bloat.
*
* Copyright (C) 1996, Olaf Kirch <okir@monad.swb.de>
*/
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/in.h>
#include <linux/in6.h>
#include <linux/sunrpc/clnt.h>
#include <linux/sunrpc/addr.h>
#include <linux/sunrpc/svc.h>
#include <linux/lockd/lockd.h>
#include <linux/mutex.h>
#include <linux/sunrpc/svc_xprt.h>
#include <net/ipv6.h>
#include "netns.h"
#define NLMDBG_FACILITY NLMDBG_HOSTCACHE
#define NLM_HOST_NRHASH 32
#define NLM_HOST_REBIND (60 * HZ)
#define NLM_HOST_EXPIRE (300 * HZ)
#define NLM_HOST_COLLECT (120 * HZ)
static struct hlist_head nlm_server_hosts[NLM_HOST_NRHASH];
static struct hlist_head nlm_client_hosts[NLM_HOST_NRHASH];
#define for_each_host(host, chain, table) \
for ((chain) = (table); \
(chain) < (table) + NLM_HOST_NRHASH; ++(chain)) \
hlist_for_each_entry((host), (chain), h_hash)
#define for_each_host_safe(host, next, chain, table) \
for ((chain) = (table); \
(chain) < (table) + NLM_HOST_NRHASH; ++(chain)) \
hlist_for_each_entry_safe((host), (next), \
(chain), h_hash)
static unsigned long nrhosts;
static DEFINE_MUTEX(nlm_host_mutex);
static void nlm_gc_hosts(struct net *net);
struct nlm_lookup_host_info {
const int server; /* search for server|client */
const struct sockaddr *sap; /* address to search for */
const size_t salen; /* it's length */
const unsigned short protocol; /* transport to search for*/
const u32 version; /* NLM version to search for */
const char *hostname; /* remote's hostname */
const size_t hostname_len; /* it's length */
const int noresvport; /* use non-priv port */
struct net *net; /* network namespace to bind */
};
/*
* Hash function must work well on big- and little-endian platforms
*/
static unsigned int __nlm_hash32(const __be32 n)
{
unsigned int hash = (__force u32)n ^ ((__force u32)n >> 16);
return hash ^ (hash >> 8);
}
static unsigned int __nlm_hash_addr4(const struct sockaddr *sap)
{
const struct sockaddr_in *sin = (struct sockaddr_in *)sap;
return __nlm_hash32(sin->sin_addr.s_addr);
}
static unsigned int __nlm_hash_addr6(const struct sockaddr *sap)
{
const struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sap;
const struct in6_addr addr = sin6->sin6_addr;
return __nlm_hash32(addr.s6_addr32[0]) ^
__nlm_hash32(addr.s6_addr32[1]) ^
__nlm_hash32(addr.s6_addr32[2]) ^
__nlm_hash32(addr.s6_addr32[3]);
}
static unsigned int nlm_hash_address(const struct sockaddr *sap)
{
unsigned int hash;
switch (sap->sa_family) {
case AF_INET:
hash = __nlm_hash_addr4(sap);
break;
case AF_INET6:
hash = __nlm_hash_addr6(sap);
break;
default:
hash = 0;
}
return hash & (NLM_HOST_NRHASH - 1);
}
/*
* Allocate and initialize an nlm_host. Common to both client and server.
*/
static struct nlm_host *nlm_alloc_host(struct nlm_lookup_host_info *ni,
struct nsm_handle *nsm)
{
struct nlm_host *host = NULL;
unsigned long now = jiffies;
if (nsm != NULL)
atomic_inc(&nsm->sm_count);
else {
host = NULL;
nsm = nsm_get_handle(ni->sap, ni->salen,
ni->hostname, ni->hostname_len);
if (unlikely(nsm == NULL)) {
dprintk("lockd: %s failed; no nsm handle\n",
__func__);
goto out;
}
}
host = kmalloc(sizeof(*host), GFP_KERNEL);
if (unlikely(host == NULL)) {
dprintk("lockd: %s failed; no memory\n", __func__);
nsm_release(nsm);
goto out;
}
memcpy(nlm_addr(host), ni->sap, ni->salen);
host->h_addrlen = ni->salen;
rpc_set_port(nlm_addr(host), 0);
host->h_srcaddrlen = 0;
host->h_rpcclnt = NULL;
host->h_name = nsm->sm_name;
host->h_version = ni->version;
host->h_proto = ni->protocol;
host->h_reclaiming = 0;
host->h_server = ni->server;
host->h_noresvport = ni->noresvport;
host->h_inuse = 0;
init_waitqueue_head(&host->h_gracewait);
init_rwsem(&host->h_rwsem);
host->h_state = 0;
host->h_nsmstate = 0;
host->h_pidcount = 0;
atomic_set(&host->h_count, 1);
mutex_init(&host->h_mutex);
host->h_nextrebind = now + NLM_HOST_REBIND;
host->h_expires = now + NLM_HOST_EXPIRE;
INIT_LIST_HEAD(&host->h_lockowners);
spin_lock_init(&host->h_lock);
INIT_LIST_HEAD(&host->h_granted);
INIT_LIST_HEAD(&host->h_reclaim);
host->h_nsmhandle = nsm;
host->h_addrbuf = nsm->sm_addrbuf;
host->net = ni->net;
out:
return host;
}
/*
* Destroy an nlm_host and free associated resources
*
* Caller must hold nlm_host_mutex.
*/
static void nlm_destroy_host_locked(struct nlm_host *host)
{
struct rpc_clnt *clnt;
struct lockd_net *ln = net_generic(host->net, lockd_net_id);
dprintk("lockd: destroy host %s\n", host->h_name);
hlist_del_init(&host->h_hash);
nsm_unmonitor(host);
nsm_release(host->h_nsmhandle);
clnt = host->h_rpcclnt;
if (clnt != NULL)
rpc_shutdown_client(clnt);
kfree(host);
ln->nrhosts--;
nrhosts--;
}
/**
* nlmclnt_lookup_host - Find an NLM host handle matching a remote server
* @sap: network address of server
* @salen: length of server address
* @protocol: transport protocol to use
* @version: NLM protocol version
* @hostname: '\0'-terminated hostname of server
* @noresvport: 1 if non-privileged port should be used
*
* Returns an nlm_host structure that matches the passed-in
* [server address, transport protocol, NLM version, server hostname].
* If one doesn't already exist in the host cache, a new handle is
* created and returned.
*/
struct nlm_host *nlmclnt_lookup_host(const struct sockaddr *sap,
const size_t salen,
const unsigned short protocol,
const u32 version,
const char *hostname,
int noresvport,
struct net *net)
{
struct nlm_lookup_host_info ni = {
.server = 0,
.sap = sap,
.salen = salen,
.protocol = protocol,
.version = version,
.hostname = hostname,
.hostname_len = strlen(hostname),
.noresvport = noresvport,
.net = net,
};
struct hlist_head *chain;
struct nlm_host *host;
struct nsm_handle *nsm = NULL;
struct lockd_net *ln = net_generic(net, lockd_net_id);
dprintk("lockd: %s(host='%s', vers=%u, proto=%s)\n", __func__,
(hostname ? hostname : "<none>"), version,
(protocol == IPPROTO_UDP ? "udp" : "tcp"));
mutex_lock(&nlm_host_mutex);
chain = &nlm_client_hosts[nlm_hash_address(sap)];
hlist_for_each_entry(host, chain, h_hash) {
if (host->net != net)
continue;
if (!rpc_cmp_addr(nlm_addr(host), sap))
continue;
/* Same address. Share an NSM handle if we already have one */
if (nsm == NULL)
nsm = host->h_nsmhandle;
if (host->h_proto != protocol)
continue;
if (host->h_version != version)
continue;
nlm_get_host(host);
dprintk("lockd: %s found host %s (%s)\n", __func__,
host->h_name, host->h_addrbuf);
goto out;
}
host = nlm_alloc_host(&ni, nsm);
if (unlikely(host == NULL))
goto out;
hlist_add_head(&host->h_hash, chain);
ln->nrhosts++;
nrhosts++;
dprintk("lockd: %s created host %s (%s)\n", __func__,
host->h_name, host->h_addrbuf);
out:
mutex_unlock(&nlm_host_mutex);
return host;
}
/**
* nlmclnt_release_host - release client nlm_host
* @host: nlm_host to release
*
*/
void nlmclnt_release_host(struct nlm_host *host)
{
if (host == NULL)
return;
dprintk("lockd: release client host %s\n", host->h_name);
WARN_ON_ONCE(host->h_server);
if (atomic_dec_and_test(&host->h_count)) {
WARN_ON_ONCE(!list_empty(&host->h_lockowners));
WARN_ON_ONCE(!list_empty(&host->h_granted));
WARN_ON_ONCE(!list_empty(&host->h_reclaim));
mutex_lock(&nlm_host_mutex);
nlm_destroy_host_locked(host);
mutex_unlock(&nlm_host_mutex);
}
}
/**
* nlmsvc_lookup_host - Find an NLM host handle matching a remote client
* @rqstp: incoming NLM request
* @hostname: name of client host
* @hostname_len: length of client hostname
*
* Returns an nlm_host structure that matches the [client address,
* transport protocol, NLM version, client hostname] of the passed-in
* NLM request. If one doesn't already exist in the host cache, a
* new handle is created and returned.
*
* Before possibly creating a new nlm_host, construct a sockaddr
* for a specific source address in case the local system has
* multiple network addresses. The family of the address in
* rq_daddr is guaranteed to be the same as the family of the
* address in rq_addr, so it's safe to use the same family for
* the source address.
*/
struct nlm_host *nlmsvc_lookup_host(const struct svc_rqst *rqstp,
const char *hostname,
const size_t hostname_len)
{
struct hlist_head *chain;
struct nlm_host *host = NULL;
struct nsm_handle *nsm = NULL;
struct sockaddr *src_sap = svc_daddr(rqstp);
size_t src_len = rqstp->rq_daddrlen;
struct net *net = SVC_NET(rqstp);
struct nlm_lookup_host_info ni = {
.server = 1,
.sap = svc_addr(rqstp),
.salen = rqstp->rq_addrlen,
.protocol = rqstp->rq_prot,
.version = rqstp->rq_vers,
.hostname = hostname,
.hostname_len = hostname_len,
.net = net,
};
struct lockd_net *ln = net_generic(net, lockd_net_id);
dprintk("lockd: %s(host='%*s', vers=%u, proto=%s)\n", __func__,
(int)hostname_len, hostname, rqstp->rq_vers,
(rqstp->rq_prot == IPPROTO_UDP ? "udp" : "tcp"));
mutex_lock(&nlm_host_mutex);
if (time_after_eq(jiffies, ln->next_gc))
nlm_gc_hosts(net);
chain = &nlm_server_hosts[nlm_hash_address(ni.sap)];
hlist_for_each_entry(host, chain, h_hash) {
if (host->net != net)
continue;
if (!rpc_cmp_addr(nlm_addr(host), ni.sap))
continue;
/* Same address. Share an NSM handle if we already have one */
if (nsm == NULL)
nsm = host->h_nsmhandle;
if (host->h_proto != ni.protocol)
continue;
if (host->h_version != ni.version)
continue;
if (!rpc_cmp_addr(nlm_srcaddr(host), src_sap))
continue;
/* Move to head of hash chain. */
hlist_del(&host->h_hash);
hlist_add_head(&host->h_hash, chain);
nlm_get_host(host);
dprintk("lockd: %s found host %s (%s)\n",
__func__, host->h_name, host->h_addrbuf);
goto out;
}
host = nlm_alloc_host(&ni, nsm);
if (unlikely(host == NULL))
goto out;
memcpy(nlm_srcaddr(host), src_sap, src_len);
host->h_srcaddrlen = src_len;
hlist_add_head(&host->h_hash, chain);
ln->nrhosts++;
nrhosts++;
dprintk("lockd: %s created host %s (%s)\n",
__func__, host->h_name, host->h_addrbuf);
out:
mutex_unlock(&nlm_host_mutex);
return host;
}
/**
* nlmsvc_release_host - release server nlm_host
* @host: nlm_host to release
*
* Host is destroyed later in nlm_gc_host().
*/
void nlmsvc_release_host(struct nlm_host *host)
{
if (host == NULL)
return;
dprintk("lockd: release server host %s\n", host->h_name);
WARN_ON_ONCE(!host->h_server);
atomic_dec(&host->h_count);
}
/*
* Create the NLM RPC client for an NLM peer
*/
struct rpc_clnt *
nlm_bind_host(struct nlm_host *host)
{
struct rpc_clnt *clnt;
dprintk("lockd: nlm_bind_host %s (%s)\n",
host->h_name, host->h_addrbuf);
/* Lock host handle */
mutex_lock(&host->h_mutex);
/* If we've already created an RPC client, check whether
* RPC rebind is required
*/
if ((clnt = host->h_rpcclnt) != NULL) {
if (time_after_eq(jiffies, host->h_nextrebind)) {
rpc_force_rebind(clnt);
host->h_nextrebind = jiffies + NLM_HOST_REBIND;
dprintk("lockd: next rebind in %lu jiffies\n",
host->h_nextrebind - jiffies);
}
} else {
unsigned long increment = nlmsvc_timeout;
struct rpc_timeout timeparms = {
.to_initval = increment,
.to_increment = increment,
.to_maxval = increment * 6UL,
.to_retries = 5U,
};
struct rpc_create_args args = {
.net = host->net,
.protocol = host->h_proto,
.address = nlm_addr(host),
.addrsize = host->h_addrlen,
.timeout = &timeparms,
.servername = host->h_name,
.program = &nlm_program,
.version = host->h_version,
.authflavor = RPC_AUTH_UNIX,
.flags = (RPC_CLNT_CREATE_NOPING |
RPC_CLNT_CREATE_AUTOBIND),
};
/*
* lockd retries server side blocks automatically so we want
* those to be soft RPC calls. Client side calls need to be
* hard RPC tasks.
*/
if (!host->h_server)
args.flags |= RPC_CLNT_CREATE_HARDRTRY;
if (host->h_noresvport)
args.flags |= RPC_CLNT_CREATE_NONPRIVPORT;
if (host->h_srcaddrlen)
args.saddress = nlm_srcaddr(host);
clnt = rpc_create(&args);
if (!IS_ERR(clnt))
host->h_rpcclnt = clnt;
else {
printk("lockd: couldn't create RPC handle for %s\n", host->h_name);
clnt = NULL;
}
}
mutex_unlock(&host->h_mutex);
return clnt;
}
/*
* Force a portmap lookup of the remote lockd port
*/
void
nlm_rebind_host(struct nlm_host *host)
{
dprintk("lockd: rebind host %s\n", host->h_name);
if (host->h_rpcclnt && time_after_eq(jiffies, host->h_nextrebind)) {
rpc_force_rebind(host->h_rpcclnt);
host->h_nextrebind = jiffies + NLM_HOST_REBIND;
}
}
/*
* Increment NLM host count
*/
struct nlm_host * nlm_get_host(struct nlm_host *host)
{
if (host) {
dprintk("lockd: get host %s\n", host->h_name);
atomic_inc(&host->h_count);
host->h_expires = jiffies + NLM_HOST_EXPIRE;
}
return host;
}
static struct nlm_host *next_host_state(struct hlist_head *cache,
struct nsm_handle *nsm,
const struct nlm_reboot *info)
{
struct nlm_host *host;
struct hlist_head *chain;
mutex_lock(&nlm_host_mutex);
for_each_host(host, chain, cache) {
if (host->h_nsmhandle == nsm
&& host->h_nsmstate != info->state) {
host->h_nsmstate = info->state;
host->h_state++;
nlm_get_host(host);
mutex_unlock(&nlm_host_mutex);
return host;
}
}
mutex_unlock(&nlm_host_mutex);
return NULL;
}
/**
* nlm_host_rebooted - Release all resources held by rebooted host
* @info: pointer to decoded results of NLM_SM_NOTIFY call
*
* We were notified that the specified host has rebooted. Release
* all resources held by that peer.
*/
void nlm_host_rebooted(const struct nlm_reboot *info)
{
struct nsm_handle *nsm;
struct nlm_host *host;
nsm = nsm_reboot_lookup(info);
if (unlikely(nsm == NULL))
return;
/* Mark all hosts tied to this NSM state as having rebooted.
* We run the loop repeatedly, because we drop the host table
* lock for this.
* To avoid processing a host several times, we match the nsmstate.
*/
while ((host = next_host_state(nlm_server_hosts, nsm, info)) != NULL) {
nlmsvc_free_host_resources(host);
nlmsvc_release_host(host);
}
while ((host = next_host_state(nlm_client_hosts, nsm, info)) != NULL) {
nlmclnt_recovery(host);
nlmclnt_release_host(host);
}
nsm_release(nsm);
}
static void nlm_complain_hosts(struct net *net)
{
struct hlist_head *chain;
struct nlm_host *host;
if (net) {
struct lockd_net *ln = net_generic(net, lockd_net_id);
if (ln->nrhosts == 0)
return;
printk(KERN_WARNING "lockd: couldn't shutdown host module for net %p!\n", net);
dprintk("lockd: %lu hosts left in net %p:\n", ln->nrhosts, net);
} else {
if (nrhosts == 0)
return;
printk(KERN_WARNING "lockd: couldn't shutdown host module!\n");
dprintk("lockd: %lu hosts left:\n", nrhosts);
}
for_each_host(host, chain, nlm_server_hosts) {
if (net && host->net != net)
continue;
dprintk(" %s (cnt %d use %d exp %ld net %p)\n",
host->h_name, atomic_read(&host->h_count),
host->h_inuse, host->h_expires, host->net);
}
}
void
nlm_shutdown_hosts_net(struct net *net)
{
struct hlist_head *chain;
struct nlm_host *host;
mutex_lock(&nlm_host_mutex);
/* First, make all hosts eligible for gc */
dprintk("lockd: nuking all hosts in net %p...\n", net);
for_each_host(host, chain, nlm_server_hosts) {
if (net && host->net != net)
continue;
host->h_expires = jiffies - 1;
if (host->h_rpcclnt) {
rpc_shutdown_client(host->h_rpcclnt);
host->h_rpcclnt = NULL;
}
}
/* Then, perform a garbage collection pass */
nlm_gc_hosts(net);
mutex_unlock(&nlm_host_mutex);
nlm_complain_hosts(net);
}
/*
* Shut down the hosts module.
* Note that this routine is called only at server shutdown time.
*/
void
nlm_shutdown_hosts(void)
{
dprintk("lockd: shutting down host module\n");
nlm_shutdown_hosts_net(NULL);
}
/*
* Garbage collect any unused NLM hosts.
* This GC combines reference counting for async operations with
* mark & sweep for resources held by remote clients.
*/
static void
nlm_gc_hosts(struct net *net)
{
struct hlist_head *chain;
struct hlist_node *next;
struct nlm_host *host;
dprintk("lockd: host garbage collection for net %p\n", net);
for_each_host(host, chain, nlm_server_hosts) {
if (net && host->net != net)
continue;
host->h_inuse = 0;
}
/* Mark all hosts that hold locks, blocks or shares */
nlmsvc_mark_resources(net);
for_each_host_safe(host, next, chain, nlm_server_hosts) {
if (net && host->net != net)
continue;
if (atomic_read(&host->h_count) || host->h_inuse
|| time_before(jiffies, host->h_expires)) {
dprintk("nlm_gc_hosts skipping %s "
"(cnt %d use %d exp %ld net %p)\n",
host->h_name, atomic_read(&host->h_count),
host->h_inuse, host->h_expires, host->net);
continue;
}
nlm_destroy_host_locked(host);
}
if (net) {
struct lockd_net *ln = net_generic(net, lockd_net_id);
ln->next_gc = jiffies + NLM_HOST_COLLECT;
}
}
| gpl-2.0 |
superceleron/Kernel-3188 | net/dsa/tag_edsa.c | 4191 | 5424 | /*
* net/dsa/tag_edsa.c - Ethertype DSA tagging
* Copyright (c) 2008-2009 Marvell Semiconductor
*
* 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/etherdevice.h>
#include <linux/list.h>
#include <linux/netdevice.h>
#include <linux/slab.h>
#include "dsa_priv.h"
#define DSA_HLEN 4
#define EDSA_HLEN 8
netdev_tx_t edsa_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct dsa_slave_priv *p = netdev_priv(dev);
u8 *edsa_header;
dev->stats.tx_packets++;
dev->stats.tx_bytes += skb->len;
/*
* Convert the outermost 802.1q tag to a DSA tag and prepend
* a DSA ethertype field is the packet is tagged, or insert
* a DSA ethertype plus DSA tag between the addresses and the
* current ethertype field if the packet is untagged.
*/
if (skb->protocol == htons(ETH_P_8021Q)) {
if (skb_cow_head(skb, DSA_HLEN) < 0)
goto out_free;
skb_push(skb, DSA_HLEN);
memmove(skb->data, skb->data + DSA_HLEN, 2 * ETH_ALEN);
/*
* Construct tagged FROM_CPU DSA tag from 802.1q tag.
*/
edsa_header = skb->data + 2 * ETH_ALEN;
edsa_header[0] = (ETH_P_EDSA >> 8) & 0xff;
edsa_header[1] = ETH_P_EDSA & 0xff;
edsa_header[2] = 0x00;
edsa_header[3] = 0x00;
edsa_header[4] = 0x60 | p->parent->index;
edsa_header[5] = p->port << 3;
/*
* Move CFI field from byte 6 to byte 5.
*/
if (edsa_header[6] & 0x10) {
edsa_header[5] |= 0x01;
edsa_header[6] &= ~0x10;
}
} else {
if (skb_cow_head(skb, EDSA_HLEN) < 0)
goto out_free;
skb_push(skb, EDSA_HLEN);
memmove(skb->data, skb->data + EDSA_HLEN, 2 * ETH_ALEN);
/*
* Construct untagged FROM_CPU DSA tag.
*/
edsa_header = skb->data + 2 * ETH_ALEN;
edsa_header[0] = (ETH_P_EDSA >> 8) & 0xff;
edsa_header[1] = ETH_P_EDSA & 0xff;
edsa_header[2] = 0x00;
edsa_header[3] = 0x00;
edsa_header[4] = 0x40 | p->parent->index;
edsa_header[5] = p->port << 3;
edsa_header[6] = 0x00;
edsa_header[7] = 0x00;
}
skb->protocol = htons(ETH_P_EDSA);
skb->dev = p->parent->dst->master_netdev;
dev_queue_xmit(skb);
return NETDEV_TX_OK;
out_free:
kfree_skb(skb);
return NETDEV_TX_OK;
}
static int edsa_rcv(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev)
{
struct dsa_switch_tree *dst = dev->dsa_ptr;
struct dsa_switch *ds;
u8 *edsa_header;
int source_device;
int source_port;
if (unlikely(dst == NULL))
goto out_drop;
skb = skb_unshare(skb, GFP_ATOMIC);
if (skb == NULL)
goto out;
if (unlikely(!pskb_may_pull(skb, EDSA_HLEN)))
goto out_drop;
/*
* Skip the two null bytes after the ethertype.
*/
edsa_header = skb->data + 2;
/*
* Check that frame type is either TO_CPU or FORWARD.
*/
if ((edsa_header[0] & 0xc0) != 0x00 && (edsa_header[0] & 0xc0) != 0xc0)
goto out_drop;
/*
* Determine source device and port.
*/
source_device = edsa_header[0] & 0x1f;
source_port = (edsa_header[1] >> 3) & 0x1f;
/*
* Check that the source device exists and that the source
* port is a registered DSA port.
*/
if (source_device >= dst->pd->nr_chips)
goto out_drop;
ds = dst->ds[source_device];
if (source_port >= DSA_MAX_PORTS || ds->ports[source_port] == NULL)
goto out_drop;
/*
* If the 'tagged' bit is set, convert the DSA tag to a 802.1q
* tag and delete the ethertype part. If the 'tagged' bit is
* clear, delete the ethertype and the DSA tag parts.
*/
if (edsa_header[0] & 0x20) {
u8 new_header[4];
/*
* Insert 802.1q ethertype and copy the VLAN-related
* fields, but clear the bit that will hold CFI (since
* DSA uses that bit location for another purpose).
*/
new_header[0] = (ETH_P_8021Q >> 8) & 0xff;
new_header[1] = ETH_P_8021Q & 0xff;
new_header[2] = edsa_header[2] & ~0x10;
new_header[3] = edsa_header[3];
/*
* Move CFI bit from its place in the DSA header to
* its 802.1q-designated place.
*/
if (edsa_header[1] & 0x01)
new_header[2] |= 0x10;
skb_pull_rcsum(skb, DSA_HLEN);
/*
* Update packet checksum if skb is CHECKSUM_COMPLETE.
*/
if (skb->ip_summed == CHECKSUM_COMPLETE) {
__wsum c = skb->csum;
c = csum_add(c, csum_partial(new_header + 2, 2, 0));
c = csum_sub(c, csum_partial(edsa_header + 2, 2, 0));
skb->csum = c;
}
memcpy(edsa_header, new_header, DSA_HLEN);
memmove(skb->data - ETH_HLEN,
skb->data - ETH_HLEN - DSA_HLEN,
2 * ETH_ALEN);
} else {
/*
* Remove DSA tag and update checksum.
*/
skb_pull_rcsum(skb, EDSA_HLEN);
memmove(skb->data - ETH_HLEN,
skb->data - ETH_HLEN - EDSA_HLEN,
2 * ETH_ALEN);
}
skb->dev = ds->ports[source_port];
skb_push(skb, ETH_HLEN);
skb->pkt_type = PACKET_HOST;
skb->protocol = eth_type_trans(skb, skb->dev);
skb->dev->stats.rx_packets++;
skb->dev->stats.rx_bytes += skb->len;
netif_receive_skb(skb);
return 0;
out_drop:
kfree_skb(skb);
out:
return 0;
}
static struct packet_type edsa_packet_type __read_mostly = {
.type = cpu_to_be16(ETH_P_EDSA),
.func = edsa_rcv,
};
static int __init edsa_init_module(void)
{
dev_add_pack(&edsa_packet_type);
return 0;
}
module_init(edsa_init_module);
static void __exit edsa_cleanup_module(void)
{
dev_remove_pack(&edsa_packet_type);
}
module_exit(edsa_cleanup_module);
| gpl-2.0 |
Mirenk/android_kernel_semc_msm7x30 | drivers/leds/leds-pwm.c | 4959 | 3401 | /*
* linux/drivers/leds-pwm.c
*
* simple PWM based LED control
*
* Copyright 2009 Luotao Fu @ Pengutronix (l.fu@pengutronix.de)
*
* based on leds-gpio.c by Raphael Assenat <raph@8d.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/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/fb.h>
#include <linux/leds.h>
#include <linux/err.h>
#include <linux/pwm.h>
#include <linux/leds_pwm.h>
#include <linux/slab.h>
struct led_pwm_data {
struct led_classdev cdev;
struct pwm_device *pwm;
unsigned int active_low;
unsigned int period;
};
static void led_pwm_set(struct led_classdev *led_cdev,
enum led_brightness brightness)
{
struct led_pwm_data *led_dat =
container_of(led_cdev, struct led_pwm_data, cdev);
unsigned int max = led_dat->cdev.max_brightness;
unsigned int period = led_dat->period;
if (brightness == 0) {
pwm_config(led_dat->pwm, 0, period);
pwm_disable(led_dat->pwm);
} else {
pwm_config(led_dat->pwm, brightness * period / max, period);
pwm_enable(led_dat->pwm);
}
}
static int led_pwm_probe(struct platform_device *pdev)
{
struct led_pwm_platform_data *pdata = pdev->dev.platform_data;
struct led_pwm *cur_led;
struct led_pwm_data *leds_data, *led_dat;
int i, ret = 0;
if (!pdata)
return -EBUSY;
leds_data = kzalloc(sizeof(struct led_pwm_data) * pdata->num_leds,
GFP_KERNEL);
if (!leds_data)
return -ENOMEM;
for (i = 0; i < pdata->num_leds; i++) {
cur_led = &pdata->leds[i];
led_dat = &leds_data[i];
led_dat->pwm = pwm_request(cur_led->pwm_id,
cur_led->name);
if (IS_ERR(led_dat->pwm)) {
ret = PTR_ERR(led_dat->pwm);
dev_err(&pdev->dev, "unable to request PWM %d\n",
cur_led->pwm_id);
goto err;
}
led_dat->cdev.name = cur_led->name;
led_dat->cdev.default_trigger = cur_led->default_trigger;
led_dat->active_low = cur_led->active_low;
led_dat->period = cur_led->pwm_period_ns;
led_dat->cdev.brightness_set = led_pwm_set;
led_dat->cdev.brightness = LED_OFF;
led_dat->cdev.max_brightness = cur_led->max_brightness;
led_dat->cdev.flags |= LED_CORE_SUSPENDRESUME;
ret = led_classdev_register(&pdev->dev, &led_dat->cdev);
if (ret < 0) {
pwm_free(led_dat->pwm);
goto err;
}
}
platform_set_drvdata(pdev, leds_data);
return 0;
err:
if (i > 0) {
for (i = i - 1; i >= 0; i--) {
led_classdev_unregister(&leds_data[i].cdev);
pwm_free(leds_data[i].pwm);
}
}
kfree(leds_data);
return ret;
}
static int __devexit led_pwm_remove(struct platform_device *pdev)
{
int i;
struct led_pwm_platform_data *pdata = pdev->dev.platform_data;
struct led_pwm_data *leds_data;
leds_data = platform_get_drvdata(pdev);
for (i = 0; i < pdata->num_leds; i++) {
led_classdev_unregister(&leds_data[i].cdev);
pwm_free(leds_data[i].pwm);
}
kfree(leds_data);
return 0;
}
static struct platform_driver led_pwm_driver = {
.probe = led_pwm_probe,
.remove = __devexit_p(led_pwm_remove),
.driver = {
.name = "leds_pwm",
.owner = THIS_MODULE,
},
};
module_platform_driver(led_pwm_driver);
MODULE_AUTHOR("Luotao Fu <l.fu@pengutronix.de>");
MODULE_DESCRIPTION("PWM LED driver for PXA");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:leds-pwm");
| gpl-2.0 |
juston-li/hammerhead | arch/mips/jz4740/reset.c | 7775 | 1852 | /*
* Copyright (C) 2010, Lars-Peter Clausen <lars@metafoo.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.
*
* 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/io.h>
#include <linux/kernel.h>
#include <linux/pm.h>
#include <asm/reboot.h>
#include <asm/mach-jz4740/base.h>
#include <asm/mach-jz4740/timer.h>
static void jz4740_halt(void)
{
while (1) {
__asm__(".set push;\n"
".set mips3;\n"
"wait;\n"
".set pop;\n"
);
}
}
#define JZ_REG_WDT_DATA 0x00
#define JZ_REG_WDT_COUNTER_ENABLE 0x04
#define JZ_REG_WDT_COUNTER 0x08
#define JZ_REG_WDT_CTRL 0x0c
static void jz4740_restart(char *command)
{
void __iomem *wdt_base = ioremap(JZ4740_WDT_BASE_ADDR, 0x0f);
jz4740_timer_enable_watchdog();
writeb(0, wdt_base + JZ_REG_WDT_COUNTER_ENABLE);
writew(0, wdt_base + JZ_REG_WDT_COUNTER);
writew(0, wdt_base + JZ_REG_WDT_DATA);
writew(BIT(2), wdt_base + JZ_REG_WDT_CTRL);
writeb(1, wdt_base + JZ_REG_WDT_COUNTER_ENABLE);
jz4740_halt();
}
#define JZ_REG_RTC_CTRL 0x00
#define JZ_REG_RTC_HIBERNATE 0x20
#define JZ_RTC_CTRL_WRDY BIT(7)
static void jz4740_power_off(void)
{
void __iomem *rtc_base = ioremap(JZ4740_RTC_BASE_ADDR, 0x24);
uint32_t ctrl;
do {
ctrl = readl(rtc_base + JZ_REG_RTC_CTRL);
} while (!(ctrl & JZ_RTC_CTRL_WRDY));
writel(1, rtc_base + JZ_REG_RTC_HIBERNATE);
jz4740_halt();
}
void jz4740_reset_init(void)
{
_machine_restart = jz4740_restart;
_machine_halt = jz4740_halt;
pm_power_off = jz4740_power_off;
}
| gpl-2.0 |
MoKee/android_kernel_zte_x9180 | drivers/staging/bcm/LeakyBucket.c | 8031 | 11392 | /**********************************************************************
* LEAKYBUCKET.C
* This file contains the routines related to Leaky Bucket Algorithm.
***********************************************************************/
#include "headers.h"
/*********************************************************************
* Function - UpdateTokenCount()
*
* Description - This function calculates the token count for each
* channel and updates the same in Adapter strucuture.
*
* Parameters - Adapter: Pointer to the Adapter structure.
*
* Returns - None
**********************************************************************/
static VOID UpdateTokenCount(register PMINI_ADAPTER Adapter)
{
ULONG liCurrentTime;
INT i = 0;
struct timeval tv;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TOKEN_COUNTS, DBG_LVL_ALL, "=====>\n");
if(NULL == Adapter)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TOKEN_COUNTS, DBG_LVL_ALL, "Adapter found NULL!\n");
return;
}
do_gettimeofday(&tv);
for(i = 0; i < NO_OF_QUEUES; i++)
{
if(TRUE == Adapter->PackInfo[i].bValid &&
(1 == Adapter->PackInfo[i].ucDirection))
{
liCurrentTime = ((tv.tv_sec-
Adapter->PackInfo[i].stLastUpdateTokenAt.tv_sec)*1000 +
(tv.tv_usec-Adapter->PackInfo[i].stLastUpdateTokenAt.tv_usec)/
1000);
if(0!=liCurrentTime)
{
Adapter->PackInfo[i].uiCurrentTokenCount += (ULONG)
((Adapter->PackInfo[i].uiMaxAllowedRate) *
((ULONG)((liCurrentTime)))/1000);
memcpy(&Adapter->PackInfo[i].stLastUpdateTokenAt,
&tv, sizeof(struct timeval));
Adapter->PackInfo[i].liLastUpdateTokenAt = liCurrentTime;
if((Adapter->PackInfo[i].uiCurrentTokenCount) >=
Adapter->PackInfo[i].uiMaxBucketSize)
{
Adapter->PackInfo[i].uiCurrentTokenCount =
Adapter->PackInfo[i].uiMaxBucketSize;
}
}
}
}
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TOKEN_COUNTS, DBG_LVL_ALL, "<=====\n");
return;
}
/*********************************************************************
* Function - IsPacketAllowedForFlow()
*
* Description - This function checks whether the given packet from the
* specified queue can be allowed for transmission by
* checking the token count.
*
* Parameters - Adapter : Pointer to the Adpater structure.
* - iQIndex : The queue Identifier.
* - ulPacketLength: Number of bytes to be transmitted.
*
* Returns - The number of bytes allowed for transmission.
*
***********************************************************************/
static ULONG GetSFTokenCount(PMINI_ADAPTER Adapter, PacketInfo *psSF)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TOKEN_COUNTS, DBG_LVL_ALL, "IsPacketAllowedForFlow ===>");
/* Validate the parameters */
if(NULL == Adapter || (psSF < Adapter->PackInfo &&
(uintptr_t)psSF > (uintptr_t) &Adapter->PackInfo[HiPriority]))
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TOKEN_COUNTS, DBG_LVL_ALL, "IPAFF: Got wrong Parameters:Adapter: %p, QIndex: %zd\n", Adapter, (psSF-Adapter->PackInfo));
return 0;
}
if(FALSE != psSF->bValid && psSF->ucDirection)
{
if(0 != psSF->uiCurrentTokenCount)
{
return psSF->uiCurrentTokenCount;
}
else
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TOKEN_COUNTS, DBG_LVL_ALL, "Not enough tokens in queue %zd Available %u\n",
psSF-Adapter->PackInfo, psSF->uiCurrentTokenCount);
psSF->uiPendedLast = 1;
}
}
else
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TOKEN_COUNTS, DBG_LVL_ALL, "IPAFF: Queue %zd not valid\n", psSF-Adapter->PackInfo);
}
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TOKEN_COUNTS, DBG_LVL_ALL, "IsPacketAllowedForFlow <===");
return 0;
}
/**
@ingroup tx_functions
This function despatches packet from the specified queue.
@return Zero(success) or Negative value(failure)
*/
static INT SendPacketFromQueue(PMINI_ADAPTER Adapter,/**<Logical Adapter*/
PacketInfo *psSF, /**<Queue identifier*/
struct sk_buff* Packet) /**<Pointer to the packet to be sent*/
{
INT Status=STATUS_FAILURE;
UINT uiIndex =0,PktLen = 0;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, SEND_QUEUE, DBG_LVL_ALL, "=====>");
if(!Adapter || !Packet || !psSF)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, SEND_QUEUE, DBG_LVL_ALL, "Got NULL Adapter or Packet");
return -EINVAL;
}
if(psSF->liDrainCalculated==0)
{
psSF->liDrainCalculated = jiffies;
}
///send the packet to the fifo..
PktLen = Packet->len;
Status = SetupNextSend(Adapter, Packet, psSF->usVCID_Value);
if(Status == 0)
{
for(uiIndex = 0 ; uiIndex < MIBS_MAX_HIST_ENTRIES ; uiIndex++)
{ if((PktLen <= MIBS_PKTSIZEHIST_RANGE*(uiIndex+1)) && (PktLen > MIBS_PKTSIZEHIST_RANGE*(uiIndex)))
Adapter->aTxPktSizeHist[uiIndex]++;
}
}
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, SEND_QUEUE, DBG_LVL_ALL, "<=====");
return Status;
}
/************************************************************************
* Function - CheckAndSendPacketFromIndex()
*
* Description - This function dequeues the data/control packet from the
* specified queue for transmission.
*
* Parameters - Adapter : Pointer to the driver control structure.
* - iQIndex : The queue Identifier.
*
* Returns - None.
*
****************************************************************************/
static VOID CheckAndSendPacketFromIndex(PMINI_ADAPTER Adapter, PacketInfo *psSF)
{
struct sk_buff *QueuePacket=NULL;
char *pControlPacket = NULL;
INT Status=0;
int iPacketLen=0;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, "%zd ====>", (psSF-Adapter->PackInfo));
if((psSF != &Adapter->PackInfo[HiPriority]) && Adapter->LinkUpStatus && atomic_read(&psSF->uiPerSFTxResourceCount))//Get data packet
{
if(!psSF->ucDirection )
return;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, "UpdateTokenCount ");
if(Adapter->IdleMode || Adapter->bPreparingForLowPowerMode)
return; /* in idle mode */
// Check for Free Descriptors
if(atomic_read(&Adapter->CurrNumFreeTxDesc) <= MINIMUM_PENDING_DESCRIPTORS)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, " No Free Tx Descriptor(%d) is available for Data pkt..",atomic_read(&Adapter->CurrNumFreeTxDesc));
return ;
}
spin_lock_bh(&psSF->SFQueueLock);
QueuePacket=psSF->FirstTxQueue;
if(QueuePacket)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, "Dequeuing Data Packet");
if(psSF->bEthCSSupport)
iPacketLen = QueuePacket->len;
else
iPacketLen = QueuePacket->len-ETH_HLEN;
iPacketLen<<=3;
if(iPacketLen <= GetSFTokenCount(Adapter, psSF))
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, "Allowed bytes %d",
(iPacketLen >> 3));
DEQUEUEPACKET(psSF->FirstTxQueue,psSF->LastTxQueue);
psSF->uiCurrentBytesOnHost -= (QueuePacket->len);
psSF->uiCurrentPacketsOnHost--;
atomic_dec(&Adapter->TotalPacketCount);
spin_unlock_bh(&psSF->SFQueueLock);
Status = SendPacketFromQueue(Adapter, psSF, QueuePacket);
psSF->uiPendedLast = FALSE;
}
else
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, "For Queue: %zd\n", psSF-Adapter->PackInfo);
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, "\nAvailable Tokens = %d required = %d\n",
psSF->uiCurrentTokenCount, iPacketLen);
//this part indicates that because of non-availability of the tokens
//pkt has not been send out hence setting the pending flag indicating the host to send it out
//first next iteration .
psSF->uiPendedLast = TRUE;
spin_unlock_bh(&psSF->SFQueueLock);
}
}
else
{
spin_unlock_bh(&psSF->SFQueueLock);
}
}
else
{
if((atomic_read(&Adapter->CurrNumFreeTxDesc) > 0 ) &&
(atomic_read(&Adapter->index_rd_txcntrlpkt) !=
atomic_read(&Adapter->index_wr_txcntrlpkt))
)
{
pControlPacket = Adapter->txctlpacket
[(atomic_read(&Adapter->index_rd_txcntrlpkt)%MAX_CNTRL_PKTS)];
if(pControlPacket)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, "Sending Control packet");
Status = SendControlPacket(Adapter, pControlPacket);
if(STATUS_SUCCESS==Status)
{
spin_lock_bh(&psSF->SFQueueLock);
psSF->NumOfPacketsSent++;
psSF->uiSentBytes+=((PLEADER)pControlPacket)->PLength;
psSF->uiSentPackets++;
atomic_dec(&Adapter->TotalPacketCount);
psSF->uiCurrentBytesOnHost -= ((PLEADER)pControlPacket)->PLength;
psSF->uiCurrentPacketsOnHost--;
atomic_inc(&Adapter->index_rd_txcntrlpkt);
spin_unlock_bh(&psSF->SFQueueLock);
}
else
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, "SendControlPacket Failed\n");
}
else
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, " Control Pkt is not available, Indexing is wrong....");
}
}
}
}
/*******************************************************************
* Function - transmit_packets()
*
* Description - This function transmits the packets from different
* queues, if free descriptors are available on target.
*
* Parameters - Adapter: Pointer to the Adapter structure.
*
* Returns - None.
********************************************************************/
VOID transmit_packets(PMINI_ADAPTER Adapter)
{
UINT uiPrevTotalCount = 0;
int iIndex = 0;
BOOLEAN exit_flag = TRUE ;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, "=====>");
if(NULL == Adapter)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX,TX_PACKETS, DBG_LVL_ALL, "Got NULL Adapter");
return;
}
if(Adapter->device_removed == TRUE)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, "Device removed");
return;
}
BCM_DEBUG_PRINT (Adapter, DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, "\nUpdateTokenCount ====>\n");
UpdateTokenCount(Adapter);
BCM_DEBUG_PRINT (Adapter, DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, "\nPruneQueueAllSF ====>\n");
PruneQueueAllSF(Adapter);
uiPrevTotalCount = atomic_read(&Adapter->TotalPacketCount);
for(iIndex=HiPriority;iIndex>=0;iIndex--)
{
if( !uiPrevTotalCount || (TRUE == Adapter->device_removed))
break;
if(Adapter->PackInfo[iIndex].bValid &&
Adapter->PackInfo[iIndex].uiPendedLast &&
Adapter->PackInfo[iIndex].uiCurrentBytesOnHost)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, "Calling CheckAndSendPacketFromIndex..");
CheckAndSendPacketFromIndex(Adapter, &Adapter->PackInfo[iIndex]);
uiPrevTotalCount--;
}
}
while(uiPrevTotalCount > 0 && !Adapter->device_removed)
{
exit_flag = TRUE ;
//second iteration to parse non-pending queues
for(iIndex=HiPriority;iIndex>=0;iIndex--)
{
if( !uiPrevTotalCount || (TRUE == Adapter->device_removed))
break;
if(Adapter->PackInfo[iIndex].bValid &&
Adapter->PackInfo[iIndex].uiCurrentBytesOnHost &&
!Adapter->PackInfo[iIndex].uiPendedLast )
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, "Calling CheckAndSendPacketFromIndex..");
CheckAndSendPacketFromIndex(Adapter, &Adapter->PackInfo[iIndex]);
uiPrevTotalCount--;
exit_flag = FALSE;
}
}
if(Adapter->IdleMode || Adapter->bPreparingForLowPowerMode)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, "In Idle Mode\n");
break;
}
if(exit_flag == TRUE )
break ;
}/* end of inner while loop */
update_per_cid_rx (Adapter);
Adapter->txtransmit_running = 0;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, "<======");
}
| gpl-2.0 |
thermatk/N8000 | drivers/staging/bcm/LeakyBucket.c | 8031 | 11392 | /**********************************************************************
* LEAKYBUCKET.C
* This file contains the routines related to Leaky Bucket Algorithm.
***********************************************************************/
#include "headers.h"
/*********************************************************************
* Function - UpdateTokenCount()
*
* Description - This function calculates the token count for each
* channel and updates the same in Adapter strucuture.
*
* Parameters - Adapter: Pointer to the Adapter structure.
*
* Returns - None
**********************************************************************/
static VOID UpdateTokenCount(register PMINI_ADAPTER Adapter)
{
ULONG liCurrentTime;
INT i = 0;
struct timeval tv;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TOKEN_COUNTS, DBG_LVL_ALL, "=====>\n");
if(NULL == Adapter)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TOKEN_COUNTS, DBG_LVL_ALL, "Adapter found NULL!\n");
return;
}
do_gettimeofday(&tv);
for(i = 0; i < NO_OF_QUEUES; i++)
{
if(TRUE == Adapter->PackInfo[i].bValid &&
(1 == Adapter->PackInfo[i].ucDirection))
{
liCurrentTime = ((tv.tv_sec-
Adapter->PackInfo[i].stLastUpdateTokenAt.tv_sec)*1000 +
(tv.tv_usec-Adapter->PackInfo[i].stLastUpdateTokenAt.tv_usec)/
1000);
if(0!=liCurrentTime)
{
Adapter->PackInfo[i].uiCurrentTokenCount += (ULONG)
((Adapter->PackInfo[i].uiMaxAllowedRate) *
((ULONG)((liCurrentTime)))/1000);
memcpy(&Adapter->PackInfo[i].stLastUpdateTokenAt,
&tv, sizeof(struct timeval));
Adapter->PackInfo[i].liLastUpdateTokenAt = liCurrentTime;
if((Adapter->PackInfo[i].uiCurrentTokenCount) >=
Adapter->PackInfo[i].uiMaxBucketSize)
{
Adapter->PackInfo[i].uiCurrentTokenCount =
Adapter->PackInfo[i].uiMaxBucketSize;
}
}
}
}
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TOKEN_COUNTS, DBG_LVL_ALL, "<=====\n");
return;
}
/*********************************************************************
* Function - IsPacketAllowedForFlow()
*
* Description - This function checks whether the given packet from the
* specified queue can be allowed for transmission by
* checking the token count.
*
* Parameters - Adapter : Pointer to the Adpater structure.
* - iQIndex : The queue Identifier.
* - ulPacketLength: Number of bytes to be transmitted.
*
* Returns - The number of bytes allowed for transmission.
*
***********************************************************************/
static ULONG GetSFTokenCount(PMINI_ADAPTER Adapter, PacketInfo *psSF)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TOKEN_COUNTS, DBG_LVL_ALL, "IsPacketAllowedForFlow ===>");
/* Validate the parameters */
if(NULL == Adapter || (psSF < Adapter->PackInfo &&
(uintptr_t)psSF > (uintptr_t) &Adapter->PackInfo[HiPriority]))
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TOKEN_COUNTS, DBG_LVL_ALL, "IPAFF: Got wrong Parameters:Adapter: %p, QIndex: %zd\n", Adapter, (psSF-Adapter->PackInfo));
return 0;
}
if(FALSE != psSF->bValid && psSF->ucDirection)
{
if(0 != psSF->uiCurrentTokenCount)
{
return psSF->uiCurrentTokenCount;
}
else
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TOKEN_COUNTS, DBG_LVL_ALL, "Not enough tokens in queue %zd Available %u\n",
psSF-Adapter->PackInfo, psSF->uiCurrentTokenCount);
psSF->uiPendedLast = 1;
}
}
else
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TOKEN_COUNTS, DBG_LVL_ALL, "IPAFF: Queue %zd not valid\n", psSF-Adapter->PackInfo);
}
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TOKEN_COUNTS, DBG_LVL_ALL, "IsPacketAllowedForFlow <===");
return 0;
}
/**
@ingroup tx_functions
This function despatches packet from the specified queue.
@return Zero(success) or Negative value(failure)
*/
static INT SendPacketFromQueue(PMINI_ADAPTER Adapter,/**<Logical Adapter*/
PacketInfo *psSF, /**<Queue identifier*/
struct sk_buff* Packet) /**<Pointer to the packet to be sent*/
{
INT Status=STATUS_FAILURE;
UINT uiIndex =0,PktLen = 0;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, SEND_QUEUE, DBG_LVL_ALL, "=====>");
if(!Adapter || !Packet || !psSF)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, SEND_QUEUE, DBG_LVL_ALL, "Got NULL Adapter or Packet");
return -EINVAL;
}
if(psSF->liDrainCalculated==0)
{
psSF->liDrainCalculated = jiffies;
}
///send the packet to the fifo..
PktLen = Packet->len;
Status = SetupNextSend(Adapter, Packet, psSF->usVCID_Value);
if(Status == 0)
{
for(uiIndex = 0 ; uiIndex < MIBS_MAX_HIST_ENTRIES ; uiIndex++)
{ if((PktLen <= MIBS_PKTSIZEHIST_RANGE*(uiIndex+1)) && (PktLen > MIBS_PKTSIZEHIST_RANGE*(uiIndex)))
Adapter->aTxPktSizeHist[uiIndex]++;
}
}
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, SEND_QUEUE, DBG_LVL_ALL, "<=====");
return Status;
}
/************************************************************************
* Function - CheckAndSendPacketFromIndex()
*
* Description - This function dequeues the data/control packet from the
* specified queue for transmission.
*
* Parameters - Adapter : Pointer to the driver control structure.
* - iQIndex : The queue Identifier.
*
* Returns - None.
*
****************************************************************************/
static VOID CheckAndSendPacketFromIndex(PMINI_ADAPTER Adapter, PacketInfo *psSF)
{
struct sk_buff *QueuePacket=NULL;
char *pControlPacket = NULL;
INT Status=0;
int iPacketLen=0;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, "%zd ====>", (psSF-Adapter->PackInfo));
if((psSF != &Adapter->PackInfo[HiPriority]) && Adapter->LinkUpStatus && atomic_read(&psSF->uiPerSFTxResourceCount))//Get data packet
{
if(!psSF->ucDirection )
return;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, "UpdateTokenCount ");
if(Adapter->IdleMode || Adapter->bPreparingForLowPowerMode)
return; /* in idle mode */
// Check for Free Descriptors
if(atomic_read(&Adapter->CurrNumFreeTxDesc) <= MINIMUM_PENDING_DESCRIPTORS)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, " No Free Tx Descriptor(%d) is available for Data pkt..",atomic_read(&Adapter->CurrNumFreeTxDesc));
return ;
}
spin_lock_bh(&psSF->SFQueueLock);
QueuePacket=psSF->FirstTxQueue;
if(QueuePacket)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, "Dequeuing Data Packet");
if(psSF->bEthCSSupport)
iPacketLen = QueuePacket->len;
else
iPacketLen = QueuePacket->len-ETH_HLEN;
iPacketLen<<=3;
if(iPacketLen <= GetSFTokenCount(Adapter, psSF))
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, "Allowed bytes %d",
(iPacketLen >> 3));
DEQUEUEPACKET(psSF->FirstTxQueue,psSF->LastTxQueue);
psSF->uiCurrentBytesOnHost -= (QueuePacket->len);
psSF->uiCurrentPacketsOnHost--;
atomic_dec(&Adapter->TotalPacketCount);
spin_unlock_bh(&psSF->SFQueueLock);
Status = SendPacketFromQueue(Adapter, psSF, QueuePacket);
psSF->uiPendedLast = FALSE;
}
else
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, "For Queue: %zd\n", psSF-Adapter->PackInfo);
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, "\nAvailable Tokens = %d required = %d\n",
psSF->uiCurrentTokenCount, iPacketLen);
//this part indicates that because of non-availability of the tokens
//pkt has not been send out hence setting the pending flag indicating the host to send it out
//first next iteration .
psSF->uiPendedLast = TRUE;
spin_unlock_bh(&psSF->SFQueueLock);
}
}
else
{
spin_unlock_bh(&psSF->SFQueueLock);
}
}
else
{
if((atomic_read(&Adapter->CurrNumFreeTxDesc) > 0 ) &&
(atomic_read(&Adapter->index_rd_txcntrlpkt) !=
atomic_read(&Adapter->index_wr_txcntrlpkt))
)
{
pControlPacket = Adapter->txctlpacket
[(atomic_read(&Adapter->index_rd_txcntrlpkt)%MAX_CNTRL_PKTS)];
if(pControlPacket)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, "Sending Control packet");
Status = SendControlPacket(Adapter, pControlPacket);
if(STATUS_SUCCESS==Status)
{
spin_lock_bh(&psSF->SFQueueLock);
psSF->NumOfPacketsSent++;
psSF->uiSentBytes+=((PLEADER)pControlPacket)->PLength;
psSF->uiSentPackets++;
atomic_dec(&Adapter->TotalPacketCount);
psSF->uiCurrentBytesOnHost -= ((PLEADER)pControlPacket)->PLength;
psSF->uiCurrentPacketsOnHost--;
atomic_inc(&Adapter->index_rd_txcntrlpkt);
spin_unlock_bh(&psSF->SFQueueLock);
}
else
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, "SendControlPacket Failed\n");
}
else
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, " Control Pkt is not available, Indexing is wrong....");
}
}
}
}
/*******************************************************************
* Function - transmit_packets()
*
* Description - This function transmits the packets from different
* queues, if free descriptors are available on target.
*
* Parameters - Adapter: Pointer to the Adapter structure.
*
* Returns - None.
********************************************************************/
VOID transmit_packets(PMINI_ADAPTER Adapter)
{
UINT uiPrevTotalCount = 0;
int iIndex = 0;
BOOLEAN exit_flag = TRUE ;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, "=====>");
if(NULL == Adapter)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX,TX_PACKETS, DBG_LVL_ALL, "Got NULL Adapter");
return;
}
if(Adapter->device_removed == TRUE)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, "Device removed");
return;
}
BCM_DEBUG_PRINT (Adapter, DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, "\nUpdateTokenCount ====>\n");
UpdateTokenCount(Adapter);
BCM_DEBUG_PRINT (Adapter, DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, "\nPruneQueueAllSF ====>\n");
PruneQueueAllSF(Adapter);
uiPrevTotalCount = atomic_read(&Adapter->TotalPacketCount);
for(iIndex=HiPriority;iIndex>=0;iIndex--)
{
if( !uiPrevTotalCount || (TRUE == Adapter->device_removed))
break;
if(Adapter->PackInfo[iIndex].bValid &&
Adapter->PackInfo[iIndex].uiPendedLast &&
Adapter->PackInfo[iIndex].uiCurrentBytesOnHost)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, "Calling CheckAndSendPacketFromIndex..");
CheckAndSendPacketFromIndex(Adapter, &Adapter->PackInfo[iIndex]);
uiPrevTotalCount--;
}
}
while(uiPrevTotalCount > 0 && !Adapter->device_removed)
{
exit_flag = TRUE ;
//second iteration to parse non-pending queues
for(iIndex=HiPriority;iIndex>=0;iIndex--)
{
if( !uiPrevTotalCount || (TRUE == Adapter->device_removed))
break;
if(Adapter->PackInfo[iIndex].bValid &&
Adapter->PackInfo[iIndex].uiCurrentBytesOnHost &&
!Adapter->PackInfo[iIndex].uiPendedLast )
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, "Calling CheckAndSendPacketFromIndex..");
CheckAndSendPacketFromIndex(Adapter, &Adapter->PackInfo[iIndex]);
uiPrevTotalCount--;
exit_flag = FALSE;
}
}
if(Adapter->IdleMode || Adapter->bPreparingForLowPowerMode)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, "In Idle Mode\n");
break;
}
if(exit_flag == TRUE )
break ;
}/* end of inner while loop */
update_per_cid_rx (Adapter);
Adapter->txtransmit_running = 0;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, "<======");
}
| gpl-2.0 |
codeworkx/android_kernel_rockchip_rk30xx | drivers/input/touchscreen/hampshire.c | 9055 | 5069 | /*
* Hampshire serial touchscreen driver
*
* Copyright (c) 2010 Adam Bennett
* Based on the dynapro driver (c) Tias Guns
*
*/
/*
* 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.
*/
/*
* 2010/04/08 Adam Bennett <abennett72@gmail.com>
* Copied dynapro.c and edited for Hampshire 4-byte protocol
*/
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/serio.h>
#include <linux/init.h>
#define DRIVER_DESC "Hampshire serial touchscreen driver"
MODULE_AUTHOR("Adam Bennett <abennett72@gmail.com>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
/*
* Definitions & global arrays.
*/
#define HAMPSHIRE_FORMAT_TOUCH_BIT 0x40
#define HAMPSHIRE_FORMAT_LENGTH 4
#define HAMPSHIRE_RESPONSE_BEGIN_BYTE 0x80
#define HAMPSHIRE_MIN_XC 0
#define HAMPSHIRE_MAX_XC 0x1000
#define HAMPSHIRE_MIN_YC 0
#define HAMPSHIRE_MAX_YC 0x1000
#define HAMPSHIRE_GET_XC(data) (((data[3] & 0x0c) >> 2) | (data[1] << 2) | ((data[0] & 0x38) << 6))
#define HAMPSHIRE_GET_YC(data) ((data[3] & 0x03) | (data[2] << 2) | ((data[0] & 0x07) << 9))
#define HAMPSHIRE_GET_TOUCHED(data) (HAMPSHIRE_FORMAT_TOUCH_BIT & data[0])
/*
* Per-touchscreen data.
*/
struct hampshire {
struct input_dev *dev;
struct serio *serio;
int idx;
unsigned char data[HAMPSHIRE_FORMAT_LENGTH];
char phys[32];
};
static void hampshire_process_data(struct hampshire *phampshire)
{
struct input_dev *dev = phampshire->dev;
if (HAMPSHIRE_FORMAT_LENGTH == ++phampshire->idx) {
input_report_abs(dev, ABS_X, HAMPSHIRE_GET_XC(phampshire->data));
input_report_abs(dev, ABS_Y, HAMPSHIRE_GET_YC(phampshire->data));
input_report_key(dev, BTN_TOUCH,
HAMPSHIRE_GET_TOUCHED(phampshire->data));
input_sync(dev);
phampshire->idx = 0;
}
}
static irqreturn_t hampshire_interrupt(struct serio *serio,
unsigned char data, unsigned int flags)
{
struct hampshire *phampshire = serio_get_drvdata(serio);
phampshire->data[phampshire->idx] = data;
if (HAMPSHIRE_RESPONSE_BEGIN_BYTE & phampshire->data[0])
hampshire_process_data(phampshire);
else
dev_dbg(&serio->dev, "unknown/unsynchronized data: %x\n",
phampshire->data[0]);
return IRQ_HANDLED;
}
static void hampshire_disconnect(struct serio *serio)
{
struct hampshire *phampshire = serio_get_drvdata(serio);
input_get_device(phampshire->dev);
input_unregister_device(phampshire->dev);
serio_close(serio);
serio_set_drvdata(serio, NULL);
input_put_device(phampshire->dev);
kfree(phampshire);
}
/*
* hampshire_connect() is the routine that is called when someone adds a
* new serio device that supports hampshire protocol and registers it as
* an input device. This is usually accomplished using inputattach.
*/
static int hampshire_connect(struct serio *serio, struct serio_driver *drv)
{
struct hampshire *phampshire;
struct input_dev *input_dev;
int err;
phampshire = kzalloc(sizeof(struct hampshire), GFP_KERNEL);
input_dev = input_allocate_device();
if (!phampshire || !input_dev) {
err = -ENOMEM;
goto fail1;
}
phampshire->serio = serio;
phampshire->dev = input_dev;
snprintf(phampshire->phys, sizeof(phampshire->phys),
"%s/input0", serio->phys);
input_dev->name = "Hampshire Serial TouchScreen";
input_dev->phys = phampshire->phys;
input_dev->id.bustype = BUS_RS232;
input_dev->id.vendor = SERIO_HAMPSHIRE;
input_dev->id.product = 0;
input_dev->id.version = 0x0001;
input_dev->dev.parent = &serio->dev;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
input_dev->keybit[BIT_WORD(BTN_TOUCH)] = BIT_MASK(BTN_TOUCH);
input_set_abs_params(phampshire->dev, ABS_X,
HAMPSHIRE_MIN_XC, HAMPSHIRE_MAX_XC, 0, 0);
input_set_abs_params(phampshire->dev, ABS_Y,
HAMPSHIRE_MIN_YC, HAMPSHIRE_MAX_YC, 0, 0);
serio_set_drvdata(serio, phampshire);
err = serio_open(serio, drv);
if (err)
goto fail2;
err = input_register_device(phampshire->dev);
if (err)
goto fail3;
return 0;
fail3: serio_close(serio);
fail2: serio_set_drvdata(serio, NULL);
fail1: input_free_device(input_dev);
kfree(phampshire);
return err;
}
/*
* The serio driver structure.
*/
static struct serio_device_id hampshire_serio_ids[] = {
{
.type = SERIO_RS232,
.proto = SERIO_HAMPSHIRE,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{ 0 }
};
MODULE_DEVICE_TABLE(serio, hampshire_serio_ids);
static struct serio_driver hampshire_drv = {
.driver = {
.name = "hampshire",
},
.description = DRIVER_DESC,
.id_table = hampshire_serio_ids,
.interrupt = hampshire_interrupt,
.connect = hampshire_connect,
.disconnect = hampshire_disconnect,
};
/*
* The functions for inserting/removing us as a module.
*/
static int __init hampshire_init(void)
{
return serio_register_driver(&hampshire_drv);
}
static void __exit hampshire_exit(void)
{
serio_unregister_driver(&hampshire_drv);
}
module_init(hampshire_init);
module_exit(hampshire_exit);
| gpl-2.0 |
itsmerajit/kernel_otus | sound/parisc/harmony.c | 9823 | 25954 | /* Hewlett-Packard Harmony audio driver
*
* This is a driver for the Harmony audio chipset found
* on the LASI ASIC of various early HP PA-RISC workstations.
*
* Copyright (C) 2004, Kyle McMartin <kyle@{debian.org,parisc-linux.org}>
*
* Based on the previous Harmony incarnations by,
* Copyright 2000 (c) Linuxcare Canada, Alex deVries
* Copyright 2000-2003 (c) Helge Deller
* Copyright 2001 (c) Matthieu Delahaye
* Copyright 2001 (c) Jean-Christophe Vaugeois
* Copyright 2003 (c) Laurent Canet
* Copyright 2004 (c) Stuart Brady
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 2, as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Notes:
* - graveyard and silence buffers last for lifetime of
* the driver. playback and capture buffers are allocated
* per _open()/_close().
*
* TODO:
*
*/
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/time.h>
#include <linux/wait.h>
#include <linux/delay.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/spinlock.h>
#include <linux/dma-mapping.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/control.h>
#include <sound/rawmidi.h>
#include <sound/initval.h>
#include <sound/info.h>
#include <asm/io.h>
#include <asm/hardware.h>
#include <asm/parisc-device.h>
#include "harmony.h"
static int index = SNDRV_DEFAULT_IDX1; /* Index 0-MAX */
static char *id = SNDRV_DEFAULT_STR1; /* ID for this card */
module_param(index, int, 0444);
MODULE_PARM_DESC(index, "Index value for Harmony driver.");
module_param(id, charp, 0444);
MODULE_PARM_DESC(id, "ID string for Harmony driver.");
static struct parisc_device_id snd_harmony_devtable[] = {
/* bushmaster / flounder */
{ HPHW_FIO, HVERSION_REV_ANY_ID, HVERSION_ANY_ID, 0x0007A },
/* 712 / 715 */
{ HPHW_FIO, HVERSION_REV_ANY_ID, HVERSION_ANY_ID, 0x0007B },
/* pace */
{ HPHW_FIO, HVERSION_REV_ANY_ID, HVERSION_ANY_ID, 0x0007E },
/* outfield / coral II */
{ HPHW_FIO, HVERSION_REV_ANY_ID, HVERSION_ANY_ID, 0x0007F },
{ 0, }
};
MODULE_DEVICE_TABLE(parisc, snd_harmony_devtable);
#define NAME "harmony"
#define PFX NAME ": "
static unsigned int snd_harmony_rates[] = {
5512, 6615, 8000, 9600,
11025, 16000, 18900, 22050,
27428, 32000, 33075, 37800,
44100, 48000
};
static unsigned int rate_bits[14] = {
HARMONY_SR_5KHZ, HARMONY_SR_6KHZ, HARMONY_SR_8KHZ,
HARMONY_SR_9KHZ, HARMONY_SR_11KHZ, HARMONY_SR_16KHZ,
HARMONY_SR_18KHZ, HARMONY_SR_22KHZ, HARMONY_SR_27KHZ,
HARMONY_SR_32KHZ, HARMONY_SR_33KHZ, HARMONY_SR_37KHZ,
HARMONY_SR_44KHZ, HARMONY_SR_48KHZ
};
static struct snd_pcm_hw_constraint_list hw_constraint_rates = {
.count = ARRAY_SIZE(snd_harmony_rates),
.list = snd_harmony_rates,
.mask = 0,
};
static inline unsigned long
harmony_read(struct snd_harmony *h, unsigned r)
{
return __raw_readl(h->iobase + r);
}
static inline void
harmony_write(struct snd_harmony *h, unsigned r, unsigned long v)
{
__raw_writel(v, h->iobase + r);
}
static inline void
harmony_wait_for_control(struct snd_harmony *h)
{
while (harmony_read(h, HARMONY_CNTL) & HARMONY_CNTL_C) ;
}
static inline void
harmony_reset(struct snd_harmony *h)
{
harmony_write(h, HARMONY_RESET, 1);
mdelay(50);
harmony_write(h, HARMONY_RESET, 0);
}
static void
harmony_disable_interrupts(struct snd_harmony *h)
{
u32 dstatus;
harmony_wait_for_control(h);
dstatus = harmony_read(h, HARMONY_DSTATUS);
dstatus &= ~HARMONY_DSTATUS_IE;
harmony_write(h, HARMONY_DSTATUS, dstatus);
}
static void
harmony_enable_interrupts(struct snd_harmony *h)
{
u32 dstatus;
harmony_wait_for_control(h);
dstatus = harmony_read(h, HARMONY_DSTATUS);
dstatus |= HARMONY_DSTATUS_IE;
harmony_write(h, HARMONY_DSTATUS, dstatus);
}
static void
harmony_mute(struct snd_harmony *h)
{
unsigned long flags;
spin_lock_irqsave(&h->mixer_lock, flags);
harmony_wait_for_control(h);
harmony_write(h, HARMONY_GAINCTL, HARMONY_GAIN_SILENCE);
spin_unlock_irqrestore(&h->mixer_lock, flags);
}
static void
harmony_unmute(struct snd_harmony *h)
{
unsigned long flags;
spin_lock_irqsave(&h->mixer_lock, flags);
harmony_wait_for_control(h);
harmony_write(h, HARMONY_GAINCTL, h->st.gain);
spin_unlock_irqrestore(&h->mixer_lock, flags);
}
static void
harmony_set_control(struct snd_harmony *h)
{
u32 ctrl;
unsigned long flags;
spin_lock_irqsave(&h->lock, flags);
ctrl = (HARMONY_CNTL_C |
(h->st.format << 6) |
(h->st.stereo << 5) |
(h->st.rate));
harmony_wait_for_control(h);
harmony_write(h, HARMONY_CNTL, ctrl);
spin_unlock_irqrestore(&h->lock, flags);
}
static irqreturn_t
snd_harmony_interrupt(int irq, void *dev)
{
u32 dstatus;
struct snd_harmony *h = dev;
spin_lock(&h->lock);
harmony_disable_interrupts(h);
harmony_wait_for_control(h);
dstatus = harmony_read(h, HARMONY_DSTATUS);
spin_unlock(&h->lock);
if (dstatus & HARMONY_DSTATUS_PN) {
if (h->psubs && h->st.playing) {
spin_lock(&h->lock);
h->pbuf.buf += h->pbuf.count; /* PAGE_SIZE */
h->pbuf.buf %= h->pbuf.size; /* MAX_BUFS*PAGE_SIZE */
harmony_write(h, HARMONY_PNXTADD,
h->pbuf.addr + h->pbuf.buf);
h->stats.play_intr++;
spin_unlock(&h->lock);
snd_pcm_period_elapsed(h->psubs);
} else {
spin_lock(&h->lock);
harmony_write(h, HARMONY_PNXTADD, h->sdma.addr);
h->stats.silence_intr++;
spin_unlock(&h->lock);
}
}
if (dstatus & HARMONY_DSTATUS_RN) {
if (h->csubs && h->st.capturing) {
spin_lock(&h->lock);
h->cbuf.buf += h->cbuf.count;
h->cbuf.buf %= h->cbuf.size;
harmony_write(h, HARMONY_RNXTADD,
h->cbuf.addr + h->cbuf.buf);
h->stats.rec_intr++;
spin_unlock(&h->lock);
snd_pcm_period_elapsed(h->csubs);
} else {
spin_lock(&h->lock);
harmony_write(h, HARMONY_RNXTADD, h->gdma.addr);
h->stats.graveyard_intr++;
spin_unlock(&h->lock);
}
}
spin_lock(&h->lock);
harmony_enable_interrupts(h);
spin_unlock(&h->lock);
return IRQ_HANDLED;
}
static unsigned int
snd_harmony_rate_bits(int rate)
{
unsigned int i;
for (i = 0; i < ARRAY_SIZE(snd_harmony_rates); i++)
if (snd_harmony_rates[i] == rate)
return rate_bits[i];
return HARMONY_SR_44KHZ;
}
static struct snd_pcm_hardware snd_harmony_playback =
{
.info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_JOINT_DUPLEX | SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_BLOCK_TRANSFER),
.formats = (SNDRV_PCM_FMTBIT_S16_BE | SNDRV_PCM_FMTBIT_MU_LAW |
SNDRV_PCM_FMTBIT_A_LAW),
.rates = (SNDRV_PCM_RATE_5512 | SNDRV_PCM_RATE_8000_48000 |
SNDRV_PCM_RATE_KNOT),
.rate_min = 5512,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = MAX_BUF_SIZE,
.period_bytes_min = BUF_SIZE,
.period_bytes_max = BUF_SIZE,
.periods_min = 1,
.periods_max = MAX_BUFS,
.fifo_size = 0,
};
static struct snd_pcm_hardware snd_harmony_capture =
{
.info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_JOINT_DUPLEX | SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_BLOCK_TRANSFER),
.formats = (SNDRV_PCM_FMTBIT_S16_BE | SNDRV_PCM_FMTBIT_MU_LAW |
SNDRV_PCM_FMTBIT_A_LAW),
.rates = (SNDRV_PCM_RATE_5512 | SNDRV_PCM_RATE_8000_48000 |
SNDRV_PCM_RATE_KNOT),
.rate_min = 5512,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = MAX_BUF_SIZE,
.period_bytes_min = BUF_SIZE,
.period_bytes_max = BUF_SIZE,
.periods_min = 1,
.periods_max = MAX_BUFS,
.fifo_size = 0,
};
static int
snd_harmony_playback_trigger(struct snd_pcm_substream *ss, int cmd)
{
struct snd_harmony *h = snd_pcm_substream_chip(ss);
if (h->st.capturing)
return -EBUSY;
spin_lock(&h->lock);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
h->st.playing = 1;
harmony_write(h, HARMONY_PNXTADD, h->pbuf.addr);
harmony_write(h, HARMONY_RNXTADD, h->gdma.addr);
harmony_unmute(h);
harmony_enable_interrupts(h);
break;
case SNDRV_PCM_TRIGGER_STOP:
h->st.playing = 0;
harmony_mute(h);
harmony_write(h, HARMONY_PNXTADD, h->sdma.addr);
harmony_disable_interrupts(h);
break;
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
case SNDRV_PCM_TRIGGER_SUSPEND:
default:
spin_unlock(&h->lock);
snd_BUG();
return -EINVAL;
}
spin_unlock(&h->lock);
return 0;
}
static int
snd_harmony_capture_trigger(struct snd_pcm_substream *ss, int cmd)
{
struct snd_harmony *h = snd_pcm_substream_chip(ss);
if (h->st.playing)
return -EBUSY;
spin_lock(&h->lock);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
h->st.capturing = 1;
harmony_write(h, HARMONY_PNXTADD, h->sdma.addr);
harmony_write(h, HARMONY_RNXTADD, h->cbuf.addr);
harmony_unmute(h);
harmony_enable_interrupts(h);
break;
case SNDRV_PCM_TRIGGER_STOP:
h->st.capturing = 0;
harmony_mute(h);
harmony_write(h, HARMONY_RNXTADD, h->gdma.addr);
harmony_disable_interrupts(h);
break;
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
case SNDRV_PCM_TRIGGER_SUSPEND:
default:
spin_unlock(&h->lock);
snd_BUG();
return -EINVAL;
}
spin_unlock(&h->lock);
return 0;
}
static int
snd_harmony_set_data_format(struct snd_harmony *h, int fmt, int force)
{
int o = h->st.format;
int n;
switch(fmt) {
case SNDRV_PCM_FORMAT_S16_BE:
n = HARMONY_DF_16BIT_LINEAR;
break;
case SNDRV_PCM_FORMAT_A_LAW:
n = HARMONY_DF_8BIT_ALAW;
break;
case SNDRV_PCM_FORMAT_MU_LAW:
n = HARMONY_DF_8BIT_ULAW;
break;
default:
n = HARMONY_DF_16BIT_LINEAR;
break;
}
if (force || o != n) {
snd_pcm_format_set_silence(fmt, h->sdma.area, SILENCE_BUFSZ /
(snd_pcm_format_physical_width(fmt)
/ 8));
}
return n;
}
static int
snd_harmony_playback_prepare(struct snd_pcm_substream *ss)
{
struct snd_harmony *h = snd_pcm_substream_chip(ss);
struct snd_pcm_runtime *rt = ss->runtime;
if (h->st.capturing)
return -EBUSY;
h->pbuf.size = snd_pcm_lib_buffer_bytes(ss);
h->pbuf.count = snd_pcm_lib_period_bytes(ss);
if (h->pbuf.buf >= h->pbuf.size)
h->pbuf.buf = 0;
h->st.playing = 0;
h->st.rate = snd_harmony_rate_bits(rt->rate);
h->st.format = snd_harmony_set_data_format(h, rt->format, 0);
if (rt->channels == 2)
h->st.stereo = HARMONY_SS_STEREO;
else
h->st.stereo = HARMONY_SS_MONO;
harmony_set_control(h);
h->pbuf.addr = rt->dma_addr;
return 0;
}
static int
snd_harmony_capture_prepare(struct snd_pcm_substream *ss)
{
struct snd_harmony *h = snd_pcm_substream_chip(ss);
struct snd_pcm_runtime *rt = ss->runtime;
if (h->st.playing)
return -EBUSY;
h->cbuf.size = snd_pcm_lib_buffer_bytes(ss);
h->cbuf.count = snd_pcm_lib_period_bytes(ss);
if (h->cbuf.buf >= h->cbuf.size)
h->cbuf.buf = 0;
h->st.capturing = 0;
h->st.rate = snd_harmony_rate_bits(rt->rate);
h->st.format = snd_harmony_set_data_format(h, rt->format, 0);
if (rt->channels == 2)
h->st.stereo = HARMONY_SS_STEREO;
else
h->st.stereo = HARMONY_SS_MONO;
harmony_set_control(h);
h->cbuf.addr = rt->dma_addr;
return 0;
}
static snd_pcm_uframes_t
snd_harmony_playback_pointer(struct snd_pcm_substream *ss)
{
struct snd_pcm_runtime *rt = ss->runtime;
struct snd_harmony *h = snd_pcm_substream_chip(ss);
unsigned long pcuradd;
unsigned long played;
if (!(h->st.playing) || (h->psubs == NULL))
return 0;
if ((h->pbuf.addr == 0) || (h->pbuf.size == 0))
return 0;
pcuradd = harmony_read(h, HARMONY_PCURADD);
played = pcuradd - h->pbuf.addr;
#ifdef HARMONY_DEBUG
printk(KERN_DEBUG PFX "playback_pointer is 0x%lx-0x%lx = %d bytes\n",
pcuradd, h->pbuf.addr, played);
#endif
if (pcuradd > h->pbuf.addr + h->pbuf.size) {
return 0;
}
return bytes_to_frames(rt, played);
}
static snd_pcm_uframes_t
snd_harmony_capture_pointer(struct snd_pcm_substream *ss)
{
struct snd_pcm_runtime *rt = ss->runtime;
struct snd_harmony *h = snd_pcm_substream_chip(ss);
unsigned long rcuradd;
unsigned long caught;
if (!(h->st.capturing) || (h->csubs == NULL))
return 0;
if ((h->cbuf.addr == 0) || (h->cbuf.size == 0))
return 0;
rcuradd = harmony_read(h, HARMONY_RCURADD);
caught = rcuradd - h->cbuf.addr;
#ifdef HARMONY_DEBUG
printk(KERN_DEBUG PFX "capture_pointer is 0x%lx-0x%lx = %d bytes\n",
rcuradd, h->cbuf.addr, caught);
#endif
if (rcuradd > h->cbuf.addr + h->cbuf.size) {
return 0;
}
return bytes_to_frames(rt, caught);
}
static int
snd_harmony_playback_open(struct snd_pcm_substream *ss)
{
struct snd_harmony *h = snd_pcm_substream_chip(ss);
struct snd_pcm_runtime *rt = ss->runtime;
int err;
h->psubs = ss;
rt->hw = snd_harmony_playback;
snd_pcm_hw_constraint_list(rt, 0, SNDRV_PCM_HW_PARAM_RATE,
&hw_constraint_rates);
err = snd_pcm_hw_constraint_integer(rt, SNDRV_PCM_HW_PARAM_PERIODS);
if (err < 0)
return err;
return 0;
}
static int
snd_harmony_capture_open(struct snd_pcm_substream *ss)
{
struct snd_harmony *h = snd_pcm_substream_chip(ss);
struct snd_pcm_runtime *rt = ss->runtime;
int err;
h->csubs = ss;
rt->hw = snd_harmony_capture;
snd_pcm_hw_constraint_list(rt, 0, SNDRV_PCM_HW_PARAM_RATE,
&hw_constraint_rates);
err = snd_pcm_hw_constraint_integer(rt, SNDRV_PCM_HW_PARAM_PERIODS);
if (err < 0)
return err;
return 0;
}
static int
snd_harmony_playback_close(struct snd_pcm_substream *ss)
{
struct snd_harmony *h = snd_pcm_substream_chip(ss);
h->psubs = NULL;
return 0;
}
static int
snd_harmony_capture_close(struct snd_pcm_substream *ss)
{
struct snd_harmony *h = snd_pcm_substream_chip(ss);
h->csubs = NULL;
return 0;
}
static int
snd_harmony_hw_params(struct snd_pcm_substream *ss,
struct snd_pcm_hw_params *hw)
{
int err;
struct snd_harmony *h = snd_pcm_substream_chip(ss);
err = snd_pcm_lib_malloc_pages(ss, params_buffer_bytes(hw));
if (err > 0 && h->dma.type == SNDRV_DMA_TYPE_CONTINUOUS)
ss->runtime->dma_addr = __pa(ss->runtime->dma_area);
return err;
}
static int
snd_harmony_hw_free(struct snd_pcm_substream *ss)
{
return snd_pcm_lib_free_pages(ss);
}
static struct snd_pcm_ops snd_harmony_playback_ops = {
.open = snd_harmony_playback_open,
.close = snd_harmony_playback_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_harmony_hw_params,
.hw_free = snd_harmony_hw_free,
.prepare = snd_harmony_playback_prepare,
.trigger = snd_harmony_playback_trigger,
.pointer = snd_harmony_playback_pointer,
};
static struct snd_pcm_ops snd_harmony_capture_ops = {
.open = snd_harmony_capture_open,
.close = snd_harmony_capture_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_harmony_hw_params,
.hw_free = snd_harmony_hw_free,
.prepare = snd_harmony_capture_prepare,
.trigger = snd_harmony_capture_trigger,
.pointer = snd_harmony_capture_pointer,
};
static int
snd_harmony_pcm_init(struct snd_harmony *h)
{
struct snd_pcm *pcm;
int err;
if (snd_BUG_ON(!h))
return -EINVAL;
harmony_disable_interrupts(h);
err = snd_pcm_new(h->card, "harmony", 0, 1, 1, &pcm);
if (err < 0)
return err;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK,
&snd_harmony_playback_ops);
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE,
&snd_harmony_capture_ops);
pcm->private_data = h;
pcm->info_flags = 0;
strcpy(pcm->name, "harmony");
h->pcm = pcm;
h->psubs = NULL;
h->csubs = NULL;
/* initialize graveyard buffer */
h->dma.type = SNDRV_DMA_TYPE_DEV;
h->dma.dev = &h->dev->dev;
err = snd_dma_alloc_pages(h->dma.type,
h->dma.dev,
BUF_SIZE*GRAVEYARD_BUFS,
&h->gdma);
if (err < 0) {
printk(KERN_ERR PFX "cannot allocate graveyard buffer!\n");
return err;
}
/* initialize silence buffers */
err = snd_dma_alloc_pages(h->dma.type,
h->dma.dev,
BUF_SIZE*SILENCE_BUFS,
&h->sdma);
if (err < 0) {
printk(KERN_ERR PFX "cannot allocate silence buffer!\n");
return err;
}
/* pre-allocate space for DMA */
err = snd_pcm_lib_preallocate_pages_for_all(pcm, h->dma.type,
h->dma.dev,
MAX_BUF_SIZE,
MAX_BUF_SIZE);
if (err < 0) {
printk(KERN_ERR PFX "buffer allocation error: %d\n", err);
return err;
}
h->st.format = snd_harmony_set_data_format(h,
SNDRV_PCM_FORMAT_S16_BE, 1);
return 0;
}
static void
snd_harmony_set_new_gain(struct snd_harmony *h)
{
harmony_wait_for_control(h);
harmony_write(h, HARMONY_GAINCTL, h->st.gain);
}
static int
snd_harmony_mixercontrol_info(struct snd_kcontrol *kc,
struct snd_ctl_elem_info *uinfo)
{
int mask = (kc->private_value >> 16) & 0xff;
int left_shift = (kc->private_value) & 0xff;
int right_shift = (kc->private_value >> 8) & 0xff;
uinfo->type = mask == 1 ? SNDRV_CTL_ELEM_TYPE_BOOLEAN :
SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = left_shift == right_shift ? 1 : 2;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = mask;
return 0;
}
static int
snd_harmony_volume_get(struct snd_kcontrol *kc,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_harmony *h = snd_kcontrol_chip(kc);
int shift_left = (kc->private_value) & 0xff;
int shift_right = (kc->private_value >> 8) & 0xff;
int mask = (kc->private_value >> 16) & 0xff;
int invert = (kc->private_value >> 24) & 0xff;
int left, right;
spin_lock_irq(&h->mixer_lock);
left = (h->st.gain >> shift_left) & mask;
right = (h->st.gain >> shift_right) & mask;
if (invert) {
left = mask - left;
right = mask - right;
}
ucontrol->value.integer.value[0] = left;
if (shift_left != shift_right)
ucontrol->value.integer.value[1] = right;
spin_unlock_irq(&h->mixer_lock);
return 0;
}
static int
snd_harmony_volume_put(struct snd_kcontrol *kc,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_harmony *h = snd_kcontrol_chip(kc);
int shift_left = (kc->private_value) & 0xff;
int shift_right = (kc->private_value >> 8) & 0xff;
int mask = (kc->private_value >> 16) & 0xff;
int invert = (kc->private_value >> 24) & 0xff;
int left, right;
int old_gain = h->st.gain;
spin_lock_irq(&h->mixer_lock);
left = ucontrol->value.integer.value[0] & mask;
if (invert)
left = mask - left;
h->st.gain &= ~( (mask << shift_left ) );
h->st.gain |= (left << shift_left);
if (shift_left != shift_right) {
right = ucontrol->value.integer.value[1] & mask;
if (invert)
right = mask - right;
h->st.gain &= ~( (mask << shift_right) );
h->st.gain |= (right << shift_right);
}
snd_harmony_set_new_gain(h);
spin_unlock_irq(&h->mixer_lock);
return h->st.gain != old_gain;
}
static int
snd_harmony_captureroute_info(struct snd_kcontrol *kc,
struct snd_ctl_elem_info *uinfo)
{
static char *texts[2] = { "Line", "Mic" };
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
uinfo->count = 1;
uinfo->value.enumerated.items = 2;
if (uinfo->value.enumerated.item > 1)
uinfo->value.enumerated.item = 1;
strcpy(uinfo->value.enumerated.name,
texts[uinfo->value.enumerated.item]);
return 0;
}
static int
snd_harmony_captureroute_get(struct snd_kcontrol *kc,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_harmony *h = snd_kcontrol_chip(kc);
int value;
spin_lock_irq(&h->mixer_lock);
value = (h->st.gain >> HARMONY_GAIN_IS_SHIFT) & 1;
ucontrol->value.enumerated.item[0] = value;
spin_unlock_irq(&h->mixer_lock);
return 0;
}
static int
snd_harmony_captureroute_put(struct snd_kcontrol *kc,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_harmony *h = snd_kcontrol_chip(kc);
int value;
int old_gain = h->st.gain;
spin_lock_irq(&h->mixer_lock);
value = ucontrol->value.enumerated.item[0] & 1;
h->st.gain &= ~HARMONY_GAIN_IS_MASK;
h->st.gain |= value << HARMONY_GAIN_IS_SHIFT;
snd_harmony_set_new_gain(h);
spin_unlock_irq(&h->mixer_lock);
return h->st.gain != old_gain;
}
#define HARMONY_CONTROLS ARRAY_SIZE(snd_harmony_controls)
#define HARMONY_VOLUME(xname, left_shift, right_shift, mask, invert) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
.info = snd_harmony_mixercontrol_info, \
.get = snd_harmony_volume_get, .put = snd_harmony_volume_put, \
.private_value = ((left_shift) | ((right_shift) << 8) | \
((mask) << 16) | ((invert) << 24)) }
static struct snd_kcontrol_new snd_harmony_controls[] = {
HARMONY_VOLUME("Master Playback Volume", HARMONY_GAIN_LO_SHIFT,
HARMONY_GAIN_RO_SHIFT, HARMONY_GAIN_OUT, 1),
HARMONY_VOLUME("Capture Volume", HARMONY_GAIN_LI_SHIFT,
HARMONY_GAIN_RI_SHIFT, HARMONY_GAIN_IN, 0),
HARMONY_VOLUME("Monitor Volume", HARMONY_GAIN_MA_SHIFT,
HARMONY_GAIN_MA_SHIFT, HARMONY_GAIN_MA, 1),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Input Route",
.info = snd_harmony_captureroute_info,
.get = snd_harmony_captureroute_get,
.put = snd_harmony_captureroute_put
},
HARMONY_VOLUME("Internal Speaker Switch", HARMONY_GAIN_SE_SHIFT,
HARMONY_GAIN_SE_SHIFT, 1, 0),
HARMONY_VOLUME("Line-Out Switch", HARMONY_GAIN_LE_SHIFT,
HARMONY_GAIN_LE_SHIFT, 1, 0),
HARMONY_VOLUME("Headphones Switch", HARMONY_GAIN_HE_SHIFT,
HARMONY_GAIN_HE_SHIFT, 1, 0),
};
static void __devinit
snd_harmony_mixer_reset(struct snd_harmony *h)
{
harmony_mute(h);
harmony_reset(h);
h->st.gain = HARMONY_GAIN_DEFAULT;
harmony_unmute(h);
}
static int __devinit
snd_harmony_mixer_init(struct snd_harmony *h)
{
struct snd_card *card;
int idx, err;
if (snd_BUG_ON(!h))
return -EINVAL;
card = h->card;
strcpy(card->mixername, "Harmony Gain control interface");
for (idx = 0; idx < HARMONY_CONTROLS; idx++) {
err = snd_ctl_add(card,
snd_ctl_new1(&snd_harmony_controls[idx], h));
if (err < 0)
return err;
}
snd_harmony_mixer_reset(h);
return 0;
}
static int
snd_harmony_free(struct snd_harmony *h)
{
if (h->gdma.addr)
snd_dma_free_pages(&h->gdma);
if (h->sdma.addr)
snd_dma_free_pages(&h->sdma);
if (h->irq >= 0)
free_irq(h->irq, h);
if (h->iobase)
iounmap(h->iobase);
parisc_set_drvdata(h->dev, NULL);
kfree(h);
return 0;
}
static int
snd_harmony_dev_free(struct snd_device *dev)
{
struct snd_harmony *h = dev->device_data;
return snd_harmony_free(h);
}
static int __devinit
snd_harmony_create(struct snd_card *card,
struct parisc_device *padev,
struct snd_harmony **rchip)
{
int err;
struct snd_harmony *h;
static struct snd_device_ops ops = {
.dev_free = snd_harmony_dev_free,
};
*rchip = NULL;
h = kzalloc(sizeof(*h), GFP_KERNEL);
if (h == NULL)
return -ENOMEM;
h->hpa = padev->hpa.start;
h->card = card;
h->dev = padev;
h->irq = -1;
h->iobase = ioremap_nocache(padev->hpa.start, HARMONY_SIZE);
if (h->iobase == NULL) {
printk(KERN_ERR PFX "unable to remap hpa 0x%lx\n",
(unsigned long)padev->hpa.start);
err = -EBUSY;
goto free_and_ret;
}
err = request_irq(padev->irq, snd_harmony_interrupt, 0,
"harmony", h);
if (err) {
printk(KERN_ERR PFX "could not obtain interrupt %d",
padev->irq);
goto free_and_ret;
}
h->irq = padev->irq;
spin_lock_init(&h->mixer_lock);
spin_lock_init(&h->lock);
if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL,
h, &ops)) < 0) {
goto free_and_ret;
}
snd_card_set_dev(card, &padev->dev);
*rchip = h;
return 0;
free_and_ret:
snd_harmony_free(h);
return err;
}
static int __devinit
snd_harmony_probe(struct parisc_device *padev)
{
int err;
struct snd_card *card;
struct snd_harmony *h;
err = snd_card_create(index, id, THIS_MODULE, 0, &card);
if (err < 0)
return err;
err = snd_harmony_create(card, padev, &h);
if (err < 0)
goto free_and_ret;
err = snd_harmony_pcm_init(h);
if (err < 0)
goto free_and_ret;
err = snd_harmony_mixer_init(h);
if (err < 0)
goto free_and_ret;
strcpy(card->driver, "harmony");
strcpy(card->shortname, "Harmony");
sprintf(card->longname, "%s at 0x%lx, irq %i",
card->shortname, h->hpa, h->irq);
err = snd_card_register(card);
if (err < 0)
goto free_and_ret;
parisc_set_drvdata(padev, card);
return 0;
free_and_ret:
snd_card_free(card);
return err;
}
static int __devexit
snd_harmony_remove(struct parisc_device *padev)
{
snd_card_free(parisc_get_drvdata(padev));
parisc_set_drvdata(padev, NULL);
return 0;
}
static struct parisc_driver snd_harmony_driver = {
.name = "harmony",
.id_table = snd_harmony_devtable,
.probe = snd_harmony_probe,
.remove = __devexit_p(snd_harmony_remove),
};
static int __init
alsa_harmony_init(void)
{
return register_parisc_driver(&snd_harmony_driver);
}
static void __exit
alsa_harmony_fini(void)
{
unregister_parisc_driver(&snd_harmony_driver);
}
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Kyle McMartin <kyle@parisc-linux.org>");
MODULE_DESCRIPTION("Harmony sound driver");
module_init(alsa_harmony_init);
module_exit(alsa_harmony_fini);
| gpl-2.0 |
Californication/lge-kernel-msm7x27-SDSL | sound/parisc/harmony.c | 9823 | 25954 | /* Hewlett-Packard Harmony audio driver
*
* This is a driver for the Harmony audio chipset found
* on the LASI ASIC of various early HP PA-RISC workstations.
*
* Copyright (C) 2004, Kyle McMartin <kyle@{debian.org,parisc-linux.org}>
*
* Based on the previous Harmony incarnations by,
* Copyright 2000 (c) Linuxcare Canada, Alex deVries
* Copyright 2000-2003 (c) Helge Deller
* Copyright 2001 (c) Matthieu Delahaye
* Copyright 2001 (c) Jean-Christophe Vaugeois
* Copyright 2003 (c) Laurent Canet
* Copyright 2004 (c) Stuart Brady
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 2, as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Notes:
* - graveyard and silence buffers last for lifetime of
* the driver. playback and capture buffers are allocated
* per _open()/_close().
*
* TODO:
*
*/
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/time.h>
#include <linux/wait.h>
#include <linux/delay.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/spinlock.h>
#include <linux/dma-mapping.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/control.h>
#include <sound/rawmidi.h>
#include <sound/initval.h>
#include <sound/info.h>
#include <asm/io.h>
#include <asm/hardware.h>
#include <asm/parisc-device.h>
#include "harmony.h"
static int index = SNDRV_DEFAULT_IDX1; /* Index 0-MAX */
static char *id = SNDRV_DEFAULT_STR1; /* ID for this card */
module_param(index, int, 0444);
MODULE_PARM_DESC(index, "Index value for Harmony driver.");
module_param(id, charp, 0444);
MODULE_PARM_DESC(id, "ID string for Harmony driver.");
static struct parisc_device_id snd_harmony_devtable[] = {
/* bushmaster / flounder */
{ HPHW_FIO, HVERSION_REV_ANY_ID, HVERSION_ANY_ID, 0x0007A },
/* 712 / 715 */
{ HPHW_FIO, HVERSION_REV_ANY_ID, HVERSION_ANY_ID, 0x0007B },
/* pace */
{ HPHW_FIO, HVERSION_REV_ANY_ID, HVERSION_ANY_ID, 0x0007E },
/* outfield / coral II */
{ HPHW_FIO, HVERSION_REV_ANY_ID, HVERSION_ANY_ID, 0x0007F },
{ 0, }
};
MODULE_DEVICE_TABLE(parisc, snd_harmony_devtable);
#define NAME "harmony"
#define PFX NAME ": "
static unsigned int snd_harmony_rates[] = {
5512, 6615, 8000, 9600,
11025, 16000, 18900, 22050,
27428, 32000, 33075, 37800,
44100, 48000
};
static unsigned int rate_bits[14] = {
HARMONY_SR_5KHZ, HARMONY_SR_6KHZ, HARMONY_SR_8KHZ,
HARMONY_SR_9KHZ, HARMONY_SR_11KHZ, HARMONY_SR_16KHZ,
HARMONY_SR_18KHZ, HARMONY_SR_22KHZ, HARMONY_SR_27KHZ,
HARMONY_SR_32KHZ, HARMONY_SR_33KHZ, HARMONY_SR_37KHZ,
HARMONY_SR_44KHZ, HARMONY_SR_48KHZ
};
static struct snd_pcm_hw_constraint_list hw_constraint_rates = {
.count = ARRAY_SIZE(snd_harmony_rates),
.list = snd_harmony_rates,
.mask = 0,
};
static inline unsigned long
harmony_read(struct snd_harmony *h, unsigned r)
{
return __raw_readl(h->iobase + r);
}
static inline void
harmony_write(struct snd_harmony *h, unsigned r, unsigned long v)
{
__raw_writel(v, h->iobase + r);
}
static inline void
harmony_wait_for_control(struct snd_harmony *h)
{
while (harmony_read(h, HARMONY_CNTL) & HARMONY_CNTL_C) ;
}
static inline void
harmony_reset(struct snd_harmony *h)
{
harmony_write(h, HARMONY_RESET, 1);
mdelay(50);
harmony_write(h, HARMONY_RESET, 0);
}
static void
harmony_disable_interrupts(struct snd_harmony *h)
{
u32 dstatus;
harmony_wait_for_control(h);
dstatus = harmony_read(h, HARMONY_DSTATUS);
dstatus &= ~HARMONY_DSTATUS_IE;
harmony_write(h, HARMONY_DSTATUS, dstatus);
}
static void
harmony_enable_interrupts(struct snd_harmony *h)
{
u32 dstatus;
harmony_wait_for_control(h);
dstatus = harmony_read(h, HARMONY_DSTATUS);
dstatus |= HARMONY_DSTATUS_IE;
harmony_write(h, HARMONY_DSTATUS, dstatus);
}
static void
harmony_mute(struct snd_harmony *h)
{
unsigned long flags;
spin_lock_irqsave(&h->mixer_lock, flags);
harmony_wait_for_control(h);
harmony_write(h, HARMONY_GAINCTL, HARMONY_GAIN_SILENCE);
spin_unlock_irqrestore(&h->mixer_lock, flags);
}
static void
harmony_unmute(struct snd_harmony *h)
{
unsigned long flags;
spin_lock_irqsave(&h->mixer_lock, flags);
harmony_wait_for_control(h);
harmony_write(h, HARMONY_GAINCTL, h->st.gain);
spin_unlock_irqrestore(&h->mixer_lock, flags);
}
static void
harmony_set_control(struct snd_harmony *h)
{
u32 ctrl;
unsigned long flags;
spin_lock_irqsave(&h->lock, flags);
ctrl = (HARMONY_CNTL_C |
(h->st.format << 6) |
(h->st.stereo << 5) |
(h->st.rate));
harmony_wait_for_control(h);
harmony_write(h, HARMONY_CNTL, ctrl);
spin_unlock_irqrestore(&h->lock, flags);
}
static irqreturn_t
snd_harmony_interrupt(int irq, void *dev)
{
u32 dstatus;
struct snd_harmony *h = dev;
spin_lock(&h->lock);
harmony_disable_interrupts(h);
harmony_wait_for_control(h);
dstatus = harmony_read(h, HARMONY_DSTATUS);
spin_unlock(&h->lock);
if (dstatus & HARMONY_DSTATUS_PN) {
if (h->psubs && h->st.playing) {
spin_lock(&h->lock);
h->pbuf.buf += h->pbuf.count; /* PAGE_SIZE */
h->pbuf.buf %= h->pbuf.size; /* MAX_BUFS*PAGE_SIZE */
harmony_write(h, HARMONY_PNXTADD,
h->pbuf.addr + h->pbuf.buf);
h->stats.play_intr++;
spin_unlock(&h->lock);
snd_pcm_period_elapsed(h->psubs);
} else {
spin_lock(&h->lock);
harmony_write(h, HARMONY_PNXTADD, h->sdma.addr);
h->stats.silence_intr++;
spin_unlock(&h->lock);
}
}
if (dstatus & HARMONY_DSTATUS_RN) {
if (h->csubs && h->st.capturing) {
spin_lock(&h->lock);
h->cbuf.buf += h->cbuf.count;
h->cbuf.buf %= h->cbuf.size;
harmony_write(h, HARMONY_RNXTADD,
h->cbuf.addr + h->cbuf.buf);
h->stats.rec_intr++;
spin_unlock(&h->lock);
snd_pcm_period_elapsed(h->csubs);
} else {
spin_lock(&h->lock);
harmony_write(h, HARMONY_RNXTADD, h->gdma.addr);
h->stats.graveyard_intr++;
spin_unlock(&h->lock);
}
}
spin_lock(&h->lock);
harmony_enable_interrupts(h);
spin_unlock(&h->lock);
return IRQ_HANDLED;
}
static unsigned int
snd_harmony_rate_bits(int rate)
{
unsigned int i;
for (i = 0; i < ARRAY_SIZE(snd_harmony_rates); i++)
if (snd_harmony_rates[i] == rate)
return rate_bits[i];
return HARMONY_SR_44KHZ;
}
static struct snd_pcm_hardware snd_harmony_playback =
{
.info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_JOINT_DUPLEX | SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_BLOCK_TRANSFER),
.formats = (SNDRV_PCM_FMTBIT_S16_BE | SNDRV_PCM_FMTBIT_MU_LAW |
SNDRV_PCM_FMTBIT_A_LAW),
.rates = (SNDRV_PCM_RATE_5512 | SNDRV_PCM_RATE_8000_48000 |
SNDRV_PCM_RATE_KNOT),
.rate_min = 5512,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = MAX_BUF_SIZE,
.period_bytes_min = BUF_SIZE,
.period_bytes_max = BUF_SIZE,
.periods_min = 1,
.periods_max = MAX_BUFS,
.fifo_size = 0,
};
static struct snd_pcm_hardware snd_harmony_capture =
{
.info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_JOINT_DUPLEX | SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_BLOCK_TRANSFER),
.formats = (SNDRV_PCM_FMTBIT_S16_BE | SNDRV_PCM_FMTBIT_MU_LAW |
SNDRV_PCM_FMTBIT_A_LAW),
.rates = (SNDRV_PCM_RATE_5512 | SNDRV_PCM_RATE_8000_48000 |
SNDRV_PCM_RATE_KNOT),
.rate_min = 5512,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = MAX_BUF_SIZE,
.period_bytes_min = BUF_SIZE,
.period_bytes_max = BUF_SIZE,
.periods_min = 1,
.periods_max = MAX_BUFS,
.fifo_size = 0,
};
static int
snd_harmony_playback_trigger(struct snd_pcm_substream *ss, int cmd)
{
struct snd_harmony *h = snd_pcm_substream_chip(ss);
if (h->st.capturing)
return -EBUSY;
spin_lock(&h->lock);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
h->st.playing = 1;
harmony_write(h, HARMONY_PNXTADD, h->pbuf.addr);
harmony_write(h, HARMONY_RNXTADD, h->gdma.addr);
harmony_unmute(h);
harmony_enable_interrupts(h);
break;
case SNDRV_PCM_TRIGGER_STOP:
h->st.playing = 0;
harmony_mute(h);
harmony_write(h, HARMONY_PNXTADD, h->sdma.addr);
harmony_disable_interrupts(h);
break;
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
case SNDRV_PCM_TRIGGER_SUSPEND:
default:
spin_unlock(&h->lock);
snd_BUG();
return -EINVAL;
}
spin_unlock(&h->lock);
return 0;
}
static int
snd_harmony_capture_trigger(struct snd_pcm_substream *ss, int cmd)
{
struct snd_harmony *h = snd_pcm_substream_chip(ss);
if (h->st.playing)
return -EBUSY;
spin_lock(&h->lock);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
h->st.capturing = 1;
harmony_write(h, HARMONY_PNXTADD, h->sdma.addr);
harmony_write(h, HARMONY_RNXTADD, h->cbuf.addr);
harmony_unmute(h);
harmony_enable_interrupts(h);
break;
case SNDRV_PCM_TRIGGER_STOP:
h->st.capturing = 0;
harmony_mute(h);
harmony_write(h, HARMONY_RNXTADD, h->gdma.addr);
harmony_disable_interrupts(h);
break;
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
case SNDRV_PCM_TRIGGER_SUSPEND:
default:
spin_unlock(&h->lock);
snd_BUG();
return -EINVAL;
}
spin_unlock(&h->lock);
return 0;
}
static int
snd_harmony_set_data_format(struct snd_harmony *h, int fmt, int force)
{
int o = h->st.format;
int n;
switch(fmt) {
case SNDRV_PCM_FORMAT_S16_BE:
n = HARMONY_DF_16BIT_LINEAR;
break;
case SNDRV_PCM_FORMAT_A_LAW:
n = HARMONY_DF_8BIT_ALAW;
break;
case SNDRV_PCM_FORMAT_MU_LAW:
n = HARMONY_DF_8BIT_ULAW;
break;
default:
n = HARMONY_DF_16BIT_LINEAR;
break;
}
if (force || o != n) {
snd_pcm_format_set_silence(fmt, h->sdma.area, SILENCE_BUFSZ /
(snd_pcm_format_physical_width(fmt)
/ 8));
}
return n;
}
static int
snd_harmony_playback_prepare(struct snd_pcm_substream *ss)
{
struct snd_harmony *h = snd_pcm_substream_chip(ss);
struct snd_pcm_runtime *rt = ss->runtime;
if (h->st.capturing)
return -EBUSY;
h->pbuf.size = snd_pcm_lib_buffer_bytes(ss);
h->pbuf.count = snd_pcm_lib_period_bytes(ss);
if (h->pbuf.buf >= h->pbuf.size)
h->pbuf.buf = 0;
h->st.playing = 0;
h->st.rate = snd_harmony_rate_bits(rt->rate);
h->st.format = snd_harmony_set_data_format(h, rt->format, 0);
if (rt->channels == 2)
h->st.stereo = HARMONY_SS_STEREO;
else
h->st.stereo = HARMONY_SS_MONO;
harmony_set_control(h);
h->pbuf.addr = rt->dma_addr;
return 0;
}
static int
snd_harmony_capture_prepare(struct snd_pcm_substream *ss)
{
struct snd_harmony *h = snd_pcm_substream_chip(ss);
struct snd_pcm_runtime *rt = ss->runtime;
if (h->st.playing)
return -EBUSY;
h->cbuf.size = snd_pcm_lib_buffer_bytes(ss);
h->cbuf.count = snd_pcm_lib_period_bytes(ss);
if (h->cbuf.buf >= h->cbuf.size)
h->cbuf.buf = 0;
h->st.capturing = 0;
h->st.rate = snd_harmony_rate_bits(rt->rate);
h->st.format = snd_harmony_set_data_format(h, rt->format, 0);
if (rt->channels == 2)
h->st.stereo = HARMONY_SS_STEREO;
else
h->st.stereo = HARMONY_SS_MONO;
harmony_set_control(h);
h->cbuf.addr = rt->dma_addr;
return 0;
}
static snd_pcm_uframes_t
snd_harmony_playback_pointer(struct snd_pcm_substream *ss)
{
struct snd_pcm_runtime *rt = ss->runtime;
struct snd_harmony *h = snd_pcm_substream_chip(ss);
unsigned long pcuradd;
unsigned long played;
if (!(h->st.playing) || (h->psubs == NULL))
return 0;
if ((h->pbuf.addr == 0) || (h->pbuf.size == 0))
return 0;
pcuradd = harmony_read(h, HARMONY_PCURADD);
played = pcuradd - h->pbuf.addr;
#ifdef HARMONY_DEBUG
printk(KERN_DEBUG PFX "playback_pointer is 0x%lx-0x%lx = %d bytes\n",
pcuradd, h->pbuf.addr, played);
#endif
if (pcuradd > h->pbuf.addr + h->pbuf.size) {
return 0;
}
return bytes_to_frames(rt, played);
}
static snd_pcm_uframes_t
snd_harmony_capture_pointer(struct snd_pcm_substream *ss)
{
struct snd_pcm_runtime *rt = ss->runtime;
struct snd_harmony *h = snd_pcm_substream_chip(ss);
unsigned long rcuradd;
unsigned long caught;
if (!(h->st.capturing) || (h->csubs == NULL))
return 0;
if ((h->cbuf.addr == 0) || (h->cbuf.size == 0))
return 0;
rcuradd = harmony_read(h, HARMONY_RCURADD);
caught = rcuradd - h->cbuf.addr;
#ifdef HARMONY_DEBUG
printk(KERN_DEBUG PFX "capture_pointer is 0x%lx-0x%lx = %d bytes\n",
rcuradd, h->cbuf.addr, caught);
#endif
if (rcuradd > h->cbuf.addr + h->cbuf.size) {
return 0;
}
return bytes_to_frames(rt, caught);
}
static int
snd_harmony_playback_open(struct snd_pcm_substream *ss)
{
struct snd_harmony *h = snd_pcm_substream_chip(ss);
struct snd_pcm_runtime *rt = ss->runtime;
int err;
h->psubs = ss;
rt->hw = snd_harmony_playback;
snd_pcm_hw_constraint_list(rt, 0, SNDRV_PCM_HW_PARAM_RATE,
&hw_constraint_rates);
err = snd_pcm_hw_constraint_integer(rt, SNDRV_PCM_HW_PARAM_PERIODS);
if (err < 0)
return err;
return 0;
}
static int
snd_harmony_capture_open(struct snd_pcm_substream *ss)
{
struct snd_harmony *h = snd_pcm_substream_chip(ss);
struct snd_pcm_runtime *rt = ss->runtime;
int err;
h->csubs = ss;
rt->hw = snd_harmony_capture;
snd_pcm_hw_constraint_list(rt, 0, SNDRV_PCM_HW_PARAM_RATE,
&hw_constraint_rates);
err = snd_pcm_hw_constraint_integer(rt, SNDRV_PCM_HW_PARAM_PERIODS);
if (err < 0)
return err;
return 0;
}
static int
snd_harmony_playback_close(struct snd_pcm_substream *ss)
{
struct snd_harmony *h = snd_pcm_substream_chip(ss);
h->psubs = NULL;
return 0;
}
static int
snd_harmony_capture_close(struct snd_pcm_substream *ss)
{
struct snd_harmony *h = snd_pcm_substream_chip(ss);
h->csubs = NULL;
return 0;
}
static int
snd_harmony_hw_params(struct snd_pcm_substream *ss,
struct snd_pcm_hw_params *hw)
{
int err;
struct snd_harmony *h = snd_pcm_substream_chip(ss);
err = snd_pcm_lib_malloc_pages(ss, params_buffer_bytes(hw));
if (err > 0 && h->dma.type == SNDRV_DMA_TYPE_CONTINUOUS)
ss->runtime->dma_addr = __pa(ss->runtime->dma_area);
return err;
}
static int
snd_harmony_hw_free(struct snd_pcm_substream *ss)
{
return snd_pcm_lib_free_pages(ss);
}
static struct snd_pcm_ops snd_harmony_playback_ops = {
.open = snd_harmony_playback_open,
.close = snd_harmony_playback_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_harmony_hw_params,
.hw_free = snd_harmony_hw_free,
.prepare = snd_harmony_playback_prepare,
.trigger = snd_harmony_playback_trigger,
.pointer = snd_harmony_playback_pointer,
};
static struct snd_pcm_ops snd_harmony_capture_ops = {
.open = snd_harmony_capture_open,
.close = snd_harmony_capture_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_harmony_hw_params,
.hw_free = snd_harmony_hw_free,
.prepare = snd_harmony_capture_prepare,
.trigger = snd_harmony_capture_trigger,
.pointer = snd_harmony_capture_pointer,
};
static int
snd_harmony_pcm_init(struct snd_harmony *h)
{
struct snd_pcm *pcm;
int err;
if (snd_BUG_ON(!h))
return -EINVAL;
harmony_disable_interrupts(h);
err = snd_pcm_new(h->card, "harmony", 0, 1, 1, &pcm);
if (err < 0)
return err;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK,
&snd_harmony_playback_ops);
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE,
&snd_harmony_capture_ops);
pcm->private_data = h;
pcm->info_flags = 0;
strcpy(pcm->name, "harmony");
h->pcm = pcm;
h->psubs = NULL;
h->csubs = NULL;
/* initialize graveyard buffer */
h->dma.type = SNDRV_DMA_TYPE_DEV;
h->dma.dev = &h->dev->dev;
err = snd_dma_alloc_pages(h->dma.type,
h->dma.dev,
BUF_SIZE*GRAVEYARD_BUFS,
&h->gdma);
if (err < 0) {
printk(KERN_ERR PFX "cannot allocate graveyard buffer!\n");
return err;
}
/* initialize silence buffers */
err = snd_dma_alloc_pages(h->dma.type,
h->dma.dev,
BUF_SIZE*SILENCE_BUFS,
&h->sdma);
if (err < 0) {
printk(KERN_ERR PFX "cannot allocate silence buffer!\n");
return err;
}
/* pre-allocate space for DMA */
err = snd_pcm_lib_preallocate_pages_for_all(pcm, h->dma.type,
h->dma.dev,
MAX_BUF_SIZE,
MAX_BUF_SIZE);
if (err < 0) {
printk(KERN_ERR PFX "buffer allocation error: %d\n", err);
return err;
}
h->st.format = snd_harmony_set_data_format(h,
SNDRV_PCM_FORMAT_S16_BE, 1);
return 0;
}
static void
snd_harmony_set_new_gain(struct snd_harmony *h)
{
harmony_wait_for_control(h);
harmony_write(h, HARMONY_GAINCTL, h->st.gain);
}
static int
snd_harmony_mixercontrol_info(struct snd_kcontrol *kc,
struct snd_ctl_elem_info *uinfo)
{
int mask = (kc->private_value >> 16) & 0xff;
int left_shift = (kc->private_value) & 0xff;
int right_shift = (kc->private_value >> 8) & 0xff;
uinfo->type = mask == 1 ? SNDRV_CTL_ELEM_TYPE_BOOLEAN :
SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = left_shift == right_shift ? 1 : 2;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = mask;
return 0;
}
static int
snd_harmony_volume_get(struct snd_kcontrol *kc,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_harmony *h = snd_kcontrol_chip(kc);
int shift_left = (kc->private_value) & 0xff;
int shift_right = (kc->private_value >> 8) & 0xff;
int mask = (kc->private_value >> 16) & 0xff;
int invert = (kc->private_value >> 24) & 0xff;
int left, right;
spin_lock_irq(&h->mixer_lock);
left = (h->st.gain >> shift_left) & mask;
right = (h->st.gain >> shift_right) & mask;
if (invert) {
left = mask - left;
right = mask - right;
}
ucontrol->value.integer.value[0] = left;
if (shift_left != shift_right)
ucontrol->value.integer.value[1] = right;
spin_unlock_irq(&h->mixer_lock);
return 0;
}
static int
snd_harmony_volume_put(struct snd_kcontrol *kc,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_harmony *h = snd_kcontrol_chip(kc);
int shift_left = (kc->private_value) & 0xff;
int shift_right = (kc->private_value >> 8) & 0xff;
int mask = (kc->private_value >> 16) & 0xff;
int invert = (kc->private_value >> 24) & 0xff;
int left, right;
int old_gain = h->st.gain;
spin_lock_irq(&h->mixer_lock);
left = ucontrol->value.integer.value[0] & mask;
if (invert)
left = mask - left;
h->st.gain &= ~( (mask << shift_left ) );
h->st.gain |= (left << shift_left);
if (shift_left != shift_right) {
right = ucontrol->value.integer.value[1] & mask;
if (invert)
right = mask - right;
h->st.gain &= ~( (mask << shift_right) );
h->st.gain |= (right << shift_right);
}
snd_harmony_set_new_gain(h);
spin_unlock_irq(&h->mixer_lock);
return h->st.gain != old_gain;
}
static int
snd_harmony_captureroute_info(struct snd_kcontrol *kc,
struct snd_ctl_elem_info *uinfo)
{
static char *texts[2] = { "Line", "Mic" };
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
uinfo->count = 1;
uinfo->value.enumerated.items = 2;
if (uinfo->value.enumerated.item > 1)
uinfo->value.enumerated.item = 1;
strcpy(uinfo->value.enumerated.name,
texts[uinfo->value.enumerated.item]);
return 0;
}
static int
snd_harmony_captureroute_get(struct snd_kcontrol *kc,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_harmony *h = snd_kcontrol_chip(kc);
int value;
spin_lock_irq(&h->mixer_lock);
value = (h->st.gain >> HARMONY_GAIN_IS_SHIFT) & 1;
ucontrol->value.enumerated.item[0] = value;
spin_unlock_irq(&h->mixer_lock);
return 0;
}
static int
snd_harmony_captureroute_put(struct snd_kcontrol *kc,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_harmony *h = snd_kcontrol_chip(kc);
int value;
int old_gain = h->st.gain;
spin_lock_irq(&h->mixer_lock);
value = ucontrol->value.enumerated.item[0] & 1;
h->st.gain &= ~HARMONY_GAIN_IS_MASK;
h->st.gain |= value << HARMONY_GAIN_IS_SHIFT;
snd_harmony_set_new_gain(h);
spin_unlock_irq(&h->mixer_lock);
return h->st.gain != old_gain;
}
#define HARMONY_CONTROLS ARRAY_SIZE(snd_harmony_controls)
#define HARMONY_VOLUME(xname, left_shift, right_shift, mask, invert) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
.info = snd_harmony_mixercontrol_info, \
.get = snd_harmony_volume_get, .put = snd_harmony_volume_put, \
.private_value = ((left_shift) | ((right_shift) << 8) | \
((mask) << 16) | ((invert) << 24)) }
static struct snd_kcontrol_new snd_harmony_controls[] = {
HARMONY_VOLUME("Master Playback Volume", HARMONY_GAIN_LO_SHIFT,
HARMONY_GAIN_RO_SHIFT, HARMONY_GAIN_OUT, 1),
HARMONY_VOLUME("Capture Volume", HARMONY_GAIN_LI_SHIFT,
HARMONY_GAIN_RI_SHIFT, HARMONY_GAIN_IN, 0),
HARMONY_VOLUME("Monitor Volume", HARMONY_GAIN_MA_SHIFT,
HARMONY_GAIN_MA_SHIFT, HARMONY_GAIN_MA, 1),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Input Route",
.info = snd_harmony_captureroute_info,
.get = snd_harmony_captureroute_get,
.put = snd_harmony_captureroute_put
},
HARMONY_VOLUME("Internal Speaker Switch", HARMONY_GAIN_SE_SHIFT,
HARMONY_GAIN_SE_SHIFT, 1, 0),
HARMONY_VOLUME("Line-Out Switch", HARMONY_GAIN_LE_SHIFT,
HARMONY_GAIN_LE_SHIFT, 1, 0),
HARMONY_VOLUME("Headphones Switch", HARMONY_GAIN_HE_SHIFT,
HARMONY_GAIN_HE_SHIFT, 1, 0),
};
static void __devinit
snd_harmony_mixer_reset(struct snd_harmony *h)
{
harmony_mute(h);
harmony_reset(h);
h->st.gain = HARMONY_GAIN_DEFAULT;
harmony_unmute(h);
}
static int __devinit
snd_harmony_mixer_init(struct snd_harmony *h)
{
struct snd_card *card;
int idx, err;
if (snd_BUG_ON(!h))
return -EINVAL;
card = h->card;
strcpy(card->mixername, "Harmony Gain control interface");
for (idx = 0; idx < HARMONY_CONTROLS; idx++) {
err = snd_ctl_add(card,
snd_ctl_new1(&snd_harmony_controls[idx], h));
if (err < 0)
return err;
}
snd_harmony_mixer_reset(h);
return 0;
}
static int
snd_harmony_free(struct snd_harmony *h)
{
if (h->gdma.addr)
snd_dma_free_pages(&h->gdma);
if (h->sdma.addr)
snd_dma_free_pages(&h->sdma);
if (h->irq >= 0)
free_irq(h->irq, h);
if (h->iobase)
iounmap(h->iobase);
parisc_set_drvdata(h->dev, NULL);
kfree(h);
return 0;
}
static int
snd_harmony_dev_free(struct snd_device *dev)
{
struct snd_harmony *h = dev->device_data;
return snd_harmony_free(h);
}
static int __devinit
snd_harmony_create(struct snd_card *card,
struct parisc_device *padev,
struct snd_harmony **rchip)
{
int err;
struct snd_harmony *h;
static struct snd_device_ops ops = {
.dev_free = snd_harmony_dev_free,
};
*rchip = NULL;
h = kzalloc(sizeof(*h), GFP_KERNEL);
if (h == NULL)
return -ENOMEM;
h->hpa = padev->hpa.start;
h->card = card;
h->dev = padev;
h->irq = -1;
h->iobase = ioremap_nocache(padev->hpa.start, HARMONY_SIZE);
if (h->iobase == NULL) {
printk(KERN_ERR PFX "unable to remap hpa 0x%lx\n",
(unsigned long)padev->hpa.start);
err = -EBUSY;
goto free_and_ret;
}
err = request_irq(padev->irq, snd_harmony_interrupt, 0,
"harmony", h);
if (err) {
printk(KERN_ERR PFX "could not obtain interrupt %d",
padev->irq);
goto free_and_ret;
}
h->irq = padev->irq;
spin_lock_init(&h->mixer_lock);
spin_lock_init(&h->lock);
if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL,
h, &ops)) < 0) {
goto free_and_ret;
}
snd_card_set_dev(card, &padev->dev);
*rchip = h;
return 0;
free_and_ret:
snd_harmony_free(h);
return err;
}
static int __devinit
snd_harmony_probe(struct parisc_device *padev)
{
int err;
struct snd_card *card;
struct snd_harmony *h;
err = snd_card_create(index, id, THIS_MODULE, 0, &card);
if (err < 0)
return err;
err = snd_harmony_create(card, padev, &h);
if (err < 0)
goto free_and_ret;
err = snd_harmony_pcm_init(h);
if (err < 0)
goto free_and_ret;
err = snd_harmony_mixer_init(h);
if (err < 0)
goto free_and_ret;
strcpy(card->driver, "harmony");
strcpy(card->shortname, "Harmony");
sprintf(card->longname, "%s at 0x%lx, irq %i",
card->shortname, h->hpa, h->irq);
err = snd_card_register(card);
if (err < 0)
goto free_and_ret;
parisc_set_drvdata(padev, card);
return 0;
free_and_ret:
snd_card_free(card);
return err;
}
static int __devexit
snd_harmony_remove(struct parisc_device *padev)
{
snd_card_free(parisc_get_drvdata(padev));
parisc_set_drvdata(padev, NULL);
return 0;
}
static struct parisc_driver snd_harmony_driver = {
.name = "harmony",
.id_table = snd_harmony_devtable,
.probe = snd_harmony_probe,
.remove = __devexit_p(snd_harmony_remove),
};
static int __init
alsa_harmony_init(void)
{
return register_parisc_driver(&snd_harmony_driver);
}
static void __exit
alsa_harmony_fini(void)
{
unregister_parisc_driver(&snd_harmony_driver);
}
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Kyle McMartin <kyle@parisc-linux.org>");
MODULE_DESCRIPTION("Harmony sound driver");
module_init(alsa_harmony_init);
module_exit(alsa_harmony_fini);
| gpl-2.0 |
Jewbie/Kernel-2.6.32 | arch/ia64/sn/pci/pcibr/pcibr_reg.c | 14175 | 7374 | /*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*
* Copyright (C) 2004 Silicon Graphics, Inc. All rights reserved.
*/
#include <linux/interrupt.h>
#include <linux/types.h>
#include <asm/sn/io.h>
#include <asm/sn/pcibr_provider.h>
#include <asm/sn/pcibus_provider_defs.h>
#include <asm/sn/pcidev.h>
#include <asm/sn/pic.h>
#include <asm/sn/tiocp.h>
union br_ptr {
struct tiocp tio;
struct pic pic;
};
/*
* Control Register Access -- Read/Write 0000_0020
*/
void pcireg_control_bit_clr(struct pcibus_info *pcibus_info, u64 bits)
{
union br_ptr __iomem *ptr = (union br_ptr __iomem *)pcibus_info->pbi_buscommon.bs_base;
if (pcibus_info) {
switch (pcibus_info->pbi_bridge_type) {
case PCIBR_BRIDGETYPE_TIOCP:
__sn_clrq_relaxed(&ptr->tio.cp_control, bits);
break;
case PCIBR_BRIDGETYPE_PIC:
__sn_clrq_relaxed(&ptr->pic.p_wid_control, bits);
break;
default:
panic
("pcireg_control_bit_clr: unknown bridgetype bridge 0x%p",
ptr);
}
}
}
void pcireg_control_bit_set(struct pcibus_info *pcibus_info, u64 bits)
{
union br_ptr __iomem *ptr = (union br_ptr __iomem *)pcibus_info->pbi_buscommon.bs_base;
if (pcibus_info) {
switch (pcibus_info->pbi_bridge_type) {
case PCIBR_BRIDGETYPE_TIOCP:
__sn_setq_relaxed(&ptr->tio.cp_control, bits);
break;
case PCIBR_BRIDGETYPE_PIC:
__sn_setq_relaxed(&ptr->pic.p_wid_control, bits);
break;
default:
panic
("pcireg_control_bit_set: unknown bridgetype bridge 0x%p",
ptr);
}
}
}
/*
* PCI/PCIX Target Flush Register Access -- Read Only 0000_0050
*/
u64 pcireg_tflush_get(struct pcibus_info *pcibus_info)
{
union br_ptr __iomem *ptr = (union br_ptr __iomem *)pcibus_info->pbi_buscommon.bs_base;
u64 ret = 0;
if (pcibus_info) {
switch (pcibus_info->pbi_bridge_type) {
case PCIBR_BRIDGETYPE_TIOCP:
ret = __sn_readq_relaxed(&ptr->tio.cp_tflush);
break;
case PCIBR_BRIDGETYPE_PIC:
ret = __sn_readq_relaxed(&ptr->pic.p_wid_tflush);
break;
default:
panic
("pcireg_tflush_get: unknown bridgetype bridge 0x%p",
ptr);
}
}
/* Read of the Target Flush should always return zero */
if (ret != 0)
panic("pcireg_tflush_get:Target Flush failed\n");
return ret;
}
/*
* Interrupt Status Register Access -- Read Only 0000_0100
*/
u64 pcireg_intr_status_get(struct pcibus_info * pcibus_info)
{
union br_ptr __iomem *ptr = (union br_ptr __iomem *)pcibus_info->pbi_buscommon.bs_base;
u64 ret = 0;
if (pcibus_info) {
switch (pcibus_info->pbi_bridge_type) {
case PCIBR_BRIDGETYPE_TIOCP:
ret = __sn_readq_relaxed(&ptr->tio.cp_int_status);
break;
case PCIBR_BRIDGETYPE_PIC:
ret = __sn_readq_relaxed(&ptr->pic.p_int_status);
break;
default:
panic
("pcireg_intr_status_get: unknown bridgetype bridge 0x%p",
ptr);
}
}
return ret;
}
/*
* Interrupt Enable Register Access -- Read/Write 0000_0108
*/
void pcireg_intr_enable_bit_clr(struct pcibus_info *pcibus_info, u64 bits)
{
union br_ptr __iomem *ptr = (union br_ptr __iomem *)pcibus_info->pbi_buscommon.bs_base;
if (pcibus_info) {
switch (pcibus_info->pbi_bridge_type) {
case PCIBR_BRIDGETYPE_TIOCP:
__sn_clrq_relaxed(&ptr->tio.cp_int_enable, bits);
break;
case PCIBR_BRIDGETYPE_PIC:
__sn_clrq_relaxed(&ptr->pic.p_int_enable, bits);
break;
default:
panic
("pcireg_intr_enable_bit_clr: unknown bridgetype bridge 0x%p",
ptr);
}
}
}
void pcireg_intr_enable_bit_set(struct pcibus_info *pcibus_info, u64 bits)
{
union br_ptr __iomem *ptr = (union br_ptr __iomem *)pcibus_info->pbi_buscommon.bs_base;
if (pcibus_info) {
switch (pcibus_info->pbi_bridge_type) {
case PCIBR_BRIDGETYPE_TIOCP:
__sn_setq_relaxed(&ptr->tio.cp_int_enable, bits);
break;
case PCIBR_BRIDGETYPE_PIC:
__sn_setq_relaxed(&ptr->pic.p_int_enable, bits);
break;
default:
panic
("pcireg_intr_enable_bit_set: unknown bridgetype bridge 0x%p",
ptr);
}
}
}
/*
* Intr Host Address Register (int_addr) -- Read/Write 0000_0130 - 0000_0168
*/
void pcireg_intr_addr_addr_set(struct pcibus_info *pcibus_info, int int_n,
u64 addr)
{
union br_ptr __iomem *ptr = (union br_ptr __iomem *)pcibus_info->pbi_buscommon.bs_base;
if (pcibus_info) {
switch (pcibus_info->pbi_bridge_type) {
case PCIBR_BRIDGETYPE_TIOCP:
__sn_clrq_relaxed(&ptr->tio.cp_int_addr[int_n],
TIOCP_HOST_INTR_ADDR);
__sn_setq_relaxed(&ptr->tio.cp_int_addr[int_n],
(addr & TIOCP_HOST_INTR_ADDR));
break;
case PCIBR_BRIDGETYPE_PIC:
__sn_clrq_relaxed(&ptr->pic.p_int_addr[int_n],
PIC_HOST_INTR_ADDR);
__sn_setq_relaxed(&ptr->pic.p_int_addr[int_n],
(addr & PIC_HOST_INTR_ADDR));
break;
default:
panic
("pcireg_intr_addr_addr_get: unknown bridgetype bridge 0x%p",
ptr);
}
}
}
/*
* Force Interrupt Register Access -- Write Only 0000_01C0 - 0000_01F8
*/
void pcireg_force_intr_set(struct pcibus_info *pcibus_info, int int_n)
{
union br_ptr __iomem *ptr = (union br_ptr __iomem *)pcibus_info->pbi_buscommon.bs_base;
if (pcibus_info) {
switch (pcibus_info->pbi_bridge_type) {
case PCIBR_BRIDGETYPE_TIOCP:
writeq(1, &ptr->tio.cp_force_pin[int_n]);
break;
case PCIBR_BRIDGETYPE_PIC:
writeq(1, &ptr->pic.p_force_pin[int_n]);
break;
default:
panic
("pcireg_force_intr_set: unknown bridgetype bridge 0x%p",
ptr);
}
}
}
/*
* Device(x) Write Buffer Flush Reg Access -- Read Only 0000_0240 - 0000_0258
*/
u64 pcireg_wrb_flush_get(struct pcibus_info *pcibus_info, int device)
{
union br_ptr __iomem *ptr = (union br_ptr __iomem *)pcibus_info->pbi_buscommon.bs_base;
u64 ret = 0;
if (pcibus_info) {
switch (pcibus_info->pbi_bridge_type) {
case PCIBR_BRIDGETYPE_TIOCP:
ret =
__sn_readq_relaxed(&ptr->tio.cp_wr_req_buf[device]);
break;
case PCIBR_BRIDGETYPE_PIC:
ret =
__sn_readq_relaxed(&ptr->pic.p_wr_req_buf[device]);
break;
default:
panic("pcireg_wrb_flush_get: unknown bridgetype bridge 0x%p", ptr);
}
}
/* Read of the Write Buffer Flush should always return zero */
return ret;
}
void pcireg_int_ate_set(struct pcibus_info *pcibus_info, int ate_index,
u64 val)
{
union br_ptr __iomem *ptr = (union br_ptr __iomem *)pcibus_info->pbi_buscommon.bs_base;
if (pcibus_info) {
switch (pcibus_info->pbi_bridge_type) {
case PCIBR_BRIDGETYPE_TIOCP:
writeq(val, &ptr->tio.cp_int_ate_ram[ate_index]);
break;
case PCIBR_BRIDGETYPE_PIC:
writeq(val, &ptr->pic.p_int_ate_ram[ate_index]);
break;
default:
panic
("pcireg_int_ate_set: unknown bridgetype bridge 0x%p",
ptr);
}
}
}
u64 __iomem *pcireg_int_ate_addr(struct pcibus_info *pcibus_info, int ate_index)
{
union br_ptr __iomem *ptr = (union br_ptr __iomem *)pcibus_info->pbi_buscommon.bs_base;
u64 __iomem *ret = NULL;
if (pcibus_info) {
switch (pcibus_info->pbi_bridge_type) {
case PCIBR_BRIDGETYPE_TIOCP:
ret = &ptr->tio.cp_int_ate_ram[ate_index];
break;
case PCIBR_BRIDGETYPE_PIC:
ret = &ptr->pic.p_int_ate_ram[ate_index];
break;
default:
panic
("pcireg_int_ate_addr: unknown bridgetype bridge 0x%p",
ptr);
}
}
return ret;
}
| gpl-2.0 |
pigworlds/asuswrttest | release/src-ra/linux/linux-2.6.21.x/fs/hfs/mdb.c | 96 | 10423 | /*
* linux/fs/hfs/mdb.c
*
* Copyright (C) 1995-1997 Paul H. Hargrove
* (C) 2003 Ardis Technologies <roman@ardistech.com>
* This file may be distributed under the terms of the GNU General Public License.
*
* This file contains functions for reading/writing the MDB.
*/
#include <linux/cdrom.h>
#include <linux/genhd.h>
#include <linux/nls.h>
#include "hfs_fs.h"
#include "btree.h"
/*================ File-local data types ================*/
/*
* The HFS Master Directory Block (MDB).
*
* Also known as the Volume Information Block (VIB), this structure is
* the HFS equivalent of a superblock.
*
* Reference: _Inside Macintosh: Files_ pages 2-59 through 2-62
*
* modified for HFS Extended
*/
static int hfs_get_last_session(struct super_block *sb,
sector_t *start, sector_t *size)
{
struct cdrom_multisession ms_info;
struct cdrom_tocentry te;
int res;
/* default values */
*start = 0;
*size = sb->s_bdev->bd_inode->i_size >> 9;
if (HFS_SB(sb)->session >= 0) {
te.cdte_track = HFS_SB(sb)->session;
te.cdte_format = CDROM_LBA;
res = ioctl_by_bdev(sb->s_bdev, CDROMREADTOCENTRY, (unsigned long)&te);
if (!res && (te.cdte_ctrl & CDROM_DATA_TRACK) == 4) {
*start = (sector_t)te.cdte_addr.lba << 2;
return 0;
}
printk(KERN_ERR "hfs: invalid session number or type of track\n");
return -EINVAL;
}
ms_info.addr_format = CDROM_LBA;
res = ioctl_by_bdev(sb->s_bdev, CDROMMULTISESSION, (unsigned long)&ms_info);
if (!res && ms_info.xa_flag)
*start = (sector_t)ms_info.addr.lba << 2;
return 0;
}
/*
* hfs_mdb_get()
*
* Build the in-core MDB for a filesystem, including
* the B-trees and the volume bitmap.
*/
int hfs_mdb_get(struct super_block *sb)
{
struct buffer_head *bh;
struct hfs_mdb *mdb, *mdb2;
unsigned int block;
char *ptr;
int off2, len, size, sect;
sector_t part_start, part_size;
loff_t off;
__be16 attrib;
/* set the device driver to 512-byte blocks */
size = sb_min_blocksize(sb, HFS_SECTOR_SIZE);
if (!size)
return -EINVAL;
if (hfs_get_last_session(sb, &part_start, &part_size))
return -EINVAL;
while (1) {
/* See if this is an HFS filesystem */
bh = sb_bread512(sb, part_start + HFS_MDB_BLK, mdb);
if (!bh)
goto out;
if (mdb->drSigWord == cpu_to_be16(HFS_SUPER_MAGIC))
break;
brelse(bh);
/* check for a partition block
* (should do this only for cdrom/loop though)
*/
if (hfs_part_find(sb, &part_start, &part_size))
goto out;
}
HFS_SB(sb)->alloc_blksz = size = be32_to_cpu(mdb->drAlBlkSiz);
if (!size || (size & (HFS_SECTOR_SIZE - 1))) {
printk(KERN_ERR "hfs: bad allocation block size %d\n", size);
goto out_bh;
}
size = min(HFS_SB(sb)->alloc_blksz, (u32)PAGE_SIZE);
/* size must be a multiple of 512 */
while (size & (size - 1))
size -= HFS_SECTOR_SIZE;
sect = be16_to_cpu(mdb->drAlBlSt) + part_start;
/* align block size to first sector */
while (sect & ((size - 1) >> HFS_SECTOR_SIZE_BITS))
size >>= 1;
/* align block size to weird alloc size */
while (HFS_SB(sb)->alloc_blksz & (size - 1))
size >>= 1;
brelse(bh);
if (!sb_set_blocksize(sb, size)) {
printk(KERN_ERR "hfs: unable to set blocksize to %u\n", size);
goto out;
}
bh = sb_bread512(sb, part_start + HFS_MDB_BLK, mdb);
if (!bh)
goto out;
if (mdb->drSigWord != cpu_to_be16(HFS_SUPER_MAGIC))
goto out_bh;
HFS_SB(sb)->mdb_bh = bh;
HFS_SB(sb)->mdb = mdb;
/* These parameters are read from the MDB, and never written */
HFS_SB(sb)->part_start = part_start;
HFS_SB(sb)->fs_ablocks = be16_to_cpu(mdb->drNmAlBlks);
HFS_SB(sb)->fs_div = HFS_SB(sb)->alloc_blksz >> sb->s_blocksize_bits;
HFS_SB(sb)->clumpablks = be32_to_cpu(mdb->drClpSiz) /
HFS_SB(sb)->alloc_blksz;
if (!HFS_SB(sb)->clumpablks)
HFS_SB(sb)->clumpablks = 1;
HFS_SB(sb)->fs_start = (be16_to_cpu(mdb->drAlBlSt) + part_start) >>
(sb->s_blocksize_bits - HFS_SECTOR_SIZE_BITS);
/* These parameters are read from and written to the MDB */
HFS_SB(sb)->free_ablocks = be16_to_cpu(mdb->drFreeBks);
HFS_SB(sb)->next_id = be32_to_cpu(mdb->drNxtCNID);
HFS_SB(sb)->root_files = be16_to_cpu(mdb->drNmFls);
HFS_SB(sb)->root_dirs = be16_to_cpu(mdb->drNmRtDirs);
HFS_SB(sb)->file_count = be32_to_cpu(mdb->drFilCnt);
HFS_SB(sb)->folder_count = be32_to_cpu(mdb->drDirCnt);
/* TRY to get the alternate (backup) MDB. */
sect = part_start + part_size - 2;
bh = sb_bread512(sb, sect, mdb2);
if (bh) {
if (mdb2->drSigWord == cpu_to_be16(HFS_SUPER_MAGIC)) {
HFS_SB(sb)->alt_mdb_bh = bh;
HFS_SB(sb)->alt_mdb = mdb2;
} else
brelse(bh);
}
if (!HFS_SB(sb)->alt_mdb) {
printk(KERN_WARNING "hfs: unable to locate alternate MDB\n");
printk(KERN_WARNING "hfs: continuing without an alternate MDB\n");
}
HFS_SB(sb)->bitmap = (__be32 *)__get_free_pages(GFP_KERNEL, PAGE_SIZE < 8192 ? 1 : 0);
if (!HFS_SB(sb)->bitmap)
goto out;
/* read in the bitmap */
block = be16_to_cpu(mdb->drVBMSt) + part_start;
off = (loff_t)block << HFS_SECTOR_SIZE_BITS;
size = (HFS_SB(sb)->fs_ablocks + 8) / 8;
ptr = (u8 *)HFS_SB(sb)->bitmap;
while (size) {
bh = sb_bread(sb, off >> sb->s_blocksize_bits);
if (!bh) {
printk(KERN_ERR "hfs: unable to read volume bitmap\n");
goto out;
}
off2 = off & (sb->s_blocksize - 1);
len = min((int)sb->s_blocksize - off2, size);
memcpy(ptr, bh->b_data + off2, len);
brelse(bh);
ptr += len;
off += len;
size -= len;
}
HFS_SB(sb)->ext_tree = hfs_btree_open(sb, HFS_EXT_CNID, hfs_ext_keycmp);
if (!HFS_SB(sb)->ext_tree) {
printk(KERN_ERR "hfs: unable to open extent tree\n");
goto out;
}
HFS_SB(sb)->cat_tree = hfs_btree_open(sb, HFS_CAT_CNID, hfs_cat_keycmp);
if (!HFS_SB(sb)->cat_tree) {
printk(KERN_ERR "hfs: unable to open catalog tree\n");
goto out;
}
attrib = mdb->drAtrb;
if (!(attrib & cpu_to_be16(HFS_SB_ATTRIB_UNMNT))) {
printk(KERN_WARNING "hfs: filesystem was not cleanly unmounted, "
"running fsck.hfs is recommended. mounting read-only.\n");
sb->s_flags |= MS_RDONLY;
}
if ((attrib & cpu_to_be16(HFS_SB_ATTRIB_SLOCK))) {
printk(KERN_WARNING "hfs: filesystem is marked locked, mounting read-only.\n");
sb->s_flags |= MS_RDONLY;
}
if (!(sb->s_flags & MS_RDONLY)) {
/* Mark the volume uncleanly unmounted in case we crash */
attrib &= cpu_to_be16(~HFS_SB_ATTRIB_UNMNT);
attrib |= cpu_to_be16(HFS_SB_ATTRIB_INCNSTNT);
mdb->drAtrb = attrib;
mdb->drWrCnt = cpu_to_be32(be32_to_cpu(mdb->drWrCnt) + 1);
mdb->drLsMod = hfs_mtime();
mark_buffer_dirty(HFS_SB(sb)->mdb_bh);
hfs_buffer_sync(HFS_SB(sb)->mdb_bh);
}
return 0;
out_bh:
brelse(bh);
out:
hfs_mdb_put(sb);
return -EIO;
}
/*
* hfs_mdb_commit()
*
* Description:
* This updates the MDB on disk (look also at hfs_write_super()).
* It does not check, if the superblock has been modified, or
* if the filesystem has been mounted read-only. It is mainly
* called by hfs_write_super() and hfs_btree_extend().
* Input Variable(s):
* struct hfs_mdb *mdb: Pointer to the hfs MDB
* int backup;
* Output Variable(s):
* NONE
* Returns:
* void
* Preconditions:
* 'mdb' points to a "valid" (struct hfs_mdb).
* Postconditions:
* The HFS MDB and on disk will be updated, by copying the possibly
* modified fields from the in memory MDB (in native byte order) to
* the disk block buffer.
* If 'backup' is non-zero then the alternate MDB is also written
* and the function doesn't return until it is actually on disk.
*/
void hfs_mdb_commit(struct super_block *sb)
{
struct hfs_mdb *mdb = HFS_SB(sb)->mdb;
if (test_and_clear_bit(HFS_FLG_MDB_DIRTY, &HFS_SB(sb)->flags)) {
/* These parameters may have been modified, so write them back */
mdb->drLsMod = hfs_mtime();
mdb->drFreeBks = cpu_to_be16(HFS_SB(sb)->free_ablocks);
mdb->drNxtCNID = cpu_to_be32(HFS_SB(sb)->next_id);
mdb->drNmFls = cpu_to_be16(HFS_SB(sb)->root_files);
mdb->drNmRtDirs = cpu_to_be16(HFS_SB(sb)->root_dirs);
mdb->drFilCnt = cpu_to_be32(HFS_SB(sb)->file_count);
mdb->drDirCnt = cpu_to_be32(HFS_SB(sb)->folder_count);
/* write MDB to disk */
mark_buffer_dirty(HFS_SB(sb)->mdb_bh);
}
/* write the backup MDB, not returning until it is written.
* we only do this when either the catalog or extents overflow
* files grow. */
if (test_and_clear_bit(HFS_FLG_ALT_MDB_DIRTY, &HFS_SB(sb)->flags) &&
HFS_SB(sb)->alt_mdb) {
hfs_inode_write_fork(HFS_SB(sb)->ext_tree->inode, mdb->drXTExtRec,
&mdb->drXTFlSize, NULL);
hfs_inode_write_fork(HFS_SB(sb)->cat_tree->inode, mdb->drCTExtRec,
&mdb->drCTFlSize, NULL);
memcpy(HFS_SB(sb)->alt_mdb, HFS_SB(sb)->mdb, HFS_SECTOR_SIZE);
HFS_SB(sb)->alt_mdb->drAtrb |= cpu_to_be16(HFS_SB_ATTRIB_UNMNT);
HFS_SB(sb)->alt_mdb->drAtrb &= cpu_to_be16(~HFS_SB_ATTRIB_INCNSTNT);
mark_buffer_dirty(HFS_SB(sb)->alt_mdb_bh);
hfs_buffer_sync(HFS_SB(sb)->alt_mdb_bh);
}
if (test_and_clear_bit(HFS_FLG_BITMAP_DIRTY, &HFS_SB(sb)->flags)) {
struct buffer_head *bh;
sector_t block;
char *ptr;
int off, size, len;
block = be16_to_cpu(HFS_SB(sb)->mdb->drVBMSt) + HFS_SB(sb)->part_start;
off = (block << HFS_SECTOR_SIZE_BITS) & (sb->s_blocksize - 1);
block >>= sb->s_blocksize_bits - HFS_SECTOR_SIZE_BITS;
size = (HFS_SB(sb)->fs_ablocks + 7) / 8;
ptr = (u8 *)HFS_SB(sb)->bitmap;
while (size) {
bh = sb_bread(sb, block);
if (!bh) {
printk(KERN_ERR "hfs: unable to read volume bitmap\n");
break;
}
len = min((int)sb->s_blocksize - off, size);
memcpy(bh->b_data + off, ptr, len);
mark_buffer_dirty(bh);
brelse(bh);
block++;
off = 0;
ptr += len;
size -= len;
}
}
}
void hfs_mdb_close(struct super_block *sb)
{
/* update volume attributes */
if (sb->s_flags & MS_RDONLY)
return;
HFS_SB(sb)->mdb->drAtrb |= cpu_to_be16(HFS_SB_ATTRIB_UNMNT);
HFS_SB(sb)->mdb->drAtrb &= cpu_to_be16(~HFS_SB_ATTRIB_INCNSTNT);
mark_buffer_dirty(HFS_SB(sb)->mdb_bh);
}
/*
* hfs_mdb_put()
*
* Release the resources associated with the in-core MDB. */
void hfs_mdb_put(struct super_block *sb)
{
if (!HFS_SB(sb))
return;
/* free the B-trees */
hfs_btree_close(HFS_SB(sb)->ext_tree);
hfs_btree_close(HFS_SB(sb)->cat_tree);
/* free the buffers holding the primary and alternate MDBs */
brelse(HFS_SB(sb)->mdb_bh);
brelse(HFS_SB(sb)->alt_mdb_bh);
if (HFS_SB(sb)->nls_io)
unload_nls(HFS_SB(sb)->nls_io);
if (HFS_SB(sb)->nls_disk)
unload_nls(HFS_SB(sb)->nls_disk);
kfree(HFS_SB(sb));
sb->s_fs_info = NULL;
}
| gpl-2.0 |
f123h456/linux | fs/cifs/cifs_debug.c | 864 | 18446 | /*
* fs/cifs_debug.c
*
* Copyright (C) International Business Machines Corp., 2000,2005
*
* Modified by Steve French (sfrench@us.ibm.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; 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/fs.h>
#include <linux/string.h>
#include <linux/ctype.h>
#include <linux/module.h>
#include <linux/proc_fs.h>
#include <asm/uaccess.h>
#include "cifspdu.h"
#include "cifsglob.h"
#include "cifsproto.h"
#include "cifs_debug.h"
#include "cifsfs.h"
void
cifs_dump_mem(char *label, void *data, int length)
{
pr_debug("%s: dump of %d bytes of data at 0x%p\n", label, length, data);
print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET, 16, 4,
data, length, true);
}
#ifdef CONFIG_CIFS_DEBUG
void cifs_vfs_err(const char *fmt, ...)
{
struct va_format vaf;
va_list args;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
pr_err("CIFS VFS: %pV", &vaf);
va_end(args);
}
#endif
void cifs_dump_detail(void *buf)
{
#ifdef CONFIG_CIFS_DEBUG2
struct smb_hdr *smb = (struct smb_hdr *)buf;
cifs_dbg(VFS, "Cmd: %d Err: 0x%x Flags: 0x%x Flgs2: 0x%x Mid: %d Pid: %d\n",
smb->Command, smb->Status.CifsError,
smb->Flags, smb->Flags2, smb->Mid, smb->Pid);
cifs_dbg(VFS, "smb buf %p len %u\n", smb, smbCalcSize(smb));
#endif /* CONFIG_CIFS_DEBUG2 */
}
void cifs_dump_mids(struct TCP_Server_Info *server)
{
#ifdef CONFIG_CIFS_DEBUG2
struct list_head *tmp;
struct mid_q_entry *mid_entry;
if (server == NULL)
return;
cifs_dbg(VFS, "Dump pending requests:\n");
spin_lock(&GlobalMid_Lock);
list_for_each(tmp, &server->pending_mid_q) {
mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
cifs_dbg(VFS, "State: %d Cmd: %d Pid: %d Cbdata: %p Mid %llu\n",
mid_entry->mid_state,
le16_to_cpu(mid_entry->command),
mid_entry->pid,
mid_entry->callback_data,
mid_entry->mid);
#ifdef CONFIG_CIFS_STATS2
cifs_dbg(VFS, "IsLarge: %d buf: %p time rcv: %ld now: %ld\n",
mid_entry->large_buf,
mid_entry->resp_buf,
mid_entry->when_received,
jiffies);
#endif /* STATS2 */
cifs_dbg(VFS, "IsMult: %d IsEnd: %d\n",
mid_entry->multiRsp, mid_entry->multiEnd);
if (mid_entry->resp_buf) {
cifs_dump_detail(mid_entry->resp_buf);
cifs_dump_mem("existing buf: ",
mid_entry->resp_buf, 62);
}
}
spin_unlock(&GlobalMid_Lock);
#endif /* CONFIG_CIFS_DEBUG2 */
}
#ifdef CONFIG_PROC_FS
static int cifs_debug_data_proc_show(struct seq_file *m, void *v)
{
struct list_head *tmp1, *tmp2, *tmp3;
struct mid_q_entry *mid_entry;
struct TCP_Server_Info *server;
struct cifs_ses *ses;
struct cifs_tcon *tcon;
int i, j;
__u32 dev_type;
seq_puts(m,
"Display Internal CIFS Data Structures for Debugging\n"
"---------------------------------------------------\n");
seq_printf(m, "CIFS Version %s\n", CIFS_VERSION);
seq_printf(m, "Features:");
#ifdef CONFIG_CIFS_DFS_UPCALL
seq_printf(m, " dfs");
#endif
#ifdef CONFIG_CIFS_FSCACHE
seq_printf(m, " fscache");
#endif
#ifdef CONFIG_CIFS_WEAK_PW_HASH
seq_printf(m, " lanman");
#endif
#ifdef CONFIG_CIFS_POSIX
seq_printf(m, " posix");
#endif
#ifdef CONFIG_CIFS_UPCALL
seq_printf(m, " spnego");
#endif
#ifdef CONFIG_CIFS_XATTR
seq_printf(m, " xattr");
#endif
#ifdef CONFIG_CIFS_ACL
seq_printf(m, " acl");
#endif
seq_putc(m, '\n');
seq_printf(m, "Active VFS Requests: %d\n", GlobalTotalActiveXid);
seq_printf(m, "Servers:");
i = 0;
spin_lock(&cifs_tcp_ses_lock);
list_for_each(tmp1, &cifs_tcp_ses_list) {
server = list_entry(tmp1, struct TCP_Server_Info,
tcp_ses_list);
i++;
list_for_each(tmp2, &server->smb_ses_list) {
ses = list_entry(tmp2, struct cifs_ses,
smb_ses_list);
if ((ses->serverDomain == NULL) ||
(ses->serverOS == NULL) ||
(ses->serverNOS == NULL)) {
seq_printf(m, "\n%d) entry for %s not fully "
"displayed\n\t", i, ses->serverName);
} else {
seq_printf(m,
"\n%d) Name: %s Domain: %s Uses: %d OS:"
" %s\n\tNOS: %s\tCapability: 0x%x\n\tSMB"
" session status: %d\t",
i, ses->serverName, ses->serverDomain,
ses->ses_count, ses->serverOS, ses->serverNOS,
ses->capabilities, ses->status);
}
seq_printf(m, "TCP status: %d\n\tLocal Users To "
"Server: %d SecMode: 0x%x Req On Wire: %d",
server->tcpStatus, server->srv_count,
server->sec_mode, in_flight(server));
#ifdef CONFIG_CIFS_STATS2
seq_printf(m, " In Send: %d In MaxReq Wait: %d",
atomic_read(&server->in_send),
atomic_read(&server->num_waiters));
#endif
seq_puts(m, "\n\tShares:");
j = 0;
list_for_each(tmp3, &ses->tcon_list) {
tcon = list_entry(tmp3, struct cifs_tcon,
tcon_list);
++j;
dev_type = le32_to_cpu(tcon->fsDevInfo.DeviceType);
seq_printf(m, "\n\t%d) %s Mounts: %d ", j,
tcon->treeName, tcon->tc_count);
if (tcon->nativeFileSystem) {
seq_printf(m, "Type: %s ",
tcon->nativeFileSystem);
}
seq_printf(m, "DevInfo: 0x%x Attributes: 0x%x"
"\n\tPathComponentMax: %d Status: %d",
le32_to_cpu(tcon->fsDevInfo.DeviceCharacteristics),
le32_to_cpu(tcon->fsAttrInfo.Attributes),
le32_to_cpu(tcon->fsAttrInfo.MaxPathNameComponentLength),
tcon->tidStatus);
if (dev_type == FILE_DEVICE_DISK)
seq_puts(m, " type: DISK ");
else if (dev_type == FILE_DEVICE_CD_ROM)
seq_puts(m, " type: CDROM ");
else
seq_printf(m, " type: %d ", dev_type);
if (server->ops->dump_share_caps)
server->ops->dump_share_caps(m, tcon);
if (tcon->need_reconnect)
seq_puts(m, "\tDISCONNECTED ");
seq_putc(m, '\n');
}
seq_puts(m, "\n\tMIDs:\n");
spin_lock(&GlobalMid_Lock);
list_for_each(tmp3, &server->pending_mid_q) {
mid_entry = list_entry(tmp3, struct mid_q_entry,
qhead);
seq_printf(m, "\tState: %d com: %d pid:"
" %d cbdata: %p mid %llu\n",
mid_entry->mid_state,
le16_to_cpu(mid_entry->command),
mid_entry->pid,
mid_entry->callback_data,
mid_entry->mid);
}
spin_unlock(&GlobalMid_Lock);
}
}
spin_unlock(&cifs_tcp_ses_lock);
seq_putc(m, '\n');
/* BB add code to dump additional info such as TCP session info now */
return 0;
}
static int cifs_debug_data_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, cifs_debug_data_proc_show, NULL);
}
static const struct file_operations cifs_debug_data_proc_fops = {
.owner = THIS_MODULE,
.open = cifs_debug_data_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
#ifdef CONFIG_CIFS_STATS
static ssize_t cifs_stats_proc_write(struct file *file,
const char __user *buffer, size_t count, loff_t *ppos)
{
char c;
bool bv;
int rc;
struct list_head *tmp1, *tmp2, *tmp3;
struct TCP_Server_Info *server;
struct cifs_ses *ses;
struct cifs_tcon *tcon;
rc = get_user(c, buffer);
if (rc)
return rc;
if (strtobool(&c, &bv) == 0) {
#ifdef CONFIG_CIFS_STATS2
atomic_set(&totBufAllocCount, 0);
atomic_set(&totSmBufAllocCount, 0);
#endif /* CONFIG_CIFS_STATS2 */
spin_lock(&cifs_tcp_ses_lock);
list_for_each(tmp1, &cifs_tcp_ses_list) {
server = list_entry(tmp1, struct TCP_Server_Info,
tcp_ses_list);
list_for_each(tmp2, &server->smb_ses_list) {
ses = list_entry(tmp2, struct cifs_ses,
smb_ses_list);
list_for_each(tmp3, &ses->tcon_list) {
tcon = list_entry(tmp3,
struct cifs_tcon,
tcon_list);
atomic_set(&tcon->num_smbs_sent, 0);
if (server->ops->clear_stats)
server->ops->clear_stats(tcon);
}
}
}
spin_unlock(&cifs_tcp_ses_lock);
}
return count;
}
static int cifs_stats_proc_show(struct seq_file *m, void *v)
{
int i;
struct list_head *tmp1, *tmp2, *tmp3;
struct TCP_Server_Info *server;
struct cifs_ses *ses;
struct cifs_tcon *tcon;
seq_printf(m,
"Resources in use\nCIFS Session: %d\n",
sesInfoAllocCount.counter);
seq_printf(m, "Share (unique mount targets): %d\n",
tconInfoAllocCount.counter);
seq_printf(m, "SMB Request/Response Buffer: %d Pool size: %d\n",
bufAllocCount.counter,
cifs_min_rcv + tcpSesAllocCount.counter);
seq_printf(m, "SMB Small Req/Resp Buffer: %d Pool size: %d\n",
smBufAllocCount.counter, cifs_min_small);
#ifdef CONFIG_CIFS_STATS2
seq_printf(m, "Total Large %d Small %d Allocations\n",
atomic_read(&totBufAllocCount),
atomic_read(&totSmBufAllocCount));
#endif /* CONFIG_CIFS_STATS2 */
seq_printf(m, "Operations (MIDs): %d\n", atomic_read(&midCount));
seq_printf(m,
"\n%d session %d share reconnects\n",
tcpSesReconnectCount.counter, tconInfoReconnectCount.counter);
seq_printf(m,
"Total vfs operations: %d maximum at one time: %d\n",
GlobalCurrentXid, GlobalMaxActiveXid);
i = 0;
spin_lock(&cifs_tcp_ses_lock);
list_for_each(tmp1, &cifs_tcp_ses_list) {
server = list_entry(tmp1, struct TCP_Server_Info,
tcp_ses_list);
list_for_each(tmp2, &server->smb_ses_list) {
ses = list_entry(tmp2, struct cifs_ses,
smb_ses_list);
list_for_each(tmp3, &ses->tcon_list) {
tcon = list_entry(tmp3,
struct cifs_tcon,
tcon_list);
i++;
seq_printf(m, "\n%d) %s", i, tcon->treeName);
if (tcon->need_reconnect)
seq_puts(m, "\tDISCONNECTED ");
seq_printf(m, "\nSMBs: %d",
atomic_read(&tcon->num_smbs_sent));
if (server->ops->print_stats)
server->ops->print_stats(m, tcon);
}
}
}
spin_unlock(&cifs_tcp_ses_lock);
seq_putc(m, '\n');
return 0;
}
static int cifs_stats_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, cifs_stats_proc_show, NULL);
}
static const struct file_operations cifs_stats_proc_fops = {
.owner = THIS_MODULE,
.open = cifs_stats_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.write = cifs_stats_proc_write,
};
#endif /* STATS */
static struct proc_dir_entry *proc_fs_cifs;
static const struct file_operations cifsFYI_proc_fops;
static const struct file_operations cifs_lookup_cache_proc_fops;
static const struct file_operations traceSMB_proc_fops;
static const struct file_operations cifs_security_flags_proc_fops;
static const struct file_operations cifs_linux_ext_proc_fops;
void
cifs_proc_init(void)
{
proc_fs_cifs = proc_mkdir("fs/cifs", NULL);
if (proc_fs_cifs == NULL)
return;
proc_create("DebugData", 0, proc_fs_cifs, &cifs_debug_data_proc_fops);
#ifdef CONFIG_CIFS_STATS
proc_create("Stats", 0, proc_fs_cifs, &cifs_stats_proc_fops);
#endif /* STATS */
proc_create("cifsFYI", 0, proc_fs_cifs, &cifsFYI_proc_fops);
proc_create("traceSMB", 0, proc_fs_cifs, &traceSMB_proc_fops);
proc_create("LinuxExtensionsEnabled", 0, proc_fs_cifs,
&cifs_linux_ext_proc_fops);
proc_create("SecurityFlags", 0, proc_fs_cifs,
&cifs_security_flags_proc_fops);
proc_create("LookupCacheEnabled", 0, proc_fs_cifs,
&cifs_lookup_cache_proc_fops);
}
void
cifs_proc_clean(void)
{
if (proc_fs_cifs == NULL)
return;
remove_proc_entry("DebugData", proc_fs_cifs);
remove_proc_entry("cifsFYI", proc_fs_cifs);
remove_proc_entry("traceSMB", proc_fs_cifs);
#ifdef CONFIG_CIFS_STATS
remove_proc_entry("Stats", proc_fs_cifs);
#endif
remove_proc_entry("SecurityFlags", proc_fs_cifs);
remove_proc_entry("LinuxExtensionsEnabled", proc_fs_cifs);
remove_proc_entry("LookupCacheEnabled", proc_fs_cifs);
remove_proc_entry("fs/cifs", NULL);
}
static int cifsFYI_proc_show(struct seq_file *m, void *v)
{
seq_printf(m, "%d\n", cifsFYI);
return 0;
}
static int cifsFYI_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, cifsFYI_proc_show, NULL);
}
static ssize_t cifsFYI_proc_write(struct file *file, const char __user *buffer,
size_t count, loff_t *ppos)
{
char c;
bool bv;
int rc;
rc = get_user(c, buffer);
if (rc)
return rc;
if (strtobool(&c, &bv) == 0)
cifsFYI = bv;
else if ((c > '1') && (c <= '9'))
cifsFYI = (int) (c - '0'); /* see cifs_debug.h for meanings */
return count;
}
static const struct file_operations cifsFYI_proc_fops = {
.owner = THIS_MODULE,
.open = cifsFYI_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.write = cifsFYI_proc_write,
};
static int cifs_linux_ext_proc_show(struct seq_file *m, void *v)
{
seq_printf(m, "%d\n", linuxExtEnabled);
return 0;
}
static int cifs_linux_ext_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, cifs_linux_ext_proc_show, NULL);
}
static ssize_t cifs_linux_ext_proc_write(struct file *file,
const char __user *buffer, size_t count, loff_t *ppos)
{
char c;
bool bv;
int rc;
rc = get_user(c, buffer);
if (rc)
return rc;
rc = strtobool(&c, &bv);
if (rc)
return rc;
linuxExtEnabled = bv;
return count;
}
static const struct file_operations cifs_linux_ext_proc_fops = {
.owner = THIS_MODULE,
.open = cifs_linux_ext_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.write = cifs_linux_ext_proc_write,
};
static int cifs_lookup_cache_proc_show(struct seq_file *m, void *v)
{
seq_printf(m, "%d\n", lookupCacheEnabled);
return 0;
}
static int cifs_lookup_cache_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, cifs_lookup_cache_proc_show, NULL);
}
static ssize_t cifs_lookup_cache_proc_write(struct file *file,
const char __user *buffer, size_t count, loff_t *ppos)
{
char c;
bool bv;
int rc;
rc = get_user(c, buffer);
if (rc)
return rc;
rc = strtobool(&c, &bv);
if (rc)
return rc;
lookupCacheEnabled = bv;
return count;
}
static const struct file_operations cifs_lookup_cache_proc_fops = {
.owner = THIS_MODULE,
.open = cifs_lookup_cache_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.write = cifs_lookup_cache_proc_write,
};
static int traceSMB_proc_show(struct seq_file *m, void *v)
{
seq_printf(m, "%d\n", traceSMB);
return 0;
}
static int traceSMB_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, traceSMB_proc_show, NULL);
}
static ssize_t traceSMB_proc_write(struct file *file, const char __user *buffer,
size_t count, loff_t *ppos)
{
char c;
bool bv;
int rc;
rc = get_user(c, buffer);
if (rc)
return rc;
rc = strtobool(&c, &bv);
if (rc)
return rc;
traceSMB = bv;
return count;
}
static const struct file_operations traceSMB_proc_fops = {
.owner = THIS_MODULE,
.open = traceSMB_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.write = traceSMB_proc_write,
};
static int cifs_security_flags_proc_show(struct seq_file *m, void *v)
{
seq_printf(m, "0x%x\n", global_secflags);
return 0;
}
static int cifs_security_flags_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, cifs_security_flags_proc_show, NULL);
}
/*
* Ensure that if someone sets a MUST flag, that we disable all other MAY
* flags except for the ones corresponding to the given MUST flag. If there are
* multiple MUST flags, then try to prefer more secure ones.
*/
static void
cifs_security_flags_handle_must_flags(unsigned int *flags)
{
unsigned int signflags = *flags & CIFSSEC_MUST_SIGN;
if ((*flags & CIFSSEC_MUST_KRB5) == CIFSSEC_MUST_KRB5)
*flags = CIFSSEC_MUST_KRB5;
else if ((*flags & CIFSSEC_MUST_NTLMSSP) == CIFSSEC_MUST_NTLMSSP)
*flags = CIFSSEC_MUST_NTLMSSP;
else if ((*flags & CIFSSEC_MUST_NTLMV2) == CIFSSEC_MUST_NTLMV2)
*flags = CIFSSEC_MUST_NTLMV2;
else if ((*flags & CIFSSEC_MUST_NTLM) == CIFSSEC_MUST_NTLM)
*flags = CIFSSEC_MUST_NTLM;
else if (CIFSSEC_MUST_LANMAN &&
(*flags & CIFSSEC_MUST_LANMAN) == CIFSSEC_MUST_LANMAN)
*flags = CIFSSEC_MUST_LANMAN;
else if (CIFSSEC_MUST_PLNTXT &&
(*flags & CIFSSEC_MUST_PLNTXT) == CIFSSEC_MUST_PLNTXT)
*flags = CIFSSEC_MUST_PLNTXT;
*flags |= signflags;
}
static ssize_t cifs_security_flags_proc_write(struct file *file,
const char __user *buffer, size_t count, loff_t *ppos)
{
int rc;
unsigned int flags;
char flags_string[12];
char c;
bool bv;
if ((count < 1) || (count > 11))
return -EINVAL;
memset(flags_string, 0, 12);
if (copy_from_user(flags_string, buffer, count))
return -EFAULT;
if (count < 3) {
/* single char or single char followed by null */
c = flags_string[0];
if (strtobool(&c, &bv) == 0) {
global_secflags = bv ? CIFSSEC_MAX : CIFSSEC_DEF;
return count;
} else if (!isdigit(c)) {
cifs_dbg(VFS, "Invalid SecurityFlags: %s\n",
flags_string);
return -EINVAL;
}
}
/* else we have a number */
rc = kstrtouint(flags_string, 0, &flags);
if (rc) {
cifs_dbg(VFS, "Invalid SecurityFlags: %s\n",
flags_string);
return rc;
}
cifs_dbg(FYI, "sec flags 0x%x\n", flags);
if (flags == 0) {
cifs_dbg(VFS, "Invalid SecurityFlags: %s\n", flags_string);
return -EINVAL;
}
if (flags & ~CIFSSEC_MASK) {
cifs_dbg(VFS, "Unsupported security flags: 0x%x\n",
flags & ~CIFSSEC_MASK);
return -EINVAL;
}
cifs_security_flags_handle_must_flags(&flags);
/* flags look ok - update the global security flags for cifs module */
global_secflags = flags;
if (global_secflags & CIFSSEC_MUST_SIGN) {
/* requiring signing implies signing is allowed */
global_secflags |= CIFSSEC_MAY_SIGN;
cifs_dbg(FYI, "packet signing now required\n");
} else if ((global_secflags & CIFSSEC_MAY_SIGN) == 0) {
cifs_dbg(FYI, "packet signing disabled\n");
}
/* BB should we turn on MAY flags for other MUST options? */
return count;
}
static const struct file_operations cifs_security_flags_proc_fops = {
.owner = THIS_MODULE,
.open = cifs_security_flags_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.write = cifs_security_flags_proc_write,
};
#else
inline void cifs_proc_init(void)
{
}
inline void cifs_proc_clean(void)
{
}
#endif /* PROC_FS */
| gpl-2.0 |
NicholasPace/android_kernel_asus_moorefield-stock | drivers/mmc/host/sh_mobile_sdhi.c | 2144 | 8241 | /*
* SuperH Mobile SDHI
*
* Copyright (C) 2009 Magnus Damm
*
* 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.
*
* Based on "Compaq ASIC3 support":
*
* Copyright 2001 Compaq Computer Corporation.
* Copyright 2004-2005 Phil Blundell
* Copyright 2007-2008 OpenedHand Ltd.
*
* Authors: Phil Blundell <pb@handhelds.org>,
* Samuel Ortiz <sameo@openedhand.com>
*
*/
#include <linux/kernel.h>
#include <linux/clk.h>
#include <linux/slab.h>
#include <linux/mod_devicetable.h>
#include <linux/module.h>
#include <linux/of_device.h>
#include <linux/platform_device.h>
#include <linux/mmc/host.h>
#include <linux/mmc/sh_mobile_sdhi.h>
#include <linux/mfd/tmio.h>
#include <linux/sh_dma.h>
#include <linux/delay.h>
#include "tmio_mmc.h"
struct sh_mobile_sdhi_of_data {
unsigned long tmio_flags;
};
static const struct sh_mobile_sdhi_of_data sh_mobile_sdhi_of_cfg[] = {
{
.tmio_flags = TMIO_MMC_HAS_IDLE_WAIT,
},
};
struct sh_mobile_sdhi {
struct clk *clk;
struct tmio_mmc_data mmc_data;
struct sh_dmae_slave param_tx;
struct sh_dmae_slave param_rx;
struct tmio_mmc_dma dma_priv;
};
static int sh_mobile_sdhi_clk_enable(struct platform_device *pdev, unsigned int *f)
{
struct mmc_host *mmc = dev_get_drvdata(&pdev->dev);
struct tmio_mmc_host *host = mmc_priv(mmc);
struct sh_mobile_sdhi *priv = container_of(host->pdata, struct sh_mobile_sdhi, mmc_data);
int ret = clk_enable(priv->clk);
if (ret < 0)
return ret;
*f = clk_get_rate(priv->clk);
return 0;
}
static void sh_mobile_sdhi_clk_disable(struct platform_device *pdev)
{
struct mmc_host *mmc = dev_get_drvdata(&pdev->dev);
struct tmio_mmc_host *host = mmc_priv(mmc);
struct sh_mobile_sdhi *priv = container_of(host->pdata, struct sh_mobile_sdhi, mmc_data);
clk_disable(priv->clk);
}
static void sh_mobile_sdhi_set_pwr(struct platform_device *pdev, int state)
{
struct sh_mobile_sdhi_info *p = pdev->dev.platform_data;
p->set_pwr(pdev, state);
}
static int sh_mobile_sdhi_get_cd(struct platform_device *pdev)
{
struct sh_mobile_sdhi_info *p = pdev->dev.platform_data;
return p->get_cd(pdev);
}
static int sh_mobile_sdhi_wait_idle(struct tmio_mmc_host *host)
{
int timeout = 1000;
while (--timeout && !(sd_ctrl_read16(host, CTL_STATUS2) & (1 << 13)))
udelay(1);
if (!timeout) {
dev_warn(host->pdata->dev, "timeout waiting for SD bus idle\n");
return -EBUSY;
}
return 0;
}
static int sh_mobile_sdhi_write16_hook(struct tmio_mmc_host *host, int addr)
{
switch (addr)
{
case CTL_SD_CMD:
case CTL_STOP_INTERNAL_ACTION:
case CTL_XFER_BLK_COUNT:
case CTL_SD_CARD_CLK_CTL:
case CTL_SD_XFER_LEN:
case CTL_SD_MEM_CARD_OPT:
case CTL_TRANSACTION_CTL:
case CTL_DMA_ENABLE:
return sh_mobile_sdhi_wait_idle(host);
}
return 0;
}
static void sh_mobile_sdhi_cd_wakeup(const struct platform_device *pdev)
{
mmc_detect_change(dev_get_drvdata(&pdev->dev), msecs_to_jiffies(100));
}
static const struct sh_mobile_sdhi_ops sdhi_ops = {
.cd_wakeup = sh_mobile_sdhi_cd_wakeup,
};
static const struct of_device_id sh_mobile_sdhi_of_match[] = {
{ .compatible = "renesas,shmobile-sdhi" },
{ .compatible = "renesas,sh7372-sdhi" },
{ .compatible = "renesas,r8a7740-sdhi", .data = &sh_mobile_sdhi_of_cfg[0], },
{},
};
MODULE_DEVICE_TABLE(of, sh_mobile_sdhi_of_match);
static int sh_mobile_sdhi_probe(struct platform_device *pdev)
{
const struct of_device_id *of_id =
of_match_device(sh_mobile_sdhi_of_match, &pdev->dev);
struct sh_mobile_sdhi *priv;
struct tmio_mmc_data *mmc_data;
struct sh_mobile_sdhi_info *p = pdev->dev.platform_data;
struct tmio_mmc_host *host;
int irq, ret, i = 0;
bool multiplexed_isr = true;
priv = devm_kzalloc(&pdev->dev, sizeof(struct sh_mobile_sdhi), GFP_KERNEL);
if (priv == NULL) {
dev_err(&pdev->dev, "kzalloc failed\n");
return -ENOMEM;
}
mmc_data = &priv->mmc_data;
if (p) {
if (p->init) {
ret = p->init(pdev, &sdhi_ops);
if (ret)
return ret;
}
}
priv->clk = devm_clk_get(&pdev->dev, NULL);
if (IS_ERR(priv->clk)) {
ret = PTR_ERR(priv->clk);
dev_err(&pdev->dev, "cannot get clock: %d\n", ret);
goto eclkget;
}
mmc_data->clk_enable = sh_mobile_sdhi_clk_enable;
mmc_data->clk_disable = sh_mobile_sdhi_clk_disable;
mmc_data->capabilities = MMC_CAP_MMC_HIGHSPEED;
mmc_data->write16_hook = sh_mobile_sdhi_write16_hook;
if (p) {
mmc_data->flags = p->tmio_flags;
mmc_data->ocr_mask = p->tmio_ocr_mask;
mmc_data->capabilities |= p->tmio_caps;
mmc_data->capabilities2 |= p->tmio_caps2;
mmc_data->cd_gpio = p->cd_gpio;
if (p->set_pwr)
mmc_data->set_pwr = sh_mobile_sdhi_set_pwr;
if (p->get_cd)
mmc_data->get_cd = sh_mobile_sdhi_get_cd;
if (p->dma_slave_tx > 0 && p->dma_slave_rx > 0) {
priv->param_tx.shdma_slave.slave_id = p->dma_slave_tx;
priv->param_rx.shdma_slave.slave_id = p->dma_slave_rx;
priv->dma_priv.chan_priv_tx = &priv->param_tx.shdma_slave;
priv->dma_priv.chan_priv_rx = &priv->param_rx.shdma_slave;
priv->dma_priv.alignment_shift = 1; /* 2-byte alignment */
mmc_data->dma = &priv->dma_priv;
}
}
/*
* All SDHI blocks support 2-byte and larger block sizes in 4-bit
* bus width mode.
*/
mmc_data->flags |= TMIO_MMC_BLKSZ_2BYTES;
/*
* All SDHI blocks support SDIO IRQ signalling.
*/
mmc_data->flags |= TMIO_MMC_SDIO_IRQ;
if (of_id && of_id->data) {
const struct sh_mobile_sdhi_of_data *of_data = of_id->data;
mmc_data->flags |= of_data->tmio_flags;
}
ret = tmio_mmc_host_probe(&host, pdev, mmc_data);
if (ret < 0)
goto eprobe;
/*
* Allow one or more specific (named) ISRs or
* one or more multiplexed (un-named) ISRs.
*/
irq = platform_get_irq_byname(pdev, SH_MOBILE_SDHI_IRQ_CARD_DETECT);
if (irq >= 0) {
multiplexed_isr = false;
ret = devm_request_irq(&pdev->dev, irq, tmio_mmc_card_detect_irq, 0,
dev_name(&pdev->dev), host);
if (ret)
goto eirq;
}
irq = platform_get_irq_byname(pdev, SH_MOBILE_SDHI_IRQ_SDIO);
if (irq >= 0) {
multiplexed_isr = false;
ret = devm_request_irq(&pdev->dev, irq, tmio_mmc_sdio_irq, 0,
dev_name(&pdev->dev), host);
if (ret)
goto eirq;
}
irq = platform_get_irq_byname(pdev, SH_MOBILE_SDHI_IRQ_SDCARD);
if (irq >= 0) {
multiplexed_isr = false;
ret = devm_request_irq(&pdev->dev, irq, tmio_mmc_sdcard_irq, 0,
dev_name(&pdev->dev), host);
if (ret)
goto eirq;
} else if (!multiplexed_isr) {
dev_err(&pdev->dev,
"Principal SD-card IRQ is missing among named interrupts\n");
ret = irq;
goto eirq;
}
if (multiplexed_isr) {
while (1) {
irq = platform_get_irq(pdev, i);
if (irq < 0)
break;
i++;
ret = devm_request_irq(&pdev->dev, irq, tmio_mmc_irq, 0,
dev_name(&pdev->dev), host);
if (ret)
goto eirq;
}
/* There must be at least one IRQ source */
if (!i)
goto eirq;
}
dev_info(&pdev->dev, "%s base at 0x%08lx clock rate %u MHz\n",
mmc_hostname(host->mmc), (unsigned long)
(platform_get_resource(pdev, IORESOURCE_MEM, 0)->start),
host->mmc->f_max / 1000000);
return ret;
eirq:
tmio_mmc_host_remove(host);
eprobe:
eclkget:
if (p && p->cleanup)
p->cleanup(pdev);
return ret;
}
static int sh_mobile_sdhi_remove(struct platform_device *pdev)
{
struct mmc_host *mmc = platform_get_drvdata(pdev);
struct tmio_mmc_host *host = mmc_priv(mmc);
struct sh_mobile_sdhi_info *p = pdev->dev.platform_data;
tmio_mmc_host_remove(host);
if (p && p->cleanup)
p->cleanup(pdev);
return 0;
}
static const struct dev_pm_ops tmio_mmc_dev_pm_ops = {
.suspend = tmio_mmc_host_suspend,
.resume = tmio_mmc_host_resume,
.runtime_suspend = tmio_mmc_host_runtime_suspend,
.runtime_resume = tmio_mmc_host_runtime_resume,
};
static struct platform_driver sh_mobile_sdhi_driver = {
.driver = {
.name = "sh_mobile_sdhi",
.owner = THIS_MODULE,
.pm = &tmio_mmc_dev_pm_ops,
.of_match_table = sh_mobile_sdhi_of_match,
},
.probe = sh_mobile_sdhi_probe,
.remove = sh_mobile_sdhi_remove,
};
module_platform_driver(sh_mobile_sdhi_driver);
MODULE_DESCRIPTION("SuperH Mobile SDHI driver");
MODULE_AUTHOR("Magnus Damm");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("platform:sh_mobile_sdhi");
| gpl-2.0 |
AICP/kernel_asus_fugu | arch/arm/mach-kirkwood/guruplug-setup.c | 2144 | 3044 | /*
* arch/arm/mach-kirkwood/guruplug-setup.c
*
* Marvell GuruPlug Reference Board Setup
*
* 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/init.h>
#include <linux/platform_device.h>
#include <linux/mtd/partitions.h>
#include <linux/ata_platform.h>
#include <linux/mv643xx_eth.h>
#include <linux/gpio.h>
#include <linux/leds.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <mach/kirkwood.h>
#include <linux/platform_data/mmc-mvsdio.h>
#include "common.h"
#include "mpp.h"
static struct mtd_partition guruplug_nand_parts[] = {
{
.name = "u-boot",
.offset = 0,
.size = SZ_1M
}, {
.name = "uImage",
.offset = MTDPART_OFS_NXTBLK,
.size = SZ_4M
}, {
.name = "root",
.offset = MTDPART_OFS_NXTBLK,
.size = MTDPART_SIZ_FULL
},
};
static struct mv643xx_eth_platform_data guruplug_ge00_data = {
.phy_addr = MV643XX_ETH_PHY_ADDR(0),
};
static struct mv643xx_eth_platform_data guruplug_ge01_data = {
.phy_addr = MV643XX_ETH_PHY_ADDR(1),
};
static struct mv_sata_platform_data guruplug_sata_data = {
.n_ports = 1,
};
static struct mvsdio_platform_data guruplug_mvsdio_data = {
/* unfortunately the CD signal has not been connected */
.gpio_card_detect = -1,
.gpio_write_protect = -1,
};
static struct gpio_led guruplug_led_pins[] = {
{
.name = "guruplug:red:health",
.gpio = 46,
.active_low = 1,
},
{
.name = "guruplug:green:health",
.gpio = 47,
.active_low = 1,
},
{
.name = "guruplug:red:wmode",
.gpio = 48,
.active_low = 1,
},
{
.name = "guruplug:green:wmode",
.gpio = 49,
.active_low = 1,
},
};
static struct gpio_led_platform_data guruplug_led_data = {
.leds = guruplug_led_pins,
.num_leds = ARRAY_SIZE(guruplug_led_pins),
};
static struct platform_device guruplug_leds = {
.name = "leds-gpio",
.id = -1,
.dev = {
.platform_data = &guruplug_led_data,
}
};
static unsigned int guruplug_mpp_config[] __initdata = {
MPP46_GPIO, /* M_RLED */
MPP47_GPIO, /* M_GLED */
MPP48_GPIO, /* B_RLED */
MPP49_GPIO, /* B_GLED */
0
};
static void __init guruplug_init(void)
{
/*
* Basic setup. Needs to be called early.
*/
kirkwood_init();
kirkwood_mpp_conf(guruplug_mpp_config);
kirkwood_uart0_init();
kirkwood_nand_init(ARRAY_AND_SIZE(guruplug_nand_parts), 25);
kirkwood_ehci_init();
kirkwood_ge00_init(&guruplug_ge00_data);
kirkwood_ge01_init(&guruplug_ge01_data);
kirkwood_sata_init(&guruplug_sata_data);
kirkwood_sdio_init(&guruplug_mvsdio_data);
platform_device_register(&guruplug_leds);
}
MACHINE_START(GURUPLUG, "Marvell GuruPlug Reference Board")
/* Maintainer: Siddarth Gore <gores@marvell.com> */
.atag_offset = 0x100,
.init_machine = guruplug_init,
.map_io = kirkwood_map_io,
.init_early = kirkwood_init_early,
.init_irq = kirkwood_init_irq,
.init_time = kirkwood_timer_init,
.restart = kirkwood_restart,
MACHINE_END
| gpl-2.0 |
ipodtouchdude/linux-amlogic | drivers/pci/hotplug/acpiphp_core.c | 2144 | 10390 | /*
* ACPI PCI Hot Plug Controller Driver
*
* Copyright (C) 1995,2001 Compaq Computer Corporation
* Copyright (C) 2001 Greg Kroah-Hartman (greg@kroah.com)
* Copyright (C) 2001 IBM Corp.
* Copyright (C) 2002 Hiroshi Aono (h-aono@ap.jp.nec.com)
* Copyright (C) 2002,2003 Takayoshi Kochi (t-kochi@bq.jp.nec.com)
* Copyright (C) 2002,2003 NEC Corporation
* Copyright (C) 2003-2005 Matthew Wilcox (matthew.wilcox@hp.com)
* Copyright (C) 2003-2005 Hewlett Packard
*
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
* NON INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Send feedback to <kristen.c.accardi@intel.com>
*
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/pci-acpi.h>
#include <linux/pci_hotplug.h>
#include <linux/slab.h>
#include <linux/smp.h>
#include "acpiphp.h"
#define MY_NAME "acpiphp"
/* name size which is used for entries in pcihpfs */
#define SLOT_NAME_SIZE 21 /* {_SUN} */
bool acpiphp_debug;
bool acpiphp_disabled;
/* local variables */
static struct acpiphp_attention_info *attention_info;
#define DRIVER_VERSION "0.5"
#define DRIVER_AUTHOR "Greg Kroah-Hartman <gregkh@us.ibm.com>, Takayoshi Kochi <t-kochi@bq.jp.nec.com>, Matthew Wilcox <willy@hp.com>"
#define DRIVER_DESC "ACPI Hot Plug PCI Controller Driver"
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
MODULE_PARM_DESC(debug, "Debugging mode enabled or not");
MODULE_PARM_DESC(disable, "disable acpiphp driver");
module_param_named(debug, acpiphp_debug, bool, 0644);
module_param_named(disable, acpiphp_disabled, bool, 0444);
/* export the attention callback registration methods */
EXPORT_SYMBOL_GPL(acpiphp_register_attention);
EXPORT_SYMBOL_GPL(acpiphp_unregister_attention);
static int enable_slot (struct hotplug_slot *slot);
static int disable_slot (struct hotplug_slot *slot);
static int set_attention_status (struct hotplug_slot *slot, u8 value);
static int get_power_status (struct hotplug_slot *slot, u8 *value);
static int get_attention_status (struct hotplug_slot *slot, u8 *value);
static int get_latch_status (struct hotplug_slot *slot, u8 *value);
static int get_adapter_status (struct hotplug_slot *slot, u8 *value);
static struct hotplug_slot_ops acpi_hotplug_slot_ops = {
.enable_slot = enable_slot,
.disable_slot = disable_slot,
.set_attention_status = set_attention_status,
.get_power_status = get_power_status,
.get_attention_status = get_attention_status,
.get_latch_status = get_latch_status,
.get_adapter_status = get_adapter_status,
};
/**
* acpiphp_register_attention - set attention LED callback
* @info: must be completely filled with LED callbacks
*
* Description: This is used to register a hardware specific ACPI
* driver that manipulates the attention LED. All the fields in
* info must be set.
*/
int acpiphp_register_attention(struct acpiphp_attention_info *info)
{
int retval = -EINVAL;
if (info && info->owner && info->set_attn &&
info->get_attn && !attention_info) {
retval = 0;
attention_info = info;
}
return retval;
}
/**
* acpiphp_unregister_attention - unset attention LED callback
* @info: must match the pointer used to register
*
* Description: This is used to un-register a hardware specific acpi
* driver that manipulates the attention LED. The pointer to the
* info struct must be the same as the one used to set it.
*/
int acpiphp_unregister_attention(struct acpiphp_attention_info *info)
{
int retval = -EINVAL;
if (info && attention_info == info) {
attention_info = NULL;
retval = 0;
}
return retval;
}
/**
* enable_slot - power on and enable a slot
* @hotplug_slot: slot to enable
*
* Actual tasks are done in acpiphp_enable_slot()
*/
static int enable_slot(struct hotplug_slot *hotplug_slot)
{
struct slot *slot = hotplug_slot->private;
dbg("%s - physical_slot = %s\n", __func__, slot_name(slot));
/* enable the specified slot */
return acpiphp_enable_slot(slot->acpi_slot);
}
/**
* disable_slot - disable and power off a slot
* @hotplug_slot: slot to disable
*
* Actual tasks are done in acpiphp_disable_slot()
*/
static int disable_slot(struct hotplug_slot *hotplug_slot)
{
struct slot *slot = hotplug_slot->private;
int retval;
dbg("%s - physical_slot = %s\n", __func__, slot_name(slot));
/* disable the specified slot */
retval = acpiphp_disable_slot(slot->acpi_slot);
if (!retval)
retval = acpiphp_eject_slot(slot->acpi_slot);
return retval;
}
/**
* set_attention_status - set attention LED
* @hotplug_slot: slot to set attention LED on
* @status: value to set attention LED to (0 or 1)
*
* attention status LED, so we use a callback that
* was registered with us. This allows hardware specific
* ACPI implementations to blink the light for us.
*/
static int set_attention_status(struct hotplug_slot *hotplug_slot, u8 status)
{
int retval = -ENODEV;
dbg("%s - physical_slot = %s\n", __func__, hotplug_slot_name(hotplug_slot));
if (attention_info && try_module_get(attention_info->owner)) {
retval = attention_info->set_attn(hotplug_slot, status);
module_put(attention_info->owner);
} else
attention_info = NULL;
return retval;
}
/**
* get_power_status - get power status of a slot
* @hotplug_slot: slot to get status
* @value: pointer to store status
*
* Some platforms may not implement _STA method properly.
* In that case, the value returned may not be reliable.
*/
static int get_power_status(struct hotplug_slot *hotplug_slot, u8 *value)
{
struct slot *slot = hotplug_slot->private;
dbg("%s - physical_slot = %s\n", __func__, slot_name(slot));
*value = acpiphp_get_power_status(slot->acpi_slot);
return 0;
}
/**
* get_attention_status - get attention LED status
* @hotplug_slot: slot to get status from
* @value: returns with value of attention LED
*
* ACPI doesn't have known method to determine the state
* of the attention status LED, so we use a callback that
* was registered with us. This allows hardware specific
* ACPI implementations to determine its state.
*/
static int get_attention_status(struct hotplug_slot *hotplug_slot, u8 *value)
{
int retval = -EINVAL;
dbg("%s - physical_slot = %s\n", __func__, hotplug_slot_name(hotplug_slot));
if (attention_info && try_module_get(attention_info->owner)) {
retval = attention_info->get_attn(hotplug_slot, value);
module_put(attention_info->owner);
} else
attention_info = NULL;
return retval;
}
/**
* get_latch_status - get latch status of a slot
* @hotplug_slot: slot to get status
* @value: pointer to store status
*
* ACPI doesn't provide any formal means to access latch status.
* Instead, we fake latch status from _STA.
*/
static int get_latch_status(struct hotplug_slot *hotplug_slot, u8 *value)
{
struct slot *slot = hotplug_slot->private;
dbg("%s - physical_slot = %s\n", __func__, slot_name(slot));
*value = acpiphp_get_latch_status(slot->acpi_slot);
return 0;
}
/**
* get_adapter_status - get adapter status of a slot
* @hotplug_slot: slot to get status
* @value: pointer to store status
*
* ACPI doesn't provide any formal means to access adapter status.
* Instead, we fake adapter status from _STA.
*/
static int get_adapter_status(struct hotplug_slot *hotplug_slot, u8 *value)
{
struct slot *slot = hotplug_slot->private;
dbg("%s - physical_slot = %s\n", __func__, slot_name(slot));
*value = acpiphp_get_adapter_status(slot->acpi_slot);
return 0;
}
/**
* release_slot - free up the memory used by a slot
* @hotplug_slot: slot to free
*/
static void release_slot(struct hotplug_slot *hotplug_slot)
{
struct slot *slot = hotplug_slot->private;
dbg("%s - physical_slot = %s\n", __func__, slot_name(slot));
kfree(slot->hotplug_slot);
kfree(slot);
}
/* callback routine to initialize 'struct slot' for each slot */
int acpiphp_register_hotplug_slot(struct acpiphp_slot *acpiphp_slot)
{
struct slot *slot;
int retval = -ENOMEM;
char name[SLOT_NAME_SIZE];
slot = kzalloc(sizeof(*slot), GFP_KERNEL);
if (!slot)
goto error;
slot->hotplug_slot = kzalloc(sizeof(*slot->hotplug_slot), GFP_KERNEL);
if (!slot->hotplug_slot)
goto error_slot;
slot->hotplug_slot->info = &slot->info;
slot->hotplug_slot->private = slot;
slot->hotplug_slot->release = &release_slot;
slot->hotplug_slot->ops = &acpi_hotplug_slot_ops;
slot->acpi_slot = acpiphp_slot;
slot->hotplug_slot->info->power_status = acpiphp_get_power_status(slot->acpi_slot);
slot->hotplug_slot->info->attention_status = 0;
slot->hotplug_slot->info->latch_status = acpiphp_get_latch_status(slot->acpi_slot);
slot->hotplug_slot->info->adapter_status = acpiphp_get_adapter_status(slot->acpi_slot);
acpiphp_slot->slot = slot;
snprintf(name, SLOT_NAME_SIZE, "%llu", slot->acpi_slot->sun);
retval = pci_hp_register(slot->hotplug_slot,
acpiphp_slot->bridge->pci_bus,
acpiphp_slot->device,
name);
if (retval == -EBUSY)
goto error_hpslot;
if (retval) {
err("pci_hp_register failed with error %d\n", retval);
goto error_hpslot;
}
info("Slot [%s] registered\n", slot_name(slot));
return 0;
error_hpslot:
kfree(slot->hotplug_slot);
error_slot:
kfree(slot);
error:
return retval;
}
void acpiphp_unregister_hotplug_slot(struct acpiphp_slot *acpiphp_slot)
{
struct slot *slot = acpiphp_slot->slot;
int retval = 0;
info("Slot [%s] unregistered\n", slot_name(slot));
retval = pci_hp_deregister(slot->hotplug_slot);
if (retval)
err("pci_hp_deregister failed with error %d\n", retval);
}
void __init acpiphp_init(void)
{
info(DRIVER_DESC " version: " DRIVER_VERSION "%s\n",
acpiphp_disabled ? ", disabled by user; please report a bug"
: "");
}
| gpl-2.0 |
Serranove/android_kernel_samsung_serranovelte | drivers/net/ethernet/marvell/skge.c | 2144 | 108113 | /*
* New driver for Marvell Yukon chipset and SysKonnect Gigabit
* Ethernet adapters. Based on earlier sk98lin, e100 and
* FreeBSD if_sk drivers.
*
* This driver intentionally does not support all the features
* of the original driver such as link fail-over and link management because
* those should be done at higher levels.
*
* Copyright (C) 2004, 2005 Stephen Hemminger <shemminger@osdl.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.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/in.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/pci.h>
#include <linux/if_vlan.h>
#include <linux/ip.h>
#include <linux/delay.h>
#include <linux/crc32.h>
#include <linux/dma-mapping.h>
#include <linux/debugfs.h>
#include <linux/sched.h>
#include <linux/seq_file.h>
#include <linux/mii.h>
#include <linux/slab.h>
#include <linux/dmi.h>
#include <linux/prefetch.h>
#include <asm/irq.h>
#include "skge.h"
#define DRV_NAME "skge"
#define DRV_VERSION "1.14"
#define DEFAULT_TX_RING_SIZE 128
#define DEFAULT_RX_RING_SIZE 512
#define MAX_TX_RING_SIZE 1024
#define TX_LOW_WATER (MAX_SKB_FRAGS + 1)
#define MAX_RX_RING_SIZE 4096
#define RX_COPY_THRESHOLD 128
#define RX_BUF_SIZE 1536
#define PHY_RETRIES 1000
#define ETH_JUMBO_MTU 9000
#define TX_WATCHDOG (5 * HZ)
#define NAPI_WEIGHT 64
#define BLINK_MS 250
#define LINK_HZ HZ
#define SKGE_EEPROM_MAGIC 0x9933aabb
MODULE_DESCRIPTION("SysKonnect Gigabit Ethernet driver");
MODULE_AUTHOR("Stephen Hemminger <shemminger@linux-foundation.org>");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);
static const u32 default_msg = (NETIF_MSG_DRV | NETIF_MSG_PROBE |
NETIF_MSG_LINK | NETIF_MSG_IFUP |
NETIF_MSG_IFDOWN);
static int debug = -1; /* defaults above */
module_param(debug, int, 0);
MODULE_PARM_DESC(debug, "Debug level (0=none,...,16=all)");
static DEFINE_PCI_DEVICE_TABLE(skge_id_table) = {
{ PCI_DEVICE(PCI_VENDOR_ID_3COM, 0x1700) }, /* 3Com 3C940 */
{ PCI_DEVICE(PCI_VENDOR_ID_3COM, 0x80EB) }, /* 3Com 3C940B */
#ifdef CONFIG_SKGE_GENESIS
{ PCI_DEVICE(PCI_VENDOR_ID_SYSKONNECT, 0x4300) }, /* SK-9xx */
#endif
{ PCI_DEVICE(PCI_VENDOR_ID_SYSKONNECT, 0x4320) }, /* SK-98xx V2.0 */
{ PCI_DEVICE(PCI_VENDOR_ID_DLINK, 0x4b01) }, /* D-Link DGE-530T (rev.B) */
{ PCI_DEVICE(PCI_VENDOR_ID_DLINK, 0x4c00) }, /* D-Link DGE-530T */
{ PCI_DEVICE(PCI_VENDOR_ID_DLINK, 0x4302) }, /* D-Link DGE-530T Rev C1 */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x4320) }, /* Marvell Yukon 88E8001/8003/8010 */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x5005) }, /* Belkin */
{ PCI_DEVICE(PCI_VENDOR_ID_CNET, 0x434E) }, /* CNet PowerG-2000 */
{ PCI_DEVICE(PCI_VENDOR_ID_LINKSYS, 0x1064) }, /* Linksys EG1064 v2 */
{ PCI_VENDOR_ID_LINKSYS, 0x1032, PCI_ANY_ID, 0x0015 }, /* Linksys EG1032 v2 */
{ 0 }
};
MODULE_DEVICE_TABLE(pci, skge_id_table);
static int skge_up(struct net_device *dev);
static int skge_down(struct net_device *dev);
static void skge_phy_reset(struct skge_port *skge);
static void skge_tx_clean(struct net_device *dev);
static int xm_phy_write(struct skge_hw *hw, int port, u16 reg, u16 val);
static int gm_phy_write(struct skge_hw *hw, int port, u16 reg, u16 val);
static void genesis_get_stats(struct skge_port *skge, u64 *data);
static void yukon_get_stats(struct skge_port *skge, u64 *data);
static void yukon_init(struct skge_hw *hw, int port);
static void genesis_mac_init(struct skge_hw *hw, int port);
static void genesis_link_up(struct skge_port *skge);
static void skge_set_multicast(struct net_device *dev);
static irqreturn_t skge_intr(int irq, void *dev_id);
/* Avoid conditionals by using array */
static const int txqaddr[] = { Q_XA1, Q_XA2 };
static const int rxqaddr[] = { Q_R1, Q_R2 };
static const u32 rxirqmask[] = { IS_R1_F, IS_R2_F };
static const u32 txirqmask[] = { IS_XA1_F, IS_XA2_F };
static const u32 napimask[] = { IS_R1_F|IS_XA1_F, IS_R2_F|IS_XA2_F };
static const u32 portmask[] = { IS_PORT_1, IS_PORT_2 };
static inline bool is_genesis(const struct skge_hw *hw)
{
#ifdef CONFIG_SKGE_GENESIS
return hw->chip_id == CHIP_ID_GENESIS;
#else
return false;
#endif
}
static int skge_get_regs_len(struct net_device *dev)
{
return 0x4000;
}
/*
* Returns copy of whole control register region
* Note: skip RAM address register because accessing it will
* cause bus hangs!
*/
static void skge_get_regs(struct net_device *dev, struct ethtool_regs *regs,
void *p)
{
const struct skge_port *skge = netdev_priv(dev);
const void __iomem *io = skge->hw->regs;
regs->version = 1;
memset(p, 0, regs->len);
memcpy_fromio(p, io, B3_RAM_ADDR);
memcpy_fromio(p + B3_RI_WTO_R1, io + B3_RI_WTO_R1,
regs->len - B3_RI_WTO_R1);
}
/* Wake on Lan only supported on Yukon chips with rev 1 or above */
static u32 wol_supported(const struct skge_hw *hw)
{
if (is_genesis(hw))
return 0;
if (hw->chip_id == CHIP_ID_YUKON && hw->chip_rev == 0)
return 0;
return WAKE_MAGIC | WAKE_PHY;
}
static void skge_wol_init(struct skge_port *skge)
{
struct skge_hw *hw = skge->hw;
int port = skge->port;
u16 ctrl;
skge_write16(hw, B0_CTST, CS_RST_CLR);
skge_write16(hw, SK_REG(port, GMAC_LINK_CTRL), GMLC_RST_CLR);
/* Turn on Vaux */
skge_write8(hw, B0_POWER_CTRL,
PC_VAUX_ENA | PC_VCC_ENA | PC_VAUX_ON | PC_VCC_OFF);
/* WA code for COMA mode -- clear PHY reset */
if (hw->chip_id == CHIP_ID_YUKON_LITE &&
hw->chip_rev >= CHIP_REV_YU_LITE_A3) {
u32 reg = skge_read32(hw, B2_GP_IO);
reg |= GP_DIR_9;
reg &= ~GP_IO_9;
skge_write32(hw, B2_GP_IO, reg);
}
skge_write32(hw, SK_REG(port, GPHY_CTRL),
GPC_DIS_SLEEP |
GPC_HWCFG_M_3 | GPC_HWCFG_M_2 | GPC_HWCFG_M_1 | GPC_HWCFG_M_0 |
GPC_ANEG_1 | GPC_RST_SET);
skge_write32(hw, SK_REG(port, GPHY_CTRL),
GPC_DIS_SLEEP |
GPC_HWCFG_M_3 | GPC_HWCFG_M_2 | GPC_HWCFG_M_1 | GPC_HWCFG_M_0 |
GPC_ANEG_1 | GPC_RST_CLR);
skge_write32(hw, SK_REG(port, GMAC_CTRL), GMC_RST_CLR);
/* Force to 10/100 skge_reset will re-enable on resume */
gm_phy_write(hw, port, PHY_MARV_AUNE_ADV,
(PHY_AN_100FULL | PHY_AN_100HALF |
PHY_AN_10FULL | PHY_AN_10HALF | PHY_AN_CSMA));
/* no 1000 HD/FD */
gm_phy_write(hw, port, PHY_MARV_1000T_CTRL, 0);
gm_phy_write(hw, port, PHY_MARV_CTRL,
PHY_CT_RESET | PHY_CT_SPS_LSB | PHY_CT_ANE |
PHY_CT_RE_CFG | PHY_CT_DUP_MD);
/* Set GMAC to no flow control and auto update for speed/duplex */
gma_write16(hw, port, GM_GP_CTRL,
GM_GPCR_FC_TX_DIS|GM_GPCR_TX_ENA|GM_GPCR_RX_ENA|
GM_GPCR_DUP_FULL|GM_GPCR_FC_RX_DIS|GM_GPCR_AU_FCT_DIS);
/* Set WOL address */
memcpy_toio(hw->regs + WOL_REGS(port, WOL_MAC_ADDR),
skge->netdev->dev_addr, ETH_ALEN);
/* Turn on appropriate WOL control bits */
skge_write16(hw, WOL_REGS(port, WOL_CTRL_STAT), WOL_CTL_CLEAR_RESULT);
ctrl = 0;
if (skge->wol & WAKE_PHY)
ctrl |= WOL_CTL_ENA_PME_ON_LINK_CHG|WOL_CTL_ENA_LINK_CHG_UNIT;
else
ctrl |= WOL_CTL_DIS_PME_ON_LINK_CHG|WOL_CTL_DIS_LINK_CHG_UNIT;
if (skge->wol & WAKE_MAGIC)
ctrl |= WOL_CTL_ENA_PME_ON_MAGIC_PKT|WOL_CTL_ENA_MAGIC_PKT_UNIT;
else
ctrl |= WOL_CTL_DIS_PME_ON_MAGIC_PKT|WOL_CTL_DIS_MAGIC_PKT_UNIT;
ctrl |= WOL_CTL_DIS_PME_ON_PATTERN|WOL_CTL_DIS_PATTERN_UNIT;
skge_write16(hw, WOL_REGS(port, WOL_CTRL_STAT), ctrl);
/* block receiver */
skge_write8(hw, SK_REG(port, RX_GMF_CTRL_T), GMF_RST_SET);
}
static void skge_get_wol(struct net_device *dev, struct ethtool_wolinfo *wol)
{
struct skge_port *skge = netdev_priv(dev);
wol->supported = wol_supported(skge->hw);
wol->wolopts = skge->wol;
}
static int skge_set_wol(struct net_device *dev, struct ethtool_wolinfo *wol)
{
struct skge_port *skge = netdev_priv(dev);
struct skge_hw *hw = skge->hw;
if ((wol->wolopts & ~wol_supported(hw)) ||
!device_can_wakeup(&hw->pdev->dev))
return -EOPNOTSUPP;
skge->wol = wol->wolopts;
device_set_wakeup_enable(&hw->pdev->dev, skge->wol);
return 0;
}
/* Determine supported/advertised modes based on hardware.
* Note: ethtool ADVERTISED_xxx == SUPPORTED_xxx
*/
static u32 skge_supported_modes(const struct skge_hw *hw)
{
u32 supported;
if (hw->copper) {
supported = (SUPPORTED_10baseT_Half |
SUPPORTED_10baseT_Full |
SUPPORTED_100baseT_Half |
SUPPORTED_100baseT_Full |
SUPPORTED_1000baseT_Half |
SUPPORTED_1000baseT_Full |
SUPPORTED_Autoneg |
SUPPORTED_TP);
if (is_genesis(hw))
supported &= ~(SUPPORTED_10baseT_Half |
SUPPORTED_10baseT_Full |
SUPPORTED_100baseT_Half |
SUPPORTED_100baseT_Full);
else if (hw->chip_id == CHIP_ID_YUKON)
supported &= ~SUPPORTED_1000baseT_Half;
} else
supported = (SUPPORTED_1000baseT_Full |
SUPPORTED_1000baseT_Half |
SUPPORTED_FIBRE |
SUPPORTED_Autoneg);
return supported;
}
static int skge_get_settings(struct net_device *dev,
struct ethtool_cmd *ecmd)
{
struct skge_port *skge = netdev_priv(dev);
struct skge_hw *hw = skge->hw;
ecmd->transceiver = XCVR_INTERNAL;
ecmd->supported = skge_supported_modes(hw);
if (hw->copper) {
ecmd->port = PORT_TP;
ecmd->phy_address = hw->phy_addr;
} else
ecmd->port = PORT_FIBRE;
ecmd->advertising = skge->advertising;
ecmd->autoneg = skge->autoneg;
ethtool_cmd_speed_set(ecmd, skge->speed);
ecmd->duplex = skge->duplex;
return 0;
}
static int skge_set_settings(struct net_device *dev, struct ethtool_cmd *ecmd)
{
struct skge_port *skge = netdev_priv(dev);
const struct skge_hw *hw = skge->hw;
u32 supported = skge_supported_modes(hw);
int err = 0;
if (ecmd->autoneg == AUTONEG_ENABLE) {
ecmd->advertising = supported;
skge->duplex = -1;
skge->speed = -1;
} else {
u32 setting;
u32 speed = ethtool_cmd_speed(ecmd);
switch (speed) {
case SPEED_1000:
if (ecmd->duplex == DUPLEX_FULL)
setting = SUPPORTED_1000baseT_Full;
else if (ecmd->duplex == DUPLEX_HALF)
setting = SUPPORTED_1000baseT_Half;
else
return -EINVAL;
break;
case SPEED_100:
if (ecmd->duplex == DUPLEX_FULL)
setting = SUPPORTED_100baseT_Full;
else if (ecmd->duplex == DUPLEX_HALF)
setting = SUPPORTED_100baseT_Half;
else
return -EINVAL;
break;
case SPEED_10:
if (ecmd->duplex == DUPLEX_FULL)
setting = SUPPORTED_10baseT_Full;
else if (ecmd->duplex == DUPLEX_HALF)
setting = SUPPORTED_10baseT_Half;
else
return -EINVAL;
break;
default:
return -EINVAL;
}
if ((setting & supported) == 0)
return -EINVAL;
skge->speed = speed;
skge->duplex = ecmd->duplex;
}
skge->autoneg = ecmd->autoneg;
skge->advertising = ecmd->advertising;
if (netif_running(dev)) {
skge_down(dev);
err = skge_up(dev);
if (err) {
dev_close(dev);
return err;
}
}
return 0;
}
static void skge_get_drvinfo(struct net_device *dev,
struct ethtool_drvinfo *info)
{
struct skge_port *skge = netdev_priv(dev);
strlcpy(info->driver, DRV_NAME, sizeof(info->driver));
strlcpy(info->version, DRV_VERSION, sizeof(info->version));
strlcpy(info->bus_info, pci_name(skge->hw->pdev),
sizeof(info->bus_info));
}
static const struct skge_stat {
char name[ETH_GSTRING_LEN];
u16 xmac_offset;
u16 gma_offset;
} skge_stats[] = {
{ "tx_bytes", XM_TXO_OK_HI, GM_TXO_OK_HI },
{ "rx_bytes", XM_RXO_OK_HI, GM_RXO_OK_HI },
{ "tx_broadcast", XM_TXF_BC_OK, GM_TXF_BC_OK },
{ "rx_broadcast", XM_RXF_BC_OK, GM_RXF_BC_OK },
{ "tx_multicast", XM_TXF_MC_OK, GM_TXF_MC_OK },
{ "rx_multicast", XM_RXF_MC_OK, GM_RXF_MC_OK },
{ "tx_unicast", XM_TXF_UC_OK, GM_TXF_UC_OK },
{ "rx_unicast", XM_RXF_UC_OK, GM_RXF_UC_OK },
{ "tx_mac_pause", XM_TXF_MPAUSE, GM_TXF_MPAUSE },
{ "rx_mac_pause", XM_RXF_MPAUSE, GM_RXF_MPAUSE },
{ "collisions", XM_TXF_SNG_COL, GM_TXF_SNG_COL },
{ "multi_collisions", XM_TXF_MUL_COL, GM_TXF_MUL_COL },
{ "aborted", XM_TXF_ABO_COL, GM_TXF_ABO_COL },
{ "late_collision", XM_TXF_LAT_COL, GM_TXF_LAT_COL },
{ "fifo_underrun", XM_TXE_FIFO_UR, GM_TXE_FIFO_UR },
{ "fifo_overflow", XM_RXE_FIFO_OV, GM_RXE_FIFO_OV },
{ "rx_toolong", XM_RXF_LNG_ERR, GM_RXF_LNG_ERR },
{ "rx_jabber", XM_RXF_JAB_PKT, GM_RXF_JAB_PKT },
{ "rx_runt", XM_RXE_RUNT, GM_RXE_FRAG },
{ "rx_too_long", XM_RXF_LNG_ERR, GM_RXF_LNG_ERR },
{ "rx_fcs_error", XM_RXF_FCS_ERR, GM_RXF_FCS_ERR },
};
static int skge_get_sset_count(struct net_device *dev, int sset)
{
switch (sset) {
case ETH_SS_STATS:
return ARRAY_SIZE(skge_stats);
default:
return -EOPNOTSUPP;
}
}
static void skge_get_ethtool_stats(struct net_device *dev,
struct ethtool_stats *stats, u64 *data)
{
struct skge_port *skge = netdev_priv(dev);
if (is_genesis(skge->hw))
genesis_get_stats(skge, data);
else
yukon_get_stats(skge, data);
}
/* Use hardware MIB variables for critical path statistics and
* transmit feedback not reported at interrupt.
* Other errors are accounted for in interrupt handler.
*/
static struct net_device_stats *skge_get_stats(struct net_device *dev)
{
struct skge_port *skge = netdev_priv(dev);
u64 data[ARRAY_SIZE(skge_stats)];
if (is_genesis(skge->hw))
genesis_get_stats(skge, data);
else
yukon_get_stats(skge, data);
dev->stats.tx_bytes = data[0];
dev->stats.rx_bytes = data[1];
dev->stats.tx_packets = data[2] + data[4] + data[6];
dev->stats.rx_packets = data[3] + data[5] + data[7];
dev->stats.multicast = data[3] + data[5];
dev->stats.collisions = data[10];
dev->stats.tx_aborted_errors = data[12];
return &dev->stats;
}
static void skge_get_strings(struct net_device *dev, u32 stringset, u8 *data)
{
int i;
switch (stringset) {
case ETH_SS_STATS:
for (i = 0; i < ARRAY_SIZE(skge_stats); i++)
memcpy(data + i * ETH_GSTRING_LEN,
skge_stats[i].name, ETH_GSTRING_LEN);
break;
}
}
static void skge_get_ring_param(struct net_device *dev,
struct ethtool_ringparam *p)
{
struct skge_port *skge = netdev_priv(dev);
p->rx_max_pending = MAX_RX_RING_SIZE;
p->tx_max_pending = MAX_TX_RING_SIZE;
p->rx_pending = skge->rx_ring.count;
p->tx_pending = skge->tx_ring.count;
}
static int skge_set_ring_param(struct net_device *dev,
struct ethtool_ringparam *p)
{
struct skge_port *skge = netdev_priv(dev);
int err = 0;
if (p->rx_pending == 0 || p->rx_pending > MAX_RX_RING_SIZE ||
p->tx_pending < TX_LOW_WATER || p->tx_pending > MAX_TX_RING_SIZE)
return -EINVAL;
skge->rx_ring.count = p->rx_pending;
skge->tx_ring.count = p->tx_pending;
if (netif_running(dev)) {
skge_down(dev);
err = skge_up(dev);
if (err)
dev_close(dev);
}
return err;
}
static u32 skge_get_msglevel(struct net_device *netdev)
{
struct skge_port *skge = netdev_priv(netdev);
return skge->msg_enable;
}
static void skge_set_msglevel(struct net_device *netdev, u32 value)
{
struct skge_port *skge = netdev_priv(netdev);
skge->msg_enable = value;
}
static int skge_nway_reset(struct net_device *dev)
{
struct skge_port *skge = netdev_priv(dev);
if (skge->autoneg != AUTONEG_ENABLE || !netif_running(dev))
return -EINVAL;
skge_phy_reset(skge);
return 0;
}
static void skge_get_pauseparam(struct net_device *dev,
struct ethtool_pauseparam *ecmd)
{
struct skge_port *skge = netdev_priv(dev);
ecmd->rx_pause = ((skge->flow_control == FLOW_MODE_SYMMETRIC) ||
(skge->flow_control == FLOW_MODE_SYM_OR_REM));
ecmd->tx_pause = (ecmd->rx_pause ||
(skge->flow_control == FLOW_MODE_LOC_SEND));
ecmd->autoneg = ecmd->rx_pause || ecmd->tx_pause;
}
static int skge_set_pauseparam(struct net_device *dev,
struct ethtool_pauseparam *ecmd)
{
struct skge_port *skge = netdev_priv(dev);
struct ethtool_pauseparam old;
int err = 0;
skge_get_pauseparam(dev, &old);
if (ecmd->autoneg != old.autoneg)
skge->flow_control = ecmd->autoneg ? FLOW_MODE_NONE : FLOW_MODE_SYMMETRIC;
else {
if (ecmd->rx_pause && ecmd->tx_pause)
skge->flow_control = FLOW_MODE_SYMMETRIC;
else if (ecmd->rx_pause && !ecmd->tx_pause)
skge->flow_control = FLOW_MODE_SYM_OR_REM;
else if (!ecmd->rx_pause && ecmd->tx_pause)
skge->flow_control = FLOW_MODE_LOC_SEND;
else
skge->flow_control = FLOW_MODE_NONE;
}
if (netif_running(dev)) {
skge_down(dev);
err = skge_up(dev);
if (err) {
dev_close(dev);
return err;
}
}
return 0;
}
/* Chip internal frequency for clock calculations */
static inline u32 hwkhz(const struct skge_hw *hw)
{
return is_genesis(hw) ? 53125 : 78125;
}
/* Chip HZ to microseconds */
static inline u32 skge_clk2usec(const struct skge_hw *hw, u32 ticks)
{
return (ticks * 1000) / hwkhz(hw);
}
/* Microseconds to chip HZ */
static inline u32 skge_usecs2clk(const struct skge_hw *hw, u32 usec)
{
return hwkhz(hw) * usec / 1000;
}
static int skge_get_coalesce(struct net_device *dev,
struct ethtool_coalesce *ecmd)
{
struct skge_port *skge = netdev_priv(dev);
struct skge_hw *hw = skge->hw;
int port = skge->port;
ecmd->rx_coalesce_usecs = 0;
ecmd->tx_coalesce_usecs = 0;
if (skge_read32(hw, B2_IRQM_CTRL) & TIM_START) {
u32 delay = skge_clk2usec(hw, skge_read32(hw, B2_IRQM_INI));
u32 msk = skge_read32(hw, B2_IRQM_MSK);
if (msk & rxirqmask[port])
ecmd->rx_coalesce_usecs = delay;
if (msk & txirqmask[port])
ecmd->tx_coalesce_usecs = delay;
}
return 0;
}
/* Note: interrupt timer is per board, but can turn on/off per port */
static int skge_set_coalesce(struct net_device *dev,
struct ethtool_coalesce *ecmd)
{
struct skge_port *skge = netdev_priv(dev);
struct skge_hw *hw = skge->hw;
int port = skge->port;
u32 msk = skge_read32(hw, B2_IRQM_MSK);
u32 delay = 25;
if (ecmd->rx_coalesce_usecs == 0)
msk &= ~rxirqmask[port];
else if (ecmd->rx_coalesce_usecs < 25 ||
ecmd->rx_coalesce_usecs > 33333)
return -EINVAL;
else {
msk |= rxirqmask[port];
delay = ecmd->rx_coalesce_usecs;
}
if (ecmd->tx_coalesce_usecs == 0)
msk &= ~txirqmask[port];
else if (ecmd->tx_coalesce_usecs < 25 ||
ecmd->tx_coalesce_usecs > 33333)
return -EINVAL;
else {
msk |= txirqmask[port];
delay = min(delay, ecmd->rx_coalesce_usecs);
}
skge_write32(hw, B2_IRQM_MSK, msk);
if (msk == 0)
skge_write32(hw, B2_IRQM_CTRL, TIM_STOP);
else {
skge_write32(hw, B2_IRQM_INI, skge_usecs2clk(hw, delay));
skge_write32(hw, B2_IRQM_CTRL, TIM_START);
}
return 0;
}
enum led_mode { LED_MODE_OFF, LED_MODE_ON, LED_MODE_TST };
static void skge_led(struct skge_port *skge, enum led_mode mode)
{
struct skge_hw *hw = skge->hw;
int port = skge->port;
spin_lock_bh(&hw->phy_lock);
if (is_genesis(hw)) {
switch (mode) {
case LED_MODE_OFF:
if (hw->phy_type == SK_PHY_BCOM)
xm_phy_write(hw, port, PHY_BCOM_P_EXT_CTRL, PHY_B_PEC_LED_OFF);
else {
skge_write32(hw, SK_REG(port, TX_LED_VAL), 0);
skge_write8(hw, SK_REG(port, TX_LED_CTRL), LED_T_OFF);
}
skge_write8(hw, SK_REG(port, LNK_LED_REG), LINKLED_OFF);
skge_write32(hw, SK_REG(port, RX_LED_VAL), 0);
skge_write8(hw, SK_REG(port, RX_LED_CTRL), LED_T_OFF);
break;
case LED_MODE_ON:
skge_write8(hw, SK_REG(port, LNK_LED_REG), LINKLED_ON);
skge_write8(hw, SK_REG(port, LNK_LED_REG), LINKLED_LINKSYNC_ON);
skge_write8(hw, SK_REG(port, RX_LED_CTRL), LED_START);
skge_write8(hw, SK_REG(port, TX_LED_CTRL), LED_START);
break;
case LED_MODE_TST:
skge_write8(hw, SK_REG(port, RX_LED_TST), LED_T_ON);
skge_write32(hw, SK_REG(port, RX_LED_VAL), 100);
skge_write8(hw, SK_REG(port, RX_LED_CTRL), LED_START);
if (hw->phy_type == SK_PHY_BCOM)
xm_phy_write(hw, port, PHY_BCOM_P_EXT_CTRL, PHY_B_PEC_LED_ON);
else {
skge_write8(hw, SK_REG(port, TX_LED_TST), LED_T_ON);
skge_write32(hw, SK_REG(port, TX_LED_VAL), 100);
skge_write8(hw, SK_REG(port, TX_LED_CTRL), LED_START);
}
}
} else {
switch (mode) {
case LED_MODE_OFF:
gm_phy_write(hw, port, PHY_MARV_LED_CTRL, 0);
gm_phy_write(hw, port, PHY_MARV_LED_OVER,
PHY_M_LED_MO_DUP(MO_LED_OFF) |
PHY_M_LED_MO_10(MO_LED_OFF) |
PHY_M_LED_MO_100(MO_LED_OFF) |
PHY_M_LED_MO_1000(MO_LED_OFF) |
PHY_M_LED_MO_RX(MO_LED_OFF));
break;
case LED_MODE_ON:
gm_phy_write(hw, port, PHY_MARV_LED_CTRL,
PHY_M_LED_PULS_DUR(PULS_170MS) |
PHY_M_LED_BLINK_RT(BLINK_84MS) |
PHY_M_LEDC_TX_CTRL |
PHY_M_LEDC_DP_CTRL);
gm_phy_write(hw, port, PHY_MARV_LED_OVER,
PHY_M_LED_MO_RX(MO_LED_OFF) |
(skge->speed == SPEED_100 ?
PHY_M_LED_MO_100(MO_LED_ON) : 0));
break;
case LED_MODE_TST:
gm_phy_write(hw, port, PHY_MARV_LED_CTRL, 0);
gm_phy_write(hw, port, PHY_MARV_LED_OVER,
PHY_M_LED_MO_DUP(MO_LED_ON) |
PHY_M_LED_MO_10(MO_LED_ON) |
PHY_M_LED_MO_100(MO_LED_ON) |
PHY_M_LED_MO_1000(MO_LED_ON) |
PHY_M_LED_MO_RX(MO_LED_ON));
}
}
spin_unlock_bh(&hw->phy_lock);
}
/* blink LED's for finding board */
static int skge_set_phys_id(struct net_device *dev,
enum ethtool_phys_id_state state)
{
struct skge_port *skge = netdev_priv(dev);
switch (state) {
case ETHTOOL_ID_ACTIVE:
return 2; /* cycle on/off twice per second */
case ETHTOOL_ID_ON:
skge_led(skge, LED_MODE_TST);
break;
case ETHTOOL_ID_OFF:
skge_led(skge, LED_MODE_OFF);
break;
case ETHTOOL_ID_INACTIVE:
/* back to regular LED state */
skge_led(skge, netif_running(dev) ? LED_MODE_ON : LED_MODE_OFF);
}
return 0;
}
static int skge_get_eeprom_len(struct net_device *dev)
{
struct skge_port *skge = netdev_priv(dev);
u32 reg2;
pci_read_config_dword(skge->hw->pdev, PCI_DEV_REG2, ®2);
return 1 << (((reg2 & PCI_VPD_ROM_SZ) >> 14) + 8);
}
static u32 skge_vpd_read(struct pci_dev *pdev, int cap, u16 offset)
{
u32 val;
pci_write_config_word(pdev, cap + PCI_VPD_ADDR, offset);
do {
pci_read_config_word(pdev, cap + PCI_VPD_ADDR, &offset);
} while (!(offset & PCI_VPD_ADDR_F));
pci_read_config_dword(pdev, cap + PCI_VPD_DATA, &val);
return val;
}
static void skge_vpd_write(struct pci_dev *pdev, int cap, u16 offset, u32 val)
{
pci_write_config_dword(pdev, cap + PCI_VPD_DATA, val);
pci_write_config_word(pdev, cap + PCI_VPD_ADDR,
offset | PCI_VPD_ADDR_F);
do {
pci_read_config_word(pdev, cap + PCI_VPD_ADDR, &offset);
} while (offset & PCI_VPD_ADDR_F);
}
static int skge_get_eeprom(struct net_device *dev, struct ethtool_eeprom *eeprom,
u8 *data)
{
struct skge_port *skge = netdev_priv(dev);
struct pci_dev *pdev = skge->hw->pdev;
int cap = pci_find_capability(pdev, PCI_CAP_ID_VPD);
int length = eeprom->len;
u16 offset = eeprom->offset;
if (!cap)
return -EINVAL;
eeprom->magic = SKGE_EEPROM_MAGIC;
while (length > 0) {
u32 val = skge_vpd_read(pdev, cap, offset);
int n = min_t(int, length, sizeof(val));
memcpy(data, &val, n);
length -= n;
data += n;
offset += n;
}
return 0;
}
static int skge_set_eeprom(struct net_device *dev, struct ethtool_eeprom *eeprom,
u8 *data)
{
struct skge_port *skge = netdev_priv(dev);
struct pci_dev *pdev = skge->hw->pdev;
int cap = pci_find_capability(pdev, PCI_CAP_ID_VPD);
int length = eeprom->len;
u16 offset = eeprom->offset;
if (!cap)
return -EINVAL;
if (eeprom->magic != SKGE_EEPROM_MAGIC)
return -EINVAL;
while (length > 0) {
u32 val;
int n = min_t(int, length, sizeof(val));
if (n < sizeof(val))
val = skge_vpd_read(pdev, cap, offset);
memcpy(&val, data, n);
skge_vpd_write(pdev, cap, offset, val);
length -= n;
data += n;
offset += n;
}
return 0;
}
static const struct ethtool_ops skge_ethtool_ops = {
.get_settings = skge_get_settings,
.set_settings = skge_set_settings,
.get_drvinfo = skge_get_drvinfo,
.get_regs_len = skge_get_regs_len,
.get_regs = skge_get_regs,
.get_wol = skge_get_wol,
.set_wol = skge_set_wol,
.get_msglevel = skge_get_msglevel,
.set_msglevel = skge_set_msglevel,
.nway_reset = skge_nway_reset,
.get_link = ethtool_op_get_link,
.get_eeprom_len = skge_get_eeprom_len,
.get_eeprom = skge_get_eeprom,
.set_eeprom = skge_set_eeprom,
.get_ringparam = skge_get_ring_param,
.set_ringparam = skge_set_ring_param,
.get_pauseparam = skge_get_pauseparam,
.set_pauseparam = skge_set_pauseparam,
.get_coalesce = skge_get_coalesce,
.set_coalesce = skge_set_coalesce,
.get_strings = skge_get_strings,
.set_phys_id = skge_set_phys_id,
.get_sset_count = skge_get_sset_count,
.get_ethtool_stats = skge_get_ethtool_stats,
};
/*
* Allocate ring elements and chain them together
* One-to-one association of board descriptors with ring elements
*/
static int skge_ring_alloc(struct skge_ring *ring, void *vaddr, u32 base)
{
struct skge_tx_desc *d;
struct skge_element *e;
int i;
ring->start = kcalloc(ring->count, sizeof(*e), GFP_KERNEL);
if (!ring->start)
return -ENOMEM;
for (i = 0, e = ring->start, d = vaddr; i < ring->count; i++, e++, d++) {
e->desc = d;
if (i == ring->count - 1) {
e->next = ring->start;
d->next_offset = base;
} else {
e->next = e + 1;
d->next_offset = base + (i+1) * sizeof(*d);
}
}
ring->to_use = ring->to_clean = ring->start;
return 0;
}
/* Allocate and setup a new buffer for receiving */
static void skge_rx_setup(struct skge_port *skge, struct skge_element *e,
struct sk_buff *skb, unsigned int bufsize)
{
struct skge_rx_desc *rd = e->desc;
u64 map;
map = pci_map_single(skge->hw->pdev, skb->data, bufsize,
PCI_DMA_FROMDEVICE);
rd->dma_lo = map;
rd->dma_hi = map >> 32;
e->skb = skb;
rd->csum1_start = ETH_HLEN;
rd->csum2_start = ETH_HLEN;
rd->csum1 = 0;
rd->csum2 = 0;
wmb();
rd->control = BMU_OWN | BMU_STF | BMU_IRQ_EOF | BMU_TCP_CHECK | bufsize;
dma_unmap_addr_set(e, mapaddr, map);
dma_unmap_len_set(e, maplen, bufsize);
}
/* Resume receiving using existing skb,
* Note: DMA address is not changed by chip.
* MTU not changed while receiver active.
*/
static inline void skge_rx_reuse(struct skge_element *e, unsigned int size)
{
struct skge_rx_desc *rd = e->desc;
rd->csum2 = 0;
rd->csum2_start = ETH_HLEN;
wmb();
rd->control = BMU_OWN | BMU_STF | BMU_IRQ_EOF | BMU_TCP_CHECK | size;
}
/* Free all buffers in receive ring, assumes receiver stopped */
static void skge_rx_clean(struct skge_port *skge)
{
struct skge_hw *hw = skge->hw;
struct skge_ring *ring = &skge->rx_ring;
struct skge_element *e;
e = ring->start;
do {
struct skge_rx_desc *rd = e->desc;
rd->control = 0;
if (e->skb) {
pci_unmap_single(hw->pdev,
dma_unmap_addr(e, mapaddr),
dma_unmap_len(e, maplen),
PCI_DMA_FROMDEVICE);
dev_kfree_skb(e->skb);
e->skb = NULL;
}
} while ((e = e->next) != ring->start);
}
/* Allocate buffers for receive ring
* For receive: to_clean is next received frame.
*/
static int skge_rx_fill(struct net_device *dev)
{
struct skge_port *skge = netdev_priv(dev);
struct skge_ring *ring = &skge->rx_ring;
struct skge_element *e;
e = ring->start;
do {
struct sk_buff *skb;
skb = __netdev_alloc_skb(dev, skge->rx_buf_size + NET_IP_ALIGN,
GFP_KERNEL);
if (!skb)
return -ENOMEM;
skb_reserve(skb, NET_IP_ALIGN);
skge_rx_setup(skge, e, skb, skge->rx_buf_size);
} while ((e = e->next) != ring->start);
ring->to_clean = ring->start;
return 0;
}
static const char *skge_pause(enum pause_status status)
{
switch (status) {
case FLOW_STAT_NONE:
return "none";
case FLOW_STAT_REM_SEND:
return "rx only";
case FLOW_STAT_LOC_SEND:
return "tx_only";
case FLOW_STAT_SYMMETRIC: /* Both station may send PAUSE */
return "both";
default:
return "indeterminated";
}
}
static void skge_link_up(struct skge_port *skge)
{
skge_write8(skge->hw, SK_REG(skge->port, LNK_LED_REG),
LED_BLK_OFF|LED_SYNC_OFF|LED_ON);
netif_carrier_on(skge->netdev);
netif_wake_queue(skge->netdev);
netif_info(skge, link, skge->netdev,
"Link is up at %d Mbps, %s duplex, flow control %s\n",
skge->speed,
skge->duplex == DUPLEX_FULL ? "full" : "half",
skge_pause(skge->flow_status));
}
static void skge_link_down(struct skge_port *skge)
{
skge_write8(skge->hw, SK_REG(skge->port, LNK_LED_REG), LED_OFF);
netif_carrier_off(skge->netdev);
netif_stop_queue(skge->netdev);
netif_info(skge, link, skge->netdev, "Link is down\n");
}
static void xm_link_down(struct skge_hw *hw, int port)
{
struct net_device *dev = hw->dev[port];
struct skge_port *skge = netdev_priv(dev);
xm_write16(hw, port, XM_IMSK, XM_IMSK_DISABLE);
if (netif_carrier_ok(dev))
skge_link_down(skge);
}
static int __xm_phy_read(struct skge_hw *hw, int port, u16 reg, u16 *val)
{
int i;
xm_write16(hw, port, XM_PHY_ADDR, reg | hw->phy_addr);
*val = xm_read16(hw, port, XM_PHY_DATA);
if (hw->phy_type == SK_PHY_XMAC)
goto ready;
for (i = 0; i < PHY_RETRIES; i++) {
if (xm_read16(hw, port, XM_MMU_CMD) & XM_MMU_PHY_RDY)
goto ready;
udelay(1);
}
return -ETIMEDOUT;
ready:
*val = xm_read16(hw, port, XM_PHY_DATA);
return 0;
}
static u16 xm_phy_read(struct skge_hw *hw, int port, u16 reg)
{
u16 v = 0;
if (__xm_phy_read(hw, port, reg, &v))
pr_warning("%s: phy read timed out\n", hw->dev[port]->name);
return v;
}
static int xm_phy_write(struct skge_hw *hw, int port, u16 reg, u16 val)
{
int i;
xm_write16(hw, port, XM_PHY_ADDR, reg | hw->phy_addr);
for (i = 0; i < PHY_RETRIES; i++) {
if (!(xm_read16(hw, port, XM_MMU_CMD) & XM_MMU_PHY_BUSY))
goto ready;
udelay(1);
}
return -EIO;
ready:
xm_write16(hw, port, XM_PHY_DATA, val);
for (i = 0; i < PHY_RETRIES; i++) {
if (!(xm_read16(hw, port, XM_MMU_CMD) & XM_MMU_PHY_BUSY))
return 0;
udelay(1);
}
return -ETIMEDOUT;
}
static void genesis_init(struct skge_hw *hw)
{
/* set blink source counter */
skge_write32(hw, B2_BSC_INI, (SK_BLK_DUR * SK_FACT_53) / 100);
skge_write8(hw, B2_BSC_CTRL, BSC_START);
/* configure mac arbiter */
skge_write16(hw, B3_MA_TO_CTRL, MA_RST_CLR);
/* configure mac arbiter timeout values */
skge_write8(hw, B3_MA_TOINI_RX1, SK_MAC_TO_53);
skge_write8(hw, B3_MA_TOINI_RX2, SK_MAC_TO_53);
skge_write8(hw, B3_MA_TOINI_TX1, SK_MAC_TO_53);
skge_write8(hw, B3_MA_TOINI_TX2, SK_MAC_TO_53);
skge_write8(hw, B3_MA_RCINI_RX1, 0);
skge_write8(hw, B3_MA_RCINI_RX2, 0);
skge_write8(hw, B3_MA_RCINI_TX1, 0);
skge_write8(hw, B3_MA_RCINI_TX2, 0);
/* configure packet arbiter timeout */
skge_write16(hw, B3_PA_CTRL, PA_RST_CLR);
skge_write16(hw, B3_PA_TOINI_RX1, SK_PKT_TO_MAX);
skge_write16(hw, B3_PA_TOINI_TX1, SK_PKT_TO_MAX);
skge_write16(hw, B3_PA_TOINI_RX2, SK_PKT_TO_MAX);
skge_write16(hw, B3_PA_TOINI_TX2, SK_PKT_TO_MAX);
}
static void genesis_reset(struct skge_hw *hw, int port)
{
static const u8 zero[8] = { 0 };
u32 reg;
skge_write8(hw, SK_REG(port, GMAC_IRQ_MSK), 0);
/* reset the statistics module */
xm_write32(hw, port, XM_GP_PORT, XM_GP_RES_STAT);
xm_write16(hw, port, XM_IMSK, XM_IMSK_DISABLE);
xm_write32(hw, port, XM_MODE, 0); /* clear Mode Reg */
xm_write16(hw, port, XM_TX_CMD, 0); /* reset TX CMD Reg */
xm_write16(hw, port, XM_RX_CMD, 0); /* reset RX CMD Reg */
/* disable Broadcom PHY IRQ */
if (hw->phy_type == SK_PHY_BCOM)
xm_write16(hw, port, PHY_BCOM_INT_MASK, 0xffff);
xm_outhash(hw, port, XM_HSM, zero);
/* Flush TX and RX fifo */
reg = xm_read32(hw, port, XM_MODE);
xm_write32(hw, port, XM_MODE, reg | XM_MD_FTF);
xm_write32(hw, port, XM_MODE, reg | XM_MD_FRF);
}
/* Convert mode to MII values */
static const u16 phy_pause_map[] = {
[FLOW_MODE_NONE] = 0,
[FLOW_MODE_LOC_SEND] = PHY_AN_PAUSE_ASYM,
[FLOW_MODE_SYMMETRIC] = PHY_AN_PAUSE_CAP,
[FLOW_MODE_SYM_OR_REM] = PHY_AN_PAUSE_CAP | PHY_AN_PAUSE_ASYM,
};
/* special defines for FIBER (88E1011S only) */
static const u16 fiber_pause_map[] = {
[FLOW_MODE_NONE] = PHY_X_P_NO_PAUSE,
[FLOW_MODE_LOC_SEND] = PHY_X_P_ASYM_MD,
[FLOW_MODE_SYMMETRIC] = PHY_X_P_SYM_MD,
[FLOW_MODE_SYM_OR_REM] = PHY_X_P_BOTH_MD,
};
/* Check status of Broadcom phy link */
static void bcom_check_link(struct skge_hw *hw, int port)
{
struct net_device *dev = hw->dev[port];
struct skge_port *skge = netdev_priv(dev);
u16 status;
/* read twice because of latch */
xm_phy_read(hw, port, PHY_BCOM_STAT);
status = xm_phy_read(hw, port, PHY_BCOM_STAT);
if ((status & PHY_ST_LSYNC) == 0) {
xm_link_down(hw, port);
return;
}
if (skge->autoneg == AUTONEG_ENABLE) {
u16 lpa, aux;
if (!(status & PHY_ST_AN_OVER))
return;
lpa = xm_phy_read(hw, port, PHY_XMAC_AUNE_LP);
if (lpa & PHY_B_AN_RF) {
netdev_notice(dev, "remote fault\n");
return;
}
aux = xm_phy_read(hw, port, PHY_BCOM_AUX_STAT);
/* Check Duplex mismatch */
switch (aux & PHY_B_AS_AN_RES_MSK) {
case PHY_B_RES_1000FD:
skge->duplex = DUPLEX_FULL;
break;
case PHY_B_RES_1000HD:
skge->duplex = DUPLEX_HALF;
break;
default:
netdev_notice(dev, "duplex mismatch\n");
return;
}
/* We are using IEEE 802.3z/D5.0 Table 37-4 */
switch (aux & PHY_B_AS_PAUSE_MSK) {
case PHY_B_AS_PAUSE_MSK:
skge->flow_status = FLOW_STAT_SYMMETRIC;
break;
case PHY_B_AS_PRR:
skge->flow_status = FLOW_STAT_REM_SEND;
break;
case PHY_B_AS_PRT:
skge->flow_status = FLOW_STAT_LOC_SEND;
break;
default:
skge->flow_status = FLOW_STAT_NONE;
}
skge->speed = SPEED_1000;
}
if (!netif_carrier_ok(dev))
genesis_link_up(skge);
}
/* Broadcom 5400 only supports giagabit! SysKonnect did not put an additional
* Phy on for 100 or 10Mbit operation
*/
static void bcom_phy_init(struct skge_port *skge)
{
struct skge_hw *hw = skge->hw;
int port = skge->port;
int i;
u16 id1, r, ext, ctl;
/* magic workaround patterns for Broadcom */
static const struct {
u16 reg;
u16 val;
} A1hack[] = {
{ 0x18, 0x0c20 }, { 0x17, 0x0012 }, { 0x15, 0x1104 },
{ 0x17, 0x0013 }, { 0x15, 0x0404 }, { 0x17, 0x8006 },
{ 0x15, 0x0132 }, { 0x17, 0x8006 }, { 0x15, 0x0232 },
{ 0x17, 0x800D }, { 0x15, 0x000F }, { 0x18, 0x0420 },
}, C0hack[] = {
{ 0x18, 0x0c20 }, { 0x17, 0x0012 }, { 0x15, 0x1204 },
{ 0x17, 0x0013 }, { 0x15, 0x0A04 }, { 0x18, 0x0420 },
};
/* read Id from external PHY (all have the same address) */
id1 = xm_phy_read(hw, port, PHY_XMAC_ID1);
/* Optimize MDIO transfer by suppressing preamble. */
r = xm_read16(hw, port, XM_MMU_CMD);
r |= XM_MMU_NO_PRE;
xm_write16(hw, port, XM_MMU_CMD, r);
switch (id1) {
case PHY_BCOM_ID1_C0:
/*
* Workaround BCOM Errata for the C0 type.
* Write magic patterns to reserved registers.
*/
for (i = 0; i < ARRAY_SIZE(C0hack); i++)
xm_phy_write(hw, port,
C0hack[i].reg, C0hack[i].val);
break;
case PHY_BCOM_ID1_A1:
/*
* Workaround BCOM Errata for the A1 type.
* Write magic patterns to reserved registers.
*/
for (i = 0; i < ARRAY_SIZE(A1hack); i++)
xm_phy_write(hw, port,
A1hack[i].reg, A1hack[i].val);
break;
}
/*
* Workaround BCOM Errata (#10523) for all BCom PHYs.
* Disable Power Management after reset.
*/
r = xm_phy_read(hw, port, PHY_BCOM_AUX_CTRL);
r |= PHY_B_AC_DIS_PM;
xm_phy_write(hw, port, PHY_BCOM_AUX_CTRL, r);
/* Dummy read */
xm_read16(hw, port, XM_ISRC);
ext = PHY_B_PEC_EN_LTR; /* enable tx led */
ctl = PHY_CT_SP1000; /* always 1000mbit */
if (skge->autoneg == AUTONEG_ENABLE) {
/*
* Workaround BCOM Errata #1 for the C5 type.
* 1000Base-T Link Acquisition Failure in Slave Mode
* Set Repeater/DTE bit 10 of the 1000Base-T Control Register
*/
u16 adv = PHY_B_1000C_RD;
if (skge->advertising & ADVERTISED_1000baseT_Half)
adv |= PHY_B_1000C_AHD;
if (skge->advertising & ADVERTISED_1000baseT_Full)
adv |= PHY_B_1000C_AFD;
xm_phy_write(hw, port, PHY_BCOM_1000T_CTRL, adv);
ctl |= PHY_CT_ANE | PHY_CT_RE_CFG;
} else {
if (skge->duplex == DUPLEX_FULL)
ctl |= PHY_CT_DUP_MD;
/* Force to slave */
xm_phy_write(hw, port, PHY_BCOM_1000T_CTRL, PHY_B_1000C_MSE);
}
/* Set autonegotiation pause parameters */
xm_phy_write(hw, port, PHY_BCOM_AUNE_ADV,
phy_pause_map[skge->flow_control] | PHY_AN_CSMA);
/* Handle Jumbo frames */
if (hw->dev[port]->mtu > ETH_DATA_LEN) {
xm_phy_write(hw, port, PHY_BCOM_AUX_CTRL,
PHY_B_AC_TX_TST | PHY_B_AC_LONG_PACK);
ext |= PHY_B_PEC_HIGH_LA;
}
xm_phy_write(hw, port, PHY_BCOM_P_EXT_CTRL, ext);
xm_phy_write(hw, port, PHY_BCOM_CTRL, ctl);
/* Use link status change interrupt */
xm_phy_write(hw, port, PHY_BCOM_INT_MASK, PHY_B_DEF_MSK);
}
static void xm_phy_init(struct skge_port *skge)
{
struct skge_hw *hw = skge->hw;
int port = skge->port;
u16 ctrl = 0;
if (skge->autoneg == AUTONEG_ENABLE) {
if (skge->advertising & ADVERTISED_1000baseT_Half)
ctrl |= PHY_X_AN_HD;
if (skge->advertising & ADVERTISED_1000baseT_Full)
ctrl |= PHY_X_AN_FD;
ctrl |= fiber_pause_map[skge->flow_control];
xm_phy_write(hw, port, PHY_XMAC_AUNE_ADV, ctrl);
/* Restart Auto-negotiation */
ctrl = PHY_CT_ANE | PHY_CT_RE_CFG;
} else {
/* Set DuplexMode in Config register */
if (skge->duplex == DUPLEX_FULL)
ctrl |= PHY_CT_DUP_MD;
/*
* Do NOT enable Auto-negotiation here. This would hold
* the link down because no IDLEs are transmitted
*/
}
xm_phy_write(hw, port, PHY_XMAC_CTRL, ctrl);
/* Poll PHY for status changes */
mod_timer(&skge->link_timer, jiffies + LINK_HZ);
}
static int xm_check_link(struct net_device *dev)
{
struct skge_port *skge = netdev_priv(dev);
struct skge_hw *hw = skge->hw;
int port = skge->port;
u16 status;
/* read twice because of latch */
xm_phy_read(hw, port, PHY_XMAC_STAT);
status = xm_phy_read(hw, port, PHY_XMAC_STAT);
if ((status & PHY_ST_LSYNC) == 0) {
xm_link_down(hw, port);
return 0;
}
if (skge->autoneg == AUTONEG_ENABLE) {
u16 lpa, res;
if (!(status & PHY_ST_AN_OVER))
return 0;
lpa = xm_phy_read(hw, port, PHY_XMAC_AUNE_LP);
if (lpa & PHY_B_AN_RF) {
netdev_notice(dev, "remote fault\n");
return 0;
}
res = xm_phy_read(hw, port, PHY_XMAC_RES_ABI);
/* Check Duplex mismatch */
switch (res & (PHY_X_RS_HD | PHY_X_RS_FD)) {
case PHY_X_RS_FD:
skge->duplex = DUPLEX_FULL;
break;
case PHY_X_RS_HD:
skge->duplex = DUPLEX_HALF;
break;
default:
netdev_notice(dev, "duplex mismatch\n");
return 0;
}
/* We are using IEEE 802.3z/D5.0 Table 37-4 */
if ((skge->flow_control == FLOW_MODE_SYMMETRIC ||
skge->flow_control == FLOW_MODE_SYM_OR_REM) &&
(lpa & PHY_X_P_SYM_MD))
skge->flow_status = FLOW_STAT_SYMMETRIC;
else if (skge->flow_control == FLOW_MODE_SYM_OR_REM &&
(lpa & PHY_X_RS_PAUSE) == PHY_X_P_ASYM_MD)
/* Enable PAUSE receive, disable PAUSE transmit */
skge->flow_status = FLOW_STAT_REM_SEND;
else if (skge->flow_control == FLOW_MODE_LOC_SEND &&
(lpa & PHY_X_RS_PAUSE) == PHY_X_P_BOTH_MD)
/* Disable PAUSE receive, enable PAUSE transmit */
skge->flow_status = FLOW_STAT_LOC_SEND;
else
skge->flow_status = FLOW_STAT_NONE;
skge->speed = SPEED_1000;
}
if (!netif_carrier_ok(dev))
genesis_link_up(skge);
return 1;
}
/* Poll to check for link coming up.
*
* Since internal PHY is wired to a level triggered pin, can't
* get an interrupt when carrier is detected, need to poll for
* link coming up.
*/
static void xm_link_timer(unsigned long arg)
{
struct skge_port *skge = (struct skge_port *) arg;
struct net_device *dev = skge->netdev;
struct skge_hw *hw = skge->hw;
int port = skge->port;
int i;
unsigned long flags;
if (!netif_running(dev))
return;
spin_lock_irqsave(&hw->phy_lock, flags);
/*
* Verify that the link by checking GPIO register three times.
* This pin has the signal from the link_sync pin connected to it.
*/
for (i = 0; i < 3; i++) {
if (xm_read16(hw, port, XM_GP_PORT) & XM_GP_INP_ASS)
goto link_down;
}
/* Re-enable interrupt to detect link down */
if (xm_check_link(dev)) {
u16 msk = xm_read16(hw, port, XM_IMSK);
msk &= ~XM_IS_INP_ASS;
xm_write16(hw, port, XM_IMSK, msk);
xm_read16(hw, port, XM_ISRC);
} else {
link_down:
mod_timer(&skge->link_timer,
round_jiffies(jiffies + LINK_HZ));
}
spin_unlock_irqrestore(&hw->phy_lock, flags);
}
static void genesis_mac_init(struct skge_hw *hw, int port)
{
struct net_device *dev = hw->dev[port];
struct skge_port *skge = netdev_priv(dev);
int jumbo = hw->dev[port]->mtu > ETH_DATA_LEN;
int i;
u32 r;
static const u8 zero[6] = { 0 };
for (i = 0; i < 10; i++) {
skge_write16(hw, SK_REG(port, TX_MFF_CTRL1),
MFF_SET_MAC_RST);
if (skge_read16(hw, SK_REG(port, TX_MFF_CTRL1)) & MFF_SET_MAC_RST)
goto reset_ok;
udelay(1);
}
netdev_warn(dev, "genesis reset failed\n");
reset_ok:
/* Unreset the XMAC. */
skge_write16(hw, SK_REG(port, TX_MFF_CTRL1), MFF_CLR_MAC_RST);
/*
* Perform additional initialization for external PHYs,
* namely for the 1000baseTX cards that use the XMAC's
* GMII mode.
*/
if (hw->phy_type != SK_PHY_XMAC) {
/* Take external Phy out of reset */
r = skge_read32(hw, B2_GP_IO);
if (port == 0)
r |= GP_DIR_0|GP_IO_0;
else
r |= GP_DIR_2|GP_IO_2;
skge_write32(hw, B2_GP_IO, r);
/* Enable GMII interface */
xm_write16(hw, port, XM_HW_CFG, XM_HW_GMII_MD);
}
switch (hw->phy_type) {
case SK_PHY_XMAC:
xm_phy_init(skge);
break;
case SK_PHY_BCOM:
bcom_phy_init(skge);
bcom_check_link(hw, port);
}
/* Set Station Address */
xm_outaddr(hw, port, XM_SA, dev->dev_addr);
/* We don't use match addresses so clear */
for (i = 1; i < 16; i++)
xm_outaddr(hw, port, XM_EXM(i), zero);
/* Clear MIB counters */
xm_write16(hw, port, XM_STAT_CMD,
XM_SC_CLR_RXC | XM_SC_CLR_TXC);
/* Clear two times according to Errata #3 */
xm_write16(hw, port, XM_STAT_CMD,
XM_SC_CLR_RXC | XM_SC_CLR_TXC);
/* configure Rx High Water Mark (XM_RX_HI_WM) */
xm_write16(hw, port, XM_RX_HI_WM, 1450);
/* We don't need the FCS appended to the packet. */
r = XM_RX_LENERR_OK | XM_RX_STRIP_FCS;
if (jumbo)
r |= XM_RX_BIG_PK_OK;
if (skge->duplex == DUPLEX_HALF) {
/*
* If in manual half duplex mode the other side might be in
* full duplex mode, so ignore if a carrier extension is not seen
* on frames received
*/
r |= XM_RX_DIS_CEXT;
}
xm_write16(hw, port, XM_RX_CMD, r);
/* We want short frames padded to 60 bytes. */
xm_write16(hw, port, XM_TX_CMD, XM_TX_AUTO_PAD);
/* Increase threshold for jumbo frames on dual port */
if (hw->ports > 1 && jumbo)
xm_write16(hw, port, XM_TX_THR, 1020);
else
xm_write16(hw, port, XM_TX_THR, 512);
/*
* Enable the reception of all error frames. This is is
* a necessary evil due to the design of the XMAC. The
* XMAC's receive FIFO is only 8K in size, however jumbo
* frames can be up to 9000 bytes in length. When bad
* frame filtering is enabled, the XMAC's RX FIFO operates
* in 'store and forward' mode. For this to work, the
* entire frame has to fit into the FIFO, but that means
* that jumbo frames larger than 8192 bytes will be
* truncated. Disabling all bad frame filtering causes
* the RX FIFO to operate in streaming mode, in which
* case the XMAC will start transferring frames out of the
* RX FIFO as soon as the FIFO threshold is reached.
*/
xm_write32(hw, port, XM_MODE, XM_DEF_MODE);
/*
* Initialize the Receive Counter Event Mask (XM_RX_EV_MSK)
* - Enable all bits excepting 'Octets Rx OK Low CntOv'
* and 'Octets Rx OK Hi Cnt Ov'.
*/
xm_write32(hw, port, XM_RX_EV_MSK, XMR_DEF_MSK);
/*
* Initialize the Transmit Counter Event Mask (XM_TX_EV_MSK)
* - Enable all bits excepting 'Octets Tx OK Low CntOv'
* and 'Octets Tx OK Hi Cnt Ov'.
*/
xm_write32(hw, port, XM_TX_EV_MSK, XMT_DEF_MSK);
/* Configure MAC arbiter */
skge_write16(hw, B3_MA_TO_CTRL, MA_RST_CLR);
/* configure timeout values */
skge_write8(hw, B3_MA_TOINI_RX1, 72);
skge_write8(hw, B3_MA_TOINI_RX2, 72);
skge_write8(hw, B3_MA_TOINI_TX1, 72);
skge_write8(hw, B3_MA_TOINI_TX2, 72);
skge_write8(hw, B3_MA_RCINI_RX1, 0);
skge_write8(hw, B3_MA_RCINI_RX2, 0);
skge_write8(hw, B3_MA_RCINI_TX1, 0);
skge_write8(hw, B3_MA_RCINI_TX2, 0);
/* Configure Rx MAC FIFO */
skge_write8(hw, SK_REG(port, RX_MFF_CTRL2), MFF_RST_CLR);
skge_write16(hw, SK_REG(port, RX_MFF_CTRL1), MFF_ENA_TIM_PAT);
skge_write8(hw, SK_REG(port, RX_MFF_CTRL2), MFF_ENA_OP_MD);
/* Configure Tx MAC FIFO */
skge_write8(hw, SK_REG(port, TX_MFF_CTRL2), MFF_RST_CLR);
skge_write16(hw, SK_REG(port, TX_MFF_CTRL1), MFF_TX_CTRL_DEF);
skge_write8(hw, SK_REG(port, TX_MFF_CTRL2), MFF_ENA_OP_MD);
if (jumbo) {
/* Enable frame flushing if jumbo frames used */
skge_write16(hw, SK_REG(port, RX_MFF_CTRL1), MFF_ENA_FLUSH);
} else {
/* enable timeout timers if normal frames */
skge_write16(hw, B3_PA_CTRL,
(port == 0) ? PA_ENA_TO_TX1 : PA_ENA_TO_TX2);
}
}
static void genesis_stop(struct skge_port *skge)
{
struct skge_hw *hw = skge->hw;
int port = skge->port;
unsigned retries = 1000;
u16 cmd;
/* Disable Tx and Rx */
cmd = xm_read16(hw, port, XM_MMU_CMD);
cmd &= ~(XM_MMU_ENA_RX | XM_MMU_ENA_TX);
xm_write16(hw, port, XM_MMU_CMD, cmd);
genesis_reset(hw, port);
/* Clear Tx packet arbiter timeout IRQ */
skge_write16(hw, B3_PA_CTRL,
port == 0 ? PA_CLR_TO_TX1 : PA_CLR_TO_TX2);
/* Reset the MAC */
skge_write16(hw, SK_REG(port, TX_MFF_CTRL1), MFF_CLR_MAC_RST);
do {
skge_write16(hw, SK_REG(port, TX_MFF_CTRL1), MFF_SET_MAC_RST);
if (!(skge_read16(hw, SK_REG(port, TX_MFF_CTRL1)) & MFF_SET_MAC_RST))
break;
} while (--retries > 0);
/* For external PHYs there must be special handling */
if (hw->phy_type != SK_PHY_XMAC) {
u32 reg = skge_read32(hw, B2_GP_IO);
if (port == 0) {
reg |= GP_DIR_0;
reg &= ~GP_IO_0;
} else {
reg |= GP_DIR_2;
reg &= ~GP_IO_2;
}
skge_write32(hw, B2_GP_IO, reg);
skge_read32(hw, B2_GP_IO);
}
xm_write16(hw, port, XM_MMU_CMD,
xm_read16(hw, port, XM_MMU_CMD)
& ~(XM_MMU_ENA_RX | XM_MMU_ENA_TX));
xm_read16(hw, port, XM_MMU_CMD);
}
static void genesis_get_stats(struct skge_port *skge, u64 *data)
{
struct skge_hw *hw = skge->hw;
int port = skge->port;
int i;
unsigned long timeout = jiffies + HZ;
xm_write16(hw, port,
XM_STAT_CMD, XM_SC_SNP_TXC | XM_SC_SNP_RXC);
/* wait for update to complete */
while (xm_read16(hw, port, XM_STAT_CMD)
& (XM_SC_SNP_TXC | XM_SC_SNP_RXC)) {
if (time_after(jiffies, timeout))
break;
udelay(10);
}
/* special case for 64 bit octet counter */
data[0] = (u64) xm_read32(hw, port, XM_TXO_OK_HI) << 32
| xm_read32(hw, port, XM_TXO_OK_LO);
data[1] = (u64) xm_read32(hw, port, XM_RXO_OK_HI) << 32
| xm_read32(hw, port, XM_RXO_OK_LO);
for (i = 2; i < ARRAY_SIZE(skge_stats); i++)
data[i] = xm_read32(hw, port, skge_stats[i].xmac_offset);
}
static void genesis_mac_intr(struct skge_hw *hw, int port)
{
struct net_device *dev = hw->dev[port];
struct skge_port *skge = netdev_priv(dev);
u16 status = xm_read16(hw, port, XM_ISRC);
netif_printk(skge, intr, KERN_DEBUG, skge->netdev,
"mac interrupt status 0x%x\n", status);
if (hw->phy_type == SK_PHY_XMAC && (status & XM_IS_INP_ASS)) {
xm_link_down(hw, port);
mod_timer(&skge->link_timer, jiffies + 1);
}
if (status & XM_IS_TXF_UR) {
xm_write32(hw, port, XM_MODE, XM_MD_FTF);
++dev->stats.tx_fifo_errors;
}
}
static void genesis_link_up(struct skge_port *skge)
{
struct skge_hw *hw = skge->hw;
int port = skge->port;
u16 cmd, msk;
u32 mode;
cmd = xm_read16(hw, port, XM_MMU_CMD);
/*
* enabling pause frame reception is required for 1000BT
* because the XMAC is not reset if the link is going down
*/
if (skge->flow_status == FLOW_STAT_NONE ||
skge->flow_status == FLOW_STAT_LOC_SEND)
/* Disable Pause Frame Reception */
cmd |= XM_MMU_IGN_PF;
else
/* Enable Pause Frame Reception */
cmd &= ~XM_MMU_IGN_PF;
xm_write16(hw, port, XM_MMU_CMD, cmd);
mode = xm_read32(hw, port, XM_MODE);
if (skge->flow_status == FLOW_STAT_SYMMETRIC ||
skge->flow_status == FLOW_STAT_LOC_SEND) {
/*
* Configure Pause Frame Generation
* Use internal and external Pause Frame Generation.
* Sending pause frames is edge triggered.
* Send a Pause frame with the maximum pause time if
* internal oder external FIFO full condition occurs.
* Send a zero pause time frame to re-start transmission.
*/
/* XM_PAUSE_DA = '010000C28001' (default) */
/* XM_MAC_PTIME = 0xffff (maximum) */
/* remember this value is defined in big endian (!) */
xm_write16(hw, port, XM_MAC_PTIME, 0xffff);
mode |= XM_PAUSE_MODE;
skge_write16(hw, SK_REG(port, RX_MFF_CTRL1), MFF_ENA_PAUSE);
} else {
/*
* disable pause frame generation is required for 1000BT
* because the XMAC is not reset if the link is going down
*/
/* Disable Pause Mode in Mode Register */
mode &= ~XM_PAUSE_MODE;
skge_write16(hw, SK_REG(port, RX_MFF_CTRL1), MFF_DIS_PAUSE);
}
xm_write32(hw, port, XM_MODE, mode);
/* Turn on detection of Tx underrun */
msk = xm_read16(hw, port, XM_IMSK);
msk &= ~XM_IS_TXF_UR;
xm_write16(hw, port, XM_IMSK, msk);
xm_read16(hw, port, XM_ISRC);
/* get MMU Command Reg. */
cmd = xm_read16(hw, port, XM_MMU_CMD);
if (hw->phy_type != SK_PHY_XMAC && skge->duplex == DUPLEX_FULL)
cmd |= XM_MMU_GMII_FD;
/*
* Workaround BCOM Errata (#10523) for all BCom Phys
* Enable Power Management after link up
*/
if (hw->phy_type == SK_PHY_BCOM) {
xm_phy_write(hw, port, PHY_BCOM_AUX_CTRL,
xm_phy_read(hw, port, PHY_BCOM_AUX_CTRL)
& ~PHY_B_AC_DIS_PM);
xm_phy_write(hw, port, PHY_BCOM_INT_MASK, PHY_B_DEF_MSK);
}
/* enable Rx/Tx */
xm_write16(hw, port, XM_MMU_CMD,
cmd | XM_MMU_ENA_RX | XM_MMU_ENA_TX);
skge_link_up(skge);
}
static inline void bcom_phy_intr(struct skge_port *skge)
{
struct skge_hw *hw = skge->hw;
int port = skge->port;
u16 isrc;
isrc = xm_phy_read(hw, port, PHY_BCOM_INT_STAT);
netif_printk(skge, intr, KERN_DEBUG, skge->netdev,
"phy interrupt status 0x%x\n", isrc);
if (isrc & PHY_B_IS_PSE)
pr_err("%s: uncorrectable pair swap error\n",
hw->dev[port]->name);
/* Workaround BCom Errata:
* enable and disable loopback mode if "NO HCD" occurs.
*/
if (isrc & PHY_B_IS_NO_HDCL) {
u16 ctrl = xm_phy_read(hw, port, PHY_BCOM_CTRL);
xm_phy_write(hw, port, PHY_BCOM_CTRL,
ctrl | PHY_CT_LOOP);
xm_phy_write(hw, port, PHY_BCOM_CTRL,
ctrl & ~PHY_CT_LOOP);
}
if (isrc & (PHY_B_IS_AN_PR | PHY_B_IS_LST_CHANGE))
bcom_check_link(hw, port);
}
static int gm_phy_write(struct skge_hw *hw, int port, u16 reg, u16 val)
{
int i;
gma_write16(hw, port, GM_SMI_DATA, val);
gma_write16(hw, port, GM_SMI_CTRL,
GM_SMI_CT_PHY_AD(hw->phy_addr) | GM_SMI_CT_REG_AD(reg));
for (i = 0; i < PHY_RETRIES; i++) {
udelay(1);
if (!(gma_read16(hw, port, GM_SMI_CTRL) & GM_SMI_CT_BUSY))
return 0;
}
pr_warning("%s: phy write timeout\n", hw->dev[port]->name);
return -EIO;
}
static int __gm_phy_read(struct skge_hw *hw, int port, u16 reg, u16 *val)
{
int i;
gma_write16(hw, port, GM_SMI_CTRL,
GM_SMI_CT_PHY_AD(hw->phy_addr)
| GM_SMI_CT_REG_AD(reg) | GM_SMI_CT_OP_RD);
for (i = 0; i < PHY_RETRIES; i++) {
udelay(1);
if (gma_read16(hw, port, GM_SMI_CTRL) & GM_SMI_CT_RD_VAL)
goto ready;
}
return -ETIMEDOUT;
ready:
*val = gma_read16(hw, port, GM_SMI_DATA);
return 0;
}
static u16 gm_phy_read(struct skge_hw *hw, int port, u16 reg)
{
u16 v = 0;
if (__gm_phy_read(hw, port, reg, &v))
pr_warning("%s: phy read timeout\n", hw->dev[port]->name);
return v;
}
/* Marvell Phy Initialization */
static void yukon_init(struct skge_hw *hw, int port)
{
struct skge_port *skge = netdev_priv(hw->dev[port]);
u16 ctrl, ct1000, adv;
if (skge->autoneg == AUTONEG_ENABLE) {
u16 ectrl = gm_phy_read(hw, port, PHY_MARV_EXT_CTRL);
ectrl &= ~(PHY_M_EC_M_DSC_MSK | PHY_M_EC_S_DSC_MSK |
PHY_M_EC_MAC_S_MSK);
ectrl |= PHY_M_EC_MAC_S(MAC_TX_CLK_25_MHZ);
ectrl |= PHY_M_EC_M_DSC(0) | PHY_M_EC_S_DSC(1);
gm_phy_write(hw, port, PHY_MARV_EXT_CTRL, ectrl);
}
ctrl = gm_phy_read(hw, port, PHY_MARV_CTRL);
if (skge->autoneg == AUTONEG_DISABLE)
ctrl &= ~PHY_CT_ANE;
ctrl |= PHY_CT_RESET;
gm_phy_write(hw, port, PHY_MARV_CTRL, ctrl);
ctrl = 0;
ct1000 = 0;
adv = PHY_AN_CSMA;
if (skge->autoneg == AUTONEG_ENABLE) {
if (hw->copper) {
if (skge->advertising & ADVERTISED_1000baseT_Full)
ct1000 |= PHY_M_1000C_AFD;
if (skge->advertising & ADVERTISED_1000baseT_Half)
ct1000 |= PHY_M_1000C_AHD;
if (skge->advertising & ADVERTISED_100baseT_Full)
adv |= PHY_M_AN_100_FD;
if (skge->advertising & ADVERTISED_100baseT_Half)
adv |= PHY_M_AN_100_HD;
if (skge->advertising & ADVERTISED_10baseT_Full)
adv |= PHY_M_AN_10_FD;
if (skge->advertising & ADVERTISED_10baseT_Half)
adv |= PHY_M_AN_10_HD;
/* Set Flow-control capabilities */
adv |= phy_pause_map[skge->flow_control];
} else {
if (skge->advertising & ADVERTISED_1000baseT_Full)
adv |= PHY_M_AN_1000X_AFD;
if (skge->advertising & ADVERTISED_1000baseT_Half)
adv |= PHY_M_AN_1000X_AHD;
adv |= fiber_pause_map[skge->flow_control];
}
/* Restart Auto-negotiation */
ctrl |= PHY_CT_ANE | PHY_CT_RE_CFG;
} else {
/* forced speed/duplex settings */
ct1000 = PHY_M_1000C_MSE;
if (skge->duplex == DUPLEX_FULL)
ctrl |= PHY_CT_DUP_MD;
switch (skge->speed) {
case SPEED_1000:
ctrl |= PHY_CT_SP1000;
break;
case SPEED_100:
ctrl |= PHY_CT_SP100;
break;
}
ctrl |= PHY_CT_RESET;
}
gm_phy_write(hw, port, PHY_MARV_1000T_CTRL, ct1000);
gm_phy_write(hw, port, PHY_MARV_AUNE_ADV, adv);
gm_phy_write(hw, port, PHY_MARV_CTRL, ctrl);
/* Enable phy interrupt on autonegotiation complete (or link up) */
if (skge->autoneg == AUTONEG_ENABLE)
gm_phy_write(hw, port, PHY_MARV_INT_MASK, PHY_M_IS_AN_MSK);
else
gm_phy_write(hw, port, PHY_MARV_INT_MASK, PHY_M_IS_DEF_MSK);
}
static void yukon_reset(struct skge_hw *hw, int port)
{
gm_phy_write(hw, port, PHY_MARV_INT_MASK, 0);/* disable PHY IRQs */
gma_write16(hw, port, GM_MC_ADDR_H1, 0); /* clear MC hash */
gma_write16(hw, port, GM_MC_ADDR_H2, 0);
gma_write16(hw, port, GM_MC_ADDR_H3, 0);
gma_write16(hw, port, GM_MC_ADDR_H4, 0);
gma_write16(hw, port, GM_RX_CTRL,
gma_read16(hw, port, GM_RX_CTRL)
| GM_RXCR_UCF_ENA | GM_RXCR_MCF_ENA);
}
/* Apparently, early versions of Yukon-Lite had wrong chip_id? */
static int is_yukon_lite_a0(struct skge_hw *hw)
{
u32 reg;
int ret;
if (hw->chip_id != CHIP_ID_YUKON)
return 0;
reg = skge_read32(hw, B2_FAR);
skge_write8(hw, B2_FAR + 3, 0xff);
ret = (skge_read8(hw, B2_FAR + 3) != 0);
skge_write32(hw, B2_FAR, reg);
return ret;
}
static void yukon_mac_init(struct skge_hw *hw, int port)
{
struct skge_port *skge = netdev_priv(hw->dev[port]);
int i;
u32 reg;
const u8 *addr = hw->dev[port]->dev_addr;
/* WA code for COMA mode -- set PHY reset */
if (hw->chip_id == CHIP_ID_YUKON_LITE &&
hw->chip_rev >= CHIP_REV_YU_LITE_A3) {
reg = skge_read32(hw, B2_GP_IO);
reg |= GP_DIR_9 | GP_IO_9;
skge_write32(hw, B2_GP_IO, reg);
}
/* hard reset */
skge_write32(hw, SK_REG(port, GPHY_CTRL), GPC_RST_SET);
skge_write32(hw, SK_REG(port, GMAC_CTRL), GMC_RST_SET);
/* WA code for COMA mode -- clear PHY reset */
if (hw->chip_id == CHIP_ID_YUKON_LITE &&
hw->chip_rev >= CHIP_REV_YU_LITE_A3) {
reg = skge_read32(hw, B2_GP_IO);
reg |= GP_DIR_9;
reg &= ~GP_IO_9;
skge_write32(hw, B2_GP_IO, reg);
}
/* Set hardware config mode */
reg = GPC_INT_POL_HI | GPC_DIS_FC | GPC_DIS_SLEEP |
GPC_ENA_XC | GPC_ANEG_ADV_ALL_M | GPC_ENA_PAUSE;
reg |= hw->copper ? GPC_HWCFG_GMII_COP : GPC_HWCFG_GMII_FIB;
/* Clear GMC reset */
skge_write32(hw, SK_REG(port, GPHY_CTRL), reg | GPC_RST_SET);
skge_write32(hw, SK_REG(port, GPHY_CTRL), reg | GPC_RST_CLR);
skge_write32(hw, SK_REG(port, GMAC_CTRL), GMC_PAUSE_ON | GMC_RST_CLR);
if (skge->autoneg == AUTONEG_DISABLE) {
reg = GM_GPCR_AU_ALL_DIS;
gma_write16(hw, port, GM_GP_CTRL,
gma_read16(hw, port, GM_GP_CTRL) | reg);
switch (skge->speed) {
case SPEED_1000:
reg &= ~GM_GPCR_SPEED_100;
reg |= GM_GPCR_SPEED_1000;
break;
case SPEED_100:
reg &= ~GM_GPCR_SPEED_1000;
reg |= GM_GPCR_SPEED_100;
break;
case SPEED_10:
reg &= ~(GM_GPCR_SPEED_1000 | GM_GPCR_SPEED_100);
break;
}
if (skge->duplex == DUPLEX_FULL)
reg |= GM_GPCR_DUP_FULL;
} else
reg = GM_GPCR_SPEED_1000 | GM_GPCR_SPEED_100 | GM_GPCR_DUP_FULL;
switch (skge->flow_control) {
case FLOW_MODE_NONE:
skge_write32(hw, SK_REG(port, GMAC_CTRL), GMC_PAUSE_OFF);
reg |= GM_GPCR_FC_TX_DIS | GM_GPCR_FC_RX_DIS | GM_GPCR_AU_FCT_DIS;
break;
case FLOW_MODE_LOC_SEND:
/* disable Rx flow-control */
reg |= GM_GPCR_FC_RX_DIS | GM_GPCR_AU_FCT_DIS;
break;
case FLOW_MODE_SYMMETRIC:
case FLOW_MODE_SYM_OR_REM:
/* enable Tx & Rx flow-control */
break;
}
gma_write16(hw, port, GM_GP_CTRL, reg);
skge_read16(hw, SK_REG(port, GMAC_IRQ_SRC));
yukon_init(hw, port);
/* MIB clear */
reg = gma_read16(hw, port, GM_PHY_ADDR);
gma_write16(hw, port, GM_PHY_ADDR, reg | GM_PAR_MIB_CLR);
for (i = 0; i < GM_MIB_CNT_SIZE; i++)
gma_read16(hw, port, GM_MIB_CNT_BASE + 8*i);
gma_write16(hw, port, GM_PHY_ADDR, reg);
/* transmit control */
gma_write16(hw, port, GM_TX_CTRL, TX_COL_THR(TX_COL_DEF));
/* receive control reg: unicast + multicast + no FCS */
gma_write16(hw, port, GM_RX_CTRL,
GM_RXCR_UCF_ENA | GM_RXCR_CRC_DIS | GM_RXCR_MCF_ENA);
/* transmit flow control */
gma_write16(hw, port, GM_TX_FLOW_CTRL, 0xffff);
/* transmit parameter */
gma_write16(hw, port, GM_TX_PARAM,
TX_JAM_LEN_VAL(TX_JAM_LEN_DEF) |
TX_JAM_IPG_VAL(TX_JAM_IPG_DEF) |
TX_IPG_JAM_DATA(TX_IPG_JAM_DEF));
/* configure the Serial Mode Register */
reg = DATA_BLIND_VAL(DATA_BLIND_DEF)
| GM_SMOD_VLAN_ENA
| IPG_DATA_VAL(IPG_DATA_DEF);
if (hw->dev[port]->mtu > ETH_DATA_LEN)
reg |= GM_SMOD_JUMBO_ENA;
gma_write16(hw, port, GM_SERIAL_MODE, reg);
/* physical address: used for pause frames */
gma_set_addr(hw, port, GM_SRC_ADDR_1L, addr);
/* virtual address for data */
gma_set_addr(hw, port, GM_SRC_ADDR_2L, addr);
/* enable interrupt mask for counter overflows */
gma_write16(hw, port, GM_TX_IRQ_MSK, 0);
gma_write16(hw, port, GM_RX_IRQ_MSK, 0);
gma_write16(hw, port, GM_TR_IRQ_MSK, 0);
/* Initialize Mac Fifo */
/* Configure Rx MAC FIFO */
skge_write16(hw, SK_REG(port, RX_GMF_FL_MSK), RX_FF_FL_DEF_MSK);
reg = GMF_OPER_ON | GMF_RX_F_FL_ON;
/* disable Rx GMAC FIFO Flush for YUKON-Lite Rev. A0 only */
if (is_yukon_lite_a0(hw))
reg &= ~GMF_RX_F_FL_ON;
skge_write8(hw, SK_REG(port, RX_GMF_CTRL_T), GMF_RST_CLR);
skge_write16(hw, SK_REG(port, RX_GMF_CTRL_T), reg);
/*
* because Pause Packet Truncation in GMAC is not working
* we have to increase the Flush Threshold to 64 bytes
* in order to flush pause packets in Rx FIFO on Yukon-1
*/
skge_write16(hw, SK_REG(port, RX_GMF_FL_THR), RX_GMF_FL_THR_DEF+1);
/* Configure Tx MAC FIFO */
skge_write8(hw, SK_REG(port, TX_GMF_CTRL_T), GMF_RST_CLR);
skge_write16(hw, SK_REG(port, TX_GMF_CTRL_T), GMF_OPER_ON);
}
/* Go into power down mode */
static void yukon_suspend(struct skge_hw *hw, int port)
{
u16 ctrl;
ctrl = gm_phy_read(hw, port, PHY_MARV_PHY_CTRL);
ctrl |= PHY_M_PC_POL_R_DIS;
gm_phy_write(hw, port, PHY_MARV_PHY_CTRL, ctrl);
ctrl = gm_phy_read(hw, port, PHY_MARV_CTRL);
ctrl |= PHY_CT_RESET;
gm_phy_write(hw, port, PHY_MARV_CTRL, ctrl);
/* switch IEEE compatible power down mode on */
ctrl = gm_phy_read(hw, port, PHY_MARV_CTRL);
ctrl |= PHY_CT_PDOWN;
gm_phy_write(hw, port, PHY_MARV_CTRL, ctrl);
}
static void yukon_stop(struct skge_port *skge)
{
struct skge_hw *hw = skge->hw;
int port = skge->port;
skge_write8(hw, SK_REG(port, GMAC_IRQ_MSK), 0);
yukon_reset(hw, port);
gma_write16(hw, port, GM_GP_CTRL,
gma_read16(hw, port, GM_GP_CTRL)
& ~(GM_GPCR_TX_ENA|GM_GPCR_RX_ENA));
gma_read16(hw, port, GM_GP_CTRL);
yukon_suspend(hw, port);
/* set GPHY Control reset */
skge_write8(hw, SK_REG(port, GPHY_CTRL), GPC_RST_SET);
skge_write8(hw, SK_REG(port, GMAC_CTRL), GMC_RST_SET);
}
static void yukon_get_stats(struct skge_port *skge, u64 *data)
{
struct skge_hw *hw = skge->hw;
int port = skge->port;
int i;
data[0] = (u64) gma_read32(hw, port, GM_TXO_OK_HI) << 32
| gma_read32(hw, port, GM_TXO_OK_LO);
data[1] = (u64) gma_read32(hw, port, GM_RXO_OK_HI) << 32
| gma_read32(hw, port, GM_RXO_OK_LO);
for (i = 2; i < ARRAY_SIZE(skge_stats); i++)
data[i] = gma_read32(hw, port,
skge_stats[i].gma_offset);
}
static void yukon_mac_intr(struct skge_hw *hw, int port)
{
struct net_device *dev = hw->dev[port];
struct skge_port *skge = netdev_priv(dev);
u8 status = skge_read8(hw, SK_REG(port, GMAC_IRQ_SRC));
netif_printk(skge, intr, KERN_DEBUG, skge->netdev,
"mac interrupt status 0x%x\n", status);
if (status & GM_IS_RX_FF_OR) {
++dev->stats.rx_fifo_errors;
skge_write8(hw, SK_REG(port, RX_GMF_CTRL_T), GMF_CLI_RX_FO);
}
if (status & GM_IS_TX_FF_UR) {
++dev->stats.tx_fifo_errors;
skge_write8(hw, SK_REG(port, TX_GMF_CTRL_T), GMF_CLI_TX_FU);
}
}
static u16 yukon_speed(const struct skge_hw *hw, u16 aux)
{
switch (aux & PHY_M_PS_SPEED_MSK) {
case PHY_M_PS_SPEED_1000:
return SPEED_1000;
case PHY_M_PS_SPEED_100:
return SPEED_100;
default:
return SPEED_10;
}
}
static void yukon_link_up(struct skge_port *skge)
{
struct skge_hw *hw = skge->hw;
int port = skge->port;
u16 reg;
/* Enable Transmit FIFO Underrun */
skge_write8(hw, SK_REG(port, GMAC_IRQ_MSK), GMAC_DEF_MSK);
reg = gma_read16(hw, port, GM_GP_CTRL);
if (skge->duplex == DUPLEX_FULL || skge->autoneg == AUTONEG_ENABLE)
reg |= GM_GPCR_DUP_FULL;
/* enable Rx/Tx */
reg |= GM_GPCR_RX_ENA | GM_GPCR_TX_ENA;
gma_write16(hw, port, GM_GP_CTRL, reg);
gm_phy_write(hw, port, PHY_MARV_INT_MASK, PHY_M_IS_DEF_MSK);
skge_link_up(skge);
}
static void yukon_link_down(struct skge_port *skge)
{
struct skge_hw *hw = skge->hw;
int port = skge->port;
u16 ctrl;
ctrl = gma_read16(hw, port, GM_GP_CTRL);
ctrl &= ~(GM_GPCR_RX_ENA | GM_GPCR_TX_ENA);
gma_write16(hw, port, GM_GP_CTRL, ctrl);
if (skge->flow_status == FLOW_STAT_REM_SEND) {
ctrl = gm_phy_read(hw, port, PHY_MARV_AUNE_ADV);
ctrl |= PHY_M_AN_ASP;
/* restore Asymmetric Pause bit */
gm_phy_write(hw, port, PHY_MARV_AUNE_ADV, ctrl);
}
skge_link_down(skge);
yukon_init(hw, port);
}
static void yukon_phy_intr(struct skge_port *skge)
{
struct skge_hw *hw = skge->hw;
int port = skge->port;
const char *reason = NULL;
u16 istatus, phystat;
istatus = gm_phy_read(hw, port, PHY_MARV_INT_STAT);
phystat = gm_phy_read(hw, port, PHY_MARV_PHY_STAT);
netif_printk(skge, intr, KERN_DEBUG, skge->netdev,
"phy interrupt status 0x%x 0x%x\n", istatus, phystat);
if (istatus & PHY_M_IS_AN_COMPL) {
if (gm_phy_read(hw, port, PHY_MARV_AUNE_LP)
& PHY_M_AN_RF) {
reason = "remote fault";
goto failed;
}
if (gm_phy_read(hw, port, PHY_MARV_1000T_STAT) & PHY_B_1000S_MSF) {
reason = "master/slave fault";
goto failed;
}
if (!(phystat & PHY_M_PS_SPDUP_RES)) {
reason = "speed/duplex";
goto failed;
}
skge->duplex = (phystat & PHY_M_PS_FULL_DUP)
? DUPLEX_FULL : DUPLEX_HALF;
skge->speed = yukon_speed(hw, phystat);
/* We are using IEEE 802.3z/D5.0 Table 37-4 */
switch (phystat & PHY_M_PS_PAUSE_MSK) {
case PHY_M_PS_PAUSE_MSK:
skge->flow_status = FLOW_STAT_SYMMETRIC;
break;
case PHY_M_PS_RX_P_EN:
skge->flow_status = FLOW_STAT_REM_SEND;
break;
case PHY_M_PS_TX_P_EN:
skge->flow_status = FLOW_STAT_LOC_SEND;
break;
default:
skge->flow_status = FLOW_STAT_NONE;
}
if (skge->flow_status == FLOW_STAT_NONE ||
(skge->speed < SPEED_1000 && skge->duplex == DUPLEX_HALF))
skge_write8(hw, SK_REG(port, GMAC_CTRL), GMC_PAUSE_OFF);
else
skge_write8(hw, SK_REG(port, GMAC_CTRL), GMC_PAUSE_ON);
yukon_link_up(skge);
return;
}
if (istatus & PHY_M_IS_LSP_CHANGE)
skge->speed = yukon_speed(hw, phystat);
if (istatus & PHY_M_IS_DUP_CHANGE)
skge->duplex = (phystat & PHY_M_PS_FULL_DUP) ? DUPLEX_FULL : DUPLEX_HALF;
if (istatus & PHY_M_IS_LST_CHANGE) {
if (phystat & PHY_M_PS_LINK_UP)
yukon_link_up(skge);
else
yukon_link_down(skge);
}
return;
failed:
pr_err("%s: autonegotiation failed (%s)\n", skge->netdev->name, reason);
/* XXX restart autonegotiation? */
}
static void skge_phy_reset(struct skge_port *skge)
{
struct skge_hw *hw = skge->hw;
int port = skge->port;
struct net_device *dev = hw->dev[port];
netif_stop_queue(skge->netdev);
netif_carrier_off(skge->netdev);
spin_lock_bh(&hw->phy_lock);
if (is_genesis(hw)) {
genesis_reset(hw, port);
genesis_mac_init(hw, port);
} else {
yukon_reset(hw, port);
yukon_init(hw, port);
}
spin_unlock_bh(&hw->phy_lock);
skge_set_multicast(dev);
}
/* Basic MII support */
static int skge_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
{
struct mii_ioctl_data *data = if_mii(ifr);
struct skge_port *skge = netdev_priv(dev);
struct skge_hw *hw = skge->hw;
int err = -EOPNOTSUPP;
if (!netif_running(dev))
return -ENODEV; /* Phy still in reset */
switch (cmd) {
case SIOCGMIIPHY:
data->phy_id = hw->phy_addr;
/* fallthru */
case SIOCGMIIREG: {
u16 val = 0;
spin_lock_bh(&hw->phy_lock);
if (is_genesis(hw))
err = __xm_phy_read(hw, skge->port, data->reg_num & 0x1f, &val);
else
err = __gm_phy_read(hw, skge->port, data->reg_num & 0x1f, &val);
spin_unlock_bh(&hw->phy_lock);
data->val_out = val;
break;
}
case SIOCSMIIREG:
spin_lock_bh(&hw->phy_lock);
if (is_genesis(hw))
err = xm_phy_write(hw, skge->port, data->reg_num & 0x1f,
data->val_in);
else
err = gm_phy_write(hw, skge->port, data->reg_num & 0x1f,
data->val_in);
spin_unlock_bh(&hw->phy_lock);
break;
}
return err;
}
static void skge_ramset(struct skge_hw *hw, u16 q, u32 start, size_t len)
{
u32 end;
start /= 8;
len /= 8;
end = start + len - 1;
skge_write8(hw, RB_ADDR(q, RB_CTRL), RB_RST_CLR);
skge_write32(hw, RB_ADDR(q, RB_START), start);
skge_write32(hw, RB_ADDR(q, RB_WP), start);
skge_write32(hw, RB_ADDR(q, RB_RP), start);
skge_write32(hw, RB_ADDR(q, RB_END), end);
if (q == Q_R1 || q == Q_R2) {
/* Set thresholds on receive queue's */
skge_write32(hw, RB_ADDR(q, RB_RX_UTPP),
start + (2*len)/3);
skge_write32(hw, RB_ADDR(q, RB_RX_LTPP),
start + (len/3));
} else {
/* Enable store & forward on Tx queue's because
* Tx FIFO is only 4K on Genesis and 1K on Yukon
*/
skge_write8(hw, RB_ADDR(q, RB_CTRL), RB_ENA_STFWD);
}
skge_write8(hw, RB_ADDR(q, RB_CTRL), RB_ENA_OP_MD);
}
/* Setup Bus Memory Interface */
static void skge_qset(struct skge_port *skge, u16 q,
const struct skge_element *e)
{
struct skge_hw *hw = skge->hw;
u32 watermark = 0x600;
u64 base = skge->dma + (e->desc - skge->mem);
/* optimization to reduce window on 32bit/33mhz */
if ((skge_read16(hw, B0_CTST) & (CS_BUS_CLOCK | CS_BUS_SLOT_SZ)) == 0)
watermark /= 2;
skge_write32(hw, Q_ADDR(q, Q_CSR), CSR_CLR_RESET);
skge_write32(hw, Q_ADDR(q, Q_F), watermark);
skge_write32(hw, Q_ADDR(q, Q_DA_H), (u32)(base >> 32));
skge_write32(hw, Q_ADDR(q, Q_DA_L), (u32)base);
}
static int skge_up(struct net_device *dev)
{
struct skge_port *skge = netdev_priv(dev);
struct skge_hw *hw = skge->hw;
int port = skge->port;
u32 chunk, ram_addr;
size_t rx_size, tx_size;
int err;
if (!is_valid_ether_addr(dev->dev_addr))
return -EINVAL;
netif_info(skge, ifup, skge->netdev, "enabling interface\n");
if (dev->mtu > RX_BUF_SIZE)
skge->rx_buf_size = dev->mtu + ETH_HLEN;
else
skge->rx_buf_size = RX_BUF_SIZE;
rx_size = skge->rx_ring.count * sizeof(struct skge_rx_desc);
tx_size = skge->tx_ring.count * sizeof(struct skge_tx_desc);
skge->mem_size = tx_size + rx_size;
skge->mem = pci_alloc_consistent(hw->pdev, skge->mem_size, &skge->dma);
if (!skge->mem)
return -ENOMEM;
BUG_ON(skge->dma & 7);
if ((u64)skge->dma >> 32 != ((u64) skge->dma + skge->mem_size) >> 32) {
dev_err(&hw->pdev->dev, "pci_alloc_consistent region crosses 4G boundary\n");
err = -EINVAL;
goto free_pci_mem;
}
memset(skge->mem, 0, skge->mem_size);
err = skge_ring_alloc(&skge->rx_ring, skge->mem, skge->dma);
if (err)
goto free_pci_mem;
err = skge_rx_fill(dev);
if (err)
goto free_rx_ring;
err = skge_ring_alloc(&skge->tx_ring, skge->mem + rx_size,
skge->dma + rx_size);
if (err)
goto free_rx_ring;
if (hw->ports == 1) {
err = request_irq(hw->pdev->irq, skge_intr, IRQF_SHARED,
dev->name, hw);
if (err) {
netdev_err(dev, "Unable to allocate interrupt %d error: %d\n",
hw->pdev->irq, err);
goto free_tx_ring;
}
}
/* Initialize MAC */
netif_carrier_off(dev);
spin_lock_bh(&hw->phy_lock);
if (is_genesis(hw))
genesis_mac_init(hw, port);
else
yukon_mac_init(hw, port);
spin_unlock_bh(&hw->phy_lock);
/* Configure RAMbuffers - equally between ports and tx/rx */
chunk = (hw->ram_size - hw->ram_offset) / (hw->ports * 2);
ram_addr = hw->ram_offset + 2 * chunk * port;
skge_ramset(hw, rxqaddr[port], ram_addr, chunk);
skge_qset(skge, rxqaddr[port], skge->rx_ring.to_clean);
BUG_ON(skge->tx_ring.to_use != skge->tx_ring.to_clean);
skge_ramset(hw, txqaddr[port], ram_addr+chunk, chunk);
skge_qset(skge, txqaddr[port], skge->tx_ring.to_use);
/* Start receiver BMU */
wmb();
skge_write8(hw, Q_ADDR(rxqaddr[port], Q_CSR), CSR_START | CSR_IRQ_CL_F);
skge_led(skge, LED_MODE_ON);
spin_lock_irq(&hw->hw_lock);
hw->intr_mask |= portmask[port];
skge_write32(hw, B0_IMSK, hw->intr_mask);
skge_read32(hw, B0_IMSK);
spin_unlock_irq(&hw->hw_lock);
napi_enable(&skge->napi);
skge_set_multicast(dev);
return 0;
free_tx_ring:
kfree(skge->tx_ring.start);
free_rx_ring:
skge_rx_clean(skge);
kfree(skge->rx_ring.start);
free_pci_mem:
pci_free_consistent(hw->pdev, skge->mem_size, skge->mem, skge->dma);
skge->mem = NULL;
return err;
}
/* stop receiver */
static void skge_rx_stop(struct skge_hw *hw, int port)
{
skge_write8(hw, Q_ADDR(rxqaddr[port], Q_CSR), CSR_STOP);
skge_write32(hw, RB_ADDR(port ? Q_R2 : Q_R1, RB_CTRL),
RB_RST_SET|RB_DIS_OP_MD);
skge_write32(hw, Q_ADDR(rxqaddr[port], Q_CSR), CSR_SET_RESET);
}
static int skge_down(struct net_device *dev)
{
struct skge_port *skge = netdev_priv(dev);
struct skge_hw *hw = skge->hw;
int port = skge->port;
if (skge->mem == NULL)
return 0;
netif_info(skge, ifdown, skge->netdev, "disabling interface\n");
netif_tx_disable(dev);
if (is_genesis(hw) && hw->phy_type == SK_PHY_XMAC)
del_timer_sync(&skge->link_timer);
napi_disable(&skge->napi);
netif_carrier_off(dev);
spin_lock_irq(&hw->hw_lock);
hw->intr_mask &= ~portmask[port];
skge_write32(hw, B0_IMSK, (hw->ports == 1) ? 0 : hw->intr_mask);
skge_read32(hw, B0_IMSK);
spin_unlock_irq(&hw->hw_lock);
if (hw->ports == 1)
free_irq(hw->pdev->irq, hw);
skge_write8(skge->hw, SK_REG(skge->port, LNK_LED_REG), LED_OFF);
if (is_genesis(hw))
genesis_stop(skge);
else
yukon_stop(skge);
/* Stop transmitter */
skge_write8(hw, Q_ADDR(txqaddr[port], Q_CSR), CSR_STOP);
skge_write32(hw, RB_ADDR(txqaddr[port], RB_CTRL),
RB_RST_SET|RB_DIS_OP_MD);
/* Disable Force Sync bit and Enable Alloc bit */
skge_write8(hw, SK_REG(port, TXA_CTRL),
TXA_DIS_FSYNC | TXA_DIS_ALLOC | TXA_STOP_RC);
/* Stop Interval Timer and Limit Counter of Tx Arbiter */
skge_write32(hw, SK_REG(port, TXA_ITI_INI), 0L);
skge_write32(hw, SK_REG(port, TXA_LIM_INI), 0L);
/* Reset PCI FIFO */
skge_write32(hw, Q_ADDR(txqaddr[port], Q_CSR), CSR_SET_RESET);
skge_write32(hw, RB_ADDR(txqaddr[port], RB_CTRL), RB_RST_SET);
/* Reset the RAM Buffer async Tx queue */
skge_write8(hw, RB_ADDR(port == 0 ? Q_XA1 : Q_XA2, RB_CTRL), RB_RST_SET);
skge_rx_stop(hw, port);
if (is_genesis(hw)) {
skge_write8(hw, SK_REG(port, TX_MFF_CTRL2), MFF_RST_SET);
skge_write8(hw, SK_REG(port, RX_MFF_CTRL2), MFF_RST_SET);
} else {
skge_write8(hw, SK_REG(port, RX_GMF_CTRL_T), GMF_RST_SET);
skge_write8(hw, SK_REG(port, TX_GMF_CTRL_T), GMF_RST_SET);
}
skge_led(skge, LED_MODE_OFF);
netif_tx_lock_bh(dev);
skge_tx_clean(dev);
netif_tx_unlock_bh(dev);
skge_rx_clean(skge);
kfree(skge->rx_ring.start);
kfree(skge->tx_ring.start);
pci_free_consistent(hw->pdev, skge->mem_size, skge->mem, skge->dma);
skge->mem = NULL;
return 0;
}
static inline int skge_avail(const struct skge_ring *ring)
{
smp_mb();
return ((ring->to_clean > ring->to_use) ? 0 : ring->count)
+ (ring->to_clean - ring->to_use) - 1;
}
static netdev_tx_t skge_xmit_frame(struct sk_buff *skb,
struct net_device *dev)
{
struct skge_port *skge = netdev_priv(dev);
struct skge_hw *hw = skge->hw;
struct skge_element *e;
struct skge_tx_desc *td;
int i;
u32 control, len;
u64 map;
if (skb_padto(skb, ETH_ZLEN))
return NETDEV_TX_OK;
if (unlikely(skge_avail(&skge->tx_ring) < skb_shinfo(skb)->nr_frags + 1))
return NETDEV_TX_BUSY;
e = skge->tx_ring.to_use;
td = e->desc;
BUG_ON(td->control & BMU_OWN);
e->skb = skb;
len = skb_headlen(skb);
map = pci_map_single(hw->pdev, skb->data, len, PCI_DMA_TODEVICE);
dma_unmap_addr_set(e, mapaddr, map);
dma_unmap_len_set(e, maplen, len);
td->dma_lo = map;
td->dma_hi = map >> 32;
if (skb->ip_summed == CHECKSUM_PARTIAL) {
const int offset = skb_checksum_start_offset(skb);
/* This seems backwards, but it is what the sk98lin
* does. Looks like hardware is wrong?
*/
if (ipip_hdr(skb)->protocol == IPPROTO_UDP &&
hw->chip_rev == 0 && hw->chip_id == CHIP_ID_YUKON)
control = BMU_TCP_CHECK;
else
control = BMU_UDP_CHECK;
td->csum_offs = 0;
td->csum_start = offset;
td->csum_write = offset + skb->csum_offset;
} else
control = BMU_CHECK;
if (!skb_shinfo(skb)->nr_frags) /* single buffer i.e. no fragments */
control |= BMU_EOF | BMU_IRQ_EOF;
else {
struct skge_tx_desc *tf = td;
control |= BMU_STFWD;
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
const skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
map = skb_frag_dma_map(&hw->pdev->dev, frag, 0,
skb_frag_size(frag), DMA_TO_DEVICE);
e = e->next;
e->skb = skb;
tf = e->desc;
BUG_ON(tf->control & BMU_OWN);
tf->dma_lo = map;
tf->dma_hi = (u64) map >> 32;
dma_unmap_addr_set(e, mapaddr, map);
dma_unmap_len_set(e, maplen, skb_frag_size(frag));
tf->control = BMU_OWN | BMU_SW | control | skb_frag_size(frag);
}
tf->control |= BMU_EOF | BMU_IRQ_EOF;
}
/* Make sure all the descriptors written */
wmb();
td->control = BMU_OWN | BMU_SW | BMU_STF | control | len;
wmb();
netdev_sent_queue(dev, skb->len);
skge_write8(hw, Q_ADDR(txqaddr[skge->port], Q_CSR), CSR_START);
netif_printk(skge, tx_queued, KERN_DEBUG, skge->netdev,
"tx queued, slot %td, len %d\n",
e - skge->tx_ring.start, skb->len);
skge->tx_ring.to_use = e->next;
smp_wmb();
if (skge_avail(&skge->tx_ring) <= TX_LOW_WATER) {
netdev_dbg(dev, "transmit queue full\n");
netif_stop_queue(dev);
}
return NETDEV_TX_OK;
}
/* Free resources associated with this reing element */
static inline void skge_tx_unmap(struct pci_dev *pdev, struct skge_element *e,
u32 control)
{
/* skb header vs. fragment */
if (control & BMU_STF)
pci_unmap_single(pdev, dma_unmap_addr(e, mapaddr),
dma_unmap_len(e, maplen),
PCI_DMA_TODEVICE);
else
pci_unmap_page(pdev, dma_unmap_addr(e, mapaddr),
dma_unmap_len(e, maplen),
PCI_DMA_TODEVICE);
}
/* Free all buffers in transmit ring */
static void skge_tx_clean(struct net_device *dev)
{
struct skge_port *skge = netdev_priv(dev);
struct skge_element *e;
for (e = skge->tx_ring.to_clean; e != skge->tx_ring.to_use; e = e->next) {
struct skge_tx_desc *td = e->desc;
skge_tx_unmap(skge->hw->pdev, e, td->control);
if (td->control & BMU_EOF)
dev_kfree_skb(e->skb);
td->control = 0;
}
netdev_reset_queue(dev);
skge->tx_ring.to_clean = e;
}
static void skge_tx_timeout(struct net_device *dev)
{
struct skge_port *skge = netdev_priv(dev);
netif_printk(skge, timer, KERN_DEBUG, skge->netdev, "tx timeout\n");
skge_write8(skge->hw, Q_ADDR(txqaddr[skge->port], Q_CSR), CSR_STOP);
skge_tx_clean(dev);
netif_wake_queue(dev);
}
static int skge_change_mtu(struct net_device *dev, int new_mtu)
{
int err;
if (new_mtu < ETH_ZLEN || new_mtu > ETH_JUMBO_MTU)
return -EINVAL;
if (!netif_running(dev)) {
dev->mtu = new_mtu;
return 0;
}
skge_down(dev);
dev->mtu = new_mtu;
err = skge_up(dev);
if (err)
dev_close(dev);
return err;
}
static const u8 pause_mc_addr[ETH_ALEN] = { 0x1, 0x80, 0xc2, 0x0, 0x0, 0x1 };
static void genesis_add_filter(u8 filter[8], const u8 *addr)
{
u32 crc, bit;
crc = ether_crc_le(ETH_ALEN, addr);
bit = ~crc & 0x3f;
filter[bit/8] |= 1 << (bit%8);
}
static void genesis_set_multicast(struct net_device *dev)
{
struct skge_port *skge = netdev_priv(dev);
struct skge_hw *hw = skge->hw;
int port = skge->port;
struct netdev_hw_addr *ha;
u32 mode;
u8 filter[8];
mode = xm_read32(hw, port, XM_MODE);
mode |= XM_MD_ENA_HASH;
if (dev->flags & IFF_PROMISC)
mode |= XM_MD_ENA_PROM;
else
mode &= ~XM_MD_ENA_PROM;
if (dev->flags & IFF_ALLMULTI)
memset(filter, 0xff, sizeof(filter));
else {
memset(filter, 0, sizeof(filter));
if (skge->flow_status == FLOW_STAT_REM_SEND ||
skge->flow_status == FLOW_STAT_SYMMETRIC)
genesis_add_filter(filter, pause_mc_addr);
netdev_for_each_mc_addr(ha, dev)
genesis_add_filter(filter, ha->addr);
}
xm_write32(hw, port, XM_MODE, mode);
xm_outhash(hw, port, XM_HSM, filter);
}
static void yukon_add_filter(u8 filter[8], const u8 *addr)
{
u32 bit = ether_crc(ETH_ALEN, addr) & 0x3f;
filter[bit/8] |= 1 << (bit%8);
}
static void yukon_set_multicast(struct net_device *dev)
{
struct skge_port *skge = netdev_priv(dev);
struct skge_hw *hw = skge->hw;
int port = skge->port;
struct netdev_hw_addr *ha;
int rx_pause = (skge->flow_status == FLOW_STAT_REM_SEND ||
skge->flow_status == FLOW_STAT_SYMMETRIC);
u16 reg;
u8 filter[8];
memset(filter, 0, sizeof(filter));
reg = gma_read16(hw, port, GM_RX_CTRL);
reg |= GM_RXCR_UCF_ENA;
if (dev->flags & IFF_PROMISC) /* promiscuous */
reg &= ~(GM_RXCR_UCF_ENA | GM_RXCR_MCF_ENA);
else if (dev->flags & IFF_ALLMULTI) /* all multicast */
memset(filter, 0xff, sizeof(filter));
else if (netdev_mc_empty(dev) && !rx_pause)/* no multicast */
reg &= ~GM_RXCR_MCF_ENA;
else {
reg |= GM_RXCR_MCF_ENA;
if (rx_pause)
yukon_add_filter(filter, pause_mc_addr);
netdev_for_each_mc_addr(ha, dev)
yukon_add_filter(filter, ha->addr);
}
gma_write16(hw, port, GM_MC_ADDR_H1,
(u16)filter[0] | ((u16)filter[1] << 8));
gma_write16(hw, port, GM_MC_ADDR_H2,
(u16)filter[2] | ((u16)filter[3] << 8));
gma_write16(hw, port, GM_MC_ADDR_H3,
(u16)filter[4] | ((u16)filter[5] << 8));
gma_write16(hw, port, GM_MC_ADDR_H4,
(u16)filter[6] | ((u16)filter[7] << 8));
gma_write16(hw, port, GM_RX_CTRL, reg);
}
static inline u16 phy_length(const struct skge_hw *hw, u32 status)
{
if (is_genesis(hw))
return status >> XMR_FS_LEN_SHIFT;
else
return status >> GMR_FS_LEN_SHIFT;
}
static inline int bad_phy_status(const struct skge_hw *hw, u32 status)
{
if (is_genesis(hw))
return (status & (XMR_FS_ERR | XMR_FS_2L_VLAN)) != 0;
else
return (status & GMR_FS_ANY_ERR) ||
(status & GMR_FS_RX_OK) == 0;
}
static void skge_set_multicast(struct net_device *dev)
{
struct skge_port *skge = netdev_priv(dev);
if (is_genesis(skge->hw))
genesis_set_multicast(dev);
else
yukon_set_multicast(dev);
}
/* Get receive buffer from descriptor.
* Handles copy of small buffers and reallocation failures
*/
static struct sk_buff *skge_rx_get(struct net_device *dev,
struct skge_element *e,
u32 control, u32 status, u16 csum)
{
struct skge_port *skge = netdev_priv(dev);
struct sk_buff *skb;
u16 len = control & BMU_BBC;
netif_printk(skge, rx_status, KERN_DEBUG, skge->netdev,
"rx slot %td status 0x%x len %d\n",
e - skge->rx_ring.start, status, len);
if (len > skge->rx_buf_size)
goto error;
if ((control & (BMU_EOF|BMU_STF)) != (BMU_STF|BMU_EOF))
goto error;
if (bad_phy_status(skge->hw, status))
goto error;
if (phy_length(skge->hw, status) != len)
goto error;
if (len < RX_COPY_THRESHOLD) {
skb = netdev_alloc_skb_ip_align(dev, len);
if (!skb)
goto resubmit;
pci_dma_sync_single_for_cpu(skge->hw->pdev,
dma_unmap_addr(e, mapaddr),
len, PCI_DMA_FROMDEVICE);
skb_copy_from_linear_data(e->skb, skb->data, len);
pci_dma_sync_single_for_device(skge->hw->pdev,
dma_unmap_addr(e, mapaddr),
len, PCI_DMA_FROMDEVICE);
skge_rx_reuse(e, skge->rx_buf_size);
} else {
struct sk_buff *nskb;
nskb = netdev_alloc_skb_ip_align(dev, skge->rx_buf_size);
if (!nskb)
goto resubmit;
pci_unmap_single(skge->hw->pdev,
dma_unmap_addr(e, mapaddr),
dma_unmap_len(e, maplen),
PCI_DMA_FROMDEVICE);
skb = e->skb;
prefetch(skb->data);
skge_rx_setup(skge, e, nskb, skge->rx_buf_size);
}
skb_put(skb, len);
if (dev->features & NETIF_F_RXCSUM) {
skb->csum = csum;
skb->ip_summed = CHECKSUM_COMPLETE;
}
skb->protocol = eth_type_trans(skb, dev);
return skb;
error:
netif_printk(skge, rx_err, KERN_DEBUG, skge->netdev,
"rx err, slot %td control 0x%x status 0x%x\n",
e - skge->rx_ring.start, control, status);
if (is_genesis(skge->hw)) {
if (status & (XMR_FS_RUNT|XMR_FS_LNG_ERR))
dev->stats.rx_length_errors++;
if (status & XMR_FS_FRA_ERR)
dev->stats.rx_frame_errors++;
if (status & XMR_FS_FCS_ERR)
dev->stats.rx_crc_errors++;
} else {
if (status & (GMR_FS_LONG_ERR|GMR_FS_UN_SIZE))
dev->stats.rx_length_errors++;
if (status & GMR_FS_FRAGMENT)
dev->stats.rx_frame_errors++;
if (status & GMR_FS_CRC_ERR)
dev->stats.rx_crc_errors++;
}
resubmit:
skge_rx_reuse(e, skge->rx_buf_size);
return NULL;
}
/* Free all buffers in Tx ring which are no longer owned by device */
static void skge_tx_done(struct net_device *dev)
{
struct skge_port *skge = netdev_priv(dev);
struct skge_ring *ring = &skge->tx_ring;
struct skge_element *e;
unsigned int bytes_compl = 0, pkts_compl = 0;
skge_write8(skge->hw, Q_ADDR(txqaddr[skge->port], Q_CSR), CSR_IRQ_CL_F);
for (e = ring->to_clean; e != ring->to_use; e = e->next) {
u32 control = ((const struct skge_tx_desc *) e->desc)->control;
if (control & BMU_OWN)
break;
skge_tx_unmap(skge->hw->pdev, e, control);
if (control & BMU_EOF) {
netif_printk(skge, tx_done, KERN_DEBUG, skge->netdev,
"tx done slot %td\n",
e - skge->tx_ring.start);
pkts_compl++;
bytes_compl += e->skb->len;
dev_kfree_skb(e->skb);
}
}
netdev_completed_queue(dev, pkts_compl, bytes_compl);
skge->tx_ring.to_clean = e;
/* Can run lockless until we need to synchronize to restart queue. */
smp_mb();
if (unlikely(netif_queue_stopped(dev) &&
skge_avail(&skge->tx_ring) > TX_LOW_WATER)) {
netif_tx_lock(dev);
if (unlikely(netif_queue_stopped(dev) &&
skge_avail(&skge->tx_ring) > TX_LOW_WATER)) {
netif_wake_queue(dev);
}
netif_tx_unlock(dev);
}
}
static int skge_poll(struct napi_struct *napi, int to_do)
{
struct skge_port *skge = container_of(napi, struct skge_port, napi);
struct net_device *dev = skge->netdev;
struct skge_hw *hw = skge->hw;
struct skge_ring *ring = &skge->rx_ring;
struct skge_element *e;
int work_done = 0;
skge_tx_done(dev);
skge_write8(hw, Q_ADDR(rxqaddr[skge->port], Q_CSR), CSR_IRQ_CL_F);
for (e = ring->to_clean; prefetch(e->next), work_done < to_do; e = e->next) {
struct skge_rx_desc *rd = e->desc;
struct sk_buff *skb;
u32 control;
rmb();
control = rd->control;
if (control & BMU_OWN)
break;
skb = skge_rx_get(dev, e, control, rd->status, rd->csum2);
if (likely(skb)) {
napi_gro_receive(napi, skb);
++work_done;
}
}
ring->to_clean = e;
/* restart receiver */
wmb();
skge_write8(hw, Q_ADDR(rxqaddr[skge->port], Q_CSR), CSR_START);
if (work_done < to_do) {
unsigned long flags;
napi_gro_flush(napi, false);
spin_lock_irqsave(&hw->hw_lock, flags);
__napi_complete(napi);
hw->intr_mask |= napimask[skge->port];
skge_write32(hw, B0_IMSK, hw->intr_mask);
skge_read32(hw, B0_IMSK);
spin_unlock_irqrestore(&hw->hw_lock, flags);
}
return work_done;
}
/* Parity errors seem to happen when Genesis is connected to a switch
* with no other ports present. Heartbeat error??
*/
static void skge_mac_parity(struct skge_hw *hw, int port)
{
struct net_device *dev = hw->dev[port];
++dev->stats.tx_heartbeat_errors;
if (is_genesis(hw))
skge_write16(hw, SK_REG(port, TX_MFF_CTRL1),
MFF_CLR_PERR);
else
/* HW-Bug #8: cleared by GMF_CLI_TX_FC instead of GMF_CLI_TX_PE */
skge_write8(hw, SK_REG(port, TX_GMF_CTRL_T),
(hw->chip_id == CHIP_ID_YUKON && hw->chip_rev == 0)
? GMF_CLI_TX_FC : GMF_CLI_TX_PE);
}
static void skge_mac_intr(struct skge_hw *hw, int port)
{
if (is_genesis(hw))
genesis_mac_intr(hw, port);
else
yukon_mac_intr(hw, port);
}
/* Handle device specific framing and timeout interrupts */
static void skge_error_irq(struct skge_hw *hw)
{
struct pci_dev *pdev = hw->pdev;
u32 hwstatus = skge_read32(hw, B0_HWE_ISRC);
if (is_genesis(hw)) {
/* clear xmac errors */
if (hwstatus & (IS_NO_STAT_M1|IS_NO_TIST_M1))
skge_write16(hw, RX_MFF_CTRL1, MFF_CLR_INSTAT);
if (hwstatus & (IS_NO_STAT_M2|IS_NO_TIST_M2))
skge_write16(hw, RX_MFF_CTRL2, MFF_CLR_INSTAT);
} else {
/* Timestamp (unused) overflow */
if (hwstatus & IS_IRQ_TIST_OV)
skge_write8(hw, GMAC_TI_ST_CTRL, GMT_ST_CLR_IRQ);
}
if (hwstatus & IS_RAM_RD_PAR) {
dev_err(&pdev->dev, "Ram read data parity error\n");
skge_write16(hw, B3_RI_CTRL, RI_CLR_RD_PERR);
}
if (hwstatus & IS_RAM_WR_PAR) {
dev_err(&pdev->dev, "Ram write data parity error\n");
skge_write16(hw, B3_RI_CTRL, RI_CLR_WR_PERR);
}
if (hwstatus & IS_M1_PAR_ERR)
skge_mac_parity(hw, 0);
if (hwstatus & IS_M2_PAR_ERR)
skge_mac_parity(hw, 1);
if (hwstatus & IS_R1_PAR_ERR) {
dev_err(&pdev->dev, "%s: receive queue parity error\n",
hw->dev[0]->name);
skge_write32(hw, B0_R1_CSR, CSR_IRQ_CL_P);
}
if (hwstatus & IS_R2_PAR_ERR) {
dev_err(&pdev->dev, "%s: receive queue parity error\n",
hw->dev[1]->name);
skge_write32(hw, B0_R2_CSR, CSR_IRQ_CL_P);
}
if (hwstatus & (IS_IRQ_MST_ERR|IS_IRQ_STAT)) {
u16 pci_status, pci_cmd;
pci_read_config_word(pdev, PCI_COMMAND, &pci_cmd);
pci_read_config_word(pdev, PCI_STATUS, &pci_status);
dev_err(&pdev->dev, "PCI error cmd=%#x status=%#x\n",
pci_cmd, pci_status);
/* Write the error bits back to clear them. */
pci_status &= PCI_STATUS_ERROR_BITS;
skge_write8(hw, B2_TST_CTRL1, TST_CFG_WRITE_ON);
pci_write_config_word(pdev, PCI_COMMAND,
pci_cmd | PCI_COMMAND_SERR | PCI_COMMAND_PARITY);
pci_write_config_word(pdev, PCI_STATUS, pci_status);
skge_write8(hw, B2_TST_CTRL1, TST_CFG_WRITE_OFF);
/* if error still set then just ignore it */
hwstatus = skge_read32(hw, B0_HWE_ISRC);
if (hwstatus & IS_IRQ_STAT) {
dev_warn(&hw->pdev->dev, "unable to clear error (so ignoring them)\n");
hw->intr_mask &= ~IS_HW_ERR;
}
}
}
/*
* Interrupt from PHY are handled in tasklet (softirq)
* because accessing phy registers requires spin wait which might
* cause excess interrupt latency.
*/
static void skge_extirq(unsigned long arg)
{
struct skge_hw *hw = (struct skge_hw *) arg;
int port;
for (port = 0; port < hw->ports; port++) {
struct net_device *dev = hw->dev[port];
if (netif_running(dev)) {
struct skge_port *skge = netdev_priv(dev);
spin_lock(&hw->phy_lock);
if (!is_genesis(hw))
yukon_phy_intr(skge);
else if (hw->phy_type == SK_PHY_BCOM)
bcom_phy_intr(skge);
spin_unlock(&hw->phy_lock);
}
}
spin_lock_irq(&hw->hw_lock);
hw->intr_mask |= IS_EXT_REG;
skge_write32(hw, B0_IMSK, hw->intr_mask);
skge_read32(hw, B0_IMSK);
spin_unlock_irq(&hw->hw_lock);
}
static irqreturn_t skge_intr(int irq, void *dev_id)
{
struct skge_hw *hw = dev_id;
u32 status;
int handled = 0;
spin_lock(&hw->hw_lock);
/* Reading this register masks IRQ */
status = skge_read32(hw, B0_SP_ISRC);
if (status == 0 || status == ~0)
goto out;
handled = 1;
status &= hw->intr_mask;
if (status & IS_EXT_REG) {
hw->intr_mask &= ~IS_EXT_REG;
tasklet_schedule(&hw->phy_task);
}
if (status & (IS_XA1_F|IS_R1_F)) {
struct skge_port *skge = netdev_priv(hw->dev[0]);
hw->intr_mask &= ~(IS_XA1_F|IS_R1_F);
napi_schedule(&skge->napi);
}
if (status & IS_PA_TO_TX1)
skge_write16(hw, B3_PA_CTRL, PA_CLR_TO_TX1);
if (status & IS_PA_TO_RX1) {
++hw->dev[0]->stats.rx_over_errors;
skge_write16(hw, B3_PA_CTRL, PA_CLR_TO_RX1);
}
if (status & IS_MAC1)
skge_mac_intr(hw, 0);
if (hw->dev[1]) {
struct skge_port *skge = netdev_priv(hw->dev[1]);
if (status & (IS_XA2_F|IS_R2_F)) {
hw->intr_mask &= ~(IS_XA2_F|IS_R2_F);
napi_schedule(&skge->napi);
}
if (status & IS_PA_TO_RX2) {
++hw->dev[1]->stats.rx_over_errors;
skge_write16(hw, B3_PA_CTRL, PA_CLR_TO_RX2);
}
if (status & IS_PA_TO_TX2)
skge_write16(hw, B3_PA_CTRL, PA_CLR_TO_TX2);
if (status & IS_MAC2)
skge_mac_intr(hw, 1);
}
if (status & IS_HW_ERR)
skge_error_irq(hw);
skge_write32(hw, B0_IMSK, hw->intr_mask);
skge_read32(hw, B0_IMSK);
out:
spin_unlock(&hw->hw_lock);
return IRQ_RETVAL(handled);
}
#ifdef CONFIG_NET_POLL_CONTROLLER
static void skge_netpoll(struct net_device *dev)
{
struct skge_port *skge = netdev_priv(dev);
disable_irq(dev->irq);
skge_intr(dev->irq, skge->hw);
enable_irq(dev->irq);
}
#endif
static int skge_set_mac_address(struct net_device *dev, void *p)
{
struct skge_port *skge = netdev_priv(dev);
struct skge_hw *hw = skge->hw;
unsigned port = skge->port;
const struct sockaddr *addr = p;
u16 ctrl;
if (!is_valid_ether_addr(addr->sa_data))
return -EADDRNOTAVAIL;
memcpy(dev->dev_addr, addr->sa_data, ETH_ALEN);
if (!netif_running(dev)) {
memcpy_toio(hw->regs + B2_MAC_1 + port*8, dev->dev_addr, ETH_ALEN);
memcpy_toio(hw->regs + B2_MAC_2 + port*8, dev->dev_addr, ETH_ALEN);
} else {
/* disable Rx */
spin_lock_bh(&hw->phy_lock);
ctrl = gma_read16(hw, port, GM_GP_CTRL);
gma_write16(hw, port, GM_GP_CTRL, ctrl & ~GM_GPCR_RX_ENA);
memcpy_toio(hw->regs + B2_MAC_1 + port*8, dev->dev_addr, ETH_ALEN);
memcpy_toio(hw->regs + B2_MAC_2 + port*8, dev->dev_addr, ETH_ALEN);
if (is_genesis(hw))
xm_outaddr(hw, port, XM_SA, dev->dev_addr);
else {
gma_set_addr(hw, port, GM_SRC_ADDR_1L, dev->dev_addr);
gma_set_addr(hw, port, GM_SRC_ADDR_2L, dev->dev_addr);
}
gma_write16(hw, port, GM_GP_CTRL, ctrl);
spin_unlock_bh(&hw->phy_lock);
}
return 0;
}
static const struct {
u8 id;
const char *name;
} skge_chips[] = {
{ CHIP_ID_GENESIS, "Genesis" },
{ CHIP_ID_YUKON, "Yukon" },
{ CHIP_ID_YUKON_LITE, "Yukon-Lite"},
{ CHIP_ID_YUKON_LP, "Yukon-LP"},
};
static const char *skge_board_name(const struct skge_hw *hw)
{
int i;
static char buf[16];
for (i = 0; i < ARRAY_SIZE(skge_chips); i++)
if (skge_chips[i].id == hw->chip_id)
return skge_chips[i].name;
snprintf(buf, sizeof buf, "chipid 0x%x", hw->chip_id);
return buf;
}
/*
* Setup the board data structure, but don't bring up
* the port(s)
*/
static int skge_reset(struct skge_hw *hw)
{
u32 reg;
u16 ctst, pci_status;
u8 t8, mac_cfg, pmd_type;
int i;
ctst = skge_read16(hw, B0_CTST);
/* do a SW reset */
skge_write8(hw, B0_CTST, CS_RST_SET);
skge_write8(hw, B0_CTST, CS_RST_CLR);
/* clear PCI errors, if any */
skge_write8(hw, B2_TST_CTRL1, TST_CFG_WRITE_ON);
skge_write8(hw, B2_TST_CTRL2, 0);
pci_read_config_word(hw->pdev, PCI_STATUS, &pci_status);
pci_write_config_word(hw->pdev, PCI_STATUS,
pci_status | PCI_STATUS_ERROR_BITS);
skge_write8(hw, B2_TST_CTRL1, TST_CFG_WRITE_OFF);
skge_write8(hw, B0_CTST, CS_MRST_CLR);
/* restore CLK_RUN bits (for Yukon-Lite) */
skge_write16(hw, B0_CTST,
ctst & (CS_CLK_RUN_HOT|CS_CLK_RUN_RST|CS_CLK_RUN_ENA));
hw->chip_id = skge_read8(hw, B2_CHIP_ID);
hw->phy_type = skge_read8(hw, B2_E_1) & 0xf;
pmd_type = skge_read8(hw, B2_PMD_TYP);
hw->copper = (pmd_type == 'T' || pmd_type == '1');
switch (hw->chip_id) {
case CHIP_ID_GENESIS:
#ifdef CONFIG_SKGE_GENESIS
switch (hw->phy_type) {
case SK_PHY_XMAC:
hw->phy_addr = PHY_ADDR_XMAC;
break;
case SK_PHY_BCOM:
hw->phy_addr = PHY_ADDR_BCOM;
break;
default:
dev_err(&hw->pdev->dev, "unsupported phy type 0x%x\n",
hw->phy_type);
return -EOPNOTSUPP;
}
break;
#else
dev_err(&hw->pdev->dev, "Genesis chip detected but not configured\n");
return -EOPNOTSUPP;
#endif
case CHIP_ID_YUKON:
case CHIP_ID_YUKON_LITE:
case CHIP_ID_YUKON_LP:
if (hw->phy_type < SK_PHY_MARV_COPPER && pmd_type != 'S')
hw->copper = 1;
hw->phy_addr = PHY_ADDR_MARV;
break;
default:
dev_err(&hw->pdev->dev, "unsupported chip type 0x%x\n",
hw->chip_id);
return -EOPNOTSUPP;
}
mac_cfg = skge_read8(hw, B2_MAC_CFG);
hw->ports = (mac_cfg & CFG_SNG_MAC) ? 1 : 2;
hw->chip_rev = (mac_cfg & CFG_CHIP_R_MSK) >> 4;
/* read the adapters RAM size */
t8 = skge_read8(hw, B2_E_0);
if (is_genesis(hw)) {
if (t8 == 3) {
/* special case: 4 x 64k x 36, offset = 0x80000 */
hw->ram_size = 0x100000;
hw->ram_offset = 0x80000;
} else
hw->ram_size = t8 * 512;
} else if (t8 == 0)
hw->ram_size = 0x20000;
else
hw->ram_size = t8 * 4096;
hw->intr_mask = IS_HW_ERR;
/* Use PHY IRQ for all but fiber based Genesis board */
if (!(is_genesis(hw) && hw->phy_type == SK_PHY_XMAC))
hw->intr_mask |= IS_EXT_REG;
if (is_genesis(hw))
genesis_init(hw);
else {
/* switch power to VCC (WA for VAUX problem) */
skge_write8(hw, B0_POWER_CTRL,
PC_VAUX_ENA | PC_VCC_ENA | PC_VAUX_OFF | PC_VCC_ON);
/* avoid boards with stuck Hardware error bits */
if ((skge_read32(hw, B0_ISRC) & IS_HW_ERR) &&
(skge_read32(hw, B0_HWE_ISRC) & IS_IRQ_SENSOR)) {
dev_warn(&hw->pdev->dev, "stuck hardware sensor bit\n");
hw->intr_mask &= ~IS_HW_ERR;
}
/* Clear PHY COMA */
skge_write8(hw, B2_TST_CTRL1, TST_CFG_WRITE_ON);
pci_read_config_dword(hw->pdev, PCI_DEV_REG1, ®);
reg &= ~PCI_PHY_COMA;
pci_write_config_dword(hw->pdev, PCI_DEV_REG1, reg);
skge_write8(hw, B2_TST_CTRL1, TST_CFG_WRITE_OFF);
for (i = 0; i < hw->ports; i++) {
skge_write16(hw, SK_REG(i, GMAC_LINK_CTRL), GMLC_RST_SET);
skge_write16(hw, SK_REG(i, GMAC_LINK_CTRL), GMLC_RST_CLR);
}
}
/* turn off hardware timer (unused) */
skge_write8(hw, B2_TI_CTRL, TIM_STOP);
skge_write8(hw, B2_TI_CTRL, TIM_CLR_IRQ);
skge_write8(hw, B0_LED, LED_STAT_ON);
/* enable the Tx Arbiters */
for (i = 0; i < hw->ports; i++)
skge_write8(hw, SK_REG(i, TXA_CTRL), TXA_ENA_ARB);
/* Initialize ram interface */
skge_write16(hw, B3_RI_CTRL, RI_RST_CLR);
skge_write8(hw, B3_RI_WTO_R1, SK_RI_TO_53);
skge_write8(hw, B3_RI_WTO_XA1, SK_RI_TO_53);
skge_write8(hw, B3_RI_WTO_XS1, SK_RI_TO_53);
skge_write8(hw, B3_RI_RTO_R1, SK_RI_TO_53);
skge_write8(hw, B3_RI_RTO_XA1, SK_RI_TO_53);
skge_write8(hw, B3_RI_RTO_XS1, SK_RI_TO_53);
skge_write8(hw, B3_RI_WTO_R2, SK_RI_TO_53);
skge_write8(hw, B3_RI_WTO_XA2, SK_RI_TO_53);
skge_write8(hw, B3_RI_WTO_XS2, SK_RI_TO_53);
skge_write8(hw, B3_RI_RTO_R2, SK_RI_TO_53);
skge_write8(hw, B3_RI_RTO_XA2, SK_RI_TO_53);
skge_write8(hw, B3_RI_RTO_XS2, SK_RI_TO_53);
skge_write32(hw, B0_HWE_IMSK, IS_ERR_MSK);
/* Set interrupt moderation for Transmit only
* Receive interrupts avoided by NAPI
*/
skge_write32(hw, B2_IRQM_MSK, IS_XA1_F|IS_XA2_F);
skge_write32(hw, B2_IRQM_INI, skge_usecs2clk(hw, 100));
skge_write32(hw, B2_IRQM_CTRL, TIM_START);
/* Leave irq disabled until first port is brought up. */
skge_write32(hw, B0_IMSK, 0);
for (i = 0; i < hw->ports; i++) {
if (is_genesis(hw))
genesis_reset(hw, i);
else
yukon_reset(hw, i);
}
return 0;
}
#ifdef CONFIG_SKGE_DEBUG
static struct dentry *skge_debug;
static int skge_debug_show(struct seq_file *seq, void *v)
{
struct net_device *dev = seq->private;
const struct skge_port *skge = netdev_priv(dev);
const struct skge_hw *hw = skge->hw;
const struct skge_element *e;
if (!netif_running(dev))
return -ENETDOWN;
seq_printf(seq, "IRQ src=%x mask=%x\n", skge_read32(hw, B0_ISRC),
skge_read32(hw, B0_IMSK));
seq_printf(seq, "Tx Ring: (%d)\n", skge_avail(&skge->tx_ring));
for (e = skge->tx_ring.to_clean; e != skge->tx_ring.to_use; e = e->next) {
const struct skge_tx_desc *t = e->desc;
seq_printf(seq, "%#x dma=%#x%08x %#x csum=%#x/%x/%x\n",
t->control, t->dma_hi, t->dma_lo, t->status,
t->csum_offs, t->csum_write, t->csum_start);
}
seq_printf(seq, "\nRx Ring:\n");
for (e = skge->rx_ring.to_clean; ; e = e->next) {
const struct skge_rx_desc *r = e->desc;
if (r->control & BMU_OWN)
break;
seq_printf(seq, "%#x dma=%#x%08x %#x %#x csum=%#x/%x\n",
r->control, r->dma_hi, r->dma_lo, r->status,
r->timestamp, r->csum1, r->csum1_start);
}
return 0;
}
static int skge_debug_open(struct inode *inode, struct file *file)
{
return single_open(file, skge_debug_show, inode->i_private);
}
static const struct file_operations skge_debug_fops = {
.owner = THIS_MODULE,
.open = skge_debug_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
/*
* Use network device events to create/remove/rename
* debugfs file entries
*/
static int skge_device_event(struct notifier_block *unused,
unsigned long event, void *ptr)
{
struct net_device *dev = ptr;
struct skge_port *skge;
struct dentry *d;
if (dev->netdev_ops->ndo_open != &skge_up || !skge_debug)
goto done;
skge = netdev_priv(dev);
switch (event) {
case NETDEV_CHANGENAME:
if (skge->debugfs) {
d = debugfs_rename(skge_debug, skge->debugfs,
skge_debug, dev->name);
if (d)
skge->debugfs = d;
else {
netdev_info(dev, "rename failed\n");
debugfs_remove(skge->debugfs);
}
}
break;
case NETDEV_GOING_DOWN:
if (skge->debugfs) {
debugfs_remove(skge->debugfs);
skge->debugfs = NULL;
}
break;
case NETDEV_UP:
d = debugfs_create_file(dev->name, S_IRUGO,
skge_debug, dev,
&skge_debug_fops);
if (!d || IS_ERR(d))
netdev_info(dev, "debugfs create failed\n");
else
skge->debugfs = d;
break;
}
done:
return NOTIFY_DONE;
}
static struct notifier_block skge_notifier = {
.notifier_call = skge_device_event,
};
static __init void skge_debug_init(void)
{
struct dentry *ent;
ent = debugfs_create_dir("skge", NULL);
if (!ent || IS_ERR(ent)) {
pr_info("debugfs create directory failed\n");
return;
}
skge_debug = ent;
register_netdevice_notifier(&skge_notifier);
}
static __exit void skge_debug_cleanup(void)
{
if (skge_debug) {
unregister_netdevice_notifier(&skge_notifier);
debugfs_remove(skge_debug);
skge_debug = NULL;
}
}
#else
#define skge_debug_init()
#define skge_debug_cleanup()
#endif
static const struct net_device_ops skge_netdev_ops = {
.ndo_open = skge_up,
.ndo_stop = skge_down,
.ndo_start_xmit = skge_xmit_frame,
.ndo_do_ioctl = skge_ioctl,
.ndo_get_stats = skge_get_stats,
.ndo_tx_timeout = skge_tx_timeout,
.ndo_change_mtu = skge_change_mtu,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_rx_mode = skge_set_multicast,
.ndo_set_mac_address = skge_set_mac_address,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = skge_netpoll,
#endif
};
/* Initialize network device */
static struct net_device *skge_devinit(struct skge_hw *hw, int port,
int highmem)
{
struct skge_port *skge;
struct net_device *dev = alloc_etherdev(sizeof(*skge));
if (!dev)
return NULL;
SET_NETDEV_DEV(dev, &hw->pdev->dev);
dev->netdev_ops = &skge_netdev_ops;
dev->ethtool_ops = &skge_ethtool_ops;
dev->watchdog_timeo = TX_WATCHDOG;
dev->irq = hw->pdev->irq;
if (highmem)
dev->features |= NETIF_F_HIGHDMA;
skge = netdev_priv(dev);
netif_napi_add(dev, &skge->napi, skge_poll, NAPI_WEIGHT);
skge->netdev = dev;
skge->hw = hw;
skge->msg_enable = netif_msg_init(debug, default_msg);
skge->tx_ring.count = DEFAULT_TX_RING_SIZE;
skge->rx_ring.count = DEFAULT_RX_RING_SIZE;
/* Auto speed and flow control */
skge->autoneg = AUTONEG_ENABLE;
skge->flow_control = FLOW_MODE_SYM_OR_REM;
skge->duplex = -1;
skge->speed = -1;
skge->advertising = skge_supported_modes(hw);
if (device_can_wakeup(&hw->pdev->dev)) {
skge->wol = wol_supported(hw) & WAKE_MAGIC;
device_set_wakeup_enable(&hw->pdev->dev, skge->wol);
}
hw->dev[port] = dev;
skge->port = port;
/* Only used for Genesis XMAC */
if (is_genesis(hw))
setup_timer(&skge->link_timer, xm_link_timer, (unsigned long) skge);
else {
dev->hw_features = NETIF_F_IP_CSUM | NETIF_F_SG |
NETIF_F_RXCSUM;
dev->features |= dev->hw_features;
}
/* read the mac address */
memcpy_fromio(dev->dev_addr, hw->regs + B2_MAC_1 + port*8, ETH_ALEN);
return dev;
}
static void skge_show_addr(struct net_device *dev)
{
const struct skge_port *skge = netdev_priv(dev);
netif_info(skge, probe, skge->netdev, "addr %pM\n", dev->dev_addr);
}
static int only_32bit_dma;
static int skge_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
{
struct net_device *dev, *dev1;
struct skge_hw *hw;
int err, using_dac = 0;
err = pci_enable_device(pdev);
if (err) {
dev_err(&pdev->dev, "cannot enable PCI device\n");
goto err_out;
}
err = pci_request_regions(pdev, DRV_NAME);
if (err) {
dev_err(&pdev->dev, "cannot obtain PCI resources\n");
goto err_out_disable_pdev;
}
pci_set_master(pdev);
if (!only_32bit_dma && !pci_set_dma_mask(pdev, DMA_BIT_MASK(64))) {
using_dac = 1;
err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(64));
} else if (!(err = pci_set_dma_mask(pdev, DMA_BIT_MASK(32)))) {
using_dac = 0;
err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32));
}
if (err) {
dev_err(&pdev->dev, "no usable DMA configuration\n");
goto err_out_free_regions;
}
#ifdef __BIG_ENDIAN
/* byte swap descriptors in hardware */
{
u32 reg;
pci_read_config_dword(pdev, PCI_DEV_REG2, ®);
reg |= PCI_REV_DESC;
pci_write_config_dword(pdev, PCI_DEV_REG2, reg);
}
#endif
err = -ENOMEM;
/* space for skge@pci:0000:04:00.0 */
hw = kzalloc(sizeof(*hw) + strlen(DRV_NAME "@pci:")
+ strlen(pci_name(pdev)) + 1, GFP_KERNEL);
if (!hw)
goto err_out_free_regions;
sprintf(hw->irq_name, DRV_NAME "@pci:%s", pci_name(pdev));
hw->pdev = pdev;
spin_lock_init(&hw->hw_lock);
spin_lock_init(&hw->phy_lock);
tasklet_init(&hw->phy_task, skge_extirq, (unsigned long) hw);
hw->regs = ioremap_nocache(pci_resource_start(pdev, 0), 0x4000);
if (!hw->regs) {
dev_err(&pdev->dev, "cannot map device registers\n");
goto err_out_free_hw;
}
err = skge_reset(hw);
if (err)
goto err_out_iounmap;
pr_info("%s addr 0x%llx irq %d chip %s rev %d\n",
DRV_VERSION,
(unsigned long long)pci_resource_start(pdev, 0), pdev->irq,
skge_board_name(hw), hw->chip_rev);
dev = skge_devinit(hw, 0, using_dac);
if (!dev) {
err = -ENOMEM;
goto err_out_led_off;
}
/* Some motherboards are broken and has zero in ROM. */
if (!is_valid_ether_addr(dev->dev_addr))
dev_warn(&pdev->dev, "bad (zero?) ethernet address in rom\n");
err = register_netdev(dev);
if (err) {
dev_err(&pdev->dev, "cannot register net device\n");
goto err_out_free_netdev;
}
skge_show_addr(dev);
if (hw->ports > 1) {
dev1 = skge_devinit(hw, 1, using_dac);
if (!dev1) {
err = -ENOMEM;
goto err_out_unregister;
}
err = register_netdev(dev1);
if (err) {
dev_err(&pdev->dev, "cannot register second net device\n");
goto err_out_free_dev1;
}
err = request_irq(pdev->irq, skge_intr, IRQF_SHARED,
hw->irq_name, hw);
if (err) {
dev_err(&pdev->dev, "cannot assign irq %d\n",
pdev->irq);
goto err_out_unregister_dev1;
}
skge_show_addr(dev1);
}
pci_set_drvdata(pdev, hw);
return 0;
err_out_unregister_dev1:
unregister_netdev(dev1);
err_out_free_dev1:
free_netdev(dev1);
err_out_unregister:
unregister_netdev(dev);
err_out_free_netdev:
free_netdev(dev);
err_out_led_off:
skge_write16(hw, B0_LED, LED_STAT_OFF);
err_out_iounmap:
iounmap(hw->regs);
err_out_free_hw:
kfree(hw);
err_out_free_regions:
pci_release_regions(pdev);
err_out_disable_pdev:
pci_disable_device(pdev);
pci_set_drvdata(pdev, NULL);
err_out:
return err;
}
static void skge_remove(struct pci_dev *pdev)
{
struct skge_hw *hw = pci_get_drvdata(pdev);
struct net_device *dev0, *dev1;
if (!hw)
return;
dev1 = hw->dev[1];
if (dev1)
unregister_netdev(dev1);
dev0 = hw->dev[0];
unregister_netdev(dev0);
tasklet_kill(&hw->phy_task);
spin_lock_irq(&hw->hw_lock);
hw->intr_mask = 0;
if (hw->ports > 1) {
skge_write32(hw, B0_IMSK, 0);
skge_read32(hw, B0_IMSK);
free_irq(pdev->irq, hw);
}
spin_unlock_irq(&hw->hw_lock);
skge_write16(hw, B0_LED, LED_STAT_OFF);
skge_write8(hw, B0_CTST, CS_RST_SET);
if (hw->ports > 1)
free_irq(pdev->irq, hw);
pci_release_regions(pdev);
pci_disable_device(pdev);
if (dev1)
free_netdev(dev1);
free_netdev(dev0);
iounmap(hw->regs);
kfree(hw);
pci_set_drvdata(pdev, NULL);
}
#ifdef CONFIG_PM_SLEEP
static int skge_suspend(struct device *dev)
{
struct pci_dev *pdev = to_pci_dev(dev);
struct skge_hw *hw = pci_get_drvdata(pdev);
int i;
if (!hw)
return 0;
for (i = 0; i < hw->ports; i++) {
struct net_device *dev = hw->dev[i];
struct skge_port *skge = netdev_priv(dev);
if (netif_running(dev))
skge_down(dev);
if (skge->wol)
skge_wol_init(skge);
}
skge_write32(hw, B0_IMSK, 0);
return 0;
}
static int skge_resume(struct device *dev)
{
struct pci_dev *pdev = to_pci_dev(dev);
struct skge_hw *hw = pci_get_drvdata(pdev);
int i, err;
if (!hw)
return 0;
err = skge_reset(hw);
if (err)
goto out;
for (i = 0; i < hw->ports; i++) {
struct net_device *dev = hw->dev[i];
if (netif_running(dev)) {
err = skge_up(dev);
if (err) {
netdev_err(dev, "could not up: %d\n", err);
dev_close(dev);
goto out;
}
}
}
out:
return err;
}
static SIMPLE_DEV_PM_OPS(skge_pm_ops, skge_suspend, skge_resume);
#define SKGE_PM_OPS (&skge_pm_ops)
#else
#define SKGE_PM_OPS NULL
#endif /* CONFIG_PM_SLEEP */
static void skge_shutdown(struct pci_dev *pdev)
{
struct skge_hw *hw = pci_get_drvdata(pdev);
int i;
if (!hw)
return;
for (i = 0; i < hw->ports; i++) {
struct net_device *dev = hw->dev[i];
struct skge_port *skge = netdev_priv(dev);
if (skge->wol)
skge_wol_init(skge);
}
pci_wake_from_d3(pdev, device_may_wakeup(&pdev->dev));
pci_set_power_state(pdev, PCI_D3hot);
}
static struct pci_driver skge_driver = {
.name = DRV_NAME,
.id_table = skge_id_table,
.probe = skge_probe,
.remove = skge_remove,
.shutdown = skge_shutdown,
.driver.pm = SKGE_PM_OPS,
};
static struct dmi_system_id skge_32bit_dma_boards[] = {
{
.ident = "Gigabyte nForce boards",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Gigabyte Technology Co"),
DMI_MATCH(DMI_BOARD_NAME, "nForce"),
},
},
{
.ident = "ASUS P5NSLI",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "ASUSTeK Computer INC."),
DMI_MATCH(DMI_BOARD_NAME, "P5NSLI")
},
},
{}
};
static int __init skge_init_module(void)
{
if (dmi_check_system(skge_32bit_dma_boards))
only_32bit_dma = 1;
skge_debug_init();
return pci_register_driver(&skge_driver);
}
static void __exit skge_cleanup_module(void)
{
pci_unregister_driver(&skge_driver);
skge_debug_cleanup();
}
module_init(skge_init_module);
module_exit(skge_cleanup_module);
| gpl-2.0 |
F4uzan/f4kernel_sprout | drivers/watchdog/pnx4008_wdt.c | 2144 | 6270 | /*
* drivers/char/watchdog/pnx4008_wdt.c
*
* Watchdog driver for PNX4008 board
*
* Authors: Dmitry Chigirev <source@mvista.com>,
* Vitaly Wool <vitalywool@gmail.com>
* Based on sa1100 driver,
* Copyright (C) 2000 Oleg Drokin <green@crimea.edu>
*
* 2005-2006 (c) MontaVista Software, Inc.
*
* (C) 2012 Wolfram Sang, Pengutronix
*
* This file is licensed under the terms of the GNU General Public License
* version 2. This program is licensed "as is" without any warranty of any
* kind, whether express or implied.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/miscdevice.h>
#include <linux/watchdog.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/clk.h>
#include <linux/spinlock.h>
#include <linux/io.h>
#include <linux/slab.h>
#include <linux/err.h>
#include <linux/of.h>
#include <mach/hardware.h>
/* WatchDog Timer - Chapter 23 Page 207 */
#define DEFAULT_HEARTBEAT 19
#define MAX_HEARTBEAT 60
/* Watchdog timer register set definition */
#define WDTIM_INT(p) ((p) + 0x0)
#define WDTIM_CTRL(p) ((p) + 0x4)
#define WDTIM_COUNTER(p) ((p) + 0x8)
#define WDTIM_MCTRL(p) ((p) + 0xC)
#define WDTIM_MATCH0(p) ((p) + 0x10)
#define WDTIM_EMR(p) ((p) + 0x14)
#define WDTIM_PULSE(p) ((p) + 0x18)
#define WDTIM_RES(p) ((p) + 0x1C)
/* WDTIM_INT bit definitions */
#define MATCH_INT 1
/* WDTIM_CTRL bit definitions */
#define COUNT_ENAB 1
#define RESET_COUNT (1 << 1)
#define DEBUG_EN (1 << 2)
/* WDTIM_MCTRL bit definitions */
#define MR0_INT 1
#undef RESET_COUNT0
#define RESET_COUNT0 (1 << 2)
#define STOP_COUNT0 (1 << 2)
#define M_RES1 (1 << 3)
#define M_RES2 (1 << 4)
#define RESFRC1 (1 << 5)
#define RESFRC2 (1 << 6)
/* WDTIM_EMR bit definitions */
#define EXT_MATCH0 1
#define MATCH_OUTPUT_HIGH (2 << 4) /*a MATCH_CTRL setting */
/* WDTIM_RES bit definitions */
#define WDOG_RESET 1 /* read only */
#define WDOG_COUNTER_RATE 13000000 /*the counter clock is 13 MHz fixed */
static bool nowayout = WATCHDOG_NOWAYOUT;
static unsigned int heartbeat = DEFAULT_HEARTBEAT;
static DEFINE_SPINLOCK(io_lock);
static void __iomem *wdt_base;
struct clk *wdt_clk;
static int pnx4008_wdt_start(struct watchdog_device *wdd)
{
spin_lock(&io_lock);
/* stop counter, initiate counter reset */
writel(RESET_COUNT, WDTIM_CTRL(wdt_base));
/*wait for reset to complete. 100% guarantee event */
while (readl(WDTIM_COUNTER(wdt_base)))
cpu_relax();
/* internal and external reset, stop after that */
writel(M_RES2 | STOP_COUNT0 | RESET_COUNT0, WDTIM_MCTRL(wdt_base));
/* configure match output */
writel(MATCH_OUTPUT_HIGH, WDTIM_EMR(wdt_base));
/* clear interrupt, just in case */
writel(MATCH_INT, WDTIM_INT(wdt_base));
/* the longest pulse period 65541/(13*10^6) seconds ~ 5 ms. */
writel(0xFFFF, WDTIM_PULSE(wdt_base));
writel(wdd->timeout * WDOG_COUNTER_RATE, WDTIM_MATCH0(wdt_base));
/*enable counter, stop when debugger active */
writel(COUNT_ENAB | DEBUG_EN, WDTIM_CTRL(wdt_base));
spin_unlock(&io_lock);
return 0;
}
static int pnx4008_wdt_stop(struct watchdog_device *wdd)
{
spin_lock(&io_lock);
writel(0, WDTIM_CTRL(wdt_base)); /*stop counter */
spin_unlock(&io_lock);
return 0;
}
static int pnx4008_wdt_set_timeout(struct watchdog_device *wdd,
unsigned int new_timeout)
{
wdd->timeout = new_timeout;
return 0;
}
static const struct watchdog_info pnx4008_wdt_ident = {
.options = WDIOF_CARDRESET | WDIOF_MAGICCLOSE |
WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING,
.identity = "PNX4008 Watchdog",
};
static const struct watchdog_ops pnx4008_wdt_ops = {
.owner = THIS_MODULE,
.start = pnx4008_wdt_start,
.stop = pnx4008_wdt_stop,
.set_timeout = pnx4008_wdt_set_timeout,
};
static struct watchdog_device pnx4008_wdd = {
.info = &pnx4008_wdt_ident,
.ops = &pnx4008_wdt_ops,
.timeout = DEFAULT_HEARTBEAT,
.min_timeout = 1,
.max_timeout = MAX_HEARTBEAT,
};
static int pnx4008_wdt_probe(struct platform_device *pdev)
{
struct resource *r;
int ret = 0;
watchdog_init_timeout(&pnx4008_wdd, heartbeat, &pdev->dev);
r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
wdt_base = devm_ioremap_resource(&pdev->dev, r);
if (IS_ERR(wdt_base))
return PTR_ERR(wdt_base);
wdt_clk = clk_get(&pdev->dev, NULL);
if (IS_ERR(wdt_clk))
return PTR_ERR(wdt_clk);
ret = clk_enable(wdt_clk);
if (ret)
goto out;
pnx4008_wdd.bootstatus = (readl(WDTIM_RES(wdt_base)) & WDOG_RESET) ?
WDIOF_CARDRESET : 0;
watchdog_set_nowayout(&pnx4008_wdd, nowayout);
pnx4008_wdt_stop(&pnx4008_wdd); /* disable for now */
ret = watchdog_register_device(&pnx4008_wdd);
if (ret < 0) {
dev_err(&pdev->dev, "cannot register watchdog device\n");
goto disable_clk;
}
dev_info(&pdev->dev, "PNX4008 Watchdog Timer: heartbeat %d sec\n",
pnx4008_wdd.timeout);
return 0;
disable_clk:
clk_disable(wdt_clk);
out:
clk_put(wdt_clk);
return ret;
}
static int pnx4008_wdt_remove(struct platform_device *pdev)
{
watchdog_unregister_device(&pnx4008_wdd);
clk_disable(wdt_clk);
clk_put(wdt_clk);
return 0;
}
#ifdef CONFIG_OF
static const struct of_device_id pnx4008_wdt_match[] = {
{ .compatible = "nxp,pnx4008-wdt" },
{ }
};
MODULE_DEVICE_TABLE(of, pnx4008_wdt_match);
#endif
static struct platform_driver platform_wdt_driver = {
.driver = {
.name = "pnx4008-watchdog",
.owner = THIS_MODULE,
.of_match_table = of_match_ptr(pnx4008_wdt_match),
},
.probe = pnx4008_wdt_probe,
.remove = pnx4008_wdt_remove,
};
module_platform_driver(platform_wdt_driver);
MODULE_AUTHOR("MontaVista Software, Inc. <source@mvista.com>");
MODULE_AUTHOR("Wolfram Sang <w.sang@pengutronix.de>");
MODULE_DESCRIPTION("PNX4008 Watchdog Driver");
module_param(heartbeat, uint, 0);
MODULE_PARM_DESC(heartbeat,
"Watchdog heartbeat period in seconds from 1 to "
__MODULE_STRING(MAX_HEARTBEAT) ", default "
__MODULE_STRING(DEFAULT_HEARTBEAT));
module_param(nowayout, bool, 0);
MODULE_PARM_DESC(nowayout,
"Set to 1 to keep watchdog running after device release");
MODULE_LICENSE("GPL");
MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR);
MODULE_ALIAS("platform:pnx4008-watchdog");
| gpl-2.0 |
kernelhackx/kernel_hammerhead | drivers/staging/bcm/InterfaceInit.c | 4192 | 23784 | #include "headers.h"
static struct usb_device_id InterfaceUsbtable[] = {
{ USB_DEVICE(BCM_USB_VENDOR_ID_T3, BCM_USB_PRODUCT_ID_T3) },
{ USB_DEVICE(BCM_USB_VENDOR_ID_T3, BCM_USB_PRODUCT_ID_T3B) },
{ USB_DEVICE(BCM_USB_VENDOR_ID_T3, BCM_USB_PRODUCT_ID_T3L) },
{ USB_DEVICE(BCM_USB_VENDOR_ID_T3, BCM_USB_PRODUCT_ID_SM250) },
{ USB_DEVICE(BCM_USB_VENDOR_ID_ZTE, BCM_USB_PRODUCT_ID_226) },
{ USB_DEVICE(BCM_USB_VENDOR_ID_FOXCONN, BCM_USB_PRODUCT_ID_1901) },
{ USB_DEVICE(BCM_USB_VENDOR_ID_ZTE, BCM_USB_PRODUCT_ID_ZTE_TU25) },
{ }
};
MODULE_DEVICE_TABLE(usb, InterfaceUsbtable);
static int debug = -1;
module_param(debug, uint, 0600);
MODULE_PARM_DESC(debug, "Debug level (0=none,...,16=all)");
static const u32 default_msg =
NETIF_MSG_DRV | NETIF_MSG_PROBE | NETIF_MSG_LINK
| NETIF_MSG_TIMER | NETIF_MSG_TX_ERR | NETIF_MSG_RX_ERR
| NETIF_MSG_IFUP | NETIF_MSG_IFDOWN;
static int InterfaceAdapterInit(PS_INTERFACE_ADAPTER Adapter);
static void InterfaceAdapterFree(PS_INTERFACE_ADAPTER psIntfAdapter)
{
int i = 0;
/* Wake up the wait_queue... */
if (psIntfAdapter->psAdapter->LEDInfo.led_thread_running & BCM_LED_THREAD_RUNNING_ACTIVELY) {
psIntfAdapter->psAdapter->DriverState = DRIVER_HALT;
wake_up(&psIntfAdapter->psAdapter->LEDInfo.notify_led_event);
}
reset_card_proc(psIntfAdapter->psAdapter);
/*
* worst case time taken by the RDM/WRM will be 5 sec. will check after every 100 ms
* to accertain the device is not being accessed. After this No RDM/WRM should be made.
*/
while (psIntfAdapter->psAdapter->DeviceAccess) {
BCM_DEBUG_PRINT(psIntfAdapter->psAdapter, DBG_TYPE_INITEXIT, DRV_ENTRY, DBG_LVL_ALL,
"Device is being accessed.\n");
msleep(100);
}
/* Free interrupt URB */
/* psIntfAdapter->psAdapter->device_removed = TRUE; */
usb_free_urb(psIntfAdapter->psInterruptUrb);
/* Free transmit URBs */
for (i = 0; i < MAXIMUM_USB_TCB; i++) {
if (psIntfAdapter->asUsbTcb[i].urb != NULL) {
usb_free_urb(psIntfAdapter->asUsbTcb[i].urb);
psIntfAdapter->asUsbTcb[i].urb = NULL;
}
}
/* Free receive URB and buffers */
for (i = 0; i < MAXIMUM_USB_RCB; i++) {
if (psIntfAdapter->asUsbRcb[i].urb != NULL) {
kfree(psIntfAdapter->asUsbRcb[i].urb->transfer_buffer);
usb_free_urb(psIntfAdapter->asUsbRcb[i].urb);
psIntfAdapter->asUsbRcb[i].urb = NULL;
}
}
AdapterFree(psIntfAdapter->psAdapter);
}
static void ConfigureEndPointTypesThroughEEPROM(PMINI_ADAPTER Adapter)
{
unsigned long ulReg = 0;
int bytes;
/* Program EP2 MAX_PKT_SIZE */
ulReg = ntohl(EP2_MPS_REG);
BeceemEEPROMBulkWrite(Adapter, (PUCHAR)&ulReg, 0x128, 4, TRUE);
ulReg = ntohl(EP2_MPS);
BeceemEEPROMBulkWrite(Adapter, (PUCHAR)&ulReg, 0x12C, 4, TRUE);
ulReg = ntohl(EP2_CFG_REG);
BeceemEEPROMBulkWrite(Adapter, (PUCHAR)&ulReg, 0x132, 4, TRUE);
if (((PS_INTERFACE_ADAPTER)(Adapter->pvInterfaceAdapter))->bHighSpeedDevice == TRUE) {
ulReg = ntohl(EP2_CFG_INT);
BeceemEEPROMBulkWrite(Adapter, (PUCHAR)&ulReg, 0x136, 4, TRUE);
} else {
/* USE BULK EP as TX in FS mode. */
ulReg = ntohl(EP2_CFG_BULK);
BeceemEEPROMBulkWrite(Adapter, (PUCHAR)&ulReg, 0x136, 4, TRUE);
}
/* Program EP4 MAX_PKT_SIZE. */
ulReg = ntohl(EP4_MPS_REG);
BeceemEEPROMBulkWrite(Adapter, (PUCHAR)&ulReg, 0x13C, 4, TRUE);
ulReg = ntohl(EP4_MPS);
BeceemEEPROMBulkWrite(Adapter, (PUCHAR)&ulReg, 0x140, 4, TRUE);
/* Program TX EP as interrupt(Alternate Setting) */
bytes = rdmalt(Adapter, 0x0F0110F8, (u32 *)&ulReg, sizeof(u32));
if (bytes < 0) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_INITEXIT, DRV_ENTRY, DBG_LVL_ALL,
"reading of Tx EP failed\n");
return;
}
ulReg |= 0x6;
ulReg = ntohl(ulReg);
BeceemEEPROMBulkWrite(Adapter, (PUCHAR)&ulReg, 0x1CC, 4, TRUE);
ulReg = ntohl(EP4_CFG_REG);
BeceemEEPROMBulkWrite(Adapter, (PUCHAR)&ulReg, 0x1C8, 4, TRUE);
/* Program ISOCHRONOUS EP size to zero. */
ulReg = ntohl(ISO_MPS_REG);
BeceemEEPROMBulkWrite(Adapter, (PUCHAR)&ulReg, 0x1D2, 4, TRUE);
ulReg = ntohl(ISO_MPS);
BeceemEEPROMBulkWrite(Adapter, (PUCHAR)&ulReg, 0x1D6, 4, TRUE);
/*
* Update EEPROM Version.
* Read 4 bytes from 508 and modify 511 and 510.
*/
ReadBeceemEEPROM(Adapter, 0x1FC, (PUINT)&ulReg);
ulReg &= 0x0101FFFF;
BeceemEEPROMBulkWrite(Adapter, (PUCHAR)&ulReg, 0x1FC, 4, TRUE);
/* Update length field if required. Also make the string NULL terminated. */
ReadBeceemEEPROM(Adapter, 0xA8, (PUINT)&ulReg);
if ((ulReg&0x00FF0000)>>16 > 0x30) {
ulReg = (ulReg&0xFF00FFFF)|(0x30<<16);
BeceemEEPROMBulkWrite(Adapter, (PUCHAR)&ulReg, 0xA8, 4, TRUE);
}
ReadBeceemEEPROM(Adapter, 0x148, (PUINT)&ulReg);
if ((ulReg&0x00FF0000)>>16 > 0x30) {
ulReg = (ulReg&0xFF00FFFF)|(0x30<<16);
BeceemEEPROMBulkWrite(Adapter, (PUCHAR)&ulReg, 0x148, 4, TRUE);
}
ulReg = 0;
BeceemEEPROMBulkWrite(Adapter, (PUCHAR)&ulReg, 0x122, 4, TRUE);
ulReg = 0;
BeceemEEPROMBulkWrite(Adapter, (PUCHAR)&ulReg, 0x1C2, 4, TRUE);
}
static int usbbcm_device_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
struct usb_device *udev = interface_to_usbdev(intf);
int retval;
PMINI_ADAPTER psAdapter;
PS_INTERFACE_ADAPTER psIntfAdapter;
struct net_device *ndev;
/* Reserve one extra queue for the bit-bucket */
ndev = alloc_etherdev_mq(sizeof(MINI_ADAPTER), NO_OF_QUEUES+1);
if (ndev == NULL) {
dev_err(&udev->dev, DRV_NAME ": no memory for device\n");
return -ENOMEM;
}
SET_NETDEV_DEV(ndev, &intf->dev);
psAdapter = netdev_priv(ndev);
psAdapter->dev = ndev;
psAdapter->msg_enable = netif_msg_init(debug, default_msg);
/* Init default driver debug state */
psAdapter->stDebugState.debug_level = DBG_LVL_CURR;
psAdapter->stDebugState.type = DBG_TYPE_INITEXIT;
/*
* Technically, one can start using BCM_DEBUG_PRINT after this point.
* However, realize that by default the Type/Subtype bitmaps are all zero now;
* so no prints will actually appear until the TestApp turns on debug paths via
* the ioctl(); so practically speaking, in early init, no logging happens.
*
* A solution (used below): we explicitly set the bitmaps to 1 for Type=DBG_TYPE_INITEXIT
* and ALL subtype's of the same. Now all bcm debug statements get logged, enabling debug
* during early init.
* Further, we turn this OFF once init_module() completes.
*/
psAdapter->stDebugState.subtype[DBG_TYPE_INITEXIT] = 0xff;
BCM_SHOW_DEBUG_BITMAP(psAdapter);
retval = InitAdapter(psAdapter);
if (retval) {
dev_err(&udev->dev, DRV_NAME ": InitAdapter Failed\n");
AdapterFree(psAdapter);
return retval;
}
/* Allocate interface adapter structure */
psIntfAdapter = kzalloc(sizeof(S_INTERFACE_ADAPTER), GFP_KERNEL);
if (psIntfAdapter == NULL) {
dev_err(&udev->dev, DRV_NAME ": no memory for Interface adapter\n");
AdapterFree(psAdapter);
return -ENOMEM;
}
psAdapter->pvInterfaceAdapter = psIntfAdapter;
psIntfAdapter->psAdapter = psAdapter;
/* Store usb interface in Interface Adapter */
psIntfAdapter->interface = intf;
usb_set_intfdata(intf, psIntfAdapter);
BCM_DEBUG_PRINT(psAdapter, DBG_TYPE_INITEXIT, DRV_ENTRY, DBG_LVL_ALL,
"psIntfAdapter 0x%p\n", psIntfAdapter);
retval = InterfaceAdapterInit(psIntfAdapter);
if (retval) {
/* If the Firmware/Cfg File is not present
* then return success, let the application
* download the files.
*/
if (-ENOENT == retval) {
BCM_DEBUG_PRINT(psAdapter, DBG_TYPE_INITEXIT, DRV_ENTRY, DBG_LVL_ALL,
"File Not Found. Use app to download.\n");
return STATUS_SUCCESS;
}
BCM_DEBUG_PRINT(psAdapter, DBG_TYPE_INITEXIT, DRV_ENTRY, DBG_LVL_ALL,
"InterfaceAdapterInit failed.\n");
usb_set_intfdata(intf, NULL);
udev = interface_to_usbdev(intf);
usb_put_dev(udev);
InterfaceAdapterFree(psIntfAdapter);
return retval;
}
if (psAdapter->chip_id > T3) {
uint32_t uiNackZeroLengthInt = 4;
retval = wrmalt(psAdapter, DISABLE_USB_ZERO_LEN_INT, &uiNackZeroLengthInt, sizeof(uiNackZeroLengthInt));
if (retval)
return retval;
}
/* Check whether the USB-Device Supports remote Wake-Up */
if (USB_CONFIG_ATT_WAKEUP & udev->actconfig->desc.bmAttributes) {
/* If Suspend then only support dynamic suspend */
if (psAdapter->bDoSuspend) {
#ifdef CONFIG_PM
pm_runtime_set_autosuspend_delay(&udev->dev, 0);
intf->needs_remote_wakeup = 1;
usb_enable_autosuspend(udev);
device_init_wakeup(&intf->dev, 1);
INIT_WORK(&psIntfAdapter->usbSuspendWork, putUsbSuspend);
BCM_DEBUG_PRINT(psAdapter, DBG_TYPE_INITEXIT, DRV_ENTRY, DBG_LVL_ALL,
"Enabling USB Auto-Suspend\n");
#endif
} else {
intf->needs_remote_wakeup = 0;
usb_disable_autosuspend(udev);
}
}
psAdapter->stDebugState.subtype[DBG_TYPE_INITEXIT] = 0x0;
return retval;
}
static void usbbcm_disconnect(struct usb_interface *intf)
{
PS_INTERFACE_ADAPTER psIntfAdapter = usb_get_intfdata(intf);
PMINI_ADAPTER psAdapter;
struct usb_device *udev = interface_to_usbdev(intf);
if (psIntfAdapter == NULL)
return;
psAdapter = psIntfAdapter->psAdapter;
netif_device_detach(psAdapter->dev);
if (psAdapter->bDoSuspend)
intf->needs_remote_wakeup = 0;
psAdapter->device_removed = TRUE ;
usb_set_intfdata(intf, NULL);
InterfaceAdapterFree(psIntfAdapter);
usb_put_dev(udev);
}
static int AllocUsbCb(PS_INTERFACE_ADAPTER psIntfAdapter)
{
int i = 0;
for (i = 0; i < MAXIMUM_USB_TCB; i++) {
psIntfAdapter->asUsbTcb[i].urb = usb_alloc_urb(0, GFP_KERNEL);
if (psIntfAdapter->asUsbTcb[i].urb == NULL) {
BCM_DEBUG_PRINT(psIntfAdapter->psAdapter, DBG_TYPE_PRINTK, 0, 0,
"Can't allocate Tx urb for index %d\n", i);
return -ENOMEM;
}
}
for (i = 0; i < MAXIMUM_USB_RCB; i++) {
psIntfAdapter->asUsbRcb[i].urb = usb_alloc_urb(0, GFP_KERNEL);
if (psIntfAdapter->asUsbRcb[i].urb == NULL) {
BCM_DEBUG_PRINT(psIntfAdapter->psAdapter, DBG_TYPE_PRINTK, 0, 0,
"Can't allocate Rx urb for index %d\n", i);
return -ENOMEM;
}
psIntfAdapter->asUsbRcb[i].urb->transfer_buffer = kmalloc(MAX_DATA_BUFFER_SIZE, GFP_KERNEL);
if (psIntfAdapter->asUsbRcb[i].urb->transfer_buffer == NULL) {
BCM_DEBUG_PRINT(psIntfAdapter->psAdapter, DBG_TYPE_PRINTK, 0, 0,
"Can't allocate Rx buffer for index %d\n", i);
return -ENOMEM;
}
psIntfAdapter->asUsbRcb[i].urb->transfer_buffer_length = MAX_DATA_BUFFER_SIZE;
}
return 0;
}
static int device_run(PS_INTERFACE_ADAPTER psIntfAdapter)
{
int value = 0;
UINT status = STATUS_SUCCESS;
status = InitCardAndDownloadFirmware(psIntfAdapter->psAdapter);
if (status != STATUS_SUCCESS) {
pr_err(DRV_NAME "InitCardAndDownloadFirmware failed.\n");
return status;
}
if (TRUE == psIntfAdapter->psAdapter->fw_download_done) {
if (StartInterruptUrb(psIntfAdapter)) {
BCM_DEBUG_PRINT(psIntfAdapter->psAdapter, DBG_TYPE_INITEXIT, DRV_ENTRY, DBG_LVL_ALL,
"Cannot send interrupt in URB\n");
}
/*
* now register the cntrl interface.
* after downloading the f/w waiting for 5 sec to get the mailbox interrupt.
*/
psIntfAdapter->psAdapter->waiting_to_fw_download_done = FALSE;
value = wait_event_timeout(psIntfAdapter->psAdapter->ioctl_fw_dnld_wait_queue,
psIntfAdapter->psAdapter->waiting_to_fw_download_done, 5*HZ);
if (value == 0)
pr_err(DRV_NAME ": Timeout waiting for mailbox interrupt.\n");
if (register_control_device_interface(psIntfAdapter->psAdapter) < 0) {
pr_err(DRV_NAME ": Register Control Device failed.\n");
return -EIO;
}
}
return 0;
}
static inline int bcm_usb_endpoint_num(const struct usb_endpoint_descriptor *epd)
{
return epd->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
}
static inline int bcm_usb_endpoint_type(const struct usb_endpoint_descriptor *epd)
{
return epd->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK;
}
static inline int bcm_usb_endpoint_dir_in(const struct usb_endpoint_descriptor *epd)
{
return ((epd->bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_DIR_IN);
}
static inline int bcm_usb_endpoint_dir_out(const struct usb_endpoint_descriptor *epd)
{
return ((epd->bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_DIR_OUT);
}
static inline int bcm_usb_endpoint_xfer_bulk(const struct usb_endpoint_descriptor *epd)
{
return ((epd->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
USB_ENDPOINT_XFER_BULK);
}
static inline int bcm_usb_endpoint_xfer_control(const struct usb_endpoint_descriptor *epd)
{
return ((epd->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
USB_ENDPOINT_XFER_CONTROL);
}
static inline int bcm_usb_endpoint_xfer_int(const struct usb_endpoint_descriptor *epd)
{
return ((epd->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
USB_ENDPOINT_XFER_INT);
}
static inline int bcm_usb_endpoint_xfer_isoc(const struct usb_endpoint_descriptor *epd)
{
return ((epd->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
USB_ENDPOINT_XFER_ISOC);
}
static inline int bcm_usb_endpoint_is_bulk_in(const struct usb_endpoint_descriptor *epd)
{
return bcm_usb_endpoint_xfer_bulk(epd) && bcm_usb_endpoint_dir_in(epd);
}
static inline int bcm_usb_endpoint_is_bulk_out(const struct usb_endpoint_descriptor *epd)
{
return bcm_usb_endpoint_xfer_bulk(epd) && bcm_usb_endpoint_dir_out(epd);
}
static inline int bcm_usb_endpoint_is_int_in(const struct usb_endpoint_descriptor *epd)
{
return bcm_usb_endpoint_xfer_int(epd) && bcm_usb_endpoint_dir_in(epd);
}
static inline int bcm_usb_endpoint_is_int_out(const struct usb_endpoint_descriptor *epd)
{
return bcm_usb_endpoint_xfer_int(epd) && bcm_usb_endpoint_dir_out(epd);
}
static inline int bcm_usb_endpoint_is_isoc_in(const struct usb_endpoint_descriptor *epd)
{
return bcm_usb_endpoint_xfer_isoc(epd) && bcm_usb_endpoint_dir_in(epd);
}
static inline int bcm_usb_endpoint_is_isoc_out(const struct usb_endpoint_descriptor *epd)
{
return bcm_usb_endpoint_xfer_isoc(epd) && bcm_usb_endpoint_dir_out(epd);
}
static int InterfaceAdapterInit(PS_INTERFACE_ADAPTER psIntfAdapter)
{
struct usb_host_interface *iface_desc;
struct usb_endpoint_descriptor *endpoint;
size_t buffer_size;
unsigned long value;
int retval = 0;
int usedIntOutForBulkTransfer = 0 ;
BOOLEAN bBcm16 = FALSE;
UINT uiData = 0;
int bytes;
/* Store the usb dev into interface adapter */
psIntfAdapter->udev = usb_get_dev(interface_to_usbdev(psIntfAdapter->interface));
psIntfAdapter->bHighSpeedDevice = (psIntfAdapter->udev->speed == USB_SPEED_HIGH);
psIntfAdapter->psAdapter->interface_rdm = BcmRDM;
psIntfAdapter->psAdapter->interface_wrm = BcmWRM;
bytes = rdmalt(psIntfAdapter->psAdapter, CHIP_ID_REG,
(u32 *)&(psIntfAdapter->psAdapter->chip_id), sizeof(u32));
if (bytes < 0) {
retval = bytes;
BCM_DEBUG_PRINT(psIntfAdapter->psAdapter, DBG_TYPE_PRINTK, 0, 0, "CHIP ID Read Failed\n");
return retval;
}
if (0xbece3200 == (psIntfAdapter->psAdapter->chip_id & ~(0xF0)))
psIntfAdapter->psAdapter->chip_id &= ~0xF0;
dev_info(&psIntfAdapter->udev->dev, "RDM Chip ID 0x%lx\n",
psIntfAdapter->psAdapter->chip_id);
iface_desc = psIntfAdapter->interface->cur_altsetting;
if (psIntfAdapter->psAdapter->chip_id == T3B) {
/* T3B device will have EEPROM, check if EEPROM is proper and BCM16 can be done or not. */
BeceemEEPROMBulkRead(psIntfAdapter->psAdapter, &uiData, 0x0, 4);
if (uiData == BECM)
bBcm16 = TRUE;
dev_info(&psIntfAdapter->udev->dev, "number of alternate setting %d\n",
psIntfAdapter->interface->num_altsetting);
if (bBcm16 == TRUE) {
/* selecting alternate setting one as a default setting for High Speed modem. */
if (psIntfAdapter->bHighSpeedDevice)
retval = usb_set_interface(psIntfAdapter->udev, DEFAULT_SETTING_0, ALTERNATE_SETTING_1);
BCM_DEBUG_PRINT(psIntfAdapter->psAdapter, DBG_TYPE_INITEXIT, DRV_ENTRY, DBG_LVL_ALL,
"BCM16 is applicable on this dongle\n");
if (retval || (psIntfAdapter->bHighSpeedDevice == FALSE)) {
usedIntOutForBulkTransfer = EP2 ;
endpoint = &iface_desc->endpoint[EP2].desc;
BCM_DEBUG_PRINT(psIntfAdapter->psAdapter, DBG_TYPE_INITEXIT, DRV_ENTRY, DBG_LVL_ALL,
"Interface altsetting failed or modem is configured to Full Speed, hence will work on default setting 0\n");
/*
* If Modem is high speed device EP2 should be INT OUT End point
* If Mode is FS then EP2 should be bulk end point
*/
if (((psIntfAdapter->bHighSpeedDevice == TRUE) && (bcm_usb_endpoint_is_int_out(endpoint) == FALSE))
|| ((psIntfAdapter->bHighSpeedDevice == FALSE) && (bcm_usb_endpoint_is_bulk_out(endpoint) == FALSE))) {
BCM_DEBUG_PRINT(psIntfAdapter->psAdapter, DBG_TYPE_INITEXIT, DRV_ENTRY, DBG_LVL_ALL,
"Configuring the EEPROM\n");
/* change the EP2, EP4 to INT OUT end point */
ConfigureEndPointTypesThroughEEPROM(psIntfAdapter->psAdapter);
/*
* It resets the device and if any thing gets changed
* in USB descriptor it will show fail and re-enumerate
* the device
*/
retval = usb_reset_device(psIntfAdapter->udev);
if (retval) {
BCM_DEBUG_PRINT(psIntfAdapter->psAdapter, DBG_TYPE_INITEXIT, DRV_ENTRY, DBG_LVL_ALL,
"reset failed. Re-enumerating the device.\n");
return retval ;
}
}
if ((psIntfAdapter->bHighSpeedDevice == FALSE) && bcm_usb_endpoint_is_bulk_out(endpoint)) {
/* Once BULK is selected in FS mode. Revert it back to INT. Else USB_IF will fail. */
UINT _uiData = ntohl(EP2_CFG_INT);
BCM_DEBUG_PRINT(psIntfAdapter->psAdapter, DBG_TYPE_INITEXIT, DRV_ENTRY, DBG_LVL_ALL,
"Reverting Bulk to INT as it is in Full Speed mode.\n");
BeceemEEPROMBulkWrite(psIntfAdapter->psAdapter, (PUCHAR)&_uiData, 0x136, 4, TRUE);
}
} else {
usedIntOutForBulkTransfer = EP4 ;
endpoint = &iface_desc->endpoint[EP4].desc;
BCM_DEBUG_PRINT(psIntfAdapter->psAdapter, DBG_TYPE_INITEXIT, DRV_ENTRY, DBG_LVL_ALL,
"Choosing AltSetting as a default setting.\n");
if (bcm_usb_endpoint_is_int_out(endpoint) == FALSE) {
BCM_DEBUG_PRINT(psIntfAdapter->psAdapter, DBG_TYPE_INITEXIT, DRV_ENTRY, DBG_LVL_ALL,
"Dongle does not have BCM16 Fix.\n");
/* change the EP2, EP4 to INT OUT end point and use EP4 in altsetting */
ConfigureEndPointTypesThroughEEPROM(psIntfAdapter->psAdapter);
/*
* It resets the device and if any thing gets changed in
* USB descriptor it will show fail and re-enumerate the
* device
*/
retval = usb_reset_device(psIntfAdapter->udev);
if (retval) {
BCM_DEBUG_PRINT(psIntfAdapter->psAdapter, DBG_TYPE_INITEXIT, DRV_ENTRY, DBG_LVL_ALL,
"reset failed. Re-enumerating the device.\n");
return retval;
}
}
}
}
}
iface_desc = psIntfAdapter->interface->cur_altsetting;
for (value = 0; value < iface_desc->desc.bNumEndpoints; ++value) {
endpoint = &iface_desc->endpoint[value].desc;
if (!psIntfAdapter->sBulkIn.bulk_in_endpointAddr && bcm_usb_endpoint_is_bulk_in(endpoint)) {
buffer_size = le16_to_cpu(endpoint->wMaxPacketSize);
psIntfAdapter->sBulkIn.bulk_in_size = buffer_size;
psIntfAdapter->sBulkIn.bulk_in_endpointAddr = endpoint->bEndpointAddress;
psIntfAdapter->sBulkIn.bulk_in_pipe =
usb_rcvbulkpipe(psIntfAdapter->udev,
psIntfAdapter->sBulkIn.bulk_in_endpointAddr);
}
if (!psIntfAdapter->sBulkOut.bulk_out_endpointAddr && bcm_usb_endpoint_is_bulk_out(endpoint)) {
psIntfAdapter->sBulkOut.bulk_out_endpointAddr = endpoint->bEndpointAddress;
psIntfAdapter->sBulkOut.bulk_out_pipe =
usb_sndbulkpipe(psIntfAdapter->udev,
psIntfAdapter->sBulkOut.bulk_out_endpointAddr);
}
if (!psIntfAdapter->sIntrIn.int_in_endpointAddr && bcm_usb_endpoint_is_int_in(endpoint)) {
buffer_size = le16_to_cpu(endpoint->wMaxPacketSize);
psIntfAdapter->sIntrIn.int_in_size = buffer_size;
psIntfAdapter->sIntrIn.int_in_endpointAddr = endpoint->bEndpointAddress;
psIntfAdapter->sIntrIn.int_in_interval = endpoint->bInterval;
psIntfAdapter->sIntrIn.int_in_buffer =
kmalloc(buffer_size, GFP_KERNEL);
if (!psIntfAdapter->sIntrIn.int_in_buffer) {
dev_err(&psIntfAdapter->udev->dev,
"could not allocate interrupt_in_buffer\n");
return -EINVAL;
}
}
if (!psIntfAdapter->sIntrOut.int_out_endpointAddr && bcm_usb_endpoint_is_int_out(endpoint)) {
if (!psIntfAdapter->sBulkOut.bulk_out_endpointAddr &&
(psIntfAdapter->psAdapter->chip_id == T3B) && (value == usedIntOutForBulkTransfer)) {
/* use first intout end point as a bulk out end point */
buffer_size = le16_to_cpu(endpoint->wMaxPacketSize);
psIntfAdapter->sBulkOut.bulk_out_size = buffer_size;
psIntfAdapter->sBulkOut.bulk_out_endpointAddr = endpoint->bEndpointAddress;
psIntfAdapter->sBulkOut.bulk_out_pipe = usb_sndintpipe(psIntfAdapter->udev,
psIntfAdapter->sBulkOut.bulk_out_endpointAddr);
psIntfAdapter->sBulkOut.int_out_interval = endpoint->bInterval;
} else if (value == EP6) {
buffer_size = le16_to_cpu(endpoint->wMaxPacketSize);
psIntfAdapter->sIntrOut.int_out_size = buffer_size;
psIntfAdapter->sIntrOut.int_out_endpointAddr = endpoint->bEndpointAddress;
psIntfAdapter->sIntrOut.int_out_interval = endpoint->bInterval;
psIntfAdapter->sIntrOut.int_out_buffer = kmalloc(buffer_size, GFP_KERNEL);
if (!psIntfAdapter->sIntrOut.int_out_buffer) {
dev_err(&psIntfAdapter->udev->dev,
"could not allocate interrupt_out_buffer\n");
return -EINVAL;
}
}
}
}
usb_set_intfdata(psIntfAdapter->interface, psIntfAdapter);
psIntfAdapter->psAdapter->bcm_file_download = InterfaceFileDownload;
psIntfAdapter->psAdapter->bcm_file_readback_from_chip =
InterfaceFileReadbackFromChip;
psIntfAdapter->psAdapter->interface_transmit = InterfaceTransmitPacket;
retval = CreateInterruptUrb(psIntfAdapter);
if (retval) {
BCM_DEBUG_PRINT(psIntfAdapter->psAdapter, DBG_TYPE_PRINTK, 0, 0,
"Cannot create interrupt urb\n");
return retval;
}
retval = AllocUsbCb(psIntfAdapter);
if (retval)
return retval;
return device_run(psIntfAdapter);
}
static int InterfaceSuspend(struct usb_interface *intf, pm_message_t message)
{
PS_INTERFACE_ADAPTER psIntfAdapter = usb_get_intfdata(intf);
psIntfAdapter->bSuspended = TRUE;
if (TRUE == psIntfAdapter->bPreparingForBusSuspend) {
psIntfAdapter->bPreparingForBusSuspend = FALSE;
if (psIntfAdapter->psAdapter->LinkStatus == LINKUP_DONE) {
psIntfAdapter->psAdapter->IdleMode = TRUE ;
BCM_DEBUG_PRINT(psIntfAdapter->psAdapter, DBG_TYPE_INITEXIT, DRV_ENTRY, DBG_LVL_ALL,
"Host Entered in PMU Idle Mode.\n");
} else {
psIntfAdapter->psAdapter->bShutStatus = TRUE;
BCM_DEBUG_PRINT(psIntfAdapter->psAdapter, DBG_TYPE_INITEXIT, DRV_ENTRY, DBG_LVL_ALL,
"Host Entered in PMU Shutdown Mode.\n");
}
}
psIntfAdapter->psAdapter->bPreparingForLowPowerMode = FALSE;
/* Signaling the control pkt path */
wake_up(&psIntfAdapter->psAdapter->lowpower_mode_wait_queue);
return 0;
}
static int InterfaceResume(struct usb_interface *intf)
{
PS_INTERFACE_ADAPTER psIntfAdapter = usb_get_intfdata(intf);
mdelay(100);
psIntfAdapter->bSuspended = FALSE;
StartInterruptUrb(psIntfAdapter);
InterfaceRx(psIntfAdapter);
return 0;
}
static struct usb_driver usbbcm_driver = {
.name = "usbbcm",
.probe = usbbcm_device_probe,
.disconnect = usbbcm_disconnect,
.suspend = InterfaceSuspend,
.resume = InterfaceResume,
.id_table = InterfaceUsbtable,
.supports_autosuspend = 1,
};
struct class *bcm_class;
static __init int bcm_init(void)
{
printk(KERN_INFO "%s: %s, %s\n", DRV_NAME, DRV_DESCRIPTION, DRV_VERSION);
printk(KERN_INFO "%s\n", DRV_COPYRIGHT);
bcm_class = class_create(THIS_MODULE, DRV_NAME);
if (IS_ERR(bcm_class)) {
printk(KERN_ERR DRV_NAME ": could not create class\n");
return PTR_ERR(bcm_class);
}
return usb_register(&usbbcm_driver);
}
static __exit void bcm_exit(void)
{
usb_deregister(&usbbcm_driver);
class_destroy(bcm_class);
}
module_init(bcm_init);
module_exit(bcm_exit);
MODULE_DESCRIPTION(DRV_DESCRIPTION);
MODULE_VERSION(DRV_VERSION);
MODULE_LICENSE("GPL");
| gpl-2.0 |
andi34/kernel_oneplus_msm8974 | arch/xtensa/kernel/ptrace.c | 4704 | 8201 | // TODO some minor issues
/*
* 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) 2001 - 2007 Tensilica Inc.
*
* Joe Taylor <joe@tensilica.com, joetylr@yahoo.com>
* Chris Zankel <chris@zankel.net>
* Scott Foehner<sfoehner@yahoo.com>,
* Kevin Chea
* Marc Gauthier<marc@tensilica.com> <marc@alumni.uwaterloo.ca>
*/
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/errno.h>
#include <linux/ptrace.h>
#include <linux/smp.h>
#include <linux/security.h>
#include <linux/signal.h>
#include <asm/pgtable.h>
#include <asm/page.h>
#include <asm/uaccess.h>
#include <asm/ptrace.h>
#include <asm/elf.h>
#include <asm/coprocessor.h>
void user_enable_single_step(struct task_struct *child)
{
child->ptrace |= PT_SINGLESTEP;
}
void user_disable_single_step(struct task_struct *child)
{
child->ptrace &= ~PT_SINGLESTEP;
}
/*
* Called by kernel/ptrace.c when detaching to disable single stepping.
*/
void ptrace_disable(struct task_struct *child)
{
/* Nothing to do.. */
}
int ptrace_getregs(struct task_struct *child, void __user *uregs)
{
struct pt_regs *regs = task_pt_regs(child);
xtensa_gregset_t __user *gregset = uregs;
unsigned long wm = regs->wmask;
unsigned long wb = regs->windowbase;
int live, i;
if (!access_ok(VERIFY_WRITE, uregs, sizeof(xtensa_gregset_t)))
return -EIO;
__put_user(regs->pc, &gregset->pc);
__put_user(regs->ps & ~(1 << PS_EXCM_BIT), &gregset->ps);
__put_user(regs->lbeg, &gregset->lbeg);
__put_user(regs->lend, &gregset->lend);
__put_user(regs->lcount, &gregset->lcount);
__put_user(regs->windowstart, &gregset->windowstart);
__put_user(regs->windowbase, &gregset->windowbase);
live = (wm & 2) ? 4 : (wm & 4) ? 8 : (wm & 8) ? 12 : 16;
for (i = 0; i < live; i++)
__put_user(regs->areg[i],gregset->a+((wb*4+i)%XCHAL_NUM_AREGS));
for (i = XCHAL_NUM_AREGS - (wm >> 4) * 4; i < XCHAL_NUM_AREGS; i++)
__put_user(regs->areg[i],gregset->a+((wb*4+i)%XCHAL_NUM_AREGS));
return 0;
}
int ptrace_setregs(struct task_struct *child, void __user *uregs)
{
struct pt_regs *regs = task_pt_regs(child);
xtensa_gregset_t *gregset = uregs;
const unsigned long ps_mask = PS_CALLINC_MASK | PS_OWB_MASK;
unsigned long ps;
unsigned long wb;
if (!access_ok(VERIFY_WRITE, uregs, sizeof(xtensa_gregset_t)))
return -EIO;
__get_user(regs->pc, &gregset->pc);
__get_user(ps, &gregset->ps);
__get_user(regs->lbeg, &gregset->lbeg);
__get_user(regs->lend, &gregset->lend);
__get_user(regs->lcount, &gregset->lcount);
__get_user(regs->windowstart, &gregset->windowstart);
__get_user(wb, &gregset->windowbase);
regs->ps = (regs->ps & ~ps_mask) | (ps & ps_mask) | (1 << PS_EXCM_BIT);
if (wb >= XCHAL_NUM_AREGS / 4)
return -EFAULT;
regs->windowbase = wb;
if (wb != 0 && __copy_from_user(regs->areg + XCHAL_NUM_AREGS - wb * 4,
gregset->a, wb * 16))
return -EFAULT;
if (__copy_from_user(regs->areg, gregset->a + wb*4, (WSBITS-wb) * 16))
return -EFAULT;
return 0;
}
int ptrace_getxregs(struct task_struct *child, void __user *uregs)
{
struct pt_regs *regs = task_pt_regs(child);
struct thread_info *ti = task_thread_info(child);
elf_xtregs_t __user *xtregs = uregs;
int ret = 0;
if (!access_ok(VERIFY_WRITE, uregs, sizeof(elf_xtregs_t)))
return -EIO;
#if XTENSA_HAVE_COPROCESSORS
/* Flush all coprocessor registers to memory. */
coprocessor_flush_all(ti);
ret |= __copy_to_user(&xtregs->cp0, &ti->xtregs_cp,
sizeof(xtregs_coprocessor_t));
#endif
ret |= __copy_to_user(&xtregs->opt, ®s->xtregs_opt,
sizeof(xtregs->opt));
ret |= __copy_to_user(&xtregs->user,&ti->xtregs_user,
sizeof(xtregs->user));
return ret ? -EFAULT : 0;
}
int ptrace_setxregs(struct task_struct *child, void __user *uregs)
{
struct thread_info *ti = task_thread_info(child);
struct pt_regs *regs = task_pt_regs(child);
elf_xtregs_t *xtregs = uregs;
int ret = 0;
if (!access_ok(VERIFY_READ, uregs, sizeof(elf_xtregs_t)))
return -EFAULT;
#if XTENSA_HAVE_COPROCESSORS
/* Flush all coprocessors before we overwrite them. */
coprocessor_flush_all(ti);
coprocessor_release_all(ti);
ret |= __copy_from_user(&ti->xtregs_cp, &xtregs->cp0,
sizeof(xtregs_coprocessor_t));
#endif
ret |= __copy_from_user(®s->xtregs_opt, &xtregs->opt,
sizeof(xtregs->opt));
ret |= __copy_from_user(&ti->xtregs_user, &xtregs->user,
sizeof(xtregs->user));
return ret ? -EFAULT : 0;
}
int ptrace_peekusr(struct task_struct *child, long regno, long __user *ret)
{
struct pt_regs *regs;
unsigned long tmp;
regs = task_pt_regs(child);
tmp = 0; /* Default return value. */
switch(regno) {
case REG_AR_BASE ... REG_AR_BASE + XCHAL_NUM_AREGS - 1:
tmp = regs->areg[regno - REG_AR_BASE];
break;
case REG_A_BASE ... REG_A_BASE + 15:
tmp = regs->areg[regno - REG_A_BASE];
break;
case REG_PC:
tmp = regs->pc;
break;
case REG_PS:
/* Note: PS.EXCM is not set while user task is running;
* its being set in regs is for exception handling
* convenience. */
tmp = (regs->ps & ~(1 << PS_EXCM_BIT));
break;
case REG_WB:
break; /* tmp = 0 */
case REG_WS:
{
unsigned long wb = regs->windowbase;
unsigned long ws = regs->windowstart;
tmp = ((ws>>wb) | (ws<<(WSBITS-wb))) & ((1<<WSBITS)-1);
break;
}
case REG_LBEG:
tmp = regs->lbeg;
break;
case REG_LEND:
tmp = regs->lend;
break;
case REG_LCOUNT:
tmp = regs->lcount;
break;
case REG_SAR:
tmp = regs->sar;
break;
case SYSCALL_NR:
tmp = regs->syscall;
break;
default:
return -EIO;
}
return put_user(tmp, ret);
}
int ptrace_pokeusr(struct task_struct *child, long regno, long val)
{
struct pt_regs *regs;
regs = task_pt_regs(child);
switch (regno) {
case REG_AR_BASE ... REG_AR_BASE + XCHAL_NUM_AREGS - 1:
regs->areg[regno - REG_AR_BASE] = val;
break;
case REG_A_BASE ... REG_A_BASE + 15:
regs->areg[regno - REG_A_BASE] = val;
break;
case REG_PC:
regs->pc = val;
break;
case SYSCALL_NR:
regs->syscall = val;
break;
default:
return -EIO;
}
return 0;
}
long arch_ptrace(struct task_struct *child, long request,
unsigned long addr, unsigned long data)
{
int ret = -EPERM;
void __user *datap = (void __user *) data;
switch (request) {
case PTRACE_PEEKTEXT: /* read word at location addr. */
case PTRACE_PEEKDATA:
ret = generic_ptrace_peekdata(child, addr, data);
break;
case PTRACE_PEEKUSR: /* read register specified by addr. */
ret = ptrace_peekusr(child, addr, datap);
break;
case PTRACE_POKETEXT: /* write the word at location addr. */
case PTRACE_POKEDATA:
ret = generic_ptrace_pokedata(child, addr, data);
break;
case PTRACE_POKEUSR: /* write register specified by addr. */
ret = ptrace_pokeusr(child, addr, data);
break;
case PTRACE_GETREGS:
ret = ptrace_getregs(child, datap);
break;
case PTRACE_SETREGS:
ret = ptrace_setregs(child, datap);
break;
case PTRACE_GETXTREGS:
ret = ptrace_getxregs(child, datap);
break;
case PTRACE_SETXTREGS:
ret = ptrace_setxregs(child, datap);
break;
default:
ret = ptrace_request(child, request, addr, data);
break;
}
return ret;
}
void do_syscall_trace(void)
{
/*
* The 0x80 provides a way for the tracing parent to distinguish
* between a syscall stop and SIGTRAP delivery
*/
ptrace_notify(SIGTRAP|((current->ptrace & PT_TRACESYSGOOD) ? 0x80 : 0));
/*
* this isn't the same as continuing with a signal, but it will do
* for normal use. strace only continues with a signal if the
* stopping signal is not SIGTRAP. -brl
*/
if (current->exit_code) {
send_sig(current->exit_code, current, 1);
current->exit_code = 0;
}
}
void do_syscall_trace_enter(struct pt_regs *regs)
{
if (test_thread_flag(TIF_SYSCALL_TRACE)
&& (current->ptrace & PT_PTRACED))
do_syscall_trace();
#if 0
audit_syscall_entry(current, AUDIT_ARCH_XTENSA..);
#endif
}
void do_syscall_trace_leave(struct pt_regs *regs)
{
if ((test_thread_flag(TIF_SYSCALL_TRACE))
&& (current->ptrace & PT_PTRACED))
do_syscall_trace();
}
| gpl-2.0 |
pvittman/donkey-cm12 | arch/arm/mach-omap2/common.c | 4704 | 4657 | /*
* linux/arch/arm/mach-omap2/common.c
*
* Code common to all OMAP2+ machines.
*
* Copyright (C) 2009 Texas Instruments
* Copyright (C) 2010 Nokia Corporation
* Tony Lindgren <tony@atomide.com>
* Added OMAP4 support - Santosh Shilimkar <santosh.shilimkar@ti.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <plat/hardware.h>
#include <plat/board.h>
#include <plat/mux.h>
#include <plat/clock.h>
#include "iomap.h"
#include "common.h"
#include "sdrc.h"
#include "control.h"
/* Global address base setup code */
#if defined(CONFIG_ARCH_OMAP2) || defined(CONFIG_ARCH_OMAP3)
static void __init __omap2_set_globals(struct omap_globals *omap2_globals)
{
omap2_set_globals_tap(omap2_globals);
omap2_set_globals_sdrc(omap2_globals);
omap2_set_globals_control(omap2_globals);
omap2_set_globals_prcm(omap2_globals);
}
#endif
#if defined(CONFIG_SOC_OMAP2420)
static struct omap_globals omap242x_globals = {
.class = OMAP242X_CLASS,
.tap = OMAP2_L4_IO_ADDRESS(0x48014000),
.sdrc = OMAP2_L3_IO_ADDRESS(OMAP2420_SDRC_BASE),
.sms = OMAP2_L3_IO_ADDRESS(OMAP2420_SMS_BASE),
.ctrl = OMAP2_L4_IO_ADDRESS(OMAP242X_CTRL_BASE),
.prm = OMAP2_L4_IO_ADDRESS(OMAP2420_PRM_BASE),
.cm = OMAP2_L4_IO_ADDRESS(OMAP2420_CM_BASE),
};
void __init omap2_set_globals_242x(void)
{
__omap2_set_globals(&omap242x_globals);
}
void __init omap242x_map_io(void)
{
omap242x_map_common_io();
}
#endif
#if defined(CONFIG_SOC_OMAP2430)
static struct omap_globals omap243x_globals = {
.class = OMAP243X_CLASS,
.tap = OMAP2_L4_IO_ADDRESS(0x4900a000),
.sdrc = OMAP2_L3_IO_ADDRESS(OMAP243X_SDRC_BASE),
.sms = OMAP2_L3_IO_ADDRESS(OMAP243X_SMS_BASE),
.ctrl = OMAP2_L4_IO_ADDRESS(OMAP243X_CTRL_BASE),
.prm = OMAP2_L4_IO_ADDRESS(OMAP2430_PRM_BASE),
.cm = OMAP2_L4_IO_ADDRESS(OMAP2430_CM_BASE),
};
void __init omap2_set_globals_243x(void)
{
__omap2_set_globals(&omap243x_globals);
}
void __init omap243x_map_io(void)
{
omap243x_map_common_io();
}
#endif
#if defined(CONFIG_ARCH_OMAP3)
static struct omap_globals omap3_globals = {
.class = OMAP343X_CLASS,
.tap = OMAP2_L4_IO_ADDRESS(0x4830A000),
.sdrc = OMAP2_L3_IO_ADDRESS(OMAP343X_SDRC_BASE),
.sms = OMAP2_L3_IO_ADDRESS(OMAP343X_SMS_BASE),
.ctrl = OMAP2_L4_IO_ADDRESS(OMAP343X_CTRL_BASE),
.prm = OMAP2_L4_IO_ADDRESS(OMAP3430_PRM_BASE),
.cm = OMAP2_L4_IO_ADDRESS(OMAP3430_CM_BASE),
};
void __init omap2_set_globals_3xxx(void)
{
__omap2_set_globals(&omap3_globals);
}
void __init omap3_map_io(void)
{
omap34xx_map_common_io();
}
/*
* Adjust TAP register base such that omap3_check_revision accesses the correct
* TI81XX register for checking device ID (it adds 0x204 to tap base while
* TI81XX DEVICE ID register is at offset 0x600 from control base).
*/
#define TI81XX_TAP_BASE (TI81XX_CTRL_BASE + \
TI81XX_CONTROL_DEVICE_ID - 0x204)
static struct omap_globals ti81xx_globals = {
.class = OMAP343X_CLASS,
.tap = OMAP2_L4_IO_ADDRESS(TI81XX_TAP_BASE),
.ctrl = OMAP2_L4_IO_ADDRESS(TI81XX_CTRL_BASE),
.prm = OMAP2_L4_IO_ADDRESS(TI81XX_PRCM_BASE),
.cm = OMAP2_L4_IO_ADDRESS(TI81XX_PRCM_BASE),
};
void __init omap2_set_globals_ti81xx(void)
{
__omap2_set_globals(&ti81xx_globals);
}
void __init ti81xx_map_io(void)
{
omapti81xx_map_common_io();
}
#define AM33XX_TAP_BASE (AM33XX_CTRL_BASE + \
TI81XX_CONTROL_DEVICE_ID - 0x204)
static struct omap_globals am33xx_globals = {
.class = AM335X_CLASS,
.tap = AM33XX_L4_WK_IO_ADDRESS(AM33XX_TAP_BASE),
.ctrl = AM33XX_L4_WK_IO_ADDRESS(AM33XX_CTRL_BASE),
.prm = AM33XX_L4_WK_IO_ADDRESS(AM33XX_PRCM_BASE),
.cm = AM33XX_L4_WK_IO_ADDRESS(AM33XX_PRCM_BASE),
};
void __init omap2_set_globals_am33xx(void)
{
__omap2_set_globals(&am33xx_globals);
}
void __init am33xx_map_io(void)
{
omapam33xx_map_common_io();
}
#endif
#if defined(CONFIG_ARCH_OMAP4)
static struct omap_globals omap4_globals = {
.class = OMAP443X_CLASS,
.tap = OMAP2_L4_IO_ADDRESS(OMAP443X_SCM_BASE),
.ctrl = OMAP2_L4_IO_ADDRESS(OMAP443X_SCM_BASE),
.ctrl_pad = OMAP2_L4_IO_ADDRESS(OMAP443X_CTRL_BASE),
.prm = OMAP2_L4_IO_ADDRESS(OMAP4430_PRM_BASE),
.cm = OMAP2_L4_IO_ADDRESS(OMAP4430_CM_BASE),
.cm2 = OMAP2_L4_IO_ADDRESS(OMAP4430_CM2_BASE),
};
void __init omap2_set_globals_443x(void)
{
omap2_set_globals_tap(&omap4_globals);
omap2_set_globals_control(&omap4_globals);
omap2_set_globals_prcm(&omap4_globals);
}
void __init omap4_map_io(void)
{
omap44xx_map_common_io();
}
#endif
| gpl-2.0 |
BanBxda/m7-3.4.10-4-4-2 | drivers/clocksource/clksrc-dbx500-prcmu.c | 4960 | 2481 | /*
* Copyright (C) ST-Ericsson SA 2011
*
* License Terms: GNU General Public License v2
* Author: Mattias Wallin <mattias.wallin@stericsson.com> for ST-Ericsson
* Author: Sundar Iyer for ST-Ericsson
* sched_clock implementation is based on:
* plat-nomadik/timer.c Linus Walleij <linus.walleij@stericsson.com>
*
* DBx500-PRCMU Timer
* The PRCMU has 5 timers which are available in a always-on
* power domain. We use the Timer 4 for our always-on clock
* source on DB8500 and Timer 3 on DB5500.
*/
#include <linux/clockchips.h>
#include <linux/clksrc-dbx500-prcmu.h>
#include <asm/sched_clock.h>
#include <mach/setup.h>
#include <mach/hardware.h>
#define RATE_32K 32768
#define TIMER_MODE_CONTINOUS 0x1
#define TIMER_DOWNCOUNT_VAL 0xffffffff
#define PRCMU_TIMER_REF 0
#define PRCMU_TIMER_DOWNCOUNT 0x4
#define PRCMU_TIMER_MODE 0x8
#define SCHED_CLOCK_MIN_WRAP 131072 /* 2^32 / 32768 */
static void __iomem *clksrc_dbx500_timer_base;
static cycle_t clksrc_dbx500_prcmu_read(struct clocksource *cs)
{
u32 count, count2;
do {
count = readl(clksrc_dbx500_timer_base +
PRCMU_TIMER_DOWNCOUNT);
count2 = readl(clksrc_dbx500_timer_base +
PRCMU_TIMER_DOWNCOUNT);
} while (count2 != count);
/* Negate because the timer is a decrementing counter */
return ~count;
}
static struct clocksource clocksource_dbx500_prcmu = {
.name = "dbx500-prcmu-timer",
.rating = 300,
.read = clksrc_dbx500_prcmu_read,
.mask = CLOCKSOURCE_MASK(32),
.flags = CLOCK_SOURCE_IS_CONTINUOUS,
};
#ifdef CONFIG_CLKSRC_DBX500_PRCMU_SCHED_CLOCK
static u32 notrace dbx500_prcmu_sched_clock_read(void)
{
if (unlikely(!clksrc_dbx500_timer_base))
return 0;
return clksrc_dbx500_prcmu_read(&clocksource_dbx500_prcmu);
}
#endif
void __init clksrc_dbx500_prcmu_init(void __iomem *base)
{
clksrc_dbx500_timer_base = base;
/*
* The A9 sub system expects the timer to be configured as
* a continous looping timer.
* The PRCMU should configure it but if it for some reason
* don't we do it here.
*/
if (readl(clksrc_dbx500_timer_base + PRCMU_TIMER_MODE) !=
TIMER_MODE_CONTINOUS) {
writel(TIMER_MODE_CONTINOUS,
clksrc_dbx500_timer_base + PRCMU_TIMER_MODE);
writel(TIMER_DOWNCOUNT_VAL,
clksrc_dbx500_timer_base + PRCMU_TIMER_REF);
}
#ifdef CONFIG_CLKSRC_DBX500_PRCMU_SCHED_CLOCK
setup_sched_clock(dbx500_prcmu_sched_clock_read,
32, RATE_32K);
#endif
clocksource_register_hz(&clocksource_dbx500_prcmu, RATE_32K);
}
| gpl-2.0 |
Freack-v/stock_kernel | arch/arm/mach-kirkwood/addr-map.c | 4960 | 2282 | /*
* arch/arm/mach-kirkwood/addr-map.c
*
* Address map functions for Marvell Kirkwood SoCs
*
* 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/init.h>
#include <linux/mbus.h>
#include <linux/io.h>
#include <mach/hardware.h>
#include <plat/addr-map.h>
#include "common.h"
/*
* Generic Address Decode Windows bit settings
*/
#define TARGET_DEV_BUS 1
#define TARGET_SRAM 3
#define TARGET_PCIE 4
#define ATTR_DEV_SPI_ROM 0x1e
#define ATTR_DEV_BOOT 0x1d
#define ATTR_DEV_NAND 0x2f
#define ATTR_DEV_CS3 0x37
#define ATTR_DEV_CS2 0x3b
#define ATTR_DEV_CS1 0x3d
#define ATTR_DEV_CS0 0x3e
#define ATTR_PCIE_IO 0xe0
#define ATTR_PCIE_MEM 0xe8
#define ATTR_PCIE1_IO 0xd0
#define ATTR_PCIE1_MEM 0xd8
#define ATTR_SRAM 0x01
/*
* Description of the windows needed by the platform code
*/
static struct __initdata orion_addr_map_cfg addr_map_cfg = {
.num_wins = 8,
.remappable_wins = 4,
.bridge_virt_base = BRIDGE_VIRT_BASE,
};
static const struct __initdata orion_addr_map_info addr_map_info[] = {
/*
* Windows for PCIe IO+MEM space.
*/
{ 0, KIRKWOOD_PCIE_IO_PHYS_BASE, KIRKWOOD_PCIE_IO_SIZE,
TARGET_PCIE, ATTR_PCIE_IO, KIRKWOOD_PCIE_IO_BUS_BASE
},
{ 1, KIRKWOOD_PCIE_MEM_PHYS_BASE, KIRKWOOD_PCIE_MEM_SIZE,
TARGET_PCIE, ATTR_PCIE_MEM, KIRKWOOD_PCIE_MEM_BUS_BASE
},
{ 2, KIRKWOOD_PCIE1_IO_PHYS_BASE, KIRKWOOD_PCIE1_IO_SIZE,
TARGET_PCIE, ATTR_PCIE1_IO, KIRKWOOD_PCIE1_IO_BUS_BASE
},
{ 3, KIRKWOOD_PCIE1_MEM_PHYS_BASE, KIRKWOOD_PCIE1_MEM_SIZE,
TARGET_PCIE, ATTR_PCIE1_MEM, KIRKWOOD_PCIE1_MEM_BUS_BASE
},
/*
* Window for NAND controller.
*/
{ 4, KIRKWOOD_NAND_MEM_PHYS_BASE, KIRKWOOD_NAND_MEM_SIZE,
TARGET_DEV_BUS, ATTR_DEV_NAND, -1
},
/*
* Window for SRAM.
*/
{ 5, KIRKWOOD_SRAM_PHYS_BASE, KIRKWOOD_SRAM_SIZE,
TARGET_SRAM, ATTR_SRAM, -1
},
/* End marker */
{ -1, 0, 0, 0, 0, 0 }
};
void __init kirkwood_setup_cpu_mbus(void)
{
/*
* Disable, clear and configure windows.
*/
orion_config_wins(&addr_map_cfg, addr_map_info);
/*
* Setup MBUS dram target info.
*/
orion_setup_cpu_mbus_target(&addr_map_cfg, DDR_WINDOW_CPU_BASE);
}
| gpl-2.0 |
NoelMacwan/SXDNickiMallow | fs/ntfs/mft.c | 9312 | 101923 | /**
* mft.c - NTFS kernel mft record operations. Part of the Linux-NTFS project.
*
* Copyright (c) 2001-2012 Anton Altaparmakov and Tuxera Inc.
* Copyright (c) 2002 Richard Russon
*
* This program/include file 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/include file 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 (in the main directory of the Linux-NTFS
* distribution in the file COPYING); if not, write to the Free Software
* Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/buffer_head.h>
#include <linux/slab.h>
#include <linux/swap.h>
#include "attrib.h"
#include "aops.h"
#include "bitmap.h"
#include "debug.h"
#include "dir.h"
#include "lcnalloc.h"
#include "malloc.h"
#include "mft.h"
#include "ntfs.h"
/**
* map_mft_record_page - map the page in which a specific mft record resides
* @ni: ntfs inode whose mft record page to map
*
* This maps the page in which the mft record of the ntfs inode @ni is situated
* and returns a pointer to the mft record within the mapped page.
*
* Return value needs to be checked with IS_ERR() and if that is true PTR_ERR()
* contains the negative error code returned.
*/
static inline MFT_RECORD *map_mft_record_page(ntfs_inode *ni)
{
loff_t i_size;
ntfs_volume *vol = ni->vol;
struct inode *mft_vi = vol->mft_ino;
struct page *page;
unsigned long index, end_index;
unsigned ofs;
BUG_ON(ni->page);
/*
* The index into the page cache and the offset within the page cache
* page of the wanted mft record. FIXME: We need to check for
* overflowing the unsigned long, but I don't think we would ever get
* here if the volume was that big...
*/
index = (u64)ni->mft_no << vol->mft_record_size_bits >>
PAGE_CACHE_SHIFT;
ofs = (ni->mft_no << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
i_size = i_size_read(mft_vi);
/* The maximum valid index into the page cache for $MFT's data. */
end_index = i_size >> PAGE_CACHE_SHIFT;
/* If the wanted index is out of bounds the mft record doesn't exist. */
if (unlikely(index >= end_index)) {
if (index > end_index || (i_size & ~PAGE_CACHE_MASK) < ofs +
vol->mft_record_size) {
page = ERR_PTR(-ENOENT);
ntfs_error(vol->sb, "Attempt to read mft record 0x%lx, "
"which is beyond the end of the mft. "
"This is probably a bug in the ntfs "
"driver.", ni->mft_no);
goto err_out;
}
}
/* Read, map, and pin the page. */
page = ntfs_map_page(mft_vi->i_mapping, index);
if (likely(!IS_ERR(page))) {
/* Catch multi sector transfer fixup errors. */
if (likely(ntfs_is_mft_recordp((le32*)(page_address(page) +
ofs)))) {
ni->page = page;
ni->page_ofs = ofs;
return page_address(page) + ofs;
}
ntfs_error(vol->sb, "Mft record 0x%lx is corrupt. "
"Run chkdsk.", ni->mft_no);
ntfs_unmap_page(page);
page = ERR_PTR(-EIO);
NVolSetErrors(vol);
}
err_out:
ni->page = NULL;
ni->page_ofs = 0;
return (void*)page;
}
/**
* map_mft_record - map, pin and lock an mft record
* @ni: ntfs inode whose MFT record to map
*
* First, take the mrec_lock mutex. We might now be sleeping, while waiting
* for the mutex if it was already locked by someone else.
*
* The page of the record is mapped using map_mft_record_page() before being
* returned to the caller.
*
* This in turn uses ntfs_map_page() to get the page containing the wanted mft
* record (it in turn calls read_cache_page() which reads it in from disk if
* necessary, increments the use count on the page so that it cannot disappear
* under us and returns a reference to the page cache page).
*
* If read_cache_page() invokes ntfs_readpage() to load the page from disk, it
* sets PG_locked and clears PG_uptodate on the page. Once I/O has completed
* and the post-read mst fixups on each mft record in the page have been
* performed, the page gets PG_uptodate set and PG_locked cleared (this is done
* in our asynchronous I/O completion handler end_buffer_read_mft_async()).
* ntfs_map_page() waits for PG_locked to become clear and checks if
* PG_uptodate is set and returns an error code if not. This provides
* sufficient protection against races when reading/using the page.
*
* However there is the write mapping to think about. Doing the above described
* checking here will be fine, because when initiating the write we will set
* PG_locked and clear PG_uptodate making sure nobody is touching the page
* contents. Doing the locking this way means that the commit to disk code in
* the page cache code paths is automatically sufficiently locked with us as
* we will not touch a page that has been locked or is not uptodate. The only
* locking problem then is them locking the page while we are accessing it.
*
* So that code will end up having to own the mrec_lock of all mft
* records/inodes present in the page before I/O can proceed. In that case we
* wouldn't need to bother with PG_locked and PG_uptodate as nobody will be
* accessing anything without owning the mrec_lock mutex. But we do need to
* use them because of the read_cache_page() invocation and the code becomes so
* much simpler this way that it is well worth it.
*
* The mft record is now ours and we return a pointer to it. You need to check
* the returned pointer with IS_ERR() and if that is true, PTR_ERR() will return
* the error code.
*
* NOTE: Caller is responsible for setting the mft record dirty before calling
* unmap_mft_record(). This is obviously only necessary if the caller really
* modified the mft record...
* Q: Do we want to recycle one of the VFS inode state bits instead?
* A: No, the inode ones mean we want to change the mft record, not we want to
* write it out.
*/
MFT_RECORD *map_mft_record(ntfs_inode *ni)
{
MFT_RECORD *m;
ntfs_debug("Entering for mft_no 0x%lx.", ni->mft_no);
/* Make sure the ntfs inode doesn't go away. */
atomic_inc(&ni->count);
/* Serialize access to this mft record. */
mutex_lock(&ni->mrec_lock);
m = map_mft_record_page(ni);
if (likely(!IS_ERR(m)))
return m;
mutex_unlock(&ni->mrec_lock);
atomic_dec(&ni->count);
ntfs_error(ni->vol->sb, "Failed with error code %lu.", -PTR_ERR(m));
return m;
}
/**
* unmap_mft_record_page - unmap the page in which a specific mft record resides
* @ni: ntfs inode whose mft record page to unmap
*
* This unmaps the page in which the mft record of the ntfs inode @ni is
* situated and returns. This is a NOOP if highmem is not configured.
*
* The unmap happens via ntfs_unmap_page() which in turn decrements the use
* count on the page thus releasing it from the pinned state.
*
* We do not actually unmap the page from memory of course, as that will be
* done by the page cache code itself when memory pressure increases or
* whatever.
*/
static inline void unmap_mft_record_page(ntfs_inode *ni)
{
BUG_ON(!ni->page);
// TODO: If dirty, blah...
ntfs_unmap_page(ni->page);
ni->page = NULL;
ni->page_ofs = 0;
return;
}
/**
* unmap_mft_record - release a mapped mft record
* @ni: ntfs inode whose MFT record to unmap
*
* We release the page mapping and the mrec_lock mutex which unmaps the mft
* record and releases it for others to get hold of. We also release the ntfs
* inode by decrementing the ntfs inode reference count.
*
* NOTE: If caller has modified the mft record, it is imperative to set the mft
* record dirty BEFORE calling unmap_mft_record().
*/
void unmap_mft_record(ntfs_inode *ni)
{
struct page *page = ni->page;
BUG_ON(!page);
ntfs_debug("Entering for mft_no 0x%lx.", ni->mft_no);
unmap_mft_record_page(ni);
mutex_unlock(&ni->mrec_lock);
atomic_dec(&ni->count);
/*
* If pure ntfs_inode, i.e. no vfs inode attached, we leave it to
* ntfs_clear_extent_inode() in the extent inode case, and to the
* caller in the non-extent, yet pure ntfs inode case, to do the actual
* tear down of all structures and freeing of all allocated memory.
*/
return;
}
/**
* map_extent_mft_record - load an extent inode and attach it to its base
* @base_ni: base ntfs inode
* @mref: mft reference of the extent inode to load
* @ntfs_ino: on successful return, pointer to the ntfs_inode structure
*
* Load the extent mft record @mref and attach it to its base inode @base_ni.
* Return the mapped extent mft record if IS_ERR(result) is false. Otherwise
* PTR_ERR(result) gives the negative error code.
*
* On successful return, @ntfs_ino contains a pointer to the ntfs_inode
* structure of the mapped extent inode.
*/
MFT_RECORD *map_extent_mft_record(ntfs_inode *base_ni, MFT_REF mref,
ntfs_inode **ntfs_ino)
{
MFT_RECORD *m;
ntfs_inode *ni = NULL;
ntfs_inode **extent_nis = NULL;
int i;
unsigned long mft_no = MREF(mref);
u16 seq_no = MSEQNO(mref);
bool destroy_ni = false;
ntfs_debug("Mapping extent mft record 0x%lx (base mft record 0x%lx).",
mft_no, base_ni->mft_no);
/* Make sure the base ntfs inode doesn't go away. */
atomic_inc(&base_ni->count);
/*
* Check if this extent inode has already been added to the base inode,
* in which case just return it. If not found, add it to the base
* inode before returning it.
*/
mutex_lock(&base_ni->extent_lock);
if (base_ni->nr_extents > 0) {
extent_nis = base_ni->ext.extent_ntfs_inos;
for (i = 0; i < base_ni->nr_extents; i++) {
if (mft_no != extent_nis[i]->mft_no)
continue;
ni = extent_nis[i];
/* Make sure the ntfs inode doesn't go away. */
atomic_inc(&ni->count);
break;
}
}
if (likely(ni != NULL)) {
mutex_unlock(&base_ni->extent_lock);
atomic_dec(&base_ni->count);
/* We found the record; just have to map and return it. */
m = map_mft_record(ni);
/* map_mft_record() has incremented this on success. */
atomic_dec(&ni->count);
if (likely(!IS_ERR(m))) {
/* Verify the sequence number. */
if (likely(le16_to_cpu(m->sequence_number) == seq_no)) {
ntfs_debug("Done 1.");
*ntfs_ino = ni;
return m;
}
unmap_mft_record(ni);
ntfs_error(base_ni->vol->sb, "Found stale extent mft "
"reference! Corrupt filesystem. "
"Run chkdsk.");
return ERR_PTR(-EIO);
}
map_err_out:
ntfs_error(base_ni->vol->sb, "Failed to map extent "
"mft record, error code %ld.", -PTR_ERR(m));
return m;
}
/* Record wasn't there. Get a new ntfs inode and initialize it. */
ni = ntfs_new_extent_inode(base_ni->vol->sb, mft_no);
if (unlikely(!ni)) {
mutex_unlock(&base_ni->extent_lock);
atomic_dec(&base_ni->count);
return ERR_PTR(-ENOMEM);
}
ni->vol = base_ni->vol;
ni->seq_no = seq_no;
ni->nr_extents = -1;
ni->ext.base_ntfs_ino = base_ni;
/* Now map the record. */
m = map_mft_record(ni);
if (IS_ERR(m)) {
mutex_unlock(&base_ni->extent_lock);
atomic_dec(&base_ni->count);
ntfs_clear_extent_inode(ni);
goto map_err_out;
}
/* Verify the sequence number if it is present. */
if (seq_no && (le16_to_cpu(m->sequence_number) != seq_no)) {
ntfs_error(base_ni->vol->sb, "Found stale extent mft "
"reference! Corrupt filesystem. Run chkdsk.");
destroy_ni = true;
m = ERR_PTR(-EIO);
goto unm_err_out;
}
/* Attach extent inode to base inode, reallocating memory if needed. */
if (!(base_ni->nr_extents & 3)) {
ntfs_inode **tmp;
int new_size = (base_ni->nr_extents + 4) * sizeof(ntfs_inode *);
tmp = kmalloc(new_size, GFP_NOFS);
if (unlikely(!tmp)) {
ntfs_error(base_ni->vol->sb, "Failed to allocate "
"internal buffer.");
destroy_ni = true;
m = ERR_PTR(-ENOMEM);
goto unm_err_out;
}
if (base_ni->nr_extents) {
BUG_ON(!base_ni->ext.extent_ntfs_inos);
memcpy(tmp, base_ni->ext.extent_ntfs_inos, new_size -
4 * sizeof(ntfs_inode *));
kfree(base_ni->ext.extent_ntfs_inos);
}
base_ni->ext.extent_ntfs_inos = tmp;
}
base_ni->ext.extent_ntfs_inos[base_ni->nr_extents++] = ni;
mutex_unlock(&base_ni->extent_lock);
atomic_dec(&base_ni->count);
ntfs_debug("Done 2.");
*ntfs_ino = ni;
return m;
unm_err_out:
unmap_mft_record(ni);
mutex_unlock(&base_ni->extent_lock);
atomic_dec(&base_ni->count);
/*
* If the extent inode was not attached to the base inode we need to
* release it or we will leak memory.
*/
if (destroy_ni)
ntfs_clear_extent_inode(ni);
return m;
}
#ifdef NTFS_RW
/**
* __mark_mft_record_dirty - set the mft record and the page containing it dirty
* @ni: ntfs inode describing the mapped mft record
*
* Internal function. Users should call mark_mft_record_dirty() instead.
*
* Set the mapped (extent) mft record of the (base or extent) ntfs inode @ni,
* as well as the page containing the mft record, dirty. Also, mark the base
* vfs inode dirty. This ensures that any changes to the mft record are
* written out to disk.
*
* NOTE: We only set I_DIRTY_SYNC and I_DIRTY_DATASYNC (and not I_DIRTY_PAGES)
* on the base vfs inode, because even though file data may have been modified,
* it is dirty in the inode meta data rather than the data page cache of the
* inode, and thus there are no data pages that need writing out. Therefore, a
* full mark_inode_dirty() is overkill. A mark_inode_dirty_sync(), on the
* other hand, is not sufficient, because ->write_inode needs to be called even
* in case of fdatasync. This needs to happen or the file data would not
* necessarily hit the device synchronously, even though the vfs inode has the
* O_SYNC flag set. Also, I_DIRTY_DATASYNC simply "feels" better than just
* I_DIRTY_SYNC, since the file data has not actually hit the block device yet,
* which is not what I_DIRTY_SYNC on its own would suggest.
*/
void __mark_mft_record_dirty(ntfs_inode *ni)
{
ntfs_inode *base_ni;
ntfs_debug("Entering for inode 0x%lx.", ni->mft_no);
BUG_ON(NInoAttr(ni));
mark_ntfs_record_dirty(ni->page, ni->page_ofs);
/* Determine the base vfs inode and mark it dirty, too. */
mutex_lock(&ni->extent_lock);
if (likely(ni->nr_extents >= 0))
base_ni = ni;
else
base_ni = ni->ext.base_ntfs_ino;
mutex_unlock(&ni->extent_lock);
__mark_inode_dirty(VFS_I(base_ni), I_DIRTY_SYNC | I_DIRTY_DATASYNC);
}
static const char *ntfs_please_email = "Please email "
"linux-ntfs-dev@lists.sourceforge.net and say that you saw "
"this message. Thank you.";
/**
* ntfs_sync_mft_mirror_umount - synchronise an mft record to the mft mirror
* @vol: ntfs volume on which the mft record to synchronize resides
* @mft_no: mft record number of mft record to synchronize
* @m: mapped, mst protected (extent) mft record to synchronize
*
* Write the mapped, mst protected (extent) mft record @m with mft record
* number @mft_no to the mft mirror ($MFTMirr) of the ntfs volume @vol,
* bypassing the page cache and the $MFTMirr inode itself.
*
* This function is only for use at umount time when the mft mirror inode has
* already been disposed off. We BUG() if we are called while the mft mirror
* inode is still attached to the volume.
*
* On success return 0. On error return -errno.
*
* NOTE: This function is not implemented yet as I am not convinced it can
* actually be triggered considering the sequence of commits we do in super.c::
* ntfs_put_super(). But just in case we provide this place holder as the
* alternative would be either to BUG() or to get a NULL pointer dereference
* and Oops.
*/
static int ntfs_sync_mft_mirror_umount(ntfs_volume *vol,
const unsigned long mft_no, MFT_RECORD *m)
{
BUG_ON(vol->mftmirr_ino);
ntfs_error(vol->sb, "Umount time mft mirror syncing is not "
"implemented yet. %s", ntfs_please_email);
return -EOPNOTSUPP;
}
/**
* ntfs_sync_mft_mirror - synchronize an mft record to the mft mirror
* @vol: ntfs volume on which the mft record to synchronize resides
* @mft_no: mft record number of mft record to synchronize
* @m: mapped, mst protected (extent) mft record to synchronize
* @sync: if true, wait for i/o completion
*
* Write the mapped, mst protected (extent) mft record @m with mft record
* number @mft_no to the mft mirror ($MFTMirr) of the ntfs volume @vol.
*
* On success return 0. On error return -errno and set the volume errors flag
* in the ntfs volume @vol.
*
* NOTE: We always perform synchronous i/o and ignore the @sync parameter.
*
* TODO: If @sync is false, want to do truly asynchronous i/o, i.e. just
* schedule i/o via ->writepage or do it via kntfsd or whatever.
*/
int ntfs_sync_mft_mirror(ntfs_volume *vol, const unsigned long mft_no,
MFT_RECORD *m, int sync)
{
struct page *page;
unsigned int blocksize = vol->sb->s_blocksize;
int max_bhs = vol->mft_record_size / blocksize;
struct buffer_head *bhs[max_bhs];
struct buffer_head *bh, *head;
u8 *kmirr;
runlist_element *rl;
unsigned int block_start, block_end, m_start, m_end, page_ofs;
int i_bhs, nr_bhs, err = 0;
unsigned char blocksize_bits = vol->sb->s_blocksize_bits;
ntfs_debug("Entering for inode 0x%lx.", mft_no);
BUG_ON(!max_bhs);
if (unlikely(!vol->mftmirr_ino)) {
/* This could happen during umount... */
err = ntfs_sync_mft_mirror_umount(vol, mft_no, m);
if (likely(!err))
return err;
goto err_out;
}
/* Get the page containing the mirror copy of the mft record @m. */
page = ntfs_map_page(vol->mftmirr_ino->i_mapping, mft_no >>
(PAGE_CACHE_SHIFT - vol->mft_record_size_bits));
if (IS_ERR(page)) {
ntfs_error(vol->sb, "Failed to map mft mirror page.");
err = PTR_ERR(page);
goto err_out;
}
lock_page(page);
BUG_ON(!PageUptodate(page));
ClearPageUptodate(page);
/* Offset of the mft mirror record inside the page. */
page_ofs = (mft_no << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
/* The address in the page of the mirror copy of the mft record @m. */
kmirr = page_address(page) + page_ofs;
/* Copy the mst protected mft record to the mirror. */
memcpy(kmirr, m, vol->mft_record_size);
/* Create uptodate buffers if not present. */
if (unlikely(!page_has_buffers(page))) {
struct buffer_head *tail;
bh = head = alloc_page_buffers(page, blocksize, 1);
do {
set_buffer_uptodate(bh);
tail = bh;
bh = bh->b_this_page;
} while (bh);
tail->b_this_page = head;
attach_page_buffers(page, head);
}
bh = head = page_buffers(page);
BUG_ON(!bh);
rl = NULL;
nr_bhs = 0;
block_start = 0;
m_start = kmirr - (u8*)page_address(page);
m_end = m_start + vol->mft_record_size;
do {
block_end = block_start + blocksize;
/* If the buffer is outside the mft record, skip it. */
if (block_end <= m_start)
continue;
if (unlikely(block_start >= m_end))
break;
/* Need to map the buffer if it is not mapped already. */
if (unlikely(!buffer_mapped(bh))) {
VCN vcn;
LCN lcn;
unsigned int vcn_ofs;
bh->b_bdev = vol->sb->s_bdev;
/* Obtain the vcn and offset of the current block. */
vcn = ((VCN)mft_no << vol->mft_record_size_bits) +
(block_start - m_start);
vcn_ofs = vcn & vol->cluster_size_mask;
vcn >>= vol->cluster_size_bits;
if (!rl) {
down_read(&NTFS_I(vol->mftmirr_ino)->
runlist.lock);
rl = NTFS_I(vol->mftmirr_ino)->runlist.rl;
/*
* $MFTMirr always has the whole of its runlist
* in memory.
*/
BUG_ON(!rl);
}
/* Seek to element containing target vcn. */
while (rl->length && rl[1].vcn <= vcn)
rl++;
lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
/* For $MFTMirr, only lcn >= 0 is a successful remap. */
if (likely(lcn >= 0)) {
/* Setup buffer head to correct block. */
bh->b_blocknr = ((lcn <<
vol->cluster_size_bits) +
vcn_ofs) >> blocksize_bits;
set_buffer_mapped(bh);
} else {
bh->b_blocknr = -1;
ntfs_error(vol->sb, "Cannot write mft mirror "
"record 0x%lx because its "
"location on disk could not "
"be determined (error code "
"%lli).", mft_no,
(long long)lcn);
err = -EIO;
}
}
BUG_ON(!buffer_uptodate(bh));
BUG_ON(!nr_bhs && (m_start != block_start));
BUG_ON(nr_bhs >= max_bhs);
bhs[nr_bhs++] = bh;
BUG_ON((nr_bhs >= max_bhs) && (m_end != block_end));
} while (block_start = block_end, (bh = bh->b_this_page) != head);
if (unlikely(rl))
up_read(&NTFS_I(vol->mftmirr_ino)->runlist.lock);
if (likely(!err)) {
/* Lock buffers and start synchronous write i/o on them. */
for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
struct buffer_head *tbh = bhs[i_bhs];
if (!trylock_buffer(tbh))
BUG();
BUG_ON(!buffer_uptodate(tbh));
clear_buffer_dirty(tbh);
get_bh(tbh);
tbh->b_end_io = end_buffer_write_sync;
submit_bh(WRITE, tbh);
}
/* Wait on i/o completion of buffers. */
for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
struct buffer_head *tbh = bhs[i_bhs];
wait_on_buffer(tbh);
if (unlikely(!buffer_uptodate(tbh))) {
err = -EIO;
/*
* Set the buffer uptodate so the page and
* buffer states do not become out of sync.
*/
set_buffer_uptodate(tbh);
}
}
} else /* if (unlikely(err)) */ {
/* Clean the buffers. */
for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++)
clear_buffer_dirty(bhs[i_bhs]);
}
/* Current state: all buffers are clean, unlocked, and uptodate. */
/* Remove the mst protection fixups again. */
post_write_mst_fixup((NTFS_RECORD*)kmirr);
flush_dcache_page(page);
SetPageUptodate(page);
unlock_page(page);
ntfs_unmap_page(page);
if (likely(!err)) {
ntfs_debug("Done.");
} else {
ntfs_error(vol->sb, "I/O error while writing mft mirror "
"record 0x%lx!", mft_no);
err_out:
ntfs_error(vol->sb, "Failed to synchronize $MFTMirr (error "
"code %i). Volume will be left marked dirty "
"on umount. Run ntfsfix on the partition "
"after umounting to correct this.", -err);
NVolSetErrors(vol);
}
return err;
}
/**
* write_mft_record_nolock - write out a mapped (extent) mft record
* @ni: ntfs inode describing the mapped (extent) mft record
* @m: mapped (extent) mft record to write
* @sync: if true, wait for i/o completion
*
* Write the mapped (extent) mft record @m described by the (regular or extent)
* ntfs inode @ni to backing store. If the mft record @m has a counterpart in
* the mft mirror, that is also updated.
*
* We only write the mft record if the ntfs inode @ni is dirty and the first
* buffer belonging to its mft record is dirty, too. We ignore the dirty state
* of subsequent buffers because we could have raced with
* fs/ntfs/aops.c::mark_ntfs_record_dirty().
*
* On success, clean the mft record and return 0. On error, leave the mft
* record dirty and return -errno.
*
* NOTE: We always perform synchronous i/o and ignore the @sync parameter.
* However, if the mft record has a counterpart in the mft mirror and @sync is
* true, we write the mft record, wait for i/o completion, and only then write
* the mft mirror copy. This ensures that if the system crashes either the mft
* or the mft mirror will contain a self-consistent mft record @m. If @sync is
* false on the other hand, we start i/o on both and then wait for completion
* on them. This provides a speedup but no longer guarantees that you will end
* up with a self-consistent mft record in the case of a crash but if you asked
* for asynchronous writing you probably do not care about that anyway.
*
* TODO: If @sync is false, want to do truly asynchronous i/o, i.e. just
* schedule i/o via ->writepage or do it via kntfsd or whatever.
*/
int write_mft_record_nolock(ntfs_inode *ni, MFT_RECORD *m, int sync)
{
ntfs_volume *vol = ni->vol;
struct page *page = ni->page;
unsigned int blocksize = vol->sb->s_blocksize;
unsigned char blocksize_bits = vol->sb->s_blocksize_bits;
int max_bhs = vol->mft_record_size / blocksize;
struct buffer_head *bhs[max_bhs];
struct buffer_head *bh, *head;
runlist_element *rl;
unsigned int block_start, block_end, m_start, m_end;
int i_bhs, nr_bhs, err = 0;
ntfs_debug("Entering for inode 0x%lx.", ni->mft_no);
BUG_ON(NInoAttr(ni));
BUG_ON(!max_bhs);
BUG_ON(!PageLocked(page));
/*
* If the ntfs_inode is clean no need to do anything. If it is dirty,
* mark it as clean now so that it can be redirtied later on if needed.
* There is no danger of races since the caller is holding the locks
* for the mft record @m and the page it is in.
*/
if (!NInoTestClearDirty(ni))
goto done;
bh = head = page_buffers(page);
BUG_ON(!bh);
rl = NULL;
nr_bhs = 0;
block_start = 0;
m_start = ni->page_ofs;
m_end = m_start + vol->mft_record_size;
do {
block_end = block_start + blocksize;
/* If the buffer is outside the mft record, skip it. */
if (block_end <= m_start)
continue;
if (unlikely(block_start >= m_end))
break;
/*
* If this block is not the first one in the record, we ignore
* the buffer's dirty state because we could have raced with a
* parallel mark_ntfs_record_dirty().
*/
if (block_start == m_start) {
/* This block is the first one in the record. */
if (!buffer_dirty(bh)) {
BUG_ON(nr_bhs);
/* Clean records are not written out. */
break;
}
}
/* Need to map the buffer if it is not mapped already. */
if (unlikely(!buffer_mapped(bh))) {
VCN vcn;
LCN lcn;
unsigned int vcn_ofs;
bh->b_bdev = vol->sb->s_bdev;
/* Obtain the vcn and offset of the current block. */
vcn = ((VCN)ni->mft_no << vol->mft_record_size_bits) +
(block_start - m_start);
vcn_ofs = vcn & vol->cluster_size_mask;
vcn >>= vol->cluster_size_bits;
if (!rl) {
down_read(&NTFS_I(vol->mft_ino)->runlist.lock);
rl = NTFS_I(vol->mft_ino)->runlist.rl;
BUG_ON(!rl);
}
/* Seek to element containing target vcn. */
while (rl->length && rl[1].vcn <= vcn)
rl++;
lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
/* For $MFT, only lcn >= 0 is a successful remap. */
if (likely(lcn >= 0)) {
/* Setup buffer head to correct block. */
bh->b_blocknr = ((lcn <<
vol->cluster_size_bits) +
vcn_ofs) >> blocksize_bits;
set_buffer_mapped(bh);
} else {
bh->b_blocknr = -1;
ntfs_error(vol->sb, "Cannot write mft record "
"0x%lx because its location "
"on disk could not be "
"determined (error code %lli).",
ni->mft_no, (long long)lcn);
err = -EIO;
}
}
BUG_ON(!buffer_uptodate(bh));
BUG_ON(!nr_bhs && (m_start != block_start));
BUG_ON(nr_bhs >= max_bhs);
bhs[nr_bhs++] = bh;
BUG_ON((nr_bhs >= max_bhs) && (m_end != block_end));
} while (block_start = block_end, (bh = bh->b_this_page) != head);
if (unlikely(rl))
up_read(&NTFS_I(vol->mft_ino)->runlist.lock);
if (!nr_bhs)
goto done;
if (unlikely(err))
goto cleanup_out;
/* Apply the mst protection fixups. */
err = pre_write_mst_fixup((NTFS_RECORD*)m, vol->mft_record_size);
if (err) {
ntfs_error(vol->sb, "Failed to apply mst fixups!");
goto cleanup_out;
}
flush_dcache_mft_record_page(ni);
/* Lock buffers and start synchronous write i/o on them. */
for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
struct buffer_head *tbh = bhs[i_bhs];
if (!trylock_buffer(tbh))
BUG();
BUG_ON(!buffer_uptodate(tbh));
clear_buffer_dirty(tbh);
get_bh(tbh);
tbh->b_end_io = end_buffer_write_sync;
submit_bh(WRITE, tbh);
}
/* Synchronize the mft mirror now if not @sync. */
if (!sync && ni->mft_no < vol->mftmirr_size)
ntfs_sync_mft_mirror(vol, ni->mft_no, m, sync);
/* Wait on i/o completion of buffers. */
for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
struct buffer_head *tbh = bhs[i_bhs];
wait_on_buffer(tbh);
if (unlikely(!buffer_uptodate(tbh))) {
err = -EIO;
/*
* Set the buffer uptodate so the page and buffer
* states do not become out of sync.
*/
if (PageUptodate(page))
set_buffer_uptodate(tbh);
}
}
/* If @sync, now synchronize the mft mirror. */
if (sync && ni->mft_no < vol->mftmirr_size)
ntfs_sync_mft_mirror(vol, ni->mft_no, m, sync);
/* Remove the mst protection fixups again. */
post_write_mst_fixup((NTFS_RECORD*)m);
flush_dcache_mft_record_page(ni);
if (unlikely(err)) {
/* I/O error during writing. This is really bad! */
ntfs_error(vol->sb, "I/O error while writing mft record "
"0x%lx! Marking base inode as bad. You "
"should unmount the volume and run chkdsk.",
ni->mft_no);
goto err_out;
}
done:
ntfs_debug("Done.");
return 0;
cleanup_out:
/* Clean the buffers. */
for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++)
clear_buffer_dirty(bhs[i_bhs]);
err_out:
/*
* Current state: all buffers are clean, unlocked, and uptodate.
* The caller should mark the base inode as bad so that no more i/o
* happens. ->clear_inode() will still be invoked so all extent inodes
* and other allocated memory will be freed.
*/
if (err == -ENOMEM) {
ntfs_error(vol->sb, "Not enough memory to write mft record. "
"Redirtying so the write is retried later.");
mark_mft_record_dirty(ni);
err = 0;
} else
NVolSetErrors(vol);
return err;
}
/**
* ntfs_may_write_mft_record - check if an mft record may be written out
* @vol: [IN] ntfs volume on which the mft record to check resides
* @mft_no: [IN] mft record number of the mft record to check
* @m: [IN] mapped mft record to check
* @locked_ni: [OUT] caller has to unlock this ntfs inode if one is returned
*
* Check if the mapped (base or extent) mft record @m with mft record number
* @mft_no belonging to the ntfs volume @vol may be written out. If necessary
* and possible the ntfs inode of the mft record is locked and the base vfs
* inode is pinned. The locked ntfs inode is then returned in @locked_ni. The
* caller is responsible for unlocking the ntfs inode and unpinning the base
* vfs inode.
*
* Return 'true' if the mft record may be written out and 'false' if not.
*
* The caller has locked the page and cleared the uptodate flag on it which
* means that we can safely write out any dirty mft records that do not have
* their inodes in icache as determined by ilookup5() as anyone
* opening/creating such an inode would block when attempting to map the mft
* record in read_cache_page() until we are finished with the write out.
*
* Here is a description of the tests we perform:
*
* If the inode is found in icache we know the mft record must be a base mft
* record. If it is dirty, we do not write it and return 'false' as the vfs
* inode write paths will result in the access times being updated which would
* cause the base mft record to be redirtied and written out again. (We know
* the access time update will modify the base mft record because Windows
* chkdsk complains if the standard information attribute is not in the base
* mft record.)
*
* If the inode is in icache and not dirty, we attempt to lock the mft record
* and if we find the lock was already taken, it is not safe to write the mft
* record and we return 'false'.
*
* If we manage to obtain the lock we have exclusive access to the mft record,
* which also allows us safe writeout of the mft record. We then set
* @locked_ni to the locked ntfs inode and return 'true'.
*
* Note we cannot just lock the mft record and sleep while waiting for the lock
* because this would deadlock due to lock reversal (normally the mft record is
* locked before the page is locked but we already have the page locked here
* when we try to lock the mft record).
*
* If the inode is not in icache we need to perform further checks.
*
* If the mft record is not a FILE record or it is a base mft record, we can
* safely write it and return 'true'.
*
* We now know the mft record is an extent mft record. We check if the inode
* corresponding to its base mft record is in icache and obtain a reference to
* it if it is. If it is not, we can safely write it and return 'true'.
*
* We now have the base inode for the extent mft record. We check if it has an
* ntfs inode for the extent mft record attached and if not it is safe to write
* the extent mft record and we return 'true'.
*
* The ntfs inode for the extent mft record is attached to the base inode so we
* attempt to lock the extent mft record and if we find the lock was already
* taken, it is not safe to write the extent mft record and we return 'false'.
*
* If we manage to obtain the lock we have exclusive access to the extent mft
* record, which also allows us safe writeout of the extent mft record. We
* set the ntfs inode of the extent mft record clean and then set @locked_ni to
* the now locked ntfs inode and return 'true'.
*
* Note, the reason for actually writing dirty mft records here and not just
* relying on the vfs inode dirty code paths is that we can have mft records
* modified without them ever having actual inodes in memory. Also we can have
* dirty mft records with clean ntfs inodes in memory. None of the described
* cases would result in the dirty mft records being written out if we only
* relied on the vfs inode dirty code paths. And these cases can really occur
* during allocation of new mft records and in particular when the
* initialized_size of the $MFT/$DATA attribute is extended and the new space
* is initialized using ntfs_mft_record_format(). The clean inode can then
* appear if the mft record is reused for a new inode before it got written
* out.
*/
bool ntfs_may_write_mft_record(ntfs_volume *vol, const unsigned long mft_no,
const MFT_RECORD *m, ntfs_inode **locked_ni)
{
struct super_block *sb = vol->sb;
struct inode *mft_vi = vol->mft_ino;
struct inode *vi;
ntfs_inode *ni, *eni, **extent_nis;
int i;
ntfs_attr na;
ntfs_debug("Entering for inode 0x%lx.", mft_no);
/*
* Normally we do not return a locked inode so set @locked_ni to NULL.
*/
BUG_ON(!locked_ni);
*locked_ni = NULL;
/*
* Check if the inode corresponding to this mft record is in the VFS
* inode cache and obtain a reference to it if it is.
*/
ntfs_debug("Looking for inode 0x%lx in icache.", mft_no);
na.mft_no = mft_no;
na.name = NULL;
na.name_len = 0;
na.type = AT_UNUSED;
/*
* Optimize inode 0, i.e. $MFT itself, since we have it in memory and
* we get here for it rather often.
*/
if (!mft_no) {
/* Balance the below iput(). */
vi = igrab(mft_vi);
BUG_ON(vi != mft_vi);
} else {
/*
* Have to use ilookup5_nowait() since ilookup5() waits for the
* inode lock which causes ntfs to deadlock when a concurrent
* inode write via the inode dirty code paths and the page
* dirty code path of the inode dirty code path when writing
* $MFT occurs.
*/
vi = ilookup5_nowait(sb, mft_no, (test_t)ntfs_test_inode, &na);
}
if (vi) {
ntfs_debug("Base inode 0x%lx is in icache.", mft_no);
/* The inode is in icache. */
ni = NTFS_I(vi);
/* Take a reference to the ntfs inode. */
atomic_inc(&ni->count);
/* If the inode is dirty, do not write this record. */
if (NInoDirty(ni)) {
ntfs_debug("Inode 0x%lx is dirty, do not write it.",
mft_no);
atomic_dec(&ni->count);
iput(vi);
return false;
}
ntfs_debug("Inode 0x%lx is not dirty.", mft_no);
/* The inode is not dirty, try to take the mft record lock. */
if (unlikely(!mutex_trylock(&ni->mrec_lock))) {
ntfs_debug("Mft record 0x%lx is already locked, do "
"not write it.", mft_no);
atomic_dec(&ni->count);
iput(vi);
return false;
}
ntfs_debug("Managed to lock mft record 0x%lx, write it.",
mft_no);
/*
* The write has to occur while we hold the mft record lock so
* return the locked ntfs inode.
*/
*locked_ni = ni;
return true;
}
ntfs_debug("Inode 0x%lx is not in icache.", mft_no);
/* The inode is not in icache. */
/* Write the record if it is not a mft record (type "FILE"). */
if (!ntfs_is_mft_record(m->magic)) {
ntfs_debug("Mft record 0x%lx is not a FILE record, write it.",
mft_no);
return true;
}
/* Write the mft record if it is a base inode. */
if (!m->base_mft_record) {
ntfs_debug("Mft record 0x%lx is a base record, write it.",
mft_no);
return true;
}
/*
* This is an extent mft record. Check if the inode corresponding to
* its base mft record is in icache and obtain a reference to it if it
* is.
*/
na.mft_no = MREF_LE(m->base_mft_record);
ntfs_debug("Mft record 0x%lx is an extent record. Looking for base "
"inode 0x%lx in icache.", mft_no, na.mft_no);
if (!na.mft_no) {
/* Balance the below iput(). */
vi = igrab(mft_vi);
BUG_ON(vi != mft_vi);
} else
vi = ilookup5_nowait(sb, na.mft_no, (test_t)ntfs_test_inode,
&na);
if (!vi) {
/*
* The base inode is not in icache, write this extent mft
* record.
*/
ntfs_debug("Base inode 0x%lx is not in icache, write the "
"extent record.", na.mft_no);
return true;
}
ntfs_debug("Base inode 0x%lx is in icache.", na.mft_no);
/*
* The base inode is in icache. Check if it has the extent inode
* corresponding to this extent mft record attached.
*/
ni = NTFS_I(vi);
mutex_lock(&ni->extent_lock);
if (ni->nr_extents <= 0) {
/*
* The base inode has no attached extent inodes, write this
* extent mft record.
*/
mutex_unlock(&ni->extent_lock);
iput(vi);
ntfs_debug("Base inode 0x%lx has no attached extent inodes, "
"write the extent record.", na.mft_no);
return true;
}
/* Iterate over the attached extent inodes. */
extent_nis = ni->ext.extent_ntfs_inos;
for (eni = NULL, i = 0; i < ni->nr_extents; ++i) {
if (mft_no == extent_nis[i]->mft_no) {
/*
* Found the extent inode corresponding to this extent
* mft record.
*/
eni = extent_nis[i];
break;
}
}
/*
* If the extent inode was not attached to the base inode, write this
* extent mft record.
*/
if (!eni) {
mutex_unlock(&ni->extent_lock);
iput(vi);
ntfs_debug("Extent inode 0x%lx is not attached to its base "
"inode 0x%lx, write the extent record.",
mft_no, na.mft_no);
return true;
}
ntfs_debug("Extent inode 0x%lx is attached to its base inode 0x%lx.",
mft_no, na.mft_no);
/* Take a reference to the extent ntfs inode. */
atomic_inc(&eni->count);
mutex_unlock(&ni->extent_lock);
/*
* Found the extent inode coresponding to this extent mft record.
* Try to take the mft record lock.
*/
if (unlikely(!mutex_trylock(&eni->mrec_lock))) {
atomic_dec(&eni->count);
iput(vi);
ntfs_debug("Extent mft record 0x%lx is already locked, do "
"not write it.", mft_no);
return false;
}
ntfs_debug("Managed to lock extent mft record 0x%lx, write it.",
mft_no);
if (NInoTestClearDirty(eni))
ntfs_debug("Extent inode 0x%lx is dirty, marking it clean.",
mft_no);
/*
* The write has to occur while we hold the mft record lock so return
* the locked extent ntfs inode.
*/
*locked_ni = eni;
return true;
}
static const char *es = " Leaving inconsistent metadata. Unmount and run "
"chkdsk.";
/**
* ntfs_mft_bitmap_find_and_alloc_free_rec_nolock - see name
* @vol: volume on which to search for a free mft record
* @base_ni: open base inode if allocating an extent mft record or NULL
*
* Search for a free mft record in the mft bitmap attribute on the ntfs volume
* @vol.
*
* If @base_ni is NULL start the search at the default allocator position.
*
* If @base_ni is not NULL start the search at the mft record after the base
* mft record @base_ni.
*
* Return the free mft record on success and -errno on error. An error code of
* -ENOSPC means that there are no free mft records in the currently
* initialized mft bitmap.
*
* Locking: Caller must hold vol->mftbmp_lock for writing.
*/
static int ntfs_mft_bitmap_find_and_alloc_free_rec_nolock(ntfs_volume *vol,
ntfs_inode *base_ni)
{
s64 pass_end, ll, data_pos, pass_start, ofs, bit;
unsigned long flags;
struct address_space *mftbmp_mapping;
u8 *buf, *byte;
struct page *page;
unsigned int page_ofs, size;
u8 pass, b;
ntfs_debug("Searching for free mft record in the currently "
"initialized mft bitmap.");
mftbmp_mapping = vol->mftbmp_ino->i_mapping;
/*
* Set the end of the pass making sure we do not overflow the mft
* bitmap.
*/
read_lock_irqsave(&NTFS_I(vol->mft_ino)->size_lock, flags);
pass_end = NTFS_I(vol->mft_ino)->allocated_size >>
vol->mft_record_size_bits;
read_unlock_irqrestore(&NTFS_I(vol->mft_ino)->size_lock, flags);
read_lock_irqsave(&NTFS_I(vol->mftbmp_ino)->size_lock, flags);
ll = NTFS_I(vol->mftbmp_ino)->initialized_size << 3;
read_unlock_irqrestore(&NTFS_I(vol->mftbmp_ino)->size_lock, flags);
if (pass_end > ll)
pass_end = ll;
pass = 1;
if (!base_ni)
data_pos = vol->mft_data_pos;
else
data_pos = base_ni->mft_no + 1;
if (data_pos < 24)
data_pos = 24;
if (data_pos >= pass_end) {
data_pos = 24;
pass = 2;
/* This happens on a freshly formatted volume. */
if (data_pos >= pass_end)
return -ENOSPC;
}
pass_start = data_pos;
ntfs_debug("Starting bitmap search: pass %u, pass_start 0x%llx, "
"pass_end 0x%llx, data_pos 0x%llx.", pass,
(long long)pass_start, (long long)pass_end,
(long long)data_pos);
/* Loop until a free mft record is found. */
for (; pass <= 2;) {
/* Cap size to pass_end. */
ofs = data_pos >> 3;
page_ofs = ofs & ~PAGE_CACHE_MASK;
size = PAGE_CACHE_SIZE - page_ofs;
ll = ((pass_end + 7) >> 3) - ofs;
if (size > ll)
size = ll;
size <<= 3;
/*
* If we are still within the active pass, search the next page
* for a zero bit.
*/
if (size) {
page = ntfs_map_page(mftbmp_mapping,
ofs >> PAGE_CACHE_SHIFT);
if (IS_ERR(page)) {
ntfs_error(vol->sb, "Failed to read mft "
"bitmap, aborting.");
return PTR_ERR(page);
}
buf = (u8*)page_address(page) + page_ofs;
bit = data_pos & 7;
data_pos &= ~7ull;
ntfs_debug("Before inner for loop: size 0x%x, "
"data_pos 0x%llx, bit 0x%llx", size,
(long long)data_pos, (long long)bit);
for (; bit < size && data_pos + bit < pass_end;
bit &= ~7ull, bit += 8) {
byte = buf + (bit >> 3);
if (*byte == 0xff)
continue;
b = ffz((unsigned long)*byte);
if (b < 8 && b >= (bit & 7)) {
ll = data_pos + (bit & ~7ull) + b;
if (unlikely(ll > (1ll << 32))) {
ntfs_unmap_page(page);
return -ENOSPC;
}
*byte |= 1 << b;
flush_dcache_page(page);
set_page_dirty(page);
ntfs_unmap_page(page);
ntfs_debug("Done. (Found and "
"allocated mft record "
"0x%llx.)",
(long long)ll);
return ll;
}
}
ntfs_debug("After inner for loop: size 0x%x, "
"data_pos 0x%llx, bit 0x%llx", size,
(long long)data_pos, (long long)bit);
data_pos += size;
ntfs_unmap_page(page);
/*
* If the end of the pass has not been reached yet,
* continue searching the mft bitmap for a zero bit.
*/
if (data_pos < pass_end)
continue;
}
/* Do the next pass. */
if (++pass == 2) {
/*
* Starting the second pass, in which we scan the first
* part of the zone which we omitted earlier.
*/
pass_end = pass_start;
data_pos = pass_start = 24;
ntfs_debug("pass %i, pass_start 0x%llx, pass_end "
"0x%llx.", pass, (long long)pass_start,
(long long)pass_end);
if (data_pos >= pass_end)
break;
}
}
/* No free mft records in currently initialized mft bitmap. */
ntfs_debug("Done. (No free mft records left in currently initialized "
"mft bitmap.)");
return -ENOSPC;
}
/**
* ntfs_mft_bitmap_extend_allocation_nolock - extend mft bitmap by a cluster
* @vol: volume on which to extend the mft bitmap attribute
*
* Extend the mft bitmap attribute on the ntfs volume @vol by one cluster.
*
* Note: Only changes allocated_size, i.e. does not touch initialized_size or
* data_size.
*
* Return 0 on success and -errno on error.
*
* Locking: - Caller must hold vol->mftbmp_lock for writing.
* - This function takes NTFS_I(vol->mftbmp_ino)->runlist.lock for
* writing and releases it before returning.
* - This function takes vol->lcnbmp_lock for writing and releases it
* before returning.
*/
static int ntfs_mft_bitmap_extend_allocation_nolock(ntfs_volume *vol)
{
LCN lcn;
s64 ll;
unsigned long flags;
struct page *page;
ntfs_inode *mft_ni, *mftbmp_ni;
runlist_element *rl, *rl2 = NULL;
ntfs_attr_search_ctx *ctx = NULL;
MFT_RECORD *mrec;
ATTR_RECORD *a = NULL;
int ret, mp_size;
u32 old_alen = 0;
u8 *b, tb;
struct {
u8 added_cluster:1;
u8 added_run:1;
u8 mp_rebuilt:1;
} status = { 0, 0, 0 };
ntfs_debug("Extending mft bitmap allocation.");
mft_ni = NTFS_I(vol->mft_ino);
mftbmp_ni = NTFS_I(vol->mftbmp_ino);
/*
* Determine the last lcn of the mft bitmap. The allocated size of the
* mft bitmap cannot be zero so we are ok to do this.
*/
down_write(&mftbmp_ni->runlist.lock);
read_lock_irqsave(&mftbmp_ni->size_lock, flags);
ll = mftbmp_ni->allocated_size;
read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
rl = ntfs_attr_find_vcn_nolock(mftbmp_ni,
(ll - 1) >> vol->cluster_size_bits, NULL);
if (unlikely(IS_ERR(rl) || !rl->length || rl->lcn < 0)) {
up_write(&mftbmp_ni->runlist.lock);
ntfs_error(vol->sb, "Failed to determine last allocated "
"cluster of mft bitmap attribute.");
if (!IS_ERR(rl))
ret = -EIO;
else
ret = PTR_ERR(rl);
return ret;
}
lcn = rl->lcn + rl->length;
ntfs_debug("Last lcn of mft bitmap attribute is 0x%llx.",
(long long)lcn);
/*
* Attempt to get the cluster following the last allocated cluster by
* hand as it may be in the MFT zone so the allocator would not give it
* to us.
*/
ll = lcn >> 3;
page = ntfs_map_page(vol->lcnbmp_ino->i_mapping,
ll >> PAGE_CACHE_SHIFT);
if (IS_ERR(page)) {
up_write(&mftbmp_ni->runlist.lock);
ntfs_error(vol->sb, "Failed to read from lcn bitmap.");
return PTR_ERR(page);
}
b = (u8*)page_address(page) + (ll & ~PAGE_CACHE_MASK);
tb = 1 << (lcn & 7ull);
down_write(&vol->lcnbmp_lock);
if (*b != 0xff && !(*b & tb)) {
/* Next cluster is free, allocate it. */
*b |= tb;
flush_dcache_page(page);
set_page_dirty(page);
up_write(&vol->lcnbmp_lock);
ntfs_unmap_page(page);
/* Update the mft bitmap runlist. */
rl->length++;
rl[1].vcn++;
status.added_cluster = 1;
ntfs_debug("Appending one cluster to mft bitmap.");
} else {
up_write(&vol->lcnbmp_lock);
ntfs_unmap_page(page);
/* Allocate a cluster from the DATA_ZONE. */
rl2 = ntfs_cluster_alloc(vol, rl[1].vcn, 1, lcn, DATA_ZONE,
true);
if (IS_ERR(rl2)) {
up_write(&mftbmp_ni->runlist.lock);
ntfs_error(vol->sb, "Failed to allocate a cluster for "
"the mft bitmap.");
return PTR_ERR(rl2);
}
rl = ntfs_runlists_merge(mftbmp_ni->runlist.rl, rl2);
if (IS_ERR(rl)) {
up_write(&mftbmp_ni->runlist.lock);
ntfs_error(vol->sb, "Failed to merge runlists for mft "
"bitmap.");
if (ntfs_cluster_free_from_rl(vol, rl2)) {
ntfs_error(vol->sb, "Failed to deallocate "
"allocated cluster.%s", es);
NVolSetErrors(vol);
}
ntfs_free(rl2);
return PTR_ERR(rl);
}
mftbmp_ni->runlist.rl = rl;
status.added_run = 1;
ntfs_debug("Adding one run to mft bitmap.");
/* Find the last run in the new runlist. */
for (; rl[1].length; rl++)
;
}
/*
* Update the attribute record as well. Note: @rl is the last
* (non-terminator) runlist element of mft bitmap.
*/
mrec = map_mft_record(mft_ni);
if (IS_ERR(mrec)) {
ntfs_error(vol->sb, "Failed to map mft record.");
ret = PTR_ERR(mrec);
goto undo_alloc;
}
ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
if (unlikely(!ctx)) {
ntfs_error(vol->sb, "Failed to get search context.");
ret = -ENOMEM;
goto undo_alloc;
}
ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
mftbmp_ni->name_len, CASE_SENSITIVE, rl[1].vcn, NULL,
0, ctx);
if (unlikely(ret)) {
ntfs_error(vol->sb, "Failed to find last attribute extent of "
"mft bitmap attribute.");
if (ret == -ENOENT)
ret = -EIO;
goto undo_alloc;
}
a = ctx->attr;
ll = sle64_to_cpu(a->data.non_resident.lowest_vcn);
/* Search back for the previous last allocated cluster of mft bitmap. */
for (rl2 = rl; rl2 > mftbmp_ni->runlist.rl; rl2--) {
if (ll >= rl2->vcn)
break;
}
BUG_ON(ll < rl2->vcn);
BUG_ON(ll >= rl2->vcn + rl2->length);
/* Get the size for the new mapping pairs array for this extent. */
mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, ll, -1);
if (unlikely(mp_size <= 0)) {
ntfs_error(vol->sb, "Get size for mapping pairs failed for "
"mft bitmap attribute extent.");
ret = mp_size;
if (!ret)
ret = -EIO;
goto undo_alloc;
}
/* Expand the attribute record if necessary. */
old_alen = le32_to_cpu(a->length);
ret = ntfs_attr_record_resize(ctx->mrec, a, mp_size +
le16_to_cpu(a->data.non_resident.mapping_pairs_offset));
if (unlikely(ret)) {
if (ret != -ENOSPC) {
ntfs_error(vol->sb, "Failed to resize attribute "
"record for mft bitmap attribute.");
goto undo_alloc;
}
// TODO: Deal with this by moving this extent to a new mft
// record or by starting a new extent in a new mft record or by
// moving other attributes out of this mft record.
// Note: It will need to be a special mft record and if none of
// those are available it gets rather complicated...
ntfs_error(vol->sb, "Not enough space in this mft record to "
"accommodate extended mft bitmap attribute "
"extent. Cannot handle this yet.");
ret = -EOPNOTSUPP;
goto undo_alloc;
}
status.mp_rebuilt = 1;
/* Generate the mapping pairs array directly into the attr record. */
ret = ntfs_mapping_pairs_build(vol, (u8*)a +
le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
mp_size, rl2, ll, -1, NULL);
if (unlikely(ret)) {
ntfs_error(vol->sb, "Failed to build mapping pairs array for "
"mft bitmap attribute.");
goto undo_alloc;
}
/* Update the highest_vcn. */
a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 1);
/*
* We now have extended the mft bitmap allocated_size by one cluster.
* Reflect this in the ntfs_inode structure and the attribute record.
*/
if (a->data.non_resident.lowest_vcn) {
/*
* We are not in the first attribute extent, switch to it, but
* first ensure the changes will make it to disk later.
*/
flush_dcache_mft_record_page(ctx->ntfs_ino);
mark_mft_record_dirty(ctx->ntfs_ino);
ntfs_attr_reinit_search_ctx(ctx);
ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL,
0, ctx);
if (unlikely(ret)) {
ntfs_error(vol->sb, "Failed to find first attribute "
"extent of mft bitmap attribute.");
goto restore_undo_alloc;
}
a = ctx->attr;
}
write_lock_irqsave(&mftbmp_ni->size_lock, flags);
mftbmp_ni->allocated_size += vol->cluster_size;
a->data.non_resident.allocated_size =
cpu_to_sle64(mftbmp_ni->allocated_size);
write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
/* Ensure the changes make it to disk. */
flush_dcache_mft_record_page(ctx->ntfs_ino);
mark_mft_record_dirty(ctx->ntfs_ino);
ntfs_attr_put_search_ctx(ctx);
unmap_mft_record(mft_ni);
up_write(&mftbmp_ni->runlist.lock);
ntfs_debug("Done.");
return 0;
restore_undo_alloc:
ntfs_attr_reinit_search_ctx(ctx);
if (ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
mftbmp_ni->name_len, CASE_SENSITIVE, rl[1].vcn, NULL,
0, ctx)) {
ntfs_error(vol->sb, "Failed to find last attribute extent of "
"mft bitmap attribute.%s", es);
write_lock_irqsave(&mftbmp_ni->size_lock, flags);
mftbmp_ni->allocated_size += vol->cluster_size;
write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
ntfs_attr_put_search_ctx(ctx);
unmap_mft_record(mft_ni);
up_write(&mftbmp_ni->runlist.lock);
/*
* The only thing that is now wrong is ->allocated_size of the
* base attribute extent which chkdsk should be able to fix.
*/
NVolSetErrors(vol);
return ret;
}
a = ctx->attr;
a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 2);
undo_alloc:
if (status.added_cluster) {
/* Truncate the last run in the runlist by one cluster. */
rl->length--;
rl[1].vcn--;
} else if (status.added_run) {
lcn = rl->lcn;
/* Remove the last run from the runlist. */
rl->lcn = rl[1].lcn;
rl->length = 0;
}
/* Deallocate the cluster. */
down_write(&vol->lcnbmp_lock);
if (ntfs_bitmap_clear_bit(vol->lcnbmp_ino, lcn)) {
ntfs_error(vol->sb, "Failed to free allocated cluster.%s", es);
NVolSetErrors(vol);
}
up_write(&vol->lcnbmp_lock);
if (status.mp_rebuilt) {
if (ntfs_mapping_pairs_build(vol, (u8*)a + le16_to_cpu(
a->data.non_resident.mapping_pairs_offset),
old_alen - le16_to_cpu(
a->data.non_resident.mapping_pairs_offset),
rl2, ll, -1, NULL)) {
ntfs_error(vol->sb, "Failed to restore mapping pairs "
"array.%s", es);
NVolSetErrors(vol);
}
if (ntfs_attr_record_resize(ctx->mrec, a, old_alen)) {
ntfs_error(vol->sb, "Failed to restore attribute "
"record.%s", es);
NVolSetErrors(vol);
}
flush_dcache_mft_record_page(ctx->ntfs_ino);
mark_mft_record_dirty(ctx->ntfs_ino);
}
if (ctx)
ntfs_attr_put_search_ctx(ctx);
if (!IS_ERR(mrec))
unmap_mft_record(mft_ni);
up_write(&mftbmp_ni->runlist.lock);
return ret;
}
/**
* ntfs_mft_bitmap_extend_initialized_nolock - extend mftbmp initialized data
* @vol: volume on which to extend the mft bitmap attribute
*
* Extend the initialized portion of the mft bitmap attribute on the ntfs
* volume @vol by 8 bytes.
*
* Note: Only changes initialized_size and data_size, i.e. requires that
* allocated_size is big enough to fit the new initialized_size.
*
* Return 0 on success and -error on error.
*
* Locking: Caller must hold vol->mftbmp_lock for writing.
*/
static int ntfs_mft_bitmap_extend_initialized_nolock(ntfs_volume *vol)
{
s64 old_data_size, old_initialized_size;
unsigned long flags;
struct inode *mftbmp_vi;
ntfs_inode *mft_ni, *mftbmp_ni;
ntfs_attr_search_ctx *ctx;
MFT_RECORD *mrec;
ATTR_RECORD *a;
int ret;
ntfs_debug("Extending mft bitmap initiailized (and data) size.");
mft_ni = NTFS_I(vol->mft_ino);
mftbmp_vi = vol->mftbmp_ino;
mftbmp_ni = NTFS_I(mftbmp_vi);
/* Get the attribute record. */
mrec = map_mft_record(mft_ni);
if (IS_ERR(mrec)) {
ntfs_error(vol->sb, "Failed to map mft record.");
return PTR_ERR(mrec);
}
ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
if (unlikely(!ctx)) {
ntfs_error(vol->sb, "Failed to get search context.");
ret = -ENOMEM;
goto unm_err_out;
}
ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL, 0, ctx);
if (unlikely(ret)) {
ntfs_error(vol->sb, "Failed to find first attribute extent of "
"mft bitmap attribute.");
if (ret == -ENOENT)
ret = -EIO;
goto put_err_out;
}
a = ctx->attr;
write_lock_irqsave(&mftbmp_ni->size_lock, flags);
old_data_size = i_size_read(mftbmp_vi);
old_initialized_size = mftbmp_ni->initialized_size;
/*
* We can simply update the initialized_size before filling the space
* with zeroes because the caller is holding the mft bitmap lock for
* writing which ensures that no one else is trying to access the data.
*/
mftbmp_ni->initialized_size += 8;
a->data.non_resident.initialized_size =
cpu_to_sle64(mftbmp_ni->initialized_size);
if (mftbmp_ni->initialized_size > old_data_size) {
i_size_write(mftbmp_vi, mftbmp_ni->initialized_size);
a->data.non_resident.data_size =
cpu_to_sle64(mftbmp_ni->initialized_size);
}
write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
/* Ensure the changes make it to disk. */
flush_dcache_mft_record_page(ctx->ntfs_ino);
mark_mft_record_dirty(ctx->ntfs_ino);
ntfs_attr_put_search_ctx(ctx);
unmap_mft_record(mft_ni);
/* Initialize the mft bitmap attribute value with zeroes. */
ret = ntfs_attr_set(mftbmp_ni, old_initialized_size, 8, 0);
if (likely(!ret)) {
ntfs_debug("Done. (Wrote eight initialized bytes to mft "
"bitmap.");
return 0;
}
ntfs_error(vol->sb, "Failed to write to mft bitmap.");
/* Try to recover from the error. */
mrec = map_mft_record(mft_ni);
if (IS_ERR(mrec)) {
ntfs_error(vol->sb, "Failed to map mft record.%s", es);
NVolSetErrors(vol);
return ret;
}
ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
if (unlikely(!ctx)) {
ntfs_error(vol->sb, "Failed to get search context.%s", es);
NVolSetErrors(vol);
goto unm_err_out;
}
if (ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL, 0, ctx)) {
ntfs_error(vol->sb, "Failed to find first attribute extent of "
"mft bitmap attribute.%s", es);
NVolSetErrors(vol);
put_err_out:
ntfs_attr_put_search_ctx(ctx);
unm_err_out:
unmap_mft_record(mft_ni);
goto err_out;
}
a = ctx->attr;
write_lock_irqsave(&mftbmp_ni->size_lock, flags);
mftbmp_ni->initialized_size = old_initialized_size;
a->data.non_resident.initialized_size =
cpu_to_sle64(old_initialized_size);
if (i_size_read(mftbmp_vi) != old_data_size) {
i_size_write(mftbmp_vi, old_data_size);
a->data.non_resident.data_size = cpu_to_sle64(old_data_size);
}
write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
flush_dcache_mft_record_page(ctx->ntfs_ino);
mark_mft_record_dirty(ctx->ntfs_ino);
ntfs_attr_put_search_ctx(ctx);
unmap_mft_record(mft_ni);
#ifdef DEBUG
read_lock_irqsave(&mftbmp_ni->size_lock, flags);
ntfs_debug("Restored status of mftbmp: allocated_size 0x%llx, "
"data_size 0x%llx, initialized_size 0x%llx.",
(long long)mftbmp_ni->allocated_size,
(long long)i_size_read(mftbmp_vi),
(long long)mftbmp_ni->initialized_size);
read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
#endif /* DEBUG */
err_out:
return ret;
}
/**
* ntfs_mft_data_extend_allocation_nolock - extend mft data attribute
* @vol: volume on which to extend the mft data attribute
*
* Extend the mft data attribute on the ntfs volume @vol by 16 mft records
* worth of clusters or if not enough space for this by one mft record worth
* of clusters.
*
* Note: Only changes allocated_size, i.e. does not touch initialized_size or
* data_size.
*
* Return 0 on success and -errno on error.
*
* Locking: - Caller must hold vol->mftbmp_lock for writing.
* - This function takes NTFS_I(vol->mft_ino)->runlist.lock for
* writing and releases it before returning.
* - This function calls functions which take vol->lcnbmp_lock for
* writing and release it before returning.
*/
static int ntfs_mft_data_extend_allocation_nolock(ntfs_volume *vol)
{
LCN lcn;
VCN old_last_vcn;
s64 min_nr, nr, ll;
unsigned long flags;
ntfs_inode *mft_ni;
runlist_element *rl, *rl2;
ntfs_attr_search_ctx *ctx = NULL;
MFT_RECORD *mrec;
ATTR_RECORD *a = NULL;
int ret, mp_size;
u32 old_alen = 0;
bool mp_rebuilt = false;
ntfs_debug("Extending mft data allocation.");
mft_ni = NTFS_I(vol->mft_ino);
/*
* Determine the preferred allocation location, i.e. the last lcn of
* the mft data attribute. The allocated size of the mft data
* attribute cannot be zero so we are ok to do this.
*/
down_write(&mft_ni->runlist.lock);
read_lock_irqsave(&mft_ni->size_lock, flags);
ll = mft_ni->allocated_size;
read_unlock_irqrestore(&mft_ni->size_lock, flags);
rl = ntfs_attr_find_vcn_nolock(mft_ni,
(ll - 1) >> vol->cluster_size_bits, NULL);
if (unlikely(IS_ERR(rl) || !rl->length || rl->lcn < 0)) {
up_write(&mft_ni->runlist.lock);
ntfs_error(vol->sb, "Failed to determine last allocated "
"cluster of mft data attribute.");
if (!IS_ERR(rl))
ret = -EIO;
else
ret = PTR_ERR(rl);
return ret;
}
lcn = rl->lcn + rl->length;
ntfs_debug("Last lcn of mft data attribute is 0x%llx.", (long long)lcn);
/* Minimum allocation is one mft record worth of clusters. */
min_nr = vol->mft_record_size >> vol->cluster_size_bits;
if (!min_nr)
min_nr = 1;
/* Want to allocate 16 mft records worth of clusters. */
nr = vol->mft_record_size << 4 >> vol->cluster_size_bits;
if (!nr)
nr = min_nr;
/* Ensure we do not go above 2^32-1 mft records. */
read_lock_irqsave(&mft_ni->size_lock, flags);
ll = mft_ni->allocated_size;
read_unlock_irqrestore(&mft_ni->size_lock, flags);
if (unlikely((ll + (nr << vol->cluster_size_bits)) >>
vol->mft_record_size_bits >= (1ll << 32))) {
nr = min_nr;
if (unlikely((ll + (nr << vol->cluster_size_bits)) >>
vol->mft_record_size_bits >= (1ll << 32))) {
ntfs_warning(vol->sb, "Cannot allocate mft record "
"because the maximum number of inodes "
"(2^32) has already been reached.");
up_write(&mft_ni->runlist.lock);
return -ENOSPC;
}
}
ntfs_debug("Trying mft data allocation with %s cluster count %lli.",
nr > min_nr ? "default" : "minimal", (long long)nr);
old_last_vcn = rl[1].vcn;
do {
rl2 = ntfs_cluster_alloc(vol, old_last_vcn, nr, lcn, MFT_ZONE,
true);
if (likely(!IS_ERR(rl2)))
break;
if (PTR_ERR(rl2) != -ENOSPC || nr == min_nr) {
ntfs_error(vol->sb, "Failed to allocate the minimal "
"number of clusters (%lli) for the "
"mft data attribute.", (long long)nr);
up_write(&mft_ni->runlist.lock);
return PTR_ERR(rl2);
}
/*
* There is not enough space to do the allocation, but there
* might be enough space to do a minimal allocation so try that
* before failing.
*/
nr = min_nr;
ntfs_debug("Retrying mft data allocation with minimal cluster "
"count %lli.", (long long)nr);
} while (1);
rl = ntfs_runlists_merge(mft_ni->runlist.rl, rl2);
if (IS_ERR(rl)) {
up_write(&mft_ni->runlist.lock);
ntfs_error(vol->sb, "Failed to merge runlists for mft data "
"attribute.");
if (ntfs_cluster_free_from_rl(vol, rl2)) {
ntfs_error(vol->sb, "Failed to deallocate clusters "
"from the mft data attribute.%s", es);
NVolSetErrors(vol);
}
ntfs_free(rl2);
return PTR_ERR(rl);
}
mft_ni->runlist.rl = rl;
ntfs_debug("Allocated %lli clusters.", (long long)nr);
/* Find the last run in the new runlist. */
for (; rl[1].length; rl++)
;
/* Update the attribute record as well. */
mrec = map_mft_record(mft_ni);
if (IS_ERR(mrec)) {
ntfs_error(vol->sb, "Failed to map mft record.");
ret = PTR_ERR(mrec);
goto undo_alloc;
}
ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
if (unlikely(!ctx)) {
ntfs_error(vol->sb, "Failed to get search context.");
ret = -ENOMEM;
goto undo_alloc;
}
ret = ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
CASE_SENSITIVE, rl[1].vcn, NULL, 0, ctx);
if (unlikely(ret)) {
ntfs_error(vol->sb, "Failed to find last attribute extent of "
"mft data attribute.");
if (ret == -ENOENT)
ret = -EIO;
goto undo_alloc;
}
a = ctx->attr;
ll = sle64_to_cpu(a->data.non_resident.lowest_vcn);
/* Search back for the previous last allocated cluster of mft bitmap. */
for (rl2 = rl; rl2 > mft_ni->runlist.rl; rl2--) {
if (ll >= rl2->vcn)
break;
}
BUG_ON(ll < rl2->vcn);
BUG_ON(ll >= rl2->vcn + rl2->length);
/* Get the size for the new mapping pairs array for this extent. */
mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, ll, -1);
if (unlikely(mp_size <= 0)) {
ntfs_error(vol->sb, "Get size for mapping pairs failed for "
"mft data attribute extent.");
ret = mp_size;
if (!ret)
ret = -EIO;
goto undo_alloc;
}
/* Expand the attribute record if necessary. */
old_alen = le32_to_cpu(a->length);
ret = ntfs_attr_record_resize(ctx->mrec, a, mp_size +
le16_to_cpu(a->data.non_resident.mapping_pairs_offset));
if (unlikely(ret)) {
if (ret != -ENOSPC) {
ntfs_error(vol->sb, "Failed to resize attribute "
"record for mft data attribute.");
goto undo_alloc;
}
// TODO: Deal with this by moving this extent to a new mft
// record or by starting a new extent in a new mft record or by
// moving other attributes out of this mft record.
// Note: Use the special reserved mft records and ensure that
// this extent is not required to find the mft record in
// question. If no free special records left we would need to
// move an existing record away, insert ours in its place, and
// then place the moved record into the newly allocated space
// and we would then need to update all references to this mft
// record appropriately. This is rather complicated...
ntfs_error(vol->sb, "Not enough space in this mft record to "
"accommodate extended mft data attribute "
"extent. Cannot handle this yet.");
ret = -EOPNOTSUPP;
goto undo_alloc;
}
mp_rebuilt = true;
/* Generate the mapping pairs array directly into the attr record. */
ret = ntfs_mapping_pairs_build(vol, (u8*)a +
le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
mp_size, rl2, ll, -1, NULL);
if (unlikely(ret)) {
ntfs_error(vol->sb, "Failed to build mapping pairs array of "
"mft data attribute.");
goto undo_alloc;
}
/* Update the highest_vcn. */
a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 1);
/*
* We now have extended the mft data allocated_size by nr clusters.
* Reflect this in the ntfs_inode structure and the attribute record.
* @rl is the last (non-terminator) runlist element of mft data
* attribute.
*/
if (a->data.non_resident.lowest_vcn) {
/*
* We are not in the first attribute extent, switch to it, but
* first ensure the changes will make it to disk later.
*/
flush_dcache_mft_record_page(ctx->ntfs_ino);
mark_mft_record_dirty(ctx->ntfs_ino);
ntfs_attr_reinit_search_ctx(ctx);
ret = ntfs_attr_lookup(mft_ni->type, mft_ni->name,
mft_ni->name_len, CASE_SENSITIVE, 0, NULL, 0,
ctx);
if (unlikely(ret)) {
ntfs_error(vol->sb, "Failed to find first attribute "
"extent of mft data attribute.");
goto restore_undo_alloc;
}
a = ctx->attr;
}
write_lock_irqsave(&mft_ni->size_lock, flags);
mft_ni->allocated_size += nr << vol->cluster_size_bits;
a->data.non_resident.allocated_size =
cpu_to_sle64(mft_ni->allocated_size);
write_unlock_irqrestore(&mft_ni->size_lock, flags);
/* Ensure the changes make it to disk. */
flush_dcache_mft_record_page(ctx->ntfs_ino);
mark_mft_record_dirty(ctx->ntfs_ino);
ntfs_attr_put_search_ctx(ctx);
unmap_mft_record(mft_ni);
up_write(&mft_ni->runlist.lock);
ntfs_debug("Done.");
return 0;
restore_undo_alloc:
ntfs_attr_reinit_search_ctx(ctx);
if (ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
CASE_SENSITIVE, rl[1].vcn, NULL, 0, ctx)) {
ntfs_error(vol->sb, "Failed to find last attribute extent of "
"mft data attribute.%s", es);
write_lock_irqsave(&mft_ni->size_lock, flags);
mft_ni->allocated_size += nr << vol->cluster_size_bits;
write_unlock_irqrestore(&mft_ni->size_lock, flags);
ntfs_attr_put_search_ctx(ctx);
unmap_mft_record(mft_ni);
up_write(&mft_ni->runlist.lock);
/*
* The only thing that is now wrong is ->allocated_size of the
* base attribute extent which chkdsk should be able to fix.
*/
NVolSetErrors(vol);
return ret;
}
ctx->attr->data.non_resident.highest_vcn =
cpu_to_sle64(old_last_vcn - 1);
undo_alloc:
if (ntfs_cluster_free(mft_ni, old_last_vcn, -1, ctx) < 0) {
ntfs_error(vol->sb, "Failed to free clusters from mft data "
"attribute.%s", es);
NVolSetErrors(vol);
}
a = ctx->attr;
if (ntfs_rl_truncate_nolock(vol, &mft_ni->runlist, old_last_vcn)) {
ntfs_error(vol->sb, "Failed to truncate mft data attribute "
"runlist.%s", es);
NVolSetErrors(vol);
}
if (mp_rebuilt && !IS_ERR(ctx->mrec)) {
if (ntfs_mapping_pairs_build(vol, (u8*)a + le16_to_cpu(
a->data.non_resident.mapping_pairs_offset),
old_alen - le16_to_cpu(
a->data.non_resident.mapping_pairs_offset),
rl2, ll, -1, NULL)) {
ntfs_error(vol->sb, "Failed to restore mapping pairs "
"array.%s", es);
NVolSetErrors(vol);
}
if (ntfs_attr_record_resize(ctx->mrec, a, old_alen)) {
ntfs_error(vol->sb, "Failed to restore attribute "
"record.%s", es);
NVolSetErrors(vol);
}
flush_dcache_mft_record_page(ctx->ntfs_ino);
mark_mft_record_dirty(ctx->ntfs_ino);
} else if (IS_ERR(ctx->mrec)) {
ntfs_error(vol->sb, "Failed to restore attribute search "
"context.%s", es);
NVolSetErrors(vol);
}
if (ctx)
ntfs_attr_put_search_ctx(ctx);
if (!IS_ERR(mrec))
unmap_mft_record(mft_ni);
up_write(&mft_ni->runlist.lock);
return ret;
}
/**
* ntfs_mft_record_layout - layout an mft record into a memory buffer
* @vol: volume to which the mft record will belong
* @mft_no: mft reference specifying the mft record number
* @m: destination buffer of size >= @vol->mft_record_size bytes
*
* Layout an empty, unused mft record with the mft record number @mft_no into
* the buffer @m. The volume @vol is needed because the mft record structure
* was modified in NTFS 3.1 so we need to know which volume version this mft
* record will be used on.
*
* Return 0 on success and -errno on error.
*/
static int ntfs_mft_record_layout(const ntfs_volume *vol, const s64 mft_no,
MFT_RECORD *m)
{
ATTR_RECORD *a;
ntfs_debug("Entering for mft record 0x%llx.", (long long)mft_no);
if (mft_no >= (1ll << 32)) {
ntfs_error(vol->sb, "Mft record number 0x%llx exceeds "
"maximum of 2^32.", (long long)mft_no);
return -ERANGE;
}
/* Start by clearing the whole mft record to gives us a clean slate. */
memset(m, 0, vol->mft_record_size);
/* Aligned to 2-byte boundary. */
if (vol->major_ver < 3 || (vol->major_ver == 3 && !vol->minor_ver))
m->usa_ofs = cpu_to_le16((sizeof(MFT_RECORD_OLD) + 1) & ~1);
else {
m->usa_ofs = cpu_to_le16((sizeof(MFT_RECORD) + 1) & ~1);
/*
* Set the NTFS 3.1+ specific fields while we know that the
* volume version is 3.1+.
*/
m->reserved = 0;
m->mft_record_number = cpu_to_le32((u32)mft_no);
}
m->magic = magic_FILE;
if (vol->mft_record_size >= NTFS_BLOCK_SIZE)
m->usa_count = cpu_to_le16(vol->mft_record_size /
NTFS_BLOCK_SIZE + 1);
else {
m->usa_count = cpu_to_le16(1);
ntfs_warning(vol->sb, "Sector size is bigger than mft record "
"size. Setting usa_count to 1. If chkdsk "
"reports this as corruption, please email "
"linux-ntfs-dev@lists.sourceforge.net stating "
"that you saw this message and that the "
"modified filesystem created was corrupt. "
"Thank you.");
}
/* Set the update sequence number to 1. */
*(le16*)((u8*)m + le16_to_cpu(m->usa_ofs)) = cpu_to_le16(1);
m->lsn = 0;
m->sequence_number = cpu_to_le16(1);
m->link_count = 0;
/*
* Place the attributes straight after the update sequence array,
* aligned to 8-byte boundary.
*/
m->attrs_offset = cpu_to_le16((le16_to_cpu(m->usa_ofs) +
(le16_to_cpu(m->usa_count) << 1) + 7) & ~7);
m->flags = 0;
/*
* Using attrs_offset plus eight bytes (for the termination attribute).
* attrs_offset is already aligned to 8-byte boundary, so no need to
* align again.
*/
m->bytes_in_use = cpu_to_le32(le16_to_cpu(m->attrs_offset) + 8);
m->bytes_allocated = cpu_to_le32(vol->mft_record_size);
m->base_mft_record = 0;
m->next_attr_instance = 0;
/* Add the termination attribute. */
a = (ATTR_RECORD*)((u8*)m + le16_to_cpu(m->attrs_offset));
a->type = AT_END;
a->length = 0;
ntfs_debug("Done.");
return 0;
}
/**
* ntfs_mft_record_format - format an mft record on an ntfs volume
* @vol: volume on which to format the mft record
* @mft_no: mft record number to format
*
* Format the mft record @mft_no in $MFT/$DATA, i.e. lay out an empty, unused
* mft record into the appropriate place of the mft data attribute. This is
* used when extending the mft data attribute.
*
* Return 0 on success and -errno on error.
*/
static int ntfs_mft_record_format(const ntfs_volume *vol, const s64 mft_no)
{
loff_t i_size;
struct inode *mft_vi = vol->mft_ino;
struct page *page;
MFT_RECORD *m;
pgoff_t index, end_index;
unsigned int ofs;
int err;
ntfs_debug("Entering for mft record 0x%llx.", (long long)mft_no);
/*
* The index into the page cache and the offset within the page cache
* page of the wanted mft record.
*/
index = mft_no << vol->mft_record_size_bits >> PAGE_CACHE_SHIFT;
ofs = (mft_no << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
/* The maximum valid index into the page cache for $MFT's data. */
i_size = i_size_read(mft_vi);
end_index = i_size >> PAGE_CACHE_SHIFT;
if (unlikely(index >= end_index)) {
if (unlikely(index > end_index || ofs + vol->mft_record_size >=
(i_size & ~PAGE_CACHE_MASK))) {
ntfs_error(vol->sb, "Tried to format non-existing mft "
"record 0x%llx.", (long long)mft_no);
return -ENOENT;
}
}
/* Read, map, and pin the page containing the mft record. */
page = ntfs_map_page(mft_vi->i_mapping, index);
if (IS_ERR(page)) {
ntfs_error(vol->sb, "Failed to map page containing mft record "
"to format 0x%llx.", (long long)mft_no);
return PTR_ERR(page);
}
lock_page(page);
BUG_ON(!PageUptodate(page));
ClearPageUptodate(page);
m = (MFT_RECORD*)((u8*)page_address(page) + ofs);
err = ntfs_mft_record_layout(vol, mft_no, m);
if (unlikely(err)) {
ntfs_error(vol->sb, "Failed to layout mft record 0x%llx.",
(long long)mft_no);
SetPageUptodate(page);
unlock_page(page);
ntfs_unmap_page(page);
return err;
}
flush_dcache_page(page);
SetPageUptodate(page);
unlock_page(page);
/*
* Make sure the mft record is written out to disk. We could use
* ilookup5() to check if an inode is in icache and so on but this is
* unnecessary as ntfs_writepage() will write the dirty record anyway.
*/
mark_ntfs_record_dirty(page, ofs);
ntfs_unmap_page(page);
ntfs_debug("Done.");
return 0;
}
/**
* ntfs_mft_record_alloc - allocate an mft record on an ntfs volume
* @vol: [IN] volume on which to allocate the mft record
* @mode: [IN] mode if want a file or directory, i.e. base inode or 0
* @base_ni: [IN] open base inode if allocating an extent mft record or NULL
* @mrec: [OUT] on successful return this is the mapped mft record
*
* Allocate an mft record in $MFT/$DATA of an open ntfs volume @vol.
*
* If @base_ni is NULL make the mft record a base mft record, i.e. a file or
* direvctory inode, and allocate it at the default allocator position. In
* this case @mode is the file mode as given to us by the caller. We in
* particular use @mode to distinguish whether a file or a directory is being
* created (S_IFDIR(mode) and S_IFREG(mode), respectively).
*
* If @base_ni is not NULL make the allocated mft record an extent record,
* allocate it starting at the mft record after the base mft record and attach
* the allocated and opened ntfs inode to the base inode @base_ni. In this
* case @mode must be 0 as it is meaningless for extent inodes.
*
* You need to check the return value with IS_ERR(). If false, the function
* was successful and the return value is the now opened ntfs inode of the
* allocated mft record. *@mrec is then set to the allocated, mapped, pinned,
* and locked mft record. If IS_ERR() is true, the function failed and the
* error code is obtained from PTR_ERR(return value). *@mrec is undefined in
* this case.
*
* Allocation strategy:
*
* To find a free mft record, we scan the mft bitmap for a zero bit. To
* optimize this we start scanning at the place specified by @base_ni or if
* @base_ni is NULL we start where we last stopped and we perform wrap around
* when we reach the end. Note, we do not try to allocate mft records below
* number 24 because numbers 0 to 15 are the defined system files anyway and 16
* to 24 are special in that they are used for storing extension mft records
* for the $DATA attribute of $MFT. This is required to avoid the possibility
* of creating a runlist with a circular dependency which once written to disk
* can never be read in again. Windows will only use records 16 to 24 for
* normal files if the volume is completely out of space. We never use them
* which means that when the volume is really out of space we cannot create any
* more files while Windows can still create up to 8 small files. We can start
* doing this at some later time, it does not matter much for now.
*
* When scanning the mft bitmap, we only search up to the last allocated mft
* record. If there are no free records left in the range 24 to number of
* allocated mft records, then we extend the $MFT/$DATA attribute in order to
* create free mft records. We extend the allocated size of $MFT/$DATA by 16
* records at a time or one cluster, if cluster size is above 16kiB. If there
* is not sufficient space to do this, we try to extend by a single mft record
* or one cluster, if cluster size is above the mft record size.
*
* No matter how many mft records we allocate, we initialize only the first
* allocated mft record, incrementing mft data size and initialized size
* accordingly, open an ntfs_inode for it and return it to the caller, unless
* there are less than 24 mft records, in which case we allocate and initialize
* mft records until we reach record 24 which we consider as the first free mft
* record for use by normal files.
*
* If during any stage we overflow the initialized data in the mft bitmap, we
* extend the initialized size (and data size) by 8 bytes, allocating another
* cluster if required. The bitmap data size has to be at least equal to the
* number of mft records in the mft, but it can be bigger, in which case the
* superflous bits are padded with zeroes.
*
* Thus, when we return successfully (IS_ERR() is false), we will have:
* - initialized / extended the mft bitmap if necessary,
* - initialized / extended the mft data if necessary,
* - set the bit corresponding to the mft record being allocated in the
* mft bitmap,
* - opened an ntfs_inode for the allocated mft record, and we will have
* - returned the ntfs_inode as well as the allocated mapped, pinned, and
* locked mft record.
*
* On error, the volume will be left in a consistent state and no record will
* be allocated. If rolling back a partial operation fails, we may leave some
* inconsistent metadata in which case we set NVolErrors() so the volume is
* left dirty when unmounted.
*
* Note, this function cannot make use of most of the normal functions, like
* for example for attribute resizing, etc, because when the run list overflows
* the base mft record and an attribute list is used, it is very important that
* the extension mft records used to store the $DATA attribute of $MFT can be
* reached without having to read the information contained inside them, as
* this would make it impossible to find them in the first place after the
* volume is unmounted. $MFT/$BITMAP probably does not need to follow this
* rule because the bitmap is not essential for finding the mft records, but on
* the other hand, handling the bitmap in this special way would make life
* easier because otherwise there might be circular invocations of functions
* when reading the bitmap.
*/
ntfs_inode *ntfs_mft_record_alloc(ntfs_volume *vol, const int mode,
ntfs_inode *base_ni, MFT_RECORD **mrec)
{
s64 ll, bit, old_data_initialized, old_data_size;
unsigned long flags;
struct inode *vi;
struct page *page;
ntfs_inode *mft_ni, *mftbmp_ni, *ni;
ntfs_attr_search_ctx *ctx;
MFT_RECORD *m;
ATTR_RECORD *a;
pgoff_t index;
unsigned int ofs;
int err;
le16 seq_no, usn;
bool record_formatted = false;
if (base_ni) {
ntfs_debug("Entering (allocating an extent mft record for "
"base mft record 0x%llx).",
(long long)base_ni->mft_no);
/* @mode and @base_ni are mutually exclusive. */
BUG_ON(mode);
} else
ntfs_debug("Entering (allocating a base mft record).");
if (mode) {
/* @mode and @base_ni are mutually exclusive. */
BUG_ON(base_ni);
/* We only support creation of normal files and directories. */
if (!S_ISREG(mode) && !S_ISDIR(mode))
return ERR_PTR(-EOPNOTSUPP);
}
BUG_ON(!mrec);
mft_ni = NTFS_I(vol->mft_ino);
mftbmp_ni = NTFS_I(vol->mftbmp_ino);
down_write(&vol->mftbmp_lock);
bit = ntfs_mft_bitmap_find_and_alloc_free_rec_nolock(vol, base_ni);
if (bit >= 0) {
ntfs_debug("Found and allocated free record (#1), bit 0x%llx.",
(long long)bit);
goto have_alloc_rec;
}
if (bit != -ENOSPC) {
up_write(&vol->mftbmp_lock);
return ERR_PTR(bit);
}
/*
* No free mft records left. If the mft bitmap already covers more
* than the currently used mft records, the next records are all free,
* so we can simply allocate the first unused mft record.
* Note: We also have to make sure that the mft bitmap at least covers
* the first 24 mft records as they are special and whilst they may not
* be in use, we do not allocate from them.
*/
read_lock_irqsave(&mft_ni->size_lock, flags);
ll = mft_ni->initialized_size >> vol->mft_record_size_bits;
read_unlock_irqrestore(&mft_ni->size_lock, flags);
read_lock_irqsave(&mftbmp_ni->size_lock, flags);
old_data_initialized = mftbmp_ni->initialized_size;
read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
if (old_data_initialized << 3 > ll && old_data_initialized > 3) {
bit = ll;
if (bit < 24)
bit = 24;
if (unlikely(bit >= (1ll << 32)))
goto max_err_out;
ntfs_debug("Found free record (#2), bit 0x%llx.",
(long long)bit);
goto found_free_rec;
}
/*
* The mft bitmap needs to be expanded until it covers the first unused
* mft record that we can allocate.
* Note: The smallest mft record we allocate is mft record 24.
*/
bit = old_data_initialized << 3;
if (unlikely(bit >= (1ll << 32)))
goto max_err_out;
read_lock_irqsave(&mftbmp_ni->size_lock, flags);
old_data_size = mftbmp_ni->allocated_size;
ntfs_debug("Status of mftbmp before extension: allocated_size 0x%llx, "
"data_size 0x%llx, initialized_size 0x%llx.",
(long long)old_data_size,
(long long)i_size_read(vol->mftbmp_ino),
(long long)old_data_initialized);
read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
if (old_data_initialized + 8 > old_data_size) {
/* Need to extend bitmap by one more cluster. */
ntfs_debug("mftbmp: initialized_size + 8 > allocated_size.");
err = ntfs_mft_bitmap_extend_allocation_nolock(vol);
if (unlikely(err)) {
up_write(&vol->mftbmp_lock);
goto err_out;
}
#ifdef DEBUG
read_lock_irqsave(&mftbmp_ni->size_lock, flags);
ntfs_debug("Status of mftbmp after allocation extension: "
"allocated_size 0x%llx, data_size 0x%llx, "
"initialized_size 0x%llx.",
(long long)mftbmp_ni->allocated_size,
(long long)i_size_read(vol->mftbmp_ino),
(long long)mftbmp_ni->initialized_size);
read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
#endif /* DEBUG */
}
/*
* We now have sufficient allocated space, extend the initialized_size
* as well as the data_size if necessary and fill the new space with
* zeroes.
*/
err = ntfs_mft_bitmap_extend_initialized_nolock(vol);
if (unlikely(err)) {
up_write(&vol->mftbmp_lock);
goto err_out;
}
#ifdef DEBUG
read_lock_irqsave(&mftbmp_ni->size_lock, flags);
ntfs_debug("Status of mftbmp after initialized extension: "
"allocated_size 0x%llx, data_size 0x%llx, "
"initialized_size 0x%llx.",
(long long)mftbmp_ni->allocated_size,
(long long)i_size_read(vol->mftbmp_ino),
(long long)mftbmp_ni->initialized_size);
read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
#endif /* DEBUG */
ntfs_debug("Found free record (#3), bit 0x%llx.", (long long)bit);
found_free_rec:
/* @bit is the found free mft record, allocate it in the mft bitmap. */
ntfs_debug("At found_free_rec.");
err = ntfs_bitmap_set_bit(vol->mftbmp_ino, bit);
if (unlikely(err)) {
ntfs_error(vol->sb, "Failed to allocate bit in mft bitmap.");
up_write(&vol->mftbmp_lock);
goto err_out;
}
ntfs_debug("Set bit 0x%llx in mft bitmap.", (long long)bit);
have_alloc_rec:
/*
* The mft bitmap is now uptodate. Deal with mft data attribute now.
* Note, we keep hold of the mft bitmap lock for writing until all
* modifications to the mft data attribute are complete, too, as they
* will impact decisions for mft bitmap and mft record allocation done
* by a parallel allocation and if the lock is not maintained a
* parallel allocation could allocate the same mft record as this one.
*/
ll = (bit + 1) << vol->mft_record_size_bits;
read_lock_irqsave(&mft_ni->size_lock, flags);
old_data_initialized = mft_ni->initialized_size;
read_unlock_irqrestore(&mft_ni->size_lock, flags);
if (ll <= old_data_initialized) {
ntfs_debug("Allocated mft record already initialized.");
goto mft_rec_already_initialized;
}
ntfs_debug("Initializing allocated mft record.");
/*
* The mft record is outside the initialized data. Extend the mft data
* attribute until it covers the allocated record. The loop is only
* actually traversed more than once when a freshly formatted volume is
* first written to so it optimizes away nicely in the common case.
*/
read_lock_irqsave(&mft_ni->size_lock, flags);
ntfs_debug("Status of mft data before extension: "
"allocated_size 0x%llx, data_size 0x%llx, "
"initialized_size 0x%llx.",
(long long)mft_ni->allocated_size,
(long long)i_size_read(vol->mft_ino),
(long long)mft_ni->initialized_size);
while (ll > mft_ni->allocated_size) {
read_unlock_irqrestore(&mft_ni->size_lock, flags);
err = ntfs_mft_data_extend_allocation_nolock(vol);
if (unlikely(err)) {
ntfs_error(vol->sb, "Failed to extend mft data "
"allocation.");
goto undo_mftbmp_alloc_nolock;
}
read_lock_irqsave(&mft_ni->size_lock, flags);
ntfs_debug("Status of mft data after allocation extension: "
"allocated_size 0x%llx, data_size 0x%llx, "
"initialized_size 0x%llx.",
(long long)mft_ni->allocated_size,
(long long)i_size_read(vol->mft_ino),
(long long)mft_ni->initialized_size);
}
read_unlock_irqrestore(&mft_ni->size_lock, flags);
/*
* Extend mft data initialized size (and data size of course) to reach
* the allocated mft record, formatting the mft records allong the way.
* Note: We only modify the ntfs_inode structure as that is all that is
* needed by ntfs_mft_record_format(). We will update the attribute
* record itself in one fell swoop later on.
*/
write_lock_irqsave(&mft_ni->size_lock, flags);
old_data_initialized = mft_ni->initialized_size;
old_data_size = vol->mft_ino->i_size;
while (ll > mft_ni->initialized_size) {
s64 new_initialized_size, mft_no;
new_initialized_size = mft_ni->initialized_size +
vol->mft_record_size;
mft_no = mft_ni->initialized_size >> vol->mft_record_size_bits;
if (new_initialized_size > i_size_read(vol->mft_ino))
i_size_write(vol->mft_ino, new_initialized_size);
write_unlock_irqrestore(&mft_ni->size_lock, flags);
ntfs_debug("Initializing mft record 0x%llx.",
(long long)mft_no);
err = ntfs_mft_record_format(vol, mft_no);
if (unlikely(err)) {
ntfs_error(vol->sb, "Failed to format mft record.");
goto undo_data_init;
}
write_lock_irqsave(&mft_ni->size_lock, flags);
mft_ni->initialized_size = new_initialized_size;
}
write_unlock_irqrestore(&mft_ni->size_lock, flags);
record_formatted = true;
/* Update the mft data attribute record to reflect the new sizes. */
m = map_mft_record(mft_ni);
if (IS_ERR(m)) {
ntfs_error(vol->sb, "Failed to map mft record.");
err = PTR_ERR(m);
goto undo_data_init;
}
ctx = ntfs_attr_get_search_ctx(mft_ni, m);
if (unlikely(!ctx)) {
ntfs_error(vol->sb, "Failed to get search context.");
err = -ENOMEM;
unmap_mft_record(mft_ni);
goto undo_data_init;
}
err = ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
CASE_SENSITIVE, 0, NULL, 0, ctx);
if (unlikely(err)) {
ntfs_error(vol->sb, "Failed to find first attribute extent of "
"mft data attribute.");
ntfs_attr_put_search_ctx(ctx);
unmap_mft_record(mft_ni);
goto undo_data_init;
}
a = ctx->attr;
read_lock_irqsave(&mft_ni->size_lock, flags);
a->data.non_resident.initialized_size =
cpu_to_sle64(mft_ni->initialized_size);
a->data.non_resident.data_size =
cpu_to_sle64(i_size_read(vol->mft_ino));
read_unlock_irqrestore(&mft_ni->size_lock, flags);
/* Ensure the changes make it to disk. */
flush_dcache_mft_record_page(ctx->ntfs_ino);
mark_mft_record_dirty(ctx->ntfs_ino);
ntfs_attr_put_search_ctx(ctx);
unmap_mft_record(mft_ni);
read_lock_irqsave(&mft_ni->size_lock, flags);
ntfs_debug("Status of mft data after mft record initialization: "
"allocated_size 0x%llx, data_size 0x%llx, "
"initialized_size 0x%llx.",
(long long)mft_ni->allocated_size,
(long long)i_size_read(vol->mft_ino),
(long long)mft_ni->initialized_size);
BUG_ON(i_size_read(vol->mft_ino) > mft_ni->allocated_size);
BUG_ON(mft_ni->initialized_size > i_size_read(vol->mft_ino));
read_unlock_irqrestore(&mft_ni->size_lock, flags);
mft_rec_already_initialized:
/*
* We can finally drop the mft bitmap lock as the mft data attribute
* has been fully updated. The only disparity left is that the
* allocated mft record still needs to be marked as in use to match the
* set bit in the mft bitmap but this is actually not a problem since
* this mft record is not referenced from anywhere yet and the fact
* that it is allocated in the mft bitmap means that no-one will try to
* allocate it either.
*/
up_write(&vol->mftbmp_lock);
/*
* We now have allocated and initialized the mft record. Calculate the
* index of and the offset within the page cache page the record is in.
*/
index = bit << vol->mft_record_size_bits >> PAGE_CACHE_SHIFT;
ofs = (bit << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
/* Read, map, and pin the page containing the mft record. */
page = ntfs_map_page(vol->mft_ino->i_mapping, index);
if (IS_ERR(page)) {
ntfs_error(vol->sb, "Failed to map page containing allocated "
"mft record 0x%llx.", (long long)bit);
err = PTR_ERR(page);
goto undo_mftbmp_alloc;
}
lock_page(page);
BUG_ON(!PageUptodate(page));
ClearPageUptodate(page);
m = (MFT_RECORD*)((u8*)page_address(page) + ofs);
/* If we just formatted the mft record no need to do it again. */
if (!record_formatted) {
/* Sanity check that the mft record is really not in use. */
if (ntfs_is_file_record(m->magic) &&
(m->flags & MFT_RECORD_IN_USE)) {
ntfs_error(vol->sb, "Mft record 0x%llx was marked "
"free in mft bitmap but is marked "
"used itself. Corrupt filesystem. "
"Unmount and run chkdsk.",
(long long)bit);
err = -EIO;
SetPageUptodate(page);
unlock_page(page);
ntfs_unmap_page(page);
NVolSetErrors(vol);
goto undo_mftbmp_alloc;
}
/*
* We need to (re-)format the mft record, preserving the
* sequence number if it is not zero as well as the update
* sequence number if it is not zero or -1 (0xffff). This
* means we do not need to care whether or not something went
* wrong with the previous mft record.
*/
seq_no = m->sequence_number;
usn = *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs));
err = ntfs_mft_record_layout(vol, bit, m);
if (unlikely(err)) {
ntfs_error(vol->sb, "Failed to layout allocated mft "
"record 0x%llx.", (long long)bit);
SetPageUptodate(page);
unlock_page(page);
ntfs_unmap_page(page);
goto undo_mftbmp_alloc;
}
if (seq_no)
m->sequence_number = seq_no;
if (usn && le16_to_cpu(usn) != 0xffff)
*(le16*)((u8*)m + le16_to_cpu(m->usa_ofs)) = usn;
}
/* Set the mft record itself in use. */
m->flags |= MFT_RECORD_IN_USE;
if (S_ISDIR(mode))
m->flags |= MFT_RECORD_IS_DIRECTORY;
flush_dcache_page(page);
SetPageUptodate(page);
if (base_ni) {
MFT_RECORD *m_tmp;
/*
* Setup the base mft record in the extent mft record. This
* completes initialization of the allocated extent mft record
* and we can simply use it with map_extent_mft_record().
*/
m->base_mft_record = MK_LE_MREF(base_ni->mft_no,
base_ni->seq_no);
/*
* Allocate an extent inode structure for the new mft record,
* attach it to the base inode @base_ni and map, pin, and lock
* its, i.e. the allocated, mft record.
*/
m_tmp = map_extent_mft_record(base_ni, bit, &ni);
if (IS_ERR(m_tmp)) {
ntfs_error(vol->sb, "Failed to map allocated extent "
"mft record 0x%llx.", (long long)bit);
err = PTR_ERR(m_tmp);
/* Set the mft record itself not in use. */
m->flags &= cpu_to_le16(
~le16_to_cpu(MFT_RECORD_IN_USE));
flush_dcache_page(page);
/* Make sure the mft record is written out to disk. */
mark_ntfs_record_dirty(page, ofs);
unlock_page(page);
ntfs_unmap_page(page);
goto undo_mftbmp_alloc;
}
BUG_ON(m != m_tmp);
/*
* Make sure the allocated mft record is written out to disk.
* No need to set the inode dirty because the caller is going
* to do that anyway after finishing with the new extent mft
* record (e.g. at a minimum a new attribute will be added to
* the mft record.
*/
mark_ntfs_record_dirty(page, ofs);
unlock_page(page);
/*
* Need to unmap the page since map_extent_mft_record() mapped
* it as well so we have it mapped twice at the moment.
*/
ntfs_unmap_page(page);
} else {
/*
* Allocate a new VFS inode and set it up. NOTE: @vi->i_nlink
* is set to 1 but the mft record->link_count is 0. The caller
* needs to bear this in mind.
*/
vi = new_inode(vol->sb);
if (unlikely(!vi)) {
err = -ENOMEM;
/* Set the mft record itself not in use. */
m->flags &= cpu_to_le16(
~le16_to_cpu(MFT_RECORD_IN_USE));
flush_dcache_page(page);
/* Make sure the mft record is written out to disk. */
mark_ntfs_record_dirty(page, ofs);
unlock_page(page);
ntfs_unmap_page(page);
goto undo_mftbmp_alloc;
}
vi->i_ino = bit;
/*
* This is for checking whether an inode has changed w.r.t. a
* file so that the file can be updated if necessary (compare
* with f_version).
*/
vi->i_version = 1;
/* The owner and group come from the ntfs volume. */
vi->i_uid = vol->uid;
vi->i_gid = vol->gid;
/* Initialize the ntfs specific part of @vi. */
ntfs_init_big_inode(vi);
ni = NTFS_I(vi);
/*
* Set the appropriate mode, attribute type, and name. For
* directories, also setup the index values to the defaults.
*/
if (S_ISDIR(mode)) {
vi->i_mode = S_IFDIR | S_IRWXUGO;
vi->i_mode &= ~vol->dmask;
NInoSetMstProtected(ni);
ni->type = AT_INDEX_ALLOCATION;
ni->name = I30;
ni->name_len = 4;
ni->itype.index.block_size = 4096;
ni->itype.index.block_size_bits = ntfs_ffs(4096) - 1;
ni->itype.index.collation_rule = COLLATION_FILE_NAME;
if (vol->cluster_size <= ni->itype.index.block_size) {
ni->itype.index.vcn_size = vol->cluster_size;
ni->itype.index.vcn_size_bits =
vol->cluster_size_bits;
} else {
ni->itype.index.vcn_size = vol->sector_size;
ni->itype.index.vcn_size_bits =
vol->sector_size_bits;
}
} else {
vi->i_mode = S_IFREG | S_IRWXUGO;
vi->i_mode &= ~vol->fmask;
ni->type = AT_DATA;
ni->name = NULL;
ni->name_len = 0;
}
if (IS_RDONLY(vi))
vi->i_mode &= ~S_IWUGO;
/* Set the inode times to the current time. */
vi->i_atime = vi->i_mtime = vi->i_ctime =
current_fs_time(vi->i_sb);
/*
* Set the file size to 0, the ntfs inode sizes are set to 0 by
* the call to ntfs_init_big_inode() below.
*/
vi->i_size = 0;
vi->i_blocks = 0;
/* Set the sequence number. */
vi->i_generation = ni->seq_no = le16_to_cpu(m->sequence_number);
/*
* Manually map, pin, and lock the mft record as we already
* have its page mapped and it is very easy to do.
*/
atomic_inc(&ni->count);
mutex_lock(&ni->mrec_lock);
ni->page = page;
ni->page_ofs = ofs;
/*
* Make sure the allocated mft record is written out to disk.
* NOTE: We do not set the ntfs inode dirty because this would
* fail in ntfs_write_inode() because the inode does not have a
* standard information attribute yet. Also, there is no need
* to set the inode dirty because the caller is going to do
* that anyway after finishing with the new mft record (e.g. at
* a minimum some new attributes will be added to the mft
* record.
*/
mark_ntfs_record_dirty(page, ofs);
unlock_page(page);
/* Add the inode to the inode hash for the superblock. */
insert_inode_hash(vi);
/* Update the default mft allocation position. */
vol->mft_data_pos = bit + 1;
}
/*
* Return the opened, allocated inode of the allocated mft record as
* well as the mapped, pinned, and locked mft record.
*/
ntfs_debug("Returning opened, allocated %sinode 0x%llx.",
base_ni ? "extent " : "", (long long)bit);
*mrec = m;
return ni;
undo_data_init:
write_lock_irqsave(&mft_ni->size_lock, flags);
mft_ni->initialized_size = old_data_initialized;
i_size_write(vol->mft_ino, old_data_size);
write_unlock_irqrestore(&mft_ni->size_lock, flags);
goto undo_mftbmp_alloc_nolock;
undo_mftbmp_alloc:
down_write(&vol->mftbmp_lock);
undo_mftbmp_alloc_nolock:
if (ntfs_bitmap_clear_bit(vol->mftbmp_ino, bit)) {
ntfs_error(vol->sb, "Failed to clear bit in mft bitmap.%s", es);
NVolSetErrors(vol);
}
up_write(&vol->mftbmp_lock);
err_out:
return ERR_PTR(err);
max_err_out:
ntfs_warning(vol->sb, "Cannot allocate mft record because the maximum "
"number of inodes (2^32) has already been reached.");
up_write(&vol->mftbmp_lock);
return ERR_PTR(-ENOSPC);
}
/**
* ntfs_extent_mft_record_free - free an extent mft record on an ntfs volume
* @ni: ntfs inode of the mapped extent mft record to free
* @m: mapped extent mft record of the ntfs inode @ni
*
* Free the mapped extent mft record @m of the extent ntfs inode @ni.
*
* Note that this function unmaps the mft record and closes and destroys @ni
* internally and hence you cannot use either @ni nor @m any more after this
* function returns success.
*
* On success return 0 and on error return -errno. @ni and @m are still valid
* in this case and have not been freed.
*
* For some errors an error message is displayed and the success code 0 is
* returned and the volume is then left dirty on umount. This makes sense in
* case we could not rollback the changes that were already done since the
* caller no longer wants to reference this mft record so it does not matter to
* the caller if something is wrong with it as long as it is properly detached
* from the base inode.
*/
int ntfs_extent_mft_record_free(ntfs_inode *ni, MFT_RECORD *m)
{
unsigned long mft_no = ni->mft_no;
ntfs_volume *vol = ni->vol;
ntfs_inode *base_ni;
ntfs_inode **extent_nis;
int i, err;
le16 old_seq_no;
u16 seq_no;
BUG_ON(NInoAttr(ni));
BUG_ON(ni->nr_extents != -1);
mutex_lock(&ni->extent_lock);
base_ni = ni->ext.base_ntfs_ino;
mutex_unlock(&ni->extent_lock);
BUG_ON(base_ni->nr_extents <= 0);
ntfs_debug("Entering for extent inode 0x%lx, base inode 0x%lx.\n",
mft_no, base_ni->mft_no);
mutex_lock(&base_ni->extent_lock);
/* Make sure we are holding the only reference to the extent inode. */
if (atomic_read(&ni->count) > 2) {
ntfs_error(vol->sb, "Tried to free busy extent inode 0x%lx, "
"not freeing.", base_ni->mft_no);
mutex_unlock(&base_ni->extent_lock);
return -EBUSY;
}
/* Dissociate the ntfs inode from the base inode. */
extent_nis = base_ni->ext.extent_ntfs_inos;
err = -ENOENT;
for (i = 0; i < base_ni->nr_extents; i++) {
if (ni != extent_nis[i])
continue;
extent_nis += i;
base_ni->nr_extents--;
memmove(extent_nis, extent_nis + 1, (base_ni->nr_extents - i) *
sizeof(ntfs_inode*));
err = 0;
break;
}
mutex_unlock(&base_ni->extent_lock);
if (unlikely(err)) {
ntfs_error(vol->sb, "Extent inode 0x%lx is not attached to "
"its base inode 0x%lx.", mft_no,
base_ni->mft_no);
BUG();
}
/*
* The extent inode is no longer attached to the base inode so no one
* can get a reference to it any more.
*/
/* Mark the mft record as not in use. */
m->flags &= ~MFT_RECORD_IN_USE;
/* Increment the sequence number, skipping zero, if it is not zero. */
old_seq_no = m->sequence_number;
seq_no = le16_to_cpu(old_seq_no);
if (seq_no == 0xffff)
seq_no = 1;
else if (seq_no)
seq_no++;
m->sequence_number = cpu_to_le16(seq_no);
/*
* Set the ntfs inode dirty and write it out. We do not need to worry
* about the base inode here since whatever caused the extent mft
* record to be freed is guaranteed to do it already.
*/
NInoSetDirty(ni);
err = write_mft_record(ni, m, 0);
if (unlikely(err)) {
ntfs_error(vol->sb, "Failed to write mft record 0x%lx, not "
"freeing.", mft_no);
goto rollback;
}
rollback_error:
/* Unmap and throw away the now freed extent inode. */
unmap_extent_mft_record(ni);
ntfs_clear_extent_inode(ni);
/* Clear the bit in the $MFT/$BITMAP corresponding to this record. */
down_write(&vol->mftbmp_lock);
err = ntfs_bitmap_clear_bit(vol->mftbmp_ino, mft_no);
up_write(&vol->mftbmp_lock);
if (unlikely(err)) {
/*
* The extent inode is gone but we failed to deallocate it in
* the mft bitmap. Just emit a warning and leave the volume
* dirty on umount.
*/
ntfs_error(vol->sb, "Failed to clear bit in mft bitmap.%s", es);
NVolSetErrors(vol);
}
return 0;
rollback:
/* Rollback what we did... */
mutex_lock(&base_ni->extent_lock);
extent_nis = base_ni->ext.extent_ntfs_inos;
if (!(base_ni->nr_extents & 3)) {
int new_size = (base_ni->nr_extents + 4) * sizeof(ntfs_inode*);
extent_nis = kmalloc(new_size, GFP_NOFS);
if (unlikely(!extent_nis)) {
ntfs_error(vol->sb, "Failed to allocate internal "
"buffer during rollback.%s", es);
mutex_unlock(&base_ni->extent_lock);
NVolSetErrors(vol);
goto rollback_error;
}
if (base_ni->nr_extents) {
BUG_ON(!base_ni->ext.extent_ntfs_inos);
memcpy(extent_nis, base_ni->ext.extent_ntfs_inos,
new_size - 4 * sizeof(ntfs_inode*));
kfree(base_ni->ext.extent_ntfs_inos);
}
base_ni->ext.extent_ntfs_inos = extent_nis;
}
m->flags |= MFT_RECORD_IN_USE;
m->sequence_number = old_seq_no;
extent_nis[base_ni->nr_extents++] = ni;
mutex_unlock(&base_ni->extent_lock);
mark_mft_record_dirty(ni);
return err;
}
#endif /* NTFS_RW */
| gpl-2.0 |
ryoon/gcc-4.2.4-SCO-OpenServer5 | gcc/testsuite/gcc.dg/vmx/3c-01a.c | 97 | 49575 | /* { dg-do compile } */
#include <altivec.h>
typedef const volatile unsigned int _1;
typedef const unsigned int _2;
typedef volatile unsigned int _3;
typedef unsigned int _4;
typedef const volatile vector bool short _5;
typedef const vector bool short _6;
typedef volatile vector bool short _7;
typedef vector bool short _8;
typedef const volatile signed short _9;
typedef const signed short _10;
typedef volatile signed short _11;
typedef signed short _12;
typedef const volatile unsigned _13;
typedef const unsigned _14;
typedef volatile unsigned _15;
typedef unsigned _16;
typedef const volatile signed short int _17;
typedef const signed short int _18;
typedef volatile signed short int _19;
typedef signed short int _20;
typedef const volatile unsigned short int _21;
typedef const unsigned short int _22;
typedef volatile unsigned short int _23;
typedef unsigned short int _24;
typedef const volatile vector pixel _25;
typedef const vector pixel _26;
typedef volatile vector pixel _27;
typedef vector pixel _28;
typedef const volatile vector bool int _29;
typedef const vector bool int _30;
typedef volatile vector bool int _31;
typedef vector bool int _32;
typedef const volatile vector signed char _33;
typedef const vector signed char _34;
typedef volatile vector signed char _35;
typedef vector signed char _36;
typedef const volatile unsigned _37;
typedef const unsigned _38;
typedef volatile unsigned _39;
typedef unsigned _40;
typedef const volatile signed int _41;
typedef const signed int _42;
typedef volatile signed int _43;
typedef signed int _44;
typedef const volatile vector float _45;
typedef const vector float _46;
typedef volatile vector float _47;
typedef vector float _48;
typedef const volatile vector signed short _49;
typedef const vector signed short _50;
typedef volatile vector signed short _51;
typedef vector signed short _52;
typedef const volatile unsigned char _53;
typedef const unsigned char _54;
typedef volatile unsigned char _55;
typedef unsigned char _56;
typedef const volatile signed int _57;
typedef const signed int _58;
typedef volatile signed int _59;
typedef signed int _60;
typedef const volatile unsigned int _61;
typedef const unsigned int _62;
typedef volatile unsigned int _63;
typedef unsigned int _64;
typedef const volatile unsigned short _65;
typedef const unsigned short _66;
typedef volatile unsigned short _67;
typedef unsigned short _68;
typedef const volatile short _69;
typedef const short _70;
typedef volatile short _71;
typedef short _72;
typedef const volatile int _73;
typedef const int _74;
typedef volatile int _75;
typedef int _76;
typedef const volatile vector unsigned short _77;
typedef const vector unsigned short _78;
typedef volatile vector unsigned short _79;
typedef vector unsigned short _80;
typedef const volatile vector bool char _81;
typedef const vector bool char _82;
typedef volatile vector bool char _83;
typedef vector bool char _84;
typedef const volatile signed _85;
typedef const signed _86;
typedef volatile signed _87;
typedef signed _88;
typedef const volatile vector signed int _89;
typedef const vector signed int _90;
typedef volatile vector signed int _91;
typedef vector signed int _92;
typedef const volatile vector unsigned int _93;
typedef const vector unsigned int _94;
typedef volatile vector unsigned int _95;
typedef vector unsigned int _96;
typedef const volatile signed _97;
typedef const signed _98;
typedef volatile signed _99;
typedef signed _100;
typedef const volatile short int _101;
typedef const short int _102;
typedef volatile short int _103;
typedef short int _104;
typedef const volatile int _105;
typedef const int _106;
typedef volatile int _107;
typedef int _108;
typedef const volatile int _109;
typedef const int _110;
typedef volatile int _111;
typedef int _112;
typedef const volatile vector unsigned char _113;
typedef const vector unsigned char _114;
typedef volatile vector unsigned char _115;
typedef vector unsigned char _116;
typedef const volatile signed char _117;
typedef const signed char _118;
typedef volatile signed char _119;
typedef signed char _120;
typedef const volatile float _121;
typedef const float _122;
typedef volatile float _123;
typedef float _124;
vector unsigned char u8;
vector signed char s8;
vector bool char b8;
vector unsigned short u16;
vector signed short s16;
vector bool short b16;
vector unsigned int u32;
vector signed int s32;
vector bool int b32;
vector float f32;
vector pixel p16;
void f(void *p)
{
u8 = vec_lvsl(1,(const volatile unsigned int *)p);
u8 = vec_lvsl(1,(_1 *)p);
u8 = vec_lvsr(1,(const volatile unsigned int *)p);
u8 = vec_lvsr(1,(_1 *)p);
u8 = vec_lvsl(1,(const unsigned int *)p);
u8 = vec_lvsl(1,(_2 *)p);
u8 = vec_lvsr(1,(const unsigned int *)p);
u8 = vec_lvsr(1,(_2 *)p);
u32 = vec_ld(1,(const unsigned int *)p);
u32 = vec_ld(1,(_2 *)p);
u32 = vec_lde(1,(const unsigned int *)p);
u32 = vec_lde(1,(_2 *)p);
u32 = vec_ldl(1,(const unsigned int *)p);
u32 = vec_ldl(1,(_2 *)p);
vec_dst((const unsigned int *)p,1,1);
vec_dstst((const unsigned int *)p,1,1);
vec_dststt((const unsigned int *)p,1,1);
vec_dstt((const unsigned int *)p,1,1);
vec_dst((_2 *)p,1,1);
vec_dstst((_2 *)p,1,1);
vec_dststt((_2 *)p,1,1);
vec_dstt((_2 *)p,1,1);
u8 = vec_lvsl(1,( volatile unsigned int *)p);
u8 = vec_lvsl(1,(_3 *)p);
u8 = vec_lvsr(1,( volatile unsigned int *)p);
u8 = vec_lvsr(1,(_3 *)p);
u8 = vec_lvsl(1,( unsigned int *)p);
u8 = vec_lvsl(1,(_4 *)p);
u8 = vec_lvsr(1,( unsigned int *)p);
u8 = vec_lvsr(1,(_4 *)p);
u32 = vec_ld(1,( unsigned int *)p);
u32 = vec_ld(1,(_4 *)p);
u32 = vec_lde(1,( unsigned int *)p);
u32 = vec_lde(1,(_4 *)p);
u32 = vec_ldl(1,( unsigned int *)p);
u32 = vec_ldl(1,(_4 *)p);
vec_dst(( unsigned int *)p,1,1);
vec_dstst(( unsigned int *)p,1,1);
vec_dststt(( unsigned int *)p,1,1);
vec_dstt(( unsigned int *)p,1,1);
vec_dst((_4 *)p,1,1);
vec_dstst((_4 *)p,1,1);
vec_dststt((_4 *)p,1,1);
vec_dstt((_4 *)p,1,1);
vec_st(u32,1,( unsigned int *)p);
vec_st(u32,1,(_4 *)p);
vec_ste(u32,1,( unsigned int *)p);
vec_ste(u32,1,(_4 *)p);
vec_stl(u32,1,( unsigned int *)p);
vec_stl(u32,1,(_4 *)p);
b16 = vec_ld(1,(const vector bool short *)p);
b16 = vec_ld(1,(_6 *)p);
b16 = vec_ldl(1,(const vector bool short *)p);
b16 = vec_ldl(1,(_6 *)p);
vec_dst((const vector bool short *)p,1,1);
vec_dstst((const vector bool short *)p,1,1);
vec_dststt((const vector bool short *)p,1,1);
vec_dstt((const vector bool short *)p,1,1);
vec_dst((_6 *)p,1,1);
vec_dstst((_6 *)p,1,1);
vec_dststt((_6 *)p,1,1);
vec_dstt((_6 *)p,1,1);
b16 = vec_ld(1,( vector bool short *)p);
b16 = vec_ld(1,(_8 *)p);
b16 = vec_ldl(1,( vector bool short *)p);
b16 = vec_ldl(1,(_8 *)p);
vec_dst(( vector bool short *)p,1,1);
vec_dstst(( vector bool short *)p,1,1);
vec_dststt(( vector bool short *)p,1,1);
vec_dstt(( vector bool short *)p,1,1);
vec_dst((_8 *)p,1,1);
vec_dstst((_8 *)p,1,1);
vec_dststt((_8 *)p,1,1);
vec_dstt((_8 *)p,1,1);
vec_st(b16,1,( vector bool short *)p);
vec_st(b16,1,(_8 *)p);
vec_stl(b16,1,( vector bool short *)p);
vec_stl(b16,1,(_8 *)p);
u8 = vec_lvsl(1,(const volatile signed short *)p);
u8 = vec_lvsl(1,(_9 *)p);
u8 = vec_lvsr(1,(const volatile signed short *)p);
u8 = vec_lvsr(1,(_9 *)p);
u8 = vec_lvsl(1,(const signed short *)p);
u8 = vec_lvsl(1,(_10 *)p);
u8 = vec_lvsr(1,(const signed short *)p);
u8 = vec_lvsr(1,(_10 *)p);
s16 = vec_ld(1,(const signed short *)p);
s16 = vec_ld(1,(_10 *)p);
s16 = vec_lde(1,(const signed short *)p);
s16 = vec_lde(1,(_10 *)p);
s16 = vec_ldl(1,(const signed short *)p);
s16 = vec_ldl(1,(_10 *)p);
vec_dst((const signed short *)p,1,1);
vec_dstst((const signed short *)p,1,1);
vec_dststt((const signed short *)p,1,1);
vec_dstt((const signed short *)p,1,1);
vec_dst((_10 *)p,1,1);
vec_dstst((_10 *)p,1,1);
vec_dststt((_10 *)p,1,1);
vec_dstt((_10 *)p,1,1);
u8 = vec_lvsl(1,( volatile signed short *)p);
u8 = vec_lvsl(1,(_11 *)p);
u8 = vec_lvsr(1,( volatile signed short *)p);
u8 = vec_lvsr(1,(_11 *)p);
u8 = vec_lvsl(1,( signed short *)p);
u8 = vec_lvsl(1,(_12 *)p);
u8 = vec_lvsr(1,( signed short *)p);
u8 = vec_lvsr(1,(_12 *)p);
s16 = vec_ld(1,( signed short *)p);
s16 = vec_ld(1,(_12 *)p);
s16 = vec_lde(1,( signed short *)p);
s16 = vec_lde(1,(_12 *)p);
s16 = vec_ldl(1,( signed short *)p);
s16 = vec_ldl(1,(_12 *)p);
vec_dst(( signed short *)p,1,1);
vec_dstst(( signed short *)p,1,1);
vec_dststt(( signed short *)p,1,1);
vec_dstt(( signed short *)p,1,1);
vec_dst((_12 *)p,1,1);
vec_dstst((_12 *)p,1,1);
vec_dststt((_12 *)p,1,1);
vec_dstt((_12 *)p,1,1);
vec_st(s16,1,( signed short *)p);
vec_st(s16,1,(_12 *)p);
vec_ste(s16,1,( signed short *)p);
vec_ste(s16,1,(_12 *)p);
vec_stl(s16,1,( signed short *)p);
vec_stl(s16,1,(_12 *)p);
u8 = vec_lvsl(1,(const volatile unsigned *)p);
u8 = vec_lvsl(1,(_13 *)p);
u8 = vec_lvsr(1,(const volatile unsigned *)p);
u8 = vec_lvsr(1,(_13 *)p);
u8 = vec_lvsl(1,(const unsigned *)p);
u8 = vec_lvsl(1,(_14 *)p);
u8 = vec_lvsr(1,(const unsigned *)p);
u8 = vec_lvsr(1,(_14 *)p);
u32 = vec_ld(1,(const unsigned *)p);
u32 = vec_ld(1,(_14 *)p);
u32 = vec_lde(1,(const unsigned *)p);
u32 = vec_lde(1,(_14 *)p);
u32 = vec_ldl(1,(const unsigned *)p);
u32 = vec_ldl(1,(_14 *)p);
vec_dst((const unsigned *)p,1,1);
vec_dstst((const unsigned *)p,1,1);
vec_dststt((const unsigned *)p,1,1);
vec_dstt((const unsigned *)p,1,1);
vec_dst((_14 *)p,1,1);
vec_dstst((_14 *)p,1,1);
vec_dststt((_14 *)p,1,1);
vec_dstt((_14 *)p,1,1);
u8 = vec_lvsl(1,( volatile unsigned *)p);
u8 = vec_lvsl(1,(_15 *)p);
u8 = vec_lvsr(1,( volatile unsigned *)p);
u8 = vec_lvsr(1,(_15 *)p);
u8 = vec_lvsl(1,( unsigned *)p);
u8 = vec_lvsl(1,(_16 *)p);
u8 = vec_lvsr(1,( unsigned *)p);
u8 = vec_lvsr(1,(_16 *)p);
u32 = vec_ld(1,( unsigned *)p);
u32 = vec_ld(1,(_16 *)p);
u32 = vec_lde(1,( unsigned *)p);
u32 = vec_lde(1,(_16 *)p);
u32 = vec_ldl(1,( unsigned *)p);
u32 = vec_ldl(1,(_16 *)p);
vec_dst(( unsigned *)p,1,1);
vec_dstst(( unsigned *)p,1,1);
vec_dststt(( unsigned *)p,1,1);
vec_dstt(( unsigned *)p,1,1);
vec_dst((_16 *)p,1,1);
vec_dstst((_16 *)p,1,1);
vec_dststt((_16 *)p,1,1);
vec_dstt((_16 *)p,1,1);
vec_st(u32,1,( unsigned *)p);
vec_st(u32,1,(_16 *)p);
vec_ste(u32,1,( unsigned *)p);
vec_ste(u32,1,(_16 *)p);
vec_stl(u32,1,( unsigned *)p);
vec_stl(u32,1,(_16 *)p);
u8 = vec_lvsl(1,(const volatile signed short int *)p);
u8 = vec_lvsl(1,(_17 *)p);
u8 = vec_lvsr(1,(const volatile signed short int *)p);
u8 = vec_lvsr(1,(_17 *)p);
u8 = vec_lvsl(1,(const signed short int *)p);
u8 = vec_lvsl(1,(_18 *)p);
u8 = vec_lvsr(1,(const signed short int *)p);
u8 = vec_lvsr(1,(_18 *)p);
s16 = vec_ld(1,(const signed short int *)p);
s16 = vec_ld(1,(_18 *)p);
s16 = vec_lde(1,(const signed short int *)p);
s16 = vec_lde(1,(_18 *)p);
s16 = vec_ldl(1,(const signed short int *)p);
s16 = vec_ldl(1,(_18 *)p);
vec_dst((const signed short int *)p,1,1);
vec_dstst((const signed short int *)p,1,1);
vec_dststt((const signed short int *)p,1,1);
vec_dstt((const signed short int *)p,1,1);
vec_dst((_18 *)p,1,1);
vec_dstst((_18 *)p,1,1);
vec_dststt((_18 *)p,1,1);
vec_dstt((_18 *)p,1,1);
u8 = vec_lvsl(1,( volatile signed short int *)p);
u8 = vec_lvsl(1,(_19 *)p);
u8 = vec_lvsr(1,( volatile signed short int *)p);
u8 = vec_lvsr(1,(_19 *)p);
u8 = vec_lvsl(1,( signed short int *)p);
u8 = vec_lvsl(1,(_20 *)p);
u8 = vec_lvsr(1,( signed short int *)p);
u8 = vec_lvsr(1,(_20 *)p);
s16 = vec_ld(1,( signed short int *)p);
s16 = vec_ld(1,(_20 *)p);
s16 = vec_lde(1,( signed short int *)p);
s16 = vec_lde(1,(_20 *)p);
s16 = vec_ldl(1,( signed short int *)p);
s16 = vec_ldl(1,(_20 *)p);
vec_dst(( signed short int *)p,1,1);
vec_dstst(( signed short int *)p,1,1);
vec_dststt(( signed short int *)p,1,1);
vec_dstt(( signed short int *)p,1,1);
vec_dst((_20 *)p,1,1);
vec_dstst((_20 *)p,1,1);
vec_dststt((_20 *)p,1,1);
vec_dstt((_20 *)p,1,1);
vec_st(s16,1,( signed short int *)p);
vec_st(s16,1,(_20 *)p);
vec_ste(s16,1,( signed short int *)p);
vec_ste(s16,1,(_20 *)p);
vec_stl(s16,1,( signed short int *)p);
vec_stl(s16,1,(_20 *)p);
u8 = vec_lvsl(1,(const volatile unsigned short int *)p);
u8 = vec_lvsl(1,(_21 *)p);
u8 = vec_lvsr(1,(const volatile unsigned short int *)p);
u8 = vec_lvsr(1,(_21 *)p);
u8 = vec_lvsl(1,(const unsigned short int *)p);
u8 = vec_lvsl(1,(_22 *)p);
u8 = vec_lvsr(1,(const unsigned short int *)p);
u8 = vec_lvsr(1,(_22 *)p);
u16 = vec_ld(1,(const unsigned short int *)p);
u16 = vec_ld(1,(_22 *)p);
u16 = vec_lde(1,(const unsigned short int *)p);
u16 = vec_lde(1,(_22 *)p);
u16 = vec_ldl(1,(const unsigned short int *)p);
u16 = vec_ldl(1,(_22 *)p);
vec_dst((const unsigned short int *)p,1,1);
vec_dstst((const unsigned short int *)p,1,1);
vec_dststt((const unsigned short int *)p,1,1);
vec_dstt((const unsigned short int *)p,1,1);
vec_dst((_22 *)p,1,1);
vec_dstst((_22 *)p,1,1);
vec_dststt((_22 *)p,1,1);
vec_dstt((_22 *)p,1,1);
u8 = vec_lvsl(1,( volatile unsigned short int *)p);
u8 = vec_lvsl(1,(_23 *)p);
u8 = vec_lvsr(1,( volatile unsigned short int *)p);
u8 = vec_lvsr(1,(_23 *)p);
u8 = vec_lvsl(1,( unsigned short int *)p);
u8 = vec_lvsl(1,(_24 *)p);
u8 = vec_lvsr(1,( unsigned short int *)p);
u8 = vec_lvsr(1,(_24 *)p);
u16 = vec_ld(1,( unsigned short int *)p);
u16 = vec_ld(1,(_24 *)p);
u16 = vec_lde(1,( unsigned short int *)p);
u16 = vec_lde(1,(_24 *)p);
u16 = vec_ldl(1,( unsigned short int *)p);
u16 = vec_ldl(1,(_24 *)p);
vec_dst(( unsigned short int *)p,1,1);
vec_dstst(( unsigned short int *)p,1,1);
vec_dststt(( unsigned short int *)p,1,1);
vec_dstt(( unsigned short int *)p,1,1);
vec_dst((_24 *)p,1,1);
vec_dstst((_24 *)p,1,1);
vec_dststt((_24 *)p,1,1);
vec_dstt((_24 *)p,1,1);
vec_st(u16,1,( unsigned short int *)p);
vec_st(u16,1,(_24 *)p);
vec_ste(u16,1,( unsigned short int *)p);
vec_ste(u16,1,(_24 *)p);
vec_stl(u16,1,( unsigned short int *)p);
vec_stl(u16,1,(_24 *)p);
p16 = vec_ld(1,(const vector pixel *)p);
p16 = vec_ld(1,(_26 *)p);
p16 = vec_ldl(1,(const vector pixel *)p);
p16 = vec_ldl(1,(_26 *)p);
vec_dst((const vector pixel *)p,1,1);
vec_dstst((const vector pixel *)p,1,1);
vec_dststt((const vector pixel *)p,1,1);
vec_dstt((const vector pixel *)p,1,1);
vec_dst((_26 *)p,1,1);
vec_dstst((_26 *)p,1,1);
vec_dststt((_26 *)p,1,1);
vec_dstt((_26 *)p,1,1);
p16 = vec_ld(1,( vector pixel *)p);
p16 = vec_ld(1,(_28 *)p);
p16 = vec_ldl(1,( vector pixel *)p);
p16 = vec_ldl(1,(_28 *)p);
vec_dst(( vector pixel *)p,1,1);
vec_dstst(( vector pixel *)p,1,1);
vec_dststt(( vector pixel *)p,1,1);
vec_dstt(( vector pixel *)p,1,1);
vec_dst((_28 *)p,1,1);
vec_dstst((_28 *)p,1,1);
vec_dststt((_28 *)p,1,1);
vec_dstt((_28 *)p,1,1);
vec_st(p16,1,( vector pixel *)p);
vec_st(p16,1,(_28 *)p);
vec_stl(p16,1,( vector pixel *)p);
vec_stl(p16,1,(_28 *)p);
b32 = vec_ld(1,(const vector bool int *)p);
b32 = vec_ld(1,(_30 *)p);
b32 = vec_ldl(1,(const vector bool int *)p);
b32 = vec_ldl(1,(_30 *)p);
vec_dst((const vector bool int *)p,1,1);
vec_dstst((const vector bool int *)p,1,1);
vec_dststt((const vector bool int *)p,1,1);
vec_dstt((const vector bool int *)p,1,1);
vec_dst((_30 *)p,1,1);
vec_dstst((_30 *)p,1,1);
vec_dststt((_30 *)p,1,1);
vec_dstt((_30 *)p,1,1);
b32 = vec_ld(1,( vector bool int *)p);
b32 = vec_ld(1,(_32 *)p);
b32 = vec_ldl(1,( vector bool int *)p);
b32 = vec_ldl(1,(_32 *)p);
vec_dst(( vector bool int *)p,1,1);
vec_dstst(( vector bool int *)p,1,1);
vec_dststt(( vector bool int *)p,1,1);
vec_dstt(( vector bool int *)p,1,1);
vec_dst((_32 *)p,1,1);
vec_dstst((_32 *)p,1,1);
vec_dststt((_32 *)p,1,1);
vec_dstt((_32 *)p,1,1);
vec_st(b32,1,( vector bool int *)p);
vec_st(b32,1,(_32 *)p);
vec_stl(b32,1,( vector bool int *)p);
vec_stl(b32,1,(_32 *)p);
s8 = vec_ld(1,(const vector signed char *)p);
s8 = vec_ld(1,(_34 *)p);
s8 = vec_ldl(1,(const vector signed char *)p);
s8 = vec_ldl(1,(_34 *)p);
vec_dst((const vector signed char *)p,1,1);
vec_dstst((const vector signed char *)p,1,1);
vec_dststt((const vector signed char *)p,1,1);
vec_dstt((const vector signed char *)p,1,1);
vec_dst((_34 *)p,1,1);
vec_dstst((_34 *)p,1,1);
vec_dststt((_34 *)p,1,1);
vec_dstt((_34 *)p,1,1);
s8 = vec_ld(1,( vector signed char *)p);
s8 = vec_ld(1,(_36 *)p);
s8 = vec_ldl(1,( vector signed char *)p);
s8 = vec_ldl(1,(_36 *)p);
vec_dst(( vector signed char *)p,1,1);
vec_dstst(( vector signed char *)p,1,1);
vec_dststt(( vector signed char *)p,1,1);
vec_dstt(( vector signed char *)p,1,1);
vec_dst((_36 *)p,1,1);
vec_dstst((_36 *)p,1,1);
vec_dststt((_36 *)p,1,1);
vec_dstt((_36 *)p,1,1);
vec_st(s8,1,( vector signed char *)p);
vec_st(s8,1,(_36 *)p);
vec_stl(s8,1,( vector signed char *)p);
vec_stl(s8,1,(_36 *)p);
u8 = vec_lvsl(1,(const volatile unsigned *)p);
u8 = vec_lvsl(1,(_37 *)p);
u8 = vec_lvsr(1,(const volatile unsigned *)p);
u8 = vec_lvsr(1,(_37 *)p);
u8 = vec_lvsl(1,(const unsigned *)p);
u8 = vec_lvsl(1,(_38 *)p);
u8 = vec_lvsr(1,(const unsigned *)p);
u8 = vec_lvsr(1,(_38 *)p);
u32 = vec_ld(1,(const unsigned *)p);
u32 = vec_ld(1,(_38 *)p);
u32 = vec_lde(1,(const unsigned *)p);
u32 = vec_lde(1,(_38 *)p);
u32 = vec_ldl(1,(const unsigned *)p);
u32 = vec_ldl(1,(_38 *)p);
vec_dst((const unsigned *)p,1,1);
vec_dstst((const unsigned *)p,1,1);
vec_dststt((const unsigned *)p,1,1);
vec_dstt((const unsigned *)p,1,1);
vec_dst((_38 *)p,1,1);
vec_dstst((_38 *)p,1,1);
vec_dststt((_38 *)p,1,1);
vec_dstt((_38 *)p,1,1);
u8 = vec_lvsl(1,( volatile unsigned *)p);
u8 = vec_lvsl(1,(_39 *)p);
u8 = vec_lvsr(1,( volatile unsigned *)p);
u8 = vec_lvsr(1,(_39 *)p);
u8 = vec_lvsl(1,( unsigned *)p);
u8 = vec_lvsl(1,(_40 *)p);
u8 = vec_lvsr(1,( unsigned *)p);
u8 = vec_lvsr(1,(_40 *)p);
u32 = vec_ld(1,( unsigned *)p);
u32 = vec_ld(1,(_40 *)p);
u32 = vec_lde(1,( unsigned *)p);
u32 = vec_lde(1,(_40 *)p);
u32 = vec_ldl(1,( unsigned *)p);
u32 = vec_ldl(1,(_40 *)p);
vec_dst(( unsigned *)p,1,1);
vec_dstst(( unsigned *)p,1,1);
vec_dststt(( unsigned *)p,1,1);
vec_dstt(( unsigned *)p,1,1);
vec_dst((_40 *)p,1,1);
vec_dstst((_40 *)p,1,1);
vec_dststt((_40 *)p,1,1);
vec_dstt((_40 *)p,1,1);
vec_st(u32,1,( unsigned *)p);
vec_st(u32,1,(_40 *)p);
vec_ste(u32,1,( unsigned *)p);
vec_ste(u32,1,(_40 *)p);
vec_stl(u32,1,( unsigned *)p);
vec_stl(u32,1,(_40 *)p);
u8 = vec_lvsl(1,(const volatile signed int *)p);
u8 = vec_lvsl(1,(_41 *)p);
u8 = vec_lvsr(1,(const volatile signed int *)p);
u8 = vec_lvsr(1,(_41 *)p);
u8 = vec_lvsl(1,(const signed int *)p);
u8 = vec_lvsl(1,(_42 *)p);
u8 = vec_lvsr(1,(const signed int *)p);
u8 = vec_lvsr(1,(_42 *)p);
s32 = vec_ld(1,(const signed int *)p);
s32 = vec_ld(1,(_42 *)p);
s32 = vec_lde(1,(const signed int *)p);
s32 = vec_lde(1,(_42 *)p);
s32 = vec_ldl(1,(const signed int *)p);
s32 = vec_ldl(1,(_42 *)p);
vec_dst((const signed int *)p,1,1);
vec_dstst((const signed int *)p,1,1);
vec_dststt((const signed int *)p,1,1);
vec_dstt((const signed int *)p,1,1);
vec_dst((_42 *)p,1,1);
vec_dstst((_42 *)p,1,1);
vec_dststt((_42 *)p,1,1);
vec_dstt((_42 *)p,1,1);
u8 = vec_lvsl(1,( volatile signed int *)p);
u8 = vec_lvsl(1,(_43 *)p);
u8 = vec_lvsr(1,( volatile signed int *)p);
u8 = vec_lvsr(1,(_43 *)p);
u8 = vec_lvsl(1,( signed int *)p);
u8 = vec_lvsl(1,(_44 *)p);
u8 = vec_lvsr(1,( signed int *)p);
u8 = vec_lvsr(1,(_44 *)p);
s32 = vec_ld(1,( signed int *)p);
s32 = vec_ld(1,(_44 *)p);
s32 = vec_lde(1,( signed int *)p);
s32 = vec_lde(1,(_44 *)p);
s32 = vec_ldl(1,( signed int *)p);
s32 = vec_ldl(1,(_44 *)p);
vec_dst(( signed int *)p,1,1);
vec_dstst(( signed int *)p,1,1);
vec_dststt(( signed int *)p,1,1);
vec_dstt(( signed int *)p,1,1);
vec_dst((_44 *)p,1,1);
vec_dstst((_44 *)p,1,1);
vec_dststt((_44 *)p,1,1);
vec_dstt((_44 *)p,1,1);
vec_st(s32,1,( signed int *)p);
vec_st(s32,1,(_44 *)p);
vec_ste(s32,1,( signed int *)p);
vec_ste(s32,1,(_44 *)p);
vec_stl(s32,1,( signed int *)p);
vec_stl(s32,1,(_44 *)p);
f32 = vec_ld(1,(const vector float *)p);
f32 = vec_ld(1,(_46 *)p);
f32 = vec_ldl(1,(const vector float *)p);
f32 = vec_ldl(1,(_46 *)p);
vec_dst((const vector float *)p,1,1);
vec_dstst((const vector float *)p,1,1);
vec_dststt((const vector float *)p,1,1);
vec_dstt((const vector float *)p,1,1);
vec_dst((_46 *)p,1,1);
vec_dstst((_46 *)p,1,1);
vec_dststt((_46 *)p,1,1);
vec_dstt((_46 *)p,1,1);
f32 = vec_ld(1,( vector float *)p);
f32 = vec_ld(1,(_48 *)p);
f32 = vec_ldl(1,( vector float *)p);
f32 = vec_ldl(1,(_48 *)p);
vec_dst(( vector float *)p,1,1);
vec_dstst(( vector float *)p,1,1);
vec_dststt(( vector float *)p,1,1);
vec_dstt(( vector float *)p,1,1);
vec_dst((_48 *)p,1,1);
vec_dstst((_48 *)p,1,1);
vec_dststt((_48 *)p,1,1);
vec_dstt((_48 *)p,1,1);
vec_st(f32,1,( vector float *)p);
vec_st(f32,1,(_48 *)p);
vec_stl(f32,1,( vector float *)p);
vec_stl(f32,1,(_48 *)p);
s16 = vec_ld(1,(const vector signed short *)p);
s16 = vec_ld(1,(_50 *)p);
s16 = vec_ldl(1,(const vector signed short *)p);
s16 = vec_ldl(1,(_50 *)p);
vec_dst((const vector signed short *)p,1,1);
vec_dstst((const vector signed short *)p,1,1);
vec_dststt((const vector signed short *)p,1,1);
vec_dstt((const vector signed short *)p,1,1);
vec_dst((_50 *)p,1,1);
vec_dstst((_50 *)p,1,1);
vec_dststt((_50 *)p,1,1);
vec_dstt((_50 *)p,1,1);
s16 = vec_ld(1,( vector signed short *)p);
s16 = vec_ld(1,(_52 *)p);
s16 = vec_ldl(1,( vector signed short *)p);
s16 = vec_ldl(1,(_52 *)p);
vec_dst(( vector signed short *)p,1,1);
vec_dstst(( vector signed short *)p,1,1);
vec_dststt(( vector signed short *)p,1,1);
vec_dstt(( vector signed short *)p,1,1);
vec_dst((_52 *)p,1,1);
vec_dstst((_52 *)p,1,1);
vec_dststt((_52 *)p,1,1);
vec_dstt((_52 *)p,1,1);
vec_st(s16,1,( vector signed short *)p);
vec_st(s16,1,(_52 *)p);
vec_stl(s16,1,( vector signed short *)p);
vec_stl(s16,1,(_52 *)p);
u8 = vec_lvsl(1,(const volatile unsigned char *)p);
u8 = vec_lvsl(1,(_53 *)p);
u8 = vec_lvsr(1,(const volatile unsigned char *)p);
u8 = vec_lvsr(1,(_53 *)p);
u8 = vec_lvsl(1,(const unsigned char *)p);
u8 = vec_lvsl(1,(_54 *)p);
u8 = vec_lvsr(1,(const unsigned char *)p);
u8 = vec_lvsr(1,(_54 *)p);
u8 = vec_ld(1,(const unsigned char *)p);
u8 = vec_ld(1,(_54 *)p);
u8 = vec_lde(1,(const unsigned char *)p);
u8 = vec_lde(1,(_54 *)p);
u8 = vec_ldl(1,(const unsigned char *)p);
u8 = vec_ldl(1,(_54 *)p);
vec_dst((const unsigned char *)p,1,1);
vec_dstst((const unsigned char *)p,1,1);
vec_dststt((const unsigned char *)p,1,1);
vec_dstt((const unsigned char *)p,1,1);
vec_dst((_54 *)p,1,1);
vec_dstst((_54 *)p,1,1);
vec_dststt((_54 *)p,1,1);
vec_dstt((_54 *)p,1,1);
u8 = vec_lvsl(1,( volatile unsigned char *)p);
u8 = vec_lvsl(1,(_55 *)p);
u8 = vec_lvsr(1,( volatile unsigned char *)p);
u8 = vec_lvsr(1,(_55 *)p);
u8 = vec_lvsl(1,( unsigned char *)p);
u8 = vec_lvsl(1,(_56 *)p);
u8 = vec_lvsr(1,( unsigned char *)p);
u8 = vec_lvsr(1,(_56 *)p);
u8 = vec_ld(1,( unsigned char *)p);
u8 = vec_ld(1,(_56 *)p);
u8 = vec_lde(1,( unsigned char *)p);
u8 = vec_lde(1,(_56 *)p);
u8 = vec_ldl(1,( unsigned char *)p);
u8 = vec_ldl(1,(_56 *)p);
vec_dst(( unsigned char *)p,1,1);
vec_dstst(( unsigned char *)p,1,1);
vec_dststt(( unsigned char *)p,1,1);
vec_dstt(( unsigned char *)p,1,1);
vec_dst((_56 *)p,1,1);
vec_dstst((_56 *)p,1,1);
vec_dststt((_56 *)p,1,1);
vec_dstt((_56 *)p,1,1);
vec_st(u8,1,( unsigned char *)p);
vec_st(u8,1,(_56 *)p);
vec_ste(u8,1,( unsigned char *)p);
vec_ste(u8,1,(_56 *)p);
vec_stl(u8,1,( unsigned char *)p);
vec_stl(u8,1,(_56 *)p);
u8 = vec_lvsl(1,(const volatile signed int *)p);
u8 = vec_lvsl(1,(_57 *)p);
u8 = vec_lvsr(1,(const volatile signed int *)p);
u8 = vec_lvsr(1,(_57 *)p);
u8 = vec_lvsl(1,(const signed int *)p);
u8 = vec_lvsl(1,(_58 *)p);
u8 = vec_lvsr(1,(const signed int *)p);
u8 = vec_lvsr(1,(_58 *)p);
s32 = vec_ld(1,(const signed int *)p);
s32 = vec_ld(1,(_58 *)p);
s32 = vec_lde(1,(const signed int *)p);
s32 = vec_lde(1,(_58 *)p);
s32 = vec_ldl(1,(const signed int *)p);
s32 = vec_ldl(1,(_58 *)p);
vec_dst((const signed int *)p,1,1);
vec_dstst((const signed int *)p,1,1);
vec_dststt((const signed int *)p,1,1);
vec_dstt((const signed int *)p,1,1);
vec_dst((_58 *)p,1,1);
vec_dstst((_58 *)p,1,1);
vec_dststt((_58 *)p,1,1);
vec_dstt((_58 *)p,1,1);
u8 = vec_lvsl(1,( volatile signed int *)p);
u8 = vec_lvsl(1,(_59 *)p);
u8 = vec_lvsr(1,( volatile signed int *)p);
u8 = vec_lvsr(1,(_59 *)p);
u8 = vec_lvsl(1,( signed int *)p);
u8 = vec_lvsl(1,(_60 *)p);
u8 = vec_lvsr(1,( signed int *)p);
u8 = vec_lvsr(1,(_60 *)p);
s32 = vec_ld(1,( signed int *)p);
s32 = vec_ld(1,(_60 *)p);
s32 = vec_lde(1,( signed int *)p);
s32 = vec_lde(1,(_60 *)p);
s32 = vec_ldl(1,( signed int *)p);
s32 = vec_ldl(1,(_60 *)p);
vec_dst(( signed int *)p,1,1);
vec_dstst(( signed int *)p,1,1);
vec_dststt(( signed int *)p,1,1);
vec_dstt(( signed int *)p,1,1);
vec_dst((_60 *)p,1,1);
vec_dstst((_60 *)p,1,1);
vec_dststt((_60 *)p,1,1);
vec_dstt((_60 *)p,1,1);
vec_st(s32,1,( signed int *)p);
vec_st(s32,1,(_60 *)p);
vec_ste(s32,1,( signed int *)p);
vec_ste(s32,1,(_60 *)p);
vec_stl(s32,1,( signed int *)p);
vec_stl(s32,1,(_60 *)p);
u8 = vec_lvsl(1,(const volatile unsigned int *)p);
u8 = vec_lvsl(1,(_61 *)p);
u8 = vec_lvsr(1,(const volatile unsigned int *)p);
u8 = vec_lvsr(1,(_61 *)p);
u8 = vec_lvsl(1,(const unsigned int *)p);
u8 = vec_lvsl(1,(_62 *)p);
u8 = vec_lvsr(1,(const unsigned int *)p);
u8 = vec_lvsr(1,(_62 *)p);
u32 = vec_ld(1,(const unsigned int *)p);
u32 = vec_ld(1,(_62 *)p);
u32 = vec_lde(1,(const unsigned int *)p);
u32 = vec_lde(1,(_62 *)p);
u32 = vec_ldl(1,(const unsigned int *)p);
u32 = vec_ldl(1,(_62 *)p);
vec_dst((const unsigned int *)p,1,1);
vec_dstst((const unsigned int *)p,1,1);
vec_dststt((const unsigned int *)p,1,1);
vec_dstt((const unsigned int *)p,1,1);
vec_dst((_62 *)p,1,1);
vec_dstst((_62 *)p,1,1);
vec_dststt((_62 *)p,1,1);
vec_dstt((_62 *)p,1,1);
u8 = vec_lvsl(1,( volatile unsigned int *)p);
u8 = vec_lvsl(1,(_63 *)p);
u8 = vec_lvsr(1,( volatile unsigned int *)p);
u8 = vec_lvsr(1,(_63 *)p);
u8 = vec_lvsl(1,( unsigned int *)p);
u8 = vec_lvsl(1,(_64 *)p);
u8 = vec_lvsr(1,( unsigned int *)p);
u8 = vec_lvsr(1,(_64 *)p);
u32 = vec_ld(1,( unsigned int *)p);
u32 = vec_ld(1,(_64 *)p);
u32 = vec_lde(1,( unsigned int *)p);
u32 = vec_lde(1,(_64 *)p);
u32 = vec_ldl(1,( unsigned int *)p);
u32 = vec_ldl(1,(_64 *)p);
vec_dst(( unsigned int *)p,1,1);
vec_dstst(( unsigned int *)p,1,1);
vec_dststt(( unsigned int *)p,1,1);
vec_dstt(( unsigned int *)p,1,1);
vec_dst((_64 *)p,1,1);
vec_dstst((_64 *)p,1,1);
vec_dststt((_64 *)p,1,1);
vec_dstt((_64 *)p,1,1);
vec_st(u32,1,( unsigned int *)p);
vec_st(u32,1,(_64 *)p);
vec_ste(u32,1,( unsigned int *)p);
vec_ste(u32,1,(_64 *)p);
vec_stl(u32,1,( unsigned int *)p);
vec_stl(u32,1,(_64 *)p);
u8 = vec_lvsl(1,(const volatile unsigned short *)p);
u8 = vec_lvsl(1,(_65 *)p);
u8 = vec_lvsr(1,(const volatile unsigned short *)p);
u8 = vec_lvsr(1,(_65 *)p);
u8 = vec_lvsl(1,(const unsigned short *)p);
u8 = vec_lvsl(1,(_66 *)p);
u8 = vec_lvsr(1,(const unsigned short *)p);
u8 = vec_lvsr(1,(_66 *)p);
u16 = vec_ld(1,(const unsigned short *)p);
u16 = vec_ld(1,(_66 *)p);
u16 = vec_lde(1,(const unsigned short *)p);
u16 = vec_lde(1,(_66 *)p);
u16 = vec_ldl(1,(const unsigned short *)p);
u16 = vec_ldl(1,(_66 *)p);
vec_dst((const unsigned short *)p,1,1);
vec_dstst((const unsigned short *)p,1,1);
vec_dststt((const unsigned short *)p,1,1);
vec_dstt((const unsigned short *)p,1,1);
vec_dst((_66 *)p,1,1);
vec_dstst((_66 *)p,1,1);
vec_dststt((_66 *)p,1,1);
vec_dstt((_66 *)p,1,1);
u8 = vec_lvsl(1,( volatile unsigned short *)p);
u8 = vec_lvsl(1,(_67 *)p);
u8 = vec_lvsr(1,( volatile unsigned short *)p);
u8 = vec_lvsr(1,(_67 *)p);
u8 = vec_lvsl(1,( unsigned short *)p);
u8 = vec_lvsl(1,(_68 *)p);
u8 = vec_lvsr(1,( unsigned short *)p);
u8 = vec_lvsr(1,(_68 *)p);
u16 = vec_ld(1,( unsigned short *)p);
u16 = vec_ld(1,(_68 *)p);
u16 = vec_lde(1,( unsigned short *)p);
u16 = vec_lde(1,(_68 *)p);
u16 = vec_ldl(1,( unsigned short *)p);
u16 = vec_ldl(1,(_68 *)p);
vec_dst(( unsigned short *)p,1,1);
vec_dstst(( unsigned short *)p,1,1);
vec_dststt(( unsigned short *)p,1,1);
vec_dstt(( unsigned short *)p,1,1);
vec_dst((_68 *)p,1,1);
vec_dstst((_68 *)p,1,1);
vec_dststt((_68 *)p,1,1);
vec_dstt((_68 *)p,1,1);
vec_st(u16,1,( unsigned short *)p);
vec_st(u16,1,(_68 *)p);
vec_ste(u16,1,( unsigned short *)p);
vec_ste(u16,1,(_68 *)p);
vec_stl(u16,1,( unsigned short *)p);
vec_stl(u16,1,(_68 *)p);
u8 = vec_lvsl(1,(const volatile short *)p);
u8 = vec_lvsl(1,(_69 *)p);
u8 = vec_lvsr(1,(const volatile short *)p);
u8 = vec_lvsr(1,(_69 *)p);
u8 = vec_lvsl(1,(const short *)p);
u8 = vec_lvsl(1,(_70 *)p);
u8 = vec_lvsr(1,(const short *)p);
u8 = vec_lvsr(1,(_70 *)p);
s16 = vec_ld(1,(const short *)p);
s16 = vec_ld(1,(_70 *)p);
s16 = vec_lde(1,(const short *)p);
s16 = vec_lde(1,(_70 *)p);
s16 = vec_ldl(1,(const short *)p);
s16 = vec_ldl(1,(_70 *)p);
vec_dst((const short *)p,1,1);
vec_dstst((const short *)p,1,1);
vec_dststt((const short *)p,1,1);
vec_dstt((const short *)p,1,1);
vec_dst((_70 *)p,1,1);
vec_dstst((_70 *)p,1,1);
vec_dststt((_70 *)p,1,1);
vec_dstt((_70 *)p,1,1);
u8 = vec_lvsl(1,( volatile short *)p);
u8 = vec_lvsl(1,(_71 *)p);
u8 = vec_lvsr(1,( volatile short *)p);
u8 = vec_lvsr(1,(_71 *)p);
u8 = vec_lvsl(1,( short *)p);
u8 = vec_lvsl(1,(_72 *)p);
u8 = vec_lvsr(1,( short *)p);
u8 = vec_lvsr(1,(_72 *)p);
s16 = vec_ld(1,( short *)p);
s16 = vec_ld(1,(_72 *)p);
s16 = vec_lde(1,( short *)p);
s16 = vec_lde(1,(_72 *)p);
s16 = vec_ldl(1,( short *)p);
s16 = vec_ldl(1,(_72 *)p);
vec_dst(( short *)p,1,1);
vec_dstst(( short *)p,1,1);
vec_dststt(( short *)p,1,1);
vec_dstt(( short *)p,1,1);
vec_dst((_72 *)p,1,1);
vec_dstst((_72 *)p,1,1);
vec_dststt((_72 *)p,1,1);
vec_dstt((_72 *)p,1,1);
vec_st(s16,1,( short *)p);
vec_st(s16,1,(_72 *)p);
vec_ste(s16,1,( short *)p);
vec_ste(s16,1,(_72 *)p);
vec_stl(s16,1,( short *)p);
vec_stl(s16,1,(_72 *)p);
u8 = vec_lvsl(1,(const int volatile *)p);
u8 = vec_lvsl(1,(_73 *)p);
u8 = vec_lvsr(1,(const int volatile *)p);
u8 = vec_lvsr(1,(_73 *)p);
u8 = vec_lvsl(1,(const int *)p);
u8 = vec_lvsl(1,(_74 *)p);
u8 = vec_lvsr(1,(const int *)p);
u8 = vec_lvsr(1,(_74 *)p);
s32 = vec_ld(1,(const int *)p);
s32 = vec_ld(1,(_74 *)p);
s32 = vec_lde(1,(const int *)p);
s32 = vec_lde(1,(_74 *)p);
s32 = vec_ldl(1,(const int *)p);
s32 = vec_ldl(1,(_74 *)p);
vec_dst((const int *)p,1,1);
vec_dstst((const int *)p,1,1);
vec_dststt((const int *)p,1,1);
vec_dstt((const int *)p,1,1);
vec_dst((_74 *)p,1,1);
vec_dstst((_74 *)p,1,1);
vec_dststt((_74 *)p,1,1);
vec_dstt((_74 *)p,1,1);
u8 = vec_lvsl(1,( volatile int *)p);
u8 = vec_lvsl(1,(_75 *)p);
u8 = vec_lvsr(1,( volatile int *)p);
u8 = vec_lvsr(1,(_75 *)p);
u8 = vec_lvsl(1,( int *)p);
u8 = vec_lvsl(1,(_76 *)p);
u8 = vec_lvsr(1,( int *)p);
u8 = vec_lvsr(1,(_76 *)p);
s32 = vec_ld(1,( int *)p);
s32 = vec_ld(1,(_76 *)p);
s32 = vec_lde(1,(int *)p);
s32 = vec_lde(1,(_76 *)p);
s32 = vec_ldl(1,(int *)p);
s32 = vec_ldl(1,(_76 *)p);
vec_dst((int *)p,1,1);
vec_dstst((int *)p,1,1);
vec_dststt((int *)p,1,1);
vec_dstt((int *)p,1,1);
vec_dst((_76 *)p,1,1);
vec_dstst((_76 *)p,1,1);
vec_dststt((_76 *)p,1,1);
vec_dstt((_76 *)p,1,1);
vec_st(s32,1,(int *)p);
vec_st(s32,1,(_76 *)p);
vec_ste(s32,1,(int *)p);
vec_ste(s32,1,(_76 *)p);
vec_stl(s32,1,(int *)p);
vec_stl(s32,1,(_76 *)p);
u16 = vec_ld(1,(const vector unsigned short *)p);
u16 = vec_ld(1,(_78 *)p);
u16 = vec_ldl(1,(const vector unsigned short *)p);
u16 = vec_ldl(1,(_78 *)p);
vec_dst((const vector unsigned short *)p,1,1);
vec_dstst((const vector unsigned short *)p,1,1);
vec_dststt((const vector unsigned short *)p,1,1);
vec_dstt((const vector unsigned short *)p,1,1);
vec_dst((_78 *)p,1,1);
vec_dstst((_78 *)p,1,1);
vec_dststt((_78 *)p,1,1);
vec_dstt((_78 *)p,1,1);
u16 = vec_ld(1,( vector unsigned short *)p);
u16 = vec_ld(1,(_80 *)p);
u16 = vec_ldl(1,( vector unsigned short *)p);
u16 = vec_ldl(1,(_80 *)p);
vec_dst(( vector unsigned short *)p,1,1);
vec_dstst(( vector unsigned short *)p,1,1);
vec_dststt(( vector unsigned short *)p,1,1);
vec_dstt(( vector unsigned short *)p,1,1);
vec_dst((_80 *)p,1,1);
vec_dstst((_80 *)p,1,1);
vec_dststt((_80 *)p,1,1);
vec_dstt((_80 *)p,1,1);
vec_st(u16,1,( vector unsigned short *)p);
vec_st(u16,1,(_80 *)p);
vec_stl(u16,1,( vector unsigned short *)p);
vec_stl(u16,1,(_80 *)p);
b8 = vec_ld(1,(const vector bool char *)p);
b8 = vec_ld(1,(_82 *)p);
b8 = vec_ldl(1,(const vector bool char *)p);
b8 = vec_ldl(1,(_82 *)p);
vec_dst((const vector bool char *)p,1,1);
vec_dstst((const vector bool char *)p,1,1);
vec_dststt((const vector bool char *)p,1,1);
vec_dstt((const vector bool char *)p,1,1);
vec_dst((_82 *)p,1,1);
vec_dstst((_82 *)p,1,1);
vec_dststt((_82 *)p,1,1);
vec_dstt((_82 *)p,1,1);
b8 = vec_ld(1,( vector bool char *)p);
b8 = vec_ld(1,(_84 *)p);
b8 = vec_ldl(1,( vector bool char *)p);
b8 = vec_ldl(1,(_84 *)p);
vec_dst(( vector bool char *)p,1,1);
vec_dstst(( vector bool char *)p,1,1);
vec_dststt(( vector bool char *)p,1,1);
vec_dstt(( vector bool char *)p,1,1);
vec_dst((_84 *)p,1,1);
vec_dstst((_84 *)p,1,1);
vec_dststt((_84 *)p,1,1);
vec_dstt((_84 *)p,1,1);
vec_st(b8,1,( vector bool char *)p);
vec_st(b8,1,(_84 *)p);
vec_stl(b8,1,( vector bool char *)p);
vec_stl(b8,1,(_84 *)p);
u8 = vec_lvsl(1,(const volatile int signed *)p);
u8 = vec_lvsl(1,(_85 *)p);
u8 = vec_lvsr(1,(const volatile int signed *)p);
u8 = vec_lvsr(1,(_85 *)p);
u8 = vec_lvsl(1,(const int signed *)p);
u8 = vec_lvsl(1,(_86 *)p);
u8 = vec_lvsr(1,(const int signed *)p);
u8 = vec_lvsr(1,(_86 *)p);
s32 = vec_ld(1,(const int signed *)p);
s32 = vec_ld(1,(_86 *)p);
s32 = vec_lde(1,(const int signed *)p);
s32 = vec_lde(1,(_86 *)p);
s32 = vec_ldl(1,(const int signed *)p);
s32 = vec_ldl(1,(_86 *)p);
vec_dst((const int signed *)p,1,1);
vec_dstst((const int signed *)p,1,1);
vec_dststt((const int signed *)p,1,1);
vec_dstt((const int signed *)p,1,1);
vec_dst((_86 *)p,1,1);
vec_dstst((_86 *)p,1,1);
vec_dststt((_86 *)p,1,1);
vec_dstt((_86 *)p,1,1);
u8 = vec_lvsl(1,( volatile int signed *)p);
u8 = vec_lvsl(1,(_87 *)p);
u8 = vec_lvsr(1,( volatile int signed *)p);
u8 = vec_lvsr(1,(_87 *)p);
u8 = vec_lvsl(1,(int signed *)p);
u8 = vec_lvsl(1,(_88 *)p);
u8 = vec_lvsr(1,(int signed *)p);
u8 = vec_lvsr(1,(_88 *)p);
s32 = vec_ld(1,(int signed *)p);
s32 = vec_ld(1,(_88 *)p);
s32 = vec_lde(1,(int signed *)p);
s32 = vec_lde(1,(_88 *)p);
s32 = vec_ldl(1,(int signed *)p);
s32 = vec_ldl(1,(_88 *)p);
vec_dst((int signed *)p,1,1);
vec_dstst((int signed *)p,1,1);
vec_dststt((int signed *)p,1,1);
vec_dstt((int signed *)p,1,1);
vec_dst((_88 *)p,1,1);
vec_dstst((_88 *)p,1,1);
vec_dststt((_88 *)p,1,1);
vec_dstt((_88 *)p,1,1);
vec_st(s32,1,(int signed *)p);
vec_st(s32,1,(_88 *)p);
vec_ste(s32,1,(int signed *)p);
vec_ste(s32,1,(_88 *)p);
vec_stl(s32,1,(int signed *)p);
vec_stl(s32,1,(_88 *)p);
s32 = vec_ld(1,(const vector signed int *)p);
s32 = vec_ld(1,(_90 *)p);
s32 = vec_ldl(1,(const vector signed int *)p);
s32 = vec_ldl(1,(_90 *)p);
vec_dst((const vector signed int *)p,1,1);
vec_dstst((const vector signed int *)p,1,1);
vec_dststt((const vector signed int *)p,1,1);
vec_dstt((const vector signed int *)p,1,1);
vec_dst((_90 *)p,1,1);
vec_dstst((_90 *)p,1,1);
vec_dststt((_90 *)p,1,1);
vec_dstt((_90 *)p,1,1);
s32 = vec_ld(1,( vector signed int *)p);
s32 = vec_ld(1,(_92 *)p);
s32 = vec_ldl(1,( vector signed int *)p);
s32 = vec_ldl(1,(_92 *)p);
vec_dst(( vector signed int *)p,1,1);
vec_dstst(( vector signed int *)p,1,1);
vec_dststt(( vector signed int *)p,1,1);
vec_dstt(( vector signed int *)p,1,1);
vec_dst((_92 *)p,1,1);
vec_dstst((_92 *)p,1,1);
vec_dststt((_92 *)p,1,1);
vec_dstt((_92 *)p,1,1);
vec_st(s32,1,( vector signed int *)p);
vec_st(s32,1,(_92 *)p);
vec_stl(s32,1,( vector signed int *)p);
vec_stl(s32,1,(_92 *)p);
u32 = vec_ld(1,(const vector unsigned int *)p);
u32 = vec_ld(1,(_94 *)p);
u32 = vec_ldl(1,(const vector unsigned int *)p);
u32 = vec_ldl(1,(_94 *)p);
vec_dst((const vector unsigned int *)p,1,1);
vec_dstst((const vector unsigned int *)p,1,1);
vec_dststt((const vector unsigned int *)p,1,1);
vec_dstt((const vector unsigned int *)p,1,1);
vec_dst((_94 *)p,1,1);
vec_dstst((_94 *)p,1,1);
vec_dststt((_94 *)p,1,1);
vec_dstt((_94 *)p,1,1);
u32 = vec_ld(1,( vector unsigned int *)p);
u32 = vec_ld(1,(_96 *)p);
u32 = vec_ldl(1,( vector unsigned int *)p);
u32 = vec_ldl(1,(_96 *)p);
vec_dst(( vector unsigned int *)p,1,1);
vec_dstst(( vector unsigned int *)p,1,1);
vec_dststt(( vector unsigned int *)p,1,1);
vec_dstt(( vector unsigned int *)p,1,1);
vec_dst((_96 *)p,1,1);
vec_dstst((_96 *)p,1,1);
vec_dststt((_96 *)p,1,1);
vec_dstt((_96 *)p,1,1);
vec_st(u32,1,( vector unsigned int *)p);
vec_st(u32,1,(_96 *)p);
vec_stl(u32,1,( vector unsigned int *)p);
vec_stl(u32,1,(_96 *)p);
u8 = vec_lvsl(1,(const volatile int signed *)p);
u8 = vec_lvsl(1,(_97 *)p);
u8 = vec_lvsr(1,(const volatile int signed *)p);
u8 = vec_lvsr(1,(_97 *)p);
u8 = vec_lvsl(1,(const int signed *)p);
u8 = vec_lvsl(1,(_98 *)p);
u8 = vec_lvsr(1,(const int signed *)p);
u8 = vec_lvsr(1,(_98 *)p);
s32 = vec_ld(1,(const int signed *)p);
s32 = vec_ld(1,(_98 *)p);
s32 = vec_lde(1,(const int signed *)p);
s32 = vec_lde(1,(_98 *)p);
s32 = vec_ldl(1,(const int signed *)p);
s32 = vec_ldl(1,(_98 *)p);
vec_dst((const int signed *)p,1,1);
vec_dstst((const int signed *)p,1,1);
vec_dststt((const int signed *)p,1,1);
vec_dstt((const int signed *)p,1,1);
vec_dst((_98 *)p,1,1);
vec_dstst((_98 *)p,1,1);
vec_dststt((_98 *)p,1,1);
vec_dstt((_98 *)p,1,1);
u8 = vec_lvsl(1,( volatile int signed *)p);
u8 = vec_lvsl(1,(_99 *)p);
u8 = vec_lvsr(1,( volatile int signed *)p);
u8 = vec_lvsr(1,(_99 *)p);
u8 = vec_lvsl(1,(int signed *)p);
u8 = vec_lvsl(1,(_100 *)p);
u8 = vec_lvsr(1,(int signed *)p);
u8 = vec_lvsr(1,(_100 *)p);
s32 = vec_ld(1,(int signed *)p);
s32 = vec_ld(1,(_100 *)p);
s32 = vec_lde(1,(int signed *)p);
s32 = vec_lde(1,(_100 *)p);
s32 = vec_ldl(1,(int signed *)p);
s32 = vec_ldl(1,(_100 *)p);
vec_dst((int signed *)p,1,1);
vec_dstst((int signed *)p,1,1);
vec_dststt((int signed *)p,1,1);
vec_dstt((int signed *)p,1,1);
vec_dst((_100 *)p,1,1);
vec_dstst((_100 *)p,1,1);
vec_dststt((_100 *)p,1,1);
vec_dstt((_100 *)p,1,1);
vec_st(s32,1,(int signed *)p);
vec_st(s32,1,(_100 *)p);
vec_ste(s32,1,(int signed *)p);
vec_ste(s32,1,(_100 *)p);
vec_stl(s32,1,(int signed *)p);
vec_stl(s32,1,(_100 *)p);
u8 = vec_lvsl(1,(const volatile short int *)p);
u8 = vec_lvsl(1,(_101 *)p);
u8 = vec_lvsr(1,(const volatile short int *)p);
u8 = vec_lvsr(1,(_101 *)p);
u8 = vec_lvsl(1,(const short int *)p);
u8 = vec_lvsl(1,(_102 *)p);
u8 = vec_lvsr(1,(const short int *)p);
u8 = vec_lvsr(1,(_102 *)p);
s16 = vec_ld(1,(const short int *)p);
s16 = vec_ld(1,(_102 *)p);
s16 = vec_lde(1,(const short int *)p);
s16 = vec_lde(1,(_102 *)p);
s16 = vec_ldl(1,(const short int *)p);
s16 = vec_ldl(1,(_102 *)p);
vec_dst((const short int *)p,1,1);
vec_dstst((const short int *)p,1,1);
vec_dststt((const short int *)p,1,1);
vec_dstt((const short int *)p,1,1);
vec_dst((_102 *)p,1,1);
vec_dstst((_102 *)p,1,1);
vec_dststt((_102 *)p,1,1);
vec_dstt((_102 *)p,1,1);
u8 = vec_lvsl(1,( volatile short int *)p);
u8 = vec_lvsl(1,(_103 *)p);
u8 = vec_lvsr(1,( volatile short int *)p);
u8 = vec_lvsr(1,(_103 *)p);
u8 = vec_lvsl(1,( short int *)p);
u8 = vec_lvsl(1,(_104 *)p);
u8 = vec_lvsr(1,( short int *)p);
u8 = vec_lvsr(1,(_104 *)p);
s16 = vec_ld(1,( short int *)p);
s16 = vec_ld(1,(_104 *)p);
s16 = vec_lde(1,( short int *)p);
s16 = vec_lde(1,(_104 *)p);
s16 = vec_ldl(1,( short int *)p);
s16 = vec_ldl(1,(_104 *)p);
vec_dst(( short int *)p,1,1);
vec_dstst(( short int *)p,1,1);
vec_dststt(( short int *)p,1,1);
vec_dstt(( short int *)p,1,1);
vec_dst((_104 *)p,1,1);
vec_dstst((_104 *)p,1,1);
vec_dststt((_104 *)p,1,1);
vec_dstt((_104 *)p,1,1);
vec_st(s16,1,( short int *)p);
vec_st(s16,1,(_104 *)p);
vec_ste(s16,1,( short int *)p);
vec_ste(s16,1,(_104 *)p);
vec_stl(s16,1,( short int *)p);
vec_stl(s16,1,(_104 *)p);
u8 = vec_lvsl(1,(const volatile int *)p);
u8 = vec_lvsl(1,(_105 *)p);
u8 = vec_lvsr(1,(const volatile int *)p);
u8 = vec_lvsr(1,(_105 *)p);
u8 = vec_lvsl(1,(const int *)p);
u8 = vec_lvsl(1,(_106 *)p);
u8 = vec_lvsr(1,(const int *)p);
u8 = vec_lvsr(1,(_106 *)p);
s32 = vec_ld(1,(const int *)p);
s32 = vec_ld(1,(_106 *)p);
s32 = vec_lde(1,(const int *)p);
s32 = vec_lde(1,(_106 *)p);
s32 = vec_ldl(1,(const int *)p);
s32 = vec_ldl(1,(_106 *)p);
vec_dst((const int *)p,1,1);
vec_dstst((const int *)p,1,1);
vec_dststt((const int *)p,1,1);
vec_dstt((const int *)p,1,1);
vec_dst((_106 *)p,1,1);
vec_dstst((_106 *)p,1,1);
vec_dststt((_106 *)p,1,1);
vec_dstt((_106 *)p,1,1);
u8 = vec_lvsl(1,( volatile int *)p);
u8 = vec_lvsl(1,(_107 *)p);
u8 = vec_lvsr(1,( volatile int *)p);
u8 = vec_lvsr(1,(_107 *)p);
u8 = vec_lvsl(1,( int *)p);
u8 = vec_lvsl(1,(_108 *)p);
u8 = vec_lvsr(1,( int *)p);
u8 = vec_lvsr(1,(_108 *)p);
s32 = vec_ld(1,( int *)p);
s32 = vec_ld(1,(_108 *)p);
s32 = vec_lde(1,( int *)p);
s32 = vec_lde(1,(_108 *)p);
s32 = vec_ldl(1,( int *)p);
s32 = vec_ldl(1,(_108 *)p);
vec_dst(( int *)p,1,1);
vec_dstst(( int *)p,1,1);
vec_dststt(( int *)p,1,1);
vec_dstt(( int *)p,1,1);
vec_dst((_108 *)p,1,1);
vec_dstst((_108 *)p,1,1);
vec_dststt((_108 *)p,1,1);
vec_dstt((_108 *)p,1,1);
vec_st(s32,1,( int *)p);
vec_st(s32,1,(_108 *)p);
vec_ste(s32,1,( int *)p);
vec_ste(s32,1,(_108 *)p);
vec_stl(s32,1,( int *)p);
vec_stl(s32,1,(_108 *)p);
u8 = vec_lvsl(1,(const volatile int *)p);
u8 = vec_lvsl(1,(_109 *)p);
u8 = vec_lvsr(1,(const volatile int *)p);
u8 = vec_lvsr(1,(_109 *)p);
u8 = vec_lvsl(1,(const int *)p);
u8 = vec_lvsl(1,(_110 *)p);
u8 = vec_lvsr(1,(const int *)p);
u8 = vec_lvsr(1,(_110 *)p);
s32 = vec_ld(1,(const int *)p);
s32 = vec_ld(1,(_110 *)p);
s32 = vec_lde(1,(const int *)p);
s32 = vec_lde(1,(_110 *)p);
s32 = vec_ldl(1,(const int *)p);
s32 = vec_ldl(1,(_110 *)p);
vec_dst((const int *)p,1,1);
vec_dstst((const int *)p,1,1);
vec_dststt((const int *)p,1,1);
vec_dstt((const int *)p,1,1);
vec_dst((_110 *)p,1,1);
vec_dstst((_110 *)p,1,1);
vec_dststt((_110 *)p,1,1);
vec_dstt((_110 *)p,1,1);
u8 = vec_lvsl(1,( volatile int *)p);
u8 = vec_lvsl(1,(_111 *)p);
u8 = vec_lvsr(1,( volatile int *)p);
u8 = vec_lvsr(1,(_111 *)p);
u8 = vec_lvsl(1,( int *)p);
u8 = vec_lvsl(1,(_112 *)p);
u8 = vec_lvsr(1,( int *)p);
u8 = vec_lvsr(1,(_112 *)p);
s32 = vec_ld(1,( int *)p);
s32 = vec_ld(1,(_112 *)p);
s32 = vec_lde(1,( int *)p);
s32 = vec_lde(1,(_112 *)p);
s32 = vec_ldl(1,( int *)p);
s32 = vec_ldl(1,(_112 *)p);
vec_dst(( int *)p,1,1);
vec_dstst(( int *)p,1,1);
vec_dststt(( int *)p,1,1);
vec_dstt(( int *)p,1,1);
vec_dst((_112 *)p,1,1);
vec_dstst((_112 *)p,1,1);
vec_dststt((_112 *)p,1,1);
vec_dstt((_112 *)p,1,1);
vec_st(s32,1,( int *)p);
vec_st(s32,1,(_112 *)p);
vec_ste(s32,1,( int *)p);
vec_ste(s32,1,(_112 *)p);
vec_stl(s32,1,( int *)p);
vec_stl(s32,1,(_112 *)p);
u8 = vec_ld(1,(const vector unsigned char *)p);
u8 = vec_ld(1,(_114 *)p);
u8 = vec_ldl(1,(const vector unsigned char *)p);
u8 = vec_ldl(1,(_114 *)p);
vec_dst((const vector unsigned char *)p,1,1);
vec_dstst((const vector unsigned char *)p,1,1);
vec_dststt((const vector unsigned char *)p,1,1);
vec_dstt((const vector unsigned char *)p,1,1);
vec_dst((_114 *)p,1,1);
vec_dstst((_114 *)p,1,1);
vec_dststt((_114 *)p,1,1);
vec_dstt((_114 *)p,1,1);
u8 = vec_ld(1,( vector unsigned char *)p);
u8 = vec_ld(1,(_116 *)p);
u8 = vec_ldl(1,( vector unsigned char *)p);
u8 = vec_ldl(1,(_116 *)p);
vec_dst(( vector unsigned char *)p,1,1);
vec_dstst(( vector unsigned char *)p,1,1);
vec_dststt(( vector unsigned char *)p,1,1);
vec_dstt(( vector unsigned char *)p,1,1);
vec_dst((_116 *)p,1,1);
vec_dstst((_116 *)p,1,1);
vec_dststt((_116 *)p,1,1);
vec_dstt((_116 *)p,1,1);
vec_st(u8,1,( vector unsigned char *)p);
vec_st(u8,1,(_116 *)p);
vec_stl(u8,1,( vector unsigned char *)p);
vec_stl(u8,1,(_116 *)p);
u8 = vec_lvsl(1,(const volatile signed char *)p);
u8 = vec_lvsl(1,(_117 *)p);
u8 = vec_lvsr(1,(const volatile signed char *)p);
u8 = vec_lvsr(1,(_117 *)p);
u8 = vec_lvsl(1,(const signed char *)p);
u8 = vec_lvsl(1,(_118 *)p);
u8 = vec_lvsr(1,(const signed char *)p);
u8 = vec_lvsr(1,(_118 *)p);
s8 = vec_ld(1,(const signed char *)p);
s8 = vec_ld(1,(_118 *)p);
s8 = vec_lde(1,(const signed char *)p);
s8 = vec_lde(1,(_118 *)p);
s8 = vec_ldl(1,(const signed char *)p);
s8 = vec_ldl(1,(_118 *)p);
vec_dst((const signed char *)p,1,1);
vec_dstst((const signed char *)p,1,1);
vec_dststt((const signed char *)p,1,1);
vec_dstt((const signed char *)p,1,1);
vec_dst((_118 *)p,1,1);
vec_dstst((_118 *)p,1,1);
vec_dststt((_118 *)p,1,1);
vec_dstt((_118 *)p,1,1);
u8 = vec_lvsl(1,( volatile signed char *)p);
u8 = vec_lvsl(1,(_119 *)p);
u8 = vec_lvsr(1,( volatile signed char *)p);
u8 = vec_lvsr(1,(_119 *)p);
u8 = vec_lvsl(1,( signed char *)p);
u8 = vec_lvsl(1,(_120 *)p);
u8 = vec_lvsr(1,( signed char *)p);
u8 = vec_lvsr(1,(_120 *)p);
s8 = vec_ld(1,( signed char *)p);
s8 = vec_ld(1,(_120 *)p);
s8 = vec_lde(1,( signed char *)p);
s8 = vec_lde(1,(_120 *)p);
s8 = vec_ldl(1,( signed char *)p);
s8 = vec_ldl(1,(_120 *)p);
vec_dst(( signed char *)p,1,1);
vec_dstst(( signed char *)p,1,1);
vec_dststt(( signed char *)p,1,1);
vec_dstt(( signed char *)p,1,1);
vec_dst((_120 *)p,1,1);
vec_dstst((_120 *)p,1,1);
vec_dststt((_120 *)p,1,1);
vec_dstt((_120 *)p,1,1);
vec_st(s8,1,( signed char *)p);
vec_st(s8,1,(_120 *)p);
vec_ste(s8,1,( signed char *)p);
vec_ste(s8,1,(_120 *)p);
vec_stl(s8,1,( signed char *)p);
vec_stl(s8,1,(_120 *)p);
u8 = vec_lvsl(1,(const volatile float *)p);
u8 = vec_lvsl(1,(_121 *)p);
u8 = vec_lvsr(1,(const volatile float *)p);
u8 = vec_lvsr(1,(_121 *)p);
u8 = vec_lvsl(1,(const float *)p);
u8 = vec_lvsl(1,(_122 *)p);
u8 = vec_lvsr(1,(const float *)p);
u8 = vec_lvsr(1,(_122 *)p);
f32 = vec_ld(1,(const float *)p);
f32 = vec_ld(1,(_122 *)p);
f32 = vec_lde(1,(const float *)p);
f32 = vec_lde(1,(_122 *)p);
f32 = vec_ldl(1,(const float *)p);
f32 = vec_ldl(1,(_122 *)p);
vec_dst((const float *)p,1,1);
vec_dstst((const float *)p,1,1);
vec_dststt((const float *)p,1,1);
vec_dstt((const float *)p,1,1);
vec_dst((_122 *)p,1,1);
vec_dstst((_122 *)p,1,1);
vec_dststt((_122 *)p,1,1);
vec_dstt((_122 *)p,1,1);
u8 = vec_lvsl(1,( volatile float *)p);
u8 = vec_lvsl(1,(_123 *)p);
u8 = vec_lvsr(1,( volatile float *)p);
u8 = vec_lvsr(1,(_123 *)p);
u8 = vec_lvsl(1,( float *)p);
u8 = vec_lvsl(1,(_124 *)p);
u8 = vec_lvsr(1,( float *)p);
u8 = vec_lvsr(1,(_124 *)p);
f32 = vec_ld(1,( float *)p);
f32 = vec_ld(1,(_124 *)p);
f32 = vec_lde(1,( float *)p);
f32 = vec_lde(1,(_124 *)p);
f32 = vec_ldl(1,( float *)p);
f32 = vec_ldl(1,(_124 *)p);
vec_dst(( float *)p,1,1);
vec_dstst(( float *)p,1,1);
vec_dststt(( float *)p,1,1);
vec_dstt(( float *)p,1,1);
vec_dst((_124 *)p,1,1);
vec_dstst((_124 *)p,1,1);
vec_dststt((_124 *)p,1,1);
vec_dstt((_124 *)p,1,1);
vec_st(f32,1,( float *)p);
vec_st(f32,1,(_124 *)p);
vec_ste(f32,1,( float *)p);
vec_ste(f32,1,(_124 *)p);
vec_stl(f32,1,( float *)p);
vec_stl(f32,1,(_124 *)p);
}
| gpl-2.0 |
merbanan/linuxtv | drivers/video/backlight/lp8788_bl.c | 353 | 7941 | /*
* TI LP8788 MFD - backlight driver
*
* Copyright 2012 Texas Instruments
*
* Author: Milo(Woogyom) Kim <milo.kim@ti.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/backlight.h>
#include <linux/err.h>
#include <linux/mfd/lp8788.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/pwm.h>
#include <linux/slab.h>
/* Register address */
#define LP8788_BL_CONFIG 0x96
#define LP8788_BL_EN BIT(0)
#define LP8788_BL_PWM_INPUT_EN BIT(5)
#define LP8788_BL_FULLSCALE_SHIFT 2
#define LP8788_BL_DIM_MODE_SHIFT 1
#define LP8788_BL_PWM_POLARITY_SHIFT 6
#define LP8788_BL_BRIGHTNESS 0x97
#define LP8788_BL_RAMP 0x98
#define LP8788_BL_RAMP_RISE_SHIFT 4
#define MAX_BRIGHTNESS 127
#define DEFAULT_BL_NAME "lcd-backlight"
struct lp8788_bl_config {
enum lp8788_bl_ctrl_mode bl_mode;
enum lp8788_bl_dim_mode dim_mode;
enum lp8788_bl_full_scale_current full_scale;
enum lp8788_bl_ramp_step rise_time;
enum lp8788_bl_ramp_step fall_time;
enum pwm_polarity pwm_pol;
};
struct lp8788_bl {
struct lp8788 *lp;
struct backlight_device *bl_dev;
struct lp8788_backlight_platform_data *pdata;
enum lp8788_bl_ctrl_mode mode;
struct pwm_device *pwm;
};
static struct lp8788_bl_config default_bl_config = {
.bl_mode = LP8788_BL_REGISTER_ONLY,
.dim_mode = LP8788_DIM_EXPONENTIAL,
.full_scale = LP8788_FULLSCALE_1900uA,
.rise_time = LP8788_RAMP_8192us,
.fall_time = LP8788_RAMP_8192us,
.pwm_pol = PWM_POLARITY_NORMAL,
};
static inline bool is_brightness_ctrl_by_pwm(enum lp8788_bl_ctrl_mode mode)
{
return mode == LP8788_BL_COMB_PWM_BASED;
}
static inline bool is_brightness_ctrl_by_register(enum lp8788_bl_ctrl_mode mode)
{
return mode == LP8788_BL_REGISTER_ONLY ||
mode == LP8788_BL_COMB_REGISTER_BASED;
}
static int lp8788_backlight_configure(struct lp8788_bl *bl)
{
struct lp8788_backlight_platform_data *pdata = bl->pdata;
struct lp8788_bl_config *cfg = &default_bl_config;
int ret;
u8 val;
/*
* Update chip configuration if platform data exists,
* otherwise use the default settings.
*/
if (pdata) {
cfg->bl_mode = pdata->bl_mode;
cfg->dim_mode = pdata->dim_mode;
cfg->full_scale = pdata->full_scale;
cfg->rise_time = pdata->rise_time;
cfg->fall_time = pdata->fall_time;
cfg->pwm_pol = pdata->pwm_pol;
}
/* Brightness ramp up/down */
val = (cfg->rise_time << LP8788_BL_RAMP_RISE_SHIFT) | cfg->fall_time;
ret = lp8788_write_byte(bl->lp, LP8788_BL_RAMP, val);
if (ret)
return ret;
/* Fullscale current setting */
val = (cfg->full_scale << LP8788_BL_FULLSCALE_SHIFT) |
(cfg->dim_mode << LP8788_BL_DIM_MODE_SHIFT);
/* Brightness control mode */
switch (cfg->bl_mode) {
case LP8788_BL_REGISTER_ONLY:
val |= LP8788_BL_EN;
break;
case LP8788_BL_COMB_PWM_BASED:
case LP8788_BL_COMB_REGISTER_BASED:
val |= LP8788_BL_EN | LP8788_BL_PWM_INPUT_EN |
(cfg->pwm_pol << LP8788_BL_PWM_POLARITY_SHIFT);
break;
default:
dev_err(bl->lp->dev, "invalid mode: %d\n", cfg->bl_mode);
return -EINVAL;
}
bl->mode = cfg->bl_mode;
return lp8788_write_byte(bl->lp, LP8788_BL_CONFIG, val);
}
static void lp8788_pwm_ctrl(struct lp8788_bl *bl, int br, int max_br)
{
unsigned int period;
unsigned int duty;
struct device *dev;
struct pwm_device *pwm;
if (!bl->pdata)
return;
period = bl->pdata->period_ns;
duty = br * period / max_br;
dev = bl->lp->dev;
/* request PWM device with the consumer name */
if (!bl->pwm) {
pwm = devm_pwm_get(dev, LP8788_DEV_BACKLIGHT);
if (IS_ERR(pwm)) {
dev_err(dev, "can not get PWM device\n");
return;
}
bl->pwm = pwm;
}
pwm_config(bl->pwm, duty, period);
if (duty)
pwm_enable(bl->pwm);
else
pwm_disable(bl->pwm);
}
static int lp8788_bl_update_status(struct backlight_device *bl_dev)
{
struct lp8788_bl *bl = bl_get_data(bl_dev);
enum lp8788_bl_ctrl_mode mode = bl->mode;
if (bl_dev->props.state & BL_CORE_SUSPENDED)
bl_dev->props.brightness = 0;
if (is_brightness_ctrl_by_pwm(mode)) {
int brt = bl_dev->props.brightness;
int max = bl_dev->props.max_brightness;
lp8788_pwm_ctrl(bl, brt, max);
} else if (is_brightness_ctrl_by_register(mode)) {
u8 brt = bl_dev->props.brightness;
lp8788_write_byte(bl->lp, LP8788_BL_BRIGHTNESS, brt);
}
return 0;
}
static int lp8788_bl_get_brightness(struct backlight_device *bl_dev)
{
return bl_dev->props.brightness;
}
static const struct backlight_ops lp8788_bl_ops = {
.options = BL_CORE_SUSPENDRESUME,
.update_status = lp8788_bl_update_status,
.get_brightness = lp8788_bl_get_brightness,
};
static int lp8788_backlight_register(struct lp8788_bl *bl)
{
struct backlight_device *bl_dev;
struct backlight_properties props;
struct lp8788_backlight_platform_data *pdata = bl->pdata;
int init_brt;
char *name;
props.type = BACKLIGHT_PLATFORM;
props.max_brightness = MAX_BRIGHTNESS;
/* Initial brightness */
if (pdata)
init_brt = min_t(int, pdata->initial_brightness,
props.max_brightness);
else
init_brt = 0;
props.brightness = init_brt;
/* Backlight device name */
if (!pdata || !pdata->name)
name = DEFAULT_BL_NAME;
else
name = pdata->name;
bl_dev = backlight_device_register(name, bl->lp->dev, bl,
&lp8788_bl_ops, &props);
if (IS_ERR(bl_dev))
return PTR_ERR(bl_dev);
bl->bl_dev = bl_dev;
return 0;
}
static void lp8788_backlight_unregister(struct lp8788_bl *bl)
{
struct backlight_device *bl_dev = bl->bl_dev;
if (bl_dev)
backlight_device_unregister(bl_dev);
}
static ssize_t lp8788_get_bl_ctl_mode(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct lp8788_bl *bl = dev_get_drvdata(dev);
enum lp8788_bl_ctrl_mode mode = bl->mode;
char *strmode;
if (is_brightness_ctrl_by_pwm(mode))
strmode = "PWM based";
else if (is_brightness_ctrl_by_register(mode))
strmode = "Register based";
else
strmode = "Invalid mode";
return scnprintf(buf, PAGE_SIZE, "%s\n", strmode);
}
static DEVICE_ATTR(bl_ctl_mode, S_IRUGO, lp8788_get_bl_ctl_mode, NULL);
static struct attribute *lp8788_attributes[] = {
&dev_attr_bl_ctl_mode.attr,
NULL,
};
static const struct attribute_group lp8788_attr_group = {
.attrs = lp8788_attributes,
};
static int lp8788_backlight_probe(struct platform_device *pdev)
{
struct lp8788 *lp = dev_get_drvdata(pdev->dev.parent);
struct lp8788_bl *bl;
int ret;
bl = devm_kzalloc(lp->dev, sizeof(struct lp8788_bl), GFP_KERNEL);
if (!bl)
return -ENOMEM;
bl->lp = lp;
if (lp->pdata)
bl->pdata = lp->pdata->bl_pdata;
platform_set_drvdata(pdev, bl);
ret = lp8788_backlight_configure(bl);
if (ret) {
dev_err(lp->dev, "backlight config err: %d\n", ret);
goto err_dev;
}
ret = lp8788_backlight_register(bl);
if (ret) {
dev_err(lp->dev, "register backlight err: %d\n", ret);
goto err_dev;
}
ret = sysfs_create_group(&pdev->dev.kobj, &lp8788_attr_group);
if (ret) {
dev_err(lp->dev, "register sysfs err: %d\n", ret);
goto err_sysfs;
}
backlight_update_status(bl->bl_dev);
return 0;
err_sysfs:
lp8788_backlight_unregister(bl);
err_dev:
return ret;
}
static int lp8788_backlight_remove(struct platform_device *pdev)
{
struct lp8788_bl *bl = platform_get_drvdata(pdev);
struct backlight_device *bl_dev = bl->bl_dev;
bl_dev->props.brightness = 0;
backlight_update_status(bl_dev);
sysfs_remove_group(&pdev->dev.kobj, &lp8788_attr_group);
lp8788_backlight_unregister(bl);
return 0;
}
static struct platform_driver lp8788_bl_driver = {
.probe = lp8788_backlight_probe,
.remove = lp8788_backlight_remove,
.driver = {
.name = LP8788_DEV_BACKLIGHT,
.owner = THIS_MODULE,
},
};
module_platform_driver(lp8788_bl_driver);
MODULE_DESCRIPTION("Texas Instruments LP8788 Backlight Driver");
MODULE_AUTHOR("Milo Kim");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:lp8788-backlight");
| gpl-2.0 |
TeamRegular/android_kernel_nvidia_shieldtablet | drivers/scsi/hpsa.c | 865 | 148532 | /*
* Disk Array driver for HP Smart Array SAS controllers
* Copyright 2000, 2009 Hewlett-Packard Development Company, L.P.
*
* 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, GOOD TITLE or
* NON INFRINGEMENT. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Questions/Comments/Bugfixes to iss_storagedev@hp.com
*
*/
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/types.h>
#include <linux/pci.h>
#include <linux/pci-aspm.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/fs.h>
#include <linux/timer.h>
#include <linux/seq_file.h>
#include <linux/init.h>
#include <linux/spinlock.h>
#include <linux/compat.h>
#include <linux/blktrace_api.h>
#include <linux/uaccess.h>
#include <linux/io.h>
#include <linux/dma-mapping.h>
#include <linux/completion.h>
#include <linux/moduleparam.h>
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_tcq.h>
#include <linux/cciss_ioctl.h>
#include <linux/string.h>
#include <linux/bitmap.h>
#include <linux/atomic.h>
#include <linux/kthread.h>
#include <linux/jiffies.h>
#include "hpsa_cmd.h"
#include "hpsa.h"
/* HPSA_DRIVER_VERSION must be 3 byte values (0-255) separated by '.' */
#define HPSA_DRIVER_VERSION "2.0.2-1"
#define DRIVER_NAME "HP HPSA Driver (v " HPSA_DRIVER_VERSION ")"
#define HPSA "hpsa"
/* How long to wait (in milliseconds) for board to go into simple mode */
#define MAX_CONFIG_WAIT 30000
#define MAX_IOCTL_CONFIG_WAIT 1000
/*define how many times we will try a command because of bus resets */
#define MAX_CMD_RETRIES 3
/* Embedded module documentation macros - see modules.h */
MODULE_AUTHOR("Hewlett-Packard Company");
MODULE_DESCRIPTION("Driver for HP Smart Array Controller version " \
HPSA_DRIVER_VERSION);
MODULE_SUPPORTED_DEVICE("HP Smart Array Controllers");
MODULE_VERSION(HPSA_DRIVER_VERSION);
MODULE_LICENSE("GPL");
static int hpsa_allow_any;
module_param(hpsa_allow_any, int, S_IRUGO|S_IWUSR);
MODULE_PARM_DESC(hpsa_allow_any,
"Allow hpsa driver to access unknown HP Smart Array hardware");
static int hpsa_simple_mode;
module_param(hpsa_simple_mode, int, S_IRUGO|S_IWUSR);
MODULE_PARM_DESC(hpsa_simple_mode,
"Use 'simple mode' rather than 'performant mode'");
/* define the PCI info for the cards we can control */
static const struct pci_device_id hpsa_pci_device_id[] = {
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSE, 0x103C, 0x3241},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSE, 0x103C, 0x3243},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSE, 0x103C, 0x3245},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSE, 0x103C, 0x3247},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSE, 0x103C, 0x3249},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSE, 0x103C, 0x324a},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSE, 0x103C, 0x324b},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSE, 0x103C, 0x3233},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSF, 0x103C, 0x3350},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSF, 0x103C, 0x3351},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSF, 0x103C, 0x3352},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSF, 0x103C, 0x3353},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSF, 0x103C, 0x3354},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSF, 0x103C, 0x3355},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSF, 0x103C, 0x3356},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSH, 0x103C, 0x1920},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSH, 0x103C, 0x1921},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSH, 0x103C, 0x1922},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSH, 0x103C, 0x1923},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSH, 0x103C, 0x1924},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSH, 0x103C, 0x1925},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSH, 0x103C, 0x1926},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSH, 0x103C, 0x1928},
{PCI_VENDOR_ID_HP, PCI_DEVICE_ID_HP_CISSF, 0x103C, 0x334d},
{PCI_VENDOR_ID_HP, PCI_ANY_ID, PCI_ANY_ID, PCI_ANY_ID,
PCI_CLASS_STORAGE_RAID << 8, 0xffff << 8, 0},
{0,}
};
MODULE_DEVICE_TABLE(pci, hpsa_pci_device_id);
/* board_id = Subsystem Device ID & Vendor ID
* product = Marketing Name for the board
* access = Address of the struct of function pointers
*/
static struct board_type products[] = {
{0x3241103C, "Smart Array P212", &SA5_access},
{0x3243103C, "Smart Array P410", &SA5_access},
{0x3245103C, "Smart Array P410i", &SA5_access},
{0x3247103C, "Smart Array P411", &SA5_access},
{0x3249103C, "Smart Array P812", &SA5_access},
{0x324a103C, "Smart Array P712m", &SA5_access},
{0x324b103C, "Smart Array P711m", &SA5_access},
{0x3350103C, "Smart Array P222", &SA5_access},
{0x3351103C, "Smart Array P420", &SA5_access},
{0x3352103C, "Smart Array P421", &SA5_access},
{0x3353103C, "Smart Array P822", &SA5_access},
{0x3354103C, "Smart Array P420i", &SA5_access},
{0x3355103C, "Smart Array P220i", &SA5_access},
{0x3356103C, "Smart Array P721m", &SA5_access},
{0x1920103C, "Smart Array", &SA5_access},
{0x1921103C, "Smart Array", &SA5_access},
{0x1922103C, "Smart Array", &SA5_access},
{0x1923103C, "Smart Array", &SA5_access},
{0x1924103C, "Smart Array", &SA5_access},
{0x1925103C, "Smart Array", &SA5_access},
{0x1926103C, "Smart Array", &SA5_access},
{0x1928103C, "Smart Array", &SA5_access},
{0x334d103C, "Smart Array P822se", &SA5_access},
{0xFFFF103C, "Unknown Smart Array", &SA5_access},
};
static int number_of_controllers;
static struct list_head hpsa_ctlr_list = LIST_HEAD_INIT(hpsa_ctlr_list);
static spinlock_t lockup_detector_lock;
static struct task_struct *hpsa_lockup_detector;
static irqreturn_t do_hpsa_intr_intx(int irq, void *dev_id);
static irqreturn_t do_hpsa_intr_msi(int irq, void *dev_id);
static int hpsa_ioctl(struct scsi_device *dev, int cmd, void *arg);
static void start_io(struct ctlr_info *h);
#ifdef CONFIG_COMPAT
static int hpsa_compat_ioctl(struct scsi_device *dev, int cmd, void *arg);
#endif
static void cmd_free(struct ctlr_info *h, struct CommandList *c);
static void cmd_special_free(struct ctlr_info *h, struct CommandList *c);
static struct CommandList *cmd_alloc(struct ctlr_info *h);
static struct CommandList *cmd_special_alloc(struct ctlr_info *h);
static int fill_cmd(struct CommandList *c, u8 cmd, struct ctlr_info *h,
void *buff, size_t size, u8 page_code, unsigned char *scsi3addr,
int cmd_type);
static int hpsa_scsi_queue_command(struct Scsi_Host *h, struct scsi_cmnd *cmd);
static void hpsa_scan_start(struct Scsi_Host *);
static int hpsa_scan_finished(struct Scsi_Host *sh,
unsigned long elapsed_time);
static int hpsa_change_queue_depth(struct scsi_device *sdev,
int qdepth, int reason);
static int hpsa_eh_device_reset_handler(struct scsi_cmnd *scsicmd);
static int hpsa_eh_abort_handler(struct scsi_cmnd *scsicmd);
static int hpsa_slave_alloc(struct scsi_device *sdev);
static void hpsa_slave_destroy(struct scsi_device *sdev);
static void hpsa_update_scsi_devices(struct ctlr_info *h, int hostno);
static int check_for_unit_attention(struct ctlr_info *h,
struct CommandList *c);
static void check_ioctl_unit_attention(struct ctlr_info *h,
struct CommandList *c);
/* performant mode helper functions */
static void calc_bucket_map(int *bucket, int num_buckets,
int nsgs, int *bucket_map);
static void hpsa_put_ctlr_into_performant_mode(struct ctlr_info *h);
static inline u32 next_command(struct ctlr_info *h, u8 q);
static int hpsa_find_cfg_addrs(struct pci_dev *pdev, void __iomem *vaddr,
u32 *cfg_base_addr, u64 *cfg_base_addr_index,
u64 *cfg_offset);
static int hpsa_pci_find_memory_BAR(struct pci_dev *pdev,
unsigned long *memory_bar);
static int hpsa_lookup_board_id(struct pci_dev *pdev, u32 *board_id);
static int hpsa_wait_for_board_state(struct pci_dev *pdev, void __iomem *vaddr,
int wait_for_ready);
static inline void finish_cmd(struct CommandList *c);
#define BOARD_NOT_READY 0
#define BOARD_READY 1
static inline struct ctlr_info *sdev_to_hba(struct scsi_device *sdev)
{
unsigned long *priv = shost_priv(sdev->host);
return (struct ctlr_info *) *priv;
}
static inline struct ctlr_info *shost_to_hba(struct Scsi_Host *sh)
{
unsigned long *priv = shost_priv(sh);
return (struct ctlr_info *) *priv;
}
static int check_for_unit_attention(struct ctlr_info *h,
struct CommandList *c)
{
if (c->err_info->SenseInfo[2] != UNIT_ATTENTION)
return 0;
switch (c->err_info->SenseInfo[12]) {
case STATE_CHANGED:
dev_warn(&h->pdev->dev, HPSA "%d: a state change "
"detected, command retried\n", h->ctlr);
break;
case LUN_FAILED:
dev_warn(&h->pdev->dev, HPSA "%d: LUN failure "
"detected, action required\n", h->ctlr);
break;
case REPORT_LUNS_CHANGED:
dev_warn(&h->pdev->dev, HPSA "%d: report LUN data "
"changed, action required\n", h->ctlr);
/*
* Note: this REPORT_LUNS_CHANGED condition only occurs on the external
* target (array) devices.
*/
break;
case POWER_OR_RESET:
dev_warn(&h->pdev->dev, HPSA "%d: a power on "
"or device reset detected\n", h->ctlr);
break;
case UNIT_ATTENTION_CLEARED:
dev_warn(&h->pdev->dev, HPSA "%d: unit attention "
"cleared by another initiator\n", h->ctlr);
break;
default:
dev_warn(&h->pdev->dev, HPSA "%d: unknown "
"unit attention detected\n", h->ctlr);
break;
}
return 1;
}
static int check_for_busy(struct ctlr_info *h, struct CommandList *c)
{
if (c->err_info->CommandStatus != CMD_TARGET_STATUS ||
(c->err_info->ScsiStatus != SAM_STAT_BUSY &&
c->err_info->ScsiStatus != SAM_STAT_TASK_SET_FULL))
return 0;
dev_warn(&h->pdev->dev, HPSA "device busy");
return 1;
}
static ssize_t host_store_rescan(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct ctlr_info *h;
struct Scsi_Host *shost = class_to_shost(dev);
h = shost_to_hba(shost);
hpsa_scan_start(h->scsi_host);
return count;
}
static ssize_t host_show_firmware_revision(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct ctlr_info *h;
struct Scsi_Host *shost = class_to_shost(dev);
unsigned char *fwrev;
h = shost_to_hba(shost);
if (!h->hba_inquiry_data)
return 0;
fwrev = &h->hba_inquiry_data[32];
return snprintf(buf, 20, "%c%c%c%c\n",
fwrev[0], fwrev[1], fwrev[2], fwrev[3]);
}
static ssize_t host_show_commands_outstanding(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct Scsi_Host *shost = class_to_shost(dev);
struct ctlr_info *h = shost_to_hba(shost);
return snprintf(buf, 20, "%d\n", h->commands_outstanding);
}
static ssize_t host_show_transport_mode(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct ctlr_info *h;
struct Scsi_Host *shost = class_to_shost(dev);
h = shost_to_hba(shost);
return snprintf(buf, 20, "%s\n",
h->transMethod & CFGTBL_Trans_Performant ?
"performant" : "simple");
}
/* List of controllers which cannot be hard reset on kexec with reset_devices */
static u32 unresettable_controller[] = {
0x324a103C, /* Smart Array P712m */
0x324b103C, /* SmartArray P711m */
0x3223103C, /* Smart Array P800 */
0x3234103C, /* Smart Array P400 */
0x3235103C, /* Smart Array P400i */
0x3211103C, /* Smart Array E200i */
0x3212103C, /* Smart Array E200 */
0x3213103C, /* Smart Array E200i */
0x3214103C, /* Smart Array E200i */
0x3215103C, /* Smart Array E200i */
0x3237103C, /* Smart Array E500 */
0x323D103C, /* Smart Array P700m */
0x40800E11, /* Smart Array 5i */
0x409C0E11, /* Smart Array 6400 */
0x409D0E11, /* Smart Array 6400 EM */
0x40700E11, /* Smart Array 5300 */
0x40820E11, /* Smart Array 532 */
0x40830E11, /* Smart Array 5312 */
0x409A0E11, /* Smart Array 641 */
0x409B0E11, /* Smart Array 642 */
0x40910E11, /* Smart Array 6i */
};
/* List of controllers which cannot even be soft reset */
static u32 soft_unresettable_controller[] = {
0x40800E11, /* Smart Array 5i */
0x40700E11, /* Smart Array 5300 */
0x40820E11, /* Smart Array 532 */
0x40830E11, /* Smart Array 5312 */
0x409A0E11, /* Smart Array 641 */
0x409B0E11, /* Smart Array 642 */
0x40910E11, /* Smart Array 6i */
/* Exclude 640x boards. These are two pci devices in one slot
* which share a battery backed cache module. One controls the
* cache, the other accesses the cache through the one that controls
* it. If we reset the one controlling the cache, the other will
* likely not be happy. Just forbid resetting this conjoined mess.
* The 640x isn't really supported by hpsa anyway.
*/
0x409C0E11, /* Smart Array 6400 */
0x409D0E11, /* Smart Array 6400 EM */
};
static int ctlr_is_hard_resettable(u32 board_id)
{
int i;
for (i = 0; i < ARRAY_SIZE(unresettable_controller); i++)
if (unresettable_controller[i] == board_id)
return 0;
return 1;
}
static int ctlr_is_soft_resettable(u32 board_id)
{
int i;
for (i = 0; i < ARRAY_SIZE(soft_unresettable_controller); i++)
if (soft_unresettable_controller[i] == board_id)
return 0;
return 1;
}
static int ctlr_is_resettable(u32 board_id)
{
return ctlr_is_hard_resettable(board_id) ||
ctlr_is_soft_resettable(board_id);
}
static ssize_t host_show_resettable(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct ctlr_info *h;
struct Scsi_Host *shost = class_to_shost(dev);
h = shost_to_hba(shost);
return snprintf(buf, 20, "%d\n", ctlr_is_resettable(h->board_id));
}
static inline int is_logical_dev_addr_mode(unsigned char scsi3addr[])
{
return (scsi3addr[3] & 0xC0) == 0x40;
}
static const char *raid_label[] = { "0", "4", "1(1+0)", "5", "5+1", "ADG",
"1(ADM)", "UNKNOWN"
};
#define RAID_UNKNOWN (ARRAY_SIZE(raid_label) - 1)
static ssize_t raid_level_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
ssize_t l = 0;
unsigned char rlevel;
struct ctlr_info *h;
struct scsi_device *sdev;
struct hpsa_scsi_dev_t *hdev;
unsigned long flags;
sdev = to_scsi_device(dev);
h = sdev_to_hba(sdev);
spin_lock_irqsave(&h->lock, flags);
hdev = sdev->hostdata;
if (!hdev) {
spin_unlock_irqrestore(&h->lock, flags);
return -ENODEV;
}
/* Is this even a logical drive? */
if (!is_logical_dev_addr_mode(hdev->scsi3addr)) {
spin_unlock_irqrestore(&h->lock, flags);
l = snprintf(buf, PAGE_SIZE, "N/A\n");
return l;
}
rlevel = hdev->raid_level;
spin_unlock_irqrestore(&h->lock, flags);
if (rlevel > RAID_UNKNOWN)
rlevel = RAID_UNKNOWN;
l = snprintf(buf, PAGE_SIZE, "RAID %s\n", raid_label[rlevel]);
return l;
}
static ssize_t lunid_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct ctlr_info *h;
struct scsi_device *sdev;
struct hpsa_scsi_dev_t *hdev;
unsigned long flags;
unsigned char lunid[8];
sdev = to_scsi_device(dev);
h = sdev_to_hba(sdev);
spin_lock_irqsave(&h->lock, flags);
hdev = sdev->hostdata;
if (!hdev) {
spin_unlock_irqrestore(&h->lock, flags);
return -ENODEV;
}
memcpy(lunid, hdev->scsi3addr, sizeof(lunid));
spin_unlock_irqrestore(&h->lock, flags);
return snprintf(buf, 20, "0x%02x%02x%02x%02x%02x%02x%02x%02x\n",
lunid[0], lunid[1], lunid[2], lunid[3],
lunid[4], lunid[5], lunid[6], lunid[7]);
}
static ssize_t unique_id_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct ctlr_info *h;
struct scsi_device *sdev;
struct hpsa_scsi_dev_t *hdev;
unsigned long flags;
unsigned char sn[16];
sdev = to_scsi_device(dev);
h = sdev_to_hba(sdev);
spin_lock_irqsave(&h->lock, flags);
hdev = sdev->hostdata;
if (!hdev) {
spin_unlock_irqrestore(&h->lock, flags);
return -ENODEV;
}
memcpy(sn, hdev->device_id, sizeof(sn));
spin_unlock_irqrestore(&h->lock, flags);
return snprintf(buf, 16 * 2 + 2,
"%02X%02X%02X%02X%02X%02X%02X%02X"
"%02X%02X%02X%02X%02X%02X%02X%02X\n",
sn[0], sn[1], sn[2], sn[3],
sn[4], sn[5], sn[6], sn[7],
sn[8], sn[9], sn[10], sn[11],
sn[12], sn[13], sn[14], sn[15]);
}
static DEVICE_ATTR(raid_level, S_IRUGO, raid_level_show, NULL);
static DEVICE_ATTR(lunid, S_IRUGO, lunid_show, NULL);
static DEVICE_ATTR(unique_id, S_IRUGO, unique_id_show, NULL);
static DEVICE_ATTR(rescan, S_IWUSR, NULL, host_store_rescan);
static DEVICE_ATTR(firmware_revision, S_IRUGO,
host_show_firmware_revision, NULL);
static DEVICE_ATTR(commands_outstanding, S_IRUGO,
host_show_commands_outstanding, NULL);
static DEVICE_ATTR(transport_mode, S_IRUGO,
host_show_transport_mode, NULL);
static DEVICE_ATTR(resettable, S_IRUGO,
host_show_resettable, NULL);
static struct device_attribute *hpsa_sdev_attrs[] = {
&dev_attr_raid_level,
&dev_attr_lunid,
&dev_attr_unique_id,
NULL,
};
static struct device_attribute *hpsa_shost_attrs[] = {
&dev_attr_rescan,
&dev_attr_firmware_revision,
&dev_attr_commands_outstanding,
&dev_attr_transport_mode,
&dev_attr_resettable,
NULL,
};
static struct scsi_host_template hpsa_driver_template = {
.module = THIS_MODULE,
.name = HPSA,
.proc_name = HPSA,
.queuecommand = hpsa_scsi_queue_command,
.scan_start = hpsa_scan_start,
.scan_finished = hpsa_scan_finished,
.change_queue_depth = hpsa_change_queue_depth,
.this_id = -1,
.use_clustering = ENABLE_CLUSTERING,
.eh_abort_handler = hpsa_eh_abort_handler,
.eh_device_reset_handler = hpsa_eh_device_reset_handler,
.ioctl = hpsa_ioctl,
.slave_alloc = hpsa_slave_alloc,
.slave_destroy = hpsa_slave_destroy,
#ifdef CONFIG_COMPAT
.compat_ioctl = hpsa_compat_ioctl,
#endif
.sdev_attrs = hpsa_sdev_attrs,
.shost_attrs = hpsa_shost_attrs,
.max_sectors = 8192,
.no_write_same = 1,
};
/* Enqueuing and dequeuing functions for cmdlists. */
static inline void addQ(struct list_head *list, struct CommandList *c)
{
list_add_tail(&c->list, list);
}
static inline u32 next_command(struct ctlr_info *h, u8 q)
{
u32 a;
struct reply_pool *rq = &h->reply_queue[q];
unsigned long flags;
if (unlikely(!(h->transMethod & CFGTBL_Trans_Performant)))
return h->access.command_completed(h, q);
if ((rq->head[rq->current_entry] & 1) == rq->wraparound) {
a = rq->head[rq->current_entry];
rq->current_entry++;
spin_lock_irqsave(&h->lock, flags);
h->commands_outstanding--;
spin_unlock_irqrestore(&h->lock, flags);
} else {
a = FIFO_EMPTY;
}
/* Check for wraparound */
if (rq->current_entry == h->max_commands) {
rq->current_entry = 0;
rq->wraparound ^= 1;
}
return a;
}
/* set_performant_mode: Modify the tag for cciss performant
* set bit 0 for pull model, bits 3-1 for block fetch
* register number
*/
static void set_performant_mode(struct ctlr_info *h, struct CommandList *c)
{
if (likely(h->transMethod & CFGTBL_Trans_Performant)) {
c->busaddr |= 1 | (h->blockFetchTable[c->Header.SGList] << 1);
if (likely(h->msix_vector))
c->Header.ReplyQueue =
smp_processor_id() % h->nreply_queues;
}
}
static int is_firmware_flash_cmd(u8 *cdb)
{
return cdb[0] == BMIC_WRITE && cdb[6] == BMIC_FLASH_FIRMWARE;
}
/*
* During firmware flash, the heartbeat register may not update as frequently
* as it should. So we dial down lockup detection during firmware flash. and
* dial it back up when firmware flash completes.
*/
#define HEARTBEAT_SAMPLE_INTERVAL_DURING_FLASH (240 * HZ)
#define HEARTBEAT_SAMPLE_INTERVAL (30 * HZ)
static void dial_down_lockup_detection_during_fw_flash(struct ctlr_info *h,
struct CommandList *c)
{
if (!is_firmware_flash_cmd(c->Request.CDB))
return;
atomic_inc(&h->firmware_flash_in_progress);
h->heartbeat_sample_interval = HEARTBEAT_SAMPLE_INTERVAL_DURING_FLASH;
}
static void dial_up_lockup_detection_on_fw_flash_complete(struct ctlr_info *h,
struct CommandList *c)
{
if (is_firmware_flash_cmd(c->Request.CDB) &&
atomic_dec_and_test(&h->firmware_flash_in_progress))
h->heartbeat_sample_interval = HEARTBEAT_SAMPLE_INTERVAL;
}
static void enqueue_cmd_and_start_io(struct ctlr_info *h,
struct CommandList *c)
{
unsigned long flags;
set_performant_mode(h, c);
dial_down_lockup_detection_during_fw_flash(h, c);
spin_lock_irqsave(&h->lock, flags);
addQ(&h->reqQ, c);
h->Qdepth++;
spin_unlock_irqrestore(&h->lock, flags);
start_io(h);
}
static inline void removeQ(struct CommandList *c)
{
if (WARN_ON(list_empty(&c->list)))
return;
list_del_init(&c->list);
}
static inline int is_hba_lunid(unsigned char scsi3addr[])
{
return memcmp(scsi3addr, RAID_CTLR_LUNID, 8) == 0;
}
static inline int is_scsi_rev_5(struct ctlr_info *h)
{
if (!h->hba_inquiry_data)
return 0;
if ((h->hba_inquiry_data[2] & 0x07) == 5)
return 1;
return 0;
}
static int hpsa_find_target_lun(struct ctlr_info *h,
unsigned char scsi3addr[], int bus, int *target, int *lun)
{
/* finds an unused bus, target, lun for a new physical device
* assumes h->devlock is held
*/
int i, found = 0;
DECLARE_BITMAP(lun_taken, HPSA_MAX_DEVICES);
bitmap_zero(lun_taken, HPSA_MAX_DEVICES);
for (i = 0; i < h->ndevices; i++) {
if (h->dev[i]->bus == bus && h->dev[i]->target != -1)
__set_bit(h->dev[i]->target, lun_taken);
}
i = find_first_zero_bit(lun_taken, HPSA_MAX_DEVICES);
if (i < HPSA_MAX_DEVICES) {
/* *bus = 1; */
*target = i;
*lun = 0;
found = 1;
}
return !found;
}
/* Add an entry into h->dev[] array. */
static int hpsa_scsi_add_entry(struct ctlr_info *h, int hostno,
struct hpsa_scsi_dev_t *device,
struct hpsa_scsi_dev_t *added[], int *nadded)
{
/* assumes h->devlock is held */
int n = h->ndevices;
int i;
unsigned char addr1[8], addr2[8];
struct hpsa_scsi_dev_t *sd;
if (n >= HPSA_MAX_DEVICES) {
dev_err(&h->pdev->dev, "too many devices, some will be "
"inaccessible.\n");
return -1;
}
/* physical devices do not have lun or target assigned until now. */
if (device->lun != -1)
/* Logical device, lun is already assigned. */
goto lun_assigned;
/* If this device a non-zero lun of a multi-lun device
* byte 4 of the 8-byte LUN addr will contain the logical
* unit no, zero otherise.
*/
if (device->scsi3addr[4] == 0) {
/* This is not a non-zero lun of a multi-lun device */
if (hpsa_find_target_lun(h, device->scsi3addr,
device->bus, &device->target, &device->lun) != 0)
return -1;
goto lun_assigned;
}
/* This is a non-zero lun of a multi-lun device.
* Search through our list and find the device which
* has the same 8 byte LUN address, excepting byte 4.
* Assign the same bus and target for this new LUN.
* Use the logical unit number from the firmware.
*/
memcpy(addr1, device->scsi3addr, 8);
addr1[4] = 0;
for (i = 0; i < n; i++) {
sd = h->dev[i];
memcpy(addr2, sd->scsi3addr, 8);
addr2[4] = 0;
/* differ only in byte 4? */
if (memcmp(addr1, addr2, 8) == 0) {
device->bus = sd->bus;
device->target = sd->target;
device->lun = device->scsi3addr[4];
break;
}
}
if (device->lun == -1) {
dev_warn(&h->pdev->dev, "physical device with no LUN=0,"
" suspect firmware bug or unsupported hardware "
"configuration.\n");
return -1;
}
lun_assigned:
h->dev[n] = device;
h->ndevices++;
added[*nadded] = device;
(*nadded)++;
/* initially, (before registering with scsi layer) we don't
* know our hostno and we don't want to print anything first
* time anyway (the scsi layer's inquiries will show that info)
*/
/* if (hostno != -1) */
dev_info(&h->pdev->dev, "%s device c%db%dt%dl%d added.\n",
scsi_device_type(device->devtype), hostno,
device->bus, device->target, device->lun);
return 0;
}
/* Update an entry in h->dev[] array. */
static void hpsa_scsi_update_entry(struct ctlr_info *h, int hostno,
int entry, struct hpsa_scsi_dev_t *new_entry)
{
/* assumes h->devlock is held */
BUG_ON(entry < 0 || entry >= HPSA_MAX_DEVICES);
/* Raid level changed. */
h->dev[entry]->raid_level = new_entry->raid_level;
dev_info(&h->pdev->dev, "%s device c%db%dt%dl%d updated.\n",
scsi_device_type(new_entry->devtype), hostno, new_entry->bus,
new_entry->target, new_entry->lun);
}
/* Replace an entry from h->dev[] array. */
static void hpsa_scsi_replace_entry(struct ctlr_info *h, int hostno,
int entry, struct hpsa_scsi_dev_t *new_entry,
struct hpsa_scsi_dev_t *added[], int *nadded,
struct hpsa_scsi_dev_t *removed[], int *nremoved)
{
/* assumes h->devlock is held */
BUG_ON(entry < 0 || entry >= HPSA_MAX_DEVICES);
removed[*nremoved] = h->dev[entry];
(*nremoved)++;
/*
* New physical devices won't have target/lun assigned yet
* so we need to preserve the values in the slot we are replacing.
*/
if (new_entry->target == -1) {
new_entry->target = h->dev[entry]->target;
new_entry->lun = h->dev[entry]->lun;
}
h->dev[entry] = new_entry;
added[*nadded] = new_entry;
(*nadded)++;
dev_info(&h->pdev->dev, "%s device c%db%dt%dl%d changed.\n",
scsi_device_type(new_entry->devtype), hostno, new_entry->bus,
new_entry->target, new_entry->lun);
}
/* Remove an entry from h->dev[] array. */
static void hpsa_scsi_remove_entry(struct ctlr_info *h, int hostno, int entry,
struct hpsa_scsi_dev_t *removed[], int *nremoved)
{
/* assumes h->devlock is held */
int i;
struct hpsa_scsi_dev_t *sd;
BUG_ON(entry < 0 || entry >= HPSA_MAX_DEVICES);
sd = h->dev[entry];
removed[*nremoved] = h->dev[entry];
(*nremoved)++;
for (i = entry; i < h->ndevices-1; i++)
h->dev[i] = h->dev[i+1];
h->ndevices--;
dev_info(&h->pdev->dev, "%s device c%db%dt%dl%d removed.\n",
scsi_device_type(sd->devtype), hostno, sd->bus, sd->target,
sd->lun);
}
#define SCSI3ADDR_EQ(a, b) ( \
(a)[7] == (b)[7] && \
(a)[6] == (b)[6] && \
(a)[5] == (b)[5] && \
(a)[4] == (b)[4] && \
(a)[3] == (b)[3] && \
(a)[2] == (b)[2] && \
(a)[1] == (b)[1] && \
(a)[0] == (b)[0])
static void fixup_botched_add(struct ctlr_info *h,
struct hpsa_scsi_dev_t *added)
{
/* called when scsi_add_device fails in order to re-adjust
* h->dev[] to match the mid layer's view.
*/
unsigned long flags;
int i, j;
spin_lock_irqsave(&h->lock, flags);
for (i = 0; i < h->ndevices; i++) {
if (h->dev[i] == added) {
for (j = i; j < h->ndevices-1; j++)
h->dev[j] = h->dev[j+1];
h->ndevices--;
break;
}
}
spin_unlock_irqrestore(&h->lock, flags);
kfree(added);
}
static inline int device_is_the_same(struct hpsa_scsi_dev_t *dev1,
struct hpsa_scsi_dev_t *dev2)
{
/* we compare everything except lun and target as these
* are not yet assigned. Compare parts likely
* to differ first
*/
if (memcmp(dev1->scsi3addr, dev2->scsi3addr,
sizeof(dev1->scsi3addr)) != 0)
return 0;
if (memcmp(dev1->device_id, dev2->device_id,
sizeof(dev1->device_id)) != 0)
return 0;
if (memcmp(dev1->model, dev2->model, sizeof(dev1->model)) != 0)
return 0;
if (memcmp(dev1->vendor, dev2->vendor, sizeof(dev1->vendor)) != 0)
return 0;
if (dev1->devtype != dev2->devtype)
return 0;
if (dev1->bus != dev2->bus)
return 0;
return 1;
}
static inline int device_updated(struct hpsa_scsi_dev_t *dev1,
struct hpsa_scsi_dev_t *dev2)
{
/* Device attributes that can change, but don't mean
* that the device is a different device, nor that the OS
* needs to be told anything about the change.
*/
if (dev1->raid_level != dev2->raid_level)
return 1;
return 0;
}
/* Find needle in haystack. If exact match found, return DEVICE_SAME,
* and return needle location in *index. If scsi3addr matches, but not
* vendor, model, serial num, etc. return DEVICE_CHANGED, and return needle
* location in *index.
* In the case of a minor device attribute change, such as RAID level, just
* return DEVICE_UPDATED, along with the updated device's location in index.
* If needle not found, return DEVICE_NOT_FOUND.
*/
static int hpsa_scsi_find_entry(struct hpsa_scsi_dev_t *needle,
struct hpsa_scsi_dev_t *haystack[], int haystack_size,
int *index)
{
int i;
#define DEVICE_NOT_FOUND 0
#define DEVICE_CHANGED 1
#define DEVICE_SAME 2
#define DEVICE_UPDATED 3
for (i = 0; i < haystack_size; i++) {
if (haystack[i] == NULL) /* previously removed. */
continue;
if (SCSI3ADDR_EQ(needle->scsi3addr, haystack[i]->scsi3addr)) {
*index = i;
if (device_is_the_same(needle, haystack[i])) {
if (device_updated(needle, haystack[i]))
return DEVICE_UPDATED;
return DEVICE_SAME;
} else {
return DEVICE_CHANGED;
}
}
}
*index = -1;
return DEVICE_NOT_FOUND;
}
static void adjust_hpsa_scsi_table(struct ctlr_info *h, int hostno,
struct hpsa_scsi_dev_t *sd[], int nsds)
{
/* sd contains scsi3 addresses and devtypes, and inquiry
* data. This function takes what's in sd to be the current
* reality and updates h->dev[] to reflect that reality.
*/
int i, entry, device_change, changes = 0;
struct hpsa_scsi_dev_t *csd;
unsigned long flags;
struct hpsa_scsi_dev_t **added, **removed;
int nadded, nremoved;
struct Scsi_Host *sh = NULL;
added = kzalloc(sizeof(*added) * HPSA_MAX_DEVICES, GFP_KERNEL);
removed = kzalloc(sizeof(*removed) * HPSA_MAX_DEVICES, GFP_KERNEL);
if (!added || !removed) {
dev_warn(&h->pdev->dev, "out of memory in "
"adjust_hpsa_scsi_table\n");
goto free_and_out;
}
spin_lock_irqsave(&h->devlock, flags);
/* find any devices in h->dev[] that are not in
* sd[] and remove them from h->dev[], and for any
* devices which have changed, remove the old device
* info and add the new device info.
* If minor device attributes change, just update
* the existing device structure.
*/
i = 0;
nremoved = 0;
nadded = 0;
while (i < h->ndevices) {
csd = h->dev[i];
device_change = hpsa_scsi_find_entry(csd, sd, nsds, &entry);
if (device_change == DEVICE_NOT_FOUND) {
changes++;
hpsa_scsi_remove_entry(h, hostno, i,
removed, &nremoved);
continue; /* remove ^^^, hence i not incremented */
} else if (device_change == DEVICE_CHANGED) {
changes++;
hpsa_scsi_replace_entry(h, hostno, i, sd[entry],
added, &nadded, removed, &nremoved);
/* Set it to NULL to prevent it from being freed
* at the bottom of hpsa_update_scsi_devices()
*/
sd[entry] = NULL;
} else if (device_change == DEVICE_UPDATED) {
hpsa_scsi_update_entry(h, hostno, i, sd[entry]);
}
i++;
}
/* Now, make sure every device listed in sd[] is also
* listed in h->dev[], adding them if they aren't found
*/
for (i = 0; i < nsds; i++) {
if (!sd[i]) /* if already added above. */
continue;
device_change = hpsa_scsi_find_entry(sd[i], h->dev,
h->ndevices, &entry);
if (device_change == DEVICE_NOT_FOUND) {
changes++;
if (hpsa_scsi_add_entry(h, hostno, sd[i],
added, &nadded) != 0)
break;
sd[i] = NULL; /* prevent from being freed later. */
} else if (device_change == DEVICE_CHANGED) {
/* should never happen... */
changes++;
dev_warn(&h->pdev->dev,
"device unexpectedly changed.\n");
/* but if it does happen, we just ignore that device */
}
}
spin_unlock_irqrestore(&h->devlock, flags);
/* Don't notify scsi mid layer of any changes the first time through
* (or if there are no changes) scsi_scan_host will do it later the
* first time through.
*/
if (hostno == -1 || !changes)
goto free_and_out;
sh = h->scsi_host;
/* Notify scsi mid layer of any removed devices */
for (i = 0; i < nremoved; i++) {
struct scsi_device *sdev =
scsi_device_lookup(sh, removed[i]->bus,
removed[i]->target, removed[i]->lun);
if (sdev != NULL) {
scsi_remove_device(sdev);
scsi_device_put(sdev);
} else {
/* We don't expect to get here.
* future cmds to this device will get selection
* timeout as if the device was gone.
*/
dev_warn(&h->pdev->dev, "didn't find c%db%dt%dl%d "
" for removal.", hostno, removed[i]->bus,
removed[i]->target, removed[i]->lun);
}
kfree(removed[i]);
removed[i] = NULL;
}
/* Notify scsi mid layer of any added devices */
for (i = 0; i < nadded; i++) {
if (scsi_add_device(sh, added[i]->bus,
added[i]->target, added[i]->lun) == 0)
continue;
dev_warn(&h->pdev->dev, "scsi_add_device c%db%dt%dl%d failed, "
"device not added.\n", hostno, added[i]->bus,
added[i]->target, added[i]->lun);
/* now we have to remove it from h->dev,
* since it didn't get added to scsi mid layer
*/
fixup_botched_add(h, added[i]);
}
free_and_out:
kfree(added);
kfree(removed);
}
/*
* Lookup bus/target/lun and retrun corresponding struct hpsa_scsi_dev_t *
* Assume's h->devlock is held.
*/
static struct hpsa_scsi_dev_t *lookup_hpsa_scsi_dev(struct ctlr_info *h,
int bus, int target, int lun)
{
int i;
struct hpsa_scsi_dev_t *sd;
for (i = 0; i < h->ndevices; i++) {
sd = h->dev[i];
if (sd->bus == bus && sd->target == target && sd->lun == lun)
return sd;
}
return NULL;
}
/* link sdev->hostdata to our per-device structure. */
static int hpsa_slave_alloc(struct scsi_device *sdev)
{
struct hpsa_scsi_dev_t *sd;
unsigned long flags;
struct ctlr_info *h;
h = sdev_to_hba(sdev);
spin_lock_irqsave(&h->devlock, flags);
sd = lookup_hpsa_scsi_dev(h, sdev_channel(sdev),
sdev_id(sdev), sdev->lun);
if (sd != NULL)
sdev->hostdata = sd;
spin_unlock_irqrestore(&h->devlock, flags);
return 0;
}
static void hpsa_slave_destroy(struct scsi_device *sdev)
{
/* nothing to do. */
}
static void hpsa_free_sg_chain_blocks(struct ctlr_info *h)
{
int i;
if (!h->cmd_sg_list)
return;
for (i = 0; i < h->nr_cmds; i++) {
kfree(h->cmd_sg_list[i]);
h->cmd_sg_list[i] = NULL;
}
kfree(h->cmd_sg_list);
h->cmd_sg_list = NULL;
}
static int hpsa_allocate_sg_chain_blocks(struct ctlr_info *h)
{
int i;
if (h->chainsize <= 0)
return 0;
h->cmd_sg_list = kzalloc(sizeof(*h->cmd_sg_list) * h->nr_cmds,
GFP_KERNEL);
if (!h->cmd_sg_list)
return -ENOMEM;
for (i = 0; i < h->nr_cmds; i++) {
h->cmd_sg_list[i] = kmalloc(sizeof(*h->cmd_sg_list[i]) *
h->chainsize, GFP_KERNEL);
if (!h->cmd_sg_list[i])
goto clean;
}
return 0;
clean:
hpsa_free_sg_chain_blocks(h);
return -ENOMEM;
}
static int hpsa_map_sg_chain_block(struct ctlr_info *h,
struct CommandList *c)
{
struct SGDescriptor *chain_sg, *chain_block;
u64 temp64;
chain_sg = &c->SG[h->max_cmd_sg_entries - 1];
chain_block = h->cmd_sg_list[c->cmdindex];
chain_sg->Ext = HPSA_SG_CHAIN;
chain_sg->Len = sizeof(*chain_sg) *
(c->Header.SGTotal - h->max_cmd_sg_entries);
temp64 = pci_map_single(h->pdev, chain_block, chain_sg->Len,
PCI_DMA_TODEVICE);
if (dma_mapping_error(&h->pdev->dev, temp64)) {
/* prevent subsequent unmapping */
chain_sg->Addr.lower = 0;
chain_sg->Addr.upper = 0;
return -1;
}
chain_sg->Addr.lower = (u32) (temp64 & 0x0FFFFFFFFULL);
chain_sg->Addr.upper = (u32) ((temp64 >> 32) & 0x0FFFFFFFFULL);
return 0;
}
static void hpsa_unmap_sg_chain_block(struct ctlr_info *h,
struct CommandList *c)
{
struct SGDescriptor *chain_sg;
union u64bit temp64;
if (c->Header.SGTotal <= h->max_cmd_sg_entries)
return;
chain_sg = &c->SG[h->max_cmd_sg_entries - 1];
temp64.val32.lower = chain_sg->Addr.lower;
temp64.val32.upper = chain_sg->Addr.upper;
pci_unmap_single(h->pdev, temp64.val, chain_sg->Len, PCI_DMA_TODEVICE);
}
static void complete_scsi_command(struct CommandList *cp)
{
struct scsi_cmnd *cmd;
struct ctlr_info *h;
struct ErrorInfo *ei;
unsigned char sense_key;
unsigned char asc; /* additional sense code */
unsigned char ascq; /* additional sense code qualifier */
unsigned long sense_data_size;
ei = cp->err_info;
cmd = (struct scsi_cmnd *) cp->scsi_cmd;
h = cp->h;
scsi_dma_unmap(cmd); /* undo the DMA mappings */
if (cp->Header.SGTotal > h->max_cmd_sg_entries)
hpsa_unmap_sg_chain_block(h, cp);
cmd->result = (DID_OK << 16); /* host byte */
cmd->result |= (COMMAND_COMPLETE << 8); /* msg byte */
cmd->result |= ei->ScsiStatus;
/* copy the sense data whether we need to or not. */
if (SCSI_SENSE_BUFFERSIZE < sizeof(ei->SenseInfo))
sense_data_size = SCSI_SENSE_BUFFERSIZE;
else
sense_data_size = sizeof(ei->SenseInfo);
if (ei->SenseLen < sense_data_size)
sense_data_size = ei->SenseLen;
memcpy(cmd->sense_buffer, ei->SenseInfo, sense_data_size);
scsi_set_resid(cmd, ei->ResidualCnt);
if (ei->CommandStatus == 0) {
cmd->scsi_done(cmd);
cmd_free(h, cp);
return;
}
/* an error has occurred */
switch (ei->CommandStatus) {
case CMD_TARGET_STATUS:
if (ei->ScsiStatus) {
/* Get sense key */
sense_key = 0xf & ei->SenseInfo[2];
/* Get additional sense code */
asc = ei->SenseInfo[12];
/* Get addition sense code qualifier */
ascq = ei->SenseInfo[13];
}
if (ei->ScsiStatus == SAM_STAT_CHECK_CONDITION) {
if (check_for_unit_attention(h, cp)) {
cmd->result = DID_SOFT_ERROR << 16;
break;
}
if (sense_key == ILLEGAL_REQUEST) {
/*
* SCSI REPORT_LUNS is commonly unsupported on
* Smart Array. Suppress noisy complaint.
*/
if (cp->Request.CDB[0] == REPORT_LUNS)
break;
/* If ASC/ASCQ indicate Logical Unit
* Not Supported condition,
*/
if ((asc == 0x25) && (ascq == 0x0)) {
dev_warn(&h->pdev->dev, "cp %p "
"has check condition\n", cp);
break;
}
}
if (sense_key == NOT_READY) {
/* If Sense is Not Ready, Logical Unit
* Not ready, Manual Intervention
* required
*/
if ((asc == 0x04) && (ascq == 0x03)) {
dev_warn(&h->pdev->dev, "cp %p "
"has check condition: unit "
"not ready, manual "
"intervention required\n", cp);
break;
}
}
if (sense_key == ABORTED_COMMAND) {
/* Aborted command is retryable */
dev_warn(&h->pdev->dev, "cp %p "
"has check condition: aborted command: "
"ASC: 0x%x, ASCQ: 0x%x\n",
cp, asc, ascq);
cmd->result |= DID_SOFT_ERROR << 16;
break;
}
/* Must be some other type of check condition */
dev_dbg(&h->pdev->dev, "cp %p has check condition: "
"unknown type: "
"Sense: 0x%x, ASC: 0x%x, ASCQ: 0x%x, "
"Returning result: 0x%x, "
"cmd=[%02x %02x %02x %02x %02x "
"%02x %02x %02x %02x %02x %02x "
"%02x %02x %02x %02x %02x]\n",
cp, sense_key, asc, ascq,
cmd->result,
cmd->cmnd[0], cmd->cmnd[1],
cmd->cmnd[2], cmd->cmnd[3],
cmd->cmnd[4], cmd->cmnd[5],
cmd->cmnd[6], cmd->cmnd[7],
cmd->cmnd[8], cmd->cmnd[9],
cmd->cmnd[10], cmd->cmnd[11],
cmd->cmnd[12], cmd->cmnd[13],
cmd->cmnd[14], cmd->cmnd[15]);
break;
}
/* Problem was not a check condition
* Pass it up to the upper layers...
*/
if (ei->ScsiStatus) {
dev_warn(&h->pdev->dev, "cp %p has status 0x%x "
"Sense: 0x%x, ASC: 0x%x, ASCQ: 0x%x, "
"Returning result: 0x%x\n",
cp, ei->ScsiStatus,
sense_key, asc, ascq,
cmd->result);
} else { /* scsi status is zero??? How??? */
dev_warn(&h->pdev->dev, "cp %p SCSI status was 0. "
"Returning no connection.\n", cp),
/* Ordinarily, this case should never happen,
* but there is a bug in some released firmware
* revisions that allows it to happen if, for
* example, a 4100 backplane loses power and
* the tape drive is in it. We assume that
* it's a fatal error of some kind because we
* can't show that it wasn't. We will make it
* look like selection timeout since that is
* the most common reason for this to occur,
* and it's severe enough.
*/
cmd->result = DID_NO_CONNECT << 16;
}
break;
case CMD_DATA_UNDERRUN: /* let mid layer handle it. */
break;
case CMD_DATA_OVERRUN:
dev_warn(&h->pdev->dev, "cp %p has"
" completed with data overrun "
"reported\n", cp);
break;
case CMD_INVALID: {
/* print_bytes(cp, sizeof(*cp), 1, 0);
print_cmd(cp); */
/* We get CMD_INVALID if you address a non-existent device
* instead of a selection timeout (no response). You will
* see this if you yank out a drive, then try to access it.
* This is kind of a shame because it means that any other
* CMD_INVALID (e.g. driver bug) will get interpreted as a
* missing target. */
cmd->result = DID_NO_CONNECT << 16;
}
break;
case CMD_PROTOCOL_ERR:
cmd->result = DID_ERROR << 16;
dev_warn(&h->pdev->dev, "cp %p has "
"protocol error\n", cp);
break;
case CMD_HARDWARE_ERR:
cmd->result = DID_ERROR << 16;
dev_warn(&h->pdev->dev, "cp %p had hardware error\n", cp);
break;
case CMD_CONNECTION_LOST:
cmd->result = DID_ERROR << 16;
dev_warn(&h->pdev->dev, "cp %p had connection lost\n", cp);
break;
case CMD_ABORTED:
cmd->result = DID_ABORT << 16;
dev_warn(&h->pdev->dev, "cp %p was aborted with status 0x%x\n",
cp, ei->ScsiStatus);
break;
case CMD_ABORT_FAILED:
cmd->result = DID_ERROR << 16;
dev_warn(&h->pdev->dev, "cp %p reports abort failed\n", cp);
break;
case CMD_UNSOLICITED_ABORT:
cmd->result = DID_SOFT_ERROR << 16; /* retry the command */
dev_warn(&h->pdev->dev, "cp %p aborted due to an unsolicited "
"abort\n", cp);
break;
case CMD_TIMEOUT:
cmd->result = DID_TIME_OUT << 16;
dev_warn(&h->pdev->dev, "cp %p timedout\n", cp);
break;
case CMD_UNABORTABLE:
cmd->result = DID_ERROR << 16;
dev_warn(&h->pdev->dev, "Command unabortable\n");
break;
default:
cmd->result = DID_ERROR << 16;
dev_warn(&h->pdev->dev, "cp %p returned unknown status %x\n",
cp, ei->CommandStatus);
}
cmd->scsi_done(cmd);
cmd_free(h, cp);
}
static void hpsa_pci_unmap(struct pci_dev *pdev,
struct CommandList *c, int sg_used, int data_direction)
{
int i;
union u64bit addr64;
for (i = 0; i < sg_used; i++) {
addr64.val32.lower = c->SG[i].Addr.lower;
addr64.val32.upper = c->SG[i].Addr.upper;
pci_unmap_single(pdev, (dma_addr_t) addr64.val, c->SG[i].Len,
data_direction);
}
}
static int hpsa_map_one(struct pci_dev *pdev,
struct CommandList *cp,
unsigned char *buf,
size_t buflen,
int data_direction)
{
u64 addr64;
if (buflen == 0 || data_direction == PCI_DMA_NONE) {
cp->Header.SGList = 0;
cp->Header.SGTotal = 0;
return 0;
}
addr64 = (u64) pci_map_single(pdev, buf, buflen, data_direction);
if (dma_mapping_error(&pdev->dev, addr64)) {
/* Prevent subsequent unmap of something never mapped */
cp->Header.SGList = 0;
cp->Header.SGTotal = 0;
return -1;
}
cp->SG[0].Addr.lower =
(u32) (addr64 & (u64) 0x00000000FFFFFFFF);
cp->SG[0].Addr.upper =
(u32) ((addr64 >> 32) & (u64) 0x00000000FFFFFFFF);
cp->SG[0].Len = buflen;
cp->Header.SGList = (u8) 1; /* no. SGs contig in this cmd */
cp->Header.SGTotal = (u16) 1; /* total sgs in this cmd list */
return 0;
}
static inline void hpsa_scsi_do_simple_cmd_core(struct ctlr_info *h,
struct CommandList *c)
{
DECLARE_COMPLETION_ONSTACK(wait);
c->waiting = &wait;
enqueue_cmd_and_start_io(h, c);
wait_for_completion(&wait);
}
static void hpsa_scsi_do_simple_cmd_core_if_no_lockup(struct ctlr_info *h,
struct CommandList *c)
{
unsigned long flags;
/* If controller lockup detected, fake a hardware error. */
spin_lock_irqsave(&h->lock, flags);
if (unlikely(h->lockup_detected)) {
spin_unlock_irqrestore(&h->lock, flags);
c->err_info->CommandStatus = CMD_HARDWARE_ERR;
} else {
spin_unlock_irqrestore(&h->lock, flags);
hpsa_scsi_do_simple_cmd_core(h, c);
}
}
#define MAX_DRIVER_CMD_RETRIES 25
static void hpsa_scsi_do_simple_cmd_with_retry(struct ctlr_info *h,
struct CommandList *c, int data_direction)
{
int backoff_time = 10, retry_count = 0;
do {
memset(c->err_info, 0, sizeof(*c->err_info));
hpsa_scsi_do_simple_cmd_core(h, c);
retry_count++;
if (retry_count > 3) {
msleep(backoff_time);
if (backoff_time < 1000)
backoff_time *= 2;
}
} while ((check_for_unit_attention(h, c) ||
check_for_busy(h, c)) &&
retry_count <= MAX_DRIVER_CMD_RETRIES);
hpsa_pci_unmap(h->pdev, c, 1, data_direction);
}
static void hpsa_scsi_interpret_error(struct CommandList *cp)
{
struct ErrorInfo *ei;
struct device *d = &cp->h->pdev->dev;
ei = cp->err_info;
switch (ei->CommandStatus) {
case CMD_TARGET_STATUS:
dev_warn(d, "cmd %p has completed with errors\n", cp);
dev_warn(d, "cmd %p has SCSI Status = %x\n", cp,
ei->ScsiStatus);
if (ei->ScsiStatus == 0)
dev_warn(d, "SCSI status is abnormally zero. "
"(probably indicates selection timeout "
"reported incorrectly due to a known "
"firmware bug, circa July, 2001.)\n");
break;
case CMD_DATA_UNDERRUN: /* let mid layer handle it. */
dev_info(d, "UNDERRUN\n");
break;
case CMD_DATA_OVERRUN:
dev_warn(d, "cp %p has completed with data overrun\n", cp);
break;
case CMD_INVALID: {
/* controller unfortunately reports SCSI passthru's
* to non-existent targets as invalid commands.
*/
dev_warn(d, "cp %p is reported invalid (probably means "
"target device no longer present)\n", cp);
/* print_bytes((unsigned char *) cp, sizeof(*cp), 1, 0);
print_cmd(cp); */
}
break;
case CMD_PROTOCOL_ERR:
dev_warn(d, "cp %p has protocol error \n", cp);
break;
case CMD_HARDWARE_ERR:
/* cmd->result = DID_ERROR << 16; */
dev_warn(d, "cp %p had hardware error\n", cp);
break;
case CMD_CONNECTION_LOST:
dev_warn(d, "cp %p had connection lost\n", cp);
break;
case CMD_ABORTED:
dev_warn(d, "cp %p was aborted\n", cp);
break;
case CMD_ABORT_FAILED:
dev_warn(d, "cp %p reports abort failed\n", cp);
break;
case CMD_UNSOLICITED_ABORT:
dev_warn(d, "cp %p aborted due to an unsolicited abort\n", cp);
break;
case CMD_TIMEOUT:
dev_warn(d, "cp %p timed out\n", cp);
break;
case CMD_UNABORTABLE:
dev_warn(d, "Command unabortable\n");
break;
default:
dev_warn(d, "cp %p returned unknown status %x\n", cp,
ei->CommandStatus);
}
}
static int hpsa_scsi_do_inquiry(struct ctlr_info *h, unsigned char *scsi3addr,
unsigned char page, unsigned char *buf,
unsigned char bufsize)
{
int rc = IO_OK;
struct CommandList *c;
struct ErrorInfo *ei;
c = cmd_special_alloc(h);
if (c == NULL) { /* trouble... */
dev_warn(&h->pdev->dev, "cmd_special_alloc returned NULL!\n");
return -ENOMEM;
}
if (fill_cmd(c, HPSA_INQUIRY, h, buf, bufsize,
page, scsi3addr, TYPE_CMD)) {
rc = -1;
goto out;
}
hpsa_scsi_do_simple_cmd_with_retry(h, c, PCI_DMA_FROMDEVICE);
ei = c->err_info;
if (ei->CommandStatus != 0 && ei->CommandStatus != CMD_DATA_UNDERRUN) {
hpsa_scsi_interpret_error(c);
rc = -1;
}
out:
cmd_special_free(h, c);
return rc;
}
static int hpsa_send_reset(struct ctlr_info *h, unsigned char *scsi3addr)
{
int rc = IO_OK;
struct CommandList *c;
struct ErrorInfo *ei;
c = cmd_special_alloc(h);
if (c == NULL) { /* trouble... */
dev_warn(&h->pdev->dev, "cmd_special_alloc returned NULL!\n");
return -ENOMEM;
}
/* fill_cmd can't fail here, no data buffer to map. */
(void) fill_cmd(c, HPSA_DEVICE_RESET_MSG, h,
NULL, 0, 0, scsi3addr, TYPE_MSG);
hpsa_scsi_do_simple_cmd_core(h, c);
/* no unmap needed here because no data xfer. */
ei = c->err_info;
if (ei->CommandStatus != 0) {
hpsa_scsi_interpret_error(c);
rc = -1;
}
cmd_special_free(h, c);
return rc;
}
static void hpsa_get_raid_level(struct ctlr_info *h,
unsigned char *scsi3addr, unsigned char *raid_level)
{
int rc;
unsigned char *buf;
*raid_level = RAID_UNKNOWN;
buf = kzalloc(64, GFP_KERNEL);
if (!buf)
return;
rc = hpsa_scsi_do_inquiry(h, scsi3addr, 0xC1, buf, 64);
if (rc == 0)
*raid_level = buf[8];
if (*raid_level > RAID_UNKNOWN)
*raid_level = RAID_UNKNOWN;
kfree(buf);
return;
}
/* Get the device id from inquiry page 0x83 */
static int hpsa_get_device_id(struct ctlr_info *h, unsigned char *scsi3addr,
unsigned char *device_id, int buflen)
{
int rc;
unsigned char *buf;
if (buflen > 16)
buflen = 16;
buf = kzalloc(64, GFP_KERNEL);
if (!buf)
return -1;
rc = hpsa_scsi_do_inquiry(h, scsi3addr, 0x83, buf, 64);
if (rc == 0)
memcpy(device_id, &buf[8], buflen);
kfree(buf);
return rc != 0;
}
static int hpsa_scsi_do_report_luns(struct ctlr_info *h, int logical,
struct ReportLUNdata *buf, int bufsize,
int extended_response)
{
int rc = IO_OK;
struct CommandList *c;
unsigned char scsi3addr[8];
struct ErrorInfo *ei;
c = cmd_special_alloc(h);
if (c == NULL) { /* trouble... */
dev_err(&h->pdev->dev, "cmd_special_alloc returned NULL!\n");
return -1;
}
/* address the controller */
memset(scsi3addr, 0, sizeof(scsi3addr));
if (fill_cmd(c, logical ? HPSA_REPORT_LOG : HPSA_REPORT_PHYS, h,
buf, bufsize, 0, scsi3addr, TYPE_CMD)) {
rc = -1;
goto out;
}
if (extended_response)
c->Request.CDB[1] = extended_response;
hpsa_scsi_do_simple_cmd_with_retry(h, c, PCI_DMA_FROMDEVICE);
ei = c->err_info;
if (ei->CommandStatus != 0 &&
ei->CommandStatus != CMD_DATA_UNDERRUN) {
hpsa_scsi_interpret_error(c);
rc = -1;
}
out:
cmd_special_free(h, c);
return rc;
}
static inline int hpsa_scsi_do_report_phys_luns(struct ctlr_info *h,
struct ReportLUNdata *buf,
int bufsize, int extended_response)
{
return hpsa_scsi_do_report_luns(h, 0, buf, bufsize, extended_response);
}
static inline int hpsa_scsi_do_report_log_luns(struct ctlr_info *h,
struct ReportLUNdata *buf, int bufsize)
{
return hpsa_scsi_do_report_luns(h, 1, buf, bufsize, 0);
}
static inline void hpsa_set_bus_target_lun(struct hpsa_scsi_dev_t *device,
int bus, int target, int lun)
{
device->bus = bus;
device->target = target;
device->lun = lun;
}
static int hpsa_update_device_info(struct ctlr_info *h,
unsigned char scsi3addr[], struct hpsa_scsi_dev_t *this_device,
unsigned char *is_OBDR_device)
{
#define OBDR_SIG_OFFSET 43
#define OBDR_TAPE_SIG "$DR-10"
#define OBDR_SIG_LEN (sizeof(OBDR_TAPE_SIG) - 1)
#define OBDR_TAPE_INQ_SIZE (OBDR_SIG_OFFSET + OBDR_SIG_LEN)
unsigned char *inq_buff;
unsigned char *obdr_sig;
inq_buff = kzalloc(OBDR_TAPE_INQ_SIZE, GFP_KERNEL);
if (!inq_buff)
goto bail_out;
/* Do an inquiry to the device to see what it is. */
if (hpsa_scsi_do_inquiry(h, scsi3addr, 0, inq_buff,
(unsigned char) OBDR_TAPE_INQ_SIZE) != 0) {
/* Inquiry failed (msg printed already) */
dev_err(&h->pdev->dev,
"hpsa_update_device_info: inquiry failed\n");
goto bail_out;
}
this_device->devtype = (inq_buff[0] & 0x1f);
memcpy(this_device->scsi3addr, scsi3addr, 8);
memcpy(this_device->vendor, &inq_buff[8],
sizeof(this_device->vendor));
memcpy(this_device->model, &inq_buff[16],
sizeof(this_device->model));
memset(this_device->device_id, 0,
sizeof(this_device->device_id));
hpsa_get_device_id(h, scsi3addr, this_device->device_id,
sizeof(this_device->device_id));
if (this_device->devtype == TYPE_DISK &&
is_logical_dev_addr_mode(scsi3addr))
hpsa_get_raid_level(h, scsi3addr, &this_device->raid_level);
else
this_device->raid_level = RAID_UNKNOWN;
if (is_OBDR_device) {
/* See if this is a One-Button-Disaster-Recovery device
* by looking for "$DR-10" at offset 43 in inquiry data.
*/
obdr_sig = &inq_buff[OBDR_SIG_OFFSET];
*is_OBDR_device = (this_device->devtype == TYPE_ROM &&
strncmp(obdr_sig, OBDR_TAPE_SIG,
OBDR_SIG_LEN) == 0);
}
kfree(inq_buff);
return 0;
bail_out:
kfree(inq_buff);
return 1;
}
static unsigned char *ext_target_model[] = {
"MSA2012",
"MSA2024",
"MSA2312",
"MSA2324",
"P2000 G3 SAS",
NULL,
};
static int is_ext_target(struct ctlr_info *h, struct hpsa_scsi_dev_t *device)
{
int i;
for (i = 0; ext_target_model[i]; i++)
if (strncmp(device->model, ext_target_model[i],
strlen(ext_target_model[i])) == 0)
return 1;
return 0;
}
/* Helper function to assign bus, target, lun mapping of devices.
* Puts non-external target logical volumes on bus 0, external target logical
* volumes on bus 1, physical devices on bus 2. and the hba on bus 3.
* Logical drive target and lun are assigned at this time, but
* physical device lun and target assignment are deferred (assigned
* in hpsa_find_target_lun, called by hpsa_scsi_add_entry.)
*/
static void figure_bus_target_lun(struct ctlr_info *h,
u8 *lunaddrbytes, struct hpsa_scsi_dev_t *device)
{
u32 lunid = le32_to_cpu(*((__le32 *) lunaddrbytes));
if (!is_logical_dev_addr_mode(lunaddrbytes)) {
/* physical device, target and lun filled in later */
if (is_hba_lunid(lunaddrbytes))
hpsa_set_bus_target_lun(device, 3, 0, lunid & 0x3fff);
else
/* defer target, lun assignment for physical devices */
hpsa_set_bus_target_lun(device, 2, -1, -1);
return;
}
/* It's a logical device */
if (is_ext_target(h, device)) {
/* external target way, put logicals on bus 1
* and match target/lun numbers box
* reports, other smart array, bus 0, target 0, match lunid
*/
hpsa_set_bus_target_lun(device,
1, (lunid >> 16) & 0x3fff, lunid & 0x00ff);
return;
}
hpsa_set_bus_target_lun(device, 0, 0, lunid & 0x3fff);
}
/*
* If there is no lun 0 on a target, linux won't find any devices.
* For the external targets (arrays), we have to manually detect the enclosure
* which is at lun zero, as CCISS_REPORT_PHYSICAL_LUNS doesn't report
* it for some reason. *tmpdevice is the target we're adding,
* this_device is a pointer into the current element of currentsd[]
* that we're building up in update_scsi_devices(), below.
* lunzerobits is a bitmap that tracks which targets already have a
* lun 0 assigned.
* Returns 1 if an enclosure was added, 0 if not.
*/
static int add_ext_target_dev(struct ctlr_info *h,
struct hpsa_scsi_dev_t *tmpdevice,
struct hpsa_scsi_dev_t *this_device, u8 *lunaddrbytes,
unsigned long lunzerobits[], int *n_ext_target_devs)
{
unsigned char scsi3addr[8];
if (test_bit(tmpdevice->target, lunzerobits))
return 0; /* There is already a lun 0 on this target. */
if (!is_logical_dev_addr_mode(lunaddrbytes))
return 0; /* It's the logical targets that may lack lun 0. */
if (!is_ext_target(h, tmpdevice))
return 0; /* Only external target devices have this problem. */
if (tmpdevice->lun == 0) /* if lun is 0, then we have a lun 0. */
return 0;
memset(scsi3addr, 0, 8);
scsi3addr[3] = tmpdevice->target;
if (is_hba_lunid(scsi3addr))
return 0; /* Don't add the RAID controller here. */
if (is_scsi_rev_5(h))
return 0; /* p1210m doesn't need to do this. */
if (*n_ext_target_devs >= MAX_EXT_TARGETS) {
dev_warn(&h->pdev->dev, "Maximum number of external "
"target devices exceeded. Check your hardware "
"configuration.");
return 0;
}
if (hpsa_update_device_info(h, scsi3addr, this_device, NULL))
return 0;
(*n_ext_target_devs)++;
hpsa_set_bus_target_lun(this_device,
tmpdevice->bus, tmpdevice->target, 0);
set_bit(tmpdevice->target, lunzerobits);
return 1;
}
/*
* Do CISS_REPORT_PHYS and CISS_REPORT_LOG. Data is returned in physdev,
* logdev. The number of luns in physdev and logdev are returned in
* *nphysicals and *nlogicals, respectively.
* Returns 0 on success, -1 otherwise.
*/
static int hpsa_gather_lun_info(struct ctlr_info *h,
int reportlunsize,
struct ReportLUNdata *physdev, u32 *nphysicals,
struct ReportLUNdata *logdev, u32 *nlogicals)
{
if (hpsa_scsi_do_report_phys_luns(h, physdev, reportlunsize, 0)) {
dev_err(&h->pdev->dev, "report physical LUNs failed.\n");
return -1;
}
*nphysicals = be32_to_cpu(*((__be32 *)physdev->LUNListLength)) / 8;
if (*nphysicals > HPSA_MAX_PHYS_LUN) {
dev_warn(&h->pdev->dev, "maximum physical LUNs (%d) exceeded."
" %d LUNs ignored.\n", HPSA_MAX_PHYS_LUN,
*nphysicals - HPSA_MAX_PHYS_LUN);
*nphysicals = HPSA_MAX_PHYS_LUN;
}
if (hpsa_scsi_do_report_log_luns(h, logdev, reportlunsize)) {
dev_err(&h->pdev->dev, "report logical LUNs failed.\n");
return -1;
}
*nlogicals = be32_to_cpu(*((__be32 *) logdev->LUNListLength)) / 8;
/* Reject Logicals in excess of our max capability. */
if (*nlogicals > HPSA_MAX_LUN) {
dev_warn(&h->pdev->dev,
"maximum logical LUNs (%d) exceeded. "
"%d LUNs ignored.\n", HPSA_MAX_LUN,
*nlogicals - HPSA_MAX_LUN);
*nlogicals = HPSA_MAX_LUN;
}
if (*nlogicals + *nphysicals > HPSA_MAX_PHYS_LUN) {
dev_warn(&h->pdev->dev,
"maximum logical + physical LUNs (%d) exceeded. "
"%d LUNs ignored.\n", HPSA_MAX_PHYS_LUN,
*nphysicals + *nlogicals - HPSA_MAX_PHYS_LUN);
*nlogicals = HPSA_MAX_PHYS_LUN - *nphysicals;
}
return 0;
}
u8 *figure_lunaddrbytes(struct ctlr_info *h, int raid_ctlr_position, int i,
int nphysicals, int nlogicals, struct ReportLUNdata *physdev_list,
struct ReportLUNdata *logdev_list)
{
/* Helper function, figure out where the LUN ID info is coming from
* given index i, lists of physical and logical devices, where in
* the list the raid controller is supposed to appear (first or last)
*/
int logicals_start = nphysicals + (raid_ctlr_position == 0);
int last_device = nphysicals + nlogicals + (raid_ctlr_position == 0);
if (i == raid_ctlr_position)
return RAID_CTLR_LUNID;
if (i < logicals_start)
return &physdev_list->LUN[i - (raid_ctlr_position == 0)][0];
if (i < last_device)
return &logdev_list->LUN[i - nphysicals -
(raid_ctlr_position == 0)][0];
BUG();
return NULL;
}
static void hpsa_update_scsi_devices(struct ctlr_info *h, int hostno)
{
/* the idea here is we could get notified
* that some devices have changed, so we do a report
* physical luns and report logical luns cmd, and adjust
* our list of devices accordingly.
*
* The scsi3addr's of devices won't change so long as the
* adapter is not reset. That means we can rescan and
* tell which devices we already know about, vs. new
* devices, vs. disappearing devices.
*/
struct ReportLUNdata *physdev_list = NULL;
struct ReportLUNdata *logdev_list = NULL;
u32 nphysicals = 0;
u32 nlogicals = 0;
u32 ndev_allocated = 0;
struct hpsa_scsi_dev_t **currentsd, *this_device, *tmpdevice;
int ncurrent = 0;
int reportlunsize = sizeof(*physdev_list) + HPSA_MAX_PHYS_LUN * 8;
int i, n_ext_target_devs, ndevs_to_allocate;
int raid_ctlr_position;
DECLARE_BITMAP(lunzerobits, MAX_EXT_TARGETS);
currentsd = kzalloc(sizeof(*currentsd) * HPSA_MAX_DEVICES, GFP_KERNEL);
physdev_list = kzalloc(reportlunsize, GFP_KERNEL);
logdev_list = kzalloc(reportlunsize, GFP_KERNEL);
tmpdevice = kzalloc(sizeof(*tmpdevice), GFP_KERNEL);
if (!currentsd || !physdev_list || !logdev_list || !tmpdevice) {
dev_err(&h->pdev->dev, "out of memory\n");
goto out;
}
memset(lunzerobits, 0, sizeof(lunzerobits));
if (hpsa_gather_lun_info(h, reportlunsize, physdev_list, &nphysicals,
logdev_list, &nlogicals))
goto out;
/* We might see up to the maximum number of logical and physical disks
* plus external target devices, and a device for the local RAID
* controller.
*/
ndevs_to_allocate = nphysicals + nlogicals + MAX_EXT_TARGETS + 1;
/* Allocate the per device structures */
for (i = 0; i < ndevs_to_allocate; i++) {
if (i >= HPSA_MAX_DEVICES) {
dev_warn(&h->pdev->dev, "maximum devices (%d) exceeded."
" %d devices ignored.\n", HPSA_MAX_DEVICES,
ndevs_to_allocate - HPSA_MAX_DEVICES);
break;
}
currentsd[i] = kzalloc(sizeof(*currentsd[i]), GFP_KERNEL);
if (!currentsd[i]) {
dev_warn(&h->pdev->dev, "out of memory at %s:%d\n",
__FILE__, __LINE__);
goto out;
}
ndev_allocated++;
}
if (unlikely(is_scsi_rev_5(h)))
raid_ctlr_position = 0;
else
raid_ctlr_position = nphysicals + nlogicals;
/* adjust our table of devices */
n_ext_target_devs = 0;
for (i = 0; i < nphysicals + nlogicals + 1; i++) {
u8 *lunaddrbytes, is_OBDR = 0;
/* Figure out where the LUN ID info is coming from */
lunaddrbytes = figure_lunaddrbytes(h, raid_ctlr_position,
i, nphysicals, nlogicals, physdev_list, logdev_list);
/* skip masked physical devices. */
if (lunaddrbytes[3] & 0xC0 &&
i < nphysicals + (raid_ctlr_position == 0))
continue;
/* Get device type, vendor, model, device id */
if (hpsa_update_device_info(h, lunaddrbytes, tmpdevice,
&is_OBDR))
continue; /* skip it if we can't talk to it. */
figure_bus_target_lun(h, lunaddrbytes, tmpdevice);
this_device = currentsd[ncurrent];
/*
* For external target devices, we have to insert a LUN 0 which
* doesn't show up in CCISS_REPORT_PHYSICAL data, but there
* is nonetheless an enclosure device there. We have to
* present that otherwise linux won't find anything if
* there is no lun 0.
*/
if (add_ext_target_dev(h, tmpdevice, this_device,
lunaddrbytes, lunzerobits,
&n_ext_target_devs)) {
ncurrent++;
this_device = currentsd[ncurrent];
}
*this_device = *tmpdevice;
switch (this_device->devtype) {
case TYPE_ROM:
/* We don't *really* support actual CD-ROM devices,
* just "One Button Disaster Recovery" tape drive
* which temporarily pretends to be a CD-ROM drive.
* So we check that the device is really an OBDR tape
* device by checking for "$DR-10" in bytes 43-48 of
* the inquiry data.
*/
if (is_OBDR)
ncurrent++;
break;
case TYPE_DISK:
if (i < nphysicals)
break;
ncurrent++;
break;
case TYPE_TAPE:
case TYPE_MEDIUM_CHANGER:
ncurrent++;
break;
case TYPE_RAID:
/* Only present the Smartarray HBA as a RAID controller.
* If it's a RAID controller other than the HBA itself
* (an external RAID controller, MSA500 or similar)
* don't present it.
*/
if (!is_hba_lunid(lunaddrbytes))
break;
ncurrent++;
break;
default:
break;
}
if (ncurrent >= HPSA_MAX_DEVICES)
break;
}
adjust_hpsa_scsi_table(h, hostno, currentsd, ncurrent);
out:
kfree(tmpdevice);
for (i = 0; i < ndev_allocated; i++)
kfree(currentsd[i]);
kfree(currentsd);
kfree(physdev_list);
kfree(logdev_list);
}
/* hpsa_scatter_gather takes a struct scsi_cmnd, (cmd), and does the pci
* dma mapping and fills in the scatter gather entries of the
* hpsa command, cp.
*/
static int hpsa_scatter_gather(struct ctlr_info *h,
struct CommandList *cp,
struct scsi_cmnd *cmd)
{
unsigned int len;
struct scatterlist *sg;
u64 addr64;
int use_sg, i, sg_index, chained;
struct SGDescriptor *curr_sg;
BUG_ON(scsi_sg_count(cmd) > h->maxsgentries);
use_sg = scsi_dma_map(cmd);
if (use_sg < 0)
return use_sg;
if (!use_sg)
goto sglist_finished;
curr_sg = cp->SG;
chained = 0;
sg_index = 0;
scsi_for_each_sg(cmd, sg, use_sg, i) {
if (i == h->max_cmd_sg_entries - 1 &&
use_sg > h->max_cmd_sg_entries) {
chained = 1;
curr_sg = h->cmd_sg_list[cp->cmdindex];
sg_index = 0;
}
addr64 = (u64) sg_dma_address(sg);
len = sg_dma_len(sg);
curr_sg->Addr.lower = (u32) (addr64 & 0x0FFFFFFFFULL);
curr_sg->Addr.upper = (u32) ((addr64 >> 32) & 0x0FFFFFFFFULL);
curr_sg->Len = len;
curr_sg->Ext = 0; /* we are not chaining */
curr_sg++;
}
if (use_sg + chained > h->maxSG)
h->maxSG = use_sg + chained;
if (chained) {
cp->Header.SGList = h->max_cmd_sg_entries;
cp->Header.SGTotal = (u16) (use_sg + 1);
if (hpsa_map_sg_chain_block(h, cp)) {
scsi_dma_unmap(cmd);
return -1;
}
return 0;
}
sglist_finished:
cp->Header.SGList = (u8) use_sg; /* no. SGs contig in this cmd */
cp->Header.SGTotal = (u16) use_sg; /* total sgs in this cmd list */
return 0;
}
static int hpsa_scsi_queue_command_lck(struct scsi_cmnd *cmd,
void (*done)(struct scsi_cmnd *))
{
struct ctlr_info *h;
struct hpsa_scsi_dev_t *dev;
unsigned char scsi3addr[8];
struct CommandList *c;
unsigned long flags;
/* Get the ptr to our adapter structure out of cmd->host. */
h = sdev_to_hba(cmd->device);
dev = cmd->device->hostdata;
if (!dev) {
cmd->result = DID_NO_CONNECT << 16;
done(cmd);
return 0;
}
memcpy(scsi3addr, dev->scsi3addr, sizeof(scsi3addr));
spin_lock_irqsave(&h->lock, flags);
if (unlikely(h->lockup_detected)) {
spin_unlock_irqrestore(&h->lock, flags);
cmd->result = DID_ERROR << 16;
done(cmd);
return 0;
}
spin_unlock_irqrestore(&h->lock, flags);
c = cmd_alloc(h);
if (c == NULL) { /* trouble... */
dev_err(&h->pdev->dev, "cmd_alloc returned NULL!\n");
return SCSI_MLQUEUE_HOST_BUSY;
}
/* Fill in the command list header */
cmd->scsi_done = done; /* save this for use by completion code */
/* save c in case we have to abort it */
cmd->host_scribble = (unsigned char *) c;
c->cmd_type = CMD_SCSI;
c->scsi_cmd = cmd;
c->Header.ReplyQueue = 0; /* unused in simple mode */
memcpy(&c->Header.LUN.LunAddrBytes[0], &scsi3addr[0], 8);
c->Header.Tag.lower = (c->cmdindex << DIRECT_LOOKUP_SHIFT);
c->Header.Tag.lower |= DIRECT_LOOKUP_BIT;
/* Fill in the request block... */
c->Request.Timeout = 0;
memset(c->Request.CDB, 0, sizeof(c->Request.CDB));
BUG_ON(cmd->cmd_len > sizeof(c->Request.CDB));
c->Request.CDBLen = cmd->cmd_len;
memcpy(c->Request.CDB, cmd->cmnd, cmd->cmd_len);
c->Request.Type.Type = TYPE_CMD;
c->Request.Type.Attribute = ATTR_SIMPLE;
switch (cmd->sc_data_direction) {
case DMA_TO_DEVICE:
c->Request.Type.Direction = XFER_WRITE;
break;
case DMA_FROM_DEVICE:
c->Request.Type.Direction = XFER_READ;
break;
case DMA_NONE:
c->Request.Type.Direction = XFER_NONE;
break;
case DMA_BIDIRECTIONAL:
/* This can happen if a buggy application does a scsi passthru
* and sets both inlen and outlen to non-zero. ( see
* ../scsi/scsi_ioctl.c:scsi_ioctl_send_command() )
*/
c->Request.Type.Direction = XFER_RSVD;
/* This is technically wrong, and hpsa controllers should
* reject it with CMD_INVALID, which is the most correct
* response, but non-fibre backends appear to let it
* slide by, and give the same results as if this field
* were set correctly. Either way is acceptable for
* our purposes here.
*/
break;
default:
dev_err(&h->pdev->dev, "unknown data direction: %d\n",
cmd->sc_data_direction);
BUG();
break;
}
if (hpsa_scatter_gather(h, c, cmd) < 0) { /* Fill SG list */
cmd_free(h, c);
return SCSI_MLQUEUE_HOST_BUSY;
}
enqueue_cmd_and_start_io(h, c);
/* the cmd'll come back via intr handler in complete_scsi_command() */
return 0;
}
static DEF_SCSI_QCMD(hpsa_scsi_queue_command)
static void hpsa_scan_start(struct Scsi_Host *sh)
{
struct ctlr_info *h = shost_to_hba(sh);
unsigned long flags;
/* wait until any scan already in progress is finished. */
while (1) {
spin_lock_irqsave(&h->scan_lock, flags);
if (h->scan_finished)
break;
spin_unlock_irqrestore(&h->scan_lock, flags);
wait_event(h->scan_wait_queue, h->scan_finished);
/* Note: We don't need to worry about a race between this
* thread and driver unload because the midlayer will
* have incremented the reference count, so unload won't
* happen if we're in here.
*/
}
h->scan_finished = 0; /* mark scan as in progress */
spin_unlock_irqrestore(&h->scan_lock, flags);
hpsa_update_scsi_devices(h, h->scsi_host->host_no);
spin_lock_irqsave(&h->scan_lock, flags);
h->scan_finished = 1; /* mark scan as finished. */
wake_up_all(&h->scan_wait_queue);
spin_unlock_irqrestore(&h->scan_lock, flags);
}
static int hpsa_scan_finished(struct Scsi_Host *sh,
unsigned long elapsed_time)
{
struct ctlr_info *h = shost_to_hba(sh);
unsigned long flags;
int finished;
spin_lock_irqsave(&h->scan_lock, flags);
finished = h->scan_finished;
spin_unlock_irqrestore(&h->scan_lock, flags);
return finished;
}
static int hpsa_change_queue_depth(struct scsi_device *sdev,
int qdepth, int reason)
{
struct ctlr_info *h = sdev_to_hba(sdev);
if (reason != SCSI_QDEPTH_DEFAULT)
return -ENOTSUPP;
if (qdepth < 1)
qdepth = 1;
else
if (qdepth > h->nr_cmds)
qdepth = h->nr_cmds;
scsi_adjust_queue_depth(sdev, scsi_get_tag_type(sdev), qdepth);
return sdev->queue_depth;
}
static void hpsa_unregister_scsi(struct ctlr_info *h)
{
/* we are being forcibly unloaded, and may not refuse. */
scsi_remove_host(h->scsi_host);
scsi_host_put(h->scsi_host);
h->scsi_host = NULL;
}
static int hpsa_register_scsi(struct ctlr_info *h)
{
struct Scsi_Host *sh;
int error;
sh = scsi_host_alloc(&hpsa_driver_template, sizeof(h));
if (sh == NULL)
goto fail;
sh->io_port = 0;
sh->n_io_port = 0;
sh->this_id = -1;
sh->max_channel = 3;
sh->max_cmd_len = MAX_COMMAND_SIZE;
sh->max_lun = HPSA_MAX_LUN;
sh->max_id = HPSA_MAX_LUN;
sh->can_queue = h->nr_cmds;
sh->cmd_per_lun = h->nr_cmds;
sh->sg_tablesize = h->maxsgentries;
h->scsi_host = sh;
sh->hostdata[0] = (unsigned long) h;
sh->irq = h->intr[h->intr_mode];
sh->unique_id = sh->irq;
error = scsi_add_host(sh, &h->pdev->dev);
if (error)
goto fail_host_put;
scsi_scan_host(sh);
return 0;
fail_host_put:
dev_err(&h->pdev->dev, "%s: scsi_add_host"
" failed for controller %d\n", __func__, h->ctlr);
scsi_host_put(sh);
return error;
fail:
dev_err(&h->pdev->dev, "%s: scsi_host_alloc"
" failed for controller %d\n", __func__, h->ctlr);
return -ENOMEM;
}
static int wait_for_device_to_become_ready(struct ctlr_info *h,
unsigned char lunaddr[])
{
int rc = 0;
int count = 0;
int waittime = 1; /* seconds */
struct CommandList *c;
c = cmd_special_alloc(h);
if (!c) {
dev_warn(&h->pdev->dev, "out of memory in "
"wait_for_device_to_become_ready.\n");
return IO_ERROR;
}
/* Send test unit ready until device ready, or give up. */
while (count < HPSA_TUR_RETRY_LIMIT) {
/* Wait for a bit. do this first, because if we send
* the TUR right away, the reset will just abort it.
*/
msleep(1000 * waittime);
count++;
/* Increase wait time with each try, up to a point. */
if (waittime < HPSA_MAX_WAIT_INTERVAL_SECS)
waittime = waittime * 2;
/* Send the Test Unit Ready, fill_cmd can't fail, no mapping */
(void) fill_cmd(c, TEST_UNIT_READY, h,
NULL, 0, 0, lunaddr, TYPE_CMD);
hpsa_scsi_do_simple_cmd_core(h, c);
/* no unmap needed here because no data xfer. */
if (c->err_info->CommandStatus == CMD_SUCCESS)
break;
if (c->err_info->CommandStatus == CMD_TARGET_STATUS &&
c->err_info->ScsiStatus == SAM_STAT_CHECK_CONDITION &&
(c->err_info->SenseInfo[2] == NO_SENSE ||
c->err_info->SenseInfo[2] == UNIT_ATTENTION))
break;
dev_warn(&h->pdev->dev, "waiting %d secs "
"for device to become ready.\n", waittime);
rc = 1; /* device not ready. */
}
if (rc)
dev_warn(&h->pdev->dev, "giving up on device.\n");
else
dev_warn(&h->pdev->dev, "device is ready.\n");
cmd_special_free(h, c);
return rc;
}
/* Need at least one of these error handlers to keep ../scsi/hosts.c from
* complaining. Doing a host- or bus-reset can't do anything good here.
*/
static int hpsa_eh_device_reset_handler(struct scsi_cmnd *scsicmd)
{
int rc;
struct ctlr_info *h;
struct hpsa_scsi_dev_t *dev;
/* find the controller to which the command to be aborted was sent */
h = sdev_to_hba(scsicmd->device);
if (h == NULL) /* paranoia */
return FAILED;
dev = scsicmd->device->hostdata;
if (!dev) {
dev_err(&h->pdev->dev, "hpsa_eh_device_reset_handler: "
"device lookup failed.\n");
return FAILED;
}
dev_warn(&h->pdev->dev, "resetting device %d:%d:%d:%d\n",
h->scsi_host->host_no, dev->bus, dev->target, dev->lun);
/* send a reset to the SCSI LUN which the command was sent to */
rc = hpsa_send_reset(h, dev->scsi3addr);
if (rc == 0 && wait_for_device_to_become_ready(h, dev->scsi3addr) == 0)
return SUCCESS;
dev_warn(&h->pdev->dev, "resetting device failed.\n");
return FAILED;
}
static void swizzle_abort_tag(u8 *tag)
{
u8 original_tag[8];
memcpy(original_tag, tag, 8);
tag[0] = original_tag[3];
tag[1] = original_tag[2];
tag[2] = original_tag[1];
tag[3] = original_tag[0];
tag[4] = original_tag[7];
tag[5] = original_tag[6];
tag[6] = original_tag[5];
tag[7] = original_tag[4];
}
static int hpsa_send_abort(struct ctlr_info *h, unsigned char *scsi3addr,
struct CommandList *abort, int swizzle)
{
int rc = IO_OK;
struct CommandList *c;
struct ErrorInfo *ei;
c = cmd_special_alloc(h);
if (c == NULL) { /* trouble... */
dev_warn(&h->pdev->dev, "cmd_special_alloc returned NULL!\n");
return -ENOMEM;
}
/* fill_cmd can't fail here, no buffer to map */
(void) fill_cmd(c, HPSA_ABORT_MSG, h, abort,
0, 0, scsi3addr, TYPE_MSG);
if (swizzle)
swizzle_abort_tag(&c->Request.CDB[4]);
hpsa_scsi_do_simple_cmd_core(h, c);
dev_dbg(&h->pdev->dev, "%s: Tag:0x%08x:%08x: do_simple_cmd_core completed.\n",
__func__, abort->Header.Tag.upper, abort->Header.Tag.lower);
/* no unmap needed here because no data xfer. */
ei = c->err_info;
switch (ei->CommandStatus) {
case CMD_SUCCESS:
break;
case CMD_UNABORTABLE: /* Very common, don't make noise. */
rc = -1;
break;
default:
dev_dbg(&h->pdev->dev, "%s: Tag:0x%08x:%08x: interpreting error.\n",
__func__, abort->Header.Tag.upper,
abort->Header.Tag.lower);
hpsa_scsi_interpret_error(c);
rc = -1;
break;
}
cmd_special_free(h, c);
dev_dbg(&h->pdev->dev, "%s: Tag:0x%08x:%08x: Finished.\n", __func__,
abort->Header.Tag.upper, abort->Header.Tag.lower);
return rc;
}
/*
* hpsa_find_cmd_in_queue
*
* Used to determine whether a command (find) is still present
* in queue_head. Optionally excludes the last element of queue_head.
*
* This is used to avoid unnecessary aborts. Commands in h->reqQ have
* not yet been submitted, and so can be aborted by the driver without
* sending an abort to the hardware.
*
* Returns pointer to command if found in queue, NULL otherwise.
*/
static struct CommandList *hpsa_find_cmd_in_queue(struct ctlr_info *h,
struct scsi_cmnd *find, struct list_head *queue_head)
{
unsigned long flags;
struct CommandList *c = NULL; /* ptr into cmpQ */
if (!find)
return 0;
spin_lock_irqsave(&h->lock, flags);
list_for_each_entry(c, queue_head, list) {
if (c->scsi_cmd == NULL) /* e.g.: passthru ioctl */
continue;
if (c->scsi_cmd == find) {
spin_unlock_irqrestore(&h->lock, flags);
return c;
}
}
spin_unlock_irqrestore(&h->lock, flags);
return NULL;
}
static struct CommandList *hpsa_find_cmd_in_queue_by_tag(struct ctlr_info *h,
u8 *tag, struct list_head *queue_head)
{
unsigned long flags;
struct CommandList *c;
spin_lock_irqsave(&h->lock, flags);
list_for_each_entry(c, queue_head, list) {
if (memcmp(&c->Header.Tag, tag, 8) != 0)
continue;
spin_unlock_irqrestore(&h->lock, flags);
return c;
}
spin_unlock_irqrestore(&h->lock, flags);
return NULL;
}
/* Some Smart Arrays need the abort tag swizzled, and some don't. It's hard to
* tell which kind we're dealing with, so we send the abort both ways. There
* shouldn't be any collisions between swizzled and unswizzled tags due to the
* way we construct our tags but we check anyway in case the assumptions which
* make this true someday become false.
*/
static int hpsa_send_abort_both_ways(struct ctlr_info *h,
unsigned char *scsi3addr, struct CommandList *abort)
{
u8 swizzled_tag[8];
struct CommandList *c;
int rc = 0, rc2 = 0;
/* we do not expect to find the swizzled tag in our queue, but
* check anyway just to be sure the assumptions which make this
* the case haven't become wrong.
*/
memcpy(swizzled_tag, &abort->Request.CDB[4], 8);
swizzle_abort_tag(swizzled_tag);
c = hpsa_find_cmd_in_queue_by_tag(h, swizzled_tag, &h->cmpQ);
if (c != NULL) {
dev_warn(&h->pdev->dev, "Unexpectedly found byte-swapped tag in completion queue.\n");
return hpsa_send_abort(h, scsi3addr, abort, 0);
}
rc = hpsa_send_abort(h, scsi3addr, abort, 0);
/* if the command is still in our queue, we can't conclude that it was
* aborted (it might have just completed normally) but in any case
* we don't need to try to abort it another way.
*/
c = hpsa_find_cmd_in_queue(h, abort->scsi_cmd, &h->cmpQ);
if (c)
rc2 = hpsa_send_abort(h, scsi3addr, abort, 1);
return rc && rc2;
}
/* Send an abort for the specified command.
* If the device and controller support it,
* send a task abort request.
*/
static int hpsa_eh_abort_handler(struct scsi_cmnd *sc)
{
int i, rc;
struct ctlr_info *h;
struct hpsa_scsi_dev_t *dev;
struct CommandList *abort; /* pointer to command to be aborted */
struct CommandList *found;
struct scsi_cmnd *as; /* ptr to scsi cmd inside aborted command. */
char msg[256]; /* For debug messaging. */
int ml = 0;
/* Find the controller of the command to be aborted */
h = sdev_to_hba(sc->device);
if (WARN(h == NULL,
"ABORT REQUEST FAILED, Controller lookup failed.\n"))
return FAILED;
/* Check that controller supports some kind of task abort */
if (!(HPSATMF_PHYS_TASK_ABORT & h->TMFSupportFlags) &&
!(HPSATMF_LOG_TASK_ABORT & h->TMFSupportFlags))
return FAILED;
memset(msg, 0, sizeof(msg));
ml += sprintf(msg+ml, "ABORT REQUEST on C%d:B%d:T%d:L%d ",
h->scsi_host->host_no, sc->device->channel,
sc->device->id, sc->device->lun);
/* Find the device of the command to be aborted */
dev = sc->device->hostdata;
if (!dev) {
dev_err(&h->pdev->dev, "%s FAILED, Device lookup failed.\n",
msg);
return FAILED;
}
/* Get SCSI command to be aborted */
abort = (struct CommandList *) sc->host_scribble;
if (abort == NULL) {
dev_err(&h->pdev->dev, "%s FAILED, Command to abort is NULL.\n",
msg);
return FAILED;
}
ml += sprintf(msg+ml, "Tag:0x%08x:%08x ",
abort->Header.Tag.upper, abort->Header.Tag.lower);
as = (struct scsi_cmnd *) abort->scsi_cmd;
if (as != NULL)
ml += sprintf(msg+ml, "Command:0x%x SN:0x%lx ",
as->cmnd[0], as->serial_number);
dev_dbg(&h->pdev->dev, "%s\n", msg);
dev_warn(&h->pdev->dev, "Abort request on C%d:B%d:T%d:L%d\n",
h->scsi_host->host_no, dev->bus, dev->target, dev->lun);
/* Search reqQ to See if command is queued but not submitted,
* if so, complete the command with aborted status and remove
* it from the reqQ.
*/
found = hpsa_find_cmd_in_queue(h, sc, &h->reqQ);
if (found) {
found->err_info->CommandStatus = CMD_ABORTED;
finish_cmd(found);
dev_info(&h->pdev->dev, "%s Request SUCCEEDED (driver queue).\n",
msg);
return SUCCESS;
}
/* not in reqQ, if also not in cmpQ, must have already completed */
found = hpsa_find_cmd_in_queue(h, sc, &h->cmpQ);
if (!found) {
dev_dbg(&h->pdev->dev, "%s Request SUCCEEDED (not known to driver).\n",
msg);
return SUCCESS;
}
/*
* Command is in flight, or possibly already completed
* by the firmware (but not to the scsi mid layer) but we can't
* distinguish which. Send the abort down.
*/
rc = hpsa_send_abort_both_ways(h, dev->scsi3addr, abort);
if (rc != 0) {
dev_dbg(&h->pdev->dev, "%s Request FAILED.\n", msg);
dev_warn(&h->pdev->dev, "FAILED abort on device C%d:B%d:T%d:L%d\n",
h->scsi_host->host_no,
dev->bus, dev->target, dev->lun);
return FAILED;
}
dev_info(&h->pdev->dev, "%s REQUEST SUCCEEDED.\n", msg);
/* If the abort(s) above completed and actually aborted the
* command, then the command to be aborted should already be
* completed. If not, wait around a bit more to see if they
* manage to complete normally.
*/
#define ABORT_COMPLETE_WAIT_SECS 30
for (i = 0; i < ABORT_COMPLETE_WAIT_SECS * 10; i++) {
found = hpsa_find_cmd_in_queue(h, sc, &h->cmpQ);
if (!found)
return SUCCESS;
msleep(100);
}
dev_warn(&h->pdev->dev, "%s FAILED. Aborted command has not completed after %d seconds.\n",
msg, ABORT_COMPLETE_WAIT_SECS);
return FAILED;
}
/*
* For operations that cannot sleep, a command block is allocated at init,
* and managed by cmd_alloc() and cmd_free() using a simple bitmap to track
* which ones are free or in use. Lock must be held when calling this.
* cmd_free() is the complement.
*/
static struct CommandList *cmd_alloc(struct ctlr_info *h)
{
struct CommandList *c;
int i;
union u64bit temp64;
dma_addr_t cmd_dma_handle, err_dma_handle;
unsigned long flags;
spin_lock_irqsave(&h->lock, flags);
do {
i = find_first_zero_bit(h->cmd_pool_bits, h->nr_cmds);
if (i == h->nr_cmds) {
spin_unlock_irqrestore(&h->lock, flags);
return NULL;
}
} while (test_and_set_bit
(i & (BITS_PER_LONG - 1),
h->cmd_pool_bits + (i / BITS_PER_LONG)) != 0);
h->nr_allocs++;
spin_unlock_irqrestore(&h->lock, flags);
c = h->cmd_pool + i;
memset(c, 0, sizeof(*c));
cmd_dma_handle = h->cmd_pool_dhandle
+ i * sizeof(*c);
c->err_info = h->errinfo_pool + i;
memset(c->err_info, 0, sizeof(*c->err_info));
err_dma_handle = h->errinfo_pool_dhandle
+ i * sizeof(*c->err_info);
c->cmdindex = i;
INIT_LIST_HEAD(&c->list);
c->busaddr = (u32) cmd_dma_handle;
temp64.val = (u64) err_dma_handle;
c->ErrDesc.Addr.lower = temp64.val32.lower;
c->ErrDesc.Addr.upper = temp64.val32.upper;
c->ErrDesc.Len = sizeof(*c->err_info);
c->h = h;
return c;
}
/* For operations that can wait for kmalloc to possibly sleep,
* this routine can be called. Lock need not be held to call
* cmd_special_alloc. cmd_special_free() is the complement.
*/
static struct CommandList *cmd_special_alloc(struct ctlr_info *h)
{
struct CommandList *c;
union u64bit temp64;
dma_addr_t cmd_dma_handle, err_dma_handle;
c = pci_alloc_consistent(h->pdev, sizeof(*c), &cmd_dma_handle);
if (c == NULL)
return NULL;
memset(c, 0, sizeof(*c));
c->cmdindex = -1;
c->err_info = pci_alloc_consistent(h->pdev, sizeof(*c->err_info),
&err_dma_handle);
if (c->err_info == NULL) {
pci_free_consistent(h->pdev,
sizeof(*c), c, cmd_dma_handle);
return NULL;
}
memset(c->err_info, 0, sizeof(*c->err_info));
INIT_LIST_HEAD(&c->list);
c->busaddr = (u32) cmd_dma_handle;
temp64.val = (u64) err_dma_handle;
c->ErrDesc.Addr.lower = temp64.val32.lower;
c->ErrDesc.Addr.upper = temp64.val32.upper;
c->ErrDesc.Len = sizeof(*c->err_info);
c->h = h;
return c;
}
static void cmd_free(struct ctlr_info *h, struct CommandList *c)
{
int i;
unsigned long flags;
i = c - h->cmd_pool;
spin_lock_irqsave(&h->lock, flags);
clear_bit(i & (BITS_PER_LONG - 1),
h->cmd_pool_bits + (i / BITS_PER_LONG));
h->nr_frees++;
spin_unlock_irqrestore(&h->lock, flags);
}
static void cmd_special_free(struct ctlr_info *h, struct CommandList *c)
{
union u64bit temp64;
temp64.val32.lower = c->ErrDesc.Addr.lower;
temp64.val32.upper = c->ErrDesc.Addr.upper;
pci_free_consistent(h->pdev, sizeof(*c->err_info),
c->err_info, (dma_addr_t) temp64.val);
pci_free_consistent(h->pdev, sizeof(*c),
c, (dma_addr_t) (c->busaddr & DIRECT_LOOKUP_MASK));
}
#ifdef CONFIG_COMPAT
static int hpsa_ioctl32_passthru(struct scsi_device *dev, int cmd, void *arg)
{
IOCTL32_Command_struct __user *arg32 =
(IOCTL32_Command_struct __user *) arg;
IOCTL_Command_struct arg64;
IOCTL_Command_struct __user *p = compat_alloc_user_space(sizeof(arg64));
int err;
u32 cp;
memset(&arg64, 0, sizeof(arg64));
err = 0;
err |= copy_from_user(&arg64.LUN_info, &arg32->LUN_info,
sizeof(arg64.LUN_info));
err |= copy_from_user(&arg64.Request, &arg32->Request,
sizeof(arg64.Request));
err |= copy_from_user(&arg64.error_info, &arg32->error_info,
sizeof(arg64.error_info));
err |= get_user(arg64.buf_size, &arg32->buf_size);
err |= get_user(cp, &arg32->buf);
arg64.buf = compat_ptr(cp);
err |= copy_to_user(p, &arg64, sizeof(arg64));
if (err)
return -EFAULT;
err = hpsa_ioctl(dev, CCISS_PASSTHRU, (void *)p);
if (err)
return err;
err |= copy_in_user(&arg32->error_info, &p->error_info,
sizeof(arg32->error_info));
if (err)
return -EFAULT;
return err;
}
static int hpsa_ioctl32_big_passthru(struct scsi_device *dev,
int cmd, void *arg)
{
BIG_IOCTL32_Command_struct __user *arg32 =
(BIG_IOCTL32_Command_struct __user *) arg;
BIG_IOCTL_Command_struct arg64;
BIG_IOCTL_Command_struct __user *p =
compat_alloc_user_space(sizeof(arg64));
int err;
u32 cp;
memset(&arg64, 0, sizeof(arg64));
err = 0;
err |= copy_from_user(&arg64.LUN_info, &arg32->LUN_info,
sizeof(arg64.LUN_info));
err |= copy_from_user(&arg64.Request, &arg32->Request,
sizeof(arg64.Request));
err |= copy_from_user(&arg64.error_info, &arg32->error_info,
sizeof(arg64.error_info));
err |= get_user(arg64.buf_size, &arg32->buf_size);
err |= get_user(arg64.malloc_size, &arg32->malloc_size);
err |= get_user(cp, &arg32->buf);
arg64.buf = compat_ptr(cp);
err |= copy_to_user(p, &arg64, sizeof(arg64));
if (err)
return -EFAULT;
err = hpsa_ioctl(dev, CCISS_BIG_PASSTHRU, (void *)p);
if (err)
return err;
err |= copy_in_user(&arg32->error_info, &p->error_info,
sizeof(arg32->error_info));
if (err)
return -EFAULT;
return err;
}
static int hpsa_compat_ioctl(struct scsi_device *dev, int cmd, void *arg)
{
switch (cmd) {
case CCISS_GETPCIINFO:
case CCISS_GETINTINFO:
case CCISS_SETINTINFO:
case CCISS_GETNODENAME:
case CCISS_SETNODENAME:
case CCISS_GETHEARTBEAT:
case CCISS_GETBUSTYPES:
case CCISS_GETFIRMVER:
case CCISS_GETDRIVVER:
case CCISS_REVALIDVOLS:
case CCISS_DEREGDISK:
case CCISS_REGNEWDISK:
case CCISS_REGNEWD:
case CCISS_RESCANDISK:
case CCISS_GETLUNINFO:
return hpsa_ioctl(dev, cmd, arg);
case CCISS_PASSTHRU32:
return hpsa_ioctl32_passthru(dev, cmd, arg);
case CCISS_BIG_PASSTHRU32:
return hpsa_ioctl32_big_passthru(dev, cmd, arg);
default:
return -ENOIOCTLCMD;
}
}
#endif
static int hpsa_getpciinfo_ioctl(struct ctlr_info *h, void __user *argp)
{
struct hpsa_pci_info pciinfo;
if (!argp)
return -EINVAL;
pciinfo.domain = pci_domain_nr(h->pdev->bus);
pciinfo.bus = h->pdev->bus->number;
pciinfo.dev_fn = h->pdev->devfn;
pciinfo.board_id = h->board_id;
if (copy_to_user(argp, &pciinfo, sizeof(pciinfo)))
return -EFAULT;
return 0;
}
static int hpsa_getdrivver_ioctl(struct ctlr_info *h, void __user *argp)
{
DriverVer_type DriverVer;
unsigned char vmaj, vmin, vsubmin;
int rc;
rc = sscanf(HPSA_DRIVER_VERSION, "%hhu.%hhu.%hhu",
&vmaj, &vmin, &vsubmin);
if (rc != 3) {
dev_info(&h->pdev->dev, "driver version string '%s' "
"unrecognized.", HPSA_DRIVER_VERSION);
vmaj = 0;
vmin = 0;
vsubmin = 0;
}
DriverVer = (vmaj << 16) | (vmin << 8) | vsubmin;
if (!argp)
return -EINVAL;
if (copy_to_user(argp, &DriverVer, sizeof(DriverVer_type)))
return -EFAULT;
return 0;
}
static int hpsa_passthru_ioctl(struct ctlr_info *h, void __user *argp)
{
IOCTL_Command_struct iocommand;
struct CommandList *c;
char *buff = NULL;
union u64bit temp64;
int rc = 0;
if (!argp)
return -EINVAL;
if (!capable(CAP_SYS_RAWIO))
return -EPERM;
if (copy_from_user(&iocommand, argp, sizeof(iocommand)))
return -EFAULT;
if ((iocommand.buf_size < 1) &&
(iocommand.Request.Type.Direction != XFER_NONE)) {
return -EINVAL;
}
if (iocommand.buf_size > 0) {
buff = kmalloc(iocommand.buf_size, GFP_KERNEL);
if (buff == NULL)
return -EFAULT;
if (iocommand.Request.Type.Direction == XFER_WRITE) {
/* Copy the data into the buffer we created */
if (copy_from_user(buff, iocommand.buf,
iocommand.buf_size)) {
rc = -EFAULT;
goto out_kfree;
}
} else {
memset(buff, 0, iocommand.buf_size);
}
}
c = cmd_special_alloc(h);
if (c == NULL) {
rc = -ENOMEM;
goto out_kfree;
}
/* Fill in the command type */
c->cmd_type = CMD_IOCTL_PEND;
/* Fill in Command Header */
c->Header.ReplyQueue = 0; /* unused in simple mode */
if (iocommand.buf_size > 0) { /* buffer to fill */
c->Header.SGList = 1;
c->Header.SGTotal = 1;
} else { /* no buffers to fill */
c->Header.SGList = 0;
c->Header.SGTotal = 0;
}
memcpy(&c->Header.LUN, &iocommand.LUN_info, sizeof(c->Header.LUN));
/* use the kernel address the cmd block for tag */
c->Header.Tag.lower = c->busaddr;
/* Fill in Request block */
memcpy(&c->Request, &iocommand.Request,
sizeof(c->Request));
/* Fill in the scatter gather information */
if (iocommand.buf_size > 0) {
temp64.val = pci_map_single(h->pdev, buff,
iocommand.buf_size, PCI_DMA_BIDIRECTIONAL);
if (dma_mapping_error(&h->pdev->dev, temp64.val)) {
c->SG[0].Addr.lower = 0;
c->SG[0].Addr.upper = 0;
c->SG[0].Len = 0;
rc = -ENOMEM;
goto out;
}
c->SG[0].Addr.lower = temp64.val32.lower;
c->SG[0].Addr.upper = temp64.val32.upper;
c->SG[0].Len = iocommand.buf_size;
c->SG[0].Ext = 0; /* we are not chaining*/
}
hpsa_scsi_do_simple_cmd_core_if_no_lockup(h, c);
if (iocommand.buf_size > 0)
hpsa_pci_unmap(h->pdev, c, 1, PCI_DMA_BIDIRECTIONAL);
check_ioctl_unit_attention(h, c);
/* Copy the error information out */
memcpy(&iocommand.error_info, c->err_info,
sizeof(iocommand.error_info));
if (copy_to_user(argp, &iocommand, sizeof(iocommand))) {
rc = -EFAULT;
goto out;
}
if (iocommand.Request.Type.Direction == XFER_READ &&
iocommand.buf_size > 0) {
/* Copy the data out of the buffer we created */
if (copy_to_user(iocommand.buf, buff, iocommand.buf_size)) {
rc = -EFAULT;
goto out;
}
}
out:
cmd_special_free(h, c);
out_kfree:
kfree(buff);
return rc;
}
static int hpsa_big_passthru_ioctl(struct ctlr_info *h, void __user *argp)
{
BIG_IOCTL_Command_struct *ioc;
struct CommandList *c;
unsigned char **buff = NULL;
int *buff_size = NULL;
union u64bit temp64;
BYTE sg_used = 0;
int status = 0;
int i;
u32 left;
u32 sz;
BYTE __user *data_ptr;
if (!argp)
return -EINVAL;
if (!capable(CAP_SYS_RAWIO))
return -EPERM;
ioc = (BIG_IOCTL_Command_struct *)
kmalloc(sizeof(*ioc), GFP_KERNEL);
if (!ioc) {
status = -ENOMEM;
goto cleanup1;
}
if (copy_from_user(ioc, argp, sizeof(*ioc))) {
status = -EFAULT;
goto cleanup1;
}
if ((ioc->buf_size < 1) &&
(ioc->Request.Type.Direction != XFER_NONE)) {
status = -EINVAL;
goto cleanup1;
}
/* Check kmalloc limits using all SGs */
if (ioc->malloc_size > MAX_KMALLOC_SIZE) {
status = -EINVAL;
goto cleanup1;
}
if (ioc->buf_size > ioc->malloc_size * SG_ENTRIES_IN_CMD) {
status = -EINVAL;
goto cleanup1;
}
buff = kzalloc(SG_ENTRIES_IN_CMD * sizeof(char *), GFP_KERNEL);
if (!buff) {
status = -ENOMEM;
goto cleanup1;
}
buff_size = kmalloc(SG_ENTRIES_IN_CMD * sizeof(int), GFP_KERNEL);
if (!buff_size) {
status = -ENOMEM;
goto cleanup1;
}
left = ioc->buf_size;
data_ptr = ioc->buf;
while (left) {
sz = (left > ioc->malloc_size) ? ioc->malloc_size : left;
buff_size[sg_used] = sz;
buff[sg_used] = kmalloc(sz, GFP_KERNEL);
if (buff[sg_used] == NULL) {
status = -ENOMEM;
goto cleanup1;
}
if (ioc->Request.Type.Direction == XFER_WRITE) {
if (copy_from_user(buff[sg_used], data_ptr, sz)) {
status = -ENOMEM;
goto cleanup1;
}
} else
memset(buff[sg_used], 0, sz);
left -= sz;
data_ptr += sz;
sg_used++;
}
c = cmd_special_alloc(h);
if (c == NULL) {
status = -ENOMEM;
goto cleanup1;
}
c->cmd_type = CMD_IOCTL_PEND;
c->Header.ReplyQueue = 0;
c->Header.SGList = c->Header.SGTotal = sg_used;
memcpy(&c->Header.LUN, &ioc->LUN_info, sizeof(c->Header.LUN));
c->Header.Tag.lower = c->busaddr;
memcpy(&c->Request, &ioc->Request, sizeof(c->Request));
if (ioc->buf_size > 0) {
int i;
for (i = 0; i < sg_used; i++) {
temp64.val = pci_map_single(h->pdev, buff[i],
buff_size[i], PCI_DMA_BIDIRECTIONAL);
if (dma_mapping_error(&h->pdev->dev, temp64.val)) {
c->SG[i].Addr.lower = 0;
c->SG[i].Addr.upper = 0;
c->SG[i].Len = 0;
hpsa_pci_unmap(h->pdev, c, i,
PCI_DMA_BIDIRECTIONAL);
status = -ENOMEM;
goto cleanup1;
}
c->SG[i].Addr.lower = temp64.val32.lower;
c->SG[i].Addr.upper = temp64.val32.upper;
c->SG[i].Len = buff_size[i];
/* we are not chaining */
c->SG[i].Ext = 0;
}
}
hpsa_scsi_do_simple_cmd_core_if_no_lockup(h, c);
if (sg_used)
hpsa_pci_unmap(h->pdev, c, sg_used, PCI_DMA_BIDIRECTIONAL);
check_ioctl_unit_attention(h, c);
/* Copy the error information out */
memcpy(&ioc->error_info, c->err_info, sizeof(ioc->error_info));
if (copy_to_user(argp, ioc, sizeof(*ioc))) {
cmd_special_free(h, c);
status = -EFAULT;
goto cleanup1;
}
if (ioc->Request.Type.Direction == XFER_READ && ioc->buf_size > 0) {
/* Copy the data out of the buffer we created */
BYTE __user *ptr = ioc->buf;
for (i = 0; i < sg_used; i++) {
if (copy_to_user(ptr, buff[i], buff_size[i])) {
cmd_special_free(h, c);
status = -EFAULT;
goto cleanup1;
}
ptr += buff_size[i];
}
}
cmd_special_free(h, c);
status = 0;
cleanup1:
if (buff) {
for (i = 0; i < sg_used; i++)
kfree(buff[i]);
kfree(buff);
}
kfree(buff_size);
kfree(ioc);
return status;
}
static void check_ioctl_unit_attention(struct ctlr_info *h,
struct CommandList *c)
{
if (c->err_info->CommandStatus == CMD_TARGET_STATUS &&
c->err_info->ScsiStatus != SAM_STAT_CHECK_CONDITION)
(void) check_for_unit_attention(h, c);
}
/*
* ioctl
*/
static int hpsa_ioctl(struct scsi_device *dev, int cmd, void *arg)
{
struct ctlr_info *h;
void __user *argp = (void __user *)arg;
h = sdev_to_hba(dev);
switch (cmd) {
case CCISS_DEREGDISK:
case CCISS_REGNEWDISK:
case CCISS_REGNEWD:
hpsa_scan_start(h->scsi_host);
return 0;
case CCISS_GETPCIINFO:
return hpsa_getpciinfo_ioctl(h, argp);
case CCISS_GETDRIVVER:
return hpsa_getdrivver_ioctl(h, argp);
case CCISS_PASSTHRU:
return hpsa_passthru_ioctl(h, argp);
case CCISS_BIG_PASSTHRU:
return hpsa_big_passthru_ioctl(h, argp);
default:
return -ENOTTY;
}
}
static int hpsa_send_host_reset(struct ctlr_info *h, unsigned char *scsi3addr,
u8 reset_type)
{
struct CommandList *c;
c = cmd_alloc(h);
if (!c)
return -ENOMEM;
/* fill_cmd can't fail here, no data buffer to map */
(void) fill_cmd(c, HPSA_DEVICE_RESET_MSG, h, NULL, 0, 0,
RAID_CTLR_LUNID, TYPE_MSG);
c->Request.CDB[1] = reset_type; /* fill_cmd defaults to target reset */
c->waiting = NULL;
enqueue_cmd_and_start_io(h, c);
/* Don't wait for completion, the reset won't complete. Don't free
* the command either. This is the last command we will send before
* re-initializing everything, so it doesn't matter and won't leak.
*/
return 0;
}
static int fill_cmd(struct CommandList *c, u8 cmd, struct ctlr_info *h,
void *buff, size_t size, u8 page_code, unsigned char *scsi3addr,
int cmd_type)
{
int pci_dir = XFER_NONE;
struct CommandList *a; /* for commands to be aborted */
c->cmd_type = CMD_IOCTL_PEND;
c->Header.ReplyQueue = 0;
if (buff != NULL && size > 0) {
c->Header.SGList = 1;
c->Header.SGTotal = 1;
} else {
c->Header.SGList = 0;
c->Header.SGTotal = 0;
}
c->Header.Tag.lower = c->busaddr;
memcpy(c->Header.LUN.LunAddrBytes, scsi3addr, 8);
c->Request.Type.Type = cmd_type;
if (cmd_type == TYPE_CMD) {
switch (cmd) {
case HPSA_INQUIRY:
/* are we trying to read a vital product page */
if (page_code != 0) {
c->Request.CDB[1] = 0x01;
c->Request.CDB[2] = page_code;
}
c->Request.CDBLen = 6;
c->Request.Type.Attribute = ATTR_SIMPLE;
c->Request.Type.Direction = XFER_READ;
c->Request.Timeout = 0;
c->Request.CDB[0] = HPSA_INQUIRY;
c->Request.CDB[4] = size & 0xFF;
break;
case HPSA_REPORT_LOG:
case HPSA_REPORT_PHYS:
/* Talking to controller so It's a physical command
mode = 00 target = 0. Nothing to write.
*/
c->Request.CDBLen = 12;
c->Request.Type.Attribute = ATTR_SIMPLE;
c->Request.Type.Direction = XFER_READ;
c->Request.Timeout = 0;
c->Request.CDB[0] = cmd;
c->Request.CDB[6] = (size >> 24) & 0xFF; /* MSB */
c->Request.CDB[7] = (size >> 16) & 0xFF;
c->Request.CDB[8] = (size >> 8) & 0xFF;
c->Request.CDB[9] = size & 0xFF;
break;
case HPSA_CACHE_FLUSH:
c->Request.CDBLen = 12;
c->Request.Type.Attribute = ATTR_SIMPLE;
c->Request.Type.Direction = XFER_WRITE;
c->Request.Timeout = 0;
c->Request.CDB[0] = BMIC_WRITE;
c->Request.CDB[6] = BMIC_CACHE_FLUSH;
c->Request.CDB[7] = (size >> 8) & 0xFF;
c->Request.CDB[8] = size & 0xFF;
break;
case TEST_UNIT_READY:
c->Request.CDBLen = 6;
c->Request.Type.Attribute = ATTR_SIMPLE;
c->Request.Type.Direction = XFER_NONE;
c->Request.Timeout = 0;
break;
default:
dev_warn(&h->pdev->dev, "unknown command 0x%c\n", cmd);
BUG();
return -1;
}
} else if (cmd_type == TYPE_MSG) {
switch (cmd) {
case HPSA_DEVICE_RESET_MSG:
c->Request.CDBLen = 16;
c->Request.Type.Type = 1; /* It is a MSG not a CMD */
c->Request.Type.Attribute = ATTR_SIMPLE;
c->Request.Type.Direction = XFER_NONE;
c->Request.Timeout = 0; /* Don't time out */
memset(&c->Request.CDB[0], 0, sizeof(c->Request.CDB));
c->Request.CDB[0] = cmd;
c->Request.CDB[1] = HPSA_RESET_TYPE_LUN;
/* If bytes 4-7 are zero, it means reset the */
/* LunID device */
c->Request.CDB[4] = 0x00;
c->Request.CDB[5] = 0x00;
c->Request.CDB[6] = 0x00;
c->Request.CDB[7] = 0x00;
break;
case HPSA_ABORT_MSG:
a = buff; /* point to command to be aborted */
dev_dbg(&h->pdev->dev, "Abort Tag:0x%08x:%08x using request Tag:0x%08x:%08x\n",
a->Header.Tag.upper, a->Header.Tag.lower,
c->Header.Tag.upper, c->Header.Tag.lower);
c->Request.CDBLen = 16;
c->Request.Type.Type = TYPE_MSG;
c->Request.Type.Attribute = ATTR_SIMPLE;
c->Request.Type.Direction = XFER_WRITE;
c->Request.Timeout = 0; /* Don't time out */
c->Request.CDB[0] = HPSA_TASK_MANAGEMENT;
c->Request.CDB[1] = HPSA_TMF_ABORT_TASK;
c->Request.CDB[2] = 0x00; /* reserved */
c->Request.CDB[3] = 0x00; /* reserved */
/* Tag to abort goes in CDB[4]-CDB[11] */
c->Request.CDB[4] = a->Header.Tag.lower & 0xFF;
c->Request.CDB[5] = (a->Header.Tag.lower >> 8) & 0xFF;
c->Request.CDB[6] = (a->Header.Tag.lower >> 16) & 0xFF;
c->Request.CDB[7] = (a->Header.Tag.lower >> 24) & 0xFF;
c->Request.CDB[8] = a->Header.Tag.upper & 0xFF;
c->Request.CDB[9] = (a->Header.Tag.upper >> 8) & 0xFF;
c->Request.CDB[10] = (a->Header.Tag.upper >> 16) & 0xFF;
c->Request.CDB[11] = (a->Header.Tag.upper >> 24) & 0xFF;
c->Request.CDB[12] = 0x00; /* reserved */
c->Request.CDB[13] = 0x00; /* reserved */
c->Request.CDB[14] = 0x00; /* reserved */
c->Request.CDB[15] = 0x00; /* reserved */
break;
default:
dev_warn(&h->pdev->dev, "unknown message type %d\n",
cmd);
BUG();
}
} else {
dev_warn(&h->pdev->dev, "unknown command type %d\n", cmd_type);
BUG();
}
switch (c->Request.Type.Direction) {
case XFER_READ:
pci_dir = PCI_DMA_FROMDEVICE;
break;
case XFER_WRITE:
pci_dir = PCI_DMA_TODEVICE;
break;
case XFER_NONE:
pci_dir = PCI_DMA_NONE;
break;
default:
pci_dir = PCI_DMA_BIDIRECTIONAL;
}
if (hpsa_map_one(h->pdev, c, buff, size, pci_dir))
return -1;
return 0;
}
/*
* Map (physical) PCI mem into (virtual) kernel space
*/
static void __iomem *remap_pci_mem(ulong base, ulong size)
{
ulong page_base = ((ulong) base) & PAGE_MASK;
ulong page_offs = ((ulong) base) - page_base;
void __iomem *page_remapped = ioremap_nocache(page_base,
page_offs + size);
return page_remapped ? (page_remapped + page_offs) : NULL;
}
/* Takes cmds off the submission queue and sends them to the hardware,
* then puts them on the queue of cmds waiting for completion.
*/
static void start_io(struct ctlr_info *h)
{
struct CommandList *c;
unsigned long flags;
spin_lock_irqsave(&h->lock, flags);
while (!list_empty(&h->reqQ)) {
c = list_entry(h->reqQ.next, struct CommandList, list);
/* can't do anything if fifo is full */
if ((h->access.fifo_full(h))) {
dev_warn(&h->pdev->dev, "fifo full\n");
break;
}
/* Get the first entry from the Request Q */
removeQ(c);
h->Qdepth--;
/* Put job onto the completed Q */
addQ(&h->cmpQ, c);
/* Must increment commands_outstanding before unlocking
* and submitting to avoid race checking for fifo full
* condition.
*/
h->commands_outstanding++;
if (h->commands_outstanding > h->max_outstanding)
h->max_outstanding = h->commands_outstanding;
/* Tell the controller execute command */
spin_unlock_irqrestore(&h->lock, flags);
h->access.submit_command(h, c);
spin_lock_irqsave(&h->lock, flags);
}
spin_unlock_irqrestore(&h->lock, flags);
}
static inline unsigned long get_next_completion(struct ctlr_info *h, u8 q)
{
return h->access.command_completed(h, q);
}
static inline bool interrupt_pending(struct ctlr_info *h)
{
return h->access.intr_pending(h);
}
static inline long interrupt_not_for_us(struct ctlr_info *h)
{
return (h->access.intr_pending(h) == 0) ||
(h->interrupts_enabled == 0);
}
static inline int bad_tag(struct ctlr_info *h, u32 tag_index,
u32 raw_tag)
{
if (unlikely(tag_index >= h->nr_cmds)) {
dev_warn(&h->pdev->dev, "bad tag 0x%08x ignored.\n", raw_tag);
return 1;
}
return 0;
}
static inline void finish_cmd(struct CommandList *c)
{
unsigned long flags;
spin_lock_irqsave(&c->h->lock, flags);
removeQ(c);
spin_unlock_irqrestore(&c->h->lock, flags);
dial_up_lockup_detection_on_fw_flash_complete(c->h, c);
if (likely(c->cmd_type == CMD_SCSI))
complete_scsi_command(c);
else if (c->cmd_type == CMD_IOCTL_PEND)
complete(c->waiting);
}
static inline u32 hpsa_tag_contains_index(u32 tag)
{
return tag & DIRECT_LOOKUP_BIT;
}
static inline u32 hpsa_tag_to_index(u32 tag)
{
return tag >> DIRECT_LOOKUP_SHIFT;
}
static inline u32 hpsa_tag_discard_error_bits(struct ctlr_info *h, u32 tag)
{
#define HPSA_PERF_ERROR_BITS ((1 << DIRECT_LOOKUP_SHIFT) - 1)
#define HPSA_SIMPLE_ERROR_BITS 0x03
if (unlikely(!(h->transMethod & CFGTBL_Trans_Performant)))
return tag & ~HPSA_SIMPLE_ERROR_BITS;
return tag & ~HPSA_PERF_ERROR_BITS;
}
/* process completion of an indexed ("direct lookup") command */
static inline void process_indexed_cmd(struct ctlr_info *h,
u32 raw_tag)
{
u32 tag_index;
struct CommandList *c;
tag_index = hpsa_tag_to_index(raw_tag);
if (!bad_tag(h, tag_index, raw_tag)) {
c = h->cmd_pool + tag_index;
finish_cmd(c);
}
}
/* process completion of a non-indexed command */
static inline void process_nonindexed_cmd(struct ctlr_info *h,
u32 raw_tag)
{
u32 tag;
struct CommandList *c = NULL;
unsigned long flags;
tag = hpsa_tag_discard_error_bits(h, raw_tag);
spin_lock_irqsave(&h->lock, flags);
list_for_each_entry(c, &h->cmpQ, list) {
if ((c->busaddr & 0xFFFFFFE0) == (tag & 0xFFFFFFE0)) {
spin_unlock_irqrestore(&h->lock, flags);
finish_cmd(c);
return;
}
}
spin_unlock_irqrestore(&h->lock, flags);
bad_tag(h, h->nr_cmds + 1, raw_tag);
}
/* Some controllers, like p400, will give us one interrupt
* after a soft reset, even if we turned interrupts off.
* Only need to check for this in the hpsa_xxx_discard_completions
* functions.
*/
static int ignore_bogus_interrupt(struct ctlr_info *h)
{
if (likely(!reset_devices))
return 0;
if (likely(h->interrupts_enabled))
return 0;
dev_info(&h->pdev->dev, "Received interrupt while interrupts disabled "
"(known firmware bug.) Ignoring.\n");
return 1;
}
/*
* Convert &h->q[x] (passed to interrupt handlers) back to h.
* Relies on (h-q[x] == x) being true for x such that
* 0 <= x < MAX_REPLY_QUEUES.
*/
static struct ctlr_info *queue_to_hba(u8 *queue)
{
return container_of((queue - *queue), struct ctlr_info, q[0]);
}
static irqreturn_t hpsa_intx_discard_completions(int irq, void *queue)
{
struct ctlr_info *h = queue_to_hba(queue);
u8 q = *(u8 *) queue;
u32 raw_tag;
if (ignore_bogus_interrupt(h))
return IRQ_NONE;
if (interrupt_not_for_us(h))
return IRQ_NONE;
h->last_intr_timestamp = get_jiffies_64();
while (interrupt_pending(h)) {
raw_tag = get_next_completion(h, q);
while (raw_tag != FIFO_EMPTY)
raw_tag = next_command(h, q);
}
return IRQ_HANDLED;
}
static irqreturn_t hpsa_msix_discard_completions(int irq, void *queue)
{
struct ctlr_info *h = queue_to_hba(queue);
u32 raw_tag;
u8 q = *(u8 *) queue;
if (ignore_bogus_interrupt(h))
return IRQ_NONE;
h->last_intr_timestamp = get_jiffies_64();
raw_tag = get_next_completion(h, q);
while (raw_tag != FIFO_EMPTY)
raw_tag = next_command(h, q);
return IRQ_HANDLED;
}
static irqreturn_t do_hpsa_intr_intx(int irq, void *queue)
{
struct ctlr_info *h = queue_to_hba((u8 *) queue);
u32 raw_tag;
u8 q = *(u8 *) queue;
if (interrupt_not_for_us(h))
return IRQ_NONE;
h->last_intr_timestamp = get_jiffies_64();
while (interrupt_pending(h)) {
raw_tag = get_next_completion(h, q);
while (raw_tag != FIFO_EMPTY) {
if (likely(hpsa_tag_contains_index(raw_tag)))
process_indexed_cmd(h, raw_tag);
else
process_nonindexed_cmd(h, raw_tag);
raw_tag = next_command(h, q);
}
}
return IRQ_HANDLED;
}
static irqreturn_t do_hpsa_intr_msi(int irq, void *queue)
{
struct ctlr_info *h = queue_to_hba(queue);
u32 raw_tag;
u8 q = *(u8 *) queue;
h->last_intr_timestamp = get_jiffies_64();
raw_tag = get_next_completion(h, q);
while (raw_tag != FIFO_EMPTY) {
if (likely(hpsa_tag_contains_index(raw_tag)))
process_indexed_cmd(h, raw_tag);
else
process_nonindexed_cmd(h, raw_tag);
raw_tag = next_command(h, q);
}
return IRQ_HANDLED;
}
/* Send a message CDB to the firmware. Careful, this only works
* in simple mode, not performant mode due to the tag lookup.
* We only ever use this immediately after a controller reset.
*/
static int hpsa_message(struct pci_dev *pdev, unsigned char opcode,
unsigned char type)
{
struct Command {
struct CommandListHeader CommandHeader;
struct RequestBlock Request;
struct ErrDescriptor ErrorDescriptor;
};
struct Command *cmd;
static const size_t cmd_sz = sizeof(*cmd) +
sizeof(cmd->ErrorDescriptor);
dma_addr_t paddr64;
uint32_t paddr32, tag;
void __iomem *vaddr;
int i, err;
vaddr = pci_ioremap_bar(pdev, 0);
if (vaddr == NULL)
return -ENOMEM;
/* The Inbound Post Queue only accepts 32-bit physical addresses for the
* CCISS commands, so they must be allocated from the lower 4GiB of
* memory.
*/
err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32));
if (err) {
iounmap(vaddr);
return -ENOMEM;
}
cmd = pci_alloc_consistent(pdev, cmd_sz, &paddr64);
if (cmd == NULL) {
iounmap(vaddr);
return -ENOMEM;
}
/* This must fit, because of the 32-bit consistent DMA mask. Also,
* although there's no guarantee, we assume that the address is at
* least 4-byte aligned (most likely, it's page-aligned).
*/
paddr32 = paddr64;
cmd->CommandHeader.ReplyQueue = 0;
cmd->CommandHeader.SGList = 0;
cmd->CommandHeader.SGTotal = 0;
cmd->CommandHeader.Tag.lower = paddr32;
cmd->CommandHeader.Tag.upper = 0;
memset(&cmd->CommandHeader.LUN.LunAddrBytes, 0, 8);
cmd->Request.CDBLen = 16;
cmd->Request.Type.Type = TYPE_MSG;
cmd->Request.Type.Attribute = ATTR_HEADOFQUEUE;
cmd->Request.Type.Direction = XFER_NONE;
cmd->Request.Timeout = 0; /* Don't time out */
cmd->Request.CDB[0] = opcode;
cmd->Request.CDB[1] = type;
memset(&cmd->Request.CDB[2], 0, 14); /* rest of the CDB is reserved */
cmd->ErrorDescriptor.Addr.lower = paddr32 + sizeof(*cmd);
cmd->ErrorDescriptor.Addr.upper = 0;
cmd->ErrorDescriptor.Len = sizeof(struct ErrorInfo);
writel(paddr32, vaddr + SA5_REQUEST_PORT_OFFSET);
for (i = 0; i < HPSA_MSG_SEND_RETRY_LIMIT; i++) {
tag = readl(vaddr + SA5_REPLY_PORT_OFFSET);
if ((tag & ~HPSA_SIMPLE_ERROR_BITS) == paddr32)
break;
msleep(HPSA_MSG_SEND_RETRY_INTERVAL_MSECS);
}
iounmap(vaddr);
/* we leak the DMA buffer here ... no choice since the controller could
* still complete the command.
*/
if (i == HPSA_MSG_SEND_RETRY_LIMIT) {
dev_err(&pdev->dev, "controller message %02x:%02x timed out\n",
opcode, type);
return -ETIMEDOUT;
}
pci_free_consistent(pdev, cmd_sz, cmd, paddr64);
if (tag & HPSA_ERROR_BIT) {
dev_err(&pdev->dev, "controller message %02x:%02x failed\n",
opcode, type);
return -EIO;
}
dev_info(&pdev->dev, "controller message %02x:%02x succeeded\n",
opcode, type);
return 0;
}
#define hpsa_noop(p) hpsa_message(p, 3, 0)
static int hpsa_controller_hard_reset(struct pci_dev *pdev,
void * __iomem vaddr, u32 use_doorbell)
{
u16 pmcsr;
int pos;
if (use_doorbell) {
/* For everything after the P600, the PCI power state method
* of resetting the controller doesn't work, so we have this
* other way using the doorbell register.
*/
dev_info(&pdev->dev, "using doorbell to reset controller\n");
writel(use_doorbell, vaddr + SA5_DOORBELL);
} else { /* Try to do it the PCI power state way */
/* Quoting from the Open CISS Specification: "The Power
* Management Control/Status Register (CSR) controls the power
* state of the device. The normal operating state is D0,
* CSR=00h. The software off state is D3, CSR=03h. To reset
* the controller, place the interface device in D3 then to D0,
* this causes a secondary PCI reset which will reset the
* controller." */
pos = pci_find_capability(pdev, PCI_CAP_ID_PM);
if (pos == 0) {
dev_err(&pdev->dev,
"hpsa_reset_controller: "
"PCI PM not supported\n");
return -ENODEV;
}
dev_info(&pdev->dev, "using PCI PM to reset controller\n");
/* enter the D3hot power management state */
pci_read_config_word(pdev, pos + PCI_PM_CTRL, &pmcsr);
pmcsr &= ~PCI_PM_CTRL_STATE_MASK;
pmcsr |= PCI_D3hot;
pci_write_config_word(pdev, pos + PCI_PM_CTRL, pmcsr);
msleep(500);
/* enter the D0 power management state */
pmcsr &= ~PCI_PM_CTRL_STATE_MASK;
pmcsr |= PCI_D0;
pci_write_config_word(pdev, pos + PCI_PM_CTRL, pmcsr);
/*
* The P600 requires a small delay when changing states.
* Otherwise we may think the board did not reset and we bail.
* This for kdump only and is particular to the P600.
*/
msleep(500);
}
return 0;
}
static void init_driver_version(char *driver_version, int len)
{
memset(driver_version, 0, len);
strncpy(driver_version, HPSA " " HPSA_DRIVER_VERSION, len - 1);
}
static int write_driver_ver_to_cfgtable(struct CfgTable __iomem *cfgtable)
{
char *driver_version;
int i, size = sizeof(cfgtable->driver_version);
driver_version = kmalloc(size, GFP_KERNEL);
if (!driver_version)
return -ENOMEM;
init_driver_version(driver_version, size);
for (i = 0; i < size; i++)
writeb(driver_version[i], &cfgtable->driver_version[i]);
kfree(driver_version);
return 0;
}
static void read_driver_ver_from_cfgtable(struct CfgTable __iomem *cfgtable,
unsigned char *driver_ver)
{
int i;
for (i = 0; i < sizeof(cfgtable->driver_version); i++)
driver_ver[i] = readb(&cfgtable->driver_version[i]);
}
static int controller_reset_failed(struct CfgTable __iomem *cfgtable)
{
char *driver_ver, *old_driver_ver;
int rc, size = sizeof(cfgtable->driver_version);
old_driver_ver = kmalloc(2 * size, GFP_KERNEL);
if (!old_driver_ver)
return -ENOMEM;
driver_ver = old_driver_ver + size;
/* After a reset, the 32 bytes of "driver version" in the cfgtable
* should have been changed, otherwise we know the reset failed.
*/
init_driver_version(old_driver_ver, size);
read_driver_ver_from_cfgtable(cfgtable, driver_ver);
rc = !memcmp(driver_ver, old_driver_ver, size);
kfree(old_driver_ver);
return rc;
}
/* This does a hard reset of the controller using PCI power management
* states or the using the doorbell register.
*/
static int hpsa_kdump_hard_reset_controller(struct pci_dev *pdev)
{
u64 cfg_offset;
u32 cfg_base_addr;
u64 cfg_base_addr_index;
void __iomem *vaddr;
unsigned long paddr;
u32 misc_fw_support;
int rc;
struct CfgTable __iomem *cfgtable;
u32 use_doorbell;
u32 board_id;
u16 command_register;
/* For controllers as old as the P600, this is very nearly
* the same thing as
*
* pci_save_state(pci_dev);
* pci_set_power_state(pci_dev, PCI_D3hot);
* pci_set_power_state(pci_dev, PCI_D0);
* pci_restore_state(pci_dev);
*
* For controllers newer than the P600, the pci power state
* method of resetting doesn't work so we have another way
* using the doorbell register.
*/
rc = hpsa_lookup_board_id(pdev, &board_id);
if (rc < 0 || !ctlr_is_resettable(board_id)) {
dev_warn(&pdev->dev, "Not resetting device.\n");
return -ENODEV;
}
/* if controller is soft- but not hard resettable... */
if (!ctlr_is_hard_resettable(board_id))
return -ENOTSUPP; /* try soft reset later. */
/* Save the PCI command register */
pci_read_config_word(pdev, 4, &command_register);
/* Turn the board off. This is so that later pci_restore_state()
* won't turn the board on before the rest of config space is ready.
*/
pci_disable_device(pdev);
pci_save_state(pdev);
/* find the first memory BAR, so we can find the cfg table */
rc = hpsa_pci_find_memory_BAR(pdev, &paddr);
if (rc)
return rc;
vaddr = remap_pci_mem(paddr, 0x250);
if (!vaddr)
return -ENOMEM;
/* find cfgtable in order to check if reset via doorbell is supported */
rc = hpsa_find_cfg_addrs(pdev, vaddr, &cfg_base_addr,
&cfg_base_addr_index, &cfg_offset);
if (rc)
goto unmap_vaddr;
cfgtable = remap_pci_mem(pci_resource_start(pdev,
cfg_base_addr_index) + cfg_offset, sizeof(*cfgtable));
if (!cfgtable) {
rc = -ENOMEM;
goto unmap_vaddr;
}
rc = write_driver_ver_to_cfgtable(cfgtable);
if (rc)
goto unmap_vaddr;
/* If reset via doorbell register is supported, use that.
* There are two such methods. Favor the newest method.
*/
misc_fw_support = readl(&cfgtable->misc_fw_support);
use_doorbell = misc_fw_support & MISC_FW_DOORBELL_RESET2;
if (use_doorbell) {
use_doorbell = DOORBELL_CTLR_RESET2;
} else {
use_doorbell = misc_fw_support & MISC_FW_DOORBELL_RESET;
if (use_doorbell) {
dev_warn(&pdev->dev, "Soft reset not supported. "
"Firmware update is required.\n");
rc = -ENOTSUPP; /* try soft reset */
goto unmap_cfgtable;
}
}
rc = hpsa_controller_hard_reset(pdev, vaddr, use_doorbell);
if (rc)
goto unmap_cfgtable;
pci_restore_state(pdev);
rc = pci_enable_device(pdev);
if (rc) {
dev_warn(&pdev->dev, "failed to enable device.\n");
goto unmap_cfgtable;
}
pci_write_config_word(pdev, 4, command_register);
/* Some devices (notably the HP Smart Array 5i Controller)
need a little pause here */
msleep(HPSA_POST_RESET_PAUSE_MSECS);
/* Wait for board to become not ready, then ready. */
dev_info(&pdev->dev, "Waiting for board to reset.\n");
rc = hpsa_wait_for_board_state(pdev, vaddr, BOARD_NOT_READY);
if (rc) {
dev_warn(&pdev->dev,
"failed waiting for board to reset."
" Will try soft reset.\n");
rc = -ENOTSUPP; /* Not expected, but try soft reset later */
goto unmap_cfgtable;
}
rc = hpsa_wait_for_board_state(pdev, vaddr, BOARD_READY);
if (rc) {
dev_warn(&pdev->dev,
"failed waiting for board to become ready "
"after hard reset\n");
goto unmap_cfgtable;
}
rc = controller_reset_failed(vaddr);
if (rc < 0)
goto unmap_cfgtable;
if (rc) {
dev_warn(&pdev->dev, "Unable to successfully reset "
"controller. Will try soft reset.\n");
rc = -ENOTSUPP;
} else {
dev_info(&pdev->dev, "board ready after hard reset.\n");
}
unmap_cfgtable:
iounmap(cfgtable);
unmap_vaddr:
iounmap(vaddr);
return rc;
}
/*
* We cannot read the structure directly, for portability we must use
* the io functions.
* This is for debug only.
*/
static void print_cfg_table(struct device *dev, struct CfgTable *tb)
{
#ifdef HPSA_DEBUG
int i;
char temp_name[17];
dev_info(dev, "Controller Configuration information\n");
dev_info(dev, "------------------------------------\n");
for (i = 0; i < 4; i++)
temp_name[i] = readb(&(tb->Signature[i]));
temp_name[4] = '\0';
dev_info(dev, " Signature = %s\n", temp_name);
dev_info(dev, " Spec Number = %d\n", readl(&(tb->SpecValence)));
dev_info(dev, " Transport methods supported = 0x%x\n",
readl(&(tb->TransportSupport)));
dev_info(dev, " Transport methods active = 0x%x\n",
readl(&(tb->TransportActive)));
dev_info(dev, " Requested transport Method = 0x%x\n",
readl(&(tb->HostWrite.TransportRequest)));
dev_info(dev, " Coalesce Interrupt Delay = 0x%x\n",
readl(&(tb->HostWrite.CoalIntDelay)));
dev_info(dev, " Coalesce Interrupt Count = 0x%x\n",
readl(&(tb->HostWrite.CoalIntCount)));
dev_info(dev, " Max outstanding commands = 0x%d\n",
readl(&(tb->CmdsOutMax)));
dev_info(dev, " Bus Types = 0x%x\n", readl(&(tb->BusTypes)));
for (i = 0; i < 16; i++)
temp_name[i] = readb(&(tb->ServerName[i]));
temp_name[16] = '\0';
dev_info(dev, " Server Name = %s\n", temp_name);
dev_info(dev, " Heartbeat Counter = 0x%x\n\n\n",
readl(&(tb->HeartBeat)));
#endif /* HPSA_DEBUG */
}
static int find_PCI_BAR_index(struct pci_dev *pdev, unsigned long pci_bar_addr)
{
int i, offset, mem_type, bar_type;
if (pci_bar_addr == PCI_BASE_ADDRESS_0) /* looking for BAR zero? */
return 0;
offset = 0;
for (i = 0; i < DEVICE_COUNT_RESOURCE; i++) {
bar_type = pci_resource_flags(pdev, i) & PCI_BASE_ADDRESS_SPACE;
if (bar_type == PCI_BASE_ADDRESS_SPACE_IO)
offset += 4;
else {
mem_type = pci_resource_flags(pdev, i) &
PCI_BASE_ADDRESS_MEM_TYPE_MASK;
switch (mem_type) {
case PCI_BASE_ADDRESS_MEM_TYPE_32:
case PCI_BASE_ADDRESS_MEM_TYPE_1M:
offset += 4; /* 32 bit */
break;
case PCI_BASE_ADDRESS_MEM_TYPE_64:
offset += 8;
break;
default: /* reserved in PCI 2.2 */
dev_warn(&pdev->dev,
"base address is invalid\n");
return -1;
break;
}
}
if (offset == pci_bar_addr - PCI_BASE_ADDRESS_0)
return i + 1;
}
return -1;
}
/* If MSI/MSI-X is supported by the kernel we will try to enable it on
* controllers that are capable. If not, we use IO-APIC mode.
*/
static void hpsa_interrupt_mode(struct ctlr_info *h)
{
#ifdef CONFIG_PCI_MSI
int err, i;
struct msix_entry hpsa_msix_entries[MAX_REPLY_QUEUES];
for (i = 0; i < MAX_REPLY_QUEUES; i++) {
hpsa_msix_entries[i].vector = 0;
hpsa_msix_entries[i].entry = i;
}
/* Some boards advertise MSI but don't really support it */
if ((h->board_id == 0x40700E11) || (h->board_id == 0x40800E11) ||
(h->board_id == 0x40820E11) || (h->board_id == 0x40830E11))
goto default_int_mode;
if (pci_find_capability(h->pdev, PCI_CAP_ID_MSIX)) {
dev_info(&h->pdev->dev, "MSIX\n");
err = pci_enable_msix(h->pdev, hpsa_msix_entries,
MAX_REPLY_QUEUES);
if (!err) {
for (i = 0; i < MAX_REPLY_QUEUES; i++)
h->intr[i] = hpsa_msix_entries[i].vector;
h->msix_vector = 1;
return;
}
if (err > 0) {
dev_warn(&h->pdev->dev, "only %d MSI-X vectors "
"available\n", err);
goto default_int_mode;
} else {
dev_warn(&h->pdev->dev, "MSI-X init failed %d\n",
err);
goto default_int_mode;
}
}
if (pci_find_capability(h->pdev, PCI_CAP_ID_MSI)) {
dev_info(&h->pdev->dev, "MSI\n");
if (!pci_enable_msi(h->pdev))
h->msi_vector = 1;
else
dev_warn(&h->pdev->dev, "MSI init failed\n");
}
default_int_mode:
#endif /* CONFIG_PCI_MSI */
/* if we get here we're going to use the default interrupt mode */
h->intr[h->intr_mode] = h->pdev->irq;
}
static int hpsa_lookup_board_id(struct pci_dev *pdev, u32 *board_id)
{
int i;
u32 subsystem_vendor_id, subsystem_device_id;
subsystem_vendor_id = pdev->subsystem_vendor;
subsystem_device_id = pdev->subsystem_device;
*board_id = ((subsystem_device_id << 16) & 0xffff0000) |
subsystem_vendor_id;
for (i = 0; i < ARRAY_SIZE(products); i++)
if (*board_id == products[i].board_id)
return i;
if ((subsystem_vendor_id != PCI_VENDOR_ID_HP &&
subsystem_vendor_id != PCI_VENDOR_ID_COMPAQ) ||
!hpsa_allow_any) {
dev_warn(&pdev->dev, "unrecognized board ID: "
"0x%08x, ignoring.\n", *board_id);
return -ENODEV;
}
return ARRAY_SIZE(products) - 1; /* generic unknown smart array */
}
static int hpsa_pci_find_memory_BAR(struct pci_dev *pdev,
unsigned long *memory_bar)
{
int i;
for (i = 0; i < DEVICE_COUNT_RESOURCE; i++)
if (pci_resource_flags(pdev, i) & IORESOURCE_MEM) {
/* addressing mode bits already removed */
*memory_bar = pci_resource_start(pdev, i);
dev_dbg(&pdev->dev, "memory BAR = %lx\n",
*memory_bar);
return 0;
}
dev_warn(&pdev->dev, "no memory BAR found\n");
return -ENODEV;
}
static int hpsa_wait_for_board_state(struct pci_dev *pdev, void __iomem *vaddr,
int wait_for_ready)
{
int i, iterations;
u32 scratchpad;
if (wait_for_ready)
iterations = HPSA_BOARD_READY_ITERATIONS;
else
iterations = HPSA_BOARD_NOT_READY_ITERATIONS;
for (i = 0; i < iterations; i++) {
scratchpad = readl(vaddr + SA5_SCRATCHPAD_OFFSET);
if (wait_for_ready) {
if (scratchpad == HPSA_FIRMWARE_READY)
return 0;
} else {
if (scratchpad != HPSA_FIRMWARE_READY)
return 0;
}
msleep(HPSA_BOARD_READY_POLL_INTERVAL_MSECS);
}
dev_warn(&pdev->dev, "board not ready, timed out.\n");
return -ENODEV;
}
static int hpsa_find_cfg_addrs(struct pci_dev *pdev, void __iomem *vaddr,
u32 *cfg_base_addr, u64 *cfg_base_addr_index,
u64 *cfg_offset)
{
*cfg_base_addr = readl(vaddr + SA5_CTCFG_OFFSET);
*cfg_offset = readl(vaddr + SA5_CTMEM_OFFSET);
*cfg_base_addr &= (u32) 0x0000ffff;
*cfg_base_addr_index = find_PCI_BAR_index(pdev, *cfg_base_addr);
if (*cfg_base_addr_index == -1) {
dev_warn(&pdev->dev, "cannot find cfg_base_addr_index\n");
return -ENODEV;
}
return 0;
}
static int hpsa_find_cfgtables(struct ctlr_info *h)
{
u64 cfg_offset;
u32 cfg_base_addr;
u64 cfg_base_addr_index;
u32 trans_offset;
int rc;
rc = hpsa_find_cfg_addrs(h->pdev, h->vaddr, &cfg_base_addr,
&cfg_base_addr_index, &cfg_offset);
if (rc)
return rc;
h->cfgtable = remap_pci_mem(pci_resource_start(h->pdev,
cfg_base_addr_index) + cfg_offset, sizeof(*h->cfgtable));
if (!h->cfgtable)
return -ENOMEM;
rc = write_driver_ver_to_cfgtable(h->cfgtable);
if (rc)
return rc;
/* Find performant mode table. */
trans_offset = readl(&h->cfgtable->TransMethodOffset);
h->transtable = remap_pci_mem(pci_resource_start(h->pdev,
cfg_base_addr_index)+cfg_offset+trans_offset,
sizeof(*h->transtable));
if (!h->transtable)
return -ENOMEM;
return 0;
}
static void hpsa_get_max_perf_mode_cmds(struct ctlr_info *h)
{
h->max_commands = readl(&(h->cfgtable->MaxPerformantModeCommands));
/* Limit commands in memory limited kdump scenario. */
if (reset_devices && h->max_commands > 32)
h->max_commands = 32;
if (h->max_commands < 16) {
dev_warn(&h->pdev->dev, "Controller reports "
"max supported commands of %d, an obvious lie. "
"Using 16. Ensure that firmware is up to date.\n",
h->max_commands);
h->max_commands = 16;
}
}
/* Interrogate the hardware for some limits:
* max commands, max SG elements without chaining, and with chaining,
* SG chain block size, etc.
*/
static void hpsa_find_board_params(struct ctlr_info *h)
{
hpsa_get_max_perf_mode_cmds(h);
h->nr_cmds = h->max_commands - 4; /* Allow room for some ioctls */
h->maxsgentries = readl(&(h->cfgtable->MaxScatterGatherElements));
/*
* Limit in-command s/g elements to 32 save dma'able memory.
* Howvever spec says if 0, use 31
*/
h->max_cmd_sg_entries = 31;
if (h->maxsgentries > 512) {
h->max_cmd_sg_entries = 32;
h->chainsize = h->maxsgentries - h->max_cmd_sg_entries + 1;
h->maxsgentries--; /* save one for chain pointer */
} else {
h->maxsgentries = 31; /* default to traditional values */
h->chainsize = 0;
}
/* Find out what task management functions are supported and cache */
h->TMFSupportFlags = readl(&(h->cfgtable->TMFSupportFlags));
}
static inline bool hpsa_CISS_signature_present(struct ctlr_info *h)
{
if (!check_signature(h->cfgtable->Signature, "CISS", 4)) {
dev_warn(&h->pdev->dev, "not a valid CISS config table\n");
return false;
}
return true;
}
/* Need to enable prefetch in the SCSI core for 6400 in x86 */
static inline void hpsa_enable_scsi_prefetch(struct ctlr_info *h)
{
#ifdef CONFIG_X86
u32 prefetch;
prefetch = readl(&(h->cfgtable->SCSI_Prefetch));
prefetch |= 0x100;
writel(prefetch, &(h->cfgtable->SCSI_Prefetch));
#endif
}
/* Disable DMA prefetch for the P600. Otherwise an ASIC bug may result
* in a prefetch beyond physical memory.
*/
static inline void hpsa_p600_dma_prefetch_quirk(struct ctlr_info *h)
{
u32 dma_prefetch;
if (h->board_id != 0x3225103C)
return;
dma_prefetch = readl(h->vaddr + I2O_DMA1_CFG);
dma_prefetch |= 0x8000;
writel(dma_prefetch, h->vaddr + I2O_DMA1_CFG);
}
static void hpsa_wait_for_mode_change_ack(struct ctlr_info *h)
{
int i;
u32 doorbell_value;
unsigned long flags;
/* under certain very rare conditions, this can take awhile.
* (e.g.: hot replace a failed 144GB drive in a RAID 5 set right
* as we enter this code.)
*/
for (i = 0; i < MAX_CONFIG_WAIT; i++) {
spin_lock_irqsave(&h->lock, flags);
doorbell_value = readl(h->vaddr + SA5_DOORBELL);
spin_unlock_irqrestore(&h->lock, flags);
if (!(doorbell_value & CFGTBL_ChangeReq))
break;
/* delay and try again */
usleep_range(10000, 20000);
}
}
static int hpsa_enter_simple_mode(struct ctlr_info *h)
{
u32 trans_support;
trans_support = readl(&(h->cfgtable->TransportSupport));
if (!(trans_support & SIMPLE_MODE))
return -ENOTSUPP;
h->max_commands = readl(&(h->cfgtable->CmdsOutMax));
/* Update the field, and then ring the doorbell */
writel(CFGTBL_Trans_Simple, &(h->cfgtable->HostWrite.TransportRequest));
writel(CFGTBL_ChangeReq, h->vaddr + SA5_DOORBELL);
hpsa_wait_for_mode_change_ack(h);
print_cfg_table(&h->pdev->dev, h->cfgtable);
if (!(readl(&(h->cfgtable->TransportActive)) & CFGTBL_Trans_Simple)) {
dev_warn(&h->pdev->dev,
"unable to get board into simple mode\n");
return -ENODEV;
}
h->transMethod = CFGTBL_Trans_Simple;
return 0;
}
static int hpsa_pci_init(struct ctlr_info *h)
{
int prod_index, err;
prod_index = hpsa_lookup_board_id(h->pdev, &h->board_id);
if (prod_index < 0)
return -ENODEV;
h->product_name = products[prod_index].product_name;
h->access = *(products[prod_index].access);
pci_disable_link_state(h->pdev, PCIE_LINK_STATE_L0S |
PCIE_LINK_STATE_L1 | PCIE_LINK_STATE_CLKPM);
err = pci_enable_device(h->pdev);
if (err) {
dev_warn(&h->pdev->dev, "unable to enable PCI device\n");
return err;
}
/* Enable bus mastering (pci_disable_device may disable this) */
pci_set_master(h->pdev);
err = pci_request_regions(h->pdev, HPSA);
if (err) {
dev_err(&h->pdev->dev,
"cannot obtain PCI resources, aborting\n");
return err;
}
hpsa_interrupt_mode(h);
err = hpsa_pci_find_memory_BAR(h->pdev, &h->paddr);
if (err)
goto err_out_free_res;
h->vaddr = remap_pci_mem(h->paddr, 0x250);
if (!h->vaddr) {
err = -ENOMEM;
goto err_out_free_res;
}
err = hpsa_wait_for_board_state(h->pdev, h->vaddr, BOARD_READY);
if (err)
goto err_out_free_res;
err = hpsa_find_cfgtables(h);
if (err)
goto err_out_free_res;
hpsa_find_board_params(h);
if (!hpsa_CISS_signature_present(h)) {
err = -ENODEV;
goto err_out_free_res;
}
hpsa_enable_scsi_prefetch(h);
hpsa_p600_dma_prefetch_quirk(h);
err = hpsa_enter_simple_mode(h);
if (err)
goto err_out_free_res;
return 0;
err_out_free_res:
if (h->transtable)
iounmap(h->transtable);
if (h->cfgtable)
iounmap(h->cfgtable);
if (h->vaddr)
iounmap(h->vaddr);
pci_disable_device(h->pdev);
pci_release_regions(h->pdev);
return err;
}
static void hpsa_hba_inquiry(struct ctlr_info *h)
{
int rc;
#define HBA_INQUIRY_BYTE_COUNT 64
h->hba_inquiry_data = kmalloc(HBA_INQUIRY_BYTE_COUNT, GFP_KERNEL);
if (!h->hba_inquiry_data)
return;
rc = hpsa_scsi_do_inquiry(h, RAID_CTLR_LUNID, 0,
h->hba_inquiry_data, HBA_INQUIRY_BYTE_COUNT);
if (rc != 0) {
kfree(h->hba_inquiry_data);
h->hba_inquiry_data = NULL;
}
}
static int hpsa_init_reset_devices(struct pci_dev *pdev)
{
int rc, i;
if (!reset_devices)
return 0;
/* Reset the controller with a PCI power-cycle or via doorbell */
rc = hpsa_kdump_hard_reset_controller(pdev);
/* -ENOTSUPP here means we cannot reset the controller
* but it's already (and still) up and running in
* "performant mode". Or, it might be 640x, which can't reset
* due to concerns about shared bbwc between 6402/6404 pair.
*/
if (rc == -ENOTSUPP)
return rc; /* just try to do the kdump anyhow. */
if (rc)
return -ENODEV;
/* Now try to get the controller to respond to a no-op */
dev_warn(&pdev->dev, "Waiting for controller to respond to no-op\n");
for (i = 0; i < HPSA_POST_RESET_NOOP_RETRIES; i++) {
if (hpsa_noop(pdev) == 0)
break;
else
dev_warn(&pdev->dev, "no-op failed%s\n",
(i < 11 ? "; re-trying" : ""));
}
return 0;
}
static int hpsa_allocate_cmd_pool(struct ctlr_info *h)
{
h->cmd_pool_bits = kzalloc(
DIV_ROUND_UP(h->nr_cmds, BITS_PER_LONG) *
sizeof(unsigned long), GFP_KERNEL);
h->cmd_pool = pci_alloc_consistent(h->pdev,
h->nr_cmds * sizeof(*h->cmd_pool),
&(h->cmd_pool_dhandle));
h->errinfo_pool = pci_alloc_consistent(h->pdev,
h->nr_cmds * sizeof(*h->errinfo_pool),
&(h->errinfo_pool_dhandle));
if ((h->cmd_pool_bits == NULL)
|| (h->cmd_pool == NULL)
|| (h->errinfo_pool == NULL)) {
dev_err(&h->pdev->dev, "out of memory in %s", __func__);
return -ENOMEM;
}
return 0;
}
static void hpsa_free_cmd_pool(struct ctlr_info *h)
{
kfree(h->cmd_pool_bits);
if (h->cmd_pool)
pci_free_consistent(h->pdev,
h->nr_cmds * sizeof(struct CommandList),
h->cmd_pool, h->cmd_pool_dhandle);
if (h->errinfo_pool)
pci_free_consistent(h->pdev,
h->nr_cmds * sizeof(struct ErrorInfo),
h->errinfo_pool,
h->errinfo_pool_dhandle);
}
static int hpsa_request_irq(struct ctlr_info *h,
irqreturn_t (*msixhandler)(int, void *),
irqreturn_t (*intxhandler)(int, void *))
{
int rc, i;
/*
* initialize h->q[x] = x so that interrupt handlers know which
* queue to process.
*/
for (i = 0; i < MAX_REPLY_QUEUES; i++)
h->q[i] = (u8) i;
if (h->intr_mode == PERF_MODE_INT && h->msix_vector) {
/* If performant mode and MSI-X, use multiple reply queues */
for (i = 0; i < MAX_REPLY_QUEUES; i++)
rc = request_irq(h->intr[i], msixhandler,
0, h->devname,
&h->q[i]);
} else {
/* Use single reply pool */
if (h->msix_vector || h->msi_vector) {
rc = request_irq(h->intr[h->intr_mode],
msixhandler, 0, h->devname,
&h->q[h->intr_mode]);
} else {
rc = request_irq(h->intr[h->intr_mode],
intxhandler, IRQF_SHARED, h->devname,
&h->q[h->intr_mode]);
}
}
if (rc) {
dev_err(&h->pdev->dev, "unable to get irq %d for %s\n",
h->intr[h->intr_mode], h->devname);
return -ENODEV;
}
return 0;
}
static int hpsa_kdump_soft_reset(struct ctlr_info *h)
{
if (hpsa_send_host_reset(h, RAID_CTLR_LUNID,
HPSA_RESET_TYPE_CONTROLLER)) {
dev_warn(&h->pdev->dev, "Resetting array controller failed.\n");
return -EIO;
}
dev_info(&h->pdev->dev, "Waiting for board to soft reset.\n");
if (hpsa_wait_for_board_state(h->pdev, h->vaddr, BOARD_NOT_READY)) {
dev_warn(&h->pdev->dev, "Soft reset had no effect.\n");
return -1;
}
dev_info(&h->pdev->dev, "Board reset, awaiting READY status.\n");
if (hpsa_wait_for_board_state(h->pdev, h->vaddr, BOARD_READY)) {
dev_warn(&h->pdev->dev, "Board failed to become ready "
"after soft reset.\n");
return -1;
}
return 0;
}
static void free_irqs(struct ctlr_info *h)
{
int i;
if (!h->msix_vector || h->intr_mode != PERF_MODE_INT) {
/* Single reply queue, only one irq to free */
i = h->intr_mode;
free_irq(h->intr[i], &h->q[i]);
return;
}
for (i = 0; i < MAX_REPLY_QUEUES; i++)
free_irq(h->intr[i], &h->q[i]);
}
static void hpsa_free_irqs_and_disable_msix(struct ctlr_info *h)
{
free_irqs(h);
#ifdef CONFIG_PCI_MSI
if (h->msix_vector) {
if (h->pdev->msix_enabled)
pci_disable_msix(h->pdev);
} else if (h->msi_vector) {
if (h->pdev->msi_enabled)
pci_disable_msi(h->pdev);
}
#endif /* CONFIG_PCI_MSI */
}
static void hpsa_undo_allocations_after_kdump_soft_reset(struct ctlr_info *h)
{
hpsa_free_irqs_and_disable_msix(h);
hpsa_free_sg_chain_blocks(h);
hpsa_free_cmd_pool(h);
kfree(h->blockFetchTable);
pci_free_consistent(h->pdev, h->reply_pool_size,
h->reply_pool, h->reply_pool_dhandle);
if (h->vaddr)
iounmap(h->vaddr);
if (h->transtable)
iounmap(h->transtable);
if (h->cfgtable)
iounmap(h->cfgtable);
pci_release_regions(h->pdev);
kfree(h);
}
static void remove_ctlr_from_lockup_detector_list(struct ctlr_info *h)
{
assert_spin_locked(&lockup_detector_lock);
if (!hpsa_lockup_detector)
return;
if (h->lockup_detected)
return; /* already stopped the lockup detector */
list_del(&h->lockup_list);
}
/* Called when controller lockup detected. */
static void fail_all_cmds_on_list(struct ctlr_info *h, struct list_head *list)
{
struct CommandList *c = NULL;
assert_spin_locked(&h->lock);
/* Mark all outstanding commands as failed and complete them. */
while (!list_empty(list)) {
c = list_entry(list->next, struct CommandList, list);
c->err_info->CommandStatus = CMD_HARDWARE_ERR;
finish_cmd(c);
}
}
static void controller_lockup_detected(struct ctlr_info *h)
{
unsigned long flags;
assert_spin_locked(&lockup_detector_lock);
remove_ctlr_from_lockup_detector_list(h);
h->access.set_intr_mask(h, HPSA_INTR_OFF);
spin_lock_irqsave(&h->lock, flags);
h->lockup_detected = readl(h->vaddr + SA5_SCRATCHPAD_OFFSET);
spin_unlock_irqrestore(&h->lock, flags);
dev_warn(&h->pdev->dev, "Controller lockup detected: 0x%08x\n",
h->lockup_detected);
pci_disable_device(h->pdev);
spin_lock_irqsave(&h->lock, flags);
fail_all_cmds_on_list(h, &h->cmpQ);
fail_all_cmds_on_list(h, &h->reqQ);
spin_unlock_irqrestore(&h->lock, flags);
}
static void detect_controller_lockup(struct ctlr_info *h)
{
u64 now;
u32 heartbeat;
unsigned long flags;
assert_spin_locked(&lockup_detector_lock);
now = get_jiffies_64();
/* If we've received an interrupt recently, we're ok. */
if (time_after64(h->last_intr_timestamp +
(h->heartbeat_sample_interval), now))
return;
/*
* If we've already checked the heartbeat recently, we're ok.
* This could happen if someone sends us a signal. We
* otherwise don't care about signals in this thread.
*/
if (time_after64(h->last_heartbeat_timestamp +
(h->heartbeat_sample_interval), now))
return;
/* If heartbeat has not changed since we last looked, we're not ok. */
spin_lock_irqsave(&h->lock, flags);
heartbeat = readl(&h->cfgtable->HeartBeat);
spin_unlock_irqrestore(&h->lock, flags);
if (h->last_heartbeat == heartbeat) {
controller_lockup_detected(h);
return;
}
/* We're ok. */
h->last_heartbeat = heartbeat;
h->last_heartbeat_timestamp = now;
}
static int detect_controller_lockup_thread(void *notused)
{
struct ctlr_info *h;
unsigned long flags;
while (1) {
struct list_head *this, *tmp;
schedule_timeout_interruptible(HEARTBEAT_SAMPLE_INTERVAL);
if (kthread_should_stop())
break;
spin_lock_irqsave(&lockup_detector_lock, flags);
list_for_each_safe(this, tmp, &hpsa_ctlr_list) {
h = list_entry(this, struct ctlr_info, lockup_list);
detect_controller_lockup(h);
}
spin_unlock_irqrestore(&lockup_detector_lock, flags);
}
return 0;
}
static void add_ctlr_to_lockup_detector_list(struct ctlr_info *h)
{
unsigned long flags;
h->heartbeat_sample_interval = HEARTBEAT_SAMPLE_INTERVAL;
spin_lock_irqsave(&lockup_detector_lock, flags);
list_add_tail(&h->lockup_list, &hpsa_ctlr_list);
spin_unlock_irqrestore(&lockup_detector_lock, flags);
}
static void start_controller_lockup_detector(struct ctlr_info *h)
{
/* Start the lockup detector thread if not already started */
if (!hpsa_lockup_detector) {
spin_lock_init(&lockup_detector_lock);
hpsa_lockup_detector =
kthread_run(detect_controller_lockup_thread,
NULL, HPSA);
}
if (!hpsa_lockup_detector) {
dev_warn(&h->pdev->dev,
"Could not start lockup detector thread\n");
return;
}
add_ctlr_to_lockup_detector_list(h);
}
static void stop_controller_lockup_detector(struct ctlr_info *h)
{
unsigned long flags;
spin_lock_irqsave(&lockup_detector_lock, flags);
remove_ctlr_from_lockup_detector_list(h);
/* If the list of ctlr's to monitor is empty, stop the thread */
if (list_empty(&hpsa_ctlr_list)) {
spin_unlock_irqrestore(&lockup_detector_lock, flags);
kthread_stop(hpsa_lockup_detector);
spin_lock_irqsave(&lockup_detector_lock, flags);
hpsa_lockup_detector = NULL;
}
spin_unlock_irqrestore(&lockup_detector_lock, flags);
}
static int hpsa_init_one(struct pci_dev *pdev, const struct pci_device_id *ent)
{
int dac, rc;
struct ctlr_info *h;
int try_soft_reset = 0;
unsigned long flags;
if (number_of_controllers == 0)
printk(KERN_INFO DRIVER_NAME "\n");
rc = hpsa_init_reset_devices(pdev);
if (rc) {
if (rc != -ENOTSUPP)
return rc;
/* If the reset fails in a particular way (it has no way to do
* a proper hard reset, so returns -ENOTSUPP) we can try to do
* a soft reset once we get the controller configured up to the
* point that it can accept a command.
*/
try_soft_reset = 1;
rc = 0;
}
reinit_after_soft_reset:
/* Command structures must be aligned on a 32-byte boundary because
* the 5 lower bits of the address are used by the hardware. and by
* the driver. See comments in hpsa.h for more info.
*/
#define COMMANDLIST_ALIGNMENT 32
BUILD_BUG_ON(sizeof(struct CommandList) % COMMANDLIST_ALIGNMENT);
h = kzalloc(sizeof(*h), GFP_KERNEL);
if (!h)
return -ENOMEM;
h->pdev = pdev;
h->intr_mode = hpsa_simple_mode ? SIMPLE_MODE_INT : PERF_MODE_INT;
INIT_LIST_HEAD(&h->cmpQ);
INIT_LIST_HEAD(&h->reqQ);
spin_lock_init(&h->lock);
spin_lock_init(&h->scan_lock);
rc = hpsa_pci_init(h);
if (rc != 0)
goto clean1;
sprintf(h->devname, HPSA "%d", number_of_controllers);
h->ctlr = number_of_controllers;
number_of_controllers++;
/* configure PCI DMA stuff */
rc = pci_set_dma_mask(pdev, DMA_BIT_MASK(64));
if (rc == 0) {
dac = 1;
} else {
rc = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
if (rc == 0) {
dac = 0;
} else {
dev_err(&pdev->dev, "no suitable DMA available\n");
goto clean1;
}
}
/* make sure the board interrupts are off */
h->access.set_intr_mask(h, HPSA_INTR_OFF);
if (hpsa_request_irq(h, do_hpsa_intr_msi, do_hpsa_intr_intx))
goto clean2;
dev_info(&pdev->dev, "%s: <0x%x> at IRQ %d%s using DAC\n",
h->devname, pdev->device,
h->intr[h->intr_mode], dac ? "" : " not");
if (hpsa_allocate_cmd_pool(h))
goto clean4;
if (hpsa_allocate_sg_chain_blocks(h))
goto clean4;
init_waitqueue_head(&h->scan_wait_queue);
h->scan_finished = 1; /* no scan currently in progress */
pci_set_drvdata(pdev, h);
h->ndevices = 0;
h->scsi_host = NULL;
spin_lock_init(&h->devlock);
hpsa_put_ctlr_into_performant_mode(h);
/* At this point, the controller is ready to take commands.
* Now, if reset_devices and the hard reset didn't work, try
* the soft reset and see if that works.
*/
if (try_soft_reset) {
/* This is kind of gross. We may or may not get a completion
* from the soft reset command, and if we do, then the value
* from the fifo may or may not be valid. So, we wait 10 secs
* after the reset throwing away any completions we get during
* that time. Unregister the interrupt handler and register
* fake ones to scoop up any residual completions.
*/
spin_lock_irqsave(&h->lock, flags);
h->access.set_intr_mask(h, HPSA_INTR_OFF);
spin_unlock_irqrestore(&h->lock, flags);
free_irqs(h);
rc = hpsa_request_irq(h, hpsa_msix_discard_completions,
hpsa_intx_discard_completions);
if (rc) {
dev_warn(&h->pdev->dev, "Failed to request_irq after "
"soft reset.\n");
goto clean4;
}
rc = hpsa_kdump_soft_reset(h);
if (rc)
/* Neither hard nor soft reset worked, we're hosed. */
goto clean4;
dev_info(&h->pdev->dev, "Board READY.\n");
dev_info(&h->pdev->dev,
"Waiting for stale completions to drain.\n");
h->access.set_intr_mask(h, HPSA_INTR_ON);
msleep(10000);
h->access.set_intr_mask(h, HPSA_INTR_OFF);
rc = controller_reset_failed(h->cfgtable);
if (rc)
dev_info(&h->pdev->dev,
"Soft reset appears to have failed.\n");
/* since the controller's reset, we have to go back and re-init
* everything. Easiest to just forget what we've done and do it
* all over again.
*/
hpsa_undo_allocations_after_kdump_soft_reset(h);
try_soft_reset = 0;
if (rc)
/* don't go to clean4, we already unallocated */
return -ENODEV;
goto reinit_after_soft_reset;
}
/* Turn the interrupts on so we can service requests */
h->access.set_intr_mask(h, HPSA_INTR_ON);
hpsa_hba_inquiry(h);
hpsa_register_scsi(h); /* hook ourselves into SCSI subsystem */
start_controller_lockup_detector(h);
return 0;
clean4:
hpsa_free_sg_chain_blocks(h);
hpsa_free_cmd_pool(h);
free_irqs(h);
clean2:
clean1:
kfree(h);
return rc;
}
static void hpsa_flush_cache(struct ctlr_info *h)
{
char *flush_buf;
struct CommandList *c;
flush_buf = kzalloc(4, GFP_KERNEL);
if (!flush_buf)
return;
c = cmd_special_alloc(h);
if (!c) {
dev_warn(&h->pdev->dev, "cmd_special_alloc returned NULL!\n");
goto out_of_memory;
}
if (fill_cmd(c, HPSA_CACHE_FLUSH, h, flush_buf, 4, 0,
RAID_CTLR_LUNID, TYPE_CMD)) {
goto out;
}
hpsa_scsi_do_simple_cmd_with_retry(h, c, PCI_DMA_TODEVICE);
if (c->err_info->CommandStatus != 0)
out:
dev_warn(&h->pdev->dev,
"error flushing cache on controller\n");
cmd_special_free(h, c);
out_of_memory:
kfree(flush_buf);
}
static void hpsa_shutdown(struct pci_dev *pdev)
{
struct ctlr_info *h;
h = pci_get_drvdata(pdev);
/* Turn board interrupts off and send the flush cache command
* sendcmd will turn off interrupt, and send the flush...
* To write all data in the battery backed cache to disks
*/
hpsa_flush_cache(h);
h->access.set_intr_mask(h, HPSA_INTR_OFF);
hpsa_free_irqs_and_disable_msix(h);
}
static void hpsa_free_device_info(struct ctlr_info *h)
{
int i;
for (i = 0; i < h->ndevices; i++)
kfree(h->dev[i]);
}
static void hpsa_remove_one(struct pci_dev *pdev)
{
struct ctlr_info *h;
if (pci_get_drvdata(pdev) == NULL) {
dev_err(&pdev->dev, "unable to remove device\n");
return;
}
h = pci_get_drvdata(pdev);
stop_controller_lockup_detector(h);
hpsa_unregister_scsi(h); /* unhook from SCSI subsystem */
hpsa_shutdown(pdev);
iounmap(h->vaddr);
iounmap(h->transtable);
iounmap(h->cfgtable);
hpsa_free_device_info(h);
hpsa_free_sg_chain_blocks(h);
pci_free_consistent(h->pdev,
h->nr_cmds * sizeof(struct CommandList),
h->cmd_pool, h->cmd_pool_dhandle);
pci_free_consistent(h->pdev,
h->nr_cmds * sizeof(struct ErrorInfo),
h->errinfo_pool, h->errinfo_pool_dhandle);
pci_free_consistent(h->pdev, h->reply_pool_size,
h->reply_pool, h->reply_pool_dhandle);
kfree(h->cmd_pool_bits);
kfree(h->blockFetchTable);
kfree(h->hba_inquiry_data);
pci_disable_device(pdev);
pci_release_regions(pdev);
pci_set_drvdata(pdev, NULL);
kfree(h);
}
static int hpsa_suspend(__attribute__((unused)) struct pci_dev *pdev,
__attribute__((unused)) pm_message_t state)
{
return -ENOSYS;
}
static int hpsa_resume(__attribute__((unused)) struct pci_dev *pdev)
{
return -ENOSYS;
}
static struct pci_driver hpsa_pci_driver = {
.name = HPSA,
.probe = hpsa_init_one,
.remove = hpsa_remove_one,
.id_table = hpsa_pci_device_id, /* id_table */
.shutdown = hpsa_shutdown,
.suspend = hpsa_suspend,
.resume = hpsa_resume,
};
/* Fill in bucket_map[], given nsgs (the max number of
* scatter gather elements supported) and bucket[],
* which is an array of 8 integers. The bucket[] array
* contains 8 different DMA transfer sizes (in 16
* byte increments) which the controller uses to fetch
* commands. This function fills in bucket_map[], which
* maps a given number of scatter gather elements to one of
* the 8 DMA transfer sizes. The point of it is to allow the
* controller to only do as much DMA as needed to fetch the
* command, with the DMA transfer size encoded in the lower
* bits of the command address.
*/
static void calc_bucket_map(int bucket[], int num_buckets,
int nsgs, int *bucket_map)
{
int i, j, b, size;
/* even a command with 0 SGs requires 4 blocks */
#define MINIMUM_TRANSFER_BLOCKS 4
#define NUM_BUCKETS 8
/* Note, bucket_map must have nsgs+1 entries. */
for (i = 0; i <= nsgs; i++) {
/* Compute size of a command with i SG entries */
size = i + MINIMUM_TRANSFER_BLOCKS;
b = num_buckets; /* Assume the biggest bucket */
/* Find the bucket that is just big enough */
for (j = 0; j < 8; j++) {
if (bucket[j] >= size) {
b = j;
break;
}
}
/* for a command with i SG entries, use bucket b. */
bucket_map[i] = b;
}
}
static void hpsa_enter_performant_mode(struct ctlr_info *h, u32 use_short_tags)
{
int i;
unsigned long register_value;
/* This is a bit complicated. There are 8 registers on
* the controller which we write to to tell it 8 different
* sizes of commands which there may be. It's a way of
* reducing the DMA done to fetch each command. Encoded into
* each command's tag are 3 bits which communicate to the controller
* which of the eight sizes that command fits within. The size of
* each command depends on how many scatter gather entries there are.
* Each SG entry requires 16 bytes. The eight registers are programmed
* with the number of 16-byte blocks a command of that size requires.
* The smallest command possible requires 5 such 16 byte blocks.
* the largest command possible requires SG_ENTRIES_IN_CMD + 4 16-byte
* blocks. Note, this only extends to the SG entries contained
* within the command block, and does not extend to chained blocks
* of SG elements. bft[] contains the eight values we write to
* the registers. They are not evenly distributed, but have more
* sizes for small commands, and fewer sizes for larger commands.
*/
int bft[8] = {5, 6, 8, 10, 12, 20, 28, SG_ENTRIES_IN_CMD + 4};
BUILD_BUG_ON(28 > SG_ENTRIES_IN_CMD + 4);
/* 5 = 1 s/g entry or 4k
* 6 = 2 s/g entry or 8k
* 8 = 4 s/g entry or 16k
* 10 = 6 s/g entry or 24k
*/
/* Controller spec: zero out this buffer. */
memset(h->reply_pool, 0, h->reply_pool_size);
bft[7] = SG_ENTRIES_IN_CMD + 4;
calc_bucket_map(bft, ARRAY_SIZE(bft),
SG_ENTRIES_IN_CMD, h->blockFetchTable);
for (i = 0; i < 8; i++)
writel(bft[i], &h->transtable->BlockFetch[i]);
/* size of controller ring buffer */
writel(h->max_commands, &h->transtable->RepQSize);
writel(h->nreply_queues, &h->transtable->RepQCount);
writel(0, &h->transtable->RepQCtrAddrLow32);
writel(0, &h->transtable->RepQCtrAddrHigh32);
for (i = 0; i < h->nreply_queues; i++) {
writel(0, &h->transtable->RepQAddr[i].upper);
writel(h->reply_pool_dhandle +
(h->max_commands * sizeof(u64) * i),
&h->transtable->RepQAddr[i].lower);
}
writel(CFGTBL_Trans_Performant | use_short_tags |
CFGTBL_Trans_enable_directed_msix,
&(h->cfgtable->HostWrite.TransportRequest));
writel(CFGTBL_ChangeReq, h->vaddr + SA5_DOORBELL);
hpsa_wait_for_mode_change_ack(h);
register_value = readl(&(h->cfgtable->TransportActive));
if (!(register_value & CFGTBL_Trans_Performant)) {
dev_warn(&h->pdev->dev, "unable to get board into"
" performant mode\n");
return;
}
/* Change the access methods to the performant access methods */
h->access = SA5_performant_access;
h->transMethod = CFGTBL_Trans_Performant;
}
static void hpsa_put_ctlr_into_performant_mode(struct ctlr_info *h)
{
u32 trans_support;
int i;
if (hpsa_simple_mode)
return;
trans_support = readl(&(h->cfgtable->TransportSupport));
if (!(trans_support & PERFORMANT_MODE))
return;
h->nreply_queues = h->msix_vector ? MAX_REPLY_QUEUES : 1;
hpsa_get_max_perf_mode_cmds(h);
/* Performant mode ring buffer and supporting data structures */
h->reply_pool_size = h->max_commands * sizeof(u64) * h->nreply_queues;
h->reply_pool = pci_alloc_consistent(h->pdev, h->reply_pool_size,
&(h->reply_pool_dhandle));
for (i = 0; i < h->nreply_queues; i++) {
h->reply_queue[i].head = &h->reply_pool[h->max_commands * i];
h->reply_queue[i].size = h->max_commands;
h->reply_queue[i].wraparound = 1; /* spec: init to 1 */
h->reply_queue[i].current_entry = 0;
}
/* Need a block fetch table for performant mode */
h->blockFetchTable = kmalloc(((SG_ENTRIES_IN_CMD + 1) *
sizeof(u32)), GFP_KERNEL);
if ((h->reply_pool == NULL)
|| (h->blockFetchTable == NULL))
goto clean_up;
hpsa_enter_performant_mode(h,
trans_support & CFGTBL_Trans_use_short_tags);
return;
clean_up:
if (h->reply_pool)
pci_free_consistent(h->pdev, h->reply_pool_size,
h->reply_pool, h->reply_pool_dhandle);
kfree(h->blockFetchTable);
}
/*
* This is it. Register the PCI driver information for the cards we control
* the OS will call our registered routines when it finds one of our cards.
*/
static int __init hpsa_init(void)
{
return pci_register_driver(&hpsa_pci_driver);
}
static void __exit hpsa_cleanup(void)
{
pci_unregister_driver(&hpsa_pci_driver);
}
module_init(hpsa_init);
module_exit(hpsa_cleanup);
| gpl-2.0 |
SomethingExplosive/android_kernel_samsung_tuna | mm/nobootmem.c | 1121 | 10713 | /*
* bootmem - A boot-time physical memory allocator and configurator
*
* Copyright (C) 1999 Ingo Molnar
* 1999 Kanoj Sarcar, SGI
* 2008 Johannes Weiner
*
* Access to this subsystem has to be serialized externally (which is true
* for the boot process anyway).
*/
#include <linux/init.h>
#include <linux/pfn.h>
#include <linux/slab.h>
#include <linux/bootmem.h>
#include <linux/module.h>
#include <linux/kmemleak.h>
#include <linux/range.h>
#include <linux/memblock.h>
#include <asm/bug.h>
#include <asm/io.h>
#include <asm/processor.h>
#include "internal.h"
#ifndef CONFIG_NEED_MULTIPLE_NODES
struct pglist_data __refdata contig_page_data;
EXPORT_SYMBOL(contig_page_data);
#endif
unsigned long max_low_pfn;
unsigned long min_low_pfn;
unsigned long max_pfn;
static void * __init __alloc_memory_core_early(int nid, u64 size, u64 align,
u64 goal, u64 limit)
{
void *ptr;
u64 addr;
if (limit > memblock.current_limit)
limit = memblock.current_limit;
addr = find_memory_core_early(nid, size, align, goal, limit);
if (addr == MEMBLOCK_ERROR)
return NULL;
ptr = phys_to_virt(addr);
memset(ptr, 0, size);
memblock_x86_reserve_range(addr, addr + size, "BOOTMEM");
/*
* The min_count is set to 0 so that bootmem allocated blocks
* are never reported as leaks.
*/
kmemleak_alloc(ptr, size, 0, 0);
return ptr;
}
/*
* free_bootmem_late - free bootmem pages directly to page allocator
* @addr: starting address of the range
* @size: size of the range in bytes
*
* This is only useful when the bootmem allocator has already been torn
* down, but we are still initializing the system. Pages are given directly
* to the page allocator, no bootmem metadata is updated because it is gone.
*/
void __init free_bootmem_late(unsigned long addr, unsigned long size)
{
unsigned long cursor, end;
kmemleak_free_part(__va(addr), size);
cursor = PFN_UP(addr);
end = PFN_DOWN(addr + size);
for (; cursor < end; cursor++) {
__free_pages_bootmem(pfn_to_page(cursor), 0);
totalram_pages++;
}
}
static void __init __free_pages_memory(unsigned long start, unsigned long end)
{
unsigned long i, start_aligned, end_aligned;
int order = ilog2(BITS_PER_LONG);
start_aligned = (start + (BITS_PER_LONG - 1)) & ~(BITS_PER_LONG - 1);
end_aligned = end & ~(BITS_PER_LONG - 1);
if (end_aligned <= start_aligned) {
for (i = start; i < end; i++)
__free_pages_bootmem(pfn_to_page(i), 0);
return;
}
for (i = start; i < start_aligned; i++)
__free_pages_bootmem(pfn_to_page(i), 0);
for (i = start_aligned; i < end_aligned; i += BITS_PER_LONG)
__free_pages_bootmem(pfn_to_page(i), order);
for (i = end_aligned; i < end; i++)
__free_pages_bootmem(pfn_to_page(i), 0);
}
unsigned long __init free_all_memory_core_early(int nodeid)
{
int i;
u64 start, end;
unsigned long count = 0;
struct range *range = NULL;
int nr_range;
nr_range = get_free_all_memory_range(&range, nodeid);
for (i = 0; i < nr_range; i++) {
start = range[i].start;
end = range[i].end;
count += end - start;
__free_pages_memory(start, end);
}
return count;
}
/**
* free_all_bootmem_node - release a node's free pages to the buddy allocator
* @pgdat: node to be released
*
* Returns the number of pages actually released.
*/
unsigned long __init free_all_bootmem_node(pg_data_t *pgdat)
{
register_page_bootmem_info_node(pgdat);
/* free_all_memory_core_early(MAX_NUMNODES) will be called later */
return 0;
}
/**
* free_all_bootmem - release free pages to the buddy allocator
*
* Returns the number of pages actually released.
*/
unsigned long __init free_all_bootmem(void)
{
/*
* We need to use MAX_NUMNODES instead of NODE_DATA(0)->node_id
* because in some case like Node0 doesn't have RAM installed
* low ram will be on Node1
* Use MAX_NUMNODES will make sure all ranges in early_node_map[]
* will be used instead of only Node0 related
*/
return free_all_memory_core_early(MAX_NUMNODES);
}
/**
* free_bootmem_node - mark a page range as usable
* @pgdat: node the range resides on
* @physaddr: starting address of the range
* @size: size of the range in bytes
*
* Partial pages will be considered reserved and left as they are.
*
* The range must reside completely on the specified node.
*/
void __init free_bootmem_node(pg_data_t *pgdat, unsigned long physaddr,
unsigned long size)
{
kmemleak_free_part(__va(physaddr), size);
memblock_x86_free_range(physaddr, physaddr + size);
}
/**
* free_bootmem - mark a page range as usable
* @addr: starting address of the range
* @size: size of the range in bytes
*
* Partial pages will be considered reserved and left as they are.
*
* The range must be contiguous but may span node boundaries.
*/
void __init free_bootmem(unsigned long addr, unsigned long size)
{
kmemleak_free_part(__va(addr), size);
memblock_x86_free_range(addr, addr + size);
}
static void * __init ___alloc_bootmem_nopanic(unsigned long size,
unsigned long align,
unsigned long goal,
unsigned long limit)
{
void *ptr;
if (WARN_ON_ONCE(slab_is_available()))
return kzalloc(size, GFP_NOWAIT);
restart:
ptr = __alloc_memory_core_early(MAX_NUMNODES, size, align, goal, limit);
if (ptr)
return ptr;
if (goal != 0) {
goal = 0;
goto restart;
}
return NULL;
}
/**
* __alloc_bootmem_nopanic - allocate boot memory without panicking
* @size: size of the request in bytes
* @align: alignment of the region
* @goal: preferred starting address of the region
*
* The goal is dropped if it can not be satisfied and the allocation will
* fall back to memory below @goal.
*
* Allocation may happen on any node in the system.
*
* Returns NULL on failure.
*/
void * __init __alloc_bootmem_nopanic(unsigned long size, unsigned long align,
unsigned long goal)
{
unsigned long limit = -1UL;
return ___alloc_bootmem_nopanic(size, align, goal, limit);
}
static void * __init ___alloc_bootmem(unsigned long size, unsigned long align,
unsigned long goal, unsigned long limit)
{
void *mem = ___alloc_bootmem_nopanic(size, align, goal, limit);
if (mem)
return mem;
/*
* Whoops, we cannot satisfy the allocation request.
*/
printk(KERN_ALERT "bootmem alloc of %lu bytes failed!\n", size);
panic("Out of memory");
return NULL;
}
/**
* __alloc_bootmem - allocate boot memory
* @size: size of the request in bytes
* @align: alignment of the region
* @goal: preferred starting address of the region
*
* The goal is dropped if it can not be satisfied and the allocation will
* fall back to memory below @goal.
*
* Allocation may happen on any node in the system.
*
* The function panics if the request can not be satisfied.
*/
void * __init __alloc_bootmem(unsigned long size, unsigned long align,
unsigned long goal)
{
unsigned long limit = -1UL;
return ___alloc_bootmem(size, align, goal, limit);
}
/**
* __alloc_bootmem_node - allocate boot memory from a specific node
* @pgdat: node to allocate from
* @size: size of the request in bytes
* @align: alignment of the region
* @goal: preferred starting address of the region
*
* The goal is dropped if it can not be satisfied and the allocation will
* fall back to memory below @goal.
*
* Allocation may fall back to any node in the system if the specified node
* can not hold the requested memory.
*
* The function panics if the request can not be satisfied.
*/
void * __init __alloc_bootmem_node(pg_data_t *pgdat, unsigned long size,
unsigned long align, unsigned long goal)
{
void *ptr;
if (WARN_ON_ONCE(slab_is_available()))
return kzalloc_node(size, GFP_NOWAIT, pgdat->node_id);
ptr = __alloc_memory_core_early(pgdat->node_id, size, align,
goal, -1ULL);
if (ptr)
return ptr;
return __alloc_memory_core_early(MAX_NUMNODES, size, align,
goal, -1ULL);
}
void * __init __alloc_bootmem_node_high(pg_data_t *pgdat, unsigned long size,
unsigned long align, unsigned long goal)
{
return __alloc_bootmem_node(pgdat, size, align, goal);
}
#ifdef CONFIG_SPARSEMEM
/**
* alloc_bootmem_section - allocate boot memory from a specific section
* @size: size of the request in bytes
* @section_nr: sparse map section to allocate from
*
* Return NULL on failure.
*/
void * __init alloc_bootmem_section(unsigned long size,
unsigned long section_nr)
{
unsigned long pfn, goal, limit;
pfn = section_nr_to_pfn(section_nr);
goal = pfn << PAGE_SHIFT;
limit = section_nr_to_pfn(section_nr + 1) << PAGE_SHIFT;
return __alloc_memory_core_early(early_pfn_to_nid(pfn), size,
SMP_CACHE_BYTES, goal, limit);
}
#endif
void * __init __alloc_bootmem_node_nopanic(pg_data_t *pgdat, unsigned long size,
unsigned long align, unsigned long goal)
{
void *ptr;
if (WARN_ON_ONCE(slab_is_available()))
return kzalloc_node(size, GFP_NOWAIT, pgdat->node_id);
ptr = __alloc_memory_core_early(pgdat->node_id, size, align,
goal, -1ULL);
if (ptr)
return ptr;
return __alloc_bootmem_nopanic(size, align, goal);
}
#ifndef ARCH_LOW_ADDRESS_LIMIT
#define ARCH_LOW_ADDRESS_LIMIT 0xffffffffUL
#endif
/**
* __alloc_bootmem_low - allocate low boot memory
* @size: size of the request in bytes
* @align: alignment of the region
* @goal: preferred starting address of the region
*
* The goal is dropped if it can not be satisfied and the allocation will
* fall back to memory below @goal.
*
* Allocation may happen on any node in the system.
*
* The function panics if the request can not be satisfied.
*/
void * __init __alloc_bootmem_low(unsigned long size, unsigned long align,
unsigned long goal)
{
return ___alloc_bootmem(size, align, goal, ARCH_LOW_ADDRESS_LIMIT);
}
/**
* __alloc_bootmem_low_node - allocate low boot memory from a specific node
* @pgdat: node to allocate from
* @size: size of the request in bytes
* @align: alignment of the region
* @goal: preferred starting address of the region
*
* The goal is dropped if it can not be satisfied and the allocation will
* fall back to memory below @goal.
*
* Allocation may fall back to any node in the system if the specified node
* can not hold the requested memory.
*
* The function panics if the request can not be satisfied.
*/
void * __init __alloc_bootmem_low_node(pg_data_t *pgdat, unsigned long size,
unsigned long align, unsigned long goal)
{
void *ptr;
if (WARN_ON_ONCE(slab_is_available()))
return kzalloc_node(size, GFP_NOWAIT, pgdat->node_id);
ptr = __alloc_memory_core_early(pgdat->node_id, size, align,
goal, ARCH_LOW_ADDRESS_LIMIT);
if (ptr)
return ptr;
return __alloc_memory_core_early(MAX_NUMNODES, size, align,
goal, ARCH_LOW_ADDRESS_LIMIT);
}
| gpl-2.0 |
TEAM-RAZOR-DEVICES/kernel_oneplus_msm8994 | drivers/net/ethernet/intel/ixgbe/ixgbe_82598.c | 2145 | 39865 | /*******************************************************************************
Intel 10 Gigabit PCI Express Linux driver
Copyright(c) 1999 - 2013 Intel Corporation.
This program is free software; you can redistribute it and/or modify it
under the terms and conditions of the GNU General Public License,
version 2, as published by the Free Software Foundation.
This program is distributed in the hope it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
Contact Information:
e1000-devel Mailing List <e1000-devel@lists.sourceforge.net>
Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*******************************************************************************/
#include <linux/pci.h>
#include <linux/delay.h>
#include <linux/sched.h>
#include "ixgbe.h"
#include "ixgbe_phy.h"
#define IXGBE_82598_MAX_TX_QUEUES 32
#define IXGBE_82598_MAX_RX_QUEUES 64
#define IXGBE_82598_RAR_ENTRIES 16
#define IXGBE_82598_MC_TBL_SIZE 128
#define IXGBE_82598_VFT_TBL_SIZE 128
#define IXGBE_82598_RX_PB_SIZE 512
static s32 ixgbe_setup_copper_link_82598(struct ixgbe_hw *hw,
ixgbe_link_speed speed,
bool autoneg_wait_to_complete);
static s32 ixgbe_read_i2c_eeprom_82598(struct ixgbe_hw *hw, u8 byte_offset,
u8 *eeprom_data);
/**
* ixgbe_set_pcie_completion_timeout - set pci-e completion timeout
* @hw: pointer to the HW structure
*
* The defaults for 82598 should be in the range of 50us to 50ms,
* however the hardware default for these parts is 500us to 1ms which is less
* than the 10ms recommended by the pci-e spec. To address this we need to
* increase the value to either 10ms to 250ms for capability version 1 config,
* or 16ms to 55ms for version 2.
**/
static void ixgbe_set_pcie_completion_timeout(struct ixgbe_hw *hw)
{
struct ixgbe_adapter *adapter = hw->back;
u32 gcr = IXGBE_READ_REG(hw, IXGBE_GCR);
u16 pcie_devctl2;
/* only take action if timeout value is defaulted to 0 */
if (gcr & IXGBE_GCR_CMPL_TMOUT_MASK)
goto out;
/*
* if capababilities version is type 1 we can write the
* timeout of 10ms to 250ms through the GCR register
*/
if (!(gcr & IXGBE_GCR_CAP_VER2)) {
gcr |= IXGBE_GCR_CMPL_TMOUT_10ms;
goto out;
}
/*
* for version 2 capabilities we need to write the config space
* directly in order to set the completion timeout value for
* 16ms to 55ms
*/
pci_read_config_word(adapter->pdev,
IXGBE_PCI_DEVICE_CONTROL2, &pcie_devctl2);
pcie_devctl2 |= IXGBE_PCI_DEVICE_CONTROL2_16ms;
pci_write_config_word(adapter->pdev,
IXGBE_PCI_DEVICE_CONTROL2, pcie_devctl2);
out:
/* disable completion timeout resend */
gcr &= ~IXGBE_GCR_CMPL_TMOUT_RESEND;
IXGBE_WRITE_REG(hw, IXGBE_GCR, gcr);
}
static s32 ixgbe_get_invariants_82598(struct ixgbe_hw *hw)
{
struct ixgbe_mac_info *mac = &hw->mac;
/* Call PHY identify routine to get the phy type */
ixgbe_identify_phy_generic(hw);
mac->mcft_size = IXGBE_82598_MC_TBL_SIZE;
mac->vft_size = IXGBE_82598_VFT_TBL_SIZE;
mac->num_rar_entries = IXGBE_82598_RAR_ENTRIES;
mac->max_rx_queues = IXGBE_82598_MAX_RX_QUEUES;
mac->max_tx_queues = IXGBE_82598_MAX_TX_QUEUES;
mac->max_msix_vectors = ixgbe_get_pcie_msix_count_generic(hw);
return 0;
}
/**
* ixgbe_init_phy_ops_82598 - PHY/SFP specific init
* @hw: pointer to hardware structure
*
* Initialize any function pointers that were not able to be
* set during get_invariants because the PHY/SFP type was
* not known. Perform the SFP init if necessary.
*
**/
static s32 ixgbe_init_phy_ops_82598(struct ixgbe_hw *hw)
{
struct ixgbe_mac_info *mac = &hw->mac;
struct ixgbe_phy_info *phy = &hw->phy;
s32 ret_val = 0;
u16 list_offset, data_offset;
/* Identify the PHY */
phy->ops.identify(hw);
/* Overwrite the link function pointers if copper PHY */
if (mac->ops.get_media_type(hw) == ixgbe_media_type_copper) {
mac->ops.setup_link = &ixgbe_setup_copper_link_82598;
mac->ops.get_link_capabilities =
&ixgbe_get_copper_link_capabilities_generic;
}
switch (hw->phy.type) {
case ixgbe_phy_tn:
phy->ops.setup_link = &ixgbe_setup_phy_link_tnx;
phy->ops.check_link = &ixgbe_check_phy_link_tnx;
phy->ops.get_firmware_version =
&ixgbe_get_phy_firmware_version_tnx;
break;
case ixgbe_phy_nl:
phy->ops.reset = &ixgbe_reset_phy_nl;
/* Call SFP+ identify routine to get the SFP+ module type */
ret_val = phy->ops.identify_sfp(hw);
if (ret_val != 0)
goto out;
else if (hw->phy.sfp_type == ixgbe_sfp_type_unknown) {
ret_val = IXGBE_ERR_SFP_NOT_SUPPORTED;
goto out;
}
/* Check to see if SFP+ module is supported */
ret_val = ixgbe_get_sfp_init_sequence_offsets(hw,
&list_offset,
&data_offset);
if (ret_val != 0) {
ret_val = IXGBE_ERR_SFP_NOT_SUPPORTED;
goto out;
}
break;
default:
break;
}
out:
return ret_val;
}
/**
* ixgbe_start_hw_82598 - Prepare hardware for Tx/Rx
* @hw: pointer to hardware structure
*
* Starts the hardware using the generic start_hw function.
* Disables relaxed ordering Then set pcie completion timeout
*
**/
static s32 ixgbe_start_hw_82598(struct ixgbe_hw *hw)
{
u32 regval;
u32 i;
s32 ret_val = 0;
ret_val = ixgbe_start_hw_generic(hw);
/* Disable relaxed ordering */
for (i = 0; ((i < hw->mac.max_tx_queues) &&
(i < IXGBE_DCA_MAX_QUEUES_82598)); i++) {
regval = IXGBE_READ_REG(hw, IXGBE_DCA_TXCTRL(i));
regval &= ~IXGBE_DCA_TXCTRL_DESC_WRO_EN;
IXGBE_WRITE_REG(hw, IXGBE_DCA_TXCTRL(i), regval);
}
for (i = 0; ((i < hw->mac.max_rx_queues) &&
(i < IXGBE_DCA_MAX_QUEUES_82598)); i++) {
regval = IXGBE_READ_REG(hw, IXGBE_DCA_RXCTRL(i));
regval &= ~(IXGBE_DCA_RXCTRL_DATA_WRO_EN |
IXGBE_DCA_RXCTRL_HEAD_WRO_EN);
IXGBE_WRITE_REG(hw, IXGBE_DCA_RXCTRL(i), regval);
}
hw->mac.rx_pb_size = IXGBE_82598_RX_PB_SIZE;
/* set the completion timeout for interface */
if (ret_val == 0)
ixgbe_set_pcie_completion_timeout(hw);
return ret_val;
}
/**
* ixgbe_get_link_capabilities_82598 - Determines link capabilities
* @hw: pointer to hardware structure
* @speed: pointer to link speed
* @autoneg: boolean auto-negotiation value
*
* Determines the link capabilities by reading the AUTOC register.
**/
static s32 ixgbe_get_link_capabilities_82598(struct ixgbe_hw *hw,
ixgbe_link_speed *speed,
bool *autoneg)
{
s32 status = 0;
u32 autoc = 0;
/*
* Determine link capabilities based on the stored value of AUTOC,
* which represents EEPROM defaults. If AUTOC value has not been
* stored, use the current register value.
*/
if (hw->mac.orig_link_settings_stored)
autoc = hw->mac.orig_autoc;
else
autoc = IXGBE_READ_REG(hw, IXGBE_AUTOC);
switch (autoc & IXGBE_AUTOC_LMS_MASK) {
case IXGBE_AUTOC_LMS_1G_LINK_NO_AN:
*speed = IXGBE_LINK_SPEED_1GB_FULL;
*autoneg = false;
break;
case IXGBE_AUTOC_LMS_10G_LINK_NO_AN:
*speed = IXGBE_LINK_SPEED_10GB_FULL;
*autoneg = false;
break;
case IXGBE_AUTOC_LMS_1G_AN:
*speed = IXGBE_LINK_SPEED_1GB_FULL;
*autoneg = true;
break;
case IXGBE_AUTOC_LMS_KX4_AN:
case IXGBE_AUTOC_LMS_KX4_AN_1G_AN:
*speed = IXGBE_LINK_SPEED_UNKNOWN;
if (autoc & IXGBE_AUTOC_KX4_SUPP)
*speed |= IXGBE_LINK_SPEED_10GB_FULL;
if (autoc & IXGBE_AUTOC_KX_SUPP)
*speed |= IXGBE_LINK_SPEED_1GB_FULL;
*autoneg = true;
break;
default:
status = IXGBE_ERR_LINK_SETUP;
break;
}
return status;
}
/**
* ixgbe_get_media_type_82598 - Determines media type
* @hw: pointer to hardware structure
*
* Returns the media type (fiber, copper, backplane)
**/
static enum ixgbe_media_type ixgbe_get_media_type_82598(struct ixgbe_hw *hw)
{
enum ixgbe_media_type media_type;
/* Detect if there is a copper PHY attached. */
switch (hw->phy.type) {
case ixgbe_phy_cu_unknown:
case ixgbe_phy_tn:
media_type = ixgbe_media_type_copper;
goto out;
default:
break;
}
/* Media type for I82598 is based on device ID */
switch (hw->device_id) {
case IXGBE_DEV_ID_82598:
case IXGBE_DEV_ID_82598_BX:
/* Default device ID is mezzanine card KX/KX4 */
media_type = ixgbe_media_type_backplane;
break;
case IXGBE_DEV_ID_82598AF_DUAL_PORT:
case IXGBE_DEV_ID_82598AF_SINGLE_PORT:
case IXGBE_DEV_ID_82598_DA_DUAL_PORT:
case IXGBE_DEV_ID_82598_SR_DUAL_PORT_EM:
case IXGBE_DEV_ID_82598EB_XF_LR:
case IXGBE_DEV_ID_82598EB_SFP_LOM:
media_type = ixgbe_media_type_fiber;
break;
case IXGBE_DEV_ID_82598EB_CX4:
case IXGBE_DEV_ID_82598_CX4_DUAL_PORT:
media_type = ixgbe_media_type_cx4;
break;
case IXGBE_DEV_ID_82598AT:
case IXGBE_DEV_ID_82598AT2:
media_type = ixgbe_media_type_copper;
break;
default:
media_type = ixgbe_media_type_unknown;
break;
}
out:
return media_type;
}
/**
* ixgbe_fc_enable_82598 - Enable flow control
* @hw: pointer to hardware structure
*
* Enable flow control according to the current settings.
**/
static s32 ixgbe_fc_enable_82598(struct ixgbe_hw *hw)
{
s32 ret_val = 0;
u32 fctrl_reg;
u32 rmcs_reg;
u32 reg;
u32 fcrtl, fcrth;
u32 link_speed = 0;
int i;
bool link_up;
/*
* Validate the water mark configuration for packet buffer 0. Zero
* water marks indicate that the packet buffer was not configured
* and the watermarks for packet buffer 0 should always be configured.
*/
if (!hw->fc.low_water ||
!hw->fc.high_water[0] ||
!hw->fc.pause_time) {
hw_dbg(hw, "Invalid water mark configuration\n");
ret_val = IXGBE_ERR_INVALID_LINK_SETTINGS;
goto out;
}
/*
* On 82598 having Rx FC on causes resets while doing 1G
* so if it's on turn it off once we know link_speed. For
* more details see 82598 Specification update.
*/
hw->mac.ops.check_link(hw, &link_speed, &link_up, false);
if (link_up && link_speed == IXGBE_LINK_SPEED_1GB_FULL) {
switch (hw->fc.requested_mode) {
case ixgbe_fc_full:
hw->fc.requested_mode = ixgbe_fc_tx_pause;
break;
case ixgbe_fc_rx_pause:
hw->fc.requested_mode = ixgbe_fc_none;
break;
default:
/* no change */
break;
}
}
/* Negotiate the fc mode to use */
ixgbe_fc_autoneg(hw);
/* Disable any previous flow control settings */
fctrl_reg = IXGBE_READ_REG(hw, IXGBE_FCTRL);
fctrl_reg &= ~(IXGBE_FCTRL_RFCE | IXGBE_FCTRL_RPFCE);
rmcs_reg = IXGBE_READ_REG(hw, IXGBE_RMCS);
rmcs_reg &= ~(IXGBE_RMCS_TFCE_PRIORITY | IXGBE_RMCS_TFCE_802_3X);
/*
* The possible values of fc.current_mode are:
* 0: Flow control is completely disabled
* 1: Rx flow control is enabled (we can receive pause frames,
* but not send pause frames).
* 2: Tx flow control is enabled (we can send pause frames but
* we do not support receiving pause frames).
* 3: Both Rx and Tx flow control (symmetric) are enabled.
* other: Invalid.
*/
switch (hw->fc.current_mode) {
case ixgbe_fc_none:
/*
* Flow control is disabled by software override or autoneg.
* The code below will actually disable it in the HW.
*/
break;
case ixgbe_fc_rx_pause:
/*
* Rx Flow control is enabled and Tx Flow control is
* disabled by software override. Since there really
* isn't a way to advertise that we are capable of RX
* Pause ONLY, we will advertise that we support both
* symmetric and asymmetric Rx PAUSE. Later, we will
* disable the adapter's ability to send PAUSE frames.
*/
fctrl_reg |= IXGBE_FCTRL_RFCE;
break;
case ixgbe_fc_tx_pause:
/*
* Tx Flow control is enabled, and Rx Flow control is
* disabled by software override.
*/
rmcs_reg |= IXGBE_RMCS_TFCE_802_3X;
break;
case ixgbe_fc_full:
/* Flow control (both Rx and Tx) is enabled by SW override. */
fctrl_reg |= IXGBE_FCTRL_RFCE;
rmcs_reg |= IXGBE_RMCS_TFCE_802_3X;
break;
default:
hw_dbg(hw, "Flow control param set incorrectly\n");
ret_val = IXGBE_ERR_CONFIG;
goto out;
break;
}
/* Set 802.3x based flow control settings. */
fctrl_reg |= IXGBE_FCTRL_DPF;
IXGBE_WRITE_REG(hw, IXGBE_FCTRL, fctrl_reg);
IXGBE_WRITE_REG(hw, IXGBE_RMCS, rmcs_reg);
fcrtl = (hw->fc.low_water << 10) | IXGBE_FCRTL_XONE;
/* Set up and enable Rx high/low water mark thresholds, enable XON. */
for (i = 0; i < MAX_TRAFFIC_CLASS; i++) {
if ((hw->fc.current_mode & ixgbe_fc_tx_pause) &&
hw->fc.high_water[i]) {
fcrth = (hw->fc.high_water[i] << 10) | IXGBE_FCRTH_FCEN;
IXGBE_WRITE_REG(hw, IXGBE_FCRTL(i), fcrtl);
IXGBE_WRITE_REG(hw, IXGBE_FCRTH(i), fcrth);
} else {
IXGBE_WRITE_REG(hw, IXGBE_FCRTL(i), 0);
IXGBE_WRITE_REG(hw, IXGBE_FCRTH(i), 0);
}
}
/* Configure pause time (2 TCs per register) */
reg = hw->fc.pause_time * 0x00010001;
for (i = 0; i < (MAX_TRAFFIC_CLASS / 2); i++)
IXGBE_WRITE_REG(hw, IXGBE_FCTTV(i), reg);
/* Configure flow control refresh threshold value */
IXGBE_WRITE_REG(hw, IXGBE_FCRTV, hw->fc.pause_time / 2);
out:
return ret_val;
}
/**
* ixgbe_start_mac_link_82598 - Configures MAC link settings
* @hw: pointer to hardware structure
*
* Configures link settings based on values in the ixgbe_hw struct.
* Restarts the link. Performs autonegotiation if needed.
**/
static s32 ixgbe_start_mac_link_82598(struct ixgbe_hw *hw,
bool autoneg_wait_to_complete)
{
u32 autoc_reg;
u32 links_reg;
u32 i;
s32 status = 0;
/* Restart link */
autoc_reg = IXGBE_READ_REG(hw, IXGBE_AUTOC);
autoc_reg |= IXGBE_AUTOC_AN_RESTART;
IXGBE_WRITE_REG(hw, IXGBE_AUTOC, autoc_reg);
/* Only poll for autoneg to complete if specified to do so */
if (autoneg_wait_to_complete) {
if ((autoc_reg & IXGBE_AUTOC_LMS_MASK) ==
IXGBE_AUTOC_LMS_KX4_AN ||
(autoc_reg & IXGBE_AUTOC_LMS_MASK) ==
IXGBE_AUTOC_LMS_KX4_AN_1G_AN) {
links_reg = 0; /* Just in case Autoneg time = 0 */
for (i = 0; i < IXGBE_AUTO_NEG_TIME; i++) {
links_reg = IXGBE_READ_REG(hw, IXGBE_LINKS);
if (links_reg & IXGBE_LINKS_KX_AN_COMP)
break;
msleep(100);
}
if (!(links_reg & IXGBE_LINKS_KX_AN_COMP)) {
status = IXGBE_ERR_AUTONEG_NOT_COMPLETE;
hw_dbg(hw, "Autonegotiation did not complete.\n");
}
}
}
/* Add delay to filter out noises during initial link setup */
msleep(50);
return status;
}
/**
* ixgbe_validate_link_ready - Function looks for phy link
* @hw: pointer to hardware structure
*
* Function indicates success when phy link is available. If phy is not ready
* within 5 seconds of MAC indicating link, the function returns error.
**/
static s32 ixgbe_validate_link_ready(struct ixgbe_hw *hw)
{
u32 timeout;
u16 an_reg;
if (hw->device_id != IXGBE_DEV_ID_82598AT2)
return 0;
for (timeout = 0;
timeout < IXGBE_VALIDATE_LINK_READY_TIMEOUT; timeout++) {
hw->phy.ops.read_reg(hw, MDIO_STAT1, MDIO_MMD_AN, &an_reg);
if ((an_reg & MDIO_AN_STAT1_COMPLETE) &&
(an_reg & MDIO_STAT1_LSTATUS))
break;
msleep(100);
}
if (timeout == IXGBE_VALIDATE_LINK_READY_TIMEOUT) {
hw_dbg(hw, "Link was indicated but link is down\n");
return IXGBE_ERR_LINK_SETUP;
}
return 0;
}
/**
* ixgbe_check_mac_link_82598 - Get link/speed status
* @hw: pointer to hardware structure
* @speed: pointer to link speed
* @link_up: true is link is up, false otherwise
* @link_up_wait_to_complete: bool used to wait for link up or not
*
* Reads the links register to determine if link is up and the current speed
**/
static s32 ixgbe_check_mac_link_82598(struct ixgbe_hw *hw,
ixgbe_link_speed *speed, bool *link_up,
bool link_up_wait_to_complete)
{
u32 links_reg;
u32 i;
u16 link_reg, adapt_comp_reg;
/*
* SERDES PHY requires us to read link status from register 0xC79F.
* Bit 0 set indicates link is up/ready; clear indicates link down.
* 0xC00C is read to check that the XAUI lanes are active. Bit 0
* clear indicates active; set indicates inactive.
*/
if (hw->phy.type == ixgbe_phy_nl) {
hw->phy.ops.read_reg(hw, 0xC79F, MDIO_MMD_PMAPMD, &link_reg);
hw->phy.ops.read_reg(hw, 0xC79F, MDIO_MMD_PMAPMD, &link_reg);
hw->phy.ops.read_reg(hw, 0xC00C, MDIO_MMD_PMAPMD,
&adapt_comp_reg);
if (link_up_wait_to_complete) {
for (i = 0; i < IXGBE_LINK_UP_TIME; i++) {
if ((link_reg & 1) &&
((adapt_comp_reg & 1) == 0)) {
*link_up = true;
break;
} else {
*link_up = false;
}
msleep(100);
hw->phy.ops.read_reg(hw, 0xC79F,
MDIO_MMD_PMAPMD,
&link_reg);
hw->phy.ops.read_reg(hw, 0xC00C,
MDIO_MMD_PMAPMD,
&adapt_comp_reg);
}
} else {
if ((link_reg & 1) && ((adapt_comp_reg & 1) == 0))
*link_up = true;
else
*link_up = false;
}
if (!*link_up)
goto out;
}
links_reg = IXGBE_READ_REG(hw, IXGBE_LINKS);
if (link_up_wait_to_complete) {
for (i = 0; i < IXGBE_LINK_UP_TIME; i++) {
if (links_reg & IXGBE_LINKS_UP) {
*link_up = true;
break;
} else {
*link_up = false;
}
msleep(100);
links_reg = IXGBE_READ_REG(hw, IXGBE_LINKS);
}
} else {
if (links_reg & IXGBE_LINKS_UP)
*link_up = true;
else
*link_up = false;
}
if (links_reg & IXGBE_LINKS_SPEED)
*speed = IXGBE_LINK_SPEED_10GB_FULL;
else
*speed = IXGBE_LINK_SPEED_1GB_FULL;
if ((hw->device_id == IXGBE_DEV_ID_82598AT2) && *link_up &&
(ixgbe_validate_link_ready(hw) != 0))
*link_up = false;
out:
return 0;
}
/**
* ixgbe_setup_mac_link_82598 - Set MAC link speed
* @hw: pointer to hardware structure
* @speed: new link speed
* @autoneg_wait_to_complete: true when waiting for completion is needed
*
* Set the link speed in the AUTOC register and restarts link.
**/
static s32 ixgbe_setup_mac_link_82598(struct ixgbe_hw *hw,
ixgbe_link_speed speed,
bool autoneg_wait_to_complete)
{
bool autoneg = false;
s32 status = 0;
ixgbe_link_speed link_capabilities = IXGBE_LINK_SPEED_UNKNOWN;
u32 curr_autoc = IXGBE_READ_REG(hw, IXGBE_AUTOC);
u32 autoc = curr_autoc;
u32 link_mode = autoc & IXGBE_AUTOC_LMS_MASK;
/* Check to see if speed passed in is supported. */
ixgbe_get_link_capabilities_82598(hw, &link_capabilities, &autoneg);
speed &= link_capabilities;
if (speed == IXGBE_LINK_SPEED_UNKNOWN)
status = IXGBE_ERR_LINK_SETUP;
/* Set KX4/KX support according to speed requested */
else if (link_mode == IXGBE_AUTOC_LMS_KX4_AN ||
link_mode == IXGBE_AUTOC_LMS_KX4_AN_1G_AN) {
autoc &= ~IXGBE_AUTOC_KX4_KX_SUPP_MASK;
if (speed & IXGBE_LINK_SPEED_10GB_FULL)
autoc |= IXGBE_AUTOC_KX4_SUPP;
if (speed & IXGBE_LINK_SPEED_1GB_FULL)
autoc |= IXGBE_AUTOC_KX_SUPP;
if (autoc != curr_autoc)
IXGBE_WRITE_REG(hw, IXGBE_AUTOC, autoc);
}
if (status == 0) {
/*
* Setup and restart the link based on the new values in
* ixgbe_hw This will write the AUTOC register based on the new
* stored values
*/
status = ixgbe_start_mac_link_82598(hw,
autoneg_wait_to_complete);
}
return status;
}
/**
* ixgbe_setup_copper_link_82598 - Set the PHY autoneg advertised field
* @hw: pointer to hardware structure
* @speed: new link speed
* @autoneg_wait_to_complete: true if waiting is needed to complete
*
* Sets the link speed in the AUTOC register in the MAC and restarts link.
**/
static s32 ixgbe_setup_copper_link_82598(struct ixgbe_hw *hw,
ixgbe_link_speed speed,
bool autoneg_wait_to_complete)
{
s32 status;
/* Setup the PHY according to input speed */
status = hw->phy.ops.setup_link_speed(hw, speed,
autoneg_wait_to_complete);
/* Set up MAC */
ixgbe_start_mac_link_82598(hw, autoneg_wait_to_complete);
return status;
}
/**
* ixgbe_reset_hw_82598 - Performs hardware reset
* @hw: pointer to hardware structure
*
* Resets the hardware by resetting the transmit and receive units, masks and
* clears all interrupts, performing a PHY reset, and performing a link (MAC)
* reset.
**/
static s32 ixgbe_reset_hw_82598(struct ixgbe_hw *hw)
{
s32 status = 0;
s32 phy_status = 0;
u32 ctrl;
u32 gheccr;
u32 i;
u32 autoc;
u8 analog_val;
/* Call adapter stop to disable tx/rx and clear interrupts */
status = hw->mac.ops.stop_adapter(hw);
if (status != 0)
goto reset_hw_out;
/*
* Power up the Atlas Tx lanes if they are currently powered down.
* Atlas Tx lanes are powered down for MAC loopback tests, but
* they are not automatically restored on reset.
*/
hw->mac.ops.read_analog_reg8(hw, IXGBE_ATLAS_PDN_LPBK, &analog_val);
if (analog_val & IXGBE_ATLAS_PDN_TX_REG_EN) {
/* Enable Tx Atlas so packets can be transmitted again */
hw->mac.ops.read_analog_reg8(hw, IXGBE_ATLAS_PDN_LPBK,
&analog_val);
analog_val &= ~IXGBE_ATLAS_PDN_TX_REG_EN;
hw->mac.ops.write_analog_reg8(hw, IXGBE_ATLAS_PDN_LPBK,
analog_val);
hw->mac.ops.read_analog_reg8(hw, IXGBE_ATLAS_PDN_10G,
&analog_val);
analog_val &= ~IXGBE_ATLAS_PDN_TX_10G_QL_ALL;
hw->mac.ops.write_analog_reg8(hw, IXGBE_ATLAS_PDN_10G,
analog_val);
hw->mac.ops.read_analog_reg8(hw, IXGBE_ATLAS_PDN_1G,
&analog_val);
analog_val &= ~IXGBE_ATLAS_PDN_TX_1G_QL_ALL;
hw->mac.ops.write_analog_reg8(hw, IXGBE_ATLAS_PDN_1G,
analog_val);
hw->mac.ops.read_analog_reg8(hw, IXGBE_ATLAS_PDN_AN,
&analog_val);
analog_val &= ~IXGBE_ATLAS_PDN_TX_AN_QL_ALL;
hw->mac.ops.write_analog_reg8(hw, IXGBE_ATLAS_PDN_AN,
analog_val);
}
/* Reset PHY */
if (hw->phy.reset_disable == false) {
/* PHY ops must be identified and initialized prior to reset */
/* Init PHY and function pointers, perform SFP setup */
phy_status = hw->phy.ops.init(hw);
if (phy_status == IXGBE_ERR_SFP_NOT_SUPPORTED)
goto reset_hw_out;
if (phy_status == IXGBE_ERR_SFP_NOT_PRESENT)
goto mac_reset_top;
hw->phy.ops.reset(hw);
}
mac_reset_top:
/*
* Issue global reset to the MAC. This needs to be a SW reset.
* If link reset is used, it might reset the MAC when mng is using it
*/
ctrl = IXGBE_READ_REG(hw, IXGBE_CTRL) | IXGBE_CTRL_RST;
IXGBE_WRITE_REG(hw, IXGBE_CTRL, ctrl);
IXGBE_WRITE_FLUSH(hw);
/* Poll for reset bit to self-clear indicating reset is complete */
for (i = 0; i < 10; i++) {
udelay(1);
ctrl = IXGBE_READ_REG(hw, IXGBE_CTRL);
if (!(ctrl & IXGBE_CTRL_RST))
break;
}
if (ctrl & IXGBE_CTRL_RST) {
status = IXGBE_ERR_RESET_FAILED;
hw_dbg(hw, "Reset polling failed to complete.\n");
}
msleep(50);
/*
* Double resets are required for recovery from certain error
* conditions. Between resets, it is necessary to stall to allow time
* for any pending HW events to complete.
*/
if (hw->mac.flags & IXGBE_FLAGS_DOUBLE_RESET_REQUIRED) {
hw->mac.flags &= ~IXGBE_FLAGS_DOUBLE_RESET_REQUIRED;
goto mac_reset_top;
}
gheccr = IXGBE_READ_REG(hw, IXGBE_GHECCR);
gheccr &= ~((1 << 21) | (1 << 18) | (1 << 9) | (1 << 6));
IXGBE_WRITE_REG(hw, IXGBE_GHECCR, gheccr);
/*
* Store the original AUTOC value if it has not been
* stored off yet. Otherwise restore the stored original
* AUTOC value since the reset operation sets back to deaults.
*/
autoc = IXGBE_READ_REG(hw, IXGBE_AUTOC);
if (hw->mac.orig_link_settings_stored == false) {
hw->mac.orig_autoc = autoc;
hw->mac.orig_link_settings_stored = true;
} else if (autoc != hw->mac.orig_autoc) {
IXGBE_WRITE_REG(hw, IXGBE_AUTOC, hw->mac.orig_autoc);
}
/* Store the permanent mac address */
hw->mac.ops.get_mac_addr(hw, hw->mac.perm_addr);
/*
* Store MAC address from RAR0, clear receive address registers, and
* clear the multicast table
*/
hw->mac.ops.init_rx_addrs(hw);
reset_hw_out:
if (phy_status)
status = phy_status;
return status;
}
/**
* ixgbe_set_vmdq_82598 - Associate a VMDq set index with a rx address
* @hw: pointer to hardware struct
* @rar: receive address register index to associate with a VMDq index
* @vmdq: VMDq set index
**/
static s32 ixgbe_set_vmdq_82598(struct ixgbe_hw *hw, u32 rar, u32 vmdq)
{
u32 rar_high;
u32 rar_entries = hw->mac.num_rar_entries;
/* Make sure we are using a valid rar index range */
if (rar >= rar_entries) {
hw_dbg(hw, "RAR index %d is out of range.\n", rar);
return IXGBE_ERR_INVALID_ARGUMENT;
}
rar_high = IXGBE_READ_REG(hw, IXGBE_RAH(rar));
rar_high &= ~IXGBE_RAH_VIND_MASK;
rar_high |= ((vmdq << IXGBE_RAH_VIND_SHIFT) & IXGBE_RAH_VIND_MASK);
IXGBE_WRITE_REG(hw, IXGBE_RAH(rar), rar_high);
return 0;
}
/**
* ixgbe_clear_vmdq_82598 - Disassociate a VMDq set index from an rx address
* @hw: pointer to hardware struct
* @rar: receive address register index to associate with a VMDq index
* @vmdq: VMDq clear index (not used in 82598, but elsewhere)
**/
static s32 ixgbe_clear_vmdq_82598(struct ixgbe_hw *hw, u32 rar, u32 vmdq)
{
u32 rar_high;
u32 rar_entries = hw->mac.num_rar_entries;
/* Make sure we are using a valid rar index range */
if (rar >= rar_entries) {
hw_dbg(hw, "RAR index %d is out of range.\n", rar);
return IXGBE_ERR_INVALID_ARGUMENT;
}
rar_high = IXGBE_READ_REG(hw, IXGBE_RAH(rar));
if (rar_high & IXGBE_RAH_VIND_MASK) {
rar_high &= ~IXGBE_RAH_VIND_MASK;
IXGBE_WRITE_REG(hw, IXGBE_RAH(rar), rar_high);
}
return 0;
}
/**
* ixgbe_set_vfta_82598 - Set VLAN filter table
* @hw: pointer to hardware structure
* @vlan: VLAN id to write to VLAN filter
* @vind: VMDq output index that maps queue to VLAN id in VFTA
* @vlan_on: boolean flag to turn on/off VLAN in VFTA
*
* Turn on/off specified VLAN in the VLAN filter table.
**/
static s32 ixgbe_set_vfta_82598(struct ixgbe_hw *hw, u32 vlan, u32 vind,
bool vlan_on)
{
u32 regindex;
u32 bitindex;
u32 bits;
u32 vftabyte;
if (vlan > 4095)
return IXGBE_ERR_PARAM;
/* Determine 32-bit word position in array */
regindex = (vlan >> 5) & 0x7F; /* upper seven bits */
/* Determine the location of the (VMD) queue index */
vftabyte = ((vlan >> 3) & 0x03); /* bits (4:3) indicating byte array */
bitindex = (vlan & 0x7) << 2; /* lower 3 bits indicate nibble */
/* Set the nibble for VMD queue index */
bits = IXGBE_READ_REG(hw, IXGBE_VFTAVIND(vftabyte, regindex));
bits &= (~(0x0F << bitindex));
bits |= (vind << bitindex);
IXGBE_WRITE_REG(hw, IXGBE_VFTAVIND(vftabyte, regindex), bits);
/* Determine the location of the bit for this VLAN id */
bitindex = vlan & 0x1F; /* lower five bits */
bits = IXGBE_READ_REG(hw, IXGBE_VFTA(regindex));
if (vlan_on)
/* Turn on this VLAN id */
bits |= (1 << bitindex);
else
/* Turn off this VLAN id */
bits &= ~(1 << bitindex);
IXGBE_WRITE_REG(hw, IXGBE_VFTA(regindex), bits);
return 0;
}
/**
* ixgbe_clear_vfta_82598 - Clear VLAN filter table
* @hw: pointer to hardware structure
*
* Clears the VLAN filer table, and the VMDq index associated with the filter
**/
static s32 ixgbe_clear_vfta_82598(struct ixgbe_hw *hw)
{
u32 offset;
u32 vlanbyte;
for (offset = 0; offset < hw->mac.vft_size; offset++)
IXGBE_WRITE_REG(hw, IXGBE_VFTA(offset), 0);
for (vlanbyte = 0; vlanbyte < 4; vlanbyte++)
for (offset = 0; offset < hw->mac.vft_size; offset++)
IXGBE_WRITE_REG(hw, IXGBE_VFTAVIND(vlanbyte, offset),
0);
return 0;
}
/**
* ixgbe_read_analog_reg8_82598 - Reads 8 bit Atlas analog register
* @hw: pointer to hardware structure
* @reg: analog register to read
* @val: read value
*
* Performs read operation to Atlas analog register specified.
**/
static s32 ixgbe_read_analog_reg8_82598(struct ixgbe_hw *hw, u32 reg, u8 *val)
{
u32 atlas_ctl;
IXGBE_WRITE_REG(hw, IXGBE_ATLASCTL,
IXGBE_ATLASCTL_WRITE_CMD | (reg << 8));
IXGBE_WRITE_FLUSH(hw);
udelay(10);
atlas_ctl = IXGBE_READ_REG(hw, IXGBE_ATLASCTL);
*val = (u8)atlas_ctl;
return 0;
}
/**
* ixgbe_write_analog_reg8_82598 - Writes 8 bit Atlas analog register
* @hw: pointer to hardware structure
* @reg: atlas register to write
* @val: value to write
*
* Performs write operation to Atlas analog register specified.
**/
static s32 ixgbe_write_analog_reg8_82598(struct ixgbe_hw *hw, u32 reg, u8 val)
{
u32 atlas_ctl;
atlas_ctl = (reg << 8) | val;
IXGBE_WRITE_REG(hw, IXGBE_ATLASCTL, atlas_ctl);
IXGBE_WRITE_FLUSH(hw);
udelay(10);
return 0;
}
/**
* ixgbe_read_i2c_phy_82598 - Reads 8 bit word over I2C interface.
* @hw: pointer to hardware structure
* @dev_addr: address to read from
* @byte_offset: byte offset to read from dev_addr
* @eeprom_data: value read
*
* Performs 8 byte read operation to SFP module's data over I2C interface.
**/
static s32 ixgbe_read_i2c_phy_82598(struct ixgbe_hw *hw, u8 dev_addr,
u8 byte_offset, u8 *eeprom_data)
{
s32 status = 0;
u16 sfp_addr = 0;
u16 sfp_data = 0;
u16 sfp_stat = 0;
u32 i;
if (hw->phy.type == ixgbe_phy_nl) {
/*
* phy SDA/SCL registers are at addresses 0xC30A to
* 0xC30D. These registers are used to talk to the SFP+
* module's EEPROM through the SDA/SCL (I2C) interface.
*/
sfp_addr = (dev_addr << 8) + byte_offset;
sfp_addr = (sfp_addr | IXGBE_I2C_EEPROM_READ_MASK);
hw->phy.ops.write_reg(hw,
IXGBE_MDIO_PMA_PMD_SDA_SCL_ADDR,
MDIO_MMD_PMAPMD,
sfp_addr);
/* Poll status */
for (i = 0; i < 100; i++) {
hw->phy.ops.read_reg(hw,
IXGBE_MDIO_PMA_PMD_SDA_SCL_STAT,
MDIO_MMD_PMAPMD,
&sfp_stat);
sfp_stat = sfp_stat & IXGBE_I2C_EEPROM_STATUS_MASK;
if (sfp_stat != IXGBE_I2C_EEPROM_STATUS_IN_PROGRESS)
break;
usleep_range(10000, 20000);
}
if (sfp_stat != IXGBE_I2C_EEPROM_STATUS_PASS) {
hw_dbg(hw, "EEPROM read did not pass.\n");
status = IXGBE_ERR_SFP_NOT_PRESENT;
goto out;
}
/* Read data */
hw->phy.ops.read_reg(hw, IXGBE_MDIO_PMA_PMD_SDA_SCL_DATA,
MDIO_MMD_PMAPMD, &sfp_data);
*eeprom_data = (u8)(sfp_data >> 8);
} else {
status = IXGBE_ERR_PHY;
}
out:
return status;
}
/**
* ixgbe_read_i2c_eeprom_82598 - Reads 8 bit word over I2C interface.
* @hw: pointer to hardware structure
* @byte_offset: EEPROM byte offset to read
* @eeprom_data: value read
*
* Performs 8 byte read operation to SFP module's EEPROM over I2C interface.
**/
static s32 ixgbe_read_i2c_eeprom_82598(struct ixgbe_hw *hw, u8 byte_offset,
u8 *eeprom_data)
{
return ixgbe_read_i2c_phy_82598(hw, IXGBE_I2C_EEPROM_DEV_ADDR,
byte_offset, eeprom_data);
}
/**
* ixgbe_read_i2c_sff8472_82598 - Reads 8 bit word over I2C interface.
* @hw: pointer to hardware structure
* @byte_offset: byte offset at address 0xA2
* @eeprom_data: value read
*
* Performs 8 byte read operation to SFP module's SFF-8472 data over I2C
**/
static s32 ixgbe_read_i2c_sff8472_82598(struct ixgbe_hw *hw, u8 byte_offset,
u8 *sff8472_data)
{
return ixgbe_read_i2c_phy_82598(hw, IXGBE_I2C_EEPROM_DEV_ADDR2,
byte_offset, sff8472_data);
}
/**
* ixgbe_get_supported_physical_layer_82598 - Returns physical layer type
* @hw: pointer to hardware structure
*
* Determines physical layer capabilities of the current configuration.
**/
static u32 ixgbe_get_supported_physical_layer_82598(struct ixgbe_hw *hw)
{
u32 physical_layer = IXGBE_PHYSICAL_LAYER_UNKNOWN;
u32 autoc = IXGBE_READ_REG(hw, IXGBE_AUTOC);
u32 pma_pmd_10g = autoc & IXGBE_AUTOC_10G_PMA_PMD_MASK;
u32 pma_pmd_1g = autoc & IXGBE_AUTOC_1G_PMA_PMD_MASK;
u16 ext_ability = 0;
hw->phy.ops.identify(hw);
/* Copper PHY must be checked before AUTOC LMS to determine correct
* physical layer because 10GBase-T PHYs use LMS = KX4/KX */
switch (hw->phy.type) {
case ixgbe_phy_tn:
case ixgbe_phy_cu_unknown:
hw->phy.ops.read_reg(hw, MDIO_PMA_EXTABLE,
MDIO_MMD_PMAPMD, &ext_ability);
if (ext_ability & MDIO_PMA_EXTABLE_10GBT)
physical_layer |= IXGBE_PHYSICAL_LAYER_10GBASE_T;
if (ext_ability & MDIO_PMA_EXTABLE_1000BT)
physical_layer |= IXGBE_PHYSICAL_LAYER_1000BASE_T;
if (ext_ability & MDIO_PMA_EXTABLE_100BTX)
physical_layer |= IXGBE_PHYSICAL_LAYER_100BASE_TX;
goto out;
default:
break;
}
switch (autoc & IXGBE_AUTOC_LMS_MASK) {
case IXGBE_AUTOC_LMS_1G_AN:
case IXGBE_AUTOC_LMS_1G_LINK_NO_AN:
if (pma_pmd_1g == IXGBE_AUTOC_1G_KX)
physical_layer = IXGBE_PHYSICAL_LAYER_1000BASE_KX;
else
physical_layer = IXGBE_PHYSICAL_LAYER_1000BASE_BX;
break;
case IXGBE_AUTOC_LMS_10G_LINK_NO_AN:
if (pma_pmd_10g == IXGBE_AUTOC_10G_CX4)
physical_layer = IXGBE_PHYSICAL_LAYER_10GBASE_CX4;
else if (pma_pmd_10g == IXGBE_AUTOC_10G_KX4)
physical_layer = IXGBE_PHYSICAL_LAYER_10GBASE_KX4;
else /* XAUI */
physical_layer = IXGBE_PHYSICAL_LAYER_UNKNOWN;
break;
case IXGBE_AUTOC_LMS_KX4_AN:
case IXGBE_AUTOC_LMS_KX4_AN_1G_AN:
if (autoc & IXGBE_AUTOC_KX_SUPP)
physical_layer |= IXGBE_PHYSICAL_LAYER_1000BASE_KX;
if (autoc & IXGBE_AUTOC_KX4_SUPP)
physical_layer |= IXGBE_PHYSICAL_LAYER_10GBASE_KX4;
break;
default:
break;
}
if (hw->phy.type == ixgbe_phy_nl) {
hw->phy.ops.identify_sfp(hw);
switch (hw->phy.sfp_type) {
case ixgbe_sfp_type_da_cu:
physical_layer = IXGBE_PHYSICAL_LAYER_SFP_PLUS_CU;
break;
case ixgbe_sfp_type_sr:
physical_layer = IXGBE_PHYSICAL_LAYER_10GBASE_SR;
break;
case ixgbe_sfp_type_lr:
physical_layer = IXGBE_PHYSICAL_LAYER_10GBASE_LR;
break;
default:
physical_layer = IXGBE_PHYSICAL_LAYER_UNKNOWN;
break;
}
}
switch (hw->device_id) {
case IXGBE_DEV_ID_82598_DA_DUAL_PORT:
physical_layer = IXGBE_PHYSICAL_LAYER_SFP_PLUS_CU;
break;
case IXGBE_DEV_ID_82598AF_DUAL_PORT:
case IXGBE_DEV_ID_82598AF_SINGLE_PORT:
case IXGBE_DEV_ID_82598_SR_DUAL_PORT_EM:
physical_layer = IXGBE_PHYSICAL_LAYER_10GBASE_SR;
break;
case IXGBE_DEV_ID_82598EB_XF_LR:
physical_layer = IXGBE_PHYSICAL_LAYER_10GBASE_LR;
break;
default:
break;
}
out:
return physical_layer;
}
/**
* ixgbe_set_lan_id_multi_port_pcie_82598 - Set LAN id for PCIe multiple
* port devices.
* @hw: pointer to the HW structure
*
* Calls common function and corrects issue with some single port devices
* that enable LAN1 but not LAN0.
**/
static void ixgbe_set_lan_id_multi_port_pcie_82598(struct ixgbe_hw *hw)
{
struct ixgbe_bus_info *bus = &hw->bus;
u16 pci_gen = 0;
u16 pci_ctrl2 = 0;
ixgbe_set_lan_id_multi_port_pcie(hw);
/* check if LAN0 is disabled */
hw->eeprom.ops.read(hw, IXGBE_PCIE_GENERAL_PTR, &pci_gen);
if ((pci_gen != 0) && (pci_gen != 0xFFFF)) {
hw->eeprom.ops.read(hw, pci_gen + IXGBE_PCIE_CTRL2, &pci_ctrl2);
/* if LAN0 is completely disabled force function to 0 */
if ((pci_ctrl2 & IXGBE_PCIE_CTRL2_LAN_DISABLE) &&
!(pci_ctrl2 & IXGBE_PCIE_CTRL2_DISABLE_SELECT) &&
!(pci_ctrl2 & IXGBE_PCIE_CTRL2_DUMMY_ENABLE)) {
bus->func = 0;
}
}
}
/**
* ixgbe_set_rxpba_82598 - Configure packet buffers
* @hw: pointer to hardware structure
* @dcb_config: pointer to ixgbe_dcb_config structure
*
* Configure packet buffers.
*/
static void ixgbe_set_rxpba_82598(struct ixgbe_hw *hw, int num_pb, u32 headroom,
int strategy)
{
u32 rxpktsize = IXGBE_RXPBSIZE_64KB;
u8 i = 0;
if (!num_pb)
return;
/* Setup Rx packet buffer sizes */
switch (strategy) {
case PBA_STRATEGY_WEIGHTED:
/* Setup the first four at 80KB */
rxpktsize = IXGBE_RXPBSIZE_80KB;
for (; i < 4; i++)
IXGBE_WRITE_REG(hw, IXGBE_RXPBSIZE(i), rxpktsize);
/* Setup the last four at 48KB...don't re-init i */
rxpktsize = IXGBE_RXPBSIZE_48KB;
/* Fall Through */
case PBA_STRATEGY_EQUAL:
default:
/* Divide the remaining Rx packet buffer evenly among the TCs */
for (; i < IXGBE_MAX_PACKET_BUFFERS; i++)
IXGBE_WRITE_REG(hw, IXGBE_RXPBSIZE(i), rxpktsize);
break;
}
/* Setup Tx packet buffer sizes */
for (i = 0; i < IXGBE_MAX_PACKET_BUFFERS; i++)
IXGBE_WRITE_REG(hw, IXGBE_TXPBSIZE(i), IXGBE_TXPBSIZE_40KB);
return;
}
static struct ixgbe_mac_operations mac_ops_82598 = {
.init_hw = &ixgbe_init_hw_generic,
.reset_hw = &ixgbe_reset_hw_82598,
.start_hw = &ixgbe_start_hw_82598,
.clear_hw_cntrs = &ixgbe_clear_hw_cntrs_generic,
.get_media_type = &ixgbe_get_media_type_82598,
.get_supported_physical_layer = &ixgbe_get_supported_physical_layer_82598,
.enable_rx_dma = &ixgbe_enable_rx_dma_generic,
.get_mac_addr = &ixgbe_get_mac_addr_generic,
.stop_adapter = &ixgbe_stop_adapter_generic,
.get_bus_info = &ixgbe_get_bus_info_generic,
.set_lan_id = &ixgbe_set_lan_id_multi_port_pcie_82598,
.read_analog_reg8 = &ixgbe_read_analog_reg8_82598,
.write_analog_reg8 = &ixgbe_write_analog_reg8_82598,
.setup_link = &ixgbe_setup_mac_link_82598,
.set_rxpba = &ixgbe_set_rxpba_82598,
.check_link = &ixgbe_check_mac_link_82598,
.get_link_capabilities = &ixgbe_get_link_capabilities_82598,
.led_on = &ixgbe_led_on_generic,
.led_off = &ixgbe_led_off_generic,
.blink_led_start = &ixgbe_blink_led_start_generic,
.blink_led_stop = &ixgbe_blink_led_stop_generic,
.set_rar = &ixgbe_set_rar_generic,
.clear_rar = &ixgbe_clear_rar_generic,
.set_vmdq = &ixgbe_set_vmdq_82598,
.clear_vmdq = &ixgbe_clear_vmdq_82598,
.init_rx_addrs = &ixgbe_init_rx_addrs_generic,
.update_mc_addr_list = &ixgbe_update_mc_addr_list_generic,
.enable_mc = &ixgbe_enable_mc_generic,
.disable_mc = &ixgbe_disable_mc_generic,
.clear_vfta = &ixgbe_clear_vfta_82598,
.set_vfta = &ixgbe_set_vfta_82598,
.fc_enable = &ixgbe_fc_enable_82598,
.set_fw_drv_ver = NULL,
.acquire_swfw_sync = &ixgbe_acquire_swfw_sync,
.release_swfw_sync = &ixgbe_release_swfw_sync,
.get_thermal_sensor_data = NULL,
.init_thermal_sensor_thresh = NULL,
.mng_fw_enabled = NULL,
};
static struct ixgbe_eeprom_operations eeprom_ops_82598 = {
.init_params = &ixgbe_init_eeprom_params_generic,
.read = &ixgbe_read_eerd_generic,
.write = &ixgbe_write_eeprom_generic,
.write_buffer = &ixgbe_write_eeprom_buffer_bit_bang_generic,
.read_buffer = &ixgbe_read_eerd_buffer_generic,
.calc_checksum = &ixgbe_calc_eeprom_checksum_generic,
.validate_checksum = &ixgbe_validate_eeprom_checksum_generic,
.update_checksum = &ixgbe_update_eeprom_checksum_generic,
};
static struct ixgbe_phy_operations phy_ops_82598 = {
.identify = &ixgbe_identify_phy_generic,
.identify_sfp = &ixgbe_identify_sfp_module_generic,
.init = &ixgbe_init_phy_ops_82598,
.reset = &ixgbe_reset_phy_generic,
.read_reg = &ixgbe_read_phy_reg_generic,
.write_reg = &ixgbe_write_phy_reg_generic,
.setup_link = &ixgbe_setup_phy_link_generic,
.setup_link_speed = &ixgbe_setup_phy_link_speed_generic,
.read_i2c_sff8472 = &ixgbe_read_i2c_sff8472_82598,
.read_i2c_eeprom = &ixgbe_read_i2c_eeprom_82598,
.check_overtemp = &ixgbe_tn_check_overtemp,
};
struct ixgbe_info ixgbe_82598_info = {
.mac = ixgbe_mac_82598EB,
.get_invariants = &ixgbe_get_invariants_82598,
.mac_ops = &mac_ops_82598,
.eeprom_ops = &eeprom_ops_82598,
.phy_ops = &phy_ops_82598,
};
| gpl-2.0 |
katinatez/android_kernel_oneplus_msm8974 | drivers/hwmon/fam15h_power.c | 2401 | 7552 | /*
* fam15h_power.c - AMD Family 15h processor power monitoring
*
* Copyright (c) 2011 Advanced Micro Devices, Inc.
* Author: Andreas Herrmann <andreas.herrmann3@amd.com>
*
*
* This driver is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License; either
* version 2 of the License, or (at your option) any later version.
*
* This driver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this driver; if not, see <http://www.gnu.org/licenses/>.
*/
#include <linux/err.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/bitops.h>
#include <asm/processor.h>
MODULE_DESCRIPTION("AMD Family 15h CPU processor power monitor");
MODULE_AUTHOR("Andreas Herrmann <andreas.herrmann3@amd.com>");
MODULE_LICENSE("GPL");
/* Family 16h Northbridge's function 4 PCI ID */
#define PCI_DEVICE_ID_AMD_16H_NB_F4 0x1534
/* D18F3 */
#define REG_NORTHBRIDGE_CAP 0xe8
/* D18F4 */
#define REG_PROCESSOR_TDP 0x1b8
/* D18F5 */
#define REG_TDP_RUNNING_AVERAGE 0xe0
#define REG_TDP_LIMIT3 0xe8
struct fam15h_power_data {
struct device *hwmon_dev;
unsigned int tdp_to_watts;
unsigned int base_tdp;
unsigned int processor_pwr_watts;
};
static ssize_t show_power(struct device *dev,
struct device_attribute *attr, char *buf)
{
u32 val, tdp_limit, running_avg_range;
s32 running_avg_capture;
u64 curr_pwr_watts;
struct pci_dev *f4 = to_pci_dev(dev);
struct fam15h_power_data *data = dev_get_drvdata(dev);
pci_bus_read_config_dword(f4->bus, PCI_DEVFN(PCI_SLOT(f4->devfn), 5),
REG_TDP_RUNNING_AVERAGE, &val);
running_avg_capture = (val >> 4) & 0x3fffff;
running_avg_capture = sign_extend32(running_avg_capture, 21);
running_avg_range = (val & 0xf) + 1;
pci_bus_read_config_dword(f4->bus, PCI_DEVFN(PCI_SLOT(f4->devfn), 5),
REG_TDP_LIMIT3, &val);
tdp_limit = val >> 16;
curr_pwr_watts = (tdp_limit + data->base_tdp) << running_avg_range;
curr_pwr_watts -= running_avg_capture;
curr_pwr_watts *= data->tdp_to_watts;
/*
* Convert to microWatt
*
* power is in Watt provided as fixed point integer with
* scaling factor 1/(2^16). For conversion we use
* (10^6)/(2^16) = 15625/(2^10)
*/
curr_pwr_watts = (curr_pwr_watts * 15625) >> (10 + running_avg_range);
return sprintf(buf, "%u\n", (unsigned int) curr_pwr_watts);
}
static DEVICE_ATTR(power1_input, S_IRUGO, show_power, NULL);
static ssize_t show_power_crit(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct fam15h_power_data *data = dev_get_drvdata(dev);
return sprintf(buf, "%u\n", data->processor_pwr_watts);
}
static DEVICE_ATTR(power1_crit, S_IRUGO, show_power_crit, NULL);
static ssize_t show_name(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "fam15h_power\n");
}
static DEVICE_ATTR(name, S_IRUGO, show_name, NULL);
static struct attribute *fam15h_power_attrs[] = {
&dev_attr_power1_input.attr,
&dev_attr_power1_crit.attr,
&dev_attr_name.attr,
NULL
};
static const struct attribute_group fam15h_power_attr_group = {
.attrs = fam15h_power_attrs,
};
static bool __devinit fam15h_power_is_internal_node0(struct pci_dev *f4)
{
u32 val;
pci_bus_read_config_dword(f4->bus, PCI_DEVFN(PCI_SLOT(f4->devfn), 3),
REG_NORTHBRIDGE_CAP, &val);
if ((val & BIT(29)) && ((val >> 30) & 3))
return false;
return true;
}
/*
* Newer BKDG versions have an updated recommendation on how to properly
* initialize the running average range (was: 0xE, now: 0x9). This avoids
* counter saturations resulting in bogus power readings.
* We correct this value ourselves to cope with older BIOSes.
*/
static const struct pci_device_id affected_device[] = {
{ PCI_VDEVICE(AMD, PCI_DEVICE_ID_AMD_15H_NB_F4) },
{ 0 }
};
static void tweak_runavg_range(struct pci_dev *pdev)
{
u32 val;
/*
* let this quirk apply only to the current version of the
* northbridge, since future versions may change the behavior
*/
if (!pci_match_id(affected_device, pdev))
return;
pci_bus_read_config_dword(pdev->bus,
PCI_DEVFN(PCI_SLOT(pdev->devfn), 5),
REG_TDP_RUNNING_AVERAGE, &val);
if ((val & 0xf) != 0xe)
return;
val &= ~0xf;
val |= 0x9;
pci_bus_write_config_dword(pdev->bus,
PCI_DEVFN(PCI_SLOT(pdev->devfn), 5),
REG_TDP_RUNNING_AVERAGE, val);
}
#ifdef CONFIG_PM
static int fam15h_power_resume(struct pci_dev *pdev)
{
tweak_runavg_range(pdev);
return 0;
}
#else
#define fam15h_power_resume NULL
#endif
static void __devinit fam15h_power_init_data(struct pci_dev *f4,
struct fam15h_power_data *data)
{
u32 val;
u64 tmp;
pci_read_config_dword(f4, REG_PROCESSOR_TDP, &val);
data->base_tdp = val >> 16;
tmp = val & 0xffff;
pci_bus_read_config_dword(f4->bus, PCI_DEVFN(PCI_SLOT(f4->devfn), 5),
REG_TDP_LIMIT3, &val);
data->tdp_to_watts = ((val & 0x3ff) << 6) | ((val >> 10) & 0x3f);
tmp *= data->tdp_to_watts;
/* result not allowed to be >= 256W */
if ((tmp >> 16) >= 256)
dev_warn(&f4->dev, "Bogus value for ProcessorPwrWatts "
"(processor_pwr_watts>=%u)\n",
(unsigned int) (tmp >> 16));
/* convert to microWatt */
data->processor_pwr_watts = (tmp * 15625) >> 10;
}
static int __devinit fam15h_power_probe(struct pci_dev *pdev,
const struct pci_device_id *id)
{
struct fam15h_power_data *data;
struct device *dev;
int err;
/*
* though we ignore every other northbridge, we still have to
* do the tweaking on _each_ node in MCM processors as the counters
* are working hand-in-hand
*/
tweak_runavg_range(pdev);
if (!fam15h_power_is_internal_node0(pdev)) {
err = -ENODEV;
goto exit;
}
data = kzalloc(sizeof(struct fam15h_power_data), GFP_KERNEL);
if (!data) {
err = -ENOMEM;
goto exit;
}
fam15h_power_init_data(pdev, data);
dev = &pdev->dev;
dev_set_drvdata(dev, data);
err = sysfs_create_group(&dev->kobj, &fam15h_power_attr_group);
if (err)
goto exit_free_data;
data->hwmon_dev = hwmon_device_register(dev);
if (IS_ERR(data->hwmon_dev)) {
err = PTR_ERR(data->hwmon_dev);
goto exit_remove_group;
}
return 0;
exit_remove_group:
sysfs_remove_group(&dev->kobj, &fam15h_power_attr_group);
exit_free_data:
kfree(data);
exit:
return err;
}
static void __devexit fam15h_power_remove(struct pci_dev *pdev)
{
struct device *dev;
struct fam15h_power_data *data;
dev = &pdev->dev;
data = dev_get_drvdata(dev);
hwmon_device_unregister(data->hwmon_dev);
sysfs_remove_group(&dev->kobj, &fam15h_power_attr_group);
dev_set_drvdata(dev, NULL);
kfree(data);
}
static DEFINE_PCI_DEVICE_TABLE(fam15h_power_id_table) = {
{ PCI_VDEVICE(AMD, PCI_DEVICE_ID_AMD_15H_NB_F4) },
{ PCI_VDEVICE(AMD, PCI_DEVICE_ID_AMD_16H_NB_F4) },
{}
};
MODULE_DEVICE_TABLE(pci, fam15h_power_id_table);
static struct pci_driver fam15h_power_driver = {
.name = "fam15h_power",
.id_table = fam15h_power_id_table,
.probe = fam15h_power_probe,
.remove = __devexit_p(fam15h_power_remove),
.resume = fam15h_power_resume,
};
static int __init fam15h_power_init(void)
{
return pci_register_driver(&fam15h_power_driver);
}
static void __exit fam15h_power_exit(void)
{
pci_unregister_driver(&fam15h_power_driver);
}
module_init(fam15h_power_init)
module_exit(fam15h_power_exit)
| gpl-2.0 |
civato/Note8.0-StormCharger-Android-4.2.2 | arch/arm/mm/fault-armv.c | 2913 | 6906 | /*
* linux/arch/arm/mm/fault-armv.c
*
* Copyright (C) 1995 Linus Torvalds
* Modifications for ARM processor (c) 1995-2002 Russell King
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/bitops.h>
#include <linux/vmalloc.h>
#include <linux/init.h>
#include <linux/pagemap.h>
#include <linux/gfp.h>
#include <asm/bugs.h>
#include <asm/cacheflush.h>
#include <asm/cachetype.h>
#include <asm/pgtable.h>
#include <asm/tlbflush.h>
#include "mm.h"
static pteval_t shared_pte_mask = L_PTE_MT_BUFFERABLE;
#if __LINUX_ARM_ARCH__ < 6
/*
* We take the easy way out of this problem - we make the
* PTE uncacheable. However, we leave the write buffer on.
*
* Note that the pte lock held when calling update_mmu_cache must also
* guard the pte (somewhere else in the same mm) that we modify here.
* Therefore those configurations which might call adjust_pte (those
* without CONFIG_CPU_CACHE_VIPT) cannot support split page_table_lock.
*/
static int do_adjust_pte(struct vm_area_struct *vma, unsigned long address,
unsigned long pfn, pte_t *ptep)
{
pte_t entry = *ptep;
int ret;
/*
* If this page is present, it's actually being shared.
*/
ret = pte_present(entry);
/*
* If this page isn't present, or is already setup to
* fault (ie, is old), we can safely ignore any issues.
*/
if (ret && (pte_val(entry) & L_PTE_MT_MASK) != shared_pte_mask) {
flush_cache_page(vma, address, pfn);
outer_flush_range((pfn << PAGE_SHIFT),
(pfn << PAGE_SHIFT) + PAGE_SIZE);
pte_val(entry) &= ~L_PTE_MT_MASK;
pte_val(entry) |= shared_pte_mask;
set_pte_at(vma->vm_mm, address, ptep, entry);
flush_tlb_page(vma, address);
}
return ret;
}
#if USE_SPLIT_PTLOCKS
/*
* If we are using split PTE locks, then we need to take the page
* lock here. Otherwise we are using shared mm->page_table_lock
* which is already locked, thus cannot take it.
*/
static inline void do_pte_lock(spinlock_t *ptl)
{
/*
* Use nested version here to indicate that we are already
* holding one similar spinlock.
*/
spin_lock_nested(ptl, SINGLE_DEPTH_NESTING);
}
static inline void do_pte_unlock(spinlock_t *ptl)
{
spin_unlock(ptl);
}
#else /* !USE_SPLIT_PTLOCKS */
static inline void do_pte_lock(spinlock_t *ptl) {}
static inline void do_pte_unlock(spinlock_t *ptl) {}
#endif /* USE_SPLIT_PTLOCKS */
static int adjust_pte(struct vm_area_struct *vma, unsigned long address,
unsigned long pfn)
{
spinlock_t *ptl;
pgd_t *pgd;
pud_t *pud;
pmd_t *pmd;
pte_t *pte;
int ret;
pgd = pgd_offset(vma->vm_mm, address);
if (pgd_none_or_clear_bad(pgd))
return 0;
pud = pud_offset(pgd, address);
if (pud_none_or_clear_bad(pud))
return 0;
pmd = pmd_offset(pud, address);
if (pmd_none_or_clear_bad(pmd))
return 0;
/*
* This is called while another page table is mapped, so we
* must use the nested version. This also means we need to
* open-code the spin-locking.
*/
ptl = pte_lockptr(vma->vm_mm, pmd);
pte = pte_offset_map(pmd, address);
do_pte_lock(ptl);
ret = do_adjust_pte(vma, address, pfn, pte);
do_pte_unlock(ptl);
pte_unmap(pte);
return ret;
}
static void
make_coherent(struct address_space *mapping, struct vm_area_struct *vma,
unsigned long addr, pte_t *ptep, unsigned long pfn)
{
struct mm_struct *mm = vma->vm_mm;
struct vm_area_struct *mpnt;
struct prio_tree_iter iter;
unsigned long offset;
pgoff_t pgoff;
int aliases = 0;
pgoff = vma->vm_pgoff + ((addr - vma->vm_start) >> PAGE_SHIFT);
/*
* If we have any shared mappings that are in the same mm
* space, then we need to handle them specially to maintain
* cache coherency.
*/
flush_dcache_mmap_lock(mapping);
vma_prio_tree_foreach(mpnt, &iter, &mapping->i_mmap, pgoff, pgoff) {
/*
* If this VMA is not in our MM, we can ignore it.
* Note that we intentionally mask out the VMA
* that we are fixing up.
*/
if (mpnt->vm_mm != mm || mpnt == vma)
continue;
if (!(mpnt->vm_flags & VM_MAYSHARE))
continue;
offset = (pgoff - mpnt->vm_pgoff) << PAGE_SHIFT;
aliases += adjust_pte(mpnt, mpnt->vm_start + offset, pfn);
}
flush_dcache_mmap_unlock(mapping);
if (aliases)
do_adjust_pte(vma, addr, pfn, ptep);
}
/*
* Take care of architecture specific things when placing a new PTE into
* a page table, or changing an existing PTE. Basically, there are two
* things that we need to take care of:
*
* 1. If PG_dcache_clean is not set for the page, we need to ensure
* that any cache entries for the kernels virtual memory
* range are written back to the page.
* 2. If we have multiple shared mappings of the same space in
* an object, we need to deal with the cache aliasing issues.
*
* Note that the pte lock will be held.
*/
void update_mmu_cache(struct vm_area_struct *vma, unsigned long addr,
pte_t *ptep)
{
unsigned long pfn = pte_pfn(*ptep);
struct address_space *mapping;
struct page *page;
if (!pfn_valid(pfn))
return;
/*
* The zero page is never written to, so never has any dirty
* cache lines, and therefore never needs to be flushed.
*/
page = pfn_to_page(pfn);
if (page == ZERO_PAGE(0))
return;
mapping = page_mapping(page);
if (!test_and_set_bit(PG_dcache_clean, &page->flags))
__flush_dcache_page(mapping, page);
if (mapping) {
if (cache_is_vivt())
make_coherent(mapping, vma, addr, ptep, pfn);
else if (vma->vm_flags & VM_EXEC)
__flush_icache_all();
}
}
#endif /* __LINUX_ARM_ARCH__ < 6 */
/*
* Check whether the write buffer has physical address aliasing
* issues. If it has, we need to avoid them for the case where
* we have several shared mappings of the same object in user
* space.
*/
static int __init check_writebuffer(unsigned long *p1, unsigned long *p2)
{
register unsigned long zero = 0, one = 1, val;
local_irq_disable();
mb();
*p1 = one;
mb();
*p2 = zero;
mb();
val = *p1;
mb();
local_irq_enable();
return val != zero;
}
void __init check_writebuffer_bugs(void)
{
struct page *page;
const char *reason;
unsigned long v = 1;
printk(KERN_INFO "CPU: Testing write buffer coherency: ");
page = alloc_page(GFP_KERNEL);
if (page) {
unsigned long *p1, *p2;
pgprot_t prot = __pgprot_modify(PAGE_KERNEL,
L_PTE_MT_MASK, L_PTE_MT_BUFFERABLE);
p1 = vmap(&page, 1, VM_IOREMAP, prot);
p2 = vmap(&page, 1, VM_IOREMAP, prot);
if (p1 && p2) {
v = check_writebuffer(p1, p2);
reason = "enabling work-around";
} else {
reason = "unable to map memory\n";
}
vunmap(p1);
vunmap(p2);
put_page(page);
} else {
reason = "unable to grab page\n";
}
if (v) {
printk("failed, %s\n", reason);
shared_pte_mask = L_PTE_MT_UNCACHED;
} else {
printk("ok\n");
}
}
| gpl-2.0 |
lioux/AK-tuna | drivers/video/igafb.c | 3169 | 15878 | /*
* linux/drivers/video/igafb.c -- Frame buffer device for IGA 1682
*
* Copyright (C) 1998 Vladimir Roganov and Gleb Raiko
*
* This driver is partly based on the Frame buffer device for ATI Mach64
* and partially on VESA-related code.
*
* Copyright (C) 1997-1998 Geert Uytterhoeven
* Copyright (C) 1998 Bernd Harries
* Copyright (C) 1998 Eddie C. Dost (ecd@skynet.be)
*
* 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.
*/
/******************************************************************************
TODO:
Despite of IGA Card has advanced graphic acceleration,
initial version is almost dummy and does not support it.
Support for video modes and acceleration must be added
together with accelerated X-Windows driver implementation.
Most important thing at this moment is that we have working
JavaEngine1 console & X with new console interface.
******************************************************************************/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/fb.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/nvram.h>
#include <asm/io.h>
#ifdef CONFIG_SPARC
#include <asm/prom.h>
#include <asm/pcic.h>
#endif
#include <video/iga.h>
struct pci_mmap_map {
unsigned long voff;
unsigned long poff;
unsigned long size;
unsigned long prot_flag;
unsigned long prot_mask;
};
struct iga_par {
struct pci_mmap_map *mmap_map;
unsigned long frame_buffer_phys;
unsigned long io_base;
};
struct fb_info fb_info;
struct fb_fix_screeninfo igafb_fix __initdata = {
.id = "IGA 1682",
.type = FB_TYPE_PACKED_PIXELS,
.mmio_len = 1000
};
struct fb_var_screeninfo default_var = {
/* 640x480, 60 Hz, Non-Interlaced (25.175 MHz dotclock) */
.xres = 640,
.yres = 480,
.xres_virtual = 640,
.yres_virtual = 480,
.bits_per_pixel = 8,
.red = {0, 8, 0 },
.green = {0, 8, 0 },
.blue = {0, 8, 0 },
.height = -1,
.width = -1,
.accel_flags = FB_ACCEL_NONE,
.pixclock = 39722,
.left_margin = 48,
.right_margin = 16,
.upper_margin = 33,
.lower_margin = 10,
.hsync_len = 96,
.vsync_len = 2,
.vmode = FB_VMODE_NONINTERLACED
};
#ifdef CONFIG_SPARC
struct fb_var_screeninfo default_var_1024x768 __initdata = {
/* 1024x768, 75 Hz, Non-Interlaced (78.75 MHz dotclock) */
.xres = 1024,
.yres = 768,
.xres_virtual = 1024,
.yres_virtual = 768,
.bits_per_pixel = 8,
.red = {0, 8, 0 },
.green = {0, 8, 0 },
.blue = {0, 8, 0 },
.height = -1,
.width = -1,
.accel_flags = FB_ACCEL_NONE,
.pixclock = 12699,
.left_margin = 176,
.right_margin = 16,
.upper_margin = 28,
.lower_margin = 1,
.hsync_len = 96,
.vsync_len = 3,
.vmode = FB_SYNC_HOR_HIGH_ACT|FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED
};
struct fb_var_screeninfo default_var_1152x900 __initdata = {
/* 1152x900, 76 Hz, Non-Interlaced (110.0 MHz dotclock) */
.xres = 1152,
.yres = 900,
.xres_virtual = 1152,
.yres_virtual = 900,
.bits_per_pixel = 8,
.red = { 0, 8, 0 },
.green = { 0, 8, 0 },
.blue = { 0, 8, 0 },
.height = -1,
.width = -1,
.accel_flags = FB_ACCEL_NONE,
.pixclock = 9091,
.left_margin = 234,
.right_margin = 24,
.upper_margin = 34,
.lower_margin = 3,
.hsync_len = 100,
.vsync_len = 3,
.vmode = FB_SYNC_HOR_HIGH_ACT|FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED
};
struct fb_var_screeninfo default_var_1280x1024 __initdata = {
/* 1280x1024, 75 Hz, Non-Interlaced (135.00 MHz dotclock) */
.xres = 1280,
.yres = 1024,
.xres_virtual = 1280,
.yres_virtual = 1024,
.bits_per_pixel = 8,
.red = {0, 8, 0 },
.green = {0, 8, 0 },
.blue = {0, 8, 0 },
.height = -1,
.width = -1,
.accel_flags = 0,
.pixclock = 7408,
.left_margin = 248,
.right_margin = 16,
.upper_margin = 38,
.lower_margin = 1,
.hsync_len = 144,
.vsync_len = 3,
.vmode = FB_SYNC_HOR_HIGH_ACT|FB_SYNC_VERT_HIGH_ACT, FB_VMODE_NONINTERLACED
};
/*
* Memory-mapped I/O functions for Sparc PCI
*
* On sparc we happen to access I/O with memory mapped functions too.
*/
#define pci_inb(par, reg) readb(par->io_base+(reg))
#define pci_outb(par, val, reg) writeb(val, par->io_base+(reg))
static inline unsigned int iga_inb(struct iga_par *par, unsigned int reg,
unsigned int idx)
{
pci_outb(par, idx, reg);
return pci_inb(par, reg + 1);
}
static inline void iga_outb(struct iga_par *par, unsigned char val,
unsigned int reg, unsigned int idx )
{
pci_outb(par, idx, reg);
pci_outb(par, val, reg+1);
}
#endif /* CONFIG_SPARC */
/*
* Very important functionality for the JavaEngine1 computer:
* make screen border black (usign special IGA registers)
*/
static void iga_blank_border(struct iga_par *par)
{
int i;
#if 0
/*
* PROM does this for us, so keep this code as a reminder
* about required read from 0x3DA and writing of 0x20 in the end.
*/
(void) pci_inb(par, 0x3DA); /* required for every access */
pci_outb(par, IGA_IDX_VGA_OVERSCAN, IGA_ATTR_CTL);
(void) pci_inb(par, IGA_ATTR_CTL+1);
pci_outb(par, 0x38, IGA_ATTR_CTL);
pci_outb(par, 0x20, IGA_ATTR_CTL); /* re-enable visual */
#endif
/*
* This does not work as it was designed because the overscan
* color is looked up in the palette. Therefore, under X11
* overscan changes color.
*/
for (i=0; i < 3; i++)
iga_outb(par, 0, IGA_EXT_CNTRL, IGA_IDX_OVERSCAN_COLOR + i);
}
#ifdef CONFIG_SPARC
static int igafb_mmap(struct fb_info *info,
struct vm_area_struct *vma)
{
struct iga_par *par = (struct iga_par *)info->par;
unsigned int size, page, map_size = 0;
unsigned long map_offset = 0;
int i;
if (!par->mmap_map)
return -ENXIO;
size = vma->vm_end - vma->vm_start;
/* Each page, see which map applies */
for (page = 0; page < size; ) {
map_size = 0;
for (i = 0; par->mmap_map[i].size; i++) {
unsigned long start = par->mmap_map[i].voff;
unsigned long end = start + par->mmap_map[i].size;
unsigned long offset = (vma->vm_pgoff << PAGE_SHIFT) + page;
if (start > offset)
continue;
if (offset >= end)
continue;
map_size = par->mmap_map[i].size - (offset - start);
map_offset = par->mmap_map[i].poff + (offset - start);
break;
}
if (!map_size) {
page += PAGE_SIZE;
continue;
}
if (page + map_size > size)
map_size = size - page;
pgprot_val(vma->vm_page_prot) &= ~(par->mmap_map[i].prot_mask);
pgprot_val(vma->vm_page_prot) |= par->mmap_map[i].prot_flag;
if (remap_pfn_range(vma, vma->vm_start + page,
map_offset >> PAGE_SHIFT, map_size, vma->vm_page_prot))
return -EAGAIN;
page += map_size;
}
if (!map_size)
return -EINVAL;
vma->vm_flags |= VM_IO;
return 0;
}
#endif /* CONFIG_SPARC */
static int igafb_setcolreg(unsigned regno, unsigned red, unsigned green,
unsigned blue, unsigned transp,
struct fb_info *info)
{
/*
* Set a single color register. The values supplied are
* already rounded down to the hardware's capabilities
* (according to the entries in the `var' structure). Return
* != 0 for invalid regno.
*/
struct iga_par *par = (struct iga_par *)info->par;
if (regno >= info->cmap.len)
return 1;
pci_outb(par, regno, DAC_W_INDEX);
pci_outb(par, red, DAC_DATA);
pci_outb(par, green, DAC_DATA);
pci_outb(par, blue, DAC_DATA);
if (regno < 16) {
switch (info->var.bits_per_pixel) {
case 16:
((u16*)(info->pseudo_palette))[regno] =
(regno << 10) | (regno << 5) | regno;
break;
case 24:
((u32*)(info->pseudo_palette))[regno] =
(regno << 16) | (regno << 8) | regno;
break;
case 32:
{ int i;
i = (regno << 8) | regno;
((u32*)(info->pseudo_palette))[regno] = (i << 16) | i;
}
break;
}
}
return 0;
}
/*
* Framebuffer option structure
*/
static struct fb_ops igafb_ops = {
.owner = THIS_MODULE,
.fb_setcolreg = igafb_setcolreg,
.fb_fillrect = cfb_fillrect,
.fb_copyarea = cfb_copyarea,
.fb_imageblit = cfb_imageblit,
#ifdef CONFIG_SPARC
.fb_mmap = igafb_mmap,
#endif
};
static int __init iga_init(struct fb_info *info, struct iga_par *par)
{
char vramsz = iga_inb(par, IGA_EXT_CNTRL, IGA_IDX_EXT_BUS_CNTL)
& MEM_SIZE_ALIAS;
int video_cmap_len;
switch (vramsz) {
case MEM_SIZE_1M:
info->fix.smem_len = 0x100000;
break;
case MEM_SIZE_2M:
info->fix.smem_len = 0x200000;
break;
case MEM_SIZE_4M:
case MEM_SIZE_RESERVED:
info->fix.smem_len = 0x400000;
break;
}
if (info->var.bits_per_pixel > 8)
video_cmap_len = 16;
else
video_cmap_len = 256;
info->fbops = &igafb_ops;
info->flags = FBINFO_DEFAULT;
fb_alloc_cmap(&info->cmap, video_cmap_len, 0);
if (register_framebuffer(info) < 0)
return 0;
printk("fb%d: %s frame buffer device at 0x%08lx [%dMB VRAM]\n",
info->node, info->fix.id,
par->frame_buffer_phys, info->fix.smem_len >> 20);
iga_blank_border(par);
return 1;
}
static int __init igafb_init(void)
{
struct fb_info *info;
struct pci_dev *pdev;
struct iga_par *par;
unsigned long addr;
int size, iga2000 = 0;
if (fb_get_options("igafb", NULL))
return -ENODEV;
pdev = pci_get_device(PCI_VENDOR_ID_INTERG,
PCI_DEVICE_ID_INTERG_1682, 0);
if (pdev == NULL) {
/*
* XXX We tried to use cyber2000fb.c for IGS 2000.
* But it does not initialize the chip in JavaStation-E, alas.
*/
pdev = pci_get_device(PCI_VENDOR_ID_INTERG, 0x2000, 0);
if(pdev == NULL) {
return -ENXIO;
}
iga2000 = 1;
}
/* We leak a reference here but as it cannot be unloaded this is
fine. If you write unload code remember to free it in unload */
size = sizeof(struct iga_par) + sizeof(u32)*16;
info = framebuffer_alloc(size, &pdev->dev);
if (!info) {
printk("igafb_init: can't alloc fb_info\n");
pci_dev_put(pdev);
return -ENOMEM;
}
par = info->par;
if ((addr = pdev->resource[0].start) == 0) {
printk("igafb_init: no memory start\n");
kfree(info);
pci_dev_put(pdev);
return -ENXIO;
}
if ((info->screen_base = ioremap(addr, 1024*1024*2)) == 0) {
printk("igafb_init: can't remap %lx[2M]\n", addr);
kfree(info);
pci_dev_put(pdev);
return -ENXIO;
}
par->frame_buffer_phys = addr & PCI_BASE_ADDRESS_MEM_MASK;
#ifdef CONFIG_SPARC
/*
* The following is sparc specific and this is why:
*
* IGS2000 has its I/O memory mapped and we want
* to generate memory cycles on PCI, e.g. do ioremap(),
* then readb/writeb() as in Documentation/IO-mapping.txt.
*
* IGS1682 is more traditional, it responds to PCI I/O
* cycles, so we want to access it with inb()/outb().
*
* On sparc, PCIC converts CPU memory access within
* phys window 0x3000xxxx into PCI I/O cycles. Therefore
* we may use readb/writeb to access them with IGS1682.
*
* We do not take io_base_phys from resource[n].start
* on IGS1682 because that chip is BROKEN. It does not
* have a base register for I/O. We just "know" what its
* I/O addresses are.
*/
if (iga2000) {
igafb_fix.mmio_start = par->frame_buffer_phys | 0x00800000;
} else {
igafb_fix.mmio_start = 0x30000000; /* XXX */
}
if ((par->io_base = (int) ioremap(igafb_fix.mmio_start, igafb_fix.smem_len)) == 0) {
printk("igafb_init: can't remap %lx[4K]\n", igafb_fix.mmio_start);
iounmap((void *)info->screen_base);
kfree(info);
pci_dev_put(pdev);
return -ENXIO;
}
/*
* Figure mmap addresses from PCI config space.
* We need two regions: for video memory and for I/O ports.
* Later one can add region for video coprocessor registers.
* However, mmap routine loops until size != 0, so we put
* one additional region with size == 0.
*/
par->mmap_map = kzalloc(4 * sizeof(*par->mmap_map), GFP_ATOMIC);
if (!par->mmap_map) {
printk("igafb_init: can't alloc mmap_map\n");
iounmap((void *)par->io_base);
iounmap(info->screen_base);
kfree(info);
pci_dev_put(pdev);
return -ENOMEM;
}
/*
* Set default vmode and cmode from PROM properties.
*/
{
struct device_node *dp = pci_device_to_OF_node(pdev);
int node = dp->node;
int width = prom_getintdefault(node, "width", 1024);
int height = prom_getintdefault(node, "height", 768);
int depth = prom_getintdefault(node, "depth", 8);
switch (width) {
case 1024:
if (height == 768)
default_var = default_var_1024x768;
break;
case 1152:
if (height == 900)
default_var = default_var_1152x900;
break;
case 1280:
if (height == 1024)
default_var = default_var_1280x1024;
break;
default:
break;
}
switch (depth) {
case 8:
default_var.bits_per_pixel = 8;
break;
case 16:
default_var.bits_per_pixel = 16;
break;
case 24:
default_var.bits_per_pixel = 24;
break;
case 32:
default_var.bits_per_pixel = 32;
break;
default:
break;
}
}
#endif
igafb_fix.smem_start = (unsigned long) info->screen_base;
igafb_fix.line_length = default_var.xres*(default_var.bits_per_pixel/8);
igafb_fix.visual = default_var.bits_per_pixel <= 8 ? FB_VISUAL_PSEUDOCOLOR : FB_VISUAL_DIRECTCOLOR;
info->var = default_var;
info->fix = igafb_fix;
info->pseudo_palette = (void *)(par + 1);
if (!iga_init(info, par)) {
iounmap((void *)par->io_base);
iounmap(info->screen_base);
kfree(par->mmap_map);
kfree(info);
return -ENODEV;
}
#ifdef CONFIG_SPARC
/*
* Add /dev/fb mmap values.
*/
/* First region is for video memory */
par->mmap_map[0].voff = 0x0;
par->mmap_map[0].poff = par->frame_buffer_phys & PAGE_MASK;
par->mmap_map[0].size = info->fix.smem_len & PAGE_MASK;
par->mmap_map[0].prot_mask = SRMMU_CACHE;
par->mmap_map[0].prot_flag = SRMMU_WRITE;
/* Second region is for I/O ports */
par->mmap_map[1].voff = par->frame_buffer_phys & PAGE_MASK;
par->mmap_map[1].poff = info->fix.smem_start & PAGE_MASK;
par->mmap_map[1].size = PAGE_SIZE * 2; /* X wants 2 pages */
par->mmap_map[1].prot_mask = SRMMU_CACHE;
par->mmap_map[1].prot_flag = SRMMU_WRITE;
#endif /* CONFIG_SPARC */
return 0;
}
static int __init igafb_setup(char *options)
{
char *this_opt;
if (!options || !*options)
return 0;
while ((this_opt = strsep(&options, ",")) != NULL) {
}
return 0;
}
module_init(igafb_init);
MODULE_LICENSE("GPL");
static struct pci_device_id igafb_pci_tbl[] __devinitdata = {
{ PCI_VENDOR_ID_INTERG, PCI_DEVICE_ID_INTERG_1682,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
{ }
};
MODULE_DEVICE_TABLE(pci, igafb_pci_tbl);
| gpl-2.0 |
friedrich420/Sprint-Note-4-Android-5.1.1-Kernel | KernelN910P-5_1_1GIT/drivers/clk/ux500/clk-sysctrl.c | 3681 | 5718 | /*
* Sysctrl clock implementation for ux500 platform.
*
* Copyright (C) 2013 ST-Ericsson SA
* Author: Ulf Hansson <ulf.hansson@linaro.org>
*
* License terms: GNU General Public License (GPL) version 2
*/
#include <linux/clk-provider.h>
#include <linux/mfd/abx500/ab8500-sysctrl.h>
#include <linux/device.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/io.h>
#include <linux/err.h>
#include "clk.h"
#define SYSCTRL_MAX_NUM_PARENTS 4
#define to_clk_sysctrl(_hw) container_of(_hw, struct clk_sysctrl, hw)
struct clk_sysctrl {
struct clk_hw hw;
struct device *dev;
u8 parent_index;
u16 reg_sel[SYSCTRL_MAX_NUM_PARENTS];
u8 reg_mask[SYSCTRL_MAX_NUM_PARENTS];
u8 reg_bits[SYSCTRL_MAX_NUM_PARENTS];
unsigned long rate;
unsigned long enable_delay_us;
};
/* Sysctrl clock operations. */
static int clk_sysctrl_prepare(struct clk_hw *hw)
{
int ret;
struct clk_sysctrl *clk = to_clk_sysctrl(hw);
ret = ab8500_sysctrl_write(clk->reg_sel[0], clk->reg_mask[0],
clk->reg_bits[0]);
if (!ret && clk->enable_delay_us)
usleep_range(clk->enable_delay_us, clk->enable_delay_us);
return ret;
}
static void clk_sysctrl_unprepare(struct clk_hw *hw)
{
struct clk_sysctrl *clk = to_clk_sysctrl(hw);
if (ab8500_sysctrl_clear(clk->reg_sel[0], clk->reg_mask[0]))
dev_err(clk->dev, "clk_sysctrl: %s fail to clear %s.\n",
__func__, __clk_get_name(hw->clk));
}
static unsigned long clk_sysctrl_recalc_rate(struct clk_hw *hw,
unsigned long parent_rate)
{
struct clk_sysctrl *clk = to_clk_sysctrl(hw);
return clk->rate;
}
static int clk_sysctrl_set_parent(struct clk_hw *hw, u8 index)
{
struct clk_sysctrl *clk = to_clk_sysctrl(hw);
u8 old_index = clk->parent_index;
int ret = 0;
if (clk->reg_sel[old_index]) {
ret = ab8500_sysctrl_clear(clk->reg_sel[old_index],
clk->reg_mask[old_index]);
if (ret)
return ret;
}
if (clk->reg_sel[index]) {
ret = ab8500_sysctrl_write(clk->reg_sel[index],
clk->reg_mask[index],
clk->reg_bits[index]);
if (ret) {
if (clk->reg_sel[old_index])
ab8500_sysctrl_write(clk->reg_sel[old_index],
clk->reg_mask[old_index],
clk->reg_bits[old_index]);
return ret;
}
}
clk->parent_index = index;
return ret;
}
static u8 clk_sysctrl_get_parent(struct clk_hw *hw)
{
struct clk_sysctrl *clk = to_clk_sysctrl(hw);
return clk->parent_index;
}
static struct clk_ops clk_sysctrl_gate_ops = {
.prepare = clk_sysctrl_prepare,
.unprepare = clk_sysctrl_unprepare,
};
static struct clk_ops clk_sysctrl_gate_fixed_rate_ops = {
.prepare = clk_sysctrl_prepare,
.unprepare = clk_sysctrl_unprepare,
.recalc_rate = clk_sysctrl_recalc_rate,
};
static struct clk_ops clk_sysctrl_set_parent_ops = {
.set_parent = clk_sysctrl_set_parent,
.get_parent = clk_sysctrl_get_parent,
};
static struct clk *clk_reg_sysctrl(struct device *dev,
const char *name,
const char **parent_names,
u8 num_parents,
u16 *reg_sel,
u8 *reg_mask,
u8 *reg_bits,
unsigned long rate,
unsigned long enable_delay_us,
unsigned long flags,
struct clk_ops *clk_sysctrl_ops)
{
struct clk_sysctrl *clk;
struct clk_init_data clk_sysctrl_init;
struct clk *clk_reg;
int i;
if (!dev)
return ERR_PTR(-EINVAL);
if (!name || (num_parents > SYSCTRL_MAX_NUM_PARENTS)) {
dev_err(dev, "clk_sysctrl: invalid arguments passed\n");
return ERR_PTR(-EINVAL);
}
clk = devm_kzalloc(dev, sizeof(struct clk_sysctrl), GFP_KERNEL);
if (!clk) {
dev_err(dev, "clk_sysctrl: could not allocate clk\n");
return ERR_PTR(-ENOMEM);
}
/* set main clock registers */
clk->reg_sel[0] = reg_sel[0];
clk->reg_bits[0] = reg_bits[0];
clk->reg_mask[0] = reg_mask[0];
/* handle clocks with more than one parent */
for (i = 1; i < num_parents; i++) {
clk->reg_sel[i] = reg_sel[i];
clk->reg_bits[i] = reg_bits[i];
clk->reg_mask[i] = reg_mask[i];
}
clk->parent_index = 0;
clk->rate = rate;
clk->enable_delay_us = enable_delay_us;
clk->dev = dev;
clk_sysctrl_init.name = name;
clk_sysctrl_init.ops = clk_sysctrl_ops;
clk_sysctrl_init.flags = flags;
clk_sysctrl_init.parent_names = parent_names;
clk_sysctrl_init.num_parents = num_parents;
clk->hw.init = &clk_sysctrl_init;
clk_reg = devm_clk_register(clk->dev, &clk->hw);
if (IS_ERR(clk_reg))
dev_err(dev, "clk_sysctrl: clk_register failed\n");
return clk_reg;
}
struct clk *clk_reg_sysctrl_gate(struct device *dev,
const char *name,
const char *parent_name,
u16 reg_sel,
u8 reg_mask,
u8 reg_bits,
unsigned long enable_delay_us,
unsigned long flags)
{
const char **parent_names = (parent_name ? &parent_name : NULL);
u8 num_parents = (parent_name ? 1 : 0);
return clk_reg_sysctrl(dev, name, parent_names, num_parents,
®_sel, ®_mask, ®_bits, 0, enable_delay_us,
flags, &clk_sysctrl_gate_ops);
}
struct clk *clk_reg_sysctrl_gate_fixed_rate(struct device *dev,
const char *name,
const char *parent_name,
u16 reg_sel,
u8 reg_mask,
u8 reg_bits,
unsigned long rate,
unsigned long enable_delay_us,
unsigned long flags)
{
const char **parent_names = (parent_name ? &parent_name : NULL);
u8 num_parents = (parent_name ? 1 : 0);
return clk_reg_sysctrl(dev, name, parent_names, num_parents,
®_sel, ®_mask, ®_bits,
rate, enable_delay_us, flags,
&clk_sysctrl_gate_fixed_rate_ops);
}
struct clk *clk_reg_sysctrl_set_parent(struct device *dev,
const char *name,
const char **parent_names,
u8 num_parents,
u16 *reg_sel,
u8 *reg_mask,
u8 *reg_bits,
unsigned long flags)
{
return clk_reg_sysctrl(dev, name, parent_names, num_parents,
reg_sel, reg_mask, reg_bits, 0, 0, flags,
&clk_sysctrl_set_parent_ops);
}
| gpl-2.0 |
devil1437/GalaxyNexusKernel | drivers/scsi/jazz_esp.c | 4193 | 5579 | /* jazz_esp.c: ESP front-end for MIPS JAZZ systems.
*
* Copyright (C) 2007 Thomas Bogendörfer (tsbogend@alpha.frankende)
*/
#include <linux/kernel.h>
#include <linux/gfp.h>
#include <linux/types.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <asm/irq.h>
#include <asm/io.h>
#include <asm/dma.h>
#include <asm/jazz.h>
#include <asm/jazzdma.h>
#include <scsi/scsi_host.h>
#include "esp_scsi.h"
#define DRV_MODULE_NAME "jazz_esp"
#define PFX DRV_MODULE_NAME ": "
#define DRV_VERSION "1.000"
#define DRV_MODULE_RELDATE "May 19, 2007"
static void jazz_esp_write8(struct esp *esp, u8 val, unsigned long reg)
{
*(volatile u8 *)(esp->regs + reg) = val;
}
static u8 jazz_esp_read8(struct esp *esp, unsigned long reg)
{
return *(volatile u8 *)(esp->regs + reg);
}
static dma_addr_t jazz_esp_map_single(struct esp *esp, void *buf,
size_t sz, int dir)
{
return dma_map_single(esp->dev, buf, sz, dir);
}
static int jazz_esp_map_sg(struct esp *esp, struct scatterlist *sg,
int num_sg, int dir)
{
return dma_map_sg(esp->dev, sg, num_sg, dir);
}
static void jazz_esp_unmap_single(struct esp *esp, dma_addr_t addr,
size_t sz, int dir)
{
dma_unmap_single(esp->dev, addr, sz, dir);
}
static void jazz_esp_unmap_sg(struct esp *esp, struct scatterlist *sg,
int num_sg, int dir)
{
dma_unmap_sg(esp->dev, sg, num_sg, dir);
}
static int jazz_esp_irq_pending(struct esp *esp)
{
if (jazz_esp_read8(esp, ESP_STATUS) & ESP_STAT_INTR)
return 1;
return 0;
}
static void jazz_esp_reset_dma(struct esp *esp)
{
vdma_disable ((int)esp->dma_regs);
}
static void jazz_esp_dma_drain(struct esp *esp)
{
/* nothing to do */
}
static void jazz_esp_dma_invalidate(struct esp *esp)
{
vdma_disable ((int)esp->dma_regs);
}
static void jazz_esp_send_dma_cmd(struct esp *esp, u32 addr, u32 esp_count,
u32 dma_count, int write, u8 cmd)
{
BUG_ON(!(cmd & ESP_CMD_DMA));
jazz_esp_write8(esp, (esp_count >> 0) & 0xff, ESP_TCLOW);
jazz_esp_write8(esp, (esp_count >> 8) & 0xff, ESP_TCMED);
vdma_disable ((int)esp->dma_regs);
if (write)
vdma_set_mode ((int)esp->dma_regs, DMA_MODE_READ);
else
vdma_set_mode ((int)esp->dma_regs, DMA_MODE_WRITE);
vdma_set_addr ((int)esp->dma_regs, addr);
vdma_set_count ((int)esp->dma_regs, dma_count);
vdma_enable ((int)esp->dma_regs);
scsi_esp_cmd(esp, cmd);
}
static int jazz_esp_dma_error(struct esp *esp)
{
u32 enable = vdma_get_enable((int)esp->dma_regs);
if (enable & (R4030_MEM_INTR|R4030_ADDR_INTR))
return 1;
return 0;
}
static const struct esp_driver_ops jazz_esp_ops = {
.esp_write8 = jazz_esp_write8,
.esp_read8 = jazz_esp_read8,
.map_single = jazz_esp_map_single,
.map_sg = jazz_esp_map_sg,
.unmap_single = jazz_esp_unmap_single,
.unmap_sg = jazz_esp_unmap_sg,
.irq_pending = jazz_esp_irq_pending,
.reset_dma = jazz_esp_reset_dma,
.dma_drain = jazz_esp_dma_drain,
.dma_invalidate = jazz_esp_dma_invalidate,
.send_dma_cmd = jazz_esp_send_dma_cmd,
.dma_error = jazz_esp_dma_error,
};
static int __devinit esp_jazz_probe(struct platform_device *dev)
{
struct scsi_host_template *tpnt = &scsi_esp_template;
struct Scsi_Host *host;
struct esp *esp;
struct resource *res;
int err;
host = scsi_host_alloc(tpnt, sizeof(struct esp));
err = -ENOMEM;
if (!host)
goto fail;
host->max_id = 8;
esp = shost_priv(host);
esp->host = host;
esp->dev = dev;
esp->ops = &jazz_esp_ops;
res = platform_get_resource(dev, IORESOURCE_MEM, 0);
if (!res)
goto fail_unlink;
esp->regs = (void __iomem *)res->start;
if (!esp->regs)
goto fail_unlink;
res = platform_get_resource(dev, IORESOURCE_MEM, 1);
if (!res)
goto fail_unlink;
esp->dma_regs = (void __iomem *)res->start;
esp->command_block = dma_alloc_coherent(esp->dev, 16,
&esp->command_block_dma,
GFP_KERNEL);
if (!esp->command_block)
goto fail_unmap_regs;
host->irq = platform_get_irq(dev, 0);
err = request_irq(host->irq, scsi_esp_intr, IRQF_SHARED, "ESP", esp);
if (err < 0)
goto fail_unmap_command_block;
esp->scsi_id = 7;
esp->host->this_id = esp->scsi_id;
esp->scsi_id_mask = (1 << esp->scsi_id);
esp->cfreq = 40000000;
dev_set_drvdata(&dev->dev, esp);
err = scsi_esp_register(esp, &dev->dev);
if (err)
goto fail_free_irq;
return 0;
fail_free_irq:
free_irq(host->irq, esp);
fail_unmap_command_block:
dma_free_coherent(esp->dev, 16,
esp->command_block,
esp->command_block_dma);
fail_unmap_regs:
fail_unlink:
scsi_host_put(host);
fail:
return err;
}
static int __devexit esp_jazz_remove(struct platform_device *dev)
{
struct esp *esp = dev_get_drvdata(&dev->dev);
unsigned int irq = esp->host->irq;
scsi_esp_unregister(esp);
free_irq(irq, esp);
dma_free_coherent(esp->dev, 16,
esp->command_block,
esp->command_block_dma);
scsi_host_put(esp->host);
return 0;
}
/* work with hotplug and coldplug */
MODULE_ALIAS("platform:jazz_esp");
static struct platform_driver esp_jazz_driver = {
.probe = esp_jazz_probe,
.remove = __devexit_p(esp_jazz_remove),
.driver = {
.name = "jazz_esp",
.owner = THIS_MODULE,
},
};
static int __init jazz_esp_init(void)
{
return platform_driver_register(&esp_jazz_driver);
}
static void __exit jazz_esp_exit(void)
{
platform_driver_unregister(&esp_jazz_driver);
}
MODULE_DESCRIPTION("JAZZ ESP SCSI driver");
MODULE_AUTHOR("Thomas Bogendoerfer (tsbogend@alpha.franken.de)");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);
module_init(jazz_esp_init);
module_exit(jazz_esp_exit);
| gpl-2.0 |
Jazz-823/kernel_samsung_i9505 | drivers/spi/spi-dw.c | 4449 | 22756 | /*
* Designware SPI core controller driver (refer pxa2xx_spi.c)
*
* Copyright (c) 2009, Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <linux/dma-mapping.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/highmem.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/spi/spi.h>
#include "spi-dw.h"
#ifdef CONFIG_DEBUG_FS
#include <linux/debugfs.h>
#endif
#define START_STATE ((void *)0)
#define RUNNING_STATE ((void *)1)
#define DONE_STATE ((void *)2)
#define ERROR_STATE ((void *)-1)
#define QUEUE_RUNNING 0
#define QUEUE_STOPPED 1
#define MRST_SPI_DEASSERT 0
#define MRST_SPI_ASSERT 1
/* Slave spi_dev related */
struct chip_data {
u16 cr0;
u8 cs; /* chip select pin */
u8 n_bytes; /* current is a 1/2/4 byte op */
u8 tmode; /* TR/TO/RO/EEPROM */
u8 type; /* SPI/SSP/MicroWire */
u8 poll_mode; /* 1 means use poll mode */
u32 dma_width;
u32 rx_threshold;
u32 tx_threshold;
u8 enable_dma;
u8 bits_per_word;
u16 clk_div; /* baud rate divider */
u32 speed_hz; /* baud rate */
void (*cs_control)(u32 command);
};
#ifdef CONFIG_DEBUG_FS
#define SPI_REGS_BUFSIZE 1024
static ssize_t spi_show_regs(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
struct dw_spi *dws;
char *buf;
u32 len = 0;
ssize_t ret;
dws = file->private_data;
buf = kzalloc(SPI_REGS_BUFSIZE, GFP_KERNEL);
if (!buf)
return 0;
len += snprintf(buf + len, SPI_REGS_BUFSIZE - len,
"MRST SPI0 registers:\n");
len += snprintf(buf + len, SPI_REGS_BUFSIZE - len,
"=================================\n");
len += snprintf(buf + len, SPI_REGS_BUFSIZE - len,
"CTRL0: \t\t0x%08x\n", dw_readl(dws, DW_SPI_CTRL0));
len += snprintf(buf + len, SPI_REGS_BUFSIZE - len,
"CTRL1: \t\t0x%08x\n", dw_readl(dws, DW_SPI_CTRL1));
len += snprintf(buf + len, SPI_REGS_BUFSIZE - len,
"SSIENR: \t0x%08x\n", dw_readl(dws, DW_SPI_SSIENR));
len += snprintf(buf + len, SPI_REGS_BUFSIZE - len,
"SER: \t\t0x%08x\n", dw_readl(dws, DW_SPI_SER));
len += snprintf(buf + len, SPI_REGS_BUFSIZE - len,
"BAUDR: \t\t0x%08x\n", dw_readl(dws, DW_SPI_BAUDR));
len += snprintf(buf + len, SPI_REGS_BUFSIZE - len,
"TXFTLR: \t0x%08x\n", dw_readl(dws, DW_SPI_TXFLTR));
len += snprintf(buf + len, SPI_REGS_BUFSIZE - len,
"RXFTLR: \t0x%08x\n", dw_readl(dws, DW_SPI_RXFLTR));
len += snprintf(buf + len, SPI_REGS_BUFSIZE - len,
"TXFLR: \t\t0x%08x\n", dw_readl(dws, DW_SPI_TXFLR));
len += snprintf(buf + len, SPI_REGS_BUFSIZE - len,
"RXFLR: \t\t0x%08x\n", dw_readl(dws, DW_SPI_RXFLR));
len += snprintf(buf + len, SPI_REGS_BUFSIZE - len,
"SR: \t\t0x%08x\n", dw_readl(dws, DW_SPI_SR));
len += snprintf(buf + len, SPI_REGS_BUFSIZE - len,
"IMR: \t\t0x%08x\n", dw_readl(dws, DW_SPI_IMR));
len += snprintf(buf + len, SPI_REGS_BUFSIZE - len,
"ISR: \t\t0x%08x\n", dw_readl(dws, DW_SPI_ISR));
len += snprintf(buf + len, SPI_REGS_BUFSIZE - len,
"DMACR: \t\t0x%08x\n", dw_readl(dws, DW_SPI_DMACR));
len += snprintf(buf + len, SPI_REGS_BUFSIZE - len,
"DMATDLR: \t0x%08x\n", dw_readl(dws, DW_SPI_DMATDLR));
len += snprintf(buf + len, SPI_REGS_BUFSIZE - len,
"DMARDLR: \t0x%08x\n", dw_readl(dws, DW_SPI_DMARDLR));
len += snprintf(buf + len, SPI_REGS_BUFSIZE - len,
"=================================\n");
ret = simple_read_from_buffer(user_buf, count, ppos, buf, len);
kfree(buf);
return ret;
}
static const struct file_operations mrst_spi_regs_ops = {
.owner = THIS_MODULE,
.open = simple_open,
.read = spi_show_regs,
.llseek = default_llseek,
};
static int mrst_spi_debugfs_init(struct dw_spi *dws)
{
dws->debugfs = debugfs_create_dir("mrst_spi", NULL);
if (!dws->debugfs)
return -ENOMEM;
debugfs_create_file("registers", S_IFREG | S_IRUGO,
dws->debugfs, (void *)dws, &mrst_spi_regs_ops);
return 0;
}
static void mrst_spi_debugfs_remove(struct dw_spi *dws)
{
if (dws->debugfs)
debugfs_remove_recursive(dws->debugfs);
}
#else
static inline int mrst_spi_debugfs_init(struct dw_spi *dws)
{
return 0;
}
static inline void mrst_spi_debugfs_remove(struct dw_spi *dws)
{
}
#endif /* CONFIG_DEBUG_FS */
/* Return the max entries we can fill into tx fifo */
static inline u32 tx_max(struct dw_spi *dws)
{
u32 tx_left, tx_room, rxtx_gap;
tx_left = (dws->tx_end - dws->tx) / dws->n_bytes;
tx_room = dws->fifo_len - dw_readw(dws, DW_SPI_TXFLR);
/*
* Another concern is about the tx/rx mismatch, we
* though to use (dws->fifo_len - rxflr - txflr) as
* one maximum value for tx, but it doesn't cover the
* data which is out of tx/rx fifo and inside the
* shift registers. So a control from sw point of
* view is taken.
*/
rxtx_gap = ((dws->rx_end - dws->rx) - (dws->tx_end - dws->tx))
/ dws->n_bytes;
return min3(tx_left, tx_room, (u32) (dws->fifo_len - rxtx_gap));
}
/* Return the max entries we should read out of rx fifo */
static inline u32 rx_max(struct dw_spi *dws)
{
u32 rx_left = (dws->rx_end - dws->rx) / dws->n_bytes;
return min(rx_left, (u32)dw_readw(dws, DW_SPI_RXFLR));
}
static void dw_writer(struct dw_spi *dws)
{
u32 max = tx_max(dws);
u16 txw = 0;
while (max--) {
/* Set the tx word if the transfer's original "tx" is not null */
if (dws->tx_end - dws->len) {
if (dws->n_bytes == 1)
txw = *(u8 *)(dws->tx);
else
txw = *(u16 *)(dws->tx);
}
dw_writew(dws, DW_SPI_DR, txw);
dws->tx += dws->n_bytes;
}
}
static void dw_reader(struct dw_spi *dws)
{
u32 max = rx_max(dws);
u16 rxw;
while (max--) {
rxw = dw_readw(dws, DW_SPI_DR);
/* Care rx only if the transfer's original "rx" is not null */
if (dws->rx_end - dws->len) {
if (dws->n_bytes == 1)
*(u8 *)(dws->rx) = rxw;
else
*(u16 *)(dws->rx) = rxw;
}
dws->rx += dws->n_bytes;
}
}
static void *next_transfer(struct dw_spi *dws)
{
struct spi_message *msg = dws->cur_msg;
struct spi_transfer *trans = dws->cur_transfer;
/* Move to next transfer */
if (trans->transfer_list.next != &msg->transfers) {
dws->cur_transfer =
list_entry(trans->transfer_list.next,
struct spi_transfer,
transfer_list);
return RUNNING_STATE;
} else
return DONE_STATE;
}
/*
* Note: first step is the protocol driver prepares
* a dma-capable memory, and this func just need translate
* the virt addr to physical
*/
static int map_dma_buffers(struct dw_spi *dws)
{
if (!dws->cur_msg->is_dma_mapped
|| !dws->dma_inited
|| !dws->cur_chip->enable_dma
|| !dws->dma_ops)
return 0;
if (dws->cur_transfer->tx_dma)
dws->tx_dma = dws->cur_transfer->tx_dma;
if (dws->cur_transfer->rx_dma)
dws->rx_dma = dws->cur_transfer->rx_dma;
return 1;
}
/* Caller already set message->status; dma and pio irqs are blocked */
static void giveback(struct dw_spi *dws)
{
struct spi_transfer *last_transfer;
unsigned long flags;
struct spi_message *msg;
spin_lock_irqsave(&dws->lock, flags);
msg = dws->cur_msg;
dws->cur_msg = NULL;
dws->cur_transfer = NULL;
dws->prev_chip = dws->cur_chip;
dws->cur_chip = NULL;
dws->dma_mapped = 0;
queue_work(dws->workqueue, &dws->pump_messages);
spin_unlock_irqrestore(&dws->lock, flags);
last_transfer = list_entry(msg->transfers.prev,
struct spi_transfer,
transfer_list);
if (!last_transfer->cs_change && dws->cs_control)
dws->cs_control(MRST_SPI_DEASSERT);
msg->state = NULL;
if (msg->complete)
msg->complete(msg->context);
}
static void int_error_stop(struct dw_spi *dws, const char *msg)
{
/* Stop the hw */
spi_enable_chip(dws, 0);
dev_err(&dws->master->dev, "%s\n", msg);
dws->cur_msg->state = ERROR_STATE;
tasklet_schedule(&dws->pump_transfers);
}
void dw_spi_xfer_done(struct dw_spi *dws)
{
/* Update total byte transferred return count actual bytes read */
dws->cur_msg->actual_length += dws->len;
/* Move to next transfer */
dws->cur_msg->state = next_transfer(dws);
/* Handle end of message */
if (dws->cur_msg->state == DONE_STATE) {
dws->cur_msg->status = 0;
giveback(dws);
} else
tasklet_schedule(&dws->pump_transfers);
}
EXPORT_SYMBOL_GPL(dw_spi_xfer_done);
static irqreturn_t interrupt_transfer(struct dw_spi *dws)
{
u16 irq_status = dw_readw(dws, DW_SPI_ISR);
/* Error handling */
if (irq_status & (SPI_INT_TXOI | SPI_INT_RXOI | SPI_INT_RXUI)) {
dw_readw(dws, DW_SPI_TXOICR);
dw_readw(dws, DW_SPI_RXOICR);
dw_readw(dws, DW_SPI_RXUICR);
int_error_stop(dws, "interrupt_transfer: fifo overrun/underrun");
return IRQ_HANDLED;
}
dw_reader(dws);
if (dws->rx_end == dws->rx) {
spi_mask_intr(dws, SPI_INT_TXEI);
dw_spi_xfer_done(dws);
return IRQ_HANDLED;
}
if (irq_status & SPI_INT_TXEI) {
spi_mask_intr(dws, SPI_INT_TXEI);
dw_writer(dws);
/* Enable TX irq always, it will be disabled when RX finished */
spi_umask_intr(dws, SPI_INT_TXEI);
}
return IRQ_HANDLED;
}
static irqreturn_t dw_spi_irq(int irq, void *dev_id)
{
struct dw_spi *dws = dev_id;
u16 irq_status = dw_readw(dws, DW_SPI_ISR) & 0x3f;
if (!irq_status)
return IRQ_NONE;
if (!dws->cur_msg) {
spi_mask_intr(dws, SPI_INT_TXEI);
return IRQ_HANDLED;
}
return dws->transfer_handler(dws);
}
/* Must be called inside pump_transfers() */
static void poll_transfer(struct dw_spi *dws)
{
do {
dw_writer(dws);
dw_reader(dws);
cpu_relax();
} while (dws->rx_end > dws->rx);
dw_spi_xfer_done(dws);
}
static void pump_transfers(unsigned long data)
{
struct dw_spi *dws = (struct dw_spi *)data;
struct spi_message *message = NULL;
struct spi_transfer *transfer = NULL;
struct spi_transfer *previous = NULL;
struct spi_device *spi = NULL;
struct chip_data *chip = NULL;
u8 bits = 0;
u8 imask = 0;
u8 cs_change = 0;
u16 txint_level = 0;
u16 clk_div = 0;
u32 speed = 0;
u32 cr0 = 0;
/* Get current state information */
message = dws->cur_msg;
transfer = dws->cur_transfer;
chip = dws->cur_chip;
spi = message->spi;
if (unlikely(!chip->clk_div))
chip->clk_div = dws->max_freq / chip->speed_hz;
if (message->state == ERROR_STATE) {
message->status = -EIO;
goto early_exit;
}
/* Handle end of message */
if (message->state == DONE_STATE) {
message->status = 0;
goto early_exit;
}
/* Delay if requested at end of transfer*/
if (message->state == RUNNING_STATE) {
previous = list_entry(transfer->transfer_list.prev,
struct spi_transfer,
transfer_list);
if (previous->delay_usecs)
udelay(previous->delay_usecs);
}
dws->n_bytes = chip->n_bytes;
dws->dma_width = chip->dma_width;
dws->cs_control = chip->cs_control;
dws->rx_dma = transfer->rx_dma;
dws->tx_dma = transfer->tx_dma;
dws->tx = (void *)transfer->tx_buf;
dws->tx_end = dws->tx + transfer->len;
dws->rx = transfer->rx_buf;
dws->rx_end = dws->rx + transfer->len;
dws->cs_change = transfer->cs_change;
dws->len = dws->cur_transfer->len;
if (chip != dws->prev_chip)
cs_change = 1;
cr0 = chip->cr0;
/* Handle per transfer options for bpw and speed */
if (transfer->speed_hz) {
speed = chip->speed_hz;
if (transfer->speed_hz != speed) {
speed = transfer->speed_hz;
if (speed > dws->max_freq) {
printk(KERN_ERR "MRST SPI0: unsupported"
"freq: %dHz\n", speed);
message->status = -EIO;
goto early_exit;
}
/* clk_div doesn't support odd number */
clk_div = dws->max_freq / speed;
clk_div = (clk_div + 1) & 0xfffe;
chip->speed_hz = speed;
chip->clk_div = clk_div;
}
}
if (transfer->bits_per_word) {
bits = transfer->bits_per_word;
switch (bits) {
case 8:
case 16:
dws->n_bytes = dws->dma_width = bits >> 3;
break;
default:
printk(KERN_ERR "MRST SPI0: unsupported bits:"
"%db\n", bits);
message->status = -EIO;
goto early_exit;
}
cr0 = (bits - 1)
| (chip->type << SPI_FRF_OFFSET)
| (spi->mode << SPI_MODE_OFFSET)
| (chip->tmode << SPI_TMOD_OFFSET);
}
message->state = RUNNING_STATE;
/*
* Adjust transfer mode if necessary. Requires platform dependent
* chipselect mechanism.
*/
if (dws->cs_control) {
if (dws->rx && dws->tx)
chip->tmode = SPI_TMOD_TR;
else if (dws->rx)
chip->tmode = SPI_TMOD_RO;
else
chip->tmode = SPI_TMOD_TO;
cr0 &= ~SPI_TMOD_MASK;
cr0 |= (chip->tmode << SPI_TMOD_OFFSET);
}
/* Check if current transfer is a DMA transaction */
dws->dma_mapped = map_dma_buffers(dws);
/*
* Interrupt mode
* we only need set the TXEI IRQ, as TX/RX always happen syncronizely
*/
if (!dws->dma_mapped && !chip->poll_mode) {
int templen = dws->len / dws->n_bytes;
txint_level = dws->fifo_len / 2;
txint_level = (templen > txint_level) ? txint_level : templen;
imask |= SPI_INT_TXEI | SPI_INT_TXOI | SPI_INT_RXUI | SPI_INT_RXOI;
dws->transfer_handler = interrupt_transfer;
}
/*
* Reprogram registers only if
* 1. chip select changes
* 2. clk_div is changed
* 3. control value changes
*/
if (dw_readw(dws, DW_SPI_CTRL0) != cr0 || cs_change || clk_div || imask) {
spi_enable_chip(dws, 0);
if (dw_readw(dws, DW_SPI_CTRL0) != cr0)
dw_writew(dws, DW_SPI_CTRL0, cr0);
spi_set_clk(dws, clk_div ? clk_div : chip->clk_div);
spi_chip_sel(dws, spi->chip_select);
/* Set the interrupt mask, for poll mode just disable all int */
spi_mask_intr(dws, 0xff);
if (imask)
spi_umask_intr(dws, imask);
if (txint_level)
dw_writew(dws, DW_SPI_TXFLTR, txint_level);
spi_enable_chip(dws, 1);
if (cs_change)
dws->prev_chip = chip;
}
if (dws->dma_mapped)
dws->dma_ops->dma_transfer(dws, cs_change);
if (chip->poll_mode)
poll_transfer(dws);
return;
early_exit:
giveback(dws);
return;
}
static void pump_messages(struct work_struct *work)
{
struct dw_spi *dws =
container_of(work, struct dw_spi, pump_messages);
unsigned long flags;
/* Lock queue and check for queue work */
spin_lock_irqsave(&dws->lock, flags);
if (list_empty(&dws->queue) || dws->run == QUEUE_STOPPED) {
dws->busy = 0;
spin_unlock_irqrestore(&dws->lock, flags);
return;
}
/* Make sure we are not already running a message */
if (dws->cur_msg) {
spin_unlock_irqrestore(&dws->lock, flags);
return;
}
/* Extract head of queue */
dws->cur_msg = list_entry(dws->queue.next, struct spi_message, queue);
list_del_init(&dws->cur_msg->queue);
/* Initial message state*/
dws->cur_msg->state = START_STATE;
dws->cur_transfer = list_entry(dws->cur_msg->transfers.next,
struct spi_transfer,
transfer_list);
dws->cur_chip = spi_get_ctldata(dws->cur_msg->spi);
/* Mark as busy and launch transfers */
tasklet_schedule(&dws->pump_transfers);
dws->busy = 1;
spin_unlock_irqrestore(&dws->lock, flags);
}
/* spi_device use this to queue in their spi_msg */
static int dw_spi_transfer(struct spi_device *spi, struct spi_message *msg)
{
struct dw_spi *dws = spi_master_get_devdata(spi->master);
unsigned long flags;
spin_lock_irqsave(&dws->lock, flags);
if (dws->run == QUEUE_STOPPED) {
spin_unlock_irqrestore(&dws->lock, flags);
return -ESHUTDOWN;
}
msg->actual_length = 0;
msg->status = -EINPROGRESS;
msg->state = START_STATE;
list_add_tail(&msg->queue, &dws->queue);
if (dws->run == QUEUE_RUNNING && !dws->busy) {
if (dws->cur_transfer || dws->cur_msg)
queue_work(dws->workqueue,
&dws->pump_messages);
else {
/* If no other data transaction in air, just go */
spin_unlock_irqrestore(&dws->lock, flags);
pump_messages(&dws->pump_messages);
return 0;
}
}
spin_unlock_irqrestore(&dws->lock, flags);
return 0;
}
/* This may be called twice for each spi dev */
static int dw_spi_setup(struct spi_device *spi)
{
struct dw_spi_chip *chip_info = NULL;
struct chip_data *chip;
if (spi->bits_per_word != 8 && spi->bits_per_word != 16)
return -EINVAL;
/* Only alloc on first setup */
chip = spi_get_ctldata(spi);
if (!chip) {
chip = kzalloc(sizeof(struct chip_data), GFP_KERNEL);
if (!chip)
return -ENOMEM;
}
/*
* Protocol drivers may change the chip settings, so...
* if chip_info exists, use it
*/
chip_info = spi->controller_data;
/* chip_info doesn't always exist */
if (chip_info) {
if (chip_info->cs_control)
chip->cs_control = chip_info->cs_control;
chip->poll_mode = chip_info->poll_mode;
chip->type = chip_info->type;
chip->rx_threshold = 0;
chip->tx_threshold = 0;
chip->enable_dma = chip_info->enable_dma;
}
if (spi->bits_per_word <= 8) {
chip->n_bytes = 1;
chip->dma_width = 1;
} else if (spi->bits_per_word <= 16) {
chip->n_bytes = 2;
chip->dma_width = 2;
} else {
/* Never take >16b case for MRST SPIC */
dev_err(&spi->dev, "invalid wordsize\n");
return -EINVAL;
}
chip->bits_per_word = spi->bits_per_word;
if (!spi->max_speed_hz) {
dev_err(&spi->dev, "No max speed HZ parameter\n");
return -EINVAL;
}
chip->speed_hz = spi->max_speed_hz;
chip->tmode = 0; /* Tx & Rx */
/* Default SPI mode is SCPOL = 0, SCPH = 0 */
chip->cr0 = (chip->bits_per_word - 1)
| (chip->type << SPI_FRF_OFFSET)
| (spi->mode << SPI_MODE_OFFSET)
| (chip->tmode << SPI_TMOD_OFFSET);
spi_set_ctldata(spi, chip);
return 0;
}
static void dw_spi_cleanup(struct spi_device *spi)
{
struct chip_data *chip = spi_get_ctldata(spi);
kfree(chip);
}
static int __devinit init_queue(struct dw_spi *dws)
{
INIT_LIST_HEAD(&dws->queue);
spin_lock_init(&dws->lock);
dws->run = QUEUE_STOPPED;
dws->busy = 0;
tasklet_init(&dws->pump_transfers,
pump_transfers, (unsigned long)dws);
INIT_WORK(&dws->pump_messages, pump_messages);
dws->workqueue = create_singlethread_workqueue(
dev_name(dws->master->dev.parent));
if (dws->workqueue == NULL)
return -EBUSY;
return 0;
}
static int start_queue(struct dw_spi *dws)
{
unsigned long flags;
spin_lock_irqsave(&dws->lock, flags);
if (dws->run == QUEUE_RUNNING || dws->busy) {
spin_unlock_irqrestore(&dws->lock, flags);
return -EBUSY;
}
dws->run = QUEUE_RUNNING;
dws->cur_msg = NULL;
dws->cur_transfer = NULL;
dws->cur_chip = NULL;
dws->prev_chip = NULL;
spin_unlock_irqrestore(&dws->lock, flags);
queue_work(dws->workqueue, &dws->pump_messages);
return 0;
}
static int stop_queue(struct dw_spi *dws)
{
unsigned long flags;
unsigned limit = 50;
int status = 0;
spin_lock_irqsave(&dws->lock, flags);
dws->run = QUEUE_STOPPED;
while ((!list_empty(&dws->queue) || dws->busy) && limit--) {
spin_unlock_irqrestore(&dws->lock, flags);
msleep(10);
spin_lock_irqsave(&dws->lock, flags);
}
if (!list_empty(&dws->queue) || dws->busy)
status = -EBUSY;
spin_unlock_irqrestore(&dws->lock, flags);
return status;
}
static int destroy_queue(struct dw_spi *dws)
{
int status;
status = stop_queue(dws);
if (status != 0)
return status;
destroy_workqueue(dws->workqueue);
return 0;
}
/* Restart the controller, disable all interrupts, clean rx fifo */
static void spi_hw_init(struct dw_spi *dws)
{
spi_enable_chip(dws, 0);
spi_mask_intr(dws, 0xff);
spi_enable_chip(dws, 1);
/*
* Try to detect the FIFO depth if not set by interface driver,
* the depth could be from 2 to 256 from HW spec
*/
if (!dws->fifo_len) {
u32 fifo;
for (fifo = 2; fifo <= 257; fifo++) {
dw_writew(dws, DW_SPI_TXFLTR, fifo);
if (fifo != dw_readw(dws, DW_SPI_TXFLTR))
break;
}
dws->fifo_len = (fifo == 257) ? 0 : fifo;
dw_writew(dws, DW_SPI_TXFLTR, 0);
}
}
int __devinit dw_spi_add_host(struct dw_spi *dws)
{
struct spi_master *master;
int ret;
BUG_ON(dws == NULL);
master = spi_alloc_master(dws->parent_dev, 0);
if (!master) {
ret = -ENOMEM;
goto exit;
}
dws->master = master;
dws->type = SSI_MOTO_SPI;
dws->prev_chip = NULL;
dws->dma_inited = 0;
dws->dma_addr = (dma_addr_t)(dws->paddr + 0x60);
snprintf(dws->name, sizeof(dws->name), "dw_spi%d",
dws->bus_num);
ret = request_irq(dws->irq, dw_spi_irq, IRQF_SHARED,
dws->name, dws);
if (ret < 0) {
dev_err(&master->dev, "can not get IRQ\n");
goto err_free_master;
}
master->mode_bits = SPI_CPOL | SPI_CPHA;
master->bus_num = dws->bus_num;
master->num_chipselect = dws->num_cs;
master->cleanup = dw_spi_cleanup;
master->setup = dw_spi_setup;
master->transfer = dw_spi_transfer;
/* Basic HW init */
spi_hw_init(dws);
if (dws->dma_ops && dws->dma_ops->dma_init) {
ret = dws->dma_ops->dma_init(dws);
if (ret) {
dev_warn(&master->dev, "DMA init failed\n");
dws->dma_inited = 0;
}
}
/* Initial and start queue */
ret = init_queue(dws);
if (ret) {
dev_err(&master->dev, "problem initializing queue\n");
goto err_diable_hw;
}
ret = start_queue(dws);
if (ret) {
dev_err(&master->dev, "problem starting queue\n");
goto err_diable_hw;
}
spi_master_set_devdata(master, dws);
ret = spi_register_master(master);
if (ret) {
dev_err(&master->dev, "problem registering spi master\n");
goto err_queue_alloc;
}
mrst_spi_debugfs_init(dws);
return 0;
err_queue_alloc:
destroy_queue(dws);
if (dws->dma_ops && dws->dma_ops->dma_exit)
dws->dma_ops->dma_exit(dws);
err_diable_hw:
spi_enable_chip(dws, 0);
free_irq(dws->irq, dws);
err_free_master:
spi_master_put(master);
exit:
return ret;
}
EXPORT_SYMBOL_GPL(dw_spi_add_host);
void __devexit dw_spi_remove_host(struct dw_spi *dws)
{
int status = 0;
if (!dws)
return;
mrst_spi_debugfs_remove(dws);
/* Remove the queue */
status = destroy_queue(dws);
if (status != 0)
dev_err(&dws->master->dev, "dw_spi_remove: workqueue will not "
"complete, message memory not freed\n");
if (dws->dma_ops && dws->dma_ops->dma_exit)
dws->dma_ops->dma_exit(dws);
spi_enable_chip(dws, 0);
/* Disable clk */
spi_set_clk(dws, 0);
free_irq(dws->irq, dws);
/* Disconnect from the SPI framework */
spi_unregister_master(dws->master);
}
EXPORT_SYMBOL_GPL(dw_spi_remove_host);
int dw_spi_suspend_host(struct dw_spi *dws)
{
int ret = 0;
ret = stop_queue(dws);
if (ret)
return ret;
spi_enable_chip(dws, 0);
spi_set_clk(dws, 0);
return ret;
}
EXPORT_SYMBOL_GPL(dw_spi_suspend_host);
int dw_spi_resume_host(struct dw_spi *dws)
{
int ret;
spi_hw_init(dws);
ret = start_queue(dws);
if (ret)
dev_err(&dws->master->dev, "fail to start queue (%d)\n", ret);
return ret;
}
EXPORT_SYMBOL_GPL(dw_spi_resume_host);
MODULE_AUTHOR("Feng Tang <feng.tang@intel.com>");
MODULE_DESCRIPTION("Driver for DesignWare SPI controller core");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
ardatdat/archos-kernel | arch/um/drivers/port_user.c | 4705 | 3774 | /*
* Copyright (C) 2001 - 2007 Jeff Dike (jdike@{linux.intel,addtoit}.com)
* Licensed under the GPL
*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <termios.h>
#include <unistd.h>
#include <netinet/in.h>
#include "chan_user.h"
#include "kern_constants.h"
#include "os.h"
#include "port.h"
#include "um_malloc.h"
#include "user.h"
struct port_chan {
int raw;
struct termios tt;
void *kernel_data;
char dev[sizeof("32768\0")];
};
static void *port_init(char *str, int device, const struct chan_opts *opts)
{
struct port_chan *data;
void *kern_data;
char *end;
int port;
if (*str != ':') {
printk(UM_KERN_ERR "port_init : channel type 'port' must "
"specify a port number\n");
return NULL;
}
str++;
port = strtoul(str, &end, 0);
if ((*end != '\0') || (end == str)) {
printk(UM_KERN_ERR "port_init : couldn't parse port '%s'\n",
str);
return NULL;
}
kern_data = port_data(port);
if (kern_data == NULL)
return NULL;
data = uml_kmalloc(sizeof(*data), UM_GFP_KERNEL);
if (data == NULL)
goto err;
*data = ((struct port_chan) { .raw = opts->raw,
.kernel_data = kern_data });
sprintf(data->dev, "%d", port);
return data;
err:
port_kern_free(kern_data);
return NULL;
}
static void port_free(void *d)
{
struct port_chan *data = d;
port_kern_free(data->kernel_data);
kfree(data);
}
static int port_open(int input, int output, int primary, void *d,
char **dev_out)
{
struct port_chan *data = d;
int fd, err;
fd = port_wait(data->kernel_data);
if ((fd >= 0) && data->raw) {
CATCH_EINTR(err = tcgetattr(fd, &data->tt));
if (err)
return err;
err = raw(fd);
if (err)
return err;
}
*dev_out = data->dev;
return fd;
}
static void port_close(int fd, void *d)
{
struct port_chan *data = d;
port_remove_dev(data->kernel_data);
os_close_file(fd);
}
const struct chan_ops port_ops = {
.type = "port",
.init = port_init,
.open = port_open,
.close = port_close,
.read = generic_read,
.write = generic_write,
.console_write = generic_console_write,
.window_size = generic_window_size,
.free = port_free,
.winch = 1,
};
int port_listen_fd(int port)
{
struct sockaddr_in addr;
int fd, err, arg;
fd = socket(PF_INET, SOCK_STREAM, 0);
if (fd == -1)
return -errno;
arg = 1;
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &arg, sizeof(arg)) < 0) {
err = -errno;
goto out;
}
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(fd, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
err = -errno;
goto out;
}
if (listen(fd, 1) < 0) {
err = -errno;
goto out;
}
err = os_set_fd_block(fd, 0);
if (err < 0)
goto out;
return fd;
out:
close(fd);
return err;
}
struct port_pre_exec_data {
int sock_fd;
int pipe_fd;
};
static void port_pre_exec(void *arg)
{
struct port_pre_exec_data *data = arg;
dup2(data->sock_fd, 0);
dup2(data->sock_fd, 1);
dup2(data->sock_fd, 2);
close(data->sock_fd);
dup2(data->pipe_fd, 3);
shutdown(3, SHUT_RD);
close(data->pipe_fd);
}
int port_connection(int fd, int *socket, int *pid_out)
{
int new, err;
char *argv[] = { "/usr/sbin/in.telnetd", "-L",
"/usr/lib/uml/port-helper", NULL };
struct port_pre_exec_data data;
new = accept(fd, NULL, 0);
if (new < 0)
return -errno;
err = os_pipe(socket, 0, 0);
if (err < 0)
goto out_close;
data = ((struct port_pre_exec_data)
{ .sock_fd = new,
.pipe_fd = socket[1] });
err = run_helper(port_pre_exec, &data, argv);
if (err < 0)
goto out_shutdown;
*pid_out = err;
return new;
out_shutdown:
shutdown(socket[0], SHUT_RDWR);
close(socket[0]);
shutdown(socket[1], SHUT_RDWR);
close(socket[1]);
out_close:
close(new);
return err;
}
| gpl-2.0 |
alexpotter1/Neutron_msm8974_hammerhead | drivers/staging/iio/dac/ad5504.c | 4961 | 9870 | /*
* AD5504, AD5501 High Voltage Digital to Analog Converter
*
* Copyright 2011 Analog Devices Inc.
*
* Licensed under the GPL-2.
*/
#include <linux/interrupt.h>
#include <linux/fs.h>
#include <linux/device.h>
#include <linux/kernel.h>
#include <linux/spi/spi.h>
#include <linux/slab.h>
#include <linux/sysfs.h>
#include <linux/regulator/consumer.h>
#include <linux/module.h>
#include "../iio.h"
#include "../sysfs.h"
#include "../events.h"
#include "dac.h"
#include "ad5504.h"
#define AD5504_CHANNEL(_chan) { \
.type = IIO_VOLTAGE, \
.indexed = 1, \
.output = 1, \
.channel = (_chan), \
.info_mask = IIO_CHAN_INFO_SCALE_SHARED_BIT, \
.address = AD5504_ADDR_DAC(_chan), \
.scan_type = IIO_ST('u', 12, 16, 0), \
}
static const struct iio_chan_spec ad5504_channels[] = {
AD5504_CHANNEL(0),
AD5504_CHANNEL(1),
AD5504_CHANNEL(2),
AD5504_CHANNEL(3),
};
static int ad5504_spi_write(struct spi_device *spi, u8 addr, u16 val)
{
u16 tmp = cpu_to_be16(AD5504_CMD_WRITE |
AD5504_ADDR(addr) |
(val & AD5504_RES_MASK));
return spi_write(spi, (u8 *)&tmp, 2);
}
static int ad5504_spi_read(struct spi_device *spi, u8 addr)
{
u16 tmp = cpu_to_be16(AD5504_CMD_READ | AD5504_ADDR(addr));
u16 val;
int ret;
struct spi_transfer t = {
.tx_buf = &tmp,
.rx_buf = &val,
.len = 2,
};
struct spi_message m;
spi_message_init(&m);
spi_message_add_tail(&t, &m);
ret = spi_sync(spi, &m);
if (ret < 0)
return ret;
return be16_to_cpu(val) & AD5504_RES_MASK;
}
static int ad5504_read_raw(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan,
int *val,
int *val2,
long m)
{
struct ad5504_state *st = iio_priv(indio_dev);
unsigned long scale_uv;
int ret;
switch (m) {
case 0:
ret = ad5504_spi_read(st->spi, chan->address);
if (ret < 0)
return ret;
*val = ret;
return IIO_VAL_INT;
case IIO_CHAN_INFO_SCALE:
scale_uv = (st->vref_mv * 1000) >> chan->scan_type.realbits;
*val = scale_uv / 1000;
*val2 = (scale_uv % 1000) * 1000;
return IIO_VAL_INT_PLUS_MICRO;
}
return -EINVAL;
}
static int ad5504_write_raw(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan,
int val,
int val2,
long mask)
{
struct ad5504_state *st = iio_priv(indio_dev);
int ret;
switch (mask) {
case 0:
if (val >= (1 << chan->scan_type.realbits) || val < 0)
return -EINVAL;
return ad5504_spi_write(st->spi, chan->address, val);
default:
ret = -EINVAL;
}
return -EINVAL;
}
static ssize_t ad5504_read_powerdown_mode(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct iio_dev *indio_dev = dev_get_drvdata(dev);
struct ad5504_state *st = iio_priv(indio_dev);
const char mode[][14] = {"20kohm_to_gnd", "three_state"};
return sprintf(buf, "%s\n", mode[st->pwr_down_mode]);
}
static ssize_t ad5504_write_powerdown_mode(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t len)
{
struct iio_dev *indio_dev = dev_get_drvdata(dev);
struct ad5504_state *st = iio_priv(indio_dev);
int ret;
if (sysfs_streq(buf, "20kohm_to_gnd"))
st->pwr_down_mode = AD5504_DAC_PWRDN_20K;
else if (sysfs_streq(buf, "three_state"))
st->pwr_down_mode = AD5504_DAC_PWRDN_3STATE;
else
ret = -EINVAL;
return ret ? ret : len;
}
static ssize_t ad5504_read_dac_powerdown(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct iio_dev *indio_dev = dev_get_drvdata(dev);
struct ad5504_state *st = iio_priv(indio_dev);
struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
return sprintf(buf, "%d\n",
!(st->pwr_down_mask & (1 << this_attr->address)));
}
static ssize_t ad5504_write_dac_powerdown(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t len)
{
long readin;
int ret;
struct iio_dev *indio_dev = dev_get_drvdata(dev);
struct ad5504_state *st = iio_priv(indio_dev);
struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
ret = strict_strtol(buf, 10, &readin);
if (ret)
return ret;
if (readin == 0)
st->pwr_down_mask |= (1 << this_attr->address);
else if (readin == 1)
st->pwr_down_mask &= ~(1 << this_attr->address);
else
ret = -EINVAL;
ret = ad5504_spi_write(st->spi, AD5504_ADDR_CTRL,
AD5504_DAC_PWRDWN_MODE(st->pwr_down_mode) |
AD5504_DAC_PWR(st->pwr_down_mask));
/* writes to the CTRL register must be followed by a NOOP */
ad5504_spi_write(st->spi, AD5504_ADDR_NOOP, 0);
return ret ? ret : len;
}
static IIO_DEVICE_ATTR(out_voltage_powerdown_mode, S_IRUGO |
S_IWUSR, ad5504_read_powerdown_mode,
ad5504_write_powerdown_mode, 0);
static IIO_CONST_ATTR(out_voltage_powerdown_mode_available,
"20kohm_to_gnd three_state");
#define IIO_DEV_ATTR_DAC_POWERDOWN(_num, _show, _store, _addr) \
IIO_DEVICE_ATTR(out_voltage##_num##_powerdown, \
S_IRUGO | S_IWUSR, _show, _store, _addr)
static IIO_DEV_ATTR_DAC_POWERDOWN(0, ad5504_read_dac_powerdown,
ad5504_write_dac_powerdown, 0);
static IIO_DEV_ATTR_DAC_POWERDOWN(1, ad5504_read_dac_powerdown,
ad5504_write_dac_powerdown, 1);
static IIO_DEV_ATTR_DAC_POWERDOWN(2, ad5504_read_dac_powerdown,
ad5504_write_dac_powerdown, 2);
static IIO_DEV_ATTR_DAC_POWERDOWN(3, ad5504_read_dac_powerdown,
ad5504_write_dac_powerdown, 3);
static struct attribute *ad5504_attributes[] = {
&iio_dev_attr_out_voltage0_powerdown.dev_attr.attr,
&iio_dev_attr_out_voltage1_powerdown.dev_attr.attr,
&iio_dev_attr_out_voltage2_powerdown.dev_attr.attr,
&iio_dev_attr_out_voltage3_powerdown.dev_attr.attr,
&iio_dev_attr_out_voltage_powerdown_mode.dev_attr.attr,
&iio_const_attr_out_voltage_powerdown_mode_available.dev_attr.attr,
NULL,
};
static const struct attribute_group ad5504_attribute_group = {
.attrs = ad5504_attributes,
};
static struct attribute *ad5501_attributes[] = {
&iio_dev_attr_out_voltage0_powerdown.dev_attr.attr,
&iio_dev_attr_out_voltage_powerdown_mode.dev_attr.attr,
&iio_const_attr_out_voltage_powerdown_mode_available.dev_attr.attr,
NULL,
};
static const struct attribute_group ad5501_attribute_group = {
.attrs = ad5501_attributes,
};
static IIO_CONST_ATTR(temp0_thresh_rising_value, "110000");
static IIO_CONST_ATTR(temp0_thresh_rising_en, "1");
static struct attribute *ad5504_ev_attributes[] = {
&iio_const_attr_temp0_thresh_rising_value.dev_attr.attr,
&iio_const_attr_temp0_thresh_rising_en.dev_attr.attr,
NULL,
};
static struct attribute_group ad5504_ev_attribute_group = {
.attrs = ad5504_ev_attributes,
.name = "events",
};
static irqreturn_t ad5504_event_handler(int irq, void *private)
{
iio_push_event(private,
IIO_UNMOD_EVENT_CODE(IIO_TEMP,
0,
IIO_EV_TYPE_THRESH,
IIO_EV_DIR_RISING),
iio_get_time_ns());
return IRQ_HANDLED;
}
static const struct iio_info ad5504_info = {
.write_raw = ad5504_write_raw,
.read_raw = ad5504_read_raw,
.attrs = &ad5504_attribute_group,
.event_attrs = &ad5504_ev_attribute_group,
.driver_module = THIS_MODULE,
};
static const struct iio_info ad5501_info = {
.write_raw = ad5504_write_raw,
.read_raw = ad5504_read_raw,
.attrs = &ad5501_attribute_group,
.event_attrs = &ad5504_ev_attribute_group,
.driver_module = THIS_MODULE,
};
static int __devinit ad5504_probe(struct spi_device *spi)
{
struct ad5504_platform_data *pdata = spi->dev.platform_data;
struct iio_dev *indio_dev;
struct ad5504_state *st;
struct regulator *reg;
int ret, voltage_uv = 0;
indio_dev = iio_allocate_device(sizeof(*st));
if (indio_dev == NULL) {
ret = -ENOMEM;
goto error_ret;
}
reg = regulator_get(&spi->dev, "vcc");
if (!IS_ERR(reg)) {
ret = regulator_enable(reg);
if (ret)
goto error_put_reg;
voltage_uv = regulator_get_voltage(reg);
}
spi_set_drvdata(spi, indio_dev);
st = iio_priv(indio_dev);
if (voltage_uv)
st->vref_mv = voltage_uv / 1000;
else if (pdata)
st->vref_mv = pdata->vref_mv;
else
dev_warn(&spi->dev, "reference voltage unspecified\n");
st->reg = reg;
st->spi = spi;
indio_dev->dev.parent = &spi->dev;
indio_dev->name = spi_get_device_id(st->spi)->name;
if (spi_get_device_id(st->spi)->driver_data == ID_AD5501) {
indio_dev->info = &ad5501_info;
indio_dev->num_channels = 1;
} else {
indio_dev->info = &ad5504_info;
indio_dev->num_channels = 4;
}
indio_dev->channels = ad5504_channels;
indio_dev->modes = INDIO_DIRECT_MODE;
if (spi->irq) {
ret = request_threaded_irq(spi->irq,
NULL,
&ad5504_event_handler,
IRQF_TRIGGER_FALLING | IRQF_ONESHOT,
spi_get_device_id(st->spi)->name,
indio_dev);
if (ret)
goto error_disable_reg;
}
ret = iio_device_register(indio_dev);
if (ret)
goto error_free_irq;
return 0;
error_free_irq:
free_irq(spi->irq, indio_dev);
error_disable_reg:
if (!IS_ERR(reg))
regulator_disable(reg);
error_put_reg:
if (!IS_ERR(reg))
regulator_put(reg);
iio_free_device(indio_dev);
error_ret:
return ret;
}
static int __devexit ad5504_remove(struct spi_device *spi)
{
struct iio_dev *indio_dev = spi_get_drvdata(spi);
struct ad5504_state *st = iio_priv(indio_dev);
iio_device_unregister(indio_dev);
if (spi->irq)
free_irq(spi->irq, indio_dev);
if (!IS_ERR(st->reg)) {
regulator_disable(st->reg);
regulator_put(st->reg);
}
iio_free_device(indio_dev);
return 0;
}
static const struct spi_device_id ad5504_id[] = {
{"ad5504", ID_AD5504},
{"ad5501", ID_AD5501},
{}
};
MODULE_DEVICE_TABLE(spi, ad5504_id);
static struct spi_driver ad5504_driver = {
.driver = {
.name = "ad5504",
.owner = THIS_MODULE,
},
.probe = ad5504_probe,
.remove = __devexit_p(ad5504_remove),
.id_table = ad5504_id,
};
module_spi_driver(ad5504_driver);
MODULE_AUTHOR("Michael Hennerich <hennerich@blackfin.uclinux.org>");
MODULE_DESCRIPTION("Analog Devices AD5501/AD5501 DAC");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
Frontier314/frontkernel_kitkat | drivers/video/backlight/lp855x_bl.c | 98 | 9283 | /*
* TI LP855x Backlight Driver
*
* Copyright (C) 2011 Texas Instruments
*
* 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/slab.h>
#include <linux/i2c.h>
#include <linux/backlight.h>
#include <linux/err.h>
#include <linux/delay.h>
#include <linux/gpio.h>
#include <linux/platform_data/lp855x.h>
#ifdef CONFIG_HAS_EARLYSUSPEND
#include <linux/earlysuspend.h>
#endif
/* Registers */
#define BRIGHTNESS_CTRL 0x00
#define DEVICE_CTRL 0x01
#define EEPROM_START 0xA0
#define EEPROM_END 0xA7
#define EPROM_START 0x98
#define EPROM_END 0xAF
#define BUF_SIZE 20
#define DEFAULT_BL_NAME "lcd-backlight"
#define MAX_BRIGHTNESS 255
struct lp855x {
const char *chipname;
enum lp855x_chip_id chip_id;
struct i2c_client *client;
struct backlight_device *bl;
struct device *dev;
struct mutex xfer_lock;
struct lp855x_platform_data *pdata;
int enabled;
#ifdef CONFIG_HAS_EARLYSUSPEND
struct early_suspend early_suspend;
#endif
};
static int lp855x_read_byte(struct lp855x *lp, u8 reg, u8 *data)
{
int ret;
mutex_lock(&lp->xfer_lock);
ret = i2c_smbus_read_byte_data(lp->client, reg);
if (ret < 0) {
mutex_unlock(&lp->xfer_lock);
dev_err(lp->dev, "failed to read 0x%.2x\n", reg);
return ret;
}
mutex_unlock(&lp->xfer_lock);
*data = (u8)ret;
return 0;
}
static int lp855x_write_byte(struct lp855x *lp, u8 reg, u8 data)
{
int ret;
mutex_lock(&lp->xfer_lock);
ret = i2c_smbus_write_byte_data(lp->client, reg, data);
mutex_unlock(&lp->xfer_lock);
return ret;
}
static bool lp855x_is_valid_rom_area(struct lp855x *lp, u8 addr)
{
u8 start, end;
switch (lp->chip_id) {
case LP8550:
case LP8551:
case LP8552:
case LP8553:
start = EEPROM_START;
end = EEPROM_END;
break;
case LP8556:
start = EPROM_START;
end = EPROM_END;
break;
default:
return false;
}
return (addr >= start && addr <= end);
}
static int lp855x_init_registers(struct lp855x *lp)
{
u8 val, addr, mask;
int i, ret;
struct lp855x_platform_data *pd = lp->pdata;
val = pd->initial_brightness;
ret = lp855x_write_byte(lp, BRIGHTNESS_CTRL, val);
if (ret)
return ret;
val = pd->device_control;
ret = lp855x_write_byte(lp, DEVICE_CTRL, val);
if (ret)
return ret;
if (pd->load_new_rom_data && pd->size_program) {
for (i = 0; i < pd->size_program; i++) {
addr = pd->rom_data[i].addr;
val = pd->rom_data[i].val;
mask = pd->rom_data[i].mask;
if (!lp855x_is_valid_rom_area(lp, addr))
continue;
if (mask) {
u8 reg_val;
ret = lp855x_read_byte(lp, addr, ®_val);
if (ret)
return ret;
val = (val & ~mask) | (reg_val & mask);
}
ret = lp855x_write_byte(lp, addr, val);
if (ret)
return ret;
}
}
return ret;
}
static int lp855x_bl_update_status(struct backlight_device *bl)
{
struct lp855x *lp = bl_get_data(bl);
enum lp855x_brightness_ctrl_mode mode = lp->pdata->mode;
int ret;
if (bl->props.state & BL_CORE_SUSPENDED)
bl->props.brightness = 0;
if (mode == PWM_BASED) {
struct lp855x_pwm_data *pd = &lp->pdata->pwm_data;
int br = bl->props.brightness;
int max_br = bl->props.max_brightness;
if (pd->pwm_set_intensity)
pd->pwm_set_intensity(br, max_br);
} else if (mode == REGISTER_BASED) {
u8 val = bl->props.brightness;
ret = lp855x_write_byte(lp, BRIGHTNESS_CTRL, val);
if (ret)
return ret;
}
return 0;
}
static int lp855x_bl_get_brightness(struct backlight_device *bl)
{
struct lp855x *lp = bl_get_data(bl);
enum lp855x_brightness_ctrl_mode mode = lp->pdata->mode;
if (mode == PWM_BASED) {
struct lp855x_pwm_data *pd = &lp->pdata->pwm_data;
int max_br = bl->props.max_brightness;
if (pd->pwm_get_intensity)
bl->props.brightness = pd->pwm_get_intensity(max_br);
} else if (mode == REGISTER_BASED) {
u8 val = 0;
lp855x_read_byte(lp, BRIGHTNESS_CTRL, &val);
bl->props.brightness = val;
}
return bl->props.brightness;
}
static const struct backlight_ops lp855x_bl_ops = {
.options = BL_CORE_SUSPENDRESUME,
.update_status = lp855x_bl_update_status,
.get_brightness = lp855x_bl_get_brightness,
};
static int lp855x_backlight_register(struct lp855x *lp)
{
struct backlight_device *bl;
struct backlight_properties props;
struct lp855x_platform_data *pdata = lp->pdata;
char *name = pdata->name ? : DEFAULT_BL_NAME;
props.type = BACKLIGHT_PLATFORM;
props.max_brightness = MAX_BRIGHTNESS;
if (pdata->initial_brightness > props.max_brightness)
pdata->initial_brightness = props.max_brightness;
props.brightness = pdata->initial_brightness;
bl = backlight_device_register(name, lp->dev, lp,
&lp855x_bl_ops, &props);
if (IS_ERR(bl))
return PTR_ERR(bl);
lp->bl = bl;
return 0;
}
static void lp855x_backlight_unregister(struct lp855x *lp)
{
if (lp->bl)
backlight_device_unregister(lp->bl);
}
static ssize_t lp855x_get_chip_id(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct lp855x *lp = dev_get_drvdata(dev);
return scnprintf(buf, BUF_SIZE, "%s\n", lp->chipname);
}
static ssize_t lp855x_get_bl_ctl_mode(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct lp855x *lp = dev_get_drvdata(dev);
enum lp855x_brightness_ctrl_mode mode = lp->pdata->mode;
char *strmode = NULL;
if (mode == PWM_BASED)
strmode = "pwm based";
else if (mode == REGISTER_BASED)
strmode = "register based";
return scnprintf(buf, BUF_SIZE, "%s\n", strmode);
}
static DEVICE_ATTR(chip_id, S_IRUGO, lp855x_get_chip_id, NULL);
static DEVICE_ATTR(bl_ctl_mode, S_IRUGO, lp855x_get_bl_ctl_mode, NULL);
static struct attribute *lp855x_attributes[] = {
&dev_attr_chip_id.attr,
&dev_attr_bl_ctl_mode.attr,
NULL,
};
static const struct attribute_group lp855x_attr_group = {
.attrs = lp855x_attributes,
};
static int lp855x_set_power(struct lp855x *lp, int on)
{
unsigned long on_udelay = lp->pdata->power_on_udelay;
pr_info("%s : %d\n", __func__, on);
if (on) {
int ret = 0;
gpio_set_value(lp->pdata->gpio_en, GPIO_LEVEL_HIGH);
usleep_range(on_udelay, on_udelay);
ret = lp855x_init_registers(lp);
if (ret)
return ret;
} else {
gpio_set_value(lp->pdata->gpio_en, GPIO_LEVEL_LOW);
}
lp->enabled = on;
return 0;
}
#ifdef CONFIG_HAS_EARLYSUSPEND
static void lp855x_early_suspend(struct early_suspend *h)
{
struct lp855x *lp =
container_of(h, struct lp855x, early_suspend);
lp855x_set_power(lp, 0);
}
static void lp855x_late_resume(struct early_suspend *h)
{
struct lp855x *lp =
container_of(h, struct lp855x, early_suspend);
lp855x_set_power(lp, 1);
backlight_update_status(lp->bl);
}
#endif
static int lp855x_probe(struct i2c_client *cl, const struct i2c_device_id *id)
{
struct lp855x *lp;
struct lp855x_platform_data *pdata = cl->dev.platform_data;
enum lp855x_brightness_ctrl_mode mode;
int ret;
if (!pdata) {
dev_err(&cl->dev, "no platform data supplied\n");
return -EINVAL;
}
if (!i2c_check_functionality(cl->adapter, I2C_FUNC_SMBUS_I2C_BLOCK))
return -EIO;
lp = devm_kzalloc(&cl->dev, sizeof(struct lp855x), GFP_KERNEL);
if (!lp)
return -ENOMEM;
mode = pdata->mode;
lp->client = cl;
lp->dev = &cl->dev;
lp->pdata = pdata;
lp->chipname = id->name;
lp->chip_id = id->driver_data;
i2c_set_clientdata(cl, lp);
mutex_init(&lp->xfer_lock);
ret = lp855x_init_registers(lp);
if (ret) {
dev_err(lp->dev, "i2c communication err: %d", ret);
if (mode == REGISTER_BASED)
goto err_dev;
}
lp->enabled = 1;
#ifdef CONFIG_HAS_EARLYSUSPEND
if (lp->pdata->use_gpio_en) {
lp->early_suspend.level = EARLY_SUSPEND_LEVEL_DISABLE_FB - 2;
lp->early_suspend.suspend = lp855x_early_suspend;
lp->early_suspend.resume = lp855x_late_resume;
register_early_suspend(&lp->early_suspend);
}
#endif
ret = lp855x_backlight_register(lp);
if (ret) {
dev_err(lp->dev,
"failed to register backlight. err: %d\n", ret);
goto err_dev;
}
ret = sysfs_create_group(&lp->dev->kobj, &lp855x_attr_group);
if (ret) {
dev_err(lp->dev, "failed to register sysfs. err: %d\n", ret);
goto err_sysfs;
}
backlight_update_status(lp->bl);
return 0;
err_sysfs:
lp855x_backlight_unregister(lp);
err_dev:
return ret;
}
static int __devexit lp855x_remove(struct i2c_client *cl)
{
struct lp855x *lp = i2c_get_clientdata(cl);
lp->bl->props.brightness = 0;
backlight_update_status(lp->bl);
sysfs_remove_group(&lp->dev->kobj, &lp855x_attr_group);
lp855x_backlight_unregister(lp);
return 0;
}
static const struct i2c_device_id lp855x_ids[] = {
{"lp8550", LP8550},
{"lp8551", LP8551},
{"lp8552", LP8552},
{"lp8553", LP8553},
{"lp8556", LP8556},
{ }
};
MODULE_DEVICE_TABLE(i2c, lp855x_ids);
static struct i2c_driver lp855x_driver = {
.driver = {
.name = "lp855x",
},
.probe = lp855x_probe,
.remove = __devexit_p(lp855x_remove),
.id_table = lp855x_ids,
};
static int __init lp855x_init(void)
{
return i2c_add_driver(&lp855x_driver);
}
static void __exit lp855x_exit(void)
{
i2c_del_driver(&lp855x_driver);
}
module_init(lp855x_init);
module_exit(lp855x_exit);
MODULE_DESCRIPTION("Texas Instruments LP855x Backlight driver");
MODULE_AUTHOR("Milo Kim <milo.kim@ti.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
drewis/android_kernel_msm | drivers/usb/host/ehci-msm72k.c | 98 | 20261 | /* ehci-msm.c - HSUSB Host Controller Driver Implementation
*
* Copyright (c) 2008-2012, Code Aurora Forum. All rights reserved.
*
* Partly derived from ehci-fsl.c and ehci-hcd.c
* Copyright (c) 2000-2004 by David Brownell
* Copyright (c) 2005 MontaVista Software
*
* 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 <linux/platform_device.h>
#include <linux/interrupt.h>
#include <linux/workqueue.h>
#include <linux/clk.h>
#include <linux/spinlock.h>
#include <mach/board.h>
#include <mach/rpc_hsusb.h>
#include <mach/msm_hsusb.h>
#include <mach/msm_hsusb_hw.h>
#include <mach/msm_otg.h>
#include <mach/clk.h>
#include <linux/wakelock.h>
#include <linux/pm_runtime.h>
#include <mach/msm72k_otg.h>
#define MSM_USB_BASE (hcd->regs)
struct msmusb_hcd {
struct ehci_hcd ehci;
struct clk *alt_core_clk;
struct clk *iface_clk;
unsigned in_lpm;
struct work_struct lpm_exit_work;
spinlock_t lock;
struct wake_lock wlock;
unsigned int clk_enabled;
struct msm_usb_host_platform_data *pdata;
unsigned running;
struct usb_phy *xceiv;
struct work_struct otg_work;
unsigned flags;
struct msm_otg_ops otg_ops;
};
static inline struct msmusb_hcd *hcd_to_mhcd(struct usb_hcd *hcd)
{
return (struct msmusb_hcd *) (hcd->hcd_priv);
}
static inline struct usb_hcd *mhcd_to_hcd(struct msmusb_hcd *mhcd)
{
return container_of((void *) mhcd, struct usb_hcd, hcd_priv);
}
static void msm_xusb_pm_qos_update(struct msmusb_hcd *mhcd, int vote)
{
struct msm_usb_host_platform_data *pdata = mhcd->pdata;
/* if otg driver is available, it would take
* care of voting for appropriate pclk source
*/
if (mhcd->xceiv)
return;
if (vote)
clk_prepare_enable(pdata->ebi1_clk);
else
clk_disable_unprepare(pdata->ebi1_clk);
}
static void msm_xusb_enable_clks(struct msmusb_hcd *mhcd)
{
struct msm_usb_host_platform_data *pdata = mhcd->pdata;
if (mhcd->clk_enabled)
return;
switch (PHY_TYPE(pdata->phy_info)) {
case USB_PHY_INTEGRATED:
/* OTG driver takes care of clock management */
break;
case USB_PHY_SERIAL_PMIC:
clk_prepare_enable(mhcd->alt_core_clk);
clk_prepare_enable(mhcd->iface_clk);
break;
default:
pr_err("%s: undefined phy type ( %X )\n", __func__,
pdata->phy_info);
return;
}
mhcd->clk_enabled = 1;
}
static void msm_xusb_disable_clks(struct msmusb_hcd *mhcd)
{
struct msm_usb_host_platform_data *pdata = mhcd->pdata;
if (!mhcd->clk_enabled)
return;
switch (PHY_TYPE(pdata->phy_info)) {
case USB_PHY_INTEGRATED:
/* OTG driver takes care of clock management */
break;
case USB_PHY_SERIAL_PMIC:
clk_disable_unprepare(mhcd->alt_core_clk);
clk_disable_unprepare(mhcd->iface_clk);
break;
default:
pr_err("%s: undefined phy type ( %X )\n", __func__,
pdata->phy_info);
return;
}
mhcd->clk_enabled = 0;
}
static int usb_wakeup_phy(struct usb_hcd *hcd)
{
struct msmusb_hcd *mhcd = hcd_to_mhcd(hcd);
struct msm_usb_host_platform_data *pdata = mhcd->pdata;
int ret = -ENODEV;
switch (PHY_TYPE(pdata->phy_info)) {
case USB_PHY_INTEGRATED:
break;
case USB_PHY_SERIAL_PMIC:
ret = msm_fsusb_resume_phy();
break;
default:
pr_err("%s: undefined phy type ( %X ) \n", __func__,
pdata->phy_info);
}
return ret;
}
#ifdef CONFIG_PM
static int usb_suspend_phy(struct usb_hcd *hcd)
{
int ret = 0;
struct msmusb_hcd *mhcd = hcd_to_mhcd(hcd);
struct msm_usb_host_platform_data *pdata = mhcd->pdata;
switch (PHY_TYPE(pdata->phy_info)) {
case USB_PHY_INTEGRATED:
break;
case USB_PHY_SERIAL_PMIC:
ret = msm_fsusb_set_remote_wakeup();
ret = msm_fsusb_suspend_phy();
break;
default:
pr_err("%s: undefined phy type ( %X ) \n", __func__,
pdata->phy_info);
ret = -ENODEV;
break;
}
return ret;
}
static int usb_lpm_enter(struct usb_hcd *hcd)
{
struct device *dev = container_of((void *)hcd, struct device,
platform_data);
struct msmusb_hcd *mhcd = hcd_to_mhcd(hcd);
disable_irq(hcd->irq);
if (mhcd->in_lpm) {
pr_info("%s: already in lpm. nothing to do\n", __func__);
enable_irq(hcd->irq);
return 0;
}
if (HC_IS_RUNNING(hcd->state)) {
pr_info("%s: can't enter into lpm. controller is runnning\n",
__func__);
enable_irq(hcd->irq);
return -1;
}
pr_info("%s: lpm enter procedure started\n", __func__);
mhcd->in_lpm = 1;
if (usb_suspend_phy(hcd)) {
mhcd->in_lpm = 0;
enable_irq(hcd->irq);
pr_info("phy suspend failed\n");
pr_info("%s: lpm enter procedure end\n", __func__);
return -1;
}
msm_xusb_disable_clks(mhcd);
if (mhcd->xceiv && mhcd->xceiv->set_suspend)
mhcd->xceiv->set_suspend(mhcd->xceiv, 1);
if (device_may_wakeup(dev))
enable_irq_wake(hcd->irq);
enable_irq(hcd->irq);
pr_info("%s: lpm enter procedure end\n", __func__);
return 0;
}
#endif
void usb_lpm_exit_w(struct work_struct *work)
{
struct msmusb_hcd *mhcd = container_of((void *) work,
struct msmusb_hcd, lpm_exit_work);
struct usb_hcd *hcd = mhcd_to_hcd(mhcd);
struct device *dev = container_of((void *)hcd, struct device,
platform_data);
msm_xusb_enable_clks(mhcd);
if (usb_wakeup_phy(hcd)) {
pr_err("fatal error: cannot bring phy out of lpm\n");
return;
}
/* If resume signalling finishes before lpm exit, PCD is not set in
* USBSTS register. Drive resume signal to the downstream device now
* so that EHCI can process the upcoming port change interrupt.*/
writel(readl(USB_PORTSC) | PORTSC_FPR, USB_PORTSC);
if (mhcd->xceiv && mhcd->xceiv->set_suspend)
mhcd->xceiv->set_suspend(mhcd->xceiv, 0);
if (device_may_wakeup(dev))
disable_irq_wake(hcd->irq);
enable_irq(hcd->irq);
}
static void usb_lpm_exit(struct usb_hcd *hcd)
{
unsigned long flags;
struct msmusb_hcd *mhcd = hcd_to_mhcd(hcd);
spin_lock_irqsave(&mhcd->lock, flags);
if (!mhcd->in_lpm) {
spin_unlock_irqrestore(&mhcd->lock, flags);
return;
}
mhcd->in_lpm = 0;
disable_irq_nosync(hcd->irq);
schedule_work(&mhcd->lpm_exit_work);
spin_unlock_irqrestore(&mhcd->lock, flags);
}
static irqreturn_t ehci_msm_irq(struct usb_hcd *hcd)
{
struct msmusb_hcd *mhcd = hcd_to_mhcd(hcd);
struct msm_otg *otg = container_of(mhcd->xceiv, struct msm_otg, phy);
/*
* OTG scheduled a work to get Integrated PHY out of LPM,
* WAIT till then */
if (PHY_TYPE(mhcd->pdata->phy_info) == USB_PHY_INTEGRATED)
if (atomic_read(&otg->in_lpm))
return IRQ_HANDLED;
return ehci_irq(hcd);
}
#ifdef CONFIG_PM
static int ehci_msm_bus_suspend(struct usb_hcd *hcd)
{
int ret;
struct msmusb_hcd *mhcd = hcd_to_mhcd(hcd);
struct device *dev = hcd->self.controller;
ret = ehci_bus_suspend(hcd);
if (ret) {
pr_err("ehci_bus suspend faield\n");
return ret;
}
if (PHY_TYPE(mhcd->pdata->phy_info) == USB_PHY_INTEGRATED)
ret = usb_phy_set_suspend(mhcd->xceiv, 1);
else
ret = usb_lpm_enter(hcd);
pm_runtime_put_noidle(dev);
pm_runtime_suspend(dev);
wake_unlock(&mhcd->wlock);
return ret;
}
static int ehci_msm_bus_resume(struct usb_hcd *hcd)
{
struct msmusb_hcd *mhcd = hcd_to_mhcd(hcd);
struct device *dev = hcd->self.controller;
wake_lock(&mhcd->wlock);
pm_runtime_get_noresume(dev);
pm_runtime_resume(dev);
if (PHY_TYPE(mhcd->pdata->phy_info) == USB_PHY_INTEGRATED) {
usb_phy_set_suspend(mhcd->xceiv, 0);
} else { /* PMIC serial phy */
usb_lpm_exit(hcd);
if (cancel_work_sync(&(mhcd->lpm_exit_work)))
usb_lpm_exit_w(&mhcd->lpm_exit_work);
}
return ehci_bus_resume(hcd);
}
#else
#define ehci_msm_bus_suspend NULL
#define ehci_msm_bus_resume NULL
#endif /* CONFIG_PM */
static int ehci_msm_reset(struct usb_hcd *hcd)
{
struct ehci_hcd *ehci = hcd_to_ehci(hcd);
int retval;
ehci->caps = USB_CAPLENGTH;
ehci->regs = USB_CAPLENGTH +
HC_LENGTH(ehci, ehci_readl(ehci, &ehci->caps->hc_capbase));
/* cache the data to minimize the chip reads*/
ehci->hcs_params = ehci_readl(ehci, &ehci->caps->hcs_params);
retval = ehci_init(hcd);
if (retval)
return retval;
hcd->has_tt = 1;
ehci->sbrn = HCD_USB2;
retval = ehci_reset(ehci);
/* SW workaround for USB stability issues*/
writel(0x0, USB_AHB_MODE);
writel(0x0, USB_AHB_BURST);
return retval;
}
#define PTS_VAL(x) (PHY_TYPE(x) == USB_PHY_SERIAL_PMIC) ? PORTSC_PTS_SERIAL : \
PORTSC_PTS_ULPI
static int ehci_msm_run(struct usb_hcd *hcd)
{
struct ehci_hcd *ehci = hcd_to_ehci(hcd);
struct msmusb_hcd *mhcd = hcd_to_mhcd(hcd);
int retval = 0;
int port = HCS_N_PORTS(ehci->hcs_params);
u32 __iomem *reg_ptr;
u32 hcc_params;
struct msm_usb_host_platform_data *pdata = mhcd->pdata;
hcd->uses_new_polling = 1;
set_bit(HCD_FLAG_POLL_RH, &hcd->flags);
/* set hostmode */
reg_ptr = (u32 __iomem *)(((u8 __iomem *)ehci->regs) + USBMODE);
ehci_writel(ehci, (USBMODE_VBUS | USBMODE_SDIS), reg_ptr);
/* port configuration - phy, port speed, port power, port enable */
while (port--)
ehci_writel(ehci, (PTS_VAL(pdata->phy_info) | PORT_POWER |
PORT_PE), &ehci->regs->port_status[port]);
ehci_writel(ehci, ehci->periodic_dma, &ehci->regs->frame_list);
ehci_writel(ehci, (u32)ehci->async->qh_dma, &ehci->regs->async_next);
hcc_params = ehci_readl(ehci, &ehci->caps->hcc_params);
if (HCC_64BIT_ADDR(hcc_params))
ehci_writel(ehci, 0, &ehci->regs->segment);
ehci->command &= ~(CMD_LRESET|CMD_IAAD|CMD_PSE|CMD_ASE|CMD_RESET);
ehci->command |= CMD_RUN;
ehci_writel(ehci, ehci->command, &ehci->regs->command);
ehci_readl(ehci, &ehci->regs->command); /* unblock posted writes */
hcd->state = HC_STATE_RUNNING;
/*Enable appropriate Interrupts*/
ehci_writel(ehci, INTR_MASK, &ehci->regs->intr_enable);
return retval;
}
static struct hc_driver msm_hc_driver = {
.description = hcd_name,
.product_desc = "Qualcomm On-Chip EHCI Host Controller",
.hcd_priv_size = sizeof(struct msmusb_hcd),
/*
* generic hardware linkage
*/
.irq = ehci_msm_irq,
.flags = HCD_USB2,
.reset = ehci_msm_reset,
.start = ehci_msm_run,
.stop = ehci_stop,
.shutdown = ehci_shutdown,
/*
* managing i/o requests and associated device resources
*/
.urb_enqueue = ehci_urb_enqueue,
.urb_dequeue = ehci_urb_dequeue,
.endpoint_disable = ehci_endpoint_disable,
/*
* scheduling support
*/
.get_frame_number = ehci_get_frame,
/*
* root hub support
*/
.hub_status_data = ehci_hub_status_data,
.hub_control = ehci_hub_control,
.bus_suspend = ehci_msm_bus_suspend,
.bus_resume = ehci_msm_bus_resume,
.relinquish_port = ehci_relinquish_port,
.clear_tt_buffer_complete = ehci_clear_tt_buffer_complete,
};
static void msm_hsusb_request_host(void *handle, int request)
{
struct msmusb_hcd *mhcd = handle;
struct usb_hcd *hcd = mhcd_to_hcd(mhcd);
struct msm_usb_host_platform_data *pdata = mhcd->pdata;
struct msm_otg *otg = container_of(mhcd->xceiv, struct msm_otg, phy);
#ifdef CONFIG_USB_OTG
struct usb_device *udev = hcd->self.root_hub;
#endif
struct device *dev = hcd->self.controller;
switch (request) {
#ifdef CONFIG_USB_OTG
case REQUEST_HNP_SUSPEND:
/* disable Root hub auto suspend. As hardware is configured
* for peripheral mode, mark hardware is not available.
*/
if (PHY_TYPE(pdata->phy_info) == USB_PHY_INTEGRATED) {
pm_runtime_disable(&udev->dev);
/* Mark root hub as disconnected. This would
* protect suspend/resume via sysfs.
*/
udev->state = USB_STATE_NOTATTACHED;
clear_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
hcd->state = HC_STATE_HALT;
pm_runtime_put_noidle(dev);
pm_runtime_suspend(dev);
}
break;
case REQUEST_HNP_RESUME:
if (PHY_TYPE(pdata->phy_info) == USB_PHY_INTEGRATED) {
pm_runtime_get_noresume(dev);
pm_runtime_resume(dev);
disable_irq(hcd->irq);
ehci_msm_reset(hcd);
ehci_msm_run(hcd);
set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
pm_runtime_enable(&udev->dev);
udev->state = USB_STATE_CONFIGURED;
enable_irq(hcd->irq);
}
break;
#endif
case REQUEST_RESUME:
usb_hcd_resume_root_hub(hcd);
break;
case REQUEST_START:
if (mhcd->running)
break;
pm_runtime_get_noresume(dev);
pm_runtime_resume(dev);
wake_lock(&mhcd->wlock);
msm_xusb_pm_qos_update(mhcd, 1);
msm_xusb_enable_clks(mhcd);
if (PHY_TYPE(pdata->phy_info) == USB_PHY_INTEGRATED)
if (otg->set_clk)
otg->set_clk(mhcd->xceiv, 1);
if (pdata->vbus_power)
pdata->vbus_power(pdata->phy_info, 1);
if (pdata->config_gpio)
pdata->config_gpio(1);
usb_add_hcd(hcd, hcd->irq, IRQF_SHARED);
mhcd->running = 1;
if (PHY_TYPE(pdata->phy_info) == USB_PHY_INTEGRATED)
if (otg->set_clk)
otg->set_clk(mhcd->xceiv, 0);
break;
case REQUEST_STOP:
if (!mhcd->running)
break;
mhcd->running = 0;
/* come out of lpm before deregistration */
if (PHY_TYPE(pdata->phy_info) == USB_PHY_SERIAL_PMIC) {
usb_lpm_exit(hcd);
if (cancel_work_sync(&(mhcd->lpm_exit_work)))
usb_lpm_exit_w(&mhcd->lpm_exit_work);
}
usb_remove_hcd(hcd);
if (pdata->config_gpio)
pdata->config_gpio(0);
if (pdata->vbus_power)
pdata->vbus_power(pdata->phy_info, 0);
msm_xusb_disable_clks(mhcd);
wake_lock_timeout(&mhcd->wlock, HZ/2);
msm_xusb_pm_qos_update(mhcd, 0);
pm_runtime_put_noidle(dev);
pm_runtime_suspend(dev);
break;
}
}
static void msm_hsusb_otg_work(struct work_struct *work)
{
struct msmusb_hcd *mhcd;
mhcd = container_of(work, struct msmusb_hcd, otg_work);
msm_hsusb_request_host((void *)mhcd, mhcd->flags);
}
static void msm_hsusb_start_host(struct usb_bus *bus, int start)
{
struct usb_hcd *hcd = bus_to_hcd(bus);
struct msmusb_hcd *mhcd = hcd_to_mhcd(hcd);
mhcd->flags = start;
if (in_interrupt())
schedule_work(&mhcd->otg_work);
else
msm_hsusb_request_host((void *)mhcd, mhcd->flags);
}
static int msm_xusb_init_phy(struct msmusb_hcd *mhcd)
{
int ret = -ENODEV;
struct usb_hcd *hcd = mhcd_to_hcd(mhcd);
struct msm_usb_host_platform_data *pdata = mhcd->pdata;
switch (PHY_TYPE(pdata->phy_info)) {
case USB_PHY_INTEGRATED:
ret = 0;
case USB_PHY_SERIAL_PMIC:
msm_xusb_enable_clks(mhcd);
writel(0, USB_USBINTR);
ret = msm_fsusb_rpc_init(&mhcd->otg_ops);
if (!ret)
msm_fsusb_init_phy();
msm_xusb_disable_clks(mhcd);
break;
default:
pr_err("%s: undefined phy type ( %X ) \n", __func__,
pdata->phy_info);
}
return ret;
}
static int msm_xusb_rpc_close(struct msmusb_hcd *mhcd)
{
int retval = -ENODEV;
struct msm_usb_host_platform_data *pdata = mhcd->pdata;
switch (PHY_TYPE(pdata->phy_info)) {
case USB_PHY_INTEGRATED:
if (!mhcd->xceiv)
retval = msm_hsusb_rpc_close();
break;
case USB_PHY_SERIAL_PMIC:
retval = msm_fsusb_reset_phy();
msm_fsusb_rpc_deinit();
break;
default:
pr_err("%s: undefined phy type ( %X ) \n", __func__,
pdata->phy_info);
}
return retval;
}
static int msm_xusb_init_host(struct platform_device *pdev,
struct msmusb_hcd *mhcd)
{
int ret = 0;
struct msm_otg *otg;
struct usb_hcd *hcd = mhcd_to_hcd(mhcd);
struct ehci_hcd *ehci = hcd_to_ehci(hcd);
struct msm_usb_host_platform_data *pdata = mhcd->pdata;
switch (PHY_TYPE(pdata->phy_info)) {
case USB_PHY_INTEGRATED:
msm_hsusb_rpc_connect();
if (pdata->vbus_init)
pdata->vbus_init(1);
/* VBUS might be present. Turn off vbus */
if (pdata->vbus_power)
pdata->vbus_power(pdata->phy_info, 0);
INIT_WORK(&mhcd->otg_work, msm_hsusb_otg_work);
mhcd->xceiv = usb_get_transceiver();
if (!mhcd->xceiv)
return -ENODEV;
otg = container_of(mhcd->xceiv, struct msm_otg, phy);
hcd->regs = otg->regs;
otg->start_host = msm_hsusb_start_host;
ret = otg_set_host(mhcd->xceiv->otg, &hcd->self);
ehci->transceiver = mhcd->xceiv;
break;
case USB_PHY_SERIAL_PMIC:
hcd->regs = ioremap(hcd->rsrc_start, hcd->rsrc_len);
if (!hcd->regs)
return -EFAULT;
/* get usb clocks */
mhcd->alt_core_clk = clk_get(&pdev->dev, "alt_core_clk");
if (IS_ERR(mhcd->alt_core_clk)) {
iounmap(hcd->regs);
return PTR_ERR(mhcd->alt_core_clk);
}
mhcd->iface_clk = clk_get(&pdev->dev, "iface_clk");
if (IS_ERR(mhcd->iface_clk)) {
iounmap(hcd->regs);
clk_put(mhcd->alt_core_clk);
return PTR_ERR(mhcd->iface_clk);
}
mhcd->otg_ops.request = msm_hsusb_request_host;
mhcd->otg_ops.handle = (void *) mhcd;
ret = msm_xusb_init_phy(mhcd);
if (ret < 0) {
iounmap(hcd->regs);
clk_put(mhcd->alt_core_clk);
clk_put(mhcd->iface_clk);
}
break;
default:
pr_err("phy type is bad\n");
}
return ret;
}
static int __devinit ehci_msm_probe(struct platform_device *pdev)
{
struct usb_hcd *hcd;
struct resource *res;
struct msm_usb_host_platform_data *pdata;
int retval;
struct msmusb_hcd *mhcd;
hcd = usb_create_hcd(&msm_hc_driver, &pdev->dev, dev_name(&pdev->dev));
if (!hcd)
return -ENOMEM;
hcd->irq = platform_get_irq(pdev, 0);
if (hcd->irq < 0) {
usb_put_hcd(hcd);
return hcd->irq;
}
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
usb_put_hcd(hcd);
return -ENODEV;
}
hcd->rsrc_start = res->start;
hcd->rsrc_len = resource_size(res);
mhcd = hcd_to_mhcd(hcd);
spin_lock_init(&mhcd->lock);
mhcd->in_lpm = 0;
mhcd->running = 0;
device_init_wakeup(&pdev->dev, 1);
pdata = pdev->dev.platform_data;
if (PHY_TYPE(pdata->phy_info) == USB_PHY_UNDEFINED) {
usb_put_hcd(hcd);
return -ENODEV;
}
hcd->power_budget = pdata->power_budget;
mhcd->pdata = pdata;
INIT_WORK(&mhcd->lpm_exit_work, usb_lpm_exit_w);
wake_lock_init(&mhcd->wlock, WAKE_LOCK_SUSPEND, dev_name(&pdev->dev));
pdata->ebi1_clk = clk_get(&pdev->dev, "core_clk");
if (IS_ERR(pdata->ebi1_clk))
pdata->ebi1_clk = NULL;
else
clk_set_rate(pdata->ebi1_clk, INT_MAX);
retval = msm_xusb_init_host(pdev, mhcd);
if (retval < 0) {
wake_lock_destroy(&mhcd->wlock);
usb_put_hcd(hcd);
clk_put(pdata->ebi1_clk);
}
pm_runtime_enable(&pdev->dev);
return retval;
}
static void msm_xusb_uninit_host(struct msmusb_hcd *mhcd)
{
struct usb_hcd *hcd = mhcd_to_hcd(mhcd);
struct msm_usb_host_platform_data *pdata = mhcd->pdata;
switch (PHY_TYPE(pdata->phy_info)) {
case USB_PHY_INTEGRATED:
if (pdata->vbus_init)
pdata->vbus_init(0);
hcd_to_ehci(hcd)->transceiver = NULL;
otg_set_host(mhcd->xceiv->otg, NULL);
usb_put_transceiver(mhcd->xceiv);
cancel_work_sync(&mhcd->otg_work);
break;
case USB_PHY_SERIAL_PMIC:
iounmap(hcd->regs);
clk_put(mhcd->alt_core_clk);
clk_put(mhcd->iface_clk);
msm_fsusb_reset_phy();
msm_fsusb_rpc_deinit();
break;
default:
pr_err("phy type is bad\n");
}
}
static int __exit ehci_msm_remove(struct platform_device *pdev)
{
struct usb_hcd *hcd = platform_get_drvdata(pdev);
struct msmusb_hcd *mhcd = hcd_to_mhcd(hcd);
struct msm_usb_host_platform_data *pdata;
int retval = 0;
pdata = pdev->dev.platform_data;
device_init_wakeup(&pdev->dev, 0);
msm_hsusb_request_host((void *)mhcd, REQUEST_STOP);
msm_xusb_uninit_host(mhcd);
retval = msm_xusb_rpc_close(mhcd);
wake_lock_destroy(&mhcd->wlock);
usb_put_hcd(hcd);
clk_put(pdata->ebi1_clk);
pm_runtime_disable(&pdev->dev);
pm_runtime_set_suspended(&pdev->dev);
return retval;
}
static int ehci_msm_runtime_suspend(struct device *dev)
{
dev_dbg(dev, "pm_runtime: suspending...\n");
return 0;
}
static int ehci_msm_runtime_resume(struct device *dev)
{
dev_dbg(dev, "pm_runtime: resuming...\n");
return 0;
}
static int ehci_msm_runtime_idle(struct device *dev)
{
dev_dbg(dev, "pm_runtime: idling...\n");
return 0;
}
static const struct dev_pm_ops ehci_msm_dev_pm_ops = {
.runtime_suspend = ehci_msm_runtime_suspend,
.runtime_resume = ehci_msm_runtime_resume,
.runtime_idle = ehci_msm_runtime_idle
};
static struct platform_driver ehci_msm_driver = {
.probe = ehci_msm_probe,
.remove = __exit_p(ehci_msm_remove),
.driver = {.name = "msm_hsusb_host",
.pm = &ehci_msm_dev_pm_ops, },
};
| gpl-2.0 |
LegacyXperia/android_kernel_semc_msm7x30 | fs/cifs/transport.c | 354 | 24467 | /*
* fs/cifs/transport.c
*
* Copyright (C) International Business Machines Corp., 2002,2008
* Author(s): Steve French (sfrench@us.ibm.com)
* Jeremy Allison (jra@samba.org) 2006.
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/fs.h>
#include <linux/list.h>
#include <linux/gfp.h>
#include <linux/wait.h>
#include <linux/net.h>
#include <linux/delay.h>
#include <linux/freezer.h>
#include <asm/uaccess.h>
#include <asm/processor.h>
#include <linux/mempool.h>
#include "cifspdu.h"
#include "cifsglob.h"
#include "cifsproto.h"
#include "cifs_debug.h"
extern mempool_t *cifs_mid_poolp;
static void
wake_up_task(struct mid_q_entry *mid)
{
wake_up_process(mid->callback_data);
}
struct mid_q_entry *
AllocMidQEntry(const struct smb_hdr *smb_buffer, struct TCP_Server_Info *server)
{
struct mid_q_entry *temp;
if (server == NULL) {
cERROR(1, "Null TCP session in AllocMidQEntry");
return NULL;
}
temp = mempool_alloc(cifs_mid_poolp, GFP_NOFS);
if (temp == NULL)
return temp;
else {
memset(temp, 0, sizeof(struct mid_q_entry));
temp->mid = smb_buffer->Mid; /* always LE */
temp->pid = current->pid;
temp->command = cpu_to_le16(smb_buffer->Command);
cFYI(1, "For smb_command %d", smb_buffer->Command);
/* do_gettimeofday(&temp->when_sent);*/ /* easier to use jiffies */
/* when mid allocated can be before when sent */
temp->when_alloc = jiffies;
/*
* The default is for the mid to be synchronous, so the
* default callback just wakes up the current task.
*/
temp->callback = wake_up_task;
temp->callback_data = current;
}
atomic_inc(&midCount);
temp->mid_state = MID_REQUEST_ALLOCATED;
return temp;
}
void
DeleteMidQEntry(struct mid_q_entry *midEntry)
{
#ifdef CONFIG_CIFS_STATS2
unsigned long now;
#endif
midEntry->mid_state = MID_FREE;
atomic_dec(&midCount);
if (midEntry->large_buf)
cifs_buf_release(midEntry->resp_buf);
else
cifs_small_buf_release(midEntry->resp_buf);
#ifdef CONFIG_CIFS_STATS2
now = jiffies;
/* commands taking longer than one second are indications that
something is wrong, unless it is quite a slow link or server */
if ((now - midEntry->when_alloc) > HZ) {
if ((cifsFYI & CIFS_TIMER) &&
(midEntry->command != cpu_to_le16(SMB_COM_LOCKING_ANDX))) {
printk(KERN_DEBUG " CIFS slow rsp: cmd %d mid %llu",
midEntry->command, midEntry->mid);
printk(" A: 0x%lx S: 0x%lx R: 0x%lx\n",
now - midEntry->when_alloc,
now - midEntry->when_sent,
now - midEntry->when_received);
}
}
#endif
mempool_free(midEntry, cifs_mid_poolp);
}
static void
delete_mid(struct mid_q_entry *mid)
{
spin_lock(&GlobalMid_Lock);
list_del(&mid->qhead);
spin_unlock(&GlobalMid_Lock);
DeleteMidQEntry(mid);
}
static int
smb_sendv(struct TCP_Server_Info *server, struct kvec *iov, int n_vec)
{
int rc = 0;
int i = 0;
struct msghdr smb_msg;
__be32 *buf_len = (__be32 *)(iov[0].iov_base);
unsigned int len = iov[0].iov_len;
unsigned int total_len;
int first_vec = 0;
unsigned int smb_buf_length = get_rfc1002_length(iov[0].iov_base);
struct socket *ssocket = server->ssocket;
if (ssocket == NULL)
return -ENOTSOCK; /* BB eventually add reconnect code here */
smb_msg.msg_name = (struct sockaddr *) &server->dstaddr;
smb_msg.msg_namelen = sizeof(struct sockaddr);
smb_msg.msg_control = NULL;
smb_msg.msg_controllen = 0;
if (server->noblocksnd)
smb_msg.msg_flags = MSG_DONTWAIT + MSG_NOSIGNAL;
else
smb_msg.msg_flags = MSG_NOSIGNAL;
total_len = 0;
for (i = 0; i < n_vec; i++)
total_len += iov[i].iov_len;
cFYI(1, "Sending smb: total_len %d", total_len);
dump_smb(iov[0].iov_base, len);
i = 0;
while (total_len) {
rc = kernel_sendmsg(ssocket, &smb_msg, &iov[first_vec],
n_vec - first_vec, total_len);
if ((rc == -ENOSPC) || (rc == -EAGAIN)) {
i++;
/*
* If blocking send we try 3 times, since each can block
* for 5 seconds. For nonblocking we have to try more
* but wait increasing amounts of time allowing time for
* socket to clear. The overall time we wait in either
* case to send on the socket is about 15 seconds.
* Similarly we wait for 15 seconds for a response from
* the server in SendReceive[2] for the server to send
* a response back for most types of requests (except
* SMB Write past end of file which can be slow, and
* blocking lock operations). NFS waits slightly longer
* than CIFS, but this can make it take longer for
* nonresponsive servers to be detected and 15 seconds
* is more than enough time for modern networks to
* send a packet. In most cases if we fail to send
* after the retries we will kill the socket and
* reconnect which may clear the network problem.
*/
if ((i >= 14) || (!server->noblocksnd && (i > 2))) {
cERROR(1, "sends on sock %p stuck for 15 seconds",
ssocket);
rc = -EAGAIN;
break;
}
msleep(1 << i);
continue;
}
if (rc < 0)
break;
if (rc == total_len) {
total_len = 0;
break;
} else if (rc > total_len) {
cERROR(1, "sent %d requested %d", rc, total_len);
break;
}
if (rc == 0) {
/* should never happen, letting socket clear before
retrying is our only obvious option here */
cERROR(1, "tcp sent no data");
msleep(500);
continue;
}
total_len -= rc;
/* the line below resets i */
for (i = first_vec; i < n_vec; i++) {
if (iov[i].iov_len) {
if (rc > iov[i].iov_len) {
rc -= iov[i].iov_len;
iov[i].iov_len = 0;
} else {
iov[i].iov_base += rc;
iov[i].iov_len -= rc;
first_vec = i;
break;
}
}
}
i = 0; /* in case we get ENOSPC on the next send */
}
if ((total_len > 0) && (total_len != smb_buf_length + 4)) {
cFYI(1, "partial send (%d remaining), terminating session",
total_len);
/* If we have only sent part of an SMB then the next SMB
could be taken as the remainder of this one. We need
to kill the socket so the server throws away the partial
SMB */
server->tcpStatus = CifsNeedReconnect;
}
if (rc < 0 && rc != -EINTR)
cERROR(1, "Error %d sending data on socket to server", rc);
else
rc = 0;
/* Don't want to modify the buffer as a side effect of this call. */
*buf_len = cpu_to_be32(smb_buf_length);
return rc;
}
int
smb_send(struct TCP_Server_Info *server, struct smb_hdr *smb_buffer,
unsigned int smb_buf_length)
{
struct kvec iov;
iov.iov_base = smb_buffer;
iov.iov_len = smb_buf_length + 4;
return smb_sendv(server, &iov, 1);
}
static int
wait_for_free_credits(struct TCP_Server_Info *server, const int optype,
int *credits)
{
int rc;
spin_lock(&server->req_lock);
if (optype == CIFS_ASYNC_OP) {
/* oplock breaks must not be held up */
server->in_flight++;
*credits -= 1;
spin_unlock(&server->req_lock);
return 0;
}
while (1) {
if (*credits <= 0) {
spin_unlock(&server->req_lock);
cifs_num_waiters_inc(server);
rc = wait_event_killable(server->request_q,
has_credits(server, credits));
cifs_num_waiters_dec(server);
if (rc)
return rc;
spin_lock(&server->req_lock);
} else {
if (server->tcpStatus == CifsExiting) {
spin_unlock(&server->req_lock);
return -ENOENT;
}
/*
* Can not count locking commands against total
* as they are allowed to block on server.
*/
/* update # of requests on the wire to server */
if (optype != CIFS_BLOCKING_OP) {
*credits -= 1;
server->in_flight++;
}
spin_unlock(&server->req_lock);
break;
}
}
return 0;
}
static int
wait_for_free_request(struct TCP_Server_Info *server, const int optype)
{
return wait_for_free_credits(server, optype, get_credits_field(server));
}
static int allocate_mid(struct cifs_ses *ses, struct smb_hdr *in_buf,
struct mid_q_entry **ppmidQ)
{
if (ses->server->tcpStatus == CifsExiting) {
return -ENOENT;
}
if (ses->server->tcpStatus == CifsNeedReconnect) {
cFYI(1, "tcp session dead - return to caller to retry");
return -EAGAIN;
}
if (ses->status != CifsGood) {
/* check if SMB session is bad because we are setting it up */
if ((in_buf->Command != SMB_COM_SESSION_SETUP_ANDX) &&
(in_buf->Command != SMB_COM_NEGOTIATE))
return -EAGAIN;
/* else ok - we are setting up session */
}
*ppmidQ = AllocMidQEntry(in_buf, ses->server);
if (*ppmidQ == NULL)
return -ENOMEM;
spin_lock(&GlobalMid_Lock);
list_add_tail(&(*ppmidQ)->qhead, &ses->server->pending_mid_q);
spin_unlock(&GlobalMid_Lock);
return 0;
}
static int
wait_for_response(struct TCP_Server_Info *server, struct mid_q_entry *midQ)
{
int error;
error = wait_event_freezekillable_unsafe(server->response_q,
midQ->mid_state != MID_REQUEST_SUBMITTED);
if (error < 0)
return -ERESTARTSYS;
return 0;
}
static int
cifs_setup_async_request(struct TCP_Server_Info *server, struct kvec *iov,
unsigned int nvec, struct mid_q_entry **ret_mid)
{
int rc;
struct smb_hdr *hdr = (struct smb_hdr *)iov[0].iov_base;
struct mid_q_entry *mid;
/* enable signing if server requires it */
if (server->sec_mode & (SECMODE_SIGN_REQUIRED | SECMODE_SIGN_ENABLED))
hdr->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
mid = AllocMidQEntry(hdr, server);
if (mid == NULL)
return -ENOMEM;
/* put it on the pending_mid_q */
spin_lock(&GlobalMid_Lock);
list_add_tail(&mid->qhead, &server->pending_mid_q);
spin_unlock(&GlobalMid_Lock);
rc = cifs_sign_smb2(iov, nvec, server, &mid->sequence_number);
if (rc)
delete_mid(mid);
*ret_mid = mid;
return rc;
}
/*
* Send a SMB request and set the callback function in the mid to handle
* the result. Caller is responsible for dealing with timeouts.
*/
int
cifs_call_async(struct TCP_Server_Info *server, struct kvec *iov,
unsigned int nvec, mid_receive_t *receive,
mid_callback_t *callback, void *cbdata, bool ignore_pend)
{
int rc;
struct mid_q_entry *mid;
rc = wait_for_free_request(server, ignore_pend ? CIFS_ASYNC_OP : 0);
if (rc)
return rc;
mutex_lock(&server->srv_mutex);
rc = cifs_setup_async_request(server, iov, nvec, &mid);
if (rc) {
mutex_unlock(&server->srv_mutex);
cifs_add_credits(server, 1);
wake_up(&server->request_q);
return rc;
}
mid->receive = receive;
mid->callback = callback;
mid->callback_data = cbdata;
mid->mid_state = MID_REQUEST_SUBMITTED;
cifs_in_send_inc(server);
rc = smb_sendv(server, iov, nvec);
cifs_in_send_dec(server);
cifs_save_when_sent(mid);
mutex_unlock(&server->srv_mutex);
if (rc)
goto out_err;
return rc;
out_err:
delete_mid(mid);
cifs_add_credits(server, 1);
wake_up(&server->request_q);
return rc;
}
/*
*
* Send an SMB Request. No response info (other than return code)
* needs to be parsed.
*
* flags indicate the type of request buffer and how long to wait
* and whether to log NT STATUS code (error) before mapping it to POSIX error
*
*/
int
SendReceiveNoRsp(const unsigned int xid, struct cifs_ses *ses,
char *in_buf, int flags)
{
int rc;
struct kvec iov[1];
int resp_buf_type;
iov[0].iov_base = in_buf;
iov[0].iov_len = get_rfc1002_length(in_buf) + 4;
flags |= CIFS_NO_RESP;
rc = SendReceive2(xid, ses, iov, 1, &resp_buf_type, flags);
cFYI(DBG2, "SendRcvNoRsp flags %d rc %d", flags, rc);
return rc;
}
static int
cifs_sync_mid_result(struct mid_q_entry *mid, struct TCP_Server_Info *server)
{
int rc = 0;
cFYI(1, "%s: cmd=%d mid=%llu state=%d", __func__,
le16_to_cpu(mid->command), mid->mid, mid->mid_state);
spin_lock(&GlobalMid_Lock);
switch (mid->mid_state) {
case MID_RESPONSE_RECEIVED:
spin_unlock(&GlobalMid_Lock);
return rc;
case MID_RETRY_NEEDED:
rc = -EAGAIN;
break;
case MID_RESPONSE_MALFORMED:
rc = -EIO;
break;
case MID_SHUTDOWN:
rc = -EHOSTDOWN;
break;
default:
list_del_init(&mid->qhead);
cERROR(1, "%s: invalid mid state mid=%llu state=%d", __func__,
mid->mid, mid->mid_state);
rc = -EIO;
}
spin_unlock(&GlobalMid_Lock);
DeleteMidQEntry(mid);
return rc;
}
/*
* An NT cancel request header looks just like the original request except:
*
* The Command is SMB_COM_NT_CANCEL
* The WordCount is zeroed out
* The ByteCount is zeroed out
*
* This function mangles an existing request buffer into a
* SMB_COM_NT_CANCEL request and then sends it.
*/
static int
send_nt_cancel(struct TCP_Server_Info *server, struct smb_hdr *in_buf,
struct mid_q_entry *mid)
{
int rc = 0;
/* -4 for RFC1001 length and +2 for BCC field */
in_buf->smb_buf_length = cpu_to_be32(sizeof(struct smb_hdr) - 4 + 2);
in_buf->Command = SMB_COM_NT_CANCEL;
in_buf->WordCount = 0;
put_bcc(0, in_buf);
mutex_lock(&server->srv_mutex);
rc = cifs_sign_smb(in_buf, server, &mid->sequence_number);
if (rc) {
mutex_unlock(&server->srv_mutex);
return rc;
}
rc = smb_send(server, in_buf, be32_to_cpu(in_buf->smb_buf_length));
mutex_unlock(&server->srv_mutex);
cFYI(1, "issued NT_CANCEL for mid %u, rc = %d",
in_buf->Mid, rc);
return rc;
}
int
cifs_check_receive(struct mid_q_entry *mid, struct TCP_Server_Info *server,
bool log_error)
{
unsigned int len = get_rfc1002_length(mid->resp_buf) + 4;
dump_smb(mid->resp_buf, min_t(u32, 92, len));
/* convert the length into a more usable form */
if (server->sec_mode & (SECMODE_SIGN_REQUIRED | SECMODE_SIGN_ENABLED)) {
struct kvec iov;
iov.iov_base = mid->resp_buf;
iov.iov_len = len;
/* FIXME: add code to kill session */
if (cifs_verify_signature(&iov, 1, server,
mid->sequence_number + 1) != 0)
cERROR(1, "Unexpected SMB signature");
}
/* BB special case reconnect tid and uid here? */
return map_smb_to_linux_error(mid->resp_buf, log_error);
}
static int
cifs_setup_request(struct cifs_ses *ses, struct kvec *iov,
unsigned int nvec, struct mid_q_entry **ret_mid)
{
int rc;
struct smb_hdr *hdr = (struct smb_hdr *)iov[0].iov_base;
struct mid_q_entry *mid;
rc = allocate_mid(ses, hdr, &mid);
if (rc)
return rc;
rc = cifs_sign_smb2(iov, nvec, ses->server, &mid->sequence_number);
if (rc)
delete_mid(mid);
*ret_mid = mid;
return rc;
}
int
SendReceive2(const unsigned int xid, struct cifs_ses *ses,
struct kvec *iov, int n_vec, int *pRespBufType /* ret */,
const int flags)
{
int rc = 0;
int long_op;
struct mid_q_entry *midQ = NULL;
char *buf = iov[0].iov_base;
long_op = flags & CIFS_TIMEOUT_MASK;
*pRespBufType = CIFS_NO_BUFFER; /* no response buf yet */
if ((ses == NULL) || (ses->server == NULL)) {
cifs_small_buf_release(buf);
cERROR(1, "Null session");
return -EIO;
}
if (ses->server->tcpStatus == CifsExiting) {
cifs_small_buf_release(buf);
return -ENOENT;
}
/*
* Ensure that we do not send more than 50 overlapping requests
* to the same server. We may make this configurable later or
* use ses->maxReq.
*/
rc = wait_for_free_request(ses->server, long_op);
if (rc) {
cifs_small_buf_release(buf);
return rc;
}
/*
* Make sure that we sign in the same order that we send on this socket
* and avoid races inside tcp sendmsg code that could cause corruption
* of smb data.
*/
mutex_lock(&ses->server->srv_mutex);
rc = cifs_setup_request(ses, iov, n_vec, &midQ);
if (rc) {
mutex_unlock(&ses->server->srv_mutex);
cifs_small_buf_release(buf);
/* Update # of requests on wire to server */
cifs_add_credits(ses->server, 1);
return rc;
}
midQ->mid_state = MID_REQUEST_SUBMITTED;
cifs_in_send_inc(ses->server);
rc = smb_sendv(ses->server, iov, n_vec);
cifs_in_send_dec(ses->server);
cifs_save_when_sent(midQ);
mutex_unlock(&ses->server->srv_mutex);
if (rc < 0) {
cifs_small_buf_release(buf);
goto out;
}
if (long_op == CIFS_ASYNC_OP) {
cifs_small_buf_release(buf);
goto out;
}
rc = wait_for_response(ses->server, midQ);
if (rc != 0) {
send_nt_cancel(ses->server, (struct smb_hdr *)buf, midQ);
spin_lock(&GlobalMid_Lock);
if (midQ->mid_state == MID_REQUEST_SUBMITTED) {
midQ->callback = DeleteMidQEntry;
spin_unlock(&GlobalMid_Lock);
cifs_small_buf_release(buf);
cifs_add_credits(ses->server, 1);
return rc;
}
spin_unlock(&GlobalMid_Lock);
}
cifs_small_buf_release(buf);
rc = cifs_sync_mid_result(midQ, ses->server);
if (rc != 0) {
cifs_add_credits(ses->server, 1);
return rc;
}
if (!midQ->resp_buf || midQ->mid_state != MID_RESPONSE_RECEIVED) {
rc = -EIO;
cFYI(1, "Bad MID state?");
goto out;
}
buf = (char *)midQ->resp_buf;
iov[0].iov_base = buf;
iov[0].iov_len = get_rfc1002_length(buf) + 4;
if (midQ->large_buf)
*pRespBufType = CIFS_LARGE_BUFFER;
else
*pRespBufType = CIFS_SMALL_BUFFER;
rc = cifs_check_receive(midQ, ses->server, flags & CIFS_LOG_ERROR);
/* mark it so buf will not be freed by delete_mid */
if ((flags & CIFS_NO_RESP) == 0)
midQ->resp_buf = NULL;
out:
delete_mid(midQ);
cifs_add_credits(ses->server, 1);
return rc;
}
int
SendReceive(const unsigned int xid, struct cifs_ses *ses,
struct smb_hdr *in_buf, struct smb_hdr *out_buf,
int *pbytes_returned, const int long_op)
{
int rc = 0;
struct mid_q_entry *midQ;
if (ses == NULL) {
cERROR(1, "Null smb session");
return -EIO;
}
if (ses->server == NULL) {
cERROR(1, "Null tcp session");
return -EIO;
}
if (ses->server->tcpStatus == CifsExiting)
return -ENOENT;
/* Ensure that we do not send more than 50 overlapping requests
to the same server. We may make this configurable later or
use ses->maxReq */
if (be32_to_cpu(in_buf->smb_buf_length) > CIFSMaxBufSize +
MAX_CIFS_HDR_SIZE - 4) {
cERROR(1, "Illegal length, greater than maximum frame, %d",
be32_to_cpu(in_buf->smb_buf_length));
return -EIO;
}
rc = wait_for_free_request(ses->server, long_op);
if (rc)
return rc;
/* make sure that we sign in the same order that we send on this socket
and avoid races inside tcp sendmsg code that could cause corruption
of smb data */
mutex_lock(&ses->server->srv_mutex);
rc = allocate_mid(ses, in_buf, &midQ);
if (rc) {
mutex_unlock(&ses->server->srv_mutex);
/* Update # of requests on wire to server */
cifs_add_credits(ses->server, 1);
return rc;
}
rc = cifs_sign_smb(in_buf, ses->server, &midQ->sequence_number);
if (rc) {
mutex_unlock(&ses->server->srv_mutex);
goto out;
}
midQ->mid_state = MID_REQUEST_SUBMITTED;
cifs_in_send_inc(ses->server);
rc = smb_send(ses->server, in_buf, be32_to_cpu(in_buf->smb_buf_length));
cifs_in_send_dec(ses->server);
cifs_save_when_sent(midQ);
mutex_unlock(&ses->server->srv_mutex);
if (rc < 0)
goto out;
if (long_op == CIFS_ASYNC_OP)
goto out;
rc = wait_for_response(ses->server, midQ);
if (rc != 0) {
send_nt_cancel(ses->server, in_buf, midQ);
spin_lock(&GlobalMid_Lock);
if (midQ->mid_state == MID_REQUEST_SUBMITTED) {
/* no longer considered to be "in-flight" */
midQ->callback = DeleteMidQEntry;
spin_unlock(&GlobalMid_Lock);
cifs_add_credits(ses->server, 1);
return rc;
}
spin_unlock(&GlobalMid_Lock);
}
rc = cifs_sync_mid_result(midQ, ses->server);
if (rc != 0) {
cifs_add_credits(ses->server, 1);
return rc;
}
if (!midQ->resp_buf || !out_buf ||
midQ->mid_state != MID_RESPONSE_RECEIVED) {
rc = -EIO;
cERROR(1, "Bad MID state?");
goto out;
}
*pbytes_returned = get_rfc1002_length(midQ->resp_buf);
memcpy(out_buf, midQ->resp_buf, *pbytes_returned + 4);
rc = cifs_check_receive(midQ, ses->server, 0);
out:
delete_mid(midQ);
cifs_add_credits(ses->server, 1);
return rc;
}
/* We send a LOCKINGX_CANCEL_LOCK to cause the Windows
blocking lock to return. */
static int
send_lock_cancel(const unsigned int xid, struct cifs_tcon *tcon,
struct smb_hdr *in_buf,
struct smb_hdr *out_buf)
{
int bytes_returned;
struct cifs_ses *ses = tcon->ses;
LOCK_REQ *pSMB = (LOCK_REQ *)in_buf;
/* We just modify the current in_buf to change
the type of lock from LOCKING_ANDX_SHARED_LOCK
or LOCKING_ANDX_EXCLUSIVE_LOCK to
LOCKING_ANDX_CANCEL_LOCK. */
pSMB->LockType = LOCKING_ANDX_CANCEL_LOCK|LOCKING_ANDX_LARGE_FILES;
pSMB->Timeout = 0;
pSMB->hdr.Mid = GetNextMid(ses->server);
return SendReceive(xid, ses, in_buf, out_buf,
&bytes_returned, 0);
}
int
SendReceiveBlockingLock(const unsigned int xid, struct cifs_tcon *tcon,
struct smb_hdr *in_buf, struct smb_hdr *out_buf,
int *pbytes_returned)
{
int rc = 0;
int rstart = 0;
struct mid_q_entry *midQ;
struct cifs_ses *ses;
if (tcon == NULL || tcon->ses == NULL) {
cERROR(1, "Null smb session");
return -EIO;
}
ses = tcon->ses;
if (ses->server == NULL) {
cERROR(1, "Null tcp session");
return -EIO;
}
if (ses->server->tcpStatus == CifsExiting)
return -ENOENT;
/* Ensure that we do not send more than 50 overlapping requests
to the same server. We may make this configurable later or
use ses->maxReq */
if (be32_to_cpu(in_buf->smb_buf_length) > CIFSMaxBufSize +
MAX_CIFS_HDR_SIZE - 4) {
cERROR(1, "Illegal length, greater than maximum frame, %d",
be32_to_cpu(in_buf->smb_buf_length));
return -EIO;
}
rc = wait_for_free_request(ses->server, CIFS_BLOCKING_OP);
if (rc)
return rc;
/* make sure that we sign in the same order that we send on this socket
and avoid races inside tcp sendmsg code that could cause corruption
of smb data */
mutex_lock(&ses->server->srv_mutex);
rc = allocate_mid(ses, in_buf, &midQ);
if (rc) {
mutex_unlock(&ses->server->srv_mutex);
return rc;
}
rc = cifs_sign_smb(in_buf, ses->server, &midQ->sequence_number);
if (rc) {
delete_mid(midQ);
mutex_unlock(&ses->server->srv_mutex);
return rc;
}
midQ->mid_state = MID_REQUEST_SUBMITTED;
cifs_in_send_inc(ses->server);
rc = smb_send(ses->server, in_buf, be32_to_cpu(in_buf->smb_buf_length));
cifs_in_send_dec(ses->server);
cifs_save_when_sent(midQ);
mutex_unlock(&ses->server->srv_mutex);
if (rc < 0) {
delete_mid(midQ);
return rc;
}
/* Wait for a reply - allow signals to interrupt. */
rc = wait_event_interruptible(ses->server->response_q,
(!(midQ->mid_state == MID_REQUEST_SUBMITTED)) ||
((ses->server->tcpStatus != CifsGood) &&
(ses->server->tcpStatus != CifsNew)));
/* Were we interrupted by a signal ? */
if ((rc == -ERESTARTSYS) &&
(midQ->mid_state == MID_REQUEST_SUBMITTED) &&
((ses->server->tcpStatus == CifsGood) ||
(ses->server->tcpStatus == CifsNew))) {
if (in_buf->Command == SMB_COM_TRANSACTION2) {
/* POSIX lock. We send a NT_CANCEL SMB to cause the
blocking lock to return. */
rc = send_nt_cancel(ses->server, in_buf, midQ);
if (rc) {
delete_mid(midQ);
return rc;
}
} else {
/* Windows lock. We send a LOCKINGX_CANCEL_LOCK
to cause the blocking lock to return. */
rc = send_lock_cancel(xid, tcon, in_buf, out_buf);
/* If we get -ENOLCK back the lock may have
already been removed. Don't exit in this case. */
if (rc && rc != -ENOLCK) {
delete_mid(midQ);
return rc;
}
}
rc = wait_for_response(ses->server, midQ);
if (rc) {
send_nt_cancel(ses->server, in_buf, midQ);
spin_lock(&GlobalMid_Lock);
if (midQ->mid_state == MID_REQUEST_SUBMITTED) {
/* no longer considered to be "in-flight" */
midQ->callback = DeleteMidQEntry;
spin_unlock(&GlobalMid_Lock);
return rc;
}
spin_unlock(&GlobalMid_Lock);
}
/* We got the response - restart system call. */
rstart = 1;
}
rc = cifs_sync_mid_result(midQ, ses->server);
if (rc != 0)
return rc;
/* rcvd frame is ok */
if (out_buf == NULL || midQ->mid_state != MID_RESPONSE_RECEIVED) {
rc = -EIO;
cERROR(1, "Bad MID state?");
goto out;
}
*pbytes_returned = get_rfc1002_length(midQ->resp_buf);
memcpy(out_buf, midQ->resp_buf, *pbytes_returned + 4);
rc = cifs_check_receive(midQ, ses->server, 0);
out:
delete_mid(midQ);
if (rstart && rc == -EACCES)
return -ERESTARTSYS;
return rc;
}
| gpl-2.0 |
sadven/meisiekernel | MeiKern/drivers/net/can/janz-ican3.c | 610 | 47647 | /*
* Janz MODULbus VMOD-ICAN3 CAN Interface Driver
*
* Copyright (c) 2010 Ira W. Snyder <iws@ovro.caltech.edu>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/platform_device.h>
#include <linux/netdevice.h>
#include <linux/can.h>
#include <linux/can/dev.h>
#include <linux/can/error.h>
#include <linux/mfd/janz.h>
#include <asm/io.h>
/* the DPM has 64k of memory, organized into 256x 256 byte pages */
#define DPM_NUM_PAGES 256
#define DPM_PAGE_SIZE 256
#define DPM_PAGE_ADDR(p) ((p) * DPM_PAGE_SIZE)
/* JANZ ICAN3 "old-style" host interface queue page numbers */
#define QUEUE_OLD_CONTROL 0
#define QUEUE_OLD_RB0 1
#define QUEUE_OLD_RB1 2
#define QUEUE_OLD_WB0 3
#define QUEUE_OLD_WB1 4
/* Janz ICAN3 "old-style" host interface control registers */
#define MSYNC_PEER 0x00 /* ICAN only */
#define MSYNC_LOCL 0x01 /* host only */
#define TARGET_RUNNING 0x02
#define MSYNC_RB0 0x01
#define MSYNC_RB1 0x02
#define MSYNC_RBLW 0x04
#define MSYNC_RB_MASK (MSYNC_RB0 | MSYNC_RB1)
#define MSYNC_WB0 0x10
#define MSYNC_WB1 0x20
#define MSYNC_WBLW 0x40
#define MSYNC_WB_MASK (MSYNC_WB0 | MSYNC_WB1)
/* Janz ICAN3 "new-style" host interface queue page numbers */
#define QUEUE_TOHOST 5
#define QUEUE_FROMHOST_MID 6
#define QUEUE_FROMHOST_HIGH 7
#define QUEUE_FROMHOST_LOW 8
/* The first free page in the DPM is #9 */
#define DPM_FREE_START 9
/* Janz ICAN3 "new-style" and "fast" host interface descriptor flags */
#define DESC_VALID 0x80
#define DESC_WRAP 0x40
#define DESC_INTERRUPT 0x20
#define DESC_IVALID 0x10
#define DESC_LEN(len) (len)
/* Janz ICAN3 Firmware Messages */
#define MSG_CONNECTI 0x02
#define MSG_DISCONNECT 0x03
#define MSG_IDVERS 0x04
#define MSG_MSGLOST 0x05
#define MSG_NEWHOSTIF 0x08
#define MSG_INQUIRY 0x0a
#define MSG_SETAFILMASK 0x10
#define MSG_INITFDPMQUEUE 0x11
#define MSG_HWCONF 0x12
#define MSG_FMSGLOST 0x15
#define MSG_CEVTIND 0x37
#define MSG_CBTRREQ 0x41
#define MSG_COFFREQ 0x42
#define MSG_CONREQ 0x43
#define MSG_CCONFREQ 0x47
/*
* Janz ICAN3 CAN Inquiry Message Types
*
* NOTE: there appears to be a firmware bug here. You must send
* NOTE: INQUIRY_STATUS and expect to receive an INQUIRY_EXTENDED
* NOTE: response. The controller never responds to a message with
* NOTE: the INQUIRY_EXTENDED subspec :(
*/
#define INQUIRY_STATUS 0x00
#define INQUIRY_TERMINATION 0x01
#define INQUIRY_EXTENDED 0x04
/* Janz ICAN3 CAN Set Acceptance Filter Mask Message Types */
#define SETAFILMASK_REJECT 0x00
#define SETAFILMASK_FASTIF 0x02
/* Janz ICAN3 CAN Hardware Configuration Message Types */
#define HWCONF_TERMINATE_ON 0x01
#define HWCONF_TERMINATE_OFF 0x00
/* Janz ICAN3 CAN Event Indication Message Types */
#define CEVTIND_EI 0x01
#define CEVTIND_DOI 0x02
#define CEVTIND_LOST 0x04
#define CEVTIND_FULL 0x08
#define CEVTIND_BEI 0x10
#define CEVTIND_CHIP_SJA1000 0x02
#define ICAN3_BUSERR_QUOTA_MAX 255
/* Janz ICAN3 CAN Frame Conversion */
#define ICAN3_SNGL 0x02
#define ICAN3_ECHO 0x10
#define ICAN3_EFF_RTR 0x40
#define ICAN3_SFF_RTR 0x10
#define ICAN3_EFF 0x80
#define ICAN3_CAN_TYPE_MASK 0x0f
#define ICAN3_CAN_TYPE_SFF 0x00
#define ICAN3_CAN_TYPE_EFF 0x01
#define ICAN3_CAN_DLC_MASK 0x0f
/*
* SJA1000 Status and Error Register Definitions
*
* Copied from drivers/net/can/sja1000/sja1000.h
*/
/* status register content */
#define SR_BS 0x80
#define SR_ES 0x40
#define SR_TS 0x20
#define SR_RS 0x10
#define SR_TCS 0x08
#define SR_TBS 0x04
#define SR_DOS 0x02
#define SR_RBS 0x01
#define SR_CRIT (SR_BS|SR_ES)
/* ECC register */
#define ECC_SEG 0x1F
#define ECC_DIR 0x20
#define ECC_ERR 6
#define ECC_BIT 0x00
#define ECC_FORM 0x40
#define ECC_STUFF 0x80
#define ECC_MASK 0xc0
/* Number of buffers for use in the "new-style" host interface */
#define ICAN3_NEW_BUFFERS 16
/* Number of buffers for use in the "fast" host interface */
#define ICAN3_TX_BUFFERS 512
#define ICAN3_RX_BUFFERS 1024
/* SJA1000 Clock Input */
#define ICAN3_CAN_CLOCK 8000000
/* Driver Name */
#define DRV_NAME "janz-ican3"
/* DPM Control Registers -- starts at offset 0x100 in the MODULbus registers */
struct ican3_dpm_control {
/* window address register */
u8 window_address;
u8 unused1;
/*
* Read access: clear interrupt from microcontroller
* Write access: send interrupt to microcontroller
*/
u8 interrupt;
u8 unused2;
/* write-only: reset all hardware on the module */
u8 hwreset;
u8 unused3;
/* write-only: generate an interrupt to the TPU */
u8 tpuinterrupt;
};
struct ican3_dev {
/* must be the first member */
struct can_priv can;
/* CAN network device */
struct net_device *ndev;
struct napi_struct napi;
/* Device for printing */
struct device *dev;
/* module number */
unsigned int num;
/* base address of registers and IRQ */
struct janz_cmodio_onboard_regs __iomem *ctrl;
struct ican3_dpm_control __iomem *dpmctrl;
void __iomem *dpm;
int irq;
/* CAN bus termination status */
struct completion termination_comp;
bool termination_enabled;
/* CAN bus error status registers */
struct completion buserror_comp;
struct can_berr_counter bec;
/* old and new style host interface */
unsigned int iftype;
/* queue for echo packets */
struct sk_buff_head echoq;
/*
* Any function which changes the current DPM page must hold this
* lock while it is performing data accesses. This ensures that the
* function will not be preempted and end up reading data from a
* different DPM page than it expects.
*/
spinlock_t lock;
/* new host interface */
unsigned int rx_int;
unsigned int rx_num;
unsigned int tx_num;
/* fast host interface */
unsigned int fastrx_start;
unsigned int fastrx_num;
unsigned int fasttx_start;
unsigned int fasttx_num;
/* first free DPM page */
unsigned int free_page;
};
struct ican3_msg {
u8 control;
u8 spec;
__le16 len;
u8 data[252];
};
struct ican3_new_desc {
u8 control;
u8 pointer;
};
struct ican3_fast_desc {
u8 control;
u8 command;
u8 data[14];
};
/* write to the window basic address register */
static inline void ican3_set_page(struct ican3_dev *mod, unsigned int page)
{
BUG_ON(page >= DPM_NUM_PAGES);
iowrite8(page, &mod->dpmctrl->window_address);
}
/*
* ICAN3 "old-style" host interface
*/
/*
* Receive a message from the ICAN3 "old-style" firmware interface
*
* LOCKING: must hold mod->lock
*
* returns 0 on success, -ENOMEM when no message exists
*/
static int ican3_old_recv_msg(struct ican3_dev *mod, struct ican3_msg *msg)
{
unsigned int mbox, mbox_page;
u8 locl, peer, xord;
/* get the MSYNC registers */
ican3_set_page(mod, QUEUE_OLD_CONTROL);
peer = ioread8(mod->dpm + MSYNC_PEER);
locl = ioread8(mod->dpm + MSYNC_LOCL);
xord = locl ^ peer;
if ((xord & MSYNC_RB_MASK) == 0x00) {
dev_dbg(mod->dev, "no mbox for reading\n");
return -ENOMEM;
}
/* find the first free mbox to read */
if ((xord & MSYNC_RB_MASK) == MSYNC_RB_MASK)
mbox = (xord & MSYNC_RBLW) ? MSYNC_RB0 : MSYNC_RB1;
else
mbox = (xord & MSYNC_RB0) ? MSYNC_RB0 : MSYNC_RB1;
/* copy the message */
mbox_page = (mbox == MSYNC_RB0) ? QUEUE_OLD_RB0 : QUEUE_OLD_RB1;
ican3_set_page(mod, mbox_page);
memcpy_fromio(msg, mod->dpm, sizeof(*msg));
/*
* notify the firmware that the read buffer is available
* for it to fill again
*/
locl ^= mbox;
ican3_set_page(mod, QUEUE_OLD_CONTROL);
iowrite8(locl, mod->dpm + MSYNC_LOCL);
return 0;
}
/*
* Send a message through the "old-style" firmware interface
*
* LOCKING: must hold mod->lock
*
* returns 0 on success, -ENOMEM when no free space exists
*/
static int ican3_old_send_msg(struct ican3_dev *mod, struct ican3_msg *msg)
{
unsigned int mbox, mbox_page;
u8 locl, peer, xord;
/* get the MSYNC registers */
ican3_set_page(mod, QUEUE_OLD_CONTROL);
peer = ioread8(mod->dpm + MSYNC_PEER);
locl = ioread8(mod->dpm + MSYNC_LOCL);
xord = locl ^ peer;
if ((xord & MSYNC_WB_MASK) == MSYNC_WB_MASK) {
dev_err(mod->dev, "no mbox for writing\n");
return -ENOMEM;
}
/* calculate a free mbox to use */
mbox = (xord & MSYNC_WB0) ? MSYNC_WB1 : MSYNC_WB0;
/* copy the message to the DPM */
mbox_page = (mbox == MSYNC_WB0) ? QUEUE_OLD_WB0 : QUEUE_OLD_WB1;
ican3_set_page(mod, mbox_page);
memcpy_toio(mod->dpm, msg, sizeof(*msg));
locl ^= mbox;
if (mbox == MSYNC_WB1)
locl |= MSYNC_WBLW;
ican3_set_page(mod, QUEUE_OLD_CONTROL);
iowrite8(locl, mod->dpm + MSYNC_LOCL);
return 0;
}
/*
* ICAN3 "new-style" Host Interface Setup
*/
static void ican3_init_new_host_interface(struct ican3_dev *mod)
{
struct ican3_new_desc desc;
unsigned long flags;
void __iomem *dst;
int i;
spin_lock_irqsave(&mod->lock, flags);
/* setup the internal datastructures for RX */
mod->rx_num = 0;
mod->rx_int = 0;
/* tohost queue descriptors are in page 5 */
ican3_set_page(mod, QUEUE_TOHOST);
dst = mod->dpm;
/* initialize the tohost (rx) queue descriptors: pages 9-24 */
for (i = 0; i < ICAN3_NEW_BUFFERS; i++) {
desc.control = DESC_INTERRUPT | DESC_LEN(1); /* I L=1 */
desc.pointer = mod->free_page;
/* set wrap flag on last buffer */
if (i == ICAN3_NEW_BUFFERS - 1)
desc.control |= DESC_WRAP;
memcpy_toio(dst, &desc, sizeof(desc));
dst += sizeof(desc);
mod->free_page++;
}
/* fromhost (tx) mid queue descriptors are in page 6 */
ican3_set_page(mod, QUEUE_FROMHOST_MID);
dst = mod->dpm;
/* setup the internal datastructures for TX */
mod->tx_num = 0;
/* initialize the fromhost mid queue descriptors: pages 25-40 */
for (i = 0; i < ICAN3_NEW_BUFFERS; i++) {
desc.control = DESC_VALID | DESC_LEN(1); /* V L=1 */
desc.pointer = mod->free_page;
/* set wrap flag on last buffer */
if (i == ICAN3_NEW_BUFFERS - 1)
desc.control |= DESC_WRAP;
memcpy_toio(dst, &desc, sizeof(desc));
dst += sizeof(desc);
mod->free_page++;
}
/* fromhost hi queue descriptors are in page 7 */
ican3_set_page(mod, QUEUE_FROMHOST_HIGH);
dst = mod->dpm;
/* initialize only a single buffer in the fromhost hi queue (unused) */
desc.control = DESC_VALID | DESC_WRAP | DESC_LEN(1); /* VW L=1 */
desc.pointer = mod->free_page;
memcpy_toio(dst, &desc, sizeof(desc));
mod->free_page++;
/* fromhost low queue descriptors are in page 8 */
ican3_set_page(mod, QUEUE_FROMHOST_LOW);
dst = mod->dpm;
/* initialize only a single buffer in the fromhost low queue (unused) */
desc.control = DESC_VALID | DESC_WRAP | DESC_LEN(1); /* VW L=1 */
desc.pointer = mod->free_page;
memcpy_toio(dst, &desc, sizeof(desc));
mod->free_page++;
spin_unlock_irqrestore(&mod->lock, flags);
}
/*
* ICAN3 Fast Host Interface Setup
*/
static void ican3_init_fast_host_interface(struct ican3_dev *mod)
{
struct ican3_fast_desc desc;
unsigned long flags;
unsigned int addr;
void __iomem *dst;
int i;
spin_lock_irqsave(&mod->lock, flags);
/* save the start recv page */
mod->fastrx_start = mod->free_page;
mod->fastrx_num = 0;
/* build a single fast tohost queue descriptor */
memset(&desc, 0, sizeof(desc));
desc.control = 0x00;
desc.command = 1;
/* build the tohost queue descriptor ring in memory */
addr = 0;
for (i = 0; i < ICAN3_RX_BUFFERS; i++) {
/* set the wrap bit on the last buffer */
if (i == ICAN3_RX_BUFFERS - 1)
desc.control |= DESC_WRAP;
/* switch to the correct page */
ican3_set_page(mod, mod->free_page);
/* copy the descriptor to the DPM */
dst = mod->dpm + addr;
memcpy_toio(dst, &desc, sizeof(desc));
addr += sizeof(desc);
/* move to the next page if necessary */
if (addr >= DPM_PAGE_SIZE) {
addr = 0;
mod->free_page++;
}
}
/* make sure we page-align the next queue */
if (addr != 0)
mod->free_page++;
/* save the start xmit page */
mod->fasttx_start = mod->free_page;
mod->fasttx_num = 0;
/* build a single fast fromhost queue descriptor */
memset(&desc, 0, sizeof(desc));
desc.control = DESC_VALID;
desc.command = 1;
/* build the fromhost queue descriptor ring in memory */
addr = 0;
for (i = 0; i < ICAN3_TX_BUFFERS; i++) {
/* set the wrap bit on the last buffer */
if (i == ICAN3_TX_BUFFERS - 1)
desc.control |= DESC_WRAP;
/* switch to the correct page */
ican3_set_page(mod, mod->free_page);
/* copy the descriptor to the DPM */
dst = mod->dpm + addr;
memcpy_toio(dst, &desc, sizeof(desc));
addr += sizeof(desc);
/* move to the next page if necessary */
if (addr >= DPM_PAGE_SIZE) {
addr = 0;
mod->free_page++;
}
}
spin_unlock_irqrestore(&mod->lock, flags);
}
/*
* ICAN3 "new-style" Host Interface Message Helpers
*/
/*
* LOCKING: must hold mod->lock
*/
static int ican3_new_send_msg(struct ican3_dev *mod, struct ican3_msg *msg)
{
struct ican3_new_desc desc;
void __iomem *desc_addr = mod->dpm + (mod->tx_num * sizeof(desc));
/* switch to the fromhost mid queue, and read the buffer descriptor */
ican3_set_page(mod, QUEUE_FROMHOST_MID);
memcpy_fromio(&desc, desc_addr, sizeof(desc));
if (!(desc.control & DESC_VALID)) {
dev_dbg(mod->dev, "%s: no free buffers\n", __func__);
return -ENOMEM;
}
/* switch to the data page, copy the data */
ican3_set_page(mod, desc.pointer);
memcpy_toio(mod->dpm, msg, sizeof(*msg));
/* switch back to the descriptor, set the valid bit, write it back */
ican3_set_page(mod, QUEUE_FROMHOST_MID);
desc.control ^= DESC_VALID;
memcpy_toio(desc_addr, &desc, sizeof(desc));
/* update the tx number */
mod->tx_num = (desc.control & DESC_WRAP) ? 0 : (mod->tx_num + 1);
return 0;
}
/*
* LOCKING: must hold mod->lock
*/
static int ican3_new_recv_msg(struct ican3_dev *mod, struct ican3_msg *msg)
{
struct ican3_new_desc desc;
void __iomem *desc_addr = mod->dpm + (mod->rx_num * sizeof(desc));
/* switch to the tohost queue, and read the buffer descriptor */
ican3_set_page(mod, QUEUE_TOHOST);
memcpy_fromio(&desc, desc_addr, sizeof(desc));
if (!(desc.control & DESC_VALID)) {
dev_dbg(mod->dev, "%s: no buffers to recv\n", __func__);
return -ENOMEM;
}
/* switch to the data page, copy the data */
ican3_set_page(mod, desc.pointer);
memcpy_fromio(msg, mod->dpm, sizeof(*msg));
/* switch back to the descriptor, toggle the valid bit, write it back */
ican3_set_page(mod, QUEUE_TOHOST);
desc.control ^= DESC_VALID;
memcpy_toio(desc_addr, &desc, sizeof(desc));
/* update the rx number */
mod->rx_num = (desc.control & DESC_WRAP) ? 0 : (mod->rx_num + 1);
return 0;
}
/*
* Message Send / Recv Helpers
*/
static int ican3_send_msg(struct ican3_dev *mod, struct ican3_msg *msg)
{
unsigned long flags;
int ret;
spin_lock_irqsave(&mod->lock, flags);
if (mod->iftype == 0)
ret = ican3_old_send_msg(mod, msg);
else
ret = ican3_new_send_msg(mod, msg);
spin_unlock_irqrestore(&mod->lock, flags);
return ret;
}
static int ican3_recv_msg(struct ican3_dev *mod, struct ican3_msg *msg)
{
unsigned long flags;
int ret;
spin_lock_irqsave(&mod->lock, flags);
if (mod->iftype == 0)
ret = ican3_old_recv_msg(mod, msg);
else
ret = ican3_new_recv_msg(mod, msg);
spin_unlock_irqrestore(&mod->lock, flags);
return ret;
}
/*
* Quick Pre-constructed Messages
*/
static int ican3_msg_connect(struct ican3_dev *mod)
{
struct ican3_msg msg;
memset(&msg, 0, sizeof(msg));
msg.spec = MSG_CONNECTI;
msg.len = cpu_to_le16(0);
return ican3_send_msg(mod, &msg);
}
static int ican3_msg_disconnect(struct ican3_dev *mod)
{
struct ican3_msg msg;
memset(&msg, 0, sizeof(msg));
msg.spec = MSG_DISCONNECT;
msg.len = cpu_to_le16(0);
return ican3_send_msg(mod, &msg);
}
static int ican3_msg_newhostif(struct ican3_dev *mod)
{
struct ican3_msg msg;
int ret;
memset(&msg, 0, sizeof(msg));
msg.spec = MSG_NEWHOSTIF;
msg.len = cpu_to_le16(0);
/* If we're not using the old interface, switching seems bogus */
WARN_ON(mod->iftype != 0);
ret = ican3_send_msg(mod, &msg);
if (ret)
return ret;
/* mark the module as using the new host interface */
mod->iftype = 1;
return 0;
}
static int ican3_msg_fasthostif(struct ican3_dev *mod)
{
struct ican3_msg msg;
unsigned int addr;
memset(&msg, 0, sizeof(msg));
msg.spec = MSG_INITFDPMQUEUE;
msg.len = cpu_to_le16(8);
/* write the tohost queue start address */
addr = DPM_PAGE_ADDR(mod->fastrx_start);
msg.data[0] = addr & 0xff;
msg.data[1] = (addr >> 8) & 0xff;
msg.data[2] = (addr >> 16) & 0xff;
msg.data[3] = (addr >> 24) & 0xff;
/* write the fromhost queue start address */
addr = DPM_PAGE_ADDR(mod->fasttx_start);
msg.data[4] = addr & 0xff;
msg.data[5] = (addr >> 8) & 0xff;
msg.data[6] = (addr >> 16) & 0xff;
msg.data[7] = (addr >> 24) & 0xff;
/* If we're not using the new interface yet, we cannot do this */
WARN_ON(mod->iftype != 1);
return ican3_send_msg(mod, &msg);
}
/*
* Setup the CAN filter to either accept or reject all
* messages from the CAN bus.
*/
static int ican3_set_id_filter(struct ican3_dev *mod, bool accept)
{
struct ican3_msg msg;
int ret;
/* Standard Frame Format */
memset(&msg, 0, sizeof(msg));
msg.spec = MSG_SETAFILMASK;
msg.len = cpu_to_le16(5);
msg.data[0] = 0x00; /* IDLo LSB */
msg.data[1] = 0x00; /* IDLo MSB */
msg.data[2] = 0xff; /* IDHi LSB */
msg.data[3] = 0x07; /* IDHi MSB */
/* accept all frames for fast host if, or reject all frames */
msg.data[4] = accept ? SETAFILMASK_FASTIF : SETAFILMASK_REJECT;
ret = ican3_send_msg(mod, &msg);
if (ret)
return ret;
/* Extended Frame Format */
memset(&msg, 0, sizeof(msg));
msg.spec = MSG_SETAFILMASK;
msg.len = cpu_to_le16(13);
msg.data[0] = 0; /* MUX = 0 */
msg.data[1] = 0x00; /* IDLo LSB */
msg.data[2] = 0x00;
msg.data[3] = 0x00;
msg.data[4] = 0x20; /* IDLo MSB */
msg.data[5] = 0xff; /* IDHi LSB */
msg.data[6] = 0xff;
msg.data[7] = 0xff;
msg.data[8] = 0x3f; /* IDHi MSB */
/* accept all frames for fast host if, or reject all frames */
msg.data[9] = accept ? SETAFILMASK_FASTIF : SETAFILMASK_REJECT;
return ican3_send_msg(mod, &msg);
}
/*
* Bring the CAN bus online or offline
*/
static int ican3_set_bus_state(struct ican3_dev *mod, bool on)
{
struct ican3_msg msg;
memset(&msg, 0, sizeof(msg));
msg.spec = on ? MSG_CONREQ : MSG_COFFREQ;
msg.len = cpu_to_le16(0);
return ican3_send_msg(mod, &msg);
}
static int ican3_set_termination(struct ican3_dev *mod, bool on)
{
struct ican3_msg msg;
memset(&msg, 0, sizeof(msg));
msg.spec = MSG_HWCONF;
msg.len = cpu_to_le16(2);
msg.data[0] = 0x00;
msg.data[1] = on ? HWCONF_TERMINATE_ON : HWCONF_TERMINATE_OFF;
return ican3_send_msg(mod, &msg);
}
static int ican3_send_inquiry(struct ican3_dev *mod, u8 subspec)
{
struct ican3_msg msg;
memset(&msg, 0, sizeof(msg));
msg.spec = MSG_INQUIRY;
msg.len = cpu_to_le16(2);
msg.data[0] = subspec;
msg.data[1] = 0x00;
return ican3_send_msg(mod, &msg);
}
static int ican3_set_buserror(struct ican3_dev *mod, u8 quota)
{
struct ican3_msg msg;
memset(&msg, 0, sizeof(msg));
msg.spec = MSG_CCONFREQ;
msg.len = cpu_to_le16(2);
msg.data[0] = 0x00;
msg.data[1] = quota;
return ican3_send_msg(mod, &msg);
}
/*
* ICAN3 to Linux CAN Frame Conversion
*/
static void ican3_to_can_frame(struct ican3_dev *mod,
struct ican3_fast_desc *desc,
struct can_frame *cf)
{
if ((desc->command & ICAN3_CAN_TYPE_MASK) == ICAN3_CAN_TYPE_SFF) {
if (desc->data[1] & ICAN3_SFF_RTR)
cf->can_id |= CAN_RTR_FLAG;
cf->can_id |= desc->data[0] << 3;
cf->can_id |= (desc->data[1] & 0xe0) >> 5;
cf->can_dlc = get_can_dlc(desc->data[1] & ICAN3_CAN_DLC_MASK);
memcpy(cf->data, &desc->data[2], cf->can_dlc);
} else {
cf->can_dlc = get_can_dlc(desc->data[0] & ICAN3_CAN_DLC_MASK);
if (desc->data[0] & ICAN3_EFF_RTR)
cf->can_id |= CAN_RTR_FLAG;
if (desc->data[0] & ICAN3_EFF) {
cf->can_id |= CAN_EFF_FLAG;
cf->can_id |= desc->data[2] << 21; /* 28-21 */
cf->can_id |= desc->data[3] << 13; /* 20-13 */
cf->can_id |= desc->data[4] << 5; /* 12-5 */
cf->can_id |= (desc->data[5] & 0xf8) >> 3;
} else {
cf->can_id |= desc->data[2] << 3; /* 10-3 */
cf->can_id |= desc->data[3] >> 5; /* 2-0 */
}
memcpy(cf->data, &desc->data[6], cf->can_dlc);
}
}
static void can_frame_to_ican3(struct ican3_dev *mod,
struct can_frame *cf,
struct ican3_fast_desc *desc)
{
/* clear out any stale data in the descriptor */
memset(desc->data, 0, sizeof(desc->data));
/* we always use the extended format, with the ECHO flag set */
desc->command = ICAN3_CAN_TYPE_EFF;
desc->data[0] |= cf->can_dlc;
desc->data[1] |= ICAN3_ECHO;
/* support single transmission (no retries) mode */
if (mod->can.ctrlmode & CAN_CTRLMODE_ONE_SHOT)
desc->data[1] |= ICAN3_SNGL;
if (cf->can_id & CAN_RTR_FLAG)
desc->data[0] |= ICAN3_EFF_RTR;
/* pack the id into the correct places */
if (cf->can_id & CAN_EFF_FLAG) {
desc->data[0] |= ICAN3_EFF;
desc->data[2] = (cf->can_id & 0x1fe00000) >> 21; /* 28-21 */
desc->data[3] = (cf->can_id & 0x001fe000) >> 13; /* 20-13 */
desc->data[4] = (cf->can_id & 0x00001fe0) >> 5; /* 12-5 */
desc->data[5] = (cf->can_id & 0x0000001f) << 3; /* 4-0 */
} else {
desc->data[2] = (cf->can_id & 0x7F8) >> 3; /* bits 10-3 */
desc->data[3] = (cf->can_id & 0x007) << 5; /* bits 2-0 */
}
/* copy the data bits into the descriptor */
memcpy(&desc->data[6], cf->data, cf->can_dlc);
}
/*
* Interrupt Handling
*/
/*
* Handle an ID + Version message response from the firmware. We never generate
* this message in production code, but it is very useful when debugging to be
* able to display this message.
*/
static void ican3_handle_idvers(struct ican3_dev *mod, struct ican3_msg *msg)
{
dev_dbg(mod->dev, "IDVERS response: %s\n", msg->data);
}
static void ican3_handle_msglost(struct ican3_dev *mod, struct ican3_msg *msg)
{
struct net_device *dev = mod->ndev;
struct net_device_stats *stats = &dev->stats;
struct can_frame *cf;
struct sk_buff *skb;
/*
* Report that communication messages with the microcontroller firmware
* are being lost. These are never CAN frames, so we do not generate an
* error frame for userspace
*/
if (msg->spec == MSG_MSGLOST) {
dev_err(mod->dev, "lost %d control messages\n", msg->data[0]);
return;
}
/*
* Oops, this indicates that we have lost messages in the fast queue,
* which are exclusively CAN messages. Our driver isn't reading CAN
* frames fast enough.
*
* We'll pretend that the SJA1000 told us that it ran out of buffer
* space, because there is not a better message for this.
*/
skb = alloc_can_err_skb(dev, &cf);
if (skb) {
cf->can_id |= CAN_ERR_CRTL;
cf->data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
stats->rx_over_errors++;
stats->rx_errors++;
netif_rx(skb);
}
}
/*
* Handle CAN Event Indication Messages from the firmware
*
* The ICAN3 firmware provides the values of some SJA1000 registers when it
* generates this message. The code below is largely copied from the
* drivers/net/can/sja1000/sja1000.c file, and adapted as necessary
*/
static int ican3_handle_cevtind(struct ican3_dev *mod, struct ican3_msg *msg)
{
struct net_device *dev = mod->ndev;
struct net_device_stats *stats = &dev->stats;
enum can_state state = mod->can.state;
u8 isrc, ecc, status, rxerr, txerr;
struct can_frame *cf;
struct sk_buff *skb;
/* we can only handle the SJA1000 part */
if (msg->data[1] != CEVTIND_CHIP_SJA1000) {
dev_err(mod->dev, "unable to handle errors on non-SJA1000\n");
return -ENODEV;
}
/* check the message length for sanity */
if (le16_to_cpu(msg->len) < 6) {
dev_err(mod->dev, "error message too short\n");
return -EINVAL;
}
isrc = msg->data[0];
ecc = msg->data[2];
status = msg->data[3];
rxerr = msg->data[4];
txerr = msg->data[5];
/*
* This hardware lacks any support other than bus error messages to
* determine if packet transmission has failed.
*
* When TX errors happen, one echo skb needs to be dropped from the
* front of the queue.
*
* A small bit of code is duplicated here and below, to avoid error
* skb allocation when it will just be freed immediately.
*/
if (isrc == CEVTIND_BEI) {
int ret;
dev_dbg(mod->dev, "bus error interrupt\n");
/* TX error */
if (!(ecc & ECC_DIR)) {
kfree_skb(skb_dequeue(&mod->echoq));
stats->tx_errors++;
} else {
stats->rx_errors++;
}
/*
* The controller automatically disables bus-error interrupts
* and therefore we must re-enable them.
*/
ret = ican3_set_buserror(mod, 1);
if (ret) {
dev_err(mod->dev, "unable to re-enable bus-error\n");
return ret;
}
/* bus error reporting is off, return immediately */
if (!(mod->can.ctrlmode & CAN_CTRLMODE_BERR_REPORTING))
return 0;
}
skb = alloc_can_err_skb(dev, &cf);
if (skb == NULL)
return -ENOMEM;
/* data overrun interrupt */
if (isrc == CEVTIND_DOI || isrc == CEVTIND_LOST) {
dev_dbg(mod->dev, "data overrun interrupt\n");
cf->can_id |= CAN_ERR_CRTL;
cf->data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
stats->rx_over_errors++;
stats->rx_errors++;
}
/* error warning + passive interrupt */
if (isrc == CEVTIND_EI) {
dev_dbg(mod->dev, "error warning + passive interrupt\n");
if (status & SR_BS) {
state = CAN_STATE_BUS_OFF;
cf->can_id |= CAN_ERR_BUSOFF;
can_bus_off(dev);
} else if (status & SR_ES) {
if (rxerr >= 128 || txerr >= 128)
state = CAN_STATE_ERROR_PASSIVE;
else
state = CAN_STATE_ERROR_WARNING;
} else {
state = CAN_STATE_ERROR_ACTIVE;
}
}
/* bus error interrupt */
if (isrc == CEVTIND_BEI) {
mod->can.can_stats.bus_error++;
cf->can_id |= CAN_ERR_PROT | CAN_ERR_BUSERROR;
switch (ecc & ECC_MASK) {
case ECC_BIT:
cf->data[2] |= CAN_ERR_PROT_BIT;
break;
case ECC_FORM:
cf->data[2] |= CAN_ERR_PROT_FORM;
break;
case ECC_STUFF:
cf->data[2] |= CAN_ERR_PROT_STUFF;
break;
default:
cf->data[2] |= CAN_ERR_PROT_UNSPEC;
cf->data[3] = ecc & ECC_SEG;
break;
}
if (!(ecc & ECC_DIR))
cf->data[2] |= CAN_ERR_PROT_TX;
cf->data[6] = txerr;
cf->data[7] = rxerr;
}
if (state != mod->can.state && (state == CAN_STATE_ERROR_WARNING ||
state == CAN_STATE_ERROR_PASSIVE)) {
cf->can_id |= CAN_ERR_CRTL;
if (state == CAN_STATE_ERROR_WARNING) {
mod->can.can_stats.error_warning++;
cf->data[1] = (txerr > rxerr) ?
CAN_ERR_CRTL_TX_WARNING :
CAN_ERR_CRTL_RX_WARNING;
} else {
mod->can.can_stats.error_passive++;
cf->data[1] = (txerr > rxerr) ?
CAN_ERR_CRTL_TX_PASSIVE :
CAN_ERR_CRTL_RX_PASSIVE;
}
cf->data[6] = txerr;
cf->data[7] = rxerr;
}
mod->can.state = state;
netif_rx(skb);
return 0;
}
static void ican3_handle_inquiry(struct ican3_dev *mod, struct ican3_msg *msg)
{
switch (msg->data[0]) {
case INQUIRY_STATUS:
case INQUIRY_EXTENDED:
mod->bec.rxerr = msg->data[5];
mod->bec.txerr = msg->data[6];
complete(&mod->buserror_comp);
break;
case INQUIRY_TERMINATION:
mod->termination_enabled = msg->data[6] & HWCONF_TERMINATE_ON;
complete(&mod->termination_comp);
break;
default:
dev_err(mod->dev, "received an unknown inquiry response\n");
break;
}
}
static void ican3_handle_unknown_message(struct ican3_dev *mod,
struct ican3_msg *msg)
{
dev_warn(mod->dev, "received unknown message: spec 0x%.2x length %d\n",
msg->spec, le16_to_cpu(msg->len));
}
/*
* Handle a control message from the firmware
*/
static void ican3_handle_message(struct ican3_dev *mod, struct ican3_msg *msg)
{
dev_dbg(mod->dev, "%s: modno %d spec 0x%.2x len %d bytes\n", __func__,
mod->num, msg->spec, le16_to_cpu(msg->len));
switch (msg->spec) {
case MSG_IDVERS:
ican3_handle_idvers(mod, msg);
break;
case MSG_MSGLOST:
case MSG_FMSGLOST:
ican3_handle_msglost(mod, msg);
break;
case MSG_CEVTIND:
ican3_handle_cevtind(mod, msg);
break;
case MSG_INQUIRY:
ican3_handle_inquiry(mod, msg);
break;
default:
ican3_handle_unknown_message(mod, msg);
break;
}
}
/*
* The ican3 needs to store all echo skbs, and therefore cannot
* use the generic infrastructure for this.
*/
static void ican3_put_echo_skb(struct ican3_dev *mod, struct sk_buff *skb)
{
struct sock *srcsk = skb->sk;
if (atomic_read(&skb->users) != 1) {
struct sk_buff *old_skb = skb;
skb = skb_clone(old_skb, GFP_ATOMIC);
kfree_skb(old_skb);
if (!skb)
return;
} else {
skb_orphan(skb);
}
skb->sk = srcsk;
/* save this skb for tx interrupt echo handling */
skb_queue_tail(&mod->echoq, skb);
}
static unsigned int ican3_get_echo_skb(struct ican3_dev *mod)
{
struct sk_buff *skb = skb_dequeue(&mod->echoq);
struct can_frame *cf;
u8 dlc;
/* this should never trigger unless there is a driver bug */
if (!skb) {
netdev_err(mod->ndev, "BUG: echo skb not occupied\n");
return 0;
}
cf = (struct can_frame *)skb->data;
dlc = cf->can_dlc;
/* check flag whether this packet has to be looped back */
if (skb->pkt_type != PACKET_LOOPBACK) {
kfree_skb(skb);
return dlc;
}
skb->protocol = htons(ETH_P_CAN);
skb->pkt_type = PACKET_BROADCAST;
skb->ip_summed = CHECKSUM_UNNECESSARY;
skb->dev = mod->ndev;
netif_receive_skb(skb);
return dlc;
}
/*
* Compare an skb with an existing echo skb
*
* This function will be used on devices which have a hardware loopback.
* On these devices, this function can be used to compare a received skb
* with the saved echo skbs so that the hardware echo skb can be dropped.
*
* Returns true if the skb's are identical, false otherwise.
*/
static bool ican3_echo_skb_matches(struct ican3_dev *mod, struct sk_buff *skb)
{
struct can_frame *cf = (struct can_frame *)skb->data;
struct sk_buff *echo_skb = skb_peek(&mod->echoq);
struct can_frame *echo_cf;
if (!echo_skb)
return false;
echo_cf = (struct can_frame *)echo_skb->data;
if (cf->can_id != echo_cf->can_id)
return false;
if (cf->can_dlc != echo_cf->can_dlc)
return false;
return memcmp(cf->data, echo_cf->data, cf->can_dlc) == 0;
}
/*
* Check that there is room in the TX ring to transmit another skb
*
* LOCKING: must hold mod->lock
*/
static bool ican3_txok(struct ican3_dev *mod)
{
struct ican3_fast_desc __iomem *desc;
u8 control;
/* check that we have echo queue space */
if (skb_queue_len(&mod->echoq) >= ICAN3_TX_BUFFERS)
return false;
/* copy the control bits of the descriptor */
ican3_set_page(mod, mod->fasttx_start + (mod->fasttx_num / 16));
desc = mod->dpm + ((mod->fasttx_num % 16) * sizeof(*desc));
control = ioread8(&desc->control);
/* if the control bits are not valid, then we have no more space */
if (!(control & DESC_VALID))
return false;
return true;
}
/*
* Receive one CAN frame from the hardware
*
* CONTEXT: must be called from user context
*/
static int ican3_recv_skb(struct ican3_dev *mod)
{
struct net_device *ndev = mod->ndev;
struct net_device_stats *stats = &ndev->stats;
struct ican3_fast_desc desc;
void __iomem *desc_addr;
struct can_frame *cf;
struct sk_buff *skb;
unsigned long flags;
spin_lock_irqsave(&mod->lock, flags);
/* copy the whole descriptor */
ican3_set_page(mod, mod->fastrx_start + (mod->fastrx_num / 16));
desc_addr = mod->dpm + ((mod->fastrx_num % 16) * sizeof(desc));
memcpy_fromio(&desc, desc_addr, sizeof(desc));
spin_unlock_irqrestore(&mod->lock, flags);
/* check that we actually have a CAN frame */
if (!(desc.control & DESC_VALID))
return -ENOBUFS;
/* allocate an skb */
skb = alloc_can_skb(ndev, &cf);
if (unlikely(skb == NULL)) {
stats->rx_dropped++;
goto err_noalloc;
}
/* convert the ICAN3 frame into Linux CAN format */
ican3_to_can_frame(mod, &desc, cf);
/*
* If this is an ECHO frame received from the hardware loopback
* feature, use the skb saved in the ECHO stack instead. This allows
* the Linux CAN core to support CAN_RAW_RECV_OWN_MSGS correctly.
*
* Since this is a confirmation of a successfully transmitted packet
* sent from this host, update the transmit statistics.
*
* Also, the netdevice queue needs to be allowed to send packets again.
*/
if (ican3_echo_skb_matches(mod, skb)) {
stats->tx_packets++;
stats->tx_bytes += ican3_get_echo_skb(mod);
kfree_skb(skb);
goto err_noalloc;
}
/* update statistics, receive the skb */
stats->rx_packets++;
stats->rx_bytes += cf->can_dlc;
netif_receive_skb(skb);
err_noalloc:
/* toggle the valid bit and return the descriptor to the ring */
desc.control ^= DESC_VALID;
spin_lock_irqsave(&mod->lock, flags);
ican3_set_page(mod, mod->fastrx_start + (mod->fastrx_num / 16));
memcpy_toio(desc_addr, &desc, 1);
/* update the next buffer pointer */
mod->fastrx_num = (desc.control & DESC_WRAP) ? 0
: (mod->fastrx_num + 1);
/* there are still more buffers to process */
spin_unlock_irqrestore(&mod->lock, flags);
return 0;
}
static int ican3_napi(struct napi_struct *napi, int budget)
{
struct ican3_dev *mod = container_of(napi, struct ican3_dev, napi);
unsigned long flags;
int received = 0;
int ret;
/* process all communication messages */
while (true) {
struct ican3_msg msg;
ret = ican3_recv_msg(mod, &msg);
if (ret)
break;
ican3_handle_message(mod, &msg);
}
/* process all CAN frames from the fast interface */
while (received < budget) {
ret = ican3_recv_skb(mod);
if (ret)
break;
received++;
}
/* We have processed all packets that the adapter had, but it
* was less than our budget, stop polling */
if (received < budget)
napi_complete(napi);
spin_lock_irqsave(&mod->lock, flags);
/* Wake up the transmit queue if necessary */
if (netif_queue_stopped(mod->ndev) && ican3_txok(mod))
netif_wake_queue(mod->ndev);
spin_unlock_irqrestore(&mod->lock, flags);
/* re-enable interrupt generation */
iowrite8(1 << mod->num, &mod->ctrl->int_enable);
return received;
}
static irqreturn_t ican3_irq(int irq, void *dev_id)
{
struct ican3_dev *mod = dev_id;
u8 stat;
/*
* The interrupt status register on this device reports interrupts
* as zeroes instead of using ones like most other devices
*/
stat = ioread8(&mod->ctrl->int_disable) & (1 << mod->num);
if (stat == (1 << mod->num))
return IRQ_NONE;
/* clear the MODULbus interrupt from the microcontroller */
ioread8(&mod->dpmctrl->interrupt);
/* disable interrupt generation, schedule the NAPI poller */
iowrite8(1 << mod->num, &mod->ctrl->int_disable);
napi_schedule(&mod->napi);
return IRQ_HANDLED;
}
/*
* Firmware reset, startup, and shutdown
*/
/*
* Reset an ICAN module to its power-on state
*
* CONTEXT: no network device registered
*/
static int ican3_reset_module(struct ican3_dev *mod)
{
unsigned long start;
u8 runold, runnew;
/* disable interrupts so no more work is scheduled */
iowrite8(1 << mod->num, &mod->ctrl->int_disable);
/* the first unallocated page in the DPM is #9 */
mod->free_page = DPM_FREE_START;
ican3_set_page(mod, QUEUE_OLD_CONTROL);
runold = ioread8(mod->dpm + TARGET_RUNNING);
/* reset the module */
iowrite8(0x00, &mod->dpmctrl->hwreset);
/* wait until the module has finished resetting and is running */
start = jiffies;
do {
ican3_set_page(mod, QUEUE_OLD_CONTROL);
runnew = ioread8(mod->dpm + TARGET_RUNNING);
if (runnew == (runold ^ 0xff))
return 0;
msleep(10);
} while (time_before(jiffies, start + HZ / 4));
dev_err(mod->dev, "failed to reset CAN module\n");
return -ETIMEDOUT;
}
static void ican3_shutdown_module(struct ican3_dev *mod)
{
ican3_msg_disconnect(mod);
ican3_reset_module(mod);
}
/*
* Startup an ICAN module, bringing it into fast mode
*/
static int ican3_startup_module(struct ican3_dev *mod)
{
int ret;
ret = ican3_reset_module(mod);
if (ret) {
dev_err(mod->dev, "unable to reset module\n");
return ret;
}
/* re-enable interrupts so we can send messages */
iowrite8(1 << mod->num, &mod->ctrl->int_enable);
ret = ican3_msg_connect(mod);
if (ret) {
dev_err(mod->dev, "unable to connect to module\n");
return ret;
}
ican3_init_new_host_interface(mod);
ret = ican3_msg_newhostif(mod);
if (ret) {
dev_err(mod->dev, "unable to switch to new-style interface\n");
return ret;
}
/* default to "termination on" */
ret = ican3_set_termination(mod, true);
if (ret) {
dev_err(mod->dev, "unable to enable termination\n");
return ret;
}
/* default to "bus errors enabled" */
ret = ican3_set_buserror(mod, 1);
if (ret) {
dev_err(mod->dev, "unable to set bus-error\n");
return ret;
}
ican3_init_fast_host_interface(mod);
ret = ican3_msg_fasthostif(mod);
if (ret) {
dev_err(mod->dev, "unable to switch to fast host interface\n");
return ret;
}
ret = ican3_set_id_filter(mod, true);
if (ret) {
dev_err(mod->dev, "unable to set acceptance filter\n");
return ret;
}
return 0;
}
/*
* CAN Network Device
*/
static int ican3_open(struct net_device *ndev)
{
struct ican3_dev *mod = netdev_priv(ndev);
int ret;
/* open the CAN layer */
ret = open_candev(ndev);
if (ret) {
dev_err(mod->dev, "unable to start CAN layer\n");
return ret;
}
/* bring the bus online */
ret = ican3_set_bus_state(mod, true);
if (ret) {
dev_err(mod->dev, "unable to set bus-on\n");
close_candev(ndev);
return ret;
}
/* start up the network device */
mod->can.state = CAN_STATE_ERROR_ACTIVE;
netif_start_queue(ndev);
return 0;
}
static int ican3_stop(struct net_device *ndev)
{
struct ican3_dev *mod = netdev_priv(ndev);
int ret;
/* stop the network device xmit routine */
netif_stop_queue(ndev);
mod->can.state = CAN_STATE_STOPPED;
/* bring the bus offline, stop receiving packets */
ret = ican3_set_bus_state(mod, false);
if (ret) {
dev_err(mod->dev, "unable to set bus-off\n");
return ret;
}
/* drop all outstanding echo skbs */
skb_queue_purge(&mod->echoq);
/* close the CAN layer */
close_candev(ndev);
return 0;
}
static int ican3_xmit(struct sk_buff *skb, struct net_device *ndev)
{
struct ican3_dev *mod = netdev_priv(ndev);
struct can_frame *cf = (struct can_frame *)skb->data;
struct ican3_fast_desc desc;
void __iomem *desc_addr;
unsigned long flags;
if (can_dropped_invalid_skb(ndev, skb))
return NETDEV_TX_OK;
spin_lock_irqsave(&mod->lock, flags);
/* check that we can actually transmit */
if (!ican3_txok(mod)) {
dev_err(mod->dev, "BUG: no free descriptors\n");
spin_unlock_irqrestore(&mod->lock, flags);
return NETDEV_TX_BUSY;
}
/* copy the control bits of the descriptor */
ican3_set_page(mod, mod->fasttx_start + (mod->fasttx_num / 16));
desc_addr = mod->dpm + ((mod->fasttx_num % 16) * sizeof(desc));
memset(&desc, 0, sizeof(desc));
memcpy_fromio(&desc, desc_addr, 1);
/* convert the Linux CAN frame into ICAN3 format */
can_frame_to_ican3(mod, cf, &desc);
/*
* This hardware doesn't have TX-done notifications, so we'll try and
* emulate it the best we can using ECHO skbs. Add the skb to the ECHO
* stack. Upon packet reception, check if the ECHO skb and received
* skb match, and use that to wake the queue.
*/
ican3_put_echo_skb(mod, skb);
/*
* the programming manual says that you must set the IVALID bit, then
* interrupt, then set the valid bit. Quite weird, but it seems to be
* required for this to work
*/
desc.control |= DESC_IVALID;
memcpy_toio(desc_addr, &desc, sizeof(desc));
/* generate a MODULbus interrupt to the microcontroller */
iowrite8(0x01, &mod->dpmctrl->interrupt);
desc.control ^= DESC_VALID;
memcpy_toio(desc_addr, &desc, sizeof(desc));
/* update the next buffer pointer */
mod->fasttx_num = (desc.control & DESC_WRAP) ? 0
: (mod->fasttx_num + 1);
/* if there is no free descriptor space, stop the transmit queue */
if (!ican3_txok(mod))
netif_stop_queue(ndev);
spin_unlock_irqrestore(&mod->lock, flags);
return NETDEV_TX_OK;
}
static const struct net_device_ops ican3_netdev_ops = {
.ndo_open = ican3_open,
.ndo_stop = ican3_stop,
.ndo_start_xmit = ican3_xmit,
};
/*
* Low-level CAN Device
*/
/* This structure was stolen from drivers/net/can/sja1000/sja1000.c */
static const struct can_bittiming_const ican3_bittiming_const = {
.name = DRV_NAME,
.tseg1_min = 1,
.tseg1_max = 16,
.tseg2_min = 1,
.tseg2_max = 8,
.sjw_max = 4,
.brp_min = 1,
.brp_max = 64,
.brp_inc = 1,
};
/*
* This routine was stolen from drivers/net/can/sja1000/sja1000.c
*
* The bittiming register command for the ICAN3 just sets the bit timing
* registers on the SJA1000 chip directly
*/
static int ican3_set_bittiming(struct net_device *ndev)
{
struct ican3_dev *mod = netdev_priv(ndev);
struct can_bittiming *bt = &mod->can.bittiming;
struct ican3_msg msg;
u8 btr0, btr1;
btr0 = ((bt->brp - 1) & 0x3f) | (((bt->sjw - 1) & 0x3) << 6);
btr1 = ((bt->prop_seg + bt->phase_seg1 - 1) & 0xf) |
(((bt->phase_seg2 - 1) & 0x7) << 4);
if (mod->can.ctrlmode & CAN_CTRLMODE_3_SAMPLES)
btr1 |= 0x80;
memset(&msg, 0, sizeof(msg));
msg.spec = MSG_CBTRREQ;
msg.len = cpu_to_le16(4);
msg.data[0] = 0x00;
msg.data[1] = 0x00;
msg.data[2] = btr0;
msg.data[3] = btr1;
return ican3_send_msg(mod, &msg);
}
static int ican3_set_mode(struct net_device *ndev, enum can_mode mode)
{
struct ican3_dev *mod = netdev_priv(ndev);
int ret;
if (mode != CAN_MODE_START)
return -ENOTSUPP;
/* bring the bus online */
ret = ican3_set_bus_state(mod, true);
if (ret) {
dev_err(mod->dev, "unable to set bus-on\n");
return ret;
}
/* start up the network device */
mod->can.state = CAN_STATE_ERROR_ACTIVE;
if (netif_queue_stopped(ndev))
netif_wake_queue(ndev);
return 0;
}
static int ican3_get_berr_counter(const struct net_device *ndev,
struct can_berr_counter *bec)
{
struct ican3_dev *mod = netdev_priv(ndev);
int ret;
ret = ican3_send_inquiry(mod, INQUIRY_STATUS);
if (ret)
return ret;
ret = wait_for_completion_timeout(&mod->buserror_comp, HZ);
if (ret == 0) {
dev_info(mod->dev, "%s timed out\n", __func__);
return -ETIMEDOUT;
}
bec->rxerr = mod->bec.rxerr;
bec->txerr = mod->bec.txerr;
return 0;
}
/*
* Sysfs Attributes
*/
static ssize_t ican3_sysfs_show_term(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct ican3_dev *mod = netdev_priv(to_net_dev(dev));
int ret;
ret = ican3_send_inquiry(mod, INQUIRY_TERMINATION);
if (ret)
return ret;
ret = wait_for_completion_timeout(&mod->termination_comp, HZ);
if (ret == 0) {
dev_info(mod->dev, "%s timed out\n", __func__);
return -ETIMEDOUT;
}
return snprintf(buf, PAGE_SIZE, "%u\n", mod->termination_enabled);
}
static ssize_t ican3_sysfs_set_term(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct ican3_dev *mod = netdev_priv(to_net_dev(dev));
unsigned long enable;
int ret;
if (strict_strtoul(buf, 0, &enable))
return -EINVAL;
ret = ican3_set_termination(mod, enable);
if (ret)
return ret;
return count;
}
static DEVICE_ATTR(termination, S_IWUSR | S_IRUGO, ican3_sysfs_show_term,
ican3_sysfs_set_term);
static struct attribute *ican3_sysfs_attrs[] = {
&dev_attr_termination.attr,
NULL,
};
static struct attribute_group ican3_sysfs_attr_group = {
.attrs = ican3_sysfs_attrs,
};
/*
* PCI Subsystem
*/
static int ican3_probe(struct platform_device *pdev)
{
struct janz_platform_data *pdata;
struct net_device *ndev;
struct ican3_dev *mod;
struct resource *res;
struct device *dev;
int ret;
pdata = pdev->dev.platform_data;
if (!pdata)
return -ENXIO;
dev_dbg(&pdev->dev, "probe: module number %d\n", pdata->modno);
/* save the struct device for printing */
dev = &pdev->dev;
/* allocate the CAN device and private data */
ndev = alloc_candev(sizeof(*mod), 0);
if (!ndev) {
dev_err(dev, "unable to allocate CANdev\n");
ret = -ENOMEM;
goto out_return;
}
platform_set_drvdata(pdev, ndev);
mod = netdev_priv(ndev);
mod->ndev = ndev;
mod->dev = &pdev->dev;
mod->num = pdata->modno;
netif_napi_add(ndev, &mod->napi, ican3_napi, ICAN3_RX_BUFFERS);
skb_queue_head_init(&mod->echoq);
spin_lock_init(&mod->lock);
init_completion(&mod->termination_comp);
init_completion(&mod->buserror_comp);
/* setup device-specific sysfs attributes */
ndev->sysfs_groups[0] = &ican3_sysfs_attr_group;
/* the first unallocated page in the DPM is 9 */
mod->free_page = DPM_FREE_START;
ndev->netdev_ops = &ican3_netdev_ops;
ndev->flags |= IFF_ECHO;
SET_NETDEV_DEV(ndev, &pdev->dev);
mod->can.clock.freq = ICAN3_CAN_CLOCK;
mod->can.bittiming_const = &ican3_bittiming_const;
mod->can.do_set_bittiming = ican3_set_bittiming;
mod->can.do_set_mode = ican3_set_mode;
mod->can.do_get_berr_counter = ican3_get_berr_counter;
mod->can.ctrlmode_supported = CAN_CTRLMODE_3_SAMPLES
| CAN_CTRLMODE_BERR_REPORTING
| CAN_CTRLMODE_ONE_SHOT;
/* find our IRQ number */
mod->irq = platform_get_irq(pdev, 0);
if (mod->irq < 0) {
dev_err(dev, "IRQ line not found\n");
ret = -ENODEV;
goto out_free_ndev;
}
ndev->irq = mod->irq;
/* get access to the MODULbus registers for this module */
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
dev_err(dev, "MODULbus registers not found\n");
ret = -ENODEV;
goto out_free_ndev;
}
mod->dpm = ioremap(res->start, resource_size(res));
if (!mod->dpm) {
dev_err(dev, "MODULbus registers not ioremap\n");
ret = -ENOMEM;
goto out_free_ndev;
}
mod->dpmctrl = mod->dpm + DPM_PAGE_SIZE;
/* get access to the control registers for this module */
res = platform_get_resource(pdev, IORESOURCE_MEM, 1);
if (!res) {
dev_err(dev, "CONTROL registers not found\n");
ret = -ENODEV;
goto out_iounmap_dpm;
}
mod->ctrl = ioremap(res->start, resource_size(res));
if (!mod->ctrl) {
dev_err(dev, "CONTROL registers not ioremap\n");
ret = -ENOMEM;
goto out_iounmap_dpm;
}
/* disable our IRQ, then hookup the IRQ handler */
iowrite8(1 << mod->num, &mod->ctrl->int_disable);
ret = request_irq(mod->irq, ican3_irq, IRQF_SHARED, DRV_NAME, mod);
if (ret) {
dev_err(dev, "unable to request IRQ\n");
goto out_iounmap_ctrl;
}
/* reset and initialize the CAN controller into fast mode */
napi_enable(&mod->napi);
ret = ican3_startup_module(mod);
if (ret) {
dev_err(dev, "%s: unable to start CANdev\n", __func__);
goto out_free_irq;
}
/* register with the Linux CAN layer */
ret = register_candev(ndev);
if (ret) {
dev_err(dev, "%s: unable to register CANdev\n", __func__);
goto out_free_irq;
}
dev_info(dev, "module %d: registered CAN device\n", pdata->modno);
return 0;
out_free_irq:
napi_disable(&mod->napi);
iowrite8(1 << mod->num, &mod->ctrl->int_disable);
free_irq(mod->irq, mod);
out_iounmap_ctrl:
iounmap(mod->ctrl);
out_iounmap_dpm:
iounmap(mod->dpm);
out_free_ndev:
free_candev(ndev);
out_return:
return ret;
}
static int ican3_remove(struct platform_device *pdev)
{
struct net_device *ndev = platform_get_drvdata(pdev);
struct ican3_dev *mod = netdev_priv(ndev);
/* unregister the netdevice, stop interrupts */
unregister_netdev(ndev);
napi_disable(&mod->napi);
iowrite8(1 << mod->num, &mod->ctrl->int_disable);
free_irq(mod->irq, mod);
/* put the module into reset */
ican3_shutdown_module(mod);
/* unmap all registers */
iounmap(mod->ctrl);
iounmap(mod->dpm);
free_candev(ndev);
return 0;
}
static struct platform_driver ican3_driver = {
.driver = {
.name = DRV_NAME,
.owner = THIS_MODULE,
},
.probe = ican3_probe,
.remove = ican3_remove,
};
module_platform_driver(ican3_driver);
MODULE_AUTHOR("Ira W. Snyder <iws@ovro.caltech.edu>");
MODULE_DESCRIPTION("Janz MODULbus VMOD-ICAN3 Driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:janz-ican3");
| gpl-2.0 |
mfrw/linux | arch/x86/pci/i386.c | 866 | 12290 | /*
* Low-Level PCI Access for i386 machines
*
* Copyright 1993, 1994 Drew Eckhardt
* Visionary Computing
* (Unix and Linux consulting and custom programming)
* Drew@Colorado.EDU
* +1 (303) 786-7975
*
* Drew's work was sponsored by:
* iX Multiuser Multitasking Magazine
* Hannover, Germany
* hm@ix.de
*
* Copyright 1997--2000 Martin Mares <mj@ucw.cz>
*
* For more information, please consult the following manuals (look at
* http://www.pcisig.com/ for how to get them):
*
* PCI BIOS Specification
* PCI Local Bus Specification
* PCI to PCI Bridge Specification
* PCI System Design Guide
*
*/
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/export.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/errno.h>
#include <linux/bootmem.h>
#include <asm/pat.h>
#include <asm/e820.h>
#include <asm/pci_x86.h>
#include <asm/io_apic.h>
/*
* This list of dynamic mappings is for temporarily maintaining
* original BIOS BAR addresses for possible reinstatement.
*/
struct pcibios_fwaddrmap {
struct list_head list;
struct pci_dev *dev;
resource_size_t fw_addr[DEVICE_COUNT_RESOURCE];
};
static LIST_HEAD(pcibios_fwaddrmappings);
static DEFINE_SPINLOCK(pcibios_fwaddrmap_lock);
static bool pcibios_fw_addr_done;
/* Must be called with 'pcibios_fwaddrmap_lock' lock held. */
static struct pcibios_fwaddrmap *pcibios_fwaddrmap_lookup(struct pci_dev *dev)
{
struct pcibios_fwaddrmap *map;
WARN_ON_SMP(!spin_is_locked(&pcibios_fwaddrmap_lock));
list_for_each_entry(map, &pcibios_fwaddrmappings, list)
if (map->dev == dev)
return map;
return NULL;
}
static void
pcibios_save_fw_addr(struct pci_dev *dev, int idx, resource_size_t fw_addr)
{
unsigned long flags;
struct pcibios_fwaddrmap *map;
if (pcibios_fw_addr_done)
return;
spin_lock_irqsave(&pcibios_fwaddrmap_lock, flags);
map = pcibios_fwaddrmap_lookup(dev);
if (!map) {
spin_unlock_irqrestore(&pcibios_fwaddrmap_lock, flags);
map = kzalloc(sizeof(*map), GFP_KERNEL);
if (!map)
return;
map->dev = pci_dev_get(dev);
map->fw_addr[idx] = fw_addr;
INIT_LIST_HEAD(&map->list);
spin_lock_irqsave(&pcibios_fwaddrmap_lock, flags);
list_add_tail(&map->list, &pcibios_fwaddrmappings);
} else
map->fw_addr[idx] = fw_addr;
spin_unlock_irqrestore(&pcibios_fwaddrmap_lock, flags);
}
resource_size_t pcibios_retrieve_fw_addr(struct pci_dev *dev, int idx)
{
unsigned long flags;
struct pcibios_fwaddrmap *map;
resource_size_t fw_addr = 0;
if (pcibios_fw_addr_done)
return 0;
spin_lock_irqsave(&pcibios_fwaddrmap_lock, flags);
map = pcibios_fwaddrmap_lookup(dev);
if (map)
fw_addr = map->fw_addr[idx];
spin_unlock_irqrestore(&pcibios_fwaddrmap_lock, flags);
return fw_addr;
}
static void __init pcibios_fw_addr_list_del(void)
{
unsigned long flags;
struct pcibios_fwaddrmap *entry, *next;
spin_lock_irqsave(&pcibios_fwaddrmap_lock, flags);
list_for_each_entry_safe(entry, next, &pcibios_fwaddrmappings, list) {
list_del(&entry->list);
pci_dev_put(entry->dev);
kfree(entry);
}
spin_unlock_irqrestore(&pcibios_fwaddrmap_lock, flags);
pcibios_fw_addr_done = true;
}
static int
skip_isa_ioresource_align(struct pci_dev *dev) {
if ((pci_probe & PCI_CAN_SKIP_ISA_ALIGN) &&
!(dev->bus->bridge_ctl & PCI_BRIDGE_CTL_ISA))
return 1;
return 0;
}
/*
* We need to avoid collisions with `mirrored' VGA ports
* and other strange ISA hardware, so we always want the
* addresses to be allocated in the 0x000-0x0ff region
* modulo 0x400.
*
* Why? Because some silly external IO cards only decode
* the low 10 bits of the IO address. The 0x00-0xff region
* is reserved for motherboard devices that decode all 16
* bits, so it's ok to allocate at, say, 0x2800-0x28ff,
* but we want to try to avoid allocating at 0x2900-0x2bff
* which might have be mirrored at 0x0100-0x03ff..
*/
resource_size_t
pcibios_align_resource(void *data, const struct resource *res,
resource_size_t size, resource_size_t align)
{
struct pci_dev *dev = data;
resource_size_t start = res->start;
if (res->flags & IORESOURCE_IO) {
if (skip_isa_ioresource_align(dev))
return start;
if (start & 0x300)
start = (start + 0x3ff) & ~0x3ff;
} else if (res->flags & IORESOURCE_MEM) {
/* The low 1MB range is reserved for ISA cards */
if (start < BIOS_END)
start = BIOS_END;
}
return start;
}
EXPORT_SYMBOL(pcibios_align_resource);
/*
* Handle resources of PCI devices. If the world were perfect, we could
* just allocate all the resource regions and do nothing more. It isn't.
* On the other hand, we cannot just re-allocate all devices, as it would
* require us to know lots of host bridge internals. So we attempt to
* keep as much of the original configuration as possible, but tweak it
* when it's found to be wrong.
*
* Known BIOS problems we have to work around:
* - I/O or memory regions not configured
* - regions configured, but not enabled in the command register
* - bogus I/O addresses above 64K used
* - expansion ROMs left enabled (this may sound harmless, but given
* the fact the PCI specs explicitly allow address decoders to be
* shared between expansion ROMs and other resource regions, it's
* at least dangerous)
* - bad resource sizes or overlaps with other regions
*
* Our solution:
* (1) Allocate resources for all buses behind PCI-to-PCI bridges.
* This gives us fixed barriers on where we can allocate.
* (2) Allocate resources for all enabled devices. If there is
* a collision, just mark the resource as unallocated. Also
* disable expansion ROMs during this step.
* (3) Try to allocate resources for disabled devices. If the
* resources were assigned correctly, everything goes well,
* if they weren't, they won't disturb allocation of other
* resources.
* (4) Assign new addresses to resources which were either
* not configured at all or misconfigured. If explicitly
* requested by the user, configure expansion ROM address
* as well.
*/
static void pcibios_allocate_bridge_resources(struct pci_dev *dev)
{
int idx;
struct resource *r;
for (idx = PCI_BRIDGE_RESOURCES; idx < PCI_NUM_RESOURCES; idx++) {
r = &dev->resource[idx];
if (!r->flags)
continue;
if (r->parent) /* Already allocated */
continue;
if (!r->start || pci_claim_bridge_resource(dev, idx) < 0) {
/*
* Something is wrong with the region.
* Invalidate the resource to prevent
* child resource allocations in this
* range.
*/
r->start = r->end = 0;
r->flags = 0;
}
}
}
static void pcibios_allocate_bus_resources(struct pci_bus *bus)
{
struct pci_bus *child;
/* Depth-First Search on bus tree */
if (bus->self)
pcibios_allocate_bridge_resources(bus->self);
list_for_each_entry(child, &bus->children, node)
pcibios_allocate_bus_resources(child);
}
struct pci_check_idx_range {
int start;
int end;
};
static void pcibios_allocate_dev_resources(struct pci_dev *dev, int pass)
{
int idx, disabled, i;
u16 command;
struct resource *r;
struct pci_check_idx_range idx_range[] = {
{ PCI_STD_RESOURCES, PCI_STD_RESOURCE_END },
#ifdef CONFIG_PCI_IOV
{ PCI_IOV_RESOURCES, PCI_IOV_RESOURCE_END },
#endif
};
pci_read_config_word(dev, PCI_COMMAND, &command);
for (i = 0; i < ARRAY_SIZE(idx_range); i++)
for (idx = idx_range[i].start; idx <= idx_range[i].end; idx++) {
r = &dev->resource[idx];
if (r->parent) /* Already allocated */
continue;
if (!r->start) /* Address not assigned at all */
continue;
if (r->flags & IORESOURCE_IO)
disabled = !(command & PCI_COMMAND_IO);
else
disabled = !(command & PCI_COMMAND_MEMORY);
if (pass == disabled) {
dev_dbg(&dev->dev,
"BAR %d: reserving %pr (d=%d, p=%d)\n",
idx, r, disabled, pass);
if (pci_claim_resource(dev, idx) < 0) {
if (r->flags & IORESOURCE_PCI_FIXED) {
dev_info(&dev->dev, "BAR %d %pR is immovable\n",
idx, r);
} else {
/* We'll assign a new address later */
pcibios_save_fw_addr(dev,
idx, r->start);
r->end -= r->start;
r->start = 0;
}
}
}
}
if (!pass) {
r = &dev->resource[PCI_ROM_RESOURCE];
if (r->flags & IORESOURCE_ROM_ENABLE) {
/* Turn the ROM off, leave the resource region,
* but keep it unregistered. */
u32 reg;
dev_dbg(&dev->dev, "disabling ROM %pR\n", r);
r->flags &= ~IORESOURCE_ROM_ENABLE;
pci_read_config_dword(dev, dev->rom_base_reg, ®);
pci_write_config_dword(dev, dev->rom_base_reg,
reg & ~PCI_ROM_ADDRESS_ENABLE);
}
}
}
static void pcibios_allocate_resources(struct pci_bus *bus, int pass)
{
struct pci_dev *dev;
struct pci_bus *child;
list_for_each_entry(dev, &bus->devices, bus_list) {
pcibios_allocate_dev_resources(dev, pass);
child = dev->subordinate;
if (child)
pcibios_allocate_resources(child, pass);
}
}
static void pcibios_allocate_dev_rom_resource(struct pci_dev *dev)
{
struct resource *r;
/*
* Try to use BIOS settings for ROMs, otherwise let
* pci_assign_unassigned_resources() allocate the new
* addresses.
*/
r = &dev->resource[PCI_ROM_RESOURCE];
if (!r->flags || !r->start)
return;
if (r->parent) /* Already allocated */
return;
if (pci_claim_resource(dev, PCI_ROM_RESOURCE) < 0) {
r->end -= r->start;
r->start = 0;
}
}
static void pcibios_allocate_rom_resources(struct pci_bus *bus)
{
struct pci_dev *dev;
struct pci_bus *child;
list_for_each_entry(dev, &bus->devices, bus_list) {
pcibios_allocate_dev_rom_resource(dev);
child = dev->subordinate;
if (child)
pcibios_allocate_rom_resources(child);
}
}
static int __init pcibios_assign_resources(void)
{
struct pci_bus *bus;
if (!(pci_probe & PCI_ASSIGN_ROMS))
list_for_each_entry(bus, &pci_root_buses, node)
pcibios_allocate_rom_resources(bus);
pci_assign_unassigned_resources();
pcibios_fw_addr_list_del();
return 0;
}
/**
* called in fs_initcall (one below subsys_initcall),
* give a chance for motherboard reserve resources
*/
fs_initcall(pcibios_assign_resources);
void pcibios_resource_survey_bus(struct pci_bus *bus)
{
dev_printk(KERN_DEBUG, &bus->dev, "Allocating resources\n");
pcibios_allocate_bus_resources(bus);
pcibios_allocate_resources(bus, 0);
pcibios_allocate_resources(bus, 1);
if (!(pci_probe & PCI_ASSIGN_ROMS))
pcibios_allocate_rom_resources(bus);
}
void __init pcibios_resource_survey(void)
{
struct pci_bus *bus;
DBG("PCI: Allocating resources\n");
list_for_each_entry(bus, &pci_root_buses, node)
pcibios_allocate_bus_resources(bus);
list_for_each_entry(bus, &pci_root_buses, node)
pcibios_allocate_resources(bus, 0);
list_for_each_entry(bus, &pci_root_buses, node)
pcibios_allocate_resources(bus, 1);
e820_reserve_resources_late();
/*
* Insert the IO APIC resources after PCI initialization has
* occurred to handle IO APICS that are mapped in on a BAR in
* PCI space, but before trying to assign unassigned pci res.
*/
ioapic_insert_resources();
}
static const struct vm_operations_struct pci_mmap_ops = {
.access = generic_access_phys,
};
int pci_mmap_page_range(struct pci_dev *dev, struct vm_area_struct *vma,
enum pci_mmap_state mmap_state, int write_combine)
{
unsigned long prot;
/* I/O space cannot be accessed via normal processor loads and
* stores on this platform.
*/
if (mmap_state == pci_mmap_io)
return -EINVAL;
prot = pgprot_val(vma->vm_page_prot);
/*
* Return error if pat is not enabled and write_combine is requested.
* Caller can followup with UC MINUS request and add a WC mtrr if there
* is a free mtrr slot.
*/
if (!pat_enabled() && write_combine)
return -EINVAL;
if (pat_enabled() && write_combine)
prot |= cachemode2protval(_PAGE_CACHE_MODE_WC);
else if (pat_enabled() || boot_cpu_data.x86 > 3)
/*
* ioremap() and ioremap_nocache() defaults to UC MINUS for now.
* To avoid attribute conflicts, request UC MINUS here
* as well.
*/
prot |= cachemode2protval(_PAGE_CACHE_MODE_UC_MINUS);
vma->vm_page_prot = __pgprot(prot);
if (io_remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff,
vma->vm_end - vma->vm_start,
vma->vm_page_prot))
return -EAGAIN;
vma->vm_ops = &pci_mmap_ops;
return 0;
}
| gpl-2.0 |
abenagiel/android_kernel_fih_msm7x30 | arch/arm/mach-sa1100/cpu-sa1100.c | 1634 | 7866 | /*
* cpu-sa1100.c: clock scaling for the SA1100
*
* Copyright (C) 2000 2001, The Delft University of Technology
*
* Authors:
* - Johan Pouwelse (J.A.Pouwelse@its.tudelft.nl): initial version
* - Erik Mouw (J.A.K.Mouw@its.tudelft.nl):
* - major rewrite for linux-2.3.99
* - rewritten for the more generic power management scheme in
* linux-2.4.5-rmk1
*
* This software has been developed while working on the LART
* computing board (http://www.lartmaker.nl/), which is
* sponsored by the Mobile Multi-media Communications
* (http://www.mmc.tudelft.nl/) and Ubiquitous Communications
* (http://www.ubicom.tudelft.nl/) projects.
*
* The authors can be reached at:
*
* Erik Mouw
* Information and Communication Theory Group
* Faculty of Information Technology and Systems
* Delft University of Technology
* P.O. Box 5031
* 2600 GA Delft
* The Netherlands
*
*
* 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
*
*
* Theory of operations
* ====================
*
* Clock scaling can be used to lower the power consumption of the CPU
* core. This will give you a somewhat longer running time.
*
* The SA-1100 has a single register to change the core clock speed:
*
* PPCR 0x90020014 PLL config
*
* However, the DRAM timings are closely related to the core clock
* speed, so we need to change these, too. The used registers are:
*
* MDCNFG 0xA0000000 DRAM config
* MDCAS0 0xA0000004 Access waveform
* MDCAS1 0xA0000008 Access waveform
* MDCAS2 0xA000000C Access waveform
*
* Care must be taken to change the DRAM parameters the correct way,
* because otherwise the DRAM becomes unusable and the kernel will
* crash.
*
* The simple solution to avoid a kernel crash is to put the actual
* clock change in ROM and jump to that code from the kernel. The main
* disadvantage is that the ROM has to be modified, which is not
* possible on all SA-1100 platforms. Another disadvantage is that
* jumping to ROM makes clock switching unecessary complicated.
*
* The idea behind this driver is that the memory configuration can be
* changed while running from DRAM (even with interrupts turned on!)
* as long as all re-configuration steps yield a valid DRAM
* configuration. The advantages are clear: it will run on all SA-1100
* platforms, and the code is very simple.
*
* If you really want to understand what is going on in
* sa1100_update_dram_timings(), you'll have to read sections 8.2,
* 9.5.7.3, and 10.2 from the "Intel StrongARM SA-1100 Microprocessor
* Developers Manual" (available for free from Intel).
*
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/cpufreq.h>
#include <asm/cputype.h>
#include <mach/hardware.h>
#include "generic.h"
typedef struct {
int speed;
u32 mdcnfg;
u32 mdcas0;
u32 mdcas1;
u32 mdcas2;
} sa1100_dram_regs_t;
static struct cpufreq_driver sa1100_driver;
static sa1100_dram_regs_t sa1100_dram_settings[] =
{
/* speed, mdcnfg, mdcas0, mdcas1, mdcas2 clock frequency */
{ 59000, 0x00dc88a3, 0xcccccccf, 0xfffffffc, 0xffffffff }, /* 59.0 MHz */
{ 73700, 0x011490a3, 0xcccccccf, 0xfffffffc, 0xffffffff }, /* 73.7 MHz */
{ 88500, 0x014e90a3, 0xcccccccf, 0xfffffffc, 0xffffffff }, /* 88.5 MHz */
{ 103200, 0x01889923, 0xcccccccf, 0xfffffffc, 0xffffffff }, /* 103.2 MHz */
{ 118000, 0x01c29923, 0x9999998f, 0xfffffff9, 0xffffffff }, /* 118.0 MHz */
{ 132700, 0x01fb2123, 0x9999998f, 0xfffffff9, 0xffffffff }, /* 132.7 MHz */
{ 147500, 0x02352123, 0x3333330f, 0xfffffff3, 0xffffffff }, /* 147.5 MHz */
{ 162200, 0x026b29a3, 0x38e38e1f, 0xfff8e38e, 0xffffffff }, /* 162.2 MHz */
{ 176900, 0x02a329a3, 0x71c71c1f, 0xfff1c71c, 0xffffffff }, /* 176.9 MHz */
{ 191700, 0x02dd31a3, 0xe38e383f, 0xffe38e38, 0xffffffff }, /* 191.7 MHz */
{ 206400, 0x03153223, 0xc71c703f, 0xffc71c71, 0xffffffff }, /* 206.4 MHz */
{ 221200, 0x034fba23, 0xc71c703f, 0xffc71c71, 0xffffffff }, /* 221.2 MHz */
{ 235900, 0x03853a23, 0xe1e1e07f, 0xe1e1e1e1, 0xffffffe1 }, /* 235.9 MHz */
{ 250700, 0x03bf3aa3, 0xc3c3c07f, 0xc3c3c3c3, 0xffffffc3 }, /* 250.7 MHz */
{ 265400, 0x03f7c2a3, 0xc3c3c07f, 0xc3c3c3c3, 0xffffffc3 }, /* 265.4 MHz */
{ 280200, 0x0431c2a3, 0x878780ff, 0x87878787, 0xffffff87 }, /* 280.2 MHz */
{ 0, 0, 0, 0, 0 } /* last entry */
};
static void sa1100_update_dram_timings(int current_speed, int new_speed)
{
sa1100_dram_regs_t *settings = sa1100_dram_settings;
/* find speed */
while (settings->speed != 0) {
if(new_speed == settings->speed)
break;
settings++;
}
if (settings->speed == 0) {
panic("%s: couldn't find dram setting for speed %d\n",
__func__, new_speed);
}
/* No risk, no fun: run with interrupts on! */
if (new_speed > current_speed) {
/* We're going FASTER, so first relax the memory
* timings before changing the core frequency
*/
/* Half the memory access clock */
MDCNFG |= MDCNFG_CDB2;
/* The order of these statements IS important, keep 8
* pulses!!
*/
MDCAS2 = settings->mdcas2;
MDCAS1 = settings->mdcas1;
MDCAS0 = settings->mdcas0;
MDCNFG = settings->mdcnfg;
} else {
/* We're going SLOWER: first decrease the core
* frequency and then tighten the memory settings.
*/
/* Half the memory access clock */
MDCNFG |= MDCNFG_CDB2;
/* The order of these statements IS important, keep 8
* pulses!!
*/
MDCAS0 = settings->mdcas0;
MDCAS1 = settings->mdcas1;
MDCAS2 = settings->mdcas2;
MDCNFG = settings->mdcnfg;
}
}
static int sa1100_target(struct cpufreq_policy *policy,
unsigned int target_freq,
unsigned int relation)
{
unsigned int cur = sa11x0_getspeed(0);
unsigned int new_ppcr;
struct cpufreq_freqs freqs;
switch(relation){
case CPUFREQ_RELATION_L:
new_ppcr = sa11x0_freq_to_ppcr(target_freq);
if (sa11x0_ppcr_to_freq(new_ppcr) > policy->max)
new_ppcr--;
break;
case CPUFREQ_RELATION_H:
new_ppcr = sa11x0_freq_to_ppcr(target_freq);
if ((sa11x0_ppcr_to_freq(new_ppcr) > target_freq) &&
(sa11x0_ppcr_to_freq(new_ppcr - 1) >= policy->min))
new_ppcr--;
break;
}
freqs.old = cur;
freqs.new = sa11x0_ppcr_to_freq(new_ppcr);
freqs.cpu = 0;
cpufreq_notify_transition(&freqs, CPUFREQ_PRECHANGE);
if (freqs.new > cur)
sa1100_update_dram_timings(cur, freqs.new);
PPCR = new_ppcr;
if (freqs.new < cur)
sa1100_update_dram_timings(cur, freqs.new);
cpufreq_notify_transition(&freqs, CPUFREQ_POSTCHANGE);
return 0;
}
static int __init sa1100_cpu_init(struct cpufreq_policy *policy)
{
if (policy->cpu != 0)
return -EINVAL;
policy->cur = policy->min = policy->max = sa11x0_getspeed(0);
policy->cpuinfo.min_freq = 59000;
policy->cpuinfo.max_freq = 287000;
policy->cpuinfo.transition_latency = CPUFREQ_ETERNAL;
return 0;
}
static struct cpufreq_driver sa1100_driver = {
.flags = CPUFREQ_STICKY,
.verify = sa11x0_verify_speed,
.target = sa1100_target,
.get = sa11x0_getspeed,
.init = sa1100_cpu_init,
.name = "sa1100",
};
static int __init sa1100_dram_init(void)
{
if (cpu_is_sa1100())
return cpufreq_register_driver(&sa1100_driver);
else
return -ENODEV;
}
arch_initcall(sa1100_dram_init);
| gpl-2.0 |
basr/Hammerhead | arch/s390/kernel/processor.c | 1890 | 2273 | /*
* arch/s390/kernel/processor.c
*
* Copyright IBM Corp. 2008
* Author(s): Martin Schwidefsky (schwidefsky@de.ibm.com)
*/
#define KMSG_COMPONENT "cpu"
#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/smp.h>
#include <linux/seq_file.h>
#include <linux/delay.h>
#include <linux/cpu.h>
#include <asm/elf.h>
#include <asm/lowcore.h>
#include <asm/param.h>
static DEFINE_PER_CPU(struct cpuid, cpu_id);
/*
* cpu_init - initializes state that is per-CPU.
*/
void __cpuinit cpu_init(void)
{
struct cpuid *id = &per_cpu(cpu_id, smp_processor_id());
struct s390_idle_data *idle = &__get_cpu_var(s390_idle);
get_cpu_id(id);
atomic_inc(&init_mm.mm_count);
current->active_mm = &init_mm;
BUG_ON(current->mm);
enter_lazy_tlb(&init_mm, current);
memset(idle, 0, sizeof(*idle));
}
/*
* show_cpuinfo - Get information on one CPU for use by procfs.
*/
static int show_cpuinfo(struct seq_file *m, void *v)
{
static const char *hwcap_str[10] = {
"esan3", "zarch", "stfle", "msa", "ldisp", "eimm", "dfp",
"edat", "etf3eh", "highgprs"
};
unsigned long n = (unsigned long) v - 1;
int i;
if (!n) {
s390_adjust_jiffies();
seq_printf(m, "vendor_id : IBM/S390\n"
"# processors : %i\n"
"bogomips per cpu: %lu.%02lu\n",
num_online_cpus(), loops_per_jiffy/(500000/HZ),
(loops_per_jiffy/(5000/HZ))%100);
seq_puts(m, "features\t: ");
for (i = 0; i < 10; i++)
if (hwcap_str[i] && (elf_hwcap & (1UL << i)))
seq_printf(m, "%s ", hwcap_str[i]);
seq_puts(m, "\n");
}
get_online_cpus();
if (cpu_online(n)) {
struct cpuid *id = &per_cpu(cpu_id, n);
seq_printf(m, "processor %li: "
"version = %02X, "
"identification = %06X, "
"machine = %04X\n",
n, id->version, id->ident, id->machine);
}
put_online_cpus();
return 0;
}
static void *c_start(struct seq_file *m, loff_t *pos)
{
return *pos < nr_cpu_ids ? (void *)((unsigned long) *pos + 1) : NULL;
}
static void *c_next(struct seq_file *m, void *v, loff_t *pos)
{
++*pos;
return c_start(m, pos);
}
static void c_stop(struct seq_file *m, void *v)
{
}
const struct seq_operations cpuinfo_op = {
.start = c_start,
.next = c_next,
.stop = c_stop,
.show = show_cpuinfo,
};
| gpl-2.0 |
vlw/android_kernel_samsung_msm8916_A3 | drivers/net/ethernet/intel/ixgbe/ixgbe_sriov.c | 2146 | 34580 | /*******************************************************************************
Intel 10 Gigabit PCI Express Linux driver
Copyright(c) 1999 - 2013 Intel Corporation.
This program is free software; you can redistribute it and/or modify it
under the terms and conditions of the GNU General Public License,
version 2, as published by the Free Software Foundation.
This program is distributed in the hope it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
Contact Information:
e1000-devel Mailing List <e1000-devel@lists.sourceforge.net>
Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*******************************************************************************/
#include <linux/types.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/netdevice.h>
#include <linux/vmalloc.h>
#include <linux/string.h>
#include <linux/in.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/ipv6.h>
#ifdef NETIF_F_HW_VLAN_CTAG_TX
#include <linux/if_vlan.h>
#endif
#include "ixgbe.h"
#include "ixgbe_type.h"
#include "ixgbe_sriov.h"
#ifdef CONFIG_PCI_IOV
static int __ixgbe_enable_sriov(struct ixgbe_adapter *adapter)
{
struct ixgbe_hw *hw = &adapter->hw;
int num_vf_macvlans, i;
struct vf_macvlans *mv_list;
adapter->flags |= IXGBE_FLAG_SRIOV_ENABLED;
e_info(probe, "SR-IOV enabled with %d VFs\n", adapter->num_vfs);
/* Enable VMDq flag so device will be set in VM mode */
adapter->flags |= IXGBE_FLAG_VMDQ_ENABLED;
if (!adapter->ring_feature[RING_F_VMDQ].limit)
adapter->ring_feature[RING_F_VMDQ].limit = 1;
adapter->ring_feature[RING_F_VMDQ].offset = adapter->num_vfs;
num_vf_macvlans = hw->mac.num_rar_entries -
(IXGBE_MAX_PF_MACVLANS + 1 + adapter->num_vfs);
adapter->mv_list = mv_list = kcalloc(num_vf_macvlans,
sizeof(struct vf_macvlans),
GFP_KERNEL);
if (mv_list) {
/* Initialize list of VF macvlans */
INIT_LIST_HEAD(&adapter->vf_mvs.l);
for (i = 0; i < num_vf_macvlans; i++) {
mv_list->vf = -1;
mv_list->free = true;
mv_list->rar_entry = hw->mac.num_rar_entries -
(i + adapter->num_vfs + 1);
list_add(&mv_list->l, &adapter->vf_mvs.l);
mv_list++;
}
}
/* Initialize default switching mode VEB */
IXGBE_WRITE_REG(hw, IXGBE_PFDTXGSWC, IXGBE_PFDTXGSWC_VT_LBEN);
adapter->flags2 |= IXGBE_FLAG2_BRIDGE_MODE_VEB;
/* If call to enable VFs succeeded then allocate memory
* for per VF control structures.
*/
adapter->vfinfo =
kcalloc(adapter->num_vfs,
sizeof(struct vf_data_storage), GFP_KERNEL);
if (adapter->vfinfo) {
/* limit trafffic classes based on VFs enabled */
if ((adapter->hw.mac.type == ixgbe_mac_82599EB) &&
(adapter->num_vfs < 16)) {
adapter->dcb_cfg.num_tcs.pg_tcs = MAX_TRAFFIC_CLASS;
adapter->dcb_cfg.num_tcs.pfc_tcs = MAX_TRAFFIC_CLASS;
} else if (adapter->num_vfs < 32) {
adapter->dcb_cfg.num_tcs.pg_tcs = 4;
adapter->dcb_cfg.num_tcs.pfc_tcs = 4;
} else {
adapter->dcb_cfg.num_tcs.pg_tcs = 1;
adapter->dcb_cfg.num_tcs.pfc_tcs = 1;
}
/* We do not support RSS w/ SR-IOV */
adapter->ring_feature[RING_F_RSS].limit = 1;
/* Disable RSC when in SR-IOV mode */
adapter->flags2 &= ~(IXGBE_FLAG2_RSC_CAPABLE |
IXGBE_FLAG2_RSC_ENABLED);
/* enable spoof checking for all VFs */
for (i = 0; i < adapter->num_vfs; i++)
adapter->vfinfo[i].spoofchk_enabled = true;
return 0;
}
return -ENOMEM;
}
/* Note this function is called when the user wants to enable SR-IOV
* VFs using the now deprecated module parameter
*/
void ixgbe_enable_sriov(struct ixgbe_adapter *adapter)
{
int pre_existing_vfs = 0;
pre_existing_vfs = pci_num_vf(adapter->pdev);
if (!pre_existing_vfs && !adapter->num_vfs)
return;
if (!pre_existing_vfs)
dev_warn(&adapter->pdev->dev,
"Enabling SR-IOV VFs using the module parameter is deprecated - please use the pci sysfs interface.\n");
/* If there are pre-existing VFs then we have to force
* use of that many - over ride any module parameter value.
* This may result from the user unloading the PF driver
* while VFs were assigned to guest VMs or because the VFs
* have been created via the new PCI SR-IOV sysfs interface.
*/
if (pre_existing_vfs) {
adapter->num_vfs = pre_existing_vfs;
dev_warn(&adapter->pdev->dev,
"Virtual Functions already enabled for this device - Please reload all VF drivers to avoid spoofed packet errors\n");
} else {
int err;
/*
* The 82599 supports up to 64 VFs per physical function
* but this implementation limits allocation to 63 so that
* basic networking resources are still available to the
* physical function. If the user requests greater thn
* 63 VFs then it is an error - reset to default of zero.
*/
adapter->num_vfs = min_t(unsigned int, adapter->num_vfs, 63);
err = pci_enable_sriov(adapter->pdev, adapter->num_vfs);
if (err) {
e_err(probe, "Failed to enable PCI sriov: %d\n", err);
adapter->num_vfs = 0;
return;
}
}
if (!__ixgbe_enable_sriov(adapter))
return;
/* If we have gotten to this point then there is no memory available
* to manage the VF devices - print message and bail.
*/
e_err(probe, "Unable to allocate memory for VF Data Storage - "
"SRIOV disabled\n");
ixgbe_disable_sriov(adapter);
}
static bool ixgbe_vfs_are_assigned(struct ixgbe_adapter *adapter)
{
struct pci_dev *pdev = adapter->pdev;
struct pci_dev *vfdev;
int dev_id;
switch (adapter->hw.mac.type) {
case ixgbe_mac_82599EB:
dev_id = IXGBE_DEV_ID_82599_VF;
break;
case ixgbe_mac_X540:
dev_id = IXGBE_DEV_ID_X540_VF;
break;
default:
return false;
}
/* loop through all the VFs to see if we own any that are assigned */
vfdev = pci_get_device(PCI_VENDOR_ID_INTEL, dev_id, NULL);
while (vfdev) {
/* if we don't own it we don't care */
if (vfdev->is_virtfn && vfdev->physfn == pdev) {
/* if it is assigned we cannot release it */
if (vfdev->dev_flags & PCI_DEV_FLAGS_ASSIGNED)
return true;
}
vfdev = pci_get_device(PCI_VENDOR_ID_INTEL, dev_id, vfdev);
}
return false;
}
#endif /* #ifdef CONFIG_PCI_IOV */
int ixgbe_disable_sriov(struct ixgbe_adapter *adapter)
{
struct ixgbe_hw *hw = &adapter->hw;
u32 gpie;
u32 vmdctl;
int rss;
/* set num VFs to 0 to prevent access to vfinfo */
adapter->num_vfs = 0;
/* free VF control structures */
kfree(adapter->vfinfo);
adapter->vfinfo = NULL;
/* free macvlan list */
kfree(adapter->mv_list);
adapter->mv_list = NULL;
/* if SR-IOV is already disabled then there is nothing to do */
if (!(adapter->flags & IXGBE_FLAG_SRIOV_ENABLED))
return 0;
#ifdef CONFIG_PCI_IOV
/*
* If our VFs are assigned we cannot shut down SR-IOV
* without causing issues, so just leave the hardware
* available but disabled
*/
if (ixgbe_vfs_are_assigned(adapter)) {
e_dev_warn("Unloading driver while VFs are assigned - VFs will not be deallocated\n");
return -EPERM;
}
/* disable iov and allow time for transactions to clear */
pci_disable_sriov(adapter->pdev);
#endif
/* turn off device IOV mode */
IXGBE_WRITE_REG(hw, IXGBE_GCR_EXT, 0);
gpie = IXGBE_READ_REG(hw, IXGBE_GPIE);
gpie &= ~IXGBE_GPIE_VTMODE_MASK;
IXGBE_WRITE_REG(hw, IXGBE_GPIE, gpie);
/* set default pool back to 0 */
vmdctl = IXGBE_READ_REG(hw, IXGBE_VT_CTL);
vmdctl &= ~IXGBE_VT_CTL_POOL_MASK;
IXGBE_WRITE_REG(hw, IXGBE_VT_CTL, vmdctl);
IXGBE_WRITE_FLUSH(hw);
/* Disable VMDq flag so device will be set in VM mode */
if (adapter->ring_feature[RING_F_VMDQ].limit == 1)
adapter->flags &= ~IXGBE_FLAG_VMDQ_ENABLED;
adapter->ring_feature[RING_F_VMDQ].offset = 0;
rss = min_t(int, IXGBE_MAX_RSS_INDICES, num_online_cpus());
adapter->ring_feature[RING_F_RSS].limit = rss;
/* take a breather then clean up driver data */
msleep(100);
adapter->flags &= ~IXGBE_FLAG_SRIOV_ENABLED;
return 0;
}
static int ixgbe_pci_sriov_enable(struct pci_dev *dev, int num_vfs)
{
#ifdef CONFIG_PCI_IOV
struct ixgbe_adapter *adapter = pci_get_drvdata(dev);
int err = 0;
int i;
int pre_existing_vfs = pci_num_vf(dev);
if (pre_existing_vfs && pre_existing_vfs != num_vfs)
err = ixgbe_disable_sriov(adapter);
else if (pre_existing_vfs && pre_existing_vfs == num_vfs)
goto out;
if (err)
goto err_out;
/* While the SR-IOV capability structure reports total VFs to be
* 64 we limit the actual number that can be allocated to 63 so
* that some transmit/receive resources can be reserved to the
* PF. The PCI bus driver already checks for other values out of
* range.
*/
if (num_vfs > 63) {
err = -EPERM;
goto err_out;
}
adapter->num_vfs = num_vfs;
err = __ixgbe_enable_sriov(adapter);
if (err)
goto err_out;
for (i = 0; i < adapter->num_vfs; i++)
ixgbe_vf_configuration(dev, (i | 0x10000000));
err = pci_enable_sriov(dev, num_vfs);
if (err) {
e_dev_warn("Failed to enable PCI sriov: %d\n", err);
goto err_out;
}
ixgbe_sriov_reinit(adapter);
out:
return num_vfs;
err_out:
return err;
#endif
return 0;
}
static int ixgbe_pci_sriov_disable(struct pci_dev *dev)
{
struct ixgbe_adapter *adapter = pci_get_drvdata(dev);
int err;
u32 current_flags = adapter->flags;
err = ixgbe_disable_sriov(adapter);
/* Only reinit if no error and state changed */
if (!err && current_flags != adapter->flags) {
/* ixgbe_disable_sriov() doesn't clear VMDQ flag */
adapter->flags &= ~IXGBE_FLAG_VMDQ_ENABLED;
#ifdef CONFIG_PCI_IOV
ixgbe_sriov_reinit(adapter);
#endif
}
return err;
}
int ixgbe_pci_sriov_configure(struct pci_dev *dev, int num_vfs)
{
if (num_vfs == 0)
return ixgbe_pci_sriov_disable(dev);
else
return ixgbe_pci_sriov_enable(dev, num_vfs);
}
static int ixgbe_set_vf_multicasts(struct ixgbe_adapter *adapter,
u32 *msgbuf, u32 vf)
{
int entries = (msgbuf[0] & IXGBE_VT_MSGINFO_MASK)
>> IXGBE_VT_MSGINFO_SHIFT;
u16 *hash_list = (u16 *)&msgbuf[1];
struct vf_data_storage *vfinfo = &adapter->vfinfo[vf];
struct ixgbe_hw *hw = &adapter->hw;
int i;
u32 vector_bit;
u32 vector_reg;
u32 mta_reg;
/* only so many hash values supported */
entries = min(entries, IXGBE_MAX_VF_MC_ENTRIES);
/*
* salt away the number of multi cast addresses assigned
* to this VF for later use to restore when the PF multi cast
* list changes
*/
vfinfo->num_vf_mc_hashes = entries;
/*
* VFs are limited to using the MTA hash table for their multicast
* addresses
*/
for (i = 0; i < entries; i++) {
vfinfo->vf_mc_hashes[i] = hash_list[i];
}
for (i = 0; i < vfinfo->num_vf_mc_hashes; i++) {
vector_reg = (vfinfo->vf_mc_hashes[i] >> 5) & 0x7F;
vector_bit = vfinfo->vf_mc_hashes[i] & 0x1F;
mta_reg = IXGBE_READ_REG(hw, IXGBE_MTA(vector_reg));
mta_reg |= (1 << vector_bit);
IXGBE_WRITE_REG(hw, IXGBE_MTA(vector_reg), mta_reg);
}
return 0;
}
static void ixgbe_restore_vf_macvlans(struct ixgbe_adapter *adapter)
{
struct ixgbe_hw *hw = &adapter->hw;
struct list_head *pos;
struct vf_macvlans *entry;
list_for_each(pos, &adapter->vf_mvs.l) {
entry = list_entry(pos, struct vf_macvlans, l);
if (!entry->free)
hw->mac.ops.set_rar(hw, entry->rar_entry,
entry->vf_macvlan,
entry->vf, IXGBE_RAH_AV);
}
}
void ixgbe_restore_vf_multicasts(struct ixgbe_adapter *adapter)
{
struct ixgbe_hw *hw = &adapter->hw;
struct vf_data_storage *vfinfo;
int i, j;
u32 vector_bit;
u32 vector_reg;
u32 mta_reg;
for (i = 0; i < adapter->num_vfs; i++) {
vfinfo = &adapter->vfinfo[i];
for (j = 0; j < vfinfo->num_vf_mc_hashes; j++) {
hw->addr_ctrl.mta_in_use++;
vector_reg = (vfinfo->vf_mc_hashes[j] >> 5) & 0x7F;
vector_bit = vfinfo->vf_mc_hashes[j] & 0x1F;
mta_reg = IXGBE_READ_REG(hw, IXGBE_MTA(vector_reg));
mta_reg |= (1 << vector_bit);
IXGBE_WRITE_REG(hw, IXGBE_MTA(vector_reg), mta_reg);
}
}
/* Restore any VF macvlans */
ixgbe_restore_vf_macvlans(adapter);
}
static int ixgbe_set_vf_vlan(struct ixgbe_adapter *adapter, int add, int vid,
u32 vf)
{
/* VLAN 0 is a special case, don't allow it to be removed */
if (!vid && !add)
return 0;
return adapter->hw.mac.ops.set_vfta(&adapter->hw, vid, vf, (bool)add);
}
static s32 ixgbe_set_vf_lpe(struct ixgbe_adapter *adapter, u32 *msgbuf, u32 vf)
{
struct ixgbe_hw *hw = &adapter->hw;
int max_frame = msgbuf[1];
u32 max_frs;
/*
* For 82599EB we have to keep all PFs and VFs operating with
* the same max_frame value in order to avoid sending an oversize
* frame to a VF. In order to guarantee this is handled correctly
* for all cases we have several special exceptions to take into
* account before we can enable the VF for receive
*/
if (adapter->hw.mac.type == ixgbe_mac_82599EB) {
struct net_device *dev = adapter->netdev;
int pf_max_frame = dev->mtu + ETH_HLEN;
u32 reg_offset, vf_shift, vfre;
s32 err = 0;
#ifdef CONFIG_FCOE
if (dev->features & NETIF_F_FCOE_MTU)
pf_max_frame = max_t(int, pf_max_frame,
IXGBE_FCOE_JUMBO_FRAME_SIZE);
#endif /* CONFIG_FCOE */
switch (adapter->vfinfo[vf].vf_api) {
case ixgbe_mbox_api_11:
/*
* Version 1.1 supports jumbo frames on VFs if PF has
* jumbo frames enabled which means legacy VFs are
* disabled
*/
if (pf_max_frame > ETH_FRAME_LEN)
break;
default:
/*
* If the PF or VF are running w/ jumbo frames enabled
* we need to shut down the VF Rx path as we cannot
* support jumbo frames on legacy VFs
*/
if ((pf_max_frame > ETH_FRAME_LEN) ||
(max_frame > (ETH_FRAME_LEN + ETH_FCS_LEN)))
err = -EINVAL;
break;
}
/* determine VF receive enable location */
vf_shift = vf % 32;
reg_offset = vf / 32;
/* enable or disable receive depending on error */
vfre = IXGBE_READ_REG(hw, IXGBE_VFRE(reg_offset));
if (err)
vfre &= ~(1 << vf_shift);
else
vfre |= 1 << vf_shift;
IXGBE_WRITE_REG(hw, IXGBE_VFRE(reg_offset), vfre);
if (err) {
e_err(drv, "VF max_frame %d out of range\n", max_frame);
return err;
}
}
/* MTU < 68 is an error and causes problems on some kernels */
if (max_frame > IXGBE_MAX_JUMBO_FRAME_SIZE) {
e_err(drv, "VF max_frame %d out of range\n", max_frame);
return -EINVAL;
}
/* pull current max frame size from hardware */
max_frs = IXGBE_READ_REG(hw, IXGBE_MAXFRS);
max_frs &= IXGBE_MHADD_MFS_MASK;
max_frs >>= IXGBE_MHADD_MFS_SHIFT;
if (max_frs < max_frame) {
max_frs = max_frame << IXGBE_MHADD_MFS_SHIFT;
IXGBE_WRITE_REG(hw, IXGBE_MAXFRS, max_frs);
}
e_info(hw, "VF requests change max MTU to %d\n", max_frame);
return 0;
}
static void ixgbe_set_vmolr(struct ixgbe_hw *hw, u32 vf, bool aupe)
{
u32 vmolr = IXGBE_READ_REG(hw, IXGBE_VMOLR(vf));
vmolr |= (IXGBE_VMOLR_ROMPE |
IXGBE_VMOLR_BAM);
if (aupe)
vmolr |= IXGBE_VMOLR_AUPE;
else
vmolr &= ~IXGBE_VMOLR_AUPE;
IXGBE_WRITE_REG(hw, IXGBE_VMOLR(vf), vmolr);
}
static void ixgbe_clear_vmvir(struct ixgbe_adapter *adapter, u32 vf)
{
struct ixgbe_hw *hw = &adapter->hw;
IXGBE_WRITE_REG(hw, IXGBE_VMVIR(vf), 0);
}
static inline void ixgbe_vf_reset_event(struct ixgbe_adapter *adapter, u32 vf)
{
struct ixgbe_hw *hw = &adapter->hw;
struct vf_data_storage *vfinfo = &adapter->vfinfo[vf];
int rar_entry = hw->mac.num_rar_entries - (vf + 1);
u8 num_tcs = netdev_get_num_tc(adapter->netdev);
/* add PF assigned VLAN or VLAN 0 */
ixgbe_set_vf_vlan(adapter, true, vfinfo->pf_vlan, vf);
/* reset offloads to defaults */
ixgbe_set_vmolr(hw, vf, !vfinfo->pf_vlan);
/* set outgoing tags for VFs */
if (!vfinfo->pf_vlan && !vfinfo->pf_qos && !num_tcs) {
ixgbe_clear_vmvir(adapter, vf);
} else {
if (vfinfo->pf_qos || !num_tcs)
ixgbe_set_vmvir(adapter, vfinfo->pf_vlan,
vfinfo->pf_qos, vf);
else
ixgbe_set_vmvir(adapter, vfinfo->pf_vlan,
adapter->default_up, vf);
if (vfinfo->spoofchk_enabled)
hw->mac.ops.set_vlan_anti_spoofing(hw, true, vf);
}
/* reset multicast table array for vf */
adapter->vfinfo[vf].num_vf_mc_hashes = 0;
/* Flush and reset the mta with the new values */
ixgbe_set_rx_mode(adapter->netdev);
hw->mac.ops.clear_rar(hw, rar_entry);
/* reset VF api back to unknown */
adapter->vfinfo[vf].vf_api = ixgbe_mbox_api_10;
}
static int ixgbe_set_vf_mac(struct ixgbe_adapter *adapter,
int vf, unsigned char *mac_addr)
{
struct ixgbe_hw *hw = &adapter->hw;
int rar_entry = hw->mac.num_rar_entries - (vf + 1);
memcpy(adapter->vfinfo[vf].vf_mac_addresses, mac_addr, 6);
hw->mac.ops.set_rar(hw, rar_entry, mac_addr, vf, IXGBE_RAH_AV);
return 0;
}
static int ixgbe_set_vf_macvlan(struct ixgbe_adapter *adapter,
int vf, int index, unsigned char *mac_addr)
{
struct ixgbe_hw *hw = &adapter->hw;
struct list_head *pos;
struct vf_macvlans *entry;
if (index <= 1) {
list_for_each(pos, &adapter->vf_mvs.l) {
entry = list_entry(pos, struct vf_macvlans, l);
if (entry->vf == vf) {
entry->vf = -1;
entry->free = true;
entry->is_macvlan = false;
hw->mac.ops.clear_rar(hw, entry->rar_entry);
}
}
}
/*
* If index was zero then we were asked to clear the uc list
* for the VF. We're done.
*/
if (!index)
return 0;
entry = NULL;
list_for_each(pos, &adapter->vf_mvs.l) {
entry = list_entry(pos, struct vf_macvlans, l);
if (entry->free)
break;
}
/*
* If we traversed the entire list and didn't find a free entry
* then we're out of space on the RAR table. Also entry may
* be NULL because the original memory allocation for the list
* failed, which is not fatal but does mean we can't support
* VF requests for MACVLAN because we couldn't allocate
* memory for the list management required.
*/
if (!entry || !entry->free)
return -ENOSPC;
entry->free = false;
entry->is_macvlan = true;
entry->vf = vf;
memcpy(entry->vf_macvlan, mac_addr, ETH_ALEN);
hw->mac.ops.set_rar(hw, entry->rar_entry, mac_addr, vf, IXGBE_RAH_AV);
return 0;
}
int ixgbe_vf_configuration(struct pci_dev *pdev, unsigned int event_mask)
{
unsigned char vf_mac_addr[6];
struct ixgbe_adapter *adapter = pci_get_drvdata(pdev);
unsigned int vfn = (event_mask & 0x3f);
bool enable = ((event_mask & 0x10000000U) != 0);
if (enable) {
eth_zero_addr(vf_mac_addr);
memcpy(adapter->vfinfo[vfn].vf_mac_addresses, vf_mac_addr, 6);
}
return 0;
}
static int ixgbe_vf_reset_msg(struct ixgbe_adapter *adapter, u32 vf)
{
struct ixgbe_hw *hw = &adapter->hw;
unsigned char *vf_mac = adapter->vfinfo[vf].vf_mac_addresses;
u32 reg, msgbuf[4];
u32 reg_offset, vf_shift;
u8 *addr = (u8 *)(&msgbuf[1]);
e_info(probe, "VF Reset msg received from vf %d\n", vf);
/* reset the filters for the device */
ixgbe_vf_reset_event(adapter, vf);
/* set vf mac address */
if (!is_zero_ether_addr(vf_mac))
ixgbe_set_vf_mac(adapter, vf, vf_mac);
vf_shift = vf % 32;
reg_offset = vf / 32;
/* enable transmit for vf */
reg = IXGBE_READ_REG(hw, IXGBE_VFTE(reg_offset));
reg |= 1 << vf_shift;
IXGBE_WRITE_REG(hw, IXGBE_VFTE(reg_offset), reg);
/* enable receive for vf */
reg = IXGBE_READ_REG(hw, IXGBE_VFRE(reg_offset));
reg |= 1 << vf_shift;
/*
* The 82599 cannot support a mix of jumbo and non-jumbo PF/VFs.
* For more info take a look at ixgbe_set_vf_lpe
*/
if (adapter->hw.mac.type == ixgbe_mac_82599EB) {
struct net_device *dev = adapter->netdev;
int pf_max_frame = dev->mtu + ETH_HLEN;
#ifdef CONFIG_FCOE
if (dev->features & NETIF_F_FCOE_MTU)
pf_max_frame = max_t(int, pf_max_frame,
IXGBE_FCOE_JUMBO_FRAME_SIZE);
#endif /* CONFIG_FCOE */
if (pf_max_frame > ETH_FRAME_LEN)
reg &= ~(1 << vf_shift);
}
IXGBE_WRITE_REG(hw, IXGBE_VFRE(reg_offset), reg);
/* enable VF mailbox for further messages */
adapter->vfinfo[vf].clear_to_send = true;
/* Enable counting of spoofed packets in the SSVPC register */
reg = IXGBE_READ_REG(hw, IXGBE_VMECM(reg_offset));
reg |= (1 << vf_shift);
IXGBE_WRITE_REG(hw, IXGBE_VMECM(reg_offset), reg);
/* reply to reset with ack and vf mac address */
msgbuf[0] = IXGBE_VF_RESET;
if (!is_zero_ether_addr(vf_mac)) {
msgbuf[0] |= IXGBE_VT_MSGTYPE_ACK;
memcpy(addr, vf_mac, ETH_ALEN);
} else {
msgbuf[0] |= IXGBE_VT_MSGTYPE_NACK;
dev_warn(&adapter->pdev->dev,
"VF %d has no MAC address assigned, you may have to assign one manually\n",
vf);
}
/*
* Piggyback the multicast filter type so VF can compute the
* correct vectors
*/
msgbuf[3] = hw->mac.mc_filter_type;
ixgbe_write_mbx(hw, msgbuf, IXGBE_VF_PERMADDR_MSG_LEN, vf);
return 0;
}
static int ixgbe_set_vf_mac_addr(struct ixgbe_adapter *adapter,
u32 *msgbuf, u32 vf)
{
u8 *new_mac = ((u8 *)(&msgbuf[1]));
if (!is_valid_ether_addr(new_mac)) {
e_warn(drv, "VF %d attempted to set invalid mac\n", vf);
return -1;
}
if (adapter->vfinfo[vf].pf_set_mac &&
memcmp(adapter->vfinfo[vf].vf_mac_addresses, new_mac,
ETH_ALEN)) {
e_warn(drv,
"VF %d attempted to override administratively set MAC address\n"
"Reload the VF driver to resume operations\n",
vf);
return -1;
}
return ixgbe_set_vf_mac(adapter, vf, new_mac) < 0;
}
static int ixgbe_set_vf_vlan_msg(struct ixgbe_adapter *adapter,
u32 *msgbuf, u32 vf)
{
struct ixgbe_hw *hw = &adapter->hw;
int add = (msgbuf[0] & IXGBE_VT_MSGINFO_MASK) >> IXGBE_VT_MSGINFO_SHIFT;
int vid = (msgbuf[1] & IXGBE_VLVF_VLANID_MASK);
int err;
u8 tcs = netdev_get_num_tc(adapter->netdev);
if (adapter->vfinfo[vf].pf_vlan || tcs) {
e_warn(drv,
"VF %d attempted to override administratively set VLAN configuration\n"
"Reload the VF driver to resume operations\n",
vf);
return -1;
}
if (add)
adapter->vfinfo[vf].vlan_count++;
else if (adapter->vfinfo[vf].vlan_count)
adapter->vfinfo[vf].vlan_count--;
err = ixgbe_set_vf_vlan(adapter, add, vid, vf);
if (!err && adapter->vfinfo[vf].spoofchk_enabled)
hw->mac.ops.set_vlan_anti_spoofing(hw, true, vf);
return err;
}
static int ixgbe_set_vf_macvlan_msg(struct ixgbe_adapter *adapter,
u32 *msgbuf, u32 vf)
{
u8 *new_mac = ((u8 *)(&msgbuf[1]));
int index = (msgbuf[0] & IXGBE_VT_MSGINFO_MASK) >>
IXGBE_VT_MSGINFO_SHIFT;
int err;
if (adapter->vfinfo[vf].pf_set_mac && index > 0) {
e_warn(drv,
"VF %d requested MACVLAN filter but is administratively denied\n",
vf);
return -1;
}
/* An non-zero index indicates the VF is setting a filter */
if (index) {
if (!is_valid_ether_addr(new_mac)) {
e_warn(drv, "VF %d attempted to set invalid mac\n", vf);
return -1;
}
/*
* If the VF is allowed to set MAC filters then turn off
* anti-spoofing to avoid false positives.
*/
if (adapter->vfinfo[vf].spoofchk_enabled)
ixgbe_ndo_set_vf_spoofchk(adapter->netdev, vf, false);
}
err = ixgbe_set_vf_macvlan(adapter, vf, index, new_mac);
if (err == -ENOSPC)
e_warn(drv,
"VF %d has requested a MACVLAN filter but there is no space for it\n",
vf);
return err < 0;
}
static int ixgbe_negotiate_vf_api(struct ixgbe_adapter *adapter,
u32 *msgbuf, u32 vf)
{
int api = msgbuf[1];
switch (api) {
case ixgbe_mbox_api_10:
case ixgbe_mbox_api_11:
adapter->vfinfo[vf].vf_api = api;
return 0;
default:
break;
}
e_info(drv, "VF %d requested invalid api version %u\n", vf, api);
return -1;
}
static int ixgbe_get_vf_queues(struct ixgbe_adapter *adapter,
u32 *msgbuf, u32 vf)
{
struct net_device *dev = adapter->netdev;
struct ixgbe_ring_feature *vmdq = &adapter->ring_feature[RING_F_VMDQ];
unsigned int default_tc = 0;
u8 num_tcs = netdev_get_num_tc(dev);
/* verify the PF is supporting the correct APIs */
switch (adapter->vfinfo[vf].vf_api) {
case ixgbe_mbox_api_20:
case ixgbe_mbox_api_11:
break;
default:
return -1;
}
/* only allow 1 Tx queue for bandwidth limiting */
msgbuf[IXGBE_VF_TX_QUEUES] = __ALIGN_MASK(1, ~vmdq->mask);
msgbuf[IXGBE_VF_RX_QUEUES] = __ALIGN_MASK(1, ~vmdq->mask);
/* if TCs > 1 determine which TC belongs to default user priority */
if (num_tcs > 1)
default_tc = netdev_get_prio_tc_map(dev, adapter->default_up);
/* notify VF of need for VLAN tag stripping, and correct queue */
if (num_tcs)
msgbuf[IXGBE_VF_TRANS_VLAN] = num_tcs;
else if (adapter->vfinfo[vf].pf_vlan || adapter->vfinfo[vf].pf_qos)
msgbuf[IXGBE_VF_TRANS_VLAN] = 1;
else
msgbuf[IXGBE_VF_TRANS_VLAN] = 0;
/* notify VF of default queue */
msgbuf[IXGBE_VF_DEF_QUEUE] = default_tc;
return 0;
}
static int ixgbe_rcv_msg_from_vf(struct ixgbe_adapter *adapter, u32 vf)
{
u32 mbx_size = IXGBE_VFMAILBOX_SIZE;
u32 msgbuf[IXGBE_VFMAILBOX_SIZE];
struct ixgbe_hw *hw = &adapter->hw;
s32 retval;
retval = ixgbe_read_mbx(hw, msgbuf, mbx_size, vf);
if (retval) {
pr_err("Error receiving message from VF\n");
return retval;
}
/* this is a message we already processed, do nothing */
if (msgbuf[0] & (IXGBE_VT_MSGTYPE_ACK | IXGBE_VT_MSGTYPE_NACK))
return retval;
/* flush the ack before we write any messages back */
IXGBE_WRITE_FLUSH(hw);
if (msgbuf[0] == IXGBE_VF_RESET)
return ixgbe_vf_reset_msg(adapter, vf);
/*
* until the vf completes a virtual function reset it should not be
* allowed to start any configuration.
*/
if (!adapter->vfinfo[vf].clear_to_send) {
msgbuf[0] |= IXGBE_VT_MSGTYPE_NACK;
ixgbe_write_mbx(hw, msgbuf, 1, vf);
return retval;
}
switch ((msgbuf[0] & 0xFFFF)) {
case IXGBE_VF_SET_MAC_ADDR:
retval = ixgbe_set_vf_mac_addr(adapter, msgbuf, vf);
break;
case IXGBE_VF_SET_MULTICAST:
retval = ixgbe_set_vf_multicasts(adapter, msgbuf, vf);
break;
case IXGBE_VF_SET_VLAN:
retval = ixgbe_set_vf_vlan_msg(adapter, msgbuf, vf);
break;
case IXGBE_VF_SET_LPE:
retval = ixgbe_set_vf_lpe(adapter, msgbuf, vf);
break;
case IXGBE_VF_SET_MACVLAN:
retval = ixgbe_set_vf_macvlan_msg(adapter, msgbuf, vf);
break;
case IXGBE_VF_API_NEGOTIATE:
retval = ixgbe_negotiate_vf_api(adapter, msgbuf, vf);
break;
case IXGBE_VF_GET_QUEUES:
retval = ixgbe_get_vf_queues(adapter, msgbuf, vf);
break;
default:
e_err(drv, "Unhandled Msg %8.8x\n", msgbuf[0]);
retval = IXGBE_ERR_MBX;
break;
}
/* notify the VF of the results of what it sent us */
if (retval)
msgbuf[0] |= IXGBE_VT_MSGTYPE_NACK;
else
msgbuf[0] |= IXGBE_VT_MSGTYPE_ACK;
msgbuf[0] |= IXGBE_VT_MSGTYPE_CTS;
ixgbe_write_mbx(hw, msgbuf, mbx_size, vf);
return retval;
}
static void ixgbe_rcv_ack_from_vf(struct ixgbe_adapter *adapter, u32 vf)
{
struct ixgbe_hw *hw = &adapter->hw;
u32 msg = IXGBE_VT_MSGTYPE_NACK;
/* if device isn't clear to send it shouldn't be reading either */
if (!adapter->vfinfo[vf].clear_to_send)
ixgbe_write_mbx(hw, &msg, 1, vf);
}
void ixgbe_msg_task(struct ixgbe_adapter *adapter)
{
struct ixgbe_hw *hw = &adapter->hw;
u32 vf;
for (vf = 0; vf < adapter->num_vfs; vf++) {
/* process any reset requests */
if (!ixgbe_check_for_rst(hw, vf))
ixgbe_vf_reset_event(adapter, vf);
/* process any messages pending */
if (!ixgbe_check_for_msg(hw, vf))
ixgbe_rcv_msg_from_vf(adapter, vf);
/* process any acks */
if (!ixgbe_check_for_ack(hw, vf))
ixgbe_rcv_ack_from_vf(adapter, vf);
}
}
void ixgbe_disable_tx_rx(struct ixgbe_adapter *adapter)
{
struct ixgbe_hw *hw = &adapter->hw;
/* disable transmit and receive for all vfs */
IXGBE_WRITE_REG(hw, IXGBE_VFTE(0), 0);
IXGBE_WRITE_REG(hw, IXGBE_VFTE(1), 0);
IXGBE_WRITE_REG(hw, IXGBE_VFRE(0), 0);
IXGBE_WRITE_REG(hw, IXGBE_VFRE(1), 0);
}
void ixgbe_ping_all_vfs(struct ixgbe_adapter *adapter)
{
struct ixgbe_hw *hw = &adapter->hw;
u32 ping;
int i;
for (i = 0 ; i < adapter->num_vfs; i++) {
ping = IXGBE_PF_CONTROL_MSG;
if (adapter->vfinfo[i].clear_to_send)
ping |= IXGBE_VT_MSGTYPE_CTS;
ixgbe_write_mbx(hw, &ping, 1, i);
}
}
int ixgbe_ndo_set_vf_mac(struct net_device *netdev, int vf, u8 *mac)
{
struct ixgbe_adapter *adapter = netdev_priv(netdev);
if (!is_valid_ether_addr(mac) || (vf >= adapter->num_vfs))
return -EINVAL;
adapter->vfinfo[vf].pf_set_mac = true;
dev_info(&adapter->pdev->dev, "setting MAC %pM on VF %d\n", mac, vf);
dev_info(&adapter->pdev->dev, "Reload the VF driver to make this"
" change effective.");
if (test_bit(__IXGBE_DOWN, &adapter->state)) {
dev_warn(&adapter->pdev->dev, "The VF MAC address has been set,"
" but the PF device is not up.\n");
dev_warn(&adapter->pdev->dev, "Bring the PF device up before"
" attempting to use the VF device.\n");
}
return ixgbe_set_vf_mac(adapter, vf, mac);
}
int ixgbe_ndo_set_vf_vlan(struct net_device *netdev, int vf, u16 vlan, u8 qos)
{
int err = 0;
struct ixgbe_adapter *adapter = netdev_priv(netdev);
struct ixgbe_hw *hw = &adapter->hw;
if ((vf >= adapter->num_vfs) || (vlan > 4095) || (qos > 7))
return -EINVAL;
if (vlan || qos) {
if (adapter->vfinfo[vf].pf_vlan)
err = ixgbe_set_vf_vlan(adapter, false,
adapter->vfinfo[vf].pf_vlan,
vf);
if (err)
goto out;
err = ixgbe_set_vf_vlan(adapter, true, vlan, vf);
if (err)
goto out;
ixgbe_set_vmvir(adapter, vlan, qos, vf);
ixgbe_set_vmolr(hw, vf, false);
if (adapter->vfinfo[vf].spoofchk_enabled)
hw->mac.ops.set_vlan_anti_spoofing(hw, true, vf);
adapter->vfinfo[vf].vlan_count++;
adapter->vfinfo[vf].pf_vlan = vlan;
adapter->vfinfo[vf].pf_qos = qos;
dev_info(&adapter->pdev->dev,
"Setting VLAN %d, QOS 0x%x on VF %d\n", vlan, qos, vf);
if (test_bit(__IXGBE_DOWN, &adapter->state)) {
dev_warn(&adapter->pdev->dev,
"The VF VLAN has been set,"
" but the PF device is not up.\n");
dev_warn(&adapter->pdev->dev,
"Bring the PF device up before"
" attempting to use the VF device.\n");
}
} else {
err = ixgbe_set_vf_vlan(adapter, false,
adapter->vfinfo[vf].pf_vlan, vf);
ixgbe_clear_vmvir(adapter, vf);
ixgbe_set_vmolr(hw, vf, true);
hw->mac.ops.set_vlan_anti_spoofing(hw, false, vf);
if (adapter->vfinfo[vf].vlan_count)
adapter->vfinfo[vf].vlan_count--;
adapter->vfinfo[vf].pf_vlan = 0;
adapter->vfinfo[vf].pf_qos = 0;
}
out:
return err;
}
static int ixgbe_link_mbps(struct ixgbe_adapter *adapter)
{
switch (adapter->link_speed) {
case IXGBE_LINK_SPEED_100_FULL:
return 100;
case IXGBE_LINK_SPEED_1GB_FULL:
return 1000;
case IXGBE_LINK_SPEED_10GB_FULL:
return 10000;
default:
return 0;
}
}
static void ixgbe_set_vf_rate_limit(struct ixgbe_adapter *adapter, int vf)
{
struct ixgbe_ring_feature *vmdq = &adapter->ring_feature[RING_F_VMDQ];
struct ixgbe_hw *hw = &adapter->hw;
u32 bcnrc_val = 0;
u16 queue, queues_per_pool;
u16 tx_rate = adapter->vfinfo[vf].tx_rate;
if (tx_rate) {
/* start with base link speed value */
bcnrc_val = adapter->vf_rate_link_speed;
/* Calculate the rate factor values to set */
bcnrc_val <<= IXGBE_RTTBCNRC_RF_INT_SHIFT;
bcnrc_val /= tx_rate;
/* clear everything but the rate factor */
bcnrc_val &= IXGBE_RTTBCNRC_RF_INT_MASK |
IXGBE_RTTBCNRC_RF_DEC_MASK;
/* enable the rate scheduler */
bcnrc_val |= IXGBE_RTTBCNRC_RS_ENA;
}
/*
* Set global transmit compensation time to the MMW_SIZE in RTTBCNRM
* register. Typically MMW_SIZE=0x014 if 9728-byte jumbo is supported
* and 0x004 otherwise.
*/
switch (hw->mac.type) {
case ixgbe_mac_82599EB:
IXGBE_WRITE_REG(hw, IXGBE_RTTBCNRM, 0x4);
break;
case ixgbe_mac_X540:
IXGBE_WRITE_REG(hw, IXGBE_RTTBCNRM, 0x14);
break;
default:
break;
}
/* determine how many queues per pool based on VMDq mask */
queues_per_pool = __ALIGN_MASK(1, ~vmdq->mask);
/* write value for all Tx queues belonging to VF */
for (queue = 0; queue < queues_per_pool; queue++) {
unsigned int reg_idx = (vf * queues_per_pool) + queue;
IXGBE_WRITE_REG(hw, IXGBE_RTTDQSEL, reg_idx);
IXGBE_WRITE_REG(hw, IXGBE_RTTBCNRC, bcnrc_val);
}
}
void ixgbe_check_vf_rate_limit(struct ixgbe_adapter *adapter)
{
int i;
/* VF Tx rate limit was not set */
if (!adapter->vf_rate_link_speed)
return;
if (ixgbe_link_mbps(adapter) != adapter->vf_rate_link_speed) {
adapter->vf_rate_link_speed = 0;
dev_info(&adapter->pdev->dev,
"Link speed has been changed. VF Transmit rate is disabled\n");
}
for (i = 0; i < adapter->num_vfs; i++) {
if (!adapter->vf_rate_link_speed)
adapter->vfinfo[i].tx_rate = 0;
ixgbe_set_vf_rate_limit(adapter, i);
}
}
int ixgbe_ndo_set_vf_bw(struct net_device *netdev, int vf, int tx_rate)
{
struct ixgbe_adapter *adapter = netdev_priv(netdev);
int link_speed;
/* verify VF is active */
if (vf >= adapter->num_vfs)
return -EINVAL;
/* verify link is up */
if (!adapter->link_up)
return -EINVAL;
/* verify we are linked at 10Gbps */
link_speed = ixgbe_link_mbps(adapter);
if (link_speed != 10000)
return -EINVAL;
/* rate limit cannot be less than 10Mbs or greater than link speed */
if (tx_rate && ((tx_rate <= 10) || (tx_rate > link_speed)))
return -EINVAL;
/* store values */
adapter->vf_rate_link_speed = link_speed;
adapter->vfinfo[vf].tx_rate = tx_rate;
/* update hardware configuration */
ixgbe_set_vf_rate_limit(adapter, vf);
return 0;
}
int ixgbe_ndo_set_vf_spoofchk(struct net_device *netdev, int vf, bool setting)
{
struct ixgbe_adapter *adapter = netdev_priv(netdev);
int vf_target_reg = vf >> 3;
int vf_target_shift = vf % 8;
struct ixgbe_hw *hw = &adapter->hw;
u32 regval;
adapter->vfinfo[vf].spoofchk_enabled = setting;
regval = IXGBE_READ_REG(hw, IXGBE_PFVFSPOOF(vf_target_reg));
regval &= ~(1 << vf_target_shift);
regval |= (setting << vf_target_shift);
IXGBE_WRITE_REG(hw, IXGBE_PFVFSPOOF(vf_target_reg), regval);
if (adapter->vfinfo[vf].vlan_count) {
vf_target_shift += IXGBE_SPOOF_VLANAS_SHIFT;
regval = IXGBE_READ_REG(hw, IXGBE_PFVFSPOOF(vf_target_reg));
regval &= ~(1 << vf_target_shift);
regval |= (setting << vf_target_shift);
IXGBE_WRITE_REG(hw, IXGBE_PFVFSPOOF(vf_target_reg), regval);
}
return 0;
}
int ixgbe_ndo_get_vf_config(struct net_device *netdev,
int vf, struct ifla_vf_info *ivi)
{
struct ixgbe_adapter *adapter = netdev_priv(netdev);
if (vf >= adapter->num_vfs)
return -EINVAL;
ivi->vf = vf;
memcpy(&ivi->mac, adapter->vfinfo[vf].vf_mac_addresses, ETH_ALEN);
ivi->tx_rate = adapter->vfinfo[vf].tx_rate;
ivi->vlan = adapter->vfinfo[vf].pf_vlan;
ivi->qos = adapter->vfinfo[vf].pf_qos;
ivi->spoofchk = adapter->vfinfo[vf].spoofchk_enabled;
return 0;
}
| gpl-2.0 |
Myself5/android_kernel_sony_msm | arch/m68k/atari/ataints.c | 2146 | 10069 | /*
* arch/m68k/atari/ataints.c -- Atari Linux interrupt handling code
*
* 5/2/94 Roman Hodek:
* Added support for TT interrupts; setup for TT SCU (may someone has
* twiddled there and we won't get the right interrupts :-()
*
* Major change: The device-independent code in m68k/ints.c didn't know
* about non-autovec ints yet. It hardcoded the number of possible ints to
* 7 (IRQ1...IRQ7). But the Atari has lots of non-autovec ints! I made the
* number of possible ints a constant defined in interrupt.h, which is
* 47 for the Atari. So we can call request_irq() for all Atari interrupts
* just the normal way. Additionally, all vectors >= 48 are initialized to
* call trap() instead of inthandler(). This must be changed here, too.
*
* 1995-07-16 Lars Brinkhoff <f93labr@dd.chalmers.se>:
* Corrected a bug in atari_add_isr() which rejected all SCC
* interrupt sources if there were no TT MFP!
*
* 12/13/95: New interface functions atari_level_triggered_int() and
* atari_register_vme_int() as support for level triggered VME interrupts.
*
* 02/12/96: (Roman)
* Total rewrite of Atari interrupt handling, for new scheme see comments
* below.
*
* 1996-09-03 lars brinkhoff <f93labr@dd.chalmers.se>:
* Added new function atari_unregister_vme_int(), and
* modified atari_register_vme_int() as well as IS_VALID_INTNO()
* to work with it.
*
* 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/kernel.h>
#include <linux/kernel_stat.h>
#include <linux/init.h>
#include <linux/seq_file.h>
#include <linux/module.h>
#include <asm/traps.h>
#include <asm/atarihw.h>
#include <asm/atariints.h>
#include <asm/atari_stdma.h>
#include <asm/irq.h>
#include <asm/entry.h>
#include <asm/io.h>
/*
* Atari interrupt handling scheme:
* --------------------------------
*
* All interrupt source have an internal number (defined in
* <asm/atariints.h>): Autovector interrupts are 1..7, then follow ST-MFP,
* TT-MFP, SCC, and finally VME interrupts. Vector numbers for the latter can
* be allocated by atari_register_vme_int().
*/
/*
* Bitmap for free interrupt vector numbers
* (new vectors starting from 0x70 can be allocated by
* atari_register_vme_int())
*/
static int free_vme_vec_bitmap;
/* GK:
* HBL IRQ handler for Falcon. Nobody needs it :-)
* ++andreas: raise ipl to disable further HBLANK interrupts.
*/
asmlinkage void falcon_hblhandler(void);
asm(".text\n"
__ALIGN_STR "\n\t"
"falcon_hblhandler:\n\t"
"orw #0x200,%sp@\n\t" /* set saved ipl to 2 */
"rte");
extern void atari_microwire_cmd(int cmd);
static unsigned int atari_irq_startup(struct irq_data *data)
{
unsigned int irq = data->irq;
m68k_irq_startup(data);
atari_turnon_irq(irq);
atari_enable_irq(irq);
return 0;
}
static void atari_irq_shutdown(struct irq_data *data)
{
unsigned int irq = data->irq;
atari_disable_irq(irq);
atari_turnoff_irq(irq);
m68k_irq_shutdown(data);
if (irq == IRQ_AUTO_4)
vectors[VEC_INT4] = falcon_hblhandler;
}
static void atari_irq_enable(struct irq_data *data)
{
atari_enable_irq(data->irq);
}
static void atari_irq_disable(struct irq_data *data)
{
atari_disable_irq(data->irq);
}
static struct irq_chip atari_irq_chip = {
.name = "atari",
.irq_startup = atari_irq_startup,
.irq_shutdown = atari_irq_shutdown,
.irq_enable = atari_irq_enable,
.irq_disable = atari_irq_disable,
};
/*
* ST-MFP timer D chained interrupts - each driver gets its own timer
* interrupt instance.
*/
struct mfptimerbase {
volatile struct MFP *mfp;
unsigned char mfp_mask, mfp_data;
unsigned short int_mask;
int handler_irq, mfptimer_irq, server_irq;
char *name;
} stmfp_base = {
.mfp = &st_mfp,
.int_mask = 0x0,
.handler_irq = IRQ_MFP_TIMD,
.mfptimer_irq = IRQ_MFP_TIMER1,
.name = "MFP Timer D"
};
static irqreturn_t mfptimer_handler(int irq, void *dev_id)
{
struct mfptimerbase *base = dev_id;
int mach_irq;
unsigned char ints;
mach_irq = base->mfptimer_irq;
ints = base->int_mask;
for (; ints; mach_irq++, ints >>= 1) {
if (ints & 1)
generic_handle_irq(mach_irq);
}
return IRQ_HANDLED;
}
static void atari_mfptimer_enable(struct irq_data *data)
{
int mfp_num = data->irq - IRQ_MFP_TIMER1;
stmfp_base.int_mask |= 1 << mfp_num;
atari_enable_irq(IRQ_MFP_TIMD);
}
static void atari_mfptimer_disable(struct irq_data *data)
{
int mfp_num = data->irq - IRQ_MFP_TIMER1;
stmfp_base.int_mask &= ~(1 << mfp_num);
if (!stmfp_base.int_mask)
atari_disable_irq(IRQ_MFP_TIMD);
}
static struct irq_chip atari_mfptimer_chip = {
.name = "timer_d",
.irq_enable = atari_mfptimer_enable,
.irq_disable = atari_mfptimer_disable,
};
/*
* EtherNAT CPLD interrupt handling
* CPLD interrupt register is at phys. 0x80000023
* Need this mapped in at interrupt startup time
* Possibly need this mapped on demand anyway -
* EtherNAT USB driver needs to disable IRQ before
* startup!
*/
static unsigned char *enat_cpld;
static unsigned int atari_ethernat_startup(struct irq_data *data)
{
int enat_num = 140 - data->irq + 1;
m68k_irq_startup(data);
/*
* map CPLD interrupt register
*/
if (!enat_cpld)
enat_cpld = (unsigned char *)ioremap((ATARI_ETHERNAT_PHYS_ADDR+0x23), 0x2);
/*
* do _not_ enable the USB chip interrupt here - causes interrupt storm
* and triggers dead interrupt watchdog
* Need to reset the USB chip to a sane state in early startup before
* removing this hack
*/
if (enat_num == 1)
*enat_cpld |= 1 << enat_num;
return 0;
}
static void atari_ethernat_enable(struct irq_data *data)
{
int enat_num = 140 - data->irq + 1;
/*
* map CPLD interrupt register
*/
if (!enat_cpld)
enat_cpld = (unsigned char *)ioremap((ATARI_ETHERNAT_PHYS_ADDR+0x23), 0x2);
*enat_cpld |= 1 << enat_num;
}
static void atari_ethernat_disable(struct irq_data *data)
{
int enat_num = 140 - data->irq + 1;
/*
* map CPLD interrupt register
*/
if (!enat_cpld)
enat_cpld = (unsigned char *)ioremap((ATARI_ETHERNAT_PHYS_ADDR+0x23), 0x2);
*enat_cpld &= ~(1 << enat_num);
}
static void atari_ethernat_shutdown(struct irq_data *data)
{
int enat_num = 140 - data->irq + 1;
if (enat_cpld) {
*enat_cpld &= ~(1 << enat_num);
iounmap(enat_cpld);
enat_cpld = NULL;
}
}
static struct irq_chip atari_ethernat_chip = {
.name = "ethernat",
.irq_startup = atari_ethernat_startup,
.irq_shutdown = atari_ethernat_shutdown,
.irq_enable = atari_ethernat_enable,
.irq_disable = atari_ethernat_disable,
};
/*
* void atari_init_IRQ (void)
*
* Parameters: None
*
* Returns: Nothing
*
* This function should be called during kernel startup to initialize
* the atari IRQ handling routines.
*/
void __init atari_init_IRQ(void)
{
m68k_setup_user_interrupt(VEC_USER, NUM_ATARI_SOURCES - IRQ_USER);
m68k_setup_irq_controller(&atari_irq_chip, handle_simple_irq, 1,
NUM_ATARI_SOURCES - 1);
/* Initialize the MFP(s) */
#ifdef ATARI_USE_SOFTWARE_EOI
st_mfp.vec_adr = 0x48; /* Software EOI-Mode */
#else
st_mfp.vec_adr = 0x40; /* Automatic EOI-Mode */
#endif
st_mfp.int_en_a = 0x00; /* turn off MFP-Ints */
st_mfp.int_en_b = 0x00;
st_mfp.int_mk_a = 0xff; /* no Masking */
st_mfp.int_mk_b = 0xff;
if (ATARIHW_PRESENT(TT_MFP)) {
#ifdef ATARI_USE_SOFTWARE_EOI
tt_mfp.vec_adr = 0x58; /* Software EOI-Mode */
#else
tt_mfp.vec_adr = 0x50; /* Automatic EOI-Mode */
#endif
tt_mfp.int_en_a = 0x00; /* turn off MFP-Ints */
tt_mfp.int_en_b = 0x00;
tt_mfp.int_mk_a = 0xff; /* no Masking */
tt_mfp.int_mk_b = 0xff;
}
if (ATARIHW_PRESENT(SCC) && !atari_SCC_reset_done) {
atari_scc.cha_a_ctrl = 9;
MFPDELAY();
atari_scc.cha_a_ctrl = (char) 0xc0; /* hardware reset */
}
if (ATARIHW_PRESENT(SCU)) {
/* init the SCU if present */
tt_scu.sys_mask = 0x10; /* enable VBL (for the cursor) and
* disable HSYNC interrupts (who
* needs them?) MFP and SCC are
* enabled in VME mask
*/
tt_scu.vme_mask = 0x60; /* enable MFP and SCC ints */
} else {
/* If no SCU and no Hades, the HSYNC interrupt needs to be
* disabled this way. (Else _inthandler in kernel/sys_call.S
* gets overruns)
*/
vectors[VEC_INT2] = falcon_hblhandler;
vectors[VEC_INT4] = falcon_hblhandler;
}
if (ATARIHW_PRESENT(PCM_8BIT) && ATARIHW_PRESENT(MICROWIRE)) {
/* Initialize the LM1992 Sound Controller to enable
the PSG sound. This is misplaced here, it should
be in an atasound_init(), that doesn't exist yet. */
atari_microwire_cmd(MW_LM1992_PSG_HIGH);
}
stdma_init();
/* Initialize the PSG: all sounds off, both ports output */
sound_ym.rd_data_reg_sel = 7;
sound_ym.wd_data = 0xff;
m68k_setup_irq_controller(&atari_mfptimer_chip, handle_simple_irq,
IRQ_MFP_TIMER1, 8);
/* prepare timer D data for use as poll interrupt */
/* set Timer D data Register - needs to be > 0 */
st_mfp.tim_dt_d = 254; /* < 100 Hz */
/* start timer D, div = 1:100 */
st_mfp.tim_ct_cd = (st_mfp.tim_ct_cd & 0xf0) | 0x6;
/* request timer D dispatch handler */
if (request_irq(IRQ_MFP_TIMD, mfptimer_handler, IRQF_SHARED,
stmfp_base.name, &stmfp_base))
pr_err("Couldn't register %s interrupt\n", stmfp_base.name);
/*
* EtherNAT ethernet / USB interrupt handlers
*/
m68k_setup_irq_controller(&atari_ethernat_chip, handle_simple_irq,
139, 2);
}
/*
* atari_register_vme_int() returns the number of a free interrupt vector for
* hardware with a programmable int vector (probably a VME board).
*/
unsigned int atari_register_vme_int(void)
{
int i;
for (i = 0; i < 32; i++)
if ((free_vme_vec_bitmap & (1 << i)) == 0)
break;
if (i == 16)
return 0;
free_vme_vec_bitmap |= 1 << i;
return VME_SOURCE_BASE + i;
}
EXPORT_SYMBOL(atari_register_vme_int);
void atari_unregister_vme_int(unsigned int irq)
{
if (irq >= VME_SOURCE_BASE && irq < VME_SOURCE_BASE + VME_MAX_SOURCES) {
irq -= VME_SOURCE_BASE;
free_vme_vec_bitmap &= ~(1 << irq);
}
}
EXPORT_SYMBOL(atari_unregister_vme_int);
| gpl-2.0 |
sleshepic/G920T_OI1_kernel | drivers/scsi/device_handler/scsi_dh_rdac.c | 2146 | 23072 | /*
* LSI/Engenio/NetApp E-Series RDAC SCSI Device Handler
*
* Copyright (C) 2005 Mike Christie. All rights reserved.
* Copyright (C) Chandra Seetharaman, IBM Corp. 2007
*
* 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 <scsi/scsi.h>
#include <scsi/scsi_eh.h>
#include <scsi/scsi_dh.h>
#include <linux/workqueue.h>
#include <linux/slab.h>
#include <linux/module.h>
#define RDAC_NAME "rdac"
#define RDAC_RETRY_COUNT 5
/*
* LSI mode page stuff
*
* These struct definitions and the forming of the
* mode page were taken from the LSI RDAC 2.4 GPL'd
* driver, and then converted to Linux conventions.
*/
#define RDAC_QUIESCENCE_TIME 20
/*
* Page Codes
*/
#define RDAC_PAGE_CODE_REDUNDANT_CONTROLLER 0x2c
/*
* Controller modes definitions
*/
#define RDAC_MODE_TRANSFER_SPECIFIED_LUNS 0x02
/*
* RDAC Options field
*/
#define RDAC_FORCED_QUIESENCE 0x02
#define RDAC_TIMEOUT (60 * HZ)
#define RDAC_RETRIES 3
struct rdac_mode_6_hdr {
u8 data_len;
u8 medium_type;
u8 device_params;
u8 block_desc_len;
};
struct rdac_mode_10_hdr {
u16 data_len;
u8 medium_type;
u8 device_params;
u16 reserved;
u16 block_desc_len;
};
struct rdac_mode_common {
u8 controller_serial[16];
u8 alt_controller_serial[16];
u8 rdac_mode[2];
u8 alt_rdac_mode[2];
u8 quiescence_timeout;
u8 rdac_options;
};
struct rdac_pg_legacy {
struct rdac_mode_6_hdr hdr;
u8 page_code;
u8 page_len;
struct rdac_mode_common common;
#define MODE6_MAX_LUN 32
u8 lun_table[MODE6_MAX_LUN];
u8 reserved2[32];
u8 reserved3;
u8 reserved4;
};
struct rdac_pg_expanded {
struct rdac_mode_10_hdr hdr;
u8 page_code;
u8 subpage_code;
u8 page_len[2];
struct rdac_mode_common common;
u8 lun_table[256];
u8 reserved3;
u8 reserved4;
};
struct c9_inquiry {
u8 peripheral_info;
u8 page_code; /* 0xC9 */
u8 reserved1;
u8 page_len;
u8 page_id[4]; /* "vace" */
u8 avte_cvp;
u8 path_prio;
u8 reserved2[38];
};
#define SUBSYS_ID_LEN 16
#define SLOT_ID_LEN 2
#define ARRAY_LABEL_LEN 31
struct c4_inquiry {
u8 peripheral_info;
u8 page_code; /* 0xC4 */
u8 reserved1;
u8 page_len;
u8 page_id[4]; /* "subs" */
u8 subsys_id[SUBSYS_ID_LEN];
u8 revision[4];
u8 slot_id[SLOT_ID_LEN];
u8 reserved[2];
};
#define UNIQUE_ID_LEN 16
struct c8_inquiry {
u8 peripheral_info;
u8 page_code; /* 0xC8 */
u8 reserved1;
u8 page_len;
u8 page_id[4]; /* "edid" */
u8 reserved2[3];
u8 vol_uniq_id_len;
u8 vol_uniq_id[16];
u8 vol_user_label_len;
u8 vol_user_label[60];
u8 array_uniq_id_len;
u8 array_unique_id[UNIQUE_ID_LEN];
u8 array_user_label_len;
u8 array_user_label[60];
u8 lun[8];
};
struct rdac_controller {
u8 array_id[UNIQUE_ID_LEN];
int use_ms10;
struct kref kref;
struct list_head node; /* list of all controllers */
union {
struct rdac_pg_legacy legacy;
struct rdac_pg_expanded expanded;
} mode_select;
u8 index;
u8 array_name[ARRAY_LABEL_LEN];
struct Scsi_Host *host;
spinlock_t ms_lock;
int ms_queued;
struct work_struct ms_work;
struct scsi_device *ms_sdev;
struct list_head ms_head;
};
struct c2_inquiry {
u8 peripheral_info;
u8 page_code; /* 0xC2 */
u8 reserved1;
u8 page_len;
u8 page_id[4]; /* "swr4" */
u8 sw_version[3];
u8 sw_date[3];
u8 features_enabled;
u8 max_lun_supported;
u8 partitions[239]; /* Total allocation length should be 0xFF */
};
struct rdac_dh_data {
struct rdac_controller *ctlr;
#define UNINITIALIZED_LUN (1 << 8)
unsigned lun;
#define RDAC_MODE 0
#define RDAC_MODE_AVT 1
#define RDAC_MODE_IOSHIP 2
unsigned char mode;
#define RDAC_STATE_ACTIVE 0
#define RDAC_STATE_PASSIVE 1
unsigned char state;
#define RDAC_LUN_UNOWNED 0
#define RDAC_LUN_OWNED 1
char lun_state;
#define RDAC_PREFERRED 0
#define RDAC_NON_PREFERRED 1
char preferred;
unsigned char sense[SCSI_SENSE_BUFFERSIZE];
union {
struct c2_inquiry c2;
struct c4_inquiry c4;
struct c8_inquiry c8;
struct c9_inquiry c9;
} inq;
};
static const char *mode[] = {
"RDAC",
"AVT",
"IOSHIP",
};
static const char *lun_state[] =
{
"unowned",
"owned",
};
struct rdac_queue_data {
struct list_head entry;
struct rdac_dh_data *h;
activate_complete callback_fn;
void *callback_data;
};
static LIST_HEAD(ctlr_list);
static DEFINE_SPINLOCK(list_lock);
static struct workqueue_struct *kmpath_rdacd;
static void send_mode_select(struct work_struct *work);
/*
* module parameter to enable rdac debug logging.
* 2 bits for each type of logging, only two types defined for now
* Can be enhanced if required at later point
*/
static int rdac_logging = 1;
module_param(rdac_logging, int, S_IRUGO|S_IWUSR);
MODULE_PARM_DESC(rdac_logging, "A bit mask of rdac logging levels, "
"Default is 1 - failover logging enabled, "
"set it to 0xF to enable all the logs");
#define RDAC_LOG_FAILOVER 0
#define RDAC_LOG_SENSE 2
#define RDAC_LOG_BITS 2
#define RDAC_LOG_LEVEL(SHIFT) \
((rdac_logging >> (SHIFT)) & ((1 << (RDAC_LOG_BITS)) - 1))
#define RDAC_LOG(SHIFT, sdev, f, arg...) \
do { \
if (unlikely(RDAC_LOG_LEVEL(SHIFT))) \
sdev_printk(KERN_INFO, sdev, RDAC_NAME ": " f "\n", ## arg); \
} while (0);
static inline struct rdac_dh_data *get_rdac_data(struct scsi_device *sdev)
{
struct scsi_dh_data *scsi_dh_data = sdev->scsi_dh_data;
BUG_ON(scsi_dh_data == NULL);
return ((struct rdac_dh_data *) scsi_dh_data->buf);
}
static struct request *get_rdac_req(struct scsi_device *sdev,
void *buffer, unsigned buflen, int rw)
{
struct request *rq;
struct request_queue *q = sdev->request_queue;
rq = blk_get_request(q, rw, GFP_NOIO);
if (!rq) {
sdev_printk(KERN_INFO, sdev,
"get_rdac_req: blk_get_request failed.\n");
return NULL;
}
if (buflen && blk_rq_map_kern(q, rq, buffer, buflen, GFP_NOIO)) {
blk_put_request(rq);
sdev_printk(KERN_INFO, sdev,
"get_rdac_req: blk_rq_map_kern failed.\n");
return NULL;
}
rq->cmd_type = REQ_TYPE_BLOCK_PC;
rq->cmd_flags |= REQ_FAILFAST_DEV | REQ_FAILFAST_TRANSPORT |
REQ_FAILFAST_DRIVER;
rq->retries = RDAC_RETRIES;
rq->timeout = RDAC_TIMEOUT;
return rq;
}
static struct request *rdac_failover_get(struct scsi_device *sdev,
struct rdac_dh_data *h, struct list_head *list)
{
struct request *rq;
struct rdac_mode_common *common;
unsigned data_size;
struct rdac_queue_data *qdata;
u8 *lun_table;
if (h->ctlr->use_ms10) {
struct rdac_pg_expanded *rdac_pg;
data_size = sizeof(struct rdac_pg_expanded);
rdac_pg = &h->ctlr->mode_select.expanded;
memset(rdac_pg, 0, data_size);
common = &rdac_pg->common;
rdac_pg->page_code = RDAC_PAGE_CODE_REDUNDANT_CONTROLLER + 0x40;
rdac_pg->subpage_code = 0x1;
rdac_pg->page_len[0] = 0x01;
rdac_pg->page_len[1] = 0x28;
lun_table = rdac_pg->lun_table;
} else {
struct rdac_pg_legacy *rdac_pg;
data_size = sizeof(struct rdac_pg_legacy);
rdac_pg = &h->ctlr->mode_select.legacy;
memset(rdac_pg, 0, data_size);
common = &rdac_pg->common;
rdac_pg->page_code = RDAC_PAGE_CODE_REDUNDANT_CONTROLLER;
rdac_pg->page_len = 0x68;
lun_table = rdac_pg->lun_table;
}
common->rdac_mode[1] = RDAC_MODE_TRANSFER_SPECIFIED_LUNS;
common->quiescence_timeout = RDAC_QUIESCENCE_TIME;
common->rdac_options = RDAC_FORCED_QUIESENCE;
list_for_each_entry(qdata, list, entry) {
lun_table[qdata->h->lun] = 0x81;
}
/* get request for block layer packet command */
rq = get_rdac_req(sdev, &h->ctlr->mode_select, data_size, WRITE);
if (!rq)
return NULL;
/* Prepare the command. */
if (h->ctlr->use_ms10) {
rq->cmd[0] = MODE_SELECT_10;
rq->cmd[7] = data_size >> 8;
rq->cmd[8] = data_size & 0xff;
} else {
rq->cmd[0] = MODE_SELECT;
rq->cmd[4] = data_size;
}
rq->cmd_len = COMMAND_SIZE(rq->cmd[0]);
rq->sense = h->sense;
memset(rq->sense, 0, SCSI_SENSE_BUFFERSIZE);
rq->sense_len = 0;
return rq;
}
static void release_controller(struct kref *kref)
{
struct rdac_controller *ctlr;
ctlr = container_of(kref, struct rdac_controller, kref);
list_del(&ctlr->node);
kfree(ctlr);
}
static struct rdac_controller *get_controller(int index, char *array_name,
u8 *array_id, struct scsi_device *sdev)
{
struct rdac_controller *ctlr, *tmp;
list_for_each_entry(tmp, &ctlr_list, node) {
if ((memcmp(tmp->array_id, array_id, UNIQUE_ID_LEN) == 0) &&
(tmp->index == index) &&
(tmp->host == sdev->host)) {
kref_get(&tmp->kref);
return tmp;
}
}
ctlr = kmalloc(sizeof(*ctlr), GFP_ATOMIC);
if (!ctlr)
return NULL;
/* initialize fields of controller */
memcpy(ctlr->array_id, array_id, UNIQUE_ID_LEN);
ctlr->index = index;
ctlr->host = sdev->host;
memcpy(ctlr->array_name, array_name, ARRAY_LABEL_LEN);
kref_init(&ctlr->kref);
ctlr->use_ms10 = -1;
ctlr->ms_queued = 0;
ctlr->ms_sdev = NULL;
spin_lock_init(&ctlr->ms_lock);
INIT_WORK(&ctlr->ms_work, send_mode_select);
INIT_LIST_HEAD(&ctlr->ms_head);
list_add(&ctlr->node, &ctlr_list);
return ctlr;
}
static int submit_inquiry(struct scsi_device *sdev, int page_code,
unsigned int len, struct rdac_dh_data *h)
{
struct request *rq;
struct request_queue *q = sdev->request_queue;
int err = SCSI_DH_RES_TEMP_UNAVAIL;
rq = get_rdac_req(sdev, &h->inq, len, READ);
if (!rq)
goto done;
/* Prepare the command. */
rq->cmd[0] = INQUIRY;
rq->cmd[1] = 1;
rq->cmd[2] = page_code;
rq->cmd[4] = len;
rq->cmd_len = COMMAND_SIZE(INQUIRY);
rq->sense = h->sense;
memset(rq->sense, 0, SCSI_SENSE_BUFFERSIZE);
rq->sense_len = 0;
err = blk_execute_rq(q, NULL, rq, 1);
if (err == -EIO)
err = SCSI_DH_IO;
blk_put_request(rq);
done:
return err;
}
static int get_lun_info(struct scsi_device *sdev, struct rdac_dh_data *h,
char *array_name, u8 *array_id)
{
int err, i;
struct c8_inquiry *inqp;
err = submit_inquiry(sdev, 0xC8, sizeof(struct c8_inquiry), h);
if (err == SCSI_DH_OK) {
inqp = &h->inq.c8;
if (inqp->page_code != 0xc8)
return SCSI_DH_NOSYS;
if (inqp->page_id[0] != 'e' || inqp->page_id[1] != 'd' ||
inqp->page_id[2] != 'i' || inqp->page_id[3] != 'd')
return SCSI_DH_NOSYS;
h->lun = inqp->lun[7]; /* Uses only the last byte */
for(i=0; i<ARRAY_LABEL_LEN-1; ++i)
*(array_name+i) = inqp->array_user_label[(2*i)+1];
*(array_name+ARRAY_LABEL_LEN-1) = '\0';
memset(array_id, 0, UNIQUE_ID_LEN);
memcpy(array_id, inqp->array_unique_id, inqp->array_uniq_id_len);
}
return err;
}
static int check_ownership(struct scsi_device *sdev, struct rdac_dh_data *h)
{
int err;
struct c9_inquiry *inqp;
h->state = RDAC_STATE_ACTIVE;
err = submit_inquiry(sdev, 0xC9, sizeof(struct c9_inquiry), h);
if (err == SCSI_DH_OK) {
inqp = &h->inq.c9;
/* detect the operating mode */
if ((inqp->avte_cvp >> 5) & 0x1)
h->mode = RDAC_MODE_IOSHIP; /* LUN in IOSHIP mode */
else if (inqp->avte_cvp >> 7)
h->mode = RDAC_MODE_AVT; /* LUN in AVT mode */
else
h->mode = RDAC_MODE; /* LUN in RDAC mode */
/* Update ownership */
if (inqp->avte_cvp & 0x1)
h->lun_state = RDAC_LUN_OWNED;
else {
h->lun_state = RDAC_LUN_UNOWNED;
if (h->mode == RDAC_MODE)
h->state = RDAC_STATE_PASSIVE;
}
/* Update path prio*/
if (inqp->path_prio & 0x1)
h->preferred = RDAC_PREFERRED;
else
h->preferred = RDAC_NON_PREFERRED;
}
return err;
}
static int initialize_controller(struct scsi_device *sdev,
struct rdac_dh_data *h, char *array_name, u8 *array_id)
{
int err, index;
struct c4_inquiry *inqp;
err = submit_inquiry(sdev, 0xC4, sizeof(struct c4_inquiry), h);
if (err == SCSI_DH_OK) {
inqp = &h->inq.c4;
/* get the controller index */
if (inqp->slot_id[1] == 0x31)
index = 0;
else
index = 1;
spin_lock(&list_lock);
h->ctlr = get_controller(index, array_name, array_id, sdev);
if (!h->ctlr)
err = SCSI_DH_RES_TEMP_UNAVAIL;
spin_unlock(&list_lock);
}
return err;
}
static int set_mode_select(struct scsi_device *sdev, struct rdac_dh_data *h)
{
int err;
struct c2_inquiry *inqp;
err = submit_inquiry(sdev, 0xC2, sizeof(struct c2_inquiry), h);
if (err == SCSI_DH_OK) {
inqp = &h->inq.c2;
/*
* If more than MODE6_MAX_LUN luns are supported, use
* mode select 10
*/
if (inqp->max_lun_supported >= MODE6_MAX_LUN)
h->ctlr->use_ms10 = 1;
else
h->ctlr->use_ms10 = 0;
}
return err;
}
static int mode_select_handle_sense(struct scsi_device *sdev,
unsigned char *sensebuf)
{
struct scsi_sense_hdr sense_hdr;
int err = SCSI_DH_IO, ret;
struct rdac_dh_data *h = get_rdac_data(sdev);
ret = scsi_normalize_sense(sensebuf, SCSI_SENSE_BUFFERSIZE, &sense_hdr);
if (!ret)
goto done;
switch (sense_hdr.sense_key) {
case NO_SENSE:
case ABORTED_COMMAND:
case UNIT_ATTENTION:
err = SCSI_DH_RETRY;
break;
case NOT_READY:
if (sense_hdr.asc == 0x04 && sense_hdr.ascq == 0x01)
/* LUN Not Ready and is in the Process of Becoming
* Ready
*/
err = SCSI_DH_RETRY;
break;
case ILLEGAL_REQUEST:
if (sense_hdr.asc == 0x91 && sense_hdr.ascq == 0x36)
/*
* Command Lock contention
*/
err = SCSI_DH_RETRY;
break;
default:
break;
}
RDAC_LOG(RDAC_LOG_FAILOVER, sdev, "array %s, ctlr %d, "
"MODE_SELECT returned with sense %02x/%02x/%02x",
(char *) h->ctlr->array_name, h->ctlr->index,
sense_hdr.sense_key, sense_hdr.asc, sense_hdr.ascq);
done:
return err;
}
static void send_mode_select(struct work_struct *work)
{
struct rdac_controller *ctlr =
container_of(work, struct rdac_controller, ms_work);
struct request *rq;
struct scsi_device *sdev = ctlr->ms_sdev;
struct rdac_dh_data *h = get_rdac_data(sdev);
struct request_queue *q = sdev->request_queue;
int err, retry_cnt = RDAC_RETRY_COUNT;
struct rdac_queue_data *tmp, *qdata;
LIST_HEAD(list);
spin_lock(&ctlr->ms_lock);
list_splice_init(&ctlr->ms_head, &list);
ctlr->ms_queued = 0;
ctlr->ms_sdev = NULL;
spin_unlock(&ctlr->ms_lock);
retry:
err = SCSI_DH_RES_TEMP_UNAVAIL;
rq = rdac_failover_get(sdev, h, &list);
if (!rq)
goto done;
RDAC_LOG(RDAC_LOG_FAILOVER, sdev, "array %s, ctlr %d, "
"%s MODE_SELECT command",
(char *) h->ctlr->array_name, h->ctlr->index,
(retry_cnt == RDAC_RETRY_COUNT) ? "queueing" : "retrying");
err = blk_execute_rq(q, NULL, rq, 1);
blk_put_request(rq);
if (err != SCSI_DH_OK) {
err = mode_select_handle_sense(sdev, h->sense);
if (err == SCSI_DH_RETRY && retry_cnt--)
goto retry;
}
if (err == SCSI_DH_OK) {
h->state = RDAC_STATE_ACTIVE;
RDAC_LOG(RDAC_LOG_FAILOVER, sdev, "array %s, ctlr %d, "
"MODE_SELECT completed",
(char *) h->ctlr->array_name, h->ctlr->index);
}
done:
list_for_each_entry_safe(qdata, tmp, &list, entry) {
list_del(&qdata->entry);
if (err == SCSI_DH_OK)
qdata->h->state = RDAC_STATE_ACTIVE;
if (qdata->callback_fn)
qdata->callback_fn(qdata->callback_data, err);
kfree(qdata);
}
return;
}
static int queue_mode_select(struct scsi_device *sdev,
activate_complete fn, void *data)
{
struct rdac_queue_data *qdata;
struct rdac_controller *ctlr;
qdata = kzalloc(sizeof(*qdata), GFP_KERNEL);
if (!qdata)
return SCSI_DH_RETRY;
qdata->h = get_rdac_data(sdev);
qdata->callback_fn = fn;
qdata->callback_data = data;
ctlr = qdata->h->ctlr;
spin_lock(&ctlr->ms_lock);
list_add_tail(&qdata->entry, &ctlr->ms_head);
if (!ctlr->ms_queued) {
ctlr->ms_queued = 1;
ctlr->ms_sdev = sdev;
queue_work(kmpath_rdacd, &ctlr->ms_work);
}
spin_unlock(&ctlr->ms_lock);
return SCSI_DH_OK;
}
static int rdac_activate(struct scsi_device *sdev,
activate_complete fn, void *data)
{
struct rdac_dh_data *h = get_rdac_data(sdev);
int err = SCSI_DH_OK;
int act = 0;
err = check_ownership(sdev, h);
if (err != SCSI_DH_OK)
goto done;
switch (h->mode) {
case RDAC_MODE:
if (h->lun_state == RDAC_LUN_UNOWNED)
act = 1;
break;
case RDAC_MODE_IOSHIP:
if ((h->lun_state == RDAC_LUN_UNOWNED) &&
(h->preferred == RDAC_PREFERRED))
act = 1;
break;
default:
break;
}
if (act) {
err = queue_mode_select(sdev, fn, data);
if (err == SCSI_DH_OK)
return 0;
}
done:
if (fn)
fn(data, err);
return 0;
}
static int rdac_prep_fn(struct scsi_device *sdev, struct request *req)
{
struct rdac_dh_data *h = get_rdac_data(sdev);
int ret = BLKPREP_OK;
if (h->state != RDAC_STATE_ACTIVE) {
ret = BLKPREP_KILL;
req->cmd_flags |= REQ_QUIET;
}
return ret;
}
static int rdac_check_sense(struct scsi_device *sdev,
struct scsi_sense_hdr *sense_hdr)
{
struct rdac_dh_data *h = get_rdac_data(sdev);
RDAC_LOG(RDAC_LOG_SENSE, sdev, "array %s, ctlr %d, "
"I/O returned with sense %02x/%02x/%02x",
(char *) h->ctlr->array_name, h->ctlr->index,
sense_hdr->sense_key, sense_hdr->asc, sense_hdr->ascq);
switch (sense_hdr->sense_key) {
case NOT_READY:
if (sense_hdr->asc == 0x04 && sense_hdr->ascq == 0x01)
/* LUN Not Ready - Logical Unit Not Ready and is in
* the process of becoming ready
* Just retry.
*/
return ADD_TO_MLQUEUE;
if (sense_hdr->asc == 0x04 && sense_hdr->ascq == 0x81)
/* LUN Not Ready - Storage firmware incompatible
* Manual code synchonisation required.
*
* Nothing we can do here. Try to bypass the path.
*/
return SUCCESS;
if (sense_hdr->asc == 0x04 && sense_hdr->ascq == 0xA1)
/* LUN Not Ready - Quiescense in progress
*
* Just retry and wait.
*/
return ADD_TO_MLQUEUE;
if (sense_hdr->asc == 0xA1 && sense_hdr->ascq == 0x02)
/* LUN Not Ready - Quiescense in progress
* or has been achieved
* Just retry.
*/
return ADD_TO_MLQUEUE;
break;
case ILLEGAL_REQUEST:
if (sense_hdr->asc == 0x94 && sense_hdr->ascq == 0x01) {
/* Invalid Request - Current Logical Unit Ownership.
* Controller is not the current owner of the LUN,
* Fail the path, so that the other path be used.
*/
h->state = RDAC_STATE_PASSIVE;
return SUCCESS;
}
break;
case UNIT_ATTENTION:
if (sense_hdr->asc == 0x29 && sense_hdr->ascq == 0x00)
/*
* Power On, Reset, or Bus Device Reset, just retry.
*/
return ADD_TO_MLQUEUE;
if (sense_hdr->asc == 0x8b && sense_hdr->ascq == 0x02)
/*
* Quiescence in progress , just retry.
*/
return ADD_TO_MLQUEUE;
break;
}
/* success just means we do not care what scsi-ml does */
return SCSI_RETURN_NOT_HANDLED;
}
static const struct scsi_dh_devlist rdac_dev_list[] = {
{"IBM", "1722"},
{"IBM", "1724"},
{"IBM", "1726"},
{"IBM", "1742"},
{"IBM", "1745"},
{"IBM", "1746"},
{"IBM", "1814"},
{"IBM", "1815"},
{"IBM", "1818"},
{"IBM", "3526"},
{"SGI", "TP9"},
{"SGI", "IS"},
{"STK", "OPENstorage D280"},
{"STK", "FLEXLINE 380"},
{"SUN", "CSM"},
{"SUN", "LCSM100"},
{"SUN", "STK6580_6780"},
{"SUN", "SUN_6180"},
{"SUN", "ArrayStorage"},
{"DELL", "MD3"},
{"NETAPP", "INF-01-00"},
{"LSI", "INF-01-00"},
{"ENGENIO", "INF-01-00"},
{NULL, NULL},
};
static bool rdac_match(struct scsi_device *sdev)
{
int i;
if (scsi_device_tpgs(sdev))
return false;
for (i = 0; rdac_dev_list[i].vendor; i++) {
if (!strncmp(sdev->vendor, rdac_dev_list[i].vendor,
strlen(rdac_dev_list[i].vendor)) &&
!strncmp(sdev->model, rdac_dev_list[i].model,
strlen(rdac_dev_list[i].model))) {
return true;
}
}
return false;
}
static int rdac_bus_attach(struct scsi_device *sdev);
static void rdac_bus_detach(struct scsi_device *sdev);
static struct scsi_device_handler rdac_dh = {
.name = RDAC_NAME,
.module = THIS_MODULE,
.devlist = rdac_dev_list,
.prep_fn = rdac_prep_fn,
.check_sense = rdac_check_sense,
.attach = rdac_bus_attach,
.detach = rdac_bus_detach,
.activate = rdac_activate,
.match = rdac_match,
};
static int rdac_bus_attach(struct scsi_device *sdev)
{
struct scsi_dh_data *scsi_dh_data;
struct rdac_dh_data *h;
unsigned long flags;
int err;
char array_name[ARRAY_LABEL_LEN];
char array_id[UNIQUE_ID_LEN];
scsi_dh_data = kzalloc(sizeof(*scsi_dh_data)
+ sizeof(*h) , GFP_KERNEL);
if (!scsi_dh_data) {
sdev_printk(KERN_ERR, sdev, "%s: Attach failed\n",
RDAC_NAME);
return -ENOMEM;
}
scsi_dh_data->scsi_dh = &rdac_dh;
h = (struct rdac_dh_data *) scsi_dh_data->buf;
h->lun = UNINITIALIZED_LUN;
h->state = RDAC_STATE_ACTIVE;
err = get_lun_info(sdev, h, array_name, array_id);
if (err != SCSI_DH_OK)
goto failed;
err = initialize_controller(sdev, h, array_name, array_id);
if (err != SCSI_DH_OK)
goto failed;
err = check_ownership(sdev, h);
if (err != SCSI_DH_OK)
goto clean_ctlr;
err = set_mode_select(sdev, h);
if (err != SCSI_DH_OK)
goto clean_ctlr;
if (!try_module_get(THIS_MODULE))
goto clean_ctlr;
spin_lock_irqsave(sdev->request_queue->queue_lock, flags);
sdev->scsi_dh_data = scsi_dh_data;
spin_unlock_irqrestore(sdev->request_queue->queue_lock, flags);
sdev_printk(KERN_NOTICE, sdev,
"%s: LUN %d (%s) (%s)\n",
RDAC_NAME, h->lun, mode[(int)h->mode],
lun_state[(int)h->lun_state]);
return 0;
clean_ctlr:
spin_lock(&list_lock);
kref_put(&h->ctlr->kref, release_controller);
spin_unlock(&list_lock);
failed:
kfree(scsi_dh_data);
sdev_printk(KERN_ERR, sdev, "%s: not attached\n",
RDAC_NAME);
return -EINVAL;
}
static void rdac_bus_detach( struct scsi_device *sdev )
{
struct scsi_dh_data *scsi_dh_data;
struct rdac_dh_data *h;
unsigned long flags;
scsi_dh_data = sdev->scsi_dh_data;
h = (struct rdac_dh_data *) scsi_dh_data->buf;
if (h->ctlr && h->ctlr->ms_queued)
flush_workqueue(kmpath_rdacd);
spin_lock_irqsave(sdev->request_queue->queue_lock, flags);
sdev->scsi_dh_data = NULL;
spin_unlock_irqrestore(sdev->request_queue->queue_lock, flags);
spin_lock(&list_lock);
if (h->ctlr)
kref_put(&h->ctlr->kref, release_controller);
spin_unlock(&list_lock);
kfree(scsi_dh_data);
module_put(THIS_MODULE);
sdev_printk(KERN_NOTICE, sdev, "%s: Detached\n", RDAC_NAME);
}
static int __init rdac_init(void)
{
int r;
r = scsi_register_device_handler(&rdac_dh);
if (r != 0) {
printk(KERN_ERR "Failed to register scsi device handler.");
goto done;
}
/*
* Create workqueue to handle mode selects for rdac
*/
kmpath_rdacd = create_singlethread_workqueue("kmpath_rdacd");
if (!kmpath_rdacd) {
scsi_unregister_device_handler(&rdac_dh);
printk(KERN_ERR "kmpath_rdacd creation failed.\n");
r = -EINVAL;
}
done:
return r;
}
static void __exit rdac_exit(void)
{
destroy_workqueue(kmpath_rdacd);
scsi_unregister_device_handler(&rdac_dh);
}
module_init(rdac_init);
module_exit(rdac_exit);
MODULE_DESCRIPTION("Multipath LSI/Engenio/NetApp E-Series RDAC driver");
MODULE_AUTHOR("Mike Christie, Chandra Seetharaman");
MODULE_VERSION("01.00.0000.0000");
MODULE_LICENSE("GPL");
| gpl-2.0 |
RegaliaEzz/Hexa-N9208 | drivers/net/irda/irda-usb.c | 2658 | 59383 | /*****************************************************************************
*
* Filename: irda-usb.c
* Version: 0.10
* Description: IrDA-USB Driver
* Status: Experimental
* Author: Dag Brattli <dag@brattli.net>
*
* Copyright (C) 2000, Roman Weissgaerber <weissg@vienna.at>
* Copyright (C) 2001, Dag Brattli <dag@brattli.net>
* Copyright (C) 2001, Jean Tourrilhes <jt@hpl.hp.com>
* Copyright (C) 2004, SigmaTel, Inc. <irquality@sigmatel.com>
* Copyright (C) 2005, Milan Beno <beno@pobox.sk>
* Copyright (C) 2006, Nick Fedchik <nick@fedchik.org.ua>
*
* 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.
*
*****************************************************************************/
/*
* IMPORTANT NOTE
* --------------
*
* As of kernel 2.5.20, this is the state of compliance and testing of
* this driver (irda-usb) with regards to the USB low level drivers...
*
* This driver has been tested SUCCESSFULLY with the following drivers :
* o usb-uhci-hcd (For Intel/Via USB controllers)
* o uhci-hcd (Alternate/JE driver for Intel/Via USB controllers)
* o ohci-hcd (For other USB controllers)
*
* This driver has NOT been tested with the following drivers :
* o ehci-hcd (USB 2.0 controllers)
*
* Note that all HCD drivers do URB_ZERO_PACKET and timeout properly,
* so we don't have to worry about that anymore.
* One common problem is the failure to set the address on the dongle,
* but this happens before the driver gets loaded...
*
* Jean II
*/
/*------------------------------------------------------------------*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <linux/slab.h>
#include <linux/rtnetlink.h>
#include <linux/usb.h>
#include <linux/firmware.h>
#include "irda-usb.h"
/*------------------------------------------------------------------*/
static int qos_mtt_bits = 0;
/* These are the currently known IrDA USB dongles. Add new dongles here */
static struct usb_device_id dongles[] = {
/* ACTiSYS Corp., ACT-IR2000U FIR-USB Adapter */
{ USB_DEVICE(0x9c4, 0x011), .driver_info = IUC_SPEED_BUG | IUC_NO_WINDOW },
/* Look like ACTiSYS, Report : IBM Corp., IBM UltraPort IrDA */
{ USB_DEVICE(0x4428, 0x012), .driver_info = IUC_SPEED_BUG | IUC_NO_WINDOW },
/* KC Technology Inc., KC-180 USB IrDA Device */
{ USB_DEVICE(0x50f, 0x180), .driver_info = IUC_SPEED_BUG | IUC_NO_WINDOW },
/* Extended Systems, Inc., XTNDAccess IrDA USB (ESI-9685) */
{ USB_DEVICE(0x8e9, 0x100), .driver_info = IUC_SPEED_BUG | IUC_NO_WINDOW },
/* SigmaTel STIR4210/4220/4116 USB IrDA (VFIR) Bridge */
{ USB_DEVICE(0x66f, 0x4210), .driver_info = IUC_STIR421X | IUC_SPEED_BUG },
{ USB_DEVICE(0x66f, 0x4220), .driver_info = IUC_STIR421X | IUC_SPEED_BUG },
{ USB_DEVICE(0x66f, 0x4116), .driver_info = IUC_STIR421X | IUC_SPEED_BUG },
{ .match_flags = USB_DEVICE_ID_MATCH_INT_CLASS |
USB_DEVICE_ID_MATCH_INT_SUBCLASS,
.bInterfaceClass = USB_CLASS_APP_SPEC,
.bInterfaceSubClass = USB_CLASS_IRDA,
.driver_info = IUC_DEFAULT, },
{ }, /* The end */
};
/*
* Important note :
* Devices based on the SigmaTel chipset (0x66f, 0x4200) are not designed
* using the "USB-IrDA specification" (yes, there exist such a thing), and
* therefore not supported by this driver (don't add them above).
* There is a Linux driver, stir4200, that support those USB devices.
* Jean II
*/
MODULE_DEVICE_TABLE(usb, dongles);
/*------------------------------------------------------------------*/
static void irda_usb_init_qos(struct irda_usb_cb *self) ;
static struct irda_class_desc *irda_usb_find_class_desc(struct usb_interface *intf);
static void irda_usb_disconnect(struct usb_interface *intf);
static void irda_usb_change_speed_xbofs(struct irda_usb_cb *self);
static netdev_tx_t irda_usb_hard_xmit(struct sk_buff *skb,
struct net_device *dev);
static int irda_usb_open(struct irda_usb_cb *self);
static void irda_usb_close(struct irda_usb_cb *self);
static void speed_bulk_callback(struct urb *urb);
static void write_bulk_callback(struct urb *urb);
static void irda_usb_receive(struct urb *urb);
static void irda_usb_rx_defer_expired(unsigned long data);
static int irda_usb_net_open(struct net_device *dev);
static int irda_usb_net_close(struct net_device *dev);
static int irda_usb_net_ioctl(struct net_device *dev, struct ifreq *rq, int cmd);
static void irda_usb_net_timeout(struct net_device *dev);
/************************ TRANSMIT ROUTINES ************************/
/*
* Receive packets from the IrDA stack and send them on the USB pipe.
* Handle speed change, timeout and lot's of ugliness...
*/
/*------------------------------------------------------------------*/
/*
* Function irda_usb_build_header(self, skb, header)
*
* Builds USB-IrDA outbound header
*
* When we send an IrDA frame over an USB pipe, we add to it a 1 byte
* header. This function create this header with the proper values.
*
* Important note : the USB-IrDA spec 1.0 say very clearly in chapter 5.4.2.2
* that the setting of the link speed and xbof number in this outbound header
* should be applied *AFTER* the frame has been sent.
* Unfortunately, some devices are not compliant with that... It seems that
* reading the spec is far too difficult...
* Jean II
*/
static void irda_usb_build_header(struct irda_usb_cb *self,
__u8 *header,
int force)
{
/* Here we check if we have an STIR421x chip,
* and if either speed or xbofs (or both) needs
* to be changed.
*/
if (self->capability & IUC_STIR421X &&
((self->new_speed != -1) || (self->new_xbofs != -1))) {
/* With STIR421x, speed and xBOFs must be set at the same
* time, even if only one of them changes.
*/
if (self->new_speed == -1)
self->new_speed = self->speed ;
if (self->new_xbofs == -1)
self->new_xbofs = self->xbofs ;
}
/* Set the link speed */
if (self->new_speed != -1) {
/* Hum... Ugly hack :-(
* Some device are not compliant with the spec and change
* parameters *before* sending the frame. - Jean II
*/
if ((self->capability & IUC_SPEED_BUG) &&
(!force) && (self->speed != -1)) {
/* No speed and xbofs change here
* (we'll do it later in the write callback) */
IRDA_DEBUG(2, "%s(), not changing speed yet\n", __func__);
*header = 0;
return;
}
IRDA_DEBUG(2, "%s(), changing speed to %d\n", __func__, self->new_speed);
self->speed = self->new_speed;
/* We will do ` self->new_speed = -1; ' in the completion
* handler just in case the current URB fail - Jean II */
switch (self->speed) {
case 2400:
*header = SPEED_2400;
break;
default:
case 9600:
*header = SPEED_9600;
break;
case 19200:
*header = SPEED_19200;
break;
case 38400:
*header = SPEED_38400;
break;
case 57600:
*header = SPEED_57600;
break;
case 115200:
*header = SPEED_115200;
break;
case 576000:
*header = SPEED_576000;
break;
case 1152000:
*header = SPEED_1152000;
break;
case 4000000:
*header = SPEED_4000000;
self->new_xbofs = 0;
break;
case 16000000:
*header = SPEED_16000000;
self->new_xbofs = 0;
break;
}
} else
/* No change */
*header = 0;
/* Set the negotiated additional XBOFS */
if (self->new_xbofs != -1) {
IRDA_DEBUG(2, "%s(), changing xbofs to %d\n", __func__, self->new_xbofs);
self->xbofs = self->new_xbofs;
/* We will do ` self->new_xbofs = -1; ' in the completion
* handler just in case the current URB fail - Jean II */
switch (self->xbofs) {
case 48:
*header |= 0x10;
break;
case 28:
case 24: /* USB spec 1.0 says 24 */
*header |= 0x20;
break;
default:
case 12:
*header |= 0x30;
break;
case 5: /* Bug in IrLAP spec? (should be 6) */
case 6:
*header |= 0x40;
break;
case 3:
*header |= 0x50;
break;
case 2:
*header |= 0x60;
break;
case 1:
*header |= 0x70;
break;
case 0:
*header |= 0x80;
break;
}
}
}
/*
* calculate turnaround time for SigmaTel header
*/
static __u8 get_turnaround_time(struct sk_buff *skb)
{
int turnaround_time = irda_get_mtt(skb);
if ( turnaround_time == 0 )
return 0;
else if ( turnaround_time <= 10 )
return 1;
else if ( turnaround_time <= 50 )
return 2;
else if ( turnaround_time <= 100 )
return 3;
else if ( turnaround_time <= 500 )
return 4;
else if ( turnaround_time <= 1000 )
return 5;
else if ( turnaround_time <= 5000 )
return 6;
else
return 7;
}
/*------------------------------------------------------------------*/
/*
* Send a command to change the speed of the dongle
* Need to be called with spinlock on.
*/
static void irda_usb_change_speed_xbofs(struct irda_usb_cb *self)
{
__u8 *frame;
struct urb *urb;
int ret;
IRDA_DEBUG(2, "%s(), speed=%d, xbofs=%d\n", __func__,
self->new_speed, self->new_xbofs);
/* Grab the speed URB */
urb = self->speed_urb;
if (urb->status != 0) {
IRDA_WARNING("%s(), URB still in use!\n", __func__);
return;
}
/* Allocate the fake frame */
frame = self->speed_buff;
/* Set the new speed and xbofs in this fake frame */
irda_usb_build_header(self, frame, 1);
if (self->capability & IUC_STIR421X) {
if (frame[0] == 0) return ; // do nothing if no change
frame[1] = 0; // other parameters don't change here
frame[2] = 0;
}
/* Submit the 0 length IrDA frame to trigger new speed settings */
usb_fill_bulk_urb(urb, self->usbdev,
usb_sndbulkpipe(self->usbdev, self->bulk_out_ep),
frame, IRDA_USB_SPEED_MTU,
speed_bulk_callback, self);
urb->transfer_buffer_length = self->header_length;
urb->transfer_flags = 0;
/* Irq disabled -> GFP_ATOMIC */
if ((ret = usb_submit_urb(urb, GFP_ATOMIC))) {
IRDA_WARNING("%s(), failed Speed URB\n", __func__);
}
}
/*------------------------------------------------------------------*/
/*
* Speed URB callback
* Now, we can only get called for the speed URB.
*/
static void speed_bulk_callback(struct urb *urb)
{
struct irda_usb_cb *self = urb->context;
IRDA_DEBUG(2, "%s()\n", __func__);
/* We should always have a context */
IRDA_ASSERT(self != NULL, return;);
/* We should always be called for the speed URB */
IRDA_ASSERT(urb == self->speed_urb, return;);
/* Check for timeout and other USB nasties */
if (urb->status != 0) {
/* I get a lot of -ECONNABORTED = -103 here - Jean II */
IRDA_DEBUG(0, "%s(), URB complete status %d, transfer_flags 0x%04X\n", __func__, urb->status, urb->transfer_flags);
/* Don't do anything here, that might confuse the USB layer.
* Instead, we will wait for irda_usb_net_timeout(), the
* network layer watchdog, to fix the situation.
* Jean II */
/* A reset of the dongle might be welcomed here - Jean II */
return;
}
/* urb is now available */
//urb->status = 0; -> tested above
/* New speed and xbof is now committed in hardware */
self->new_speed = -1;
self->new_xbofs = -1;
/* Allow the stack to send more packets */
netif_wake_queue(self->netdev);
}
/*------------------------------------------------------------------*/
/*
* Send an IrDA frame to the USB dongle (for transmission)
*/
static netdev_tx_t irda_usb_hard_xmit(struct sk_buff *skb,
struct net_device *netdev)
{
struct irda_usb_cb *self = netdev_priv(netdev);
struct urb *urb = self->tx_urb;
unsigned long flags;
s32 speed;
s16 xbofs;
int res, mtt;
IRDA_DEBUG(4, "%s() on %s\n", __func__, netdev->name);
netif_stop_queue(netdev);
/* Protect us from USB callbacks, net watchdog and else. */
spin_lock_irqsave(&self->lock, flags);
/* Check if the device is still there.
* We need to check self->present under the spinlock because
* of irda_usb_disconnect() is synchronous - Jean II */
if (!self->present) {
IRDA_DEBUG(0, "%s(), Device is gone...\n", __func__);
goto drop;
}
/* Check if we need to change the number of xbofs */
xbofs = irda_get_next_xbofs(skb);
if ((xbofs != self->xbofs) && (xbofs != -1)) {
self->new_xbofs = xbofs;
}
/* Check if we need to change the speed */
speed = irda_get_next_speed(skb);
if ((speed != self->speed) && (speed != -1)) {
/* Set the desired speed */
self->new_speed = speed;
/* Check for empty frame */
if (!skb->len) {
/* IrLAP send us an empty frame to make us change the
* speed. Changing speed with the USB adapter is in
* fact sending an empty frame to the adapter, so we
* could just let the present function do its job.
* However, we would wait for min turn time,
* do an extra memcpy and increment packet counters...
* Jean II */
irda_usb_change_speed_xbofs(self);
netdev->trans_start = jiffies;
/* Will netif_wake_queue() in callback */
goto drop;
}
}
if (urb->status != 0) {
IRDA_WARNING("%s(), URB still in use!\n", __func__);
goto drop;
}
skb_copy_from_linear_data(skb, self->tx_buff + self->header_length, skb->len);
/* Change setting for next frame */
if (self->capability & IUC_STIR421X) {
__u8 turnaround_time;
__u8* frame = self->tx_buff;
turnaround_time = get_turnaround_time( skb );
irda_usb_build_header(self, frame, 0);
frame[2] = turnaround_time;
if ((skb->len != 0) &&
((skb->len % 128) == 0) &&
((skb->len % 512) != 0)) {
/* add extra byte for special SigmaTel feature */
frame[1] = 1;
skb_put(skb, 1);
} else {
frame[1] = 0;
}
} else {
irda_usb_build_header(self, self->tx_buff, 0);
}
/* FIXME: Make macro out of this one */
((struct irda_skb_cb *)skb->cb)->context = self;
usb_fill_bulk_urb(urb, self->usbdev,
usb_sndbulkpipe(self->usbdev, self->bulk_out_ep),
self->tx_buff, skb->len + self->header_length,
write_bulk_callback, skb);
/* This flag (URB_ZERO_PACKET) indicates that what we send is not
* a continuous stream of data but separate packets.
* In this case, the USB layer will insert an empty USB frame (TD)
* after each of our packets that is exact multiple of the frame size.
* This is how the dongle will detect the end of packet - Jean II */
urb->transfer_flags = URB_ZERO_PACKET;
/* Generate min turn time. FIXME: can we do better than this? */
/* Trying to a turnaround time at this level is trying to measure
* processor clock cycle with a wrist-watch, approximate at best...
*
* What we know is the last time we received a frame over USB.
* Due to latency over USB that depend on the USB load, we don't
* know when this frame was received over IrDA (a few ms before ?)
* Then, same story for our outgoing frame...
*
* In theory, the USB dongle is supposed to handle the turnaround
* by itself (spec 1.0, chater 4, page 6). Who knows ??? That's
* why this code is enabled only for dongles that doesn't meet
* the spec.
* Jean II */
if (self->capability & IUC_NO_TURN) {
mtt = irda_get_mtt(skb);
if (mtt) {
int diff;
do_gettimeofday(&self->now);
diff = self->now.tv_usec - self->stamp.tv_usec;
#ifdef IU_USB_MIN_RTT
/* Factor in USB delays -> Get rid of udelay() that
* would be lost in the noise - Jean II */
diff += IU_USB_MIN_RTT;
#endif /* IU_USB_MIN_RTT */
/* If the usec counter did wraparound, the diff will
* go negative (tv_usec is a long), so we need to
* correct it by one second. Jean II */
if (diff < 0)
diff += 1000000;
/* Check if the mtt is larger than the time we have
* already used by all the protocol processing
*/
if (mtt > diff) {
mtt -= diff;
if (mtt > 1000)
mdelay(mtt/1000);
else
udelay(mtt);
}
}
}
/* Ask USB to send the packet - Irq disabled -> GFP_ATOMIC */
if ((res = usb_submit_urb(urb, GFP_ATOMIC))) {
IRDA_WARNING("%s(), failed Tx URB\n", __func__);
netdev->stats.tx_errors++;
/* Let USB recover : We will catch that in the watchdog */
/*netif_start_queue(netdev);*/
} else {
/* Increment packet stats */
netdev->stats.tx_packets++;
netdev->stats.tx_bytes += skb->len;
netdev->trans_start = jiffies;
}
spin_unlock_irqrestore(&self->lock, flags);
return NETDEV_TX_OK;
drop:
/* Drop silently the skb and exit */
dev_kfree_skb(skb);
spin_unlock_irqrestore(&self->lock, flags);
return NETDEV_TX_OK;
}
/*------------------------------------------------------------------*/
/*
* Note : this function will be called only for tx_urb...
*/
static void write_bulk_callback(struct urb *urb)
{
unsigned long flags;
struct sk_buff *skb = urb->context;
struct irda_usb_cb *self = ((struct irda_skb_cb *) skb->cb)->context;
IRDA_DEBUG(2, "%s()\n", __func__);
/* We should always have a context */
IRDA_ASSERT(self != NULL, return;);
/* We should always be called for the speed URB */
IRDA_ASSERT(urb == self->tx_urb, return;);
/* Free up the skb */
dev_kfree_skb_any(skb);
urb->context = NULL;
/* Check for timeout and other USB nasties */
if (urb->status != 0) {
/* I get a lot of -ECONNABORTED = -103 here - Jean II */
IRDA_DEBUG(0, "%s(), URB complete status %d, transfer_flags 0x%04X\n", __func__, urb->status, urb->transfer_flags);
/* Don't do anything here, that might confuse the USB layer,
* and we could go in recursion and blow the kernel stack...
* Instead, we will wait for irda_usb_net_timeout(), the
* network layer watchdog, to fix the situation.
* Jean II */
/* A reset of the dongle might be welcomed here - Jean II */
return;
}
/* urb is now available */
//urb->status = 0; -> tested above
/* Make sure we read self->present properly */
spin_lock_irqsave(&self->lock, flags);
/* If the network is closed, stop everything */
if ((!self->netopen) || (!self->present)) {
IRDA_DEBUG(0, "%s(), Network is gone...\n", __func__);
spin_unlock_irqrestore(&self->lock, flags);
return;
}
/* If changes to speed or xbofs is pending... */
if ((self->new_speed != -1) || (self->new_xbofs != -1)) {
if ((self->new_speed != self->speed) ||
(self->new_xbofs != self->xbofs)) {
/* We haven't changed speed yet (because of
* IUC_SPEED_BUG), so do it now - Jean II */
IRDA_DEBUG(1, "%s(), Changing speed now...\n", __func__);
irda_usb_change_speed_xbofs(self);
} else {
/* New speed and xbof is now committed in hardware */
self->new_speed = -1;
self->new_xbofs = -1;
/* Done, waiting for next packet */
netif_wake_queue(self->netdev);
}
} else {
/* Otherwise, allow the stack to send more packets */
netif_wake_queue(self->netdev);
}
spin_unlock_irqrestore(&self->lock, flags);
}
/*------------------------------------------------------------------*/
/*
* Watchdog timer from the network layer.
* After a predetermined timeout, if we don't give confirmation that
* the packet has been sent (i.e. no call to netif_wake_queue()),
* the network layer will call this function.
* Note that URB that we submit have also a timeout. When the URB timeout
* expire, the normal URB callback is called (write_bulk_callback()).
*/
static void irda_usb_net_timeout(struct net_device *netdev)
{
unsigned long flags;
struct irda_usb_cb *self = netdev_priv(netdev);
struct urb *urb;
int done = 0; /* If we have made any progress */
IRDA_DEBUG(0, "%s(), Network layer thinks we timed out!\n", __func__);
IRDA_ASSERT(self != NULL, return;);
/* Protect us from USB callbacks, net Tx and else. */
spin_lock_irqsave(&self->lock, flags);
/* self->present *MUST* be read under spinlock */
if (!self->present) {
IRDA_WARNING("%s(), device not present!\n", __func__);
netif_stop_queue(netdev);
spin_unlock_irqrestore(&self->lock, flags);
return;
}
/* Check speed URB */
urb = self->speed_urb;
if (urb->status != 0) {
IRDA_DEBUG(0, "%s: Speed change timed out, urb->status=%d, urb->transfer_flags=0x%04X\n", netdev->name, urb->status, urb->transfer_flags);
switch (urb->status) {
case -EINPROGRESS:
usb_unlink_urb(urb);
/* Note : above will *NOT* call netif_wake_queue()
* in completion handler, we will come back here.
* Jean II */
done = 1;
break;
case -ECONNRESET:
case -ENOENT: /* urb unlinked by us */
default: /* ??? - Play safe */
urb->status = 0;
netif_wake_queue(self->netdev);
done = 1;
break;
}
}
/* Check Tx URB */
urb = self->tx_urb;
if (urb->status != 0) {
struct sk_buff *skb = urb->context;
IRDA_DEBUG(0, "%s: Tx timed out, urb->status=%d, urb->transfer_flags=0x%04X\n", netdev->name, urb->status, urb->transfer_flags);
/* Increase error count */
netdev->stats.tx_errors++;
#ifdef IU_BUG_KICK_TIMEOUT
/* Can't be a bad idea to reset the speed ;-) - Jean II */
if(self->new_speed == -1)
self->new_speed = self->speed;
if(self->new_xbofs == -1)
self->new_xbofs = self->xbofs;
irda_usb_change_speed_xbofs(self);
#endif /* IU_BUG_KICK_TIMEOUT */
switch (urb->status) {
case -EINPROGRESS:
usb_unlink_urb(urb);
/* Note : above will *NOT* call netif_wake_queue()
* in completion handler, because urb->status will
* be -ENOENT. We will fix that at the next watchdog,
* leaving more time to USB to recover...
* Jean II */
done = 1;
break;
case -ECONNRESET:
case -ENOENT: /* urb unlinked by us */
default: /* ??? - Play safe */
if(skb != NULL) {
dev_kfree_skb_any(skb);
urb->context = NULL;
}
urb->status = 0;
netif_wake_queue(self->netdev);
done = 1;
break;
}
}
spin_unlock_irqrestore(&self->lock, flags);
/* Maybe we need a reset */
/* Note : Some drivers seem to use a usb_set_interface() when they
* need to reset the hardware. Hum...
*/
/* if(done == 0) */
}
/************************* RECEIVE ROUTINES *************************/
/*
* Receive packets from the USB layer stack and pass them to the IrDA stack.
* Try to work around USB failures...
*/
/*
* Note :
* Some of you may have noticed that most dongle have an interrupt in pipe
* that we don't use. Here is the little secret...
* When we hang a Rx URB on the bulk in pipe, it generates some USB traffic
* in every USB frame. This is unnecessary overhead.
* The interrupt in pipe will generate an event every time a packet is
* received. Reading an interrupt pipe adds minimal overhead, but has some
* latency (~1ms).
* If we are connected (speed != 9600), we want to minimise latency, so
* we just always hang the Rx URB and ignore the interrupt.
* If we are not connected (speed == 9600), there is usually no Rx traffic,
* and we want to minimise the USB overhead. In this case we should wait
* on the interrupt pipe and hang the Rx URB only when an interrupt is
* received.
* Jean II
*
* Note : don't read the above as what we are currently doing, but as
* something we could do with KC dongle. Also don't forget that the
* interrupt pipe is not part of the original standard, so this would
* need to be optional...
* Jean II
*/
/*------------------------------------------------------------------*/
/*
* Submit a Rx URB to the USB layer to handle reception of a frame
* Mostly called by the completion callback of the previous URB.
*
* Jean II
*/
static void irda_usb_submit(struct irda_usb_cb *self, struct sk_buff *skb, struct urb *urb)
{
struct irda_skb_cb *cb;
int ret;
IRDA_DEBUG(2, "%s()\n", __func__);
/* This should never happen */
IRDA_ASSERT(skb != NULL, return;);
IRDA_ASSERT(urb != NULL, return;);
/* Save ourselves in the skb */
cb = (struct irda_skb_cb *) skb->cb;
cb->context = self;
/* Reinitialize URB */
usb_fill_bulk_urb(urb, self->usbdev,
usb_rcvbulkpipe(self->usbdev, self->bulk_in_ep),
skb->data, IRDA_SKB_MAX_MTU,
irda_usb_receive, skb);
urb->status = 0;
/* Can be called from irda_usb_receive (irq handler) -> GFP_ATOMIC */
ret = usb_submit_urb(urb, GFP_ATOMIC);
if (ret) {
/* If this ever happen, we are in deep s***.
* Basically, the Rx path will stop... */
IRDA_WARNING("%s(), Failed to submit Rx URB %d\n",
__func__, ret);
}
}
/*------------------------------------------------------------------*/
/*
* Function irda_usb_receive(urb)
*
* Called by the USB subsystem when a frame has been received
*
*/
static void irda_usb_receive(struct urb *urb)
{
struct sk_buff *skb = (struct sk_buff *) urb->context;
struct irda_usb_cb *self;
struct irda_skb_cb *cb;
struct sk_buff *newskb;
struct sk_buff *dataskb;
struct urb *next_urb;
unsigned int len, docopy;
IRDA_DEBUG(2, "%s(), len=%d\n", __func__, urb->actual_length);
/* Find ourselves */
cb = (struct irda_skb_cb *) skb->cb;
IRDA_ASSERT(cb != NULL, return;);
self = (struct irda_usb_cb *) cb->context;
IRDA_ASSERT(self != NULL, return;);
/* If the network is closed or the device gone, stop everything */
if ((!self->netopen) || (!self->present)) {
IRDA_DEBUG(0, "%s(), Network is gone!\n", __func__);
/* Don't re-submit the URB : will stall the Rx path */
return;
}
/* Check the status */
if (urb->status != 0) {
switch (urb->status) {
case -EILSEQ:
self->netdev->stats.rx_crc_errors++;
/* Also precursor to a hot-unplug on UHCI. */
/* Fallthrough... */
case -ECONNRESET:
/* Random error, if I remember correctly */
/* uhci_cleanup_unlink() is going to kill the Rx
* URB just after we return. No problem, at this
* point the URB will be idle ;-) - Jean II */
case -ESHUTDOWN:
/* That's usually a hot-unplug. Submit will fail... */
case -ETIME:
/* Usually precursor to a hot-unplug on OHCI. */
default:
self->netdev->stats.rx_errors++;
IRDA_DEBUG(0, "%s(), RX status %d, transfer_flags 0x%04X\n", __func__, urb->status, urb->transfer_flags);
break;
}
/* If we received an error, we don't want to resubmit the
* Rx URB straight away but to give the USB layer a little
* bit of breathing room.
* We are in the USB thread context, therefore there is a
* danger of recursion (new URB we submit fails, we come
* back here).
* With recent USB stack (2.6.15+), I'm seeing that on
* hot unplug of the dongle...
* Lowest effective timer is 10ms...
* Jean II */
self->rx_defer_timer.function = irda_usb_rx_defer_expired;
self->rx_defer_timer.data = (unsigned long) urb;
mod_timer(&self->rx_defer_timer, jiffies + (10 * HZ / 1000));
return;
}
/* Check for empty frames */
if (urb->actual_length <= self->header_length) {
IRDA_WARNING("%s(), empty frame!\n", __func__);
goto done;
}
/*
* Remember the time we received this frame, so we can
* reduce the min turn time a bit since we will know
* how much time we have used for protocol processing
*/
do_gettimeofday(&self->stamp);
/* Check if we need to copy the data to a new skb or not.
* For most frames, we use ZeroCopy and pass the already
* allocated skb up the stack.
* If the frame is small, it is more efficient to copy it
* to save memory (copy will be fast anyway - that's
* called Rx-copy-break). Jean II */
docopy = (urb->actual_length < IRDA_RX_COPY_THRESHOLD);
/* Allocate a new skb */
if (self->capability & IUC_STIR421X)
newskb = dev_alloc_skb(docopy ? urb->actual_length :
IRDA_SKB_MAX_MTU +
USB_IRDA_STIR421X_HEADER);
else
newskb = dev_alloc_skb(docopy ? urb->actual_length :
IRDA_SKB_MAX_MTU);
if (!newskb) {
self->netdev->stats.rx_dropped++;
/* We could deliver the current skb, but this would stall
* the Rx path. Better drop the packet... Jean II */
goto done;
}
/* Make sure IP header get aligned (IrDA header is 5 bytes) */
/* But IrDA-USB header is 1 byte. Jean II */
//skb_reserve(newskb, USB_IRDA_HEADER - 1);
if(docopy) {
/* Copy packet, so we can recycle the original */
skb_copy_from_linear_data(skb, newskb->data, urb->actual_length);
/* Deliver this new skb */
dataskb = newskb;
/* And hook the old skb to the URB
* Note : we don't need to "clean up" the old skb,
* as we never touched it. Jean II */
} else {
/* We are using ZeroCopy. Deliver old skb */
dataskb = skb;
/* And hook the new skb to the URB */
skb = newskb;
}
/* Set proper length on skb & remove USB-IrDA header */
skb_put(dataskb, urb->actual_length);
skb_pull(dataskb, self->header_length);
/* Ask the networking layer to queue the packet for the IrDA stack */
dataskb->dev = self->netdev;
skb_reset_mac_header(dataskb);
dataskb->protocol = htons(ETH_P_IRDA);
len = dataskb->len;
netif_rx(dataskb);
/* Keep stats up to date */
self->netdev->stats.rx_bytes += len;
self->netdev->stats.rx_packets++;
done:
/* Note : at this point, the URB we've just received (urb)
* is still referenced by the USB layer. For example, if we
* have received a -ECONNRESET, uhci_cleanup_unlink() will
* continue to process it (in fact, cleaning it up).
* If we were to submit this URB, disaster would ensue.
* Therefore, we submit our idle URB, and put this URB in our
* idle slot....
* Jean II */
/* Note : with this scheme, we could submit the idle URB before
* processing the Rx URB. I don't think it would buy us anything as
* we are running in the USB thread context. Jean II */
next_urb = self->idle_rx_urb;
/* Recycle Rx URB : Now, the idle URB is the present one */
urb->context = NULL;
self->idle_rx_urb = urb;
/* Submit the idle URB to replace the URB we've just received.
* Do it last to avoid race conditions... Jean II */
irda_usb_submit(self, skb, next_urb);
}
/*------------------------------------------------------------------*/
/*
* In case of errors, we want the USB layer to have time to recover.
* Now, it is time to resubmit ouur Rx URB...
*/
static void irda_usb_rx_defer_expired(unsigned long data)
{
struct urb *urb = (struct urb *) data;
struct sk_buff *skb = (struct sk_buff *) urb->context;
struct irda_usb_cb *self;
struct irda_skb_cb *cb;
struct urb *next_urb;
IRDA_DEBUG(2, "%s()\n", __func__);
/* Find ourselves */
cb = (struct irda_skb_cb *) skb->cb;
IRDA_ASSERT(cb != NULL, return;);
self = (struct irda_usb_cb *) cb->context;
IRDA_ASSERT(self != NULL, return;);
/* Same stuff as when Rx is done, see above... */
next_urb = self->idle_rx_urb;
urb->context = NULL;
self->idle_rx_urb = urb;
irda_usb_submit(self, skb, next_urb);
}
/*------------------------------------------------------------------*/
/*
* Callbak from IrDA layer. IrDA wants to know if we have
* started receiving anything.
*/
static int irda_usb_is_receiving(struct irda_usb_cb *self)
{
/* Note : because of the way UHCI works, it's almost impossible
* to get this info. The Controller DMA directly to memory and
* signal only when the whole frame is finished. To know if the
* first TD of the URB has been filled or not seems hard work...
*
* The other solution would be to use the "receiving" command
* on the default decriptor with a usb_control_msg(), but that
* would add USB traffic and would return result only in the
* next USB frame (~1ms).
*
* I've been told that current dongles send status info on their
* interrupt endpoint, and that's what the Windows driver uses
* to know this info. Unfortunately, this is not yet in the spec...
*
* Jean II
*/
return 0; /* For now */
}
#define STIR421X_PATCH_PRODUCT_VER "Product Version: "
#define STIR421X_PATCH_STMP_TAG "STMP"
#define STIR421X_PATCH_CODE_OFFSET 512 /* patch image starts before here */
/* marks end of patch file header (PC DOS text file EOF character) */
#define STIR421X_PATCH_END_OF_HDR_TAG 0x1A
#define STIR421X_PATCH_BLOCK_SIZE 1023
/*
* Function stir421x_fwupload (struct irda_usb_cb *self,
* unsigned char *patch,
* const unsigned int patch_len)
*
* Upload firmware code to SigmaTel 421X IRDA-USB dongle
*/
static int stir421x_fw_upload(struct irda_usb_cb *self,
const unsigned char *patch,
const unsigned int patch_len)
{
int ret = -ENOMEM;
int actual_len = 0;
unsigned int i;
unsigned int block_size = 0;
unsigned char *patch_block;
patch_block = kzalloc(STIR421X_PATCH_BLOCK_SIZE, GFP_KERNEL);
if (patch_block == NULL)
return -ENOMEM;
/* break up patch into 1023-byte sections */
for (i = 0; i < patch_len; i += block_size) {
block_size = patch_len - i;
if (block_size > STIR421X_PATCH_BLOCK_SIZE)
block_size = STIR421X_PATCH_BLOCK_SIZE;
/* upload the patch section */
memcpy(patch_block, patch + i, block_size);
ret = usb_bulk_msg(self->usbdev,
usb_sndbulkpipe(self->usbdev,
self->bulk_out_ep),
patch_block, block_size,
&actual_len, msecs_to_jiffies(500));
IRDA_DEBUG(3,"%s(): Bulk send %u bytes, ret=%d\n",
__func__, actual_len, ret);
if (ret < 0)
break;
mdelay(10);
}
kfree(patch_block);
return ret;
}
/*
* Function stir421x_patch_device(struct irda_usb_cb *self)
*
* Get a firmware code from userspase using hotplug request_firmware() call
*/
static int stir421x_patch_device(struct irda_usb_cb *self)
{
unsigned int i;
int ret;
char stir421x_fw_name[12];
const struct firmware *fw;
const unsigned char *fw_version_ptr; /* pointer to version string */
unsigned long fw_version = 0;
/*
* Known firmware patch file names for STIR421x dongles
* are "42101001.sb" or "42101002.sb"
*/
sprintf(stir421x_fw_name, "4210%4X.sb",
self->usbdev->descriptor.bcdDevice);
ret = request_firmware(&fw, stir421x_fw_name, &self->usbdev->dev);
if (ret < 0)
return ret;
/* We get a patch from userspace */
IRDA_MESSAGE("%s(): Received firmware %s (%zu bytes)\n",
__func__, stir421x_fw_name, fw->size);
ret = -EINVAL;
/* Get the bcd product version */
if (!memcmp(fw->data, STIR421X_PATCH_PRODUCT_VER,
sizeof(STIR421X_PATCH_PRODUCT_VER) - 1)) {
fw_version_ptr = fw->data +
sizeof(STIR421X_PATCH_PRODUCT_VER) - 1;
/* Let's check if the product version is dotted */
if (fw_version_ptr[3] == '.' &&
fw_version_ptr[7] == '.') {
unsigned long major, minor, build;
major = simple_strtoul(fw_version_ptr, NULL, 10);
minor = simple_strtoul(fw_version_ptr + 4, NULL, 10);
build = simple_strtoul(fw_version_ptr + 8, NULL, 10);
fw_version = (major << 12)
+ (minor << 8)
+ ((build / 10) << 4)
+ (build % 10);
IRDA_DEBUG(3, "%s(): Firmware Product version %ld\n",
__func__, fw_version);
}
}
if (self->usbdev->descriptor.bcdDevice == cpu_to_le16(fw_version)) {
/*
* If we're here, we've found a correct patch
* The actual image starts after the "STMP" keyword
* so forward to the firmware header tag
*/
for (i = 0; i < fw->size && fw->data[i] !=
STIR421X_PATCH_END_OF_HDR_TAG; i++) ;
/* here we check for the out of buffer case */
if (i < STIR421X_PATCH_CODE_OFFSET && i < fw->size &&
STIR421X_PATCH_END_OF_HDR_TAG == fw->data[i]) {
if (!memcmp(fw->data + i + 1, STIR421X_PATCH_STMP_TAG,
sizeof(STIR421X_PATCH_STMP_TAG) - 1)) {
/* We can upload the patch to the target */
i += sizeof(STIR421X_PATCH_STMP_TAG);
ret = stir421x_fw_upload(self, &fw->data[i],
fw->size - i);
}
}
}
release_firmware(fw);
return ret;
}
/********************** IRDA DEVICE CALLBACKS **********************/
/*
* Main calls from the IrDA/Network subsystem.
* Mostly registering a new irda-usb device and removing it....
* We only deal with the IrDA side of the business, the USB side will
* be dealt with below...
*/
/*------------------------------------------------------------------*/
/*
* Function irda_usb_net_open (dev)
*
* Network device is taken up. Usually this is done by "ifconfig irda0 up"
*
* Note : don't mess with self->netopen - Jean II
*/
static int irda_usb_net_open(struct net_device *netdev)
{
struct irda_usb_cb *self;
unsigned long flags;
char hwname[16];
int i;
IRDA_DEBUG(1, "%s()\n", __func__);
IRDA_ASSERT(netdev != NULL, return -1;);
self = netdev_priv(netdev);
IRDA_ASSERT(self != NULL, return -1;);
spin_lock_irqsave(&self->lock, flags);
/* Can only open the device if it's there */
if(!self->present) {
spin_unlock_irqrestore(&self->lock, flags);
IRDA_WARNING("%s(), device not present!\n", __func__);
return -1;
}
if(self->needspatch) {
spin_unlock_irqrestore(&self->lock, flags);
IRDA_WARNING("%s(), device needs patch\n", __func__) ;
return -EIO ;
}
/* Initialise default speed and xbofs value
* (IrLAP will change that soon) */
self->speed = -1;
self->xbofs = -1;
self->new_speed = -1;
self->new_xbofs = -1;
/* To do *before* submitting Rx urbs and starting net Tx queue
* Jean II */
self->netopen = 1;
spin_unlock_irqrestore(&self->lock, flags);
/*
* Now that everything should be initialized properly,
* Open new IrLAP layer instance to take care of us...
* Note : will send immediately a speed change...
*/
sprintf(hwname, "usb#%d", self->usbdev->devnum);
self->irlap = irlap_open(netdev, &self->qos, hwname);
IRDA_ASSERT(self->irlap != NULL, return -1;);
/* Allow IrLAP to send data to us */
netif_start_queue(netdev);
/* We submit all the Rx URB except for one that we keep idle.
* Need to be initialised before submitting other USBs, because
* in some cases as soon as we submit the URBs the USB layer
* will trigger a dummy receive - Jean II */
self->idle_rx_urb = self->rx_urb[IU_MAX_ACTIVE_RX_URBS];
self->idle_rx_urb->context = NULL;
/* Now that we can pass data to IrLAP, allow the USB layer
* to send us some data... */
for (i = 0; i < IU_MAX_ACTIVE_RX_URBS; i++) {
struct sk_buff *skb = dev_alloc_skb(IRDA_SKB_MAX_MTU);
if (!skb) {
/* If this ever happen, we are in deep s***.
* Basically, we can't start the Rx path... */
IRDA_WARNING("%s(), Failed to allocate Rx skb\n",
__func__);
return -1;
}
//skb_reserve(newskb, USB_IRDA_HEADER - 1);
irda_usb_submit(self, skb, self->rx_urb[i]);
}
/* Ready to play !!! */
return 0;
}
/*------------------------------------------------------------------*/
/*
* Function irda_usb_net_close (self)
*
* Network device is taken down. Usually this is done by
* "ifconfig irda0 down"
*/
static int irda_usb_net_close(struct net_device *netdev)
{
struct irda_usb_cb *self;
int i;
IRDA_DEBUG(1, "%s()\n", __func__);
IRDA_ASSERT(netdev != NULL, return -1;);
self = netdev_priv(netdev);
IRDA_ASSERT(self != NULL, return -1;);
/* Clear this flag *before* unlinking the urbs and *before*
* stopping the network Tx queue - Jean II */
self->netopen = 0;
/* Stop network Tx queue */
netif_stop_queue(netdev);
/* Kill defered Rx URB */
del_timer(&self->rx_defer_timer);
/* Deallocate all the Rx path buffers (URBs and skb) */
for (i = 0; i < self->max_rx_urb; i++) {
struct urb *urb = self->rx_urb[i];
struct sk_buff *skb = (struct sk_buff *) urb->context;
/* Cancel the receive command */
usb_kill_urb(urb);
/* The skb is ours, free it */
if(skb) {
dev_kfree_skb(skb);
urb->context = NULL;
}
}
/* Cancel Tx and speed URB - need to be synchronous to avoid races */
usb_kill_urb(self->tx_urb);
usb_kill_urb(self->speed_urb);
/* Stop and remove instance of IrLAP */
if (self->irlap)
irlap_close(self->irlap);
self->irlap = NULL;
return 0;
}
/*------------------------------------------------------------------*/
/*
* IOCTLs : Extra out-of-band network commands...
*/
static int irda_usb_net_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
{
unsigned long flags;
struct if_irda_req *irq = (struct if_irda_req *) rq;
struct irda_usb_cb *self;
int ret = 0;
IRDA_ASSERT(dev != NULL, return -1;);
self = netdev_priv(dev);
IRDA_ASSERT(self != NULL, return -1;);
IRDA_DEBUG(2, "%s(), %s, (cmd=0x%X)\n", __func__, dev->name, cmd);
switch (cmd) {
case SIOCSBANDWIDTH: /* Set bandwidth */
if (!capable(CAP_NET_ADMIN))
return -EPERM;
/* Protect us from USB callbacks, net watchdog and else. */
spin_lock_irqsave(&self->lock, flags);
/* Check if the device is still there */
if(self->present) {
/* Set the desired speed */
self->new_speed = irq->ifr_baudrate;
irda_usb_change_speed_xbofs(self);
}
spin_unlock_irqrestore(&self->lock, flags);
break;
case SIOCSMEDIABUSY: /* Set media busy */
if (!capable(CAP_NET_ADMIN))
return -EPERM;
/* Check if the IrDA stack is still there */
if(self->netopen)
irda_device_set_media_busy(self->netdev, TRUE);
break;
case SIOCGRECEIVING: /* Check if we are receiving right now */
irq->ifr_receiving = irda_usb_is_receiving(self);
break;
default:
ret = -EOPNOTSUPP;
}
return ret;
}
/*------------------------------------------------------------------*/
/********************* IRDA CONFIG SUBROUTINES *********************/
/*
* Various subroutines dealing with IrDA and network stuff we use to
* configure and initialise each irda-usb instance.
* These functions are used below in the main calls of the driver...
*/
/*------------------------------------------------------------------*/
/*
* Set proper values in the IrDA QOS structure
*/
static inline void irda_usb_init_qos(struct irda_usb_cb *self)
{
struct irda_class_desc *desc;
IRDA_DEBUG(3, "%s()\n", __func__);
desc = self->irda_desc;
/* Initialize QoS for this device */
irda_init_max_qos_capabilies(&self->qos);
/* See spec section 7.2 for meaning.
* Values are little endian (as most USB stuff), the IrDA stack
* use it in native order (see parameters.c). - Jean II */
self->qos.baud_rate.bits = le16_to_cpu(desc->wBaudRate);
self->qos.min_turn_time.bits = desc->bmMinTurnaroundTime;
self->qos.additional_bofs.bits = desc->bmAdditionalBOFs;
self->qos.window_size.bits = desc->bmWindowSize;
self->qos.data_size.bits = desc->bmDataSize;
IRDA_DEBUG(0, "%s(), dongle says speed=0x%X, size=0x%X, window=0x%X, bofs=0x%X, turn=0x%X\n",
__func__, self->qos.baud_rate.bits, self->qos.data_size.bits, self->qos.window_size.bits, self->qos.additional_bofs.bits, self->qos.min_turn_time.bits);
/* Don't always trust what the dongle tell us */
if(self->capability & IUC_SIR_ONLY)
self->qos.baud_rate.bits &= 0x00ff;
if(self->capability & IUC_SMALL_PKT)
self->qos.data_size.bits = 0x07;
if(self->capability & IUC_NO_WINDOW)
self->qos.window_size.bits = 0x01;
if(self->capability & IUC_MAX_WINDOW)
self->qos.window_size.bits = 0x7f;
if(self->capability & IUC_MAX_XBOFS)
self->qos.additional_bofs.bits = 0x01;
#if 1
/* Module parameter can override the rx window size */
if (qos_mtt_bits)
self->qos.min_turn_time.bits = qos_mtt_bits;
#endif
/*
* Note : most of those values apply only for the receive path,
* the transmit path will be set differently - Jean II
*/
irda_qos_bits_to_value(&self->qos);
}
/*------------------------------------------------------------------*/
static const struct net_device_ops irda_usb_netdev_ops = {
.ndo_open = irda_usb_net_open,
.ndo_stop = irda_usb_net_close,
.ndo_do_ioctl = irda_usb_net_ioctl,
.ndo_start_xmit = irda_usb_hard_xmit,
.ndo_tx_timeout = irda_usb_net_timeout,
};
/*
* Initialise the network side of the irda-usb instance
* Called when a new USB instance is registered in irda_usb_probe()
*/
static inline int irda_usb_open(struct irda_usb_cb *self)
{
struct net_device *netdev = self->netdev;
IRDA_DEBUG(1, "%s()\n", __func__);
netdev->netdev_ops = &irda_usb_netdev_ops;
irda_usb_init_qos(self);
return register_netdev(netdev);
}
/*------------------------------------------------------------------*/
/*
* Cleanup the network side of the irda-usb instance
* Called when a USB instance is removed in irda_usb_disconnect()
*/
static inline void irda_usb_close(struct irda_usb_cb *self)
{
IRDA_DEBUG(1, "%s()\n", __func__);
/* Remove netdevice */
unregister_netdev(self->netdev);
/* Remove the speed buffer */
kfree(self->speed_buff);
self->speed_buff = NULL;
kfree(self->tx_buff);
self->tx_buff = NULL;
}
/********************** USB CONFIG SUBROUTINES **********************/
/*
* Various subroutines dealing with USB stuff we use to configure and
* initialise each irda-usb instance.
* These functions are used below in the main calls of the driver...
*/
/*------------------------------------------------------------------*/
/*
* Function irda_usb_parse_endpoints(dev, ifnum)
*
* Parse the various endpoints and find the one we need.
*
* The endpoint are the pipes used to communicate with the USB device.
* The spec defines 2 endpoints of type bulk transfer, one in, and one out.
* These are used to pass frames back and forth with the dongle.
* Most dongle have also an interrupt endpoint, that will be probably
* documented in the next spec...
*/
static inline int irda_usb_parse_endpoints(struct irda_usb_cb *self, struct usb_host_endpoint *endpoint, int ennum)
{
int i; /* Endpoint index in table */
/* Init : no endpoints */
self->bulk_in_ep = 0;
self->bulk_out_ep = 0;
self->bulk_int_ep = 0;
/* Let's look at all those endpoints */
for(i = 0; i < ennum; i++) {
/* All those variables will get optimised by the compiler,
* so let's aim for clarity... - Jean II */
__u8 ep; /* Endpoint address */
__u8 dir; /* Endpoint direction */
__u8 attr; /* Endpoint attribute */
__u16 psize; /* Endpoint max packet size in bytes */
/* Get endpoint address, direction and attribute */
ep = endpoint[i].desc.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
dir = endpoint[i].desc.bEndpointAddress & USB_ENDPOINT_DIR_MASK;
attr = endpoint[i].desc.bmAttributes;
psize = le16_to_cpu(endpoint[i].desc.wMaxPacketSize);
/* Is it a bulk endpoint ??? */
if(attr == USB_ENDPOINT_XFER_BULK) {
/* We need to find an IN and an OUT */
if(dir == USB_DIR_IN) {
/* This is our Rx endpoint */
self->bulk_in_ep = ep;
} else {
/* This is our Tx endpoint */
self->bulk_out_ep = ep;
self->bulk_out_mtu = psize;
}
} else {
if((attr == USB_ENDPOINT_XFER_INT) &&
(dir == USB_DIR_IN)) {
/* This is our interrupt endpoint */
self->bulk_int_ep = ep;
} else {
IRDA_ERROR("%s(), Unrecognised endpoint %02X.\n", __func__, ep);
}
}
}
IRDA_DEBUG(0, "%s(), And our endpoints are : in=%02X, out=%02X (%d), int=%02X\n",
__func__, self->bulk_in_ep, self->bulk_out_ep, self->bulk_out_mtu, self->bulk_int_ep);
return (self->bulk_in_ep != 0) && (self->bulk_out_ep != 0);
}
#ifdef IU_DUMP_CLASS_DESC
/*------------------------------------------------------------------*/
/*
* Function usb_irda_dump_class_desc(desc)
*
* Prints out the contents of the IrDA class descriptor
*
*/
static inline void irda_usb_dump_class_desc(struct irda_class_desc *desc)
{
/* Values are little endian */
printk("bLength=%x\n", desc->bLength);
printk("bDescriptorType=%x\n", desc->bDescriptorType);
printk("bcdSpecRevision=%x\n", le16_to_cpu(desc->bcdSpecRevision));
printk("bmDataSize=%x\n", desc->bmDataSize);
printk("bmWindowSize=%x\n", desc->bmWindowSize);
printk("bmMinTurnaroundTime=%d\n", desc->bmMinTurnaroundTime);
printk("wBaudRate=%x\n", le16_to_cpu(desc->wBaudRate));
printk("bmAdditionalBOFs=%x\n", desc->bmAdditionalBOFs);
printk("bIrdaRateSniff=%x\n", desc->bIrdaRateSniff);
printk("bMaxUnicastList=%x\n", desc->bMaxUnicastList);
}
#endif /* IU_DUMP_CLASS_DESC */
/*------------------------------------------------------------------*/
/*
* Function irda_usb_find_class_desc(intf)
*
* Returns instance of IrDA class descriptor, or NULL if not found
*
* The class descriptor is some extra info that IrDA USB devices will
* offer to us, describing their IrDA characteristics. We will use that in
* irda_usb_init_qos()
*/
static inline struct irda_class_desc *irda_usb_find_class_desc(struct usb_interface *intf)
{
struct usb_device *dev = interface_to_usbdev (intf);
struct irda_class_desc *desc;
int ret;
desc = kzalloc(sizeof(*desc), GFP_KERNEL);
if (!desc)
return NULL;
/* USB-IrDA class spec 1.0:
* 6.1.3: Standard "Get Descriptor" Device Request is not
* appropriate to retrieve class-specific descriptor
* 6.2.5: Class Specific "Get Class Descriptor" Interface Request
* is mandatory and returns the USB-IrDA class descriptor
*/
ret = usb_control_msg(dev, usb_rcvctrlpipe(dev,0),
IU_REQ_GET_CLASS_DESC,
USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
0, intf->altsetting->desc.bInterfaceNumber, desc,
sizeof(*desc), 500);
IRDA_DEBUG(1, "%s(), ret=%d\n", __func__, ret);
if (ret < sizeof(*desc)) {
IRDA_WARNING("usb-irda: class_descriptor read %s (%d)\n",
(ret<0) ? "failed" : "too short", ret);
}
else if (desc->bDescriptorType != USB_DT_IRDA) {
IRDA_WARNING("usb-irda: bad class_descriptor type\n");
}
else {
#ifdef IU_DUMP_CLASS_DESC
irda_usb_dump_class_desc(desc);
#endif /* IU_DUMP_CLASS_DESC */
return desc;
}
kfree(desc);
return NULL;
}
/*********************** USB DEVICE CALLBACKS ***********************/
/*
* Main calls from the USB subsystem.
* Mostly registering a new irda-usb device and removing it....
*/
/*------------------------------------------------------------------*/
/*
* This routine is called by the USB subsystem for each new device
* in the system. We need to check if the device is ours, and in
* this case start handling it.
* The USB layer protect us from reentrancy (via BKL), so we don't need
* to spinlock in there... Jean II
*/
static int irda_usb_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct net_device *net;
struct usb_device *dev = interface_to_usbdev(intf);
struct irda_usb_cb *self;
struct usb_host_interface *interface;
struct irda_class_desc *irda_desc;
int ret = -ENOMEM;
int i; /* Driver instance index / Rx URB index */
/* Note : the probe make sure to call us only for devices that
* matches the list of dongle (top of the file). So, we
* don't need to check if the dongle is really ours.
* Jean II */
IRDA_MESSAGE("IRDA-USB found at address %d, Vendor: %x, Product: %x\n",
dev->devnum, le16_to_cpu(dev->descriptor.idVendor),
le16_to_cpu(dev->descriptor.idProduct));
net = alloc_irdadev(sizeof(*self));
if (!net)
goto err_out;
SET_NETDEV_DEV(net, &intf->dev);
self = netdev_priv(net);
self->netdev = net;
spin_lock_init(&self->lock);
init_timer(&self->rx_defer_timer);
self->capability = id->driver_info;
self->needspatch = ((self->capability & IUC_STIR421X) != 0);
/* Create all of the needed urbs */
if (self->capability & IUC_STIR421X) {
self->max_rx_urb = IU_SIGMATEL_MAX_RX_URBS;
self->header_length = USB_IRDA_STIR421X_HEADER;
} else {
self->max_rx_urb = IU_MAX_RX_URBS;
self->header_length = USB_IRDA_HEADER;
}
self->rx_urb = kcalloc(self->max_rx_urb, sizeof(struct urb *),
GFP_KERNEL);
if (!self->rx_urb)
goto err_free_net;
for (i = 0; i < self->max_rx_urb; i++) {
self->rx_urb[i] = usb_alloc_urb(0, GFP_KERNEL);
if (!self->rx_urb[i]) {
goto err_out_1;
}
}
self->tx_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!self->tx_urb) {
goto err_out_1;
}
self->speed_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!self->speed_urb) {
goto err_out_2;
}
/* Is this really necessary? (no, except maybe for broken devices) */
if (usb_reset_configuration (dev) < 0) {
dev_err(&intf->dev, "reset_configuration failed\n");
ret = -EIO;
goto err_out_3;
}
/* Is this really necessary? */
/* Note : some driver do hardcode the interface number, some others
* specify an alternate, but very few driver do like this.
* Jean II */
ret = usb_set_interface(dev, intf->altsetting->desc.bInterfaceNumber, 0);
IRDA_DEBUG(1, "usb-irda: set interface %d result %d\n", intf->altsetting->desc.bInterfaceNumber, ret);
switch (ret) {
case 0:
break;
case -EPIPE: /* -EPIPE = -32 */
/* Martin Diehl says if we get a -EPIPE we should
* be fine and we don't need to do a usb_clear_halt().
* - Jean II */
IRDA_DEBUG(0, "%s(), Received -EPIPE, ignoring...\n", __func__);
break;
default:
IRDA_DEBUG(0, "%s(), Unknown error %d\n", __func__, ret);
ret = -EIO;
goto err_out_3;
}
/* Find our endpoints */
interface = intf->cur_altsetting;
if(!irda_usb_parse_endpoints(self, interface->endpoint,
interface->desc.bNumEndpoints)) {
IRDA_ERROR("%s(), Bogus endpoints...\n", __func__);
ret = -EIO;
goto err_out_3;
}
self->usbdev = dev;
/* Find IrDA class descriptor */
irda_desc = irda_usb_find_class_desc(intf);
ret = -ENODEV;
if (!irda_desc)
goto err_out_3;
if (self->needspatch) {
ret = usb_control_msg (self->usbdev, usb_sndctrlpipe (self->usbdev, 0),
0x02, 0x40, 0, 0, NULL, 0, 500);
if (ret < 0) {
IRDA_DEBUG (0, "usb_control_msg failed %d\n", ret);
goto err_out_3;
} else {
mdelay(10);
}
}
self->irda_desc = irda_desc;
self->present = 1;
self->netopen = 0;
self->usbintf = intf;
/* Allocate the buffer for speed changes */
/* Don't change this buffer size and allocation without doing
* some heavy and complete testing. Don't ask why :-(
* Jean II */
self->speed_buff = kzalloc(IRDA_USB_SPEED_MTU, GFP_KERNEL);
if (!self->speed_buff)
goto err_out_3;
self->tx_buff = kzalloc(IRDA_SKB_MAX_MTU + self->header_length,
GFP_KERNEL);
if (!self->tx_buff)
goto err_out_4;
ret = irda_usb_open(self);
if (ret)
goto err_out_5;
IRDA_MESSAGE("IrDA: Registered device %s\n", net->name);
usb_set_intfdata(intf, self);
if (self->needspatch) {
/* Now we fetch and upload the firmware patch */
ret = stir421x_patch_device(self);
self->needspatch = (ret < 0);
if (self->needspatch) {
IRDA_ERROR("STIR421X: Couldn't upload patch\n");
goto err_out_6;
}
/* replace IrDA class descriptor with what patched device is now reporting */
irda_desc = irda_usb_find_class_desc (self->usbintf);
if (!irda_desc) {
ret = -ENODEV;
goto err_out_6;
}
kfree(self->irda_desc);
self->irda_desc = irda_desc;
irda_usb_init_qos(self);
}
return 0;
err_out_6:
unregister_netdev(self->netdev);
err_out_5:
kfree(self->tx_buff);
err_out_4:
kfree(self->speed_buff);
err_out_3:
/* Free all urbs that we may have created */
usb_free_urb(self->speed_urb);
err_out_2:
usb_free_urb(self->tx_urb);
err_out_1:
for (i = 0; i < self->max_rx_urb; i++)
usb_free_urb(self->rx_urb[i]);
kfree(self->rx_urb);
err_free_net:
free_netdev(net);
err_out:
return ret;
}
/*------------------------------------------------------------------*/
/*
* The current irda-usb device is removed, the USB layer tell us
* to shut it down...
* One of the constraints is that when we exit this function,
* we cannot use the usb_device no more. Gone. Destroyed. kfree().
* Most other subsystem allow you to destroy the instance at a time
* when it's convenient to you, to postpone it to a later date, but
* not the USB subsystem.
* So, we must make bloody sure that everything gets deactivated.
* Jean II
*/
static void irda_usb_disconnect(struct usb_interface *intf)
{
unsigned long flags;
struct irda_usb_cb *self = usb_get_intfdata(intf);
int i;
IRDA_DEBUG(1, "%s()\n", __func__);
usb_set_intfdata(intf, NULL);
if (!self)
return;
/* Make sure that the Tx path is not executing. - Jean II */
spin_lock_irqsave(&self->lock, flags);
/* Oups ! We are not there any more.
* This will stop/desactivate the Tx path. - Jean II */
self->present = 0;
/* Kill defered Rx URB */
del_timer(&self->rx_defer_timer);
/* We need to have irq enabled to unlink the URBs. That's OK,
* at this point the Tx path is gone - Jean II */
spin_unlock_irqrestore(&self->lock, flags);
/* Hum... Check if networking is still active (avoid races) */
if((self->netopen) || (self->irlap)) {
/* Accept no more transmissions */
/*netif_device_detach(self->netdev);*/
netif_stop_queue(self->netdev);
/* Stop all the receive URBs. Must be synchronous. */
for (i = 0; i < self->max_rx_urb; i++)
usb_kill_urb(self->rx_urb[i]);
/* Cancel Tx and speed URB.
* Make sure it's synchronous to avoid races. */
usb_kill_urb(self->tx_urb);
usb_kill_urb(self->speed_urb);
}
/* Cleanup the device stuff */
irda_usb_close(self);
/* No longer attached to USB bus */
self->usbdev = NULL;
self->usbintf = NULL;
/* Clean up our urbs */
for (i = 0; i < self->max_rx_urb; i++)
usb_free_urb(self->rx_urb[i]);
kfree(self->rx_urb);
/* Clean up Tx and speed URB */
usb_free_urb(self->tx_urb);
usb_free_urb(self->speed_urb);
/* Free self and network device */
free_netdev(self->netdev);
IRDA_DEBUG(0, "%s(), USB IrDA Disconnected\n", __func__);
}
#ifdef CONFIG_PM
/* USB suspend, so power off the transmitter/receiver */
static int irda_usb_suspend(struct usb_interface *intf, pm_message_t message)
{
struct irda_usb_cb *self = usb_get_intfdata(intf);
int i;
netif_device_detach(self->netdev);
if (self->tx_urb != NULL)
usb_kill_urb(self->tx_urb);
if (self->speed_urb != NULL)
usb_kill_urb(self->speed_urb);
for (i = 0; i < self->max_rx_urb; i++) {
if (self->rx_urb[i] != NULL)
usb_kill_urb(self->rx_urb[i]);
}
return 0;
}
/* Coming out of suspend, so reset hardware */
static int irda_usb_resume(struct usb_interface *intf)
{
struct irda_usb_cb *self = usb_get_intfdata(intf);
int i;
for (i = 0; i < self->max_rx_urb; i++) {
if (self->rx_urb[i] != NULL)
usb_submit_urb(self->rx_urb[i], GFP_KERNEL);
}
netif_device_attach(self->netdev);
return 0;
}
#endif
/*------------------------------------------------------------------*/
/*
* USB device callbacks
*/
static struct usb_driver irda_driver = {
.name = "irda-usb",
.probe = irda_usb_probe,
.disconnect = irda_usb_disconnect,
.id_table = dongles,
#ifdef CONFIG_PM
.suspend = irda_usb_suspend,
.resume = irda_usb_resume,
#endif
};
module_usb_driver(irda_driver);
/*
* Module parameters
*/
module_param(qos_mtt_bits, int, 0);
MODULE_PARM_DESC(qos_mtt_bits, "Minimum Turn Time");
MODULE_AUTHOR("Roman Weissgaerber <weissg@vienna.at>, Dag Brattli <dag@brattli.net>, Jean Tourrilhes <jt@hpl.hp.com> and Nick Fedchik <nick@fedchik.org.ua>");
MODULE_DESCRIPTION("IrDA-USB Dongle Driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
ajayramaswamy/linux-imx-gk802 | drivers/staging/wlags49_h2/wl_wext.c | 2914 | 109028 | /*******************************************************************************
* Agere Systems Inc.
* Wireless device driver for Linux (wlags49).
*
* Copyright (c) 1998-2003 Agere Systems Inc.
* All rights reserved.
* http://www.agere.com
*
* Initially developed by TriplePoint, Inc.
* http://www.triplepoint.com
*
*------------------------------------------------------------------------------
*
* SOFTWARE LICENSE
*
* This software is provided subject to the following terms and conditions,
* which you should read carefully before using the software. Using this
* software indicates your acceptance of these terms and conditions. If you do
* not agree with these terms and conditions, do not use the software.
*
* Copyright © 2003 Agere Systems Inc.
* All rights reserved.
*
* Redistribution and use in source or binary forms, with or without
* modifications, 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 as comments in the code as
* well as in the documentation and/or other materials provided with the
* distribution.
*
* . Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following Disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* . Neither the name of Agere Systems Inc. nor the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* Disclaimer
*
* THIS SOFTWARE IS PROVIDED AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, INFRINGEMENT AND THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ANY
* USE, MODIFICATION OR DISTRIBUTION OF THIS SOFTWARE IS SOLELY AT THE USERS OWN
* RISK. IN NO EVENT SHALL AGERE SYSTEMS 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, INCLUDING, BUT NOT LIMITED TO, 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 files
******************************************************************************/
#include <wl_version.h>
#include <linux/if_arp.h>
#include <linux/ioport.h>
#include <linux/delay.h>
#include <asm/uaccess.h>
#include <debug.h>
#include <hcf.h>
#include <hcfdef.h>
#include <wl_if.h>
#include <wl_internal.h>
#include <wl_util.h>
#include <wl_main.h>
#include <wl_wext.h>
#include <wl_priv.h>
/* If WIRELESS_EXT is not defined (as a result of HAS_WIRELESS_EXTENSIONS
#including linux/wireless.h), then these functions do not need to be included
in the build. */
#ifdef WIRELESS_EXT
#define IWE_STREAM_ADD_EVENT(info, buf, end, iwe, len) \
iwe_stream_add_event(info, buf, end, iwe, len)
#define IWE_STREAM_ADD_POINT(info, buf, end, iwe, msg) \
iwe_stream_add_point(info, buf, end, iwe, msg)
/*******************************************************************************
* global definitions
******************************************************************************/
#if DBG
extern dbg_info_t *DbgInfo;
#endif // DBG
/*******************************************************************************
* wireless_commit()
*******************************************************************************
*
* DESCRIPTION:
*
* Commit
* protocol used.
*
* PARAMETERS:
*
* wrq - the wireless request buffer
*
* RETURNS:
*
* N/A
*
******************************************************************************/
static int wireless_commit(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *rqu, char *extra)
{
struct wl_private *lp = wl_priv(dev);
unsigned long flags;
int ret = 0;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wireless_commit" );
DBG_ENTER(DbgInfo);
if(lp->portState == WVLAN_PORT_STATE_DISABLED) {
ret = -EBUSY;
goto out;
}
wl_lock( lp, &flags );
wl_act_int_off( lp );
wl_apply(lp);
wl_act_int_on( lp );
wl_unlock(lp, &flags);
out:
DBG_LEAVE( DbgInfo );
return ret;
} // wireless_commit
/*============================================================================*/
/*******************************************************************************
* wireless_get_protocol()
*******************************************************************************
*
* DESCRIPTION:
*
* Returns a vendor-defined string that should identify the wireless
* protocol used.
*
* PARAMETERS:
*
* wrq - the wireless request buffer
*
* RETURNS:
*
* N/A
*
******************************************************************************/
static int wireless_get_protocol(struct net_device *dev, struct iw_request_info *info, char *name, char *extra)
{
DBG_FUNC( "wireless_get_protocol" );
DBG_ENTER( DbgInfo );
/* Originally, the driver was placing the string "Wireless" here. However,
the wireless extensions (/linux/wireless.h) indicate this string should
describe the wireless protocol. */
strcpy(name, "IEEE 802.11b");
DBG_LEAVE(DbgInfo);
return 0;
} // wireless_get_protocol
/*============================================================================*/
/*******************************************************************************
* wireless_set_frequency()
*******************************************************************************
*
* DESCRIPTION:
*
* Sets the frequency (channel) on which the card should Tx/Rx.
*
* PARAMETERS:
*
* wrq - the wireless request buffer
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
static int wireless_set_frequency(struct net_device *dev, struct iw_request_info *info, struct iw_freq *freq, char *extra)
{
struct wl_private *lp = wl_priv(dev);
unsigned long flags;
int channel = 0;
int ret = 0;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wireless_set_frequency" );
DBG_ENTER( DbgInfo );
if(lp->portState == WVLAN_PORT_STATE_DISABLED) {
ret = -EBUSY;
goto out;
}
if( !capable( CAP_NET_ADMIN )) {
ret = -EPERM;
DBG_LEAVE( DbgInfo );
return ret;
}
/* If frequency specified, look up channel */
if( freq->e == 1 ) {
int f = freq->m / 100000;
channel = wl_get_chan_from_freq( f );
}
/* Channel specified */
if( freq->e == 0 ) {
channel = freq->m;
}
/* If the channel is an 802.11a channel, set Bit 8 */
if( channel > 14 ) {
channel = channel | 0x100;
}
wl_lock( lp, &flags );
wl_act_int_off( lp );
lp->Channel = channel;
/* Commit the adapter parameters */
wl_apply( lp );
/* Send an event that channel/freq has been set */
wl_wext_event_freq( lp->dev );
wl_act_int_on( lp );
wl_unlock(lp, &flags);
out:
DBG_LEAVE( DbgInfo );
return ret;
} // wireless_set_frequency
/*============================================================================*/
/*******************************************************************************
* wireless_get_frequency()
*******************************************************************************
*
* DESCRIPTION:
*
* Gets the frequency (channel) on which the card is Tx/Rx.
*
* PARAMETERS:
*
* wrq - the wireless request buffer
* lp - the device's private adapter structure
*
* RETURNS:
*
* N/A
*
******************************************************************************/
static int wireless_get_frequency(struct net_device *dev, struct iw_request_info *info, struct iw_freq *freq, char *extra)
{
struct wl_private *lp = wl_priv(dev);
unsigned long flags;
int ret = -1;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wireless_get_frequency" );
DBG_ENTER( DbgInfo );
if(lp->portState == WVLAN_PORT_STATE_DISABLED) {
ret = -EBUSY;
goto out;
}
wl_lock( lp, &flags );
wl_act_int_off( lp );
lp->ltvRecord.len = 2;
lp->ltvRecord.typ = CFG_CUR_CHANNEL;
ret = hcf_get_info( &(lp->hcfCtx), (LTVP)&( lp->ltvRecord ));
if( ret == HCF_SUCCESS ) {
hcf_16 channel = CNV_LITTLE_TO_INT( lp->ltvRecord.u.u16[0] );
#ifdef USE_FREQUENCY
freq->m = wl_get_freq_from_chan( channel ) * 100000;
freq->e = 1;
#else
freq->m = channel;
freq->e = 0;
#endif /* USE_FREQUENCY */
}
wl_act_int_on( lp );
wl_unlock(lp, &flags);
ret = (ret == HCF_SUCCESS ? 0 : -EFAULT);
out:
DBG_LEAVE( DbgInfo );
return ret;
} // wireless_get_frequency
/*============================================================================*/
/*******************************************************************************
* wireless_get_range()
*******************************************************************************
*
* DESCRIPTION:
*
* This function is used to provide misc info and statistics about the
* wireless device.
*
* PARAMETERS:
*
* wrq - the wireless request buffer
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
static int wireless_get_range(struct net_device *dev, struct iw_request_info *info, struct iw_point *data, char *extra)
{
struct wl_private *lp = wl_priv(dev);
unsigned long flags;
struct iw_range *range = (struct iw_range *) extra;
int ret = 0;
int status = -1;
int count;
__u16 *pTxRate;
int retries = 0;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wireless_get_range" );
DBG_ENTER( DbgInfo );
/* Set range information */
data->length = sizeof(struct iw_range);
memset(range, 0, sizeof(struct iw_range));
wl_lock( lp, &flags );
wl_act_int_off( lp );
/* Set range information */
memset( range, 0, sizeof( struct iw_range ));
retry:
/* Get the current transmit rate from the adapter */
lp->ltvRecord.len = 1 + (sizeof(*pTxRate) / sizeof(hcf_16));
lp->ltvRecord.typ = CFG_CUR_TX_RATE;
status = hcf_get_info( &( lp->hcfCtx ), (LTVP)&( lp->ltvRecord ));
if( status != HCF_SUCCESS ) {
/* Recovery action: reset and retry up to 10 times */
DBG_TRACE( DbgInfo, "Get CFG_CUR_TX_RATE failed: 0x%x\n", status );
if (retries < 10) {
retries++;
/* Holding the lock too long, make a gap to allow other processes */
wl_unlock(lp, &flags);
wl_lock( lp, &flags );
status = wl_reset( dev );
if ( status != HCF_SUCCESS ) {
DBG_TRACE( DbgInfo, "reset failed: 0x%x\n", status );
ret = -EFAULT;
goto out_unlock;
}
/* Holding the lock too long, make a gap to allow other processes */
wl_unlock(lp, &flags);
wl_lock( lp, &flags );
goto retry;
} else {
DBG_TRACE( DbgInfo, "Get CFG_CUR_TX_RATE failed: %d retries\n", retries );
ret = -EFAULT;
goto out_unlock;
}
}
/* Holding the lock too long, make a gap to allow other processes */
wl_unlock(lp, &flags);
wl_lock( lp, &flags );
pTxRate = (__u16 *)&( lp->ltvRecord.u.u32 );
range->throughput = CNV_LITTLE_TO_INT( *pTxRate ) * MEGABIT;
if (retries > 0) {
DBG_TRACE( DbgInfo, "Get CFG_CUR_TX_RATE succes: %d retries\n", retries );
}
// NWID - NOT SUPPORTED
/* Channel/Frequency Info */
range->num_channels = RADIO_CHANNELS;
/* Signal Level Thresholds */
range->sensitivity = RADIO_SENSITIVITY_LEVELS;
/* Link quality */
#ifdef USE_DBM
range->max_qual.qual = (u_char)HCF_MAX_COMM_QUALITY;
/* If the value returned in /proc/net/wireless is greater than the maximum range,
iwconfig assumes that the value is in dBm. Because an unsigned char is used,
it requires a bit of contorsion... */
range->max_qual.level = (u_char)( dbm( HCF_MIN_SIGNAL_LEVEL ) - 1 );
range->max_qual.noise = (u_char)( dbm( HCF_MIN_NOISE_LEVEL ) - 1 );
#else
range->max_qual.qual = 100;
range->max_qual.level = 100;
range->max_qual.noise = 100;
#endif /* USE_DBM */
/* Set available rates */
range->num_bitrates = 0;
lp->ltvRecord.len = 6;
lp->ltvRecord.typ = CFG_SUPPORTED_DATA_RATES;
status = hcf_get_info( &( lp->hcfCtx ), (LTVP)&( lp->ltvRecord ));
if( status == HCF_SUCCESS ) {
for( count = 0; count < MAX_RATES; count++ )
if( lp->ltvRecord.u.u8[count+2] != 0 ) {
range->bitrate[count] = lp->ltvRecord.u.u8[count+2] * MEGABIT / 2;
range->num_bitrates++;
}
} else {
DBG_TRACE( DbgInfo, "CFG_SUPPORTED_DATA_RATES: 0x%x\n", status );
ret = -EFAULT;
goto out_unlock;
}
/* RTS Threshold info */
range->min_rts = MIN_RTS_BYTES;
range->max_rts = MAX_RTS_BYTES;
// Frag Threshold info - NOT SUPPORTED
// Power Management info - NOT SUPPORTED
/* Encryption */
#if WIRELESS_EXT > 8
/* Holding the lock too long, make a gap to allow other processes */
wl_unlock(lp, &flags);
wl_lock( lp, &flags );
/* Is WEP supported? */
if( wl_has_wep( &( lp->hcfCtx ))) {
/* WEP: RC4 40 bits */
range->encoding_size[0] = MIN_KEY_SIZE;
/* RC4 ~128 bits */
range->encoding_size[1] = MAX_KEY_SIZE;
range->num_encoding_sizes = 2;
range->max_encoding_tokens = MAX_KEYS;
}
#endif /* WIRELESS_EXT > 8 */
/* Tx Power Info */
range->txpower_capa = IW_TXPOW_MWATT;
range->num_txpower = 1;
range->txpower[0] = RADIO_TX_POWER_MWATT;
#if WIRELESS_EXT > 10
/* Wireless Extension Info */
range->we_version_compiled = WIRELESS_EXT;
range->we_version_source = WIRELESS_SUPPORT;
// Retry Limits and Lifetime - NOT SUPPORTED
#endif
#if WIRELESS_EXT > 11
/* Holding the lock too long, make a gap to allow other processes */
wl_unlock(lp, &flags);
wl_lock( lp, &flags );
DBG_TRACE( DbgInfo, "calling wl_wireless_stats\n" );
wl_wireless_stats( lp->dev );
range->avg_qual = lp->wstats.qual;
DBG_TRACE( DbgInfo, "wl_wireless_stats done\n" );
#endif
/* Event capability (kernel + driver) */
range->event_capa[0] = (IW_EVENT_CAPA_K_0 |
IW_EVENT_CAPA_MASK(SIOCGIWAP) |
IW_EVENT_CAPA_MASK(SIOCGIWSCAN));
range->event_capa[1] = IW_EVENT_CAPA_K_1;
range->event_capa[4] = (IW_EVENT_CAPA_MASK(IWEVREGISTERED) |
IW_EVENT_CAPA_MASK(IWEVCUSTOM) |
IW_EVENT_CAPA_MASK(IWEVEXPIRED));
range->enc_capa = IW_ENC_CAPA_WPA | IW_ENC_CAPA_CIPHER_TKIP;
out_unlock:
wl_act_int_on( lp );
wl_unlock(lp, &flags);
DBG_LEAVE(DbgInfo);
return ret;
} // wireless_get_range
/*============================================================================*/
/*******************************************************************************
* wireless_get_bssid()
*******************************************************************************
*
* DESCRIPTION:
*
* Gets the BSSID the wireless device is currently associated with.
*
* PARAMETERS:
*
* wrq - the wireless request buffer
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
static int wireless_get_bssid(struct net_device *dev, struct iw_request_info *info, struct sockaddr *ap_addr, char *extra)
{
struct wl_private *lp = wl_priv(dev);
unsigned long flags;
int ret = 0;
#if 1 //;? (HCF_TYPE) & HCF_TYPE_STA
int status = -1;
#endif /* (HCF_TYPE) & HCF_TYPE_STA */
/*------------------------------------------------------------------------*/
DBG_FUNC( "wireless_get_bssid" );
DBG_ENTER( DbgInfo );
if(lp->portState == WVLAN_PORT_STATE_DISABLED) {
ret = -EBUSY;
goto out;
}
wl_lock( lp, &flags );
wl_act_int_off( lp );
memset( &ap_addr->sa_data, 0, ETH_ALEN );
ap_addr->sa_family = ARPHRD_ETHER;
/* Assume AP mode here, which means the BSSID is our own MAC address. In
STA mode, this address will be overwritten with the actual BSSID using
the code below. */
memcpy(&ap_addr->sa_data, lp->dev->dev_addr, ETH_ALEN);
#if 1 //;? (HCF_TYPE) & HCF_TYPE_STA
//;?should we return an error status in AP mode
if ( CNV_INT_TO_LITTLE( lp->hcfCtx.IFB_FWIdentity.comp_id ) == COMP_ID_FW_STA ) {
/* Get Current BSSID */
lp->ltvRecord.typ = CFG_CUR_BSSID;
lp->ltvRecord.len = 4;
status = hcf_get_info( &( lp->hcfCtx ), (LTVP)&( lp->ltvRecord ));
if( status == HCF_SUCCESS ) {
/* Copy info into sockaddr struct */
memcpy(&ap_addr->sa_data, lp->ltvRecord.u.u8, ETH_ALEN);
} else {
ret = -EFAULT;
}
}
#endif // (HCF_TYPE) & HCF_TYPE_STA
wl_act_int_on( lp );
wl_unlock(lp, &flags);
out:
DBG_LEAVE(DbgInfo);
return ret;
} // wireless_get_bssid
/*============================================================================*/
/*******************************************************************************
* wireless_get_ap_list()
*******************************************************************************
*
* DESCRIPTION:
*
* Gets the results of a network scan.
*
* PARAMETERS:
*
* wrq - the wireless request buffer
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
* NOTE: SIOCGIWAPLIST has been deprecated by SIOCSIWSCAN. This function
* implements SIOCGIWAPLIST only to provide backwards compatibility. For
* all systems using WIRELESS_EXT v14 and higher, use SIOCSIWSCAN!
*
******************************************************************************/
static int wireless_get_ap_list (struct net_device *dev, struct iw_request_info *info, struct iw_point *data, char *extra)
{
struct wl_private *lp = wl_priv(dev);
unsigned long flags;
int ret;
int num_aps = -1;
int sec_count = 0;
hcf_32 count;
struct sockaddr *hwa = NULL;
struct iw_quality *qual = NULL;
#ifdef WARP
ScanResult *p = &lp->scan_results;
#else
ProbeResult *p = &lp->probe_results;
#endif // WARP
/*------------------------------------------------------------------------*/
DBG_FUNC( "wireless_get_ap_list" );
DBG_ENTER( DbgInfo );
if(lp->portState == WVLAN_PORT_STATE_DISABLED) {
ret = -EBUSY;
goto out;
}
wl_lock( lp, &flags );
wl_act_int_off( lp );
/* Set the completion state to FALSE */
lp->scan_results.scan_complete = FALSE;
lp->probe_results.scan_complete = FALSE;
/* Channels to scan */
lp->ltvRecord.len = 2;
lp->ltvRecord.typ = CFG_SCAN_CHANNELS_2GHZ;
lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( 0x7FFF );
ret = hcf_put_info( &( lp->hcfCtx ), (LTVP)&( lp->ltvRecord ));
DBG_TRACE( DbgInfo, "CFG_SCAN_CHANNELS_2GHZ result: 0x%x\n", ret );
/* Set the SCAN_SSID to "ANY". Using this RID for scan prevents the need to
disassociate from the network we are currently on */
lp->ltvRecord.len = 2;
lp->ltvRecord.typ = CFG_SCAN_SSID;
lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( 0 );
ret = hcf_put_info( &( lp->hcfCtx ), (LTVP)&( lp->ltvRecord ));
DBG_TRACE( DbgInfo, "CFG_SCAN_SSID to 'any' ret: 0x%x\n", ret );
/* Initiate the scan */
#ifdef WARP
ret = hcf_action( &( lp->hcfCtx ), MDD_ACT_SCAN );
#else
ret = hcf_action( &( lp->hcfCtx ), HCF_ACT_ACS_SCAN );
#endif // WARP
wl_act_int_on( lp );
//;? unlock? what about the access to lp below? is it broken?
wl_unlock(lp, &flags);
if( ret == HCF_SUCCESS ) {
DBG_TRACE( DbgInfo, "SUCCESSFULLY INITIATED SCAN...\n" );
while( (*p).scan_complete == FALSE && ret == HCF_SUCCESS ) {
DBG_TRACE( DbgInfo, "Waiting for scan results...\n" );
/* Abort the scan if we've waited for more than MAX_SCAN_TIME_SEC */
if( sec_count++ > MAX_SCAN_TIME_SEC ) {
ret = -EIO;
} else {
/* Wait for 1 sec in 10ms intervals, scheduling the kernel to do
other things in the meantime, This prevents system lockups by
giving some time back to the kernel */
for( count = 0; count < 100; count ++ ) {
mdelay( 10 );
schedule( );
}
}
}
rmb();
if ( ret != HCF_SUCCESS ) {
DBG_ERROR( DbgInfo, "timeout waiting for scan results\n" );
} else {
num_aps = (*p)/*lp->probe_results*/.num_aps;
if (num_aps > IW_MAX_AP) {
num_aps = IW_MAX_AP;
}
data->length = num_aps;
hwa = (struct sockaddr *)extra;
qual = (struct iw_quality *) extra +
( sizeof( struct sockaddr ) * num_aps );
/* This flag is used to tell the user if we provide quality
information. Since we provide signal/noise levels but no
quality info on a scan, this is set to 0. Setting to 1 and
providing a quality of 0 produces weird results. If we ever
provide quality (or can calculate it), this can be changed */
data->flags = 0;
for( count = 0; count < num_aps; count++ ) {
#ifdef WARP
memcpy( hwa[count].sa_data,
(*p)/*lp->scan_results*/.APTable[count].bssid, ETH_ALEN );
#else //;?why use BSSID and bssid as names in seemingly very comparable situations
DBG_PRINT("BSSID: %pM\n",
(*p).ProbeTable[count].BSSID);
memcpy( hwa[count].sa_data,
(*p)/*lp->probe_results*/.ProbeTable[count].BSSID, ETH_ALEN );
#endif // WARP
}
/* Once the data is copied to the wireless struct, invalidate the
scan result to initiate a rescan on the next request */
(*p)/*lp->probe_results*/.scan_complete = FALSE;
/* Send the wireless event that the scan has completed, just in case
it's needed */
wl_wext_event_scan_complete( lp->dev );
}
}
out:
DBG_LEAVE( DbgInfo );
return ret;
} // wireless_get_ap_list
/*============================================================================*/
/*******************************************************************************
* wireless_set_sensitivity()
*******************************************************************************
*
* DESCRIPTION:
*
* Sets the sensitivity (distance between APs) of the wireless card.
*
* PARAMETERS:
*
* wrq - the wireless request buffer
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
static int wireless_set_sensitivity(struct net_device *dev, struct iw_request_info *info, struct iw_param *sens, char *extra)
{
struct wl_private *lp = wl_priv(dev);
unsigned long flags;
int ret = 0;
int dens = sens->value;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wireless_set_sensitivity" );
DBG_ENTER( DbgInfo );
if(lp->portState == WVLAN_PORT_STATE_DISABLED) {
ret = -EBUSY;
goto out;
}
if(( dens < 1 ) || ( dens > 3 )) {
ret = -EINVAL;
goto out;
}
wl_lock( lp, &flags );
wl_act_int_off( lp );
lp->DistanceBetweenAPs = dens;
wl_apply( lp );
wl_act_int_on( lp );
wl_unlock(lp, &flags);
out:
DBG_LEAVE( DbgInfo );
return ret;
} // wireless_set_sensitivity
/*============================================================================*/
/*******************************************************************************
* wireless_get_sensitivity()
*******************************************************************************
*
* DESCRIPTION:
*
* Gets the sensitivity (distance between APs) of the wireless card.
*
* PARAMETERS:
*
* wrq - the wireless request buffer
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
static int wireless_get_sensitivity(struct net_device *dev, struct iw_request_info *info, struct iw_param *sens, char *extra)
{
struct wl_private *lp = wl_priv(dev);
int ret = 0;
/*------------------------------------------------------------------------*/
/*------------------------------------------------------------------------*/
DBG_FUNC( "wireless_get_sensitivity" );
DBG_ENTER( DbgInfo );
if(lp->portState == WVLAN_PORT_STATE_DISABLED) {
ret = -EBUSY;
goto out;
}
/* not worth locking ... */
sens->value = lp->DistanceBetweenAPs;
sens->fixed = 0; /* auto */
out:
DBG_LEAVE( DbgInfo );
return ret;
} // wireless_get_sensitivity
/*============================================================================*/
/*******************************************************************************
* wireless_set_essid()
*******************************************************************************
*
* DESCRIPTION:
*
* Sets the ESSID (network name) that the wireless device should associate
* with.
*
* PARAMETERS:
*
* wrq - the wireless request buffer
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
static int wireless_set_essid(struct net_device *dev, struct iw_request_info *info, struct iw_point *data, char *ssid)
{
struct wl_private *lp = wl_priv(dev);
unsigned long flags;
int ret = 0;
DBG_FUNC( "wireless_set_essid" );
DBG_ENTER( DbgInfo );
if(lp->portState == WVLAN_PORT_STATE_DISABLED) {
ret = -EBUSY;
goto out;
}
if (data->flags != 0 && data->length > HCF_MAX_NAME_LEN + 1) {
ret = -EINVAL;
goto out;
}
wl_lock( lp, &flags );
wl_act_int_off( lp );
memset( lp->NetworkName, 0, sizeof( lp->NetworkName ));
/* data->flags is zero to ask for "any" */
if( data->flags == 0 ) {
/* Need this because in STAP build PARM_DEFAULT_SSID is "LinuxAP"
* ;?but there ain't no STAP anymore*/
if ( CNV_INT_TO_LITTLE( lp->hcfCtx.IFB_FWIdentity.comp_id ) == COMP_ID_FW_STA ) {
strcpy( lp->NetworkName, "ANY" );
} else {
//strcpy( lp->NetworkName, "ANY" );
strcpy( lp->NetworkName, PARM_DEFAULT_SSID );
}
} else {
memcpy( lp->NetworkName, ssid, data->length );
}
DBG_NOTICE( DbgInfo, "set NetworkName: %s\n", ssid );
/* Commit the adapter parameters */
wl_apply( lp );
/* Send an event that ESSID has been set */
wl_wext_event_essid( lp->dev );
wl_act_int_on( lp );
wl_unlock(lp, &flags);
out:
DBG_LEAVE( DbgInfo );
return ret;
} // wireless_set_essid
/*============================================================================*/
/*******************************************************************************
* wireless_get_essid()
*******************************************************************************
*
* DESCRIPTION:
*
* Gets the ESSID (network name) that the wireless device is associated
* with.
*
* PARAMETERS:
*
* wrq - the wireless request buffer
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
static int wireless_get_essid(struct net_device *dev, struct iw_request_info *info, struct iw_point *data, char *essid)
{
struct wl_private *lp = wl_priv(dev);
unsigned long flags;
int ret = 0;
int status = -1;
wvName_t *pName;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wireless_get_essid" );
DBG_ENTER( DbgInfo );
if(lp->portState == WVLAN_PORT_STATE_DISABLED) {
ret = -EBUSY;
goto out;
}
wl_lock( lp, &flags );
wl_act_int_off( lp );
/* Get the desired network name */
lp->ltvRecord.len = 1 + ( sizeof( *pName ) / sizeof( hcf_16 ));
#if 1 //;? (HCF_TYPE) & HCF_TYPE_STA
//;?should we return an error status in AP mode
lp->ltvRecord.typ = CFG_DESIRED_SSID;
#endif
#if 1 //;? (HCF_TYPE) & HCF_TYPE_AP
//;?should we restore this to allow smaller memory footprint
if ( CNV_INT_TO_LITTLE( lp->hcfCtx.IFB_FWIdentity.comp_id ) == COMP_ID_FW_AP ) {
lp->ltvRecord.typ = CFG_CNF_OWN_SSID;
}
#endif // HCF_AP
status = hcf_get_info( &( lp->hcfCtx ), (LTVP)&( lp->ltvRecord ));
if( status == HCF_SUCCESS ) {
pName = (wvName_t *)&( lp->ltvRecord.u.u32 );
/* Endian translate the string length */
pName->length = CNV_LITTLE_TO_INT( pName->length );
/* Copy the information into the user buffer */
data->length = pName->length;
/* NOTE: Null terminating is necessary for proper display of the SSID in
the wireless tools */
data->length = pName->length + 1;
if( pName->length < HCF_MAX_NAME_LEN ) {
pName->name[pName->length] = '\0';
}
data->flags = 1;
#if 1 //;? (HCF_TYPE) & HCF_TYPE_STA
//;?should we return an error status in AP mode
#ifdef RETURN_CURRENT_NETWORKNAME
/* if desired is null ("any"), return current or "any" */
if( pName->name[0] == '\0' ) {
/* Get the current network name */
lp->ltvRecord.len = 1 + ( sizeof(*pName ) / sizeof( hcf_16 ));
lp->ltvRecord.typ = CFG_CUR_SSID;
status = hcf_get_info( &( lp->hcfCtx ), (LTVP)&( lp->ltvRecord ));
if( status == HCF_SUCCESS ) {
pName = (wvName_t *)&( lp->ltvRecord.u.u32 );
/* Endian translate the string length */
pName->length = CNV_LITTLE_TO_INT( pName->length );
/* Copy the information into the user buffer */
data->length = pName->length + 1;
if( pName->length < HCF_MAX_NAME_LEN ) {
pName->name[pName->length] = '\0';
}
data->flags = 1;
} else {
ret = -EFAULT;
goto out_unlock;
}
}
#endif // RETURN_CURRENT_NETWORKNAME
#endif // HCF_STA
data->length--;
if (pName->length > IW_ESSID_MAX_SIZE) {
ret = -EFAULT;
goto out_unlock;
}
memcpy(essid, pName->name, pName->length);
} else {
ret = -EFAULT;
goto out_unlock;
}
out_unlock:
wl_act_int_on( lp );
wl_unlock(lp, &flags);
out:
DBG_LEAVE( DbgInfo );
return ret;
} // wireless_get_essid
/*============================================================================*/
/*******************************************************************************
* wireless_set_encode()
*******************************************************************************
*
* DESCRIPTION:
*
* Sets the encryption keys and status (enable or disable).
*
* PARAMETERS:
*
* wrq - the wireless request buffer
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
static int wireless_set_encode(struct net_device *dev, struct iw_request_info *info, struct iw_point *erq, char *keybuf)
{
struct wl_private *lp = wl_priv(dev);
unsigned long flags;
int ret = 0;
#if 1 //;? #if WIRELESS_EXT > 8 - used unconditionally in the rest of the code...
hcf_8 encryption_state;
#endif // WIRELESS_EXT > 8
/*------------------------------------------------------------------------*/
DBG_FUNC( "wireless_set_encode" );
DBG_ENTER( DbgInfo );
if(lp->portState == WVLAN_PORT_STATE_DISABLED) {
ret = -EBUSY;
goto out;
}
wl_lock( lp, &flags );
wl_act_int_off( lp );
/* Is encryption supported? */
if( !wl_has_wep( &( lp->hcfCtx ))) {
DBG_WARNING( DbgInfo, "WEP not supported on this device\n" );
ret = -EOPNOTSUPP;
goto out_unlock;
}
DBG_NOTICE( DbgInfo, "pointer: %p, length: %d, flags: %#x\n",
keybuf, erq->length,
erq->flags);
/* Save state of Encryption switch */
encryption_state = lp->EnableEncryption;
/* Basic checking: do we have a key to set? */
if((erq->length) != 0) {
int index = ( erq->flags & IW_ENCODE_INDEX ) - 1;
int tk = lp->TransmitKeyID - 1; // current key
/* Check the size of the key */
switch(erq->length) {
case 0:
break;
case MIN_KEY_SIZE:
case MAX_KEY_SIZE:
/* Check the index */
if(( index < 0 ) || ( index >= MAX_KEYS )) {
index = tk;
}
/* Cleanup */
memset( lp->DefaultKeys.key[index].key, 0, MAX_KEY_SIZE );
/* Copy the key in the driver */
memcpy( lp->DefaultKeys.key[index].key, keybuf, erq->length);
/* Set the length */
lp->DefaultKeys.key[index].len = erq->length;
DBG_NOTICE( DbgInfo, "encoding.length: %d\n", erq->length );
DBG_NOTICE( DbgInfo, "set key: %s(%d) [%d]\n", lp->DefaultKeys.key[index].key,
lp->DefaultKeys.key[index].len, index );
/* Enable WEP (if possible) */
if(( index == tk ) && ( lp->DefaultKeys.key[tk].len > 0 )) {
lp->EnableEncryption = 1;
}
break;
default:
DBG_WARNING( DbgInfo, "Invalid Key length\n" );
ret = -EINVAL;
goto out_unlock;
}
} else {
int index = ( erq->flags & IW_ENCODE_INDEX ) - 1;
/* Do we want to just set the current transmit key? */
if(( index >= 0 ) && ( index < MAX_KEYS )) {
DBG_NOTICE( DbgInfo, "index: %d; len: %d\n", index,
lp->DefaultKeys.key[index].len );
if( lp->DefaultKeys.key[index].len > 0 ) {
lp->TransmitKeyID = index + 1;
lp->EnableEncryption = 1;
} else {
DBG_WARNING( DbgInfo, "Problem setting the current TxKey\n" );
DBG_LEAVE( DbgInfo );
ret = -EINVAL;
}
}
}
/* Read the flags */
if( erq->flags & IW_ENCODE_DISABLED ) {
lp->EnableEncryption = 0; // disable encryption
} else {
lp->EnableEncryption = 1;
}
if( erq->flags & IW_ENCODE_RESTRICTED ) {
DBG_WARNING( DbgInfo, "IW_ENCODE_RESTRICTED invalid\n" );
ret = -EINVAL; // Invalid
}
DBG_TRACE( DbgInfo, "encryption_state : %d\n", encryption_state );
DBG_TRACE( DbgInfo, "lp->EnableEncryption : %d\n", lp->EnableEncryption );
DBG_TRACE( DbgInfo, "erq->length : %d\n",
erq->length);
DBG_TRACE( DbgInfo, "erq->flags : 0x%x\n",
erq->flags);
/* Write the changes to the card */
if( ret == 0 ) {
DBG_NOTICE( DbgInfo, "encrypt: %d, ID: %d\n", lp->EnableEncryption,
lp->TransmitKeyID );
if( lp->EnableEncryption == encryption_state ) {
if( erq->length != 0 ) {
/* Dynamic WEP key update */
wl_set_wep_keys( lp );
}
} else {
/* To switch encryption on/off, soft reset is required */
wl_apply( lp );
}
}
/* Send an event that Encryption has been set */
wl_wext_event_encode( dev );
out_unlock:
wl_act_int_on( lp );
wl_unlock(lp, &flags);
out:
DBG_LEAVE( DbgInfo );
return ret;
} // wireless_set_encode
/*============================================================================*/
/*******************************************************************************
* wireless_get_encode()
*******************************************************************************
*
* DESCRIPTION:
*
* Gets the encryption keys and status.
*
* PARAMETERS:
*
* wrq - the wireless request buffer
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
static int wireless_get_encode(struct net_device *dev, struct iw_request_info *info, struct iw_point *erq, char *key)
{
struct wl_private *lp = wl_priv(dev);
unsigned long flags;
int ret = 0;
int index;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wireless_get_encode" );
DBG_ENTER( DbgInfo );
DBG_NOTICE(DbgInfo, "GIWENCODE: encrypt: %d, ID: %d\n", lp->EnableEncryption, lp->TransmitKeyID);
if(lp->portState == WVLAN_PORT_STATE_DISABLED) {
ret = -EBUSY;
goto out;
}
/* Only super-user can see WEP key */
if( !capable( CAP_NET_ADMIN )) {
ret = -EPERM;
DBG_LEAVE( DbgInfo );
return ret;
}
wl_lock( lp, &flags );
wl_act_int_off( lp );
/* Is it supported? */
if( !wl_has_wep( &( lp->hcfCtx ))) {
ret = -EOPNOTSUPP;
goto out_unlock;
}
/* Basic checking */
index = (erq->flags & IW_ENCODE_INDEX ) - 1;
/* Set the flags */
erq->flags = 0;
if( lp->EnableEncryption == 0 ) {
erq->flags |= IW_ENCODE_DISABLED;
}
/* Which key do we want */
if(( index < 0 ) || ( index >= MAX_KEYS )) {
index = lp->TransmitKeyID - 1;
}
erq->flags |= index + 1;
/* Copy the key to the user buffer */
erq->length = lp->DefaultKeys.key[index].len;
memcpy(key, lp->DefaultKeys.key[index].key, erq->length);
out_unlock:
wl_act_int_on( lp );
wl_unlock(lp, &flags);
out:
DBG_LEAVE( DbgInfo );
return ret;
} // wireless_get_encode
/*============================================================================*/
/*******************************************************************************
* wireless_set_nickname()
*******************************************************************************
*
* DESCRIPTION:
*
* Sets the nickname, or station name, of the wireless device.
*
* PARAMETERS:
*
* wrq - the wireless request buffer
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
static int wireless_set_nickname(struct net_device *dev, struct iw_request_info *info, struct iw_point *data, char *nickname)
{
struct wl_private *lp = wl_priv(dev);
unsigned long flags;
int ret = 0;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wireless_set_nickname" );
DBG_ENTER( DbgInfo );
if(lp->portState == WVLAN_PORT_STATE_DISABLED) {
ret = -EBUSY;
goto out;
}
#if 0 //;? Needed, was present in original code but not in 7.18 Linux 2.6 kernel version
if( !capable(CAP_NET_ADMIN )) {
ret = -EPERM;
DBG_LEAVE( DbgInfo );
return ret;
}
#endif
/* Validate the new value */
if(data->length > HCF_MAX_NAME_LEN) {
ret = -EINVAL;
goto out;
}
wl_lock( lp, &flags );
wl_act_int_off( lp );
memset( lp->StationName, 0, sizeof( lp->StationName ));
memcpy( lp->StationName, nickname, data->length );
/* Commit the adapter parameters */
wl_apply( lp );
wl_act_int_on( lp );
wl_unlock(lp, &flags);
out:
DBG_LEAVE( DbgInfo );
return ret;
} // wireless_set_nickname
/*============================================================================*/
/*******************************************************************************
* wireless_get_nickname()
*******************************************************************************
*
* DESCRIPTION:
*
* Gets the nickname, or station name, of the wireless device.
*
* PARAMETERS:
*
* wrq - the wireless request buffer
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
static int wireless_get_nickname(struct net_device *dev, struct iw_request_info *info, struct iw_point *data, char *nickname)
{
struct wl_private *lp = wl_priv(dev);
unsigned long flags;
int ret = 0;
int status = -1;
wvName_t *pName;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wireless_get_nickname" );
DBG_ENTER( DbgInfo );
if(lp->portState == WVLAN_PORT_STATE_DISABLED) {
ret = -EBUSY;
goto out;
}
wl_lock( lp, &flags );
wl_act_int_off( lp );
/* Get the current station name */
lp->ltvRecord.len = 1 + ( sizeof( *pName ) / sizeof( hcf_16 ));
lp->ltvRecord.typ = CFG_CNF_OWN_NAME;
status = hcf_get_info( &( lp->hcfCtx ), (LTVP)&( lp->ltvRecord ));
if( status == HCF_SUCCESS ) {
pName = (wvName_t *)&( lp->ltvRecord.u.u32 );
/* Endian translate the length */
pName->length = CNV_LITTLE_TO_INT( pName->length );
if ( pName->length > IW_ESSID_MAX_SIZE ) {
ret = -EFAULT;
} else {
/* Copy the information into the user buffer */
data->length = pName->length;
memcpy(nickname, pName->name, pName->length);
}
} else {
ret = -EFAULT;
}
wl_act_int_on( lp );
wl_unlock(lp, &flags);
out:
DBG_LEAVE(DbgInfo);
return ret;
} // wireless_get_nickname
/*============================================================================*/
/*******************************************************************************
* wireless_set_porttype()
*******************************************************************************
*
* DESCRIPTION:
*
* Sets the port type of the wireless device.
*
* PARAMETERS:
*
* wrq - the wireless request buffer
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
static int wireless_set_porttype(struct net_device *dev, struct iw_request_info *info, __u32 *mode, char *extra)
{
struct wl_private *lp = wl_priv(dev);
unsigned long flags;
int ret = 0;
hcf_16 portType;
hcf_16 createIBSS;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wireless_set_porttype" );
DBG_ENTER( DbgInfo );
if(lp->portState == WVLAN_PORT_STATE_DISABLED) {
ret = -EBUSY;
goto out;
}
wl_lock( lp, &flags );
wl_act_int_off( lp );
/* Validate the new value */
switch( *mode ) {
case IW_MODE_ADHOC:
/* When user requests ad-hoc, set IBSS mode! */
portType = 1;
createIBSS = 1;
lp->DownloadFirmware = WVLAN_DRV_MODE_STA; //1;
break;
case IW_MODE_AUTO:
case IW_MODE_INFRA:
/* Both automatic and infrastructure set port to BSS/STA mode */
portType = 1;
createIBSS = 0;
lp->DownloadFirmware = WVLAN_DRV_MODE_STA; //1;
break;
#if 0 //;? (HCF_TYPE) & HCF_TYPE_AP
case IW_MODE_MASTER:
/* Set BSS/AP mode */
portType = 1;
lp->CreateIBSS = 0;
lp->DownloadFirmware = WVLAN_DRV_MODE_AP; //2;
break;
#endif /* (HCF_TYPE) & HCF_TYPE_AP */
default:
portType = 0;
createIBSS = 0;
ret = -EINVAL;
}
if( portType != 0 ) {
/* Only do something if there is a mode change */
if( ( lp->PortType != portType ) || (lp->CreateIBSS != createIBSS)) {
lp->PortType = portType;
lp->CreateIBSS = createIBSS;
/* Commit the adapter parameters */
wl_go( lp );
/* Send an event that mode has been set */
wl_wext_event_mode( lp->dev );
}
}
wl_act_int_on( lp );
wl_unlock(lp, &flags);
out:
DBG_LEAVE( DbgInfo );
return ret;
} // wireless_set_porttype
/*============================================================================*/
/*******************************************************************************
* wireless_get_porttype()
*******************************************************************************
*
* DESCRIPTION:
*
* Gets the port type of the wireless device.
*
* PARAMETERS:
*
* wrq - the wireless request buffer
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
static int wireless_get_porttype(struct net_device *dev, struct iw_request_info *info, __u32 *mode, char *extra)
{
struct wl_private *lp = wl_priv(dev);
unsigned long flags;
int ret = 0;
int status = -1;
hcf_16 *pPortType;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wireless_get_porttype" );
DBG_ENTER( DbgInfo );
if(lp->portState == WVLAN_PORT_STATE_DISABLED) {
ret = -EBUSY;
goto out;
}
wl_lock( lp, &flags );
wl_act_int_off( lp );
/* Get the current port type */
lp->ltvRecord.len = 1 + ( sizeof( *pPortType ) / sizeof( hcf_16 ));
lp->ltvRecord.typ = CFG_CNF_PORT_TYPE;
status = hcf_get_info( &( lp->hcfCtx ), (LTVP)&( lp->ltvRecord ));
if( status == HCF_SUCCESS ) {
pPortType = (hcf_16 *)&( lp->ltvRecord.u.u32 );
*pPortType = CNV_LITTLE_TO_INT( *pPortType );
switch( *pPortType ) {
case 1:
#if 0
#if (HCF_TYPE) & HCF_TYPE_AP
if ( CNV_INT_TO_LITTLE( lp->hcfCtx.IFB_FWIdentity.comp_id ) == COMP_ID_FW_AP ) {
*mode = IW_MODE_MASTER;
} else {
*mode = IW_MODE_INFRA;
}
#else
*mode = IW_MODE_INFRA;
#endif /* (HCF_TYPE) & HCF_TYPE_AP */
#endif
if ( CNV_INT_TO_LITTLE( lp->hcfCtx.IFB_FWIdentity.comp_id ) == COMP_ID_FW_AP ) {
*mode = IW_MODE_MASTER;
} else {
if( lp->CreateIBSS ) {
*mode = IW_MODE_ADHOC;
} else {
*mode = IW_MODE_INFRA;
}
}
break;
case 3:
*mode = IW_MODE_ADHOC;
break;
default:
ret = -EFAULT;
break;
}
} else {
ret = -EFAULT;
}
wl_act_int_on( lp );
wl_unlock(lp, &flags);
out:
DBG_LEAVE( DbgInfo );
return ret;
} // wireless_get_porttype
/*============================================================================*/
/*******************************************************************************
* wireless_set_power()
*******************************************************************************
*
* DESCRIPTION:
*
* Sets the power management settings of the wireless device.
*
* PARAMETERS:
*
* wrq - the wireless request buffer
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
static int wireless_set_power(struct net_device *dev, struct iw_request_info *info, struct iw_param *wrq, char *extra)
{
struct wl_private *lp = wl_priv(dev);
unsigned long flags;
int ret = 0;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wireless_set_power" );
DBG_ENTER( DbgInfo );
if(lp->portState == WVLAN_PORT_STATE_DISABLED) {
ret = -EBUSY;
goto out;
}
DBG_PRINT( "THIS CORRUPTS PMEnabled ;?!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n" );
#if 0 //;? Needed, was present in original code but not in 7.18 Linux 2.6 kernel version
if( !capable( CAP_NET_ADMIN )) {
ret = -EPERM;
DBG_LEAVE( DbgInfo );
return ret;
}
#endif
wl_lock( lp, &flags );
wl_act_int_off( lp );
/* Set the power management state based on the 'disabled' value */
if( wrq->disabled ) {
lp->PMEnabled = 0;
} else {
lp->PMEnabled = 1;
}
/* Commit the adapter parameters */
wl_apply( lp );
wl_act_int_on( lp );
wl_unlock(lp, &flags);
out:
DBG_LEAVE( DbgInfo );
return ret;
} // wireless_set_power
/*============================================================================*/
/*******************************************************************************
* wireless_get_power()
*******************************************************************************
*
* DESCRIPTION:
*
* Gets the power management settings of the wireless device.
*
* PARAMETERS:
*
* wrq - the wireless request buffer
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
static int wireless_get_power(struct net_device *dev, struct iw_request_info *info, struct iw_param *rrq, char *extra)
{
struct wl_private *lp = wl_priv(dev);
unsigned long flags;
int ret = 0;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wireless_get_power" );
DBG_ENTER( DbgInfo );
if(lp->portState == WVLAN_PORT_STATE_DISABLED) {
ret = -EBUSY;
goto out;
}
DBG_PRINT( "THIS IS PROBABLY AN OVER-SIMPLIFICATION ;?!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n" );
wl_lock( lp, &flags );
wl_act_int_off( lp );
rrq->flags = 0;
rrq->value = 0;
if( lp->PMEnabled ) {
rrq->disabled = 0;
} else {
rrq->disabled = 1;
}
wl_act_int_on( lp );
wl_unlock(lp, &flags);
out:
DBG_LEAVE( DbgInfo );
return ret;
} // wireless_get_power
/*============================================================================*/
/*******************************************************************************
* wireless_get_tx_power()
*******************************************************************************
*
* DESCRIPTION:
*
* Gets the transmit power of the wireless device's radio.
*
* PARAMETERS:
*
* wrq - the wireless request buffer
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
static int wireless_get_tx_power(struct net_device *dev, struct iw_request_info *info, struct iw_param *rrq, char *extra)
{
struct wl_private *lp = wl_priv(dev);
unsigned long flags;
int ret = 0;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wireless_get_tx_power" );
DBG_ENTER( DbgInfo );
if(lp->portState == WVLAN_PORT_STATE_DISABLED) {
ret = -EBUSY;
goto out;
}
wl_lock( lp, &flags );
wl_act_int_off( lp );
#ifdef USE_POWER_DBM
rrq->value = RADIO_TX_POWER_DBM;
rrq->flags = IW_TXPOW_DBM;
#else
rrq->value = RADIO_TX_POWER_MWATT;
rrq->flags = IW_TXPOW_MWATT;
#endif
rrq->fixed = 1;
rrq->disabled = 0;
wl_act_int_on( lp );
wl_unlock(lp, &flags);
out:
DBG_LEAVE( DbgInfo );
return ret;
} // wireless_get_tx_power
/*============================================================================*/
/*******************************************************************************
* wireless_set_rts_threshold()
*******************************************************************************
*
* DESCRIPTION:
*
* Sets the RTS threshold for the wireless card.
*
* PARAMETERS:
*
* wrq - the wireless request buffer
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
static int wireless_set_rts_threshold (struct net_device *dev, struct iw_request_info *info, struct iw_param *rts, char *extra)
{
int ret = 0;
struct wl_private *lp = wl_priv(dev);
unsigned long flags;
int rthr = rts->value;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wireless_set_rts_threshold" );
DBG_ENTER( DbgInfo );
if(lp->portState == WVLAN_PORT_STATE_DISABLED) {
ret = -EBUSY;
goto out;
}
if(rts->fixed == 0) {
ret = -EINVAL;
goto out;
}
#if WIRELESS_EXT > 8
if( rts->disabled ) {
rthr = 2347;
}
#endif /* WIRELESS_EXT > 8 */
if(( rthr < 256 ) || ( rthr > 2347 )) {
ret = -EINVAL;
goto out;
}
wl_lock( lp, &flags );
wl_act_int_off( lp );
lp->RTSThreshold = rthr;
wl_apply( lp );
wl_act_int_on( lp );
wl_unlock(lp, &flags);
out:
DBG_LEAVE( DbgInfo );
return ret;
} // wireless_set_rts_threshold
/*============================================================================*/
/*******************************************************************************
* wireless_get_rts_threshold()
*******************************************************************************
*
* DESCRIPTION:
*
* Gets the RTS threshold for the wireless card.
*
* PARAMETERS:
*
* wrq - the wireless request buffer
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
static int wireless_get_rts_threshold (struct net_device *dev, struct iw_request_info *info, struct iw_param *rts, char *extra)
{
int ret = 0;
struct wl_private *lp = wl_priv(dev);
unsigned long flags;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wireless_get_rts_threshold" );
DBG_ENTER( DbgInfo );
if(lp->portState == WVLAN_PORT_STATE_DISABLED) {
ret = -EBUSY;
goto out;
}
wl_lock( lp, &flags );
wl_act_int_off( lp );
rts->value = lp->RTSThreshold;
#if WIRELESS_EXT > 8
rts->disabled = ( rts->value == 2347 );
#endif /* WIRELESS_EXT > 8 */
rts->fixed = 1;
wl_act_int_on( lp );
wl_unlock(lp, &flags);
out:
DBG_LEAVE( DbgInfo );
return ret;
} // wireless_get_rts_threshold
/*============================================================================*/
/*******************************************************************************
* wireless_set_rate()
*******************************************************************************
*
* DESCRIPTION:
*
* Set the default data rate setting used by the wireless device.
*
* PARAMETERS:
*
* wrq - the wireless request buffer
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
static int wireless_set_rate(struct net_device *dev, struct iw_request_info *info, struct iw_param *rrq, char *extra)
{
struct wl_private *lp = wl_priv(dev);
unsigned long flags;
int ret = 0;
#ifdef WARP
int status = -1;
int index = 0;
#endif // WARP
/*------------------------------------------------------------------------*/
DBG_FUNC( "wireless_set_rate" );
DBG_ENTER( DbgInfo );
if(lp->portState == WVLAN_PORT_STATE_DISABLED) {
ret = -EBUSY;
goto out;
}
wl_lock( lp, &flags );
wl_act_int_off( lp );
#ifdef WARP
/* Determine if the card is operating in the 2.4 or 5.0 GHz band; check
if Bit 9 is set in the current channel RID */
lp->ltvRecord.len = 2;
lp->ltvRecord.typ = CFG_CUR_CHANNEL;
status = hcf_get_info( &( lp->hcfCtx ), (LTVP)&( lp->ltvRecord ));
if( status == HCF_SUCCESS ) {
index = ( CNV_LITTLE_TO_INT( lp->ltvRecord.u.u16[0] ) & 0x100 ) ? 1 : 0;
DBG_PRINT( "Index: %d\n", index );
} else {
DBG_ERROR( DbgInfo, "Could not determine radio frequency\n" );
DBG_LEAVE( DbgInfo );
ret = -EINVAL;
goto out_unlock;
}
if( rrq->value > 0 &&
rrq->value <= 1 * MEGABIT ) {
lp->TxRateControl[index] = 0x0001;
}
else if( rrq->value > 1 * MEGABIT &&
rrq->value <= 2 * MEGABIT ) {
if( rrq->fixed == 1 ) {
lp->TxRateControl[index] = 0x0002;
} else {
lp->TxRateControl[index] = 0x0003;
}
}
else if( rrq->value > 2 * MEGABIT &&
rrq->value <= 5 * MEGABIT ) {
if( rrq->fixed == 1 ) {
lp->TxRateControl[index] = 0x0004;
} else {
lp->TxRateControl[index] = 0x0007;
}
}
else if( rrq->value > 5 * MEGABIT &&
rrq->value <= 6 * MEGABIT ) {
if( rrq->fixed == 1 ) {
lp->TxRateControl[index] = 0x0010;
} else {
lp->TxRateControl[index] = 0x0017;
}
}
else if( rrq->value > 6 * MEGABIT &&
rrq->value <= 9 * MEGABIT ) {
if( rrq->fixed == 1 ) {
lp->TxRateControl[index] = 0x0020;
} else {
lp->TxRateControl[index] = 0x0037;
}
}
else if( rrq->value > 9 * MEGABIT &&
rrq->value <= 11 * MEGABIT ) {
if( rrq->fixed == 1 ) {
lp->TxRateControl[index] = 0x0008;
} else {
lp->TxRateControl[index] = 0x003F;
}
}
else if( rrq->value > 11 * MEGABIT &&
rrq->value <= 12 * MEGABIT ) {
if( rrq->fixed == 1 ) {
lp->TxRateControl[index] = 0x0040;
} else {
lp->TxRateControl[index] = 0x007F;
}
}
else if( rrq->value > 12 * MEGABIT &&
rrq->value <= 18 * MEGABIT ) {
if( rrq->fixed == 1 ) {
lp->TxRateControl[index] = 0x0080;
} else {
lp->TxRateControl[index] = 0x00FF;
}
}
else if( rrq->value > 18 * MEGABIT &&
rrq->value <= 24 * MEGABIT ) {
if( rrq->fixed == 1 ) {
lp->TxRateControl[index] = 0x0100;
} else {
lp->TxRateControl[index] = 0x01FF;
}
}
else if( rrq->value > 24 * MEGABIT &&
rrq->value <= 36 * MEGABIT ) {
if( rrq->fixed == 1 ) {
lp->TxRateControl[index] = 0x0200;
} else {
lp->TxRateControl[index] = 0x03FF;
}
}
else if( rrq->value > 36 * MEGABIT &&
rrq->value <= 48 * MEGABIT ) {
if( rrq->fixed == 1 ) {
lp->TxRateControl[index] = 0x0400;
} else {
lp->TxRateControl[index] = 0x07FF;
}
}
else if( rrq->value > 48 * MEGABIT &&
rrq->value <= 54 * MEGABIT ) {
if( rrq->fixed == 1 ) {
lp->TxRateControl[index] = 0x0800;
} else {
lp->TxRateControl[index] = 0x0FFF;
}
}
else if( rrq->fixed == 0 ) {
/* In this case, the user has not specified a bitrate, only the "auto"
moniker. So, set to all supported rates */
lp->TxRateControl[index] = PARM_MAX_TX_RATE;
} else {
rrq->value = 0;
ret = -EINVAL;
goto out_unlock;
}
#else
if( rrq->value > 0 &&
rrq->value <= 1 * MEGABIT ) {
lp->TxRateControl[0] = 1;
}
else if( rrq->value > 1 * MEGABIT &&
rrq->value <= 2 * MEGABIT ) {
if( rrq->fixed ) {
lp->TxRateControl[0] = 2;
} else {
lp->TxRateControl[0] = 6;
}
}
else if( rrq->value > 2 * MEGABIT &&
rrq->value <= 5 * MEGABIT ) {
if( rrq->fixed ) {
lp->TxRateControl[0] = 4;
} else {
lp->TxRateControl[0] = 7;
}
}
else if( rrq->value > 5 * MEGABIT &&
rrq->value <= 11 * MEGABIT ) {
if( rrq->fixed) {
lp->TxRateControl[0] = 5;
} else {
lp->TxRateControl[0] = 3;
}
}
else if( rrq->fixed == 0 ) {
/* In this case, the user has not specified a bitrate, only the "auto"
moniker. So, set the rate to 11Mb auto */
lp->TxRateControl[0] = 3;
} else {
rrq->value = 0;
ret = -EINVAL;
goto out_unlock;
}
#endif // WARP
/* Commit the adapter parameters */
wl_apply( lp );
out_unlock:
wl_act_int_on( lp );
wl_unlock(lp, &flags);
out:
DBG_LEAVE( DbgInfo );
return ret;
} // wireless_set_rate
/*============================================================================*/
/*******************************************************************************
* wireless_get_rate()
*******************************************************************************
*
* DESCRIPTION:
*
* Get the default data rate setting used by the wireless device.
*
* PARAMETERS:
*
* wrq - the wireless request buffer
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
static int wireless_get_rate(struct net_device *dev, struct iw_request_info *info, struct iw_param *rrq, char *extra)
{
struct wl_private *lp = wl_priv(dev);
unsigned long flags;
int ret = 0;
int status = -1;
hcf_16 txRate;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wireless_get_rate" );
DBG_ENTER( DbgInfo );
if(lp->portState == WVLAN_PORT_STATE_DISABLED) {
ret = -EBUSY;
goto out;
}
wl_lock( lp, &flags );
wl_act_int_off( lp );
/* Get the current transmit rate from the adapter */
lp->ltvRecord.len = 1 + ( sizeof(txRate)/sizeof(hcf_16));
lp->ltvRecord.typ = CFG_CUR_TX_RATE;
status = hcf_get_info( &( lp->hcfCtx ), (LTVP)&( lp->ltvRecord ));
if( status == HCF_SUCCESS ) {
#ifdef WARP
txRate = CNV_LITTLE_TO_INT( lp->ltvRecord.u.u16[0] );
if( txRate & 0x0001 ) {
txRate = 1;
}
else if( txRate & 0x0002 ) {
txRate = 2;
}
else if( txRate & 0x0004 ) {
txRate = 5;
}
else if( txRate & 0x0008 ) {
txRate = 11;
}
else if( txRate & 0x00010 ) {
txRate = 6;
}
else if( txRate & 0x00020 ) {
txRate = 9;
}
else if( txRate & 0x00040 ) {
txRate = 12;
}
else if( txRate & 0x00080 ) {
txRate = 18;
}
else if( txRate & 0x00100 ) {
txRate = 24;
}
else if( txRate & 0x00200 ) {
txRate = 36;
}
else if( txRate & 0x00400 ) {
txRate = 48;
}
else if( txRate & 0x00800 ) {
txRate = 54;
}
#else
txRate = (hcf_16)CNV_LITTLE_TO_LONG( lp->ltvRecord.u.u32[0] );
#endif // WARP
rrq->value = txRate * MEGABIT;
} else {
rrq->value = 0;
ret = -EFAULT;
}
wl_act_int_on( lp );
wl_unlock(lp, &flags);
out:
DBG_LEAVE( DbgInfo );
return ret;
} // wireless_get_rate
/*============================================================================*/
#if 0 //;? Not used anymore
/*******************************************************************************
* wireless_get_private_interface()
*******************************************************************************
*
* DESCRIPTION:
*
* Returns the Linux Wireless Extensions' compatible private interface of
* the driver.
*
* PARAMETERS:
*
* wrq - the wireless request buffer
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
int wireless_get_private_interface( struct iwreq *wrq, struct wl_private *lp )
{
int ret = 0;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wireless_get_private_interface" );
DBG_ENTER( DbgInfo );
if(lp->portState == WVLAN_PORT_STATE_DISABLED) {
ret = -EBUSY;
goto out;
}
if( wrq->u.data.pointer != NULL ) {
struct iw_priv_args priv[] =
{
{ SIOCSIWNETNAME, IW_PRIV_TYPE_CHAR | HCF_MAX_NAME_LEN, 0, "snetwork_name" },
{ SIOCGIWNETNAME, 0, IW_PRIV_TYPE_CHAR | HCF_MAX_NAME_LEN, "gnetwork_name" },
{ SIOCSIWSTANAME, IW_PRIV_TYPE_CHAR | HCF_MAX_NAME_LEN, 0, "sstation_name" },
{ SIOCGIWSTANAME, 0, IW_PRIV_TYPE_CHAR | HCF_MAX_NAME_LEN, "gstation_name" },
{ SIOCSIWPORTTYPE, IW_PRIV_TYPE_BYTE | IW_PRIV_SIZE_FIXED | 1, 0, "sport_type" },
{ SIOCGIWPORTTYPE, 0, IW_PRIV_TYPE_BYTE | IW_PRIV_SIZE_FIXED | 1, "gport_type" },
};
/* Verify the user buffer */
ret = verify_area( VERIFY_WRITE, wrq->u.data.pointer, sizeof( priv ));
if( ret != 0 ) {
DBG_LEAVE( DbgInfo );
return ret;
}
/* Copy the data into the user's buffer */
wrq->u.data.length = NELEM( priv );
copy_to_user( wrq->u.data.pointer, &priv, sizeof( priv ));
}
out:
DBG_LEAVE( DbgInfo );
return ret;
} // wireless_get_private_interface
/*============================================================================*/
#endif
#if WIRELESS_EXT > 13
/*******************************************************************************
* wireless_set_scan()
*******************************************************************************
*
* DESCRIPTION:
*
* Instructs the driver to initiate a network scan.
*
* PARAMETERS:
*
* wrq - the wireless request buffer
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
static int wireless_set_scan(struct net_device *dev, struct iw_request_info *info, struct iw_point *data, char *extra)
{
struct wl_private *lp = wl_priv(dev);
unsigned long flags;
int ret = 0;
int status = -1;
int retries = 0;
/*------------------------------------------------------------------------*/
//;? Note: shows results as trace, retruns always 0 unless BUSY
DBG_FUNC( "wireless_set_scan" );
DBG_ENTER( DbgInfo );
if(lp->portState == WVLAN_PORT_STATE_DISABLED) {
ret = -EBUSY;
goto out;
}
wl_lock( lp, &flags );
wl_act_int_off( lp );
/*
* This looks like a nice place to test if the HCF is still
* communicating with the card. It seems that sometimes BAP_1
* gets corrupted. By looking at the comments in HCF the
* cause is still a mystery. Okay, the communication to the
* card is dead, reset the card to revive.
*/
if((lp->hcfCtx.IFB_CardStat & CARD_STAT_DEFUNCT) != 0)
{
DBG_TRACE( DbgInfo, "CARD is in DEFUNCT mode, reset it to bring it back to life\n" );
wl_reset( dev );
}
retry:
/* Set the completion state to FALSE */
lp->probe_results.scan_complete = FALSE;
/* Channels to scan */
#ifdef WARP
lp->ltvRecord.len = 5;
lp->ltvRecord.typ = CFG_SCAN_CHANNEL;
lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( 0x3FFF ); // 2.4 GHz Band
lp->ltvRecord.u.u16[1] = CNV_INT_TO_LITTLE( 0xFFFF ); // 5.0 GHz Band
lp->ltvRecord.u.u16[2] = CNV_INT_TO_LITTLE( 0xFFFF ); // ..
lp->ltvRecord.u.u16[3] = CNV_INT_TO_LITTLE( 0x0007 ); // ..
#else
lp->ltvRecord.len = 2;
lp->ltvRecord.typ = CFG_SCAN_CHANNEL;
lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( 0x7FFF );
#endif // WARP
status = hcf_put_info( &( lp->hcfCtx ), (LTVP)&( lp->ltvRecord ));
DBG_TRACE( DbgInfo, "CFG_SCAN_CHANNEL result : 0x%x\n", status );
// Holding the lock too long, make a gap to allow other processes
wl_unlock(lp, &flags);
wl_lock( lp, &flags );
if( status != HCF_SUCCESS ) {
//Recovery
retries++;
if(retries <= 10) {
DBG_TRACE( DbgInfo, "Reset card to recover, attempt: %d\n", retries );
wl_reset( dev );
// Holding the lock too long, make a gap to allow other processes
wl_unlock(lp, &flags);
wl_lock( lp, &flags );
goto retry;
}
}
/* Set the SCAN_SSID to "ANY". Using this RID for scan prevents the need to
disassociate from the network we are currently on */
lp->ltvRecord.len = 18;
lp->ltvRecord.typ = CFG_SCAN_SSID;
lp->ltvRecord.u.u16[0] = CNV_INT_TO_LITTLE( 0 );
lp->ltvRecord.u.u16[1] = CNV_INT_TO_LITTLE( 0 );
status = hcf_put_info( &( lp->hcfCtx ), (LTVP)&( lp->ltvRecord ));
// Holding the lock too long, make a gap to allow other processes
wl_unlock(lp, &flags);
wl_lock( lp, &flags );
DBG_TRACE( DbgInfo, "CFG_SCAN_SSID to 'any' status: 0x%x\n", status );
/* Initiate the scan */
/* NOTE: Using HCF_ACT_SCAN has been removed, as using HCF_ACT_ACS_SCAN to
retrieve probe responses must always be used to support WPA */
status = hcf_action( &( lp->hcfCtx ), HCF_ACT_ACS_SCAN );
if( status == HCF_SUCCESS ) {
DBG_TRACE( DbgInfo, "SUCCESSFULLY INITIATED SCAN...\n" );
} else {
DBG_TRACE( DbgInfo, "INITIATE SCAN FAILED...\n" );
}
wl_act_int_on( lp );
wl_unlock(lp, &flags);
out:
DBG_LEAVE(DbgInfo);
return ret;
} // wireless_set_scan
/*============================================================================*/
/*******************************************************************************
* wireless_get_scan()
*******************************************************************************
*
* DESCRIPTION:
*
* Instructs the driver to gather and return the results of a network scan.
*
* PARAMETERS:
*
* wrq - the wireless request buffer
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
static int wireless_get_scan(struct net_device *dev, struct iw_request_info *info, struct iw_point *data, char *extra)
{
struct wl_private *lp = wl_priv(dev);
unsigned long flags;
int ret = 0;
int count;
char *buf;
char *buf_end;
struct iw_event iwe;
PROBE_RESP *probe_resp;
hcf_8 msg[512];
hcf_8 *wpa_ie;
hcf_16 wpa_ie_len;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wireless_get_scan" );
DBG_ENTER( DbgInfo );
if(lp->portState == WVLAN_PORT_STATE_DISABLED) {
ret = -EBUSY;
goto out;
}
wl_lock( lp, &flags );
wl_act_int_off( lp );
/* If the scan is not done, tell the calling process to try again later */
if( !lp->probe_results.scan_complete ) {
ret = -EAGAIN;
goto out_unlock;
}
DBG_TRACE( DbgInfo, "SCAN COMPLETE, Num of APs: %d\n",
lp->probe_results.num_aps );
buf = extra;
buf_end = extra + IW_SCAN_MAX_DATA;
for( count = 0; count < lp->probe_results.num_aps; count++ ) {
/* Reference the probe response from the table */
probe_resp = (PROBE_RESP *)&lp->probe_results.ProbeTable[count];
/* First entry MUST be the MAC address */
memset( &iwe, 0, sizeof( iwe ));
iwe.cmd = SIOCGIWAP;
iwe.u.ap_addr.sa_family = ARPHRD_ETHER;
memcpy( iwe.u.ap_addr.sa_data, probe_resp->BSSID, ETH_ALEN);
iwe.len = IW_EV_ADDR_LEN;
buf = IWE_STREAM_ADD_EVENT(info, buf, buf_end, &iwe, IW_EV_ADDR_LEN);
/* Use the mode to indicate if it's a station or AP */
/* Won't always be an AP if in IBSS mode */
memset( &iwe, 0, sizeof( iwe ));
iwe.cmd = SIOCGIWMODE;
if( probe_resp->capability & CAPABILITY_IBSS ) {
iwe.u.mode = IW_MODE_INFRA;
} else {
iwe.u.mode = IW_MODE_MASTER;
}
iwe.len = IW_EV_UINT_LEN;
buf = IWE_STREAM_ADD_EVENT(info, buf, buf_end, &iwe, IW_EV_UINT_LEN);
/* Any quality information */
memset(&iwe, 0, sizeof(iwe));
iwe.cmd = IWEVQUAL;
iwe.u.qual.level = dbm(probe_resp->signal);
iwe.u.qual.noise = dbm(probe_resp->silence);
iwe.u.qual.qual = iwe.u.qual.level - iwe.u.qual.noise;
iwe.u.qual.updated = lp->probe_results.scan_complete | IW_QUAL_DBM;
iwe.len = IW_EV_QUAL_LEN;
buf = IWE_STREAM_ADD_EVENT(info, buf, buf_end, &iwe, IW_EV_QUAL_LEN);
/* ESSID information */
if( probe_resp->rawData[1] > 0 ) {
memset( &iwe, 0, sizeof( iwe ));
iwe.cmd = SIOCGIWESSID;
iwe.u.data.length = probe_resp->rawData[1];
iwe.u.data.flags = 1;
buf = IWE_STREAM_ADD_POINT(info, buf, buf_end, &iwe, &probe_resp->rawData[2]);
}
/* Encryption Information */
memset( &iwe, 0, sizeof( iwe ));
iwe.cmd = SIOCGIWENCODE;
iwe.u.data.length = 0;
/* Check the capabilities field of the Probe Response to see if
'privacy' is supported on the AP in question */
if( probe_resp->capability & CAPABILITY_PRIVACY ) {
iwe.u.data.flags |= IW_ENCODE_ENABLED;
} else {
iwe.u.data.flags |= IW_ENCODE_DISABLED;
}
buf = IWE_STREAM_ADD_POINT(info, buf, buf_end, &iwe, NULL);
/* Frequency Info */
memset( &iwe, 0, sizeof( iwe ));
iwe.cmd = SIOCGIWFREQ;
iwe.len = IW_EV_FREQ_LEN;
iwe.u.freq.m = wl_parse_ds_ie( probe_resp );
iwe.u.freq.e = 0;
buf = IWE_STREAM_ADD_EVENT(info, buf, buf_end, &iwe, IW_EV_FREQ_LEN);
#if WIRELESS_EXT > 14
/* Custom info (Beacon Interval) */
memset( &iwe, 0, sizeof( iwe ));
memset( msg, 0, sizeof( msg ));
iwe.cmd = IWEVCUSTOM;
sprintf( msg, "beacon_interval=%d", probe_resp->beaconInterval );
iwe.u.data.length = strlen( msg );
buf = IWE_STREAM_ADD_POINT(info, buf, buf_end, &iwe, msg);
/* Custom info (WPA-IE) */
wpa_ie = NULL;
wpa_ie_len = 0;
wpa_ie = wl_parse_wpa_ie( probe_resp, &wpa_ie_len );
if( wpa_ie != NULL ) {
memset( &iwe, 0, sizeof( iwe ));
memset( msg, 0, sizeof( msg ));
iwe.cmd = IWEVCUSTOM;
sprintf( msg, "wpa_ie=%s", wl_print_wpa_ie( wpa_ie, wpa_ie_len ));
iwe.u.data.length = strlen( msg );
buf = IWE_STREAM_ADD_POINT(info, buf, buf_end, &iwe, msg);
}
/* Add other custom info in formatted string format as needed... */
#endif
}
data->length = buf - extra;
out_unlock:
wl_act_int_on( lp );
wl_unlock(lp, &flags);
out:
DBG_LEAVE( DbgInfo );
return ret;
} // wireless_get_scan
/*============================================================================*/
#endif // WIRELESS_EXT > 13
#if WIRELESS_EXT > 17
static int wireless_set_auth(struct net_device *dev,
struct iw_request_info *info,
struct iw_param *data, char *extra)
{
struct wl_private *lp = wl_priv(dev);
unsigned long flags;
int ret;
int iwa_idx = data->flags & IW_AUTH_INDEX;
int iwa_val = data->value;
DBG_FUNC( "wireless_set_auth" );
DBG_ENTER( DbgInfo );
if(lp->portState == WVLAN_PORT_STATE_DISABLED) {
ret = -EBUSY;
goto out;
}
wl_lock( lp, &flags );
wl_act_int_off( lp );
switch (iwa_idx) {
case IW_AUTH_WPA_VERSION:
DBG_TRACE( DbgInfo, "IW_AUTH_WPA_VERSION\n");
/* We do support WPA only; how should DISABLED be treated? */
if (iwa_val == IW_AUTH_WPA_VERSION_WPA)
ret = 0;
else
ret = -EINVAL;
break;
case IW_AUTH_WPA_ENABLED:
DBG_TRACE( DbgInfo, "IW_AUTH_WPA_ENABLED: val = %d\n", iwa_val);
if (iwa_val)
lp->EnableEncryption = 2;
else
lp->EnableEncryption = 0;
ret = 0;
break;
case IW_AUTH_TKIP_COUNTERMEASURES:
DBG_TRACE( DbgInfo, "IW_AUTH_TKIP_COUNTERMEASURES\n");
lp->driverEnable = !iwa_val;
if(lp->driverEnable)
hcf_cntl(&(lp->hcfCtx), HCF_CNTL_ENABLE | HCF_PORT_0);
else
hcf_cntl(&(lp->hcfCtx), HCF_CNTL_DISABLE | HCF_PORT_0);
ret = 0;
break;
case IW_AUTH_DROP_UNENCRYPTED:
DBG_TRACE( DbgInfo, "IW_AUTH_DROP_UNENCRYPTED\n");
/* We do not actually do anything here, just to silence
* wpa_supplicant */
ret = 0;
break;
case IW_AUTH_CIPHER_PAIRWISE:
DBG_TRACE( DbgInfo, "IW_AUTH_CIPHER_PAIRWISE\n");
/* not implemented, return an error */
ret = -EINVAL;
break;
case IW_AUTH_CIPHER_GROUP:
DBG_TRACE( DbgInfo, "IW_AUTH_CIPHER_GROUP\n");
/* not implemented, return an error */
ret = -EINVAL;
break;
case IW_AUTH_KEY_MGMT:
DBG_TRACE( DbgInfo, "IW_AUTH_KEY_MGMT\n");
/* not implemented, return an error */
ret = -EINVAL;
break;
case IW_AUTH_80211_AUTH_ALG:
DBG_TRACE( DbgInfo, "IW_AUTH_80211_AUTH_ALG\n");
/* not implemented, return an error */
ret = -EINVAL;
break;
case IW_AUTH_RX_UNENCRYPTED_EAPOL:
DBG_TRACE( DbgInfo, "IW_AUTH_RX_UNENCRYPTED_EAPOL\n");
/* not implemented, return an error */
ret = -EINVAL;
break;
case IW_AUTH_ROAMING_CONTROL:
DBG_TRACE( DbgInfo, "IW_AUTH_ROAMING_CONTROL\n");
/* not implemented, return an error */
ret = -EINVAL;
break;
case IW_AUTH_PRIVACY_INVOKED:
DBG_TRACE( DbgInfo, "IW_AUTH_PRIVACY_INVOKED\n");
/* not implemented, return an error */
ret = -EINVAL;
break;
default:
DBG_TRACE( DbgInfo, "IW_AUTH_?? (%d) unknown\n", iwa_idx);
/* return an error */
ret = -EINVAL;
break;
}
wl_act_int_on( lp );
wl_unlock(lp, &flags);
out:
DBG_LEAVE( DbgInfo );
return ret;
} // wireless_set_auth
/*============================================================================*/
static int hermes_set_key(ltv_t *ltv, int alg, int key_idx, u8 *addr,
int set_tx, u8 *seq, u8 *key, size_t key_len)
{
int ret = -EINVAL;
// int count = 0;
int buf_idx = 0;
hcf_8 tsc[IW_ENCODE_SEQ_MAX_SIZE] =
{ 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00 };
DBG_FUNC( "hermes_set_key" );
DBG_ENTER( DbgInfo );
/*
* Check the key index here; if 0, load as Pairwise Key, otherwise,
* load as a group key. Note that for the Hermes, the RIDs for
* group/pariwise keys are different from each other and different
* than the default WEP keys as well.
*/
switch (alg)
{
case IW_ENCODE_ALG_TKIP:
DBG_TRACE( DbgInfo, "IW_ENCODE_ALG_TKIP: key(%d)\n", key_idx);
#if 0
/*
* Make sure that there is no data queued up in the firmware
* before setting the TKIP keys. If this check is not
* performed, some data may be sent out with incorrect MIC
* and cause synchronizarion errors with the AP
*/
/* Check every 1ms for 100ms */
for( count = 0; count < 100; count++ )
{
usleep( 1000 );
ltv.len = 2;
ltv.typ = 0xFD91; // This RID not defined in HCF yet!!!
ltv.u.u16[0] = 0;
wl_get_info( sock, <v, ifname );
if( ltv.u.u16[0] == 0 )
{
break;
}
}
if( count == 100 )
{
wpa_printf( MSG_DEBUG, "Timed out waiting for TxQ!" );
}
#endif
switch (key_idx) {
case 0:
ltv->len = 28;
ltv->typ = CFG_ADD_TKIP_MAPPED_KEY;
/* Load the BSSID */
memcpy(<v->u.u8[buf_idx], addr, ETH_ALEN);
buf_idx += ETH_ALEN;
/* Load the TKIP key */
memcpy(<v->u.u8[buf_idx], &key[0], 16);
buf_idx += 16;
/* Load the TSC */
memcpy(<v->u.u8[buf_idx], tsc, IW_ENCODE_SEQ_MAX_SIZE);
buf_idx += IW_ENCODE_SEQ_MAX_SIZE;
/* Load the RSC */
memcpy(<v->u.u8[buf_idx], seq, IW_ENCODE_SEQ_MAX_SIZE);
buf_idx += IW_ENCODE_SEQ_MAX_SIZE;
/* Load the TxMIC key */
memcpy(<v->u.u8[buf_idx], &key[16], 8);
buf_idx += 8;
/* Load the RxMIC key */
memcpy(<v->u.u8[buf_idx], &key[24], 8);
ret = 0;
break;
case 1:
case 2:
case 3:
ltv->len = 26;
ltv->typ = CFG_ADD_TKIP_DEFAULT_KEY;
/* Load the key Index */
ltv->u.u16[buf_idx] = key_idx;
/* If this is a Tx Key, set bit 8000 */
if(set_tx)
ltv->u.u16[buf_idx] |= 0x8000;
buf_idx += 2;
/* Load the RSC */
memcpy(<v->u.u8[buf_idx], seq, IW_ENCODE_SEQ_MAX_SIZE);
buf_idx += IW_ENCODE_SEQ_MAX_SIZE;
/* Load the TKIP, TxMIC, and RxMIC keys in one shot, because in
CFG_ADD_TKIP_DEFAULT_KEY they are back-to-back */
memcpy(<v->u.u8[buf_idx], key, key_len);
buf_idx += key_len;
/* Load the TSC */
memcpy(<v->u.u8[buf_idx], tsc, IW_ENCODE_SEQ_MAX_SIZE);
ltv->u.u16[0] = CNV_INT_TO_LITTLE(ltv->u.u16[0]);
ret = 0;
break;
default:
break;
}
break;
case IW_ENCODE_ALG_WEP:
DBG_TRACE( DbgInfo, "IW_ENCODE_ALG_WEP: key(%d)\n", key_idx);
break;
case IW_ENCODE_ALG_CCMP:
DBG_TRACE( DbgInfo, "IW_ENCODE_ALG_CCMP: key(%d)\n", key_idx);
break;
case IW_ENCODE_ALG_NONE:
DBG_TRACE( DbgInfo, "IW_ENCODE_ALG_NONE: key(%d)\n", key_idx);
switch (key_idx) {
case 0:
if (memcmp(addr, "\xff\xff\xff\xff\xff\xff", ETH_ALEN) != 0) {
//if (addr != NULL) {
ltv->len = 7;
ltv->typ = CFG_REMOVE_TKIP_MAPPED_KEY;
memcpy(<v->u.u8[0], addr, ETH_ALEN);
ret = 0;
}
break;
case 1:
case 2:
case 3:
/* Clear the Group TKIP keys by index */
ltv->len = 2;
ltv->typ = CFG_REMOVE_TKIP_DEFAULT_KEY;
ltv->u.u16[0] = key_idx;
ret = 0;
break;
default:
break;
}
break;
default:
DBG_TRACE( DbgInfo, "IW_ENCODE_??: key(%d)\n", key_idx);
break;
}
DBG_LEAVE( DbgInfo );
return ret;
} // hermes_set_key
/*============================================================================*/
static int wireless_set_encodeext (struct net_device *dev,
struct iw_request_info *info,
struct iw_point *erq, char *keybuf)
{
struct wl_private *lp = wl_priv(dev);
unsigned long flags;
int ret;
int key_idx = (erq->flags&IW_ENCODE_INDEX) - 1;
ltv_t ltv;
struct iw_encode_ext *ext = (struct iw_encode_ext *)keybuf;
DBG_FUNC( "wireless_set_encodeext" );
DBG_ENTER( DbgInfo );
if(lp->portState == WVLAN_PORT_STATE_DISABLED) {
ret = -EBUSY;
goto out;
}
if (sizeof(ext->rx_seq) != 8) {
DBG_TRACE(DbgInfo, "rz_seq size mismatch\n");
DBG_LEAVE(DbgInfo);
return -EINVAL;
}
/* Handle WEP keys via the old set encode procedure */
if(ext->alg == IW_ENCODE_ALG_WEP) {
struct iw_point wep_erq;
char *wep_keybuf;
/* Build request structure */
wep_erq.flags = erq->flags; // take over flags with key index
wep_erq.length = ext->key_len; // take length from extended key info
wep_keybuf = ext->key; // pointer to the key text
/* Call wireless_set_encode tot handle the WEP key */
ret = wireless_set_encode(dev, info, &wep_erq, wep_keybuf);
goto out;
}
/* Proceed for extended encode functions for WAP and NONE */
wl_lock( lp, &flags );
wl_act_int_off( lp );
memset(<v, 0, sizeof(ltv));
ret = hermes_set_key(<v, ext->alg, key_idx, ext->addr.sa_data,
ext->ext_flags & IW_ENCODE_EXT_SET_TX_KEY,
ext->rx_seq, ext->key, ext->key_len);
if (ret != 0) {
DBG_TRACE( DbgInfo, "hermes_set_key returned != 0, key not set\n");
goto out_unlock;
}
/* Put the key in HCF */
ret = hcf_put_info(&(lp->hcfCtx), (LTVP)<v);
out_unlock:
if(ret == HCF_SUCCESS) {
DBG_TRACE( DbgInfo, "Put key info succes\n");
} else {
DBG_TRACE( DbgInfo, "Put key info failed, key not set\n");
}
wl_act_int_on( lp );
wl_unlock(lp, &flags);
out:
DBG_LEAVE( DbgInfo );
return ret;
} // wireless_set_encodeext
/*============================================================================*/
static int wireless_get_genie(struct net_device *dev,
struct iw_request_info *info,
struct iw_point *data, char *extra)
{
struct wl_private *lp = wl_priv(dev);
unsigned long flags;
int ret = 0;
ltv_t ltv;
DBG_FUNC( "wireless_get_genie" );
DBG_ENTER( DbgInfo );
if(lp->portState == WVLAN_PORT_STATE_DISABLED) {
ret = -EBUSY;
goto out;
}
wl_lock( lp, &flags );
wl_act_int_off( lp );
memset(<v, 0, sizeof(ltv));
ltv.len = 2;
ltv.typ = CFG_SET_WPA_AUTH_KEY_MGMT_SUITE;
lp->AuthKeyMgmtSuite = ltv.u.u16[0] = 4;
ltv.u.u16[0] = CNV_INT_TO_LITTLE(ltv.u.u16[0]);
ret = hcf_put_info(&(lp->hcfCtx), (LTVP)<v);
wl_act_int_on( lp );
wl_unlock(lp, &flags);
out:
DBG_LEAVE( DbgInfo );
return ret;
}
/*============================================================================*/
#endif // WIRELESS_EXT > 17
/*******************************************************************************
* wl_wireless_stats()
*******************************************************************************
*
* DESCRIPTION:
*
* Return the current device wireless statistics.
*
* PARAMETERS:
*
* wrq - the wireless request buffer
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
struct iw_statistics * wl_wireless_stats( struct net_device *dev )
{
struct iw_statistics *pStats;
struct wl_private *lp = wl_priv(dev);
/*------------------------------------------------------------------------*/
DBG_FUNC( "wl_wireless_stats" );
DBG_ENTER(DbgInfo);
DBG_PARAM(DbgInfo, "dev", "%s (0x%p)", dev->name, dev);
pStats = NULL;
/* Initialize the statistics */
pStats = &( lp->wstats );
pStats->qual.updated = 0x00;
if( !( lp->flags & WVLAN2_UIL_BUSY ))
{
CFG_COMMS_QUALITY_STRCT *pQual;
CFG_HERMES_TALLIES_STRCT tallies;
int status;
/* Update driver status */
pStats->status = 0;
/* Get the current link quality information */
lp->ltvRecord.len = 1 + ( sizeof( *pQual ) / sizeof( hcf_16 ));
lp->ltvRecord.typ = CFG_COMMS_QUALITY;
status = hcf_get_info( &( lp->hcfCtx ), (LTVP)&( lp->ltvRecord ));
if( status == HCF_SUCCESS ) {
pQual = (CFG_COMMS_QUALITY_STRCT *)&( lp->ltvRecord );
#ifdef USE_DBM
pStats->qual.qual = (u_char) CNV_LITTLE_TO_INT( pQual->coms_qual );
pStats->qual.level = (u_char) dbm( CNV_LITTLE_TO_INT( pQual->signal_lvl ));
pStats->qual.noise = (u_char) dbm( CNV_LITTLE_TO_INT( pQual->noise_lvl ));
pStats->qual.updated |= (IW_QUAL_QUAL_UPDATED |
IW_QUAL_LEVEL_UPDATED |
IW_QUAL_NOISE_UPDATED |
IW_QUAL_DBM);
#else
pStats->qual.qual = percent( CNV_LITTLE_TO_INT( pQual->coms_qual ),
HCF_MIN_COMM_QUALITY,
HCF_MAX_COMM_QUALITY );
pStats->qual.level = percent( CNV_LITTLE_TO_INT( pQual->signal_lvl ),
HCF_MIN_SIGNAL_LEVEL,
HCF_MAX_SIGNAL_LEVEL );
pStats->qual.noise = percent( CNV_LITTLE_TO_INT( pQual->noise_lvl ),
HCF_MIN_NOISE_LEVEL,
HCF_MAX_NOISE_LEVEL );
pStats->qual.updated |= (IW_QUAL_QUAL_UPDATED |
IW_QUAL_LEVEL_UPDATED |
IW_QUAL_NOISE_UPDATED);
#endif /* USE_DBM */
} else {
memset( &( pStats->qual ), 0, sizeof( pStats->qual ));
}
/* Get the current tallies from the adapter */
/* Only possible when the device is open */
if(lp->portState == WVLAN_PORT_STATE_DISABLED) {
if( wl_get_tallies( lp, &tallies ) == 0 ) {
/* No endian translation is needed here, as CFG_TALLIES is an
MSF RID; all processing is done on the host, not the card! */
pStats->discard.nwid = 0L;
pStats->discard.code = tallies.RxWEPUndecryptable;
pStats->discard.misc = tallies.TxDiscards +
tallies.RxFCSErrors +
//tallies.RxDiscardsNoBuffer +
tallies.TxDiscardsWrongSA;
//;? Extra taken over from Linux driver based on 7.18 version
pStats->discard.retries = tallies.TxRetryLimitExceeded;
pStats->discard.fragment = tallies.RxMsgInBadMsgFragments;
} else {
memset( &( pStats->discard ), 0, sizeof( pStats->discard ));
}
} else {
memset( &( pStats->discard ), 0, sizeof( pStats->discard ));
}
}
DBG_LEAVE( DbgInfo );
return pStats;
} // wl_wireless_stats
/*============================================================================*/
/*******************************************************************************
* wl_get_wireless_stats()
*******************************************************************************
*
* DESCRIPTION:
*
* Return the current device wireless statistics. This function calls
* wl_wireless_stats, but acquires spinlocks first as it can be called
* directly by the network layer.
*
* PARAMETERS:
*
* wrq - the wireless request buffer
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
struct iw_statistics * wl_get_wireless_stats( struct net_device *dev )
{
unsigned long flags;
struct wl_private *lp = wl_priv(dev);
struct iw_statistics *pStats = NULL;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wl_get_wireless_stats" );
DBG_ENTER(DbgInfo);
wl_lock( lp, &flags );
wl_act_int_off( lp );
#ifdef USE_RTS
if( lp->useRTS == 1 ) {
DBG_TRACE( DbgInfo, "Skipping wireless stats, in RTS mode\n" );
} else
#endif
{
pStats = wl_wireless_stats( dev );
}
wl_act_int_on( lp );
wl_unlock(lp, &flags);
DBG_LEAVE( DbgInfo );
return pStats;
} // wl_get_wireless_stats
/*******************************************************************************
* wl_spy_gather()
*******************************************************************************
*
* DESCRIPTION:
*
* Gather wireless spy statistics.
*
* PARAMETERS:
*
* wrq - the wireless request buffer
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
inline void wl_spy_gather( struct net_device *dev, u_char *mac )
{
struct iw_quality wstats;
int status;
u_char stats[2];
DESC_STRCT desc[1];
struct wl_private *lp = wl_priv(dev);
/*------------------------------------------------------------------------*/
/* shortcut */
if (!lp->spy_data.spy_number) {
return;
}
/* Gather wireless spy statistics: for each packet, compare the source
address with out list, and if match, get the stats. */
memset( stats, 0, sizeof(stats));
memset( desc, 0, sizeof(DESC_STRCT));
desc[0].buf_addr = stats;
desc[0].BUF_SIZE = sizeof(stats);
desc[0].next_desc_addr = 0; // terminate list
status = hcf_rcv_msg( &( lp->hcfCtx ), &desc[0], 0 );
if( status == HCF_SUCCESS ) {
wstats.level = (u_char) dbm(stats[1]);
wstats.noise = (u_char) dbm(stats[0]);
wstats.qual = wstats.level > wstats.noise ? wstats.level - wstats.noise : 0;
wstats.updated = (IW_QUAL_QUAL_UPDATED |
IW_QUAL_LEVEL_UPDATED |
IW_QUAL_NOISE_UPDATED |
IW_QUAL_DBM);
wireless_spy_update( dev, mac, &wstats );
}
} // wl_spy_gather
/*============================================================================*/
/*******************************************************************************
* wl_wext_event_freq()
*******************************************************************************
*
* DESCRIPTION:
*
* This function is used to send an event that the channel/freq
* configuration for a specific device has changed.
*
*
* PARAMETERS:
*
* dev - the network device for which this event is to be issued
*
* RETURNS:
*
* N/A
*
******************************************************************************/
void wl_wext_event_freq( struct net_device *dev )
{
#if WIRELESS_EXT > 13
union iwreq_data wrqu;
struct wl_private *lp = wl_priv(dev);
/*------------------------------------------------------------------------*/
memset( &wrqu, 0, sizeof( wrqu ));
wrqu.freq.m = lp->Channel;
wrqu.freq.e = 0;
wireless_send_event( dev, SIOCSIWFREQ, &wrqu, NULL );
#endif /* WIRELESS_EXT > 13 */
return;
} // wl_wext_event_freq
/*============================================================================*/
/*******************************************************************************
* wl_wext_event_mode()
*******************************************************************************
*
* DESCRIPTION:
*
* This function is used to send an event that the mode of operation
* for a specific device has changed.
*
*
* PARAMETERS:
*
* dev - the network device for which this event is to be issued
*
* RETURNS:
*
* N/A
*
******************************************************************************/
void wl_wext_event_mode( struct net_device *dev )
{
#if WIRELESS_EXT > 13
union iwreq_data wrqu;
struct wl_private *lp = wl_priv(dev);
/*------------------------------------------------------------------------*/
memset( &wrqu, 0, sizeof( wrqu ));
if ( CNV_INT_TO_LITTLE( lp->hcfCtx.IFB_FWIdentity.comp_id ) == COMP_ID_FW_STA ) {
wrqu.mode = IW_MODE_INFRA;
} else {
wrqu.mode = IW_MODE_MASTER;
}
wireless_send_event( dev, SIOCSIWMODE, &wrqu, NULL );
#endif /* WIRELESS_EXT > 13 */
return;
} // wl_wext_event_mode
/*============================================================================*/
/*******************************************************************************
* wl_wext_event_essid()
*******************************************************************************
*
* DESCRIPTION:
*
* This function is used to send an event that the ESSID configuration for
* a specific device has changed.
*
*
* PARAMETERS:
*
* dev - the network device for which this event is to be issued
*
* RETURNS:
*
* N/A
*
******************************************************************************/
void wl_wext_event_essid( struct net_device *dev )
{
#if WIRELESS_EXT > 13
union iwreq_data wrqu;
struct wl_private *lp = wl_priv(dev);
/*------------------------------------------------------------------------*/
memset( &wrqu, 0, sizeof( wrqu ));
/* Fill out the buffer. Note that the buffer doesn't actually contain the
ESSID, but a pointer to the contents. In addition, the 'extra' field of
the call to wireless_send_event() must also point to where the ESSID
lives */
wrqu.essid.length = strlen( lp->NetworkName );
wrqu.essid.pointer = (caddr_t)lp->NetworkName;
wrqu.essid.flags = 1;
wireless_send_event( dev, SIOCSIWESSID, &wrqu, lp->NetworkName );
#endif /* WIRELESS_EXT > 13 */
return;
} // wl_wext_event_essid
/*============================================================================*/
/*******************************************************************************
* wl_wext_event_encode()
*******************************************************************************
*
* DESCRIPTION:
*
* This function is used to send an event that the encryption configuration
* for a specific device has changed.
*
*
* PARAMETERS:
*
* dev - the network device for which this event is to be issued
*
* RETURNS:
*
* N/A
*
******************************************************************************/
void wl_wext_event_encode( struct net_device *dev )
{
#if WIRELESS_EXT > 13
union iwreq_data wrqu;
struct wl_private *lp = wl_priv(dev);
int index = 0;
/*------------------------------------------------------------------------*/
memset( &wrqu, 0, sizeof( wrqu ));
if( lp->EnableEncryption == 0 ) {
wrqu.encoding.flags = IW_ENCODE_DISABLED;
} else {
wrqu.encoding.flags |= lp->TransmitKeyID;
index = lp->TransmitKeyID - 1;
/* Only set IW_ENCODE_RESTRICTED/OPEN flag using lp->ExcludeUnencrypted
if we're in AP mode */
#if 1 //;? (HCF_TYPE) & HCF_TYPE_AP
//;?should we restore this to allow smaller memory footprint
if ( CNV_INT_TO_LITTLE( lp->hcfCtx.IFB_FWIdentity.comp_id ) == COMP_ID_FW_AP ) {
if( lp->ExcludeUnencrypted ) {
wrqu.encoding.flags |= IW_ENCODE_RESTRICTED;
} else {
wrqu.encoding.flags |= IW_ENCODE_OPEN;
}
}
#endif // HCF_TYPE_AP
/* Only provide the key if permissions allow */
if( capable( CAP_NET_ADMIN )) {
wrqu.encoding.pointer = (caddr_t)lp->DefaultKeys.key[index].key;
wrqu.encoding.length = lp->DefaultKeys.key[index].len;
} else {
wrqu.encoding.flags |= IW_ENCODE_NOKEY;
}
}
wireless_send_event( dev, SIOCSIWENCODE, &wrqu,
lp->DefaultKeys.key[index].key );
#endif /* WIRELESS_EXT > 13 */
return;
} // wl_wext_event_encode
/*============================================================================*/
/*******************************************************************************
* wl_wext_event_ap()
*******************************************************************************
*
* DESCRIPTION:
*
* This function is used to send an event that the device has been
* associated to a new AP.
*
*
* PARAMETERS:
*
* dev - the network device for which this event is to be issued
*
* RETURNS:
*
* N/A
*
******************************************************************************/
void wl_wext_event_ap( struct net_device *dev )
{
#if WIRELESS_EXT > 13
union iwreq_data wrqu;
struct wl_private *lp = wl_priv(dev);
int status;
/*------------------------------------------------------------------------*/
/* Retrieve the WPA-IEs used by the firmware and send an event. We must send
this event BEFORE sending the association event, as there are timing
issues with the hostap supplicant. The supplicant will attempt to process
an EAPOL-Key frame from an AP before receiving this information, which
is required properly process the said frame. */
wl_wext_event_assoc_ie( dev );
/* Get the BSSID */
lp->ltvRecord.typ = CFG_CUR_BSSID;
lp->ltvRecord.len = 4;
status = hcf_get_info( &( lp->hcfCtx ), (LTVP)&( lp->ltvRecord ));
if( status == HCF_SUCCESS ) {
memset( &wrqu, 0, sizeof( wrqu ));
memcpy( wrqu.addr.sa_data, lp->ltvRecord.u.u8, ETH_ALEN );
wrqu.addr.sa_family = ARPHRD_ETHER;
wireless_send_event( dev, SIOCGIWAP, &wrqu, NULL );
}
#endif /* WIRELESS_EXT > 13 */
return;
} // wl_wext_event_ap
/*============================================================================*/
/*******************************************************************************
* wl_wext_event_scan_complete()
*******************************************************************************
*
* DESCRIPTION:
*
* This function is used to send an event that a request for a network scan
* has completed.
*
*
* PARAMETERS:
*
* dev - the network device for which this event is to be issued
*
* RETURNS:
*
* N/A
*
******************************************************************************/
void wl_wext_event_scan_complete( struct net_device *dev )
{
#if WIRELESS_EXT > 13
union iwreq_data wrqu;
/*------------------------------------------------------------------------*/
memset( &wrqu, 0, sizeof( wrqu ));
wrqu.addr.sa_family = ARPHRD_ETHER;
wireless_send_event( dev, SIOCGIWSCAN, &wrqu, NULL );
#endif /* WIRELESS_EXT > 13 */
return;
} // wl_wext_event_scan_complete
/*============================================================================*/
/*******************************************************************************
* wl_wext_event_new_sta()
*******************************************************************************
*
* DESCRIPTION:
*
* This function is used to send an event that an AP has registered a new
* station.
*
*
* PARAMETERS:
*
* dev - the network device for which this event is to be issued
*
* RETURNS:
*
* N/A
*
******************************************************************************/
void wl_wext_event_new_sta( struct net_device *dev )
{
#if WIRELESS_EXT > 14
union iwreq_data wrqu;
/*------------------------------------------------------------------------*/
memset( &wrqu, 0, sizeof( wrqu ));
/* Send the station's mac address here */
memcpy( wrqu.addr.sa_data, dev->dev_addr, ETH_ALEN );
wrqu.addr.sa_family = ARPHRD_ETHER;
wireless_send_event( dev, IWEVREGISTERED, &wrqu, NULL );
#endif /* WIRELESS_EXT > 14 */
return;
} // wl_wext_event_new_sta
/*============================================================================*/
/*******************************************************************************
* wl_wext_event_expired_sta()
*******************************************************************************
*
* DESCRIPTION:
*
* This function is used to send an event that an AP has deregistered a
* station.
*
*
* PARAMETERS:
*
* dev - the network device for which this event is to be issued
*
* RETURNS:
*
* N/A
*
******************************************************************************/
void wl_wext_event_expired_sta( struct net_device *dev )
{
#if WIRELESS_EXT > 14
union iwreq_data wrqu;
/*------------------------------------------------------------------------*/
memset( &wrqu, 0, sizeof( wrqu ));
memcpy( wrqu.addr.sa_data, dev->dev_addr, ETH_ALEN );
wrqu.addr.sa_family = ARPHRD_ETHER;
wireless_send_event( dev, IWEVEXPIRED, &wrqu, NULL );
#endif /* WIRELESS_EXT > 14 */
return;
} // wl_wext_event_expired_sta
/*============================================================================*/
/*******************************************************************************
* wl_wext_event_mic_failed()
*******************************************************************************
*
* DESCRIPTION:
*
* This function is used to send an event that MIC calculations failed.
*
*
* PARAMETERS:
*
* dev - the network device for which this event is to be issued
*
* RETURNS:
*
* N/A
*
******************************************************************************/
void wl_wext_event_mic_failed( struct net_device *dev )
{
#if WIRELESS_EXT > 14
char msg[512];
union iwreq_data wrqu;
struct wl_private *lp = wl_priv(dev);
int key_idx;
char *addr1;
char *addr2;
WVLAN_RX_WMP_HDR *hdr;
/*------------------------------------------------------------------------*/
key_idx = lp->lookAheadBuf[HFS_STAT+1] >> 3;
key_idx &= 0x03;
/* Cast the lookahead buffer into a RFS format */
hdr = (WVLAN_RX_WMP_HDR *)&lp->lookAheadBuf[HFS_STAT];
/* Cast the addresses to byte buffers, as in the above RFS they are word
length */
addr1 = (char *)hdr->address1;
addr2 = (char *)hdr->address2;
DBG_PRINT( "MIC FAIL - KEY USED : %d, STATUS : 0x%04x\n", key_idx,
hdr->status );
memset( &wrqu, 0, sizeof( wrqu ));
memset( msg, 0, sizeof( msg ));
/* Because MIC failures are not part of the Wireless Extensions yet, they
must be passed as a string using an IWEVCUSTOM event. In order for the
event to be effective, the string format must be known by both the
driver and the supplicant. The following is the string format used by the
hostap project's WPA supplicant, and will be used here until the Wireless
Extensions interface adds this support:
MLME-MICHAELMICFAILURE.indication(keyid=# broadcast/unicast addr=addr2)
*/
/* NOTE: Format of MAC address (using colons to separate bytes) may cause
a problem in future versions of the supplicant, if they ever
actually parse these parameters */
#if DBG
sprintf(msg, "MLME-MICHAELMICFAILURE.indication(keyid=%d %scast "
"addr=%pM)", key_idx, addr1[0] & 0x01 ? "broad" : "uni",
addr2);
#endif
wrqu.data.length = strlen( msg );
wireless_send_event( dev, IWEVCUSTOM, &wrqu, msg );
#endif /* WIRELESS_EXT > 14 */
return;
} // wl_wext_event_mic_failed
/*============================================================================*/
/*******************************************************************************
* wl_wext_event_assoc_ie()
*******************************************************************************
*
* DESCRIPTION:
*
* This function is used to send an event containing the WPA-IE generated
* by the firmware in an association request.
*
*
* PARAMETERS:
*
* dev - the network device for which this event is to be issued
*
* RETURNS:
*
* N/A
*
******************************************************************************/
void wl_wext_event_assoc_ie( struct net_device *dev )
{
#if WIRELESS_EXT > 14
char msg[512];
union iwreq_data wrqu;
struct wl_private *lp = wl_priv(dev);
int status;
PROBE_RESP data;
hcf_16 length;
hcf_8 *wpa_ie;
/*------------------------------------------------------------------------*/
memset( &wrqu, 0, sizeof( wrqu ));
memset( msg, 0, sizeof( msg ));
/* Retrieve the Association Request IE */
lp->ltvRecord.len = 45;
lp->ltvRecord.typ = CFG_CUR_ASSOC_REQ_INFO;
status = hcf_get_info( &( lp->hcfCtx ), (LTVP)&( lp->ltvRecord ));
if( status == HCF_SUCCESS )
{
length = 0;
memcpy( &data.rawData, &( lp->ltvRecord.u.u8[1] ), 88 );
wpa_ie = wl_parse_wpa_ie( &data, &length );
/* Because this event (Association WPA-IE) is not part of the Wireless
Extensions yet, it must be passed as a string using an IWEVCUSTOM event.
In order for the event to be effective, the string format must be known
by both the driver and the supplicant. The following is the string format
used by the hostap project's WPA supplicant, and will be used here until
the Wireless Extensions interface adds this support:
ASSOCINFO(ReqIEs=WPA-IE RespIEs=WPA-IE)
*/
if( length != 0 )
{
sprintf( msg, "ASSOCINFO(ReqIEs=%s)", wl_print_wpa_ie( wpa_ie, length ));
wrqu.data.length = strlen( msg );
wireless_send_event( dev, IWEVCUSTOM, &wrqu, msg );
}
}
#endif /* WIRELESS_EXT > 14 */
return;
} // wl_wext_event_assoc_ie
/*============================================================================*/
/* Structures to export the Wireless Handlers */
static const iw_handler wl_handler[] =
{
(iw_handler) wireless_commit, /* SIOCSIWCOMMIT */
(iw_handler) wireless_get_protocol, /* SIOCGIWNAME */
(iw_handler) NULL, /* SIOCSIWNWID */
(iw_handler) NULL, /* SIOCGIWNWID */
(iw_handler) wireless_set_frequency, /* SIOCSIWFREQ */
(iw_handler) wireless_get_frequency, /* SIOCGIWFREQ */
(iw_handler) wireless_set_porttype, /* SIOCSIWMODE */
(iw_handler) wireless_get_porttype, /* SIOCGIWMODE */
(iw_handler) wireless_set_sensitivity, /* SIOCSIWSENS */
(iw_handler) wireless_get_sensitivity, /* SIOCGIWSENS */
(iw_handler) NULL , /* SIOCSIWRANGE */
(iw_handler) wireless_get_range, /* SIOCGIWRANGE */
(iw_handler) NULL , /* SIOCSIWPRIV */
(iw_handler) NULL /* kernel code */, /* SIOCGIWPRIV */
(iw_handler) NULL , /* SIOCSIWSTATS */
(iw_handler) NULL /* kernel code */, /* SIOCGIWSTATS */
iw_handler_set_spy, /* SIOCSIWSPY */
iw_handler_get_spy, /* SIOCGIWSPY */
NULL, /* SIOCSIWTHRSPY */
NULL, /* SIOCGIWTHRSPY */
(iw_handler) NULL, /* SIOCSIWAP */
#if 1 //;? (HCF_TYPE) & HCF_TYPE_STA
(iw_handler) wireless_get_bssid, /* SIOCGIWAP */
#else
(iw_handler) NULL, /* SIOCGIWAP */
#endif
(iw_handler) NULL, /* SIOCSIWMLME */
(iw_handler) wireless_get_ap_list, /* SIOCGIWAPLIST */
(iw_handler) wireless_set_scan, /* SIOCSIWSCAN */
(iw_handler) wireless_get_scan, /* SIOCGIWSCAN */
(iw_handler) wireless_set_essid, /* SIOCSIWESSID */
(iw_handler) wireless_get_essid, /* SIOCGIWESSID */
(iw_handler) wireless_set_nickname, /* SIOCSIWNICKN */
(iw_handler) wireless_get_nickname, /* SIOCGIWNICKN */
(iw_handler) NULL, /* -- hole -- */
(iw_handler) NULL, /* -- hole -- */
(iw_handler) wireless_set_rate, /* SIOCSIWRATE */
(iw_handler) wireless_get_rate, /* SIOCGIWRATE */
(iw_handler) wireless_set_rts_threshold,/* SIOCSIWRTS */
(iw_handler) wireless_get_rts_threshold,/* SIOCGIWRTS */
(iw_handler) NULL, /* SIOCSIWFRAG */
(iw_handler) NULL, /* SIOCGIWFRAG */
(iw_handler) NULL, /* SIOCSIWTXPOW */
(iw_handler) wireless_get_tx_power, /* SIOCGIWTXPOW */
(iw_handler) NULL, /* SIOCSIWRETRY */
(iw_handler) NULL, /* SIOCGIWRETRY */
(iw_handler) wireless_set_encode, /* SIOCSIWENCODE */
(iw_handler) wireless_get_encode, /* SIOCGIWENCODE */
(iw_handler) wireless_set_power, /* SIOCSIWPOWER */
(iw_handler) wireless_get_power, /* SIOCGIWPOWER */
(iw_handler) NULL, /* -- hole -- */
(iw_handler) NULL, /* -- hole -- */
(iw_handler) wireless_get_genie, /* SIOCSIWGENIE */
(iw_handler) NULL, /* SIOCGIWGENIE */
(iw_handler) wireless_set_auth, /* SIOCSIWAUTH */
(iw_handler) NULL, /* SIOCGIWAUTH */
(iw_handler) wireless_set_encodeext, /* SIOCSIWENCODEEXT */
(iw_handler) NULL, /* SIOCGIWENCODEEXT */
(iw_handler) NULL, /* SIOCSIWPMKSA */
(iw_handler) NULL, /* -- hole -- */
};
static const iw_handler wl_private_handler[] =
{ /* SIOCIWFIRSTPRIV + */
wvlan_set_netname, /* 0: SIOCSIWNETNAME */
wvlan_get_netname, /* 1: SIOCGIWNETNAME */
wvlan_set_station_nickname, /* 2: SIOCSIWSTANAME */
wvlan_get_station_nickname, /* 3: SIOCGIWSTANAME */
#if 1 //;? (HCF_TYPE) & HCF_TYPE_STA
wvlan_set_porttype, /* 4: SIOCSIWPORTTYPE */
wvlan_get_porttype, /* 5: SIOCGIWPORTTYPE */
#endif
};
struct iw_priv_args wl_priv_args[] = {
{SIOCSIWNETNAME, IW_PRIV_TYPE_CHAR | HCF_MAX_NAME_LEN, 0, "snetwork_name" },
{SIOCGIWNETNAME, 0, IW_PRIV_TYPE_CHAR | HCF_MAX_NAME_LEN, "gnetwork_name" },
{SIOCSIWSTANAME, IW_PRIV_TYPE_CHAR | HCF_MAX_NAME_LEN, 0, "sstation_name" },
{SIOCGIWSTANAME, 0, IW_PRIV_TYPE_CHAR | HCF_MAX_NAME_LEN, "gstation_name" },
#if 1 //;? #if (HCF_TYPE) & HCF_TYPE_STA
{SIOCSIWPORTTYPE, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "sport_type" },
{SIOCGIWPORTTYPE, 0, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, "gport_type" },
#endif
};
const struct iw_handler_def wl_iw_handler_def =
{
.num_private = sizeof(wl_private_handler) / sizeof(iw_handler),
.private = (iw_handler *) wl_private_handler,
.private_args = (struct iw_priv_args *) wl_priv_args,
.num_private_args = sizeof(wl_priv_args) / sizeof(struct iw_priv_args),
.num_standard = sizeof(wl_handler) / sizeof(iw_handler),
.standard = (iw_handler *) wl_handler,
.get_wireless_stats = wl_get_wireless_stats,
};
#endif // WIRELESS_EXT
| gpl-2.0 |
Supermaster34/3.0-Kernel-Galaxy-Player-US | drivers/watchdog/iTCO_vendor_support.c | 4194 | 11254 | /*
* intel TCO vendor specific watchdog driver support
*
* (c) Copyright 2006-2009 Wim Van Sebroeck <wim@iguana.be>.
*
* 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.
*
* Neither Wim Van Sebroeck nor Iguana vzw. admit liability nor
* provide warranty for any of this software. This material is
* provided "AS-IS" and at no charge.
*/
/*
* Includes, defines, variables, module parameters, ...
*/
/* Module and version information */
#define DRV_NAME "iTCO_vendor_support"
#define DRV_VERSION "1.04"
#define PFX DRV_NAME ": "
/* Includes */
#include <linux/module.h> /* For module specific items */
#include <linux/moduleparam.h> /* For new moduleparam's */
#include <linux/types.h> /* For standard types (like size_t) */
#include <linux/errno.h> /* For the -ENODEV/... values */
#include <linux/kernel.h> /* For printk/panic/... */
#include <linux/init.h> /* For __init/__exit/... */
#include <linux/ioport.h> /* For io-port access */
#include <linux/io.h> /* For inb/outb/... */
#include "iTCO_vendor.h"
/* iTCO defines */
#define SMI_EN (acpibase + 0x30) /* SMI Control and Enable Register */
#define TCOBASE (acpibase + 0x60) /* TCO base address */
#define TCO1_STS (TCOBASE + 0x04) /* TCO1 Status Register */
/* List of vendor support modes */
/* SuperMicro Pentium 3 Era 370SSE+-OEM1/P3TSSE */
#define SUPERMICRO_OLD_BOARD 1
/* SuperMicro Pentium 4 / Xeon 4 / EMT64T Era Systems */
#define SUPERMICRO_NEW_BOARD 2
/* Broken BIOS */
#define BROKEN_BIOS 911
static int vendorsupport;
module_param(vendorsupport, int, 0);
MODULE_PARM_DESC(vendorsupport, "iTCO vendor specific support mode, default="
"0 (none), 1=SuperMicro Pent3, 2=SuperMicro Pent4+, "
"911=Broken SMI BIOS");
/*
* Vendor Specific Support
*/
/*
* Vendor Support: 1
* Board: Super Micro Computer Inc. 370SSE+-OEM1/P3TSSE
* iTCO chipset: ICH2
*
* Code contributed by: R. Seretny <lkpatches@paypc.com>
* Documentation obtained by R. Seretny from SuperMicro Technical Support
*
* To enable Watchdog function:
* BIOS setup -> Power -> TCO Logic SMI Enable -> Within5Minutes
* This setting enables SMI to clear the watchdog expired flag.
* If BIOS or CPU fail which may cause SMI hang, then system will
* reboot. When application starts to use watchdog function,
* application has to take over the control from SMI.
*
* For P3TSSE, J36 jumper needs to be removed to enable the Watchdog
* function.
*
* Note: The system will reboot when Expire Flag is set TWICE.
* So, if the watchdog timer is 20 seconds, then the maximum hang
* time is about 40 seconds, and the minimum hang time is about
* 20.6 seconds.
*/
static void supermicro_old_pre_start(unsigned long acpibase)
{
unsigned long val32;
/* Bit 13: TCO_EN -> 0 = Disables TCO logic generating an SMI# */
val32 = inl(SMI_EN);
val32 &= 0xffffdfff; /* Turn off SMI clearing watchdog */
outl(val32, SMI_EN); /* Needed to activate watchdog */
}
static void supermicro_old_pre_stop(unsigned long acpibase)
{
unsigned long val32;
/* Bit 13: TCO_EN -> 1 = Enables the TCO logic to generate SMI# */
val32 = inl(SMI_EN);
val32 |= 0x00002000; /* Turn on SMI clearing watchdog */
outl(val32, SMI_EN); /* Needed to deactivate watchdog */
}
/*
* Vendor Support: 2
* Board: Super Micro Computer Inc. P4SBx, P4DPx
* iTCO chipset: ICH4
*
* Code contributed by: R. Seretny <lkpatches@paypc.com>
* Documentation obtained by R. Seretny from SuperMicro Technical Support
*
* To enable Watchdog function:
* 1. BIOS
* For P4SBx:
* BIOS setup -> Advanced -> Integrated Peripherals -> Watch Dog Feature
* For P4DPx:
* BIOS setup -> Advanced -> I/O Device Configuration -> Watch Dog
* This setting enables or disables Watchdog function. When enabled, the
* default watchdog timer is set to be 5 minutes (about 4m35s). It is
* enough to load and run the OS. The application (service or driver) has
* to take over the control once OS is running up and before watchdog
* expires.
*
* 2. JUMPER
* For P4SBx: JP39
* For P4DPx: JP37
* This jumper is used for safety. Closed is enabled. This jumper
* prevents user enables watchdog in BIOS by accident.
*
* To enable Watch Dog function, both BIOS and JUMPER must be enabled.
*
* The documentation lists motherboards P4SBx and P4DPx series as of
* 20-March-2002. However, this code works flawlessly with much newer
* motherboards, such as my X6DHR-8G2 (SuperServer 6014H-82).
*
* The original iTCO driver as written does not actually reset the
* watchdog timer on these machines, as a result they reboot after five
* minutes.
*
* NOTE: You may leave the Watchdog function disabled in the SuperMicro
* BIOS to avoid a "boot-race"... This driver will enable watchdog
* functionality even if it's disabled in the BIOS once the /dev/watchdog
* file is opened.
*/
/* I/O Port's */
#define SM_REGINDEX 0x2e /* SuperMicro ICH4+ Register Index */
#define SM_DATAIO 0x2f /* SuperMicro ICH4+ Register Data I/O */
/* Control Register's */
#define SM_CTLPAGESW 0x07 /* SuperMicro ICH4+ Control Page Switch */
#define SM_CTLPAGE 0x08 /* SuperMicro ICH4+ Control Page Num */
#define SM_WATCHENABLE 0x30 /* Watchdog enable: Bit 0: 0=off, 1=on */
#define SM_WATCHPAGE 0x87 /* Watchdog unlock control page */
#define SM_ENDWATCH 0xAA /* Watchdog lock control page */
#define SM_COUNTMODE 0xf5 /* Watchdog count mode select */
/* (Bit 3: 0 = seconds, 1 = minutes */
#define SM_WATCHTIMER 0xf6 /* 8-bits, Watchdog timer counter (RW) */
#define SM_RESETCONTROL 0xf7 /* Watchdog reset control */
/* Bit 6: timer is reset by kbd interrupt */
/* Bit 7: timer is reset by mouse interrupt */
static void supermicro_new_unlock_watchdog(void)
{
/* Write 0x87 to port 0x2e twice */
outb(SM_WATCHPAGE, SM_REGINDEX);
outb(SM_WATCHPAGE, SM_REGINDEX);
/* Switch to watchdog control page */
outb(SM_CTLPAGESW, SM_REGINDEX);
outb(SM_CTLPAGE, SM_DATAIO);
}
static void supermicro_new_lock_watchdog(void)
{
outb(SM_ENDWATCH, SM_REGINDEX);
}
static void supermicro_new_pre_start(unsigned int heartbeat)
{
unsigned int val;
supermicro_new_unlock_watchdog();
/* Watchdog timer setting needs to be in seconds*/
outb(SM_COUNTMODE, SM_REGINDEX);
val = inb(SM_DATAIO);
val &= 0xF7;
outb(val, SM_DATAIO);
/* Write heartbeat interval to WDOG */
outb(SM_WATCHTIMER, SM_REGINDEX);
outb((heartbeat & 255), SM_DATAIO);
/* Make sure keyboard/mouse interrupts don't interfere */
outb(SM_RESETCONTROL, SM_REGINDEX);
val = inb(SM_DATAIO);
val &= 0x3f;
outb(val, SM_DATAIO);
/* enable watchdog by setting bit 0 of Watchdog Enable to 1 */
outb(SM_WATCHENABLE, SM_REGINDEX);
val = inb(SM_DATAIO);
val |= 0x01;
outb(val, SM_DATAIO);
supermicro_new_lock_watchdog();
}
static void supermicro_new_pre_stop(void)
{
unsigned int val;
supermicro_new_unlock_watchdog();
/* disable watchdog by setting bit 0 of Watchdog Enable to 0 */
outb(SM_WATCHENABLE, SM_REGINDEX);
val = inb(SM_DATAIO);
val &= 0xFE;
outb(val, SM_DATAIO);
supermicro_new_lock_watchdog();
}
static void supermicro_new_pre_set_heartbeat(unsigned int heartbeat)
{
supermicro_new_unlock_watchdog();
/* reset watchdog timeout to heartveat value */
outb(SM_WATCHTIMER, SM_REGINDEX);
outb((heartbeat & 255), SM_DATAIO);
supermicro_new_lock_watchdog();
}
/*
* Vendor Support: 911
* Board: Some Intel ICHx based motherboards
* iTCO chipset: ICH7+
*
* Some Intel motherboards have a broken BIOS implementation: i.e.
* the SMI handler clear's the TIMEOUT bit in the TC01_STS register
* and does not reload the time. Thus the TCO watchdog does not reboot
* the system.
*
* These are the conclusions of Andriy Gapon <avg@icyb.net.ua> after
* debugging: the SMI handler is quite simple - it tests value in
* TCO1_CNT against 0x800, i.e. checks TCO_TMR_HLT. If the bit is set
* the handler goes into an infinite loop, apparently to allow the
* second timeout and reboot. Otherwise it simply clears TIMEOUT bit
* in TCO1_STS and that's it.
* So the logic seems to be reversed, because it is hard to see how
* TIMEOUT can get set to 1 and SMI generated when TCO_TMR_HLT is set
* (other than a transitional effect).
*
* The only fix found to get the motherboard(s) to reboot is to put
* the glb_smi_en bit to 0. This is a dirty hack that bypasses the
* broken code by disabling Global SMI.
*
* WARNING: globally disabling SMI could possibly lead to dramatic
* problems, especially on laptops! I.e. various ACPI things where
* SMI is used for communication between OS and firmware.
*
* Don't use this fix if you don't need to!!!
*/
static void broken_bios_start(unsigned long acpibase)
{
unsigned long val32;
val32 = inl(SMI_EN);
/* Bit 13: TCO_EN -> 0 = Disables TCO logic generating an SMI#
Bit 0: GBL_SMI_EN -> 0 = No SMI# will be generated by ICH. */
val32 &= 0xffffdffe;
outl(val32, SMI_EN);
}
static void broken_bios_stop(unsigned long acpibase)
{
unsigned long val32;
val32 = inl(SMI_EN);
/* Bit 13: TCO_EN -> 1 = Enables TCO logic generating an SMI#
Bit 0: GBL_SMI_EN -> 1 = Turn global SMI on again. */
val32 |= 0x00002001;
outl(val32, SMI_EN);
}
/*
* Generic Support Functions
*/
void iTCO_vendor_pre_start(unsigned long acpibase,
unsigned int heartbeat)
{
switch (vendorsupport) {
case SUPERMICRO_OLD_BOARD:
supermicro_old_pre_start(acpibase);
break;
case SUPERMICRO_NEW_BOARD:
supermicro_new_pre_start(heartbeat);
break;
case BROKEN_BIOS:
broken_bios_start(acpibase);
break;
}
}
EXPORT_SYMBOL(iTCO_vendor_pre_start);
void iTCO_vendor_pre_stop(unsigned long acpibase)
{
switch (vendorsupport) {
case SUPERMICRO_OLD_BOARD:
supermicro_old_pre_stop(acpibase);
break;
case SUPERMICRO_NEW_BOARD:
supermicro_new_pre_stop();
break;
case BROKEN_BIOS:
broken_bios_stop(acpibase);
break;
}
}
EXPORT_SYMBOL(iTCO_vendor_pre_stop);
void iTCO_vendor_pre_keepalive(unsigned long acpibase, unsigned int heartbeat)
{
if (vendorsupport == SUPERMICRO_NEW_BOARD)
supermicro_new_pre_set_heartbeat(heartbeat);
}
EXPORT_SYMBOL(iTCO_vendor_pre_keepalive);
void iTCO_vendor_pre_set_heartbeat(unsigned int heartbeat)
{
if (vendorsupport == SUPERMICRO_NEW_BOARD)
supermicro_new_pre_set_heartbeat(heartbeat);
}
EXPORT_SYMBOL(iTCO_vendor_pre_set_heartbeat);
int iTCO_vendor_check_noreboot_on(void)
{
switch (vendorsupport) {
case SUPERMICRO_OLD_BOARD:
return 0;
default:
return 1;
}
}
EXPORT_SYMBOL(iTCO_vendor_check_noreboot_on);
static int __init iTCO_vendor_init_module(void)
{
printk(KERN_INFO PFX "vendor-support=%d\n", vendorsupport);
return 0;
}
static void __exit iTCO_vendor_exit_module(void)
{
printk(KERN_INFO PFX "Module Unloaded\n");
}
module_init(iTCO_vendor_init_module);
module_exit(iTCO_vendor_exit_module);
MODULE_AUTHOR("Wim Van Sebroeck <wim@iguana.be>, "
"R. Seretny <lkpatches@paypc.com>");
MODULE_DESCRIPTION("Intel TCO Vendor Specific WatchDog Timer Driver Support");
MODULE_VERSION(DRV_VERSION);
MODULE_LICENSE("GPL");
| gpl-2.0 |
chadouming/android_kernel_htc_msm8994 | drivers/net/ethernet/toshiba/spider_net_ethtool.c | 4450 | 5020 | /*
* Network device driver for Cell Processor-Based Blade
*
* (C) Copyright IBM Corp. 2005
*
* Authors : Utz Bacher <utz.bacher@de.ibm.com>
* Jens Osterkamp <Jens.Osterkamp@de.ibm.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, 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/netdevice.h>
#include <linux/ethtool.h>
#include <linux/pci.h>
#include "spider_net.h"
static struct {
const char str[ETH_GSTRING_LEN];
} ethtool_stats_keys[] = {
{ "tx_packets" },
{ "tx_bytes" },
{ "rx_packets" },
{ "rx_bytes" },
{ "tx_errors" },
{ "tx_dropped" },
{ "rx_dropped" },
{ "rx_descriptor_error" },
{ "tx_timeouts" },
{ "alloc_rx_skb_error" },
{ "rx_iommu_map_error" },
{ "tx_iommu_map_error" },
{ "rx_desc_unk_state" },
};
static int
spider_net_ethtool_get_settings(struct net_device *netdev,
struct ethtool_cmd *cmd)
{
struct spider_net_card *card;
card = netdev_priv(netdev);
cmd->supported = (SUPPORTED_1000baseT_Full |
SUPPORTED_FIBRE);
cmd->advertising = (ADVERTISED_1000baseT_Full |
ADVERTISED_FIBRE);
cmd->port = PORT_FIBRE;
ethtool_cmd_speed_set(cmd, card->phy.speed);
cmd->duplex = DUPLEX_FULL;
return 0;
}
static void
spider_net_ethtool_get_drvinfo(struct net_device *netdev,
struct ethtool_drvinfo *drvinfo)
{
struct spider_net_card *card;
card = netdev_priv(netdev);
/* clear and fill out info */
strlcpy(drvinfo->driver, spider_net_driver_name,
sizeof(drvinfo->driver));
strlcpy(drvinfo->version, VERSION, sizeof(drvinfo->version));
strlcpy(drvinfo->fw_version, "no information",
sizeof(drvinfo->fw_version));
strlcpy(drvinfo->bus_info, pci_name(card->pdev),
sizeof(drvinfo->bus_info));
}
static void
spider_net_ethtool_get_wol(struct net_device *netdev,
struct ethtool_wolinfo *wolinfo)
{
/* no support for wol */
wolinfo->supported = 0;
wolinfo->wolopts = 0;
}
static u32
spider_net_ethtool_get_msglevel(struct net_device *netdev)
{
struct spider_net_card *card;
card = netdev_priv(netdev);
return card->msg_enable;
}
static void
spider_net_ethtool_set_msglevel(struct net_device *netdev,
u32 level)
{
struct spider_net_card *card;
card = netdev_priv(netdev);
card->msg_enable = level;
}
static int
spider_net_ethtool_nway_reset(struct net_device *netdev)
{
if (netif_running(netdev)) {
spider_net_stop(netdev);
spider_net_open(netdev);
}
return 0;
}
static void
spider_net_ethtool_get_ringparam(struct net_device *netdev,
struct ethtool_ringparam *ering)
{
struct spider_net_card *card = netdev_priv(netdev);
ering->tx_max_pending = SPIDER_NET_TX_DESCRIPTORS_MAX;
ering->tx_pending = card->tx_chain.num_desc;
ering->rx_max_pending = SPIDER_NET_RX_DESCRIPTORS_MAX;
ering->rx_pending = card->rx_chain.num_desc;
}
static int spider_net_get_sset_count(struct net_device *netdev, int sset)
{
switch (sset) {
case ETH_SS_STATS:
return ARRAY_SIZE(ethtool_stats_keys);
default:
return -EOPNOTSUPP;
}
}
static void spider_net_get_ethtool_stats(struct net_device *netdev,
struct ethtool_stats *stats, u64 *data)
{
struct spider_net_card *card = netdev_priv(netdev);
data[0] = netdev->stats.tx_packets;
data[1] = netdev->stats.tx_bytes;
data[2] = netdev->stats.rx_packets;
data[3] = netdev->stats.rx_bytes;
data[4] = netdev->stats.tx_errors;
data[5] = netdev->stats.tx_dropped;
data[6] = netdev->stats.rx_dropped;
data[7] = card->spider_stats.rx_desc_error;
data[8] = card->spider_stats.tx_timeouts;
data[9] = card->spider_stats.alloc_rx_skb_error;
data[10] = card->spider_stats.rx_iommu_map_error;
data[11] = card->spider_stats.tx_iommu_map_error;
data[12] = card->spider_stats.rx_desc_unk_state;
}
static void spider_net_get_strings(struct net_device *netdev, u32 stringset,
u8 *data)
{
memcpy(data, ethtool_stats_keys, sizeof(ethtool_stats_keys));
}
const struct ethtool_ops spider_net_ethtool_ops = {
.get_settings = spider_net_ethtool_get_settings,
.get_drvinfo = spider_net_ethtool_get_drvinfo,
.get_wol = spider_net_ethtool_get_wol,
.get_msglevel = spider_net_ethtool_get_msglevel,
.set_msglevel = spider_net_ethtool_set_msglevel,
.get_link = ethtool_op_get_link,
.nway_reset = spider_net_ethtool_nway_reset,
.get_ringparam = spider_net_ethtool_get_ringparam,
.get_strings = spider_net_get_strings,
.get_sset_count = spider_net_get_sset_count,
.get_ethtool_stats = spider_net_get_ethtool_stats,
};
| gpl-2.0 |
eyeballer/LenovoA1-3.0.8 | arch/um/drivers/tty.c | 4706 | 1544 | /*
* Copyright (C) 2001 - 2007 Jeff Dike (jdike@{linux.intel,addtoit}.com)
* Licensed under the GPL
*/
#include <errno.h>
#include <fcntl.h>
#include <termios.h>
#include "chan_user.h"
#include "kern_constants.h"
#include "os.h"
#include "um_malloc.h"
#include "user.h"
struct tty_chan {
char *dev;
int raw;
struct termios tt;
};
static void *tty_chan_init(char *str, int device, const struct chan_opts *opts)
{
struct tty_chan *data;
if (*str != ':') {
printk(UM_KERN_ERR "tty_init : channel type 'tty' must specify "
"a device\n");
return NULL;
}
str++;
data = uml_kmalloc(sizeof(*data), UM_GFP_KERNEL);
if (data == NULL)
return NULL;
*data = ((struct tty_chan) { .dev = str,
.raw = opts->raw });
return data;
}
static int tty_open(int input, int output, int primary, void *d,
char **dev_out)
{
struct tty_chan *data = d;
int fd, err, mode = 0;
if (input && output)
mode = O_RDWR;
else if (input)
mode = O_RDONLY;
else if (output)
mode = O_WRONLY;
fd = open(data->dev, mode);
if (fd < 0)
return -errno;
if (data->raw) {
CATCH_EINTR(err = tcgetattr(fd, &data->tt));
if (err)
return err;
err = raw(fd);
if (err)
return err;
}
*dev_out = data->dev;
return fd;
}
const struct chan_ops tty_ops = {
.type = "tty",
.init = tty_chan_init,
.open = tty_open,
.close = generic_close,
.read = generic_read,
.write = generic_write,
.console_write = generic_console_write,
.window_size = generic_window_size,
.free = generic_free,
.winch = 0,
};
| gpl-2.0 |
de-wolff/caf_device_kernel_msm | drivers/staging/iio/adc/ad7606_spi.c | 4962 | 2367 | /*
* AD7606 SPI ADC driver
*
* Copyright 2011 Analog Devices Inc.
*
* Licensed under the GPL-2.
*/
#include <linux/module.h>
#include <linux/spi/spi.h>
#include <linux/types.h>
#include <linux/err.h>
#include "../iio.h"
#include "ad7606.h"
#define MAX_SPI_FREQ_HZ 23500000 /* VDRIVE above 4.75 V */
static int ad7606_spi_read_block(struct device *dev,
int count, void *buf)
{
struct spi_device *spi = to_spi_device(dev);
int i, ret;
unsigned short *data = buf;
ret = spi_read(spi, (u8 *)buf, count * 2);
if (ret < 0) {
dev_err(&spi->dev, "SPI read error\n");
return ret;
}
for (i = 0; i < count; i++)
data[i] = be16_to_cpu(data[i]);
return 0;
}
static const struct ad7606_bus_ops ad7606_spi_bops = {
.read_block = ad7606_spi_read_block,
};
static int __devinit ad7606_spi_probe(struct spi_device *spi)
{
struct iio_dev *indio_dev;
indio_dev = ad7606_probe(&spi->dev, spi->irq, NULL,
spi_get_device_id(spi)->driver_data,
&ad7606_spi_bops);
if (IS_ERR(indio_dev))
return PTR_ERR(indio_dev);
spi_set_drvdata(spi, indio_dev);
return 0;
}
static int __devexit ad7606_spi_remove(struct spi_device *spi)
{
struct iio_dev *indio_dev = dev_get_drvdata(&spi->dev);
return ad7606_remove(indio_dev, spi->irq);
}
#ifdef CONFIG_PM
static int ad7606_spi_suspend(struct device *dev)
{
struct iio_dev *indio_dev = dev_get_drvdata(dev);
ad7606_suspend(indio_dev);
return 0;
}
static int ad7606_spi_resume(struct device *dev)
{
struct iio_dev *indio_dev = dev_get_drvdata(dev);
ad7606_resume(indio_dev);
return 0;
}
static const struct dev_pm_ops ad7606_pm_ops = {
.suspend = ad7606_spi_suspend,
.resume = ad7606_spi_resume,
};
#define AD7606_SPI_PM_OPS (&ad7606_pm_ops)
#else
#define AD7606_SPI_PM_OPS NULL
#endif
static const struct spi_device_id ad7606_id[] = {
{"ad7606-8", ID_AD7606_8},
{"ad7606-6", ID_AD7606_6},
{"ad7606-4", ID_AD7606_4},
{}
};
MODULE_DEVICE_TABLE(spi, ad7606_id);
static struct spi_driver ad7606_driver = {
.driver = {
.name = "ad7606",
.owner = THIS_MODULE,
.pm = AD7606_SPI_PM_OPS,
},
.probe = ad7606_spi_probe,
.remove = __devexit_p(ad7606_spi_remove),
.id_table = ad7606_id,
};
module_spi_driver(ad7606_driver);
MODULE_AUTHOR("Michael Hennerich <hennerich@blackfin.uclinux.org>");
MODULE_DESCRIPTION("Analog Devices AD7606 ADC");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
clemsyn/UpdatedTF101-OCkernel | arch/um/kernel/sigio.c | 4962 | 1043 | /*
* Copyright (C) 2002 - 2007 Jeff Dike (jdike@{linux.intel,addtoit}.com)
* Licensed under the GPL
*/
#include <linux/interrupt.h>
#include "irq_kern.h"
#include "os.h"
#include "sigio.h"
/* Protected by sigio_lock() called from write_sigio_workaround */
static int sigio_irq_fd = -1;
static irqreturn_t sigio_interrupt(int irq, void *data)
{
char c;
os_read_file(sigio_irq_fd, &c, sizeof(c));
reactivate_fd(sigio_irq_fd, SIGIO_WRITE_IRQ);
return IRQ_HANDLED;
}
int write_sigio_irq(int fd)
{
int err;
err = um_request_irq(SIGIO_WRITE_IRQ, fd, IRQ_READ, sigio_interrupt,
IRQF_DISABLED|IRQF_SAMPLE_RANDOM, "write sigio",
NULL);
if (err) {
printk(KERN_ERR "write_sigio_irq : um_request_irq failed, "
"err = %d\n", err);
return -1;
}
sigio_irq_fd = fd;
return 0;
}
/* These are called from os-Linux/sigio.c to protect its pollfds arrays. */
static DEFINE_SPINLOCK(sigio_spinlock);
void sigio_lock(void)
{
spin_lock(&sigio_spinlock);
}
void sigio_unlock(void)
{
spin_unlock(&sigio_spinlock);
}
| gpl-2.0 |
qwerty97/src1 | arch/arm/common/via82c505.c | 4962 | 1888 | #include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/interrupt.h>
#include <linux/mm.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/io.h>
#include <asm/system.h>
#include <asm/mach/pci.h>
#define MAX_SLOTS 7
#define CONFIG_CMD(bus, devfn, where) (0x80000000 | (bus->number << 16) | (devfn << 8) | (where & ~3))
static int
via82c505_read_config(struct pci_bus *bus, unsigned int devfn, int where,
int size, u32 *value)
{
outl(CONFIG_CMD(bus,devfn,where),0xCF8);
switch (size) {
case 1:
*value=inb(0xCFC + (where&3));
break;
case 2:
*value=inw(0xCFC + (where&2));
break;
case 4:
*value=inl(0xCFC);
break;
}
return PCIBIOS_SUCCESSFUL;
}
static int
via82c505_write_config(struct pci_bus *bus, unsigned int devfn, int where,
int size, u32 value)
{
outl(CONFIG_CMD(bus,devfn,where),0xCF8);
switch (size) {
case 1:
outb(value, 0xCFC + (where&3));
break;
case 2:
outw(value, 0xCFC + (where&2));
break;
case 4:
outl(value, 0xCFC);
break;
}
return PCIBIOS_SUCCESSFUL;
}
static struct pci_ops via82c505_ops = {
.read = via82c505_read_config,
.write = via82c505_write_config,
};
void __init via82c505_preinit(void)
{
printk(KERN_DEBUG "PCI: VIA 82c505\n");
if (!request_region(0xA8,2,"via config")) {
printk(KERN_WARNING"VIA 82c505: Unable to request region 0xA8\n");
return;
}
if (!request_region(0xCF8,8,"pci config")) {
printk(KERN_WARNING"VIA 82c505: Unable to request region 0xCF8\n");
release_region(0xA8, 2);
return;
}
/* Enable compatible Mode */
outb(0x96,0xA8);
outb(0x18,0xA9);
outb(0x93,0xA8);
outb(0xd0,0xA9);
}
int __init via82c505_setup(int nr, struct pci_sys_data *sys)
{
return (nr == 0);
}
struct pci_bus * __init via82c505_scan_bus(int nr, struct pci_sys_data *sysdata)
{
if (nr == 0)
return pci_scan_bus(0, &via82c505_ops, sysdata);
return NULL;
}
| gpl-2.0 |
AOSP-Nexus/android_kernel_msm | arch/powerpc/platforms/powermac/feature.c | 7522 | 82395 | /*
* Copyright (C) 1996-2001 Paul Mackerras (paulus@cs.anu.edu.au)
* Ben. Herrenschmidt (benh@kernel.crashing.org)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* TODO:
*
* - Replace mdelay with some schedule loop if possible
* - Shorten some obfuscated delays on some routines (like modem
* power)
* - Refcount some clocks (see darwin)
* - Split split split...
*
*/
#include <linux/types.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/spinlock.h>
#include <linux/adb.h>
#include <linux/pmu.h>
#include <linux/ioport.h>
#include <linux/export.h>
#include <linux/pci.h>
#include <asm/sections.h>
#include <asm/errno.h>
#include <asm/ohare.h>
#include <asm/heathrow.h>
#include <asm/keylargo.h>
#include <asm/uninorth.h>
#include <asm/io.h>
#include <asm/prom.h>
#include <asm/machdep.h>
#include <asm/pmac_feature.h>
#include <asm/dbdma.h>
#include <asm/pci-bridge.h>
#include <asm/pmac_low_i2c.h>
#undef DEBUG_FEATURE
#ifdef DEBUG_FEATURE
#define DBG(fmt...) printk(KERN_DEBUG fmt)
#else
#define DBG(fmt...)
#endif
#ifdef CONFIG_6xx
extern int powersave_lowspeed;
#endif
extern int powersave_nap;
extern struct device_node *k2_skiplist[2];
/*
* We use a single global lock to protect accesses. Each driver has
* to take care of its own locking
*/
DEFINE_RAW_SPINLOCK(feature_lock);
#define LOCK(flags) raw_spin_lock_irqsave(&feature_lock, flags);
#define UNLOCK(flags) raw_spin_unlock_irqrestore(&feature_lock, flags);
/*
* Instance of some macio stuffs
*/
struct macio_chip macio_chips[MAX_MACIO_CHIPS];
struct macio_chip *macio_find(struct device_node *child, int type)
{
while(child) {
int i;
for (i=0; i < MAX_MACIO_CHIPS && macio_chips[i].of_node; i++)
if (child == macio_chips[i].of_node &&
(!type || macio_chips[i].type == type))
return &macio_chips[i];
child = child->parent;
}
return NULL;
}
EXPORT_SYMBOL_GPL(macio_find);
static const char *macio_names[] =
{
"Unknown",
"Grand Central",
"OHare",
"OHareII",
"Heathrow",
"Gatwick",
"Paddington",
"Keylargo",
"Pangea",
"Intrepid",
"K2",
"Shasta",
};
struct device_node *uninorth_node;
u32 __iomem *uninorth_base;
static u32 uninorth_rev;
static int uninorth_maj;
static void __iomem *u3_ht_base;
/*
* For each motherboard family, we have a table of functions pointers
* that handle the various features.
*/
typedef long (*feature_call)(struct device_node *node, long param, long value);
struct feature_table_entry {
unsigned int selector;
feature_call function;
};
struct pmac_mb_def
{
const char* model_string;
const char* model_name;
int model_id;
struct feature_table_entry* features;
unsigned long board_flags;
};
static struct pmac_mb_def pmac_mb;
/*
* Here are the chip specific feature functions
*/
static inline int simple_feature_tweak(struct device_node *node, int type,
int reg, u32 mask, int value)
{
struct macio_chip* macio;
unsigned long flags;
macio = macio_find(node, type);
if (!macio)
return -ENODEV;
LOCK(flags);
if (value)
MACIO_BIS(reg, mask);
else
MACIO_BIC(reg, mask);
(void)MACIO_IN32(reg);
UNLOCK(flags);
return 0;
}
#ifndef CONFIG_POWER4
static long ohare_htw_scc_enable(struct device_node *node, long param,
long value)
{
struct macio_chip* macio;
unsigned long chan_mask;
unsigned long fcr;
unsigned long flags;
int htw, trans;
unsigned long rmask;
macio = macio_find(node, 0);
if (!macio)
return -ENODEV;
if (!strcmp(node->name, "ch-a"))
chan_mask = MACIO_FLAG_SCCA_ON;
else if (!strcmp(node->name, "ch-b"))
chan_mask = MACIO_FLAG_SCCB_ON;
else
return -ENODEV;
htw = (macio->type == macio_heathrow || macio->type == macio_paddington
|| macio->type == macio_gatwick);
/* On these machines, the HRW_SCC_TRANS_EN_N bit mustn't be touched */
trans = (pmac_mb.model_id != PMAC_TYPE_YOSEMITE &&
pmac_mb.model_id != PMAC_TYPE_YIKES);
if (value) {
#ifdef CONFIG_ADB_PMU
if ((param & 0xfff) == PMAC_SCC_IRDA)
pmu_enable_irled(1);
#endif /* CONFIG_ADB_PMU */
LOCK(flags);
fcr = MACIO_IN32(OHARE_FCR);
/* Check if scc cell need enabling */
if (!(fcr & OH_SCC_ENABLE)) {
fcr |= OH_SCC_ENABLE;
if (htw) {
/* Side effect: this will also power up the
* modem, but it's too messy to figure out on which
* ports this controls the tranceiver and on which
* it controls the modem
*/
if (trans)
fcr &= ~HRW_SCC_TRANS_EN_N;
MACIO_OUT32(OHARE_FCR, fcr);
fcr |= (rmask = HRW_RESET_SCC);
MACIO_OUT32(OHARE_FCR, fcr);
} else {
fcr |= (rmask = OH_SCC_RESET);
MACIO_OUT32(OHARE_FCR, fcr);
}
UNLOCK(flags);
(void)MACIO_IN32(OHARE_FCR);
mdelay(15);
LOCK(flags);
fcr &= ~rmask;
MACIO_OUT32(OHARE_FCR, fcr);
}
if (chan_mask & MACIO_FLAG_SCCA_ON)
fcr |= OH_SCCA_IO;
if (chan_mask & MACIO_FLAG_SCCB_ON)
fcr |= OH_SCCB_IO;
MACIO_OUT32(OHARE_FCR, fcr);
macio->flags |= chan_mask;
UNLOCK(flags);
if (param & PMAC_SCC_FLAG_XMON)
macio->flags |= MACIO_FLAG_SCC_LOCKED;
} else {
if (macio->flags & MACIO_FLAG_SCC_LOCKED)
return -EPERM;
LOCK(flags);
fcr = MACIO_IN32(OHARE_FCR);
if (chan_mask & MACIO_FLAG_SCCA_ON)
fcr &= ~OH_SCCA_IO;
if (chan_mask & MACIO_FLAG_SCCB_ON)
fcr &= ~OH_SCCB_IO;
MACIO_OUT32(OHARE_FCR, fcr);
if ((fcr & (OH_SCCA_IO | OH_SCCB_IO)) == 0) {
fcr &= ~OH_SCC_ENABLE;
if (htw && trans)
fcr |= HRW_SCC_TRANS_EN_N;
MACIO_OUT32(OHARE_FCR, fcr);
}
macio->flags &= ~(chan_mask);
UNLOCK(flags);
mdelay(10);
#ifdef CONFIG_ADB_PMU
if ((param & 0xfff) == PMAC_SCC_IRDA)
pmu_enable_irled(0);
#endif /* CONFIG_ADB_PMU */
}
return 0;
}
static long ohare_floppy_enable(struct device_node *node, long param,
long value)
{
return simple_feature_tweak(node, macio_ohare,
OHARE_FCR, OH_FLOPPY_ENABLE, value);
}
static long ohare_mesh_enable(struct device_node *node, long param, long value)
{
return simple_feature_tweak(node, macio_ohare,
OHARE_FCR, OH_MESH_ENABLE, value);
}
static long ohare_ide_enable(struct device_node *node, long param, long value)
{
switch(param) {
case 0:
/* For some reason, setting the bit in set_initial_features()
* doesn't stick. I'm still investigating... --BenH.
*/
if (value)
simple_feature_tweak(node, macio_ohare,
OHARE_FCR, OH_IOBUS_ENABLE, 1);
return simple_feature_tweak(node, macio_ohare,
OHARE_FCR, OH_IDE0_ENABLE, value);
case 1:
return simple_feature_tweak(node, macio_ohare,
OHARE_FCR, OH_BAY_IDE_ENABLE, value);
default:
return -ENODEV;
}
}
static long ohare_ide_reset(struct device_node *node, long param, long value)
{
switch(param) {
case 0:
return simple_feature_tweak(node, macio_ohare,
OHARE_FCR, OH_IDE0_RESET_N, !value);
case 1:
return simple_feature_tweak(node, macio_ohare,
OHARE_FCR, OH_IDE1_RESET_N, !value);
default:
return -ENODEV;
}
}
static long ohare_sleep_state(struct device_node *node, long param, long value)
{
struct macio_chip* macio = &macio_chips[0];
if ((pmac_mb.board_flags & PMAC_MB_CAN_SLEEP) == 0)
return -EPERM;
if (value == 1) {
MACIO_BIC(OHARE_FCR, OH_IOBUS_ENABLE);
} else if (value == 0) {
MACIO_BIS(OHARE_FCR, OH_IOBUS_ENABLE);
}
return 0;
}
static long heathrow_modem_enable(struct device_node *node, long param,
long value)
{
struct macio_chip* macio;
u8 gpio;
unsigned long flags;
macio = macio_find(node, macio_unknown);
if (!macio)
return -ENODEV;
gpio = MACIO_IN8(HRW_GPIO_MODEM_RESET) & ~1;
if (!value) {
LOCK(flags);
MACIO_OUT8(HRW_GPIO_MODEM_RESET, gpio);
UNLOCK(flags);
(void)MACIO_IN8(HRW_GPIO_MODEM_RESET);
mdelay(250);
}
if (pmac_mb.model_id != PMAC_TYPE_YOSEMITE &&
pmac_mb.model_id != PMAC_TYPE_YIKES) {
LOCK(flags);
if (value)
MACIO_BIC(HEATHROW_FCR, HRW_SCC_TRANS_EN_N);
else
MACIO_BIS(HEATHROW_FCR, HRW_SCC_TRANS_EN_N);
UNLOCK(flags);
(void)MACIO_IN32(HEATHROW_FCR);
mdelay(250);
}
if (value) {
LOCK(flags);
MACIO_OUT8(HRW_GPIO_MODEM_RESET, gpio | 1);
(void)MACIO_IN8(HRW_GPIO_MODEM_RESET);
UNLOCK(flags); mdelay(250); LOCK(flags);
MACIO_OUT8(HRW_GPIO_MODEM_RESET, gpio);
(void)MACIO_IN8(HRW_GPIO_MODEM_RESET);
UNLOCK(flags); mdelay(250); LOCK(flags);
MACIO_OUT8(HRW_GPIO_MODEM_RESET, gpio | 1);
(void)MACIO_IN8(HRW_GPIO_MODEM_RESET);
UNLOCK(flags); mdelay(250);
}
return 0;
}
static long heathrow_floppy_enable(struct device_node *node, long param,
long value)
{
return simple_feature_tweak(node, macio_unknown,
HEATHROW_FCR,
HRW_SWIM_ENABLE|HRW_BAY_FLOPPY_ENABLE,
value);
}
static long heathrow_mesh_enable(struct device_node *node, long param,
long value)
{
struct macio_chip* macio;
unsigned long flags;
macio = macio_find(node, macio_unknown);
if (!macio)
return -ENODEV;
LOCK(flags);
/* Set clear mesh cell enable */
if (value)
MACIO_BIS(HEATHROW_FCR, HRW_MESH_ENABLE);
else
MACIO_BIC(HEATHROW_FCR, HRW_MESH_ENABLE);
(void)MACIO_IN32(HEATHROW_FCR);
udelay(10);
/* Set/Clear termination power */
if (value)
MACIO_BIC(HEATHROW_MBCR, 0x04000000);
else
MACIO_BIS(HEATHROW_MBCR, 0x04000000);
(void)MACIO_IN32(HEATHROW_MBCR);
udelay(10);
UNLOCK(flags);
return 0;
}
static long heathrow_ide_enable(struct device_node *node, long param,
long value)
{
switch(param) {
case 0:
return simple_feature_tweak(node, macio_unknown,
HEATHROW_FCR, HRW_IDE0_ENABLE, value);
case 1:
return simple_feature_tweak(node, macio_unknown,
HEATHROW_FCR, HRW_BAY_IDE_ENABLE, value);
default:
return -ENODEV;
}
}
static long heathrow_ide_reset(struct device_node *node, long param,
long value)
{
switch(param) {
case 0:
return simple_feature_tweak(node, macio_unknown,
HEATHROW_FCR, HRW_IDE0_RESET_N, !value);
case 1:
return simple_feature_tweak(node, macio_unknown,
HEATHROW_FCR, HRW_IDE1_RESET_N, !value);
default:
return -ENODEV;
}
}
static long heathrow_bmac_enable(struct device_node *node, long param,
long value)
{
struct macio_chip* macio;
unsigned long flags;
macio = macio_find(node, 0);
if (!macio)
return -ENODEV;
if (value) {
LOCK(flags);
MACIO_BIS(HEATHROW_FCR, HRW_BMAC_IO_ENABLE);
MACIO_BIS(HEATHROW_FCR, HRW_BMAC_RESET);
UNLOCK(flags);
(void)MACIO_IN32(HEATHROW_FCR);
mdelay(10);
LOCK(flags);
MACIO_BIC(HEATHROW_FCR, HRW_BMAC_RESET);
UNLOCK(flags);
(void)MACIO_IN32(HEATHROW_FCR);
mdelay(10);
} else {
LOCK(flags);
MACIO_BIC(HEATHROW_FCR, HRW_BMAC_IO_ENABLE);
UNLOCK(flags);
}
return 0;
}
static long heathrow_sound_enable(struct device_node *node, long param,
long value)
{
struct macio_chip* macio;
unsigned long flags;
/* B&W G3 and Yikes don't support that properly (the
* sound appear to never come back after beeing shut down).
*/
if (pmac_mb.model_id == PMAC_TYPE_YOSEMITE ||
pmac_mb.model_id == PMAC_TYPE_YIKES)
return 0;
macio = macio_find(node, 0);
if (!macio)
return -ENODEV;
if (value) {
LOCK(flags);
MACIO_BIS(HEATHROW_FCR, HRW_SOUND_CLK_ENABLE);
MACIO_BIC(HEATHROW_FCR, HRW_SOUND_POWER_N);
UNLOCK(flags);
(void)MACIO_IN32(HEATHROW_FCR);
} else {
LOCK(flags);
MACIO_BIS(HEATHROW_FCR, HRW_SOUND_POWER_N);
MACIO_BIC(HEATHROW_FCR, HRW_SOUND_CLK_ENABLE);
UNLOCK(flags);
}
return 0;
}
static u32 save_fcr[6];
static u32 save_mbcr;
static struct dbdma_regs save_dbdma[13];
static struct dbdma_regs save_alt_dbdma[13];
static void dbdma_save(struct macio_chip *macio, struct dbdma_regs *save)
{
int i;
/* Save state & config of DBDMA channels */
for (i = 0; i < 13; i++) {
volatile struct dbdma_regs __iomem * chan = (void __iomem *)
(macio->base + ((0x8000+i*0x100)>>2));
save[i].cmdptr_hi = in_le32(&chan->cmdptr_hi);
save[i].cmdptr = in_le32(&chan->cmdptr);
save[i].intr_sel = in_le32(&chan->intr_sel);
save[i].br_sel = in_le32(&chan->br_sel);
save[i].wait_sel = in_le32(&chan->wait_sel);
}
}
static void dbdma_restore(struct macio_chip *macio, struct dbdma_regs *save)
{
int i;
/* Save state & config of DBDMA channels */
for (i = 0; i < 13; i++) {
volatile struct dbdma_regs __iomem * chan = (void __iomem *)
(macio->base + ((0x8000+i*0x100)>>2));
out_le32(&chan->control, (ACTIVE|DEAD|WAKE|FLUSH|PAUSE|RUN)<<16);
while (in_le32(&chan->status) & ACTIVE)
mb();
out_le32(&chan->cmdptr_hi, save[i].cmdptr_hi);
out_le32(&chan->cmdptr, save[i].cmdptr);
out_le32(&chan->intr_sel, save[i].intr_sel);
out_le32(&chan->br_sel, save[i].br_sel);
out_le32(&chan->wait_sel, save[i].wait_sel);
}
}
static void heathrow_sleep(struct macio_chip *macio, int secondary)
{
if (secondary) {
dbdma_save(macio, save_alt_dbdma);
save_fcr[2] = MACIO_IN32(0x38);
save_fcr[3] = MACIO_IN32(0x3c);
} else {
dbdma_save(macio, save_dbdma);
save_fcr[0] = MACIO_IN32(0x38);
save_fcr[1] = MACIO_IN32(0x3c);
save_mbcr = MACIO_IN32(0x34);
/* Make sure sound is shut down */
MACIO_BIS(HEATHROW_FCR, HRW_SOUND_POWER_N);
MACIO_BIC(HEATHROW_FCR, HRW_SOUND_CLK_ENABLE);
/* This seems to be necessary as well or the fan
* keeps coming up and battery drains fast */
MACIO_BIC(HEATHROW_FCR, HRW_IOBUS_ENABLE);
MACIO_BIC(HEATHROW_FCR, HRW_IDE0_RESET_N);
/* Make sure eth is down even if module or sleep
* won't work properly */
MACIO_BIC(HEATHROW_FCR, HRW_BMAC_IO_ENABLE | HRW_BMAC_RESET);
}
/* Make sure modem is shut down */
MACIO_OUT8(HRW_GPIO_MODEM_RESET,
MACIO_IN8(HRW_GPIO_MODEM_RESET) & ~1);
MACIO_BIS(HEATHROW_FCR, HRW_SCC_TRANS_EN_N);
MACIO_BIC(HEATHROW_FCR, OH_SCCA_IO|OH_SCCB_IO|HRW_SCC_ENABLE);
/* Let things settle */
(void)MACIO_IN32(HEATHROW_FCR);
}
static void heathrow_wakeup(struct macio_chip *macio, int secondary)
{
if (secondary) {
MACIO_OUT32(0x38, save_fcr[2]);
(void)MACIO_IN32(0x38);
mdelay(1);
MACIO_OUT32(0x3c, save_fcr[3]);
(void)MACIO_IN32(0x38);
mdelay(10);
dbdma_restore(macio, save_alt_dbdma);
} else {
MACIO_OUT32(0x38, save_fcr[0] | HRW_IOBUS_ENABLE);
(void)MACIO_IN32(0x38);
mdelay(1);
MACIO_OUT32(0x3c, save_fcr[1]);
(void)MACIO_IN32(0x38);
mdelay(1);
MACIO_OUT32(0x34, save_mbcr);
(void)MACIO_IN32(0x38);
mdelay(10);
dbdma_restore(macio, save_dbdma);
}
}
static long heathrow_sleep_state(struct device_node *node, long param,
long value)
{
if ((pmac_mb.board_flags & PMAC_MB_CAN_SLEEP) == 0)
return -EPERM;
if (value == 1) {
if (macio_chips[1].type == macio_gatwick)
heathrow_sleep(&macio_chips[0], 1);
heathrow_sleep(&macio_chips[0], 0);
} else if (value == 0) {
heathrow_wakeup(&macio_chips[0], 0);
if (macio_chips[1].type == macio_gatwick)
heathrow_wakeup(&macio_chips[0], 1);
}
return 0;
}
static long core99_scc_enable(struct device_node *node, long param, long value)
{
struct macio_chip* macio;
unsigned long flags;
unsigned long chan_mask;
u32 fcr;
macio = macio_find(node, 0);
if (!macio)
return -ENODEV;
if (!strcmp(node->name, "ch-a"))
chan_mask = MACIO_FLAG_SCCA_ON;
else if (!strcmp(node->name, "ch-b"))
chan_mask = MACIO_FLAG_SCCB_ON;
else
return -ENODEV;
if (value) {
int need_reset_scc = 0;
int need_reset_irda = 0;
LOCK(flags);
fcr = MACIO_IN32(KEYLARGO_FCR0);
/* Check if scc cell need enabling */
if (!(fcr & KL0_SCC_CELL_ENABLE)) {
fcr |= KL0_SCC_CELL_ENABLE;
need_reset_scc = 1;
}
if (chan_mask & MACIO_FLAG_SCCA_ON) {
fcr |= KL0_SCCA_ENABLE;
/* Don't enable line drivers for I2S modem */
if ((param & 0xfff) == PMAC_SCC_I2S1)
fcr &= ~KL0_SCC_A_INTF_ENABLE;
else
fcr |= KL0_SCC_A_INTF_ENABLE;
}
if (chan_mask & MACIO_FLAG_SCCB_ON) {
fcr |= KL0_SCCB_ENABLE;
/* Perform irda specific inits */
if ((param & 0xfff) == PMAC_SCC_IRDA) {
fcr &= ~KL0_SCC_B_INTF_ENABLE;
fcr |= KL0_IRDA_ENABLE;
fcr |= KL0_IRDA_CLK32_ENABLE | KL0_IRDA_CLK19_ENABLE;
fcr |= KL0_IRDA_SOURCE1_SEL;
fcr &= ~(KL0_IRDA_FAST_CONNECT|KL0_IRDA_DEFAULT1|KL0_IRDA_DEFAULT0);
fcr &= ~(KL0_IRDA_SOURCE2_SEL|KL0_IRDA_HIGH_BAND);
need_reset_irda = 1;
} else
fcr |= KL0_SCC_B_INTF_ENABLE;
}
MACIO_OUT32(KEYLARGO_FCR0, fcr);
macio->flags |= chan_mask;
if (need_reset_scc) {
MACIO_BIS(KEYLARGO_FCR0, KL0_SCC_RESET);
(void)MACIO_IN32(KEYLARGO_FCR0);
UNLOCK(flags);
mdelay(15);
LOCK(flags);
MACIO_BIC(KEYLARGO_FCR0, KL0_SCC_RESET);
}
if (need_reset_irda) {
MACIO_BIS(KEYLARGO_FCR0, KL0_IRDA_RESET);
(void)MACIO_IN32(KEYLARGO_FCR0);
UNLOCK(flags);
mdelay(15);
LOCK(flags);
MACIO_BIC(KEYLARGO_FCR0, KL0_IRDA_RESET);
}
UNLOCK(flags);
if (param & PMAC_SCC_FLAG_XMON)
macio->flags |= MACIO_FLAG_SCC_LOCKED;
} else {
if (macio->flags & MACIO_FLAG_SCC_LOCKED)
return -EPERM;
LOCK(flags);
fcr = MACIO_IN32(KEYLARGO_FCR0);
if (chan_mask & MACIO_FLAG_SCCA_ON)
fcr &= ~KL0_SCCA_ENABLE;
if (chan_mask & MACIO_FLAG_SCCB_ON) {
fcr &= ~KL0_SCCB_ENABLE;
/* Perform irda specific clears */
if ((param & 0xfff) == PMAC_SCC_IRDA) {
fcr &= ~KL0_IRDA_ENABLE;
fcr &= ~(KL0_IRDA_CLK32_ENABLE | KL0_IRDA_CLK19_ENABLE);
fcr &= ~(KL0_IRDA_FAST_CONNECT|KL0_IRDA_DEFAULT1|KL0_IRDA_DEFAULT0);
fcr &= ~(KL0_IRDA_SOURCE1_SEL|KL0_IRDA_SOURCE2_SEL|KL0_IRDA_HIGH_BAND);
}
}
MACIO_OUT32(KEYLARGO_FCR0, fcr);
if ((fcr & (KL0_SCCA_ENABLE | KL0_SCCB_ENABLE)) == 0) {
fcr &= ~KL0_SCC_CELL_ENABLE;
MACIO_OUT32(KEYLARGO_FCR0, fcr);
}
macio->flags &= ~(chan_mask);
UNLOCK(flags);
mdelay(10);
}
return 0;
}
static long
core99_modem_enable(struct device_node *node, long param, long value)
{
struct macio_chip* macio;
u8 gpio;
unsigned long flags;
/* Hack for internal USB modem */
if (node == NULL) {
if (macio_chips[0].type != macio_keylargo)
return -ENODEV;
node = macio_chips[0].of_node;
}
macio = macio_find(node, 0);
if (!macio)
return -ENODEV;
gpio = MACIO_IN8(KL_GPIO_MODEM_RESET);
gpio |= KEYLARGO_GPIO_OUTPUT_ENABLE;
gpio &= ~KEYLARGO_GPIO_OUTOUT_DATA;
if (!value) {
LOCK(flags);
MACIO_OUT8(KL_GPIO_MODEM_RESET, gpio);
UNLOCK(flags);
(void)MACIO_IN8(KL_GPIO_MODEM_RESET);
mdelay(250);
}
LOCK(flags);
if (value) {
MACIO_BIC(KEYLARGO_FCR2, KL2_ALT_DATA_OUT);
UNLOCK(flags);
(void)MACIO_IN32(KEYLARGO_FCR2);
mdelay(250);
} else {
MACIO_BIS(KEYLARGO_FCR2, KL2_ALT_DATA_OUT);
UNLOCK(flags);
}
if (value) {
LOCK(flags);
MACIO_OUT8(KL_GPIO_MODEM_RESET, gpio | KEYLARGO_GPIO_OUTOUT_DATA);
(void)MACIO_IN8(KL_GPIO_MODEM_RESET);
UNLOCK(flags); mdelay(250); LOCK(flags);
MACIO_OUT8(KL_GPIO_MODEM_RESET, gpio);
(void)MACIO_IN8(KL_GPIO_MODEM_RESET);
UNLOCK(flags); mdelay(250); LOCK(flags);
MACIO_OUT8(KL_GPIO_MODEM_RESET, gpio | KEYLARGO_GPIO_OUTOUT_DATA);
(void)MACIO_IN8(KL_GPIO_MODEM_RESET);
UNLOCK(flags); mdelay(250);
}
return 0;
}
static long
pangea_modem_enable(struct device_node *node, long param, long value)
{
struct macio_chip* macio;
u8 gpio;
unsigned long flags;
/* Hack for internal USB modem */
if (node == NULL) {
if (macio_chips[0].type != macio_pangea &&
macio_chips[0].type != macio_intrepid)
return -ENODEV;
node = macio_chips[0].of_node;
}
macio = macio_find(node, 0);
if (!macio)
return -ENODEV;
gpio = MACIO_IN8(KL_GPIO_MODEM_RESET);
gpio |= KEYLARGO_GPIO_OUTPUT_ENABLE;
gpio &= ~KEYLARGO_GPIO_OUTOUT_DATA;
if (!value) {
LOCK(flags);
MACIO_OUT8(KL_GPIO_MODEM_RESET, gpio);
UNLOCK(flags);
(void)MACIO_IN8(KL_GPIO_MODEM_RESET);
mdelay(250);
}
LOCK(flags);
if (value) {
MACIO_OUT8(KL_GPIO_MODEM_POWER,
KEYLARGO_GPIO_OUTPUT_ENABLE);
UNLOCK(flags);
(void)MACIO_IN32(KEYLARGO_FCR2);
mdelay(250);
} else {
MACIO_OUT8(KL_GPIO_MODEM_POWER,
KEYLARGO_GPIO_OUTPUT_ENABLE | KEYLARGO_GPIO_OUTOUT_DATA);
UNLOCK(flags);
}
if (value) {
LOCK(flags);
MACIO_OUT8(KL_GPIO_MODEM_RESET, gpio | KEYLARGO_GPIO_OUTOUT_DATA);
(void)MACIO_IN8(KL_GPIO_MODEM_RESET);
UNLOCK(flags); mdelay(250); LOCK(flags);
MACIO_OUT8(KL_GPIO_MODEM_RESET, gpio);
(void)MACIO_IN8(KL_GPIO_MODEM_RESET);
UNLOCK(flags); mdelay(250); LOCK(flags);
MACIO_OUT8(KL_GPIO_MODEM_RESET, gpio | KEYLARGO_GPIO_OUTOUT_DATA);
(void)MACIO_IN8(KL_GPIO_MODEM_RESET);
UNLOCK(flags); mdelay(250);
}
return 0;
}
static long
core99_ata100_enable(struct device_node *node, long value)
{
unsigned long flags;
struct pci_dev *pdev = NULL;
u8 pbus, pid;
int rc;
if (uninorth_rev < 0x24)
return -ENODEV;
LOCK(flags);
if (value)
UN_BIS(UNI_N_CLOCK_CNTL, UNI_N_CLOCK_CNTL_ATA100);
else
UN_BIC(UNI_N_CLOCK_CNTL, UNI_N_CLOCK_CNTL_ATA100);
(void)UN_IN(UNI_N_CLOCK_CNTL);
UNLOCK(flags);
udelay(20);
if (value) {
if (pci_device_from_OF_node(node, &pbus, &pid) == 0)
pdev = pci_get_bus_and_slot(pbus, pid);
if (pdev == NULL)
return 0;
rc = pci_enable_device(pdev);
if (rc == 0)
pci_set_master(pdev);
pci_dev_put(pdev);
if (rc)
return rc;
}
return 0;
}
static long
core99_ide_enable(struct device_node *node, long param, long value)
{
/* Bus ID 0 to 2 are KeyLargo based IDE, busID 3 is U2
* based ata-100
*/
switch(param) {
case 0:
return simple_feature_tweak(node, macio_unknown,
KEYLARGO_FCR1, KL1_EIDE0_ENABLE, value);
case 1:
return simple_feature_tweak(node, macio_unknown,
KEYLARGO_FCR1, KL1_EIDE1_ENABLE, value);
case 2:
return simple_feature_tweak(node, macio_unknown,
KEYLARGO_FCR1, KL1_UIDE_ENABLE, value);
case 3:
return core99_ata100_enable(node, value);
default:
return -ENODEV;
}
}
static long
core99_ide_reset(struct device_node *node, long param, long value)
{
switch(param) {
case 0:
return simple_feature_tweak(node, macio_unknown,
KEYLARGO_FCR1, KL1_EIDE0_RESET_N, !value);
case 1:
return simple_feature_tweak(node, macio_unknown,
KEYLARGO_FCR1, KL1_EIDE1_RESET_N, !value);
case 2:
return simple_feature_tweak(node, macio_unknown,
KEYLARGO_FCR1, KL1_UIDE_RESET_N, !value);
default:
return -ENODEV;
}
}
static long
core99_gmac_enable(struct device_node *node, long param, long value)
{
unsigned long flags;
LOCK(flags);
if (value)
UN_BIS(UNI_N_CLOCK_CNTL, UNI_N_CLOCK_CNTL_GMAC);
else
UN_BIC(UNI_N_CLOCK_CNTL, UNI_N_CLOCK_CNTL_GMAC);
(void)UN_IN(UNI_N_CLOCK_CNTL);
UNLOCK(flags);
udelay(20);
return 0;
}
static long
core99_gmac_phy_reset(struct device_node *node, long param, long value)
{
unsigned long flags;
struct macio_chip *macio;
macio = &macio_chips[0];
if (macio->type != macio_keylargo && macio->type != macio_pangea &&
macio->type != macio_intrepid)
return -ENODEV;
LOCK(flags);
MACIO_OUT8(KL_GPIO_ETH_PHY_RESET, KEYLARGO_GPIO_OUTPUT_ENABLE);
(void)MACIO_IN8(KL_GPIO_ETH_PHY_RESET);
UNLOCK(flags);
mdelay(10);
LOCK(flags);
MACIO_OUT8(KL_GPIO_ETH_PHY_RESET, /*KEYLARGO_GPIO_OUTPUT_ENABLE | */
KEYLARGO_GPIO_OUTOUT_DATA);
UNLOCK(flags);
mdelay(10);
return 0;
}
static long
core99_sound_chip_enable(struct device_node *node, long param, long value)
{
struct macio_chip* macio;
unsigned long flags;
macio = macio_find(node, 0);
if (!macio)
return -ENODEV;
/* Do a better probe code, screamer G4 desktops &
* iMacs can do that too, add a recalibrate in
* the driver as well
*/
if (pmac_mb.model_id == PMAC_TYPE_PISMO ||
pmac_mb.model_id == PMAC_TYPE_TITANIUM) {
LOCK(flags);
if (value)
MACIO_OUT8(KL_GPIO_SOUND_POWER,
KEYLARGO_GPIO_OUTPUT_ENABLE |
KEYLARGO_GPIO_OUTOUT_DATA);
else
MACIO_OUT8(KL_GPIO_SOUND_POWER,
KEYLARGO_GPIO_OUTPUT_ENABLE);
(void)MACIO_IN8(KL_GPIO_SOUND_POWER);
UNLOCK(flags);
}
return 0;
}
static long
core99_airport_enable(struct device_node *node, long param, long value)
{
struct macio_chip* macio;
unsigned long flags;
int state;
macio = macio_find(node, 0);
if (!macio)
return -ENODEV;
/* Hint: we allow passing of macio itself for the sake of the
* sleep code
*/
if (node != macio->of_node &&
(!node->parent || node->parent != macio->of_node))
return -ENODEV;
state = (macio->flags & MACIO_FLAG_AIRPORT_ON) != 0;
if (value == state)
return 0;
if (value) {
/* This code is a reproduction of OF enable-cardslot
* and init-wireless methods, slightly hacked until
* I got it working.
*/
LOCK(flags);
MACIO_OUT8(KEYLARGO_GPIO_0+0xf, 5);
(void)MACIO_IN8(KEYLARGO_GPIO_0+0xf);
UNLOCK(flags);
mdelay(10);
LOCK(flags);
MACIO_OUT8(KEYLARGO_GPIO_0+0xf, 4);
(void)MACIO_IN8(KEYLARGO_GPIO_0+0xf);
UNLOCK(flags);
mdelay(10);
LOCK(flags);
MACIO_BIC(KEYLARGO_FCR2, KL2_CARDSEL_16);
(void)MACIO_IN32(KEYLARGO_FCR2);
udelay(10);
MACIO_OUT8(KEYLARGO_GPIO_EXTINT_0+0xb, 0);
(void)MACIO_IN8(KEYLARGO_GPIO_EXTINT_0+0xb);
udelay(10);
MACIO_OUT8(KEYLARGO_GPIO_EXTINT_0+0xa, 0x28);
(void)MACIO_IN8(KEYLARGO_GPIO_EXTINT_0+0xa);
udelay(10);
MACIO_OUT8(KEYLARGO_GPIO_EXTINT_0+0xd, 0x28);
(void)MACIO_IN8(KEYLARGO_GPIO_EXTINT_0+0xd);
udelay(10);
MACIO_OUT8(KEYLARGO_GPIO_0+0xd, 0x28);
(void)MACIO_IN8(KEYLARGO_GPIO_0+0xd);
udelay(10);
MACIO_OUT8(KEYLARGO_GPIO_0+0xe, 0x28);
(void)MACIO_IN8(KEYLARGO_GPIO_0+0xe);
UNLOCK(flags);
udelay(10);
MACIO_OUT32(0x1c000, 0);
mdelay(1);
MACIO_OUT8(0x1a3e0, 0x41);
(void)MACIO_IN8(0x1a3e0);
udelay(10);
LOCK(flags);
MACIO_BIS(KEYLARGO_FCR2, KL2_CARDSEL_16);
(void)MACIO_IN32(KEYLARGO_FCR2);
UNLOCK(flags);
mdelay(100);
macio->flags |= MACIO_FLAG_AIRPORT_ON;
} else {
LOCK(flags);
MACIO_BIC(KEYLARGO_FCR2, KL2_CARDSEL_16);
(void)MACIO_IN32(KEYLARGO_FCR2);
MACIO_OUT8(KL_GPIO_AIRPORT_0, 0);
MACIO_OUT8(KL_GPIO_AIRPORT_1, 0);
MACIO_OUT8(KL_GPIO_AIRPORT_2, 0);
MACIO_OUT8(KL_GPIO_AIRPORT_3, 0);
MACIO_OUT8(KL_GPIO_AIRPORT_4, 0);
(void)MACIO_IN8(KL_GPIO_AIRPORT_4);
UNLOCK(flags);
macio->flags &= ~MACIO_FLAG_AIRPORT_ON;
}
return 0;
}
#ifdef CONFIG_SMP
static long
core99_reset_cpu(struct device_node *node, long param, long value)
{
unsigned int reset_io = 0;
unsigned long flags;
struct macio_chip *macio;
struct device_node *np;
struct device_node *cpus;
const int dflt_reset_lines[] = { KL_GPIO_RESET_CPU0,
KL_GPIO_RESET_CPU1,
KL_GPIO_RESET_CPU2,
KL_GPIO_RESET_CPU3 };
macio = &macio_chips[0];
if (macio->type != macio_keylargo)
return -ENODEV;
cpus = of_find_node_by_path("/cpus");
if (cpus == NULL)
return -ENODEV;
for (np = cpus->child; np != NULL; np = np->sibling) {
const u32 *num = of_get_property(np, "reg", NULL);
const u32 *rst = of_get_property(np, "soft-reset", NULL);
if (num == NULL || rst == NULL)
continue;
if (param == *num) {
reset_io = *rst;
break;
}
}
of_node_put(cpus);
if (np == NULL || reset_io == 0)
reset_io = dflt_reset_lines[param];
LOCK(flags);
MACIO_OUT8(reset_io, KEYLARGO_GPIO_OUTPUT_ENABLE);
(void)MACIO_IN8(reset_io);
udelay(1);
MACIO_OUT8(reset_io, 0);
(void)MACIO_IN8(reset_io);
UNLOCK(flags);
return 0;
}
#endif /* CONFIG_SMP */
static long
core99_usb_enable(struct device_node *node, long param, long value)
{
struct macio_chip *macio;
unsigned long flags;
const char *prop;
int number;
u32 reg;
macio = &macio_chips[0];
if (macio->type != macio_keylargo && macio->type != macio_pangea &&
macio->type != macio_intrepid)
return -ENODEV;
prop = of_get_property(node, "AAPL,clock-id", NULL);
if (!prop)
return -ENODEV;
if (strncmp(prop, "usb0u048", 8) == 0)
number = 0;
else if (strncmp(prop, "usb1u148", 8) == 0)
number = 2;
else if (strncmp(prop, "usb2u248", 8) == 0)
number = 4;
else
return -ENODEV;
/* Sorry for the brute-force locking, but this is only used during
* sleep and the timing seem to be critical
*/
LOCK(flags);
if (value) {
/* Turn ON */
if (number == 0) {
MACIO_BIC(KEYLARGO_FCR0, (KL0_USB0_PAD_SUSPEND0 | KL0_USB0_PAD_SUSPEND1));
(void)MACIO_IN32(KEYLARGO_FCR0);
UNLOCK(flags);
mdelay(1);
LOCK(flags);
MACIO_BIS(KEYLARGO_FCR0, KL0_USB0_CELL_ENABLE);
} else if (number == 2) {
MACIO_BIC(KEYLARGO_FCR0, (KL0_USB1_PAD_SUSPEND0 | KL0_USB1_PAD_SUSPEND1));
UNLOCK(flags);
(void)MACIO_IN32(KEYLARGO_FCR0);
mdelay(1);
LOCK(flags);
MACIO_BIS(KEYLARGO_FCR0, KL0_USB1_CELL_ENABLE);
} else if (number == 4) {
MACIO_BIC(KEYLARGO_FCR1, (KL1_USB2_PAD_SUSPEND0 | KL1_USB2_PAD_SUSPEND1));
UNLOCK(flags);
(void)MACIO_IN32(KEYLARGO_FCR1);
mdelay(1);
LOCK(flags);
MACIO_BIS(KEYLARGO_FCR1, KL1_USB2_CELL_ENABLE);
}
if (number < 4) {
reg = MACIO_IN32(KEYLARGO_FCR4);
reg &= ~(KL4_PORT_WAKEUP_ENABLE(number) | KL4_PORT_RESUME_WAKE_EN(number) |
KL4_PORT_CONNECT_WAKE_EN(number) | KL4_PORT_DISCONNECT_WAKE_EN(number));
reg &= ~(KL4_PORT_WAKEUP_ENABLE(number+1) | KL4_PORT_RESUME_WAKE_EN(number+1) |
KL4_PORT_CONNECT_WAKE_EN(number+1) | KL4_PORT_DISCONNECT_WAKE_EN(number+1));
MACIO_OUT32(KEYLARGO_FCR4, reg);
(void)MACIO_IN32(KEYLARGO_FCR4);
udelay(10);
} else {
reg = MACIO_IN32(KEYLARGO_FCR3);
reg &= ~(KL3_IT_PORT_WAKEUP_ENABLE(0) | KL3_IT_PORT_RESUME_WAKE_EN(0) |
KL3_IT_PORT_CONNECT_WAKE_EN(0) | KL3_IT_PORT_DISCONNECT_WAKE_EN(0));
reg &= ~(KL3_IT_PORT_WAKEUP_ENABLE(1) | KL3_IT_PORT_RESUME_WAKE_EN(1) |
KL3_IT_PORT_CONNECT_WAKE_EN(1) | KL3_IT_PORT_DISCONNECT_WAKE_EN(1));
MACIO_OUT32(KEYLARGO_FCR3, reg);
(void)MACIO_IN32(KEYLARGO_FCR3);
udelay(10);
}
if (macio->type == macio_intrepid) {
/* wait for clock stopped bits to clear */
u32 test0 = 0, test1 = 0;
u32 status0, status1;
int timeout = 1000;
UNLOCK(flags);
switch (number) {
case 0:
test0 = UNI_N_CLOCK_STOPPED_USB0;
test1 = UNI_N_CLOCK_STOPPED_USB0PCI;
break;
case 2:
test0 = UNI_N_CLOCK_STOPPED_USB1;
test1 = UNI_N_CLOCK_STOPPED_USB1PCI;
break;
case 4:
test0 = UNI_N_CLOCK_STOPPED_USB2;
test1 = UNI_N_CLOCK_STOPPED_USB2PCI;
break;
}
do {
if (--timeout <= 0) {
printk(KERN_ERR "core99_usb_enable: "
"Timeout waiting for clocks\n");
break;
}
mdelay(1);
status0 = UN_IN(UNI_N_CLOCK_STOP_STATUS0);
status1 = UN_IN(UNI_N_CLOCK_STOP_STATUS1);
} while ((status0 & test0) | (status1 & test1));
LOCK(flags);
}
} else {
/* Turn OFF */
if (number < 4) {
reg = MACIO_IN32(KEYLARGO_FCR4);
reg |= KL4_PORT_WAKEUP_ENABLE(number) | KL4_PORT_RESUME_WAKE_EN(number) |
KL4_PORT_CONNECT_WAKE_EN(number) | KL4_PORT_DISCONNECT_WAKE_EN(number);
reg |= KL4_PORT_WAKEUP_ENABLE(number+1) | KL4_PORT_RESUME_WAKE_EN(number+1) |
KL4_PORT_CONNECT_WAKE_EN(number+1) | KL4_PORT_DISCONNECT_WAKE_EN(number+1);
MACIO_OUT32(KEYLARGO_FCR4, reg);
(void)MACIO_IN32(KEYLARGO_FCR4);
udelay(1);
} else {
reg = MACIO_IN32(KEYLARGO_FCR3);
reg |= KL3_IT_PORT_WAKEUP_ENABLE(0) | KL3_IT_PORT_RESUME_WAKE_EN(0) |
KL3_IT_PORT_CONNECT_WAKE_EN(0) | KL3_IT_PORT_DISCONNECT_WAKE_EN(0);
reg |= KL3_IT_PORT_WAKEUP_ENABLE(1) | KL3_IT_PORT_RESUME_WAKE_EN(1) |
KL3_IT_PORT_CONNECT_WAKE_EN(1) | KL3_IT_PORT_DISCONNECT_WAKE_EN(1);
MACIO_OUT32(KEYLARGO_FCR3, reg);
(void)MACIO_IN32(KEYLARGO_FCR3);
udelay(1);
}
if (number == 0) {
if (macio->type != macio_intrepid)
MACIO_BIC(KEYLARGO_FCR0, KL0_USB0_CELL_ENABLE);
(void)MACIO_IN32(KEYLARGO_FCR0);
udelay(1);
MACIO_BIS(KEYLARGO_FCR0, (KL0_USB0_PAD_SUSPEND0 | KL0_USB0_PAD_SUSPEND1));
(void)MACIO_IN32(KEYLARGO_FCR0);
} else if (number == 2) {
if (macio->type != macio_intrepid)
MACIO_BIC(KEYLARGO_FCR0, KL0_USB1_CELL_ENABLE);
(void)MACIO_IN32(KEYLARGO_FCR0);
udelay(1);
MACIO_BIS(KEYLARGO_FCR0, (KL0_USB1_PAD_SUSPEND0 | KL0_USB1_PAD_SUSPEND1));
(void)MACIO_IN32(KEYLARGO_FCR0);
} else if (number == 4) {
udelay(1);
MACIO_BIS(KEYLARGO_FCR1, (KL1_USB2_PAD_SUSPEND0 | KL1_USB2_PAD_SUSPEND1));
(void)MACIO_IN32(KEYLARGO_FCR1);
}
udelay(1);
}
UNLOCK(flags);
return 0;
}
static long
core99_firewire_enable(struct device_node *node, long param, long value)
{
unsigned long flags;
struct macio_chip *macio;
macio = &macio_chips[0];
if (macio->type != macio_keylargo && macio->type != macio_pangea &&
macio->type != macio_intrepid)
return -ENODEV;
if (!(macio->flags & MACIO_FLAG_FW_SUPPORTED))
return -ENODEV;
LOCK(flags);
if (value) {
UN_BIS(UNI_N_CLOCK_CNTL, UNI_N_CLOCK_CNTL_FW);
(void)UN_IN(UNI_N_CLOCK_CNTL);
} else {
UN_BIC(UNI_N_CLOCK_CNTL, UNI_N_CLOCK_CNTL_FW);
(void)UN_IN(UNI_N_CLOCK_CNTL);
}
UNLOCK(flags);
mdelay(1);
return 0;
}
static long
core99_firewire_cable_power(struct device_node *node, long param, long value)
{
unsigned long flags;
struct macio_chip *macio;
/* Trick: we allow NULL node */
if ((pmac_mb.board_flags & PMAC_MB_HAS_FW_POWER) == 0)
return -ENODEV;
macio = &macio_chips[0];
if (macio->type != macio_keylargo && macio->type != macio_pangea &&
macio->type != macio_intrepid)
return -ENODEV;
if (!(macio->flags & MACIO_FLAG_FW_SUPPORTED))
return -ENODEV;
LOCK(flags);
if (value) {
MACIO_OUT8(KL_GPIO_FW_CABLE_POWER , 0);
MACIO_IN8(KL_GPIO_FW_CABLE_POWER);
udelay(10);
} else {
MACIO_OUT8(KL_GPIO_FW_CABLE_POWER , 4);
MACIO_IN8(KL_GPIO_FW_CABLE_POWER); udelay(10);
}
UNLOCK(flags);
mdelay(1);
return 0;
}
static long
intrepid_aack_delay_enable(struct device_node *node, long param, long value)
{
unsigned long flags;
if (uninorth_rev < 0xd2)
return -ENODEV;
LOCK(flags);
if (param)
UN_BIS(UNI_N_AACK_DELAY, UNI_N_AACK_DELAY_ENABLE);
else
UN_BIC(UNI_N_AACK_DELAY, UNI_N_AACK_DELAY_ENABLE);
UNLOCK(flags);
return 0;
}
#endif /* CONFIG_POWER4 */
static long
core99_read_gpio(struct device_node *node, long param, long value)
{
struct macio_chip *macio = &macio_chips[0];
return MACIO_IN8(param);
}
static long
core99_write_gpio(struct device_node *node, long param, long value)
{
struct macio_chip *macio = &macio_chips[0];
MACIO_OUT8(param, (u8)(value & 0xff));
return 0;
}
#ifdef CONFIG_POWER4
static long g5_gmac_enable(struct device_node *node, long param, long value)
{
struct macio_chip *macio = &macio_chips[0];
unsigned long flags;
if (node == NULL)
return -ENODEV;
LOCK(flags);
if (value) {
MACIO_BIS(KEYLARGO_FCR1, K2_FCR1_GMAC_CLK_ENABLE);
mb();
k2_skiplist[0] = NULL;
} else {
k2_skiplist[0] = node;
mb();
MACIO_BIC(KEYLARGO_FCR1, K2_FCR1_GMAC_CLK_ENABLE);
}
UNLOCK(flags);
mdelay(1);
return 0;
}
static long g5_fw_enable(struct device_node *node, long param, long value)
{
struct macio_chip *macio = &macio_chips[0];
unsigned long flags;
if (node == NULL)
return -ENODEV;
LOCK(flags);
if (value) {
MACIO_BIS(KEYLARGO_FCR1, K2_FCR1_FW_CLK_ENABLE);
mb();
k2_skiplist[1] = NULL;
} else {
k2_skiplist[1] = node;
mb();
MACIO_BIC(KEYLARGO_FCR1, K2_FCR1_FW_CLK_ENABLE);
}
UNLOCK(flags);
mdelay(1);
return 0;
}
static long g5_mpic_enable(struct device_node *node, long param, long value)
{
unsigned long flags;
struct device_node *parent = of_get_parent(node);
int is_u3;
if (parent == NULL)
return 0;
is_u3 = strcmp(parent->name, "u3") == 0 ||
strcmp(parent->name, "u4") == 0;
of_node_put(parent);
if (!is_u3)
return 0;
LOCK(flags);
UN_BIS(U3_TOGGLE_REG, U3_MPIC_RESET | U3_MPIC_OUTPUT_ENABLE);
UNLOCK(flags);
return 0;
}
static long g5_eth_phy_reset(struct device_node *node, long param, long value)
{
struct macio_chip *macio = &macio_chips[0];
struct device_node *phy;
int need_reset;
/*
* We must not reset the combo PHYs, only the BCM5221 found in
* the iMac G5.
*/
phy = of_get_next_child(node, NULL);
if (!phy)
return -ENODEV;
need_reset = of_device_is_compatible(phy, "B5221");
of_node_put(phy);
if (!need_reset)
return 0;
/* PHY reset is GPIO 29, not in device-tree unfortunately */
MACIO_OUT8(K2_GPIO_EXTINT_0 + 29,
KEYLARGO_GPIO_OUTPUT_ENABLE | KEYLARGO_GPIO_OUTOUT_DATA);
/* Thankfully, this is now always called at a time when we can
* schedule by sungem.
*/
msleep(10);
MACIO_OUT8(K2_GPIO_EXTINT_0 + 29, 0);
return 0;
}
static long g5_i2s_enable(struct device_node *node, long param, long value)
{
/* Very crude implementation for now */
struct macio_chip *macio = &macio_chips[0];
unsigned long flags;
int cell;
u32 fcrs[3][3] = {
{ 0,
K2_FCR1_I2S0_CELL_ENABLE |
K2_FCR1_I2S0_CLK_ENABLE_BIT | K2_FCR1_I2S0_ENABLE,
KL3_I2S0_CLK18_ENABLE
},
{ KL0_SCC_A_INTF_ENABLE,
K2_FCR1_I2S1_CELL_ENABLE |
K2_FCR1_I2S1_CLK_ENABLE_BIT | K2_FCR1_I2S1_ENABLE,
KL3_I2S1_CLK18_ENABLE
},
{ KL0_SCC_B_INTF_ENABLE,
SH_FCR1_I2S2_CELL_ENABLE |
SH_FCR1_I2S2_CLK_ENABLE_BIT | SH_FCR1_I2S2_ENABLE,
SH_FCR3_I2S2_CLK18_ENABLE
},
};
if (macio->type != macio_keylargo2 && macio->type != macio_shasta)
return -ENODEV;
if (strncmp(node->name, "i2s-", 4))
return -ENODEV;
cell = node->name[4] - 'a';
switch(cell) {
case 0:
case 1:
break;
case 2:
if (macio->type == macio_shasta)
break;
default:
return -ENODEV;
}
LOCK(flags);
if (value) {
MACIO_BIC(KEYLARGO_FCR0, fcrs[cell][0]);
MACIO_BIS(KEYLARGO_FCR1, fcrs[cell][1]);
MACIO_BIS(KEYLARGO_FCR3, fcrs[cell][2]);
} else {
MACIO_BIC(KEYLARGO_FCR3, fcrs[cell][2]);
MACIO_BIC(KEYLARGO_FCR1, fcrs[cell][1]);
MACIO_BIS(KEYLARGO_FCR0, fcrs[cell][0]);
}
udelay(10);
UNLOCK(flags);
return 0;
}
#ifdef CONFIG_SMP
static long g5_reset_cpu(struct device_node *node, long param, long value)
{
unsigned int reset_io = 0;
unsigned long flags;
struct macio_chip *macio;
struct device_node *np;
struct device_node *cpus;
macio = &macio_chips[0];
if (macio->type != macio_keylargo2 && macio->type != macio_shasta)
return -ENODEV;
cpus = of_find_node_by_path("/cpus");
if (cpus == NULL)
return -ENODEV;
for (np = cpus->child; np != NULL; np = np->sibling) {
const u32 *num = of_get_property(np, "reg", NULL);
const u32 *rst = of_get_property(np, "soft-reset", NULL);
if (num == NULL || rst == NULL)
continue;
if (param == *num) {
reset_io = *rst;
break;
}
}
of_node_put(cpus);
if (np == NULL || reset_io == 0)
return -ENODEV;
LOCK(flags);
MACIO_OUT8(reset_io, KEYLARGO_GPIO_OUTPUT_ENABLE);
(void)MACIO_IN8(reset_io);
udelay(1);
MACIO_OUT8(reset_io, 0);
(void)MACIO_IN8(reset_io);
UNLOCK(flags);
return 0;
}
#endif /* CONFIG_SMP */
/*
* This can be called from pmac_smp so isn't static
*
* This takes the second CPU off the bus on dual CPU machines
* running UP
*/
void g5_phy_disable_cpu1(void)
{
if (uninorth_maj == 3)
UN_OUT(U3_API_PHY_CONFIG_1, 0);
}
#endif /* CONFIG_POWER4 */
#ifndef CONFIG_POWER4
#ifdef CONFIG_PM
static u32 save_gpio_levels[2];
static u8 save_gpio_extint[KEYLARGO_GPIO_EXTINT_CNT];
static u8 save_gpio_normal[KEYLARGO_GPIO_CNT];
static u32 save_unin_clock_ctl;
static void keylargo_shutdown(struct macio_chip *macio, int sleep_mode)
{
u32 temp;
if (sleep_mode) {
mdelay(1);
MACIO_BIS(KEYLARGO_FCR0, KL0_USB_REF_SUSPEND);
(void)MACIO_IN32(KEYLARGO_FCR0);
mdelay(1);
}
MACIO_BIC(KEYLARGO_FCR0,KL0_SCCA_ENABLE | KL0_SCCB_ENABLE |
KL0_SCC_CELL_ENABLE |
KL0_IRDA_ENABLE | KL0_IRDA_CLK32_ENABLE |
KL0_IRDA_CLK19_ENABLE);
MACIO_BIC(KEYLARGO_MBCR, KL_MBCR_MB0_DEV_MASK);
MACIO_BIS(KEYLARGO_MBCR, KL_MBCR_MB0_IDE_ENABLE);
MACIO_BIC(KEYLARGO_FCR1,
KL1_AUDIO_SEL_22MCLK | KL1_AUDIO_CLK_ENABLE_BIT |
KL1_AUDIO_CLK_OUT_ENABLE | KL1_AUDIO_CELL_ENABLE |
KL1_I2S0_CELL_ENABLE | KL1_I2S0_CLK_ENABLE_BIT |
KL1_I2S0_ENABLE | KL1_I2S1_CELL_ENABLE |
KL1_I2S1_CLK_ENABLE_BIT | KL1_I2S1_ENABLE |
KL1_EIDE0_ENABLE | KL1_EIDE0_RESET_N |
KL1_EIDE1_ENABLE | KL1_EIDE1_RESET_N |
KL1_UIDE_ENABLE);
MACIO_BIS(KEYLARGO_FCR2, KL2_ALT_DATA_OUT);
MACIO_BIC(KEYLARGO_FCR2, KL2_IOBUS_ENABLE);
temp = MACIO_IN32(KEYLARGO_FCR3);
if (macio->rev >= 2) {
temp |= KL3_SHUTDOWN_PLL2X;
if (sleep_mode)
temp |= KL3_SHUTDOWN_PLL_TOTAL;
}
temp |= KL3_SHUTDOWN_PLLKW6 | KL3_SHUTDOWN_PLLKW4 |
KL3_SHUTDOWN_PLLKW35;
if (sleep_mode)
temp |= KL3_SHUTDOWN_PLLKW12;
temp &= ~(KL3_CLK66_ENABLE | KL3_CLK49_ENABLE | KL3_CLK45_ENABLE
| KL3_CLK31_ENABLE | KL3_I2S1_CLK18_ENABLE | KL3_I2S0_CLK18_ENABLE);
if (sleep_mode)
temp &= ~(KL3_TIMER_CLK18_ENABLE | KL3_VIA_CLK16_ENABLE);
MACIO_OUT32(KEYLARGO_FCR3, temp);
/* Flush posted writes & wait a bit */
(void)MACIO_IN32(KEYLARGO_FCR0); mdelay(1);
}
static void pangea_shutdown(struct macio_chip *macio, int sleep_mode)
{
u32 temp;
MACIO_BIC(KEYLARGO_FCR0,KL0_SCCA_ENABLE | KL0_SCCB_ENABLE |
KL0_SCC_CELL_ENABLE |
KL0_USB0_CELL_ENABLE | KL0_USB1_CELL_ENABLE);
MACIO_BIC(KEYLARGO_FCR1,
KL1_AUDIO_SEL_22MCLK | KL1_AUDIO_CLK_ENABLE_BIT |
KL1_AUDIO_CLK_OUT_ENABLE | KL1_AUDIO_CELL_ENABLE |
KL1_I2S0_CELL_ENABLE | KL1_I2S0_CLK_ENABLE_BIT |
KL1_I2S0_ENABLE | KL1_I2S1_CELL_ENABLE |
KL1_I2S1_CLK_ENABLE_BIT | KL1_I2S1_ENABLE |
KL1_UIDE_ENABLE);
if (pmac_mb.board_flags & PMAC_MB_MOBILE)
MACIO_BIC(KEYLARGO_FCR1, KL1_UIDE_RESET_N);
MACIO_BIS(KEYLARGO_FCR2, KL2_ALT_DATA_OUT);
temp = MACIO_IN32(KEYLARGO_FCR3);
temp |= KL3_SHUTDOWN_PLLKW6 | KL3_SHUTDOWN_PLLKW4 |
KL3_SHUTDOWN_PLLKW35;
temp &= ~(KL3_CLK49_ENABLE | KL3_CLK45_ENABLE | KL3_CLK31_ENABLE
| KL3_I2S0_CLK18_ENABLE | KL3_I2S1_CLK18_ENABLE);
if (sleep_mode)
temp &= ~(KL3_VIA_CLK16_ENABLE | KL3_TIMER_CLK18_ENABLE);
MACIO_OUT32(KEYLARGO_FCR3, temp);
/* Flush posted writes & wait a bit */
(void)MACIO_IN32(KEYLARGO_FCR0); mdelay(1);
}
static void intrepid_shutdown(struct macio_chip *macio, int sleep_mode)
{
u32 temp;
MACIO_BIC(KEYLARGO_FCR0,KL0_SCCA_ENABLE | KL0_SCCB_ENABLE |
KL0_SCC_CELL_ENABLE);
MACIO_BIC(KEYLARGO_FCR1,
KL1_I2S0_CELL_ENABLE | KL1_I2S0_CLK_ENABLE_BIT |
KL1_I2S0_ENABLE | KL1_I2S1_CELL_ENABLE |
KL1_I2S1_CLK_ENABLE_BIT | KL1_I2S1_ENABLE |
KL1_EIDE0_ENABLE);
if (pmac_mb.board_flags & PMAC_MB_MOBILE)
MACIO_BIC(KEYLARGO_FCR1, KL1_UIDE_RESET_N);
temp = MACIO_IN32(KEYLARGO_FCR3);
temp &= ~(KL3_CLK49_ENABLE | KL3_CLK45_ENABLE |
KL3_I2S1_CLK18_ENABLE | KL3_I2S0_CLK18_ENABLE);
if (sleep_mode)
temp &= ~(KL3_TIMER_CLK18_ENABLE | KL3_IT_VIA_CLK32_ENABLE);
MACIO_OUT32(KEYLARGO_FCR3, temp);
/* Flush posted writes & wait a bit */
(void)MACIO_IN32(KEYLARGO_FCR0);
mdelay(10);
}
static int
core99_sleep(void)
{
struct macio_chip *macio;
int i;
macio = &macio_chips[0];
if (macio->type != macio_keylargo && macio->type != macio_pangea &&
macio->type != macio_intrepid)
return -ENODEV;
/* We power off the wireless slot in case it was not done
* by the driver. We don't power it on automatically however
*/
if (macio->flags & MACIO_FLAG_AIRPORT_ON)
core99_airport_enable(macio->of_node, 0, 0);
/* We power off the FW cable. Should be done by the driver... */
if (macio->flags & MACIO_FLAG_FW_SUPPORTED) {
core99_firewire_enable(NULL, 0, 0);
core99_firewire_cable_power(NULL, 0, 0);
}
/* We make sure int. modem is off (in case driver lost it) */
if (macio->type == macio_keylargo)
core99_modem_enable(macio->of_node, 0, 0);
else
pangea_modem_enable(macio->of_node, 0, 0);
/* We make sure the sound is off as well */
core99_sound_chip_enable(macio->of_node, 0, 0);
/*
* Save various bits of KeyLargo
*/
/* Save the state of the various GPIOs */
save_gpio_levels[0] = MACIO_IN32(KEYLARGO_GPIO_LEVELS0);
save_gpio_levels[1] = MACIO_IN32(KEYLARGO_GPIO_LEVELS1);
for (i=0; i<KEYLARGO_GPIO_EXTINT_CNT; i++)
save_gpio_extint[i] = MACIO_IN8(KEYLARGO_GPIO_EXTINT_0+i);
for (i=0; i<KEYLARGO_GPIO_CNT; i++)
save_gpio_normal[i] = MACIO_IN8(KEYLARGO_GPIO_0+i);
/* Save the FCRs */
if (macio->type == macio_keylargo)
save_mbcr = MACIO_IN32(KEYLARGO_MBCR);
save_fcr[0] = MACIO_IN32(KEYLARGO_FCR0);
save_fcr[1] = MACIO_IN32(KEYLARGO_FCR1);
save_fcr[2] = MACIO_IN32(KEYLARGO_FCR2);
save_fcr[3] = MACIO_IN32(KEYLARGO_FCR3);
save_fcr[4] = MACIO_IN32(KEYLARGO_FCR4);
if (macio->type == macio_pangea || macio->type == macio_intrepid)
save_fcr[5] = MACIO_IN32(KEYLARGO_FCR5);
/* Save state & config of DBDMA channels */
dbdma_save(macio, save_dbdma);
/*
* Turn off as much as we can
*/
if (macio->type == macio_pangea)
pangea_shutdown(macio, 1);
else if (macio->type == macio_intrepid)
intrepid_shutdown(macio, 1);
else if (macio->type == macio_keylargo)
keylargo_shutdown(macio, 1);
/*
* Put the host bridge to sleep
*/
save_unin_clock_ctl = UN_IN(UNI_N_CLOCK_CNTL);
/* Note: do not switch GMAC off, driver does it when necessary, WOL must keep it
* enabled !
*/
UN_OUT(UNI_N_CLOCK_CNTL, save_unin_clock_ctl &
~(/*UNI_N_CLOCK_CNTL_GMAC|*/UNI_N_CLOCK_CNTL_FW/*|UNI_N_CLOCK_CNTL_PCI*/));
udelay(100);
UN_OUT(UNI_N_HWINIT_STATE, UNI_N_HWINIT_STATE_SLEEPING);
UN_OUT(UNI_N_POWER_MGT, UNI_N_POWER_MGT_SLEEP);
mdelay(10);
/*
* FIXME: A bit of black magic with OpenPIC (don't ask me why)
*/
if (pmac_mb.model_id == PMAC_TYPE_SAWTOOTH) {
MACIO_BIS(0x506e0, 0x00400000);
MACIO_BIS(0x506e0, 0x80000000);
}
return 0;
}
static int
core99_wake_up(void)
{
struct macio_chip *macio;
int i;
macio = &macio_chips[0];
if (macio->type != macio_keylargo && macio->type != macio_pangea &&
macio->type != macio_intrepid)
return -ENODEV;
/*
* Wakeup the host bridge
*/
UN_OUT(UNI_N_POWER_MGT, UNI_N_POWER_MGT_NORMAL);
udelay(10);
UN_OUT(UNI_N_HWINIT_STATE, UNI_N_HWINIT_STATE_RUNNING);
udelay(10);
/*
* Restore KeyLargo
*/
if (macio->type == macio_keylargo) {
MACIO_OUT32(KEYLARGO_MBCR, save_mbcr);
(void)MACIO_IN32(KEYLARGO_MBCR); udelay(10);
}
MACIO_OUT32(KEYLARGO_FCR0, save_fcr[0]);
(void)MACIO_IN32(KEYLARGO_FCR0); udelay(10);
MACIO_OUT32(KEYLARGO_FCR1, save_fcr[1]);
(void)MACIO_IN32(KEYLARGO_FCR1); udelay(10);
MACIO_OUT32(KEYLARGO_FCR2, save_fcr[2]);
(void)MACIO_IN32(KEYLARGO_FCR2); udelay(10);
MACIO_OUT32(KEYLARGO_FCR3, save_fcr[3]);
(void)MACIO_IN32(KEYLARGO_FCR3); udelay(10);
MACIO_OUT32(KEYLARGO_FCR4, save_fcr[4]);
(void)MACIO_IN32(KEYLARGO_FCR4); udelay(10);
if (macio->type == macio_pangea || macio->type == macio_intrepid) {
MACIO_OUT32(KEYLARGO_FCR5, save_fcr[5]);
(void)MACIO_IN32(KEYLARGO_FCR5); udelay(10);
}
dbdma_restore(macio, save_dbdma);
MACIO_OUT32(KEYLARGO_GPIO_LEVELS0, save_gpio_levels[0]);
MACIO_OUT32(KEYLARGO_GPIO_LEVELS1, save_gpio_levels[1]);
for (i=0; i<KEYLARGO_GPIO_EXTINT_CNT; i++)
MACIO_OUT8(KEYLARGO_GPIO_EXTINT_0+i, save_gpio_extint[i]);
for (i=0; i<KEYLARGO_GPIO_CNT; i++)
MACIO_OUT8(KEYLARGO_GPIO_0+i, save_gpio_normal[i]);
/* FIXME more black magic with OpenPIC ... */
if (pmac_mb.model_id == PMAC_TYPE_SAWTOOTH) {
MACIO_BIC(0x506e0, 0x00400000);
MACIO_BIC(0x506e0, 0x80000000);
}
UN_OUT(UNI_N_CLOCK_CNTL, save_unin_clock_ctl);
udelay(100);
return 0;
}
#endif /* CONFIG_PM */
static long
core99_sleep_state(struct device_node *node, long param, long value)
{
/* Param == 1 means to enter the "fake sleep" mode that is
* used for CPU speed switch
*/
if (param == 1) {
if (value == 1) {
UN_OUT(UNI_N_HWINIT_STATE, UNI_N_HWINIT_STATE_SLEEPING);
UN_OUT(UNI_N_POWER_MGT, UNI_N_POWER_MGT_IDLE2);
} else {
UN_OUT(UNI_N_POWER_MGT, UNI_N_POWER_MGT_NORMAL);
udelay(10);
UN_OUT(UNI_N_HWINIT_STATE, UNI_N_HWINIT_STATE_RUNNING);
udelay(10);
}
return 0;
}
if ((pmac_mb.board_flags & PMAC_MB_CAN_SLEEP) == 0)
return -EPERM;
#ifdef CONFIG_PM
if (value == 1)
return core99_sleep();
else if (value == 0)
return core99_wake_up();
#endif /* CONFIG_PM */
return 0;
}
#endif /* CONFIG_POWER4 */
static long
generic_dev_can_wake(struct device_node *node, long param, long value)
{
/* Todo: eventually check we are really dealing with on-board
* video device ...
*/
if (pmac_mb.board_flags & PMAC_MB_MAY_SLEEP)
pmac_mb.board_flags |= PMAC_MB_CAN_SLEEP;
return 0;
}
static long generic_get_mb_info(struct device_node *node, long param, long value)
{
switch(param) {
case PMAC_MB_INFO_MODEL:
return pmac_mb.model_id;
case PMAC_MB_INFO_FLAGS:
return pmac_mb.board_flags;
case PMAC_MB_INFO_NAME:
/* hack hack hack... but should work */
*((const char **)value) = pmac_mb.model_name;
return 0;
}
return -EINVAL;
}
/*
* Table definitions
*/
/* Used on any machine
*/
static struct feature_table_entry any_features[] = {
{ PMAC_FTR_GET_MB_INFO, generic_get_mb_info },
{ PMAC_FTR_DEVICE_CAN_WAKE, generic_dev_can_wake },
{ 0, NULL }
};
#ifndef CONFIG_POWER4
/* OHare based motherboards. Currently, we only use these on the
* 2400,3400 and 3500 series powerbooks. Some older desktops seem
* to have issues with turning on/off those asic cells
*/
static struct feature_table_entry ohare_features[] = {
{ PMAC_FTR_SCC_ENABLE, ohare_htw_scc_enable },
{ PMAC_FTR_SWIM3_ENABLE, ohare_floppy_enable },
{ PMAC_FTR_MESH_ENABLE, ohare_mesh_enable },
{ PMAC_FTR_IDE_ENABLE, ohare_ide_enable},
{ PMAC_FTR_IDE_RESET, ohare_ide_reset},
{ PMAC_FTR_SLEEP_STATE, ohare_sleep_state },
{ 0, NULL }
};
/* Heathrow desktop machines (Beige G3).
* Separated as some features couldn't be properly tested
* and the serial port control bits appear to confuse it.
*/
static struct feature_table_entry heathrow_desktop_features[] = {
{ PMAC_FTR_SWIM3_ENABLE, heathrow_floppy_enable },
{ PMAC_FTR_MESH_ENABLE, heathrow_mesh_enable },
{ PMAC_FTR_IDE_ENABLE, heathrow_ide_enable },
{ PMAC_FTR_IDE_RESET, heathrow_ide_reset },
{ PMAC_FTR_BMAC_ENABLE, heathrow_bmac_enable },
{ 0, NULL }
};
/* Heathrow based laptop, that is the Wallstreet and mainstreet
* powerbooks.
*/
static struct feature_table_entry heathrow_laptop_features[] = {
{ PMAC_FTR_SCC_ENABLE, ohare_htw_scc_enable },
{ PMAC_FTR_MODEM_ENABLE, heathrow_modem_enable },
{ PMAC_FTR_SWIM3_ENABLE, heathrow_floppy_enable },
{ PMAC_FTR_MESH_ENABLE, heathrow_mesh_enable },
{ PMAC_FTR_IDE_ENABLE, heathrow_ide_enable },
{ PMAC_FTR_IDE_RESET, heathrow_ide_reset },
{ PMAC_FTR_BMAC_ENABLE, heathrow_bmac_enable },
{ PMAC_FTR_SOUND_CHIP_ENABLE, heathrow_sound_enable },
{ PMAC_FTR_SLEEP_STATE, heathrow_sleep_state },
{ 0, NULL }
};
/* Paddington based machines
* The lombard (101) powerbook, first iMac models, B&W G3 and Yikes G4.
*/
static struct feature_table_entry paddington_features[] = {
{ PMAC_FTR_SCC_ENABLE, ohare_htw_scc_enable },
{ PMAC_FTR_MODEM_ENABLE, heathrow_modem_enable },
{ PMAC_FTR_SWIM3_ENABLE, heathrow_floppy_enable },
{ PMAC_FTR_MESH_ENABLE, heathrow_mesh_enable },
{ PMAC_FTR_IDE_ENABLE, heathrow_ide_enable },
{ PMAC_FTR_IDE_RESET, heathrow_ide_reset },
{ PMAC_FTR_BMAC_ENABLE, heathrow_bmac_enable },
{ PMAC_FTR_SOUND_CHIP_ENABLE, heathrow_sound_enable },
{ PMAC_FTR_SLEEP_STATE, heathrow_sleep_state },
{ 0, NULL }
};
/* Core99 & MacRISC 2 machines (all machines released since the
* iBook (included), that is all AGP machines, except pangea
* chipset. The pangea chipset is the "combo" UniNorth/KeyLargo
* used on iBook2 & iMac "flow power".
*/
static struct feature_table_entry core99_features[] = {
{ PMAC_FTR_SCC_ENABLE, core99_scc_enable },
{ PMAC_FTR_MODEM_ENABLE, core99_modem_enable },
{ PMAC_FTR_IDE_ENABLE, core99_ide_enable },
{ PMAC_FTR_IDE_RESET, core99_ide_reset },
{ PMAC_FTR_GMAC_ENABLE, core99_gmac_enable },
{ PMAC_FTR_GMAC_PHY_RESET, core99_gmac_phy_reset },
{ PMAC_FTR_SOUND_CHIP_ENABLE, core99_sound_chip_enable },
{ PMAC_FTR_AIRPORT_ENABLE, core99_airport_enable },
{ PMAC_FTR_USB_ENABLE, core99_usb_enable },
{ PMAC_FTR_1394_ENABLE, core99_firewire_enable },
{ PMAC_FTR_1394_CABLE_POWER, core99_firewire_cable_power },
#ifdef CONFIG_PM
{ PMAC_FTR_SLEEP_STATE, core99_sleep_state },
#endif
#ifdef CONFIG_SMP
{ PMAC_FTR_RESET_CPU, core99_reset_cpu },
#endif /* CONFIG_SMP */
{ PMAC_FTR_READ_GPIO, core99_read_gpio },
{ PMAC_FTR_WRITE_GPIO, core99_write_gpio },
{ 0, NULL }
};
/* RackMac
*/
static struct feature_table_entry rackmac_features[] = {
{ PMAC_FTR_SCC_ENABLE, core99_scc_enable },
{ PMAC_FTR_IDE_ENABLE, core99_ide_enable },
{ PMAC_FTR_IDE_RESET, core99_ide_reset },
{ PMAC_FTR_GMAC_ENABLE, core99_gmac_enable },
{ PMAC_FTR_GMAC_PHY_RESET, core99_gmac_phy_reset },
{ PMAC_FTR_USB_ENABLE, core99_usb_enable },
{ PMAC_FTR_1394_ENABLE, core99_firewire_enable },
{ PMAC_FTR_1394_CABLE_POWER, core99_firewire_cable_power },
{ PMAC_FTR_SLEEP_STATE, core99_sleep_state },
#ifdef CONFIG_SMP
{ PMAC_FTR_RESET_CPU, core99_reset_cpu },
#endif /* CONFIG_SMP */
{ PMAC_FTR_READ_GPIO, core99_read_gpio },
{ PMAC_FTR_WRITE_GPIO, core99_write_gpio },
{ 0, NULL }
};
/* Pangea features
*/
static struct feature_table_entry pangea_features[] = {
{ PMAC_FTR_SCC_ENABLE, core99_scc_enable },
{ PMAC_FTR_MODEM_ENABLE, pangea_modem_enable },
{ PMAC_FTR_IDE_ENABLE, core99_ide_enable },
{ PMAC_FTR_IDE_RESET, core99_ide_reset },
{ PMAC_FTR_GMAC_ENABLE, core99_gmac_enable },
{ PMAC_FTR_GMAC_PHY_RESET, core99_gmac_phy_reset },
{ PMAC_FTR_SOUND_CHIP_ENABLE, core99_sound_chip_enable },
{ PMAC_FTR_AIRPORT_ENABLE, core99_airport_enable },
{ PMAC_FTR_USB_ENABLE, core99_usb_enable },
{ PMAC_FTR_1394_ENABLE, core99_firewire_enable },
{ PMAC_FTR_1394_CABLE_POWER, core99_firewire_cable_power },
{ PMAC_FTR_SLEEP_STATE, core99_sleep_state },
{ PMAC_FTR_READ_GPIO, core99_read_gpio },
{ PMAC_FTR_WRITE_GPIO, core99_write_gpio },
{ 0, NULL }
};
/* Intrepid features
*/
static struct feature_table_entry intrepid_features[] = {
{ PMAC_FTR_SCC_ENABLE, core99_scc_enable },
{ PMAC_FTR_MODEM_ENABLE, pangea_modem_enable },
{ PMAC_FTR_IDE_ENABLE, core99_ide_enable },
{ PMAC_FTR_IDE_RESET, core99_ide_reset },
{ PMAC_FTR_GMAC_ENABLE, core99_gmac_enable },
{ PMAC_FTR_GMAC_PHY_RESET, core99_gmac_phy_reset },
{ PMAC_FTR_SOUND_CHIP_ENABLE, core99_sound_chip_enable },
{ PMAC_FTR_AIRPORT_ENABLE, core99_airport_enable },
{ PMAC_FTR_USB_ENABLE, core99_usb_enable },
{ PMAC_FTR_1394_ENABLE, core99_firewire_enable },
{ PMAC_FTR_1394_CABLE_POWER, core99_firewire_cable_power },
{ PMAC_FTR_SLEEP_STATE, core99_sleep_state },
{ PMAC_FTR_READ_GPIO, core99_read_gpio },
{ PMAC_FTR_WRITE_GPIO, core99_write_gpio },
{ PMAC_FTR_AACK_DELAY_ENABLE, intrepid_aack_delay_enable },
{ 0, NULL }
};
#else /* CONFIG_POWER4 */
/* G5 features
*/
static struct feature_table_entry g5_features[] = {
{ PMAC_FTR_GMAC_ENABLE, g5_gmac_enable },
{ PMAC_FTR_1394_ENABLE, g5_fw_enable },
{ PMAC_FTR_ENABLE_MPIC, g5_mpic_enable },
{ PMAC_FTR_GMAC_PHY_RESET, g5_eth_phy_reset },
{ PMAC_FTR_SOUND_CHIP_ENABLE, g5_i2s_enable },
#ifdef CONFIG_SMP
{ PMAC_FTR_RESET_CPU, g5_reset_cpu },
#endif /* CONFIG_SMP */
{ PMAC_FTR_READ_GPIO, core99_read_gpio },
{ PMAC_FTR_WRITE_GPIO, core99_write_gpio },
{ 0, NULL }
};
#endif /* CONFIG_POWER4 */
static struct pmac_mb_def pmac_mb_defs[] = {
#ifndef CONFIG_POWER4
/*
* Desktops
*/
{ "AAPL,8500", "PowerMac 8500/8600",
PMAC_TYPE_PSURGE, NULL,
0
},
{ "AAPL,9500", "PowerMac 9500/9600",
PMAC_TYPE_PSURGE, NULL,
0
},
{ "AAPL,7200", "PowerMac 7200",
PMAC_TYPE_PSURGE, NULL,
0
},
{ "AAPL,7300", "PowerMac 7200/7300",
PMAC_TYPE_PSURGE, NULL,
0
},
{ "AAPL,7500", "PowerMac 7500",
PMAC_TYPE_PSURGE, NULL,
0
},
{ "AAPL,ShinerESB", "Apple Network Server",
PMAC_TYPE_ANS, NULL,
0
},
{ "AAPL,e407", "Alchemy",
PMAC_TYPE_ALCHEMY, NULL,
0
},
{ "AAPL,e411", "Gazelle",
PMAC_TYPE_GAZELLE, NULL,
0
},
{ "AAPL,Gossamer", "PowerMac G3 (Gossamer)",
PMAC_TYPE_GOSSAMER, heathrow_desktop_features,
0
},
{ "AAPL,PowerMac G3", "PowerMac G3 (Silk)",
PMAC_TYPE_SILK, heathrow_desktop_features,
0
},
{ "PowerMac1,1", "Blue&White G3",
PMAC_TYPE_YOSEMITE, paddington_features,
0
},
{ "PowerMac1,2", "PowerMac G4 PCI Graphics",
PMAC_TYPE_YIKES, paddington_features,
0
},
{ "PowerMac2,1", "iMac FireWire",
PMAC_TYPE_FW_IMAC, core99_features,
PMAC_MB_MAY_SLEEP | PMAC_MB_OLD_CORE99
},
{ "PowerMac2,2", "iMac FireWire",
PMAC_TYPE_FW_IMAC, core99_features,
PMAC_MB_MAY_SLEEP | PMAC_MB_OLD_CORE99
},
{ "PowerMac3,1", "PowerMac G4 AGP Graphics",
PMAC_TYPE_SAWTOOTH, core99_features,
PMAC_MB_OLD_CORE99
},
{ "PowerMac3,2", "PowerMac G4 AGP Graphics",
PMAC_TYPE_SAWTOOTH, core99_features,
PMAC_MB_MAY_SLEEP | PMAC_MB_OLD_CORE99
},
{ "PowerMac3,3", "PowerMac G4 AGP Graphics",
PMAC_TYPE_SAWTOOTH, core99_features,
PMAC_MB_MAY_SLEEP | PMAC_MB_OLD_CORE99
},
{ "PowerMac3,4", "PowerMac G4 Silver",
PMAC_TYPE_QUICKSILVER, core99_features,
PMAC_MB_MAY_SLEEP
},
{ "PowerMac3,5", "PowerMac G4 Silver",
PMAC_TYPE_QUICKSILVER, core99_features,
PMAC_MB_MAY_SLEEP
},
{ "PowerMac3,6", "PowerMac G4 Windtunnel",
PMAC_TYPE_WINDTUNNEL, core99_features,
PMAC_MB_MAY_SLEEP,
},
{ "PowerMac4,1", "iMac \"Flower Power\"",
PMAC_TYPE_PANGEA_IMAC, pangea_features,
PMAC_MB_MAY_SLEEP
},
{ "PowerMac4,2", "Flat panel iMac",
PMAC_TYPE_FLAT_PANEL_IMAC, pangea_features,
PMAC_MB_CAN_SLEEP
},
{ "PowerMac4,4", "eMac",
PMAC_TYPE_EMAC, core99_features,
PMAC_MB_MAY_SLEEP
},
{ "PowerMac5,1", "PowerMac G4 Cube",
PMAC_TYPE_CUBE, core99_features,
PMAC_MB_MAY_SLEEP | PMAC_MB_OLD_CORE99
},
{ "PowerMac6,1", "Flat panel iMac",
PMAC_TYPE_UNKNOWN_INTREPID, intrepid_features,
PMAC_MB_MAY_SLEEP,
},
{ "PowerMac6,3", "Flat panel iMac",
PMAC_TYPE_UNKNOWN_INTREPID, intrepid_features,
PMAC_MB_MAY_SLEEP,
},
{ "PowerMac6,4", "eMac",
PMAC_TYPE_UNKNOWN_INTREPID, intrepid_features,
PMAC_MB_MAY_SLEEP,
},
{ "PowerMac10,1", "Mac mini",
PMAC_TYPE_UNKNOWN_INTREPID, intrepid_features,
PMAC_MB_MAY_SLEEP,
},
{ "PowerMac10,2", "Mac mini (Late 2005)",
PMAC_TYPE_UNKNOWN_INTREPID, intrepid_features,
PMAC_MB_MAY_SLEEP,
},
{ "iMac,1", "iMac (first generation)",
PMAC_TYPE_ORIG_IMAC, paddington_features,
0
},
/*
* Xserve's
*/
{ "RackMac1,1", "XServe",
PMAC_TYPE_RACKMAC, rackmac_features,
0,
},
{ "RackMac1,2", "XServe rev. 2",
PMAC_TYPE_RACKMAC, rackmac_features,
0,
},
/*
* Laptops
*/
{ "AAPL,3400/2400", "PowerBook 3400",
PMAC_TYPE_HOOPER, ohare_features,
PMAC_MB_CAN_SLEEP | PMAC_MB_MOBILE
},
{ "AAPL,3500", "PowerBook 3500",
PMAC_TYPE_KANGA, ohare_features,
PMAC_MB_CAN_SLEEP | PMAC_MB_MOBILE
},
{ "AAPL,PowerBook1998", "PowerBook Wallstreet",
PMAC_TYPE_WALLSTREET, heathrow_laptop_features,
PMAC_MB_CAN_SLEEP | PMAC_MB_MOBILE
},
{ "PowerBook1,1", "PowerBook 101 (Lombard)",
PMAC_TYPE_101_PBOOK, paddington_features,
PMAC_MB_CAN_SLEEP | PMAC_MB_MOBILE
},
{ "PowerBook2,1", "iBook (first generation)",
PMAC_TYPE_ORIG_IBOOK, core99_features,
PMAC_MB_CAN_SLEEP | PMAC_MB_OLD_CORE99 | PMAC_MB_MOBILE
},
{ "PowerBook2,2", "iBook FireWire",
PMAC_TYPE_FW_IBOOK, core99_features,
PMAC_MB_MAY_SLEEP | PMAC_MB_HAS_FW_POWER |
PMAC_MB_OLD_CORE99 | PMAC_MB_MOBILE
},
{ "PowerBook3,1", "PowerBook Pismo",
PMAC_TYPE_PISMO, core99_features,
PMAC_MB_MAY_SLEEP | PMAC_MB_HAS_FW_POWER |
PMAC_MB_OLD_CORE99 | PMAC_MB_MOBILE
},
{ "PowerBook3,2", "PowerBook Titanium",
PMAC_TYPE_TITANIUM, core99_features,
PMAC_MB_MAY_SLEEP | PMAC_MB_HAS_FW_POWER | PMAC_MB_MOBILE
},
{ "PowerBook3,3", "PowerBook Titanium II",
PMAC_TYPE_TITANIUM2, core99_features,
PMAC_MB_MAY_SLEEP | PMAC_MB_HAS_FW_POWER | PMAC_MB_MOBILE
},
{ "PowerBook3,4", "PowerBook Titanium III",
PMAC_TYPE_TITANIUM3, core99_features,
PMAC_MB_MAY_SLEEP | PMAC_MB_HAS_FW_POWER | PMAC_MB_MOBILE
},
{ "PowerBook3,5", "PowerBook Titanium IV",
PMAC_TYPE_TITANIUM4, core99_features,
PMAC_MB_MAY_SLEEP | PMAC_MB_HAS_FW_POWER | PMAC_MB_MOBILE
},
{ "PowerBook4,1", "iBook 2",
PMAC_TYPE_IBOOK2, pangea_features,
PMAC_MB_MAY_SLEEP | PMAC_MB_HAS_FW_POWER | PMAC_MB_MOBILE
},
{ "PowerBook4,2", "iBook 2",
PMAC_TYPE_IBOOK2, pangea_features,
PMAC_MB_MAY_SLEEP | PMAC_MB_HAS_FW_POWER | PMAC_MB_MOBILE
},
{ "PowerBook4,3", "iBook 2 rev. 2",
PMAC_TYPE_IBOOK2, pangea_features,
PMAC_MB_MAY_SLEEP | PMAC_MB_HAS_FW_POWER | PMAC_MB_MOBILE
},
{ "PowerBook5,1", "PowerBook G4 17\"",
PMAC_TYPE_UNKNOWN_INTREPID, intrepid_features,
PMAC_MB_HAS_FW_POWER | PMAC_MB_MOBILE,
},
{ "PowerBook5,2", "PowerBook G4 15\"",
PMAC_TYPE_UNKNOWN_INTREPID, intrepid_features,
PMAC_MB_MAY_SLEEP | PMAC_MB_HAS_FW_POWER | PMAC_MB_MOBILE,
},
{ "PowerBook5,3", "PowerBook G4 17\"",
PMAC_TYPE_UNKNOWN_INTREPID, intrepid_features,
PMAC_MB_MAY_SLEEP | PMAC_MB_HAS_FW_POWER | PMAC_MB_MOBILE,
},
{ "PowerBook5,4", "PowerBook G4 15\"",
PMAC_TYPE_UNKNOWN_INTREPID, intrepid_features,
PMAC_MB_MAY_SLEEP | PMAC_MB_HAS_FW_POWER | PMAC_MB_MOBILE,
},
{ "PowerBook5,5", "PowerBook G4 17\"",
PMAC_TYPE_UNKNOWN_INTREPID, intrepid_features,
PMAC_MB_MAY_SLEEP | PMAC_MB_HAS_FW_POWER | PMAC_MB_MOBILE,
},
{ "PowerBook5,6", "PowerBook G4 15\"",
PMAC_TYPE_UNKNOWN_INTREPID, intrepid_features,
PMAC_MB_MAY_SLEEP | PMAC_MB_HAS_FW_POWER | PMAC_MB_MOBILE,
},
{ "PowerBook5,7", "PowerBook G4 17\"",
PMAC_TYPE_UNKNOWN_INTREPID, intrepid_features,
PMAC_MB_MAY_SLEEP | PMAC_MB_HAS_FW_POWER | PMAC_MB_MOBILE,
},
{ "PowerBook5,8", "PowerBook G4 15\"",
PMAC_TYPE_UNKNOWN_INTREPID, intrepid_features,
PMAC_MB_MAY_SLEEP | PMAC_MB_MOBILE,
},
{ "PowerBook5,9", "PowerBook G4 17\"",
PMAC_TYPE_UNKNOWN_INTREPID, intrepid_features,
PMAC_MB_MAY_SLEEP | PMAC_MB_MOBILE,
},
{ "PowerBook6,1", "PowerBook G4 12\"",
PMAC_TYPE_UNKNOWN_INTREPID, intrepid_features,
PMAC_MB_MAY_SLEEP | PMAC_MB_HAS_FW_POWER | PMAC_MB_MOBILE,
},
{ "PowerBook6,2", "PowerBook G4",
PMAC_TYPE_UNKNOWN_INTREPID, intrepid_features,
PMAC_MB_MAY_SLEEP | PMAC_MB_HAS_FW_POWER | PMAC_MB_MOBILE,
},
{ "PowerBook6,3", "iBook G4",
PMAC_TYPE_UNKNOWN_INTREPID, intrepid_features,
PMAC_MB_MAY_SLEEP | PMAC_MB_HAS_FW_POWER | PMAC_MB_MOBILE,
},
{ "PowerBook6,4", "PowerBook G4 12\"",
PMAC_TYPE_UNKNOWN_INTREPID, intrepid_features,
PMAC_MB_MAY_SLEEP | PMAC_MB_HAS_FW_POWER | PMAC_MB_MOBILE,
},
{ "PowerBook6,5", "iBook G4",
PMAC_TYPE_UNKNOWN_INTREPID, intrepid_features,
PMAC_MB_MAY_SLEEP | PMAC_MB_HAS_FW_POWER | PMAC_MB_MOBILE,
},
{ "PowerBook6,7", "iBook G4",
PMAC_TYPE_UNKNOWN_INTREPID, intrepid_features,
PMAC_MB_MAY_SLEEP | PMAC_MB_HAS_FW_POWER | PMAC_MB_MOBILE,
},
{ "PowerBook6,8", "PowerBook G4 12\"",
PMAC_TYPE_UNKNOWN_INTREPID, intrepid_features,
PMAC_MB_MAY_SLEEP | PMAC_MB_HAS_FW_POWER | PMAC_MB_MOBILE,
},
#else /* CONFIG_POWER4 */
{ "PowerMac7,2", "PowerMac G5",
PMAC_TYPE_POWERMAC_G5, g5_features,
0,
},
#ifdef CONFIG_PPC64
{ "PowerMac7,3", "PowerMac G5",
PMAC_TYPE_POWERMAC_G5, g5_features,
0,
},
{ "PowerMac8,1", "iMac G5",
PMAC_TYPE_IMAC_G5, g5_features,
0,
},
{ "PowerMac9,1", "PowerMac G5",
PMAC_TYPE_POWERMAC_G5_U3L, g5_features,
0,
},
{ "PowerMac11,2", "PowerMac G5 Dual Core",
PMAC_TYPE_POWERMAC_G5_U3L, g5_features,
0,
},
{ "PowerMac12,1", "iMac G5 (iSight)",
PMAC_TYPE_POWERMAC_G5_U3L, g5_features,
0,
},
{ "RackMac3,1", "XServe G5",
PMAC_TYPE_XSERVE_G5, g5_features,
0,
},
#endif /* CONFIG_PPC64 */
#endif /* CONFIG_POWER4 */
};
/*
* The toplevel feature_call callback
*/
long pmac_do_feature_call(unsigned int selector, ...)
{
struct device_node *node;
long param, value;
int i;
feature_call func = NULL;
va_list args;
if (pmac_mb.features)
for (i=0; pmac_mb.features[i].function; i++)
if (pmac_mb.features[i].selector == selector) {
func = pmac_mb.features[i].function;
break;
}
if (!func)
for (i=0; any_features[i].function; i++)
if (any_features[i].selector == selector) {
func = any_features[i].function;
break;
}
if (!func)
return -ENODEV;
va_start(args, selector);
node = (struct device_node*)va_arg(args, void*);
param = va_arg(args, long);
value = va_arg(args, long);
va_end(args);
return func(node, param, value);
}
static int __init probe_motherboard(void)
{
int i;
struct macio_chip *macio = &macio_chips[0];
const char *model = NULL;
struct device_node *dt;
int ret = 0;
/* Lookup known motherboard type in device-tree. First try an
* exact match on the "model" property, then try a "compatible"
* match is none is found.
*/
dt = of_find_node_by_name(NULL, "device-tree");
if (dt != NULL)
model = of_get_property(dt, "model", NULL);
for(i=0; model && i<ARRAY_SIZE(pmac_mb_defs); i++) {
if (strcmp(model, pmac_mb_defs[i].model_string) == 0) {
pmac_mb = pmac_mb_defs[i];
goto found;
}
}
for(i=0; i<ARRAY_SIZE(pmac_mb_defs); i++) {
if (of_machine_is_compatible(pmac_mb_defs[i].model_string)) {
pmac_mb = pmac_mb_defs[i];
goto found;
}
}
/* Fallback to selection depending on mac-io chip type */
switch(macio->type) {
#ifndef CONFIG_POWER4
case macio_grand_central:
pmac_mb.model_id = PMAC_TYPE_PSURGE;
pmac_mb.model_name = "Unknown PowerSurge";
break;
case macio_ohare:
pmac_mb.model_id = PMAC_TYPE_UNKNOWN_OHARE;
pmac_mb.model_name = "Unknown OHare-based";
break;
case macio_heathrow:
pmac_mb.model_id = PMAC_TYPE_UNKNOWN_HEATHROW;
pmac_mb.model_name = "Unknown Heathrow-based";
pmac_mb.features = heathrow_desktop_features;
break;
case macio_paddington:
pmac_mb.model_id = PMAC_TYPE_UNKNOWN_PADDINGTON;
pmac_mb.model_name = "Unknown Paddington-based";
pmac_mb.features = paddington_features;
break;
case macio_keylargo:
pmac_mb.model_id = PMAC_TYPE_UNKNOWN_CORE99;
pmac_mb.model_name = "Unknown Keylargo-based";
pmac_mb.features = core99_features;
break;
case macio_pangea:
pmac_mb.model_id = PMAC_TYPE_UNKNOWN_PANGEA;
pmac_mb.model_name = "Unknown Pangea-based";
pmac_mb.features = pangea_features;
break;
case macio_intrepid:
pmac_mb.model_id = PMAC_TYPE_UNKNOWN_INTREPID;
pmac_mb.model_name = "Unknown Intrepid-based";
pmac_mb.features = intrepid_features;
break;
#else /* CONFIG_POWER4 */
case macio_keylargo2:
pmac_mb.model_id = PMAC_TYPE_UNKNOWN_K2;
pmac_mb.model_name = "Unknown K2-based";
pmac_mb.features = g5_features;
break;
case macio_shasta:
pmac_mb.model_id = PMAC_TYPE_UNKNOWN_SHASTA;
pmac_mb.model_name = "Unknown Shasta-based";
pmac_mb.features = g5_features;
break;
#endif /* CONFIG_POWER4 */
default:
ret = -ENODEV;
goto done;
}
found:
#ifndef CONFIG_POWER4
/* Fixup Hooper vs. Comet */
if (pmac_mb.model_id == PMAC_TYPE_HOOPER) {
u32 __iomem * mach_id_ptr = ioremap(0xf3000034, 4);
if (!mach_id_ptr) {
ret = -ENODEV;
goto done;
}
/* Here, I used to disable the media-bay on comet. It
* appears this is wrong, the floppy connector is actually
* a kind of media-bay and works with the current driver.
*/
if (__raw_readl(mach_id_ptr) & 0x20000000UL)
pmac_mb.model_id = PMAC_TYPE_COMET;
iounmap(mach_id_ptr);
}
/* Set default value of powersave_nap on machines that support it.
* It appears that uninorth rev 3 has a problem with it, we don't
* enable it on those. In theory, the flush-on-lock property is
* supposed to be set when not supported, but I'm not very confident
* that all Apple OF revs did it properly, I do it the paranoid way.
*/
while (uninorth_base && uninorth_rev > 3) {
struct device_node *cpus = of_find_node_by_path("/cpus");
struct device_node *np;
if (!cpus || !cpus->child) {
printk(KERN_WARNING "Can't find CPU(s) in device tree !\n");
of_node_put(cpus);
break;
}
np = cpus->child;
/* Nap mode not supported on SMP */
if (np->sibling) {
of_node_put(cpus);
break;
}
/* Nap mode not supported if flush-on-lock property is present */
if (of_get_property(np, "flush-on-lock", NULL)) {
of_node_put(cpus);
break;
}
of_node_put(cpus);
powersave_nap = 1;
printk(KERN_DEBUG "Processor NAP mode on idle enabled.\n");
break;
}
/* On CPUs that support it (750FX), lowspeed by default during
* NAP mode
*/
powersave_lowspeed = 1;
#else /* CONFIG_POWER4 */
powersave_nap = 1;
#endif /* CONFIG_POWER4 */
/* Check for "mobile" machine */
if (model && (strncmp(model, "PowerBook", 9) == 0
|| strncmp(model, "iBook", 5) == 0))
pmac_mb.board_flags |= PMAC_MB_MOBILE;
printk(KERN_INFO "PowerMac motherboard: %s\n", pmac_mb.model_name);
done:
of_node_put(dt);
return ret;
}
/* Initialize the Core99 UniNorth host bridge and memory controller
*/
static void __init probe_uninorth(void)
{
const u32 *addrp;
phys_addr_t address;
unsigned long actrl;
/* Locate core99 Uni-N */
uninorth_node = of_find_node_by_name(NULL, "uni-n");
uninorth_maj = 1;
/* Locate G5 u3 */
if (uninorth_node == NULL) {
uninorth_node = of_find_node_by_name(NULL, "u3");
uninorth_maj = 3;
}
/* Locate G5 u4 */
if (uninorth_node == NULL) {
uninorth_node = of_find_node_by_name(NULL, "u4");
uninorth_maj = 4;
}
if (uninorth_node == NULL) {
uninorth_maj = 0;
return;
}
addrp = of_get_property(uninorth_node, "reg", NULL);
if (addrp == NULL)
return;
address = of_translate_address(uninorth_node, addrp);
if (address == 0)
return;
uninorth_base = ioremap(address, 0x40000);
if (uninorth_base == NULL)
return;
uninorth_rev = in_be32(UN_REG(UNI_N_VERSION));
if (uninorth_maj == 3 || uninorth_maj == 4) {
u3_ht_base = ioremap(address + U3_HT_CONFIG_BASE, 0x1000);
if (u3_ht_base == NULL) {
iounmap(uninorth_base);
return;
}
}
printk(KERN_INFO "Found %s memory controller & host bridge"
" @ 0x%08x revision: 0x%02x\n", uninorth_maj == 3 ? "U3" :
uninorth_maj == 4 ? "U4" : "UniNorth",
(unsigned int)address, uninorth_rev);
printk(KERN_INFO "Mapped at 0x%08lx\n", (unsigned long)uninorth_base);
/* Set the arbitrer QAck delay according to what Apple does
*/
if (uninorth_rev < 0x11) {
actrl = UN_IN(UNI_N_ARB_CTRL) & ~UNI_N_ARB_CTRL_QACK_DELAY_MASK;
actrl |= ((uninorth_rev < 3) ? UNI_N_ARB_CTRL_QACK_DELAY105 :
UNI_N_ARB_CTRL_QACK_DELAY) <<
UNI_N_ARB_CTRL_QACK_DELAY_SHIFT;
UN_OUT(UNI_N_ARB_CTRL, actrl);
}
/* Some more magic as done by them in recent MacOS X on UniNorth
* revs 1.5 to 2.O and Pangea. Seem to toggle the UniN Maxbus/PCI
* memory timeout
*/
if ((uninorth_rev >= 0x11 && uninorth_rev <= 0x24) ||
uninorth_rev == 0xc0)
UN_OUT(0x2160, UN_IN(0x2160) & 0x00ffffff);
}
static void __init probe_one_macio(const char *name, const char *compat, int type)
{
struct device_node* node;
int i;
volatile u32 __iomem *base;
const u32 *addrp, *revp;
phys_addr_t addr;
u64 size;
for (node = NULL; (node = of_find_node_by_name(node, name)) != NULL;) {
if (!compat)
break;
if (of_device_is_compatible(node, compat))
break;
}
if (!node)
return;
for(i=0; i<MAX_MACIO_CHIPS; i++) {
if (!macio_chips[i].of_node)
break;
if (macio_chips[i].of_node == node)
return;
}
if (i >= MAX_MACIO_CHIPS) {
printk(KERN_ERR "pmac_feature: Please increase MAX_MACIO_CHIPS !\n");
printk(KERN_ERR "pmac_feature: %s skipped\n", node->full_name);
return;
}
addrp = of_get_pci_address(node, 0, &size, NULL);
if (addrp == NULL) {
printk(KERN_ERR "pmac_feature: %s: can't find base !\n",
node->full_name);
return;
}
addr = of_translate_address(node, addrp);
if (addr == 0) {
printk(KERN_ERR "pmac_feature: %s, can't translate base !\n",
node->full_name);
return;
}
base = ioremap(addr, (unsigned long)size);
if (!base) {
printk(KERN_ERR "pmac_feature: %s, can't map mac-io chip !\n",
node->full_name);
return;
}
if (type == macio_keylargo || type == macio_keylargo2) {
const u32 *did = of_get_property(node, "device-id", NULL);
if (*did == 0x00000025)
type = macio_pangea;
if (*did == 0x0000003e)
type = macio_intrepid;
if (*did == 0x0000004f)
type = macio_shasta;
}
macio_chips[i].of_node = node;
macio_chips[i].type = type;
macio_chips[i].base = base;
macio_chips[i].flags = MACIO_FLAG_SCCA_ON | MACIO_FLAG_SCCB_ON;
macio_chips[i].name = macio_names[type];
revp = of_get_property(node, "revision-id", NULL);
if (revp)
macio_chips[i].rev = *revp;
printk(KERN_INFO "Found a %s mac-io controller, rev: %d, mapped at 0x%p\n",
macio_names[type], macio_chips[i].rev, macio_chips[i].base);
}
static int __init
probe_macios(void)
{
/* Warning, ordering is important */
probe_one_macio("gc", NULL, macio_grand_central);
probe_one_macio("ohare", NULL, macio_ohare);
probe_one_macio("pci106b,7", NULL, macio_ohareII);
probe_one_macio("mac-io", "keylargo", macio_keylargo);
probe_one_macio("mac-io", "paddington", macio_paddington);
probe_one_macio("mac-io", "gatwick", macio_gatwick);
probe_one_macio("mac-io", "heathrow", macio_heathrow);
probe_one_macio("mac-io", "K2-Keylargo", macio_keylargo2);
/* Make sure the "main" macio chip appear first */
if (macio_chips[0].type == macio_gatwick
&& macio_chips[1].type == macio_heathrow) {
struct macio_chip temp = macio_chips[0];
macio_chips[0] = macio_chips[1];
macio_chips[1] = temp;
}
if (macio_chips[0].type == macio_ohareII
&& macio_chips[1].type == macio_ohare) {
struct macio_chip temp = macio_chips[0];
macio_chips[0] = macio_chips[1];
macio_chips[1] = temp;
}
macio_chips[0].lbus.index = 0;
macio_chips[1].lbus.index = 1;
return (macio_chips[0].of_node == NULL) ? -ENODEV : 0;
}
static void __init
initial_serial_shutdown(struct device_node *np)
{
int len;
const struct slot_names_prop {
int count;
char name[1];
} *slots;
const char *conn;
int port_type = PMAC_SCC_ASYNC;
int modem = 0;
slots = of_get_property(np, "slot-names", &len);
conn = of_get_property(np, "AAPL,connector", &len);
if (conn && (strcmp(conn, "infrared") == 0))
port_type = PMAC_SCC_IRDA;
else if (of_device_is_compatible(np, "cobalt"))
modem = 1;
else if (slots && slots->count > 0) {
if (strcmp(slots->name, "IrDA") == 0)
port_type = PMAC_SCC_IRDA;
else if (strcmp(slots->name, "Modem") == 0)
modem = 1;
}
if (modem)
pmac_call_feature(PMAC_FTR_MODEM_ENABLE, np, 0, 0);
pmac_call_feature(PMAC_FTR_SCC_ENABLE, np, port_type, 0);
}
static void __init
set_initial_features(void)
{
struct device_node *np;
/* That hack appears to be necessary for some StarMax motherboards
* but I'm not too sure it was audited for side-effects on other
* ohare based machines...
* Since I still have difficulties figuring the right way to
* differenciate them all and since that hack was there for a long
* time, I'll keep it around
*/
if (macio_chips[0].type == macio_ohare) {
struct macio_chip *macio = &macio_chips[0];
np = of_find_node_by_name(NULL, "via-pmu");
if (np)
MACIO_BIS(OHARE_FCR, OH_IOBUS_ENABLE);
else
MACIO_OUT32(OHARE_FCR, STARMAX_FEATURES);
of_node_put(np);
} else if (macio_chips[1].type == macio_ohare) {
struct macio_chip *macio = &macio_chips[1];
MACIO_BIS(OHARE_FCR, OH_IOBUS_ENABLE);
}
#ifdef CONFIG_POWER4
if (macio_chips[0].type == macio_keylargo2 ||
macio_chips[0].type == macio_shasta) {
#ifndef CONFIG_SMP
/* On SMP machines running UP, we have the second CPU eating
* bus cycles. We need to take it off the bus. This is done
* from pmac_smp for SMP kernels running on one CPU
*/
np = of_find_node_by_type(NULL, "cpu");
if (np != NULL)
np = of_find_node_by_type(np, "cpu");
if (np != NULL) {
g5_phy_disable_cpu1();
of_node_put(np);
}
#endif /* CONFIG_SMP */
/* Enable GMAC for now for PCI probing. It will be disabled
* later on after PCI probe
*/
np = of_find_node_by_name(NULL, "ethernet");
while(np) {
if (of_device_is_compatible(np, "K2-GMAC"))
g5_gmac_enable(np, 0, 1);
np = of_find_node_by_name(np, "ethernet");
}
/* Enable FW before PCI probe. Will be disabled later on
* Note: We should have a batter way to check that we are
* dealing with uninorth internal cell and not a PCI cell
* on the external PCI. The code below works though.
*/
np = of_find_node_by_name(NULL, "firewire");
while(np) {
if (of_device_is_compatible(np, "pci106b,5811")) {
macio_chips[0].flags |= MACIO_FLAG_FW_SUPPORTED;
g5_fw_enable(np, 0, 1);
}
np = of_find_node_by_name(np, "firewire");
}
}
#else /* CONFIG_POWER4 */
if (macio_chips[0].type == macio_keylargo ||
macio_chips[0].type == macio_pangea ||
macio_chips[0].type == macio_intrepid) {
/* Enable GMAC for now for PCI probing. It will be disabled
* later on after PCI probe
*/
np = of_find_node_by_name(NULL, "ethernet");
while(np) {
if (np->parent
&& of_device_is_compatible(np->parent, "uni-north")
&& of_device_is_compatible(np, "gmac"))
core99_gmac_enable(np, 0, 1);
np = of_find_node_by_name(np, "ethernet");
}
/* Enable FW before PCI probe. Will be disabled later on
* Note: We should have a batter way to check that we are
* dealing with uninorth internal cell and not a PCI cell
* on the external PCI. The code below works though.
*/
np = of_find_node_by_name(NULL, "firewire");
while(np) {
if (np->parent
&& of_device_is_compatible(np->parent, "uni-north")
&& (of_device_is_compatible(np, "pci106b,18") ||
of_device_is_compatible(np, "pci106b,30") ||
of_device_is_compatible(np, "pci11c1,5811"))) {
macio_chips[0].flags |= MACIO_FLAG_FW_SUPPORTED;
core99_firewire_enable(np, 0, 1);
}
np = of_find_node_by_name(np, "firewire");
}
/* Enable ATA-100 before PCI probe. */
np = of_find_node_by_name(NULL, "ata-6");
while(np) {
if (np->parent
&& of_device_is_compatible(np->parent, "uni-north")
&& of_device_is_compatible(np, "kauai-ata")) {
core99_ata100_enable(np, 1);
}
np = of_find_node_by_name(np, "ata-6");
}
/* Switch airport off */
for_each_node_by_name(np, "radio") {
if (np->parent == macio_chips[0].of_node) {
macio_chips[0].flags |= MACIO_FLAG_AIRPORT_ON;
core99_airport_enable(np, 0, 0);
}
}
}
/* On all machines that support sound PM, switch sound off */
if (macio_chips[0].of_node)
pmac_do_feature_call(PMAC_FTR_SOUND_CHIP_ENABLE,
macio_chips[0].of_node, 0, 0);
/* While on some desktop G3s, we turn it back on */
if (macio_chips[0].of_node && macio_chips[0].type == macio_heathrow
&& (pmac_mb.model_id == PMAC_TYPE_GOSSAMER ||
pmac_mb.model_id == PMAC_TYPE_SILK)) {
struct macio_chip *macio = &macio_chips[0];
MACIO_BIS(HEATHROW_FCR, HRW_SOUND_CLK_ENABLE);
MACIO_BIC(HEATHROW_FCR, HRW_SOUND_POWER_N);
}
#endif /* CONFIG_POWER4 */
/* On all machines, switch modem & serial ports off */
for_each_node_by_name(np, "ch-a")
initial_serial_shutdown(np);
of_node_put(np);
for_each_node_by_name(np, "ch-b")
initial_serial_shutdown(np);
of_node_put(np);
}
void __init
pmac_feature_init(void)
{
/* Detect the UniNorth memory controller */
probe_uninorth();
/* Probe mac-io controllers */
if (probe_macios()) {
printk(KERN_WARNING "No mac-io chip found\n");
return;
}
/* Probe machine type */
if (probe_motherboard())
printk(KERN_WARNING "Unknown PowerMac !\n");
/* Set some initial features (turn off some chips that will
* be later turned on)
*/
set_initial_features();
}
#if 0
static void dump_HT_speeds(char *name, u32 cfg, u32 frq)
{
int freqs[16] = { 200,300,400,500,600,800,1000,0,0,0,0,0,0,0,0,0 };
int bits[8] = { 8,16,0,32,2,4,0,0 };
int freq = (frq >> 8) & 0xf;
if (freqs[freq] == 0)
printk("%s: Unknown HT link frequency %x\n", name, freq);
else
printk("%s: %d MHz on main link, (%d in / %d out) bits width\n",
name, freqs[freq],
bits[(cfg >> 28) & 0x7], bits[(cfg >> 24) & 0x7]);
}
void __init pmac_check_ht_link(void)
{
u32 ufreq, freq, ucfg, cfg;
struct device_node *pcix_node;
u8 px_bus, px_devfn;
struct pci_controller *px_hose;
(void)in_be32(u3_ht_base + U3_HT_LINK_COMMAND);
ucfg = cfg = in_be32(u3_ht_base + U3_HT_LINK_CONFIG);
ufreq = freq = in_be32(u3_ht_base + U3_HT_LINK_FREQ);
dump_HT_speeds("U3 HyperTransport", cfg, freq);
pcix_node = of_find_compatible_node(NULL, "pci", "pci-x");
if (pcix_node == NULL) {
printk("No PCI-X bridge found\n");
return;
}
if (pci_device_from_OF_node(pcix_node, &px_bus, &px_devfn) != 0) {
printk("PCI-X bridge found but not matched to pci\n");
return;
}
px_hose = pci_find_hose_for_OF_device(pcix_node);
if (px_hose == NULL) {
printk("PCI-X bridge found but not matched to host\n");
return;
}
early_read_config_dword(px_hose, px_bus, px_devfn, 0xc4, &cfg);
early_read_config_dword(px_hose, px_bus, px_devfn, 0xcc, &freq);
dump_HT_speeds("PCI-X HT Uplink", cfg, freq);
early_read_config_dword(px_hose, px_bus, px_devfn, 0xc8, &cfg);
early_read_config_dword(px_hose, px_bus, px_devfn, 0xd0, &freq);
dump_HT_speeds("PCI-X HT Downlink", cfg, freq);
}
#endif /* 0 */
/*
* Early video resume hook
*/
static void (*pmac_early_vresume_proc)(void *data);
static void *pmac_early_vresume_data;
void pmac_set_early_video_resume(void (*proc)(void *data), void *data)
{
if (!machine_is(powermac))
return;
preempt_disable();
pmac_early_vresume_proc = proc;
pmac_early_vresume_data = data;
preempt_enable();
}
EXPORT_SYMBOL(pmac_set_early_video_resume);
void pmac_call_early_video_resume(void)
{
if (pmac_early_vresume_proc)
pmac_early_vresume_proc(pmac_early_vresume_data);
}
/*
* AGP related suspend/resume code
*/
static struct pci_dev *pmac_agp_bridge;
static int (*pmac_agp_suspend)(struct pci_dev *bridge);
static int (*pmac_agp_resume)(struct pci_dev *bridge);
void pmac_register_agp_pm(struct pci_dev *bridge,
int (*suspend)(struct pci_dev *bridge),
int (*resume)(struct pci_dev *bridge))
{
if (suspend || resume) {
pmac_agp_bridge = bridge;
pmac_agp_suspend = suspend;
pmac_agp_resume = resume;
return;
}
if (bridge != pmac_agp_bridge)
return;
pmac_agp_suspend = pmac_agp_resume = NULL;
return;
}
EXPORT_SYMBOL(pmac_register_agp_pm);
void pmac_suspend_agp_for_card(struct pci_dev *dev)
{
if (pmac_agp_bridge == NULL || pmac_agp_suspend == NULL)
return;
if (pmac_agp_bridge->bus != dev->bus)
return;
pmac_agp_suspend(pmac_agp_bridge);
}
EXPORT_SYMBOL(pmac_suspend_agp_for_card);
void pmac_resume_agp_for_card(struct pci_dev *dev)
{
if (pmac_agp_bridge == NULL || pmac_agp_resume == NULL)
return;
if (pmac_agp_bridge->bus != dev->bus)
return;
pmac_agp_resume(pmac_agp_bridge);
}
EXPORT_SYMBOL(pmac_resume_agp_for_card);
int pmac_get_uninorth_variant(void)
{
return uninorth_maj;
}
| gpl-2.0 |
cmenard/kernel_smdk4412 | drivers/s390/scsi/zfcp_fc.c | 8034 | 26785 | /*
* zfcp device driver
*
* Fibre Channel related functions for the zfcp device driver.
*
* Copyright IBM Corporation 2008, 2010
*/
#define KMSG_COMPONENT "zfcp"
#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/utsname.h>
#include <scsi/fc/fc_els.h>
#include <scsi/libfc.h>
#include "zfcp_ext.h"
#include "zfcp_fc.h"
struct kmem_cache *zfcp_fc_req_cache;
static u32 zfcp_fc_rscn_range_mask[] = {
[ELS_ADDR_FMT_PORT] = 0xFFFFFF,
[ELS_ADDR_FMT_AREA] = 0xFFFF00,
[ELS_ADDR_FMT_DOM] = 0xFF0000,
[ELS_ADDR_FMT_FAB] = 0x000000,
};
/**
* zfcp_fc_post_event - post event to userspace via fc_transport
* @work: work struct with enqueued events
*/
void zfcp_fc_post_event(struct work_struct *work)
{
struct zfcp_fc_event *event = NULL, *tmp = NULL;
LIST_HEAD(tmp_lh);
struct zfcp_fc_events *events = container_of(work,
struct zfcp_fc_events, work);
struct zfcp_adapter *adapter = container_of(events, struct zfcp_adapter,
events);
spin_lock_bh(&events->list_lock);
list_splice_init(&events->list, &tmp_lh);
spin_unlock_bh(&events->list_lock);
list_for_each_entry_safe(event, tmp, &tmp_lh, list) {
fc_host_post_event(adapter->scsi_host, fc_get_event_number(),
event->code, event->data);
list_del(&event->list);
kfree(event);
}
}
/**
* zfcp_fc_enqueue_event - safely enqueue FC HBA API event from irq context
* @adapter: The adapter where to enqueue the event
* @event_code: The event code (as defined in fc_host_event_code in
* scsi_transport_fc.h)
* @event_data: The event data (e.g. n_port page in case of els)
*/
void zfcp_fc_enqueue_event(struct zfcp_adapter *adapter,
enum fc_host_event_code event_code, u32 event_data)
{
struct zfcp_fc_event *event;
event = kmalloc(sizeof(struct zfcp_fc_event), GFP_ATOMIC);
if (!event)
return;
event->code = event_code;
event->data = event_data;
spin_lock(&adapter->events.list_lock);
list_add_tail(&event->list, &adapter->events.list);
spin_unlock(&adapter->events.list_lock);
queue_work(adapter->work_queue, &adapter->events.work);
}
static int zfcp_fc_wka_port_get(struct zfcp_fc_wka_port *wka_port)
{
if (mutex_lock_interruptible(&wka_port->mutex))
return -ERESTARTSYS;
if (wka_port->status == ZFCP_FC_WKA_PORT_OFFLINE ||
wka_port->status == ZFCP_FC_WKA_PORT_CLOSING) {
wka_port->status = ZFCP_FC_WKA_PORT_OPENING;
if (zfcp_fsf_open_wka_port(wka_port))
wka_port->status = ZFCP_FC_WKA_PORT_OFFLINE;
}
mutex_unlock(&wka_port->mutex);
wait_event(wka_port->completion_wq,
wka_port->status == ZFCP_FC_WKA_PORT_ONLINE ||
wka_port->status == ZFCP_FC_WKA_PORT_OFFLINE);
if (wka_port->status == ZFCP_FC_WKA_PORT_ONLINE) {
atomic_inc(&wka_port->refcount);
return 0;
}
return -EIO;
}
static void zfcp_fc_wka_port_offline(struct work_struct *work)
{
struct delayed_work *dw = to_delayed_work(work);
struct zfcp_fc_wka_port *wka_port =
container_of(dw, struct zfcp_fc_wka_port, work);
mutex_lock(&wka_port->mutex);
if ((atomic_read(&wka_port->refcount) != 0) ||
(wka_port->status != ZFCP_FC_WKA_PORT_ONLINE))
goto out;
wka_port->status = ZFCP_FC_WKA_PORT_CLOSING;
if (zfcp_fsf_close_wka_port(wka_port)) {
wka_port->status = ZFCP_FC_WKA_PORT_OFFLINE;
wake_up(&wka_port->completion_wq);
}
out:
mutex_unlock(&wka_port->mutex);
}
static void zfcp_fc_wka_port_put(struct zfcp_fc_wka_port *wka_port)
{
if (atomic_dec_return(&wka_port->refcount) != 0)
return;
/* wait 10 milliseconds, other reqs might pop in */
schedule_delayed_work(&wka_port->work, HZ / 100);
}
static void zfcp_fc_wka_port_init(struct zfcp_fc_wka_port *wka_port, u32 d_id,
struct zfcp_adapter *adapter)
{
init_waitqueue_head(&wka_port->completion_wq);
wka_port->adapter = adapter;
wka_port->d_id = d_id;
wka_port->status = ZFCP_FC_WKA_PORT_OFFLINE;
atomic_set(&wka_port->refcount, 0);
mutex_init(&wka_port->mutex);
INIT_DELAYED_WORK(&wka_port->work, zfcp_fc_wka_port_offline);
}
static void zfcp_fc_wka_port_force_offline(struct zfcp_fc_wka_port *wka)
{
cancel_delayed_work_sync(&wka->work);
mutex_lock(&wka->mutex);
wka->status = ZFCP_FC_WKA_PORT_OFFLINE;
mutex_unlock(&wka->mutex);
}
void zfcp_fc_wka_ports_force_offline(struct zfcp_fc_wka_ports *gs)
{
if (!gs)
return;
zfcp_fc_wka_port_force_offline(&gs->ms);
zfcp_fc_wka_port_force_offline(&gs->ts);
zfcp_fc_wka_port_force_offline(&gs->ds);
zfcp_fc_wka_port_force_offline(&gs->as);
}
static void _zfcp_fc_incoming_rscn(struct zfcp_fsf_req *fsf_req, u32 range,
struct fc_els_rscn_page *page)
{
unsigned long flags;
struct zfcp_adapter *adapter = fsf_req->adapter;
struct zfcp_port *port;
read_lock_irqsave(&adapter->port_list_lock, flags);
list_for_each_entry(port, &adapter->port_list, list) {
if ((port->d_id & range) == (ntoh24(page->rscn_fid) & range))
zfcp_fc_test_link(port);
if (!port->d_id)
zfcp_erp_port_reopen(port,
ZFCP_STATUS_COMMON_ERP_FAILED,
"fcrscn1");
}
read_unlock_irqrestore(&adapter->port_list_lock, flags);
}
static void zfcp_fc_incoming_rscn(struct zfcp_fsf_req *fsf_req)
{
struct fsf_status_read_buffer *status_buffer = (void *)fsf_req->data;
struct fc_els_rscn *head;
struct fc_els_rscn_page *page;
u16 i;
u16 no_entries;
unsigned int afmt;
head = (struct fc_els_rscn *) status_buffer->payload.data;
page = (struct fc_els_rscn_page *) head;
/* see FC-FS */
no_entries = head->rscn_plen / sizeof(struct fc_els_rscn_page);
for (i = 1; i < no_entries; i++) {
/* skip head and start with 1st element */
page++;
afmt = page->rscn_page_flags & ELS_RSCN_ADDR_FMT_MASK;
_zfcp_fc_incoming_rscn(fsf_req, zfcp_fc_rscn_range_mask[afmt],
page);
zfcp_fc_enqueue_event(fsf_req->adapter, FCH_EVT_RSCN,
*(u32 *)page);
}
queue_work(fsf_req->adapter->work_queue, &fsf_req->adapter->scan_work);
}
static void zfcp_fc_incoming_wwpn(struct zfcp_fsf_req *req, u64 wwpn)
{
unsigned long flags;
struct zfcp_adapter *adapter = req->adapter;
struct zfcp_port *port;
read_lock_irqsave(&adapter->port_list_lock, flags);
list_for_each_entry(port, &adapter->port_list, list)
if (port->wwpn == wwpn) {
zfcp_erp_port_forced_reopen(port, 0, "fciwwp1");
break;
}
read_unlock_irqrestore(&adapter->port_list_lock, flags);
}
static void zfcp_fc_incoming_plogi(struct zfcp_fsf_req *req)
{
struct fsf_status_read_buffer *status_buffer;
struct fc_els_flogi *plogi;
status_buffer = (struct fsf_status_read_buffer *) req->data;
plogi = (struct fc_els_flogi *) status_buffer->payload.data;
zfcp_fc_incoming_wwpn(req, plogi->fl_wwpn);
}
static void zfcp_fc_incoming_logo(struct zfcp_fsf_req *req)
{
struct fsf_status_read_buffer *status_buffer =
(struct fsf_status_read_buffer *)req->data;
struct fc_els_logo *logo =
(struct fc_els_logo *) status_buffer->payload.data;
zfcp_fc_incoming_wwpn(req, logo->fl_n_port_wwn);
}
/**
* zfcp_fc_incoming_els - handle incoming ELS
* @fsf_req - request which contains incoming ELS
*/
void zfcp_fc_incoming_els(struct zfcp_fsf_req *fsf_req)
{
struct fsf_status_read_buffer *status_buffer =
(struct fsf_status_read_buffer *) fsf_req->data;
unsigned int els_type = status_buffer->payload.data[0];
zfcp_dbf_san_in_els("fciels1", fsf_req);
if (els_type == ELS_PLOGI)
zfcp_fc_incoming_plogi(fsf_req);
else if (els_type == ELS_LOGO)
zfcp_fc_incoming_logo(fsf_req);
else if (els_type == ELS_RSCN)
zfcp_fc_incoming_rscn(fsf_req);
}
static void zfcp_fc_ns_gid_pn_eval(struct zfcp_fc_req *fc_req)
{
struct zfcp_fsf_ct_els *ct_els = &fc_req->ct_els;
struct zfcp_fc_gid_pn_rsp *gid_pn_rsp = &fc_req->u.gid_pn.rsp;
if (ct_els->status)
return;
if (gid_pn_rsp->ct_hdr.ct_cmd != FC_FS_ACC)
return;
/* looks like a valid d_id */
ct_els->port->d_id = ntoh24(gid_pn_rsp->gid_pn.fp_fid);
}
static void zfcp_fc_complete(void *data)
{
complete(data);
}
static void zfcp_fc_ct_ns_init(struct fc_ct_hdr *ct_hdr, u16 cmd, u16 mr_size)
{
ct_hdr->ct_rev = FC_CT_REV;
ct_hdr->ct_fs_type = FC_FST_DIR;
ct_hdr->ct_fs_subtype = FC_NS_SUBTYPE;
ct_hdr->ct_cmd = cmd;
ct_hdr->ct_mr_size = mr_size / 4;
}
static int zfcp_fc_ns_gid_pn_request(struct zfcp_port *port,
struct zfcp_fc_req *fc_req)
{
struct zfcp_adapter *adapter = port->adapter;
DECLARE_COMPLETION_ONSTACK(completion);
struct zfcp_fc_gid_pn_req *gid_pn_req = &fc_req->u.gid_pn.req;
struct zfcp_fc_gid_pn_rsp *gid_pn_rsp = &fc_req->u.gid_pn.rsp;
int ret;
/* setup parameters for send generic command */
fc_req->ct_els.port = port;
fc_req->ct_els.handler = zfcp_fc_complete;
fc_req->ct_els.handler_data = &completion;
fc_req->ct_els.req = &fc_req->sg_req;
fc_req->ct_els.resp = &fc_req->sg_rsp;
sg_init_one(&fc_req->sg_req, gid_pn_req, sizeof(*gid_pn_req));
sg_init_one(&fc_req->sg_rsp, gid_pn_rsp, sizeof(*gid_pn_rsp));
zfcp_fc_ct_ns_init(&gid_pn_req->ct_hdr,
FC_NS_GID_PN, ZFCP_FC_CT_SIZE_PAGE);
gid_pn_req->gid_pn.fn_wwpn = port->wwpn;
ret = zfcp_fsf_send_ct(&adapter->gs->ds, &fc_req->ct_els,
adapter->pool.gid_pn_req,
ZFCP_FC_CTELS_TMO);
if (!ret) {
wait_for_completion(&completion);
zfcp_fc_ns_gid_pn_eval(fc_req);
}
return ret;
}
/**
* zfcp_fc_ns_gid_pn - initiate GID_PN nameserver request
* @port: port where GID_PN request is needed
* return: -ENOMEM on error, 0 otherwise
*/
static int zfcp_fc_ns_gid_pn(struct zfcp_port *port)
{
int ret;
struct zfcp_fc_req *fc_req;
struct zfcp_adapter *adapter = port->adapter;
fc_req = mempool_alloc(adapter->pool.gid_pn, GFP_ATOMIC);
if (!fc_req)
return -ENOMEM;
memset(fc_req, 0, sizeof(*fc_req));
ret = zfcp_fc_wka_port_get(&adapter->gs->ds);
if (ret)
goto out;
ret = zfcp_fc_ns_gid_pn_request(port, fc_req);
zfcp_fc_wka_port_put(&adapter->gs->ds);
out:
mempool_free(fc_req, adapter->pool.gid_pn);
return ret;
}
void zfcp_fc_port_did_lookup(struct work_struct *work)
{
int ret;
struct zfcp_port *port = container_of(work, struct zfcp_port,
gid_pn_work);
ret = zfcp_fc_ns_gid_pn(port);
if (ret) {
/* could not issue gid_pn for some reason */
zfcp_erp_adapter_reopen(port->adapter, 0, "fcgpn_1");
goto out;
}
if (!port->d_id) {
zfcp_erp_set_port_status(port, ZFCP_STATUS_COMMON_ERP_FAILED);
goto out;
}
zfcp_erp_port_reopen(port, 0, "fcgpn_3");
out:
put_device(&port->dev);
}
/**
* zfcp_fc_trigger_did_lookup - trigger the d_id lookup using a GID_PN request
* @port: The zfcp_port to lookup the d_id for.
*/
void zfcp_fc_trigger_did_lookup(struct zfcp_port *port)
{
get_device(&port->dev);
if (!queue_work(port->adapter->work_queue, &port->gid_pn_work))
put_device(&port->dev);
}
/**
* zfcp_fc_plogi_evaluate - evaluate PLOGI playload
* @port: zfcp_port structure
* @plogi: plogi payload
*
* Evaluate PLOGI playload and copy important fields into zfcp_port structure
*/
void zfcp_fc_plogi_evaluate(struct zfcp_port *port, struct fc_els_flogi *plogi)
{
if (plogi->fl_wwpn != port->wwpn) {
port->d_id = 0;
dev_warn(&port->adapter->ccw_device->dev,
"A port opened with WWPN 0x%016Lx returned data that "
"identifies it as WWPN 0x%016Lx\n",
(unsigned long long) port->wwpn,
(unsigned long long) plogi->fl_wwpn);
return;
}
port->wwnn = plogi->fl_wwnn;
port->maxframe_size = plogi->fl_csp.sp_bb_data;
if (plogi->fl_cssp[0].cp_class & FC_CPC_VALID)
port->supported_classes |= FC_COS_CLASS1;
if (plogi->fl_cssp[1].cp_class & FC_CPC_VALID)
port->supported_classes |= FC_COS_CLASS2;
if (plogi->fl_cssp[2].cp_class & FC_CPC_VALID)
port->supported_classes |= FC_COS_CLASS3;
if (plogi->fl_cssp[3].cp_class & FC_CPC_VALID)
port->supported_classes |= FC_COS_CLASS4;
}
static void zfcp_fc_adisc_handler(void *data)
{
struct zfcp_fc_req *fc_req = data;
struct zfcp_port *port = fc_req->ct_els.port;
struct fc_els_adisc *adisc_resp = &fc_req->u.adisc.rsp;
if (fc_req->ct_els.status) {
/* request rejected or timed out */
zfcp_erp_port_forced_reopen(port, ZFCP_STATUS_COMMON_ERP_FAILED,
"fcadh_1");
goto out;
}
if (!port->wwnn)
port->wwnn = adisc_resp->adisc_wwnn;
if ((port->wwpn != adisc_resp->adisc_wwpn) ||
!(atomic_read(&port->status) & ZFCP_STATUS_COMMON_OPEN)) {
zfcp_erp_port_reopen(port, ZFCP_STATUS_COMMON_ERP_FAILED,
"fcadh_2");
goto out;
}
/* port is good, unblock rport without going through erp */
zfcp_scsi_schedule_rport_register(port);
out:
atomic_clear_mask(ZFCP_STATUS_PORT_LINK_TEST, &port->status);
put_device(&port->dev);
kmem_cache_free(zfcp_fc_req_cache, fc_req);
}
static int zfcp_fc_adisc(struct zfcp_port *port)
{
struct zfcp_fc_req *fc_req;
struct zfcp_adapter *adapter = port->adapter;
struct Scsi_Host *shost = adapter->scsi_host;
int ret;
fc_req = kmem_cache_zalloc(zfcp_fc_req_cache, GFP_ATOMIC);
if (!fc_req)
return -ENOMEM;
fc_req->ct_els.port = port;
fc_req->ct_els.req = &fc_req->sg_req;
fc_req->ct_els.resp = &fc_req->sg_rsp;
sg_init_one(&fc_req->sg_req, &fc_req->u.adisc.req,
sizeof(struct fc_els_adisc));
sg_init_one(&fc_req->sg_rsp, &fc_req->u.adisc.rsp,
sizeof(struct fc_els_adisc));
fc_req->ct_els.handler = zfcp_fc_adisc_handler;
fc_req->ct_els.handler_data = fc_req;
/* acc. to FC-FS, hard_nport_id in ADISC should not be set for ports
without FC-AL-2 capability, so we don't set it */
fc_req->u.adisc.req.adisc_wwpn = fc_host_port_name(shost);
fc_req->u.adisc.req.adisc_wwnn = fc_host_node_name(shost);
fc_req->u.adisc.req.adisc_cmd = ELS_ADISC;
hton24(fc_req->u.adisc.req.adisc_port_id, fc_host_port_id(shost));
ret = zfcp_fsf_send_els(adapter, port->d_id, &fc_req->ct_els,
ZFCP_FC_CTELS_TMO);
if (ret)
kmem_cache_free(zfcp_fc_req_cache, fc_req);
return ret;
}
void zfcp_fc_link_test_work(struct work_struct *work)
{
struct zfcp_port *port =
container_of(work, struct zfcp_port, test_link_work);
int retval;
get_device(&port->dev);
port->rport_task = RPORT_DEL;
zfcp_scsi_rport_work(&port->rport_work);
/* only issue one test command at one time per port */
if (atomic_read(&port->status) & ZFCP_STATUS_PORT_LINK_TEST)
goto out;
atomic_set_mask(ZFCP_STATUS_PORT_LINK_TEST, &port->status);
retval = zfcp_fc_adisc(port);
if (retval == 0)
return;
/* send of ADISC was not possible */
atomic_clear_mask(ZFCP_STATUS_PORT_LINK_TEST, &port->status);
zfcp_erp_port_forced_reopen(port, 0, "fcltwk1");
out:
put_device(&port->dev);
}
/**
* zfcp_fc_test_link - lightweight link test procedure
* @port: port to be tested
*
* Test status of a link to a remote port using the ELS command ADISC.
* If there is a problem with the remote port, error recovery steps
* will be triggered.
*/
void zfcp_fc_test_link(struct zfcp_port *port)
{
get_device(&port->dev);
if (!queue_work(port->adapter->work_queue, &port->test_link_work))
put_device(&port->dev);
}
static struct zfcp_fc_req *zfcp_alloc_sg_env(int buf_num)
{
struct zfcp_fc_req *fc_req;
fc_req = kmem_cache_zalloc(zfcp_fc_req_cache, GFP_KERNEL);
if (!fc_req)
return NULL;
if (zfcp_sg_setup_table(&fc_req->sg_rsp, buf_num)) {
kmem_cache_free(zfcp_fc_req_cache, fc_req);
return NULL;
}
sg_init_one(&fc_req->sg_req, &fc_req->u.gpn_ft.req,
sizeof(struct zfcp_fc_gpn_ft_req));
return fc_req;
}
static int zfcp_fc_send_gpn_ft(struct zfcp_fc_req *fc_req,
struct zfcp_adapter *adapter, int max_bytes)
{
struct zfcp_fsf_ct_els *ct_els = &fc_req->ct_els;
struct zfcp_fc_gpn_ft_req *req = &fc_req->u.gpn_ft.req;
DECLARE_COMPLETION_ONSTACK(completion);
int ret;
zfcp_fc_ct_ns_init(&req->ct_hdr, FC_NS_GPN_FT, max_bytes);
req->gpn_ft.fn_fc4_type = FC_TYPE_FCP;
ct_els->handler = zfcp_fc_complete;
ct_els->handler_data = &completion;
ct_els->req = &fc_req->sg_req;
ct_els->resp = &fc_req->sg_rsp;
ret = zfcp_fsf_send_ct(&adapter->gs->ds, ct_els, NULL,
ZFCP_FC_CTELS_TMO);
if (!ret)
wait_for_completion(&completion);
return ret;
}
static void zfcp_fc_validate_port(struct zfcp_port *port, struct list_head *lh)
{
if (!(atomic_read(&port->status) & ZFCP_STATUS_COMMON_NOESC))
return;
atomic_clear_mask(ZFCP_STATUS_COMMON_NOESC, &port->status);
if ((port->supported_classes != 0) ||
!list_empty(&port->unit_list))
return;
list_move_tail(&port->list, lh);
}
static int zfcp_fc_eval_gpn_ft(struct zfcp_fc_req *fc_req,
struct zfcp_adapter *adapter, int max_entries)
{
struct zfcp_fsf_ct_els *ct_els = &fc_req->ct_els;
struct scatterlist *sg = &fc_req->sg_rsp;
struct fc_ct_hdr *hdr = sg_virt(sg);
struct fc_gpn_ft_resp *acc = sg_virt(sg);
struct zfcp_port *port, *tmp;
unsigned long flags;
LIST_HEAD(remove_lh);
u32 d_id;
int ret = 0, x, last = 0;
if (ct_els->status)
return -EIO;
if (hdr->ct_cmd != FC_FS_ACC) {
if (hdr->ct_reason == FC_BA_RJT_UNABLE)
return -EAGAIN; /* might be a temporary condition */
return -EIO;
}
if (hdr->ct_mr_size) {
dev_warn(&adapter->ccw_device->dev,
"The name server reported %d words residual data\n",
hdr->ct_mr_size);
return -E2BIG;
}
/* first entry is the header */
for (x = 1; x < max_entries && !last; x++) {
if (x % (ZFCP_FC_GPN_FT_ENT_PAGE + 1))
acc++;
else
acc = sg_virt(++sg);
last = acc->fp_flags & FC_NS_FID_LAST;
d_id = ntoh24(acc->fp_fid);
/* don't attach ports with a well known address */
if (d_id >= FC_FID_WELL_KNOWN_BASE)
continue;
/* skip the adapter's port and known remote ports */
if (acc->fp_wwpn == fc_host_port_name(adapter->scsi_host))
continue;
port = zfcp_port_enqueue(adapter, acc->fp_wwpn,
ZFCP_STATUS_COMMON_NOESC, d_id);
if (!IS_ERR(port))
zfcp_erp_port_reopen(port, 0, "fcegpf1");
else if (PTR_ERR(port) != -EEXIST)
ret = PTR_ERR(port);
}
zfcp_erp_wait(adapter);
write_lock_irqsave(&adapter->port_list_lock, flags);
list_for_each_entry_safe(port, tmp, &adapter->port_list, list)
zfcp_fc_validate_port(port, &remove_lh);
write_unlock_irqrestore(&adapter->port_list_lock, flags);
list_for_each_entry_safe(port, tmp, &remove_lh, list) {
zfcp_erp_port_shutdown(port, 0, "fcegpf2");
zfcp_device_unregister(&port->dev, &zfcp_sysfs_port_attrs);
}
return ret;
}
/**
* zfcp_fc_scan_ports - scan remote ports and attach new ports
* @work: reference to scheduled work
*/
void zfcp_fc_scan_ports(struct work_struct *work)
{
struct zfcp_adapter *adapter = container_of(work, struct zfcp_adapter,
scan_work);
int ret, i;
struct zfcp_fc_req *fc_req;
int chain, max_entries, buf_num, max_bytes;
chain = adapter->adapter_features & FSF_FEATURE_ELS_CT_CHAINED_SBALS;
buf_num = chain ? ZFCP_FC_GPN_FT_NUM_BUFS : 1;
max_entries = chain ? ZFCP_FC_GPN_FT_MAX_ENT : ZFCP_FC_GPN_FT_ENT_PAGE;
max_bytes = chain ? ZFCP_FC_GPN_FT_MAX_SIZE : ZFCP_FC_CT_SIZE_PAGE;
if (fc_host_port_type(adapter->scsi_host) != FC_PORTTYPE_NPORT &&
fc_host_port_type(adapter->scsi_host) != FC_PORTTYPE_NPIV)
return;
if (zfcp_fc_wka_port_get(&adapter->gs->ds))
return;
fc_req = zfcp_alloc_sg_env(buf_num);
if (!fc_req)
goto out;
for (i = 0; i < 3; i++) {
ret = zfcp_fc_send_gpn_ft(fc_req, adapter, max_bytes);
if (!ret) {
ret = zfcp_fc_eval_gpn_ft(fc_req, adapter, max_entries);
if (ret == -EAGAIN)
ssleep(1);
else
break;
}
}
zfcp_sg_free_table(&fc_req->sg_rsp, buf_num);
kmem_cache_free(zfcp_fc_req_cache, fc_req);
out:
zfcp_fc_wka_port_put(&adapter->gs->ds);
}
static int zfcp_fc_gspn(struct zfcp_adapter *adapter,
struct zfcp_fc_req *fc_req)
{
DECLARE_COMPLETION_ONSTACK(completion);
char devno[] = "DEVNO:";
struct zfcp_fsf_ct_els *ct_els = &fc_req->ct_els;
struct zfcp_fc_gspn_req *gspn_req = &fc_req->u.gspn.req;
struct zfcp_fc_gspn_rsp *gspn_rsp = &fc_req->u.gspn.rsp;
int ret;
zfcp_fc_ct_ns_init(&gspn_req->ct_hdr, FC_NS_GSPN_ID,
FC_SYMBOLIC_NAME_SIZE);
hton24(gspn_req->gspn.fp_fid, fc_host_port_id(adapter->scsi_host));
sg_init_one(&fc_req->sg_req, gspn_req, sizeof(*gspn_req));
sg_init_one(&fc_req->sg_rsp, gspn_rsp, sizeof(*gspn_rsp));
ct_els->handler = zfcp_fc_complete;
ct_els->handler_data = &completion;
ct_els->req = &fc_req->sg_req;
ct_els->resp = &fc_req->sg_rsp;
ret = zfcp_fsf_send_ct(&adapter->gs->ds, ct_els, NULL,
ZFCP_FC_CTELS_TMO);
if (ret)
return ret;
wait_for_completion(&completion);
if (ct_els->status)
return ct_els->status;
if (fc_host_port_type(adapter->scsi_host) == FC_PORTTYPE_NPIV &&
!(strstr(gspn_rsp->gspn.fp_name, devno)))
snprintf(fc_host_symbolic_name(adapter->scsi_host),
FC_SYMBOLIC_NAME_SIZE, "%s%s %s NAME: %s",
gspn_rsp->gspn.fp_name, devno,
dev_name(&adapter->ccw_device->dev),
init_utsname()->nodename);
else
strlcpy(fc_host_symbolic_name(adapter->scsi_host),
gspn_rsp->gspn.fp_name, FC_SYMBOLIC_NAME_SIZE);
return 0;
}
static void zfcp_fc_rspn(struct zfcp_adapter *adapter,
struct zfcp_fc_req *fc_req)
{
DECLARE_COMPLETION_ONSTACK(completion);
struct Scsi_Host *shost = adapter->scsi_host;
struct zfcp_fsf_ct_els *ct_els = &fc_req->ct_els;
struct zfcp_fc_rspn_req *rspn_req = &fc_req->u.rspn.req;
struct fc_ct_hdr *rspn_rsp = &fc_req->u.rspn.rsp;
int ret, len;
zfcp_fc_ct_ns_init(&rspn_req->ct_hdr, FC_NS_RSPN_ID,
FC_SYMBOLIC_NAME_SIZE);
hton24(rspn_req->rspn.fr_fid.fp_fid, fc_host_port_id(shost));
len = strlcpy(rspn_req->rspn.fr_name, fc_host_symbolic_name(shost),
FC_SYMBOLIC_NAME_SIZE);
rspn_req->rspn.fr_name_len = len;
sg_init_one(&fc_req->sg_req, rspn_req, sizeof(*rspn_req));
sg_init_one(&fc_req->sg_rsp, rspn_rsp, sizeof(*rspn_rsp));
ct_els->handler = zfcp_fc_complete;
ct_els->handler_data = &completion;
ct_els->req = &fc_req->sg_req;
ct_els->resp = &fc_req->sg_rsp;
ret = zfcp_fsf_send_ct(&adapter->gs->ds, ct_els, NULL,
ZFCP_FC_CTELS_TMO);
if (!ret)
wait_for_completion(&completion);
}
/**
* zfcp_fc_sym_name_update - Retrieve and update the symbolic port name
* @work: ns_up_work of the adapter where to update the symbolic port name
*
* Retrieve the current symbolic port name that may have been set by
* the hardware using the GSPN request and update the fc_host
* symbolic_name sysfs attribute. When running in NPIV mode (and hence
* the port name is unique for this system), update the symbolic port
* name to add Linux specific information and update the FC nameserver
* using the RSPN request.
*/
void zfcp_fc_sym_name_update(struct work_struct *work)
{
struct zfcp_adapter *adapter = container_of(work, struct zfcp_adapter,
ns_up_work);
int ret;
struct zfcp_fc_req *fc_req;
if (fc_host_port_type(adapter->scsi_host) != FC_PORTTYPE_NPORT &&
fc_host_port_type(adapter->scsi_host) != FC_PORTTYPE_NPIV)
return;
fc_req = kmem_cache_zalloc(zfcp_fc_req_cache, GFP_KERNEL);
if (!fc_req)
return;
ret = zfcp_fc_wka_port_get(&adapter->gs->ds);
if (ret)
goto out_free;
ret = zfcp_fc_gspn(adapter, fc_req);
if (ret || fc_host_port_type(adapter->scsi_host) != FC_PORTTYPE_NPIV)
goto out_ds_put;
memset(fc_req, 0, sizeof(*fc_req));
zfcp_fc_rspn(adapter, fc_req);
out_ds_put:
zfcp_fc_wka_port_put(&adapter->gs->ds);
out_free:
kmem_cache_free(zfcp_fc_req_cache, fc_req);
}
static void zfcp_fc_ct_els_job_handler(void *data)
{
struct fc_bsg_job *job = data;
struct zfcp_fsf_ct_els *zfcp_ct_els = job->dd_data;
struct fc_bsg_reply *jr = job->reply;
jr->reply_payload_rcv_len = job->reply_payload.payload_len;
jr->reply_data.ctels_reply.status = FC_CTELS_STATUS_OK;
jr->result = zfcp_ct_els->status ? -EIO : 0;
job->job_done(job);
}
static struct zfcp_fc_wka_port *zfcp_fc_job_wka_port(struct fc_bsg_job *job)
{
u32 preamble_word1;
u8 gs_type;
struct zfcp_adapter *adapter;
preamble_word1 = job->request->rqst_data.r_ct.preamble_word1;
gs_type = (preamble_word1 & 0xff000000) >> 24;
adapter = (struct zfcp_adapter *) job->shost->hostdata[0];
switch (gs_type) {
case FC_FST_ALIAS:
return &adapter->gs->as;
case FC_FST_MGMT:
return &adapter->gs->ms;
case FC_FST_TIME:
return &adapter->gs->ts;
break;
case FC_FST_DIR:
return &adapter->gs->ds;
break;
default:
return NULL;
}
}
static void zfcp_fc_ct_job_handler(void *data)
{
struct fc_bsg_job *job = data;
struct zfcp_fc_wka_port *wka_port;
wka_port = zfcp_fc_job_wka_port(job);
zfcp_fc_wka_port_put(wka_port);
zfcp_fc_ct_els_job_handler(data);
}
static int zfcp_fc_exec_els_job(struct fc_bsg_job *job,
struct zfcp_adapter *adapter)
{
struct zfcp_fsf_ct_els *els = job->dd_data;
struct fc_rport *rport = job->rport;
struct zfcp_port *port;
u32 d_id;
if (rport) {
port = zfcp_get_port_by_wwpn(adapter, rport->port_name);
if (!port)
return -EINVAL;
d_id = port->d_id;
put_device(&port->dev);
} else
d_id = ntoh24(job->request->rqst_data.h_els.port_id);
els->handler = zfcp_fc_ct_els_job_handler;
return zfcp_fsf_send_els(adapter, d_id, els, job->req->timeout / HZ);
}
static int zfcp_fc_exec_ct_job(struct fc_bsg_job *job,
struct zfcp_adapter *adapter)
{
int ret;
struct zfcp_fsf_ct_els *ct = job->dd_data;
struct zfcp_fc_wka_port *wka_port;
wka_port = zfcp_fc_job_wka_port(job);
if (!wka_port)
return -EINVAL;
ret = zfcp_fc_wka_port_get(wka_port);
if (ret)
return ret;
ct->handler = zfcp_fc_ct_job_handler;
ret = zfcp_fsf_send_ct(wka_port, ct, NULL, job->req->timeout / HZ);
if (ret)
zfcp_fc_wka_port_put(wka_port);
return ret;
}
int zfcp_fc_exec_bsg_job(struct fc_bsg_job *job)
{
struct Scsi_Host *shost;
struct zfcp_adapter *adapter;
struct zfcp_fsf_ct_els *ct_els = job->dd_data;
shost = job->rport ? rport_to_shost(job->rport) : job->shost;
adapter = (struct zfcp_adapter *)shost->hostdata[0];
if (!(atomic_read(&adapter->status) & ZFCP_STATUS_COMMON_OPEN))
return -EINVAL;
ct_els->req = job->request_payload.sg_list;
ct_els->resp = job->reply_payload.sg_list;
ct_els->handler_data = job;
switch (job->request->msgcode) {
case FC_BSG_RPT_ELS:
case FC_BSG_HST_ELS_NOLOGIN:
return zfcp_fc_exec_els_job(job, adapter);
case FC_BSG_RPT_CT:
case FC_BSG_HST_CT:
return zfcp_fc_exec_ct_job(job, adapter);
default:
return -EINVAL;
}
}
int zfcp_fc_timeout_bsg_job(struct fc_bsg_job *job)
{
/* hardware tracks timeout, reset bsg timeout to not interfere */
return -EAGAIN;
}
int zfcp_fc_gs_setup(struct zfcp_adapter *adapter)
{
struct zfcp_fc_wka_ports *wka_ports;
wka_ports = kzalloc(sizeof(struct zfcp_fc_wka_ports), GFP_KERNEL);
if (!wka_ports)
return -ENOMEM;
adapter->gs = wka_ports;
zfcp_fc_wka_port_init(&wka_ports->ms, FC_FID_MGMT_SERV, adapter);
zfcp_fc_wka_port_init(&wka_ports->ts, FC_FID_TIME_SERV, adapter);
zfcp_fc_wka_port_init(&wka_ports->ds, FC_FID_DIR_SERV, adapter);
zfcp_fc_wka_port_init(&wka_ports->as, FC_FID_ALIASES, adapter);
return 0;
}
void zfcp_fc_gs_destroy(struct zfcp_adapter *adapter)
{
kfree(adapter->gs);
adapter->gs = NULL;
}
| gpl-2.0 |
CowboyEnvy/Android_Kernel_samsung_amazing3gcri | sound/pci/pcxhr/pcxhr_core.c | 8034 | 37111 | /*
* Driver for Digigram pcxhr compatible soundcards
*
* low level interface with interrupt and message handling implementation
*
* Copyright (c) 2004 by Digigram <alsa@digigram.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/delay.h>
#include <linux/firmware.h>
#include <linux/interrupt.h>
#include <asm/io.h>
#include <sound/core.h>
#include "pcxhr.h"
#include "pcxhr_mixer.h"
#include "pcxhr_hwdep.h"
#include "pcxhr_core.h"
/* registers used on the PLX (port 1) */
#define PCXHR_PLX_OFFSET_MIN 0x40
#define PCXHR_PLX_MBOX0 0x40
#define PCXHR_PLX_MBOX1 0x44
#define PCXHR_PLX_MBOX2 0x48
#define PCXHR_PLX_MBOX3 0x4C
#define PCXHR_PLX_MBOX4 0x50
#define PCXHR_PLX_MBOX5 0x54
#define PCXHR_PLX_MBOX6 0x58
#define PCXHR_PLX_MBOX7 0x5C
#define PCXHR_PLX_L2PCIDB 0x64
#define PCXHR_PLX_IRQCS 0x68
#define PCXHR_PLX_CHIPSC 0x6C
/* registers used on the DSP (port 2) */
#define PCXHR_DSP_ICR 0x00
#define PCXHR_DSP_CVR 0x04
#define PCXHR_DSP_ISR 0x08
#define PCXHR_DSP_IVR 0x0C
#define PCXHR_DSP_RXH 0x14
#define PCXHR_DSP_TXH 0x14
#define PCXHR_DSP_RXM 0x18
#define PCXHR_DSP_TXM 0x18
#define PCXHR_DSP_RXL 0x1C
#define PCXHR_DSP_TXL 0x1C
#define PCXHR_DSP_RESET 0x20
#define PCXHR_DSP_OFFSET_MAX 0x20
/* access to the card */
#define PCXHR_PLX 1
#define PCXHR_DSP 2
#if (PCXHR_DSP_OFFSET_MAX > PCXHR_PLX_OFFSET_MIN)
#undef PCXHR_REG_TO_PORT(x)
#else
#define PCXHR_REG_TO_PORT(x) ((x)>PCXHR_DSP_OFFSET_MAX ? PCXHR_PLX : PCXHR_DSP)
#endif
#define PCXHR_INPB(mgr,x) inb((mgr)->port[PCXHR_REG_TO_PORT(x)] + (x))
#define PCXHR_INPL(mgr,x) inl((mgr)->port[PCXHR_REG_TO_PORT(x)] + (x))
#define PCXHR_OUTPB(mgr,x,data) outb((data), (mgr)->port[PCXHR_REG_TO_PORT(x)] + (x))
#define PCXHR_OUTPL(mgr,x,data) outl((data), (mgr)->port[PCXHR_REG_TO_PORT(x)] + (x))
/* attention : access the PCXHR_DSP_* registers with inb and outb only ! */
/* params used with PCXHR_PLX_MBOX0 */
#define PCXHR_MBOX0_HF5 (1 << 0)
#define PCXHR_MBOX0_HF4 (1 << 1)
#define PCXHR_MBOX0_BOOT_HERE (1 << 23)
/* params used with PCXHR_PLX_IRQCS */
#define PCXHR_IRQCS_ENABLE_PCIIRQ (1 << 8)
#define PCXHR_IRQCS_ENABLE_PCIDB (1 << 9)
#define PCXHR_IRQCS_ACTIVE_PCIDB (1 << 13)
/* params used with PCXHR_PLX_CHIPSC */
#define PCXHR_CHIPSC_INIT_VALUE 0x100D767E
#define PCXHR_CHIPSC_RESET_XILINX (1 << 16)
#define PCXHR_CHIPSC_GPI_USERI (1 << 17)
#define PCXHR_CHIPSC_DATA_CLK (1 << 24)
#define PCXHR_CHIPSC_DATA_IN (1 << 26)
/* params used with PCXHR_DSP_ICR */
#define PCXHR_ICR_HI08_RREQ 0x01
#define PCXHR_ICR_HI08_TREQ 0x02
#define PCXHR_ICR_HI08_HDRQ 0x04
#define PCXHR_ICR_HI08_HF0 0x08
#define PCXHR_ICR_HI08_HF1 0x10
#define PCXHR_ICR_HI08_HLEND 0x20
#define PCXHR_ICR_HI08_INIT 0x80
/* params used with PCXHR_DSP_CVR */
#define PCXHR_CVR_HI08_HC 0x80
/* params used with PCXHR_DSP_ISR */
#define PCXHR_ISR_HI08_RXDF 0x01
#define PCXHR_ISR_HI08_TXDE 0x02
#define PCXHR_ISR_HI08_TRDY 0x04
#define PCXHR_ISR_HI08_ERR 0x08
#define PCXHR_ISR_HI08_CHK 0x10
#define PCXHR_ISR_HI08_HREQ 0x80
/* constants used for delay in msec */
#define PCXHR_WAIT_DEFAULT 2
#define PCXHR_WAIT_IT 25
#define PCXHR_WAIT_IT_EXTRA 65
/*
* pcxhr_check_reg_bit - wait for the specified bit is set/reset on a register
* @reg: register to check
* @mask: bit mask
* @bit: resultant bit to be checked
* @time: time-out of loop in msec
*
* returns zero if a bit matches, or a negative error code.
*/
static int pcxhr_check_reg_bit(struct pcxhr_mgr *mgr, unsigned int reg,
unsigned char mask, unsigned char bit, int time,
unsigned char* read)
{
int i = 0;
unsigned long end_time = jiffies + (time * HZ + 999) / 1000;
do {
*read = PCXHR_INPB(mgr, reg);
if ((*read & mask) == bit) {
if (i > 100)
snd_printdd("ATTENTION! check_reg(%x) "
"loopcount=%d\n",
reg, i);
return 0;
}
i++;
} while (time_after_eq(end_time, jiffies));
snd_printk(KERN_ERR
"pcxhr_check_reg_bit: timeout, reg=%x, mask=0x%x, val=%x\n",
reg, mask, *read);
return -EIO;
}
/* constants used with pcxhr_check_reg_bit() */
#define PCXHR_TIMEOUT_DSP 200
#define PCXHR_MASK_EXTRA_INFO 0x0000FE
#define PCXHR_MASK_IT_HF0 0x000100
#define PCXHR_MASK_IT_HF1 0x000200
#define PCXHR_MASK_IT_NO_HF0_HF1 0x000400
#define PCXHR_MASK_IT_MANAGE_HF5 0x000800
#define PCXHR_MASK_IT_WAIT 0x010000
#define PCXHR_MASK_IT_WAIT_EXTRA 0x020000
#define PCXHR_IT_SEND_BYTE_XILINX (0x0000003C | PCXHR_MASK_IT_HF0)
#define PCXHR_IT_TEST_XILINX (0x0000003C | PCXHR_MASK_IT_HF1 | \
PCXHR_MASK_IT_MANAGE_HF5)
#define PCXHR_IT_DOWNLOAD_BOOT (0x0000000C | PCXHR_MASK_IT_HF1 | \
PCXHR_MASK_IT_MANAGE_HF5 | \
PCXHR_MASK_IT_WAIT)
#define PCXHR_IT_RESET_BOARD_FUNC (0x0000000C | PCXHR_MASK_IT_HF0 | \
PCXHR_MASK_IT_MANAGE_HF5 | \
PCXHR_MASK_IT_WAIT_EXTRA)
#define PCXHR_IT_DOWNLOAD_DSP (0x0000000C | \
PCXHR_MASK_IT_MANAGE_HF5 | \
PCXHR_MASK_IT_WAIT)
#define PCXHR_IT_DEBUG (0x0000005A | PCXHR_MASK_IT_NO_HF0_HF1)
#define PCXHR_IT_RESET_SEMAPHORE (0x0000005C | PCXHR_MASK_IT_NO_HF0_HF1)
#define PCXHR_IT_MESSAGE (0x00000074 | PCXHR_MASK_IT_NO_HF0_HF1)
#define PCXHR_IT_RESET_CHK (0x00000076 | PCXHR_MASK_IT_NO_HF0_HF1)
#define PCXHR_IT_UPDATE_RBUFFER (0x00000078 | PCXHR_MASK_IT_NO_HF0_HF1)
static int pcxhr_send_it_dsp(struct pcxhr_mgr *mgr,
unsigned int itdsp, int atomic)
{
int err;
unsigned char reg;
if (itdsp & PCXHR_MASK_IT_MANAGE_HF5) {
/* clear hf5 bit */
PCXHR_OUTPL(mgr, PCXHR_PLX_MBOX0,
PCXHR_INPL(mgr, PCXHR_PLX_MBOX0) &
~PCXHR_MBOX0_HF5);
}
if ((itdsp & PCXHR_MASK_IT_NO_HF0_HF1) == 0) {
reg = (PCXHR_ICR_HI08_RREQ |
PCXHR_ICR_HI08_TREQ |
PCXHR_ICR_HI08_HDRQ);
if (itdsp & PCXHR_MASK_IT_HF0)
reg |= PCXHR_ICR_HI08_HF0;
if (itdsp & PCXHR_MASK_IT_HF1)
reg |= PCXHR_ICR_HI08_HF1;
PCXHR_OUTPB(mgr, PCXHR_DSP_ICR, reg);
}
reg = (unsigned char)(((itdsp & PCXHR_MASK_EXTRA_INFO) >> 1) |
PCXHR_CVR_HI08_HC);
PCXHR_OUTPB(mgr, PCXHR_DSP_CVR, reg);
if (itdsp & PCXHR_MASK_IT_WAIT) {
if (atomic)
mdelay(PCXHR_WAIT_IT);
else
msleep(PCXHR_WAIT_IT);
}
if (itdsp & PCXHR_MASK_IT_WAIT_EXTRA) {
if (atomic)
mdelay(PCXHR_WAIT_IT_EXTRA);
else
msleep(PCXHR_WAIT_IT);
}
/* wait for CVR_HI08_HC == 0 */
err = pcxhr_check_reg_bit(mgr, PCXHR_DSP_CVR, PCXHR_CVR_HI08_HC, 0,
PCXHR_TIMEOUT_DSP, ®);
if (err) {
snd_printk(KERN_ERR "pcxhr_send_it_dsp : TIMEOUT CVR\n");
return err;
}
if (itdsp & PCXHR_MASK_IT_MANAGE_HF5) {
/* wait for hf5 bit */
err = pcxhr_check_reg_bit(mgr, PCXHR_PLX_MBOX0,
PCXHR_MBOX0_HF5,
PCXHR_MBOX0_HF5,
PCXHR_TIMEOUT_DSP,
®);
if (err) {
snd_printk(KERN_ERR
"pcxhr_send_it_dsp : TIMEOUT HF5\n");
return err;
}
}
return 0; /* retry not handled here */
}
void pcxhr_reset_xilinx_com(struct pcxhr_mgr *mgr)
{
/* reset second xilinx */
PCXHR_OUTPL(mgr, PCXHR_PLX_CHIPSC,
PCXHR_CHIPSC_INIT_VALUE & ~PCXHR_CHIPSC_RESET_XILINX);
}
static void pcxhr_enable_irq(struct pcxhr_mgr *mgr, int enable)
{
unsigned int reg = PCXHR_INPL(mgr, PCXHR_PLX_IRQCS);
/* enable/disable interrupts */
if (enable)
reg |= (PCXHR_IRQCS_ENABLE_PCIIRQ | PCXHR_IRQCS_ENABLE_PCIDB);
else
reg &= ~(PCXHR_IRQCS_ENABLE_PCIIRQ | PCXHR_IRQCS_ENABLE_PCIDB);
PCXHR_OUTPL(mgr, PCXHR_PLX_IRQCS, reg);
}
void pcxhr_reset_dsp(struct pcxhr_mgr *mgr)
{
/* disable interrupts */
pcxhr_enable_irq(mgr, 0);
/* let's reset the DSP */
PCXHR_OUTPB(mgr, PCXHR_DSP_RESET, 0);
msleep( PCXHR_WAIT_DEFAULT ); /* wait 2 msec */
PCXHR_OUTPB(mgr, PCXHR_DSP_RESET, 3);
msleep( PCXHR_WAIT_DEFAULT ); /* wait 2 msec */
/* reset mailbox */
PCXHR_OUTPL(mgr, PCXHR_PLX_MBOX0, 0);
}
void pcxhr_enable_dsp(struct pcxhr_mgr *mgr)
{
/* enable interrupts */
pcxhr_enable_irq(mgr, 1);
}
/*
* load the xilinx image
*/
int pcxhr_load_xilinx_binary(struct pcxhr_mgr *mgr,
const struct firmware *xilinx, int second)
{
unsigned int i;
unsigned int chipsc;
unsigned char data;
unsigned char mask;
const unsigned char *image;
/* test first xilinx */
chipsc = PCXHR_INPL(mgr, PCXHR_PLX_CHIPSC);
/* REV01 cards do not support the PCXHR_CHIPSC_GPI_USERI bit anymore */
/* this bit will always be 1;
* no possibility to test presence of first xilinx
*/
if(second) {
if ((chipsc & PCXHR_CHIPSC_GPI_USERI) == 0) {
snd_printk(KERN_ERR "error loading first xilinx\n");
return -EINVAL;
}
/* activate second xilinx */
chipsc |= PCXHR_CHIPSC_RESET_XILINX;
PCXHR_OUTPL(mgr, PCXHR_PLX_CHIPSC, chipsc);
msleep( PCXHR_WAIT_DEFAULT ); /* wait 2 msec */
}
image = xilinx->data;
for (i = 0; i < xilinx->size; i++, image++) {
data = *image;
mask = 0x80;
while (mask) {
chipsc &= ~(PCXHR_CHIPSC_DATA_CLK |
PCXHR_CHIPSC_DATA_IN);
if (data & mask)
chipsc |= PCXHR_CHIPSC_DATA_IN;
PCXHR_OUTPL(mgr, PCXHR_PLX_CHIPSC, chipsc);
chipsc |= PCXHR_CHIPSC_DATA_CLK;
PCXHR_OUTPL(mgr, PCXHR_PLX_CHIPSC, chipsc);
mask >>= 1;
}
/* don't take too much time in this loop... */
cond_resched();
}
chipsc &= ~(PCXHR_CHIPSC_DATA_CLK | PCXHR_CHIPSC_DATA_IN);
PCXHR_OUTPL(mgr, PCXHR_PLX_CHIPSC, chipsc);
/* wait 2 msec (time to boot the xilinx before any access) */
msleep( PCXHR_WAIT_DEFAULT );
return 0;
}
/*
* send an executable file to the DSP
*/
static int pcxhr_download_dsp(struct pcxhr_mgr *mgr, const struct firmware *dsp)
{
int err;
unsigned int i;
unsigned int len;
const unsigned char *data;
unsigned char dummy;
/* check the length of boot image */
if (dsp->size <= 0)
return -EINVAL;
if (dsp->size % 3)
return -EINVAL;
if (snd_BUG_ON(!dsp->data))
return -EINVAL;
/* transfert data buffer from PC to DSP */
for (i = 0; i < dsp->size; i += 3) {
data = dsp->data + i;
if (i == 0) {
/* test data header consistency */
len = (unsigned int)((data[0]<<16) +
(data[1]<<8) +
data[2]);
if (len && (dsp->size != (len + 2) * 3))
return -EINVAL;
}
/* wait DSP ready for new transfer */
err = pcxhr_check_reg_bit(mgr, PCXHR_DSP_ISR,
PCXHR_ISR_HI08_TRDY,
PCXHR_ISR_HI08_TRDY,
PCXHR_TIMEOUT_DSP, &dummy);
if (err) {
snd_printk(KERN_ERR
"dsp loading error at position %d\n", i);
return err;
}
/* send host data */
PCXHR_OUTPB(mgr, PCXHR_DSP_TXH, data[0]);
PCXHR_OUTPB(mgr, PCXHR_DSP_TXM, data[1]);
PCXHR_OUTPB(mgr, PCXHR_DSP_TXL, data[2]);
/* don't take too much time in this loop... */
cond_resched();
}
/* give some time to boot the DSP */
msleep(PCXHR_WAIT_DEFAULT);
return 0;
}
/*
* load the eeprom image
*/
int pcxhr_load_eeprom_binary(struct pcxhr_mgr *mgr,
const struct firmware *eeprom)
{
int err;
unsigned char reg;
/* init value of the ICR register */
reg = PCXHR_ICR_HI08_RREQ | PCXHR_ICR_HI08_TREQ | PCXHR_ICR_HI08_HDRQ;
if (PCXHR_INPL(mgr, PCXHR_PLX_MBOX0) & PCXHR_MBOX0_BOOT_HERE) {
/* no need to load the eeprom binary,
* but init the HI08 interface
*/
PCXHR_OUTPB(mgr, PCXHR_DSP_ICR, reg | PCXHR_ICR_HI08_INIT);
msleep(PCXHR_WAIT_DEFAULT);
PCXHR_OUTPB(mgr, PCXHR_DSP_ICR, reg);
msleep(PCXHR_WAIT_DEFAULT);
snd_printdd("no need to load eeprom boot\n");
return 0;
}
PCXHR_OUTPB(mgr, PCXHR_DSP_ICR, reg);
err = pcxhr_download_dsp(mgr, eeprom);
if (err)
return err;
/* wait for chk bit */
return pcxhr_check_reg_bit(mgr, PCXHR_DSP_ISR, PCXHR_ISR_HI08_CHK,
PCXHR_ISR_HI08_CHK, PCXHR_TIMEOUT_DSP, ®);
}
/*
* load the boot image
*/
int pcxhr_load_boot_binary(struct pcxhr_mgr *mgr, const struct firmware *boot)
{
int err;
unsigned int physaddr = mgr->hostport.addr;
unsigned char dummy;
/* send the hostport address to the DSP (only the upper 24 bit !) */
if (snd_BUG_ON(physaddr & 0xff))
return -EINVAL;
PCXHR_OUTPL(mgr, PCXHR_PLX_MBOX1, (physaddr >> 8));
err = pcxhr_send_it_dsp(mgr, PCXHR_IT_DOWNLOAD_BOOT, 0);
if (err)
return err;
/* clear hf5 bit */
PCXHR_OUTPL(mgr, PCXHR_PLX_MBOX0,
PCXHR_INPL(mgr, PCXHR_PLX_MBOX0) & ~PCXHR_MBOX0_HF5);
err = pcxhr_download_dsp(mgr, boot);
if (err)
return err;
/* wait for hf5 bit */
return pcxhr_check_reg_bit(mgr, PCXHR_PLX_MBOX0, PCXHR_MBOX0_HF5,
PCXHR_MBOX0_HF5, PCXHR_TIMEOUT_DSP, &dummy);
}
/*
* load the final dsp image
*/
int pcxhr_load_dsp_binary(struct pcxhr_mgr *mgr, const struct firmware *dsp)
{
int err;
unsigned char dummy;
err = pcxhr_send_it_dsp(mgr, PCXHR_IT_RESET_BOARD_FUNC, 0);
if (err)
return err;
err = pcxhr_send_it_dsp(mgr, PCXHR_IT_DOWNLOAD_DSP, 0);
if (err)
return err;
err = pcxhr_download_dsp(mgr, dsp);
if (err)
return err;
/* wait for chk bit */
return pcxhr_check_reg_bit(mgr, PCXHR_DSP_ISR,
PCXHR_ISR_HI08_CHK,
PCXHR_ISR_HI08_CHK,
PCXHR_TIMEOUT_DSP, &dummy);
}
struct pcxhr_cmd_info {
u32 opcode; /* command word */
u16 st_length; /* status length */
u16 st_type; /* status type (RMH_SSIZE_XXX) */
};
/* RMH status type */
enum {
RMH_SSIZE_FIXED = 0, /* status size fix (st_length = 0..x) */
RMH_SSIZE_ARG = 1, /* status size given in the LSB byte */
RMH_SSIZE_MASK = 2, /* status size given in bitmask */
};
/*
* Array of DSP commands
*/
static struct pcxhr_cmd_info pcxhr_dsp_cmds[] = {
[CMD_VERSION] = { 0x010000, 1, RMH_SSIZE_FIXED },
[CMD_SUPPORTED] = { 0x020000, 4, RMH_SSIZE_FIXED },
[CMD_TEST_IT] = { 0x040000, 1, RMH_SSIZE_FIXED },
[CMD_SEND_IRQA] = { 0x070001, 0, RMH_SSIZE_FIXED },
[CMD_ACCESS_IO_WRITE] = { 0x090000, 1, RMH_SSIZE_ARG },
[CMD_ACCESS_IO_READ] = { 0x094000, 1, RMH_SSIZE_ARG },
[CMD_ASYNC] = { 0x0a0000, 1, RMH_SSIZE_ARG },
[CMD_MODIFY_CLOCK] = { 0x0d0000, 0, RMH_SSIZE_FIXED },
[CMD_RESYNC_AUDIO_INPUTS] = { 0x0e0000, 0, RMH_SSIZE_FIXED },
[CMD_GET_DSP_RESOURCES] = { 0x100000, 4, RMH_SSIZE_FIXED },
[CMD_SET_TIMER_INTERRUPT] = { 0x110000, 0, RMH_SSIZE_FIXED },
[CMD_RES_PIPE] = { 0x400000, 0, RMH_SSIZE_FIXED },
[CMD_FREE_PIPE] = { 0x410000, 0, RMH_SSIZE_FIXED },
[CMD_CONF_PIPE] = { 0x422101, 0, RMH_SSIZE_FIXED },
[CMD_STOP_PIPE] = { 0x470004, 0, RMH_SSIZE_FIXED },
[CMD_PIPE_SAMPLE_COUNT] = { 0x49a000, 2, RMH_SSIZE_FIXED },
[CMD_CAN_START_PIPE] = { 0x4b0000, 1, RMH_SSIZE_FIXED },
[CMD_START_STREAM] = { 0x802000, 0, RMH_SSIZE_FIXED },
[CMD_STREAM_OUT_LEVEL_ADJUST] = { 0x822000, 0, RMH_SSIZE_FIXED },
[CMD_STOP_STREAM] = { 0x832000, 0, RMH_SSIZE_FIXED },
[CMD_UPDATE_R_BUFFERS] = { 0x840000, 0, RMH_SSIZE_FIXED },
[CMD_FORMAT_STREAM_OUT] = { 0x860000, 0, RMH_SSIZE_FIXED },
[CMD_FORMAT_STREAM_IN] = { 0x870000, 0, RMH_SSIZE_FIXED },
[CMD_STREAM_SAMPLE_COUNT] = { 0x902000, 2, RMH_SSIZE_FIXED },
[CMD_AUDIO_LEVEL_ADJUST] = { 0xc22000, 0, RMH_SSIZE_FIXED },
};
#ifdef CONFIG_SND_DEBUG_VERBOSE
static char* cmd_names[] = {
[CMD_VERSION] = "CMD_VERSION",
[CMD_SUPPORTED] = "CMD_SUPPORTED",
[CMD_TEST_IT] = "CMD_TEST_IT",
[CMD_SEND_IRQA] = "CMD_SEND_IRQA",
[CMD_ACCESS_IO_WRITE] = "CMD_ACCESS_IO_WRITE",
[CMD_ACCESS_IO_READ] = "CMD_ACCESS_IO_READ",
[CMD_ASYNC] = "CMD_ASYNC",
[CMD_MODIFY_CLOCK] = "CMD_MODIFY_CLOCK",
[CMD_RESYNC_AUDIO_INPUTS] = "CMD_RESYNC_AUDIO_INPUTS",
[CMD_GET_DSP_RESOURCES] = "CMD_GET_DSP_RESOURCES",
[CMD_SET_TIMER_INTERRUPT] = "CMD_SET_TIMER_INTERRUPT",
[CMD_RES_PIPE] = "CMD_RES_PIPE",
[CMD_FREE_PIPE] = "CMD_FREE_PIPE",
[CMD_CONF_PIPE] = "CMD_CONF_PIPE",
[CMD_STOP_PIPE] = "CMD_STOP_PIPE",
[CMD_PIPE_SAMPLE_COUNT] = "CMD_PIPE_SAMPLE_COUNT",
[CMD_CAN_START_PIPE] = "CMD_CAN_START_PIPE",
[CMD_START_STREAM] = "CMD_START_STREAM",
[CMD_STREAM_OUT_LEVEL_ADJUST] = "CMD_STREAM_OUT_LEVEL_ADJUST",
[CMD_STOP_STREAM] = "CMD_STOP_STREAM",
[CMD_UPDATE_R_BUFFERS] = "CMD_UPDATE_R_BUFFERS",
[CMD_FORMAT_STREAM_OUT] = "CMD_FORMAT_STREAM_OUT",
[CMD_FORMAT_STREAM_IN] = "CMD_FORMAT_STREAM_IN",
[CMD_STREAM_SAMPLE_COUNT] = "CMD_STREAM_SAMPLE_COUNT",
[CMD_AUDIO_LEVEL_ADJUST] = "CMD_AUDIO_LEVEL_ADJUST",
};
#endif
static int pcxhr_read_rmh_status(struct pcxhr_mgr *mgr, struct pcxhr_rmh *rmh)
{
int err;
int i;
u32 data;
u32 size_mask;
unsigned char reg;
int max_stat_len;
if (rmh->stat_len < PCXHR_SIZE_MAX_STATUS)
max_stat_len = PCXHR_SIZE_MAX_STATUS;
else max_stat_len = rmh->stat_len;
for (i = 0; i < rmh->stat_len; i++) {
/* wait for receiver full */
err = pcxhr_check_reg_bit(mgr, PCXHR_DSP_ISR,
PCXHR_ISR_HI08_RXDF,
PCXHR_ISR_HI08_RXDF,
PCXHR_TIMEOUT_DSP, ®);
if (err) {
snd_printk(KERN_ERR "ERROR RMH stat: "
"ISR:RXDF=1 (ISR = %x; i=%d )\n",
reg, i);
return err;
}
/* read data */
data = PCXHR_INPB(mgr, PCXHR_DSP_TXH) << 16;
data |= PCXHR_INPB(mgr, PCXHR_DSP_TXM) << 8;
data |= PCXHR_INPB(mgr, PCXHR_DSP_TXL);
/* need to update rmh->stat_len on the fly ?? */
if (!i) {
if (rmh->dsp_stat != RMH_SSIZE_FIXED) {
if (rmh->dsp_stat == RMH_SSIZE_ARG) {
rmh->stat_len = (data & 0x0000ff) + 1;
data &= 0xffff00;
} else {
/* rmh->dsp_stat == RMH_SSIZE_MASK */
rmh->stat_len = 1;
size_mask = data;
while (size_mask) {
if (size_mask & 1)
rmh->stat_len++;
size_mask >>= 1;
}
}
}
}
#ifdef CONFIG_SND_DEBUG_VERBOSE
if (rmh->cmd_idx < CMD_LAST_INDEX)
snd_printdd(" stat[%d]=%x\n", i, data);
#endif
if (i < max_stat_len)
rmh->stat[i] = data;
}
if (rmh->stat_len > max_stat_len) {
snd_printdd("PCXHR : rmh->stat_len=%x too big\n",
rmh->stat_len);
rmh->stat_len = max_stat_len;
}
return 0;
}
static int pcxhr_send_msg_nolock(struct pcxhr_mgr *mgr, struct pcxhr_rmh *rmh)
{
int err;
int i;
u32 data;
unsigned char reg;
if (snd_BUG_ON(rmh->cmd_len >= PCXHR_SIZE_MAX_CMD))
return -EINVAL;
err = pcxhr_send_it_dsp(mgr, PCXHR_IT_MESSAGE, 1);
if (err) {
snd_printk(KERN_ERR "pcxhr_send_message : ED_DSP_CRASHED\n");
return err;
}
/* wait for chk bit */
err = pcxhr_check_reg_bit(mgr, PCXHR_DSP_ISR, PCXHR_ISR_HI08_CHK,
PCXHR_ISR_HI08_CHK, PCXHR_TIMEOUT_DSP, ®);
if (err)
return err;
/* reset irq chk */
err = pcxhr_send_it_dsp(mgr, PCXHR_IT_RESET_CHK, 1);
if (err)
return err;
/* wait for chk bit == 0*/
err = pcxhr_check_reg_bit(mgr, PCXHR_DSP_ISR, PCXHR_ISR_HI08_CHK, 0,
PCXHR_TIMEOUT_DSP, ®);
if (err)
return err;
data = rmh->cmd[0];
if (rmh->cmd_len > 1)
data |= 0x008000; /* MASK_MORE_THAN_1_WORD_COMMAND */
else
data &= 0xff7fff; /* MASK_1_WORD_COMMAND */
#ifdef CONFIG_SND_DEBUG_VERBOSE
if (rmh->cmd_idx < CMD_LAST_INDEX)
snd_printdd("MSG cmd[0]=%x (%s)\n",
data, cmd_names[rmh->cmd_idx]);
#endif
err = pcxhr_check_reg_bit(mgr, PCXHR_DSP_ISR, PCXHR_ISR_HI08_TRDY,
PCXHR_ISR_HI08_TRDY, PCXHR_TIMEOUT_DSP, ®);
if (err)
return err;
PCXHR_OUTPB(mgr, PCXHR_DSP_TXH, (data>>16)&0xFF);
PCXHR_OUTPB(mgr, PCXHR_DSP_TXM, (data>>8)&0xFF);
PCXHR_OUTPB(mgr, PCXHR_DSP_TXL, (data&0xFF));
if (rmh->cmd_len > 1) {
/* send length */
data = rmh->cmd_len - 1;
err = pcxhr_check_reg_bit(mgr, PCXHR_DSP_ISR,
PCXHR_ISR_HI08_TRDY,
PCXHR_ISR_HI08_TRDY,
PCXHR_TIMEOUT_DSP, ®);
if (err)
return err;
PCXHR_OUTPB(mgr, PCXHR_DSP_TXH, (data>>16)&0xFF);
PCXHR_OUTPB(mgr, PCXHR_DSP_TXM, (data>>8)&0xFF);
PCXHR_OUTPB(mgr, PCXHR_DSP_TXL, (data&0xFF));
for (i=1; i < rmh->cmd_len; i++) {
/* send other words */
data = rmh->cmd[i];
#ifdef CONFIG_SND_DEBUG_VERBOSE
if (rmh->cmd_idx < CMD_LAST_INDEX)
snd_printdd(" cmd[%d]=%x\n", i, data);
#endif
err = pcxhr_check_reg_bit(mgr, PCXHR_DSP_ISR,
PCXHR_ISR_HI08_TRDY,
PCXHR_ISR_HI08_TRDY,
PCXHR_TIMEOUT_DSP, ®);
if (err)
return err;
PCXHR_OUTPB(mgr, PCXHR_DSP_TXH, (data>>16)&0xFF);
PCXHR_OUTPB(mgr, PCXHR_DSP_TXM, (data>>8)&0xFF);
PCXHR_OUTPB(mgr, PCXHR_DSP_TXL, (data&0xFF));
}
}
/* wait for chk bit */
err = pcxhr_check_reg_bit(mgr, PCXHR_DSP_ISR, PCXHR_ISR_HI08_CHK,
PCXHR_ISR_HI08_CHK, PCXHR_TIMEOUT_DSP, ®);
if (err)
return err;
/* test status ISR */
if (reg & PCXHR_ISR_HI08_ERR) {
/* ERROR, wait for receiver full */
err = pcxhr_check_reg_bit(mgr, PCXHR_DSP_ISR,
PCXHR_ISR_HI08_RXDF,
PCXHR_ISR_HI08_RXDF,
PCXHR_TIMEOUT_DSP, ®);
if (err) {
snd_printk(KERN_ERR "ERROR RMH: ISR:RXDF=1 (ISR = %x)\n", reg);
return err;
}
/* read error code */
data = PCXHR_INPB(mgr, PCXHR_DSP_TXH) << 16;
data |= PCXHR_INPB(mgr, PCXHR_DSP_TXM) << 8;
data |= PCXHR_INPB(mgr, PCXHR_DSP_TXL);
snd_printk(KERN_ERR "ERROR RMH(%d): 0x%x\n",
rmh->cmd_idx, data);
err = -EINVAL;
} else {
/* read the response data */
err = pcxhr_read_rmh_status(mgr, rmh);
}
/* reset semaphore */
if (pcxhr_send_it_dsp(mgr, PCXHR_IT_RESET_SEMAPHORE, 1) < 0)
return -EIO;
return err;
}
/**
* pcxhr_init_rmh - initialize the RMH instance
* @rmh: the rmh pointer to be initialized
* @cmd: the rmh command to be set
*/
void pcxhr_init_rmh(struct pcxhr_rmh *rmh, int cmd)
{
if (snd_BUG_ON(cmd >= CMD_LAST_INDEX))
return;
rmh->cmd[0] = pcxhr_dsp_cmds[cmd].opcode;
rmh->cmd_len = 1;
rmh->stat_len = pcxhr_dsp_cmds[cmd].st_length;
rmh->dsp_stat = pcxhr_dsp_cmds[cmd].st_type;
rmh->cmd_idx = cmd;
}
void pcxhr_set_pipe_cmd_params(struct pcxhr_rmh *rmh, int capture,
unsigned int param1, unsigned int param2,
unsigned int param3)
{
snd_BUG_ON(param1 > MASK_FIRST_FIELD);
if (capture)
rmh->cmd[0] |= 0x800; /* COMMAND_RECORD_MASK */
if (param1)
rmh->cmd[0] |= (param1 << FIELD_SIZE);
if (param2) {
snd_BUG_ON(param2 > MASK_FIRST_FIELD);
rmh->cmd[0] |= param2;
}
if(param3) {
snd_BUG_ON(param3 > MASK_DSP_WORD);
rmh->cmd[1] = param3;
rmh->cmd_len = 2;
}
}
/*
* pcxhr_send_msg - send a DSP message with spinlock
* @rmh: the rmh record to send and receive
*
* returns 0 if successful, or a negative error code.
*/
int pcxhr_send_msg(struct pcxhr_mgr *mgr, struct pcxhr_rmh *rmh)
{
unsigned long flags;
int err;
spin_lock_irqsave(&mgr->msg_lock, flags);
err = pcxhr_send_msg_nolock(mgr, rmh);
spin_unlock_irqrestore(&mgr->msg_lock, flags);
return err;
}
static inline int pcxhr_pipes_running(struct pcxhr_mgr *mgr)
{
int start_mask = PCXHR_INPL(mgr, PCXHR_PLX_MBOX2);
/* least segnificant 12 bits are the pipe states
* for the playback audios
* next 12 bits are the pipe states for the capture audios
* (PCXHR_PIPE_STATE_CAPTURE_OFFSET)
*/
start_mask &= 0xffffff;
snd_printdd("CMD_PIPE_STATE MBOX2=0x%06x\n", start_mask);
return start_mask;
}
#define PCXHR_PIPE_STATE_CAPTURE_OFFSET 12
#define MAX_WAIT_FOR_DSP 20
static int pcxhr_prepair_pipe_start(struct pcxhr_mgr *mgr,
int audio_mask, int *retry)
{
struct pcxhr_rmh rmh;
int err;
int audio = 0;
*retry = 0;
while (audio_mask) {
if (audio_mask & 1) {
pcxhr_init_rmh(&rmh, CMD_CAN_START_PIPE);
if (audio < PCXHR_PIPE_STATE_CAPTURE_OFFSET) {
/* can start playback pipe */
pcxhr_set_pipe_cmd_params(&rmh, 0, audio, 0, 0);
} else {
/* can start capture pipe */
pcxhr_set_pipe_cmd_params(&rmh, 1, audio -
PCXHR_PIPE_STATE_CAPTURE_OFFSET,
0, 0);
}
err = pcxhr_send_msg(mgr, &rmh);
if (err) {
snd_printk(KERN_ERR
"error pipe start "
"(CMD_CAN_START_PIPE) err=%x!\n",
err);
return err;
}
/* if the pipe couldn't be prepaired for start,
* retry it later
*/
if (rmh.stat[0] == 0)
*retry |= (1<<audio);
}
audio_mask>>=1;
audio++;
}
return 0;
}
static int pcxhr_stop_pipes(struct pcxhr_mgr *mgr, int audio_mask)
{
struct pcxhr_rmh rmh;
int err;
int audio = 0;
while (audio_mask) {
if (audio_mask & 1) {
pcxhr_init_rmh(&rmh, CMD_STOP_PIPE);
if (audio < PCXHR_PIPE_STATE_CAPTURE_OFFSET) {
/* stop playback pipe */
pcxhr_set_pipe_cmd_params(&rmh, 0, audio, 0, 0);
} else {
/* stop capture pipe */
pcxhr_set_pipe_cmd_params(&rmh, 1, audio -
PCXHR_PIPE_STATE_CAPTURE_OFFSET,
0, 0);
}
err = pcxhr_send_msg(mgr, &rmh);
if (err) {
snd_printk(KERN_ERR
"error pipe stop "
"(CMD_STOP_PIPE) err=%x!\n", err);
return err;
}
}
audio_mask>>=1;
audio++;
}
return 0;
}
static int pcxhr_toggle_pipes(struct pcxhr_mgr *mgr, int audio_mask)
{
struct pcxhr_rmh rmh;
int err;
int audio = 0;
while (audio_mask) {
if (audio_mask & 1) {
pcxhr_init_rmh(&rmh, CMD_CONF_PIPE);
if (audio < PCXHR_PIPE_STATE_CAPTURE_OFFSET)
pcxhr_set_pipe_cmd_params(&rmh, 0, 0, 0,
1 << audio);
else
pcxhr_set_pipe_cmd_params(&rmh, 1, 0, 0,
1 << (audio - PCXHR_PIPE_STATE_CAPTURE_OFFSET));
err = pcxhr_send_msg(mgr, &rmh);
if (err) {
snd_printk(KERN_ERR
"error pipe start "
"(CMD_CONF_PIPE) err=%x!\n", err);
return err;
}
}
audio_mask>>=1;
audio++;
}
/* now fire the interrupt on the card */
pcxhr_init_rmh(&rmh, CMD_SEND_IRQA);
err = pcxhr_send_msg(mgr, &rmh);
if (err) {
snd_printk(KERN_ERR
"error pipe start (CMD_SEND_IRQA) err=%x!\n",
err);
return err;
}
return 0;
}
int pcxhr_set_pipe_state(struct pcxhr_mgr *mgr, int playback_mask,
int capture_mask, int start)
{
int state, i, err;
int audio_mask;
#ifdef CONFIG_SND_DEBUG_VERBOSE
struct timeval my_tv1, my_tv2;
do_gettimeofday(&my_tv1);
#endif
audio_mask = (playback_mask |
(capture_mask << PCXHR_PIPE_STATE_CAPTURE_OFFSET));
/* current pipe state (playback + record) */
state = pcxhr_pipes_running(mgr);
snd_printdd("pcxhr_set_pipe_state %s (mask %x current %x)\n",
start ? "START" : "STOP", audio_mask, state);
if (start) {
/* start only pipes that are not yet started */
audio_mask &= ~state;
state = audio_mask;
for (i = 0; i < MAX_WAIT_FOR_DSP; i++) {
err = pcxhr_prepair_pipe_start(mgr, state, &state);
if (err)
return err;
if (state == 0)
break; /* success, all pipes prepaired */
mdelay(1); /* wait 1 millisecond and retry */
}
} else {
audio_mask &= state; /* stop only pipes that are started */
}
if (audio_mask == 0)
return 0;
err = pcxhr_toggle_pipes(mgr, audio_mask);
if (err)
return err;
i = 0;
while (1) {
state = pcxhr_pipes_running(mgr);
/* have all pipes the new state ? */
if ((state & audio_mask) == (start ? audio_mask : 0))
break;
if (++i >= MAX_WAIT_FOR_DSP * 100) {
snd_printk(KERN_ERR "error pipe start/stop\n");
return -EBUSY;
}
udelay(10); /* wait 10 microseconds */
}
if (!start) {
err = pcxhr_stop_pipes(mgr, audio_mask);
if (err)
return err;
}
#ifdef CONFIG_SND_DEBUG_VERBOSE
do_gettimeofday(&my_tv2);
snd_printdd("***SET PIPE STATE*** TIME = %ld (err = %x)\n",
(long)(my_tv2.tv_usec - my_tv1.tv_usec), err);
#endif
return 0;
}
int pcxhr_write_io_num_reg_cont(struct pcxhr_mgr *mgr, unsigned int mask,
unsigned int value, int *changed)
{
struct pcxhr_rmh rmh;
unsigned long flags;
int err;
spin_lock_irqsave(&mgr->msg_lock, flags);
if ((mgr->io_num_reg_cont & mask) == value) {
snd_printdd("IO_NUM_REG_CONT mask %x already is set to %x\n",
mask, value);
if (changed)
*changed = 0;
spin_unlock_irqrestore(&mgr->msg_lock, flags);
return 0; /* already programmed */
}
pcxhr_init_rmh(&rmh, CMD_ACCESS_IO_WRITE);
rmh.cmd[0] |= IO_NUM_REG_CONT;
rmh.cmd[1] = mask;
rmh.cmd[2] = value;
rmh.cmd_len = 3;
err = pcxhr_send_msg_nolock(mgr, &rmh);
if (err == 0) {
mgr->io_num_reg_cont &= ~mask;
mgr->io_num_reg_cont |= value;
if (changed)
*changed = 1;
}
spin_unlock_irqrestore(&mgr->msg_lock, flags);
return err;
}
#define PCXHR_IRQ_TIMER 0x000300
#define PCXHR_IRQ_FREQ_CHANGE 0x000800
#define PCXHR_IRQ_TIME_CODE 0x001000
#define PCXHR_IRQ_NOTIFY 0x002000
#define PCXHR_IRQ_ASYNC 0x008000
#define PCXHR_IRQ_MASK 0x00bb00
#define PCXHR_FATAL_DSP_ERR 0xff0000
enum pcxhr_async_err_src {
PCXHR_ERR_PIPE,
PCXHR_ERR_STREAM,
PCXHR_ERR_AUDIO
};
static int pcxhr_handle_async_err(struct pcxhr_mgr *mgr, u32 err,
enum pcxhr_async_err_src err_src, int pipe,
int is_capture)
{
#ifdef CONFIG_SND_DEBUG_VERBOSE
static char* err_src_name[] = {
[PCXHR_ERR_PIPE] = "Pipe",
[PCXHR_ERR_STREAM] = "Stream",
[PCXHR_ERR_AUDIO] = "Audio"
};
#endif
if (err & 0xfff)
err &= 0xfff;
else
err = ((err >> 12) & 0xfff);
if (!err)
return 0;
snd_printdd("CMD_ASYNC : Error %s %s Pipe %d err=%x\n",
err_src_name[err_src],
is_capture ? "Record" : "Play", pipe, err);
if (err == 0xe01)
mgr->async_err_stream_xrun++;
else if (err == 0xe10)
mgr->async_err_pipe_xrun++;
else
mgr->async_err_other_last = (int)err;
return 1;
}
void pcxhr_msg_tasklet(unsigned long arg)
{
struct pcxhr_mgr *mgr = (struct pcxhr_mgr *)(arg);
struct pcxhr_rmh *prmh = mgr->prmh;
int err;
int i, j;
if (mgr->src_it_dsp & PCXHR_IRQ_FREQ_CHANGE)
snd_printdd("TASKLET : PCXHR_IRQ_FREQ_CHANGE event occurred\n");
if (mgr->src_it_dsp & PCXHR_IRQ_TIME_CODE)
snd_printdd("TASKLET : PCXHR_IRQ_TIME_CODE event occurred\n");
if (mgr->src_it_dsp & PCXHR_IRQ_NOTIFY)
snd_printdd("TASKLET : PCXHR_IRQ_NOTIFY event occurred\n");
if (mgr->src_it_dsp & (PCXHR_IRQ_FREQ_CHANGE | PCXHR_IRQ_TIME_CODE)) {
/* clear events FREQ_CHANGE and TIME_CODE */
pcxhr_init_rmh(prmh, CMD_TEST_IT);
err = pcxhr_send_msg(mgr, prmh);
snd_printdd("CMD_TEST_IT : err=%x, stat=%x\n",
err, prmh->stat[0]);
}
if (mgr->src_it_dsp & PCXHR_IRQ_ASYNC) {
snd_printdd("TASKLET : PCXHR_IRQ_ASYNC event occurred\n");
pcxhr_init_rmh(prmh, CMD_ASYNC);
prmh->cmd[0] |= 1; /* add SEL_ASYNC_EVENTS */
/* this is the only one extra long response command */
prmh->stat_len = PCXHR_SIZE_MAX_LONG_STATUS;
err = pcxhr_send_msg(mgr, prmh);
if (err)
snd_printk(KERN_ERR "ERROR pcxhr_msg_tasklet=%x;\n",
err);
i = 1;
while (i < prmh->stat_len) {
int nb_audio = ((prmh->stat[i] >> FIELD_SIZE) &
MASK_FIRST_FIELD);
int nb_stream = ((prmh->stat[i] >> (2*FIELD_SIZE)) &
MASK_FIRST_FIELD);
int pipe = prmh->stat[i] & MASK_FIRST_FIELD;
int is_capture = prmh->stat[i] & 0x400000;
u32 err2;
if (prmh->stat[i] & 0x800000) { /* if BIT_END */
snd_printdd("TASKLET : End%sPipe %d\n",
is_capture ? "Record" : "Play",
pipe);
}
i++;
err2 = prmh->stat[i] ? prmh->stat[i] : prmh->stat[i+1];
if (err2)
pcxhr_handle_async_err(mgr, err2,
PCXHR_ERR_PIPE,
pipe, is_capture);
i += 2;
for (j = 0; j < nb_stream; j++) {
err2 = prmh->stat[i] ?
prmh->stat[i] : prmh->stat[i+1];
if (err2)
pcxhr_handle_async_err(mgr, err2,
PCXHR_ERR_STREAM,
pipe,
is_capture);
i += 2;
}
for (j = 0; j < nb_audio; j++) {
err2 = prmh->stat[i] ?
prmh->stat[i] : prmh->stat[i+1];
if (err2)
pcxhr_handle_async_err(mgr, err2,
PCXHR_ERR_AUDIO,
pipe,
is_capture);
i += 2;
}
}
}
}
static u_int64_t pcxhr_stream_read_position(struct pcxhr_mgr *mgr,
struct pcxhr_stream *stream)
{
u_int64_t hw_sample_count;
struct pcxhr_rmh rmh;
int err, stream_mask;
stream_mask = stream->pipe->is_capture ? 1 : 1<<stream->substream->number;
/* get sample count for one stream */
pcxhr_init_rmh(&rmh, CMD_STREAM_SAMPLE_COUNT);
pcxhr_set_pipe_cmd_params(&rmh, stream->pipe->is_capture,
stream->pipe->first_audio, 0, stream_mask);
/* rmh.stat_len = 2; */ /* 2 resp data for each stream of the pipe */
err = pcxhr_send_msg(mgr, &rmh);
if (err)
return 0;
hw_sample_count = ((u_int64_t)rmh.stat[0]) << 24;
hw_sample_count += (u_int64_t)rmh.stat[1];
snd_printdd("stream %c%d : abs samples real(%ld) timer(%ld)\n",
stream->pipe->is_capture ? 'C' : 'P',
stream->substream->number,
(long unsigned int)hw_sample_count,
(long unsigned int)(stream->timer_abs_periods +
stream->timer_period_frag +
mgr->granularity));
return hw_sample_count;
}
static void pcxhr_update_timer_pos(struct pcxhr_mgr *mgr,
struct pcxhr_stream *stream,
int samples_to_add)
{
if (stream->substream &&
(stream->status == PCXHR_STREAM_STATUS_RUNNING)) {
u_int64_t new_sample_count;
int elapsed = 0;
int hardware_read = 0;
struct snd_pcm_runtime *runtime = stream->substream->runtime;
if (samples_to_add < 0) {
stream->timer_is_synced = 0;
/* add default if no hardware_read possible */
samples_to_add = mgr->granularity;
}
if (!stream->timer_is_synced) {
if ((stream->timer_abs_periods != 0) ||
((stream->timer_period_frag + samples_to_add) >=
runtime->period_size)) {
new_sample_count =
pcxhr_stream_read_position(mgr, stream);
hardware_read = 1;
if (new_sample_count >= mgr->granularity) {
/* sub security offset because of
* jitter and finer granularity of
* dsp time (MBOX4)
*/
new_sample_count -= mgr->granularity;
stream->timer_is_synced = 1;
}
}
}
if (!hardware_read) {
/* if we didn't try to sync the position, increment it
* by PCXHR_GRANULARITY every timer interrupt
*/
new_sample_count = stream->timer_abs_periods +
stream->timer_period_frag + samples_to_add;
}
while (1) {
u_int64_t new_elapse_pos = stream->timer_abs_periods +
runtime->period_size;
if (new_elapse_pos > new_sample_count)
break;
elapsed = 1;
stream->timer_buf_periods++;
if (stream->timer_buf_periods >= runtime->periods)
stream->timer_buf_periods = 0;
stream->timer_abs_periods = new_elapse_pos;
}
if (new_sample_count >= stream->timer_abs_periods) {
stream->timer_period_frag =
(u_int32_t)(new_sample_count -
stream->timer_abs_periods);
} else {
snd_printk(KERN_ERR
"ERROR new_sample_count too small ??? %ld\n",
(long unsigned int)new_sample_count);
}
if (elapsed) {
spin_unlock(&mgr->lock);
snd_pcm_period_elapsed(stream->substream);
spin_lock(&mgr->lock);
}
}
}
irqreturn_t pcxhr_interrupt(int irq, void *dev_id)
{
struct pcxhr_mgr *mgr = dev_id;
unsigned int reg;
int i, j;
struct snd_pcxhr *chip;
spin_lock(&mgr->lock);
reg = PCXHR_INPL(mgr, PCXHR_PLX_IRQCS);
if (! (reg & PCXHR_IRQCS_ACTIVE_PCIDB)) {
spin_unlock(&mgr->lock);
/* this device did not cause the interrupt */
return IRQ_NONE;
}
/* clear interrupt */
reg = PCXHR_INPL(mgr, PCXHR_PLX_L2PCIDB);
PCXHR_OUTPL(mgr, PCXHR_PLX_L2PCIDB, reg);
/* timer irq occurred */
if (reg & PCXHR_IRQ_TIMER) {
int timer_toggle = reg & PCXHR_IRQ_TIMER;
/* is a 24 bit counter */
int dsp_time_new =
PCXHR_INPL(mgr, PCXHR_PLX_MBOX4) & PCXHR_DSP_TIME_MASK;
int dsp_time_diff = dsp_time_new - mgr->dsp_time_last;
if ((dsp_time_diff < 0) &&
(mgr->dsp_time_last != PCXHR_DSP_TIME_INVALID)) {
snd_printdd("ERROR DSP TIME old(%d) new(%d) -> "
"resynchronize all streams\n",
mgr->dsp_time_last, dsp_time_new);
mgr->dsp_time_err++;
}
#ifdef CONFIG_SND_DEBUG_VERBOSE
if (dsp_time_diff == 0)
snd_printdd("ERROR DSP TIME NO DIFF time(%d)\n",
dsp_time_new);
else if (dsp_time_diff >= (2*mgr->granularity))
snd_printdd("ERROR DSP TIME TOO BIG old(%d) add(%d)\n",
mgr->dsp_time_last,
dsp_time_new - mgr->dsp_time_last);
else if (dsp_time_diff % mgr->granularity)
snd_printdd("ERROR DSP TIME increased by %d\n",
dsp_time_diff);
#endif
mgr->dsp_time_last = dsp_time_new;
if (timer_toggle == mgr->timer_toggle) {
snd_printdd("ERROR TIMER TOGGLE\n");
mgr->dsp_time_err++;
}
mgr->timer_toggle = timer_toggle;
reg &= ~PCXHR_IRQ_TIMER;
for (i = 0; i < mgr->num_cards; i++) {
chip = mgr->chip[i];
for (j = 0; j < chip->nb_streams_capt; j++)
pcxhr_update_timer_pos(mgr,
&chip->capture_stream[j],
dsp_time_diff);
}
for (i = 0; i < mgr->num_cards; i++) {
chip = mgr->chip[i];
for (j = 0; j < chip->nb_streams_play; j++)
pcxhr_update_timer_pos(mgr,
&chip->playback_stream[j],
dsp_time_diff);
}
}
/* other irq's handled in the tasklet */
if (reg & PCXHR_IRQ_MASK) {
if (reg & PCXHR_IRQ_ASYNC) {
/* as we didn't request any async notifications,
* some kind of xrun error will probably occurred
*/
/* better resynchronize all streams next interrupt : */
mgr->dsp_time_last = PCXHR_DSP_TIME_INVALID;
}
mgr->src_it_dsp = reg;
tasklet_schedule(&mgr->msg_taskq);
}
#ifdef CONFIG_SND_DEBUG_VERBOSE
if (reg & PCXHR_FATAL_DSP_ERR)
snd_printdd("FATAL DSP ERROR : %x\n", reg);
#endif
spin_unlock(&mgr->lock);
return IRQ_HANDLED; /* this device caused the interrupt */
}
| gpl-2.0 |
razrqcom-dev-team/android_kernel_motorola_apq8084 | drivers/media/dvb-frontends/tda10023.c | 8802 | 16592 | /*
TDA10023 - DVB-C decoder
(as used in Philips CU1216-3 NIM and the Reelbox DVB-C tuner card)
Copyright (C) 2005 Georg Acher, BayCom GmbH (acher at baycom dot de)
Copyright (c) 2006 Hartmut Birr (e9hack at gmail dot com)
Remotely based on tda10021.c
Copyright (C) 1999 Convergence Integrated Media GmbH <ralph@convergence.de>
Copyright (C) 2004 Markus Schulz <msc@antzsystem.de>
Support for TDA10021
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/delay.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <asm/div64.h>
#include "dvb_frontend.h"
#include "tda1002x.h"
#define REG0_INIT_VAL 0x23
struct tda10023_state {
struct i2c_adapter* i2c;
/* configuration settings */
const struct tda10023_config *config;
struct dvb_frontend frontend;
u8 pwm;
u8 reg0;
/* clock settings */
u32 xtal;
u8 pll_m;
u8 pll_p;
u8 pll_n;
u32 sysclk;
};
#define dprintk(x...)
static int verbose;
static u8 tda10023_readreg (struct tda10023_state* state, u8 reg)
{
u8 b0 [] = { reg };
u8 b1 [] = { 0 };
struct i2c_msg msg [] = { { .addr = state->config->demod_address, .flags = 0, .buf = b0, .len = 1 },
{ .addr = state->config->demod_address, .flags = I2C_M_RD, .buf = b1, .len = 1 } };
int ret;
ret = i2c_transfer (state->i2c, msg, 2);
if (ret != 2) {
int num = state->frontend.dvb ? state->frontend.dvb->num : -1;
printk(KERN_ERR "DVB: TDA10023(%d): %s: readreg error "
"(reg == 0x%02x, ret == %i)\n",
num, __func__, reg, ret);
}
return b1[0];
}
static int tda10023_writereg (struct tda10023_state* state, u8 reg, u8 data)
{
u8 buf[] = { reg, data };
struct i2c_msg msg = { .addr = state->config->demod_address, .flags = 0, .buf = buf, .len = 2 };
int ret;
ret = i2c_transfer (state->i2c, &msg, 1);
if (ret != 1) {
int num = state->frontend.dvb ? state->frontend.dvb->num : -1;
printk(KERN_ERR "DVB: TDA10023(%d): %s, writereg error "
"(reg == 0x%02x, val == 0x%02x, ret == %i)\n",
num, __func__, reg, data, ret);
}
return (ret != 1) ? -EREMOTEIO : 0;
}
static int tda10023_writebit (struct tda10023_state* state, u8 reg, u8 mask,u8 data)
{
if (mask==0xff)
return tda10023_writereg(state, reg, data);
else {
u8 val;
val=tda10023_readreg(state,reg);
val&=~mask;
val|=(data&mask);
return tda10023_writereg(state, reg, val);
}
}
static void tda10023_writetab(struct tda10023_state* state, u8* tab)
{
u8 r,m,v;
while (1) {
r=*tab++;
m=*tab++;
v=*tab++;
if (r==0xff) {
if (m==0xff)
break;
else
msleep(m);
}
else
tda10023_writebit(state,r,m,v);
}
}
//get access to tuner
static int lock_tuner(struct tda10023_state* state)
{
u8 buf[2] = { 0x0f, 0xc0 };
struct i2c_msg msg = {.addr=state->config->demod_address, .flags=0, .buf=buf, .len=2};
if(i2c_transfer(state->i2c, &msg, 1) != 1)
{
printk("tda10023: lock tuner fails\n");
return -EREMOTEIO;
}
return 0;
}
//release access from tuner
static int unlock_tuner(struct tda10023_state* state)
{
u8 buf[2] = { 0x0f, 0x40 };
struct i2c_msg msg_post={.addr=state->config->demod_address, .flags=0, .buf=buf, .len=2};
if(i2c_transfer(state->i2c, &msg_post, 1) != 1)
{
printk("tda10023: unlock tuner fails\n");
return -EREMOTEIO;
}
return 0;
}
static int tda10023_setup_reg0 (struct tda10023_state* state, u8 reg0)
{
reg0 |= state->reg0 & 0x63;
tda10023_writereg (state, 0x00, reg0 & 0xfe);
tda10023_writereg (state, 0x00, reg0 | 0x01);
state->reg0 = reg0;
return 0;
}
static int tda10023_set_symbolrate (struct tda10023_state* state, u32 sr)
{
s32 BDR;
s32 BDRI;
s16 SFIL=0;
u16 NDEC = 0;
/* avoid floating point operations multiplying syscloc and divider
by 10 */
u32 sysclk_x_10 = state->sysclk * 10;
if (sr < (u32)(sysclk_x_10/984)) {
NDEC=3;
SFIL=1;
} else if (sr < (u32)(sysclk_x_10/640)) {
NDEC=3;
SFIL=0;
} else if (sr < (u32)(sysclk_x_10/492)) {
NDEC=2;
SFIL=1;
} else if (sr < (u32)(sysclk_x_10/320)) {
NDEC=2;
SFIL=0;
} else if (sr < (u32)(sysclk_x_10/246)) {
NDEC=1;
SFIL=1;
} else if (sr < (u32)(sysclk_x_10/160)) {
NDEC=1;
SFIL=0;
} else if (sr < (u32)(sysclk_x_10/123)) {
NDEC=0;
SFIL=1;
}
BDRI = (state->sysclk)*16;
BDRI>>=NDEC;
BDRI +=sr/2;
BDRI /=sr;
if (BDRI>255)
BDRI=255;
{
u64 BDRX;
BDRX=1<<(24+NDEC);
BDRX*=sr;
do_div(BDRX, state->sysclk); /* BDRX/=SYSCLK; */
BDR=(s32)BDRX;
}
dprintk("Symbolrate %i, BDR %i BDRI %i, NDEC %i\n",
sr, BDR, BDRI, NDEC);
tda10023_writebit (state, 0x03, 0xc0, NDEC<<6);
tda10023_writereg (state, 0x0a, BDR&255);
tda10023_writereg (state, 0x0b, (BDR>>8)&255);
tda10023_writereg (state, 0x0c, (BDR>>16)&31);
tda10023_writereg (state, 0x0d, BDRI);
tda10023_writereg (state, 0x3d, (SFIL<<7));
return 0;
}
static int tda10023_init (struct dvb_frontend *fe)
{
struct tda10023_state* state = fe->demodulator_priv;
u8 tda10023_inittab[] = {
/* reg mask val */
/* 000 */ 0x2a, 0xff, 0x02, /* PLL3, Bypass, Power Down */
/* 003 */ 0xff, 0x64, 0x00, /* Sleep 100ms */
/* 006 */ 0x2a, 0xff, 0x03, /* PLL3, Bypass, Power Down */
/* 009 */ 0xff, 0x64, 0x00, /* Sleep 100ms */
/* PLL1 */
/* 012 */ 0x28, 0xff, (state->pll_m-1),
/* PLL2 */
/* 015 */ 0x29, 0xff, ((state->pll_p-1)<<6)|(state->pll_n-1),
/* GPR FSAMPLING=1 */
/* 018 */ 0x00, 0xff, REG0_INIT_VAL,
/* 021 */ 0x2a, 0xff, 0x08, /* PLL3 PSACLK=1 */
/* 024 */ 0xff, 0x64, 0x00, /* Sleep 100ms */
/* 027 */ 0x1f, 0xff, 0x00, /* RESET */
/* 030 */ 0xff, 0x64, 0x00, /* Sleep 100ms */
/* 033 */ 0xe6, 0x0c, 0x04, /* RSCFG_IND */
/* 036 */ 0x10, 0xc0, 0x80, /* DECDVBCFG1 PBER=1 */
/* 039 */ 0x0e, 0xff, 0x82, /* GAIN1 */
/* 042 */ 0x03, 0x08, 0x08, /* CLKCONF DYN=1 */
/* 045 */ 0x2e, 0xbf, 0x30, /* AGCCONF2 TRIAGC=0,POSAGC=ENAGCIF=1
PPWMTUN=0 PPWMIF=0 */
/* 048 */ 0x01, 0xff, 0x30, /* AGCREF */
/* 051 */ 0x1e, 0x84, 0x84, /* CONTROL SACLK_ON=1 */
/* 054 */ 0x1b, 0xff, 0xc8, /* ADC TWOS=1 */
/* 057 */ 0x3b, 0xff, 0xff, /* IFMAX */
/* 060 */ 0x3c, 0xff, 0x00, /* IFMIN */
/* 063 */ 0x34, 0xff, 0x00, /* PWMREF */
/* 066 */ 0x35, 0xff, 0xff, /* TUNMAX */
/* 069 */ 0x36, 0xff, 0x00, /* TUNMIN */
/* 072 */ 0x06, 0xff, 0x7f, /* EQCONF1 POSI=7 ENADAPT=ENEQUAL=DFE=1 */
/* 075 */ 0x1c, 0x30, 0x30, /* EQCONF2 STEPALGO=SGNALGO=1 */
/* 078 */ 0x37, 0xff, 0xf6, /* DELTAF_LSB */
/* 081 */ 0x38, 0xff, 0xff, /* DELTAF_MSB */
/* 084 */ 0x02, 0xff, 0x93, /* AGCCONF1 IFS=1 KAGCIF=2 KAGCTUN=3 */
/* 087 */ 0x2d, 0xff, 0xf6, /* SWEEP SWPOS=1 SWDYN=7 SWSTEP=1 SWLEN=2 */
/* 090 */ 0x04, 0x10, 0x00, /* SWRAMP=1 */
/* 093 */ 0x12, 0xff, TDA10023_OUTPUT_MODE_PARALLEL_B, /*
INTP1 POCLKP=1 FEL=1 MFS=0 */
/* 096 */ 0x2b, 0x01, 0xa1, /* INTS1 */
/* 099 */ 0x20, 0xff, 0x04, /* INTP2 SWAPP=? MSBFIRSTP=? INTPSEL=? */
/* 102 */ 0x2c, 0xff, 0x0d, /* INTP/S TRIP=0 TRIS=0 */
/* 105 */ 0xc4, 0xff, 0x00,
/* 108 */ 0xc3, 0x30, 0x00,
/* 111 */ 0xb5, 0xff, 0x19, /* ERAGC_THD */
/* 114 */ 0x00, 0x03, 0x01, /* GPR, CLBS soft reset */
/* 117 */ 0x00, 0x03, 0x03, /* GPR, CLBS soft reset */
/* 120 */ 0xff, 0x64, 0x00, /* Sleep 100ms */
/* 123 */ 0xff, 0xff, 0xff
};
dprintk("DVB: TDA10023(%d): init chip\n", fe->dvb->num);
/* override default values if set in config */
if (state->config->deltaf) {
tda10023_inittab[80] = (state->config->deltaf & 0xff);
tda10023_inittab[83] = (state->config->deltaf >> 8);
}
if (state->config->output_mode)
tda10023_inittab[95] = state->config->output_mode;
tda10023_writetab(state, tda10023_inittab);
return 0;
}
struct qam_params {
u8 qam, lockthr, mseth, aref, agcrefnyq, eragnyq_thd;
};
static int tda10023_set_parameters(struct dvb_frontend *fe)
{
struct dtv_frontend_properties *c = &fe->dtv_property_cache;
u32 delsys = c->delivery_system;
unsigned qam = c->modulation;
bool is_annex_c;
struct tda10023_state* state = fe->demodulator_priv;
static const struct qam_params qam_params[] = {
/* Modulation QAM LOCKTHR MSETH AREF AGCREFNYQ ERAGCNYQ_THD */
[QPSK] = { (5<<2), 0x78, 0x8c, 0x96, 0x78, 0x4c },
[QAM_16] = { (0<<2), 0x87, 0xa2, 0x91, 0x8c, 0x57 },
[QAM_32] = { (1<<2), 0x64, 0x74, 0x96, 0x8c, 0x57 },
[QAM_64] = { (2<<2), 0x46, 0x43, 0x6a, 0x6a, 0x44 },
[QAM_128] = { (3<<2), 0x36, 0x34, 0x7e, 0x78, 0x4c },
[QAM_256] = { (4<<2), 0x26, 0x23, 0x6c, 0x5c, 0x3c },
};
switch (delsys) {
case SYS_DVBC_ANNEX_A:
is_annex_c = false;
break;
case SYS_DVBC_ANNEX_C:
is_annex_c = true;
break;
default:
return -EINVAL;
}
/*
* gcc optimizes the code bellow the same way as it would code:
* "if (qam > 5) return -EINVAL;"
* Yet, the code is clearer, as it shows what QAM standards are
* supported by the driver, and avoids the usage of magic numbers on
* it.
*/
switch (qam) {
case QPSK:
case QAM_16:
case QAM_32:
case QAM_64:
case QAM_128:
case QAM_256:
break;
default:
return -EINVAL;
}
if (fe->ops.tuner_ops.set_params) {
fe->ops.tuner_ops.set_params(fe);
if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 0);
}
tda10023_set_symbolrate(state, c->symbol_rate);
tda10023_writereg(state, 0x05, qam_params[qam].lockthr);
tda10023_writereg(state, 0x08, qam_params[qam].mseth);
tda10023_writereg(state, 0x09, qam_params[qam].aref);
tda10023_writereg(state, 0xb4, qam_params[qam].agcrefnyq);
tda10023_writereg(state, 0xb6, qam_params[qam].eragnyq_thd);
#if 0
tda10023_writereg(state, 0x04, (c->inversion ? 0x12 : 0x32));
tda10023_writebit(state, 0x04, 0x60, (c->inversion ? 0 : 0x20));
#endif
tda10023_writebit(state, 0x04, 0x40, 0x40);
if (is_annex_c)
tda10023_writebit(state, 0x3d, 0xfc, 0x03);
else
tda10023_writebit(state, 0x3d, 0xfc, 0x02);
tda10023_setup_reg0(state, qam_params[qam].qam);
return 0;
}
static int tda10023_read_status(struct dvb_frontend* fe, fe_status_t* status)
{
struct tda10023_state* state = fe->demodulator_priv;
int sync;
*status = 0;
//0x11[1] == CARLOCK -> Carrier locked
//0x11[2] == FSYNC -> Frame synchronisation
//0x11[3] == FEL -> Front End locked
//0x11[6] == NODVB -> DVB Mode Information
sync = tda10023_readreg (state, 0x11);
if (sync & 2)
*status |= FE_HAS_SIGNAL|FE_HAS_CARRIER;
if (sync & 4)
*status |= FE_HAS_SYNC|FE_HAS_VITERBI;
if (sync & 8)
*status |= FE_HAS_LOCK;
return 0;
}
static int tda10023_read_ber(struct dvb_frontend* fe, u32* ber)
{
struct tda10023_state* state = fe->demodulator_priv;
u8 a,b,c;
a=tda10023_readreg(state, 0x14);
b=tda10023_readreg(state, 0x15);
c=tda10023_readreg(state, 0x16)&0xf;
tda10023_writebit (state, 0x10, 0xc0, 0x00);
*ber = a | (b<<8)| (c<<16);
return 0;
}
static int tda10023_read_signal_strength(struct dvb_frontend* fe, u16* strength)
{
struct tda10023_state* state = fe->demodulator_priv;
u8 ifgain=tda10023_readreg(state, 0x2f);
u16 gain = ((255-tda10023_readreg(state, 0x17))) + (255-ifgain)/16;
// Max raw value is about 0xb0 -> Normalize to >0xf0 after 0x90
if (gain>0x90)
gain=gain+2*(gain-0x90);
if (gain>255)
gain=255;
*strength = (gain<<8)|gain;
return 0;
}
static int tda10023_read_snr(struct dvb_frontend* fe, u16* snr)
{
struct tda10023_state* state = fe->demodulator_priv;
u8 quality = ~tda10023_readreg(state, 0x18);
*snr = (quality << 8) | quality;
return 0;
}
static int tda10023_read_ucblocks(struct dvb_frontend* fe, u32* ucblocks)
{
struct tda10023_state* state = fe->demodulator_priv;
u8 a,b,c,d;
a= tda10023_readreg (state, 0x74);
b= tda10023_readreg (state, 0x75);
c= tda10023_readreg (state, 0x76);
d= tda10023_readreg (state, 0x77);
*ucblocks = a | (b<<8)|(c<<16)|(d<<24);
tda10023_writebit (state, 0x10, 0x20,0x00);
tda10023_writebit (state, 0x10, 0x20,0x20);
tda10023_writebit (state, 0x13, 0x01, 0x00);
return 0;
}
static int tda10023_get_frontend(struct dvb_frontend *fe)
{
struct dtv_frontend_properties *p = &fe->dtv_property_cache;
struct tda10023_state* state = fe->demodulator_priv;
int sync,inv;
s8 afc = 0;
sync = tda10023_readreg(state, 0x11);
afc = tda10023_readreg(state, 0x19);
inv = tda10023_readreg(state, 0x04);
if (verbose) {
/* AFC only valid when carrier has been recovered */
printk(sync & 2 ? "DVB: TDA10023(%d): AFC (%d) %dHz\n" :
"DVB: TDA10023(%d): [AFC (%d) %dHz]\n",
state->frontend.dvb->num, afc,
-((s32)p->symbol_rate * afc) >> 10);
}
p->inversion = (inv&0x20?0:1);
p->modulation = ((state->reg0 >> 2) & 7) + QAM_16;
p->fec_inner = FEC_NONE;
p->frequency = ((p->frequency + 31250) / 62500) * 62500;
if (sync & 2)
p->frequency -= ((s32)p->symbol_rate * afc) >> 10;
return 0;
}
static int tda10023_sleep(struct dvb_frontend* fe)
{
struct tda10023_state* state = fe->demodulator_priv;
tda10023_writereg (state, 0x1b, 0x02); /* pdown ADC */
tda10023_writereg (state, 0x00, 0x80); /* standby */
return 0;
}
static int tda10023_i2c_gate_ctrl(struct dvb_frontend* fe, int enable)
{
struct tda10023_state* state = fe->demodulator_priv;
if (enable) {
lock_tuner(state);
} else {
unlock_tuner(state);
}
return 0;
}
static void tda10023_release(struct dvb_frontend* fe)
{
struct tda10023_state* state = fe->demodulator_priv;
kfree(state);
}
static struct dvb_frontend_ops tda10023_ops;
struct dvb_frontend *tda10023_attach(const struct tda10023_config *config,
struct i2c_adapter *i2c,
u8 pwm)
{
struct tda10023_state* state = NULL;
/* allocate memory for the internal state */
state = kzalloc(sizeof(struct tda10023_state), GFP_KERNEL);
if (state == NULL) goto error;
/* setup the state */
state->config = config;
state->i2c = i2c;
/* wakeup if in standby */
tda10023_writereg (state, 0x00, 0x33);
/* check if the demod is there */
if ((tda10023_readreg(state, 0x1a) & 0xf0) != 0x70) goto error;
/* create dvb_frontend */
memcpy(&state->frontend.ops, &tda10023_ops, sizeof(struct dvb_frontend_ops));
state->pwm = pwm;
state->reg0 = REG0_INIT_VAL;
if (state->config->xtal) {
state->xtal = state->config->xtal;
state->pll_m = state->config->pll_m;
state->pll_p = state->config->pll_p;
state->pll_n = state->config->pll_n;
} else {
/* set default values if not defined in config */
state->xtal = 28920000;
state->pll_m = 8;
state->pll_p = 4;
state->pll_n = 1;
}
/* calc sysclk */
state->sysclk = (state->xtal * state->pll_m / \
(state->pll_n * state->pll_p));
state->frontend.ops.info.symbol_rate_min = (state->sysclk/2)/64;
state->frontend.ops.info.symbol_rate_max = (state->sysclk/2)/4;
dprintk("DVB: TDA10023 %s: xtal:%d pll_m:%d pll_p:%d pll_n:%d\n",
__func__, state->xtal, state->pll_m, state->pll_p,
state->pll_n);
state->frontend.demodulator_priv = state;
return &state->frontend;
error:
kfree(state);
return NULL;
}
static struct dvb_frontend_ops tda10023_ops = {
.delsys = { SYS_DVBC_ANNEX_A, SYS_DVBC_ANNEX_C },
.info = {
.name = "Philips TDA10023 DVB-C",
.frequency_stepsize = 62500,
.frequency_min = 47000000,
.frequency_max = 862000000,
.symbol_rate_min = 0, /* set in tda10023_attach */
.symbol_rate_max = 0, /* set in tda10023_attach */
.caps = 0x400 | //FE_CAN_QAM_4
FE_CAN_QAM_16 | FE_CAN_QAM_32 | FE_CAN_QAM_64 |
FE_CAN_QAM_128 | FE_CAN_QAM_256 |
FE_CAN_FEC_AUTO
},
.release = tda10023_release,
.init = tda10023_init,
.sleep = tda10023_sleep,
.i2c_gate_ctrl = tda10023_i2c_gate_ctrl,
.set_frontend = tda10023_set_parameters,
.get_frontend = tda10023_get_frontend,
.read_status = tda10023_read_status,
.read_ber = tda10023_read_ber,
.read_signal_strength = tda10023_read_signal_strength,
.read_snr = tda10023_read_snr,
.read_ucblocks = tda10023_read_ucblocks,
};
MODULE_DESCRIPTION("Philips TDA10023 DVB-C demodulator driver");
MODULE_AUTHOR("Georg Acher, Hartmut Birr");
MODULE_LICENSE("GPL");
EXPORT_SYMBOL(tda10023_attach);
| gpl-2.0 |
loverszhaokai/gcc | gcc/testsuite/gcc.target/i386/avx512f-vaddps-2.c | 99 | 1199 | /* { dg-do run } */
/* { dg-options "-O2 -mavx512f" } */
/* { dg-require-effective-target avx512f } */
#define AVX512F
#include "avx512f-helper.h"
#define SIZE (AVX512F_LEN / 32)
#include "avx512f-mask-type.h"
static void
CALC (float *r, float *s1, float *s2)
{
int i;
for (i = 0; i < SIZE; i++)
{
r[i] = s1[i] + s2[i];
}
}
void
TEST (void)
{
int i, sign;
UNION_TYPE (AVX512F_LEN,) res1, res2, res3, src1, src2;
MASK_TYPE mask = MASK_VALUE;
float res_ref[SIZE];
sign = -1;
for (i = 0; i < SIZE; i++)
{
src1.a[i] = 1.5 + 34.67 * i * sign;
src2.a[i] = -22.17 * i * sign;
sign = sign * -1;
}
for (i = 0; i < SIZE; i++)
res2.a[i] = DEFAULT_VALUE;
res1.x = INTRINSIC (_add_ps) (src1.x, src2.x);
res2.x = INTRINSIC (_mask_add_ps) (res2.x, mask, src1.x, src2.x);
res3.x = INTRINSIC (_maskz_add_ps) (mask, src1.x, src2.x);
CALC (res_ref, src1.a, src2.a);
if (UNION_CHECK (AVX512F_LEN,) (res1, res_ref))
abort ();
MASK_MERGE () (res_ref, mask, SIZE);
if (UNION_CHECK (AVX512F_LEN,) (res2, res_ref))
abort ();
MASK_ZERO () (res_ref, mask, SIZE);
if (UNION_CHECK (AVX512F_LEN,) (res3, res_ref))
abort ();
}
| gpl-2.0 |
eugene373/ka6_last_Dead_Horse | fs/ubifs/file.c | 355 | 45805 | /*
* This file is part of UBIFS.
*
* 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; if not, write to the Free Software Foundation, Inc., 51
* Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Authors: Artem Bityutskiy (Битюцкий Артём)
* Adrian Hunter
*/
/*
* This file implements VFS file and inode operations for regular files, device
* nodes and symlinks as well as address space operations.
*
* UBIFS uses 2 page flags: @PG_private and @PG_checked. @PG_private is set if
* the page is dirty and is used for optimization purposes - dirty pages are
* not budgeted so the flag shows that 'ubifs_write_end()' should not release
* the budget for this page. The @PG_checked flag is set if full budgeting is
* required for the page e.g., when it corresponds to a file hole or it is
* beyond the file size. The budgeting is done in 'ubifs_write_begin()', because
* it is OK to fail in this function, and the budget is released in
* 'ubifs_write_end()'. So the @PG_private and @PG_checked flags carry
* information about how the page was budgeted, to make it possible to release
* the budget properly.
*
* A thing to keep in mind: inode @i_mutex is locked in most VFS operations we
* implement. However, this is not true for 'ubifs_writepage()', which may be
* called with @i_mutex unlocked. For example, when pdflush is doing background
* write-back, it calls 'ubifs_writepage()' with unlocked @i_mutex. At "normal"
* work-paths the @i_mutex is locked in 'ubifs_writepage()', e.g. in the
* "sys_write -> alloc_pages -> direct reclaim path". So, in 'ubifs_writepage()'
* we are only guaranteed that the page is locked.
*
* Similarly, @i_mutex is not always locked in 'ubifs_readpage()', e.g., the
* read-ahead path does not lock it ("sys_read -> generic_file_aio_read ->
* ondemand_readahead -> readpage"). In case of readahead, @I_LOCK flag is not
* set as well. However, UBIFS disables readahead.
*/
#include "ubifs.h"
#include <linux/mount.h>
#include <linux/namei.h>
static int read_block(struct inode *inode, void *addr, unsigned int block,
struct ubifs_data_node *dn)
{
struct ubifs_info *c = inode->i_sb->s_fs_info;
int err, len, out_len;
union ubifs_key key;
unsigned int dlen;
data_key_init(c, &key, inode->i_ino, block);
err = ubifs_tnc_lookup(c, &key, dn);
if (err) {
if (err == -ENOENT)
/* Not found, so it must be a hole */
memset(addr, 0, UBIFS_BLOCK_SIZE);
return err;
}
ubifs_assert(le64_to_cpu(dn->ch.sqnum) >
ubifs_inode(inode)->creat_sqnum);
len = le32_to_cpu(dn->size);
if (len <= 0 || len > UBIFS_BLOCK_SIZE)
goto dump;
dlen = le32_to_cpu(dn->ch.len) - UBIFS_DATA_NODE_SZ;
out_len = UBIFS_BLOCK_SIZE;
err = ubifs_decompress(&dn->data, dlen, addr, &out_len,
le16_to_cpu(dn->compr_type));
if (err || len != out_len)
goto dump;
/*
* Data length can be less than a full block, even for blocks that are
* not the last in the file (e.g., as a result of making a hole and
* appending data). Ensure that the remainder is zeroed out.
*/
if (len < UBIFS_BLOCK_SIZE)
memset(addr + len, 0, UBIFS_BLOCK_SIZE - len);
return 0;
dump:
ubifs_err("bad data node (block %u, inode %lu)",
block, inode->i_ino);
dbg_dump_node(c, dn);
return -EINVAL;
}
static int do_readpage(struct page *page)
{
void *addr;
int err = 0, i;
unsigned int block, beyond;
struct ubifs_data_node *dn;
struct inode *inode = page->mapping->host;
loff_t i_size = i_size_read(inode);
dbg_gen("ino %lu, pg %lu, i_size %lld, flags %#lx",
inode->i_ino, page->index, i_size, page->flags);
ubifs_assert(!PageChecked(page));
ubifs_assert(!PagePrivate(page));
addr = kmap(page);
block = page->index << UBIFS_BLOCKS_PER_PAGE_SHIFT;
beyond = (i_size + UBIFS_BLOCK_SIZE - 1) >> UBIFS_BLOCK_SHIFT;
if (block >= beyond) {
/* Reading beyond inode */
SetPageChecked(page);
memset(addr, 0, PAGE_CACHE_SIZE);
goto out;
}
dn = kmalloc(UBIFS_MAX_DATA_NODE_SZ, GFP_NOFS);
if (!dn) {
err = -ENOMEM;
goto error;
}
i = 0;
while (1) {
int ret;
if (block >= beyond) {
/* Reading beyond inode */
err = -ENOENT;
memset(addr, 0, UBIFS_BLOCK_SIZE);
} else {
ret = read_block(inode, addr, block, dn);
if (ret) {
err = ret;
if (err != -ENOENT)
break;
} else if (block + 1 == beyond) {
int dlen = le32_to_cpu(dn->size);
int ilen = i_size & (UBIFS_BLOCK_SIZE - 1);
if (ilen && ilen < dlen)
memset(addr + ilen, 0, dlen - ilen);
}
}
if (++i >= UBIFS_BLOCKS_PER_PAGE)
break;
block += 1;
addr += UBIFS_BLOCK_SIZE;
}
if (err) {
if (err == -ENOENT) {
/* Not found, so it must be a hole */
SetPageChecked(page);
dbg_gen("hole");
goto out_free;
}
ubifs_err("cannot read page %lu of inode %lu, error %d",
page->index, inode->i_ino, err);
goto error;
}
out_free:
kfree(dn);
out:
SetPageUptodate(page);
ClearPageError(page);
flush_dcache_page(page);
kunmap(page);
return 0;
error:
kfree(dn);
ClearPageUptodate(page);
SetPageError(page);
flush_dcache_page(page);
kunmap(page);
return err;
}
/**
* release_new_page_budget - release budget of a new page.
* @c: UBIFS file-system description object
*
* This is a helper function which releases budget corresponding to the budget
* of one new page of data.
*/
static void release_new_page_budget(struct ubifs_info *c)
{
struct ubifs_budget_req req = { .recalculate = 1, .new_page = 1 };
ubifs_release_budget(c, &req);
}
/**
* release_existing_page_budget - release budget of an existing page.
* @c: UBIFS file-system description object
*
* This is a helper function which releases budget corresponding to the budget
* of changing one one page of data which already exists on the flash media.
*/
static void release_existing_page_budget(struct ubifs_info *c)
{
struct ubifs_budget_req req = { .dd_growth = c->page_budget};
ubifs_release_budget(c, &req);
}
static int write_begin_slow(struct address_space *mapping,
loff_t pos, unsigned len, struct page **pagep,
unsigned flags)
{
struct inode *inode = mapping->host;
struct ubifs_info *c = inode->i_sb->s_fs_info;
pgoff_t index = pos >> PAGE_CACHE_SHIFT;
struct ubifs_budget_req req = { .new_page = 1 };
int uninitialized_var(err), appending = !!(pos + len > inode->i_size);
struct page *page;
dbg_gen("ino %lu, pos %llu, len %u, i_size %lld",
inode->i_ino, pos, len, inode->i_size);
/*
* At the slow path we have to budget before locking the page, because
* budgeting may force write-back, which would wait on locked pages and
* deadlock if we had the page locked. At this point we do not know
* anything about the page, so assume that this is a new page which is
* written to a hole. This corresponds to largest budget. Later the
* budget will be amended if this is not true.
*/
if (appending)
/* We are appending data, budget for inode change */
req.dirtied_ino = 1;
err = ubifs_budget_space(c, &req);
if (unlikely(err))
return err;
page = grab_cache_page_write_begin(mapping, index, flags);
if (unlikely(!page)) {
ubifs_release_budget(c, &req);
return -ENOMEM;
}
if (!PageUptodate(page)) {
if (!(pos & ~PAGE_CACHE_MASK) && len == PAGE_CACHE_SIZE)
SetPageChecked(page);
else {
err = do_readpage(page);
if (err) {
unlock_page(page);
page_cache_release(page);
return err;
}
}
SetPageUptodate(page);
ClearPageError(page);
}
if (PagePrivate(page))
/*
* The page is dirty, which means it was budgeted twice:
* o first time the budget was allocated by the task which
* made the page dirty and set the PG_private flag;
* o and then we budgeted for it for the second time at the
* very beginning of this function.
*
* So what we have to do is to release the page budget we
* allocated.
*/
release_new_page_budget(c);
else if (!PageChecked(page))
/*
* We are changing a page which already exists on the media.
* This means that changing the page does not make the amount
* of indexing information larger, and this part of the budget
* which we have already acquired may be released.
*/
ubifs_convert_page_budget(c);
if (appending) {
struct ubifs_inode *ui = ubifs_inode(inode);
/*
* 'ubifs_write_end()' is optimized from the fast-path part of
* 'ubifs_write_begin()' and expects the @ui_mutex to be locked
* if data is appended.
*/
mutex_lock(&ui->ui_mutex);
if (ui->dirty)
/*
* The inode is dirty already, so we may free the
* budget we allocated.
*/
ubifs_release_dirty_inode_budget(c, ui);
}
*pagep = page;
return 0;
}
/**
* allocate_budget - allocate budget for 'ubifs_write_begin()'.
* @c: UBIFS file-system description object
* @page: page to allocate budget for
* @ui: UBIFS inode object the page belongs to
* @appending: non-zero if the page is appended
*
* This is a helper function for 'ubifs_write_begin()' which allocates budget
* for the operation. The budget is allocated differently depending on whether
* this is appending, whether the page is dirty or not, and so on. This
* function leaves the @ui->ui_mutex locked in case of appending. Returns zero
* in case of success and %-ENOSPC in case of failure.
*/
static int allocate_budget(struct ubifs_info *c, struct page *page,
struct ubifs_inode *ui, int appending)
{
struct ubifs_budget_req req = { .fast = 1 };
if (PagePrivate(page)) {
if (!appending)
/*
* The page is dirty and we are not appending, which
* means no budget is needed at all.
*/
return 0;
mutex_lock(&ui->ui_mutex);
if (ui->dirty)
/*
* The page is dirty and we are appending, so the inode
* has to be marked as dirty. However, it is already
* dirty, so we do not need any budget. We may return,
* but @ui->ui_mutex hast to be left locked because we
* should prevent write-back from flushing the inode
* and freeing the budget. The lock will be released in
* 'ubifs_write_end()'.
*/
return 0;
/*
* The page is dirty, we are appending, the inode is clean, so
* we need to budget the inode change.
*/
req.dirtied_ino = 1;
} else {
if (PageChecked(page))
/*
* The page corresponds to a hole and does not
* exist on the media. So changing it makes
* make the amount of indexing information
* larger, and we have to budget for a new
* page.
*/
req.new_page = 1;
else
/*
* Not a hole, the change will not add any new
* indexing information, budget for page
* change.
*/
req.dirtied_page = 1;
if (appending) {
mutex_lock(&ui->ui_mutex);
if (!ui->dirty)
/*
* The inode is clean but we will have to mark
* it as dirty because we are appending. This
* needs a budget.
*/
req.dirtied_ino = 1;
}
}
return ubifs_budget_space(c, &req);
}
/*
* This function is called when a page of data is going to be written. Since
* the page of data will not necessarily go to the flash straight away, UBIFS
* has to reserve space on the media for it, which is done by means of
* budgeting.
*
* This is the hot-path of the file-system and we are trying to optimize it as
* much as possible. For this reasons it is split on 2 parts - slow and fast.
*
* There many budgeting cases:
* o a new page is appended - we have to budget for a new page and for
* changing the inode; however, if the inode is already dirty, there is
* no need to budget for it;
* o an existing clean page is changed - we have budget for it; if the page
* does not exist on the media (a hole), we have to budget for a new
* page; otherwise, we may budget for changing an existing page; the
* difference between these cases is that changing an existing page does
* not introduce anything new to the FS indexing information, so it does
* not grow, and smaller budget is acquired in this case;
* o an existing dirty page is changed - no need to budget at all, because
* the page budget has been acquired by earlier, when the page has been
* marked dirty.
*
* UBIFS budgeting sub-system may force write-back if it thinks there is no
* space to reserve. This imposes some locking restrictions and makes it
* impossible to take into account the above cases, and makes it impossible to
* optimize budgeting.
*
* The solution for this is that the fast path of 'ubifs_write_begin()' assumes
* there is a plenty of flash space and the budget will be acquired quickly,
* without forcing write-back. The slow path does not make this assumption.
*/
static int ubifs_write_begin(struct file *file, struct address_space *mapping,
loff_t pos, unsigned len, unsigned flags,
struct page **pagep, void **fsdata)
{
struct inode *inode = mapping->host;
struct ubifs_info *c = inode->i_sb->s_fs_info;
struct ubifs_inode *ui = ubifs_inode(inode);
pgoff_t index = pos >> PAGE_CACHE_SHIFT;
int uninitialized_var(err), appending = !!(pos + len > inode->i_size);
int skipped_read = 0;
struct page *page;
ubifs_assert(ubifs_inode(inode)->ui_size == inode->i_size);
if (unlikely(c->ro_media))
return -EROFS;
/* Try out the fast-path part first */
page = grab_cache_page_write_begin(mapping, index, flags);
if (unlikely(!page))
return -ENOMEM;
if (!PageUptodate(page)) {
/* The page is not loaded from the flash */
if (!(pos & ~PAGE_CACHE_MASK) && len == PAGE_CACHE_SIZE) {
/*
* We change whole page so no need to load it. But we
* have to set the @PG_checked flag to make the further
* code know that the page is new. This might be not
* true, but it is better to budget more than to read
* the page from the media.
*/
SetPageChecked(page);
skipped_read = 1;
} else {
err = do_readpage(page);
if (err) {
unlock_page(page);
page_cache_release(page);
return err;
}
}
SetPageUptodate(page);
ClearPageError(page);
}
err = allocate_budget(c, page, ui, appending);
if (unlikely(err)) {
ubifs_assert(err == -ENOSPC);
/*
* If we skipped reading the page because we were going to
* write all of it, then it is not up to date.
*/
if (skipped_read) {
ClearPageChecked(page);
ClearPageUptodate(page);
}
/*
* Budgeting failed which means it would have to force
* write-back but didn't, because we set the @fast flag in the
* request. Write-back cannot be done now, while we have the
* page locked, because it would deadlock. Unlock and free
* everything and fall-back to slow-path.
*/
if (appending) {
ubifs_assert(mutex_is_locked(&ui->ui_mutex));
mutex_unlock(&ui->ui_mutex);
}
unlock_page(page);
page_cache_release(page);
return write_begin_slow(mapping, pos, len, pagep, flags);
}
/*
* Whee, we acquired budgeting quickly - without involving
* garbage-collection, committing or forcing write-back. We return
* with @ui->ui_mutex locked if we are appending pages, and unlocked
* otherwise. This is an optimization (slightly hacky though).
*/
*pagep = page;
return 0;
}
/**
* cancel_budget - cancel budget.
* @c: UBIFS file-system description object
* @page: page to cancel budget for
* @ui: UBIFS inode object the page belongs to
* @appending: non-zero if the page is appended
*
* This is a helper function for a page write operation. It unlocks the
* @ui->ui_mutex in case of appending.
*/
static void cancel_budget(struct ubifs_info *c, struct page *page,
struct ubifs_inode *ui, int appending)
{
if (appending) {
if (!ui->dirty)
ubifs_release_dirty_inode_budget(c, ui);
mutex_unlock(&ui->ui_mutex);
}
if (!PagePrivate(page)) {
if (PageChecked(page))
release_new_page_budget(c);
else
release_existing_page_budget(c);
}
}
static int ubifs_write_end(struct file *file, struct address_space *mapping,
loff_t pos, unsigned len, unsigned copied,
struct page *page, void *fsdata)
{
struct inode *inode = mapping->host;
struct ubifs_inode *ui = ubifs_inode(inode);
struct ubifs_info *c = inode->i_sb->s_fs_info;
loff_t end_pos = pos + len;
int appending = !!(end_pos > inode->i_size);
dbg_gen("ino %lu, pos %llu, pg %lu, len %u, copied %d, i_size %lld",
inode->i_ino, pos, page->index, len, copied, inode->i_size);
if (unlikely(copied < len && len == PAGE_CACHE_SIZE)) {
/*
* VFS copied less data to the page that it intended and
* declared in its '->write_begin()' call via the @len
* argument. If the page was not up-to-date, and @len was
* @PAGE_CACHE_SIZE, the 'ubifs_write_begin()' function did
* not load it from the media (for optimization reasons). This
* means that part of the page contains garbage. So read the
* page now.
*/
dbg_gen("copied %d instead of %d, read page and repeat",
copied, len);
cancel_budget(c, page, ui, appending);
/*
* Return 0 to force VFS to repeat the whole operation, or the
* error code if 'do_readpage()' fails.
*/
copied = do_readpage(page);
goto out;
}
if (!PagePrivate(page)) {
SetPagePrivate(page);
atomic_long_inc(&c->dirty_pg_cnt);
__set_page_dirty_nobuffers(page);
}
if (appending) {
i_size_write(inode, end_pos);
ui->ui_size = end_pos;
/*
* Note, we do not set @I_DIRTY_PAGES (which means that the
* inode has dirty pages), this has been done in
* '__set_page_dirty_nobuffers()'.
*/
__mark_inode_dirty(inode, I_DIRTY_DATASYNC);
ubifs_assert(mutex_is_locked(&ui->ui_mutex));
mutex_unlock(&ui->ui_mutex);
}
out:
unlock_page(page);
page_cache_release(page);
return copied;
}
/**
* populate_page - copy data nodes into a page for bulk-read.
* @c: UBIFS file-system description object
* @page: page
* @bu: bulk-read information
* @n: next zbranch slot
*
* This function returns %0 on success and a negative error code on failure.
*/
static int populate_page(struct ubifs_info *c, struct page *page,
struct bu_info *bu, int *n)
{
int i = 0, nn = *n, offs = bu->zbranch[0].offs, hole = 0, read = 0;
struct inode *inode = page->mapping->host;
loff_t i_size = i_size_read(inode);
unsigned int page_block;
void *addr, *zaddr;
pgoff_t end_index;
dbg_gen("ino %lu, pg %lu, i_size %lld, flags %#lx",
inode->i_ino, page->index, i_size, page->flags);
addr = zaddr = kmap(page);
end_index = (i_size - 1) >> PAGE_CACHE_SHIFT;
if (!i_size || page->index > end_index) {
hole = 1;
memset(addr, 0, PAGE_CACHE_SIZE);
goto out_hole;
}
page_block = page->index << UBIFS_BLOCKS_PER_PAGE_SHIFT;
while (1) {
int err, len, out_len, dlen;
if (nn >= bu->cnt) {
hole = 1;
memset(addr, 0, UBIFS_BLOCK_SIZE);
} else if (key_block(c, &bu->zbranch[nn].key) == page_block) {
struct ubifs_data_node *dn;
dn = bu->buf + (bu->zbranch[nn].offs - offs);
ubifs_assert(le64_to_cpu(dn->ch.sqnum) >
ubifs_inode(inode)->creat_sqnum);
len = le32_to_cpu(dn->size);
if (len <= 0 || len > UBIFS_BLOCK_SIZE)
goto out_err;
dlen = le32_to_cpu(dn->ch.len) - UBIFS_DATA_NODE_SZ;
out_len = UBIFS_BLOCK_SIZE;
err = ubifs_decompress(&dn->data, dlen, addr, &out_len,
le16_to_cpu(dn->compr_type));
if (err || len != out_len)
goto out_err;
if (len < UBIFS_BLOCK_SIZE)
memset(addr + len, 0, UBIFS_BLOCK_SIZE - len);
nn += 1;
read = (i << UBIFS_BLOCK_SHIFT) + len;
} else if (key_block(c, &bu->zbranch[nn].key) < page_block) {
nn += 1;
continue;
} else {
hole = 1;
memset(addr, 0, UBIFS_BLOCK_SIZE);
}
if (++i >= UBIFS_BLOCKS_PER_PAGE)
break;
addr += UBIFS_BLOCK_SIZE;
page_block += 1;
}
if (end_index == page->index) {
int len = i_size & (PAGE_CACHE_SIZE - 1);
if (len && len < read)
memset(zaddr + len, 0, read - len);
}
out_hole:
if (hole) {
SetPageChecked(page);
dbg_gen("hole");
}
SetPageUptodate(page);
ClearPageError(page);
flush_dcache_page(page);
kunmap(page);
*n = nn;
return 0;
out_err:
ClearPageUptodate(page);
SetPageError(page);
flush_dcache_page(page);
kunmap(page);
ubifs_err("bad data node (block %u, inode %lu)",
page_block, inode->i_ino);
return -EINVAL;
}
/**
* ubifs_do_bulk_read - do bulk-read.
* @c: UBIFS file-system description object
* @bu: bulk-read information
* @page1: first page to read
*
* This function returns %1 if the bulk-read is done, otherwise %0 is returned.
*/
static int ubifs_do_bulk_read(struct ubifs_info *c, struct bu_info *bu,
struct page *page1)
{
pgoff_t offset = page1->index, end_index;
struct address_space *mapping = page1->mapping;
struct inode *inode = mapping->host;
struct ubifs_inode *ui = ubifs_inode(inode);
int err, page_idx, page_cnt, ret = 0, n = 0;
int allocate = bu->buf ? 0 : 1;
loff_t isize;
err = ubifs_tnc_get_bu_keys(c, bu);
if (err)
goto out_warn;
if (bu->eof) {
/* Turn off bulk-read at the end of the file */
ui->read_in_a_row = 1;
ui->bulk_read = 0;
}
page_cnt = bu->blk_cnt >> UBIFS_BLOCKS_PER_PAGE_SHIFT;
if (!page_cnt) {
/*
* This happens when there are multiple blocks per page and the
* blocks for the first page we are looking for, are not
* together. If all the pages were like this, bulk-read would
* reduce performance, so we turn it off for a while.
*/
goto out_bu_off;
}
if (bu->cnt) {
if (allocate) {
/*
* Allocate bulk-read buffer depending on how many data
* nodes we are going to read.
*/
bu->buf_len = bu->zbranch[bu->cnt - 1].offs +
bu->zbranch[bu->cnt - 1].len -
bu->zbranch[0].offs;
ubifs_assert(bu->buf_len > 0);
ubifs_assert(bu->buf_len <= c->leb_size);
bu->buf = kmalloc(bu->buf_len, GFP_NOFS | __GFP_NOWARN);
if (!bu->buf)
goto out_bu_off;
}
err = ubifs_tnc_bulk_read(c, bu);
if (err)
goto out_warn;
}
err = populate_page(c, page1, bu, &n);
if (err)
goto out_warn;
unlock_page(page1);
ret = 1;
isize = i_size_read(inode);
if (isize == 0)
goto out_free;
end_index = ((isize - 1) >> PAGE_CACHE_SHIFT);
for (page_idx = 1; page_idx < page_cnt; page_idx++) {
pgoff_t page_offset = offset + page_idx;
struct page *page;
if (page_offset > end_index)
break;
page = find_or_create_page(mapping, page_offset,
GFP_NOFS | __GFP_COLD);
if (!page)
break;
if (!PageUptodate(page))
err = populate_page(c, page, bu, &n);
unlock_page(page);
page_cache_release(page);
if (err)
break;
}
ui->last_page_read = offset + page_idx - 1;
out_free:
if (allocate)
kfree(bu->buf);
return ret;
out_warn:
ubifs_warn("ignoring error %d and skipping bulk-read", err);
goto out_free;
out_bu_off:
ui->read_in_a_row = ui->bulk_read = 0;
goto out_free;
}
/**
* ubifs_bulk_read - determine whether to bulk-read and, if so, do it.
* @page: page from which to start bulk-read.
*
* Some flash media are capable of reading sequentially at faster rates. UBIFS
* bulk-read facility is designed to take advantage of that, by reading in one
* go consecutive data nodes that are also located consecutively in the same
* LEB. This function returns %1 if a bulk-read is done and %0 otherwise.
*/
static int ubifs_bulk_read(struct page *page)
{
struct inode *inode = page->mapping->host;
struct ubifs_info *c = inode->i_sb->s_fs_info;
struct ubifs_inode *ui = ubifs_inode(inode);
pgoff_t index = page->index, last_page_read = ui->last_page_read;
struct bu_info *bu;
int err = 0, allocated = 0;
ui->last_page_read = index;
if (!c->bulk_read)
return 0;
/*
* Bulk-read is protected by @ui->ui_mutex, but it is an optimization,
* so don't bother if we cannot lock the mutex.
*/
if (!mutex_trylock(&ui->ui_mutex))
return 0;
if (index != last_page_read + 1) {
/* Turn off bulk-read if we stop reading sequentially */
ui->read_in_a_row = 1;
if (ui->bulk_read)
ui->bulk_read = 0;
goto out_unlock;
}
if (!ui->bulk_read) {
ui->read_in_a_row += 1;
if (ui->read_in_a_row < 3)
goto out_unlock;
/* Three reads in a row, so switch on bulk-read */
ui->bulk_read = 1;
}
/*
* If possible, try to use pre-allocated bulk-read information, which
* is protected by @c->bu_mutex.
*/
if (mutex_trylock(&c->bu_mutex))
bu = &c->bu;
else {
bu = kmalloc(sizeof(struct bu_info), GFP_NOFS | __GFP_NOWARN);
if (!bu)
goto out_unlock;
bu->buf = NULL;
allocated = 1;
}
bu->buf_len = c->max_bu_buf_len;
data_key_init(c, &bu->key, inode->i_ino,
page->index << UBIFS_BLOCKS_PER_PAGE_SHIFT);
err = ubifs_do_bulk_read(c, bu, page);
if (!allocated)
mutex_unlock(&c->bu_mutex);
else
kfree(bu);
out_unlock:
mutex_unlock(&ui->ui_mutex);
return err;
}
static int ubifs_readpage(struct file *file, struct page *page)
{
if (ubifs_bulk_read(page))
return 0;
do_readpage(page);
unlock_page(page);
return 0;
}
static int do_writepage(struct page *page, int len)
{
int err = 0, i, blen;
unsigned int block;
void *addr;
union ubifs_key key;
struct inode *inode = page->mapping->host;
struct ubifs_info *c = inode->i_sb->s_fs_info;
#ifdef UBIFS_DEBUG
spin_lock(&ui->ui_lock);
ubifs_assert(page->index <= ui->synced_i_size << PAGE_CACHE_SIZE);
spin_unlock(&ui->ui_lock);
#endif
/* Update radix tree tags */
set_page_writeback(page);
addr = kmap(page);
block = page->index << UBIFS_BLOCKS_PER_PAGE_SHIFT;
i = 0;
while (len) {
blen = min_t(int, len, UBIFS_BLOCK_SIZE);
data_key_init(c, &key, inode->i_ino, block);
err = ubifs_jnl_write_data(c, inode, &key, addr, blen);
if (err)
break;
if (++i >= UBIFS_BLOCKS_PER_PAGE)
break;
block += 1;
addr += blen;
len -= blen;
}
if (err) {
SetPageError(page);
ubifs_err("cannot write page %lu of inode %lu, error %d",
page->index, inode->i_ino, err);
ubifs_ro_mode(c, err);
}
ubifs_assert(PagePrivate(page));
if (PageChecked(page))
release_new_page_budget(c);
else
release_existing_page_budget(c);
atomic_long_dec(&c->dirty_pg_cnt);
ClearPagePrivate(page);
ClearPageChecked(page);
kunmap(page);
unlock_page(page);
end_page_writeback(page);
return err;
}
/*
* When writing-back dirty inodes, VFS first writes-back pages belonging to the
* inode, then the inode itself. For UBIFS this may cause a problem. Consider a
* situation when a we have an inode with size 0, then a megabyte of data is
* appended to the inode, then write-back starts and flushes some amount of the
* dirty pages, the journal becomes full, commit happens and finishes, and then
* an unclean reboot happens. When the file system is mounted next time, the
* inode size would still be 0, but there would be many pages which are beyond
* the inode size, they would be indexed and consume flash space. Because the
* journal has been committed, the replay would not be able to detect this
* situation and correct the inode size. This means UBIFS would have to scan
* whole index and correct all inode sizes, which is long an unacceptable.
*
* To prevent situations like this, UBIFS writes pages back only if they are
* within the last synchronized inode size, i.e. the size which has been
* written to the flash media last time. Otherwise, UBIFS forces inode
* write-back, thus making sure the on-flash inode contains current inode size,
* and then keeps writing pages back.
*
* Some locking issues explanation. 'ubifs_writepage()' first is called with
* the page locked, and it locks @ui_mutex. However, write-back does take inode
* @i_mutex, which means other VFS operations may be run on this inode at the
* same time. And the problematic one is truncation to smaller size, from where
* we have to call 'vmtruncate()', which first changes @inode->i_size, then
* drops the truncated pages. And while dropping the pages, it takes the page
* lock. This means that 'do_truncation()' cannot call 'vmtruncate()' with
* @ui_mutex locked, because it would deadlock with 'ubifs_writepage()'. This
* means that @inode->i_size is changed while @ui_mutex is unlocked.
*
* But in 'ubifs_writepage()' we have to guarantee that we do not write beyond
* inode size. How do we do this if @inode->i_size may became smaller while we
* are in the middle of 'ubifs_writepage()'? The UBIFS solution is the
* @ui->ui_isize "shadow" field which UBIFS uses instead of @inode->i_size
* internally and updates it under @ui_mutex.
*
* Q: why we do not worry that if we race with truncation, we may end up with a
* situation when the inode is truncated while we are in the middle of
* 'do_writepage()', so we do write beyond inode size?
* A: If we are in the middle of 'do_writepage()', truncation would be locked
* on the page lock and it would not write the truncated inode node to the
* journal before we have finished.
*/
static int ubifs_writepage(struct page *page, struct writeback_control *wbc)
{
struct inode *inode = page->mapping->host;
struct ubifs_inode *ui = ubifs_inode(inode);
loff_t i_size = i_size_read(inode), synced_i_size;
pgoff_t end_index = i_size >> PAGE_CACHE_SHIFT;
int err, len = i_size & (PAGE_CACHE_SIZE - 1);
void *kaddr;
dbg_gen("ino %lu, pg %lu, pg flags %#lx",
inode->i_ino, page->index, page->flags);
ubifs_assert(PagePrivate(page));
/* Is the page fully outside @i_size? (truncate in progress) */
if (page->index > end_index || (page->index == end_index && !len)) {
err = 0;
goto out_unlock;
}
spin_lock(&ui->ui_lock);
synced_i_size = ui->synced_i_size;
spin_unlock(&ui->ui_lock);
/* Is the page fully inside @i_size? */
if (page->index < end_index) {
if (page->index >= synced_i_size >> PAGE_CACHE_SHIFT) {
err = inode->i_sb->s_op->write_inode(inode, 1);
if (err)
goto out_unlock;
/*
* The inode has been written, but the write-buffer has
* not been synchronized, so in case of an unclean
* reboot we may end up with some pages beyond inode
* size, but they would be in the journal (because
* commit flushes write buffers) and recovery would deal
* with this.
*/
}
return do_writepage(page, PAGE_CACHE_SIZE);
}
/*
* The page straddles @i_size. It must be zeroed out on each and every
* writepage invocation because it may be mmapped. "A file is mapped
* in multiples of the page size. For a file that is not a multiple of
* the page size, the remaining memory is zeroed when mapped, and
* writes to that region are not written out to the file."
*/
kaddr = kmap_atomic(page, KM_USER0);
memset(kaddr + len, 0, PAGE_CACHE_SIZE - len);
flush_dcache_page(page);
kunmap_atomic(kaddr, KM_USER0);
if (i_size > synced_i_size) {
err = inode->i_sb->s_op->write_inode(inode, 1);
if (err)
goto out_unlock;
}
return do_writepage(page, len);
out_unlock:
unlock_page(page);
return err;
}
/**
* do_attr_changes - change inode attributes.
* @inode: inode to change attributes for
* @attr: describes attributes to change
*/
static void do_attr_changes(struct inode *inode, const struct iattr *attr)
{
if (attr->ia_valid & ATTR_UID)
inode->i_uid = attr->ia_uid;
if (attr->ia_valid & ATTR_GID)
inode->i_gid = attr->ia_gid;
if (attr->ia_valid & ATTR_ATIME)
inode->i_atime = timespec_trunc(attr->ia_atime,
inode->i_sb->s_time_gran);
if (attr->ia_valid & ATTR_MTIME)
inode->i_mtime = timespec_trunc(attr->ia_mtime,
inode->i_sb->s_time_gran);
if (attr->ia_valid & ATTR_CTIME)
inode->i_ctime = timespec_trunc(attr->ia_ctime,
inode->i_sb->s_time_gran);
if (attr->ia_valid & ATTR_MODE) {
umode_t mode = attr->ia_mode;
if (!in_group_p(inode->i_gid) && !capable(CAP_FSETID))
mode &= ~S_ISGID;
inode->i_mode = mode;
}
}
/**
* do_truncation - truncate an inode.
* @c: UBIFS file-system description object
* @inode: inode to truncate
* @attr: inode attribute changes description
*
* This function implements VFS '->setattr()' call when the inode is truncated
* to a smaller size. Returns zero in case of success and a negative error code
* in case of failure.
*/
static int do_truncation(struct ubifs_info *c, struct inode *inode,
const struct iattr *attr)
{
int err;
struct ubifs_budget_req req;
loff_t old_size = inode->i_size, new_size = attr->ia_size;
int offset = new_size & (UBIFS_BLOCK_SIZE - 1), budgeted = 1;
struct ubifs_inode *ui = ubifs_inode(inode);
dbg_gen("ino %lu, size %lld -> %lld", inode->i_ino, old_size, new_size);
memset(&req, 0, sizeof(struct ubifs_budget_req));
/*
* If this is truncation to a smaller size, and we do not truncate on a
* block boundary, budget for changing one data block, because the last
* block will be re-written.
*/
if (new_size & (UBIFS_BLOCK_SIZE - 1))
req.dirtied_page = 1;
req.dirtied_ino = 1;
/* A funny way to budget for truncation node */
req.dirtied_ino_d = UBIFS_TRUN_NODE_SZ;
err = ubifs_budget_space(c, &req);
if (err) {
/*
* Treat truncations to zero as deletion and always allow them,
* just like we do for '->unlink()'.
*/
if (new_size || err != -ENOSPC)
return err;
budgeted = 0;
}
err = vmtruncate(inode, new_size);
if (err)
goto out_budg;
if (offset) {
pgoff_t index = new_size >> PAGE_CACHE_SHIFT;
struct page *page;
page = find_lock_page(inode->i_mapping, index);
if (page) {
if (PageDirty(page)) {
/*
* 'ubifs_jnl_truncate()' will try to truncate
* the last data node, but it contains
* out-of-date data because the page is dirty.
* Write the page now, so that
* 'ubifs_jnl_truncate()' will see an already
* truncated (and up to date) data node.
*/
ubifs_assert(PagePrivate(page));
clear_page_dirty_for_io(page);
if (UBIFS_BLOCKS_PER_PAGE_SHIFT)
offset = new_size &
(PAGE_CACHE_SIZE - 1);
err = do_writepage(page, offset);
page_cache_release(page);
if (err)
goto out_budg;
/*
* We could now tell 'ubifs_jnl_truncate()' not
* to read the last block.
*/
} else {
/*
* We could 'kmap()' the page and pass the data
* to 'ubifs_jnl_truncate()' to save it from
* having to read it.
*/
unlock_page(page);
page_cache_release(page);
}
}
}
mutex_lock(&ui->ui_mutex);
ui->ui_size = inode->i_size;
/* Truncation changes inode [mc]time */
inode->i_mtime = inode->i_ctime = ubifs_current_time(inode);
/* Other attributes may be changed at the same time as well */
do_attr_changes(inode, attr);
err = ubifs_jnl_truncate(c, inode, old_size, new_size);
mutex_unlock(&ui->ui_mutex);
out_budg:
if (budgeted)
ubifs_release_budget(c, &req);
else {
c->nospace = c->nospace_rp = 0;
smp_wmb();
}
return err;
}
/**
* do_setattr - change inode attributes.
* @c: UBIFS file-system description object
* @inode: inode to change attributes for
* @attr: inode attribute changes description
*
* This function implements VFS '->setattr()' call for all cases except
* truncations to smaller size. Returns zero in case of success and a negative
* error code in case of failure.
*/
static int do_setattr(struct ubifs_info *c, struct inode *inode,
const struct iattr *attr)
{
int err, release;
loff_t new_size = attr->ia_size;
struct ubifs_inode *ui = ubifs_inode(inode);
struct ubifs_budget_req req = { .dirtied_ino = 1,
.dirtied_ino_d = ALIGN(ui->data_len, 8) };
err = ubifs_budget_space(c, &req);
if (err)
return err;
if (attr->ia_valid & ATTR_SIZE) {
dbg_gen("size %lld -> %lld", inode->i_size, new_size);
err = vmtruncate(inode, new_size);
if (err)
goto out;
}
mutex_lock(&ui->ui_mutex);
if (attr->ia_valid & ATTR_SIZE) {
/* Truncation changes inode [mc]time */
inode->i_mtime = inode->i_ctime = ubifs_current_time(inode);
/* 'vmtruncate()' changed @i_size, update @ui_size */
ui->ui_size = inode->i_size;
}
do_attr_changes(inode, attr);
release = ui->dirty;
if (attr->ia_valid & ATTR_SIZE)
/*
* Inode length changed, so we have to make sure
* @I_DIRTY_DATASYNC is set.
*/
__mark_inode_dirty(inode, I_DIRTY_SYNC | I_DIRTY_DATASYNC);
else
mark_inode_dirty_sync(inode);
mutex_unlock(&ui->ui_mutex);
if (release)
ubifs_release_budget(c, &req);
if (IS_SYNC(inode))
err = inode->i_sb->s_op->write_inode(inode, 1);
return err;
out:
ubifs_release_budget(c, &req);
return err;
}
int ubifs_setattr(struct dentry *dentry, struct iattr *attr)
{
int err;
struct inode *inode = dentry->d_inode;
struct ubifs_info *c = inode->i_sb->s_fs_info;
dbg_gen("ino %lu, mode %#x, ia_valid %#x",
inode->i_ino, inode->i_mode, attr->ia_valid);
err = inode_change_ok(inode, attr);
if (err)
return err;
err = dbg_check_synced_i_size(inode);
if (err)
return err;
if ((attr->ia_valid & ATTR_SIZE) && attr->ia_size < inode->i_size)
/* Truncation to a smaller size */
err = do_truncation(c, inode, attr);
else
err = do_setattr(c, inode, attr);
return err;
}
static void ubifs_invalidatepage(struct page *page, unsigned long offset)
{
struct inode *inode = page->mapping->host;
struct ubifs_info *c = inode->i_sb->s_fs_info;
ubifs_assert(PagePrivate(page));
if (offset)
/* Partial page remains dirty */
return;
if (PageChecked(page))
release_new_page_budget(c);
else
release_existing_page_budget(c);
atomic_long_dec(&c->dirty_pg_cnt);
ClearPagePrivate(page);
ClearPageChecked(page);
}
static void *ubifs_follow_link(struct dentry *dentry, struct nameidata *nd)
{
struct ubifs_inode *ui = ubifs_inode(dentry->d_inode);
nd_set_link(nd, ui->data);
return NULL;
}
int ubifs_fsync(struct file *file, struct dentry *dentry, int datasync)
{
struct inode *inode = dentry->d_inode;
struct ubifs_info *c = inode->i_sb->s_fs_info;
int err;
dbg_gen("syncing inode %lu", inode->i_ino);
/*
* VFS has already synchronized dirty pages for this inode. Synchronize
* the inode unless this is a 'datasync()' call.
*/
if (!datasync || (inode->i_state & I_DIRTY_DATASYNC)) {
err = inode->i_sb->s_op->write_inode(inode, 1);
if (err)
return err;
}
/*
* Nodes related to this inode may still sit in a write-buffer. Flush
* them.
*/
err = ubifs_sync_wbufs_by_inode(c, inode);
if (err)
return err;
return 0;
}
/**
* mctime_update_needed - check if mtime or ctime update is needed.
* @inode: the inode to do the check for
* @now: current time
*
* This helper function checks if the inode mtime/ctime should be updated or
* not. If current values of the time-stamps are within the UBIFS inode time
* granularity, they are not updated. This is an optimization.
*/
static inline int mctime_update_needed(const struct inode *inode,
const struct timespec *now)
{
if (!timespec_equal(&inode->i_mtime, now) ||
!timespec_equal(&inode->i_ctime, now))
return 1;
return 0;
}
/**
* update_ctime - update mtime and ctime of an inode.
* @c: UBIFS file-system description object
* @inode: inode to update
*
* This function updates mtime and ctime of the inode if it is not equivalent to
* current time. Returns zero in case of success and a negative error code in
* case of failure.
*/
static int update_mctime(struct ubifs_info *c, struct inode *inode)
{
struct timespec now = ubifs_current_time(inode);
struct ubifs_inode *ui = ubifs_inode(inode);
if (mctime_update_needed(inode, &now)) {
int err, release;
struct ubifs_budget_req req = { .dirtied_ino = 1,
.dirtied_ino_d = ALIGN(ui->data_len, 8) };
err = ubifs_budget_space(c, &req);
if (err)
return err;
mutex_lock(&ui->ui_mutex);
inode->i_mtime = inode->i_ctime = ubifs_current_time(inode);
release = ui->dirty;
mark_inode_dirty_sync(inode);
mutex_unlock(&ui->ui_mutex);
if (release)
ubifs_release_budget(c, &req);
}
return 0;
}
static ssize_t ubifs_aio_write(struct kiocb *iocb, const struct iovec *iov,
unsigned long nr_segs, loff_t pos)
{
int err;
ssize_t ret;
struct inode *inode = iocb->ki_filp->f_mapping->host;
struct ubifs_info *c = inode->i_sb->s_fs_info;
err = update_mctime(c, inode);
if (err)
return err;
ret = generic_file_aio_write(iocb, iov, nr_segs, pos);
if (ret < 0)
return ret;
if (ret > 0 && (IS_SYNC(inode) || iocb->ki_filp->f_flags & O_SYNC)) {
err = ubifs_sync_wbufs_by_inode(c, inode);
if (err)
return err;
}
return ret;
}
static int ubifs_set_page_dirty(struct page *page)
{
int ret;
ret = __set_page_dirty_nobuffers(page);
/*
* An attempt to dirty a page without budgeting for it - should not
* happen.
*/
ubifs_assert(ret == 0);
return ret;
}
static int ubifs_releasepage(struct page *page, gfp_t unused_gfp_flags)
{
/*
* An attempt to release a dirty page without budgeting for it - should
* not happen.
*/
if (PageWriteback(page))
return 0;
ubifs_assert(PagePrivate(page));
ubifs_assert(0);
ClearPagePrivate(page);
ClearPageChecked(page);
return 1;
}
/*
* mmap()d file has taken write protection fault and is being made
* writable. UBIFS must ensure page is budgeted for.
*/
static int ubifs_vm_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
{
struct page *page = vmf->page;
struct inode *inode = vma->vm_file->f_path.dentry->d_inode;
struct ubifs_info *c = inode->i_sb->s_fs_info;
struct timespec now = ubifs_current_time(inode);
struct ubifs_budget_req req = { .new_page = 1 };
int err, update_time;
dbg_gen("ino %lu, pg %lu, i_size %lld", inode->i_ino, page->index,
i_size_read(inode));
ubifs_assert(!(inode->i_sb->s_flags & MS_RDONLY));
if (unlikely(c->ro_media))
return VM_FAULT_SIGBUS; /* -EROFS */
/*
* We have not locked @page so far so we may budget for changing the
* page. Note, we cannot do this after we locked the page, because
* budgeting may cause write-back which would cause deadlock.
*
* At the moment we do not know whether the page is dirty or not, so we
* assume that it is not and budget for a new page. We could look at
* the @PG_private flag and figure this out, but we may race with write
* back and the page state may change by the time we lock it, so this
* would need additional care. We do not bother with this at the
* moment, although it might be good idea to do. Instead, we allocate
* budget for a new page and amend it later on if the page was in fact
* dirty.
*
* The budgeting-related logic of this function is similar to what we
* do in 'ubifs_write_begin()' and 'ubifs_write_end()'. Glance there
* for more comments.
*/
update_time = mctime_update_needed(inode, &now);
if (update_time)
/*
* We have to change inode time stamp which requires extra
* budgeting.
*/
req.dirtied_ino = 1;
err = ubifs_budget_space(c, &req);
if (unlikely(err)) {
if (err == -ENOSPC)
ubifs_warn("out of space for mmapped file "
"(inode number %lu)", inode->i_ino);
return VM_FAULT_SIGBUS;
}
lock_page(page);
if (unlikely(page->mapping != inode->i_mapping ||
page_offset(page) > i_size_read(inode))) {
/* Page got truncated out from underneath us */
err = -EINVAL;
goto out_unlock;
}
if (PagePrivate(page))
release_new_page_budget(c);
else {
if (!PageChecked(page))
ubifs_convert_page_budget(c);
SetPagePrivate(page);
atomic_long_inc(&c->dirty_pg_cnt);
__set_page_dirty_nobuffers(page);
}
if (update_time) {
int release;
struct ubifs_inode *ui = ubifs_inode(inode);
mutex_lock(&ui->ui_mutex);
inode->i_mtime = inode->i_ctime = ubifs_current_time(inode);
release = ui->dirty;
mark_inode_dirty_sync(inode);
mutex_unlock(&ui->ui_mutex);
if (release)
ubifs_release_dirty_inode_budget(c, ui);
}
unlock_page(page);
return 0;
out_unlock:
unlock_page(page);
ubifs_release_budget(c, &req);
if (err)
err = VM_FAULT_SIGBUS;
return err;
}
static const struct vm_operations_struct ubifs_file_vm_ops = {
.fault = filemap_fault,
.page_mkwrite = ubifs_vm_page_mkwrite,
};
static int ubifs_file_mmap(struct file *file, struct vm_area_struct *vma)
{
int err;
/* 'generic_file_mmap()' takes care of NOMMU case */
err = generic_file_mmap(file, vma);
if (err)
return err;
vma->vm_ops = &ubifs_file_vm_ops;
return 0;
}
const struct address_space_operations ubifs_file_address_operations = {
.readpage = ubifs_readpage,
.writepage = ubifs_writepage,
.write_begin = ubifs_write_begin,
.write_end = ubifs_write_end,
.invalidatepage = ubifs_invalidatepage,
.set_page_dirty = ubifs_set_page_dirty,
.releasepage = ubifs_releasepage,
};
const struct inode_operations ubifs_file_inode_operations = {
.setattr = ubifs_setattr,
.getattr = ubifs_getattr,
#ifdef CONFIG_UBIFS_FS_XATTR
.setxattr = ubifs_setxattr,
.getxattr = ubifs_getxattr,
.listxattr = ubifs_listxattr,
.removexattr = ubifs_removexattr,
#endif
};
const struct inode_operations ubifs_symlink_inode_operations = {
.readlink = generic_readlink,
.follow_link = ubifs_follow_link,
.setattr = ubifs_setattr,
.getattr = ubifs_getattr,
};
const struct file_operations ubifs_file_operations = {
.llseek = generic_file_llseek,
.read = do_sync_read,
.write = do_sync_write,
.aio_read = generic_file_aio_read,
.aio_write = ubifs_aio_write,
.mmap = ubifs_file_mmap,
.fsync = ubifs_fsync,
.unlocked_ioctl = ubifs_ioctl,
.splice_read = generic_file_splice_read,
.splice_write = generic_file_splice_write,
#ifdef CONFIG_COMPAT
.compat_ioctl = ubifs_compat_ioctl,
#endif
};
| gpl-2.0 |
coredumb/linux-grsecurity | drivers/staging/lustre/lnet/selftest/conctl.c | 355 | 22379 | /*
* GPL HEADER START
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 only,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is included
* in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; If not, see
* http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*
* GPL HEADER END
*/
/*
* Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
* Use is subject to license terms.
*
* Copyright (c) 2012, Intel Corporation.
*/
/*
* This file is part of Lustre, http://www.lustre.org/
* Lustre is a trademark of Sun Microsystems, Inc.
*
* lnet/selftest/conctl.c
*
* IOC handle in kernel
*
* Author: Liang Zhen <liangzhen@clusterfs.com>
*/
#include <linux/libcfs/libcfs.h>
#include <linux/lnet/lib-lnet.h>
#include <linux/lnet/lnetst.h>
#include "console.h"
int
lst_session_new_ioctl(lstio_session_new_args_t *args)
{
char *name;
int rc;
if (args->lstio_ses_idp == NULL || /* address for output sid */
args->lstio_ses_key == 0 || /* no key is specified */
args->lstio_ses_namep == NULL || /* session name */
args->lstio_ses_nmlen <= 0 ||
args->lstio_ses_nmlen > LST_NAME_SIZE)
return -EINVAL;
LIBCFS_ALLOC(name, args->lstio_ses_nmlen + 1);
if (name == NULL)
return -ENOMEM;
if (copy_from_user(name,
args->lstio_ses_namep,
args->lstio_ses_nmlen)) {
LIBCFS_FREE(name, args->lstio_ses_nmlen + 1);
return -EFAULT;
}
name[args->lstio_ses_nmlen] = 0;
rc = lstcon_session_new(name,
args->lstio_ses_key,
args->lstio_ses_feats,
args->lstio_ses_force,
args->lstio_ses_timeout,
args->lstio_ses_idp);
LIBCFS_FREE(name, args->lstio_ses_nmlen + 1);
return rc;
}
int
lst_session_end_ioctl(lstio_session_end_args_t *args)
{
if (args->lstio_ses_key != console_session.ses_key)
return -EACCES;
return lstcon_session_end();
}
int
lst_session_info_ioctl(lstio_session_info_args_t *args)
{
/* no checking of key */
if (args->lstio_ses_idp == NULL || /* address for output sid */
args->lstio_ses_keyp == NULL || /* address for output key */
args->lstio_ses_featp == NULL || /* address for output features */
args->lstio_ses_ndinfo == NULL || /* address for output ndinfo */
args->lstio_ses_namep == NULL || /* address for output name */
args->lstio_ses_nmlen <= 0 ||
args->lstio_ses_nmlen > LST_NAME_SIZE)
return -EINVAL;
return lstcon_session_info(args->lstio_ses_idp,
args->lstio_ses_keyp,
args->lstio_ses_featp,
args->lstio_ses_ndinfo,
args->lstio_ses_namep,
args->lstio_ses_nmlen);
}
int
lst_debug_ioctl(lstio_debug_args_t *args)
{
char *name = NULL;
int client = 1;
int rc;
if (args->lstio_dbg_key != console_session.ses_key)
return -EACCES;
if (args->lstio_dbg_resultp == NULL)
return -EINVAL;
if (args->lstio_dbg_namep != NULL && /* name of batch/group */
(args->lstio_dbg_nmlen <= 0 ||
args->lstio_dbg_nmlen > LST_NAME_SIZE))
return -EINVAL;
if (args->lstio_dbg_namep != NULL) {
LIBCFS_ALLOC(name, args->lstio_dbg_nmlen + 1);
if (name == NULL)
return -ENOMEM;
if (copy_from_user(name, args->lstio_dbg_namep,
args->lstio_dbg_nmlen)) {
LIBCFS_FREE(name, args->lstio_dbg_nmlen + 1);
return -EFAULT;
}
name[args->lstio_dbg_nmlen] = 0;
}
rc = -EINVAL;
switch (args->lstio_dbg_type) {
case LST_OPC_SESSION:
rc = lstcon_session_debug(args->lstio_dbg_timeout,
args->lstio_dbg_resultp);
break;
case LST_OPC_BATCHSRV:
client = 0;
case LST_OPC_BATCHCLI:
if (name == NULL)
goto out;
rc = lstcon_batch_debug(args->lstio_dbg_timeout,
name, client, args->lstio_dbg_resultp);
break;
case LST_OPC_GROUP:
if (name == NULL)
goto out;
rc = lstcon_group_debug(args->lstio_dbg_timeout,
name, args->lstio_dbg_resultp);
break;
case LST_OPC_NODES:
if (args->lstio_dbg_count <= 0 ||
args->lstio_dbg_idsp == NULL)
goto out;
rc = lstcon_nodes_debug(args->lstio_dbg_timeout,
args->lstio_dbg_count,
args->lstio_dbg_idsp,
args->lstio_dbg_resultp);
break;
default:
break;
}
out:
if (name != NULL)
LIBCFS_FREE(name, args->lstio_dbg_nmlen + 1);
return rc;
}
int
lst_group_add_ioctl(lstio_group_add_args_t *args)
{
char *name;
int rc;
if (args->lstio_grp_key != console_session.ses_key)
return -EACCES;
if (args->lstio_grp_namep == NULL||
args->lstio_grp_nmlen <= 0 ||
args->lstio_grp_nmlen > LST_NAME_SIZE)
return -EINVAL;
LIBCFS_ALLOC(name, args->lstio_grp_nmlen + 1);
if (name == NULL)
return -ENOMEM;
if (copy_from_user(name,
args->lstio_grp_namep,
args->lstio_grp_nmlen)) {
LIBCFS_FREE(name, args->lstio_grp_nmlen);
return -EFAULT;
}
name[args->lstio_grp_nmlen] = 0;
rc = lstcon_group_add(name);
LIBCFS_FREE(name, args->lstio_grp_nmlen + 1);
return rc;
}
int
lst_group_del_ioctl(lstio_group_del_args_t *args)
{
int rc;
char *name;
if (args->lstio_grp_key != console_session.ses_key)
return -EACCES;
if (args->lstio_grp_namep == NULL ||
args->lstio_grp_nmlen <= 0 ||
args->lstio_grp_nmlen > LST_NAME_SIZE)
return -EINVAL;
LIBCFS_ALLOC(name, args->lstio_grp_nmlen + 1);
if (name == NULL)
return -ENOMEM;
if (copy_from_user(name,
args->lstio_grp_namep,
args->lstio_grp_nmlen)) {
LIBCFS_FREE(name, args->lstio_grp_nmlen + 1);
return -EFAULT;
}
name[args->lstio_grp_nmlen] = 0;
rc = lstcon_group_del(name);
LIBCFS_FREE(name, args->lstio_grp_nmlen + 1);
return rc;
}
int
lst_group_update_ioctl(lstio_group_update_args_t *args)
{
int rc;
char *name;
if (args->lstio_grp_key != console_session.ses_key)
return -EACCES;
if (args->lstio_grp_resultp == NULL ||
args->lstio_grp_namep == NULL ||
args->lstio_grp_nmlen <= 0 ||
args->lstio_grp_nmlen > LST_NAME_SIZE)
return -EINVAL;
LIBCFS_ALLOC(name, args->lstio_grp_nmlen + 1);
if (name == NULL)
return -ENOMEM;
if (copy_from_user(name,
args->lstio_grp_namep,
args->lstio_grp_nmlen)) {
LIBCFS_FREE(name, args->lstio_grp_nmlen + 1);
return -EFAULT;
}
name[args->lstio_grp_nmlen] = 0;
switch (args->lstio_grp_opc) {
case LST_GROUP_CLEAN:
rc = lstcon_group_clean(name, args->lstio_grp_args);
break;
case LST_GROUP_REFRESH:
rc = lstcon_group_refresh(name, args->lstio_grp_resultp);
break;
case LST_GROUP_RMND:
if (args->lstio_grp_count <= 0 ||
args->lstio_grp_idsp == NULL) {
rc = -EINVAL;
break;
}
rc = lstcon_nodes_remove(name, args->lstio_grp_count,
args->lstio_grp_idsp,
args->lstio_grp_resultp);
break;
default:
rc = -EINVAL;
break;
}
LIBCFS_FREE(name, args->lstio_grp_nmlen + 1);
return rc;
}
int
lst_nodes_add_ioctl(lstio_group_nodes_args_t *args)
{
unsigned feats;
int rc;
char *name;
if (args->lstio_grp_key != console_session.ses_key)
return -EACCES;
if (args->lstio_grp_idsp == NULL || /* array of ids */
args->lstio_grp_count <= 0 ||
args->lstio_grp_resultp == NULL ||
args->lstio_grp_featp == NULL ||
args->lstio_grp_namep == NULL ||
args->lstio_grp_nmlen <= 0 ||
args->lstio_grp_nmlen > LST_NAME_SIZE)
return -EINVAL;
LIBCFS_ALLOC(name, args->lstio_grp_nmlen + 1);
if (name == NULL)
return -ENOMEM;
if (copy_from_user(name, args->lstio_grp_namep,
args->lstio_grp_nmlen)) {
LIBCFS_FREE(name, args->lstio_grp_nmlen + 1);
return -EFAULT;
}
name[args->lstio_grp_nmlen] = 0;
rc = lstcon_nodes_add(name, args->lstio_grp_count,
args->lstio_grp_idsp, &feats,
args->lstio_grp_resultp);
LIBCFS_FREE(name, args->lstio_grp_nmlen + 1);
if (rc == 0 &&
copy_to_user(args->lstio_grp_featp, &feats, sizeof(feats))) {
return -EINVAL;
}
return rc;
}
int
lst_group_list_ioctl(lstio_group_list_args_t *args)
{
if (args->lstio_grp_key != console_session.ses_key)
return -EACCES;
if (args->lstio_grp_idx < 0 ||
args->lstio_grp_namep == NULL ||
args->lstio_grp_nmlen <= 0 ||
args->lstio_grp_nmlen > LST_NAME_SIZE)
return -EINVAL;
return lstcon_group_list(args->lstio_grp_idx,
args->lstio_grp_nmlen,
args->lstio_grp_namep);
}
int
lst_group_info_ioctl(lstio_group_info_args_t *args)
{
char *name;
int ndent;
int index;
int rc;
if (args->lstio_grp_key != console_session.ses_key)
return -EACCES;
if (args->lstio_grp_namep == NULL ||
args->lstio_grp_nmlen <= 0 ||
args->lstio_grp_nmlen > LST_NAME_SIZE)
return -EINVAL;
if (args->lstio_grp_entp == NULL && /* output: group entry */
args->lstio_grp_dentsp == NULL) /* output: node entry */
return -EINVAL;
if (args->lstio_grp_dentsp != NULL) { /* have node entry */
if (args->lstio_grp_idxp == NULL || /* node index */
args->lstio_grp_ndentp == NULL) /* # of node entry */
return -EINVAL;
if (copy_from_user(&ndent, args->lstio_grp_ndentp,
sizeof(ndent)) ||
copy_from_user(&index, args->lstio_grp_idxp,
sizeof(index)))
return -EFAULT;
if (ndent <= 0 || index < 0)
return -EINVAL;
}
LIBCFS_ALLOC(name, args->lstio_grp_nmlen + 1);
if (name == NULL)
return -ENOMEM;
if (copy_from_user(name,
args->lstio_grp_namep,
args->lstio_grp_nmlen)) {
LIBCFS_FREE(name, args->lstio_grp_nmlen + 1);
return -EFAULT;
}
name[args->lstio_grp_nmlen] = 0;
rc = lstcon_group_info(name, args->lstio_grp_entp,
&index, &ndent, args->lstio_grp_dentsp);
LIBCFS_FREE(name, args->lstio_grp_nmlen + 1);
if (rc != 0)
return rc;
if (args->lstio_grp_dentsp != NULL &&
(copy_to_user(args->lstio_grp_idxp, &index, sizeof(index)) ||
copy_to_user(args->lstio_grp_ndentp, &ndent, sizeof(ndent))))
rc = -EFAULT;
return 0;
}
int
lst_batch_add_ioctl(lstio_batch_add_args_t *args)
{
int rc;
char *name;
if (args->lstio_bat_key != console_session.ses_key)
return -EACCES;
if (args->lstio_bat_namep == NULL ||
args->lstio_bat_nmlen <= 0 ||
args->lstio_bat_nmlen > LST_NAME_SIZE)
return -EINVAL;
LIBCFS_ALLOC(name, args->lstio_bat_nmlen + 1);
if (name == NULL)
return -ENOMEM;
if (copy_from_user(name,
args->lstio_bat_namep,
args->lstio_bat_nmlen)) {
LIBCFS_FREE(name, args->lstio_bat_nmlen + 1);
return -EFAULT;
}
name[args->lstio_bat_nmlen] = 0;
rc = lstcon_batch_add(name);
LIBCFS_FREE(name, args->lstio_bat_nmlen + 1);
return rc;
}
int
lst_batch_run_ioctl(lstio_batch_run_args_t *args)
{
int rc;
char *name;
if (args->lstio_bat_key != console_session.ses_key)
return -EACCES;
if (args->lstio_bat_namep == NULL ||
args->lstio_bat_nmlen <= 0 ||
args->lstio_bat_nmlen > LST_NAME_SIZE)
return -EINVAL;
LIBCFS_ALLOC(name, args->lstio_bat_nmlen + 1);
if (name == NULL)
return -ENOMEM;
if (copy_from_user(name,
args->lstio_bat_namep,
args->lstio_bat_nmlen)) {
LIBCFS_FREE(name, args->lstio_bat_nmlen + 1);
return -EFAULT;
}
name[args->lstio_bat_nmlen] = 0;
rc = lstcon_batch_run(name, args->lstio_bat_timeout,
args->lstio_bat_resultp);
LIBCFS_FREE(name, args->lstio_bat_nmlen + 1);
return rc;
}
int
lst_batch_stop_ioctl(lstio_batch_stop_args_t *args)
{
int rc;
char *name;
if (args->lstio_bat_key != console_session.ses_key)
return -EACCES;
if (args->lstio_bat_resultp == NULL ||
args->lstio_bat_namep == NULL ||
args->lstio_bat_nmlen <= 0 ||
args->lstio_bat_nmlen > LST_NAME_SIZE)
return -EINVAL;
LIBCFS_ALLOC(name, args->lstio_bat_nmlen + 1);
if (name == NULL)
return -ENOMEM;
if (copy_from_user(name,
args->lstio_bat_namep,
args->lstio_bat_nmlen)) {
LIBCFS_FREE(name, args->lstio_bat_nmlen + 1);
return -EFAULT;
}
name[args->lstio_bat_nmlen] = 0;
rc = lstcon_batch_stop(name, args->lstio_bat_force,
args->lstio_bat_resultp);
LIBCFS_FREE(name, args->lstio_bat_nmlen + 1);
return rc;
}
int
lst_batch_query_ioctl(lstio_batch_query_args_t *args)
{
char *name;
int rc;
if (args->lstio_bat_key != console_session.ses_key)
return -EACCES;
if (args->lstio_bat_resultp == NULL ||
args->lstio_bat_namep == NULL ||
args->lstio_bat_nmlen <= 0 ||
args->lstio_bat_nmlen > LST_NAME_SIZE)
return -EINVAL;
if (args->lstio_bat_testidx < 0)
return -EINVAL;
LIBCFS_ALLOC(name, args->lstio_bat_nmlen + 1);
if (name == NULL)
return -ENOMEM;
if (copy_from_user(name,
args->lstio_bat_namep,
args->lstio_bat_nmlen)) {
LIBCFS_FREE(name, args->lstio_bat_nmlen + 1);
return -EFAULT;
}
name[args->lstio_bat_nmlen] = 0;
rc = lstcon_test_batch_query(name,
args->lstio_bat_testidx,
args->lstio_bat_client,
args->lstio_bat_timeout,
args->lstio_bat_resultp);
LIBCFS_FREE(name, args->lstio_bat_nmlen + 1);
return rc;
}
int
lst_batch_list_ioctl(lstio_batch_list_args_t *args)
{
if (args->lstio_bat_key != console_session.ses_key)
return -EACCES;
if (args->lstio_bat_idx < 0 ||
args->lstio_bat_namep == NULL ||
args->lstio_bat_nmlen <= 0 ||
args->lstio_bat_nmlen > LST_NAME_SIZE)
return -EINVAL;
return lstcon_batch_list(args->lstio_bat_idx,
args->lstio_bat_nmlen,
args->lstio_bat_namep);
}
int
lst_batch_info_ioctl(lstio_batch_info_args_t *args)
{
char *name;
int rc;
int index;
int ndent;
if (args->lstio_bat_key != console_session.ses_key)
return -EACCES;
if (args->lstio_bat_namep == NULL || /* batch name */
args->lstio_bat_nmlen <= 0 ||
args->lstio_bat_nmlen > LST_NAME_SIZE)
return -EINVAL;
if (args->lstio_bat_entp == NULL && /* output: batch entry */
args->lstio_bat_dentsp == NULL) /* output: node entry */
return -EINVAL;
if (args->lstio_bat_dentsp != NULL) { /* have node entry */
if (args->lstio_bat_idxp == NULL || /* node index */
args->lstio_bat_ndentp == NULL) /* # of node entry */
return -EINVAL;
if (copy_from_user(&index, args->lstio_bat_idxp,
sizeof(index)) ||
copy_from_user(&ndent, args->lstio_bat_ndentp,
sizeof(ndent)))
return -EFAULT;
if (ndent <= 0 || index < 0)
return -EINVAL;
}
LIBCFS_ALLOC(name, args->lstio_bat_nmlen + 1);
if (name == NULL)
return -ENOMEM;
if (copy_from_user(name,
args->lstio_bat_namep, args->lstio_bat_nmlen)) {
LIBCFS_FREE(name, args->lstio_bat_nmlen + 1);
return -EFAULT;
}
name[args->lstio_bat_nmlen] = 0;
rc = lstcon_batch_info(name,
args->lstio_bat_entp, args->lstio_bat_server,
args->lstio_bat_testidx, &index, &ndent,
args->lstio_bat_dentsp);
LIBCFS_FREE(name, args->lstio_bat_nmlen + 1);
if (rc != 0)
return rc;
if (args->lstio_bat_dentsp != NULL &&
(copy_to_user(args->lstio_bat_idxp, &index, sizeof(index)) ||
copy_to_user(args->lstio_bat_ndentp, &ndent, sizeof(ndent))))
rc = -EFAULT;
return rc;
}
int
lst_stat_query_ioctl(lstio_stat_args_t *args)
{
int rc;
char *name;
/* TODO: not finished */
if (args->lstio_sta_key != console_session.ses_key)
return -EACCES;
if (args->lstio_sta_resultp == NULL ||
(args->lstio_sta_namep == NULL &&
args->lstio_sta_idsp == NULL) ||
args->lstio_sta_nmlen <= 0 ||
args->lstio_sta_nmlen > LST_NAME_SIZE)
return -EINVAL;
if (args->lstio_sta_idsp != NULL &&
args->lstio_sta_count <= 0)
return -EINVAL;
LIBCFS_ALLOC(name, args->lstio_sta_nmlen + 1);
if (name == NULL)
return -ENOMEM;
if (copy_from_user(name, args->lstio_sta_namep,
args->lstio_sta_nmlen)) {
LIBCFS_FREE(name, args->lstio_sta_nmlen + 1);
return -EFAULT;
}
if (args->lstio_sta_idsp == NULL) {
rc = lstcon_group_stat(name, args->lstio_sta_timeout,
args->lstio_sta_resultp);
} else {
rc = lstcon_nodes_stat(args->lstio_sta_count,
args->lstio_sta_idsp,
args->lstio_sta_timeout,
args->lstio_sta_resultp);
}
LIBCFS_FREE(name, args->lstio_sta_nmlen + 1);
return rc;
}
int lst_test_add_ioctl(lstio_test_args_t *args)
{
char *batch_name;
char *src_name = NULL;
char *dst_name = NULL;
void *param = NULL;
int ret = 0;
int rc = -ENOMEM;
if (args->lstio_tes_resultp == NULL ||
args->lstio_tes_retp == NULL ||
args->lstio_tes_bat_name == NULL || /* no specified batch */
args->lstio_tes_bat_nmlen <= 0 ||
args->lstio_tes_bat_nmlen > LST_NAME_SIZE ||
args->lstio_tes_sgrp_name == NULL || /* no source group */
args->lstio_tes_sgrp_nmlen <= 0 ||
args->lstio_tes_sgrp_nmlen > LST_NAME_SIZE ||
args->lstio_tes_dgrp_name == NULL || /* no target group */
args->lstio_tes_dgrp_nmlen <= 0 ||
args->lstio_tes_dgrp_nmlen > LST_NAME_SIZE)
return -EINVAL;
if (args->lstio_tes_loop == 0 || /* negative is infinite */
args->lstio_tes_concur <= 0 ||
args->lstio_tes_dist <= 0 ||
args->lstio_tes_span <= 0)
return -EINVAL;
/* have parameter, check if parameter length is valid */
if (args->lstio_tes_param != NULL &&
(args->lstio_tes_param_len <= 0 ||
args->lstio_tes_param_len > PAGE_CACHE_SIZE - sizeof(lstcon_test_t)))
return -EINVAL;
LIBCFS_ALLOC(batch_name, args->lstio_tes_bat_nmlen + 1);
if (batch_name == NULL)
return rc;
LIBCFS_ALLOC(src_name, args->lstio_tes_sgrp_nmlen + 1);
if (src_name == NULL)
goto out;
LIBCFS_ALLOC(dst_name, args->lstio_tes_dgrp_nmlen + 1);
if (dst_name == NULL)
goto out;
if (args->lstio_tes_param != NULL) {
LIBCFS_ALLOC(param, args->lstio_tes_param_len);
if (param == NULL)
goto out;
}
rc = -EFAULT;
if (copy_from_user(batch_name, args->lstio_tes_bat_name,
args->lstio_tes_bat_nmlen) ||
copy_from_user(src_name, args->lstio_tes_sgrp_name,
args->lstio_tes_sgrp_nmlen) ||
copy_from_user(dst_name, args->lstio_tes_dgrp_name,
args->lstio_tes_dgrp_nmlen) ||
copy_from_user(param, args->lstio_tes_param,
args->lstio_tes_param_len))
goto out;
rc = lstcon_test_add(batch_name,
args->lstio_tes_type,
args->lstio_tes_loop,
args->lstio_tes_concur,
args->lstio_tes_dist, args->lstio_tes_span,
src_name, dst_name, param,
args->lstio_tes_param_len,
&ret, args->lstio_tes_resultp);
if (ret != 0)
rc = (copy_to_user(args->lstio_tes_retp, &ret,
sizeof(ret))) ? -EFAULT : 0;
out:
if (batch_name != NULL)
LIBCFS_FREE(batch_name, args->lstio_tes_bat_nmlen + 1);
if (src_name != NULL)
LIBCFS_FREE(src_name, args->lstio_tes_sgrp_nmlen + 1);
if (dst_name != NULL)
LIBCFS_FREE(dst_name, args->lstio_tes_dgrp_nmlen + 1);
if (param != NULL)
LIBCFS_FREE(param, args->lstio_tes_param_len);
return rc;
}
int
lstcon_ioctl_entry(unsigned int cmd, struct libcfs_ioctl_data *data)
{
char *buf;
int opc = data->ioc_u32[0];
int rc;
if (cmd != IOC_LIBCFS_LNETST)
return -EINVAL;
if (data->ioc_plen1 > PAGE_CACHE_SIZE)
return -EINVAL;
LIBCFS_ALLOC(buf, data->ioc_plen1);
if (buf == NULL)
return -ENOMEM;
/* copy in parameter */
if (copy_from_user(buf, data->ioc_pbuf1, data->ioc_plen1)) {
LIBCFS_FREE(buf, data->ioc_plen1);
return -EFAULT;
}
mutex_lock(&console_session.ses_mutex);
console_session.ses_laststamp = cfs_time_current_sec();
if (console_session.ses_shutdown) {
rc = -ESHUTDOWN;
goto out;
}
if (console_session.ses_expired)
lstcon_session_end();
if (opc != LSTIO_SESSION_NEW &&
console_session.ses_state == LST_SESSION_NONE) {
CDEBUG(D_NET, "LST no active session\n");
rc = -ESRCH;
goto out;
}
memset(&console_session.ses_trans_stat, 0, sizeof(lstcon_trans_stat_t));
switch (opc) {
case LSTIO_SESSION_NEW:
rc = lst_session_new_ioctl((lstio_session_new_args_t *)buf);
break;
case LSTIO_SESSION_END:
rc = lst_session_end_ioctl((lstio_session_end_args_t *)buf);
break;
case LSTIO_SESSION_INFO:
rc = lst_session_info_ioctl((lstio_session_info_args_t *)buf);
break;
case LSTIO_DEBUG:
rc = lst_debug_ioctl((lstio_debug_args_t *)buf);
break;
case LSTIO_GROUP_ADD:
rc = lst_group_add_ioctl((lstio_group_add_args_t *)buf);
break;
case LSTIO_GROUP_DEL:
rc = lst_group_del_ioctl((lstio_group_del_args_t *)buf);
break;
case LSTIO_GROUP_UPDATE:
rc = lst_group_update_ioctl((lstio_group_update_args_t *)buf);
break;
case LSTIO_NODES_ADD:
rc = lst_nodes_add_ioctl((lstio_group_nodes_args_t *)buf);
break;
case LSTIO_GROUP_LIST:
rc = lst_group_list_ioctl((lstio_group_list_args_t *)buf);
break;
case LSTIO_GROUP_INFO:
rc = lst_group_info_ioctl((lstio_group_info_args_t *)buf);
break;
case LSTIO_BATCH_ADD:
rc = lst_batch_add_ioctl((lstio_batch_add_args_t *)buf);
break;
case LSTIO_BATCH_START:
rc = lst_batch_run_ioctl((lstio_batch_run_args_t *)buf);
break;
case LSTIO_BATCH_STOP:
rc = lst_batch_stop_ioctl((lstio_batch_stop_args_t *)buf);
break;
case LSTIO_BATCH_QUERY:
rc = lst_batch_query_ioctl((lstio_batch_query_args_t *)buf);
break;
case LSTIO_BATCH_LIST:
rc = lst_batch_list_ioctl((lstio_batch_list_args_t *)buf);
break;
case LSTIO_BATCH_INFO:
rc = lst_batch_info_ioctl((lstio_batch_info_args_t *)buf);
break;
case LSTIO_TEST_ADD:
rc = lst_test_add_ioctl((lstio_test_args_t *)buf);
break;
case LSTIO_STAT_QUERY:
rc = lst_stat_query_ioctl((lstio_stat_args_t *)buf);
break;
default:
rc = -EINVAL;
}
if (copy_to_user(data->ioc_pbuf2, &console_session.ses_trans_stat,
sizeof(lstcon_trans_stat_t)))
rc = -EFAULT;
out:
mutex_unlock(&console_session.ses_mutex);
LIBCFS_FREE(buf, data->ioc_plen1);
return rc;
}
EXPORT_SYMBOL(lstcon_ioctl_entry);
| gpl-2.0 |
ulrikdb/linux | drivers/of/device.c | 355 | 4752 | #include <linux/string.h>
#include <linux/kernel.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/mod_devicetable.h>
#include <linux/slab.h>
#include <asm/errno.h>
#include "of_private.h"
/**
* of_match_device - Tell if a struct device matches an of_device_id list
* @ids: array of of device match structures to search in
* @dev: the of device structure to match against
*
* Used by a driver to check whether an platform_device present in the
* system is in its list of supported devices.
*/
const struct of_device_id *of_match_device(const struct of_device_id *matches,
const struct device *dev)
{
if ((!matches) || (!dev->of_node))
return NULL;
return of_match_node(matches, dev->of_node);
}
EXPORT_SYMBOL(of_match_device);
struct platform_device *of_dev_get(struct platform_device *dev)
{
struct device *tmp;
if (!dev)
return NULL;
tmp = get_device(&dev->dev);
if (tmp)
return to_platform_device(tmp);
else
return NULL;
}
EXPORT_SYMBOL(of_dev_get);
void of_dev_put(struct platform_device *dev)
{
if (dev)
put_device(&dev->dev);
}
EXPORT_SYMBOL(of_dev_put);
int of_device_add(struct platform_device *ofdev)
{
BUG_ON(ofdev->dev.of_node == NULL);
/* name and id have to be set so that the platform bus doesn't get
* confused on matching */
ofdev->name = dev_name(&ofdev->dev);
ofdev->id = -1;
/* device_add will assume that this device is on the same node as
* the parent. If there is no parent defined, set the node
* explicitly */
if (!ofdev->dev.parent)
set_dev_node(&ofdev->dev, of_node_to_nid(ofdev->dev.of_node));
return device_add(&ofdev->dev);
}
int of_device_register(struct platform_device *pdev)
{
device_initialize(&pdev->dev);
return of_device_add(pdev);
}
EXPORT_SYMBOL(of_device_register);
void of_device_unregister(struct platform_device *ofdev)
{
device_unregister(&ofdev->dev);
}
EXPORT_SYMBOL(of_device_unregister);
ssize_t of_device_get_modalias(struct device *dev, char *str, ssize_t len)
{
const char *compat;
int cplen, i;
ssize_t tsize, csize, repend;
if ((!dev) || (!dev->of_node))
return -ENODEV;
/* Name & Type */
csize = snprintf(str, len, "of:N%sT%s", dev->of_node->name,
dev->of_node->type);
/* Get compatible property if any */
compat = of_get_property(dev->of_node, "compatible", &cplen);
if (!compat)
return csize;
/* Find true end (we tolerate multiple \0 at the end */
for (i = (cplen - 1); i >= 0 && !compat[i]; i--)
cplen--;
if (!cplen)
return csize;
cplen++;
/* Check space (need cplen+1 chars including final \0) */
tsize = csize + cplen;
repend = tsize;
if (csize >= len) /* @ the limit, all is already filled */
return tsize;
if (tsize >= len) { /* limit compat list */
cplen = len - csize - 1;
repend = len;
}
/* Copy and do char replacement */
memcpy(&str[csize + 1], compat, cplen);
for (i = csize; i < repend; i++) {
char c = str[i];
if (c == '\0')
str[i] = 'C';
else if (c == ' ')
str[i] = '_';
}
return tsize;
}
/**
* of_device_uevent - Display OF related uevent information
*/
void of_device_uevent(struct device *dev, struct kobj_uevent_env *env)
{
const char *compat;
struct alias_prop *app;
int seen = 0, cplen, sl;
if ((!dev) || (!dev->of_node))
return;
add_uevent_var(env, "OF_NAME=%s", dev->of_node->name);
add_uevent_var(env, "OF_FULLNAME=%s", dev->of_node->full_name);
if (dev->of_node->type && strcmp("<NULL>", dev->of_node->type) != 0)
add_uevent_var(env, "OF_TYPE=%s", dev->of_node->type);
/* Since the compatible field can contain pretty much anything
* it's not really legal to split it out with commas. We split it
* up using a number of environment variables instead. */
compat = of_get_property(dev->of_node, "compatible", &cplen);
while (compat && *compat && cplen > 0) {
add_uevent_var(env, "OF_COMPATIBLE_%d=%s", seen, compat);
sl = strlen(compat) + 1;
compat += sl;
cplen -= sl;
seen++;
}
add_uevent_var(env, "OF_COMPATIBLE_N=%d", seen);
seen = 0;
mutex_lock(&of_aliases_mutex);
list_for_each_entry(app, &aliases_lookup, link) {
if (dev->of_node == app->np) {
add_uevent_var(env, "OF_ALIAS_%d=%s", seen,
app->alias);
seen++;
}
}
mutex_unlock(&of_aliases_mutex);
}
int of_device_uevent_modalias(struct device *dev, struct kobj_uevent_env *env)
{
int sl;
if ((!dev) || (!dev->of_node))
return -ENODEV;
/* Devicetree modalias is tricky, we add it in 2 steps */
if (add_uevent_var(env, "MODALIAS="))
return -ENOMEM;
sl = of_device_get_modalias(dev, &env->buf[env->buflen-1],
sizeof(env->buf) - env->buflen);
if (sl >= (sizeof(env->buf) - env->buflen))
return -ENOMEM;
env->buflen += sl;
return 0;
}
| gpl-2.0 |
francegabb/mxu1130driver | drivers/gpu/drm/msm/mdp/mdp4/mdp4_crtc.c | 355 | 17966 | /*
* Copyright (C) 2013 Red Hat
* Author: Rob Clark <robdclark@gmail.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mdp4_kms.h"
#include <drm/drm_mode.h>
#include "drm_crtc.h"
#include "drm_crtc_helper.h"
#include "drm_flip_work.h"
struct mdp4_crtc {
struct drm_crtc base;
char name[8];
int id;
int ovlp;
enum mdp4_dma dma;
bool enabled;
/* which mixer/encoder we route output to: */
int mixer;
struct {
spinlock_t lock;
bool stale;
uint32_t width, height;
uint32_t x, y;
/* next cursor to scan-out: */
uint32_t next_iova;
struct drm_gem_object *next_bo;
/* current cursor being scanned out: */
struct drm_gem_object *scanout_bo;
} cursor;
/* if there is a pending flip, these will be non-null: */
struct drm_pending_vblank_event *event;
#define PENDING_CURSOR 0x1
#define PENDING_FLIP 0x2
atomic_t pending;
/* for unref'ing cursor bo's after scanout completes: */
struct drm_flip_work unref_cursor_work;
struct mdp_irq vblank;
struct mdp_irq err;
};
#define to_mdp4_crtc(x) container_of(x, struct mdp4_crtc, base)
static struct mdp4_kms *get_kms(struct drm_crtc *crtc)
{
struct msm_drm_private *priv = crtc->dev->dev_private;
return to_mdp4_kms(to_mdp_kms(priv->kms));
}
static void request_pending(struct drm_crtc *crtc, uint32_t pending)
{
struct mdp4_crtc *mdp4_crtc = to_mdp4_crtc(crtc);
atomic_or(pending, &mdp4_crtc->pending);
mdp_irq_register(&get_kms(crtc)->base, &mdp4_crtc->vblank);
}
static void crtc_flush(struct drm_crtc *crtc)
{
struct mdp4_crtc *mdp4_crtc = to_mdp4_crtc(crtc);
struct mdp4_kms *mdp4_kms = get_kms(crtc);
struct drm_plane *plane;
uint32_t flush = 0;
drm_atomic_crtc_for_each_plane(plane, crtc) {
enum mdp4_pipe pipe_id = mdp4_plane_pipe(plane);
flush |= pipe2flush(pipe_id);
}
flush |= ovlp2flush(mdp4_crtc->ovlp);
DBG("%s: flush=%08x", mdp4_crtc->name, flush);
mdp4_write(mdp4_kms, REG_MDP4_OVERLAY_FLUSH, flush);
}
/* if file!=NULL, this is preclose potential cancel-flip path */
static void complete_flip(struct drm_crtc *crtc, struct drm_file *file)
{
struct mdp4_crtc *mdp4_crtc = to_mdp4_crtc(crtc);
struct drm_device *dev = crtc->dev;
struct drm_pending_vblank_event *event;
unsigned long flags;
spin_lock_irqsave(&dev->event_lock, flags);
event = mdp4_crtc->event;
if (event) {
/* if regular vblank case (!file) or if cancel-flip from
* preclose on file that requested flip, then send the
* event:
*/
if (!file || (event->base.file_priv == file)) {
mdp4_crtc->event = NULL;
DBG("%s: send event: %p", mdp4_crtc->name, event);
drm_send_vblank_event(dev, mdp4_crtc->id, event);
}
}
spin_unlock_irqrestore(&dev->event_lock, flags);
}
static void unref_cursor_worker(struct drm_flip_work *work, void *val)
{
struct mdp4_crtc *mdp4_crtc =
container_of(work, struct mdp4_crtc, unref_cursor_work);
struct mdp4_kms *mdp4_kms = get_kms(&mdp4_crtc->base);
msm_gem_put_iova(val, mdp4_kms->id);
drm_gem_object_unreference_unlocked(val);
}
static void mdp4_crtc_destroy(struct drm_crtc *crtc)
{
struct mdp4_crtc *mdp4_crtc = to_mdp4_crtc(crtc);
drm_crtc_cleanup(crtc);
drm_flip_work_cleanup(&mdp4_crtc->unref_cursor_work);
kfree(mdp4_crtc);
}
static bool mdp4_crtc_mode_fixup(struct drm_crtc *crtc,
const struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
return true;
}
/* statically (for now) map planes to mixer stage (z-order): */
static const int idxs[] = {
[VG1] = 1,
[VG2] = 2,
[RGB1] = 0,
[RGB2] = 0,
[RGB3] = 0,
[VG3] = 3,
[VG4] = 4,
};
/* setup mixer config, for which we need to consider all crtc's and
* the planes attached to them
*
* TODO may possibly need some extra locking here
*/
static void setup_mixer(struct mdp4_kms *mdp4_kms)
{
struct drm_mode_config *config = &mdp4_kms->dev->mode_config;
struct drm_crtc *crtc;
uint32_t mixer_cfg = 0;
static const enum mdp_mixer_stage_id stages[] = {
STAGE_BASE, STAGE0, STAGE1, STAGE2, STAGE3,
};
list_for_each_entry(crtc, &config->crtc_list, head) {
struct mdp4_crtc *mdp4_crtc = to_mdp4_crtc(crtc);
struct drm_plane *plane;
drm_atomic_crtc_for_each_plane(plane, crtc) {
enum mdp4_pipe pipe_id = mdp4_plane_pipe(plane);
int idx = idxs[pipe_id];
mixer_cfg = mixercfg(mixer_cfg, mdp4_crtc->mixer,
pipe_id, stages[idx]);
}
}
mdp4_write(mdp4_kms, REG_MDP4_LAYERMIXER_IN_CFG, mixer_cfg);
}
static void blend_setup(struct drm_crtc *crtc)
{
struct mdp4_crtc *mdp4_crtc = to_mdp4_crtc(crtc);
struct mdp4_kms *mdp4_kms = get_kms(crtc);
struct drm_plane *plane;
int i, ovlp = mdp4_crtc->ovlp;
bool alpha[4]= { false, false, false, false };
mdp4_write(mdp4_kms, REG_MDP4_OVLP_TRANSP_LOW0(ovlp), 0);
mdp4_write(mdp4_kms, REG_MDP4_OVLP_TRANSP_LOW1(ovlp), 0);
mdp4_write(mdp4_kms, REG_MDP4_OVLP_TRANSP_HIGH0(ovlp), 0);
mdp4_write(mdp4_kms, REG_MDP4_OVLP_TRANSP_HIGH1(ovlp), 0);
drm_atomic_crtc_for_each_plane(plane, crtc) {
enum mdp4_pipe pipe_id = mdp4_plane_pipe(plane);
int idx = idxs[pipe_id];
if (idx > 0) {
const struct mdp_format *format =
to_mdp_format(msm_framebuffer_format(plane->fb));
alpha[idx-1] = format->alpha_enable;
}
}
for (i = 0; i < 4; i++) {
uint32_t op;
if (alpha[i]) {
op = MDP4_OVLP_STAGE_OP_FG_ALPHA(FG_PIXEL) |
MDP4_OVLP_STAGE_OP_BG_ALPHA(FG_PIXEL) |
MDP4_OVLP_STAGE_OP_BG_INV_ALPHA;
} else {
op = MDP4_OVLP_STAGE_OP_FG_ALPHA(FG_CONST) |
MDP4_OVLP_STAGE_OP_BG_ALPHA(BG_CONST);
}
mdp4_write(mdp4_kms, REG_MDP4_OVLP_STAGE_FG_ALPHA(ovlp, i), 0xff);
mdp4_write(mdp4_kms, REG_MDP4_OVLP_STAGE_BG_ALPHA(ovlp, i), 0x00);
mdp4_write(mdp4_kms, REG_MDP4_OVLP_STAGE_OP(ovlp, i), op);
mdp4_write(mdp4_kms, REG_MDP4_OVLP_STAGE_CO3(ovlp, i), 1);
mdp4_write(mdp4_kms, REG_MDP4_OVLP_STAGE_TRANSP_LOW0(ovlp, i), 0);
mdp4_write(mdp4_kms, REG_MDP4_OVLP_STAGE_TRANSP_LOW1(ovlp, i), 0);
mdp4_write(mdp4_kms, REG_MDP4_OVLP_STAGE_TRANSP_HIGH0(ovlp, i), 0);
mdp4_write(mdp4_kms, REG_MDP4_OVLP_STAGE_TRANSP_HIGH1(ovlp, i), 0);
}
setup_mixer(mdp4_kms);
}
static void mdp4_crtc_mode_set_nofb(struct drm_crtc *crtc)
{
struct mdp4_crtc *mdp4_crtc = to_mdp4_crtc(crtc);
struct mdp4_kms *mdp4_kms = get_kms(crtc);
enum mdp4_dma dma = mdp4_crtc->dma;
int ovlp = mdp4_crtc->ovlp;
struct drm_display_mode *mode;
if (WARN_ON(!crtc->state))
return;
mode = &crtc->state->adjusted_mode;
DBG("%s: set mode: %d:\"%s\" %d %d %d %d %d %d %d %d %d %d 0x%x 0x%x",
mdp4_crtc->name, mode->base.id, mode->name,
mode->vrefresh, mode->clock,
mode->hdisplay, mode->hsync_start,
mode->hsync_end, mode->htotal,
mode->vdisplay, mode->vsync_start,
mode->vsync_end, mode->vtotal,
mode->type, mode->flags);
mdp4_write(mdp4_kms, REG_MDP4_DMA_SRC_SIZE(dma),
MDP4_DMA_SRC_SIZE_WIDTH(mode->hdisplay) |
MDP4_DMA_SRC_SIZE_HEIGHT(mode->vdisplay));
/* take data from pipe: */
mdp4_write(mdp4_kms, REG_MDP4_DMA_SRC_BASE(dma), 0);
mdp4_write(mdp4_kms, REG_MDP4_DMA_SRC_STRIDE(dma), 0);
mdp4_write(mdp4_kms, REG_MDP4_DMA_DST_SIZE(dma),
MDP4_DMA_DST_SIZE_WIDTH(0) |
MDP4_DMA_DST_SIZE_HEIGHT(0));
mdp4_write(mdp4_kms, REG_MDP4_OVLP_BASE(ovlp), 0);
mdp4_write(mdp4_kms, REG_MDP4_OVLP_SIZE(ovlp),
MDP4_OVLP_SIZE_WIDTH(mode->hdisplay) |
MDP4_OVLP_SIZE_HEIGHT(mode->vdisplay));
mdp4_write(mdp4_kms, REG_MDP4_OVLP_STRIDE(ovlp), 0);
mdp4_write(mdp4_kms, REG_MDP4_OVLP_CFG(ovlp), 1);
if (dma == DMA_E) {
mdp4_write(mdp4_kms, REG_MDP4_DMA_E_QUANT(0), 0x00ff0000);
mdp4_write(mdp4_kms, REG_MDP4_DMA_E_QUANT(1), 0x00ff0000);
mdp4_write(mdp4_kms, REG_MDP4_DMA_E_QUANT(2), 0x00ff0000);
}
}
static void mdp4_crtc_disable(struct drm_crtc *crtc)
{
struct mdp4_crtc *mdp4_crtc = to_mdp4_crtc(crtc);
struct mdp4_kms *mdp4_kms = get_kms(crtc);
DBG("%s", mdp4_crtc->name);
if (WARN_ON(!mdp4_crtc->enabled))
return;
mdp_irq_unregister(&mdp4_kms->base, &mdp4_crtc->err);
mdp4_disable(mdp4_kms);
mdp4_crtc->enabled = false;
}
static void mdp4_crtc_enable(struct drm_crtc *crtc)
{
struct mdp4_crtc *mdp4_crtc = to_mdp4_crtc(crtc);
struct mdp4_kms *mdp4_kms = get_kms(crtc);
DBG("%s", mdp4_crtc->name);
if (WARN_ON(mdp4_crtc->enabled))
return;
mdp4_enable(mdp4_kms);
mdp_irq_register(&mdp4_kms->base, &mdp4_crtc->err);
crtc_flush(crtc);
mdp4_crtc->enabled = true;
}
static int mdp4_crtc_atomic_check(struct drm_crtc *crtc,
struct drm_crtc_state *state)
{
struct mdp4_crtc *mdp4_crtc = to_mdp4_crtc(crtc);
DBG("%s: check", mdp4_crtc->name);
// TODO anything else to check?
return 0;
}
static void mdp4_crtc_atomic_begin(struct drm_crtc *crtc)
{
struct mdp4_crtc *mdp4_crtc = to_mdp4_crtc(crtc);
DBG("%s: begin", mdp4_crtc->name);
}
static void mdp4_crtc_atomic_flush(struct drm_crtc *crtc)
{
struct mdp4_crtc *mdp4_crtc = to_mdp4_crtc(crtc);
struct drm_device *dev = crtc->dev;
unsigned long flags;
DBG("%s: event: %p", mdp4_crtc->name, crtc->state->event);
WARN_ON(mdp4_crtc->event);
spin_lock_irqsave(&dev->event_lock, flags);
mdp4_crtc->event = crtc->state->event;
spin_unlock_irqrestore(&dev->event_lock, flags);
blend_setup(crtc);
crtc_flush(crtc);
request_pending(crtc, PENDING_FLIP);
}
static int mdp4_crtc_set_property(struct drm_crtc *crtc,
struct drm_property *property, uint64_t val)
{
// XXX
return -EINVAL;
}
#define CURSOR_WIDTH 64
#define CURSOR_HEIGHT 64
/* called from IRQ to update cursor related registers (if needed). The
* cursor registers, other than x/y position, appear not to be double
* buffered, and changing them other than from vblank seems to trigger
* underflow.
*/
static void update_cursor(struct drm_crtc *crtc)
{
struct mdp4_crtc *mdp4_crtc = to_mdp4_crtc(crtc);
struct mdp4_kms *mdp4_kms = get_kms(crtc);
enum mdp4_dma dma = mdp4_crtc->dma;
unsigned long flags;
spin_lock_irqsave(&mdp4_crtc->cursor.lock, flags);
if (mdp4_crtc->cursor.stale) {
struct drm_gem_object *next_bo = mdp4_crtc->cursor.next_bo;
struct drm_gem_object *prev_bo = mdp4_crtc->cursor.scanout_bo;
uint32_t iova = mdp4_crtc->cursor.next_iova;
if (next_bo) {
/* take a obj ref + iova ref when we start scanning out: */
drm_gem_object_reference(next_bo);
msm_gem_get_iova_locked(next_bo, mdp4_kms->id, &iova);
/* enable cursor: */
mdp4_write(mdp4_kms, REG_MDP4_DMA_CURSOR_SIZE(dma),
MDP4_DMA_CURSOR_SIZE_WIDTH(mdp4_crtc->cursor.width) |
MDP4_DMA_CURSOR_SIZE_HEIGHT(mdp4_crtc->cursor.height));
mdp4_write(mdp4_kms, REG_MDP4_DMA_CURSOR_BASE(dma), iova);
mdp4_write(mdp4_kms, REG_MDP4_DMA_CURSOR_BLEND_CONFIG(dma),
MDP4_DMA_CURSOR_BLEND_CONFIG_FORMAT(CURSOR_ARGB) |
MDP4_DMA_CURSOR_BLEND_CONFIG_CURSOR_EN);
} else {
/* disable cursor: */
mdp4_write(mdp4_kms, REG_MDP4_DMA_CURSOR_BASE(dma),
mdp4_kms->blank_cursor_iova);
}
/* and drop the iova ref + obj rev when done scanning out: */
if (prev_bo)
drm_flip_work_queue(&mdp4_crtc->unref_cursor_work, prev_bo);
mdp4_crtc->cursor.scanout_bo = next_bo;
mdp4_crtc->cursor.stale = false;
}
mdp4_write(mdp4_kms, REG_MDP4_DMA_CURSOR_POS(dma),
MDP4_DMA_CURSOR_POS_X(mdp4_crtc->cursor.x) |
MDP4_DMA_CURSOR_POS_Y(mdp4_crtc->cursor.y));
spin_unlock_irqrestore(&mdp4_crtc->cursor.lock, flags);
}
static int mdp4_crtc_cursor_set(struct drm_crtc *crtc,
struct drm_file *file_priv, uint32_t handle,
uint32_t width, uint32_t height)
{
struct mdp4_crtc *mdp4_crtc = to_mdp4_crtc(crtc);
struct mdp4_kms *mdp4_kms = get_kms(crtc);
struct drm_device *dev = crtc->dev;
struct drm_gem_object *cursor_bo, *old_bo;
unsigned long flags;
uint32_t iova;
int ret;
if ((width > CURSOR_WIDTH) || (height > CURSOR_HEIGHT)) {
dev_err(dev->dev, "bad cursor size: %dx%d\n", width, height);
return -EINVAL;
}
if (handle) {
cursor_bo = drm_gem_object_lookup(dev, file_priv, handle);
if (!cursor_bo)
return -ENOENT;
} else {
cursor_bo = NULL;
}
if (cursor_bo) {
ret = msm_gem_get_iova(cursor_bo, mdp4_kms->id, &iova);
if (ret)
goto fail;
} else {
iova = 0;
}
spin_lock_irqsave(&mdp4_crtc->cursor.lock, flags);
old_bo = mdp4_crtc->cursor.next_bo;
mdp4_crtc->cursor.next_bo = cursor_bo;
mdp4_crtc->cursor.next_iova = iova;
mdp4_crtc->cursor.width = width;
mdp4_crtc->cursor.height = height;
mdp4_crtc->cursor.stale = true;
spin_unlock_irqrestore(&mdp4_crtc->cursor.lock, flags);
if (old_bo) {
/* drop our previous reference: */
drm_flip_work_queue(&mdp4_crtc->unref_cursor_work, old_bo);
}
request_pending(crtc, PENDING_CURSOR);
return 0;
fail:
drm_gem_object_unreference_unlocked(cursor_bo);
return ret;
}
static int mdp4_crtc_cursor_move(struct drm_crtc *crtc, int x, int y)
{
struct mdp4_crtc *mdp4_crtc = to_mdp4_crtc(crtc);
unsigned long flags;
spin_lock_irqsave(&mdp4_crtc->cursor.lock, flags);
mdp4_crtc->cursor.x = x;
mdp4_crtc->cursor.y = y;
spin_unlock_irqrestore(&mdp4_crtc->cursor.lock, flags);
crtc_flush(crtc);
request_pending(crtc, PENDING_CURSOR);
return 0;
}
static const struct drm_crtc_funcs mdp4_crtc_funcs = {
.set_config = drm_atomic_helper_set_config,
.destroy = mdp4_crtc_destroy,
.page_flip = drm_atomic_helper_page_flip,
.set_property = mdp4_crtc_set_property,
.cursor_set = mdp4_crtc_cursor_set,
.cursor_move = mdp4_crtc_cursor_move,
.reset = drm_atomic_helper_crtc_reset,
.atomic_duplicate_state = drm_atomic_helper_crtc_duplicate_state,
.atomic_destroy_state = drm_atomic_helper_crtc_destroy_state,
};
static const struct drm_crtc_helper_funcs mdp4_crtc_helper_funcs = {
.mode_fixup = mdp4_crtc_mode_fixup,
.mode_set_nofb = mdp4_crtc_mode_set_nofb,
.disable = mdp4_crtc_disable,
.enable = mdp4_crtc_enable,
.atomic_check = mdp4_crtc_atomic_check,
.atomic_begin = mdp4_crtc_atomic_begin,
.atomic_flush = mdp4_crtc_atomic_flush,
};
static void mdp4_crtc_vblank_irq(struct mdp_irq *irq, uint32_t irqstatus)
{
struct mdp4_crtc *mdp4_crtc = container_of(irq, struct mdp4_crtc, vblank);
struct drm_crtc *crtc = &mdp4_crtc->base;
struct msm_drm_private *priv = crtc->dev->dev_private;
unsigned pending;
mdp_irq_unregister(&get_kms(crtc)->base, &mdp4_crtc->vblank);
pending = atomic_xchg(&mdp4_crtc->pending, 0);
if (pending & PENDING_FLIP) {
complete_flip(crtc, NULL);
}
if (pending & PENDING_CURSOR) {
update_cursor(crtc);
drm_flip_work_commit(&mdp4_crtc->unref_cursor_work, priv->wq);
}
}
static void mdp4_crtc_err_irq(struct mdp_irq *irq, uint32_t irqstatus)
{
struct mdp4_crtc *mdp4_crtc = container_of(irq, struct mdp4_crtc, err);
struct drm_crtc *crtc = &mdp4_crtc->base;
DBG("%s: error: %08x", mdp4_crtc->name, irqstatus);
crtc_flush(crtc);
}
uint32_t mdp4_crtc_vblank(struct drm_crtc *crtc)
{
struct mdp4_crtc *mdp4_crtc = to_mdp4_crtc(crtc);
return mdp4_crtc->vblank.irqmask;
}
void mdp4_crtc_cancel_pending_flip(struct drm_crtc *crtc, struct drm_file *file)
{
struct mdp4_crtc *mdp4_crtc = to_mdp4_crtc(crtc);
DBG("%s: cancel: %p", mdp4_crtc->name, file);
complete_flip(crtc, file);
}
/* set dma config, ie. the format the encoder wants. */
void mdp4_crtc_set_config(struct drm_crtc *crtc, uint32_t config)
{
struct mdp4_crtc *mdp4_crtc = to_mdp4_crtc(crtc);
struct mdp4_kms *mdp4_kms = get_kms(crtc);
mdp4_write(mdp4_kms, REG_MDP4_DMA_CONFIG(mdp4_crtc->dma), config);
}
/* set interface for routing crtc->encoder: */
void mdp4_crtc_set_intf(struct drm_crtc *crtc, enum mdp4_intf intf, int mixer)
{
struct mdp4_crtc *mdp4_crtc = to_mdp4_crtc(crtc);
struct mdp4_kms *mdp4_kms = get_kms(crtc);
uint32_t intf_sel;
intf_sel = mdp4_read(mdp4_kms, REG_MDP4_DISP_INTF_SEL);
switch (mdp4_crtc->dma) {
case DMA_P:
intf_sel &= ~MDP4_DISP_INTF_SEL_PRIM__MASK;
intf_sel |= MDP4_DISP_INTF_SEL_PRIM(intf);
break;
case DMA_S:
intf_sel &= ~MDP4_DISP_INTF_SEL_SEC__MASK;
intf_sel |= MDP4_DISP_INTF_SEL_SEC(intf);
break;
case DMA_E:
intf_sel &= ~MDP4_DISP_INTF_SEL_EXT__MASK;
intf_sel |= MDP4_DISP_INTF_SEL_EXT(intf);
break;
}
if (intf == INTF_DSI_VIDEO) {
intf_sel &= ~MDP4_DISP_INTF_SEL_DSI_CMD;
intf_sel |= MDP4_DISP_INTF_SEL_DSI_VIDEO;
} else if (intf == INTF_DSI_CMD) {
intf_sel &= ~MDP4_DISP_INTF_SEL_DSI_VIDEO;
intf_sel |= MDP4_DISP_INTF_SEL_DSI_CMD;
}
mdp4_crtc->mixer = mixer;
blend_setup(crtc);
DBG("%s: intf_sel=%08x", mdp4_crtc->name, intf_sel);
mdp4_write(mdp4_kms, REG_MDP4_DISP_INTF_SEL, intf_sel);
}
static const char *dma_names[] = {
"DMA_P", "DMA_S", "DMA_E",
};
/* initialize crtc */
struct drm_crtc *mdp4_crtc_init(struct drm_device *dev,
struct drm_plane *plane, int id, int ovlp_id,
enum mdp4_dma dma_id)
{
struct drm_crtc *crtc = NULL;
struct mdp4_crtc *mdp4_crtc;
mdp4_crtc = kzalloc(sizeof(*mdp4_crtc), GFP_KERNEL);
if (!mdp4_crtc)
return ERR_PTR(-ENOMEM);
crtc = &mdp4_crtc->base;
mdp4_crtc->id = id;
mdp4_crtc->ovlp = ovlp_id;
mdp4_crtc->dma = dma_id;
mdp4_crtc->vblank.irqmask = dma2irq(mdp4_crtc->dma);
mdp4_crtc->vblank.irq = mdp4_crtc_vblank_irq;
mdp4_crtc->err.irqmask = dma2err(mdp4_crtc->dma);
mdp4_crtc->err.irq = mdp4_crtc_err_irq;
snprintf(mdp4_crtc->name, sizeof(mdp4_crtc->name), "%s:%d",
dma_names[dma_id], ovlp_id);
spin_lock_init(&mdp4_crtc->cursor.lock);
drm_flip_work_init(&mdp4_crtc->unref_cursor_work,
"unref cursor", unref_cursor_worker);
drm_crtc_init_with_planes(dev, crtc, plane, NULL, &mdp4_crtc_funcs);
drm_crtc_helper_add(crtc, &mdp4_crtc_helper_funcs);
plane->crtc = crtc;
mdp4_plane_install_properties(plane, &crtc->base);
return crtc;
}
| gpl-2.0 |
0x20c24/linux-psec | drivers/video/fbdev/arkfb.c | 611 | 32832 | /*
* linux/drivers/video/arkfb.c -- Frame buffer device driver for ARK 2000PV
* with ICS 5342 dac (it is easy to add support for different dacs).
*
* Copyright (c) 2007 Ondrej Zajicek <santiago@crfreenet.org>
*
* 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.
*
* Code is based on s3fb
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/tty.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/fb.h>
#include <linux/svga.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/console.h> /* Why should fb driver call console functions? because console_lock() */
#include <video/vga.h>
#ifdef CONFIG_MTRR
#include <asm/mtrr.h>
#endif
struct arkfb_info {
int mclk_freq;
int mtrr_reg;
struct dac_info *dac;
struct vgastate state;
struct mutex open_lock;
unsigned int ref_count;
u32 pseudo_palette[16];
};
/* ------------------------------------------------------------------------- */
static const struct svga_fb_format arkfb_formats[] = {
{ 0, {0, 6, 0}, {0, 6, 0}, {0, 6, 0}, {0, 0, 0}, 0,
FB_TYPE_TEXT, FB_AUX_TEXT_SVGA_STEP4, FB_VISUAL_PSEUDOCOLOR, 8, 8},
{ 4, {0, 6, 0}, {0, 6, 0}, {0, 6, 0}, {0, 0, 0}, 0,
FB_TYPE_PACKED_PIXELS, 0, FB_VISUAL_PSEUDOCOLOR, 8, 16},
{ 4, {0, 6, 0}, {0, 6, 0}, {0, 6, 0}, {0, 0, 0}, 1,
FB_TYPE_INTERLEAVED_PLANES, 1, FB_VISUAL_PSEUDOCOLOR, 8, 16},
{ 8, {0, 6, 0}, {0, 6, 0}, {0, 6, 0}, {0, 0, 0}, 0,
FB_TYPE_PACKED_PIXELS, 0, FB_VISUAL_PSEUDOCOLOR, 8, 8},
{16, {10, 5, 0}, {5, 5, 0}, {0, 5, 0}, {0, 0, 0}, 0,
FB_TYPE_PACKED_PIXELS, 0, FB_VISUAL_TRUECOLOR, 4, 4},
{16, {11, 5, 0}, {5, 6, 0}, {0, 5, 0}, {0, 0, 0}, 0,
FB_TYPE_PACKED_PIXELS, 0, FB_VISUAL_TRUECOLOR, 4, 4},
{24, {16, 8, 0}, {8, 8, 0}, {0, 8, 0}, {0, 0, 0}, 0,
FB_TYPE_PACKED_PIXELS, 0, FB_VISUAL_TRUECOLOR, 8, 8},
{32, {16, 8, 0}, {8, 8, 0}, {0, 8, 0}, {0, 0, 0}, 0,
FB_TYPE_PACKED_PIXELS, 0, FB_VISUAL_TRUECOLOR, 2, 2},
SVGA_FORMAT_END
};
/* CRT timing register sets */
static const struct vga_regset ark_h_total_regs[] = {{0x00, 0, 7}, {0x41, 7, 7}, VGA_REGSET_END};
static const struct vga_regset ark_h_display_regs[] = {{0x01, 0, 7}, {0x41, 6, 6}, VGA_REGSET_END};
static const struct vga_regset ark_h_blank_start_regs[] = {{0x02, 0, 7}, {0x41, 5, 5}, VGA_REGSET_END};
static const struct vga_regset ark_h_blank_end_regs[] = {{0x03, 0, 4}, {0x05, 7, 7 }, VGA_REGSET_END};
static const struct vga_regset ark_h_sync_start_regs[] = {{0x04, 0, 7}, {0x41, 4, 4}, VGA_REGSET_END};
static const struct vga_regset ark_h_sync_end_regs[] = {{0x05, 0, 4}, VGA_REGSET_END};
static const struct vga_regset ark_v_total_regs[] = {{0x06, 0, 7}, {0x07, 0, 0}, {0x07, 5, 5}, {0x40, 7, 7}, VGA_REGSET_END};
static const struct vga_regset ark_v_display_regs[] = {{0x12, 0, 7}, {0x07, 1, 1}, {0x07, 6, 6}, {0x40, 6, 6}, VGA_REGSET_END};
static const struct vga_regset ark_v_blank_start_regs[] = {{0x15, 0, 7}, {0x07, 3, 3}, {0x09, 5, 5}, {0x40, 5, 5}, VGA_REGSET_END};
// const struct vga_regset ark_v_blank_end_regs[] = {{0x16, 0, 6}, VGA_REGSET_END};
static const struct vga_regset ark_v_blank_end_regs[] = {{0x16, 0, 7}, VGA_REGSET_END};
static const struct vga_regset ark_v_sync_start_regs[] = {{0x10, 0, 7}, {0x07, 2, 2}, {0x07, 7, 7}, {0x40, 4, 4}, VGA_REGSET_END};
static const struct vga_regset ark_v_sync_end_regs[] = {{0x11, 0, 3}, VGA_REGSET_END};
static const struct vga_regset ark_line_compare_regs[] = {{0x18, 0, 7}, {0x07, 4, 4}, {0x09, 6, 6}, VGA_REGSET_END};
static const struct vga_regset ark_start_address_regs[] = {{0x0d, 0, 7}, {0x0c, 0, 7}, {0x40, 0, 2}, VGA_REGSET_END};
static const struct vga_regset ark_offset_regs[] = {{0x13, 0, 7}, {0x41, 3, 3}, VGA_REGSET_END};
static const struct svga_timing_regs ark_timing_regs = {
ark_h_total_regs, ark_h_display_regs, ark_h_blank_start_regs,
ark_h_blank_end_regs, ark_h_sync_start_regs, ark_h_sync_end_regs,
ark_v_total_regs, ark_v_display_regs, ark_v_blank_start_regs,
ark_v_blank_end_regs, ark_v_sync_start_regs, ark_v_sync_end_regs,
};
/* ------------------------------------------------------------------------- */
/* Module parameters */
static char *mode_option = "640x480-8@60";
#ifdef CONFIG_MTRR
static int mtrr = 1;
#endif
MODULE_AUTHOR("(c) 2007 Ondrej Zajicek <santiago@crfreenet.org>");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("fbdev driver for ARK 2000PV");
module_param(mode_option, charp, 0444);
MODULE_PARM_DESC(mode_option, "Default video mode ('640x480-8@60', etc)");
module_param_named(mode, mode_option, charp, 0444);
MODULE_PARM_DESC(mode, "Default video mode ('640x480-8@60', etc) (deprecated)");
#ifdef CONFIG_MTRR
module_param(mtrr, int, 0444);
MODULE_PARM_DESC(mtrr, "Enable write-combining with MTRR (1=enable, 0=disable, default=1)");
#endif
static int threshold = 4;
module_param(threshold, int, 0644);
MODULE_PARM_DESC(threshold, "FIFO threshold");
/* ------------------------------------------------------------------------- */
static void arkfb_settile(struct fb_info *info, struct fb_tilemap *map)
{
const u8 *font = map->data;
u8 __iomem *fb = (u8 __iomem *)info->screen_base;
int i, c;
if ((map->width != 8) || (map->height != 16) ||
(map->depth != 1) || (map->length != 256)) {
fb_err(info, "unsupported font parameters: width %d, height %d, depth %d, length %d\n",
map->width, map->height, map->depth, map->length);
return;
}
fb += 2;
for (c = 0; c < map->length; c++) {
for (i = 0; i < map->height; i++) {
fb_writeb(font[i], &fb[i * 4]);
fb_writeb(font[i], &fb[i * 4 + (128 * 8)]);
}
fb += 128;
if ((c % 8) == 7)
fb += 128*8;
font += map->height;
}
}
static void arkfb_tilecursor(struct fb_info *info, struct fb_tilecursor *cursor)
{
struct arkfb_info *par = info->par;
svga_tilecursor(par->state.vgabase, info, cursor);
}
static struct fb_tile_ops arkfb_tile_ops = {
.fb_settile = arkfb_settile,
.fb_tilecopy = svga_tilecopy,
.fb_tilefill = svga_tilefill,
.fb_tileblit = svga_tileblit,
.fb_tilecursor = arkfb_tilecursor,
.fb_get_tilemax = svga_get_tilemax,
};
/* ------------------------------------------------------------------------- */
/* image data is MSB-first, fb structure is MSB-first too */
static inline u32 expand_color(u32 c)
{
return ((c & 1) | ((c & 2) << 7) | ((c & 4) << 14) | ((c & 8) << 21)) * 0xFF;
}
/* arkfb_iplan_imageblit silently assumes that almost everything is 8-pixel aligned */
static void arkfb_iplan_imageblit(struct fb_info *info, const struct fb_image *image)
{
u32 fg = expand_color(image->fg_color);
u32 bg = expand_color(image->bg_color);
const u8 *src1, *src;
u8 __iomem *dst1;
u32 __iomem *dst;
u32 val;
int x, y;
src1 = image->data;
dst1 = info->screen_base + (image->dy * info->fix.line_length)
+ ((image->dx / 8) * 4);
for (y = 0; y < image->height; y++) {
src = src1;
dst = (u32 __iomem *) dst1;
for (x = 0; x < image->width; x += 8) {
val = *(src++) * 0x01010101;
val = (val & fg) | (~val & bg);
fb_writel(val, dst++);
}
src1 += image->width / 8;
dst1 += info->fix.line_length;
}
}
/* arkfb_iplan_fillrect silently assumes that almost everything is 8-pixel aligned */
static void arkfb_iplan_fillrect(struct fb_info *info, const struct fb_fillrect *rect)
{
u32 fg = expand_color(rect->color);
u8 __iomem *dst1;
u32 __iomem *dst;
int x, y;
dst1 = info->screen_base + (rect->dy * info->fix.line_length)
+ ((rect->dx / 8) * 4);
for (y = 0; y < rect->height; y++) {
dst = (u32 __iomem *) dst1;
for (x = 0; x < rect->width; x += 8) {
fb_writel(fg, dst++);
}
dst1 += info->fix.line_length;
}
}
/* image data is MSB-first, fb structure is high-nibble-in-low-byte-first */
static inline u32 expand_pixel(u32 c)
{
return (((c & 1) << 24) | ((c & 2) << 27) | ((c & 4) << 14) | ((c & 8) << 17) |
((c & 16) << 4) | ((c & 32) << 7) | ((c & 64) >> 6) | ((c & 128) >> 3)) * 0xF;
}
/* arkfb_cfb4_imageblit silently assumes that almost everything is 8-pixel aligned */
static void arkfb_cfb4_imageblit(struct fb_info *info, const struct fb_image *image)
{
u32 fg = image->fg_color * 0x11111111;
u32 bg = image->bg_color * 0x11111111;
const u8 *src1, *src;
u8 __iomem *dst1;
u32 __iomem *dst;
u32 val;
int x, y;
src1 = image->data;
dst1 = info->screen_base + (image->dy * info->fix.line_length)
+ ((image->dx / 8) * 4);
for (y = 0; y < image->height; y++) {
src = src1;
dst = (u32 __iomem *) dst1;
for (x = 0; x < image->width; x += 8) {
val = expand_pixel(*(src++));
val = (val & fg) | (~val & bg);
fb_writel(val, dst++);
}
src1 += image->width / 8;
dst1 += info->fix.line_length;
}
}
static void arkfb_imageblit(struct fb_info *info, const struct fb_image *image)
{
if ((info->var.bits_per_pixel == 4) && (image->depth == 1)
&& ((image->width % 8) == 0) && ((image->dx % 8) == 0)) {
if (info->fix.type == FB_TYPE_INTERLEAVED_PLANES)
arkfb_iplan_imageblit(info, image);
else
arkfb_cfb4_imageblit(info, image);
} else
cfb_imageblit(info, image);
}
static void arkfb_fillrect(struct fb_info *info, const struct fb_fillrect *rect)
{
if ((info->var.bits_per_pixel == 4)
&& ((rect->width % 8) == 0) && ((rect->dx % 8) == 0)
&& (info->fix.type == FB_TYPE_INTERLEAVED_PLANES))
arkfb_iplan_fillrect(info, rect);
else
cfb_fillrect(info, rect);
}
/* ------------------------------------------------------------------------- */
enum
{
DAC_PSEUDO8_8,
DAC_RGB1555_8,
DAC_RGB0565_8,
DAC_RGB0888_8,
DAC_RGB8888_8,
DAC_PSEUDO8_16,
DAC_RGB1555_16,
DAC_RGB0565_16,
DAC_RGB0888_16,
DAC_RGB8888_16,
DAC_MAX
};
struct dac_ops {
int (*dac_get_mode)(struct dac_info *info);
int (*dac_set_mode)(struct dac_info *info, int mode);
int (*dac_get_freq)(struct dac_info *info, int channel);
int (*dac_set_freq)(struct dac_info *info, int channel, u32 freq);
void (*dac_release)(struct dac_info *info);
};
typedef void (*dac_read_regs_t)(void *data, u8 *code, int count);
typedef void (*dac_write_regs_t)(void *data, u8 *code, int count);
struct dac_info
{
struct dac_ops *dacops;
dac_read_regs_t dac_read_regs;
dac_write_regs_t dac_write_regs;
void *data;
};
static inline u8 dac_read_reg(struct dac_info *info, u8 reg)
{
u8 code[2] = {reg, 0};
info->dac_read_regs(info->data, code, 1);
return code[1];
}
static inline void dac_read_regs(struct dac_info *info, u8 *code, int count)
{
info->dac_read_regs(info->data, code, count);
}
static inline void dac_write_reg(struct dac_info *info, u8 reg, u8 val)
{
u8 code[2] = {reg, val};
info->dac_write_regs(info->data, code, 1);
}
static inline void dac_write_regs(struct dac_info *info, u8 *code, int count)
{
info->dac_write_regs(info->data, code, count);
}
static inline int dac_set_mode(struct dac_info *info, int mode)
{
return info->dacops->dac_set_mode(info, mode);
}
static inline int dac_set_freq(struct dac_info *info, int channel, u32 freq)
{
return info->dacops->dac_set_freq(info, channel, freq);
}
static inline void dac_release(struct dac_info *info)
{
info->dacops->dac_release(info);
}
/* ------------------------------------------------------------------------- */
/* ICS5342 DAC */
struct ics5342_info
{
struct dac_info dac;
u8 mode;
};
#define DAC_PAR(info) ((struct ics5342_info *) info)
/* LSB is set to distinguish unused slots */
static const u8 ics5342_mode_table[DAC_MAX] = {
[DAC_PSEUDO8_8] = 0x01, [DAC_RGB1555_8] = 0x21, [DAC_RGB0565_8] = 0x61,
[DAC_RGB0888_8] = 0x41, [DAC_PSEUDO8_16] = 0x11, [DAC_RGB1555_16] = 0x31,
[DAC_RGB0565_16] = 0x51, [DAC_RGB0888_16] = 0x91, [DAC_RGB8888_16] = 0x71
};
static int ics5342_set_mode(struct dac_info *info, int mode)
{
u8 code;
if (mode >= DAC_MAX)
return -EINVAL;
code = ics5342_mode_table[mode];
if (! code)
return -EINVAL;
dac_write_reg(info, 6, code & 0xF0);
DAC_PAR(info)->mode = mode;
return 0;
}
static const struct svga_pll ics5342_pll = {3, 129, 3, 33, 0, 3,
60000, 250000, 14318};
/* pd4 - allow only posdivider 4 (r=2) */
static const struct svga_pll ics5342_pll_pd4 = {3, 129, 3, 33, 2, 2,
60000, 335000, 14318};
/* 270 MHz should be upper bound for VCO clock according to specs,
but that is too restrictive in pd4 case */
static int ics5342_set_freq(struct dac_info *info, int channel, u32 freq)
{
u16 m, n, r;
/* only postdivider 4 (r=2) is valid in mode DAC_PSEUDO8_16 */
int rv = svga_compute_pll((DAC_PAR(info)->mode == DAC_PSEUDO8_16)
? &ics5342_pll_pd4 : &ics5342_pll,
freq, &m, &n, &r, 0);
if (rv < 0) {
return -EINVAL;
} else {
u8 code[6] = {4, 3, 5, m-2, 5, (n-2) | (r << 5)};
dac_write_regs(info, code, 3);
return 0;
}
}
static void ics5342_release(struct dac_info *info)
{
ics5342_set_mode(info, DAC_PSEUDO8_8);
kfree(info);
}
static struct dac_ops ics5342_ops = {
.dac_set_mode = ics5342_set_mode,
.dac_set_freq = ics5342_set_freq,
.dac_release = ics5342_release
};
static struct dac_info * ics5342_init(dac_read_regs_t drr, dac_write_regs_t dwr, void *data)
{
struct dac_info *info = kzalloc(sizeof(struct ics5342_info), GFP_KERNEL);
if (! info)
return NULL;
info->dacops = &ics5342_ops;
info->dac_read_regs = drr;
info->dac_write_regs = dwr;
info->data = data;
DAC_PAR(info)->mode = DAC_PSEUDO8_8; /* estimation */
return info;
}
/* ------------------------------------------------------------------------- */
static unsigned short dac_regs[4] = {0x3c8, 0x3c9, 0x3c6, 0x3c7};
static void ark_dac_read_regs(void *data, u8 *code, int count)
{
struct fb_info *info = data;
struct arkfb_info *par;
u8 regval;
par = info->par;
regval = vga_rseq(par->state.vgabase, 0x1C);
while (count != 0)
{
vga_wseq(par->state.vgabase, 0x1C, regval | (code[0] & 4 ? 0x80 : 0));
code[1] = vga_r(par->state.vgabase, dac_regs[code[0] & 3]);
count--;
code += 2;
}
vga_wseq(par->state.vgabase, 0x1C, regval);
}
static void ark_dac_write_regs(void *data, u8 *code, int count)
{
struct fb_info *info = data;
struct arkfb_info *par;
u8 regval;
par = info->par;
regval = vga_rseq(par->state.vgabase, 0x1C);
while (count != 0)
{
vga_wseq(par->state.vgabase, 0x1C, regval | (code[0] & 4 ? 0x80 : 0));
vga_w(par->state.vgabase, dac_regs[code[0] & 3], code[1]);
count--;
code += 2;
}
vga_wseq(par->state.vgabase, 0x1C, regval);
}
static void ark_set_pixclock(struct fb_info *info, u32 pixclock)
{
struct arkfb_info *par = info->par;
u8 regval;
int rv = dac_set_freq(par->dac, 0, 1000000000 / pixclock);
if (rv < 0) {
fb_err(info, "cannot set requested pixclock, keeping old value\n");
return;
}
/* Set VGA misc register */
regval = vga_r(par->state.vgabase, VGA_MIS_R);
vga_w(par->state.vgabase, VGA_MIS_W, regval | VGA_MIS_ENB_PLL_LOAD);
}
/* Open framebuffer */
static int arkfb_open(struct fb_info *info, int user)
{
struct arkfb_info *par = info->par;
mutex_lock(&(par->open_lock));
if (par->ref_count == 0) {
void __iomem *vgabase = par->state.vgabase;
memset(&(par->state), 0, sizeof(struct vgastate));
par->state.vgabase = vgabase;
par->state.flags = VGA_SAVE_MODE | VGA_SAVE_FONTS | VGA_SAVE_CMAP;
par->state.num_crtc = 0x60;
par->state.num_seq = 0x30;
save_vga(&(par->state));
}
par->ref_count++;
mutex_unlock(&(par->open_lock));
return 0;
}
/* Close framebuffer */
static int arkfb_release(struct fb_info *info, int user)
{
struct arkfb_info *par = info->par;
mutex_lock(&(par->open_lock));
if (par->ref_count == 0) {
mutex_unlock(&(par->open_lock));
return -EINVAL;
}
if (par->ref_count == 1) {
restore_vga(&(par->state));
dac_set_mode(par->dac, DAC_PSEUDO8_8);
}
par->ref_count--;
mutex_unlock(&(par->open_lock));
return 0;
}
/* Validate passed in var */
static int arkfb_check_var(struct fb_var_screeninfo *var, struct fb_info *info)
{
int rv, mem, step;
/* Find appropriate format */
rv = svga_match_format (arkfb_formats, var, NULL);
if (rv < 0)
{
fb_err(info, "unsupported mode requested\n");
return rv;
}
/* Do not allow to have real resoulution larger than virtual */
if (var->xres > var->xres_virtual)
var->xres_virtual = var->xres;
if (var->yres > var->yres_virtual)
var->yres_virtual = var->yres;
/* Round up xres_virtual to have proper alignment of lines */
step = arkfb_formats[rv].xresstep - 1;
var->xres_virtual = (var->xres_virtual+step) & ~step;
/* Check whether have enough memory */
mem = ((var->bits_per_pixel * var->xres_virtual) >> 3) * var->yres_virtual;
if (mem > info->screen_size)
{
fb_err(info, "not enough framebuffer memory (%d kB requested, %d kB available)\n",
mem >> 10, (unsigned int) (info->screen_size >> 10));
return -EINVAL;
}
rv = svga_check_timings (&ark_timing_regs, var, info->node);
if (rv < 0)
{
fb_err(info, "invalid timings requested\n");
return rv;
}
/* Interlaced mode is broken */
if (var->vmode & FB_VMODE_INTERLACED)
return -EINVAL;
return 0;
}
/* Set video mode from par */
static int arkfb_set_par(struct fb_info *info)
{
struct arkfb_info *par = info->par;
u32 value, mode, hmul, hdiv, offset_value, screen_size;
u32 bpp = info->var.bits_per_pixel;
u8 regval;
if (bpp != 0) {
info->fix.ypanstep = 1;
info->fix.line_length = (info->var.xres_virtual * bpp) / 8;
info->flags &= ~FBINFO_MISC_TILEBLITTING;
info->tileops = NULL;
/* in 4bpp supports 8p wide tiles only, any tiles otherwise */
info->pixmap.blit_x = (bpp == 4) ? (1 << (8 - 1)) : (~(u32)0);
info->pixmap.blit_y = ~(u32)0;
offset_value = (info->var.xres_virtual * bpp) / 64;
screen_size = info->var.yres_virtual * info->fix.line_length;
} else {
info->fix.ypanstep = 16;
info->fix.line_length = 0;
info->flags |= FBINFO_MISC_TILEBLITTING;
info->tileops = &arkfb_tile_ops;
/* supports 8x16 tiles only */
info->pixmap.blit_x = 1 << (8 - 1);
info->pixmap.blit_y = 1 << (16 - 1);
offset_value = info->var.xres_virtual / 16;
screen_size = (info->var.xres_virtual * info->var.yres_virtual) / 64;
}
info->var.xoffset = 0;
info->var.yoffset = 0;
info->var.activate = FB_ACTIVATE_NOW;
/* Unlock registers */
svga_wcrt_mask(par->state.vgabase, 0x11, 0x00, 0x80);
/* Blank screen and turn off sync */
svga_wseq_mask(par->state.vgabase, 0x01, 0x20, 0x20);
svga_wcrt_mask(par->state.vgabase, 0x17, 0x00, 0x80);
/* Set default values */
svga_set_default_gfx_regs(par->state.vgabase);
svga_set_default_atc_regs(par->state.vgabase);
svga_set_default_seq_regs(par->state.vgabase);
svga_set_default_crt_regs(par->state.vgabase);
svga_wcrt_multi(par->state.vgabase, ark_line_compare_regs, 0xFFFFFFFF);
svga_wcrt_multi(par->state.vgabase, ark_start_address_regs, 0);
/* ARK specific initialization */
svga_wseq_mask(par->state.vgabase, 0x10, 0x1F, 0x1F); /* enable linear framebuffer and full memory access */
svga_wseq_mask(par->state.vgabase, 0x12, 0x03, 0x03); /* 4 MB linear framebuffer size */
vga_wseq(par->state.vgabase, 0x13, info->fix.smem_start >> 16);
vga_wseq(par->state.vgabase, 0x14, info->fix.smem_start >> 24);
vga_wseq(par->state.vgabase, 0x15, 0);
vga_wseq(par->state.vgabase, 0x16, 0);
/* Set the FIFO threshold register */
/* It is fascinating way to store 5-bit value in 8-bit register */
regval = 0x10 | ((threshold & 0x0E) >> 1) | (threshold & 0x01) << 7 | (threshold & 0x10) << 1;
vga_wseq(par->state.vgabase, 0x18, regval);
/* Set the offset register */
fb_dbg(info, "offset register : %d\n", offset_value);
svga_wcrt_multi(par->state.vgabase, ark_offset_regs, offset_value);
/* fix for hi-res textmode */
svga_wcrt_mask(par->state.vgabase, 0x40, 0x08, 0x08);
if (info->var.vmode & FB_VMODE_DOUBLE)
svga_wcrt_mask(par->state.vgabase, 0x09, 0x80, 0x80);
else
svga_wcrt_mask(par->state.vgabase, 0x09, 0x00, 0x80);
if (info->var.vmode & FB_VMODE_INTERLACED)
svga_wcrt_mask(par->state.vgabase, 0x44, 0x04, 0x04);
else
svga_wcrt_mask(par->state.vgabase, 0x44, 0x00, 0x04);
hmul = 1;
hdiv = 1;
mode = svga_match_format(arkfb_formats, &(info->var), &(info->fix));
/* Set mode-specific register values */
switch (mode) {
case 0:
fb_dbg(info, "text mode\n");
svga_set_textmode_vga_regs(par->state.vgabase);
vga_wseq(par->state.vgabase, 0x11, 0x10); /* basic VGA mode */
svga_wcrt_mask(par->state.vgabase, 0x46, 0x00, 0x04); /* 8bit pixel path */
dac_set_mode(par->dac, DAC_PSEUDO8_8);
break;
case 1:
fb_dbg(info, "4 bit pseudocolor\n");
vga_wgfx(par->state.vgabase, VGA_GFX_MODE, 0x40);
vga_wseq(par->state.vgabase, 0x11, 0x10); /* basic VGA mode */
svga_wcrt_mask(par->state.vgabase, 0x46, 0x00, 0x04); /* 8bit pixel path */
dac_set_mode(par->dac, DAC_PSEUDO8_8);
break;
case 2:
fb_dbg(info, "4 bit pseudocolor, planar\n");
vga_wseq(par->state.vgabase, 0x11, 0x10); /* basic VGA mode */
svga_wcrt_mask(par->state.vgabase, 0x46, 0x00, 0x04); /* 8bit pixel path */
dac_set_mode(par->dac, DAC_PSEUDO8_8);
break;
case 3:
fb_dbg(info, "8 bit pseudocolor\n");
vga_wseq(par->state.vgabase, 0x11, 0x16); /* 8bpp accel mode */
if (info->var.pixclock > 20000) {
fb_dbg(info, "not using multiplex\n");
svga_wcrt_mask(par->state.vgabase, 0x46, 0x00, 0x04); /* 8bit pixel path */
dac_set_mode(par->dac, DAC_PSEUDO8_8);
} else {
fb_dbg(info, "using multiplex\n");
svga_wcrt_mask(par->state.vgabase, 0x46, 0x04, 0x04); /* 16bit pixel path */
dac_set_mode(par->dac, DAC_PSEUDO8_16);
hdiv = 2;
}
break;
case 4:
fb_dbg(info, "5/5/5 truecolor\n");
vga_wseq(par->state.vgabase, 0x11, 0x1A); /* 16bpp accel mode */
svga_wcrt_mask(par->state.vgabase, 0x46, 0x04, 0x04); /* 16bit pixel path */
dac_set_mode(par->dac, DAC_RGB1555_16);
break;
case 5:
fb_dbg(info, "5/6/5 truecolor\n");
vga_wseq(par->state.vgabase, 0x11, 0x1A); /* 16bpp accel mode */
svga_wcrt_mask(par->state.vgabase, 0x46, 0x04, 0x04); /* 16bit pixel path */
dac_set_mode(par->dac, DAC_RGB0565_16);
break;
case 6:
fb_dbg(info, "8/8/8 truecolor\n");
vga_wseq(par->state.vgabase, 0x11, 0x16); /* 8bpp accel mode ??? */
svga_wcrt_mask(par->state.vgabase, 0x46, 0x04, 0x04); /* 16bit pixel path */
dac_set_mode(par->dac, DAC_RGB0888_16);
hmul = 3;
hdiv = 2;
break;
case 7:
fb_dbg(info, "8/8/8/8 truecolor\n");
vga_wseq(par->state.vgabase, 0x11, 0x1E); /* 32bpp accel mode */
svga_wcrt_mask(par->state.vgabase, 0x46, 0x04, 0x04); /* 16bit pixel path */
dac_set_mode(par->dac, DAC_RGB8888_16);
hmul = 2;
break;
default:
fb_err(info, "unsupported mode - bug\n");
return -EINVAL;
}
ark_set_pixclock(info, (hdiv * info->var.pixclock) / hmul);
svga_set_timings(par->state.vgabase, &ark_timing_regs, &(info->var), hmul, hdiv,
(info->var.vmode & FB_VMODE_DOUBLE) ? 2 : 1,
(info->var.vmode & FB_VMODE_INTERLACED) ? 2 : 1,
hmul, info->node);
/* Set interlaced mode start/end register */
value = info->var.xres + info->var.left_margin + info->var.right_margin + info->var.hsync_len;
value = ((value * hmul / hdiv) / 8) - 5;
vga_wcrt(par->state.vgabase, 0x42, (value + 1) / 2);
memset_io(info->screen_base, 0x00, screen_size);
/* Device and screen back on */
svga_wcrt_mask(par->state.vgabase, 0x17, 0x80, 0x80);
svga_wseq_mask(par->state.vgabase, 0x01, 0x00, 0x20);
return 0;
}
/* Set a colour register */
static int arkfb_setcolreg(u_int regno, u_int red, u_int green, u_int blue,
u_int transp, struct fb_info *fb)
{
switch (fb->var.bits_per_pixel) {
case 0:
case 4:
if (regno >= 16)
return -EINVAL;
if ((fb->var.bits_per_pixel == 4) &&
(fb->var.nonstd == 0)) {
outb(0xF0, VGA_PEL_MSK);
outb(regno*16, VGA_PEL_IW);
} else {
outb(0x0F, VGA_PEL_MSK);
outb(regno, VGA_PEL_IW);
}
outb(red >> 10, VGA_PEL_D);
outb(green >> 10, VGA_PEL_D);
outb(blue >> 10, VGA_PEL_D);
break;
case 8:
if (regno >= 256)
return -EINVAL;
outb(0xFF, VGA_PEL_MSK);
outb(regno, VGA_PEL_IW);
outb(red >> 10, VGA_PEL_D);
outb(green >> 10, VGA_PEL_D);
outb(blue >> 10, VGA_PEL_D);
break;
case 16:
if (regno >= 16)
return 0;
if (fb->var.green.length == 5)
((u32*)fb->pseudo_palette)[regno] = ((red & 0xF800) >> 1) |
((green & 0xF800) >> 6) | ((blue & 0xF800) >> 11);
else if (fb->var.green.length == 6)
((u32*)fb->pseudo_palette)[regno] = (red & 0xF800) |
((green & 0xFC00) >> 5) | ((blue & 0xF800) >> 11);
else
return -EINVAL;
break;
case 24:
case 32:
if (regno >= 16)
return 0;
((u32*)fb->pseudo_palette)[regno] = ((red & 0xFF00) << 8) |
(green & 0xFF00) | ((blue & 0xFF00) >> 8);
break;
default:
return -EINVAL;
}
return 0;
}
/* Set the display blanking state */
static int arkfb_blank(int blank_mode, struct fb_info *info)
{
struct arkfb_info *par = info->par;
switch (blank_mode) {
case FB_BLANK_UNBLANK:
fb_dbg(info, "unblank\n");
svga_wseq_mask(par->state.vgabase, 0x01, 0x00, 0x20);
svga_wcrt_mask(par->state.vgabase, 0x17, 0x80, 0x80);
break;
case FB_BLANK_NORMAL:
fb_dbg(info, "blank\n");
svga_wseq_mask(par->state.vgabase, 0x01, 0x20, 0x20);
svga_wcrt_mask(par->state.vgabase, 0x17, 0x80, 0x80);
break;
case FB_BLANK_POWERDOWN:
case FB_BLANK_HSYNC_SUSPEND:
case FB_BLANK_VSYNC_SUSPEND:
fb_dbg(info, "sync down\n");
svga_wseq_mask(par->state.vgabase, 0x01, 0x20, 0x20);
svga_wcrt_mask(par->state.vgabase, 0x17, 0x00, 0x80);
break;
}
return 0;
}
/* Pan the display */
static int arkfb_pan_display(struct fb_var_screeninfo *var, struct fb_info *info)
{
struct arkfb_info *par = info->par;
unsigned int offset;
/* Calculate the offset */
if (info->var.bits_per_pixel == 0) {
offset = (var->yoffset / 16) * (info->var.xres_virtual / 2)
+ (var->xoffset / 2);
offset = offset >> 2;
} else {
offset = (var->yoffset * info->fix.line_length) +
(var->xoffset * info->var.bits_per_pixel / 8);
offset = offset >> ((info->var.bits_per_pixel == 4) ? 2 : 3);
}
/* Set the offset */
svga_wcrt_multi(par->state.vgabase, ark_start_address_regs, offset);
return 0;
}
/* ------------------------------------------------------------------------- */
/* Frame buffer operations */
static struct fb_ops arkfb_ops = {
.owner = THIS_MODULE,
.fb_open = arkfb_open,
.fb_release = arkfb_release,
.fb_check_var = arkfb_check_var,
.fb_set_par = arkfb_set_par,
.fb_setcolreg = arkfb_setcolreg,
.fb_blank = arkfb_blank,
.fb_pan_display = arkfb_pan_display,
.fb_fillrect = arkfb_fillrect,
.fb_copyarea = cfb_copyarea,
.fb_imageblit = arkfb_imageblit,
.fb_get_caps = svga_get_caps,
};
/* ------------------------------------------------------------------------- */
/* PCI probe */
static int ark_pci_probe(struct pci_dev *dev, const struct pci_device_id *id)
{
struct pci_bus_region bus_reg;
struct resource vga_res;
struct fb_info *info;
struct arkfb_info *par;
int rc;
u8 regval;
/* Ignore secondary VGA device because there is no VGA arbitration */
if (! svga_primary_device(dev)) {
dev_info(&(dev->dev), "ignoring secondary device\n");
return -ENODEV;
}
/* Allocate and fill driver data structure */
info = framebuffer_alloc(sizeof(struct arkfb_info), &(dev->dev));
if (! info) {
dev_err(&(dev->dev), "cannot allocate memory\n");
return -ENOMEM;
}
par = info->par;
mutex_init(&par->open_lock);
info->flags = FBINFO_PARTIAL_PAN_OK | FBINFO_HWACCEL_YPAN;
info->fbops = &arkfb_ops;
/* Prepare PCI device */
rc = pci_enable_device(dev);
if (rc < 0) {
dev_err(info->device, "cannot enable PCI device\n");
goto err_enable_device;
}
rc = pci_request_regions(dev, "arkfb");
if (rc < 0) {
dev_err(info->device, "cannot reserve framebuffer region\n");
goto err_request_regions;
}
par->dac = ics5342_init(ark_dac_read_regs, ark_dac_write_regs, info);
if (! par->dac) {
rc = -ENOMEM;
dev_err(info->device, "RAMDAC initialization failed\n");
goto err_dac;
}
info->fix.smem_start = pci_resource_start(dev, 0);
info->fix.smem_len = pci_resource_len(dev, 0);
/* Map physical IO memory address into kernel space */
info->screen_base = pci_iomap(dev, 0, 0);
if (! info->screen_base) {
rc = -ENOMEM;
dev_err(info->device, "iomap for framebuffer failed\n");
goto err_iomap;
}
bus_reg.start = 0;
bus_reg.end = 64 * 1024;
vga_res.flags = IORESOURCE_IO;
pcibios_bus_to_resource(dev->bus, &vga_res, &bus_reg);
par->state.vgabase = (void __iomem *) (unsigned long) vga_res.start;
/* FIXME get memsize */
regval = vga_rseq(par->state.vgabase, 0x10);
info->screen_size = (1 << (regval >> 6)) << 20;
info->fix.smem_len = info->screen_size;
strcpy(info->fix.id, "ARK 2000PV");
info->fix.mmio_start = 0;
info->fix.mmio_len = 0;
info->fix.type = FB_TYPE_PACKED_PIXELS;
info->fix.visual = FB_VISUAL_PSEUDOCOLOR;
info->fix.ypanstep = 0;
info->fix.accel = FB_ACCEL_NONE;
info->pseudo_palette = (void*) (par->pseudo_palette);
/* Prepare startup mode */
rc = fb_find_mode(&(info->var), info, mode_option, NULL, 0, NULL, 8);
if (! ((rc == 1) || (rc == 2))) {
rc = -EINVAL;
dev_err(info->device, "mode %s not found\n", mode_option);
goto err_find_mode;
}
rc = fb_alloc_cmap(&info->cmap, 256, 0);
if (rc < 0) {
dev_err(info->device, "cannot allocate colormap\n");
goto err_alloc_cmap;
}
rc = register_framebuffer(info);
if (rc < 0) {
dev_err(info->device, "cannot register framebuffer\n");
goto err_reg_fb;
}
fb_info(info, "%s on %s, %d MB RAM\n",
info->fix.id, pci_name(dev), info->fix.smem_len >> 20);
/* Record a reference to the driver data */
pci_set_drvdata(dev, info);
#ifdef CONFIG_MTRR
if (mtrr) {
par->mtrr_reg = -1;
par->mtrr_reg = mtrr_add(info->fix.smem_start, info->fix.smem_len, MTRR_TYPE_WRCOMB, 1);
}
#endif
return 0;
/* Error handling */
err_reg_fb:
fb_dealloc_cmap(&info->cmap);
err_alloc_cmap:
err_find_mode:
pci_iounmap(dev, info->screen_base);
err_iomap:
dac_release(par->dac);
err_dac:
pci_release_regions(dev);
err_request_regions:
/* pci_disable_device(dev); */
err_enable_device:
framebuffer_release(info);
return rc;
}
/* PCI remove */
static void ark_pci_remove(struct pci_dev *dev)
{
struct fb_info *info = pci_get_drvdata(dev);
if (info) {
struct arkfb_info *par = info->par;
#ifdef CONFIG_MTRR
if (par->mtrr_reg >= 0) {
mtrr_del(par->mtrr_reg, 0, 0);
par->mtrr_reg = -1;
}
#endif
dac_release(par->dac);
unregister_framebuffer(info);
fb_dealloc_cmap(&info->cmap);
pci_iounmap(dev, info->screen_base);
pci_release_regions(dev);
/* pci_disable_device(dev); */
framebuffer_release(info);
}
}
#ifdef CONFIG_PM
/* PCI suspend */
static int ark_pci_suspend (struct pci_dev* dev, pm_message_t state)
{
struct fb_info *info = pci_get_drvdata(dev);
struct arkfb_info *par = info->par;
dev_info(info->device, "suspend\n");
console_lock();
mutex_lock(&(par->open_lock));
if ((state.event == PM_EVENT_FREEZE) || (par->ref_count == 0)) {
mutex_unlock(&(par->open_lock));
console_unlock();
return 0;
}
fb_set_suspend(info, 1);
pci_save_state(dev);
pci_disable_device(dev);
pci_set_power_state(dev, pci_choose_state(dev, state));
mutex_unlock(&(par->open_lock));
console_unlock();
return 0;
}
/* PCI resume */
static int ark_pci_resume (struct pci_dev* dev)
{
struct fb_info *info = pci_get_drvdata(dev);
struct arkfb_info *par = info->par;
dev_info(info->device, "resume\n");
console_lock();
mutex_lock(&(par->open_lock));
if (par->ref_count == 0)
goto fail;
pci_set_power_state(dev, PCI_D0);
pci_restore_state(dev);
if (pci_enable_device(dev))
goto fail;
pci_set_master(dev);
arkfb_set_par(info);
fb_set_suspend(info, 0);
fail:
mutex_unlock(&(par->open_lock));
console_unlock();
return 0;
}
#else
#define ark_pci_suspend NULL
#define ark_pci_resume NULL
#endif /* CONFIG_PM */
/* List of boards that we are trying to support */
static struct pci_device_id ark_devices[] = {
{PCI_DEVICE(0xEDD8, 0xA099)},
{0, 0, 0, 0, 0, 0, 0}
};
MODULE_DEVICE_TABLE(pci, ark_devices);
static struct pci_driver arkfb_pci_driver = {
.name = "arkfb",
.id_table = ark_devices,
.probe = ark_pci_probe,
.remove = ark_pci_remove,
.suspend = ark_pci_suspend,
.resume = ark_pci_resume,
};
/* Cleanup */
static void __exit arkfb_cleanup(void)
{
pr_debug("arkfb: cleaning up\n");
pci_unregister_driver(&arkfb_pci_driver);
}
/* Driver Initialisation */
static int __init arkfb_init(void)
{
#ifndef MODULE
char *option = NULL;
if (fb_get_options("arkfb", &option))
return -ENODEV;
if (option && *option)
mode_option = option;
#endif
pr_debug("arkfb: initializing\n");
return pci_register_driver(&arkfb_pci_driver);
}
module_init(arkfb_init);
module_exit(arkfb_cleanup);
| gpl-2.0 |
jshafer817/sailfish_kernel_hp_tenderloin30 | sound/usb/mixer.c | 611 | 64034 | /*
* (Tentative) USB Audio Driver for ALSA
*
* Mixer control part
*
* Copyright (c) 2002 by Takashi Iwai <tiwai@suse.de>
*
* Many codes borrowed from audio.c by
* Alan Cox (alan@lxorguk.ukuu.org.uk)
* Thomas Sailer (sailer@ife.ee.ethz.ch)
*
*
* 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
*
*/
/*
* TODOs, for both the mixer and the streaming interfaces:
*
* - support for UAC2 effect units
* - support for graphical equalizers
* - RANGE and MEM set commands (UAC2)
* - RANGE and MEM interrupt dispatchers (UAC2)
* - audio channel clustering (UAC2)
* - audio sample rate converter units (UAC2)
* - proper handling of clock multipliers (UAC2)
* - dispatch clock change notifications (UAC2)
* - stop PCM streams which use a clock that became invalid
* - stop PCM streams which use a clock selector that has changed
* - parse available sample rates again when clock sources changed
*/
#include <linux/bitops.h>
#include <linux/init.h>
#include <linux/list.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/usb.h>
#include <linux/usb/audio.h>
#include <linux/usb/audio-v2.h>
#include <sound/core.h>
#include <sound/control.h>
#include <sound/hwdep.h>
#include <sound/info.h>
#include <sound/tlv.h>
#include "usbaudio.h"
#include "mixer.h"
#include "helper.h"
#include "mixer_quirks.h"
#include "power.h"
#define MAX_ID_ELEMS 256
struct usb_audio_term {
int id;
int type;
int channels;
unsigned int chconfig;
int name;
};
struct usbmix_name_map;
struct mixer_build {
struct snd_usb_audio *chip;
struct usb_mixer_interface *mixer;
unsigned char *buffer;
unsigned int buflen;
DECLARE_BITMAP(unitbitmap, MAX_ID_ELEMS);
struct usb_audio_term oterm;
const struct usbmix_name_map *map;
const struct usbmix_selector_map *selector_map;
};
/*E-mu 0202/0404/0204 eXtension Unit(XU) control*/
enum {
USB_XU_CLOCK_RATE = 0xe301,
USB_XU_CLOCK_SOURCE = 0xe302,
USB_XU_DIGITAL_IO_STATUS = 0xe303,
USB_XU_DEVICE_OPTIONS = 0xe304,
USB_XU_DIRECT_MONITORING = 0xe305,
USB_XU_METERING = 0xe306
};
enum {
USB_XU_CLOCK_SOURCE_SELECTOR = 0x02, /* clock source*/
USB_XU_CLOCK_RATE_SELECTOR = 0x03, /* clock rate */
USB_XU_DIGITAL_FORMAT_SELECTOR = 0x01, /* the spdif format */
USB_XU_SOFT_LIMIT_SELECTOR = 0x03 /* soft limiter */
};
/*
* manual mapping of mixer names
* if the mixer topology is too complicated and the parsed names are
* ambiguous, add the entries in usbmixer_maps.c.
*/
#include "mixer_maps.c"
static const struct usbmix_name_map *
find_map(struct mixer_build *state, int unitid, int control)
{
const struct usbmix_name_map *p = state->map;
if (!p)
return NULL;
for (p = state->map; p->id; p++) {
if (p->id == unitid &&
(!control || !p->control || control == p->control))
return p;
}
return NULL;
}
/* get the mapped name if the unit matches */
static int
check_mapped_name(const struct usbmix_name_map *p, char *buf, int buflen)
{
if (!p || !p->name)
return 0;
buflen--;
return strlcpy(buf, p->name, buflen);
}
/* check whether the control should be ignored */
static inline int
check_ignored_ctl(const struct usbmix_name_map *p)
{
if (!p || p->name || p->dB)
return 0;
return 1;
}
/* dB mapping */
static inline void check_mapped_dB(const struct usbmix_name_map *p,
struct usb_mixer_elem_info *cval)
{
if (p && p->dB) {
cval->dBmin = p->dB->min;
cval->dBmax = p->dB->max;
cval->initialized = 1;
}
}
/* get the mapped selector source name */
static int check_mapped_selector_name(struct mixer_build *state, int unitid,
int index, char *buf, int buflen)
{
const struct usbmix_selector_map *p;
if (! state->selector_map)
return 0;
for (p = state->selector_map; p->id; p++) {
if (p->id == unitid && index < p->count)
return strlcpy(buf, p->names[index], buflen);
}
return 0;
}
/*
* find an audio control unit with the given unit id
*/
static void *find_audio_control_unit(struct mixer_build *state, unsigned char unit)
{
/* we just parse the header */
struct uac_feature_unit_descriptor *hdr = NULL;
while ((hdr = snd_usb_find_desc(state->buffer, state->buflen, hdr,
USB_DT_CS_INTERFACE)) != NULL) {
if (hdr->bLength >= 4 &&
hdr->bDescriptorSubtype >= UAC_INPUT_TERMINAL &&
hdr->bDescriptorSubtype <= UAC2_SAMPLE_RATE_CONVERTER &&
hdr->bUnitID == unit)
return hdr;
}
return NULL;
}
/*
* copy a string with the given id
*/
static int snd_usb_copy_string_desc(struct mixer_build *state, int index, char *buf, int maxlen)
{
int len = usb_string(state->chip->dev, index, buf, maxlen - 1);
buf[len] = 0;
return len;
}
/*
* convert from the byte/word on usb descriptor to the zero-based integer
*/
static int convert_signed_value(struct usb_mixer_elem_info *cval, int val)
{
switch (cval->val_type) {
case USB_MIXER_BOOLEAN:
return !!val;
case USB_MIXER_INV_BOOLEAN:
return !val;
case USB_MIXER_U8:
val &= 0xff;
break;
case USB_MIXER_S8:
val &= 0xff;
if (val >= 0x80)
val -= 0x100;
break;
case USB_MIXER_U16:
val &= 0xffff;
break;
case USB_MIXER_S16:
val &= 0xffff;
if (val >= 0x8000)
val -= 0x10000;
break;
}
return val;
}
/*
* convert from the zero-based int to the byte/word for usb descriptor
*/
static int convert_bytes_value(struct usb_mixer_elem_info *cval, int val)
{
switch (cval->val_type) {
case USB_MIXER_BOOLEAN:
return !!val;
case USB_MIXER_INV_BOOLEAN:
return !val;
case USB_MIXER_S8:
case USB_MIXER_U8:
return val & 0xff;
case USB_MIXER_S16:
case USB_MIXER_U16:
return val & 0xffff;
}
return 0; /* not reached */
}
static int get_relative_value(struct usb_mixer_elem_info *cval, int val)
{
if (! cval->res)
cval->res = 1;
if (val < cval->min)
return 0;
else if (val >= cval->max)
return (cval->max - cval->min + cval->res - 1) / cval->res;
else
return (val - cval->min) / cval->res;
}
static int get_abs_value(struct usb_mixer_elem_info *cval, int val)
{
if (val < 0)
return cval->min;
if (! cval->res)
cval->res = 1;
val *= cval->res;
val += cval->min;
if (val > cval->max)
return cval->max;
return val;
}
/*
* retrieve a mixer value
*/
static int get_ctl_value_v1(struct usb_mixer_elem_info *cval, int request, int validx, int *value_ret)
{
struct snd_usb_audio *chip = cval->mixer->chip;
unsigned char buf[2];
int val_len = cval->val_type >= USB_MIXER_S16 ? 2 : 1;
int timeout = 10;
int idx = 0, err;
err = snd_usb_autoresume(cval->mixer->chip);
if (err < 0)
return -EIO;
down_read(&chip->shutdown_rwsem);
while (timeout-- > 0) {
if (chip->shutdown)
break;
idx = snd_usb_ctrl_intf(chip) | (cval->id << 8);
if (snd_usb_ctl_msg(chip->dev, usb_rcvctrlpipe(chip->dev, 0), request,
USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_IN,
validx, idx, buf, val_len, 100) >= val_len) {
*value_ret = convert_signed_value(cval, snd_usb_combine_bytes(buf, val_len));
err = 0;
goto out;
}
}
snd_printdd(KERN_ERR "cannot get ctl value: req = %#x, wValue = %#x, wIndex = %#x, type = %d\n",
request, validx, idx, cval->val_type);
err = -EINVAL;
out:
up_read(&chip->shutdown_rwsem);
snd_usb_autosuspend(cval->mixer->chip);
return err;
}
static int get_ctl_value_v2(struct usb_mixer_elem_info *cval, int request, int validx, int *value_ret)
{
struct snd_usb_audio *chip = cval->mixer->chip;
unsigned char buf[2 + 3*sizeof(__u16)]; /* enough space for one range */
unsigned char *val;
int idx = 0, ret, size;
__u8 bRequest;
if (request == UAC_GET_CUR) {
bRequest = UAC2_CS_CUR;
size = sizeof(__u16);
} else {
bRequest = UAC2_CS_RANGE;
size = sizeof(buf);
}
memset(buf, 0, sizeof(buf));
ret = snd_usb_autoresume(chip) ? -EIO : 0;
if (ret)
goto error;
down_read(&chip->shutdown_rwsem);
if (chip->shutdown)
ret = -ENODEV;
else {
idx = snd_usb_ctrl_intf(chip) | (cval->id << 8);
ret = snd_usb_ctl_msg(chip->dev, usb_rcvctrlpipe(chip->dev, 0), bRequest,
USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_IN,
validx, idx, buf, size, 1000);
}
up_read(&chip->shutdown_rwsem);
snd_usb_autosuspend(chip);
if (ret < 0) {
error:
snd_printk(KERN_ERR "cannot get ctl value: req = %#x, wValue = %#x, wIndex = %#x, type = %d\n",
request, validx, idx, cval->val_type);
return ret;
}
/* FIXME: how should we handle multiple triplets here? */
switch (request) {
case UAC_GET_CUR:
val = buf;
break;
case UAC_GET_MIN:
val = buf + sizeof(__u16);
break;
case UAC_GET_MAX:
val = buf + sizeof(__u16) * 2;
break;
case UAC_GET_RES:
val = buf + sizeof(__u16) * 3;
break;
default:
return -EINVAL;
}
*value_ret = convert_signed_value(cval, snd_usb_combine_bytes(val, sizeof(__u16)));
return 0;
}
static int get_ctl_value(struct usb_mixer_elem_info *cval, int request, int validx, int *value_ret)
{
return (cval->mixer->protocol == UAC_VERSION_1) ?
get_ctl_value_v1(cval, request, validx, value_ret) :
get_ctl_value_v2(cval, request, validx, value_ret);
}
static int get_cur_ctl_value(struct usb_mixer_elem_info *cval, int validx, int *value)
{
return get_ctl_value(cval, UAC_GET_CUR, validx, value);
}
/* channel = 0: master, 1 = first channel */
static inline int get_cur_mix_raw(struct usb_mixer_elem_info *cval,
int channel, int *value)
{
return get_ctl_value(cval, UAC_GET_CUR, (cval->control << 8) | channel, value);
}
static int get_cur_mix_value(struct usb_mixer_elem_info *cval,
int channel, int index, int *value)
{
int err;
if (cval->cached & (1 << channel)) {
*value = cval->cache_val[index];
return 0;
}
err = get_cur_mix_raw(cval, channel, value);
if (err < 0) {
if (!cval->mixer->ignore_ctl_error)
snd_printd(KERN_ERR "cannot get current value for control %d ch %d: err = %d\n",
cval->control, channel, err);
return err;
}
cval->cached |= 1 << channel;
cval->cache_val[index] = *value;
return 0;
}
/*
* set a mixer value
*/
int snd_usb_mixer_set_ctl_value(struct usb_mixer_elem_info *cval,
int request, int validx, int value_set)
{
struct snd_usb_audio *chip = cval->mixer->chip;
unsigned char buf[2];
int idx = 0, val_len, err, timeout = 10;
if (cval->mixer->protocol == UAC_VERSION_1) {
val_len = cval->val_type >= USB_MIXER_S16 ? 2 : 1;
} else { /* UAC_VERSION_2 */
/* audio class v2 controls are always 2 bytes in size */
val_len = sizeof(__u16);
/* FIXME */
if (request != UAC_SET_CUR) {
snd_printdd(KERN_WARNING "RANGE setting not yet supported\n");
return -EINVAL;
}
request = UAC2_CS_CUR;
}
value_set = convert_bytes_value(cval, value_set);
buf[0] = value_set & 0xff;
buf[1] = (value_set >> 8) & 0xff;
err = snd_usb_autoresume(chip);
if (err < 0)
return -EIO;
down_read(&chip->shutdown_rwsem);
while (timeout-- > 0) {
if (chip->shutdown)
break;
idx = snd_usb_ctrl_intf(chip) | (cval->id << 8);
if (snd_usb_ctl_msg(chip->dev,
usb_sndctrlpipe(chip->dev, 0), request,
USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_OUT,
validx, idx, buf, val_len, 100) >= 0) {
err = 0;
goto out;
}
}
snd_printdd(KERN_ERR "cannot set ctl value: req = %#x, wValue = %#x, wIndex = %#x, type = %d, data = %#x/%#x\n",
request, validx, idx, cval->val_type, buf[0], buf[1]);
err = -EINVAL;
out:
up_read(&chip->shutdown_rwsem);
snd_usb_autosuspend(chip);
return err;
}
static int set_cur_ctl_value(struct usb_mixer_elem_info *cval, int validx, int value)
{
return snd_usb_mixer_set_ctl_value(cval, UAC_SET_CUR, validx, value);
}
static int set_cur_mix_value(struct usb_mixer_elem_info *cval, int channel,
int index, int value)
{
int err;
unsigned int read_only = (channel == 0) ?
cval->master_readonly :
cval->ch_readonly & (1 << (channel - 1));
if (read_only) {
snd_printdd(KERN_INFO "%s(): channel %d of control %d is read_only\n",
__func__, channel, cval->control);
return 0;
}
err = snd_usb_mixer_set_ctl_value(cval, UAC_SET_CUR, (cval->control << 8) | channel,
value);
if (err < 0)
return err;
cval->cached |= 1 << channel;
cval->cache_val[index] = value;
return 0;
}
/*
* TLV callback for mixer volume controls
*/
static int mixer_vol_tlv(struct snd_kcontrol *kcontrol, int op_flag,
unsigned int size, unsigned int __user *_tlv)
{
struct usb_mixer_elem_info *cval = kcontrol->private_data;
DECLARE_TLV_DB_MINMAX(scale, 0, 0);
if (size < sizeof(scale))
return -ENOMEM;
scale[2] = cval->dBmin;
scale[3] = cval->dBmax;
if (copy_to_user(_tlv, scale, sizeof(scale)))
return -EFAULT;
return 0;
}
/*
* parser routines begin here...
*/
static int parse_audio_unit(struct mixer_build *state, int unitid);
/*
* check if the input/output channel routing is enabled on the given bitmap.
* used for mixer unit parser
*/
static int check_matrix_bitmap(unsigned char *bmap, int ich, int och, int num_outs)
{
int idx = ich * num_outs + och;
return bmap[idx >> 3] & (0x80 >> (idx & 7));
}
/*
* add an alsa control element
* search and increment the index until an empty slot is found.
*
* if failed, give up and free the control instance.
*/
int snd_usb_mixer_add_control(struct usb_mixer_interface *mixer,
struct snd_kcontrol *kctl)
{
struct usb_mixer_elem_info *cval = kctl->private_data;
int err;
while (snd_ctl_find_id(mixer->chip->card, &kctl->id))
kctl->id.index++;
if ((err = snd_ctl_add(mixer->chip->card, kctl)) < 0) {
snd_printd(KERN_ERR "cannot add control (err = %d)\n", err);
return err;
}
cval->elem_id = &kctl->id;
cval->next_id_elem = mixer->id_elems[cval->id];
mixer->id_elems[cval->id] = cval;
return 0;
}
/*
* get a terminal name string
*/
static struct iterm_name_combo {
int type;
char *name;
} iterm_names[] = {
{ 0x0300, "Output" },
{ 0x0301, "Speaker" },
{ 0x0302, "Headphone" },
{ 0x0303, "HMD Audio" },
{ 0x0304, "Desktop Speaker" },
{ 0x0305, "Room Speaker" },
{ 0x0306, "Com Speaker" },
{ 0x0307, "LFE" },
{ 0x0600, "External In" },
{ 0x0601, "Analog In" },
{ 0x0602, "Digital In" },
{ 0x0603, "Line" },
{ 0x0604, "Legacy In" },
{ 0x0605, "IEC958 In" },
{ 0x0606, "1394 DA Stream" },
{ 0x0607, "1394 DV Stream" },
{ 0x0700, "Embedded" },
{ 0x0701, "Noise Source" },
{ 0x0702, "Equalization Noise" },
{ 0x0703, "CD" },
{ 0x0704, "DAT" },
{ 0x0705, "DCC" },
{ 0x0706, "MiniDisk" },
{ 0x0707, "Analog Tape" },
{ 0x0708, "Phonograph" },
{ 0x0709, "VCR Audio" },
{ 0x070a, "Video Disk Audio" },
{ 0x070b, "DVD Audio" },
{ 0x070c, "TV Tuner Audio" },
{ 0x070d, "Satellite Rec Audio" },
{ 0x070e, "Cable Tuner Audio" },
{ 0x070f, "DSS Audio" },
{ 0x0710, "Radio Receiver" },
{ 0x0711, "Radio Transmitter" },
{ 0x0712, "Multi-Track Recorder" },
{ 0x0713, "Synthesizer" },
{ 0 },
};
static int get_term_name(struct mixer_build *state, struct usb_audio_term *iterm,
unsigned char *name, int maxlen, int term_only)
{
struct iterm_name_combo *names;
if (iterm->name)
return snd_usb_copy_string_desc(state, iterm->name, name, maxlen);
/* virtual type - not a real terminal */
if (iterm->type >> 16) {
if (term_only)
return 0;
switch (iterm->type >> 16) {
case UAC_SELECTOR_UNIT:
strcpy(name, "Selector"); return 8;
case UAC1_PROCESSING_UNIT:
strcpy(name, "Process Unit"); return 12;
case UAC1_EXTENSION_UNIT:
strcpy(name, "Ext Unit"); return 8;
case UAC_MIXER_UNIT:
strcpy(name, "Mixer"); return 5;
default:
return sprintf(name, "Unit %d", iterm->id);
}
}
switch (iterm->type & 0xff00) {
case 0x0100:
strcpy(name, "PCM"); return 3;
case 0x0200:
strcpy(name, "Mic"); return 3;
case 0x0400:
strcpy(name, "Headset"); return 7;
case 0x0500:
strcpy(name, "Phone"); return 5;
}
for (names = iterm_names; names->type; names++)
if (names->type == iterm->type) {
strcpy(name, names->name);
return strlen(names->name);
}
return 0;
}
/*
* parse the source unit recursively until it reaches to a terminal
* or a branched unit.
*/
static int check_input_term(struct mixer_build *state, int id, struct usb_audio_term *term)
{
int err;
void *p1;
memset(term, 0, sizeof(*term));
while ((p1 = find_audio_control_unit(state, id)) != NULL) {
unsigned char *hdr = p1;
term->id = id;
switch (hdr[2]) {
case UAC_INPUT_TERMINAL:
if (state->mixer->protocol == UAC_VERSION_1) {
struct uac_input_terminal_descriptor *d = p1;
term->type = le16_to_cpu(d->wTerminalType);
term->channels = d->bNrChannels;
term->chconfig = le16_to_cpu(d->wChannelConfig);
term->name = d->iTerminal;
} else { /* UAC_VERSION_2 */
struct uac2_input_terminal_descriptor *d = p1;
term->type = le16_to_cpu(d->wTerminalType);
term->channels = d->bNrChannels;
term->chconfig = le32_to_cpu(d->bmChannelConfig);
term->name = d->iTerminal;
/* call recursively to get the clock selectors */
err = check_input_term(state, d->bCSourceID, term);
if (err < 0)
return err;
}
return 0;
case UAC_FEATURE_UNIT: {
/* the header is the same for v1 and v2 */
struct uac_feature_unit_descriptor *d = p1;
id = d->bSourceID;
break; /* continue to parse */
}
case UAC_MIXER_UNIT: {
struct uac_mixer_unit_descriptor *d = p1;
term->type = d->bDescriptorSubtype << 16; /* virtual type */
term->channels = uac_mixer_unit_bNrChannels(d);
term->chconfig = uac_mixer_unit_wChannelConfig(d, state->mixer->protocol);
term->name = uac_mixer_unit_iMixer(d);
return 0;
}
case UAC_SELECTOR_UNIT:
case UAC2_CLOCK_SELECTOR: {
struct uac_selector_unit_descriptor *d = p1;
/* call recursively to retrieve the channel info */
err = check_input_term(state, d->baSourceID[0], term);
if (err < 0)
return err;
term->type = d->bDescriptorSubtype << 16; /* virtual type */
term->id = id;
term->name = uac_selector_unit_iSelector(d);
return 0;
}
case UAC1_PROCESSING_UNIT:
case UAC1_EXTENSION_UNIT: {
struct uac_processing_unit_descriptor *d = p1;
if (d->bNrInPins) {
id = d->baSourceID[0];
break; /* continue to parse */
}
term->type = d->bDescriptorSubtype << 16; /* virtual type */
term->channels = uac_processing_unit_bNrChannels(d);
term->chconfig = uac_processing_unit_wChannelConfig(d, state->mixer->protocol);
term->name = uac_processing_unit_iProcessing(d, state->mixer->protocol);
return 0;
}
case UAC2_CLOCK_SOURCE: {
struct uac_clock_source_descriptor *d = p1;
term->type = d->bDescriptorSubtype << 16; /* virtual type */
term->id = id;
term->name = d->iClockSource;
return 0;
}
default:
return -ENODEV;
}
}
return -ENODEV;
}
/*
* Feature Unit
*/
/* feature unit control information */
struct usb_feature_control_info {
const char *name;
unsigned int type; /* control type (mute, volume, etc.) */
};
static struct usb_feature_control_info audio_feature_info[] = {
{ "Mute", USB_MIXER_INV_BOOLEAN },
{ "Volume", USB_MIXER_S16 },
{ "Tone Control - Bass", USB_MIXER_S8 },
{ "Tone Control - Mid", USB_MIXER_S8 },
{ "Tone Control - Treble", USB_MIXER_S8 },
{ "Graphic Equalizer", USB_MIXER_S8 }, /* FIXME: not implemeted yet */
{ "Auto Gain Control", USB_MIXER_BOOLEAN },
{ "Delay Control", USB_MIXER_U16 },
{ "Bass Boost", USB_MIXER_BOOLEAN },
{ "Loudness", USB_MIXER_BOOLEAN },
/* UAC2 specific */
{ "Input Gain Control", USB_MIXER_U16 },
{ "Input Gain Pad Control", USB_MIXER_BOOLEAN },
{ "Phase Inverter Control", USB_MIXER_BOOLEAN },
};
/* private_free callback */
static void usb_mixer_elem_free(struct snd_kcontrol *kctl)
{
kfree(kctl->private_data);
kctl->private_data = NULL;
}
/*
* interface to ALSA control for feature/mixer units
*/
/* volume control quirks */
static void volume_control_quirks(struct usb_mixer_elem_info *cval,
struct snd_kcontrol *kctl)
{
switch (cval->mixer->chip->usb_id) {
case USB_ID(0x0471, 0x0101):
case USB_ID(0x0471, 0x0104):
case USB_ID(0x0471, 0x0105):
case USB_ID(0x0672, 0x1041):
/* quirk for UDA1321/N101.
* note that detection between firmware 2.1.1.7 (N101)
* and later 2.1.1.21 is not very clear from datasheets.
* I hope that the min value is -15360 for newer firmware --jk
*/
if (!strcmp(kctl->id.name, "PCM Playback Volume") &&
cval->min == -15616) {
snd_printk(KERN_INFO
"set volume quirk for UDA1321/N101 chip\n");
cval->max = -256;
}
break;
case USB_ID(0x046d, 0x09a4):
if (!strcmp(kctl->id.name, "Mic Capture Volume")) {
snd_printk(KERN_INFO
"set volume quirk for QuickCam E3500\n");
cval->min = 6080;
cval->max = 8768;
cval->res = 192;
}
break;
case USB_ID(0x046d, 0x0808):
case USB_ID(0x046d, 0x0809):
case USB_ID(0x046d, 0x0991):
/* Most audio usb devices lie about volume resolution.
* Most Logitech webcams have res = 384.
* Proboly there is some logitech magic behind this number --fishor
*/
if (!strcmp(kctl->id.name, "Mic Capture Volume")) {
snd_printk(KERN_INFO
"set resolution quirk: cval->res = 384\n");
cval->res = 384;
}
break;
}
}
/*
* retrieve the minimum and maximum values for the specified control
*/
static int get_min_max_with_quirks(struct usb_mixer_elem_info *cval,
int default_min, struct snd_kcontrol *kctl)
{
/* for failsafe */
cval->min = default_min;
cval->max = cval->min + 1;
cval->res = 1;
cval->dBmin = cval->dBmax = 0;
if (cval->val_type == USB_MIXER_BOOLEAN ||
cval->val_type == USB_MIXER_INV_BOOLEAN) {
cval->initialized = 1;
} else {
int minchn = 0;
if (cval->cmask) {
int i;
for (i = 0; i < MAX_CHANNELS; i++)
if (cval->cmask & (1 << i)) {
minchn = i + 1;
break;
}
}
if (get_ctl_value(cval, UAC_GET_MAX, (cval->control << 8) | minchn, &cval->max) < 0 ||
get_ctl_value(cval, UAC_GET_MIN, (cval->control << 8) | minchn, &cval->min) < 0) {
snd_printd(KERN_ERR "%d:%d: cannot get min/max values for control %d (id %d)\n",
cval->id, snd_usb_ctrl_intf(cval->mixer->chip), cval->control, cval->id);
return -EINVAL;
}
if (get_ctl_value(cval, UAC_GET_RES, (cval->control << 8) | minchn, &cval->res) < 0) {
cval->res = 1;
} else {
int last_valid_res = cval->res;
while (cval->res > 1) {
if (snd_usb_mixer_set_ctl_value(cval, UAC_SET_RES,
(cval->control << 8) | minchn, cval->res / 2) < 0)
break;
cval->res /= 2;
}
if (get_ctl_value(cval, UAC_GET_RES, (cval->control << 8) | minchn, &cval->res) < 0)
cval->res = last_valid_res;
}
if (cval->res == 0)
cval->res = 1;
/* Additional checks for the proper resolution
*
* Some devices report smaller resolutions than actually
* reacting. They don't return errors but simply clip
* to the lower aligned value.
*/
if (cval->min + cval->res < cval->max) {
int last_valid_res = cval->res;
int saved, test, check;
get_cur_mix_raw(cval, minchn, &saved);
for (;;) {
test = saved;
if (test < cval->max)
test += cval->res;
else
test -= cval->res;
if (test < cval->min || test > cval->max ||
set_cur_mix_value(cval, minchn, 0, test) ||
get_cur_mix_raw(cval, minchn, &check)) {
cval->res = last_valid_res;
break;
}
if (test == check)
break;
cval->res *= 2;
}
set_cur_mix_value(cval, minchn, 0, saved);
}
cval->initialized = 1;
}
if (kctl)
volume_control_quirks(cval, kctl);
/* USB descriptions contain the dB scale in 1/256 dB unit
* while ALSA TLV contains in 1/100 dB unit
*/
cval->dBmin = (convert_signed_value(cval, cval->min) * 100) / 256;
cval->dBmax = (convert_signed_value(cval, cval->max) * 100) / 256;
if (cval->dBmin > cval->dBmax) {
/* something is wrong; assume it's either from/to 0dB */
if (cval->dBmin < 0)
cval->dBmax = 0;
else if (cval->dBmin > 0)
cval->dBmin = 0;
if (cval->dBmin > cval->dBmax) {
/* totally crap, return an error */
return -EINVAL;
}
}
return 0;
}
#define get_min_max(cval, def) get_min_max_with_quirks(cval, def, NULL)
/* get a feature/mixer unit info */
static int mixer_ctl_feature_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
struct usb_mixer_elem_info *cval = kcontrol->private_data;
if (cval->val_type == USB_MIXER_BOOLEAN ||
cval->val_type == USB_MIXER_INV_BOOLEAN)
uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
else
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = cval->channels;
if (cval->val_type == USB_MIXER_BOOLEAN ||
cval->val_type == USB_MIXER_INV_BOOLEAN) {
uinfo->value.integer.min = 0;
uinfo->value.integer.max = 1;
} else {
if (!cval->initialized) {
get_min_max_with_quirks(cval, 0, kcontrol);
if (cval->initialized && cval->dBmin >= cval->dBmax) {
kcontrol->vd[0].access &=
~(SNDRV_CTL_ELEM_ACCESS_TLV_READ |
SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK);
snd_ctl_notify(cval->mixer->chip->card,
SNDRV_CTL_EVENT_MASK_INFO,
&kcontrol->id);
}
}
uinfo->value.integer.min = 0;
uinfo->value.integer.max =
(cval->max - cval->min + cval->res - 1) / cval->res;
}
return 0;
}
/* get the current value from feature/mixer unit */
static int mixer_ctl_feature_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct usb_mixer_elem_info *cval = kcontrol->private_data;
int c, cnt, val, err;
ucontrol->value.integer.value[0] = cval->min;
if (cval->cmask) {
cnt = 0;
for (c = 0; c < MAX_CHANNELS; c++) {
if (!(cval->cmask & (1 << c)))
continue;
err = get_cur_mix_value(cval, c + 1, cnt, &val);
if (err < 0)
return cval->mixer->ignore_ctl_error ? 0 : err;
val = get_relative_value(cval, val);
ucontrol->value.integer.value[cnt] = val;
cnt++;
}
return 0;
} else {
/* master channel */
err = get_cur_mix_value(cval, 0, 0, &val);
if (err < 0)
return cval->mixer->ignore_ctl_error ? 0 : err;
val = get_relative_value(cval, val);
ucontrol->value.integer.value[0] = val;
}
return 0;
}
/* put the current value to feature/mixer unit */
static int mixer_ctl_feature_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct usb_mixer_elem_info *cval = kcontrol->private_data;
int c, cnt, val, oval, err;
int changed = 0;
if (cval->cmask) {
cnt = 0;
for (c = 0; c < MAX_CHANNELS; c++) {
if (!(cval->cmask & (1 << c)))
continue;
err = get_cur_mix_value(cval, c + 1, cnt, &oval);
if (err < 0)
return cval->mixer->ignore_ctl_error ? 0 : err;
val = ucontrol->value.integer.value[cnt];
val = get_abs_value(cval, val);
if (oval != val) {
set_cur_mix_value(cval, c + 1, cnt, val);
changed = 1;
}
cnt++;
}
} else {
/* master channel */
err = get_cur_mix_value(cval, 0, 0, &oval);
if (err < 0)
return cval->mixer->ignore_ctl_error ? 0 : err;
val = ucontrol->value.integer.value[0];
val = get_abs_value(cval, val);
if (val != oval) {
set_cur_mix_value(cval, 0, 0, val);
changed = 1;
}
}
return changed;
}
static struct snd_kcontrol_new usb_feature_unit_ctl = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "", /* will be filled later manually */
.info = mixer_ctl_feature_info,
.get = mixer_ctl_feature_get,
.put = mixer_ctl_feature_put,
};
/* the read-only variant */
static struct snd_kcontrol_new usb_feature_unit_ctl_ro = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "", /* will be filled later manually */
.info = mixer_ctl_feature_info,
.get = mixer_ctl_feature_get,
.put = NULL,
};
/* This symbol is exported in order to allow the mixer quirks to
* hook up to the standard feature unit control mechanism */
struct snd_kcontrol_new *snd_usb_feature_unit_ctl = &usb_feature_unit_ctl;
/*
* build a feature control
*/
static size_t append_ctl_name(struct snd_kcontrol *kctl, const char *str)
{
return strlcat(kctl->id.name, str, sizeof(kctl->id.name));
}
static void build_feature_ctl(struct mixer_build *state, void *raw_desc,
unsigned int ctl_mask, int control,
struct usb_audio_term *iterm, int unitid,
int readonly_mask)
{
struct uac_feature_unit_descriptor *desc = raw_desc;
unsigned int len = 0;
int mapped_name = 0;
int nameid = uac_feature_unit_iFeature(desc);
struct snd_kcontrol *kctl;
struct usb_mixer_elem_info *cval;
const struct usbmix_name_map *map;
unsigned int range;
control++; /* change from zero-based to 1-based value */
if (control == UAC_FU_GRAPHIC_EQUALIZER) {
/* FIXME: not supported yet */
return;
}
map = find_map(state, unitid, control);
if (check_ignored_ctl(map))
return;
cval = kzalloc(sizeof(*cval), GFP_KERNEL);
if (! cval) {
snd_printk(KERN_ERR "cannot malloc kcontrol\n");
return;
}
cval->mixer = state->mixer;
cval->id = unitid;
cval->control = control;
cval->cmask = ctl_mask;
cval->val_type = audio_feature_info[control-1].type;
if (ctl_mask == 0) {
cval->channels = 1; /* master channel */
cval->master_readonly = readonly_mask;
} else {
int i, c = 0;
for (i = 0; i < 16; i++)
if (ctl_mask & (1 << i))
c++;
cval->channels = c;
cval->ch_readonly = readonly_mask;
}
/* if all channels in the mask are marked read-only, make the control
* read-only. set_cur_mix_value() will check the mask again and won't
* issue write commands to read-only channels. */
if (cval->channels == readonly_mask)
kctl = snd_ctl_new1(&usb_feature_unit_ctl_ro, cval);
else
kctl = snd_ctl_new1(&usb_feature_unit_ctl, cval);
if (! kctl) {
snd_printk(KERN_ERR "cannot malloc kcontrol\n");
kfree(cval);
return;
}
kctl->private_free = usb_mixer_elem_free;
len = check_mapped_name(map, kctl->id.name, sizeof(kctl->id.name));
mapped_name = len != 0;
if (! len && nameid)
len = snd_usb_copy_string_desc(state, nameid,
kctl->id.name, sizeof(kctl->id.name));
/* get min/max values */
get_min_max_with_quirks(cval, 0, kctl);
switch (control) {
case UAC_FU_MUTE:
case UAC_FU_VOLUME:
/* determine the control name. the rule is:
* - if a name id is given in descriptor, use it.
* - if the connected input can be determined, then use the name
* of terminal type.
* - if the connected output can be determined, use it.
* - otherwise, anonymous name.
*/
if (! len) {
len = get_term_name(state, iterm, kctl->id.name, sizeof(kctl->id.name), 1);
if (! len)
len = get_term_name(state, &state->oterm, kctl->id.name, sizeof(kctl->id.name), 1);
if (! len)
len = snprintf(kctl->id.name, sizeof(kctl->id.name),
"Feature %d", unitid);
}
/* determine the stream direction:
* if the connected output is USB stream, then it's likely a
* capture stream. otherwise it should be playback (hopefully :)
*/
if (! mapped_name && ! (state->oterm.type >> 16)) {
if ((state->oterm.type & 0xff00) == 0x0100) {
len = append_ctl_name(kctl, " Capture");
} else {
len = append_ctl_name(kctl, " Playback");
}
}
append_ctl_name(kctl, control == UAC_FU_MUTE ?
" Switch" : " Volume");
if (control == UAC_FU_VOLUME) {
check_mapped_dB(map, cval);
if (cval->dBmin < cval->dBmax || !cval->initialized) {
kctl->tlv.c = mixer_vol_tlv;
kctl->vd[0].access |=
SNDRV_CTL_ELEM_ACCESS_TLV_READ |
SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK;
}
}
break;
default:
if (! len)
strlcpy(kctl->id.name, audio_feature_info[control-1].name,
sizeof(kctl->id.name));
break;
}
range = (cval->max - cval->min) / cval->res;
/* Are there devices with volume range more than 255? I use a bit more
* to be sure. 384 is a resolution magic number found on Logitech
* devices. It will definitively catch all buggy Logitech devices.
*/
if (range > 384) {
snd_printk(KERN_WARNING "usb_audio: Warning! Unlikely big "
"volume range (=%u), cval->res is probably wrong.",
range);
snd_printk(KERN_WARNING "usb_audio: [%d] FU [%s] ch = %d, "
"val = %d/%d/%d", cval->id,
kctl->id.name, cval->channels,
cval->min, cval->max, cval->res);
}
snd_printdd(KERN_INFO "[%d] FU [%s] ch = %d, val = %d/%d/%d\n",
cval->id, kctl->id.name, cval->channels, cval->min, cval->max, cval->res);
snd_usb_mixer_add_control(state->mixer, kctl);
}
/*
* parse a feature unit
*
* most of controls are defined here.
*/
static int parse_audio_feature_unit(struct mixer_build *state, int unitid, void *_ftr)
{
int channels, i, j;
struct usb_audio_term iterm;
unsigned int master_bits, first_ch_bits;
int err, csize;
struct uac_feature_unit_descriptor *hdr = _ftr;
__u8 *bmaControls;
if (state->mixer->protocol == UAC_VERSION_1) {
csize = hdr->bControlSize;
if (!csize) {
snd_printdd(KERN_ERR "usbaudio: unit %u: "
"invalid bControlSize == 0\n", unitid);
return -EINVAL;
}
channels = (hdr->bLength - 7) / csize - 1;
bmaControls = hdr->bmaControls;
if (hdr->bLength < 7 + csize) {
snd_printk(KERN_ERR "usbaudio: unit %u: "
"invalid UAC_FEATURE_UNIT descriptor\n",
unitid);
return -EINVAL;
}
} else {
struct uac2_feature_unit_descriptor *ftr = _ftr;
csize = 4;
channels = (hdr->bLength - 6) / 4 - 1;
bmaControls = ftr->bmaControls;
if (hdr->bLength < 6 + csize) {
snd_printk(KERN_ERR "usbaudio: unit %u: "
"invalid UAC_FEATURE_UNIT descriptor\n",
unitid);
return -EINVAL;
}
}
/* parse the source unit */
if ((err = parse_audio_unit(state, hdr->bSourceID)) < 0)
return err;
/* determine the input source type and name */
err = check_input_term(state, hdr->bSourceID, &iterm);
if (err < 0)
return err;
master_bits = snd_usb_combine_bytes(bmaControls, csize);
/* master configuration quirks */
switch (state->chip->usb_id) {
case USB_ID(0x08bb, 0x2702):
snd_printk(KERN_INFO
"usbmixer: master volume quirk for PCM2702 chip\n");
/* disable non-functional volume control */
master_bits &= ~UAC_CONTROL_BIT(UAC_FU_VOLUME);
break;
case USB_ID(0x1130, 0xf211):
snd_printk(KERN_INFO
"usbmixer: volume control quirk for Tenx TP6911 Audio Headset\n");
/* disable non-functional volume control */
channels = 0;
break;
}
if (channels > 0)
first_ch_bits = snd_usb_combine_bytes(bmaControls + csize, csize);
else
first_ch_bits = 0;
if (state->mixer->protocol == UAC_VERSION_1) {
/* check all control types */
for (i = 0; i < 10; i++) {
unsigned int ch_bits = 0;
for (j = 0; j < channels; j++) {
unsigned int mask = snd_usb_combine_bytes(bmaControls + csize * (j+1), csize);
if (mask & (1 << i))
ch_bits |= (1 << j);
}
/* audio class v1 controls are never read-only */
if (ch_bits & 1) /* the first channel must be set (for ease of programming) */
build_feature_ctl(state, _ftr, ch_bits, i, &iterm, unitid, 0);
if (master_bits & (1 << i))
build_feature_ctl(state, _ftr, 0, i, &iterm, unitid, 0);
}
} else { /* UAC_VERSION_2 */
for (i = 0; i < 30/2; i++) {
unsigned int ch_bits = 0;
unsigned int ch_read_only = 0;
for (j = 0; j < channels; j++) {
unsigned int mask = snd_usb_combine_bytes(bmaControls + csize * (j+1), csize);
if (uac2_control_is_readable(mask, i)) {
ch_bits |= (1 << j);
if (!uac2_control_is_writeable(mask, i))
ch_read_only |= (1 << j);
}
}
/* NOTE: build_feature_ctl() will mark the control read-only if all channels
* are marked read-only in the descriptors. Otherwise, the control will be
* reported as writeable, but the driver will not actually issue a write
* command for read-only channels */
if (ch_bits & 1) /* the first channel must be set (for ease of programming) */
build_feature_ctl(state, _ftr, ch_bits, i, &iterm, unitid, ch_read_only);
if (uac2_control_is_readable(master_bits, i))
build_feature_ctl(state, _ftr, 0, i, &iterm, unitid,
!uac2_control_is_writeable(master_bits, i));
}
}
return 0;
}
/*
* Mixer Unit
*/
/*
* build a mixer unit control
*
* the callbacks are identical with feature unit.
* input channel number (zero based) is given in control field instead.
*/
static void build_mixer_unit_ctl(struct mixer_build *state,
struct uac_mixer_unit_descriptor *desc,
int in_pin, int in_ch, int unitid,
struct usb_audio_term *iterm)
{
struct usb_mixer_elem_info *cval;
unsigned int num_outs = uac_mixer_unit_bNrChannels(desc);
unsigned int i, len;
struct snd_kcontrol *kctl;
const struct usbmix_name_map *map;
map = find_map(state, unitid, 0);
if (check_ignored_ctl(map))
return;
cval = kzalloc(sizeof(*cval), GFP_KERNEL);
if (! cval)
return;
cval->mixer = state->mixer;
cval->id = unitid;
cval->control = in_ch + 1; /* based on 1 */
cval->val_type = USB_MIXER_S16;
for (i = 0; i < num_outs; i++) {
if (check_matrix_bitmap(uac_mixer_unit_bmControls(desc, state->mixer->protocol), in_ch, i, num_outs)) {
cval->cmask |= (1 << i);
cval->channels++;
}
}
/* get min/max values */
get_min_max(cval, 0);
kctl = snd_ctl_new1(&usb_feature_unit_ctl, cval);
if (! kctl) {
snd_printk(KERN_ERR "cannot malloc kcontrol\n");
kfree(cval);
return;
}
kctl->private_free = usb_mixer_elem_free;
len = check_mapped_name(map, kctl->id.name, sizeof(kctl->id.name));
if (! len)
len = get_term_name(state, iterm, kctl->id.name, sizeof(kctl->id.name), 0);
if (! len)
len = sprintf(kctl->id.name, "Mixer Source %d", in_ch + 1);
append_ctl_name(kctl, " Volume");
snd_printdd(KERN_INFO "[%d] MU [%s] ch = %d, val = %d/%d\n",
cval->id, kctl->id.name, cval->channels, cval->min, cval->max);
snd_usb_mixer_add_control(state->mixer, kctl);
}
/*
* parse a mixer unit
*/
static int parse_audio_mixer_unit(struct mixer_build *state, int unitid, void *raw_desc)
{
struct uac_mixer_unit_descriptor *desc = raw_desc;
struct usb_audio_term iterm;
int input_pins, num_ins, num_outs;
int pin, ich, err;
if (desc->bLength < 11 || ! (input_pins = desc->bNrInPins) || ! (num_outs = uac_mixer_unit_bNrChannels(desc))) {
snd_printk(KERN_ERR "invalid MIXER UNIT descriptor %d\n", unitid);
return -EINVAL;
}
/* no bmControls field (e.g. Maya44) -> ignore */
if (desc->bLength <= 10 + input_pins) {
snd_printdd(KERN_INFO "MU %d has no bmControls field\n", unitid);
return 0;
}
num_ins = 0;
ich = 0;
for (pin = 0; pin < input_pins; pin++) {
err = parse_audio_unit(state, desc->baSourceID[pin]);
if (err < 0)
return err;
err = check_input_term(state, desc->baSourceID[pin], &iterm);
if (err < 0)
return err;
num_ins += iterm.channels;
for (; ich < num_ins; ++ich) {
int och, ich_has_controls = 0;
for (och = 0; och < num_outs; ++och) {
if (check_matrix_bitmap(uac_mixer_unit_bmControls(desc, state->mixer->protocol),
ich, och, num_outs)) {
ich_has_controls = 1;
break;
}
}
if (ich_has_controls)
build_mixer_unit_ctl(state, desc, pin, ich,
unitid, &iterm);
}
}
return 0;
}
/*
* Processing Unit / Extension Unit
*/
/* get callback for processing/extension unit */
static int mixer_ctl_procunit_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct usb_mixer_elem_info *cval = kcontrol->private_data;
int err, val;
err = get_cur_ctl_value(cval, cval->control << 8, &val);
if (err < 0 && cval->mixer->ignore_ctl_error) {
ucontrol->value.integer.value[0] = cval->min;
return 0;
}
if (err < 0)
return err;
val = get_relative_value(cval, val);
ucontrol->value.integer.value[0] = val;
return 0;
}
/* put callback for processing/extension unit */
static int mixer_ctl_procunit_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct usb_mixer_elem_info *cval = kcontrol->private_data;
int val, oval, err;
err = get_cur_ctl_value(cval, cval->control << 8, &oval);
if (err < 0) {
if (cval->mixer->ignore_ctl_error)
return 0;
return err;
}
val = ucontrol->value.integer.value[0];
val = get_abs_value(cval, val);
if (val != oval) {
set_cur_ctl_value(cval, cval->control << 8, val);
return 1;
}
return 0;
}
/* alsa control interface for processing/extension unit */
static struct snd_kcontrol_new mixer_procunit_ctl = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "", /* will be filled later */
.info = mixer_ctl_feature_info,
.get = mixer_ctl_procunit_get,
.put = mixer_ctl_procunit_put,
};
/*
* predefined data for processing units
*/
struct procunit_value_info {
int control;
char *suffix;
int val_type;
int min_value;
};
struct procunit_info {
int type;
char *name;
struct procunit_value_info *values;
};
static struct procunit_value_info updown_proc_info[] = {
{ UAC_UD_ENABLE, "Switch", USB_MIXER_BOOLEAN },
{ UAC_UD_MODE_SELECT, "Mode Select", USB_MIXER_U8, 1 },
{ 0 }
};
static struct procunit_value_info prologic_proc_info[] = {
{ UAC_DP_ENABLE, "Switch", USB_MIXER_BOOLEAN },
{ UAC_DP_MODE_SELECT, "Mode Select", USB_MIXER_U8, 1 },
{ 0 }
};
static struct procunit_value_info threed_enh_proc_info[] = {
{ UAC_3D_ENABLE, "Switch", USB_MIXER_BOOLEAN },
{ UAC_3D_SPACE, "Spaciousness", USB_MIXER_U8 },
{ 0 }
};
static struct procunit_value_info reverb_proc_info[] = {
{ UAC_REVERB_ENABLE, "Switch", USB_MIXER_BOOLEAN },
{ UAC_REVERB_LEVEL, "Level", USB_MIXER_U8 },
{ UAC_REVERB_TIME, "Time", USB_MIXER_U16 },
{ UAC_REVERB_FEEDBACK, "Feedback", USB_MIXER_U8 },
{ 0 }
};
static struct procunit_value_info chorus_proc_info[] = {
{ UAC_CHORUS_ENABLE, "Switch", USB_MIXER_BOOLEAN },
{ UAC_CHORUS_LEVEL, "Level", USB_MIXER_U8 },
{ UAC_CHORUS_RATE, "Rate", USB_MIXER_U16 },
{ UAC_CHORUS_DEPTH, "Depth", USB_MIXER_U16 },
{ 0 }
};
static struct procunit_value_info dcr_proc_info[] = {
{ UAC_DCR_ENABLE, "Switch", USB_MIXER_BOOLEAN },
{ UAC_DCR_RATE, "Ratio", USB_MIXER_U16 },
{ UAC_DCR_MAXAMPL, "Max Amp", USB_MIXER_S16 },
{ UAC_DCR_THRESHOLD, "Threshold", USB_MIXER_S16 },
{ UAC_DCR_ATTACK_TIME, "Attack Time", USB_MIXER_U16 },
{ UAC_DCR_RELEASE_TIME, "Release Time", USB_MIXER_U16 },
{ 0 }
};
static struct procunit_info procunits[] = {
{ UAC_PROCESS_UP_DOWNMIX, "Up Down", updown_proc_info },
{ UAC_PROCESS_DOLBY_PROLOGIC, "Dolby Prologic", prologic_proc_info },
{ UAC_PROCESS_STEREO_EXTENDER, "3D Stereo Extender", threed_enh_proc_info },
{ UAC_PROCESS_REVERB, "Reverb", reverb_proc_info },
{ UAC_PROCESS_CHORUS, "Chorus", chorus_proc_info },
{ UAC_PROCESS_DYN_RANGE_COMP, "DCR", dcr_proc_info },
{ 0 },
};
/*
* predefined data for extension units
*/
static struct procunit_value_info clock_rate_xu_info[] = {
{ USB_XU_CLOCK_RATE_SELECTOR, "Selector", USB_MIXER_U8, 0 },
{ 0 }
};
static struct procunit_value_info clock_source_xu_info[] = {
{ USB_XU_CLOCK_SOURCE_SELECTOR, "External", USB_MIXER_BOOLEAN },
{ 0 }
};
static struct procunit_value_info spdif_format_xu_info[] = {
{ USB_XU_DIGITAL_FORMAT_SELECTOR, "SPDIF/AC3", USB_MIXER_BOOLEAN },
{ 0 }
};
static struct procunit_value_info soft_limit_xu_info[] = {
{ USB_XU_SOFT_LIMIT_SELECTOR, " ", USB_MIXER_BOOLEAN },
{ 0 }
};
static struct procunit_info extunits[] = {
{ USB_XU_CLOCK_RATE, "Clock rate", clock_rate_xu_info },
{ USB_XU_CLOCK_SOURCE, "DigitalIn CLK source", clock_source_xu_info },
{ USB_XU_DIGITAL_IO_STATUS, "DigitalOut format:", spdif_format_xu_info },
{ USB_XU_DEVICE_OPTIONS, "AnalogueIn Soft Limit", soft_limit_xu_info },
{ 0 }
};
/*
* build a processing/extension unit
*/
static int build_audio_procunit(struct mixer_build *state, int unitid, void *raw_desc, struct procunit_info *list, char *name)
{
struct uac_processing_unit_descriptor *desc = raw_desc;
int num_ins = desc->bNrInPins;
struct usb_mixer_elem_info *cval;
struct snd_kcontrol *kctl;
int i, err, nameid, type, len;
struct procunit_info *info;
struct procunit_value_info *valinfo;
const struct usbmix_name_map *map;
static struct procunit_value_info default_value_info[] = {
{ 0x01, "Switch", USB_MIXER_BOOLEAN },
{ 0 }
};
static struct procunit_info default_info = {
0, NULL, default_value_info
};
if (desc->bLength < 13 || desc->bLength < 13 + num_ins ||
desc->bLength < num_ins + uac_processing_unit_bControlSize(desc, state->mixer->protocol)) {
snd_printk(KERN_ERR "invalid %s descriptor (id %d)\n", name, unitid);
return -EINVAL;
}
for (i = 0; i < num_ins; i++) {
if ((err = parse_audio_unit(state, desc->baSourceID[i])) < 0)
return err;
}
type = le16_to_cpu(desc->wProcessType);
for (info = list; info && info->type; info++)
if (info->type == type)
break;
if (! info || ! info->type)
info = &default_info;
for (valinfo = info->values; valinfo->control; valinfo++) {
__u8 *controls = uac_processing_unit_bmControls(desc, state->mixer->protocol);
if (! (controls[valinfo->control / 8] & (1 << ((valinfo->control % 8) - 1))))
continue;
map = find_map(state, unitid, valinfo->control);
if (check_ignored_ctl(map))
continue;
cval = kzalloc(sizeof(*cval), GFP_KERNEL);
if (! cval) {
snd_printk(KERN_ERR "cannot malloc kcontrol\n");
return -ENOMEM;
}
cval->mixer = state->mixer;
cval->id = unitid;
cval->control = valinfo->control;
cval->val_type = valinfo->val_type;
cval->channels = 1;
/* get min/max values */
if (type == UAC_PROCESS_UP_DOWNMIX && cval->control == UAC_UD_MODE_SELECT) {
__u8 *control_spec = uac_processing_unit_specific(desc, state->mixer->protocol);
/* FIXME: hard-coded */
cval->min = 1;
cval->max = control_spec[0];
cval->res = 1;
cval->initialized = 1;
} else {
if (type == USB_XU_CLOCK_RATE) {
/* E-Mu USB 0404/0202/TrackerPre/0204
* samplerate control quirk
*/
cval->min = 0;
cval->max = 5;
cval->res = 1;
cval->initialized = 1;
} else
get_min_max(cval, valinfo->min_value);
}
kctl = snd_ctl_new1(&mixer_procunit_ctl, cval);
if (! kctl) {
snd_printk(KERN_ERR "cannot malloc kcontrol\n");
kfree(cval);
return -ENOMEM;
}
kctl->private_free = usb_mixer_elem_free;
if (check_mapped_name(map, kctl->id.name,
sizeof(kctl->id.name)))
/* nothing */ ;
else if (info->name)
strlcpy(kctl->id.name, info->name, sizeof(kctl->id.name));
else {
nameid = uac_processing_unit_iProcessing(desc, state->mixer->protocol);
len = 0;
if (nameid)
len = snd_usb_copy_string_desc(state, nameid, kctl->id.name, sizeof(kctl->id.name));
if (! len)
strlcpy(kctl->id.name, name, sizeof(kctl->id.name));
}
append_ctl_name(kctl, " ");
append_ctl_name(kctl, valinfo->suffix);
snd_printdd(KERN_INFO "[%d] PU [%s] ch = %d, val = %d/%d\n",
cval->id, kctl->id.name, cval->channels, cval->min, cval->max);
if ((err = snd_usb_mixer_add_control(state->mixer, kctl)) < 0)
return err;
}
return 0;
}
static int parse_audio_processing_unit(struct mixer_build *state, int unitid, void *raw_desc)
{
return build_audio_procunit(state, unitid, raw_desc, procunits, "Processing Unit");
}
static int parse_audio_extension_unit(struct mixer_build *state, int unitid, void *raw_desc)
{
/* Note that we parse extension units with processing unit descriptors.
* That's ok as the layout is the same */
return build_audio_procunit(state, unitid, raw_desc, extunits, "Extension Unit");
}
/*
* Selector Unit
*/
/* info callback for selector unit
* use an enumerator type for routing
*/
static int mixer_ctl_selector_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
struct usb_mixer_elem_info *cval = kcontrol->private_data;
const char **itemlist = (const char **)kcontrol->private_value;
if (snd_BUG_ON(!itemlist))
return -EINVAL;
return snd_ctl_enum_info(uinfo, 1, cval->max, itemlist);
}
/* get callback for selector unit */
static int mixer_ctl_selector_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct usb_mixer_elem_info *cval = kcontrol->private_data;
int val, err;
err = get_cur_ctl_value(cval, cval->control << 8, &val);
if (err < 0) {
if (cval->mixer->ignore_ctl_error) {
ucontrol->value.enumerated.item[0] = 0;
return 0;
}
return err;
}
val = get_relative_value(cval, val);
ucontrol->value.enumerated.item[0] = val;
return 0;
}
/* put callback for selector unit */
static int mixer_ctl_selector_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct usb_mixer_elem_info *cval = kcontrol->private_data;
int val, oval, err;
err = get_cur_ctl_value(cval, cval->control << 8, &oval);
if (err < 0) {
if (cval->mixer->ignore_ctl_error)
return 0;
return err;
}
val = ucontrol->value.enumerated.item[0];
val = get_abs_value(cval, val);
if (val != oval) {
set_cur_ctl_value(cval, cval->control << 8, val);
return 1;
}
return 0;
}
/* alsa control interface for selector unit */
static struct snd_kcontrol_new mixer_selectunit_ctl = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "", /* will be filled later */
.info = mixer_ctl_selector_info,
.get = mixer_ctl_selector_get,
.put = mixer_ctl_selector_put,
};
/* private free callback.
* free both private_data and private_value
*/
static void usb_mixer_selector_elem_free(struct snd_kcontrol *kctl)
{
int i, num_ins = 0;
if (kctl->private_data) {
struct usb_mixer_elem_info *cval = kctl->private_data;
num_ins = cval->max;
kfree(cval);
kctl->private_data = NULL;
}
if (kctl->private_value) {
char **itemlist = (char **)kctl->private_value;
for (i = 0; i < num_ins; i++)
kfree(itemlist[i]);
kfree(itemlist);
kctl->private_value = 0;
}
}
/*
* parse a selector unit
*/
static int parse_audio_selector_unit(struct mixer_build *state, int unitid, void *raw_desc)
{
struct uac_selector_unit_descriptor *desc = raw_desc;
unsigned int i, nameid, len;
int err;
struct usb_mixer_elem_info *cval;
struct snd_kcontrol *kctl;
const struct usbmix_name_map *map;
char **namelist;
if (!desc->bNrInPins || desc->bLength < 5 + desc->bNrInPins) {
snd_printk(KERN_ERR "invalid SELECTOR UNIT descriptor %d\n", unitid);
return -EINVAL;
}
for (i = 0; i < desc->bNrInPins; i++) {
if ((err = parse_audio_unit(state, desc->baSourceID[i])) < 0)
return err;
}
if (desc->bNrInPins == 1) /* only one ? nonsense! */
return 0;
map = find_map(state, unitid, 0);
if (check_ignored_ctl(map))
return 0;
cval = kzalloc(sizeof(*cval), GFP_KERNEL);
if (! cval) {
snd_printk(KERN_ERR "cannot malloc kcontrol\n");
return -ENOMEM;
}
cval->mixer = state->mixer;
cval->id = unitid;
cval->val_type = USB_MIXER_U8;
cval->channels = 1;
cval->min = 1;
cval->max = desc->bNrInPins;
cval->res = 1;
cval->initialized = 1;
if (desc->bDescriptorSubtype == UAC2_CLOCK_SELECTOR)
cval->control = UAC2_CX_CLOCK_SELECTOR;
else
cval->control = 0;
namelist = kmalloc(sizeof(char *) * desc->bNrInPins, GFP_KERNEL);
if (! namelist) {
snd_printk(KERN_ERR "cannot malloc\n");
kfree(cval);
return -ENOMEM;
}
#define MAX_ITEM_NAME_LEN 64
for (i = 0; i < desc->bNrInPins; i++) {
struct usb_audio_term iterm;
len = 0;
namelist[i] = kmalloc(MAX_ITEM_NAME_LEN, GFP_KERNEL);
if (! namelist[i]) {
snd_printk(KERN_ERR "cannot malloc\n");
while (i--)
kfree(namelist[i]);
kfree(namelist);
kfree(cval);
return -ENOMEM;
}
len = check_mapped_selector_name(state, unitid, i, namelist[i],
MAX_ITEM_NAME_LEN);
if (! len && check_input_term(state, desc->baSourceID[i], &iterm) >= 0)
len = get_term_name(state, &iterm, namelist[i], MAX_ITEM_NAME_LEN, 0);
if (! len)
sprintf(namelist[i], "Input %d", i);
}
kctl = snd_ctl_new1(&mixer_selectunit_ctl, cval);
if (! kctl) {
snd_printk(KERN_ERR "cannot malloc kcontrol\n");
kfree(namelist);
kfree(cval);
return -ENOMEM;
}
kctl->private_value = (unsigned long)namelist;
kctl->private_free = usb_mixer_selector_elem_free;
nameid = uac_selector_unit_iSelector(desc);
len = check_mapped_name(map, kctl->id.name, sizeof(kctl->id.name));
if (len)
;
else if (nameid)
snd_usb_copy_string_desc(state, nameid, kctl->id.name, sizeof(kctl->id.name));
else {
len = get_term_name(state, &state->oterm,
kctl->id.name, sizeof(kctl->id.name), 0);
if (! len)
strlcpy(kctl->id.name, "USB", sizeof(kctl->id.name));
if (desc->bDescriptorSubtype == UAC2_CLOCK_SELECTOR)
append_ctl_name(kctl, " Clock Source");
else if ((state->oterm.type & 0xff00) == 0x0100)
append_ctl_name(kctl, " Capture Source");
else
append_ctl_name(kctl, " Playback Source");
}
snd_printdd(KERN_INFO "[%d] SU [%s] items = %d\n",
cval->id, kctl->id.name, desc->bNrInPins);
if ((err = snd_usb_mixer_add_control(state->mixer, kctl)) < 0)
return err;
return 0;
}
/*
* parse an audio unit recursively
*/
static int parse_audio_unit(struct mixer_build *state, int unitid)
{
unsigned char *p1;
if (test_and_set_bit(unitid, state->unitbitmap))
return 0; /* the unit already visited */
p1 = find_audio_control_unit(state, unitid);
if (!p1) {
snd_printk(KERN_ERR "usbaudio: unit %d not found!\n", unitid);
return -EINVAL;
}
switch (p1[2]) {
case UAC_INPUT_TERMINAL:
case UAC2_CLOCK_SOURCE:
return 0; /* NOP */
case UAC_MIXER_UNIT:
return parse_audio_mixer_unit(state, unitid, p1);
case UAC_SELECTOR_UNIT:
case UAC2_CLOCK_SELECTOR:
return parse_audio_selector_unit(state, unitid, p1);
case UAC_FEATURE_UNIT:
return parse_audio_feature_unit(state, unitid, p1);
case UAC1_PROCESSING_UNIT:
/* UAC2_EFFECT_UNIT has the same value */
if (state->mixer->protocol == UAC_VERSION_1)
return parse_audio_processing_unit(state, unitid, p1);
else
return 0; /* FIXME - effect units not implemented yet */
case UAC1_EXTENSION_UNIT:
/* UAC2_PROCESSING_UNIT_V2 has the same value */
if (state->mixer->protocol == UAC_VERSION_1)
return parse_audio_extension_unit(state, unitid, p1);
else /* UAC_VERSION_2 */
return parse_audio_processing_unit(state, unitid, p1);
default:
snd_printk(KERN_ERR "usbaudio: unit %u: unexpected type 0x%02x\n", unitid, p1[2]);
return -EINVAL;
}
}
static void snd_usb_mixer_free(struct usb_mixer_interface *mixer)
{
kfree(mixer->id_elems);
if (mixer->urb) {
kfree(mixer->urb->transfer_buffer);
usb_free_urb(mixer->urb);
}
usb_free_urb(mixer->rc_urb);
kfree(mixer->rc_setup_packet);
kfree(mixer);
}
static int snd_usb_mixer_dev_free(struct snd_device *device)
{
struct usb_mixer_interface *mixer = device->device_data;
snd_usb_mixer_free(mixer);
return 0;
}
/*
* create mixer controls
*
* walk through all UAC_OUTPUT_TERMINAL descriptors to search for mixers
*/
static int snd_usb_mixer_controls(struct usb_mixer_interface *mixer)
{
struct mixer_build state;
int err;
const struct usbmix_ctl_map *map;
void *p;
memset(&state, 0, sizeof(state));
state.chip = mixer->chip;
state.mixer = mixer;
state.buffer = mixer->hostif->extra;
state.buflen = mixer->hostif->extralen;
/* check the mapping table */
for (map = usbmix_ctl_maps; map->id; map++) {
if (map->id == state.chip->usb_id) {
state.map = map->map;
state.selector_map = map->selector_map;
mixer->ignore_ctl_error = map->ignore_ctl_error;
break;
}
}
p = NULL;
while ((p = snd_usb_find_csint_desc(mixer->hostif->extra, mixer->hostif->extralen,
p, UAC_OUTPUT_TERMINAL)) != NULL) {
if (mixer->protocol == UAC_VERSION_1) {
struct uac1_output_terminal_descriptor *desc = p;
if (desc->bLength < sizeof(*desc))
continue; /* invalid descriptor? */
set_bit(desc->bTerminalID, state.unitbitmap); /* mark terminal ID as visited */
state.oterm.id = desc->bTerminalID;
state.oterm.type = le16_to_cpu(desc->wTerminalType);
state.oterm.name = desc->iTerminal;
err = parse_audio_unit(&state, desc->bSourceID);
if (err < 0 && err != -EINVAL)
return err;
} else { /* UAC_VERSION_2 */
struct uac2_output_terminal_descriptor *desc = p;
if (desc->bLength < sizeof(*desc))
continue; /* invalid descriptor? */
set_bit(desc->bTerminalID, state.unitbitmap); /* mark terminal ID as visited */
state.oterm.id = desc->bTerminalID;
state.oterm.type = le16_to_cpu(desc->wTerminalType);
state.oterm.name = desc->iTerminal;
err = parse_audio_unit(&state, desc->bSourceID);
if (err < 0 && err != -EINVAL)
return err;
/* for UAC2, use the same approach to also add the clock selectors */
err = parse_audio_unit(&state, desc->bCSourceID);
if (err < 0 && err != -EINVAL)
return err;
}
}
return 0;
}
void snd_usb_mixer_notify_id(struct usb_mixer_interface *mixer, int unitid)
{
struct usb_mixer_elem_info *info;
for (info = mixer->id_elems[unitid]; info; info = info->next_id_elem)
snd_ctl_notify(mixer->chip->card, SNDRV_CTL_EVENT_MASK_VALUE,
info->elem_id);
}
static void snd_usb_mixer_dump_cval(struct snd_info_buffer *buffer,
int unitid,
struct usb_mixer_elem_info *cval)
{
static char *val_types[] = {"BOOLEAN", "INV_BOOLEAN",
"S8", "U8", "S16", "U16"};
snd_iprintf(buffer, " Unit: %i\n", unitid);
if (cval->elem_id)
snd_iprintf(buffer, " Control: name=\"%s\", index=%i\n",
cval->elem_id->name, cval->elem_id->index);
snd_iprintf(buffer, " Info: id=%i, control=%i, cmask=0x%x, "
"channels=%i, type=\"%s\"\n", cval->id,
cval->control, cval->cmask, cval->channels,
val_types[cval->val_type]);
snd_iprintf(buffer, " Volume: min=%i, max=%i, dBmin=%i, dBmax=%i\n",
cval->min, cval->max, cval->dBmin, cval->dBmax);
}
static void snd_usb_mixer_proc_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_usb_audio *chip = entry->private_data;
struct usb_mixer_interface *mixer;
struct usb_mixer_elem_info *cval;
int unitid;
list_for_each_entry(mixer, &chip->mixer_list, list) {
snd_iprintf(buffer,
"USB Mixer: usb_id=0x%08x, ctrlif=%i, ctlerr=%i\n",
chip->usb_id, snd_usb_ctrl_intf(chip),
mixer->ignore_ctl_error);
snd_iprintf(buffer, "Card: %s\n", chip->card->longname);
for (unitid = 0; unitid < MAX_ID_ELEMS; unitid++) {
for (cval = mixer->id_elems[unitid]; cval;
cval = cval->next_id_elem)
snd_usb_mixer_dump_cval(buffer, unitid, cval);
}
}
}
static void snd_usb_mixer_interrupt_v2(struct usb_mixer_interface *mixer,
int attribute, int value, int index)
{
struct usb_mixer_elem_info *info;
__u8 unitid = (index >> 8) & 0xff;
__u8 control = (value >> 8) & 0xff;
__u8 channel = value & 0xff;
if (channel >= MAX_CHANNELS) {
snd_printk(KERN_DEBUG "%s(): bogus channel number %d\n",
__func__, channel);
return;
}
for (info = mixer->id_elems[unitid]; info; info = info->next_id_elem) {
if (info->control != control)
continue;
switch (attribute) {
case UAC2_CS_CUR:
/* invalidate cache, so the value is read from the device */
if (channel)
info->cached &= ~(1 << channel);
else /* master channel */
info->cached = 0;
snd_ctl_notify(mixer->chip->card, SNDRV_CTL_EVENT_MASK_VALUE,
info->elem_id);
break;
case UAC2_CS_RANGE:
/* TODO */
break;
case UAC2_CS_MEM:
/* TODO */
break;
default:
snd_printk(KERN_DEBUG "unknown attribute %d in interrupt\n",
attribute);
break;
} /* switch */
}
}
static void snd_usb_mixer_interrupt(struct urb *urb)
{
struct usb_mixer_interface *mixer = urb->context;
int len = urb->actual_length;
int ustatus = urb->status;
if (ustatus != 0)
goto requeue;
if (mixer->protocol == UAC_VERSION_1) {
struct uac1_status_word *status;
for (status = urb->transfer_buffer;
len >= sizeof(*status);
len -= sizeof(*status), status++) {
snd_printd(KERN_DEBUG "status interrupt: %02x %02x\n",
status->bStatusType,
status->bOriginator);
/* ignore any notifications not from the control interface */
if ((status->bStatusType & UAC1_STATUS_TYPE_ORIG_MASK) !=
UAC1_STATUS_TYPE_ORIG_AUDIO_CONTROL_IF)
continue;
if (status->bStatusType & UAC1_STATUS_TYPE_MEM_CHANGED)
snd_usb_mixer_rc_memory_change(mixer, status->bOriginator);
else
snd_usb_mixer_notify_id(mixer, status->bOriginator);
}
} else { /* UAC_VERSION_2 */
struct uac2_interrupt_data_msg *msg;
for (msg = urb->transfer_buffer;
len >= sizeof(*msg);
len -= sizeof(*msg), msg++) {
/* drop vendor specific and endpoint requests */
if ((msg->bInfo & UAC2_INTERRUPT_DATA_MSG_VENDOR) ||
(msg->bInfo & UAC2_INTERRUPT_DATA_MSG_EP))
continue;
snd_usb_mixer_interrupt_v2(mixer, msg->bAttribute,
le16_to_cpu(msg->wValue),
le16_to_cpu(msg->wIndex));
}
}
requeue:
if (ustatus != -ENOENT && ustatus != -ECONNRESET && ustatus != -ESHUTDOWN) {
urb->dev = mixer->chip->dev;
usb_submit_urb(urb, GFP_ATOMIC);
}
}
/* stop any bus activity of a mixer */
void snd_usb_mixer_inactivate(struct usb_mixer_interface *mixer)
{
usb_kill_urb(mixer->urb);
usb_kill_urb(mixer->rc_urb);
}
int snd_usb_mixer_activate(struct usb_mixer_interface *mixer)
{
int err;
if (mixer->urb) {
err = usb_submit_urb(mixer->urb, GFP_NOIO);
if (err < 0)
return err;
}
return 0;
}
/* create the handler for the optional status interrupt endpoint */
static int snd_usb_mixer_status_create(struct usb_mixer_interface *mixer)
{
struct usb_endpoint_descriptor *ep;
void *transfer_buffer;
int buffer_length;
unsigned int epnum;
/* we need one interrupt input endpoint */
if (get_iface_desc(mixer->hostif)->bNumEndpoints < 1)
return 0;
ep = get_endpoint(mixer->hostif, 0);
if (!usb_endpoint_dir_in(ep) || !usb_endpoint_xfer_int(ep))
return 0;
epnum = usb_endpoint_num(ep);
buffer_length = le16_to_cpu(ep->wMaxPacketSize);
transfer_buffer = kmalloc(buffer_length, GFP_KERNEL);
if (!transfer_buffer)
return -ENOMEM;
mixer->urb = usb_alloc_urb(0, GFP_KERNEL);
if (!mixer->urb) {
kfree(transfer_buffer);
return -ENOMEM;
}
usb_fill_int_urb(mixer->urb, mixer->chip->dev,
usb_rcvintpipe(mixer->chip->dev, epnum),
transfer_buffer, buffer_length,
snd_usb_mixer_interrupt, mixer, ep->bInterval);
usb_submit_urb(mixer->urb, GFP_KERNEL);
return 0;
}
int snd_usb_create_mixer(struct snd_usb_audio *chip, int ctrlif,
int ignore_error)
{
static struct snd_device_ops dev_ops = {
.dev_free = snd_usb_mixer_dev_free
};
struct usb_mixer_interface *mixer;
struct snd_info_entry *entry;
int err;
strcpy(chip->card->mixername, "USB Mixer");
mixer = kzalloc(sizeof(*mixer), GFP_KERNEL);
if (!mixer)
return -ENOMEM;
mixer->chip = chip;
mixer->ignore_ctl_error = ignore_error;
mixer->id_elems = kcalloc(MAX_ID_ELEMS, sizeof(*mixer->id_elems),
GFP_KERNEL);
if (!mixer->id_elems) {
kfree(mixer);
return -ENOMEM;
}
mixer->hostif = &usb_ifnum_to_if(chip->dev, ctrlif)->altsetting[0];
switch (get_iface_desc(mixer->hostif)->bInterfaceProtocol) {
case UAC_VERSION_1:
default:
mixer->protocol = UAC_VERSION_1;
break;
case UAC_VERSION_2:
mixer->protocol = UAC_VERSION_2;
break;
}
if ((err = snd_usb_mixer_controls(mixer)) < 0 ||
(err = snd_usb_mixer_status_create(mixer)) < 0)
goto _error;
snd_usb_mixer_apply_create_quirk(mixer);
err = snd_device_new(chip->card, SNDRV_DEV_LOWLEVEL, mixer, &dev_ops);
if (err < 0)
goto _error;
if (list_empty(&chip->mixer_list) &&
!snd_card_proc_new(chip->card, "usbmixer", &entry))
snd_info_set_text_ops(entry, chip, snd_usb_mixer_proc_read);
list_add(&mixer->list, &chip->mixer_list);
return 0;
_error:
snd_usb_mixer_free(mixer);
return err;
}
void snd_usb_mixer_disconnect(struct list_head *p)
{
struct usb_mixer_interface *mixer;
mixer = list_entry(p, struct usb_mixer_interface, list);
usb_kill_urb(mixer->urb);
usb_kill_urb(mixer->rc_urb);
}
| gpl-2.0 |
imoseyon/leanKernel-tbolt-gingerbread | drivers/scsi/aic7xxx/aic7xxx_core.c | 867 | 216584 | /*
* Core routines and tables shareable across OS platforms.
*
* Copyright (c) 1994-2002 Justin T. Gibbs.
* Copyright (c) 2000-2002 Adaptec Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* NO WARRANTY
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* $Id: //depot/aic7xxx/aic7xxx/aic7xxx.c#155 $
*/
#ifdef __linux__
#include "aic7xxx_osm.h"
#include "aic7xxx_inline.h"
#include "aicasm/aicasm_insformat.h"
#else
#include <dev/aic7xxx/aic7xxx_osm.h>
#include <dev/aic7xxx/aic7xxx_inline.h>
#include <dev/aic7xxx/aicasm/aicasm_insformat.h>
#endif
/***************************** Lookup Tables **********************************/
static const char *const ahc_chip_names[] = {
"NONE",
"aic7770",
"aic7850",
"aic7855",
"aic7859",
"aic7860",
"aic7870",
"aic7880",
"aic7895",
"aic7895C",
"aic7890/91",
"aic7896/97",
"aic7892",
"aic7899"
};
static const u_int num_chip_names = ARRAY_SIZE(ahc_chip_names);
/*
* Hardware error codes.
*/
struct ahc_hard_error_entry {
uint8_t errno;
const char *errmesg;
};
static const struct ahc_hard_error_entry ahc_hard_errors[] = {
{ ILLHADDR, "Illegal Host Access" },
{ ILLSADDR, "Illegal Sequencer Address referrenced" },
{ ILLOPCODE, "Illegal Opcode in sequencer program" },
{ SQPARERR, "Sequencer Parity Error" },
{ DPARERR, "Data-path Parity Error" },
{ MPARERR, "Scratch or SCB Memory Parity Error" },
{ PCIERRSTAT, "PCI Error detected" },
{ CIOPARERR, "CIOBUS Parity Error" },
};
static const u_int num_errors = ARRAY_SIZE(ahc_hard_errors);
static const struct ahc_phase_table_entry ahc_phase_table[] =
{
{ P_DATAOUT, MSG_NOOP, "in Data-out phase" },
{ P_DATAIN, MSG_INITIATOR_DET_ERR, "in Data-in phase" },
{ P_DATAOUT_DT, MSG_NOOP, "in DT Data-out phase" },
{ P_DATAIN_DT, MSG_INITIATOR_DET_ERR, "in DT Data-in phase" },
{ P_COMMAND, MSG_NOOP, "in Command phase" },
{ P_MESGOUT, MSG_NOOP, "in Message-out phase" },
{ P_STATUS, MSG_INITIATOR_DET_ERR, "in Status phase" },
{ P_MESGIN, MSG_PARITY_ERROR, "in Message-in phase" },
{ P_BUSFREE, MSG_NOOP, "while idle" },
{ 0, MSG_NOOP, "in unknown phase" }
};
/*
* In most cases we only wish to itterate over real phases, so
* exclude the last element from the count.
*/
static const u_int num_phases = ARRAY_SIZE(ahc_phase_table) - 1;
/*
* Valid SCSIRATE values. (p. 3-17)
* Provides a mapping of tranfer periods in ns to the proper value to
* stick in the scsixfer reg.
*/
static const struct ahc_syncrate ahc_syncrates[] =
{
/* ultra2 fast/ultra period rate */
{ 0x42, 0x000, 9, "80.0" },
{ 0x03, 0x000, 10, "40.0" },
{ 0x04, 0x000, 11, "33.0" },
{ 0x05, 0x100, 12, "20.0" },
{ 0x06, 0x110, 15, "16.0" },
{ 0x07, 0x120, 18, "13.4" },
{ 0x08, 0x000, 25, "10.0" },
{ 0x19, 0x010, 31, "8.0" },
{ 0x1a, 0x020, 37, "6.67" },
{ 0x1b, 0x030, 43, "5.7" },
{ 0x1c, 0x040, 50, "5.0" },
{ 0x00, 0x050, 56, "4.4" },
{ 0x00, 0x060, 62, "4.0" },
{ 0x00, 0x070, 68, "3.6" },
{ 0x00, 0x000, 0, NULL }
};
/* Our Sequencer Program */
#include "aic7xxx_seq.h"
/**************************** Function Declarations ***************************/
static void ahc_force_renegotiation(struct ahc_softc *ahc,
struct ahc_devinfo *devinfo);
static struct ahc_tmode_tstate*
ahc_alloc_tstate(struct ahc_softc *ahc,
u_int scsi_id, char channel);
#ifdef AHC_TARGET_MODE
static void ahc_free_tstate(struct ahc_softc *ahc,
u_int scsi_id, char channel, int force);
#endif
static const struct ahc_syncrate*
ahc_devlimited_syncrate(struct ahc_softc *ahc,
struct ahc_initiator_tinfo *,
u_int *period,
u_int *ppr_options,
role_t role);
static void ahc_update_pending_scbs(struct ahc_softc *ahc);
static void ahc_fetch_devinfo(struct ahc_softc *ahc,
struct ahc_devinfo *devinfo);
static void ahc_scb_devinfo(struct ahc_softc *ahc,
struct ahc_devinfo *devinfo,
struct scb *scb);
static void ahc_assert_atn(struct ahc_softc *ahc);
static void ahc_setup_initiator_msgout(struct ahc_softc *ahc,
struct ahc_devinfo *devinfo,
struct scb *scb);
static void ahc_build_transfer_msg(struct ahc_softc *ahc,
struct ahc_devinfo *devinfo);
static void ahc_construct_sdtr(struct ahc_softc *ahc,
struct ahc_devinfo *devinfo,
u_int period, u_int offset);
static void ahc_construct_wdtr(struct ahc_softc *ahc,
struct ahc_devinfo *devinfo,
u_int bus_width);
static void ahc_construct_ppr(struct ahc_softc *ahc,
struct ahc_devinfo *devinfo,
u_int period, u_int offset,
u_int bus_width, u_int ppr_options);
static void ahc_clear_msg_state(struct ahc_softc *ahc);
static void ahc_handle_proto_violation(struct ahc_softc *ahc);
static void ahc_handle_message_phase(struct ahc_softc *ahc);
typedef enum {
AHCMSG_1B,
AHCMSG_2B,
AHCMSG_EXT
} ahc_msgtype;
static int ahc_sent_msg(struct ahc_softc *ahc, ahc_msgtype type,
u_int msgval, int full);
static int ahc_parse_msg(struct ahc_softc *ahc,
struct ahc_devinfo *devinfo);
static int ahc_handle_msg_reject(struct ahc_softc *ahc,
struct ahc_devinfo *devinfo);
static void ahc_handle_ign_wide_residue(struct ahc_softc *ahc,
struct ahc_devinfo *devinfo);
static void ahc_reinitialize_dataptrs(struct ahc_softc *ahc);
static void ahc_handle_devreset(struct ahc_softc *ahc,
struct ahc_devinfo *devinfo,
cam_status status, char *message,
int verbose_level);
#ifdef AHC_TARGET_MODE
static void ahc_setup_target_msgin(struct ahc_softc *ahc,
struct ahc_devinfo *devinfo,
struct scb *scb);
#endif
static bus_dmamap_callback_t ahc_dmamap_cb;
static void ahc_build_free_scb_list(struct ahc_softc *ahc);
static int ahc_init_scbdata(struct ahc_softc *ahc);
static void ahc_fini_scbdata(struct ahc_softc *ahc);
static void ahc_qinfifo_requeue(struct ahc_softc *ahc,
struct scb *prev_scb,
struct scb *scb);
static int ahc_qinfifo_count(struct ahc_softc *ahc);
static u_int ahc_rem_scb_from_disc_list(struct ahc_softc *ahc,
u_int prev, u_int scbptr);
static void ahc_add_curscb_to_free_list(struct ahc_softc *ahc);
static u_int ahc_rem_wscb(struct ahc_softc *ahc,
u_int scbpos, u_int prev);
static void ahc_reset_current_bus(struct ahc_softc *ahc);
#ifdef AHC_DUMP_SEQ
static void ahc_dumpseq(struct ahc_softc *ahc);
#endif
static int ahc_loadseq(struct ahc_softc *ahc);
static int ahc_check_patch(struct ahc_softc *ahc,
const struct patch **start_patch,
u_int start_instr, u_int *skip_addr);
static void ahc_download_instr(struct ahc_softc *ahc,
u_int instrptr, uint8_t *dconsts);
#ifdef AHC_TARGET_MODE
static void ahc_queue_lstate_event(struct ahc_softc *ahc,
struct ahc_tmode_lstate *lstate,
u_int initiator_id,
u_int event_type,
u_int event_arg);
static void ahc_update_scsiid(struct ahc_softc *ahc,
u_int targid_mask);
static int ahc_handle_target_cmd(struct ahc_softc *ahc,
struct target_cmd *cmd);
#endif
static u_int ahc_index_busy_tcl(struct ahc_softc *ahc, u_int tcl);
static void ahc_unbusy_tcl(struct ahc_softc *ahc, u_int tcl);
static void ahc_busy_tcl(struct ahc_softc *ahc,
u_int tcl, u_int busyid);
/************************** SCB and SCB queue management **********************/
static void ahc_run_untagged_queues(struct ahc_softc *ahc);
static void ahc_run_untagged_queue(struct ahc_softc *ahc,
struct scb_tailq *queue);
/****************************** Initialization ********************************/
static void ahc_alloc_scbs(struct ahc_softc *ahc);
static void ahc_shutdown(void *arg);
/*************************** Interrupt Services *******************************/
static void ahc_clear_intstat(struct ahc_softc *ahc);
static void ahc_run_qoutfifo(struct ahc_softc *ahc);
#ifdef AHC_TARGET_MODE
static void ahc_run_tqinfifo(struct ahc_softc *ahc, int paused);
#endif
static void ahc_handle_brkadrint(struct ahc_softc *ahc);
static void ahc_handle_seqint(struct ahc_softc *ahc, u_int intstat);
static void ahc_handle_scsiint(struct ahc_softc *ahc,
u_int intstat);
static void ahc_clear_critical_section(struct ahc_softc *ahc);
/***************************** Error Recovery *********************************/
static void ahc_freeze_devq(struct ahc_softc *ahc, struct scb *scb);
static int ahc_abort_scbs(struct ahc_softc *ahc, int target,
char channel, int lun, u_int tag,
role_t role, uint32_t status);
static void ahc_calc_residual(struct ahc_softc *ahc,
struct scb *scb);
/*********************** Untagged Transaction Routines ************************/
static inline void ahc_freeze_untagged_queues(struct ahc_softc *ahc);
static inline void ahc_release_untagged_queues(struct ahc_softc *ahc);
/*
* Block our completion routine from starting the next untagged
* transaction for this target or target lun.
*/
static inline void
ahc_freeze_untagged_queues(struct ahc_softc *ahc)
{
if ((ahc->flags & AHC_SCB_BTT) == 0)
ahc->untagged_queue_lock++;
}
/*
* Allow the next untagged transaction for this target or target lun
* to be executed. We use a counting semaphore to allow the lock
* to be acquired recursively. Once the count drops to zero, the
* transaction queues will be run.
*/
static inline void
ahc_release_untagged_queues(struct ahc_softc *ahc)
{
if ((ahc->flags & AHC_SCB_BTT) == 0) {
ahc->untagged_queue_lock--;
if (ahc->untagged_queue_lock == 0)
ahc_run_untagged_queues(ahc);
}
}
/************************* Sequencer Execution Control ************************/
/*
* Work around any chip bugs related to halting sequencer execution.
* On Ultra2 controllers, we must clear the CIOBUS stretch signal by
* reading a register that will set this signal and deassert it.
* Without this workaround, if the chip is paused, by an interrupt or
* manual pause while accessing scb ram, accesses to certain registers
* will hang the system (infinite pci retries).
*/
static void
ahc_pause_bug_fix(struct ahc_softc *ahc)
{
if ((ahc->features & AHC_ULTRA2) != 0)
(void)ahc_inb(ahc, CCSCBCTL);
}
/*
* Determine whether the sequencer has halted code execution.
* Returns non-zero status if the sequencer is stopped.
*/
int
ahc_is_paused(struct ahc_softc *ahc)
{
return ((ahc_inb(ahc, HCNTRL) & PAUSE) != 0);
}
/*
* Request that the sequencer stop and wait, indefinitely, for it
* to stop. The sequencer will only acknowledge that it is paused
* once it has reached an instruction boundary and PAUSEDIS is
* cleared in the SEQCTL register. The sequencer may use PAUSEDIS
* for critical sections.
*/
void
ahc_pause(struct ahc_softc *ahc)
{
ahc_outb(ahc, HCNTRL, ahc->pause);
/*
* Since the sequencer can disable pausing in a critical section, we
* must loop until it actually stops.
*/
while (ahc_is_paused(ahc) == 0)
;
ahc_pause_bug_fix(ahc);
}
/*
* Allow the sequencer to continue program execution.
* We check here to ensure that no additional interrupt
* sources that would cause the sequencer to halt have been
* asserted. If, for example, a SCSI bus reset is detected
* while we are fielding a different, pausing, interrupt type,
* we don't want to release the sequencer before going back
* into our interrupt handler and dealing with this new
* condition.
*/
void
ahc_unpause(struct ahc_softc *ahc)
{
if ((ahc_inb(ahc, INTSTAT) & (SCSIINT | SEQINT | BRKADRINT)) == 0)
ahc_outb(ahc, HCNTRL, ahc->unpause);
}
/************************** Memory mapping routines ***************************/
static struct ahc_dma_seg *
ahc_sg_bus_to_virt(struct scb *scb, uint32_t sg_busaddr)
{
int sg_index;
sg_index = (sg_busaddr - scb->sg_list_phys)/sizeof(struct ahc_dma_seg);
/* sg_list_phys points to entry 1, not 0 */
sg_index++;
return (&scb->sg_list[sg_index]);
}
static uint32_t
ahc_sg_virt_to_bus(struct scb *scb, struct ahc_dma_seg *sg)
{
int sg_index;
/* sg_list_phys points to entry 1, not 0 */
sg_index = sg - &scb->sg_list[1];
return (scb->sg_list_phys + (sg_index * sizeof(*scb->sg_list)));
}
static uint32_t
ahc_hscb_busaddr(struct ahc_softc *ahc, u_int index)
{
return (ahc->scb_data->hscb_busaddr
+ (sizeof(struct hardware_scb) * index));
}
static void
ahc_sync_scb(struct ahc_softc *ahc, struct scb *scb, int op)
{
ahc_dmamap_sync(ahc, ahc->scb_data->hscb_dmat,
ahc->scb_data->hscb_dmamap,
/*offset*/(scb->hscb - ahc->hscbs) * sizeof(*scb->hscb),
/*len*/sizeof(*scb->hscb), op);
}
void
ahc_sync_sglist(struct ahc_softc *ahc, struct scb *scb, int op)
{
if (scb->sg_count == 0)
return;
ahc_dmamap_sync(ahc, ahc->scb_data->sg_dmat, scb->sg_map->sg_dmamap,
/*offset*/(scb->sg_list - scb->sg_map->sg_vaddr)
* sizeof(struct ahc_dma_seg),
/*len*/sizeof(struct ahc_dma_seg) * scb->sg_count, op);
}
#ifdef AHC_TARGET_MODE
static uint32_t
ahc_targetcmd_offset(struct ahc_softc *ahc, u_int index)
{
return (((uint8_t *)&ahc->targetcmds[index]) - ahc->qoutfifo);
}
#endif
/*********************** Miscelaneous Support Functions ***********************/
/*
* Determine whether the sequencer reported a residual
* for this SCB/transaction.
*/
static void
ahc_update_residual(struct ahc_softc *ahc, struct scb *scb)
{
uint32_t sgptr;
sgptr = ahc_le32toh(scb->hscb->sgptr);
if ((sgptr & SG_RESID_VALID) != 0)
ahc_calc_residual(ahc, scb);
}
/*
* Return pointers to the transfer negotiation information
* for the specified our_id/remote_id pair.
*/
struct ahc_initiator_tinfo *
ahc_fetch_transinfo(struct ahc_softc *ahc, char channel, u_int our_id,
u_int remote_id, struct ahc_tmode_tstate **tstate)
{
/*
* Transfer data structures are stored from the perspective
* of the target role. Since the parameters for a connection
* in the initiator role to a given target are the same as
* when the roles are reversed, we pretend we are the target.
*/
if (channel == 'B')
our_id += 8;
*tstate = ahc->enabled_targets[our_id];
return (&(*tstate)->transinfo[remote_id]);
}
uint16_t
ahc_inw(struct ahc_softc *ahc, u_int port)
{
uint16_t r = ahc_inb(ahc, port+1) << 8;
return r | ahc_inb(ahc, port);
}
void
ahc_outw(struct ahc_softc *ahc, u_int port, u_int value)
{
ahc_outb(ahc, port, value & 0xFF);
ahc_outb(ahc, port+1, (value >> 8) & 0xFF);
}
uint32_t
ahc_inl(struct ahc_softc *ahc, u_int port)
{
return ((ahc_inb(ahc, port))
| (ahc_inb(ahc, port+1) << 8)
| (ahc_inb(ahc, port+2) << 16)
| (ahc_inb(ahc, port+3) << 24));
}
void
ahc_outl(struct ahc_softc *ahc, u_int port, uint32_t value)
{
ahc_outb(ahc, port, (value) & 0xFF);
ahc_outb(ahc, port+1, ((value) >> 8) & 0xFF);
ahc_outb(ahc, port+2, ((value) >> 16) & 0xFF);
ahc_outb(ahc, port+3, ((value) >> 24) & 0xFF);
}
uint64_t
ahc_inq(struct ahc_softc *ahc, u_int port)
{
return ((ahc_inb(ahc, port))
| (ahc_inb(ahc, port+1) << 8)
| (ahc_inb(ahc, port+2) << 16)
| (ahc_inb(ahc, port+3) << 24)
| (((uint64_t)ahc_inb(ahc, port+4)) << 32)
| (((uint64_t)ahc_inb(ahc, port+5)) << 40)
| (((uint64_t)ahc_inb(ahc, port+6)) << 48)
| (((uint64_t)ahc_inb(ahc, port+7)) << 56));
}
void
ahc_outq(struct ahc_softc *ahc, u_int port, uint64_t value)
{
ahc_outb(ahc, port, value & 0xFF);
ahc_outb(ahc, port+1, (value >> 8) & 0xFF);
ahc_outb(ahc, port+2, (value >> 16) & 0xFF);
ahc_outb(ahc, port+3, (value >> 24) & 0xFF);
ahc_outb(ahc, port+4, (value >> 32) & 0xFF);
ahc_outb(ahc, port+5, (value >> 40) & 0xFF);
ahc_outb(ahc, port+6, (value >> 48) & 0xFF);
ahc_outb(ahc, port+7, (value >> 56) & 0xFF);
}
/*
* Get a free scb. If there are none, see if we can allocate a new SCB.
*/
struct scb *
ahc_get_scb(struct ahc_softc *ahc)
{
struct scb *scb;
if ((scb = SLIST_FIRST(&ahc->scb_data->free_scbs)) == NULL) {
ahc_alloc_scbs(ahc);
scb = SLIST_FIRST(&ahc->scb_data->free_scbs);
if (scb == NULL)
return (NULL);
}
SLIST_REMOVE_HEAD(&ahc->scb_data->free_scbs, links.sle);
return (scb);
}
/*
* Return an SCB resource to the free list.
*/
void
ahc_free_scb(struct ahc_softc *ahc, struct scb *scb)
{
struct hardware_scb *hscb;
hscb = scb->hscb;
/* Clean up for the next user */
ahc->scb_data->scbindex[hscb->tag] = NULL;
scb->flags = SCB_FREE;
hscb->control = 0;
SLIST_INSERT_HEAD(&ahc->scb_data->free_scbs, scb, links.sle);
/* Notify the OSM that a resource is now available. */
ahc_platform_scb_free(ahc, scb);
}
struct scb *
ahc_lookup_scb(struct ahc_softc *ahc, u_int tag)
{
struct scb* scb;
scb = ahc->scb_data->scbindex[tag];
if (scb != NULL)
ahc_sync_scb(ahc, scb,
BUS_DMASYNC_POSTREAD|BUS_DMASYNC_POSTWRITE);
return (scb);
}
static void
ahc_swap_with_next_hscb(struct ahc_softc *ahc, struct scb *scb)
{
struct hardware_scb *q_hscb;
u_int saved_tag;
/*
* Our queuing method is a bit tricky. The card
* knows in advance which HSCB to download, and we
* can't disappoint it. To achieve this, the next
* SCB to download is saved off in ahc->next_queued_scb.
* When we are called to queue "an arbitrary scb",
* we copy the contents of the incoming HSCB to the one
* the sequencer knows about, swap HSCB pointers and
* finally assign the SCB to the tag indexed location
* in the scb_array. This makes sure that we can still
* locate the correct SCB by SCB_TAG.
*/
q_hscb = ahc->next_queued_scb->hscb;
saved_tag = q_hscb->tag;
memcpy(q_hscb, scb->hscb, sizeof(*scb->hscb));
if ((scb->flags & SCB_CDB32_PTR) != 0) {
q_hscb->shared_data.cdb_ptr =
ahc_htole32(ahc_hscb_busaddr(ahc, q_hscb->tag)
+ offsetof(struct hardware_scb, cdb32));
}
q_hscb->tag = saved_tag;
q_hscb->next = scb->hscb->tag;
/* Now swap HSCB pointers. */
ahc->next_queued_scb->hscb = scb->hscb;
scb->hscb = q_hscb;
/* Now define the mapping from tag to SCB in the scbindex */
ahc->scb_data->scbindex[scb->hscb->tag] = scb;
}
/*
* Tell the sequencer about a new transaction to execute.
*/
void
ahc_queue_scb(struct ahc_softc *ahc, struct scb *scb)
{
ahc_swap_with_next_hscb(ahc, scb);
if (scb->hscb->tag == SCB_LIST_NULL
|| scb->hscb->next == SCB_LIST_NULL)
panic("Attempt to queue invalid SCB tag %x:%x\n",
scb->hscb->tag, scb->hscb->next);
/*
* Setup data "oddness".
*/
scb->hscb->lun &= LID;
if (ahc_get_transfer_length(scb) & 0x1)
scb->hscb->lun |= SCB_XFERLEN_ODD;
/*
* Keep a history of SCBs we've downloaded in the qinfifo.
*/
ahc->qinfifo[ahc->qinfifonext++] = scb->hscb->tag;
/*
* Make sure our data is consistent from the
* perspective of the adapter.
*/
ahc_sync_scb(ahc, scb, BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
/* Tell the adapter about the newly queued SCB */
if ((ahc->features & AHC_QUEUE_REGS) != 0) {
ahc_outb(ahc, HNSCB_QOFF, ahc->qinfifonext);
} else {
if ((ahc->features & AHC_AUTOPAUSE) == 0)
ahc_pause(ahc);
ahc_outb(ahc, KERNEL_QINPOS, ahc->qinfifonext);
if ((ahc->features & AHC_AUTOPAUSE) == 0)
ahc_unpause(ahc);
}
}
struct scsi_sense_data *
ahc_get_sense_buf(struct ahc_softc *ahc, struct scb *scb)
{
int offset;
offset = scb - ahc->scb_data->scbarray;
return (&ahc->scb_data->sense[offset]);
}
static uint32_t
ahc_get_sense_bufaddr(struct ahc_softc *ahc, struct scb *scb)
{
int offset;
offset = scb - ahc->scb_data->scbarray;
return (ahc->scb_data->sense_busaddr
+ (offset * sizeof(struct scsi_sense_data)));
}
/************************** Interrupt Processing ******************************/
static void
ahc_sync_qoutfifo(struct ahc_softc *ahc, int op)
{
ahc_dmamap_sync(ahc, ahc->shared_data_dmat, ahc->shared_data_dmamap,
/*offset*/0, /*len*/256, op);
}
static void
ahc_sync_tqinfifo(struct ahc_softc *ahc, int op)
{
#ifdef AHC_TARGET_MODE
if ((ahc->flags & AHC_TARGETROLE) != 0) {
ahc_dmamap_sync(ahc, ahc->shared_data_dmat,
ahc->shared_data_dmamap,
ahc_targetcmd_offset(ahc, 0),
sizeof(struct target_cmd) * AHC_TMODE_CMDS,
op);
}
#endif
}
/*
* See if the firmware has posted any completed commands
* into our in-core command complete fifos.
*/
#define AHC_RUN_QOUTFIFO 0x1
#define AHC_RUN_TQINFIFO 0x2
static u_int
ahc_check_cmdcmpltqueues(struct ahc_softc *ahc)
{
u_int retval;
retval = 0;
ahc_dmamap_sync(ahc, ahc->shared_data_dmat, ahc->shared_data_dmamap,
/*offset*/ahc->qoutfifonext, /*len*/1,
BUS_DMASYNC_POSTREAD);
if (ahc->qoutfifo[ahc->qoutfifonext] != SCB_LIST_NULL)
retval |= AHC_RUN_QOUTFIFO;
#ifdef AHC_TARGET_MODE
if ((ahc->flags & AHC_TARGETROLE) != 0
&& (ahc->flags & AHC_TQINFIFO_BLOCKED) == 0) {
ahc_dmamap_sync(ahc, ahc->shared_data_dmat,
ahc->shared_data_dmamap,
ahc_targetcmd_offset(ahc, ahc->tqinfifofnext),
/*len*/sizeof(struct target_cmd),
BUS_DMASYNC_POSTREAD);
if (ahc->targetcmds[ahc->tqinfifonext].cmd_valid != 0)
retval |= AHC_RUN_TQINFIFO;
}
#endif
return (retval);
}
/*
* Catch an interrupt from the adapter
*/
int
ahc_intr(struct ahc_softc *ahc)
{
u_int intstat;
if ((ahc->pause & INTEN) == 0) {
/*
* Our interrupt is not enabled on the chip
* and may be disabled for re-entrancy reasons,
* so just return. This is likely just a shared
* interrupt.
*/
return (0);
}
/*
* Instead of directly reading the interrupt status register,
* infer the cause of the interrupt by checking our in-core
* completion queues. This avoids a costly PCI bus read in
* most cases.
*/
if ((ahc->flags & (AHC_ALL_INTERRUPTS|AHC_EDGE_INTERRUPT)) == 0
&& (ahc_check_cmdcmpltqueues(ahc) != 0))
intstat = CMDCMPLT;
else {
intstat = ahc_inb(ahc, INTSTAT);
}
if ((intstat & INT_PEND) == 0) {
#if AHC_PCI_CONFIG > 0
if (ahc->unsolicited_ints > 500) {
ahc->unsolicited_ints = 0;
if ((ahc->chip & AHC_PCI) != 0
&& (ahc_inb(ahc, ERROR) & PCIERRSTAT) != 0)
ahc->bus_intr(ahc);
}
#endif
ahc->unsolicited_ints++;
return (0);
}
ahc->unsolicited_ints = 0;
if (intstat & CMDCMPLT) {
ahc_outb(ahc, CLRINT, CLRCMDINT);
/*
* Ensure that the chip sees that we've cleared
* this interrupt before we walk the output fifo.
* Otherwise, we may, due to posted bus writes,
* clear the interrupt after we finish the scan,
* and after the sequencer has added new entries
* and asserted the interrupt again.
*/
ahc_flush_device_writes(ahc);
ahc_run_qoutfifo(ahc);
#ifdef AHC_TARGET_MODE
if ((ahc->flags & AHC_TARGETROLE) != 0)
ahc_run_tqinfifo(ahc, /*paused*/FALSE);
#endif
}
/*
* Handle statuses that may invalidate our cached
* copy of INTSTAT separately.
*/
if (intstat == 0xFF && (ahc->features & AHC_REMOVABLE) != 0) {
/* Hot eject. Do nothing */
} else if (intstat & BRKADRINT) {
ahc_handle_brkadrint(ahc);
} else if ((intstat & (SEQINT|SCSIINT)) != 0) {
ahc_pause_bug_fix(ahc);
if ((intstat & SEQINT) != 0)
ahc_handle_seqint(ahc, intstat);
if ((intstat & SCSIINT) != 0)
ahc_handle_scsiint(ahc, intstat);
}
return (1);
}
/************************* Sequencer Execution Control ************************/
/*
* Restart the sequencer program from address zero
*/
static void
ahc_restart(struct ahc_softc *ahc)
{
uint8_t sblkctl;
ahc_pause(ahc);
/* No more pending messages. */
ahc_clear_msg_state(ahc);
ahc_outb(ahc, SCSISIGO, 0); /* De-assert BSY */
ahc_outb(ahc, MSG_OUT, MSG_NOOP); /* No message to send */
ahc_outb(ahc, SXFRCTL1, ahc_inb(ahc, SXFRCTL1) & ~BITBUCKET);
ahc_outb(ahc, LASTPHASE, P_BUSFREE);
ahc_outb(ahc, SAVED_SCSIID, 0xFF);
ahc_outb(ahc, SAVED_LUN, 0xFF);
/*
* Ensure that the sequencer's idea of TQINPOS
* matches our own. The sequencer increments TQINPOS
* only after it sees a DMA complete and a reset could
* occur before the increment leaving the kernel to believe
* the command arrived but the sequencer to not.
*/
ahc_outb(ahc, TQINPOS, ahc->tqinfifonext);
/* Always allow reselection */
ahc_outb(ahc, SCSISEQ,
ahc_inb(ahc, SCSISEQ_TEMPLATE) & (ENSELI|ENRSELI|ENAUTOATNP));
if ((ahc->features & AHC_CMD_CHAN) != 0) {
/* Ensure that no DMA operations are in progress */
ahc_outb(ahc, CCSCBCNT, 0);
ahc_outb(ahc, CCSGCTL, 0);
ahc_outb(ahc, CCSCBCTL, 0);
}
/*
* If we were in the process of DMA'ing SCB data into
* an SCB, replace that SCB on the free list. This prevents
* an SCB leak.
*/
if ((ahc_inb(ahc, SEQ_FLAGS2) & SCB_DMA) != 0) {
ahc_add_curscb_to_free_list(ahc);
ahc_outb(ahc, SEQ_FLAGS2,
ahc_inb(ahc, SEQ_FLAGS2) & ~SCB_DMA);
}
/*
* Clear any pending sequencer interrupt. It is no
* longer relevant since we're resetting the Program
* Counter.
*/
ahc_outb(ahc, CLRINT, CLRSEQINT);
ahc_outb(ahc, MWI_RESIDUAL, 0);
ahc_outb(ahc, SEQCTL, ahc->seqctl);
ahc_outb(ahc, SEQADDR0, 0);
ahc_outb(ahc, SEQADDR1, 0);
/*
* Take the LED out of diagnostic mode on PM resume, too
*/
sblkctl = ahc_inb(ahc, SBLKCTL);
ahc_outb(ahc, SBLKCTL, (sblkctl & ~(DIAGLEDEN|DIAGLEDON)));
ahc_unpause(ahc);
}
/************************* Input/Output Queues ********************************/
static void
ahc_run_qoutfifo(struct ahc_softc *ahc)
{
struct scb *scb;
u_int scb_index;
ahc_sync_qoutfifo(ahc, BUS_DMASYNC_POSTREAD);
while (ahc->qoutfifo[ahc->qoutfifonext] != SCB_LIST_NULL) {
scb_index = ahc->qoutfifo[ahc->qoutfifonext];
if ((ahc->qoutfifonext & 0x03) == 0x03) {
u_int modnext;
/*
* Clear 32bits of QOUTFIFO at a time
* so that we don't clobber an incoming
* byte DMA to the array on architectures
* that only support 32bit load and store
* operations.
*/
modnext = ahc->qoutfifonext & ~0x3;
*((uint32_t *)(&ahc->qoutfifo[modnext])) = 0xFFFFFFFFUL;
ahc_dmamap_sync(ahc, ahc->shared_data_dmat,
ahc->shared_data_dmamap,
/*offset*/modnext, /*len*/4,
BUS_DMASYNC_PREREAD);
}
ahc->qoutfifonext++;
scb = ahc_lookup_scb(ahc, scb_index);
if (scb == NULL) {
printf("%s: WARNING no command for scb %d "
"(cmdcmplt)\nQOUTPOS = %d\n",
ahc_name(ahc), scb_index,
(ahc->qoutfifonext - 1) & 0xFF);
continue;
}
/*
* Save off the residual
* if there is one.
*/
ahc_update_residual(ahc, scb);
ahc_done(ahc, scb);
}
}
static void
ahc_run_untagged_queues(struct ahc_softc *ahc)
{
int i;
for (i = 0; i < 16; i++)
ahc_run_untagged_queue(ahc, &ahc->untagged_queues[i]);
}
static void
ahc_run_untagged_queue(struct ahc_softc *ahc, struct scb_tailq *queue)
{
struct scb *scb;
if (ahc->untagged_queue_lock != 0)
return;
if ((scb = TAILQ_FIRST(queue)) != NULL
&& (scb->flags & SCB_ACTIVE) == 0) {
scb->flags |= SCB_ACTIVE;
ahc_queue_scb(ahc, scb);
}
}
/************************* Interrupt Handling *********************************/
static void
ahc_handle_brkadrint(struct ahc_softc *ahc)
{
/*
* We upset the sequencer :-(
* Lookup the error message
*/
int i;
int error;
error = ahc_inb(ahc, ERROR);
for (i = 0; error != 1 && i < num_errors; i++)
error >>= 1;
printf("%s: brkadrint, %s at seqaddr = 0x%x\n",
ahc_name(ahc), ahc_hard_errors[i].errmesg,
ahc_inb(ahc, SEQADDR0) |
(ahc_inb(ahc, SEQADDR1) << 8));
ahc_dump_card_state(ahc);
/* Tell everyone that this HBA is no longer available */
ahc_abort_scbs(ahc, CAM_TARGET_WILDCARD, ALL_CHANNELS,
CAM_LUN_WILDCARD, SCB_LIST_NULL, ROLE_UNKNOWN,
CAM_NO_HBA);
/* Disable all interrupt sources by resetting the controller */
ahc_shutdown(ahc);
}
static void
ahc_handle_seqint(struct ahc_softc *ahc, u_int intstat)
{
struct scb *scb;
struct ahc_devinfo devinfo;
ahc_fetch_devinfo(ahc, &devinfo);
/*
* Clear the upper byte that holds SEQINT status
* codes and clear the SEQINT bit. We will unpause
* the sequencer, if appropriate, after servicing
* the request.
*/
ahc_outb(ahc, CLRINT, CLRSEQINT);
switch (intstat & SEQINT_MASK) {
case BAD_STATUS:
{
u_int scb_index;
struct hardware_scb *hscb;
/*
* Set the default return value to 0 (don't
* send sense). The sense code will change
* this if needed.
*/
ahc_outb(ahc, RETURN_1, 0);
/*
* The sequencer will notify us when a command
* has an error that would be of interest to
* the kernel. This allows us to leave the sequencer
* running in the common case of command completes
* without error. The sequencer will already have
* dma'd the SCB back up to us, so we can reference
* the in kernel copy directly.
*/
scb_index = ahc_inb(ahc, SCB_TAG);
scb = ahc_lookup_scb(ahc, scb_index);
if (scb == NULL) {
ahc_print_devinfo(ahc, &devinfo);
printf("ahc_intr - referenced scb "
"not valid during seqint 0x%x scb(%d)\n",
intstat, scb_index);
ahc_dump_card_state(ahc);
panic("for safety");
goto unpause;
}
hscb = scb->hscb;
/* Don't want to clobber the original sense code */
if ((scb->flags & SCB_SENSE) != 0) {
/*
* Clear the SCB_SENSE Flag and have
* the sequencer do a normal command
* complete.
*/
scb->flags &= ~SCB_SENSE;
ahc_set_transaction_status(scb, CAM_AUTOSENSE_FAIL);
break;
}
ahc_set_transaction_status(scb, CAM_SCSI_STATUS_ERROR);
/* Freeze the queue until the client sees the error. */
ahc_freeze_devq(ahc, scb);
ahc_freeze_scb(scb);
ahc_set_scsi_status(scb, hscb->shared_data.status.scsi_status);
switch (hscb->shared_data.status.scsi_status) {
case SCSI_STATUS_OK:
printf("%s: Interrupted for staus of 0???\n",
ahc_name(ahc));
break;
case SCSI_STATUS_CMD_TERMINATED:
case SCSI_STATUS_CHECK_COND:
{
struct ahc_dma_seg *sg;
struct scsi_sense *sc;
struct ahc_initiator_tinfo *targ_info;
struct ahc_tmode_tstate *tstate;
struct ahc_transinfo *tinfo;
#ifdef AHC_DEBUG
if (ahc_debug & AHC_SHOW_SENSE) {
ahc_print_path(ahc, scb);
printf("SCB %d: requests Check Status\n",
scb->hscb->tag);
}
#endif
if (ahc_perform_autosense(scb) == 0)
break;
targ_info = ahc_fetch_transinfo(ahc,
devinfo.channel,
devinfo.our_scsiid,
devinfo.target,
&tstate);
tinfo = &targ_info->curr;
sg = scb->sg_list;
sc = (struct scsi_sense *)(&hscb->shared_data.cdb);
/*
* Save off the residual if there is one.
*/
ahc_update_residual(ahc, scb);
#ifdef AHC_DEBUG
if (ahc_debug & AHC_SHOW_SENSE) {
ahc_print_path(ahc, scb);
printf("Sending Sense\n");
}
#endif
sg->addr = ahc_get_sense_bufaddr(ahc, scb);
sg->len = ahc_get_sense_bufsize(ahc, scb);
sg->len |= AHC_DMA_LAST_SEG;
/* Fixup byte order */
sg->addr = ahc_htole32(sg->addr);
sg->len = ahc_htole32(sg->len);
sc->opcode = REQUEST_SENSE;
sc->byte2 = 0;
if (tinfo->protocol_version <= SCSI_REV_2
&& SCB_GET_LUN(scb) < 8)
sc->byte2 = SCB_GET_LUN(scb) << 5;
sc->unused[0] = 0;
sc->unused[1] = 0;
sc->length = sg->len;
sc->control = 0;
/*
* We can't allow the target to disconnect.
* This will be an untagged transaction and
* having the target disconnect will make this
* transaction indestinguishable from outstanding
* tagged transactions.
*/
hscb->control = 0;
/*
* This request sense could be because the
* the device lost power or in some other
* way has lost our transfer negotiations.
* Renegotiate if appropriate. Unit attention
* errors will be reported before any data
* phases occur.
*/
if (ahc_get_residual(scb)
== ahc_get_transfer_length(scb)) {
ahc_update_neg_request(ahc, &devinfo,
tstate, targ_info,
AHC_NEG_IF_NON_ASYNC);
}
if (tstate->auto_negotiate & devinfo.target_mask) {
hscb->control |= MK_MESSAGE;
scb->flags &= ~SCB_NEGOTIATE;
scb->flags |= SCB_AUTO_NEGOTIATE;
}
hscb->cdb_len = sizeof(*sc);
hscb->dataptr = sg->addr;
hscb->datacnt = sg->len;
hscb->sgptr = scb->sg_list_phys | SG_FULL_RESID;
hscb->sgptr = ahc_htole32(hscb->sgptr);
scb->sg_count = 1;
scb->flags |= SCB_SENSE;
ahc_qinfifo_requeue_tail(ahc, scb);
ahc_outb(ahc, RETURN_1, SEND_SENSE);
/*
* Ensure we have enough time to actually
* retrieve the sense.
*/
ahc_scb_timer_reset(scb, 5 * 1000000);
break;
}
default:
break;
}
break;
}
case NO_MATCH:
{
/* Ensure we don't leave the selection hardware on */
ahc_outb(ahc, SCSISEQ,
ahc_inb(ahc, SCSISEQ) & (ENSELI|ENRSELI|ENAUTOATNP));
printf("%s:%c:%d: no active SCB for reconnecting "
"target - issuing BUS DEVICE RESET\n",
ahc_name(ahc), devinfo.channel, devinfo.target);
printf("SAVED_SCSIID == 0x%x, SAVED_LUN == 0x%x, "
"ARG_1 == 0x%x ACCUM = 0x%x\n",
ahc_inb(ahc, SAVED_SCSIID), ahc_inb(ahc, SAVED_LUN),
ahc_inb(ahc, ARG_1), ahc_inb(ahc, ACCUM));
printf("SEQ_FLAGS == 0x%x, SCBPTR == 0x%x, BTT == 0x%x, "
"SINDEX == 0x%x\n",
ahc_inb(ahc, SEQ_FLAGS), ahc_inb(ahc, SCBPTR),
ahc_index_busy_tcl(ahc,
BUILD_TCL(ahc_inb(ahc, SAVED_SCSIID),
ahc_inb(ahc, SAVED_LUN))),
ahc_inb(ahc, SINDEX));
printf("SCSIID == 0x%x, SCB_SCSIID == 0x%x, SCB_LUN == 0x%x, "
"SCB_TAG == 0x%x, SCB_CONTROL == 0x%x\n",
ahc_inb(ahc, SCSIID), ahc_inb(ahc, SCB_SCSIID),
ahc_inb(ahc, SCB_LUN), ahc_inb(ahc, SCB_TAG),
ahc_inb(ahc, SCB_CONTROL));
printf("SCSIBUSL == 0x%x, SCSISIGI == 0x%x\n",
ahc_inb(ahc, SCSIBUSL), ahc_inb(ahc, SCSISIGI));
printf("SXFRCTL0 == 0x%x\n", ahc_inb(ahc, SXFRCTL0));
printf("SEQCTL == 0x%x\n", ahc_inb(ahc, SEQCTL));
ahc_dump_card_state(ahc);
ahc->msgout_buf[0] = MSG_BUS_DEV_RESET;
ahc->msgout_len = 1;
ahc->msgout_index = 0;
ahc->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
ahc_outb(ahc, MSG_OUT, HOST_MSG);
ahc_assert_atn(ahc);
break;
}
case SEND_REJECT:
{
u_int rejbyte = ahc_inb(ahc, ACCUM);
printf("%s:%c:%d: Warning - unknown message received from "
"target (0x%x). Rejecting\n",
ahc_name(ahc), devinfo.channel, devinfo.target, rejbyte);
break;
}
case PROTO_VIOLATION:
{
ahc_handle_proto_violation(ahc);
break;
}
case IGN_WIDE_RES:
ahc_handle_ign_wide_residue(ahc, &devinfo);
break;
case PDATA_REINIT:
ahc_reinitialize_dataptrs(ahc);
break;
case BAD_PHASE:
{
u_int lastphase;
lastphase = ahc_inb(ahc, LASTPHASE);
printf("%s:%c:%d: unknown scsi bus phase %x, "
"lastphase = 0x%x. Attempting to continue\n",
ahc_name(ahc), devinfo.channel, devinfo.target,
lastphase, ahc_inb(ahc, SCSISIGI));
break;
}
case MISSED_BUSFREE:
{
u_int lastphase;
lastphase = ahc_inb(ahc, LASTPHASE);
printf("%s:%c:%d: Missed busfree. "
"Lastphase = 0x%x, Curphase = 0x%x\n",
ahc_name(ahc), devinfo.channel, devinfo.target,
lastphase, ahc_inb(ahc, SCSISIGI));
ahc_restart(ahc);
return;
}
case HOST_MSG_LOOP:
{
/*
* The sequencer has encountered a message phase
* that requires host assistance for completion.
* While handling the message phase(s), we will be
* notified by the sequencer after each byte is
* transfered so we can track bus phase changes.
*
* If this is the first time we've seen a HOST_MSG_LOOP
* interrupt, initialize the state of the host message
* loop.
*/
if (ahc->msg_type == MSG_TYPE_NONE) {
struct scb *scb;
u_int scb_index;
u_int bus_phase;
bus_phase = ahc_inb(ahc, SCSISIGI) & PHASE_MASK;
if (bus_phase != P_MESGIN
&& bus_phase != P_MESGOUT) {
printf("ahc_intr: HOST_MSG_LOOP bad "
"phase 0x%x\n",
bus_phase);
/*
* Probably transitioned to bus free before
* we got here. Just punt the message.
*/
ahc_clear_intstat(ahc);
ahc_restart(ahc);
return;
}
scb_index = ahc_inb(ahc, SCB_TAG);
scb = ahc_lookup_scb(ahc, scb_index);
if (devinfo.role == ROLE_INITIATOR) {
if (bus_phase == P_MESGOUT) {
if (scb == NULL)
panic("HOST_MSG_LOOP with "
"invalid SCB %x\n",
scb_index);
ahc_setup_initiator_msgout(ahc,
&devinfo,
scb);
} else {
ahc->msg_type =
MSG_TYPE_INITIATOR_MSGIN;
ahc->msgin_index = 0;
}
}
#ifdef AHC_TARGET_MODE
else {
if (bus_phase == P_MESGOUT) {
ahc->msg_type =
MSG_TYPE_TARGET_MSGOUT;
ahc->msgin_index = 0;
}
else
ahc_setup_target_msgin(ahc,
&devinfo,
scb);
}
#endif
}
ahc_handle_message_phase(ahc);
break;
}
case PERR_DETECTED:
{
/*
* If we've cleared the parity error interrupt
* but the sequencer still believes that SCSIPERR
* is true, it must be that the parity error is
* for the currently presented byte on the bus,
* and we are not in a phase (data-in) where we will
* eventually ack this byte. Ack the byte and
* throw it away in the hope that the target will
* take us to message out to deliver the appropriate
* error message.
*/
if ((intstat & SCSIINT) == 0
&& (ahc_inb(ahc, SSTAT1) & SCSIPERR) != 0) {
if ((ahc->features & AHC_DT) == 0) {
u_int curphase;
/*
* The hardware will only let you ack bytes
* if the expected phase in SCSISIGO matches
* the current phase. Make sure this is
* currently the case.
*/
curphase = ahc_inb(ahc, SCSISIGI) & PHASE_MASK;
ahc_outb(ahc, LASTPHASE, curphase);
ahc_outb(ahc, SCSISIGO, curphase);
}
if ((ahc_inb(ahc, SCSISIGI) & (CDI|MSGI)) == 0) {
int wait;
/*
* In a data phase. Faster to bitbucket
* the data than to individually ack each
* byte. This is also the only strategy
* that will work with AUTOACK enabled.
*/
ahc_outb(ahc, SXFRCTL1,
ahc_inb(ahc, SXFRCTL1) | BITBUCKET);
wait = 5000;
while (--wait != 0) {
if ((ahc_inb(ahc, SCSISIGI)
& (CDI|MSGI)) != 0)
break;
ahc_delay(100);
}
ahc_outb(ahc, SXFRCTL1,
ahc_inb(ahc, SXFRCTL1) & ~BITBUCKET);
if (wait == 0) {
struct scb *scb;
u_int scb_index;
ahc_print_devinfo(ahc, &devinfo);
printf("Unable to clear parity error. "
"Resetting bus.\n");
scb_index = ahc_inb(ahc, SCB_TAG);
scb = ahc_lookup_scb(ahc, scb_index);
if (scb != NULL)
ahc_set_transaction_status(scb,
CAM_UNCOR_PARITY);
ahc_reset_channel(ahc, devinfo.channel,
/*init reset*/TRUE);
}
} else {
ahc_inb(ahc, SCSIDATL);
}
}
break;
}
case DATA_OVERRUN:
{
/*
* When the sequencer detects an overrun, it
* places the controller in "BITBUCKET" mode
* and allows the target to complete its transfer.
* Unfortunately, none of the counters get updated
* when the controller is in this mode, so we have
* no way of knowing how large the overrun was.
*/
u_int scbindex = ahc_inb(ahc, SCB_TAG);
u_int lastphase = ahc_inb(ahc, LASTPHASE);
u_int i;
scb = ahc_lookup_scb(ahc, scbindex);
for (i = 0; i < num_phases; i++) {
if (lastphase == ahc_phase_table[i].phase)
break;
}
ahc_print_path(ahc, scb);
printf("data overrun detected %s."
" Tag == 0x%x.\n",
ahc_phase_table[i].phasemsg,
scb->hscb->tag);
ahc_print_path(ahc, scb);
printf("%s seen Data Phase. Length = %ld. NumSGs = %d.\n",
ahc_inb(ahc, SEQ_FLAGS) & DPHASE ? "Have" : "Haven't",
ahc_get_transfer_length(scb), scb->sg_count);
if (scb->sg_count > 0) {
for (i = 0; i < scb->sg_count; i++) {
printf("sg[%d] - Addr 0x%x%x : Length %d\n",
i,
(ahc_le32toh(scb->sg_list[i].len) >> 24
& SG_HIGH_ADDR_BITS),
ahc_le32toh(scb->sg_list[i].addr),
ahc_le32toh(scb->sg_list[i].len)
& AHC_SG_LEN_MASK);
}
}
/*
* Set this and it will take effect when the
* target does a command complete.
*/
ahc_freeze_devq(ahc, scb);
if ((scb->flags & SCB_SENSE) == 0) {
ahc_set_transaction_status(scb, CAM_DATA_RUN_ERR);
} else {
scb->flags &= ~SCB_SENSE;
ahc_set_transaction_status(scb, CAM_AUTOSENSE_FAIL);
}
ahc_freeze_scb(scb);
if ((ahc->features & AHC_ULTRA2) != 0) {
/*
* Clear the channel in case we return
* to data phase later.
*/
ahc_outb(ahc, SXFRCTL0,
ahc_inb(ahc, SXFRCTL0) | CLRSTCNT|CLRCHN);
ahc_outb(ahc, SXFRCTL0,
ahc_inb(ahc, SXFRCTL0) | CLRSTCNT|CLRCHN);
}
if ((ahc->flags & AHC_39BIT_ADDRESSING) != 0) {
u_int dscommand1;
/* Ensure HHADDR is 0 for future DMA operations. */
dscommand1 = ahc_inb(ahc, DSCOMMAND1);
ahc_outb(ahc, DSCOMMAND1, dscommand1 | HADDLDSEL0);
ahc_outb(ahc, HADDR, 0);
ahc_outb(ahc, DSCOMMAND1, dscommand1);
}
break;
}
case MKMSG_FAILED:
{
u_int scbindex;
printf("%s:%c:%d:%d: Attempt to issue message failed\n",
ahc_name(ahc), devinfo.channel, devinfo.target,
devinfo.lun);
scbindex = ahc_inb(ahc, SCB_TAG);
scb = ahc_lookup_scb(ahc, scbindex);
if (scb != NULL
&& (scb->flags & SCB_RECOVERY_SCB) != 0)
/*
* Ensure that we didn't put a second instance of this
* SCB into the QINFIFO.
*/
ahc_search_qinfifo(ahc, SCB_GET_TARGET(ahc, scb),
SCB_GET_CHANNEL(ahc, scb),
SCB_GET_LUN(scb), scb->hscb->tag,
ROLE_INITIATOR, /*status*/0,
SEARCH_REMOVE);
break;
}
case NO_FREE_SCB:
{
printf("%s: No free or disconnected SCBs\n", ahc_name(ahc));
ahc_dump_card_state(ahc);
panic("for safety");
break;
}
case SCB_MISMATCH:
{
u_int scbptr;
scbptr = ahc_inb(ahc, SCBPTR);
printf("Bogus TAG after DMA. SCBPTR %d, tag %d, our tag %d\n",
scbptr, ahc_inb(ahc, ARG_1),
ahc->scb_data->hscbs[scbptr].tag);
ahc_dump_card_state(ahc);
panic("for saftey");
break;
}
case OUT_OF_RANGE:
{
printf("%s: BTT calculation out of range\n", ahc_name(ahc));
printf("SAVED_SCSIID == 0x%x, SAVED_LUN == 0x%x, "
"ARG_1 == 0x%x ACCUM = 0x%x\n",
ahc_inb(ahc, SAVED_SCSIID), ahc_inb(ahc, SAVED_LUN),
ahc_inb(ahc, ARG_1), ahc_inb(ahc, ACCUM));
printf("SEQ_FLAGS == 0x%x, SCBPTR == 0x%x, BTT == 0x%x, "
"SINDEX == 0x%x\n, A == 0x%x\n",
ahc_inb(ahc, SEQ_FLAGS), ahc_inb(ahc, SCBPTR),
ahc_index_busy_tcl(ahc,
BUILD_TCL(ahc_inb(ahc, SAVED_SCSIID),
ahc_inb(ahc, SAVED_LUN))),
ahc_inb(ahc, SINDEX),
ahc_inb(ahc, ACCUM));
printf("SCSIID == 0x%x, SCB_SCSIID == 0x%x, SCB_LUN == 0x%x, "
"SCB_TAG == 0x%x, SCB_CONTROL == 0x%x\n",
ahc_inb(ahc, SCSIID), ahc_inb(ahc, SCB_SCSIID),
ahc_inb(ahc, SCB_LUN), ahc_inb(ahc, SCB_TAG),
ahc_inb(ahc, SCB_CONTROL));
printf("SCSIBUSL == 0x%x, SCSISIGI == 0x%x\n",
ahc_inb(ahc, SCSIBUSL), ahc_inb(ahc, SCSISIGI));
ahc_dump_card_state(ahc);
panic("for safety");
break;
}
default:
printf("ahc_intr: seqint, "
"intstat == 0x%x, scsisigi = 0x%x\n",
intstat, ahc_inb(ahc, SCSISIGI));
break;
}
unpause:
/*
* The sequencer is paused immediately on
* a SEQINT, so we should restart it when
* we're done.
*/
ahc_unpause(ahc);
}
static void
ahc_handle_scsiint(struct ahc_softc *ahc, u_int intstat)
{
u_int scb_index;
u_int status0;
u_int status;
struct scb *scb;
char cur_channel;
char intr_channel;
if ((ahc->features & AHC_TWIN) != 0
&& ((ahc_inb(ahc, SBLKCTL) & SELBUSB) != 0))
cur_channel = 'B';
else
cur_channel = 'A';
intr_channel = cur_channel;
if ((ahc->features & AHC_ULTRA2) != 0)
status0 = ahc_inb(ahc, SSTAT0) & IOERR;
else
status0 = 0;
status = ahc_inb(ahc, SSTAT1) & (SELTO|SCSIRSTI|BUSFREE|SCSIPERR);
if (status == 0 && status0 == 0) {
if ((ahc->features & AHC_TWIN) != 0) {
/* Try the other channel */
ahc_outb(ahc, SBLKCTL, ahc_inb(ahc, SBLKCTL) ^ SELBUSB);
status = ahc_inb(ahc, SSTAT1)
& (SELTO|SCSIRSTI|BUSFREE|SCSIPERR);
intr_channel = (cur_channel == 'A') ? 'B' : 'A';
}
if (status == 0) {
printf("%s: Spurious SCSI interrupt\n", ahc_name(ahc));
ahc_outb(ahc, CLRINT, CLRSCSIINT);
ahc_unpause(ahc);
return;
}
}
/* Make sure the sequencer is in a safe location. */
ahc_clear_critical_section(ahc);
scb_index = ahc_inb(ahc, SCB_TAG);
scb = ahc_lookup_scb(ahc, scb_index);
if (scb != NULL
&& (ahc_inb(ahc, SEQ_FLAGS) & NOT_IDENTIFIED) != 0)
scb = NULL;
if ((ahc->features & AHC_ULTRA2) != 0
&& (status0 & IOERR) != 0) {
int now_lvd;
now_lvd = ahc_inb(ahc, SBLKCTL) & ENAB40;
printf("%s: Transceiver State Has Changed to %s mode\n",
ahc_name(ahc), now_lvd ? "LVD" : "SE");
ahc_outb(ahc, CLRSINT0, CLRIOERR);
/*
* When transitioning to SE mode, the reset line
* glitches, triggering an arbitration bug in some
* Ultra2 controllers. This bug is cleared when we
* assert the reset line. Since a reset glitch has
* already occurred with this transition and a
* transceiver state change is handled just like
* a bus reset anyway, asserting the reset line
* ourselves is safe.
*/
ahc_reset_channel(ahc, intr_channel,
/*Initiate Reset*/now_lvd == 0);
} else if ((status & SCSIRSTI) != 0) {
printf("%s: Someone reset channel %c\n",
ahc_name(ahc), intr_channel);
if (intr_channel != cur_channel)
ahc_outb(ahc, SBLKCTL, ahc_inb(ahc, SBLKCTL) ^ SELBUSB);
ahc_reset_channel(ahc, intr_channel, /*Initiate Reset*/FALSE);
} else if ((status & SCSIPERR) != 0) {
/*
* Determine the bus phase and queue an appropriate message.
* SCSIPERR is latched true as soon as a parity error
* occurs. If the sequencer acked the transfer that
* caused the parity error and the currently presented
* transfer on the bus has correct parity, SCSIPERR will
* be cleared by CLRSCSIPERR. Use this to determine if
* we should look at the last phase the sequencer recorded,
* or the current phase presented on the bus.
*/
struct ahc_devinfo devinfo;
u_int mesg_out;
u_int curphase;
u_int errorphase;
u_int lastphase;
u_int scsirate;
u_int i;
u_int sstat2;
int silent;
lastphase = ahc_inb(ahc, LASTPHASE);
curphase = ahc_inb(ahc, SCSISIGI) & PHASE_MASK;
sstat2 = ahc_inb(ahc, SSTAT2);
ahc_outb(ahc, CLRSINT1, CLRSCSIPERR);
/*
* For all phases save DATA, the sequencer won't
* automatically ack a byte that has a parity error
* in it. So the only way that the current phase
* could be 'data-in' is if the parity error is for
* an already acked byte in the data phase. During
* synchronous data-in transfers, we may actually
* ack bytes before latching the current phase in
* LASTPHASE, leading to the discrepancy between
* curphase and lastphase.
*/
if ((ahc_inb(ahc, SSTAT1) & SCSIPERR) != 0
|| curphase == P_DATAIN || curphase == P_DATAIN_DT)
errorphase = curphase;
else
errorphase = lastphase;
for (i = 0; i < num_phases; i++) {
if (errorphase == ahc_phase_table[i].phase)
break;
}
mesg_out = ahc_phase_table[i].mesg_out;
silent = FALSE;
if (scb != NULL) {
if (SCB_IS_SILENT(scb))
silent = TRUE;
else
ahc_print_path(ahc, scb);
scb->flags |= SCB_TRANSMISSION_ERROR;
} else
printf("%s:%c:%d: ", ahc_name(ahc), intr_channel,
SCSIID_TARGET(ahc, ahc_inb(ahc, SAVED_SCSIID)));
scsirate = ahc_inb(ahc, SCSIRATE);
if (silent == FALSE) {
printf("parity error detected %s. "
"SEQADDR(0x%x) SCSIRATE(0x%x)\n",
ahc_phase_table[i].phasemsg,
ahc_inw(ahc, SEQADDR0),
scsirate);
if ((ahc->features & AHC_DT) != 0) {
if ((sstat2 & CRCVALERR) != 0)
printf("\tCRC Value Mismatch\n");
if ((sstat2 & CRCENDERR) != 0)
printf("\tNo terminal CRC packet "
"recevied\n");
if ((sstat2 & CRCREQERR) != 0)
printf("\tIllegal CRC packet "
"request\n");
if ((sstat2 & DUAL_EDGE_ERR) != 0)
printf("\tUnexpected %sDT Data Phase\n",
(scsirate & SINGLE_EDGE)
? "" : "non-");
}
}
if ((ahc->features & AHC_DT) != 0
&& (sstat2 & DUAL_EDGE_ERR) != 0) {
/*
* This error applies regardless of
* data direction, so ignore the value
* in the phase table.
*/
mesg_out = MSG_INITIATOR_DET_ERR;
}
/*
* We've set the hardware to assert ATN if we
* get a parity error on "in" phases, so all we
* need to do is stuff the message buffer with
* the appropriate message. "In" phases have set
* mesg_out to something other than MSG_NOP.
*/
if (mesg_out != MSG_NOOP) {
if (ahc->msg_type != MSG_TYPE_NONE)
ahc->send_msg_perror = TRUE;
else
ahc_outb(ahc, MSG_OUT, mesg_out);
}
/*
* Force a renegotiation with this target just in
* case we are out of sync for some external reason
* unknown (or unreported) by the target.
*/
ahc_fetch_devinfo(ahc, &devinfo);
ahc_force_renegotiation(ahc, &devinfo);
ahc_outb(ahc, CLRINT, CLRSCSIINT);
ahc_unpause(ahc);
} else if ((status & SELTO) != 0) {
u_int scbptr;
/* Stop the selection */
ahc_outb(ahc, SCSISEQ, 0);
/* No more pending messages */
ahc_clear_msg_state(ahc);
/* Clear interrupt state */
ahc_outb(ahc, SIMODE1, ahc_inb(ahc, SIMODE1) & ~ENBUSFREE);
ahc_outb(ahc, CLRSINT1, CLRSELTIMEO|CLRBUSFREE|CLRSCSIPERR);
/*
* Although the driver does not care about the
* 'Selection in Progress' status bit, the busy
* LED does. SELINGO is only cleared by a successfull
* selection, so we must manually clear it to insure
* the LED turns off just incase no future successful
* selections occur (e.g. no devices on the bus).
*/
ahc_outb(ahc, CLRSINT0, CLRSELINGO);
scbptr = ahc_inb(ahc, WAITING_SCBH);
ahc_outb(ahc, SCBPTR, scbptr);
scb_index = ahc_inb(ahc, SCB_TAG);
scb = ahc_lookup_scb(ahc, scb_index);
if (scb == NULL) {
printf("%s: ahc_intr - referenced scb not "
"valid during SELTO scb(%d, %d)\n",
ahc_name(ahc), scbptr, scb_index);
ahc_dump_card_state(ahc);
} else {
struct ahc_devinfo devinfo;
#ifdef AHC_DEBUG
if ((ahc_debug & AHC_SHOW_SELTO) != 0) {
ahc_print_path(ahc, scb);
printf("Saw Selection Timeout for SCB 0x%x\n",
scb_index);
}
#endif
ahc_scb_devinfo(ahc, &devinfo, scb);
ahc_set_transaction_status(scb, CAM_SEL_TIMEOUT);
ahc_freeze_devq(ahc, scb);
/*
* Cancel any pending transactions on the device
* now that it seems to be missing. This will
* also revert us to async/narrow transfers until
* we can renegotiate with the device.
*/
ahc_handle_devreset(ahc, &devinfo,
CAM_SEL_TIMEOUT,
"Selection Timeout",
/*verbose_level*/1);
}
ahc_outb(ahc, CLRINT, CLRSCSIINT);
ahc_restart(ahc);
} else if ((status & BUSFREE) != 0
&& (ahc_inb(ahc, SIMODE1) & ENBUSFREE) != 0) {
struct ahc_devinfo devinfo;
u_int lastphase;
u_int saved_scsiid;
u_int saved_lun;
u_int target;
u_int initiator_role_id;
char channel;
int printerror;
/*
* Clear our selection hardware as soon as possible.
* We may have an entry in the waiting Q for this target,
* that is affected by this busfree and we don't want to
* go about selecting the target while we handle the event.
*/
ahc_outb(ahc, SCSISEQ,
ahc_inb(ahc, SCSISEQ) & (ENSELI|ENRSELI|ENAUTOATNP));
/*
* Disable busfree interrupts and clear the busfree
* interrupt status. We do this here so that several
* bus transactions occur prior to clearing the SCSIINT
* latch. It can take a bit for the clearing to take effect.
*/
ahc_outb(ahc, SIMODE1, ahc_inb(ahc, SIMODE1) & ~ENBUSFREE);
ahc_outb(ahc, CLRSINT1, CLRBUSFREE|CLRSCSIPERR);
/*
* Look at what phase we were last in.
* If its message out, chances are pretty good
* that the busfree was in response to one of
* our abort requests.
*/
lastphase = ahc_inb(ahc, LASTPHASE);
saved_scsiid = ahc_inb(ahc, SAVED_SCSIID);
saved_lun = ahc_inb(ahc, SAVED_LUN);
target = SCSIID_TARGET(ahc, saved_scsiid);
initiator_role_id = SCSIID_OUR_ID(saved_scsiid);
channel = SCSIID_CHANNEL(ahc, saved_scsiid);
ahc_compile_devinfo(&devinfo, initiator_role_id,
target, saved_lun, channel, ROLE_INITIATOR);
printerror = 1;
if (lastphase == P_MESGOUT) {
u_int tag;
tag = SCB_LIST_NULL;
if (ahc_sent_msg(ahc, AHCMSG_1B, MSG_ABORT_TAG, TRUE)
|| ahc_sent_msg(ahc, AHCMSG_1B, MSG_ABORT, TRUE)) {
if (ahc->msgout_buf[ahc->msgout_index - 1]
== MSG_ABORT_TAG)
tag = scb->hscb->tag;
ahc_print_path(ahc, scb);
printf("SCB %d - Abort%s Completed.\n",
scb->hscb->tag, tag == SCB_LIST_NULL ?
"" : " Tag");
ahc_abort_scbs(ahc, target, channel,
saved_lun, tag,
ROLE_INITIATOR,
CAM_REQ_ABORTED);
printerror = 0;
} else if (ahc_sent_msg(ahc, AHCMSG_1B,
MSG_BUS_DEV_RESET, TRUE)) {
#ifdef __FreeBSD__
/*
* Don't mark the user's request for this BDR
* as completing with CAM_BDR_SENT. CAM3
* specifies CAM_REQ_CMP.
*/
if (scb != NULL
&& scb->io_ctx->ccb_h.func_code== XPT_RESET_DEV
&& ahc_match_scb(ahc, scb, target, channel,
CAM_LUN_WILDCARD,
SCB_LIST_NULL,
ROLE_INITIATOR)) {
ahc_set_transaction_status(scb, CAM_REQ_CMP);
}
#endif
ahc_compile_devinfo(&devinfo,
initiator_role_id,
target,
CAM_LUN_WILDCARD,
channel,
ROLE_INITIATOR);
ahc_handle_devreset(ahc, &devinfo,
CAM_BDR_SENT,
"Bus Device Reset",
/*verbose_level*/0);
printerror = 0;
} else if (ahc_sent_msg(ahc, AHCMSG_EXT,
MSG_EXT_PPR, FALSE)) {
struct ahc_initiator_tinfo *tinfo;
struct ahc_tmode_tstate *tstate;
/*
* PPR Rejected. Try non-ppr negotiation
* and retry command.
*/
tinfo = ahc_fetch_transinfo(ahc,
devinfo.channel,
devinfo.our_scsiid,
devinfo.target,
&tstate);
tinfo->curr.transport_version = 2;
tinfo->goal.transport_version = 2;
tinfo->goal.ppr_options = 0;
ahc_qinfifo_requeue_tail(ahc, scb);
printerror = 0;
} else if (ahc_sent_msg(ahc, AHCMSG_EXT,
MSG_EXT_WDTR, FALSE)) {
/*
* Negotiation Rejected. Go-narrow and
* retry command.
*/
ahc_set_width(ahc, &devinfo,
MSG_EXT_WDTR_BUS_8_BIT,
AHC_TRANS_CUR|AHC_TRANS_GOAL,
/*paused*/TRUE);
ahc_qinfifo_requeue_tail(ahc, scb);
printerror = 0;
} else if (ahc_sent_msg(ahc, AHCMSG_EXT,
MSG_EXT_SDTR, FALSE)) {
/*
* Negotiation Rejected. Go-async and
* retry command.
*/
ahc_set_syncrate(ahc, &devinfo,
/*syncrate*/NULL,
/*period*/0, /*offset*/0,
/*ppr_options*/0,
AHC_TRANS_CUR|AHC_TRANS_GOAL,
/*paused*/TRUE);
ahc_qinfifo_requeue_tail(ahc, scb);
printerror = 0;
}
}
if (printerror != 0) {
u_int i;
if (scb != NULL) {
u_int tag;
if ((scb->hscb->control & TAG_ENB) != 0)
tag = scb->hscb->tag;
else
tag = SCB_LIST_NULL;
ahc_print_path(ahc, scb);
ahc_abort_scbs(ahc, target, channel,
SCB_GET_LUN(scb), tag,
ROLE_INITIATOR,
CAM_UNEXP_BUSFREE);
} else {
/*
* We had not fully identified this connection,
* so we cannot abort anything.
*/
printf("%s: ", ahc_name(ahc));
}
for (i = 0; i < num_phases; i++) {
if (lastphase == ahc_phase_table[i].phase)
break;
}
if (lastphase != P_BUSFREE) {
/*
* Renegotiate with this device at the
* next oportunity just in case this busfree
* is due to a negotiation mismatch with the
* device.
*/
ahc_force_renegotiation(ahc, &devinfo);
}
printf("Unexpected busfree %s\n"
"SEQADDR == 0x%x\n",
ahc_phase_table[i].phasemsg,
ahc_inb(ahc, SEQADDR0)
| (ahc_inb(ahc, SEQADDR1) << 8));
}
ahc_outb(ahc, CLRINT, CLRSCSIINT);
ahc_restart(ahc);
} else {
printf("%s: Missing case in ahc_handle_scsiint. status = %x\n",
ahc_name(ahc), status);
ahc_outb(ahc, CLRINT, CLRSCSIINT);
}
}
/*
* Force renegotiation to occur the next time we initiate
* a command to the current device.
*/
static void
ahc_force_renegotiation(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
{
struct ahc_initiator_tinfo *targ_info;
struct ahc_tmode_tstate *tstate;
targ_info = ahc_fetch_transinfo(ahc,
devinfo->channel,
devinfo->our_scsiid,
devinfo->target,
&tstate);
ahc_update_neg_request(ahc, devinfo, tstate,
targ_info, AHC_NEG_IF_NON_ASYNC);
}
#define AHC_MAX_STEPS 2000
static void
ahc_clear_critical_section(struct ahc_softc *ahc)
{
int stepping;
int steps;
u_int simode0;
u_int simode1;
if (ahc->num_critical_sections == 0)
return;
stepping = FALSE;
steps = 0;
simode0 = 0;
simode1 = 0;
for (;;) {
struct cs *cs;
u_int seqaddr;
u_int i;
seqaddr = ahc_inb(ahc, SEQADDR0)
| (ahc_inb(ahc, SEQADDR1) << 8);
/*
* Seqaddr represents the next instruction to execute,
* so we are really executing the instruction just
* before it.
*/
if (seqaddr != 0)
seqaddr -= 1;
cs = ahc->critical_sections;
for (i = 0; i < ahc->num_critical_sections; i++, cs++) {
if (cs->begin < seqaddr && cs->end >= seqaddr)
break;
}
if (i == ahc->num_critical_sections)
break;
if (steps > AHC_MAX_STEPS) {
printf("%s: Infinite loop in critical section\n",
ahc_name(ahc));
ahc_dump_card_state(ahc);
panic("critical section loop");
}
steps++;
if (stepping == FALSE) {
/*
* Disable all interrupt sources so that the
* sequencer will not be stuck by a pausing
* interrupt condition while we attempt to
* leave a critical section.
*/
simode0 = ahc_inb(ahc, SIMODE0);
ahc_outb(ahc, SIMODE0, 0);
simode1 = ahc_inb(ahc, SIMODE1);
if ((ahc->features & AHC_DT) != 0)
/*
* On DT class controllers, we
* use the enhanced busfree logic.
* Unfortunately we cannot re-enable
* busfree detection within the
* current connection, so we must
* leave it on while single stepping.
*/
ahc_outb(ahc, SIMODE1, simode1 & ENBUSFREE);
else
ahc_outb(ahc, SIMODE1, 0);
ahc_outb(ahc, CLRINT, CLRSCSIINT);
ahc_outb(ahc, SEQCTL, ahc->seqctl | STEP);
stepping = TRUE;
}
if ((ahc->features & AHC_DT) != 0) {
ahc_outb(ahc, CLRSINT1, CLRBUSFREE);
ahc_outb(ahc, CLRINT, CLRSCSIINT);
}
ahc_outb(ahc, HCNTRL, ahc->unpause);
while (!ahc_is_paused(ahc))
ahc_delay(200);
}
if (stepping) {
ahc_outb(ahc, SIMODE0, simode0);
ahc_outb(ahc, SIMODE1, simode1);
ahc_outb(ahc, SEQCTL, ahc->seqctl);
}
}
/*
* Clear any pending interrupt status.
*/
static void
ahc_clear_intstat(struct ahc_softc *ahc)
{
/* Clear any interrupt conditions this may have caused */
ahc_outb(ahc, CLRSINT1, CLRSELTIMEO|CLRATNO|CLRSCSIRSTI
|CLRBUSFREE|CLRSCSIPERR|CLRPHASECHG|
CLRREQINIT);
ahc_flush_device_writes(ahc);
ahc_outb(ahc, CLRSINT0, CLRSELDO|CLRSELDI|CLRSELINGO);
ahc_flush_device_writes(ahc);
ahc_outb(ahc, CLRINT, CLRSCSIINT);
ahc_flush_device_writes(ahc);
}
/**************************** Debugging Routines ******************************/
#ifdef AHC_DEBUG
uint32_t ahc_debug = AHC_DEBUG_OPTS;
#endif
#if 0 /* unused */
static void
ahc_print_scb(struct scb *scb)
{
int i;
struct hardware_scb *hscb = scb->hscb;
printf("scb:%p control:0x%x scsiid:0x%x lun:%d cdb_len:%d\n",
(void *)scb,
hscb->control,
hscb->scsiid,
hscb->lun,
hscb->cdb_len);
printf("Shared Data: ");
for (i = 0; i < sizeof(hscb->shared_data.cdb); i++)
printf("%#02x", hscb->shared_data.cdb[i]);
printf(" dataptr:%#x datacnt:%#x sgptr:%#x tag:%#x\n",
ahc_le32toh(hscb->dataptr),
ahc_le32toh(hscb->datacnt),
ahc_le32toh(hscb->sgptr),
hscb->tag);
if (scb->sg_count > 0) {
for (i = 0; i < scb->sg_count; i++) {
printf("sg[%d] - Addr 0x%x%x : Length %d\n",
i,
(ahc_le32toh(scb->sg_list[i].len) >> 24
& SG_HIGH_ADDR_BITS),
ahc_le32toh(scb->sg_list[i].addr),
ahc_le32toh(scb->sg_list[i].len));
}
}
}
#endif
/************************* Transfer Negotiation *******************************/
/*
* Allocate per target mode instance (ID we respond to as a target)
* transfer negotiation data structures.
*/
static struct ahc_tmode_tstate *
ahc_alloc_tstate(struct ahc_softc *ahc, u_int scsi_id, char channel)
{
struct ahc_tmode_tstate *master_tstate;
struct ahc_tmode_tstate *tstate;
int i;
master_tstate = ahc->enabled_targets[ahc->our_id];
if (channel == 'B') {
scsi_id += 8;
master_tstate = ahc->enabled_targets[ahc->our_id_b + 8];
}
if (ahc->enabled_targets[scsi_id] != NULL
&& ahc->enabled_targets[scsi_id] != master_tstate)
panic("%s: ahc_alloc_tstate - Target already allocated",
ahc_name(ahc));
tstate = (struct ahc_tmode_tstate*)malloc(sizeof(*tstate),
M_DEVBUF, M_NOWAIT);
if (tstate == NULL)
return (NULL);
/*
* If we have allocated a master tstate, copy user settings from
* the master tstate (taken from SRAM or the EEPROM) for this
* channel, but reset our current and goal settings to async/narrow
* until an initiator talks to us.
*/
if (master_tstate != NULL) {
memcpy(tstate, master_tstate, sizeof(*tstate));
memset(tstate->enabled_luns, 0, sizeof(tstate->enabled_luns));
tstate->ultraenb = 0;
for (i = 0; i < AHC_NUM_TARGETS; i++) {
memset(&tstate->transinfo[i].curr, 0,
sizeof(tstate->transinfo[i].curr));
memset(&tstate->transinfo[i].goal, 0,
sizeof(tstate->transinfo[i].goal));
}
} else
memset(tstate, 0, sizeof(*tstate));
ahc->enabled_targets[scsi_id] = tstate;
return (tstate);
}
#ifdef AHC_TARGET_MODE
/*
* Free per target mode instance (ID we respond to as a target)
* transfer negotiation data structures.
*/
static void
ahc_free_tstate(struct ahc_softc *ahc, u_int scsi_id, char channel, int force)
{
struct ahc_tmode_tstate *tstate;
/*
* Don't clean up our "master" tstate.
* It has our default user settings.
*/
if (((channel == 'B' && scsi_id == ahc->our_id_b)
|| (channel == 'A' && scsi_id == ahc->our_id))
&& force == FALSE)
return;
if (channel == 'B')
scsi_id += 8;
tstate = ahc->enabled_targets[scsi_id];
if (tstate != NULL)
free(tstate, M_DEVBUF);
ahc->enabled_targets[scsi_id] = NULL;
}
#endif
/*
* Called when we have an active connection to a target on the bus,
* this function finds the nearest syncrate to the input period limited
* by the capabilities of the bus connectivity of and sync settings for
* the target.
*/
const struct ahc_syncrate *
ahc_devlimited_syncrate(struct ahc_softc *ahc,
struct ahc_initiator_tinfo *tinfo,
u_int *period, u_int *ppr_options, role_t role)
{
struct ahc_transinfo *transinfo;
u_int maxsync;
if ((ahc->features & AHC_ULTRA2) != 0) {
if ((ahc_inb(ahc, SBLKCTL) & ENAB40) != 0
&& (ahc_inb(ahc, SSTAT2) & EXP_ACTIVE) == 0) {
maxsync = AHC_SYNCRATE_DT;
} else {
maxsync = AHC_SYNCRATE_ULTRA;
/* Can't do DT on an SE bus */
*ppr_options &= ~MSG_EXT_PPR_DT_REQ;
}
} else if ((ahc->features & AHC_ULTRA) != 0) {
maxsync = AHC_SYNCRATE_ULTRA;
} else {
maxsync = AHC_SYNCRATE_FAST;
}
/*
* Never allow a value higher than our current goal
* period otherwise we may allow a target initiated
* negotiation to go above the limit as set by the
* user. In the case of an initiator initiated
* sync negotiation, we limit based on the user
* setting. This allows the system to still accept
* incoming negotiations even if target initiated
* negotiation is not performed.
*/
if (role == ROLE_TARGET)
transinfo = &tinfo->user;
else
transinfo = &tinfo->goal;
*ppr_options &= transinfo->ppr_options;
if (transinfo->width == MSG_EXT_WDTR_BUS_8_BIT) {
maxsync = max(maxsync, (u_int)AHC_SYNCRATE_ULTRA2);
*ppr_options &= ~MSG_EXT_PPR_DT_REQ;
}
if (transinfo->period == 0) {
*period = 0;
*ppr_options = 0;
return (NULL);
}
*period = max(*period, (u_int)transinfo->period);
return (ahc_find_syncrate(ahc, period, ppr_options, maxsync));
}
/*
* Look up the valid period to SCSIRATE conversion in our table.
* Return the period and offset that should be sent to the target
* if this was the beginning of an SDTR.
*/
const struct ahc_syncrate *
ahc_find_syncrate(struct ahc_softc *ahc, u_int *period,
u_int *ppr_options, u_int maxsync)
{
const struct ahc_syncrate *syncrate;
if ((ahc->features & AHC_DT) == 0)
*ppr_options &= ~MSG_EXT_PPR_DT_REQ;
/* Skip all DT only entries if DT is not available */
if ((*ppr_options & MSG_EXT_PPR_DT_REQ) == 0
&& maxsync < AHC_SYNCRATE_ULTRA2)
maxsync = AHC_SYNCRATE_ULTRA2;
/* Now set the maxsync based on the card capabilities
* DT is already done above */
if ((ahc->features & (AHC_DT | AHC_ULTRA2)) == 0
&& maxsync < AHC_SYNCRATE_ULTRA)
maxsync = AHC_SYNCRATE_ULTRA;
if ((ahc->features & (AHC_DT | AHC_ULTRA2 | AHC_ULTRA)) == 0
&& maxsync < AHC_SYNCRATE_FAST)
maxsync = AHC_SYNCRATE_FAST;
for (syncrate = &ahc_syncrates[maxsync];
syncrate->rate != NULL;
syncrate++) {
/*
* The Ultra2 table doesn't go as low
* as for the Fast/Ultra cards.
*/
if ((ahc->features & AHC_ULTRA2) != 0
&& (syncrate->sxfr_u2 == 0))
break;
if (*period <= syncrate->period) {
/*
* When responding to a target that requests
* sync, the requested rate may fall between
* two rates that we can output, but still be
* a rate that we can receive. Because of this,
* we want to respond to the target with
* the same rate that it sent to us even
* if the period we use to send data to it
* is lower. Only lower the response period
* if we must.
*/
if (syncrate == &ahc_syncrates[maxsync])
*period = syncrate->period;
/*
* At some speeds, we only support
* ST transfers.
*/
if ((syncrate->sxfr_u2 & ST_SXFR) != 0)
*ppr_options &= ~MSG_EXT_PPR_DT_REQ;
break;
}
}
if ((*period == 0)
|| (syncrate->rate == NULL)
|| ((ahc->features & AHC_ULTRA2) != 0
&& (syncrate->sxfr_u2 == 0))) {
/* Use asynchronous transfers. */
*period = 0;
syncrate = NULL;
*ppr_options &= ~MSG_EXT_PPR_DT_REQ;
}
return (syncrate);
}
/*
* Convert from an entry in our syncrate table to the SCSI equivalent
* sync "period" factor.
*/
u_int
ahc_find_period(struct ahc_softc *ahc, u_int scsirate, u_int maxsync)
{
const struct ahc_syncrate *syncrate;
if ((ahc->features & AHC_ULTRA2) != 0)
scsirate &= SXFR_ULTRA2;
else
scsirate &= SXFR;
/* now set maxsync based on card capabilities */
if ((ahc->features & AHC_DT) == 0 && maxsync < AHC_SYNCRATE_ULTRA2)
maxsync = AHC_SYNCRATE_ULTRA2;
if ((ahc->features & (AHC_DT | AHC_ULTRA2)) == 0
&& maxsync < AHC_SYNCRATE_ULTRA)
maxsync = AHC_SYNCRATE_ULTRA;
if ((ahc->features & (AHC_DT | AHC_ULTRA2 | AHC_ULTRA)) == 0
&& maxsync < AHC_SYNCRATE_FAST)
maxsync = AHC_SYNCRATE_FAST;
syncrate = &ahc_syncrates[maxsync];
while (syncrate->rate != NULL) {
if ((ahc->features & AHC_ULTRA2) != 0) {
if (syncrate->sxfr_u2 == 0)
break;
else if (scsirate == (syncrate->sxfr_u2 & SXFR_ULTRA2))
return (syncrate->period);
} else if (scsirate == (syncrate->sxfr & SXFR)) {
return (syncrate->period);
}
syncrate++;
}
return (0); /* async */
}
/*
* Truncate the given synchronous offset to a value the
* current adapter type and syncrate are capable of.
*/
static void
ahc_validate_offset(struct ahc_softc *ahc,
struct ahc_initiator_tinfo *tinfo,
const struct ahc_syncrate *syncrate,
u_int *offset, int wide, role_t role)
{
u_int maxoffset;
/* Limit offset to what we can do */
if (syncrate == NULL) {
maxoffset = 0;
} else if ((ahc->features & AHC_ULTRA2) != 0) {
maxoffset = MAX_OFFSET_ULTRA2;
} else {
if (wide)
maxoffset = MAX_OFFSET_16BIT;
else
maxoffset = MAX_OFFSET_8BIT;
}
*offset = min(*offset, maxoffset);
if (tinfo != NULL) {
if (role == ROLE_TARGET)
*offset = min(*offset, (u_int)tinfo->user.offset);
else
*offset = min(*offset, (u_int)tinfo->goal.offset);
}
}
/*
* Truncate the given transfer width parameter to a value the
* current adapter type is capable of.
*/
static void
ahc_validate_width(struct ahc_softc *ahc, struct ahc_initiator_tinfo *tinfo,
u_int *bus_width, role_t role)
{
switch (*bus_width) {
default:
if (ahc->features & AHC_WIDE) {
/* Respond Wide */
*bus_width = MSG_EXT_WDTR_BUS_16_BIT;
break;
}
/* FALLTHROUGH */
case MSG_EXT_WDTR_BUS_8_BIT:
*bus_width = MSG_EXT_WDTR_BUS_8_BIT;
break;
}
if (tinfo != NULL) {
if (role == ROLE_TARGET)
*bus_width = min((u_int)tinfo->user.width, *bus_width);
else
*bus_width = min((u_int)tinfo->goal.width, *bus_width);
}
}
/*
* Update the bitmask of targets for which the controller should
* negotiate with at the next convenient oportunity. This currently
* means the next time we send the initial identify messages for
* a new transaction.
*/
int
ahc_update_neg_request(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
struct ahc_tmode_tstate *tstate,
struct ahc_initiator_tinfo *tinfo, ahc_neg_type neg_type)
{
u_int auto_negotiate_orig;
auto_negotiate_orig = tstate->auto_negotiate;
if (neg_type == AHC_NEG_ALWAYS) {
/*
* Force our "current" settings to be
* unknown so that unless a bus reset
* occurs the need to renegotiate is
* recorded persistently.
*/
if ((ahc->features & AHC_WIDE) != 0)
tinfo->curr.width = AHC_WIDTH_UNKNOWN;
tinfo->curr.period = AHC_PERIOD_UNKNOWN;
tinfo->curr.offset = AHC_OFFSET_UNKNOWN;
}
if (tinfo->curr.period != tinfo->goal.period
|| tinfo->curr.width != tinfo->goal.width
|| tinfo->curr.offset != tinfo->goal.offset
|| tinfo->curr.ppr_options != tinfo->goal.ppr_options
|| (neg_type == AHC_NEG_IF_NON_ASYNC
&& (tinfo->goal.offset != 0
|| tinfo->goal.width != MSG_EXT_WDTR_BUS_8_BIT
|| tinfo->goal.ppr_options != 0)))
tstate->auto_negotiate |= devinfo->target_mask;
else
tstate->auto_negotiate &= ~devinfo->target_mask;
return (auto_negotiate_orig != tstate->auto_negotiate);
}
/*
* Update the user/goal/curr tables of synchronous negotiation
* parameters as well as, in the case of a current or active update,
* any data structures on the host controller. In the case of an
* active update, the specified target is currently talking to us on
* the bus, so the transfer parameter update must take effect
* immediately.
*/
void
ahc_set_syncrate(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
const struct ahc_syncrate *syncrate, u_int period,
u_int offset, u_int ppr_options, u_int type, int paused)
{
struct ahc_initiator_tinfo *tinfo;
struct ahc_tmode_tstate *tstate;
u_int old_period;
u_int old_offset;
u_int old_ppr;
int active;
int update_needed;
active = (type & AHC_TRANS_ACTIVE) == AHC_TRANS_ACTIVE;
update_needed = 0;
if (syncrate == NULL) {
period = 0;
offset = 0;
}
tinfo = ahc_fetch_transinfo(ahc, devinfo->channel, devinfo->our_scsiid,
devinfo->target, &tstate);
if ((type & AHC_TRANS_USER) != 0) {
tinfo->user.period = period;
tinfo->user.offset = offset;
tinfo->user.ppr_options = ppr_options;
}
if ((type & AHC_TRANS_GOAL) != 0) {
tinfo->goal.period = period;
tinfo->goal.offset = offset;
tinfo->goal.ppr_options = ppr_options;
}
old_period = tinfo->curr.period;
old_offset = tinfo->curr.offset;
old_ppr = tinfo->curr.ppr_options;
if ((type & AHC_TRANS_CUR) != 0
&& (old_period != period
|| old_offset != offset
|| old_ppr != ppr_options)) {
u_int scsirate;
update_needed++;
scsirate = tinfo->scsirate;
if ((ahc->features & AHC_ULTRA2) != 0) {
scsirate &= ~(SXFR_ULTRA2|SINGLE_EDGE|ENABLE_CRC);
if (syncrate != NULL) {
scsirate |= syncrate->sxfr_u2;
if ((ppr_options & MSG_EXT_PPR_DT_REQ) != 0)
scsirate |= ENABLE_CRC;
else
scsirate |= SINGLE_EDGE;
}
} else {
scsirate &= ~(SXFR|SOFS);
/*
* Ensure Ultra mode is set properly for
* this target.
*/
tstate->ultraenb &= ~devinfo->target_mask;
if (syncrate != NULL) {
if (syncrate->sxfr & ULTRA_SXFR) {
tstate->ultraenb |=
devinfo->target_mask;
}
scsirate |= syncrate->sxfr & SXFR;
scsirate |= offset & SOFS;
}
if (active) {
u_int sxfrctl0;
sxfrctl0 = ahc_inb(ahc, SXFRCTL0);
sxfrctl0 &= ~FAST20;
if (tstate->ultraenb & devinfo->target_mask)
sxfrctl0 |= FAST20;
ahc_outb(ahc, SXFRCTL0, sxfrctl0);
}
}
if (active) {
ahc_outb(ahc, SCSIRATE, scsirate);
if ((ahc->features & AHC_ULTRA2) != 0)
ahc_outb(ahc, SCSIOFFSET, offset);
}
tinfo->scsirate = scsirate;
tinfo->curr.period = period;
tinfo->curr.offset = offset;
tinfo->curr.ppr_options = ppr_options;
ahc_send_async(ahc, devinfo->channel, devinfo->target,
CAM_LUN_WILDCARD, AC_TRANSFER_NEG);
if (bootverbose) {
if (offset != 0) {
printf("%s: target %d synchronous at %sMHz%s, "
"offset = 0x%x\n", ahc_name(ahc),
devinfo->target, syncrate->rate,
(ppr_options & MSG_EXT_PPR_DT_REQ)
? " DT" : "", offset);
} else {
printf("%s: target %d using "
"asynchronous transfers\n",
ahc_name(ahc), devinfo->target);
}
}
}
update_needed += ahc_update_neg_request(ahc, devinfo, tstate,
tinfo, AHC_NEG_TO_GOAL);
if (update_needed)
ahc_update_pending_scbs(ahc);
}
/*
* Update the user/goal/curr tables of wide negotiation
* parameters as well as, in the case of a current or active update,
* any data structures on the host controller. In the case of an
* active update, the specified target is currently talking to us on
* the bus, so the transfer parameter update must take effect
* immediately.
*/
void
ahc_set_width(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
u_int width, u_int type, int paused)
{
struct ahc_initiator_tinfo *tinfo;
struct ahc_tmode_tstate *tstate;
u_int oldwidth;
int active;
int update_needed;
active = (type & AHC_TRANS_ACTIVE) == AHC_TRANS_ACTIVE;
update_needed = 0;
tinfo = ahc_fetch_transinfo(ahc, devinfo->channel, devinfo->our_scsiid,
devinfo->target, &tstate);
if ((type & AHC_TRANS_USER) != 0)
tinfo->user.width = width;
if ((type & AHC_TRANS_GOAL) != 0)
tinfo->goal.width = width;
oldwidth = tinfo->curr.width;
if ((type & AHC_TRANS_CUR) != 0 && oldwidth != width) {
u_int scsirate;
update_needed++;
scsirate = tinfo->scsirate;
scsirate &= ~WIDEXFER;
if (width == MSG_EXT_WDTR_BUS_16_BIT)
scsirate |= WIDEXFER;
tinfo->scsirate = scsirate;
if (active)
ahc_outb(ahc, SCSIRATE, scsirate);
tinfo->curr.width = width;
ahc_send_async(ahc, devinfo->channel, devinfo->target,
CAM_LUN_WILDCARD, AC_TRANSFER_NEG);
if (bootverbose) {
printf("%s: target %d using %dbit transfers\n",
ahc_name(ahc), devinfo->target,
8 * (0x01 << width));
}
}
update_needed += ahc_update_neg_request(ahc, devinfo, tstate,
tinfo, AHC_NEG_TO_GOAL);
if (update_needed)
ahc_update_pending_scbs(ahc);
}
/*
* Update the current state of tagged queuing for a given target.
*/
static void
ahc_set_tags(struct ahc_softc *ahc, struct scsi_cmnd *cmd,
struct ahc_devinfo *devinfo, ahc_queue_alg alg)
{
struct scsi_device *sdev = cmd->device;
ahc_platform_set_tags(ahc, sdev, devinfo, alg);
ahc_send_async(ahc, devinfo->channel, devinfo->target,
devinfo->lun, AC_TRANSFER_NEG);
}
/*
* When the transfer settings for a connection change, update any
* in-transit SCBs to contain the new data so the hardware will
* be set correctly during future (re)selections.
*/
static void
ahc_update_pending_scbs(struct ahc_softc *ahc)
{
struct scb *pending_scb;
int pending_scb_count;
int i;
int paused;
u_int saved_scbptr;
/*
* Traverse the pending SCB list and ensure that all of the
* SCBs there have the proper settings.
*/
pending_scb_count = 0;
LIST_FOREACH(pending_scb, &ahc->pending_scbs, pending_links) {
struct ahc_devinfo devinfo;
struct hardware_scb *pending_hscb;
struct ahc_initiator_tinfo *tinfo;
struct ahc_tmode_tstate *tstate;
ahc_scb_devinfo(ahc, &devinfo, pending_scb);
tinfo = ahc_fetch_transinfo(ahc, devinfo.channel,
devinfo.our_scsiid,
devinfo.target, &tstate);
pending_hscb = pending_scb->hscb;
pending_hscb->control &= ~ULTRAENB;
if ((tstate->ultraenb & devinfo.target_mask) != 0)
pending_hscb->control |= ULTRAENB;
pending_hscb->scsirate = tinfo->scsirate;
pending_hscb->scsioffset = tinfo->curr.offset;
if ((tstate->auto_negotiate & devinfo.target_mask) == 0
&& (pending_scb->flags & SCB_AUTO_NEGOTIATE) != 0) {
pending_scb->flags &= ~SCB_AUTO_NEGOTIATE;
pending_hscb->control &= ~MK_MESSAGE;
}
ahc_sync_scb(ahc, pending_scb,
BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
pending_scb_count++;
}
if (pending_scb_count == 0)
return;
if (ahc_is_paused(ahc)) {
paused = 1;
} else {
paused = 0;
ahc_pause(ahc);
}
saved_scbptr = ahc_inb(ahc, SCBPTR);
/* Ensure that the hscbs down on the card match the new information */
for (i = 0; i < ahc->scb_data->maxhscbs; i++) {
struct hardware_scb *pending_hscb;
u_int control;
u_int scb_tag;
ahc_outb(ahc, SCBPTR, i);
scb_tag = ahc_inb(ahc, SCB_TAG);
pending_scb = ahc_lookup_scb(ahc, scb_tag);
if (pending_scb == NULL)
continue;
pending_hscb = pending_scb->hscb;
control = ahc_inb(ahc, SCB_CONTROL);
control &= ~(ULTRAENB|MK_MESSAGE);
control |= pending_hscb->control & (ULTRAENB|MK_MESSAGE);
ahc_outb(ahc, SCB_CONTROL, control);
ahc_outb(ahc, SCB_SCSIRATE, pending_hscb->scsirate);
ahc_outb(ahc, SCB_SCSIOFFSET, pending_hscb->scsioffset);
}
ahc_outb(ahc, SCBPTR, saved_scbptr);
if (paused == 0)
ahc_unpause(ahc);
}
/**************************** Pathing Information *****************************/
static void
ahc_fetch_devinfo(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
{
u_int saved_scsiid;
role_t role;
int our_id;
if (ahc_inb(ahc, SSTAT0) & TARGET)
role = ROLE_TARGET;
else
role = ROLE_INITIATOR;
if (role == ROLE_TARGET
&& (ahc->features & AHC_MULTI_TID) != 0
&& (ahc_inb(ahc, SEQ_FLAGS)
& (CMDPHASE_PENDING|TARG_CMD_PENDING|NO_DISCONNECT)) != 0) {
/* We were selected, so pull our id from TARGIDIN */
our_id = ahc_inb(ahc, TARGIDIN) & OID;
} else if ((ahc->features & AHC_ULTRA2) != 0)
our_id = ahc_inb(ahc, SCSIID_ULTRA2) & OID;
else
our_id = ahc_inb(ahc, SCSIID) & OID;
saved_scsiid = ahc_inb(ahc, SAVED_SCSIID);
ahc_compile_devinfo(devinfo,
our_id,
SCSIID_TARGET(ahc, saved_scsiid),
ahc_inb(ahc, SAVED_LUN),
SCSIID_CHANNEL(ahc, saved_scsiid),
role);
}
static const struct ahc_phase_table_entry*
ahc_lookup_phase_entry(int phase)
{
const struct ahc_phase_table_entry *entry;
const struct ahc_phase_table_entry *last_entry;
/*
* num_phases doesn't include the default entry which
* will be returned if the phase doesn't match.
*/
last_entry = &ahc_phase_table[num_phases];
for (entry = ahc_phase_table; entry < last_entry; entry++) {
if (phase == entry->phase)
break;
}
return (entry);
}
void
ahc_compile_devinfo(struct ahc_devinfo *devinfo, u_int our_id, u_int target,
u_int lun, char channel, role_t role)
{
devinfo->our_scsiid = our_id;
devinfo->target = target;
devinfo->lun = lun;
devinfo->target_offset = target;
devinfo->channel = channel;
devinfo->role = role;
if (channel == 'B')
devinfo->target_offset += 8;
devinfo->target_mask = (0x01 << devinfo->target_offset);
}
void
ahc_print_devinfo(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
{
printf("%s:%c:%d:%d: ", ahc_name(ahc), devinfo->channel,
devinfo->target, devinfo->lun);
}
static void
ahc_scb_devinfo(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
struct scb *scb)
{
role_t role;
int our_id;
our_id = SCSIID_OUR_ID(scb->hscb->scsiid);
role = ROLE_INITIATOR;
if ((scb->flags & SCB_TARGET_SCB) != 0)
role = ROLE_TARGET;
ahc_compile_devinfo(devinfo, our_id, SCB_GET_TARGET(ahc, scb),
SCB_GET_LUN(scb), SCB_GET_CHANNEL(ahc, scb), role);
}
/************************ Message Phase Processing ****************************/
static void
ahc_assert_atn(struct ahc_softc *ahc)
{
u_int scsisigo;
scsisigo = ATNO;
if ((ahc->features & AHC_DT) == 0)
scsisigo |= ahc_inb(ahc, SCSISIGI);
ahc_outb(ahc, SCSISIGO, scsisigo);
}
/*
* When an initiator transaction with the MK_MESSAGE flag either reconnects
* or enters the initial message out phase, we are interrupted. Fill our
* outgoing message buffer with the appropriate message and beging handing
* the message phase(s) manually.
*/
static void
ahc_setup_initiator_msgout(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
struct scb *scb)
{
/*
* To facilitate adding multiple messages together,
* each routine should increment the index and len
* variables instead of setting them explicitly.
*/
ahc->msgout_index = 0;
ahc->msgout_len = 0;
if ((scb->flags & SCB_DEVICE_RESET) == 0
&& ahc_inb(ahc, MSG_OUT) == MSG_IDENTIFYFLAG) {
u_int identify_msg;
identify_msg = MSG_IDENTIFYFLAG | SCB_GET_LUN(scb);
if ((scb->hscb->control & DISCENB) != 0)
identify_msg |= MSG_IDENTIFY_DISCFLAG;
ahc->msgout_buf[ahc->msgout_index++] = identify_msg;
ahc->msgout_len++;
if ((scb->hscb->control & TAG_ENB) != 0) {
ahc->msgout_buf[ahc->msgout_index++] =
scb->hscb->control & (TAG_ENB|SCB_TAG_TYPE);
ahc->msgout_buf[ahc->msgout_index++] = scb->hscb->tag;
ahc->msgout_len += 2;
}
}
if (scb->flags & SCB_DEVICE_RESET) {
ahc->msgout_buf[ahc->msgout_index++] = MSG_BUS_DEV_RESET;
ahc->msgout_len++;
ahc_print_path(ahc, scb);
printf("Bus Device Reset Message Sent\n");
/*
* Clear our selection hardware in advance of
* the busfree. We may have an entry in the waiting
* Q for this target, and we don't want to go about
* selecting while we handle the busfree and blow it
* away.
*/
ahc_outb(ahc, SCSISEQ, (ahc_inb(ahc, SCSISEQ) & ~ENSELO));
} else if ((scb->flags & SCB_ABORT) != 0) {
if ((scb->hscb->control & TAG_ENB) != 0)
ahc->msgout_buf[ahc->msgout_index++] = MSG_ABORT_TAG;
else
ahc->msgout_buf[ahc->msgout_index++] = MSG_ABORT;
ahc->msgout_len++;
ahc_print_path(ahc, scb);
printf("Abort%s Message Sent\n",
(scb->hscb->control & TAG_ENB) != 0 ? " Tag" : "");
/*
* Clear our selection hardware in advance of
* the busfree. We may have an entry in the waiting
* Q for this target, and we don't want to go about
* selecting while we handle the busfree and blow it
* away.
*/
ahc_outb(ahc, SCSISEQ, (ahc_inb(ahc, SCSISEQ) & ~ENSELO));
} else if ((scb->flags & (SCB_AUTO_NEGOTIATE|SCB_NEGOTIATE)) != 0) {
ahc_build_transfer_msg(ahc, devinfo);
} else {
printf("ahc_intr: AWAITING_MSG for an SCB that "
"does not have a waiting message\n");
printf("SCSIID = %x, target_mask = %x\n", scb->hscb->scsiid,
devinfo->target_mask);
panic("SCB = %d, SCB Control = %x, MSG_OUT = %x "
"SCB flags = %x", scb->hscb->tag, scb->hscb->control,
ahc_inb(ahc, MSG_OUT), scb->flags);
}
/*
* Clear the MK_MESSAGE flag from the SCB so we aren't
* asked to send this message again.
*/
ahc_outb(ahc, SCB_CONTROL, ahc_inb(ahc, SCB_CONTROL) & ~MK_MESSAGE);
scb->hscb->control &= ~MK_MESSAGE;
ahc->msgout_index = 0;
ahc->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
}
/*
* Build an appropriate transfer negotiation message for the
* currently active target.
*/
static void
ahc_build_transfer_msg(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
{
/*
* We need to initiate transfer negotiations.
* If our current and goal settings are identical,
* we want to renegotiate due to a check condition.
*/
struct ahc_initiator_tinfo *tinfo;
struct ahc_tmode_tstate *tstate;
const struct ahc_syncrate *rate;
int dowide;
int dosync;
int doppr;
u_int period;
u_int ppr_options;
u_int offset;
tinfo = ahc_fetch_transinfo(ahc, devinfo->channel, devinfo->our_scsiid,
devinfo->target, &tstate);
/*
* Filter our period based on the current connection.
* If we can't perform DT transfers on this segment (not in LVD
* mode for instance), then our decision to issue a PPR message
* may change.
*/
period = tinfo->goal.period;
offset = tinfo->goal.offset;
ppr_options = tinfo->goal.ppr_options;
/* Target initiated PPR is not allowed in the SCSI spec */
if (devinfo->role == ROLE_TARGET)
ppr_options = 0;
rate = ahc_devlimited_syncrate(ahc, tinfo, &period,
&ppr_options, devinfo->role);
dowide = tinfo->curr.width != tinfo->goal.width;
dosync = tinfo->curr.offset != offset || tinfo->curr.period != period;
/*
* Only use PPR if we have options that need it, even if the device
* claims to support it. There might be an expander in the way
* that doesn't.
*/
doppr = ppr_options != 0;
if (!dowide && !dosync && !doppr) {
dowide = tinfo->goal.width != MSG_EXT_WDTR_BUS_8_BIT;
dosync = tinfo->goal.offset != 0;
}
if (!dowide && !dosync && !doppr) {
/*
* Force async with a WDTR message if we have a wide bus,
* or just issue an SDTR with a 0 offset.
*/
if ((ahc->features & AHC_WIDE) != 0)
dowide = 1;
else
dosync = 1;
if (bootverbose) {
ahc_print_devinfo(ahc, devinfo);
printf("Ensuring async\n");
}
}
/* Target initiated PPR is not allowed in the SCSI spec */
if (devinfo->role == ROLE_TARGET)
doppr = 0;
/*
* Both the PPR message and SDTR message require the
* goal syncrate to be limited to what the target device
* is capable of handling (based on whether an LVD->SE
* expander is on the bus), so combine these two cases.
* Regardless, guarantee that if we are using WDTR and SDTR
* messages that WDTR comes first.
*/
if (doppr || (dosync && !dowide)) {
offset = tinfo->goal.offset;
ahc_validate_offset(ahc, tinfo, rate, &offset,
doppr ? tinfo->goal.width
: tinfo->curr.width,
devinfo->role);
if (doppr) {
ahc_construct_ppr(ahc, devinfo, period, offset,
tinfo->goal.width, ppr_options);
} else {
ahc_construct_sdtr(ahc, devinfo, period, offset);
}
} else {
ahc_construct_wdtr(ahc, devinfo, tinfo->goal.width);
}
}
/*
* Build a synchronous negotiation message in our message
* buffer based on the input parameters.
*/
static void
ahc_construct_sdtr(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
u_int period, u_int offset)
{
if (offset == 0)
period = AHC_ASYNC_XFER_PERIOD;
ahc->msgout_index += spi_populate_sync_msg(
ahc->msgout_buf + ahc->msgout_index, period, offset);
ahc->msgout_len += 5;
if (bootverbose) {
printf("(%s:%c:%d:%d): Sending SDTR period %x, offset %x\n",
ahc_name(ahc), devinfo->channel, devinfo->target,
devinfo->lun, period, offset);
}
}
/*
* Build a wide negotiation message in our message
* buffer based on the input parameters.
*/
static void
ahc_construct_wdtr(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
u_int bus_width)
{
ahc->msgout_index += spi_populate_width_msg(
ahc->msgout_buf + ahc->msgout_index, bus_width);
ahc->msgout_len += 4;
if (bootverbose) {
printf("(%s:%c:%d:%d): Sending WDTR %x\n",
ahc_name(ahc), devinfo->channel, devinfo->target,
devinfo->lun, bus_width);
}
}
/*
* Build a parallel protocol request message in our message
* buffer based on the input parameters.
*/
static void
ahc_construct_ppr(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
u_int period, u_int offset, u_int bus_width,
u_int ppr_options)
{
if (offset == 0)
period = AHC_ASYNC_XFER_PERIOD;
ahc->msgout_index += spi_populate_ppr_msg(
ahc->msgout_buf + ahc->msgout_index, period, offset,
bus_width, ppr_options);
ahc->msgout_len += 8;
if (bootverbose) {
printf("(%s:%c:%d:%d): Sending PPR bus_width %x, period %x, "
"offset %x, ppr_options %x\n", ahc_name(ahc),
devinfo->channel, devinfo->target, devinfo->lun,
bus_width, period, offset, ppr_options);
}
}
/*
* Clear any active message state.
*/
static void
ahc_clear_msg_state(struct ahc_softc *ahc)
{
ahc->msgout_len = 0;
ahc->msgin_index = 0;
ahc->msg_type = MSG_TYPE_NONE;
if ((ahc_inb(ahc, SCSISIGI) & ATNI) != 0) {
/*
* The target didn't care to respond to our
* message request, so clear ATN.
*/
ahc_outb(ahc, CLRSINT1, CLRATNO);
}
ahc_outb(ahc, MSG_OUT, MSG_NOOP);
ahc_outb(ahc, SEQ_FLAGS2,
ahc_inb(ahc, SEQ_FLAGS2) & ~TARGET_MSG_PENDING);
}
static void
ahc_handle_proto_violation(struct ahc_softc *ahc)
{
struct ahc_devinfo devinfo;
struct scb *scb;
u_int scbid;
u_int seq_flags;
u_int curphase;
u_int lastphase;
int found;
ahc_fetch_devinfo(ahc, &devinfo);
scbid = ahc_inb(ahc, SCB_TAG);
scb = ahc_lookup_scb(ahc, scbid);
seq_flags = ahc_inb(ahc, SEQ_FLAGS);
curphase = ahc_inb(ahc, SCSISIGI) & PHASE_MASK;
lastphase = ahc_inb(ahc, LASTPHASE);
if ((seq_flags & NOT_IDENTIFIED) != 0) {
/*
* The reconnecting target either did not send an
* identify message, or did, but we didn't find an SCB
* to match.
*/
ahc_print_devinfo(ahc, &devinfo);
printf("Target did not send an IDENTIFY message. "
"LASTPHASE = 0x%x.\n", lastphase);
scb = NULL;
} else if (scb == NULL) {
/*
* We don't seem to have an SCB active for this
* transaction. Print an error and reset the bus.
*/
ahc_print_devinfo(ahc, &devinfo);
printf("No SCB found during protocol violation\n");
goto proto_violation_reset;
} else {
ahc_set_transaction_status(scb, CAM_SEQUENCE_FAIL);
if ((seq_flags & NO_CDB_SENT) != 0) {
ahc_print_path(ahc, scb);
printf("No or incomplete CDB sent to device.\n");
} else if ((ahc_inb(ahc, SCB_CONTROL) & STATUS_RCVD) == 0) {
/*
* The target never bothered to provide status to
* us prior to completing the command. Since we don't
* know the disposition of this command, we must attempt
* to abort it. Assert ATN and prepare to send an abort
* message.
*/
ahc_print_path(ahc, scb);
printf("Completed command without status.\n");
} else {
ahc_print_path(ahc, scb);
printf("Unknown protocol violation.\n");
ahc_dump_card_state(ahc);
}
}
if ((lastphase & ~P_DATAIN_DT) == 0
|| lastphase == P_COMMAND) {
proto_violation_reset:
/*
* Target either went directly to data/command
* phase or didn't respond to our ATN.
* The only safe thing to do is to blow
* it away with a bus reset.
*/
found = ahc_reset_channel(ahc, 'A', TRUE);
printf("%s: Issued Channel %c Bus Reset. "
"%d SCBs aborted\n", ahc_name(ahc), 'A', found);
} else {
/*
* Leave the selection hardware off in case
* this abort attempt will affect yet to
* be sent commands.
*/
ahc_outb(ahc, SCSISEQ,
ahc_inb(ahc, SCSISEQ) & ~ENSELO);
ahc_assert_atn(ahc);
ahc_outb(ahc, MSG_OUT, HOST_MSG);
if (scb == NULL) {
ahc_print_devinfo(ahc, &devinfo);
ahc->msgout_buf[0] = MSG_ABORT_TASK;
ahc->msgout_len = 1;
ahc->msgout_index = 0;
ahc->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
} else {
ahc_print_path(ahc, scb);
scb->flags |= SCB_ABORT;
}
printf("Protocol violation %s. Attempting to abort.\n",
ahc_lookup_phase_entry(curphase)->phasemsg);
}
}
/*
* Manual message loop handler.
*/
static void
ahc_handle_message_phase(struct ahc_softc *ahc)
{
struct ahc_devinfo devinfo;
u_int bus_phase;
int end_session;
ahc_fetch_devinfo(ahc, &devinfo);
end_session = FALSE;
bus_phase = ahc_inb(ahc, SCSISIGI) & PHASE_MASK;
reswitch:
switch (ahc->msg_type) {
case MSG_TYPE_INITIATOR_MSGOUT:
{
int lastbyte;
int phasemis;
int msgdone;
if (ahc->msgout_len == 0)
panic("HOST_MSG_LOOP interrupt with no active message");
#ifdef AHC_DEBUG
if ((ahc_debug & AHC_SHOW_MESSAGES) != 0) {
ahc_print_devinfo(ahc, &devinfo);
printf("INITIATOR_MSG_OUT");
}
#endif
phasemis = bus_phase != P_MESGOUT;
if (phasemis) {
#ifdef AHC_DEBUG
if ((ahc_debug & AHC_SHOW_MESSAGES) != 0) {
printf(" PHASEMIS %s\n",
ahc_lookup_phase_entry(bus_phase)
->phasemsg);
}
#endif
if (bus_phase == P_MESGIN) {
/*
* Change gears and see if
* this messages is of interest to
* us or should be passed back to
* the sequencer.
*/
ahc_outb(ahc, CLRSINT1, CLRATNO);
ahc->send_msg_perror = FALSE;
ahc->msg_type = MSG_TYPE_INITIATOR_MSGIN;
ahc->msgin_index = 0;
goto reswitch;
}
end_session = TRUE;
break;
}
if (ahc->send_msg_perror) {
ahc_outb(ahc, CLRSINT1, CLRATNO);
ahc_outb(ahc, CLRSINT1, CLRREQINIT);
#ifdef AHC_DEBUG
if ((ahc_debug & AHC_SHOW_MESSAGES) != 0)
printf(" byte 0x%x\n", ahc->send_msg_perror);
#endif
ahc_outb(ahc, SCSIDATL, MSG_PARITY_ERROR);
break;
}
msgdone = ahc->msgout_index == ahc->msgout_len;
if (msgdone) {
/*
* The target has requested a retry.
* Re-assert ATN, reset our message index to
* 0, and try again.
*/
ahc->msgout_index = 0;
ahc_assert_atn(ahc);
}
lastbyte = ahc->msgout_index == (ahc->msgout_len - 1);
if (lastbyte) {
/* Last byte is signified by dropping ATN */
ahc_outb(ahc, CLRSINT1, CLRATNO);
}
/*
* Clear our interrupt status and present
* the next byte on the bus.
*/
ahc_outb(ahc, CLRSINT1, CLRREQINIT);
#ifdef AHC_DEBUG
if ((ahc_debug & AHC_SHOW_MESSAGES) != 0)
printf(" byte 0x%x\n",
ahc->msgout_buf[ahc->msgout_index]);
#endif
ahc_outb(ahc, SCSIDATL, ahc->msgout_buf[ahc->msgout_index++]);
break;
}
case MSG_TYPE_INITIATOR_MSGIN:
{
int phasemis;
int message_done;
#ifdef AHC_DEBUG
if ((ahc_debug & AHC_SHOW_MESSAGES) != 0) {
ahc_print_devinfo(ahc, &devinfo);
printf("INITIATOR_MSG_IN");
}
#endif
phasemis = bus_phase != P_MESGIN;
if (phasemis) {
#ifdef AHC_DEBUG
if ((ahc_debug & AHC_SHOW_MESSAGES) != 0) {
printf(" PHASEMIS %s\n",
ahc_lookup_phase_entry(bus_phase)
->phasemsg);
}
#endif
ahc->msgin_index = 0;
if (bus_phase == P_MESGOUT
&& (ahc->send_msg_perror == TRUE
|| (ahc->msgout_len != 0
&& ahc->msgout_index == 0))) {
ahc->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
goto reswitch;
}
end_session = TRUE;
break;
}
/* Pull the byte in without acking it */
ahc->msgin_buf[ahc->msgin_index] = ahc_inb(ahc, SCSIBUSL);
#ifdef AHC_DEBUG
if ((ahc_debug & AHC_SHOW_MESSAGES) != 0)
printf(" byte 0x%x\n",
ahc->msgin_buf[ahc->msgin_index]);
#endif
message_done = ahc_parse_msg(ahc, &devinfo);
if (message_done) {
/*
* Clear our incoming message buffer in case there
* is another message following this one.
*/
ahc->msgin_index = 0;
/*
* If this message illicited a response,
* assert ATN so the target takes us to the
* message out phase.
*/
if (ahc->msgout_len != 0) {
#ifdef AHC_DEBUG
if ((ahc_debug & AHC_SHOW_MESSAGES) != 0) {
ahc_print_devinfo(ahc, &devinfo);
printf("Asserting ATN for response\n");
}
#endif
ahc_assert_atn(ahc);
}
} else
ahc->msgin_index++;
if (message_done == MSGLOOP_TERMINATED) {
end_session = TRUE;
} else {
/* Ack the byte */
ahc_outb(ahc, CLRSINT1, CLRREQINIT);
ahc_inb(ahc, SCSIDATL);
}
break;
}
case MSG_TYPE_TARGET_MSGIN:
{
int msgdone;
int msgout_request;
if (ahc->msgout_len == 0)
panic("Target MSGIN with no active message");
/*
* If we interrupted a mesgout session, the initiator
* will not know this until our first REQ. So, we
* only honor mesgout requests after we've sent our
* first byte.
*/
if ((ahc_inb(ahc, SCSISIGI) & ATNI) != 0
&& ahc->msgout_index > 0)
msgout_request = TRUE;
else
msgout_request = FALSE;
if (msgout_request) {
/*
* Change gears and see if
* this messages is of interest to
* us or should be passed back to
* the sequencer.
*/
ahc->msg_type = MSG_TYPE_TARGET_MSGOUT;
ahc_outb(ahc, SCSISIGO, P_MESGOUT | BSYO);
ahc->msgin_index = 0;
/* Dummy read to REQ for first byte */
ahc_inb(ahc, SCSIDATL);
ahc_outb(ahc, SXFRCTL0,
ahc_inb(ahc, SXFRCTL0) | SPIOEN);
break;
}
msgdone = ahc->msgout_index == ahc->msgout_len;
if (msgdone) {
ahc_outb(ahc, SXFRCTL0,
ahc_inb(ahc, SXFRCTL0) & ~SPIOEN);
end_session = TRUE;
break;
}
/*
* Present the next byte on the bus.
*/
ahc_outb(ahc, SXFRCTL0, ahc_inb(ahc, SXFRCTL0) | SPIOEN);
ahc_outb(ahc, SCSIDATL, ahc->msgout_buf[ahc->msgout_index++]);
break;
}
case MSG_TYPE_TARGET_MSGOUT:
{
int lastbyte;
int msgdone;
/*
* The initiator signals that this is
* the last byte by dropping ATN.
*/
lastbyte = (ahc_inb(ahc, SCSISIGI) & ATNI) == 0;
/*
* Read the latched byte, but turn off SPIOEN first
* so that we don't inadvertently cause a REQ for the
* next byte.
*/
ahc_outb(ahc, SXFRCTL0, ahc_inb(ahc, SXFRCTL0) & ~SPIOEN);
ahc->msgin_buf[ahc->msgin_index] = ahc_inb(ahc, SCSIDATL);
msgdone = ahc_parse_msg(ahc, &devinfo);
if (msgdone == MSGLOOP_TERMINATED) {
/*
* The message is *really* done in that it caused
* us to go to bus free. The sequencer has already
* been reset at this point, so pull the ejection
* handle.
*/
return;
}
ahc->msgin_index++;
/*
* XXX Read spec about initiator dropping ATN too soon
* and use msgdone to detect it.
*/
if (msgdone == MSGLOOP_MSGCOMPLETE) {
ahc->msgin_index = 0;
/*
* If this message illicited a response, transition
* to the Message in phase and send it.
*/
if (ahc->msgout_len != 0) {
ahc_outb(ahc, SCSISIGO, P_MESGIN | BSYO);
ahc_outb(ahc, SXFRCTL0,
ahc_inb(ahc, SXFRCTL0) | SPIOEN);
ahc->msg_type = MSG_TYPE_TARGET_MSGIN;
ahc->msgin_index = 0;
break;
}
}
if (lastbyte)
end_session = TRUE;
else {
/* Ask for the next byte. */
ahc_outb(ahc, SXFRCTL0,
ahc_inb(ahc, SXFRCTL0) | SPIOEN);
}
break;
}
default:
panic("Unknown REQINIT message type");
}
if (end_session) {
ahc_clear_msg_state(ahc);
ahc_outb(ahc, RETURN_1, EXIT_MSG_LOOP);
} else
ahc_outb(ahc, RETURN_1, CONT_MSG_LOOP);
}
/*
* See if we sent a particular extended message to the target.
* If "full" is true, return true only if the target saw the full
* message. If "full" is false, return true if the target saw at
* least the first byte of the message.
*/
static int
ahc_sent_msg(struct ahc_softc *ahc, ahc_msgtype type, u_int msgval, int full)
{
int found;
u_int index;
found = FALSE;
index = 0;
while (index < ahc->msgout_len) {
if (ahc->msgout_buf[index] == MSG_EXTENDED) {
u_int end_index;
end_index = index + 1 + ahc->msgout_buf[index + 1];
if (ahc->msgout_buf[index+2] == msgval
&& type == AHCMSG_EXT) {
if (full) {
if (ahc->msgout_index > end_index)
found = TRUE;
} else if (ahc->msgout_index > index)
found = TRUE;
}
index = end_index;
} else if (ahc->msgout_buf[index] >= MSG_SIMPLE_TASK
&& ahc->msgout_buf[index] <= MSG_IGN_WIDE_RESIDUE) {
/* Skip tag type and tag id or residue param*/
index += 2;
} else {
/* Single byte message */
if (type == AHCMSG_1B
&& ahc->msgout_buf[index] == msgval
&& ahc->msgout_index > index)
found = TRUE;
index++;
}
if (found)
break;
}
return (found);
}
/*
* Wait for a complete incoming message, parse it, and respond accordingly.
*/
static int
ahc_parse_msg(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
{
struct ahc_initiator_tinfo *tinfo;
struct ahc_tmode_tstate *tstate;
int reject;
int done;
int response;
u_int targ_scsirate;
done = MSGLOOP_IN_PROG;
response = FALSE;
reject = FALSE;
tinfo = ahc_fetch_transinfo(ahc, devinfo->channel, devinfo->our_scsiid,
devinfo->target, &tstate);
targ_scsirate = tinfo->scsirate;
/*
* Parse as much of the message as is available,
* rejecting it if we don't support it. When
* the entire message is available and has been
* handled, return MSGLOOP_MSGCOMPLETE, indicating
* that we have parsed an entire message.
*
* In the case of extended messages, we accept the length
* byte outright and perform more checking once we know the
* extended message type.
*/
switch (ahc->msgin_buf[0]) {
case MSG_DISCONNECT:
case MSG_SAVEDATAPOINTER:
case MSG_CMDCOMPLETE:
case MSG_RESTOREPOINTERS:
case MSG_IGN_WIDE_RESIDUE:
/*
* End our message loop as these are messages
* the sequencer handles on its own.
*/
done = MSGLOOP_TERMINATED;
break;
case MSG_MESSAGE_REJECT:
response = ahc_handle_msg_reject(ahc, devinfo);
/* FALLTHROUGH */
case MSG_NOOP:
done = MSGLOOP_MSGCOMPLETE;
break;
case MSG_EXTENDED:
{
/* Wait for enough of the message to begin validation */
if (ahc->msgin_index < 2)
break;
switch (ahc->msgin_buf[2]) {
case MSG_EXT_SDTR:
{
const struct ahc_syncrate *syncrate;
u_int period;
u_int ppr_options;
u_int offset;
u_int saved_offset;
if (ahc->msgin_buf[1] != MSG_EXT_SDTR_LEN) {
reject = TRUE;
break;
}
/*
* Wait until we have both args before validating
* and acting on this message.
*
* Add one to MSG_EXT_SDTR_LEN to account for
* the extended message preamble.
*/
if (ahc->msgin_index < (MSG_EXT_SDTR_LEN + 1))
break;
period = ahc->msgin_buf[3];
ppr_options = 0;
saved_offset = offset = ahc->msgin_buf[4];
syncrate = ahc_devlimited_syncrate(ahc, tinfo, &period,
&ppr_options,
devinfo->role);
ahc_validate_offset(ahc, tinfo, syncrate, &offset,
targ_scsirate & WIDEXFER,
devinfo->role);
if (bootverbose) {
printf("(%s:%c:%d:%d): Received "
"SDTR period %x, offset %x\n\t"
"Filtered to period %x, offset %x\n",
ahc_name(ahc), devinfo->channel,
devinfo->target, devinfo->lun,
ahc->msgin_buf[3], saved_offset,
period, offset);
}
ahc_set_syncrate(ahc, devinfo,
syncrate, period,
offset, ppr_options,
AHC_TRANS_ACTIVE|AHC_TRANS_GOAL,
/*paused*/TRUE);
/*
* See if we initiated Sync Negotiation
* and didn't have to fall down to async
* transfers.
*/
if (ahc_sent_msg(ahc, AHCMSG_EXT, MSG_EXT_SDTR, TRUE)) {
/* We started it */
if (saved_offset != offset) {
/* Went too low - force async */
reject = TRUE;
}
} else {
/*
* Send our own SDTR in reply
*/
if (bootverbose
&& devinfo->role == ROLE_INITIATOR) {
printf("(%s:%c:%d:%d): Target "
"Initiated SDTR\n",
ahc_name(ahc), devinfo->channel,
devinfo->target, devinfo->lun);
}
ahc->msgout_index = 0;
ahc->msgout_len = 0;
ahc_construct_sdtr(ahc, devinfo,
period, offset);
ahc->msgout_index = 0;
response = TRUE;
}
done = MSGLOOP_MSGCOMPLETE;
break;
}
case MSG_EXT_WDTR:
{
u_int bus_width;
u_int saved_width;
u_int sending_reply;
sending_reply = FALSE;
if (ahc->msgin_buf[1] != MSG_EXT_WDTR_LEN) {
reject = TRUE;
break;
}
/*
* Wait until we have our arg before validating
* and acting on this message.
*
* Add one to MSG_EXT_WDTR_LEN to account for
* the extended message preamble.
*/
if (ahc->msgin_index < (MSG_EXT_WDTR_LEN + 1))
break;
bus_width = ahc->msgin_buf[3];
saved_width = bus_width;
ahc_validate_width(ahc, tinfo, &bus_width,
devinfo->role);
if (bootverbose) {
printf("(%s:%c:%d:%d): Received WDTR "
"%x filtered to %x\n",
ahc_name(ahc), devinfo->channel,
devinfo->target, devinfo->lun,
saved_width, bus_width);
}
if (ahc_sent_msg(ahc, AHCMSG_EXT, MSG_EXT_WDTR, TRUE)) {
/*
* Don't send a WDTR back to the
* target, since we asked first.
* If the width went higher than our
* request, reject it.
*/
if (saved_width > bus_width) {
reject = TRUE;
printf("(%s:%c:%d:%d): requested %dBit "
"transfers. Rejecting...\n",
ahc_name(ahc), devinfo->channel,
devinfo->target, devinfo->lun,
8 * (0x01 << bus_width));
bus_width = 0;
}
} else {
/*
* Send our own WDTR in reply
*/
if (bootverbose
&& devinfo->role == ROLE_INITIATOR) {
printf("(%s:%c:%d:%d): Target "
"Initiated WDTR\n",
ahc_name(ahc), devinfo->channel,
devinfo->target, devinfo->lun);
}
ahc->msgout_index = 0;
ahc->msgout_len = 0;
ahc_construct_wdtr(ahc, devinfo, bus_width);
ahc->msgout_index = 0;
response = TRUE;
sending_reply = TRUE;
}
/*
* After a wide message, we are async, but
* some devices don't seem to honor this portion
* of the spec. Force a renegotiation of the
* sync component of our transfer agreement even
* if our goal is async. By updating our width
* after forcing the negotiation, we avoid
* renegotiating for width.
*/
ahc_update_neg_request(ahc, devinfo, tstate,
tinfo, AHC_NEG_ALWAYS);
ahc_set_width(ahc, devinfo, bus_width,
AHC_TRANS_ACTIVE|AHC_TRANS_GOAL,
/*paused*/TRUE);
if (sending_reply == FALSE && reject == FALSE) {
/*
* We will always have an SDTR to send.
*/
ahc->msgout_index = 0;
ahc->msgout_len = 0;
ahc_build_transfer_msg(ahc, devinfo);
ahc->msgout_index = 0;
response = TRUE;
}
done = MSGLOOP_MSGCOMPLETE;
break;
}
case MSG_EXT_PPR:
{
const struct ahc_syncrate *syncrate;
u_int period;
u_int offset;
u_int bus_width;
u_int ppr_options;
u_int saved_width;
u_int saved_offset;
u_int saved_ppr_options;
if (ahc->msgin_buf[1] != MSG_EXT_PPR_LEN) {
reject = TRUE;
break;
}
/*
* Wait until we have all args before validating
* and acting on this message.
*
* Add one to MSG_EXT_PPR_LEN to account for
* the extended message preamble.
*/
if (ahc->msgin_index < (MSG_EXT_PPR_LEN + 1))
break;
period = ahc->msgin_buf[3];
offset = ahc->msgin_buf[5];
bus_width = ahc->msgin_buf[6];
saved_width = bus_width;
ppr_options = ahc->msgin_buf[7];
/*
* According to the spec, a DT only
* period factor with no DT option
* set implies async.
*/
if ((ppr_options & MSG_EXT_PPR_DT_REQ) == 0
&& period == 9)
offset = 0;
saved_ppr_options = ppr_options;
saved_offset = offset;
/*
* Mask out any options we don't support
* on any controller. Transfer options are
* only available if we are negotiating wide.
*/
ppr_options &= MSG_EXT_PPR_DT_REQ;
if (bus_width == 0)
ppr_options = 0;
ahc_validate_width(ahc, tinfo, &bus_width,
devinfo->role);
syncrate = ahc_devlimited_syncrate(ahc, tinfo, &period,
&ppr_options,
devinfo->role);
ahc_validate_offset(ahc, tinfo, syncrate,
&offset, bus_width,
devinfo->role);
if (ahc_sent_msg(ahc, AHCMSG_EXT, MSG_EXT_PPR, TRUE)) {
/*
* If we are unable to do any of the
* requested options (we went too low),
* then we'll have to reject the message.
*/
if (saved_width > bus_width
|| saved_offset != offset
|| saved_ppr_options != ppr_options) {
reject = TRUE;
period = 0;
offset = 0;
bus_width = 0;
ppr_options = 0;
syncrate = NULL;
}
} else {
if (devinfo->role != ROLE_TARGET)
printf("(%s:%c:%d:%d): Target "
"Initiated PPR\n",
ahc_name(ahc), devinfo->channel,
devinfo->target, devinfo->lun);
else
printf("(%s:%c:%d:%d): Initiator "
"Initiated PPR\n",
ahc_name(ahc), devinfo->channel,
devinfo->target, devinfo->lun);
ahc->msgout_index = 0;
ahc->msgout_len = 0;
ahc_construct_ppr(ahc, devinfo, period, offset,
bus_width, ppr_options);
ahc->msgout_index = 0;
response = TRUE;
}
if (bootverbose) {
printf("(%s:%c:%d:%d): Received PPR width %x, "
"period %x, offset %x,options %x\n"
"\tFiltered to width %x, period %x, "
"offset %x, options %x\n",
ahc_name(ahc), devinfo->channel,
devinfo->target, devinfo->lun,
saved_width, ahc->msgin_buf[3],
saved_offset, saved_ppr_options,
bus_width, period, offset, ppr_options);
}
ahc_set_width(ahc, devinfo, bus_width,
AHC_TRANS_ACTIVE|AHC_TRANS_GOAL,
/*paused*/TRUE);
ahc_set_syncrate(ahc, devinfo,
syncrate, period,
offset, ppr_options,
AHC_TRANS_ACTIVE|AHC_TRANS_GOAL,
/*paused*/TRUE);
done = MSGLOOP_MSGCOMPLETE;
break;
}
default:
/* Unknown extended message. Reject it. */
reject = TRUE;
break;
}
break;
}
#ifdef AHC_TARGET_MODE
case MSG_BUS_DEV_RESET:
ahc_handle_devreset(ahc, devinfo,
CAM_BDR_SENT,
"Bus Device Reset Received",
/*verbose_level*/0);
ahc_restart(ahc);
done = MSGLOOP_TERMINATED;
break;
case MSG_ABORT_TAG:
case MSG_ABORT:
case MSG_CLEAR_QUEUE:
{
int tag;
/* Target mode messages */
if (devinfo->role != ROLE_TARGET) {
reject = TRUE;
break;
}
tag = SCB_LIST_NULL;
if (ahc->msgin_buf[0] == MSG_ABORT_TAG)
tag = ahc_inb(ahc, INITIATOR_TAG);
ahc_abort_scbs(ahc, devinfo->target, devinfo->channel,
devinfo->lun, tag, ROLE_TARGET,
CAM_REQ_ABORTED);
tstate = ahc->enabled_targets[devinfo->our_scsiid];
if (tstate != NULL) {
struct ahc_tmode_lstate* lstate;
lstate = tstate->enabled_luns[devinfo->lun];
if (lstate != NULL) {
ahc_queue_lstate_event(ahc, lstate,
devinfo->our_scsiid,
ahc->msgin_buf[0],
/*arg*/tag);
ahc_send_lstate_events(ahc, lstate);
}
}
ahc_restart(ahc);
done = MSGLOOP_TERMINATED;
break;
}
#endif
case MSG_TERM_IO_PROC:
default:
reject = TRUE;
break;
}
if (reject) {
/*
* Setup to reject the message.
*/
ahc->msgout_index = 0;
ahc->msgout_len = 1;
ahc->msgout_buf[0] = MSG_MESSAGE_REJECT;
done = MSGLOOP_MSGCOMPLETE;
response = TRUE;
}
if (done != MSGLOOP_IN_PROG && !response)
/* Clear the outgoing message buffer */
ahc->msgout_len = 0;
return (done);
}
/*
* Process a message reject message.
*/
static int
ahc_handle_msg_reject(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
{
/*
* What we care about here is if we had an
* outstanding SDTR or WDTR message for this
* target. If we did, this is a signal that
* the target is refusing negotiation.
*/
struct scb *scb;
struct ahc_initiator_tinfo *tinfo;
struct ahc_tmode_tstate *tstate;
u_int scb_index;
u_int last_msg;
int response = 0;
scb_index = ahc_inb(ahc, SCB_TAG);
scb = ahc_lookup_scb(ahc, scb_index);
tinfo = ahc_fetch_transinfo(ahc, devinfo->channel,
devinfo->our_scsiid,
devinfo->target, &tstate);
/* Might be necessary */
last_msg = ahc_inb(ahc, LAST_MSG);
if (ahc_sent_msg(ahc, AHCMSG_EXT, MSG_EXT_PPR, /*full*/FALSE)) {
/*
* Target does not support the PPR message.
* Attempt to negotiate SPI-2 style.
*/
if (bootverbose) {
printf("(%s:%c:%d:%d): PPR Rejected. "
"Trying WDTR/SDTR\n",
ahc_name(ahc), devinfo->channel,
devinfo->target, devinfo->lun);
}
tinfo->goal.ppr_options = 0;
tinfo->curr.transport_version = 2;
tinfo->goal.transport_version = 2;
ahc->msgout_index = 0;
ahc->msgout_len = 0;
ahc_build_transfer_msg(ahc, devinfo);
ahc->msgout_index = 0;
response = 1;
} else if (ahc_sent_msg(ahc, AHCMSG_EXT, MSG_EXT_WDTR, /*full*/FALSE)) {
/* note 8bit xfers */
printf("(%s:%c:%d:%d): refuses WIDE negotiation. Using "
"8bit transfers\n", ahc_name(ahc),
devinfo->channel, devinfo->target, devinfo->lun);
ahc_set_width(ahc, devinfo, MSG_EXT_WDTR_BUS_8_BIT,
AHC_TRANS_ACTIVE|AHC_TRANS_GOAL,
/*paused*/TRUE);
/*
* No need to clear the sync rate. If the target
* did not accept the command, our syncrate is
* unaffected. If the target started the negotiation,
* but rejected our response, we already cleared the
* sync rate before sending our WDTR.
*/
if (tinfo->goal.offset != tinfo->curr.offset) {
/* Start the sync negotiation */
ahc->msgout_index = 0;
ahc->msgout_len = 0;
ahc_build_transfer_msg(ahc, devinfo);
ahc->msgout_index = 0;
response = 1;
}
} else if (ahc_sent_msg(ahc, AHCMSG_EXT, MSG_EXT_SDTR, /*full*/FALSE)) {
/* note asynch xfers and clear flag */
ahc_set_syncrate(ahc, devinfo, /*syncrate*/NULL, /*period*/0,
/*offset*/0, /*ppr_options*/0,
AHC_TRANS_ACTIVE|AHC_TRANS_GOAL,
/*paused*/TRUE);
printf("(%s:%c:%d:%d): refuses synchronous negotiation. "
"Using asynchronous transfers\n",
ahc_name(ahc), devinfo->channel,
devinfo->target, devinfo->lun);
} else if ((scb->hscb->control & MSG_SIMPLE_TASK) != 0) {
int tag_type;
int mask;
tag_type = (scb->hscb->control & MSG_SIMPLE_TASK);
if (tag_type == MSG_SIMPLE_TASK) {
printf("(%s:%c:%d:%d): refuses tagged commands. "
"Performing non-tagged I/O\n", ahc_name(ahc),
devinfo->channel, devinfo->target, devinfo->lun);
ahc_set_tags(ahc, scb->io_ctx, devinfo, AHC_QUEUE_NONE);
mask = ~0x23;
} else {
printf("(%s:%c:%d:%d): refuses %s tagged commands. "
"Performing simple queue tagged I/O only\n",
ahc_name(ahc), devinfo->channel, devinfo->target,
devinfo->lun, tag_type == MSG_ORDERED_TASK
? "ordered" : "head of queue");
ahc_set_tags(ahc, scb->io_ctx, devinfo, AHC_QUEUE_BASIC);
mask = ~0x03;
}
/*
* Resend the identify for this CCB as the target
* may believe that the selection is invalid otherwise.
*/
ahc_outb(ahc, SCB_CONTROL,
ahc_inb(ahc, SCB_CONTROL) & mask);
scb->hscb->control &= mask;
ahc_set_transaction_tag(scb, /*enabled*/FALSE,
/*type*/MSG_SIMPLE_TASK);
ahc_outb(ahc, MSG_OUT, MSG_IDENTIFYFLAG);
ahc_assert_atn(ahc);
/*
* This transaction is now at the head of
* the untagged queue for this target.
*/
if ((ahc->flags & AHC_SCB_BTT) == 0) {
struct scb_tailq *untagged_q;
untagged_q =
&(ahc->untagged_queues[devinfo->target_offset]);
TAILQ_INSERT_HEAD(untagged_q, scb, links.tqe);
scb->flags |= SCB_UNTAGGEDQ;
}
ahc_busy_tcl(ahc, BUILD_TCL(scb->hscb->scsiid, devinfo->lun),
scb->hscb->tag);
/*
* Requeue all tagged commands for this target
* currently in our posession so they can be
* converted to untagged commands.
*/
ahc_search_qinfifo(ahc, SCB_GET_TARGET(ahc, scb),
SCB_GET_CHANNEL(ahc, scb),
SCB_GET_LUN(scb), /*tag*/SCB_LIST_NULL,
ROLE_INITIATOR, CAM_REQUEUE_REQ,
SEARCH_COMPLETE);
} else {
/*
* Otherwise, we ignore it.
*/
printf("%s:%c:%d: Message reject for %x -- ignored\n",
ahc_name(ahc), devinfo->channel, devinfo->target,
last_msg);
}
return (response);
}
/*
* Process an ingnore wide residue message.
*/
static void
ahc_handle_ign_wide_residue(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
{
u_int scb_index;
struct scb *scb;
scb_index = ahc_inb(ahc, SCB_TAG);
scb = ahc_lookup_scb(ahc, scb_index);
/*
* XXX Actually check data direction in the sequencer?
* Perhaps add datadir to some spare bits in the hscb?
*/
if ((ahc_inb(ahc, SEQ_FLAGS) & DPHASE) == 0
|| ahc_get_transfer_dir(scb) != CAM_DIR_IN) {
/*
* Ignore the message if we haven't
* seen an appropriate data phase yet.
*/
} else {
/*
* If the residual occurred on the last
* transfer and the transfer request was
* expected to end on an odd count, do
* nothing. Otherwise, subtract a byte
* and update the residual count accordingly.
*/
uint32_t sgptr;
sgptr = ahc_inb(ahc, SCB_RESIDUAL_SGPTR);
if ((sgptr & SG_LIST_NULL) != 0
&& (ahc_inb(ahc, SCB_LUN) & SCB_XFERLEN_ODD) != 0) {
/*
* If the residual occurred on the last
* transfer and the transfer request was
* expected to end on an odd count, do
* nothing.
*/
} else {
struct ahc_dma_seg *sg;
uint32_t data_cnt;
uint32_t data_addr;
uint32_t sglen;
/* Pull in all of the sgptr */
sgptr = ahc_inl(ahc, SCB_RESIDUAL_SGPTR);
data_cnt = ahc_inl(ahc, SCB_RESIDUAL_DATACNT);
if ((sgptr & SG_LIST_NULL) != 0) {
/*
* The residual data count is not updated
* for the command run to completion case.
* Explicitly zero the count.
*/
data_cnt &= ~AHC_SG_LEN_MASK;
}
data_addr = ahc_inl(ahc, SHADDR);
data_cnt += 1;
data_addr -= 1;
sgptr &= SG_PTR_MASK;
sg = ahc_sg_bus_to_virt(scb, sgptr);
/*
* The residual sg ptr points to the next S/G
* to load so we must go back one.
*/
sg--;
sglen = ahc_le32toh(sg->len) & AHC_SG_LEN_MASK;
if (sg != scb->sg_list
&& sglen < (data_cnt & AHC_SG_LEN_MASK)) {
sg--;
sglen = ahc_le32toh(sg->len);
/*
* Preserve High Address and SG_LIST bits
* while setting the count to 1.
*/
data_cnt = 1 | (sglen & (~AHC_SG_LEN_MASK));
data_addr = ahc_le32toh(sg->addr)
+ (sglen & AHC_SG_LEN_MASK) - 1;
/*
* Increment sg so it points to the
* "next" sg.
*/
sg++;
sgptr = ahc_sg_virt_to_bus(scb, sg);
}
ahc_outl(ahc, SCB_RESIDUAL_SGPTR, sgptr);
ahc_outl(ahc, SCB_RESIDUAL_DATACNT, data_cnt);
/*
* Toggle the "oddness" of the transfer length
* to handle this mid-transfer ignore wide
* residue. This ensures that the oddness is
* correct for subsequent data transfers.
*/
ahc_outb(ahc, SCB_LUN,
ahc_inb(ahc, SCB_LUN) ^ SCB_XFERLEN_ODD);
}
}
}
/*
* Reinitialize the data pointers for the active transfer
* based on its current residual.
*/
static void
ahc_reinitialize_dataptrs(struct ahc_softc *ahc)
{
struct scb *scb;
struct ahc_dma_seg *sg;
u_int scb_index;
uint32_t sgptr;
uint32_t resid;
uint32_t dataptr;
scb_index = ahc_inb(ahc, SCB_TAG);
scb = ahc_lookup_scb(ahc, scb_index);
sgptr = (ahc_inb(ahc, SCB_RESIDUAL_SGPTR + 3) << 24)
| (ahc_inb(ahc, SCB_RESIDUAL_SGPTR + 2) << 16)
| (ahc_inb(ahc, SCB_RESIDUAL_SGPTR + 1) << 8)
| ahc_inb(ahc, SCB_RESIDUAL_SGPTR);
sgptr &= SG_PTR_MASK;
sg = ahc_sg_bus_to_virt(scb, sgptr);
/* The residual sg_ptr always points to the next sg */
sg--;
resid = (ahc_inb(ahc, SCB_RESIDUAL_DATACNT + 2) << 16)
| (ahc_inb(ahc, SCB_RESIDUAL_DATACNT + 1) << 8)
| ahc_inb(ahc, SCB_RESIDUAL_DATACNT);
dataptr = ahc_le32toh(sg->addr)
+ (ahc_le32toh(sg->len) & AHC_SG_LEN_MASK)
- resid;
if ((ahc->flags & AHC_39BIT_ADDRESSING) != 0) {
u_int dscommand1;
dscommand1 = ahc_inb(ahc, DSCOMMAND1);
ahc_outb(ahc, DSCOMMAND1, dscommand1 | HADDLDSEL0);
ahc_outb(ahc, HADDR,
(ahc_le32toh(sg->len) >> 24) & SG_HIGH_ADDR_BITS);
ahc_outb(ahc, DSCOMMAND1, dscommand1);
}
ahc_outb(ahc, HADDR + 3, dataptr >> 24);
ahc_outb(ahc, HADDR + 2, dataptr >> 16);
ahc_outb(ahc, HADDR + 1, dataptr >> 8);
ahc_outb(ahc, HADDR, dataptr);
ahc_outb(ahc, HCNT + 2, resid >> 16);
ahc_outb(ahc, HCNT + 1, resid >> 8);
ahc_outb(ahc, HCNT, resid);
if ((ahc->features & AHC_ULTRA2) == 0) {
ahc_outb(ahc, STCNT + 2, resid >> 16);
ahc_outb(ahc, STCNT + 1, resid >> 8);
ahc_outb(ahc, STCNT, resid);
}
}
/*
* Handle the effects of issuing a bus device reset message.
*/
static void
ahc_handle_devreset(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
cam_status status, char *message, int verbose_level)
{
#ifdef AHC_TARGET_MODE
struct ahc_tmode_tstate* tstate;
u_int lun;
#endif
int found;
found = ahc_abort_scbs(ahc, devinfo->target, devinfo->channel,
CAM_LUN_WILDCARD, SCB_LIST_NULL, devinfo->role,
status);
#ifdef AHC_TARGET_MODE
/*
* Send an immediate notify ccb to all target mord peripheral
* drivers affected by this action.
*/
tstate = ahc->enabled_targets[devinfo->our_scsiid];
if (tstate != NULL) {
for (lun = 0; lun < AHC_NUM_LUNS; lun++) {
struct ahc_tmode_lstate* lstate;
lstate = tstate->enabled_luns[lun];
if (lstate == NULL)
continue;
ahc_queue_lstate_event(ahc, lstate, devinfo->our_scsiid,
MSG_BUS_DEV_RESET, /*arg*/0);
ahc_send_lstate_events(ahc, lstate);
}
}
#endif
/*
* Go back to async/narrow transfers and renegotiate.
*/
ahc_set_width(ahc, devinfo, MSG_EXT_WDTR_BUS_8_BIT,
AHC_TRANS_CUR, /*paused*/TRUE);
ahc_set_syncrate(ahc, devinfo, /*syncrate*/NULL,
/*period*/0, /*offset*/0, /*ppr_options*/0,
AHC_TRANS_CUR, /*paused*/TRUE);
if (status != CAM_SEL_TIMEOUT)
ahc_send_async(ahc, devinfo->channel, devinfo->target,
CAM_LUN_WILDCARD, AC_SENT_BDR);
if (message != NULL
&& (verbose_level <= bootverbose))
printf("%s: %s on %c:%d. %d SCBs aborted\n", ahc_name(ahc),
message, devinfo->channel, devinfo->target, found);
}
#ifdef AHC_TARGET_MODE
static void
ahc_setup_target_msgin(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
struct scb *scb)
{
/*
* To facilitate adding multiple messages together,
* each routine should increment the index and len
* variables instead of setting them explicitly.
*/
ahc->msgout_index = 0;
ahc->msgout_len = 0;
if (scb != NULL && (scb->flags & SCB_AUTO_NEGOTIATE) != 0)
ahc_build_transfer_msg(ahc, devinfo);
else
panic("ahc_intr: AWAITING target message with no message");
ahc->msgout_index = 0;
ahc->msg_type = MSG_TYPE_TARGET_MSGIN;
}
#endif
/**************************** Initialization **********************************/
/*
* Allocate a controller structure for a new device
* and perform initial initializion.
*/
struct ahc_softc *
ahc_alloc(void *platform_arg, char *name)
{
struct ahc_softc *ahc;
int i;
#ifndef __FreeBSD__
ahc = malloc(sizeof(*ahc), M_DEVBUF, M_NOWAIT);
if (!ahc) {
printf("aic7xxx: cannot malloc softc!\n");
free(name, M_DEVBUF);
return NULL;
}
#else
ahc = device_get_softc((device_t)platform_arg);
#endif
memset(ahc, 0, sizeof(*ahc));
ahc->seep_config = malloc(sizeof(*ahc->seep_config),
M_DEVBUF, M_NOWAIT);
if (ahc->seep_config == NULL) {
#ifndef __FreeBSD__
free(ahc, M_DEVBUF);
#endif
free(name, M_DEVBUF);
return (NULL);
}
LIST_INIT(&ahc->pending_scbs);
/* We don't know our unit number until the OSM sets it */
ahc->name = name;
ahc->unit = -1;
ahc->description = NULL;
ahc->channel = 'A';
ahc->channel_b = 'B';
ahc->chip = AHC_NONE;
ahc->features = AHC_FENONE;
ahc->bugs = AHC_BUGNONE;
ahc->flags = AHC_FNONE;
/*
* Default to all error reporting enabled with the
* sequencer operating at its fastest speed.
* The bus attach code may modify this.
*/
ahc->seqctl = FASTMODE;
for (i = 0; i < AHC_NUM_TARGETS; i++)
TAILQ_INIT(&ahc->untagged_queues[i]);
if (ahc_platform_alloc(ahc, platform_arg) != 0) {
ahc_free(ahc);
ahc = NULL;
}
return (ahc);
}
int
ahc_softc_init(struct ahc_softc *ahc)
{
/* The IRQMS bit is only valid on VL and EISA chips */
if ((ahc->chip & AHC_PCI) == 0)
ahc->unpause = ahc_inb(ahc, HCNTRL) & IRQMS;
else
ahc->unpause = 0;
ahc->pause = ahc->unpause | PAUSE;
/* XXX The shared scb data stuff should be deprecated */
if (ahc->scb_data == NULL) {
ahc->scb_data = malloc(sizeof(*ahc->scb_data),
M_DEVBUF, M_NOWAIT);
if (ahc->scb_data == NULL)
return (ENOMEM);
memset(ahc->scb_data, 0, sizeof(*ahc->scb_data));
}
return (0);
}
void
ahc_set_unit(struct ahc_softc *ahc, int unit)
{
ahc->unit = unit;
}
void
ahc_set_name(struct ahc_softc *ahc, char *name)
{
if (ahc->name != NULL)
free(ahc->name, M_DEVBUF);
ahc->name = name;
}
void
ahc_free(struct ahc_softc *ahc)
{
int i;
switch (ahc->init_level) {
default:
case 5:
ahc_shutdown(ahc);
/* FALLTHROUGH */
case 4:
ahc_dmamap_unload(ahc, ahc->shared_data_dmat,
ahc->shared_data_dmamap);
/* FALLTHROUGH */
case 3:
ahc_dmamem_free(ahc, ahc->shared_data_dmat, ahc->qoutfifo,
ahc->shared_data_dmamap);
ahc_dmamap_destroy(ahc, ahc->shared_data_dmat,
ahc->shared_data_dmamap);
/* FALLTHROUGH */
case 2:
ahc_dma_tag_destroy(ahc, ahc->shared_data_dmat);
case 1:
#ifndef __linux__
ahc_dma_tag_destroy(ahc, ahc->buffer_dmat);
#endif
break;
case 0:
break;
}
#ifndef __linux__
ahc_dma_tag_destroy(ahc, ahc->parent_dmat);
#endif
ahc_platform_free(ahc);
ahc_fini_scbdata(ahc);
for (i = 0; i < AHC_NUM_TARGETS; i++) {
struct ahc_tmode_tstate *tstate;
tstate = ahc->enabled_targets[i];
if (tstate != NULL) {
#ifdef AHC_TARGET_MODE
int j;
for (j = 0; j < AHC_NUM_LUNS; j++) {
struct ahc_tmode_lstate *lstate;
lstate = tstate->enabled_luns[j];
if (lstate != NULL) {
xpt_free_path(lstate->path);
free(lstate, M_DEVBUF);
}
}
#endif
free(tstate, M_DEVBUF);
}
}
#ifdef AHC_TARGET_MODE
if (ahc->black_hole != NULL) {
xpt_free_path(ahc->black_hole->path);
free(ahc->black_hole, M_DEVBUF);
}
#endif
if (ahc->name != NULL)
free(ahc->name, M_DEVBUF);
if (ahc->seep_config != NULL)
free(ahc->seep_config, M_DEVBUF);
#ifndef __FreeBSD__
free(ahc, M_DEVBUF);
#endif
return;
}
static void
ahc_shutdown(void *arg)
{
struct ahc_softc *ahc;
int i;
ahc = (struct ahc_softc *)arg;
/* This will reset most registers to 0, but not all */
ahc_reset(ahc, /*reinit*/FALSE);
ahc_outb(ahc, SCSISEQ, 0);
ahc_outb(ahc, SXFRCTL0, 0);
ahc_outb(ahc, DSPCISTATUS, 0);
for (i = TARG_SCSIRATE; i < SCSICONF; i++)
ahc_outb(ahc, i, 0);
}
/*
* Reset the controller and record some information about it
* that is only available just after a reset. If "reinit" is
* non-zero, this reset occured after initial configuration
* and the caller requests that the chip be fully reinitialized
* to a runable state. Chip interrupts are *not* enabled after
* a reinitialization. The caller must enable interrupts via
* ahc_intr_enable().
*/
int
ahc_reset(struct ahc_softc *ahc, int reinit)
{
u_int sblkctl;
u_int sxfrctl1_a, sxfrctl1_b;
int error;
int wait;
/*
* Preserve the value of the SXFRCTL1 register for all channels.
* It contains settings that affect termination and we don't want
* to disturb the integrity of the bus.
*/
ahc_pause(ahc);
sxfrctl1_b = 0;
if ((ahc->chip & AHC_CHIPID_MASK) == AHC_AIC7770) {
u_int sblkctl;
/*
* Save channel B's settings in case this chip
* is setup for TWIN channel operation.
*/
sblkctl = ahc_inb(ahc, SBLKCTL);
ahc_outb(ahc, SBLKCTL, sblkctl | SELBUSB);
sxfrctl1_b = ahc_inb(ahc, SXFRCTL1);
ahc_outb(ahc, SBLKCTL, sblkctl & ~SELBUSB);
}
sxfrctl1_a = ahc_inb(ahc, SXFRCTL1);
ahc_outb(ahc, HCNTRL, CHIPRST | ahc->pause);
/*
* Ensure that the reset has finished. We delay 1000us
* prior to reading the register to make sure the chip
* has sufficiently completed its reset to handle register
* accesses.
*/
wait = 1000;
do {
ahc_delay(1000);
} while (--wait && !(ahc_inb(ahc, HCNTRL) & CHIPRSTACK));
if (wait == 0) {
printf("%s: WARNING - Failed chip reset! "
"Trying to initialize anyway.\n", ahc_name(ahc));
}
ahc_outb(ahc, HCNTRL, ahc->pause);
/* Determine channel configuration */
sblkctl = ahc_inb(ahc, SBLKCTL) & (SELBUSB|SELWIDE);
/* No Twin Channel PCI cards */
if ((ahc->chip & AHC_PCI) != 0)
sblkctl &= ~SELBUSB;
switch (sblkctl) {
case 0:
/* Single Narrow Channel */
break;
case 2:
/* Wide Channel */
ahc->features |= AHC_WIDE;
break;
case 8:
/* Twin Channel */
ahc->features |= AHC_TWIN;
break;
default:
printf(" Unsupported adapter type. Ignoring\n");
return(-1);
}
/*
* Reload sxfrctl1.
*
* We must always initialize STPWEN to 1 before we
* restore the saved values. STPWEN is initialized
* to a tri-state condition which can only be cleared
* by turning it on.
*/
if ((ahc->features & AHC_TWIN) != 0) {
u_int sblkctl;
sblkctl = ahc_inb(ahc, SBLKCTL);
ahc_outb(ahc, SBLKCTL, sblkctl | SELBUSB);
ahc_outb(ahc, SXFRCTL1, sxfrctl1_b);
ahc_outb(ahc, SBLKCTL, sblkctl & ~SELBUSB);
}
ahc_outb(ahc, SXFRCTL1, sxfrctl1_a);
error = 0;
if (reinit != 0)
/*
* If a recovery action has forced a chip reset,
* re-initialize the chip to our liking.
*/
error = ahc->bus_chip_init(ahc);
#ifdef AHC_DUMP_SEQ
else
ahc_dumpseq(ahc);
#endif
return (error);
}
/*
* Determine the number of SCBs available on the controller
*/
int
ahc_probe_scbs(struct ahc_softc *ahc) {
int i;
for (i = 0; i < AHC_SCB_MAX; i++) {
ahc_outb(ahc, SCBPTR, i);
ahc_outb(ahc, SCB_BASE, i);
if (ahc_inb(ahc, SCB_BASE) != i)
break;
ahc_outb(ahc, SCBPTR, 0);
if (ahc_inb(ahc, SCB_BASE) != 0)
break;
}
return (i);
}
static void
ahc_dmamap_cb(void *arg, bus_dma_segment_t *segs, int nseg, int error)
{
dma_addr_t *baddr;
baddr = (dma_addr_t *)arg;
*baddr = segs->ds_addr;
}
static void
ahc_build_free_scb_list(struct ahc_softc *ahc)
{
int scbsize;
int i;
scbsize = 32;
if ((ahc->flags & AHC_LSCBS_ENABLED) != 0)
scbsize = 64;
for (i = 0; i < ahc->scb_data->maxhscbs; i++) {
int j;
ahc_outb(ahc, SCBPTR, i);
/*
* Touch all SCB bytes to avoid parity errors
* should one of our debugging routines read
* an otherwise uninitiatlized byte.
*/
for (j = 0; j < scbsize; j++)
ahc_outb(ahc, SCB_BASE+j, 0xFF);
/* Clear the control byte. */
ahc_outb(ahc, SCB_CONTROL, 0);
/* Set the next pointer */
if ((ahc->flags & AHC_PAGESCBS) != 0)
ahc_outb(ahc, SCB_NEXT, i+1);
else
ahc_outb(ahc, SCB_NEXT, SCB_LIST_NULL);
/* Make the tag number, SCSIID, and lun invalid */
ahc_outb(ahc, SCB_TAG, SCB_LIST_NULL);
ahc_outb(ahc, SCB_SCSIID, 0xFF);
ahc_outb(ahc, SCB_LUN, 0xFF);
}
if ((ahc->flags & AHC_PAGESCBS) != 0) {
/* SCB 0 heads the free list. */
ahc_outb(ahc, FREE_SCBH, 0);
} else {
/* No free list. */
ahc_outb(ahc, FREE_SCBH, SCB_LIST_NULL);
}
/* Make sure that the last SCB terminates the free list */
ahc_outb(ahc, SCBPTR, i-1);
ahc_outb(ahc, SCB_NEXT, SCB_LIST_NULL);
}
static int
ahc_init_scbdata(struct ahc_softc *ahc)
{
struct scb_data *scb_data;
scb_data = ahc->scb_data;
SLIST_INIT(&scb_data->free_scbs);
SLIST_INIT(&scb_data->sg_maps);
/* Allocate SCB resources */
scb_data->scbarray =
(struct scb *)malloc(sizeof(struct scb) * AHC_SCB_MAX_ALLOC,
M_DEVBUF, M_NOWAIT);
if (scb_data->scbarray == NULL)
return (ENOMEM);
memset(scb_data->scbarray, 0, sizeof(struct scb) * AHC_SCB_MAX_ALLOC);
/* Determine the number of hardware SCBs and initialize them */
scb_data->maxhscbs = ahc_probe_scbs(ahc);
if (ahc->scb_data->maxhscbs == 0) {
printf("%s: No SCB space found\n", ahc_name(ahc));
return (ENXIO);
}
/*
* Create our DMA tags. These tags define the kinds of device
* accessible memory allocations and memory mappings we will
* need to perform during normal operation.
*
* Unless we need to further restrict the allocation, we rely
* on the restrictions of the parent dmat, hence the common
* use of MAXADDR and MAXSIZE.
*/
/* DMA tag for our hardware scb structures */
if (ahc_dma_tag_create(ahc, ahc->parent_dmat, /*alignment*/1,
/*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
/*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
/*highaddr*/BUS_SPACE_MAXADDR,
/*filter*/NULL, /*filterarg*/NULL,
AHC_SCB_MAX_ALLOC * sizeof(struct hardware_scb),
/*nsegments*/1,
/*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
/*flags*/0, &scb_data->hscb_dmat) != 0) {
goto error_exit;
}
scb_data->init_level++;
/* Allocation for our hscbs */
if (ahc_dmamem_alloc(ahc, scb_data->hscb_dmat,
(void **)&scb_data->hscbs,
BUS_DMA_NOWAIT, &scb_data->hscb_dmamap) != 0) {
goto error_exit;
}
scb_data->init_level++;
/* And permanently map them */
ahc_dmamap_load(ahc, scb_data->hscb_dmat, scb_data->hscb_dmamap,
scb_data->hscbs,
AHC_SCB_MAX_ALLOC * sizeof(struct hardware_scb),
ahc_dmamap_cb, &scb_data->hscb_busaddr, /*flags*/0);
scb_data->init_level++;
/* DMA tag for our sense buffers */
if (ahc_dma_tag_create(ahc, ahc->parent_dmat, /*alignment*/1,
/*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
/*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
/*highaddr*/BUS_SPACE_MAXADDR,
/*filter*/NULL, /*filterarg*/NULL,
AHC_SCB_MAX_ALLOC * sizeof(struct scsi_sense_data),
/*nsegments*/1,
/*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
/*flags*/0, &scb_data->sense_dmat) != 0) {
goto error_exit;
}
scb_data->init_level++;
/* Allocate them */
if (ahc_dmamem_alloc(ahc, scb_data->sense_dmat,
(void **)&scb_data->sense,
BUS_DMA_NOWAIT, &scb_data->sense_dmamap) != 0) {
goto error_exit;
}
scb_data->init_level++;
/* And permanently map them */
ahc_dmamap_load(ahc, scb_data->sense_dmat, scb_data->sense_dmamap,
scb_data->sense,
AHC_SCB_MAX_ALLOC * sizeof(struct scsi_sense_data),
ahc_dmamap_cb, &scb_data->sense_busaddr, /*flags*/0);
scb_data->init_level++;
/* DMA tag for our S/G structures. We allocate in page sized chunks */
if (ahc_dma_tag_create(ahc, ahc->parent_dmat, /*alignment*/8,
/*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
/*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
/*highaddr*/BUS_SPACE_MAXADDR,
/*filter*/NULL, /*filterarg*/NULL,
PAGE_SIZE, /*nsegments*/1,
/*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
/*flags*/0, &scb_data->sg_dmat) != 0) {
goto error_exit;
}
scb_data->init_level++;
/* Perform initial CCB allocation */
memset(scb_data->hscbs, 0,
AHC_SCB_MAX_ALLOC * sizeof(struct hardware_scb));
ahc_alloc_scbs(ahc);
if (scb_data->numscbs == 0) {
printf("%s: ahc_init_scbdata - "
"Unable to allocate initial scbs\n",
ahc_name(ahc));
goto error_exit;
}
/*
* Reserve the next queued SCB.
*/
ahc->next_queued_scb = ahc_get_scb(ahc);
/*
* Note that we were successfull
*/
return (0);
error_exit:
return (ENOMEM);
}
static void
ahc_fini_scbdata(struct ahc_softc *ahc)
{
struct scb_data *scb_data;
scb_data = ahc->scb_data;
if (scb_data == NULL)
return;
switch (scb_data->init_level) {
default:
case 7:
{
struct sg_map_node *sg_map;
while ((sg_map = SLIST_FIRST(&scb_data->sg_maps))!= NULL) {
SLIST_REMOVE_HEAD(&scb_data->sg_maps, links);
ahc_dmamap_unload(ahc, scb_data->sg_dmat,
sg_map->sg_dmamap);
ahc_dmamem_free(ahc, scb_data->sg_dmat,
sg_map->sg_vaddr,
sg_map->sg_dmamap);
free(sg_map, M_DEVBUF);
}
ahc_dma_tag_destroy(ahc, scb_data->sg_dmat);
}
case 6:
ahc_dmamap_unload(ahc, scb_data->sense_dmat,
scb_data->sense_dmamap);
case 5:
ahc_dmamem_free(ahc, scb_data->sense_dmat, scb_data->sense,
scb_data->sense_dmamap);
ahc_dmamap_destroy(ahc, scb_data->sense_dmat,
scb_data->sense_dmamap);
case 4:
ahc_dma_tag_destroy(ahc, scb_data->sense_dmat);
case 3:
ahc_dmamap_unload(ahc, scb_data->hscb_dmat,
scb_data->hscb_dmamap);
case 2:
ahc_dmamem_free(ahc, scb_data->hscb_dmat, scb_data->hscbs,
scb_data->hscb_dmamap);
ahc_dmamap_destroy(ahc, scb_data->hscb_dmat,
scb_data->hscb_dmamap);
case 1:
ahc_dma_tag_destroy(ahc, scb_data->hscb_dmat);
break;
case 0:
break;
}
if (scb_data->scbarray != NULL)
free(scb_data->scbarray, M_DEVBUF);
}
static void
ahc_alloc_scbs(struct ahc_softc *ahc)
{
struct scb_data *scb_data;
struct scb *next_scb;
struct sg_map_node *sg_map;
dma_addr_t physaddr;
struct ahc_dma_seg *segs;
int newcount;
int i;
scb_data = ahc->scb_data;
if (scb_data->numscbs >= AHC_SCB_MAX_ALLOC)
/* Can't allocate any more */
return;
next_scb = &scb_data->scbarray[scb_data->numscbs];
sg_map = malloc(sizeof(*sg_map), M_DEVBUF, M_NOWAIT);
if (sg_map == NULL)
return;
/* Allocate S/G space for the next batch of SCBS */
if (ahc_dmamem_alloc(ahc, scb_data->sg_dmat,
(void **)&sg_map->sg_vaddr,
BUS_DMA_NOWAIT, &sg_map->sg_dmamap) != 0) {
free(sg_map, M_DEVBUF);
return;
}
SLIST_INSERT_HEAD(&scb_data->sg_maps, sg_map, links);
ahc_dmamap_load(ahc, scb_data->sg_dmat, sg_map->sg_dmamap,
sg_map->sg_vaddr, PAGE_SIZE, ahc_dmamap_cb,
&sg_map->sg_physaddr, /*flags*/0);
segs = sg_map->sg_vaddr;
physaddr = sg_map->sg_physaddr;
newcount = (PAGE_SIZE / (AHC_NSEG * sizeof(struct ahc_dma_seg)));
newcount = min(newcount, (AHC_SCB_MAX_ALLOC - scb_data->numscbs));
for (i = 0; i < newcount; i++) {
struct scb_platform_data *pdata;
#ifndef __linux__
int error;
#endif
pdata = (struct scb_platform_data *)malloc(sizeof(*pdata),
M_DEVBUF, M_NOWAIT);
if (pdata == NULL)
break;
next_scb->platform_data = pdata;
next_scb->sg_map = sg_map;
next_scb->sg_list = segs;
/*
* The sequencer always starts with the second entry.
* The first entry is embedded in the scb.
*/
next_scb->sg_list_phys = physaddr + sizeof(struct ahc_dma_seg);
next_scb->ahc_softc = ahc;
next_scb->flags = SCB_FREE;
#ifndef __linux__
error = ahc_dmamap_create(ahc, ahc->buffer_dmat, /*flags*/0,
&next_scb->dmamap);
if (error != 0)
break;
#endif
next_scb->hscb = &scb_data->hscbs[scb_data->numscbs];
next_scb->hscb->tag = ahc->scb_data->numscbs;
SLIST_INSERT_HEAD(&ahc->scb_data->free_scbs,
next_scb, links.sle);
segs += AHC_NSEG;
physaddr += (AHC_NSEG * sizeof(struct ahc_dma_seg));
next_scb++;
ahc->scb_data->numscbs++;
}
}
void
ahc_controller_info(struct ahc_softc *ahc, char *buf)
{
int len;
len = sprintf(buf, "%s: ", ahc_chip_names[ahc->chip & AHC_CHIPID_MASK]);
buf += len;
if ((ahc->features & AHC_TWIN) != 0)
len = sprintf(buf, "Twin Channel, A SCSI Id=%d, "
"B SCSI Id=%d, primary %c, ",
ahc->our_id, ahc->our_id_b,
(ahc->flags & AHC_PRIMARY_CHANNEL) + 'A');
else {
const char *speed;
const char *type;
speed = "";
if ((ahc->features & AHC_ULTRA) != 0) {
speed = "Ultra ";
} else if ((ahc->features & AHC_DT) != 0) {
speed = "Ultra160 ";
} else if ((ahc->features & AHC_ULTRA2) != 0) {
speed = "Ultra2 ";
}
if ((ahc->features & AHC_WIDE) != 0) {
type = "Wide";
} else {
type = "Single";
}
len = sprintf(buf, "%s%s Channel %c, SCSI Id=%d, ",
speed, type, ahc->channel, ahc->our_id);
}
buf += len;
if ((ahc->flags & AHC_PAGESCBS) != 0)
sprintf(buf, "%d/%d SCBs",
ahc->scb_data->maxhscbs, AHC_MAX_QUEUE);
else
sprintf(buf, "%d SCBs", ahc->scb_data->maxhscbs);
}
int
ahc_chip_init(struct ahc_softc *ahc)
{
int term;
int error;
u_int i;
u_int scsi_conf;
u_int scsiseq_template;
uint32_t physaddr;
ahc_outb(ahc, SEQ_FLAGS, 0);
ahc_outb(ahc, SEQ_FLAGS2, 0);
/* Set the SCSI Id, SXFRCTL0, SXFRCTL1, and SIMODE1, for both channels*/
if (ahc->features & AHC_TWIN) {
/*
* Setup Channel B first.
*/
ahc_outb(ahc, SBLKCTL, ahc_inb(ahc, SBLKCTL) | SELBUSB);
term = (ahc->flags & AHC_TERM_ENB_B) != 0 ? STPWEN : 0;
ahc_outb(ahc, SCSIID, ahc->our_id_b);
scsi_conf = ahc_inb(ahc, SCSICONF + 1);
ahc_outb(ahc, SXFRCTL1, (scsi_conf & (ENSPCHK|STIMESEL))
|term|ahc->seltime_b|ENSTIMER|ACTNEGEN);
if ((ahc->features & AHC_ULTRA2) != 0)
ahc_outb(ahc, SIMODE0, ahc_inb(ahc, SIMODE0)|ENIOERR);
ahc_outb(ahc, SIMODE1, ENSELTIMO|ENSCSIRST|ENSCSIPERR);
ahc_outb(ahc, SXFRCTL0, DFON|SPIOEN);
/* Select Channel A */
ahc_outb(ahc, SBLKCTL, ahc_inb(ahc, SBLKCTL) & ~SELBUSB);
}
term = (ahc->flags & AHC_TERM_ENB_A) != 0 ? STPWEN : 0;
if ((ahc->features & AHC_ULTRA2) != 0)
ahc_outb(ahc, SCSIID_ULTRA2, ahc->our_id);
else
ahc_outb(ahc, SCSIID, ahc->our_id);
scsi_conf = ahc_inb(ahc, SCSICONF);
ahc_outb(ahc, SXFRCTL1, (scsi_conf & (ENSPCHK|STIMESEL))
|term|ahc->seltime
|ENSTIMER|ACTNEGEN);
if ((ahc->features & AHC_ULTRA2) != 0)
ahc_outb(ahc, SIMODE0, ahc_inb(ahc, SIMODE0)|ENIOERR);
ahc_outb(ahc, SIMODE1, ENSELTIMO|ENSCSIRST|ENSCSIPERR);
ahc_outb(ahc, SXFRCTL0, DFON|SPIOEN);
/* There are no untagged SCBs active yet. */
for (i = 0; i < 16; i++) {
ahc_unbusy_tcl(ahc, BUILD_TCL(i << 4, 0));
if ((ahc->flags & AHC_SCB_BTT) != 0) {
int lun;
/*
* The SCB based BTT allows an entry per
* target and lun pair.
*/
for (lun = 1; lun < AHC_NUM_LUNS; lun++)
ahc_unbusy_tcl(ahc, BUILD_TCL(i << 4, lun));
}
}
/* All of our queues are empty */
for (i = 0; i < 256; i++)
ahc->qoutfifo[i] = SCB_LIST_NULL;
ahc_sync_qoutfifo(ahc, BUS_DMASYNC_PREREAD);
for (i = 0; i < 256; i++)
ahc->qinfifo[i] = SCB_LIST_NULL;
if ((ahc->features & AHC_MULTI_TID) != 0) {
ahc_outb(ahc, TARGID, 0);
ahc_outb(ahc, TARGID + 1, 0);
}
/*
* Tell the sequencer where it can find our arrays in memory.
*/
physaddr = ahc->scb_data->hscb_busaddr;
ahc_outb(ahc, HSCB_ADDR, physaddr & 0xFF);
ahc_outb(ahc, HSCB_ADDR + 1, (physaddr >> 8) & 0xFF);
ahc_outb(ahc, HSCB_ADDR + 2, (physaddr >> 16) & 0xFF);
ahc_outb(ahc, HSCB_ADDR + 3, (physaddr >> 24) & 0xFF);
physaddr = ahc->shared_data_busaddr;
ahc_outb(ahc, SHARED_DATA_ADDR, physaddr & 0xFF);
ahc_outb(ahc, SHARED_DATA_ADDR + 1, (physaddr >> 8) & 0xFF);
ahc_outb(ahc, SHARED_DATA_ADDR + 2, (physaddr >> 16) & 0xFF);
ahc_outb(ahc, SHARED_DATA_ADDR + 3, (physaddr >> 24) & 0xFF);
/*
* Initialize the group code to command length table.
* This overrides the values in TARG_SCSIRATE, so only
* setup the table after we have processed that information.
*/
ahc_outb(ahc, CMDSIZE_TABLE, 5);
ahc_outb(ahc, CMDSIZE_TABLE + 1, 9);
ahc_outb(ahc, CMDSIZE_TABLE + 2, 9);
ahc_outb(ahc, CMDSIZE_TABLE + 3, 0);
ahc_outb(ahc, CMDSIZE_TABLE + 4, 15);
ahc_outb(ahc, CMDSIZE_TABLE + 5, 11);
ahc_outb(ahc, CMDSIZE_TABLE + 6, 0);
ahc_outb(ahc, CMDSIZE_TABLE + 7, 0);
if ((ahc->features & AHC_HS_MAILBOX) != 0)
ahc_outb(ahc, HS_MAILBOX, 0);
/* Tell the sequencer of our initial queue positions */
if ((ahc->features & AHC_TARGETMODE) != 0) {
ahc->tqinfifonext = 1;
ahc_outb(ahc, KERNEL_TQINPOS, ahc->tqinfifonext - 1);
ahc_outb(ahc, TQINPOS, ahc->tqinfifonext);
}
ahc->qinfifonext = 0;
ahc->qoutfifonext = 0;
if ((ahc->features & AHC_QUEUE_REGS) != 0) {
ahc_outb(ahc, QOFF_CTLSTA, SCB_QSIZE_256);
ahc_outb(ahc, HNSCB_QOFF, ahc->qinfifonext);
ahc_outb(ahc, SNSCB_QOFF, ahc->qinfifonext);
ahc_outb(ahc, SDSCB_QOFF, 0);
} else {
ahc_outb(ahc, KERNEL_QINPOS, ahc->qinfifonext);
ahc_outb(ahc, QINPOS, ahc->qinfifonext);
ahc_outb(ahc, QOUTPOS, ahc->qoutfifonext);
}
/* We don't have any waiting selections */
ahc_outb(ahc, WAITING_SCBH, SCB_LIST_NULL);
/* Our disconnection list is empty too */
ahc_outb(ahc, DISCONNECTED_SCBH, SCB_LIST_NULL);
/* Message out buffer starts empty */
ahc_outb(ahc, MSG_OUT, MSG_NOOP);
/*
* Setup the allowed SCSI Sequences based on operational mode.
* If we are a target, we'll enable select in operations once
* we've had a lun enabled.
*/
scsiseq_template = ENSELO|ENAUTOATNO|ENAUTOATNP;
if ((ahc->flags & AHC_INITIATORROLE) != 0)
scsiseq_template |= ENRSELI;
ahc_outb(ahc, SCSISEQ_TEMPLATE, scsiseq_template);
/* Initialize our list of free SCBs. */
ahc_build_free_scb_list(ahc);
/*
* Tell the sequencer which SCB will be the next one it receives.
*/
ahc_outb(ahc, NEXT_QUEUED_SCB, ahc->next_queued_scb->hscb->tag);
/*
* Load the Sequencer program and Enable the adapter
* in "fast" mode.
*/
if (bootverbose)
printf("%s: Downloading Sequencer Program...",
ahc_name(ahc));
error = ahc_loadseq(ahc);
if (error != 0)
return (error);
if ((ahc->features & AHC_ULTRA2) != 0) {
int wait;
/*
* Wait for up to 500ms for our transceivers
* to settle. If the adapter does not have
* a cable attached, the transceivers may
* never settle, so don't complain if we
* fail here.
*/
for (wait = 5000;
(ahc_inb(ahc, SBLKCTL) & (ENAB40|ENAB20)) == 0 && wait;
wait--)
ahc_delay(100);
}
ahc_restart(ahc);
return (0);
}
/*
* Start the board, ready for normal operation
*/
int
ahc_init(struct ahc_softc *ahc)
{
int max_targ;
u_int i;
u_int scsi_conf;
u_int ultraenb;
u_int discenable;
u_int tagenable;
size_t driver_data_size;
#ifdef AHC_DEBUG
if ((ahc_debug & AHC_DEBUG_SEQUENCER) != 0)
ahc->flags |= AHC_SEQUENCER_DEBUG;
#endif
#ifdef AHC_PRINT_SRAM
printf("Scratch Ram:");
for (i = 0x20; i < 0x5f; i++) {
if (((i % 8) == 0) && (i != 0)) {
printf ("\n ");
}
printf (" 0x%x", ahc_inb(ahc, i));
}
if ((ahc->features & AHC_MORE_SRAM) != 0) {
for (i = 0x70; i < 0x7f; i++) {
if (((i % 8) == 0) && (i != 0)) {
printf ("\n ");
}
printf (" 0x%x", ahc_inb(ahc, i));
}
}
printf ("\n");
/*
* Reading uninitialized scratch ram may
* generate parity errors.
*/
ahc_outb(ahc, CLRINT, CLRPARERR);
ahc_outb(ahc, CLRINT, CLRBRKADRINT);
#endif
max_targ = 15;
/*
* Assume we have a board at this stage and it has been reset.
*/
if ((ahc->flags & AHC_USEDEFAULTS) != 0)
ahc->our_id = ahc->our_id_b = 7;
/*
* Default to allowing initiator operations.
*/
ahc->flags |= AHC_INITIATORROLE;
/*
* Only allow target mode features if this unit has them enabled.
*/
if ((AHC_TMODE_ENABLE & (0x1 << ahc->unit)) == 0)
ahc->features &= ~AHC_TARGETMODE;
#ifndef __linux__
/* DMA tag for mapping buffers into device visible space. */
if (ahc_dma_tag_create(ahc, ahc->parent_dmat, /*alignment*/1,
/*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
/*lowaddr*/ahc->flags & AHC_39BIT_ADDRESSING
? (dma_addr_t)0x7FFFFFFFFFULL
: BUS_SPACE_MAXADDR_32BIT,
/*highaddr*/BUS_SPACE_MAXADDR,
/*filter*/NULL, /*filterarg*/NULL,
/*maxsize*/(AHC_NSEG - 1) * PAGE_SIZE,
/*nsegments*/AHC_NSEG,
/*maxsegsz*/AHC_MAXTRANSFER_SIZE,
/*flags*/BUS_DMA_ALLOCNOW,
&ahc->buffer_dmat) != 0) {
return (ENOMEM);
}
#endif
ahc->init_level++;
/*
* DMA tag for our command fifos and other data in system memory
* the card's sequencer must be able to access. For initiator
* roles, we need to allocate space for the qinfifo and qoutfifo.
* The qinfifo and qoutfifo are composed of 256 1 byte elements.
* When providing for the target mode role, we must additionally
* provide space for the incoming target command fifo and an extra
* byte to deal with a dma bug in some chip versions.
*/
driver_data_size = 2 * 256 * sizeof(uint8_t);
if ((ahc->features & AHC_TARGETMODE) != 0)
driver_data_size += AHC_TMODE_CMDS * sizeof(struct target_cmd)
+ /*DMA WideOdd Bug Buffer*/1;
if (ahc_dma_tag_create(ahc, ahc->parent_dmat, /*alignment*/1,
/*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
/*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
/*highaddr*/BUS_SPACE_MAXADDR,
/*filter*/NULL, /*filterarg*/NULL,
driver_data_size,
/*nsegments*/1,
/*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
/*flags*/0, &ahc->shared_data_dmat) != 0) {
return (ENOMEM);
}
ahc->init_level++;
/* Allocation of driver data */
if (ahc_dmamem_alloc(ahc, ahc->shared_data_dmat,
(void **)&ahc->qoutfifo,
BUS_DMA_NOWAIT, &ahc->shared_data_dmamap) != 0) {
return (ENOMEM);
}
ahc->init_level++;
/* And permanently map it in */
ahc_dmamap_load(ahc, ahc->shared_data_dmat, ahc->shared_data_dmamap,
ahc->qoutfifo, driver_data_size, ahc_dmamap_cb,
&ahc->shared_data_busaddr, /*flags*/0);
if ((ahc->features & AHC_TARGETMODE) != 0) {
ahc->targetcmds = (struct target_cmd *)ahc->qoutfifo;
ahc->qoutfifo = (uint8_t *)&ahc->targetcmds[AHC_TMODE_CMDS];
ahc->dma_bug_buf = ahc->shared_data_busaddr
+ driver_data_size - 1;
/* All target command blocks start out invalid. */
for (i = 0; i < AHC_TMODE_CMDS; i++)
ahc->targetcmds[i].cmd_valid = 0;
ahc_sync_tqinfifo(ahc, BUS_DMASYNC_PREREAD);
ahc->qoutfifo = (uint8_t *)&ahc->targetcmds[256];
}
ahc->qinfifo = &ahc->qoutfifo[256];
ahc->init_level++;
/* Allocate SCB data now that buffer_dmat is initialized */
if (ahc->scb_data->maxhscbs == 0)
if (ahc_init_scbdata(ahc) != 0)
return (ENOMEM);
/*
* Allocate a tstate to house information for our
* initiator presence on the bus as well as the user
* data for any target mode initiator.
*/
if (ahc_alloc_tstate(ahc, ahc->our_id, 'A') == NULL) {
printf("%s: unable to allocate ahc_tmode_tstate. "
"Failing attach\n", ahc_name(ahc));
return (ENOMEM);
}
if ((ahc->features & AHC_TWIN) != 0) {
if (ahc_alloc_tstate(ahc, ahc->our_id_b, 'B') == NULL) {
printf("%s: unable to allocate ahc_tmode_tstate. "
"Failing attach\n", ahc_name(ahc));
return (ENOMEM);
}
}
if (ahc->scb_data->maxhscbs < AHC_SCB_MAX_ALLOC) {
ahc->flags |= AHC_PAGESCBS;
} else {
ahc->flags &= ~AHC_PAGESCBS;
}
#ifdef AHC_DEBUG
if (ahc_debug & AHC_SHOW_MISC) {
printf("%s: hardware scb %u bytes; kernel scb %u bytes; "
"ahc_dma %u bytes\n",
ahc_name(ahc),
(u_int)sizeof(struct hardware_scb),
(u_int)sizeof(struct scb),
(u_int)sizeof(struct ahc_dma_seg));
}
#endif /* AHC_DEBUG */
/*
* Look at the information that board initialization or
* the board bios has left us.
*/
if (ahc->features & AHC_TWIN) {
scsi_conf = ahc_inb(ahc, SCSICONF + 1);
if ((scsi_conf & RESET_SCSI) != 0
&& (ahc->flags & AHC_INITIATORROLE) != 0)
ahc->flags |= AHC_RESET_BUS_B;
}
scsi_conf = ahc_inb(ahc, SCSICONF);
if ((scsi_conf & RESET_SCSI) != 0
&& (ahc->flags & AHC_INITIATORROLE) != 0)
ahc->flags |= AHC_RESET_BUS_A;
ultraenb = 0;
tagenable = ALL_TARGETS_MASK;
/* Grab the disconnection disable table and invert it for our needs */
if ((ahc->flags & AHC_USEDEFAULTS) != 0) {
printf("%s: Host Adapter Bios disabled. Using default SCSI "
"device parameters\n", ahc_name(ahc));
ahc->flags |= AHC_EXTENDED_TRANS_A|AHC_EXTENDED_TRANS_B|
AHC_TERM_ENB_A|AHC_TERM_ENB_B;
discenable = ALL_TARGETS_MASK;
if ((ahc->features & AHC_ULTRA) != 0)
ultraenb = ALL_TARGETS_MASK;
} else {
discenable = ~((ahc_inb(ahc, DISC_DSB + 1) << 8)
| ahc_inb(ahc, DISC_DSB));
if ((ahc->features & (AHC_ULTRA|AHC_ULTRA2)) != 0)
ultraenb = (ahc_inb(ahc, ULTRA_ENB + 1) << 8)
| ahc_inb(ahc, ULTRA_ENB);
}
if ((ahc->features & (AHC_WIDE|AHC_TWIN)) == 0)
max_targ = 7;
for (i = 0; i <= max_targ; i++) {
struct ahc_initiator_tinfo *tinfo;
struct ahc_tmode_tstate *tstate;
u_int our_id;
u_int target_id;
char channel;
channel = 'A';
our_id = ahc->our_id;
target_id = i;
if (i > 7 && (ahc->features & AHC_TWIN) != 0) {
channel = 'B';
our_id = ahc->our_id_b;
target_id = i % 8;
}
tinfo = ahc_fetch_transinfo(ahc, channel, our_id,
target_id, &tstate);
/* Default to async narrow across the board */
memset(tinfo, 0, sizeof(*tinfo));
if (ahc->flags & AHC_USEDEFAULTS) {
if ((ahc->features & AHC_WIDE) != 0)
tinfo->user.width = MSG_EXT_WDTR_BUS_16_BIT;
/*
* These will be truncated when we determine the
* connection type we have with the target.
*/
tinfo->user.period = ahc_syncrates->period;
tinfo->user.offset = MAX_OFFSET;
} else {
u_int scsirate;
uint16_t mask;
/* Take the settings leftover in scratch RAM. */
scsirate = ahc_inb(ahc, TARG_SCSIRATE + i);
mask = (0x01 << i);
if ((ahc->features & AHC_ULTRA2) != 0) {
u_int offset;
u_int maxsync;
if ((scsirate & SOFS) == 0x0F) {
/*
* Haven't negotiated yet,
* so the format is different.
*/
scsirate = (scsirate & SXFR) >> 4
| (ultraenb & mask)
? 0x08 : 0x0
| (scsirate & WIDEXFER);
offset = MAX_OFFSET_ULTRA2;
} else
offset = ahc_inb(ahc, TARG_OFFSET + i);
if ((scsirate & ~WIDEXFER) == 0 && offset != 0)
/* Set to the lowest sync rate, 5MHz */
scsirate |= 0x1c;
maxsync = AHC_SYNCRATE_ULTRA2;
if ((ahc->features & AHC_DT) != 0)
maxsync = AHC_SYNCRATE_DT;
tinfo->user.period =
ahc_find_period(ahc, scsirate, maxsync);
if (offset == 0)
tinfo->user.period = 0;
else
tinfo->user.offset = MAX_OFFSET;
if ((scsirate & SXFR_ULTRA2) <= 8/*10MHz*/
&& (ahc->features & AHC_DT) != 0)
tinfo->user.ppr_options =
MSG_EXT_PPR_DT_REQ;
} else if ((scsirate & SOFS) != 0) {
if ((scsirate & SXFR) == 0x40
&& (ultraenb & mask) != 0) {
/* Treat 10MHz as a non-ultra speed */
scsirate &= ~SXFR;
ultraenb &= ~mask;
}
tinfo->user.period =
ahc_find_period(ahc, scsirate,
(ultraenb & mask)
? AHC_SYNCRATE_ULTRA
: AHC_SYNCRATE_FAST);
if (tinfo->user.period != 0)
tinfo->user.offset = MAX_OFFSET;
}
if (tinfo->user.period == 0)
tinfo->user.offset = 0;
if ((scsirate & WIDEXFER) != 0
&& (ahc->features & AHC_WIDE) != 0)
tinfo->user.width = MSG_EXT_WDTR_BUS_16_BIT;
tinfo->user.protocol_version = 4;
if ((ahc->features & AHC_DT) != 0)
tinfo->user.transport_version = 3;
else
tinfo->user.transport_version = 2;
tinfo->goal.protocol_version = 2;
tinfo->goal.transport_version = 2;
tinfo->curr.protocol_version = 2;
tinfo->curr.transport_version = 2;
}
tstate->ultraenb = 0;
}
ahc->user_discenable = discenable;
ahc->user_tagenable = tagenable;
return (ahc->bus_chip_init(ahc));
}
void
ahc_intr_enable(struct ahc_softc *ahc, int enable)
{
u_int hcntrl;
hcntrl = ahc_inb(ahc, HCNTRL);
hcntrl &= ~INTEN;
ahc->pause &= ~INTEN;
ahc->unpause &= ~INTEN;
if (enable) {
hcntrl |= INTEN;
ahc->pause |= INTEN;
ahc->unpause |= INTEN;
}
ahc_outb(ahc, HCNTRL, hcntrl);
}
/*
* Ensure that the card is paused in a location
* outside of all critical sections and that all
* pending work is completed prior to returning.
* This routine should only be called from outside
* an interrupt context.
*/
void
ahc_pause_and_flushwork(struct ahc_softc *ahc)
{
int intstat;
int maxloops;
int paused;
maxloops = 1000;
ahc->flags |= AHC_ALL_INTERRUPTS;
paused = FALSE;
do {
if (paused) {
ahc_unpause(ahc);
/*
* Give the sequencer some time to service
* any active selections.
*/
ahc_delay(500);
}
ahc_intr(ahc);
ahc_pause(ahc);
paused = TRUE;
ahc_outb(ahc, SCSISEQ, ahc_inb(ahc, SCSISEQ) & ~ENSELO);
intstat = ahc_inb(ahc, INTSTAT);
if ((intstat & INT_PEND) == 0) {
ahc_clear_critical_section(ahc);
intstat = ahc_inb(ahc, INTSTAT);
}
} while (--maxloops
&& (intstat != 0xFF || (ahc->features & AHC_REMOVABLE) == 0)
&& ((intstat & INT_PEND) != 0
|| (ahc_inb(ahc, SSTAT0) & (SELDO|SELINGO)) != 0));
if (maxloops == 0) {
printf("Infinite interrupt loop, INTSTAT = %x",
ahc_inb(ahc, INTSTAT));
}
ahc_platform_flushwork(ahc);
ahc->flags &= ~AHC_ALL_INTERRUPTS;
}
#ifdef CONFIG_PM
int
ahc_suspend(struct ahc_softc *ahc)
{
ahc_pause_and_flushwork(ahc);
if (LIST_FIRST(&ahc->pending_scbs) != NULL) {
ahc_unpause(ahc);
return (EBUSY);
}
#ifdef AHC_TARGET_MODE
/*
* XXX What about ATIOs that have not yet been serviced?
* Perhaps we should just refuse to be suspended if we
* are acting in a target role.
*/
if (ahc->pending_device != NULL) {
ahc_unpause(ahc);
return (EBUSY);
}
#endif
ahc_shutdown(ahc);
return (0);
}
int
ahc_resume(struct ahc_softc *ahc)
{
ahc_reset(ahc, /*reinit*/TRUE);
ahc_intr_enable(ahc, TRUE);
ahc_restart(ahc);
return (0);
}
#endif
/************************** Busy Target Table *********************************/
/*
* Return the untagged transaction id for a given target/channel lun.
* Optionally, clear the entry.
*/
static u_int
ahc_index_busy_tcl(struct ahc_softc *ahc, u_int tcl)
{
u_int scbid;
u_int target_offset;
if ((ahc->flags & AHC_SCB_BTT) != 0) {
u_int saved_scbptr;
saved_scbptr = ahc_inb(ahc, SCBPTR);
ahc_outb(ahc, SCBPTR, TCL_LUN(tcl));
scbid = ahc_inb(ahc, SCB_64_BTT + TCL_TARGET_OFFSET(tcl));
ahc_outb(ahc, SCBPTR, saved_scbptr);
} else {
target_offset = TCL_TARGET_OFFSET(tcl);
scbid = ahc_inb(ahc, BUSY_TARGETS + target_offset);
}
return (scbid);
}
static void
ahc_unbusy_tcl(struct ahc_softc *ahc, u_int tcl)
{
u_int target_offset;
if ((ahc->flags & AHC_SCB_BTT) != 0) {
u_int saved_scbptr;
saved_scbptr = ahc_inb(ahc, SCBPTR);
ahc_outb(ahc, SCBPTR, TCL_LUN(tcl));
ahc_outb(ahc, SCB_64_BTT+TCL_TARGET_OFFSET(tcl), SCB_LIST_NULL);
ahc_outb(ahc, SCBPTR, saved_scbptr);
} else {
target_offset = TCL_TARGET_OFFSET(tcl);
ahc_outb(ahc, BUSY_TARGETS + target_offset, SCB_LIST_NULL);
}
}
static void
ahc_busy_tcl(struct ahc_softc *ahc, u_int tcl, u_int scbid)
{
u_int target_offset;
if ((ahc->flags & AHC_SCB_BTT) != 0) {
u_int saved_scbptr;
saved_scbptr = ahc_inb(ahc, SCBPTR);
ahc_outb(ahc, SCBPTR, TCL_LUN(tcl));
ahc_outb(ahc, SCB_64_BTT + TCL_TARGET_OFFSET(tcl), scbid);
ahc_outb(ahc, SCBPTR, saved_scbptr);
} else {
target_offset = TCL_TARGET_OFFSET(tcl);
ahc_outb(ahc, BUSY_TARGETS + target_offset, scbid);
}
}
/************************** SCB and SCB queue management **********************/
int
ahc_match_scb(struct ahc_softc *ahc, struct scb *scb, int target,
char channel, int lun, u_int tag, role_t role)
{
int targ = SCB_GET_TARGET(ahc, scb);
char chan = SCB_GET_CHANNEL(ahc, scb);
int slun = SCB_GET_LUN(scb);
int match;
match = ((chan == channel) || (channel == ALL_CHANNELS));
if (match != 0)
match = ((targ == target) || (target == CAM_TARGET_WILDCARD));
if (match != 0)
match = ((lun == slun) || (lun == CAM_LUN_WILDCARD));
if (match != 0) {
#ifdef AHC_TARGET_MODE
int group;
group = XPT_FC_GROUP(scb->io_ctx->ccb_h.func_code);
if (role == ROLE_INITIATOR) {
match = (group != XPT_FC_GROUP_TMODE)
&& ((tag == scb->hscb->tag)
|| (tag == SCB_LIST_NULL));
} else if (role == ROLE_TARGET) {
match = (group == XPT_FC_GROUP_TMODE)
&& ((tag == scb->io_ctx->csio.tag_id)
|| (tag == SCB_LIST_NULL));
}
#else /* !AHC_TARGET_MODE */
match = ((tag == scb->hscb->tag) || (tag == SCB_LIST_NULL));
#endif /* AHC_TARGET_MODE */
}
return match;
}
static void
ahc_freeze_devq(struct ahc_softc *ahc, struct scb *scb)
{
int target;
char channel;
int lun;
target = SCB_GET_TARGET(ahc, scb);
lun = SCB_GET_LUN(scb);
channel = SCB_GET_CHANNEL(ahc, scb);
ahc_search_qinfifo(ahc, target, channel, lun,
/*tag*/SCB_LIST_NULL, ROLE_UNKNOWN,
CAM_REQUEUE_REQ, SEARCH_COMPLETE);
ahc_platform_freeze_devq(ahc, scb);
}
void
ahc_qinfifo_requeue_tail(struct ahc_softc *ahc, struct scb *scb)
{
struct scb *prev_scb;
prev_scb = NULL;
if (ahc_qinfifo_count(ahc) != 0) {
u_int prev_tag;
uint8_t prev_pos;
prev_pos = ahc->qinfifonext - 1;
prev_tag = ahc->qinfifo[prev_pos];
prev_scb = ahc_lookup_scb(ahc, prev_tag);
}
ahc_qinfifo_requeue(ahc, prev_scb, scb);
if ((ahc->features & AHC_QUEUE_REGS) != 0) {
ahc_outb(ahc, HNSCB_QOFF, ahc->qinfifonext);
} else {
ahc_outb(ahc, KERNEL_QINPOS, ahc->qinfifonext);
}
}
static void
ahc_qinfifo_requeue(struct ahc_softc *ahc, struct scb *prev_scb,
struct scb *scb)
{
if (prev_scb == NULL) {
ahc_outb(ahc, NEXT_QUEUED_SCB, scb->hscb->tag);
} else {
prev_scb->hscb->next = scb->hscb->tag;
ahc_sync_scb(ahc, prev_scb,
BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
}
ahc->qinfifo[ahc->qinfifonext++] = scb->hscb->tag;
scb->hscb->next = ahc->next_queued_scb->hscb->tag;
ahc_sync_scb(ahc, scb, BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
}
static int
ahc_qinfifo_count(struct ahc_softc *ahc)
{
uint8_t qinpos;
uint8_t diff;
if ((ahc->features & AHC_QUEUE_REGS) != 0) {
qinpos = ahc_inb(ahc, SNSCB_QOFF);
ahc_outb(ahc, SNSCB_QOFF, qinpos);
} else
qinpos = ahc_inb(ahc, QINPOS);
diff = ahc->qinfifonext - qinpos;
return (diff);
}
int
ahc_search_qinfifo(struct ahc_softc *ahc, int target, char channel,
int lun, u_int tag, role_t role, uint32_t status,
ahc_search_action action)
{
struct scb *scb;
struct scb *prev_scb;
uint8_t qinstart;
uint8_t qinpos;
uint8_t qintail;
uint8_t next;
uint8_t prev;
uint8_t curscbptr;
int found;
int have_qregs;
qintail = ahc->qinfifonext;
have_qregs = (ahc->features & AHC_QUEUE_REGS) != 0;
if (have_qregs) {
qinstart = ahc_inb(ahc, SNSCB_QOFF);
ahc_outb(ahc, SNSCB_QOFF, qinstart);
} else
qinstart = ahc_inb(ahc, QINPOS);
qinpos = qinstart;
found = 0;
prev_scb = NULL;
if (action == SEARCH_COMPLETE) {
/*
* Don't attempt to run any queued untagged transactions
* until we are done with the abort process.
*/
ahc_freeze_untagged_queues(ahc);
}
/*
* Start with an empty queue. Entries that are not chosen
* for removal will be re-added to the queue as we go.
*/
ahc->qinfifonext = qinpos;
ahc_outb(ahc, NEXT_QUEUED_SCB, ahc->next_queued_scb->hscb->tag);
while (qinpos != qintail) {
scb = ahc_lookup_scb(ahc, ahc->qinfifo[qinpos]);
if (scb == NULL) {
printf("qinpos = %d, SCB index = %d\n",
qinpos, ahc->qinfifo[qinpos]);
panic("Loop 1\n");
}
if (ahc_match_scb(ahc, scb, target, channel, lun, tag, role)) {
/*
* We found an scb that needs to be acted on.
*/
found++;
switch (action) {
case SEARCH_COMPLETE:
{
cam_status ostat;
cam_status cstat;
ostat = ahc_get_transaction_status(scb);
if (ostat == CAM_REQ_INPROG)
ahc_set_transaction_status(scb, status);
cstat = ahc_get_transaction_status(scb);
if (cstat != CAM_REQ_CMP)
ahc_freeze_scb(scb);
if ((scb->flags & SCB_ACTIVE) == 0)
printf("Inactive SCB in qinfifo\n");
ahc_done(ahc, scb);
/* FALLTHROUGH */
}
case SEARCH_REMOVE:
break;
case SEARCH_COUNT:
ahc_qinfifo_requeue(ahc, prev_scb, scb);
prev_scb = scb;
break;
}
} else {
ahc_qinfifo_requeue(ahc, prev_scb, scb);
prev_scb = scb;
}
qinpos++;
}
if ((ahc->features & AHC_QUEUE_REGS) != 0) {
ahc_outb(ahc, HNSCB_QOFF, ahc->qinfifonext);
} else {
ahc_outb(ahc, KERNEL_QINPOS, ahc->qinfifonext);
}
if (action != SEARCH_COUNT
&& (found != 0)
&& (qinstart != ahc->qinfifonext)) {
/*
* The sequencer may be in the process of dmaing
* down the SCB at the beginning of the queue.
* This could be problematic if either the first,
* or the second SCB is removed from the queue
* (the first SCB includes a pointer to the "next"
* SCB to dma). If we have removed any entries, swap
* the first element in the queue with the next HSCB
* so the sequencer will notice that NEXT_QUEUED_SCB
* has changed during its dma attempt and will retry
* the DMA.
*/
scb = ahc_lookup_scb(ahc, ahc->qinfifo[qinstart]);
if (scb == NULL) {
printf("found = %d, qinstart = %d, qinfifionext = %d\n",
found, qinstart, ahc->qinfifonext);
panic("First/Second Qinfifo fixup\n");
}
/*
* ahc_swap_with_next_hscb forces our next pointer to
* point to the reserved SCB for future commands. Save
* and restore our original next pointer to maintain
* queue integrity.
*/
next = scb->hscb->next;
ahc->scb_data->scbindex[scb->hscb->tag] = NULL;
ahc_swap_with_next_hscb(ahc, scb);
scb->hscb->next = next;
ahc->qinfifo[qinstart] = scb->hscb->tag;
/* Tell the card about the new head of the qinfifo. */
ahc_outb(ahc, NEXT_QUEUED_SCB, scb->hscb->tag);
/* Fixup the tail "next" pointer. */
qintail = ahc->qinfifonext - 1;
scb = ahc_lookup_scb(ahc, ahc->qinfifo[qintail]);
scb->hscb->next = ahc->next_queued_scb->hscb->tag;
}
/*
* Search waiting for selection list.
*/
curscbptr = ahc_inb(ahc, SCBPTR);
next = ahc_inb(ahc, WAITING_SCBH); /* Start at head of list. */
prev = SCB_LIST_NULL;
while (next != SCB_LIST_NULL) {
uint8_t scb_index;
ahc_outb(ahc, SCBPTR, next);
scb_index = ahc_inb(ahc, SCB_TAG);
if (scb_index >= ahc->scb_data->numscbs) {
printf("Waiting List inconsistency. "
"SCB index == %d, yet numscbs == %d.",
scb_index, ahc->scb_data->numscbs);
ahc_dump_card_state(ahc);
panic("for safety");
}
scb = ahc_lookup_scb(ahc, scb_index);
if (scb == NULL) {
printf("scb_index = %d, next = %d\n",
scb_index, next);
panic("Waiting List traversal\n");
}
if (ahc_match_scb(ahc, scb, target, channel,
lun, SCB_LIST_NULL, role)) {
/*
* We found an scb that needs to be acted on.
*/
found++;
switch (action) {
case SEARCH_COMPLETE:
{
cam_status ostat;
cam_status cstat;
ostat = ahc_get_transaction_status(scb);
if (ostat == CAM_REQ_INPROG)
ahc_set_transaction_status(scb,
status);
cstat = ahc_get_transaction_status(scb);
if (cstat != CAM_REQ_CMP)
ahc_freeze_scb(scb);
if ((scb->flags & SCB_ACTIVE) == 0)
printf("Inactive SCB in Waiting List\n");
ahc_done(ahc, scb);
/* FALLTHROUGH */
}
case SEARCH_REMOVE:
next = ahc_rem_wscb(ahc, next, prev);
break;
case SEARCH_COUNT:
prev = next;
next = ahc_inb(ahc, SCB_NEXT);
break;
}
} else {
prev = next;
next = ahc_inb(ahc, SCB_NEXT);
}
}
ahc_outb(ahc, SCBPTR, curscbptr);
found += ahc_search_untagged_queues(ahc, /*ahc_io_ctx_t*/NULL, target,
channel, lun, status, action);
if (action == SEARCH_COMPLETE)
ahc_release_untagged_queues(ahc);
return (found);
}
int
ahc_search_untagged_queues(struct ahc_softc *ahc, ahc_io_ctx_t ctx,
int target, char channel, int lun, uint32_t status,
ahc_search_action action)
{
struct scb *scb;
int maxtarget;
int found;
int i;
if (action == SEARCH_COMPLETE) {
/*
* Don't attempt to run any queued untagged transactions
* until we are done with the abort process.
*/
ahc_freeze_untagged_queues(ahc);
}
found = 0;
i = 0;
if ((ahc->flags & AHC_SCB_BTT) == 0) {
maxtarget = 16;
if (target != CAM_TARGET_WILDCARD) {
i = target;
if (channel == 'B')
i += 8;
maxtarget = i + 1;
}
} else {
maxtarget = 0;
}
for (; i < maxtarget; i++) {
struct scb_tailq *untagged_q;
struct scb *next_scb;
untagged_q = &(ahc->untagged_queues[i]);
next_scb = TAILQ_FIRST(untagged_q);
while (next_scb != NULL) {
scb = next_scb;
next_scb = TAILQ_NEXT(scb, links.tqe);
/*
* The head of the list may be the currently
* active untagged command for a device.
* We're only searching for commands that
* have not been started. A transaction
* marked active but still in the qinfifo
* is removed by the qinfifo scanning code
* above.
*/
if ((scb->flags & SCB_ACTIVE) != 0)
continue;
if (ahc_match_scb(ahc, scb, target, channel, lun,
SCB_LIST_NULL, ROLE_INITIATOR) == 0
|| (ctx != NULL && ctx != scb->io_ctx))
continue;
/*
* We found an scb that needs to be acted on.
*/
found++;
switch (action) {
case SEARCH_COMPLETE:
{
cam_status ostat;
cam_status cstat;
ostat = ahc_get_transaction_status(scb);
if (ostat == CAM_REQ_INPROG)
ahc_set_transaction_status(scb, status);
cstat = ahc_get_transaction_status(scb);
if (cstat != CAM_REQ_CMP)
ahc_freeze_scb(scb);
if ((scb->flags & SCB_ACTIVE) == 0)
printf("Inactive SCB in untaggedQ\n");
ahc_done(ahc, scb);
break;
}
case SEARCH_REMOVE:
scb->flags &= ~SCB_UNTAGGEDQ;
TAILQ_REMOVE(untagged_q, scb, links.tqe);
break;
case SEARCH_COUNT:
break;
}
}
}
if (action == SEARCH_COMPLETE)
ahc_release_untagged_queues(ahc);
return (found);
}
int
ahc_search_disc_list(struct ahc_softc *ahc, int target, char channel,
int lun, u_int tag, int stop_on_first, int remove,
int save_state)
{
struct scb *scbp;
u_int next;
u_int prev;
u_int count;
u_int active_scb;
count = 0;
next = ahc_inb(ahc, DISCONNECTED_SCBH);
prev = SCB_LIST_NULL;
if (save_state) {
/* restore this when we're done */
active_scb = ahc_inb(ahc, SCBPTR);
} else
/* Silence compiler */
active_scb = SCB_LIST_NULL;
while (next != SCB_LIST_NULL) {
u_int scb_index;
ahc_outb(ahc, SCBPTR, next);
scb_index = ahc_inb(ahc, SCB_TAG);
if (scb_index >= ahc->scb_data->numscbs) {
printf("Disconnected List inconsistency. "
"SCB index == %d, yet numscbs == %d.",
scb_index, ahc->scb_data->numscbs);
ahc_dump_card_state(ahc);
panic("for safety");
}
if (next == prev) {
panic("Disconnected List Loop. "
"cur SCBPTR == %x, prev SCBPTR == %x.",
next, prev);
}
scbp = ahc_lookup_scb(ahc, scb_index);
if (ahc_match_scb(ahc, scbp, target, channel, lun,
tag, ROLE_INITIATOR)) {
count++;
if (remove) {
next =
ahc_rem_scb_from_disc_list(ahc, prev, next);
} else {
prev = next;
next = ahc_inb(ahc, SCB_NEXT);
}
if (stop_on_first)
break;
} else {
prev = next;
next = ahc_inb(ahc, SCB_NEXT);
}
}
if (save_state)
ahc_outb(ahc, SCBPTR, active_scb);
return (count);
}
/*
* Remove an SCB from the on chip list of disconnected transactions.
* This is empty/unused if we are not performing SCB paging.
*/
static u_int
ahc_rem_scb_from_disc_list(struct ahc_softc *ahc, u_int prev, u_int scbptr)
{
u_int next;
ahc_outb(ahc, SCBPTR, scbptr);
next = ahc_inb(ahc, SCB_NEXT);
ahc_outb(ahc, SCB_CONTROL, 0);
ahc_add_curscb_to_free_list(ahc);
if (prev != SCB_LIST_NULL) {
ahc_outb(ahc, SCBPTR, prev);
ahc_outb(ahc, SCB_NEXT, next);
} else
ahc_outb(ahc, DISCONNECTED_SCBH, next);
return (next);
}
/*
* Add the SCB as selected by SCBPTR onto the on chip list of
* free hardware SCBs. This list is empty/unused if we are not
* performing SCB paging.
*/
static void
ahc_add_curscb_to_free_list(struct ahc_softc *ahc)
{
/*
* Invalidate the tag so that our abort
* routines don't think it's active.
*/
ahc_outb(ahc, SCB_TAG, SCB_LIST_NULL);
if ((ahc->flags & AHC_PAGESCBS) != 0) {
ahc_outb(ahc, SCB_NEXT, ahc_inb(ahc, FREE_SCBH));
ahc_outb(ahc, FREE_SCBH, ahc_inb(ahc, SCBPTR));
}
}
/*
* Manipulate the waiting for selection list and return the
* scb that follows the one that we remove.
*/
static u_int
ahc_rem_wscb(struct ahc_softc *ahc, u_int scbpos, u_int prev)
{
u_int curscb, next;
/*
* Select the SCB we want to abort and
* pull the next pointer out of it.
*/
curscb = ahc_inb(ahc, SCBPTR);
ahc_outb(ahc, SCBPTR, scbpos);
next = ahc_inb(ahc, SCB_NEXT);
/* Clear the necessary fields */
ahc_outb(ahc, SCB_CONTROL, 0);
ahc_add_curscb_to_free_list(ahc);
/* update the waiting list */
if (prev == SCB_LIST_NULL) {
/* First in the list */
ahc_outb(ahc, WAITING_SCBH, next);
/*
* Ensure we aren't attempting to perform
* selection for this entry.
*/
ahc_outb(ahc, SCSISEQ, (ahc_inb(ahc, SCSISEQ) & ~ENSELO));
} else {
/*
* Select the scb that pointed to us
* and update its next pointer.
*/
ahc_outb(ahc, SCBPTR, prev);
ahc_outb(ahc, SCB_NEXT, next);
}
/*
* Point us back at the original scb position.
*/
ahc_outb(ahc, SCBPTR, curscb);
return next;
}
/******************************** Error Handling ******************************/
/*
* Abort all SCBs that match the given description (target/channel/lun/tag),
* setting their status to the passed in status if the status has not already
* been modified from CAM_REQ_INPROG. This routine assumes that the sequencer
* is paused before it is called.
*/
static int
ahc_abort_scbs(struct ahc_softc *ahc, int target, char channel,
int lun, u_int tag, role_t role, uint32_t status)
{
struct scb *scbp;
struct scb *scbp_next;
u_int active_scb;
int i, j;
int maxtarget;
int minlun;
int maxlun;
int found;
/*
* Don't attempt to run any queued untagged transactions
* until we are done with the abort process.
*/
ahc_freeze_untagged_queues(ahc);
/* restore this when we're done */
active_scb = ahc_inb(ahc, SCBPTR);
found = ahc_search_qinfifo(ahc, target, channel, lun, SCB_LIST_NULL,
role, CAM_REQUEUE_REQ, SEARCH_COMPLETE);
/*
* Clean out the busy target table for any untagged commands.
*/
i = 0;
maxtarget = 16;
if (target != CAM_TARGET_WILDCARD) {
i = target;
if (channel == 'B')
i += 8;
maxtarget = i + 1;
}
if (lun == CAM_LUN_WILDCARD) {
/*
* Unless we are using an SCB based
* busy targets table, there is only
* one table entry for all luns of
* a target.
*/
minlun = 0;
maxlun = 1;
if ((ahc->flags & AHC_SCB_BTT) != 0)
maxlun = AHC_NUM_LUNS;
} else {
minlun = lun;
maxlun = lun + 1;
}
if (role != ROLE_TARGET) {
for (;i < maxtarget; i++) {
for (j = minlun;j < maxlun; j++) {
u_int scbid;
u_int tcl;
tcl = BUILD_TCL(i << 4, j);
scbid = ahc_index_busy_tcl(ahc, tcl);
scbp = ahc_lookup_scb(ahc, scbid);
if (scbp == NULL
|| ahc_match_scb(ahc, scbp, target, channel,
lun, tag, role) == 0)
continue;
ahc_unbusy_tcl(ahc, BUILD_TCL(i << 4, j));
}
}
/*
* Go through the disconnected list and remove any entries we
* have queued for completion, 0'ing their control byte too.
* We save the active SCB and restore it ourselves, so there
* is no reason for this search to restore it too.
*/
ahc_search_disc_list(ahc, target, channel, lun, tag,
/*stop_on_first*/FALSE, /*remove*/TRUE,
/*save_state*/FALSE);
}
/*
* Go through the hardware SCB array looking for commands that
* were active but not on any list. In some cases, these remnants
* might not still have mappings in the scbindex array (e.g. unexpected
* bus free with the same scb queued for an abort). Don't hold this
* against them.
*/
for (i = 0; i < ahc->scb_data->maxhscbs; i++) {
u_int scbid;
ahc_outb(ahc, SCBPTR, i);
scbid = ahc_inb(ahc, SCB_TAG);
scbp = ahc_lookup_scb(ahc, scbid);
if ((scbp == NULL && scbid != SCB_LIST_NULL)
|| (scbp != NULL
&& ahc_match_scb(ahc, scbp, target, channel, lun, tag, role)))
ahc_add_curscb_to_free_list(ahc);
}
/*
* Go through the pending CCB list and look for
* commands for this target that are still active.
* These are other tagged commands that were
* disconnected when the reset occurred.
*/
scbp_next = LIST_FIRST(&ahc->pending_scbs);
while (scbp_next != NULL) {
scbp = scbp_next;
scbp_next = LIST_NEXT(scbp, pending_links);
if (ahc_match_scb(ahc, scbp, target, channel, lun, tag, role)) {
cam_status ostat;
ostat = ahc_get_transaction_status(scbp);
if (ostat == CAM_REQ_INPROG)
ahc_set_transaction_status(scbp, status);
if (ahc_get_transaction_status(scbp) != CAM_REQ_CMP)
ahc_freeze_scb(scbp);
if ((scbp->flags & SCB_ACTIVE) == 0)
printf("Inactive SCB on pending list\n");
ahc_done(ahc, scbp);
found++;
}
}
ahc_outb(ahc, SCBPTR, active_scb);
ahc_platform_abort_scbs(ahc, target, channel, lun, tag, role, status);
ahc_release_untagged_queues(ahc);
return found;
}
static void
ahc_reset_current_bus(struct ahc_softc *ahc)
{
uint8_t scsiseq;
ahc_outb(ahc, SIMODE1, ahc_inb(ahc, SIMODE1) & ~ENSCSIRST);
scsiseq = ahc_inb(ahc, SCSISEQ);
ahc_outb(ahc, SCSISEQ, scsiseq | SCSIRSTO);
ahc_flush_device_writes(ahc);
ahc_delay(AHC_BUSRESET_DELAY);
/* Turn off the bus reset */
ahc_outb(ahc, SCSISEQ, scsiseq & ~SCSIRSTO);
ahc_clear_intstat(ahc);
/* Re-enable reset interrupts */
ahc_outb(ahc, SIMODE1, ahc_inb(ahc, SIMODE1) | ENSCSIRST);
}
int
ahc_reset_channel(struct ahc_softc *ahc, char channel, int initiate_reset)
{
struct ahc_devinfo devinfo;
u_int initiator, target, max_scsiid;
u_int sblkctl;
u_int scsiseq;
u_int simode1;
int found;
int restart_needed;
char cur_channel;
ahc->pending_device = NULL;
ahc_compile_devinfo(&devinfo,
CAM_TARGET_WILDCARD,
CAM_TARGET_WILDCARD,
CAM_LUN_WILDCARD,
channel, ROLE_UNKNOWN);
ahc_pause(ahc);
/* Make sure the sequencer is in a safe location. */
ahc_clear_critical_section(ahc);
/*
* Run our command complete fifos to ensure that we perform
* completion processing on any commands that 'completed'
* before the reset occurred.
*/
ahc_run_qoutfifo(ahc);
#ifdef AHC_TARGET_MODE
/*
* XXX - In Twin mode, the tqinfifo may have commands
* for an unaffected channel in it. However, if
* we have run out of ATIO resources to drain that
* queue, we may not get them all out here. Further,
* the blocked transactions for the reset channel
* should just be killed off, irrespecitve of whether
* we are blocked on ATIO resources. Write a routine
* to compact the tqinfifo appropriately.
*/
if ((ahc->flags & AHC_TARGETROLE) != 0) {
ahc_run_tqinfifo(ahc, /*paused*/TRUE);
}
#endif
/*
* Reset the bus if we are initiating this reset
*/
sblkctl = ahc_inb(ahc, SBLKCTL);
cur_channel = 'A';
if ((ahc->features & AHC_TWIN) != 0
&& ((sblkctl & SELBUSB) != 0))
cur_channel = 'B';
scsiseq = ahc_inb(ahc, SCSISEQ_TEMPLATE);
if (cur_channel != channel) {
/* Case 1: Command for another bus is active
* Stealthily reset the other bus without
* upsetting the current bus.
*/
ahc_outb(ahc, SBLKCTL, sblkctl ^ SELBUSB);
simode1 = ahc_inb(ahc, SIMODE1) & ~(ENBUSFREE|ENSCSIRST);
#ifdef AHC_TARGET_MODE
/*
* Bus resets clear ENSELI, so we cannot
* defer re-enabling bus reset interrupts
* if we are in target mode.
*/
if ((ahc->flags & AHC_TARGETROLE) != 0)
simode1 |= ENSCSIRST;
#endif
ahc_outb(ahc, SIMODE1, simode1);
if (initiate_reset)
ahc_reset_current_bus(ahc);
ahc_clear_intstat(ahc);
ahc_outb(ahc, SCSISEQ, scsiseq & (ENSELI|ENRSELI|ENAUTOATNP));
ahc_outb(ahc, SBLKCTL, sblkctl);
restart_needed = FALSE;
} else {
/* Case 2: A command from this bus is active or we're idle */
simode1 = ahc_inb(ahc, SIMODE1) & ~(ENBUSFREE|ENSCSIRST);
#ifdef AHC_TARGET_MODE
/*
* Bus resets clear ENSELI, so we cannot
* defer re-enabling bus reset interrupts
* if we are in target mode.
*/
if ((ahc->flags & AHC_TARGETROLE) != 0)
simode1 |= ENSCSIRST;
#endif
ahc_outb(ahc, SIMODE1, simode1);
if (initiate_reset)
ahc_reset_current_bus(ahc);
ahc_clear_intstat(ahc);
ahc_outb(ahc, SCSISEQ, scsiseq & (ENSELI|ENRSELI|ENAUTOATNP));
restart_needed = TRUE;
}
/*
* Clean up all the state information for the
* pending transactions on this bus.
*/
found = ahc_abort_scbs(ahc, CAM_TARGET_WILDCARD, channel,
CAM_LUN_WILDCARD, SCB_LIST_NULL,
ROLE_UNKNOWN, CAM_SCSI_BUS_RESET);
max_scsiid = (ahc->features & AHC_WIDE) ? 15 : 7;
#ifdef AHC_TARGET_MODE
/*
* Send an immediate notify ccb to all target more peripheral
* drivers affected by this action.
*/
for (target = 0; target <= max_scsiid; target++) {
struct ahc_tmode_tstate* tstate;
u_int lun;
tstate = ahc->enabled_targets[target];
if (tstate == NULL)
continue;
for (lun = 0; lun < AHC_NUM_LUNS; lun++) {
struct ahc_tmode_lstate* lstate;
lstate = tstate->enabled_luns[lun];
if (lstate == NULL)
continue;
ahc_queue_lstate_event(ahc, lstate, CAM_TARGET_WILDCARD,
EVENT_TYPE_BUS_RESET, /*arg*/0);
ahc_send_lstate_events(ahc, lstate);
}
}
#endif
/* Notify the XPT that a bus reset occurred */
ahc_send_async(ahc, devinfo.channel, CAM_TARGET_WILDCARD,
CAM_LUN_WILDCARD, AC_BUS_RESET);
/*
* Revert to async/narrow transfers until we renegotiate.
*/
for (target = 0; target <= max_scsiid; target++) {
if (ahc->enabled_targets[target] == NULL)
continue;
for (initiator = 0; initiator <= max_scsiid; initiator++) {
struct ahc_devinfo devinfo;
ahc_compile_devinfo(&devinfo, target, initiator,
CAM_LUN_WILDCARD,
channel, ROLE_UNKNOWN);
ahc_set_width(ahc, &devinfo, MSG_EXT_WDTR_BUS_8_BIT,
AHC_TRANS_CUR, /*paused*/TRUE);
ahc_set_syncrate(ahc, &devinfo, /*syncrate*/NULL,
/*period*/0, /*offset*/0,
/*ppr_options*/0, AHC_TRANS_CUR,
/*paused*/TRUE);
}
}
if (restart_needed)
ahc_restart(ahc);
else
ahc_unpause(ahc);
return found;
}
/***************************** Residual Processing ****************************/
/*
* Calculate the residual for a just completed SCB.
*/
static void
ahc_calc_residual(struct ahc_softc *ahc, struct scb *scb)
{
struct hardware_scb *hscb;
struct status_pkt *spkt;
uint32_t sgptr;
uint32_t resid_sgptr;
uint32_t resid;
/*
* 5 cases.
* 1) No residual.
* SG_RESID_VALID clear in sgptr.
* 2) Transferless command
* 3) Never performed any transfers.
* sgptr has SG_FULL_RESID set.
* 4) No residual but target did not
* save data pointers after the
* last transfer, so sgptr was
* never updated.
* 5) We have a partial residual.
* Use residual_sgptr to determine
* where we are.
*/
hscb = scb->hscb;
sgptr = ahc_le32toh(hscb->sgptr);
if ((sgptr & SG_RESID_VALID) == 0)
/* Case 1 */
return;
sgptr &= ~SG_RESID_VALID;
if ((sgptr & SG_LIST_NULL) != 0)
/* Case 2 */
return;
spkt = &hscb->shared_data.status;
resid_sgptr = ahc_le32toh(spkt->residual_sg_ptr);
if ((sgptr & SG_FULL_RESID) != 0) {
/* Case 3 */
resid = ahc_get_transfer_length(scb);
} else if ((resid_sgptr & SG_LIST_NULL) != 0) {
/* Case 4 */
return;
} else if ((resid_sgptr & ~SG_PTR_MASK) != 0) {
panic("Bogus resid sgptr value 0x%x\n", resid_sgptr);
} else {
struct ahc_dma_seg *sg;
/*
* Remainder of the SG where the transfer
* stopped.
*/
resid = ahc_le32toh(spkt->residual_datacnt) & AHC_SG_LEN_MASK;
sg = ahc_sg_bus_to_virt(scb, resid_sgptr & SG_PTR_MASK);
/* The residual sg_ptr always points to the next sg */
sg--;
/*
* Add up the contents of all residual
* SG segments that are after the SG where
* the transfer stopped.
*/
while ((ahc_le32toh(sg->len) & AHC_DMA_LAST_SEG) == 0) {
sg++;
resid += ahc_le32toh(sg->len) & AHC_SG_LEN_MASK;
}
}
if ((scb->flags & SCB_SENSE) == 0)
ahc_set_residual(scb, resid);
else
ahc_set_sense_residual(scb, resid);
#ifdef AHC_DEBUG
if ((ahc_debug & AHC_SHOW_MISC) != 0) {
ahc_print_path(ahc, scb);
printf("Handled %sResidual of %d bytes\n",
(scb->flags & SCB_SENSE) ? "Sense " : "", resid);
}
#endif
}
/******************************* Target Mode **********************************/
#ifdef AHC_TARGET_MODE
/*
* Add a target mode event to this lun's queue
*/
static void
ahc_queue_lstate_event(struct ahc_softc *ahc, struct ahc_tmode_lstate *lstate,
u_int initiator_id, u_int event_type, u_int event_arg)
{
struct ahc_tmode_event *event;
int pending;
xpt_freeze_devq(lstate->path, /*count*/1);
if (lstate->event_w_idx >= lstate->event_r_idx)
pending = lstate->event_w_idx - lstate->event_r_idx;
else
pending = AHC_TMODE_EVENT_BUFFER_SIZE + 1
- (lstate->event_r_idx - lstate->event_w_idx);
if (event_type == EVENT_TYPE_BUS_RESET
|| event_type == MSG_BUS_DEV_RESET) {
/*
* Any earlier events are irrelevant, so reset our buffer.
* This has the effect of allowing us to deal with reset
* floods (an external device holding down the reset line)
* without losing the event that is really interesting.
*/
lstate->event_r_idx = 0;
lstate->event_w_idx = 0;
xpt_release_devq(lstate->path, pending, /*runqueue*/FALSE);
}
if (pending == AHC_TMODE_EVENT_BUFFER_SIZE) {
xpt_print_path(lstate->path);
printf("immediate event %x:%x lost\n",
lstate->event_buffer[lstate->event_r_idx].event_type,
lstate->event_buffer[lstate->event_r_idx].event_arg);
lstate->event_r_idx++;
if (lstate->event_r_idx == AHC_TMODE_EVENT_BUFFER_SIZE)
lstate->event_r_idx = 0;
xpt_release_devq(lstate->path, /*count*/1, /*runqueue*/FALSE);
}
event = &lstate->event_buffer[lstate->event_w_idx];
event->initiator_id = initiator_id;
event->event_type = event_type;
event->event_arg = event_arg;
lstate->event_w_idx++;
if (lstate->event_w_idx == AHC_TMODE_EVENT_BUFFER_SIZE)
lstate->event_w_idx = 0;
}
/*
* Send any target mode events queued up waiting
* for immediate notify resources.
*/
void
ahc_send_lstate_events(struct ahc_softc *ahc, struct ahc_tmode_lstate *lstate)
{
struct ccb_hdr *ccbh;
struct ccb_immed_notify *inot;
while (lstate->event_r_idx != lstate->event_w_idx
&& (ccbh = SLIST_FIRST(&lstate->immed_notifies)) != NULL) {
struct ahc_tmode_event *event;
event = &lstate->event_buffer[lstate->event_r_idx];
SLIST_REMOVE_HEAD(&lstate->immed_notifies, sim_links.sle);
inot = (struct ccb_immed_notify *)ccbh;
switch (event->event_type) {
case EVENT_TYPE_BUS_RESET:
ccbh->status = CAM_SCSI_BUS_RESET|CAM_DEV_QFRZN;
break;
default:
ccbh->status = CAM_MESSAGE_RECV|CAM_DEV_QFRZN;
inot->message_args[0] = event->event_type;
inot->message_args[1] = event->event_arg;
break;
}
inot->initiator_id = event->initiator_id;
inot->sense_len = 0;
xpt_done((union ccb *)inot);
lstate->event_r_idx++;
if (lstate->event_r_idx == AHC_TMODE_EVENT_BUFFER_SIZE)
lstate->event_r_idx = 0;
}
}
#endif
/******************** Sequencer Program Patching/Download *********************/
#ifdef AHC_DUMP_SEQ
void
ahc_dumpseq(struct ahc_softc* ahc)
{
int i;
ahc_outb(ahc, SEQCTL, PERRORDIS|FAILDIS|FASTMODE|LOADRAM);
ahc_outb(ahc, SEQADDR0, 0);
ahc_outb(ahc, SEQADDR1, 0);
for (i = 0; i < ahc->instruction_ram_size; i++) {
uint8_t ins_bytes[4];
ahc_insb(ahc, SEQRAM, ins_bytes, 4);
printf("0x%08x\n", ins_bytes[0] << 24
| ins_bytes[1] << 16
| ins_bytes[2] << 8
| ins_bytes[3]);
}
}
#endif
static int
ahc_loadseq(struct ahc_softc *ahc)
{
struct cs cs_table[num_critical_sections];
u_int begin_set[num_critical_sections];
u_int end_set[num_critical_sections];
const struct patch *cur_patch;
u_int cs_count;
u_int cur_cs;
u_int i;
u_int skip_addr;
u_int sg_prefetch_cnt;
int downloaded;
uint8_t download_consts[7];
/*
* Start out with 0 critical sections
* that apply to this firmware load.
*/
cs_count = 0;
cur_cs = 0;
memset(begin_set, 0, sizeof(begin_set));
memset(end_set, 0, sizeof(end_set));
/* Setup downloadable constant table */
download_consts[QOUTFIFO_OFFSET] = 0;
if (ahc->targetcmds != NULL)
download_consts[QOUTFIFO_OFFSET] += 32;
download_consts[QINFIFO_OFFSET] = download_consts[QOUTFIFO_OFFSET] + 1;
download_consts[CACHESIZE_MASK] = ahc->pci_cachesize - 1;
download_consts[INVERTED_CACHESIZE_MASK] = ~(ahc->pci_cachesize - 1);
sg_prefetch_cnt = ahc->pci_cachesize;
if (sg_prefetch_cnt < (2 * sizeof(struct ahc_dma_seg)))
sg_prefetch_cnt = 2 * sizeof(struct ahc_dma_seg);
download_consts[SG_PREFETCH_CNT] = sg_prefetch_cnt;
download_consts[SG_PREFETCH_ALIGN_MASK] = ~(sg_prefetch_cnt - 1);
download_consts[SG_PREFETCH_ADDR_MASK] = (sg_prefetch_cnt - 1);
cur_patch = patches;
downloaded = 0;
skip_addr = 0;
ahc_outb(ahc, SEQCTL, PERRORDIS|FAILDIS|FASTMODE|LOADRAM);
ahc_outb(ahc, SEQADDR0, 0);
ahc_outb(ahc, SEQADDR1, 0);
for (i = 0; i < sizeof(seqprog)/4; i++) {
if (ahc_check_patch(ahc, &cur_patch, i, &skip_addr) == 0) {
/*
* Don't download this instruction as it
* is in a patch that was removed.
*/
continue;
}
if (downloaded == ahc->instruction_ram_size) {
/*
* We're about to exceed the instruction
* storage capacity for this chip. Fail
* the load.
*/
printf("\n%s: Program too large for instruction memory "
"size of %d!\n", ahc_name(ahc),
ahc->instruction_ram_size);
return (ENOMEM);
}
/*
* Move through the CS table until we find a CS
* that might apply to this instruction.
*/
for (; cur_cs < num_critical_sections; cur_cs++) {
if (critical_sections[cur_cs].end <= i) {
if (begin_set[cs_count] == TRUE
&& end_set[cs_count] == FALSE) {
cs_table[cs_count].end = downloaded;
end_set[cs_count] = TRUE;
cs_count++;
}
continue;
}
if (critical_sections[cur_cs].begin <= i
&& begin_set[cs_count] == FALSE) {
cs_table[cs_count].begin = downloaded;
begin_set[cs_count] = TRUE;
}
break;
}
ahc_download_instr(ahc, i, download_consts);
downloaded++;
}
ahc->num_critical_sections = cs_count;
if (cs_count != 0) {
cs_count *= sizeof(struct cs);
ahc->critical_sections = malloc(cs_count, M_DEVBUF, M_NOWAIT);
if (ahc->critical_sections == NULL)
panic("ahc_loadseq: Could not malloc");
memcpy(ahc->critical_sections, cs_table, cs_count);
}
ahc_outb(ahc, SEQCTL, PERRORDIS|FAILDIS|FASTMODE);
if (bootverbose) {
printf(" %d instructions downloaded\n", downloaded);
printf("%s: Features 0x%x, Bugs 0x%x, Flags 0x%x\n",
ahc_name(ahc), ahc->features, ahc->bugs, ahc->flags);
}
return (0);
}
static int
ahc_check_patch(struct ahc_softc *ahc, const struct patch **start_patch,
u_int start_instr, u_int *skip_addr)
{
const struct patch *cur_patch;
const struct patch *last_patch;
u_int num_patches;
num_patches = ARRAY_SIZE(patches);
last_patch = &patches[num_patches];
cur_patch = *start_patch;
while (cur_patch < last_patch && start_instr == cur_patch->begin) {
if (cur_patch->patch_func(ahc) == 0) {
/* Start rejecting code */
*skip_addr = start_instr + cur_patch->skip_instr;
cur_patch += cur_patch->skip_patch;
} else {
/* Accepted this patch. Advance to the next
* one and wait for our intruction pointer to
* hit this point.
*/
cur_patch++;
}
}
*start_patch = cur_patch;
if (start_instr < *skip_addr)
/* Still skipping */
return (0);
return (1);
}
static void
ahc_download_instr(struct ahc_softc *ahc, u_int instrptr, uint8_t *dconsts)
{
union ins_formats instr;
struct ins_format1 *fmt1_ins;
struct ins_format3 *fmt3_ins;
u_int opcode;
/*
* The firmware is always compiled into a little endian format.
*/
instr.integer = ahc_le32toh(*(uint32_t*)&seqprog[instrptr * 4]);
fmt1_ins = &instr.format1;
fmt3_ins = NULL;
/* Pull the opcode */
opcode = instr.format1.opcode;
switch (opcode) {
case AIC_OP_JMP:
case AIC_OP_JC:
case AIC_OP_JNC:
case AIC_OP_CALL:
case AIC_OP_JNE:
case AIC_OP_JNZ:
case AIC_OP_JE:
case AIC_OP_JZ:
{
const struct patch *cur_patch;
int address_offset;
u_int address;
u_int skip_addr;
u_int i;
fmt3_ins = &instr.format3;
address_offset = 0;
address = fmt3_ins->address;
cur_patch = patches;
skip_addr = 0;
for (i = 0; i < address;) {
ahc_check_patch(ahc, &cur_patch, i, &skip_addr);
if (skip_addr > i) {
int end_addr;
end_addr = min(address, skip_addr);
address_offset += end_addr - i;
i = skip_addr;
} else {
i++;
}
}
address -= address_offset;
fmt3_ins->address = address;
/* FALLTHROUGH */
}
case AIC_OP_OR:
case AIC_OP_AND:
case AIC_OP_XOR:
case AIC_OP_ADD:
case AIC_OP_ADC:
case AIC_OP_BMOV:
if (fmt1_ins->parity != 0) {
fmt1_ins->immediate = dconsts[fmt1_ins->immediate];
}
fmt1_ins->parity = 0;
if ((ahc->features & AHC_CMD_CHAN) == 0
&& opcode == AIC_OP_BMOV) {
/*
* Block move was added at the same time
* as the command channel. Verify that
* this is only a move of a single element
* and convert the BMOV to a MOV
* (AND with an immediate of FF).
*/
if (fmt1_ins->immediate != 1)
panic("%s: BMOV not supported\n",
ahc_name(ahc));
fmt1_ins->opcode = AIC_OP_AND;
fmt1_ins->immediate = 0xff;
}
/* FALLTHROUGH */
case AIC_OP_ROL:
if ((ahc->features & AHC_ULTRA2) != 0) {
int i, count;
/* Calculate odd parity for the instruction */
for (i = 0, count = 0; i < 31; i++) {
uint32_t mask;
mask = 0x01 << i;
if ((instr.integer & mask) != 0)
count++;
}
if ((count & 0x01) == 0)
instr.format1.parity = 1;
} else {
/* Compress the instruction for older sequencers */
if (fmt3_ins != NULL) {
instr.integer =
fmt3_ins->immediate
| (fmt3_ins->source << 8)
| (fmt3_ins->address << 16)
| (fmt3_ins->opcode << 25);
} else {
instr.integer =
fmt1_ins->immediate
| (fmt1_ins->source << 8)
| (fmt1_ins->destination << 16)
| (fmt1_ins->ret << 24)
| (fmt1_ins->opcode << 25);
}
}
/* The sequencer is a little endian cpu */
instr.integer = ahc_htole32(instr.integer);
ahc_outsb(ahc, SEQRAM, instr.bytes, 4);
break;
default:
panic("Unknown opcode encountered in seq program");
break;
}
}
int
ahc_print_register(const ahc_reg_parse_entry_t *table, u_int num_entries,
const char *name, u_int address, u_int value,
u_int *cur_column, u_int wrap_point)
{
int printed;
u_int printed_mask;
if (cur_column != NULL && *cur_column >= wrap_point) {
printf("\n");
*cur_column = 0;
}
printed = printf("%s[0x%x]", name, value);
if (table == NULL) {
printed += printf(" ");
*cur_column += printed;
return (printed);
}
printed_mask = 0;
while (printed_mask != 0xFF) {
int entry;
for (entry = 0; entry < num_entries; entry++) {
if (((value & table[entry].mask)
!= table[entry].value)
|| ((printed_mask & table[entry].mask)
== table[entry].mask))
continue;
printed += printf("%s%s",
printed_mask == 0 ? ":(" : "|",
table[entry].name);
printed_mask |= table[entry].mask;
break;
}
if (entry >= num_entries)
break;
}
if (printed_mask != 0)
printed += printf(") ");
else
printed += printf(" ");
if (cur_column != NULL)
*cur_column += printed;
return (printed);
}
void
ahc_dump_card_state(struct ahc_softc *ahc)
{
struct scb *scb;
struct scb_tailq *untagged_q;
u_int cur_col;
int paused;
int target;
int maxtarget;
int i;
uint8_t last_phase;
uint8_t qinpos;
uint8_t qintail;
uint8_t qoutpos;
uint8_t scb_index;
uint8_t saved_scbptr;
if (ahc_is_paused(ahc)) {
paused = 1;
} else {
paused = 0;
ahc_pause(ahc);
}
saved_scbptr = ahc_inb(ahc, SCBPTR);
last_phase = ahc_inb(ahc, LASTPHASE);
printf(">>>>>>>>>>>>>>>>>> Dump Card State Begins <<<<<<<<<<<<<<<<<\n"
"%s: Dumping Card State %s, at SEQADDR 0x%x\n",
ahc_name(ahc), ahc_lookup_phase_entry(last_phase)->phasemsg,
ahc_inb(ahc, SEQADDR0) | (ahc_inb(ahc, SEQADDR1) << 8));
if (paused)
printf("Card was paused\n");
printf("ACCUM = 0x%x, SINDEX = 0x%x, DINDEX = 0x%x, ARG_2 = 0x%x\n",
ahc_inb(ahc, ACCUM), ahc_inb(ahc, SINDEX), ahc_inb(ahc, DINDEX),
ahc_inb(ahc, ARG_2));
printf("HCNT = 0x%x SCBPTR = 0x%x\n", ahc_inb(ahc, HCNT),
ahc_inb(ahc, SCBPTR));
cur_col = 0;
if ((ahc->features & AHC_DT) != 0)
ahc_scsiphase_print(ahc_inb(ahc, SCSIPHASE), &cur_col, 50);
ahc_scsisigi_print(ahc_inb(ahc, SCSISIGI), &cur_col, 50);
ahc_error_print(ahc_inb(ahc, ERROR), &cur_col, 50);
ahc_scsibusl_print(ahc_inb(ahc, SCSIBUSL), &cur_col, 50);
ahc_lastphase_print(ahc_inb(ahc, LASTPHASE), &cur_col, 50);
ahc_scsiseq_print(ahc_inb(ahc, SCSISEQ), &cur_col, 50);
ahc_sblkctl_print(ahc_inb(ahc, SBLKCTL), &cur_col, 50);
ahc_scsirate_print(ahc_inb(ahc, SCSIRATE), &cur_col, 50);
ahc_seqctl_print(ahc_inb(ahc, SEQCTL), &cur_col, 50);
ahc_seq_flags_print(ahc_inb(ahc, SEQ_FLAGS), &cur_col, 50);
ahc_sstat0_print(ahc_inb(ahc, SSTAT0), &cur_col, 50);
ahc_sstat1_print(ahc_inb(ahc, SSTAT1), &cur_col, 50);
ahc_sstat2_print(ahc_inb(ahc, SSTAT2), &cur_col, 50);
ahc_sstat3_print(ahc_inb(ahc, SSTAT3), &cur_col, 50);
ahc_simode0_print(ahc_inb(ahc, SIMODE0), &cur_col, 50);
ahc_simode1_print(ahc_inb(ahc, SIMODE1), &cur_col, 50);
ahc_sxfrctl0_print(ahc_inb(ahc, SXFRCTL0), &cur_col, 50);
ahc_dfcntrl_print(ahc_inb(ahc, DFCNTRL), &cur_col, 50);
ahc_dfstatus_print(ahc_inb(ahc, DFSTATUS), &cur_col, 50);
if (cur_col != 0)
printf("\n");
printf("STACK:");
for (i = 0; i < STACK_SIZE; i++)
printf(" 0x%x", ahc_inb(ahc, STACK)|(ahc_inb(ahc, STACK) << 8));
printf("\nSCB count = %d\n", ahc->scb_data->numscbs);
printf("Kernel NEXTQSCB = %d\n", ahc->next_queued_scb->hscb->tag);
printf("Card NEXTQSCB = %d\n", ahc_inb(ahc, NEXT_QUEUED_SCB));
/* QINFIFO */
printf("QINFIFO entries: ");
if ((ahc->features & AHC_QUEUE_REGS) != 0) {
qinpos = ahc_inb(ahc, SNSCB_QOFF);
ahc_outb(ahc, SNSCB_QOFF, qinpos);
} else
qinpos = ahc_inb(ahc, QINPOS);
qintail = ahc->qinfifonext;
while (qinpos != qintail) {
printf("%d ", ahc->qinfifo[qinpos]);
qinpos++;
}
printf("\n");
printf("Waiting Queue entries: ");
scb_index = ahc_inb(ahc, WAITING_SCBH);
i = 0;
while (scb_index != SCB_LIST_NULL && i++ < 256) {
ahc_outb(ahc, SCBPTR, scb_index);
printf("%d:%d ", scb_index, ahc_inb(ahc, SCB_TAG));
scb_index = ahc_inb(ahc, SCB_NEXT);
}
printf("\n");
printf("Disconnected Queue entries: ");
scb_index = ahc_inb(ahc, DISCONNECTED_SCBH);
i = 0;
while (scb_index != SCB_LIST_NULL && i++ < 256) {
ahc_outb(ahc, SCBPTR, scb_index);
printf("%d:%d ", scb_index, ahc_inb(ahc, SCB_TAG));
scb_index = ahc_inb(ahc, SCB_NEXT);
}
printf("\n");
ahc_sync_qoutfifo(ahc, BUS_DMASYNC_POSTREAD);
printf("QOUTFIFO entries: ");
qoutpos = ahc->qoutfifonext;
i = 0;
while (ahc->qoutfifo[qoutpos] != SCB_LIST_NULL && i++ < 256) {
printf("%d ", ahc->qoutfifo[qoutpos]);
qoutpos++;
}
printf("\n");
printf("Sequencer Free SCB List: ");
scb_index = ahc_inb(ahc, FREE_SCBH);
i = 0;
while (scb_index != SCB_LIST_NULL && i++ < 256) {
ahc_outb(ahc, SCBPTR, scb_index);
printf("%d ", scb_index);
scb_index = ahc_inb(ahc, SCB_NEXT);
}
printf("\n");
printf("Sequencer SCB Info: ");
for (i = 0; i < ahc->scb_data->maxhscbs; i++) {
ahc_outb(ahc, SCBPTR, i);
cur_col = printf("\n%3d ", i);
ahc_scb_control_print(ahc_inb(ahc, SCB_CONTROL), &cur_col, 60);
ahc_scb_scsiid_print(ahc_inb(ahc, SCB_SCSIID), &cur_col, 60);
ahc_scb_lun_print(ahc_inb(ahc, SCB_LUN), &cur_col, 60);
ahc_scb_tag_print(ahc_inb(ahc, SCB_TAG), &cur_col, 60);
}
printf("\n");
printf("Pending list: ");
i = 0;
LIST_FOREACH(scb, &ahc->pending_scbs, pending_links) {
if (i++ > 256)
break;
cur_col = printf("\n%3d ", scb->hscb->tag);
ahc_scb_control_print(scb->hscb->control, &cur_col, 60);
ahc_scb_scsiid_print(scb->hscb->scsiid, &cur_col, 60);
ahc_scb_lun_print(scb->hscb->lun, &cur_col, 60);
if ((ahc->flags & AHC_PAGESCBS) == 0) {
ahc_outb(ahc, SCBPTR, scb->hscb->tag);
printf("(");
ahc_scb_control_print(ahc_inb(ahc, SCB_CONTROL),
&cur_col, 60);
ahc_scb_tag_print(ahc_inb(ahc, SCB_TAG), &cur_col, 60);
printf(")");
}
}
printf("\n");
printf("Kernel Free SCB list: ");
i = 0;
SLIST_FOREACH(scb, &ahc->scb_data->free_scbs, links.sle) {
if (i++ > 256)
break;
printf("%d ", scb->hscb->tag);
}
printf("\n");
maxtarget = (ahc->features & (AHC_WIDE|AHC_TWIN)) ? 15 : 7;
for (target = 0; target <= maxtarget; target++) {
untagged_q = &ahc->untagged_queues[target];
if (TAILQ_FIRST(untagged_q) == NULL)
continue;
printf("Untagged Q(%d): ", target);
i = 0;
TAILQ_FOREACH(scb, untagged_q, links.tqe) {
if (i++ > 256)
break;
printf("%d ", scb->hscb->tag);
}
printf("\n");
}
ahc_platform_dump_card_state(ahc);
printf("\n<<<<<<<<<<<<<<<<< Dump Card State Ends >>>>>>>>>>>>>>>>>>\n");
ahc_outb(ahc, SCBPTR, saved_scbptr);
if (paused == 0)
ahc_unpause(ahc);
}
/************************* Target Mode ****************************************/
#ifdef AHC_TARGET_MODE
cam_status
ahc_find_tmode_devs(struct ahc_softc *ahc, struct cam_sim *sim, union ccb *ccb,
struct ahc_tmode_tstate **tstate,
struct ahc_tmode_lstate **lstate,
int notfound_failure)
{
if ((ahc->features & AHC_TARGETMODE) == 0)
return (CAM_REQ_INVALID);
/*
* Handle the 'black hole' device that sucks up
* requests to unattached luns on enabled targets.
*/
if (ccb->ccb_h.target_id == CAM_TARGET_WILDCARD
&& ccb->ccb_h.target_lun == CAM_LUN_WILDCARD) {
*tstate = NULL;
*lstate = ahc->black_hole;
} else {
u_int max_id;
max_id = (ahc->features & AHC_WIDE) ? 16 : 8;
if (ccb->ccb_h.target_id >= max_id)
return (CAM_TID_INVALID);
if (ccb->ccb_h.target_lun >= AHC_NUM_LUNS)
return (CAM_LUN_INVALID);
*tstate = ahc->enabled_targets[ccb->ccb_h.target_id];
*lstate = NULL;
if (*tstate != NULL)
*lstate =
(*tstate)->enabled_luns[ccb->ccb_h.target_lun];
}
if (notfound_failure != 0 && *lstate == NULL)
return (CAM_PATH_INVALID);
return (CAM_REQ_CMP);
}
void
ahc_handle_en_lun(struct ahc_softc *ahc, struct cam_sim *sim, union ccb *ccb)
{
struct ahc_tmode_tstate *tstate;
struct ahc_tmode_lstate *lstate;
struct ccb_en_lun *cel;
cam_status status;
u_long s;
u_int target;
u_int lun;
u_int target_mask;
u_int our_id;
int error;
char channel;
status = ahc_find_tmode_devs(ahc, sim, ccb, &tstate, &lstate,
/*notfound_failure*/FALSE);
if (status != CAM_REQ_CMP) {
ccb->ccb_h.status = status;
return;
}
if (cam_sim_bus(sim) == 0)
our_id = ahc->our_id;
else
our_id = ahc->our_id_b;
if (ccb->ccb_h.target_id != our_id) {
/*
* our_id represents our initiator ID, or
* the ID of the first target to have an
* enabled lun in target mode. There are
* two cases that may preclude enabling a
* target id other than our_id.
*
* o our_id is for an active initiator role.
* Since the hardware does not support
* reselections to the initiator role at
* anything other than our_id, and our_id
* is used by the hardware to indicate the
* ID to use for both select-out and
* reselect-out operations, the only target
* ID we can support in this mode is our_id.
*
* o The MULTARGID feature is not available and
* a previous target mode ID has been enabled.
*/
if ((ahc->features & AHC_MULTIROLE) != 0) {
if ((ahc->features & AHC_MULTI_TID) != 0
&& (ahc->flags & AHC_INITIATORROLE) != 0) {
/*
* Only allow additional targets if
* the initiator role is disabled.
* The hardware cannot handle a re-select-in
* on the initiator id during a re-select-out
* on a different target id.
*/
status = CAM_TID_INVALID;
} else if ((ahc->flags & AHC_INITIATORROLE) != 0
|| ahc->enabled_luns > 0) {
/*
* Only allow our target id to change
* if the initiator role is not configured
* and there are no enabled luns which
* are attached to the currently registered
* scsi id.
*/
status = CAM_TID_INVALID;
}
} else if ((ahc->features & AHC_MULTI_TID) == 0
&& ahc->enabled_luns > 0) {
status = CAM_TID_INVALID;
}
}
if (status != CAM_REQ_CMP) {
ccb->ccb_h.status = status;
return;
}
/*
* We now have an id that is valid.
* If we aren't in target mode, switch modes.
*/
if ((ahc->flags & AHC_TARGETROLE) == 0
&& ccb->ccb_h.target_id != CAM_TARGET_WILDCARD) {
u_long s;
ahc_flag saved_flags;
printf("Configuring Target Mode\n");
ahc_lock(ahc, &s);
if (LIST_FIRST(&ahc->pending_scbs) != NULL) {
ccb->ccb_h.status = CAM_BUSY;
ahc_unlock(ahc, &s);
return;
}
saved_flags = ahc->flags;
ahc->flags |= AHC_TARGETROLE;
if ((ahc->features & AHC_MULTIROLE) == 0)
ahc->flags &= ~AHC_INITIATORROLE;
ahc_pause(ahc);
error = ahc_loadseq(ahc);
if (error != 0) {
/*
* Restore original configuration and notify
* the caller that we cannot support target mode.
* Since the adapter started out in this
* configuration, the firmware load will succeed,
* so there is no point in checking ahc_loadseq's
* return value.
*/
ahc->flags = saved_flags;
(void)ahc_loadseq(ahc);
ahc_restart(ahc);
ahc_unlock(ahc, &s);
ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
return;
}
ahc_restart(ahc);
ahc_unlock(ahc, &s);
}
cel = &ccb->cel;
target = ccb->ccb_h.target_id;
lun = ccb->ccb_h.target_lun;
channel = SIM_CHANNEL(ahc, sim);
target_mask = 0x01 << target;
if (channel == 'B')
target_mask <<= 8;
if (cel->enable != 0) {
u_int scsiseq;
/* Are we already enabled?? */
if (lstate != NULL) {
xpt_print_path(ccb->ccb_h.path);
printf("Lun already enabled\n");
ccb->ccb_h.status = CAM_LUN_ALRDY_ENA;
return;
}
if (cel->grp6_len != 0
|| cel->grp7_len != 0) {
/*
* Don't (yet?) support vendor
* specific commands.
*/
ccb->ccb_h.status = CAM_REQ_INVALID;
printf("Non-zero Group Codes\n");
return;
}
/*
* Seems to be okay.
* Setup our data structures.
*/
if (target != CAM_TARGET_WILDCARD && tstate == NULL) {
tstate = ahc_alloc_tstate(ahc, target, channel);
if (tstate == NULL) {
xpt_print_path(ccb->ccb_h.path);
printf("Couldn't allocate tstate\n");
ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
return;
}
}
lstate = malloc(sizeof(*lstate), M_DEVBUF, M_NOWAIT);
if (lstate == NULL) {
xpt_print_path(ccb->ccb_h.path);
printf("Couldn't allocate lstate\n");
ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
return;
}
memset(lstate, 0, sizeof(*lstate));
status = xpt_create_path(&lstate->path, /*periph*/NULL,
xpt_path_path_id(ccb->ccb_h.path),
xpt_path_target_id(ccb->ccb_h.path),
xpt_path_lun_id(ccb->ccb_h.path));
if (status != CAM_REQ_CMP) {
free(lstate, M_DEVBUF);
xpt_print_path(ccb->ccb_h.path);
printf("Couldn't allocate path\n");
ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
return;
}
SLIST_INIT(&lstate->accept_tios);
SLIST_INIT(&lstate->immed_notifies);
ahc_lock(ahc, &s);
ahc_pause(ahc);
if (target != CAM_TARGET_WILDCARD) {
tstate->enabled_luns[lun] = lstate;
ahc->enabled_luns++;
if ((ahc->features & AHC_MULTI_TID) != 0) {
u_int targid_mask;
targid_mask = ahc_inb(ahc, TARGID)
| (ahc_inb(ahc, TARGID + 1) << 8);
targid_mask |= target_mask;
ahc_outb(ahc, TARGID, targid_mask);
ahc_outb(ahc, TARGID+1, (targid_mask >> 8));
ahc_update_scsiid(ahc, targid_mask);
} else {
u_int our_id;
char channel;
channel = SIM_CHANNEL(ahc, sim);
our_id = SIM_SCSI_ID(ahc, sim);
/*
* This can only happen if selections
* are not enabled
*/
if (target != our_id) {
u_int sblkctl;
char cur_channel;
int swap;
sblkctl = ahc_inb(ahc, SBLKCTL);
cur_channel = (sblkctl & SELBUSB)
? 'B' : 'A';
if ((ahc->features & AHC_TWIN) == 0)
cur_channel = 'A';
swap = cur_channel != channel;
if (channel == 'A')
ahc->our_id = target;
else
ahc->our_id_b = target;
if (swap)
ahc_outb(ahc, SBLKCTL,
sblkctl ^ SELBUSB);
ahc_outb(ahc, SCSIID, target);
if (swap)
ahc_outb(ahc, SBLKCTL, sblkctl);
}
}
} else
ahc->black_hole = lstate;
/* Allow select-in operations */
if (ahc->black_hole != NULL && ahc->enabled_luns > 0) {
scsiseq = ahc_inb(ahc, SCSISEQ_TEMPLATE);
scsiseq |= ENSELI;
ahc_outb(ahc, SCSISEQ_TEMPLATE, scsiseq);
scsiseq = ahc_inb(ahc, SCSISEQ);
scsiseq |= ENSELI;
ahc_outb(ahc, SCSISEQ, scsiseq);
}
ahc_unpause(ahc);
ahc_unlock(ahc, &s);
ccb->ccb_h.status = CAM_REQ_CMP;
xpt_print_path(ccb->ccb_h.path);
printf("Lun now enabled for target mode\n");
} else {
struct scb *scb;
int i, empty;
if (lstate == NULL) {
ccb->ccb_h.status = CAM_LUN_INVALID;
return;
}
ahc_lock(ahc, &s);
ccb->ccb_h.status = CAM_REQ_CMP;
LIST_FOREACH(scb, &ahc->pending_scbs, pending_links) {
struct ccb_hdr *ccbh;
ccbh = &scb->io_ctx->ccb_h;
if (ccbh->func_code == XPT_CONT_TARGET_IO
&& !xpt_path_comp(ccbh->path, ccb->ccb_h.path)){
printf("CTIO pending\n");
ccb->ccb_h.status = CAM_REQ_INVALID;
ahc_unlock(ahc, &s);
return;
}
}
if (SLIST_FIRST(&lstate->accept_tios) != NULL) {
printf("ATIOs pending\n");
ccb->ccb_h.status = CAM_REQ_INVALID;
}
if (SLIST_FIRST(&lstate->immed_notifies) != NULL) {
printf("INOTs pending\n");
ccb->ccb_h.status = CAM_REQ_INVALID;
}
if (ccb->ccb_h.status != CAM_REQ_CMP) {
ahc_unlock(ahc, &s);
return;
}
xpt_print_path(ccb->ccb_h.path);
printf("Target mode disabled\n");
xpt_free_path(lstate->path);
free(lstate, M_DEVBUF);
ahc_pause(ahc);
/* Can we clean up the target too? */
if (target != CAM_TARGET_WILDCARD) {
tstate->enabled_luns[lun] = NULL;
ahc->enabled_luns--;
for (empty = 1, i = 0; i < 8; i++)
if (tstate->enabled_luns[i] != NULL) {
empty = 0;
break;
}
if (empty) {
ahc_free_tstate(ahc, target, channel,
/*force*/FALSE);
if (ahc->features & AHC_MULTI_TID) {
u_int targid_mask;
targid_mask = ahc_inb(ahc, TARGID)
| (ahc_inb(ahc, TARGID + 1)
<< 8);
targid_mask &= ~target_mask;
ahc_outb(ahc, TARGID, targid_mask);
ahc_outb(ahc, TARGID+1,
(targid_mask >> 8));
ahc_update_scsiid(ahc, targid_mask);
}
}
} else {
ahc->black_hole = NULL;
/*
* We can't allow selections without
* our black hole device.
*/
empty = TRUE;
}
if (ahc->enabled_luns == 0) {
/* Disallow select-in */
u_int scsiseq;
scsiseq = ahc_inb(ahc, SCSISEQ_TEMPLATE);
scsiseq &= ~ENSELI;
ahc_outb(ahc, SCSISEQ_TEMPLATE, scsiseq);
scsiseq = ahc_inb(ahc, SCSISEQ);
scsiseq &= ~ENSELI;
ahc_outb(ahc, SCSISEQ, scsiseq);
if ((ahc->features & AHC_MULTIROLE) == 0) {
printf("Configuring Initiator Mode\n");
ahc->flags &= ~AHC_TARGETROLE;
ahc->flags |= AHC_INITIATORROLE;
/*
* Returning to a configuration that
* fit previously will always succeed.
*/
(void)ahc_loadseq(ahc);
ahc_restart(ahc);
/*
* Unpaused. The extra unpause
* that follows is harmless.
*/
}
}
ahc_unpause(ahc);
ahc_unlock(ahc, &s);
}
}
static void
ahc_update_scsiid(struct ahc_softc *ahc, u_int targid_mask)
{
u_int scsiid_mask;
u_int scsiid;
if ((ahc->features & AHC_MULTI_TID) == 0)
panic("ahc_update_scsiid called on non-multitid unit\n");
/*
* Since we will rely on the TARGID mask
* for selection enables, ensure that OID
* in SCSIID is not set to some other ID
* that we don't want to allow selections on.
*/
if ((ahc->features & AHC_ULTRA2) != 0)
scsiid = ahc_inb(ahc, SCSIID_ULTRA2);
else
scsiid = ahc_inb(ahc, SCSIID);
scsiid_mask = 0x1 << (scsiid & OID);
if ((targid_mask & scsiid_mask) == 0) {
u_int our_id;
/* ffs counts from 1 */
our_id = ffs(targid_mask);
if (our_id == 0)
our_id = ahc->our_id;
else
our_id--;
scsiid &= TID;
scsiid |= our_id;
}
if ((ahc->features & AHC_ULTRA2) != 0)
ahc_outb(ahc, SCSIID_ULTRA2, scsiid);
else
ahc_outb(ahc, SCSIID, scsiid);
}
static void
ahc_run_tqinfifo(struct ahc_softc *ahc, int paused)
{
struct target_cmd *cmd;
/*
* If the card supports auto-access pause,
* we can access the card directly regardless
* of whether it is paused or not.
*/
if ((ahc->features & AHC_AUTOPAUSE) != 0)
paused = TRUE;
ahc_sync_tqinfifo(ahc, BUS_DMASYNC_POSTREAD);
while ((cmd = &ahc->targetcmds[ahc->tqinfifonext])->cmd_valid != 0) {
/*
* Only advance through the queue if we
* have the resources to process the command.
*/
if (ahc_handle_target_cmd(ahc, cmd) != 0)
break;
cmd->cmd_valid = 0;
ahc_dmamap_sync(ahc, ahc->shared_data_dmat,
ahc->shared_data_dmamap,
ahc_targetcmd_offset(ahc, ahc->tqinfifonext),
sizeof(struct target_cmd),
BUS_DMASYNC_PREREAD);
ahc->tqinfifonext++;
/*
* Lazily update our position in the target mode incoming
* command queue as seen by the sequencer.
*/
if ((ahc->tqinfifonext & (HOST_TQINPOS - 1)) == 1) {
if ((ahc->features & AHC_HS_MAILBOX) != 0) {
u_int hs_mailbox;
hs_mailbox = ahc_inb(ahc, HS_MAILBOX);
hs_mailbox &= ~HOST_TQINPOS;
hs_mailbox |= ahc->tqinfifonext & HOST_TQINPOS;
ahc_outb(ahc, HS_MAILBOX, hs_mailbox);
} else {
if (!paused)
ahc_pause(ahc);
ahc_outb(ahc, KERNEL_TQINPOS,
ahc->tqinfifonext & HOST_TQINPOS);
if (!paused)
ahc_unpause(ahc);
}
}
}
}
static int
ahc_handle_target_cmd(struct ahc_softc *ahc, struct target_cmd *cmd)
{
struct ahc_tmode_tstate *tstate;
struct ahc_tmode_lstate *lstate;
struct ccb_accept_tio *atio;
uint8_t *byte;
int initiator;
int target;
int lun;
initiator = SCSIID_TARGET(ahc, cmd->scsiid);
target = SCSIID_OUR_ID(cmd->scsiid);
lun = (cmd->identify & MSG_IDENTIFY_LUNMASK);
byte = cmd->bytes;
tstate = ahc->enabled_targets[target];
lstate = NULL;
if (tstate != NULL)
lstate = tstate->enabled_luns[lun];
/*
* Commands for disabled luns go to the black hole driver.
*/
if (lstate == NULL)
lstate = ahc->black_hole;
atio = (struct ccb_accept_tio*)SLIST_FIRST(&lstate->accept_tios);
if (atio == NULL) {
ahc->flags |= AHC_TQINFIFO_BLOCKED;
/*
* Wait for more ATIOs from the peripheral driver for this lun.
*/
if (bootverbose)
printf("%s: ATIOs exhausted\n", ahc_name(ahc));
return (1);
} else
ahc->flags &= ~AHC_TQINFIFO_BLOCKED;
#if 0
printf("Incoming command from %d for %d:%d%s\n",
initiator, target, lun,
lstate == ahc->black_hole ? "(Black Holed)" : "");
#endif
SLIST_REMOVE_HEAD(&lstate->accept_tios, sim_links.sle);
if (lstate == ahc->black_hole) {
/* Fill in the wildcards */
atio->ccb_h.target_id = target;
atio->ccb_h.target_lun = lun;
}
/*
* Package it up and send it off to
* whomever has this lun enabled.
*/
atio->sense_len = 0;
atio->init_id = initiator;
if (byte[0] != 0xFF) {
/* Tag was included */
atio->tag_action = *byte++;
atio->tag_id = *byte++;
atio->ccb_h.flags = CAM_TAG_ACTION_VALID;
} else {
atio->ccb_h.flags = 0;
}
byte++;
/* Okay. Now determine the cdb size based on the command code */
switch (*byte >> CMD_GROUP_CODE_SHIFT) {
case 0:
atio->cdb_len = 6;
break;
case 1:
case 2:
atio->cdb_len = 10;
break;
case 4:
atio->cdb_len = 16;
break;
case 5:
atio->cdb_len = 12;
break;
case 3:
default:
/* Only copy the opcode. */
atio->cdb_len = 1;
printf("Reserved or VU command code type encountered\n");
break;
}
memcpy(atio->cdb_io.cdb_bytes, byte, atio->cdb_len);
atio->ccb_h.status |= CAM_CDB_RECVD;
if ((cmd->identify & MSG_IDENTIFY_DISCFLAG) == 0) {
/*
* We weren't allowed to disconnect.
* We're hanging on the bus until a
* continue target I/O comes in response
* to this accept tio.
*/
#if 0
printf("Received Immediate Command %d:%d:%d - %p\n",
initiator, target, lun, ahc->pending_device);
#endif
ahc->pending_device = lstate;
ahc_freeze_ccb((union ccb *)atio);
atio->ccb_h.flags |= CAM_DIS_DISCONNECT;
}
xpt_done((union ccb*)atio);
return (0);
}
#endif
| gpl-2.0 |
jayk/linux | drivers/net/wireless/iwlwifi/dvm/power.c | 1379 | 12902 | /******************************************************************************
*
* Copyright(c) 2007 - 2014 Intel Corporation. All rights reserved.
*
* Portions of this file are derived from the ipw3945 project, as well
* as portions of the ieee80211 subsystem header files.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* The full GNU General Public License is included in this distribution in the
* file called LICENSE.
*
* Contact Information:
* Intel Linux Wireless <ilw@linux.intel.com>
* Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*****************************************************************************/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <net/mac80211.h>
#include "iwl-io.h"
#include "iwl-debug.h"
#include "iwl-trans.h"
#include "iwl-modparams.h"
#include "dev.h"
#include "agn.h"
#include "commands.h"
#include "power.h"
static bool force_cam = true;
module_param(force_cam, bool, 0644);
MODULE_PARM_DESC(force_cam, "force continuously aware mode (no power saving at all)");
/*
* Setting power level allows the card to go to sleep when not busy.
*
* We calculate a sleep command based on the required latency, which
* we get from mac80211. In order to handle thermal throttling, we can
* also use pre-defined power levels.
*/
/*
* This defines the old power levels. They are still used by default
* (level 1) and for thermal throttle (levels 3 through 5)
*/
struct iwl_power_vec_entry {
struct iwl_powertable_cmd cmd;
u8 no_dtim; /* number of skip dtim */
};
#define IWL_DTIM_RANGE_0_MAX 2
#define IWL_DTIM_RANGE_1_MAX 10
#define NOSLP cpu_to_le16(0), 0, 0
#define SLP IWL_POWER_DRIVER_ALLOW_SLEEP_MSK, 0, 0
#define ASLP (IWL_POWER_POWER_SAVE_ENA_MSK | \
IWL_POWER_POWER_MANAGEMENT_ENA_MSK | \
IWL_POWER_ADVANCE_PM_ENA_MSK)
#define ASLP_TOUT(T) cpu_to_le32(T)
#define TU_TO_USEC 1024
#define SLP_TOUT(T) cpu_to_le32((T) * TU_TO_USEC)
#define SLP_VEC(X0, X1, X2, X3, X4) {cpu_to_le32(X0), \
cpu_to_le32(X1), \
cpu_to_le32(X2), \
cpu_to_le32(X3), \
cpu_to_le32(X4)}
/* default power management (not Tx power) table values */
/* for DTIM period 0 through IWL_DTIM_RANGE_0_MAX */
/* DTIM 0 - 2 */
static const struct iwl_power_vec_entry range_0[IWL_POWER_NUM] = {
{{SLP, SLP_TOUT(200), SLP_TOUT(500), SLP_VEC(1, 1, 2, 2, 0xFF)}, 0},
{{SLP, SLP_TOUT(200), SLP_TOUT(300), SLP_VEC(1, 2, 2, 2, 0xFF)}, 0},
{{SLP, SLP_TOUT(50), SLP_TOUT(100), SLP_VEC(2, 2, 2, 2, 0xFF)}, 0},
{{SLP, SLP_TOUT(50), SLP_TOUT(25), SLP_VEC(2, 2, 4, 4, 0xFF)}, 1},
{{SLP, SLP_TOUT(25), SLP_TOUT(25), SLP_VEC(2, 2, 4, 6, 0xFF)}, 2}
};
/* for DTIM period IWL_DTIM_RANGE_0_MAX + 1 through IWL_DTIM_RANGE_1_MAX */
/* DTIM 3 - 10 */
static const struct iwl_power_vec_entry range_1[IWL_POWER_NUM] = {
{{SLP, SLP_TOUT(200), SLP_TOUT(500), SLP_VEC(1, 2, 3, 4, 4)}, 0},
{{SLP, SLP_TOUT(200), SLP_TOUT(300), SLP_VEC(1, 2, 3, 4, 7)}, 0},
{{SLP, SLP_TOUT(50), SLP_TOUT(100), SLP_VEC(2, 4, 6, 7, 9)}, 0},
{{SLP, SLP_TOUT(50), SLP_TOUT(25), SLP_VEC(2, 4, 6, 9, 10)}, 1},
{{SLP, SLP_TOUT(25), SLP_TOUT(25), SLP_VEC(2, 4, 6, 10, 10)}, 2}
};
/* for DTIM period > IWL_DTIM_RANGE_1_MAX */
/* DTIM 11 - */
static const struct iwl_power_vec_entry range_2[IWL_POWER_NUM] = {
{{SLP, SLP_TOUT(200), SLP_TOUT(500), SLP_VEC(1, 2, 3, 4, 0xFF)}, 0},
{{SLP, SLP_TOUT(200), SLP_TOUT(300), SLP_VEC(2, 4, 6, 7, 0xFF)}, 0},
{{SLP, SLP_TOUT(50), SLP_TOUT(100), SLP_VEC(2, 7, 9, 9, 0xFF)}, 0},
{{SLP, SLP_TOUT(50), SLP_TOUT(25), SLP_VEC(2, 7, 9, 9, 0xFF)}, 0},
{{SLP, SLP_TOUT(25), SLP_TOUT(25), SLP_VEC(4, 7, 10, 10, 0xFF)}, 0}
};
/* advance power management */
/* DTIM 0 - 2 */
static const struct iwl_power_vec_entry apm_range_0[IWL_POWER_NUM] = {
{{ASLP, 0, 0, ASLP_TOUT(50), ASLP_TOUT(50),
SLP_VEC(1, 2, 4, 6, 0xFF), 0}, 0},
{{ASLP, 0, 0, ASLP_TOUT(50), ASLP_TOUT(50),
SLP_VEC(1, 2, 4, 6, 0xFF), 0}, 0},
{{ASLP, 0, 0, ASLP_TOUT(50), ASLP_TOUT(50),
SLP_VEC(1, 2, 4, 6, 0xFF), 0}, 0},
{{ASLP, 0, 0, ASLP_TOUT(50), ASLP_TOUT(50),
SLP_VEC(1, 2, 4, 6, 0xFF), 0}, 0},
{{ASLP, 0, 0, ASLP_TOUT(50), ASLP_TOUT(50),
SLP_VEC(1, 2, 6, 8, 0xFF), ASLP_TOUT(2)}, 2}
};
/* for DTIM period IWL_DTIM_RANGE_0_MAX + 1 through IWL_DTIM_RANGE_1_MAX */
/* DTIM 3 - 10 */
static const struct iwl_power_vec_entry apm_range_1[IWL_POWER_NUM] = {
{{ASLP, 0, 0, ASLP_TOUT(50), ASLP_TOUT(50),
SLP_VEC(1, 2, 4, 6, 0xFF), 0}, 0},
{{ASLP, 0, 0, ASLP_TOUT(50), ASLP_TOUT(50),
SLP_VEC(1, 2, 4, 6, 0xFF), 0}, 0},
{{ASLP, 0, 0, ASLP_TOUT(50), ASLP_TOUT(50),
SLP_VEC(1, 2, 4, 6, 0xFF), 0}, 0},
{{ASLP, 0, 0, ASLP_TOUT(50), ASLP_TOUT(50),
SLP_VEC(1, 2, 4, 6, 0xFF), 0}, 0},
{{ASLP, 0, 0, ASLP_TOUT(50), ASLP_TOUT(50),
SLP_VEC(1, 2, 6, 8, 0xFF), 0}, 2}
};
/* for DTIM period > IWL_DTIM_RANGE_1_MAX */
/* DTIM 11 - */
static const struct iwl_power_vec_entry apm_range_2[IWL_POWER_NUM] = {
{{ASLP, 0, 0, ASLP_TOUT(50), ASLP_TOUT(50),
SLP_VEC(1, 2, 4, 6, 0xFF), 0}, 0},
{{ASLP, 0, 0, ASLP_TOUT(50), ASLP_TOUT(50),
SLP_VEC(1, 2, 4, 6, 0xFF), 0}, 0},
{{ASLP, 0, 0, ASLP_TOUT(50), ASLP_TOUT(50),
SLP_VEC(1, 2, 4, 6, 0xFF), 0}, 0},
{{ASLP, 0, 0, ASLP_TOUT(50), ASLP_TOUT(50),
SLP_VEC(1, 2, 4, 6, 0xFF), 0}, 0},
{{ASLP, 0, 0, ASLP_TOUT(50), ASLP_TOUT(50),
SLP_VEC(1, 2, 6, 8, 0xFF), ASLP_TOUT(2)}, 2}
};
static void iwl_static_sleep_cmd(struct iwl_priv *priv,
struct iwl_powertable_cmd *cmd,
enum iwl_power_level lvl, int period)
{
const struct iwl_power_vec_entry *table;
int max_sleep[IWL_POWER_VEC_SIZE] = { 0 };
int i;
u8 skip;
u32 slp_itrvl;
if (priv->lib->adv_pm) {
table = apm_range_2;
if (period <= IWL_DTIM_RANGE_1_MAX)
table = apm_range_1;
if (period <= IWL_DTIM_RANGE_0_MAX)
table = apm_range_0;
} else {
table = range_2;
if (period <= IWL_DTIM_RANGE_1_MAX)
table = range_1;
if (period <= IWL_DTIM_RANGE_0_MAX)
table = range_0;
}
if (WARN_ON(lvl < 0 || lvl >= IWL_POWER_NUM))
memset(cmd, 0, sizeof(*cmd));
else
*cmd = table[lvl].cmd;
if (period == 0) {
skip = 0;
period = 1;
for (i = 0; i < IWL_POWER_VEC_SIZE; i++)
max_sleep[i] = 1;
} else {
skip = table[lvl].no_dtim;
for (i = 0; i < IWL_POWER_VEC_SIZE; i++)
max_sleep[i] = le32_to_cpu(cmd->sleep_interval[i]);
max_sleep[IWL_POWER_VEC_SIZE - 1] = skip + 1;
}
slp_itrvl = le32_to_cpu(cmd->sleep_interval[IWL_POWER_VEC_SIZE - 1]);
/* figure out the listen interval based on dtim period and skip */
if (slp_itrvl == 0xFF)
cmd->sleep_interval[IWL_POWER_VEC_SIZE - 1] =
cpu_to_le32(period * (skip + 1));
slp_itrvl = le32_to_cpu(cmd->sleep_interval[IWL_POWER_VEC_SIZE - 1]);
if (slp_itrvl > period)
cmd->sleep_interval[IWL_POWER_VEC_SIZE - 1] =
cpu_to_le32((slp_itrvl / period) * period);
if (skip)
cmd->flags |= IWL_POWER_SLEEP_OVER_DTIM_MSK;
else
cmd->flags &= ~IWL_POWER_SLEEP_OVER_DTIM_MSK;
if (priv->cfg->base_params->shadow_reg_enable)
cmd->flags |= IWL_POWER_SHADOW_REG_ENA;
else
cmd->flags &= ~IWL_POWER_SHADOW_REG_ENA;
if (iwl_advanced_bt_coexist(priv)) {
if (!priv->lib->bt_params->bt_sco_disable)
cmd->flags |= IWL_POWER_BT_SCO_ENA;
else
cmd->flags &= ~IWL_POWER_BT_SCO_ENA;
}
slp_itrvl = le32_to_cpu(cmd->sleep_interval[IWL_POWER_VEC_SIZE - 1]);
if (slp_itrvl > IWL_CONN_MAX_LISTEN_INTERVAL)
cmd->sleep_interval[IWL_POWER_VEC_SIZE - 1] =
cpu_to_le32(IWL_CONN_MAX_LISTEN_INTERVAL);
/* enforce max sleep interval */
for (i = IWL_POWER_VEC_SIZE - 1; i >= 0 ; i--) {
if (le32_to_cpu(cmd->sleep_interval[i]) >
(max_sleep[i] * period))
cmd->sleep_interval[i] =
cpu_to_le32(max_sleep[i] * period);
if (i != (IWL_POWER_VEC_SIZE - 1)) {
if (le32_to_cpu(cmd->sleep_interval[i]) >
le32_to_cpu(cmd->sleep_interval[i+1]))
cmd->sleep_interval[i] =
cmd->sleep_interval[i+1];
}
}
if (priv->power_data.bus_pm)
cmd->flags |= IWL_POWER_PCI_PM_MSK;
else
cmd->flags &= ~IWL_POWER_PCI_PM_MSK;
IWL_DEBUG_POWER(priv, "numSkipDtim = %u, dtimPeriod = %d\n",
skip, period);
/* The power level here is 0-4 (used as array index), but user expects
to see 1-5 (according to spec). */
IWL_DEBUG_POWER(priv, "Sleep command for index %d\n", lvl + 1);
}
static void iwl_power_sleep_cam_cmd(struct iwl_priv *priv,
struct iwl_powertable_cmd *cmd)
{
memset(cmd, 0, sizeof(*cmd));
if (priv->power_data.bus_pm)
cmd->flags |= IWL_POWER_PCI_PM_MSK;
IWL_DEBUG_POWER(priv, "Sleep command for CAM\n");
}
static int iwl_set_power(struct iwl_priv *priv, struct iwl_powertable_cmd *cmd)
{
IWL_DEBUG_POWER(priv, "Sending power/sleep command\n");
IWL_DEBUG_POWER(priv, "Flags value = 0x%08X\n", cmd->flags);
IWL_DEBUG_POWER(priv, "Tx timeout = %u\n", le32_to_cpu(cmd->tx_data_timeout));
IWL_DEBUG_POWER(priv, "Rx timeout = %u\n", le32_to_cpu(cmd->rx_data_timeout));
IWL_DEBUG_POWER(priv, "Sleep interval vector = { %d , %d , %d , %d , %d }\n",
le32_to_cpu(cmd->sleep_interval[0]),
le32_to_cpu(cmd->sleep_interval[1]),
le32_to_cpu(cmd->sleep_interval[2]),
le32_to_cpu(cmd->sleep_interval[3]),
le32_to_cpu(cmd->sleep_interval[4]));
return iwl_dvm_send_cmd_pdu(priv, POWER_TABLE_CMD, 0,
sizeof(struct iwl_powertable_cmd), cmd);
}
static void iwl_power_build_cmd(struct iwl_priv *priv,
struct iwl_powertable_cmd *cmd)
{
bool enabled = priv->hw->conf.flags & IEEE80211_CONF_PS;
int dtimper;
if (force_cam) {
iwl_power_sleep_cam_cmd(priv, cmd);
return;
}
dtimper = priv->hw->conf.ps_dtim_period ?: 1;
if (priv->wowlan)
iwl_static_sleep_cmd(priv, cmd, IWL_POWER_INDEX_5, dtimper);
else if (!priv->lib->no_idle_support &&
priv->hw->conf.flags & IEEE80211_CONF_IDLE)
iwl_static_sleep_cmd(priv, cmd, IWL_POWER_INDEX_5, 20);
else if (iwl_tt_is_low_power_state(priv)) {
/* in thermal throttling low power state */
iwl_static_sleep_cmd(priv, cmd,
iwl_tt_current_power_mode(priv), dtimper);
} else if (!enabled)
iwl_power_sleep_cam_cmd(priv, cmd);
else if (priv->power_data.debug_sleep_level_override >= 0)
iwl_static_sleep_cmd(priv, cmd,
priv->power_data.debug_sleep_level_override,
dtimper);
else {
/* Note that the user parameter is 1-5 (according to spec),
but we pass 0-4 because it acts as an array index. */
if (iwlwifi_mod_params.power_level > IWL_POWER_INDEX_1 &&
iwlwifi_mod_params.power_level <= IWL_POWER_NUM)
iwl_static_sleep_cmd(priv, cmd,
iwlwifi_mod_params.power_level - 1, dtimper);
else
iwl_static_sleep_cmd(priv, cmd,
IWL_POWER_INDEX_1, dtimper);
}
}
int iwl_power_set_mode(struct iwl_priv *priv, struct iwl_powertable_cmd *cmd,
bool force)
{
int ret;
bool update_chains;
lockdep_assert_held(&priv->mutex);
/* Don't update the RX chain when chain noise calibration is running */
update_chains = priv->chain_noise_data.state == IWL_CHAIN_NOISE_DONE ||
priv->chain_noise_data.state == IWL_CHAIN_NOISE_ALIVE;
if (!memcmp(&priv->power_data.sleep_cmd, cmd, sizeof(*cmd)) && !force)
return 0;
if (!iwl_is_ready_rf(priv))
return -EIO;
/* scan complete use sleep_power_next, need to be updated */
memcpy(&priv->power_data.sleep_cmd_next, cmd, sizeof(*cmd));
if (test_bit(STATUS_SCANNING, &priv->status) && !force) {
IWL_DEBUG_INFO(priv, "Defer power set mode while scanning\n");
return 0;
}
if (cmd->flags & IWL_POWER_DRIVER_ALLOW_SLEEP_MSK)
iwl_dvm_set_pmi(priv, true);
ret = iwl_set_power(priv, cmd);
if (!ret) {
if (!(cmd->flags & IWL_POWER_DRIVER_ALLOW_SLEEP_MSK))
iwl_dvm_set_pmi(priv, false);
if (update_chains)
iwl_update_chain_flags(priv);
else
IWL_DEBUG_POWER(priv,
"Cannot update the power, chain noise "
"calibration running: %d\n",
priv->chain_noise_data.state);
memcpy(&priv->power_data.sleep_cmd, cmd, sizeof(*cmd));
} else
IWL_ERR(priv, "set power fail, ret = %d\n", ret);
return ret;
}
int iwl_power_update_mode(struct iwl_priv *priv, bool force)
{
struct iwl_powertable_cmd cmd;
iwl_power_build_cmd(priv, &cmd);
return iwl_power_set_mode(priv, &cmd, force);
}
/* initialize to default */
void iwl_power_initialize(struct iwl_priv *priv)
{
priv->power_data.bus_pm = priv->trans->pm_support;
priv->power_data.debug_sleep_level_override = -1;
memset(&priv->power_data.sleep_cmd, 0,
sizeof(priv->power_data.sleep_cmd));
}
| gpl-2.0 |
sandeep1027/kernel-3.10 | drivers/net/wireless/rtlwifi/pci.c | 1635 | 57281 | /******************************************************************************
*
* Copyright(c) 2009-2012 Realtek Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* The full GNU General Public License is included in this distribution in the
* file called LICENSE.
*
* Contact Information:
* wlanfae <wlanfae@realtek.com>
* Realtek Corporation, No. 2, Innovation Road II, Hsinchu Science Park,
* Hsinchu 300, Taiwan.
*
* Larry Finger <Larry.Finger@lwfinger.net>
*
*****************************************************************************/
#include "wifi.h"
#include "core.h"
#include "pci.h"
#include "base.h"
#include "ps.h"
#include "efuse.h"
#include <linux/export.h>
#include <linux/kmemleak.h>
static const u16 pcibridge_vendors[PCI_BRIDGE_VENDOR_MAX] = {
PCI_VENDOR_ID_INTEL,
PCI_VENDOR_ID_ATI,
PCI_VENDOR_ID_AMD,
PCI_VENDOR_ID_SI
};
static const u8 ac_to_hwq[] = {
VO_QUEUE,
VI_QUEUE,
BE_QUEUE,
BK_QUEUE
};
static u8 _rtl_mac_to_hwqueue(struct ieee80211_hw *hw,
struct sk_buff *skb)
{
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
__le16 fc = rtl_get_fc(skb);
u8 queue_index = skb_get_queue_mapping(skb);
if (unlikely(ieee80211_is_beacon(fc)))
return BEACON_QUEUE;
if (ieee80211_is_mgmt(fc) || ieee80211_is_ctl(fc))
return MGNT_QUEUE;
if (rtlhal->hw_type == HARDWARE_TYPE_RTL8192SE)
if (ieee80211_is_nullfunc(fc))
return HIGH_QUEUE;
return ac_to_hwq[queue_index];
}
/* Update PCI dependent default settings*/
static void _rtl_pci_update_default_setting(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_pci_priv *pcipriv = rtl_pcipriv(hw);
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
u8 pcibridge_vendor = pcipriv->ndis_adapter.pcibridge_vendor;
u8 init_aspm;
ppsc->reg_rfps_level = 0;
ppsc->support_aspm = false;
/*Update PCI ASPM setting */
ppsc->const_amdpci_aspm = rtlpci->const_amdpci_aspm;
switch (rtlpci->const_pci_aspm) {
case 0:
/*No ASPM */
break;
case 1:
/*ASPM dynamically enabled/disable. */
ppsc->reg_rfps_level |= RT_RF_LPS_LEVEL_ASPM;
break;
case 2:
/*ASPM with Clock Req dynamically enabled/disable. */
ppsc->reg_rfps_level |= (RT_RF_LPS_LEVEL_ASPM |
RT_RF_OFF_LEVL_CLK_REQ);
break;
case 3:
/*
* Always enable ASPM and Clock Req
* from initialization to halt.
* */
ppsc->reg_rfps_level &= ~(RT_RF_LPS_LEVEL_ASPM);
ppsc->reg_rfps_level |= (RT_RF_PS_LEVEL_ALWAYS_ASPM |
RT_RF_OFF_LEVL_CLK_REQ);
break;
case 4:
/*
* Always enable ASPM without Clock Req
* from initialization to halt.
* */
ppsc->reg_rfps_level &= ~(RT_RF_LPS_LEVEL_ASPM |
RT_RF_OFF_LEVL_CLK_REQ);
ppsc->reg_rfps_level |= RT_RF_PS_LEVEL_ALWAYS_ASPM;
break;
}
ppsc->reg_rfps_level |= RT_RF_OFF_LEVL_HALT_NIC;
/*Update Radio OFF setting */
switch (rtlpci->const_hwsw_rfoff_d3) {
case 1:
if (ppsc->reg_rfps_level & RT_RF_LPS_LEVEL_ASPM)
ppsc->reg_rfps_level |= RT_RF_OFF_LEVL_ASPM;
break;
case 2:
if (ppsc->reg_rfps_level & RT_RF_LPS_LEVEL_ASPM)
ppsc->reg_rfps_level |= RT_RF_OFF_LEVL_ASPM;
ppsc->reg_rfps_level |= RT_RF_OFF_LEVL_HALT_NIC;
break;
case 3:
ppsc->reg_rfps_level |= RT_RF_OFF_LEVL_PCI_D3;
break;
}
/*Set HW definition to determine if it supports ASPM. */
switch (rtlpci->const_support_pciaspm) {
case 0:{
/*Not support ASPM. */
bool support_aspm = false;
ppsc->support_aspm = support_aspm;
break;
}
case 1:{
/*Support ASPM. */
bool support_aspm = true;
bool support_backdoor = true;
ppsc->support_aspm = support_aspm;
/*if (priv->oem_id == RT_CID_TOSHIBA &&
!priv->ndis_adapter.amd_l1_patch)
support_backdoor = false; */
ppsc->support_backdoor = support_backdoor;
break;
}
case 2:
/*ASPM value set by chipset. */
if (pcibridge_vendor == PCI_BRIDGE_VENDOR_INTEL) {
bool support_aspm = true;
ppsc->support_aspm = support_aspm;
}
break;
default:
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"switch case not processed\n");
break;
}
/* toshiba aspm issue, toshiba will set aspm selfly
* so we should not set aspm in driver */
pci_read_config_byte(rtlpci->pdev, 0x80, &init_aspm);
if (rtlpriv->rtlhal.hw_type == HARDWARE_TYPE_RTL8192SE &&
init_aspm == 0x43)
ppsc->support_aspm = false;
}
static bool _rtl_pci_platform_switch_device_pci_aspm(
struct ieee80211_hw *hw,
u8 value)
{
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
if (rtlhal->hw_type != HARDWARE_TYPE_RTL8192SE)
value |= 0x40;
pci_write_config_byte(rtlpci->pdev, 0x80, value);
return false;
}
/*When we set 0x01 to enable clk request. Set 0x0 to disable clk req.*/
static void _rtl_pci_switch_clk_req(struct ieee80211_hw *hw, u8 value)
{
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
pci_write_config_byte(rtlpci->pdev, 0x81, value);
if (rtlhal->hw_type == HARDWARE_TYPE_RTL8192SE)
udelay(100);
}
/*Disable RTL8192SE ASPM & Disable Pci Bridge ASPM*/
static void rtl_pci_disable_aspm(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_pci_priv *pcipriv = rtl_pcipriv(hw);
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
u8 pcibridge_vendor = pcipriv->ndis_adapter.pcibridge_vendor;
u8 num4bytes = pcipriv->ndis_adapter.num4bytes;
/*Retrieve original configuration settings. */
u8 linkctrl_reg = pcipriv->ndis_adapter.linkctrl_reg;
u16 pcibridge_linkctrlreg = pcipriv->ndis_adapter.
pcibridge_linkctrlreg;
u16 aspmlevel = 0;
u8 tmp_u1b = 0;
if (!ppsc->support_aspm)
return;
if (pcibridge_vendor == PCI_BRIDGE_VENDOR_UNKNOWN) {
RT_TRACE(rtlpriv, COMP_POWER, DBG_TRACE,
"PCI(Bridge) UNKNOWN\n");
return;
}
if (ppsc->reg_rfps_level & RT_RF_OFF_LEVL_CLK_REQ) {
RT_CLEAR_PS_LEVEL(ppsc, RT_RF_OFF_LEVL_CLK_REQ);
_rtl_pci_switch_clk_req(hw, 0x0);
}
/*for promising device will in L0 state after an I/O. */
pci_read_config_byte(rtlpci->pdev, 0x80, &tmp_u1b);
/*Set corresponding value. */
aspmlevel |= BIT(0) | BIT(1);
linkctrl_reg &= ~aspmlevel;
pcibridge_linkctrlreg &= ~(BIT(0) | BIT(1));
_rtl_pci_platform_switch_device_pci_aspm(hw, linkctrl_reg);
udelay(50);
/*4 Disable Pci Bridge ASPM */
pci_write_config_byte(rtlpci->pdev, (num4bytes << 2),
pcibridge_linkctrlreg);
udelay(50);
}
/*
*Enable RTL8192SE ASPM & Enable Pci Bridge ASPM for
*power saving We should follow the sequence to enable
*RTL8192SE first then enable Pci Bridge ASPM
*or the system will show bluescreen.
*/
static void rtl_pci_enable_aspm(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_pci_priv *pcipriv = rtl_pcipriv(hw);
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
u8 pcibridge_vendor = pcipriv->ndis_adapter.pcibridge_vendor;
u8 num4bytes = pcipriv->ndis_adapter.num4bytes;
u16 aspmlevel;
u8 u_pcibridge_aspmsetting;
u8 u_device_aspmsetting;
if (!ppsc->support_aspm)
return;
if (pcibridge_vendor == PCI_BRIDGE_VENDOR_UNKNOWN) {
RT_TRACE(rtlpriv, COMP_POWER, DBG_TRACE,
"PCI(Bridge) UNKNOWN\n");
return;
}
/*4 Enable Pci Bridge ASPM */
u_pcibridge_aspmsetting =
pcipriv->ndis_adapter.pcibridge_linkctrlreg |
rtlpci->const_hostpci_aspm_setting;
if (pcibridge_vendor == PCI_BRIDGE_VENDOR_INTEL)
u_pcibridge_aspmsetting &= ~BIT(0);
pci_write_config_byte(rtlpci->pdev, (num4bytes << 2),
u_pcibridge_aspmsetting);
RT_TRACE(rtlpriv, COMP_INIT, DBG_LOUD,
"PlatformEnableASPM(): Write reg[%x] = %x\n",
(pcipriv->ndis_adapter.pcibridge_pciehdr_offset + 0x10),
u_pcibridge_aspmsetting);
udelay(50);
/*Get ASPM level (with/without Clock Req) */
aspmlevel = rtlpci->const_devicepci_aspm_setting;
u_device_aspmsetting = pcipriv->ndis_adapter.linkctrl_reg;
/*_rtl_pci_platform_switch_device_pci_aspm(dev,*/
/*(priv->ndis_adapter.linkctrl_reg | ASPMLevel)); */
u_device_aspmsetting |= aspmlevel;
_rtl_pci_platform_switch_device_pci_aspm(hw, u_device_aspmsetting);
if (ppsc->reg_rfps_level & RT_RF_OFF_LEVL_CLK_REQ) {
_rtl_pci_switch_clk_req(hw, (ppsc->reg_rfps_level &
RT_RF_OFF_LEVL_CLK_REQ) ? 1 : 0);
RT_SET_PS_LEVEL(ppsc, RT_RF_OFF_LEVL_CLK_REQ);
}
udelay(100);
}
static bool rtl_pci_get_amd_l1_patch(struct ieee80211_hw *hw)
{
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
bool status = false;
u8 offset_e0;
unsigned offset_e4;
pci_write_config_byte(rtlpci->pdev, 0xe0, 0xa0);
pci_read_config_byte(rtlpci->pdev, 0xe0, &offset_e0);
if (offset_e0 == 0xA0) {
pci_read_config_dword(rtlpci->pdev, 0xe4, &offset_e4);
if (offset_e4 & BIT(23))
status = true;
}
return status;
}
static bool rtl_pci_check_buddy_priv(struct ieee80211_hw *hw,
struct rtl_priv **buddy_priv)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_pci_priv *pcipriv = rtl_pcipriv(hw);
bool find_buddy_priv = false;
struct rtl_priv *tpriv = NULL;
struct rtl_pci_priv *tpcipriv = NULL;
if (!list_empty(&rtlpriv->glb_var->glb_priv_list)) {
list_for_each_entry(tpriv, &rtlpriv->glb_var->glb_priv_list,
list) {
if (tpriv) {
tpcipriv = (struct rtl_pci_priv *)tpriv->priv;
RT_TRACE(rtlpriv, COMP_INIT, DBG_LOUD,
"pcipriv->ndis_adapter.funcnumber %x\n",
pcipriv->ndis_adapter.funcnumber);
RT_TRACE(rtlpriv, COMP_INIT, DBG_LOUD,
"tpcipriv->ndis_adapter.funcnumber %x\n",
tpcipriv->ndis_adapter.funcnumber);
if ((pcipriv->ndis_adapter.busnumber ==
tpcipriv->ndis_adapter.busnumber) &&
(pcipriv->ndis_adapter.devnumber ==
tpcipriv->ndis_adapter.devnumber) &&
(pcipriv->ndis_adapter.funcnumber !=
tpcipriv->ndis_adapter.funcnumber)) {
find_buddy_priv = true;
break;
}
}
}
}
RT_TRACE(rtlpriv, COMP_INIT, DBG_LOUD,
"find_buddy_priv %d\n", find_buddy_priv);
if (find_buddy_priv)
*buddy_priv = tpriv;
return find_buddy_priv;
}
static void rtl_pci_get_linkcontrol_field(struct ieee80211_hw *hw)
{
struct rtl_pci_priv *pcipriv = rtl_pcipriv(hw);
struct rtl_pci *rtlpci = rtl_pcidev(pcipriv);
u8 capabilityoffset = pcipriv->ndis_adapter.pcibridge_pciehdr_offset;
u8 linkctrl_reg;
u8 num4bbytes;
num4bbytes = (capabilityoffset + 0x10) / 4;
/*Read Link Control Register */
pci_read_config_byte(rtlpci->pdev, (num4bbytes << 2), &linkctrl_reg);
pcipriv->ndis_adapter.pcibridge_linkctrlreg = linkctrl_reg;
}
static void rtl_pci_parse_configuration(struct pci_dev *pdev,
struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_pci_priv *pcipriv = rtl_pcipriv(hw);
u8 tmp;
u16 linkctrl_reg;
/*Link Control Register */
pcie_capability_read_word(pdev, PCI_EXP_LNKCTL, &linkctrl_reg);
pcipriv->ndis_adapter.linkctrl_reg = (u8)linkctrl_reg;
RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE, "Link Control Register =%x\n",
pcipriv->ndis_adapter.linkctrl_reg);
pci_read_config_byte(pdev, 0x98, &tmp);
tmp |= BIT(4);
pci_write_config_byte(pdev, 0x98, tmp);
tmp = 0x17;
pci_write_config_byte(pdev, 0x70f, tmp);
}
static void rtl_pci_init_aspm(struct ieee80211_hw *hw)
{
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
_rtl_pci_update_default_setting(hw);
if (ppsc->reg_rfps_level & RT_RF_PS_LEVEL_ALWAYS_ASPM) {
/*Always enable ASPM & Clock Req. */
rtl_pci_enable_aspm(hw);
RT_SET_PS_LEVEL(ppsc, RT_RF_PS_LEVEL_ALWAYS_ASPM);
}
}
static void _rtl_pci_io_handler_init(struct device *dev,
struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
rtlpriv->io.dev = dev;
rtlpriv->io.write8_async = pci_write8_async;
rtlpriv->io.write16_async = pci_write16_async;
rtlpriv->io.write32_async = pci_write32_async;
rtlpriv->io.read8_sync = pci_read8_sync;
rtlpriv->io.read16_sync = pci_read16_sync;
rtlpriv->io.read32_sync = pci_read32_sync;
}
static bool _rtl_update_earlymode_info(struct ieee80211_hw *hw,
struct sk_buff *skb, struct rtl_tcb_desc *tcb_desc, u8 tid)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct sk_buff *next_skb;
u8 additionlen = FCS_LEN;
/* here open is 4, wep/tkip is 8, aes is 12*/
if (info->control.hw_key)
additionlen += info->control.hw_key->icv_len;
/* The most skb num is 6 */
tcb_desc->empkt_num = 0;
spin_lock_bh(&rtlpriv->locks.waitq_lock);
skb_queue_walk(&rtlpriv->mac80211.skb_waitq[tid], next_skb) {
struct ieee80211_tx_info *next_info;
next_info = IEEE80211_SKB_CB(next_skb);
if (next_info->flags & IEEE80211_TX_CTL_AMPDU) {
tcb_desc->empkt_len[tcb_desc->empkt_num] =
next_skb->len + additionlen;
tcb_desc->empkt_num++;
} else {
break;
}
if (skb_queue_is_last(&rtlpriv->mac80211.skb_waitq[tid],
next_skb))
break;
if (tcb_desc->empkt_num >= rtlhal->max_earlymode_num)
break;
}
spin_unlock_bh(&rtlpriv->locks.waitq_lock);
return true;
}
/* just for early mode now */
static void _rtl_pci_tx_chk_waitq(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
struct sk_buff *skb = NULL;
struct ieee80211_tx_info *info = NULL;
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
int tid;
if (!rtlpriv->rtlhal.earlymode_enable)
return;
if (rtlpriv->dm.supp_phymode_switch &&
(rtlpriv->easy_concurrent_ctl.switch_in_process ||
(rtlpriv->buddy_priv &&
rtlpriv->buddy_priv->easy_concurrent_ctl.switch_in_process)))
return;
/* we juse use em for BE/BK/VI/VO */
for (tid = 7; tid >= 0; tid--) {
u8 hw_queue = ac_to_hwq[rtl_tid_to_ac(tid)];
struct rtl8192_tx_ring *ring = &rtlpci->tx_ring[hw_queue];
while (!mac->act_scanning &&
rtlpriv->psc.rfpwr_state == ERFON) {
struct rtl_tcb_desc tcb_desc;
memset(&tcb_desc, 0, sizeof(struct rtl_tcb_desc));
spin_lock_bh(&rtlpriv->locks.waitq_lock);
if (!skb_queue_empty(&mac->skb_waitq[tid]) &&
(ring->entries - skb_queue_len(&ring->queue) >
rtlhal->max_earlymode_num)) {
skb = skb_dequeue(&mac->skb_waitq[tid]);
} else {
spin_unlock_bh(&rtlpriv->locks.waitq_lock);
break;
}
spin_unlock_bh(&rtlpriv->locks.waitq_lock);
/* Some macaddr can't do early mode. like
* multicast/broadcast/no_qos data */
info = IEEE80211_SKB_CB(skb);
if (info->flags & IEEE80211_TX_CTL_AMPDU)
_rtl_update_earlymode_info(hw, skb,
&tcb_desc, tid);
rtlpriv->intf_ops->adapter_tx(hw, NULL, skb, &tcb_desc);
}
}
}
static void _rtl_pci_tx_isr(struct ieee80211_hw *hw, int prio)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
struct rtl8192_tx_ring *ring = &rtlpci->tx_ring[prio];
while (skb_queue_len(&ring->queue)) {
struct rtl_tx_desc *entry = &ring->desc[ring->idx];
struct sk_buff *skb;
struct ieee80211_tx_info *info;
__le16 fc;
u8 tid;
u8 own = (u8) rtlpriv->cfg->ops->get_desc((u8 *) entry, true,
HW_DESC_OWN);
/*beacon packet will only use the first
*descriptor by defaut, and the own may not
*be cleared by the hardware
*/
if (own)
return;
ring->idx = (ring->idx + 1) % ring->entries;
skb = __skb_dequeue(&ring->queue);
pci_unmap_single(rtlpci->pdev,
rtlpriv->cfg->ops->
get_desc((u8 *) entry, true,
HW_DESC_TXBUFF_ADDR),
skb->len, PCI_DMA_TODEVICE);
/* remove early mode header */
if (rtlpriv->rtlhal.earlymode_enable)
skb_pull(skb, EM_HDR_LEN);
RT_TRACE(rtlpriv, (COMP_INTR | COMP_SEND), DBG_TRACE,
"new ring->idx:%d, free: skb_queue_len:%d, free: seq:%x\n",
ring->idx,
skb_queue_len(&ring->queue),
*(u16 *) (skb->data + 22));
if (prio == TXCMD_QUEUE) {
dev_kfree_skb(skb);
goto tx_status_ok;
}
/* for sw LPS, just after NULL skb send out, we can
* sure AP knows we are sleeping, we should not let
* rf sleep
*/
fc = rtl_get_fc(skb);
if (ieee80211_is_nullfunc(fc)) {
if (ieee80211_has_pm(fc)) {
rtlpriv->mac80211.offchan_delay = true;
rtlpriv->psc.state_inap = true;
} else {
rtlpriv->psc.state_inap = false;
}
}
if (ieee80211_is_action(fc)) {
struct ieee80211_mgmt *action_frame =
(struct ieee80211_mgmt *)skb->data;
if (action_frame->u.action.u.ht_smps.action ==
WLAN_HT_ACTION_SMPS) {
dev_kfree_skb(skb);
goto tx_status_ok;
}
}
/* update tid tx pkt num */
tid = rtl_get_tid(skb);
if (tid <= 7)
rtlpriv->link_info.tidtx_inperiod[tid]++;
info = IEEE80211_SKB_CB(skb);
ieee80211_tx_info_clear_status(info);
info->flags |= IEEE80211_TX_STAT_ACK;
/*info->status.rates[0].count = 1; */
ieee80211_tx_status_irqsafe(hw, skb);
if ((ring->entries - skb_queue_len(&ring->queue))
== 2) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_LOUD,
"more desc left, wake skb_queue@%d, ring->idx = %d, skb_queue_len = 0x%d\n",
prio, ring->idx,
skb_queue_len(&ring->queue));
ieee80211_wake_queue(hw,
skb_get_queue_mapping
(skb));
}
tx_status_ok:
skb = NULL;
}
if (((rtlpriv->link_info.num_rx_inperiod +
rtlpriv->link_info.num_tx_inperiod) > 8) ||
(rtlpriv->link_info.num_rx_inperiod > 2)) {
rtlpriv->enter_ps = false;
schedule_work(&rtlpriv->works.lps_change_work);
}
}
static void _rtl_receive_one(struct ieee80211_hw *hw, struct sk_buff *skb,
struct ieee80211_rx_status rx_status)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct ieee80211_hdr *hdr = rtl_get_hdr(skb);
__le16 fc = rtl_get_fc(skb);
bool unicast = false;
struct sk_buff *uskb = NULL;
u8 *pdata;
memcpy(IEEE80211_SKB_RXCB(skb), &rx_status, sizeof(rx_status));
if (is_broadcast_ether_addr(hdr->addr1)) {
;/*TODO*/
} else if (is_multicast_ether_addr(hdr->addr1)) {
;/*TODO*/
} else {
unicast = true;
rtlpriv->stats.rxbytesunicast += skb->len;
}
rtl_is_special_data(hw, skb, false);
if (ieee80211_is_data(fc)) {
rtlpriv->cfg->ops->led_control(hw, LED_CTL_RX);
if (unicast)
rtlpriv->link_info.num_rx_inperiod++;
}
/* static bcn for roaming */
rtl_beacon_statistic(hw, skb);
rtl_p2p_info(hw, (void *)skb->data, skb->len);
/* for sw lps */
rtl_swlps_beacon(hw, (void *)skb->data, skb->len);
rtl_recognize_peer(hw, (void *)skb->data, skb->len);
if ((rtlpriv->mac80211.opmode == NL80211_IFTYPE_AP) &&
(rtlpriv->rtlhal.current_bandtype == BAND_ON_2_4G) &&
(ieee80211_is_beacon(fc) || ieee80211_is_probe_resp(fc)))
return;
if (unlikely(!rtl_action_proc(hw, skb, false)))
return;
uskb = dev_alloc_skb(skb->len + 128);
if (!uskb)
return; /* exit if allocation failed */
memcpy(IEEE80211_SKB_RXCB(uskb), &rx_status, sizeof(rx_status));
pdata = (u8 *)skb_put(uskb, skb->len);
memcpy(pdata, skb->data, skb->len);
ieee80211_rx_irqsafe(hw, uskb);
}
static void _rtl_pci_rx_interrupt(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
int rx_queue_idx = RTL_PCI_RX_MPDU_QUEUE;
struct ieee80211_rx_status rx_status = { 0 };
unsigned int count = rtlpci->rxringcount;
u8 own;
u8 tmp_one;
u32 bufferaddress;
struct rtl_stats stats = {
.signal = 0,
.noise = -98,
.rate = 0,
};
int index = rtlpci->rx_ring[rx_queue_idx].idx;
if (rtlpci->driver_is_goingto_unload)
return;
/*RX NORMAL PKT */
while (count--) {
/*rx descriptor */
struct rtl_rx_desc *pdesc = &rtlpci->rx_ring[rx_queue_idx].desc[
index];
/*rx pkt */
struct sk_buff *skb = rtlpci->rx_ring[rx_queue_idx].rx_buf[
index];
struct sk_buff *new_skb = NULL;
own = (u8) rtlpriv->cfg->ops->get_desc((u8 *) pdesc,
false, HW_DESC_OWN);
/*wait data to be filled by hardware */
if (own)
break;
rtlpriv->cfg->ops->query_rx_desc(hw, &stats,
&rx_status,
(u8 *) pdesc, skb);
if (stats.crc || stats.hwerror)
goto done;
new_skb = dev_alloc_skb(rtlpci->rxbuffersize);
if (unlikely(!new_skb)) {
RT_TRACE(rtlpriv, (COMP_INTR | COMP_RECV), DBG_DMESG,
"can't alloc skb for rx\n");
goto done;
}
kmemleak_not_leak(new_skb);
pci_unmap_single(rtlpci->pdev,
*((dma_addr_t *) skb->cb),
rtlpci->rxbuffersize,
PCI_DMA_FROMDEVICE);
skb_put(skb, rtlpriv->cfg->ops->get_desc((u8 *) pdesc, false,
HW_DESC_RXPKT_LEN));
skb_reserve(skb, stats.rx_drvinfo_size + stats.rx_bufshift);
/*
* NOTICE This can not be use for mac80211,
* this is done in mac80211 code,
* if you done here sec DHCP will fail
* skb_trim(skb, skb->len - 4);
*/
_rtl_receive_one(hw, skb, rx_status);
if (((rtlpriv->link_info.num_rx_inperiod +
rtlpriv->link_info.num_tx_inperiod) > 8) ||
(rtlpriv->link_info.num_rx_inperiod > 2)) {
rtlpriv->enter_ps = false;
schedule_work(&rtlpriv->works.lps_change_work);
}
dev_kfree_skb_any(skb);
skb = new_skb;
rtlpci->rx_ring[rx_queue_idx].rx_buf[index] = skb;
*((dma_addr_t *) skb->cb) =
pci_map_single(rtlpci->pdev, skb_tail_pointer(skb),
rtlpci->rxbuffersize,
PCI_DMA_FROMDEVICE);
done:
bufferaddress = (*((dma_addr_t *)skb->cb));
if (pci_dma_mapping_error(rtlpci->pdev, bufferaddress))
return;
tmp_one = 1;
rtlpriv->cfg->ops->set_desc((u8 *) pdesc, false,
HW_DESC_RXBUFF_ADDR,
(u8 *)&bufferaddress);
rtlpriv->cfg->ops->set_desc((u8 *)pdesc, false,
HW_DESC_RXPKT_LEN,
(u8 *)&rtlpci->rxbuffersize);
if (index == rtlpci->rxringcount - 1)
rtlpriv->cfg->ops->set_desc((u8 *)pdesc, false,
HW_DESC_RXERO,
&tmp_one);
rtlpriv->cfg->ops->set_desc((u8 *)pdesc, false, HW_DESC_RXOWN,
&tmp_one);
index = (index + 1) % rtlpci->rxringcount;
}
rtlpci->rx_ring[rx_queue_idx].idx = index;
}
static irqreturn_t _rtl_pci_interrupt(int irq, void *dev_id)
{
struct ieee80211_hw *hw = dev_id;
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
unsigned long flags;
u32 inta = 0;
u32 intb = 0;
irqreturn_t ret = IRQ_HANDLED;
spin_lock_irqsave(&rtlpriv->locks.irq_th_lock, flags);
/*read ISR: 4/8bytes */
rtlpriv->cfg->ops->interrupt_recognized(hw, &inta, &intb);
/*Shared IRQ or HW disappared */
if (!inta || inta == 0xffff) {
ret = IRQ_NONE;
goto done;
}
/*<1> beacon related */
if (inta & rtlpriv->cfg->maps[RTL_IMR_TBDOK]) {
RT_TRACE(rtlpriv, COMP_INTR, DBG_TRACE,
"beacon ok interrupt!\n");
}
if (unlikely(inta & rtlpriv->cfg->maps[RTL_IMR_TBDER])) {
RT_TRACE(rtlpriv, COMP_INTR, DBG_TRACE,
"beacon err interrupt!\n");
}
if (inta & rtlpriv->cfg->maps[RTL_IMR_BDOK]) {
RT_TRACE(rtlpriv, COMP_INTR, DBG_TRACE, "beacon interrupt!\n");
}
if (inta & rtlpriv->cfg->maps[RTL_IMR_BCNINT]) {
RT_TRACE(rtlpriv, COMP_INTR, DBG_TRACE,
"prepare beacon for interrupt!\n");
tasklet_schedule(&rtlpriv->works.irq_prepare_bcn_tasklet);
}
/*<3> Tx related */
if (unlikely(inta & rtlpriv->cfg->maps[RTL_IMR_TXFOVW]))
RT_TRACE(rtlpriv, COMP_ERR, DBG_WARNING, "IMR_TXFOVW!\n");
if (inta & rtlpriv->cfg->maps[RTL_IMR_MGNTDOK]) {
RT_TRACE(rtlpriv, COMP_INTR, DBG_TRACE,
"Manage ok interrupt!\n");
_rtl_pci_tx_isr(hw, MGNT_QUEUE);
}
if (inta & rtlpriv->cfg->maps[RTL_IMR_HIGHDOK]) {
RT_TRACE(rtlpriv, COMP_INTR, DBG_TRACE,
"HIGH_QUEUE ok interrupt!\n");
_rtl_pci_tx_isr(hw, HIGH_QUEUE);
}
if (inta & rtlpriv->cfg->maps[RTL_IMR_BKDOK]) {
rtlpriv->link_info.num_tx_inperiod++;
RT_TRACE(rtlpriv, COMP_INTR, DBG_TRACE,
"BK Tx OK interrupt!\n");
_rtl_pci_tx_isr(hw, BK_QUEUE);
}
if (inta & rtlpriv->cfg->maps[RTL_IMR_BEDOK]) {
rtlpriv->link_info.num_tx_inperiod++;
RT_TRACE(rtlpriv, COMP_INTR, DBG_TRACE,
"BE TX OK interrupt!\n");
_rtl_pci_tx_isr(hw, BE_QUEUE);
}
if (inta & rtlpriv->cfg->maps[RTL_IMR_VIDOK]) {
rtlpriv->link_info.num_tx_inperiod++;
RT_TRACE(rtlpriv, COMP_INTR, DBG_TRACE,
"VI TX OK interrupt!\n");
_rtl_pci_tx_isr(hw, VI_QUEUE);
}
if (inta & rtlpriv->cfg->maps[RTL_IMR_VODOK]) {
rtlpriv->link_info.num_tx_inperiod++;
RT_TRACE(rtlpriv, COMP_INTR, DBG_TRACE,
"Vo TX OK interrupt!\n");
_rtl_pci_tx_isr(hw, VO_QUEUE);
}
if (rtlhal->hw_type == HARDWARE_TYPE_RTL8192SE) {
if (inta & rtlpriv->cfg->maps[RTL_IMR_COMDOK]) {
rtlpriv->link_info.num_tx_inperiod++;
RT_TRACE(rtlpriv, COMP_INTR, DBG_TRACE,
"CMD TX OK interrupt!\n");
_rtl_pci_tx_isr(hw, TXCMD_QUEUE);
}
}
/*<2> Rx related */
if (inta & rtlpriv->cfg->maps[RTL_IMR_ROK]) {
RT_TRACE(rtlpriv, COMP_INTR, DBG_TRACE, "Rx ok interrupt!\n");
_rtl_pci_rx_interrupt(hw);
}
if (unlikely(inta & rtlpriv->cfg->maps[RTL_IMR_RDU])) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_WARNING,
"rx descriptor unavailable!\n");
_rtl_pci_rx_interrupt(hw);
}
if (unlikely(inta & rtlpriv->cfg->maps[RTL_IMR_RXFOVW])) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_WARNING, "rx overflow !\n");
_rtl_pci_rx_interrupt(hw);
}
/*fw related*/
if (rtlhal->hw_type == HARDWARE_TYPE_RTL8723AE) {
if (inta & rtlpriv->cfg->maps[RTL_IMR_C2HCMD]) {
RT_TRACE(rtlpriv, COMP_INTR, DBG_TRACE,
"firmware interrupt!\n");
queue_delayed_work(rtlpriv->works.rtl_wq,
&rtlpriv->works.fwevt_wq, 0);
}
}
if (rtlpriv->rtlhal.earlymode_enable)
tasklet_schedule(&rtlpriv->works.irq_tasklet);
done:
spin_unlock_irqrestore(&rtlpriv->locks.irq_th_lock, flags);
return ret;
}
static void _rtl_pci_irq_tasklet(struct ieee80211_hw *hw)
{
_rtl_pci_tx_chk_waitq(hw);
}
static void _rtl_pci_prepare_bcn_tasklet(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl8192_tx_ring *ring = NULL;
struct ieee80211_hdr *hdr = NULL;
struct ieee80211_tx_info *info = NULL;
struct sk_buff *pskb = NULL;
struct rtl_tx_desc *pdesc = NULL;
struct rtl_tcb_desc tcb_desc;
u8 temp_one = 1;
memset(&tcb_desc, 0, sizeof(struct rtl_tcb_desc));
ring = &rtlpci->tx_ring[BEACON_QUEUE];
pskb = __skb_dequeue(&ring->queue);
if (pskb) {
struct rtl_tx_desc *entry = &ring->desc[ring->idx];
pci_unmap_single(rtlpci->pdev, rtlpriv->cfg->ops->get_desc(
(u8 *) entry, true, HW_DESC_TXBUFF_ADDR),
pskb->len, PCI_DMA_TODEVICE);
kfree_skb(pskb);
}
/*NB: the beacon data buffer must be 32-bit aligned. */
pskb = ieee80211_beacon_get(hw, mac->vif);
if (pskb == NULL)
return;
hdr = rtl_get_hdr(pskb);
info = IEEE80211_SKB_CB(pskb);
pdesc = &ring->desc[0];
rtlpriv->cfg->ops->fill_tx_desc(hw, hdr, (u8 *) pdesc,
info, NULL, pskb, BEACON_QUEUE, &tcb_desc);
__skb_queue_tail(&ring->queue, pskb);
rtlpriv->cfg->ops->set_desc((u8 *) pdesc, true, HW_DESC_OWN,
&temp_one);
return;
}
static void _rtl_pci_init_trx_var(struct ieee80211_hw *hw)
{
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
u8 i;
for (i = 0; i < RTL_PCI_MAX_TX_QUEUE_COUNT; i++)
rtlpci->txringcount[i] = RT_TXDESC_NUM;
/*
*we just alloc 2 desc for beacon queue,
*because we just need first desc in hw beacon.
*/
rtlpci->txringcount[BEACON_QUEUE] = 2;
/*
*BE queue need more descriptor for performance
*consideration or, No more tx desc will happen,
*and may cause mac80211 mem leakage.
*/
rtlpci->txringcount[BE_QUEUE] = RT_TXDESC_NUM_BE_QUEUE;
rtlpci->rxbuffersize = 9100; /*2048/1024; */
rtlpci->rxringcount = RTL_PCI_MAX_RX_COUNT; /*64; */
}
static void _rtl_pci_init_struct(struct ieee80211_hw *hw,
struct pci_dev *pdev)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
rtlpci->up_first_time = true;
rtlpci->being_init_adapter = false;
rtlhal->hw = hw;
rtlpci->pdev = pdev;
/*Tx/Rx related var */
_rtl_pci_init_trx_var(hw);
/*IBSS*/ mac->beacon_interval = 100;
/*AMPDU*/
mac->min_space_cfg = 0;
mac->max_mss_density = 0;
/*set sane AMPDU defaults */
mac->current_ampdu_density = 7;
mac->current_ampdu_factor = 3;
/*QOS*/
rtlpci->acm_method = eAcmWay2_SW;
/*task */
tasklet_init(&rtlpriv->works.irq_tasklet,
(void (*)(unsigned long))_rtl_pci_irq_tasklet,
(unsigned long)hw);
tasklet_init(&rtlpriv->works.irq_prepare_bcn_tasklet,
(void (*)(unsigned long))_rtl_pci_prepare_bcn_tasklet,
(unsigned long)hw);
INIT_WORK(&rtlpriv->works.lps_change_work,
rtl_lps_change_work_callback);
}
static int _rtl_pci_init_tx_ring(struct ieee80211_hw *hw,
unsigned int prio, unsigned int entries)
{
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_tx_desc *ring;
dma_addr_t dma;
u32 nextdescaddress;
int i;
ring = pci_alloc_consistent(rtlpci->pdev,
sizeof(*ring) * entries, &dma);
if (!ring || (unsigned long)ring & 0xFF) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"Cannot allocate TX ring (prio = %d)\n", prio);
return -ENOMEM;
}
memset(ring, 0, sizeof(*ring) * entries);
rtlpci->tx_ring[prio].desc = ring;
rtlpci->tx_ring[prio].dma = dma;
rtlpci->tx_ring[prio].idx = 0;
rtlpci->tx_ring[prio].entries = entries;
skb_queue_head_init(&rtlpci->tx_ring[prio].queue);
RT_TRACE(rtlpriv, COMP_INIT, DBG_LOUD, "queue:%d, ring_addr:%p\n",
prio, ring);
for (i = 0; i < entries; i++) {
nextdescaddress = (u32) dma +
((i + 1) % entries) *
sizeof(*ring);
rtlpriv->cfg->ops->set_desc((u8 *)&(ring[i]),
true, HW_DESC_TX_NEXTDESC_ADDR,
(u8 *)&nextdescaddress);
}
return 0;
}
static int _rtl_pci_init_rx_ring(struct ieee80211_hw *hw)
{
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_rx_desc *entry = NULL;
int i, rx_queue_idx;
u8 tmp_one = 1;
/*
*rx_queue_idx 0:RX_MPDU_QUEUE
*rx_queue_idx 1:RX_CMD_QUEUE
*/
for (rx_queue_idx = 0; rx_queue_idx < RTL_PCI_MAX_RX_QUEUE;
rx_queue_idx++) {
rtlpci->rx_ring[rx_queue_idx].desc =
pci_alloc_consistent(rtlpci->pdev,
sizeof(*rtlpci->rx_ring[rx_queue_idx].
desc) * rtlpci->rxringcount,
&rtlpci->rx_ring[rx_queue_idx].dma);
if (!rtlpci->rx_ring[rx_queue_idx].desc ||
(unsigned long)rtlpci->rx_ring[rx_queue_idx].desc & 0xFF) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"Cannot allocate RX ring\n");
return -ENOMEM;
}
memset(rtlpci->rx_ring[rx_queue_idx].desc, 0,
sizeof(*rtlpci->rx_ring[rx_queue_idx].desc) *
rtlpci->rxringcount);
rtlpci->rx_ring[rx_queue_idx].idx = 0;
/* If amsdu_8k is disabled, set buffersize to 4096. This
* change will reduce memory fragmentation.
*/
if (rtlpci->rxbuffersize > 4096 &&
rtlpriv->rtlhal.disable_amsdu_8k)
rtlpci->rxbuffersize = 4096;
for (i = 0; i < rtlpci->rxringcount; i++) {
struct sk_buff *skb =
dev_alloc_skb(rtlpci->rxbuffersize);
u32 bufferaddress;
if (!skb)
return 0;
kmemleak_not_leak(skb);
entry = &rtlpci->rx_ring[rx_queue_idx].desc[i];
/*skb->dev = dev; */
rtlpci->rx_ring[rx_queue_idx].rx_buf[i] = skb;
/*
*just set skb->cb to mapping addr
*for pci_unmap_single use
*/
*((dma_addr_t *) skb->cb) =
pci_map_single(rtlpci->pdev, skb_tail_pointer(skb),
rtlpci->rxbuffersize,
PCI_DMA_FROMDEVICE);
bufferaddress = (*((dma_addr_t *)skb->cb));
if (pci_dma_mapping_error(rtlpci->pdev, bufferaddress)) {
dev_kfree_skb_any(skb);
return 1;
}
rtlpriv->cfg->ops->set_desc((u8 *)entry, false,
HW_DESC_RXBUFF_ADDR,
(u8 *)&bufferaddress);
rtlpriv->cfg->ops->set_desc((u8 *)entry, false,
HW_DESC_RXPKT_LEN,
(u8 *)&rtlpci->
rxbuffersize);
rtlpriv->cfg->ops->set_desc((u8 *) entry, false,
HW_DESC_RXOWN,
&tmp_one);
}
rtlpriv->cfg->ops->set_desc((u8 *) entry, false,
HW_DESC_RXERO, &tmp_one);
}
return 0;
}
static void _rtl_pci_free_tx_ring(struct ieee80211_hw *hw,
unsigned int prio)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
struct rtl8192_tx_ring *ring = &rtlpci->tx_ring[prio];
while (skb_queue_len(&ring->queue)) {
struct rtl_tx_desc *entry = &ring->desc[ring->idx];
struct sk_buff *skb = __skb_dequeue(&ring->queue);
pci_unmap_single(rtlpci->pdev,
rtlpriv->cfg->
ops->get_desc((u8 *) entry, true,
HW_DESC_TXBUFF_ADDR),
skb->len, PCI_DMA_TODEVICE);
kfree_skb(skb);
ring->idx = (ring->idx + 1) % ring->entries;
}
if (ring->desc) {
pci_free_consistent(rtlpci->pdev,
sizeof(*ring->desc) * ring->entries,
ring->desc, ring->dma);
ring->desc = NULL;
}
}
static void _rtl_pci_free_rx_ring(struct rtl_pci *rtlpci)
{
int i, rx_queue_idx;
/*rx_queue_idx 0:RX_MPDU_QUEUE */
/*rx_queue_idx 1:RX_CMD_QUEUE */
for (rx_queue_idx = 0; rx_queue_idx < RTL_PCI_MAX_RX_QUEUE;
rx_queue_idx++) {
for (i = 0; i < rtlpci->rxringcount; i++) {
struct sk_buff *skb =
rtlpci->rx_ring[rx_queue_idx].rx_buf[i];
if (!skb)
continue;
pci_unmap_single(rtlpci->pdev,
*((dma_addr_t *) skb->cb),
rtlpci->rxbuffersize,
PCI_DMA_FROMDEVICE);
kfree_skb(skb);
}
if (rtlpci->rx_ring[rx_queue_idx].desc) {
pci_free_consistent(rtlpci->pdev,
sizeof(*rtlpci->rx_ring[rx_queue_idx].
desc) * rtlpci->rxringcount,
rtlpci->rx_ring[rx_queue_idx].desc,
rtlpci->rx_ring[rx_queue_idx].dma);
rtlpci->rx_ring[rx_queue_idx].desc = NULL;
}
}
}
static int _rtl_pci_init_trx_ring(struct ieee80211_hw *hw)
{
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
int ret;
int i;
ret = _rtl_pci_init_rx_ring(hw);
if (ret)
return ret;
for (i = 0; i < RTL_PCI_MAX_TX_QUEUE_COUNT; i++) {
ret = _rtl_pci_init_tx_ring(hw, i,
rtlpci->txringcount[i]);
if (ret)
goto err_free_rings;
}
return 0;
err_free_rings:
_rtl_pci_free_rx_ring(rtlpci);
for (i = 0; i < RTL_PCI_MAX_TX_QUEUE_COUNT; i++)
if (rtlpci->tx_ring[i].desc)
_rtl_pci_free_tx_ring(hw, i);
return 1;
}
static int _rtl_pci_deinit_trx_ring(struct ieee80211_hw *hw)
{
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
u32 i;
/*free rx rings */
_rtl_pci_free_rx_ring(rtlpci);
/*free tx rings */
for (i = 0; i < RTL_PCI_MAX_TX_QUEUE_COUNT; i++)
_rtl_pci_free_tx_ring(hw, i);
return 0;
}
int rtl_pci_reset_trx_ring(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
int i, rx_queue_idx;
unsigned long flags;
u8 tmp_one = 1;
/*rx_queue_idx 0:RX_MPDU_QUEUE */
/*rx_queue_idx 1:RX_CMD_QUEUE */
for (rx_queue_idx = 0; rx_queue_idx < RTL_PCI_MAX_RX_QUEUE;
rx_queue_idx++) {
/*
*force the rx_ring[RX_MPDU_QUEUE/
*RX_CMD_QUEUE].idx to the first one
*/
if (rtlpci->rx_ring[rx_queue_idx].desc) {
struct rtl_rx_desc *entry = NULL;
for (i = 0; i < rtlpci->rxringcount; i++) {
entry = &rtlpci->rx_ring[rx_queue_idx].desc[i];
rtlpriv->cfg->ops->set_desc((u8 *) entry,
false,
HW_DESC_RXOWN,
&tmp_one);
}
rtlpci->rx_ring[rx_queue_idx].idx = 0;
}
}
/*
*after reset, release previous pending packet,
*and force the tx idx to the first one
*/
for (i = 0; i < RTL_PCI_MAX_TX_QUEUE_COUNT; i++) {
if (rtlpci->tx_ring[i].desc) {
struct rtl8192_tx_ring *ring = &rtlpci->tx_ring[i];
while (skb_queue_len(&ring->queue)) {
struct rtl_tx_desc *entry;
struct sk_buff *skb;
spin_lock_irqsave(&rtlpriv->locks.irq_th_lock,
flags);
entry = &ring->desc[ring->idx];
skb = __skb_dequeue(&ring->queue);
pci_unmap_single(rtlpci->pdev,
rtlpriv->cfg->ops->
get_desc((u8 *)
entry,
true,
HW_DESC_TXBUFF_ADDR),
skb->len, PCI_DMA_TODEVICE);
ring->idx = (ring->idx + 1) % ring->entries;
spin_unlock_irqrestore(&rtlpriv->locks.irq_th_lock,
flags);
kfree_skb(skb);
}
ring->idx = 0;
}
}
return 0;
}
static bool rtl_pci_tx_chk_waitq_insert(struct ieee80211_hw *hw,
struct ieee80211_sta *sta,
struct sk_buff *skb)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_sta_info *sta_entry = NULL;
u8 tid = rtl_get_tid(skb);
__le16 fc = rtl_get_fc(skb);
if (!sta)
return false;
sta_entry = (struct rtl_sta_info *)sta->drv_priv;
if (!rtlpriv->rtlhal.earlymode_enable)
return false;
if (ieee80211_is_nullfunc(fc))
return false;
if (ieee80211_is_qos_nullfunc(fc))
return false;
if (ieee80211_is_pspoll(fc))
return false;
if (sta_entry->tids[tid].agg.agg_state != RTL_AGG_OPERATIONAL)
return false;
if (_rtl_mac_to_hwqueue(hw, skb) > VO_QUEUE)
return false;
if (tid > 7)
return false;
/* maybe every tid should be checked */
if (!rtlpriv->link_info.higher_busytxtraffic[tid])
return false;
spin_lock_bh(&rtlpriv->locks.waitq_lock);
skb_queue_tail(&rtlpriv->mac80211.skb_waitq[tid], skb);
spin_unlock_bh(&rtlpriv->locks.waitq_lock);
return true;
}
static int rtl_pci_tx(struct ieee80211_hw *hw,
struct ieee80211_sta *sta,
struct sk_buff *skb,
struct rtl_tcb_desc *ptcb_desc)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_sta_info *sta_entry = NULL;
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
struct rtl8192_tx_ring *ring;
struct rtl_tx_desc *pdesc;
u8 idx;
u8 hw_queue = _rtl_mac_to_hwqueue(hw, skb);
unsigned long flags;
struct ieee80211_hdr *hdr = rtl_get_hdr(skb);
__le16 fc = rtl_get_fc(skb);
u8 *pda_addr = hdr->addr1;
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
/*ssn */
u8 tid = 0;
u16 seq_number = 0;
u8 own;
u8 temp_one = 1;
if (ieee80211_is_mgmt(fc))
rtl_tx_mgmt_proc(hw, skb);
if (rtlpriv->psc.sw_ps_enabled) {
if (ieee80211_is_data(fc) && !ieee80211_is_nullfunc(fc) &&
!ieee80211_has_pm(fc))
hdr->frame_control |= cpu_to_le16(IEEE80211_FCTL_PM);
}
rtl_action_proc(hw, skb, true);
if (is_multicast_ether_addr(pda_addr))
rtlpriv->stats.txbytesmulticast += skb->len;
else if (is_broadcast_ether_addr(pda_addr))
rtlpriv->stats.txbytesbroadcast += skb->len;
else
rtlpriv->stats.txbytesunicast += skb->len;
spin_lock_irqsave(&rtlpriv->locks.irq_th_lock, flags);
ring = &rtlpci->tx_ring[hw_queue];
if (hw_queue != BEACON_QUEUE)
idx = (ring->idx + skb_queue_len(&ring->queue)) %
ring->entries;
else
idx = 0;
pdesc = &ring->desc[idx];
own = (u8) rtlpriv->cfg->ops->get_desc((u8 *) pdesc,
true, HW_DESC_OWN);
if ((own == 1) && (hw_queue != BEACON_QUEUE)) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_WARNING,
"No more TX desc@%d, ring->idx = %d, idx = %d, skb_queue_len = 0x%d\n",
hw_queue, ring->idx, idx,
skb_queue_len(&ring->queue));
spin_unlock_irqrestore(&rtlpriv->locks.irq_th_lock, flags);
return skb->len;
}
if (ieee80211_is_data_qos(fc)) {
tid = rtl_get_tid(skb);
if (sta) {
sta_entry = (struct rtl_sta_info *)sta->drv_priv;
seq_number = (le16_to_cpu(hdr->seq_ctrl) &
IEEE80211_SCTL_SEQ) >> 4;
seq_number += 1;
if (!ieee80211_has_morefrags(hdr->frame_control))
sta_entry->tids[tid].seq_number = seq_number;
}
}
if (ieee80211_is_data(fc))
rtlpriv->cfg->ops->led_control(hw, LED_CTL_TX);
rtlpriv->cfg->ops->fill_tx_desc(hw, hdr, (u8 *)pdesc,
info, sta, skb, hw_queue, ptcb_desc);
__skb_queue_tail(&ring->queue, skb);
rtlpriv->cfg->ops->set_desc((u8 *)pdesc, true,
HW_DESC_OWN, &temp_one);
if ((ring->entries - skb_queue_len(&ring->queue)) < 2 &&
hw_queue != BEACON_QUEUE) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_LOUD,
"less desc left, stop skb_queue@%d, ring->idx = %d, idx = %d, skb_queue_len = 0x%d\n",
hw_queue, ring->idx, idx,
skb_queue_len(&ring->queue));
ieee80211_stop_queue(hw, skb_get_queue_mapping(skb));
}
spin_unlock_irqrestore(&rtlpriv->locks.irq_th_lock, flags);
rtlpriv->cfg->ops->tx_polling(hw, hw_queue);
return 0;
}
static void rtl_pci_flush(struct ieee80211_hw *hw, bool drop)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_pci_priv *pcipriv = rtl_pcipriv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
u16 i = 0;
int queue_id;
struct rtl8192_tx_ring *ring;
if (mac->skip_scan)
return;
for (queue_id = RTL_PCI_MAX_TX_QUEUE_COUNT - 1; queue_id >= 0;) {
u32 queue_len;
ring = &pcipriv->dev.tx_ring[queue_id];
queue_len = skb_queue_len(&ring->queue);
if (queue_len == 0 || queue_id == BEACON_QUEUE ||
queue_id == TXCMD_QUEUE) {
queue_id--;
continue;
} else {
msleep(20);
i++;
}
/* we just wait 1s for all queues */
if (rtlpriv->psc.rfpwr_state == ERFOFF ||
is_hal_stop(rtlhal) || i >= 200)
return;
}
}
static void rtl_pci_deinit(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
_rtl_pci_deinit_trx_ring(hw);
synchronize_irq(rtlpci->pdev->irq);
tasklet_kill(&rtlpriv->works.irq_tasklet);
cancel_work_sync(&rtlpriv->works.lps_change_work);
flush_workqueue(rtlpriv->works.rtl_wq);
destroy_workqueue(rtlpriv->works.rtl_wq);
}
static int rtl_pci_init(struct ieee80211_hw *hw, struct pci_dev *pdev)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
int err;
_rtl_pci_init_struct(hw, pdev);
err = _rtl_pci_init_trx_ring(hw);
if (err) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"tx ring initialization failed\n");
return err;
}
return 0;
}
static int rtl_pci_start(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
int err;
rtl_pci_reset_trx_ring(hw);
rtlpci->driver_is_goingto_unload = false;
err = rtlpriv->cfg->ops->hw_init(hw);
if (err) {
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG,
"Failed to config hardware!\n");
return err;
}
rtlpriv->cfg->ops->enable_interrupt(hw);
RT_TRACE(rtlpriv, COMP_INIT, DBG_LOUD, "enable_interrupt OK\n");
rtl_init_rx_config(hw);
/*should be after adapter start and interrupt enable. */
set_hal_start(rtlhal);
RT_CLEAR_PS_LEVEL(ppsc, RT_RF_OFF_LEVL_HALT_NIC);
rtlpci->up_first_time = false;
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG, "OK\n");
return 0;
}
static void rtl_pci_stop(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
unsigned long flags;
u8 RFInProgressTimeOut = 0;
/*
*should be before disable interrupt&adapter
*and will do it immediately.
*/
set_hal_stop(rtlhal);
rtlpci->driver_is_goingto_unload = true;
rtlpriv->cfg->ops->disable_interrupt(hw);
cancel_work_sync(&rtlpriv->works.lps_change_work);
spin_lock_irqsave(&rtlpriv->locks.rf_ps_lock, flags);
while (ppsc->rfchange_inprogress) {
spin_unlock_irqrestore(&rtlpriv->locks.rf_ps_lock, flags);
if (RFInProgressTimeOut > 100) {
spin_lock_irqsave(&rtlpriv->locks.rf_ps_lock, flags);
break;
}
mdelay(1);
RFInProgressTimeOut++;
spin_lock_irqsave(&rtlpriv->locks.rf_ps_lock, flags);
}
ppsc->rfchange_inprogress = true;
spin_unlock_irqrestore(&rtlpriv->locks.rf_ps_lock, flags);
rtlpriv->cfg->ops->hw_disable(hw);
/* some things are not needed if firmware not available */
if (!rtlpriv->max_fw_size)
return;
rtlpriv->cfg->ops->led_control(hw, LED_CTL_POWER_OFF);
spin_lock_irqsave(&rtlpriv->locks.rf_ps_lock, flags);
ppsc->rfchange_inprogress = false;
spin_unlock_irqrestore(&rtlpriv->locks.rf_ps_lock, flags);
rtl_pci_enable_aspm(hw);
}
static bool _rtl_pci_find_adapter(struct pci_dev *pdev,
struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_pci_priv *pcipriv = rtl_pcipriv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct pci_dev *bridge_pdev = pdev->bus->self;
u16 venderid;
u16 deviceid;
u8 revisionid;
u16 irqline;
u8 tmp;
pcipriv->ndis_adapter.pcibridge_vendor = PCI_BRIDGE_VENDOR_UNKNOWN;
venderid = pdev->vendor;
deviceid = pdev->device;
pci_read_config_byte(pdev, 0x8, &revisionid);
pci_read_config_word(pdev, 0x3C, &irqline);
/* PCI ID 0x10ec:0x8192 occurs for both RTL8192E, which uses
* r8192e_pci, and RTL8192SE, which uses this driver. If the
* revision ID is RTL_PCI_REVISION_ID_8192PCIE (0x01), then
* the correct driver is r8192e_pci, thus this routine should
* return false.
*/
if (deviceid == RTL_PCI_8192SE_DID &&
revisionid == RTL_PCI_REVISION_ID_8192PCIE)
return false;
if (deviceid == RTL_PCI_8192_DID ||
deviceid == RTL_PCI_0044_DID ||
deviceid == RTL_PCI_0047_DID ||
deviceid == RTL_PCI_8192SE_DID ||
deviceid == RTL_PCI_8174_DID ||
deviceid == RTL_PCI_8173_DID ||
deviceid == RTL_PCI_8172_DID ||
deviceid == RTL_PCI_8171_DID) {
switch (revisionid) {
case RTL_PCI_REVISION_ID_8192PCIE:
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG,
"8192 PCI-E is found - vid/did=%x/%x\n",
venderid, deviceid);
rtlhal->hw_type = HARDWARE_TYPE_RTL8192E;
return false;
case RTL_PCI_REVISION_ID_8192SE:
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG,
"8192SE is found - vid/did=%x/%x\n",
venderid, deviceid);
rtlhal->hw_type = HARDWARE_TYPE_RTL8192SE;
break;
default:
RT_TRACE(rtlpriv, COMP_ERR, DBG_WARNING,
"Err: Unknown device - vid/did=%x/%x\n",
venderid, deviceid);
rtlhal->hw_type = HARDWARE_TYPE_RTL8192SE;
break;
}
} else if (deviceid == RTL_PCI_8723AE_DID) {
rtlhal->hw_type = HARDWARE_TYPE_RTL8723AE;
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG,
"8723AE PCI-E is found - "
"vid/did=%x/%x\n", venderid, deviceid);
} else if (deviceid == RTL_PCI_8192CET_DID ||
deviceid == RTL_PCI_8192CE_DID ||
deviceid == RTL_PCI_8191CE_DID ||
deviceid == RTL_PCI_8188CE_DID) {
rtlhal->hw_type = HARDWARE_TYPE_RTL8192CE;
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG,
"8192C PCI-E is found - vid/did=%x/%x\n",
venderid, deviceid);
} else if (deviceid == RTL_PCI_8192DE_DID ||
deviceid == RTL_PCI_8192DE_DID2) {
rtlhal->hw_type = HARDWARE_TYPE_RTL8192DE;
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG,
"8192D PCI-E is found - vid/did=%x/%x\n",
venderid, deviceid);
} else if (deviceid == RTL_PCI_8188EE_DID) {
rtlhal->hw_type = HARDWARE_TYPE_RTL8188EE;
RT_TRACE(rtlpriv, COMP_INIT, DBG_LOUD,
"Find adapter, Hardware type is 8188EE\n");
} else {
RT_TRACE(rtlpriv, COMP_ERR, DBG_WARNING,
"Err: Unknown device - vid/did=%x/%x\n",
venderid, deviceid);
rtlhal->hw_type = RTL_DEFAULT_HARDWARE_TYPE;
}
if (rtlhal->hw_type == HARDWARE_TYPE_RTL8192DE) {
if (revisionid == 0 || revisionid == 1) {
if (revisionid == 0) {
RT_TRACE(rtlpriv, COMP_INIT, DBG_LOUD,
"Find 92DE MAC0\n");
rtlhal->interfaceindex = 0;
} else if (revisionid == 1) {
RT_TRACE(rtlpriv, COMP_INIT, DBG_LOUD,
"Find 92DE MAC1\n");
rtlhal->interfaceindex = 1;
}
} else {
RT_TRACE(rtlpriv, COMP_INIT, DBG_LOUD,
"Unknown device - VendorID/DeviceID=%x/%x, Revision=%x\n",
venderid, deviceid, revisionid);
rtlhal->interfaceindex = 0;
}
}
/*find bus info */
pcipriv->ndis_adapter.busnumber = pdev->bus->number;
pcipriv->ndis_adapter.devnumber = PCI_SLOT(pdev->devfn);
pcipriv->ndis_adapter.funcnumber = PCI_FUNC(pdev->devfn);
/* some ARM have no bridge_pdev and will crash here
* so we should check if bridge_pdev is NULL
*/
if (bridge_pdev) {
/*find bridge info if available */
pcipriv->ndis_adapter.pcibridge_vendorid = bridge_pdev->vendor;
for (tmp = 0; tmp < PCI_BRIDGE_VENDOR_MAX; tmp++) {
if (bridge_pdev->vendor == pcibridge_vendors[tmp]) {
pcipriv->ndis_adapter.pcibridge_vendor = tmp;
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG,
"Pci Bridge Vendor is found index: %d\n",
tmp);
break;
}
}
}
if (pcipriv->ndis_adapter.pcibridge_vendor !=
PCI_BRIDGE_VENDOR_UNKNOWN) {
pcipriv->ndis_adapter.pcibridge_busnum =
bridge_pdev->bus->number;
pcipriv->ndis_adapter.pcibridge_devnum =
PCI_SLOT(bridge_pdev->devfn);
pcipriv->ndis_adapter.pcibridge_funcnum =
PCI_FUNC(bridge_pdev->devfn);
pcipriv->ndis_adapter.pcibridge_pciehdr_offset =
pci_pcie_cap(bridge_pdev);
pcipriv->ndis_adapter.num4bytes =
(pcipriv->ndis_adapter.pcibridge_pciehdr_offset + 0x10) / 4;
rtl_pci_get_linkcontrol_field(hw);
if (pcipriv->ndis_adapter.pcibridge_vendor ==
PCI_BRIDGE_VENDOR_AMD) {
pcipriv->ndis_adapter.amd_l1_patch =
rtl_pci_get_amd_l1_patch(hw);
}
}
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG,
"pcidev busnumber:devnumber:funcnumber:vendor:link_ctl %d:%d:%d:%x:%x\n",
pcipriv->ndis_adapter.busnumber,
pcipriv->ndis_adapter.devnumber,
pcipriv->ndis_adapter.funcnumber,
pdev->vendor, pcipriv->ndis_adapter.linkctrl_reg);
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG,
"pci_bridge busnumber:devnumber:funcnumber:vendor:pcie_cap:link_ctl_reg:amd %d:%d:%d:%x:%x:%x:%x\n",
pcipriv->ndis_adapter.pcibridge_busnum,
pcipriv->ndis_adapter.pcibridge_devnum,
pcipriv->ndis_adapter.pcibridge_funcnum,
pcibridge_vendors[pcipriv->ndis_adapter.pcibridge_vendor],
pcipriv->ndis_adapter.pcibridge_pciehdr_offset,
pcipriv->ndis_adapter.pcibridge_linkctrlreg,
pcipriv->ndis_adapter.amd_l1_patch);
rtl_pci_parse_configuration(pdev, hw);
list_add_tail(&rtlpriv->list, &rtlpriv->glb_var->glb_priv_list);
return true;
}
int rtl_pci_probe(struct pci_dev *pdev,
const struct pci_device_id *id)
{
struct ieee80211_hw *hw = NULL;
struct rtl_priv *rtlpriv = NULL;
struct rtl_pci_priv *pcipriv = NULL;
struct rtl_pci *rtlpci;
unsigned long pmem_start, pmem_len, pmem_flags;
int err;
err = pci_enable_device(pdev);
if (err) {
RT_ASSERT(false, "%s : Cannot enable new PCI device\n",
pci_name(pdev));
return err;
}
if (!pci_set_dma_mask(pdev, DMA_BIT_MASK(32))) {
if (pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32))) {
RT_ASSERT(false,
"Unable to obtain 32bit DMA for consistent allocations\n");
err = -ENOMEM;
goto fail1;
}
}
pci_set_master(pdev);
hw = ieee80211_alloc_hw(sizeof(struct rtl_pci_priv) +
sizeof(struct rtl_priv), &rtl_ops);
if (!hw) {
RT_ASSERT(false,
"%s : ieee80211 alloc failed\n", pci_name(pdev));
err = -ENOMEM;
goto fail1;
}
SET_IEEE80211_DEV(hw, &pdev->dev);
pci_set_drvdata(pdev, hw);
rtlpriv = hw->priv;
rtlpriv->hw = hw;
pcipriv = (void *)rtlpriv->priv;
pcipriv->dev.pdev = pdev;
init_completion(&rtlpriv->firmware_loading_complete);
/* init cfg & intf_ops */
rtlpriv->rtlhal.interface = INTF_PCI;
rtlpriv->cfg = (struct rtl_hal_cfg *)(id->driver_data);
rtlpriv->intf_ops = &rtl_pci_ops;
rtlpriv->glb_var = &global_var;
/*
*init dbgp flags before all
*other functions, because we will
*use it in other funtions like
*RT_TRACE/RT_PRINT/RTL_PRINT_DATA
*you can not use these macro
*before this
*/
rtl_dbgp_flag_init(hw);
/* MEM map */
err = pci_request_regions(pdev, KBUILD_MODNAME);
if (err) {
RT_ASSERT(false, "Can't obtain PCI resources\n");
goto fail1;
}
pmem_start = pci_resource_start(pdev, rtlpriv->cfg->bar_id);
pmem_len = pci_resource_len(pdev, rtlpriv->cfg->bar_id);
pmem_flags = pci_resource_flags(pdev, rtlpriv->cfg->bar_id);
/*shared mem start */
rtlpriv->io.pci_mem_start =
(unsigned long)pci_iomap(pdev,
rtlpriv->cfg->bar_id, pmem_len);
if (rtlpriv->io.pci_mem_start == 0) {
RT_ASSERT(false, "Can't map PCI mem\n");
err = -ENOMEM;
goto fail2;
}
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG,
"mem mapped space: start: 0x%08lx len:%08lx flags:%08lx, after map:0x%08lx\n",
pmem_start, pmem_len, pmem_flags,
rtlpriv->io.pci_mem_start);
/* Disable Clk Request */
pci_write_config_byte(pdev, 0x81, 0);
/* leave D3 mode */
pci_write_config_byte(pdev, 0x44, 0);
pci_write_config_byte(pdev, 0x04, 0x06);
pci_write_config_byte(pdev, 0x04, 0x07);
/* find adapter */
if (!_rtl_pci_find_adapter(pdev, hw)) {
err = -ENODEV;
goto fail3;
}
/* Init IO handler */
_rtl_pci_io_handler_init(&pdev->dev, hw);
/*like read eeprom and so on */
rtlpriv->cfg->ops->read_eeprom_info(hw);
/*aspm */
rtl_pci_init_aspm(hw);
/* Init mac80211 sw */
err = rtl_init_core(hw);
if (err) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"Can't allocate sw for mac80211\n");
goto fail3;
}
/* Init PCI sw */
err = rtl_pci_init(hw, pdev);
if (err) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG, "Failed to init PCI\n");
goto fail3;
}
if (rtlpriv->cfg->ops->init_sw_vars(hw)) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG, "Can't init_sw_vars\n");
err = -ENODEV;
goto fail3;
}
rtlpriv->cfg->ops->init_sw_leds(hw);
err = sysfs_create_group(&pdev->dev.kobj, &rtl_attribute_group);
if (err) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"failed to create sysfs device attributes\n");
goto fail3;
}
rtlpci = rtl_pcidev(pcipriv);
err = request_irq(rtlpci->pdev->irq, &_rtl_pci_interrupt,
IRQF_SHARED, KBUILD_MODNAME, hw);
if (err) {
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG,
"%s: failed to register IRQ handler\n",
wiphy_name(hw->wiphy));
goto fail3;
}
rtlpci->irq_alloc = 1;
return 0;
fail3:
rtl_deinit_core(hw);
if (rtlpriv->io.pci_mem_start != 0)
pci_iounmap(pdev, (void __iomem *)rtlpriv->io.pci_mem_start);
fail2:
pci_release_regions(pdev);
complete(&rtlpriv->firmware_loading_complete);
fail1:
if (hw)
ieee80211_free_hw(hw);
pci_set_drvdata(pdev, NULL);
pci_disable_device(pdev);
return err;
}
EXPORT_SYMBOL(rtl_pci_probe);
void rtl_pci_disconnect(struct pci_dev *pdev)
{
struct ieee80211_hw *hw = pci_get_drvdata(pdev);
struct rtl_pci_priv *pcipriv = rtl_pcipriv(hw);
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_pci *rtlpci = rtl_pcidev(pcipriv);
struct rtl_mac *rtlmac = rtl_mac(rtlpriv);
/* just in case driver is removed before firmware callback */
wait_for_completion(&rtlpriv->firmware_loading_complete);
clear_bit(RTL_STATUS_INTERFACE_START, &rtlpriv->status);
sysfs_remove_group(&pdev->dev.kobj, &rtl_attribute_group);
/*ieee80211_unregister_hw will call ops_stop */
if (rtlmac->mac80211_registered == 1) {
ieee80211_unregister_hw(hw);
rtlmac->mac80211_registered = 0;
} else {
rtl_deinit_deferred_work(hw);
rtlpriv->intf_ops->adapter_stop(hw);
}
rtlpriv->cfg->ops->disable_interrupt(hw);
/*deinit rfkill */
rtl_deinit_rfkill(hw);
rtl_pci_deinit(hw);
rtl_deinit_core(hw);
rtlpriv->cfg->ops->deinit_sw_vars(hw);
if (rtlpci->irq_alloc) {
synchronize_irq(rtlpci->pdev->irq);
free_irq(rtlpci->pdev->irq, hw);
rtlpci->irq_alloc = 0;
}
list_del(&rtlpriv->list);
if (rtlpriv->io.pci_mem_start != 0) {
pci_iounmap(pdev, (void __iomem *)rtlpriv->io.pci_mem_start);
pci_release_regions(pdev);
}
pci_disable_device(pdev);
rtl_pci_disable_aspm(hw);
pci_set_drvdata(pdev, NULL);
ieee80211_free_hw(hw);
}
EXPORT_SYMBOL(rtl_pci_disconnect);
#ifdef CONFIG_PM_SLEEP
/***************************************
kernel pci power state define:
PCI_D0 ((pci_power_t __force) 0)
PCI_D1 ((pci_power_t __force) 1)
PCI_D2 ((pci_power_t __force) 2)
PCI_D3hot ((pci_power_t __force) 3)
PCI_D3cold ((pci_power_t __force) 4)
PCI_UNKNOWN ((pci_power_t __force) 5)
This function is called when system
goes into suspend state mac80211 will
call rtl_mac_stop() from the mac80211
suspend function first, So there is
no need to call hw_disable here.
****************************************/
int rtl_pci_suspend(struct device *dev)
{
struct pci_dev *pdev = to_pci_dev(dev);
struct ieee80211_hw *hw = pci_get_drvdata(pdev);
struct rtl_priv *rtlpriv = rtl_priv(hw);
rtlpriv->cfg->ops->hw_suspend(hw);
rtl_deinit_rfkill(hw);
return 0;
}
EXPORT_SYMBOL(rtl_pci_suspend);
int rtl_pci_resume(struct device *dev)
{
struct pci_dev *pdev = to_pci_dev(dev);
struct ieee80211_hw *hw = pci_get_drvdata(pdev);
struct rtl_priv *rtlpriv = rtl_priv(hw);
rtlpriv->cfg->ops->hw_resume(hw);
rtl_init_rfkill(hw);
return 0;
}
EXPORT_SYMBOL(rtl_pci_resume);
#endif /* CONFIG_PM_SLEEP */
struct rtl_intf_ops rtl_pci_ops = {
.read_efuse_byte = read_efuse_byte,
.adapter_start = rtl_pci_start,
.adapter_stop = rtl_pci_stop,
.check_buddy_priv = rtl_pci_check_buddy_priv,
.adapter_tx = rtl_pci_tx,
.flush = rtl_pci_flush,
.reset_trx_ring = rtl_pci_reset_trx_ring,
.waitq_insert = rtl_pci_tx_chk_waitq_insert,
.disable_aspm = rtl_pci_disable_aspm,
.enable_aspm = rtl_pci_enable_aspm,
};
| gpl-2.0 |
Riccorbypro/android_kernel_sony_wukong | arch/powerpc/kvm/book3s_mmu_hpte.c | 2147 | 8654 | /*
* Copyright (C) 2010 SUSE Linux Products GmbH. All rights reserved.
*
* Authors:
* Alexander Graf <agraf@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 License
* along with this program; if not, write to the Free Software
* Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <linux/kvm_host.h>
#include <linux/hash.h>
#include <linux/slab.h>
#include <asm/kvm_ppc.h>
#include <asm/kvm_book3s.h>
#include <asm/machdep.h>
#include <asm/mmu_context.h>
#include <asm/hw_irq.h>
#include "trace.h"
#define PTE_SIZE 12
static struct kmem_cache *hpte_cache;
static inline u64 kvmppc_mmu_hash_pte(u64 eaddr)
{
return hash_64(eaddr >> PTE_SIZE, HPTEG_HASH_BITS_PTE);
}
static inline u64 kvmppc_mmu_hash_pte_long(u64 eaddr)
{
return hash_64((eaddr & 0x0ffff000) >> PTE_SIZE,
HPTEG_HASH_BITS_PTE_LONG);
}
static inline u64 kvmppc_mmu_hash_vpte(u64 vpage)
{
return hash_64(vpage & 0xfffffffffULL, HPTEG_HASH_BITS_VPTE);
}
static inline u64 kvmppc_mmu_hash_vpte_long(u64 vpage)
{
return hash_64((vpage & 0xffffff000ULL) >> 12,
HPTEG_HASH_BITS_VPTE_LONG);
}
void kvmppc_mmu_hpte_cache_map(struct kvm_vcpu *vcpu, struct hpte_cache *pte)
{
u64 index;
struct kvmppc_vcpu_book3s *vcpu3s = to_book3s(vcpu);
trace_kvm_book3s_mmu_map(pte);
spin_lock(&vcpu3s->mmu_lock);
/* Add to ePTE list */
index = kvmppc_mmu_hash_pte(pte->pte.eaddr);
hlist_add_head_rcu(&pte->list_pte, &vcpu3s->hpte_hash_pte[index]);
/* Add to ePTE_long list */
index = kvmppc_mmu_hash_pte_long(pte->pte.eaddr);
hlist_add_head_rcu(&pte->list_pte_long,
&vcpu3s->hpte_hash_pte_long[index]);
/* Add to vPTE list */
index = kvmppc_mmu_hash_vpte(pte->pte.vpage);
hlist_add_head_rcu(&pte->list_vpte, &vcpu3s->hpte_hash_vpte[index]);
/* Add to vPTE_long list */
index = kvmppc_mmu_hash_vpte_long(pte->pte.vpage);
hlist_add_head_rcu(&pte->list_vpte_long,
&vcpu3s->hpte_hash_vpte_long[index]);
spin_unlock(&vcpu3s->mmu_lock);
}
static void free_pte_rcu(struct rcu_head *head)
{
struct hpte_cache *pte = container_of(head, struct hpte_cache, rcu_head);
kmem_cache_free(hpte_cache, pte);
}
static void invalidate_pte(struct kvm_vcpu *vcpu, struct hpte_cache *pte)
{
struct kvmppc_vcpu_book3s *vcpu3s = to_book3s(vcpu);
trace_kvm_book3s_mmu_invalidate(pte);
/* Different for 32 and 64 bit */
kvmppc_mmu_invalidate_pte(vcpu, pte);
spin_lock(&vcpu3s->mmu_lock);
/* pte already invalidated in between? */
if (hlist_unhashed(&pte->list_pte)) {
spin_unlock(&vcpu3s->mmu_lock);
return;
}
hlist_del_init_rcu(&pte->list_pte);
hlist_del_init_rcu(&pte->list_pte_long);
hlist_del_init_rcu(&pte->list_vpte);
hlist_del_init_rcu(&pte->list_vpte_long);
spin_unlock(&vcpu3s->mmu_lock);
vcpu3s->hpte_cache_count--;
call_rcu(&pte->rcu_head, free_pte_rcu);
}
static void kvmppc_mmu_pte_flush_all(struct kvm_vcpu *vcpu)
{
struct kvmppc_vcpu_book3s *vcpu3s = to_book3s(vcpu);
struct hpte_cache *pte;
int i;
rcu_read_lock();
for (i = 0; i < HPTEG_HASH_NUM_VPTE_LONG; i++) {
struct hlist_head *list = &vcpu3s->hpte_hash_vpte_long[i];
hlist_for_each_entry_rcu(pte, list, list_vpte_long)
invalidate_pte(vcpu, pte);
}
rcu_read_unlock();
}
static void kvmppc_mmu_pte_flush_page(struct kvm_vcpu *vcpu, ulong guest_ea)
{
struct kvmppc_vcpu_book3s *vcpu3s = to_book3s(vcpu);
struct hlist_head *list;
struct hpte_cache *pte;
/* Find the list of entries in the map */
list = &vcpu3s->hpte_hash_pte[kvmppc_mmu_hash_pte(guest_ea)];
rcu_read_lock();
/* Check the list for matching entries and invalidate */
hlist_for_each_entry_rcu(pte, list, list_pte)
if ((pte->pte.eaddr & ~0xfffUL) == guest_ea)
invalidate_pte(vcpu, pte);
rcu_read_unlock();
}
static void kvmppc_mmu_pte_flush_long(struct kvm_vcpu *vcpu, ulong guest_ea)
{
struct kvmppc_vcpu_book3s *vcpu3s = to_book3s(vcpu);
struct hlist_head *list;
struct hpte_cache *pte;
/* Find the list of entries in the map */
list = &vcpu3s->hpte_hash_pte_long[
kvmppc_mmu_hash_pte_long(guest_ea)];
rcu_read_lock();
/* Check the list for matching entries and invalidate */
hlist_for_each_entry_rcu(pte, list, list_pte_long)
if ((pte->pte.eaddr & 0x0ffff000UL) == guest_ea)
invalidate_pte(vcpu, pte);
rcu_read_unlock();
}
void kvmppc_mmu_pte_flush(struct kvm_vcpu *vcpu, ulong guest_ea, ulong ea_mask)
{
trace_kvm_book3s_mmu_flush("", vcpu, guest_ea, ea_mask);
guest_ea &= ea_mask;
switch (ea_mask) {
case ~0xfffUL:
kvmppc_mmu_pte_flush_page(vcpu, guest_ea);
break;
case 0x0ffff000:
kvmppc_mmu_pte_flush_long(vcpu, guest_ea);
break;
case 0:
/* Doing a complete flush -> start from scratch */
kvmppc_mmu_pte_flush_all(vcpu);
break;
default:
WARN_ON(1);
break;
}
}
/* Flush with mask 0xfffffffff */
static void kvmppc_mmu_pte_vflush_short(struct kvm_vcpu *vcpu, u64 guest_vp)
{
struct kvmppc_vcpu_book3s *vcpu3s = to_book3s(vcpu);
struct hlist_head *list;
struct hpte_cache *pte;
u64 vp_mask = 0xfffffffffULL;
list = &vcpu3s->hpte_hash_vpte[kvmppc_mmu_hash_vpte(guest_vp)];
rcu_read_lock();
/* Check the list for matching entries and invalidate */
hlist_for_each_entry_rcu(pte, list, list_vpte)
if ((pte->pte.vpage & vp_mask) == guest_vp)
invalidate_pte(vcpu, pte);
rcu_read_unlock();
}
/* Flush with mask 0xffffff000 */
static void kvmppc_mmu_pte_vflush_long(struct kvm_vcpu *vcpu, u64 guest_vp)
{
struct kvmppc_vcpu_book3s *vcpu3s = to_book3s(vcpu);
struct hlist_head *list;
struct hpte_cache *pte;
u64 vp_mask = 0xffffff000ULL;
list = &vcpu3s->hpte_hash_vpte_long[
kvmppc_mmu_hash_vpte_long(guest_vp)];
rcu_read_lock();
/* Check the list for matching entries and invalidate */
hlist_for_each_entry_rcu(pte, list, list_vpte_long)
if ((pte->pte.vpage & vp_mask) == guest_vp)
invalidate_pte(vcpu, pte);
rcu_read_unlock();
}
void kvmppc_mmu_pte_vflush(struct kvm_vcpu *vcpu, u64 guest_vp, u64 vp_mask)
{
trace_kvm_book3s_mmu_flush("v", vcpu, guest_vp, vp_mask);
guest_vp &= vp_mask;
switch(vp_mask) {
case 0xfffffffffULL:
kvmppc_mmu_pte_vflush_short(vcpu, guest_vp);
break;
case 0xffffff000ULL:
kvmppc_mmu_pte_vflush_long(vcpu, guest_vp);
break;
default:
WARN_ON(1);
return;
}
}
void kvmppc_mmu_pte_pflush(struct kvm_vcpu *vcpu, ulong pa_start, ulong pa_end)
{
struct kvmppc_vcpu_book3s *vcpu3s = to_book3s(vcpu);
struct hpte_cache *pte;
int i;
trace_kvm_book3s_mmu_flush("p", vcpu, pa_start, pa_end);
rcu_read_lock();
for (i = 0; i < HPTEG_HASH_NUM_VPTE_LONG; i++) {
struct hlist_head *list = &vcpu3s->hpte_hash_vpte_long[i];
hlist_for_each_entry_rcu(pte, list, list_vpte_long)
if ((pte->pte.raddr >= pa_start) &&
(pte->pte.raddr < pa_end))
invalidate_pte(vcpu, pte);
}
rcu_read_unlock();
}
struct hpte_cache *kvmppc_mmu_hpte_cache_next(struct kvm_vcpu *vcpu)
{
struct kvmppc_vcpu_book3s *vcpu3s = to_book3s(vcpu);
struct hpte_cache *pte;
pte = kmem_cache_zalloc(hpte_cache, GFP_KERNEL);
vcpu3s->hpte_cache_count++;
if (vcpu3s->hpte_cache_count == HPTEG_CACHE_NUM)
kvmppc_mmu_pte_flush_all(vcpu);
return pte;
}
void kvmppc_mmu_hpte_destroy(struct kvm_vcpu *vcpu)
{
kvmppc_mmu_pte_flush(vcpu, 0, 0);
}
static void kvmppc_mmu_hpte_init_hash(struct hlist_head *hash_list, int len)
{
int i;
for (i = 0; i < len; i++)
INIT_HLIST_HEAD(&hash_list[i]);
}
int kvmppc_mmu_hpte_init(struct kvm_vcpu *vcpu)
{
struct kvmppc_vcpu_book3s *vcpu3s = to_book3s(vcpu);
/* init hpte lookup hashes */
kvmppc_mmu_hpte_init_hash(vcpu3s->hpte_hash_pte,
ARRAY_SIZE(vcpu3s->hpte_hash_pte));
kvmppc_mmu_hpte_init_hash(vcpu3s->hpte_hash_pte_long,
ARRAY_SIZE(vcpu3s->hpte_hash_pte_long));
kvmppc_mmu_hpte_init_hash(vcpu3s->hpte_hash_vpte,
ARRAY_SIZE(vcpu3s->hpte_hash_vpte));
kvmppc_mmu_hpte_init_hash(vcpu3s->hpte_hash_vpte_long,
ARRAY_SIZE(vcpu3s->hpte_hash_vpte_long));
spin_lock_init(&vcpu3s->mmu_lock);
return 0;
}
int kvmppc_mmu_hpte_sysinit(void)
{
/* init hpte slab cache */
hpte_cache = kmem_cache_create("kvm-spt", sizeof(struct hpte_cache),
sizeof(struct hpte_cache), 0, NULL);
return 0;
}
void kvmppc_mmu_hpte_sysexit(void)
{
kmem_cache_destroy(hpte_cache);
}
| gpl-2.0 |
gingo21/kernel_wiko_cink_slim | sound/soc/samsung/s3c24xx_simtec.c | 2915 | 9306 | /* sound/soc/samsung/s3c24xx_simtec.c
*
* Copyright 2009 Simtec Electronics
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/gpio.h>
#include <linux/clk.h>
#include <sound/soc.h>
#include <plat/audio-simtec.h>
#include "s3c24xx-i2s.h"
#include "s3c24xx_simtec.h"
static struct s3c24xx_audio_simtec_pdata *pdata;
static struct clk *xtal_clk;
static int spk_gain;
static int spk_unmute;
/**
* speaker_gain_get - read the speaker gain setting.
* @kcontrol: The control for the speaker gain.
* @ucontrol: The value that needs to be updated.
*
* Read the value for the AMP gain control.
*/
static int speaker_gain_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
ucontrol->value.integer.value[0] = spk_gain;
return 0;
}
/**
* speaker_gain_set - set the value of the speaker amp gain
* @value: The value to write.
*/
static void speaker_gain_set(int value)
{
gpio_set_value_cansleep(pdata->amp_gain[0], value & 1);
gpio_set_value_cansleep(pdata->amp_gain[1], value >> 1);
}
/**
* speaker_gain_put - set the speaker gain setting.
* @kcontrol: The control for the speaker gain.
* @ucontrol: The value that needs to be set.
*
* Set the value of the speaker gain from the specified
* @ucontrol setting.
*
* Note, if the speaker amp is muted, then we do not set a gain value
* as at-least one of the ICs that is fitted will try and power up even
* if the main control is set to off.
*/
static int speaker_gain_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int value = ucontrol->value.integer.value[0];
spk_gain = value;
if (!spk_unmute)
speaker_gain_set(value);
return 0;
}
static const struct snd_kcontrol_new amp_gain_controls[] = {
SOC_SINGLE_EXT("Speaker Gain", 0, 0, 3, 0,
speaker_gain_get, speaker_gain_put),
};
/**
* spk_unmute_state - set the unmute state of the speaker
* @to: zero to unmute, non-zero to ununmute.
*/
static void spk_unmute_state(int to)
{
pr_debug("%s: to=%d\n", __func__, to);
spk_unmute = to;
gpio_set_value(pdata->amp_gpio, to);
/* if we're umuting, also re-set the gain */
if (to && pdata->amp_gain[0] > 0)
speaker_gain_set(spk_gain);
}
/**
* speaker_unmute_get - read the speaker unmute setting.
* @kcontrol: The control for the speaker gain.
* @ucontrol: The value that needs to be updated.
*
* Read the value for the AMP gain control.
*/
static int speaker_unmute_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
ucontrol->value.integer.value[0] = spk_unmute;
return 0;
}
/**
* speaker_unmute_put - set the speaker unmute setting.
* @kcontrol: The control for the speaker gain.
* @ucontrol: The value that needs to be set.
*
* Set the value of the speaker gain from the specified
* @ucontrol setting.
*/
static int speaker_unmute_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
spk_unmute_state(ucontrol->value.integer.value[0]);
return 0;
}
/* This is added as a manual control as the speaker amps create clicks
* when their power state is changed, which are far more noticeable than
* anything produced by the CODEC itself.
*/
static const struct snd_kcontrol_new amp_unmute_controls[] = {
SOC_SINGLE_EXT("Speaker Switch", 0, 0, 1, 0,
speaker_unmute_get, speaker_unmute_put),
};
void simtec_audio_init(struct snd_soc_pcm_runtime *rtd)
{
struct snd_soc_codec *codec = rtd->codec;
if (pdata->amp_gpio > 0) {
pr_debug("%s: adding amp routes\n", __func__);
snd_soc_add_controls(codec, amp_unmute_controls,
ARRAY_SIZE(amp_unmute_controls));
}
if (pdata->amp_gain[0] > 0) {
pr_debug("%s: adding amp controls\n", __func__);
snd_soc_add_controls(codec, amp_gain_controls,
ARRAY_SIZE(amp_gain_controls));
}
}
EXPORT_SYMBOL_GPL(simtec_audio_init);
#define CODEC_CLOCK 12000000
/**
* simtec_hw_params - update hardware parameters
* @substream: The audio substream instance.
* @params: The parameters requested.
*
* Update the codec data routing and configuration settings
* from the supplied data.
*/
static int simtec_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *codec_dai = rtd->codec_dai;
struct snd_soc_dai *cpu_dai = rtd->cpu_dai;
int ret;
/* Set the CODEC as the bus clock master, I2S */
ret = snd_soc_dai_set_fmt(cpu_dai, SND_SOC_DAIFMT_I2S |
SND_SOC_DAIFMT_NB_NF |
SND_SOC_DAIFMT_CBM_CFM);
if (ret) {
pr_err("%s: failed set cpu dai format\n", __func__);
return ret;
}
/* Set the CODEC as the bus clock master */
ret = snd_soc_dai_set_fmt(codec_dai, SND_SOC_DAIFMT_I2S |
SND_SOC_DAIFMT_NB_NF |
SND_SOC_DAIFMT_CBM_CFM);
if (ret) {
pr_err("%s: failed set codec dai format\n", __func__);
return ret;
}
ret = snd_soc_dai_set_sysclk(codec_dai, 0,
CODEC_CLOCK, SND_SOC_CLOCK_IN);
if (ret) {
pr_err( "%s: failed setting codec sysclk\n", __func__);
return ret;
}
if (pdata->use_mpllin) {
ret = snd_soc_dai_set_sysclk(cpu_dai, S3C24XX_CLKSRC_MPLL,
0, SND_SOC_CLOCK_OUT);
if (ret) {
pr_err("%s: failed to set MPLLin as clksrc\n",
__func__);
return ret;
}
}
if (pdata->output_cdclk) {
int cdclk_scale;
cdclk_scale = clk_get_rate(xtal_clk) / CODEC_CLOCK;
cdclk_scale--;
ret = snd_soc_dai_set_clkdiv(cpu_dai, S3C24XX_DIV_PRESCALER,
cdclk_scale);
}
return 0;
}
static int simtec_call_startup(struct s3c24xx_audio_simtec_pdata *pd)
{
/* call any board supplied startup code, this currently only
* covers the bast/vr1000 which have a CPLD in the way of the
* LRCLK */
if (pd->startup)
pd->startup();
return 0;
}
static struct snd_soc_ops simtec_snd_ops = {
.hw_params = simtec_hw_params,
};
/**
* attach_gpio_amp - get and configure the necessary gpios
* @dev: The device we're probing.
* @pd: The platform data supplied by the board.
*
* If there is a GPIO based amplifier attached to the board, claim
* the necessary GPIO lines for it, and set default values.
*/
static int attach_gpio_amp(struct device *dev,
struct s3c24xx_audio_simtec_pdata *pd)
{
int ret;
/* attach gpio amp gain (if any) */
if (pdata->amp_gain[0] > 0) {
ret = gpio_request(pd->amp_gain[0], "gpio-amp-gain0");
if (ret) {
dev_err(dev, "cannot get amp gpio gain0\n");
return ret;
}
ret = gpio_request(pd->amp_gain[1], "gpio-amp-gain1");
if (ret) {
dev_err(dev, "cannot get amp gpio gain1\n");
gpio_free(pdata->amp_gain[0]);
return ret;
}
gpio_direction_output(pd->amp_gain[0], 0);
gpio_direction_output(pd->amp_gain[1], 0);
}
/* note, currently we assume GPA0 isn't valid amp */
if (pdata->amp_gpio > 0) {
ret = gpio_request(pd->amp_gpio, "gpio-amp");
if (ret) {
dev_err(dev, "cannot get amp gpio %d (%d)\n",
pd->amp_gpio, ret);
goto err_amp;
}
/* set the amp off at startup */
spk_unmute_state(0);
}
return 0;
err_amp:
if (pd->amp_gain[0] > 0) {
gpio_free(pd->amp_gain[0]);
gpio_free(pd->amp_gain[1]);
}
return ret;
}
static void detach_gpio_amp(struct s3c24xx_audio_simtec_pdata *pd)
{
if (pd->amp_gain[0] > 0) {
gpio_free(pd->amp_gain[0]);
gpio_free(pd->amp_gain[1]);
}
if (pd->amp_gpio > 0)
gpio_free(pd->amp_gpio);
}
#ifdef CONFIG_PM
int simtec_audio_resume(struct device *dev)
{
simtec_call_startup(pdata);
return 0;
}
const struct dev_pm_ops simtec_audio_pmops = {
.resume = simtec_audio_resume,
};
EXPORT_SYMBOL_GPL(simtec_audio_pmops);
#endif
int __devinit simtec_audio_core_probe(struct platform_device *pdev,
struct snd_soc_card *card)
{
struct platform_device *snd_dev;
int ret;
card->dai_link->ops = &simtec_snd_ops;
pdata = pdev->dev.platform_data;
if (!pdata) {
dev_err(&pdev->dev, "no platform data supplied\n");
return -EINVAL;
}
simtec_call_startup(pdata);
xtal_clk = clk_get(&pdev->dev, "xtal");
if (IS_ERR(xtal_clk)) {
dev_err(&pdev->dev, "could not get clkout0\n");
return -EINVAL;
}
dev_info(&pdev->dev, "xtal rate is %ld\n", clk_get_rate(xtal_clk));
ret = attach_gpio_amp(&pdev->dev, pdata);
if (ret)
goto err_clk;
snd_dev = platform_device_alloc("soc-audio", -1);
if (!snd_dev) {
dev_err(&pdev->dev, "failed to alloc soc-audio devicec\n");
ret = -ENOMEM;
goto err_gpio;
}
platform_set_drvdata(snd_dev, card);
ret = platform_device_add(snd_dev);
if (ret) {
dev_err(&pdev->dev, "failed to add soc-audio dev\n");
goto err_pdev;
}
platform_set_drvdata(pdev, snd_dev);
return 0;
err_pdev:
platform_device_put(snd_dev);
err_gpio:
detach_gpio_amp(pdata);
err_clk:
clk_put(xtal_clk);
return ret;
}
EXPORT_SYMBOL_GPL(simtec_audio_core_probe);
int __devexit simtec_audio_remove(struct platform_device *pdev)
{
struct platform_device *snd_dev = platform_get_drvdata(pdev);
platform_device_unregister(snd_dev);
detach_gpio_amp(pdata);
clk_put(xtal_clk);
return 0;
}
EXPORT_SYMBOL_GPL(simtec_audio_remove);
MODULE_AUTHOR("Ben Dooks <ben@simtec.co.uk>");
MODULE_DESCRIPTION("ALSA SoC Simtec Audio common support");
MODULE_LICENSE("GPL");
| gpl-2.0 |
HTCKernels/One-SV-cricket-k2plccl | arch/arm/mach-omap2/hsmmc.c | 4707 | 15713 | /*
* linux/arch/arm/mach-omap2/hsmmc.c
*
* Copyright (C) 2007-2008 Texas Instruments
* Copyright (C) 2008 Nokia Corporation
* Author: Texas Instruments
*
* 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/slab.h>
#include <linux/string.h>
#include <linux/delay.h>
#include <linux/gpio.h>
#include <mach/hardware.h>
#include <plat/mmc.h>
#include <plat/omap-pm.h>
#include <plat/mux.h>
#include <plat/omap_device.h>
#include "mux.h"
#include "hsmmc.h"
#include "control.h"
#if defined(CONFIG_MMC_OMAP_HS) || defined(CONFIG_MMC_OMAP_HS_MODULE)
static u16 control_pbias_offset;
static u16 control_devconf1_offset;
static u16 control_mmc1;
#define HSMMC_NAME_LEN 9
#if defined(CONFIG_ARCH_OMAP3) && defined(CONFIG_PM)
static int hsmmc_get_context_loss(struct device *dev)
{
return omap_pm_get_dev_context_loss_count(dev);
}
#else
#define hsmmc_get_context_loss NULL
#endif
static void omap_hsmmc1_before_set_reg(struct device *dev, int slot,
int power_on, int vdd)
{
u32 reg, prog_io;
struct omap_mmc_platform_data *mmc = dev->platform_data;
if (mmc->slots[0].remux)
mmc->slots[0].remux(dev, slot, power_on);
/*
* Assume we power both OMAP VMMC1 (for CMD, CLK, DAT0..3) and the
* card with Vcc regulator (from twl4030 or whatever). OMAP has both
* 1.8V and 3.0V modes, controlled by the PBIAS register.
*
* In 8-bit modes, OMAP VMMC1A (for DAT4..7) needs a supply, which
* is most naturally TWL VSIM; those pins also use PBIAS.
*
* FIXME handle VMMC1A as needed ...
*/
if (power_on) {
if (cpu_is_omap2430()) {
reg = omap_ctrl_readl(OMAP243X_CONTROL_DEVCONF1);
if ((1 << vdd) >= MMC_VDD_30_31)
reg |= OMAP243X_MMC1_ACTIVE_OVERWRITE;
else
reg &= ~OMAP243X_MMC1_ACTIVE_OVERWRITE;
omap_ctrl_writel(reg, OMAP243X_CONTROL_DEVCONF1);
}
if (mmc->slots[0].internal_clock) {
reg = omap_ctrl_readl(OMAP2_CONTROL_DEVCONF0);
reg |= OMAP2_MMCSDIO1ADPCLKISEL;
omap_ctrl_writel(reg, OMAP2_CONTROL_DEVCONF0);
}
reg = omap_ctrl_readl(control_pbias_offset);
if (cpu_is_omap3630()) {
/* Set MMC I/O to 52Mhz */
prog_io = omap_ctrl_readl(OMAP343X_CONTROL_PROG_IO1);
prog_io |= OMAP3630_PRG_SDMMC1_SPEEDCTRL;
omap_ctrl_writel(prog_io, OMAP343X_CONTROL_PROG_IO1);
} else {
reg |= OMAP2_PBIASSPEEDCTRL0;
}
reg &= ~OMAP2_PBIASLITEPWRDNZ0;
omap_ctrl_writel(reg, control_pbias_offset);
} else {
reg = omap_ctrl_readl(control_pbias_offset);
reg &= ~OMAP2_PBIASLITEPWRDNZ0;
omap_ctrl_writel(reg, control_pbias_offset);
}
}
static void omap_hsmmc1_after_set_reg(struct device *dev, int slot,
int power_on, int vdd)
{
u32 reg;
/* 100ms delay required for PBIAS configuration */
msleep(100);
if (power_on) {
reg = omap_ctrl_readl(control_pbias_offset);
reg |= (OMAP2_PBIASLITEPWRDNZ0 | OMAP2_PBIASSPEEDCTRL0);
if ((1 << vdd) <= MMC_VDD_165_195)
reg &= ~OMAP2_PBIASLITEVMODE0;
else
reg |= OMAP2_PBIASLITEVMODE0;
omap_ctrl_writel(reg, control_pbias_offset);
} else {
reg = omap_ctrl_readl(control_pbias_offset);
reg |= (OMAP2_PBIASSPEEDCTRL0 | OMAP2_PBIASLITEPWRDNZ0 |
OMAP2_PBIASLITEVMODE0);
omap_ctrl_writel(reg, control_pbias_offset);
}
}
static void omap4_hsmmc1_before_set_reg(struct device *dev, int slot,
int power_on, int vdd)
{
u32 reg;
/*
* Assume we power both OMAP VMMC1 (for CMD, CLK, DAT0..3) and the
* card with Vcc regulator (from twl4030 or whatever). OMAP has both
* 1.8V and 3.0V modes, controlled by the PBIAS register.
*/
reg = omap4_ctrl_pad_readl(control_pbias_offset);
reg &= ~(OMAP4_MMC1_PBIASLITE_PWRDNZ_MASK |
OMAP4_MMC1_PWRDNZ_MASK |
OMAP4_MMC1_PBIASLITE_VMODE_MASK);
omap4_ctrl_pad_writel(reg, control_pbias_offset);
}
static void omap4_hsmmc1_after_set_reg(struct device *dev, int slot,
int power_on, int vdd)
{
u32 reg;
unsigned long timeout;
if (power_on) {
reg = omap4_ctrl_pad_readl(control_pbias_offset);
reg |= OMAP4_MMC1_PBIASLITE_PWRDNZ_MASK;
if ((1 << vdd) <= MMC_VDD_165_195)
reg &= ~OMAP4_MMC1_PBIASLITE_VMODE_MASK;
else
reg |= OMAP4_MMC1_PBIASLITE_VMODE_MASK;
reg |= (OMAP4_MMC1_PBIASLITE_PWRDNZ_MASK |
OMAP4_MMC1_PWRDNZ_MASK);
omap4_ctrl_pad_writel(reg, control_pbias_offset);
timeout = jiffies + msecs_to_jiffies(5);
do {
reg = omap4_ctrl_pad_readl(control_pbias_offset);
if (!(reg & OMAP4_MMC1_PBIASLITE_VMODE_ERROR_MASK))
break;
usleep_range(100, 200);
} while (!time_after(jiffies, timeout));
if (reg & OMAP4_MMC1_PBIASLITE_VMODE_ERROR_MASK) {
pr_err("Pbias Voltage is not same as LDO\n");
/* Caution : On VMODE_ERROR Power Down MMC IO */
reg &= ~(OMAP4_MMC1_PWRDNZ_MASK);
omap4_ctrl_pad_writel(reg, control_pbias_offset);
}
}
}
static void hsmmc2_select_input_clk_src(struct omap_mmc_platform_data *mmc)
{
u32 reg;
reg = omap_ctrl_readl(control_devconf1_offset);
if (mmc->slots[0].internal_clock)
reg |= OMAP2_MMCSDIO2ADPCLKISEL;
else
reg &= ~OMAP2_MMCSDIO2ADPCLKISEL;
omap_ctrl_writel(reg, control_devconf1_offset);
}
static void hsmmc2_before_set_reg(struct device *dev, int slot,
int power_on, int vdd)
{
struct omap_mmc_platform_data *mmc = dev->platform_data;
if (mmc->slots[0].remux)
mmc->slots[0].remux(dev, slot, power_on);
if (power_on)
hsmmc2_select_input_clk_src(mmc);
}
static int am35x_hsmmc2_set_power(struct device *dev, int slot,
int power_on, int vdd)
{
struct omap_mmc_platform_data *mmc = dev->platform_data;
if (power_on)
hsmmc2_select_input_clk_src(mmc);
return 0;
}
static int nop_mmc_set_power(struct device *dev, int slot, int power_on,
int vdd)
{
return 0;
}
static inline void omap_hsmmc_mux(struct omap_mmc_platform_data *mmc_controller,
int controller_nr)
{
if (gpio_is_valid(mmc_controller->slots[0].switch_pin) &&
(mmc_controller->slots[0].switch_pin < OMAP_MAX_GPIO_LINES))
omap_mux_init_gpio(mmc_controller->slots[0].switch_pin,
OMAP_PIN_INPUT_PULLUP);
if (gpio_is_valid(mmc_controller->slots[0].gpio_wp) &&
(mmc_controller->slots[0].gpio_wp < OMAP_MAX_GPIO_LINES))
omap_mux_init_gpio(mmc_controller->slots[0].gpio_wp,
OMAP_PIN_INPUT_PULLUP);
if (cpu_is_omap34xx()) {
if (controller_nr == 0) {
omap_mux_init_signal("sdmmc1_clk",
OMAP_PIN_INPUT_PULLUP);
omap_mux_init_signal("sdmmc1_cmd",
OMAP_PIN_INPUT_PULLUP);
omap_mux_init_signal("sdmmc1_dat0",
OMAP_PIN_INPUT_PULLUP);
if (mmc_controller->slots[0].caps &
(MMC_CAP_4_BIT_DATA | MMC_CAP_8_BIT_DATA)) {
omap_mux_init_signal("sdmmc1_dat1",
OMAP_PIN_INPUT_PULLUP);
omap_mux_init_signal("sdmmc1_dat2",
OMAP_PIN_INPUT_PULLUP);
omap_mux_init_signal("sdmmc1_dat3",
OMAP_PIN_INPUT_PULLUP);
}
if (mmc_controller->slots[0].caps &
MMC_CAP_8_BIT_DATA) {
omap_mux_init_signal("sdmmc1_dat4",
OMAP_PIN_INPUT_PULLUP);
omap_mux_init_signal("sdmmc1_dat5",
OMAP_PIN_INPUT_PULLUP);
omap_mux_init_signal("sdmmc1_dat6",
OMAP_PIN_INPUT_PULLUP);
omap_mux_init_signal("sdmmc1_dat7",
OMAP_PIN_INPUT_PULLUP);
}
}
if (controller_nr == 1) {
/* MMC2 */
omap_mux_init_signal("sdmmc2_clk",
OMAP_PIN_INPUT_PULLUP);
omap_mux_init_signal("sdmmc2_cmd",
OMAP_PIN_INPUT_PULLUP);
omap_mux_init_signal("sdmmc2_dat0",
OMAP_PIN_INPUT_PULLUP);
/*
* For 8 wire configurations, Lines DAT4, 5, 6 and 7
* need to be muxed in the board-*.c files
*/
if (mmc_controller->slots[0].caps &
(MMC_CAP_4_BIT_DATA | MMC_CAP_8_BIT_DATA)) {
omap_mux_init_signal("sdmmc2_dat1",
OMAP_PIN_INPUT_PULLUP);
omap_mux_init_signal("sdmmc2_dat2",
OMAP_PIN_INPUT_PULLUP);
omap_mux_init_signal("sdmmc2_dat3",
OMAP_PIN_INPUT_PULLUP);
}
if (mmc_controller->slots[0].caps &
MMC_CAP_8_BIT_DATA) {
omap_mux_init_signal("sdmmc2_dat4.sdmmc2_dat4",
OMAP_PIN_INPUT_PULLUP);
omap_mux_init_signal("sdmmc2_dat5.sdmmc2_dat5",
OMAP_PIN_INPUT_PULLUP);
omap_mux_init_signal("sdmmc2_dat6.sdmmc2_dat6",
OMAP_PIN_INPUT_PULLUP);
omap_mux_init_signal("sdmmc2_dat7.sdmmc2_dat7",
OMAP_PIN_INPUT_PULLUP);
}
}
/*
* For MMC3 the pins need to be muxed in the board-*.c files
*/
}
}
static int __init omap_hsmmc_pdata_init(struct omap2_hsmmc_info *c,
struct omap_mmc_platform_data *mmc)
{
char *hc_name;
hc_name = kzalloc(sizeof(char) * (HSMMC_NAME_LEN + 1), GFP_KERNEL);
if (!hc_name) {
pr_err("Cannot allocate memory for controller slot name\n");
kfree(hc_name);
return -ENOMEM;
}
if (c->name)
strncpy(hc_name, c->name, HSMMC_NAME_LEN);
else
snprintf(hc_name, (HSMMC_NAME_LEN + 1), "mmc%islot%i",
c->mmc, 1);
mmc->slots[0].name = hc_name;
mmc->nr_slots = 1;
mmc->slots[0].caps = c->caps;
mmc->slots[0].pm_caps = c->pm_caps;
mmc->slots[0].internal_clock = !c->ext_clock;
mmc->dma_mask = 0xffffffff;
mmc->max_freq = c->max_freq;
if (cpu_is_omap44xx())
mmc->reg_offset = OMAP4_MMC_REG_OFFSET;
else
mmc->reg_offset = 0;
mmc->get_context_loss_count = hsmmc_get_context_loss;
mmc->slots[0].switch_pin = c->gpio_cd;
mmc->slots[0].gpio_wp = c->gpio_wp;
mmc->slots[0].remux = c->remux;
mmc->slots[0].init_card = c->init_card;
if (c->cover_only)
mmc->slots[0].cover = 1;
if (c->nonremovable)
mmc->slots[0].nonremovable = 1;
if (c->power_saving)
mmc->slots[0].power_saving = 1;
if (c->no_off)
mmc->slots[0].no_off = 1;
if (c->no_off_init)
mmc->slots[0].no_regulator_off_init = c->no_off_init;
if (c->vcc_aux_disable_is_sleep)
mmc->slots[0].vcc_aux_disable_is_sleep = 1;
/*
* NOTE: MMC slots should have a Vcc regulator set up.
* This may be from a TWL4030-family chip, another
* controllable regulator, or a fixed supply.
*
* temporary HACK: ocr_mask instead of fixed supply
*/
if (cpu_is_omap3505() || cpu_is_omap3517())
mmc->slots[0].ocr_mask = MMC_VDD_165_195 |
MMC_VDD_26_27 |
MMC_VDD_27_28 |
MMC_VDD_29_30 |
MMC_VDD_30_31 |
MMC_VDD_31_32;
else
mmc->slots[0].ocr_mask = c->ocr_mask;
if (!cpu_is_omap3517() && !cpu_is_omap3505())
mmc->slots[0].features |= HSMMC_HAS_PBIAS;
if (cpu_is_omap44xx() && (omap_rev() > OMAP4430_REV_ES1_0))
mmc->slots[0].features |= HSMMC_HAS_UPDATED_RESET;
switch (c->mmc) {
case 1:
if (mmc->slots[0].features & HSMMC_HAS_PBIAS) {
/* on-chip level shifting via PBIAS0/PBIAS1 */
if (cpu_is_omap44xx()) {
mmc->slots[0].before_set_reg =
omap4_hsmmc1_before_set_reg;
mmc->slots[0].after_set_reg =
omap4_hsmmc1_after_set_reg;
} else {
mmc->slots[0].before_set_reg =
omap_hsmmc1_before_set_reg;
mmc->slots[0].after_set_reg =
omap_hsmmc1_after_set_reg;
}
}
if (cpu_is_omap3517() || cpu_is_omap3505())
mmc->slots[0].set_power = nop_mmc_set_power;
/* OMAP3630 HSMMC1 supports only 4-bit */
if (cpu_is_omap3630() &&
(c->caps & MMC_CAP_8_BIT_DATA)) {
c->caps &= ~MMC_CAP_8_BIT_DATA;
c->caps |= MMC_CAP_4_BIT_DATA;
mmc->slots[0].caps = c->caps;
}
break;
case 2:
if (cpu_is_omap3517() || cpu_is_omap3505())
mmc->slots[0].set_power = am35x_hsmmc2_set_power;
if (c->ext_clock)
c->transceiver = 1;
if (c->transceiver && (c->caps & MMC_CAP_8_BIT_DATA)) {
c->caps &= ~MMC_CAP_8_BIT_DATA;
c->caps |= MMC_CAP_4_BIT_DATA;
}
if (mmc->slots[0].features & HSMMC_HAS_PBIAS) {
/* off-chip level shifting, or none */
mmc->slots[0].before_set_reg = hsmmc2_before_set_reg;
mmc->slots[0].after_set_reg = NULL;
}
break;
case 3:
case 4:
case 5:
mmc->slots[0].before_set_reg = NULL;
mmc->slots[0].after_set_reg = NULL;
break;
default:
pr_err("MMC%d configuration not supported!\n", c->mmc);
kfree(hc_name);
return -ENODEV;
}
return 0;
}
static int omap_hsmmc_done;
void omap_hsmmc_late_init(struct omap2_hsmmc_info *c)
{
struct platform_device *pdev;
struct omap_mmc_platform_data *mmc_pdata;
int res;
if (omap_hsmmc_done != 1)
return;
omap_hsmmc_done++;
for (; c->mmc; c++) {
if (!c->deferred)
continue;
pdev = c->pdev;
if (!pdev)
continue;
mmc_pdata = pdev->dev.platform_data;
if (!mmc_pdata)
continue;
mmc_pdata->slots[0].switch_pin = c->gpio_cd;
mmc_pdata->slots[0].gpio_wp = c->gpio_wp;
res = omap_device_register(pdev);
if (res)
pr_err("Could not late init MMC %s\n",
c->name);
}
}
#define MAX_OMAP_MMC_HWMOD_NAME_LEN 16
static void __init omap_hsmmc_init_one(struct omap2_hsmmc_info *hsmmcinfo,
int ctrl_nr)
{
struct omap_hwmod *oh;
struct omap_hwmod *ohs[1];
struct omap_device *od;
struct platform_device *pdev;
char oh_name[MAX_OMAP_MMC_HWMOD_NAME_LEN];
struct omap_mmc_platform_data *mmc_data;
struct omap_mmc_dev_attr *mmc_dev_attr;
char *name;
int res;
mmc_data = kzalloc(sizeof(struct omap_mmc_platform_data), GFP_KERNEL);
if (!mmc_data) {
pr_err("Cannot allocate memory for mmc device!\n");
return;
}
res = omap_hsmmc_pdata_init(hsmmcinfo, mmc_data);
if (res < 0)
goto free_mmc;
omap_hsmmc_mux(mmc_data, (ctrl_nr - 1));
name = "omap_hsmmc";
res = snprintf(oh_name, MAX_OMAP_MMC_HWMOD_NAME_LEN,
"mmc%d", ctrl_nr);
WARN(res >= MAX_OMAP_MMC_HWMOD_NAME_LEN,
"String buffer overflow in MMC%d device setup\n", ctrl_nr);
oh = omap_hwmod_lookup(oh_name);
if (!oh) {
pr_err("Could not look up %s\n", oh_name);
goto free_name;
}
ohs[0] = oh;
if (oh->dev_attr != NULL) {
mmc_dev_attr = oh->dev_attr;
mmc_data->controller_flags = mmc_dev_attr->flags;
/*
* erratum 2.1.1.128 doesn't apply if board has
* a transceiver is attached
*/
if (hsmmcinfo->transceiver)
mmc_data->controller_flags &=
~OMAP_HSMMC_BROKEN_MULTIBLOCK_READ;
}
pdev = platform_device_alloc(name, ctrl_nr - 1);
if (!pdev) {
pr_err("Could not allocate pdev for %s\n", name);
goto free_name;
}
dev_set_name(&pdev->dev, "%s.%d", pdev->name, pdev->id);
od = omap_device_alloc(pdev, ohs, 1, NULL, 0);
if (!od) {
pr_err("Could not allocate od for %s\n", name);
goto put_pdev;
}
res = platform_device_add_data(pdev, mmc_data,
sizeof(struct omap_mmc_platform_data));
if (res) {
pr_err("Could not add pdata for %s\n", name);
goto put_pdev;
}
hsmmcinfo->pdev = pdev;
if (hsmmcinfo->deferred)
goto free_mmc;
res = omap_device_register(pdev);
if (res) {
pr_err("Could not register od for %s\n", name);
goto free_od;
}
goto free_mmc;
free_od:
omap_device_delete(od);
put_pdev:
platform_device_put(pdev);
free_name:
kfree(mmc_data->slots[0].name);
free_mmc:
kfree(mmc_data);
}
void __init omap_hsmmc_init(struct omap2_hsmmc_info *controllers)
{
u32 reg;
if (omap_hsmmc_done)
return;
omap_hsmmc_done = 1;
if (!cpu_is_omap44xx()) {
if (cpu_is_omap2430()) {
control_pbias_offset = OMAP243X_CONTROL_PBIAS_LITE;
control_devconf1_offset = OMAP243X_CONTROL_DEVCONF1;
} else {
control_pbias_offset = OMAP343X_CONTROL_PBIAS_LITE;
control_devconf1_offset = OMAP343X_CONTROL_DEVCONF1;
}
} else {
control_pbias_offset =
OMAP4_CTRL_MODULE_PAD_CORE_CONTROL_PBIASLITE;
control_mmc1 = OMAP4_CTRL_MODULE_PAD_CORE_CONTROL_MMC1;
reg = omap4_ctrl_pad_readl(control_mmc1);
reg |= (OMAP4_SDMMC1_PUSTRENGTH_GRP0_MASK |
OMAP4_SDMMC1_PUSTRENGTH_GRP1_MASK);
reg &= ~(OMAP4_SDMMC1_PUSTRENGTH_GRP2_MASK |
OMAP4_SDMMC1_PUSTRENGTH_GRP3_MASK);
reg |= (OMAP4_SDMMC1_DR0_SPEEDCTRL_MASK |
OMAP4_SDMMC1_DR1_SPEEDCTRL_MASK |
OMAP4_SDMMC1_DR2_SPEEDCTRL_MASK);
omap4_ctrl_pad_writel(reg, control_mmc1);
}
for (; controllers->mmc; controllers++)
omap_hsmmc_init_one(controllers, controllers->mmc);
}
#endif
| gpl-2.0 |
laruence/linux | sound/pci/ctxfi/ctdaio.c | 8035 | 17649 | /**
* Copyright (C) 2008, Creative Technology Ltd. All Rights Reserved.
*
* This source file is released under GPL v2 license (no other versions).
* See the COPYING file included in the main directory of this source
* distribution for the license terms and conditions.
*
* @File ctdaio.c
*
* @Brief
* This file contains the implementation of Digital Audio Input Output
* resource management object.
*
* @Author Liu Chun
* @Date May 23 2008
*
*/
#include "ctdaio.h"
#include "cthardware.h"
#include "ctimap.h"
#include <linux/slab.h>
#include <linux/kernel.h>
#define DAIO_OUT_MAX SPDIFOO
struct daio_usage {
unsigned short data;
};
struct daio_rsc_idx {
unsigned short left;
unsigned short right;
};
struct daio_rsc_idx idx_20k1[NUM_DAIOTYP] = {
[LINEO1] = {.left = 0x00, .right = 0x01},
[LINEO2] = {.left = 0x18, .right = 0x19},
[LINEO3] = {.left = 0x08, .right = 0x09},
[LINEO4] = {.left = 0x10, .right = 0x11},
[LINEIM] = {.left = 0x1b5, .right = 0x1bd},
[SPDIFOO] = {.left = 0x20, .right = 0x21},
[SPDIFIO] = {.left = 0x15, .right = 0x1d},
[SPDIFI1] = {.left = 0x95, .right = 0x9d},
};
struct daio_rsc_idx idx_20k2[NUM_DAIOTYP] = {
[LINEO1] = {.left = 0x40, .right = 0x41},
[LINEO2] = {.left = 0x60, .right = 0x61},
[LINEO3] = {.left = 0x50, .right = 0x51},
[LINEO4] = {.left = 0x70, .right = 0x71},
[LINEIM] = {.left = 0x45, .right = 0xc5},
[MIC] = {.left = 0x55, .right = 0xd5},
[SPDIFOO] = {.left = 0x00, .right = 0x01},
[SPDIFIO] = {.left = 0x05, .right = 0x85},
};
static int daio_master(struct rsc *rsc)
{
/* Actually, this is not the resource index of DAIO.
* For DAO, it is the input mapper index. And, for DAI,
* it is the output time-slot index. */
return rsc->conj = rsc->idx;
}
static int daio_index(const struct rsc *rsc)
{
return rsc->conj;
}
static int daio_out_next_conj(struct rsc *rsc)
{
return rsc->conj += 2;
}
static int daio_in_next_conj_20k1(struct rsc *rsc)
{
return rsc->conj += 0x200;
}
static int daio_in_next_conj_20k2(struct rsc *rsc)
{
return rsc->conj += 0x100;
}
static struct rsc_ops daio_out_rsc_ops = {
.master = daio_master,
.next_conj = daio_out_next_conj,
.index = daio_index,
.output_slot = NULL,
};
static struct rsc_ops daio_in_rsc_ops_20k1 = {
.master = daio_master,
.next_conj = daio_in_next_conj_20k1,
.index = NULL,
.output_slot = daio_index,
};
static struct rsc_ops daio_in_rsc_ops_20k2 = {
.master = daio_master,
.next_conj = daio_in_next_conj_20k2,
.index = NULL,
.output_slot = daio_index,
};
static unsigned int daio_device_index(enum DAIOTYP type, struct hw *hw)
{
switch (hw->chip_type) {
case ATC20K1:
switch (type) {
case SPDIFOO: return 0;
case SPDIFIO: return 0;
case SPDIFI1: return 1;
case LINEO1: return 4;
case LINEO2: return 7;
case LINEO3: return 5;
case LINEO4: return 6;
case LINEIM: return 7;
default: return -EINVAL;
}
case ATC20K2:
switch (type) {
case SPDIFOO: return 0;
case SPDIFIO: return 0;
case LINEO1: return 4;
case LINEO2: return 7;
case LINEO3: return 5;
case LINEO4: return 6;
case LINEIM: return 4;
case MIC: return 5;
default: return -EINVAL;
}
default:
return -EINVAL;
}
}
static int dao_rsc_reinit(struct dao *dao, const struct dao_desc *desc);
static int dao_spdif_get_spos(struct dao *dao, unsigned int *spos)
{
((struct hw *)dao->hw)->dao_get_spos(dao->ctrl_blk, spos);
return 0;
}
static int dao_spdif_set_spos(struct dao *dao, unsigned int spos)
{
((struct hw *)dao->hw)->dao_set_spos(dao->ctrl_blk, spos);
return 0;
}
static int dao_commit_write(struct dao *dao)
{
((struct hw *)dao->hw)->dao_commit_write(dao->hw,
daio_device_index(dao->daio.type, dao->hw), dao->ctrl_blk);
return 0;
}
static int dao_set_left_input(struct dao *dao, struct rsc *input)
{
struct imapper *entry;
struct daio *daio = &dao->daio;
int i;
entry = kzalloc((sizeof(*entry) * daio->rscl.msr), GFP_KERNEL);
if (!entry)
return -ENOMEM;
dao->ops->clear_left_input(dao);
/* Program master and conjugate resources */
input->ops->master(input);
daio->rscl.ops->master(&daio->rscl);
for (i = 0; i < daio->rscl.msr; i++, entry++) {
entry->slot = input->ops->output_slot(input);
entry->user = entry->addr = daio->rscl.ops->index(&daio->rscl);
dao->mgr->imap_add(dao->mgr, entry);
dao->imappers[i] = entry;
input->ops->next_conj(input);
daio->rscl.ops->next_conj(&daio->rscl);
}
input->ops->master(input);
daio->rscl.ops->master(&daio->rscl);
return 0;
}
static int dao_set_right_input(struct dao *dao, struct rsc *input)
{
struct imapper *entry;
struct daio *daio = &dao->daio;
int i;
entry = kzalloc((sizeof(*entry) * daio->rscr.msr), GFP_KERNEL);
if (!entry)
return -ENOMEM;
dao->ops->clear_right_input(dao);
/* Program master and conjugate resources */
input->ops->master(input);
daio->rscr.ops->master(&daio->rscr);
for (i = 0; i < daio->rscr.msr; i++, entry++) {
entry->slot = input->ops->output_slot(input);
entry->user = entry->addr = daio->rscr.ops->index(&daio->rscr);
dao->mgr->imap_add(dao->mgr, entry);
dao->imappers[daio->rscl.msr + i] = entry;
input->ops->next_conj(input);
daio->rscr.ops->next_conj(&daio->rscr);
}
input->ops->master(input);
daio->rscr.ops->master(&daio->rscr);
return 0;
}
static int dao_clear_left_input(struct dao *dao)
{
struct imapper *entry;
struct daio *daio = &dao->daio;
int i;
if (!dao->imappers[0])
return 0;
entry = dao->imappers[0];
dao->mgr->imap_delete(dao->mgr, entry);
/* Program conjugate resources */
for (i = 1; i < daio->rscl.msr; i++) {
entry = dao->imappers[i];
dao->mgr->imap_delete(dao->mgr, entry);
dao->imappers[i] = NULL;
}
kfree(dao->imappers[0]);
dao->imappers[0] = NULL;
return 0;
}
static int dao_clear_right_input(struct dao *dao)
{
struct imapper *entry;
struct daio *daio = &dao->daio;
int i;
if (!dao->imappers[daio->rscl.msr])
return 0;
entry = dao->imappers[daio->rscl.msr];
dao->mgr->imap_delete(dao->mgr, entry);
/* Program conjugate resources */
for (i = 1; i < daio->rscr.msr; i++) {
entry = dao->imappers[daio->rscl.msr + i];
dao->mgr->imap_delete(dao->mgr, entry);
dao->imappers[daio->rscl.msr + i] = NULL;
}
kfree(dao->imappers[daio->rscl.msr]);
dao->imappers[daio->rscl.msr] = NULL;
return 0;
}
static struct dao_rsc_ops dao_ops = {
.set_spos = dao_spdif_set_spos,
.commit_write = dao_commit_write,
.get_spos = dao_spdif_get_spos,
.reinit = dao_rsc_reinit,
.set_left_input = dao_set_left_input,
.set_right_input = dao_set_right_input,
.clear_left_input = dao_clear_left_input,
.clear_right_input = dao_clear_right_input,
};
static int dai_set_srt_srcl(struct dai *dai, struct rsc *src)
{
src->ops->master(src);
((struct hw *)dai->hw)->dai_srt_set_srcm(dai->ctrl_blk,
src->ops->index(src));
return 0;
}
static int dai_set_srt_srcr(struct dai *dai, struct rsc *src)
{
src->ops->master(src);
((struct hw *)dai->hw)->dai_srt_set_srco(dai->ctrl_blk,
src->ops->index(src));
return 0;
}
static int dai_set_srt_msr(struct dai *dai, unsigned int msr)
{
unsigned int rsr;
for (rsr = 0; msr > 1; msr >>= 1)
rsr++;
((struct hw *)dai->hw)->dai_srt_set_rsr(dai->ctrl_blk, rsr);
return 0;
}
static int dai_set_enb_src(struct dai *dai, unsigned int enb)
{
((struct hw *)dai->hw)->dai_srt_set_ec(dai->ctrl_blk, enb);
return 0;
}
static int dai_set_enb_srt(struct dai *dai, unsigned int enb)
{
((struct hw *)dai->hw)->dai_srt_set_et(dai->ctrl_blk, enb);
return 0;
}
static int dai_commit_write(struct dai *dai)
{
((struct hw *)dai->hw)->dai_commit_write(dai->hw,
daio_device_index(dai->daio.type, dai->hw), dai->ctrl_blk);
return 0;
}
static struct dai_rsc_ops dai_ops = {
.set_srt_srcl = dai_set_srt_srcl,
.set_srt_srcr = dai_set_srt_srcr,
.set_srt_msr = dai_set_srt_msr,
.set_enb_src = dai_set_enb_src,
.set_enb_srt = dai_set_enb_srt,
.commit_write = dai_commit_write,
};
static int daio_rsc_init(struct daio *daio,
const struct daio_desc *desc,
void *hw)
{
int err;
unsigned int idx_l, idx_r;
switch (((struct hw *)hw)->chip_type) {
case ATC20K1:
idx_l = idx_20k1[desc->type].left;
idx_r = idx_20k1[desc->type].right;
break;
case ATC20K2:
idx_l = idx_20k2[desc->type].left;
idx_r = idx_20k2[desc->type].right;
break;
default:
return -EINVAL;
}
err = rsc_init(&daio->rscl, idx_l, DAIO, desc->msr, hw);
if (err)
return err;
err = rsc_init(&daio->rscr, idx_r, DAIO, desc->msr, hw);
if (err)
goto error1;
/* Set daio->rscl/r->ops to daio specific ones */
if (desc->type <= DAIO_OUT_MAX) {
daio->rscl.ops = daio->rscr.ops = &daio_out_rsc_ops;
} else {
switch (((struct hw *)hw)->chip_type) {
case ATC20K1:
daio->rscl.ops = daio->rscr.ops = &daio_in_rsc_ops_20k1;
break;
case ATC20K2:
daio->rscl.ops = daio->rscr.ops = &daio_in_rsc_ops_20k2;
break;
default:
break;
}
}
daio->type = desc->type;
return 0;
error1:
rsc_uninit(&daio->rscl);
return err;
}
static int daio_rsc_uninit(struct daio *daio)
{
rsc_uninit(&daio->rscl);
rsc_uninit(&daio->rscr);
return 0;
}
static int dao_rsc_init(struct dao *dao,
const struct daio_desc *desc,
struct daio_mgr *mgr)
{
struct hw *hw = mgr->mgr.hw;
unsigned int conf;
int err;
err = daio_rsc_init(&dao->daio, desc, mgr->mgr.hw);
if (err)
return err;
dao->imappers = kzalloc(sizeof(void *)*desc->msr*2, GFP_KERNEL);
if (!dao->imappers) {
err = -ENOMEM;
goto error1;
}
dao->ops = &dao_ops;
dao->mgr = mgr;
dao->hw = hw;
err = hw->dao_get_ctrl_blk(&dao->ctrl_blk);
if (err)
goto error2;
hw->daio_mgr_dsb_dao(mgr->mgr.ctrl_blk,
daio_device_index(dao->daio.type, hw));
hw->daio_mgr_commit_write(hw, mgr->mgr.ctrl_blk);
conf = (desc->msr & 0x7) | (desc->passthru << 3);
hw->daio_mgr_dao_init(mgr->mgr.ctrl_blk,
daio_device_index(dao->daio.type, hw), conf);
hw->daio_mgr_enb_dao(mgr->mgr.ctrl_blk,
daio_device_index(dao->daio.type, hw));
hw->daio_mgr_commit_write(hw, mgr->mgr.ctrl_blk);
return 0;
error2:
kfree(dao->imappers);
dao->imappers = NULL;
error1:
daio_rsc_uninit(&dao->daio);
return err;
}
static int dao_rsc_uninit(struct dao *dao)
{
if (dao->imappers) {
if (dao->imappers[0])
dao_clear_left_input(dao);
if (dao->imappers[dao->daio.rscl.msr])
dao_clear_right_input(dao);
kfree(dao->imappers);
dao->imappers = NULL;
}
((struct hw *)dao->hw)->dao_put_ctrl_blk(dao->ctrl_blk);
dao->hw = dao->ctrl_blk = NULL;
daio_rsc_uninit(&dao->daio);
return 0;
}
static int dao_rsc_reinit(struct dao *dao, const struct dao_desc *desc)
{
struct daio_mgr *mgr = dao->mgr;
struct daio_desc dsc = {0};
dsc.type = dao->daio.type;
dsc.msr = desc->msr;
dsc.passthru = desc->passthru;
dao_rsc_uninit(dao);
return dao_rsc_init(dao, &dsc, mgr);
}
static int dai_rsc_init(struct dai *dai,
const struct daio_desc *desc,
struct daio_mgr *mgr)
{
int err;
struct hw *hw = mgr->mgr.hw;
unsigned int rsr, msr;
err = daio_rsc_init(&dai->daio, desc, mgr->mgr.hw);
if (err)
return err;
dai->ops = &dai_ops;
dai->hw = mgr->mgr.hw;
err = hw->dai_get_ctrl_blk(&dai->ctrl_blk);
if (err)
goto error1;
for (rsr = 0, msr = desc->msr; msr > 1; msr >>= 1)
rsr++;
hw->dai_srt_set_rsr(dai->ctrl_blk, rsr);
hw->dai_srt_set_drat(dai->ctrl_blk, 0);
/* default to disabling control of a SRC */
hw->dai_srt_set_ec(dai->ctrl_blk, 0);
hw->dai_srt_set_et(dai->ctrl_blk, 0); /* default to disabling SRT */
hw->dai_commit_write(hw,
daio_device_index(dai->daio.type, dai->hw), dai->ctrl_blk);
return 0;
error1:
daio_rsc_uninit(&dai->daio);
return err;
}
static int dai_rsc_uninit(struct dai *dai)
{
((struct hw *)dai->hw)->dai_put_ctrl_blk(dai->ctrl_blk);
dai->hw = dai->ctrl_blk = NULL;
daio_rsc_uninit(&dai->daio);
return 0;
}
static int daio_mgr_get_rsc(struct rsc_mgr *mgr, enum DAIOTYP type)
{
if (((struct daio_usage *)mgr->rscs)->data & (0x1 << type))
return -ENOENT;
((struct daio_usage *)mgr->rscs)->data |= (0x1 << type);
return 0;
}
static int daio_mgr_put_rsc(struct rsc_mgr *mgr, enum DAIOTYP type)
{
((struct daio_usage *)mgr->rscs)->data &= ~(0x1 << type);
return 0;
}
static int get_daio_rsc(struct daio_mgr *mgr,
const struct daio_desc *desc,
struct daio **rdaio)
{
int err;
struct dai *dai = NULL;
struct dao *dao = NULL;
unsigned long flags;
*rdaio = NULL;
/* Check whether there are sufficient daio resources to meet request. */
spin_lock_irqsave(&mgr->mgr_lock, flags);
err = daio_mgr_get_rsc(&mgr->mgr, desc->type);
spin_unlock_irqrestore(&mgr->mgr_lock, flags);
if (err) {
printk(KERN_ERR "Can't meet DAIO resource request!\n");
return err;
}
/* Allocate mem for daio resource */
if (desc->type <= DAIO_OUT_MAX) {
dao = kzalloc(sizeof(*dao), GFP_KERNEL);
if (!dao) {
err = -ENOMEM;
goto error;
}
err = dao_rsc_init(dao, desc, mgr);
if (err)
goto error;
*rdaio = &dao->daio;
} else {
dai = kzalloc(sizeof(*dai), GFP_KERNEL);
if (!dai) {
err = -ENOMEM;
goto error;
}
err = dai_rsc_init(dai, desc, mgr);
if (err)
goto error;
*rdaio = &dai->daio;
}
mgr->daio_enable(mgr, *rdaio);
mgr->commit_write(mgr);
return 0;
error:
if (dao)
kfree(dao);
else if (dai)
kfree(dai);
spin_lock_irqsave(&mgr->mgr_lock, flags);
daio_mgr_put_rsc(&mgr->mgr, desc->type);
spin_unlock_irqrestore(&mgr->mgr_lock, flags);
return err;
}
static int put_daio_rsc(struct daio_mgr *mgr, struct daio *daio)
{
unsigned long flags;
mgr->daio_disable(mgr, daio);
mgr->commit_write(mgr);
spin_lock_irqsave(&mgr->mgr_lock, flags);
daio_mgr_put_rsc(&mgr->mgr, daio->type);
spin_unlock_irqrestore(&mgr->mgr_lock, flags);
if (daio->type <= DAIO_OUT_MAX) {
dao_rsc_uninit(container_of(daio, struct dao, daio));
kfree(container_of(daio, struct dao, daio));
} else {
dai_rsc_uninit(container_of(daio, struct dai, daio));
kfree(container_of(daio, struct dai, daio));
}
return 0;
}
static int daio_mgr_enb_daio(struct daio_mgr *mgr, struct daio *daio)
{
struct hw *hw = mgr->mgr.hw;
if (DAIO_OUT_MAX >= daio->type) {
hw->daio_mgr_enb_dao(mgr->mgr.ctrl_blk,
daio_device_index(daio->type, hw));
} else {
hw->daio_mgr_enb_dai(mgr->mgr.ctrl_blk,
daio_device_index(daio->type, hw));
}
return 0;
}
static int daio_mgr_dsb_daio(struct daio_mgr *mgr, struct daio *daio)
{
struct hw *hw = mgr->mgr.hw;
if (DAIO_OUT_MAX >= daio->type) {
hw->daio_mgr_dsb_dao(mgr->mgr.ctrl_blk,
daio_device_index(daio->type, hw));
} else {
hw->daio_mgr_dsb_dai(mgr->mgr.ctrl_blk,
daio_device_index(daio->type, hw));
}
return 0;
}
static int daio_map_op(void *data, struct imapper *entry)
{
struct rsc_mgr *mgr = &((struct daio_mgr *)data)->mgr;
struct hw *hw = mgr->hw;
hw->daio_mgr_set_imaparc(mgr->ctrl_blk, entry->slot);
hw->daio_mgr_set_imapnxt(mgr->ctrl_blk, entry->next);
hw->daio_mgr_set_imapaddr(mgr->ctrl_blk, entry->addr);
hw->daio_mgr_commit_write(mgr->hw, mgr->ctrl_blk);
return 0;
}
static int daio_imap_add(struct daio_mgr *mgr, struct imapper *entry)
{
unsigned long flags;
int err;
spin_lock_irqsave(&mgr->imap_lock, flags);
if (!entry->addr && mgr->init_imap_added) {
input_mapper_delete(&mgr->imappers, mgr->init_imap,
daio_map_op, mgr);
mgr->init_imap_added = 0;
}
err = input_mapper_add(&mgr->imappers, entry, daio_map_op, mgr);
spin_unlock_irqrestore(&mgr->imap_lock, flags);
return err;
}
static int daio_imap_delete(struct daio_mgr *mgr, struct imapper *entry)
{
unsigned long flags;
int err;
spin_lock_irqsave(&mgr->imap_lock, flags);
err = input_mapper_delete(&mgr->imappers, entry, daio_map_op, mgr);
if (list_empty(&mgr->imappers)) {
input_mapper_add(&mgr->imappers, mgr->init_imap,
daio_map_op, mgr);
mgr->init_imap_added = 1;
}
spin_unlock_irqrestore(&mgr->imap_lock, flags);
return err;
}
static int daio_mgr_commit_write(struct daio_mgr *mgr)
{
struct hw *hw = mgr->mgr.hw;
hw->daio_mgr_commit_write(hw, mgr->mgr.ctrl_blk);
return 0;
}
int daio_mgr_create(void *hw, struct daio_mgr **rdaio_mgr)
{
int err, i;
struct daio_mgr *daio_mgr;
struct imapper *entry;
*rdaio_mgr = NULL;
daio_mgr = kzalloc(sizeof(*daio_mgr), GFP_KERNEL);
if (!daio_mgr)
return -ENOMEM;
err = rsc_mgr_init(&daio_mgr->mgr, DAIO, NUM_DAIOTYP, hw);
if (err)
goto error1;
spin_lock_init(&daio_mgr->mgr_lock);
spin_lock_init(&daio_mgr->imap_lock);
INIT_LIST_HEAD(&daio_mgr->imappers);
entry = kzalloc(sizeof(*entry), GFP_KERNEL);
if (!entry) {
err = -ENOMEM;
goto error2;
}
entry->slot = entry->addr = entry->next = entry->user = 0;
list_add(&entry->list, &daio_mgr->imappers);
daio_mgr->init_imap = entry;
daio_mgr->init_imap_added = 1;
daio_mgr->get_daio = get_daio_rsc;
daio_mgr->put_daio = put_daio_rsc;
daio_mgr->daio_enable = daio_mgr_enb_daio;
daio_mgr->daio_disable = daio_mgr_dsb_daio;
daio_mgr->imap_add = daio_imap_add;
daio_mgr->imap_delete = daio_imap_delete;
daio_mgr->commit_write = daio_mgr_commit_write;
for (i = 0; i < 8; i++) {
((struct hw *)hw)->daio_mgr_dsb_dao(daio_mgr->mgr.ctrl_blk, i);
((struct hw *)hw)->daio_mgr_dsb_dai(daio_mgr->mgr.ctrl_blk, i);
}
((struct hw *)hw)->daio_mgr_commit_write(hw, daio_mgr->mgr.ctrl_blk);
*rdaio_mgr = daio_mgr;
return 0;
error2:
rsc_mgr_uninit(&daio_mgr->mgr);
error1:
kfree(daio_mgr);
return err;
}
int daio_mgr_destroy(struct daio_mgr *daio_mgr)
{
unsigned long flags;
/* free daio input mapper list */
spin_lock_irqsave(&daio_mgr->imap_lock, flags);
free_input_mapper_list(&daio_mgr->imappers);
spin_unlock_irqrestore(&daio_mgr->imap_lock, flags);
rsc_mgr_uninit(&daio_mgr->mgr);
kfree(daio_mgr);
return 0;
}
| gpl-2.0 |
MattCrystal/sarin-gas-aosp-jewel | drivers/media/dvb/pt1/va1j5jf8007t.c | 8803 | 11580 | /*
* ISDB-T driver for VA1J5JF8007/VA1J5JF8011
*
* Copyright (C) 2009 HIRANO Takahito <hiranotaka@zng.info>
*
* based on pt1dvr - http://pt1dvr.sourceforge.jp/
* by Tomoaki Ishikawa <tomy@users.sourceforge.jp>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/i2c.h>
#include "dvb_frontend.h"
#include "dvb_math.h"
#include "va1j5jf8007t.h"
enum va1j5jf8007t_tune_state {
VA1J5JF8007T_IDLE,
VA1J5JF8007T_SET_FREQUENCY,
VA1J5JF8007T_CHECK_FREQUENCY,
VA1J5JF8007T_SET_MODULATION,
VA1J5JF8007T_CHECK_MODULATION,
VA1J5JF8007T_TRACK,
VA1J5JF8007T_ABORT,
};
struct va1j5jf8007t_state {
const struct va1j5jf8007t_config *config;
struct i2c_adapter *adap;
struct dvb_frontend fe;
enum va1j5jf8007t_tune_state tune_state;
};
static int va1j5jf8007t_read_snr(struct dvb_frontend *fe, u16 *snr)
{
struct va1j5jf8007t_state *state;
u8 addr;
int i;
u8 write_buf[1], read_buf[1];
struct i2c_msg msgs[2];
s32 word, x, y;
state = fe->demodulator_priv;
addr = state->config->demod_address;
word = 0;
for (i = 0; i < 3; i++) {
write_buf[0] = 0x8b + i;
msgs[0].addr = addr;
msgs[0].flags = 0;
msgs[0].len = sizeof(write_buf);
msgs[0].buf = write_buf;
msgs[1].addr = addr;
msgs[1].flags = I2C_M_RD;
msgs[1].len = sizeof(read_buf);
msgs[1].buf = read_buf;
if (i2c_transfer(state->adap, msgs, 2) != 2)
return -EREMOTEIO;
word <<= 8;
word |= read_buf[0];
}
if (!word)
return -EIO;
x = 10 * (intlog10(0x540000 * 100 / word) - (2 << 24));
y = (24ll << 46) / 1000000;
y = ((s64)y * x >> 30) - (16ll << 40) / 10000;
y = ((s64)y * x >> 29) + (398ll << 35) / 10000;
y = ((s64)y * x >> 30) + (5491ll << 29) / 10000;
y = ((s64)y * x >> 30) + (30965ll << 23) / 10000;
*snr = y >> 15;
return 0;
}
static int va1j5jf8007t_get_frontend_algo(struct dvb_frontend *fe)
{
return DVBFE_ALGO_HW;
}
static int
va1j5jf8007t_read_status(struct dvb_frontend *fe, fe_status_t *status)
{
struct va1j5jf8007t_state *state;
state = fe->demodulator_priv;
switch (state->tune_state) {
case VA1J5JF8007T_IDLE:
case VA1J5JF8007T_SET_FREQUENCY:
case VA1J5JF8007T_CHECK_FREQUENCY:
*status = 0;
return 0;
case VA1J5JF8007T_SET_MODULATION:
case VA1J5JF8007T_CHECK_MODULATION:
case VA1J5JF8007T_ABORT:
*status |= FE_HAS_SIGNAL;
return 0;
case VA1J5JF8007T_TRACK:
*status |= FE_HAS_SIGNAL | FE_HAS_CARRIER | FE_HAS_LOCK;
return 0;
}
BUG();
}
struct va1j5jf8007t_cb_map {
u32 frequency;
u8 cb;
};
static const struct va1j5jf8007t_cb_map va1j5jf8007t_cb_maps[] = {
{ 90000000, 0x80 },
{ 140000000, 0x81 },
{ 170000000, 0xa1 },
{ 220000000, 0x62 },
{ 330000000, 0xa2 },
{ 402000000, 0xe2 },
{ 450000000, 0x64 },
{ 550000000, 0x84 },
{ 600000000, 0xa4 },
{ 700000000, 0xc4 },
};
static u8 va1j5jf8007t_lookup_cb(u32 frequency)
{
int i;
const struct va1j5jf8007t_cb_map *map;
for (i = 0; i < ARRAY_SIZE(va1j5jf8007t_cb_maps); i++) {
map = &va1j5jf8007t_cb_maps[i];
if (frequency < map->frequency)
return map->cb;
}
return 0xe4;
}
static int va1j5jf8007t_set_frequency(struct va1j5jf8007t_state *state)
{
u32 frequency;
u16 word;
u8 buf[6];
struct i2c_msg msg;
frequency = state->fe.dtv_property_cache.frequency;
word = (frequency + 71428) / 142857 + 399;
buf[0] = 0xfe;
buf[1] = 0xc2;
buf[2] = word >> 8;
buf[3] = word;
buf[4] = 0x80;
buf[5] = va1j5jf8007t_lookup_cb(frequency);
msg.addr = state->config->demod_address;
msg.flags = 0;
msg.len = sizeof(buf);
msg.buf = buf;
if (i2c_transfer(state->adap, &msg, 1) != 1)
return -EREMOTEIO;
return 0;
}
static int
va1j5jf8007t_check_frequency(struct va1j5jf8007t_state *state, int *lock)
{
u8 addr;
u8 write_buf[2], read_buf[1];
struct i2c_msg msgs[2];
addr = state->config->demod_address;
write_buf[0] = 0xfe;
write_buf[1] = 0xc3;
msgs[0].addr = addr;
msgs[0].flags = 0;
msgs[0].len = sizeof(write_buf);
msgs[0].buf = write_buf;
msgs[1].addr = addr;
msgs[1].flags = I2C_M_RD;
msgs[1].len = sizeof(read_buf);
msgs[1].buf = read_buf;
if (i2c_transfer(state->adap, msgs, 2) != 2)
return -EREMOTEIO;
*lock = read_buf[0] & 0x40;
return 0;
}
static int va1j5jf8007t_set_modulation(struct va1j5jf8007t_state *state)
{
u8 buf[2];
struct i2c_msg msg;
buf[0] = 0x01;
buf[1] = 0x40;
msg.addr = state->config->demod_address;
msg.flags = 0;
msg.len = sizeof(buf);
msg.buf = buf;
if (i2c_transfer(state->adap, &msg, 1) != 1)
return -EREMOTEIO;
return 0;
}
static int va1j5jf8007t_check_modulation(struct va1j5jf8007t_state *state,
int *lock, int *retry)
{
u8 addr;
u8 write_buf[1], read_buf[1];
struct i2c_msg msgs[2];
addr = state->config->demod_address;
write_buf[0] = 0x80;
msgs[0].addr = addr;
msgs[0].flags = 0;
msgs[0].len = sizeof(write_buf);
msgs[0].buf = write_buf;
msgs[1].addr = addr;
msgs[1].flags = I2C_M_RD;
msgs[1].len = sizeof(read_buf);
msgs[1].buf = read_buf;
if (i2c_transfer(state->adap, msgs, 2) != 2)
return -EREMOTEIO;
*lock = !(read_buf[0] & 0x10);
*retry = read_buf[0] & 0x80;
return 0;
}
static int
va1j5jf8007t_tune(struct dvb_frontend *fe,
bool re_tune,
unsigned int mode_flags, unsigned int *delay,
fe_status_t *status)
{
struct va1j5jf8007t_state *state;
int ret;
int lock = 0, retry = 0;
state = fe->demodulator_priv;
if (re_tune)
state->tune_state = VA1J5JF8007T_SET_FREQUENCY;
switch (state->tune_state) {
case VA1J5JF8007T_IDLE:
*delay = 3 * HZ;
*status = 0;
return 0;
case VA1J5JF8007T_SET_FREQUENCY:
ret = va1j5jf8007t_set_frequency(state);
if (ret < 0)
return ret;
state->tune_state = VA1J5JF8007T_CHECK_FREQUENCY;
*delay = 0;
*status = 0;
return 0;
case VA1J5JF8007T_CHECK_FREQUENCY:
ret = va1j5jf8007t_check_frequency(state, &lock);
if (ret < 0)
return ret;
if (!lock) {
*delay = (HZ + 999) / 1000;
*status = 0;
return 0;
}
state->tune_state = VA1J5JF8007T_SET_MODULATION;
*delay = 0;
*status = FE_HAS_SIGNAL;
return 0;
case VA1J5JF8007T_SET_MODULATION:
ret = va1j5jf8007t_set_modulation(state);
if (ret < 0)
return ret;
state->tune_state = VA1J5JF8007T_CHECK_MODULATION;
*delay = 0;
*status = FE_HAS_SIGNAL;
return 0;
case VA1J5JF8007T_CHECK_MODULATION:
ret = va1j5jf8007t_check_modulation(state, &lock, &retry);
if (ret < 0)
return ret;
if (!lock) {
if (!retry) {
state->tune_state = VA1J5JF8007T_ABORT;
*delay = 3 * HZ;
*status = FE_HAS_SIGNAL;
return 0;
}
*delay = (HZ + 999) / 1000;
*status = FE_HAS_SIGNAL;
return 0;
}
state->tune_state = VA1J5JF8007T_TRACK;
/* fall through */
case VA1J5JF8007T_TRACK:
*delay = 3 * HZ;
*status = FE_HAS_SIGNAL | FE_HAS_CARRIER | FE_HAS_LOCK;
return 0;
case VA1J5JF8007T_ABORT:
*delay = 3 * HZ;
*status = FE_HAS_SIGNAL;
return 0;
}
BUG();
}
static int va1j5jf8007t_init_frequency(struct va1j5jf8007t_state *state)
{
u8 buf[7];
struct i2c_msg msg;
buf[0] = 0xfe;
buf[1] = 0xc2;
buf[2] = 0x01;
buf[3] = 0x8f;
buf[4] = 0xc1;
buf[5] = 0x80;
buf[6] = 0x80;
msg.addr = state->config->demod_address;
msg.flags = 0;
msg.len = sizeof(buf);
msg.buf = buf;
if (i2c_transfer(state->adap, &msg, 1) != 1)
return -EREMOTEIO;
return 0;
}
static int va1j5jf8007t_set_sleep(struct va1j5jf8007t_state *state, int sleep)
{
u8 buf[2];
struct i2c_msg msg;
buf[0] = 0x03;
buf[1] = sleep ? 0x90 : 0x80;
msg.addr = state->config->demod_address;
msg.flags = 0;
msg.len = sizeof(buf);
msg.buf = buf;
if (i2c_transfer(state->adap, &msg, 1) != 1)
return -EREMOTEIO;
return 0;
}
static int va1j5jf8007t_sleep(struct dvb_frontend *fe)
{
struct va1j5jf8007t_state *state;
int ret;
state = fe->demodulator_priv;
ret = va1j5jf8007t_init_frequency(state);
if (ret < 0)
return ret;
return va1j5jf8007t_set_sleep(state, 1);
}
static int va1j5jf8007t_init(struct dvb_frontend *fe)
{
struct va1j5jf8007t_state *state;
state = fe->demodulator_priv;
state->tune_state = VA1J5JF8007T_IDLE;
return va1j5jf8007t_set_sleep(state, 0);
}
static void va1j5jf8007t_release(struct dvb_frontend *fe)
{
struct va1j5jf8007t_state *state;
state = fe->demodulator_priv;
kfree(state);
}
static struct dvb_frontend_ops va1j5jf8007t_ops = {
.delsys = { SYS_ISDBT },
.info = {
.name = "VA1J5JF8007/VA1J5JF8011 ISDB-T",
.frequency_min = 90000000,
.frequency_max = 770000000,
.frequency_stepsize = 142857,
.caps = FE_CAN_INVERSION_AUTO | FE_CAN_FEC_AUTO |
FE_CAN_QAM_AUTO | FE_CAN_TRANSMISSION_MODE_AUTO |
FE_CAN_GUARD_INTERVAL_AUTO | FE_CAN_HIERARCHY_AUTO,
},
.read_snr = va1j5jf8007t_read_snr,
.get_frontend_algo = va1j5jf8007t_get_frontend_algo,
.read_status = va1j5jf8007t_read_status,
.tune = va1j5jf8007t_tune,
.sleep = va1j5jf8007t_sleep,
.init = va1j5jf8007t_init,
.release = va1j5jf8007t_release,
};
static const u8 va1j5jf8007t_20mhz_prepare_bufs[][2] = {
{0x03, 0x90}, {0x14, 0x8f}, {0x1c, 0x2a}, {0x1d, 0xa8}, {0x1e, 0xa2},
{0x22, 0x83}, {0x31, 0x0d}, {0x32, 0xe0}, {0x39, 0xd3}, {0x3a, 0x00},
{0x5c, 0x40}, {0x5f, 0x80}, {0x75, 0x02}, {0x76, 0x4e}, {0x77, 0x03},
{0xef, 0x01}
};
static const u8 va1j5jf8007t_25mhz_prepare_bufs[][2] = {
{0x03, 0x90}, {0x1c, 0x2a}, {0x1d, 0xa8}, {0x1e, 0xa2}, {0x22, 0x83},
{0x3a, 0x00}, {0x5c, 0x40}, {0x5f, 0x80}, {0x75, 0x0a}, {0x76, 0x4c},
{0x77, 0x03}, {0xef, 0x01}
};
int va1j5jf8007t_prepare(struct dvb_frontend *fe)
{
struct va1j5jf8007t_state *state;
const u8 (*bufs)[2];
int size;
u8 buf[2];
struct i2c_msg msg;
int i;
state = fe->demodulator_priv;
switch (state->config->frequency) {
case VA1J5JF8007T_20MHZ:
bufs = va1j5jf8007t_20mhz_prepare_bufs;
size = ARRAY_SIZE(va1j5jf8007t_20mhz_prepare_bufs);
break;
case VA1J5JF8007T_25MHZ:
bufs = va1j5jf8007t_25mhz_prepare_bufs;
size = ARRAY_SIZE(va1j5jf8007t_25mhz_prepare_bufs);
break;
default:
return -EINVAL;
}
msg.addr = state->config->demod_address;
msg.flags = 0;
msg.len = sizeof(buf);
msg.buf = buf;
for (i = 0; i < size; i++) {
memcpy(buf, bufs[i], sizeof(buf));
if (i2c_transfer(state->adap, &msg, 1) != 1)
return -EREMOTEIO;
}
return va1j5jf8007t_init_frequency(state);
}
struct dvb_frontend *
va1j5jf8007t_attach(const struct va1j5jf8007t_config *config,
struct i2c_adapter *adap)
{
struct va1j5jf8007t_state *state;
struct dvb_frontend *fe;
u8 buf[2];
struct i2c_msg msg;
state = kzalloc(sizeof(struct va1j5jf8007t_state), GFP_KERNEL);
if (!state)
return NULL;
state->config = config;
state->adap = adap;
fe = &state->fe;
memcpy(&fe->ops, &va1j5jf8007t_ops, sizeof(struct dvb_frontend_ops));
fe->demodulator_priv = state;
buf[0] = 0x01;
buf[1] = 0x80;
msg.addr = state->config->demod_address;
msg.flags = 0;
msg.len = sizeof(buf);
msg.buf = buf;
if (i2c_transfer(state->adap, &msg, 1) != 1) {
kfree(state);
return NULL;
}
return fe;
}
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.