repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
xiaowei942/kernel_2.6.36_t21 | sound/soc/codecs/tlv320aic26.c | 831 | 14779 | /*
* Texas Instruments TLV320AIC26 low power audio CODEC
* ALSA SoC CODEC driver
*
* Copyright (C) 2008 Secret Lab Technologies Ltd.
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/pm.h>
#include <linux/device.h>
#include <linux/sysfs.h>
#include <linux/spi/spi.h>
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include <sound/soc-dapm.h>
#include <sound/soc-of-simple.h>
#include <sound/initval.h>
#include "tlv320aic26.h"
MODULE_DESCRIPTION("ASoC TLV320AIC26 codec driver");
MODULE_AUTHOR("Grant Likely <grant.likely@secretlab.ca>");
MODULE_LICENSE("GPL");
/* AIC26 driver private data */
struct aic26 {
struct spi_device *spi;
struct snd_soc_codec codec;
u16 reg_cache[AIC26_NUM_REGS]; /* shadow registers */
int master;
int datfm;
int mclk;
/* Keyclick parameters */
int keyclick_amplitude;
int keyclick_freq;
int keyclick_len;
};
/* ---------------------------------------------------------------------
* Register access routines
*/
static unsigned int aic26_reg_read(struct snd_soc_codec *codec,
unsigned int reg)
{
struct aic26 *aic26 = snd_soc_codec_get_drvdata(codec);
u16 *cache = codec->reg_cache;
u16 cmd, value;
u8 buffer[2];
int rc;
if (reg >= AIC26_NUM_REGS) {
WARN_ON_ONCE(1);
return 0;
}
/* Do SPI transfer; first 16bits are command; remaining is
* register contents */
cmd = AIC26_READ_COMMAND_WORD(reg);
buffer[0] = (cmd >> 8) & 0xff;
buffer[1] = cmd & 0xff;
rc = spi_write_then_read(aic26->spi, buffer, 2, buffer, 2);
if (rc) {
dev_err(&aic26->spi->dev, "AIC26 reg read error\n");
return -EIO;
}
value = (buffer[0] << 8) | buffer[1];
/* Update the cache before returning with the value */
cache[reg] = value;
return value;
}
static unsigned int aic26_reg_read_cache(struct snd_soc_codec *codec,
unsigned int reg)
{
u16 *cache = codec->reg_cache;
if (reg >= AIC26_NUM_REGS) {
WARN_ON_ONCE(1);
return 0;
}
return cache[reg];
}
static int aic26_reg_write(struct snd_soc_codec *codec, unsigned int reg,
unsigned int value)
{
struct aic26 *aic26 = snd_soc_codec_get_drvdata(codec);
u16 *cache = codec->reg_cache;
u16 cmd;
u8 buffer[4];
int rc;
if (reg >= AIC26_NUM_REGS) {
WARN_ON_ONCE(1);
return -EINVAL;
}
/* Do SPI transfer; first 16bits are command; remaining is data
* to write into register */
cmd = AIC26_WRITE_COMMAND_WORD(reg);
buffer[0] = (cmd >> 8) & 0xff;
buffer[1] = cmd & 0xff;
buffer[2] = value >> 8;
buffer[3] = value;
rc = spi_write(aic26->spi, buffer, 4);
if (rc) {
dev_err(&aic26->spi->dev, "AIC26 reg read error\n");
return -EIO;
}
/* update cache before returning */
cache[reg] = value;
return 0;
}
/* ---------------------------------------------------------------------
* Digital Audio Interface Operations
*/
static int aic26_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_device *socdev = rtd->socdev;
struct snd_soc_codec *codec = socdev->card->codec;
struct aic26 *aic26 = snd_soc_codec_get_drvdata(codec);
int fsref, divisor, wlen, pval, jval, dval, qval;
u16 reg;
dev_dbg(&aic26->spi->dev, "aic26_hw_params(substream=%p, params=%p)\n",
substream, params);
dev_dbg(&aic26->spi->dev, "rate=%i format=%i\n", params_rate(params),
params_format(params));
switch (params_rate(params)) {
case 8000: fsref = 48000; divisor = AIC26_DIV_6; break;
case 11025: fsref = 44100; divisor = AIC26_DIV_4; break;
case 12000: fsref = 48000; divisor = AIC26_DIV_4; break;
case 16000: fsref = 48000; divisor = AIC26_DIV_3; break;
case 22050: fsref = 44100; divisor = AIC26_DIV_2; break;
case 24000: fsref = 48000; divisor = AIC26_DIV_2; break;
case 32000: fsref = 48000; divisor = AIC26_DIV_1_5; break;
case 44100: fsref = 44100; divisor = AIC26_DIV_1; break;
case 48000: fsref = 48000; divisor = AIC26_DIV_1; break;
default:
dev_dbg(&aic26->spi->dev, "bad rate\n"); return -EINVAL;
}
/* select data word length */
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S8: wlen = AIC26_WLEN_16; break;
case SNDRV_PCM_FORMAT_S16_BE: wlen = AIC26_WLEN_16; break;
case SNDRV_PCM_FORMAT_S24_BE: wlen = AIC26_WLEN_24; break;
case SNDRV_PCM_FORMAT_S32_BE: wlen = AIC26_WLEN_32; break;
default:
dev_dbg(&aic26->spi->dev, "bad format\n"); return -EINVAL;
}
/* Configure PLL */
pval = 1;
jval = (fsref == 44100) ? 7 : 8;
dval = (fsref == 44100) ? 5264 : 1920;
qval = 0;
reg = 0x8000 | qval << 11 | pval << 8 | jval << 2;
aic26_reg_write(codec, AIC26_REG_PLL_PROG1, reg);
reg = dval << 2;
aic26_reg_write(codec, AIC26_REG_PLL_PROG2, reg);
/* Audio Control 3 (master mode, fsref rate) */
reg = aic26_reg_read_cache(codec, AIC26_REG_AUDIO_CTRL3);
reg &= ~0xf800;
if (aic26->master)
reg |= 0x0800;
if (fsref == 48000)
reg |= 0x2000;
aic26_reg_write(codec, AIC26_REG_AUDIO_CTRL3, reg);
/* Audio Control 1 (FSref divisor) */
reg = aic26_reg_read_cache(codec, AIC26_REG_AUDIO_CTRL1);
reg &= ~0x0fff;
reg |= wlen | aic26->datfm | (divisor << 3) | divisor;
aic26_reg_write(codec, AIC26_REG_AUDIO_CTRL1, reg);
return 0;
}
/**
* aic26_mute - Mute control to reduce noise when changing audio format
*/
static int aic26_mute(struct snd_soc_dai *dai, int mute)
{
struct snd_soc_codec *codec = dai->codec;
struct aic26 *aic26 = snd_soc_codec_get_drvdata(codec);
u16 reg = aic26_reg_read_cache(codec, AIC26_REG_DAC_GAIN);
dev_dbg(&aic26->spi->dev, "aic26_mute(dai=%p, mute=%i)\n",
dai, mute);
if (mute)
reg |= 0x8080;
else
reg &= ~0x8080;
aic26_reg_write(codec, AIC26_REG_DAC_GAIN, reg);
return 0;
}
static int aic26_set_sysclk(struct snd_soc_dai *codec_dai,
int clk_id, unsigned int freq, int dir)
{
struct snd_soc_codec *codec = codec_dai->codec;
struct aic26 *aic26 = snd_soc_codec_get_drvdata(codec);
dev_dbg(&aic26->spi->dev, "aic26_set_sysclk(dai=%p, clk_id==%i,"
" freq=%i, dir=%i)\n",
codec_dai, clk_id, freq, dir);
/* MCLK needs to fall between 2MHz and 50 MHz */
if ((freq < 2000000) || (freq > 50000000))
return -EINVAL;
aic26->mclk = freq;
return 0;
}
static int aic26_set_fmt(struct snd_soc_dai *codec_dai, unsigned int fmt)
{
struct snd_soc_codec *codec = codec_dai->codec;
struct aic26 *aic26 = snd_soc_codec_get_drvdata(codec);
dev_dbg(&aic26->spi->dev, "aic26_set_fmt(dai=%p, fmt==%i)\n",
codec_dai, fmt);
/* set master/slave audio interface */
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBM_CFM: aic26->master = 1; break;
case SND_SOC_DAIFMT_CBS_CFS: aic26->master = 0; break;
default:
dev_dbg(&aic26->spi->dev, "bad master\n"); return -EINVAL;
}
/* interface format */
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_I2S: aic26->datfm = AIC26_DATFM_I2S; break;
case SND_SOC_DAIFMT_DSP_A: aic26->datfm = AIC26_DATFM_DSP; break;
case SND_SOC_DAIFMT_RIGHT_J: aic26->datfm = AIC26_DATFM_RIGHTJ; break;
case SND_SOC_DAIFMT_LEFT_J: aic26->datfm = AIC26_DATFM_LEFTJ; break;
default:
dev_dbg(&aic26->spi->dev, "bad format\n"); return -EINVAL;
}
return 0;
}
/* ---------------------------------------------------------------------
* Digital Audio Interface Definition
*/
#define AIC26_RATES (SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_11025 |\
SNDRV_PCM_RATE_16000 | SNDRV_PCM_RATE_22050 |\
SNDRV_PCM_RATE_32000 | SNDRV_PCM_RATE_44100 |\
SNDRV_PCM_RATE_48000)
#define AIC26_FORMATS (SNDRV_PCM_FMTBIT_S8 | SNDRV_PCM_FMTBIT_S16_BE |\
SNDRV_PCM_FMTBIT_S24_BE | SNDRV_PCM_FMTBIT_S32_BE)
static struct snd_soc_dai_ops aic26_dai_ops = {
.hw_params = aic26_hw_params,
.digital_mute = aic26_mute,
.set_sysclk = aic26_set_sysclk,
.set_fmt = aic26_set_fmt,
};
struct snd_soc_dai aic26_dai = {
.name = "tlv320aic26",
.playback = {
.stream_name = "Playback",
.channels_min = 2,
.channels_max = 2,
.rates = AIC26_RATES,
.formats = AIC26_FORMATS,
},
.capture = {
.stream_name = "Capture",
.channels_min = 2,
.channels_max = 2,
.rates = AIC26_RATES,
.formats = AIC26_FORMATS,
},
.ops = &aic26_dai_ops,
};
EXPORT_SYMBOL_GPL(aic26_dai);
/* ---------------------------------------------------------------------
* ALSA controls
*/
static const char *aic26_capture_src_text[] = {"Mic", "Aux"};
static const struct soc_enum aic26_capture_src_enum =
SOC_ENUM_SINGLE(AIC26_REG_AUDIO_CTRL1, 12, 2, aic26_capture_src_text);
static const struct snd_kcontrol_new aic26_snd_controls[] = {
/* Output */
SOC_DOUBLE("PCM Playback Volume", AIC26_REG_DAC_GAIN, 8, 0, 0x7f, 1),
SOC_DOUBLE("PCM Playback Switch", AIC26_REG_DAC_GAIN, 15, 7, 1, 1),
SOC_SINGLE("PCM Capture Volume", AIC26_REG_ADC_GAIN, 8, 0x7f, 0),
SOC_SINGLE("PCM Capture Mute", AIC26_REG_ADC_GAIN, 15, 1, 1),
SOC_SINGLE("Keyclick activate", AIC26_REG_AUDIO_CTRL2, 15, 0x1, 0),
SOC_SINGLE("Keyclick amplitude", AIC26_REG_AUDIO_CTRL2, 12, 0x7, 0),
SOC_SINGLE("Keyclick frequency", AIC26_REG_AUDIO_CTRL2, 8, 0x7, 0),
SOC_SINGLE("Keyclick period", AIC26_REG_AUDIO_CTRL2, 4, 0xf, 0),
SOC_ENUM("Capture Source", aic26_capture_src_enum),
};
/* ---------------------------------------------------------------------
* SoC CODEC portion of driver: probe and release routines
*/
static int aic26_probe(struct platform_device *pdev)
{
struct snd_soc_device *socdev = platform_get_drvdata(pdev);
struct snd_soc_codec *codec;
struct aic26 *aic26;
int ret, err;
dev_info(&pdev->dev, "Probing AIC26 SoC CODEC driver\n");
dev_dbg(&pdev->dev, "socdev=%p\n", socdev);
dev_dbg(&pdev->dev, "codec_data=%p\n", socdev->codec_data);
/* Fetch the relevant aic26 private data here (it's already been
* stored in the .codec pointer) */
aic26 = socdev->codec_data;
if (aic26 == NULL) {
dev_err(&pdev->dev, "aic26: missing codec pointer\n");
return -ENODEV;
}
codec = &aic26->codec;
socdev->card->codec = codec;
dev_dbg(&pdev->dev, "Registering PCMs, dev=%p, socdev->dev=%p\n",
&pdev->dev, socdev->dev);
/* register pcms */
ret = snd_soc_new_pcms(socdev, SNDRV_DEFAULT_IDX1, SNDRV_DEFAULT_STR1);
if (ret < 0) {
dev_err(&pdev->dev, "aic26: failed to create pcms\n");
return -ENODEV;
}
/* register controls */
dev_dbg(&pdev->dev, "Registering controls\n");
err = snd_soc_add_controls(codec, aic26_snd_controls,
ARRAY_SIZE(aic26_snd_controls));
WARN_ON(err < 0);
return 0;
}
static int aic26_remove(struct platform_device *pdev)
{
struct snd_soc_device *socdev = platform_get_drvdata(pdev);
snd_soc_free_pcms(socdev);
return 0;
}
struct snd_soc_codec_device aic26_soc_codec_dev = {
.probe = aic26_probe,
.remove = aic26_remove,
};
EXPORT_SYMBOL_GPL(aic26_soc_codec_dev);
/* ---------------------------------------------------------------------
* SPI device portion of driver: sysfs files for debugging
*/
static ssize_t aic26_keyclick_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct aic26 *aic26 = dev_get_drvdata(dev);
int val, amp, freq, len;
val = aic26_reg_read_cache(&aic26->codec, AIC26_REG_AUDIO_CTRL2);
amp = (val >> 12) & 0x7;
freq = (125 << ((val >> 8) & 0x7)) >> 1;
len = 2 * (1 + ((val >> 4) & 0xf));
return sprintf(buf, "amp=%x freq=%iHz len=%iclks\n", amp, freq, len);
}
/* Any write to the keyclick attribute will trigger the keyclick event */
static ssize_t aic26_keyclick_set(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct aic26 *aic26 = dev_get_drvdata(dev);
int val;
val = aic26_reg_read_cache(&aic26->codec, AIC26_REG_AUDIO_CTRL2);
val |= 0x8000;
aic26_reg_write(&aic26->codec, AIC26_REG_AUDIO_CTRL2, val);
return count;
}
static DEVICE_ATTR(keyclick, 0644, aic26_keyclick_show, aic26_keyclick_set);
/* ---------------------------------------------------------------------
* SPI device portion of driver: probe and release routines and SPI
* driver registration.
*/
static int aic26_spi_probe(struct spi_device *spi)
{
struct aic26 *aic26;
int ret, i, reg;
dev_dbg(&spi->dev, "probing tlv320aic26 spi device\n");
/* Allocate driver data */
aic26 = kzalloc(sizeof *aic26, GFP_KERNEL);
if (!aic26)
return -ENOMEM;
/* Initialize the driver data */
aic26->spi = spi;
dev_set_drvdata(&spi->dev, aic26);
/* Setup what we can in the codec structure so that the register
* access functions will work as expected. More will be filled
* out when it is probed by the SoC CODEC part of this driver */
snd_soc_codec_set_drvdata(&aic26->codec, aic26);
aic26->codec.name = "aic26";
aic26->codec.owner = THIS_MODULE;
aic26->codec.dai = &aic26_dai;
aic26->codec.num_dai = 1;
aic26->codec.read = aic26_reg_read;
aic26->codec.write = aic26_reg_write;
aic26->master = 1;
mutex_init(&aic26->codec.mutex);
INIT_LIST_HEAD(&aic26->codec.dapm_widgets);
INIT_LIST_HEAD(&aic26->codec.dapm_paths);
aic26->codec.reg_cache_size = AIC26_NUM_REGS;
aic26->codec.reg_cache = aic26->reg_cache;
aic26_dai.dev = &spi->dev;
ret = snd_soc_register_dai(&aic26_dai);
if (ret != 0) {
dev_err(&spi->dev, "Failed to register DAI: %d\n", ret);
kfree(aic26);
return ret;
}
/* Reset the codec to power on defaults */
aic26_reg_write(&aic26->codec, AIC26_REG_RESET, 0xBB00);
/* Power up CODEC */
aic26_reg_write(&aic26->codec, AIC26_REG_POWER_CTRL, 0);
/* Audio Control 3 (master mode, fsref rate) */
reg = aic26_reg_read(&aic26->codec, AIC26_REG_AUDIO_CTRL3);
reg &= ~0xf800;
reg |= 0x0800; /* set master mode */
aic26_reg_write(&aic26->codec, AIC26_REG_AUDIO_CTRL3, reg);
/* Fill register cache */
for (i = 0; i < ARRAY_SIZE(aic26->reg_cache); i++)
aic26_reg_read(&aic26->codec, i);
/* Register the sysfs files for debugging */
/* Create SysFS files */
ret = device_create_file(&spi->dev, &dev_attr_keyclick);
if (ret)
dev_info(&spi->dev, "error creating sysfs files\n");
#if defined(CONFIG_SND_SOC_OF_SIMPLE)
/* Tell the of_soc helper about this codec */
of_snd_soc_register_codec(&aic26_soc_codec_dev, aic26, &aic26_dai,
spi->dev.archdata.of_node);
#endif
dev_dbg(&spi->dev, "SPI device initialized\n");
return 0;
}
static int aic26_spi_remove(struct spi_device *spi)
{
struct aic26 *aic26 = dev_get_drvdata(&spi->dev);
snd_soc_unregister_dai(&aic26_dai);
kfree(aic26);
return 0;
}
static struct spi_driver aic26_spi = {
.driver = {
.name = "tlv320aic26",
.owner = THIS_MODULE,
},
.probe = aic26_spi_probe,
.remove = aic26_spi_remove,
};
static int __init aic26_init(void)
{
return spi_register_driver(&aic26_spi);
}
module_init(aic26_init);
static void __exit aic26_exit(void)
{
spi_unregister_driver(&aic26_spi);
}
module_exit(aic26_exit);
| gpl-2.0 |
AndroidDeveloperAlliance/ZenKernel_TUNA | drivers/net/enic/enic_main.c | 1855 | 61084 | /*
* Copyright 2008-2010 Cisco Systems, Inc. All rights reserved.
* Copyright 2007 Nuova Systems, Inc. All rights reserved.
*
* This program is free software; you may 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.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/workqueue.h>
#include <linux/pci.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/if_ether.h>
#include <linux/if_vlan.h>
#include <linux/ethtool.h>
#include <linux/in.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <linux/tcp.h>
#include <linux/rtnetlink.h>
#include <linux/prefetch.h>
#include <net/ip6_checksum.h>
#include "cq_enet_desc.h"
#include "vnic_dev.h"
#include "vnic_intr.h"
#include "vnic_stats.h"
#include "vnic_vic.h"
#include "enic_res.h"
#include "enic.h"
#include "enic_dev.h"
#include "enic_pp.h"
#define ENIC_NOTIFY_TIMER_PERIOD (2 * HZ)
#define WQ_ENET_MAX_DESC_LEN (1 << WQ_ENET_LEN_BITS)
#define MAX_TSO (1 << 16)
#define ENIC_DESC_MAX_SPLITS (MAX_TSO / WQ_ENET_MAX_DESC_LEN + 1)
#define PCI_DEVICE_ID_CISCO_VIC_ENET 0x0043 /* ethernet vnic */
#define PCI_DEVICE_ID_CISCO_VIC_ENET_DYN 0x0044 /* enet dynamic vnic */
/* Supported devices */
static DEFINE_PCI_DEVICE_TABLE(enic_id_table) = {
{ PCI_VDEVICE(CISCO, PCI_DEVICE_ID_CISCO_VIC_ENET) },
{ PCI_VDEVICE(CISCO, PCI_DEVICE_ID_CISCO_VIC_ENET_DYN) },
{ 0, } /* end of table */
};
MODULE_DESCRIPTION(DRV_DESCRIPTION);
MODULE_AUTHOR("Scott Feldman <scofeldm@cisco.com>");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);
MODULE_DEVICE_TABLE(pci, enic_id_table);
struct enic_stat {
char name[ETH_GSTRING_LEN];
unsigned int offset;
};
#define ENIC_TX_STAT(stat) \
{ .name = #stat, .offset = offsetof(struct vnic_tx_stats, stat) / 8 }
#define ENIC_RX_STAT(stat) \
{ .name = #stat, .offset = offsetof(struct vnic_rx_stats, stat) / 8 }
static const struct enic_stat enic_tx_stats[] = {
ENIC_TX_STAT(tx_frames_ok),
ENIC_TX_STAT(tx_unicast_frames_ok),
ENIC_TX_STAT(tx_multicast_frames_ok),
ENIC_TX_STAT(tx_broadcast_frames_ok),
ENIC_TX_STAT(tx_bytes_ok),
ENIC_TX_STAT(tx_unicast_bytes_ok),
ENIC_TX_STAT(tx_multicast_bytes_ok),
ENIC_TX_STAT(tx_broadcast_bytes_ok),
ENIC_TX_STAT(tx_drops),
ENIC_TX_STAT(tx_errors),
ENIC_TX_STAT(tx_tso),
};
static const struct enic_stat enic_rx_stats[] = {
ENIC_RX_STAT(rx_frames_ok),
ENIC_RX_STAT(rx_frames_total),
ENIC_RX_STAT(rx_unicast_frames_ok),
ENIC_RX_STAT(rx_multicast_frames_ok),
ENIC_RX_STAT(rx_broadcast_frames_ok),
ENIC_RX_STAT(rx_bytes_ok),
ENIC_RX_STAT(rx_unicast_bytes_ok),
ENIC_RX_STAT(rx_multicast_bytes_ok),
ENIC_RX_STAT(rx_broadcast_bytes_ok),
ENIC_RX_STAT(rx_drop),
ENIC_RX_STAT(rx_no_bufs),
ENIC_RX_STAT(rx_errors),
ENIC_RX_STAT(rx_rss),
ENIC_RX_STAT(rx_crc_errors),
ENIC_RX_STAT(rx_frames_64),
ENIC_RX_STAT(rx_frames_127),
ENIC_RX_STAT(rx_frames_255),
ENIC_RX_STAT(rx_frames_511),
ENIC_RX_STAT(rx_frames_1023),
ENIC_RX_STAT(rx_frames_1518),
ENIC_RX_STAT(rx_frames_to_max),
};
static const unsigned int enic_n_tx_stats = ARRAY_SIZE(enic_tx_stats);
static const unsigned int enic_n_rx_stats = ARRAY_SIZE(enic_rx_stats);
static int enic_is_dynamic(struct enic *enic)
{
return enic->pdev->device == PCI_DEVICE_ID_CISCO_VIC_ENET_DYN;
}
static inline unsigned int enic_cq_rq(struct enic *enic, unsigned int rq)
{
return rq;
}
static inline unsigned int enic_cq_wq(struct enic *enic, unsigned int wq)
{
return enic->rq_count + wq;
}
static inline unsigned int enic_legacy_io_intr(void)
{
return 0;
}
static inline unsigned int enic_legacy_err_intr(void)
{
return 1;
}
static inline unsigned int enic_legacy_notify_intr(void)
{
return 2;
}
static inline unsigned int enic_msix_rq_intr(struct enic *enic, unsigned int rq)
{
return rq;
}
static inline unsigned int enic_msix_wq_intr(struct enic *enic, unsigned int wq)
{
return enic->rq_count + wq;
}
static inline unsigned int enic_msix_err_intr(struct enic *enic)
{
return enic->rq_count + enic->wq_count;
}
static inline unsigned int enic_msix_notify_intr(struct enic *enic)
{
return enic->rq_count + enic->wq_count + 1;
}
static int enic_get_settings(struct net_device *netdev,
struct ethtool_cmd *ecmd)
{
struct enic *enic = netdev_priv(netdev);
ecmd->supported = (SUPPORTED_10000baseT_Full | SUPPORTED_FIBRE);
ecmd->advertising = (ADVERTISED_10000baseT_Full | ADVERTISED_FIBRE);
ecmd->port = PORT_FIBRE;
ecmd->transceiver = XCVR_EXTERNAL;
if (netif_carrier_ok(netdev)) {
ethtool_cmd_speed_set(ecmd, vnic_dev_port_speed(enic->vdev));
ecmd->duplex = DUPLEX_FULL;
} else {
ethtool_cmd_speed_set(ecmd, -1);
ecmd->duplex = -1;
}
ecmd->autoneg = AUTONEG_DISABLE;
return 0;
}
static void enic_get_drvinfo(struct net_device *netdev,
struct ethtool_drvinfo *drvinfo)
{
struct enic *enic = netdev_priv(netdev);
struct vnic_devcmd_fw_info *fw_info;
enic_dev_fw_info(enic, &fw_info);
strncpy(drvinfo->driver, DRV_NAME, sizeof(drvinfo->driver));
strncpy(drvinfo->version, DRV_VERSION, sizeof(drvinfo->version));
strncpy(drvinfo->fw_version, fw_info->fw_version,
sizeof(drvinfo->fw_version));
strncpy(drvinfo->bus_info, pci_name(enic->pdev),
sizeof(drvinfo->bus_info));
}
static void enic_get_strings(struct net_device *netdev, u32 stringset, u8 *data)
{
unsigned int i;
switch (stringset) {
case ETH_SS_STATS:
for (i = 0; i < enic_n_tx_stats; i++) {
memcpy(data, enic_tx_stats[i].name, ETH_GSTRING_LEN);
data += ETH_GSTRING_LEN;
}
for (i = 0; i < enic_n_rx_stats; i++) {
memcpy(data, enic_rx_stats[i].name, ETH_GSTRING_LEN);
data += ETH_GSTRING_LEN;
}
break;
}
}
static int enic_get_sset_count(struct net_device *netdev, int sset)
{
switch (sset) {
case ETH_SS_STATS:
return enic_n_tx_stats + enic_n_rx_stats;
default:
return -EOPNOTSUPP;
}
}
static void enic_get_ethtool_stats(struct net_device *netdev,
struct ethtool_stats *stats, u64 *data)
{
struct enic *enic = netdev_priv(netdev);
struct vnic_stats *vstats;
unsigned int i;
enic_dev_stats_dump(enic, &vstats);
for (i = 0; i < enic_n_tx_stats; i++)
*(data++) = ((u64 *)&vstats->tx)[enic_tx_stats[i].offset];
for (i = 0; i < enic_n_rx_stats; i++)
*(data++) = ((u64 *)&vstats->rx)[enic_rx_stats[i].offset];
}
static u32 enic_get_msglevel(struct net_device *netdev)
{
struct enic *enic = netdev_priv(netdev);
return enic->msg_enable;
}
static void enic_set_msglevel(struct net_device *netdev, u32 value)
{
struct enic *enic = netdev_priv(netdev);
enic->msg_enable = value;
}
static int enic_get_coalesce(struct net_device *netdev,
struct ethtool_coalesce *ecmd)
{
struct enic *enic = netdev_priv(netdev);
ecmd->tx_coalesce_usecs = enic->tx_coalesce_usecs;
ecmd->rx_coalesce_usecs = enic->rx_coalesce_usecs;
return 0;
}
static int enic_set_coalesce(struct net_device *netdev,
struct ethtool_coalesce *ecmd)
{
struct enic *enic = netdev_priv(netdev);
u32 tx_coalesce_usecs;
u32 rx_coalesce_usecs;
unsigned int i, intr;
tx_coalesce_usecs = min_t(u32,
INTR_COALESCE_HW_TO_USEC(VNIC_INTR_TIMER_MAX),
ecmd->tx_coalesce_usecs);
rx_coalesce_usecs = min_t(u32,
INTR_COALESCE_HW_TO_USEC(VNIC_INTR_TIMER_MAX),
ecmd->rx_coalesce_usecs);
switch (vnic_dev_get_intr_mode(enic->vdev)) {
case VNIC_DEV_INTR_MODE_INTX:
if (tx_coalesce_usecs != rx_coalesce_usecs)
return -EINVAL;
intr = enic_legacy_io_intr();
vnic_intr_coalescing_timer_set(&enic->intr[intr],
INTR_COALESCE_USEC_TO_HW(tx_coalesce_usecs));
break;
case VNIC_DEV_INTR_MODE_MSI:
if (tx_coalesce_usecs != rx_coalesce_usecs)
return -EINVAL;
vnic_intr_coalescing_timer_set(&enic->intr[0],
INTR_COALESCE_USEC_TO_HW(tx_coalesce_usecs));
break;
case VNIC_DEV_INTR_MODE_MSIX:
for (i = 0; i < enic->wq_count; i++) {
intr = enic_msix_wq_intr(enic, i);
vnic_intr_coalescing_timer_set(&enic->intr[intr],
INTR_COALESCE_USEC_TO_HW(tx_coalesce_usecs));
}
for (i = 0; i < enic->rq_count; i++) {
intr = enic_msix_rq_intr(enic, i);
vnic_intr_coalescing_timer_set(&enic->intr[intr],
INTR_COALESCE_USEC_TO_HW(rx_coalesce_usecs));
}
break;
default:
break;
}
enic->tx_coalesce_usecs = tx_coalesce_usecs;
enic->rx_coalesce_usecs = rx_coalesce_usecs;
return 0;
}
static const struct ethtool_ops enic_ethtool_ops = {
.get_settings = enic_get_settings,
.get_drvinfo = enic_get_drvinfo,
.get_msglevel = enic_get_msglevel,
.set_msglevel = enic_set_msglevel,
.get_link = ethtool_op_get_link,
.get_strings = enic_get_strings,
.get_sset_count = enic_get_sset_count,
.get_ethtool_stats = enic_get_ethtool_stats,
.get_coalesce = enic_get_coalesce,
.set_coalesce = enic_set_coalesce,
};
static void enic_free_wq_buf(struct vnic_wq *wq, struct vnic_wq_buf *buf)
{
struct enic *enic = vnic_dev_priv(wq->vdev);
if (buf->sop)
pci_unmap_single(enic->pdev, buf->dma_addr,
buf->len, PCI_DMA_TODEVICE);
else
pci_unmap_page(enic->pdev, buf->dma_addr,
buf->len, PCI_DMA_TODEVICE);
if (buf->os_buf)
dev_kfree_skb_any(buf->os_buf);
}
static void enic_wq_free_buf(struct vnic_wq *wq,
struct cq_desc *cq_desc, struct vnic_wq_buf *buf, void *opaque)
{
enic_free_wq_buf(wq, buf);
}
static int enic_wq_service(struct vnic_dev *vdev, struct cq_desc *cq_desc,
u8 type, u16 q_number, u16 completed_index, void *opaque)
{
struct enic *enic = vnic_dev_priv(vdev);
spin_lock(&enic->wq_lock[q_number]);
vnic_wq_service(&enic->wq[q_number], cq_desc,
completed_index, enic_wq_free_buf,
opaque);
if (netif_queue_stopped(enic->netdev) &&
vnic_wq_desc_avail(&enic->wq[q_number]) >=
(MAX_SKB_FRAGS + ENIC_DESC_MAX_SPLITS))
netif_wake_queue(enic->netdev);
spin_unlock(&enic->wq_lock[q_number]);
return 0;
}
static void enic_log_q_error(struct enic *enic)
{
unsigned int i;
u32 error_status;
for (i = 0; i < enic->wq_count; i++) {
error_status = vnic_wq_error_status(&enic->wq[i]);
if (error_status)
netdev_err(enic->netdev, "WQ[%d] error_status %d\n",
i, error_status);
}
for (i = 0; i < enic->rq_count; i++) {
error_status = vnic_rq_error_status(&enic->rq[i]);
if (error_status)
netdev_err(enic->netdev, "RQ[%d] error_status %d\n",
i, error_status);
}
}
static void enic_msglvl_check(struct enic *enic)
{
u32 msg_enable = vnic_dev_msg_lvl(enic->vdev);
if (msg_enable != enic->msg_enable) {
netdev_info(enic->netdev, "msg lvl changed from 0x%x to 0x%x\n",
enic->msg_enable, msg_enable);
enic->msg_enable = msg_enable;
}
}
static void enic_mtu_check(struct enic *enic)
{
u32 mtu = vnic_dev_mtu(enic->vdev);
struct net_device *netdev = enic->netdev;
if (mtu && mtu != enic->port_mtu) {
enic->port_mtu = mtu;
if (mtu < netdev->mtu)
netdev_warn(netdev,
"interface MTU (%d) set higher "
"than switch port MTU (%d)\n",
netdev->mtu, mtu);
}
}
static void enic_link_check(struct enic *enic)
{
int link_status = vnic_dev_link_status(enic->vdev);
int carrier_ok = netif_carrier_ok(enic->netdev);
if (link_status && !carrier_ok) {
netdev_info(enic->netdev, "Link UP\n");
netif_carrier_on(enic->netdev);
} else if (!link_status && carrier_ok) {
netdev_info(enic->netdev, "Link DOWN\n");
netif_carrier_off(enic->netdev);
}
}
static void enic_notify_check(struct enic *enic)
{
enic_msglvl_check(enic);
enic_mtu_check(enic);
enic_link_check(enic);
}
#define ENIC_TEST_INTR(pba, i) (pba & (1 << i))
static irqreturn_t enic_isr_legacy(int irq, void *data)
{
struct net_device *netdev = data;
struct enic *enic = netdev_priv(netdev);
unsigned int io_intr = enic_legacy_io_intr();
unsigned int err_intr = enic_legacy_err_intr();
unsigned int notify_intr = enic_legacy_notify_intr();
u32 pba;
vnic_intr_mask(&enic->intr[io_intr]);
pba = vnic_intr_legacy_pba(enic->legacy_pba);
if (!pba) {
vnic_intr_unmask(&enic->intr[io_intr]);
return IRQ_NONE; /* not our interrupt */
}
if (ENIC_TEST_INTR(pba, notify_intr)) {
vnic_intr_return_all_credits(&enic->intr[notify_intr]);
enic_notify_check(enic);
}
if (ENIC_TEST_INTR(pba, err_intr)) {
vnic_intr_return_all_credits(&enic->intr[err_intr]);
enic_log_q_error(enic);
/* schedule recovery from WQ/RQ error */
schedule_work(&enic->reset);
return IRQ_HANDLED;
}
if (ENIC_TEST_INTR(pba, io_intr)) {
if (napi_schedule_prep(&enic->napi[0]))
__napi_schedule(&enic->napi[0]);
} else {
vnic_intr_unmask(&enic->intr[io_intr]);
}
return IRQ_HANDLED;
}
static irqreturn_t enic_isr_msi(int irq, void *data)
{
struct enic *enic = data;
/* With MSI, there is no sharing of interrupts, so this is
* our interrupt and there is no need to ack it. The device
* is not providing per-vector masking, so the OS will not
* write to PCI config space to mask/unmask the interrupt.
* We're using mask_on_assertion for MSI, so the device
* automatically masks the interrupt when the interrupt is
* generated. Later, when exiting polling, the interrupt
* will be unmasked (see enic_poll).
*
* Also, the device uses the same PCIe Traffic Class (TC)
* for Memory Write data and MSI, so there are no ordering
* issues; the MSI will always arrive at the Root Complex
* _after_ corresponding Memory Writes (i.e. descriptor
* writes).
*/
napi_schedule(&enic->napi[0]);
return IRQ_HANDLED;
}
static irqreturn_t enic_isr_msix_rq(int irq, void *data)
{
struct napi_struct *napi = data;
/* schedule NAPI polling for RQ cleanup */
napi_schedule(napi);
return IRQ_HANDLED;
}
static irqreturn_t enic_isr_msix_wq(int irq, void *data)
{
struct enic *enic = data;
unsigned int cq = enic_cq_wq(enic, 0);
unsigned int intr = enic_msix_wq_intr(enic, 0);
unsigned int wq_work_to_do = -1; /* no limit */
unsigned int wq_work_done;
wq_work_done = vnic_cq_service(&enic->cq[cq],
wq_work_to_do, enic_wq_service, NULL);
vnic_intr_return_credits(&enic->intr[intr],
wq_work_done,
1 /* unmask intr */,
1 /* reset intr timer */);
return IRQ_HANDLED;
}
static irqreturn_t enic_isr_msix_err(int irq, void *data)
{
struct enic *enic = data;
unsigned int intr = enic_msix_err_intr(enic);
vnic_intr_return_all_credits(&enic->intr[intr]);
enic_log_q_error(enic);
/* schedule recovery from WQ/RQ error */
schedule_work(&enic->reset);
return IRQ_HANDLED;
}
static irqreturn_t enic_isr_msix_notify(int irq, void *data)
{
struct enic *enic = data;
unsigned int intr = enic_msix_notify_intr(enic);
vnic_intr_return_all_credits(&enic->intr[intr]);
enic_notify_check(enic);
return IRQ_HANDLED;
}
static inline void enic_queue_wq_skb_cont(struct enic *enic,
struct vnic_wq *wq, struct sk_buff *skb,
unsigned int len_left, int loopback)
{
skb_frag_t *frag;
/* Queue additional data fragments */
for (frag = skb_shinfo(skb)->frags; len_left; frag++) {
len_left -= frag->size;
enic_queue_wq_desc_cont(wq, skb,
pci_map_page(enic->pdev, frag->page,
frag->page_offset, frag->size,
PCI_DMA_TODEVICE),
frag->size,
(len_left == 0), /* EOP? */
loopback);
}
}
static inline void enic_queue_wq_skb_vlan(struct enic *enic,
struct vnic_wq *wq, struct sk_buff *skb,
int vlan_tag_insert, unsigned int vlan_tag, int loopback)
{
unsigned int head_len = skb_headlen(skb);
unsigned int len_left = skb->len - head_len;
int eop = (len_left == 0);
/* Queue the main skb fragment. The fragments are no larger
* than max MTU(9000)+ETH_HDR_LEN(14) bytes, which is less
* than WQ_ENET_MAX_DESC_LEN length. So only one descriptor
* per fragment is queued.
*/
enic_queue_wq_desc(wq, skb,
pci_map_single(enic->pdev, skb->data,
head_len, PCI_DMA_TODEVICE),
head_len,
vlan_tag_insert, vlan_tag,
eop, loopback);
if (!eop)
enic_queue_wq_skb_cont(enic, wq, skb, len_left, loopback);
}
static inline void enic_queue_wq_skb_csum_l4(struct enic *enic,
struct vnic_wq *wq, struct sk_buff *skb,
int vlan_tag_insert, unsigned int vlan_tag, int loopback)
{
unsigned int head_len = skb_headlen(skb);
unsigned int len_left = skb->len - head_len;
unsigned int hdr_len = skb_checksum_start_offset(skb);
unsigned int csum_offset = hdr_len + skb->csum_offset;
int eop = (len_left == 0);
/* Queue the main skb fragment. The fragments are no larger
* than max MTU(9000)+ETH_HDR_LEN(14) bytes, which is less
* than WQ_ENET_MAX_DESC_LEN length. So only one descriptor
* per fragment is queued.
*/
enic_queue_wq_desc_csum_l4(wq, skb,
pci_map_single(enic->pdev, skb->data,
head_len, PCI_DMA_TODEVICE),
head_len,
csum_offset,
hdr_len,
vlan_tag_insert, vlan_tag,
eop, loopback);
if (!eop)
enic_queue_wq_skb_cont(enic, wq, skb, len_left, loopback);
}
static inline void enic_queue_wq_skb_tso(struct enic *enic,
struct vnic_wq *wq, struct sk_buff *skb, unsigned int mss,
int vlan_tag_insert, unsigned int vlan_tag, int loopback)
{
unsigned int frag_len_left = skb_headlen(skb);
unsigned int len_left = skb->len - frag_len_left;
unsigned int hdr_len = skb_transport_offset(skb) + tcp_hdrlen(skb);
int eop = (len_left == 0);
unsigned int len;
dma_addr_t dma_addr;
unsigned int offset = 0;
skb_frag_t *frag;
/* Preload TCP csum field with IP pseudo hdr calculated
* with IP length set to zero. HW will later add in length
* to each TCP segment resulting from the TSO.
*/
if (skb->protocol == cpu_to_be16(ETH_P_IP)) {
ip_hdr(skb)->check = 0;
tcp_hdr(skb)->check = ~csum_tcpudp_magic(ip_hdr(skb)->saddr,
ip_hdr(skb)->daddr, 0, IPPROTO_TCP, 0);
} else if (skb->protocol == cpu_to_be16(ETH_P_IPV6)) {
tcp_hdr(skb)->check = ~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
&ipv6_hdr(skb)->daddr, 0, IPPROTO_TCP, 0);
}
/* Queue WQ_ENET_MAX_DESC_LEN length descriptors
* for the main skb fragment
*/
while (frag_len_left) {
len = min(frag_len_left, (unsigned int)WQ_ENET_MAX_DESC_LEN);
dma_addr = pci_map_single(enic->pdev, skb->data + offset,
len, PCI_DMA_TODEVICE);
enic_queue_wq_desc_tso(wq, skb,
dma_addr,
len,
mss, hdr_len,
vlan_tag_insert, vlan_tag,
eop && (len == frag_len_left), loopback);
frag_len_left -= len;
offset += len;
}
if (eop)
return;
/* Queue WQ_ENET_MAX_DESC_LEN length descriptors
* for additional data fragments
*/
for (frag = skb_shinfo(skb)->frags; len_left; frag++) {
len_left -= frag->size;
frag_len_left = frag->size;
offset = frag->page_offset;
while (frag_len_left) {
len = min(frag_len_left,
(unsigned int)WQ_ENET_MAX_DESC_LEN);
dma_addr = pci_map_page(enic->pdev, frag->page,
offset, len,
PCI_DMA_TODEVICE);
enic_queue_wq_desc_cont(wq, skb,
dma_addr,
len,
(len_left == 0) &&
(len == frag_len_left), /* EOP? */
loopback);
frag_len_left -= len;
offset += len;
}
}
}
static inline void enic_queue_wq_skb(struct enic *enic,
struct vnic_wq *wq, struct sk_buff *skb)
{
unsigned int mss = skb_shinfo(skb)->gso_size;
unsigned int vlan_tag = 0;
int vlan_tag_insert = 0;
int loopback = 0;
if (vlan_tx_tag_present(skb)) {
/* VLAN tag from trunking driver */
vlan_tag_insert = 1;
vlan_tag = vlan_tx_tag_get(skb);
} else if (enic->loop_enable) {
vlan_tag = enic->loop_tag;
loopback = 1;
}
if (mss)
enic_queue_wq_skb_tso(enic, wq, skb, mss,
vlan_tag_insert, vlan_tag, loopback);
else if (skb->ip_summed == CHECKSUM_PARTIAL)
enic_queue_wq_skb_csum_l4(enic, wq, skb,
vlan_tag_insert, vlan_tag, loopback);
else
enic_queue_wq_skb_vlan(enic, wq, skb,
vlan_tag_insert, vlan_tag, loopback);
}
/* netif_tx_lock held, process context with BHs disabled, or BH */
static netdev_tx_t enic_hard_start_xmit(struct sk_buff *skb,
struct net_device *netdev)
{
struct enic *enic = netdev_priv(netdev);
struct vnic_wq *wq = &enic->wq[0];
unsigned long flags;
if (skb->len <= 0) {
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
/* Non-TSO sends must fit within ENIC_NON_TSO_MAX_DESC descs,
* which is very likely. In the off chance it's going to take
* more than * ENIC_NON_TSO_MAX_DESC, linearize the skb.
*/
if (skb_shinfo(skb)->gso_size == 0 &&
skb_shinfo(skb)->nr_frags + 1 > ENIC_NON_TSO_MAX_DESC &&
skb_linearize(skb)) {
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
spin_lock_irqsave(&enic->wq_lock[0], flags);
if (vnic_wq_desc_avail(wq) <
skb_shinfo(skb)->nr_frags + ENIC_DESC_MAX_SPLITS) {
netif_stop_queue(netdev);
/* This is a hard error, log it */
netdev_err(netdev, "BUG! Tx ring full when queue awake!\n");
spin_unlock_irqrestore(&enic->wq_lock[0], flags);
return NETDEV_TX_BUSY;
}
enic_queue_wq_skb(enic, wq, skb);
if (vnic_wq_desc_avail(wq) < MAX_SKB_FRAGS + ENIC_DESC_MAX_SPLITS)
netif_stop_queue(netdev);
spin_unlock_irqrestore(&enic->wq_lock[0], flags);
return NETDEV_TX_OK;
}
/* dev_base_lock rwlock held, nominally process context */
static struct net_device_stats *enic_get_stats(struct net_device *netdev)
{
struct enic *enic = netdev_priv(netdev);
struct net_device_stats *net_stats = &netdev->stats;
struct vnic_stats *stats;
enic_dev_stats_dump(enic, &stats);
net_stats->tx_packets = stats->tx.tx_frames_ok;
net_stats->tx_bytes = stats->tx.tx_bytes_ok;
net_stats->tx_errors = stats->tx.tx_errors;
net_stats->tx_dropped = stats->tx.tx_drops;
net_stats->rx_packets = stats->rx.rx_frames_ok;
net_stats->rx_bytes = stats->rx.rx_bytes_ok;
net_stats->rx_errors = stats->rx.rx_errors;
net_stats->multicast = stats->rx.rx_multicast_frames_ok;
net_stats->rx_over_errors = enic->rq_truncated_pkts;
net_stats->rx_crc_errors = enic->rq_bad_fcs;
net_stats->rx_dropped = stats->rx.rx_no_bufs + stats->rx.rx_drop;
return net_stats;
}
void enic_reset_addr_lists(struct enic *enic)
{
enic->mc_count = 0;
enic->uc_count = 0;
enic->flags = 0;
}
static int enic_set_mac_addr(struct net_device *netdev, char *addr)
{
struct enic *enic = netdev_priv(netdev);
if (enic_is_dynamic(enic)) {
if (!is_valid_ether_addr(addr) && !is_zero_ether_addr(addr))
return -EADDRNOTAVAIL;
} else {
if (!is_valid_ether_addr(addr))
return -EADDRNOTAVAIL;
}
memcpy(netdev->dev_addr, addr, netdev->addr_len);
return 0;
}
static int enic_set_mac_address_dynamic(struct net_device *netdev, void *p)
{
struct enic *enic = netdev_priv(netdev);
struct sockaddr *saddr = p;
char *addr = saddr->sa_data;
int err;
if (netif_running(enic->netdev)) {
err = enic_dev_del_station_addr(enic);
if (err)
return err;
}
err = enic_set_mac_addr(netdev, addr);
if (err)
return err;
if (netif_running(enic->netdev)) {
err = enic_dev_add_station_addr(enic);
if (err)
return err;
}
return err;
}
static int enic_set_mac_address(struct net_device *netdev, void *p)
{
struct sockaddr *saddr = p;
char *addr = saddr->sa_data;
struct enic *enic = netdev_priv(netdev);
int err;
err = enic_dev_del_station_addr(enic);
if (err)
return err;
err = enic_set_mac_addr(netdev, addr);
if (err)
return err;
return enic_dev_add_station_addr(enic);
}
static void enic_update_multicast_addr_list(struct enic *enic)
{
struct net_device *netdev = enic->netdev;
struct netdev_hw_addr *ha;
unsigned int mc_count = netdev_mc_count(netdev);
u8 mc_addr[ENIC_MULTICAST_PERFECT_FILTERS][ETH_ALEN];
unsigned int i, j;
if (mc_count > ENIC_MULTICAST_PERFECT_FILTERS) {
netdev_warn(netdev, "Registering only %d out of %d "
"multicast addresses\n",
ENIC_MULTICAST_PERFECT_FILTERS, mc_count);
mc_count = ENIC_MULTICAST_PERFECT_FILTERS;
}
/* Is there an easier way? Trying to minimize to
* calls to add/del multicast addrs. We keep the
* addrs from the last call in enic->mc_addr and
* look for changes to add/del.
*/
i = 0;
netdev_for_each_mc_addr(ha, netdev) {
if (i == mc_count)
break;
memcpy(mc_addr[i++], ha->addr, ETH_ALEN);
}
for (i = 0; i < enic->mc_count; i++) {
for (j = 0; j < mc_count; j++)
if (compare_ether_addr(enic->mc_addr[i],
mc_addr[j]) == 0)
break;
if (j == mc_count)
enic_dev_del_addr(enic, enic->mc_addr[i]);
}
for (i = 0; i < mc_count; i++) {
for (j = 0; j < enic->mc_count; j++)
if (compare_ether_addr(mc_addr[i],
enic->mc_addr[j]) == 0)
break;
if (j == enic->mc_count)
enic_dev_add_addr(enic, mc_addr[i]);
}
/* Save the list to compare against next time
*/
for (i = 0; i < mc_count; i++)
memcpy(enic->mc_addr[i], mc_addr[i], ETH_ALEN);
enic->mc_count = mc_count;
}
static void enic_update_unicast_addr_list(struct enic *enic)
{
struct net_device *netdev = enic->netdev;
struct netdev_hw_addr *ha;
unsigned int uc_count = netdev_uc_count(netdev);
u8 uc_addr[ENIC_UNICAST_PERFECT_FILTERS][ETH_ALEN];
unsigned int i, j;
if (uc_count > ENIC_UNICAST_PERFECT_FILTERS) {
netdev_warn(netdev, "Registering only %d out of %d "
"unicast addresses\n",
ENIC_UNICAST_PERFECT_FILTERS, uc_count);
uc_count = ENIC_UNICAST_PERFECT_FILTERS;
}
/* Is there an easier way? Trying to minimize to
* calls to add/del unicast addrs. We keep the
* addrs from the last call in enic->uc_addr and
* look for changes to add/del.
*/
i = 0;
netdev_for_each_uc_addr(ha, netdev) {
if (i == uc_count)
break;
memcpy(uc_addr[i++], ha->addr, ETH_ALEN);
}
for (i = 0; i < enic->uc_count; i++) {
for (j = 0; j < uc_count; j++)
if (compare_ether_addr(enic->uc_addr[i],
uc_addr[j]) == 0)
break;
if (j == uc_count)
enic_dev_del_addr(enic, enic->uc_addr[i]);
}
for (i = 0; i < uc_count; i++) {
for (j = 0; j < enic->uc_count; j++)
if (compare_ether_addr(uc_addr[i],
enic->uc_addr[j]) == 0)
break;
if (j == enic->uc_count)
enic_dev_add_addr(enic, uc_addr[i]);
}
/* Save the list to compare against next time
*/
for (i = 0; i < uc_count; i++)
memcpy(enic->uc_addr[i], uc_addr[i], ETH_ALEN);
enic->uc_count = uc_count;
}
/* netif_tx_lock held, BHs disabled */
static void enic_set_rx_mode(struct net_device *netdev)
{
struct enic *enic = netdev_priv(netdev);
int directed = 1;
int multicast = (netdev->flags & IFF_MULTICAST) ? 1 : 0;
int broadcast = (netdev->flags & IFF_BROADCAST) ? 1 : 0;
int promisc = (netdev->flags & IFF_PROMISC) ||
netdev_uc_count(netdev) > ENIC_UNICAST_PERFECT_FILTERS;
int allmulti = (netdev->flags & IFF_ALLMULTI) ||
netdev_mc_count(netdev) > ENIC_MULTICAST_PERFECT_FILTERS;
unsigned int flags = netdev->flags |
(allmulti ? IFF_ALLMULTI : 0) |
(promisc ? IFF_PROMISC : 0);
if (enic->flags != flags) {
enic->flags = flags;
enic_dev_packet_filter(enic, directed,
multicast, broadcast, promisc, allmulti);
}
if (!promisc) {
enic_update_unicast_addr_list(enic);
if (!allmulti)
enic_update_multicast_addr_list(enic);
}
}
/* rtnl lock is held */
static void enic_vlan_rx_register(struct net_device *netdev,
struct vlan_group *vlan_group)
{
struct enic *enic = netdev_priv(netdev);
enic->vlan_group = vlan_group;
}
/* netif_tx_lock held, BHs disabled */
static void enic_tx_timeout(struct net_device *netdev)
{
struct enic *enic = netdev_priv(netdev);
schedule_work(&enic->reset);
}
static int enic_set_vf_mac(struct net_device *netdev, int vf, u8 *mac)
{
struct enic *enic = netdev_priv(netdev);
if (vf != PORT_SELF_VF)
return -EOPNOTSUPP;
/* Ignore the vf argument for now. We can assume the request
* is coming on a vf.
*/
if (is_valid_ether_addr(mac)) {
memcpy(enic->pp.vf_mac, mac, ETH_ALEN);
return 0;
} else
return -EINVAL;
}
static int enic_set_vf_port(struct net_device *netdev, int vf,
struct nlattr *port[])
{
struct enic *enic = netdev_priv(netdev);
struct enic_port_profile prev_pp;
int err = 0, restore_pp = 1;
/* don't support VFs, yet */
if (vf != PORT_SELF_VF)
return -EOPNOTSUPP;
if (!port[IFLA_PORT_REQUEST])
return -EOPNOTSUPP;
memcpy(&prev_pp, &enic->pp, sizeof(enic->pp));
memset(&enic->pp, 0, sizeof(enic->pp));
enic->pp.set |= ENIC_SET_REQUEST;
enic->pp.request = nla_get_u8(port[IFLA_PORT_REQUEST]);
if (port[IFLA_PORT_PROFILE]) {
enic->pp.set |= ENIC_SET_NAME;
memcpy(enic->pp.name, nla_data(port[IFLA_PORT_PROFILE]),
PORT_PROFILE_MAX);
}
if (port[IFLA_PORT_INSTANCE_UUID]) {
enic->pp.set |= ENIC_SET_INSTANCE;
memcpy(enic->pp.instance_uuid,
nla_data(port[IFLA_PORT_INSTANCE_UUID]), PORT_UUID_MAX);
}
if (port[IFLA_PORT_HOST_UUID]) {
enic->pp.set |= ENIC_SET_HOST;
memcpy(enic->pp.host_uuid,
nla_data(port[IFLA_PORT_HOST_UUID]), PORT_UUID_MAX);
}
/* Special case handling: mac came from IFLA_VF_MAC */
if (!is_zero_ether_addr(prev_pp.vf_mac))
memcpy(enic->pp.mac_addr, prev_pp.vf_mac, ETH_ALEN);
if (is_zero_ether_addr(netdev->dev_addr))
random_ether_addr(netdev->dev_addr);
err = enic_process_set_pp_request(enic, &prev_pp, &restore_pp);
if (err) {
if (restore_pp) {
/* Things are still the way they were: Implicit
* DISASSOCIATE failed
*/
memcpy(&enic->pp, &prev_pp, sizeof(enic->pp));
} else {
memset(&enic->pp, 0, sizeof(enic->pp));
memset(netdev->dev_addr, 0, ETH_ALEN);
}
} else {
/* Set flag to indicate that the port assoc/disassoc
* request has been sent out to fw
*/
enic->pp.set |= ENIC_PORT_REQUEST_APPLIED;
/* If DISASSOCIATE, clean up all assigned/saved macaddresses */
if (enic->pp.request == PORT_REQUEST_DISASSOCIATE) {
memset(enic->pp.mac_addr, 0, ETH_ALEN);
memset(netdev->dev_addr, 0, ETH_ALEN);
}
}
memset(enic->pp.vf_mac, 0, ETH_ALEN);
return err;
}
static int enic_get_vf_port(struct net_device *netdev, int vf,
struct sk_buff *skb)
{
struct enic *enic = netdev_priv(netdev);
u16 response = PORT_PROFILE_RESPONSE_SUCCESS;
int err;
if (!(enic->pp.set & ENIC_PORT_REQUEST_APPLIED))
return -ENODATA;
err = enic_process_get_pp_request(enic, enic->pp.request, &response);
if (err)
return err;
NLA_PUT_U16(skb, IFLA_PORT_REQUEST, enic->pp.request);
NLA_PUT_U16(skb, IFLA_PORT_RESPONSE, response);
if (enic->pp.set & ENIC_SET_NAME)
NLA_PUT(skb, IFLA_PORT_PROFILE, PORT_PROFILE_MAX,
enic->pp.name);
if (enic->pp.set & ENIC_SET_INSTANCE)
NLA_PUT(skb, IFLA_PORT_INSTANCE_UUID, PORT_UUID_MAX,
enic->pp.instance_uuid);
if (enic->pp.set & ENIC_SET_HOST)
NLA_PUT(skb, IFLA_PORT_HOST_UUID, PORT_UUID_MAX,
enic->pp.host_uuid);
return 0;
nla_put_failure:
return -EMSGSIZE;
}
static void enic_free_rq_buf(struct vnic_rq *rq, struct vnic_rq_buf *buf)
{
struct enic *enic = vnic_dev_priv(rq->vdev);
if (!buf->os_buf)
return;
pci_unmap_single(enic->pdev, buf->dma_addr,
buf->len, PCI_DMA_FROMDEVICE);
dev_kfree_skb_any(buf->os_buf);
}
static int enic_rq_alloc_buf(struct vnic_rq *rq)
{
struct enic *enic = vnic_dev_priv(rq->vdev);
struct net_device *netdev = enic->netdev;
struct sk_buff *skb;
unsigned int len = netdev->mtu + VLAN_ETH_HLEN;
unsigned int os_buf_index = 0;
dma_addr_t dma_addr;
skb = netdev_alloc_skb_ip_align(netdev, len);
if (!skb)
return -ENOMEM;
dma_addr = pci_map_single(enic->pdev, skb->data,
len, PCI_DMA_FROMDEVICE);
enic_queue_rq_desc(rq, skb, os_buf_index,
dma_addr, len);
return 0;
}
static void enic_rq_indicate_buf(struct vnic_rq *rq,
struct cq_desc *cq_desc, struct vnic_rq_buf *buf,
int skipped, void *opaque)
{
struct enic *enic = vnic_dev_priv(rq->vdev);
struct net_device *netdev = enic->netdev;
struct sk_buff *skb;
u8 type, color, eop, sop, ingress_port, vlan_stripped;
u8 fcoe, fcoe_sof, fcoe_fc_crc_ok, fcoe_enc_error, fcoe_eof;
u8 tcp_udp_csum_ok, udp, tcp, ipv4_csum_ok;
u8 ipv6, ipv4, ipv4_fragment, fcs_ok, rss_type, csum_not_calc;
u8 packet_error;
u16 q_number, completed_index, bytes_written, vlan_tci, checksum;
u32 rss_hash;
if (skipped)
return;
skb = buf->os_buf;
prefetch(skb->data - NET_IP_ALIGN);
pci_unmap_single(enic->pdev, buf->dma_addr,
buf->len, PCI_DMA_FROMDEVICE);
cq_enet_rq_desc_dec((struct cq_enet_rq_desc *)cq_desc,
&type, &color, &q_number, &completed_index,
&ingress_port, &fcoe, &eop, &sop, &rss_type,
&csum_not_calc, &rss_hash, &bytes_written,
&packet_error, &vlan_stripped, &vlan_tci, &checksum,
&fcoe_sof, &fcoe_fc_crc_ok, &fcoe_enc_error,
&fcoe_eof, &tcp_udp_csum_ok, &udp, &tcp,
&ipv4_csum_ok, &ipv6, &ipv4, &ipv4_fragment,
&fcs_ok);
if (packet_error) {
if (!fcs_ok) {
if (bytes_written > 0)
enic->rq_bad_fcs++;
else if (bytes_written == 0)
enic->rq_truncated_pkts++;
}
dev_kfree_skb_any(skb);
return;
}
if (eop && bytes_written > 0) {
/* Good receive
*/
skb_put(skb, bytes_written);
skb->protocol = eth_type_trans(skb, netdev);
if ((netdev->features & NETIF_F_RXCSUM) && !csum_not_calc) {
skb->csum = htons(checksum);
skb->ip_summed = CHECKSUM_COMPLETE;
}
skb->dev = netdev;
if (enic->vlan_group && vlan_stripped &&
(vlan_tci & CQ_ENET_RQ_DESC_VLAN_TCI_VLAN_MASK)) {
if (netdev->features & NETIF_F_GRO)
vlan_gro_receive(&enic->napi[q_number],
enic->vlan_group, vlan_tci, skb);
else
vlan_hwaccel_receive_skb(skb,
enic->vlan_group, vlan_tci);
} else {
if (netdev->features & NETIF_F_GRO)
napi_gro_receive(&enic->napi[q_number], skb);
else
netif_receive_skb(skb);
}
} else {
/* Buffer overflow
*/
dev_kfree_skb_any(skb);
}
}
static int enic_rq_service(struct vnic_dev *vdev, struct cq_desc *cq_desc,
u8 type, u16 q_number, u16 completed_index, void *opaque)
{
struct enic *enic = vnic_dev_priv(vdev);
vnic_rq_service(&enic->rq[q_number], cq_desc,
completed_index, VNIC_RQ_RETURN_DESC,
enic_rq_indicate_buf, opaque);
return 0;
}
static int enic_poll(struct napi_struct *napi, int budget)
{
struct net_device *netdev = napi->dev;
struct enic *enic = netdev_priv(netdev);
unsigned int cq_rq = enic_cq_rq(enic, 0);
unsigned int cq_wq = enic_cq_wq(enic, 0);
unsigned int intr = enic_legacy_io_intr();
unsigned int rq_work_to_do = budget;
unsigned int wq_work_to_do = -1; /* no limit */
unsigned int work_done, rq_work_done, wq_work_done;
int err;
/* Service RQ (first) and WQ
*/
rq_work_done = vnic_cq_service(&enic->cq[cq_rq],
rq_work_to_do, enic_rq_service, NULL);
wq_work_done = vnic_cq_service(&enic->cq[cq_wq],
wq_work_to_do, enic_wq_service, NULL);
/* Accumulate intr event credits for this polling
* cycle. An intr event is the completion of a
* a WQ or RQ packet.
*/
work_done = rq_work_done + wq_work_done;
if (work_done > 0)
vnic_intr_return_credits(&enic->intr[intr],
work_done,
0 /* don't unmask intr */,
0 /* don't reset intr timer */);
err = vnic_rq_fill(&enic->rq[0], enic_rq_alloc_buf);
/* Buffer allocation failed. Stay in polling
* mode so we can try to fill the ring again.
*/
if (err)
rq_work_done = rq_work_to_do;
if (rq_work_done < rq_work_to_do) {
/* Some work done, but not enough to stay in polling,
* exit polling
*/
napi_complete(napi);
vnic_intr_unmask(&enic->intr[intr]);
}
return rq_work_done;
}
static int enic_poll_msix(struct napi_struct *napi, int budget)
{
struct net_device *netdev = napi->dev;
struct enic *enic = netdev_priv(netdev);
unsigned int rq = (napi - &enic->napi[0]);
unsigned int cq = enic_cq_rq(enic, rq);
unsigned int intr = enic_msix_rq_intr(enic, rq);
unsigned int work_to_do = budget;
unsigned int work_done;
int err;
/* Service RQ
*/
work_done = vnic_cq_service(&enic->cq[cq],
work_to_do, enic_rq_service, NULL);
/* Return intr event credits for this polling
* cycle. An intr event is the completion of a
* RQ packet.
*/
if (work_done > 0)
vnic_intr_return_credits(&enic->intr[intr],
work_done,
0 /* don't unmask intr */,
0 /* don't reset intr timer */);
err = vnic_rq_fill(&enic->rq[rq], enic_rq_alloc_buf);
/* Buffer allocation failed. Stay in polling mode
* so we can try to fill the ring again.
*/
if (err)
work_done = work_to_do;
if (work_done < work_to_do) {
/* Some work done, but not enough to stay in polling,
* exit polling
*/
napi_complete(napi);
vnic_intr_unmask(&enic->intr[intr]);
}
return work_done;
}
static void enic_notify_timer(unsigned long data)
{
struct enic *enic = (struct enic *)data;
enic_notify_check(enic);
mod_timer(&enic->notify_timer,
round_jiffies(jiffies + ENIC_NOTIFY_TIMER_PERIOD));
}
static void enic_free_intr(struct enic *enic)
{
struct net_device *netdev = enic->netdev;
unsigned int i;
switch (vnic_dev_get_intr_mode(enic->vdev)) {
case VNIC_DEV_INTR_MODE_INTX:
free_irq(enic->pdev->irq, netdev);
break;
case VNIC_DEV_INTR_MODE_MSI:
free_irq(enic->pdev->irq, enic);
break;
case VNIC_DEV_INTR_MODE_MSIX:
for (i = 0; i < ARRAY_SIZE(enic->msix); i++)
if (enic->msix[i].requested)
free_irq(enic->msix_entry[i].vector,
enic->msix[i].devid);
break;
default:
break;
}
}
static int enic_request_intr(struct enic *enic)
{
struct net_device *netdev = enic->netdev;
unsigned int i, intr;
int err = 0;
switch (vnic_dev_get_intr_mode(enic->vdev)) {
case VNIC_DEV_INTR_MODE_INTX:
err = request_irq(enic->pdev->irq, enic_isr_legacy,
IRQF_SHARED, netdev->name, netdev);
break;
case VNIC_DEV_INTR_MODE_MSI:
err = request_irq(enic->pdev->irq, enic_isr_msi,
0, netdev->name, enic);
break;
case VNIC_DEV_INTR_MODE_MSIX:
for (i = 0; i < enic->rq_count; i++) {
intr = enic_msix_rq_intr(enic, i);
sprintf(enic->msix[intr].devname,
"%.11s-rx-%d", netdev->name, i);
enic->msix[intr].isr = enic_isr_msix_rq;
enic->msix[intr].devid = &enic->napi[i];
}
for (i = 0; i < enic->wq_count; i++) {
intr = enic_msix_wq_intr(enic, i);
sprintf(enic->msix[intr].devname,
"%.11s-tx-%d", netdev->name, i);
enic->msix[intr].isr = enic_isr_msix_wq;
enic->msix[intr].devid = enic;
}
intr = enic_msix_err_intr(enic);
sprintf(enic->msix[intr].devname,
"%.11s-err", netdev->name);
enic->msix[intr].isr = enic_isr_msix_err;
enic->msix[intr].devid = enic;
intr = enic_msix_notify_intr(enic);
sprintf(enic->msix[intr].devname,
"%.11s-notify", netdev->name);
enic->msix[intr].isr = enic_isr_msix_notify;
enic->msix[intr].devid = enic;
for (i = 0; i < ARRAY_SIZE(enic->msix); i++)
enic->msix[i].requested = 0;
for (i = 0; i < enic->intr_count; i++) {
err = request_irq(enic->msix_entry[i].vector,
enic->msix[i].isr, 0,
enic->msix[i].devname,
enic->msix[i].devid);
if (err) {
enic_free_intr(enic);
break;
}
enic->msix[i].requested = 1;
}
break;
default:
break;
}
return err;
}
static void enic_synchronize_irqs(struct enic *enic)
{
unsigned int i;
switch (vnic_dev_get_intr_mode(enic->vdev)) {
case VNIC_DEV_INTR_MODE_INTX:
case VNIC_DEV_INTR_MODE_MSI:
synchronize_irq(enic->pdev->irq);
break;
case VNIC_DEV_INTR_MODE_MSIX:
for (i = 0; i < enic->intr_count; i++)
synchronize_irq(enic->msix_entry[i].vector);
break;
default:
break;
}
}
static int enic_dev_notify_set(struct enic *enic)
{
int err;
spin_lock(&enic->devcmd_lock);
switch (vnic_dev_get_intr_mode(enic->vdev)) {
case VNIC_DEV_INTR_MODE_INTX:
err = vnic_dev_notify_set(enic->vdev,
enic_legacy_notify_intr());
break;
case VNIC_DEV_INTR_MODE_MSIX:
err = vnic_dev_notify_set(enic->vdev,
enic_msix_notify_intr(enic));
break;
default:
err = vnic_dev_notify_set(enic->vdev, -1 /* no intr */);
break;
}
spin_unlock(&enic->devcmd_lock);
return err;
}
static void enic_notify_timer_start(struct enic *enic)
{
switch (vnic_dev_get_intr_mode(enic->vdev)) {
case VNIC_DEV_INTR_MODE_MSI:
mod_timer(&enic->notify_timer, jiffies);
break;
default:
/* Using intr for notification for INTx/MSI-X */
break;
};
}
/* rtnl lock is held, process context */
static int enic_open(struct net_device *netdev)
{
struct enic *enic = netdev_priv(netdev);
unsigned int i;
int err;
err = enic_request_intr(enic);
if (err) {
netdev_err(netdev, "Unable to request irq.\n");
return err;
}
err = enic_dev_notify_set(enic);
if (err) {
netdev_err(netdev,
"Failed to alloc notify buffer, aborting.\n");
goto err_out_free_intr;
}
for (i = 0; i < enic->rq_count; i++) {
vnic_rq_fill(&enic->rq[i], enic_rq_alloc_buf);
/* Need at least one buffer on ring to get going */
if (vnic_rq_desc_used(&enic->rq[i]) == 0) {
netdev_err(netdev, "Unable to alloc receive buffers\n");
err = -ENOMEM;
goto err_out_notify_unset;
}
}
for (i = 0; i < enic->wq_count; i++)
vnic_wq_enable(&enic->wq[i]);
for (i = 0; i < enic->rq_count; i++)
vnic_rq_enable(&enic->rq[i]);
if (enic_is_dynamic(enic) && !is_zero_ether_addr(enic->pp.mac_addr))
enic_dev_add_addr(enic, enic->pp.mac_addr);
else
enic_dev_add_station_addr(enic);
enic_set_rx_mode(netdev);
netif_wake_queue(netdev);
for (i = 0; i < enic->rq_count; i++)
napi_enable(&enic->napi[i]);
enic_dev_enable(enic);
for (i = 0; i < enic->intr_count; i++)
vnic_intr_unmask(&enic->intr[i]);
enic_notify_timer_start(enic);
return 0;
err_out_notify_unset:
enic_dev_notify_unset(enic);
err_out_free_intr:
enic_free_intr(enic);
return err;
}
/* rtnl lock is held, process context */
static int enic_stop(struct net_device *netdev)
{
struct enic *enic = netdev_priv(netdev);
unsigned int i;
int err;
for (i = 0; i < enic->intr_count; i++) {
vnic_intr_mask(&enic->intr[i]);
(void)vnic_intr_masked(&enic->intr[i]); /* flush write */
}
enic_synchronize_irqs(enic);
del_timer_sync(&enic->notify_timer);
enic_dev_disable(enic);
for (i = 0; i < enic->rq_count; i++)
napi_disable(&enic->napi[i]);
netif_carrier_off(netdev);
netif_tx_disable(netdev);
if (enic_is_dynamic(enic) && !is_zero_ether_addr(enic->pp.mac_addr))
enic_dev_del_addr(enic, enic->pp.mac_addr);
else
enic_dev_del_station_addr(enic);
for (i = 0; i < enic->wq_count; i++) {
err = vnic_wq_disable(&enic->wq[i]);
if (err)
return err;
}
for (i = 0; i < enic->rq_count; i++) {
err = vnic_rq_disable(&enic->rq[i]);
if (err)
return err;
}
enic_dev_notify_unset(enic);
enic_free_intr(enic);
for (i = 0; i < enic->wq_count; i++)
vnic_wq_clean(&enic->wq[i], enic_free_wq_buf);
for (i = 0; i < enic->rq_count; i++)
vnic_rq_clean(&enic->rq[i], enic_free_rq_buf);
for (i = 0; i < enic->cq_count; i++)
vnic_cq_clean(&enic->cq[i]);
for (i = 0; i < enic->intr_count; i++)
vnic_intr_clean(&enic->intr[i]);
return 0;
}
static int enic_change_mtu(struct net_device *netdev, int new_mtu)
{
struct enic *enic = netdev_priv(netdev);
int running = netif_running(netdev);
if (new_mtu < ENIC_MIN_MTU || new_mtu > ENIC_MAX_MTU)
return -EINVAL;
if (running)
enic_stop(netdev);
netdev->mtu = new_mtu;
if (netdev->mtu > enic->port_mtu)
netdev_warn(netdev,
"interface MTU (%d) set higher than port MTU (%d)\n",
netdev->mtu, enic->port_mtu);
if (running)
enic_open(netdev);
return 0;
}
#ifdef CONFIG_NET_POLL_CONTROLLER
static void enic_poll_controller(struct net_device *netdev)
{
struct enic *enic = netdev_priv(netdev);
struct vnic_dev *vdev = enic->vdev;
unsigned int i, intr;
switch (vnic_dev_get_intr_mode(vdev)) {
case VNIC_DEV_INTR_MODE_MSIX:
for (i = 0; i < enic->rq_count; i++) {
intr = enic_msix_rq_intr(enic, i);
enic_isr_msix_rq(enic->msix_entry[intr].vector,
&enic->napi[i]);
}
for (i = 0; i < enic->wq_count; i++) {
intr = enic_msix_wq_intr(enic, i);
enic_isr_msix_wq(enic->msix_entry[intr].vector, enic);
}
break;
case VNIC_DEV_INTR_MODE_MSI:
enic_isr_msi(enic->pdev->irq, enic);
break;
case VNIC_DEV_INTR_MODE_INTX:
enic_isr_legacy(enic->pdev->irq, netdev);
break;
default:
break;
}
}
#endif
static int enic_dev_wait(struct vnic_dev *vdev,
int (*start)(struct vnic_dev *, int),
int (*finished)(struct vnic_dev *, int *),
int arg)
{
unsigned long time;
int done;
int err;
BUG_ON(in_interrupt());
err = start(vdev, arg);
if (err)
return err;
/* Wait for func to complete...2 seconds max
*/
time = jiffies + (HZ * 2);
do {
err = finished(vdev, &done);
if (err)
return err;
if (done)
return 0;
schedule_timeout_uninterruptible(HZ / 10);
} while (time_after(time, jiffies));
return -ETIMEDOUT;
}
static int enic_dev_open(struct enic *enic)
{
int err;
err = enic_dev_wait(enic->vdev, vnic_dev_open,
vnic_dev_open_done, 0);
if (err)
dev_err(enic_get_dev(enic), "vNIC device open failed, err %d\n",
err);
return err;
}
static int enic_dev_hang_reset(struct enic *enic)
{
int err;
err = enic_dev_wait(enic->vdev, vnic_dev_hang_reset,
vnic_dev_hang_reset_done, 0);
if (err)
netdev_err(enic->netdev, "vNIC hang reset failed, err %d\n",
err);
return err;
}
static int enic_set_rsskey(struct enic *enic)
{
dma_addr_t rss_key_buf_pa;
union vnic_rss_key *rss_key_buf_va = NULL;
union vnic_rss_key rss_key = {
.key[0].b = {85, 67, 83, 97, 119, 101, 115, 111, 109, 101},
.key[1].b = {80, 65, 76, 79, 117, 110, 105, 113, 117, 101},
.key[2].b = {76, 73, 78, 85, 88, 114, 111, 99, 107, 115},
.key[3].b = {69, 78, 73, 67, 105, 115, 99, 111, 111, 108},
};
int err;
rss_key_buf_va = pci_alloc_consistent(enic->pdev,
sizeof(union vnic_rss_key), &rss_key_buf_pa);
if (!rss_key_buf_va)
return -ENOMEM;
memcpy(rss_key_buf_va, &rss_key, sizeof(union vnic_rss_key));
spin_lock(&enic->devcmd_lock);
err = enic_set_rss_key(enic,
rss_key_buf_pa,
sizeof(union vnic_rss_key));
spin_unlock(&enic->devcmd_lock);
pci_free_consistent(enic->pdev, sizeof(union vnic_rss_key),
rss_key_buf_va, rss_key_buf_pa);
return err;
}
static int enic_set_rsscpu(struct enic *enic, u8 rss_hash_bits)
{
dma_addr_t rss_cpu_buf_pa;
union vnic_rss_cpu *rss_cpu_buf_va = NULL;
unsigned int i;
int err;
rss_cpu_buf_va = pci_alloc_consistent(enic->pdev,
sizeof(union vnic_rss_cpu), &rss_cpu_buf_pa);
if (!rss_cpu_buf_va)
return -ENOMEM;
for (i = 0; i < (1 << rss_hash_bits); i++)
(*rss_cpu_buf_va).cpu[i/4].b[i%4] = i % enic->rq_count;
spin_lock(&enic->devcmd_lock);
err = enic_set_rss_cpu(enic,
rss_cpu_buf_pa,
sizeof(union vnic_rss_cpu));
spin_unlock(&enic->devcmd_lock);
pci_free_consistent(enic->pdev, sizeof(union vnic_rss_cpu),
rss_cpu_buf_va, rss_cpu_buf_pa);
return err;
}
static int enic_set_niccfg(struct enic *enic, u8 rss_default_cpu,
u8 rss_hash_type, u8 rss_hash_bits, u8 rss_base_cpu, u8 rss_enable)
{
const u8 tso_ipid_split_en = 0;
const u8 ig_vlan_strip_en = 1;
int err;
/* Enable VLAN tag stripping.
*/
spin_lock(&enic->devcmd_lock);
err = enic_set_nic_cfg(enic,
rss_default_cpu, rss_hash_type,
rss_hash_bits, rss_base_cpu,
rss_enable, tso_ipid_split_en,
ig_vlan_strip_en);
spin_unlock(&enic->devcmd_lock);
return err;
}
static int enic_set_rss_nic_cfg(struct enic *enic)
{
struct device *dev = enic_get_dev(enic);
const u8 rss_default_cpu = 0;
const u8 rss_hash_type = NIC_CFG_RSS_HASH_TYPE_IPV4 |
NIC_CFG_RSS_HASH_TYPE_TCP_IPV4 |
NIC_CFG_RSS_HASH_TYPE_IPV6 |
NIC_CFG_RSS_HASH_TYPE_TCP_IPV6;
const u8 rss_hash_bits = 7;
const u8 rss_base_cpu = 0;
u8 rss_enable = ENIC_SETTING(enic, RSS) && (enic->rq_count > 1);
if (rss_enable) {
if (!enic_set_rsskey(enic)) {
if (enic_set_rsscpu(enic, rss_hash_bits)) {
rss_enable = 0;
dev_warn(dev, "RSS disabled, "
"Failed to set RSS cpu indirection table.");
}
} else {
rss_enable = 0;
dev_warn(dev, "RSS disabled, Failed to set RSS key.\n");
}
}
return enic_set_niccfg(enic, rss_default_cpu, rss_hash_type,
rss_hash_bits, rss_base_cpu, rss_enable);
}
static void enic_reset(struct work_struct *work)
{
struct enic *enic = container_of(work, struct enic, reset);
if (!netif_running(enic->netdev))
return;
rtnl_lock();
enic_dev_hang_notify(enic);
enic_stop(enic->netdev);
enic_dev_hang_reset(enic);
enic_reset_addr_lists(enic);
enic_init_vnic_resources(enic);
enic_set_rss_nic_cfg(enic);
enic_dev_set_ig_vlan_rewrite_mode(enic);
enic_open(enic->netdev);
rtnl_unlock();
}
static int enic_set_intr_mode(struct enic *enic)
{
unsigned int n = min_t(unsigned int, enic->rq_count, ENIC_RQ_MAX);
unsigned int m = min_t(unsigned int, enic->wq_count, ENIC_WQ_MAX);
unsigned int i;
/* Set interrupt mode (INTx, MSI, MSI-X) depending
* on system capabilities.
*
* Try MSI-X first
*
* We need n RQs, m WQs, n+m CQs, and n+m+2 INTRs
* (the second to last INTR is used for WQ/RQ errors)
* (the last INTR is used for notifications)
*/
BUG_ON(ARRAY_SIZE(enic->msix_entry) < n + m + 2);
for (i = 0; i < n + m + 2; i++)
enic->msix_entry[i].entry = i;
/* Use multiple RQs if RSS is enabled
*/
if (ENIC_SETTING(enic, RSS) &&
enic->config.intr_mode < 1 &&
enic->rq_count >= n &&
enic->wq_count >= m &&
enic->cq_count >= n + m &&
enic->intr_count >= n + m + 2) {
if (!pci_enable_msix(enic->pdev, enic->msix_entry, n + m + 2)) {
enic->rq_count = n;
enic->wq_count = m;
enic->cq_count = n + m;
enic->intr_count = n + m + 2;
vnic_dev_set_intr_mode(enic->vdev,
VNIC_DEV_INTR_MODE_MSIX);
return 0;
}
}
if (enic->config.intr_mode < 1 &&
enic->rq_count >= 1 &&
enic->wq_count >= m &&
enic->cq_count >= 1 + m &&
enic->intr_count >= 1 + m + 2) {
if (!pci_enable_msix(enic->pdev, enic->msix_entry, 1 + m + 2)) {
enic->rq_count = 1;
enic->wq_count = m;
enic->cq_count = 1 + m;
enic->intr_count = 1 + m + 2;
vnic_dev_set_intr_mode(enic->vdev,
VNIC_DEV_INTR_MODE_MSIX);
return 0;
}
}
/* Next try MSI
*
* We need 1 RQ, 1 WQ, 2 CQs, and 1 INTR
*/
if (enic->config.intr_mode < 2 &&
enic->rq_count >= 1 &&
enic->wq_count >= 1 &&
enic->cq_count >= 2 &&
enic->intr_count >= 1 &&
!pci_enable_msi(enic->pdev)) {
enic->rq_count = 1;
enic->wq_count = 1;
enic->cq_count = 2;
enic->intr_count = 1;
vnic_dev_set_intr_mode(enic->vdev, VNIC_DEV_INTR_MODE_MSI);
return 0;
}
/* Next try INTx
*
* We need 1 RQ, 1 WQ, 2 CQs, and 3 INTRs
* (the first INTR is used for WQ/RQ)
* (the second INTR is used for WQ/RQ errors)
* (the last INTR is used for notifications)
*/
if (enic->config.intr_mode < 3 &&
enic->rq_count >= 1 &&
enic->wq_count >= 1 &&
enic->cq_count >= 2 &&
enic->intr_count >= 3) {
enic->rq_count = 1;
enic->wq_count = 1;
enic->cq_count = 2;
enic->intr_count = 3;
vnic_dev_set_intr_mode(enic->vdev, VNIC_DEV_INTR_MODE_INTX);
return 0;
}
vnic_dev_set_intr_mode(enic->vdev, VNIC_DEV_INTR_MODE_UNKNOWN);
return -EINVAL;
}
static void enic_clear_intr_mode(struct enic *enic)
{
switch (vnic_dev_get_intr_mode(enic->vdev)) {
case VNIC_DEV_INTR_MODE_MSIX:
pci_disable_msix(enic->pdev);
break;
case VNIC_DEV_INTR_MODE_MSI:
pci_disable_msi(enic->pdev);
break;
default:
break;
}
vnic_dev_set_intr_mode(enic->vdev, VNIC_DEV_INTR_MODE_UNKNOWN);
}
static const struct net_device_ops enic_netdev_dynamic_ops = {
.ndo_open = enic_open,
.ndo_stop = enic_stop,
.ndo_start_xmit = enic_hard_start_xmit,
.ndo_get_stats = enic_get_stats,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_rx_mode = enic_set_rx_mode,
.ndo_set_multicast_list = enic_set_rx_mode,
.ndo_set_mac_address = enic_set_mac_address_dynamic,
.ndo_change_mtu = enic_change_mtu,
.ndo_vlan_rx_register = enic_vlan_rx_register,
.ndo_vlan_rx_add_vid = enic_vlan_rx_add_vid,
.ndo_vlan_rx_kill_vid = enic_vlan_rx_kill_vid,
.ndo_tx_timeout = enic_tx_timeout,
.ndo_set_vf_port = enic_set_vf_port,
.ndo_get_vf_port = enic_get_vf_port,
.ndo_set_vf_mac = enic_set_vf_mac,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = enic_poll_controller,
#endif
};
static const struct net_device_ops enic_netdev_ops = {
.ndo_open = enic_open,
.ndo_stop = enic_stop,
.ndo_start_xmit = enic_hard_start_xmit,
.ndo_get_stats = enic_get_stats,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_mac_address = enic_set_mac_address,
.ndo_set_rx_mode = enic_set_rx_mode,
.ndo_set_multicast_list = enic_set_rx_mode,
.ndo_change_mtu = enic_change_mtu,
.ndo_vlan_rx_register = enic_vlan_rx_register,
.ndo_vlan_rx_add_vid = enic_vlan_rx_add_vid,
.ndo_vlan_rx_kill_vid = enic_vlan_rx_kill_vid,
.ndo_tx_timeout = enic_tx_timeout,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = enic_poll_controller,
#endif
};
static void enic_dev_deinit(struct enic *enic)
{
unsigned int i;
for (i = 0; i < enic->rq_count; i++)
netif_napi_del(&enic->napi[i]);
enic_free_vnic_resources(enic);
enic_clear_intr_mode(enic);
}
static int enic_dev_init(struct enic *enic)
{
struct device *dev = enic_get_dev(enic);
struct net_device *netdev = enic->netdev;
unsigned int i;
int err;
/* Get vNIC configuration
*/
err = enic_get_vnic_config(enic);
if (err) {
dev_err(dev, "Get vNIC configuration failed, aborting\n");
return err;
}
/* Get available resource counts
*/
enic_get_res_counts(enic);
/* Set interrupt mode based on resource counts and system
* capabilities
*/
err = enic_set_intr_mode(enic);
if (err) {
dev_err(dev, "Failed to set intr mode based on resource "
"counts and system capabilities, aborting\n");
return err;
}
/* Allocate and configure vNIC resources
*/
err = enic_alloc_vnic_resources(enic);
if (err) {
dev_err(dev, "Failed to alloc vNIC resources, aborting\n");
goto err_out_free_vnic_resources;
}
enic_init_vnic_resources(enic);
err = enic_set_rss_nic_cfg(enic);
if (err) {
dev_err(dev, "Failed to config nic, aborting\n");
goto err_out_free_vnic_resources;
}
switch (vnic_dev_get_intr_mode(enic->vdev)) {
default:
netif_napi_add(netdev, &enic->napi[0], enic_poll, 64);
break;
case VNIC_DEV_INTR_MODE_MSIX:
for (i = 0; i < enic->rq_count; i++)
netif_napi_add(netdev, &enic->napi[i],
enic_poll_msix, 64);
break;
}
return 0;
err_out_free_vnic_resources:
enic_clear_intr_mode(enic);
enic_free_vnic_resources(enic);
return err;
}
static void enic_iounmap(struct enic *enic)
{
unsigned int i;
for (i = 0; i < ARRAY_SIZE(enic->bar); i++)
if (enic->bar[i].vaddr)
iounmap(enic->bar[i].vaddr);
}
static int __devinit enic_probe(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct device *dev = &pdev->dev;
struct net_device *netdev;
struct enic *enic;
int using_dac = 0;
unsigned int i;
int err;
/* Allocate net device structure and initialize. Private
* instance data is initialized to zero.
*/
netdev = alloc_etherdev(sizeof(struct enic));
if (!netdev) {
pr_err("Etherdev alloc failed, aborting\n");
return -ENOMEM;
}
pci_set_drvdata(pdev, netdev);
SET_NETDEV_DEV(netdev, &pdev->dev);
enic = netdev_priv(netdev);
enic->netdev = netdev;
enic->pdev = pdev;
/* Setup PCI resources
*/
err = pci_enable_device_mem(pdev);
if (err) {
dev_err(dev, "Cannot enable PCI device, aborting\n");
goto err_out_free_netdev;
}
err = pci_request_regions(pdev, DRV_NAME);
if (err) {
dev_err(dev, "Cannot request PCI regions, aborting\n");
goto err_out_disable_device;
}
pci_set_master(pdev);
/* Query PCI controller on system for DMA addressing
* limitation for the device. Try 40-bit first, and
* fail to 32-bit.
*/
err = pci_set_dma_mask(pdev, DMA_BIT_MASK(40));
if (err) {
err = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
if (err) {
dev_err(dev, "No usable DMA configuration, aborting\n");
goto err_out_release_regions;
}
err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32));
if (err) {
dev_err(dev, "Unable to obtain %u-bit DMA "
"for consistent allocations, aborting\n", 32);
goto err_out_release_regions;
}
} else {
err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(40));
if (err) {
dev_err(dev, "Unable to obtain %u-bit DMA "
"for consistent allocations, aborting\n", 40);
goto err_out_release_regions;
}
using_dac = 1;
}
/* Map vNIC resources from BAR0-5
*/
for (i = 0; i < ARRAY_SIZE(enic->bar); i++) {
if (!(pci_resource_flags(pdev, i) & IORESOURCE_MEM))
continue;
enic->bar[i].len = pci_resource_len(pdev, i);
enic->bar[i].vaddr = pci_iomap(pdev, i, enic->bar[i].len);
if (!enic->bar[i].vaddr) {
dev_err(dev, "Cannot memory-map BAR %d, aborting\n", i);
err = -ENODEV;
goto err_out_iounmap;
}
enic->bar[i].bus_addr = pci_resource_start(pdev, i);
}
/* Register vNIC device
*/
enic->vdev = vnic_dev_register(NULL, enic, pdev, enic->bar,
ARRAY_SIZE(enic->bar));
if (!enic->vdev) {
dev_err(dev, "vNIC registration failed, aborting\n");
err = -ENODEV;
goto err_out_iounmap;
}
/* Issue device open to get device in known state
*/
err = enic_dev_open(enic);
if (err) {
dev_err(dev, "vNIC dev open failed, aborting\n");
goto err_out_vnic_unregister;
}
/* Setup devcmd lock
*/
spin_lock_init(&enic->devcmd_lock);
/*
* Set ingress vlan rewrite mode before vnic initialization
*/
err = enic_dev_set_ig_vlan_rewrite_mode(enic);
if (err) {
dev_err(dev,
"Failed to set ingress vlan rewrite mode, aborting.\n");
goto err_out_dev_close;
}
/* Issue device init to initialize the vnic-to-switch link.
* We'll start with carrier off and wait for link UP
* notification later to turn on carrier. We don't need
* to wait here for the vnic-to-switch link initialization
* to complete; link UP notification is the indication that
* the process is complete.
*/
netif_carrier_off(netdev);
/* Do not call dev_init for a dynamic vnic.
* For a dynamic vnic, init_prov_info will be
* called later by an upper layer.
*/
if (!enic_is_dynamic(enic)) {
err = vnic_dev_init(enic->vdev, 0);
if (err) {
dev_err(dev, "vNIC dev init failed, aborting\n");
goto err_out_dev_close;
}
}
err = enic_dev_init(enic);
if (err) {
dev_err(dev, "Device initialization failed, aborting\n");
goto err_out_dev_close;
}
/* Setup notification timer, HW reset task, and wq locks
*/
init_timer(&enic->notify_timer);
enic->notify_timer.function = enic_notify_timer;
enic->notify_timer.data = (unsigned long)enic;
INIT_WORK(&enic->reset, enic_reset);
for (i = 0; i < enic->wq_count; i++)
spin_lock_init(&enic->wq_lock[i]);
/* Register net device
*/
enic->port_mtu = enic->config.mtu;
(void)enic_change_mtu(netdev, enic->port_mtu);
err = enic_set_mac_addr(netdev, enic->mac_addr);
if (err) {
dev_err(dev, "Invalid MAC address, aborting\n");
goto err_out_dev_deinit;
}
enic->tx_coalesce_usecs = enic->config.intr_timer_usec;
enic->rx_coalesce_usecs = enic->tx_coalesce_usecs;
if (enic_is_dynamic(enic))
netdev->netdev_ops = &enic_netdev_dynamic_ops;
else
netdev->netdev_ops = &enic_netdev_ops;
netdev->watchdog_timeo = 2 * HZ;
netdev->ethtool_ops = &enic_ethtool_ops;
netdev->features |= NETIF_F_HW_VLAN_TX | NETIF_F_HW_VLAN_RX;
if (ENIC_SETTING(enic, LOOP)) {
netdev->features &= ~NETIF_F_HW_VLAN_TX;
enic->loop_enable = 1;
enic->loop_tag = enic->config.loop_tag;
dev_info(dev, "loopback tag=0x%04x\n", enic->loop_tag);
}
if (ENIC_SETTING(enic, TXCSUM))
netdev->hw_features |= NETIF_F_SG | NETIF_F_HW_CSUM;
if (ENIC_SETTING(enic, TSO))
netdev->hw_features |= NETIF_F_TSO |
NETIF_F_TSO6 | NETIF_F_TSO_ECN;
if (ENIC_SETTING(enic, RXCSUM))
netdev->hw_features |= NETIF_F_RXCSUM;
netdev->features |= netdev->hw_features;
if (using_dac)
netdev->features |= NETIF_F_HIGHDMA;
err = register_netdev(netdev);
if (err) {
dev_err(dev, "Cannot register net device, aborting\n");
goto err_out_dev_deinit;
}
return 0;
err_out_dev_deinit:
enic_dev_deinit(enic);
err_out_dev_close:
vnic_dev_close(enic->vdev);
err_out_vnic_unregister:
vnic_dev_unregister(enic->vdev);
err_out_iounmap:
enic_iounmap(enic);
err_out_release_regions:
pci_release_regions(pdev);
err_out_disable_device:
pci_disable_device(pdev);
err_out_free_netdev:
pci_set_drvdata(pdev, NULL);
free_netdev(netdev);
return err;
}
static void __devexit enic_remove(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
if (netdev) {
struct enic *enic = netdev_priv(netdev);
cancel_work_sync(&enic->reset);
unregister_netdev(netdev);
enic_dev_deinit(enic);
vnic_dev_close(enic->vdev);
vnic_dev_unregister(enic->vdev);
enic_iounmap(enic);
pci_release_regions(pdev);
pci_disable_device(pdev);
pci_set_drvdata(pdev, NULL);
free_netdev(netdev);
}
}
static struct pci_driver enic_driver = {
.name = DRV_NAME,
.id_table = enic_id_table,
.probe = enic_probe,
.remove = __devexit_p(enic_remove),
};
static int __init enic_init_module(void)
{
pr_info("%s, ver %s\n", DRV_DESCRIPTION, DRV_VERSION);
return pci_register_driver(&enic_driver);
}
static void __exit enic_cleanup_module(void)
{
pci_unregister_driver(&enic_driver);
}
module_init(enic_init_module);
module_exit(enic_cleanup_module);
| gpl-2.0 |
StarKissed/starkissed-kernel-trlte | drivers/net/wimax/i2400m/netdev.c | 2623 | 20176 | /*
* Intel Wireless WiMAX Connection 2400m
* Glue with the networking stack
*
*
* Copyright (C) 2007 Intel Corporation <linux-wimax@intel.com>
* Yanir Lubetkin <yanirx.lubetkin@intel.com>
* Inaky Perez-Gonzalez <inaky.perez-gonzalez@intel.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*
*
* This implements an ethernet device for the i2400m.
*
* We fake being an ethernet device to simplify the support from user
* space and from the other side. The world is (sadly) configured to
* take in only Ethernet devices...
*
* Because of this, when using firmwares <= v1.3, there is an
* copy-each-rxed-packet overhead on the RX path. Each IP packet has
* to be reallocated to add an ethernet header (as there is no space
* in what we get from the device). This is a known drawback and
* firmwares >= 1.4 add header space that can be used to insert the
* ethernet header without having to reallocate and copy.
*
* TX error handling is tricky; because we have to FIFO/queue the
* buffers for transmission (as the hardware likes it aggregated), we
* just give the skb to the TX subsystem and by the time it is
* transmitted, we have long forgotten about it. So we just don't care
* too much about it.
*
* Note that when the device is in idle mode with the basestation, we
* need to negotiate coming back up online. That involves negotiation
* and possible user space interaction. Thus, we defer to a workqueue
* to do all that. By default, we only queue a single packet and drop
* the rest, as potentially the time to go back from idle to normal is
* long.
*
* ROADMAP
*
* i2400m_open Called on ifconfig up
* i2400m_stop Called on ifconfig down
*
* i2400m_hard_start_xmit Called by the network stack to send a packet
* i2400m_net_wake_tx Wake up device from basestation-IDLE & TX
* i2400m_wake_tx_work
* i2400m_cmd_exit_idle
* i2400m_tx
* i2400m_net_tx TX a data frame
* i2400m_tx
*
* i2400m_change_mtu Called on ifconfig mtu XXX
*
* i2400m_tx_timeout Called when the device times out
*
* i2400m_net_rx Called by the RX code when a data frame is
* available (firmware <= 1.3)
* i2400m_net_erx Called by the RX code when a data frame is
* available (firmware >= 1.4).
* i2400m_netdev_setup Called to setup all the netdev stuff from
* alloc_netdev.
*/
#include <linux/if_arp.h>
#include <linux/slab.h>
#include <linux/netdevice.h>
#include <linux/ethtool.h>
#include <linux/export.h>
#include "i2400m.h"
#define D_SUBMODULE netdev
#include "debug-levels.h"
enum {
/* netdev interface */
/* 20 secs? yep, this is the maximum timeout that the device
* might take to get out of IDLE / negotiate it with the base
* station. We add 1sec for good measure. */
I2400M_TX_TIMEOUT = 21 * HZ,
/*
* Experimentation has determined that, 20 to be a good value
* for minimizing the jitter in the throughput.
*/
I2400M_TX_QLEN = 20,
};
static
int i2400m_open(struct net_device *net_dev)
{
int result;
struct i2400m *i2400m = net_dev_to_i2400m(net_dev);
struct device *dev = i2400m_dev(i2400m);
d_fnstart(3, dev, "(net_dev %p [i2400m %p])\n", net_dev, i2400m);
/* Make sure we wait until init is complete... */
mutex_lock(&i2400m->init_mutex);
if (i2400m->updown)
result = 0;
else
result = -EBUSY;
mutex_unlock(&i2400m->init_mutex);
d_fnend(3, dev, "(net_dev %p [i2400m %p]) = %d\n",
net_dev, i2400m, result);
return result;
}
static
int i2400m_stop(struct net_device *net_dev)
{
struct i2400m *i2400m = net_dev_to_i2400m(net_dev);
struct device *dev = i2400m_dev(i2400m);
d_fnstart(3, dev, "(net_dev %p [i2400m %p])\n", net_dev, i2400m);
i2400m_net_wake_stop(i2400m);
d_fnend(3, dev, "(net_dev %p [i2400m %p]) = 0\n", net_dev, i2400m);
return 0;
}
/*
* Wake up the device and transmit a held SKB, then restart the net queue
*
* When the device goes into basestation-idle mode, we need to tell it
* to exit that mode; it will negotiate with the base station, user
* space may have to intervene to rehandshake crypto and then tell us
* when it is ready to transmit the packet we have "queued". Still we
* need to give it sometime after it reports being ok.
*
* On error, there is not much we can do. If the error was on TX, we
* still wake the queue up to see if the next packet will be luckier.
*
* If _cmd_exit_idle() fails...well, it could be many things; most
* commonly it is that something else took the device out of IDLE mode
* (for example, the base station). In that case we get an -EILSEQ and
* we are just going to ignore that one. If the device is back to
* connected, then fine -- if it is someother state, the packet will
* be dropped anyway.
*/
void i2400m_wake_tx_work(struct work_struct *ws)
{
int result;
struct i2400m *i2400m = container_of(ws, struct i2400m, wake_tx_ws);
struct net_device *net_dev = i2400m->wimax_dev.net_dev;
struct device *dev = i2400m_dev(i2400m);
struct sk_buff *skb;
unsigned long flags;
spin_lock_irqsave(&i2400m->tx_lock, flags);
skb = i2400m->wake_tx_skb;
i2400m->wake_tx_skb = NULL;
spin_unlock_irqrestore(&i2400m->tx_lock, flags);
d_fnstart(3, dev, "(ws %p i2400m %p skb %p)\n", ws, i2400m, skb);
result = -EINVAL;
if (skb == NULL) {
dev_err(dev, "WAKE&TX: skb disappeared!\n");
goto out_put;
}
/* If we have, somehow, lost the connection after this was
* queued, don't do anything; this might be the device got
* reset or just disconnected. */
if (unlikely(!netif_carrier_ok(net_dev)))
goto out_kfree;
result = i2400m_cmd_exit_idle(i2400m);
if (result == -EILSEQ)
result = 0;
if (result < 0) {
dev_err(dev, "WAKE&TX: device didn't get out of idle: "
"%d - resetting\n", result);
i2400m_reset(i2400m, I2400M_RT_BUS);
goto error;
}
result = wait_event_timeout(i2400m->state_wq,
i2400m->state != I2400M_SS_IDLE,
net_dev->watchdog_timeo - HZ/2);
if (result == 0)
result = -ETIMEDOUT;
if (result < 0) {
dev_err(dev, "WAKE&TX: error waiting for device to exit IDLE: "
"%d - resetting\n", result);
i2400m_reset(i2400m, I2400M_RT_BUS);
goto error;
}
msleep(20); /* device still needs some time or it drops it */
result = i2400m_tx(i2400m, skb->data, skb->len, I2400M_PT_DATA);
error:
netif_wake_queue(net_dev);
out_kfree:
kfree_skb(skb); /* refcount transferred by _hard_start_xmit() */
out_put:
i2400m_put(i2400m);
d_fnend(3, dev, "(ws %p i2400m %p skb %p) = void [%d]\n",
ws, i2400m, skb, result);
}
/*
* Prepare the data payload TX header
*
* The i2400m expects a 4 byte header in front of a data packet.
*
* Because we pretend to be an ethernet device, this packet comes with
* an ethernet header. Pull it and push our header.
*/
static
void i2400m_tx_prep_header(struct sk_buff *skb)
{
struct i2400m_pl_data_hdr *pl_hdr;
skb_pull(skb, ETH_HLEN);
pl_hdr = (struct i2400m_pl_data_hdr *) skb_push(skb, sizeof(*pl_hdr));
pl_hdr->reserved = 0;
}
/*
* Cleanup resources acquired during i2400m_net_wake_tx()
*
* This is called by __i2400m_dev_stop and means we have to make sure
* the workqueue is flushed from any pending work.
*/
void i2400m_net_wake_stop(struct i2400m *i2400m)
{
struct device *dev = i2400m_dev(i2400m);
struct sk_buff *wake_tx_skb;
unsigned long flags;
d_fnstart(3, dev, "(i2400m %p)\n", i2400m);
/*
* See i2400m_hard_start_xmit(), references are taken there and
* here we release them if the packet was still pending.
*/
cancel_work_sync(&i2400m->wake_tx_ws);
spin_lock_irqsave(&i2400m->tx_lock, flags);
wake_tx_skb = i2400m->wake_tx_skb;
i2400m->wake_tx_skb = NULL;
spin_unlock_irqrestore(&i2400m->tx_lock, flags);
if (wake_tx_skb) {
i2400m_put(i2400m);
kfree_skb(wake_tx_skb);
}
d_fnend(3, dev, "(i2400m %p) = void\n", i2400m);
}
/*
* TX an skb to an idle device
*
* When the device is in basestation-idle mode, we need to wake it up
* and then TX. So we queue a work_struct for doing so.
*
* We need to get an extra ref for the skb (so it is not dropped), as
* well as be careful not to queue more than one request (won't help
* at all). If more than one request comes or there are errors, we
* just drop the packets (see i2400m_hard_start_xmit()).
*/
static
int i2400m_net_wake_tx(struct i2400m *i2400m, struct net_device *net_dev,
struct sk_buff *skb)
{
int result;
struct device *dev = i2400m_dev(i2400m);
unsigned long flags;
d_fnstart(3, dev, "(skb %p net_dev %p)\n", skb, net_dev);
if (net_ratelimit()) {
d_printf(3, dev, "WAKE&NETTX: "
"skb %p sending %d bytes to radio\n",
skb, skb->len);
d_dump(4, dev, skb->data, skb->len);
}
/* We hold a ref count for i2400m and skb, so when
* stopping() the device, we need to cancel that work
* and if pending, release those resources. */
result = 0;
spin_lock_irqsave(&i2400m->tx_lock, flags);
if (!i2400m->wake_tx_skb) {
netif_stop_queue(net_dev);
i2400m_get(i2400m);
i2400m->wake_tx_skb = skb_get(skb); /* transfer ref count */
i2400m_tx_prep_header(skb);
result = schedule_work(&i2400m->wake_tx_ws);
WARN_ON(result == 0);
}
spin_unlock_irqrestore(&i2400m->tx_lock, flags);
if (result == 0) {
/* Yes, this happens even if we stopped the
* queue -- blame the queue disciplines that
* queue without looking -- I guess there is a reason
* for that. */
if (net_ratelimit())
d_printf(1, dev, "NETTX: device exiting idle, "
"dropping skb %p, queue running %d\n",
skb, netif_queue_stopped(net_dev));
result = -EBUSY;
}
d_fnend(3, dev, "(skb %p net_dev %p) = %d\n", skb, net_dev, result);
return result;
}
/*
* Transmit a packet to the base station on behalf of the network stack.
*
* Returns: 0 if ok, < 0 errno code on error.
*
* We need to pull the ethernet header and add the hardware header,
* which is currently set to all zeroes and reserved.
*/
static
int i2400m_net_tx(struct i2400m *i2400m, struct net_device *net_dev,
struct sk_buff *skb)
{
int result;
struct device *dev = i2400m_dev(i2400m);
d_fnstart(3, dev, "(i2400m %p net_dev %p skb %p)\n",
i2400m, net_dev, skb);
/* FIXME: check eth hdr, only IPv4 is routed by the device as of now */
net_dev->trans_start = jiffies;
i2400m_tx_prep_header(skb);
d_printf(3, dev, "NETTX: skb %p sending %d bytes to radio\n",
skb, skb->len);
d_dump(4, dev, skb->data, skb->len);
result = i2400m_tx(i2400m, skb->data, skb->len, I2400M_PT_DATA);
d_fnend(3, dev, "(i2400m %p net_dev %p skb %p) = %d\n",
i2400m, net_dev, skb, result);
return result;
}
/*
* Transmit a packet to the base station on behalf of the network stack
*
*
* Returns: NETDEV_TX_OK (always, even in case of error)
*
* In case of error, we just drop it. Reasons:
*
* - we add a hw header to each skb, and if the network stack
* retries, we have no way to know if that skb has it or not.
*
* - network protocols have their own drop-recovery mechanisms
*
* - there is not much else we can do
*
* If the device is idle, we need to wake it up; that is an operation
* that will sleep. See i2400m_net_wake_tx() for details.
*/
static
netdev_tx_t i2400m_hard_start_xmit(struct sk_buff *skb,
struct net_device *net_dev)
{
struct i2400m *i2400m = net_dev_to_i2400m(net_dev);
struct device *dev = i2400m_dev(i2400m);
int result = -1;
d_fnstart(3, dev, "(skb %p net_dev %p)\n", skb, net_dev);
if (skb_header_cloned(skb) &&
pskb_expand_head(skb, 0, 0, GFP_ATOMIC))
goto drop;
if (i2400m->state == I2400M_SS_IDLE)
result = i2400m_net_wake_tx(i2400m, net_dev, skb);
else
result = i2400m_net_tx(i2400m, net_dev, skb);
if (result < 0) {
drop:
net_dev->stats.tx_dropped++;
} else {
net_dev->stats.tx_packets++;
net_dev->stats.tx_bytes += skb->len;
}
dev_kfree_skb(skb);
d_fnend(3, dev, "(skb %p net_dev %p) = %d\n", skb, net_dev, result);
return NETDEV_TX_OK;
}
static
int i2400m_change_mtu(struct net_device *net_dev, int new_mtu)
{
int result;
struct i2400m *i2400m = net_dev_to_i2400m(net_dev);
struct device *dev = i2400m_dev(i2400m);
if (new_mtu >= I2400M_MAX_MTU) {
dev_err(dev, "Cannot change MTU to %d (max is %d)\n",
new_mtu, I2400M_MAX_MTU);
result = -EINVAL;
} else {
net_dev->mtu = new_mtu;
result = 0;
}
return result;
}
static
void i2400m_tx_timeout(struct net_device *net_dev)
{
/*
* We might want to kick the device
*
* There is not much we can do though, as the device requires
* that we send the data aggregated. By the time we receive
* this, there might be data pending to be sent or not...
*/
net_dev->stats.tx_errors++;
}
/*
* Create a fake ethernet header
*
* For emulating an ethernet device, every received IP header has to
* be prefixed with an ethernet header. Fake it with the given
* protocol.
*/
static
void i2400m_rx_fake_eth_header(struct net_device *net_dev,
void *_eth_hdr, __be16 protocol)
{
struct i2400m *i2400m = net_dev_to_i2400m(net_dev);
struct ethhdr *eth_hdr = _eth_hdr;
memcpy(eth_hdr->h_dest, net_dev->dev_addr, sizeof(eth_hdr->h_dest));
memcpy(eth_hdr->h_source, i2400m->src_mac_addr,
sizeof(eth_hdr->h_source));
eth_hdr->h_proto = protocol;
}
/*
* i2400m_net_rx - pass a network packet to the stack
*
* @i2400m: device instance
* @skb_rx: the skb where the buffer pointed to by @buf is
* @i: 1 if payload is the only one
* @buf: pointer to the buffer containing the data
* @len: buffer's length
*
* This is only used now for the v1.3 firmware. It will be deprecated
* in >= 2.6.31.
*
* Note that due to firmware limitations, we don't have space to add
* an ethernet header, so we need to copy each packet. Firmware
* versions >= v1.4 fix this [see i2400m_net_erx()].
*
* We just clone the skb and set it up so that it's skb->data pointer
* points to "buf" and it's length.
*
* Note that if the payload is the last (or the only one) in a
* multi-payload message, we don't clone the SKB but just reuse it.
*
* This function is normally run from a thread context. However, we
* still use netif_rx() instead of netif_receive_skb() as was
* recommended in the mailing list. Reason is in some stress tests
* when sending/receiving a lot of data we seem to hit a softlock in
* the kernel's TCP implementation [aroudn tcp_delay_timer()]. Using
* netif_rx() took care of the issue.
*
* This is, of course, still open to do more research on why running
* with netif_receive_skb() hits this softlock. FIXME.
*
* FIXME: currently we don't do any efforts at distinguishing if what
* we got was an IPv4 or IPv6 header, to setup the protocol field
* correctly.
*/
void i2400m_net_rx(struct i2400m *i2400m, struct sk_buff *skb_rx,
unsigned i, const void *buf, int buf_len)
{
struct net_device *net_dev = i2400m->wimax_dev.net_dev;
struct device *dev = i2400m_dev(i2400m);
struct sk_buff *skb;
d_fnstart(2, dev, "(i2400m %p buf %p buf_len %d)\n",
i2400m, buf, buf_len);
if (i) {
skb = skb_get(skb_rx);
d_printf(2, dev, "RX: reusing first payload skb %p\n", skb);
skb_pull(skb, buf - (void *) skb->data);
skb_trim(skb, (void *) skb_end_pointer(skb) - buf);
} else {
/* Yes, this is bad -- a lot of overhead -- see
* comments at the top of the file */
skb = __netdev_alloc_skb(net_dev, buf_len, GFP_KERNEL);
if (skb == NULL) {
dev_err(dev, "NETRX: no memory to realloc skb\n");
net_dev->stats.rx_dropped++;
goto error_skb_realloc;
}
memcpy(skb_put(skb, buf_len), buf, buf_len);
}
i2400m_rx_fake_eth_header(i2400m->wimax_dev.net_dev,
skb->data - ETH_HLEN,
cpu_to_be16(ETH_P_IP));
skb_set_mac_header(skb, -ETH_HLEN);
skb->dev = i2400m->wimax_dev.net_dev;
skb->protocol = htons(ETH_P_IP);
net_dev->stats.rx_packets++;
net_dev->stats.rx_bytes += buf_len;
d_printf(3, dev, "NETRX: receiving %d bytes to network stack\n",
buf_len);
d_dump(4, dev, buf, buf_len);
netif_rx_ni(skb); /* see notes in function header */
error_skb_realloc:
d_fnend(2, dev, "(i2400m %p buf %p buf_len %d) = void\n",
i2400m, buf, buf_len);
}
/*
* i2400m_net_erx - pass a network packet to the stack (extended version)
*
* @i2400m: device descriptor
* @skb: the skb where the packet is - the skb should be set to point
* at the IP packet; this function will add ethernet headers if
* needed.
* @cs: packet type
*
* This is only used now for firmware >= v1.4. Note it is quite
* similar to i2400m_net_rx() (used only for v1.3 firmware).
*
* This function is normally run from a thread context. However, we
* still use netif_rx() instead of netif_receive_skb() as was
* recommended in the mailing list. Reason is in some stress tests
* when sending/receiving a lot of data we seem to hit a softlock in
* the kernel's TCP implementation [aroudn tcp_delay_timer()]. Using
* netif_rx() took care of the issue.
*
* This is, of course, still open to do more research on why running
* with netif_receive_skb() hits this softlock. FIXME.
*/
void i2400m_net_erx(struct i2400m *i2400m, struct sk_buff *skb,
enum i2400m_cs cs)
{
struct net_device *net_dev = i2400m->wimax_dev.net_dev;
struct device *dev = i2400m_dev(i2400m);
int protocol;
d_fnstart(2, dev, "(i2400m %p skb %p [%u] cs %d)\n",
i2400m, skb, skb->len, cs);
switch(cs) {
case I2400M_CS_IPV4_0:
case I2400M_CS_IPV4:
protocol = ETH_P_IP;
i2400m_rx_fake_eth_header(i2400m->wimax_dev.net_dev,
skb->data - ETH_HLEN,
cpu_to_be16(ETH_P_IP));
skb_set_mac_header(skb, -ETH_HLEN);
skb->dev = i2400m->wimax_dev.net_dev;
skb->protocol = htons(ETH_P_IP);
net_dev->stats.rx_packets++;
net_dev->stats.rx_bytes += skb->len;
break;
default:
dev_err(dev, "ERX: BUG? CS type %u unsupported\n", cs);
goto error;
}
d_printf(3, dev, "ERX: receiving %d bytes to the network stack\n",
skb->len);
d_dump(4, dev, skb->data, skb->len);
netif_rx_ni(skb); /* see notes in function header */
error:
d_fnend(2, dev, "(i2400m %p skb %p [%u] cs %d) = void\n",
i2400m, skb, skb->len, cs);
}
static const struct net_device_ops i2400m_netdev_ops = {
.ndo_open = i2400m_open,
.ndo_stop = i2400m_stop,
.ndo_start_xmit = i2400m_hard_start_xmit,
.ndo_tx_timeout = i2400m_tx_timeout,
.ndo_change_mtu = i2400m_change_mtu,
};
static void i2400m_get_drvinfo(struct net_device *net_dev,
struct ethtool_drvinfo *info)
{
struct i2400m *i2400m = net_dev_to_i2400m(net_dev);
strlcpy(info->driver, KBUILD_MODNAME, sizeof(info->driver));
strlcpy(info->fw_version, i2400m->fw_name ? : "",
sizeof(info->fw_version));
if (net_dev->dev.parent)
strlcpy(info->bus_info, dev_name(net_dev->dev.parent),
sizeof(info->bus_info));
}
static const struct ethtool_ops i2400m_ethtool_ops = {
.get_drvinfo = i2400m_get_drvinfo,
.get_link = ethtool_op_get_link,
};
/**
* i2400m_netdev_setup - Setup setup @net_dev's i2400m private data
*
* Called by alloc_netdev()
*/
void i2400m_netdev_setup(struct net_device *net_dev)
{
d_fnstart(3, NULL, "(net_dev %p)\n", net_dev);
ether_setup(net_dev);
net_dev->mtu = I2400M_MAX_MTU;
net_dev->tx_queue_len = I2400M_TX_QLEN;
net_dev->features =
NETIF_F_VLAN_CHALLENGED
| NETIF_F_HIGHDMA;
net_dev->flags =
IFF_NOARP /* i2400m is apure IP device */
& (~IFF_BROADCAST /* i2400m is P2P */
& ~IFF_MULTICAST);
net_dev->watchdog_timeo = I2400M_TX_TIMEOUT;
net_dev->netdev_ops = &i2400m_netdev_ops;
net_dev->ethtool_ops = &i2400m_ethtool_ops;
d_fnend(3, NULL, "(net_dev %p) = void\n", net_dev);
}
EXPORT_SYMBOL_GPL(i2400m_netdev_setup);
| gpl-2.0 |
prasidh09/cse506 | unionfs-3.10.y/drivers/acpi/acpica/utinit.c | 2623 | 4939 | /******************************************************************************
*
* Module Name: utinit - Common ACPI subsystem initialization
*
*****************************************************************************/
/*
* Copyright (C) 2000 - 2013, Intel Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* NO WARRANTY
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*/
#include <acpi/acpi.h>
#include "accommon.h"
#include "acnamesp.h"
#include "acevents.h"
#include "actables.h"
#define _COMPONENT ACPI_UTILITIES
ACPI_MODULE_NAME("utinit")
/* Local prototypes */
static void acpi_ut_terminate(void);
#if (!ACPI_REDUCED_HARDWARE)
static void acpi_ut_free_gpe_lists(void);
#else
#define acpi_ut_free_gpe_lists()
#endif /* !ACPI_REDUCED_HARDWARE */
#if (!ACPI_REDUCED_HARDWARE)
/******************************************************************************
*
* FUNCTION: acpi_ut_free_gpe_lists
*
* PARAMETERS: none
*
* RETURN: none
*
* DESCRIPTION: Free global GPE lists
*
******************************************************************************/
static void acpi_ut_free_gpe_lists(void)
{
struct acpi_gpe_block_info *gpe_block;
struct acpi_gpe_block_info *next_gpe_block;
struct acpi_gpe_xrupt_info *gpe_xrupt_info;
struct acpi_gpe_xrupt_info *next_gpe_xrupt_info;
/* Free global GPE blocks and related info structures */
gpe_xrupt_info = acpi_gbl_gpe_xrupt_list_head;
while (gpe_xrupt_info) {
gpe_block = gpe_xrupt_info->gpe_block_list_head;
while (gpe_block) {
next_gpe_block = gpe_block->next;
ACPI_FREE(gpe_block->event_info);
ACPI_FREE(gpe_block->register_info);
ACPI_FREE(gpe_block);
gpe_block = next_gpe_block;
}
next_gpe_xrupt_info = gpe_xrupt_info->next;
ACPI_FREE(gpe_xrupt_info);
gpe_xrupt_info = next_gpe_xrupt_info;
}
}
#endif /* !ACPI_REDUCED_HARDWARE */
/******************************************************************************
*
* FUNCTION: acpi_ut_terminate
*
* PARAMETERS: none
*
* RETURN: none
*
* DESCRIPTION: Free global memory
*
******************************************************************************/
static void acpi_ut_terminate(void)
{
ACPI_FUNCTION_TRACE(ut_terminate);
acpi_ut_free_gpe_lists();
acpi_ut_delete_address_lists();
return_VOID;
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_subsystem_shutdown
*
* PARAMETERS: None
*
* RETURN: None
*
* DESCRIPTION: Shutdown the various components. Do not delete the mutex
* objects here, because the AML debugger may be still running.
*
******************************************************************************/
void acpi_ut_subsystem_shutdown(void)
{
ACPI_FUNCTION_TRACE(ut_subsystem_shutdown);
#ifndef ACPI_ASL_COMPILER
/* Close the acpi_event Handling */
acpi_ev_terminate();
/* Delete any dynamic _OSI interfaces */
acpi_ut_interface_terminate();
#endif
/* Close the Namespace */
acpi_ns_terminate();
/* Delete the ACPI tables */
acpi_tb_terminate();
/* Close the globals */
acpi_ut_terminate();
/* Purge the local caches */
(void)acpi_ut_delete_caches();
return_VOID;
}
| gpl-2.0 |
KlinkOnE/android_kernel_kyleoc2 | drivers/media/video/gspca/m5602/m5602_ov7660.c | 3135 | 11578 | /*
* Driver for the ov7660 sensor
*
* Copyright (C) 2009 Erik Andrén
* Copyright (C) 2007 Ilyes Gouta. Based on the m5603x Linux Driver Project.
* Copyright (C) 2005 m5603x Linux Driver Project <m5602@x3ng.com.br>
*
* Portions of code to USB interface and ALi driver software,
* Copyright (c) 2006 Willem Duinker
* v4l2 interface modeled after the V4L2 driver
* for SN9C10x PC Camera Controllers
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, version 2.
*
*/
#include "m5602_ov7660.h"
static int ov7660_get_gain(struct gspca_dev *gspca_dev, __s32 *val);
static int ov7660_set_gain(struct gspca_dev *gspca_dev, __s32 val);
static int ov7660_get_auto_white_balance(struct gspca_dev *gspca_dev,
__s32 *val);
static int ov7660_set_auto_white_balance(struct gspca_dev *gspca_dev,
__s32 val);
static int ov7660_get_auto_gain(struct gspca_dev *gspca_dev, __s32 *val);
static int ov7660_set_auto_gain(struct gspca_dev *gspca_dev, __s32 val);
static int ov7660_get_auto_exposure(struct gspca_dev *gspca_dev, __s32 *val);
static int ov7660_set_auto_exposure(struct gspca_dev *gspca_dev, __s32 val);
static int ov7660_get_hflip(struct gspca_dev *gspca_dev, __s32 *val);
static int ov7660_set_hflip(struct gspca_dev *gspca_dev, __s32 val);
static int ov7660_get_vflip(struct gspca_dev *gspca_dev, __s32 *val);
static int ov7660_set_vflip(struct gspca_dev *gspca_dev, __s32 val);
static const struct ctrl ov7660_ctrls[] = {
#define GAIN_IDX 1
{
{
.id = V4L2_CID_GAIN,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "gain",
.minimum = 0x00,
.maximum = 0xff,
.step = 0x1,
.default_value = OV7660_DEFAULT_GAIN,
.flags = V4L2_CTRL_FLAG_SLIDER
},
.set = ov7660_set_gain,
.get = ov7660_get_gain
},
#define BLUE_BALANCE_IDX 2
#define RED_BALANCE_IDX 3
#define AUTO_WHITE_BALANCE_IDX 4
{
{
.id = V4L2_CID_AUTO_WHITE_BALANCE,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "auto white balance",
.minimum = 0,
.maximum = 1,
.step = 1,
.default_value = 1
},
.set = ov7660_set_auto_white_balance,
.get = ov7660_get_auto_white_balance
},
#define AUTO_GAIN_CTRL_IDX 5
{
{
.id = V4L2_CID_AUTOGAIN,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "auto gain control",
.minimum = 0,
.maximum = 1,
.step = 1,
.default_value = 1
},
.set = ov7660_set_auto_gain,
.get = ov7660_get_auto_gain
},
#define AUTO_EXPOSURE_IDX 6
{
{
.id = V4L2_CID_EXPOSURE_AUTO,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "auto exposure",
.minimum = 0,
.maximum = 1,
.step = 1,
.default_value = 1
},
.set = ov7660_set_auto_exposure,
.get = ov7660_get_auto_exposure
},
#define HFLIP_IDX 7
{
{
.id = V4L2_CID_HFLIP,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "horizontal flip",
.minimum = 0,
.maximum = 1,
.step = 1,
.default_value = 0
},
.set = ov7660_set_hflip,
.get = ov7660_get_hflip
},
#define VFLIP_IDX 8
{
{
.id = V4L2_CID_VFLIP,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "vertical flip",
.minimum = 0,
.maximum = 1,
.step = 1,
.default_value = 0
},
.set = ov7660_set_vflip,
.get = ov7660_get_vflip
},
};
static struct v4l2_pix_format ov7660_modes[] = {
{
640,
480,
V4L2_PIX_FMT_SBGGR8,
V4L2_FIELD_NONE,
.sizeimage =
640 * 480,
.bytesperline = 640,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = 0
}
};
static void ov7660_dump_registers(struct sd *sd);
int ov7660_probe(struct sd *sd)
{
int err = 0, i;
u8 prod_id = 0, ver_id = 0;
s32 *sensor_settings;
if (force_sensor) {
if (force_sensor == OV7660_SENSOR) {
info("Forcing an %s sensor", ov7660.name);
goto sensor_found;
}
/* If we want to force another sensor,
don't try to probe this one */
return -ENODEV;
}
/* Do the preinit */
for (i = 0; i < ARRAY_SIZE(preinit_ov7660) && !err; i++) {
u8 data[2];
if (preinit_ov7660[i][0] == BRIDGE) {
err = m5602_write_bridge(sd,
preinit_ov7660[i][1],
preinit_ov7660[i][2]);
} else {
data[0] = preinit_ov7660[i][2];
err = m5602_write_sensor(sd,
preinit_ov7660[i][1], data, 1);
}
}
if (err < 0)
return err;
if (m5602_read_sensor(sd, OV7660_PID, &prod_id, 1))
return -ENODEV;
if (m5602_read_sensor(sd, OV7660_VER, &ver_id, 1))
return -ENODEV;
info("Sensor reported 0x%x%x", prod_id, ver_id);
if ((prod_id == 0x76) && (ver_id == 0x60)) {
info("Detected a ov7660 sensor");
goto sensor_found;
}
return -ENODEV;
sensor_found:
sensor_settings = kmalloc(
ARRAY_SIZE(ov7660_ctrls) * sizeof(s32), GFP_KERNEL);
if (!sensor_settings)
return -ENOMEM;
sd->gspca_dev.cam.cam_mode = ov7660_modes;
sd->gspca_dev.cam.nmodes = ARRAY_SIZE(ov7660_modes);
sd->desc->ctrls = ov7660_ctrls;
sd->desc->nctrls = ARRAY_SIZE(ov7660_ctrls);
for (i = 0; i < ARRAY_SIZE(ov7660_ctrls); i++)
sensor_settings[i] = ov7660_ctrls[i].qctrl.default_value;
sd->sensor_priv = sensor_settings;
return 0;
}
int ov7660_init(struct sd *sd)
{
int i, err = 0;
s32 *sensor_settings = sd->sensor_priv;
/* Init the sensor */
for (i = 0; i < ARRAY_SIZE(init_ov7660); i++) {
u8 data[2];
if (init_ov7660[i][0] == BRIDGE) {
err = m5602_write_bridge(sd,
init_ov7660[i][1],
init_ov7660[i][2]);
} else {
data[0] = init_ov7660[i][2];
err = m5602_write_sensor(sd,
init_ov7660[i][1], data, 1);
}
}
if (dump_sensor)
ov7660_dump_registers(sd);
err = ov7660_set_gain(&sd->gspca_dev, sensor_settings[GAIN_IDX]);
if (err < 0)
return err;
err = ov7660_set_auto_white_balance(&sd->gspca_dev,
sensor_settings[AUTO_WHITE_BALANCE_IDX]);
if (err < 0)
return err;
err = ov7660_set_auto_gain(&sd->gspca_dev,
sensor_settings[AUTO_GAIN_CTRL_IDX]);
if (err < 0)
return err;
err = ov7660_set_auto_exposure(&sd->gspca_dev,
sensor_settings[AUTO_EXPOSURE_IDX]);
if (err < 0)
return err;
err = ov7660_set_hflip(&sd->gspca_dev,
sensor_settings[HFLIP_IDX]);
if (err < 0)
return err;
err = ov7660_set_vflip(&sd->gspca_dev,
sensor_settings[VFLIP_IDX]);
return err;
}
int ov7660_start(struct sd *sd)
{
return 0;
}
int ov7660_stop(struct sd *sd)
{
return 0;
}
void ov7660_disconnect(struct sd *sd)
{
ov7660_stop(sd);
sd->sensor = NULL;
kfree(sd->sensor_priv);
}
static int ov7660_get_gain(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
*val = sensor_settings[GAIN_IDX];
PDEBUG(D_V4L2, "Read gain %d", *val);
return 0;
}
static int ov7660_set_gain(struct gspca_dev *gspca_dev, __s32 val)
{
int err;
u8 i2c_data;
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
PDEBUG(D_V4L2, "Setting gain to %d", val);
sensor_settings[GAIN_IDX] = val;
err = m5602_write_sensor(sd, OV7660_GAIN, &i2c_data, 1);
return err;
}
static int ov7660_get_auto_white_balance(struct gspca_dev *gspca_dev,
__s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
*val = sensor_settings[AUTO_WHITE_BALANCE_IDX];
return 0;
}
static int ov7660_set_auto_white_balance(struct gspca_dev *gspca_dev,
__s32 val)
{
int err;
u8 i2c_data;
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
PDEBUG(D_V4L2, "Set auto white balance to %d", val);
sensor_settings[AUTO_WHITE_BALANCE_IDX] = val;
err = m5602_read_sensor(sd, OV7660_COM8, &i2c_data, 1);
if (err < 0)
return err;
i2c_data = ((i2c_data & 0xfd) | ((val & 0x01) << 1));
err = m5602_write_sensor(sd, OV7660_COM8, &i2c_data, 1);
return err;
}
static int ov7660_get_auto_gain(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
*val = sensor_settings[AUTO_GAIN_CTRL_IDX];
PDEBUG(D_V4L2, "Read auto gain control %d", *val);
return 0;
}
static int ov7660_set_auto_gain(struct gspca_dev *gspca_dev, __s32 val)
{
int err;
u8 i2c_data;
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
PDEBUG(D_V4L2, "Set auto gain control to %d", val);
sensor_settings[AUTO_GAIN_CTRL_IDX] = val;
err = m5602_read_sensor(sd, OV7660_COM8, &i2c_data, 1);
if (err < 0)
return err;
i2c_data = ((i2c_data & 0xfb) | ((val & 0x01) << 2));
return m5602_write_sensor(sd, OV7660_COM8, &i2c_data, 1);
}
static int ov7660_get_auto_exposure(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
*val = sensor_settings[AUTO_EXPOSURE_IDX];
PDEBUG(D_V4L2, "Read auto exposure control %d", *val);
return 0;
}
static int ov7660_set_auto_exposure(struct gspca_dev *gspca_dev,
__s32 val)
{
int err;
u8 i2c_data;
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
PDEBUG(D_V4L2, "Set auto exposure control to %d", val);
sensor_settings[AUTO_EXPOSURE_IDX] = val;
err = m5602_read_sensor(sd, OV7660_COM8, &i2c_data, 1);
if (err < 0)
return err;
i2c_data = ((i2c_data & 0xfe) | ((val & 0x01) << 0));
return m5602_write_sensor(sd, OV7660_COM8, &i2c_data, 1);
}
static int ov7660_get_hflip(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
*val = sensor_settings[HFLIP_IDX];
PDEBUG(D_V4L2, "Read horizontal flip %d", *val);
return 0;
}
static int ov7660_set_hflip(struct gspca_dev *gspca_dev, __s32 val)
{
int err;
u8 i2c_data;
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
PDEBUG(D_V4L2, "Set horizontal flip to %d", val);
sensor_settings[HFLIP_IDX] = val;
i2c_data = ((val & 0x01) << 5) |
(sensor_settings[VFLIP_IDX] << 4);
err = m5602_write_sensor(sd, OV7660_MVFP, &i2c_data, 1);
return err;
}
static int ov7660_get_vflip(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
*val = sensor_settings[VFLIP_IDX];
PDEBUG(D_V4L2, "Read vertical flip %d", *val);
return 0;
}
static int ov7660_set_vflip(struct gspca_dev *gspca_dev, __s32 val)
{
int err;
u8 i2c_data;
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
PDEBUG(D_V4L2, "Set vertical flip to %d", val);
sensor_settings[VFLIP_IDX] = val;
i2c_data = ((val & 0x01) << 4) | (sensor_settings[VFLIP_IDX] << 5);
err = m5602_write_sensor(sd, OV7660_MVFP, &i2c_data, 1);
if (err < 0)
return err;
/* When vflip is toggled we need to readjust the bridge hsync/vsync */
if (gspca_dev->streaming)
err = ov7660_start(sd);
return err;
}
static void ov7660_dump_registers(struct sd *sd)
{
int address;
info("Dumping the ov7660 register state");
for (address = 0; address < 0xa9; address++) {
u8 value;
m5602_read_sensor(sd, address, &value, 1);
info("register 0x%x contains 0x%x",
address, value);
}
info("ov7660 register state dump complete");
info("Probing for which registers that are read/write");
for (address = 0; address < 0xff; address++) {
u8 old_value, ctrl_value;
u8 test_value[2] = {0xff, 0xff};
m5602_read_sensor(sd, address, &old_value, 1);
m5602_write_sensor(sd, address, test_value, 1);
m5602_read_sensor(sd, address, &ctrl_value, 1);
if (ctrl_value == test_value[0])
info("register 0x%x is writeable", address);
else
info("register 0x%x is read only", address);
/* Restore original value */
m5602_write_sensor(sd, address, &old_value, 1);
}
}
| gpl-2.0 |
omnirom/android_kernel_samsung_espresso10 | drivers/media/video/gspca/m5602/m5602_s5k4aa.c | 3135 | 17391 | /*
* Driver for the s5k4aa sensor
*
* Copyright (C) 2008 Erik Andrén
* Copyright (C) 2007 Ilyes Gouta. Based on the m5603x Linux Driver Project.
* Copyright (C) 2005 m5603x Linux Driver Project <m5602@x3ng.com.br>
*
* Portions of code to USB interface and ALi driver software,
* Copyright (c) 2006 Willem Duinker
* v4l2 interface modeled after the V4L2 driver
* for SN9C10x PC Camera Controllers
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, version 2.
*
*/
#include "m5602_s5k4aa.h"
static int s5k4aa_get_exposure(struct gspca_dev *gspca_dev, __s32 *val);
static int s5k4aa_set_exposure(struct gspca_dev *gspca_dev, __s32 val);
static int s5k4aa_get_vflip(struct gspca_dev *gspca_dev, __s32 *val);
static int s5k4aa_set_vflip(struct gspca_dev *gspca_dev, __s32 val);
static int s5k4aa_get_hflip(struct gspca_dev *gspca_dev, __s32 *val);
static int s5k4aa_set_hflip(struct gspca_dev *gspca_dev, __s32 val);
static int s5k4aa_get_gain(struct gspca_dev *gspca_dev, __s32 *val);
static int s5k4aa_set_gain(struct gspca_dev *gspca_dev, __s32 val);
static int s5k4aa_get_noise(struct gspca_dev *gspca_dev, __s32 *val);
static int s5k4aa_set_noise(struct gspca_dev *gspca_dev, __s32 val);
static int s5k4aa_get_brightness(struct gspca_dev *gspca_dev, __s32 *val);
static int s5k4aa_set_brightness(struct gspca_dev *gspca_dev, __s32 val);
static
const
struct dmi_system_id s5k4aa_vflip_dmi_table[] = {
{
.ident = "BRUNEINIT",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "BRUNENIT"),
DMI_MATCH(DMI_PRODUCT_NAME, "BRUNENIT"),
DMI_MATCH(DMI_BOARD_VERSION, "00030D0000000001")
}
}, {
.ident = "Fujitsu-Siemens Amilo Xa 2528",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "FUJITSU SIEMENS"),
DMI_MATCH(DMI_PRODUCT_NAME, "AMILO Xa 2528")
}
}, {
.ident = "Fujitsu-Siemens Amilo Xi 2428",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "FUJITSU SIEMENS"),
DMI_MATCH(DMI_PRODUCT_NAME, "AMILO Xi 2428")
}
}, {
.ident = "Fujitsu-Siemens Amilo Xi 2528",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "FUJITSU SIEMENS"),
DMI_MATCH(DMI_PRODUCT_NAME, "AMILO Xi 2528")
}
}, {
.ident = "Fujitsu-Siemens Amilo Xi 2550",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "FUJITSU SIEMENS"),
DMI_MATCH(DMI_PRODUCT_NAME, "AMILO Xi 2550")
}
}, {
.ident = "Fujitsu-Siemens Amilo Pa 2548",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "FUJITSU SIEMENS"),
DMI_MATCH(DMI_PRODUCT_NAME, "AMILO Pa 2548")
}
}, {
.ident = "MSI GX700",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Micro-Star International"),
DMI_MATCH(DMI_PRODUCT_NAME, "GX700"),
DMI_MATCH(DMI_BIOS_DATE, "12/02/2008")
}
}, {
.ident = "MSI GX700",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Micro-Star International"),
DMI_MATCH(DMI_PRODUCT_NAME, "GX700"),
DMI_MATCH(DMI_BIOS_DATE, "07/26/2007")
}
}, {
.ident = "MSI GX700",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Micro-Star International"),
DMI_MATCH(DMI_PRODUCT_NAME, "GX700"),
DMI_MATCH(DMI_BIOS_DATE, "07/19/2007")
}
}, {
.ident = "MSI GX700/GX705/EX700",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Micro-Star International"),
DMI_MATCH(DMI_PRODUCT_NAME, "GX700/GX705/EX700")
}
}, {
.ident = "MSI L735",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Micro-Star International"),
DMI_MATCH(DMI_PRODUCT_NAME, "MS-1717X")
}
}, {
.ident = "Lenovo Y300",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "L3000 Y300"),
DMI_MATCH(DMI_PRODUCT_NAME, "Y300")
}
},
{ }
};
static struct v4l2_pix_format s5k4aa_modes[] = {
{
640,
480,
V4L2_PIX_FMT_SBGGR8,
V4L2_FIELD_NONE,
.sizeimage =
640 * 480,
.bytesperline = 640,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = 0
},
{
1280,
1024,
V4L2_PIX_FMT_SBGGR8,
V4L2_FIELD_NONE,
.sizeimage =
1280 * 1024,
.bytesperline = 1280,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = 0
}
};
static const struct ctrl s5k4aa_ctrls[] = {
#define VFLIP_IDX 0
{
{
.id = V4L2_CID_VFLIP,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "vertical flip",
.minimum = 0,
.maximum = 1,
.step = 1,
.default_value = 0
},
.set = s5k4aa_set_vflip,
.get = s5k4aa_get_vflip
},
#define HFLIP_IDX 1
{
{
.id = V4L2_CID_HFLIP,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "horizontal flip",
.minimum = 0,
.maximum = 1,
.step = 1,
.default_value = 0
},
.set = s5k4aa_set_hflip,
.get = s5k4aa_get_hflip
},
#define GAIN_IDX 2
{
{
.id = V4L2_CID_GAIN,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Gain",
.minimum = 0,
.maximum = 127,
.step = 1,
.default_value = S5K4AA_DEFAULT_GAIN,
.flags = V4L2_CTRL_FLAG_SLIDER
},
.set = s5k4aa_set_gain,
.get = s5k4aa_get_gain
},
#define EXPOSURE_IDX 3
{
{
.id = V4L2_CID_EXPOSURE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Exposure",
.minimum = 13,
.maximum = 0xfff,
.step = 1,
.default_value = 0x100,
.flags = V4L2_CTRL_FLAG_SLIDER
},
.set = s5k4aa_set_exposure,
.get = s5k4aa_get_exposure
},
#define NOISE_SUPP_IDX 4
{
{
.id = V4L2_CID_PRIVATE_BASE,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "Noise suppression (smoothing)",
.minimum = 0,
.maximum = 1,
.step = 1,
.default_value = 1,
},
.set = s5k4aa_set_noise,
.get = s5k4aa_get_noise
},
#define BRIGHTNESS_IDX 5
{
{
.id = V4L2_CID_BRIGHTNESS,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Brightness",
.minimum = 0,
.maximum = 0x1f,
.step = 1,
.default_value = S5K4AA_DEFAULT_BRIGHTNESS,
},
.set = s5k4aa_set_brightness,
.get = s5k4aa_get_brightness
},
};
static void s5k4aa_dump_registers(struct sd *sd);
int s5k4aa_probe(struct sd *sd)
{
u8 prod_id[6] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
const u8 expected_prod_id[6] = {0x00, 0x10, 0x00, 0x4b, 0x33, 0x75};
int i, err = 0;
s32 *sensor_settings;
if (force_sensor) {
if (force_sensor == S5K4AA_SENSOR) {
info("Forcing a %s sensor", s5k4aa.name);
goto sensor_found;
}
/* If we want to force another sensor, don't try to probe this
* one */
return -ENODEV;
}
PDEBUG(D_PROBE, "Probing for a s5k4aa sensor");
/* Preinit the sensor */
for (i = 0; i < ARRAY_SIZE(preinit_s5k4aa) && !err; i++) {
u8 data[2] = {0x00, 0x00};
switch (preinit_s5k4aa[i][0]) {
case BRIDGE:
err = m5602_write_bridge(sd,
preinit_s5k4aa[i][1],
preinit_s5k4aa[i][2]);
break;
case SENSOR:
data[0] = preinit_s5k4aa[i][2];
err = m5602_write_sensor(sd,
preinit_s5k4aa[i][1],
data, 1);
break;
case SENSOR_LONG:
data[0] = preinit_s5k4aa[i][2];
data[1] = preinit_s5k4aa[i][3];
err = m5602_write_sensor(sd,
preinit_s5k4aa[i][1],
data, 2);
break;
default:
info("Invalid stream command, exiting init");
return -EINVAL;
}
}
/* Test some registers, but we don't know their exact meaning yet */
if (m5602_read_sensor(sd, 0x00, prod_id, 2))
return -ENODEV;
if (m5602_read_sensor(sd, 0x02, prod_id+2, 2))
return -ENODEV;
if (m5602_read_sensor(sd, 0x04, prod_id+4, 2))
return -ENODEV;
if (memcmp(prod_id, expected_prod_id, sizeof(prod_id)))
return -ENODEV;
else
info("Detected a s5k4aa sensor");
sensor_found:
sensor_settings = kmalloc(
ARRAY_SIZE(s5k4aa_ctrls) * sizeof(s32), GFP_KERNEL);
if (!sensor_settings)
return -ENOMEM;
sd->gspca_dev.cam.cam_mode = s5k4aa_modes;
sd->gspca_dev.cam.nmodes = ARRAY_SIZE(s5k4aa_modes);
sd->desc->ctrls = s5k4aa_ctrls;
sd->desc->nctrls = ARRAY_SIZE(s5k4aa_ctrls);
for (i = 0; i < ARRAY_SIZE(s5k4aa_ctrls); i++)
sensor_settings[i] = s5k4aa_ctrls[i].qctrl.default_value;
sd->sensor_priv = sensor_settings;
return 0;
}
int s5k4aa_start(struct sd *sd)
{
int i, err = 0;
u8 data[2];
struct cam *cam = &sd->gspca_dev.cam;
s32 *sensor_settings = sd->sensor_priv;
switch (cam->cam_mode[sd->gspca_dev.curr_mode].width) {
case 1280:
PDEBUG(D_V4L2, "Configuring camera for SXGA mode");
for (i = 0; i < ARRAY_SIZE(SXGA_s5k4aa); i++) {
switch (SXGA_s5k4aa[i][0]) {
case BRIDGE:
err = m5602_write_bridge(sd,
SXGA_s5k4aa[i][1],
SXGA_s5k4aa[i][2]);
break;
case SENSOR:
data[0] = SXGA_s5k4aa[i][2];
err = m5602_write_sensor(sd,
SXGA_s5k4aa[i][1],
data, 1);
break;
case SENSOR_LONG:
data[0] = SXGA_s5k4aa[i][2];
data[1] = SXGA_s5k4aa[i][3];
err = m5602_write_sensor(sd,
SXGA_s5k4aa[i][1],
data, 2);
break;
default:
err("Invalid stream command, exiting init");
return -EINVAL;
}
}
err = s5k4aa_set_noise(&sd->gspca_dev, 0);
if (err < 0)
return err;
break;
case 640:
PDEBUG(D_V4L2, "Configuring camera for VGA mode");
for (i = 0; i < ARRAY_SIZE(VGA_s5k4aa); i++) {
switch (VGA_s5k4aa[i][0]) {
case BRIDGE:
err = m5602_write_bridge(sd,
VGA_s5k4aa[i][1],
VGA_s5k4aa[i][2]);
break;
case SENSOR:
data[0] = VGA_s5k4aa[i][2];
err = m5602_write_sensor(sd,
VGA_s5k4aa[i][1],
data, 1);
break;
case SENSOR_LONG:
data[0] = VGA_s5k4aa[i][2];
data[1] = VGA_s5k4aa[i][3];
err = m5602_write_sensor(sd,
VGA_s5k4aa[i][1],
data, 2);
break;
default:
err("Invalid stream command, exiting init");
return -EINVAL;
}
}
err = s5k4aa_set_noise(&sd->gspca_dev, 1);
if (err < 0)
return err;
break;
}
if (err < 0)
return err;
err = s5k4aa_set_exposure(&sd->gspca_dev,
sensor_settings[EXPOSURE_IDX]);
if (err < 0)
return err;
err = s5k4aa_set_gain(&sd->gspca_dev, sensor_settings[GAIN_IDX]);
if (err < 0)
return err;
err = s5k4aa_set_brightness(&sd->gspca_dev,
sensor_settings[BRIGHTNESS_IDX]);
if (err < 0)
return err;
err = s5k4aa_set_noise(&sd->gspca_dev, sensor_settings[NOISE_SUPP_IDX]);
if (err < 0)
return err;
err = s5k4aa_set_vflip(&sd->gspca_dev, sensor_settings[VFLIP_IDX]);
if (err < 0)
return err;
return s5k4aa_set_hflip(&sd->gspca_dev, sensor_settings[HFLIP_IDX]);
}
int s5k4aa_init(struct sd *sd)
{
int i, err = 0;
for (i = 0; i < ARRAY_SIZE(init_s5k4aa) && !err; i++) {
u8 data[2] = {0x00, 0x00};
switch (init_s5k4aa[i][0]) {
case BRIDGE:
err = m5602_write_bridge(sd,
init_s5k4aa[i][1],
init_s5k4aa[i][2]);
break;
case SENSOR:
data[0] = init_s5k4aa[i][2];
err = m5602_write_sensor(sd,
init_s5k4aa[i][1], data, 1);
break;
case SENSOR_LONG:
data[0] = init_s5k4aa[i][2];
data[1] = init_s5k4aa[i][3];
err = m5602_write_sensor(sd,
init_s5k4aa[i][1], data, 2);
break;
default:
info("Invalid stream command, exiting init");
return -EINVAL;
}
}
if (dump_sensor)
s5k4aa_dump_registers(sd);
return err;
}
static int s5k4aa_get_exposure(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
*val = sensor_settings[EXPOSURE_IDX];
PDEBUG(D_V4L2, "Read exposure %d", *val);
return 0;
}
static int s5k4aa_set_exposure(struct gspca_dev *gspca_dev, __s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
u8 data = S5K4AA_PAGE_MAP_2;
int err;
sensor_settings[EXPOSURE_IDX] = val;
PDEBUG(D_V4L2, "Set exposure to %d", val);
err = m5602_write_sensor(sd, S5K4AA_PAGE_MAP, &data, 1);
if (err < 0)
return err;
data = (val >> 8) & 0xff;
err = m5602_write_sensor(sd, S5K4AA_EXPOSURE_HI, &data, 1);
if (err < 0)
return err;
data = val & 0xff;
err = m5602_write_sensor(sd, S5K4AA_EXPOSURE_LO, &data, 1);
return err;
}
static int s5k4aa_get_vflip(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
*val = sensor_settings[VFLIP_IDX];
PDEBUG(D_V4L2, "Read vertical flip %d", *val);
return 0;
}
static int s5k4aa_set_vflip(struct gspca_dev *gspca_dev, __s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
u8 data = S5K4AA_PAGE_MAP_2;
int err;
sensor_settings[VFLIP_IDX] = val;
PDEBUG(D_V4L2, "Set vertical flip to %d", val);
err = m5602_write_sensor(sd, S5K4AA_PAGE_MAP, &data, 1);
if (err < 0)
return err;
err = m5602_read_sensor(sd, S5K4AA_READ_MODE, &data, 1);
if (err < 0)
return err;
if (dmi_check_system(s5k4aa_vflip_dmi_table))
val = !val;
data = ((data & ~S5K4AA_RM_V_FLIP) | ((val & 0x01) << 7));
err = m5602_write_sensor(sd, S5K4AA_READ_MODE, &data, 1);
if (err < 0)
return err;
err = m5602_read_sensor(sd, S5K4AA_ROWSTART_LO, &data, 1);
if (err < 0)
return err;
if (val)
data &= 0xfe;
else
data |= 0x01;
err = m5602_write_sensor(sd, S5K4AA_ROWSTART_LO, &data, 1);
return err;
}
static int s5k4aa_get_hflip(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
*val = sensor_settings[HFLIP_IDX];
PDEBUG(D_V4L2, "Read horizontal flip %d", *val);
return 0;
}
static int s5k4aa_set_hflip(struct gspca_dev *gspca_dev, __s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
u8 data = S5K4AA_PAGE_MAP_2;
int err;
sensor_settings[HFLIP_IDX] = val;
PDEBUG(D_V4L2, "Set horizontal flip to %d", val);
err = m5602_write_sensor(sd, S5K4AA_PAGE_MAP, &data, 1);
if (err < 0)
return err;
err = m5602_read_sensor(sd, S5K4AA_READ_MODE, &data, 1);
if (err < 0)
return err;
if (dmi_check_system(s5k4aa_vflip_dmi_table))
val = !val;
data = ((data & ~S5K4AA_RM_H_FLIP) | ((val & 0x01) << 6));
err = m5602_write_sensor(sd, S5K4AA_READ_MODE, &data, 1);
if (err < 0)
return err;
err = m5602_read_sensor(sd, S5K4AA_COLSTART_LO, &data, 1);
if (err < 0)
return err;
if (val)
data &= 0xfe;
else
data |= 0x01;
err = m5602_write_sensor(sd, S5K4AA_COLSTART_LO, &data, 1);
return err;
}
static int s5k4aa_get_gain(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
*val = sensor_settings[GAIN_IDX];
PDEBUG(D_V4L2, "Read gain %d", *val);
return 0;
}
static int s5k4aa_set_gain(struct gspca_dev *gspca_dev, __s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
u8 data = S5K4AA_PAGE_MAP_2;
int err;
sensor_settings[GAIN_IDX] = val;
PDEBUG(D_V4L2, "Set gain to %d", val);
err = m5602_write_sensor(sd, S5K4AA_PAGE_MAP, &data, 1);
if (err < 0)
return err;
data = val & 0xff;
err = m5602_write_sensor(sd, S5K4AA_GAIN, &data, 1);
return err;
}
static int s5k4aa_get_brightness(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
*val = sensor_settings[BRIGHTNESS_IDX];
PDEBUG(D_V4L2, "Read brightness %d", *val);
return 0;
}
static int s5k4aa_set_brightness(struct gspca_dev *gspca_dev, __s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
u8 data = S5K4AA_PAGE_MAP_2;
int err;
sensor_settings[BRIGHTNESS_IDX] = val;
PDEBUG(D_V4L2, "Set brightness to %d", val);
err = m5602_write_sensor(sd, S5K4AA_PAGE_MAP, &data, 1);
if (err < 0)
return err;
data = val & 0xff;
return m5602_write_sensor(sd, S5K4AA_BRIGHTNESS, &data, 1);
}
static int s5k4aa_get_noise(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
*val = sensor_settings[NOISE_SUPP_IDX];
PDEBUG(D_V4L2, "Read noise %d", *val);
return 0;
}
static int s5k4aa_set_noise(struct gspca_dev *gspca_dev, __s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
s32 *sensor_settings = sd->sensor_priv;
u8 data = S5K4AA_PAGE_MAP_2;
int err;
sensor_settings[NOISE_SUPP_IDX] = val;
PDEBUG(D_V4L2, "Set noise to %d", val);
err = m5602_write_sensor(sd, S5K4AA_PAGE_MAP, &data, 1);
if (err < 0)
return err;
data = val & 0x01;
return m5602_write_sensor(sd, S5K4AA_NOISE_SUPP, &data, 1);
}
void s5k4aa_disconnect(struct sd *sd)
{
sd->sensor = NULL;
kfree(sd->sensor_priv);
}
static void s5k4aa_dump_registers(struct sd *sd)
{
int address;
u8 page, old_page;
m5602_read_sensor(sd, S5K4AA_PAGE_MAP, &old_page, 1);
for (page = 0; page < 16; page++) {
m5602_write_sensor(sd, S5K4AA_PAGE_MAP, &page, 1);
info("Dumping the s5k4aa register state for page 0x%x", page);
for (address = 0; address <= 0xff; address++) {
u8 value = 0;
m5602_read_sensor(sd, address, &value, 1);
info("register 0x%x contains 0x%x",
address, value);
}
}
info("s5k4aa register state dump complete");
for (page = 0; page < 16; page++) {
m5602_write_sensor(sd, S5K4AA_PAGE_MAP, &page, 1);
info("Probing for which registers that are "
"read/write for page 0x%x", page);
for (address = 0; address <= 0xff; address++) {
u8 old_value, ctrl_value, test_value = 0xff;
m5602_read_sensor(sd, address, &old_value, 1);
m5602_write_sensor(sd, address, &test_value, 1);
m5602_read_sensor(sd, address, &ctrl_value, 1);
if (ctrl_value == test_value)
info("register 0x%x is writeable", address);
else
info("register 0x%x is read only", address);
/* Restore original value */
m5602_write_sensor(sd, address, &old_value, 1);
}
}
info("Read/write register probing complete");
m5602_write_sensor(sd, S5K4AA_PAGE_MAP, &old_page, 1);
}
| gpl-2.0 |
Nothing-Dev/android_kernel_motorola_msm8610 | arch/x86/kernel/dumpstack.c | 4671 | 7559 | /*
* Copyright (C) 1991, 1992 Linus Torvalds
* Copyright (C) 2000, 2001, 2002 Andi Kleen, SuSE Labs
*/
#include <linux/kallsyms.h>
#include <linux/kprobes.h>
#include <linux/uaccess.h>
#include <linux/utsname.h>
#include <linux/hardirq.h>
#include <linux/kdebug.h>
#include <linux/module.h>
#include <linux/ptrace.h>
#include <linux/ftrace.h>
#include <linux/kexec.h>
#include <linux/bug.h>
#include <linux/nmi.h>
#include <linux/sysfs.h>
#include <asm/stacktrace.h>
int panic_on_unrecovered_nmi;
int panic_on_io_nmi;
unsigned int code_bytes = 64;
int kstack_depth_to_print = 3 * STACKSLOTS_PER_LINE;
static int die_counter;
void printk_address(unsigned long address, int reliable)
{
printk(" [<%p>] %s%pB\n", (void *) address,
reliable ? "" : "? ", (void *) address);
}
#ifdef CONFIG_FUNCTION_GRAPH_TRACER
static void
print_ftrace_graph_addr(unsigned long addr, void *data,
const struct stacktrace_ops *ops,
struct thread_info *tinfo, int *graph)
{
struct task_struct *task;
unsigned long ret_addr;
int index;
if (addr != (unsigned long)return_to_handler)
return;
task = tinfo->task;
index = task->curr_ret_stack;
if (!task->ret_stack || index < *graph)
return;
index -= *graph;
ret_addr = task->ret_stack[index].ret;
ops->address(data, ret_addr, 1);
(*graph)++;
}
#else
static inline void
print_ftrace_graph_addr(unsigned long addr, void *data,
const struct stacktrace_ops *ops,
struct thread_info *tinfo, int *graph)
{ }
#endif
/*
* x86-64 can have up to three kernel stacks:
* process stack
* interrupt stack
* severe exception (double fault, nmi, stack fault, debug, mce) hardware stack
*/
static inline int valid_stack_ptr(struct thread_info *tinfo,
void *p, unsigned int size, void *end)
{
void *t = tinfo;
if (end) {
if (p < end && p >= (end-THREAD_SIZE))
return 1;
else
return 0;
}
return p > t && p < t + THREAD_SIZE - size;
}
unsigned long
print_context_stack(struct thread_info *tinfo,
unsigned long *stack, unsigned long bp,
const struct stacktrace_ops *ops, void *data,
unsigned long *end, int *graph)
{
struct stack_frame *frame = (struct stack_frame *)bp;
while (valid_stack_ptr(tinfo, stack, sizeof(*stack), end)) {
unsigned long addr;
addr = *stack;
if (__kernel_text_address(addr)) {
if ((unsigned long) stack == bp + sizeof(long)) {
ops->address(data, addr, 1);
frame = frame->next_frame;
bp = (unsigned long) frame;
} else {
ops->address(data, addr, 0);
}
print_ftrace_graph_addr(addr, data, ops, tinfo, graph);
}
stack++;
}
return bp;
}
EXPORT_SYMBOL_GPL(print_context_stack);
unsigned long
print_context_stack_bp(struct thread_info *tinfo,
unsigned long *stack, unsigned long bp,
const struct stacktrace_ops *ops, void *data,
unsigned long *end, int *graph)
{
struct stack_frame *frame = (struct stack_frame *)bp;
unsigned long *ret_addr = &frame->return_address;
while (valid_stack_ptr(tinfo, ret_addr, sizeof(*ret_addr), end)) {
unsigned long addr = *ret_addr;
if (!__kernel_text_address(addr))
break;
ops->address(data, addr, 1);
frame = frame->next_frame;
ret_addr = &frame->return_address;
print_ftrace_graph_addr(addr, data, ops, tinfo, graph);
}
return (unsigned long)frame;
}
EXPORT_SYMBOL_GPL(print_context_stack_bp);
static int print_trace_stack(void *data, char *name)
{
printk("%s <%s> ", (char *)data, name);
return 0;
}
/*
* Print one address/symbol entries per line.
*/
static void print_trace_address(void *data, unsigned long addr, int reliable)
{
touch_nmi_watchdog();
printk(data);
printk_address(addr, reliable);
}
static const struct stacktrace_ops print_trace_ops = {
.stack = print_trace_stack,
.address = print_trace_address,
.walk_stack = print_context_stack,
};
void
show_trace_log_lvl(struct task_struct *task, struct pt_regs *regs,
unsigned long *stack, unsigned long bp, char *log_lvl)
{
printk("%sCall Trace:\n", log_lvl);
dump_trace(task, regs, stack, bp, &print_trace_ops, log_lvl);
}
void show_trace(struct task_struct *task, struct pt_regs *regs,
unsigned long *stack, unsigned long bp)
{
show_trace_log_lvl(task, regs, stack, bp, "");
}
void show_stack(struct task_struct *task, unsigned long *sp)
{
show_stack_log_lvl(task, NULL, sp, 0, "");
}
/*
* The architecture-independent dump_stack generator
*/
void dump_stack(void)
{
unsigned long bp;
unsigned long stack;
bp = stack_frame(current, NULL);
printk("Pid: %d, comm: %.20s %s %s %.*s\n",
current->pid, current->comm, print_tainted(),
init_utsname()->release,
(int)strcspn(init_utsname()->version, " "),
init_utsname()->version);
show_trace(NULL, NULL, &stack, bp);
}
EXPORT_SYMBOL(dump_stack);
static arch_spinlock_t die_lock = __ARCH_SPIN_LOCK_UNLOCKED;
static int die_owner = -1;
static unsigned int die_nest_count;
unsigned __kprobes long oops_begin(void)
{
int cpu;
unsigned long flags;
oops_enter();
/* racy, but better than risking deadlock. */
raw_local_irq_save(flags);
cpu = smp_processor_id();
if (!arch_spin_trylock(&die_lock)) {
if (cpu == die_owner)
/* nested oops. should stop eventually */;
else
arch_spin_lock(&die_lock);
}
die_nest_count++;
die_owner = cpu;
console_verbose();
bust_spinlocks(1);
return flags;
}
EXPORT_SYMBOL_GPL(oops_begin);
void __kprobes oops_end(unsigned long flags, struct pt_regs *regs, int signr)
{
if (regs && kexec_should_crash(current))
crash_kexec(regs);
bust_spinlocks(0);
die_owner = -1;
add_taint(TAINT_DIE);
die_nest_count--;
if (!die_nest_count)
/* Nest count reaches zero, release the lock. */
arch_spin_unlock(&die_lock);
raw_local_irq_restore(flags);
oops_exit();
if (!signr)
return;
if (in_interrupt())
panic("Fatal exception in interrupt");
if (panic_on_oops)
panic("Fatal exception");
do_exit(signr);
}
int __kprobes __die(const char *str, struct pt_regs *regs, long err)
{
#ifdef CONFIG_X86_32
unsigned short ss;
unsigned long sp;
#endif
printk(KERN_DEFAULT
"%s: %04lx [#%d] ", str, err & 0xffff, ++die_counter);
#ifdef CONFIG_PREEMPT
printk("PREEMPT ");
#endif
#ifdef CONFIG_SMP
printk("SMP ");
#endif
#ifdef CONFIG_DEBUG_PAGEALLOC
printk("DEBUG_PAGEALLOC");
#endif
printk("\n");
if (notify_die(DIE_OOPS, str, regs, err,
current->thread.trap_nr, SIGSEGV) == NOTIFY_STOP)
return 1;
show_registers(regs);
#ifdef CONFIG_X86_32
if (user_mode_vm(regs)) {
sp = regs->sp;
ss = regs->ss & 0xffff;
} else {
sp = kernel_stack_pointer(regs);
savesegment(ss, ss);
}
printk(KERN_EMERG "EIP: [<%08lx>] ", regs->ip);
print_symbol("%s", regs->ip);
printk(" SS:ESP %04x:%08lx\n", ss, sp);
#else
/* Executive summary in case the oops scrolled away */
printk(KERN_ALERT "RIP ");
printk_address(regs->ip, 1);
printk(" RSP <%016lx>\n", regs->sp);
#endif
return 0;
}
/*
* This is gone through when something in the kernel has done something bad
* and is about to be terminated:
*/
void die(const char *str, struct pt_regs *regs, long err)
{
unsigned long flags = oops_begin();
int sig = SIGSEGV;
if (!user_mode_vm(regs))
report_bug(regs->ip, regs);
if (__die(str, regs, err))
sig = 0;
oops_end(flags, regs, sig);
}
static int __init kstack_setup(char *s)
{
if (!s)
return -EINVAL;
kstack_depth_to_print = simple_strtoul(s, NULL, 0);
return 0;
}
early_param("kstack", kstack_setup);
static int __init code_bytes_setup(char *s)
{
code_bytes = simple_strtoul(s, NULL, 0);
if (code_bytes > 8192)
code_bytes = 8192;
return 1;
}
__setup("code_bytes=", code_bytes_setup);
| gpl-2.0 |
ReaperXL2/Overkill_v4_extended | drivers/input/sparse-keymap.c | 5183 | 8782 | /*
* Generic support for sparse keymaps
*
* Copyright (c) 2009 Dmitry Torokhov
*
* Derived from wistron button driver:
* Copyright (C) 2005 Miloslav Trmac <mitr@volny.cz>
* Copyright (C) 2005 Bernhard Rosenkraenzer <bero@arklinux.org>
* Copyright (C) 2005 Dmitry Torokhov <dtor@mail.ru>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*/
#include <linux/input.h>
#include <linux/input/sparse-keymap.h>
#include <linux/module.h>
#include <linux/slab.h>
MODULE_AUTHOR("Dmitry Torokhov <dtor@mail.ru>");
MODULE_DESCRIPTION("Generic support for sparse keymaps");
MODULE_LICENSE("GPL v2");
MODULE_VERSION("0.1");
static unsigned int sparse_keymap_get_key_index(struct input_dev *dev,
const struct key_entry *k)
{
struct key_entry *key;
unsigned int idx = 0;
for (key = dev->keycode; key->type != KE_END; key++) {
if (key->type == KE_KEY) {
if (key == k)
break;
idx++;
}
}
return idx;
}
static struct key_entry *sparse_keymap_entry_by_index(struct input_dev *dev,
unsigned int index)
{
struct key_entry *key;
unsigned int key_cnt = 0;
for (key = dev->keycode; key->type != KE_END; key++)
if (key->type == KE_KEY)
if (key_cnt++ == index)
return key;
return NULL;
}
/**
* sparse_keymap_entry_from_scancode - perform sparse keymap lookup
* @dev: Input device using sparse keymap
* @code: Scan code
*
* This function is used to perform &struct key_entry lookup in an
* input device using sparse keymap.
*/
struct key_entry *sparse_keymap_entry_from_scancode(struct input_dev *dev,
unsigned int code)
{
struct key_entry *key;
for (key = dev->keycode; key->type != KE_END; key++)
if (code == key->code)
return key;
return NULL;
}
EXPORT_SYMBOL(sparse_keymap_entry_from_scancode);
/**
* sparse_keymap_entry_from_keycode - perform sparse keymap lookup
* @dev: Input device using sparse keymap
* @keycode: Key code
*
* This function is used to perform &struct key_entry lookup in an
* input device using sparse keymap.
*/
struct key_entry *sparse_keymap_entry_from_keycode(struct input_dev *dev,
unsigned int keycode)
{
struct key_entry *key;
for (key = dev->keycode; key->type != KE_END; key++)
if (key->type == KE_KEY && keycode == key->keycode)
return key;
return NULL;
}
EXPORT_SYMBOL(sparse_keymap_entry_from_keycode);
static struct key_entry *sparse_keymap_locate(struct input_dev *dev,
const struct input_keymap_entry *ke)
{
struct key_entry *key;
unsigned int scancode;
if (ke->flags & INPUT_KEYMAP_BY_INDEX)
key = sparse_keymap_entry_by_index(dev, ke->index);
else if (input_scancode_to_scalar(ke, &scancode) == 0)
key = sparse_keymap_entry_from_scancode(dev, scancode);
else
key = NULL;
return key;
}
static int sparse_keymap_getkeycode(struct input_dev *dev,
struct input_keymap_entry *ke)
{
const struct key_entry *key;
if (dev->keycode) {
key = sparse_keymap_locate(dev, ke);
if (key && key->type == KE_KEY) {
ke->keycode = key->keycode;
if (!(ke->flags & INPUT_KEYMAP_BY_INDEX))
ke->index =
sparse_keymap_get_key_index(dev, key);
ke->len = sizeof(key->code);
memcpy(ke->scancode, &key->code, sizeof(key->code));
return 0;
}
}
return -EINVAL;
}
static int sparse_keymap_setkeycode(struct input_dev *dev,
const struct input_keymap_entry *ke,
unsigned int *old_keycode)
{
struct key_entry *key;
if (dev->keycode) {
key = sparse_keymap_locate(dev, ke);
if (key && key->type == KE_KEY) {
*old_keycode = key->keycode;
key->keycode = ke->keycode;
set_bit(ke->keycode, dev->keybit);
if (!sparse_keymap_entry_from_keycode(dev, *old_keycode))
clear_bit(*old_keycode, dev->keybit);
return 0;
}
}
return -EINVAL;
}
/**
* sparse_keymap_setup - set up sparse keymap for an input device
* @dev: Input device
* @keymap: Keymap in form of array of &key_entry structures ending
* with %KE_END type entry
* @setup: Function that can be used to adjust keymap entries
* depending on device's deeds, may be %NULL
*
* The function calculates size and allocates copy of the original
* keymap after which sets up input device event bits appropriately.
* Before destroying input device allocated keymap should be freed
* with a call to sparse_keymap_free().
*/
int sparse_keymap_setup(struct input_dev *dev,
const struct key_entry *keymap,
int (*setup)(struct input_dev *, struct key_entry *))
{
size_t map_size = 1; /* to account for the last KE_END entry */
const struct key_entry *e;
struct key_entry *map, *entry;
int i;
int error;
for (e = keymap; e->type != KE_END; e++)
map_size++;
map = kcalloc(map_size, sizeof (struct key_entry), GFP_KERNEL);
if (!map)
return -ENOMEM;
memcpy(map, keymap, map_size * sizeof (struct key_entry));
for (i = 0; i < map_size; i++) {
entry = &map[i];
if (setup) {
error = setup(dev, entry);
if (error)
goto err_out;
}
switch (entry->type) {
case KE_KEY:
__set_bit(EV_KEY, dev->evbit);
__set_bit(entry->keycode, dev->keybit);
break;
case KE_SW:
case KE_VSW:
__set_bit(EV_SW, dev->evbit);
__set_bit(entry->sw.code, dev->swbit);
break;
}
}
if (test_bit(EV_KEY, dev->evbit)) {
__set_bit(KEY_UNKNOWN, dev->keybit);
__set_bit(EV_MSC, dev->evbit);
__set_bit(MSC_SCAN, dev->mscbit);
}
dev->keycode = map;
dev->keycodemax = map_size;
dev->getkeycode = sparse_keymap_getkeycode;
dev->setkeycode = sparse_keymap_setkeycode;
return 0;
err_out:
kfree(map);
return error;
}
EXPORT_SYMBOL(sparse_keymap_setup);
/**
* sparse_keymap_free - free memory allocated for sparse keymap
* @dev: Input device using sparse keymap
*
* This function is used to free memory allocated by sparse keymap
* in an input device that was set up by sparse_keymap_setup().
* NOTE: It is safe to cal this function while input device is
* still registered (however the drivers should care not to try to
* use freed keymap and thus have to shut off interrups/polling
* before freeing the keymap).
*/
void sparse_keymap_free(struct input_dev *dev)
{
unsigned long flags;
/*
* Take event lock to prevent racing with input_get_keycode()
* and input_set_keycode() if we are called while input device
* is still registered.
*/
spin_lock_irqsave(&dev->event_lock, flags);
kfree(dev->keycode);
dev->keycode = NULL;
dev->keycodemax = 0;
spin_unlock_irqrestore(&dev->event_lock, flags);
}
EXPORT_SYMBOL(sparse_keymap_free);
/**
* sparse_keymap_report_entry - report event corresponding to given key entry
* @dev: Input device for which event should be reported
* @ke: key entry describing event
* @value: Value that should be reported (ignored by %KE_SW entries)
* @autorelease: Signals whether release event should be emitted for %KE_KEY
* entries right after reporting press event, ignored by all other
* entries
*
* This function is used to report input event described by given
* &struct key_entry.
*/
void sparse_keymap_report_entry(struct input_dev *dev, const struct key_entry *ke,
unsigned int value, bool autorelease)
{
switch (ke->type) {
case KE_KEY:
input_event(dev, EV_MSC, MSC_SCAN, ke->code);
input_report_key(dev, ke->keycode, value);
input_sync(dev);
if (value && autorelease) {
input_report_key(dev, ke->keycode, 0);
input_sync(dev);
}
break;
case KE_SW:
value = ke->sw.value;
/* fall through */
case KE_VSW:
input_report_switch(dev, ke->sw.code, value);
break;
}
}
EXPORT_SYMBOL(sparse_keymap_report_entry);
/**
* sparse_keymap_report_event - report event corresponding to given scancode
* @dev: Input device using sparse keymap
* @code: Scan code
* @value: Value that should be reported (ignored by %KE_SW entries)
* @autorelease: Signals whether release event should be emitted for %KE_KEY
* entries right after reporting press event, ignored by all other
* entries
*
* This function is used to perform lookup in an input device using sparse
* keymap and report corresponding event. Returns %true if lookup was
* successful and %false otherwise.
*/
bool sparse_keymap_report_event(struct input_dev *dev, unsigned int code,
unsigned int value, bool autorelease)
{
const struct key_entry *ke =
sparse_keymap_entry_from_scancode(dev, code);
struct key_entry unknown_ke;
if (ke) {
sparse_keymap_report_entry(dev, ke, value, autorelease);
return true;
}
/* Report an unknown key event as a debugging aid */
unknown_ke.type = KE_KEY;
unknown_ke.code = code;
unknown_ke.keycode = KEY_UNKNOWN;
sparse_keymap_report_entry(dev, &unknown_ke, value, true);
return false;
}
EXPORT_SYMBOL(sparse_keymap_report_event);
| gpl-2.0 |
hanjin1987/android_kernel_msm7x27a | drivers/video/68328fb.c | 5183 | 13556 | /*
* linux/drivers/video/68328fb.c -- Low level implementation of the
* mc68x328 LCD frame buffer device
*
* Copyright (C) 2003 Georges Menie
*
* This driver assumes an already configured controller (e.g. from config.c)
* Keep the code clean of board specific initialization.
*
* This code has not been tested with colors, colormap management functions
* are minimal (no colormap data written to the 68328 registers...)
*
* initial version of this driver:
* Copyright (C) 1998,1999 Kenneth Albanowski <kjahds@kjahds.com>,
* The Silver Hammer Group, Ltd.
*
* this version is based on :
*
* linux/drivers/video/vfb.c -- Virtual frame buffer device
*
* Copyright (C) 2002 James Simmons
*
* Copyright (C) 1997 Geert Uytterhoeven
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of this archive for
* more details.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/vmalloc.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <asm/uaccess.h>
#include <linux/fb.h>
#include <linux/init.h>
#if defined(CONFIG_M68VZ328)
#include <asm/MC68VZ328.h>
#elif defined(CONFIG_M68EZ328)
#include <asm/MC68EZ328.h>
#elif defined(CONFIG_M68328)
#include <asm/MC68328.h>
#else
#error wrong architecture for the MC68x328 frame buffer device
#endif
#if defined(CONFIG_FB_68328_INVERT)
#define MC68X328FB_MONO_VISUAL FB_VISUAL_MONO01
#else
#define MC68X328FB_MONO_VISUAL FB_VISUAL_MONO10
#endif
static u_long videomemory;
static u_long videomemorysize;
static struct fb_info fb_info;
static u32 mc68x328fb_pseudo_palette[16];
static struct fb_var_screeninfo mc68x328fb_default __initdata = {
.red = { 0, 8, 0 },
.green = { 0, 8, 0 },
.blue = { 0, 8, 0 },
.activate = FB_ACTIVATE_TEST,
.height = -1,
.width = -1,
.pixclock = 20000,
.left_margin = 64,
.right_margin = 64,
.upper_margin = 32,
.lower_margin = 32,
.hsync_len = 64,
.vsync_len = 2,
.vmode = FB_VMODE_NONINTERLACED,
};
static struct fb_fix_screeninfo mc68x328fb_fix __initdata = {
.id = "68328fb",
.type = FB_TYPE_PACKED_PIXELS,
.xpanstep = 1,
.ypanstep = 1,
.ywrapstep = 1,
.accel = FB_ACCEL_NONE,
};
/*
* Interface used by the world
*/
int mc68x328fb_init(void);
int mc68x328fb_setup(char *);
static int mc68x328fb_check_var(struct fb_var_screeninfo *var,
struct fb_info *info);
static int mc68x328fb_set_par(struct fb_info *info);
static int mc68x328fb_setcolreg(u_int regno, u_int red, u_int green, u_int blue,
u_int transp, struct fb_info *info);
static int mc68x328fb_pan_display(struct fb_var_screeninfo *var,
struct fb_info *info);
static int mc68x328fb_mmap(struct fb_info *info, struct vm_area_struct *vma);
static struct fb_ops mc68x328fb_ops = {
.fb_check_var = mc68x328fb_check_var,
.fb_set_par = mc68x328fb_set_par,
.fb_setcolreg = mc68x328fb_setcolreg,
.fb_pan_display = mc68x328fb_pan_display,
.fb_fillrect = cfb_fillrect,
.fb_copyarea = cfb_copyarea,
.fb_imageblit = cfb_imageblit,
.fb_mmap = mc68x328fb_mmap,
};
/*
* Internal routines
*/
static u_long get_line_length(int xres_virtual, int bpp)
{
u_long length;
length = xres_virtual * bpp;
length = (length + 31) & ~31;
length >>= 3;
return (length);
}
/*
* Setting the video mode has been split into two parts.
* First part, xxxfb_check_var, must not write anything
* to hardware, it should only verify and adjust var.
* This means it doesn't alter par but it does use hardware
* data from it to check this var.
*/
static int mc68x328fb_check_var(struct fb_var_screeninfo *var,
struct fb_info *info)
{
u_long line_length;
/*
* FB_VMODE_CONUPDATE and FB_VMODE_SMOOTH_XPAN are equal!
* as FB_VMODE_SMOOTH_XPAN is only used internally
*/
if (var->vmode & FB_VMODE_CONUPDATE) {
var->vmode |= FB_VMODE_YWRAP;
var->xoffset = info->var.xoffset;
var->yoffset = info->var.yoffset;
}
/*
* Some very basic checks
*/
if (!var->xres)
var->xres = 1;
if (!var->yres)
var->yres = 1;
if (var->xres > var->xres_virtual)
var->xres_virtual = var->xres;
if (var->yres > var->yres_virtual)
var->yres_virtual = var->yres;
if (var->bits_per_pixel <= 1)
var->bits_per_pixel = 1;
else if (var->bits_per_pixel <= 8)
var->bits_per_pixel = 8;
else if (var->bits_per_pixel <= 16)
var->bits_per_pixel = 16;
else if (var->bits_per_pixel <= 24)
var->bits_per_pixel = 24;
else if (var->bits_per_pixel <= 32)
var->bits_per_pixel = 32;
else
return -EINVAL;
if (var->xres_virtual < var->xoffset + var->xres)
var->xres_virtual = var->xoffset + var->xres;
if (var->yres_virtual < var->yoffset + var->yres)
var->yres_virtual = var->yoffset + var->yres;
/*
* Memory limit
*/
line_length =
get_line_length(var->xres_virtual, var->bits_per_pixel);
if (line_length * var->yres_virtual > videomemorysize)
return -ENOMEM;
/*
* Now that we checked it we alter var. The reason being is that the video
* mode passed in might not work but slight changes to it might make it
* work. This way we let the user know what is acceptable.
*/
switch (var->bits_per_pixel) {
case 1:
var->red.offset = 0;
var->red.length = 1;
var->green.offset = 0;
var->green.length = 1;
var->blue.offset = 0;
var->blue.length = 1;
var->transp.offset = 0;
var->transp.length = 0;
break;
case 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;
case 16: /* RGBA 5551 */
if (var->transp.length) {
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;
} else { /* RGB 565 */
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 24: /* RGB 888 */
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 32: /* RGBA 8888 */
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;
}
var->red.msb_right = 0;
var->green.msb_right = 0;
var->blue.msb_right = 0;
var->transp.msb_right = 0;
return 0;
}
/* This routine actually sets the video mode. It's in here where we
* the hardware state info->par and fix which can be affected by the
* change in par. For this driver it doesn't do much.
*/
static int mc68x328fb_set_par(struct fb_info *info)
{
info->fix.line_length = get_line_length(info->var.xres_virtual,
info->var.bits_per_pixel);
return 0;
}
/*
* 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.
*/
static int mc68x328fb_setcolreg(u_int regno, u_int red, u_int green, u_int blue,
u_int transp, struct fb_info *info)
{
if (regno >= 256) /* no. of hw registers */
return 1;
/*
* Program hardware... do anything you want with transp
*/
/* grayscale works only partially under directcolor */
if (info->var.grayscale) {
/* grayscale = 0.30*R + 0.59*G + 0.11*B */
red = green = blue =
(red * 77 + green * 151 + blue * 28) >> 8;
}
/* Directcolor:
* var->{color}.offset contains start of bitfield
* var->{color}.length contains length of bitfield
* {hardwarespecific} contains width of RAMDAC
* cmap[X] is programmed to (X << red.offset) | (X << green.offset) | (X << blue.offset)
* RAMDAC[X] is programmed to (red, green, blue)
*
* Pseudocolor:
* uses offset = 0 && length = RAMDAC register width.
* var->{color}.offset is 0
* var->{color}.length contains width of DAC
* cmap is not used
* RAMDAC[X] is programmed to (red, green, blue)
* Truecolor:
* does not use DAC. Usually 3 are present.
* var->{color}.offset contains start of bitfield
* var->{color}.length contains length of bitfield
* cmap is programmed to (red << red.offset) | (green << green.offset) |
* (blue << blue.offset) | (transp << transp.offset)
* RAMDAC does not exist
*/
#define CNVT_TOHW(val,width) ((((val)<<(width))+0x7FFF-(val))>>16)
switch (info->fix.visual) {
case FB_VISUAL_TRUECOLOR:
case FB_VISUAL_PSEUDOCOLOR:
red = CNVT_TOHW(red, info->var.red.length);
green = CNVT_TOHW(green, info->var.green.length);
blue = CNVT_TOHW(blue, info->var.blue.length);
transp = CNVT_TOHW(transp, info->var.transp.length);
break;
case FB_VISUAL_DIRECTCOLOR:
red = CNVT_TOHW(red, 8); /* expect 8 bit DAC */
green = CNVT_TOHW(green, 8);
blue = CNVT_TOHW(blue, 8);
/* hey, there is bug in transp handling... */
transp = CNVT_TOHW(transp, 8);
break;
}
#undef CNVT_TOHW
/* Truecolor has hardware independent palette */
if (info->fix.visual == FB_VISUAL_TRUECOLOR) {
u32 v;
if (regno >= 16)
return 1;
v = (red << info->var.red.offset) |
(green << info->var.green.offset) |
(blue << info->var.blue.offset) |
(transp << info->var.transp.offset);
switch (info->var.bits_per_pixel) {
case 8:
break;
case 16:
((u32 *) (info->pseudo_palette))[regno] = v;
break;
case 24:
case 32:
((u32 *) (info->pseudo_palette))[regno] = v;
break;
}
return 0;
}
return 0;
}
/*
* Pan or Wrap the Display
*
* This call looks only at xoffset, yoffset and the FB_VMODE_YWRAP flag
*/
static int mc68x328fb_pan_display(struct fb_var_screeninfo *var,
struct fb_info *info)
{
if (var->vmode & FB_VMODE_YWRAP) {
if (var->yoffset < 0
|| var->yoffset >= info->var.yres_virtual
|| var->xoffset)
return -EINVAL;
} else {
if (var->xoffset + info->var.xres > info->var.xres_virtual ||
var->yoffset + info->var.yres > info->var.yres_virtual)
return -EINVAL;
}
info->var.xoffset = var->xoffset;
info->var.yoffset = var->yoffset;
if (var->vmode & FB_VMODE_YWRAP)
info->var.vmode |= FB_VMODE_YWRAP;
else
info->var.vmode &= ~FB_VMODE_YWRAP;
return 0;
}
/*
* Most drivers don't need their own mmap function
*/
static int mc68x328fb_mmap(struct fb_info *info, struct vm_area_struct *vma)
{
#ifndef MMU
/* this is uClinux (no MMU) specific code */
vma->vm_flags |= VM_RESERVED;
vma->vm_start = videomemory;
return 0;
#else
return -EINVAL;
#endif
}
int __init mc68x328fb_setup(char *options)
{
#if 0
char *this_opt;
#endif
if (!options || !*options)
return 1;
#if 0
while ((this_opt = strsep(&options, ",")) != NULL) {
if (!*this_opt)
continue;
if (!strncmp(this_opt, "disable", 7))
mc68x328fb_enable = 0;
}
#endif
return 1;
}
/*
* Initialisation
*/
int __init mc68x328fb_init(void)
{
#ifndef MODULE
char *option = NULL;
if (fb_get_options("68328fb", &option))
return -ENODEV;
mc68x328fb_setup(option);
#endif
/*
* initialize the default mode from the LCD controller registers
*/
mc68x328fb_default.xres = LXMAX;
mc68x328fb_default.yres = LYMAX+1;
mc68x328fb_default.xres_virtual = mc68x328fb_default.xres;
mc68x328fb_default.yres_virtual = mc68x328fb_default.yres;
mc68x328fb_default.bits_per_pixel = 1 + (LPICF & 0x01);
videomemory = LSSA;
videomemorysize = (mc68x328fb_default.xres_virtual+7) / 8 *
mc68x328fb_default.yres_virtual * mc68x328fb_default.bits_per_pixel;
fb_info.screen_base = (void *)videomemory;
fb_info.fbops = &mc68x328fb_ops;
fb_info.var = mc68x328fb_default;
fb_info.fix = mc68x328fb_fix;
fb_info.fix.smem_start = videomemory;
fb_info.fix.smem_len = videomemorysize;
fb_info.fix.line_length =
get_line_length(mc68x328fb_default.xres_virtual, mc68x328fb_default.bits_per_pixel);
fb_info.fix.visual = (mc68x328fb_default.bits_per_pixel) == 1 ?
MC68X328FB_MONO_VISUAL : FB_VISUAL_PSEUDOCOLOR;
if (fb_info.var.bits_per_pixel == 1) {
fb_info.var.red.length = fb_info.var.green.length = fb_info.var.blue.length = 1;
fb_info.var.red.offset = fb_info.var.green.offset = fb_info.var.blue.offset = 0;
}
fb_info.pseudo_palette = &mc68x328fb_pseudo_palette;
fb_info.flags = FBINFO_DEFAULT | FBINFO_HWACCEL_YPAN;
if (fb_alloc_cmap(&fb_info.cmap, 256, 0))
return -ENOMEM;
if (register_framebuffer(&fb_info) < 0) {
fb_dealloc_cmap(&fb_info.cmap);
return -EINVAL;
}
printk(KERN_INFO
"fb%d: %s frame buffer device\n", fb_info.node, fb_info.fix.id);
printk(KERN_INFO
"fb%d: %dx%dx%d at 0x%08lx\n", fb_info.node,
mc68x328fb_default.xres_virtual, mc68x328fb_default.yres_virtual,
1 << mc68x328fb_default.bits_per_pixel, videomemory);
return 0;
}
module_init(mc68x328fb_init);
#ifdef MODULE
static void __exit mc68x328fb_cleanup(void)
{
unregister_framebuffer(&fb_info);
fb_dealloc_cmap(&fb_info.cmap);
}
module_exit(mc68x328fb_cleanup);
MODULE_LICENSE("GPL");
#endif /* MODULE */
| gpl-2.0 |
somcom3x/android_kernel_motorola_msm8992 | drivers/net/wireless/hostap/hostap_80211_tx.c | 7743 | 16387 | #include <linux/slab.h>
#include <linux/export.h>
#include "hostap_80211.h"
#include "hostap_common.h"
#include "hostap_wlan.h"
#include "hostap.h"
#include "hostap_ap.h"
/* See IEEE 802.1H for LLC/SNAP encapsulation/decapsulation */
/* Ethernet-II snap header (RFC1042 for most EtherTypes) */
static unsigned char rfc1042_header[] =
{ 0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00 };
/* Bridge-Tunnel header (for EtherTypes ETH_P_AARP and ETH_P_IPX) */
static unsigned char bridge_tunnel_header[] =
{ 0xaa, 0xaa, 0x03, 0x00, 0x00, 0xf8 };
/* No encapsulation header if EtherType < 0x600 (=length) */
void hostap_dump_tx_80211(const char *name, struct sk_buff *skb)
{
struct ieee80211_hdr *hdr;
u16 fc;
hdr = (struct ieee80211_hdr *) skb->data;
printk(KERN_DEBUG "%s: TX len=%d jiffies=%ld\n",
name, skb->len, jiffies);
if (skb->len < 2)
return;
fc = le16_to_cpu(hdr->frame_control);
printk(KERN_DEBUG " FC=0x%04x (type=%d:%d)%s%s",
fc, (fc & IEEE80211_FCTL_FTYPE) >> 2,
(fc & IEEE80211_FCTL_STYPE) >> 4,
fc & IEEE80211_FCTL_TODS ? " [ToDS]" : "",
fc & IEEE80211_FCTL_FROMDS ? " [FromDS]" : "");
if (skb->len < IEEE80211_DATA_HDR3_LEN) {
printk("\n");
return;
}
printk(" dur=0x%04x seq=0x%04x\n", le16_to_cpu(hdr->duration_id),
le16_to_cpu(hdr->seq_ctrl));
printk(KERN_DEBUG " A1=%pM", hdr->addr1);
printk(" A2=%pM", hdr->addr2);
printk(" A3=%pM", hdr->addr3);
if (skb->len >= 30)
printk(" A4=%pM", hdr->addr4);
printk("\n");
}
/* hard_start_xmit function for data interfaces (wlan#, wlan#wds#, wlan#sta)
* Convert Ethernet header into a suitable IEEE 802.11 header depending on
* device configuration. */
netdev_tx_t hostap_data_start_xmit(struct sk_buff *skb,
struct net_device *dev)
{
struct hostap_interface *iface;
local_info_t *local;
int need_headroom, need_tailroom = 0;
struct ieee80211_hdr hdr;
u16 fc, ethertype = 0;
enum {
WDS_NO = 0, WDS_OWN_FRAME, WDS_COMPLIANT_FRAME
} use_wds = WDS_NO;
u8 *encaps_data;
int hdr_len, encaps_len, skip_header_bytes;
int to_assoc_ap = 0;
struct hostap_skb_tx_data *meta;
iface = netdev_priv(dev);
local = iface->local;
if (skb->len < ETH_HLEN) {
printk(KERN_DEBUG "%s: hostap_data_start_xmit: short skb "
"(len=%d)\n", dev->name, skb->len);
kfree_skb(skb);
return NETDEV_TX_OK;
}
if (local->ddev != dev) {
use_wds = (local->iw_mode == IW_MODE_MASTER &&
!(local->wds_type & HOSTAP_WDS_STANDARD_FRAME)) ?
WDS_OWN_FRAME : WDS_COMPLIANT_FRAME;
if (dev == local->stadev) {
to_assoc_ap = 1;
use_wds = WDS_NO;
} else if (dev == local->apdev) {
printk(KERN_DEBUG "%s: prism2_tx: trying to use "
"AP device with Ethernet net dev\n", dev->name);
kfree_skb(skb);
return NETDEV_TX_OK;
}
} else {
if (local->iw_mode == IW_MODE_REPEAT) {
printk(KERN_DEBUG "%s: prism2_tx: trying to use "
"non-WDS link in Repeater mode\n", dev->name);
kfree_skb(skb);
return NETDEV_TX_OK;
} else if (local->iw_mode == IW_MODE_INFRA &&
(local->wds_type & HOSTAP_WDS_AP_CLIENT) &&
memcmp(skb->data + ETH_ALEN, dev->dev_addr,
ETH_ALEN) != 0) {
/* AP client mode: send frames with foreign src addr
* using 4-addr WDS frames */
use_wds = WDS_COMPLIANT_FRAME;
}
}
/* Incoming skb->data: dst_addr[6], src_addr[6], proto[2], payload
* ==>
* Prism2 TX frame with 802.11 header:
* txdesc (address order depending on used mode; includes dst_addr and
* src_addr), possible encapsulation (RFC1042/Bridge-Tunnel;
* proto[2], payload {, possible addr4[6]} */
ethertype = (skb->data[12] << 8) | skb->data[13];
memset(&hdr, 0, sizeof(hdr));
/* Length of data after IEEE 802.11 header */
encaps_data = NULL;
encaps_len = 0;
skip_header_bytes = ETH_HLEN;
if (ethertype == ETH_P_AARP || ethertype == ETH_P_IPX) {
encaps_data = bridge_tunnel_header;
encaps_len = sizeof(bridge_tunnel_header);
skip_header_bytes -= 2;
} else if (ethertype >= 0x600) {
encaps_data = rfc1042_header;
encaps_len = sizeof(rfc1042_header);
skip_header_bytes -= 2;
}
fc = IEEE80211_FTYPE_DATA | IEEE80211_STYPE_DATA;
hdr_len = IEEE80211_DATA_HDR3_LEN;
if (use_wds != WDS_NO) {
/* Note! Prism2 station firmware has problems with sending real
* 802.11 frames with four addresses; until these problems can
* be fixed or worked around, 4-addr frames needed for WDS are
* using incompatible format: FromDS flag is not set and the
* fourth address is added after the frame payload; it is
* assumed, that the receiving station knows how to handle this
* frame format */
if (use_wds == WDS_COMPLIANT_FRAME) {
fc |= IEEE80211_FCTL_FROMDS | IEEE80211_FCTL_TODS;
/* From&To DS: Addr1 = RA, Addr2 = TA, Addr3 = DA,
* Addr4 = SA */
skb_copy_from_linear_data_offset(skb, ETH_ALEN,
&hdr.addr4, ETH_ALEN);
hdr_len += ETH_ALEN;
} else {
/* bogus 4-addr format to workaround Prism2 station
* f/w bug */
fc |= IEEE80211_FCTL_TODS;
/* From DS: Addr1 = DA (used as RA),
* Addr2 = BSSID (used as TA), Addr3 = SA (used as DA),
*/
/* SA from skb->data + ETH_ALEN will be added after
* frame payload; use hdr.addr4 as a temporary buffer
*/
skb_copy_from_linear_data_offset(skb, ETH_ALEN,
&hdr.addr4, ETH_ALEN);
need_tailroom += ETH_ALEN;
}
/* send broadcast and multicast frames to broadcast RA, if
* configured; otherwise, use unicast RA of the WDS link */
if ((local->wds_type & HOSTAP_WDS_BROADCAST_RA) &&
skb->data[0] & 0x01)
memset(&hdr.addr1, 0xff, ETH_ALEN);
else if (iface->type == HOSTAP_INTERFACE_WDS)
memcpy(&hdr.addr1, iface->u.wds.remote_addr,
ETH_ALEN);
else
memcpy(&hdr.addr1, local->bssid, ETH_ALEN);
memcpy(&hdr.addr2, dev->dev_addr, ETH_ALEN);
skb_copy_from_linear_data(skb, &hdr.addr3, ETH_ALEN);
} else if (local->iw_mode == IW_MODE_MASTER && !to_assoc_ap) {
fc |= IEEE80211_FCTL_FROMDS;
/* From DS: Addr1 = DA, Addr2 = BSSID, Addr3 = SA */
skb_copy_from_linear_data(skb, &hdr.addr1, ETH_ALEN);
memcpy(&hdr.addr2, dev->dev_addr, ETH_ALEN);
skb_copy_from_linear_data_offset(skb, ETH_ALEN, &hdr.addr3,
ETH_ALEN);
} else if (local->iw_mode == IW_MODE_INFRA || to_assoc_ap) {
fc |= IEEE80211_FCTL_TODS;
/* To DS: Addr1 = BSSID, Addr2 = SA, Addr3 = DA */
memcpy(&hdr.addr1, to_assoc_ap ?
local->assoc_ap_addr : local->bssid, ETH_ALEN);
skb_copy_from_linear_data_offset(skb, ETH_ALEN, &hdr.addr2,
ETH_ALEN);
skb_copy_from_linear_data(skb, &hdr.addr3, ETH_ALEN);
} else if (local->iw_mode == IW_MODE_ADHOC) {
/* not From/To DS: Addr1 = DA, Addr2 = SA, Addr3 = BSSID */
skb_copy_from_linear_data(skb, &hdr.addr1, ETH_ALEN);
skb_copy_from_linear_data_offset(skb, ETH_ALEN, &hdr.addr2,
ETH_ALEN);
memcpy(&hdr.addr3, local->bssid, ETH_ALEN);
}
hdr.frame_control = cpu_to_le16(fc);
skb_pull(skb, skip_header_bytes);
need_headroom = local->func->need_tx_headroom + hdr_len + encaps_len;
if (skb_tailroom(skb) < need_tailroom) {
skb = skb_unshare(skb, GFP_ATOMIC);
if (skb == NULL) {
iface->stats.tx_dropped++;
return NETDEV_TX_OK;
}
if (pskb_expand_head(skb, need_headroom, need_tailroom,
GFP_ATOMIC)) {
kfree_skb(skb);
iface->stats.tx_dropped++;
return NETDEV_TX_OK;
}
} else if (skb_headroom(skb) < need_headroom) {
struct sk_buff *tmp = skb;
skb = skb_realloc_headroom(skb, need_headroom);
kfree_skb(tmp);
if (skb == NULL) {
iface->stats.tx_dropped++;
return NETDEV_TX_OK;
}
} else {
skb = skb_unshare(skb, GFP_ATOMIC);
if (skb == NULL) {
iface->stats.tx_dropped++;
return NETDEV_TX_OK;
}
}
if (encaps_data)
memcpy(skb_push(skb, encaps_len), encaps_data, encaps_len);
memcpy(skb_push(skb, hdr_len), &hdr, hdr_len);
if (use_wds == WDS_OWN_FRAME) {
memcpy(skb_put(skb, ETH_ALEN), &hdr.addr4, ETH_ALEN);
}
iface->stats.tx_packets++;
iface->stats.tx_bytes += skb->len;
skb_reset_mac_header(skb);
meta = (struct hostap_skb_tx_data *) skb->cb;
memset(meta, 0, sizeof(*meta));
meta->magic = HOSTAP_SKB_TX_DATA_MAGIC;
if (use_wds)
meta->flags |= HOSTAP_TX_FLAGS_WDS;
meta->ethertype = ethertype;
meta->iface = iface;
/* Send IEEE 802.11 encapsulated frame using the master radio device */
skb->dev = local->dev;
dev_queue_xmit(skb);
return NETDEV_TX_OK;
}
/* hard_start_xmit function for hostapd wlan#ap interfaces */
netdev_tx_t hostap_mgmt_start_xmit(struct sk_buff *skb,
struct net_device *dev)
{
struct hostap_interface *iface;
local_info_t *local;
struct hostap_skb_tx_data *meta;
struct ieee80211_hdr *hdr;
u16 fc;
iface = netdev_priv(dev);
local = iface->local;
if (skb->len < 10) {
printk(KERN_DEBUG "%s: hostap_mgmt_start_xmit: short skb "
"(len=%d)\n", dev->name, skb->len);
kfree_skb(skb);
return NETDEV_TX_OK;
}
iface->stats.tx_packets++;
iface->stats.tx_bytes += skb->len;
meta = (struct hostap_skb_tx_data *) skb->cb;
memset(meta, 0, sizeof(*meta));
meta->magic = HOSTAP_SKB_TX_DATA_MAGIC;
meta->iface = iface;
if (skb->len >= IEEE80211_DATA_HDR3_LEN + sizeof(rfc1042_header) + 2) {
hdr = (struct ieee80211_hdr *) skb->data;
fc = le16_to_cpu(hdr->frame_control);
if (ieee80211_is_data(hdr->frame_control) &&
(fc & IEEE80211_FCTL_STYPE) == IEEE80211_STYPE_DATA) {
u8 *pos = &skb->data[IEEE80211_DATA_HDR3_LEN +
sizeof(rfc1042_header)];
meta->ethertype = (pos[0] << 8) | pos[1];
}
}
/* Send IEEE 802.11 encapsulated frame using the master radio device */
skb->dev = local->dev;
dev_queue_xmit(skb);
return NETDEV_TX_OK;
}
/* Called only from software IRQ */
static struct sk_buff * hostap_tx_encrypt(struct sk_buff *skb,
struct lib80211_crypt_data *crypt)
{
struct hostap_interface *iface;
local_info_t *local;
struct ieee80211_hdr *hdr;
int prefix_len, postfix_len, hdr_len, res;
iface = netdev_priv(skb->dev);
local = iface->local;
if (skb->len < IEEE80211_DATA_HDR3_LEN) {
kfree_skb(skb);
return NULL;
}
if (local->tkip_countermeasures &&
strcmp(crypt->ops->name, "TKIP") == 0) {
hdr = (struct ieee80211_hdr *) skb->data;
if (net_ratelimit()) {
printk(KERN_DEBUG "%s: TKIP countermeasures: dropped "
"TX packet to %pM\n",
local->dev->name, hdr->addr1);
}
kfree_skb(skb);
return NULL;
}
skb = skb_unshare(skb, GFP_ATOMIC);
if (skb == NULL)
return NULL;
prefix_len = crypt->ops->extra_mpdu_prefix_len +
crypt->ops->extra_msdu_prefix_len;
postfix_len = crypt->ops->extra_mpdu_postfix_len +
crypt->ops->extra_msdu_postfix_len;
if ((skb_headroom(skb) < prefix_len ||
skb_tailroom(skb) < postfix_len) &&
pskb_expand_head(skb, prefix_len, postfix_len, GFP_ATOMIC)) {
kfree_skb(skb);
return NULL;
}
hdr = (struct ieee80211_hdr *) skb->data;
hdr_len = hostap_80211_get_hdrlen(hdr->frame_control);
/* Host-based IEEE 802.11 fragmentation for TX is not yet supported, so
* call both MSDU and MPDU encryption functions from here. */
atomic_inc(&crypt->refcnt);
res = 0;
if (crypt->ops->encrypt_msdu)
res = crypt->ops->encrypt_msdu(skb, hdr_len, crypt->priv);
if (res == 0 && crypt->ops->encrypt_mpdu)
res = crypt->ops->encrypt_mpdu(skb, hdr_len, crypt->priv);
atomic_dec(&crypt->refcnt);
if (res < 0) {
kfree_skb(skb);
return NULL;
}
return skb;
}
/* hard_start_xmit function for master radio interface wifi#.
* AP processing (TX rate control, power save buffering, etc.).
* Use hardware TX function to send the frame. */
netdev_tx_t hostap_master_start_xmit(struct sk_buff *skb,
struct net_device *dev)
{
struct hostap_interface *iface;
local_info_t *local;
netdev_tx_t ret = NETDEV_TX_BUSY;
u16 fc;
struct hostap_tx_data tx;
ap_tx_ret tx_ret;
struct hostap_skb_tx_data *meta;
int no_encrypt = 0;
struct ieee80211_hdr *hdr;
iface = netdev_priv(dev);
local = iface->local;
tx.skb = skb;
tx.sta_ptr = NULL;
meta = (struct hostap_skb_tx_data *) skb->cb;
if (meta->magic != HOSTAP_SKB_TX_DATA_MAGIC) {
printk(KERN_DEBUG "%s: invalid skb->cb magic (0x%08x, "
"expected 0x%08x)\n",
dev->name, meta->magic, HOSTAP_SKB_TX_DATA_MAGIC);
ret = NETDEV_TX_OK;
iface->stats.tx_dropped++;
goto fail;
}
if (local->host_encrypt) {
/* Set crypt to default algorithm and key; will be replaced in
* AP code if STA has own alg/key */
tx.crypt = local->crypt_info.crypt[local->crypt_info.tx_keyidx];
tx.host_encrypt = 1;
} else {
tx.crypt = NULL;
tx.host_encrypt = 0;
}
if (skb->len < 24) {
printk(KERN_DEBUG "%s: hostap_master_start_xmit: short skb "
"(len=%d)\n", dev->name, skb->len);
ret = NETDEV_TX_OK;
iface->stats.tx_dropped++;
goto fail;
}
/* FIX (?):
* Wi-Fi 802.11b test plan suggests that AP should ignore power save
* bit in authentication and (re)association frames and assume tha
* STA remains awake for the response. */
tx_ret = hostap_handle_sta_tx(local, &tx);
skb = tx.skb;
meta = (struct hostap_skb_tx_data *) skb->cb;
hdr = (struct ieee80211_hdr *) skb->data;
fc = le16_to_cpu(hdr->frame_control);
switch (tx_ret) {
case AP_TX_CONTINUE:
break;
case AP_TX_CONTINUE_NOT_AUTHORIZED:
if (local->ieee_802_1x &&
ieee80211_is_data(hdr->frame_control) &&
meta->ethertype != ETH_P_PAE &&
!(meta->flags & HOSTAP_TX_FLAGS_WDS)) {
printk(KERN_DEBUG "%s: dropped frame to unauthorized "
"port (IEEE 802.1X): ethertype=0x%04x\n",
dev->name, meta->ethertype);
hostap_dump_tx_80211(dev->name, skb);
ret = NETDEV_TX_OK; /* drop packet */
iface->stats.tx_dropped++;
goto fail;
}
break;
case AP_TX_DROP:
ret = NETDEV_TX_OK; /* drop packet */
iface->stats.tx_dropped++;
goto fail;
case AP_TX_RETRY:
goto fail;
case AP_TX_BUFFERED:
/* do not free skb here, it will be freed when the
* buffered frame is sent/timed out */
ret = NETDEV_TX_OK;
goto tx_exit;
}
/* Request TX callback if protocol version is 2 in 802.11 header;
* this version 2 is a special case used between hostapd and kernel
* driver */
if (((fc & IEEE80211_FCTL_VERS) == BIT(1)) &&
local->ap && local->ap->tx_callback_idx && meta->tx_cb_idx == 0) {
meta->tx_cb_idx = local->ap->tx_callback_idx;
/* remove special version from the frame header */
fc &= ~IEEE80211_FCTL_VERS;
hdr->frame_control = cpu_to_le16(fc);
}
if (!ieee80211_is_data(hdr->frame_control)) {
no_encrypt = 1;
tx.crypt = NULL;
}
if (local->ieee_802_1x && meta->ethertype == ETH_P_PAE && tx.crypt &&
!(fc & IEEE80211_FCTL_PROTECTED)) {
no_encrypt = 1;
PDEBUG(DEBUG_EXTRA2, "%s: TX: IEEE 802.1X - passing "
"unencrypted EAPOL frame\n", dev->name);
tx.crypt = NULL; /* no encryption for IEEE 802.1X frames */
}
if (tx.crypt && (!tx.crypt->ops || !tx.crypt->ops->encrypt_mpdu))
tx.crypt = NULL;
else if ((tx.crypt ||
local->crypt_info.crypt[local->crypt_info.tx_keyidx]) &&
!no_encrypt) {
/* Add ISWEP flag both for firmware and host based encryption
*/
fc |= IEEE80211_FCTL_PROTECTED;
hdr->frame_control = cpu_to_le16(fc);
} else if (local->drop_unencrypted &&
ieee80211_is_data(hdr->frame_control) &&
meta->ethertype != ETH_P_PAE) {
if (net_ratelimit()) {
printk(KERN_DEBUG "%s: dropped unencrypted TX data "
"frame (drop_unencrypted=1)\n", dev->name);
}
iface->stats.tx_dropped++;
ret = NETDEV_TX_OK;
goto fail;
}
if (tx.crypt) {
skb = hostap_tx_encrypt(skb, tx.crypt);
if (skb == NULL) {
printk(KERN_DEBUG "%s: TX - encryption failed\n",
dev->name);
ret = NETDEV_TX_OK;
goto fail;
}
meta = (struct hostap_skb_tx_data *) skb->cb;
if (meta->magic != HOSTAP_SKB_TX_DATA_MAGIC) {
printk(KERN_DEBUG "%s: invalid skb->cb magic (0x%08x, "
"expected 0x%08x) after hostap_tx_encrypt\n",
dev->name, meta->magic,
HOSTAP_SKB_TX_DATA_MAGIC);
ret = NETDEV_TX_OK;
iface->stats.tx_dropped++;
goto fail;
}
}
if (local->func->tx == NULL || local->func->tx(skb, dev)) {
ret = NETDEV_TX_OK;
iface->stats.tx_dropped++;
} else {
ret = NETDEV_TX_OK;
iface->stats.tx_packets++;
iface->stats.tx_bytes += skb->len;
}
fail:
if (ret == NETDEV_TX_OK && skb)
dev_kfree_skb(skb);
tx_exit:
if (tx.sta_ptr)
hostap_handle_sta_release(tx.sta_ptr);
return ret;
}
EXPORT_SYMBOL(hostap_master_start_xmit);
| gpl-2.0 |
thanhphat11/Kernel-Stock-A900-SLK | drivers/base/transport_class.c | 9535 | 9577 | /*
* transport_class.c - implementation of generic transport classes
* using attribute_containers
*
* Copyright (c) 2005 - James Bottomley <James.Bottomley@steeleye.com>
*
* This file is licensed under GPLv2
*
* The basic idea here is to allow any "device controller" (which
* would most often be a Host Bus Adapter to use the services of one
* or more tranport classes for performing transport specific
* services. Transport specific services are things that the generic
* command layer doesn't want to know about (speed settings, line
* condidtioning, etc), but which the user might be interested in.
* Thus, the HBA's use the routines exported by the transport classes
* to perform these functions. The transport classes export certain
* values to the user via sysfs using attribute containers.
*
* Note: because not every HBA will care about every transport
* attribute, there's a many to one relationship that goes like this:
*
* transport class<-----attribute container<----class device
*
* Usually the attribute container is per-HBA, but the design doesn't
* mandate that. Although most of the services will be specific to
* the actual external storage connection used by the HBA, the generic
* transport class is framed entirely in terms of generic devices to
* allow it to be used by any physical HBA in the system.
*/
#include <linux/export.h>
#include <linux/attribute_container.h>
#include <linux/transport_class.h>
/**
* transport_class_register - register an initial transport class
*
* @tclass: a pointer to the transport class structure to be initialised
*
* The transport class contains an embedded class which is used to
* identify it. The caller should initialise this structure with
* zeros and then generic class must have been initialised with the
* actual transport class unique name. There's a macro
* DECLARE_TRANSPORT_CLASS() to do this (declared classes still must
* be registered).
*
* Returns 0 on success or error on failure.
*/
int transport_class_register(struct transport_class *tclass)
{
return class_register(&tclass->class);
}
EXPORT_SYMBOL_GPL(transport_class_register);
/**
* transport_class_unregister - unregister a previously registered class
*
* @tclass: The transport class to unregister
*
* Must be called prior to deallocating the memory for the transport
* class.
*/
void transport_class_unregister(struct transport_class *tclass)
{
class_unregister(&tclass->class);
}
EXPORT_SYMBOL_GPL(transport_class_unregister);
static int anon_transport_dummy_function(struct transport_container *tc,
struct device *dev,
struct device *cdev)
{
/* do nothing */
return 0;
}
/**
* anon_transport_class_register - register an anonymous class
*
* @atc: The anon transport class to register
*
* The anonymous transport class contains both a transport class and a
* container. The idea of an anonymous class is that it never
* actually has any device attributes associated with it (and thus
* saves on container storage). So it can only be used for triggering
* events. Use prezero and then use DECLARE_ANON_TRANSPORT_CLASS() to
* initialise the anon transport class storage.
*/
int anon_transport_class_register(struct anon_transport_class *atc)
{
int error;
atc->container.class = &atc->tclass.class;
attribute_container_set_no_classdevs(&atc->container);
error = attribute_container_register(&atc->container);
if (error)
return error;
atc->tclass.setup = anon_transport_dummy_function;
atc->tclass.remove = anon_transport_dummy_function;
return 0;
}
EXPORT_SYMBOL_GPL(anon_transport_class_register);
/**
* anon_transport_class_unregister - unregister an anon class
*
* @atc: Pointer to the anon transport class to unregister
*
* Must be called prior to deallocating the memory for the anon
* transport class.
*/
void anon_transport_class_unregister(struct anon_transport_class *atc)
{
if (unlikely(attribute_container_unregister(&atc->container)))
BUG();
}
EXPORT_SYMBOL_GPL(anon_transport_class_unregister);
static int transport_setup_classdev(struct attribute_container *cont,
struct device *dev,
struct device *classdev)
{
struct transport_class *tclass = class_to_transport_class(cont->class);
struct transport_container *tcont = attribute_container_to_transport_container(cont);
if (tclass->setup)
tclass->setup(tcont, dev, classdev);
return 0;
}
/**
* transport_setup_device - declare a new dev for transport class association but don't make it visible yet.
* @dev: the generic device representing the entity being added
*
* Usually, dev represents some component in the HBA system (either
* the HBA itself or a device remote across the HBA bus). This
* routine is simply a trigger point to see if any set of transport
* classes wishes to associate with the added device. This allocates
* storage for the class device and initialises it, but does not yet
* add it to the system or add attributes to it (you do this with
* transport_add_device). If you have no need for a separate setup
* and add operations, use transport_register_device (see
* transport_class.h).
*/
void transport_setup_device(struct device *dev)
{
attribute_container_add_device(dev, transport_setup_classdev);
}
EXPORT_SYMBOL_GPL(transport_setup_device);
static int transport_add_class_device(struct attribute_container *cont,
struct device *dev,
struct device *classdev)
{
int error = attribute_container_add_class_device(classdev);
struct transport_container *tcont =
attribute_container_to_transport_container(cont);
if (!error && tcont->statistics)
error = sysfs_create_group(&classdev->kobj, tcont->statistics);
return error;
}
/**
* transport_add_device - declare a new dev for transport class association
*
* @dev: the generic device representing the entity being added
*
* Usually, dev represents some component in the HBA system (either
* the HBA itself or a device remote across the HBA bus). This
* routine is simply a trigger point used to add the device to the
* system and register attributes for it.
*/
void transport_add_device(struct device *dev)
{
attribute_container_device_trigger(dev, transport_add_class_device);
}
EXPORT_SYMBOL_GPL(transport_add_device);
static int transport_configure(struct attribute_container *cont,
struct device *dev,
struct device *cdev)
{
struct transport_class *tclass = class_to_transport_class(cont->class);
struct transport_container *tcont = attribute_container_to_transport_container(cont);
if (tclass->configure)
tclass->configure(tcont, dev, cdev);
return 0;
}
/**
* transport_configure_device - configure an already set up device
*
* @dev: generic device representing device to be configured
*
* The idea of configure is simply to provide a point within the setup
* process to allow the transport class to extract information from a
* device after it has been setup. This is used in SCSI because we
* have to have a setup device to begin using the HBA, but after we
* send the initial inquiry, we use configure to extract the device
* parameters. The device need not have been added to be configured.
*/
void transport_configure_device(struct device *dev)
{
attribute_container_device_trigger(dev, transport_configure);
}
EXPORT_SYMBOL_GPL(transport_configure_device);
static int transport_remove_classdev(struct attribute_container *cont,
struct device *dev,
struct device *classdev)
{
struct transport_container *tcont =
attribute_container_to_transport_container(cont);
struct transport_class *tclass = class_to_transport_class(cont->class);
if (tclass->remove)
tclass->remove(tcont, dev, classdev);
if (tclass->remove != anon_transport_dummy_function) {
if (tcont->statistics)
sysfs_remove_group(&classdev->kobj, tcont->statistics);
attribute_container_class_device_del(classdev);
}
return 0;
}
/**
* transport_remove_device - remove the visibility of a device
*
* @dev: generic device to remove
*
* This call removes the visibility of the device (to the user from
* sysfs), but does not destroy it. To eliminate a device entirely
* you must also call transport_destroy_device. If you don't need to
* do remove and destroy as separate operations, use
* transport_unregister_device() (see transport_class.h) which will
* perform both calls for you.
*/
void transport_remove_device(struct device *dev)
{
attribute_container_device_trigger(dev, transport_remove_classdev);
}
EXPORT_SYMBOL_GPL(transport_remove_device);
static void transport_destroy_classdev(struct attribute_container *cont,
struct device *dev,
struct device *classdev)
{
struct transport_class *tclass = class_to_transport_class(cont->class);
if (tclass->remove != anon_transport_dummy_function)
put_device(classdev);
}
/**
* transport_destroy_device - destroy a removed device
*
* @dev: device to eliminate from the transport class.
*
* This call triggers the elimination of storage associated with the
* transport classdev. Note: all it really does is relinquish a
* reference to the classdev. The memory will not be freed until the
* last reference goes to zero. Note also that the classdev retains a
* reference count on dev, so dev too will remain for as long as the
* transport class device remains around.
*/
void transport_destroy_device(struct device *dev)
{
attribute_container_remove_device(dev, transport_destroy_classdev);
}
EXPORT_SYMBOL_GPL(transport_destroy_device);
| gpl-2.0 |
Kcilorak/s2110_3.0.8_kernel | fs/afs/vlclient.c | 13631 | 5573 | /* AFS Volume Location Service client
*
* Copyright (C) 2002 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/gfp.h>
#include <linux/init.h>
#include <linux/sched.h>
#include "internal.h"
/*
* map volume locator abort codes to error codes
*/
static int afs_vl_abort_to_error(u32 abort_code)
{
_enter("%u", abort_code);
switch (abort_code) {
case AFSVL_IDEXIST: return -EEXIST;
case AFSVL_IO: return -EREMOTEIO;
case AFSVL_NAMEEXIST: return -EEXIST;
case AFSVL_CREATEFAIL: return -EREMOTEIO;
case AFSVL_NOENT: return -ENOMEDIUM;
case AFSVL_EMPTY: return -ENOMEDIUM;
case AFSVL_ENTDELETED: return -ENOMEDIUM;
case AFSVL_BADNAME: return -EINVAL;
case AFSVL_BADINDEX: return -EINVAL;
case AFSVL_BADVOLTYPE: return -EINVAL;
case AFSVL_BADSERVER: return -EINVAL;
case AFSVL_BADPARTITION: return -EINVAL;
case AFSVL_REPSFULL: return -EFBIG;
case AFSVL_NOREPSERVER: return -ENOENT;
case AFSVL_DUPREPSERVER: return -EEXIST;
case AFSVL_RWNOTFOUND: return -ENOENT;
case AFSVL_BADREFCOUNT: return -EINVAL;
case AFSVL_SIZEEXCEEDED: return -EINVAL;
case AFSVL_BADENTRY: return -EINVAL;
case AFSVL_BADVOLIDBUMP: return -EINVAL;
case AFSVL_IDALREADYHASHED: return -EINVAL;
case AFSVL_ENTRYLOCKED: return -EBUSY;
case AFSVL_BADVOLOPER: return -EBADRQC;
case AFSVL_BADRELLOCKTYPE: return -EINVAL;
case AFSVL_RERELEASE: return -EREMOTEIO;
case AFSVL_BADSERVERFLAG: return -EINVAL;
case AFSVL_PERM: return -EACCES;
case AFSVL_NOMEM: return -EREMOTEIO;
default:
return afs_abort_to_error(abort_code);
}
}
/*
* deliver reply data to a VL.GetEntryByXXX call
*/
static int afs_deliver_vl_get_entry_by_xxx(struct afs_call *call,
struct sk_buff *skb, bool last)
{
struct afs_cache_vlocation *entry;
__be32 *bp;
u32 tmp;
int loop;
_enter(",,%u", last);
afs_transfer_reply(call, skb);
if (!last)
return 0;
if (call->reply_size != call->reply_max)
return -EBADMSG;
/* unmarshall the reply once we've received all of it */
entry = call->reply;
bp = call->buffer;
for (loop = 0; loop < 64; loop++)
entry->name[loop] = ntohl(*bp++);
entry->name[loop] = 0;
bp++; /* final NUL */
bp++; /* type */
entry->nservers = ntohl(*bp++);
for (loop = 0; loop < 8; loop++)
entry->servers[loop].s_addr = *bp++;
bp += 8; /* partition IDs */
for (loop = 0; loop < 8; loop++) {
tmp = ntohl(*bp++);
entry->srvtmask[loop] = 0;
if (tmp & AFS_VLSF_RWVOL)
entry->srvtmask[loop] |= AFS_VOL_VTM_RW;
if (tmp & AFS_VLSF_ROVOL)
entry->srvtmask[loop] |= AFS_VOL_VTM_RO;
if (tmp & AFS_VLSF_BACKVOL)
entry->srvtmask[loop] |= AFS_VOL_VTM_BAK;
}
entry->vid[0] = ntohl(*bp++);
entry->vid[1] = ntohl(*bp++);
entry->vid[2] = ntohl(*bp++);
bp++; /* clone ID */
tmp = ntohl(*bp++); /* flags */
entry->vidmask = 0;
if (tmp & AFS_VLF_RWEXISTS)
entry->vidmask |= AFS_VOL_VTM_RW;
if (tmp & AFS_VLF_ROEXISTS)
entry->vidmask |= AFS_VOL_VTM_RO;
if (tmp & AFS_VLF_BACKEXISTS)
entry->vidmask |= AFS_VOL_VTM_BAK;
if (!entry->vidmask)
return -EBADMSG;
_leave(" = 0 [done]");
return 0;
}
/*
* VL.GetEntryByName operation type
*/
static const struct afs_call_type afs_RXVLGetEntryByName = {
.name = "VL.GetEntryByName",
.deliver = afs_deliver_vl_get_entry_by_xxx,
.abort_to_error = afs_vl_abort_to_error,
.destructor = afs_flat_call_destructor,
};
/*
* VL.GetEntryById operation type
*/
static const struct afs_call_type afs_RXVLGetEntryById = {
.name = "VL.GetEntryById",
.deliver = afs_deliver_vl_get_entry_by_xxx,
.abort_to_error = afs_vl_abort_to_error,
.destructor = afs_flat_call_destructor,
};
/*
* dispatch a get volume entry by name operation
*/
int afs_vl_get_entry_by_name(struct in_addr *addr,
struct key *key,
const char *volname,
struct afs_cache_vlocation *entry,
const struct afs_wait_mode *wait_mode)
{
struct afs_call *call;
size_t volnamesz, reqsz, padsz;
__be32 *bp;
_enter("");
volnamesz = strlen(volname);
padsz = (4 - (volnamesz & 3)) & 3;
reqsz = 8 + volnamesz + padsz;
call = afs_alloc_flat_call(&afs_RXVLGetEntryByName, reqsz, 384);
if (!call)
return -ENOMEM;
call->key = key;
call->reply = entry;
call->service_id = VL_SERVICE;
call->port = htons(AFS_VL_PORT);
/* marshall the parameters */
bp = call->request;
*bp++ = htonl(VLGETENTRYBYNAME);
*bp++ = htonl(volnamesz);
memcpy(bp, volname, volnamesz);
if (padsz > 0)
memset((void *) bp + volnamesz, 0, padsz);
/* initiate the call */
return afs_make_call(addr, call, GFP_KERNEL, wait_mode);
}
/*
* dispatch a get volume entry by ID operation
*/
int afs_vl_get_entry_by_id(struct in_addr *addr,
struct key *key,
afs_volid_t volid,
afs_voltype_t voltype,
struct afs_cache_vlocation *entry,
const struct afs_wait_mode *wait_mode)
{
struct afs_call *call;
__be32 *bp;
_enter("");
call = afs_alloc_flat_call(&afs_RXVLGetEntryById, 12, 384);
if (!call)
return -ENOMEM;
call->key = key;
call->reply = entry;
call->service_id = VL_SERVICE;
call->port = htons(AFS_VL_PORT);
/* marshall the parameters */
bp = call->request;
*bp++ = htonl(VLGETENTRYBYID);
*bp++ = htonl(volid);
*bp = htonl(voltype);
/* initiate the call */
return afs_make_call(addr, call, GFP_KERNEL, wait_mode);
}
| gpl-2.0 |
projectz201408/zkernel | drivers/net/ethernet/freescale/gianfar.c | 64 | 92380 | /* drivers/net/ethernet/freescale/gianfar.c
*
* Gianfar Ethernet Driver
* This driver is designed for the non-CPM ethernet controllers
* on the 85xx and 83xx family of integrated processors
* Based on 8260_io/fcc_enet.c
*
* Author: Andy Fleming
* Maintainer: Kumar Gala
* Modifier: Sandeep Gopalpet <sandeep.kumar@freescale.com>
*
* Copyright 2002-2009, 2011-2013 Freescale Semiconductor, Inc.
* Copyright 2007 MontaVista Software, Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* Gianfar: AKA Lambda Draconis, "Dragon"
* RA 11 31 24.2
* Dec +69 19 52
* V 3.84
* B-V +1.62
*
* Theory of operation
*
* The driver is initialized through of_device. Configuration information
* is therefore conveyed through an OF-style device tree.
*
* The Gianfar Ethernet Controller uses a ring of buffer
* descriptors. The beginning is indicated by a register
* pointing to the physical address of the start of the ring.
* The end is determined by a "wrap" bit being set in the
* last descriptor of the ring.
*
* When a packet is received, the RXF bit in the
* IEVENT register is set, triggering an interrupt when the
* corresponding bit in the IMASK register is also set (if
* interrupt coalescing is active, then the interrupt may not
* happen immediately, but will wait until either a set number
* of frames or amount of time have passed). In NAPI, the
* interrupt handler will signal there is work to be done, and
* exit. This method will start at the last known empty
* descriptor, and process every subsequent descriptor until there
* are none left with data (NAPI will stop after a set number of
* packets to give time to other tasks, but will eventually
* process all the packets). The data arrives inside a
* pre-allocated skb, and so after the skb is passed up to the
* stack, a new skb must be allocated, and the address field in
* the buffer descriptor must be updated to indicate this new
* skb.
*
* When the kernel requests that a packet be transmitted, the
* driver starts where it left off last time, and points the
* descriptor at the buffer which was passed in. The driver
* then informs the DMA engine that there are packets ready to
* be transmitted. Once the controller is finished transmitting
* the packet, an interrupt may be triggered (under the same
* conditions as for reception, but depending on the TXF bit).
* The driver then cleans up the buffer.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#define DEBUG
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/unistd.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/if_vlan.h>
#include <linux/spinlock.h>
#include <linux/mm.h>
#include <linux/of_address.h>
#include <linux/of_irq.h>
#include <linux/of_mdio.h>
#include <linux/of_platform.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/udp.h>
#include <linux/in.h>
#include <linux/net_tstamp.h>
#include <asm/io.h>
#include <asm/reg.h>
#include <asm/mpc85xx.h>
#include <asm/irq.h>
#include <asm/uaccess.h>
#include <linux/module.h>
#include <linux/dma-mapping.h>
#include <linux/crc32.h>
#include <linux/mii.h>
#include <linux/phy.h>
#include <linux/phy_fixed.h>
#include <linux/of.h>
#include <linux/of_net.h>
#include "gianfar.h"
#define TX_TIMEOUT (1*HZ)
const char gfar_driver_version[] = "1.3";
static int gfar_enet_open(struct net_device *dev);
static int gfar_start_xmit(struct sk_buff *skb, struct net_device *dev);
static void gfar_reset_task(struct work_struct *work);
static void gfar_timeout(struct net_device *dev);
static int gfar_close(struct net_device *dev);
struct sk_buff *gfar_new_skb(struct net_device *dev);
static void gfar_new_rxbdp(struct gfar_priv_rx_q *rx_queue, struct rxbd8 *bdp,
struct sk_buff *skb);
static int gfar_set_mac_address(struct net_device *dev);
static int gfar_change_mtu(struct net_device *dev, int new_mtu);
static irqreturn_t gfar_error(int irq, void *dev_id);
static irqreturn_t gfar_transmit(int irq, void *dev_id);
static irqreturn_t gfar_interrupt(int irq, void *dev_id);
static void adjust_link(struct net_device *dev);
static noinline void gfar_update_link_state(struct gfar_private *priv);
static int init_phy(struct net_device *dev);
static int gfar_probe(struct platform_device *ofdev);
static int gfar_remove(struct platform_device *ofdev);
static void free_skb_resources(struct gfar_private *priv);
static void gfar_set_multi(struct net_device *dev);
static void gfar_set_hash_for_addr(struct net_device *dev, u8 *addr);
static void gfar_configure_serdes(struct net_device *dev);
static int gfar_poll_rx(struct napi_struct *napi, int budget);
static int gfar_poll_tx(struct napi_struct *napi, int budget);
static int gfar_poll_rx_sq(struct napi_struct *napi, int budget);
static int gfar_poll_tx_sq(struct napi_struct *napi, int budget);
#ifdef CONFIG_NET_POLL_CONTROLLER
static void gfar_netpoll(struct net_device *dev);
#endif
int gfar_clean_rx_ring(struct gfar_priv_rx_q *rx_queue, int rx_work_limit);
static void gfar_clean_tx_ring(struct gfar_priv_tx_q *tx_queue);
static void gfar_process_frame(struct net_device *dev, struct sk_buff *skb,
int amount_pull, struct napi_struct *napi);
static void gfar_halt_nodisable(struct gfar_private *priv);
static void gfar_clear_exact_match(struct net_device *dev);
static void gfar_set_mac_for_addr(struct net_device *dev, int num,
const u8 *addr);
static int gfar_ioctl(struct net_device *dev, struct ifreq *rq, int cmd);
MODULE_AUTHOR("Freescale Semiconductor, Inc");
MODULE_DESCRIPTION("Gianfar Ethernet Driver");
MODULE_LICENSE("GPL");
static void gfar_init_rxbdp(struct gfar_priv_rx_q *rx_queue, struct rxbd8 *bdp,
dma_addr_t buf)
{
u32 lstatus;
bdp->bufPtr = buf;
lstatus = BD_LFLAG(RXBD_EMPTY | RXBD_INTERRUPT);
if (bdp == rx_queue->rx_bd_base + rx_queue->rx_ring_size - 1)
lstatus |= BD_LFLAG(RXBD_WRAP);
eieio();
bdp->lstatus = lstatus;
}
static int gfar_init_bds(struct net_device *ndev)
{
struct gfar_private *priv = netdev_priv(ndev);
struct gfar_priv_tx_q *tx_queue = NULL;
struct gfar_priv_rx_q *rx_queue = NULL;
struct txbd8 *txbdp;
struct rxbd8 *rxbdp;
int i, j;
for (i = 0; i < priv->num_tx_queues; i++) {
tx_queue = priv->tx_queue[i];
/* Initialize some variables in our dev structure */
tx_queue->num_txbdfree = tx_queue->tx_ring_size;
tx_queue->dirty_tx = tx_queue->tx_bd_base;
tx_queue->cur_tx = tx_queue->tx_bd_base;
tx_queue->skb_curtx = 0;
tx_queue->skb_dirtytx = 0;
/* Initialize Transmit Descriptor Ring */
txbdp = tx_queue->tx_bd_base;
for (j = 0; j < tx_queue->tx_ring_size; j++) {
txbdp->lstatus = 0;
txbdp->bufPtr = 0;
txbdp++;
}
/* Set the last descriptor in the ring to indicate wrap */
txbdp--;
txbdp->status |= TXBD_WRAP;
}
for (i = 0; i < priv->num_rx_queues; i++) {
rx_queue = priv->rx_queue[i];
rx_queue->cur_rx = rx_queue->rx_bd_base;
rx_queue->skb_currx = 0;
rxbdp = rx_queue->rx_bd_base;
for (j = 0; j < rx_queue->rx_ring_size; j++) {
struct sk_buff *skb = rx_queue->rx_skbuff[j];
if (skb) {
gfar_init_rxbdp(rx_queue, rxbdp,
rxbdp->bufPtr);
} else {
skb = gfar_new_skb(ndev);
if (!skb) {
netdev_err(ndev, "Can't allocate RX buffers\n");
return -ENOMEM;
}
rx_queue->rx_skbuff[j] = skb;
gfar_new_rxbdp(rx_queue, rxbdp, skb);
}
rxbdp++;
}
}
return 0;
}
static int gfar_alloc_skb_resources(struct net_device *ndev)
{
void *vaddr;
dma_addr_t addr;
int i, j, k;
struct gfar_private *priv = netdev_priv(ndev);
struct device *dev = priv->dev;
struct gfar_priv_tx_q *tx_queue = NULL;
struct gfar_priv_rx_q *rx_queue = NULL;
priv->total_tx_ring_size = 0;
for (i = 0; i < priv->num_tx_queues; i++)
priv->total_tx_ring_size += priv->tx_queue[i]->tx_ring_size;
priv->total_rx_ring_size = 0;
for (i = 0; i < priv->num_rx_queues; i++)
priv->total_rx_ring_size += priv->rx_queue[i]->rx_ring_size;
/* Allocate memory for the buffer descriptors */
vaddr = dma_alloc_coherent(dev,
(priv->total_tx_ring_size *
sizeof(struct txbd8)) +
(priv->total_rx_ring_size *
sizeof(struct rxbd8)),
&addr, GFP_KERNEL);
if (!vaddr)
return -ENOMEM;
for (i = 0; i < priv->num_tx_queues; i++) {
tx_queue = priv->tx_queue[i];
tx_queue->tx_bd_base = vaddr;
tx_queue->tx_bd_dma_base = addr;
tx_queue->dev = ndev;
/* enet DMA only understands physical addresses */
addr += sizeof(struct txbd8) * tx_queue->tx_ring_size;
vaddr += sizeof(struct txbd8) * tx_queue->tx_ring_size;
}
/* Start the rx descriptor ring where the tx ring leaves off */
for (i = 0; i < priv->num_rx_queues; i++) {
rx_queue = priv->rx_queue[i];
rx_queue->rx_bd_base = vaddr;
rx_queue->rx_bd_dma_base = addr;
rx_queue->dev = ndev;
addr += sizeof(struct rxbd8) * rx_queue->rx_ring_size;
vaddr += sizeof(struct rxbd8) * rx_queue->rx_ring_size;
}
/* Setup the skbuff rings */
for (i = 0; i < priv->num_tx_queues; i++) {
tx_queue = priv->tx_queue[i];
tx_queue->tx_skbuff =
kmalloc_array(tx_queue->tx_ring_size,
sizeof(*tx_queue->tx_skbuff),
GFP_KERNEL);
if (!tx_queue->tx_skbuff)
goto cleanup;
for (k = 0; k < tx_queue->tx_ring_size; k++)
tx_queue->tx_skbuff[k] = NULL;
}
for (i = 0; i < priv->num_rx_queues; i++) {
rx_queue = priv->rx_queue[i];
rx_queue->rx_skbuff =
kmalloc_array(rx_queue->rx_ring_size,
sizeof(*rx_queue->rx_skbuff),
GFP_KERNEL);
if (!rx_queue->rx_skbuff)
goto cleanup;
for (j = 0; j < rx_queue->rx_ring_size; j++)
rx_queue->rx_skbuff[j] = NULL;
}
if (gfar_init_bds(ndev))
goto cleanup;
return 0;
cleanup:
free_skb_resources(priv);
return -ENOMEM;
}
static void gfar_init_tx_rx_base(struct gfar_private *priv)
{
struct gfar __iomem *regs = priv->gfargrp[0].regs;
u32 __iomem *baddr;
int i;
baddr = ®s->tbase0;
for (i = 0; i < priv->num_tx_queues; i++) {
gfar_write(baddr, priv->tx_queue[i]->tx_bd_dma_base);
baddr += 2;
}
baddr = ®s->rbase0;
for (i = 0; i < priv->num_rx_queues; i++) {
gfar_write(baddr, priv->rx_queue[i]->rx_bd_dma_base);
baddr += 2;
}
}
static void gfar_rx_buff_size_config(struct gfar_private *priv)
{
int frame_size = priv->ndev->mtu + ETH_HLEN;
/* set this when rx hw offload (TOE) functions are being used */
priv->uses_rxfcb = 0;
if (priv->ndev->features & (NETIF_F_RXCSUM | NETIF_F_HW_VLAN_CTAG_RX))
priv->uses_rxfcb = 1;
if (priv->hwts_rx_en)
priv->uses_rxfcb = 1;
if (priv->uses_rxfcb)
frame_size += GMAC_FCB_LEN;
frame_size += priv->padding;
frame_size = (frame_size & ~(INCREMENTAL_BUFFER_SIZE - 1)) +
INCREMENTAL_BUFFER_SIZE;
priv->rx_buffer_size = frame_size;
}
static void gfar_mac_rx_config(struct gfar_private *priv)
{
struct gfar __iomem *regs = priv->gfargrp[0].regs;
u32 rctrl = 0;
if (priv->rx_filer_enable) {
rctrl |= RCTRL_FILREN;
/* Program the RIR0 reg with the required distribution */
if (priv->poll_mode == GFAR_SQ_POLLING)
gfar_write(®s->rir0, DEFAULT_2RXQ_RIR0);
else /* GFAR_MQ_POLLING */
gfar_write(®s->rir0, DEFAULT_8RXQ_RIR0);
}
/* Restore PROMISC mode */
if (priv->ndev->flags & IFF_PROMISC)
rctrl |= RCTRL_PROM;
if (priv->ndev->features & NETIF_F_RXCSUM)
rctrl |= RCTRL_CHECKSUMMING;
if (priv->extended_hash)
rctrl |= RCTRL_EXTHASH | RCTRL_EMEN;
if (priv->padding) {
rctrl &= ~RCTRL_PAL_MASK;
rctrl |= RCTRL_PADDING(priv->padding);
}
/* Enable HW time stamping if requested from user space */
if (priv->hwts_rx_en)
rctrl |= RCTRL_PRSDEP_INIT | RCTRL_TS_ENABLE;
if (priv->ndev->features & NETIF_F_HW_VLAN_CTAG_RX)
rctrl |= RCTRL_VLEX | RCTRL_PRSDEP_INIT;
/* Init rctrl based on our settings */
gfar_write(®s->rctrl, rctrl);
}
static void gfar_mac_tx_config(struct gfar_private *priv)
{
struct gfar __iomem *regs = priv->gfargrp[0].regs;
u32 tctrl = 0;
if (priv->ndev->features & NETIF_F_IP_CSUM)
tctrl |= TCTRL_INIT_CSUM;
if (priv->prio_sched_en)
tctrl |= TCTRL_TXSCHED_PRIO;
else {
tctrl |= TCTRL_TXSCHED_WRRS;
gfar_write(®s->tr03wt, DEFAULT_WRRS_WEIGHT);
gfar_write(®s->tr47wt, DEFAULT_WRRS_WEIGHT);
}
if (priv->ndev->features & NETIF_F_HW_VLAN_CTAG_TX)
tctrl |= TCTRL_VLINS;
gfar_write(®s->tctrl, tctrl);
}
static void gfar_configure_coalescing(struct gfar_private *priv,
unsigned long tx_mask, unsigned long rx_mask)
{
struct gfar __iomem *regs = priv->gfargrp[0].regs;
u32 __iomem *baddr;
if (priv->mode == MQ_MG_MODE) {
int i = 0;
baddr = ®s->txic0;
for_each_set_bit(i, &tx_mask, priv->num_tx_queues) {
gfar_write(baddr + i, 0);
if (likely(priv->tx_queue[i]->txcoalescing))
gfar_write(baddr + i, priv->tx_queue[i]->txic);
}
baddr = ®s->rxic0;
for_each_set_bit(i, &rx_mask, priv->num_rx_queues) {
gfar_write(baddr + i, 0);
if (likely(priv->rx_queue[i]->rxcoalescing))
gfar_write(baddr + i, priv->rx_queue[i]->rxic);
}
} else {
/* Backward compatible case -- even if we enable
* multiple queues, there's only single reg to program
*/
gfar_write(®s->txic, 0);
if (likely(priv->tx_queue[0]->txcoalescing))
gfar_write(®s->txic, priv->tx_queue[0]->txic);
gfar_write(®s->rxic, 0);
if (unlikely(priv->rx_queue[0]->rxcoalescing))
gfar_write(®s->rxic, priv->rx_queue[0]->rxic);
}
}
void gfar_configure_coalescing_all(struct gfar_private *priv)
{
gfar_configure_coalescing(priv, 0xFF, 0xFF);
}
static struct net_device_stats *gfar_get_stats(struct net_device *dev)
{
struct gfar_private *priv = netdev_priv(dev);
unsigned long rx_packets = 0, rx_bytes = 0, rx_dropped = 0;
unsigned long tx_packets = 0, tx_bytes = 0;
int i;
for (i = 0; i < priv->num_rx_queues; i++) {
rx_packets += priv->rx_queue[i]->stats.rx_packets;
rx_bytes += priv->rx_queue[i]->stats.rx_bytes;
rx_dropped += priv->rx_queue[i]->stats.rx_dropped;
}
dev->stats.rx_packets = rx_packets;
dev->stats.rx_bytes = rx_bytes;
dev->stats.rx_dropped = rx_dropped;
for (i = 0; i < priv->num_tx_queues; i++) {
tx_bytes += priv->tx_queue[i]->stats.tx_bytes;
tx_packets += priv->tx_queue[i]->stats.tx_packets;
}
dev->stats.tx_bytes = tx_bytes;
dev->stats.tx_packets = tx_packets;
return &dev->stats;
}
static const struct net_device_ops gfar_netdev_ops = {
.ndo_open = gfar_enet_open,
.ndo_start_xmit = gfar_start_xmit,
.ndo_stop = gfar_close,
.ndo_change_mtu = gfar_change_mtu,
.ndo_set_features = gfar_set_features,
.ndo_set_rx_mode = gfar_set_multi,
.ndo_tx_timeout = gfar_timeout,
.ndo_do_ioctl = gfar_ioctl,
.ndo_get_stats = gfar_get_stats,
.ndo_set_mac_address = eth_mac_addr,
.ndo_validate_addr = eth_validate_addr,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = gfar_netpoll,
#endif
};
static void gfar_ints_disable(struct gfar_private *priv)
{
int i;
for (i = 0; i < priv->num_grps; i++) {
struct gfar __iomem *regs = priv->gfargrp[i].regs;
/* Clear IEVENT */
gfar_write(®s->ievent, IEVENT_INIT_CLEAR);
/* Initialize IMASK */
gfar_write(®s->imask, IMASK_INIT_CLEAR);
}
}
static void gfar_ints_enable(struct gfar_private *priv)
{
int i;
for (i = 0; i < priv->num_grps; i++) {
struct gfar __iomem *regs = priv->gfargrp[i].regs;
/* Unmask the interrupts we look for */
gfar_write(®s->imask, IMASK_DEFAULT);
}
}
void lock_tx_qs(struct gfar_private *priv)
{
int i;
for (i = 0; i < priv->num_tx_queues; i++)
spin_lock(&priv->tx_queue[i]->txlock);
}
void unlock_tx_qs(struct gfar_private *priv)
{
int i;
for (i = 0; i < priv->num_tx_queues; i++)
spin_unlock(&priv->tx_queue[i]->txlock);
}
static int gfar_alloc_tx_queues(struct gfar_private *priv)
{
int i;
for (i = 0; i < priv->num_tx_queues; i++) {
priv->tx_queue[i] = kzalloc(sizeof(struct gfar_priv_tx_q),
GFP_KERNEL);
if (!priv->tx_queue[i])
return -ENOMEM;
priv->tx_queue[i]->tx_skbuff = NULL;
priv->tx_queue[i]->qindex = i;
priv->tx_queue[i]->dev = priv->ndev;
spin_lock_init(&(priv->tx_queue[i]->txlock));
}
return 0;
}
static int gfar_alloc_rx_queues(struct gfar_private *priv)
{
int i;
for (i = 0; i < priv->num_rx_queues; i++) {
priv->rx_queue[i] = kzalloc(sizeof(struct gfar_priv_rx_q),
GFP_KERNEL);
if (!priv->rx_queue[i])
return -ENOMEM;
priv->rx_queue[i]->rx_skbuff = NULL;
priv->rx_queue[i]->qindex = i;
priv->rx_queue[i]->dev = priv->ndev;
}
return 0;
}
static void gfar_free_tx_queues(struct gfar_private *priv)
{
int i;
for (i = 0; i < priv->num_tx_queues; i++)
kfree(priv->tx_queue[i]);
}
static void gfar_free_rx_queues(struct gfar_private *priv)
{
int i;
for (i = 0; i < priv->num_rx_queues; i++)
kfree(priv->rx_queue[i]);
}
static void unmap_group_regs(struct gfar_private *priv)
{
int i;
for (i = 0; i < MAXGROUPS; i++)
if (priv->gfargrp[i].regs)
iounmap(priv->gfargrp[i].regs);
}
static void free_gfar_dev(struct gfar_private *priv)
{
int i, j;
for (i = 0; i < priv->num_grps; i++)
for (j = 0; j < GFAR_NUM_IRQS; j++) {
kfree(priv->gfargrp[i].irqinfo[j]);
priv->gfargrp[i].irqinfo[j] = NULL;
}
free_netdev(priv->ndev);
}
static void disable_napi(struct gfar_private *priv)
{
int i;
for (i = 0; i < priv->num_grps; i++) {
napi_disable(&priv->gfargrp[i].napi_rx);
napi_disable(&priv->gfargrp[i].napi_tx);
}
}
static void enable_napi(struct gfar_private *priv)
{
int i;
for (i = 0; i < priv->num_grps; i++) {
napi_enable(&priv->gfargrp[i].napi_rx);
napi_enable(&priv->gfargrp[i].napi_tx);
}
}
static int gfar_parse_group(struct device_node *np,
struct gfar_private *priv, const char *model)
{
struct gfar_priv_grp *grp = &priv->gfargrp[priv->num_grps];
int i;
for (i = 0; i < GFAR_NUM_IRQS; i++) {
grp->irqinfo[i] = kzalloc(sizeof(struct gfar_irqinfo),
GFP_KERNEL);
if (!grp->irqinfo[i])
return -ENOMEM;
}
grp->regs = of_iomap(np, 0);
if (!grp->regs)
return -ENOMEM;
gfar_irq(grp, TX)->irq = irq_of_parse_and_map(np, 0);
/* If we aren't the FEC we have multiple interrupts */
if (model && strcasecmp(model, "FEC")) {
gfar_irq(grp, RX)->irq = irq_of_parse_and_map(np, 1);
gfar_irq(grp, ER)->irq = irq_of_parse_and_map(np, 2);
if (gfar_irq(grp, TX)->irq == NO_IRQ ||
gfar_irq(grp, RX)->irq == NO_IRQ ||
gfar_irq(grp, ER)->irq == NO_IRQ)
return -EINVAL;
}
grp->priv = priv;
spin_lock_init(&grp->grplock);
if (priv->mode == MQ_MG_MODE) {
u32 *rxq_mask, *txq_mask;
rxq_mask = (u32 *)of_get_property(np, "fsl,rx-bit-map", NULL);
txq_mask = (u32 *)of_get_property(np, "fsl,tx-bit-map", NULL);
if (priv->poll_mode == GFAR_SQ_POLLING) {
/* One Q per interrupt group: Q0 to G0, Q1 to G1 */
grp->rx_bit_map = (DEFAULT_MAPPING >> priv->num_grps);
grp->tx_bit_map = (DEFAULT_MAPPING >> priv->num_grps);
} else { /* GFAR_MQ_POLLING */
grp->rx_bit_map = rxq_mask ?
*rxq_mask : (DEFAULT_MAPPING >> priv->num_grps);
grp->tx_bit_map = txq_mask ?
*txq_mask : (DEFAULT_MAPPING >> priv->num_grps);
}
} else {
grp->rx_bit_map = 0xFF;
grp->tx_bit_map = 0xFF;
}
/* bit_map's MSB is q0 (from q0 to q7) but, for_each_set_bit parses
* right to left, so we need to revert the 8 bits to get the q index
*/
grp->rx_bit_map = bitrev8(grp->rx_bit_map);
grp->tx_bit_map = bitrev8(grp->tx_bit_map);
/* Calculate RSTAT, TSTAT, RQUEUE and TQUEUE values,
* also assign queues to groups
*/
for_each_set_bit(i, &grp->rx_bit_map, priv->num_rx_queues) {
if (!grp->rx_queue)
grp->rx_queue = priv->rx_queue[i];
grp->num_rx_queues++;
grp->rstat |= (RSTAT_CLEAR_RHALT >> i);
priv->rqueue |= ((RQUEUE_EN0 | RQUEUE_EX0) >> i);
priv->rx_queue[i]->grp = grp;
}
for_each_set_bit(i, &grp->tx_bit_map, priv->num_tx_queues) {
if (!grp->tx_queue)
grp->tx_queue = priv->tx_queue[i];
grp->num_tx_queues++;
grp->tstat |= (TSTAT_CLEAR_THALT >> i);
priv->tqueue |= (TQUEUE_EN0 >> i);
priv->tx_queue[i]->grp = grp;
}
priv->num_grps++;
return 0;
}
static int gfar_of_init(struct platform_device *ofdev, struct net_device **pdev)
{
const char *model;
const char *ctype;
const void *mac_addr;
int err = 0, i;
struct net_device *dev = NULL;
struct gfar_private *priv = NULL;
struct device_node *np = ofdev->dev.of_node;
struct device_node *child = NULL;
const u32 *stash;
const u32 *stash_len;
const u32 *stash_idx;
unsigned int num_tx_qs, num_rx_qs;
u32 *tx_queues, *rx_queues;
unsigned short mode, poll_mode;
if (!np || !of_device_is_available(np))
return -ENODEV;
if (of_device_is_compatible(np, "fsl,etsec2")) {
mode = MQ_MG_MODE;
poll_mode = GFAR_SQ_POLLING;
} else {
mode = SQ_SG_MODE;
poll_mode = GFAR_SQ_POLLING;
}
/* parse the num of HW tx and rx queues */
tx_queues = (u32 *)of_get_property(np, "fsl,num_tx_queues", NULL);
rx_queues = (u32 *)of_get_property(np, "fsl,num_rx_queues", NULL);
if (mode == SQ_SG_MODE) {
num_tx_qs = 1;
num_rx_qs = 1;
} else { /* MQ_MG_MODE */
/* get the actual number of supported groups */
unsigned int num_grps = of_get_available_child_count(np);
if (num_grps == 0 || num_grps > MAXGROUPS) {
dev_err(&ofdev->dev, "Invalid # of int groups(%d)\n",
num_grps);
pr_err("Cannot do alloc_etherdev, aborting\n");
return -EINVAL;
}
if (poll_mode == GFAR_SQ_POLLING) {
num_tx_qs = num_grps; /* one txq per int group */
num_rx_qs = num_grps; /* one rxq per int group */
} else { /* GFAR_MQ_POLLING */
num_tx_qs = tx_queues ? *tx_queues : 1;
num_rx_qs = rx_queues ? *rx_queues : 1;
}
}
if (num_tx_qs > MAX_TX_QS) {
pr_err("num_tx_qs(=%d) greater than MAX_TX_QS(=%d)\n",
num_tx_qs, MAX_TX_QS);
pr_err("Cannot do alloc_etherdev, aborting\n");
return -EINVAL;
}
if (num_rx_qs > MAX_RX_QS) {
pr_err("num_rx_qs(=%d) greater than MAX_RX_QS(=%d)\n",
num_rx_qs, MAX_RX_QS);
pr_err("Cannot do alloc_etherdev, aborting\n");
return -EINVAL;
}
*pdev = alloc_etherdev_mq(sizeof(*priv), num_tx_qs);
dev = *pdev;
if (NULL == dev)
return -ENOMEM;
priv = netdev_priv(dev);
priv->ndev = dev;
priv->mode = mode;
priv->poll_mode = poll_mode;
priv->num_tx_queues = num_tx_qs;
netif_set_real_num_rx_queues(dev, num_rx_qs);
priv->num_rx_queues = num_rx_qs;
err = gfar_alloc_tx_queues(priv);
if (err)
goto tx_alloc_failed;
err = gfar_alloc_rx_queues(priv);
if (err)
goto rx_alloc_failed;
/* Init Rx queue filer rule set linked list */
INIT_LIST_HEAD(&priv->rx_list.list);
priv->rx_list.count = 0;
mutex_init(&priv->rx_queue_access);
model = of_get_property(np, "model", NULL);
for (i = 0; i < MAXGROUPS; i++)
priv->gfargrp[i].regs = NULL;
/* Parse and initialize group specific information */
if (priv->mode == MQ_MG_MODE) {
for_each_child_of_node(np, child) {
err = gfar_parse_group(child, priv, model);
if (err)
goto err_grp_init;
}
} else { /* SQ_SG_MODE */
err = gfar_parse_group(np, priv, model);
if (err)
goto err_grp_init;
}
stash = of_get_property(np, "bd-stash", NULL);
if (stash) {
priv->device_flags |= FSL_GIANFAR_DEV_HAS_BD_STASHING;
priv->bd_stash_en = 1;
}
stash_len = of_get_property(np, "rx-stash-len", NULL);
if (stash_len)
priv->rx_stash_size = *stash_len;
stash_idx = of_get_property(np, "rx-stash-idx", NULL);
if (stash_idx)
priv->rx_stash_index = *stash_idx;
if (stash_len || stash_idx)
priv->device_flags |= FSL_GIANFAR_DEV_HAS_BUF_STASHING;
mac_addr = of_get_mac_address(np);
if (mac_addr)
memcpy(dev->dev_addr, mac_addr, ETH_ALEN);
if (model && !strcasecmp(model, "TSEC"))
priv->device_flags |= FSL_GIANFAR_DEV_HAS_GIGABIT |
FSL_GIANFAR_DEV_HAS_COALESCE |
FSL_GIANFAR_DEV_HAS_RMON |
FSL_GIANFAR_DEV_HAS_MULTI_INTR;
if (model && !strcasecmp(model, "eTSEC"))
priv->device_flags |= FSL_GIANFAR_DEV_HAS_GIGABIT |
FSL_GIANFAR_DEV_HAS_COALESCE |
FSL_GIANFAR_DEV_HAS_RMON |
FSL_GIANFAR_DEV_HAS_MULTI_INTR |
FSL_GIANFAR_DEV_HAS_CSUM |
FSL_GIANFAR_DEV_HAS_VLAN |
FSL_GIANFAR_DEV_HAS_MAGIC_PACKET |
FSL_GIANFAR_DEV_HAS_EXTENDED_HASH |
FSL_GIANFAR_DEV_HAS_TIMER;
ctype = of_get_property(np, "phy-connection-type", NULL);
/* We only care about rgmii-id. The rest are autodetected */
if (ctype && !strcmp(ctype, "rgmii-id"))
priv->interface = PHY_INTERFACE_MODE_RGMII_ID;
else
priv->interface = PHY_INTERFACE_MODE_MII;
if (of_get_property(np, "fsl,magic-packet", NULL))
priv->device_flags |= FSL_GIANFAR_DEV_HAS_MAGIC_PACKET;
priv->phy_node = of_parse_phandle(np, "phy-handle", 0);
/* In the case of a fixed PHY, the DT node associated
* to the PHY is the Ethernet MAC DT node.
*/
if (of_phy_is_fixed_link(np)) {
err = of_phy_register_fixed_link(np);
if (err)
goto err_grp_init;
priv->phy_node = np;
}
/* Find the TBI PHY. If it's not there, we don't support SGMII */
priv->tbi_node = of_parse_phandle(np, "tbi-handle", 0);
return 0;
err_grp_init:
unmap_group_regs(priv);
rx_alloc_failed:
gfar_free_rx_queues(priv);
tx_alloc_failed:
gfar_free_tx_queues(priv);
free_gfar_dev(priv);
return err;
}
static int gfar_hwtstamp_set(struct net_device *netdev, struct ifreq *ifr)
{
struct hwtstamp_config config;
struct gfar_private *priv = netdev_priv(netdev);
if (copy_from_user(&config, ifr->ifr_data, sizeof(config)))
return -EFAULT;
/* reserved for future extensions */
if (config.flags)
return -EINVAL;
switch (config.tx_type) {
case HWTSTAMP_TX_OFF:
priv->hwts_tx_en = 0;
break;
case HWTSTAMP_TX_ON:
if (!(priv->device_flags & FSL_GIANFAR_DEV_HAS_TIMER))
return -ERANGE;
priv->hwts_tx_en = 1;
break;
default:
return -ERANGE;
}
switch (config.rx_filter) {
case HWTSTAMP_FILTER_NONE:
if (priv->hwts_rx_en) {
priv->hwts_rx_en = 0;
reset_gfar(netdev);
}
break;
default:
if (!(priv->device_flags & FSL_GIANFAR_DEV_HAS_TIMER))
return -ERANGE;
if (!priv->hwts_rx_en) {
priv->hwts_rx_en = 1;
reset_gfar(netdev);
}
config.rx_filter = HWTSTAMP_FILTER_ALL;
break;
}
return copy_to_user(ifr->ifr_data, &config, sizeof(config)) ?
-EFAULT : 0;
}
static int gfar_hwtstamp_get(struct net_device *netdev, struct ifreq *ifr)
{
struct hwtstamp_config config;
struct gfar_private *priv = netdev_priv(netdev);
config.flags = 0;
config.tx_type = priv->hwts_tx_en ? HWTSTAMP_TX_ON : HWTSTAMP_TX_OFF;
config.rx_filter = (priv->hwts_rx_en ?
HWTSTAMP_FILTER_ALL : HWTSTAMP_FILTER_NONE);
return copy_to_user(ifr->ifr_data, &config, sizeof(config)) ?
-EFAULT : 0;
}
static int gfar_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
{
struct gfar_private *priv = netdev_priv(dev);
if (!netif_running(dev))
return -EINVAL;
if (cmd == SIOCSHWTSTAMP)
return gfar_hwtstamp_set(dev, rq);
if (cmd == SIOCGHWTSTAMP)
return gfar_hwtstamp_get(dev, rq);
if (!priv->phydev)
return -ENODEV;
return phy_mii_ioctl(priv->phydev, rq, cmd);
}
static u32 cluster_entry_per_class(struct gfar_private *priv, u32 rqfar,
u32 class)
{
u32 rqfpr = FPR_FILER_MASK;
u32 rqfcr = 0x0;
rqfar--;
rqfcr = RQFCR_CLE | RQFCR_PID_MASK | RQFCR_CMP_EXACT;
priv->ftp_rqfpr[rqfar] = rqfpr;
priv->ftp_rqfcr[rqfar] = rqfcr;
gfar_write_filer(priv, rqfar, rqfcr, rqfpr);
rqfar--;
rqfcr = RQFCR_CMP_NOMATCH;
priv->ftp_rqfpr[rqfar] = rqfpr;
priv->ftp_rqfcr[rqfar] = rqfcr;
gfar_write_filer(priv, rqfar, rqfcr, rqfpr);
rqfar--;
rqfcr = RQFCR_CMP_EXACT | RQFCR_PID_PARSE | RQFCR_CLE | RQFCR_AND;
rqfpr = class;
priv->ftp_rqfcr[rqfar] = rqfcr;
priv->ftp_rqfpr[rqfar] = rqfpr;
gfar_write_filer(priv, rqfar, rqfcr, rqfpr);
rqfar--;
rqfcr = RQFCR_CMP_EXACT | RQFCR_PID_MASK | RQFCR_AND;
rqfpr = class;
priv->ftp_rqfcr[rqfar] = rqfcr;
priv->ftp_rqfpr[rqfar] = rqfpr;
gfar_write_filer(priv, rqfar, rqfcr, rqfpr);
return rqfar;
}
static void gfar_init_filer_table(struct gfar_private *priv)
{
int i = 0x0;
u32 rqfar = MAX_FILER_IDX;
u32 rqfcr = 0x0;
u32 rqfpr = FPR_FILER_MASK;
/* Default rule */
rqfcr = RQFCR_CMP_MATCH;
priv->ftp_rqfcr[rqfar] = rqfcr;
priv->ftp_rqfpr[rqfar] = rqfpr;
gfar_write_filer(priv, rqfar, rqfcr, rqfpr);
rqfar = cluster_entry_per_class(priv, rqfar, RQFPR_IPV6);
rqfar = cluster_entry_per_class(priv, rqfar, RQFPR_IPV6 | RQFPR_UDP);
rqfar = cluster_entry_per_class(priv, rqfar, RQFPR_IPV6 | RQFPR_TCP);
rqfar = cluster_entry_per_class(priv, rqfar, RQFPR_IPV4);
rqfar = cluster_entry_per_class(priv, rqfar, RQFPR_IPV4 | RQFPR_UDP);
rqfar = cluster_entry_per_class(priv, rqfar, RQFPR_IPV4 | RQFPR_TCP);
/* cur_filer_idx indicated the first non-masked rule */
priv->cur_filer_idx = rqfar;
/* Rest are masked rules */
rqfcr = RQFCR_CMP_NOMATCH;
for (i = 0; i < rqfar; i++) {
priv->ftp_rqfcr[i] = rqfcr;
priv->ftp_rqfpr[i] = rqfpr;
gfar_write_filer(priv, i, rqfcr, rqfpr);
}
}
static void __gfar_detect_errata_83xx(struct gfar_private *priv)
{
unsigned int pvr = mfspr(SPRN_PVR);
unsigned int svr = mfspr(SPRN_SVR);
unsigned int mod = (svr >> 16) & 0xfff6; /* w/o E suffix */
unsigned int rev = svr & 0xffff;
/* MPC8313 Rev 2.0 and higher; All MPC837x */
if ((pvr == 0x80850010 && mod == 0x80b0 && rev >= 0x0020) ||
(pvr == 0x80861010 && (mod & 0xfff9) == 0x80c0))
priv->errata |= GFAR_ERRATA_74;
/* MPC8313 and MPC837x all rev */
if ((pvr == 0x80850010 && mod == 0x80b0) ||
(pvr == 0x80861010 && (mod & 0xfff9) == 0x80c0))
priv->errata |= GFAR_ERRATA_76;
/* MPC8313 Rev < 2.0 */
if (pvr == 0x80850010 && mod == 0x80b0 && rev < 0x0020)
priv->errata |= GFAR_ERRATA_12;
}
static void __gfar_detect_errata_85xx(struct gfar_private *priv)
{
unsigned int svr = mfspr(SPRN_SVR);
if ((SVR_SOC_VER(svr) == SVR_8548) && (SVR_REV(svr) == 0x20))
priv->errata |= GFAR_ERRATA_12;
if (((SVR_SOC_VER(svr) == SVR_P2020) && (SVR_REV(svr) < 0x20)) ||
((SVR_SOC_VER(svr) == SVR_P2010) && (SVR_REV(svr) < 0x20)))
priv->errata |= GFAR_ERRATA_76; /* aka eTSEC 20 */
}
static void gfar_detect_errata(struct gfar_private *priv)
{
struct device *dev = &priv->ofdev->dev;
/* no plans to fix */
priv->errata |= GFAR_ERRATA_A002;
if (pvr_version_is(PVR_VER_E500V1) || pvr_version_is(PVR_VER_E500V2))
__gfar_detect_errata_85xx(priv);
else /* non-mpc85xx parts, i.e. e300 core based */
__gfar_detect_errata_83xx(priv);
if (priv->errata)
dev_info(dev, "enabled errata workarounds, flags: 0x%x\n",
priv->errata);
}
void gfar_mac_reset(struct gfar_private *priv)
{
struct gfar __iomem *regs = priv->gfargrp[0].regs;
u32 tempval;
/* Reset MAC layer */
gfar_write(®s->maccfg1, MACCFG1_SOFT_RESET);
/* We need to delay at least 3 TX clocks */
udelay(3);
/* the soft reset bit is not self-resetting, so we need to
* clear it before resuming normal operation
*/
gfar_write(®s->maccfg1, 0);
udelay(3);
/* Compute rx_buff_size based on config flags */
gfar_rx_buff_size_config(priv);
/* Initialize the max receive frame/buffer lengths */
gfar_write(®s->maxfrm, priv->rx_buffer_size);
gfar_write(®s->mrblr, priv->rx_buffer_size);
/* Initialize the Minimum Frame Length Register */
gfar_write(®s->minflr, MINFLR_INIT_SETTINGS);
/* Initialize MACCFG2. */
tempval = MACCFG2_INIT_SETTINGS;
/* If the mtu is larger than the max size for standard
* ethernet frames (ie, a jumbo frame), then set maccfg2
* to allow huge frames, and to check the length
*/
if (priv->rx_buffer_size > DEFAULT_RX_BUFFER_SIZE ||
gfar_has_errata(priv, GFAR_ERRATA_74))
tempval |= MACCFG2_HUGEFRAME | MACCFG2_LENGTHCHECK;
gfar_write(®s->maccfg2, tempval);
/* Clear mac addr hash registers */
gfar_write(®s->igaddr0, 0);
gfar_write(®s->igaddr1, 0);
gfar_write(®s->igaddr2, 0);
gfar_write(®s->igaddr3, 0);
gfar_write(®s->igaddr4, 0);
gfar_write(®s->igaddr5, 0);
gfar_write(®s->igaddr6, 0);
gfar_write(®s->igaddr7, 0);
gfar_write(®s->gaddr0, 0);
gfar_write(®s->gaddr1, 0);
gfar_write(®s->gaddr2, 0);
gfar_write(®s->gaddr3, 0);
gfar_write(®s->gaddr4, 0);
gfar_write(®s->gaddr5, 0);
gfar_write(®s->gaddr6, 0);
gfar_write(®s->gaddr7, 0);
if (priv->extended_hash)
gfar_clear_exact_match(priv->ndev);
gfar_mac_rx_config(priv);
gfar_mac_tx_config(priv);
gfar_set_mac_address(priv->ndev);
gfar_set_multi(priv->ndev);
/* clear ievent and imask before configuring coalescing */
gfar_ints_disable(priv);
/* Configure the coalescing support */
gfar_configure_coalescing_all(priv);
}
static void gfar_hw_init(struct gfar_private *priv)
{
struct gfar __iomem *regs = priv->gfargrp[0].regs;
u32 attrs;
/* Stop the DMA engine now, in case it was running before
* (The firmware could have used it, and left it running).
*/
gfar_halt(priv);
gfar_mac_reset(priv);
/* Zero out the rmon mib registers if it has them */
if (priv->device_flags & FSL_GIANFAR_DEV_HAS_RMON) {
memset_io(&(regs->rmon), 0, sizeof(struct rmon_mib));
/* Mask off the CAM interrupts */
gfar_write(®s->rmon.cam1, 0xffffffff);
gfar_write(®s->rmon.cam2, 0xffffffff);
}
/* Initialize ECNTRL */
gfar_write(®s->ecntrl, ECNTRL_INIT_SETTINGS);
/* Set the extraction length and index */
attrs = ATTRELI_EL(priv->rx_stash_size) |
ATTRELI_EI(priv->rx_stash_index);
gfar_write(®s->attreli, attrs);
/* Start with defaults, and add stashing
* depending on driver parameters
*/
attrs = ATTR_INIT_SETTINGS;
if (priv->bd_stash_en)
attrs |= ATTR_BDSTASH;
if (priv->rx_stash_size != 0)
attrs |= ATTR_BUFSTASH;
gfar_write(®s->attr, attrs);
/* FIFO configs */
gfar_write(®s->fifo_tx_thr, DEFAULT_FIFO_TX_THR);
gfar_write(®s->fifo_tx_starve, DEFAULT_FIFO_TX_STARVE);
gfar_write(®s->fifo_tx_starve_shutoff, DEFAULT_FIFO_TX_STARVE_OFF);
/* Program the interrupt steering regs, only for MG devices */
if (priv->num_grps > 1)
gfar_write_isrg(priv);
}
static void gfar_init_addr_hash_table(struct gfar_private *priv)
{
struct gfar __iomem *regs = priv->gfargrp[0].regs;
if (priv->device_flags & FSL_GIANFAR_DEV_HAS_EXTENDED_HASH) {
priv->extended_hash = 1;
priv->hash_width = 9;
priv->hash_regs[0] = ®s->igaddr0;
priv->hash_regs[1] = ®s->igaddr1;
priv->hash_regs[2] = ®s->igaddr2;
priv->hash_regs[3] = ®s->igaddr3;
priv->hash_regs[4] = ®s->igaddr4;
priv->hash_regs[5] = ®s->igaddr5;
priv->hash_regs[6] = ®s->igaddr6;
priv->hash_regs[7] = ®s->igaddr7;
priv->hash_regs[8] = ®s->gaddr0;
priv->hash_regs[9] = ®s->gaddr1;
priv->hash_regs[10] = ®s->gaddr2;
priv->hash_regs[11] = ®s->gaddr3;
priv->hash_regs[12] = ®s->gaddr4;
priv->hash_regs[13] = ®s->gaddr5;
priv->hash_regs[14] = ®s->gaddr6;
priv->hash_regs[15] = ®s->gaddr7;
} else {
priv->extended_hash = 0;
priv->hash_width = 8;
priv->hash_regs[0] = ®s->gaddr0;
priv->hash_regs[1] = ®s->gaddr1;
priv->hash_regs[2] = ®s->gaddr2;
priv->hash_regs[3] = ®s->gaddr3;
priv->hash_regs[4] = ®s->gaddr4;
priv->hash_regs[5] = ®s->gaddr5;
priv->hash_regs[6] = ®s->gaddr6;
priv->hash_regs[7] = ®s->gaddr7;
}
}
/* Set up the ethernet device structure, private data,
* and anything else we need before we start
*/
static int gfar_probe(struct platform_device *ofdev)
{
struct net_device *dev = NULL;
struct gfar_private *priv = NULL;
int err = 0, i;
err = gfar_of_init(ofdev, &dev);
if (err)
return err;
priv = netdev_priv(dev);
priv->ndev = dev;
priv->ofdev = ofdev;
priv->dev = &ofdev->dev;
SET_NETDEV_DEV(dev, &ofdev->dev);
spin_lock_init(&priv->bflock);
INIT_WORK(&priv->reset_task, gfar_reset_task);
platform_set_drvdata(ofdev, priv);
gfar_detect_errata(priv);
/* Set the dev->base_addr to the gfar reg region */
dev->base_addr = (unsigned long) priv->gfargrp[0].regs;
/* Fill in the dev structure */
dev->watchdog_timeo = TX_TIMEOUT;
dev->mtu = 1500;
dev->netdev_ops = &gfar_netdev_ops;
dev->ethtool_ops = &gfar_ethtool_ops;
/* Register for napi ...We are registering NAPI for each grp */
for (i = 0; i < priv->num_grps; i++) {
if (priv->poll_mode == GFAR_SQ_POLLING) {
netif_napi_add(dev, &priv->gfargrp[i].napi_rx,
gfar_poll_rx_sq, GFAR_DEV_WEIGHT);
netif_napi_add(dev, &priv->gfargrp[i].napi_tx,
gfar_poll_tx_sq, 2);
} else {
netif_napi_add(dev, &priv->gfargrp[i].napi_rx,
gfar_poll_rx, GFAR_DEV_WEIGHT);
netif_napi_add(dev, &priv->gfargrp[i].napi_tx,
gfar_poll_tx, 2);
}
}
if (priv->device_flags & FSL_GIANFAR_DEV_HAS_CSUM) {
dev->hw_features = NETIF_F_IP_CSUM | NETIF_F_SG |
NETIF_F_RXCSUM;
dev->features |= NETIF_F_IP_CSUM | NETIF_F_SG |
NETIF_F_RXCSUM | NETIF_F_HIGHDMA;
}
if (priv->device_flags & FSL_GIANFAR_DEV_HAS_VLAN) {
dev->hw_features |= NETIF_F_HW_VLAN_CTAG_TX |
NETIF_F_HW_VLAN_CTAG_RX;
dev->features |= NETIF_F_HW_VLAN_CTAG_RX;
}
gfar_init_addr_hash_table(priv);
/* Insert receive time stamps into padding alignment bytes */
if (priv->device_flags & FSL_GIANFAR_DEV_HAS_TIMER)
priv->padding = 8;
if (dev->features & NETIF_F_IP_CSUM ||
priv->device_flags & FSL_GIANFAR_DEV_HAS_TIMER)
dev->needed_headroom = GMAC_FCB_LEN;
priv->rx_buffer_size = DEFAULT_RX_BUFFER_SIZE;
/* Initializing some of the rx/tx queue level parameters */
for (i = 0; i < priv->num_tx_queues; i++) {
priv->tx_queue[i]->tx_ring_size = DEFAULT_TX_RING_SIZE;
priv->tx_queue[i]->num_txbdfree = DEFAULT_TX_RING_SIZE;
priv->tx_queue[i]->txcoalescing = DEFAULT_TX_COALESCE;
priv->tx_queue[i]->txic = DEFAULT_TXIC;
}
for (i = 0; i < priv->num_rx_queues; i++) {
priv->rx_queue[i]->rx_ring_size = DEFAULT_RX_RING_SIZE;
priv->rx_queue[i]->rxcoalescing = DEFAULT_RX_COALESCE;
priv->rx_queue[i]->rxic = DEFAULT_RXIC;
}
/* always enable rx filer */
priv->rx_filer_enable = 1;
/* Enable most messages by default */
priv->msg_enable = (NETIF_MSG_IFUP << 1 ) - 1;
/* use pritority h/w tx queue scheduling for single queue devices */
if (priv->num_tx_queues == 1)
priv->prio_sched_en = 1;
set_bit(GFAR_DOWN, &priv->state);
gfar_hw_init(priv);
/* Carrier starts down, phylib will bring it up */
netif_carrier_off(dev);
err = register_netdev(dev);
if (err) {
pr_err("%s: Cannot register net device, aborting\n", dev->name);
goto register_fail;
}
device_init_wakeup(&dev->dev,
priv->device_flags &
FSL_GIANFAR_DEV_HAS_MAGIC_PACKET);
/* fill out IRQ number and name fields */
for (i = 0; i < priv->num_grps; i++) {
struct gfar_priv_grp *grp = &priv->gfargrp[i];
if (priv->device_flags & FSL_GIANFAR_DEV_HAS_MULTI_INTR) {
sprintf(gfar_irq(grp, TX)->name, "%s%s%c%s",
dev->name, "_g", '0' + i, "_tx");
sprintf(gfar_irq(grp, RX)->name, "%s%s%c%s",
dev->name, "_g", '0' + i, "_rx");
sprintf(gfar_irq(grp, ER)->name, "%s%s%c%s",
dev->name, "_g", '0' + i, "_er");
} else
strcpy(gfar_irq(grp, TX)->name, dev->name);
}
/* Initialize the filer table */
gfar_init_filer_table(priv);
/* Print out the device info */
netdev_info(dev, "mac: %pM\n", dev->dev_addr);
/* Even more device info helps when determining which kernel
* provided which set of benchmarks.
*/
netdev_info(dev, "Running with NAPI enabled\n");
for (i = 0; i < priv->num_rx_queues; i++)
netdev_info(dev, "RX BD ring size for Q[%d]: %d\n",
i, priv->rx_queue[i]->rx_ring_size);
for (i = 0; i < priv->num_tx_queues; i++)
netdev_info(dev, "TX BD ring size for Q[%d]: %d\n",
i, priv->tx_queue[i]->tx_ring_size);
return 0;
register_fail:
unmap_group_regs(priv);
gfar_free_rx_queues(priv);
gfar_free_tx_queues(priv);
if (priv->phy_node)
of_node_put(priv->phy_node);
if (priv->tbi_node)
of_node_put(priv->tbi_node);
free_gfar_dev(priv);
return err;
}
static int gfar_remove(struct platform_device *ofdev)
{
struct gfar_private *priv = platform_get_drvdata(ofdev);
if (priv->phy_node)
of_node_put(priv->phy_node);
if (priv->tbi_node)
of_node_put(priv->tbi_node);
unregister_netdev(priv->ndev);
unmap_group_regs(priv);
gfar_free_rx_queues(priv);
gfar_free_tx_queues(priv);
free_gfar_dev(priv);
return 0;
}
#ifdef CONFIG_PM
static int gfar_suspend(struct device *dev)
{
struct gfar_private *priv = dev_get_drvdata(dev);
struct net_device *ndev = priv->ndev;
struct gfar __iomem *regs = priv->gfargrp[0].regs;
unsigned long flags;
u32 tempval;
int magic_packet = priv->wol_en &&
(priv->device_flags &
FSL_GIANFAR_DEV_HAS_MAGIC_PACKET);
netif_device_detach(ndev);
if (netif_running(ndev)) {
local_irq_save(flags);
lock_tx_qs(priv);
gfar_halt_nodisable(priv);
/* Disable Tx, and Rx if wake-on-LAN is disabled. */
tempval = gfar_read(®s->maccfg1);
tempval &= ~MACCFG1_TX_EN;
if (!magic_packet)
tempval &= ~MACCFG1_RX_EN;
gfar_write(®s->maccfg1, tempval);
unlock_tx_qs(priv);
local_irq_restore(flags);
disable_napi(priv);
if (magic_packet) {
/* Enable interrupt on Magic Packet */
gfar_write(®s->imask, IMASK_MAG);
/* Enable Magic Packet mode */
tempval = gfar_read(®s->maccfg2);
tempval |= MACCFG2_MPEN;
gfar_write(®s->maccfg2, tempval);
} else {
phy_stop(priv->phydev);
}
}
return 0;
}
static int gfar_resume(struct device *dev)
{
struct gfar_private *priv = dev_get_drvdata(dev);
struct net_device *ndev = priv->ndev;
struct gfar __iomem *regs = priv->gfargrp[0].regs;
unsigned long flags;
u32 tempval;
int magic_packet = priv->wol_en &&
(priv->device_flags &
FSL_GIANFAR_DEV_HAS_MAGIC_PACKET);
if (!netif_running(ndev)) {
netif_device_attach(ndev);
return 0;
}
if (!magic_packet && priv->phydev)
phy_start(priv->phydev);
/* Disable Magic Packet mode, in case something
* else woke us up.
*/
local_irq_save(flags);
lock_tx_qs(priv);
tempval = gfar_read(®s->maccfg2);
tempval &= ~MACCFG2_MPEN;
gfar_write(®s->maccfg2, tempval);
gfar_start(priv);
unlock_tx_qs(priv);
local_irq_restore(flags);
netif_device_attach(ndev);
enable_napi(priv);
return 0;
}
static int gfar_restore(struct device *dev)
{
struct gfar_private *priv = dev_get_drvdata(dev);
struct net_device *ndev = priv->ndev;
if (!netif_running(ndev)) {
netif_device_attach(ndev);
return 0;
}
if (gfar_init_bds(ndev)) {
free_skb_resources(priv);
return -ENOMEM;
}
gfar_mac_reset(priv);
gfar_init_tx_rx_base(priv);
gfar_start(priv);
priv->oldlink = 0;
priv->oldspeed = 0;
priv->oldduplex = -1;
if (priv->phydev)
phy_start(priv->phydev);
netif_device_attach(ndev);
enable_napi(priv);
return 0;
}
static struct dev_pm_ops gfar_pm_ops = {
.suspend = gfar_suspend,
.resume = gfar_resume,
.freeze = gfar_suspend,
.thaw = gfar_resume,
.restore = gfar_restore,
};
#define GFAR_PM_OPS (&gfar_pm_ops)
#else
#define GFAR_PM_OPS NULL
#endif
/* Reads the controller's registers to determine what interface
* connects it to the PHY.
*/
static phy_interface_t gfar_get_interface(struct net_device *dev)
{
struct gfar_private *priv = netdev_priv(dev);
struct gfar __iomem *regs = priv->gfargrp[0].regs;
u32 ecntrl;
ecntrl = gfar_read(®s->ecntrl);
if (ecntrl & ECNTRL_SGMII_MODE)
return PHY_INTERFACE_MODE_SGMII;
if (ecntrl & ECNTRL_TBI_MODE) {
if (ecntrl & ECNTRL_REDUCED_MODE)
return PHY_INTERFACE_MODE_RTBI;
else
return PHY_INTERFACE_MODE_TBI;
}
if (ecntrl & ECNTRL_REDUCED_MODE) {
if (ecntrl & ECNTRL_REDUCED_MII_MODE) {
return PHY_INTERFACE_MODE_RMII;
}
else {
phy_interface_t interface = priv->interface;
/* This isn't autodetected right now, so it must
* be set by the device tree or platform code.
*/
if (interface == PHY_INTERFACE_MODE_RGMII_ID)
return PHY_INTERFACE_MODE_RGMII_ID;
return PHY_INTERFACE_MODE_RGMII;
}
}
if (priv->device_flags & FSL_GIANFAR_DEV_HAS_GIGABIT)
return PHY_INTERFACE_MODE_GMII;
return PHY_INTERFACE_MODE_MII;
}
/* Initializes driver's PHY state, and attaches to the PHY.
* Returns 0 on success.
*/
static int init_phy(struct net_device *dev)
{
struct gfar_private *priv = netdev_priv(dev);
uint gigabit_support =
priv->device_flags & FSL_GIANFAR_DEV_HAS_GIGABIT ?
GFAR_SUPPORTED_GBIT : 0;
phy_interface_t interface;
priv->oldlink = 0;
priv->oldspeed = 0;
priv->oldduplex = -1;
interface = gfar_get_interface(dev);
priv->phydev = of_phy_connect(dev, priv->phy_node, &adjust_link, 0,
interface);
if (!priv->phydev) {
dev_err(&dev->dev, "could not attach to PHY\n");
return -ENODEV;
}
if (interface == PHY_INTERFACE_MODE_SGMII)
gfar_configure_serdes(dev);
/* Remove any features not supported by the controller */
priv->phydev->supported &= (GFAR_SUPPORTED | gigabit_support);
priv->phydev->advertising = priv->phydev->supported;
return 0;
}
/* Initialize TBI PHY interface for communicating with the
* SERDES lynx PHY on the chip. We communicate with this PHY
* through the MDIO bus on each controller, treating it as a
* "normal" PHY at the address found in the TBIPA register. We assume
* that the TBIPA register is valid. Either the MDIO bus code will set
* it to a value that doesn't conflict with other PHYs on the bus, or the
* value doesn't matter, as there are no other PHYs on the bus.
*/
static void gfar_configure_serdes(struct net_device *dev)
{
struct gfar_private *priv = netdev_priv(dev);
struct phy_device *tbiphy;
if (!priv->tbi_node) {
dev_warn(&dev->dev, "error: SGMII mode requires that the "
"device tree specify a tbi-handle\n");
return;
}
tbiphy = of_phy_find_device(priv->tbi_node);
if (!tbiphy) {
dev_err(&dev->dev, "error: Could not get TBI device\n");
return;
}
/* If the link is already up, we must already be ok, and don't need to
* configure and reset the TBI<->SerDes link. Maybe U-Boot configured
* everything for us? Resetting it takes the link down and requires
* several seconds for it to come back.
*/
if (phy_read(tbiphy, MII_BMSR) & BMSR_LSTATUS)
return;
/* Single clk mode, mii mode off(for serdes communication) */
phy_write(tbiphy, MII_TBICON, TBICON_CLK_SELECT);
phy_write(tbiphy, MII_ADVERTISE,
ADVERTISE_1000XFULL | ADVERTISE_1000XPAUSE |
ADVERTISE_1000XPSE_ASYM);
phy_write(tbiphy, MII_BMCR,
BMCR_ANENABLE | BMCR_ANRESTART | BMCR_FULLDPLX |
BMCR_SPEED1000);
}
static int __gfar_is_rx_idle(struct gfar_private *priv)
{
u32 res;
/* Normaly TSEC should not hang on GRS commands, so we should
* actually wait for IEVENT_GRSC flag.
*/
if (!gfar_has_errata(priv, GFAR_ERRATA_A002))
return 0;
/* Read the eTSEC register at offset 0xD1C. If bits 7-14 are
* the same as bits 23-30, the eTSEC Rx is assumed to be idle
* and the Rx can be safely reset.
*/
res = gfar_read((void __iomem *)priv->gfargrp[0].regs + 0xd1c);
res &= 0x7f807f80;
if ((res & 0xffff) == (res >> 16))
return 1;
return 0;
}
/* Halt the receive and transmit queues */
static void gfar_halt_nodisable(struct gfar_private *priv)
{
struct gfar __iomem *regs = priv->gfargrp[0].regs;
u32 tempval;
gfar_ints_disable(priv);
/* Stop the DMA, and wait for it to stop */
tempval = gfar_read(®s->dmactrl);
if ((tempval & (DMACTRL_GRS | DMACTRL_GTS)) !=
(DMACTRL_GRS | DMACTRL_GTS)) {
int ret;
tempval |= (DMACTRL_GRS | DMACTRL_GTS);
gfar_write(®s->dmactrl, tempval);
do {
ret = spin_event_timeout(((gfar_read(®s->ievent) &
(IEVENT_GRSC | IEVENT_GTSC)) ==
(IEVENT_GRSC | IEVENT_GTSC)), 1000000, 0);
if (!ret && !(gfar_read(®s->ievent) & IEVENT_GRSC))
ret = __gfar_is_rx_idle(priv);
} while (!ret);
}
}
/* Halt the receive and transmit queues */
void gfar_halt(struct gfar_private *priv)
{
struct gfar __iomem *regs = priv->gfargrp[0].regs;
u32 tempval;
/* Dissable the Rx/Tx hw queues */
gfar_write(®s->rqueue, 0);
gfar_write(®s->tqueue, 0);
mdelay(10);
gfar_halt_nodisable(priv);
/* Disable Rx/Tx DMA */
tempval = gfar_read(®s->maccfg1);
tempval &= ~(MACCFG1_RX_EN | MACCFG1_TX_EN);
gfar_write(®s->maccfg1, tempval);
}
void stop_gfar(struct net_device *dev)
{
struct gfar_private *priv = netdev_priv(dev);
netif_tx_stop_all_queues(dev);
smp_mb__before_atomic();
set_bit(GFAR_DOWN, &priv->state);
smp_mb__after_atomic();
disable_napi(priv);
/* disable ints and gracefully shut down Rx/Tx DMA */
gfar_halt(priv);
phy_stop(priv->phydev);
free_skb_resources(priv);
}
static void free_skb_tx_queue(struct gfar_priv_tx_q *tx_queue)
{
struct txbd8 *txbdp;
struct gfar_private *priv = netdev_priv(tx_queue->dev);
int i, j;
txbdp = tx_queue->tx_bd_base;
for (i = 0; i < tx_queue->tx_ring_size; i++) {
if (!tx_queue->tx_skbuff[i])
continue;
dma_unmap_single(priv->dev, txbdp->bufPtr,
txbdp->length, DMA_TO_DEVICE);
txbdp->lstatus = 0;
for (j = 0; j < skb_shinfo(tx_queue->tx_skbuff[i])->nr_frags;
j++) {
txbdp++;
dma_unmap_page(priv->dev, txbdp->bufPtr,
txbdp->length, DMA_TO_DEVICE);
}
txbdp++;
dev_kfree_skb_any(tx_queue->tx_skbuff[i]);
tx_queue->tx_skbuff[i] = NULL;
}
kfree(tx_queue->tx_skbuff);
tx_queue->tx_skbuff = NULL;
}
static void free_skb_rx_queue(struct gfar_priv_rx_q *rx_queue)
{
struct rxbd8 *rxbdp;
struct gfar_private *priv = netdev_priv(rx_queue->dev);
int i;
rxbdp = rx_queue->rx_bd_base;
for (i = 0; i < rx_queue->rx_ring_size; i++) {
if (rx_queue->rx_skbuff[i]) {
dma_unmap_single(priv->dev, rxbdp->bufPtr,
priv->rx_buffer_size,
DMA_FROM_DEVICE);
dev_kfree_skb_any(rx_queue->rx_skbuff[i]);
rx_queue->rx_skbuff[i] = NULL;
}
rxbdp->lstatus = 0;
rxbdp->bufPtr = 0;
rxbdp++;
}
kfree(rx_queue->rx_skbuff);
rx_queue->rx_skbuff = NULL;
}
/* If there are any tx skbs or rx skbs still around, free them.
* Then free tx_skbuff and rx_skbuff
*/
static void free_skb_resources(struct gfar_private *priv)
{
struct gfar_priv_tx_q *tx_queue = NULL;
struct gfar_priv_rx_q *rx_queue = NULL;
int i;
/* Go through all the buffer descriptors and free their data buffers */
for (i = 0; i < priv->num_tx_queues; i++) {
struct netdev_queue *txq;
tx_queue = priv->tx_queue[i];
txq = netdev_get_tx_queue(tx_queue->dev, tx_queue->qindex);
if (tx_queue->tx_skbuff)
free_skb_tx_queue(tx_queue);
netdev_tx_reset_queue(txq);
}
for (i = 0; i < priv->num_rx_queues; i++) {
rx_queue = priv->rx_queue[i];
if (rx_queue->rx_skbuff)
free_skb_rx_queue(rx_queue);
}
dma_free_coherent(priv->dev,
sizeof(struct txbd8) * priv->total_tx_ring_size +
sizeof(struct rxbd8) * priv->total_rx_ring_size,
priv->tx_queue[0]->tx_bd_base,
priv->tx_queue[0]->tx_bd_dma_base);
}
void gfar_start(struct gfar_private *priv)
{
struct gfar __iomem *regs = priv->gfargrp[0].regs;
u32 tempval;
int i = 0;
/* Enable Rx/Tx hw queues */
gfar_write(®s->rqueue, priv->rqueue);
gfar_write(®s->tqueue, priv->tqueue);
/* Initialize DMACTRL to have WWR and WOP */
tempval = gfar_read(®s->dmactrl);
tempval |= DMACTRL_INIT_SETTINGS;
gfar_write(®s->dmactrl, tempval);
/* Make sure we aren't stopped */
tempval = gfar_read(®s->dmactrl);
tempval &= ~(DMACTRL_GRS | DMACTRL_GTS);
gfar_write(®s->dmactrl, tempval);
for (i = 0; i < priv->num_grps; i++) {
regs = priv->gfargrp[i].regs;
/* Clear THLT/RHLT, so that the DMA starts polling now */
gfar_write(®s->tstat, priv->gfargrp[i].tstat);
gfar_write(®s->rstat, priv->gfargrp[i].rstat);
}
/* Enable Rx/Tx DMA */
tempval = gfar_read(®s->maccfg1);
tempval |= (MACCFG1_RX_EN | MACCFG1_TX_EN);
gfar_write(®s->maccfg1, tempval);
gfar_ints_enable(priv);
priv->ndev->trans_start = jiffies; /* prevent tx timeout */
}
static void free_grp_irqs(struct gfar_priv_grp *grp)
{
free_irq(gfar_irq(grp, TX)->irq, grp);
free_irq(gfar_irq(grp, RX)->irq, grp);
free_irq(gfar_irq(grp, ER)->irq, grp);
}
static int register_grp_irqs(struct gfar_priv_grp *grp)
{
struct gfar_private *priv = grp->priv;
struct net_device *dev = priv->ndev;
int err;
/* If the device has multiple interrupts, register for
* them. Otherwise, only register for the one
*/
if (priv->device_flags & FSL_GIANFAR_DEV_HAS_MULTI_INTR) {
/* Install our interrupt handlers for Error,
* Transmit, and Receive
*/
err = request_irq(gfar_irq(grp, ER)->irq, gfar_error, 0,
gfar_irq(grp, ER)->name, grp);
if (err < 0) {
netif_err(priv, intr, dev, "Can't get IRQ %d\n",
gfar_irq(grp, ER)->irq);
goto err_irq_fail;
}
err = request_irq(gfar_irq(grp, TX)->irq, gfar_transmit, 0,
gfar_irq(grp, TX)->name, grp);
if (err < 0) {
netif_err(priv, intr, dev, "Can't get IRQ %d\n",
gfar_irq(grp, TX)->irq);
goto tx_irq_fail;
}
err = request_irq(gfar_irq(grp, RX)->irq, gfar_receive, 0,
gfar_irq(grp, RX)->name, grp);
if (err < 0) {
netif_err(priv, intr, dev, "Can't get IRQ %d\n",
gfar_irq(grp, RX)->irq);
goto rx_irq_fail;
}
} else {
err = request_irq(gfar_irq(grp, TX)->irq, gfar_interrupt, 0,
gfar_irq(grp, TX)->name, grp);
if (err < 0) {
netif_err(priv, intr, dev, "Can't get IRQ %d\n",
gfar_irq(grp, TX)->irq);
goto err_irq_fail;
}
}
return 0;
rx_irq_fail:
free_irq(gfar_irq(grp, TX)->irq, grp);
tx_irq_fail:
free_irq(gfar_irq(grp, ER)->irq, grp);
err_irq_fail:
return err;
}
static void gfar_free_irq(struct gfar_private *priv)
{
int i;
/* Free the IRQs */
if (priv->device_flags & FSL_GIANFAR_DEV_HAS_MULTI_INTR) {
for (i = 0; i < priv->num_grps; i++)
free_grp_irqs(&priv->gfargrp[i]);
} else {
for (i = 0; i < priv->num_grps; i++)
free_irq(gfar_irq(&priv->gfargrp[i], TX)->irq,
&priv->gfargrp[i]);
}
}
static int gfar_request_irq(struct gfar_private *priv)
{
int err, i, j;
for (i = 0; i < priv->num_grps; i++) {
err = register_grp_irqs(&priv->gfargrp[i]);
if (err) {
for (j = 0; j < i; j++)
free_grp_irqs(&priv->gfargrp[j]);
return err;
}
}
return 0;
}
/* Bring the controller up and running */
int startup_gfar(struct net_device *ndev)
{
struct gfar_private *priv = netdev_priv(ndev);
int err;
gfar_mac_reset(priv);
err = gfar_alloc_skb_resources(ndev);
if (err)
return err;
gfar_init_tx_rx_base(priv);
smp_mb__before_atomic();
clear_bit(GFAR_DOWN, &priv->state);
smp_mb__after_atomic();
/* Start Rx/Tx DMA and enable the interrupts */
gfar_start(priv);
phy_start(priv->phydev);
enable_napi(priv);
netif_tx_wake_all_queues(ndev);
return 0;
}
/* Called when something needs to use the ethernet device
* Returns 0 for success.
*/
static int gfar_enet_open(struct net_device *dev)
{
struct gfar_private *priv = netdev_priv(dev);
int err;
err = init_phy(dev);
if (err)
return err;
err = gfar_request_irq(priv);
if (err)
return err;
err = startup_gfar(dev);
if (err)
return err;
device_set_wakeup_enable(&dev->dev, priv->wol_en);
return err;
}
static inline struct txfcb *gfar_add_fcb(struct sk_buff *skb)
{
struct txfcb *fcb = (struct txfcb *)skb_push(skb, GMAC_FCB_LEN);
memset(fcb, 0, GMAC_FCB_LEN);
return fcb;
}
static inline void gfar_tx_checksum(struct sk_buff *skb, struct txfcb *fcb,
int fcb_length)
{
/* If we're here, it's a IP packet with a TCP or UDP
* payload. We set it to checksum, using a pseudo-header
* we provide
*/
u8 flags = TXFCB_DEFAULT;
/* Tell the controller what the protocol is
* And provide the already calculated phcs
*/
if (ip_hdr(skb)->protocol == IPPROTO_UDP) {
flags |= TXFCB_UDP;
fcb->phcs = udp_hdr(skb)->check;
} else
fcb->phcs = tcp_hdr(skb)->check;
/* l3os is the distance between the start of the
* frame (skb->data) and the start of the IP hdr.
* l4os is the distance between the start of the
* l3 hdr and the l4 hdr
*/
fcb->l3os = (u16)(skb_network_offset(skb) - fcb_length);
fcb->l4os = skb_network_header_len(skb);
fcb->flags = flags;
}
void inline gfar_tx_vlan(struct sk_buff *skb, struct txfcb *fcb)
{
fcb->flags |= TXFCB_VLN;
fcb->vlctl = vlan_tx_tag_get(skb);
}
static inline struct txbd8 *skip_txbd(struct txbd8 *bdp, int stride,
struct txbd8 *base, int ring_size)
{
struct txbd8 *new_bd = bdp + stride;
return (new_bd >= (base + ring_size)) ? (new_bd - ring_size) : new_bd;
}
static inline struct txbd8 *next_txbd(struct txbd8 *bdp, struct txbd8 *base,
int ring_size)
{
return skip_txbd(bdp, 1, base, ring_size);
}
/* eTSEC12: csum generation not supported for some fcb offsets */
static inline bool gfar_csum_errata_12(struct gfar_private *priv,
unsigned long fcb_addr)
{
return (gfar_has_errata(priv, GFAR_ERRATA_12) &&
(fcb_addr % 0x20) > 0x18);
}
/* eTSEC76: csum generation for frames larger than 2500 may
* cause excess delays before start of transmission
*/
static inline bool gfar_csum_errata_76(struct gfar_private *priv,
unsigned int len)
{
return (gfar_has_errata(priv, GFAR_ERRATA_76) &&
(len > 2500));
}
/* This is called by the kernel when a frame is ready for transmission.
* It is pointed to by the dev->hard_start_xmit function pointer
*/
static int gfar_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct gfar_private *priv = netdev_priv(dev);
struct gfar_priv_tx_q *tx_queue = NULL;
struct netdev_queue *txq;
struct gfar __iomem *regs = NULL;
struct txfcb *fcb = NULL;
struct txbd8 *txbdp, *txbdp_start, *base, *txbdp_tstamp = NULL;
u32 lstatus;
int i, rq = 0;
int do_tstamp, do_csum, do_vlan;
u32 bufaddr;
unsigned long flags;
unsigned int nr_frags, nr_txbds, bytes_sent, fcb_len = 0;
rq = skb->queue_mapping;
tx_queue = priv->tx_queue[rq];
txq = netdev_get_tx_queue(dev, rq);
base = tx_queue->tx_bd_base;
regs = tx_queue->grp->regs;
do_csum = (CHECKSUM_PARTIAL == skb->ip_summed);
do_vlan = vlan_tx_tag_present(skb);
do_tstamp = (skb_shinfo(skb)->tx_flags & SKBTX_HW_TSTAMP) &&
priv->hwts_tx_en;
if (do_csum || do_vlan)
fcb_len = GMAC_FCB_LEN;
/* check if time stamp should be generated */
if (unlikely(do_tstamp))
fcb_len = GMAC_FCB_LEN + GMAC_TXPAL_LEN;
/* make space for additional header when fcb is needed */
if (fcb_len && unlikely(skb_headroom(skb) < fcb_len)) {
struct sk_buff *skb_new;
skb_new = skb_realloc_headroom(skb, fcb_len);
if (!skb_new) {
dev->stats.tx_errors++;
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
if (skb->sk)
skb_set_owner_w(skb_new, skb->sk);
dev_consume_skb_any(skb);
skb = skb_new;
}
/* total number of fragments in the SKB */
nr_frags = skb_shinfo(skb)->nr_frags;
/* calculate the required number of TxBDs for this skb */
if (unlikely(do_tstamp))
nr_txbds = nr_frags + 2;
else
nr_txbds = nr_frags + 1;
/* check if there is space to queue this packet */
if (nr_txbds > tx_queue->num_txbdfree) {
/* no space, stop the queue */
netif_tx_stop_queue(txq);
dev->stats.tx_fifo_errors++;
return NETDEV_TX_BUSY;
}
/* Update transmit stats */
bytes_sent = skb->len;
tx_queue->stats.tx_bytes += bytes_sent;
/* keep Tx bytes on wire for BQL accounting */
GFAR_CB(skb)->bytes_sent = bytes_sent;
tx_queue->stats.tx_packets++;
txbdp = txbdp_start = tx_queue->cur_tx;
lstatus = txbdp->lstatus;
/* Time stamp insertion requires one additional TxBD */
if (unlikely(do_tstamp))
txbdp_tstamp = txbdp = next_txbd(txbdp, base,
tx_queue->tx_ring_size);
if (nr_frags == 0) {
if (unlikely(do_tstamp))
txbdp_tstamp->lstatus |= BD_LFLAG(TXBD_LAST |
TXBD_INTERRUPT);
else
lstatus |= BD_LFLAG(TXBD_LAST | TXBD_INTERRUPT);
} else {
/* Place the fragment addresses and lengths into the TxBDs */
for (i = 0; i < nr_frags; i++) {
unsigned int frag_len;
/* Point at the next BD, wrapping as needed */
txbdp = next_txbd(txbdp, base, tx_queue->tx_ring_size);
frag_len = skb_shinfo(skb)->frags[i].size;
lstatus = txbdp->lstatus | frag_len |
BD_LFLAG(TXBD_READY);
/* Handle the last BD specially */
if (i == nr_frags - 1)
lstatus |= BD_LFLAG(TXBD_LAST | TXBD_INTERRUPT);
bufaddr = skb_frag_dma_map(priv->dev,
&skb_shinfo(skb)->frags[i],
0,
frag_len,
DMA_TO_DEVICE);
/* set the TxBD length and buffer pointer */
txbdp->bufPtr = bufaddr;
txbdp->lstatus = lstatus;
}
lstatus = txbdp_start->lstatus;
}
/* Add TxPAL between FCB and frame if required */
if (unlikely(do_tstamp)) {
skb_push(skb, GMAC_TXPAL_LEN);
memset(skb->data, 0, GMAC_TXPAL_LEN);
}
/* Add TxFCB if required */
if (fcb_len) {
fcb = gfar_add_fcb(skb);
lstatus |= BD_LFLAG(TXBD_TOE);
}
/* Set up checksumming */
if (do_csum) {
gfar_tx_checksum(skb, fcb, fcb_len);
if (unlikely(gfar_csum_errata_12(priv, (unsigned long)fcb)) ||
unlikely(gfar_csum_errata_76(priv, skb->len))) {
__skb_pull(skb, GMAC_FCB_LEN);
skb_checksum_help(skb);
if (do_vlan || do_tstamp) {
/* put back a new fcb for vlan/tstamp TOE */
fcb = gfar_add_fcb(skb);
} else {
/* Tx TOE not used */
lstatus &= ~(BD_LFLAG(TXBD_TOE));
fcb = NULL;
}
}
}
if (do_vlan)
gfar_tx_vlan(skb, fcb);
/* Setup tx hardware time stamping if requested */
if (unlikely(do_tstamp)) {
skb_shinfo(skb)->tx_flags |= SKBTX_IN_PROGRESS;
fcb->ptp = 1;
}
txbdp_start->bufPtr = dma_map_single(priv->dev, skb->data,
skb_headlen(skb), DMA_TO_DEVICE);
/* If time stamping is requested one additional TxBD must be set up. The
* first TxBD points to the FCB and must have a data length of
* GMAC_FCB_LEN. The second TxBD points to the actual frame data with
* the full frame length.
*/
if (unlikely(do_tstamp)) {
txbdp_tstamp->bufPtr = txbdp_start->bufPtr + fcb_len;
txbdp_tstamp->lstatus |= BD_LFLAG(TXBD_READY) |
(skb_headlen(skb) - fcb_len);
lstatus |= BD_LFLAG(TXBD_CRC | TXBD_READY) | GMAC_FCB_LEN;
} else {
lstatus |= BD_LFLAG(TXBD_CRC | TXBD_READY) | skb_headlen(skb);
}
netdev_tx_sent_queue(txq, bytes_sent);
/* We can work in parallel with gfar_clean_tx_ring(), except
* when modifying num_txbdfree. Note that we didn't grab the lock
* when we were reading the num_txbdfree and checking for available
* space, that's because outside of this function it can only grow,
* and once we've got needed space, it cannot suddenly disappear.
*
* The lock also protects us from gfar_error(), which can modify
* regs->tstat and thus retrigger the transfers, which is why we
* also must grab the lock before setting ready bit for the first
* to be transmitted BD.
*/
spin_lock_irqsave(&tx_queue->txlock, flags);
/* The powerpc-specific eieio() is used, as wmb() has too strong
* semantics (it requires synchronization between cacheable and
* uncacheable mappings, which eieio doesn't provide and which we
* don't need), thus requiring a more expensive sync instruction. At
* some point, the set of architecture-independent barrier functions
* should be expanded to include weaker barriers.
*/
eieio();
txbdp_start->lstatus = lstatus;
eieio(); /* force lstatus write before tx_skbuff */
tx_queue->tx_skbuff[tx_queue->skb_curtx] = skb;
/* Update the current skb pointer to the next entry we will use
* (wrapping if necessary)
*/
tx_queue->skb_curtx = (tx_queue->skb_curtx + 1) &
TX_RING_MOD_MASK(tx_queue->tx_ring_size);
tx_queue->cur_tx = next_txbd(txbdp, base, tx_queue->tx_ring_size);
/* reduce TxBD free count */
tx_queue->num_txbdfree -= (nr_txbds);
/* If the next BD still needs to be cleaned up, then the bds
* are full. We need to tell the kernel to stop sending us stuff.
*/
if (!tx_queue->num_txbdfree) {
netif_tx_stop_queue(txq);
dev->stats.tx_fifo_errors++;
}
/* Tell the DMA to go go go */
gfar_write(®s->tstat, TSTAT_CLEAR_THALT >> tx_queue->qindex);
/* Unlock priv */
spin_unlock_irqrestore(&tx_queue->txlock, flags);
return NETDEV_TX_OK;
}
/* Stops the kernel queue, and halts the controller */
static int gfar_close(struct net_device *dev)
{
struct gfar_private *priv = netdev_priv(dev);
cancel_work_sync(&priv->reset_task);
stop_gfar(dev);
/* Disconnect from the PHY */
phy_disconnect(priv->phydev);
priv->phydev = NULL;
gfar_free_irq(priv);
return 0;
}
/* Changes the mac address if the controller is not running. */
static int gfar_set_mac_address(struct net_device *dev)
{
gfar_set_mac_for_addr(dev, 0, dev->dev_addr);
return 0;
}
static int gfar_change_mtu(struct net_device *dev, int new_mtu)
{
struct gfar_private *priv = netdev_priv(dev);
int frame_size = new_mtu + ETH_HLEN;
if ((frame_size < 64) || (frame_size > JUMBO_FRAME_SIZE)) {
netif_err(priv, drv, dev, "Invalid MTU setting\n");
return -EINVAL;
}
while (test_and_set_bit_lock(GFAR_RESETTING, &priv->state))
cpu_relax();
if (dev->flags & IFF_UP)
stop_gfar(dev);
dev->mtu = new_mtu;
if (dev->flags & IFF_UP)
startup_gfar(dev);
clear_bit_unlock(GFAR_RESETTING, &priv->state);
return 0;
}
void reset_gfar(struct net_device *ndev)
{
struct gfar_private *priv = netdev_priv(ndev);
while (test_and_set_bit_lock(GFAR_RESETTING, &priv->state))
cpu_relax();
stop_gfar(ndev);
startup_gfar(ndev);
clear_bit_unlock(GFAR_RESETTING, &priv->state);
}
/* gfar_reset_task gets scheduled when a packet has not been
* transmitted after a set amount of time.
* For now, assume that clearing out all the structures, and
* starting over will fix the problem.
*/
static void gfar_reset_task(struct work_struct *work)
{
struct gfar_private *priv = container_of(work, struct gfar_private,
reset_task);
reset_gfar(priv->ndev);
}
static void gfar_timeout(struct net_device *dev)
{
struct gfar_private *priv = netdev_priv(dev);
dev->stats.tx_errors++;
schedule_work(&priv->reset_task);
}
static void gfar_align_skb(struct sk_buff *skb)
{
/* We need the data buffer to be aligned properly. We will reserve
* as many bytes as needed to align the data properly
*/
skb_reserve(skb, RXBUF_ALIGNMENT -
(((unsigned long) skb->data) & (RXBUF_ALIGNMENT - 1)));
}
/* Interrupt Handler for Transmit complete */
static void gfar_clean_tx_ring(struct gfar_priv_tx_q *tx_queue)
{
struct net_device *dev = tx_queue->dev;
struct netdev_queue *txq;
struct gfar_private *priv = netdev_priv(dev);
struct txbd8 *bdp, *next = NULL;
struct txbd8 *lbdp = NULL;
struct txbd8 *base = tx_queue->tx_bd_base;
struct sk_buff *skb;
int skb_dirtytx;
int tx_ring_size = tx_queue->tx_ring_size;
int frags = 0, nr_txbds = 0;
int i;
int howmany = 0;
int tqi = tx_queue->qindex;
unsigned int bytes_sent = 0;
u32 lstatus;
size_t buflen;
txq = netdev_get_tx_queue(dev, tqi);
bdp = tx_queue->dirty_tx;
skb_dirtytx = tx_queue->skb_dirtytx;
while ((skb = tx_queue->tx_skbuff[skb_dirtytx])) {
unsigned long flags;
frags = skb_shinfo(skb)->nr_frags;
/* When time stamping, one additional TxBD must be freed.
* Also, we need to dma_unmap_single() the TxPAL.
*/
if (unlikely(skb_shinfo(skb)->tx_flags & SKBTX_IN_PROGRESS))
nr_txbds = frags + 2;
else
nr_txbds = frags + 1;
lbdp = skip_txbd(bdp, nr_txbds - 1, base, tx_ring_size);
lstatus = lbdp->lstatus;
/* Only clean completed frames */
if ((lstatus & BD_LFLAG(TXBD_READY)) &&
(lstatus & BD_LENGTH_MASK))
break;
if (unlikely(skb_shinfo(skb)->tx_flags & SKBTX_IN_PROGRESS)) {
next = next_txbd(bdp, base, tx_ring_size);
buflen = next->length + GMAC_FCB_LEN + GMAC_TXPAL_LEN;
} else
buflen = bdp->length;
dma_unmap_single(priv->dev, bdp->bufPtr,
buflen, DMA_TO_DEVICE);
if (unlikely(skb_shinfo(skb)->tx_flags & SKBTX_IN_PROGRESS)) {
struct skb_shared_hwtstamps shhwtstamps;
u64 *ns = (u64*) (((u32)skb->data + 0x10) & ~0x7);
memset(&shhwtstamps, 0, sizeof(shhwtstamps));
shhwtstamps.hwtstamp = ns_to_ktime(*ns);
skb_pull(skb, GMAC_FCB_LEN + GMAC_TXPAL_LEN);
skb_tstamp_tx(skb, &shhwtstamps);
bdp->lstatus &= BD_LFLAG(TXBD_WRAP);
bdp = next;
}
bdp->lstatus &= BD_LFLAG(TXBD_WRAP);
bdp = next_txbd(bdp, base, tx_ring_size);
for (i = 0; i < frags; i++) {
dma_unmap_page(priv->dev, bdp->bufPtr,
bdp->length, DMA_TO_DEVICE);
bdp->lstatus &= BD_LFLAG(TXBD_WRAP);
bdp = next_txbd(bdp, base, tx_ring_size);
}
bytes_sent += GFAR_CB(skb)->bytes_sent;
dev_kfree_skb_any(skb);
tx_queue->tx_skbuff[skb_dirtytx] = NULL;
skb_dirtytx = (skb_dirtytx + 1) &
TX_RING_MOD_MASK(tx_ring_size);
howmany++;
spin_lock_irqsave(&tx_queue->txlock, flags);
tx_queue->num_txbdfree += nr_txbds;
spin_unlock_irqrestore(&tx_queue->txlock, flags);
}
/* If we freed a buffer, we can restart transmission, if necessary */
if (tx_queue->num_txbdfree &&
netif_tx_queue_stopped(txq) &&
!(test_bit(GFAR_DOWN, &priv->state)))
netif_wake_subqueue(priv->ndev, tqi);
/* Update dirty indicators */
tx_queue->skb_dirtytx = skb_dirtytx;
tx_queue->dirty_tx = bdp;
netdev_tx_completed_queue(txq, howmany, bytes_sent);
}
static void gfar_new_rxbdp(struct gfar_priv_rx_q *rx_queue, struct rxbd8 *bdp,
struct sk_buff *skb)
{
struct net_device *dev = rx_queue->dev;
struct gfar_private *priv = netdev_priv(dev);
dma_addr_t buf;
buf = dma_map_single(priv->dev, skb->data,
priv->rx_buffer_size, DMA_FROM_DEVICE);
gfar_init_rxbdp(rx_queue, bdp, buf);
}
static struct sk_buff *gfar_alloc_skb(struct net_device *dev)
{
struct gfar_private *priv = netdev_priv(dev);
struct sk_buff *skb;
skb = netdev_alloc_skb(dev, priv->rx_buffer_size + RXBUF_ALIGNMENT);
if (!skb)
return NULL;
gfar_align_skb(skb);
return skb;
}
struct sk_buff *gfar_new_skb(struct net_device *dev)
{
return gfar_alloc_skb(dev);
}
static inline void count_errors(unsigned short status, struct net_device *dev)
{
struct gfar_private *priv = netdev_priv(dev);
struct net_device_stats *stats = &dev->stats;
struct gfar_extra_stats *estats = &priv->extra_stats;
/* If the packet was truncated, none of the other errors matter */
if (status & RXBD_TRUNCATED) {
stats->rx_length_errors++;
atomic64_inc(&estats->rx_trunc);
return;
}
/* Count the errors, if there were any */
if (status & (RXBD_LARGE | RXBD_SHORT)) {
stats->rx_length_errors++;
if (status & RXBD_LARGE)
atomic64_inc(&estats->rx_large);
else
atomic64_inc(&estats->rx_short);
}
if (status & RXBD_NONOCTET) {
stats->rx_frame_errors++;
atomic64_inc(&estats->rx_nonoctet);
}
if (status & RXBD_CRCERR) {
atomic64_inc(&estats->rx_crcerr);
stats->rx_crc_errors++;
}
if (status & RXBD_OVERRUN) {
atomic64_inc(&estats->rx_overrun);
stats->rx_crc_errors++;
}
}
irqreturn_t gfar_receive(int irq, void *grp_id)
{
struct gfar_priv_grp *grp = (struct gfar_priv_grp *)grp_id;
unsigned long flags;
u32 imask;
if (likely(napi_schedule_prep(&grp->napi_rx))) {
spin_lock_irqsave(&grp->grplock, flags);
imask = gfar_read(&grp->regs->imask);
imask &= IMASK_RX_DISABLED;
gfar_write(&grp->regs->imask, imask);
spin_unlock_irqrestore(&grp->grplock, flags);
__napi_schedule(&grp->napi_rx);
} else {
/* Clear IEVENT, so interrupts aren't called again
* because of the packets that have already arrived.
*/
gfar_write(&grp->regs->ievent, IEVENT_RX_MASK);
}
return IRQ_HANDLED;
}
/* Interrupt Handler for Transmit complete */
static irqreturn_t gfar_transmit(int irq, void *grp_id)
{
struct gfar_priv_grp *grp = (struct gfar_priv_grp *)grp_id;
unsigned long flags;
u32 imask;
if (likely(napi_schedule_prep(&grp->napi_tx))) {
spin_lock_irqsave(&grp->grplock, flags);
imask = gfar_read(&grp->regs->imask);
imask &= IMASK_TX_DISABLED;
gfar_write(&grp->regs->imask, imask);
spin_unlock_irqrestore(&grp->grplock, flags);
__napi_schedule(&grp->napi_tx);
} else {
/* Clear IEVENT, so interrupts aren't called again
* because of the packets that have already arrived.
*/
gfar_write(&grp->regs->ievent, IEVENT_TX_MASK);
}
return IRQ_HANDLED;
}
static inline void gfar_rx_checksum(struct sk_buff *skb, struct rxfcb *fcb)
{
/* If valid headers were found, and valid sums
* were verified, then we tell the kernel that no
* checksumming is necessary. Otherwise, it is [FIXME]
*/
if ((fcb->flags & RXFCB_CSUM_MASK) == (RXFCB_CIP | RXFCB_CTU))
skb->ip_summed = CHECKSUM_UNNECESSARY;
else
skb_checksum_none_assert(skb);
}
/* gfar_process_frame() -- handle one incoming packet if skb isn't NULL. */
static void gfar_process_frame(struct net_device *dev, struct sk_buff *skb,
int amount_pull, struct napi_struct *napi)
{
struct gfar_private *priv = netdev_priv(dev);
struct rxfcb *fcb = NULL;
/* fcb is at the beginning if exists */
fcb = (struct rxfcb *)skb->data;
/* Remove the FCB from the skb
* Remove the padded bytes, if there are any
*/
if (amount_pull) {
skb_record_rx_queue(skb, fcb->rq);
skb_pull(skb, amount_pull);
}
/* Get receive timestamp from the skb */
if (priv->hwts_rx_en) {
struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb);
u64 *ns = (u64 *) skb->data;
memset(shhwtstamps, 0, sizeof(*shhwtstamps));
shhwtstamps->hwtstamp = ns_to_ktime(*ns);
}
if (priv->padding)
skb_pull(skb, priv->padding);
if (dev->features & NETIF_F_RXCSUM)
gfar_rx_checksum(skb, fcb);
/* Tell the skb what kind of packet this is */
skb->protocol = eth_type_trans(skb, dev);
/* There's need to check for NETIF_F_HW_VLAN_CTAG_RX here.
* Even if vlan rx accel is disabled, on some chips
* RXFCB_VLN is pseudo randomly set.
*/
if (dev->features & NETIF_F_HW_VLAN_CTAG_RX &&
fcb->flags & RXFCB_VLN)
__vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), fcb->vlctl);
/* Send the packet up the stack */
napi_gro_receive(napi, skb);
}
/* gfar_clean_rx_ring() -- Processes each frame in the rx ring
* until the budget/quota has been reached. Returns the number
* of frames handled
*/
int gfar_clean_rx_ring(struct gfar_priv_rx_q *rx_queue, int rx_work_limit)
{
struct net_device *dev = rx_queue->dev;
struct rxbd8 *bdp, *base;
struct sk_buff *skb;
int pkt_len;
int amount_pull;
int howmany = 0;
struct gfar_private *priv = netdev_priv(dev);
/* Get the first full descriptor */
bdp = rx_queue->cur_rx;
base = rx_queue->rx_bd_base;
amount_pull = priv->uses_rxfcb ? GMAC_FCB_LEN : 0;
while (!((bdp->status & RXBD_EMPTY) || (--rx_work_limit < 0))) {
struct sk_buff *newskb;
rmb();
/* Add another skb for the future */
newskb = gfar_new_skb(dev);
skb = rx_queue->rx_skbuff[rx_queue->skb_currx];
dma_unmap_single(priv->dev, bdp->bufPtr,
priv->rx_buffer_size, DMA_FROM_DEVICE);
if (unlikely(!(bdp->status & RXBD_ERR) &&
bdp->length > priv->rx_buffer_size))
bdp->status = RXBD_LARGE;
/* We drop the frame if we failed to allocate a new buffer */
if (unlikely(!newskb || !(bdp->status & RXBD_LAST) ||
bdp->status & RXBD_ERR)) {
count_errors(bdp->status, dev);
if (unlikely(!newskb))
newskb = skb;
else if (skb)
dev_kfree_skb(skb);
} else {
/* Increment the number of packets */
rx_queue->stats.rx_packets++;
howmany++;
if (likely(skb)) {
pkt_len = bdp->length - ETH_FCS_LEN;
/* Remove the FCS from the packet length */
skb_put(skb, pkt_len);
rx_queue->stats.rx_bytes += pkt_len;
skb_record_rx_queue(skb, rx_queue->qindex);
gfar_process_frame(dev, skb, amount_pull,
&rx_queue->grp->napi_rx);
} else {
netif_warn(priv, rx_err, dev, "Missing skb!\n");
rx_queue->stats.rx_dropped++;
atomic64_inc(&priv->extra_stats.rx_skbmissing);
}
}
rx_queue->rx_skbuff[rx_queue->skb_currx] = newskb;
/* Setup the new bdp */
gfar_new_rxbdp(rx_queue, bdp, newskb);
/* Update to the next pointer */
bdp = next_bd(bdp, base, rx_queue->rx_ring_size);
/* update to point at the next skb */
rx_queue->skb_currx = (rx_queue->skb_currx + 1) &
RX_RING_MOD_MASK(rx_queue->rx_ring_size);
}
/* Update the current rxbd pointer to be the next one */
rx_queue->cur_rx = bdp;
return howmany;
}
static int gfar_poll_rx_sq(struct napi_struct *napi, int budget)
{
struct gfar_priv_grp *gfargrp =
container_of(napi, struct gfar_priv_grp, napi_rx);
struct gfar __iomem *regs = gfargrp->regs;
struct gfar_priv_rx_q *rx_queue = gfargrp->rx_queue;
int work_done = 0;
/* Clear IEVENT, so interrupts aren't called again
* because of the packets that have already arrived
*/
gfar_write(®s->ievent, IEVENT_RX_MASK);
work_done = gfar_clean_rx_ring(rx_queue, budget);
if (work_done < budget) {
u32 imask;
napi_complete(napi);
/* Clear the halt bit in RSTAT */
gfar_write(®s->rstat, gfargrp->rstat);
spin_lock_irq(&gfargrp->grplock);
imask = gfar_read(®s->imask);
imask |= IMASK_RX_DEFAULT;
gfar_write(®s->imask, imask);
spin_unlock_irq(&gfargrp->grplock);
}
return work_done;
}
static int gfar_poll_tx_sq(struct napi_struct *napi, int budget)
{
struct gfar_priv_grp *gfargrp =
container_of(napi, struct gfar_priv_grp, napi_tx);
struct gfar __iomem *regs = gfargrp->regs;
struct gfar_priv_tx_q *tx_queue = gfargrp->tx_queue;
u32 imask;
/* Clear IEVENT, so interrupts aren't called again
* because of the packets that have already arrived
*/
gfar_write(®s->ievent, IEVENT_TX_MASK);
/* run Tx cleanup to completion */
if (tx_queue->tx_skbuff[tx_queue->skb_dirtytx])
gfar_clean_tx_ring(tx_queue);
napi_complete(napi);
spin_lock_irq(&gfargrp->grplock);
imask = gfar_read(®s->imask);
imask |= IMASK_TX_DEFAULT;
gfar_write(®s->imask, imask);
spin_unlock_irq(&gfargrp->grplock);
return 0;
}
static int gfar_poll_rx(struct napi_struct *napi, int budget)
{
struct gfar_priv_grp *gfargrp =
container_of(napi, struct gfar_priv_grp, napi_rx);
struct gfar_private *priv = gfargrp->priv;
struct gfar __iomem *regs = gfargrp->regs;
struct gfar_priv_rx_q *rx_queue = NULL;
int work_done = 0, work_done_per_q = 0;
int i, budget_per_q = 0;
unsigned long rstat_rxf;
int num_act_queues;
/* Clear IEVENT, so interrupts aren't called again
* because of the packets that have already arrived
*/
gfar_write(®s->ievent, IEVENT_RX_MASK);
rstat_rxf = gfar_read(®s->rstat) & RSTAT_RXF_MASK;
num_act_queues = bitmap_weight(&rstat_rxf, MAX_RX_QS);
if (num_act_queues)
budget_per_q = budget/num_act_queues;
for_each_set_bit(i, &gfargrp->rx_bit_map, priv->num_rx_queues) {
/* skip queue if not active */
if (!(rstat_rxf & (RSTAT_CLEAR_RXF0 >> i)))
continue;
rx_queue = priv->rx_queue[i];
work_done_per_q =
gfar_clean_rx_ring(rx_queue, budget_per_q);
work_done += work_done_per_q;
/* finished processing this queue */
if (work_done_per_q < budget_per_q) {
/* clear active queue hw indication */
gfar_write(®s->rstat,
RSTAT_CLEAR_RXF0 >> i);
num_act_queues--;
if (!num_act_queues)
break;
}
}
if (!num_act_queues) {
u32 imask;
napi_complete(napi);
/* Clear the halt bit in RSTAT */
gfar_write(®s->rstat, gfargrp->rstat);
spin_lock_irq(&gfargrp->grplock);
imask = gfar_read(®s->imask);
imask |= IMASK_RX_DEFAULT;
gfar_write(®s->imask, imask);
spin_unlock_irq(&gfargrp->grplock);
}
return work_done;
}
static int gfar_poll_tx(struct napi_struct *napi, int budget)
{
struct gfar_priv_grp *gfargrp =
container_of(napi, struct gfar_priv_grp, napi_tx);
struct gfar_private *priv = gfargrp->priv;
struct gfar __iomem *regs = gfargrp->regs;
struct gfar_priv_tx_q *tx_queue = NULL;
int has_tx_work = 0;
int i;
/* Clear IEVENT, so interrupts aren't called again
* because of the packets that have already arrived
*/
gfar_write(®s->ievent, IEVENT_TX_MASK);
for_each_set_bit(i, &gfargrp->tx_bit_map, priv->num_tx_queues) {
tx_queue = priv->tx_queue[i];
/* run Tx cleanup to completion */
if (tx_queue->tx_skbuff[tx_queue->skb_dirtytx]) {
gfar_clean_tx_ring(tx_queue);
has_tx_work = 1;
}
}
if (!has_tx_work) {
u32 imask;
napi_complete(napi);
spin_lock_irq(&gfargrp->grplock);
imask = gfar_read(®s->imask);
imask |= IMASK_TX_DEFAULT;
gfar_write(®s->imask, imask);
spin_unlock_irq(&gfargrp->grplock);
}
return 0;
}
#ifdef CONFIG_NET_POLL_CONTROLLER
/* Polling 'interrupt' - used by things like netconsole to send skbs
* without having to re-enable interrupts. It's not called while
* the interrupt routine is executing.
*/
static void gfar_netpoll(struct net_device *dev)
{
struct gfar_private *priv = netdev_priv(dev);
int i;
/* If the device has multiple interrupts, run tx/rx */
if (priv->device_flags & FSL_GIANFAR_DEV_HAS_MULTI_INTR) {
for (i = 0; i < priv->num_grps; i++) {
struct gfar_priv_grp *grp = &priv->gfargrp[i];
disable_irq(gfar_irq(grp, TX)->irq);
disable_irq(gfar_irq(grp, RX)->irq);
disable_irq(gfar_irq(grp, ER)->irq);
gfar_interrupt(gfar_irq(grp, TX)->irq, grp);
enable_irq(gfar_irq(grp, ER)->irq);
enable_irq(gfar_irq(grp, RX)->irq);
enable_irq(gfar_irq(grp, TX)->irq);
}
} else {
for (i = 0; i < priv->num_grps; i++) {
struct gfar_priv_grp *grp = &priv->gfargrp[i];
disable_irq(gfar_irq(grp, TX)->irq);
gfar_interrupt(gfar_irq(grp, TX)->irq, grp);
enable_irq(gfar_irq(grp, TX)->irq);
}
}
}
#endif
/* The interrupt handler for devices with one interrupt */
static irqreturn_t gfar_interrupt(int irq, void *grp_id)
{
struct gfar_priv_grp *gfargrp = grp_id;
/* Save ievent for future reference */
u32 events = gfar_read(&gfargrp->regs->ievent);
/* Check for reception */
if (events & IEVENT_RX_MASK)
gfar_receive(irq, grp_id);
/* Check for transmit completion */
if (events & IEVENT_TX_MASK)
gfar_transmit(irq, grp_id);
/* Check for errors */
if (events & IEVENT_ERR_MASK)
gfar_error(irq, grp_id);
return IRQ_HANDLED;
}
/* Called every time the controller might need to be made
* aware of new link state. The PHY code conveys this
* information through variables in the phydev structure, and this
* function converts those variables into the appropriate
* register values, and can bring down the device if needed.
*/
static void adjust_link(struct net_device *dev)
{
struct gfar_private *priv = netdev_priv(dev);
struct phy_device *phydev = priv->phydev;
if (unlikely(phydev->link != priv->oldlink ||
phydev->duplex != priv->oldduplex ||
phydev->speed != priv->oldspeed))
gfar_update_link_state(priv);
}
/* Update the hash table based on the current list of multicast
* addresses we subscribe to. Also, change the promiscuity of
* the device based on the flags (this function is called
* whenever dev->flags is changed
*/
static void gfar_set_multi(struct net_device *dev)
{
struct netdev_hw_addr *ha;
struct gfar_private *priv = netdev_priv(dev);
struct gfar __iomem *regs = priv->gfargrp[0].regs;
u32 tempval;
if (dev->flags & IFF_PROMISC) {
/* Set RCTRL to PROM */
tempval = gfar_read(®s->rctrl);
tempval |= RCTRL_PROM;
gfar_write(®s->rctrl, tempval);
} else {
/* Set RCTRL to not PROM */
tempval = gfar_read(®s->rctrl);
tempval &= ~(RCTRL_PROM);
gfar_write(®s->rctrl, tempval);
}
if (dev->flags & IFF_ALLMULTI) {
/* Set the hash to rx all multicast frames */
gfar_write(®s->igaddr0, 0xffffffff);
gfar_write(®s->igaddr1, 0xffffffff);
gfar_write(®s->igaddr2, 0xffffffff);
gfar_write(®s->igaddr3, 0xffffffff);
gfar_write(®s->igaddr4, 0xffffffff);
gfar_write(®s->igaddr5, 0xffffffff);
gfar_write(®s->igaddr6, 0xffffffff);
gfar_write(®s->igaddr7, 0xffffffff);
gfar_write(®s->gaddr0, 0xffffffff);
gfar_write(®s->gaddr1, 0xffffffff);
gfar_write(®s->gaddr2, 0xffffffff);
gfar_write(®s->gaddr3, 0xffffffff);
gfar_write(®s->gaddr4, 0xffffffff);
gfar_write(®s->gaddr5, 0xffffffff);
gfar_write(®s->gaddr6, 0xffffffff);
gfar_write(®s->gaddr7, 0xffffffff);
} else {
int em_num;
int idx;
/* zero out the hash */
gfar_write(®s->igaddr0, 0x0);
gfar_write(®s->igaddr1, 0x0);
gfar_write(®s->igaddr2, 0x0);
gfar_write(®s->igaddr3, 0x0);
gfar_write(®s->igaddr4, 0x0);
gfar_write(®s->igaddr5, 0x0);
gfar_write(®s->igaddr6, 0x0);
gfar_write(®s->igaddr7, 0x0);
gfar_write(®s->gaddr0, 0x0);
gfar_write(®s->gaddr1, 0x0);
gfar_write(®s->gaddr2, 0x0);
gfar_write(®s->gaddr3, 0x0);
gfar_write(®s->gaddr4, 0x0);
gfar_write(®s->gaddr5, 0x0);
gfar_write(®s->gaddr6, 0x0);
gfar_write(®s->gaddr7, 0x0);
/* If we have extended hash tables, we need to
* clear the exact match registers to prepare for
* setting them
*/
if (priv->extended_hash) {
em_num = GFAR_EM_NUM + 1;
gfar_clear_exact_match(dev);
idx = 1;
} else {
idx = 0;
em_num = 0;
}
if (netdev_mc_empty(dev))
return;
/* Parse the list, and set the appropriate bits */
netdev_for_each_mc_addr(ha, dev) {
if (idx < em_num) {
gfar_set_mac_for_addr(dev, idx, ha->addr);
idx++;
} else
gfar_set_hash_for_addr(dev, ha->addr);
}
}
}
/* Clears each of the exact match registers to zero, so they
* don't interfere with normal reception
*/
static void gfar_clear_exact_match(struct net_device *dev)
{
int idx;
static const u8 zero_arr[ETH_ALEN] = {0, 0, 0, 0, 0, 0};
for (idx = 1; idx < GFAR_EM_NUM + 1; idx++)
gfar_set_mac_for_addr(dev, idx, zero_arr);
}
/* Set the appropriate hash bit for the given addr */
/* The algorithm works like so:
* 1) Take the Destination Address (ie the multicast address), and
* do a CRC on it (little endian), and reverse the bits of the
* result.
* 2) Use the 8 most significant bits as a hash into a 256-entry
* table. The table is controlled through 8 32-bit registers:
* gaddr0-7. gaddr0's MSB is entry 0, and gaddr7's LSB is
* gaddr7. This means that the 3 most significant bits in the
* hash index which gaddr register to use, and the 5 other bits
* indicate which bit (assuming an IBM numbering scheme, which
* for PowerPC (tm) is usually the case) in the register holds
* the entry.
*/
static void gfar_set_hash_for_addr(struct net_device *dev, u8 *addr)
{
u32 tempval;
struct gfar_private *priv = netdev_priv(dev);
u32 result = ether_crc(ETH_ALEN, addr);
int width = priv->hash_width;
u8 whichbit = (result >> (32 - width)) & 0x1f;
u8 whichreg = result >> (32 - width + 5);
u32 value = (1 << (31-whichbit));
tempval = gfar_read(priv->hash_regs[whichreg]);
tempval |= value;
gfar_write(priv->hash_regs[whichreg], tempval);
}
/* There are multiple MAC Address register pairs on some controllers
* This function sets the numth pair to a given address
*/
static void gfar_set_mac_for_addr(struct net_device *dev, int num,
const u8 *addr)
{
struct gfar_private *priv = netdev_priv(dev);
struct gfar __iomem *regs = priv->gfargrp[0].regs;
int idx;
char tmpbuf[ETH_ALEN];
u32 tempval;
u32 __iomem *macptr = ®s->macstnaddr1;
macptr += num*2;
/* Now copy it into the mac registers backwards, cuz
* little endian is silly
*/
for (idx = 0; idx < ETH_ALEN; idx++)
tmpbuf[ETH_ALEN - 1 - idx] = addr[idx];
gfar_write(macptr, *((u32 *) (tmpbuf)));
tempval = *((u32 *) (tmpbuf + 4));
gfar_write(macptr+1, tempval);
}
/* GFAR error interrupt handler */
static irqreturn_t gfar_error(int irq, void *grp_id)
{
struct gfar_priv_grp *gfargrp = grp_id;
struct gfar __iomem *regs = gfargrp->regs;
struct gfar_private *priv= gfargrp->priv;
struct net_device *dev = priv->ndev;
/* Save ievent for future reference */
u32 events = gfar_read(®s->ievent);
/* Clear IEVENT */
gfar_write(®s->ievent, events & IEVENT_ERR_MASK);
/* Magic Packet is not an error. */
if ((priv->device_flags & FSL_GIANFAR_DEV_HAS_MAGIC_PACKET) &&
(events & IEVENT_MAG))
events &= ~IEVENT_MAG;
/* Hmm... */
if (netif_msg_rx_err(priv) || netif_msg_tx_err(priv))
netdev_dbg(dev,
"error interrupt (ievent=0x%08x imask=0x%08x)\n",
events, gfar_read(®s->imask));
/* Update the error counters */
if (events & IEVENT_TXE) {
dev->stats.tx_errors++;
if (events & IEVENT_LC)
dev->stats.tx_window_errors++;
if (events & IEVENT_CRL)
dev->stats.tx_aborted_errors++;
if (events & IEVENT_XFUN) {
unsigned long flags;
netif_dbg(priv, tx_err, dev,
"TX FIFO underrun, packet dropped\n");
dev->stats.tx_dropped++;
atomic64_inc(&priv->extra_stats.tx_underrun);
local_irq_save(flags);
lock_tx_qs(priv);
/* Reactivate the Tx Queues */
gfar_write(®s->tstat, gfargrp->tstat);
unlock_tx_qs(priv);
local_irq_restore(flags);
}
netif_dbg(priv, tx_err, dev, "Transmit Error\n");
}
if (events & IEVENT_BSY) {
dev->stats.rx_errors++;
atomic64_inc(&priv->extra_stats.rx_bsy);
gfar_receive(irq, grp_id);
netif_dbg(priv, rx_err, dev, "busy error (rstat: %x)\n",
gfar_read(®s->rstat));
}
if (events & IEVENT_BABR) {
dev->stats.rx_errors++;
atomic64_inc(&priv->extra_stats.rx_babr);
netif_dbg(priv, rx_err, dev, "babbling RX error\n");
}
if (events & IEVENT_EBERR) {
atomic64_inc(&priv->extra_stats.eberr);
netif_dbg(priv, rx_err, dev, "bus error\n");
}
if (events & IEVENT_RXC)
netif_dbg(priv, rx_status, dev, "control frame\n");
if (events & IEVENT_BABT) {
atomic64_inc(&priv->extra_stats.tx_babt);
netif_dbg(priv, tx_err, dev, "babbling TX error\n");
}
return IRQ_HANDLED;
}
static u32 gfar_get_flowctrl_cfg(struct gfar_private *priv)
{
struct phy_device *phydev = priv->phydev;
u32 val = 0;
if (!phydev->duplex)
return val;
if (!priv->pause_aneg_en) {
if (priv->tx_pause_en)
val |= MACCFG1_TX_FLOW;
if (priv->rx_pause_en)
val |= MACCFG1_RX_FLOW;
} else {
u16 lcl_adv, rmt_adv;
u8 flowctrl;
/* get link partner capabilities */
rmt_adv = 0;
if (phydev->pause)
rmt_adv = LPA_PAUSE_CAP;
if (phydev->asym_pause)
rmt_adv |= LPA_PAUSE_ASYM;
lcl_adv = mii_advertise_flowctrl(phydev->advertising);
flowctrl = mii_resolve_flowctrl_fdx(lcl_adv, rmt_adv);
if (flowctrl & FLOW_CTRL_TX)
val |= MACCFG1_TX_FLOW;
if (flowctrl & FLOW_CTRL_RX)
val |= MACCFG1_RX_FLOW;
}
return val;
}
static noinline void gfar_update_link_state(struct gfar_private *priv)
{
struct gfar __iomem *regs = priv->gfargrp[0].regs;
struct phy_device *phydev = priv->phydev;
if (unlikely(test_bit(GFAR_RESETTING, &priv->state)))
return;
if (phydev->link) {
u32 tempval1 = gfar_read(®s->maccfg1);
u32 tempval = gfar_read(®s->maccfg2);
u32 ecntrl = gfar_read(®s->ecntrl);
if (phydev->duplex != priv->oldduplex) {
if (!(phydev->duplex))
tempval &= ~(MACCFG2_FULL_DUPLEX);
else
tempval |= MACCFG2_FULL_DUPLEX;
priv->oldduplex = phydev->duplex;
}
if (phydev->speed != priv->oldspeed) {
switch (phydev->speed) {
case 1000:
tempval =
((tempval & ~(MACCFG2_IF)) | MACCFG2_GMII);
ecntrl &= ~(ECNTRL_R100);
break;
case 100:
case 10:
tempval =
((tempval & ~(MACCFG2_IF)) | MACCFG2_MII);
/* Reduced mode distinguishes
* between 10 and 100
*/
if (phydev->speed == SPEED_100)
ecntrl |= ECNTRL_R100;
else
ecntrl &= ~(ECNTRL_R100);
break;
default:
netif_warn(priv, link, priv->ndev,
"Ack! Speed (%d) is not 10/100/1000!\n",
phydev->speed);
break;
}
priv->oldspeed = phydev->speed;
}
tempval1 &= ~(MACCFG1_TX_FLOW | MACCFG1_RX_FLOW);
tempval1 |= gfar_get_flowctrl_cfg(priv);
gfar_write(®s->maccfg1, tempval1);
gfar_write(®s->maccfg2, tempval);
gfar_write(®s->ecntrl, ecntrl);
if (!priv->oldlink)
priv->oldlink = 1;
} else if (priv->oldlink) {
priv->oldlink = 0;
priv->oldspeed = 0;
priv->oldduplex = -1;
}
if (netif_msg_link(priv))
phy_print_status(phydev);
}
static struct of_device_id gfar_match[] =
{
{
.type = "network",
.compatible = "gianfar",
},
{
.compatible = "fsl,etsec2",
},
{},
};
MODULE_DEVICE_TABLE(of, gfar_match);
/* Structure for a device driver */
static struct platform_driver gfar_driver = {
.driver = {
.name = "fsl-gianfar",
.owner = THIS_MODULE,
.pm = GFAR_PM_OPS,
.of_match_table = gfar_match,
},
.probe = gfar_probe,
.remove = gfar_remove,
};
module_platform_driver(gfar_driver);
| gpl-2.0 |
dan-and/linux-sunxi | drivers/gpu/mali/mali/platform/mali_platform_pmu_testing/mali_platform.c | 64 | 1410 | /*
* Copyright (C) 2010-2012 ARM Limited. All rights reserved.
*
* This program is free software and is provided to you under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation, and any use by you of this program is subject to the terms of such GNU licence.
*
* A copy of the licence is included with the program, and can also be obtained from Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/**
* @file mali_platform.c
* Platform specific Mali driver functions for a default platform
*/
#include "mali_kernel_common.h"
#include "mali_osk.h"
#include "mali_platform.h"
#include "mali_pmu.h"
#include "linux/mali/mali_utgard.h"
static u32 bPowerOff = 1;
_mali_osk_errcode_t mali_platform_init(void)
{
MALI_SUCCESS;
}
_mali_osk_errcode_t mali_platform_deinit(void)
{
MALI_SUCCESS;
}
_mali_osk_errcode_t mali_platform_power_mode_change(mali_power_mode power_mode)
{
switch (power_mode)
{
case MALI_POWER_MODE_ON:
if (bPowerOff == 1)
{
mali_pmu_powerup();
bPowerOff = 0;
}
break;
case MALI_POWER_MODE_LIGHT_SLEEP:
case MALI_POWER_MODE_DEEP_SLEEP:
if (bPowerOff == 0)
{
mali_pmu_powerdown();
bPowerOff = 1;
}
break;
}
MALI_SUCCESS;
}
void mali_gpu_utilization_handler(u32 utilization)
{
}
void set_mali_parent_power_domain(void* dev)
{
}
| gpl-2.0 |
friendlyarm/uboot_nanopi | post/cpu/rlwnm.c | 64 | 3869 | /*
* (C) Copyright 2002
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* See file CREDITS for list of people who contributed to this
* project.
*
* 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 <common.h>
/*
* CPU test
* Shift instructions: rlwnm
*
* The test contains a pre-built table of instructions, operands and
* expected results. For each table entry, the test will cyclically use
* different sets of operand registers and result registers.
*/
#ifdef CONFIG_POST
#include <post.h>
#include "cpu_asm.h"
#if CONFIG_POST & CFG_POST_CPU
extern void cpu_post_exec_22 (ulong *code, ulong *cr, ulong *res, ulong op1,
ulong op2);
extern ulong cpu_post_makecr (long v);
static struct cpu_post_rlwnm_s
{
ulong cmd;
ulong op1;
ulong op2;
uchar mb;
uchar me;
ulong res;
} cpu_post_rlwnm_table[] =
{
{
OP_RLWNM,
0xffff0000,
24,
16,
23,
0x0000ff00
},
};
static unsigned int cpu_post_rlwnm_size =
sizeof (cpu_post_rlwnm_table) / sizeof (struct cpu_post_rlwnm_s);
int cpu_post_test_rlwnm (void)
{
int ret = 0;
unsigned int i, reg;
int flag = disable_interrupts();
for (i = 0; i < cpu_post_rlwnm_size && ret == 0; i++)
{
struct cpu_post_rlwnm_s *test = cpu_post_rlwnm_table + i;
for (reg = 0; reg < 32 && ret == 0; reg++)
{
unsigned int reg0 = (reg + 0) % 32;
unsigned int reg1 = (reg + 1) % 32;
unsigned int reg2 = (reg + 2) % 32;
unsigned int stk = reg < 16 ? 31 : 15;
unsigned long code[] =
{
ASM_STW(stk, 1, -4),
ASM_ADDI(stk, 1, -24),
ASM_STW(3, stk, 12),
ASM_STW(4, stk, 16),
ASM_STW(reg0, stk, 8),
ASM_STW(reg1, stk, 4),
ASM_STW(reg2, stk, 0),
ASM_LWZ(reg1, stk, 12),
ASM_LWZ(reg0, stk, 16),
ASM_122(test->cmd, reg2, reg1, reg0, test->mb, test->me),
ASM_STW(reg2, stk, 12),
ASM_LWZ(reg2, stk, 0),
ASM_LWZ(reg1, stk, 4),
ASM_LWZ(reg0, stk, 8),
ASM_LWZ(3, stk, 12),
ASM_ADDI(1, stk, 24),
ASM_LWZ(stk, 1, -4),
ASM_BLR,
};
unsigned long codecr[] =
{
ASM_STW(stk, 1, -4),
ASM_ADDI(stk, 1, -24),
ASM_STW(3, stk, 12),
ASM_STW(4, stk, 16),
ASM_STW(reg0, stk, 8),
ASM_STW(reg1, stk, 4),
ASM_STW(reg2, stk, 0),
ASM_LWZ(reg1, stk, 12),
ASM_LWZ(reg0, stk, 16),
ASM_122(test->cmd, reg2, reg1, reg0, test->mb, test->me) |
BIT_C,
ASM_STW(reg2, stk, 12),
ASM_LWZ(reg2, stk, 0),
ASM_LWZ(reg1, stk, 4),
ASM_LWZ(reg0, stk, 8),
ASM_LWZ(3, stk, 12),
ASM_ADDI(1, stk, 24),
ASM_LWZ(stk, 1, -4),
ASM_BLR,
};
ulong res;
ulong cr;
if (ret == 0)
{
cr = 0;
cpu_post_exec_22 (code, & cr, & res, test->op1, test->op2);
ret = res == test->res && cr == 0 ? 0 : -1;
if (ret != 0)
{
post_log ("Error at rlwnm test %d !\n", i);
}
}
if (ret == 0)
{
cpu_post_exec_22 (codecr, & cr, & res, test->op1, test->op2);
ret = res == test->res &&
(cr & 0xe0000000) == cpu_post_makecr (res) ? 0 : -1;
if (ret != 0)
{
post_log ("Error at rlwnm test %d !\n", i);
}
}
}
}
if (flag)
enable_interrupts();
return ret;
}
#endif
#endif
| gpl-2.0 |
ultrasystem/system | drivers/gpu/drm/radeon/rs600.c | 64 | 34047 | /*
* Copyright 2008 Advanced Micro Devices, Inc.
* Copyright 2008 Red Hat Inc.
* Copyright 2009 Jerome Glisse.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors: Dave Airlie
* Alex Deucher
* Jerome Glisse
*/
/* RS600 / Radeon X1250/X1270 integrated GPU
*
* This file gather function specific to RS600 which is the IGP of
* the X1250/X1270 family supporting intel CPU (while RS690/RS740
* is the X1250/X1270 supporting AMD CPU). The display engine are
* the avivo one, bios is an atombios, 3D block are the one of the
* R4XX family. The GART is different from the RS400 one and is very
* close to the one of the R600 family (R600 likely being an evolution
* of the RS600 GART block).
*/
#include <drm/drmP.h>
#include "radeon.h"
#include "radeon_asic.h"
#include "atom.h"
#include "rs600d.h"
#include "rs600_reg_safe.h"
static void rs600_gpu_init(struct radeon_device *rdev);
int rs600_mc_wait_for_idle(struct radeon_device *rdev);
static const u32 crtc_offsets[2] =
{
0,
AVIVO_D2CRTC_H_TOTAL - AVIVO_D1CRTC_H_TOTAL
};
static bool avivo_is_in_vblank(struct radeon_device *rdev, int crtc)
{
if (RREG32(AVIVO_D1CRTC_STATUS + crtc_offsets[crtc]) & AVIVO_D1CRTC_V_BLANK)
return true;
else
return false;
}
static bool avivo_is_counter_moving(struct radeon_device *rdev, int crtc)
{
u32 pos1, pos2;
pos1 = RREG32(AVIVO_D1CRTC_STATUS_POSITION + crtc_offsets[crtc]);
pos2 = RREG32(AVIVO_D1CRTC_STATUS_POSITION + crtc_offsets[crtc]);
if (pos1 != pos2)
return true;
else
return false;
}
/**
* avivo_wait_for_vblank - vblank wait asic callback.
*
* @rdev: radeon_device pointer
* @crtc: crtc to wait for vblank on
*
* Wait for vblank on the requested crtc (r5xx-r7xx).
*/
void avivo_wait_for_vblank(struct radeon_device *rdev, int crtc)
{
unsigned i = 0;
if (crtc >= rdev->num_crtc)
return;
if (!(RREG32(AVIVO_D1CRTC_CONTROL + crtc_offsets[crtc]) & AVIVO_CRTC_EN))
return;
/* depending on when we hit vblank, we may be close to active; if so,
* wait for another frame.
*/
while (avivo_is_in_vblank(rdev, crtc)) {
if (i++ % 100 == 0) {
if (!avivo_is_counter_moving(rdev, crtc))
break;
}
}
while (!avivo_is_in_vblank(rdev, crtc)) {
if (i++ % 100 == 0) {
if (!avivo_is_counter_moving(rdev, crtc))
break;
}
}
}
void rs600_pre_page_flip(struct radeon_device *rdev, int crtc)
{
/* enable the pflip int */
radeon_irq_kms_pflip_irq_get(rdev, crtc);
}
void rs600_post_page_flip(struct radeon_device *rdev, int crtc)
{
/* disable the pflip int */
radeon_irq_kms_pflip_irq_put(rdev, crtc);
}
u32 rs600_page_flip(struct radeon_device *rdev, int crtc_id, u64 crtc_base)
{
struct radeon_crtc *radeon_crtc = rdev->mode_info.crtcs[crtc_id];
u32 tmp = RREG32(AVIVO_D1GRPH_UPDATE + radeon_crtc->crtc_offset);
int i;
/* Lock the graphics update lock */
tmp |= AVIVO_D1GRPH_UPDATE_LOCK;
WREG32(AVIVO_D1GRPH_UPDATE + radeon_crtc->crtc_offset, tmp);
/* update the scanout addresses */
WREG32(AVIVO_D1GRPH_SECONDARY_SURFACE_ADDRESS + radeon_crtc->crtc_offset,
(u32)crtc_base);
WREG32(AVIVO_D1GRPH_PRIMARY_SURFACE_ADDRESS + radeon_crtc->crtc_offset,
(u32)crtc_base);
/* Wait for update_pending to go high. */
for (i = 0; i < rdev->usec_timeout; i++) {
if (RREG32(AVIVO_D1GRPH_UPDATE + radeon_crtc->crtc_offset) & AVIVO_D1GRPH_SURFACE_UPDATE_PENDING)
break;
udelay(1);
}
DRM_DEBUG("Update pending now high. Unlocking vupdate_lock.\n");
/* Unlock the lock, so double-buffering can take place inside vblank */
tmp &= ~AVIVO_D1GRPH_UPDATE_LOCK;
WREG32(AVIVO_D1GRPH_UPDATE + radeon_crtc->crtc_offset, tmp);
/* Return current update_pending status: */
return RREG32(AVIVO_D1GRPH_UPDATE + radeon_crtc->crtc_offset) & AVIVO_D1GRPH_SURFACE_UPDATE_PENDING;
}
void avivo_program_fmt(struct drm_encoder *encoder)
{
struct drm_device *dev = encoder->dev;
struct radeon_device *rdev = dev->dev_private;
struct radeon_encoder *radeon_encoder = to_radeon_encoder(encoder);
struct drm_connector *connector = radeon_get_connector_for_encoder(encoder);
int bpc = 0;
u32 tmp = 0;
enum radeon_connector_dither dither = RADEON_FMT_DITHER_DISABLE;
if (connector) {
struct radeon_connector *radeon_connector = to_radeon_connector(connector);
bpc = radeon_get_monitor_bpc(connector);
dither = radeon_connector->dither;
}
/* LVDS FMT is set up by atom */
if (radeon_encoder->devices & ATOM_DEVICE_LCD_SUPPORT)
return;
if (bpc == 0)
return;
switch (bpc) {
case 6:
if (dither == RADEON_FMT_DITHER_ENABLE)
/* XXX sort out optimal dither settings */
tmp |= AVIVO_TMDS_BIT_DEPTH_CONTROL_SPATIAL_DITHER_EN;
else
tmp |= AVIVO_TMDS_BIT_DEPTH_CONTROL_TRUNCATE_EN;
break;
case 8:
if (dither == RADEON_FMT_DITHER_ENABLE)
/* XXX sort out optimal dither settings */
tmp |= (AVIVO_TMDS_BIT_DEPTH_CONTROL_SPATIAL_DITHER_EN |
AVIVO_TMDS_BIT_DEPTH_CONTROL_SPATIAL_DITHER_DEPTH);
else
tmp |= (AVIVO_TMDS_BIT_DEPTH_CONTROL_TRUNCATE_EN |
AVIVO_TMDS_BIT_DEPTH_CONTROL_TRUNCATE_DEPTH);
break;
case 10:
default:
/* not needed */
break;
}
switch (radeon_encoder->encoder_id) {
case ENCODER_OBJECT_ID_INTERNAL_KLDSCP_TMDS1:
WREG32(AVIVO_TMDSA_BIT_DEPTH_CONTROL, tmp);
break;
case ENCODER_OBJECT_ID_INTERNAL_LVTM1:
WREG32(AVIVO_LVTMA_BIT_DEPTH_CONTROL, tmp);
break;
case ENCODER_OBJECT_ID_INTERNAL_KLDSCP_DVO1:
WREG32(AVIVO_DVOA_BIT_DEPTH_CONTROL, tmp);
break;
case ENCODER_OBJECT_ID_INTERNAL_DDI:
WREG32(AVIVO_DDIA_BIT_DEPTH_CONTROL, tmp);
break;
default:
break;
}
}
void rs600_pm_misc(struct radeon_device *rdev)
{
int requested_index = rdev->pm.requested_power_state_index;
struct radeon_power_state *ps = &rdev->pm.power_state[requested_index];
struct radeon_voltage *voltage = &ps->clock_info[0].voltage;
u32 tmp, dyn_pwrmgt_sclk_length, dyn_sclk_vol_cntl;
u32 hdp_dyn_cntl, /*mc_host_dyn_cntl,*/ dyn_backbias_cntl;
if ((voltage->type == VOLTAGE_GPIO) && (voltage->gpio.valid)) {
if (ps->misc & ATOM_PM_MISCINFO_VOLTAGE_DROP_SUPPORT) {
tmp = RREG32(voltage->gpio.reg);
if (voltage->active_high)
tmp |= voltage->gpio.mask;
else
tmp &= ~(voltage->gpio.mask);
WREG32(voltage->gpio.reg, tmp);
if (voltage->delay)
udelay(voltage->delay);
} else {
tmp = RREG32(voltage->gpio.reg);
if (voltage->active_high)
tmp &= ~voltage->gpio.mask;
else
tmp |= voltage->gpio.mask;
WREG32(voltage->gpio.reg, tmp);
if (voltage->delay)
udelay(voltage->delay);
}
} else if (voltage->type == VOLTAGE_VDDC)
radeon_atom_set_voltage(rdev, voltage->vddc_id, SET_VOLTAGE_TYPE_ASIC_VDDC);
dyn_pwrmgt_sclk_length = RREG32_PLL(DYN_PWRMGT_SCLK_LENGTH);
dyn_pwrmgt_sclk_length &= ~REDUCED_POWER_SCLK_HILEN(0xf);
dyn_pwrmgt_sclk_length &= ~REDUCED_POWER_SCLK_LOLEN(0xf);
if (ps->misc & ATOM_PM_MISCINFO_ASIC_REDUCED_SPEED_SCLK_EN) {
if (ps->misc & ATOM_PM_MISCINFO_DYNAMIC_CLOCK_DIVIDER_BY_2) {
dyn_pwrmgt_sclk_length |= REDUCED_POWER_SCLK_HILEN(2);
dyn_pwrmgt_sclk_length |= REDUCED_POWER_SCLK_LOLEN(2);
} else if (ps->misc & ATOM_PM_MISCINFO_DYNAMIC_CLOCK_DIVIDER_BY_4) {
dyn_pwrmgt_sclk_length |= REDUCED_POWER_SCLK_HILEN(4);
dyn_pwrmgt_sclk_length |= REDUCED_POWER_SCLK_LOLEN(4);
}
} else {
dyn_pwrmgt_sclk_length |= REDUCED_POWER_SCLK_HILEN(1);
dyn_pwrmgt_sclk_length |= REDUCED_POWER_SCLK_LOLEN(1);
}
WREG32_PLL(DYN_PWRMGT_SCLK_LENGTH, dyn_pwrmgt_sclk_length);
dyn_sclk_vol_cntl = RREG32_PLL(DYN_SCLK_VOL_CNTL);
if (ps->misc & ATOM_PM_MISCINFO_ASIC_DYNAMIC_VOLTAGE_EN) {
dyn_sclk_vol_cntl |= IO_CG_VOLTAGE_DROP;
if (voltage->delay) {
dyn_sclk_vol_cntl |= VOLTAGE_DROP_SYNC;
dyn_sclk_vol_cntl |= VOLTAGE_DELAY_SEL(voltage->delay);
} else
dyn_sclk_vol_cntl &= ~VOLTAGE_DROP_SYNC;
} else
dyn_sclk_vol_cntl &= ~IO_CG_VOLTAGE_DROP;
WREG32_PLL(DYN_SCLK_VOL_CNTL, dyn_sclk_vol_cntl);
hdp_dyn_cntl = RREG32_PLL(HDP_DYN_CNTL);
if (ps->misc & ATOM_PM_MISCINFO_DYNAMIC_HDP_BLOCK_EN)
hdp_dyn_cntl &= ~HDP_FORCEON;
else
hdp_dyn_cntl |= HDP_FORCEON;
WREG32_PLL(HDP_DYN_CNTL, hdp_dyn_cntl);
#if 0
/* mc_host_dyn seems to cause hangs from time to time */
mc_host_dyn_cntl = RREG32_PLL(MC_HOST_DYN_CNTL);
if (ps->misc & ATOM_PM_MISCINFO_DYNAMIC_MC_HOST_BLOCK_EN)
mc_host_dyn_cntl &= ~MC_HOST_FORCEON;
else
mc_host_dyn_cntl |= MC_HOST_FORCEON;
WREG32_PLL(MC_HOST_DYN_CNTL, mc_host_dyn_cntl);
#endif
dyn_backbias_cntl = RREG32_PLL(DYN_BACKBIAS_CNTL);
if (ps->misc & ATOM_PM_MISCINFO2_DYNAMIC_BACK_BIAS_EN)
dyn_backbias_cntl |= IO_CG_BACKBIAS_EN;
else
dyn_backbias_cntl &= ~IO_CG_BACKBIAS_EN;
WREG32_PLL(DYN_BACKBIAS_CNTL, dyn_backbias_cntl);
/* set pcie lanes */
if ((rdev->flags & RADEON_IS_PCIE) &&
!(rdev->flags & RADEON_IS_IGP) &&
rdev->asic->pm.set_pcie_lanes &&
(ps->pcie_lanes !=
rdev->pm.power_state[rdev->pm.current_power_state_index].pcie_lanes)) {
radeon_set_pcie_lanes(rdev,
ps->pcie_lanes);
DRM_DEBUG("Setting: p: %d\n", ps->pcie_lanes);
}
}
void rs600_pm_prepare(struct radeon_device *rdev)
{
struct drm_device *ddev = rdev->ddev;
struct drm_crtc *crtc;
struct radeon_crtc *radeon_crtc;
u32 tmp;
/* disable any active CRTCs */
list_for_each_entry(crtc, &ddev->mode_config.crtc_list, head) {
radeon_crtc = to_radeon_crtc(crtc);
if (radeon_crtc->enabled) {
tmp = RREG32(AVIVO_D1CRTC_CONTROL + radeon_crtc->crtc_offset);
tmp |= AVIVO_CRTC_DISP_READ_REQUEST_DISABLE;
WREG32(AVIVO_D1CRTC_CONTROL + radeon_crtc->crtc_offset, tmp);
}
}
}
void rs600_pm_finish(struct radeon_device *rdev)
{
struct drm_device *ddev = rdev->ddev;
struct drm_crtc *crtc;
struct radeon_crtc *radeon_crtc;
u32 tmp;
/* enable any active CRTCs */
list_for_each_entry(crtc, &ddev->mode_config.crtc_list, head) {
radeon_crtc = to_radeon_crtc(crtc);
if (radeon_crtc->enabled) {
tmp = RREG32(AVIVO_D1CRTC_CONTROL + radeon_crtc->crtc_offset);
tmp &= ~AVIVO_CRTC_DISP_READ_REQUEST_DISABLE;
WREG32(AVIVO_D1CRTC_CONTROL + radeon_crtc->crtc_offset, tmp);
}
}
}
/* hpd for digital panel detect/disconnect */
bool rs600_hpd_sense(struct radeon_device *rdev, enum radeon_hpd_id hpd)
{
u32 tmp;
bool connected = false;
switch (hpd) {
case RADEON_HPD_1:
tmp = RREG32(R_007D04_DC_HOT_PLUG_DETECT1_INT_STATUS);
if (G_007D04_DC_HOT_PLUG_DETECT1_SENSE(tmp))
connected = true;
break;
case RADEON_HPD_2:
tmp = RREG32(R_007D14_DC_HOT_PLUG_DETECT2_INT_STATUS);
if (G_007D14_DC_HOT_PLUG_DETECT2_SENSE(tmp))
connected = true;
break;
default:
break;
}
return connected;
}
void rs600_hpd_set_polarity(struct radeon_device *rdev,
enum radeon_hpd_id hpd)
{
u32 tmp;
bool connected = rs600_hpd_sense(rdev, hpd);
switch (hpd) {
case RADEON_HPD_1:
tmp = RREG32(R_007D08_DC_HOT_PLUG_DETECT1_INT_CONTROL);
if (connected)
tmp &= ~S_007D08_DC_HOT_PLUG_DETECT1_INT_POLARITY(1);
else
tmp |= S_007D08_DC_HOT_PLUG_DETECT1_INT_POLARITY(1);
WREG32(R_007D08_DC_HOT_PLUG_DETECT1_INT_CONTROL, tmp);
break;
case RADEON_HPD_2:
tmp = RREG32(R_007D18_DC_HOT_PLUG_DETECT2_INT_CONTROL);
if (connected)
tmp &= ~S_007D18_DC_HOT_PLUG_DETECT2_INT_POLARITY(1);
else
tmp |= S_007D18_DC_HOT_PLUG_DETECT2_INT_POLARITY(1);
WREG32(R_007D18_DC_HOT_PLUG_DETECT2_INT_CONTROL, tmp);
break;
default:
break;
}
}
void rs600_hpd_init(struct radeon_device *rdev)
{
struct drm_device *dev = rdev->ddev;
struct drm_connector *connector;
unsigned enable = 0;
list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
struct radeon_connector *radeon_connector = to_radeon_connector(connector);
switch (radeon_connector->hpd.hpd) {
case RADEON_HPD_1:
WREG32(R_007D00_DC_HOT_PLUG_DETECT1_CONTROL,
S_007D00_DC_HOT_PLUG_DETECT1_EN(1));
break;
case RADEON_HPD_2:
WREG32(R_007D10_DC_HOT_PLUG_DETECT2_CONTROL,
S_007D10_DC_HOT_PLUG_DETECT2_EN(1));
break;
default:
break;
}
enable |= 1 << radeon_connector->hpd.hpd;
radeon_hpd_set_polarity(rdev, radeon_connector->hpd.hpd);
}
radeon_irq_kms_enable_hpd(rdev, enable);
}
void rs600_hpd_fini(struct radeon_device *rdev)
{
struct drm_device *dev = rdev->ddev;
struct drm_connector *connector;
unsigned disable = 0;
list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
struct radeon_connector *radeon_connector = to_radeon_connector(connector);
switch (radeon_connector->hpd.hpd) {
case RADEON_HPD_1:
WREG32(R_007D00_DC_HOT_PLUG_DETECT1_CONTROL,
S_007D00_DC_HOT_PLUG_DETECT1_EN(0));
break;
case RADEON_HPD_2:
WREG32(R_007D10_DC_HOT_PLUG_DETECT2_CONTROL,
S_007D10_DC_HOT_PLUG_DETECT2_EN(0));
break;
default:
break;
}
disable |= 1 << radeon_connector->hpd.hpd;
}
radeon_irq_kms_disable_hpd(rdev, disable);
}
int rs600_asic_reset(struct radeon_device *rdev)
{
struct rv515_mc_save save;
u32 status, tmp;
int ret = 0;
status = RREG32(R_000E40_RBBM_STATUS);
if (!G_000E40_GUI_ACTIVE(status)) {
return 0;
}
/* Stops all mc clients */
rv515_mc_stop(rdev, &save);
status = RREG32(R_000E40_RBBM_STATUS);
dev_info(rdev->dev, "(%s:%d) RBBM_STATUS=0x%08X\n", __func__, __LINE__, status);
/* stop CP */
WREG32(RADEON_CP_CSQ_CNTL, 0);
tmp = RREG32(RADEON_CP_RB_CNTL);
WREG32(RADEON_CP_RB_CNTL, tmp | RADEON_RB_RPTR_WR_ENA);
WREG32(RADEON_CP_RB_RPTR_WR, 0);
WREG32(RADEON_CP_RB_WPTR, 0);
WREG32(RADEON_CP_RB_CNTL, tmp);
pci_save_state(rdev->pdev);
/* disable bus mastering */
pci_clear_master(rdev->pdev);
mdelay(1);
/* reset GA+VAP */
WREG32(R_0000F0_RBBM_SOFT_RESET, S_0000F0_SOFT_RESET_VAP(1) |
S_0000F0_SOFT_RESET_GA(1));
RREG32(R_0000F0_RBBM_SOFT_RESET);
mdelay(500);
WREG32(R_0000F0_RBBM_SOFT_RESET, 0);
mdelay(1);
status = RREG32(R_000E40_RBBM_STATUS);
dev_info(rdev->dev, "(%s:%d) RBBM_STATUS=0x%08X\n", __func__, __LINE__, status);
/* reset CP */
WREG32(R_0000F0_RBBM_SOFT_RESET, S_0000F0_SOFT_RESET_CP(1));
RREG32(R_0000F0_RBBM_SOFT_RESET);
mdelay(500);
WREG32(R_0000F0_RBBM_SOFT_RESET, 0);
mdelay(1);
status = RREG32(R_000E40_RBBM_STATUS);
dev_info(rdev->dev, "(%s:%d) RBBM_STATUS=0x%08X\n", __func__, __LINE__, status);
/* reset MC */
WREG32(R_0000F0_RBBM_SOFT_RESET, S_0000F0_SOFT_RESET_MC(1));
RREG32(R_0000F0_RBBM_SOFT_RESET);
mdelay(500);
WREG32(R_0000F0_RBBM_SOFT_RESET, 0);
mdelay(1);
status = RREG32(R_000E40_RBBM_STATUS);
dev_info(rdev->dev, "(%s:%d) RBBM_STATUS=0x%08X\n", __func__, __LINE__, status);
/* restore PCI & busmastering */
pci_restore_state(rdev->pdev);
/* Check if GPU is idle */
if (G_000E40_GA_BUSY(status) || G_000E40_VAP_BUSY(status)) {
dev_err(rdev->dev, "failed to reset GPU\n");
ret = -1;
} else
dev_info(rdev->dev, "GPU reset succeed\n");
rv515_mc_resume(rdev, &save);
return ret;
}
/*
* GART.
*/
void rs600_gart_tlb_flush(struct radeon_device *rdev)
{
uint32_t tmp;
tmp = RREG32_MC(R_000100_MC_PT0_CNTL);
tmp &= C_000100_INVALIDATE_ALL_L1_TLBS & C_000100_INVALIDATE_L2_CACHE;
WREG32_MC(R_000100_MC_PT0_CNTL, tmp);
tmp = RREG32_MC(R_000100_MC_PT0_CNTL);
tmp |= S_000100_INVALIDATE_ALL_L1_TLBS(1) | S_000100_INVALIDATE_L2_CACHE(1);
WREG32_MC(R_000100_MC_PT0_CNTL, tmp);
tmp = RREG32_MC(R_000100_MC_PT0_CNTL);
tmp &= C_000100_INVALIDATE_ALL_L1_TLBS & C_000100_INVALIDATE_L2_CACHE;
WREG32_MC(R_000100_MC_PT0_CNTL, tmp);
tmp = RREG32_MC(R_000100_MC_PT0_CNTL);
}
static int rs600_gart_init(struct radeon_device *rdev)
{
int r;
if (rdev->gart.robj) {
WARN(1, "RS600 GART already initialized\n");
return 0;
}
/* Initialize common gart structure */
r = radeon_gart_init(rdev);
if (r) {
return r;
}
rdev->gart.table_size = rdev->gart.num_gpu_pages * 8;
return radeon_gart_table_vram_alloc(rdev);
}
static int rs600_gart_enable(struct radeon_device *rdev)
{
u32 tmp;
int r, i;
if (rdev->gart.robj == NULL) {
dev_err(rdev->dev, "No VRAM object for PCIE GART.\n");
return -EINVAL;
}
r = radeon_gart_table_vram_pin(rdev);
if (r)
return r;
radeon_gart_restore(rdev);
/* Enable bus master */
tmp = RREG32(RADEON_BUS_CNTL) & ~RS600_BUS_MASTER_DIS;
WREG32(RADEON_BUS_CNTL, tmp);
/* FIXME: setup default page */
WREG32_MC(R_000100_MC_PT0_CNTL,
(S_000100_EFFECTIVE_L2_CACHE_SIZE(6) |
S_000100_EFFECTIVE_L2_QUEUE_SIZE(6)));
for (i = 0; i < 19; i++) {
WREG32_MC(R_00016C_MC_PT0_CLIENT0_CNTL + i,
S_00016C_ENABLE_TRANSLATION_MODE_OVERRIDE(1) |
S_00016C_SYSTEM_ACCESS_MODE_MASK(
V_00016C_SYSTEM_ACCESS_MODE_NOT_IN_SYS) |
S_00016C_SYSTEM_APERTURE_UNMAPPED_ACCESS(
V_00016C_SYSTEM_APERTURE_UNMAPPED_PASSTHROUGH) |
S_00016C_EFFECTIVE_L1_CACHE_SIZE(3) |
S_00016C_ENABLE_FRAGMENT_PROCESSING(1) |
S_00016C_EFFECTIVE_L1_QUEUE_SIZE(3));
}
/* enable first context */
WREG32_MC(R_000102_MC_PT0_CONTEXT0_CNTL,
S_000102_ENABLE_PAGE_TABLE(1) |
S_000102_PAGE_TABLE_DEPTH(V_000102_PAGE_TABLE_FLAT));
/* disable all other contexts */
for (i = 1; i < 8; i++)
WREG32_MC(R_000102_MC_PT0_CONTEXT0_CNTL + i, 0);
/* setup the page table */
WREG32_MC(R_00012C_MC_PT0_CONTEXT0_FLAT_BASE_ADDR,
rdev->gart.table_addr);
WREG32_MC(R_00013C_MC_PT0_CONTEXT0_FLAT_START_ADDR, rdev->mc.gtt_start);
WREG32_MC(R_00014C_MC_PT0_CONTEXT0_FLAT_END_ADDR, rdev->mc.gtt_end);
WREG32_MC(R_00011C_MC_PT0_CONTEXT0_DEFAULT_READ_ADDR, 0);
/* System context maps to VRAM space */
WREG32_MC(R_000112_MC_PT0_SYSTEM_APERTURE_LOW_ADDR, rdev->mc.vram_start);
WREG32_MC(R_000114_MC_PT0_SYSTEM_APERTURE_HIGH_ADDR, rdev->mc.vram_end);
/* enable page tables */
tmp = RREG32_MC(R_000100_MC_PT0_CNTL);
WREG32_MC(R_000100_MC_PT0_CNTL, (tmp | S_000100_ENABLE_PT(1)));
tmp = RREG32_MC(R_000009_MC_CNTL1);
WREG32_MC(R_000009_MC_CNTL1, (tmp | S_000009_ENABLE_PAGE_TABLES(1)));
rs600_gart_tlb_flush(rdev);
DRM_INFO("PCIE GART of %uM enabled (table at 0x%016llX).\n",
(unsigned)(rdev->mc.gtt_size >> 20),
(unsigned long long)rdev->gart.table_addr);
rdev->gart.ready = true;
return 0;
}
static void rs600_gart_disable(struct radeon_device *rdev)
{
u32 tmp;
/* FIXME: disable out of gart access */
WREG32_MC(R_000100_MC_PT0_CNTL, 0);
tmp = RREG32_MC(R_000009_MC_CNTL1);
WREG32_MC(R_000009_MC_CNTL1, tmp & C_000009_ENABLE_PAGE_TABLES);
radeon_gart_table_vram_unpin(rdev);
}
static void rs600_gart_fini(struct radeon_device *rdev)
{
radeon_gart_fini(rdev);
rs600_gart_disable(rdev);
radeon_gart_table_vram_free(rdev);
}
#define R600_PTE_VALID (1 << 0)
#define R600_PTE_SYSTEM (1 << 1)
#define R600_PTE_SNOOPED (1 << 2)
#define R600_PTE_READABLE (1 << 5)
#define R600_PTE_WRITEABLE (1 << 6)
int rs600_gart_set_page(struct radeon_device *rdev, int i, uint64_t addr)
{
void __iomem *ptr = (void *)rdev->gart.ptr;
if (i < 0 || i > rdev->gart.num_gpu_pages) {
return -EINVAL;
}
addr = addr & 0xFFFFFFFFFFFFF000ULL;
if (addr != rdev->dummy_page.addr)
addr |= R600_PTE_VALID | R600_PTE_READABLE |
R600_PTE_WRITEABLE;
addr |= R600_PTE_SYSTEM | R600_PTE_SNOOPED;
writeq(addr, ptr + (i * 8));
return 0;
}
int rs600_irq_set(struct radeon_device *rdev)
{
uint32_t tmp = 0;
uint32_t mode_int = 0;
u32 hpd1 = RREG32(R_007D08_DC_HOT_PLUG_DETECT1_INT_CONTROL) &
~S_007D08_DC_HOT_PLUG_DETECT1_INT_EN(1);
u32 hpd2 = RREG32(R_007D18_DC_HOT_PLUG_DETECT2_INT_CONTROL) &
~S_007D18_DC_HOT_PLUG_DETECT2_INT_EN(1);
u32 hdmi0;
if (ASIC_IS_DCE2(rdev))
hdmi0 = RREG32(R_007408_HDMI0_AUDIO_PACKET_CONTROL) &
~S_007408_HDMI0_AZ_FORMAT_WTRIG_MASK(1);
else
hdmi0 = 0;
if (!rdev->irq.installed) {
WARN(1, "Can't enable IRQ/MSI because no handler is installed\n");
WREG32(R_000040_GEN_INT_CNTL, 0);
return -EINVAL;
}
if (atomic_read(&rdev->irq.ring_int[RADEON_RING_TYPE_GFX_INDEX])) {
tmp |= S_000040_SW_INT_EN(1);
}
if (rdev->irq.crtc_vblank_int[0] ||
atomic_read(&rdev->irq.pflip[0])) {
mode_int |= S_006540_D1MODE_VBLANK_INT_MASK(1);
}
if (rdev->irq.crtc_vblank_int[1] ||
atomic_read(&rdev->irq.pflip[1])) {
mode_int |= S_006540_D2MODE_VBLANK_INT_MASK(1);
}
if (rdev->irq.hpd[0]) {
hpd1 |= S_007D08_DC_HOT_PLUG_DETECT1_INT_EN(1);
}
if (rdev->irq.hpd[1]) {
hpd2 |= S_007D18_DC_HOT_PLUG_DETECT2_INT_EN(1);
}
if (rdev->irq.afmt[0]) {
hdmi0 |= S_007408_HDMI0_AZ_FORMAT_WTRIG_MASK(1);
}
WREG32(R_000040_GEN_INT_CNTL, tmp);
WREG32(R_006540_DxMODE_INT_MASK, mode_int);
WREG32(R_007D08_DC_HOT_PLUG_DETECT1_INT_CONTROL, hpd1);
WREG32(R_007D18_DC_HOT_PLUG_DETECT2_INT_CONTROL, hpd2);
if (ASIC_IS_DCE2(rdev))
WREG32(R_007408_HDMI0_AUDIO_PACKET_CONTROL, hdmi0);
return 0;
}
static inline u32 rs600_irq_ack(struct radeon_device *rdev)
{
uint32_t irqs = RREG32(R_000044_GEN_INT_STATUS);
uint32_t irq_mask = S_000044_SW_INT(1);
u32 tmp;
if (G_000044_DISPLAY_INT_STAT(irqs)) {
rdev->irq.stat_regs.r500.disp_int = RREG32(R_007EDC_DISP_INTERRUPT_STATUS);
if (G_007EDC_LB_D1_VBLANK_INTERRUPT(rdev->irq.stat_regs.r500.disp_int)) {
WREG32(R_006534_D1MODE_VBLANK_STATUS,
S_006534_D1MODE_VBLANK_ACK(1));
}
if (G_007EDC_LB_D2_VBLANK_INTERRUPT(rdev->irq.stat_regs.r500.disp_int)) {
WREG32(R_006D34_D2MODE_VBLANK_STATUS,
S_006D34_D2MODE_VBLANK_ACK(1));
}
if (G_007EDC_DC_HOT_PLUG_DETECT1_INTERRUPT(rdev->irq.stat_regs.r500.disp_int)) {
tmp = RREG32(R_007D08_DC_HOT_PLUG_DETECT1_INT_CONTROL);
tmp |= S_007D08_DC_HOT_PLUG_DETECT1_INT_ACK(1);
WREG32(R_007D08_DC_HOT_PLUG_DETECT1_INT_CONTROL, tmp);
}
if (G_007EDC_DC_HOT_PLUG_DETECT2_INTERRUPT(rdev->irq.stat_regs.r500.disp_int)) {
tmp = RREG32(R_007D18_DC_HOT_PLUG_DETECT2_INT_CONTROL);
tmp |= S_007D18_DC_HOT_PLUG_DETECT2_INT_ACK(1);
WREG32(R_007D18_DC_HOT_PLUG_DETECT2_INT_CONTROL, tmp);
}
} else {
rdev->irq.stat_regs.r500.disp_int = 0;
}
if (ASIC_IS_DCE2(rdev)) {
rdev->irq.stat_regs.r500.hdmi0_status = RREG32(R_007404_HDMI0_STATUS) &
S_007404_HDMI0_AZ_FORMAT_WTRIG(1);
if (G_007404_HDMI0_AZ_FORMAT_WTRIG(rdev->irq.stat_regs.r500.hdmi0_status)) {
tmp = RREG32(R_007408_HDMI0_AUDIO_PACKET_CONTROL);
tmp |= S_007408_HDMI0_AZ_FORMAT_WTRIG_ACK(1);
WREG32(R_007408_HDMI0_AUDIO_PACKET_CONTROL, tmp);
}
} else
rdev->irq.stat_regs.r500.hdmi0_status = 0;
if (irqs) {
WREG32(R_000044_GEN_INT_STATUS, irqs);
}
return irqs & irq_mask;
}
void rs600_irq_disable(struct radeon_device *rdev)
{
u32 hdmi0 = RREG32(R_007408_HDMI0_AUDIO_PACKET_CONTROL) &
~S_007408_HDMI0_AZ_FORMAT_WTRIG_MASK(1);
WREG32(R_007408_HDMI0_AUDIO_PACKET_CONTROL, hdmi0);
WREG32(R_000040_GEN_INT_CNTL, 0);
WREG32(R_006540_DxMODE_INT_MASK, 0);
/* Wait and acknowledge irq */
mdelay(1);
rs600_irq_ack(rdev);
}
int rs600_irq_process(struct radeon_device *rdev)
{
u32 status, msi_rearm;
bool queue_hotplug = false;
bool queue_hdmi = false;
status = rs600_irq_ack(rdev);
if (!status &&
!rdev->irq.stat_regs.r500.disp_int &&
!rdev->irq.stat_regs.r500.hdmi0_status) {
return IRQ_NONE;
}
while (status ||
rdev->irq.stat_regs.r500.disp_int ||
rdev->irq.stat_regs.r500.hdmi0_status) {
/* SW interrupt */
if (G_000044_SW_INT(status)) {
radeon_fence_process(rdev, RADEON_RING_TYPE_GFX_INDEX);
}
/* Vertical blank interrupts */
if (G_007EDC_LB_D1_VBLANK_INTERRUPT(rdev->irq.stat_regs.r500.disp_int)) {
if (rdev->irq.crtc_vblank_int[0]) {
drm_handle_vblank(rdev->ddev, 0);
rdev->pm.vblank_sync = true;
wake_up(&rdev->irq.vblank_queue);
}
if (atomic_read(&rdev->irq.pflip[0]))
radeon_crtc_handle_flip(rdev, 0);
}
if (G_007EDC_LB_D2_VBLANK_INTERRUPT(rdev->irq.stat_regs.r500.disp_int)) {
if (rdev->irq.crtc_vblank_int[1]) {
drm_handle_vblank(rdev->ddev, 1);
rdev->pm.vblank_sync = true;
wake_up(&rdev->irq.vblank_queue);
}
if (atomic_read(&rdev->irq.pflip[1]))
radeon_crtc_handle_flip(rdev, 1);
}
if (G_007EDC_DC_HOT_PLUG_DETECT1_INTERRUPT(rdev->irq.stat_regs.r500.disp_int)) {
queue_hotplug = true;
DRM_DEBUG("HPD1\n");
}
if (G_007EDC_DC_HOT_PLUG_DETECT2_INTERRUPT(rdev->irq.stat_regs.r500.disp_int)) {
queue_hotplug = true;
DRM_DEBUG("HPD2\n");
}
if (G_007404_HDMI0_AZ_FORMAT_WTRIG(rdev->irq.stat_regs.r500.hdmi0_status)) {
queue_hdmi = true;
DRM_DEBUG("HDMI0\n");
}
status = rs600_irq_ack(rdev);
}
if (queue_hotplug)
schedule_work(&rdev->hotplug_work);
if (queue_hdmi)
schedule_work(&rdev->audio_work);
if (rdev->msi_enabled) {
switch (rdev->family) {
case CHIP_RS600:
case CHIP_RS690:
case CHIP_RS740:
msi_rearm = RREG32(RADEON_BUS_CNTL) & ~RS600_MSI_REARM;
WREG32(RADEON_BUS_CNTL, msi_rearm);
WREG32(RADEON_BUS_CNTL, msi_rearm | RS600_MSI_REARM);
break;
default:
WREG32(RADEON_MSI_REARM_EN, RV370_MSI_REARM_EN);
break;
}
}
return IRQ_HANDLED;
}
u32 rs600_get_vblank_counter(struct radeon_device *rdev, int crtc)
{
if (crtc == 0)
return RREG32(R_0060A4_D1CRTC_STATUS_FRAME_COUNT);
else
return RREG32(R_0068A4_D2CRTC_STATUS_FRAME_COUNT);
}
int rs600_mc_wait_for_idle(struct radeon_device *rdev)
{
unsigned i;
for (i = 0; i < rdev->usec_timeout; i++) {
if (G_000000_MC_IDLE(RREG32_MC(R_000000_MC_STATUS)))
return 0;
udelay(1);
}
return -1;
}
static void rs600_gpu_init(struct radeon_device *rdev)
{
r420_pipes_init(rdev);
/* Wait for mc idle */
if (rs600_mc_wait_for_idle(rdev))
dev_warn(rdev->dev, "Wait MC idle timeout before updating MC.\n");
}
static void rs600_mc_init(struct radeon_device *rdev)
{
u64 base;
rdev->mc.aper_base = pci_resource_start(rdev->pdev, 0);
rdev->mc.aper_size = pci_resource_len(rdev->pdev, 0);
rdev->mc.vram_is_ddr = true;
rdev->mc.vram_width = 128;
rdev->mc.real_vram_size = RREG32(RADEON_CONFIG_MEMSIZE);
rdev->mc.mc_vram_size = rdev->mc.real_vram_size;
rdev->mc.visible_vram_size = rdev->mc.aper_size;
rdev->mc.igp_sideport_enabled = radeon_atombios_sideport_present(rdev);
base = RREG32_MC(R_000004_MC_FB_LOCATION);
base = G_000004_MC_FB_START(base) << 16;
radeon_vram_location(rdev, &rdev->mc, base);
rdev->mc.gtt_base_align = 0;
radeon_gtt_location(rdev, &rdev->mc);
radeon_update_bandwidth_info(rdev);
}
void rs600_bandwidth_update(struct radeon_device *rdev)
{
struct drm_display_mode *mode0 = NULL;
struct drm_display_mode *mode1 = NULL;
u32 d1mode_priority_a_cnt, d2mode_priority_a_cnt;
/* FIXME: implement full support */
if (!rdev->mode_info.mode_config_initialized)
return;
radeon_update_display_priority(rdev);
if (rdev->mode_info.crtcs[0]->base.enabled)
mode0 = &rdev->mode_info.crtcs[0]->base.mode;
if (rdev->mode_info.crtcs[1]->base.enabled)
mode1 = &rdev->mode_info.crtcs[1]->base.mode;
rs690_line_buffer_adjust(rdev, mode0, mode1);
if (rdev->disp_priority == 2) {
d1mode_priority_a_cnt = RREG32(R_006548_D1MODE_PRIORITY_A_CNT);
d2mode_priority_a_cnt = RREG32(R_006D48_D2MODE_PRIORITY_A_CNT);
d1mode_priority_a_cnt |= S_006548_D1MODE_PRIORITY_A_ALWAYS_ON(1);
d2mode_priority_a_cnt |= S_006D48_D2MODE_PRIORITY_A_ALWAYS_ON(1);
WREG32(R_006548_D1MODE_PRIORITY_A_CNT, d1mode_priority_a_cnt);
WREG32(R_00654C_D1MODE_PRIORITY_B_CNT, d1mode_priority_a_cnt);
WREG32(R_006D48_D2MODE_PRIORITY_A_CNT, d2mode_priority_a_cnt);
WREG32(R_006D4C_D2MODE_PRIORITY_B_CNT, d2mode_priority_a_cnt);
}
}
uint32_t rs600_mc_rreg(struct radeon_device *rdev, uint32_t reg)
{
unsigned long flags;
u32 r;
spin_lock_irqsave(&rdev->mc_idx_lock, flags);
WREG32(R_000070_MC_IND_INDEX, S_000070_MC_IND_ADDR(reg) |
S_000070_MC_IND_CITF_ARB0(1));
r = RREG32(R_000074_MC_IND_DATA);
spin_unlock_irqrestore(&rdev->mc_idx_lock, flags);
return r;
}
void rs600_mc_wreg(struct radeon_device *rdev, uint32_t reg, uint32_t v)
{
unsigned long flags;
spin_lock_irqsave(&rdev->mc_idx_lock, flags);
WREG32(R_000070_MC_IND_INDEX, S_000070_MC_IND_ADDR(reg) |
S_000070_MC_IND_CITF_ARB0(1) | S_000070_MC_IND_WR_EN(1));
WREG32(R_000074_MC_IND_DATA, v);
spin_unlock_irqrestore(&rdev->mc_idx_lock, flags);
}
static void rs600_debugfs(struct radeon_device *rdev)
{
if (r100_debugfs_rbbm_init(rdev))
DRM_ERROR("Failed to register debugfs file for RBBM !\n");
}
void rs600_set_safe_registers(struct radeon_device *rdev)
{
rdev->config.r300.reg_safe_bm = rs600_reg_safe_bm;
rdev->config.r300.reg_safe_bm_size = ARRAY_SIZE(rs600_reg_safe_bm);
}
static void rs600_mc_program(struct radeon_device *rdev)
{
struct rv515_mc_save save;
/* Stops all mc clients */
rv515_mc_stop(rdev, &save);
/* Wait for mc idle */
if (rs600_mc_wait_for_idle(rdev))
dev_warn(rdev->dev, "Wait MC idle timeout before updating MC.\n");
/* FIXME: What does AGP means for such chipset ? */
WREG32_MC(R_000005_MC_AGP_LOCATION, 0x0FFFFFFF);
WREG32_MC(R_000006_AGP_BASE, 0);
WREG32_MC(R_000007_AGP_BASE_2, 0);
/* Program MC */
WREG32_MC(R_000004_MC_FB_LOCATION,
S_000004_MC_FB_START(rdev->mc.vram_start >> 16) |
S_000004_MC_FB_TOP(rdev->mc.vram_end >> 16));
WREG32(R_000134_HDP_FB_LOCATION,
S_000134_HDP_FB_START(rdev->mc.vram_start >> 16));
rv515_mc_resume(rdev, &save);
}
static int rs600_startup(struct radeon_device *rdev)
{
int r;
rs600_mc_program(rdev);
/* Resume clock */
rv515_clock_startup(rdev);
/* Initialize GPU configuration (# pipes, ...) */
rs600_gpu_init(rdev);
/* Initialize GART (initialize after TTM so we can allocate
* memory through TTM but finalize after TTM) */
r = rs600_gart_enable(rdev);
if (r)
return r;
/* allocate wb buffer */
r = radeon_wb_init(rdev);
if (r)
return r;
r = radeon_fence_driver_start_ring(rdev, RADEON_RING_TYPE_GFX_INDEX);
if (r) {
dev_err(rdev->dev, "failed initializing CP fences (%d).\n", r);
return r;
}
/* Enable IRQ */
if (!rdev->irq.installed) {
r = radeon_irq_kms_init(rdev);
if (r)
return r;
}
rs600_irq_set(rdev);
rdev->config.r300.hdp_cntl = RREG32(RADEON_HOST_PATH_CNTL);
/* 1M ring buffer */
r = r100_cp_init(rdev, 1024 * 1024);
if (r) {
dev_err(rdev->dev, "failed initializing CP (%d).\n", r);
return r;
}
r = radeon_ib_pool_init(rdev);
if (r) {
dev_err(rdev->dev, "IB initialization failed (%d).\n", r);
return r;
}
r = r600_audio_init(rdev);
if (r) {
dev_err(rdev->dev, "failed initializing audio\n");
return r;
}
return 0;
}
int rs600_resume(struct radeon_device *rdev)
{
int r;
/* Make sur GART are not working */
rs600_gart_disable(rdev);
/* Resume clock before doing reset */
rv515_clock_startup(rdev);
/* Reset gpu before posting otherwise ATOM will enter infinite loop */
if (radeon_asic_reset(rdev)) {
dev_warn(rdev->dev, "GPU reset failed ! (0xE40=0x%08X, 0x7C0=0x%08X)\n",
RREG32(R_000E40_RBBM_STATUS),
RREG32(R_0007C0_CP_STAT));
}
/* post */
atom_asic_init(rdev->mode_info.atom_context);
/* Resume clock after posting */
rv515_clock_startup(rdev);
/* Initialize surface registers */
radeon_surface_init(rdev);
rdev->accel_working = true;
r = rs600_startup(rdev);
if (r) {
rdev->accel_working = false;
}
return r;
}
int rs600_suspend(struct radeon_device *rdev)
{
radeon_pm_suspend(rdev);
r600_audio_fini(rdev);
r100_cp_disable(rdev);
radeon_wb_disable(rdev);
rs600_irq_disable(rdev);
rs600_gart_disable(rdev);
return 0;
}
void rs600_fini(struct radeon_device *rdev)
{
radeon_pm_fini(rdev);
r600_audio_fini(rdev);
r100_cp_fini(rdev);
radeon_wb_fini(rdev);
radeon_ib_pool_fini(rdev);
radeon_gem_fini(rdev);
rs600_gart_fini(rdev);
radeon_irq_kms_fini(rdev);
radeon_fence_driver_fini(rdev);
radeon_bo_fini(rdev);
radeon_atombios_fini(rdev);
kfree(rdev->bios);
rdev->bios = NULL;
}
int rs600_init(struct radeon_device *rdev)
{
int r;
/* Disable VGA */
rv515_vga_render_disable(rdev);
/* Initialize scratch registers */
radeon_scratch_init(rdev);
/* Initialize surface registers */
radeon_surface_init(rdev);
/* restore some register to sane defaults */
r100_restore_sanity(rdev);
/* BIOS */
if (!radeon_get_bios(rdev)) {
if (ASIC_IS_AVIVO(rdev))
return -EINVAL;
}
if (rdev->is_atom_bios) {
r = radeon_atombios_init(rdev);
if (r)
return r;
} else {
dev_err(rdev->dev, "Expecting atombios for RS600 GPU\n");
return -EINVAL;
}
/* Reset gpu before posting otherwise ATOM will enter infinite loop */
if (radeon_asic_reset(rdev)) {
dev_warn(rdev->dev,
"GPU reset failed ! (0xE40=0x%08X, 0x7C0=0x%08X)\n",
RREG32(R_000E40_RBBM_STATUS),
RREG32(R_0007C0_CP_STAT));
}
/* check if cards are posted or not */
if (radeon_boot_test_post_card(rdev) == false)
return -EINVAL;
/* Initialize clocks */
radeon_get_clock_info(rdev->ddev);
/* initialize memory controller */
rs600_mc_init(rdev);
rs600_debugfs(rdev);
/* Fence driver */
r = radeon_fence_driver_init(rdev);
if (r)
return r;
/* Memory manager */
r = radeon_bo_init(rdev);
if (r)
return r;
r = rs600_gart_init(rdev);
if (r)
return r;
rs600_set_safe_registers(rdev);
/* Initialize power management */
radeon_pm_init(rdev);
rdev->accel_working = true;
r = rs600_startup(rdev);
if (r) {
/* Somethings want wront with the accel init stop accel */
dev_err(rdev->dev, "Disabling GPU acceleration\n");
r100_cp_fini(rdev);
radeon_wb_fini(rdev);
radeon_ib_pool_fini(rdev);
rs600_gart_fini(rdev);
radeon_irq_kms_fini(rdev);
rdev->accel_working = false;
}
return 0;
}
| gpl-2.0 |
arpith20/linux | arch/arm/mach-s5pv210/pm.c | 1600 | 4011 | /* linux/arch/arm/mach-s5pv210/pm.c
*
* Copyright (c) 2010-2014 Samsung Electronics Co., Ltd.
* http://www.samsung.com
*
* S5PV210 - Power Management support
*
* Based on arch/arm/mach-s3c2410/pm.c
* Copyright (c) 2006 Simtec Electronics
* Ben Dooks <ben@simtec.co.uk>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/init.h>
#include <linux/suspend.h>
#include <linux/syscore_ops.h>
#include <linux/io.h>
#include <asm/cacheflush.h>
#include <asm/suspend.h>
#include <plat/pm-common.h>
#include "common.h"
#include "regs-clock.h"
static struct sleep_save s5pv210_core_save[] = {
/* Clock ETC */
SAVE_ITEM(S5P_MDNIE_SEL),
};
/*
* VIC wake-up support (TODO)
*/
static u32 s5pv210_irqwake_intmask = 0xffffffff;
/*
* Suspend helpers.
*/
static int s5pv210_cpu_suspend(unsigned long arg)
{
unsigned long tmp;
/* issue the standby signal into the pm unit. Note, we
* issue a write-buffer drain just in case */
tmp = 0;
asm("b 1f\n\t"
".align 5\n\t"
"1:\n\t"
"mcr p15, 0, %0, c7, c10, 5\n\t"
"mcr p15, 0, %0, c7, c10, 4\n\t"
"wfi" : : "r" (tmp));
pr_info("Failed to suspend the system\n");
return 1; /* Aborting suspend */
}
static void s5pv210_pm_prepare(void)
{
unsigned int tmp;
/* Set wake-up mask registers */
__raw_writel(exynos_get_eint_wake_mask(), S5P_EINT_WAKEUP_MASK);
__raw_writel(s5pv210_irqwake_intmask, S5P_WAKEUP_MASK);
/* ensure at least INFORM0 has the resume address */
__raw_writel(virt_to_phys(s5pv210_cpu_resume), S5P_INFORM0);
tmp = __raw_readl(S5P_SLEEP_CFG);
tmp &= ~(S5P_SLEEP_CFG_OSC_EN | S5P_SLEEP_CFG_USBOSC_EN);
__raw_writel(tmp, S5P_SLEEP_CFG);
/* WFI for SLEEP mode configuration by SYSCON */
tmp = __raw_readl(S5P_PWR_CFG);
tmp &= S5P_CFG_WFI_CLEAN;
tmp |= S5P_CFG_WFI_SLEEP;
__raw_writel(tmp, S5P_PWR_CFG);
/* SYSCON interrupt handling disable */
tmp = __raw_readl(S5P_OTHERS);
tmp |= S5P_OTHER_SYSC_INTOFF;
__raw_writel(tmp, S5P_OTHERS);
s3c_pm_do_save(s5pv210_core_save, ARRAY_SIZE(s5pv210_core_save));
}
/*
* Suspend operations.
*/
static int s5pv210_suspend_enter(suspend_state_t state)
{
int ret;
s3c_pm_debug_init();
S3C_PMDBG("%s: suspending the system...\n", __func__);
S3C_PMDBG("%s: wakeup masks: %08x,%08x\n", __func__,
s5pv210_irqwake_intmask, exynos_get_eint_wake_mask());
if (s5pv210_irqwake_intmask == -1U
&& exynos_get_eint_wake_mask() == -1U) {
pr_err("%s: No wake-up sources!\n", __func__);
pr_err("%s: Aborting sleep\n", __func__);
return -EINVAL;
}
s3c_pm_save_uarts();
s5pv210_pm_prepare();
flush_cache_all();
s3c_pm_check_store();
ret = cpu_suspend(0, s5pv210_cpu_suspend);
if (ret)
return ret;
s3c_pm_restore_uarts();
S3C_PMDBG("%s: wakeup stat: %08x\n", __func__,
__raw_readl(S5P_WAKEUP_STAT));
s3c_pm_check_restore();
S3C_PMDBG("%s: resuming the system...\n", __func__);
return 0;
}
static int s5pv210_suspend_prepare(void)
{
s3c_pm_check_prepare();
return 0;
}
static void s5pv210_suspend_finish(void)
{
s3c_pm_check_cleanup();
}
static const struct platform_suspend_ops s5pv210_suspend_ops = {
.enter = s5pv210_suspend_enter,
.prepare = s5pv210_suspend_prepare,
.finish = s5pv210_suspend_finish,
.valid = suspend_valid_only_mem,
};
/*
* Syscore operations used to delay restore of certain registers.
*/
static void s5pv210_pm_resume(void)
{
u32 tmp;
tmp = __raw_readl(S5P_OTHERS);
tmp |= (S5P_OTHERS_RET_IO | S5P_OTHERS_RET_CF |\
S5P_OTHERS_RET_MMC | S5P_OTHERS_RET_UART);
__raw_writel(tmp , S5P_OTHERS);
s3c_pm_do_restore_core(s5pv210_core_save, ARRAY_SIZE(s5pv210_core_save));
}
static struct syscore_ops s5pv210_pm_syscore_ops = {
.resume = s5pv210_pm_resume,
};
/*
* Initialization entry point.
*/
void __init s5pv210_pm_init(void)
{
register_syscore_ops(&s5pv210_pm_syscore_ops);
suspend_set_ops(&s5pv210_suspend_ops);
}
| gpl-2.0 |
perillamint/Kite2 | arch/arm/kernel/ptrace.c | 1600 | 22906 | /*
* linux/arch/arm/kernel/ptrace.c
*
* By Ross Biro 1/23/92
* edited by Linus Torvalds
* ARM modifications Copyright (C) 2000 Russell King
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/elf.h>
#include <linux/smp.h>
#include <linux/ptrace.h>
#include <linux/user.h>
#include <linux/security.h>
#include <linux/init.h>
#include <linux/signal.h>
#include <linux/uaccess.h>
#include <linux/perf_event.h>
#include <linux/hw_breakpoint.h>
#include <linux/regset.h>
#include <linux/audit.h>
#include <asm/pgtable.h>
#include <asm/traps.h>
#define REG_PC 15
#define REG_PSR 16
/*
* does not yet catch signals sent when the child dies.
* in exit.c or in signal.c.
*/
#if 0
/*
* Breakpoint SWI instruction: SWI &9F0001
*/
#define BREAKINST_ARM 0xef9f0001
#define BREAKINST_THUMB 0xdf00 /* fill this in later */
#else
/*
* New breakpoints - use an undefined instruction. The ARM architecture
* reference manual guarantees that the following instruction space
* will produce an undefined instruction exception on all CPUs:
*
* ARM: xxxx 0111 1111 xxxx xxxx xxxx 1111 xxxx
* Thumb: 1101 1110 xxxx xxxx
*/
#define BREAKINST_ARM 0xe7f001f0
#define BREAKINST_THUMB 0xde01
#endif
struct pt_regs_offset {
const char *name;
int offset;
};
#define REG_OFFSET_NAME(r) \
{.name = #r, .offset = offsetof(struct pt_regs, ARM_##r)}
#define REG_OFFSET_END {.name = NULL, .offset = 0}
static const struct pt_regs_offset regoffset_table[] = {
REG_OFFSET_NAME(r0),
REG_OFFSET_NAME(r1),
REG_OFFSET_NAME(r2),
REG_OFFSET_NAME(r3),
REG_OFFSET_NAME(r4),
REG_OFFSET_NAME(r5),
REG_OFFSET_NAME(r6),
REG_OFFSET_NAME(r7),
REG_OFFSET_NAME(r8),
REG_OFFSET_NAME(r9),
REG_OFFSET_NAME(r10),
REG_OFFSET_NAME(fp),
REG_OFFSET_NAME(ip),
REG_OFFSET_NAME(sp),
REG_OFFSET_NAME(lr),
REG_OFFSET_NAME(pc),
REG_OFFSET_NAME(cpsr),
REG_OFFSET_NAME(ORIG_r0),
REG_OFFSET_END,
};
/**
* regs_query_register_offset() - query register offset from its name
* @name: the name of a register
*
* regs_query_register_offset() returns the offset of a register in struct
* pt_regs from its name. If the name is invalid, this returns -EINVAL;
*/
int regs_query_register_offset(const char *name)
{
const struct pt_regs_offset *roff;
for (roff = regoffset_table; roff->name != NULL; roff++)
if (!strcmp(roff->name, name))
return roff->offset;
return -EINVAL;
}
/**
* regs_query_register_name() - query register name from its offset
* @offset: the offset of a register in struct pt_regs.
*
* regs_query_register_name() returns the name of a register from its
* offset in struct pt_regs. If the @offset is invalid, this returns NULL;
*/
const char *regs_query_register_name(unsigned int offset)
{
const struct pt_regs_offset *roff;
for (roff = regoffset_table; roff->name != NULL; roff++)
if (roff->offset == offset)
return roff->name;
return NULL;
}
/**
* regs_within_kernel_stack() - check the address in the stack
* @regs: pt_regs which contains kernel stack pointer.
* @addr: address which is checked.
*
* regs_within_kernel_stack() checks @addr is within the kernel stack page(s).
* If @addr is within the kernel stack, it returns true. If not, returns false.
*/
bool regs_within_kernel_stack(struct pt_regs *regs, unsigned long addr)
{
return ((addr & ~(THREAD_SIZE - 1)) ==
(kernel_stack_pointer(regs) & ~(THREAD_SIZE - 1)));
}
/**
* regs_get_kernel_stack_nth() - get Nth entry of the stack
* @regs: pt_regs which contains kernel stack pointer.
* @n: stack entry number.
*
* regs_get_kernel_stack_nth() returns @n th entry of the kernel stack which
* is specified by @regs. If the @n th entry is NOT in the kernel stack,
* this returns 0.
*/
unsigned long regs_get_kernel_stack_nth(struct pt_regs *regs, unsigned int n)
{
unsigned long *addr = (unsigned long *)kernel_stack_pointer(regs);
addr += n;
if (regs_within_kernel_stack(regs, (unsigned long)addr))
return *addr;
else
return 0;
}
/*
* this routine will get a word off of the processes privileged stack.
* the offset is how far from the base addr as stored in the THREAD.
* this routine assumes that all the privileged stacks are in our
* data space.
*/
static inline long get_user_reg(struct task_struct *task, int offset)
{
return task_pt_regs(task)->uregs[offset];
}
/*
* this routine will put a word on the processes privileged stack.
* the offset is how far from the base addr as stored in the THREAD.
* this routine assumes that all the privileged stacks are in our
* data space.
*/
static inline int
put_user_reg(struct task_struct *task, int offset, long data)
{
struct pt_regs newregs, *regs = task_pt_regs(task);
int ret = -EINVAL;
newregs = *regs;
newregs.uregs[offset] = data;
if (valid_user_regs(&newregs)) {
regs->uregs[offset] = data;
ret = 0;
}
return ret;
}
/*
* Called by kernel/ptrace.c when detaching..
*/
void ptrace_disable(struct task_struct *child)
{
/* Nothing to do. */
}
/*
* Handle hitting a breakpoint.
*/
void ptrace_break(struct task_struct *tsk, struct pt_regs *regs)
{
siginfo_t info;
info.si_signo = SIGTRAP;
info.si_errno = 0;
info.si_code = TRAP_BRKPT;
info.si_addr = (void __user *)instruction_pointer(regs);
force_sig_info(SIGTRAP, &info, tsk);
}
static int break_trap(struct pt_regs *regs, unsigned int instr)
{
ptrace_break(current, regs);
return 0;
}
static struct undef_hook arm_break_hook = {
.instr_mask = 0x0fffffff,
.instr_val = 0x07f001f0,
.cpsr_mask = PSR_T_BIT,
.cpsr_val = 0,
.fn = break_trap,
};
static struct undef_hook thumb_break_hook = {
.instr_mask = 0xffff,
.instr_val = 0xde01,
.cpsr_mask = PSR_T_BIT,
.cpsr_val = PSR_T_BIT,
.fn = break_trap,
};
static struct undef_hook thumb2_break_hook = {
.instr_mask = 0xffffffff,
.instr_val = 0xf7f0a000,
.cpsr_mask = PSR_T_BIT,
.cpsr_val = PSR_T_BIT,
.fn = break_trap,
};
static int __init ptrace_break_init(void)
{
register_undef_hook(&arm_break_hook);
register_undef_hook(&thumb_break_hook);
register_undef_hook(&thumb2_break_hook);
return 0;
}
core_initcall(ptrace_break_init);
/*
* Read the word at offset "off" into the "struct user". We
* actually access the pt_regs stored on the kernel stack.
*/
static int ptrace_read_user(struct task_struct *tsk, unsigned long off,
unsigned long __user *ret)
{
unsigned long tmp;
if (off & 3)
return -EIO;
tmp = 0;
if (off == PT_TEXT_ADDR)
tmp = tsk->mm->start_code;
else if (off == PT_DATA_ADDR)
tmp = tsk->mm->start_data;
else if (off == PT_TEXT_END_ADDR)
tmp = tsk->mm->end_code;
else if (off < sizeof(struct pt_regs))
tmp = get_user_reg(tsk, off >> 2);
else if (off >= sizeof(struct user))
return -EIO;
return put_user(tmp, ret);
}
/*
* Write the word at offset "off" into "struct user". We
* actually access the pt_regs stored on the kernel stack.
*/
static int ptrace_write_user(struct task_struct *tsk, unsigned long off,
unsigned long val)
{
if (off & 3 || off >= sizeof(struct user))
return -EIO;
if (off >= sizeof(struct pt_regs))
return 0;
return put_user_reg(tsk, off >> 2, val);
}
#ifdef CONFIG_IWMMXT
/*
* Get the child iWMMXt state.
*/
static int ptrace_getwmmxregs(struct task_struct *tsk, void __user *ufp)
{
struct thread_info *thread = task_thread_info(tsk);
if (!test_ti_thread_flag(thread, TIF_USING_IWMMXT))
return -ENODATA;
iwmmxt_task_disable(thread); /* force it to ram */
return copy_to_user(ufp, &thread->fpstate.iwmmxt, IWMMXT_SIZE)
? -EFAULT : 0;
}
/*
* Set the child iWMMXt state.
*/
static int ptrace_setwmmxregs(struct task_struct *tsk, void __user *ufp)
{
struct thread_info *thread = task_thread_info(tsk);
if (!test_ti_thread_flag(thread, TIF_USING_IWMMXT))
return -EACCES;
iwmmxt_task_release(thread); /* force a reload */
return copy_from_user(&thread->fpstate.iwmmxt, ufp, IWMMXT_SIZE)
? -EFAULT : 0;
}
#endif
#ifdef CONFIG_CRUNCH
/*
* Get the child Crunch state.
*/
static int ptrace_getcrunchregs(struct task_struct *tsk, void __user *ufp)
{
struct thread_info *thread = task_thread_info(tsk);
crunch_task_disable(thread); /* force it to ram */
return copy_to_user(ufp, &thread->crunchstate, CRUNCH_SIZE)
? -EFAULT : 0;
}
/*
* Set the child Crunch state.
*/
static int ptrace_setcrunchregs(struct task_struct *tsk, void __user *ufp)
{
struct thread_info *thread = task_thread_info(tsk);
crunch_task_release(thread); /* force a reload */
return copy_from_user(&thread->crunchstate, ufp, CRUNCH_SIZE)
? -EFAULT : 0;
}
#endif
#ifdef CONFIG_HAVE_HW_BREAKPOINT
/*
* Convert a virtual register number into an index for a thread_info
* breakpoint array. Breakpoints are identified using positive numbers
* whilst watchpoints are negative. The registers are laid out as pairs
* of (address, control), each pair mapping to a unique hw_breakpoint struct.
* Register 0 is reserved for describing resource information.
*/
static int ptrace_hbp_num_to_idx(long num)
{
if (num < 0)
num = (ARM_MAX_BRP << 1) - num;
return (num - 1) >> 1;
}
/*
* Returns the virtual register number for the address of the
* breakpoint at index idx.
*/
static long ptrace_hbp_idx_to_num(int idx)
{
long mid = ARM_MAX_BRP << 1;
long num = (idx << 1) + 1;
return num > mid ? mid - num : num;
}
/*
* Handle hitting a HW-breakpoint.
*/
static void ptrace_hbptriggered(struct perf_event *bp,
struct perf_sample_data *data,
struct pt_regs *regs)
{
struct arch_hw_breakpoint *bkpt = counter_arch_bp(bp);
long num;
int i;
siginfo_t info;
for (i = 0; i < ARM_MAX_HBP_SLOTS; ++i)
if (current->thread.debug.hbp[i] == bp)
break;
num = (i == ARM_MAX_HBP_SLOTS) ? 0 : ptrace_hbp_idx_to_num(i);
info.si_signo = SIGTRAP;
info.si_errno = (int)num;
info.si_code = TRAP_HWBKPT;
info.si_addr = (void __user *)(bkpt->trigger);
force_sig_info(SIGTRAP, &info, current);
}
/*
* Set ptrace breakpoint pointers to zero for this task.
* This is required in order to prevent child processes from unregistering
* breakpoints held by their parent.
*/
void clear_ptrace_hw_breakpoint(struct task_struct *tsk)
{
memset(tsk->thread.debug.hbp, 0, sizeof(tsk->thread.debug.hbp));
}
/*
* Unregister breakpoints from this task and reset the pointers in
* the thread_struct.
*/
void flush_ptrace_hw_breakpoint(struct task_struct *tsk)
{
int i;
struct thread_struct *t = &tsk->thread;
for (i = 0; i < ARM_MAX_HBP_SLOTS; i++) {
if (t->debug.hbp[i]) {
unregister_hw_breakpoint(t->debug.hbp[i]);
t->debug.hbp[i] = NULL;
}
}
}
static u32 ptrace_get_hbp_resource_info(void)
{
u8 num_brps, num_wrps, debug_arch, wp_len;
u32 reg = 0;
num_brps = hw_breakpoint_slots(TYPE_INST);
num_wrps = hw_breakpoint_slots(TYPE_DATA);
debug_arch = arch_get_debug_arch();
wp_len = arch_get_max_wp_len();
reg |= debug_arch;
reg <<= 8;
reg |= wp_len;
reg <<= 8;
reg |= num_wrps;
reg <<= 8;
reg |= num_brps;
return reg;
}
static struct perf_event *ptrace_hbp_create(struct task_struct *tsk, int type)
{
struct perf_event_attr attr;
ptrace_breakpoint_init(&attr);
/* Initialise fields to sane defaults. */
attr.bp_addr = 0;
attr.bp_len = HW_BREAKPOINT_LEN_4;
attr.bp_type = type;
attr.disabled = 1;
return register_user_hw_breakpoint(&attr, ptrace_hbptriggered, NULL,
tsk);
}
static int ptrace_gethbpregs(struct task_struct *tsk, long num,
unsigned long __user *data)
{
u32 reg;
int idx, ret = 0;
struct perf_event *bp;
struct arch_hw_breakpoint_ctrl arch_ctrl;
if (num == 0) {
reg = ptrace_get_hbp_resource_info();
} else {
idx = ptrace_hbp_num_to_idx(num);
if (idx < 0 || idx >= ARM_MAX_HBP_SLOTS) {
ret = -EINVAL;
goto out;
}
bp = tsk->thread.debug.hbp[idx];
if (!bp) {
reg = 0;
goto put;
}
arch_ctrl = counter_arch_bp(bp)->ctrl;
/*
* Fix up the len because we may have adjusted it
* to compensate for an unaligned address.
*/
while (!(arch_ctrl.len & 0x1))
arch_ctrl.len >>= 1;
if (num & 0x1)
reg = bp->attr.bp_addr;
else
reg = encode_ctrl_reg(arch_ctrl);
}
put:
if (put_user(reg, data))
ret = -EFAULT;
out:
return ret;
}
static int ptrace_sethbpregs(struct task_struct *tsk, long num,
unsigned long __user *data)
{
int idx, gen_len, gen_type, implied_type, ret = 0;
u32 user_val;
struct perf_event *bp;
struct arch_hw_breakpoint_ctrl ctrl;
struct perf_event_attr attr;
if (num == 0)
goto out;
else if (num < 0)
implied_type = HW_BREAKPOINT_RW;
else
implied_type = HW_BREAKPOINT_X;
idx = ptrace_hbp_num_to_idx(num);
if (idx < 0 || idx >= ARM_MAX_HBP_SLOTS) {
ret = -EINVAL;
goto out;
}
if (get_user(user_val, data)) {
ret = -EFAULT;
goto out;
}
bp = tsk->thread.debug.hbp[idx];
if (!bp) {
bp = ptrace_hbp_create(tsk, implied_type);
if (IS_ERR(bp)) {
ret = PTR_ERR(bp);
goto out;
}
tsk->thread.debug.hbp[idx] = bp;
}
attr = bp->attr;
if (num & 0x1) {
/* Address */
attr.bp_addr = user_val;
} else {
/* Control */
decode_ctrl_reg(user_val, &ctrl);
ret = arch_bp_generic_fields(ctrl, &gen_len, &gen_type);
if (ret)
goto out;
if ((gen_type & implied_type) != gen_type) {
ret = -EINVAL;
goto out;
}
attr.bp_len = gen_len;
attr.bp_type = gen_type;
attr.disabled = !ctrl.enabled;
}
ret = modify_user_hw_breakpoint(bp, &attr);
out:
return ret;
}
#endif
/* regset get/set implementations */
static int gpr_get(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
void *kbuf, void __user *ubuf)
{
struct pt_regs *regs = task_pt_regs(target);
return user_regset_copyout(&pos, &count, &kbuf, &ubuf,
regs,
0, sizeof(*regs));
}
static int gpr_set(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf)
{
int ret;
struct pt_regs newregs;
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf,
&newregs,
0, sizeof(newregs));
if (ret)
return ret;
if (!valid_user_regs(&newregs))
return -EINVAL;
*task_pt_regs(target) = newregs;
return 0;
}
static int fpa_get(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
void *kbuf, void __user *ubuf)
{
return user_regset_copyout(&pos, &count, &kbuf, &ubuf,
&task_thread_info(target)->fpstate,
0, sizeof(struct user_fp));
}
static int fpa_set(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf)
{
struct thread_info *thread = task_thread_info(target);
thread->used_cp[1] = thread->used_cp[2] = 1;
return user_regset_copyin(&pos, &count, &kbuf, &ubuf,
&thread->fpstate,
0, sizeof(struct user_fp));
}
#ifdef CONFIG_VFP
/*
* VFP register get/set implementations.
*
* With respect to the kernel, struct user_fp is divided into three chunks:
* 16 or 32 real VFP registers (d0-d15 or d0-31)
* These are transferred to/from the real registers in the task's
* vfp_hard_struct. The number of registers depends on the kernel
* configuration.
*
* 16 or 0 fake VFP registers (d16-d31 or empty)
* i.e., the user_vfp structure has space for 32 registers even if
* the kernel doesn't have them all.
*
* vfp_get() reads this chunk as zero where applicable
* vfp_set() ignores this chunk
*
* 1 word for the FPSCR
*
* The bounds-checking logic built into user_regset_copyout and friends
* means that we can make a simple sequence of calls to map the relevant data
* to/from the specified slice of the user regset structure.
*/
static int vfp_get(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
void *kbuf, void __user *ubuf)
{
int ret;
struct thread_info *thread = task_thread_info(target);
struct vfp_hard_struct const *vfp = &thread->vfpstate.hard;
const size_t user_fpregs_offset = offsetof(struct user_vfp, fpregs);
const size_t user_fpscr_offset = offsetof(struct user_vfp, fpscr);
vfp_sync_hwstate(thread);
ret = user_regset_copyout(&pos, &count, &kbuf, &ubuf,
&vfp->fpregs,
user_fpregs_offset,
user_fpregs_offset + sizeof(vfp->fpregs));
if (ret)
return ret;
ret = user_regset_copyout_zero(&pos, &count, &kbuf, &ubuf,
user_fpregs_offset + sizeof(vfp->fpregs),
user_fpscr_offset);
if (ret)
return ret;
return user_regset_copyout(&pos, &count, &kbuf, &ubuf,
&vfp->fpscr,
user_fpscr_offset,
user_fpscr_offset + sizeof(vfp->fpscr));
}
/*
* For vfp_set() a read-modify-write is done on the VFP registers,
* in order to avoid writing back a half-modified set of registers on
* failure.
*/
static int vfp_set(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf)
{
int ret;
struct thread_info *thread = task_thread_info(target);
struct vfp_hard_struct new_vfp;
const size_t user_fpregs_offset = offsetof(struct user_vfp, fpregs);
const size_t user_fpscr_offset = offsetof(struct user_vfp, fpscr);
vfp_sync_hwstate(thread);
new_vfp = thread->vfpstate.hard;
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf,
&new_vfp.fpregs,
user_fpregs_offset,
user_fpregs_offset + sizeof(new_vfp.fpregs));
if (ret)
return ret;
ret = user_regset_copyin_ignore(&pos, &count, &kbuf, &ubuf,
user_fpregs_offset + sizeof(new_vfp.fpregs),
user_fpscr_offset);
if (ret)
return ret;
ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf,
&new_vfp.fpscr,
user_fpscr_offset,
user_fpscr_offset + sizeof(new_vfp.fpscr));
if (ret)
return ret;
vfp_flush_hwstate(thread);
thread->vfpstate.hard = new_vfp;
return 0;
}
#endif /* CONFIG_VFP */
enum arm_regset {
REGSET_GPR,
REGSET_FPR,
#ifdef CONFIG_VFP
REGSET_VFP,
#endif
};
static const struct user_regset arm_regsets[] = {
[REGSET_GPR] = {
.core_note_type = NT_PRSTATUS,
.n = ELF_NGREG,
.size = sizeof(u32),
.align = sizeof(u32),
.get = gpr_get,
.set = gpr_set
},
[REGSET_FPR] = {
/*
* For the FPA regs in fpstate, the real fields are a mixture
* of sizes, so pretend that the registers are word-sized:
*/
.core_note_type = NT_PRFPREG,
.n = sizeof(struct user_fp) / sizeof(u32),
.size = sizeof(u32),
.align = sizeof(u32),
.get = fpa_get,
.set = fpa_set
},
#ifdef CONFIG_VFP
[REGSET_VFP] = {
/*
* Pretend that the VFP regs are word-sized, since the FPSCR is
* a single word dangling at the end of struct user_vfp:
*/
.core_note_type = NT_ARM_VFP,
.n = ARM_VFPREGS_SIZE / sizeof(u32),
.size = sizeof(u32),
.align = sizeof(u32),
.get = vfp_get,
.set = vfp_set
},
#endif /* CONFIG_VFP */
};
static const struct user_regset_view user_arm_view = {
.name = "arm", .e_machine = ELF_ARCH, .ei_osabi = ELF_OSABI,
.regsets = arm_regsets, .n = ARRAY_SIZE(arm_regsets)
};
const struct user_regset_view *task_user_regset_view(struct task_struct *task)
{
return &user_arm_view;
}
long arch_ptrace(struct task_struct *child, long request,
unsigned long addr, unsigned long data)
{
int ret;
unsigned long __user *datap = (unsigned long __user *) data;
switch (request) {
case PTRACE_PEEKUSR:
ret = ptrace_read_user(child, addr, datap);
break;
case PTRACE_POKEUSR:
ret = ptrace_write_user(child, addr, data);
break;
case PTRACE_GETREGS:
ret = copy_regset_to_user(child,
&user_arm_view, REGSET_GPR,
0, sizeof(struct pt_regs),
datap);
break;
case PTRACE_SETREGS:
ret = copy_regset_from_user(child,
&user_arm_view, REGSET_GPR,
0, sizeof(struct pt_regs),
datap);
break;
case PTRACE_GETFPREGS:
ret = copy_regset_to_user(child,
&user_arm_view, REGSET_FPR,
0, sizeof(union fp_state),
datap);
break;
case PTRACE_SETFPREGS:
ret = copy_regset_from_user(child,
&user_arm_view, REGSET_FPR,
0, sizeof(union fp_state),
datap);
break;
#ifdef CONFIG_IWMMXT
case PTRACE_GETWMMXREGS:
ret = ptrace_getwmmxregs(child, datap);
break;
case PTRACE_SETWMMXREGS:
ret = ptrace_setwmmxregs(child, datap);
break;
#endif
case PTRACE_GET_THREAD_AREA:
ret = put_user(task_thread_info(child)->tp_value,
datap);
break;
case PTRACE_SET_SYSCALL:
task_thread_info(child)->syscall = data;
ret = 0;
break;
#ifdef CONFIG_CRUNCH
case PTRACE_GETCRUNCHREGS:
ret = ptrace_getcrunchregs(child, datap);
break;
case PTRACE_SETCRUNCHREGS:
ret = ptrace_setcrunchregs(child, datap);
break;
#endif
#ifdef CONFIG_VFP
case PTRACE_GETVFPREGS:
ret = copy_regset_to_user(child,
&user_arm_view, REGSET_VFP,
0, ARM_VFPREGS_SIZE,
datap);
break;
case PTRACE_SETVFPREGS:
ret = copy_regset_from_user(child,
&user_arm_view, REGSET_VFP,
0, ARM_VFPREGS_SIZE,
datap);
break;
#endif
#ifdef CONFIG_HAVE_HW_BREAKPOINT
case PTRACE_GETHBPREGS:
if (ptrace_get_breakpoints(child) < 0)
return -ESRCH;
ret = ptrace_gethbpregs(child, addr,
(unsigned long __user *)data);
ptrace_put_breakpoints(child);
break;
case PTRACE_SETHBPREGS:
if (ptrace_get_breakpoints(child) < 0)
return -ESRCH;
ret = ptrace_sethbpregs(child, addr,
(unsigned long __user *)data);
ptrace_put_breakpoints(child);
break;
#endif
default:
ret = ptrace_request(child, request, addr, data);
break;
}
return ret;
}
asmlinkage int syscall_trace(int why, struct pt_regs *regs, int scno)
{
unsigned long ip;
if (why)
audit_syscall_exit(regs);
else
audit_syscall_entry(AUDIT_ARCH_ARM, scno, regs->ARM_r0,
regs->ARM_r1, regs->ARM_r2, regs->ARM_r3);
if (!test_thread_flag(TIF_SYSCALL_TRACE))
return scno;
if (!(current->ptrace & PT_PTRACED))
return scno;
current_thread_info()->syscall = scno;
/*
* IP is used to denote syscall entry/exit:
* IP = 0 -> entry, =1 -> exit
*/
ip = regs->ARM_ip;
regs->ARM_ip = why;
/* 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;
}
regs->ARM_ip = ip;
return current_thread_info()->syscall;
}
| gpl-2.0 |
HaoZeke/kernel | drivers/net/dummy.c | 2112 | 5066 | /* dummy.c: a dummy net driver
The purpose of this driver is to provide a device to point a
route through, but not to actually transmit packets.
Why? If you have a machine whose only connection is an occasional
PPP/SLIP/PLIP link, you can only connect to your own hostname
when the link is up. Otherwise you have to use localhost.
This isn't very consistent.
One solution is to set up a dummy link using PPP/SLIP/PLIP,
but this seems (to me) too much overhead for too little gain.
This driver provides a small alternative. Thus you can do
[when not running slip]
ifconfig dummy slip.addr.ess.here up
[to go to slip]
ifconfig dummy down
dip whatever
This was written by looking at Donald Becker's skeleton driver
and the loopback driver. I then threw away anything that didn't
apply! Thanks to Alan Cox for the key clue on what to do with
misguided packets.
Nick Holloway, 27th May 1994
[I tweaked this explanation a little but that's all]
Alan Cox, 30th May 1994
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/init.h>
#include <linux/moduleparam.h>
#include <linux/rtnetlink.h>
#include <net/rtnetlink.h>
#include <linux/u64_stats_sync.h>
static int numdummies = 1;
/* fake multicast ability */
static void set_multicast_list(struct net_device *dev)
{
}
struct pcpu_dstats {
u64 tx_packets;
u64 tx_bytes;
struct u64_stats_sync syncp;
};
static struct rtnl_link_stats64 *dummy_get_stats64(struct net_device *dev,
struct rtnl_link_stats64 *stats)
{
int i;
for_each_possible_cpu(i) {
const struct pcpu_dstats *dstats;
u64 tbytes, tpackets;
unsigned int start;
dstats = per_cpu_ptr(dev->dstats, i);
do {
start = u64_stats_fetch_begin_bh(&dstats->syncp);
tbytes = dstats->tx_bytes;
tpackets = dstats->tx_packets;
} while (u64_stats_fetch_retry_bh(&dstats->syncp, start));
stats->tx_bytes += tbytes;
stats->tx_packets += tpackets;
}
return stats;
}
static netdev_tx_t dummy_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct pcpu_dstats *dstats = this_cpu_ptr(dev->dstats);
u64_stats_update_begin(&dstats->syncp);
dstats->tx_packets++;
dstats->tx_bytes += skb->len;
u64_stats_update_end(&dstats->syncp);
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
static int dummy_dev_init(struct net_device *dev)
{
dev->dstats = alloc_percpu(struct pcpu_dstats);
if (!dev->dstats)
return -ENOMEM;
return 0;
}
static void dummy_dev_uninit(struct net_device *dev)
{
free_percpu(dev->dstats);
}
static int dummy_change_carrier(struct net_device *dev, bool new_carrier)
{
if (new_carrier)
netif_carrier_on(dev);
else
netif_carrier_off(dev);
return 0;
}
static const struct net_device_ops dummy_netdev_ops = {
.ndo_init = dummy_dev_init,
.ndo_uninit = dummy_dev_uninit,
.ndo_start_xmit = dummy_xmit,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_rx_mode = set_multicast_list,
.ndo_set_mac_address = eth_mac_addr,
.ndo_get_stats64 = dummy_get_stats64,
.ndo_change_carrier = dummy_change_carrier,
};
static void dummy_setup(struct net_device *dev)
{
ether_setup(dev);
/* Initialize the device structure. */
dev->netdev_ops = &dummy_netdev_ops;
dev->destructor = free_netdev;
/* Fill in device structure with ethernet-generic values. */
dev->tx_queue_len = 0;
dev->flags |= IFF_NOARP;
dev->flags &= ~IFF_MULTICAST;
dev->priv_flags |= IFF_LIVE_ADDR_CHANGE;
dev->features |= NETIF_F_SG | NETIF_F_FRAGLIST | NETIF_F_TSO;
dev->features |= NETIF_F_HW_CSUM | NETIF_F_HIGHDMA | NETIF_F_LLTX;
eth_hw_addr_random(dev);
}
static int dummy_validate(struct nlattr *tb[], struct nlattr *data[])
{
if (tb[IFLA_ADDRESS]) {
if (nla_len(tb[IFLA_ADDRESS]) != ETH_ALEN)
return -EINVAL;
if (!is_valid_ether_addr(nla_data(tb[IFLA_ADDRESS])))
return -EADDRNOTAVAIL;
}
return 0;
}
static struct rtnl_link_ops dummy_link_ops __read_mostly = {
.kind = "dummy",
.setup = dummy_setup,
.validate = dummy_validate,
};
/* Number of dummy devices to be set up by this module. */
module_param(numdummies, int, 0);
MODULE_PARM_DESC(numdummies, "Number of dummy pseudo devices");
static int __init dummy_init_one(void)
{
struct net_device *dev_dummy;
int err;
dev_dummy = alloc_netdev(0, "dummy%d", dummy_setup);
if (!dev_dummy)
return -ENOMEM;
dev_dummy->rtnl_link_ops = &dummy_link_ops;
err = register_netdevice(dev_dummy);
if (err < 0)
goto err;
return 0;
err:
free_netdev(dev_dummy);
return err;
}
static int __init dummy_init_module(void)
{
int i, err = 0;
rtnl_lock();
err = __rtnl_link_register(&dummy_link_ops);
if (err < 0)
goto out;
for (i = 0; i < numdummies && !err; i++) {
err = dummy_init_one();
cond_resched();
}
if (err < 0)
__rtnl_link_unregister(&dummy_link_ops);
out:
rtnl_unlock();
return err;
}
static void __exit dummy_cleanup_module(void)
{
rtnl_link_unregister(&dummy_link_ops);
}
module_init(dummy_init_module);
module_exit(dummy_cleanup_module);
MODULE_LICENSE("GPL");
MODULE_ALIAS_RTNL_LINK("dummy");
| gpl-2.0 |
Slim80/Fulgor_Kernel_Lollipop | net/ceph/crypto.c | 3392 | 11879 |
#include <linux/ceph/ceph_debug.h>
#include <linux/err.h>
#include <linux/scatterlist.h>
#include <linux/slab.h>
#include <crypto/hash.h>
#include <linux/key-type.h>
#include <keys/ceph-type.h>
#include <linux/ceph/decode.h>
#include "crypto.h"
int ceph_crypto_key_clone(struct ceph_crypto_key *dst,
const struct ceph_crypto_key *src)
{
memcpy(dst, src, sizeof(struct ceph_crypto_key));
dst->key = kmemdup(src->key, src->len, GFP_NOFS);
if (!dst->key)
return -ENOMEM;
return 0;
}
int ceph_crypto_key_encode(struct ceph_crypto_key *key, void **p, void *end)
{
if (*p + sizeof(u16) + sizeof(key->created) +
sizeof(u16) + key->len > end)
return -ERANGE;
ceph_encode_16(p, key->type);
ceph_encode_copy(p, &key->created, sizeof(key->created));
ceph_encode_16(p, key->len);
ceph_encode_copy(p, key->key, key->len);
return 0;
}
int ceph_crypto_key_decode(struct ceph_crypto_key *key, void **p, void *end)
{
ceph_decode_need(p, end, 2*sizeof(u16) + sizeof(key->created), bad);
key->type = ceph_decode_16(p);
ceph_decode_copy(p, &key->created, sizeof(key->created));
key->len = ceph_decode_16(p);
ceph_decode_need(p, end, key->len, bad);
key->key = kmalloc(key->len, GFP_NOFS);
if (!key->key)
return -ENOMEM;
ceph_decode_copy(p, key->key, key->len);
return 0;
bad:
dout("failed to decode crypto key\n");
return -EINVAL;
}
int ceph_crypto_key_unarmor(struct ceph_crypto_key *key, const char *inkey)
{
int inlen = strlen(inkey);
int blen = inlen * 3 / 4;
void *buf, *p;
int ret;
dout("crypto_key_unarmor %s\n", inkey);
buf = kmalloc(blen, GFP_NOFS);
if (!buf)
return -ENOMEM;
blen = ceph_unarmor(buf, inkey, inkey+inlen);
if (blen < 0) {
kfree(buf);
return blen;
}
p = buf;
ret = ceph_crypto_key_decode(key, &p, p + blen);
kfree(buf);
if (ret)
return ret;
dout("crypto_key_unarmor key %p type %d len %d\n", key,
key->type, key->len);
return 0;
}
#define AES_KEY_SIZE 16
static struct crypto_blkcipher *ceph_crypto_alloc_cipher(void)
{
return crypto_alloc_blkcipher("cbc(aes)", 0, CRYPTO_ALG_ASYNC);
}
static const u8 *aes_iv = (u8 *)CEPH_AES_IV;
static int ceph_aes_encrypt(const void *key, int key_len,
void *dst, size_t *dst_len,
const void *src, size_t src_len)
{
struct scatterlist sg_in[2], sg_out[1];
struct crypto_blkcipher *tfm = ceph_crypto_alloc_cipher();
struct blkcipher_desc desc = { .tfm = tfm, .flags = 0 };
int ret;
void *iv;
int ivsize;
size_t zero_padding = (0x10 - (src_len & 0x0f));
char pad[16];
if (IS_ERR(tfm))
return PTR_ERR(tfm);
memset(pad, zero_padding, zero_padding);
*dst_len = src_len + zero_padding;
crypto_blkcipher_setkey((void *)tfm, key, key_len);
sg_init_table(sg_in, 2);
sg_set_buf(&sg_in[0], src, src_len);
sg_set_buf(&sg_in[1], pad, zero_padding);
sg_init_table(sg_out, 1);
sg_set_buf(sg_out, dst, *dst_len);
iv = crypto_blkcipher_crt(tfm)->iv;
ivsize = crypto_blkcipher_ivsize(tfm);
memcpy(iv, aes_iv, ivsize);
/*
print_hex_dump(KERN_ERR, "enc key: ", DUMP_PREFIX_NONE, 16, 1,
key, key_len, 1);
print_hex_dump(KERN_ERR, "enc src: ", DUMP_PREFIX_NONE, 16, 1,
src, src_len, 1);
print_hex_dump(KERN_ERR, "enc pad: ", DUMP_PREFIX_NONE, 16, 1,
pad, zero_padding, 1);
*/
ret = crypto_blkcipher_encrypt(&desc, sg_out, sg_in,
src_len + zero_padding);
crypto_free_blkcipher(tfm);
if (ret < 0)
pr_err("ceph_aes_crypt failed %d\n", ret);
/*
print_hex_dump(KERN_ERR, "enc out: ", DUMP_PREFIX_NONE, 16, 1,
dst, *dst_len, 1);
*/
return 0;
}
static int ceph_aes_encrypt2(const void *key, int key_len, void *dst,
size_t *dst_len,
const void *src1, size_t src1_len,
const void *src2, size_t src2_len)
{
struct scatterlist sg_in[3], sg_out[1];
struct crypto_blkcipher *tfm = ceph_crypto_alloc_cipher();
struct blkcipher_desc desc = { .tfm = tfm, .flags = 0 };
int ret;
void *iv;
int ivsize;
size_t zero_padding = (0x10 - ((src1_len + src2_len) & 0x0f));
char pad[16];
if (IS_ERR(tfm))
return PTR_ERR(tfm);
memset(pad, zero_padding, zero_padding);
*dst_len = src1_len + src2_len + zero_padding;
crypto_blkcipher_setkey((void *)tfm, key, key_len);
sg_init_table(sg_in, 3);
sg_set_buf(&sg_in[0], src1, src1_len);
sg_set_buf(&sg_in[1], src2, src2_len);
sg_set_buf(&sg_in[2], pad, zero_padding);
sg_init_table(sg_out, 1);
sg_set_buf(sg_out, dst, *dst_len);
iv = crypto_blkcipher_crt(tfm)->iv;
ivsize = crypto_blkcipher_ivsize(tfm);
memcpy(iv, aes_iv, ivsize);
/*
print_hex_dump(KERN_ERR, "enc key: ", DUMP_PREFIX_NONE, 16, 1,
key, key_len, 1);
print_hex_dump(KERN_ERR, "enc src1: ", DUMP_PREFIX_NONE, 16, 1,
src1, src1_len, 1);
print_hex_dump(KERN_ERR, "enc src2: ", DUMP_PREFIX_NONE, 16, 1,
src2, src2_len, 1);
print_hex_dump(KERN_ERR, "enc pad: ", DUMP_PREFIX_NONE, 16, 1,
pad, zero_padding, 1);
*/
ret = crypto_blkcipher_encrypt(&desc, sg_out, sg_in,
src1_len + src2_len + zero_padding);
crypto_free_blkcipher(tfm);
if (ret < 0)
pr_err("ceph_aes_crypt2 failed %d\n", ret);
/*
print_hex_dump(KERN_ERR, "enc out: ", DUMP_PREFIX_NONE, 16, 1,
dst, *dst_len, 1);
*/
return 0;
}
static int ceph_aes_decrypt(const void *key, int key_len,
void *dst, size_t *dst_len,
const void *src, size_t src_len)
{
struct scatterlist sg_in[1], sg_out[2];
struct crypto_blkcipher *tfm = ceph_crypto_alloc_cipher();
struct blkcipher_desc desc = { .tfm = tfm };
char pad[16];
void *iv;
int ivsize;
int ret;
int last_byte;
if (IS_ERR(tfm))
return PTR_ERR(tfm);
crypto_blkcipher_setkey((void *)tfm, key, key_len);
sg_init_table(sg_in, 1);
sg_init_table(sg_out, 2);
sg_set_buf(sg_in, src, src_len);
sg_set_buf(&sg_out[0], dst, *dst_len);
sg_set_buf(&sg_out[1], pad, sizeof(pad));
iv = crypto_blkcipher_crt(tfm)->iv;
ivsize = crypto_blkcipher_ivsize(tfm);
memcpy(iv, aes_iv, ivsize);
/*
print_hex_dump(KERN_ERR, "dec key: ", DUMP_PREFIX_NONE, 16, 1,
key, key_len, 1);
print_hex_dump(KERN_ERR, "dec in: ", DUMP_PREFIX_NONE, 16, 1,
src, src_len, 1);
*/
ret = crypto_blkcipher_decrypt(&desc, sg_out, sg_in, src_len);
crypto_free_blkcipher(tfm);
if (ret < 0) {
pr_err("ceph_aes_decrypt failed %d\n", ret);
return ret;
}
if (src_len <= *dst_len)
last_byte = ((char *)dst)[src_len - 1];
else
last_byte = pad[src_len - *dst_len - 1];
if (last_byte <= 16 && src_len >= last_byte) {
*dst_len = src_len - last_byte;
} else {
pr_err("ceph_aes_decrypt got bad padding %d on src len %d\n",
last_byte, (int)src_len);
return -EPERM; /* bad padding */
}
/*
print_hex_dump(KERN_ERR, "dec out: ", DUMP_PREFIX_NONE, 16, 1,
dst, *dst_len, 1);
*/
return 0;
}
static int ceph_aes_decrypt2(const void *key, int key_len,
void *dst1, size_t *dst1_len,
void *dst2, size_t *dst2_len,
const void *src, size_t src_len)
{
struct scatterlist sg_in[1], sg_out[3];
struct crypto_blkcipher *tfm = ceph_crypto_alloc_cipher();
struct blkcipher_desc desc = { .tfm = tfm };
char pad[16];
void *iv;
int ivsize;
int ret;
int last_byte;
if (IS_ERR(tfm))
return PTR_ERR(tfm);
sg_init_table(sg_in, 1);
sg_set_buf(sg_in, src, src_len);
sg_init_table(sg_out, 3);
sg_set_buf(&sg_out[0], dst1, *dst1_len);
sg_set_buf(&sg_out[1], dst2, *dst2_len);
sg_set_buf(&sg_out[2], pad, sizeof(pad));
crypto_blkcipher_setkey((void *)tfm, key, key_len);
iv = crypto_blkcipher_crt(tfm)->iv;
ivsize = crypto_blkcipher_ivsize(tfm);
memcpy(iv, aes_iv, ivsize);
/*
print_hex_dump(KERN_ERR, "dec key: ", DUMP_PREFIX_NONE, 16, 1,
key, key_len, 1);
print_hex_dump(KERN_ERR, "dec in: ", DUMP_PREFIX_NONE, 16, 1,
src, src_len, 1);
*/
ret = crypto_blkcipher_decrypt(&desc, sg_out, sg_in, src_len);
crypto_free_blkcipher(tfm);
if (ret < 0) {
pr_err("ceph_aes_decrypt failed %d\n", ret);
return ret;
}
if (src_len <= *dst1_len)
last_byte = ((char *)dst1)[src_len - 1];
else if (src_len <= *dst1_len + *dst2_len)
last_byte = ((char *)dst2)[src_len - *dst1_len - 1];
else
last_byte = pad[src_len - *dst1_len - *dst2_len - 1];
if (last_byte <= 16 && src_len >= last_byte) {
src_len -= last_byte;
} else {
pr_err("ceph_aes_decrypt got bad padding %d on src len %d\n",
last_byte, (int)src_len);
return -EPERM; /* bad padding */
}
if (src_len < *dst1_len) {
*dst1_len = src_len;
*dst2_len = 0;
} else {
*dst2_len = src_len - *dst1_len;
}
/*
print_hex_dump(KERN_ERR, "dec out1: ", DUMP_PREFIX_NONE, 16, 1,
dst1, *dst1_len, 1);
print_hex_dump(KERN_ERR, "dec out2: ", DUMP_PREFIX_NONE, 16, 1,
dst2, *dst2_len, 1);
*/
return 0;
}
int ceph_decrypt(struct ceph_crypto_key *secret, void *dst, size_t *dst_len,
const void *src, size_t src_len)
{
switch (secret->type) {
case CEPH_CRYPTO_NONE:
if (*dst_len < src_len)
return -ERANGE;
memcpy(dst, src, src_len);
*dst_len = src_len;
return 0;
case CEPH_CRYPTO_AES:
return ceph_aes_decrypt(secret->key, secret->len, dst,
dst_len, src, src_len);
default:
return -EINVAL;
}
}
int ceph_decrypt2(struct ceph_crypto_key *secret,
void *dst1, size_t *dst1_len,
void *dst2, size_t *dst2_len,
const void *src, size_t src_len)
{
size_t t;
switch (secret->type) {
case CEPH_CRYPTO_NONE:
if (*dst1_len + *dst2_len < src_len)
return -ERANGE;
t = min(*dst1_len, src_len);
memcpy(dst1, src, t);
*dst1_len = t;
src += t;
src_len -= t;
if (src_len) {
t = min(*dst2_len, src_len);
memcpy(dst2, src, t);
*dst2_len = t;
}
return 0;
case CEPH_CRYPTO_AES:
return ceph_aes_decrypt2(secret->key, secret->len,
dst1, dst1_len, dst2, dst2_len,
src, src_len);
default:
return -EINVAL;
}
}
int ceph_encrypt(struct ceph_crypto_key *secret, void *dst, size_t *dst_len,
const void *src, size_t src_len)
{
switch (secret->type) {
case CEPH_CRYPTO_NONE:
if (*dst_len < src_len)
return -ERANGE;
memcpy(dst, src, src_len);
*dst_len = src_len;
return 0;
case CEPH_CRYPTO_AES:
return ceph_aes_encrypt(secret->key, secret->len, dst,
dst_len, src, src_len);
default:
return -EINVAL;
}
}
int ceph_encrypt2(struct ceph_crypto_key *secret, void *dst, size_t *dst_len,
const void *src1, size_t src1_len,
const void *src2, size_t src2_len)
{
switch (secret->type) {
case CEPH_CRYPTO_NONE:
if (*dst_len < src1_len + src2_len)
return -ERANGE;
memcpy(dst, src1, src1_len);
memcpy(dst + src1_len, src2, src2_len);
*dst_len = src1_len + src2_len;
return 0;
case CEPH_CRYPTO_AES:
return ceph_aes_encrypt2(secret->key, secret->len, dst, dst_len,
src1, src1_len, src2, src2_len);
default:
return -EINVAL;
}
}
int ceph_key_instantiate(struct key *key, const void *data, size_t datalen)
{
struct ceph_crypto_key *ckey;
int ret;
void *p;
ret = -EINVAL;
if (datalen <= 0 || datalen > 32767 || !data)
goto err;
ret = key_payload_reserve(key, datalen);
if (ret < 0)
goto err;
ret = -ENOMEM;
ckey = kmalloc(sizeof(*ckey), GFP_KERNEL);
if (!ckey)
goto err;
/* TODO ceph_crypto_key_decode should really take const input */
p = (void *)data;
ret = ceph_crypto_key_decode(ckey, &p, (char*)data+datalen);
if (ret < 0)
goto err_ckey;
key->payload.data = ckey;
return 0;
err_ckey:
kfree(ckey);
err:
return ret;
}
int ceph_key_match(const struct key *key, const void *description)
{
return strcmp(key->description, description) == 0;
}
void ceph_key_destroy(struct key *key) {
struct ceph_crypto_key *ckey = key->payload.data;
ceph_crypto_key_destroy(ckey);
}
struct key_type key_type_ceph = {
.name = "ceph",
.instantiate = ceph_key_instantiate,
.match = ceph_key_match,
.destroy = ceph_key_destroy,
};
int ceph_crypto_init(void) {
return register_key_type(&key_type_ceph);
}
void ceph_crypto_shutdown(void) {
unregister_key_type(&key_type_ceph);
}
| gpl-2.0 |
gimmeitorilltell/slim_kernel_samsung_msm8660 | net/ipv6/netfilter/ip6table_filter.c | 4160 | 3022 | /*
* This is the 1999 rewrite of IP Firewalling, aiming for kernel 2.3.x.
*
* Copyright (C) 1999 Paul `Rusty' Russell & Michael J. Neuling
* Copyright (C) 2000-2004 Netfilter Core Team <coreteam@netfilter.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/netfilter_ipv6/ip6_tables.h>
#include <linux/slab.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Netfilter Core Team <coreteam@netfilter.org>");
MODULE_DESCRIPTION("ip6tables filter table");
#define FILTER_VALID_HOOKS ((1 << NF_INET_LOCAL_IN) | \
(1 << NF_INET_FORWARD) | \
(1 << NF_INET_LOCAL_OUT))
static const struct xt_table packet_filter = {
.name = "filter",
.valid_hooks = FILTER_VALID_HOOKS,
.me = THIS_MODULE,
.af = NFPROTO_IPV6,
.priority = NF_IP6_PRI_FILTER,
};
/* The work comes in here from netfilter.c. */
static unsigned int
ip6table_filter_hook(unsigned int hook, struct sk_buff *skb,
const struct net_device *in, const struct net_device *out,
int (*okfn)(struct sk_buff *))
{
const struct net *net = dev_net((in != NULL) ? in : out);
return ip6t_do_table(skb, hook, in, out, net->ipv6.ip6table_filter);
}
static struct nf_hook_ops *filter_ops __read_mostly;
/* Default to forward because I got too much mail already. */
static int forward = NF_ACCEPT;
module_param(forward, bool, 0000);
static int __net_init ip6table_filter_net_init(struct net *net)
{
struct ip6t_replace *repl;
repl = ip6t_alloc_initial_table(&packet_filter);
if (repl == NULL)
return -ENOMEM;
/* Entry 1 is the FORWARD hook */
((struct ip6t_standard *)repl->entries)[1].target.verdict =
-forward - 1;
net->ipv6.ip6table_filter =
ip6t_register_table(net, &packet_filter, repl);
kfree(repl);
if (IS_ERR(net->ipv6.ip6table_filter))
return PTR_ERR(net->ipv6.ip6table_filter);
return 0;
}
static void __net_exit ip6table_filter_net_exit(struct net *net)
{
ip6t_unregister_table(net, net->ipv6.ip6table_filter);
}
static struct pernet_operations ip6table_filter_net_ops = {
.init = ip6table_filter_net_init,
.exit = ip6table_filter_net_exit,
};
static int __init ip6table_filter_init(void)
{
int ret;
if (forward < 0 || forward > NF_MAX_VERDICT) {
pr_err("iptables forward must be 0 or 1\n");
return -EINVAL;
}
ret = register_pernet_subsys(&ip6table_filter_net_ops);
if (ret < 0)
return ret;
/* Register hooks */
filter_ops = xt_hook_link(&packet_filter, ip6table_filter_hook);
if (IS_ERR(filter_ops)) {
ret = PTR_ERR(filter_ops);
goto cleanup_table;
}
return ret;
cleanup_table:
unregister_pernet_subsys(&ip6table_filter_net_ops);
return ret;
}
static void __exit ip6table_filter_fini(void)
{
xt_hook_unlink(&packet_filter, filter_ops);
unregister_pernet_subsys(&ip6table_filter_net_ops);
}
module_init(ip6table_filter_init);
module_exit(ip6table_filter_fini);
| gpl-2.0 |
akw28888/msm | arch/sh/boards/mach-se/7724/setup.c | 4416 | 22670 | /*
* linux/arch/sh/boards/se/7724/setup.c
*
* Copyright (C) 2009 Renesas Solutions Corp.
*
* Kuninori Morimoto <morimoto.kuninori@renesas.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/init.h>
#include <linux/device.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/mmc/host.h>
#include <linux/mmc/sh_mobile_sdhi.h>
#include <linux/mtd/physmap.h>
#include <linux/delay.h>
#include <linux/smc91x.h>
#include <linux/gpio.h>
#include <linux/input.h>
#include <linux/input/sh_keysc.h>
#include <linux/usb/r8a66597.h>
#include <linux/sh_eth.h>
#include <linux/videodev2.h>
#include <video/sh_mobile_lcdc.h>
#include <media/sh_mobile_ceu.h>
#include <sound/sh_fsi.h>
#include <asm/io.h>
#include <asm/heartbeat.h>
#include <asm/clock.h>
#include <asm/suspend.h>
#include <cpu/sh7724.h>
#include <mach-se/mach/se7724.h>
/*
* SWx 1234 5678
* ------------------------------------
* SW31 : 1001 1100 : default
* SW32 : 0111 1111 : use on board flash
*
* SW41 : abxx xxxx -> a = 0 : Analog monitor
* 1 : Digital monitor
* b = 0 : VGA
* 1 : 720p
*/
/*
* about 720p
*
* When you use 1280 x 720 lcdc output,
* you should change OSC6 lcdc clock from 25.175MHz to 74.25MHz,
* and change SW41 to use 720p
*/
/*
* about sound
*
* This setup.c supports FSI slave mode.
* Please change J20, J21, J22 pin to 1-2 connection.
*/
/* Heartbeat */
static struct resource heartbeat_resource = {
.start = PA_LED,
.end = PA_LED,
.flags = IORESOURCE_MEM | IORESOURCE_MEM_16BIT,
};
static struct platform_device heartbeat_device = {
.name = "heartbeat",
.id = -1,
.num_resources = 1,
.resource = &heartbeat_resource,
};
/* LAN91C111 */
static struct smc91x_platdata smc91x_info = {
.flags = SMC91X_USE_16BIT | SMC91X_NOWAIT,
};
static struct resource smc91x_eth_resources[] = {
[0] = {
.name = "SMC91C111" ,
.start = 0x1a300300,
.end = 0x1a30030f,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ0_SMC,
.flags = IORESOURCE_IRQ | IORESOURCE_IRQ_HIGHLEVEL,
},
};
static struct platform_device smc91x_eth_device = {
.name = "smc91x",
.num_resources = ARRAY_SIZE(smc91x_eth_resources),
.resource = smc91x_eth_resources,
.dev = {
.platform_data = &smc91x_info,
},
};
/* MTD */
static struct mtd_partition nor_flash_partitions[] = {
{
.name = "uboot",
.offset = 0,
.size = (1 * 1024 * 1024),
.mask_flags = MTD_WRITEABLE, /* Read-only */
}, {
.name = "kernel",
.offset = MTDPART_OFS_APPEND,
.size = (2 * 1024 * 1024),
}, {
.name = "free-area",
.offset = MTDPART_OFS_APPEND,
.size = MTDPART_SIZ_FULL,
},
};
static struct physmap_flash_data nor_flash_data = {
.width = 2,
.parts = nor_flash_partitions,
.nr_parts = ARRAY_SIZE(nor_flash_partitions),
};
static struct resource nor_flash_resources[] = {
[0] = {
.name = "NOR Flash",
.start = 0x00000000,
.end = 0x01ffffff,
.flags = IORESOURCE_MEM,
}
};
static struct platform_device nor_flash_device = {
.name = "physmap-flash",
.resource = nor_flash_resources,
.num_resources = ARRAY_SIZE(nor_flash_resources),
.dev = {
.platform_data = &nor_flash_data,
},
};
/* LCDC */
static const struct fb_videomode lcdc_720p_modes[] = {
{
.name = "LB070WV1",
.sync = 0, /* hsync and vsync are active low */
.xres = 1280,
.yres = 720,
.left_margin = 220,
.right_margin = 110,
.hsync_len = 40,
.upper_margin = 20,
.lower_margin = 5,
.vsync_len = 5,
},
};
static const struct fb_videomode lcdc_vga_modes[] = {
{
.name = "LB070WV1",
.sync = 0, /* hsync and vsync are active low */
.xres = 640,
.yres = 480,
.left_margin = 105,
.right_margin = 50,
.hsync_len = 96,
.upper_margin = 33,
.lower_margin = 10,
.vsync_len = 2,
},
};
static struct sh_mobile_lcdc_info lcdc_info = {
.clock_source = LCDC_CLK_EXTERNAL,
.ch[0] = {
.chan = LCDC_CHAN_MAINLCD,
.fourcc = V4L2_PIX_FMT_RGB565,
.clock_divider = 1,
.panel_cfg = { /* 7.0 inch */
.width = 152,
.height = 91,
},
}
};
static struct resource lcdc_resources[] = {
[0] = {
.name = "LCDC",
.start = 0xfe940000,
.end = 0xfe942fff,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 106,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device lcdc_device = {
.name = "sh_mobile_lcdc_fb",
.num_resources = ARRAY_SIZE(lcdc_resources),
.resource = lcdc_resources,
.dev = {
.platform_data = &lcdc_info,
},
};
/* CEU0 */
static struct sh_mobile_ceu_info sh_mobile_ceu0_info = {
.flags = SH_CEU_FLAG_USE_8BIT_BUS,
};
static struct resource ceu0_resources[] = {
[0] = {
.name = "CEU0",
.start = 0xfe910000,
.end = 0xfe91009f,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 52,
.flags = IORESOURCE_IRQ,
},
[2] = {
/* place holder for contiguous memory */
},
};
static struct platform_device ceu0_device = {
.name = "sh_mobile_ceu",
.id = 0, /* "ceu0" clock */
.num_resources = ARRAY_SIZE(ceu0_resources),
.resource = ceu0_resources,
.dev = {
.platform_data = &sh_mobile_ceu0_info,
},
};
/* CEU1 */
static struct sh_mobile_ceu_info sh_mobile_ceu1_info = {
.flags = SH_CEU_FLAG_USE_8BIT_BUS,
};
static struct resource ceu1_resources[] = {
[0] = {
.name = "CEU1",
.start = 0xfe914000,
.end = 0xfe91409f,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 63,
.flags = IORESOURCE_IRQ,
},
[2] = {
/* place holder for contiguous memory */
},
};
static struct platform_device ceu1_device = {
.name = "sh_mobile_ceu",
.id = 1, /* "ceu1" clock */
.num_resources = ARRAY_SIZE(ceu1_resources),
.resource = ceu1_resources,
.dev = {
.platform_data = &sh_mobile_ceu1_info,
},
};
/* FSI */
/* change J20, J21, J22 pin to 1-2 connection to use slave mode */
static struct sh_fsi_platform_info fsi_info = {
.port_a = {
.flags = SH_FSI_BRS_INV,
},
};
static struct resource fsi_resources[] = {
[0] = {
.name = "FSI",
.start = 0xFE3C0000,
.end = 0xFE3C021d,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 108,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device fsi_device = {
.name = "sh_fsi",
.id = 0,
.num_resources = ARRAY_SIZE(fsi_resources),
.resource = fsi_resources,
.dev = {
.platform_data = &fsi_info,
},
};
static struct fsi_ak4642_info fsi_ak4642_info = {
.name = "AK4642",
.card = "FSIA-AK4642",
.cpu_dai = "fsia-dai",
.codec = "ak4642-codec.0-0012",
.platform = "sh_fsi.0",
.id = FSI_PORT_A,
};
static struct platform_device fsi_ak4642_device = {
.name = "fsi-ak4642-audio",
.dev = {
.platform_data = &fsi_ak4642_info,
},
};
/* KEYSC in SoC (Needs SW33-2 set to ON) */
static struct sh_keysc_info keysc_info = {
.mode = SH_KEYSC_MODE_1,
.scan_timing = 3,
.delay = 50,
.keycodes = {
KEY_1, KEY_2, KEY_3, KEY_4, KEY_5,
KEY_6, KEY_7, KEY_8, KEY_9, KEY_A,
KEY_B, KEY_C, KEY_D, KEY_E, KEY_F,
KEY_G, KEY_H, KEY_I, KEY_K, KEY_L,
KEY_M, KEY_N, KEY_O, KEY_P, KEY_Q,
KEY_R, KEY_S, KEY_T, KEY_U, KEY_V,
},
};
static struct resource keysc_resources[] = {
[0] = {
.name = "KEYSC",
.start = 0x044b0000,
.end = 0x044b000f,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 79,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device keysc_device = {
.name = "sh_keysc",
.id = 0, /* "keysc0" clock */
.num_resources = ARRAY_SIZE(keysc_resources),
.resource = keysc_resources,
.dev = {
.platform_data = &keysc_info,
},
};
/* SH Eth */
static struct resource sh_eth_resources[] = {
[0] = {
.start = SH_ETH_ADDR,
.end = SH_ETH_ADDR + 0x1FC,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 91,
.flags = IORESOURCE_IRQ | IORESOURCE_IRQ_HIGHLEVEL,
},
};
static struct sh_eth_plat_data sh_eth_plat = {
.phy = 0x1f, /* SMSC LAN8187 */
.edmac_endian = EDMAC_LITTLE_ENDIAN,
};
static struct platform_device sh_eth_device = {
.name = "sh-eth",
.id = 0,
.dev = {
.platform_data = &sh_eth_plat,
},
.num_resources = ARRAY_SIZE(sh_eth_resources),
.resource = sh_eth_resources,
};
static struct r8a66597_platdata sh7724_usb0_host_data = {
.on_chip = 1,
};
static struct resource sh7724_usb0_host_resources[] = {
[0] = {
.start = 0xa4d80000,
.end = 0xa4d80124 - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 65,
.end = 65,
.flags = IORESOURCE_IRQ | IRQF_TRIGGER_LOW,
},
};
static struct platform_device sh7724_usb0_host_device = {
.name = "r8a66597_hcd",
.id = 0,
.dev = {
.dma_mask = NULL, /* not use dma */
.coherent_dma_mask = 0xffffffff,
.platform_data = &sh7724_usb0_host_data,
},
.num_resources = ARRAY_SIZE(sh7724_usb0_host_resources),
.resource = sh7724_usb0_host_resources,
};
static struct r8a66597_platdata sh7724_usb1_gadget_data = {
.on_chip = 1,
};
static struct resource sh7724_usb1_gadget_resources[] = {
[0] = {
.start = 0xa4d90000,
.end = 0xa4d90123,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 66,
.end = 66,
.flags = IORESOURCE_IRQ | IRQF_TRIGGER_LOW,
},
};
static struct platform_device sh7724_usb1_gadget_device = {
.name = "r8a66597_udc",
.id = 1, /* USB1 */
.dev = {
.dma_mask = NULL, /* not use dma */
.coherent_dma_mask = 0xffffffff,
.platform_data = &sh7724_usb1_gadget_data,
},
.num_resources = ARRAY_SIZE(sh7724_usb1_gadget_resources),
.resource = sh7724_usb1_gadget_resources,
};
static struct resource sdhi0_cn7_resources[] = {
[0] = {
.name = "SDHI0",
.start = 0x04ce0000,
.end = 0x04ce00ff,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 100,
.flags = IORESOURCE_IRQ,
},
};
static struct sh_mobile_sdhi_info sh7724_sdhi0_data = {
.dma_slave_tx = SHDMA_SLAVE_SDHI0_TX,
.dma_slave_rx = SHDMA_SLAVE_SDHI0_RX,
.tmio_caps = MMC_CAP_SDIO_IRQ,
};
static struct platform_device sdhi0_cn7_device = {
.name = "sh_mobile_sdhi",
.id = 0,
.num_resources = ARRAY_SIZE(sdhi0_cn7_resources),
.resource = sdhi0_cn7_resources,
.dev = {
.platform_data = &sh7724_sdhi0_data,
},
};
static struct resource sdhi1_cn8_resources[] = {
[0] = {
.name = "SDHI1",
.start = 0x04cf0000,
.end = 0x04cf00ff,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 23,
.flags = IORESOURCE_IRQ,
},
};
static struct sh_mobile_sdhi_info sh7724_sdhi1_data = {
.dma_slave_tx = SHDMA_SLAVE_SDHI1_TX,
.dma_slave_rx = SHDMA_SLAVE_SDHI1_RX,
.tmio_caps = MMC_CAP_SDIO_IRQ,
};
static struct platform_device sdhi1_cn8_device = {
.name = "sh_mobile_sdhi",
.id = 1,
.num_resources = ARRAY_SIZE(sdhi1_cn8_resources),
.resource = sdhi1_cn8_resources,
.dev = {
.platform_data = &sh7724_sdhi1_data,
},
};
/* IrDA */
static struct resource irda_resources[] = {
[0] = {
.name = "IrDA",
.start = 0xA45D0000,
.end = 0xA45D0049,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 20,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device irda_device = {
.name = "sh_sir",
.num_resources = ARRAY_SIZE(irda_resources),
.resource = irda_resources,
};
#include <media/ak881x.h>
#include <media/sh_vou.h>
static struct ak881x_pdata ak881x_pdata = {
.flags = AK881X_IF_MODE_SLAVE,
};
static struct i2c_board_info ak8813 = {
/* With open J18 jumper address is 0x21 */
I2C_BOARD_INFO("ak8813", 0x20),
.platform_data = &ak881x_pdata,
};
static struct sh_vou_pdata sh_vou_pdata = {
.bus_fmt = SH_VOU_BUS_8BIT,
.flags = SH_VOU_HSYNC_LOW | SH_VOU_VSYNC_LOW,
.board_info = &ak8813,
.i2c_adap = 0,
};
static struct resource sh_vou_resources[] = {
[0] = {
.start = 0xfe960000,
.end = 0xfe962043,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 55,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device vou_device = {
.name = "sh-vou",
.id = -1,
.num_resources = ARRAY_SIZE(sh_vou_resources),
.resource = sh_vou_resources,
.dev = {
.platform_data = &sh_vou_pdata,
},
};
static struct platform_device *ms7724se_devices[] __initdata = {
&heartbeat_device,
&smc91x_eth_device,
&lcdc_device,
&nor_flash_device,
&ceu0_device,
&ceu1_device,
&keysc_device,
&sh_eth_device,
&sh7724_usb0_host_device,
&sh7724_usb1_gadget_device,
&fsi_device,
&fsi_ak4642_device,
&sdhi0_cn7_device,
&sdhi1_cn8_device,
&irda_device,
&vou_device,
};
/* I2C device */
static struct i2c_board_info i2c0_devices[] = {
{
I2C_BOARD_INFO("ak4642", 0x12),
},
};
#define EEPROM_OP 0xBA206000
#define EEPROM_ADR 0xBA206004
#define EEPROM_DATA 0xBA20600C
#define EEPROM_STAT 0xBA206010
#define EEPROM_STRT 0xBA206014
static int __init sh_eth_is_eeprom_ready(void)
{
int t = 10000;
while (t--) {
if (!__raw_readw(EEPROM_STAT))
return 1;
udelay(1);
}
printk(KERN_ERR "ms7724se can not access to eeprom\n");
return 0;
}
static void __init sh_eth_init(void)
{
int i;
u16 mac;
/* check EEPROM status */
if (!sh_eth_is_eeprom_ready())
return;
/* read MAC addr from EEPROM */
for (i = 0 ; i < 3 ; i++) {
__raw_writew(0x0, EEPROM_OP); /* read */
__raw_writew(i*2, EEPROM_ADR);
__raw_writew(0x1, EEPROM_STRT);
if (!sh_eth_is_eeprom_ready())
return;
mac = __raw_readw(EEPROM_DATA);
sh_eth_plat.mac_addr[i << 1] = mac & 0xff;
sh_eth_plat.mac_addr[(i << 1) + 1] = mac >> 8;
}
}
#define SW4140 0xBA201000
#define FPGA_OUT 0xBA200400
#define PORT_HIZA 0xA4050158
#define PORT_MSELCRB 0xA4050182
#define SW41_A 0x0100
#define SW41_B 0x0200
#define SW41_C 0x0400
#define SW41_D 0x0800
#define SW41_E 0x1000
#define SW41_F 0x2000
#define SW41_G 0x4000
#define SW41_H 0x8000
extern char ms7724se_sdram_enter_start;
extern char ms7724se_sdram_enter_end;
extern char ms7724se_sdram_leave_start;
extern char ms7724se_sdram_leave_end;
static int __init arch_setup(void)
{
/* enable I2C device */
i2c_register_board_info(0, i2c0_devices,
ARRAY_SIZE(i2c0_devices));
return 0;
}
arch_initcall(arch_setup);
static int __init devices_setup(void)
{
u16 sw = __raw_readw(SW4140); /* select camera, monitor */
struct clk *clk;
u16 fpga_out;
/* register board specific self-refresh code */
sh_mobile_register_self_refresh(SUSP_SH_STANDBY | SUSP_SH_SF |
SUSP_SH_RSTANDBY,
&ms7724se_sdram_enter_start,
&ms7724se_sdram_enter_end,
&ms7724se_sdram_leave_start,
&ms7724se_sdram_leave_end);
/* Reset Release */
fpga_out = __raw_readw(FPGA_OUT);
/* bit4: NTSC_PDN, bit5: NTSC_RESET */
fpga_out &= ~((1 << 1) | /* LAN */
(1 << 4) | /* AK8813 PDN */
(1 << 5) | /* AK8813 RESET */
(1 << 6) | /* VIDEO DAC */
(1 << 7) | /* AK4643 */
(1 << 8) | /* IrDA */
(1 << 12) | /* USB0 */
(1 << 14)); /* RMII */
__raw_writew(fpga_out | (1 << 4), FPGA_OUT);
udelay(10);
/* AK8813 RESET */
__raw_writew(fpga_out | (1 << 5), FPGA_OUT);
udelay(10);
__raw_writew(fpga_out, FPGA_OUT);
/* turn on USB clocks, use external clock */
__raw_writew((__raw_readw(PORT_MSELCRB) & ~0xc000) | 0x8000, PORT_MSELCRB);
/* Let LED9 show STATUS2 */
gpio_request(GPIO_FN_STATUS2, NULL);
/* Lit LED10 show STATUS0 */
gpio_request(GPIO_FN_STATUS0, NULL);
/* Lit LED11 show PDSTATUS */
gpio_request(GPIO_FN_PDSTATUS, NULL);
/* enable USB0 port */
__raw_writew(0x0600, 0xa40501d4);
/* enable USB1 port */
__raw_writew(0x0600, 0xa4050192);
/* enable IRQ 0,1,2 */
gpio_request(GPIO_FN_INTC_IRQ0, NULL);
gpio_request(GPIO_FN_INTC_IRQ1, NULL);
gpio_request(GPIO_FN_INTC_IRQ2, NULL);
/* enable SCIFA3 */
gpio_request(GPIO_FN_SCIF3_I_SCK, NULL);
gpio_request(GPIO_FN_SCIF3_I_RXD, NULL);
gpio_request(GPIO_FN_SCIF3_I_TXD, NULL);
gpio_request(GPIO_FN_SCIF3_I_CTS, NULL);
gpio_request(GPIO_FN_SCIF3_I_RTS, NULL);
/* enable LCDC */
gpio_request(GPIO_FN_LCDD23, NULL);
gpio_request(GPIO_FN_LCDD22, NULL);
gpio_request(GPIO_FN_LCDD21, NULL);
gpio_request(GPIO_FN_LCDD20, NULL);
gpio_request(GPIO_FN_LCDD19, NULL);
gpio_request(GPIO_FN_LCDD18, NULL);
gpio_request(GPIO_FN_LCDD17, NULL);
gpio_request(GPIO_FN_LCDD16, NULL);
gpio_request(GPIO_FN_LCDD15, NULL);
gpio_request(GPIO_FN_LCDD14, NULL);
gpio_request(GPIO_FN_LCDD13, NULL);
gpio_request(GPIO_FN_LCDD12, NULL);
gpio_request(GPIO_FN_LCDD11, NULL);
gpio_request(GPIO_FN_LCDD10, NULL);
gpio_request(GPIO_FN_LCDD9, NULL);
gpio_request(GPIO_FN_LCDD8, NULL);
gpio_request(GPIO_FN_LCDD7, NULL);
gpio_request(GPIO_FN_LCDD6, NULL);
gpio_request(GPIO_FN_LCDD5, NULL);
gpio_request(GPIO_FN_LCDD4, NULL);
gpio_request(GPIO_FN_LCDD3, NULL);
gpio_request(GPIO_FN_LCDD2, NULL);
gpio_request(GPIO_FN_LCDD1, NULL);
gpio_request(GPIO_FN_LCDD0, NULL);
gpio_request(GPIO_FN_LCDDISP, NULL);
gpio_request(GPIO_FN_LCDHSYN, NULL);
gpio_request(GPIO_FN_LCDDCK, NULL);
gpio_request(GPIO_FN_LCDVSYN, NULL);
gpio_request(GPIO_FN_LCDDON, NULL);
gpio_request(GPIO_FN_LCDVEPWC, NULL);
gpio_request(GPIO_FN_LCDVCPWC, NULL);
gpio_request(GPIO_FN_LCDRD, NULL);
gpio_request(GPIO_FN_LCDLCLK, NULL);
__raw_writew((__raw_readw(PORT_HIZA) & ~0x0001), PORT_HIZA);
/* enable CEU0 */
gpio_request(GPIO_FN_VIO0_D15, NULL);
gpio_request(GPIO_FN_VIO0_D14, NULL);
gpio_request(GPIO_FN_VIO0_D13, NULL);
gpio_request(GPIO_FN_VIO0_D12, NULL);
gpio_request(GPIO_FN_VIO0_D11, NULL);
gpio_request(GPIO_FN_VIO0_D10, NULL);
gpio_request(GPIO_FN_VIO0_D9, NULL);
gpio_request(GPIO_FN_VIO0_D8, NULL);
gpio_request(GPIO_FN_VIO0_D7, NULL);
gpio_request(GPIO_FN_VIO0_D6, NULL);
gpio_request(GPIO_FN_VIO0_D5, NULL);
gpio_request(GPIO_FN_VIO0_D4, NULL);
gpio_request(GPIO_FN_VIO0_D3, NULL);
gpio_request(GPIO_FN_VIO0_D2, NULL);
gpio_request(GPIO_FN_VIO0_D1, NULL);
gpio_request(GPIO_FN_VIO0_D0, NULL);
gpio_request(GPIO_FN_VIO0_VD, NULL);
gpio_request(GPIO_FN_VIO0_CLK, NULL);
gpio_request(GPIO_FN_VIO0_FLD, NULL);
gpio_request(GPIO_FN_VIO0_HD, NULL);
platform_resource_setup_memory(&ceu0_device, "ceu0", 4 << 20);
/* enable CEU1 */
gpio_request(GPIO_FN_VIO1_D7, NULL);
gpio_request(GPIO_FN_VIO1_D6, NULL);
gpio_request(GPIO_FN_VIO1_D5, NULL);
gpio_request(GPIO_FN_VIO1_D4, NULL);
gpio_request(GPIO_FN_VIO1_D3, NULL);
gpio_request(GPIO_FN_VIO1_D2, NULL);
gpio_request(GPIO_FN_VIO1_D1, NULL);
gpio_request(GPIO_FN_VIO1_D0, NULL);
gpio_request(GPIO_FN_VIO1_FLD, NULL);
gpio_request(GPIO_FN_VIO1_HD, NULL);
gpio_request(GPIO_FN_VIO1_VD, NULL);
gpio_request(GPIO_FN_VIO1_CLK, NULL);
platform_resource_setup_memory(&ceu1_device, "ceu1", 4 << 20);
/* KEYSC */
gpio_request(GPIO_FN_KEYOUT5_IN5, NULL);
gpio_request(GPIO_FN_KEYOUT4_IN6, NULL);
gpio_request(GPIO_FN_KEYIN4, NULL);
gpio_request(GPIO_FN_KEYIN3, NULL);
gpio_request(GPIO_FN_KEYIN2, NULL);
gpio_request(GPIO_FN_KEYIN1, NULL);
gpio_request(GPIO_FN_KEYIN0, NULL);
gpio_request(GPIO_FN_KEYOUT3, NULL);
gpio_request(GPIO_FN_KEYOUT2, NULL);
gpio_request(GPIO_FN_KEYOUT1, NULL);
gpio_request(GPIO_FN_KEYOUT0, NULL);
/* enable FSI */
gpio_request(GPIO_FN_FSIMCKA, NULL);
gpio_request(GPIO_FN_FSIIASD, NULL);
gpio_request(GPIO_FN_FSIOASD, NULL);
gpio_request(GPIO_FN_FSIIABCK, NULL);
gpio_request(GPIO_FN_FSIIALRCK, NULL);
gpio_request(GPIO_FN_FSIOABCK, NULL);
gpio_request(GPIO_FN_FSIOALRCK, NULL);
gpio_request(GPIO_FN_CLKAUDIOAO, NULL);
/* set SPU2 clock to 83.4 MHz */
clk = clk_get(NULL, "spu_clk");
if (!IS_ERR(clk)) {
clk_set_rate(clk, clk_round_rate(clk, 83333333));
clk_put(clk);
}
/* change parent of FSI A */
clk = clk_get(NULL, "fsia_clk");
if (!IS_ERR(clk)) {
/* 48kHz dummy clock was used to make sure 1/1 divide */
clk_set_rate(&sh7724_fsimcka_clk, 48000);
clk_set_parent(clk, &sh7724_fsimcka_clk);
clk_set_rate(clk, 48000);
clk_put(clk);
}
/* SDHI0 connected to cn7 */
gpio_request(GPIO_FN_SDHI0CD, NULL);
gpio_request(GPIO_FN_SDHI0WP, NULL);
gpio_request(GPIO_FN_SDHI0D3, NULL);
gpio_request(GPIO_FN_SDHI0D2, NULL);
gpio_request(GPIO_FN_SDHI0D1, NULL);
gpio_request(GPIO_FN_SDHI0D0, NULL);
gpio_request(GPIO_FN_SDHI0CMD, NULL);
gpio_request(GPIO_FN_SDHI0CLK, NULL);
/* SDHI1 connected to cn8 */
gpio_request(GPIO_FN_SDHI1CD, NULL);
gpio_request(GPIO_FN_SDHI1WP, NULL);
gpio_request(GPIO_FN_SDHI1D3, NULL);
gpio_request(GPIO_FN_SDHI1D2, NULL);
gpio_request(GPIO_FN_SDHI1D1, NULL);
gpio_request(GPIO_FN_SDHI1D0, NULL);
gpio_request(GPIO_FN_SDHI1CMD, NULL);
gpio_request(GPIO_FN_SDHI1CLK, NULL);
/* enable IrDA */
gpio_request(GPIO_FN_IRDA_OUT, NULL);
gpio_request(GPIO_FN_IRDA_IN, NULL);
/*
* enable SH-Eth
*
* please remove J33 pin from your board !!
*
* ms7724 board should not use GPIO_FN_LNKSTA pin
* So, This time PTX5 is set to input pin
*/
gpio_request(GPIO_FN_RMII_RXD0, NULL);
gpio_request(GPIO_FN_RMII_RXD1, NULL);
gpio_request(GPIO_FN_RMII_TXD0, NULL);
gpio_request(GPIO_FN_RMII_TXD1, NULL);
gpio_request(GPIO_FN_RMII_REF_CLK, NULL);
gpio_request(GPIO_FN_RMII_TX_EN, NULL);
gpio_request(GPIO_FN_RMII_RX_ER, NULL);
gpio_request(GPIO_FN_RMII_CRS_DV, NULL);
gpio_request(GPIO_FN_MDIO, NULL);
gpio_request(GPIO_FN_MDC, NULL);
gpio_request(GPIO_PTX5, NULL);
gpio_direction_input(GPIO_PTX5);
sh_eth_init();
if (sw & SW41_B) {
/* 720p */
lcdc_info.ch[0].lcd_modes = lcdc_720p_modes;
lcdc_info.ch[0].num_modes = ARRAY_SIZE(lcdc_720p_modes);
} else {
/* VGA */
lcdc_info.ch[0].lcd_modes = lcdc_vga_modes;
lcdc_info.ch[0].num_modes = ARRAY_SIZE(lcdc_vga_modes);
}
if (sw & SW41_A) {
/* Digital monitor */
lcdc_info.ch[0].interface_type = RGB18;
lcdc_info.ch[0].flags = 0;
} else {
/* Analog monitor */
lcdc_info.ch[0].interface_type = RGB24;
lcdc_info.ch[0].flags = LCDC_FLAGS_DWPOL;
}
/* VOU */
gpio_request(GPIO_FN_DV_D15, NULL);
gpio_request(GPIO_FN_DV_D14, NULL);
gpio_request(GPIO_FN_DV_D13, NULL);
gpio_request(GPIO_FN_DV_D12, NULL);
gpio_request(GPIO_FN_DV_D11, NULL);
gpio_request(GPIO_FN_DV_D10, NULL);
gpio_request(GPIO_FN_DV_D9, NULL);
gpio_request(GPIO_FN_DV_D8, NULL);
gpio_request(GPIO_FN_DV_CLKI, NULL);
gpio_request(GPIO_FN_DV_CLK, NULL);
gpio_request(GPIO_FN_DV_VSYNC, NULL);
gpio_request(GPIO_FN_DV_HSYNC, NULL);
return platform_add_devices(ms7724se_devices,
ARRAY_SIZE(ms7724se_devices));
}
device_initcall(devices_setup);
static struct sh_machine_vector mv_ms7724se __initmv = {
.mv_name = "ms7724se",
.mv_init_irq = init_se7724_IRQ,
.mv_nr_irqs = SE7724_FPGA_IRQ_BASE + SE7724_FPGA_IRQ_NR,
};
| gpl-2.0 |
iamthedarkone/Nexus-S-Kernel | arch/x86/crypto/crc32c-intel.c | 4928 | 4975 | /*
* Using hardware provided CRC32 instruction to accelerate the CRC32 disposal.
* CRC32C polynomial:0x1EDC6F41(BE)/0x82F63B78(LE)
* CRC32 is a new instruction in Intel SSE4.2, the reference can be found at:
* http://www.intel.com/products/processor/manuals/
* Intel(R) 64 and IA-32 Architectures Software Developer's Manual
* Volume 2A: Instruction Set Reference, A-M
*
* Copyright (C) 2008 Intel Corporation
* Authors: Austin Zhang <austin_zhang@linux.intel.com>
* Kent Liu <kent.liu@intel.com>
*
* 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/init.h>
#include <linux/module.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <crypto/internal/hash.h>
#include <asm/cpufeature.h>
#define CHKSUM_BLOCK_SIZE 1
#define CHKSUM_DIGEST_SIZE 4
#define SCALE_F sizeof(unsigned long)
#ifdef CONFIG_X86_64
#define REX_PRE "0x48, "
#else
#define REX_PRE
#endif
static u32 crc32c_intel_le_hw_byte(u32 crc, unsigned char const *data, size_t length)
{
while (length--) {
__asm__ __volatile__(
".byte 0xf2, 0xf, 0x38, 0xf0, 0xf1"
:"=S"(crc)
:"0"(crc), "c"(*data)
);
data++;
}
return crc;
}
static u32 __pure crc32c_intel_le_hw(u32 crc, unsigned char const *p, size_t len)
{
unsigned int iquotient = len / SCALE_F;
unsigned int iremainder = len % SCALE_F;
unsigned long *ptmp = (unsigned long *)p;
while (iquotient--) {
__asm__ __volatile__(
".byte 0xf2, " REX_PRE "0xf, 0x38, 0xf1, 0xf1;"
:"=S"(crc)
:"0"(crc), "c"(*ptmp)
);
ptmp++;
}
if (iremainder)
crc = crc32c_intel_le_hw_byte(crc, (unsigned char *)ptmp,
iremainder);
return crc;
}
/*
* Setting the seed allows arbitrary accumulators and flexible XOR policy
* If your algorithm starts with ~0, then XOR with ~0 before you set
* the seed.
*/
static int crc32c_intel_setkey(struct crypto_shash *hash, const u8 *key,
unsigned int keylen)
{
u32 *mctx = crypto_shash_ctx(hash);
if (keylen != sizeof(u32)) {
crypto_shash_set_flags(hash, CRYPTO_TFM_RES_BAD_KEY_LEN);
return -EINVAL;
}
*mctx = le32_to_cpup((__le32 *)key);
return 0;
}
static int crc32c_intel_init(struct shash_desc *desc)
{
u32 *mctx = crypto_shash_ctx(desc->tfm);
u32 *crcp = shash_desc_ctx(desc);
*crcp = *mctx;
return 0;
}
static int crc32c_intel_update(struct shash_desc *desc, const u8 *data,
unsigned int len)
{
u32 *crcp = shash_desc_ctx(desc);
*crcp = crc32c_intel_le_hw(*crcp, data, len);
return 0;
}
static int __crc32c_intel_finup(u32 *crcp, const u8 *data, unsigned int len,
u8 *out)
{
*(__le32 *)out = ~cpu_to_le32(crc32c_intel_le_hw(*crcp, data, len));
return 0;
}
static int crc32c_intel_finup(struct shash_desc *desc, const u8 *data,
unsigned int len, u8 *out)
{
return __crc32c_intel_finup(shash_desc_ctx(desc), data, len, out);
}
static int crc32c_intel_final(struct shash_desc *desc, u8 *out)
{
u32 *crcp = shash_desc_ctx(desc);
*(__le32 *)out = ~cpu_to_le32p(crcp);
return 0;
}
static int crc32c_intel_digest(struct shash_desc *desc, const u8 *data,
unsigned int len, u8 *out)
{
return __crc32c_intel_finup(crypto_shash_ctx(desc->tfm), data, len,
out);
}
static int crc32c_intel_cra_init(struct crypto_tfm *tfm)
{
u32 *key = crypto_tfm_ctx(tfm);
*key = ~0;
return 0;
}
static struct shash_alg alg = {
.setkey = crc32c_intel_setkey,
.init = crc32c_intel_init,
.update = crc32c_intel_update,
.final = crc32c_intel_final,
.finup = crc32c_intel_finup,
.digest = crc32c_intel_digest,
.descsize = sizeof(u32),
.digestsize = CHKSUM_DIGEST_SIZE,
.base = {
.cra_name = "crc32c",
.cra_driver_name = "crc32c-intel",
.cra_priority = 200,
.cra_blocksize = CHKSUM_BLOCK_SIZE,
.cra_ctxsize = sizeof(u32),
.cra_module = THIS_MODULE,
.cra_init = crc32c_intel_cra_init,
}
};
static int __init crc32c_intel_mod_init(void)
{
if (cpu_has_xmm4_2)
return crypto_register_shash(&alg);
else
return -ENODEV;
}
static void __exit crc32c_intel_mod_fini(void)
{
crypto_unregister_shash(&alg);
}
module_init(crc32c_intel_mod_init);
module_exit(crc32c_intel_mod_fini);
MODULE_AUTHOR("Austin Zhang <austin.zhang@intel.com>, Kent Liu <kent.liu@intel.com>");
MODULE_DESCRIPTION("CRC32c (Castagnoli) optimization using Intel Hardware.");
MODULE_LICENSE("GPL");
MODULE_ALIAS("crc32c");
MODULE_ALIAS("crc32c-intel");
| gpl-2.0 |
DevSwift/Kernel-3.4-U8500 | drivers/md/linear.c | 4928 | 9015 | /*
linear.c : Multiple Devices driver for Linux
Copyright (C) 1994-96 Marc ZYNGIER
<zyngier@ufr-info-p7.ibp.fr> or
<maz@gloups.fdn.fr>
Linear mode management functions.
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.
You should have received a copy of the GNU General Public License
(for example /usr/src/linux/COPYING); if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/blkdev.h>
#include <linux/raid/md_u.h>
#include <linux/seq_file.h>
#include <linux/module.h>
#include <linux/slab.h>
#include "md.h"
#include "linear.h"
/*
* find which device holds a particular offset
*/
static inline struct dev_info *which_dev(struct mddev *mddev, sector_t sector)
{
int lo, mid, hi;
struct linear_conf *conf;
lo = 0;
hi = mddev->raid_disks - 1;
conf = rcu_dereference(mddev->private);
/*
* Binary Search
*/
while (hi > lo) {
mid = (hi + lo) / 2;
if (sector < conf->disks[mid].end_sector)
hi = mid;
else
lo = mid + 1;
}
return conf->disks + lo;
}
/**
* linear_mergeable_bvec -- tell bio layer if two requests can be merged
* @q: request queue
* @bvm: properties of new bio
* @biovec: the request that could be merged to it.
*
* Return amount of bytes we can take at this offset
*/
static int linear_mergeable_bvec(struct request_queue *q,
struct bvec_merge_data *bvm,
struct bio_vec *biovec)
{
struct mddev *mddev = q->queuedata;
struct dev_info *dev0;
unsigned long maxsectors, bio_sectors = bvm->bi_size >> 9;
sector_t sector = bvm->bi_sector + get_start_sect(bvm->bi_bdev);
int maxbytes = biovec->bv_len;
struct request_queue *subq;
rcu_read_lock();
dev0 = which_dev(mddev, sector);
maxsectors = dev0->end_sector - sector;
subq = bdev_get_queue(dev0->rdev->bdev);
if (subq->merge_bvec_fn) {
bvm->bi_bdev = dev0->rdev->bdev;
bvm->bi_sector -= dev0->end_sector - dev0->rdev->sectors;
maxbytes = min(maxbytes, subq->merge_bvec_fn(subq, bvm,
biovec));
}
rcu_read_unlock();
if (maxsectors < bio_sectors)
maxsectors = 0;
else
maxsectors -= bio_sectors;
if (maxsectors <= (PAGE_SIZE >> 9 ) && bio_sectors == 0)
return maxbytes;
if (maxsectors > (maxbytes >> 9))
return maxbytes;
else
return maxsectors << 9;
}
static int linear_congested(void *data, int bits)
{
struct mddev *mddev = data;
struct linear_conf *conf;
int i, ret = 0;
if (mddev_congested(mddev, bits))
return 1;
rcu_read_lock();
conf = rcu_dereference(mddev->private);
for (i = 0; i < mddev->raid_disks && !ret ; i++) {
struct request_queue *q = bdev_get_queue(conf->disks[i].rdev->bdev);
ret |= bdi_congested(&q->backing_dev_info, bits);
}
rcu_read_unlock();
return ret;
}
static sector_t linear_size(struct mddev *mddev, sector_t sectors, int raid_disks)
{
struct linear_conf *conf;
sector_t array_sectors;
rcu_read_lock();
conf = rcu_dereference(mddev->private);
WARN_ONCE(sectors || raid_disks,
"%s does not support generic reshape\n", __func__);
array_sectors = conf->array_sectors;
rcu_read_unlock();
return array_sectors;
}
static struct linear_conf *linear_conf(struct mddev *mddev, int raid_disks)
{
struct linear_conf *conf;
struct md_rdev *rdev;
int i, cnt;
conf = kzalloc (sizeof (*conf) + raid_disks*sizeof(struct dev_info),
GFP_KERNEL);
if (!conf)
return NULL;
cnt = 0;
conf->array_sectors = 0;
rdev_for_each(rdev, mddev) {
int j = rdev->raid_disk;
struct dev_info *disk = conf->disks + j;
sector_t sectors;
if (j < 0 || j >= raid_disks || disk->rdev) {
printk(KERN_ERR "md/linear:%s: disk numbering problem. Aborting!\n",
mdname(mddev));
goto out;
}
disk->rdev = rdev;
if (mddev->chunk_sectors) {
sectors = rdev->sectors;
sector_div(sectors, mddev->chunk_sectors);
rdev->sectors = sectors * mddev->chunk_sectors;
}
disk_stack_limits(mddev->gendisk, rdev->bdev,
rdev->data_offset << 9);
conf->array_sectors += rdev->sectors;
cnt++;
}
if (cnt != raid_disks) {
printk(KERN_ERR "md/linear:%s: not enough drives present. Aborting!\n",
mdname(mddev));
goto out;
}
/*
* Here we calculate the device offsets.
*/
conf->disks[0].end_sector = conf->disks[0].rdev->sectors;
for (i = 1; i < raid_disks; i++)
conf->disks[i].end_sector =
conf->disks[i-1].end_sector +
conf->disks[i].rdev->sectors;
return conf;
out:
kfree(conf);
return NULL;
}
static int linear_run (struct mddev *mddev)
{
struct linear_conf *conf;
int ret;
if (md_check_no_bitmap(mddev))
return -EINVAL;
conf = linear_conf(mddev, mddev->raid_disks);
if (!conf)
return 1;
mddev->private = conf;
md_set_array_sectors(mddev, linear_size(mddev, 0, 0));
blk_queue_merge_bvec(mddev->queue, linear_mergeable_bvec);
mddev->queue->backing_dev_info.congested_fn = linear_congested;
mddev->queue->backing_dev_info.congested_data = mddev;
ret = md_integrity_register(mddev);
if (ret) {
kfree(conf);
mddev->private = NULL;
}
return ret;
}
static int linear_add(struct mddev *mddev, struct md_rdev *rdev)
{
/* Adding a drive to a linear array allows the array to grow.
* It is permitted if the new drive has a matching superblock
* already on it, with raid_disk equal to raid_disks.
* It is achieved by creating a new linear_private_data structure
* and swapping it in in-place of the current one.
* The current one is never freed until the array is stopped.
* This avoids races.
*/
struct linear_conf *newconf, *oldconf;
if (rdev->saved_raid_disk != mddev->raid_disks)
return -EINVAL;
rdev->raid_disk = rdev->saved_raid_disk;
rdev->saved_raid_disk = -1;
newconf = linear_conf(mddev,mddev->raid_disks+1);
if (!newconf)
return -ENOMEM;
oldconf = rcu_dereference(mddev->private);
mddev->raid_disks++;
rcu_assign_pointer(mddev->private, newconf);
md_set_array_sectors(mddev, linear_size(mddev, 0, 0));
set_capacity(mddev->gendisk, mddev->array_sectors);
revalidate_disk(mddev->gendisk);
kfree_rcu(oldconf, rcu);
return 0;
}
static int linear_stop (struct mddev *mddev)
{
struct linear_conf *conf = mddev->private;
/*
* We do not require rcu protection here since
* we hold reconfig_mutex for both linear_add and
* linear_stop, so they cannot race.
* We should make sure any old 'conf's are properly
* freed though.
*/
rcu_barrier();
blk_sync_queue(mddev->queue); /* the unplug fn references 'conf'*/
kfree(conf);
mddev->private = NULL;
return 0;
}
static void linear_make_request(struct mddev *mddev, struct bio *bio)
{
struct dev_info *tmp_dev;
sector_t start_sector;
if (unlikely(bio->bi_rw & REQ_FLUSH)) {
md_flush_request(mddev, bio);
return;
}
rcu_read_lock();
tmp_dev = which_dev(mddev, bio->bi_sector);
start_sector = tmp_dev->end_sector - tmp_dev->rdev->sectors;
if (unlikely(bio->bi_sector >= (tmp_dev->end_sector)
|| (bio->bi_sector < start_sector))) {
char b[BDEVNAME_SIZE];
printk(KERN_ERR
"md/linear:%s: make_request: Sector %llu out of bounds on "
"dev %s: %llu sectors, offset %llu\n",
mdname(mddev),
(unsigned long long)bio->bi_sector,
bdevname(tmp_dev->rdev->bdev, b),
(unsigned long long)tmp_dev->rdev->sectors,
(unsigned long long)start_sector);
rcu_read_unlock();
bio_io_error(bio);
return;
}
if (unlikely(bio->bi_sector + (bio->bi_size >> 9) >
tmp_dev->end_sector)) {
/* This bio crosses a device boundary, so we have to
* split it.
*/
struct bio_pair *bp;
sector_t end_sector = tmp_dev->end_sector;
rcu_read_unlock();
bp = bio_split(bio, end_sector - bio->bi_sector);
linear_make_request(mddev, &bp->bio1);
linear_make_request(mddev, &bp->bio2);
bio_pair_release(bp);
return;
}
bio->bi_bdev = tmp_dev->rdev->bdev;
bio->bi_sector = bio->bi_sector - start_sector
+ tmp_dev->rdev->data_offset;
rcu_read_unlock();
generic_make_request(bio);
}
static void linear_status (struct seq_file *seq, struct mddev *mddev)
{
seq_printf(seq, " %dk rounding", mddev->chunk_sectors / 2);
}
static struct md_personality linear_personality =
{
.name = "linear",
.level = LEVEL_LINEAR,
.owner = THIS_MODULE,
.make_request = linear_make_request,
.run = linear_run,
.stop = linear_stop,
.status = linear_status,
.hot_add_disk = linear_add,
.size = linear_size,
};
static int __init linear_init (void)
{
return register_md_personality (&linear_personality);
}
static void linear_exit (void)
{
unregister_md_personality (&linear_personality);
}
module_init(linear_init);
module_exit(linear_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Linear device concatenation personality for MD");
MODULE_ALIAS("md-personality-1"); /* LINEAR - deprecated*/
MODULE_ALIAS("md-linear");
MODULE_ALIAS("md-level--1");
| gpl-2.0 |
A2109devs/lenovo_a2109a_kernel | arch/ia64/kernel/kprobes.c | 8768 | 30405 | /*
* Kernel Probes (KProbes)
* arch/ia64/kernel/kprobes.c
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Copyright (C) IBM Corporation, 2002, 2004
* Copyright (C) Intel Corporation, 2005
*
* 2005-Apr Rusty Lynch <rusty.lynch@intel.com> and Anil S Keshavamurthy
* <anil.s.keshavamurthy@intel.com> adapted from i386
*/
#include <linux/kprobes.h>
#include <linux/ptrace.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <linux/preempt.h>
#include <linux/moduleloader.h>
#include <linux/kdebug.h>
#include <asm/pgtable.h>
#include <asm/sections.h>
#include <asm/uaccess.h>
extern void jprobe_inst_return(void);
DEFINE_PER_CPU(struct kprobe *, current_kprobe) = NULL;
DEFINE_PER_CPU(struct kprobe_ctlblk, kprobe_ctlblk);
struct kretprobe_blackpoint kretprobe_blacklist[] = {{NULL, NULL}};
enum instruction_type {A, I, M, F, B, L, X, u};
static enum instruction_type bundle_encoding[32][3] = {
{ M, I, I }, /* 00 */
{ M, I, I }, /* 01 */
{ M, I, I }, /* 02 */
{ M, I, I }, /* 03 */
{ M, L, X }, /* 04 */
{ M, L, X }, /* 05 */
{ u, u, u }, /* 06 */
{ u, u, u }, /* 07 */
{ M, M, I }, /* 08 */
{ M, M, I }, /* 09 */
{ M, M, I }, /* 0A */
{ M, M, I }, /* 0B */
{ M, F, I }, /* 0C */
{ M, F, I }, /* 0D */
{ M, M, F }, /* 0E */
{ M, M, F }, /* 0F */
{ M, I, B }, /* 10 */
{ M, I, B }, /* 11 */
{ M, B, B }, /* 12 */
{ M, B, B }, /* 13 */
{ u, u, u }, /* 14 */
{ u, u, u }, /* 15 */
{ B, B, B }, /* 16 */
{ B, B, B }, /* 17 */
{ M, M, B }, /* 18 */
{ M, M, B }, /* 19 */
{ u, u, u }, /* 1A */
{ u, u, u }, /* 1B */
{ M, F, B }, /* 1C */
{ M, F, B }, /* 1D */
{ u, u, u }, /* 1E */
{ u, u, u }, /* 1F */
};
/* Insert a long branch code */
static void __kprobes set_brl_inst(void *from, void *to)
{
s64 rel = ((s64) to - (s64) from) >> 4;
bundle_t *brl;
brl = (bundle_t *) ((u64) from & ~0xf);
brl->quad0.template = 0x05; /* [MLX](stop) */
brl->quad0.slot0 = NOP_M_INST; /* nop.m 0x0 */
brl->quad0.slot1_p0 = ((rel >> 20) & 0x7fffffffff) << 2;
brl->quad1.slot1_p1 = (((rel >> 20) & 0x7fffffffff) << 2) >> (64 - 46);
/* brl.cond.sptk.many.clr rel<<4 (qp=0) */
brl->quad1.slot2 = BRL_INST(rel >> 59, rel & 0xfffff);
}
/*
* In this function we check to see if the instruction
* is IP relative instruction and update the kprobe
* inst flag accordingly
*/
static void __kprobes update_kprobe_inst_flag(uint template, uint slot,
uint major_opcode,
unsigned long kprobe_inst,
struct kprobe *p)
{
p->ainsn.inst_flag = 0;
p->ainsn.target_br_reg = 0;
p->ainsn.slot = slot;
/* Check for Break instruction
* Bits 37:40 Major opcode to be zero
* Bits 27:32 X6 to be zero
* Bits 32:35 X3 to be zero
*/
if ((!major_opcode) && (!((kprobe_inst >> 27) & 0x1FF)) ) {
/* is a break instruction */
p->ainsn.inst_flag |= INST_FLAG_BREAK_INST;
return;
}
if (bundle_encoding[template][slot] == B) {
switch (major_opcode) {
case INDIRECT_CALL_OPCODE:
p->ainsn.inst_flag |= INST_FLAG_FIX_BRANCH_REG;
p->ainsn.target_br_reg = ((kprobe_inst >> 6) & 0x7);
break;
case IP_RELATIVE_PREDICT_OPCODE:
case IP_RELATIVE_BRANCH_OPCODE:
p->ainsn.inst_flag |= INST_FLAG_FIX_RELATIVE_IP_ADDR;
break;
case IP_RELATIVE_CALL_OPCODE:
p->ainsn.inst_flag |= INST_FLAG_FIX_RELATIVE_IP_ADDR;
p->ainsn.inst_flag |= INST_FLAG_FIX_BRANCH_REG;
p->ainsn.target_br_reg = ((kprobe_inst >> 6) & 0x7);
break;
}
} else if (bundle_encoding[template][slot] == X) {
switch (major_opcode) {
case LONG_CALL_OPCODE:
p->ainsn.inst_flag |= INST_FLAG_FIX_BRANCH_REG;
p->ainsn.target_br_reg = ((kprobe_inst >> 6) & 0x7);
break;
}
}
return;
}
/*
* In this function we check to see if the instruction
* (qp) cmpx.crel.ctype p1,p2=r2,r3
* on which we are inserting kprobe is cmp instruction
* with ctype as unc.
*/
static uint __kprobes is_cmp_ctype_unc_inst(uint template, uint slot,
uint major_opcode,
unsigned long kprobe_inst)
{
cmp_inst_t cmp_inst;
uint ctype_unc = 0;
if (!((bundle_encoding[template][slot] == I) ||
(bundle_encoding[template][slot] == M)))
goto out;
if (!((major_opcode == 0xC) || (major_opcode == 0xD) ||
(major_opcode == 0xE)))
goto out;
cmp_inst.l = kprobe_inst;
if ((cmp_inst.f.x2 == 0) || (cmp_inst.f.x2 == 1)) {
/* Integer compare - Register Register (A6 type)*/
if ((cmp_inst.f.tb == 0) && (cmp_inst.f.ta == 0)
&&(cmp_inst.f.c == 1))
ctype_unc = 1;
} else if ((cmp_inst.f.x2 == 2)||(cmp_inst.f.x2 == 3)) {
/* Integer compare - Immediate Register (A8 type)*/
if ((cmp_inst.f.ta == 0) &&(cmp_inst.f.c == 1))
ctype_unc = 1;
}
out:
return ctype_unc;
}
/*
* In this function we check to see if the instruction
* on which we are inserting kprobe is supported.
* Returns qp value if supported
* Returns -EINVAL if unsupported
*/
static int __kprobes unsupported_inst(uint template, uint slot,
uint major_opcode,
unsigned long kprobe_inst,
unsigned long addr)
{
int qp;
qp = kprobe_inst & 0x3f;
if (is_cmp_ctype_unc_inst(template, slot, major_opcode, kprobe_inst)) {
if (slot == 1 && qp) {
printk(KERN_WARNING "Kprobes on cmp unc "
"instruction on slot 1 at <0x%lx> "
"is not supported\n", addr);
return -EINVAL;
}
qp = 0;
}
else if (bundle_encoding[template][slot] == I) {
if (major_opcode == 0) {
/*
* Check for Integer speculation instruction
* - Bit 33-35 to be equal to 0x1
*/
if (((kprobe_inst >> 33) & 0x7) == 1) {
printk(KERN_WARNING
"Kprobes on speculation inst at <0x%lx> not supported\n",
addr);
return -EINVAL;
}
/*
* IP relative mov instruction
* - Bit 27-35 to be equal to 0x30
*/
if (((kprobe_inst >> 27) & 0x1FF) == 0x30) {
printk(KERN_WARNING
"Kprobes on \"mov r1=ip\" at <0x%lx> not supported\n",
addr);
return -EINVAL;
}
}
else if ((major_opcode == 5) && !(kprobe_inst & (0xFUl << 33)) &&
(kprobe_inst & (0x1UL << 12))) {
/* test bit instructions, tbit,tnat,tf
* bit 33-36 to be equal to 0
* bit 12 to be equal to 1
*/
if (slot == 1 && qp) {
printk(KERN_WARNING "Kprobes on test bit "
"instruction on slot at <0x%lx> "
"is not supported\n", addr);
return -EINVAL;
}
qp = 0;
}
}
else if (bundle_encoding[template][slot] == B) {
if (major_opcode == 7) {
/* IP-Relative Predict major code is 7 */
printk(KERN_WARNING "Kprobes on IP-Relative"
"Predict is not supported\n");
return -EINVAL;
}
else if (major_opcode == 2) {
/* Indirect Predict, major code is 2
* bit 27-32 to be equal to 10 or 11
*/
int x6=(kprobe_inst >> 27) & 0x3F;
if ((x6 == 0x10) || (x6 == 0x11)) {
printk(KERN_WARNING "Kprobes on "
"Indirect Predict is not supported\n");
return -EINVAL;
}
}
}
/* kernel does not use float instruction, here for safety kprobe
* will judge whether it is fcmp/flass/float approximation instruction
*/
else if (unlikely(bundle_encoding[template][slot] == F)) {
if ((major_opcode == 4 || major_opcode == 5) &&
(kprobe_inst & (0x1 << 12))) {
/* fcmp/fclass unc instruction */
if (slot == 1 && qp) {
printk(KERN_WARNING "Kprobes on fcmp/fclass "
"instruction on slot at <0x%lx> "
"is not supported\n", addr);
return -EINVAL;
}
qp = 0;
}
if ((major_opcode == 0 || major_opcode == 1) &&
(kprobe_inst & (0x1UL << 33))) {
/* float Approximation instruction */
if (slot == 1 && qp) {
printk(KERN_WARNING "Kprobes on float Approx "
"instr at <0x%lx> is not supported\n",
addr);
return -EINVAL;
}
qp = 0;
}
}
return qp;
}
/*
* In this function we override the bundle with
* the break instruction at the given slot.
*/
static void __kprobes prepare_break_inst(uint template, uint slot,
uint major_opcode,
unsigned long kprobe_inst,
struct kprobe *p,
int qp)
{
unsigned long break_inst = BREAK_INST;
bundle_t *bundle = &p->opcode.bundle;
/*
* Copy the original kprobe_inst qualifying predicate(qp)
* to the break instruction
*/
break_inst |= qp;
switch (slot) {
case 0:
bundle->quad0.slot0 = break_inst;
break;
case 1:
bundle->quad0.slot1_p0 = break_inst;
bundle->quad1.slot1_p1 = break_inst >> (64-46);
break;
case 2:
bundle->quad1.slot2 = break_inst;
break;
}
/*
* Update the instruction flag, so that we can
* emulate the instruction properly after we
* single step on original instruction
*/
update_kprobe_inst_flag(template, slot, major_opcode, kprobe_inst, p);
}
static void __kprobes get_kprobe_inst(bundle_t *bundle, uint slot,
unsigned long *kprobe_inst, uint *major_opcode)
{
unsigned long kprobe_inst_p0, kprobe_inst_p1;
unsigned int template;
template = bundle->quad0.template;
switch (slot) {
case 0:
*major_opcode = (bundle->quad0.slot0 >> SLOT0_OPCODE_SHIFT);
*kprobe_inst = bundle->quad0.slot0;
break;
case 1:
*major_opcode = (bundle->quad1.slot1_p1 >> SLOT1_p1_OPCODE_SHIFT);
kprobe_inst_p0 = bundle->quad0.slot1_p0;
kprobe_inst_p1 = bundle->quad1.slot1_p1;
*kprobe_inst = kprobe_inst_p0 | (kprobe_inst_p1 << (64-46));
break;
case 2:
*major_opcode = (bundle->quad1.slot2 >> SLOT2_OPCODE_SHIFT);
*kprobe_inst = bundle->quad1.slot2;
break;
}
}
/* Returns non-zero if the addr is in the Interrupt Vector Table */
static int __kprobes in_ivt_functions(unsigned long addr)
{
return (addr >= (unsigned long)__start_ivt_text
&& addr < (unsigned long)__end_ivt_text);
}
static int __kprobes valid_kprobe_addr(int template, int slot,
unsigned long addr)
{
if ((slot > 2) || ((bundle_encoding[template][1] == L) && slot > 1)) {
printk(KERN_WARNING "Attempting to insert unaligned kprobe "
"at 0x%lx\n", addr);
return -EINVAL;
}
if (in_ivt_functions(addr)) {
printk(KERN_WARNING "Kprobes can't be inserted inside "
"IVT functions at 0x%lx\n", addr);
return -EINVAL;
}
return 0;
}
static void __kprobes save_previous_kprobe(struct kprobe_ctlblk *kcb)
{
unsigned int i;
i = atomic_add_return(1, &kcb->prev_kprobe_index);
kcb->prev_kprobe[i-1].kp = kprobe_running();
kcb->prev_kprobe[i-1].status = kcb->kprobe_status;
}
static void __kprobes restore_previous_kprobe(struct kprobe_ctlblk *kcb)
{
unsigned int i;
i = atomic_read(&kcb->prev_kprobe_index);
__get_cpu_var(current_kprobe) = kcb->prev_kprobe[i-1].kp;
kcb->kprobe_status = kcb->prev_kprobe[i-1].status;
atomic_sub(1, &kcb->prev_kprobe_index);
}
static void __kprobes set_current_kprobe(struct kprobe *p,
struct kprobe_ctlblk *kcb)
{
__get_cpu_var(current_kprobe) = p;
}
static void kretprobe_trampoline(void)
{
}
/*
* At this point the target function has been tricked into
* returning into our trampoline. Lookup the associated instance
* and then:
* - call the handler function
* - cleanup by marking the instance as unused
* - long jump back to the original return address
*/
int __kprobes trampoline_probe_handler(struct kprobe *p, struct pt_regs *regs)
{
struct kretprobe_instance *ri = NULL;
struct hlist_head *head, empty_rp;
struct hlist_node *node, *tmp;
unsigned long flags, orig_ret_address = 0;
unsigned long trampoline_address =
((struct fnptr *)kretprobe_trampoline)->ip;
INIT_HLIST_HEAD(&empty_rp);
kretprobe_hash_lock(current, &head, &flags);
/*
* It is possible to have multiple instances associated with a given
* task either because an multiple functions in the call path
* have a return probe installed on them, and/or more than one return
* return probe was registered for a target function.
*
* We can handle this because:
* - instances are always inserted at the head of the list
* - when multiple return probes are registered for the same
* function, the first instance's ret_addr will point to the
* real return address, and all the rest will point to
* kretprobe_trampoline
*/
hlist_for_each_entry_safe(ri, node, tmp, head, hlist) {
if (ri->task != current)
/* another task is sharing our hash bucket */
continue;
orig_ret_address = (unsigned long)ri->ret_addr;
if (orig_ret_address != trampoline_address)
/*
* This is the real return address. Any other
* instances associated with this task are for
* other calls deeper on the call stack
*/
break;
}
regs->cr_iip = orig_ret_address;
hlist_for_each_entry_safe(ri, node, tmp, head, hlist) {
if (ri->task != current)
/* another task is sharing our hash bucket */
continue;
if (ri->rp && ri->rp->handler)
ri->rp->handler(ri, regs);
orig_ret_address = (unsigned long)ri->ret_addr;
recycle_rp_inst(ri, &empty_rp);
if (orig_ret_address != trampoline_address)
/*
* This is the real return address. Any other
* instances associated with this task are for
* other calls deeper on the call stack
*/
break;
}
kretprobe_assert(ri, orig_ret_address, trampoline_address);
reset_current_kprobe();
kretprobe_hash_unlock(current, &flags);
preempt_enable_no_resched();
hlist_for_each_entry_safe(ri, node, tmp, &empty_rp, hlist) {
hlist_del(&ri->hlist);
kfree(ri);
}
/*
* By returning a non-zero value, we are telling
* kprobe_handler() that we don't want the post_handler
* to run (and have re-enabled preemption)
*/
return 1;
}
void __kprobes arch_prepare_kretprobe(struct kretprobe_instance *ri,
struct pt_regs *regs)
{
ri->ret_addr = (kprobe_opcode_t *)regs->b0;
/* Replace the return addr with trampoline addr */
regs->b0 = ((struct fnptr *)kretprobe_trampoline)->ip;
}
/* Check the instruction in the slot is break */
static int __kprobes __is_ia64_break_inst(bundle_t *bundle, uint slot)
{
unsigned int major_opcode;
unsigned int template = bundle->quad0.template;
unsigned long kprobe_inst;
/* Move to slot 2, if bundle is MLX type and kprobe slot is 1 */
if (slot == 1 && bundle_encoding[template][1] == L)
slot++;
/* Get Kprobe probe instruction at given slot*/
get_kprobe_inst(bundle, slot, &kprobe_inst, &major_opcode);
/* For break instruction,
* Bits 37:40 Major opcode to be zero
* Bits 27:32 X6 to be zero
* Bits 32:35 X3 to be zero
*/
if (major_opcode || ((kprobe_inst >> 27) & 0x1FF)) {
/* Not a break instruction */
return 0;
}
/* Is a break instruction */
return 1;
}
/*
* In this function, we check whether the target bundle modifies IP or
* it triggers an exception. If so, it cannot be boostable.
*/
static int __kprobes can_boost(bundle_t *bundle, uint slot,
unsigned long bundle_addr)
{
unsigned int template = bundle->quad0.template;
do {
if (search_exception_tables(bundle_addr + slot) ||
__is_ia64_break_inst(bundle, slot))
return 0; /* exception may occur in this bundle*/
} while ((++slot) < 3);
template &= 0x1e;
if (template >= 0x10 /* including B unit */ ||
template == 0x04 /* including X unit */ ||
template == 0x06) /* undefined */
return 0;
return 1;
}
/* Prepare long jump bundle and disables other boosters if need */
static void __kprobes prepare_booster(struct kprobe *p)
{
unsigned long addr = (unsigned long)p->addr & ~0xFULL;
unsigned int slot = (unsigned long)p->addr & 0xf;
struct kprobe *other_kp;
if (can_boost(&p->ainsn.insn[0].bundle, slot, addr)) {
set_brl_inst(&p->ainsn.insn[1].bundle, (bundle_t *)addr + 1);
p->ainsn.inst_flag |= INST_FLAG_BOOSTABLE;
}
/* disables boosters in previous slots */
for (; addr < (unsigned long)p->addr; addr++) {
other_kp = get_kprobe((void *)addr);
if (other_kp)
other_kp->ainsn.inst_flag &= ~INST_FLAG_BOOSTABLE;
}
}
int __kprobes arch_prepare_kprobe(struct kprobe *p)
{
unsigned long addr = (unsigned long) p->addr;
unsigned long *kprobe_addr = (unsigned long *)(addr & ~0xFULL);
unsigned long kprobe_inst=0;
unsigned int slot = addr & 0xf, template, major_opcode = 0;
bundle_t *bundle;
int qp;
bundle = &((kprobe_opcode_t *)kprobe_addr)->bundle;
template = bundle->quad0.template;
if(valid_kprobe_addr(template, slot, addr))
return -EINVAL;
/* Move to slot 2, if bundle is MLX type and kprobe slot is 1 */
if (slot == 1 && bundle_encoding[template][1] == L)
slot++;
/* Get kprobe_inst and major_opcode from the bundle */
get_kprobe_inst(bundle, slot, &kprobe_inst, &major_opcode);
qp = unsupported_inst(template, slot, major_opcode, kprobe_inst, addr);
if (qp < 0)
return -EINVAL;
p->ainsn.insn = get_insn_slot();
if (!p->ainsn.insn)
return -ENOMEM;
memcpy(&p->opcode, kprobe_addr, sizeof(kprobe_opcode_t));
memcpy(p->ainsn.insn, kprobe_addr, sizeof(kprobe_opcode_t));
prepare_break_inst(template, slot, major_opcode, kprobe_inst, p, qp);
prepare_booster(p);
return 0;
}
void __kprobes arch_arm_kprobe(struct kprobe *p)
{
unsigned long arm_addr;
bundle_t *src, *dest;
arm_addr = ((unsigned long)p->addr) & ~0xFUL;
dest = &((kprobe_opcode_t *)arm_addr)->bundle;
src = &p->opcode.bundle;
flush_icache_range((unsigned long)p->ainsn.insn,
(unsigned long)p->ainsn.insn +
sizeof(kprobe_opcode_t) * MAX_INSN_SIZE);
switch (p->ainsn.slot) {
case 0:
dest->quad0.slot0 = src->quad0.slot0;
break;
case 1:
dest->quad1.slot1_p1 = src->quad1.slot1_p1;
break;
case 2:
dest->quad1.slot2 = src->quad1.slot2;
break;
}
flush_icache_range(arm_addr, arm_addr + sizeof(kprobe_opcode_t));
}
void __kprobes arch_disarm_kprobe(struct kprobe *p)
{
unsigned long arm_addr;
bundle_t *src, *dest;
arm_addr = ((unsigned long)p->addr) & ~0xFUL;
dest = &((kprobe_opcode_t *)arm_addr)->bundle;
/* p->ainsn.insn contains the original unaltered kprobe_opcode_t */
src = &p->ainsn.insn->bundle;
switch (p->ainsn.slot) {
case 0:
dest->quad0.slot0 = src->quad0.slot0;
break;
case 1:
dest->quad1.slot1_p1 = src->quad1.slot1_p1;
break;
case 2:
dest->quad1.slot2 = src->quad1.slot2;
break;
}
flush_icache_range(arm_addr, arm_addr + sizeof(kprobe_opcode_t));
}
void __kprobes arch_remove_kprobe(struct kprobe *p)
{
if (p->ainsn.insn) {
free_insn_slot(p->ainsn.insn,
p->ainsn.inst_flag & INST_FLAG_BOOSTABLE);
p->ainsn.insn = NULL;
}
}
/*
* We are resuming execution after a single step fault, so the pt_regs
* structure reflects the register state after we executed the instruction
* located in the kprobe (p->ainsn.insn->bundle). We still need to adjust
* the ip to point back to the original stack address. To set the IP address
* to original stack address, handle the case where we need to fixup the
* relative IP address and/or fixup branch register.
*/
static void __kprobes resume_execution(struct kprobe *p, struct pt_regs *regs)
{
unsigned long bundle_addr = (unsigned long) (&p->ainsn.insn->bundle);
unsigned long resume_addr = (unsigned long)p->addr & ~0xFULL;
unsigned long template;
int slot = ((unsigned long)p->addr & 0xf);
template = p->ainsn.insn->bundle.quad0.template;
if (slot == 1 && bundle_encoding[template][1] == L)
slot = 2;
if (p->ainsn.inst_flag & ~INST_FLAG_BOOSTABLE) {
if (p->ainsn.inst_flag & INST_FLAG_FIX_RELATIVE_IP_ADDR) {
/* Fix relative IP address */
regs->cr_iip = (regs->cr_iip - bundle_addr) +
resume_addr;
}
if (p->ainsn.inst_flag & INST_FLAG_FIX_BRANCH_REG) {
/*
* Fix target branch register, software convention is
* to use either b0 or b6 or b7, so just checking
* only those registers
*/
switch (p->ainsn.target_br_reg) {
case 0:
if ((regs->b0 == bundle_addr) ||
(regs->b0 == bundle_addr + 0x10)) {
regs->b0 = (regs->b0 - bundle_addr) +
resume_addr;
}
break;
case 6:
if ((regs->b6 == bundle_addr) ||
(regs->b6 == bundle_addr + 0x10)) {
regs->b6 = (regs->b6 - bundle_addr) +
resume_addr;
}
break;
case 7:
if ((regs->b7 == bundle_addr) ||
(regs->b7 == bundle_addr + 0x10)) {
regs->b7 = (regs->b7 - bundle_addr) +
resume_addr;
}
break;
} /* end switch */
}
goto turn_ss_off;
}
if (slot == 2) {
if (regs->cr_iip == bundle_addr + 0x10) {
regs->cr_iip = resume_addr + 0x10;
}
} else {
if (regs->cr_iip == bundle_addr) {
regs->cr_iip = resume_addr;
}
}
turn_ss_off:
/* Turn off Single Step bit */
ia64_psr(regs)->ss = 0;
}
static void __kprobes prepare_ss(struct kprobe *p, struct pt_regs *regs)
{
unsigned long bundle_addr = (unsigned long) &p->ainsn.insn->bundle;
unsigned long slot = (unsigned long)p->addr & 0xf;
/* single step inline if break instruction */
if (p->ainsn.inst_flag == INST_FLAG_BREAK_INST)
regs->cr_iip = (unsigned long)p->addr & ~0xFULL;
else
regs->cr_iip = bundle_addr & ~0xFULL;
if (slot > 2)
slot = 0;
ia64_psr(regs)->ri = slot;
/* turn on single stepping */
ia64_psr(regs)->ss = 1;
}
static int __kprobes is_ia64_break_inst(struct pt_regs *regs)
{
unsigned int slot = ia64_psr(regs)->ri;
unsigned long *kprobe_addr = (unsigned long *)regs->cr_iip;
bundle_t bundle;
memcpy(&bundle, kprobe_addr, sizeof(bundle_t));
return __is_ia64_break_inst(&bundle, slot);
}
static int __kprobes pre_kprobes_handler(struct die_args *args)
{
struct kprobe *p;
int ret = 0;
struct pt_regs *regs = args->regs;
kprobe_opcode_t *addr = (kprobe_opcode_t *)instruction_pointer(regs);
struct kprobe_ctlblk *kcb;
/*
* We don't want to be preempted for the entire
* duration of kprobe processing
*/
preempt_disable();
kcb = get_kprobe_ctlblk();
/* Handle recursion cases */
if (kprobe_running()) {
p = get_kprobe(addr);
if (p) {
if ((kcb->kprobe_status == KPROBE_HIT_SS) &&
(p->ainsn.inst_flag == INST_FLAG_BREAK_INST)) {
ia64_psr(regs)->ss = 0;
goto no_kprobe;
}
/* We have reentered the pre_kprobe_handler(), since
* another probe was hit while within the handler.
* We here save the original kprobes variables and
* just single step on the instruction of the new probe
* without calling any user handlers.
*/
save_previous_kprobe(kcb);
set_current_kprobe(p, kcb);
kprobes_inc_nmissed_count(p);
prepare_ss(p, regs);
kcb->kprobe_status = KPROBE_REENTER;
return 1;
} else if (args->err == __IA64_BREAK_JPROBE) {
/*
* jprobe instrumented function just completed
*/
p = __get_cpu_var(current_kprobe);
if (p->break_handler && p->break_handler(p, regs)) {
goto ss_probe;
}
} else if (!is_ia64_break_inst(regs)) {
/* The breakpoint instruction was removed by
* another cpu right after we hit, no further
* handling of this interrupt is appropriate
*/
ret = 1;
goto no_kprobe;
} else {
/* Not our break */
goto no_kprobe;
}
}
p = get_kprobe(addr);
if (!p) {
if (!is_ia64_break_inst(regs)) {
/*
* The breakpoint instruction was removed right
* after we hit it. Another cpu has removed
* either a probepoint or a debugger breakpoint
* at this address. In either case, no further
* handling of this interrupt is appropriate.
*/
ret = 1;
}
/* Not one of our break, let kernel handle it */
goto no_kprobe;
}
set_current_kprobe(p, kcb);
kcb->kprobe_status = KPROBE_HIT_ACTIVE;
if (p->pre_handler && p->pre_handler(p, regs))
/*
* Our pre-handler is specifically requesting that we just
* do a return. This is used for both the jprobe pre-handler
* and the kretprobe trampoline
*/
return 1;
ss_probe:
#if !defined(CONFIG_PREEMPT)
if (p->ainsn.inst_flag == INST_FLAG_BOOSTABLE && !p->post_handler) {
/* Boost up -- we can execute copied instructions directly */
ia64_psr(regs)->ri = p->ainsn.slot;
regs->cr_iip = (unsigned long)&p->ainsn.insn->bundle & ~0xFULL;
/* turn single stepping off */
ia64_psr(regs)->ss = 0;
reset_current_kprobe();
preempt_enable_no_resched();
return 1;
}
#endif
prepare_ss(p, regs);
kcb->kprobe_status = KPROBE_HIT_SS;
return 1;
no_kprobe:
preempt_enable_no_resched();
return ret;
}
static int __kprobes post_kprobes_handler(struct pt_regs *regs)
{
struct kprobe *cur = kprobe_running();
struct kprobe_ctlblk *kcb = get_kprobe_ctlblk();
if (!cur)
return 0;
if ((kcb->kprobe_status != KPROBE_REENTER) && cur->post_handler) {
kcb->kprobe_status = KPROBE_HIT_SSDONE;
cur->post_handler(cur, regs, 0);
}
resume_execution(cur, regs);
/*Restore back the original saved kprobes variables and continue. */
if (kcb->kprobe_status == KPROBE_REENTER) {
restore_previous_kprobe(kcb);
goto out;
}
reset_current_kprobe();
out:
preempt_enable_no_resched();
return 1;
}
int __kprobes kprobe_fault_handler(struct pt_regs *regs, int trapnr)
{
struct kprobe *cur = kprobe_running();
struct kprobe_ctlblk *kcb = get_kprobe_ctlblk();
switch(kcb->kprobe_status) {
case KPROBE_HIT_SS:
case KPROBE_REENTER:
/*
* We are here because the instruction being single
* stepped caused a page fault. We reset the current
* kprobe and the instruction pointer points back to
* the probe address and allow the page fault handler
* to continue as a normal page fault.
*/
regs->cr_iip = ((unsigned long)cur->addr) & ~0xFULL;
ia64_psr(regs)->ri = ((unsigned long)cur->addr) & 0xf;
if (kcb->kprobe_status == KPROBE_REENTER)
restore_previous_kprobe(kcb);
else
reset_current_kprobe();
preempt_enable_no_resched();
break;
case KPROBE_HIT_ACTIVE:
case KPROBE_HIT_SSDONE:
/*
* We increment the nmissed count for accounting,
* we can also use npre/npostfault count for accouting
* these specific fault cases.
*/
kprobes_inc_nmissed_count(cur);
/*
* We come here because instructions in the pre/post
* handler caused the page_fault, this could happen
* if handler tries to access user space by
* copy_from_user(), get_user() etc. Let the
* user-specified handler try to fix it first.
*/
if (cur->fault_handler && cur->fault_handler(cur, regs, trapnr))
return 1;
/*
* In case the user-specified fault handler returned
* zero, try to fix up.
*/
if (ia64_done_with_exception(regs))
return 1;
/*
* Let ia64_do_page_fault() fix it.
*/
break;
default:
break;
}
return 0;
}
int __kprobes kprobe_exceptions_notify(struct notifier_block *self,
unsigned long val, void *data)
{
struct die_args *args = (struct die_args *)data;
int ret = NOTIFY_DONE;
if (args->regs && user_mode(args->regs))
return ret;
switch(val) {
case DIE_BREAK:
/* err is break number from ia64_bad_break() */
if ((args->err >> 12) == (__IA64_BREAK_KPROBE >> 12)
|| args->err == __IA64_BREAK_JPROBE
|| args->err == 0)
if (pre_kprobes_handler(args))
ret = NOTIFY_STOP;
break;
case DIE_FAULT:
/* err is vector number from ia64_fault() */
if (args->err == 36)
if (post_kprobes_handler(args->regs))
ret = NOTIFY_STOP;
break;
default:
break;
}
return ret;
}
struct param_bsp_cfm {
unsigned long ip;
unsigned long *bsp;
unsigned long cfm;
};
static void ia64_get_bsp_cfm(struct unw_frame_info *info, void *arg)
{
unsigned long ip;
struct param_bsp_cfm *lp = arg;
do {
unw_get_ip(info, &ip);
if (ip == 0)
break;
if (ip == lp->ip) {
unw_get_bsp(info, (unsigned long*)&lp->bsp);
unw_get_cfm(info, (unsigned long*)&lp->cfm);
return;
}
} while (unw_unwind(info) >= 0);
lp->bsp = NULL;
lp->cfm = 0;
return;
}
unsigned long arch_deref_entry_point(void *entry)
{
return ((struct fnptr *)entry)->ip;
}
int __kprobes setjmp_pre_handler(struct kprobe *p, struct pt_regs *regs)
{
struct jprobe *jp = container_of(p, struct jprobe, kp);
unsigned long addr = arch_deref_entry_point(jp->entry);
struct kprobe_ctlblk *kcb = get_kprobe_ctlblk();
struct param_bsp_cfm pa;
int bytes;
/*
* Callee owns the argument space and could overwrite it, eg
* tail call optimization. So to be absolutely safe
* we save the argument space before transferring the control
* to instrumented jprobe function which runs in
* the process context
*/
pa.ip = regs->cr_iip;
unw_init_running(ia64_get_bsp_cfm, &pa);
bytes = (char *)ia64_rse_skip_regs(pa.bsp, pa.cfm & 0x3f)
- (char *)pa.bsp;
memcpy( kcb->jprobes_saved_stacked_regs,
pa.bsp,
bytes );
kcb->bsp = pa.bsp;
kcb->cfm = pa.cfm;
/* save architectural state */
kcb->jprobe_saved_regs = *regs;
/* after rfi, execute the jprobe instrumented function */
regs->cr_iip = addr & ~0xFULL;
ia64_psr(regs)->ri = addr & 0xf;
regs->r1 = ((struct fnptr *)(jp->entry))->gp;
/*
* fix the return address to our jprobe_inst_return() function
* in the jprobes.S file
*/
regs->b0 = ((struct fnptr *)(jprobe_inst_return))->ip;
return 1;
}
/* ia64 does not need this */
void __kprobes jprobe_return(void)
{
}
int __kprobes longjmp_break_handler(struct kprobe *p, struct pt_regs *regs)
{
struct kprobe_ctlblk *kcb = get_kprobe_ctlblk();
int bytes;
/* restoring architectural state */
*regs = kcb->jprobe_saved_regs;
/* restoring the original argument space */
flush_register_stack();
bytes = (char *)ia64_rse_skip_regs(kcb->bsp, kcb->cfm & 0x3f)
- (char *)kcb->bsp;
memcpy( kcb->bsp,
kcb->jprobes_saved_stacked_regs,
bytes );
invalidate_stacked_regs();
preempt_enable_no_resched();
return 1;
}
static struct kprobe trampoline_p = {
.pre_handler = trampoline_probe_handler
};
int __init arch_init_kprobes(void)
{
trampoline_p.addr =
(kprobe_opcode_t *)((struct fnptr *)kretprobe_trampoline)->ip;
return register_kprobe(&trampoline_p);
}
int __kprobes arch_trampoline_kprobe(struct kprobe *p)
{
if (p->addr ==
(kprobe_opcode_t *)((struct fnptr *)kretprobe_trampoline)->ip)
return 1;
return 0;
}
| gpl-2.0 |
antaril/AGK-LOLLIPOP | sound/pci/pcxhr/pcxhr_mixer.c | 12608 | 36943 | #define __NO_VERSION__
/*
* Driver for Digigram pcxhr compatible soundcards
*
* mixer callbacks
*
* 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/time.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/mutex.h>
#include <sound/core.h>
#include "pcxhr.h"
#include "pcxhr_hwdep.h"
#include "pcxhr_core.h"
#include <sound/control.h>
#include <sound/tlv.h>
#include <sound/asoundef.h>
#include "pcxhr_mixer.h"
#include "pcxhr_mix22.h"
#define PCXHR_LINE_CAPTURE_LEVEL_MIN 0 /* -112.0 dB */
#define PCXHR_LINE_CAPTURE_LEVEL_MAX 255 /* +15.5 dB */
#define PCXHR_LINE_CAPTURE_ZERO_LEVEL 224 /* 0.0 dB ( 0 dBu -> 0 dBFS ) */
#define PCXHR_LINE_PLAYBACK_LEVEL_MIN 0 /* -104.0 dB */
#define PCXHR_LINE_PLAYBACK_LEVEL_MAX 128 /* +24.0 dB */
#define PCXHR_LINE_PLAYBACK_ZERO_LEVEL 104 /* 0.0 dB ( 0 dBFS -> 0 dBu ) */
static const DECLARE_TLV_DB_SCALE(db_scale_analog_capture, -11200, 50, 1550);
static const DECLARE_TLV_DB_SCALE(db_scale_analog_playback, -10400, 100, 2400);
static const DECLARE_TLV_DB_SCALE(db_scale_a_hr222_capture, -11150, 50, 1600);
static const DECLARE_TLV_DB_SCALE(db_scale_a_hr222_playback, -2550, 50, 2400);
static int pcxhr_update_analog_audio_level(struct snd_pcxhr *chip,
int is_capture, int channel)
{
int err, vol;
struct pcxhr_rmh rmh;
pcxhr_init_rmh(&rmh, CMD_ACCESS_IO_WRITE);
if (is_capture) {
rmh.cmd[0] |= IO_NUM_REG_IN_ANA_LEVEL;
rmh.cmd[2] = chip->analog_capture_volume[channel];
} else {
rmh.cmd[0] |= IO_NUM_REG_OUT_ANA_LEVEL;
if (chip->analog_playback_active[channel])
vol = chip->analog_playback_volume[channel];
else
vol = PCXHR_LINE_PLAYBACK_LEVEL_MIN;
/* playback analog levels are inversed */
rmh.cmd[2] = PCXHR_LINE_PLAYBACK_LEVEL_MAX - vol;
}
rmh.cmd[1] = 1 << ((2 * chip->chip_idx) + channel); /* audio mask */
rmh.cmd_len = 3;
err = pcxhr_send_msg(chip->mgr, &rmh);
if (err < 0) {
snd_printk(KERN_DEBUG "error update_analog_audio_level card(%d)"
" is_capture(%d) err(%x)\n",
chip->chip_idx, is_capture, err);
return -EINVAL;
}
return 0;
}
/*
* analog level control
*/
static int pcxhr_analog_vol_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
if (kcontrol->private_value == 0) { /* playback */
if (chip->mgr->is_hr_stereo) {
uinfo->value.integer.min =
HR222_LINE_PLAYBACK_LEVEL_MIN; /* -25 dB */
uinfo->value.integer.max =
HR222_LINE_PLAYBACK_LEVEL_MAX; /* +24 dB */
} else {
uinfo->value.integer.min =
PCXHR_LINE_PLAYBACK_LEVEL_MIN; /*-104 dB */
uinfo->value.integer.max =
PCXHR_LINE_PLAYBACK_LEVEL_MAX; /* +24 dB */
}
} else { /* capture */
if (chip->mgr->is_hr_stereo) {
uinfo->value.integer.min =
HR222_LINE_CAPTURE_LEVEL_MIN; /*-112 dB */
uinfo->value.integer.max =
HR222_LINE_CAPTURE_LEVEL_MAX; /* +15.5 dB */
} else {
uinfo->value.integer.min =
PCXHR_LINE_CAPTURE_LEVEL_MIN; /*-112 dB */
uinfo->value.integer.max =
PCXHR_LINE_CAPTURE_LEVEL_MAX; /* +15.5 dB */
}
}
return 0;
}
static int pcxhr_analog_vol_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
mutex_lock(&chip->mgr->mixer_mutex);
if (kcontrol->private_value == 0) { /* playback */
ucontrol->value.integer.value[0] = chip->analog_playback_volume[0];
ucontrol->value.integer.value[1] = chip->analog_playback_volume[1];
} else { /* capture */
ucontrol->value.integer.value[0] = chip->analog_capture_volume[0];
ucontrol->value.integer.value[1] = chip->analog_capture_volume[1];
}
mutex_unlock(&chip->mgr->mixer_mutex);
return 0;
}
static int pcxhr_analog_vol_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
int changed = 0;
int is_capture, i;
mutex_lock(&chip->mgr->mixer_mutex);
is_capture = (kcontrol->private_value != 0);
for (i = 0; i < 2; i++) {
int new_volume = ucontrol->value.integer.value[i];
int *stored_volume = is_capture ?
&chip->analog_capture_volume[i] :
&chip->analog_playback_volume[i];
if (is_capture) {
if (chip->mgr->is_hr_stereo) {
if (new_volume < HR222_LINE_CAPTURE_LEVEL_MIN ||
new_volume > HR222_LINE_CAPTURE_LEVEL_MAX)
continue;
} else {
if (new_volume < PCXHR_LINE_CAPTURE_LEVEL_MIN ||
new_volume > PCXHR_LINE_CAPTURE_LEVEL_MAX)
continue;
}
} else {
if (chip->mgr->is_hr_stereo) {
if (new_volume < HR222_LINE_PLAYBACK_LEVEL_MIN ||
new_volume > HR222_LINE_PLAYBACK_LEVEL_MAX)
continue;
} else {
if (new_volume < PCXHR_LINE_PLAYBACK_LEVEL_MIN ||
new_volume > PCXHR_LINE_PLAYBACK_LEVEL_MAX)
continue;
}
}
if (*stored_volume != new_volume) {
*stored_volume = new_volume;
changed = 1;
if (chip->mgr->is_hr_stereo)
hr222_update_analog_audio_level(chip,
is_capture, i);
else
pcxhr_update_analog_audio_level(chip,
is_capture, i);
}
}
mutex_unlock(&chip->mgr->mixer_mutex);
return changed;
}
static struct snd_kcontrol_new pcxhr_control_analog_level = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.access = (SNDRV_CTL_ELEM_ACCESS_READWRITE |
SNDRV_CTL_ELEM_ACCESS_TLV_READ),
/* name will be filled later */
.info = pcxhr_analog_vol_info,
.get = pcxhr_analog_vol_get,
.put = pcxhr_analog_vol_put,
/* tlv will be filled later */
};
/* shared */
#define pcxhr_sw_info snd_ctl_boolean_stereo_info
static int pcxhr_audio_sw_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
mutex_lock(&chip->mgr->mixer_mutex);
ucontrol->value.integer.value[0] = chip->analog_playback_active[0];
ucontrol->value.integer.value[1] = chip->analog_playback_active[1];
mutex_unlock(&chip->mgr->mixer_mutex);
return 0;
}
static int pcxhr_audio_sw_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
int i, changed = 0;
mutex_lock(&chip->mgr->mixer_mutex);
for(i = 0; i < 2; i++) {
if (chip->analog_playback_active[i] !=
ucontrol->value.integer.value[i]) {
chip->analog_playback_active[i] =
!!ucontrol->value.integer.value[i];
changed = 1;
/* update playback levels */
if (chip->mgr->is_hr_stereo)
hr222_update_analog_audio_level(chip, 0, i);
else
pcxhr_update_analog_audio_level(chip, 0, i);
}
}
mutex_unlock(&chip->mgr->mixer_mutex);
return changed;
}
static struct snd_kcontrol_new pcxhr_control_output_switch = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Master Playback Switch",
.info = pcxhr_sw_info, /* shared */
.get = pcxhr_audio_sw_get,
.put = pcxhr_audio_sw_put
};
#define PCXHR_DIGITAL_LEVEL_MIN 0x000 /* -110 dB */
#define PCXHR_DIGITAL_LEVEL_MAX 0x1ff /* +18 dB */
#define PCXHR_DIGITAL_ZERO_LEVEL 0x1b7 /* 0 dB */
static const DECLARE_TLV_DB_SCALE(db_scale_digital, -10975, 25, 1800);
#define MORE_THAN_ONE_STREAM_LEVEL 0x000001
#define VALID_STREAM_PAN_LEVEL_MASK 0x800000
#define VALID_STREAM_LEVEL_MASK 0x400000
#define VALID_STREAM_LEVEL_1_MASK 0x200000
#define VALID_STREAM_LEVEL_2_MASK 0x100000
static int pcxhr_update_playback_stream_level(struct snd_pcxhr* chip, int idx)
{
int err;
struct pcxhr_rmh rmh;
struct pcxhr_pipe *pipe = &chip->playback_pipe;
int left, right;
if (chip->digital_playback_active[idx][0])
left = chip->digital_playback_volume[idx][0];
else
left = PCXHR_DIGITAL_LEVEL_MIN;
if (chip->digital_playback_active[idx][1])
right = chip->digital_playback_volume[idx][1];
else
right = PCXHR_DIGITAL_LEVEL_MIN;
pcxhr_init_rmh(&rmh, CMD_STREAM_OUT_LEVEL_ADJUST);
/* add pipe and stream mask */
pcxhr_set_pipe_cmd_params(&rmh, 0, pipe->first_audio, 0, 1<<idx);
/* volume left->left / right->right panoramic level */
rmh.cmd[0] |= MORE_THAN_ONE_STREAM_LEVEL;
rmh.cmd[2] = VALID_STREAM_PAN_LEVEL_MASK | VALID_STREAM_LEVEL_1_MASK;
rmh.cmd[2] |= (left << 10);
rmh.cmd[3] = VALID_STREAM_PAN_LEVEL_MASK | VALID_STREAM_LEVEL_2_MASK;
rmh.cmd[3] |= right;
rmh.cmd_len = 4;
err = pcxhr_send_msg(chip->mgr, &rmh);
if (err < 0) {
snd_printk(KERN_DEBUG "error update_playback_stream_level "
"card(%d) err(%x)\n", chip->chip_idx, err);
return -EINVAL;
}
return 0;
}
#define AUDIO_IO_HAS_MUTE_LEVEL 0x400000
#define AUDIO_IO_HAS_MUTE_MONITOR_1 0x200000
#define VALID_AUDIO_IO_DIGITAL_LEVEL 0x000001
#define VALID_AUDIO_IO_MONITOR_LEVEL 0x000002
#define VALID_AUDIO_IO_MUTE_LEVEL 0x000004
#define VALID_AUDIO_IO_MUTE_MONITOR_1 0x000008
static int pcxhr_update_audio_pipe_level(struct snd_pcxhr *chip,
int capture, int channel)
{
int err;
struct pcxhr_rmh rmh;
struct pcxhr_pipe *pipe;
if (capture)
pipe = &chip->capture_pipe[0];
else
pipe = &chip->playback_pipe;
pcxhr_init_rmh(&rmh, CMD_AUDIO_LEVEL_ADJUST);
/* add channel mask */
pcxhr_set_pipe_cmd_params(&rmh, capture, 0, 0,
1 << (channel + pipe->first_audio));
/* TODO : if mask (3 << pipe->first_audio) is used, left and right
* channel will be programmed to the same params */
if (capture) {
rmh.cmd[0] |= VALID_AUDIO_IO_DIGITAL_LEVEL;
/* VALID_AUDIO_IO_MUTE_LEVEL not yet handled
* (capture pipe level) */
rmh.cmd[2] = chip->digital_capture_volume[channel];
} else {
rmh.cmd[0] |= VALID_AUDIO_IO_MONITOR_LEVEL |
VALID_AUDIO_IO_MUTE_MONITOR_1;
/* VALID_AUDIO_IO_DIGITAL_LEVEL and VALID_AUDIO_IO_MUTE_LEVEL
* not yet handled (playback pipe level)
*/
rmh.cmd[2] = chip->monitoring_volume[channel] << 10;
if (chip->monitoring_active[channel] == 0)
rmh.cmd[2] |= AUDIO_IO_HAS_MUTE_MONITOR_1;
}
rmh.cmd_len = 3;
err = pcxhr_send_msg(chip->mgr, &rmh);
if (err < 0) {
snd_printk(KERN_DEBUG "error update_audio_level(%d) err=%x\n",
chip->chip_idx, err);
return -EINVAL;
}
return 0;
}
/* shared */
static int pcxhr_digital_vol_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
uinfo->value.integer.min = PCXHR_DIGITAL_LEVEL_MIN; /* -109.5 dB */
uinfo->value.integer.max = PCXHR_DIGITAL_LEVEL_MAX; /* 18.0 dB */
return 0;
}
static int pcxhr_pcm_vol_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
int idx = snd_ctl_get_ioffidx(kcontrol, &ucontrol->id); /* index */
int *stored_volume;
int is_capture = kcontrol->private_value;
mutex_lock(&chip->mgr->mixer_mutex);
if (is_capture) /* digital capture */
stored_volume = chip->digital_capture_volume;
else /* digital playback */
stored_volume = chip->digital_playback_volume[idx];
ucontrol->value.integer.value[0] = stored_volume[0];
ucontrol->value.integer.value[1] = stored_volume[1];
mutex_unlock(&chip->mgr->mixer_mutex);
return 0;
}
static int pcxhr_pcm_vol_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
int idx = snd_ctl_get_ioffidx(kcontrol, &ucontrol->id); /* index */
int changed = 0;
int is_capture = kcontrol->private_value;
int *stored_volume;
int i;
mutex_lock(&chip->mgr->mixer_mutex);
if (is_capture) /* digital capture */
stored_volume = chip->digital_capture_volume;
else /* digital playback */
stored_volume = chip->digital_playback_volume[idx];
for (i = 0; i < 2; i++) {
int vol = ucontrol->value.integer.value[i];
if (vol < PCXHR_DIGITAL_LEVEL_MIN ||
vol > PCXHR_DIGITAL_LEVEL_MAX)
continue;
if (stored_volume[i] != vol) {
stored_volume[i] = vol;
changed = 1;
if (is_capture) /* update capture volume */
pcxhr_update_audio_pipe_level(chip, 1, i);
}
}
if (!is_capture && changed) /* update playback volume */
pcxhr_update_playback_stream_level(chip, idx);
mutex_unlock(&chip->mgr->mixer_mutex);
return changed;
}
static struct snd_kcontrol_new snd_pcxhr_pcm_vol =
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.access = (SNDRV_CTL_ELEM_ACCESS_READWRITE |
SNDRV_CTL_ELEM_ACCESS_TLV_READ),
/* name will be filled later */
/* count will be filled later */
.info = pcxhr_digital_vol_info, /* shared */
.get = pcxhr_pcm_vol_get,
.put = pcxhr_pcm_vol_put,
.tlv = { .p = db_scale_digital },
};
static int pcxhr_pcm_sw_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
int idx = snd_ctl_get_ioffidx(kcontrol, &ucontrol->id); /* index */
mutex_lock(&chip->mgr->mixer_mutex);
ucontrol->value.integer.value[0] = chip->digital_playback_active[idx][0];
ucontrol->value.integer.value[1] = chip->digital_playback_active[idx][1];
mutex_unlock(&chip->mgr->mixer_mutex);
return 0;
}
static int pcxhr_pcm_sw_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
int changed = 0;
int idx = snd_ctl_get_ioffidx(kcontrol, &ucontrol->id); /* index */
int i, j;
mutex_lock(&chip->mgr->mixer_mutex);
j = idx;
for (i = 0; i < 2; i++) {
if (chip->digital_playback_active[j][i] !=
ucontrol->value.integer.value[i]) {
chip->digital_playback_active[j][i] =
!!ucontrol->value.integer.value[i];
changed = 1;
}
}
if (changed)
pcxhr_update_playback_stream_level(chip, idx);
mutex_unlock(&chip->mgr->mixer_mutex);
return changed;
}
static struct snd_kcontrol_new pcxhr_control_pcm_switch = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "PCM Playback Switch",
.count = PCXHR_PLAYBACK_STREAMS,
.info = pcxhr_sw_info, /* shared */
.get = pcxhr_pcm_sw_get,
.put = pcxhr_pcm_sw_put
};
/*
* monitoring level control
*/
static int pcxhr_monitor_vol_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
mutex_lock(&chip->mgr->mixer_mutex);
ucontrol->value.integer.value[0] = chip->monitoring_volume[0];
ucontrol->value.integer.value[1] = chip->monitoring_volume[1];
mutex_unlock(&chip->mgr->mixer_mutex);
return 0;
}
static int pcxhr_monitor_vol_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
int changed = 0;
int i;
mutex_lock(&chip->mgr->mixer_mutex);
for (i = 0; i < 2; i++) {
if (chip->monitoring_volume[i] !=
ucontrol->value.integer.value[i]) {
chip->monitoring_volume[i] =
ucontrol->value.integer.value[i];
if (chip->monitoring_active[i])
/* update monitoring volume and mute */
/* do only when monitoring is unmuted */
pcxhr_update_audio_pipe_level(chip, 0, i);
changed = 1;
}
}
mutex_unlock(&chip->mgr->mixer_mutex);
return changed;
}
static struct snd_kcontrol_new pcxhr_control_monitor_vol = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.access = (SNDRV_CTL_ELEM_ACCESS_READWRITE |
SNDRV_CTL_ELEM_ACCESS_TLV_READ),
.name = "Monitoring Playback Volume",
.info = pcxhr_digital_vol_info, /* shared */
.get = pcxhr_monitor_vol_get,
.put = pcxhr_monitor_vol_put,
.tlv = { .p = db_scale_digital },
};
/*
* monitoring switch control
*/
static int pcxhr_monitor_sw_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
mutex_lock(&chip->mgr->mixer_mutex);
ucontrol->value.integer.value[0] = chip->monitoring_active[0];
ucontrol->value.integer.value[1] = chip->monitoring_active[1];
mutex_unlock(&chip->mgr->mixer_mutex);
return 0;
}
static int pcxhr_monitor_sw_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
int changed = 0;
int i;
mutex_lock(&chip->mgr->mixer_mutex);
for (i = 0; i < 2; i++) {
if (chip->monitoring_active[i] !=
ucontrol->value.integer.value[i]) {
chip->monitoring_active[i] =
!!ucontrol->value.integer.value[i];
changed |= (1<<i); /* mask 0x01 and 0x02 */
}
}
if (changed & 0x01)
/* update left monitoring volume and mute */
pcxhr_update_audio_pipe_level(chip, 0, 0);
if (changed & 0x02)
/* update right monitoring volume and mute */
pcxhr_update_audio_pipe_level(chip, 0, 1);
mutex_unlock(&chip->mgr->mixer_mutex);
return (changed != 0);
}
static struct snd_kcontrol_new pcxhr_control_monitor_sw = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Monitoring Playback Switch",
.info = pcxhr_sw_info, /* shared */
.get = pcxhr_monitor_sw_get,
.put = pcxhr_monitor_sw_put
};
/*
* audio source select
*/
#define PCXHR_SOURCE_AUDIO01_UER 0x000100
#define PCXHR_SOURCE_AUDIO01_SYNC 0x000200
#define PCXHR_SOURCE_AUDIO23_UER 0x000400
#define PCXHR_SOURCE_AUDIO45_UER 0x001000
#define PCXHR_SOURCE_AUDIO67_UER 0x040000
static int pcxhr_set_audio_source(struct snd_pcxhr* chip)
{
struct pcxhr_rmh rmh;
unsigned int mask, reg;
unsigned int codec;
int err, changed;
switch (chip->chip_idx) {
case 0 : mask = PCXHR_SOURCE_AUDIO01_UER; codec = CS8420_01_CS; break;
case 1 : mask = PCXHR_SOURCE_AUDIO23_UER; codec = CS8420_23_CS; break;
case 2 : mask = PCXHR_SOURCE_AUDIO45_UER; codec = CS8420_45_CS; break;
case 3 : mask = PCXHR_SOURCE_AUDIO67_UER; codec = CS8420_67_CS; break;
default: return -EINVAL;
}
if (chip->audio_capture_source != 0) {
reg = mask; /* audio source from digital plug */
} else {
reg = 0; /* audio source from analog plug */
}
/* set the input source */
pcxhr_write_io_num_reg_cont(chip->mgr, mask, reg, &changed);
/* resync them (otherwise channel inversion possible) */
if (changed) {
pcxhr_init_rmh(&rmh, CMD_RESYNC_AUDIO_INPUTS);
rmh.cmd[0] |= (1 << chip->chip_idx);
err = pcxhr_send_msg(chip->mgr, &rmh);
if (err)
return err;
}
if (chip->mgr->board_aes_in_192k) {
int i;
unsigned int src_config = 0xC0;
/* update all src configs with one call */
for (i = 0; (i < 4) && (i < chip->mgr->capture_chips); i++) {
if (chip->mgr->chip[i]->audio_capture_source == 2)
src_config |= (1 << (3 - i));
}
/* set codec SRC on off */
pcxhr_init_rmh(&rmh, CMD_ACCESS_IO_WRITE);
rmh.cmd_len = 2;
rmh.cmd[0] |= IO_NUM_REG_CONFIG_SRC;
rmh.cmd[1] = src_config;
err = pcxhr_send_msg(chip->mgr, &rmh);
} else {
int use_src = 0;
if (chip->audio_capture_source == 2)
use_src = 1;
/* set codec SRC on off */
pcxhr_init_rmh(&rmh, CMD_ACCESS_IO_WRITE);
rmh.cmd_len = 3;
rmh.cmd[0] |= IO_NUM_UER_CHIP_REG;
rmh.cmd[1] = codec;
rmh.cmd[2] = ((CS8420_DATA_FLOW_CTL & CHIP_SIG_AND_MAP_SPI) |
(use_src ? 0x41 : 0x54));
err = pcxhr_send_msg(chip->mgr, &rmh);
if (err)
return err;
rmh.cmd[2] = ((CS8420_CLOCK_SRC_CTL & CHIP_SIG_AND_MAP_SPI) |
(use_src ? 0x41 : 0x49));
err = pcxhr_send_msg(chip->mgr, &rmh);
}
return err;
}
static int pcxhr_audio_src_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
static const char *texts[5] = {
"Line", "Digital", "Digi+SRC", "Mic", "Line+Mic"
};
int i;
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
i = 2; /* no SRC, no Mic available */
if (chip->mgr->board_has_aes1) {
i = 3; /* SRC available */
if (chip->mgr->board_has_mic)
i = 5; /* Mic and MicroMix available */
}
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
uinfo->count = 1;
uinfo->value.enumerated.items = i;
if (uinfo->value.enumerated.item > (i-1))
uinfo->value.enumerated.item = i-1;
strcpy(uinfo->value.enumerated.name,
texts[uinfo->value.enumerated.item]);
return 0;
}
static int pcxhr_audio_src_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
ucontrol->value.enumerated.item[0] = chip->audio_capture_source;
return 0;
}
static int pcxhr_audio_src_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
int ret = 0;
int i = 2; /* no SRC, no Mic available */
if (chip->mgr->board_has_aes1) {
i = 3; /* SRC available */
if (chip->mgr->board_has_mic)
i = 5; /* Mic and MicroMix available */
}
if (ucontrol->value.enumerated.item[0] >= i)
return -EINVAL;
mutex_lock(&chip->mgr->mixer_mutex);
if (chip->audio_capture_source != ucontrol->value.enumerated.item[0]) {
chip->audio_capture_source = ucontrol->value.enumerated.item[0];
if (chip->mgr->is_hr_stereo)
hr222_set_audio_source(chip);
else
pcxhr_set_audio_source(chip);
ret = 1;
}
mutex_unlock(&chip->mgr->mixer_mutex);
return ret;
}
static struct snd_kcontrol_new pcxhr_control_audio_src = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Capture Source",
.info = pcxhr_audio_src_info,
.get = pcxhr_audio_src_get,
.put = pcxhr_audio_src_put,
};
/*
* clock type selection
* enum pcxhr_clock_type {
* PCXHR_CLOCK_TYPE_INTERNAL = 0,
* PCXHR_CLOCK_TYPE_WORD_CLOCK,
* PCXHR_CLOCK_TYPE_AES_SYNC,
* PCXHR_CLOCK_TYPE_AES_1,
* PCXHR_CLOCK_TYPE_AES_2,
* PCXHR_CLOCK_TYPE_AES_3,
* PCXHR_CLOCK_TYPE_AES_4,
* PCXHR_CLOCK_TYPE_MAX = PCXHR_CLOCK_TYPE_AES_4,
* HR22_CLOCK_TYPE_INTERNAL = PCXHR_CLOCK_TYPE_INTERNAL,
* HR22_CLOCK_TYPE_AES_SYNC,
* HR22_CLOCK_TYPE_AES_1,
* HR22_CLOCK_TYPE_MAX = HR22_CLOCK_TYPE_AES_1,
* };
*/
static int pcxhr_clock_type_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
static const char *textsPCXHR[7] = {
"Internal", "WordClock", "AES Sync",
"AES 1", "AES 2", "AES 3", "AES 4"
};
static const char *textsHR22[3] = {
"Internal", "AES Sync", "AES 1"
};
const char **texts;
struct pcxhr_mgr *mgr = snd_kcontrol_chip(kcontrol);
int clock_items = 2; /* at least Internal and AES Sync clock */
if (mgr->board_has_aes1) {
clock_items += mgr->capture_chips; /* add AES x */
if (!mgr->is_hr_stereo)
clock_items += 1; /* add word clock */
}
if (mgr->is_hr_stereo) {
texts = textsHR22;
snd_BUG_ON(clock_items > (HR22_CLOCK_TYPE_MAX+1));
} else {
texts = textsPCXHR;
snd_BUG_ON(clock_items > (PCXHR_CLOCK_TYPE_MAX+1));
}
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
uinfo->count = 1;
uinfo->value.enumerated.items = clock_items;
if (uinfo->value.enumerated.item >= clock_items)
uinfo->value.enumerated.item = clock_items-1;
strcpy(uinfo->value.enumerated.name,
texts[uinfo->value.enumerated.item]);
return 0;
}
static int pcxhr_clock_type_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct pcxhr_mgr *mgr = snd_kcontrol_chip(kcontrol);
ucontrol->value.enumerated.item[0] = mgr->use_clock_type;
return 0;
}
static int pcxhr_clock_type_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct pcxhr_mgr *mgr = snd_kcontrol_chip(kcontrol);
int rate, ret = 0;
unsigned int clock_items = 2; /* at least Internal and AES Sync clock */
if (mgr->board_has_aes1) {
clock_items += mgr->capture_chips; /* add AES x */
if (!mgr->is_hr_stereo)
clock_items += 1; /* add word clock */
}
if (ucontrol->value.enumerated.item[0] >= clock_items)
return -EINVAL;
mutex_lock(&mgr->mixer_mutex);
if (mgr->use_clock_type != ucontrol->value.enumerated.item[0]) {
mutex_lock(&mgr->setup_mutex);
mgr->use_clock_type = ucontrol->value.enumerated.item[0];
rate = 0;
if (mgr->use_clock_type != PCXHR_CLOCK_TYPE_INTERNAL) {
pcxhr_get_external_clock(mgr, mgr->use_clock_type,
&rate);
} else {
rate = mgr->sample_rate;
if (!rate)
rate = 48000;
}
if (rate) {
pcxhr_set_clock(mgr, rate);
if (mgr->sample_rate)
mgr->sample_rate = rate;
}
mutex_unlock(&mgr->setup_mutex);
ret = 1; /* return 1 even if the set was not done. ok ? */
}
mutex_unlock(&mgr->mixer_mutex);
return ret;
}
static struct snd_kcontrol_new pcxhr_control_clock_type = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Clock Mode",
.info = pcxhr_clock_type_info,
.get = pcxhr_clock_type_get,
.put = pcxhr_clock_type_put,
};
/*
* clock rate control
* specific control that scans the sample rates on the external plugs
*/
static int pcxhr_clock_rate_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
struct pcxhr_mgr *mgr = snd_kcontrol_chip(kcontrol);
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 3 + mgr->capture_chips;
uinfo->value.integer.min = 0; /* clock not present */
uinfo->value.integer.max = 192000; /* max sample rate 192 kHz */
return 0;
}
static int pcxhr_clock_rate_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct pcxhr_mgr *mgr = snd_kcontrol_chip(kcontrol);
int i, err, rate;
mutex_lock(&mgr->mixer_mutex);
for(i = 0; i < 3 + mgr->capture_chips; i++) {
if (i == PCXHR_CLOCK_TYPE_INTERNAL)
rate = mgr->sample_rate_real;
else {
err = pcxhr_get_external_clock(mgr, i, &rate);
if (err)
break;
}
ucontrol->value.integer.value[i] = rate;
}
mutex_unlock(&mgr->mixer_mutex);
return 0;
}
static struct snd_kcontrol_new pcxhr_control_clock_rate = {
.access = SNDRV_CTL_ELEM_ACCESS_READ,
.iface = SNDRV_CTL_ELEM_IFACE_CARD,
.name = "Clock Rates",
.info = pcxhr_clock_rate_info,
.get = pcxhr_clock_rate_get,
};
/*
* IEC958 status bits
*/
static int pcxhr_iec958_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958;
uinfo->count = 1;
return 0;
}
static int pcxhr_iec958_capture_byte(struct snd_pcxhr *chip,
int aes_idx, unsigned char *aes_bits)
{
int i, err;
unsigned char temp;
struct pcxhr_rmh rmh;
pcxhr_init_rmh(&rmh, CMD_ACCESS_IO_READ);
rmh.cmd[0] |= IO_NUM_UER_CHIP_REG;
switch (chip->chip_idx) {
/* instead of CS8420_01_CS use CS8416_01_CS for AES SYNC plug */
case 0: rmh.cmd[1] = CS8420_01_CS; break;
case 1: rmh.cmd[1] = CS8420_23_CS; break;
case 2: rmh.cmd[1] = CS8420_45_CS; break;
case 3: rmh.cmd[1] = CS8420_67_CS; break;
default: return -EINVAL;
}
if (chip->mgr->board_aes_in_192k) {
switch (aes_idx) {
case 0: rmh.cmd[2] = CS8416_CSB0; break;
case 1: rmh.cmd[2] = CS8416_CSB1; break;
case 2: rmh.cmd[2] = CS8416_CSB2; break;
case 3: rmh.cmd[2] = CS8416_CSB3; break;
case 4: rmh.cmd[2] = CS8416_CSB4; break;
default: return -EINVAL;
}
} else {
switch (aes_idx) {
/* instead of CS8420_CSB0 use CS8416_CSBx for AES SYNC plug */
case 0: rmh.cmd[2] = CS8420_CSB0; break;
case 1: rmh.cmd[2] = CS8420_CSB1; break;
case 2: rmh.cmd[2] = CS8420_CSB2; break;
case 3: rmh.cmd[2] = CS8420_CSB3; break;
case 4: rmh.cmd[2] = CS8420_CSB4; break;
default: return -EINVAL;
}
}
/* size and code the chip id for the fpga */
rmh.cmd[1] &= 0x0fffff;
/* chip signature + map for spi read */
rmh.cmd[2] &= CHIP_SIG_AND_MAP_SPI;
rmh.cmd_len = 3;
err = pcxhr_send_msg(chip->mgr, &rmh);
if (err)
return err;
if (chip->mgr->board_aes_in_192k) {
temp = (unsigned char)rmh.stat[1];
} else {
temp = 0;
/* reversed bit order (not with CS8416_01_CS) */
for (i = 0; i < 8; i++) {
temp <<= 1;
if (rmh.stat[1] & (1 << i))
temp |= 1;
}
}
snd_printdd("read iec958 AES %d byte %d = 0x%x\n",
chip->chip_idx, aes_idx, temp);
*aes_bits = temp;
return 0;
}
static int pcxhr_iec958_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
unsigned char aes_bits;
int i, err;
mutex_lock(&chip->mgr->mixer_mutex);
for(i = 0; i < 5; i++) {
if (kcontrol->private_value == 0) /* playback */
aes_bits = chip->aes_bits[i];
else { /* capture */
if (chip->mgr->is_hr_stereo)
err = hr222_iec958_capture_byte(chip, i,
&aes_bits);
else
err = pcxhr_iec958_capture_byte(chip, i,
&aes_bits);
if (err)
break;
}
ucontrol->value.iec958.status[i] = aes_bits;
}
mutex_unlock(&chip->mgr->mixer_mutex);
return 0;
}
static int pcxhr_iec958_mask_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int i;
for (i = 0; i < 5; i++)
ucontrol->value.iec958.status[i] = 0xff;
return 0;
}
static int pcxhr_iec958_update_byte(struct snd_pcxhr *chip,
int aes_idx, unsigned char aes_bits)
{
int i, err, cmd;
unsigned char new_bits = aes_bits;
unsigned char old_bits = chip->aes_bits[aes_idx];
struct pcxhr_rmh rmh;
for (i = 0; i < 8; i++) {
if ((old_bits & 0x01) != (new_bits & 0x01)) {
cmd = chip->chip_idx & 0x03; /* chip index 0..3 */
if (chip->chip_idx > 3)
/* new bit used if chip_idx>3 (PCX1222HR) */
cmd |= 1 << 22;
cmd |= ((aes_idx << 3) + i) << 2; /* add bit offset */
cmd |= (new_bits & 0x01) << 23; /* add bit value */
pcxhr_init_rmh(&rmh, CMD_ACCESS_IO_WRITE);
rmh.cmd[0] |= IO_NUM_REG_CUER;
rmh.cmd[1] = cmd;
rmh.cmd_len = 2;
snd_printdd("write iec958 AES %d byte %d bit %d (cmd %x)\n",
chip->chip_idx, aes_idx, i, cmd);
err = pcxhr_send_msg(chip->mgr, &rmh);
if (err)
return err;
}
old_bits >>= 1;
new_bits >>= 1;
}
chip->aes_bits[aes_idx] = aes_bits;
return 0;
}
static int pcxhr_iec958_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
int i, changed = 0;
/* playback */
mutex_lock(&chip->mgr->mixer_mutex);
for (i = 0; i < 5; i++) {
if (ucontrol->value.iec958.status[i] != chip->aes_bits[i]) {
if (chip->mgr->is_hr_stereo)
hr222_iec958_update_byte(chip, i,
ucontrol->value.iec958.status[i]);
else
pcxhr_iec958_update_byte(chip, i,
ucontrol->value.iec958.status[i]);
changed = 1;
}
}
mutex_unlock(&chip->mgr->mixer_mutex);
return changed;
}
static struct snd_kcontrol_new pcxhr_control_playback_iec958_mask = {
.access = SNDRV_CTL_ELEM_ACCESS_READ,
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,MASK),
.info = pcxhr_iec958_info,
.get = pcxhr_iec958_mask_get
};
static struct snd_kcontrol_new pcxhr_control_playback_iec958 = {
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,DEFAULT),
.info = pcxhr_iec958_info,
.get = pcxhr_iec958_get,
.put = pcxhr_iec958_put,
.private_value = 0 /* playback */
};
static struct snd_kcontrol_new pcxhr_control_capture_iec958_mask = {
.access = SNDRV_CTL_ELEM_ACCESS_READ,
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.name = SNDRV_CTL_NAME_IEC958("",CAPTURE,MASK),
.info = pcxhr_iec958_info,
.get = pcxhr_iec958_mask_get
};
static struct snd_kcontrol_new pcxhr_control_capture_iec958 = {
.access = SNDRV_CTL_ELEM_ACCESS_READ,
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.name = SNDRV_CTL_NAME_IEC958("",CAPTURE,DEFAULT),
.info = pcxhr_iec958_info,
.get = pcxhr_iec958_get,
.private_value = 1 /* capture */
};
static void pcxhr_init_audio_levels(struct snd_pcxhr *chip)
{
int i;
for (i = 0; i < 2; i++) {
if (chip->nb_streams_play) {
int j;
/* at boot time the digital volumes are unmuted 0dB */
for (j = 0; j < PCXHR_PLAYBACK_STREAMS; j++) {
chip->digital_playback_active[j][i] = 1;
chip->digital_playback_volume[j][i] =
PCXHR_DIGITAL_ZERO_LEVEL;
}
/* after boot, only two bits are set on the uer
* interface
*/
chip->aes_bits[0] = (IEC958_AES0_PROFESSIONAL |
IEC958_AES0_PRO_FS_48000);
#ifdef CONFIG_SND_DEBUG
/* analog volumes for playback
* (is LEVEL_MIN after boot)
*/
chip->analog_playback_active[i] = 1;
if (chip->mgr->is_hr_stereo)
chip->analog_playback_volume[i] =
HR222_LINE_PLAYBACK_ZERO_LEVEL;
else {
chip->analog_playback_volume[i] =
PCXHR_LINE_PLAYBACK_ZERO_LEVEL;
pcxhr_update_analog_audio_level(chip, 0, i);
}
#endif
/* stereo cards need to be initialised after boot */
if (chip->mgr->is_hr_stereo)
hr222_update_analog_audio_level(chip, 0, i);
}
if (chip->nb_streams_capt) {
/* at boot time the digital volumes are unmuted 0dB */
chip->digital_capture_volume[i] =
PCXHR_DIGITAL_ZERO_LEVEL;
chip->analog_capture_active = 1;
#ifdef CONFIG_SND_DEBUG
/* analog volumes for playback
* (is LEVEL_MIN after boot)
*/
if (chip->mgr->is_hr_stereo)
chip->analog_capture_volume[i] =
HR222_LINE_CAPTURE_ZERO_LEVEL;
else {
chip->analog_capture_volume[i] =
PCXHR_LINE_CAPTURE_ZERO_LEVEL;
pcxhr_update_analog_audio_level(chip, 1, i);
}
#endif
/* stereo cards need to be initialised after boot */
if (chip->mgr->is_hr_stereo)
hr222_update_analog_audio_level(chip, 1, i);
}
}
return;
}
int pcxhr_create_mixer(struct pcxhr_mgr *mgr)
{
struct snd_pcxhr *chip;
int err, i;
mutex_init(&mgr->mixer_mutex); /* can be in another place */
for (i = 0; i < mgr->num_cards; i++) {
struct snd_kcontrol_new temp;
chip = mgr->chip[i];
if (chip->nb_streams_play) {
/* analog output level control */
temp = pcxhr_control_analog_level;
temp.name = "Master Playback Volume";
temp.private_value = 0; /* playback */
if (mgr->is_hr_stereo)
temp.tlv.p = db_scale_a_hr222_playback;
else
temp.tlv.p = db_scale_analog_playback;
err = snd_ctl_add(chip->card,
snd_ctl_new1(&temp, chip));
if (err < 0)
return err;
/* output mute controls */
err = snd_ctl_add(chip->card,
snd_ctl_new1(&pcxhr_control_output_switch,
chip));
if (err < 0)
return err;
temp = snd_pcxhr_pcm_vol;
temp.name = "PCM Playback Volume";
temp.count = PCXHR_PLAYBACK_STREAMS;
temp.private_value = 0; /* playback */
err = snd_ctl_add(chip->card,
snd_ctl_new1(&temp, chip));
if (err < 0)
return err;
err = snd_ctl_add(chip->card,
snd_ctl_new1(&pcxhr_control_pcm_switch, chip));
if (err < 0)
return err;
/* IEC958 controls */
err = snd_ctl_add(chip->card,
snd_ctl_new1(&pcxhr_control_playback_iec958_mask,
chip));
if (err < 0)
return err;
err = snd_ctl_add(chip->card,
snd_ctl_new1(&pcxhr_control_playback_iec958,
chip));
if (err < 0)
return err;
}
if (chip->nb_streams_capt) {
/* analog input level control */
temp = pcxhr_control_analog_level;
temp.name = "Line Capture Volume";
temp.private_value = 1; /* capture */
if (mgr->is_hr_stereo)
temp.tlv.p = db_scale_a_hr222_capture;
else
temp.tlv.p = db_scale_analog_capture;
err = snd_ctl_add(chip->card,
snd_ctl_new1(&temp, chip));
if (err < 0)
return err;
temp = snd_pcxhr_pcm_vol;
temp.name = "PCM Capture Volume";
temp.count = 1;
temp.private_value = 1; /* capture */
err = snd_ctl_add(chip->card,
snd_ctl_new1(&temp, chip));
if (err < 0)
return err;
/* Audio source */
err = snd_ctl_add(chip->card,
snd_ctl_new1(&pcxhr_control_audio_src, chip));
if (err < 0)
return err;
/* IEC958 controls */
err = snd_ctl_add(chip->card,
snd_ctl_new1(&pcxhr_control_capture_iec958_mask,
chip));
if (err < 0)
return err;
err = snd_ctl_add(chip->card,
snd_ctl_new1(&pcxhr_control_capture_iec958,
chip));
if (err < 0)
return err;
if (mgr->is_hr_stereo) {
err = hr222_add_mic_controls(chip);
if (err < 0)
return err;
}
}
/* monitoring only if playback and capture device available */
if (chip->nb_streams_capt > 0 && chip->nb_streams_play > 0) {
/* monitoring */
err = snd_ctl_add(chip->card,
snd_ctl_new1(&pcxhr_control_monitor_vol, chip));
if (err < 0)
return err;
err = snd_ctl_add(chip->card,
snd_ctl_new1(&pcxhr_control_monitor_sw, chip));
if (err < 0)
return err;
}
if (i == 0) {
/* clock mode only one control per pcxhr */
err = snd_ctl_add(chip->card,
snd_ctl_new1(&pcxhr_control_clock_type, mgr));
if (err < 0)
return err;
/* non standard control used to scan
* the external clock presence/frequencies
*/
err = snd_ctl_add(chip->card,
snd_ctl_new1(&pcxhr_control_clock_rate, mgr));
if (err < 0)
return err;
}
/* init values for the mixer data */
pcxhr_init_audio_levels(chip);
}
return 0;
}
| gpl-2.0 |
CyanogenMod/android_kernel_samsung_crespo | sound/pci/pcxhr/pcxhr_mixer.c | 12608 | 36943 | #define __NO_VERSION__
/*
* Driver for Digigram pcxhr compatible soundcards
*
* mixer callbacks
*
* 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/time.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/mutex.h>
#include <sound/core.h>
#include "pcxhr.h"
#include "pcxhr_hwdep.h"
#include "pcxhr_core.h"
#include <sound/control.h>
#include <sound/tlv.h>
#include <sound/asoundef.h>
#include "pcxhr_mixer.h"
#include "pcxhr_mix22.h"
#define PCXHR_LINE_CAPTURE_LEVEL_MIN 0 /* -112.0 dB */
#define PCXHR_LINE_CAPTURE_LEVEL_MAX 255 /* +15.5 dB */
#define PCXHR_LINE_CAPTURE_ZERO_LEVEL 224 /* 0.0 dB ( 0 dBu -> 0 dBFS ) */
#define PCXHR_LINE_PLAYBACK_LEVEL_MIN 0 /* -104.0 dB */
#define PCXHR_LINE_PLAYBACK_LEVEL_MAX 128 /* +24.0 dB */
#define PCXHR_LINE_PLAYBACK_ZERO_LEVEL 104 /* 0.0 dB ( 0 dBFS -> 0 dBu ) */
static const DECLARE_TLV_DB_SCALE(db_scale_analog_capture, -11200, 50, 1550);
static const DECLARE_TLV_DB_SCALE(db_scale_analog_playback, -10400, 100, 2400);
static const DECLARE_TLV_DB_SCALE(db_scale_a_hr222_capture, -11150, 50, 1600);
static const DECLARE_TLV_DB_SCALE(db_scale_a_hr222_playback, -2550, 50, 2400);
static int pcxhr_update_analog_audio_level(struct snd_pcxhr *chip,
int is_capture, int channel)
{
int err, vol;
struct pcxhr_rmh rmh;
pcxhr_init_rmh(&rmh, CMD_ACCESS_IO_WRITE);
if (is_capture) {
rmh.cmd[0] |= IO_NUM_REG_IN_ANA_LEVEL;
rmh.cmd[2] = chip->analog_capture_volume[channel];
} else {
rmh.cmd[0] |= IO_NUM_REG_OUT_ANA_LEVEL;
if (chip->analog_playback_active[channel])
vol = chip->analog_playback_volume[channel];
else
vol = PCXHR_LINE_PLAYBACK_LEVEL_MIN;
/* playback analog levels are inversed */
rmh.cmd[2] = PCXHR_LINE_PLAYBACK_LEVEL_MAX - vol;
}
rmh.cmd[1] = 1 << ((2 * chip->chip_idx) + channel); /* audio mask */
rmh.cmd_len = 3;
err = pcxhr_send_msg(chip->mgr, &rmh);
if (err < 0) {
snd_printk(KERN_DEBUG "error update_analog_audio_level card(%d)"
" is_capture(%d) err(%x)\n",
chip->chip_idx, is_capture, err);
return -EINVAL;
}
return 0;
}
/*
* analog level control
*/
static int pcxhr_analog_vol_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
if (kcontrol->private_value == 0) { /* playback */
if (chip->mgr->is_hr_stereo) {
uinfo->value.integer.min =
HR222_LINE_PLAYBACK_LEVEL_MIN; /* -25 dB */
uinfo->value.integer.max =
HR222_LINE_PLAYBACK_LEVEL_MAX; /* +24 dB */
} else {
uinfo->value.integer.min =
PCXHR_LINE_PLAYBACK_LEVEL_MIN; /*-104 dB */
uinfo->value.integer.max =
PCXHR_LINE_PLAYBACK_LEVEL_MAX; /* +24 dB */
}
} else { /* capture */
if (chip->mgr->is_hr_stereo) {
uinfo->value.integer.min =
HR222_LINE_CAPTURE_LEVEL_MIN; /*-112 dB */
uinfo->value.integer.max =
HR222_LINE_CAPTURE_LEVEL_MAX; /* +15.5 dB */
} else {
uinfo->value.integer.min =
PCXHR_LINE_CAPTURE_LEVEL_MIN; /*-112 dB */
uinfo->value.integer.max =
PCXHR_LINE_CAPTURE_LEVEL_MAX; /* +15.5 dB */
}
}
return 0;
}
static int pcxhr_analog_vol_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
mutex_lock(&chip->mgr->mixer_mutex);
if (kcontrol->private_value == 0) { /* playback */
ucontrol->value.integer.value[0] = chip->analog_playback_volume[0];
ucontrol->value.integer.value[1] = chip->analog_playback_volume[1];
} else { /* capture */
ucontrol->value.integer.value[0] = chip->analog_capture_volume[0];
ucontrol->value.integer.value[1] = chip->analog_capture_volume[1];
}
mutex_unlock(&chip->mgr->mixer_mutex);
return 0;
}
static int pcxhr_analog_vol_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
int changed = 0;
int is_capture, i;
mutex_lock(&chip->mgr->mixer_mutex);
is_capture = (kcontrol->private_value != 0);
for (i = 0; i < 2; i++) {
int new_volume = ucontrol->value.integer.value[i];
int *stored_volume = is_capture ?
&chip->analog_capture_volume[i] :
&chip->analog_playback_volume[i];
if (is_capture) {
if (chip->mgr->is_hr_stereo) {
if (new_volume < HR222_LINE_CAPTURE_LEVEL_MIN ||
new_volume > HR222_LINE_CAPTURE_LEVEL_MAX)
continue;
} else {
if (new_volume < PCXHR_LINE_CAPTURE_LEVEL_MIN ||
new_volume > PCXHR_LINE_CAPTURE_LEVEL_MAX)
continue;
}
} else {
if (chip->mgr->is_hr_stereo) {
if (new_volume < HR222_LINE_PLAYBACK_LEVEL_MIN ||
new_volume > HR222_LINE_PLAYBACK_LEVEL_MAX)
continue;
} else {
if (new_volume < PCXHR_LINE_PLAYBACK_LEVEL_MIN ||
new_volume > PCXHR_LINE_PLAYBACK_LEVEL_MAX)
continue;
}
}
if (*stored_volume != new_volume) {
*stored_volume = new_volume;
changed = 1;
if (chip->mgr->is_hr_stereo)
hr222_update_analog_audio_level(chip,
is_capture, i);
else
pcxhr_update_analog_audio_level(chip,
is_capture, i);
}
}
mutex_unlock(&chip->mgr->mixer_mutex);
return changed;
}
static struct snd_kcontrol_new pcxhr_control_analog_level = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.access = (SNDRV_CTL_ELEM_ACCESS_READWRITE |
SNDRV_CTL_ELEM_ACCESS_TLV_READ),
/* name will be filled later */
.info = pcxhr_analog_vol_info,
.get = pcxhr_analog_vol_get,
.put = pcxhr_analog_vol_put,
/* tlv will be filled later */
};
/* shared */
#define pcxhr_sw_info snd_ctl_boolean_stereo_info
static int pcxhr_audio_sw_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
mutex_lock(&chip->mgr->mixer_mutex);
ucontrol->value.integer.value[0] = chip->analog_playback_active[0];
ucontrol->value.integer.value[1] = chip->analog_playback_active[1];
mutex_unlock(&chip->mgr->mixer_mutex);
return 0;
}
static int pcxhr_audio_sw_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
int i, changed = 0;
mutex_lock(&chip->mgr->mixer_mutex);
for(i = 0; i < 2; i++) {
if (chip->analog_playback_active[i] !=
ucontrol->value.integer.value[i]) {
chip->analog_playback_active[i] =
!!ucontrol->value.integer.value[i];
changed = 1;
/* update playback levels */
if (chip->mgr->is_hr_stereo)
hr222_update_analog_audio_level(chip, 0, i);
else
pcxhr_update_analog_audio_level(chip, 0, i);
}
}
mutex_unlock(&chip->mgr->mixer_mutex);
return changed;
}
static struct snd_kcontrol_new pcxhr_control_output_switch = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Master Playback Switch",
.info = pcxhr_sw_info, /* shared */
.get = pcxhr_audio_sw_get,
.put = pcxhr_audio_sw_put
};
#define PCXHR_DIGITAL_LEVEL_MIN 0x000 /* -110 dB */
#define PCXHR_DIGITAL_LEVEL_MAX 0x1ff /* +18 dB */
#define PCXHR_DIGITAL_ZERO_LEVEL 0x1b7 /* 0 dB */
static const DECLARE_TLV_DB_SCALE(db_scale_digital, -10975, 25, 1800);
#define MORE_THAN_ONE_STREAM_LEVEL 0x000001
#define VALID_STREAM_PAN_LEVEL_MASK 0x800000
#define VALID_STREAM_LEVEL_MASK 0x400000
#define VALID_STREAM_LEVEL_1_MASK 0x200000
#define VALID_STREAM_LEVEL_2_MASK 0x100000
static int pcxhr_update_playback_stream_level(struct snd_pcxhr* chip, int idx)
{
int err;
struct pcxhr_rmh rmh;
struct pcxhr_pipe *pipe = &chip->playback_pipe;
int left, right;
if (chip->digital_playback_active[idx][0])
left = chip->digital_playback_volume[idx][0];
else
left = PCXHR_DIGITAL_LEVEL_MIN;
if (chip->digital_playback_active[idx][1])
right = chip->digital_playback_volume[idx][1];
else
right = PCXHR_DIGITAL_LEVEL_MIN;
pcxhr_init_rmh(&rmh, CMD_STREAM_OUT_LEVEL_ADJUST);
/* add pipe and stream mask */
pcxhr_set_pipe_cmd_params(&rmh, 0, pipe->first_audio, 0, 1<<idx);
/* volume left->left / right->right panoramic level */
rmh.cmd[0] |= MORE_THAN_ONE_STREAM_LEVEL;
rmh.cmd[2] = VALID_STREAM_PAN_LEVEL_MASK | VALID_STREAM_LEVEL_1_MASK;
rmh.cmd[2] |= (left << 10);
rmh.cmd[3] = VALID_STREAM_PAN_LEVEL_MASK | VALID_STREAM_LEVEL_2_MASK;
rmh.cmd[3] |= right;
rmh.cmd_len = 4;
err = pcxhr_send_msg(chip->mgr, &rmh);
if (err < 0) {
snd_printk(KERN_DEBUG "error update_playback_stream_level "
"card(%d) err(%x)\n", chip->chip_idx, err);
return -EINVAL;
}
return 0;
}
#define AUDIO_IO_HAS_MUTE_LEVEL 0x400000
#define AUDIO_IO_HAS_MUTE_MONITOR_1 0x200000
#define VALID_AUDIO_IO_DIGITAL_LEVEL 0x000001
#define VALID_AUDIO_IO_MONITOR_LEVEL 0x000002
#define VALID_AUDIO_IO_MUTE_LEVEL 0x000004
#define VALID_AUDIO_IO_MUTE_MONITOR_1 0x000008
static int pcxhr_update_audio_pipe_level(struct snd_pcxhr *chip,
int capture, int channel)
{
int err;
struct pcxhr_rmh rmh;
struct pcxhr_pipe *pipe;
if (capture)
pipe = &chip->capture_pipe[0];
else
pipe = &chip->playback_pipe;
pcxhr_init_rmh(&rmh, CMD_AUDIO_LEVEL_ADJUST);
/* add channel mask */
pcxhr_set_pipe_cmd_params(&rmh, capture, 0, 0,
1 << (channel + pipe->first_audio));
/* TODO : if mask (3 << pipe->first_audio) is used, left and right
* channel will be programmed to the same params */
if (capture) {
rmh.cmd[0] |= VALID_AUDIO_IO_DIGITAL_LEVEL;
/* VALID_AUDIO_IO_MUTE_LEVEL not yet handled
* (capture pipe level) */
rmh.cmd[2] = chip->digital_capture_volume[channel];
} else {
rmh.cmd[0] |= VALID_AUDIO_IO_MONITOR_LEVEL |
VALID_AUDIO_IO_MUTE_MONITOR_1;
/* VALID_AUDIO_IO_DIGITAL_LEVEL and VALID_AUDIO_IO_MUTE_LEVEL
* not yet handled (playback pipe level)
*/
rmh.cmd[2] = chip->monitoring_volume[channel] << 10;
if (chip->monitoring_active[channel] == 0)
rmh.cmd[2] |= AUDIO_IO_HAS_MUTE_MONITOR_1;
}
rmh.cmd_len = 3;
err = pcxhr_send_msg(chip->mgr, &rmh);
if (err < 0) {
snd_printk(KERN_DEBUG "error update_audio_level(%d) err=%x\n",
chip->chip_idx, err);
return -EINVAL;
}
return 0;
}
/* shared */
static int pcxhr_digital_vol_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
uinfo->value.integer.min = PCXHR_DIGITAL_LEVEL_MIN; /* -109.5 dB */
uinfo->value.integer.max = PCXHR_DIGITAL_LEVEL_MAX; /* 18.0 dB */
return 0;
}
static int pcxhr_pcm_vol_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
int idx = snd_ctl_get_ioffidx(kcontrol, &ucontrol->id); /* index */
int *stored_volume;
int is_capture = kcontrol->private_value;
mutex_lock(&chip->mgr->mixer_mutex);
if (is_capture) /* digital capture */
stored_volume = chip->digital_capture_volume;
else /* digital playback */
stored_volume = chip->digital_playback_volume[idx];
ucontrol->value.integer.value[0] = stored_volume[0];
ucontrol->value.integer.value[1] = stored_volume[1];
mutex_unlock(&chip->mgr->mixer_mutex);
return 0;
}
static int pcxhr_pcm_vol_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
int idx = snd_ctl_get_ioffidx(kcontrol, &ucontrol->id); /* index */
int changed = 0;
int is_capture = kcontrol->private_value;
int *stored_volume;
int i;
mutex_lock(&chip->mgr->mixer_mutex);
if (is_capture) /* digital capture */
stored_volume = chip->digital_capture_volume;
else /* digital playback */
stored_volume = chip->digital_playback_volume[idx];
for (i = 0; i < 2; i++) {
int vol = ucontrol->value.integer.value[i];
if (vol < PCXHR_DIGITAL_LEVEL_MIN ||
vol > PCXHR_DIGITAL_LEVEL_MAX)
continue;
if (stored_volume[i] != vol) {
stored_volume[i] = vol;
changed = 1;
if (is_capture) /* update capture volume */
pcxhr_update_audio_pipe_level(chip, 1, i);
}
}
if (!is_capture && changed) /* update playback volume */
pcxhr_update_playback_stream_level(chip, idx);
mutex_unlock(&chip->mgr->mixer_mutex);
return changed;
}
static struct snd_kcontrol_new snd_pcxhr_pcm_vol =
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.access = (SNDRV_CTL_ELEM_ACCESS_READWRITE |
SNDRV_CTL_ELEM_ACCESS_TLV_READ),
/* name will be filled later */
/* count will be filled later */
.info = pcxhr_digital_vol_info, /* shared */
.get = pcxhr_pcm_vol_get,
.put = pcxhr_pcm_vol_put,
.tlv = { .p = db_scale_digital },
};
static int pcxhr_pcm_sw_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
int idx = snd_ctl_get_ioffidx(kcontrol, &ucontrol->id); /* index */
mutex_lock(&chip->mgr->mixer_mutex);
ucontrol->value.integer.value[0] = chip->digital_playback_active[idx][0];
ucontrol->value.integer.value[1] = chip->digital_playback_active[idx][1];
mutex_unlock(&chip->mgr->mixer_mutex);
return 0;
}
static int pcxhr_pcm_sw_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
int changed = 0;
int idx = snd_ctl_get_ioffidx(kcontrol, &ucontrol->id); /* index */
int i, j;
mutex_lock(&chip->mgr->mixer_mutex);
j = idx;
for (i = 0; i < 2; i++) {
if (chip->digital_playback_active[j][i] !=
ucontrol->value.integer.value[i]) {
chip->digital_playback_active[j][i] =
!!ucontrol->value.integer.value[i];
changed = 1;
}
}
if (changed)
pcxhr_update_playback_stream_level(chip, idx);
mutex_unlock(&chip->mgr->mixer_mutex);
return changed;
}
static struct snd_kcontrol_new pcxhr_control_pcm_switch = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "PCM Playback Switch",
.count = PCXHR_PLAYBACK_STREAMS,
.info = pcxhr_sw_info, /* shared */
.get = pcxhr_pcm_sw_get,
.put = pcxhr_pcm_sw_put
};
/*
* monitoring level control
*/
static int pcxhr_monitor_vol_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
mutex_lock(&chip->mgr->mixer_mutex);
ucontrol->value.integer.value[0] = chip->monitoring_volume[0];
ucontrol->value.integer.value[1] = chip->monitoring_volume[1];
mutex_unlock(&chip->mgr->mixer_mutex);
return 0;
}
static int pcxhr_monitor_vol_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
int changed = 0;
int i;
mutex_lock(&chip->mgr->mixer_mutex);
for (i = 0; i < 2; i++) {
if (chip->monitoring_volume[i] !=
ucontrol->value.integer.value[i]) {
chip->monitoring_volume[i] =
ucontrol->value.integer.value[i];
if (chip->monitoring_active[i])
/* update monitoring volume and mute */
/* do only when monitoring is unmuted */
pcxhr_update_audio_pipe_level(chip, 0, i);
changed = 1;
}
}
mutex_unlock(&chip->mgr->mixer_mutex);
return changed;
}
static struct snd_kcontrol_new pcxhr_control_monitor_vol = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.access = (SNDRV_CTL_ELEM_ACCESS_READWRITE |
SNDRV_CTL_ELEM_ACCESS_TLV_READ),
.name = "Monitoring Playback Volume",
.info = pcxhr_digital_vol_info, /* shared */
.get = pcxhr_monitor_vol_get,
.put = pcxhr_monitor_vol_put,
.tlv = { .p = db_scale_digital },
};
/*
* monitoring switch control
*/
static int pcxhr_monitor_sw_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
mutex_lock(&chip->mgr->mixer_mutex);
ucontrol->value.integer.value[0] = chip->monitoring_active[0];
ucontrol->value.integer.value[1] = chip->monitoring_active[1];
mutex_unlock(&chip->mgr->mixer_mutex);
return 0;
}
static int pcxhr_monitor_sw_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
int changed = 0;
int i;
mutex_lock(&chip->mgr->mixer_mutex);
for (i = 0; i < 2; i++) {
if (chip->monitoring_active[i] !=
ucontrol->value.integer.value[i]) {
chip->monitoring_active[i] =
!!ucontrol->value.integer.value[i];
changed |= (1<<i); /* mask 0x01 and 0x02 */
}
}
if (changed & 0x01)
/* update left monitoring volume and mute */
pcxhr_update_audio_pipe_level(chip, 0, 0);
if (changed & 0x02)
/* update right monitoring volume and mute */
pcxhr_update_audio_pipe_level(chip, 0, 1);
mutex_unlock(&chip->mgr->mixer_mutex);
return (changed != 0);
}
static struct snd_kcontrol_new pcxhr_control_monitor_sw = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Monitoring Playback Switch",
.info = pcxhr_sw_info, /* shared */
.get = pcxhr_monitor_sw_get,
.put = pcxhr_monitor_sw_put
};
/*
* audio source select
*/
#define PCXHR_SOURCE_AUDIO01_UER 0x000100
#define PCXHR_SOURCE_AUDIO01_SYNC 0x000200
#define PCXHR_SOURCE_AUDIO23_UER 0x000400
#define PCXHR_SOURCE_AUDIO45_UER 0x001000
#define PCXHR_SOURCE_AUDIO67_UER 0x040000
static int pcxhr_set_audio_source(struct snd_pcxhr* chip)
{
struct pcxhr_rmh rmh;
unsigned int mask, reg;
unsigned int codec;
int err, changed;
switch (chip->chip_idx) {
case 0 : mask = PCXHR_SOURCE_AUDIO01_UER; codec = CS8420_01_CS; break;
case 1 : mask = PCXHR_SOURCE_AUDIO23_UER; codec = CS8420_23_CS; break;
case 2 : mask = PCXHR_SOURCE_AUDIO45_UER; codec = CS8420_45_CS; break;
case 3 : mask = PCXHR_SOURCE_AUDIO67_UER; codec = CS8420_67_CS; break;
default: return -EINVAL;
}
if (chip->audio_capture_source != 0) {
reg = mask; /* audio source from digital plug */
} else {
reg = 0; /* audio source from analog plug */
}
/* set the input source */
pcxhr_write_io_num_reg_cont(chip->mgr, mask, reg, &changed);
/* resync them (otherwise channel inversion possible) */
if (changed) {
pcxhr_init_rmh(&rmh, CMD_RESYNC_AUDIO_INPUTS);
rmh.cmd[0] |= (1 << chip->chip_idx);
err = pcxhr_send_msg(chip->mgr, &rmh);
if (err)
return err;
}
if (chip->mgr->board_aes_in_192k) {
int i;
unsigned int src_config = 0xC0;
/* update all src configs with one call */
for (i = 0; (i < 4) && (i < chip->mgr->capture_chips); i++) {
if (chip->mgr->chip[i]->audio_capture_source == 2)
src_config |= (1 << (3 - i));
}
/* set codec SRC on off */
pcxhr_init_rmh(&rmh, CMD_ACCESS_IO_WRITE);
rmh.cmd_len = 2;
rmh.cmd[0] |= IO_NUM_REG_CONFIG_SRC;
rmh.cmd[1] = src_config;
err = pcxhr_send_msg(chip->mgr, &rmh);
} else {
int use_src = 0;
if (chip->audio_capture_source == 2)
use_src = 1;
/* set codec SRC on off */
pcxhr_init_rmh(&rmh, CMD_ACCESS_IO_WRITE);
rmh.cmd_len = 3;
rmh.cmd[0] |= IO_NUM_UER_CHIP_REG;
rmh.cmd[1] = codec;
rmh.cmd[2] = ((CS8420_DATA_FLOW_CTL & CHIP_SIG_AND_MAP_SPI) |
(use_src ? 0x41 : 0x54));
err = pcxhr_send_msg(chip->mgr, &rmh);
if (err)
return err;
rmh.cmd[2] = ((CS8420_CLOCK_SRC_CTL & CHIP_SIG_AND_MAP_SPI) |
(use_src ? 0x41 : 0x49));
err = pcxhr_send_msg(chip->mgr, &rmh);
}
return err;
}
static int pcxhr_audio_src_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
static const char *texts[5] = {
"Line", "Digital", "Digi+SRC", "Mic", "Line+Mic"
};
int i;
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
i = 2; /* no SRC, no Mic available */
if (chip->mgr->board_has_aes1) {
i = 3; /* SRC available */
if (chip->mgr->board_has_mic)
i = 5; /* Mic and MicroMix available */
}
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
uinfo->count = 1;
uinfo->value.enumerated.items = i;
if (uinfo->value.enumerated.item > (i-1))
uinfo->value.enumerated.item = i-1;
strcpy(uinfo->value.enumerated.name,
texts[uinfo->value.enumerated.item]);
return 0;
}
static int pcxhr_audio_src_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
ucontrol->value.enumerated.item[0] = chip->audio_capture_source;
return 0;
}
static int pcxhr_audio_src_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
int ret = 0;
int i = 2; /* no SRC, no Mic available */
if (chip->mgr->board_has_aes1) {
i = 3; /* SRC available */
if (chip->mgr->board_has_mic)
i = 5; /* Mic and MicroMix available */
}
if (ucontrol->value.enumerated.item[0] >= i)
return -EINVAL;
mutex_lock(&chip->mgr->mixer_mutex);
if (chip->audio_capture_source != ucontrol->value.enumerated.item[0]) {
chip->audio_capture_source = ucontrol->value.enumerated.item[0];
if (chip->mgr->is_hr_stereo)
hr222_set_audio_source(chip);
else
pcxhr_set_audio_source(chip);
ret = 1;
}
mutex_unlock(&chip->mgr->mixer_mutex);
return ret;
}
static struct snd_kcontrol_new pcxhr_control_audio_src = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Capture Source",
.info = pcxhr_audio_src_info,
.get = pcxhr_audio_src_get,
.put = pcxhr_audio_src_put,
};
/*
* clock type selection
* enum pcxhr_clock_type {
* PCXHR_CLOCK_TYPE_INTERNAL = 0,
* PCXHR_CLOCK_TYPE_WORD_CLOCK,
* PCXHR_CLOCK_TYPE_AES_SYNC,
* PCXHR_CLOCK_TYPE_AES_1,
* PCXHR_CLOCK_TYPE_AES_2,
* PCXHR_CLOCK_TYPE_AES_3,
* PCXHR_CLOCK_TYPE_AES_4,
* PCXHR_CLOCK_TYPE_MAX = PCXHR_CLOCK_TYPE_AES_4,
* HR22_CLOCK_TYPE_INTERNAL = PCXHR_CLOCK_TYPE_INTERNAL,
* HR22_CLOCK_TYPE_AES_SYNC,
* HR22_CLOCK_TYPE_AES_1,
* HR22_CLOCK_TYPE_MAX = HR22_CLOCK_TYPE_AES_1,
* };
*/
static int pcxhr_clock_type_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
static const char *textsPCXHR[7] = {
"Internal", "WordClock", "AES Sync",
"AES 1", "AES 2", "AES 3", "AES 4"
};
static const char *textsHR22[3] = {
"Internal", "AES Sync", "AES 1"
};
const char **texts;
struct pcxhr_mgr *mgr = snd_kcontrol_chip(kcontrol);
int clock_items = 2; /* at least Internal and AES Sync clock */
if (mgr->board_has_aes1) {
clock_items += mgr->capture_chips; /* add AES x */
if (!mgr->is_hr_stereo)
clock_items += 1; /* add word clock */
}
if (mgr->is_hr_stereo) {
texts = textsHR22;
snd_BUG_ON(clock_items > (HR22_CLOCK_TYPE_MAX+1));
} else {
texts = textsPCXHR;
snd_BUG_ON(clock_items > (PCXHR_CLOCK_TYPE_MAX+1));
}
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
uinfo->count = 1;
uinfo->value.enumerated.items = clock_items;
if (uinfo->value.enumerated.item >= clock_items)
uinfo->value.enumerated.item = clock_items-1;
strcpy(uinfo->value.enumerated.name,
texts[uinfo->value.enumerated.item]);
return 0;
}
static int pcxhr_clock_type_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct pcxhr_mgr *mgr = snd_kcontrol_chip(kcontrol);
ucontrol->value.enumerated.item[0] = mgr->use_clock_type;
return 0;
}
static int pcxhr_clock_type_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct pcxhr_mgr *mgr = snd_kcontrol_chip(kcontrol);
int rate, ret = 0;
unsigned int clock_items = 2; /* at least Internal and AES Sync clock */
if (mgr->board_has_aes1) {
clock_items += mgr->capture_chips; /* add AES x */
if (!mgr->is_hr_stereo)
clock_items += 1; /* add word clock */
}
if (ucontrol->value.enumerated.item[0] >= clock_items)
return -EINVAL;
mutex_lock(&mgr->mixer_mutex);
if (mgr->use_clock_type != ucontrol->value.enumerated.item[0]) {
mutex_lock(&mgr->setup_mutex);
mgr->use_clock_type = ucontrol->value.enumerated.item[0];
rate = 0;
if (mgr->use_clock_type != PCXHR_CLOCK_TYPE_INTERNAL) {
pcxhr_get_external_clock(mgr, mgr->use_clock_type,
&rate);
} else {
rate = mgr->sample_rate;
if (!rate)
rate = 48000;
}
if (rate) {
pcxhr_set_clock(mgr, rate);
if (mgr->sample_rate)
mgr->sample_rate = rate;
}
mutex_unlock(&mgr->setup_mutex);
ret = 1; /* return 1 even if the set was not done. ok ? */
}
mutex_unlock(&mgr->mixer_mutex);
return ret;
}
static struct snd_kcontrol_new pcxhr_control_clock_type = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Clock Mode",
.info = pcxhr_clock_type_info,
.get = pcxhr_clock_type_get,
.put = pcxhr_clock_type_put,
};
/*
* clock rate control
* specific control that scans the sample rates on the external plugs
*/
static int pcxhr_clock_rate_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
struct pcxhr_mgr *mgr = snd_kcontrol_chip(kcontrol);
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 3 + mgr->capture_chips;
uinfo->value.integer.min = 0; /* clock not present */
uinfo->value.integer.max = 192000; /* max sample rate 192 kHz */
return 0;
}
static int pcxhr_clock_rate_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct pcxhr_mgr *mgr = snd_kcontrol_chip(kcontrol);
int i, err, rate;
mutex_lock(&mgr->mixer_mutex);
for(i = 0; i < 3 + mgr->capture_chips; i++) {
if (i == PCXHR_CLOCK_TYPE_INTERNAL)
rate = mgr->sample_rate_real;
else {
err = pcxhr_get_external_clock(mgr, i, &rate);
if (err)
break;
}
ucontrol->value.integer.value[i] = rate;
}
mutex_unlock(&mgr->mixer_mutex);
return 0;
}
static struct snd_kcontrol_new pcxhr_control_clock_rate = {
.access = SNDRV_CTL_ELEM_ACCESS_READ,
.iface = SNDRV_CTL_ELEM_IFACE_CARD,
.name = "Clock Rates",
.info = pcxhr_clock_rate_info,
.get = pcxhr_clock_rate_get,
};
/*
* IEC958 status bits
*/
static int pcxhr_iec958_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958;
uinfo->count = 1;
return 0;
}
static int pcxhr_iec958_capture_byte(struct snd_pcxhr *chip,
int aes_idx, unsigned char *aes_bits)
{
int i, err;
unsigned char temp;
struct pcxhr_rmh rmh;
pcxhr_init_rmh(&rmh, CMD_ACCESS_IO_READ);
rmh.cmd[0] |= IO_NUM_UER_CHIP_REG;
switch (chip->chip_idx) {
/* instead of CS8420_01_CS use CS8416_01_CS for AES SYNC plug */
case 0: rmh.cmd[1] = CS8420_01_CS; break;
case 1: rmh.cmd[1] = CS8420_23_CS; break;
case 2: rmh.cmd[1] = CS8420_45_CS; break;
case 3: rmh.cmd[1] = CS8420_67_CS; break;
default: return -EINVAL;
}
if (chip->mgr->board_aes_in_192k) {
switch (aes_idx) {
case 0: rmh.cmd[2] = CS8416_CSB0; break;
case 1: rmh.cmd[2] = CS8416_CSB1; break;
case 2: rmh.cmd[2] = CS8416_CSB2; break;
case 3: rmh.cmd[2] = CS8416_CSB3; break;
case 4: rmh.cmd[2] = CS8416_CSB4; break;
default: return -EINVAL;
}
} else {
switch (aes_idx) {
/* instead of CS8420_CSB0 use CS8416_CSBx for AES SYNC plug */
case 0: rmh.cmd[2] = CS8420_CSB0; break;
case 1: rmh.cmd[2] = CS8420_CSB1; break;
case 2: rmh.cmd[2] = CS8420_CSB2; break;
case 3: rmh.cmd[2] = CS8420_CSB3; break;
case 4: rmh.cmd[2] = CS8420_CSB4; break;
default: return -EINVAL;
}
}
/* size and code the chip id for the fpga */
rmh.cmd[1] &= 0x0fffff;
/* chip signature + map for spi read */
rmh.cmd[2] &= CHIP_SIG_AND_MAP_SPI;
rmh.cmd_len = 3;
err = pcxhr_send_msg(chip->mgr, &rmh);
if (err)
return err;
if (chip->mgr->board_aes_in_192k) {
temp = (unsigned char)rmh.stat[1];
} else {
temp = 0;
/* reversed bit order (not with CS8416_01_CS) */
for (i = 0; i < 8; i++) {
temp <<= 1;
if (rmh.stat[1] & (1 << i))
temp |= 1;
}
}
snd_printdd("read iec958 AES %d byte %d = 0x%x\n",
chip->chip_idx, aes_idx, temp);
*aes_bits = temp;
return 0;
}
static int pcxhr_iec958_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
unsigned char aes_bits;
int i, err;
mutex_lock(&chip->mgr->mixer_mutex);
for(i = 0; i < 5; i++) {
if (kcontrol->private_value == 0) /* playback */
aes_bits = chip->aes_bits[i];
else { /* capture */
if (chip->mgr->is_hr_stereo)
err = hr222_iec958_capture_byte(chip, i,
&aes_bits);
else
err = pcxhr_iec958_capture_byte(chip, i,
&aes_bits);
if (err)
break;
}
ucontrol->value.iec958.status[i] = aes_bits;
}
mutex_unlock(&chip->mgr->mixer_mutex);
return 0;
}
static int pcxhr_iec958_mask_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int i;
for (i = 0; i < 5; i++)
ucontrol->value.iec958.status[i] = 0xff;
return 0;
}
static int pcxhr_iec958_update_byte(struct snd_pcxhr *chip,
int aes_idx, unsigned char aes_bits)
{
int i, err, cmd;
unsigned char new_bits = aes_bits;
unsigned char old_bits = chip->aes_bits[aes_idx];
struct pcxhr_rmh rmh;
for (i = 0; i < 8; i++) {
if ((old_bits & 0x01) != (new_bits & 0x01)) {
cmd = chip->chip_idx & 0x03; /* chip index 0..3 */
if (chip->chip_idx > 3)
/* new bit used if chip_idx>3 (PCX1222HR) */
cmd |= 1 << 22;
cmd |= ((aes_idx << 3) + i) << 2; /* add bit offset */
cmd |= (new_bits & 0x01) << 23; /* add bit value */
pcxhr_init_rmh(&rmh, CMD_ACCESS_IO_WRITE);
rmh.cmd[0] |= IO_NUM_REG_CUER;
rmh.cmd[1] = cmd;
rmh.cmd_len = 2;
snd_printdd("write iec958 AES %d byte %d bit %d (cmd %x)\n",
chip->chip_idx, aes_idx, i, cmd);
err = pcxhr_send_msg(chip->mgr, &rmh);
if (err)
return err;
}
old_bits >>= 1;
new_bits >>= 1;
}
chip->aes_bits[aes_idx] = aes_bits;
return 0;
}
static int pcxhr_iec958_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_pcxhr *chip = snd_kcontrol_chip(kcontrol);
int i, changed = 0;
/* playback */
mutex_lock(&chip->mgr->mixer_mutex);
for (i = 0; i < 5; i++) {
if (ucontrol->value.iec958.status[i] != chip->aes_bits[i]) {
if (chip->mgr->is_hr_stereo)
hr222_iec958_update_byte(chip, i,
ucontrol->value.iec958.status[i]);
else
pcxhr_iec958_update_byte(chip, i,
ucontrol->value.iec958.status[i]);
changed = 1;
}
}
mutex_unlock(&chip->mgr->mixer_mutex);
return changed;
}
static struct snd_kcontrol_new pcxhr_control_playback_iec958_mask = {
.access = SNDRV_CTL_ELEM_ACCESS_READ,
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,MASK),
.info = pcxhr_iec958_info,
.get = pcxhr_iec958_mask_get
};
static struct snd_kcontrol_new pcxhr_control_playback_iec958 = {
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,DEFAULT),
.info = pcxhr_iec958_info,
.get = pcxhr_iec958_get,
.put = pcxhr_iec958_put,
.private_value = 0 /* playback */
};
static struct snd_kcontrol_new pcxhr_control_capture_iec958_mask = {
.access = SNDRV_CTL_ELEM_ACCESS_READ,
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.name = SNDRV_CTL_NAME_IEC958("",CAPTURE,MASK),
.info = pcxhr_iec958_info,
.get = pcxhr_iec958_mask_get
};
static struct snd_kcontrol_new pcxhr_control_capture_iec958 = {
.access = SNDRV_CTL_ELEM_ACCESS_READ,
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.name = SNDRV_CTL_NAME_IEC958("",CAPTURE,DEFAULT),
.info = pcxhr_iec958_info,
.get = pcxhr_iec958_get,
.private_value = 1 /* capture */
};
static void pcxhr_init_audio_levels(struct snd_pcxhr *chip)
{
int i;
for (i = 0; i < 2; i++) {
if (chip->nb_streams_play) {
int j;
/* at boot time the digital volumes are unmuted 0dB */
for (j = 0; j < PCXHR_PLAYBACK_STREAMS; j++) {
chip->digital_playback_active[j][i] = 1;
chip->digital_playback_volume[j][i] =
PCXHR_DIGITAL_ZERO_LEVEL;
}
/* after boot, only two bits are set on the uer
* interface
*/
chip->aes_bits[0] = (IEC958_AES0_PROFESSIONAL |
IEC958_AES0_PRO_FS_48000);
#ifdef CONFIG_SND_DEBUG
/* analog volumes for playback
* (is LEVEL_MIN after boot)
*/
chip->analog_playback_active[i] = 1;
if (chip->mgr->is_hr_stereo)
chip->analog_playback_volume[i] =
HR222_LINE_PLAYBACK_ZERO_LEVEL;
else {
chip->analog_playback_volume[i] =
PCXHR_LINE_PLAYBACK_ZERO_LEVEL;
pcxhr_update_analog_audio_level(chip, 0, i);
}
#endif
/* stereo cards need to be initialised after boot */
if (chip->mgr->is_hr_stereo)
hr222_update_analog_audio_level(chip, 0, i);
}
if (chip->nb_streams_capt) {
/* at boot time the digital volumes are unmuted 0dB */
chip->digital_capture_volume[i] =
PCXHR_DIGITAL_ZERO_LEVEL;
chip->analog_capture_active = 1;
#ifdef CONFIG_SND_DEBUG
/* analog volumes for playback
* (is LEVEL_MIN after boot)
*/
if (chip->mgr->is_hr_stereo)
chip->analog_capture_volume[i] =
HR222_LINE_CAPTURE_ZERO_LEVEL;
else {
chip->analog_capture_volume[i] =
PCXHR_LINE_CAPTURE_ZERO_LEVEL;
pcxhr_update_analog_audio_level(chip, 1, i);
}
#endif
/* stereo cards need to be initialised after boot */
if (chip->mgr->is_hr_stereo)
hr222_update_analog_audio_level(chip, 1, i);
}
}
return;
}
int pcxhr_create_mixer(struct pcxhr_mgr *mgr)
{
struct snd_pcxhr *chip;
int err, i;
mutex_init(&mgr->mixer_mutex); /* can be in another place */
for (i = 0; i < mgr->num_cards; i++) {
struct snd_kcontrol_new temp;
chip = mgr->chip[i];
if (chip->nb_streams_play) {
/* analog output level control */
temp = pcxhr_control_analog_level;
temp.name = "Master Playback Volume";
temp.private_value = 0; /* playback */
if (mgr->is_hr_stereo)
temp.tlv.p = db_scale_a_hr222_playback;
else
temp.tlv.p = db_scale_analog_playback;
err = snd_ctl_add(chip->card,
snd_ctl_new1(&temp, chip));
if (err < 0)
return err;
/* output mute controls */
err = snd_ctl_add(chip->card,
snd_ctl_new1(&pcxhr_control_output_switch,
chip));
if (err < 0)
return err;
temp = snd_pcxhr_pcm_vol;
temp.name = "PCM Playback Volume";
temp.count = PCXHR_PLAYBACK_STREAMS;
temp.private_value = 0; /* playback */
err = snd_ctl_add(chip->card,
snd_ctl_new1(&temp, chip));
if (err < 0)
return err;
err = snd_ctl_add(chip->card,
snd_ctl_new1(&pcxhr_control_pcm_switch, chip));
if (err < 0)
return err;
/* IEC958 controls */
err = snd_ctl_add(chip->card,
snd_ctl_new1(&pcxhr_control_playback_iec958_mask,
chip));
if (err < 0)
return err;
err = snd_ctl_add(chip->card,
snd_ctl_new1(&pcxhr_control_playback_iec958,
chip));
if (err < 0)
return err;
}
if (chip->nb_streams_capt) {
/* analog input level control */
temp = pcxhr_control_analog_level;
temp.name = "Line Capture Volume";
temp.private_value = 1; /* capture */
if (mgr->is_hr_stereo)
temp.tlv.p = db_scale_a_hr222_capture;
else
temp.tlv.p = db_scale_analog_capture;
err = snd_ctl_add(chip->card,
snd_ctl_new1(&temp, chip));
if (err < 0)
return err;
temp = snd_pcxhr_pcm_vol;
temp.name = "PCM Capture Volume";
temp.count = 1;
temp.private_value = 1; /* capture */
err = snd_ctl_add(chip->card,
snd_ctl_new1(&temp, chip));
if (err < 0)
return err;
/* Audio source */
err = snd_ctl_add(chip->card,
snd_ctl_new1(&pcxhr_control_audio_src, chip));
if (err < 0)
return err;
/* IEC958 controls */
err = snd_ctl_add(chip->card,
snd_ctl_new1(&pcxhr_control_capture_iec958_mask,
chip));
if (err < 0)
return err;
err = snd_ctl_add(chip->card,
snd_ctl_new1(&pcxhr_control_capture_iec958,
chip));
if (err < 0)
return err;
if (mgr->is_hr_stereo) {
err = hr222_add_mic_controls(chip);
if (err < 0)
return err;
}
}
/* monitoring only if playback and capture device available */
if (chip->nb_streams_capt > 0 && chip->nb_streams_play > 0) {
/* monitoring */
err = snd_ctl_add(chip->card,
snd_ctl_new1(&pcxhr_control_monitor_vol, chip));
if (err < 0)
return err;
err = snd_ctl_add(chip->card,
snd_ctl_new1(&pcxhr_control_monitor_sw, chip));
if (err < 0)
return err;
}
if (i == 0) {
/* clock mode only one control per pcxhr */
err = snd_ctl_add(chip->card,
snd_ctl_new1(&pcxhr_control_clock_type, mgr));
if (err < 0)
return err;
/* non standard control used to scan
* the external clock presence/frequencies
*/
err = snd_ctl_add(chip->card,
snd_ctl_new1(&pcxhr_control_clock_rate, mgr));
if (err < 0)
return err;
}
/* init values for the mixer data */
pcxhr_init_audio_levels(chip);
}
return 0;
}
| gpl-2.0 |
MarginC/linux | drivers/video/fbdev/matrox/g450_pll.c | 14656 | 13720 | /*
*
* Hardware accelerated Matrox PCI cards - G450/G550 PLL control.
*
* (c) 2001-2002 Petr Vandrovec <vandrove@vc.cvut.cz>
*
* Portions Copyright (c) 2001 Matrox Graphics Inc.
*
* Version: 1.64 2002/06/10
*
* 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 "g450_pll.h"
#include "matroxfb_DAC1064.h"
static inline unsigned int g450_vco2f(unsigned char p, unsigned int fvco) {
return (p & 0x40) ? fvco : fvco >> ((p & 3) + 1);
}
static inline unsigned int g450_f2vco(unsigned char p, unsigned int fin) {
return (p & 0x40) ? fin : fin << ((p & 3) + 1);
}
static unsigned int g450_mnp2vco(const struct matrox_fb_info *minfo,
unsigned int mnp)
{
unsigned int m, n;
m = ((mnp >> 16) & 0x0FF) + 1;
n = ((mnp >> 7) & 0x1FE) + 4;
return (minfo->features.pll.ref_freq * n + (m >> 1)) / m;
}
unsigned int g450_mnp2f(const struct matrox_fb_info *minfo, unsigned int mnp)
{
return g450_vco2f(mnp, g450_mnp2vco(minfo, mnp));
}
static inline unsigned int pll_freq_delta(unsigned int f1, unsigned int f2) {
if (f2 < f1) {
f2 = f1 - f2;
} else {
f2 = f2 - f1;
}
return f2;
}
#define NO_MORE_MNP 0x01FFFFFF
#define G450_MNP_FREQBITS (0xFFFFFF43) /* do not mask high byte so we'll catch NO_MORE_MNP */
static unsigned int g450_nextpll(const struct matrox_fb_info *minfo,
const struct matrox_pll_limits *pi,
unsigned int *fvco, unsigned int mnp)
{
unsigned int m, n, p;
unsigned int tvco = *fvco;
m = (mnp >> 16) & 0xFF;
p = mnp & 0xFF;
do {
if (m == 0 || m == 0xFF) {
if (m == 0) {
if (p & 0x40) {
return NO_MORE_MNP;
}
if (p & 3) {
p--;
} else {
p = 0x40;
}
tvco >>= 1;
if (tvco < pi->vcomin) {
return NO_MORE_MNP;
}
*fvco = tvco;
}
p &= 0x43;
if (tvco < 550000) {
/* p |= 0x00; */
} else if (tvco < 700000) {
p |= 0x08;
} else if (tvco < 1000000) {
p |= 0x10;
} else if (tvco < 1150000) {
p |= 0x18;
} else {
p |= 0x20;
}
m = 9;
} else {
m--;
}
n = ((tvco * (m+1) + minfo->features.pll.ref_freq) / (minfo->features.pll.ref_freq * 2)) - 2;
} while (n < 0x03 || n > 0x7A);
return (m << 16) | (n << 8) | p;
}
static unsigned int g450_firstpll(const struct matrox_fb_info *minfo,
const struct matrox_pll_limits *pi,
unsigned int *vco, unsigned int fout)
{
unsigned int p;
unsigned int vcomax;
vcomax = pi->vcomax;
if (fout > (vcomax / 2)) {
if (fout > vcomax) {
*vco = vcomax;
} else {
*vco = fout;
}
p = 0x40;
} else {
unsigned int tvco;
p = 3;
tvco = g450_f2vco(p, fout);
while (p && (tvco > vcomax)) {
p--;
tvco >>= 1;
}
if (tvco < pi->vcomin) {
tvco = pi->vcomin;
}
*vco = tvco;
}
return g450_nextpll(minfo, pi, vco, 0xFF0000 | p);
}
static inline unsigned int g450_setpll(const struct matrox_fb_info *minfo,
unsigned int mnp, unsigned int pll)
{
switch (pll) {
case M_PIXEL_PLL_A:
matroxfb_DAC_out(minfo, M1064_XPIXPLLAM, mnp >> 16);
matroxfb_DAC_out(minfo, M1064_XPIXPLLAN, mnp >> 8);
matroxfb_DAC_out(minfo, M1064_XPIXPLLAP, mnp);
return M1064_XPIXPLLSTAT;
case M_PIXEL_PLL_B:
matroxfb_DAC_out(minfo, M1064_XPIXPLLBM, mnp >> 16);
matroxfb_DAC_out(minfo, M1064_XPIXPLLBN, mnp >> 8);
matroxfb_DAC_out(minfo, M1064_XPIXPLLBP, mnp);
return M1064_XPIXPLLSTAT;
case M_PIXEL_PLL_C:
matroxfb_DAC_out(minfo, M1064_XPIXPLLCM, mnp >> 16);
matroxfb_DAC_out(minfo, M1064_XPIXPLLCN, mnp >> 8);
matroxfb_DAC_out(minfo, M1064_XPIXPLLCP, mnp);
return M1064_XPIXPLLSTAT;
case M_SYSTEM_PLL:
matroxfb_DAC_out(minfo, DAC1064_XSYSPLLM, mnp >> 16);
matroxfb_DAC_out(minfo, DAC1064_XSYSPLLN, mnp >> 8);
matroxfb_DAC_out(minfo, DAC1064_XSYSPLLP, mnp);
return DAC1064_XSYSPLLSTAT;
case M_VIDEO_PLL:
matroxfb_DAC_out(minfo, M1064_XVIDPLLM, mnp >> 16);
matroxfb_DAC_out(minfo, M1064_XVIDPLLN, mnp >> 8);
matroxfb_DAC_out(minfo, M1064_XVIDPLLP, mnp);
return M1064_XVIDPLLSTAT;
}
return 0;
}
static inline unsigned int g450_cmppll(const struct matrox_fb_info *minfo,
unsigned int mnp, unsigned int pll)
{
unsigned char m = mnp >> 16;
unsigned char n = mnp >> 8;
unsigned char p = mnp;
switch (pll) {
case M_PIXEL_PLL_A:
return (matroxfb_DAC_in(minfo, M1064_XPIXPLLAM) != m ||
matroxfb_DAC_in(minfo, M1064_XPIXPLLAN) != n ||
matroxfb_DAC_in(minfo, M1064_XPIXPLLAP) != p);
case M_PIXEL_PLL_B:
return (matroxfb_DAC_in(minfo, M1064_XPIXPLLBM) != m ||
matroxfb_DAC_in(minfo, M1064_XPIXPLLBN) != n ||
matroxfb_DAC_in(minfo, M1064_XPIXPLLBP) != p);
case M_PIXEL_PLL_C:
return (matroxfb_DAC_in(minfo, M1064_XPIXPLLCM) != m ||
matroxfb_DAC_in(minfo, M1064_XPIXPLLCN) != n ||
matroxfb_DAC_in(minfo, M1064_XPIXPLLCP) != p);
case M_SYSTEM_PLL:
return (matroxfb_DAC_in(minfo, DAC1064_XSYSPLLM) != m ||
matroxfb_DAC_in(minfo, DAC1064_XSYSPLLN) != n ||
matroxfb_DAC_in(minfo, DAC1064_XSYSPLLP) != p);
case M_VIDEO_PLL:
return (matroxfb_DAC_in(minfo, M1064_XVIDPLLM) != m ||
matroxfb_DAC_in(minfo, M1064_XVIDPLLN) != n ||
matroxfb_DAC_in(minfo, M1064_XVIDPLLP) != p);
}
return 1;
}
static inline int g450_isplllocked(const struct matrox_fb_info *minfo,
unsigned int regidx)
{
unsigned int j;
for (j = 0; j < 1000; j++) {
if (matroxfb_DAC_in(minfo, regidx) & 0x40) {
unsigned int r = 0;
int i;
for (i = 0; i < 100; i++) {
r += matroxfb_DAC_in(minfo, regidx) & 0x40;
}
return r >= (90 * 0x40);
}
/* udelay(1)... but DAC_in is much slower... */
}
return 0;
}
static int g450_testpll(const struct matrox_fb_info *minfo, unsigned int mnp,
unsigned int pll)
{
return g450_isplllocked(minfo, g450_setpll(minfo, mnp, pll));
}
static void updatehwstate_clk(struct matrox_hw_state* hw, unsigned int mnp, unsigned int pll) {
switch (pll) {
case M_SYSTEM_PLL:
hw->DACclk[3] = mnp >> 16;
hw->DACclk[4] = mnp >> 8;
hw->DACclk[5] = mnp;
break;
}
}
void matroxfb_g450_setpll_cond(struct matrox_fb_info *minfo, unsigned int mnp,
unsigned int pll)
{
if (g450_cmppll(minfo, mnp, pll)) {
g450_setpll(minfo, mnp, pll);
}
}
static inline unsigned int g450_findworkingpll(struct matrox_fb_info *minfo,
unsigned int pll,
unsigned int *mnparray,
unsigned int mnpcount)
{
unsigned int found = 0;
unsigned int idx;
unsigned int mnpfound = mnparray[0];
for (idx = 0; idx < mnpcount; idx++) {
unsigned int sarray[3];
unsigned int *sptr;
{
unsigned int mnp;
sptr = sarray;
mnp = mnparray[idx];
if (mnp & 0x38) {
*sptr++ = mnp - 8;
}
if ((mnp & 0x38) != 0x38) {
*sptr++ = mnp + 8;
}
*sptr = mnp;
}
while (sptr >= sarray) {
unsigned int mnp = *sptr--;
if (g450_testpll(minfo, mnp - 0x0300, pll) &&
g450_testpll(minfo, mnp + 0x0300, pll) &&
g450_testpll(minfo, mnp - 0x0200, pll) &&
g450_testpll(minfo, mnp + 0x0200, pll) &&
g450_testpll(minfo, mnp - 0x0100, pll) &&
g450_testpll(minfo, mnp + 0x0100, pll)) {
if (g450_testpll(minfo, mnp, pll)) {
return mnp;
}
} else if (!found && g450_testpll(minfo, mnp, pll)) {
mnpfound = mnp;
found = 1;
}
}
}
g450_setpll(minfo, mnpfound, pll);
return mnpfound;
}
static void g450_addcache(struct matrox_pll_cache* ci, unsigned int mnp_key, unsigned int mnp_value) {
if (++ci->valid > ARRAY_SIZE(ci->data)) {
ci->valid = ARRAY_SIZE(ci->data);
}
memmove(ci->data + 1, ci->data, (ci->valid - 1) * sizeof(*ci->data));
ci->data[0].mnp_key = mnp_key & G450_MNP_FREQBITS;
ci->data[0].mnp_value = mnp_value;
}
static int g450_checkcache(struct matrox_fb_info *minfo,
struct matrox_pll_cache *ci, unsigned int mnp_key)
{
unsigned int i;
mnp_key &= G450_MNP_FREQBITS;
for (i = 0; i < ci->valid; i++) {
if (ci->data[i].mnp_key == mnp_key) {
unsigned int mnp;
mnp = ci->data[i].mnp_value;
if (i) {
memmove(ci->data + 1, ci->data, i * sizeof(*ci->data));
ci->data[0].mnp_key = mnp_key;
ci->data[0].mnp_value = mnp;
}
return mnp;
}
}
return NO_MORE_MNP;
}
static int __g450_setclk(struct matrox_fb_info *minfo, unsigned int fout,
unsigned int pll, unsigned int *mnparray,
unsigned int *deltaarray)
{
unsigned int mnpcount;
unsigned int pixel_vco;
const struct matrox_pll_limits* pi;
struct matrox_pll_cache* ci;
pixel_vco = 0;
switch (pll) {
case M_PIXEL_PLL_A:
case M_PIXEL_PLL_B:
case M_PIXEL_PLL_C:
{
u_int8_t tmp, xpwrctrl;
unsigned long flags;
matroxfb_DAC_lock_irqsave(flags);
xpwrctrl = matroxfb_DAC_in(minfo, M1064_XPWRCTRL);
matroxfb_DAC_out(minfo, M1064_XPWRCTRL, xpwrctrl & ~M1064_XPWRCTRL_PANELPDN);
mga_outb(M_SEQ_INDEX, M_SEQ1);
mga_outb(M_SEQ_DATA, mga_inb(M_SEQ_DATA) | M_SEQ1_SCROFF);
tmp = matroxfb_DAC_in(minfo, M1064_XPIXCLKCTRL);
tmp |= M1064_XPIXCLKCTRL_DIS;
if (!(tmp & M1064_XPIXCLKCTRL_PLL_UP)) {
tmp |= M1064_XPIXCLKCTRL_PLL_UP;
}
matroxfb_DAC_out(minfo, M1064_XPIXCLKCTRL, tmp);
/* DVI PLL preferred for frequencies up to
panel link max, standard PLL otherwise */
if (fout >= minfo->max_pixel_clock_panellink)
tmp = 0;
else tmp =
M1064_XDVICLKCTRL_DVIDATAPATHSEL |
M1064_XDVICLKCTRL_C1DVICLKSEL |
M1064_XDVICLKCTRL_C1DVICLKEN |
M1064_XDVICLKCTRL_DVILOOPCTL |
M1064_XDVICLKCTRL_P1LOOPBWDTCTL;
/* Setting this breaks PC systems so don't do it */
/* matroxfb_DAC_out(minfo, M1064_XDVICLKCTRL, tmp); */
matroxfb_DAC_out(minfo, M1064_XPWRCTRL,
xpwrctrl);
matroxfb_DAC_unlock_irqrestore(flags);
}
{
u_int8_t misc;
misc = mga_inb(M_MISC_REG_READ) & ~0x0C;
switch (pll) {
case M_PIXEL_PLL_A:
break;
case M_PIXEL_PLL_B:
misc |= 0x04;
break;
default:
misc |= 0x0C;
break;
}
mga_outb(M_MISC_REG, misc);
}
pi = &minfo->limits.pixel;
ci = &minfo->cache.pixel;
break;
case M_SYSTEM_PLL:
{
u_int32_t opt;
pci_read_config_dword(minfo->pcidev, PCI_OPTION_REG, &opt);
if (!(opt & 0x20)) {
pci_write_config_dword(minfo->pcidev, PCI_OPTION_REG, opt | 0x20);
}
}
pi = &minfo->limits.system;
ci = &minfo->cache.system;
break;
case M_VIDEO_PLL:
{
u_int8_t tmp;
unsigned int mnp;
unsigned long flags;
matroxfb_DAC_lock_irqsave(flags);
tmp = matroxfb_DAC_in(minfo, M1064_XPWRCTRL);
if (!(tmp & 2)) {
matroxfb_DAC_out(minfo, M1064_XPWRCTRL, tmp | 2);
}
mnp = matroxfb_DAC_in(minfo, M1064_XPIXPLLCM) << 16;
mnp |= matroxfb_DAC_in(minfo, M1064_XPIXPLLCN) << 8;
pixel_vco = g450_mnp2vco(minfo, mnp);
matroxfb_DAC_unlock_irqrestore(flags);
}
pi = &minfo->limits.video;
ci = &minfo->cache.video;
break;
default:
return -EINVAL;
}
mnpcount = 0;
{
unsigned int mnp;
unsigned int xvco;
for (mnp = g450_firstpll(minfo, pi, &xvco, fout); mnp != NO_MORE_MNP; mnp = g450_nextpll(minfo, pi, &xvco, mnp)) {
unsigned int idx;
unsigned int vco;
unsigned int delta;
vco = g450_mnp2vco(minfo, mnp);
#if 0
if (pll == M_VIDEO_PLL) {
unsigned int big, small;
if (vco < pixel_vco) {
small = vco;
big = pixel_vco;
} else {
small = pixel_vco;
big = vco;
}
while (big > small) {
big >>= 1;
}
if (big == small) {
continue;
}
}
#endif
delta = pll_freq_delta(fout, g450_vco2f(mnp, vco));
for (idx = mnpcount; idx > 0; idx--) {
/* == is important; due to nextpll algorithm we get
sorted equally good frequencies from lower VCO
frequency to higher - with <= lowest wins, while
with < highest one wins */
if (delta <= deltaarray[idx-1]) {
/* all else being equal except VCO,
* choose VCO not near (within 1/16th or so) VCOmin
* (freqs near VCOmin aren't as stable)
*/
if (delta == deltaarray[idx-1]
&& vco != g450_mnp2vco(minfo, mnparray[idx-1])
&& vco < (pi->vcomin * 17 / 16)) {
break;
}
mnparray[idx] = mnparray[idx-1];
deltaarray[idx] = deltaarray[idx-1];
} else {
break;
}
}
mnparray[idx] = mnp;
deltaarray[idx] = delta;
mnpcount++;
}
}
/* VideoPLL and PixelPLL matched: do nothing... In all other cases we should get at least one frequency */
if (!mnpcount) {
return -EBUSY;
}
{
unsigned long flags;
unsigned int mnp;
matroxfb_DAC_lock_irqsave(flags);
mnp = g450_checkcache(minfo, ci, mnparray[0]);
if (mnp != NO_MORE_MNP) {
matroxfb_g450_setpll_cond(minfo, mnp, pll);
} else {
mnp = g450_findworkingpll(minfo, pll, mnparray, mnpcount);
g450_addcache(ci, mnparray[0], mnp);
}
updatehwstate_clk(&minfo->hw, mnp, pll);
matroxfb_DAC_unlock_irqrestore(flags);
return mnp;
}
}
/* It must be greater than number of possible PLL values.
* Currently there is 5(p) * 10(m) = 50 possible values. */
#define MNP_TABLE_SIZE 64
int matroxfb_g450_setclk(struct matrox_fb_info *minfo, unsigned int fout,
unsigned int pll)
{
unsigned int* arr;
arr = kmalloc(sizeof(*arr) * MNP_TABLE_SIZE * 2, GFP_KERNEL);
if (arr) {
int r;
r = __g450_setclk(minfo, fout, pll, arr, arr + MNP_TABLE_SIZE);
kfree(arr);
return r;
}
return -ENOMEM;
}
EXPORT_SYMBOL(matroxfb_g450_setclk);
EXPORT_SYMBOL(g450_mnp2f);
EXPORT_SYMBOL(matroxfb_g450_setpll_cond);
MODULE_AUTHOR("(c) 2001-2002 Petr Vandrovec <vandrove@vc.cvut.cz>");
MODULE_DESCRIPTION("Matrox G450/G550 PLL driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
Joshndroid/android_kernel_google_msm | drivers/video/matrox/g450_pll.c | 14656 | 13720 | /*
*
* Hardware accelerated Matrox PCI cards - G450/G550 PLL control.
*
* (c) 2001-2002 Petr Vandrovec <vandrove@vc.cvut.cz>
*
* Portions Copyright (c) 2001 Matrox Graphics Inc.
*
* Version: 1.64 2002/06/10
*
* 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 "g450_pll.h"
#include "matroxfb_DAC1064.h"
static inline unsigned int g450_vco2f(unsigned char p, unsigned int fvco) {
return (p & 0x40) ? fvco : fvco >> ((p & 3) + 1);
}
static inline unsigned int g450_f2vco(unsigned char p, unsigned int fin) {
return (p & 0x40) ? fin : fin << ((p & 3) + 1);
}
static unsigned int g450_mnp2vco(const struct matrox_fb_info *minfo,
unsigned int mnp)
{
unsigned int m, n;
m = ((mnp >> 16) & 0x0FF) + 1;
n = ((mnp >> 7) & 0x1FE) + 4;
return (minfo->features.pll.ref_freq * n + (m >> 1)) / m;
}
unsigned int g450_mnp2f(const struct matrox_fb_info *minfo, unsigned int mnp)
{
return g450_vco2f(mnp, g450_mnp2vco(minfo, mnp));
}
static inline unsigned int pll_freq_delta(unsigned int f1, unsigned int f2) {
if (f2 < f1) {
f2 = f1 - f2;
} else {
f2 = f2 - f1;
}
return f2;
}
#define NO_MORE_MNP 0x01FFFFFF
#define G450_MNP_FREQBITS (0xFFFFFF43) /* do not mask high byte so we'll catch NO_MORE_MNP */
static unsigned int g450_nextpll(const struct matrox_fb_info *minfo,
const struct matrox_pll_limits *pi,
unsigned int *fvco, unsigned int mnp)
{
unsigned int m, n, p;
unsigned int tvco = *fvco;
m = (mnp >> 16) & 0xFF;
p = mnp & 0xFF;
do {
if (m == 0 || m == 0xFF) {
if (m == 0) {
if (p & 0x40) {
return NO_MORE_MNP;
}
if (p & 3) {
p--;
} else {
p = 0x40;
}
tvco >>= 1;
if (tvco < pi->vcomin) {
return NO_MORE_MNP;
}
*fvco = tvco;
}
p &= 0x43;
if (tvco < 550000) {
/* p |= 0x00; */
} else if (tvco < 700000) {
p |= 0x08;
} else if (tvco < 1000000) {
p |= 0x10;
} else if (tvco < 1150000) {
p |= 0x18;
} else {
p |= 0x20;
}
m = 9;
} else {
m--;
}
n = ((tvco * (m+1) + minfo->features.pll.ref_freq) / (minfo->features.pll.ref_freq * 2)) - 2;
} while (n < 0x03 || n > 0x7A);
return (m << 16) | (n << 8) | p;
}
static unsigned int g450_firstpll(const struct matrox_fb_info *minfo,
const struct matrox_pll_limits *pi,
unsigned int *vco, unsigned int fout)
{
unsigned int p;
unsigned int vcomax;
vcomax = pi->vcomax;
if (fout > (vcomax / 2)) {
if (fout > vcomax) {
*vco = vcomax;
} else {
*vco = fout;
}
p = 0x40;
} else {
unsigned int tvco;
p = 3;
tvco = g450_f2vco(p, fout);
while (p && (tvco > vcomax)) {
p--;
tvco >>= 1;
}
if (tvco < pi->vcomin) {
tvco = pi->vcomin;
}
*vco = tvco;
}
return g450_nextpll(minfo, pi, vco, 0xFF0000 | p);
}
static inline unsigned int g450_setpll(const struct matrox_fb_info *minfo,
unsigned int mnp, unsigned int pll)
{
switch (pll) {
case M_PIXEL_PLL_A:
matroxfb_DAC_out(minfo, M1064_XPIXPLLAM, mnp >> 16);
matroxfb_DAC_out(minfo, M1064_XPIXPLLAN, mnp >> 8);
matroxfb_DAC_out(minfo, M1064_XPIXPLLAP, mnp);
return M1064_XPIXPLLSTAT;
case M_PIXEL_PLL_B:
matroxfb_DAC_out(minfo, M1064_XPIXPLLBM, mnp >> 16);
matroxfb_DAC_out(minfo, M1064_XPIXPLLBN, mnp >> 8);
matroxfb_DAC_out(minfo, M1064_XPIXPLLBP, mnp);
return M1064_XPIXPLLSTAT;
case M_PIXEL_PLL_C:
matroxfb_DAC_out(minfo, M1064_XPIXPLLCM, mnp >> 16);
matroxfb_DAC_out(minfo, M1064_XPIXPLLCN, mnp >> 8);
matroxfb_DAC_out(minfo, M1064_XPIXPLLCP, mnp);
return M1064_XPIXPLLSTAT;
case M_SYSTEM_PLL:
matroxfb_DAC_out(minfo, DAC1064_XSYSPLLM, mnp >> 16);
matroxfb_DAC_out(minfo, DAC1064_XSYSPLLN, mnp >> 8);
matroxfb_DAC_out(minfo, DAC1064_XSYSPLLP, mnp);
return DAC1064_XSYSPLLSTAT;
case M_VIDEO_PLL:
matroxfb_DAC_out(minfo, M1064_XVIDPLLM, mnp >> 16);
matroxfb_DAC_out(minfo, M1064_XVIDPLLN, mnp >> 8);
matroxfb_DAC_out(minfo, M1064_XVIDPLLP, mnp);
return M1064_XVIDPLLSTAT;
}
return 0;
}
static inline unsigned int g450_cmppll(const struct matrox_fb_info *minfo,
unsigned int mnp, unsigned int pll)
{
unsigned char m = mnp >> 16;
unsigned char n = mnp >> 8;
unsigned char p = mnp;
switch (pll) {
case M_PIXEL_PLL_A:
return (matroxfb_DAC_in(minfo, M1064_XPIXPLLAM) != m ||
matroxfb_DAC_in(minfo, M1064_XPIXPLLAN) != n ||
matroxfb_DAC_in(minfo, M1064_XPIXPLLAP) != p);
case M_PIXEL_PLL_B:
return (matroxfb_DAC_in(minfo, M1064_XPIXPLLBM) != m ||
matroxfb_DAC_in(minfo, M1064_XPIXPLLBN) != n ||
matroxfb_DAC_in(minfo, M1064_XPIXPLLBP) != p);
case M_PIXEL_PLL_C:
return (matroxfb_DAC_in(minfo, M1064_XPIXPLLCM) != m ||
matroxfb_DAC_in(minfo, M1064_XPIXPLLCN) != n ||
matroxfb_DAC_in(minfo, M1064_XPIXPLLCP) != p);
case M_SYSTEM_PLL:
return (matroxfb_DAC_in(minfo, DAC1064_XSYSPLLM) != m ||
matroxfb_DAC_in(minfo, DAC1064_XSYSPLLN) != n ||
matroxfb_DAC_in(minfo, DAC1064_XSYSPLLP) != p);
case M_VIDEO_PLL:
return (matroxfb_DAC_in(minfo, M1064_XVIDPLLM) != m ||
matroxfb_DAC_in(minfo, M1064_XVIDPLLN) != n ||
matroxfb_DAC_in(minfo, M1064_XVIDPLLP) != p);
}
return 1;
}
static inline int g450_isplllocked(const struct matrox_fb_info *minfo,
unsigned int regidx)
{
unsigned int j;
for (j = 0; j < 1000; j++) {
if (matroxfb_DAC_in(minfo, regidx) & 0x40) {
unsigned int r = 0;
int i;
for (i = 0; i < 100; i++) {
r += matroxfb_DAC_in(minfo, regidx) & 0x40;
}
return r >= (90 * 0x40);
}
/* udelay(1)... but DAC_in is much slower... */
}
return 0;
}
static int g450_testpll(const struct matrox_fb_info *minfo, unsigned int mnp,
unsigned int pll)
{
return g450_isplllocked(minfo, g450_setpll(minfo, mnp, pll));
}
static void updatehwstate_clk(struct matrox_hw_state* hw, unsigned int mnp, unsigned int pll) {
switch (pll) {
case M_SYSTEM_PLL:
hw->DACclk[3] = mnp >> 16;
hw->DACclk[4] = mnp >> 8;
hw->DACclk[5] = mnp;
break;
}
}
void matroxfb_g450_setpll_cond(struct matrox_fb_info *minfo, unsigned int mnp,
unsigned int pll)
{
if (g450_cmppll(minfo, mnp, pll)) {
g450_setpll(minfo, mnp, pll);
}
}
static inline unsigned int g450_findworkingpll(struct matrox_fb_info *minfo,
unsigned int pll,
unsigned int *mnparray,
unsigned int mnpcount)
{
unsigned int found = 0;
unsigned int idx;
unsigned int mnpfound = mnparray[0];
for (idx = 0; idx < mnpcount; idx++) {
unsigned int sarray[3];
unsigned int *sptr;
{
unsigned int mnp;
sptr = sarray;
mnp = mnparray[idx];
if (mnp & 0x38) {
*sptr++ = mnp - 8;
}
if ((mnp & 0x38) != 0x38) {
*sptr++ = mnp + 8;
}
*sptr = mnp;
}
while (sptr >= sarray) {
unsigned int mnp = *sptr--;
if (g450_testpll(minfo, mnp - 0x0300, pll) &&
g450_testpll(minfo, mnp + 0x0300, pll) &&
g450_testpll(minfo, mnp - 0x0200, pll) &&
g450_testpll(minfo, mnp + 0x0200, pll) &&
g450_testpll(minfo, mnp - 0x0100, pll) &&
g450_testpll(minfo, mnp + 0x0100, pll)) {
if (g450_testpll(minfo, mnp, pll)) {
return mnp;
}
} else if (!found && g450_testpll(minfo, mnp, pll)) {
mnpfound = mnp;
found = 1;
}
}
}
g450_setpll(minfo, mnpfound, pll);
return mnpfound;
}
static void g450_addcache(struct matrox_pll_cache* ci, unsigned int mnp_key, unsigned int mnp_value) {
if (++ci->valid > ARRAY_SIZE(ci->data)) {
ci->valid = ARRAY_SIZE(ci->data);
}
memmove(ci->data + 1, ci->data, (ci->valid - 1) * sizeof(*ci->data));
ci->data[0].mnp_key = mnp_key & G450_MNP_FREQBITS;
ci->data[0].mnp_value = mnp_value;
}
static int g450_checkcache(struct matrox_fb_info *minfo,
struct matrox_pll_cache *ci, unsigned int mnp_key)
{
unsigned int i;
mnp_key &= G450_MNP_FREQBITS;
for (i = 0; i < ci->valid; i++) {
if (ci->data[i].mnp_key == mnp_key) {
unsigned int mnp;
mnp = ci->data[i].mnp_value;
if (i) {
memmove(ci->data + 1, ci->data, i * sizeof(*ci->data));
ci->data[0].mnp_key = mnp_key;
ci->data[0].mnp_value = mnp;
}
return mnp;
}
}
return NO_MORE_MNP;
}
static int __g450_setclk(struct matrox_fb_info *minfo, unsigned int fout,
unsigned int pll, unsigned int *mnparray,
unsigned int *deltaarray)
{
unsigned int mnpcount;
unsigned int pixel_vco;
const struct matrox_pll_limits* pi;
struct matrox_pll_cache* ci;
pixel_vco = 0;
switch (pll) {
case M_PIXEL_PLL_A:
case M_PIXEL_PLL_B:
case M_PIXEL_PLL_C:
{
u_int8_t tmp, xpwrctrl;
unsigned long flags;
matroxfb_DAC_lock_irqsave(flags);
xpwrctrl = matroxfb_DAC_in(minfo, M1064_XPWRCTRL);
matroxfb_DAC_out(minfo, M1064_XPWRCTRL, xpwrctrl & ~M1064_XPWRCTRL_PANELPDN);
mga_outb(M_SEQ_INDEX, M_SEQ1);
mga_outb(M_SEQ_DATA, mga_inb(M_SEQ_DATA) | M_SEQ1_SCROFF);
tmp = matroxfb_DAC_in(minfo, M1064_XPIXCLKCTRL);
tmp |= M1064_XPIXCLKCTRL_DIS;
if (!(tmp & M1064_XPIXCLKCTRL_PLL_UP)) {
tmp |= M1064_XPIXCLKCTRL_PLL_UP;
}
matroxfb_DAC_out(minfo, M1064_XPIXCLKCTRL, tmp);
/* DVI PLL preferred for frequencies up to
panel link max, standard PLL otherwise */
if (fout >= minfo->max_pixel_clock_panellink)
tmp = 0;
else tmp =
M1064_XDVICLKCTRL_DVIDATAPATHSEL |
M1064_XDVICLKCTRL_C1DVICLKSEL |
M1064_XDVICLKCTRL_C1DVICLKEN |
M1064_XDVICLKCTRL_DVILOOPCTL |
M1064_XDVICLKCTRL_P1LOOPBWDTCTL;
/* Setting this breaks PC systems so don't do it */
/* matroxfb_DAC_out(minfo, M1064_XDVICLKCTRL, tmp); */
matroxfb_DAC_out(minfo, M1064_XPWRCTRL,
xpwrctrl);
matroxfb_DAC_unlock_irqrestore(flags);
}
{
u_int8_t misc;
misc = mga_inb(M_MISC_REG_READ) & ~0x0C;
switch (pll) {
case M_PIXEL_PLL_A:
break;
case M_PIXEL_PLL_B:
misc |= 0x04;
break;
default:
misc |= 0x0C;
break;
}
mga_outb(M_MISC_REG, misc);
}
pi = &minfo->limits.pixel;
ci = &minfo->cache.pixel;
break;
case M_SYSTEM_PLL:
{
u_int32_t opt;
pci_read_config_dword(minfo->pcidev, PCI_OPTION_REG, &opt);
if (!(opt & 0x20)) {
pci_write_config_dword(minfo->pcidev, PCI_OPTION_REG, opt | 0x20);
}
}
pi = &minfo->limits.system;
ci = &minfo->cache.system;
break;
case M_VIDEO_PLL:
{
u_int8_t tmp;
unsigned int mnp;
unsigned long flags;
matroxfb_DAC_lock_irqsave(flags);
tmp = matroxfb_DAC_in(minfo, M1064_XPWRCTRL);
if (!(tmp & 2)) {
matroxfb_DAC_out(minfo, M1064_XPWRCTRL, tmp | 2);
}
mnp = matroxfb_DAC_in(minfo, M1064_XPIXPLLCM) << 16;
mnp |= matroxfb_DAC_in(minfo, M1064_XPIXPLLCN) << 8;
pixel_vco = g450_mnp2vco(minfo, mnp);
matroxfb_DAC_unlock_irqrestore(flags);
}
pi = &minfo->limits.video;
ci = &minfo->cache.video;
break;
default:
return -EINVAL;
}
mnpcount = 0;
{
unsigned int mnp;
unsigned int xvco;
for (mnp = g450_firstpll(minfo, pi, &xvco, fout); mnp != NO_MORE_MNP; mnp = g450_nextpll(minfo, pi, &xvco, mnp)) {
unsigned int idx;
unsigned int vco;
unsigned int delta;
vco = g450_mnp2vco(minfo, mnp);
#if 0
if (pll == M_VIDEO_PLL) {
unsigned int big, small;
if (vco < pixel_vco) {
small = vco;
big = pixel_vco;
} else {
small = pixel_vco;
big = vco;
}
while (big > small) {
big >>= 1;
}
if (big == small) {
continue;
}
}
#endif
delta = pll_freq_delta(fout, g450_vco2f(mnp, vco));
for (idx = mnpcount; idx > 0; idx--) {
/* == is important; due to nextpll algorithm we get
sorted equally good frequencies from lower VCO
frequency to higher - with <= lowest wins, while
with < highest one wins */
if (delta <= deltaarray[idx-1]) {
/* all else being equal except VCO,
* choose VCO not near (within 1/16th or so) VCOmin
* (freqs near VCOmin aren't as stable)
*/
if (delta == deltaarray[idx-1]
&& vco != g450_mnp2vco(minfo, mnparray[idx-1])
&& vco < (pi->vcomin * 17 / 16)) {
break;
}
mnparray[idx] = mnparray[idx-1];
deltaarray[idx] = deltaarray[idx-1];
} else {
break;
}
}
mnparray[idx] = mnp;
deltaarray[idx] = delta;
mnpcount++;
}
}
/* VideoPLL and PixelPLL matched: do nothing... In all other cases we should get at least one frequency */
if (!mnpcount) {
return -EBUSY;
}
{
unsigned long flags;
unsigned int mnp;
matroxfb_DAC_lock_irqsave(flags);
mnp = g450_checkcache(minfo, ci, mnparray[0]);
if (mnp != NO_MORE_MNP) {
matroxfb_g450_setpll_cond(minfo, mnp, pll);
} else {
mnp = g450_findworkingpll(minfo, pll, mnparray, mnpcount);
g450_addcache(ci, mnparray[0], mnp);
}
updatehwstate_clk(&minfo->hw, mnp, pll);
matroxfb_DAC_unlock_irqrestore(flags);
return mnp;
}
}
/* It must be greater than number of possible PLL values.
* Currently there is 5(p) * 10(m) = 50 possible values. */
#define MNP_TABLE_SIZE 64
int matroxfb_g450_setclk(struct matrox_fb_info *minfo, unsigned int fout,
unsigned int pll)
{
unsigned int* arr;
arr = kmalloc(sizeof(*arr) * MNP_TABLE_SIZE * 2, GFP_KERNEL);
if (arr) {
int r;
r = __g450_setclk(minfo, fout, pll, arr, arr + MNP_TABLE_SIZE);
kfree(arr);
return r;
}
return -ENOMEM;
}
EXPORT_SYMBOL(matroxfb_g450_setclk);
EXPORT_SYMBOL(g450_mnp2f);
EXPORT_SYMBOL(matroxfb_g450_setpll_cond);
MODULE_AUTHOR("(c) 2001-2002 Petr Vandrovec <vandrove@vc.cvut.cz>");
MODULE_DESCRIPTION("Matrox G450/G550 PLL driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
Broadcom/cygnus-linux | arch/x86/crypto/cast5_avx_glue.c | 65 | 12550 | /*
* Glue Code for the AVX assembler implemention of the Cast5 Cipher
*
* Copyright (C) 2012 Johannes Goetzfried
* <Johannes.Goetzfried@informatik.stud.uni-erlangen.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
*/
#include <linux/module.h>
#include <linux/hardirq.h>
#include <linux/types.h>
#include <linux/crypto.h>
#include <linux/err.h>
#include <crypto/ablk_helper.h>
#include <crypto/algapi.h>
#include <crypto/cast5.h>
#include <crypto/cryptd.h>
#include <crypto/ctr.h>
#include <asm/fpu/api.h>
#include <asm/crypto/glue_helper.h>
#define CAST5_PARALLEL_BLOCKS 16
asmlinkage void cast5_ecb_enc_16way(struct cast5_ctx *ctx, u8 *dst,
const u8 *src);
asmlinkage void cast5_ecb_dec_16way(struct cast5_ctx *ctx, u8 *dst,
const u8 *src);
asmlinkage void cast5_cbc_dec_16way(struct cast5_ctx *ctx, u8 *dst,
const u8 *src);
asmlinkage void cast5_ctr_16way(struct cast5_ctx *ctx, u8 *dst, const u8 *src,
__be64 *iv);
static inline bool cast5_fpu_begin(bool fpu_enabled, unsigned int nbytes)
{
return glue_fpu_begin(CAST5_BLOCK_SIZE, CAST5_PARALLEL_BLOCKS,
NULL, fpu_enabled, nbytes);
}
static inline void cast5_fpu_end(bool fpu_enabled)
{
return glue_fpu_end(fpu_enabled);
}
static int ecb_crypt(struct blkcipher_desc *desc, struct blkcipher_walk *walk,
bool enc)
{
bool fpu_enabled = false;
struct cast5_ctx *ctx = crypto_blkcipher_ctx(desc->tfm);
const unsigned int bsize = CAST5_BLOCK_SIZE;
unsigned int nbytes;
void (*fn)(struct cast5_ctx *ctx, u8 *dst, const u8 *src);
int err;
fn = (enc) ? cast5_ecb_enc_16way : cast5_ecb_dec_16way;
err = blkcipher_walk_virt(desc, walk);
desc->flags &= ~CRYPTO_TFM_REQ_MAY_SLEEP;
while ((nbytes = walk->nbytes)) {
u8 *wsrc = walk->src.virt.addr;
u8 *wdst = walk->dst.virt.addr;
fpu_enabled = cast5_fpu_begin(fpu_enabled, nbytes);
/* Process multi-block batch */
if (nbytes >= bsize * CAST5_PARALLEL_BLOCKS) {
do {
fn(ctx, wdst, wsrc);
wsrc += bsize * CAST5_PARALLEL_BLOCKS;
wdst += bsize * CAST5_PARALLEL_BLOCKS;
nbytes -= bsize * CAST5_PARALLEL_BLOCKS;
} while (nbytes >= bsize * CAST5_PARALLEL_BLOCKS);
if (nbytes < bsize)
goto done;
}
fn = (enc) ? __cast5_encrypt : __cast5_decrypt;
/* Handle leftovers */
do {
fn(ctx, wdst, wsrc);
wsrc += bsize;
wdst += bsize;
nbytes -= bsize;
} while (nbytes >= bsize);
done:
err = blkcipher_walk_done(desc, walk, nbytes);
}
cast5_fpu_end(fpu_enabled);
return err;
}
static int ecb_encrypt(struct blkcipher_desc *desc, struct scatterlist *dst,
struct scatterlist *src, unsigned int nbytes)
{
struct blkcipher_walk walk;
blkcipher_walk_init(&walk, dst, src, nbytes);
return ecb_crypt(desc, &walk, true);
}
static int ecb_decrypt(struct blkcipher_desc *desc, struct scatterlist *dst,
struct scatterlist *src, unsigned int nbytes)
{
struct blkcipher_walk walk;
blkcipher_walk_init(&walk, dst, src, nbytes);
return ecb_crypt(desc, &walk, false);
}
static unsigned int __cbc_encrypt(struct blkcipher_desc *desc,
struct blkcipher_walk *walk)
{
struct cast5_ctx *ctx = crypto_blkcipher_ctx(desc->tfm);
const unsigned int bsize = CAST5_BLOCK_SIZE;
unsigned int nbytes = walk->nbytes;
u64 *src = (u64 *)walk->src.virt.addr;
u64 *dst = (u64 *)walk->dst.virt.addr;
u64 *iv = (u64 *)walk->iv;
do {
*dst = *src ^ *iv;
__cast5_encrypt(ctx, (u8 *)dst, (u8 *)dst);
iv = dst;
src += 1;
dst += 1;
nbytes -= bsize;
} while (nbytes >= bsize);
*(u64 *)walk->iv = *iv;
return nbytes;
}
static int cbc_encrypt(struct blkcipher_desc *desc, struct scatterlist *dst,
struct scatterlist *src, unsigned int nbytes)
{
struct blkcipher_walk walk;
int err;
blkcipher_walk_init(&walk, dst, src, nbytes);
err = blkcipher_walk_virt(desc, &walk);
while ((nbytes = walk.nbytes)) {
nbytes = __cbc_encrypt(desc, &walk);
err = blkcipher_walk_done(desc, &walk, nbytes);
}
return err;
}
static unsigned int __cbc_decrypt(struct blkcipher_desc *desc,
struct blkcipher_walk *walk)
{
struct cast5_ctx *ctx = crypto_blkcipher_ctx(desc->tfm);
const unsigned int bsize = CAST5_BLOCK_SIZE;
unsigned int nbytes = walk->nbytes;
u64 *src = (u64 *)walk->src.virt.addr;
u64 *dst = (u64 *)walk->dst.virt.addr;
u64 last_iv;
/* Start of the last block. */
src += nbytes / bsize - 1;
dst += nbytes / bsize - 1;
last_iv = *src;
/* Process multi-block batch */
if (nbytes >= bsize * CAST5_PARALLEL_BLOCKS) {
do {
nbytes -= bsize * (CAST5_PARALLEL_BLOCKS - 1);
src -= CAST5_PARALLEL_BLOCKS - 1;
dst -= CAST5_PARALLEL_BLOCKS - 1;
cast5_cbc_dec_16way(ctx, (u8 *)dst, (u8 *)src);
nbytes -= bsize;
if (nbytes < bsize)
goto done;
*dst ^= *(src - 1);
src -= 1;
dst -= 1;
} while (nbytes >= bsize * CAST5_PARALLEL_BLOCKS);
}
/* Handle leftovers */
for (;;) {
__cast5_decrypt(ctx, (u8 *)dst, (u8 *)src);
nbytes -= bsize;
if (nbytes < bsize)
break;
*dst ^= *(src - 1);
src -= 1;
dst -= 1;
}
done:
*dst ^= *(u64 *)walk->iv;
*(u64 *)walk->iv = last_iv;
return nbytes;
}
static int cbc_decrypt(struct blkcipher_desc *desc, struct scatterlist *dst,
struct scatterlist *src, unsigned int nbytes)
{
bool fpu_enabled = false;
struct blkcipher_walk walk;
int err;
blkcipher_walk_init(&walk, dst, src, nbytes);
err = blkcipher_walk_virt(desc, &walk);
desc->flags &= ~CRYPTO_TFM_REQ_MAY_SLEEP;
while ((nbytes = walk.nbytes)) {
fpu_enabled = cast5_fpu_begin(fpu_enabled, nbytes);
nbytes = __cbc_decrypt(desc, &walk);
err = blkcipher_walk_done(desc, &walk, nbytes);
}
cast5_fpu_end(fpu_enabled);
return err;
}
static void ctr_crypt_final(struct blkcipher_desc *desc,
struct blkcipher_walk *walk)
{
struct cast5_ctx *ctx = crypto_blkcipher_ctx(desc->tfm);
u8 *ctrblk = walk->iv;
u8 keystream[CAST5_BLOCK_SIZE];
u8 *src = walk->src.virt.addr;
u8 *dst = walk->dst.virt.addr;
unsigned int nbytes = walk->nbytes;
__cast5_encrypt(ctx, keystream, ctrblk);
crypto_xor_cpy(dst, keystream, src, nbytes);
crypto_inc(ctrblk, CAST5_BLOCK_SIZE);
}
static unsigned int __ctr_crypt(struct blkcipher_desc *desc,
struct blkcipher_walk *walk)
{
struct cast5_ctx *ctx = crypto_blkcipher_ctx(desc->tfm);
const unsigned int bsize = CAST5_BLOCK_SIZE;
unsigned int nbytes = walk->nbytes;
u64 *src = (u64 *)walk->src.virt.addr;
u64 *dst = (u64 *)walk->dst.virt.addr;
/* Process multi-block batch */
if (nbytes >= bsize * CAST5_PARALLEL_BLOCKS) {
do {
cast5_ctr_16way(ctx, (u8 *)dst, (u8 *)src,
(__be64 *)walk->iv);
src += CAST5_PARALLEL_BLOCKS;
dst += CAST5_PARALLEL_BLOCKS;
nbytes -= bsize * CAST5_PARALLEL_BLOCKS;
} while (nbytes >= bsize * CAST5_PARALLEL_BLOCKS);
if (nbytes < bsize)
goto done;
}
/* Handle leftovers */
do {
u64 ctrblk;
if (dst != src)
*dst = *src;
ctrblk = *(u64 *)walk->iv;
be64_add_cpu((__be64 *)walk->iv, 1);
__cast5_encrypt(ctx, (u8 *)&ctrblk, (u8 *)&ctrblk);
*dst ^= ctrblk;
src += 1;
dst += 1;
nbytes -= bsize;
} while (nbytes >= bsize);
done:
return nbytes;
}
static int ctr_crypt(struct blkcipher_desc *desc, struct scatterlist *dst,
struct scatterlist *src, unsigned int nbytes)
{
bool fpu_enabled = false;
struct blkcipher_walk walk;
int err;
blkcipher_walk_init(&walk, dst, src, nbytes);
err = blkcipher_walk_virt_block(desc, &walk, CAST5_BLOCK_SIZE);
desc->flags &= ~CRYPTO_TFM_REQ_MAY_SLEEP;
while ((nbytes = walk.nbytes) >= CAST5_BLOCK_SIZE) {
fpu_enabled = cast5_fpu_begin(fpu_enabled, nbytes);
nbytes = __ctr_crypt(desc, &walk);
err = blkcipher_walk_done(desc, &walk, nbytes);
}
cast5_fpu_end(fpu_enabled);
if (walk.nbytes) {
ctr_crypt_final(desc, &walk);
err = blkcipher_walk_done(desc, &walk, 0);
}
return err;
}
static struct crypto_alg cast5_algs[6] = { {
.cra_name = "__ecb-cast5-avx",
.cra_driver_name = "__driver-ecb-cast5-avx",
.cra_priority = 0,
.cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER |
CRYPTO_ALG_INTERNAL,
.cra_blocksize = CAST5_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct cast5_ctx),
.cra_alignmask = 0,
.cra_type = &crypto_blkcipher_type,
.cra_module = THIS_MODULE,
.cra_u = {
.blkcipher = {
.min_keysize = CAST5_MIN_KEY_SIZE,
.max_keysize = CAST5_MAX_KEY_SIZE,
.setkey = cast5_setkey,
.encrypt = ecb_encrypt,
.decrypt = ecb_decrypt,
},
},
}, {
.cra_name = "__cbc-cast5-avx",
.cra_driver_name = "__driver-cbc-cast5-avx",
.cra_priority = 0,
.cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER |
CRYPTO_ALG_INTERNAL,
.cra_blocksize = CAST5_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct cast5_ctx),
.cra_alignmask = 0,
.cra_type = &crypto_blkcipher_type,
.cra_module = THIS_MODULE,
.cra_u = {
.blkcipher = {
.min_keysize = CAST5_MIN_KEY_SIZE,
.max_keysize = CAST5_MAX_KEY_SIZE,
.setkey = cast5_setkey,
.encrypt = cbc_encrypt,
.decrypt = cbc_decrypt,
},
},
}, {
.cra_name = "__ctr-cast5-avx",
.cra_driver_name = "__driver-ctr-cast5-avx",
.cra_priority = 0,
.cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER |
CRYPTO_ALG_INTERNAL,
.cra_blocksize = 1,
.cra_ctxsize = sizeof(struct cast5_ctx),
.cra_alignmask = 0,
.cra_type = &crypto_blkcipher_type,
.cra_module = THIS_MODULE,
.cra_u = {
.blkcipher = {
.min_keysize = CAST5_MIN_KEY_SIZE,
.max_keysize = CAST5_MAX_KEY_SIZE,
.ivsize = CAST5_BLOCK_SIZE,
.setkey = cast5_setkey,
.encrypt = ctr_crypt,
.decrypt = ctr_crypt,
},
},
}, {
.cra_name = "ecb(cast5)",
.cra_driver_name = "ecb-cast5-avx",
.cra_priority = 200,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC,
.cra_blocksize = CAST5_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct async_helper_ctx),
.cra_alignmask = 0,
.cra_type = &crypto_ablkcipher_type,
.cra_module = THIS_MODULE,
.cra_init = ablk_init,
.cra_exit = ablk_exit,
.cra_u = {
.ablkcipher = {
.min_keysize = CAST5_MIN_KEY_SIZE,
.max_keysize = CAST5_MAX_KEY_SIZE,
.setkey = ablk_set_key,
.encrypt = ablk_encrypt,
.decrypt = ablk_decrypt,
},
},
}, {
.cra_name = "cbc(cast5)",
.cra_driver_name = "cbc-cast5-avx",
.cra_priority = 200,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC,
.cra_blocksize = CAST5_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct async_helper_ctx),
.cra_alignmask = 0,
.cra_type = &crypto_ablkcipher_type,
.cra_module = THIS_MODULE,
.cra_init = ablk_init,
.cra_exit = ablk_exit,
.cra_u = {
.ablkcipher = {
.min_keysize = CAST5_MIN_KEY_SIZE,
.max_keysize = CAST5_MAX_KEY_SIZE,
.ivsize = CAST5_BLOCK_SIZE,
.setkey = ablk_set_key,
.encrypt = __ablk_encrypt,
.decrypt = ablk_decrypt,
},
},
}, {
.cra_name = "ctr(cast5)",
.cra_driver_name = "ctr-cast5-avx",
.cra_priority = 200,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC,
.cra_blocksize = 1,
.cra_ctxsize = sizeof(struct async_helper_ctx),
.cra_alignmask = 0,
.cra_type = &crypto_ablkcipher_type,
.cra_module = THIS_MODULE,
.cra_init = ablk_init,
.cra_exit = ablk_exit,
.cra_u = {
.ablkcipher = {
.min_keysize = CAST5_MIN_KEY_SIZE,
.max_keysize = CAST5_MAX_KEY_SIZE,
.ivsize = CAST5_BLOCK_SIZE,
.setkey = ablk_set_key,
.encrypt = ablk_encrypt,
.decrypt = ablk_encrypt,
.geniv = "chainiv",
},
},
} };
static int __init cast5_init(void)
{
const char *feature_name;
if (!cpu_has_xfeatures(XFEATURE_MASK_SSE | XFEATURE_MASK_YMM,
&feature_name)) {
pr_info("CPU feature '%s' is not supported.\n", feature_name);
return -ENODEV;
}
return crypto_register_algs(cast5_algs, ARRAY_SIZE(cast5_algs));
}
static void __exit cast5_exit(void)
{
crypto_unregister_algs(cast5_algs, ARRAY_SIZE(cast5_algs));
}
module_init(cast5_init);
module_exit(cast5_exit);
MODULE_DESCRIPTION("Cast5 Cipher Algorithm, AVX optimized");
MODULE_LICENSE("GPL");
MODULE_ALIAS_CRYPTO("cast5");
| gpl-2.0 |
DARKCHYLDX101/GCC-UBER | gcc/testsuite/gcc.dg/pr48552-2.c | 65 | 1495 | /* PR c/48552 */
/* { dg-do compile } */
/* { dg-options "" } */
struct S;
void
f1 (void *x)
{
__asm ("" : : "r" (*x)); /* { dg-warning "dereferencing" "deref" } */
} /* { dg-error "invalid use of void expression" "void expr" { target *-*-* } 10 } */
void
f2 (void *x)
{
__asm ("" : "=r" (*x)); /* { dg-warning "dereferencing" "deref" } */
} /* { dg-error "invalid use of void expression" "void expr" { target *-*-* } 16 } */
/* { dg-error "invalid lvalue in asm output 0" "invalid lvalue" { target *-*-* } 16 } */
void
f3 (void *x)
{
__asm ("" : : "m" (*x)); /* { dg-warning "dereferencing" } */
}
void
f4 (void *x)
{
__asm ("" : "=m" (*x)); /* { dg-warning "dereferencing" } */
}
void
f5 (void *x)
{
__asm ("" : : "g" (*x)); /* { dg-warning "dereferencing" "deref" } */
} /* { dg-error "invalid use of void expression" "void expr" { target *-*-* } 34 } */
void
f6 (void *x)
{
__asm ("" : "=g" (*x)); /* { dg-warning "dereferencing" "deref" } */
} /* { dg-error "invalid use of void expression" "void expr" { target *-*-* } 40 } */
/* { dg-error "invalid lvalue in asm output 0" "invalid lvalue" { target *-*-* } 40 } */
void
f7 (struct S *x)
{
__asm ("" : : "r" (*x)); /* { dg-error "dereferencing pointer to incomplete type" } */
}
void
f8 (struct S *x)
{
__asm ("" : "=r" (*x)); /* { dg-error "dereferencing pointer to incomplete type" "incomplete" } */
} /* { dg-error "invalid lvalue in asm output 0" "invalid lvalue" { target *-*-* } 52 } */
| gpl-2.0 |
AngSanley/angsanleykernel-nokia-normandy | drivers/media/video/msm/io/msm_io_vfe31_v4l2.c | 65 | 6024 | /* Copyright (c) 2010-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.
*
*/
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <linux/regulator/consumer.h>
#include <mach/gpio.h>
#include <mach/board.h>
#include <mach/camera.h>
#include <mach/vreg.h>
#include <mach/camera.h>
#include <mach/clk.h>
#include <mach/msm_bus.h>
#include <mach/msm_bus_board.h>
#include <linux/pm_qos.h>
/* AXI rates in KHz */
#define MSM_AXI_QOS_PREVIEW 192000
#define MSM_AXI_QOS_SNAPSHOT 192000
#define MSM_AXI_QOS_RECORDING 192000
#define BUFF_SIZE_128 128
static struct clk *camio_vfe_clk;
static struct clk *camio_vpe_clk;
static struct clk *camio_vpe_pclk;
static struct regulator *fs_vpe;
static int vpe_clk_rate;
int msm_camio_clk_enable(enum msm_camio_clk_type clktype)
{
int rc = 0;
struct clk *clk = NULL;
switch (clktype) {
case CAMIO_VPE_CLK:
camio_vpe_clk =
clk = clk_get(NULL, "vpe_clk");
vpe_clk_rate = clk_round_rate(camio_vpe_clk, vpe_clk_rate);
clk_set_rate(camio_vpe_clk, vpe_clk_rate);
break;
case CAMIO_VPE_PCLK:
camio_vpe_pclk =
clk = clk_get(NULL, "vpe_pclk");
break;
default:
break;
}
if (!IS_ERR(clk)) {
clk_prepare(clk);
clk_enable(clk);
} else {
rc = -1;
}
return rc;
}
int msm_camio_clk_disable(enum msm_camio_clk_type clktype)
{
int rc = 0;
struct clk *clk = NULL;
switch (clktype) {
case CAMIO_VPE_CLK:
clk = camio_vpe_clk;
break;
case CAMIO_VPE_PCLK:
clk = camio_vpe_pclk;
break;
default:
break;
}
if (!IS_ERR(clk)) {
clk_disable(clk);
clk_unprepare(clk);
clk_put(clk);
} else {
rc = -1;
}
return rc;
}
int msm_camio_vfe_clk_rate_set(int rate)
{
int rc = 0;
struct clk *clk = camio_vfe_clk;
if (rate > clk_get_rate(clk))
rc = clk_set_rate(clk, rate);
return rc;
}
void msm_camio_clk_rate_set_2(struct clk *clk, int rate)
{
clk_set_rate(clk, rate);
}
int msm_camio_vpe_clk_disable(void)
{
int rc = 0;
if (fs_vpe) {
regulator_disable(fs_vpe);
regulator_put(fs_vpe);
}
rc = msm_camio_clk_disable(CAMIO_VPE_CLK);
if (rc < 0)
return rc;
rc = msm_camio_clk_disable(CAMIO_VPE_PCLK);
return rc;
}
int msm_camio_vpe_clk_enable(uint32_t clk_rate)
{
int rc = 0;
fs_vpe = regulator_get(NULL, "fs_vpe");
if (IS_ERR(fs_vpe)) {
CDBG("%s: Regulator FS_VPE get failed %ld\n", __func__,
PTR_ERR(fs_vpe));
fs_vpe = NULL;
} else if (regulator_enable(fs_vpe)) {
CDBG("%s: Regulator FS_VPE enable failed\n", __func__);
regulator_put(fs_vpe);
}
vpe_clk_rate = clk_rate;
rc = msm_camio_clk_enable(CAMIO_VPE_CLK);
if (rc < 0)
return rc;
rc = msm_camio_clk_enable(CAMIO_VPE_PCLK);
return rc;
}
void msm_camio_vfe_blk_reset(void)
{
return;
}
void msm_camio_vfe_blk_reset_3(void)
{
return;
}
static void msm_camio_axi_cfg(enum msm_bus_perf_setting perf_setting)
{
switch (perf_setting) {
case S_INIT:
add_axi_qos();
break;
case S_PREVIEW:
update_axi_qos(MSM_AXI_QOS_PREVIEW);
break;
case S_VIDEO:
update_axi_qos(MSM_AXI_QOS_RECORDING);
break;
case S_CAPTURE:
update_axi_qos(MSM_AXI_QOS_SNAPSHOT);
break;
case S_DEFAULT:
update_axi_qos(PM_QOS_DEFAULT_VALUE);
break;
case S_EXIT:
release_axi_qos();
break;
default:
CDBG("%s: INVALID CASE\n", __func__);
}
}
void msm_camio_bus_scale_cfg(struct msm_bus_scale_pdata *cam_bus_scale_table,
enum msm_bus_perf_setting perf_setting)
{
static uint32_t bus_perf_client;
int rc = 0;
if (cam_bus_scale_table == NULL) {
msm_camio_axi_cfg(perf_setting);
return;
}
switch (perf_setting) {
case S_INIT:
bus_perf_client =
msm_bus_scale_register_client(cam_bus_scale_table);
if (!bus_perf_client) {
pr_err("%s: Registration Failed!!!\n", __func__);
bus_perf_client = 0;
return;
}
CDBG("%s: S_INIT rc = %u\n", __func__, bus_perf_client);
break;
case S_EXIT:
if (bus_perf_client) {
CDBG("%s: S_EXIT\n", __func__);
msm_bus_scale_unregister_client(bus_perf_client);
} else
pr_err("%s: Bus Client NOT Registered!!!\n", __func__);
break;
case S_PREVIEW:
if (bus_perf_client) {
rc = msm_bus_scale_client_update_request(
bus_perf_client, 1);
CDBG("%s: S_PREVIEW rc = %d\n", __func__, rc);
} else
pr_err("%s: Bus Client NOT Registered!!!\n", __func__);
break;
case S_VIDEO:
if (bus_perf_client) {
rc = msm_bus_scale_client_update_request(
bus_perf_client, 2);
CDBG("%s: S_VIDEO rc = %d\n", __func__, rc);
} else
pr_err("%s: Bus Client NOT Registered!!!\n", __func__);
break;
case S_CAPTURE:
if (bus_perf_client) {
rc = msm_bus_scale_client_update_request(
bus_perf_client, 3);
CDBG("%s: S_CAPTURE rc = %d\n", __func__, rc);
} else
pr_err("%s: Bus Client NOT Registered!!!\n", __func__);
break;
case S_ZSL:
if (bus_perf_client) {
rc = msm_bus_scale_client_update_request(
bus_perf_client, 4);
CDBG("%s: S_ZSL rc = %d\n", __func__, rc);
} else
pr_err("%s: Bus Client NOT Registered!!!\n", __func__);
break;
case S_STEREO_VIDEO:
if (bus_perf_client) {
rc = msm_bus_scale_client_update_request(
bus_perf_client, 5);
CDBG("%s: S_STEREO_VIDEO rc = %d\n", __func__, rc);
} else
pr_err("%s: Bus Client NOT Registered!!!\n", __func__);
break;
case S_STEREO_CAPTURE:
if (bus_perf_client) {
rc = msm_bus_scale_client_update_request(
bus_perf_client, 6);
CDBG("%s: S_STEREO_VIDEO rc = %d\n", __func__, rc);
} else
pr_err("%s: Bus Client NOT Registered!!!\n", __func__);
break;
case S_DEFAULT:
break;
default:
pr_warning("%s: INVALID CASE\n", __func__);
}
}
| gpl-2.0 |
v1ron/mk802iv-linux | arch/arm/mach-rk30/board-pmu-wm8326.c | 65 | 22438 | #include <linux/regulator/machine.h>
#include <linux/mfd/wm831x/pdata.h>
#include <linux/mfd/wm831x/core.h>
#include <linux/mfd/wm831x/gpio.h>
#include <linux/mfd/wm831x/pmu.h>
#include <mach/sram.h>
#include <linux/earlysuspend.h>
/* wm8326 pmu*/
#if defined(CONFIG_GPIO_WM831X)
static struct rk29_gpio_expander_info wm831x_gpio_settinginfo[] = {
{
.gpio_num = WM831X_P01, // tp3
.pin_type = GPIO_OUT,
.pin_value = GPIO_LOW,
},
{
.gpio_num = WM831X_P02, //tp4
.pin_type = GPIO_IN,
},
{
.gpio_num = WM831X_P03, //tp2
.pin_type = GPIO_OUT,
.pin_value = GPIO_HIGH,
},
{
.gpio_num = WM831X_P04, //tp1
.pin_type = GPIO_IN,
},
{
.gpio_num = WM831X_P05, //tp1
.pin_type = GPIO_IN,
},
{
.gpio_num = WM831X_P06, //tp1
.pin_type = GPIO_OUT,
.pin_value = GPIO_HIGH,
},
{
.gpio_num = WM831X_P07, //tp1
.pin_type = GPIO_IN,
},
{
.gpio_num = WM831X_P08, //tp1
.pin_type = GPIO_OUT,
.pin_value = GPIO_HIGH,
},
{
.gpio_num = WM831X_P09, //tp1
.pin_type = GPIO_OUT,
.pin_value = GPIO_HIGH,
},
{
.gpio_num = WM831X_P10, //tp1
.pin_type = GPIO_IN,
},
{
.gpio_num = WM831X_P11, //tp1
.pin_type = GPIO_OUT,
.pin_value = GPIO_HIGH,
},
{
.gpio_num = WM831X_P12,
.pin_type = GPIO_OUT,
.pin_value = GPIO_HIGH,
},
};
#endif
#if defined(CONFIG_MFD_WM831X)
#define UNLOCK_SECURITY_KEY ~(0x1<<5)
#define LOCK_SECURITY_KEY 0x00
static struct wm831x *Wm831x;
static int wm831x_pre_init(struct wm831x *parm)
{
int ret;
Wm831x = parm;
printk("%s\n", __func__);
#ifdef CONFIG_RK_CONFIG
if(sram_gpio_init(get_port_config(pmic_slp).gpio, &pmic_sleep) < 0){
printk(KERN_ERR "sram_gpio_init failed\n");
return -EINVAL;
}
if(port_output_init(pmic_slp, 0, "pmic_slp") < 0){
printk(KERN_ERR "port_output_init failed\n");
return -EINVAL;
}
#else
if(sram_gpio_init(PMU_POWER_SLEEP, &pmic_sleep) < 0){
printk(KERN_ERR "sram_gpio_init failed\n");
return -EINVAL;
}
gpio_request(PMU_POWER_SLEEP, "NULL");
gpio_direction_output(PMU_POWER_SLEEP, GPIO_LOW);
#endif
#ifdef CONFIG_WM8326_VBAT_LOW_DETECTION
#ifdef CONFIG_BATTERY_RK30_VOL3V8
wm831x_set_bits(parm,WM831X_SYSVDD_CONTROL ,0xc077,0xc035); //pvdd power on dect vbat voltage
printk("+++The vbat is too low+++\n");
#endif
#endif
ret = wm831x_reg_read(parm, WM831X_POWER_STATE) & 0xffff;
wm831x_reg_write(parm, WM831X_POWER_STATE, (ret & 0xfff8) | 0x04);
wm831x_set_bits(parm, WM831X_RTC_CONTROL, WM831X_RTC_ALAM_ENA_MASK, 0x0400);//enable rtc alam
//BATT_FET_ENA = 1
wm831x_reg_write(parm, WM831X_SECURITY_KEY, 0x9716); // unlock security key
wm831x_set_bits(parm, WM831X_RESET_CONTROL, 0x1003, 0x1001);
ret = wm831x_reg_read(parm, WM831X_RESET_CONTROL) & 0xffff & UNLOCK_SECURITY_KEY; // enternal reset active in sleep
// printk("%s:WM831X_RESET_CONTROL=0x%x\n", __func__, ret);
wm831x_reg_write(parm, WM831X_RESET_CONTROL, ret);
wm831x_set_bits(parm,WM831X_DC1_ON_CONFIG ,0x0300,0x0000); //set dcdc mode is FCCM
wm831x_set_bits(parm,WM831X_DC2_ON_CONFIG ,0x0300,0x0000);
wm831x_set_bits(parm,WM831X_DC3_ON_CONFIG ,0x0300,0x0000);
wm831x_set_bits(parm,0x4066,0x0300,0x0000);
#ifndef CONFIG_MACH_RK3066_SDK
wm831x_set_bits(parm,WM831X_LDO10_CONTROL ,0x0040,0x0040);// set ldo10 in switch mode
#endif
wm831x_set_bits(parm,WM831X_STATUS_LED_1 ,0xc300,0xc100);// set led1 on(in manual mode)
wm831x_set_bits(parm,WM831X_STATUS_LED_2 ,0xc300,0xc000);//set led2 off(in manual mode)
wm831x_set_bits(parm,WM831X_LDO5_SLEEP_CONTROL ,0xe000,0x2000);// set ldo5 is disable in sleep mode
wm831x_set_bits(parm,WM831X_LDO1_SLEEP_CONTROL ,0xe000,0x2000);// set ldo1 is disable in sleep mode
wm831x_reg_write(parm, WM831X_SECURITY_KEY, LOCK_SECURITY_KEY); // lock security key
return 0;
}
static int wm831x_mask_interrupt(struct wm831x *Wm831x)
{
/**************************clear interrupt********************/
wm831x_reg_write(Wm831x,WM831X_INTERRUPT_STATUS_1,0xffff);
wm831x_reg_write(Wm831x,WM831X_INTERRUPT_STATUS_2,0xffff);
wm831x_reg_write(Wm831x,WM831X_INTERRUPT_STATUS_3,0xffff);
wm831x_reg_write(Wm831x,WM831X_INTERRUPT_STATUS_4,0xffff);
wm831x_reg_write(Wm831x,WM831X_INTERRUPT_STATUS_5,0xffff);
wm831x_reg_write(Wm831x,WM831X_SYSTEM_INTERRUPTS_MASK,0xbedc); //mask interrupt which not used
return 0;
/*****************************************************************/
}
#ifdef CONFIG_WM8326_VBAT_LOW_DETECTION
static int wm831x_low_power_detection(struct wm831x *wm831x)
{
#ifdef CONFIG_BATTERY_RK30_VOL3V8
wm831x_reg_write(wm831x,WM831X_SYSTEM_INTERRUPTS_MASK,0xbe5c);
wm831x_set_bits(wm831x,WM831X_INTERRUPT_STATUS_1_MASK,0x8000,0x0000);
wm831x_set_bits(wm831x,WM831X_SYSVDD_CONTROL ,0xc077,0x0035); //set pvdd low voltage is 3.1v hi voltage is 3.3v
#else
wm831x_reg_write(wm831x,WM831X_AUXADC_CONTROL,0x803f); //open adc
wm831x_reg_write(wm831x,WM831X_AUXADC_CONTROL,0xd03f);
wm831x_reg_write(wm831x,WM831X_AUXADC_SOURCE,0x0001);
wm831x_reg_write(wm831x,WM831X_COMPARATOR_CONTROL,0x0001);
wm831x_reg_write(wm831x,WM831X_COMPARATOR_1,0x2844); //set the low power is 3.1v
wm831x_reg_write(wm831x,WM831X_INTERRUPT_STATUS_1_MASK,0x99ee);
wm831x_set_bits(wm831x,WM831X_SYSTEM_INTERRUPTS_MASK,0x0100,0x0000);
if (wm831x_reg_read(wm831x,WM831X_AUXADC_DATA)< 0x1844){
printk("The vbat is too low.\n");
wm831x_device_shutdown(wm831x);
}
#endif
return 0;
}
#endif
#define AVS_BASE 172
int wm831x_post_init(struct wm831x *Wm831x)
{
struct regulator *dcdc;
struct regulator *ldo;
int i = 0;
g_pmic_type = PMIC_TYPE_WM8326;
printk("%s:g_pmic_type=%d\n",__func__,g_pmic_type);
for(i = 0; i < ARRAY_SIZE(wm8326_dcdc_info); i++)
{
dcdc =regulator_get(NULL, wm8326_dcdc_info[i].name);
regulator_set_voltage(dcdc, wm8326_dcdc_info[i].min_uv, wm8326_dcdc_info[i].max_uv);
regulator_set_suspend_voltage(dcdc, wm8326_dcdc_info[i].suspend_vol);
regulator_enable(dcdc);
printk("%s %s =%dmV end\n", __func__,wm8326_dcdc_info[i].name, regulator_get_voltage(dcdc));
regulator_put(dcdc);
udelay(100);
}
for(i = 0; i < ARRAY_SIZE(wm8326_ldo_info); i++)
{
ldo =regulator_get(NULL, wm8326_ldo_info[i].name);
regulator_set_voltage(ldo, wm8326_ldo_info[i].min_uv, wm8326_ldo_info[i].max_uv);
regulator_set_suspend_voltage(ldo, wm8326_ldo_info[i].suspend_vol);
regulator_enable(ldo);
//printk("%s %s =%dmV end\n", __func__,tps65910_dcdc_info[i].name, regulator_get_voltage(ldo));
regulator_put(ldo);
udelay(100);
}
wm831x_mask_interrupt(Wm831x);
#ifdef CONFIG_WM8326_VBAT_LOW_DETECTION
wm831x_low_power_detection(Wm831x);
#endif
printk("wm831x_post_init end");
return 0;
}
static int wm831x_last_deinit(struct wm831x *Wm831x)
{
struct regulator *ldo;
printk("%s\n", __func__);
ldo = regulator_get(NULL, "ldo1");
regulator_disable(ldo);
regulator_put(ldo);
ldo = regulator_get(NULL, "ldo2");
regulator_disable(ldo);
regulator_put(ldo);
ldo = regulator_get(NULL, "ldo3");
regulator_disable(ldo);
regulator_put(ldo);
ldo = regulator_get(NULL, "ldo4");
//regulator_disable(ldo);
regulator_put(ldo);
ldo = regulator_get(NULL, "ldo5");
// regulator_disable(ldo);
regulator_put(ldo);
ldo = regulator_get(NULL, "ldo6");
// regulator_disable(ldo);
regulator_put(ldo);
ldo = regulator_get(NULL, "ldo7");
regulator_disable(ldo);
regulator_put(ldo);
ldo = regulator_get(NULL, "ldo8");
regulator_disable(ldo);
regulator_put(ldo);
ldo = regulator_get(NULL, "ldo9");
regulator_disable(ldo);
regulator_put(ldo);
ldo = regulator_get(NULL, "ldo10");
regulator_disable(ldo);
regulator_put(ldo);
return 0;
}
struct wm831x_status_pdata wm831x_status_platdata[WM831X_MAX_STATUS] = {
{
.default_src = WM831X_STATUS_OTP,
.name = "wm831x_status0",
.default_trigger = "wm831x_otp",
},
{
.default_src = WM831X_STATUS_POWER,
.name = "wm831x_status1",
.default_trigger = "wm831x_power",
},
};
static struct regulator_consumer_supply dcdc1_consumers[] = {
{
.supply = "vdd_core",
}
};
static struct regulator_consumer_supply dcdc2_consumers[] = {
{
.supply = "vdd_cpu",
}
};
static struct regulator_consumer_supply dcdc3_consumers[] = {
{
.supply = "dcdc3",
}
};
static struct regulator_consumer_supply dcdc4_consumers[] = {
{
.supply = "dcdc4",
}
};
#if 0
static struct regulator_consumer_supply epe1_consumers[] = {
{
.supply = "epe1",
}
};
static struct regulator_consumer_supply epe2_consumers[] = {
{
.supply = "epe2",
}
};
#endif
static struct regulator_consumer_supply ldo1_consumers[] = {
{
.supply = "ldo1",
}
};
static struct regulator_consumer_supply ldo2_consumers[] = {
{
.supply = "ldo2",
}
};
static struct regulator_consumer_supply ldo3_consumers[] = {
{
.supply = "ldo3",
}
};
static struct regulator_consumer_supply ldo4_consumers[] = {
{
.supply = "ldo4",
}
};
static struct regulator_consumer_supply ldo5_consumers[] = {
{
.supply = "ldo5",
}
};
static struct regulator_consumer_supply ldo6_consumers[] = {
{
.supply = "ldo6",
}
};
static struct regulator_consumer_supply ldo7_consumers[] = {
{
.supply = "ldo7",
}
};
static struct regulator_consumer_supply ldo8_consumers[] = {
{
.supply = "ldo8",
}
};
static struct regulator_consumer_supply ldo9_consumers[] = {
{
.supply = "ldo9",
}
};
static struct regulator_consumer_supply ldo10_consumers[] = {
{
.supply = "ldo10",
}
};
static struct regulator_consumer_supply ldo11_consumers[] = {
{
.supply = "ldo11",
}
};
struct regulator_init_data wm831x_regulator_init_dcdc[WM831X_MAX_DCDC] = {
{
.constraints = {
.name = "DCDC1",
.min_uV = 600000,
.max_uV = 1800000, //0.6-1.8V
.apply_uV = true,
.valid_ops_mask = REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_MODE,
.valid_modes_mask = REGULATOR_MODE_STANDBY | REGULATOR_MODE_NORMAL | REGULATOR_MODE_FAST | REGULATOR_MODE_IDLE,
},
.num_consumer_supplies = ARRAY_SIZE(dcdc1_consumers),
.consumer_supplies = dcdc1_consumers,
},
{
.constraints = {
.name = "DCDC2",
.min_uV = 600000,
.max_uV = 1800000, //0.6-1.8V
.apply_uV = true,
.valid_ops_mask = REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_MODE,
.valid_modes_mask = REGULATOR_MODE_STANDBY | REGULATOR_MODE_NORMAL | REGULATOR_MODE_FAST | REGULATOR_MODE_IDLE,
},
.num_consumer_supplies = ARRAY_SIZE(dcdc2_consumers),
.consumer_supplies = dcdc2_consumers,
},
{
.constraints = {
.name = "DCDC3",
.min_uV = 850000,
.max_uV = 3400000, //0.85-3.4V
.apply_uV = true,
.valid_ops_mask = REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_MODE,
.valid_modes_mask = REGULATOR_MODE_STANDBY | REGULATOR_MODE_NORMAL | REGULATOR_MODE_FAST | REGULATOR_MODE_IDLE,
},
.num_consumer_supplies = ARRAY_SIZE(dcdc3_consumers),
.consumer_supplies = dcdc3_consumers,
},
{
.constraints = {
.name = "DCDC4",
.min_uV = 850000,
.max_uV = 3400000, //0.85-3.4V
.apply_uV = true,
.valid_ops_mask = REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_MODE,
.valid_modes_mask = REGULATOR_MODE_STANDBY | REGULATOR_MODE_NORMAL | REGULATOR_MODE_FAST | REGULATOR_MODE_IDLE,
},
.num_consumer_supplies = ARRAY_SIZE(dcdc4_consumers),
.consumer_supplies = dcdc4_consumers,
},
};
#if 0
struct regulator_init_data wm831x_regulator_init_epe[WM831X_MAX_EPE] = {
{
.constraints = {
.name = "EPE1",
.min_uV = 1200000,
.max_uV = 3000000,
.apply_uV = true,
.valid_ops_mask = REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_VOLTAGE,
},
.num_consumer_supplies = ARRAY_SIZE(epe1_consumers),
.consumer_supplies = epe1_consumers,
},
{
.constraints = {
.name = "EPE2",
.min_uV = 1200000,
.max_uV = 3000000,
.apply_uV = true,
.valid_ops_mask = REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_VOLTAGE,
},
.num_consumer_supplies = ARRAY_SIZE(epe2_consumers),
.consumer_supplies = epe2_consumers,
},
};
#endif
struct regulator_init_data wm831x_regulator_init_ldo[WM831X_MAX_LDO] = {
{
.constraints = {
.name = "LDO1",
.min_uV = 900000,
.max_uV = 3300000,
.apply_uV = true,
.valid_ops_mask = REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_MODE,
.valid_modes_mask = REGULATOR_MODE_IDLE | REGULATOR_MODE_NORMAL,
},
.num_consumer_supplies = ARRAY_SIZE(ldo1_consumers),
.consumer_supplies = ldo1_consumers,
},
{
.constraints = {
.name = "LDO2",
.min_uV = 900000,
.max_uV = 3300000,
.apply_uV = true,
.valid_ops_mask = REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_MODE,
.valid_modes_mask = REGULATOR_MODE_IDLE | REGULATOR_MODE_NORMAL,
},
.num_consumer_supplies = ARRAY_SIZE(ldo2_consumers),
.consumer_supplies = ldo2_consumers,
},
{
.constraints = {
.name = "LDO3",
.min_uV = 900000,
.max_uV = 3300000,
.apply_uV = true,
.valid_ops_mask = REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_MODE,
.valid_modes_mask = REGULATOR_MODE_IDLE | REGULATOR_MODE_NORMAL,
},
.num_consumer_supplies = ARRAY_SIZE(ldo3_consumers),
.consumer_supplies = ldo3_consumers,
},
{
.constraints = {
.name = "LDO4",
.min_uV = 900000,
.max_uV = 3300000,
.apply_uV = true,
.valid_ops_mask = REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_MODE,
.valid_modes_mask = REGULATOR_MODE_IDLE | REGULATOR_MODE_NORMAL,
},
.num_consumer_supplies = ARRAY_SIZE(ldo4_consumers),
.consumer_supplies = ldo4_consumers,
},
{
.constraints = {
.name = "LDO5",
.min_uV = 900000,
.max_uV = 3300000,
.apply_uV = true,
.valid_ops_mask = REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_MODE,
.valid_modes_mask = REGULATOR_MODE_IDLE | REGULATOR_MODE_NORMAL,
},
.num_consumer_supplies = ARRAY_SIZE(ldo5_consumers),
.consumer_supplies = ldo5_consumers,
},
{
.constraints = {
.name = "LDO6",
.min_uV = 900000,
.max_uV = 3300000,
.apply_uV = true,
.valid_ops_mask = REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_MODE,
.valid_modes_mask = REGULATOR_MODE_IDLE | REGULATOR_MODE_NORMAL,
},
.num_consumer_supplies = ARRAY_SIZE(ldo6_consumers),
.consumer_supplies = ldo6_consumers,
},
{
.constraints = {
.name = "LDO7",
.min_uV = 1000000,
.max_uV = 3500000,
.apply_uV = true,
.valid_ops_mask = REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_MODE,
.valid_modes_mask = REGULATOR_MODE_IDLE | REGULATOR_MODE_NORMAL,
},
.num_consumer_supplies = ARRAY_SIZE(ldo7_consumers),
.consumer_supplies = ldo7_consumers,
},
{
.constraints = {
.name = "LDO8",
.min_uV = 1000000,
.max_uV = 3500000,
.apply_uV = true,
.valid_ops_mask = REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_MODE,
.valid_modes_mask = REGULATOR_MODE_IDLE | REGULATOR_MODE_NORMAL,
},
.num_consumer_supplies = ARRAY_SIZE(ldo8_consumers),
.consumer_supplies = ldo8_consumers,
},
{
.constraints = {
.name = "LDO9",
.min_uV = 1000000,
.max_uV = 3500000,
.apply_uV = true,
.valid_ops_mask = REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_MODE,
.valid_modes_mask = REGULATOR_MODE_IDLE | REGULATOR_MODE_NORMAL,
},
.num_consumer_supplies = ARRAY_SIZE(ldo9_consumers),
.consumer_supplies = ldo9_consumers,
},
{
.constraints = {
.name = "LDO10",
.min_uV = 1000000,
.max_uV = 3500000,
.apply_uV = true,
.valid_ops_mask = REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_MODE,
.valid_modes_mask = REGULATOR_MODE_IDLE | REGULATOR_MODE_NORMAL,
},
.num_consumer_supplies = ARRAY_SIZE(ldo10_consumers),
.consumer_supplies = ldo10_consumers,
},
{
.constraints = {
.name = "LDO11",
.min_uV = 800000,
.max_uV = 1550000,
.apply_uV = true,
.valid_ops_mask = REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_MODE,
.valid_modes_mask = REGULATOR_MODE_IDLE | REGULATOR_MODE_NORMAL,
},
.num_consumer_supplies = ARRAY_SIZE(ldo11_consumers),
.consumer_supplies = ldo11_consumers,
},
};
static int wm831x_init_pin_type(struct wm831x *wm831x)
{
struct wm831x_pdata *pdata;
struct rk29_gpio_expander_info *wm831x_gpio_settinginfo;
uint16_t wm831x_settingpin_num;
int i;
if (!wm831x || !wm831x->dev)
goto out;
pdata = wm831x->dev->platform_data;
if (!pdata)
goto out;
wm831x_gpio_settinginfo = pdata->settinginfo;
if (!wm831x_gpio_settinginfo)
goto out;
wm831x_settingpin_num = pdata->settinginfolen;
for (i = 0; i < wm831x_settingpin_num; i++) {
if (wm831x_gpio_settinginfo[i].pin_type == GPIO_IN) {
wm831x_set_bits(wm831x,
WM831X_GPIO1_CONTROL + i,
WM831X_GPN_DIR_MASK | WM831X_GPN_TRI_MASK,
1 << WM831X_GPN_DIR_SHIFT | 1 << WM831X_GPN_TRI_SHIFT);
if (i == 1) {
wm831x_set_bits(wm831x,
WM831X_GPIO1_CONTROL + i,
WM831X_GPN_POL_MASK,
0x0400);
wm831x_set_bits(wm831x,
WM831X_GPIO1_CONTROL + i,
WM831X_GPN_FN_MASK,
0x0003);
} // set gpio2 sleep/wakeup
if (i == 9) {
wm831x_set_bits(wm831x,
WM831X_GPIO1_CONTROL + i,
WM831X_GPN_PULL_MASK,
0x0000); //disable pullup/down
wm831x_set_bits(wm831x,
WM831X_GPIO1_CONTROL + i,
WM831X_GPN_PWR_DOM_MASK,
0x0800);
wm831x_set_bits(wm831x,
WM831X_GPIO1_CONTROL + i,
WM831X_GPN_ENA_MASK,
0x0000);
} //set gpio10 as adc input
} else {
wm831x_set_bits(wm831x,
WM831X_GPIO1_CONTROL + i,
WM831X_GPN_DIR_MASK | WM831X_GPN_TRI_MASK,
1 << WM831X_GPN_TRI_SHIFT);
if (wm831x_gpio_settinginfo[i].pin_value == GPIO_HIGH) {
wm831x_set_bits(wm831x, WM831X_GPIO_LEVEL, 1 << i, 1 << i);
} else {
wm831x_set_bits(wm831x, WM831X_GPIO_LEVEL, 1 << i, 0 << i);
}
if (i == 2) {
wm831x_set_bits(wm831x,
WM831X_GPIO1_CONTROL + i,
WM831X_GPN_PWR_DOM_MASK | WM831X_GPN_POL_MASK |WM831X_GPN_FN_MASK,
1 << WM831X_GPN_POL_SHIFT | 1 << WM831X_GPN_PWR_DOM_SHIFT | 1 << 0);
} // set gpio3 as clkout output 32.768K
}
}
#if 0
for (i = 0; i < pdata->gpio_pin_num; i++) {
wm831x_set_bits(wm831x,
WM831X_GPIO1_CONTROL + i,
WM831X_GPN_PULL_MASK | WM831X_GPN_POL_MASK | WM831X_GPN_OD_MASK | WM831X_GPN_TRI_MASK,
1 << WM831X_GPN_POL_SHIFT | 1 << WM831X_GPN_TRI_SHIFT);
ret = wm831x_reg_read(wm831x, WM831X_GPIO1_CONTROL + i);
printk("Gpio%d Pin Configuration = %x\n", i, ret);
}
#endif
out:
return 0;
}
#ifdef CONFIG_HAS_EARLYSUSPEND
void wm831x_pmu_early_suspend(struct early_suspend *h)
{
struct regulator *dcdc;
struct regulator *ldo;
printk("%s\n", __func__);
dcdc = regulator_get(NULL, "dcdc4"); //vcc_io
regulator_set_voltage(dcdc, 2800000, 2800000);
regulator_set_mode(dcdc, REGULATOR_MODE_STANDBY);
regulator_enable(dcdc);
printk("%s set dcdc4 vcc_io=%dmV end\n", __func__, regulator_get_voltage(dcdc));
regulator_put(dcdc);
udelay(100);
ldo = regulator_get(NULL, "ldo1"); //
regulator_set_mode(ldo, REGULATOR_MODE_IDLE);
regulator_enable(ldo);
regulator_put(ldo);
udelay(100);
ldo = regulator_get(NULL, "ldo4");
regulator_set_mode(ldo, REGULATOR_MODE_IDLE);
regulator_enable(ldo);
regulator_put(ldo);
udelay(100);
ldo = regulator_get(NULL, "ldo6");
regulator_set_mode(ldo, REGULATOR_MODE_IDLE);
regulator_enable(ldo);
regulator_put(ldo);
udelay(100);
ldo = regulator_get(NULL, "ldo8");
regulator_set_mode(ldo, REGULATOR_MODE_IDLE);
regulator_enable(ldo);
regulator_put(ldo);
udelay(100);
}
void wm831x_pmu_early_resume(struct early_suspend *h)
{
struct regulator *dcdc;
struct regulator *ldo;
printk("%s\n", __func__);
dcdc = regulator_get(NULL, "dcdc4"); //vcc_io
#ifdef CONFIG_MACH_RK3066_SDK
regulator_set_voltage(dcdc, 3300000, 3300000);
#else
regulator_set_voltage(dcdc, 3000000, 3000000);
#endif
regulator_set_mode(dcdc, REGULATOR_MODE_FAST);
regulator_enable(dcdc);
printk("%s set dcdc4 vcc_io=%dmV end\n", __func__, regulator_get_voltage(dcdc));
regulator_put(dcdc);
udelay(100);
ldo = regulator_get(NULL, "ldo1"); //
regulator_set_mode(ldo, REGULATOR_MODE_NORMAL);
regulator_enable(ldo);
regulator_put(ldo);
udelay(100);
ldo = regulator_get(NULL, "ldo4");
regulator_set_mode(ldo, REGULATOR_MODE_NORMAL);
regulator_enable(ldo);
regulator_put(ldo);
udelay(100);
ldo = regulator_get(NULL, "ldo6");
regulator_set_mode(ldo, REGULATOR_MODE_NORMAL);
regulator_enable(ldo);
regulator_put(ldo);
udelay(100);
ldo = regulator_get(NULL, "ldo8");
regulator_set_mode(ldo, REGULATOR_MODE_NORMAL);
regulator_enable(ldo);
regulator_put(ldo);
udelay(100);
}
#else
void wm831x_pmu_early_suspend(struct regulator_dev *rdev)
{
}
void wm831x_pmu_early_resume(struct regulator_dev *rdev)
{
}
#endif
void __sramfunc board_pmu_wm8326_suspend(void)
{
#ifdef CONFIG_CLK_SWITCH_TO_32K
sram_gpio_set_value(pmic_sleep, GPIO_HIGH);
#endif
}
void __sramfunc board_pmu_wm8326_resume(void)
{
#ifdef CONFIG_CLK_SWITCH_TO_32K
sram_gpio_set_value(pmic_sleep, GPIO_LOW);
sram_32k_udelay(10000);
#endif
}
static struct wm831x_pdata wm831x_platdata = {
/** Called before subdevices are set up */
.pre_init = wm831x_pre_init,
/** Called after subdevices are set up */
.post_init = wm831x_post_init,
/** Called before subdevices are power down */
.last_deinit = wm831x_last_deinit,
#if defined(CONFIG_GPIO_WM831X)
.gpio_base = WM831X_GPIO_EXPANDER_BASE,
.gpio_pin_num = WM831X_TOTOL_GPIO_NUM,
.settinginfo = wm831x_gpio_settinginfo,
.settinginfolen = ARRAY_SIZE(wm831x_gpio_settinginfo),
.pin_type_init = wm831x_init_pin_type,
.irq_base = IRQ_BOARD_BASE,
#endif
/** LED1 = 0 and so on */
.status = { &wm831x_status_platdata[0], &wm831x_status_platdata[1] },
/** DCDC1 = 0 and so on */
.dcdc = {
&wm831x_regulator_init_dcdc[0],
&wm831x_regulator_init_dcdc[1],
&wm831x_regulator_init_dcdc[2],
&wm831x_regulator_init_dcdc[3],
},
/** EPE1 = 0 and so on */
//.epe = { &wm831x_regulator_init_epe[0], &wm831x_regulator_init_epe[1] },
/** LDO1 = 0 and so on */
.ldo = {
&wm831x_regulator_init_ldo[0],
&wm831x_regulator_init_ldo[1],
&wm831x_regulator_init_ldo[2],
&wm831x_regulator_init_ldo[3],
&wm831x_regulator_init_ldo[4],
&wm831x_regulator_init_ldo[5],
&wm831x_regulator_init_ldo[6],
&wm831x_regulator_init_ldo[7],
&wm831x_regulator_init_ldo[8],
&wm831x_regulator_init_ldo[9],
&wm831x_regulator_init_ldo[10],
},
};
#endif
| gpl-2.0 |
explora26/kernel-hikey-linaro | sound/soc/codecs/wm8962.c | 321 | 122014 | /*
* wm8962.c -- WM8962 ALSA SoC Audio driver
*
* Copyright 2010-2 Wolfson Microelectronics plc
*
* Author: Mark Brown <broonie@opensource.wolfsonmicro.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/moduleparam.h>
#include <linux/init.h>
#include <linux/clk.h>
#include <linux/delay.h>
#include <linux/pm.h>
#include <linux/gcd.h>
#include <linux/gpio.h>
#include <linux/i2c.h>
#include <linux/input.h>
#include <linux/pm_runtime.h>
#include <linux/regmap.h>
#include <linux/regulator/consumer.h>
#include <linux/slab.h>
#include <linux/workqueue.h>
#include <linux/mutex.h>
#include <sound/core.h>
#include <sound/jack.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include <sound/initval.h>
#include <sound/tlv.h>
#include <sound/wm8962.h>
#include <trace/events/asoc.h>
#include "wm8962.h"
#define WM8962_NUM_SUPPLIES 8
static const char *wm8962_supply_names[WM8962_NUM_SUPPLIES] = {
"DCVDD",
"DBVDD",
"AVDD",
"CPVDD",
"MICVDD",
"PLLVDD",
"SPKVDD1",
"SPKVDD2",
};
/* codec private data */
struct wm8962_priv {
struct wm8962_pdata pdata;
struct regmap *regmap;
struct snd_soc_codec *codec;
int sysclk;
int sysclk_rate;
int bclk; /* Desired BCLK */
int lrclk;
struct completion fll_lock;
int fll_src;
int fll_fref;
int fll_fout;
struct mutex dsp2_ena_lock;
u16 dsp2_ena;
struct delayed_work mic_work;
struct snd_soc_jack *jack;
struct regulator_bulk_data supplies[WM8962_NUM_SUPPLIES];
struct notifier_block disable_nb[WM8962_NUM_SUPPLIES];
struct input_dev *beep;
struct work_struct beep_work;
int beep_rate;
#ifdef CONFIG_GPIOLIB
struct gpio_chip gpio_chip;
#endif
int irq;
};
/* We can't use the same notifier block for more than one supply and
* there's no way I can see to get from a callback to the caller
* except container_of().
*/
#define WM8962_REGULATOR_EVENT(n) \
static int wm8962_regulator_event_##n(struct notifier_block *nb, \
unsigned long event, void *data) \
{ \
struct wm8962_priv *wm8962 = container_of(nb, struct wm8962_priv, \
disable_nb[n]); \
if (event & REGULATOR_EVENT_DISABLE) { \
regcache_mark_dirty(wm8962->regmap); \
} \
return 0; \
}
WM8962_REGULATOR_EVENT(0)
WM8962_REGULATOR_EVENT(1)
WM8962_REGULATOR_EVENT(2)
WM8962_REGULATOR_EVENT(3)
WM8962_REGULATOR_EVENT(4)
WM8962_REGULATOR_EVENT(5)
WM8962_REGULATOR_EVENT(6)
WM8962_REGULATOR_EVENT(7)
static struct reg_default wm8962_reg[] = {
{ 0, 0x009F }, /* R0 - Left Input volume */
{ 1, 0x049F }, /* R1 - Right Input volume */
{ 2, 0x0000 }, /* R2 - HPOUTL volume */
{ 3, 0x0000 }, /* R3 - HPOUTR volume */
{ 5, 0x0018 }, /* R5 - ADC & DAC Control 1 */
{ 6, 0x2008 }, /* R6 - ADC & DAC Control 2 */
{ 7, 0x000A }, /* R7 - Audio Interface 0 */
{ 9, 0x0300 }, /* R9 - Audio Interface 1 */
{ 10, 0x00C0 }, /* R10 - Left DAC volume */
{ 11, 0x00C0 }, /* R11 - Right DAC volume */
{ 14, 0x0040 }, /* R14 - Audio Interface 2 */
{ 15, 0x6243 }, /* R15 - Software Reset */
{ 17, 0x007B }, /* R17 - ALC1 */
{ 19, 0x1C32 }, /* R19 - ALC3 */
{ 20, 0x3200 }, /* R20 - Noise Gate */
{ 21, 0x00C0 }, /* R21 - Left ADC volume */
{ 22, 0x00C0 }, /* R22 - Right ADC volume */
{ 23, 0x0160 }, /* R23 - Additional control(1) */
{ 24, 0x0000 }, /* R24 - Additional control(2) */
{ 25, 0x0000 }, /* R25 - Pwr Mgmt (1) */
{ 26, 0x0000 }, /* R26 - Pwr Mgmt (2) */
{ 27, 0x0010 }, /* R27 - Additional Control (3) */
{ 28, 0x0000 }, /* R28 - Anti-pop */
{ 30, 0x005E }, /* R30 - Clocking 3 */
{ 31, 0x0000 }, /* R31 - Input mixer control (1) */
{ 32, 0x0145 }, /* R32 - Left input mixer volume */
{ 33, 0x0145 }, /* R33 - Right input mixer volume */
{ 34, 0x0009 }, /* R34 - Input mixer control (2) */
{ 35, 0x0003 }, /* R35 - Input bias control */
{ 37, 0x0008 }, /* R37 - Left input PGA control */
{ 38, 0x0008 }, /* R38 - Right input PGA control */
{ 40, 0x0000 }, /* R40 - SPKOUTL volume */
{ 41, 0x0000 }, /* R41 - SPKOUTR volume */
{ 49, 0x0010 }, /* R49 - Class D Control 1 */
{ 51, 0x0003 }, /* R51 - Class D Control 2 */
{ 56, 0x0506 }, /* R56 - Clocking 4 */
{ 57, 0x0000 }, /* R57 - DAC DSP Mixing (1) */
{ 58, 0x0000 }, /* R58 - DAC DSP Mixing (2) */
{ 60, 0x0300 }, /* R60 - DC Servo 0 */
{ 61, 0x0300 }, /* R61 - DC Servo 1 */
{ 64, 0x0810 }, /* R64 - DC Servo 4 */
{ 68, 0x001B }, /* R68 - Analogue PGA Bias */
{ 69, 0x0000 }, /* R69 - Analogue HP 0 */
{ 71, 0x01FB }, /* R71 - Analogue HP 2 */
{ 72, 0x0000 }, /* R72 - Charge Pump 1 */
{ 82, 0x0004 }, /* R82 - Charge Pump B */
{ 87, 0x0000 }, /* R87 - Write Sequencer Control 1 */
{ 90, 0x0000 }, /* R90 - Write Sequencer Control 2 */
{ 93, 0x0000 }, /* R93 - Write Sequencer Control 3 */
{ 94, 0x0000 }, /* R94 - Control Interface */
{ 99, 0x0000 }, /* R99 - Mixer Enables */
{ 100, 0x0000 }, /* R100 - Headphone Mixer (1) */
{ 101, 0x0000 }, /* R101 - Headphone Mixer (2) */
{ 102, 0x013F }, /* R102 - Headphone Mixer (3) */
{ 103, 0x013F }, /* R103 - Headphone Mixer (4) */
{ 105, 0x0000 }, /* R105 - Speaker Mixer (1) */
{ 106, 0x0000 }, /* R106 - Speaker Mixer (2) */
{ 107, 0x013F }, /* R107 - Speaker Mixer (3) */
{ 108, 0x013F }, /* R108 - Speaker Mixer (4) */
{ 109, 0x0003 }, /* R109 - Speaker Mixer (5) */
{ 110, 0x0002 }, /* R110 - Beep Generator (1) */
{ 115, 0x0006 }, /* R115 - Oscillator Trim (3) */
{ 116, 0x0026 }, /* R116 - Oscillator Trim (4) */
{ 119, 0x0000 }, /* R119 - Oscillator Trim (7) */
{ 124, 0x0011 }, /* R124 - Analogue Clocking1 */
{ 125, 0x004B }, /* R125 - Analogue Clocking2 */
{ 126, 0x000D }, /* R126 - Analogue Clocking3 */
{ 127, 0x0000 }, /* R127 - PLL Software Reset */
{ 131, 0x0000 }, /* R131 - PLL 4 */
{ 136, 0x0067 }, /* R136 - PLL 9 */
{ 137, 0x001C }, /* R137 - PLL 10 */
{ 138, 0x0071 }, /* R138 - PLL 11 */
{ 139, 0x00C7 }, /* R139 - PLL 12 */
{ 140, 0x0067 }, /* R140 - PLL 13 */
{ 141, 0x0048 }, /* R141 - PLL 14 */
{ 142, 0x0022 }, /* R142 - PLL 15 */
{ 143, 0x0097 }, /* R143 - PLL 16 */
{ 155, 0x000C }, /* R155 - FLL Control (1) */
{ 156, 0x0039 }, /* R156 - FLL Control (2) */
{ 157, 0x0180 }, /* R157 - FLL Control (3) */
{ 159, 0x0032 }, /* R159 - FLL Control (5) */
{ 160, 0x0018 }, /* R160 - FLL Control (6) */
{ 161, 0x007D }, /* R161 - FLL Control (7) */
{ 162, 0x0008 }, /* R162 - FLL Control (8) */
{ 252, 0x0005 }, /* R252 - General test 1 */
{ 256, 0x0000 }, /* R256 - DF1 */
{ 257, 0x0000 }, /* R257 - DF2 */
{ 258, 0x0000 }, /* R258 - DF3 */
{ 259, 0x0000 }, /* R259 - DF4 */
{ 260, 0x0000 }, /* R260 - DF5 */
{ 261, 0x0000 }, /* R261 - DF6 */
{ 262, 0x0000 }, /* R262 - DF7 */
{ 264, 0x0000 }, /* R264 - LHPF1 */
{ 265, 0x0000 }, /* R265 - LHPF2 */
{ 268, 0x0000 }, /* R268 - THREED1 */
{ 269, 0x0000 }, /* R269 - THREED2 */
{ 270, 0x0000 }, /* R270 - THREED3 */
{ 271, 0x0000 }, /* R271 - THREED4 */
{ 276, 0x000C }, /* R276 - DRC 1 */
{ 277, 0x0925 }, /* R277 - DRC 2 */
{ 278, 0x0000 }, /* R278 - DRC 3 */
{ 279, 0x0000 }, /* R279 - DRC 4 */
{ 280, 0x0000 }, /* R280 - DRC 5 */
{ 285, 0x0000 }, /* R285 - Tloopback */
{ 335, 0x0004 }, /* R335 - EQ1 */
{ 336, 0x6318 }, /* R336 - EQ2 */
{ 337, 0x6300 }, /* R337 - EQ3 */
{ 338, 0x0FCA }, /* R338 - EQ4 */
{ 339, 0x0400 }, /* R339 - EQ5 */
{ 340, 0x00D8 }, /* R340 - EQ6 */
{ 341, 0x1EB5 }, /* R341 - EQ7 */
{ 342, 0xF145 }, /* R342 - EQ8 */
{ 343, 0x0B75 }, /* R343 - EQ9 */
{ 344, 0x01C5 }, /* R344 - EQ10 */
{ 345, 0x1C58 }, /* R345 - EQ11 */
{ 346, 0xF373 }, /* R346 - EQ12 */
{ 347, 0x0A54 }, /* R347 - EQ13 */
{ 348, 0x0558 }, /* R348 - EQ14 */
{ 349, 0x168E }, /* R349 - EQ15 */
{ 350, 0xF829 }, /* R350 - EQ16 */
{ 351, 0x07AD }, /* R351 - EQ17 */
{ 352, 0x1103 }, /* R352 - EQ18 */
{ 353, 0x0564 }, /* R353 - EQ19 */
{ 354, 0x0559 }, /* R354 - EQ20 */
{ 355, 0x4000 }, /* R355 - EQ21 */
{ 356, 0x6318 }, /* R356 - EQ22 */
{ 357, 0x6300 }, /* R357 - EQ23 */
{ 358, 0x0FCA }, /* R358 - EQ24 */
{ 359, 0x0400 }, /* R359 - EQ25 */
{ 360, 0x00D8 }, /* R360 - EQ26 */
{ 361, 0x1EB5 }, /* R361 - EQ27 */
{ 362, 0xF145 }, /* R362 - EQ28 */
{ 363, 0x0B75 }, /* R363 - EQ29 */
{ 364, 0x01C5 }, /* R364 - EQ30 */
{ 365, 0x1C58 }, /* R365 - EQ31 */
{ 366, 0xF373 }, /* R366 - EQ32 */
{ 367, 0x0A54 }, /* R367 - EQ33 */
{ 368, 0x0558 }, /* R368 - EQ34 */
{ 369, 0x168E }, /* R369 - EQ35 */
{ 370, 0xF829 }, /* R370 - EQ36 */
{ 371, 0x07AD }, /* R371 - EQ37 */
{ 372, 0x1103 }, /* R372 - EQ38 */
{ 373, 0x0564 }, /* R373 - EQ39 */
{ 374, 0x0559 }, /* R374 - EQ40 */
{ 375, 0x4000 }, /* R375 - EQ41 */
{ 513, 0x0000 }, /* R513 - GPIO 2 */
{ 514, 0x0000 }, /* R514 - GPIO 3 */
{ 516, 0x8100 }, /* R516 - GPIO 5 */
{ 517, 0x8100 }, /* R517 - GPIO 6 */
{ 568, 0x0030 }, /* R568 - Interrupt Status 1 Mask */
{ 569, 0xFFED }, /* R569 - Interrupt Status 2 Mask */
{ 576, 0x0000 }, /* R576 - Interrupt Control */
{ 584, 0x002D }, /* R584 - IRQ Debounce */
{ 586, 0x0000 }, /* R586 - MICINT Source Pol */
{ 768, 0x1C00 }, /* R768 - DSP2 Power Management */
{ 8192, 0x0000 }, /* R8192 - DSP2 Instruction RAM 0 */
{ 9216, 0x0030 }, /* R9216 - DSP2 Address RAM 2 */
{ 9217, 0x0000 }, /* R9217 - DSP2 Address RAM 1 */
{ 9218, 0x0000 }, /* R9218 - DSP2 Address RAM 0 */
{ 12288, 0x0000 }, /* R12288 - DSP2 Data1 RAM 1 */
{ 12289, 0x0000 }, /* R12289 - DSP2 Data1 RAM 0 */
{ 13312, 0x0000 }, /* R13312 - DSP2 Data2 RAM 1 */
{ 13313, 0x0000 }, /* R13313 - DSP2 Data2 RAM 0 */
{ 14336, 0x0000 }, /* R14336 - DSP2 Data3 RAM 1 */
{ 14337, 0x0000 }, /* R14337 - DSP2 Data3 RAM 0 */
{ 15360, 0x000A }, /* R15360 - DSP2 Coeff RAM 0 */
{ 16384, 0x0000 }, /* R16384 - RETUNEADC_SHARED_COEFF_1 */
{ 16385, 0x0000 }, /* R16385 - RETUNEADC_SHARED_COEFF_0 */
{ 16386, 0x0000 }, /* R16386 - RETUNEDAC_SHARED_COEFF_1 */
{ 16387, 0x0000 }, /* R16387 - RETUNEDAC_SHARED_COEFF_0 */
{ 16388, 0x0000 }, /* R16388 - SOUNDSTAGE_ENABLES_1 */
{ 16389, 0x0000 }, /* R16389 - SOUNDSTAGE_ENABLES_0 */
{ 16896, 0x0002 }, /* R16896 - HDBASS_AI_1 */
{ 16897, 0xBD12 }, /* R16897 - HDBASS_AI_0 */
{ 16898, 0x007C }, /* R16898 - HDBASS_AR_1 */
{ 16899, 0x586C }, /* R16899 - HDBASS_AR_0 */
{ 16900, 0x0053 }, /* R16900 - HDBASS_B_1 */
{ 16901, 0x8121 }, /* R16901 - HDBASS_B_0 */
{ 16902, 0x003F }, /* R16902 - HDBASS_K_1 */
{ 16903, 0x8BD8 }, /* R16903 - HDBASS_K_0 */
{ 16904, 0x0032 }, /* R16904 - HDBASS_N1_1 */
{ 16905, 0xF52D }, /* R16905 - HDBASS_N1_0 */
{ 16906, 0x0065 }, /* R16906 - HDBASS_N2_1 */
{ 16907, 0xAC8C }, /* R16907 - HDBASS_N2_0 */
{ 16908, 0x006B }, /* R16908 - HDBASS_N3_1 */
{ 16909, 0xE087 }, /* R16909 - HDBASS_N3_0 */
{ 16910, 0x0072 }, /* R16910 - HDBASS_N4_1 */
{ 16911, 0x1483 }, /* R16911 - HDBASS_N4_0 */
{ 16912, 0x0072 }, /* R16912 - HDBASS_N5_1 */
{ 16913, 0x1483 }, /* R16913 - HDBASS_N5_0 */
{ 16914, 0x0043 }, /* R16914 - HDBASS_X1_1 */
{ 16915, 0x3525 }, /* R16915 - HDBASS_X1_0 */
{ 16916, 0x0006 }, /* R16916 - HDBASS_X2_1 */
{ 16917, 0x6A4A }, /* R16917 - HDBASS_X2_0 */
{ 16918, 0x0043 }, /* R16918 - HDBASS_X3_1 */
{ 16919, 0x6079 }, /* R16919 - HDBASS_X3_0 */
{ 16920, 0x0008 }, /* R16920 - HDBASS_ATK_1 */
{ 16921, 0x0000 }, /* R16921 - HDBASS_ATK_0 */
{ 16922, 0x0001 }, /* R16922 - HDBASS_DCY_1 */
{ 16923, 0x0000 }, /* R16923 - HDBASS_DCY_0 */
{ 16924, 0x0059 }, /* R16924 - HDBASS_PG_1 */
{ 16925, 0x999A }, /* R16925 - HDBASS_PG_0 */
{ 17048, 0x0083 }, /* R17408 - HPF_C_1 */
{ 17049, 0x98AD }, /* R17409 - HPF_C_0 */
{ 17920, 0x007F }, /* R17920 - ADCL_RETUNE_C1_1 */
{ 17921, 0xFFFF }, /* R17921 - ADCL_RETUNE_C1_0 */
{ 17922, 0x0000 }, /* R17922 - ADCL_RETUNE_C2_1 */
{ 17923, 0x0000 }, /* R17923 - ADCL_RETUNE_C2_0 */
{ 17924, 0x0000 }, /* R17924 - ADCL_RETUNE_C3_1 */
{ 17925, 0x0000 }, /* R17925 - ADCL_RETUNE_C3_0 */
{ 17926, 0x0000 }, /* R17926 - ADCL_RETUNE_C4_1 */
{ 17927, 0x0000 }, /* R17927 - ADCL_RETUNE_C4_0 */
{ 17928, 0x0000 }, /* R17928 - ADCL_RETUNE_C5_1 */
{ 17929, 0x0000 }, /* R17929 - ADCL_RETUNE_C5_0 */
{ 17930, 0x0000 }, /* R17930 - ADCL_RETUNE_C6_1 */
{ 17931, 0x0000 }, /* R17931 - ADCL_RETUNE_C6_0 */
{ 17932, 0x0000 }, /* R17932 - ADCL_RETUNE_C7_1 */
{ 17933, 0x0000 }, /* R17933 - ADCL_RETUNE_C7_0 */
{ 17934, 0x0000 }, /* R17934 - ADCL_RETUNE_C8_1 */
{ 17935, 0x0000 }, /* R17935 - ADCL_RETUNE_C8_0 */
{ 17936, 0x0000 }, /* R17936 - ADCL_RETUNE_C9_1 */
{ 17937, 0x0000 }, /* R17937 - ADCL_RETUNE_C9_0 */
{ 17938, 0x0000 }, /* R17938 - ADCL_RETUNE_C10_1 */
{ 17939, 0x0000 }, /* R17939 - ADCL_RETUNE_C10_0 */
{ 17940, 0x0000 }, /* R17940 - ADCL_RETUNE_C11_1 */
{ 17941, 0x0000 }, /* R17941 - ADCL_RETUNE_C11_0 */
{ 17942, 0x0000 }, /* R17942 - ADCL_RETUNE_C12_1 */
{ 17943, 0x0000 }, /* R17943 - ADCL_RETUNE_C12_0 */
{ 17944, 0x0000 }, /* R17944 - ADCL_RETUNE_C13_1 */
{ 17945, 0x0000 }, /* R17945 - ADCL_RETUNE_C13_0 */
{ 17946, 0x0000 }, /* R17946 - ADCL_RETUNE_C14_1 */
{ 17947, 0x0000 }, /* R17947 - ADCL_RETUNE_C14_0 */
{ 17948, 0x0000 }, /* R17948 - ADCL_RETUNE_C15_1 */
{ 17949, 0x0000 }, /* R17949 - ADCL_RETUNE_C15_0 */
{ 17950, 0x0000 }, /* R17950 - ADCL_RETUNE_C16_1 */
{ 17951, 0x0000 }, /* R17951 - ADCL_RETUNE_C16_0 */
{ 17952, 0x0000 }, /* R17952 - ADCL_RETUNE_C17_1 */
{ 17953, 0x0000 }, /* R17953 - ADCL_RETUNE_C17_0 */
{ 17954, 0x0000 }, /* R17954 - ADCL_RETUNE_C18_1 */
{ 17955, 0x0000 }, /* R17955 - ADCL_RETUNE_C18_0 */
{ 17956, 0x0000 }, /* R17956 - ADCL_RETUNE_C19_1 */
{ 17957, 0x0000 }, /* R17957 - ADCL_RETUNE_C19_0 */
{ 17958, 0x0000 }, /* R17958 - ADCL_RETUNE_C20_1 */
{ 17959, 0x0000 }, /* R17959 - ADCL_RETUNE_C20_0 */
{ 17960, 0x0000 }, /* R17960 - ADCL_RETUNE_C21_1 */
{ 17961, 0x0000 }, /* R17961 - ADCL_RETUNE_C21_0 */
{ 17962, 0x0000 }, /* R17962 - ADCL_RETUNE_C22_1 */
{ 17963, 0x0000 }, /* R17963 - ADCL_RETUNE_C22_0 */
{ 17964, 0x0000 }, /* R17964 - ADCL_RETUNE_C23_1 */
{ 17965, 0x0000 }, /* R17965 - ADCL_RETUNE_C23_0 */
{ 17966, 0x0000 }, /* R17966 - ADCL_RETUNE_C24_1 */
{ 17967, 0x0000 }, /* R17967 - ADCL_RETUNE_C24_0 */
{ 17968, 0x0000 }, /* R17968 - ADCL_RETUNE_C25_1 */
{ 17969, 0x0000 }, /* R17969 - ADCL_RETUNE_C25_0 */
{ 17970, 0x0000 }, /* R17970 - ADCL_RETUNE_C26_1 */
{ 17971, 0x0000 }, /* R17971 - ADCL_RETUNE_C26_0 */
{ 17972, 0x0000 }, /* R17972 - ADCL_RETUNE_C27_1 */
{ 17973, 0x0000 }, /* R17973 - ADCL_RETUNE_C27_0 */
{ 17974, 0x0000 }, /* R17974 - ADCL_RETUNE_C28_1 */
{ 17975, 0x0000 }, /* R17975 - ADCL_RETUNE_C28_0 */
{ 17976, 0x0000 }, /* R17976 - ADCL_RETUNE_C29_1 */
{ 17977, 0x0000 }, /* R17977 - ADCL_RETUNE_C29_0 */
{ 17978, 0x0000 }, /* R17978 - ADCL_RETUNE_C30_1 */
{ 17979, 0x0000 }, /* R17979 - ADCL_RETUNE_C30_0 */
{ 17980, 0x0000 }, /* R17980 - ADCL_RETUNE_C31_1 */
{ 17981, 0x0000 }, /* R17981 - ADCL_RETUNE_C31_0 */
{ 17982, 0x0000 }, /* R17982 - ADCL_RETUNE_C32_1 */
{ 17983, 0x0000 }, /* R17983 - ADCL_RETUNE_C32_0 */
{ 18432, 0x0020 }, /* R18432 - RETUNEADC_PG2_1 */
{ 18433, 0x0000 }, /* R18433 - RETUNEADC_PG2_0 */
{ 18434, 0x0040 }, /* R18434 - RETUNEADC_PG_1 */
{ 18435, 0x0000 }, /* R18435 - RETUNEADC_PG_0 */
{ 18944, 0x007F }, /* R18944 - ADCR_RETUNE_C1_1 */
{ 18945, 0xFFFF }, /* R18945 - ADCR_RETUNE_C1_0 */
{ 18946, 0x0000 }, /* R18946 - ADCR_RETUNE_C2_1 */
{ 18947, 0x0000 }, /* R18947 - ADCR_RETUNE_C2_0 */
{ 18948, 0x0000 }, /* R18948 - ADCR_RETUNE_C3_1 */
{ 18949, 0x0000 }, /* R18949 - ADCR_RETUNE_C3_0 */
{ 18950, 0x0000 }, /* R18950 - ADCR_RETUNE_C4_1 */
{ 18951, 0x0000 }, /* R18951 - ADCR_RETUNE_C4_0 */
{ 18952, 0x0000 }, /* R18952 - ADCR_RETUNE_C5_1 */
{ 18953, 0x0000 }, /* R18953 - ADCR_RETUNE_C5_0 */
{ 18954, 0x0000 }, /* R18954 - ADCR_RETUNE_C6_1 */
{ 18955, 0x0000 }, /* R18955 - ADCR_RETUNE_C6_0 */
{ 18956, 0x0000 }, /* R18956 - ADCR_RETUNE_C7_1 */
{ 18957, 0x0000 }, /* R18957 - ADCR_RETUNE_C7_0 */
{ 18958, 0x0000 }, /* R18958 - ADCR_RETUNE_C8_1 */
{ 18959, 0x0000 }, /* R18959 - ADCR_RETUNE_C8_0 */
{ 18960, 0x0000 }, /* R18960 - ADCR_RETUNE_C9_1 */
{ 18961, 0x0000 }, /* R18961 - ADCR_RETUNE_C9_0 */
{ 18962, 0x0000 }, /* R18962 - ADCR_RETUNE_C10_1 */
{ 18963, 0x0000 }, /* R18963 - ADCR_RETUNE_C10_0 */
{ 18964, 0x0000 }, /* R18964 - ADCR_RETUNE_C11_1 */
{ 18965, 0x0000 }, /* R18965 - ADCR_RETUNE_C11_0 */
{ 18966, 0x0000 }, /* R18966 - ADCR_RETUNE_C12_1 */
{ 18967, 0x0000 }, /* R18967 - ADCR_RETUNE_C12_0 */
{ 18968, 0x0000 }, /* R18968 - ADCR_RETUNE_C13_1 */
{ 18969, 0x0000 }, /* R18969 - ADCR_RETUNE_C13_0 */
{ 18970, 0x0000 }, /* R18970 - ADCR_RETUNE_C14_1 */
{ 18971, 0x0000 }, /* R18971 - ADCR_RETUNE_C14_0 */
{ 18972, 0x0000 }, /* R18972 - ADCR_RETUNE_C15_1 */
{ 18973, 0x0000 }, /* R18973 - ADCR_RETUNE_C15_0 */
{ 18974, 0x0000 }, /* R18974 - ADCR_RETUNE_C16_1 */
{ 18975, 0x0000 }, /* R18975 - ADCR_RETUNE_C16_0 */
{ 18976, 0x0000 }, /* R18976 - ADCR_RETUNE_C17_1 */
{ 18977, 0x0000 }, /* R18977 - ADCR_RETUNE_C17_0 */
{ 18978, 0x0000 }, /* R18978 - ADCR_RETUNE_C18_1 */
{ 18979, 0x0000 }, /* R18979 - ADCR_RETUNE_C18_0 */
{ 18980, 0x0000 }, /* R18980 - ADCR_RETUNE_C19_1 */
{ 18981, 0x0000 }, /* R18981 - ADCR_RETUNE_C19_0 */
{ 18982, 0x0000 }, /* R18982 - ADCR_RETUNE_C20_1 */
{ 18983, 0x0000 }, /* R18983 - ADCR_RETUNE_C20_0 */
{ 18984, 0x0000 }, /* R18984 - ADCR_RETUNE_C21_1 */
{ 18985, 0x0000 }, /* R18985 - ADCR_RETUNE_C21_0 */
{ 18986, 0x0000 }, /* R18986 - ADCR_RETUNE_C22_1 */
{ 18987, 0x0000 }, /* R18987 - ADCR_RETUNE_C22_0 */
{ 18988, 0x0000 }, /* R18988 - ADCR_RETUNE_C23_1 */
{ 18989, 0x0000 }, /* R18989 - ADCR_RETUNE_C23_0 */
{ 18990, 0x0000 }, /* R18990 - ADCR_RETUNE_C24_1 */
{ 18991, 0x0000 }, /* R18991 - ADCR_RETUNE_C24_0 */
{ 18992, 0x0000 }, /* R18992 - ADCR_RETUNE_C25_1 */
{ 18993, 0x0000 }, /* R18993 - ADCR_RETUNE_C25_0 */
{ 18994, 0x0000 }, /* R18994 - ADCR_RETUNE_C26_1 */
{ 18995, 0x0000 }, /* R18995 - ADCR_RETUNE_C26_0 */
{ 18996, 0x0000 }, /* R18996 - ADCR_RETUNE_C27_1 */
{ 18997, 0x0000 }, /* R18997 - ADCR_RETUNE_C27_0 */
{ 18998, 0x0000 }, /* R18998 - ADCR_RETUNE_C28_1 */
{ 18999, 0x0000 }, /* R18999 - ADCR_RETUNE_C28_0 */
{ 19000, 0x0000 }, /* R19000 - ADCR_RETUNE_C29_1 */
{ 19001, 0x0000 }, /* R19001 - ADCR_RETUNE_C29_0 */
{ 19002, 0x0000 }, /* R19002 - ADCR_RETUNE_C30_1 */
{ 19003, 0x0000 }, /* R19003 - ADCR_RETUNE_C30_0 */
{ 19004, 0x0000 }, /* R19004 - ADCR_RETUNE_C31_1 */
{ 19005, 0x0000 }, /* R19005 - ADCR_RETUNE_C31_0 */
{ 19006, 0x0000 }, /* R19006 - ADCR_RETUNE_C32_1 */
{ 19007, 0x0000 }, /* R19007 - ADCR_RETUNE_C32_0 */
{ 19456, 0x007F }, /* R19456 - DACL_RETUNE_C1_1 */
{ 19457, 0xFFFF }, /* R19457 - DACL_RETUNE_C1_0 */
{ 19458, 0x0000 }, /* R19458 - DACL_RETUNE_C2_1 */
{ 19459, 0x0000 }, /* R19459 - DACL_RETUNE_C2_0 */
{ 19460, 0x0000 }, /* R19460 - DACL_RETUNE_C3_1 */
{ 19461, 0x0000 }, /* R19461 - DACL_RETUNE_C3_0 */
{ 19462, 0x0000 }, /* R19462 - DACL_RETUNE_C4_1 */
{ 19463, 0x0000 }, /* R19463 - DACL_RETUNE_C4_0 */
{ 19464, 0x0000 }, /* R19464 - DACL_RETUNE_C5_1 */
{ 19465, 0x0000 }, /* R19465 - DACL_RETUNE_C5_0 */
{ 19466, 0x0000 }, /* R19466 - DACL_RETUNE_C6_1 */
{ 19467, 0x0000 }, /* R19467 - DACL_RETUNE_C6_0 */
{ 19468, 0x0000 }, /* R19468 - DACL_RETUNE_C7_1 */
{ 19469, 0x0000 }, /* R19469 - DACL_RETUNE_C7_0 */
{ 19470, 0x0000 }, /* R19470 - DACL_RETUNE_C8_1 */
{ 19471, 0x0000 }, /* R19471 - DACL_RETUNE_C8_0 */
{ 19472, 0x0000 }, /* R19472 - DACL_RETUNE_C9_1 */
{ 19473, 0x0000 }, /* R19473 - DACL_RETUNE_C9_0 */
{ 19474, 0x0000 }, /* R19474 - DACL_RETUNE_C10_1 */
{ 19475, 0x0000 }, /* R19475 - DACL_RETUNE_C10_0 */
{ 19476, 0x0000 }, /* R19476 - DACL_RETUNE_C11_1 */
{ 19477, 0x0000 }, /* R19477 - DACL_RETUNE_C11_0 */
{ 19478, 0x0000 }, /* R19478 - DACL_RETUNE_C12_1 */
{ 19479, 0x0000 }, /* R19479 - DACL_RETUNE_C12_0 */
{ 19480, 0x0000 }, /* R19480 - DACL_RETUNE_C13_1 */
{ 19481, 0x0000 }, /* R19481 - DACL_RETUNE_C13_0 */
{ 19482, 0x0000 }, /* R19482 - DACL_RETUNE_C14_1 */
{ 19483, 0x0000 }, /* R19483 - DACL_RETUNE_C14_0 */
{ 19484, 0x0000 }, /* R19484 - DACL_RETUNE_C15_1 */
{ 19485, 0x0000 }, /* R19485 - DACL_RETUNE_C15_0 */
{ 19486, 0x0000 }, /* R19486 - DACL_RETUNE_C16_1 */
{ 19487, 0x0000 }, /* R19487 - DACL_RETUNE_C16_0 */
{ 19488, 0x0000 }, /* R19488 - DACL_RETUNE_C17_1 */
{ 19489, 0x0000 }, /* R19489 - DACL_RETUNE_C17_0 */
{ 19490, 0x0000 }, /* R19490 - DACL_RETUNE_C18_1 */
{ 19491, 0x0000 }, /* R19491 - DACL_RETUNE_C18_0 */
{ 19492, 0x0000 }, /* R19492 - DACL_RETUNE_C19_1 */
{ 19493, 0x0000 }, /* R19493 - DACL_RETUNE_C19_0 */
{ 19494, 0x0000 }, /* R19494 - DACL_RETUNE_C20_1 */
{ 19495, 0x0000 }, /* R19495 - DACL_RETUNE_C20_0 */
{ 19496, 0x0000 }, /* R19496 - DACL_RETUNE_C21_1 */
{ 19497, 0x0000 }, /* R19497 - DACL_RETUNE_C21_0 */
{ 19498, 0x0000 }, /* R19498 - DACL_RETUNE_C22_1 */
{ 19499, 0x0000 }, /* R19499 - DACL_RETUNE_C22_0 */
{ 19500, 0x0000 }, /* R19500 - DACL_RETUNE_C23_1 */
{ 19501, 0x0000 }, /* R19501 - DACL_RETUNE_C23_0 */
{ 19502, 0x0000 }, /* R19502 - DACL_RETUNE_C24_1 */
{ 19503, 0x0000 }, /* R19503 - DACL_RETUNE_C24_0 */
{ 19504, 0x0000 }, /* R19504 - DACL_RETUNE_C25_1 */
{ 19505, 0x0000 }, /* R19505 - DACL_RETUNE_C25_0 */
{ 19506, 0x0000 }, /* R19506 - DACL_RETUNE_C26_1 */
{ 19507, 0x0000 }, /* R19507 - DACL_RETUNE_C26_0 */
{ 19508, 0x0000 }, /* R19508 - DACL_RETUNE_C27_1 */
{ 19509, 0x0000 }, /* R19509 - DACL_RETUNE_C27_0 */
{ 19510, 0x0000 }, /* R19510 - DACL_RETUNE_C28_1 */
{ 19511, 0x0000 }, /* R19511 - DACL_RETUNE_C28_0 */
{ 19512, 0x0000 }, /* R19512 - DACL_RETUNE_C29_1 */
{ 19513, 0x0000 }, /* R19513 - DACL_RETUNE_C29_0 */
{ 19514, 0x0000 }, /* R19514 - DACL_RETUNE_C30_1 */
{ 19515, 0x0000 }, /* R19515 - DACL_RETUNE_C30_0 */
{ 19516, 0x0000 }, /* R19516 - DACL_RETUNE_C31_1 */
{ 19517, 0x0000 }, /* R19517 - DACL_RETUNE_C31_0 */
{ 19518, 0x0000 }, /* R19518 - DACL_RETUNE_C32_1 */
{ 19519, 0x0000 }, /* R19519 - DACL_RETUNE_C32_0 */
{ 19968, 0x0020 }, /* R19968 - RETUNEDAC_PG2_1 */
{ 19969, 0x0000 }, /* R19969 - RETUNEDAC_PG2_0 */
{ 19970, 0x0040 }, /* R19970 - RETUNEDAC_PG_1 */
{ 19971, 0x0000 }, /* R19971 - RETUNEDAC_PG_0 */
{ 20480, 0x007F }, /* R20480 - DACR_RETUNE_C1_1 */
{ 20481, 0xFFFF }, /* R20481 - DACR_RETUNE_C1_0 */
{ 20482, 0x0000 }, /* R20482 - DACR_RETUNE_C2_1 */
{ 20483, 0x0000 }, /* R20483 - DACR_RETUNE_C2_0 */
{ 20484, 0x0000 }, /* R20484 - DACR_RETUNE_C3_1 */
{ 20485, 0x0000 }, /* R20485 - DACR_RETUNE_C3_0 */
{ 20486, 0x0000 }, /* R20486 - DACR_RETUNE_C4_1 */
{ 20487, 0x0000 }, /* R20487 - DACR_RETUNE_C4_0 */
{ 20488, 0x0000 }, /* R20488 - DACR_RETUNE_C5_1 */
{ 20489, 0x0000 }, /* R20489 - DACR_RETUNE_C5_0 */
{ 20490, 0x0000 }, /* R20490 - DACR_RETUNE_C6_1 */
{ 20491, 0x0000 }, /* R20491 - DACR_RETUNE_C6_0 */
{ 20492, 0x0000 }, /* R20492 - DACR_RETUNE_C7_1 */
{ 20493, 0x0000 }, /* R20493 - DACR_RETUNE_C7_0 */
{ 20494, 0x0000 }, /* R20494 - DACR_RETUNE_C8_1 */
{ 20495, 0x0000 }, /* R20495 - DACR_RETUNE_C8_0 */
{ 20496, 0x0000 }, /* R20496 - DACR_RETUNE_C9_1 */
{ 20497, 0x0000 }, /* R20497 - DACR_RETUNE_C9_0 */
{ 20498, 0x0000 }, /* R20498 - DACR_RETUNE_C10_1 */
{ 20499, 0x0000 }, /* R20499 - DACR_RETUNE_C10_0 */
{ 20500, 0x0000 }, /* R20500 - DACR_RETUNE_C11_1 */
{ 20501, 0x0000 }, /* R20501 - DACR_RETUNE_C11_0 */
{ 20502, 0x0000 }, /* R20502 - DACR_RETUNE_C12_1 */
{ 20503, 0x0000 }, /* R20503 - DACR_RETUNE_C12_0 */
{ 20504, 0x0000 }, /* R20504 - DACR_RETUNE_C13_1 */
{ 20505, 0x0000 }, /* R20505 - DACR_RETUNE_C13_0 */
{ 20506, 0x0000 }, /* R20506 - DACR_RETUNE_C14_1 */
{ 20507, 0x0000 }, /* R20507 - DACR_RETUNE_C14_0 */
{ 20508, 0x0000 }, /* R20508 - DACR_RETUNE_C15_1 */
{ 20509, 0x0000 }, /* R20509 - DACR_RETUNE_C15_0 */
{ 20510, 0x0000 }, /* R20510 - DACR_RETUNE_C16_1 */
{ 20511, 0x0000 }, /* R20511 - DACR_RETUNE_C16_0 */
{ 20512, 0x0000 }, /* R20512 - DACR_RETUNE_C17_1 */
{ 20513, 0x0000 }, /* R20513 - DACR_RETUNE_C17_0 */
{ 20514, 0x0000 }, /* R20514 - DACR_RETUNE_C18_1 */
{ 20515, 0x0000 }, /* R20515 - DACR_RETUNE_C18_0 */
{ 20516, 0x0000 }, /* R20516 - DACR_RETUNE_C19_1 */
{ 20517, 0x0000 }, /* R20517 - DACR_RETUNE_C19_0 */
{ 20518, 0x0000 }, /* R20518 - DACR_RETUNE_C20_1 */
{ 20519, 0x0000 }, /* R20519 - DACR_RETUNE_C20_0 */
{ 20520, 0x0000 }, /* R20520 - DACR_RETUNE_C21_1 */
{ 20521, 0x0000 }, /* R20521 - DACR_RETUNE_C21_0 */
{ 20522, 0x0000 }, /* R20522 - DACR_RETUNE_C22_1 */
{ 20523, 0x0000 }, /* R20523 - DACR_RETUNE_C22_0 */
{ 20524, 0x0000 }, /* R20524 - DACR_RETUNE_C23_1 */
{ 20525, 0x0000 }, /* R20525 - DACR_RETUNE_C23_0 */
{ 20526, 0x0000 }, /* R20526 - DACR_RETUNE_C24_1 */
{ 20527, 0x0000 }, /* R20527 - DACR_RETUNE_C24_0 */
{ 20528, 0x0000 }, /* R20528 - DACR_RETUNE_C25_1 */
{ 20529, 0x0000 }, /* R20529 - DACR_RETUNE_C25_0 */
{ 20530, 0x0000 }, /* R20530 - DACR_RETUNE_C26_1 */
{ 20531, 0x0000 }, /* R20531 - DACR_RETUNE_C26_0 */
{ 20532, 0x0000 }, /* R20532 - DACR_RETUNE_C27_1 */
{ 20533, 0x0000 }, /* R20533 - DACR_RETUNE_C27_0 */
{ 20534, 0x0000 }, /* R20534 - DACR_RETUNE_C28_1 */
{ 20535, 0x0000 }, /* R20535 - DACR_RETUNE_C28_0 */
{ 20536, 0x0000 }, /* R20536 - DACR_RETUNE_C29_1 */
{ 20537, 0x0000 }, /* R20537 - DACR_RETUNE_C29_0 */
{ 20538, 0x0000 }, /* R20538 - DACR_RETUNE_C30_1 */
{ 20539, 0x0000 }, /* R20539 - DACR_RETUNE_C30_0 */
{ 20540, 0x0000 }, /* R20540 - DACR_RETUNE_C31_1 */
{ 20541, 0x0000 }, /* R20541 - DACR_RETUNE_C31_0 */
{ 20542, 0x0000 }, /* R20542 - DACR_RETUNE_C32_1 */
{ 20543, 0x0000 }, /* R20543 - DACR_RETUNE_C32_0 */
{ 20992, 0x008C }, /* R20992 - VSS_XHD2_1 */
{ 20993, 0x0200 }, /* R20993 - VSS_XHD2_0 */
{ 20994, 0x0035 }, /* R20994 - VSS_XHD3_1 */
{ 20995, 0x0700 }, /* R20995 - VSS_XHD3_0 */
{ 20996, 0x003A }, /* R20996 - VSS_XHN1_1 */
{ 20997, 0x4100 }, /* R20997 - VSS_XHN1_0 */
{ 20998, 0x008B }, /* R20998 - VSS_XHN2_1 */
{ 20999, 0x7D00 }, /* R20999 - VSS_XHN2_0 */
{ 21000, 0x003A }, /* R21000 - VSS_XHN3_1 */
{ 21001, 0x4100 }, /* R21001 - VSS_XHN3_0 */
{ 21002, 0x008C }, /* R21002 - VSS_XLA_1 */
{ 21003, 0xFEE8 }, /* R21003 - VSS_XLA_0 */
{ 21004, 0x0078 }, /* R21004 - VSS_XLB_1 */
{ 21005, 0x0000 }, /* R21005 - VSS_XLB_0 */
{ 21006, 0x003F }, /* R21006 - VSS_XLG_1 */
{ 21007, 0xB260 }, /* R21007 - VSS_XLG_0 */
{ 21008, 0x002D }, /* R21008 - VSS_PG2_1 */
{ 21009, 0x1818 }, /* R21009 - VSS_PG2_0 */
{ 21010, 0x0020 }, /* R21010 - VSS_PG_1 */
{ 21011, 0x0000 }, /* R21011 - VSS_PG_0 */
{ 21012, 0x00F1 }, /* R21012 - VSS_XTD1_1 */
{ 21013, 0x8340 }, /* R21013 - VSS_XTD1_0 */
{ 21014, 0x00FB }, /* R21014 - VSS_XTD2_1 */
{ 21015, 0x8300 }, /* R21015 - VSS_XTD2_0 */
{ 21016, 0x00EE }, /* R21016 - VSS_XTD3_1 */
{ 21017, 0xAEC0 }, /* R21017 - VSS_XTD3_0 */
{ 21018, 0x00FB }, /* R21018 - VSS_XTD4_1 */
{ 21019, 0xAC40 }, /* R21019 - VSS_XTD4_0 */
{ 21020, 0x00F1 }, /* R21020 - VSS_XTD5_1 */
{ 21021, 0x7F80 }, /* R21021 - VSS_XTD5_0 */
{ 21022, 0x00F4 }, /* R21022 - VSS_XTD6_1 */
{ 21023, 0x3B40 }, /* R21023 - VSS_XTD6_0 */
{ 21024, 0x00F5 }, /* R21024 - VSS_XTD7_1 */
{ 21025, 0xFB00 }, /* R21025 - VSS_XTD7_0 */
{ 21026, 0x00EA }, /* R21026 - VSS_XTD8_1 */
{ 21027, 0x10C0 }, /* R21027 - VSS_XTD8_0 */
{ 21028, 0x00FC }, /* R21028 - VSS_XTD9_1 */
{ 21029, 0xC580 }, /* R21029 - VSS_XTD9_0 */
{ 21030, 0x00E2 }, /* R21030 - VSS_XTD10_1 */
{ 21031, 0x75C0 }, /* R21031 - VSS_XTD10_0 */
{ 21032, 0x0004 }, /* R21032 - VSS_XTD11_1 */
{ 21033, 0xB480 }, /* R21033 - VSS_XTD11_0 */
{ 21034, 0x00D4 }, /* R21034 - VSS_XTD12_1 */
{ 21035, 0xF980 }, /* R21035 - VSS_XTD12_0 */
{ 21036, 0x0004 }, /* R21036 - VSS_XTD13_1 */
{ 21037, 0x9140 }, /* R21037 - VSS_XTD13_0 */
{ 21038, 0x00D8 }, /* R21038 - VSS_XTD14_1 */
{ 21039, 0xA480 }, /* R21039 - VSS_XTD14_0 */
{ 21040, 0x0002 }, /* R21040 - VSS_XTD15_1 */
{ 21041, 0x3DC0 }, /* R21041 - VSS_XTD15_0 */
{ 21042, 0x00CF }, /* R21042 - VSS_XTD16_1 */
{ 21043, 0x7A80 }, /* R21043 - VSS_XTD16_0 */
{ 21044, 0x00DC }, /* R21044 - VSS_XTD17_1 */
{ 21045, 0x0600 }, /* R21045 - VSS_XTD17_0 */
{ 21046, 0x00F2 }, /* R21046 - VSS_XTD18_1 */
{ 21047, 0xDAC0 }, /* R21047 - VSS_XTD18_0 */
{ 21048, 0x00BA }, /* R21048 - VSS_XTD19_1 */
{ 21049, 0xF340 }, /* R21049 - VSS_XTD19_0 */
{ 21050, 0x000A }, /* R21050 - VSS_XTD20_1 */
{ 21051, 0x7940 }, /* R21051 - VSS_XTD20_0 */
{ 21052, 0x001C }, /* R21052 - VSS_XTD21_1 */
{ 21053, 0x0680 }, /* R21053 - VSS_XTD21_0 */
{ 21054, 0x00FD }, /* R21054 - VSS_XTD22_1 */
{ 21055, 0x2D00 }, /* R21055 - VSS_XTD22_0 */
{ 21056, 0x001C }, /* R21056 - VSS_XTD23_1 */
{ 21057, 0xE840 }, /* R21057 - VSS_XTD23_0 */
{ 21058, 0x000D }, /* R21058 - VSS_XTD24_1 */
{ 21059, 0xDC40 }, /* R21059 - VSS_XTD24_0 */
{ 21060, 0x00FC }, /* R21060 - VSS_XTD25_1 */
{ 21061, 0x9D00 }, /* R21061 - VSS_XTD25_0 */
{ 21062, 0x0009 }, /* R21062 - VSS_XTD26_1 */
{ 21063, 0x5580 }, /* R21063 - VSS_XTD26_0 */
{ 21064, 0x00FE }, /* R21064 - VSS_XTD27_1 */
{ 21065, 0x7E80 }, /* R21065 - VSS_XTD27_0 */
{ 21066, 0x000E }, /* R21066 - VSS_XTD28_1 */
{ 21067, 0xAB40 }, /* R21067 - VSS_XTD28_0 */
{ 21068, 0x00F9 }, /* R21068 - VSS_XTD29_1 */
{ 21069, 0x9880 }, /* R21069 - VSS_XTD29_0 */
{ 21070, 0x0009 }, /* R21070 - VSS_XTD30_1 */
{ 21071, 0x87C0 }, /* R21071 - VSS_XTD30_0 */
{ 21072, 0x00FD }, /* R21072 - VSS_XTD31_1 */
{ 21073, 0x2C40 }, /* R21073 - VSS_XTD31_0 */
{ 21074, 0x0009 }, /* R21074 - VSS_XTD32_1 */
{ 21075, 0x4800 }, /* R21075 - VSS_XTD32_0 */
{ 21076, 0x0003 }, /* R21076 - VSS_XTS1_1 */
{ 21077, 0x5F40 }, /* R21077 - VSS_XTS1_0 */
{ 21078, 0x0000 }, /* R21078 - VSS_XTS2_1 */
{ 21079, 0x8700 }, /* R21079 - VSS_XTS2_0 */
{ 21080, 0x00FA }, /* R21080 - VSS_XTS3_1 */
{ 21081, 0xE4C0 }, /* R21081 - VSS_XTS3_0 */
{ 21082, 0x0000 }, /* R21082 - VSS_XTS4_1 */
{ 21083, 0x0B40 }, /* R21083 - VSS_XTS4_0 */
{ 21084, 0x0004 }, /* R21084 - VSS_XTS5_1 */
{ 21085, 0xE180 }, /* R21085 - VSS_XTS5_0 */
{ 21086, 0x0001 }, /* R21086 - VSS_XTS6_1 */
{ 21087, 0x1F40 }, /* R21087 - VSS_XTS6_0 */
{ 21088, 0x00F8 }, /* R21088 - VSS_XTS7_1 */
{ 21089, 0xB000 }, /* R21089 - VSS_XTS7_0 */
{ 21090, 0x00FB }, /* R21090 - VSS_XTS8_1 */
{ 21091, 0xCBC0 }, /* R21091 - VSS_XTS8_0 */
{ 21092, 0x0004 }, /* R21092 - VSS_XTS9_1 */
{ 21093, 0xF380 }, /* R21093 - VSS_XTS9_0 */
{ 21094, 0x0007 }, /* R21094 - VSS_XTS10_1 */
{ 21095, 0xDF40 }, /* R21095 - VSS_XTS10_0 */
{ 21096, 0x00FF }, /* R21096 - VSS_XTS11_1 */
{ 21097, 0x0700 }, /* R21097 - VSS_XTS11_0 */
{ 21098, 0x00EF }, /* R21098 - VSS_XTS12_1 */
{ 21099, 0xD700 }, /* R21099 - VSS_XTS12_0 */
{ 21100, 0x00FB }, /* R21100 - VSS_XTS13_1 */
{ 21101, 0xAF40 }, /* R21101 - VSS_XTS13_0 */
{ 21102, 0x0010 }, /* R21102 - VSS_XTS14_1 */
{ 21103, 0x8A80 }, /* R21103 - VSS_XTS14_0 */
{ 21104, 0x0011 }, /* R21104 - VSS_XTS15_1 */
{ 21105, 0x07C0 }, /* R21105 - VSS_XTS15_0 */
{ 21106, 0x00E0 }, /* R21106 - VSS_XTS16_1 */
{ 21107, 0x0800 }, /* R21107 - VSS_XTS16_0 */
{ 21108, 0x00D2 }, /* R21108 - VSS_XTS17_1 */
{ 21109, 0x7600 }, /* R21109 - VSS_XTS17_0 */
{ 21110, 0x0020 }, /* R21110 - VSS_XTS18_1 */
{ 21111, 0xCF40 }, /* R21111 - VSS_XTS18_0 */
{ 21112, 0x0030 }, /* R21112 - VSS_XTS19_1 */
{ 21113, 0x2340 }, /* R21113 - VSS_XTS19_0 */
{ 21114, 0x00FD }, /* R21114 - VSS_XTS20_1 */
{ 21115, 0x69C0 }, /* R21115 - VSS_XTS20_0 */
{ 21116, 0x0028 }, /* R21116 - VSS_XTS21_1 */
{ 21117, 0x3500 }, /* R21117 - VSS_XTS21_0 */
{ 21118, 0x0006 }, /* R21118 - VSS_XTS22_1 */
{ 21119, 0x3300 }, /* R21119 - VSS_XTS22_0 */
{ 21120, 0x00D9 }, /* R21120 - VSS_XTS23_1 */
{ 21121, 0xF6C0 }, /* R21121 - VSS_XTS23_0 */
{ 21122, 0x00F3 }, /* R21122 - VSS_XTS24_1 */
{ 21123, 0x3340 }, /* R21123 - VSS_XTS24_0 */
{ 21124, 0x000F }, /* R21124 - VSS_XTS25_1 */
{ 21125, 0x4200 }, /* R21125 - VSS_XTS25_0 */
{ 21126, 0x0004 }, /* R21126 - VSS_XTS26_1 */
{ 21127, 0x0C80 }, /* R21127 - VSS_XTS26_0 */
{ 21128, 0x00FB }, /* R21128 - VSS_XTS27_1 */
{ 21129, 0x3F80 }, /* R21129 - VSS_XTS27_0 */
{ 21130, 0x00F7 }, /* R21130 - VSS_XTS28_1 */
{ 21131, 0x57C0 }, /* R21131 - VSS_XTS28_0 */
{ 21132, 0x0003 }, /* R21132 - VSS_XTS29_1 */
{ 21133, 0x5400 }, /* R21133 - VSS_XTS29_0 */
{ 21134, 0x0000 }, /* R21134 - VSS_XTS30_1 */
{ 21135, 0xC6C0 }, /* R21135 - VSS_XTS30_0 */
{ 21136, 0x0003 }, /* R21136 - VSS_XTS31_1 */
{ 21137, 0x12C0 }, /* R21137 - VSS_XTS31_0 */
{ 21138, 0x00FD }, /* R21138 - VSS_XTS32_1 */
{ 21139, 0x8580 }, /* R21139 - VSS_XTS32_0 */
};
static bool wm8962_volatile_register(struct device *dev, unsigned int reg)
{
switch (reg) {
case WM8962_CLOCKING1:
case WM8962_CLOCKING2:
case WM8962_SOFTWARE_RESET:
case WM8962_ALC2:
case WM8962_THERMAL_SHUTDOWN_STATUS:
case WM8962_ADDITIONAL_CONTROL_4:
case WM8962_DC_SERVO_6:
case WM8962_INTERRUPT_STATUS_1:
case WM8962_INTERRUPT_STATUS_2:
case WM8962_DSP2_EXECCONTROL:
return true;
default:
return false;
}
}
static bool wm8962_readable_register(struct device *dev, unsigned int reg)
{
switch (reg) {
case WM8962_LEFT_INPUT_VOLUME:
case WM8962_RIGHT_INPUT_VOLUME:
case WM8962_HPOUTL_VOLUME:
case WM8962_HPOUTR_VOLUME:
case WM8962_CLOCKING1:
case WM8962_ADC_DAC_CONTROL_1:
case WM8962_ADC_DAC_CONTROL_2:
case WM8962_AUDIO_INTERFACE_0:
case WM8962_CLOCKING2:
case WM8962_AUDIO_INTERFACE_1:
case WM8962_LEFT_DAC_VOLUME:
case WM8962_RIGHT_DAC_VOLUME:
case WM8962_AUDIO_INTERFACE_2:
case WM8962_SOFTWARE_RESET:
case WM8962_ALC1:
case WM8962_ALC2:
case WM8962_ALC3:
case WM8962_NOISE_GATE:
case WM8962_LEFT_ADC_VOLUME:
case WM8962_RIGHT_ADC_VOLUME:
case WM8962_ADDITIONAL_CONTROL_1:
case WM8962_ADDITIONAL_CONTROL_2:
case WM8962_PWR_MGMT_1:
case WM8962_PWR_MGMT_2:
case WM8962_ADDITIONAL_CONTROL_3:
case WM8962_ANTI_POP:
case WM8962_CLOCKING_3:
case WM8962_INPUT_MIXER_CONTROL_1:
case WM8962_LEFT_INPUT_MIXER_VOLUME:
case WM8962_RIGHT_INPUT_MIXER_VOLUME:
case WM8962_INPUT_MIXER_CONTROL_2:
case WM8962_INPUT_BIAS_CONTROL:
case WM8962_LEFT_INPUT_PGA_CONTROL:
case WM8962_RIGHT_INPUT_PGA_CONTROL:
case WM8962_SPKOUTL_VOLUME:
case WM8962_SPKOUTR_VOLUME:
case WM8962_THERMAL_SHUTDOWN_STATUS:
case WM8962_ADDITIONAL_CONTROL_4:
case WM8962_CLASS_D_CONTROL_1:
case WM8962_CLASS_D_CONTROL_2:
case WM8962_CLOCKING_4:
case WM8962_DAC_DSP_MIXING_1:
case WM8962_DAC_DSP_MIXING_2:
case WM8962_DC_SERVO_0:
case WM8962_DC_SERVO_1:
case WM8962_DC_SERVO_4:
case WM8962_DC_SERVO_6:
case WM8962_ANALOGUE_PGA_BIAS:
case WM8962_ANALOGUE_HP_0:
case WM8962_ANALOGUE_HP_2:
case WM8962_CHARGE_PUMP_1:
case WM8962_CHARGE_PUMP_B:
case WM8962_WRITE_SEQUENCER_CONTROL_1:
case WM8962_WRITE_SEQUENCER_CONTROL_2:
case WM8962_WRITE_SEQUENCER_CONTROL_3:
case WM8962_CONTROL_INTERFACE:
case WM8962_MIXER_ENABLES:
case WM8962_HEADPHONE_MIXER_1:
case WM8962_HEADPHONE_MIXER_2:
case WM8962_HEADPHONE_MIXER_3:
case WM8962_HEADPHONE_MIXER_4:
case WM8962_SPEAKER_MIXER_1:
case WM8962_SPEAKER_MIXER_2:
case WM8962_SPEAKER_MIXER_3:
case WM8962_SPEAKER_MIXER_4:
case WM8962_SPEAKER_MIXER_5:
case WM8962_BEEP_GENERATOR_1:
case WM8962_OSCILLATOR_TRIM_3:
case WM8962_OSCILLATOR_TRIM_4:
case WM8962_OSCILLATOR_TRIM_7:
case WM8962_ANALOGUE_CLOCKING1:
case WM8962_ANALOGUE_CLOCKING2:
case WM8962_ANALOGUE_CLOCKING3:
case WM8962_PLL_SOFTWARE_RESET:
case WM8962_PLL2:
case WM8962_PLL_4:
case WM8962_PLL_9:
case WM8962_PLL_10:
case WM8962_PLL_11:
case WM8962_PLL_12:
case WM8962_PLL_13:
case WM8962_PLL_14:
case WM8962_PLL_15:
case WM8962_PLL_16:
case WM8962_FLL_CONTROL_1:
case WM8962_FLL_CONTROL_2:
case WM8962_FLL_CONTROL_3:
case WM8962_FLL_CONTROL_5:
case WM8962_FLL_CONTROL_6:
case WM8962_FLL_CONTROL_7:
case WM8962_FLL_CONTROL_8:
case WM8962_GENERAL_TEST_1:
case WM8962_DF1:
case WM8962_DF2:
case WM8962_DF3:
case WM8962_DF4:
case WM8962_DF5:
case WM8962_DF6:
case WM8962_DF7:
case WM8962_LHPF1:
case WM8962_LHPF2:
case WM8962_THREED1:
case WM8962_THREED2:
case WM8962_THREED3:
case WM8962_THREED4:
case WM8962_DRC_1:
case WM8962_DRC_2:
case WM8962_DRC_3:
case WM8962_DRC_4:
case WM8962_DRC_5:
case WM8962_TLOOPBACK:
case WM8962_EQ1:
case WM8962_EQ2:
case WM8962_EQ3:
case WM8962_EQ4:
case WM8962_EQ5:
case WM8962_EQ6:
case WM8962_EQ7:
case WM8962_EQ8:
case WM8962_EQ9:
case WM8962_EQ10:
case WM8962_EQ11:
case WM8962_EQ12:
case WM8962_EQ13:
case WM8962_EQ14:
case WM8962_EQ15:
case WM8962_EQ16:
case WM8962_EQ17:
case WM8962_EQ18:
case WM8962_EQ19:
case WM8962_EQ20:
case WM8962_EQ21:
case WM8962_EQ22:
case WM8962_EQ23:
case WM8962_EQ24:
case WM8962_EQ25:
case WM8962_EQ26:
case WM8962_EQ27:
case WM8962_EQ28:
case WM8962_EQ29:
case WM8962_EQ30:
case WM8962_EQ31:
case WM8962_EQ32:
case WM8962_EQ33:
case WM8962_EQ34:
case WM8962_EQ35:
case WM8962_EQ36:
case WM8962_EQ37:
case WM8962_EQ38:
case WM8962_EQ39:
case WM8962_EQ40:
case WM8962_EQ41:
case WM8962_GPIO_BASE:
case WM8962_GPIO_2:
case WM8962_GPIO_3:
case WM8962_GPIO_5:
case WM8962_GPIO_6:
case WM8962_INTERRUPT_STATUS_1:
case WM8962_INTERRUPT_STATUS_2:
case WM8962_INTERRUPT_STATUS_1_MASK:
case WM8962_INTERRUPT_STATUS_2_MASK:
case WM8962_INTERRUPT_CONTROL:
case WM8962_IRQ_DEBOUNCE:
case WM8962_MICINT_SOURCE_POL:
case WM8962_DSP2_POWER_MANAGEMENT:
case WM8962_DSP2_EXECCONTROL:
case WM8962_DSP2_INSTRUCTION_RAM_0:
case WM8962_DSP2_ADDRESS_RAM_2:
case WM8962_DSP2_ADDRESS_RAM_1:
case WM8962_DSP2_ADDRESS_RAM_0:
case WM8962_DSP2_DATA1_RAM_1:
case WM8962_DSP2_DATA1_RAM_0:
case WM8962_DSP2_DATA2_RAM_1:
case WM8962_DSP2_DATA2_RAM_0:
case WM8962_DSP2_DATA3_RAM_1:
case WM8962_DSP2_DATA3_RAM_0:
case WM8962_DSP2_COEFF_RAM_0:
case WM8962_RETUNEADC_SHARED_COEFF_1:
case WM8962_RETUNEADC_SHARED_COEFF_0:
case WM8962_RETUNEDAC_SHARED_COEFF_1:
case WM8962_RETUNEDAC_SHARED_COEFF_0:
case WM8962_SOUNDSTAGE_ENABLES_1:
case WM8962_SOUNDSTAGE_ENABLES_0:
case WM8962_HDBASS_AI_1:
case WM8962_HDBASS_AI_0:
case WM8962_HDBASS_AR_1:
case WM8962_HDBASS_AR_0:
case WM8962_HDBASS_B_1:
case WM8962_HDBASS_B_0:
case WM8962_HDBASS_K_1:
case WM8962_HDBASS_K_0:
case WM8962_HDBASS_N1_1:
case WM8962_HDBASS_N1_0:
case WM8962_HDBASS_N2_1:
case WM8962_HDBASS_N2_0:
case WM8962_HDBASS_N3_1:
case WM8962_HDBASS_N3_0:
case WM8962_HDBASS_N4_1:
case WM8962_HDBASS_N4_0:
case WM8962_HDBASS_N5_1:
case WM8962_HDBASS_N5_0:
case WM8962_HDBASS_X1_1:
case WM8962_HDBASS_X1_0:
case WM8962_HDBASS_X2_1:
case WM8962_HDBASS_X2_0:
case WM8962_HDBASS_X3_1:
case WM8962_HDBASS_X3_0:
case WM8962_HDBASS_ATK_1:
case WM8962_HDBASS_ATK_0:
case WM8962_HDBASS_DCY_1:
case WM8962_HDBASS_DCY_0:
case WM8962_HDBASS_PG_1:
case WM8962_HDBASS_PG_0:
case WM8962_HPF_C_1:
case WM8962_HPF_C_0:
case WM8962_ADCL_RETUNE_C1_1:
case WM8962_ADCL_RETUNE_C1_0:
case WM8962_ADCL_RETUNE_C2_1:
case WM8962_ADCL_RETUNE_C2_0:
case WM8962_ADCL_RETUNE_C3_1:
case WM8962_ADCL_RETUNE_C3_0:
case WM8962_ADCL_RETUNE_C4_1:
case WM8962_ADCL_RETUNE_C4_0:
case WM8962_ADCL_RETUNE_C5_1:
case WM8962_ADCL_RETUNE_C5_0:
case WM8962_ADCL_RETUNE_C6_1:
case WM8962_ADCL_RETUNE_C6_0:
case WM8962_ADCL_RETUNE_C7_1:
case WM8962_ADCL_RETUNE_C7_0:
case WM8962_ADCL_RETUNE_C8_1:
case WM8962_ADCL_RETUNE_C8_0:
case WM8962_ADCL_RETUNE_C9_1:
case WM8962_ADCL_RETUNE_C9_0:
case WM8962_ADCL_RETUNE_C10_1:
case WM8962_ADCL_RETUNE_C10_0:
case WM8962_ADCL_RETUNE_C11_1:
case WM8962_ADCL_RETUNE_C11_0:
case WM8962_ADCL_RETUNE_C12_1:
case WM8962_ADCL_RETUNE_C12_0:
case WM8962_ADCL_RETUNE_C13_1:
case WM8962_ADCL_RETUNE_C13_0:
case WM8962_ADCL_RETUNE_C14_1:
case WM8962_ADCL_RETUNE_C14_0:
case WM8962_ADCL_RETUNE_C15_1:
case WM8962_ADCL_RETUNE_C15_0:
case WM8962_ADCL_RETUNE_C16_1:
case WM8962_ADCL_RETUNE_C16_0:
case WM8962_ADCL_RETUNE_C17_1:
case WM8962_ADCL_RETUNE_C17_0:
case WM8962_ADCL_RETUNE_C18_1:
case WM8962_ADCL_RETUNE_C18_0:
case WM8962_ADCL_RETUNE_C19_1:
case WM8962_ADCL_RETUNE_C19_0:
case WM8962_ADCL_RETUNE_C20_1:
case WM8962_ADCL_RETUNE_C20_0:
case WM8962_ADCL_RETUNE_C21_1:
case WM8962_ADCL_RETUNE_C21_0:
case WM8962_ADCL_RETUNE_C22_1:
case WM8962_ADCL_RETUNE_C22_0:
case WM8962_ADCL_RETUNE_C23_1:
case WM8962_ADCL_RETUNE_C23_0:
case WM8962_ADCL_RETUNE_C24_1:
case WM8962_ADCL_RETUNE_C24_0:
case WM8962_ADCL_RETUNE_C25_1:
case WM8962_ADCL_RETUNE_C25_0:
case WM8962_ADCL_RETUNE_C26_1:
case WM8962_ADCL_RETUNE_C26_0:
case WM8962_ADCL_RETUNE_C27_1:
case WM8962_ADCL_RETUNE_C27_0:
case WM8962_ADCL_RETUNE_C28_1:
case WM8962_ADCL_RETUNE_C28_0:
case WM8962_ADCL_RETUNE_C29_1:
case WM8962_ADCL_RETUNE_C29_0:
case WM8962_ADCL_RETUNE_C30_1:
case WM8962_ADCL_RETUNE_C30_0:
case WM8962_ADCL_RETUNE_C31_1:
case WM8962_ADCL_RETUNE_C31_0:
case WM8962_ADCL_RETUNE_C32_1:
case WM8962_ADCL_RETUNE_C32_0:
case WM8962_RETUNEADC_PG2_1:
case WM8962_RETUNEADC_PG2_0:
case WM8962_RETUNEADC_PG_1:
case WM8962_RETUNEADC_PG_0:
case WM8962_ADCR_RETUNE_C1_1:
case WM8962_ADCR_RETUNE_C1_0:
case WM8962_ADCR_RETUNE_C2_1:
case WM8962_ADCR_RETUNE_C2_0:
case WM8962_ADCR_RETUNE_C3_1:
case WM8962_ADCR_RETUNE_C3_0:
case WM8962_ADCR_RETUNE_C4_1:
case WM8962_ADCR_RETUNE_C4_0:
case WM8962_ADCR_RETUNE_C5_1:
case WM8962_ADCR_RETUNE_C5_0:
case WM8962_ADCR_RETUNE_C6_1:
case WM8962_ADCR_RETUNE_C6_0:
case WM8962_ADCR_RETUNE_C7_1:
case WM8962_ADCR_RETUNE_C7_0:
case WM8962_ADCR_RETUNE_C8_1:
case WM8962_ADCR_RETUNE_C8_0:
case WM8962_ADCR_RETUNE_C9_1:
case WM8962_ADCR_RETUNE_C9_0:
case WM8962_ADCR_RETUNE_C10_1:
case WM8962_ADCR_RETUNE_C10_0:
case WM8962_ADCR_RETUNE_C11_1:
case WM8962_ADCR_RETUNE_C11_0:
case WM8962_ADCR_RETUNE_C12_1:
case WM8962_ADCR_RETUNE_C12_0:
case WM8962_ADCR_RETUNE_C13_1:
case WM8962_ADCR_RETUNE_C13_0:
case WM8962_ADCR_RETUNE_C14_1:
case WM8962_ADCR_RETUNE_C14_0:
case WM8962_ADCR_RETUNE_C15_1:
case WM8962_ADCR_RETUNE_C15_0:
case WM8962_ADCR_RETUNE_C16_1:
case WM8962_ADCR_RETUNE_C16_0:
case WM8962_ADCR_RETUNE_C17_1:
case WM8962_ADCR_RETUNE_C17_0:
case WM8962_ADCR_RETUNE_C18_1:
case WM8962_ADCR_RETUNE_C18_0:
case WM8962_ADCR_RETUNE_C19_1:
case WM8962_ADCR_RETUNE_C19_0:
case WM8962_ADCR_RETUNE_C20_1:
case WM8962_ADCR_RETUNE_C20_0:
case WM8962_ADCR_RETUNE_C21_1:
case WM8962_ADCR_RETUNE_C21_0:
case WM8962_ADCR_RETUNE_C22_1:
case WM8962_ADCR_RETUNE_C22_0:
case WM8962_ADCR_RETUNE_C23_1:
case WM8962_ADCR_RETUNE_C23_0:
case WM8962_ADCR_RETUNE_C24_1:
case WM8962_ADCR_RETUNE_C24_0:
case WM8962_ADCR_RETUNE_C25_1:
case WM8962_ADCR_RETUNE_C25_0:
case WM8962_ADCR_RETUNE_C26_1:
case WM8962_ADCR_RETUNE_C26_0:
case WM8962_ADCR_RETUNE_C27_1:
case WM8962_ADCR_RETUNE_C27_0:
case WM8962_ADCR_RETUNE_C28_1:
case WM8962_ADCR_RETUNE_C28_0:
case WM8962_ADCR_RETUNE_C29_1:
case WM8962_ADCR_RETUNE_C29_0:
case WM8962_ADCR_RETUNE_C30_1:
case WM8962_ADCR_RETUNE_C30_0:
case WM8962_ADCR_RETUNE_C31_1:
case WM8962_ADCR_RETUNE_C31_0:
case WM8962_ADCR_RETUNE_C32_1:
case WM8962_ADCR_RETUNE_C32_0:
case WM8962_DACL_RETUNE_C1_1:
case WM8962_DACL_RETUNE_C1_0:
case WM8962_DACL_RETUNE_C2_1:
case WM8962_DACL_RETUNE_C2_0:
case WM8962_DACL_RETUNE_C3_1:
case WM8962_DACL_RETUNE_C3_0:
case WM8962_DACL_RETUNE_C4_1:
case WM8962_DACL_RETUNE_C4_0:
case WM8962_DACL_RETUNE_C5_1:
case WM8962_DACL_RETUNE_C5_0:
case WM8962_DACL_RETUNE_C6_1:
case WM8962_DACL_RETUNE_C6_0:
case WM8962_DACL_RETUNE_C7_1:
case WM8962_DACL_RETUNE_C7_0:
case WM8962_DACL_RETUNE_C8_1:
case WM8962_DACL_RETUNE_C8_0:
case WM8962_DACL_RETUNE_C9_1:
case WM8962_DACL_RETUNE_C9_0:
case WM8962_DACL_RETUNE_C10_1:
case WM8962_DACL_RETUNE_C10_0:
case WM8962_DACL_RETUNE_C11_1:
case WM8962_DACL_RETUNE_C11_0:
case WM8962_DACL_RETUNE_C12_1:
case WM8962_DACL_RETUNE_C12_0:
case WM8962_DACL_RETUNE_C13_1:
case WM8962_DACL_RETUNE_C13_0:
case WM8962_DACL_RETUNE_C14_1:
case WM8962_DACL_RETUNE_C14_0:
case WM8962_DACL_RETUNE_C15_1:
case WM8962_DACL_RETUNE_C15_0:
case WM8962_DACL_RETUNE_C16_1:
case WM8962_DACL_RETUNE_C16_0:
case WM8962_DACL_RETUNE_C17_1:
case WM8962_DACL_RETUNE_C17_0:
case WM8962_DACL_RETUNE_C18_1:
case WM8962_DACL_RETUNE_C18_0:
case WM8962_DACL_RETUNE_C19_1:
case WM8962_DACL_RETUNE_C19_0:
case WM8962_DACL_RETUNE_C20_1:
case WM8962_DACL_RETUNE_C20_0:
case WM8962_DACL_RETUNE_C21_1:
case WM8962_DACL_RETUNE_C21_0:
case WM8962_DACL_RETUNE_C22_1:
case WM8962_DACL_RETUNE_C22_0:
case WM8962_DACL_RETUNE_C23_1:
case WM8962_DACL_RETUNE_C23_0:
case WM8962_DACL_RETUNE_C24_1:
case WM8962_DACL_RETUNE_C24_0:
case WM8962_DACL_RETUNE_C25_1:
case WM8962_DACL_RETUNE_C25_0:
case WM8962_DACL_RETUNE_C26_1:
case WM8962_DACL_RETUNE_C26_0:
case WM8962_DACL_RETUNE_C27_1:
case WM8962_DACL_RETUNE_C27_0:
case WM8962_DACL_RETUNE_C28_1:
case WM8962_DACL_RETUNE_C28_0:
case WM8962_DACL_RETUNE_C29_1:
case WM8962_DACL_RETUNE_C29_0:
case WM8962_DACL_RETUNE_C30_1:
case WM8962_DACL_RETUNE_C30_0:
case WM8962_DACL_RETUNE_C31_1:
case WM8962_DACL_RETUNE_C31_0:
case WM8962_DACL_RETUNE_C32_1:
case WM8962_DACL_RETUNE_C32_0:
case WM8962_RETUNEDAC_PG2_1:
case WM8962_RETUNEDAC_PG2_0:
case WM8962_RETUNEDAC_PG_1:
case WM8962_RETUNEDAC_PG_0:
case WM8962_DACR_RETUNE_C1_1:
case WM8962_DACR_RETUNE_C1_0:
case WM8962_DACR_RETUNE_C2_1:
case WM8962_DACR_RETUNE_C2_0:
case WM8962_DACR_RETUNE_C3_1:
case WM8962_DACR_RETUNE_C3_0:
case WM8962_DACR_RETUNE_C4_1:
case WM8962_DACR_RETUNE_C4_0:
case WM8962_DACR_RETUNE_C5_1:
case WM8962_DACR_RETUNE_C5_0:
case WM8962_DACR_RETUNE_C6_1:
case WM8962_DACR_RETUNE_C6_0:
case WM8962_DACR_RETUNE_C7_1:
case WM8962_DACR_RETUNE_C7_0:
case WM8962_DACR_RETUNE_C8_1:
case WM8962_DACR_RETUNE_C8_0:
case WM8962_DACR_RETUNE_C9_1:
case WM8962_DACR_RETUNE_C9_0:
case WM8962_DACR_RETUNE_C10_1:
case WM8962_DACR_RETUNE_C10_0:
case WM8962_DACR_RETUNE_C11_1:
case WM8962_DACR_RETUNE_C11_0:
case WM8962_DACR_RETUNE_C12_1:
case WM8962_DACR_RETUNE_C12_0:
case WM8962_DACR_RETUNE_C13_1:
case WM8962_DACR_RETUNE_C13_0:
case WM8962_DACR_RETUNE_C14_1:
case WM8962_DACR_RETUNE_C14_0:
case WM8962_DACR_RETUNE_C15_1:
case WM8962_DACR_RETUNE_C15_0:
case WM8962_DACR_RETUNE_C16_1:
case WM8962_DACR_RETUNE_C16_0:
case WM8962_DACR_RETUNE_C17_1:
case WM8962_DACR_RETUNE_C17_0:
case WM8962_DACR_RETUNE_C18_1:
case WM8962_DACR_RETUNE_C18_0:
case WM8962_DACR_RETUNE_C19_1:
case WM8962_DACR_RETUNE_C19_0:
case WM8962_DACR_RETUNE_C20_1:
case WM8962_DACR_RETUNE_C20_0:
case WM8962_DACR_RETUNE_C21_1:
case WM8962_DACR_RETUNE_C21_0:
case WM8962_DACR_RETUNE_C22_1:
case WM8962_DACR_RETUNE_C22_0:
case WM8962_DACR_RETUNE_C23_1:
case WM8962_DACR_RETUNE_C23_0:
case WM8962_DACR_RETUNE_C24_1:
case WM8962_DACR_RETUNE_C24_0:
case WM8962_DACR_RETUNE_C25_1:
case WM8962_DACR_RETUNE_C25_0:
case WM8962_DACR_RETUNE_C26_1:
case WM8962_DACR_RETUNE_C26_0:
case WM8962_DACR_RETUNE_C27_1:
case WM8962_DACR_RETUNE_C27_0:
case WM8962_DACR_RETUNE_C28_1:
case WM8962_DACR_RETUNE_C28_0:
case WM8962_DACR_RETUNE_C29_1:
case WM8962_DACR_RETUNE_C29_0:
case WM8962_DACR_RETUNE_C30_1:
case WM8962_DACR_RETUNE_C30_0:
case WM8962_DACR_RETUNE_C31_1:
case WM8962_DACR_RETUNE_C31_0:
case WM8962_DACR_RETUNE_C32_1:
case WM8962_DACR_RETUNE_C32_0:
case WM8962_VSS_XHD2_1:
case WM8962_VSS_XHD2_0:
case WM8962_VSS_XHD3_1:
case WM8962_VSS_XHD3_0:
case WM8962_VSS_XHN1_1:
case WM8962_VSS_XHN1_0:
case WM8962_VSS_XHN2_1:
case WM8962_VSS_XHN2_0:
case WM8962_VSS_XHN3_1:
case WM8962_VSS_XHN3_0:
case WM8962_VSS_XLA_1:
case WM8962_VSS_XLA_0:
case WM8962_VSS_XLB_1:
case WM8962_VSS_XLB_0:
case WM8962_VSS_XLG_1:
case WM8962_VSS_XLG_0:
case WM8962_VSS_PG2_1:
case WM8962_VSS_PG2_0:
case WM8962_VSS_PG_1:
case WM8962_VSS_PG_0:
case WM8962_VSS_XTD1_1:
case WM8962_VSS_XTD1_0:
case WM8962_VSS_XTD2_1:
case WM8962_VSS_XTD2_0:
case WM8962_VSS_XTD3_1:
case WM8962_VSS_XTD3_0:
case WM8962_VSS_XTD4_1:
case WM8962_VSS_XTD4_0:
case WM8962_VSS_XTD5_1:
case WM8962_VSS_XTD5_0:
case WM8962_VSS_XTD6_1:
case WM8962_VSS_XTD6_0:
case WM8962_VSS_XTD7_1:
case WM8962_VSS_XTD7_0:
case WM8962_VSS_XTD8_1:
case WM8962_VSS_XTD8_0:
case WM8962_VSS_XTD9_1:
case WM8962_VSS_XTD9_0:
case WM8962_VSS_XTD10_1:
case WM8962_VSS_XTD10_0:
case WM8962_VSS_XTD11_1:
case WM8962_VSS_XTD11_0:
case WM8962_VSS_XTD12_1:
case WM8962_VSS_XTD12_0:
case WM8962_VSS_XTD13_1:
case WM8962_VSS_XTD13_0:
case WM8962_VSS_XTD14_1:
case WM8962_VSS_XTD14_0:
case WM8962_VSS_XTD15_1:
case WM8962_VSS_XTD15_0:
case WM8962_VSS_XTD16_1:
case WM8962_VSS_XTD16_0:
case WM8962_VSS_XTD17_1:
case WM8962_VSS_XTD17_0:
case WM8962_VSS_XTD18_1:
case WM8962_VSS_XTD18_0:
case WM8962_VSS_XTD19_1:
case WM8962_VSS_XTD19_0:
case WM8962_VSS_XTD20_1:
case WM8962_VSS_XTD20_0:
case WM8962_VSS_XTD21_1:
case WM8962_VSS_XTD21_0:
case WM8962_VSS_XTD22_1:
case WM8962_VSS_XTD22_0:
case WM8962_VSS_XTD23_1:
case WM8962_VSS_XTD23_0:
case WM8962_VSS_XTD24_1:
case WM8962_VSS_XTD24_0:
case WM8962_VSS_XTD25_1:
case WM8962_VSS_XTD25_0:
case WM8962_VSS_XTD26_1:
case WM8962_VSS_XTD26_0:
case WM8962_VSS_XTD27_1:
case WM8962_VSS_XTD27_0:
case WM8962_VSS_XTD28_1:
case WM8962_VSS_XTD28_0:
case WM8962_VSS_XTD29_1:
case WM8962_VSS_XTD29_0:
case WM8962_VSS_XTD30_1:
case WM8962_VSS_XTD30_0:
case WM8962_VSS_XTD31_1:
case WM8962_VSS_XTD31_0:
case WM8962_VSS_XTD32_1:
case WM8962_VSS_XTD32_0:
case WM8962_VSS_XTS1_1:
case WM8962_VSS_XTS1_0:
case WM8962_VSS_XTS2_1:
case WM8962_VSS_XTS2_0:
case WM8962_VSS_XTS3_1:
case WM8962_VSS_XTS3_0:
case WM8962_VSS_XTS4_1:
case WM8962_VSS_XTS4_0:
case WM8962_VSS_XTS5_1:
case WM8962_VSS_XTS5_0:
case WM8962_VSS_XTS6_1:
case WM8962_VSS_XTS6_0:
case WM8962_VSS_XTS7_1:
case WM8962_VSS_XTS7_0:
case WM8962_VSS_XTS8_1:
case WM8962_VSS_XTS8_0:
case WM8962_VSS_XTS9_1:
case WM8962_VSS_XTS9_0:
case WM8962_VSS_XTS10_1:
case WM8962_VSS_XTS10_0:
case WM8962_VSS_XTS11_1:
case WM8962_VSS_XTS11_0:
case WM8962_VSS_XTS12_1:
case WM8962_VSS_XTS12_0:
case WM8962_VSS_XTS13_1:
case WM8962_VSS_XTS13_0:
case WM8962_VSS_XTS14_1:
case WM8962_VSS_XTS14_0:
case WM8962_VSS_XTS15_1:
case WM8962_VSS_XTS15_0:
case WM8962_VSS_XTS16_1:
case WM8962_VSS_XTS16_0:
case WM8962_VSS_XTS17_1:
case WM8962_VSS_XTS17_0:
case WM8962_VSS_XTS18_1:
case WM8962_VSS_XTS18_0:
case WM8962_VSS_XTS19_1:
case WM8962_VSS_XTS19_0:
case WM8962_VSS_XTS20_1:
case WM8962_VSS_XTS20_0:
case WM8962_VSS_XTS21_1:
case WM8962_VSS_XTS21_0:
case WM8962_VSS_XTS22_1:
case WM8962_VSS_XTS22_0:
case WM8962_VSS_XTS23_1:
case WM8962_VSS_XTS23_0:
case WM8962_VSS_XTS24_1:
case WM8962_VSS_XTS24_0:
case WM8962_VSS_XTS25_1:
case WM8962_VSS_XTS25_0:
case WM8962_VSS_XTS26_1:
case WM8962_VSS_XTS26_0:
case WM8962_VSS_XTS27_1:
case WM8962_VSS_XTS27_0:
case WM8962_VSS_XTS28_1:
case WM8962_VSS_XTS28_0:
case WM8962_VSS_XTS29_1:
case WM8962_VSS_XTS29_0:
case WM8962_VSS_XTS30_1:
case WM8962_VSS_XTS30_0:
case WM8962_VSS_XTS31_1:
case WM8962_VSS_XTS31_0:
case WM8962_VSS_XTS32_1:
case WM8962_VSS_XTS32_0:
return true;
default:
return false;
}
}
static int wm8962_reset(struct wm8962_priv *wm8962)
{
int ret;
ret = regmap_write(wm8962->regmap, WM8962_SOFTWARE_RESET, 0x6243);
if (ret != 0)
return ret;
return regmap_write(wm8962->regmap, WM8962_PLL_SOFTWARE_RESET, 0);
}
static const DECLARE_TLV_DB_SCALE(inpga_tlv, -2325, 75, 0);
static const DECLARE_TLV_DB_SCALE(mixin_tlv, -1500, 300, 0);
static const unsigned int mixinpga_tlv[] = {
TLV_DB_RANGE_HEAD(5),
0, 1, TLV_DB_SCALE_ITEM(0, 600, 0),
2, 2, TLV_DB_SCALE_ITEM(1300, 1300, 0),
3, 4, TLV_DB_SCALE_ITEM(1800, 200, 0),
5, 5, TLV_DB_SCALE_ITEM(2400, 0, 0),
6, 7, TLV_DB_SCALE_ITEM(2700, 300, 0),
};
static const DECLARE_TLV_DB_SCALE(beep_tlv, -9600, 600, 1);
static const DECLARE_TLV_DB_SCALE(digital_tlv, -7200, 75, 1);
static const DECLARE_TLV_DB_SCALE(st_tlv, -3600, 300, 0);
static const DECLARE_TLV_DB_SCALE(inmix_tlv, -600, 600, 0);
static const DECLARE_TLV_DB_SCALE(bypass_tlv, -1500, 300, 0);
static const DECLARE_TLV_DB_SCALE(out_tlv, -12100, 100, 1);
static const DECLARE_TLV_DB_SCALE(hp_tlv, -700, 100, 0);
static const unsigned int classd_tlv[] = {
TLV_DB_RANGE_HEAD(2),
0, 6, TLV_DB_SCALE_ITEM(0, 150, 0),
7, 7, TLV_DB_SCALE_ITEM(1200, 0, 0),
};
static const DECLARE_TLV_DB_SCALE(eq_tlv, -1200, 100, 0);
static int wm8962_dsp2_write_config(struct snd_soc_codec *codec)
{
struct wm8962_priv *wm8962 = snd_soc_codec_get_drvdata(codec);
return regcache_sync_region(wm8962->regmap,
WM8962_HDBASS_AI_1, WM8962_MAX_REGISTER);
}
static int wm8962_dsp2_set_enable(struct snd_soc_codec *codec, u16 val)
{
u16 adcl = snd_soc_read(codec, WM8962_LEFT_ADC_VOLUME);
u16 adcr = snd_soc_read(codec, WM8962_RIGHT_ADC_VOLUME);
u16 dac = snd_soc_read(codec, WM8962_ADC_DAC_CONTROL_1);
/* Mute the ADCs and DACs */
snd_soc_write(codec, WM8962_LEFT_ADC_VOLUME, 0);
snd_soc_write(codec, WM8962_RIGHT_ADC_VOLUME, WM8962_ADC_VU);
snd_soc_update_bits(codec, WM8962_ADC_DAC_CONTROL_1,
WM8962_DAC_MUTE, WM8962_DAC_MUTE);
snd_soc_write(codec, WM8962_SOUNDSTAGE_ENABLES_0, val);
/* Restore the ADCs and DACs */
snd_soc_write(codec, WM8962_LEFT_ADC_VOLUME, adcl);
snd_soc_write(codec, WM8962_RIGHT_ADC_VOLUME, adcr);
snd_soc_update_bits(codec, WM8962_ADC_DAC_CONTROL_1,
WM8962_DAC_MUTE, dac);
return 0;
}
static int wm8962_dsp2_start(struct snd_soc_codec *codec)
{
struct wm8962_priv *wm8962 = snd_soc_codec_get_drvdata(codec);
wm8962_dsp2_write_config(codec);
snd_soc_write(codec, WM8962_DSP2_EXECCONTROL, WM8962_DSP2_RUNR);
wm8962_dsp2_set_enable(codec, wm8962->dsp2_ena);
return 0;
}
static int wm8962_dsp2_stop(struct snd_soc_codec *codec)
{
wm8962_dsp2_set_enable(codec, 0);
snd_soc_write(codec, WM8962_DSP2_EXECCONTROL, WM8962_DSP2_STOP);
return 0;
}
#define WM8962_DSP2_ENABLE(xname, xshift) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
.info = wm8962_dsp2_ena_info, \
.get = wm8962_dsp2_ena_get, .put = wm8962_dsp2_ena_put, \
.private_value = xshift }
static int wm8962_dsp2_ena_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
uinfo->count = 1;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = 1;
return 0;
}
static int wm8962_dsp2_ena_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int shift = kcontrol->private_value;
struct snd_soc_codec *codec = snd_soc_kcontrol_codec(kcontrol);
struct wm8962_priv *wm8962 = snd_soc_codec_get_drvdata(codec);
ucontrol->value.integer.value[0] = !!(wm8962->dsp2_ena & 1 << shift);
return 0;
}
static int wm8962_dsp2_ena_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
int shift = kcontrol->private_value;
struct snd_soc_codec *codec = snd_soc_kcontrol_codec(kcontrol);
struct wm8962_priv *wm8962 = snd_soc_codec_get_drvdata(codec);
int old = wm8962->dsp2_ena;
int ret = 0;
int dsp2_running = snd_soc_read(codec, WM8962_DSP2_POWER_MANAGEMENT) &
WM8962_DSP2_ENA;
mutex_lock(&wm8962->dsp2_ena_lock);
if (ucontrol->value.integer.value[0])
wm8962->dsp2_ena |= 1 << shift;
else
wm8962->dsp2_ena &= ~(1 << shift);
if (wm8962->dsp2_ena == old)
goto out;
ret = 1;
if (dsp2_running) {
if (wm8962->dsp2_ena)
wm8962_dsp2_set_enable(codec, wm8962->dsp2_ena);
else
wm8962_dsp2_stop(codec);
}
out:
mutex_unlock(&wm8962->dsp2_ena_lock);
return ret;
}
/* The VU bits for the headphones are in a different register to the mute
* bits and only take effect on the PGA if it is actually powered.
*/
static int wm8962_put_hp_sw(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_soc_kcontrol_codec(kcontrol);
int ret;
/* Apply the update (if any) */
ret = snd_soc_put_volsw(kcontrol, ucontrol);
if (ret == 0)
return 0;
/* If the left PGA is enabled hit that VU bit... */
ret = snd_soc_read(codec, WM8962_PWR_MGMT_2);
if (ret & WM8962_HPOUTL_PGA_ENA) {
snd_soc_write(codec, WM8962_HPOUTL_VOLUME,
snd_soc_read(codec, WM8962_HPOUTL_VOLUME));
return 1;
}
/* ...otherwise the right. The VU is stereo. */
if (ret & WM8962_HPOUTR_PGA_ENA)
snd_soc_write(codec, WM8962_HPOUTR_VOLUME,
snd_soc_read(codec, WM8962_HPOUTR_VOLUME));
return 1;
}
/* The VU bits for the speakers are in a different register to the mute
* bits and only take effect on the PGA if it is actually powered.
*/
static int wm8962_put_spk_sw(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_soc_kcontrol_codec(kcontrol);
int ret;
/* Apply the update (if any) */
ret = snd_soc_put_volsw(kcontrol, ucontrol);
if (ret == 0)
return 0;
/* If the left PGA is enabled hit that VU bit... */
ret = snd_soc_read(codec, WM8962_PWR_MGMT_2);
if (ret & WM8962_SPKOUTL_PGA_ENA) {
snd_soc_write(codec, WM8962_SPKOUTL_VOLUME,
snd_soc_read(codec, WM8962_SPKOUTL_VOLUME));
return 1;
}
/* ...otherwise the right. The VU is stereo. */
if (ret & WM8962_SPKOUTR_PGA_ENA)
snd_soc_write(codec, WM8962_SPKOUTR_VOLUME,
snd_soc_read(codec, WM8962_SPKOUTR_VOLUME));
return 1;
}
static const char *cap_hpf_mode_text[] = {
"Hi-fi", "Application"
};
static SOC_ENUM_SINGLE_DECL(cap_hpf_mode,
WM8962_ADC_DAC_CONTROL_2, 10, cap_hpf_mode_text);
static const char *cap_lhpf_mode_text[] = {
"LPF", "HPF"
};
static SOC_ENUM_SINGLE_DECL(cap_lhpf_mode,
WM8962_LHPF1, 1, cap_lhpf_mode_text);
static const struct snd_kcontrol_new wm8962_snd_controls[] = {
SOC_DOUBLE("Input Mixer Switch", WM8962_INPUT_MIXER_CONTROL_1, 3, 2, 1, 1),
SOC_SINGLE_TLV("MIXINL IN2L Volume", WM8962_LEFT_INPUT_MIXER_VOLUME, 6, 7, 0,
mixin_tlv),
SOC_SINGLE_TLV("MIXINL PGA Volume", WM8962_LEFT_INPUT_MIXER_VOLUME, 3, 7, 0,
mixinpga_tlv),
SOC_SINGLE_TLV("MIXINL IN3L Volume", WM8962_LEFT_INPUT_MIXER_VOLUME, 0, 7, 0,
mixin_tlv),
SOC_SINGLE_TLV("MIXINR IN2R Volume", WM8962_RIGHT_INPUT_MIXER_VOLUME, 6, 7, 0,
mixin_tlv),
SOC_SINGLE_TLV("MIXINR PGA Volume", WM8962_RIGHT_INPUT_MIXER_VOLUME, 3, 7, 0,
mixinpga_tlv),
SOC_SINGLE_TLV("MIXINR IN3R Volume", WM8962_RIGHT_INPUT_MIXER_VOLUME, 0, 7, 0,
mixin_tlv),
SOC_DOUBLE_R_TLV("Digital Capture Volume", WM8962_LEFT_ADC_VOLUME,
WM8962_RIGHT_ADC_VOLUME, 1, 127, 0, digital_tlv),
SOC_DOUBLE_R_TLV("Capture Volume", WM8962_LEFT_INPUT_VOLUME,
WM8962_RIGHT_INPUT_VOLUME, 0, 63, 0, inpga_tlv),
SOC_DOUBLE_R("Capture Switch", WM8962_LEFT_INPUT_VOLUME,
WM8962_RIGHT_INPUT_VOLUME, 7, 1, 1),
SOC_DOUBLE_R("Capture ZC Switch", WM8962_LEFT_INPUT_VOLUME,
WM8962_RIGHT_INPUT_VOLUME, 6, 1, 1),
SOC_SINGLE("Capture HPF Switch", WM8962_ADC_DAC_CONTROL_1, 0, 1, 1),
SOC_ENUM("Capture HPF Mode", cap_hpf_mode),
SOC_SINGLE("Capture HPF Cutoff", WM8962_ADC_DAC_CONTROL_2, 7, 7, 0),
SOC_SINGLE("Capture LHPF Switch", WM8962_LHPF1, 0, 1, 0),
SOC_ENUM("Capture LHPF Mode", cap_lhpf_mode),
SOC_DOUBLE_R_TLV("Sidetone Volume", WM8962_DAC_DSP_MIXING_1,
WM8962_DAC_DSP_MIXING_2, 4, 12, 0, st_tlv),
SOC_DOUBLE_R_TLV("Digital Playback Volume", WM8962_LEFT_DAC_VOLUME,
WM8962_RIGHT_DAC_VOLUME, 1, 127, 0, digital_tlv),
SOC_SINGLE("DAC High Performance Switch", WM8962_ADC_DAC_CONTROL_2, 0, 1, 0),
SOC_SINGLE("DAC L/R Swap Switch", WM8962_AUDIO_INTERFACE_0, 5, 1, 0),
SOC_SINGLE("ADC L/R Swap Switch", WM8962_AUDIO_INTERFACE_0, 8, 1, 0),
SOC_SINGLE("ADC High Performance Switch", WM8962_ADDITIONAL_CONTROL_1,
5, 1, 0),
SOC_SINGLE_TLV("Beep Volume", WM8962_BEEP_GENERATOR_1, 4, 15, 0, beep_tlv),
SOC_DOUBLE_R_TLV("Headphone Volume", WM8962_HPOUTL_VOLUME,
WM8962_HPOUTR_VOLUME, 0, 127, 0, out_tlv),
SOC_DOUBLE_EXT("Headphone Switch", WM8962_PWR_MGMT_2, 1, 0, 1, 1,
snd_soc_get_volsw, wm8962_put_hp_sw),
SOC_DOUBLE_R("Headphone ZC Switch", WM8962_HPOUTL_VOLUME, WM8962_HPOUTR_VOLUME,
7, 1, 0),
SOC_DOUBLE_TLV("Headphone Aux Volume", WM8962_ANALOGUE_HP_2, 3, 6, 7, 0,
hp_tlv),
SOC_DOUBLE_R("Headphone Mixer Switch", WM8962_HEADPHONE_MIXER_3,
WM8962_HEADPHONE_MIXER_4, 8, 1, 1),
SOC_SINGLE_TLV("HPMIXL IN4L Volume", WM8962_HEADPHONE_MIXER_3,
3, 7, 0, bypass_tlv),
SOC_SINGLE_TLV("HPMIXL IN4R Volume", WM8962_HEADPHONE_MIXER_3,
0, 7, 0, bypass_tlv),
SOC_SINGLE_TLV("HPMIXL MIXINL Volume", WM8962_HEADPHONE_MIXER_3,
7, 1, 1, inmix_tlv),
SOC_SINGLE_TLV("HPMIXL MIXINR Volume", WM8962_HEADPHONE_MIXER_3,
6, 1, 1, inmix_tlv),
SOC_SINGLE_TLV("HPMIXR IN4L Volume", WM8962_HEADPHONE_MIXER_4,
3, 7, 0, bypass_tlv),
SOC_SINGLE_TLV("HPMIXR IN4R Volume", WM8962_HEADPHONE_MIXER_4,
0, 7, 0, bypass_tlv),
SOC_SINGLE_TLV("HPMIXR MIXINL Volume", WM8962_HEADPHONE_MIXER_4,
7, 1, 1, inmix_tlv),
SOC_SINGLE_TLV("HPMIXR MIXINR Volume", WM8962_HEADPHONE_MIXER_4,
6, 1, 1, inmix_tlv),
SOC_SINGLE_TLV("Speaker Boost Volume", WM8962_CLASS_D_CONTROL_2, 0, 7, 0,
classd_tlv),
SOC_SINGLE("EQ Switch", WM8962_EQ1, WM8962_EQ_ENA_SHIFT, 1, 0),
SOC_DOUBLE_R_TLV("EQ1 Volume", WM8962_EQ2, WM8962_EQ22,
WM8962_EQL_B1_GAIN_SHIFT, 31, 0, eq_tlv),
SOC_DOUBLE_R_TLV("EQ2 Volume", WM8962_EQ2, WM8962_EQ22,
WM8962_EQL_B2_GAIN_SHIFT, 31, 0, eq_tlv),
SOC_DOUBLE_R_TLV("EQ3 Volume", WM8962_EQ2, WM8962_EQ22,
WM8962_EQL_B3_GAIN_SHIFT, 31, 0, eq_tlv),
SOC_DOUBLE_R_TLV("EQ4 Volume", WM8962_EQ3, WM8962_EQ23,
WM8962_EQL_B4_GAIN_SHIFT, 31, 0, eq_tlv),
SOC_DOUBLE_R_TLV("EQ5 Volume", WM8962_EQ3, WM8962_EQ23,
WM8962_EQL_B5_GAIN_SHIFT, 31, 0, eq_tlv),
SND_SOC_BYTES("EQL Coefficients", WM8962_EQ4, 18),
SND_SOC_BYTES("EQR Coefficients", WM8962_EQ24, 18),
SOC_SINGLE("3D Switch", WM8962_THREED1, 0, 1, 0),
SND_SOC_BYTES_MASK("3D Coefficients", WM8962_THREED1, 4, WM8962_THREED_ENA),
SOC_SINGLE("DF1 Switch", WM8962_DF1, 0, 1, 0),
SND_SOC_BYTES_MASK("DF1 Coefficients", WM8962_DF1, 7, WM8962_DF1_ENA),
SOC_SINGLE("DRC Switch", WM8962_DRC_1, 0, 1, 0),
SND_SOC_BYTES_MASK("DRC Coefficients", WM8962_DRC_1, 5, WM8962_DRC_ENA),
WM8962_DSP2_ENABLE("VSS Switch", WM8962_VSS_ENA_SHIFT),
SND_SOC_BYTES("VSS Coefficients", WM8962_VSS_XHD2_1, 148),
WM8962_DSP2_ENABLE("HPF1 Switch", WM8962_HPF1_ENA_SHIFT),
WM8962_DSP2_ENABLE("HPF2 Switch", WM8962_HPF2_ENA_SHIFT),
SND_SOC_BYTES("HPF Coefficients", WM8962_LHPF2, 1),
WM8962_DSP2_ENABLE("HD Bass Switch", WM8962_HDBASS_ENA_SHIFT),
SND_SOC_BYTES("HD Bass Coefficients", WM8962_HDBASS_AI_1, 30),
SOC_DOUBLE("ALC Switch", WM8962_ALC1, WM8962_ALCL_ENA_SHIFT,
WM8962_ALCR_ENA_SHIFT, 1, 0),
SND_SOC_BYTES_MASK("ALC Coefficients", WM8962_ALC1, 4,
WM8962_ALCL_ENA_MASK | WM8962_ALCR_ENA_MASK),
};
static const struct snd_kcontrol_new wm8962_spk_mono_controls[] = {
SOC_SINGLE_TLV("Speaker Volume", WM8962_SPKOUTL_VOLUME, 0, 127, 0, out_tlv),
SOC_SINGLE_EXT("Speaker Switch", WM8962_CLASS_D_CONTROL_1, 1, 1, 1,
snd_soc_get_volsw, wm8962_put_spk_sw),
SOC_SINGLE("Speaker ZC Switch", WM8962_SPKOUTL_VOLUME, 7, 1, 0),
SOC_SINGLE("Speaker Mixer Switch", WM8962_SPEAKER_MIXER_3, 8, 1, 1),
SOC_SINGLE_TLV("Speaker Mixer IN4L Volume", WM8962_SPEAKER_MIXER_3,
3, 7, 0, bypass_tlv),
SOC_SINGLE_TLV("Speaker Mixer IN4R Volume", WM8962_SPEAKER_MIXER_3,
0, 7, 0, bypass_tlv),
SOC_SINGLE_TLV("Speaker Mixer MIXINL Volume", WM8962_SPEAKER_MIXER_3,
7, 1, 1, inmix_tlv),
SOC_SINGLE_TLV("Speaker Mixer MIXINR Volume", WM8962_SPEAKER_MIXER_3,
6, 1, 1, inmix_tlv),
SOC_SINGLE_TLV("Speaker Mixer DACL Volume", WM8962_SPEAKER_MIXER_5,
7, 1, 0, inmix_tlv),
SOC_SINGLE_TLV("Speaker Mixer DACR Volume", WM8962_SPEAKER_MIXER_5,
6, 1, 0, inmix_tlv),
};
static const struct snd_kcontrol_new wm8962_spk_stereo_controls[] = {
SOC_DOUBLE_R_TLV("Speaker Volume", WM8962_SPKOUTL_VOLUME,
WM8962_SPKOUTR_VOLUME, 0, 127, 0, out_tlv),
SOC_DOUBLE_EXT("Speaker Switch", WM8962_CLASS_D_CONTROL_1, 1, 0, 1, 1,
snd_soc_get_volsw, wm8962_put_spk_sw),
SOC_DOUBLE_R("Speaker ZC Switch", WM8962_SPKOUTL_VOLUME, WM8962_SPKOUTR_VOLUME,
7, 1, 0),
SOC_DOUBLE_R("Speaker Mixer Switch", WM8962_SPEAKER_MIXER_3,
WM8962_SPEAKER_MIXER_4, 8, 1, 1),
SOC_SINGLE_TLV("SPKOUTL Mixer IN4L Volume", WM8962_SPEAKER_MIXER_3,
3, 7, 0, bypass_tlv),
SOC_SINGLE_TLV("SPKOUTL Mixer IN4R Volume", WM8962_SPEAKER_MIXER_3,
0, 7, 0, bypass_tlv),
SOC_SINGLE_TLV("SPKOUTL Mixer MIXINL Volume", WM8962_SPEAKER_MIXER_3,
7, 1, 1, inmix_tlv),
SOC_SINGLE_TLV("SPKOUTL Mixer MIXINR Volume", WM8962_SPEAKER_MIXER_3,
6, 1, 1, inmix_tlv),
SOC_SINGLE_TLV("SPKOUTL Mixer DACL Volume", WM8962_SPEAKER_MIXER_5,
7, 1, 0, inmix_tlv),
SOC_SINGLE_TLV("SPKOUTL Mixer DACR Volume", WM8962_SPEAKER_MIXER_5,
6, 1, 0, inmix_tlv),
SOC_SINGLE_TLV("SPKOUTR Mixer IN4L Volume", WM8962_SPEAKER_MIXER_4,
3, 7, 0, bypass_tlv),
SOC_SINGLE_TLV("SPKOUTR Mixer IN4R Volume", WM8962_SPEAKER_MIXER_4,
0, 7, 0, bypass_tlv),
SOC_SINGLE_TLV("SPKOUTR Mixer MIXINL Volume", WM8962_SPEAKER_MIXER_4,
7, 1, 1, inmix_tlv),
SOC_SINGLE_TLV("SPKOUTR Mixer MIXINR Volume", WM8962_SPEAKER_MIXER_4,
6, 1, 1, inmix_tlv),
SOC_SINGLE_TLV("SPKOUTR Mixer DACL Volume", WM8962_SPEAKER_MIXER_5,
5, 1, 0, inmix_tlv),
SOC_SINGLE_TLV("SPKOUTR Mixer DACR Volume", WM8962_SPEAKER_MIXER_5,
4, 1, 0, inmix_tlv),
};
static int cp_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
switch (event) {
case SND_SOC_DAPM_POST_PMU:
msleep(5);
break;
default:
WARN(1, "Invalid event %d\n", event);
return -EINVAL;
}
return 0;
}
static int hp_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = snd_soc_dapm_to_codec(w->dapm);
int timeout;
int reg;
int expected = (WM8962_DCS_STARTUP_DONE_HP1L |
WM8962_DCS_STARTUP_DONE_HP1R);
switch (event) {
case SND_SOC_DAPM_POST_PMU:
snd_soc_update_bits(codec, WM8962_ANALOGUE_HP_0,
WM8962_HP1L_ENA | WM8962_HP1R_ENA,
WM8962_HP1L_ENA | WM8962_HP1R_ENA);
udelay(20);
snd_soc_update_bits(codec, WM8962_ANALOGUE_HP_0,
WM8962_HP1L_ENA_DLY | WM8962_HP1R_ENA_DLY,
WM8962_HP1L_ENA_DLY | WM8962_HP1R_ENA_DLY);
/* Start the DC servo */
snd_soc_update_bits(codec, WM8962_DC_SERVO_1,
WM8962_HP1L_DCS_ENA | WM8962_HP1R_DCS_ENA |
WM8962_HP1L_DCS_STARTUP |
WM8962_HP1R_DCS_STARTUP,
WM8962_HP1L_DCS_ENA | WM8962_HP1R_DCS_ENA |
WM8962_HP1L_DCS_STARTUP |
WM8962_HP1R_DCS_STARTUP);
/* Wait for it to complete, should be well under 100ms */
timeout = 0;
do {
msleep(1);
reg = snd_soc_read(codec, WM8962_DC_SERVO_6);
if (reg < 0) {
dev_err(codec->dev,
"Failed to read DCS status: %d\n",
reg);
continue;
}
dev_dbg(codec->dev, "DCS status: %x\n", reg);
} while (++timeout < 200 && (reg & expected) != expected);
if ((reg & expected) != expected)
dev_err(codec->dev, "DC servo timed out\n");
else
dev_dbg(codec->dev, "DC servo complete after %dms\n",
timeout);
snd_soc_update_bits(codec, WM8962_ANALOGUE_HP_0,
WM8962_HP1L_ENA_OUTP |
WM8962_HP1R_ENA_OUTP,
WM8962_HP1L_ENA_OUTP |
WM8962_HP1R_ENA_OUTP);
udelay(20);
snd_soc_update_bits(codec, WM8962_ANALOGUE_HP_0,
WM8962_HP1L_RMV_SHORT |
WM8962_HP1R_RMV_SHORT,
WM8962_HP1L_RMV_SHORT |
WM8962_HP1R_RMV_SHORT);
break;
case SND_SOC_DAPM_PRE_PMD:
snd_soc_update_bits(codec, WM8962_ANALOGUE_HP_0,
WM8962_HP1L_RMV_SHORT |
WM8962_HP1R_RMV_SHORT, 0);
udelay(20);
snd_soc_update_bits(codec, WM8962_DC_SERVO_1,
WM8962_HP1L_DCS_ENA | WM8962_HP1R_DCS_ENA |
WM8962_HP1L_DCS_STARTUP |
WM8962_HP1R_DCS_STARTUP,
0);
snd_soc_update_bits(codec, WM8962_ANALOGUE_HP_0,
WM8962_HP1L_ENA | WM8962_HP1R_ENA |
WM8962_HP1L_ENA_DLY | WM8962_HP1R_ENA_DLY |
WM8962_HP1L_ENA_OUTP |
WM8962_HP1R_ENA_OUTP, 0);
break;
default:
WARN(1, "Invalid event %d\n", event);
return -EINVAL;
}
return 0;
}
/* VU bits for the output PGAs only take effect while the PGA is powered */
static int out_pga_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = snd_soc_dapm_to_codec(w->dapm);
int reg;
switch (w->shift) {
case WM8962_HPOUTR_PGA_ENA_SHIFT:
reg = WM8962_HPOUTR_VOLUME;
break;
case WM8962_HPOUTL_PGA_ENA_SHIFT:
reg = WM8962_HPOUTL_VOLUME;
break;
case WM8962_SPKOUTR_PGA_ENA_SHIFT:
reg = WM8962_SPKOUTR_VOLUME;
break;
case WM8962_SPKOUTL_PGA_ENA_SHIFT:
reg = WM8962_SPKOUTL_VOLUME;
break;
default:
WARN(1, "Invalid shift %d\n", w->shift);
return -EINVAL;
}
switch (event) {
case SND_SOC_DAPM_POST_PMU:
return snd_soc_write(codec, reg, snd_soc_read(codec, reg));
default:
WARN(1, "Invalid event %d\n", event);
return -EINVAL;
}
}
static int dsp2_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = snd_soc_dapm_to_codec(w->dapm);
struct wm8962_priv *wm8962 = snd_soc_codec_get_drvdata(codec);
switch (event) {
case SND_SOC_DAPM_POST_PMU:
if (wm8962->dsp2_ena)
wm8962_dsp2_start(codec);
break;
case SND_SOC_DAPM_PRE_PMD:
if (wm8962->dsp2_ena)
wm8962_dsp2_stop(codec);
break;
default:
WARN(1, "Invalid event %d\n", event);
return -EINVAL;
}
return 0;
}
static const char *st_text[] = { "None", "Left", "Right" };
static SOC_ENUM_SINGLE_DECL(str_enum,
WM8962_DAC_DSP_MIXING_1, 2, st_text);
static const struct snd_kcontrol_new str_mux =
SOC_DAPM_ENUM("Right Sidetone", str_enum);
static SOC_ENUM_SINGLE_DECL(stl_enum,
WM8962_DAC_DSP_MIXING_2, 2, st_text);
static const struct snd_kcontrol_new stl_mux =
SOC_DAPM_ENUM("Left Sidetone", stl_enum);
static const char *outmux_text[] = { "DAC", "Mixer" };
static SOC_ENUM_SINGLE_DECL(spkoutr_enum,
WM8962_SPEAKER_MIXER_2, 7, outmux_text);
static const struct snd_kcontrol_new spkoutr_mux =
SOC_DAPM_ENUM("SPKOUTR Mux", spkoutr_enum);
static SOC_ENUM_SINGLE_DECL(spkoutl_enum,
WM8962_SPEAKER_MIXER_1, 7, outmux_text);
static const struct snd_kcontrol_new spkoutl_mux =
SOC_DAPM_ENUM("SPKOUTL Mux", spkoutl_enum);
static SOC_ENUM_SINGLE_DECL(hpoutr_enum,
WM8962_HEADPHONE_MIXER_2, 7, outmux_text);
static const struct snd_kcontrol_new hpoutr_mux =
SOC_DAPM_ENUM("HPOUTR Mux", hpoutr_enum);
static SOC_ENUM_SINGLE_DECL(hpoutl_enum,
WM8962_HEADPHONE_MIXER_1, 7, outmux_text);
static const struct snd_kcontrol_new hpoutl_mux =
SOC_DAPM_ENUM("HPOUTL Mux", hpoutl_enum);
static const struct snd_kcontrol_new inpgal[] = {
SOC_DAPM_SINGLE("IN1L Switch", WM8962_LEFT_INPUT_PGA_CONTROL, 3, 1, 0),
SOC_DAPM_SINGLE("IN2L Switch", WM8962_LEFT_INPUT_PGA_CONTROL, 2, 1, 0),
SOC_DAPM_SINGLE("IN3L Switch", WM8962_LEFT_INPUT_PGA_CONTROL, 1, 1, 0),
SOC_DAPM_SINGLE("IN4L Switch", WM8962_LEFT_INPUT_PGA_CONTROL, 0, 1, 0),
};
static const struct snd_kcontrol_new inpgar[] = {
SOC_DAPM_SINGLE("IN1R Switch", WM8962_RIGHT_INPUT_PGA_CONTROL, 3, 1, 0),
SOC_DAPM_SINGLE("IN2R Switch", WM8962_RIGHT_INPUT_PGA_CONTROL, 2, 1, 0),
SOC_DAPM_SINGLE("IN3R Switch", WM8962_RIGHT_INPUT_PGA_CONTROL, 1, 1, 0),
SOC_DAPM_SINGLE("IN4R Switch", WM8962_RIGHT_INPUT_PGA_CONTROL, 0, 1, 0),
};
static const struct snd_kcontrol_new mixinl[] = {
SOC_DAPM_SINGLE("IN2L Switch", WM8962_INPUT_MIXER_CONTROL_2, 5, 1, 0),
SOC_DAPM_SINGLE("IN3L Switch", WM8962_INPUT_MIXER_CONTROL_2, 4, 1, 0),
SOC_DAPM_SINGLE("PGA Switch", WM8962_INPUT_MIXER_CONTROL_2, 3, 1, 0),
};
static const struct snd_kcontrol_new mixinr[] = {
SOC_DAPM_SINGLE("IN2R Switch", WM8962_INPUT_MIXER_CONTROL_2, 2, 1, 0),
SOC_DAPM_SINGLE("IN3R Switch", WM8962_INPUT_MIXER_CONTROL_2, 1, 1, 0),
SOC_DAPM_SINGLE("PGA Switch", WM8962_INPUT_MIXER_CONTROL_2, 0, 1, 0),
};
static const struct snd_kcontrol_new hpmixl[] = {
SOC_DAPM_SINGLE("DACL Switch", WM8962_HEADPHONE_MIXER_1, 5, 1, 0),
SOC_DAPM_SINGLE("DACR Switch", WM8962_HEADPHONE_MIXER_1, 4, 1, 0),
SOC_DAPM_SINGLE("MIXINL Switch", WM8962_HEADPHONE_MIXER_1, 3, 1, 0),
SOC_DAPM_SINGLE("MIXINR Switch", WM8962_HEADPHONE_MIXER_1, 2, 1, 0),
SOC_DAPM_SINGLE("IN4L Switch", WM8962_HEADPHONE_MIXER_1, 1, 1, 0),
SOC_DAPM_SINGLE("IN4R Switch", WM8962_HEADPHONE_MIXER_1, 0, 1, 0),
};
static const struct snd_kcontrol_new hpmixr[] = {
SOC_DAPM_SINGLE("DACL Switch", WM8962_HEADPHONE_MIXER_2, 5, 1, 0),
SOC_DAPM_SINGLE("DACR Switch", WM8962_HEADPHONE_MIXER_2, 4, 1, 0),
SOC_DAPM_SINGLE("MIXINL Switch", WM8962_HEADPHONE_MIXER_2, 3, 1, 0),
SOC_DAPM_SINGLE("MIXINR Switch", WM8962_HEADPHONE_MIXER_2, 2, 1, 0),
SOC_DAPM_SINGLE("IN4L Switch", WM8962_HEADPHONE_MIXER_2, 1, 1, 0),
SOC_DAPM_SINGLE("IN4R Switch", WM8962_HEADPHONE_MIXER_2, 0, 1, 0),
};
static const struct snd_kcontrol_new spkmixl[] = {
SOC_DAPM_SINGLE("DACL Switch", WM8962_SPEAKER_MIXER_1, 5, 1, 0),
SOC_DAPM_SINGLE("DACR Switch", WM8962_SPEAKER_MIXER_1, 4, 1, 0),
SOC_DAPM_SINGLE("MIXINL Switch", WM8962_SPEAKER_MIXER_1, 3, 1, 0),
SOC_DAPM_SINGLE("MIXINR Switch", WM8962_SPEAKER_MIXER_1, 2, 1, 0),
SOC_DAPM_SINGLE("IN4L Switch", WM8962_SPEAKER_MIXER_1, 1, 1, 0),
SOC_DAPM_SINGLE("IN4R Switch", WM8962_SPEAKER_MIXER_1, 0, 1, 0),
};
static const struct snd_kcontrol_new spkmixr[] = {
SOC_DAPM_SINGLE("DACL Switch", WM8962_SPEAKER_MIXER_2, 5, 1, 0),
SOC_DAPM_SINGLE("DACR Switch", WM8962_SPEAKER_MIXER_2, 4, 1, 0),
SOC_DAPM_SINGLE("MIXINL Switch", WM8962_SPEAKER_MIXER_2, 3, 1, 0),
SOC_DAPM_SINGLE("MIXINR Switch", WM8962_SPEAKER_MIXER_2, 2, 1, 0),
SOC_DAPM_SINGLE("IN4L Switch", WM8962_SPEAKER_MIXER_2, 1, 1, 0),
SOC_DAPM_SINGLE("IN4R Switch", WM8962_SPEAKER_MIXER_2, 0, 1, 0),
};
static const struct snd_soc_dapm_widget wm8962_dapm_widgets[] = {
SND_SOC_DAPM_INPUT("IN1L"),
SND_SOC_DAPM_INPUT("IN1R"),
SND_SOC_DAPM_INPUT("IN2L"),
SND_SOC_DAPM_INPUT("IN2R"),
SND_SOC_DAPM_INPUT("IN3L"),
SND_SOC_DAPM_INPUT("IN3R"),
SND_SOC_DAPM_INPUT("IN4L"),
SND_SOC_DAPM_INPUT("IN4R"),
SND_SOC_DAPM_SIGGEN("Beep"),
SND_SOC_DAPM_INPUT("DMICDAT"),
SND_SOC_DAPM_SUPPLY("MICBIAS", WM8962_PWR_MGMT_1, 1, 0, NULL, 0),
SND_SOC_DAPM_SUPPLY("Class G", WM8962_CHARGE_PUMP_B, 0, 1, NULL, 0),
SND_SOC_DAPM_SUPPLY("SYSCLK", WM8962_CLOCKING2, 5, 0, NULL, 0),
SND_SOC_DAPM_SUPPLY("Charge Pump", WM8962_CHARGE_PUMP_1, 0, 0, cp_event,
SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_SUPPLY("TOCLK", WM8962_ADDITIONAL_CONTROL_1, 0, 0, NULL, 0),
SND_SOC_DAPM_SUPPLY_S("DSP2", 1, WM8962_DSP2_POWER_MANAGEMENT,
WM8962_DSP2_ENA_SHIFT, 0, dsp2_event,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_PMD),
SND_SOC_DAPM_SUPPLY("TEMP_HP", WM8962_ADDITIONAL_CONTROL_4, 2, 0, NULL, 0),
SND_SOC_DAPM_SUPPLY("TEMP_SPK", WM8962_ADDITIONAL_CONTROL_4, 1, 0, NULL, 0),
SND_SOC_DAPM_MIXER("INPGAL", WM8962_LEFT_INPUT_PGA_CONTROL, 4, 0,
inpgal, ARRAY_SIZE(inpgal)),
SND_SOC_DAPM_MIXER("INPGAR", WM8962_RIGHT_INPUT_PGA_CONTROL, 4, 0,
inpgar, ARRAY_SIZE(inpgar)),
SND_SOC_DAPM_MIXER("MIXINL", WM8962_PWR_MGMT_1, 5, 0,
mixinl, ARRAY_SIZE(mixinl)),
SND_SOC_DAPM_MIXER("MIXINR", WM8962_PWR_MGMT_1, 4, 0,
mixinr, ARRAY_SIZE(mixinr)),
SND_SOC_DAPM_AIF_IN("DMIC_ENA", NULL, 0, WM8962_PWR_MGMT_1, 10, 0),
SND_SOC_DAPM_ADC("ADCL", "Capture", WM8962_PWR_MGMT_1, 3, 0),
SND_SOC_DAPM_ADC("ADCR", "Capture", WM8962_PWR_MGMT_1, 2, 0),
SND_SOC_DAPM_MUX("STL", SND_SOC_NOPM, 0, 0, &stl_mux),
SND_SOC_DAPM_MUX("STR", SND_SOC_NOPM, 0, 0, &str_mux),
SND_SOC_DAPM_DAC("DACL", "Playback", WM8962_PWR_MGMT_2, 8, 0),
SND_SOC_DAPM_DAC("DACR", "Playback", WM8962_PWR_MGMT_2, 7, 0),
SND_SOC_DAPM_PGA("Left Bypass", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_PGA("Right Bypass", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("HPMIXL", WM8962_MIXER_ENABLES, 3, 0,
hpmixl, ARRAY_SIZE(hpmixl)),
SND_SOC_DAPM_MIXER("HPMIXR", WM8962_MIXER_ENABLES, 2, 0,
hpmixr, ARRAY_SIZE(hpmixr)),
SND_SOC_DAPM_MUX_E("HPOUTL PGA", WM8962_PWR_MGMT_2, 6, 0, &hpoutl_mux,
out_pga_event, SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_MUX_E("HPOUTR PGA", WM8962_PWR_MGMT_2, 5, 0, &hpoutr_mux,
out_pga_event, SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_PGA_E("HPOUT", SND_SOC_NOPM, 0, 0, NULL, 0, hp_event,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_PMD),
SND_SOC_DAPM_OUTPUT("HPOUTL"),
SND_SOC_DAPM_OUTPUT("HPOUTR"),
};
static const struct snd_soc_dapm_widget wm8962_dapm_spk_mono_widgets[] = {
SND_SOC_DAPM_MIXER("Speaker Mixer", WM8962_MIXER_ENABLES, 1, 0,
spkmixl, ARRAY_SIZE(spkmixl)),
SND_SOC_DAPM_MUX_E("Speaker PGA", WM8962_PWR_MGMT_2, 4, 0, &spkoutl_mux,
out_pga_event, SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_PGA("Speaker Output", WM8962_CLASS_D_CONTROL_1, 7, 0, NULL, 0),
SND_SOC_DAPM_OUTPUT("SPKOUT"),
};
static const struct snd_soc_dapm_widget wm8962_dapm_spk_stereo_widgets[] = {
SND_SOC_DAPM_MIXER("SPKOUTL Mixer", WM8962_MIXER_ENABLES, 1, 0,
spkmixl, ARRAY_SIZE(spkmixl)),
SND_SOC_DAPM_MIXER("SPKOUTR Mixer", WM8962_MIXER_ENABLES, 0, 0,
spkmixr, ARRAY_SIZE(spkmixr)),
SND_SOC_DAPM_MUX_E("SPKOUTL PGA", WM8962_PWR_MGMT_2, 4, 0, &spkoutl_mux,
out_pga_event, SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_MUX_E("SPKOUTR PGA", WM8962_PWR_MGMT_2, 3, 0, &spkoutr_mux,
out_pga_event, SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_PGA("SPKOUTR Output", WM8962_CLASS_D_CONTROL_1, 7, 0, NULL, 0),
SND_SOC_DAPM_PGA("SPKOUTL Output", WM8962_CLASS_D_CONTROL_1, 6, 0, NULL, 0),
SND_SOC_DAPM_OUTPUT("SPKOUTL"),
SND_SOC_DAPM_OUTPUT("SPKOUTR"),
};
static const struct snd_soc_dapm_route wm8962_intercon[] = {
{ "INPGAL", "IN1L Switch", "IN1L" },
{ "INPGAL", "IN2L Switch", "IN2L" },
{ "INPGAL", "IN3L Switch", "IN3L" },
{ "INPGAL", "IN4L Switch", "IN4L" },
{ "INPGAR", "IN1R Switch", "IN1R" },
{ "INPGAR", "IN2R Switch", "IN2R" },
{ "INPGAR", "IN3R Switch", "IN3R" },
{ "INPGAR", "IN4R Switch", "IN4R" },
{ "MIXINL", "IN2L Switch", "IN2L" },
{ "MIXINL", "IN3L Switch", "IN3L" },
{ "MIXINL", "PGA Switch", "INPGAL" },
{ "MIXINR", "IN2R Switch", "IN2R" },
{ "MIXINR", "IN3R Switch", "IN3R" },
{ "MIXINR", "PGA Switch", "INPGAR" },
{ "MICBIAS", NULL, "SYSCLK" },
{ "DMIC_ENA", NULL, "DMICDAT" },
{ "ADCL", NULL, "SYSCLK" },
{ "ADCL", NULL, "TOCLK" },
{ "ADCL", NULL, "MIXINL" },
{ "ADCL", NULL, "DMIC_ENA" },
{ "ADCL", NULL, "DSP2" },
{ "ADCR", NULL, "SYSCLK" },
{ "ADCR", NULL, "TOCLK" },
{ "ADCR", NULL, "MIXINR" },
{ "ADCR", NULL, "DMIC_ENA" },
{ "ADCR", NULL, "DSP2" },
{ "STL", "Left", "ADCL" },
{ "STL", "Right", "ADCR" },
{ "STL", NULL, "Class G" },
{ "STR", "Left", "ADCL" },
{ "STR", "Right", "ADCR" },
{ "STR", NULL, "Class G" },
{ "DACL", NULL, "SYSCLK" },
{ "DACL", NULL, "TOCLK" },
{ "DACL", NULL, "Beep" },
{ "DACL", NULL, "STL" },
{ "DACL", NULL, "DSP2" },
{ "DACR", NULL, "SYSCLK" },
{ "DACR", NULL, "TOCLK" },
{ "DACR", NULL, "Beep" },
{ "DACR", NULL, "STR" },
{ "DACR", NULL, "DSP2" },
{ "HPMIXL", "IN4L Switch", "IN4L" },
{ "HPMIXL", "IN4R Switch", "IN4R" },
{ "HPMIXL", "DACL Switch", "DACL" },
{ "HPMIXL", "DACR Switch", "DACR" },
{ "HPMIXL", "MIXINL Switch", "MIXINL" },
{ "HPMIXL", "MIXINR Switch", "MIXINR" },
{ "HPMIXR", "IN4L Switch", "IN4L" },
{ "HPMIXR", "IN4R Switch", "IN4R" },
{ "HPMIXR", "DACL Switch", "DACL" },
{ "HPMIXR", "DACR Switch", "DACR" },
{ "HPMIXR", "MIXINL Switch", "MIXINL" },
{ "HPMIXR", "MIXINR Switch", "MIXINR" },
{ "Left Bypass", NULL, "HPMIXL" },
{ "Left Bypass", NULL, "Class G" },
{ "Right Bypass", NULL, "HPMIXR" },
{ "Right Bypass", NULL, "Class G" },
{ "HPOUTL PGA", "Mixer", "Left Bypass" },
{ "HPOUTL PGA", "DAC", "DACL" },
{ "HPOUTR PGA", "Mixer", "Right Bypass" },
{ "HPOUTR PGA", "DAC", "DACR" },
{ "HPOUT", NULL, "HPOUTL PGA" },
{ "HPOUT", NULL, "HPOUTR PGA" },
{ "HPOUT", NULL, "Charge Pump" },
{ "HPOUT", NULL, "SYSCLK" },
{ "HPOUT", NULL, "TOCLK" },
{ "HPOUTL", NULL, "HPOUT" },
{ "HPOUTR", NULL, "HPOUT" },
{ "HPOUTL", NULL, "TEMP_HP" },
{ "HPOUTR", NULL, "TEMP_HP" },
};
static const struct snd_soc_dapm_route wm8962_spk_mono_intercon[] = {
{ "Speaker Mixer", "IN4L Switch", "IN4L" },
{ "Speaker Mixer", "IN4R Switch", "IN4R" },
{ "Speaker Mixer", "DACL Switch", "DACL" },
{ "Speaker Mixer", "DACR Switch", "DACR" },
{ "Speaker Mixer", "MIXINL Switch", "MIXINL" },
{ "Speaker Mixer", "MIXINR Switch", "MIXINR" },
{ "Speaker PGA", "Mixer", "Speaker Mixer" },
{ "Speaker PGA", "DAC", "DACL" },
{ "Speaker Output", NULL, "Speaker PGA" },
{ "Speaker Output", NULL, "SYSCLK" },
{ "Speaker Output", NULL, "TOCLK" },
{ "Speaker Output", NULL, "TEMP_SPK" },
{ "SPKOUT", NULL, "Speaker Output" },
};
static const struct snd_soc_dapm_route wm8962_spk_stereo_intercon[] = {
{ "SPKOUTL Mixer", "IN4L Switch", "IN4L" },
{ "SPKOUTL Mixer", "IN4R Switch", "IN4R" },
{ "SPKOUTL Mixer", "DACL Switch", "DACL" },
{ "SPKOUTL Mixer", "DACR Switch", "DACR" },
{ "SPKOUTL Mixer", "MIXINL Switch", "MIXINL" },
{ "SPKOUTL Mixer", "MIXINR Switch", "MIXINR" },
{ "SPKOUTR Mixer", "IN4L Switch", "IN4L" },
{ "SPKOUTR Mixer", "IN4R Switch", "IN4R" },
{ "SPKOUTR Mixer", "DACL Switch", "DACL" },
{ "SPKOUTR Mixer", "DACR Switch", "DACR" },
{ "SPKOUTR Mixer", "MIXINL Switch", "MIXINL" },
{ "SPKOUTR Mixer", "MIXINR Switch", "MIXINR" },
{ "SPKOUTL PGA", "Mixer", "SPKOUTL Mixer" },
{ "SPKOUTL PGA", "DAC", "DACL" },
{ "SPKOUTR PGA", "Mixer", "SPKOUTR Mixer" },
{ "SPKOUTR PGA", "DAC", "DACR" },
{ "SPKOUTL Output", NULL, "SPKOUTL PGA" },
{ "SPKOUTL Output", NULL, "SYSCLK" },
{ "SPKOUTL Output", NULL, "TOCLK" },
{ "SPKOUTL Output", NULL, "TEMP_SPK" },
{ "SPKOUTR Output", NULL, "SPKOUTR PGA" },
{ "SPKOUTR Output", NULL, "SYSCLK" },
{ "SPKOUTR Output", NULL, "TOCLK" },
{ "SPKOUTR Output", NULL, "TEMP_SPK" },
{ "SPKOUTL", NULL, "SPKOUTL Output" },
{ "SPKOUTR", NULL, "SPKOUTR Output" },
};
static int wm8962_add_widgets(struct snd_soc_codec *codec)
{
struct wm8962_priv *wm8962 = snd_soc_codec_get_drvdata(codec);
struct wm8962_pdata *pdata = &wm8962->pdata;
struct snd_soc_dapm_context *dapm = &codec->dapm;
snd_soc_add_codec_controls(codec, wm8962_snd_controls,
ARRAY_SIZE(wm8962_snd_controls));
if (pdata->spk_mono)
snd_soc_add_codec_controls(codec, wm8962_spk_mono_controls,
ARRAY_SIZE(wm8962_spk_mono_controls));
else
snd_soc_add_codec_controls(codec, wm8962_spk_stereo_controls,
ARRAY_SIZE(wm8962_spk_stereo_controls));
snd_soc_dapm_new_controls(dapm, wm8962_dapm_widgets,
ARRAY_SIZE(wm8962_dapm_widgets));
if (pdata->spk_mono)
snd_soc_dapm_new_controls(dapm, wm8962_dapm_spk_mono_widgets,
ARRAY_SIZE(wm8962_dapm_spk_mono_widgets));
else
snd_soc_dapm_new_controls(dapm, wm8962_dapm_spk_stereo_widgets,
ARRAY_SIZE(wm8962_dapm_spk_stereo_widgets));
snd_soc_dapm_add_routes(dapm, wm8962_intercon,
ARRAY_SIZE(wm8962_intercon));
if (pdata->spk_mono)
snd_soc_dapm_add_routes(dapm, wm8962_spk_mono_intercon,
ARRAY_SIZE(wm8962_spk_mono_intercon));
else
snd_soc_dapm_add_routes(dapm, wm8962_spk_stereo_intercon,
ARRAY_SIZE(wm8962_spk_stereo_intercon));
snd_soc_dapm_disable_pin(dapm, "Beep");
return 0;
}
/* -1 for reserved values */
static const int bclk_divs[] = {
1, -1, 2, 3, 4, -1, 6, 8, -1, 12, 16, 24, -1, 32, 32, 32
};
static const int sysclk_rates[] = {
64, 128, 192, 256, 384, 512, 768, 1024, 1408, 1536, 3072, 6144
};
static void wm8962_configure_bclk(struct snd_soc_codec *codec)
{
struct wm8962_priv *wm8962 = snd_soc_codec_get_drvdata(codec);
int dspclk, i;
int clocking2 = 0;
int clocking4 = 0;
int aif2 = 0;
if (!wm8962->sysclk_rate) {
dev_dbg(codec->dev, "No SYSCLK configured\n");
return;
}
if (!wm8962->bclk || !wm8962->lrclk) {
dev_dbg(codec->dev, "No audio clocks configured\n");
return;
}
for (i = 0; i < ARRAY_SIZE(sysclk_rates); i++) {
if (sysclk_rates[i] == wm8962->sysclk_rate / wm8962->lrclk) {
clocking4 |= i << WM8962_SYSCLK_RATE_SHIFT;
break;
}
}
if (i == ARRAY_SIZE(sysclk_rates)) {
dev_err(codec->dev, "Unsupported sysclk ratio %d\n",
wm8962->sysclk_rate / wm8962->lrclk);
return;
}
dev_dbg(codec->dev, "Selected sysclk ratio %d\n", sysclk_rates[i]);
snd_soc_update_bits(codec, WM8962_CLOCKING_4,
WM8962_SYSCLK_RATE_MASK, clocking4);
/* DSPCLK_DIV can be only generated correctly after enabling SYSCLK.
* So we here provisionally enable it and then disable it afterward
* if current bias_level hasn't reached SND_SOC_BIAS_ON.
*/
if (codec->dapm.bias_level != SND_SOC_BIAS_ON)
snd_soc_update_bits(codec, WM8962_CLOCKING2,
WM8962_SYSCLK_ENA_MASK, WM8962_SYSCLK_ENA);
dspclk = snd_soc_read(codec, WM8962_CLOCKING1);
if (codec->dapm.bias_level != SND_SOC_BIAS_ON)
snd_soc_update_bits(codec, WM8962_CLOCKING2,
WM8962_SYSCLK_ENA_MASK, 0);
if (dspclk < 0) {
dev_err(codec->dev, "Failed to read DSPCLK: %d\n", dspclk);
return;
}
dspclk = (dspclk & WM8962_DSPCLK_DIV_MASK) >> WM8962_DSPCLK_DIV_SHIFT;
switch (dspclk) {
case 0:
dspclk = wm8962->sysclk_rate;
break;
case 1:
dspclk = wm8962->sysclk_rate / 2;
break;
case 2:
dspclk = wm8962->sysclk_rate / 4;
break;
default:
dev_warn(codec->dev, "Unknown DSPCLK divisor read back\n");
dspclk = wm8962->sysclk;
}
dev_dbg(codec->dev, "DSPCLK is %dHz, BCLK %d\n", dspclk, wm8962->bclk);
/* We're expecting an exact match */
for (i = 0; i < ARRAY_SIZE(bclk_divs); i++) {
if (bclk_divs[i] < 0)
continue;
if (dspclk / bclk_divs[i] == wm8962->bclk) {
dev_dbg(codec->dev, "Selected BCLK_DIV %d for %dHz\n",
bclk_divs[i], wm8962->bclk);
clocking2 |= i;
break;
}
}
if (i == ARRAY_SIZE(bclk_divs)) {
dev_err(codec->dev, "Unsupported BCLK ratio %d\n",
dspclk / wm8962->bclk);
return;
}
aif2 |= wm8962->bclk / wm8962->lrclk;
dev_dbg(codec->dev, "Selected LRCLK divisor %d for %dHz\n",
wm8962->bclk / wm8962->lrclk, wm8962->lrclk);
snd_soc_update_bits(codec, WM8962_CLOCKING2,
WM8962_BCLK_DIV_MASK, clocking2);
snd_soc_update_bits(codec, WM8962_AUDIO_INTERFACE_2,
WM8962_AIF_RATE_MASK, aif2);
}
static int wm8962_set_bias_level(struct snd_soc_codec *codec,
enum snd_soc_bias_level level)
{
if (level == codec->dapm.bias_level)
return 0;
switch (level) {
case SND_SOC_BIAS_ON:
break;
case SND_SOC_BIAS_PREPARE:
/* VMID 2*50k */
snd_soc_update_bits(codec, WM8962_PWR_MGMT_1,
WM8962_VMID_SEL_MASK, 0x80);
wm8962_configure_bclk(codec);
break;
case SND_SOC_BIAS_STANDBY:
/* VMID 2*250k */
snd_soc_update_bits(codec, WM8962_PWR_MGMT_1,
WM8962_VMID_SEL_MASK, 0x100);
if (codec->dapm.bias_level == SND_SOC_BIAS_OFF)
msleep(100);
break;
case SND_SOC_BIAS_OFF:
break;
}
codec->dapm.bias_level = level;
return 0;
}
static const struct {
int rate;
int reg;
} sr_vals[] = {
{ 48000, 0 },
{ 44100, 0 },
{ 32000, 1 },
{ 22050, 2 },
{ 24000, 2 },
{ 16000, 3 },
{ 11025, 4 },
{ 12000, 4 },
{ 8000, 5 },
{ 88200, 6 },
{ 96000, 6 },
};
static int wm8962_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct snd_soc_codec *codec = dai->codec;
struct wm8962_priv *wm8962 = snd_soc_codec_get_drvdata(codec);
int i;
int aif0 = 0;
int adctl3 = 0;
wm8962->bclk = snd_soc_params_to_bclk(params);
if (params_channels(params) == 1)
wm8962->bclk *= 2;
wm8962->lrclk = params_rate(params);
for (i = 0; i < ARRAY_SIZE(sr_vals); i++) {
if (sr_vals[i].rate == wm8962->lrclk) {
adctl3 |= sr_vals[i].reg;
break;
}
}
if (i == ARRAY_SIZE(sr_vals)) {
dev_err(codec->dev, "Unsupported rate %dHz\n", wm8962->lrclk);
return -EINVAL;
}
if (wm8962->lrclk % 8000 == 0)
adctl3 |= WM8962_SAMPLE_RATE_INT_MODE;
switch (params_width(params)) {
case 16:
break;
case 20:
aif0 |= 0x4;
break;
case 24:
aif0 |= 0x8;
break;
case 32:
aif0 |= 0xc;
break;
default:
return -EINVAL;
}
snd_soc_update_bits(codec, WM8962_AUDIO_INTERFACE_0,
WM8962_WL_MASK, aif0);
snd_soc_update_bits(codec, WM8962_ADDITIONAL_CONTROL_3,
WM8962_SAMPLE_RATE_INT_MODE |
WM8962_SAMPLE_RATE_MASK, adctl3);
dev_dbg(codec->dev, "hw_params set BCLK %dHz LRCLK %dHz\n",
wm8962->bclk, wm8962->lrclk);
if (codec->dapm.bias_level == SND_SOC_BIAS_ON)
wm8962_configure_bclk(codec);
return 0;
}
static int wm8962_set_dai_sysclk(struct snd_soc_dai *dai, int clk_id,
unsigned int freq, int dir)
{
struct snd_soc_codec *codec = dai->codec;
struct wm8962_priv *wm8962 = snd_soc_codec_get_drvdata(codec);
int src;
switch (clk_id) {
case WM8962_SYSCLK_MCLK:
wm8962->sysclk = WM8962_SYSCLK_MCLK;
src = 0;
break;
case WM8962_SYSCLK_FLL:
wm8962->sysclk = WM8962_SYSCLK_FLL;
src = 1 << WM8962_SYSCLK_SRC_SHIFT;
break;
default:
return -EINVAL;
}
snd_soc_update_bits(codec, WM8962_CLOCKING2, WM8962_SYSCLK_SRC_MASK,
src);
wm8962->sysclk_rate = freq;
return 0;
}
static int wm8962_set_dai_fmt(struct snd_soc_dai *dai, unsigned int fmt)
{
struct snd_soc_codec *codec = dai->codec;
int aif0 = 0;
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_DSP_B:
aif0 |= WM8962_LRCLK_INV | 3;
case SND_SOC_DAIFMT_DSP_A:
aif0 |= 3;
switch (fmt & SND_SOC_DAIFMT_INV_MASK) {
case SND_SOC_DAIFMT_NB_NF:
case SND_SOC_DAIFMT_IB_NF:
break;
default:
return -EINVAL;
}
break;
case SND_SOC_DAIFMT_RIGHT_J:
break;
case SND_SOC_DAIFMT_LEFT_J:
aif0 |= 1;
break;
case SND_SOC_DAIFMT_I2S:
aif0 |= 2;
break;
default:
return -EINVAL;
}
switch (fmt & SND_SOC_DAIFMT_INV_MASK) {
case SND_SOC_DAIFMT_NB_NF:
break;
case SND_SOC_DAIFMT_IB_NF:
aif0 |= WM8962_BCLK_INV;
break;
case SND_SOC_DAIFMT_NB_IF:
aif0 |= WM8962_LRCLK_INV;
break;
case SND_SOC_DAIFMT_IB_IF:
aif0 |= WM8962_BCLK_INV | WM8962_LRCLK_INV;
break;
default:
return -EINVAL;
}
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBM_CFM:
aif0 |= WM8962_MSTR;
break;
case SND_SOC_DAIFMT_CBS_CFS:
break;
default:
return -EINVAL;
}
snd_soc_update_bits(codec, WM8962_AUDIO_INTERFACE_0,
WM8962_FMT_MASK | WM8962_BCLK_INV | WM8962_MSTR |
WM8962_LRCLK_INV, aif0);
return 0;
}
struct _fll_div {
u16 fll_fratio;
u16 fll_outdiv;
u16 fll_refclk_div;
u16 n;
u16 theta;
u16 lambda;
};
/* The size in bits of the FLL divide multiplied by 10
* to allow rounding later */
#define FIXED_FLL_SIZE ((1 << 16) * 10)
static struct {
unsigned int min;
unsigned int max;
u16 fll_fratio;
int ratio;
} fll_fratios[] = {
{ 0, 64000, 4, 16 },
{ 64000, 128000, 3, 8 },
{ 128000, 256000, 2, 4 },
{ 256000, 1000000, 1, 2 },
{ 1000000, 13500000, 0, 1 },
};
static int fll_factors(struct _fll_div *fll_div, unsigned int Fref,
unsigned int Fout)
{
unsigned int target;
unsigned int div;
unsigned int fratio, gcd_fll;
int i;
/* Fref must be <=13.5MHz */
div = 1;
fll_div->fll_refclk_div = 0;
while ((Fref / div) > 13500000) {
div *= 2;
fll_div->fll_refclk_div++;
if (div > 4) {
pr_err("Can't scale %dMHz input down to <=13.5MHz\n",
Fref);
return -EINVAL;
}
}
pr_debug("FLL Fref=%u Fout=%u\n", Fref, Fout);
/* Apply the division for our remaining calculations */
Fref /= div;
/* Fvco should be 90-100MHz; don't check the upper bound */
div = 2;
while (Fout * div < 90000000) {
div++;
if (div > 64) {
pr_err("Unable to find FLL_OUTDIV for Fout=%uHz\n",
Fout);
return -EINVAL;
}
}
target = Fout * div;
fll_div->fll_outdiv = div - 1;
pr_debug("FLL Fvco=%dHz\n", target);
/* Find an appropriate FLL_FRATIO and factor it out of the target */
for (i = 0; i < ARRAY_SIZE(fll_fratios); i++) {
if (fll_fratios[i].min <= Fref && Fref <= fll_fratios[i].max) {
fll_div->fll_fratio = fll_fratios[i].fll_fratio;
fratio = fll_fratios[i].ratio;
break;
}
}
if (i == ARRAY_SIZE(fll_fratios)) {
pr_err("Unable to find FLL_FRATIO for Fref=%uHz\n", Fref);
return -EINVAL;
}
fll_div->n = target / (fratio * Fref);
if (target % Fref == 0) {
fll_div->theta = 0;
fll_div->lambda = 0;
} else {
gcd_fll = gcd(target, fratio * Fref);
fll_div->theta = (target - (fll_div->n * fratio * Fref))
/ gcd_fll;
fll_div->lambda = (fratio * Fref) / gcd_fll;
}
pr_debug("FLL N=%x THETA=%x LAMBDA=%x\n",
fll_div->n, fll_div->theta, fll_div->lambda);
pr_debug("FLL_FRATIO=%x FLL_OUTDIV=%x FLL_REFCLK_DIV=%x\n",
fll_div->fll_fratio, fll_div->fll_outdiv,
fll_div->fll_refclk_div);
return 0;
}
static int wm8962_set_fll(struct snd_soc_codec *codec, int fll_id, int source,
unsigned int Fref, unsigned int Fout)
{
struct wm8962_priv *wm8962 = snd_soc_codec_get_drvdata(codec);
struct _fll_div fll_div;
unsigned long timeout;
int ret;
int fll1 = 0;
/* Any change? */
if (source == wm8962->fll_src && Fref == wm8962->fll_fref &&
Fout == wm8962->fll_fout)
return 0;
if (Fout == 0) {
dev_dbg(codec->dev, "FLL disabled\n");
wm8962->fll_fref = 0;
wm8962->fll_fout = 0;
snd_soc_update_bits(codec, WM8962_FLL_CONTROL_1,
WM8962_FLL_ENA, 0);
pm_runtime_put(codec->dev);
return 0;
}
ret = fll_factors(&fll_div, Fref, Fout);
if (ret != 0)
return ret;
/* Parameters good, disable so we can reprogram */
snd_soc_update_bits(codec, WM8962_FLL_CONTROL_1, WM8962_FLL_ENA, 0);
switch (fll_id) {
case WM8962_FLL_MCLK:
case WM8962_FLL_BCLK:
case WM8962_FLL_OSC:
fll1 |= (fll_id - 1) << WM8962_FLL_REFCLK_SRC_SHIFT;
break;
case WM8962_FLL_INT:
snd_soc_update_bits(codec, WM8962_FLL_CONTROL_1,
WM8962_FLL_OSC_ENA, WM8962_FLL_OSC_ENA);
snd_soc_update_bits(codec, WM8962_FLL_CONTROL_5,
WM8962_FLL_FRC_NCO, WM8962_FLL_FRC_NCO);
break;
default:
dev_err(codec->dev, "Unknown FLL source %d\n", ret);
return -EINVAL;
}
if (fll_div.theta || fll_div.lambda)
fll1 |= WM8962_FLL_FRAC;
/* Stop the FLL while we reconfigure */
snd_soc_update_bits(codec, WM8962_FLL_CONTROL_1, WM8962_FLL_ENA, 0);
snd_soc_update_bits(codec, WM8962_FLL_CONTROL_2,
WM8962_FLL_OUTDIV_MASK |
WM8962_FLL_REFCLK_DIV_MASK,
(fll_div.fll_outdiv << WM8962_FLL_OUTDIV_SHIFT) |
(fll_div.fll_refclk_div));
snd_soc_update_bits(codec, WM8962_FLL_CONTROL_3,
WM8962_FLL_FRATIO_MASK, fll_div.fll_fratio);
snd_soc_write(codec, WM8962_FLL_CONTROL_6, fll_div.theta);
snd_soc_write(codec, WM8962_FLL_CONTROL_7, fll_div.lambda);
snd_soc_write(codec, WM8962_FLL_CONTROL_8, fll_div.n);
reinit_completion(&wm8962->fll_lock);
ret = pm_runtime_get_sync(codec->dev);
if (ret < 0) {
dev_err(codec->dev, "Failed to resume device: %d\n", ret);
return ret;
}
snd_soc_update_bits(codec, WM8962_FLL_CONTROL_1,
WM8962_FLL_FRAC | WM8962_FLL_REFCLK_SRC_MASK |
WM8962_FLL_ENA, fll1 | WM8962_FLL_ENA);
dev_dbg(codec->dev, "FLL configured for %dHz->%dHz\n", Fref, Fout);
/* This should be a massive overestimate but go even
* higher if we'll error out
*/
if (wm8962->irq)
timeout = msecs_to_jiffies(5);
else
timeout = msecs_to_jiffies(1);
timeout = wait_for_completion_timeout(&wm8962->fll_lock,
timeout);
if (timeout == 0 && wm8962->irq) {
dev_err(codec->dev, "FLL lock timed out");
snd_soc_update_bits(codec, WM8962_FLL_CONTROL_1,
WM8962_FLL_ENA, 0);
pm_runtime_put(codec->dev);
return -ETIMEDOUT;
}
wm8962->fll_fref = Fref;
wm8962->fll_fout = Fout;
wm8962->fll_src = source;
return 0;
}
static int wm8962_mute(struct snd_soc_dai *dai, int mute)
{
struct snd_soc_codec *codec = dai->codec;
int val, ret;
if (mute)
val = WM8962_DAC_MUTE | WM8962_DAC_MUTE_ALT;
else
val = 0;
/**
* The DAC mute bit is mirrored in two registers, update both to keep
* the register cache consistent.
*/
ret = snd_soc_update_bits(codec, WM8962_CLASS_D_CONTROL_1,
WM8962_DAC_MUTE_ALT, val);
if (ret < 0)
return ret;
return snd_soc_update_bits(codec, WM8962_ADC_DAC_CONTROL_1,
WM8962_DAC_MUTE, val);
}
#define WM8962_RATES SNDRV_PCM_RATE_8000_96000
#define WM8962_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S20_3LE |\
SNDRV_PCM_FMTBIT_S24_LE | SNDRV_PCM_FMTBIT_S32_LE)
static const struct snd_soc_dai_ops wm8962_dai_ops = {
.hw_params = wm8962_hw_params,
.set_sysclk = wm8962_set_dai_sysclk,
.set_fmt = wm8962_set_dai_fmt,
.digital_mute = wm8962_mute,
};
static struct snd_soc_dai_driver wm8962_dai = {
.name = "wm8962",
.playback = {
.stream_name = "Playback",
.channels_min = 1,
.channels_max = 2,
.rates = WM8962_RATES,
.formats = WM8962_FORMATS,
},
.capture = {
.stream_name = "Capture",
.channels_min = 1,
.channels_max = 2,
.rates = WM8962_RATES,
.formats = WM8962_FORMATS,
},
.ops = &wm8962_dai_ops,
.symmetric_rates = 1,
};
static void wm8962_mic_work(struct work_struct *work)
{
struct wm8962_priv *wm8962 = container_of(work,
struct wm8962_priv,
mic_work.work);
struct snd_soc_codec *codec = wm8962->codec;
int status = 0;
int irq_pol = 0;
int reg;
reg = snd_soc_read(codec, WM8962_ADDITIONAL_CONTROL_4);
if (reg & WM8962_MICDET_STS) {
status |= SND_JACK_MICROPHONE;
irq_pol |= WM8962_MICD_IRQ_POL;
}
if (reg & WM8962_MICSHORT_STS) {
status |= SND_JACK_BTN_0;
irq_pol |= WM8962_MICSCD_IRQ_POL;
}
snd_soc_jack_report(wm8962->jack, status,
SND_JACK_MICROPHONE | SND_JACK_BTN_0);
snd_soc_update_bits(codec, WM8962_MICINT_SOURCE_POL,
WM8962_MICSCD_IRQ_POL |
WM8962_MICD_IRQ_POL, irq_pol);
}
static irqreturn_t wm8962_irq(int irq, void *data)
{
struct device *dev = data;
struct wm8962_priv *wm8962 = dev_get_drvdata(dev);
unsigned int mask;
unsigned int active;
int reg, ret;
ret = pm_runtime_get_sync(dev);
if (ret < 0) {
dev_err(dev, "Failed to resume: %d\n", ret);
return IRQ_NONE;
}
ret = regmap_read(wm8962->regmap, WM8962_INTERRUPT_STATUS_2_MASK,
&mask);
if (ret != 0) {
pm_runtime_put(dev);
dev_err(dev, "Failed to read interrupt mask: %d\n",
ret);
return IRQ_NONE;
}
ret = regmap_read(wm8962->regmap, WM8962_INTERRUPT_STATUS_2, &active);
if (ret != 0) {
pm_runtime_put(dev);
dev_err(dev, "Failed to read interrupt: %d\n", ret);
return IRQ_NONE;
}
active &= ~mask;
if (!active) {
pm_runtime_put(dev);
return IRQ_NONE;
}
/* Acknowledge the interrupts */
ret = regmap_write(wm8962->regmap, WM8962_INTERRUPT_STATUS_2, active);
if (ret != 0)
dev_warn(dev, "Failed to ack interrupt: %d\n", ret);
if (active & WM8962_FLL_LOCK_EINT) {
dev_dbg(dev, "FLL locked\n");
complete(&wm8962->fll_lock);
}
if (active & WM8962_FIFOS_ERR_EINT)
dev_err(dev, "FIFO error\n");
if (active & WM8962_TEMP_SHUT_EINT) {
dev_crit(dev, "Thermal shutdown\n");
ret = regmap_read(wm8962->regmap,
WM8962_THERMAL_SHUTDOWN_STATUS, ®);
if (ret != 0) {
dev_warn(dev, "Failed to read thermal status: %d\n",
ret);
reg = 0;
}
if (reg & WM8962_TEMP_ERR_HP)
dev_crit(dev, "Headphone thermal error\n");
if (reg & WM8962_TEMP_WARN_HP)
dev_crit(dev, "Headphone thermal warning\n");
if (reg & WM8962_TEMP_ERR_SPK)
dev_crit(dev, "Speaker thermal error\n");
if (reg & WM8962_TEMP_WARN_SPK)
dev_crit(dev, "Speaker thermal warning\n");
}
if (active & (WM8962_MICSCD_EINT | WM8962_MICD_EINT)) {
dev_dbg(dev, "Microphone event detected\n");
#ifndef CONFIG_SND_SOC_WM8962_MODULE
trace_snd_soc_jack_irq(dev_name(dev));
#endif
pm_wakeup_event(dev, 300);
queue_delayed_work(system_power_efficient_wq,
&wm8962->mic_work,
msecs_to_jiffies(250));
}
pm_runtime_put(dev);
return IRQ_HANDLED;
}
/**
* wm8962_mic_detect - Enable microphone detection via the WM8962 IRQ
*
* @codec: WM8962 codec
* @jack: jack to report detection events on
*
* Enable microphone detection via IRQ on the WM8962. If GPIOs are
* being used to bring out signals to the processor then only platform
* data configuration is needed for WM8962 and processor GPIOs should
* be configured using snd_soc_jack_add_gpios() instead.
*
* If no jack is supplied detection will be disabled.
*/
int wm8962_mic_detect(struct snd_soc_codec *codec, struct snd_soc_jack *jack)
{
struct wm8962_priv *wm8962 = snd_soc_codec_get_drvdata(codec);
struct snd_soc_dapm_context *dapm = &codec->dapm;
int irq_mask, enable;
wm8962->jack = jack;
if (jack) {
irq_mask = 0;
enable = WM8962_MICDET_ENA;
} else {
irq_mask = WM8962_MICD_EINT | WM8962_MICSCD_EINT;
enable = 0;
}
snd_soc_update_bits(codec, WM8962_INTERRUPT_STATUS_2_MASK,
WM8962_MICD_EINT | WM8962_MICSCD_EINT, irq_mask);
snd_soc_update_bits(codec, WM8962_ADDITIONAL_CONTROL_4,
WM8962_MICDET_ENA, enable);
/* Send an initial empty report */
snd_soc_jack_report(wm8962->jack, 0,
SND_JACK_MICROPHONE | SND_JACK_BTN_0);
snd_soc_dapm_mutex_lock(dapm);
if (jack) {
snd_soc_dapm_force_enable_pin_unlocked(dapm, "SYSCLK");
snd_soc_dapm_force_enable_pin_unlocked(dapm, "MICBIAS");
} else {
snd_soc_dapm_disable_pin_unlocked(dapm, "SYSCLK");
snd_soc_dapm_disable_pin_unlocked(dapm, "MICBIAS");
}
snd_soc_dapm_mutex_unlock(dapm);
return 0;
}
EXPORT_SYMBOL_GPL(wm8962_mic_detect);
static int beep_rates[] = {
500, 1000, 2000, 4000,
};
static void wm8962_beep_work(struct work_struct *work)
{
struct wm8962_priv *wm8962 =
container_of(work, struct wm8962_priv, beep_work);
struct snd_soc_codec *codec = wm8962->codec;
struct snd_soc_dapm_context *dapm = &codec->dapm;
int i;
int reg = 0;
int best = 0;
if (wm8962->beep_rate) {
for (i = 0; i < ARRAY_SIZE(beep_rates); i++) {
if (abs(wm8962->beep_rate - beep_rates[i]) <
abs(wm8962->beep_rate - beep_rates[best]))
best = i;
}
dev_dbg(codec->dev, "Set beep rate %dHz for requested %dHz\n",
beep_rates[best], wm8962->beep_rate);
reg = WM8962_BEEP_ENA | (best << WM8962_BEEP_RATE_SHIFT);
snd_soc_dapm_enable_pin(dapm, "Beep");
} else {
dev_dbg(codec->dev, "Disabling beep\n");
snd_soc_dapm_disable_pin(dapm, "Beep");
}
snd_soc_update_bits(codec, WM8962_BEEP_GENERATOR_1,
WM8962_BEEP_ENA | WM8962_BEEP_RATE_MASK, reg);
snd_soc_dapm_sync(dapm);
}
/* For usability define a way of injecting beep events for the device -
* many systems will not have a keyboard.
*/
static int wm8962_beep_event(struct input_dev *dev, unsigned int type,
unsigned int code, int hz)
{
struct snd_soc_codec *codec = input_get_drvdata(dev);
struct wm8962_priv *wm8962 = snd_soc_codec_get_drvdata(codec);
dev_dbg(codec->dev, "Beep event %x %x\n", code, hz);
switch (code) {
case SND_BELL:
if (hz)
hz = 1000;
case SND_TONE:
break;
default:
return -1;
}
/* Kick the beep from a workqueue */
wm8962->beep_rate = hz;
schedule_work(&wm8962->beep_work);
return 0;
}
static ssize_t wm8962_beep_set(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct wm8962_priv *wm8962 = dev_get_drvdata(dev);
long int time;
int ret;
ret = kstrtol(buf, 10, &time);
if (ret != 0)
return ret;
input_event(wm8962->beep, EV_SND, SND_TONE, time);
return count;
}
static DEVICE_ATTR(beep, 0200, NULL, wm8962_beep_set);
static void wm8962_init_beep(struct snd_soc_codec *codec)
{
struct wm8962_priv *wm8962 = snd_soc_codec_get_drvdata(codec);
int ret;
wm8962->beep = devm_input_allocate_device(codec->dev);
if (!wm8962->beep) {
dev_err(codec->dev, "Failed to allocate beep device\n");
return;
}
INIT_WORK(&wm8962->beep_work, wm8962_beep_work);
wm8962->beep_rate = 0;
wm8962->beep->name = "WM8962 Beep Generator";
wm8962->beep->phys = dev_name(codec->dev);
wm8962->beep->id.bustype = BUS_I2C;
wm8962->beep->evbit[0] = BIT_MASK(EV_SND);
wm8962->beep->sndbit[0] = BIT_MASK(SND_BELL) | BIT_MASK(SND_TONE);
wm8962->beep->event = wm8962_beep_event;
wm8962->beep->dev.parent = codec->dev;
input_set_drvdata(wm8962->beep, codec);
ret = input_register_device(wm8962->beep);
if (ret != 0) {
wm8962->beep = NULL;
dev_err(codec->dev, "Failed to register beep device\n");
}
ret = device_create_file(codec->dev, &dev_attr_beep);
if (ret != 0) {
dev_err(codec->dev, "Failed to create keyclick file: %d\n",
ret);
}
}
static void wm8962_free_beep(struct snd_soc_codec *codec)
{
struct wm8962_priv *wm8962 = snd_soc_codec_get_drvdata(codec);
device_remove_file(codec->dev, &dev_attr_beep);
cancel_work_sync(&wm8962->beep_work);
wm8962->beep = NULL;
snd_soc_update_bits(codec, WM8962_BEEP_GENERATOR_1, WM8962_BEEP_ENA,0);
}
static void wm8962_set_gpio_mode(struct wm8962_priv *wm8962, int gpio)
{
int mask = 0;
int val = 0;
/* Some of the GPIOs are behind MFP configuration and need to
* be put into GPIO mode. */
switch (gpio) {
case 2:
mask = WM8962_CLKOUT2_SEL_MASK;
val = 1 << WM8962_CLKOUT2_SEL_SHIFT;
break;
case 3:
mask = WM8962_CLKOUT3_SEL_MASK;
val = 1 << WM8962_CLKOUT3_SEL_SHIFT;
break;
default:
break;
}
if (mask)
regmap_update_bits(wm8962->regmap, WM8962_ANALOGUE_CLOCKING1,
mask, val);
}
#ifdef CONFIG_GPIOLIB
static inline struct wm8962_priv *gpio_to_wm8962(struct gpio_chip *chip)
{
return container_of(chip, struct wm8962_priv, gpio_chip);
}
static int wm8962_gpio_request(struct gpio_chip *chip, unsigned offset)
{
struct wm8962_priv *wm8962 = gpio_to_wm8962(chip);
/* The WM8962 GPIOs aren't linearly numbered. For simplicity
* we export linear numbers and error out if the unsupported
* ones are requsted.
*/
switch (offset + 1) {
case 2:
case 3:
case 5:
case 6:
break;
default:
return -EINVAL;
}
wm8962_set_gpio_mode(wm8962, offset + 1);
return 0;
}
static void wm8962_gpio_set(struct gpio_chip *chip, unsigned offset, int value)
{
struct wm8962_priv *wm8962 = gpio_to_wm8962(chip);
struct snd_soc_codec *codec = wm8962->codec;
snd_soc_update_bits(codec, WM8962_GPIO_BASE + offset,
WM8962_GP2_LVL, !!value << WM8962_GP2_LVL_SHIFT);
}
static int wm8962_gpio_direction_out(struct gpio_chip *chip,
unsigned offset, int value)
{
struct wm8962_priv *wm8962 = gpio_to_wm8962(chip);
struct snd_soc_codec *codec = wm8962->codec;
int ret, val;
/* Force function 1 (logic output) */
val = (1 << WM8962_GP2_FN_SHIFT) | (value << WM8962_GP2_LVL_SHIFT);
ret = snd_soc_update_bits(codec, WM8962_GPIO_BASE + offset,
WM8962_GP2_FN_MASK | WM8962_GP2_LVL, val);
if (ret < 0)
return ret;
return 0;
}
static struct gpio_chip wm8962_template_chip = {
.label = "wm8962",
.owner = THIS_MODULE,
.request = wm8962_gpio_request,
.direction_output = wm8962_gpio_direction_out,
.set = wm8962_gpio_set,
.can_sleep = 1,
};
static void wm8962_init_gpio(struct snd_soc_codec *codec)
{
struct wm8962_priv *wm8962 = snd_soc_codec_get_drvdata(codec);
struct wm8962_pdata *pdata = &wm8962->pdata;
int ret;
wm8962->gpio_chip = wm8962_template_chip;
wm8962->gpio_chip.ngpio = WM8962_MAX_GPIO;
wm8962->gpio_chip.dev = codec->dev;
if (pdata->gpio_base)
wm8962->gpio_chip.base = pdata->gpio_base;
else
wm8962->gpio_chip.base = -1;
ret = gpiochip_add(&wm8962->gpio_chip);
if (ret != 0)
dev_err(codec->dev, "Failed to add GPIOs: %d\n", ret);
}
static void wm8962_free_gpio(struct snd_soc_codec *codec)
{
struct wm8962_priv *wm8962 = snd_soc_codec_get_drvdata(codec);
gpiochip_remove(&wm8962->gpio_chip);
}
#else
static void wm8962_init_gpio(struct snd_soc_codec *codec)
{
}
static void wm8962_free_gpio(struct snd_soc_codec *codec)
{
}
#endif
static int wm8962_probe(struct snd_soc_codec *codec)
{
int ret;
struct wm8962_priv *wm8962 = snd_soc_codec_get_drvdata(codec);
int i;
bool dmicclk, dmicdat;
wm8962->codec = codec;
wm8962->disable_nb[0].notifier_call = wm8962_regulator_event_0;
wm8962->disable_nb[1].notifier_call = wm8962_regulator_event_1;
wm8962->disable_nb[2].notifier_call = wm8962_regulator_event_2;
wm8962->disable_nb[3].notifier_call = wm8962_regulator_event_3;
wm8962->disable_nb[4].notifier_call = wm8962_regulator_event_4;
wm8962->disable_nb[5].notifier_call = wm8962_regulator_event_5;
wm8962->disable_nb[6].notifier_call = wm8962_regulator_event_6;
wm8962->disable_nb[7].notifier_call = wm8962_regulator_event_7;
/* This should really be moved into the regulator core */
for (i = 0; i < ARRAY_SIZE(wm8962->supplies); i++) {
ret = regulator_register_notifier(wm8962->supplies[i].consumer,
&wm8962->disable_nb[i]);
if (ret != 0) {
dev_err(codec->dev,
"Failed to register regulator notifier: %d\n",
ret);
}
}
wm8962_add_widgets(codec);
/* Save boards having to disable DMIC when not in use */
dmicclk = false;
dmicdat = false;
for (i = 0; i < WM8962_MAX_GPIO; i++) {
switch (snd_soc_read(codec, WM8962_GPIO_BASE + i)
& WM8962_GP2_FN_MASK) {
case WM8962_GPIO_FN_DMICCLK:
dmicclk = true;
break;
case WM8962_GPIO_FN_DMICDAT:
dmicdat = true;
break;
default:
break;
}
}
if (!dmicclk || !dmicdat) {
dev_dbg(codec->dev, "DMIC not in use, disabling\n");
snd_soc_dapm_nc_pin(&codec->dapm, "DMICDAT");
}
if (dmicclk != dmicdat)
dev_warn(codec->dev, "DMIC GPIOs partially configured\n");
wm8962_init_beep(codec);
wm8962_init_gpio(codec);
return 0;
}
static int wm8962_remove(struct snd_soc_codec *codec)
{
struct wm8962_priv *wm8962 = snd_soc_codec_get_drvdata(codec);
int i;
cancel_delayed_work_sync(&wm8962->mic_work);
wm8962_free_gpio(codec);
wm8962_free_beep(codec);
for (i = 0; i < ARRAY_SIZE(wm8962->supplies); i++)
regulator_unregister_notifier(wm8962->supplies[i].consumer,
&wm8962->disable_nb[i]);
return 0;
}
static struct snd_soc_codec_driver soc_codec_dev_wm8962 = {
.probe = wm8962_probe,
.remove = wm8962_remove,
.set_bias_level = wm8962_set_bias_level,
.set_pll = wm8962_set_fll,
.idle_bias_off = true,
};
/* Improve power consumption for IN4 DC measurement mode */
static const struct reg_default wm8962_dc_measure[] = {
{ 0xfd, 0x1 },
{ 0xcc, 0x40 },
{ 0xfd, 0 },
};
static const struct regmap_config wm8962_regmap = {
.reg_bits = 16,
.val_bits = 16,
.max_register = WM8962_MAX_REGISTER,
.reg_defaults = wm8962_reg,
.num_reg_defaults = ARRAY_SIZE(wm8962_reg),
.volatile_reg = wm8962_volatile_register,
.readable_reg = wm8962_readable_register,
.cache_type = REGCACHE_RBTREE,
};
static int wm8962_set_pdata_from_of(struct i2c_client *i2c,
struct wm8962_pdata *pdata)
{
const struct device_node *np = i2c->dev.of_node;
u32 val32;
int i;
if (of_property_read_bool(np, "spk-mono"))
pdata->spk_mono = true;
if (of_property_read_u32(np, "mic-cfg", &val32) >= 0)
pdata->mic_cfg = val32;
if (of_property_read_u32_array(np, "gpio-cfg", pdata->gpio_init,
ARRAY_SIZE(pdata->gpio_init)) >= 0)
for (i = 0; i < ARRAY_SIZE(pdata->gpio_init); i++) {
/*
* The range of GPIO register value is [0x0, 0xffff]
* While the default value of each register is 0x0
* Any other value will be regarded as default value
*/
if (pdata->gpio_init[i] > 0xffff)
pdata->gpio_init[i] = 0x0;
}
pdata->mclk = devm_clk_get(&i2c->dev, NULL);
return 0;
}
static int wm8962_i2c_probe(struct i2c_client *i2c,
const struct i2c_device_id *id)
{
struct wm8962_pdata *pdata = dev_get_platdata(&i2c->dev);
struct wm8962_priv *wm8962;
unsigned int reg;
int ret, i, irq_pol, trigger;
wm8962 = devm_kzalloc(&i2c->dev, sizeof(*wm8962), GFP_KERNEL);
if (wm8962 == NULL)
return -ENOMEM;
mutex_init(&wm8962->dsp2_ena_lock);
i2c_set_clientdata(i2c, wm8962);
INIT_DELAYED_WORK(&wm8962->mic_work, wm8962_mic_work);
init_completion(&wm8962->fll_lock);
wm8962->irq = i2c->irq;
/* If platform data was supplied, update the default data in priv */
if (pdata) {
memcpy(&wm8962->pdata, pdata, sizeof(struct wm8962_pdata));
} else if (i2c->dev.of_node) {
ret = wm8962_set_pdata_from_of(i2c, &wm8962->pdata);
if (ret != 0)
return ret;
}
/* Mark the mclk pointer to NULL if no mclk assigned */
if (IS_ERR(wm8962->pdata.mclk)) {
/* But do not ignore the request for probe defer */
if (PTR_ERR(wm8962->pdata.mclk) == -EPROBE_DEFER)
return -EPROBE_DEFER;
wm8962->pdata.mclk = NULL;
}
for (i = 0; i < ARRAY_SIZE(wm8962->supplies); i++)
wm8962->supplies[i].supply = wm8962_supply_names[i];
ret = devm_regulator_bulk_get(&i2c->dev, ARRAY_SIZE(wm8962->supplies),
wm8962->supplies);
if (ret != 0) {
dev_err(&i2c->dev, "Failed to request supplies: %d\n", ret);
goto err;
}
ret = regulator_bulk_enable(ARRAY_SIZE(wm8962->supplies),
wm8962->supplies);
if (ret != 0) {
dev_err(&i2c->dev, "Failed to enable supplies: %d\n", ret);
return ret;
}
wm8962->regmap = devm_regmap_init_i2c(i2c, &wm8962_regmap);
if (IS_ERR(wm8962->regmap)) {
ret = PTR_ERR(wm8962->regmap);
dev_err(&i2c->dev, "Failed to allocate regmap: %d\n", ret);
goto err_enable;
}
/*
* We haven't marked the chip revision as volatile due to
* sharing a register with the right input volume; explicitly
* bypass the cache to read it.
*/
regcache_cache_bypass(wm8962->regmap, true);
ret = regmap_read(wm8962->regmap, WM8962_SOFTWARE_RESET, ®);
if (ret < 0) {
dev_err(&i2c->dev, "Failed to read ID register\n");
goto err_enable;
}
if (reg != 0x6243) {
dev_err(&i2c->dev,
"Device is not a WM8962, ID %x != 0x6243\n", reg);
ret = -EINVAL;
goto err_enable;
}
ret = regmap_read(wm8962->regmap, WM8962_RIGHT_INPUT_VOLUME, ®);
if (ret < 0) {
dev_err(&i2c->dev, "Failed to read device revision: %d\n",
ret);
goto err_enable;
}
dev_info(&i2c->dev, "customer id %x revision %c\n",
(reg & WM8962_CUST_ID_MASK) >> WM8962_CUST_ID_SHIFT,
((reg & WM8962_CHIP_REV_MASK) >> WM8962_CHIP_REV_SHIFT)
+ 'A');
regcache_cache_bypass(wm8962->regmap, false);
ret = wm8962_reset(wm8962);
if (ret < 0) {
dev_err(&i2c->dev, "Failed to issue reset\n");
goto err_enable;
}
/* SYSCLK defaults to on; make sure it is off so we can safely
* write to registers if the device is declocked.
*/
regmap_update_bits(wm8962->regmap, WM8962_CLOCKING2,
WM8962_SYSCLK_ENA, 0);
/* Ensure we have soft control over all registers */
regmap_update_bits(wm8962->regmap, WM8962_CLOCKING2,
WM8962_CLKREG_OVD, WM8962_CLKREG_OVD);
/* Ensure that the oscillator and PLLs are disabled */
regmap_update_bits(wm8962->regmap, WM8962_PLL2,
WM8962_OSC_ENA | WM8962_PLL2_ENA | WM8962_PLL3_ENA,
0);
/* Apply static configuration for GPIOs */
for (i = 0; i < ARRAY_SIZE(wm8962->pdata.gpio_init); i++)
if (wm8962->pdata.gpio_init[i]) {
wm8962_set_gpio_mode(wm8962, i + 1);
regmap_write(wm8962->regmap, 0x200 + i,
wm8962->pdata.gpio_init[i] & 0xffff);
}
/* Put the speakers into mono mode? */
if (wm8962->pdata.spk_mono)
regmap_update_bits(wm8962->regmap, WM8962_CLASS_D_CONTROL_2,
WM8962_SPK_MONO_MASK, WM8962_SPK_MONO);
/* Micbias setup, detection enable and detection
* threasholds. */
if (wm8962->pdata.mic_cfg)
regmap_update_bits(wm8962->regmap, WM8962_ADDITIONAL_CONTROL_4,
WM8962_MICDET_ENA |
WM8962_MICDET_THR_MASK |
WM8962_MICSHORT_THR_MASK |
WM8962_MICBIAS_LVL,
wm8962->pdata.mic_cfg);
/* Latch volume update bits */
regmap_update_bits(wm8962->regmap, WM8962_LEFT_INPUT_VOLUME,
WM8962_IN_VU, WM8962_IN_VU);
regmap_update_bits(wm8962->regmap, WM8962_RIGHT_INPUT_VOLUME,
WM8962_IN_VU, WM8962_IN_VU);
regmap_update_bits(wm8962->regmap, WM8962_LEFT_ADC_VOLUME,
WM8962_ADC_VU, WM8962_ADC_VU);
regmap_update_bits(wm8962->regmap, WM8962_RIGHT_ADC_VOLUME,
WM8962_ADC_VU, WM8962_ADC_VU);
regmap_update_bits(wm8962->regmap, WM8962_LEFT_DAC_VOLUME,
WM8962_DAC_VU, WM8962_DAC_VU);
regmap_update_bits(wm8962->regmap, WM8962_RIGHT_DAC_VOLUME,
WM8962_DAC_VU, WM8962_DAC_VU);
regmap_update_bits(wm8962->regmap, WM8962_SPKOUTL_VOLUME,
WM8962_SPKOUT_VU, WM8962_SPKOUT_VU);
regmap_update_bits(wm8962->regmap, WM8962_SPKOUTR_VOLUME,
WM8962_SPKOUT_VU, WM8962_SPKOUT_VU);
regmap_update_bits(wm8962->regmap, WM8962_HPOUTL_VOLUME,
WM8962_HPOUT_VU, WM8962_HPOUT_VU);
regmap_update_bits(wm8962->regmap, WM8962_HPOUTR_VOLUME,
WM8962_HPOUT_VU, WM8962_HPOUT_VU);
/* Stereo control for EQ */
regmap_update_bits(wm8962->regmap, WM8962_EQ1,
WM8962_EQ_SHARED_COEFF, 0);
/* Don't debouce interrupts so we don't need SYSCLK */
regmap_update_bits(wm8962->regmap, WM8962_IRQ_DEBOUNCE,
WM8962_FLL_LOCK_DB | WM8962_PLL3_LOCK_DB |
WM8962_PLL2_LOCK_DB | WM8962_TEMP_SHUT_DB,
0);
if (wm8962->pdata.in4_dc_measure) {
ret = regmap_register_patch(wm8962->regmap,
wm8962_dc_measure,
ARRAY_SIZE(wm8962_dc_measure));
if (ret != 0)
dev_err(&i2c->dev,
"Failed to configure for DC mesurement: %d\n",
ret);
}
if (wm8962->irq) {
if (wm8962->pdata.irq_active_low) {
trigger = IRQF_TRIGGER_LOW;
irq_pol = WM8962_IRQ_POL;
} else {
trigger = IRQF_TRIGGER_HIGH;
irq_pol = 0;
}
regmap_update_bits(wm8962->regmap, WM8962_INTERRUPT_CONTROL,
WM8962_IRQ_POL, irq_pol);
ret = devm_request_threaded_irq(&i2c->dev, wm8962->irq, NULL,
wm8962_irq,
trigger | IRQF_ONESHOT,
"wm8962", &i2c->dev);
if (ret != 0) {
dev_err(&i2c->dev, "Failed to request IRQ %d: %d\n",
wm8962->irq, ret);
wm8962->irq = 0;
/* Non-fatal */
} else {
/* Enable some IRQs by default */
regmap_update_bits(wm8962->regmap,
WM8962_INTERRUPT_STATUS_2_MASK,
WM8962_FLL_LOCK_EINT |
WM8962_TEMP_SHUT_EINT |
WM8962_FIFOS_ERR_EINT, 0);
}
}
pm_runtime_enable(&i2c->dev);
pm_request_idle(&i2c->dev);
ret = snd_soc_register_codec(&i2c->dev,
&soc_codec_dev_wm8962, &wm8962_dai, 1);
if (ret < 0)
goto err_enable;
regcache_cache_only(wm8962->regmap, true);
/* The drivers should power up as needed */
regulator_bulk_disable(ARRAY_SIZE(wm8962->supplies), wm8962->supplies);
return 0;
err_enable:
regulator_bulk_disable(ARRAY_SIZE(wm8962->supplies), wm8962->supplies);
err:
return ret;
}
static int wm8962_i2c_remove(struct i2c_client *client)
{
snd_soc_unregister_codec(&client->dev);
return 0;
}
#ifdef CONFIG_PM
static int wm8962_runtime_resume(struct device *dev)
{
struct wm8962_priv *wm8962 = dev_get_drvdata(dev);
int ret;
ret = clk_prepare_enable(wm8962->pdata.mclk);
if (ret) {
dev_err(dev, "Failed to enable MCLK: %d\n", ret);
return ret;
}
ret = regulator_bulk_enable(ARRAY_SIZE(wm8962->supplies),
wm8962->supplies);
if (ret != 0) {
dev_err(dev,
"Failed to enable supplies: %d\n", ret);
return ret;
}
regcache_cache_only(wm8962->regmap, false);
wm8962_reset(wm8962);
/* SYSCLK defaults to on; make sure it is off so we can safely
* write to registers if the device is declocked.
*/
regmap_update_bits(wm8962->regmap, WM8962_CLOCKING2,
WM8962_SYSCLK_ENA, 0);
/* Ensure we have soft control over all registers */
regmap_update_bits(wm8962->regmap, WM8962_CLOCKING2,
WM8962_CLKREG_OVD, WM8962_CLKREG_OVD);
/* Ensure that the oscillator and PLLs are disabled */
regmap_update_bits(wm8962->regmap, WM8962_PLL2,
WM8962_OSC_ENA | WM8962_PLL2_ENA | WM8962_PLL3_ENA,
0);
regcache_sync(wm8962->regmap);
regmap_update_bits(wm8962->regmap, WM8962_ANTI_POP,
WM8962_STARTUP_BIAS_ENA | WM8962_VMID_BUF_ENA,
WM8962_STARTUP_BIAS_ENA | WM8962_VMID_BUF_ENA);
/* Bias enable at 2*5k (fast start-up) */
regmap_update_bits(wm8962->regmap, WM8962_PWR_MGMT_1,
WM8962_BIAS_ENA | WM8962_VMID_SEL_MASK,
WM8962_BIAS_ENA | 0x180);
msleep(5);
return 0;
}
static int wm8962_runtime_suspend(struct device *dev)
{
struct wm8962_priv *wm8962 = dev_get_drvdata(dev);
regmap_update_bits(wm8962->regmap, WM8962_PWR_MGMT_1,
WM8962_VMID_SEL_MASK | WM8962_BIAS_ENA, 0);
regmap_update_bits(wm8962->regmap, WM8962_ANTI_POP,
WM8962_STARTUP_BIAS_ENA |
WM8962_VMID_BUF_ENA, 0);
regcache_cache_only(wm8962->regmap, true);
regulator_bulk_disable(ARRAY_SIZE(wm8962->supplies),
wm8962->supplies);
clk_disable_unprepare(wm8962->pdata.mclk);
return 0;
}
#endif
static struct dev_pm_ops wm8962_pm = {
SET_RUNTIME_PM_OPS(wm8962_runtime_suspend, wm8962_runtime_resume, NULL)
};
static const struct i2c_device_id wm8962_i2c_id[] = {
{ "wm8962", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, wm8962_i2c_id);
static const struct of_device_id wm8962_of_match[] = {
{ .compatible = "wlf,wm8962", },
{ }
};
MODULE_DEVICE_TABLE(of, wm8962_of_match);
static struct i2c_driver wm8962_i2c_driver = {
.driver = {
.name = "wm8962",
.owner = THIS_MODULE,
.of_match_table = wm8962_of_match,
.pm = &wm8962_pm,
},
.probe = wm8962_i2c_probe,
.remove = wm8962_i2c_remove,
.id_table = wm8962_i2c_id,
};
module_i2c_driver(wm8962_i2c_driver);
MODULE_DESCRIPTION("ASoC WM8962 driver");
MODULE_AUTHOR("Mark Brown <broonie@opensource.wolfsonmicro.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
MoKee/android_kernel_motorola_apq8084 | drivers/mtd/ubi/debug.c | 2369 | 12841 | /*
* Copyright (c) International Business Machines Corp., 2006
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Artem Bityutskiy (Битюцкий Артём)
*/
#include "ubi.h"
#include <linux/debugfs.h>
#include <linux/uaccess.h>
#include <linux/module.h>
/**
* ubi_dump_flash - dump a region of flash.
* @ubi: UBI device description object
* @pnum: the physical eraseblock number to dump
* @offset: the starting offset within the physical eraseblock to dump
* @len: the length of the region to dump
*/
void ubi_dump_flash(struct ubi_device *ubi, int pnum, int offset, int len)
{
int err;
size_t read;
void *buf;
loff_t addr = (loff_t)pnum * ubi->peb_size + offset;
buf = vmalloc(len);
if (!buf)
return;
err = mtd_read(ubi->mtd, addr, len, &read, buf);
if (err && err != -EUCLEAN) {
ubi_err("error %d while reading %d bytes from PEB %d:%d, read %zd bytes",
err, len, pnum, offset, read);
goto out;
}
ubi_msg("dumping %d bytes of data from PEB %d, offset %d",
len, pnum, offset);
print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET, 32, 1, buf, len, 1);
out:
vfree(buf);
return;
}
/**
* ubi_dump_ec_hdr - dump an erase counter header.
* @ec_hdr: the erase counter header to dump
*/
void ubi_dump_ec_hdr(const struct ubi_ec_hdr *ec_hdr)
{
pr_err("Erase counter header dump:\n");
pr_err("\tmagic %#08x\n", be32_to_cpu(ec_hdr->magic));
pr_err("\tversion %d\n", (int)ec_hdr->version);
pr_err("\tec %llu\n", (long long)be64_to_cpu(ec_hdr->ec));
pr_err("\tvid_hdr_offset %d\n", be32_to_cpu(ec_hdr->vid_hdr_offset));
pr_err("\tdata_offset %d\n", be32_to_cpu(ec_hdr->data_offset));
pr_err("\timage_seq %d\n", be32_to_cpu(ec_hdr->image_seq));
pr_err("\thdr_crc %#08x\n", be32_to_cpu(ec_hdr->hdr_crc));
pr_err("erase counter header hexdump:\n");
print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET, 32, 1,
ec_hdr, UBI_EC_HDR_SIZE, 1);
}
/**
* ubi_dump_vid_hdr - dump a volume identifier header.
* @vid_hdr: the volume identifier header to dump
*/
void ubi_dump_vid_hdr(const struct ubi_vid_hdr *vid_hdr)
{
pr_err("Volume identifier header dump:\n");
pr_err("\tmagic %08x\n", be32_to_cpu(vid_hdr->magic));
pr_err("\tversion %d\n", (int)vid_hdr->version);
pr_err("\tvol_type %d\n", (int)vid_hdr->vol_type);
pr_err("\tcopy_flag %d\n", (int)vid_hdr->copy_flag);
pr_err("\tcompat %d\n", (int)vid_hdr->compat);
pr_err("\tvol_id %d\n", be32_to_cpu(vid_hdr->vol_id));
pr_err("\tlnum %d\n", be32_to_cpu(vid_hdr->lnum));
pr_err("\tdata_size %d\n", be32_to_cpu(vid_hdr->data_size));
pr_err("\tused_ebs %d\n", be32_to_cpu(vid_hdr->used_ebs));
pr_err("\tdata_pad %d\n", be32_to_cpu(vid_hdr->data_pad));
pr_err("\tsqnum %llu\n",
(unsigned long long)be64_to_cpu(vid_hdr->sqnum));
pr_err("\thdr_crc %08x\n", be32_to_cpu(vid_hdr->hdr_crc));
pr_err("Volume identifier header hexdump:\n");
print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET, 32, 1,
vid_hdr, UBI_VID_HDR_SIZE, 1);
}
/**
* ubi_dump_vol_info - dump volume information.
* @vol: UBI volume description object
*/
void ubi_dump_vol_info(const struct ubi_volume *vol)
{
pr_err("Volume information dump:\n");
pr_err("\tvol_id %d\n", vol->vol_id);
pr_err("\treserved_pebs %d\n", vol->reserved_pebs);
pr_err("\talignment %d\n", vol->alignment);
pr_err("\tdata_pad %d\n", vol->data_pad);
pr_err("\tvol_type %d\n", vol->vol_type);
pr_err("\tname_len %d\n", vol->name_len);
pr_err("\tusable_leb_size %d\n", vol->usable_leb_size);
pr_err("\tused_ebs %d\n", vol->used_ebs);
pr_err("\tused_bytes %lld\n", vol->used_bytes);
pr_err("\tlast_eb_bytes %d\n", vol->last_eb_bytes);
pr_err("\tcorrupted %d\n", vol->corrupted);
pr_err("\tupd_marker %d\n", vol->upd_marker);
if (vol->name_len <= UBI_VOL_NAME_MAX &&
strnlen(vol->name, vol->name_len + 1) == vol->name_len) {
pr_err("\tname %s\n", vol->name);
} else {
pr_err("\t1st 5 characters of name: %c%c%c%c%c\n",
vol->name[0], vol->name[1], vol->name[2],
vol->name[3], vol->name[4]);
}
}
/**
* ubi_dump_vtbl_record - dump a &struct ubi_vtbl_record object.
* @r: the object to dump
* @idx: volume table index
*/
void ubi_dump_vtbl_record(const struct ubi_vtbl_record *r, int idx)
{
int name_len = be16_to_cpu(r->name_len);
pr_err("Volume table record %d dump:\n", idx);
pr_err("\treserved_pebs %d\n", be32_to_cpu(r->reserved_pebs));
pr_err("\talignment %d\n", be32_to_cpu(r->alignment));
pr_err("\tdata_pad %d\n", be32_to_cpu(r->data_pad));
pr_err("\tvol_type %d\n", (int)r->vol_type);
pr_err("\tupd_marker %d\n", (int)r->upd_marker);
pr_err("\tname_len %d\n", name_len);
if (r->name[0] == '\0') {
pr_err("\tname NULL\n");
return;
}
if (name_len <= UBI_VOL_NAME_MAX &&
strnlen(&r->name[0], name_len + 1) == name_len) {
pr_err("\tname %s\n", &r->name[0]);
} else {
pr_err("\t1st 5 characters of name: %c%c%c%c%c\n",
r->name[0], r->name[1], r->name[2], r->name[3],
r->name[4]);
}
pr_err("\tcrc %#08x\n", be32_to_cpu(r->crc));
}
/**
* ubi_dump_av - dump a &struct ubi_ainf_volume object.
* @av: the object to dump
*/
void ubi_dump_av(const struct ubi_ainf_volume *av)
{
pr_err("Volume attaching information dump:\n");
pr_err("\tvol_id %d\n", av->vol_id);
pr_err("\thighest_lnum %d\n", av->highest_lnum);
pr_err("\tleb_count %d\n", av->leb_count);
pr_err("\tcompat %d\n", av->compat);
pr_err("\tvol_type %d\n", av->vol_type);
pr_err("\tused_ebs %d\n", av->used_ebs);
pr_err("\tlast_data_size %d\n", av->last_data_size);
pr_err("\tdata_pad %d\n", av->data_pad);
}
/**
* ubi_dump_aeb - dump a &struct ubi_ainf_peb object.
* @aeb: the object to dump
* @type: object type: 0 - not corrupted, 1 - corrupted
*/
void ubi_dump_aeb(const struct ubi_ainf_peb *aeb, int type)
{
pr_err("eraseblock attaching information dump:\n");
pr_err("\tec %d\n", aeb->ec);
pr_err("\tpnum %d\n", aeb->pnum);
if (type == 0) {
pr_err("\tlnum %d\n", aeb->lnum);
pr_err("\tscrub %d\n", aeb->scrub);
pr_err("\tsqnum %llu\n", aeb->sqnum);
}
}
/**
* ubi_dump_mkvol_req - dump a &struct ubi_mkvol_req object.
* @req: the object to dump
*/
void ubi_dump_mkvol_req(const struct ubi_mkvol_req *req)
{
char nm[17];
pr_err("Volume creation request dump:\n");
pr_err("\tvol_id %d\n", req->vol_id);
pr_err("\talignment %d\n", req->alignment);
pr_err("\tbytes %lld\n", (long long)req->bytes);
pr_err("\tvol_type %d\n", req->vol_type);
pr_err("\tname_len %d\n", req->name_len);
memcpy(nm, req->name, 16);
nm[16] = 0;
pr_err("\t1st 16 characters of name: %s\n", nm);
}
/*
* Root directory for UBI stuff in debugfs. Contains sub-directories which
* contain the stuff specific to particular UBI devices.
*/
static struct dentry *dfs_rootdir;
/**
* ubi_debugfs_init - create UBI debugfs directory.
*
* Create UBI debugfs directory. Returns zero in case of success and a negative
* error code in case of failure.
*/
int ubi_debugfs_init(void)
{
if (!IS_ENABLED(CONFIG_DEBUG_FS))
return 0;
dfs_rootdir = debugfs_create_dir("ubi", NULL);
if (IS_ERR_OR_NULL(dfs_rootdir)) {
int err = dfs_rootdir ? -ENODEV : PTR_ERR(dfs_rootdir);
ubi_err("cannot create \"ubi\" debugfs directory, error %d\n",
err);
return err;
}
return 0;
}
/**
* ubi_debugfs_exit - remove UBI debugfs directory.
*/
void ubi_debugfs_exit(void)
{
if (IS_ENABLED(CONFIG_DEBUG_FS))
debugfs_remove(dfs_rootdir);
}
/* Read an UBI debugfs file */
static ssize_t dfs_file_read(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
unsigned long ubi_num = (unsigned long)file->private_data;
struct dentry *dent = file->f_path.dentry;
struct ubi_device *ubi;
struct ubi_debug_info *d;
char buf[3];
int val;
ubi = ubi_get_device(ubi_num);
if (!ubi)
return -ENODEV;
d = &ubi->dbg;
if (dent == d->dfs_chk_gen)
val = d->chk_gen;
else if (dent == d->dfs_chk_io)
val = d->chk_io;
else if (dent == d->dfs_disable_bgt)
val = d->disable_bgt;
else if (dent == d->dfs_emulate_bitflips)
val = d->emulate_bitflips;
else if (dent == d->dfs_emulate_io_failures)
val = d->emulate_io_failures;
else {
count = -EINVAL;
goto out;
}
if (val)
buf[0] = '1';
else
buf[0] = '0';
buf[1] = '\n';
buf[2] = 0x00;
count = simple_read_from_buffer(user_buf, count, ppos, buf, 2);
out:
ubi_put_device(ubi);
return count;
}
/* Write an UBI debugfs file */
static ssize_t dfs_file_write(struct file *file, const char __user *user_buf,
size_t count, loff_t *ppos)
{
unsigned long ubi_num = (unsigned long)file->private_data;
struct dentry *dent = file->f_path.dentry;
struct ubi_device *ubi;
struct ubi_debug_info *d;
size_t buf_size;
char buf[8];
int val;
ubi = ubi_get_device(ubi_num);
if (!ubi)
return -ENODEV;
d = &ubi->dbg;
buf_size = min_t(size_t, count, (sizeof(buf) - 1));
if (copy_from_user(buf, user_buf, buf_size)) {
count = -EFAULT;
goto out;
}
if (buf[0] == '1')
val = 1;
else if (buf[0] == '0')
val = 0;
else {
count = -EINVAL;
goto out;
}
if (dent == d->dfs_chk_gen)
d->chk_gen = val;
else if (dent == d->dfs_chk_io)
d->chk_io = val;
else if (dent == d->dfs_disable_bgt)
d->disable_bgt = val;
else if (dent == d->dfs_emulate_bitflips)
d->emulate_bitflips = val;
else if (dent == d->dfs_emulate_io_failures)
d->emulate_io_failures = val;
else
count = -EINVAL;
out:
ubi_put_device(ubi);
return count;
}
/* File operations for all UBI debugfs files */
static const struct file_operations dfs_fops = {
.read = dfs_file_read,
.write = dfs_file_write,
.open = simple_open,
.llseek = no_llseek,
.owner = THIS_MODULE,
};
/**
* ubi_debugfs_init_dev - initialize debugfs for an UBI device.
* @ubi: UBI device description object
*
* This function creates all debugfs files for UBI device @ubi. Returns zero in
* case of success and a negative error code in case of failure.
*/
int ubi_debugfs_init_dev(struct ubi_device *ubi)
{
int err, n;
unsigned long ubi_num = ubi->ubi_num;
const char *fname;
struct dentry *dent;
struct ubi_debug_info *d = &ubi->dbg;
if (!IS_ENABLED(CONFIG_DEBUG_FS))
return 0;
n = snprintf(d->dfs_dir_name, UBI_DFS_DIR_LEN + 1, UBI_DFS_DIR_NAME,
ubi->ubi_num);
if (n == UBI_DFS_DIR_LEN) {
/* The array size is too small */
fname = UBI_DFS_DIR_NAME;
dent = ERR_PTR(-EINVAL);
goto out;
}
fname = d->dfs_dir_name;
dent = debugfs_create_dir(fname, dfs_rootdir);
if (IS_ERR_OR_NULL(dent))
goto out;
d->dfs_dir = dent;
fname = "chk_gen";
dent = debugfs_create_file(fname, S_IWUSR, d->dfs_dir, (void *)ubi_num,
&dfs_fops);
if (IS_ERR_OR_NULL(dent))
goto out_remove;
d->dfs_chk_gen = dent;
fname = "chk_io";
dent = debugfs_create_file(fname, S_IWUSR, d->dfs_dir, (void *)ubi_num,
&dfs_fops);
if (IS_ERR_OR_NULL(dent))
goto out_remove;
d->dfs_chk_io = dent;
fname = "tst_disable_bgt";
dent = debugfs_create_file(fname, S_IWUSR, d->dfs_dir, (void *)ubi_num,
&dfs_fops);
if (IS_ERR_OR_NULL(dent))
goto out_remove;
d->dfs_disable_bgt = dent;
fname = "tst_emulate_bitflips";
dent = debugfs_create_file(fname, S_IWUSR, d->dfs_dir, (void *)ubi_num,
&dfs_fops);
if (IS_ERR_OR_NULL(dent))
goto out_remove;
d->dfs_emulate_bitflips = dent;
fname = "tst_emulate_io_failures";
dent = debugfs_create_file(fname, S_IWUSR, d->dfs_dir, (void *)ubi_num,
&dfs_fops);
if (IS_ERR_OR_NULL(dent))
goto out_remove;
d->dfs_emulate_io_failures = dent;
return 0;
out_remove:
debugfs_remove_recursive(d->dfs_dir);
out:
err = dent ? PTR_ERR(dent) : -ENODEV;
ubi_err("cannot create \"%s\" debugfs file or directory, error %d\n",
fname, err);
return err;
}
/**
* dbg_debug_exit_dev - free all debugfs files corresponding to device @ubi
* @ubi: UBI device description object
*/
void ubi_debugfs_exit_dev(struct ubi_device *ubi)
{
if (IS_ENABLED(CONFIG_DEBUG_FS))
debugfs_remove_recursive(ubi->dbg.dfs_dir);
}
| gpl-2.0 |
kgp700/nexroid-sgs4ltea-kk | drivers/video/msm/mdp_ppp31.c | 3649 | 8511 | /* drivers/video/msm/mdp_ppp31.c
*
* Copyright (C) 2009 The Linux Foundation. All rights reserved.
* Copyright (C) 2009 Google Incorporated
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/errno.h>
#include <linux/kernel.h>
#include <asm/io.h>
#include <linux/msm_mdp.h>
#include "mdp_hw.h"
#include "mdp_ppp.h"
#define NUM_COEFFS 32
struct mdp_scale_coeffs {
uint16_t c[4][NUM_COEFFS];
};
struct mdp_scale_tbl_info {
uint16_t offset;
uint32_t set:2;
int use_pr;
struct mdp_scale_coeffs coeffs;
};
enum {
MDP_SCALE_PT2TOPT4,
MDP_SCALE_PT4TOPT6,
MDP_SCALE_PT6TOPT8,
MDP_SCALE_PT8TO8,
MDP_SCALE_MAX,
};
static struct mdp_scale_coeffs mdp_scale_pr_coeffs = {
.c = {
[0] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
},
[1] = {
511, 511, 511, 511, 511, 511, 511, 511,
511, 511, 511, 511, 511, 511, 511, 511,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
},
[2] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
511, 511, 511, 511, 511, 511, 511, 511,
511, 511, 511, 511, 511, 511, 511, 511,
},
[3] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
},
},
};
static struct mdp_scale_tbl_info mdp_scale_tbl[MDP_SCALE_MAX] = {
[ MDP_SCALE_PT2TOPT4 ] = {
.offset = 0,
.set = MDP_PPP_SCALE_COEFF_D0_SET,
.use_pr = -1,
.coeffs.c = {
[0] = {
131, 131, 130, 129, 128, 127, 127, 126,
125, 125, 124, 123, 123, 121, 120, 119,
119, 118, 117, 117, 116, 115, 115, 114,
113, 112, 111, 110, 109, 109, 108, 107,
},
[1] = {
141, 140, 140, 140, 140, 139, 138, 138,
138, 137, 137, 137, 136, 137, 137, 137,
136, 136, 136, 135, 135, 135, 134, 134,
134, 134, 134, 133, 133, 132, 132, 132,
},
[2] = {
132, 132, 132, 133, 133, 134, 134, 134,
134, 134, 135, 135, 135, 136, 136, 136,
137, 137, 137, 136, 137, 137, 137, 138,
138, 138, 139, 140, 140, 140, 140, 141,
},
[3] = {
107, 108, 109, 109, 110, 111, 112, 113,
114, 115, 115, 116, 117, 117, 118, 119,
119, 120, 121, 123, 123, 124, 125, 125,
126, 127, 127, 128, 129, 130, 131, 131,
}
},
},
[ MDP_SCALE_PT4TOPT6 ] = {
.offset = 32,
.set = MDP_PPP_SCALE_COEFF_D1_SET,
.use_pr = -1,
.coeffs.c = {
[0] = {
136, 132, 128, 123, 119, 115, 111, 107,
103, 98, 95, 91, 87, 84, 80, 76,
73, 69, 66, 62, 59, 57, 54, 50,
47, 44, 41, 39, 36, 33, 32, 29,
},
[1] = {
206, 205, 204, 204, 201, 200, 199, 197,
196, 194, 191, 191, 189, 185, 184, 182,
180, 178, 176, 173, 170, 168, 165, 162,
160, 157, 155, 152, 148, 146, 142, 140,
},
[2] = {
140, 142, 146, 148, 152, 155, 157, 160,
162, 165, 168, 170, 173, 176, 178, 180,
182, 184, 185, 189, 191, 191, 194, 196,
197, 199, 200, 201, 204, 204, 205, 206,
},
[3] = {
29, 32, 33, 36, 39, 41, 44, 47,
50, 54, 57, 59, 62, 66, 69, 73,
76, 80, 84, 87, 91, 95, 98, 103,
107, 111, 115, 119, 123, 128, 132, 136,
},
},
},
[ MDP_SCALE_PT6TOPT8 ] = {
.offset = 64,
.set = MDP_PPP_SCALE_COEFF_D2_SET,
.use_pr = -1,
.coeffs.c = {
[0] = {
104, 96, 89, 82, 75, 68, 61, 55,
49, 43, 38, 33, 28, 24, 20, 16,
12, 9, 6, 4, 2, 0, -2, -4,
-5, -6, -7, -7, -8, -8, -8, -8,
},
[1] = {
303, 303, 302, 300, 298, 296, 293, 289,
286, 281, 276, 270, 265, 258, 252, 245,
238, 230, 223, 214, 206, 197, 189, 180,
172, 163, 154, 145, 137, 128, 120, 112,
},
[2] = {
112, 120, 128, 137, 145, 154, 163, 172,
180, 189, 197, 206, 214, 223, 230, 238,
245, 252, 258, 265, 270, 276, 281, 286,
289, 293, 296, 298, 300, 302, 303, 303,
},
[3] = {
-8, -8, -8, -8, -7, -7, -6, -5,
-4, -2, 0, 2, 4, 6, 9, 12,
16, 20, 24, 28, 33, 38, 43, 49,
55, 61, 68, 75, 82, 89, 96, 104,
},
},
},
[ MDP_SCALE_PT8TO8 ] = {
.offset = 96,
.set = MDP_PPP_SCALE_COEFF_U1_SET,
.use_pr = -1,
.coeffs.c = {
[0] = {
0, -7, -13, -19, -24, -28, -32, -34,
-37, -39, -40, -41, -41, -41, -40, -40,
-38, -37, -35, -33, -31, -29, -26, -24,
-21, -18, -15, -13, -10, -7, -5, -2,
},
[1] = {
511, 507, 501, 494, 485, 475, 463, 450,
436, 422, 405, 388, 370, 352, 333, 314,
293, 274, 253, 233, 213, 193, 172, 152,
133, 113, 95, 77, 60, 43, 28, 13,
},
[2] = {
0, 13, 28, 43, 60, 77, 95, 113,
133, 152, 172, 193, 213, 233, 253, 274,
294, 314, 333, 352, 370, 388, 405, 422,
436, 450, 463, 475, 485, 494, 501, 507,
},
[3] = {
0, -2, -5, -7, -10, -13, -15, -18,
-21, -24, -26, -29, -31, -33, -35, -37,
-38, -40, -40, -41, -41, -41, -40, -39,
-37, -34, -32, -28, -24, -19, -13, -7,
},
},
},
};
static void load_table(const struct mdp_info *mdp, int scale, int use_pr)
{
int i;
uint32_t val;
struct mdp_scale_coeffs *coeffs;
struct mdp_scale_tbl_info *tbl = &mdp_scale_tbl[scale];
if (use_pr == tbl->use_pr)
return;
tbl->use_pr = use_pr;
if (!use_pr)
coeffs = &tbl->coeffs;
else
coeffs = &mdp_scale_pr_coeffs;
for (i = 0; i < NUM_COEFFS; ++i) {
val = ((coeffs->c[1][i] & 0x3ff) << 16) |
(coeffs->c[0][i] & 0x3ff);
mdp_writel(mdp, val, MDP_PPP_SCALE_COEFF_LSBn(tbl->offset + i));
val = ((coeffs->c[3][i] & 0x3ff) << 16) |
(coeffs->c[2][i] & 0x3ff);
mdp_writel(mdp, val, MDP_PPP_SCALE_COEFF_MSBn(tbl->offset + i));
}
}
#define SCALER_PHASE_BITS 29
static void scale_params(uint32_t dim_in, uint32_t dim_out, uint32_t scaler,
uint32_t *phase_init, uint32_t *phase_step)
{
uint64_t src = dim_in;
uint64_t dst = dim_out;
uint64_t numer;
uint64_t denom;
*phase_init = 0;
if (dst == 1) {
/* if destination is 1 pixel wide, the value of phase_step
* is unimportant. */
*phase_step = (uint32_t) (src << SCALER_PHASE_BITS);
if (scaler == MDP_PPP_SCALER_FIR)
*phase_init =
(uint32_t) ((src - 1) << SCALER_PHASE_BITS);
return;
}
if (scaler == MDP_PPP_SCALER_FIR) {
numer = (src - 1) << SCALER_PHASE_BITS;
denom = dst - 1;
/* we want to round up the result*/
numer += denom - 1;
} else {
numer = src << SCALER_PHASE_BITS;
denom = dst;
}
do_div(numer, denom);
*phase_step = (uint32_t) numer;
}
static int scale_idx(int factor)
{
int idx;
if (factor > 80)
idx = MDP_SCALE_PT8TO8;
else if (factor > 60)
idx = MDP_SCALE_PT6TOPT8;
else if (factor > 40)
idx = MDP_SCALE_PT4TOPT6;
else
idx = MDP_SCALE_PT2TOPT4;
return idx;
}
int mdp_ppp_cfg_scale(const struct mdp_info *mdp, struct ppp_regs *regs,
struct mdp_rect *src_rect, struct mdp_rect *dst_rect,
uint32_t src_format, uint32_t dst_format)
{
uint32_t x_fac;
uint32_t y_fac;
uint32_t scaler_x = MDP_PPP_SCALER_FIR;
uint32_t scaler_y = MDP_PPP_SCALER_FIR;
// Don't use pixel repeat mode, it looks bad
int use_pr = 0;
int x_idx;
int y_idx;
if (unlikely(src_rect->w > 2048 || src_rect->h > 2048))
return -ENOTSUPP;
x_fac = (dst_rect->w * 100) / src_rect->w;
y_fac = (dst_rect->h * 100) / src_rect->h;
/* if down-scaling by a factor smaller than 1/4, use M/N */
scaler_x = x_fac <= 25 ? MDP_PPP_SCALER_MN : MDP_PPP_SCALER_FIR;
scaler_y = y_fac <= 25 ? MDP_PPP_SCALER_MN : MDP_PPP_SCALER_FIR;
scale_params(src_rect->w, dst_rect->w, scaler_x, ®s->phasex_init,
®s->phasex_step);
scale_params(src_rect->h, dst_rect->h, scaler_y, ®s->phasey_init,
®s->phasey_step);
x_idx = scale_idx(x_fac);
y_idx = scale_idx(y_fac);
load_table(mdp, x_idx, use_pr);
load_table(mdp, y_idx, use_pr);
regs->scale_cfg = 0;
// Enable SVI when source or destination is YUV
if (!IS_RGB(src_format) && !IS_RGB(dst_format))
regs->scale_cfg |= (1 << 6);
regs->scale_cfg |= (mdp_scale_tbl[x_idx].set << 2) |
(mdp_scale_tbl[x_idx].set << 4);
regs->scale_cfg |= (scaler_x << 0) | (scaler_y << 1);
return 0;
}
int mdp_ppp_load_blur(const struct mdp_info *mdp)
{
return -ENOTSUPP;
}
void mdp_ppp_init_scale(const struct mdp_info *mdp)
{
int scale;
for (scale = 0; scale < MDP_SCALE_MAX; ++scale)
load_table(mdp, scale, 0);
}
| gpl-2.0 |
playfulgod/kernel_lge_l1m | arch/powerpc/platforms/embedded6xx/linkstation.c | 4673 | 4199 | /*
* Board setup routines for the Buffalo Linkstation / Kurobox Platform.
*
* Copyright (C) 2006 G. Liakhovetski (g.liakhovetski@gmx.de)
*
* Based on sandpoint.c by Mark A. Greer
*
* 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/initrd.h>
#include <linux/of_platform.h>
#include <asm/time.h>
#include <asm/prom.h>
#include <asm/mpic.h>
#include <asm/pci-bridge.h>
#include "mpc10x.h"
static __initdata struct of_device_id of_bus_ids[] = {
{ .type = "soc", },
{ .compatible = "simple-bus", },
{},
};
static int __init declare_of_platform_devices(void)
{
of_platform_bus_probe(NULL, of_bus_ids, NULL);
return 0;
}
machine_device_initcall(linkstation, declare_of_platform_devices);
static int __init linkstation_add_bridge(struct device_node *dev)
{
#ifdef CONFIG_PCI
int len;
struct pci_controller *hose;
const int *bus_range;
printk("Adding PCI host bridge %s\n", dev->full_name);
bus_range = of_get_property(dev, "bus-range", &len);
if (bus_range == NULL || len < 2 * sizeof(int))
printk(KERN_WARNING "Can't get bus-range for %s, assume"
" bus 0\n", dev->full_name);
hose = pcibios_alloc_controller(dev);
if (hose == NULL)
return -ENOMEM;
hose->first_busno = bus_range ? bus_range[0] : 0;
hose->last_busno = bus_range ? bus_range[1] : 0xff;
setup_indirect_pci(hose, 0xfec00000, 0xfee00000, 0);
/* Interpret the "ranges" property */
/* This also maps the I/O region and sets isa_io/mem_base */
pci_process_bridge_OF_ranges(hose, dev, 1);
#endif
return 0;
}
static void __init linkstation_setup_arch(void)
{
struct device_node *np;
/* Lookup PCI host bridges */
for_each_compatible_node(np, "pci", "mpc10x-pci")
linkstation_add_bridge(np);
printk(KERN_INFO "BUFFALO Network Attached Storage Series\n");
printk(KERN_INFO "(C) 2002-2005 BUFFALO INC.\n");
}
/*
* Interrupt setup and service. Interrupts on the linkstation come
* from the four PCI slots plus onboard 8241 devices: I2C, DUART.
*/
static void __init linkstation_init_IRQ(void)
{
struct mpic *mpic;
struct device_node *dnp;
const u32 *prop;
int size;
phys_addr_t paddr;
dnp = of_find_node_by_type(NULL, "open-pic");
if (dnp == NULL)
return;
prop = of_get_property(dnp, "reg", &size);
paddr = (phys_addr_t)of_translate_address(dnp, prop);
mpic = mpic_alloc(dnp, paddr, MPIC_PRIMARY | MPIC_WANTS_RESET, 4, 32, " EPIC ");
BUG_ON(mpic == NULL);
/* PCI IRQs */
mpic_assign_isu(mpic, 0, paddr + 0x10200);
/* I2C */
mpic_assign_isu(mpic, 1, paddr + 0x11000);
/* ttyS0, ttyS1 */
mpic_assign_isu(mpic, 2, paddr + 0x11100);
mpic_init(mpic);
}
extern void avr_uart_configure(void);
extern void avr_uart_send(const char);
static void linkstation_restart(char *cmd)
{
local_irq_disable();
/* Reset system via AVR */
avr_uart_configure();
/* Send reboot command */
avr_uart_send('C');
for(;;) /* Spin until reset happens */
avr_uart_send('G'); /* "kick" */
}
static void linkstation_power_off(void)
{
local_irq_disable();
/* Power down system via AVR */
avr_uart_configure();
/* send shutdown command */
avr_uart_send('E');
for(;;) /* Spin until power-off happens */
avr_uart_send('G'); /* "kick" */
/* NOTREACHED */
}
static void linkstation_halt(void)
{
linkstation_power_off();
/* NOTREACHED */
}
static void linkstation_show_cpuinfo(struct seq_file *m)
{
seq_printf(m, "vendor\t\t: Buffalo Technology\n");
seq_printf(m, "machine\t\t: Linkstation I/Kurobox(HG)\n");
}
static int __init linkstation_probe(void)
{
unsigned long root;
root = of_get_flat_dt_root();
if (!of_flat_dt_is_compatible(root, "linkstation"))
return 0;
return 1;
}
define_machine(linkstation){
.name = "Buffalo Linkstation",
.probe = linkstation_probe,
.setup_arch = linkstation_setup_arch,
.init_IRQ = linkstation_init_IRQ,
.show_cpuinfo = linkstation_show_cpuinfo,
.get_irq = mpic_get_irq,
.restart = linkstation_restart,
.power_off = linkstation_power_off,
.halt = linkstation_halt,
.calibrate_decr = generic_calibrate_decr,
};
| gpl-2.0 |
boa19861105/android_442_KitKat_kernel_htc_dlxpul | drivers/input/touchscreen/ads7846.c | 4929 | 34257 | /*
* ADS7846 based touchscreen and sensor driver
*
* Copyright (c) 2005 David Brownell
* Copyright (c) 2006 Nokia Corporation
* Various changes: Imre Deak <imre.deak@nokia.com>
*
* Using code from:
* - corgi_ts.c
* Copyright (C) 2004-2005 Richard Purdie
* - omap_ts.[hc], ads7846.h, ts_osk.c
* Copyright (C) 2002 MontaVista Software
* Copyright (C) 2004 Texas Instruments
* Copyright (C) 2005 Dirk Behme
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/types.h>
#include <linux/hwmon.h>
#include <linux/init.h>
#include <linux/err.h>
#include <linux/sched.h>
#include <linux/delay.h>
#include <linux/input.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include <linux/pm.h>
#include <linux/gpio.h>
#include <linux/spi/spi.h>
#include <linux/spi/ads7846.h>
#include <linux/regulator/consumer.h>
#include <linux/module.h>
#include <asm/irq.h>
/*
* This code has been heavily tested on a Nokia 770, and lightly
* tested on other ads7846 devices (OSK/Mistral, Lubbock, Spitz).
* TSC2046 is just newer ads7846 silicon.
* Support for ads7843 tested on Atmel at91sam926x-EK.
* Support for ads7845 has only been stubbed in.
* Support for Analog Devices AD7873 and AD7843 tested.
*
* IRQ handling needs a workaround because of a shortcoming in handling
* edge triggered IRQs on some platforms like the OMAP1/2. These
* platforms don't handle the ARM lazy IRQ disabling properly, thus we
* have to maintain our own SW IRQ disabled status. This should be
* removed as soon as the affected platform's IRQ handling is fixed.
*
* App note sbaa036 talks in more detail about accurate sampling...
* that ought to help in situations like LCDs inducing noise (which
* can also be helped by using synch signals) and more generally.
* This driver tries to utilize the measures described in the app
* note. The strength of filtering can be set in the board-* specific
* files.
*/
#define TS_POLL_DELAY 1 /* ms delay before the first sample */
#define TS_POLL_PERIOD 5 /* ms delay between samples */
/* this driver doesn't aim at the peak continuous sample rate */
#define SAMPLE_BITS (8 /*cmd*/ + 16 /*sample*/ + 2 /* before, after */)
struct ts_event {
/*
* For portability, we can't read 12 bit values using SPI (which
* would make the controller deliver them as native byte order u16
* with msbs zeroed). Instead, we read them as two 8-bit values,
* *** WHICH NEED BYTESWAPPING *** and range adjustment.
*/
u16 x;
u16 y;
u16 z1, z2;
bool ignore;
u8 x_buf[3];
u8 y_buf[3];
};
/*
* We allocate this separately to avoid cache line sharing issues when
* driver is used with DMA-based SPI controllers (like atmel_spi) on
* systems where main memory is not DMA-coherent (most non-x86 boards).
*/
struct ads7846_packet {
u8 read_x, read_y, read_z1, read_z2, pwrdown;
u16 dummy; /* for the pwrdown read */
struct ts_event tc;
/* for ads7845 with mpc5121 psc spi we use 3-byte buffers */
u8 read_x_cmd[3], read_y_cmd[3], pwrdown_cmd[3];
};
struct ads7846 {
struct input_dev *input;
char phys[32];
char name[32];
struct spi_device *spi;
struct regulator *reg;
#if defined(CONFIG_HWMON) || defined(CONFIG_HWMON_MODULE)
struct attribute_group *attr_group;
struct device *hwmon;
#endif
u16 model;
u16 vref_mv;
u16 vref_delay_usecs;
u16 x_plate_ohms;
u16 pressure_max;
bool swap_xy;
bool use_internal;
struct ads7846_packet *packet;
struct spi_transfer xfer[18];
struct spi_message msg[5];
int msg_count;
wait_queue_head_t wait;
bool pendown;
int read_cnt;
int read_rep;
int last_read;
u16 debounce_max;
u16 debounce_tol;
u16 debounce_rep;
u16 penirq_recheck_delay_usecs;
struct mutex lock;
bool stopped; /* P: lock */
bool disabled; /* P: lock */
bool suspended; /* P: lock */
int (*filter)(void *data, int data_idx, int *val);
void *filter_data;
void (*filter_cleanup)(void *data);
int (*get_pendown_state)(void);
int gpio_pendown;
void (*wait_for_sync)(void);
};
/* leave chip selected when we're done, for quicker re-select? */
#if 0
#define CS_CHANGE(xfer) ((xfer).cs_change = 1)
#else
#define CS_CHANGE(xfer) ((xfer).cs_change = 0)
#endif
/*--------------------------------------------------------------------------*/
/* The ADS7846 has touchscreen and other sensors.
* Earlier ads784x chips are somewhat compatible.
*/
#define ADS_START (1 << 7)
#define ADS_A2A1A0_d_y (1 << 4) /* differential */
#define ADS_A2A1A0_d_z1 (3 << 4) /* differential */
#define ADS_A2A1A0_d_z2 (4 << 4) /* differential */
#define ADS_A2A1A0_d_x (5 << 4) /* differential */
#define ADS_A2A1A0_temp0 (0 << 4) /* non-differential */
#define ADS_A2A1A0_vbatt (2 << 4) /* non-differential */
#define ADS_A2A1A0_vaux (6 << 4) /* non-differential */
#define ADS_A2A1A0_temp1 (7 << 4) /* non-differential */
#define ADS_8_BIT (1 << 3)
#define ADS_12_BIT (0 << 3)
#define ADS_SER (1 << 2) /* non-differential */
#define ADS_DFR (0 << 2) /* differential */
#define ADS_PD10_PDOWN (0 << 0) /* low power mode + penirq */
#define ADS_PD10_ADC_ON (1 << 0) /* ADC on */
#define ADS_PD10_REF_ON (2 << 0) /* vREF on + penirq */
#define ADS_PD10_ALL_ON (3 << 0) /* ADC + vREF on */
#define MAX_12BIT ((1<<12)-1)
/* leave ADC powered up (disables penirq) between differential samples */
#define READ_12BIT_DFR(x, adc, vref) (ADS_START | ADS_A2A1A0_d_ ## x \
| ADS_12_BIT | ADS_DFR | \
(adc ? ADS_PD10_ADC_ON : 0) | (vref ? ADS_PD10_REF_ON : 0))
#define READ_Y(vref) (READ_12BIT_DFR(y, 1, vref))
#define READ_Z1(vref) (READ_12BIT_DFR(z1, 1, vref))
#define READ_Z2(vref) (READ_12BIT_DFR(z2, 1, vref))
#define READ_X(vref) (READ_12BIT_DFR(x, 1, vref))
#define PWRDOWN (READ_12BIT_DFR(y, 0, 0)) /* LAST */
/* single-ended samples need to first power up reference voltage;
* we leave both ADC and VREF powered
*/
#define READ_12BIT_SER(x) (ADS_START | ADS_A2A1A0_ ## x \
| ADS_12_BIT | ADS_SER)
#define REF_ON (READ_12BIT_DFR(x, 1, 1))
#define REF_OFF (READ_12BIT_DFR(y, 0, 0))
/* Must be called with ts->lock held */
static void ads7846_stop(struct ads7846 *ts)
{
if (!ts->disabled && !ts->suspended) {
/* Signal IRQ thread to stop polling and disable the handler. */
ts->stopped = true;
mb();
wake_up(&ts->wait);
disable_irq(ts->spi->irq);
}
}
/* Must be called with ts->lock held */
static void ads7846_restart(struct ads7846 *ts)
{
if (!ts->disabled && !ts->suspended) {
/* Tell IRQ thread that it may poll the device. */
ts->stopped = false;
mb();
enable_irq(ts->spi->irq);
}
}
/* Must be called with ts->lock held */
static void __ads7846_disable(struct ads7846 *ts)
{
ads7846_stop(ts);
regulator_disable(ts->reg);
/*
* We know the chip's in low power mode since we always
* leave it that way after every request
*/
}
/* Must be called with ts->lock held */
static void __ads7846_enable(struct ads7846 *ts)
{
regulator_enable(ts->reg);
ads7846_restart(ts);
}
static void ads7846_disable(struct ads7846 *ts)
{
mutex_lock(&ts->lock);
if (!ts->disabled) {
if (!ts->suspended)
__ads7846_disable(ts);
ts->disabled = true;
}
mutex_unlock(&ts->lock);
}
static void ads7846_enable(struct ads7846 *ts)
{
mutex_lock(&ts->lock);
if (ts->disabled) {
ts->disabled = false;
if (!ts->suspended)
__ads7846_enable(ts);
}
mutex_unlock(&ts->lock);
}
/*--------------------------------------------------------------------------*/
/*
* Non-touchscreen sensors only use single-ended conversions.
* The range is GND..vREF. The ads7843 and ads7835 must use external vREF;
* ads7846 lets that pin be unconnected, to use internal vREF.
*/
struct ser_req {
u8 ref_on;
u8 command;
u8 ref_off;
u16 scratch;
struct spi_message msg;
struct spi_transfer xfer[6];
/*
* DMA (thus cache coherency maintenance) requires the
* transfer buffers to live in their own cache lines.
*/
__be16 sample ____cacheline_aligned;
};
struct ads7845_ser_req {
u8 command[3];
struct spi_message msg;
struct spi_transfer xfer[2];
/*
* DMA (thus cache coherency maintenance) requires the
* transfer buffers to live in their own cache lines.
*/
u8 sample[3] ____cacheline_aligned;
};
static int ads7846_read12_ser(struct device *dev, unsigned command)
{
struct spi_device *spi = to_spi_device(dev);
struct ads7846 *ts = dev_get_drvdata(dev);
struct ser_req *req;
int status;
req = kzalloc(sizeof *req, GFP_KERNEL);
if (!req)
return -ENOMEM;
spi_message_init(&req->msg);
/* maybe turn on internal vREF, and let it settle */
if (ts->use_internal) {
req->ref_on = REF_ON;
req->xfer[0].tx_buf = &req->ref_on;
req->xfer[0].len = 1;
spi_message_add_tail(&req->xfer[0], &req->msg);
req->xfer[1].rx_buf = &req->scratch;
req->xfer[1].len = 2;
/* for 1uF, settle for 800 usec; no cap, 100 usec. */
req->xfer[1].delay_usecs = ts->vref_delay_usecs;
spi_message_add_tail(&req->xfer[1], &req->msg);
/* Enable reference voltage */
command |= ADS_PD10_REF_ON;
}
/* Enable ADC in every case */
command |= ADS_PD10_ADC_ON;
/* take sample */
req->command = (u8) command;
req->xfer[2].tx_buf = &req->command;
req->xfer[2].len = 1;
spi_message_add_tail(&req->xfer[2], &req->msg);
req->xfer[3].rx_buf = &req->sample;
req->xfer[3].len = 2;
spi_message_add_tail(&req->xfer[3], &req->msg);
/* REVISIT: take a few more samples, and compare ... */
/* converter in low power mode & enable PENIRQ */
req->ref_off = PWRDOWN;
req->xfer[4].tx_buf = &req->ref_off;
req->xfer[4].len = 1;
spi_message_add_tail(&req->xfer[4], &req->msg);
req->xfer[5].rx_buf = &req->scratch;
req->xfer[5].len = 2;
CS_CHANGE(req->xfer[5]);
spi_message_add_tail(&req->xfer[5], &req->msg);
mutex_lock(&ts->lock);
ads7846_stop(ts);
status = spi_sync(spi, &req->msg);
ads7846_restart(ts);
mutex_unlock(&ts->lock);
if (status == 0) {
/* on-wire is a must-ignore bit, a BE12 value, then padding */
status = be16_to_cpu(req->sample);
status = status >> 3;
status &= 0x0fff;
}
kfree(req);
return status;
}
static int ads7845_read12_ser(struct device *dev, unsigned command)
{
struct spi_device *spi = to_spi_device(dev);
struct ads7846 *ts = dev_get_drvdata(dev);
struct ads7845_ser_req *req;
int status;
req = kzalloc(sizeof *req, GFP_KERNEL);
if (!req)
return -ENOMEM;
spi_message_init(&req->msg);
req->command[0] = (u8) command;
req->xfer[0].tx_buf = req->command;
req->xfer[0].rx_buf = req->sample;
req->xfer[0].len = 3;
spi_message_add_tail(&req->xfer[0], &req->msg);
mutex_lock(&ts->lock);
ads7846_stop(ts);
status = spi_sync(spi, &req->msg);
ads7846_restart(ts);
mutex_unlock(&ts->lock);
if (status == 0) {
/* BE12 value, then padding */
status = be16_to_cpu(*((u16 *)&req->sample[1]));
status = status >> 3;
status &= 0x0fff;
}
kfree(req);
return status;
}
#if defined(CONFIG_HWMON) || defined(CONFIG_HWMON_MODULE)
#define SHOW(name, var, adjust) static ssize_t \
name ## _show(struct device *dev, struct device_attribute *attr, char *buf) \
{ \
struct ads7846 *ts = dev_get_drvdata(dev); \
ssize_t v = ads7846_read12_ser(dev, \
READ_12BIT_SER(var)); \
if (v < 0) \
return v; \
return sprintf(buf, "%u\n", adjust(ts, v)); \
} \
static DEVICE_ATTR(name, S_IRUGO, name ## _show, NULL);
/* Sysfs conventions report temperatures in millidegrees Celsius.
* ADS7846 could use the low-accuracy two-sample scheme, but can't do the high
* accuracy scheme without calibration data. For now we won't try either;
* userspace sees raw sensor values, and must scale/calibrate appropriately.
*/
static inline unsigned null_adjust(struct ads7846 *ts, ssize_t v)
{
return v;
}
SHOW(temp0, temp0, null_adjust) /* temp1_input */
SHOW(temp1, temp1, null_adjust) /* temp2_input */
/* sysfs conventions report voltages in millivolts. We can convert voltages
* if we know vREF. userspace may need to scale vAUX to match the board's
* external resistors; we assume that vBATT only uses the internal ones.
*/
static inline unsigned vaux_adjust(struct ads7846 *ts, ssize_t v)
{
unsigned retval = v;
/* external resistors may scale vAUX into 0..vREF */
retval *= ts->vref_mv;
retval = retval >> 12;
return retval;
}
static inline unsigned vbatt_adjust(struct ads7846 *ts, ssize_t v)
{
unsigned retval = vaux_adjust(ts, v);
/* ads7846 has a resistor ladder to scale this signal down */
if (ts->model == 7846)
retval *= 4;
return retval;
}
SHOW(in0_input, vaux, vaux_adjust)
SHOW(in1_input, vbatt, vbatt_adjust)
static struct attribute *ads7846_attributes[] = {
&dev_attr_temp0.attr,
&dev_attr_temp1.attr,
&dev_attr_in0_input.attr,
&dev_attr_in1_input.attr,
NULL,
};
static struct attribute_group ads7846_attr_group = {
.attrs = ads7846_attributes,
};
static struct attribute *ads7843_attributes[] = {
&dev_attr_in0_input.attr,
&dev_attr_in1_input.attr,
NULL,
};
static struct attribute_group ads7843_attr_group = {
.attrs = ads7843_attributes,
};
static struct attribute *ads7845_attributes[] = {
&dev_attr_in0_input.attr,
NULL,
};
static struct attribute_group ads7845_attr_group = {
.attrs = ads7845_attributes,
};
static int ads784x_hwmon_register(struct spi_device *spi, struct ads7846 *ts)
{
struct device *hwmon;
int err;
/* hwmon sensors need a reference voltage */
switch (ts->model) {
case 7846:
if (!ts->vref_mv) {
dev_dbg(&spi->dev, "assuming 2.5V internal vREF\n");
ts->vref_mv = 2500;
ts->use_internal = true;
}
break;
case 7845:
case 7843:
if (!ts->vref_mv) {
dev_warn(&spi->dev,
"external vREF for ADS%d not specified\n",
ts->model);
return 0;
}
break;
}
/* different chips have different sensor groups */
switch (ts->model) {
case 7846:
ts->attr_group = &ads7846_attr_group;
break;
case 7845:
ts->attr_group = &ads7845_attr_group;
break;
case 7843:
ts->attr_group = &ads7843_attr_group;
break;
default:
dev_dbg(&spi->dev, "ADS%d not recognized\n", ts->model);
return 0;
}
err = sysfs_create_group(&spi->dev.kobj, ts->attr_group);
if (err)
return err;
hwmon = hwmon_device_register(&spi->dev);
if (IS_ERR(hwmon)) {
sysfs_remove_group(&spi->dev.kobj, ts->attr_group);
return PTR_ERR(hwmon);
}
ts->hwmon = hwmon;
return 0;
}
static void ads784x_hwmon_unregister(struct spi_device *spi,
struct ads7846 *ts)
{
if (ts->hwmon) {
sysfs_remove_group(&spi->dev.kobj, ts->attr_group);
hwmon_device_unregister(ts->hwmon);
}
}
#else
static inline int ads784x_hwmon_register(struct spi_device *spi,
struct ads7846 *ts)
{
return 0;
}
static inline void ads784x_hwmon_unregister(struct spi_device *spi,
struct ads7846 *ts)
{
}
#endif
static ssize_t ads7846_pen_down_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct ads7846 *ts = dev_get_drvdata(dev);
return sprintf(buf, "%u\n", ts->pendown);
}
static DEVICE_ATTR(pen_down, S_IRUGO, ads7846_pen_down_show, NULL);
static ssize_t ads7846_disable_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct ads7846 *ts = dev_get_drvdata(dev);
return sprintf(buf, "%u\n", ts->disabled);
}
static ssize_t ads7846_disable_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct ads7846 *ts = dev_get_drvdata(dev);
unsigned int i;
int err;
err = kstrtouint(buf, 10, &i);
if (err)
return err;
if (i)
ads7846_disable(ts);
else
ads7846_enable(ts);
return count;
}
static DEVICE_ATTR(disable, 0664, ads7846_disable_show, ads7846_disable_store);
static struct attribute *ads784x_attributes[] = {
&dev_attr_pen_down.attr,
&dev_attr_disable.attr,
NULL,
};
static struct attribute_group ads784x_attr_group = {
.attrs = ads784x_attributes,
};
/*--------------------------------------------------------------------------*/
static int get_pendown_state(struct ads7846 *ts)
{
if (ts->get_pendown_state)
return ts->get_pendown_state();
return !gpio_get_value(ts->gpio_pendown);
}
static void null_wait_for_sync(void)
{
}
static int ads7846_debounce_filter(void *ads, int data_idx, int *val)
{
struct ads7846 *ts = ads;
if (!ts->read_cnt || (abs(ts->last_read - *val) > ts->debounce_tol)) {
/* Start over collecting consistent readings. */
ts->read_rep = 0;
/*
* Repeat it, if this was the first read or the read
* wasn't consistent enough.
*/
if (ts->read_cnt < ts->debounce_max) {
ts->last_read = *val;
ts->read_cnt++;
return ADS7846_FILTER_REPEAT;
} else {
/*
* Maximum number of debouncing reached and still
* not enough number of consistent readings. Abort
* the whole sample, repeat it in the next sampling
* period.
*/
ts->read_cnt = 0;
return ADS7846_FILTER_IGNORE;
}
} else {
if (++ts->read_rep > ts->debounce_rep) {
/*
* Got a good reading for this coordinate,
* go for the next one.
*/
ts->read_cnt = 0;
ts->read_rep = 0;
return ADS7846_FILTER_OK;
} else {
/* Read more values that are consistent. */
ts->read_cnt++;
return ADS7846_FILTER_REPEAT;
}
}
}
static int ads7846_no_filter(void *ads, int data_idx, int *val)
{
return ADS7846_FILTER_OK;
}
static int ads7846_get_value(struct ads7846 *ts, struct spi_message *m)
{
struct spi_transfer *t =
list_entry(m->transfers.prev, struct spi_transfer, transfer_list);
if (ts->model == 7845) {
return be16_to_cpup((__be16 *)&(((char*)t->rx_buf)[1])) >> 3;
} else {
/*
* adjust: on-wire is a must-ignore bit, a BE12 value, then
* padding; built from two 8 bit values written msb-first.
*/
return be16_to_cpup((__be16 *)t->rx_buf) >> 3;
}
}
static void ads7846_update_value(struct spi_message *m, int val)
{
struct spi_transfer *t =
list_entry(m->transfers.prev, struct spi_transfer, transfer_list);
*(u16 *)t->rx_buf = val;
}
static void ads7846_read_state(struct ads7846 *ts)
{
struct ads7846_packet *packet = ts->packet;
struct spi_message *m;
int msg_idx = 0;
int val;
int action;
int error;
while (msg_idx < ts->msg_count) {
ts->wait_for_sync();
m = &ts->msg[msg_idx];
error = spi_sync(ts->spi, m);
if (error) {
dev_err(&ts->spi->dev, "spi_async --> %d\n", error);
packet->tc.ignore = true;
return;
}
/*
* Last message is power down request, no need to convert
* or filter the value.
*/
if (msg_idx < ts->msg_count - 1) {
val = ads7846_get_value(ts, m);
action = ts->filter(ts->filter_data, msg_idx, &val);
switch (action) {
case ADS7846_FILTER_REPEAT:
continue;
case ADS7846_FILTER_IGNORE:
packet->tc.ignore = true;
msg_idx = ts->msg_count - 1;
continue;
case ADS7846_FILTER_OK:
ads7846_update_value(m, val);
packet->tc.ignore = false;
msg_idx++;
break;
default:
BUG();
}
} else {
msg_idx++;
}
}
}
static void ads7846_report_state(struct ads7846 *ts)
{
struct ads7846_packet *packet = ts->packet;
unsigned int Rt;
u16 x, y, z1, z2;
/*
* ads7846_get_value() does in-place conversion (including byte swap)
* from on-the-wire format as part of debouncing to get stable
* readings.
*/
if (ts->model == 7845) {
x = *(u16 *)packet->tc.x_buf;
y = *(u16 *)packet->tc.y_buf;
z1 = 0;
z2 = 0;
} else {
x = packet->tc.x;
y = packet->tc.y;
z1 = packet->tc.z1;
z2 = packet->tc.z2;
}
/* range filtering */
if (x == MAX_12BIT)
x = 0;
if (ts->model == 7843) {
Rt = ts->pressure_max / 2;
} else if (ts->model == 7845) {
if (get_pendown_state(ts))
Rt = ts->pressure_max / 2;
else
Rt = 0;
dev_vdbg(&ts->spi->dev, "x/y: %d/%d, PD %d\n", x, y, Rt);
} else if (likely(x && z1)) {
/* compute touch pressure resistance using equation #2 */
Rt = z2;
Rt -= z1;
Rt *= x;
Rt *= ts->x_plate_ohms;
Rt /= z1;
Rt = (Rt + 2047) >> 12;
} else {
Rt = 0;
}
/*
* Sample found inconsistent by debouncing or pressure is beyond
* the maximum. Don't report it to user space, repeat at least
* once more the measurement
*/
if (packet->tc.ignore || Rt > ts->pressure_max) {
dev_vdbg(&ts->spi->dev, "ignored %d pressure %d\n",
packet->tc.ignore, Rt);
return;
}
/*
* Maybe check the pendown state before reporting. This discards
* false readings when the pen is lifted.
*/
if (ts->penirq_recheck_delay_usecs) {
udelay(ts->penirq_recheck_delay_usecs);
if (!get_pendown_state(ts))
Rt = 0;
}
/*
* NOTE: We can't rely on the pressure to determine the pen down
* state, even this controller has a pressure sensor. The pressure
* value can fluctuate for quite a while after lifting the pen and
* in some cases may not even settle at the expected value.
*
* The only safe way to check for the pen up condition is in the
* timer by reading the pen signal state (it's a GPIO _and_ IRQ).
*/
if (Rt) {
struct input_dev *input = ts->input;
if (ts->swap_xy)
swap(x, y);
if (!ts->pendown) {
input_report_key(input, BTN_TOUCH, 1);
ts->pendown = true;
dev_vdbg(&ts->spi->dev, "DOWN\n");
}
input_report_abs(input, ABS_X, x);
input_report_abs(input, ABS_Y, y);
input_report_abs(input, ABS_PRESSURE, ts->pressure_max - Rt);
input_sync(input);
dev_vdbg(&ts->spi->dev, "%4d/%4d/%4d\n", x, y, Rt);
}
}
static irqreturn_t ads7846_hard_irq(int irq, void *handle)
{
struct ads7846 *ts = handle;
return get_pendown_state(ts) ? IRQ_WAKE_THREAD : IRQ_HANDLED;
}
static irqreturn_t ads7846_irq(int irq, void *handle)
{
struct ads7846 *ts = handle;
/* Start with a small delay before checking pendown state */
msleep(TS_POLL_DELAY);
while (!ts->stopped && get_pendown_state(ts)) {
/* pen is down, continue with the measurement */
ads7846_read_state(ts);
if (!ts->stopped)
ads7846_report_state(ts);
wait_event_timeout(ts->wait, ts->stopped,
msecs_to_jiffies(TS_POLL_PERIOD));
}
if (ts->pendown) {
struct input_dev *input = ts->input;
input_report_key(input, BTN_TOUCH, 0);
input_report_abs(input, ABS_PRESSURE, 0);
input_sync(input);
ts->pendown = false;
dev_vdbg(&ts->spi->dev, "UP\n");
}
return IRQ_HANDLED;
}
#ifdef CONFIG_PM_SLEEP
static int ads7846_suspend(struct device *dev)
{
struct ads7846 *ts = dev_get_drvdata(dev);
mutex_lock(&ts->lock);
if (!ts->suspended) {
if (!ts->disabled)
__ads7846_disable(ts);
if (device_may_wakeup(&ts->spi->dev))
enable_irq_wake(ts->spi->irq);
ts->suspended = true;
}
mutex_unlock(&ts->lock);
return 0;
}
static int ads7846_resume(struct device *dev)
{
struct ads7846 *ts = dev_get_drvdata(dev);
mutex_lock(&ts->lock);
if (ts->suspended) {
ts->suspended = false;
if (device_may_wakeup(&ts->spi->dev))
disable_irq_wake(ts->spi->irq);
if (!ts->disabled)
__ads7846_enable(ts);
}
mutex_unlock(&ts->lock);
return 0;
}
#endif
static SIMPLE_DEV_PM_OPS(ads7846_pm, ads7846_suspend, ads7846_resume);
static int __devinit ads7846_setup_pendown(struct spi_device *spi, struct ads7846 *ts)
{
struct ads7846_platform_data *pdata = spi->dev.platform_data;
int err;
/*
* REVISIT when the irq can be triggered active-low, or if for some
* reason the touchscreen isn't hooked up, we don't need to access
* the pendown state.
*/
if (pdata->get_pendown_state) {
ts->get_pendown_state = pdata->get_pendown_state;
} else if (gpio_is_valid(pdata->gpio_pendown)) {
err = gpio_request_one(pdata->gpio_pendown, GPIOF_IN,
"ads7846_pendown");
if (err) {
dev_err(&spi->dev,
"failed to request/setup pendown GPIO%d: %d\n",
pdata->gpio_pendown, err);
return err;
}
ts->gpio_pendown = pdata->gpio_pendown;
} else {
dev_err(&spi->dev, "no get_pendown_state nor gpio_pendown?\n");
return -EINVAL;
}
return 0;
}
/*
* Set up the transfers to read touchscreen state; this assumes we
* use formula #2 for pressure, not #3.
*/
static void __devinit ads7846_setup_spi_msg(struct ads7846 *ts,
const struct ads7846_platform_data *pdata)
{
struct spi_message *m = &ts->msg[0];
struct spi_transfer *x = ts->xfer;
struct ads7846_packet *packet = ts->packet;
int vref = pdata->keep_vref_on;
if (ts->model == 7873) {
/*
* The AD7873 is almost identical to the ADS7846
* keep VREF off during differential/ratiometric
* conversion modes.
*/
ts->model = 7846;
vref = 0;
}
ts->msg_count = 1;
spi_message_init(m);
m->context = ts;
if (ts->model == 7845) {
packet->read_y_cmd[0] = READ_Y(vref);
packet->read_y_cmd[1] = 0;
packet->read_y_cmd[2] = 0;
x->tx_buf = &packet->read_y_cmd[0];
x->rx_buf = &packet->tc.y_buf[0];
x->len = 3;
spi_message_add_tail(x, m);
} else {
/* y- still on; turn on only y+ (and ADC) */
packet->read_y = READ_Y(vref);
x->tx_buf = &packet->read_y;
x->len = 1;
spi_message_add_tail(x, m);
x++;
x->rx_buf = &packet->tc.y;
x->len = 2;
spi_message_add_tail(x, m);
}
/*
* The first sample after switching drivers can be low quality;
* optionally discard it, using a second one after the signals
* have had enough time to stabilize.
*/
if (pdata->settle_delay_usecs) {
x->delay_usecs = pdata->settle_delay_usecs;
x++;
x->tx_buf = &packet->read_y;
x->len = 1;
spi_message_add_tail(x, m);
x++;
x->rx_buf = &packet->tc.y;
x->len = 2;
spi_message_add_tail(x, m);
}
ts->msg_count++;
m++;
spi_message_init(m);
m->context = ts;
if (ts->model == 7845) {
x++;
packet->read_x_cmd[0] = READ_X(vref);
packet->read_x_cmd[1] = 0;
packet->read_x_cmd[2] = 0;
x->tx_buf = &packet->read_x_cmd[0];
x->rx_buf = &packet->tc.x_buf[0];
x->len = 3;
spi_message_add_tail(x, m);
} else {
/* turn y- off, x+ on, then leave in lowpower */
x++;
packet->read_x = READ_X(vref);
x->tx_buf = &packet->read_x;
x->len = 1;
spi_message_add_tail(x, m);
x++;
x->rx_buf = &packet->tc.x;
x->len = 2;
spi_message_add_tail(x, m);
}
/* ... maybe discard first sample ... */
if (pdata->settle_delay_usecs) {
x->delay_usecs = pdata->settle_delay_usecs;
x++;
x->tx_buf = &packet->read_x;
x->len = 1;
spi_message_add_tail(x, m);
x++;
x->rx_buf = &packet->tc.x;
x->len = 2;
spi_message_add_tail(x, m);
}
/* turn y+ off, x- on; we'll use formula #2 */
if (ts->model == 7846) {
ts->msg_count++;
m++;
spi_message_init(m);
m->context = ts;
x++;
packet->read_z1 = READ_Z1(vref);
x->tx_buf = &packet->read_z1;
x->len = 1;
spi_message_add_tail(x, m);
x++;
x->rx_buf = &packet->tc.z1;
x->len = 2;
spi_message_add_tail(x, m);
/* ... maybe discard first sample ... */
if (pdata->settle_delay_usecs) {
x->delay_usecs = pdata->settle_delay_usecs;
x++;
x->tx_buf = &packet->read_z1;
x->len = 1;
spi_message_add_tail(x, m);
x++;
x->rx_buf = &packet->tc.z1;
x->len = 2;
spi_message_add_tail(x, m);
}
ts->msg_count++;
m++;
spi_message_init(m);
m->context = ts;
x++;
packet->read_z2 = READ_Z2(vref);
x->tx_buf = &packet->read_z2;
x->len = 1;
spi_message_add_tail(x, m);
x++;
x->rx_buf = &packet->tc.z2;
x->len = 2;
spi_message_add_tail(x, m);
/* ... maybe discard first sample ... */
if (pdata->settle_delay_usecs) {
x->delay_usecs = pdata->settle_delay_usecs;
x++;
x->tx_buf = &packet->read_z2;
x->len = 1;
spi_message_add_tail(x, m);
x++;
x->rx_buf = &packet->tc.z2;
x->len = 2;
spi_message_add_tail(x, m);
}
}
/* power down */
ts->msg_count++;
m++;
spi_message_init(m);
m->context = ts;
if (ts->model == 7845) {
x++;
packet->pwrdown_cmd[0] = PWRDOWN;
packet->pwrdown_cmd[1] = 0;
packet->pwrdown_cmd[2] = 0;
x->tx_buf = &packet->pwrdown_cmd[0];
x->len = 3;
} else {
x++;
packet->pwrdown = PWRDOWN;
x->tx_buf = &packet->pwrdown;
x->len = 1;
spi_message_add_tail(x, m);
x++;
x->rx_buf = &packet->dummy;
x->len = 2;
}
CS_CHANGE(*x);
spi_message_add_tail(x, m);
}
static int __devinit ads7846_probe(struct spi_device *spi)
{
struct ads7846 *ts;
struct ads7846_packet *packet;
struct input_dev *input_dev;
struct ads7846_platform_data *pdata = spi->dev.platform_data;
unsigned long irq_flags;
int err;
if (!spi->irq) {
dev_dbg(&spi->dev, "no IRQ?\n");
return -ENODEV;
}
if (!pdata) {
dev_dbg(&spi->dev, "no platform data?\n");
return -ENODEV;
}
/* don't exceed max specified sample rate */
if (spi->max_speed_hz > (125000 * SAMPLE_BITS)) {
dev_dbg(&spi->dev, "f(sample) %d KHz?\n",
(spi->max_speed_hz/SAMPLE_BITS)/1000);
return -EINVAL;
}
/* We'd set TX word size 8 bits and RX word size to 13 bits ... except
* that even if the hardware can do that, the SPI controller driver
* may not. So we stick to very-portable 8 bit words, both RX and TX.
*/
spi->bits_per_word = 8;
spi->mode = SPI_MODE_0;
err = spi_setup(spi);
if (err < 0)
return err;
ts = kzalloc(sizeof(struct ads7846), GFP_KERNEL);
packet = kzalloc(sizeof(struct ads7846_packet), GFP_KERNEL);
input_dev = input_allocate_device();
if (!ts || !packet || !input_dev) {
err = -ENOMEM;
goto err_free_mem;
}
dev_set_drvdata(&spi->dev, ts);
ts->packet = packet;
ts->spi = spi;
ts->input = input_dev;
ts->vref_mv = pdata->vref_mv;
ts->swap_xy = pdata->swap_xy;
mutex_init(&ts->lock);
init_waitqueue_head(&ts->wait);
ts->model = pdata->model ? : 7846;
ts->vref_delay_usecs = pdata->vref_delay_usecs ? : 100;
ts->x_plate_ohms = pdata->x_plate_ohms ? : 400;
ts->pressure_max = pdata->pressure_max ? : ~0;
if (pdata->filter != NULL) {
if (pdata->filter_init != NULL) {
err = pdata->filter_init(pdata, &ts->filter_data);
if (err < 0)
goto err_free_mem;
}
ts->filter = pdata->filter;
ts->filter_cleanup = pdata->filter_cleanup;
} else if (pdata->debounce_max) {
ts->debounce_max = pdata->debounce_max;
if (ts->debounce_max < 2)
ts->debounce_max = 2;
ts->debounce_tol = pdata->debounce_tol;
ts->debounce_rep = pdata->debounce_rep;
ts->filter = ads7846_debounce_filter;
ts->filter_data = ts;
} else {
ts->filter = ads7846_no_filter;
}
err = ads7846_setup_pendown(spi, ts);
if (err)
goto err_cleanup_filter;
if (pdata->penirq_recheck_delay_usecs)
ts->penirq_recheck_delay_usecs =
pdata->penirq_recheck_delay_usecs;
ts->wait_for_sync = pdata->wait_for_sync ? : null_wait_for_sync;
snprintf(ts->phys, sizeof(ts->phys), "%s/input0", dev_name(&spi->dev));
snprintf(ts->name, sizeof(ts->name), "ADS%d Touchscreen", ts->model);
input_dev->name = ts->name;
input_dev->phys = ts->phys;
input_dev->dev.parent = &spi->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(input_dev, ABS_X,
pdata->x_min ? : 0,
pdata->x_max ? : MAX_12BIT,
0, 0);
input_set_abs_params(input_dev, ABS_Y,
pdata->y_min ? : 0,
pdata->y_max ? : MAX_12BIT,
0, 0);
input_set_abs_params(input_dev, ABS_PRESSURE,
pdata->pressure_min, pdata->pressure_max, 0, 0);
ads7846_setup_spi_msg(ts, pdata);
ts->reg = regulator_get(&spi->dev, "vcc");
if (IS_ERR(ts->reg)) {
err = PTR_ERR(ts->reg);
dev_err(&spi->dev, "unable to get regulator: %d\n", err);
goto err_free_gpio;
}
err = regulator_enable(ts->reg);
if (err) {
dev_err(&spi->dev, "unable to enable regulator: %d\n", err);
goto err_put_regulator;
}
irq_flags = pdata->irq_flags ? : IRQF_TRIGGER_FALLING;
irq_flags |= IRQF_ONESHOT;
err = request_threaded_irq(spi->irq, ads7846_hard_irq, ads7846_irq,
irq_flags, spi->dev.driver->name, ts);
if (err && !pdata->irq_flags) {
dev_info(&spi->dev,
"trying pin change workaround on irq %d\n", spi->irq);
irq_flags |= IRQF_TRIGGER_RISING;
err = request_threaded_irq(spi->irq,
ads7846_hard_irq, ads7846_irq,
irq_flags, spi->dev.driver->name, ts);
}
if (err) {
dev_dbg(&spi->dev, "irq %d busy?\n", spi->irq);
goto err_disable_regulator;
}
err = ads784x_hwmon_register(spi, ts);
if (err)
goto err_free_irq;
dev_info(&spi->dev, "touchscreen, irq %d\n", spi->irq);
/*
* Take a first sample, leaving nPENIRQ active and vREF off; avoid
* the touchscreen, in case it's not connected.
*/
if (ts->model == 7845)
ads7845_read12_ser(&spi->dev, PWRDOWN);
else
(void) ads7846_read12_ser(&spi->dev, READ_12BIT_SER(vaux));
err = sysfs_create_group(&spi->dev.kobj, &ads784x_attr_group);
if (err)
goto err_remove_hwmon;
err = input_register_device(input_dev);
if (err)
goto err_remove_attr_group;
device_init_wakeup(&spi->dev, pdata->wakeup);
return 0;
err_remove_attr_group:
sysfs_remove_group(&spi->dev.kobj, &ads784x_attr_group);
err_remove_hwmon:
ads784x_hwmon_unregister(spi, ts);
err_free_irq:
free_irq(spi->irq, ts);
err_disable_regulator:
regulator_disable(ts->reg);
err_put_regulator:
regulator_put(ts->reg);
err_free_gpio:
if (!ts->get_pendown_state)
gpio_free(ts->gpio_pendown);
err_cleanup_filter:
if (ts->filter_cleanup)
ts->filter_cleanup(ts->filter_data);
err_free_mem:
input_free_device(input_dev);
kfree(packet);
kfree(ts);
return err;
}
static int __devexit ads7846_remove(struct spi_device *spi)
{
struct ads7846 *ts = dev_get_drvdata(&spi->dev);
device_init_wakeup(&spi->dev, false);
sysfs_remove_group(&spi->dev.kobj, &ads784x_attr_group);
ads7846_disable(ts);
free_irq(ts->spi->irq, ts);
input_unregister_device(ts->input);
ads784x_hwmon_unregister(spi, ts);
regulator_disable(ts->reg);
regulator_put(ts->reg);
if (!ts->get_pendown_state) {
/*
* If we are not using specialized pendown method we must
* have been relying on gpio we set up ourselves.
*/
gpio_free(ts->gpio_pendown);
}
if (ts->filter_cleanup)
ts->filter_cleanup(ts->filter_data);
kfree(ts->packet);
kfree(ts);
dev_dbg(&spi->dev, "unregistered touchscreen\n");
return 0;
}
static struct spi_driver ads7846_driver = {
.driver = {
.name = "ads7846",
.owner = THIS_MODULE,
.pm = &ads7846_pm,
},
.probe = ads7846_probe,
.remove = __devexit_p(ads7846_remove),
};
module_spi_driver(ads7846_driver);
MODULE_DESCRIPTION("ADS7846 TouchScreen Driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("spi:ads7846");
| gpl-2.0 |
DirtyUnicorns/android_kernel_motorola_msm8226 | drivers/media/video/au0828/au0828-dvb.c | 8001 | 11129 | /*
* Driver for the Auvitek USB bridge
*
* Copyright (c) 2008 Steven Toth <stoth@linuxtv.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/suspend.h>
#include <media/v4l2-common.h>
#include "au0828.h"
#include "au8522.h"
#include "xc5000.h"
#include "mxl5007t.h"
#include "tda18271.h"
DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr);
#define _AU0828_BULKPIPE 0x83
#define _BULKPIPESIZE 0xe522
static u8 hauppauge_hvr950q_led_states[] = {
0x00, /* off */
0x02, /* yellow */
0x04, /* green */
};
static struct au8522_led_config hauppauge_hvr950q_led_cfg = {
.gpio_output = 0x00e0,
.gpio_output_enable = 0x6006,
.gpio_output_disable = 0x0660,
.gpio_leds = 0x00e2,
.led_states = hauppauge_hvr950q_led_states,
.num_led_states = sizeof(hauppauge_hvr950q_led_states),
.vsb8_strong = 20 /* dB */ * 10,
.qam64_strong = 25 /* dB */ * 10,
.qam256_strong = 32 /* dB */ * 10,
};
static struct au8522_config hauppauge_hvr950q_config = {
.demod_address = 0x8e >> 1,
.status_mode = AU8522_DEMODLOCKING,
.qam_if = AU8522_IF_6MHZ,
.vsb_if = AU8522_IF_6MHZ,
.led_cfg = &hauppauge_hvr950q_led_cfg,
};
static struct au8522_config fusionhdtv7usb_config = {
.demod_address = 0x8e >> 1,
.status_mode = AU8522_DEMODLOCKING,
.qam_if = AU8522_IF_6MHZ,
.vsb_if = AU8522_IF_6MHZ,
};
static struct au8522_config hauppauge_woodbury_config = {
.demod_address = 0x8e >> 1,
.status_mode = AU8522_DEMODLOCKING,
.qam_if = AU8522_IF_4MHZ,
.vsb_if = AU8522_IF_3_25MHZ,
};
static struct xc5000_config hauppauge_hvr950q_tunerconfig = {
.i2c_address = 0x61,
.if_khz = 6000,
};
static struct mxl5007t_config mxl5007t_hvr950q_config = {
.xtal_freq_hz = MxL_XTAL_24_MHZ,
.if_freq_hz = MxL_IF_6_MHZ,
};
static struct tda18271_config hauppauge_woodbury_tunerconfig = {
.gate = TDA18271_GATE_DIGITAL,
};
/*-------------------------------------------------------------------*/
static void urb_completion(struct urb *purb)
{
struct au0828_dev *dev = purb->context;
int ptype = usb_pipetype(purb->pipe);
dprintk(2, "%s()\n", __func__);
if (!dev)
return;
if (dev->urb_streaming == 0)
return;
if (ptype != PIPE_BULK) {
printk(KERN_ERR "%s() Unsupported URB type %d\n",
__func__, ptype);
return;
}
/* Feed the transport payload into the kernel demux */
dvb_dmx_swfilter_packets(&dev->dvb.demux,
purb->transfer_buffer, purb->actual_length / 188);
/* Clean the buffer before we requeue */
memset(purb->transfer_buffer, 0, URB_BUFSIZE);
/* Requeue URB */
usb_submit_urb(purb, GFP_ATOMIC);
}
static int stop_urb_transfer(struct au0828_dev *dev)
{
int i;
dprintk(2, "%s()\n", __func__);
for (i = 0; i < URB_COUNT; i++) {
usb_kill_urb(dev->urbs[i]);
kfree(dev->urbs[i]->transfer_buffer);
usb_free_urb(dev->urbs[i]);
}
dev->urb_streaming = 0;
return 0;
}
static int start_urb_transfer(struct au0828_dev *dev)
{
struct urb *purb;
int i, ret = -ENOMEM;
dprintk(2, "%s()\n", __func__);
if (dev->urb_streaming) {
dprintk(2, "%s: bulk xfer already running!\n", __func__);
return 0;
}
for (i = 0; i < URB_COUNT; i++) {
dev->urbs[i] = usb_alloc_urb(0, GFP_KERNEL);
if (!dev->urbs[i])
goto err;
purb = dev->urbs[i];
purb->transfer_buffer = kzalloc(URB_BUFSIZE, GFP_KERNEL);
if (!purb->transfer_buffer) {
usb_free_urb(purb);
dev->urbs[i] = NULL;
goto err;
}
purb->status = -EINPROGRESS;
usb_fill_bulk_urb(purb,
dev->usbdev,
usb_rcvbulkpipe(dev->usbdev,
_AU0828_BULKPIPE),
purb->transfer_buffer,
URB_BUFSIZE,
urb_completion,
dev);
}
for (i = 0; i < URB_COUNT; i++) {
ret = usb_submit_urb(dev->urbs[i], GFP_ATOMIC);
if (ret != 0) {
stop_urb_transfer(dev);
printk(KERN_ERR "%s: failed urb submission, "
"err = %d\n", __func__, ret);
return ret;
}
}
dev->urb_streaming = 1;
ret = 0;
err:
return ret;
}
static int au0828_dvb_start_feed(struct dvb_demux_feed *feed)
{
struct dvb_demux *demux = feed->demux;
struct au0828_dev *dev = (struct au0828_dev *) demux->priv;
struct au0828_dvb *dvb = &dev->dvb;
int ret = 0;
dprintk(1, "%s()\n", __func__);
if (!demux->dmx.frontend)
return -EINVAL;
if (dvb) {
mutex_lock(&dvb->lock);
if (dvb->feeding++ == 0) {
/* Start transport */
au0828_write(dev, 0x608, 0x90);
au0828_write(dev, 0x609, 0x72);
au0828_write(dev, 0x60a, 0x71);
au0828_write(dev, 0x60b, 0x01);
ret = start_urb_transfer(dev);
}
mutex_unlock(&dvb->lock);
}
return ret;
}
static int au0828_dvb_stop_feed(struct dvb_demux_feed *feed)
{
struct dvb_demux *demux = feed->demux;
struct au0828_dev *dev = (struct au0828_dev *) demux->priv;
struct au0828_dvb *dvb = &dev->dvb;
int ret = 0;
dprintk(1, "%s()\n", __func__);
if (dvb) {
mutex_lock(&dvb->lock);
if (--dvb->feeding == 0) {
/* Stop transport */
au0828_write(dev, 0x608, 0x00);
au0828_write(dev, 0x609, 0x00);
au0828_write(dev, 0x60a, 0x00);
au0828_write(dev, 0x60b, 0x00);
ret = stop_urb_transfer(dev);
}
mutex_unlock(&dvb->lock);
}
return ret;
}
static int dvb_register(struct au0828_dev *dev)
{
struct au0828_dvb *dvb = &dev->dvb;
int result;
dprintk(1, "%s()\n", __func__);
/* register adapter */
result = dvb_register_adapter(&dvb->adapter, DRIVER_NAME, THIS_MODULE,
&dev->usbdev->dev, adapter_nr);
if (result < 0) {
printk(KERN_ERR "%s: dvb_register_adapter failed "
"(errno = %d)\n", DRIVER_NAME, result);
goto fail_adapter;
}
dvb->adapter.priv = dev;
/* register frontend */
result = dvb_register_frontend(&dvb->adapter, dvb->frontend);
if (result < 0) {
printk(KERN_ERR "%s: dvb_register_frontend failed "
"(errno = %d)\n", DRIVER_NAME, result);
goto fail_frontend;
}
/* register demux stuff */
dvb->demux.dmx.capabilities =
DMX_TS_FILTERING | DMX_SECTION_FILTERING |
DMX_MEMORY_BASED_FILTERING;
dvb->demux.priv = dev;
dvb->demux.filternum = 256;
dvb->demux.feednum = 256;
dvb->demux.start_feed = au0828_dvb_start_feed;
dvb->demux.stop_feed = au0828_dvb_stop_feed;
result = dvb_dmx_init(&dvb->demux);
if (result < 0) {
printk(KERN_ERR "%s: dvb_dmx_init failed (errno = %d)\n",
DRIVER_NAME, result);
goto fail_dmx;
}
dvb->dmxdev.filternum = 256;
dvb->dmxdev.demux = &dvb->demux.dmx;
dvb->dmxdev.capabilities = 0;
result = dvb_dmxdev_init(&dvb->dmxdev, &dvb->adapter);
if (result < 0) {
printk(KERN_ERR "%s: dvb_dmxdev_init failed (errno = %d)\n",
DRIVER_NAME, result);
goto fail_dmxdev;
}
dvb->fe_hw.source = DMX_FRONTEND_0;
result = dvb->demux.dmx.add_frontend(&dvb->demux.dmx, &dvb->fe_hw);
if (result < 0) {
printk(KERN_ERR "%s: add_frontend failed "
"(DMX_FRONTEND_0, errno = %d)\n", DRIVER_NAME, result);
goto fail_fe_hw;
}
dvb->fe_mem.source = DMX_MEMORY_FE;
result = dvb->demux.dmx.add_frontend(&dvb->demux.dmx, &dvb->fe_mem);
if (result < 0) {
printk(KERN_ERR "%s: add_frontend failed "
"(DMX_MEMORY_FE, errno = %d)\n", DRIVER_NAME, result);
goto fail_fe_mem;
}
result = dvb->demux.dmx.connect_frontend(&dvb->demux.dmx, &dvb->fe_hw);
if (result < 0) {
printk(KERN_ERR "%s: connect_frontend failed (errno = %d)\n",
DRIVER_NAME, result);
goto fail_fe_conn;
}
/* register network adapter */
dvb_net_init(&dvb->adapter, &dvb->net, &dvb->demux.dmx);
return 0;
fail_fe_conn:
dvb->demux.dmx.remove_frontend(&dvb->demux.dmx, &dvb->fe_mem);
fail_fe_mem:
dvb->demux.dmx.remove_frontend(&dvb->demux.dmx, &dvb->fe_hw);
fail_fe_hw:
dvb_dmxdev_release(&dvb->dmxdev);
fail_dmxdev:
dvb_dmx_release(&dvb->demux);
fail_dmx:
dvb_unregister_frontend(dvb->frontend);
fail_frontend:
dvb_frontend_detach(dvb->frontend);
dvb_unregister_adapter(&dvb->adapter);
fail_adapter:
return result;
}
void au0828_dvb_unregister(struct au0828_dev *dev)
{
struct au0828_dvb *dvb = &dev->dvb;
dprintk(1, "%s()\n", __func__);
if (dvb->frontend == NULL)
return;
dvb_net_release(&dvb->net);
dvb->demux.dmx.remove_frontend(&dvb->demux.dmx, &dvb->fe_mem);
dvb->demux.dmx.remove_frontend(&dvb->demux.dmx, &dvb->fe_hw);
dvb_dmxdev_release(&dvb->dmxdev);
dvb_dmx_release(&dvb->demux);
dvb_unregister_frontend(dvb->frontend);
dvb_frontend_detach(dvb->frontend);
dvb_unregister_adapter(&dvb->adapter);
}
/* All the DVB attach calls go here, this function get's modified
* for each new card. No other function in this file needs
* to change.
*/
int au0828_dvb_register(struct au0828_dev *dev)
{
struct au0828_dvb *dvb = &dev->dvb;
int ret;
dprintk(1, "%s()\n", __func__);
/* init frontend */
switch (dev->boardnr) {
case AU0828_BOARD_HAUPPAUGE_HVR850:
case AU0828_BOARD_HAUPPAUGE_HVR950Q:
dvb->frontend = dvb_attach(au8522_attach,
&hauppauge_hvr950q_config,
&dev->i2c_adap);
if (dvb->frontend != NULL)
dvb_attach(xc5000_attach, dvb->frontend, &dev->i2c_adap,
&hauppauge_hvr950q_tunerconfig);
break;
case AU0828_BOARD_HAUPPAUGE_HVR950Q_MXL:
dvb->frontend = dvb_attach(au8522_attach,
&hauppauge_hvr950q_config,
&dev->i2c_adap);
if (dvb->frontend != NULL)
dvb_attach(mxl5007t_attach, dvb->frontend,
&dev->i2c_adap, 0x60,
&mxl5007t_hvr950q_config);
break;
case AU0828_BOARD_HAUPPAUGE_WOODBURY:
dvb->frontend = dvb_attach(au8522_attach,
&hauppauge_woodbury_config,
&dev->i2c_adap);
if (dvb->frontend != NULL)
dvb_attach(tda18271_attach, dvb->frontend,
0x60, &dev->i2c_adap,
&hauppauge_woodbury_tunerconfig);
break;
case AU0828_BOARD_DVICO_FUSIONHDTV7:
dvb->frontend = dvb_attach(au8522_attach,
&fusionhdtv7usb_config,
&dev->i2c_adap);
if (dvb->frontend != NULL) {
dvb_attach(xc5000_attach, dvb->frontend,
&dev->i2c_adap,
&hauppauge_hvr950q_tunerconfig);
}
break;
default:
printk(KERN_WARNING "The frontend of your DVB/ATSC card "
"isn't supported yet\n");
break;
}
if (NULL == dvb->frontend) {
printk(KERN_ERR "%s() Frontend initialization failed\n",
__func__);
return -1;
}
/* define general-purpose callback pointer */
dvb->frontend->callback = au0828_tuner_callback;
/* register everything */
ret = dvb_register(dev);
if (ret < 0) {
if (dvb->frontend->ops.release)
dvb->frontend->ops.release(dvb->frontend);
return ret;
}
return 0;
}
| gpl-2.0 |
valir/android_kernel_samsung_chagalllte | arch/mips/ath79/dev-spi.c | 12353 | 1076 | /*
* Atheros AR71XX/AR724X/AR913X SPI controller device
*
* Copyright (C) 2008-2010 Gabor Juhos <juhosg@openwrt.org>
* Copyright (C) 2008 Imre Kaloz <kaloz@openwrt.org>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*/
#include <linux/platform_device.h>
#include <asm/mach-ath79/ar71xx_regs.h>
#include "dev-spi.h"
static struct resource ath79_spi_resources[] = {
{
.start = AR71XX_SPI_BASE,
.end = AR71XX_SPI_BASE + AR71XX_SPI_SIZE - 1,
.flags = IORESOURCE_MEM,
},
};
static struct platform_device ath79_spi_device = {
.name = "ath79-spi",
.id = -1,
.resource = ath79_spi_resources,
.num_resources = ARRAY_SIZE(ath79_spi_resources),
};
void __init ath79_register_spi(struct ath79_spi_platform_data *pdata,
struct spi_board_info const *info,
unsigned n)
{
spi_register_board_info(info, n);
ath79_spi_device.dev.platform_data = pdata;
platform_device_register(&ath79_spi_device);
}
| gpl-2.0 |
Nothing-Dev/Samsung_STE_Kernel-exp | arch/ia64/sn/kernel/sn2/cache.c | 14145 | 1233 | /*
* 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-2003, 2006 Silicon Graphics, Inc. All rights reserved.
*
*/
#include <linux/module.h>
#include <asm/pgalloc.h>
#include <asm/sn/arch.h>
/**
* sn_flush_all_caches - flush a range of address from all caches (incl. L4)
* @flush_addr: identity mapped region 7 address to start flushing
* @bytes: number of bytes to flush
*
* Flush a range of addresses from all caches including L4.
* All addresses fully or partially contained within
* @flush_addr to @flush_addr + @bytes are flushed
* from all caches.
*/
void
sn_flush_all_caches(long flush_addr, long bytes)
{
unsigned long addr = flush_addr;
/* SHub1 requires a cached address */
if (is_shub1() && (addr & RGN_BITS) == RGN_BASE(RGN_UNCACHED))
addr = (addr - RGN_BASE(RGN_UNCACHED)) + RGN_BASE(RGN_KERNEL);
flush_icache_range(addr, addr + bytes);
/*
* The last call may have returned before the caches
* were actually flushed, so we call it again to make
* sure.
*/
flush_icache_range(addr, addr + bytes);
mb();
}
EXPORT_SYMBOL(sn_flush_all_caches);
| gpl-2.0 |
Meninblack007/almighty_kernel | drivers/net/can/flexcan.c | 1602 | 31007 | /*
* flexcan.c - FLEXCAN CAN controller driver
*
* Copyright (c) 2005-2006 Varma Electronics Oy
* Copyright (c) 2009 Sascha Hauer, Pengutronix
* Copyright (c) 2010 Marc Kleine-Budde, Pengutronix
*
* Based on code originally by Andrey Volkov <avolkov@varma-el.com>
*
* LICENCE:
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation version 2.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/netdevice.h>
#include <linux/can.h>
#include <linux/can/dev.h>
#include <linux/can/error.h>
#include <linux/can/led.h>
#include <linux/can/platform/flexcan.h>
#include <linux/clk.h>
#include <linux/delay.h>
#include <linux/if_arp.h>
#include <linux/if_ether.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/platform_device.h>
#include <linux/pinctrl/consumer.h>
#define DRV_NAME "flexcan"
/* 8 for RX fifo and 2 error handling */
#define FLEXCAN_NAPI_WEIGHT (8 + 2)
/* FLEXCAN module configuration register (CANMCR) bits */
#define FLEXCAN_MCR_MDIS BIT(31)
#define FLEXCAN_MCR_FRZ BIT(30)
#define FLEXCAN_MCR_FEN BIT(29)
#define FLEXCAN_MCR_HALT BIT(28)
#define FLEXCAN_MCR_NOT_RDY BIT(27)
#define FLEXCAN_MCR_WAK_MSK BIT(26)
#define FLEXCAN_MCR_SOFTRST BIT(25)
#define FLEXCAN_MCR_FRZ_ACK BIT(24)
#define FLEXCAN_MCR_SUPV BIT(23)
#define FLEXCAN_MCR_SLF_WAK BIT(22)
#define FLEXCAN_MCR_WRN_EN BIT(21)
#define FLEXCAN_MCR_LPM_ACK BIT(20)
#define FLEXCAN_MCR_WAK_SRC BIT(19)
#define FLEXCAN_MCR_DOZE BIT(18)
#define FLEXCAN_MCR_SRX_DIS BIT(17)
#define FLEXCAN_MCR_BCC BIT(16)
#define FLEXCAN_MCR_LPRIO_EN BIT(13)
#define FLEXCAN_MCR_AEN BIT(12)
#define FLEXCAN_MCR_MAXMB(x) ((x) & 0x1f)
#define FLEXCAN_MCR_IDAM_A (0 << 8)
#define FLEXCAN_MCR_IDAM_B (1 << 8)
#define FLEXCAN_MCR_IDAM_C (2 << 8)
#define FLEXCAN_MCR_IDAM_D (3 << 8)
/* FLEXCAN control register (CANCTRL) bits */
#define FLEXCAN_CTRL_PRESDIV(x) (((x) & 0xff) << 24)
#define FLEXCAN_CTRL_RJW(x) (((x) & 0x03) << 22)
#define FLEXCAN_CTRL_PSEG1(x) (((x) & 0x07) << 19)
#define FLEXCAN_CTRL_PSEG2(x) (((x) & 0x07) << 16)
#define FLEXCAN_CTRL_BOFF_MSK BIT(15)
#define FLEXCAN_CTRL_ERR_MSK BIT(14)
#define FLEXCAN_CTRL_CLK_SRC BIT(13)
#define FLEXCAN_CTRL_LPB BIT(12)
#define FLEXCAN_CTRL_TWRN_MSK BIT(11)
#define FLEXCAN_CTRL_RWRN_MSK BIT(10)
#define FLEXCAN_CTRL_SMP BIT(7)
#define FLEXCAN_CTRL_BOFF_REC BIT(6)
#define FLEXCAN_CTRL_TSYN BIT(5)
#define FLEXCAN_CTRL_LBUF BIT(4)
#define FLEXCAN_CTRL_LOM BIT(3)
#define FLEXCAN_CTRL_PROPSEG(x) ((x) & 0x07)
#define FLEXCAN_CTRL_ERR_BUS (FLEXCAN_CTRL_ERR_MSK)
#define FLEXCAN_CTRL_ERR_STATE \
(FLEXCAN_CTRL_TWRN_MSK | FLEXCAN_CTRL_RWRN_MSK | \
FLEXCAN_CTRL_BOFF_MSK)
#define FLEXCAN_CTRL_ERR_ALL \
(FLEXCAN_CTRL_ERR_BUS | FLEXCAN_CTRL_ERR_STATE)
/* FLEXCAN error and status register (ESR) bits */
#define FLEXCAN_ESR_TWRN_INT BIT(17)
#define FLEXCAN_ESR_RWRN_INT BIT(16)
#define FLEXCAN_ESR_BIT1_ERR BIT(15)
#define FLEXCAN_ESR_BIT0_ERR BIT(14)
#define FLEXCAN_ESR_ACK_ERR BIT(13)
#define FLEXCAN_ESR_CRC_ERR BIT(12)
#define FLEXCAN_ESR_FRM_ERR BIT(11)
#define FLEXCAN_ESR_STF_ERR BIT(10)
#define FLEXCAN_ESR_TX_WRN BIT(9)
#define FLEXCAN_ESR_RX_WRN BIT(8)
#define FLEXCAN_ESR_IDLE BIT(7)
#define FLEXCAN_ESR_TXRX BIT(6)
#define FLEXCAN_EST_FLT_CONF_SHIFT (4)
#define FLEXCAN_ESR_FLT_CONF_MASK (0x3 << FLEXCAN_EST_FLT_CONF_SHIFT)
#define FLEXCAN_ESR_FLT_CONF_ACTIVE (0x0 << FLEXCAN_EST_FLT_CONF_SHIFT)
#define FLEXCAN_ESR_FLT_CONF_PASSIVE (0x1 << FLEXCAN_EST_FLT_CONF_SHIFT)
#define FLEXCAN_ESR_BOFF_INT BIT(2)
#define FLEXCAN_ESR_ERR_INT BIT(1)
#define FLEXCAN_ESR_WAK_INT BIT(0)
#define FLEXCAN_ESR_ERR_BUS \
(FLEXCAN_ESR_BIT1_ERR | FLEXCAN_ESR_BIT0_ERR | \
FLEXCAN_ESR_ACK_ERR | FLEXCAN_ESR_CRC_ERR | \
FLEXCAN_ESR_FRM_ERR | FLEXCAN_ESR_STF_ERR)
#define FLEXCAN_ESR_ERR_STATE \
(FLEXCAN_ESR_TWRN_INT | FLEXCAN_ESR_RWRN_INT | FLEXCAN_ESR_BOFF_INT)
#define FLEXCAN_ESR_ERR_ALL \
(FLEXCAN_ESR_ERR_BUS | FLEXCAN_ESR_ERR_STATE)
#define FLEXCAN_ESR_ALL_INT \
(FLEXCAN_ESR_TWRN_INT | FLEXCAN_ESR_RWRN_INT | \
FLEXCAN_ESR_BOFF_INT | FLEXCAN_ESR_ERR_INT)
/* FLEXCAN interrupt flag register (IFLAG) bits */
#define FLEXCAN_TX_BUF_ID 8
#define FLEXCAN_IFLAG_BUF(x) BIT(x)
#define FLEXCAN_IFLAG_RX_FIFO_OVERFLOW BIT(7)
#define FLEXCAN_IFLAG_RX_FIFO_WARN BIT(6)
#define FLEXCAN_IFLAG_RX_FIFO_AVAILABLE BIT(5)
#define FLEXCAN_IFLAG_DEFAULT \
(FLEXCAN_IFLAG_RX_FIFO_OVERFLOW | FLEXCAN_IFLAG_RX_FIFO_AVAILABLE | \
FLEXCAN_IFLAG_BUF(FLEXCAN_TX_BUF_ID))
/* FLEXCAN message buffers */
#define FLEXCAN_MB_CNT_CODE(x) (((x) & 0xf) << 24)
#define FLEXCAN_MB_CNT_SRR BIT(22)
#define FLEXCAN_MB_CNT_IDE BIT(21)
#define FLEXCAN_MB_CNT_RTR BIT(20)
#define FLEXCAN_MB_CNT_LENGTH(x) (((x) & 0xf) << 16)
#define FLEXCAN_MB_CNT_TIMESTAMP(x) ((x) & 0xffff)
#define FLEXCAN_MB_CODE_MASK (0xf0ffffff)
/*
* FLEXCAN hardware feature flags
*
* Below is some version info we got:
* SOC Version IP-Version Glitch- [TR]WRN_INT
* Filter? connected?
* MX25 FlexCAN2 03.00.00.00 no no
* MX28 FlexCAN2 03.00.04.00 yes yes
* MX35 FlexCAN2 03.00.00.00 no no
* MX53 FlexCAN2 03.00.00.00 yes no
* MX6s FlexCAN3 10.00.12.00 yes yes
*
* Some SOCs do not have the RX_WARN & TX_WARN interrupt line connected.
*/
#define FLEXCAN_HAS_V10_FEATURES BIT(1) /* For core version >= 10 */
#define FLEXCAN_HAS_BROKEN_ERR_STATE BIT(2) /* [TR]WRN_INT not connected */
/* Structure of the message buffer */
struct flexcan_mb {
u32 can_ctrl;
u32 can_id;
u32 data[2];
};
/* Structure of the hardware registers */
struct flexcan_regs {
u32 mcr; /* 0x00 */
u32 ctrl; /* 0x04 */
u32 timer; /* 0x08 */
u32 _reserved1; /* 0x0c */
u32 rxgmask; /* 0x10 */
u32 rx14mask; /* 0x14 */
u32 rx15mask; /* 0x18 */
u32 ecr; /* 0x1c */
u32 esr; /* 0x20 */
u32 imask2; /* 0x24 */
u32 imask1; /* 0x28 */
u32 iflag2; /* 0x2c */
u32 iflag1; /* 0x30 */
u32 crl2; /* 0x34 */
u32 esr2; /* 0x38 */
u32 imeur; /* 0x3c */
u32 lrfr; /* 0x40 */
u32 crcr; /* 0x44 */
u32 rxfgmask; /* 0x48 */
u32 rxfir; /* 0x4c */
u32 _reserved3[12];
struct flexcan_mb cantxfg[64];
};
struct flexcan_devtype_data {
u32 features; /* hardware controller features */
};
struct flexcan_priv {
struct can_priv can;
struct net_device *dev;
struct napi_struct napi;
void __iomem *base;
u32 reg_esr;
u32 reg_ctrl_default;
struct clk *clk_ipg;
struct clk *clk_per;
struct flexcan_platform_data *pdata;
const struct flexcan_devtype_data *devtype_data;
};
static struct flexcan_devtype_data fsl_p1010_devtype_data = {
.features = FLEXCAN_HAS_BROKEN_ERR_STATE,
};
static struct flexcan_devtype_data fsl_imx28_devtype_data;
static struct flexcan_devtype_data fsl_imx6q_devtype_data = {
.features = FLEXCAN_HAS_V10_FEATURES,
};
static const struct can_bittiming_const flexcan_bittiming_const = {
.name = DRV_NAME,
.tseg1_min = 4,
.tseg1_max = 16,
.tseg2_min = 2,
.tseg2_max = 8,
.sjw_max = 4,
.brp_min = 1,
.brp_max = 256,
.brp_inc = 1,
};
/*
* Abstract off the read/write for arm versus ppc.
*/
#if defined(__BIG_ENDIAN)
static inline u32 flexcan_read(void __iomem *addr)
{
return in_be32(addr);
}
static inline void flexcan_write(u32 val, void __iomem *addr)
{
out_be32(addr, val);
}
#else
static inline u32 flexcan_read(void __iomem *addr)
{
return readl(addr);
}
static inline void flexcan_write(u32 val, void __iomem *addr)
{
writel(val, addr);
}
#endif
/*
* Swtich transceiver on or off
*/
static void flexcan_transceiver_switch(const struct flexcan_priv *priv, int on)
{
if (priv->pdata && priv->pdata->transceiver_switch)
priv->pdata->transceiver_switch(on);
}
static inline int flexcan_has_and_handle_berr(const struct flexcan_priv *priv,
u32 reg_esr)
{
return (priv->can.ctrlmode & CAN_CTRLMODE_BERR_REPORTING) &&
(reg_esr & FLEXCAN_ESR_ERR_BUS);
}
static inline void flexcan_chip_enable(struct flexcan_priv *priv)
{
struct flexcan_regs __iomem *regs = priv->base;
u32 reg;
reg = flexcan_read(®s->mcr);
reg &= ~FLEXCAN_MCR_MDIS;
flexcan_write(reg, ®s->mcr);
udelay(10);
}
static inline void flexcan_chip_disable(struct flexcan_priv *priv)
{
struct flexcan_regs __iomem *regs = priv->base;
u32 reg;
reg = flexcan_read(®s->mcr);
reg |= FLEXCAN_MCR_MDIS;
flexcan_write(reg, ®s->mcr);
}
static int flexcan_get_berr_counter(const struct net_device *dev,
struct can_berr_counter *bec)
{
const struct flexcan_priv *priv = netdev_priv(dev);
struct flexcan_regs __iomem *regs = priv->base;
u32 reg = flexcan_read(®s->ecr);
bec->txerr = (reg >> 0) & 0xff;
bec->rxerr = (reg >> 8) & 0xff;
return 0;
}
static int flexcan_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
const struct flexcan_priv *priv = netdev_priv(dev);
struct flexcan_regs __iomem *regs = priv->base;
struct can_frame *cf = (struct can_frame *)skb->data;
u32 can_id;
u32 ctrl = FLEXCAN_MB_CNT_CODE(0xc) | (cf->can_dlc << 16);
if (can_dropped_invalid_skb(dev, skb))
return NETDEV_TX_OK;
netif_stop_queue(dev);
if (cf->can_id & CAN_EFF_FLAG) {
can_id = cf->can_id & CAN_EFF_MASK;
ctrl |= FLEXCAN_MB_CNT_IDE | FLEXCAN_MB_CNT_SRR;
} else {
can_id = (cf->can_id & CAN_SFF_MASK) << 18;
}
if (cf->can_id & CAN_RTR_FLAG)
ctrl |= FLEXCAN_MB_CNT_RTR;
if (cf->can_dlc > 0) {
u32 data = be32_to_cpup((__be32 *)&cf->data[0]);
flexcan_write(data, ®s->cantxfg[FLEXCAN_TX_BUF_ID].data[0]);
}
if (cf->can_dlc > 3) {
u32 data = be32_to_cpup((__be32 *)&cf->data[4]);
flexcan_write(data, ®s->cantxfg[FLEXCAN_TX_BUF_ID].data[1]);
}
can_put_echo_skb(skb, dev, 0);
flexcan_write(can_id, ®s->cantxfg[FLEXCAN_TX_BUF_ID].can_id);
flexcan_write(ctrl, ®s->cantxfg[FLEXCAN_TX_BUF_ID].can_ctrl);
return NETDEV_TX_OK;
}
static void do_bus_err(struct net_device *dev,
struct can_frame *cf, u32 reg_esr)
{
struct flexcan_priv *priv = netdev_priv(dev);
int rx_errors = 0, tx_errors = 0;
cf->can_id |= CAN_ERR_PROT | CAN_ERR_BUSERROR;
if (reg_esr & FLEXCAN_ESR_BIT1_ERR) {
netdev_dbg(dev, "BIT1_ERR irq\n");
cf->data[2] |= CAN_ERR_PROT_BIT1;
tx_errors = 1;
}
if (reg_esr & FLEXCAN_ESR_BIT0_ERR) {
netdev_dbg(dev, "BIT0_ERR irq\n");
cf->data[2] |= CAN_ERR_PROT_BIT0;
tx_errors = 1;
}
if (reg_esr & FLEXCAN_ESR_ACK_ERR) {
netdev_dbg(dev, "ACK_ERR irq\n");
cf->can_id |= CAN_ERR_ACK;
cf->data[3] |= CAN_ERR_PROT_LOC_ACK;
tx_errors = 1;
}
if (reg_esr & FLEXCAN_ESR_CRC_ERR) {
netdev_dbg(dev, "CRC_ERR irq\n");
cf->data[2] |= CAN_ERR_PROT_BIT;
cf->data[3] |= CAN_ERR_PROT_LOC_CRC_SEQ;
rx_errors = 1;
}
if (reg_esr & FLEXCAN_ESR_FRM_ERR) {
netdev_dbg(dev, "FRM_ERR irq\n");
cf->data[2] |= CAN_ERR_PROT_FORM;
rx_errors = 1;
}
if (reg_esr & FLEXCAN_ESR_STF_ERR) {
netdev_dbg(dev, "STF_ERR irq\n");
cf->data[2] |= CAN_ERR_PROT_STUFF;
rx_errors = 1;
}
priv->can.can_stats.bus_error++;
if (rx_errors)
dev->stats.rx_errors++;
if (tx_errors)
dev->stats.tx_errors++;
}
static int flexcan_poll_bus_err(struct net_device *dev, u32 reg_esr)
{
struct sk_buff *skb;
struct can_frame *cf;
skb = alloc_can_err_skb(dev, &cf);
if (unlikely(!skb))
return 0;
do_bus_err(dev, cf, reg_esr);
netif_receive_skb(skb);
dev->stats.rx_packets++;
dev->stats.rx_bytes += cf->can_dlc;
return 1;
}
static void do_state(struct net_device *dev,
struct can_frame *cf, enum can_state new_state)
{
struct flexcan_priv *priv = netdev_priv(dev);
struct can_berr_counter bec;
flexcan_get_berr_counter(dev, &bec);
switch (priv->can.state) {
case CAN_STATE_ERROR_ACTIVE:
/*
* from: ERROR_ACTIVE
* to : ERROR_WARNING, ERROR_PASSIVE, BUS_OFF
* => : there was a warning int
*/
if (new_state >= CAN_STATE_ERROR_WARNING &&
new_state <= CAN_STATE_BUS_OFF) {
netdev_dbg(dev, "Error Warning IRQ\n");
priv->can.can_stats.error_warning++;
cf->can_id |= CAN_ERR_CRTL;
cf->data[1] = (bec.txerr > bec.rxerr) ?
CAN_ERR_CRTL_TX_WARNING :
CAN_ERR_CRTL_RX_WARNING;
}
case CAN_STATE_ERROR_WARNING: /* fallthrough */
/*
* from: ERROR_ACTIVE, ERROR_WARNING
* to : ERROR_PASSIVE, BUS_OFF
* => : error passive int
*/
if (new_state >= CAN_STATE_ERROR_PASSIVE &&
new_state <= CAN_STATE_BUS_OFF) {
netdev_dbg(dev, "Error Passive IRQ\n");
priv->can.can_stats.error_passive++;
cf->can_id |= CAN_ERR_CRTL;
cf->data[1] = (bec.txerr > bec.rxerr) ?
CAN_ERR_CRTL_TX_PASSIVE :
CAN_ERR_CRTL_RX_PASSIVE;
}
break;
case CAN_STATE_BUS_OFF:
netdev_err(dev, "BUG! "
"hardware recovered automatically from BUS_OFF\n");
break;
default:
break;
}
/* process state changes depending on the new state */
switch (new_state) {
case CAN_STATE_ERROR_ACTIVE:
netdev_dbg(dev, "Error Active\n");
cf->can_id |= CAN_ERR_PROT;
cf->data[2] = CAN_ERR_PROT_ACTIVE;
break;
case CAN_STATE_BUS_OFF:
cf->can_id |= CAN_ERR_BUSOFF;
can_bus_off(dev);
break;
default:
break;
}
}
static int flexcan_poll_state(struct net_device *dev, u32 reg_esr)
{
struct flexcan_priv *priv = netdev_priv(dev);
struct sk_buff *skb;
struct can_frame *cf;
enum can_state new_state;
int flt;
flt = reg_esr & FLEXCAN_ESR_FLT_CONF_MASK;
if (likely(flt == FLEXCAN_ESR_FLT_CONF_ACTIVE)) {
if (likely(!(reg_esr & (FLEXCAN_ESR_TX_WRN |
FLEXCAN_ESR_RX_WRN))))
new_state = CAN_STATE_ERROR_ACTIVE;
else
new_state = CAN_STATE_ERROR_WARNING;
} else if (unlikely(flt == FLEXCAN_ESR_FLT_CONF_PASSIVE))
new_state = CAN_STATE_ERROR_PASSIVE;
else
new_state = CAN_STATE_BUS_OFF;
/* state hasn't changed */
if (likely(new_state == priv->can.state))
return 0;
skb = alloc_can_err_skb(dev, &cf);
if (unlikely(!skb))
return 0;
do_state(dev, cf, new_state);
priv->can.state = new_state;
netif_receive_skb(skb);
dev->stats.rx_packets++;
dev->stats.rx_bytes += cf->can_dlc;
return 1;
}
static void flexcan_read_fifo(const struct net_device *dev,
struct can_frame *cf)
{
const struct flexcan_priv *priv = netdev_priv(dev);
struct flexcan_regs __iomem *regs = priv->base;
struct flexcan_mb __iomem *mb = ®s->cantxfg[0];
u32 reg_ctrl, reg_id;
reg_ctrl = flexcan_read(&mb->can_ctrl);
reg_id = flexcan_read(&mb->can_id);
if (reg_ctrl & FLEXCAN_MB_CNT_IDE)
cf->can_id = ((reg_id >> 0) & CAN_EFF_MASK) | CAN_EFF_FLAG;
else
cf->can_id = (reg_id >> 18) & CAN_SFF_MASK;
if (reg_ctrl & FLEXCAN_MB_CNT_RTR)
cf->can_id |= CAN_RTR_FLAG;
cf->can_dlc = get_can_dlc((reg_ctrl >> 16) & 0xf);
*(__be32 *)(cf->data + 0) = cpu_to_be32(flexcan_read(&mb->data[0]));
*(__be32 *)(cf->data + 4) = cpu_to_be32(flexcan_read(&mb->data[1]));
/* mark as read */
flexcan_write(FLEXCAN_IFLAG_RX_FIFO_AVAILABLE, ®s->iflag1);
flexcan_read(®s->timer);
}
static int flexcan_read_frame(struct net_device *dev)
{
struct net_device_stats *stats = &dev->stats;
struct can_frame *cf;
struct sk_buff *skb;
skb = alloc_can_skb(dev, &cf);
if (unlikely(!skb)) {
stats->rx_dropped++;
return 0;
}
flexcan_read_fifo(dev, cf);
netif_receive_skb(skb);
stats->rx_packets++;
stats->rx_bytes += cf->can_dlc;
can_led_event(dev, CAN_LED_EVENT_RX);
return 1;
}
static int flexcan_poll(struct napi_struct *napi, int quota)
{
struct net_device *dev = napi->dev;
const struct flexcan_priv *priv = netdev_priv(dev);
struct flexcan_regs __iomem *regs = priv->base;
u32 reg_iflag1, reg_esr;
int work_done = 0;
/*
* The error bits are cleared on read,
* use saved value from irq handler.
*/
reg_esr = flexcan_read(®s->esr) | priv->reg_esr;
/* handle state changes */
work_done += flexcan_poll_state(dev, reg_esr);
/* handle RX-FIFO */
reg_iflag1 = flexcan_read(®s->iflag1);
while (reg_iflag1 & FLEXCAN_IFLAG_RX_FIFO_AVAILABLE &&
work_done < quota) {
work_done += flexcan_read_frame(dev);
reg_iflag1 = flexcan_read(®s->iflag1);
}
/* report bus errors */
if (flexcan_has_and_handle_berr(priv, reg_esr) && work_done < quota)
work_done += flexcan_poll_bus_err(dev, reg_esr);
if (work_done < quota) {
napi_complete(napi);
/* enable IRQs */
flexcan_write(FLEXCAN_IFLAG_DEFAULT, ®s->imask1);
flexcan_write(priv->reg_ctrl_default, ®s->ctrl);
}
return work_done;
}
static irqreturn_t flexcan_irq(int irq, void *dev_id)
{
struct net_device *dev = dev_id;
struct net_device_stats *stats = &dev->stats;
struct flexcan_priv *priv = netdev_priv(dev);
struct flexcan_regs __iomem *regs = priv->base;
u32 reg_iflag1, reg_esr;
reg_iflag1 = flexcan_read(®s->iflag1);
reg_esr = flexcan_read(®s->esr);
/* ACK all bus error and state change IRQ sources */
if (reg_esr & FLEXCAN_ESR_ALL_INT)
flexcan_write(reg_esr & FLEXCAN_ESR_ALL_INT, ®s->esr);
/*
* schedule NAPI in case of:
* - rx IRQ
* - state change IRQ
* - bus error IRQ and bus error reporting is activated
*/
if ((reg_iflag1 & FLEXCAN_IFLAG_RX_FIFO_AVAILABLE) ||
(reg_esr & FLEXCAN_ESR_ERR_STATE) ||
flexcan_has_and_handle_berr(priv, reg_esr)) {
/*
* The error bits are cleared on read,
* save them for later use.
*/
priv->reg_esr = reg_esr & FLEXCAN_ESR_ERR_BUS;
flexcan_write(FLEXCAN_IFLAG_DEFAULT &
~FLEXCAN_IFLAG_RX_FIFO_AVAILABLE, ®s->imask1);
flexcan_write(priv->reg_ctrl_default & ~FLEXCAN_CTRL_ERR_ALL,
®s->ctrl);
napi_schedule(&priv->napi);
}
/* FIFO overflow */
if (reg_iflag1 & FLEXCAN_IFLAG_RX_FIFO_OVERFLOW) {
flexcan_write(FLEXCAN_IFLAG_RX_FIFO_OVERFLOW, ®s->iflag1);
dev->stats.rx_over_errors++;
dev->stats.rx_errors++;
}
/* transmission complete interrupt */
if (reg_iflag1 & (1 << FLEXCAN_TX_BUF_ID)) {
stats->tx_bytes += can_get_echo_skb(dev, 0);
stats->tx_packets++;
can_led_event(dev, CAN_LED_EVENT_TX);
flexcan_write((1 << FLEXCAN_TX_BUF_ID), ®s->iflag1);
netif_wake_queue(dev);
}
return IRQ_HANDLED;
}
static void flexcan_set_bittiming(struct net_device *dev)
{
const struct flexcan_priv *priv = netdev_priv(dev);
const struct can_bittiming *bt = &priv->can.bittiming;
struct flexcan_regs __iomem *regs = priv->base;
u32 reg;
reg = flexcan_read(®s->ctrl);
reg &= ~(FLEXCAN_CTRL_PRESDIV(0xff) |
FLEXCAN_CTRL_RJW(0x3) |
FLEXCAN_CTRL_PSEG1(0x7) |
FLEXCAN_CTRL_PSEG2(0x7) |
FLEXCAN_CTRL_PROPSEG(0x7) |
FLEXCAN_CTRL_LPB |
FLEXCAN_CTRL_SMP |
FLEXCAN_CTRL_LOM);
reg |= FLEXCAN_CTRL_PRESDIV(bt->brp - 1) |
FLEXCAN_CTRL_PSEG1(bt->phase_seg1 - 1) |
FLEXCAN_CTRL_PSEG2(bt->phase_seg2 - 1) |
FLEXCAN_CTRL_RJW(bt->sjw - 1) |
FLEXCAN_CTRL_PROPSEG(bt->prop_seg - 1);
if (priv->can.ctrlmode & CAN_CTRLMODE_LOOPBACK)
reg |= FLEXCAN_CTRL_LPB;
if (priv->can.ctrlmode & CAN_CTRLMODE_LISTENONLY)
reg |= FLEXCAN_CTRL_LOM;
if (priv->can.ctrlmode & CAN_CTRLMODE_3_SAMPLES)
reg |= FLEXCAN_CTRL_SMP;
netdev_info(dev, "writing ctrl=0x%08x\n", reg);
flexcan_write(reg, ®s->ctrl);
/* print chip status */
netdev_dbg(dev, "%s: mcr=0x%08x ctrl=0x%08x\n", __func__,
flexcan_read(®s->mcr), flexcan_read(®s->ctrl));
}
/*
* flexcan_chip_start
*
* this functions is entered with clocks enabled
*
*/
static int flexcan_chip_start(struct net_device *dev)
{
struct flexcan_priv *priv = netdev_priv(dev);
struct flexcan_regs __iomem *regs = priv->base;
int err;
u32 reg_mcr, reg_ctrl;
/* enable module */
flexcan_chip_enable(priv);
/* soft reset */
flexcan_write(FLEXCAN_MCR_SOFTRST, ®s->mcr);
udelay(10);
reg_mcr = flexcan_read(®s->mcr);
if (reg_mcr & FLEXCAN_MCR_SOFTRST) {
netdev_err(dev, "Failed to softreset can module (mcr=0x%08x)\n",
reg_mcr);
err = -ENODEV;
goto out;
}
flexcan_set_bittiming(dev);
/*
* MCR
*
* enable freeze
* enable fifo
* halt now
* only supervisor access
* enable warning int
* choose format C
* disable local echo
*
*/
reg_mcr = flexcan_read(®s->mcr);
reg_mcr &= ~FLEXCAN_MCR_MAXMB(0xff);
reg_mcr |= FLEXCAN_MCR_FRZ | FLEXCAN_MCR_FEN | FLEXCAN_MCR_HALT |
FLEXCAN_MCR_SUPV | FLEXCAN_MCR_WRN_EN |
FLEXCAN_MCR_IDAM_C | FLEXCAN_MCR_SRX_DIS |
FLEXCAN_MCR_MAXMB(FLEXCAN_TX_BUF_ID);
netdev_dbg(dev, "%s: writing mcr=0x%08x", __func__, reg_mcr);
flexcan_write(reg_mcr, ®s->mcr);
/*
* CTRL
*
* disable timer sync feature
*
* disable auto busoff recovery
* transmit lowest buffer first
*
* enable tx and rx warning interrupt
* enable bus off interrupt
* (== FLEXCAN_CTRL_ERR_STATE)
*/
reg_ctrl = flexcan_read(®s->ctrl);
reg_ctrl &= ~FLEXCAN_CTRL_TSYN;
reg_ctrl |= FLEXCAN_CTRL_BOFF_REC | FLEXCAN_CTRL_LBUF |
FLEXCAN_CTRL_ERR_STATE;
/*
* enable the "error interrupt" (FLEXCAN_CTRL_ERR_MSK),
* on most Flexcan cores, too. Otherwise we don't get
* any error warning or passive interrupts.
*/
if (priv->devtype_data->features & FLEXCAN_HAS_BROKEN_ERR_STATE ||
priv->can.ctrlmode & CAN_CTRLMODE_BERR_REPORTING)
reg_ctrl |= FLEXCAN_CTRL_ERR_MSK;
/* save for later use */
priv->reg_ctrl_default = reg_ctrl;
netdev_dbg(dev, "%s: writing ctrl=0x%08x", __func__, reg_ctrl);
flexcan_write(reg_ctrl, ®s->ctrl);
/* Abort any pending TX, mark Mailbox as INACTIVE */
flexcan_write(FLEXCAN_MB_CNT_CODE(0x4),
®s->cantxfg[FLEXCAN_TX_BUF_ID].can_ctrl);
/* acceptance mask/acceptance code (accept everything) */
flexcan_write(0x0, ®s->rxgmask);
flexcan_write(0x0, ®s->rx14mask);
flexcan_write(0x0, ®s->rx15mask);
if (priv->devtype_data->features & FLEXCAN_HAS_V10_FEATURES)
flexcan_write(0x0, ®s->rxfgmask);
flexcan_transceiver_switch(priv, 1);
/* synchronize with the can bus */
reg_mcr = flexcan_read(®s->mcr);
reg_mcr &= ~FLEXCAN_MCR_HALT;
flexcan_write(reg_mcr, ®s->mcr);
priv->can.state = CAN_STATE_ERROR_ACTIVE;
/* enable FIFO interrupts */
flexcan_write(FLEXCAN_IFLAG_DEFAULT, ®s->imask1);
/* print chip status */
netdev_dbg(dev, "%s: reading mcr=0x%08x ctrl=0x%08x\n", __func__,
flexcan_read(®s->mcr), flexcan_read(®s->ctrl));
return 0;
out:
flexcan_chip_disable(priv);
return err;
}
/*
* flexcan_chip_stop
*
* this functions is entered with clocks enabled
*
*/
static void flexcan_chip_stop(struct net_device *dev)
{
struct flexcan_priv *priv = netdev_priv(dev);
struct flexcan_regs __iomem *regs = priv->base;
u32 reg;
/* Disable all interrupts */
flexcan_write(0, ®s->imask1);
/* Disable + halt module */
reg = flexcan_read(®s->mcr);
reg |= FLEXCAN_MCR_MDIS | FLEXCAN_MCR_HALT;
flexcan_write(reg, ®s->mcr);
flexcan_transceiver_switch(priv, 0);
priv->can.state = CAN_STATE_STOPPED;
return;
}
static int flexcan_open(struct net_device *dev)
{
struct flexcan_priv *priv = netdev_priv(dev);
int err;
clk_prepare_enable(priv->clk_ipg);
clk_prepare_enable(priv->clk_per);
err = open_candev(dev);
if (err)
goto out;
err = request_irq(dev->irq, flexcan_irq, IRQF_SHARED, dev->name, dev);
if (err)
goto out_close;
/* start chip and queuing */
err = flexcan_chip_start(dev);
if (err)
goto out_free_irq;
can_led_event(dev, CAN_LED_EVENT_OPEN);
napi_enable(&priv->napi);
netif_start_queue(dev);
return 0;
out_free_irq:
free_irq(dev->irq, dev);
out_close:
close_candev(dev);
out:
clk_disable_unprepare(priv->clk_per);
clk_disable_unprepare(priv->clk_ipg);
return err;
}
static int flexcan_close(struct net_device *dev)
{
struct flexcan_priv *priv = netdev_priv(dev);
netif_stop_queue(dev);
napi_disable(&priv->napi);
flexcan_chip_stop(dev);
free_irq(dev->irq, dev);
clk_disable_unprepare(priv->clk_per);
clk_disable_unprepare(priv->clk_ipg);
close_candev(dev);
can_led_event(dev, CAN_LED_EVENT_STOP);
return 0;
}
static int flexcan_set_mode(struct net_device *dev, enum can_mode mode)
{
int err;
switch (mode) {
case CAN_MODE_START:
err = flexcan_chip_start(dev);
if (err)
return err;
netif_wake_queue(dev);
break;
default:
return -EOPNOTSUPP;
}
return 0;
}
static const struct net_device_ops flexcan_netdev_ops = {
.ndo_open = flexcan_open,
.ndo_stop = flexcan_close,
.ndo_start_xmit = flexcan_start_xmit,
};
static int register_flexcandev(struct net_device *dev)
{
struct flexcan_priv *priv = netdev_priv(dev);
struct flexcan_regs __iomem *regs = priv->base;
u32 reg, err;
clk_prepare_enable(priv->clk_ipg);
clk_prepare_enable(priv->clk_per);
/* select "bus clock", chip must be disabled */
flexcan_chip_disable(priv);
reg = flexcan_read(®s->ctrl);
reg |= FLEXCAN_CTRL_CLK_SRC;
flexcan_write(reg, ®s->ctrl);
flexcan_chip_enable(priv);
/* set freeze, halt and activate FIFO, restrict register access */
reg = flexcan_read(®s->mcr);
reg |= FLEXCAN_MCR_FRZ | FLEXCAN_MCR_HALT |
FLEXCAN_MCR_FEN | FLEXCAN_MCR_SUPV;
flexcan_write(reg, ®s->mcr);
/*
* Currently we only support newer versions of this core
* featuring a RX FIFO. Older cores found on some Coldfire
* derivates are not yet supported.
*/
reg = flexcan_read(®s->mcr);
if (!(reg & FLEXCAN_MCR_FEN)) {
netdev_err(dev, "Could not enable RX FIFO, unsupported core\n");
err = -ENODEV;
goto out;
}
err = register_candev(dev);
out:
/* disable core and turn off clocks */
flexcan_chip_disable(priv);
clk_disable_unprepare(priv->clk_per);
clk_disable_unprepare(priv->clk_ipg);
return err;
}
static void unregister_flexcandev(struct net_device *dev)
{
unregister_candev(dev);
}
static const struct of_device_id flexcan_of_match[] = {
{ .compatible = "fsl,imx6q-flexcan", .data = &fsl_imx6q_devtype_data, },
{ .compatible = "fsl,imx28-flexcan", .data = &fsl_imx28_devtype_data, },
{ .compatible = "fsl,p1010-flexcan", .data = &fsl_p1010_devtype_data, },
{ /* sentinel */ },
};
MODULE_DEVICE_TABLE(of, flexcan_of_match);
static const struct platform_device_id flexcan_id_table[] = {
{ .name = "flexcan", .driver_data = (kernel_ulong_t)&fsl_p1010_devtype_data, },
{ /* sentinel */ },
};
MODULE_DEVICE_TABLE(platform, flexcan_id_table);
static int flexcan_probe(struct platform_device *pdev)
{
const struct of_device_id *of_id;
const struct flexcan_devtype_data *devtype_data;
struct net_device *dev;
struct flexcan_priv *priv;
struct resource *mem;
struct clk *clk_ipg = NULL, *clk_per = NULL;
struct pinctrl *pinctrl;
void __iomem *base;
resource_size_t mem_size;
int err, irq;
u32 clock_freq = 0;
pinctrl = devm_pinctrl_get_select_default(&pdev->dev);
if (IS_ERR(pinctrl))
return PTR_ERR(pinctrl);
if (pdev->dev.of_node)
of_property_read_u32(pdev->dev.of_node,
"clock-frequency", &clock_freq);
if (!clock_freq) {
clk_ipg = devm_clk_get(&pdev->dev, "ipg");
if (IS_ERR(clk_ipg)) {
dev_err(&pdev->dev, "no ipg clock defined\n");
err = PTR_ERR(clk_ipg);
goto failed_clock;
}
clock_freq = clk_get_rate(clk_ipg);
clk_per = devm_clk_get(&pdev->dev, "per");
if (IS_ERR(clk_per)) {
dev_err(&pdev->dev, "no per clock defined\n");
err = PTR_ERR(clk_per);
goto failed_clock;
}
}
mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
irq = platform_get_irq(pdev, 0);
if (!mem || irq <= 0) {
err = -ENODEV;
goto failed_get;
}
mem_size = resource_size(mem);
if (!request_mem_region(mem->start, mem_size, pdev->name)) {
err = -EBUSY;
goto failed_get;
}
base = ioremap(mem->start, mem_size);
if (!base) {
err = -ENOMEM;
goto failed_map;
}
dev = alloc_candev(sizeof(struct flexcan_priv), 1);
if (!dev) {
err = -ENOMEM;
goto failed_alloc;
}
of_id = of_match_device(flexcan_of_match, &pdev->dev);
if (of_id) {
devtype_data = of_id->data;
} else if (pdev->id_entry->driver_data) {
devtype_data = (struct flexcan_devtype_data *)
pdev->id_entry->driver_data;
} else {
err = -ENODEV;
goto failed_devtype;
}
dev->netdev_ops = &flexcan_netdev_ops;
dev->irq = irq;
dev->flags |= IFF_ECHO;
priv = netdev_priv(dev);
priv->can.clock.freq = clock_freq;
priv->can.bittiming_const = &flexcan_bittiming_const;
priv->can.do_set_mode = flexcan_set_mode;
priv->can.do_get_berr_counter = flexcan_get_berr_counter;
priv->can.ctrlmode_supported = CAN_CTRLMODE_LOOPBACK |
CAN_CTRLMODE_LISTENONLY | CAN_CTRLMODE_3_SAMPLES |
CAN_CTRLMODE_BERR_REPORTING;
priv->base = base;
priv->dev = dev;
priv->clk_ipg = clk_ipg;
priv->clk_per = clk_per;
priv->pdata = pdev->dev.platform_data;
priv->devtype_data = devtype_data;
netif_napi_add(dev, &priv->napi, flexcan_poll, FLEXCAN_NAPI_WEIGHT);
dev_set_drvdata(&pdev->dev, dev);
SET_NETDEV_DEV(dev, &pdev->dev);
err = register_flexcandev(dev);
if (err) {
dev_err(&pdev->dev, "registering netdev failed\n");
goto failed_register;
}
devm_can_led_init(dev);
dev_info(&pdev->dev, "device registered (reg_base=%p, irq=%d)\n",
priv->base, dev->irq);
return 0;
failed_register:
failed_devtype:
free_candev(dev);
failed_alloc:
iounmap(base);
failed_map:
release_mem_region(mem->start, mem_size);
failed_get:
failed_clock:
return err;
}
static int flexcan_remove(struct platform_device *pdev)
{
struct net_device *dev = platform_get_drvdata(pdev);
struct flexcan_priv *priv = netdev_priv(dev);
struct resource *mem;
unregister_flexcandev(dev);
platform_set_drvdata(pdev, NULL);
iounmap(priv->base);
mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
release_mem_region(mem->start, resource_size(mem));
free_candev(dev);
return 0;
}
#ifdef CONFIG_PM
static int flexcan_suspend(struct platform_device *pdev, pm_message_t state)
{
struct net_device *dev = platform_get_drvdata(pdev);
struct flexcan_priv *priv = netdev_priv(dev);
flexcan_chip_disable(priv);
if (netif_running(dev)) {
netif_stop_queue(dev);
netif_device_detach(dev);
}
priv->can.state = CAN_STATE_SLEEPING;
return 0;
}
static int flexcan_resume(struct platform_device *pdev)
{
struct net_device *dev = platform_get_drvdata(pdev);
struct flexcan_priv *priv = netdev_priv(dev);
priv->can.state = CAN_STATE_ERROR_ACTIVE;
if (netif_running(dev)) {
netif_device_attach(dev);
netif_start_queue(dev);
}
flexcan_chip_enable(priv);
return 0;
}
#else
#define flexcan_suspend NULL
#define flexcan_resume NULL
#endif
static struct platform_driver flexcan_driver = {
.driver = {
.name = DRV_NAME,
.owner = THIS_MODULE,
.of_match_table = flexcan_of_match,
},
.probe = flexcan_probe,
.remove = flexcan_remove,
.suspend = flexcan_suspend,
.resume = flexcan_resume,
.id_table = flexcan_id_table,
};
module_platform_driver(flexcan_driver);
MODULE_AUTHOR("Sascha Hauer <kernel@pengutronix.de>, "
"Marc Kleine-Budde <kernel@pengutronix.de>");
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("CAN port driver for flexcan based chip");
| gpl-2.0 |
GrandPrime/android_kernel_samsung_msm8916-caf | arch/arm/mach-s5pv210/mach-smdkv210.c | 2114 | 8579 | /* linux/arch/arm/mach-s5pv210/mach-smdkv210.c
*
* Copyright (c) 2010 Samsung Electronics Co., Ltd.
* http://www.samsung.com/
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/i2c.h>
#include <linux/init.h>
#include <linux/serial_core.h>
#include <linux/device.h>
#include <linux/dm9000.h>
#include <linux/fb.h>
#include <linux/gpio.h>
#include <linux/delay.h>
#include <linux/pwm_backlight.h>
#include <linux/platform_data/s3c-hsotg.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/setup.h>
#include <asm/mach-types.h>
#include <video/platform_lcd.h>
#include <video/samsung_fimd.h>
#include <mach/map.h>
#include <mach/regs-clock.h>
#include <plat/regs-serial.h>
#include <plat/regs-srom.h>
#include <plat/gpio-cfg.h>
#include <plat/devs.h>
#include <plat/cpu.h>
#include <plat/adc.h>
#include <linux/platform_data/touchscreen-s3c2410.h>
#include <linux/platform_data/ata-samsung_cf.h>
#include <linux/platform_data/i2c-s3c2410.h>
#include <plat/keypad.h>
#include <plat/pm.h>
#include <plat/fb.h>
#include <plat/samsung-time.h>
#include <plat/backlight.h>
#include <plat/mfc.h>
#include <plat/clock.h>
#include "common.h"
/* Following are default values for UCON, ULCON and UFCON UART registers */
#define SMDKV210_UCON_DEFAULT (S3C2410_UCON_TXILEVEL | \
S3C2410_UCON_RXILEVEL | \
S3C2410_UCON_TXIRQMODE | \
S3C2410_UCON_RXIRQMODE | \
S3C2410_UCON_RXFIFO_TOI | \
S3C2443_UCON_RXERR_IRQEN)
#define SMDKV210_ULCON_DEFAULT S3C2410_LCON_CS8
#define SMDKV210_UFCON_DEFAULT (S3C2410_UFCON_FIFOMODE | \
S5PV210_UFCON_TXTRIG4 | \
S5PV210_UFCON_RXTRIG4)
static struct s3c2410_uartcfg smdkv210_uartcfgs[] __initdata = {
[0] = {
.hwport = 0,
.flags = 0,
.ucon = SMDKV210_UCON_DEFAULT,
.ulcon = SMDKV210_ULCON_DEFAULT,
.ufcon = SMDKV210_UFCON_DEFAULT,
},
[1] = {
.hwport = 1,
.flags = 0,
.ucon = SMDKV210_UCON_DEFAULT,
.ulcon = SMDKV210_ULCON_DEFAULT,
.ufcon = SMDKV210_UFCON_DEFAULT,
},
[2] = {
.hwport = 2,
.flags = 0,
.ucon = SMDKV210_UCON_DEFAULT,
.ulcon = SMDKV210_ULCON_DEFAULT,
.ufcon = SMDKV210_UFCON_DEFAULT,
},
[3] = {
.hwport = 3,
.flags = 0,
.ucon = SMDKV210_UCON_DEFAULT,
.ulcon = SMDKV210_ULCON_DEFAULT,
.ufcon = SMDKV210_UFCON_DEFAULT,
},
};
static struct s3c_ide_platdata smdkv210_ide_pdata __initdata = {
.setup_gpio = s5pv210_ide_setup_gpio,
};
static uint32_t smdkv210_keymap[] __initdata = {
/* KEY(row, col, keycode) */
KEY(0, 3, KEY_1), KEY(0, 4, KEY_2), KEY(0, 5, KEY_3),
KEY(0, 6, KEY_4), KEY(0, 7, KEY_5),
KEY(1, 3, KEY_A), KEY(1, 4, KEY_B), KEY(1, 5, KEY_C),
KEY(1, 6, KEY_D), KEY(1, 7, KEY_E)
};
static struct matrix_keymap_data smdkv210_keymap_data __initdata = {
.keymap = smdkv210_keymap,
.keymap_size = ARRAY_SIZE(smdkv210_keymap),
};
static struct samsung_keypad_platdata smdkv210_keypad_data __initdata = {
.keymap_data = &smdkv210_keymap_data,
.rows = 8,
.cols = 8,
};
static struct resource smdkv210_dm9000_resources[] = {
[0] = DEFINE_RES_MEM(S5PV210_PA_SROM_BANK5, 1),
[1] = DEFINE_RES_MEM(S5PV210_PA_SROM_BANK5 + 2, 1),
[2] = DEFINE_RES_NAMED(IRQ_EINT(9), 1, NULL, IORESOURCE_IRQ \
| IORESOURCE_IRQ_HIGHLEVEL),
};
static struct dm9000_plat_data smdkv210_dm9000_platdata = {
.flags = DM9000_PLATF_16BITONLY | DM9000_PLATF_NO_EEPROM,
.dev_addr = { 0x00, 0x09, 0xc0, 0xff, 0xec, 0x48 },
};
static struct platform_device smdkv210_dm9000 = {
.name = "dm9000",
.id = -1,
.num_resources = ARRAY_SIZE(smdkv210_dm9000_resources),
.resource = smdkv210_dm9000_resources,
.dev = {
.platform_data = &smdkv210_dm9000_platdata,
},
};
static void smdkv210_lte480wv_set_power(struct plat_lcd_data *pd,
unsigned int power)
{
if (power) {
#if !defined(CONFIG_BACKLIGHT_PWM)
gpio_request_one(S5PV210_GPD0(3), GPIOF_OUT_INIT_HIGH, "GPD0");
gpio_free(S5PV210_GPD0(3));
#endif
/* fire nRESET on power up */
gpio_request_one(S5PV210_GPH0(6), GPIOF_OUT_INIT_HIGH, "GPH0");
gpio_set_value(S5PV210_GPH0(6), 0);
mdelay(10);
gpio_set_value(S5PV210_GPH0(6), 1);
mdelay(10);
gpio_free(S5PV210_GPH0(6));
} else {
#if !defined(CONFIG_BACKLIGHT_PWM)
gpio_request_one(S5PV210_GPD0(3), GPIOF_OUT_INIT_LOW, "GPD0");
gpio_free(S5PV210_GPD0(3));
#endif
}
}
static struct plat_lcd_data smdkv210_lcd_lte480wv_data = {
.set_power = smdkv210_lte480wv_set_power,
};
static struct platform_device smdkv210_lcd_lte480wv = {
.name = "platform-lcd",
.dev.parent = &s3c_device_fb.dev,
.dev.platform_data = &smdkv210_lcd_lte480wv_data,
};
static struct s3c_fb_pd_win smdkv210_fb_win0 = {
.max_bpp = 32,
.default_bpp = 24,
.xres = 800,
.yres = 480,
};
static struct fb_videomode smdkv210_lcd_timing = {
.left_margin = 13,
.right_margin = 8,
.upper_margin = 7,
.lower_margin = 5,
.hsync_len = 3,
.vsync_len = 1,
.xres = 800,
.yres = 480,
};
static struct s3c_fb_platdata smdkv210_lcd0_pdata __initdata = {
.win[0] = &smdkv210_fb_win0,
.vtiming = &smdkv210_lcd_timing,
.vidcon0 = VIDCON0_VIDOUT_RGB | VIDCON0_PNRMODE_RGB,
.vidcon1 = VIDCON1_INV_HSYNC | VIDCON1_INV_VSYNC,
.setup_gpio = s5pv210_fb_gpio_setup_24bpp,
};
/* USB OTG */
static struct s3c_hsotg_plat smdkv210_hsotg_pdata;
static struct platform_device *smdkv210_devices[] __initdata = {
&s3c_device_adc,
&s3c_device_cfcon,
&s3c_device_fb,
&s3c_device_hsmmc0,
&s3c_device_hsmmc1,
&s3c_device_hsmmc2,
&s3c_device_hsmmc3,
&s3c_device_i2c0,
&s3c_device_i2c1,
&s3c_device_i2c2,
&s3c_device_rtc,
&s3c_device_ts,
&s3c_device_usb_hsotg,
&s3c_device_wdt,
&s5p_device_fimc0,
&s5p_device_fimc1,
&s5p_device_fimc2,
&s5p_device_fimc_md,
&s5p_device_jpeg,
&s5p_device_mfc,
&s5p_device_mfc_l,
&s5p_device_mfc_r,
&s5pv210_device_ac97,
&s5pv210_device_iis0,
&s5pv210_device_spdif,
&samsung_asoc_idma,
&samsung_device_keypad,
&smdkv210_dm9000,
&smdkv210_lcd_lte480wv,
};
static void __init smdkv210_dm9000_init(void)
{
unsigned int tmp;
gpio_request(S5PV210_MP01(5), "nCS5");
s3c_gpio_cfgpin(S5PV210_MP01(5), S3C_GPIO_SFN(2));
gpio_free(S5PV210_MP01(5));
tmp = (5 << S5P_SROM_BCX__TACC__SHIFT);
__raw_writel(tmp, S5P_SROM_BC5);
tmp = __raw_readl(S5P_SROM_BW);
tmp &= (S5P_SROM_BW__CS_MASK << S5P_SROM_BW__NCS5__SHIFT);
tmp |= (1 << S5P_SROM_BW__NCS5__SHIFT);
__raw_writel(tmp, S5P_SROM_BW);
}
static struct i2c_board_info smdkv210_i2c_devs0[] __initdata = {
{ I2C_BOARD_INFO("24c08", 0x50), }, /* Samsung S524AD0XD1 */
{ I2C_BOARD_INFO("wm8580", 0x1b), },
};
static struct i2c_board_info smdkv210_i2c_devs1[] __initdata = {
/* To Be Updated */
};
static struct i2c_board_info smdkv210_i2c_devs2[] __initdata = {
/* To Be Updated */
};
/* LCD Backlight data */
static struct samsung_bl_gpio_info smdkv210_bl_gpio_info = {
.no = S5PV210_GPD0(3),
.func = S3C_GPIO_SFN(2),
};
static struct platform_pwm_backlight_data smdkv210_bl_data = {
.pwm_id = 3,
.pwm_period_ns = 1000,
};
static void __init smdkv210_map_io(void)
{
s5pv210_init_io(NULL, 0);
s3c24xx_init_clocks(clk_xusbxti.rate);
s3c24xx_init_uarts(smdkv210_uartcfgs, ARRAY_SIZE(smdkv210_uartcfgs));
samsung_set_timer_source(SAMSUNG_PWM2, SAMSUNG_PWM4);
}
static void __init smdkv210_reserve(void)
{
s5p_mfc_reserve_mem(0x43000000, 8 << 20, 0x51000000, 8 << 20);
}
static void __init smdkv210_machine_init(void)
{
s3c_pm_init();
smdkv210_dm9000_init();
samsung_keypad_set_platdata(&smdkv210_keypad_data);
s3c24xx_ts_set_platdata(NULL);
s3c_i2c0_set_platdata(NULL);
s3c_i2c1_set_platdata(NULL);
s3c_i2c2_set_platdata(NULL);
i2c_register_board_info(0, smdkv210_i2c_devs0,
ARRAY_SIZE(smdkv210_i2c_devs0));
i2c_register_board_info(1, smdkv210_i2c_devs1,
ARRAY_SIZE(smdkv210_i2c_devs1));
i2c_register_board_info(2, smdkv210_i2c_devs2,
ARRAY_SIZE(smdkv210_i2c_devs2));
s3c_ide_set_platdata(&smdkv210_ide_pdata);
s3c_fb_set_platdata(&smdkv210_lcd0_pdata);
samsung_bl_set(&smdkv210_bl_gpio_info, &smdkv210_bl_data);
s3c_hsotg_set_platdata(&smdkv210_hsotg_pdata);
platform_add_devices(smdkv210_devices, ARRAY_SIZE(smdkv210_devices));
}
MACHINE_START(SMDKV210, "SMDKV210")
/* Maintainer: Kukjin Kim <kgene.kim@samsung.com> */
.atag_offset = 0x100,
.init_irq = s5pv210_init_irq,
.map_io = smdkv210_map_io,
.init_machine = smdkv210_machine_init,
.init_time = samsung_timer_init,
.restart = s5pv210_restart,
.reserve = &smdkv210_reserve,
MACHINE_END
| gpl-2.0 |
nushor/samsung_aries_ics_OLD | arch/mips/mti-malta/malta-init.c | 2370 | 9852 | /*
* Copyright (C) 1999, 2000, 2004, 2005 MIPS Technologies, Inc.
* All rights reserved.
* Authors: Carsten Langgaard <carstenl@mips.com>
* Maciej W. Rozycki <macro@mips.com>
*
* This program is free software; you can distribute it and/or modify it
* under the terms of the GNU General Public License (Version 2) as
* published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston MA 02111-1307, USA.
*
* PROM library initialisation code.
*/
#include <linux/init.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <asm/bootinfo.h>
#include <asm/gt64120.h>
#include <asm/io.h>
#include <asm/system.h>
#include <asm/cacheflush.h>
#include <asm/traps.h>
#include <asm/gcmpregs.h>
#include <asm/mips-boards/prom.h>
#include <asm/mips-boards/generic.h>
#include <asm/mips-boards/bonito64.h>
#include <asm/mips-boards/msc01_pci.h>
#include <asm/mips-boards/malta.h>
int prom_argc;
int *_prom_argv, *_prom_envp;
/*
* YAMON (32-bit PROM) pass arguments and environment as 32-bit pointer.
* This macro take care of sign extension, if running in 64-bit mode.
*/
#define prom_envp(index) ((char *)(long)_prom_envp[(index)])
int init_debug;
static int mips_revision_corid;
int mips_revision_sconid;
/* Bonito64 system controller register base. */
unsigned long _pcictrl_bonito;
unsigned long _pcictrl_bonito_pcicfg;
/* GT64120 system controller register base */
unsigned long _pcictrl_gt64120;
/* MIPS System controller register base */
unsigned long _pcictrl_msc;
char *prom_getenv(char *envname)
{
/*
* Return a pointer to the given environment variable.
* In 64-bit mode: we're using 64-bit pointers, but all pointers
* in the PROM structures are only 32-bit, so we need some
* workarounds, if we are running in 64-bit mode.
*/
int i, index=0;
i = strlen(envname);
while (prom_envp(index)) {
if(strncmp(envname, prom_envp(index), i) == 0) {
return(prom_envp(index+1));
}
index += 2;
}
return NULL;
}
static inline unsigned char str2hexnum(unsigned char c)
{
if (c >= '0' && c <= '9')
return c - '0';
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
return 0; /* foo */
}
static inline void str2eaddr(unsigned char *ea, unsigned char *str)
{
int i;
for (i = 0; i < 6; i++) {
unsigned char num;
if((*str == '.') || (*str == ':'))
str++;
num = str2hexnum(*str++) << 4;
num |= (str2hexnum(*str++));
ea[i] = num;
}
}
int get_ethernet_addr(char *ethernet_addr)
{
char *ethaddr_str;
ethaddr_str = prom_getenv("ethaddr");
if (!ethaddr_str) {
printk("ethaddr not set in boot prom\n");
return -1;
}
str2eaddr(ethernet_addr, ethaddr_str);
if (init_debug > 1) {
int i;
printk("get_ethernet_addr: ");
for (i=0; i<5; i++)
printk("%02x:", (unsigned char)*(ethernet_addr+i));
printk("%02x\n", *(ethernet_addr+i));
}
return 0;
}
#ifdef CONFIG_SERIAL_8250_CONSOLE
static void __init console_config(void)
{
char console_string[40];
int baud = 0;
char parity = '\0', bits = '\0', flow = '\0';
char *s;
if ((strstr(prom_getcmdline(), "console=")) == NULL) {
s = prom_getenv("modetty0");
if (s) {
while (*s >= '0' && *s <= '9')
baud = baud*10 + *s++ - '0';
if (*s == ',') s++;
if (*s) parity = *s++;
if (*s == ',') s++;
if (*s) bits = *s++;
if (*s == ',') s++;
if (*s == 'h') flow = 'r';
}
if (baud == 0)
baud = 38400;
if (parity != 'n' && parity != 'o' && parity != 'e')
parity = 'n';
if (bits != '7' && bits != '8')
bits = '8';
if (flow == '\0')
flow = 'r';
sprintf(console_string, " console=ttyS0,%d%c%c%c", baud, parity, bits, flow);
strcat(prom_getcmdline(), console_string);
pr_info("Config serial console:%s\n", console_string);
}
}
#endif
static void __init mips_nmi_setup(void)
{
void *base;
extern char except_vec_nmi;
base = cpu_has_veic ?
(void *)(CAC_BASE + 0xa80) :
(void *)(CAC_BASE + 0x380);
memcpy(base, &except_vec_nmi, 0x80);
flush_icache_range((unsigned long)base, (unsigned long)base + 0x80);
}
static void __init mips_ejtag_setup(void)
{
void *base;
extern char except_vec_ejtag_debug;
base = cpu_has_veic ?
(void *)(CAC_BASE + 0xa00) :
(void *)(CAC_BASE + 0x300);
memcpy(base, &except_vec_ejtag_debug, 0x80);
flush_icache_range((unsigned long)base, (unsigned long)base + 0x80);
}
extern struct plat_smp_ops msmtc_smp_ops;
void __init prom_init(void)
{
prom_argc = fw_arg0;
_prom_argv = (int *) fw_arg1;
_prom_envp = (int *) fw_arg2;
mips_display_message("LINUX");
/*
* early setup of _pcictrl_bonito so that we can determine
* the system controller on a CORE_EMUL board
*/
_pcictrl_bonito = (unsigned long)ioremap(BONITO_REG_BASE, BONITO_REG_SIZE);
mips_revision_corid = MIPS_REVISION_CORID;
if (mips_revision_corid == MIPS_REVISION_CORID_CORE_EMUL) {
if (BONITO_PCIDID == 0x0001df53 ||
BONITO_PCIDID == 0x0003df53)
mips_revision_corid = MIPS_REVISION_CORID_CORE_EMUL_BON;
else
mips_revision_corid = MIPS_REVISION_CORID_CORE_EMUL_MSC;
}
mips_revision_sconid = MIPS_REVISION_SCONID;
if (mips_revision_sconid == MIPS_REVISION_SCON_OTHER) {
switch (mips_revision_corid) {
case MIPS_REVISION_CORID_QED_RM5261:
case MIPS_REVISION_CORID_CORE_LV:
case MIPS_REVISION_CORID_CORE_FPGA:
case MIPS_REVISION_CORID_CORE_FPGAR2:
mips_revision_sconid = MIPS_REVISION_SCON_GT64120;
break;
case MIPS_REVISION_CORID_CORE_EMUL_BON:
case MIPS_REVISION_CORID_BONITO64:
case MIPS_REVISION_CORID_CORE_20K:
mips_revision_sconid = MIPS_REVISION_SCON_BONITO;
break;
case MIPS_REVISION_CORID_CORE_MSC:
case MIPS_REVISION_CORID_CORE_FPGA2:
case MIPS_REVISION_CORID_CORE_24K:
/*
* SOCit/ROCit support is essentially identical
* but make an attempt to distinguish them
*/
mips_revision_sconid = MIPS_REVISION_SCON_SOCIT;
break;
case MIPS_REVISION_CORID_CORE_FPGA3:
case MIPS_REVISION_CORID_CORE_FPGA4:
case MIPS_REVISION_CORID_CORE_FPGA5:
case MIPS_REVISION_CORID_CORE_EMUL_MSC:
default:
/* See above */
mips_revision_sconid = MIPS_REVISION_SCON_ROCIT;
break;
}
}
switch (mips_revision_sconid) {
u32 start, map, mask, data;
case MIPS_REVISION_SCON_GT64120:
/*
* Setup the North bridge to do Master byte-lane swapping
* when running in bigendian.
*/
_pcictrl_gt64120 = (unsigned long)ioremap(MIPS_GT_BASE, 0x2000);
#ifdef CONFIG_CPU_LITTLE_ENDIAN
GT_WRITE(GT_PCI0_CMD_OFS, GT_PCI0_CMD_MBYTESWAP_BIT |
GT_PCI0_CMD_SBYTESWAP_BIT);
#else
GT_WRITE(GT_PCI0_CMD_OFS, 0);
#endif
/* Fix up PCI I/O mapping if necessary (for Atlas). */
start = GT_READ(GT_PCI0IOLD_OFS);
map = GT_READ(GT_PCI0IOREMAP_OFS);
if ((start & map) != 0) {
map &= ~start;
GT_WRITE(GT_PCI0IOREMAP_OFS, map);
}
set_io_port_base(MALTA_GT_PORT_BASE);
break;
case MIPS_REVISION_SCON_BONITO:
_pcictrl_bonito_pcicfg = (unsigned long)ioremap(BONITO_PCICFG_BASE, BONITO_PCICFG_SIZE);
/*
* Disable Bonito IOBC.
*/
BONITO_PCIMEMBASECFG = BONITO_PCIMEMBASECFG &
~(BONITO_PCIMEMBASECFG_MEMBASE0_CACHED |
BONITO_PCIMEMBASECFG_MEMBASE1_CACHED);
/*
* Setup the North bridge to do Master byte-lane swapping
* when running in bigendian.
*/
#ifdef CONFIG_CPU_LITTLE_ENDIAN
BONITO_BONGENCFG = BONITO_BONGENCFG &
~(BONITO_BONGENCFG_MSTRBYTESWAP |
BONITO_BONGENCFG_BYTESWAP);
#else
BONITO_BONGENCFG = BONITO_BONGENCFG |
BONITO_BONGENCFG_MSTRBYTESWAP |
BONITO_BONGENCFG_BYTESWAP;
#endif
set_io_port_base(MALTA_BONITO_PORT_BASE);
break;
case MIPS_REVISION_SCON_SOCIT:
case MIPS_REVISION_SCON_ROCIT:
_pcictrl_msc = (unsigned long)ioremap(MIPS_MSC01_PCI_REG_BASE, 0x2000);
mips_pci_controller:
mb();
MSC_READ(MSC01_PCI_CFG, data);
MSC_WRITE(MSC01_PCI_CFG, data & ~MSC01_PCI_CFG_EN_BIT);
wmb();
/* Fix up lane swapping. */
#ifdef CONFIG_CPU_LITTLE_ENDIAN
MSC_WRITE(MSC01_PCI_SWAP, MSC01_PCI_SWAP_NOSWAP);
#else
MSC_WRITE(MSC01_PCI_SWAP,
MSC01_PCI_SWAP_BYTESWAP << MSC01_PCI_SWAP_IO_SHF |
MSC01_PCI_SWAP_BYTESWAP << MSC01_PCI_SWAP_MEM_SHF |
MSC01_PCI_SWAP_BYTESWAP << MSC01_PCI_SWAP_BAR0_SHF);
#endif
/* Fix up target memory mapping. */
MSC_READ(MSC01_PCI_BAR0, mask);
MSC_WRITE(MSC01_PCI_P2SCMSKL, mask & MSC01_PCI_BAR0_SIZE_MSK);
/* Don't handle target retries indefinitely. */
if ((data & MSC01_PCI_CFG_MAXRTRY_MSK) ==
MSC01_PCI_CFG_MAXRTRY_MSK)
data = (data & ~(MSC01_PCI_CFG_MAXRTRY_MSK <<
MSC01_PCI_CFG_MAXRTRY_SHF)) |
((MSC01_PCI_CFG_MAXRTRY_MSK - 1) <<
MSC01_PCI_CFG_MAXRTRY_SHF);
wmb();
MSC_WRITE(MSC01_PCI_CFG, data);
mb();
set_io_port_base(MALTA_MSC_PORT_BASE);
break;
case MIPS_REVISION_SCON_SOCITSC:
case MIPS_REVISION_SCON_SOCITSCP:
_pcictrl_msc = (unsigned long)ioremap(MIPS_SOCITSC_PCI_REG_BASE, 0x2000);
goto mips_pci_controller;
default:
/* Unknown system controller */
mips_display_message("SC Error");
while (1); /* We die here... */
}
board_nmi_handler_setup = mips_nmi_setup;
board_ejtag_handler_setup = mips_ejtag_setup;
prom_init_cmdline();
prom_meminit();
#ifdef CONFIG_SERIAL_8250_CONSOLE
console_config();
#endif
#ifdef CONFIG_MIPS_CMP
/* Early detection of CMP support */
if (gcmp_probe(GCMP_BASE_ADDR, GCMP_ADDRSPACE_SZ))
register_smp_ops(&cmp_smp_ops);
else
#endif
#ifdef CONFIG_MIPS_MT_SMP
register_smp_ops(&vsmp_smp_ops);
#endif
#ifdef CONFIG_MIPS_MT_SMTC
register_smp_ops(&msmtc_smp_ops);
#endif
}
| gpl-2.0 |
Dazzworld/android_kernel_zte_hn8916 | drivers/i2c/busses/i2c-sis630.c | 2370 | 14915 | /*
Copyright (c) 2002,2003 Alexander Malysh <amalysh@web.de>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
Status: beta
Supports:
SIS 630
SIS 730
SIS 964
Notable differences between chips:
+------------------------+--------------------+-------------------+
| | SIS630/730 | SIS964 |
+------------------------+--------------------+-------------------+
| Clock | 14kHz/56kHz | 55.56kHz/27.78kHz |
| SMBus registers offset | 0x80 | 0xE0 |
| SMB_CNT | Bit 1 = Slave Busy | Bit 1 = Bus probe |
| (not used yet) | Bit 3 is reserved | Bit 3 = Last byte |
| SMB_PCOUNT | Offset + 0x06 | Offset + 0x14 |
| SMB_COUNT | 4:0 bits | 5:0 bits |
+------------------------+--------------------+-------------------+
(Other differences don't affect the functions provided by the driver)
Note: we assume there can only be one device, with one SMBus interface.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/pci.h>
#include <linux/ioport.h>
#include <linux/init.h>
#include <linux/i2c.h>
#include <linux/acpi.h>
#include <linux/io.h>
/* SIS964 id is defined here as we are the only file using it */
#define PCI_DEVICE_ID_SI_964 0x0964
/* SIS630/730/964 SMBus registers */
#define SMB_STS 0x00 /* status */
#define SMB_CNT 0x02 /* control */
#define SMBHOST_CNT 0x03 /* host control */
#define SMB_ADDR 0x04 /* address */
#define SMB_CMD 0x05 /* command */
#define SMB_COUNT 0x07 /* byte count */
#define SMB_BYTE 0x08 /* ~0x8F data byte field */
/* SMB_STS register */
#define BYTE_DONE_STS 0x10 /* Byte Done Status / Block Array */
#define SMBCOL_STS 0x04 /* Collision */
#define SMBERR_STS 0x02 /* Device error */
/* SMB_CNT register */
#define MSTO_EN 0x40 /* Host Master Timeout Enable */
#define SMBCLK_SEL 0x20 /* Host master clock selection */
#define SMB_PROBE 0x02 /* Bus Probe/Slave busy */
#define SMB_HOSTBUSY 0x01 /* Host Busy */
/* SMBHOST_CNT register */
#define SMB_KILL 0x20 /* Kill */
#define SMB_START 0x10 /* Start */
/* register count for request_region
* As we don't use SMB_PCOUNT, 20 is ok for SiS630 and SiS964
*/
#define SIS630_SMB_IOREGION 20
/* PCI address constants */
/* acpi base address register */
#define SIS630_ACPI_BASE_REG 0x74
/* bios control register */
#define SIS630_BIOS_CTL_REG 0x40
/* Other settings */
#define MAX_TIMEOUT 500
/* SIS630 constants */
#define SIS630_QUICK 0x00
#define SIS630_BYTE 0x01
#define SIS630_BYTE_DATA 0x02
#define SIS630_WORD_DATA 0x03
#define SIS630_PCALL 0x04
#define SIS630_BLOCK_DATA 0x05
static struct pci_driver sis630_driver;
/* insmod parameters */
static bool high_clock;
static bool force;
module_param(high_clock, bool, 0);
MODULE_PARM_DESC(high_clock,
"Set Host Master Clock to 56KHz (default 14KHz) (SIS630/730 only).");
module_param(force, bool, 0);
MODULE_PARM_DESC(force, "Forcibly enable the SIS630. DANGEROUS!");
/* SMBus base adress */
static unsigned short smbus_base;
/* supported chips */
static int supported[] = {
PCI_DEVICE_ID_SI_630,
PCI_DEVICE_ID_SI_730,
PCI_DEVICE_ID_SI_760,
0 /* terminates the list */
};
static inline u8 sis630_read(u8 reg)
{
return inb(smbus_base + reg);
}
static inline void sis630_write(u8 reg, u8 data)
{
outb(data, smbus_base + reg);
}
static int sis630_transaction_start(struct i2c_adapter *adap, int size,
u8 *oldclock)
{
int temp;
/* Make sure the SMBus host is ready to start transmitting. */
temp = sis630_read(SMB_CNT);
if ((temp & (SMB_PROBE | SMB_HOSTBUSY)) != 0x00) {
dev_dbg(&adap->dev, "SMBus busy (%02x). Resetting...\n", temp);
/* kill smbus transaction */
sis630_write(SMBHOST_CNT, SMB_KILL);
temp = sis630_read(SMB_CNT);
if (temp & (SMB_PROBE | SMB_HOSTBUSY)) {
dev_dbg(&adap->dev, "Failed! (%02x)\n", temp);
return -EBUSY;
} else {
dev_dbg(&adap->dev, "Successful!\n");
}
}
/* save old clock, so we can prevent machine for hung */
*oldclock = sis630_read(SMB_CNT);
dev_dbg(&adap->dev, "saved clock 0x%02x\n", *oldclock);
/* disable timeout interrupt,
* set Host Master Clock to 56KHz if requested */
if (high_clock)
sis630_write(SMB_CNT, SMBCLK_SEL);
else
sis630_write(SMB_CNT, (*oldclock & ~MSTO_EN));
/* clear all sticky bits */
temp = sis630_read(SMB_STS);
sis630_write(SMB_STS, temp & 0x1e);
/* start the transaction by setting bit 4 and size */
sis630_write(SMBHOST_CNT, SMB_START | (size & 0x07));
return 0;
}
static int sis630_transaction_wait(struct i2c_adapter *adap, int size)
{
int temp, result = 0, timeout = 0;
/* We will always wait for a fraction of a second! */
do {
msleep(1);
temp = sis630_read(SMB_STS);
/* check if block transmitted */
if (size == SIS630_BLOCK_DATA && (temp & BYTE_DONE_STS))
break;
} while (!(temp & 0x0e) && (timeout++ < MAX_TIMEOUT));
/* If the SMBus is still busy, we give up */
if (timeout > MAX_TIMEOUT) {
dev_dbg(&adap->dev, "SMBus Timeout!\n");
result = -ETIMEDOUT;
}
if (temp & SMBERR_STS) {
dev_dbg(&adap->dev, "Error: Failed bus transaction\n");
result = -ENXIO;
}
if (temp & SMBCOL_STS) {
dev_err(&adap->dev, "Bus collision!\n");
result = -EAGAIN;
}
return result;
}
static void sis630_transaction_end(struct i2c_adapter *adap, u8 oldclock)
{
/* clear all status "sticky" bits */
sis630_write(SMB_STS, 0xFF);
dev_dbg(&adap->dev,
"SMB_CNT before clock restore 0x%02x\n", sis630_read(SMB_CNT));
/*
* restore old Host Master Clock if high_clock is set
* and oldclock was not 56KHz
*/
if (high_clock && !(oldclock & SMBCLK_SEL))
sis630_write(SMB_CNT, sis630_read(SMB_CNT) & ~SMBCLK_SEL);
dev_dbg(&adap->dev,
"SMB_CNT after clock restore 0x%02x\n", sis630_read(SMB_CNT));
}
static int sis630_transaction(struct i2c_adapter *adap, int size)
{
int result = 0;
u8 oldclock = 0;
result = sis630_transaction_start(adap, size, &oldclock);
if (!result) {
result = sis630_transaction_wait(adap, size);
sis630_transaction_end(adap, oldclock);
}
return result;
}
static int sis630_block_data(struct i2c_adapter *adap,
union i2c_smbus_data *data, int read_write)
{
int i, len = 0, rc = 0;
u8 oldclock = 0;
if (read_write == I2C_SMBUS_WRITE) {
len = data->block[0];
if (len < 0)
len = 0;
else if (len > 32)
len = 32;
sis630_write(SMB_COUNT, len);
for (i = 1; i <= len; i++) {
dev_dbg(&adap->dev,
"set data 0x%02x\n", data->block[i]);
/* set data */
sis630_write(SMB_BYTE + (i - 1) % 8, data->block[i]);
if (i == 8 || (len < 8 && i == len)) {
dev_dbg(&adap->dev,
"start trans len=%d i=%d\n", len, i);
/* first transaction */
rc = sis630_transaction_start(adap,
SIS630_BLOCK_DATA, &oldclock);
if (rc)
return rc;
} else if ((i - 1) % 8 == 7 || i == len) {
dev_dbg(&adap->dev,
"trans_wait len=%d i=%d\n", len, i);
if (i > 8) {
dev_dbg(&adap->dev,
"clear smbary_sts"
" len=%d i=%d\n", len, i);
/*
If this is not first transaction,
we must clear sticky bit.
clear SMBARY_STS
*/
sis630_write(SMB_STS, BYTE_DONE_STS);
}
rc = sis630_transaction_wait(adap,
SIS630_BLOCK_DATA);
if (rc) {
dev_dbg(&adap->dev,
"trans_wait failed\n");
break;
}
}
}
} else {
/* read request */
data->block[0] = len = 0;
rc = sis630_transaction_start(adap,
SIS630_BLOCK_DATA, &oldclock);
if (rc)
return rc;
do {
rc = sis630_transaction_wait(adap, SIS630_BLOCK_DATA);
if (rc) {
dev_dbg(&adap->dev, "trans_wait failed\n");
break;
}
/* if this first transaction then read byte count */
if (len == 0)
data->block[0] = sis630_read(SMB_COUNT);
/* just to be sure */
if (data->block[0] > 32)
data->block[0] = 32;
dev_dbg(&adap->dev,
"block data read len=0x%x\n", data->block[0]);
for (i = 0; i < 8 && len < data->block[0]; i++, len++) {
dev_dbg(&adap->dev,
"read i=%d len=%d\n", i, len);
data->block[len + 1] = sis630_read(SMB_BYTE +
i);
}
dev_dbg(&adap->dev,
"clear smbary_sts len=%d i=%d\n", len, i);
/* clear SMBARY_STS */
sis630_write(SMB_STS, BYTE_DONE_STS);
} while (len < data->block[0]);
}
sis630_transaction_end(adap, oldclock);
return rc;
}
/* Return negative errno on error. */
static s32 sis630_access(struct i2c_adapter *adap, u16 addr,
unsigned short flags, char read_write,
u8 command, int size, union i2c_smbus_data *data)
{
int status;
switch (size) {
case I2C_SMBUS_QUICK:
sis630_write(SMB_ADDR,
((addr & 0x7f) << 1) | (read_write & 0x01));
size = SIS630_QUICK;
break;
case I2C_SMBUS_BYTE:
sis630_write(SMB_ADDR,
((addr & 0x7f) << 1) | (read_write & 0x01));
if (read_write == I2C_SMBUS_WRITE)
sis630_write(SMB_CMD, command);
size = SIS630_BYTE;
break;
case I2C_SMBUS_BYTE_DATA:
sis630_write(SMB_ADDR,
((addr & 0x7f) << 1) | (read_write & 0x01));
sis630_write(SMB_CMD, command);
if (read_write == I2C_SMBUS_WRITE)
sis630_write(SMB_BYTE, data->byte);
size = SIS630_BYTE_DATA;
break;
case I2C_SMBUS_PROC_CALL:
case I2C_SMBUS_WORD_DATA:
sis630_write(SMB_ADDR,
((addr & 0x7f) << 1) | (read_write & 0x01));
sis630_write(SMB_CMD, command);
if (read_write == I2C_SMBUS_WRITE) {
sis630_write(SMB_BYTE, data->word & 0xff);
sis630_write(SMB_BYTE + 1, (data->word & 0xff00) >> 8);
}
size = (size == I2C_SMBUS_PROC_CALL ?
SIS630_PCALL : SIS630_WORD_DATA);
break;
case I2C_SMBUS_BLOCK_DATA:
sis630_write(SMB_ADDR,
((addr & 0x7f) << 1) | (read_write & 0x01));
sis630_write(SMB_CMD, command);
size = SIS630_BLOCK_DATA;
return sis630_block_data(adap, data, read_write);
default:
dev_warn(&adap->dev, "Unsupported transaction %d\n", size);
return -EOPNOTSUPP;
}
status = sis630_transaction(adap, size);
if (status)
return status;
if ((size != SIS630_PCALL) &&
((read_write == I2C_SMBUS_WRITE) || (size == SIS630_QUICK))) {
return 0;
}
switch (size) {
case SIS630_BYTE:
case SIS630_BYTE_DATA:
data->byte = sis630_read(SMB_BYTE);
break;
case SIS630_PCALL:
case SIS630_WORD_DATA:
data->word = sis630_read(SMB_BYTE) +
(sis630_read(SMB_BYTE + 1) << 8);
break;
}
return 0;
}
static u32 sis630_func(struct i2c_adapter *adapter)
{
return I2C_FUNC_SMBUS_QUICK | I2C_FUNC_SMBUS_BYTE |
I2C_FUNC_SMBUS_BYTE_DATA | I2C_FUNC_SMBUS_WORD_DATA |
I2C_FUNC_SMBUS_PROC_CALL | I2C_FUNC_SMBUS_BLOCK_DATA;
}
static int sis630_setup(struct pci_dev *sis630_dev)
{
unsigned char b;
struct pci_dev *dummy = NULL;
int retval, i;
/* acpi base address */
unsigned short acpi_base;
/* check for supported SiS devices */
for (i = 0; supported[i] > 0; i++) {
dummy = pci_get_device(PCI_VENDOR_ID_SI, supported[i], dummy);
if (dummy)
break; /* found */
}
if (dummy) {
pci_dev_put(dummy);
} else if (force) {
dev_err(&sis630_dev->dev,
"WARNING: Can't detect SIS630 compatible device, but "
"loading because of force option enabled\n");
} else {
return -ENODEV;
}
/*
Enable ACPI first , so we can accsess reg 74-75
in acpi io space and read acpi base addr
*/
if (pci_read_config_byte(sis630_dev, SIS630_BIOS_CTL_REG, &b)) {
dev_err(&sis630_dev->dev, "Error: Can't read bios ctl reg\n");
retval = -ENODEV;
goto exit;
}
/* if ACPI already enabled , do nothing */
if (!(b & 0x80) &&
pci_write_config_byte(sis630_dev, SIS630_BIOS_CTL_REG, b | 0x80)) {
dev_err(&sis630_dev->dev, "Error: Can't enable ACPI\n");
retval = -ENODEV;
goto exit;
}
/* Determine the ACPI base address */
if (pci_read_config_word(sis630_dev,
SIS630_ACPI_BASE_REG, &acpi_base)) {
dev_err(&sis630_dev->dev,
"Error: Can't determine ACPI base address\n");
retval = -ENODEV;
goto exit;
}
dev_dbg(&sis630_dev->dev, "ACPI base at 0x%04hx\n", acpi_base);
if (supported[i] == PCI_DEVICE_ID_SI_760)
smbus_base = acpi_base + 0xE0;
else
smbus_base = acpi_base + 0x80;
dev_dbg(&sis630_dev->dev, "SMBus base at 0x%04hx\n", smbus_base);
retval = acpi_check_region(smbus_base + SMB_STS, SIS630_SMB_IOREGION,
sis630_driver.name);
if (retval)
goto exit;
/* Everything is happy, let's grab the memory and set things up. */
if (!request_region(smbus_base + SMB_STS, SIS630_SMB_IOREGION,
sis630_driver.name)) {
dev_err(&sis630_dev->dev,
"I/O Region 0x%04hx-0x%04hx for SMBus already in use.\n",
smbus_base + SMB_STS,
smbus_base + SMB_STS + SIS630_SMB_IOREGION - 1);
retval = -EBUSY;
goto exit;
}
retval = 0;
exit:
if (retval)
smbus_base = 0;
return retval;
}
static const struct i2c_algorithm smbus_algorithm = {
.smbus_xfer = sis630_access,
.functionality = sis630_func,
};
static struct i2c_adapter sis630_adapter = {
.owner = THIS_MODULE,
.class = I2C_CLASS_HWMON | I2C_CLASS_SPD,
.algo = &smbus_algorithm,
.retries = 3
};
static DEFINE_PCI_DEVICE_TABLE(sis630_ids) = {
{ PCI_DEVICE(PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_503) },
{ PCI_DEVICE(PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_LPC) },
{ PCI_DEVICE(PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_964) },
{ 0, }
};
MODULE_DEVICE_TABLE(pci, sis630_ids);
static int sis630_probe(struct pci_dev *dev, const struct pci_device_id *id)
{
if (sis630_setup(dev)) {
dev_err(&dev->dev,
"SIS630 compatible bus not detected, "
"module not inserted.\n");
return -ENODEV;
}
/* set up the sysfs linkage to our parent device */
sis630_adapter.dev.parent = &dev->dev;
snprintf(sis630_adapter.name, sizeof(sis630_adapter.name),
"SMBus SIS630 adapter at %04hx", smbus_base + SMB_STS);
return i2c_add_adapter(&sis630_adapter);
}
static void sis630_remove(struct pci_dev *dev)
{
if (smbus_base) {
i2c_del_adapter(&sis630_adapter);
release_region(smbus_base + SMB_STS, SIS630_SMB_IOREGION);
smbus_base = 0;
}
}
static struct pci_driver sis630_driver = {
.name = "sis630_smbus",
.id_table = sis630_ids,
.probe = sis630_probe,
.remove = sis630_remove,
};
module_pci_driver(sis630_driver);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Alexander Malysh <amalysh@web.de>");
MODULE_DESCRIPTION("SIS630 SMBus driver");
| gpl-2.0 |
ZTE-Dev/android_kernel_zte_p892e10 | drivers/net/wireless/rtlwifi/rtl8192cu/rf.c | 2882 | 15015 | /******************************************************************************
*
* 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 "reg.h"
#include "def.h"
#include "phy.h"
#include "rf.h"
#include "dm.h"
static bool _rtl92c_phy_rf6052_config_parafile(struct ieee80211_hw *hw);
void rtl92cu_phy_rf6052_set_bandwidth(struct ieee80211_hw *hw, u8 bandwidth)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_phy *rtlphy = &(rtlpriv->phy);
switch (bandwidth) {
case HT_CHANNEL_WIDTH_20:
rtlphy->rfreg_chnlval[0] = ((rtlphy->rfreg_chnlval[0] &
0xfffff3ff) | 0x0400);
rtl_set_rfreg(hw, RF90_PATH_A, RF_CHNLBW, RFREG_OFFSET_MASK,
rtlphy->rfreg_chnlval[0]);
break;
case HT_CHANNEL_WIDTH_20_40:
rtlphy->rfreg_chnlval[0] = ((rtlphy->rfreg_chnlval[0] &
0xfffff3ff));
rtl_set_rfreg(hw, RF90_PATH_A, RF_CHNLBW, RFREG_OFFSET_MASK,
rtlphy->rfreg_chnlval[0]);
break;
default:
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"unknown bandwidth: %#X\n", bandwidth);
break;
}
}
void rtl92cu_phy_rf6052_set_cck_txpower(struct ieee80211_hw *hw,
u8 *ppowerlevel)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_phy *rtlphy = &(rtlpriv->phy);
struct rtl_hal *rtlhal = rtl_hal(rtlpriv);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl_efuse *rtlefuse = rtl_efuse(rtl_priv(hw));
u32 tx_agc[2] = { 0, 0 }, tmpval = 0;
bool turbo_scanoff = false;
u8 idx1, idx2;
u8 *ptr;
if (rtlhal->interface == INTF_PCI) {
if (rtlefuse->eeprom_regulatory != 0)
turbo_scanoff = true;
} else {
if ((rtlefuse->eeprom_regulatory != 0) ||
(rtlefuse->external_pa))
turbo_scanoff = true;
}
if (mac->act_scanning) {
tx_agc[RF90_PATH_A] = 0x3f3f3f3f;
tx_agc[RF90_PATH_B] = 0x3f3f3f3f;
if (turbo_scanoff) {
for (idx1 = RF90_PATH_A; idx1 <= RF90_PATH_B; idx1++) {
tx_agc[idx1] = ppowerlevel[idx1] |
(ppowerlevel[idx1] << 8) |
(ppowerlevel[idx1] << 16) |
(ppowerlevel[idx1] << 24);
if (rtlhal->interface == INTF_USB) {
if (tx_agc[idx1] > 0x20 &&
rtlefuse->external_pa)
tx_agc[idx1] = 0x20;
}
}
}
} else {
if (rtlpriv->dm.dynamic_txhighpower_lvl ==
TXHIGHPWRLEVEL_LEVEL1) {
tx_agc[RF90_PATH_A] = 0x10101010;
tx_agc[RF90_PATH_B] = 0x10101010;
} else if (rtlpriv->dm.dynamic_txhighpower_lvl ==
TXHIGHPWRLEVEL_LEVEL1) {
tx_agc[RF90_PATH_A] = 0x00000000;
tx_agc[RF90_PATH_B] = 0x00000000;
} else{
for (idx1 = RF90_PATH_A; idx1 <= RF90_PATH_B; idx1++) {
tx_agc[idx1] = ppowerlevel[idx1] |
(ppowerlevel[idx1] << 8) |
(ppowerlevel[idx1] << 16) |
(ppowerlevel[idx1] << 24);
}
if (rtlefuse->eeprom_regulatory == 0) {
tmpval = (rtlphy->mcs_txpwrlevel_origoffset
[0][6]) +
(rtlphy->mcs_txpwrlevel_origoffset
[0][7] << 8);
tx_agc[RF90_PATH_A] += tmpval;
tmpval = (rtlphy->mcs_txpwrlevel_origoffset
[0][14]) +
(rtlphy->mcs_txpwrlevel_origoffset
[0][15] << 24);
tx_agc[RF90_PATH_B] += tmpval;
}
}
}
for (idx1 = RF90_PATH_A; idx1 <= RF90_PATH_B; idx1++) {
ptr = (u8 *) (&(tx_agc[idx1]));
for (idx2 = 0; idx2 < 4; idx2++) {
if (*ptr > RF6052_MAX_TX_PWR)
*ptr = RF6052_MAX_TX_PWR;
ptr++;
}
}
tmpval = tx_agc[RF90_PATH_A] & 0xff;
rtl_set_bbreg(hw, RTXAGC_A_CCK1_MCS32, MASKBYTE1, tmpval);
RTPRINT(rtlpriv, FPHY, PHY_TXPWR,
"CCK PWR 1M (rf-A) = 0x%x (reg 0x%x)\n",
tmpval, RTXAGC_A_CCK1_MCS32);
tmpval = tx_agc[RF90_PATH_A] >> 8;
if (mac->mode == WIRELESS_MODE_B)
tmpval = tmpval & 0xff00ffff;
rtl_set_bbreg(hw, RTXAGC_B_CCK11_A_CCK2_11, 0xffffff00, tmpval);
RTPRINT(rtlpriv, FPHY, PHY_TXPWR,
"CCK PWR 2~11M (rf-A) = 0x%x (reg 0x%x)\n",
tmpval, RTXAGC_B_CCK11_A_CCK2_11);
tmpval = tx_agc[RF90_PATH_B] >> 24;
rtl_set_bbreg(hw, RTXAGC_B_CCK11_A_CCK2_11, MASKBYTE0, tmpval);
RTPRINT(rtlpriv, FPHY, PHY_TXPWR,
"CCK PWR 11M (rf-B) = 0x%x (reg 0x%x)\n",
tmpval, RTXAGC_B_CCK11_A_CCK2_11);
tmpval = tx_agc[RF90_PATH_B] & 0x00ffffff;
rtl_set_bbreg(hw, RTXAGC_B_CCK1_55_MCS32, 0xffffff00, tmpval);
RTPRINT(rtlpriv, FPHY, PHY_TXPWR,
"CCK PWR 1~5.5M (rf-B) = 0x%x (reg 0x%x)\n",
tmpval, RTXAGC_B_CCK1_55_MCS32);
}
static void rtl92c_phy_get_power_base(struct ieee80211_hw *hw,
u8 *ppowerlevel, u8 channel,
u32 *ofdmbase, u32 *mcsbase)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_phy *rtlphy = &(rtlpriv->phy);
struct rtl_efuse *rtlefuse = rtl_efuse(rtl_priv(hw));
u32 powerBase0, powerBase1;
u8 legacy_pwrdiff = 0, ht20_pwrdiff = 0;
u8 i, powerlevel[2];
for (i = 0; i < 2; i++) {
powerlevel[i] = ppowerlevel[i];
legacy_pwrdiff = rtlefuse->txpwr_legacyhtdiff[i][channel - 1];
powerBase0 = powerlevel[i] + legacy_pwrdiff;
powerBase0 = (powerBase0 << 24) | (powerBase0 << 16) |
(powerBase0 << 8) | powerBase0;
*(ofdmbase + i) = powerBase0;
RTPRINT(rtlpriv, FPHY, PHY_TXPWR,
" [OFDM power base index rf(%c) = 0x%x]\n",
i == 0 ? 'A' : 'B', *(ofdmbase + i));
}
for (i = 0; i < 2; i++) {
if (rtlphy->current_chan_bw == HT_CHANNEL_WIDTH_20) {
ht20_pwrdiff = rtlefuse->txpwr_ht20diff[i][channel - 1];
powerlevel[i] += ht20_pwrdiff;
}
powerBase1 = powerlevel[i];
powerBase1 = (powerBase1 << 24) |
(powerBase1 << 16) | (powerBase1 << 8) | powerBase1;
*(mcsbase + i) = powerBase1;
RTPRINT(rtlpriv, FPHY, PHY_TXPWR,
" [MCS power base index rf(%c) = 0x%x]\n",
i == 0 ? 'A' : 'B', *(mcsbase + i));
}
}
static void _rtl92c_get_txpower_writeval_by_regulatory(struct ieee80211_hw *hw,
u8 channel, u8 index,
u32 *powerBase0,
u32 *powerBase1,
u32 *p_outwriteval)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_phy *rtlphy = &(rtlpriv->phy);
struct rtl_efuse *rtlefuse = rtl_efuse(rtl_priv(hw));
u8 i, chnlgroup = 0, pwr_diff_limit[4];
u32 writeVal, customer_limit, rf;
for (rf = 0; rf < 2; rf++) {
switch (rtlefuse->eeprom_regulatory) {
case 0:
chnlgroup = 0;
writeVal = rtlphy->mcs_txpwrlevel_origoffset
[chnlgroup][index + (rf ? 8 : 0)]
+ ((index < 2) ? powerBase0[rf] : powerBase1[rf]);
RTPRINT(rtlpriv, FPHY, PHY_TXPWR,
"RTK better performance,writeVal(%c) = 0x%x\n",
rf == 0 ? 'A' : 'B', writeVal);
break;
case 1:
if (rtlphy->pwrgroup_cnt == 1)
chnlgroup = 0;
if (rtlphy->pwrgroup_cnt >= 3) {
if (channel <= 3)
chnlgroup = 0;
else if (channel >= 4 && channel <= 9)
chnlgroup = 1;
else if (channel > 9)
chnlgroup = 2;
if (rtlphy->current_chan_bw ==
HT_CHANNEL_WIDTH_20)
chnlgroup++;
else
chnlgroup += 4;
}
writeVal = rtlphy->mcs_txpwrlevel_origoffset
[chnlgroup][index +
(rf ? 8 : 0)] +
((index < 2) ? powerBase0[rf] :
powerBase1[rf]);
RTPRINT(rtlpriv, FPHY, PHY_TXPWR,
"Realtek regulatory, 20MHz, writeVal(%c) = 0x%x\n",
rf == 0 ? 'A' : 'B', writeVal);
break;
case 2:
writeVal = ((index < 2) ? powerBase0[rf] :
powerBase1[rf]);
RTPRINT(rtlpriv, FPHY, PHY_TXPWR,
"Better regulatory,writeVal(%c) = 0x%x\n",
rf == 0 ? 'A' : 'B', writeVal);
break;
case 3:
chnlgroup = 0;
if (rtlphy->current_chan_bw ==
HT_CHANNEL_WIDTH_20_40) {
RTPRINT(rtlpriv, FPHY, PHY_TXPWR,
"customer's limit, 40MHzrf(%c) = 0x%x\n",
rf == 0 ? 'A' : 'B',
rtlefuse->pwrgroup_ht40[rf]
[channel - 1]);
} else {
RTPRINT(rtlpriv, FPHY, PHY_TXPWR,
"customer's limit, 20MHz rf(%c) = 0x%x\n",
rf == 0 ? 'A' : 'B',
rtlefuse->pwrgroup_ht20[rf]
[channel - 1]);
}
for (i = 0; i < 4; i++) {
pwr_diff_limit[i] =
(u8) ((rtlphy->mcs_txpwrlevel_origoffset
[chnlgroup][index + (rf ? 8 : 0)]
& (0x7f << (i * 8))) >> (i * 8));
if (rtlphy->current_chan_bw ==
HT_CHANNEL_WIDTH_20_40) {
if (pwr_diff_limit[i] >
rtlefuse->pwrgroup_ht40[rf]
[channel - 1])
pwr_diff_limit[i] = rtlefuse->
pwrgroup_ht40[rf]
[channel - 1];
} else {
if (pwr_diff_limit[i] >
rtlefuse->pwrgroup_ht20[rf]
[channel - 1])
pwr_diff_limit[i] =
rtlefuse->pwrgroup_ht20[rf]
[channel - 1];
}
}
customer_limit = (pwr_diff_limit[3] << 24) |
(pwr_diff_limit[2] << 16) |
(pwr_diff_limit[1] << 8) | (pwr_diff_limit[0]);
RTPRINT(rtlpriv, FPHY, PHY_TXPWR,
"Customer's limit rf(%c) = 0x%x\n",
rf == 0 ? 'A' : 'B', customer_limit);
writeVal = customer_limit + ((index < 2) ?
powerBase0[rf] : powerBase1[rf]);
RTPRINT(rtlpriv, FPHY, PHY_TXPWR,
"Customer, writeVal rf(%c)= 0x%x\n",
rf == 0 ? 'A' : 'B', writeVal);
break;
default:
chnlgroup = 0;
writeVal = rtlphy->mcs_txpwrlevel_origoffset[chnlgroup]
[index + (rf ? 8 : 0)] + ((index < 2) ?
powerBase0[rf] : powerBase1[rf]);
RTPRINT(rtlpriv, FPHY, PHY_TXPWR,
"RTK better performance, writeValrf(%c) = 0x%x\n",
rf == 0 ? 'A' : 'B', writeVal);
break;
}
if (rtlpriv->dm.dynamic_txhighpower_lvl ==
TXHIGHPWRLEVEL_LEVEL1)
writeVal = 0x14141414;
else if (rtlpriv->dm.dynamic_txhighpower_lvl ==
TXHIGHPWRLEVEL_LEVEL2)
writeVal = 0x00000000;
if (rtlpriv->dm.dynamic_txhighpower_lvl == TXHIGHPWRLEVEL_BT1)
writeVal = writeVal - 0x06060606;
else if (rtlpriv->dm.dynamic_txhighpower_lvl ==
TXHIGHPWRLEVEL_BT2)
writeVal = writeVal;
*(p_outwriteval + rf) = writeVal;
}
}
static void _rtl92c_write_ofdm_power_reg(struct ieee80211_hw *hw,
u8 index, u32 *pValue)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_phy *rtlphy = &(rtlpriv->phy);
u16 regoffset_a[6] = {
RTXAGC_A_RATE18_06, RTXAGC_A_RATE54_24,
RTXAGC_A_MCS03_MCS00, RTXAGC_A_MCS07_MCS04,
RTXAGC_A_MCS11_MCS08, RTXAGC_A_MCS15_MCS12
};
u16 regoffset_b[6] = {
RTXAGC_B_RATE18_06, RTXAGC_B_RATE54_24,
RTXAGC_B_MCS03_MCS00, RTXAGC_B_MCS07_MCS04,
RTXAGC_B_MCS11_MCS08, RTXAGC_B_MCS15_MCS12
};
u8 i, rf, pwr_val[4];
u32 writeVal;
u16 regoffset;
for (rf = 0; rf < 2; rf++) {
writeVal = pValue[rf];
for (i = 0; i < 4; i++) {
pwr_val[i] = (u8)((writeVal & (0x7f << (i * 8))) >>
(i * 8));
if (pwr_val[i] > RF6052_MAX_TX_PWR)
pwr_val[i] = RF6052_MAX_TX_PWR;
}
writeVal = (pwr_val[3] << 24) | (pwr_val[2] << 16) |
(pwr_val[1] << 8) | pwr_val[0];
if (rf == 0)
regoffset = regoffset_a[index];
else
regoffset = regoffset_b[index];
rtl_set_bbreg(hw, regoffset, MASKDWORD, writeVal);
RTPRINT(rtlpriv, FPHY, PHY_TXPWR,
"Set 0x%x = %08x\n", regoffset, writeVal);
if (((get_rf_type(rtlphy) == RF_2T2R) &&
(regoffset == RTXAGC_A_MCS15_MCS12 ||
regoffset == RTXAGC_B_MCS15_MCS12)) ||
((get_rf_type(rtlphy) != RF_2T2R) &&
(regoffset == RTXAGC_A_MCS07_MCS04 ||
regoffset == RTXAGC_B_MCS07_MCS04))) {
writeVal = pwr_val[3];
if (regoffset == RTXAGC_A_MCS15_MCS12 ||
regoffset == RTXAGC_A_MCS07_MCS04)
regoffset = 0xc90;
if (regoffset == RTXAGC_B_MCS15_MCS12 ||
regoffset == RTXAGC_B_MCS07_MCS04)
regoffset = 0xc98;
for (i = 0; i < 3; i++) {
writeVal = (writeVal > 6) ? (writeVal - 6) : 0;
rtl_write_byte(rtlpriv, (u32)(regoffset + i),
(u8)writeVal);
}
}
}
}
void rtl92cu_phy_rf6052_set_ofdm_txpower(struct ieee80211_hw *hw,
u8 *ppowerlevel, u8 channel)
{
u32 writeVal[2], powerBase0[2], powerBase1[2];
u8 index = 0;
rtl92c_phy_get_power_base(hw, ppowerlevel,
channel, &powerBase0[0], &powerBase1[0]);
for (index = 0; index < 6; index++) {
_rtl92c_get_txpower_writeval_by_regulatory(hw,
channel, index,
&powerBase0[0],
&powerBase1[0],
&writeVal[0]);
_rtl92c_write_ofdm_power_reg(hw, index, &writeVal[0]);
}
}
bool rtl92cu_phy_rf6052_config(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_phy *rtlphy = &(rtlpriv->phy);
bool rtstatus = true;
u8 b_reg_hwparafile = 1;
if (rtlphy->rf_type == RF_1T1R)
rtlphy->num_total_rfpath = 1;
else
rtlphy->num_total_rfpath = 2;
if (b_reg_hwparafile == 1)
rtstatus = _rtl92c_phy_rf6052_config_parafile(hw);
return rtstatus;
}
static bool _rtl92c_phy_rf6052_config_parafile(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_phy *rtlphy = &(rtlpriv->phy);
u32 u4_regvalue = 0;
u8 rfpath;
bool rtstatus = true;
struct bb_reg_def *pphyreg;
for (rfpath = 0; rfpath < rtlphy->num_total_rfpath; rfpath++) {
pphyreg = &rtlphy->phyreg_def[rfpath];
switch (rfpath) {
case RF90_PATH_A:
case RF90_PATH_C:
u4_regvalue = rtl_get_bbreg(hw, pphyreg->rfintfs,
BRFSI_RFENV);
break;
case RF90_PATH_B:
case RF90_PATH_D:
u4_regvalue = rtl_get_bbreg(hw, pphyreg->rfintfs,
BRFSI_RFENV << 16);
break;
}
rtl_set_bbreg(hw, pphyreg->rfintfe, BRFSI_RFENV << 16, 0x1);
udelay(1);
rtl_set_bbreg(hw, pphyreg->rfintfo, BRFSI_RFENV, 0x1);
udelay(1);
rtl_set_bbreg(hw, pphyreg->rfhssi_para2,
B3WIREADDREAALENGTH, 0x0);
udelay(1);
rtl_set_bbreg(hw, pphyreg->rfhssi_para2, B3WIREDATALENGTH, 0x0);
udelay(1);
switch (rfpath) {
case RF90_PATH_A:
rtstatus = rtl92cu_phy_config_rf_with_headerfile(hw,
(enum radio_path) rfpath);
break;
case RF90_PATH_B:
rtstatus = rtl92cu_phy_config_rf_with_headerfile(hw,
(enum radio_path) rfpath);
break;
case RF90_PATH_C:
break;
case RF90_PATH_D:
break;
}
switch (rfpath) {
case RF90_PATH_A:
case RF90_PATH_C:
rtl_set_bbreg(hw, pphyreg->rfintfs,
BRFSI_RFENV, u4_regvalue);
break;
case RF90_PATH_B:
case RF90_PATH_D:
rtl_set_bbreg(hw, pphyreg->rfintfs,
BRFSI_RFENV << 16, u4_regvalue);
break;
}
if (!rtstatus) {
RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE,
"Radio[%d] Fail!!", rfpath);
goto phy_rf_cfg_fail;
}
}
RT_TRACE(rtlpriv, COMP_INIT, DBG_TRACE, "<---\n");
return rtstatus;
phy_rf_cfg_fail:
return rtstatus;
}
| gpl-2.0 |
curbthepain/us990_kernel | arch/blackfin/kernel/reboot.c | 4418 | 2656 | /*
* arch/blackfin/kernel/reboot.c - handle shutdown/reboot
*
* Copyright 2004-2007 Analog Devices Inc.
*
* Licensed under the GPL-2 or later.
*/
#include <linux/interrupt.h>
#include <asm/bfin-global.h>
#include <asm/reboot.h>
#include <asm/bfrom.h>
/* A system soft reset makes external memory unusable so force
* this function into L1. We use the compiler ssync here rather
* than SSYNC() because it's safe (no interrupts and such) and
* we save some L1. We do not need to force sanity in the SYSCR
* register as the BMODE selection bit is cleared by the soft
* reset while the Core B bit (on dual core parts) is cleared by
* the core reset.
*/
__attribute__ ((__l1_text__, __noreturn__))
static void bfin_reset(void)
{
if (!ANOMALY_05000353 && !ANOMALY_05000386)
bfrom_SoftReset((void *)(L1_SCRATCH_START + L1_SCRATCH_LENGTH - 20));
/* Wait for completion of "system" events such as cache line
* line fills so that we avoid infinite stalls later on as
* much as possible. This code is in L1, so it won't trigger
* any such event after this point in time.
*/
__builtin_bfin_ssync();
/* Initiate System software reset. */
bfin_write_SWRST(0x7);
/* Due to the way reset is handled in the hardware, we need
* to delay for 10 SCLKS. The only reliable way to do this is
* to calculate the CCLK/SCLK ratio and multiply 10. For now,
* we'll assume worse case which is a 1:15 ratio.
*/
asm(
"LSETUP (1f, 1f) LC0 = %0\n"
"1: nop;"
:
: "a" (15 * 10)
: "LC0", "LB0", "LT0"
);
/* Clear System software reset */
bfin_write_SWRST(0);
/* The BF526 ROM will crash during reset */
#if defined(__ADSPBF522__) || defined(__ADSPBF524__) || defined(__ADSPBF526__)
/* Seems to be fixed with newer parts though ... */
if (__SILICON_REVISION__ < 1 && bfin_revid() < 1)
bfin_read_SWRST();
#endif
/* Wait for the SWRST write to complete. Cannot rely on SSYNC
* though as the System state is all reset now.
*/
asm(
"LSETUP (1f, 1f) LC1 = %0\n"
"1: nop;"
:
: "a" (15 * 1)
: "LC1", "LB1", "LT1"
);
while (1)
/* Issue core reset */
asm("raise 1");
}
__attribute__((weak))
void native_machine_restart(char *cmd)
{
}
void machine_restart(char *cmd)
{
native_machine_restart(cmd);
local_irq_disable();
if (smp_processor_id())
smp_call_function((void *)bfin_reset, 0, 1);
else
bfin_reset();
}
__attribute__((weak))
void native_machine_halt(void)
{
idle_with_irq_disabled();
}
void machine_halt(void)
{
native_machine_halt();
}
__attribute__((weak))
void native_machine_power_off(void)
{
idle_with_irq_disabled();
}
void machine_power_off(void)
{
native_machine_power_off();
}
| gpl-2.0 |
evil-god/runbo-q5x6 | kernel/arch/mips/bcm47xx/setup.c | 4418 | 7014 | /*
* Copyright (C) 2004 Florian Schirmer <jolt@tuxbox.org>
* Copyright (C) 2006 Felix Fietkau <nbd@openwrt.org>
* Copyright (C) 2006 Michael Buesch <m@bues.ch>
* Copyright (C) 2010 Waldemar Brodkorb <wbx@openadk.org>
* Copyright (C) 2010-2012 Hauke Mehrtens <hauke@hauke-m.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 SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/export.h>
#include <linux/types.h>
#include <linux/ssb/ssb.h>
#include <linux/ssb/ssb_embedded.h>
#include <linux/bcma/bcma_soc.h>
#include <asm/bootinfo.h>
#include <asm/reboot.h>
#include <asm/time.h>
#include <bcm47xx.h>
#include <asm/mach-bcm47xx/nvram.h>
union bcm47xx_bus bcm47xx_bus;
EXPORT_SYMBOL(bcm47xx_bus);
enum bcm47xx_bus_type bcm47xx_bus_type;
EXPORT_SYMBOL(bcm47xx_bus_type);
static void bcm47xx_machine_restart(char *command)
{
printk(KERN_ALERT "Please stand by while rebooting the system...\n");
local_irq_disable();
/* Set the watchdog timer to reset immediately */
switch (bcm47xx_bus_type) {
#ifdef CONFIG_BCM47XX_SSB
case BCM47XX_BUS_TYPE_SSB:
ssb_watchdog_timer_set(&bcm47xx_bus.ssb, 1);
break;
#endif
#ifdef CONFIG_BCM47XX_BCMA
case BCM47XX_BUS_TYPE_BCMA:
bcma_chipco_watchdog_timer_set(&bcm47xx_bus.bcma.bus.drv_cc, 1);
break;
#endif
}
while (1)
cpu_relax();
}
static void bcm47xx_machine_halt(void)
{
/* Disable interrupts and watchdog and spin forever */
local_irq_disable();
switch (bcm47xx_bus_type) {
#ifdef CONFIG_BCM47XX_SSB
case BCM47XX_BUS_TYPE_SSB:
ssb_watchdog_timer_set(&bcm47xx_bus.ssb, 0);
break;
#endif
#ifdef CONFIG_BCM47XX_BCMA
case BCM47XX_BUS_TYPE_BCMA:
bcma_chipco_watchdog_timer_set(&bcm47xx_bus.bcma.bus.drv_cc, 0);
break;
#endif
}
while (1)
cpu_relax();
}
#ifdef CONFIG_BCM47XX_SSB
static int bcm47xx_get_sprom_ssb(struct ssb_bus *bus, struct ssb_sprom *out)
{
char prefix[10];
if (bus->bustype == SSB_BUSTYPE_PCI) {
snprintf(prefix, sizeof(prefix), "pci/%u/%u/",
bus->host_pci->bus->number + 1,
PCI_SLOT(bus->host_pci->devfn));
bcm47xx_fill_sprom(out, prefix);
return 0;
} else {
printk(KERN_WARNING "bcm47xx: unable to fill SPROM for given bustype.\n");
return -EINVAL;
}
}
static int bcm47xx_get_invariants(struct ssb_bus *bus,
struct ssb_init_invariants *iv)
{
char buf[20];
/* Fill boardinfo structure */
memset(&(iv->boardinfo), 0 , sizeof(struct ssb_boardinfo));
if (nvram_getenv("boardvendor", buf, sizeof(buf)) >= 0)
iv->boardinfo.vendor = (u16)simple_strtoul(buf, NULL, 0);
else
iv->boardinfo.vendor = SSB_BOARDVENDOR_BCM;
if (nvram_getenv("boardtype", buf, sizeof(buf)) >= 0)
iv->boardinfo.type = (u16)simple_strtoul(buf, NULL, 0);
if (nvram_getenv("boardrev", buf, sizeof(buf)) >= 0)
iv->boardinfo.rev = (u16)simple_strtoul(buf, NULL, 0);
bcm47xx_fill_sprom(&iv->sprom, NULL);
if (nvram_getenv("cardbus", buf, sizeof(buf)) >= 0)
iv->has_cardbus_slot = !!simple_strtoul(buf, NULL, 10);
return 0;
}
static void __init bcm47xx_register_ssb(void)
{
int err;
char buf[100];
struct ssb_mipscore *mcore;
err = ssb_arch_register_fallback_sprom(&bcm47xx_get_sprom_ssb);
if (err)
printk(KERN_WARNING "bcm47xx: someone else already registered"
" a ssb SPROM callback handler (err %d)\n", err);
err = ssb_bus_ssbbus_register(&(bcm47xx_bus.ssb), SSB_ENUM_BASE,
bcm47xx_get_invariants);
if (err)
panic("Failed to initialize SSB bus (err %d)", err);
mcore = &bcm47xx_bus.ssb.mipscore;
if (nvram_getenv("kernel_args", buf, sizeof(buf)) >= 0) {
if (strstr(buf, "console=ttyS1")) {
struct ssb_serial_port port;
printk(KERN_DEBUG "Swapping serial ports!\n");
/* swap serial ports */
memcpy(&port, &mcore->serial_ports[0], sizeof(port));
memcpy(&mcore->serial_ports[0], &mcore->serial_ports[1],
sizeof(port));
memcpy(&mcore->serial_ports[1], &port, sizeof(port));
}
}
}
#endif
#ifdef CONFIG_BCM47XX_BCMA
static int bcm47xx_get_sprom_bcma(struct bcma_bus *bus, struct ssb_sprom *out)
{
char prefix[10];
struct bcma_device *core;
switch (bus->hosttype) {
case BCMA_HOSTTYPE_PCI:
snprintf(prefix, sizeof(prefix), "pci/%u/%u/",
bus->host_pci->bus->number + 1,
PCI_SLOT(bus->host_pci->devfn));
bcm47xx_fill_sprom(out, prefix);
return 0;
case BCMA_HOSTTYPE_SOC:
bcm47xx_fill_sprom_ethernet(out, NULL);
core = bcma_find_core(bus, BCMA_CORE_80211);
if (core) {
snprintf(prefix, sizeof(prefix), "sb/%u/",
core->core_index);
bcm47xx_fill_sprom(out, prefix);
}
return 0;
default:
pr_warn("bcm47xx: unable to fill SPROM for given bustype.\n");
return -EINVAL;
}
}
static void __init bcm47xx_register_bcma(void)
{
int err;
err = bcma_arch_register_fallback_sprom(&bcm47xx_get_sprom_bcma);
if (err)
pr_warn("bcm47xx: someone else already registered a bcma SPROM callback handler (err %d)\n", err);
err = bcma_host_soc_register(&bcm47xx_bus.bcma);
if (err)
panic("Failed to initialize BCMA bus (err %d)", err);
}
#endif
void __init plat_mem_setup(void)
{
struct cpuinfo_mips *c = ¤t_cpu_data;
if (c->cputype == CPU_74K) {
printk(KERN_INFO "bcm47xx: using bcma bus\n");
#ifdef CONFIG_BCM47XX_BCMA
bcm47xx_bus_type = BCM47XX_BUS_TYPE_BCMA;
bcm47xx_register_bcma();
#endif
} else {
printk(KERN_INFO "bcm47xx: using ssb bus\n");
#ifdef CONFIG_BCM47XX_SSB
bcm47xx_bus_type = BCM47XX_BUS_TYPE_SSB;
bcm47xx_register_ssb();
#endif
}
_machine_restart = bcm47xx_machine_restart;
_machine_halt = bcm47xx_machine_halt;
pm_power_off = bcm47xx_machine_halt;
}
static int __init bcm47xx_register_bus_complete(void)
{
switch (bcm47xx_bus_type) {
#ifdef CONFIG_BCM47XX_SSB
case BCM47XX_BUS_TYPE_SSB:
/* Nothing to do */
break;
#endif
#ifdef CONFIG_BCM47XX_BCMA
case BCM47XX_BUS_TYPE_BCMA:
bcma_bus_register(&bcm47xx_bus.bcma.bus);
break;
#endif
}
return 0;
}
device_initcall(bcm47xx_register_bus_complete);
| gpl-2.0 |
SlimRoms/kernel_xiaomi_armani | arch/blackfin/mach-bf548/boards/ezkit.c | 4418 | 39988 | /*
* Copyright 2004-2009 Analog Devices Inc.
* 2005 National ICT Australia (NICTA)
* Aidan Williams <aidan@nicta.com.au>
*
* Licensed under the GPL-2 or later.
*/
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
#include <linux/mtd/physmap.h>
#include <linux/spi/spi.h>
#include <linux/spi/flash.h>
#include <linux/irq.h>
#include <linux/i2c.h>
#include <linux/interrupt.h>
#include <linux/usb/musb.h>
#include <asm/bfin5xx_spi.h>
#include <asm/dma.h>
#include <asm/gpio.h>
#include <asm/nand.h>
#include <asm/dpmc.h>
#include <asm/bfin_sport.h>
#include <asm/portmux.h>
#include <asm/bfin_sdh.h>
#include <mach/bf54x_keys.h>
#include <linux/input.h>
#include <linux/spi/ad7877.h>
/*
* Name the Board for the /proc/cpuinfo
*/
const char bfin_board_name[] = "ADI BF548-EZKIT";
/*
* Driver needs to know address, irq and flag pin.
*/
#if defined(CONFIG_USB_ISP1760_HCD) || defined(CONFIG_USB_ISP1760_HCD_MODULE)
#include <linux/usb/isp1760.h>
static struct resource bfin_isp1760_resources[] = {
[0] = {
.start = 0x2C0C0000,
.end = 0x2C0C0000 + 0xfffff,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ_PG7,
.end = IRQ_PG7,
.flags = IORESOURCE_IRQ,
},
};
static struct isp1760_platform_data isp1760_priv = {
.is_isp1761 = 0,
.bus_width_16 = 1,
.port1_otg = 0,
.analog_oc = 0,
.dack_polarity_high = 0,
.dreq_polarity_high = 0,
};
static struct platform_device bfin_isp1760_device = {
.name = "isp1760",
.id = 0,
.dev = {
.platform_data = &isp1760_priv,
},
.num_resources = ARRAY_SIZE(bfin_isp1760_resources),
.resource = bfin_isp1760_resources,
};
#endif
#if defined(CONFIG_FB_BF54X_LQ043) || defined(CONFIG_FB_BF54X_LQ043_MODULE)
#include <mach/bf54x-lq043.h>
static struct bfin_bf54xfb_mach_info bf54x_lq043_data = {
.width = 95,
.height = 54,
.xres = {480, 480, 480},
.yres = {272, 272, 272},
.bpp = {24, 24, 24},
.disp = GPIO_PE3,
};
static struct resource bf54x_lq043_resources[] = {
{
.start = IRQ_EPPI0_ERR,
.end = IRQ_EPPI0_ERR,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device bf54x_lq043_device = {
.name = "bf54x-lq043",
.id = -1,
.num_resources = ARRAY_SIZE(bf54x_lq043_resources),
.resource = bf54x_lq043_resources,
.dev = {
.platform_data = &bf54x_lq043_data,
},
};
#endif
#if defined(CONFIG_KEYBOARD_BFIN) || defined(CONFIG_KEYBOARD_BFIN_MODULE)
static const unsigned int bf548_keymap[] = {
KEYVAL(0, 0, KEY_ENTER),
KEYVAL(0, 1, KEY_HELP),
KEYVAL(0, 2, KEY_0),
KEYVAL(0, 3, KEY_BACKSPACE),
KEYVAL(1, 0, KEY_TAB),
KEYVAL(1, 1, KEY_9),
KEYVAL(1, 2, KEY_8),
KEYVAL(1, 3, KEY_7),
KEYVAL(2, 0, KEY_DOWN),
KEYVAL(2, 1, KEY_6),
KEYVAL(2, 2, KEY_5),
KEYVAL(2, 3, KEY_4),
KEYVAL(3, 0, KEY_UP),
KEYVAL(3, 1, KEY_3),
KEYVAL(3, 2, KEY_2),
KEYVAL(3, 3, KEY_1),
};
static struct bfin_kpad_platform_data bf54x_kpad_data = {
.rows = 4,
.cols = 4,
.keymap = bf548_keymap,
.keymapsize = ARRAY_SIZE(bf548_keymap),
.repeat = 0,
.debounce_time = 5000, /* ns (5ms) */
.coldrive_time = 1000, /* ns (1ms) */
.keyup_test_interval = 50, /* ms (50ms) */
};
static struct resource bf54x_kpad_resources[] = {
{
.start = IRQ_KEY,
.end = IRQ_KEY,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device bf54x_kpad_device = {
.name = "bf54x-keys",
.id = -1,
.num_resources = ARRAY_SIZE(bf54x_kpad_resources),
.resource = bf54x_kpad_resources,
.dev = {
.platform_data = &bf54x_kpad_data,
},
};
#endif
#if defined(CONFIG_INPUT_BFIN_ROTARY) || defined(CONFIG_INPUT_BFIN_ROTARY_MODULE)
#include <asm/bfin_rotary.h>
static struct bfin_rotary_platform_data bfin_rotary_data = {
/*.rotary_up_key = KEY_UP,*/
/*.rotary_down_key = KEY_DOWN,*/
.rotary_rel_code = REL_WHEEL,
.rotary_button_key = KEY_ENTER,
.debounce = 10, /* 0..17 */
.mode = ROT_QUAD_ENC | ROT_DEBE,
};
static struct resource bfin_rotary_resources[] = {
{
.start = IRQ_CNT,
.end = IRQ_CNT,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device bfin_rotary_device = {
.name = "bfin-rotary",
.id = -1,
.num_resources = ARRAY_SIZE(bfin_rotary_resources),
.resource = bfin_rotary_resources,
.dev = {
.platform_data = &bfin_rotary_data,
},
};
#endif
#if defined(CONFIG_INPUT_ADXL34X) || defined(CONFIG_INPUT_ADXL34X_MODULE)
#include <linux/input/adxl34x.h>
static const struct adxl34x_platform_data adxl34x_info = {
.x_axis_offset = 0,
.y_axis_offset = 0,
.z_axis_offset = 0,
.tap_threshold = 0x31,
.tap_duration = 0x10,
.tap_latency = 0x60,
.tap_window = 0xF0,
.tap_axis_control = ADXL_TAP_X_EN | ADXL_TAP_Y_EN | ADXL_TAP_Z_EN,
.act_axis_control = 0xFF,
.activity_threshold = 5,
.inactivity_threshold = 3,
.inactivity_time = 4,
.free_fall_threshold = 0x7,
.free_fall_time = 0x20,
.data_rate = 0x8,
.data_range = ADXL_FULL_RES,
.ev_type = EV_ABS,
.ev_code_x = ABS_X, /* EV_REL */
.ev_code_y = ABS_Y, /* EV_REL */
.ev_code_z = ABS_Z, /* EV_REL */
.ev_code_tap = {BTN_TOUCH, BTN_TOUCH, BTN_TOUCH}, /* EV_KEY x,y,z */
/* .ev_code_ff = KEY_F,*/ /* EV_KEY */
/* .ev_code_act_inactivity = KEY_A,*/ /* EV_KEY */
.power_mode = ADXL_AUTO_SLEEP | ADXL_LINK,
.fifo_mode = ADXL_FIFO_STREAM,
.orientation_enable = ADXL_EN_ORIENTATION_3D,
.deadzone_angle = ADXL_DEADZONE_ANGLE_10p8,
.divisor_length = ADXL_LP_FILTER_DIVISOR_16,
/* EV_KEY {+Z, +Y, +X, -X, -Y, -Z} */
.ev_codes_orient_3d = {BTN_Z, BTN_Y, BTN_X, BTN_A, BTN_B, BTN_C},
};
#endif
#if defined(CONFIG_RTC_DRV_BFIN) || defined(CONFIG_RTC_DRV_BFIN_MODULE)
static struct platform_device rtc_device = {
.name = "rtc-bfin",
.id = -1,
};
#endif
#if defined(CONFIG_SERIAL_BFIN) || defined(CONFIG_SERIAL_BFIN_MODULE)
#ifdef CONFIG_SERIAL_BFIN_UART0
static struct resource bfin_uart0_resources[] = {
{
.start = UART0_DLL,
.end = UART0_RBR+2,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_UART0_TX,
.end = IRQ_UART0_TX,
.flags = IORESOURCE_IRQ,
},
{
.start = IRQ_UART0_RX,
.end = IRQ_UART0_RX,
.flags = IORESOURCE_IRQ,
},
{
.start = IRQ_UART0_ERROR,
.end = IRQ_UART0_ERROR,
.flags = IORESOURCE_IRQ,
},
{
.start = CH_UART0_TX,
.end = CH_UART0_TX,
.flags = IORESOURCE_DMA,
},
{
.start = CH_UART0_RX,
.end = CH_UART0_RX,
.flags = IORESOURCE_DMA,
},
};
static unsigned short bfin_uart0_peripherals[] = {
P_UART0_TX, P_UART0_RX, 0
};
static struct platform_device bfin_uart0_device = {
.name = "bfin-uart",
.id = 0,
.num_resources = ARRAY_SIZE(bfin_uart0_resources),
.resource = bfin_uart0_resources,
.dev = {
.platform_data = &bfin_uart0_peripherals, /* Passed to driver */
},
};
#endif
#ifdef CONFIG_SERIAL_BFIN_UART1
static struct resource bfin_uart1_resources[] = {
{
.start = UART1_DLL,
.end = UART1_RBR+2,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_UART1_TX,
.end = IRQ_UART1_TX,
.flags = IORESOURCE_IRQ,
},
{
.start = IRQ_UART1_RX,
.end = IRQ_UART1_RX,
.flags = IORESOURCE_IRQ,
},
{
.start = IRQ_UART1_ERROR,
.end = IRQ_UART1_ERROR,
.flags = IORESOURCE_IRQ,
},
{
.start = CH_UART1_TX,
.end = CH_UART1_TX,
.flags = IORESOURCE_DMA,
},
{
.start = CH_UART1_RX,
.end = CH_UART1_RX,
.flags = IORESOURCE_DMA,
},
#ifdef CONFIG_BFIN_UART1_CTSRTS
{ /* CTS pin -- 0 means not supported */
.start = GPIO_PE10,
.end = GPIO_PE10,
.flags = IORESOURCE_IO,
},
{ /* RTS pin -- 0 means not supported */
.start = GPIO_PE9,
.end = GPIO_PE9,
.flags = IORESOURCE_IO,
},
#endif
};
static unsigned short bfin_uart1_peripherals[] = {
P_UART1_TX, P_UART1_RX,
#ifdef CONFIG_BFIN_UART1_CTSRTS
P_UART1_RTS, P_UART1_CTS,
#endif
0
};
static struct platform_device bfin_uart1_device = {
.name = "bfin-uart",
.id = 1,
.num_resources = ARRAY_SIZE(bfin_uart1_resources),
.resource = bfin_uart1_resources,
.dev = {
.platform_data = &bfin_uart1_peripherals, /* Passed to driver */
},
};
#endif
#ifdef CONFIG_SERIAL_BFIN_UART2
static struct resource bfin_uart2_resources[] = {
{
.start = UART2_DLL,
.end = UART2_RBR+2,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_UART2_TX,
.end = IRQ_UART2_TX,
.flags = IORESOURCE_IRQ,
},
{
.start = IRQ_UART2_RX,
.end = IRQ_UART2_RX,
.flags = IORESOURCE_IRQ,
},
{
.start = IRQ_UART2_ERROR,
.end = IRQ_UART2_ERROR,
.flags = IORESOURCE_IRQ,
},
{
.start = CH_UART2_TX,
.end = CH_UART2_TX,
.flags = IORESOURCE_DMA,
},
{
.start = CH_UART2_RX,
.end = CH_UART2_RX,
.flags = IORESOURCE_DMA,
},
};
static unsigned short bfin_uart2_peripherals[] = {
P_UART2_TX, P_UART2_RX, 0
};
static struct platform_device bfin_uart2_device = {
.name = "bfin-uart",
.id = 2,
.num_resources = ARRAY_SIZE(bfin_uart2_resources),
.resource = bfin_uart2_resources,
.dev = {
.platform_data = &bfin_uart2_peripherals, /* Passed to driver */
},
};
#endif
#ifdef CONFIG_SERIAL_BFIN_UART3
static struct resource bfin_uart3_resources[] = {
{
.start = UART3_DLL,
.end = UART3_RBR+2,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_UART3_TX,
.end = IRQ_UART3_TX,
.flags = IORESOURCE_IRQ,
},
{
.start = IRQ_UART3_RX,
.end = IRQ_UART3_RX,
.flags = IORESOURCE_IRQ,
},
{
.start = IRQ_UART3_ERROR,
.end = IRQ_UART3_ERROR,
.flags = IORESOURCE_IRQ,
},
{
.start = CH_UART3_TX,
.end = CH_UART3_TX,
.flags = IORESOURCE_DMA,
},
{
.start = CH_UART3_RX,
.end = CH_UART3_RX,
.flags = IORESOURCE_DMA,
},
#ifdef CONFIG_BFIN_UART3_CTSRTS
{ /* CTS pin -- 0 means not supported */
.start = GPIO_PB3,
.end = GPIO_PB3,
.flags = IORESOURCE_IO,
},
{ /* RTS pin -- 0 means not supported */
.start = GPIO_PB2,
.end = GPIO_PB2,
.flags = IORESOURCE_IO,
},
#endif
};
static unsigned short bfin_uart3_peripherals[] = {
P_UART3_TX, P_UART3_RX,
#ifdef CONFIG_BFIN_UART3_CTSRTS
P_UART3_RTS, P_UART3_CTS,
#endif
0
};
static struct platform_device bfin_uart3_device = {
.name = "bfin-uart",
.id = 3,
.num_resources = ARRAY_SIZE(bfin_uart3_resources),
.resource = bfin_uart3_resources,
.dev = {
.platform_data = &bfin_uart3_peripherals, /* Passed to driver */
},
};
#endif
#endif
#if defined(CONFIG_BFIN_SIR) || defined(CONFIG_BFIN_SIR_MODULE)
#ifdef CONFIG_BFIN_SIR0
static struct resource bfin_sir0_resources[] = {
{
.start = 0xFFC00400,
.end = 0xFFC004FF,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_UART0_RX,
.end = IRQ_UART0_RX+1,
.flags = IORESOURCE_IRQ,
},
{
.start = CH_UART0_RX,
.end = CH_UART0_RX+1,
.flags = IORESOURCE_DMA,
},
};
static struct platform_device bfin_sir0_device = {
.name = "bfin_sir",
.id = 0,
.num_resources = ARRAY_SIZE(bfin_sir0_resources),
.resource = bfin_sir0_resources,
};
#endif
#ifdef CONFIG_BFIN_SIR1
static struct resource bfin_sir1_resources[] = {
{
.start = 0xFFC02000,
.end = 0xFFC020FF,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_UART1_RX,
.end = IRQ_UART1_RX+1,
.flags = IORESOURCE_IRQ,
},
{
.start = CH_UART1_RX,
.end = CH_UART1_RX+1,
.flags = IORESOURCE_DMA,
},
};
static struct platform_device bfin_sir1_device = {
.name = "bfin_sir",
.id = 1,
.num_resources = ARRAY_SIZE(bfin_sir1_resources),
.resource = bfin_sir1_resources,
};
#endif
#ifdef CONFIG_BFIN_SIR2
static struct resource bfin_sir2_resources[] = {
{
.start = 0xFFC02100,
.end = 0xFFC021FF,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_UART2_RX,
.end = IRQ_UART2_RX+1,
.flags = IORESOURCE_IRQ,
},
{
.start = CH_UART2_RX,
.end = CH_UART2_RX+1,
.flags = IORESOURCE_DMA,
},
};
static struct platform_device bfin_sir2_device = {
.name = "bfin_sir",
.id = 2,
.num_resources = ARRAY_SIZE(bfin_sir2_resources),
.resource = bfin_sir2_resources,
};
#endif
#ifdef CONFIG_BFIN_SIR3
static struct resource bfin_sir3_resources[] = {
{
.start = 0xFFC03100,
.end = 0xFFC031FF,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_UART3_RX,
.end = IRQ_UART3_RX+1,
.flags = IORESOURCE_IRQ,
},
{
.start = CH_UART3_RX,
.end = CH_UART3_RX+1,
.flags = IORESOURCE_DMA,
},
};
static struct platform_device bfin_sir3_device = {
.name = "bfin_sir",
.id = 3,
.num_resources = ARRAY_SIZE(bfin_sir3_resources),
.resource = bfin_sir3_resources,
};
#endif
#endif
#if defined(CONFIG_SMSC911X) || defined(CONFIG_SMSC911X_MODULE)
#include <linux/smsc911x.h>
static struct resource smsc911x_resources[] = {
{
.name = "smsc911x-memory",
.start = 0x24000000,
.end = 0x24000000 + 0xFF,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_PE8,
.end = IRQ_PE8,
.flags = IORESOURCE_IRQ | IORESOURCE_IRQ_LOWLEVEL,
},
};
static struct smsc911x_platform_config smsc911x_config = {
.flags = SMSC911X_USE_32BIT,
.irq_polarity = SMSC911X_IRQ_POLARITY_ACTIVE_LOW,
.irq_type = SMSC911X_IRQ_TYPE_OPEN_DRAIN,
.phy_interface = PHY_INTERFACE_MODE_MII,
};
static struct platform_device smsc911x_device = {
.name = "smsc911x",
.id = 0,
.num_resources = ARRAY_SIZE(smsc911x_resources),
.resource = smsc911x_resources,
.dev = {
.platform_data = &smsc911x_config,
},
};
#endif
#if defined(CONFIG_USB_MUSB_HDRC) || defined(CONFIG_USB_MUSB_HDRC_MODULE)
static struct resource musb_resources[] = {
[0] = {
.start = 0xFFC03C00,
.end = 0xFFC040FF,
.flags = IORESOURCE_MEM,
},
[1] = { /* general IRQ */
.start = IRQ_USB_INT0,
.end = IRQ_USB_INT0,
.flags = IORESOURCE_IRQ | IORESOURCE_IRQ_HIGHLEVEL,
.name = "mc"
},
[2] = { /* DMA IRQ */
.start = IRQ_USB_DMA,
.end = IRQ_USB_DMA,
.flags = IORESOURCE_IRQ | IORESOURCE_IRQ_HIGHLEVEL,
.name = "dma"
},
};
static struct musb_hdrc_config musb_config = {
.multipoint = 0,
.dyn_fifo = 0,
.soft_con = 1,
.dma = 1,
.num_eps = 8,
.dma_channels = 8,
.gpio_vrsel = GPIO_PE7,
/* Some custom boards need to be active low, just set it to "0"
* if it is the case.
*/
.gpio_vrsel_active = 1,
.clkin = 24, /* musb CLKIN in MHZ */
};
static struct musb_hdrc_platform_data musb_plat = {
#if defined(CONFIG_USB_MUSB_OTG)
.mode = MUSB_OTG,
#elif defined(CONFIG_USB_MUSB_HDRC_HCD)
.mode = MUSB_HOST,
#elif defined(CONFIG_USB_GADGET_MUSB_HDRC)
.mode = MUSB_PERIPHERAL,
#endif
.config = &musb_config,
};
static u64 musb_dmamask = ~(u32)0;
static struct platform_device musb_device = {
.name = "musb-blackfin",
.id = 0,
.dev = {
.dma_mask = &musb_dmamask,
.coherent_dma_mask = 0xffffffff,
.platform_data = &musb_plat,
},
.num_resources = ARRAY_SIZE(musb_resources),
.resource = musb_resources,
};
#endif
#if defined(CONFIG_SERIAL_BFIN_SPORT) || defined(CONFIG_SERIAL_BFIN_SPORT_MODULE)
#ifdef CONFIG_SERIAL_BFIN_SPORT0_UART
static struct resource bfin_sport0_uart_resources[] = {
{
.start = SPORT0_TCR1,
.end = SPORT0_MRCS3+4,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_SPORT0_RX,
.end = IRQ_SPORT0_RX+1,
.flags = IORESOURCE_IRQ,
},
{
.start = IRQ_SPORT0_ERROR,
.end = IRQ_SPORT0_ERROR,
.flags = IORESOURCE_IRQ,
},
};
static unsigned short bfin_sport0_peripherals[] = {
P_SPORT0_TFS, P_SPORT0_DTPRI, P_SPORT0_TSCLK, P_SPORT0_RFS,
P_SPORT0_DRPRI, P_SPORT0_RSCLK, 0
};
static struct platform_device bfin_sport0_uart_device = {
.name = "bfin-sport-uart",
.id = 0,
.num_resources = ARRAY_SIZE(bfin_sport0_uart_resources),
.resource = bfin_sport0_uart_resources,
.dev = {
.platform_data = &bfin_sport0_peripherals, /* Passed to driver */
},
};
#endif
#ifdef CONFIG_SERIAL_BFIN_SPORT1_UART
static struct resource bfin_sport1_uart_resources[] = {
{
.start = SPORT1_TCR1,
.end = SPORT1_MRCS3+4,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_SPORT1_RX,
.end = IRQ_SPORT1_RX+1,
.flags = IORESOURCE_IRQ,
},
{
.start = IRQ_SPORT1_ERROR,
.end = IRQ_SPORT1_ERROR,
.flags = IORESOURCE_IRQ,
},
};
static unsigned short bfin_sport1_peripherals[] = {
P_SPORT1_TFS, P_SPORT1_DTPRI, P_SPORT1_TSCLK, P_SPORT1_RFS,
P_SPORT1_DRPRI, P_SPORT1_RSCLK, 0
};
static struct platform_device bfin_sport1_uart_device = {
.name = "bfin-sport-uart",
.id = 1,
.num_resources = ARRAY_SIZE(bfin_sport1_uart_resources),
.resource = bfin_sport1_uart_resources,
.dev = {
.platform_data = &bfin_sport1_peripherals, /* Passed to driver */
},
};
#endif
#ifdef CONFIG_SERIAL_BFIN_SPORT2_UART
static struct resource bfin_sport2_uart_resources[] = {
{
.start = SPORT2_TCR1,
.end = SPORT2_MRCS3+4,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_SPORT2_RX,
.end = IRQ_SPORT2_RX+1,
.flags = IORESOURCE_IRQ,
},
{
.start = IRQ_SPORT2_ERROR,
.end = IRQ_SPORT2_ERROR,
.flags = IORESOURCE_IRQ,
},
};
static unsigned short bfin_sport2_peripherals[] = {
P_SPORT2_TFS, P_SPORT2_DTPRI, P_SPORT2_TSCLK, P_SPORT2_RFS,
P_SPORT2_DRPRI, P_SPORT2_RSCLK, P_SPORT2_DRSEC, P_SPORT2_DTSEC, 0
};
static struct platform_device bfin_sport2_uart_device = {
.name = "bfin-sport-uart",
.id = 2,
.num_resources = ARRAY_SIZE(bfin_sport2_uart_resources),
.resource = bfin_sport2_uart_resources,
.dev = {
.platform_data = &bfin_sport2_peripherals, /* Passed to driver */
},
};
#endif
#ifdef CONFIG_SERIAL_BFIN_SPORT3_UART
static struct resource bfin_sport3_uart_resources[] = {
{
.start = SPORT3_TCR1,
.end = SPORT3_MRCS3+4,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_SPORT3_RX,
.end = IRQ_SPORT3_RX+1,
.flags = IORESOURCE_IRQ,
},
{
.start = IRQ_SPORT3_ERROR,
.end = IRQ_SPORT3_ERROR,
.flags = IORESOURCE_IRQ,
},
};
static unsigned short bfin_sport3_peripherals[] = {
P_SPORT3_TFS, P_SPORT3_DTPRI, P_SPORT3_TSCLK, P_SPORT3_RFS,
P_SPORT3_DRPRI, P_SPORT3_RSCLK, P_SPORT3_DRSEC, P_SPORT3_DTSEC, 0
};
static struct platform_device bfin_sport3_uart_device = {
.name = "bfin-sport-uart",
.id = 3,
.num_resources = ARRAY_SIZE(bfin_sport3_uart_resources),
.resource = bfin_sport3_uart_resources,
.dev = {
.platform_data = &bfin_sport3_peripherals, /* Passed to driver */
},
};
#endif
#endif
#if defined(CONFIG_CAN_BFIN) || defined(CONFIG_CAN_BFIN_MODULE)
static unsigned short bfin_can0_peripherals[] = {
P_CAN0_RX, P_CAN0_TX, 0
};
static struct resource bfin_can0_resources[] = {
{
.start = 0xFFC02A00,
.end = 0xFFC02FFF,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_CAN0_RX,
.end = IRQ_CAN0_RX,
.flags = IORESOURCE_IRQ,
},
{
.start = IRQ_CAN0_TX,
.end = IRQ_CAN0_TX,
.flags = IORESOURCE_IRQ,
},
{
.start = IRQ_CAN0_ERROR,
.end = IRQ_CAN0_ERROR,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device bfin_can0_device = {
.name = "bfin_can",
.id = 0,
.num_resources = ARRAY_SIZE(bfin_can0_resources),
.resource = bfin_can0_resources,
.dev = {
.platform_data = &bfin_can0_peripherals, /* Passed to driver */
},
};
static unsigned short bfin_can1_peripherals[] = {
P_CAN1_RX, P_CAN1_TX, 0
};
static struct resource bfin_can1_resources[] = {
{
.start = 0xFFC03200,
.end = 0xFFC037FF,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_CAN1_RX,
.end = IRQ_CAN1_RX,
.flags = IORESOURCE_IRQ,
},
{
.start = IRQ_CAN1_TX,
.end = IRQ_CAN1_TX,
.flags = IORESOURCE_IRQ,
},
{
.start = IRQ_CAN1_ERROR,
.end = IRQ_CAN1_ERROR,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device bfin_can1_device = {
.name = "bfin_can",
.id = 1,
.num_resources = ARRAY_SIZE(bfin_can1_resources),
.resource = bfin_can1_resources,
.dev = {
.platform_data = &bfin_can1_peripherals, /* Passed to driver */
},
};
#endif
#if defined(CONFIG_PATA_BF54X) || defined(CONFIG_PATA_BF54X_MODULE)
static struct resource bfin_atapi_resources[] = {
{
.start = 0xFFC03800,
.end = 0xFFC0386F,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_ATAPI_ERR,
.end = IRQ_ATAPI_ERR,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device bfin_atapi_device = {
.name = "pata-bf54x",
.id = -1,
.num_resources = ARRAY_SIZE(bfin_atapi_resources),
.resource = bfin_atapi_resources,
};
#endif
#if defined(CONFIG_MTD_NAND_BF5XX) || defined(CONFIG_MTD_NAND_BF5XX_MODULE)
static struct mtd_partition partition_info[] = {
{
.name = "bootloader(nand)",
.offset = 0,
.size = 0x80000,
}, {
.name = "linux kernel(nand)",
.offset = MTDPART_OFS_APPEND,
.size = 4 * 1024 * 1024,
},
{
.name = "file system(nand)",
.offset = MTDPART_OFS_APPEND,
.size = MTDPART_SIZ_FULL,
},
};
static struct bf5xx_nand_platform bf5xx_nand_platform = {
.data_width = NFC_NWIDTH_8,
.partitions = partition_info,
.nr_partitions = ARRAY_SIZE(partition_info),
.rd_dly = 3,
.wr_dly = 3,
};
static struct resource bf5xx_nand_resources[] = {
{
.start = 0xFFC03B00,
.end = 0xFFC03B4F,
.flags = IORESOURCE_MEM,
},
{
.start = CH_NFC,
.end = CH_NFC,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device bf5xx_nand_device = {
.name = "bf5xx-nand",
.id = 0,
.num_resources = ARRAY_SIZE(bf5xx_nand_resources),
.resource = bf5xx_nand_resources,
.dev = {
.platform_data = &bf5xx_nand_platform,
},
};
#endif
#if defined(CONFIG_SDH_BFIN) || defined(CONFIG_SDH_BFIN_MODULE)
static struct bfin_sd_host bfin_sdh_data = {
.dma_chan = CH_SDH,
.irq_int0 = IRQ_SDH_MASK0,
.pin_req = {P_SD_D0, P_SD_D1, P_SD_D2, P_SD_D3, P_SD_CLK, P_SD_CMD, 0},
};
static struct platform_device bf54x_sdh_device = {
.name = "bfin-sdh",
.id = 0,
.dev = {
.platform_data = &bfin_sdh_data,
},
};
#endif
#if defined(CONFIG_MTD_PHYSMAP) || defined(CONFIG_MTD_PHYSMAP_MODULE)
static struct mtd_partition ezkit_partitions[] = {
{
.name = "bootloader(nor)",
.size = 0x80000,
.offset = 0,
}, {
.name = "linux kernel(nor)",
.size = 0x400000,
.offset = MTDPART_OFS_APPEND,
}, {
.name = "file system(nor)",
.size = 0x1000000 - 0x80000 - 0x400000 - 0x8000 * 4,
.offset = MTDPART_OFS_APPEND,
}, {
.name = "config(nor)",
.size = 0x8000 * 3,
.offset = MTDPART_OFS_APPEND,
}, {
.name = "u-boot env(nor)",
.size = 0x8000,
.offset = MTDPART_OFS_APPEND,
}
};
static struct physmap_flash_data ezkit_flash_data = {
.width = 2,
.parts = ezkit_partitions,
.nr_parts = ARRAY_SIZE(ezkit_partitions),
};
static struct resource ezkit_flash_resource = {
.start = 0x20000000,
.end = 0x21ffffff,
.flags = IORESOURCE_MEM,
};
static struct platform_device ezkit_flash_device = {
.name = "physmap-flash",
.id = 0,
.dev = {
.platform_data = &ezkit_flash_data,
},
.num_resources = 1,
.resource = &ezkit_flash_resource,
};
#endif
#if defined(CONFIG_MTD_M25P80) \
|| defined(CONFIG_MTD_M25P80_MODULE)
/* SPI flash chip (m25p16) */
static struct mtd_partition bfin_spi_flash_partitions[] = {
{
.name = "bootloader(spi)",
.size = 0x00080000,
.offset = 0,
.mask_flags = MTD_CAP_ROM
}, {
.name = "linux kernel(spi)",
.size = MTDPART_SIZ_FULL,
.offset = MTDPART_OFS_APPEND,
}
};
static struct flash_platform_data bfin_spi_flash_data = {
.name = "m25p80",
.parts = bfin_spi_flash_partitions,
.nr_parts = ARRAY_SIZE(bfin_spi_flash_partitions),
.type = "m25p16",
};
static struct bfin5xx_spi_chip spi_flash_chip_info = {
.enable_dma = 0, /* use dma transfer with this chip*/
};
#endif
#if defined(CONFIG_TOUCHSCREEN_AD7877) || defined(CONFIG_TOUCHSCREEN_AD7877_MODULE)
static const struct ad7877_platform_data bfin_ad7877_ts_info = {
.model = 7877,
.vref_delay_usecs = 50, /* internal, no capacitor */
.x_plate_ohms = 419,
.y_plate_ohms = 486,
.pressure_max = 1000,
.pressure_min = 0,
.stopacq_polarity = 1,
.first_conversion_delay = 3,
.acquisition_time = 1,
.averaging = 1,
.pen_down_acc_interval = 1,
};
#endif
static struct spi_board_info bfin_spi_board_info[] __initdata = {
#if defined(CONFIG_MTD_M25P80) \
|| defined(CONFIG_MTD_M25P80_MODULE)
{
/* the modalias must be the same as spi device driver name */
.modalias = "m25p80", /* Name of spi_driver for this device */
.max_speed_hz = 25000000, /* max spi clock (SCK) speed in HZ */
.bus_num = 0, /* Framework bus number */
.chip_select = 1, /* SPI_SSEL1*/
.platform_data = &bfin_spi_flash_data,
.controller_data = &spi_flash_chip_info,
.mode = SPI_MODE_3,
},
#endif
#if defined(CONFIG_SND_BF5XX_SOC_AD183X) \
|| defined(CONFIG_SND_BF5XX_SOC_AD183X_MODULE)
{
.modalias = "ad183x",
.max_speed_hz = 3125000, /* max spi clock (SCK) speed in HZ */
.bus_num = 1,
.chip_select = 4,
},
#endif
#if defined(CONFIG_TOUCHSCREEN_AD7877) || defined(CONFIG_TOUCHSCREEN_AD7877_MODULE)
{
.modalias = "ad7877",
.platform_data = &bfin_ad7877_ts_info,
.irq = IRQ_PB4, /* old boards (<=Rev 1.3) use IRQ_PJ11 */
.max_speed_hz = 12500000, /* max spi clock (SCK) speed in HZ */
.bus_num = 0,
.chip_select = 2,
},
#endif
#if defined(CONFIG_SPI_SPIDEV) || defined(CONFIG_SPI_SPIDEV_MODULE)
{
.modalias = "spidev",
.max_speed_hz = 3125000, /* max spi clock (SCK) speed in HZ */
.bus_num = 0,
.chip_select = 1,
},
#endif
#if defined(CONFIG_INPUT_ADXL34X_SPI) || defined(CONFIG_INPUT_ADXL34X_SPI_MODULE)
{
.modalias = "adxl34x",
.platform_data = &adxl34x_info,
.irq = IRQ_PC5,
.max_speed_hz = 5000000, /* max spi clock (SCK) speed in HZ */
.bus_num = 1,
.chip_select = 2,
.mode = SPI_MODE_3,
},
#endif
};
#if defined(CONFIG_SPI_BFIN5XX) || defined(CONFIG_SPI_BFIN5XX_MODULE)
/* SPI (0) */
static struct resource bfin_spi0_resource[] = {
[0] = {
.start = SPI0_REGBASE,
.end = SPI0_REGBASE + 0xFF,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = CH_SPI0,
.end = CH_SPI0,
.flags = IORESOURCE_DMA,
},
[2] = {
.start = IRQ_SPI0,
.end = IRQ_SPI0,
.flags = IORESOURCE_IRQ,
}
};
/* SPI (1) */
static struct resource bfin_spi1_resource[] = {
[0] = {
.start = SPI1_REGBASE,
.end = SPI1_REGBASE + 0xFF,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = CH_SPI1,
.end = CH_SPI1,
.flags = IORESOURCE_DMA,
},
[2] = {
.start = IRQ_SPI1,
.end = IRQ_SPI1,
.flags = IORESOURCE_IRQ,
}
};
/* SPI controller data */
static struct bfin5xx_spi_master bf54x_spi_master_info0 = {
.num_chipselect = 4,
.enable_dma = 1, /* master has the ability to do dma transfer */
.pin_req = {P_SPI0_SCK, P_SPI0_MISO, P_SPI0_MOSI, 0},
};
static struct platform_device bf54x_spi_master0 = {
.name = "bfin-spi",
.id = 0, /* Bus number */
.num_resources = ARRAY_SIZE(bfin_spi0_resource),
.resource = bfin_spi0_resource,
.dev = {
.platform_data = &bf54x_spi_master_info0, /* Passed to driver */
},
};
static struct bfin5xx_spi_master bf54x_spi_master_info1 = {
.num_chipselect = 4,
.enable_dma = 1, /* master has the ability to do dma transfer */
.pin_req = {P_SPI1_SCK, P_SPI1_MISO, P_SPI1_MOSI, 0},
};
static struct platform_device bf54x_spi_master1 = {
.name = "bfin-spi",
.id = 1, /* Bus number */
.num_resources = ARRAY_SIZE(bfin_spi1_resource),
.resource = bfin_spi1_resource,
.dev = {
.platform_data = &bf54x_spi_master_info1, /* Passed to driver */
},
};
#endif /* spi master and devices */
#if defined(CONFIG_VIDEO_BLACKFIN_CAPTURE) \
|| defined(CONFIG_VIDEO_BLACKFIN_CAPTURE_MODULE)
#include <linux/videodev2.h>
#include <media/blackfin/bfin_capture.h>
#include <media/blackfin/ppi.h>
static const unsigned short ppi_req[] = {
P_PPI1_D0, P_PPI1_D1, P_PPI1_D2, P_PPI1_D3,
P_PPI1_D4, P_PPI1_D5, P_PPI1_D6, P_PPI1_D7,
P_PPI1_CLK, P_PPI1_FS1, P_PPI1_FS2,
0,
};
static const struct ppi_info ppi_info = {
.type = PPI_TYPE_EPPI,
.dma_ch = CH_EPPI1,
.irq_err = IRQ_EPPI1_ERROR,
.base = (void __iomem *)EPPI1_STATUS,
.pin_req = ppi_req,
};
#if defined(CONFIG_VIDEO_VS6624) \
|| defined(CONFIG_VIDEO_VS6624_MODULE)
static struct v4l2_input vs6624_inputs[] = {
{
.index = 0,
.name = "Camera",
.type = V4L2_INPUT_TYPE_CAMERA,
.std = V4L2_STD_UNKNOWN,
},
};
static struct bcap_route vs6624_routes[] = {
{
.input = 0,
.output = 0,
},
};
static const unsigned vs6624_ce_pin = GPIO_PG6;
static struct bfin_capture_config bfin_capture_data = {
.card_name = "BF548",
.inputs = vs6624_inputs,
.num_inputs = ARRAY_SIZE(vs6624_inputs),
.routes = vs6624_routes,
.i2c_adapter_id = 0,
.board_info = {
.type = "vs6624",
.addr = 0x10,
.platform_data = (void *)&vs6624_ce_pin,
},
.ppi_info = &ppi_info,
.ppi_control = (POLC | PACKEN | DLEN_8 | XFR_TYPE | 0x20),
.int_mask = 0xFFFFFFFF, /* disable error interrupt on eppi */
.blank_clocks = 8, /* 8 clocks as SAV and EAV */
};
#endif
static struct platform_device bfin_capture_device = {
.name = "bfin_capture",
.dev = {
.platform_data = &bfin_capture_data,
},
};
#endif
#if defined(CONFIG_I2C_BLACKFIN_TWI) || defined(CONFIG_I2C_BLACKFIN_TWI_MODULE)
static struct resource bfin_twi0_resource[] = {
[0] = {
.start = TWI0_REGBASE,
.end = TWI0_REGBASE + 0xFF,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ_TWI0,
.end = IRQ_TWI0,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device i2c_bfin_twi0_device = {
.name = "i2c-bfin-twi",
.id = 0,
.num_resources = ARRAY_SIZE(bfin_twi0_resource),
.resource = bfin_twi0_resource,
};
#if !defined(CONFIG_BF542) /* The BF542 only has 1 TWI */
static struct resource bfin_twi1_resource[] = {
[0] = {
.start = TWI1_REGBASE,
.end = TWI1_REGBASE + 0xFF,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ_TWI1,
.end = IRQ_TWI1,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device i2c_bfin_twi1_device = {
.name = "i2c-bfin-twi",
.id = 1,
.num_resources = ARRAY_SIZE(bfin_twi1_resource),
.resource = bfin_twi1_resource,
};
#endif
#endif
static struct i2c_board_info __initdata bfin_i2c_board_info0[] = {
#if defined(CONFIG_SND_SOC_SSM2602) || defined(CONFIG_SND_SOC_SSM2602_MODULE)
{
I2C_BOARD_INFO("ssm2602", 0x1b),
},
#endif
};
#if !defined(CONFIG_BF542) /* The BF542 only has 1 TWI */
static struct i2c_board_info __initdata bfin_i2c_board_info1[] = {
#if defined(CONFIG_BFIN_TWI_LCD) || defined(CONFIG_BFIN_TWI_LCD_MODULE)
{
I2C_BOARD_INFO("pcf8574_lcd", 0x22),
},
#endif
#if defined(CONFIG_INPUT_PCF8574) || defined(CONFIG_INPUT_PCF8574_MODULE)
{
I2C_BOARD_INFO("pcf8574_keypad", 0x27),
.irq = 212,
},
#endif
#if defined(CONFIG_INPUT_ADXL34X_I2C) || defined(CONFIG_INPUT_ADXL34X_I2C_MODULE)
{
I2C_BOARD_INFO("adxl34x", 0x53),
.irq = IRQ_PC5,
.platform_data = (void *)&adxl34x_info,
},
#endif
#if defined(CONFIG_BFIN_TWI_LCD) || defined(CONFIG_BFIN_TWI_LCD_MODULE)
{
I2C_BOARD_INFO("ad5252", 0x2f),
},
#endif
};
#endif
#if defined(CONFIG_KEYBOARD_GPIO) || defined(CONFIG_KEYBOARD_GPIO_MODULE)
#include <linux/gpio_keys.h>
static struct gpio_keys_button bfin_gpio_keys_table[] = {
{BTN_0, GPIO_PB8, 1, "gpio-keys: BTN0"},
{BTN_1, GPIO_PB9, 1, "gpio-keys: BTN1"},
{BTN_2, GPIO_PB10, 1, "gpio-keys: BTN2"},
{BTN_3, GPIO_PB11, 1, "gpio-keys: BTN3"},
};
static struct gpio_keys_platform_data bfin_gpio_keys_data = {
.buttons = bfin_gpio_keys_table,
.nbuttons = ARRAY_SIZE(bfin_gpio_keys_table),
};
static struct platform_device bfin_device_gpiokeys = {
.name = "gpio-keys",
.dev = {
.platform_data = &bfin_gpio_keys_data,
},
};
#endif
static const unsigned int cclk_vlev_datasheet[] =
{
/*
* Internal VLEV BF54XSBBC1533
****temporarily using these values until data sheet is updated
*/
VRPAIR(VLEV_085, 150000000),
VRPAIR(VLEV_090, 250000000),
VRPAIR(VLEV_110, 276000000),
VRPAIR(VLEV_115, 301000000),
VRPAIR(VLEV_120, 525000000),
VRPAIR(VLEV_125, 550000000),
VRPAIR(VLEV_130, 600000000),
};
static struct bfin_dpmc_platform_data bfin_dmpc_vreg_data = {
.tuple_tab = cclk_vlev_datasheet,
.tabsize = ARRAY_SIZE(cclk_vlev_datasheet),
.vr_settling_time = 25 /* us */,
};
static struct platform_device bfin_dpmc = {
.name = "bfin dpmc",
.dev = {
.platform_data = &bfin_dmpc_vreg_data,
},
};
#if defined(CONFIG_SND_BF5XX_I2S) || defined(CONFIG_SND_BF5XX_I2S_MODULE) || \
defined(CONFIG_SND_BF5XX_TDM) || defined(CONFIG_SND_BF5XX_TDM_MODULE) || \
defined(CONFIG_SND_BF5XX_AC97) || defined(CONFIG_SND_BF5XX_AC97_MODULE)
#define SPORT_REQ(x) \
[x] = {P_SPORT##x##_TFS, P_SPORT##x##_DTPRI, P_SPORT##x##_TSCLK, \
P_SPORT##x##_RFS, P_SPORT##x##_DRPRI, P_SPORT##x##_RSCLK, 0}
static const u16 bfin_snd_pin[][7] = {
SPORT_REQ(0),
SPORT_REQ(1),
SPORT_REQ(2),
SPORT_REQ(3),
};
static struct bfin_snd_platform_data bfin_snd_data[] = {
{
.pin_req = &bfin_snd_pin[0][0],
},
{
.pin_req = &bfin_snd_pin[1][0],
},
{
.pin_req = &bfin_snd_pin[2][0],
},
{
.pin_req = &bfin_snd_pin[3][0],
},
};
#define BFIN_SND_RES(x) \
[x] = { \
{ \
.start = SPORT##x##_TCR1, \
.end = SPORT##x##_TCR1, \
.flags = IORESOURCE_MEM \
}, \
{ \
.start = CH_SPORT##x##_RX, \
.end = CH_SPORT##x##_RX, \
.flags = IORESOURCE_DMA, \
}, \
{ \
.start = CH_SPORT##x##_TX, \
.end = CH_SPORT##x##_TX, \
.flags = IORESOURCE_DMA, \
}, \
{ \
.start = IRQ_SPORT##x##_ERROR, \
.end = IRQ_SPORT##x##_ERROR, \
.flags = IORESOURCE_IRQ, \
} \
}
static struct resource bfin_snd_resources[][4] = {
BFIN_SND_RES(0),
BFIN_SND_RES(1),
BFIN_SND_RES(2),
BFIN_SND_RES(3),
};
#endif
#if defined(CONFIG_SND_BF5XX_I2S) || defined(CONFIG_SND_BF5XX_I2S_MODULE)
static struct platform_device bfin_i2s_pcm = {
.name = "bfin-i2s-pcm-audio",
.id = -1,
};
#endif
#if defined(CONFIG_SND_BF5XX_TDM) || defined(CONFIG_SND_BF5XX_TDM_MODULE)
static struct platform_device bfin_tdm_pcm = {
.name = "bfin-tdm-pcm-audio",
.id = -1,
};
#endif
#if defined(CONFIG_SND_BF5XX_AC97) || defined(CONFIG_SND_BF5XX_AC97_MODULE)
static struct platform_device bfin_ac97_pcm = {
.name = "bfin-ac97-pcm-audio",
.id = -1,
};
#endif
#if defined(CONFIG_SND_BF5XX_SOC_AD73311) || defined(CONFIG_SND_BF5XX_SOC_AD73311_MODULE)
static struct platform_device bfin_ad73311_codec_device = {
.name = "ad73311",
.id = -1,
};
#endif
#if defined(CONFIG_SND_BF5XX_SOC_AD1980) || defined(CONFIG_SND_BF5XX_SOC_AD1980_MODULE)
static struct platform_device bfin_ad1980_codec_device = {
.name = "ad1980",
.id = -1,
};
#endif
#if defined(CONFIG_SND_BF5XX_SOC_I2S) || defined(CONFIG_SND_BF5XX_SOC_I2S_MODULE)
static struct platform_device bfin_i2s = {
.name = "bfin-i2s",
.id = CONFIG_SND_BF5XX_SPORT_NUM,
.num_resources = ARRAY_SIZE(bfin_snd_resources[CONFIG_SND_BF5XX_SPORT_NUM]),
.resource = bfin_snd_resources[CONFIG_SND_BF5XX_SPORT_NUM],
.dev = {
.platform_data = &bfin_snd_data[CONFIG_SND_BF5XX_SPORT_NUM],
},
};
#endif
#if defined(CONFIG_SND_BF5XX_SOC_TDM) || defined(CONFIG_SND_BF5XX_SOC_TDM_MODULE)
static struct platform_device bfin_tdm = {
.name = "bfin-tdm",
.id = CONFIG_SND_BF5XX_SPORT_NUM,
.num_resources = ARRAY_SIZE(bfin_snd_resources[CONFIG_SND_BF5XX_SPORT_NUM]),
.resource = bfin_snd_resources[CONFIG_SND_BF5XX_SPORT_NUM],
.dev = {
.platform_data = &bfin_snd_data[CONFIG_SND_BF5XX_SPORT_NUM],
},
};
#endif
#if defined(CONFIG_SND_BF5XX_SOC_AC97) || defined(CONFIG_SND_BF5XX_SOC_AC97_MODULE)
static struct platform_device bfin_ac97 = {
.name = "bfin-ac97",
.id = CONFIG_SND_BF5XX_SPORT_NUM,
.num_resources = ARRAY_SIZE(bfin_snd_resources[CONFIG_SND_BF5XX_SPORT_NUM]),
.resource = bfin_snd_resources[CONFIG_SND_BF5XX_SPORT_NUM],
.dev = {
.platform_data = &bfin_snd_data[CONFIG_SND_BF5XX_SPORT_NUM],
},
};
#endif
static struct platform_device *ezkit_devices[] __initdata = {
&bfin_dpmc,
#if defined(CONFIG_RTC_DRV_BFIN) || defined(CONFIG_RTC_DRV_BFIN_MODULE)
&rtc_device,
#endif
#if defined(CONFIG_SERIAL_BFIN) || defined(CONFIG_SERIAL_BFIN_MODULE)
#ifdef CONFIG_SERIAL_BFIN_UART0
&bfin_uart0_device,
#endif
#ifdef CONFIG_SERIAL_BFIN_UART1
&bfin_uart1_device,
#endif
#ifdef CONFIG_SERIAL_BFIN_UART2
&bfin_uart2_device,
#endif
#ifdef CONFIG_SERIAL_BFIN_UART3
&bfin_uart3_device,
#endif
#endif
#if defined(CONFIG_BFIN_SIR) || defined(CONFIG_BFIN_SIR_MODULE)
#ifdef CONFIG_BFIN_SIR0
&bfin_sir0_device,
#endif
#ifdef CONFIG_BFIN_SIR1
&bfin_sir1_device,
#endif
#ifdef CONFIG_BFIN_SIR2
&bfin_sir2_device,
#endif
#ifdef CONFIG_BFIN_SIR3
&bfin_sir3_device,
#endif
#endif
#if defined(CONFIG_FB_BF54X_LQ043) || defined(CONFIG_FB_BF54X_LQ043_MODULE)
&bf54x_lq043_device,
#endif
#if defined(CONFIG_SMSC911X) || defined(CONFIG_SMSC911X_MODULE)
&smsc911x_device,
#endif
#if defined(CONFIG_USB_MUSB_HDRC) || defined(CONFIG_USB_MUSB_HDRC_MODULE)
&musb_device,
#endif
#if defined(CONFIG_USB_ISP1760_HCD) || defined(CONFIG_USB_ISP1760_HCD_MODULE)
&bfin_isp1760_device,
#endif
#if defined(CONFIG_SERIAL_BFIN_SPORT) || defined(CONFIG_SERIAL_BFIN_SPORT_MODULE)
#ifdef CONFIG_SERIAL_BFIN_SPORT0_UART
&bfin_sport0_uart_device,
#endif
#ifdef CONFIG_SERIAL_BFIN_SPORT1_UART
&bfin_sport1_uart_device,
#endif
#ifdef CONFIG_SERIAL_BFIN_SPORT2_UART
&bfin_sport2_uart_device,
#endif
#ifdef CONFIG_SERIAL_BFIN_SPORT3_UART
&bfin_sport3_uart_device,
#endif
#endif
#if defined(CONFIG_CAN_BFIN) || defined(CONFIG_CAN_BFIN_MODULE)
&bfin_can0_device,
&bfin_can1_device,
#endif
#if defined(CONFIG_PATA_BF54X) || defined(CONFIG_PATA_BF54X_MODULE)
&bfin_atapi_device,
#endif
#if defined(CONFIG_MTD_NAND_BF5XX) || defined(CONFIG_MTD_NAND_BF5XX_MODULE)
&bf5xx_nand_device,
#endif
#if defined(CONFIG_SDH_BFIN) || defined(CONFIG_SDH_BFIN_MODULE)
&bf54x_sdh_device,
#endif
#if defined(CONFIG_SPI_BFIN5XX) || defined(CONFIG_SPI_BFIN5XX_MODULE)
&bf54x_spi_master0,
&bf54x_spi_master1,
#endif
#if defined(CONFIG_VIDEO_BLACKFIN_CAPTURE) \
|| defined(CONFIG_VIDEO_BLACKFIN_CAPTURE_MODULE)
&bfin_capture_device,
#endif
#if defined(CONFIG_KEYBOARD_BFIN) || defined(CONFIG_KEYBOARD_BFIN_MODULE)
&bf54x_kpad_device,
#endif
#if defined(CONFIG_INPUT_BFIN_ROTARY) || defined(CONFIG_INPUT_BFIN_ROTARY_MODULE)
&bfin_rotary_device,
#endif
#if defined(CONFIG_I2C_BLACKFIN_TWI) || defined(CONFIG_I2C_BLACKFIN_TWI_MODULE)
&i2c_bfin_twi0_device,
#if !defined(CONFIG_BF542)
&i2c_bfin_twi1_device,
#endif
#endif
#if defined(CONFIG_KEYBOARD_GPIO) || defined(CONFIG_KEYBOARD_GPIO_MODULE)
&bfin_device_gpiokeys,
#endif
#if defined(CONFIG_MTD_PHYSMAP) || defined(CONFIG_MTD_PHYSMAP_MODULE)
&ezkit_flash_device,
#endif
#if defined(CONFIG_SND_BF5XX_I2S) || defined(CONFIG_SND_BF5XX_I2S_MODULE)
&bfin_i2s_pcm,
#endif
#if defined(CONFIG_SND_BF5XX_TDM) || defined(CONFIG_SND_BF5XX_TDM_MODULE)
&bfin_tdm_pcm,
#endif
#if defined(CONFIG_SND_BF5XX_AC97) || defined(CONFIG_SND_BF5XX_AC97_MODULE)
&bfin_ac97_pcm,
#endif
#if defined(CONFIG_SND_BF5XX_SOC_AD1980) || defined(CONFIG_SND_BF5XX_SOC_AD1980_MODULE)
&bfin_ad1980_codec_device,
#endif
#if defined(CONFIG_SND_BF5XX_I2S) || defined(CONFIG_SND_BF5XX_I2S_MODULE)
&bfin_i2s,
#endif
#if defined(CONFIG_SND_BF5XX_TDM) || defined(CONFIG_SND_BF5XX_TDM_MODULE)
&bfin_tdm,
#endif
#if defined(CONFIG_SND_BF5XX_AC97) || defined(CONFIG_SND_BF5XX_AC97_MODULE)
&bfin_ac97,
#endif
};
static int __init ezkit_init(void)
{
printk(KERN_INFO "%s(): registering device resources\n", __func__);
i2c_register_board_info(0, bfin_i2c_board_info0,
ARRAY_SIZE(bfin_i2c_board_info0));
#if !defined(CONFIG_BF542) /* The BF542 only has 1 TWI */
i2c_register_board_info(1, bfin_i2c_board_info1,
ARRAY_SIZE(bfin_i2c_board_info1));
#endif
platform_add_devices(ezkit_devices, ARRAY_SIZE(ezkit_devices));
spi_register_board_info(bfin_spi_board_info, ARRAY_SIZE(bfin_spi_board_info));
return 0;
}
arch_initcall(ezkit_init);
static struct platform_device *ezkit_early_devices[] __initdata = {
#if defined(CONFIG_SERIAL_BFIN_CONSOLE) || defined(CONFIG_EARLY_PRINTK)
#ifdef CONFIG_SERIAL_BFIN_UART0
&bfin_uart0_device,
#endif
#ifdef CONFIG_SERIAL_BFIN_UART1
&bfin_uart1_device,
#endif
#ifdef CONFIG_SERIAL_BFIN_UART2
&bfin_uart2_device,
#endif
#ifdef CONFIG_SERIAL_BFIN_UART3
&bfin_uart3_device,
#endif
#endif
#if defined(CONFIG_SERIAL_BFIN_SPORT_CONSOLE)
#ifdef CONFIG_SERIAL_BFIN_SPORT0_UART
&bfin_sport0_uart_device,
#endif
#ifdef CONFIG_SERIAL_BFIN_SPORT1_UART
&bfin_sport1_uart_device,
#endif
#ifdef CONFIG_SERIAL_BFIN_SPORT2_UART
&bfin_sport2_uart_device,
#endif
#ifdef CONFIG_SERIAL_BFIN_SPORT3_UART
&bfin_sport3_uart_device,
#endif
#endif
};
void __init native_machine_early_platform_add_devices(void)
{
printk(KERN_INFO "register early platform devices\n");
early_platform_add_devices(ezkit_early_devices,
ARRAY_SIZE(ezkit_early_devices));
}
| gpl-2.0 |
emceethemouth/kernel_flo | arch/s390/kernel/os_info.c | 4418 | 4015 | /*
* OS info memory interface
*
* Copyright IBM Corp. 2012
* Author(s): Michael Holzheu <holzheu@linux.vnet.ibm.com>
*/
#define KMSG_COMPONENT "os_info"
#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
#include <linux/crash_dump.h>
#include <linux/kernel.h>
#include <asm/checksum.h>
#include <asm/lowcore.h>
#include <asm/os_info.h>
/*
* OS info structure has to be page aligned
*/
static struct os_info os_info __page_aligned_data;
/*
* Compute checksum over OS info structure
*/
u32 os_info_csum(struct os_info *os_info)
{
int size = sizeof(*os_info) - offsetof(struct os_info, version_major);
return csum_partial(&os_info->version_major, size, 0);
}
/*
* Add crashkernel info to OS info and update checksum
*/
void os_info_crashkernel_add(unsigned long base, unsigned long size)
{
os_info.crashkernel_addr = (u64)(unsigned long)base;
os_info.crashkernel_size = (u64)(unsigned long)size;
os_info.csum = os_info_csum(&os_info);
}
/*
* Add OS info entry and update checksum
*/
void os_info_entry_add(int nr, void *ptr, u64 size)
{
os_info.entry[nr].addr = (u64)(unsigned long)ptr;
os_info.entry[nr].size = size;
os_info.entry[nr].csum = csum_partial(ptr, size, 0);
os_info.csum = os_info_csum(&os_info);
}
/*
* Initialize OS info struture and set lowcore pointer
*/
void __init os_info_init(void)
{
void *ptr = &os_info;
os_info.version_major = OS_INFO_VERSION_MAJOR;
os_info.version_minor = OS_INFO_VERSION_MINOR;
os_info.magic = OS_INFO_MAGIC;
os_info.csum = os_info_csum(&os_info);
copy_to_absolute_zero(&S390_lowcore.os_info, &ptr, sizeof(ptr));
}
#ifdef CONFIG_CRASH_DUMP
static struct os_info *os_info_old;
/*
* Allocate and copy OS info entry from oldmem
*/
static void os_info_old_alloc(int nr, int align)
{
unsigned long addr, size = 0;
char *buf, *buf_align, *msg;
u32 csum;
addr = os_info_old->entry[nr].addr;
if (!addr) {
msg = "not available";
goto fail;
}
size = os_info_old->entry[nr].size;
buf = kmalloc(size + align - 1, GFP_KERNEL);
if (!buf) {
msg = "alloc failed";
goto fail;
}
buf_align = PTR_ALIGN(buf, align);
if (copy_from_oldmem(buf_align, (void *) addr, size)) {
msg = "copy failed";
goto fail_free;
}
csum = csum_partial(buf_align, size, 0);
if (csum != os_info_old->entry[nr].csum) {
msg = "checksum failed";
goto fail_free;
}
os_info_old->entry[nr].addr = (u64)(unsigned long)buf_align;
msg = "copied";
goto out;
fail_free:
kfree(buf);
fail:
os_info_old->entry[nr].addr = 0;
out:
pr_info("entry %i: %s (addr=0x%lx size=%lu)\n",
nr, msg, addr, size);
}
/*
* Initialize os info and os info entries from oldmem
*/
static void os_info_old_init(void)
{
static int os_info_init;
unsigned long addr;
if (os_info_init)
return;
if (!OLDMEM_BASE)
goto fail;
if (copy_from_oldmem(&addr, &S390_lowcore.os_info, sizeof(addr)))
goto fail;
if (addr == 0 || addr % PAGE_SIZE)
goto fail;
os_info_old = kzalloc(sizeof(*os_info_old), GFP_KERNEL);
if (!os_info_old)
goto fail;
if (copy_from_oldmem(os_info_old, (void *) addr, sizeof(*os_info_old)))
goto fail_free;
if (os_info_old->magic != OS_INFO_MAGIC)
goto fail_free;
if (os_info_old->csum != os_info_csum(os_info_old))
goto fail_free;
if (os_info_old->version_major > OS_INFO_VERSION_MAJOR)
goto fail_free;
os_info_old_alloc(OS_INFO_VMCOREINFO, 1);
os_info_old_alloc(OS_INFO_REIPL_BLOCK, 1);
os_info_old_alloc(OS_INFO_INIT_FN, PAGE_SIZE);
pr_info("crashkernel: addr=0x%lx size=%lu\n",
(unsigned long) os_info_old->crashkernel_addr,
(unsigned long) os_info_old->crashkernel_size);
os_info_init = 1;
return;
fail_free:
kfree(os_info_old);
fail:
os_info_init = 1;
os_info_old = NULL;
}
/*
* Return pointer to os infor entry and its size
*/
void *os_info_old_entry(int nr, unsigned long *size)
{
os_info_old_init();
if (!os_info_old)
return NULL;
if (!os_info_old->entry[nr].addr)
return NULL;
*size = (unsigned long) os_info_old->entry[nr].size;
return (void *)(unsigned long)os_info_old->entry[nr].addr;
}
#endif
| gpl-2.0 |
GustavoRD78/78Kernel-Android-N-Developer-Preview-3 | drivers/tty/moxa.c | 4930 | 53169 | /*****************************************************************************/
/*
* moxa.c -- MOXA Intellio family multiport serial driver.
*
* Copyright (C) 1999-2000 Moxa Technologies (support@moxa.com).
* Copyright (c) 2007 Jiri Slaby <jirislaby@gmail.com>
*
* This code is loosely based on the Linux serial driver, written by
* Linus Torvalds, Theodore T'so and others.
*
* 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.
*/
/*
* MOXA Intellio Series Driver
* for : LINUX
* date : 1999/1/7
* version : 5.1
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/mm.h>
#include <linux/ioport.h>
#include <linux/errno.h>
#include <linux/firmware.h>
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/timer.h>
#include <linux/interrupt.h>
#include <linux/tty.h>
#include <linux/tty_flip.h>
#include <linux/major.h>
#include <linux/string.h>
#include <linux/fcntl.h>
#include <linux/ptrace.h>
#include <linux/serial.h>
#include <linux/tty_driver.h>
#include <linux/delay.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/bitops.h>
#include <linux/slab.h>
#include <linux/ratelimit.h>
#include <asm/io.h>
#include <asm/uaccess.h>
#include "moxa.h"
#define MOXA_VERSION "6.0k"
#define MOXA_FW_HDRLEN 32
#define MOXAMAJOR 172
#define MAX_BOARDS 4 /* Don't change this value */
#define MAX_PORTS_PER_BOARD 32 /* Don't change this value */
#define MAX_PORTS (MAX_BOARDS * MAX_PORTS_PER_BOARD)
#define MOXA_IS_320(brd) ((brd)->boardType == MOXA_BOARD_C320_ISA || \
(brd)->boardType == MOXA_BOARD_C320_PCI)
/*
* Define the Moxa PCI vendor and device IDs.
*/
#define MOXA_BUS_TYPE_ISA 0
#define MOXA_BUS_TYPE_PCI 1
enum {
MOXA_BOARD_C218_PCI = 1,
MOXA_BOARD_C218_ISA,
MOXA_BOARD_C320_PCI,
MOXA_BOARD_C320_ISA,
MOXA_BOARD_CP204J,
};
static char *moxa_brdname[] =
{
"C218 Turbo PCI series",
"C218 Turbo ISA series",
"C320 Turbo PCI series",
"C320 Turbo ISA series",
"CP-204J series",
};
#ifdef CONFIG_PCI
static struct pci_device_id moxa_pcibrds[] = {
{ PCI_DEVICE(PCI_VENDOR_ID_MOXA, PCI_DEVICE_ID_MOXA_C218),
.driver_data = MOXA_BOARD_C218_PCI },
{ PCI_DEVICE(PCI_VENDOR_ID_MOXA, PCI_DEVICE_ID_MOXA_C320),
.driver_data = MOXA_BOARD_C320_PCI },
{ PCI_DEVICE(PCI_VENDOR_ID_MOXA, PCI_DEVICE_ID_MOXA_CP204J),
.driver_data = MOXA_BOARD_CP204J },
{ 0 }
};
MODULE_DEVICE_TABLE(pci, moxa_pcibrds);
#endif /* CONFIG_PCI */
struct moxa_port;
static struct moxa_board_conf {
int boardType;
int numPorts;
int busType;
unsigned int ready;
struct moxa_port *ports;
void __iomem *basemem;
void __iomem *intNdx;
void __iomem *intPend;
void __iomem *intTable;
} moxa_boards[MAX_BOARDS];
struct mxser_mstatus {
tcflag_t cflag;
int cts;
int dsr;
int ri;
int dcd;
};
struct moxaq_str {
int inq;
int outq;
};
struct moxa_port {
struct tty_port port;
struct moxa_board_conf *board;
void __iomem *tableAddr;
int type;
int cflag;
unsigned long statusflags;
u8 DCDState; /* Protected by the port lock */
u8 lineCtrl;
u8 lowChkFlag;
};
struct mon_str {
int tick;
int rxcnt[MAX_PORTS];
int txcnt[MAX_PORTS];
};
/* statusflags */
#define TXSTOPPED 1
#define LOWWAIT 2
#define EMPTYWAIT 3
#define SERIAL_DO_RESTART
#define WAKEUP_CHARS 256
static int ttymajor = MOXAMAJOR;
static struct mon_str moxaLog;
static unsigned int moxaFuncTout = HZ / 2;
static unsigned int moxaLowWaterChk;
static DEFINE_MUTEX(moxa_openlock);
static DEFINE_SPINLOCK(moxa_lock);
static unsigned long baseaddr[MAX_BOARDS];
static unsigned int type[MAX_BOARDS];
static unsigned int numports[MAX_BOARDS];
MODULE_AUTHOR("William Chen");
MODULE_DESCRIPTION("MOXA Intellio Family Multiport Board Device Driver");
MODULE_LICENSE("GPL");
MODULE_FIRMWARE("c218tunx.cod");
MODULE_FIRMWARE("cp204unx.cod");
MODULE_FIRMWARE("c320tunx.cod");
module_param_array(type, uint, NULL, 0);
MODULE_PARM_DESC(type, "card type: C218=2, C320=4");
module_param_array(baseaddr, ulong, NULL, 0);
MODULE_PARM_DESC(baseaddr, "base address");
module_param_array(numports, uint, NULL, 0);
MODULE_PARM_DESC(numports, "numports (ignored for C218)");
module_param(ttymajor, int, 0);
/*
* static functions:
*/
static int moxa_open(struct tty_struct *, struct file *);
static void moxa_close(struct tty_struct *, struct file *);
static int moxa_write(struct tty_struct *, const unsigned char *, int);
static int moxa_write_room(struct tty_struct *);
static void moxa_flush_buffer(struct tty_struct *);
static int moxa_chars_in_buffer(struct tty_struct *);
static void moxa_set_termios(struct tty_struct *, struct ktermios *);
static void moxa_stop(struct tty_struct *);
static void moxa_start(struct tty_struct *);
static void moxa_hangup(struct tty_struct *);
static int moxa_tiocmget(struct tty_struct *tty);
static int moxa_tiocmset(struct tty_struct *tty,
unsigned int set, unsigned int clear);
static void moxa_poll(unsigned long);
static void moxa_set_tty_param(struct tty_struct *, struct ktermios *);
static void moxa_shutdown(struct tty_port *);
static int moxa_carrier_raised(struct tty_port *);
static void moxa_dtr_rts(struct tty_port *, int);
/*
* moxa board interface functions:
*/
static void MoxaPortEnable(struct moxa_port *);
static void MoxaPortDisable(struct moxa_port *);
static int MoxaPortSetTermio(struct moxa_port *, struct ktermios *, speed_t);
static int MoxaPortGetLineOut(struct moxa_port *, int *, int *);
static void MoxaPortLineCtrl(struct moxa_port *, int, int);
static void MoxaPortFlowCtrl(struct moxa_port *, int, int, int, int, int);
static int MoxaPortLineStatus(struct moxa_port *);
static void MoxaPortFlushData(struct moxa_port *, int);
static int MoxaPortWriteData(struct tty_struct *, const unsigned char *, int);
static int MoxaPortReadData(struct moxa_port *);
static int MoxaPortTxQueue(struct moxa_port *);
static int MoxaPortRxQueue(struct moxa_port *);
static int MoxaPortTxFree(struct moxa_port *);
static void MoxaPortTxDisable(struct moxa_port *);
static void MoxaPortTxEnable(struct moxa_port *);
static int moxa_get_serial_info(struct moxa_port *, struct serial_struct __user *);
static int moxa_set_serial_info(struct moxa_port *, struct serial_struct __user *);
static void MoxaSetFifo(struct moxa_port *port, int enable);
/*
* I/O functions
*/
static DEFINE_SPINLOCK(moxafunc_lock);
static void moxa_wait_finish(void __iomem *ofsAddr)
{
unsigned long end = jiffies + moxaFuncTout;
while (readw(ofsAddr + FuncCode) != 0)
if (time_after(jiffies, end))
return;
if (readw(ofsAddr + FuncCode) != 0)
printk_ratelimited(KERN_WARNING "moxa function expired\n");
}
static void moxafunc(void __iomem *ofsAddr, u16 cmd, u16 arg)
{
unsigned long flags;
spin_lock_irqsave(&moxafunc_lock, flags);
writew(arg, ofsAddr + FuncArg);
writew(cmd, ofsAddr + FuncCode);
moxa_wait_finish(ofsAddr);
spin_unlock_irqrestore(&moxafunc_lock, flags);
}
static int moxafuncret(void __iomem *ofsAddr, u16 cmd, u16 arg)
{
unsigned long flags;
u16 ret;
spin_lock_irqsave(&moxafunc_lock, flags);
writew(arg, ofsAddr + FuncArg);
writew(cmd, ofsAddr + FuncCode);
moxa_wait_finish(ofsAddr);
ret = readw(ofsAddr + FuncArg);
spin_unlock_irqrestore(&moxafunc_lock, flags);
return ret;
}
static void moxa_low_water_check(void __iomem *ofsAddr)
{
u16 rptr, wptr, mask, len;
if (readb(ofsAddr + FlagStat) & Xoff_state) {
rptr = readw(ofsAddr + RXrptr);
wptr = readw(ofsAddr + RXwptr);
mask = readw(ofsAddr + RX_mask);
len = (wptr - rptr) & mask;
if (len <= Low_water)
moxafunc(ofsAddr, FC_SendXon, 0);
}
}
/*
* TTY operations
*/
static int moxa_ioctl(struct tty_struct *tty,
unsigned int cmd, unsigned long arg)
{
struct moxa_port *ch = tty->driver_data;
void __user *argp = (void __user *)arg;
int status, ret = 0;
if (tty->index == MAX_PORTS) {
if (cmd != MOXA_GETDATACOUNT && cmd != MOXA_GET_IOQUEUE &&
cmd != MOXA_GETMSTATUS)
return -EINVAL;
} else if (!ch)
return -ENODEV;
switch (cmd) {
case MOXA_GETDATACOUNT:
moxaLog.tick = jiffies;
if (copy_to_user(argp, &moxaLog, sizeof(moxaLog)))
ret = -EFAULT;
break;
case MOXA_FLUSH_QUEUE:
MoxaPortFlushData(ch, arg);
break;
case MOXA_GET_IOQUEUE: {
struct moxaq_str __user *argm = argp;
struct moxaq_str tmp;
struct moxa_port *p;
unsigned int i, j;
for (i = 0; i < MAX_BOARDS; i++) {
p = moxa_boards[i].ports;
for (j = 0; j < MAX_PORTS_PER_BOARD; j++, p++, argm++) {
memset(&tmp, 0, sizeof(tmp));
spin_lock_bh(&moxa_lock);
if (moxa_boards[i].ready) {
tmp.inq = MoxaPortRxQueue(p);
tmp.outq = MoxaPortTxQueue(p);
}
spin_unlock_bh(&moxa_lock);
if (copy_to_user(argm, &tmp, sizeof(tmp)))
return -EFAULT;
}
}
break;
} case MOXA_GET_OQUEUE:
status = MoxaPortTxQueue(ch);
ret = put_user(status, (unsigned long __user *)argp);
break;
case MOXA_GET_IQUEUE:
status = MoxaPortRxQueue(ch);
ret = put_user(status, (unsigned long __user *)argp);
break;
case MOXA_GETMSTATUS: {
struct mxser_mstatus __user *argm = argp;
struct mxser_mstatus tmp;
struct moxa_port *p;
unsigned int i, j;
for (i = 0; i < MAX_BOARDS; i++) {
p = moxa_boards[i].ports;
for (j = 0; j < MAX_PORTS_PER_BOARD; j++, p++, argm++) {
struct tty_struct *ttyp;
memset(&tmp, 0, sizeof(tmp));
spin_lock_bh(&moxa_lock);
if (!moxa_boards[i].ready) {
spin_unlock_bh(&moxa_lock);
goto copy;
}
status = MoxaPortLineStatus(p);
spin_unlock_bh(&moxa_lock);
if (status & 1)
tmp.cts = 1;
if (status & 2)
tmp.dsr = 1;
if (status & 4)
tmp.dcd = 1;
ttyp = tty_port_tty_get(&p->port);
if (!ttyp || !ttyp->termios)
tmp.cflag = p->cflag;
else
tmp.cflag = ttyp->termios->c_cflag;
tty_kref_put(ttyp);
copy:
if (copy_to_user(argm, &tmp, sizeof(tmp)))
return -EFAULT;
}
}
break;
}
case TIOCGSERIAL:
mutex_lock(&ch->port.mutex);
ret = moxa_get_serial_info(ch, argp);
mutex_unlock(&ch->port.mutex);
break;
case TIOCSSERIAL:
mutex_lock(&ch->port.mutex);
ret = moxa_set_serial_info(ch, argp);
mutex_unlock(&ch->port.mutex);
break;
default:
ret = -ENOIOCTLCMD;
}
return ret;
}
static int moxa_break_ctl(struct tty_struct *tty, int state)
{
struct moxa_port *port = tty->driver_data;
moxafunc(port->tableAddr, state ? FC_SendBreak : FC_StopBreak,
Magic_code);
return 0;
}
static const struct tty_operations moxa_ops = {
.open = moxa_open,
.close = moxa_close,
.write = moxa_write,
.write_room = moxa_write_room,
.flush_buffer = moxa_flush_buffer,
.chars_in_buffer = moxa_chars_in_buffer,
.ioctl = moxa_ioctl,
.set_termios = moxa_set_termios,
.stop = moxa_stop,
.start = moxa_start,
.hangup = moxa_hangup,
.break_ctl = moxa_break_ctl,
.tiocmget = moxa_tiocmget,
.tiocmset = moxa_tiocmset,
};
static const struct tty_port_operations moxa_port_ops = {
.carrier_raised = moxa_carrier_raised,
.dtr_rts = moxa_dtr_rts,
.shutdown = moxa_shutdown,
};
static struct tty_driver *moxaDriver;
static DEFINE_TIMER(moxaTimer, moxa_poll, 0, 0);
/*
* HW init
*/
static int moxa_check_fw_model(struct moxa_board_conf *brd, u8 model)
{
switch (brd->boardType) {
case MOXA_BOARD_C218_ISA:
case MOXA_BOARD_C218_PCI:
if (model != 1)
goto err;
break;
case MOXA_BOARD_CP204J:
if (model != 3)
goto err;
break;
default:
if (model != 2)
goto err;
break;
}
return 0;
err:
return -EINVAL;
}
static int moxa_check_fw(const void *ptr)
{
const __le16 *lptr = ptr;
if (*lptr != cpu_to_le16(0x7980))
return -EINVAL;
return 0;
}
static int moxa_load_bios(struct moxa_board_conf *brd, const u8 *buf,
size_t len)
{
void __iomem *baseAddr = brd->basemem;
u16 tmp;
writeb(HW_reset, baseAddr + Control_reg); /* reset */
msleep(10);
memset_io(baseAddr, 0, 4096);
memcpy_toio(baseAddr, buf, len); /* download BIOS */
writeb(0, baseAddr + Control_reg); /* restart */
msleep(2000);
switch (brd->boardType) {
case MOXA_BOARD_C218_ISA:
case MOXA_BOARD_C218_PCI:
tmp = readw(baseAddr + C218_key);
if (tmp != C218_KeyCode)
goto err;
break;
case MOXA_BOARD_CP204J:
tmp = readw(baseAddr + C218_key);
if (tmp != CP204J_KeyCode)
goto err;
break;
default:
tmp = readw(baseAddr + C320_key);
if (tmp != C320_KeyCode)
goto err;
tmp = readw(baseAddr + C320_status);
if (tmp != STS_init) {
printk(KERN_ERR "MOXA: bios upload failed -- CPU/Basic "
"module not found\n");
return -EIO;
}
break;
}
return 0;
err:
printk(KERN_ERR "MOXA: bios upload failed -- board not found\n");
return -EIO;
}
static int moxa_load_320b(struct moxa_board_conf *brd, const u8 *ptr,
size_t len)
{
void __iomem *baseAddr = brd->basemem;
if (len < 7168) {
printk(KERN_ERR "MOXA: invalid 320 bios -- too short\n");
return -EINVAL;
}
writew(len - 7168 - 2, baseAddr + C320bapi_len);
writeb(1, baseAddr + Control_reg); /* Select Page 1 */
memcpy_toio(baseAddr + DynPage_addr, ptr, 7168);
writeb(2, baseAddr + Control_reg); /* Select Page 2 */
memcpy_toio(baseAddr + DynPage_addr, ptr + 7168, len - 7168);
return 0;
}
static int moxa_real_load_code(struct moxa_board_conf *brd, const void *ptr,
size_t len)
{
void __iomem *baseAddr = brd->basemem;
const __le16 *uptr = ptr;
size_t wlen, len2, j;
unsigned long key, loadbuf, loadlen, checksum, checksum_ok;
unsigned int i, retry;
u16 usum, keycode;
keycode = (brd->boardType == MOXA_BOARD_CP204J) ? CP204J_KeyCode :
C218_KeyCode;
switch (brd->boardType) {
case MOXA_BOARD_CP204J:
case MOXA_BOARD_C218_ISA:
case MOXA_BOARD_C218_PCI:
key = C218_key;
loadbuf = C218_LoadBuf;
loadlen = C218DLoad_len;
checksum = C218check_sum;
checksum_ok = C218chksum_ok;
break;
default:
key = C320_key;
keycode = C320_KeyCode;
loadbuf = C320_LoadBuf;
loadlen = C320DLoad_len;
checksum = C320check_sum;
checksum_ok = C320chksum_ok;
break;
}
usum = 0;
wlen = len >> 1;
for (i = 0; i < wlen; i++)
usum += le16_to_cpu(uptr[i]);
retry = 0;
do {
wlen = len >> 1;
j = 0;
while (wlen) {
len2 = (wlen > 2048) ? 2048 : wlen;
wlen -= len2;
memcpy_toio(baseAddr + loadbuf, ptr + j, len2 << 1);
j += len2 << 1;
writew(len2, baseAddr + loadlen);
writew(0, baseAddr + key);
for (i = 0; i < 100; i++) {
if (readw(baseAddr + key) == keycode)
break;
msleep(10);
}
if (readw(baseAddr + key) != keycode)
return -EIO;
}
writew(0, baseAddr + loadlen);
writew(usum, baseAddr + checksum);
writew(0, baseAddr + key);
for (i = 0; i < 100; i++) {
if (readw(baseAddr + key) == keycode)
break;
msleep(10);
}
retry++;
} while ((readb(baseAddr + checksum_ok) != 1) && (retry < 3));
if (readb(baseAddr + checksum_ok) != 1)
return -EIO;
writew(0, baseAddr + key);
for (i = 0; i < 600; i++) {
if (readw(baseAddr + Magic_no) == Magic_code)
break;
msleep(10);
}
if (readw(baseAddr + Magic_no) != Magic_code)
return -EIO;
if (MOXA_IS_320(brd)) {
if (brd->busType == MOXA_BUS_TYPE_PCI) { /* ASIC board */
writew(0x3800, baseAddr + TMS320_PORT1);
writew(0x3900, baseAddr + TMS320_PORT2);
writew(28499, baseAddr + TMS320_CLOCK);
} else {
writew(0x3200, baseAddr + TMS320_PORT1);
writew(0x3400, baseAddr + TMS320_PORT2);
writew(19999, baseAddr + TMS320_CLOCK);
}
}
writew(1, baseAddr + Disable_IRQ);
writew(0, baseAddr + Magic_no);
for (i = 0; i < 500; i++) {
if (readw(baseAddr + Magic_no) == Magic_code)
break;
msleep(10);
}
if (readw(baseAddr + Magic_no) != Magic_code)
return -EIO;
if (MOXA_IS_320(brd)) {
j = readw(baseAddr + Module_cnt);
if (j <= 0)
return -EIO;
brd->numPorts = j * 8;
writew(j, baseAddr + Module_no);
writew(0, baseAddr + Magic_no);
for (i = 0; i < 600; i++) {
if (readw(baseAddr + Magic_no) == Magic_code)
break;
msleep(10);
}
if (readw(baseAddr + Magic_no) != Magic_code)
return -EIO;
}
brd->intNdx = baseAddr + IRQindex;
brd->intPend = baseAddr + IRQpending;
brd->intTable = baseAddr + IRQtable;
return 0;
}
static int moxa_load_code(struct moxa_board_conf *brd, const void *ptr,
size_t len)
{
void __iomem *ofsAddr, *baseAddr = brd->basemem;
struct moxa_port *port;
int retval, i;
if (len % 2) {
printk(KERN_ERR "MOXA: bios length is not even\n");
return -EINVAL;
}
retval = moxa_real_load_code(brd, ptr, len); /* may change numPorts */
if (retval)
return retval;
switch (brd->boardType) {
case MOXA_BOARD_C218_ISA:
case MOXA_BOARD_C218_PCI:
case MOXA_BOARD_CP204J:
port = brd->ports;
for (i = 0; i < brd->numPorts; i++, port++) {
port->board = brd;
port->DCDState = 0;
port->tableAddr = baseAddr + Extern_table +
Extern_size * i;
ofsAddr = port->tableAddr;
writew(C218rx_mask, ofsAddr + RX_mask);
writew(C218tx_mask, ofsAddr + TX_mask);
writew(C218rx_spage + i * C218buf_pageno, ofsAddr + Page_rxb);
writew(readw(ofsAddr + Page_rxb) + C218rx_pageno, ofsAddr + EndPage_rxb);
writew(C218tx_spage + i * C218buf_pageno, ofsAddr + Page_txb);
writew(readw(ofsAddr + Page_txb) + C218tx_pageno, ofsAddr + EndPage_txb);
}
break;
default:
port = brd->ports;
for (i = 0; i < brd->numPorts; i++, port++) {
port->board = brd;
port->DCDState = 0;
port->tableAddr = baseAddr + Extern_table +
Extern_size * i;
ofsAddr = port->tableAddr;
switch (brd->numPorts) {
case 8:
writew(C320p8rx_mask, ofsAddr + RX_mask);
writew(C320p8tx_mask, ofsAddr + TX_mask);
writew(C320p8rx_spage + i * C320p8buf_pgno, ofsAddr + Page_rxb);
writew(readw(ofsAddr + Page_rxb) + C320p8rx_pgno, ofsAddr + EndPage_rxb);
writew(C320p8tx_spage + i * C320p8buf_pgno, ofsAddr + Page_txb);
writew(readw(ofsAddr + Page_txb) + C320p8tx_pgno, ofsAddr + EndPage_txb);
break;
case 16:
writew(C320p16rx_mask, ofsAddr + RX_mask);
writew(C320p16tx_mask, ofsAddr + TX_mask);
writew(C320p16rx_spage + i * C320p16buf_pgno, ofsAddr + Page_rxb);
writew(readw(ofsAddr + Page_rxb) + C320p16rx_pgno, ofsAddr + EndPage_rxb);
writew(C320p16tx_spage + i * C320p16buf_pgno, ofsAddr + Page_txb);
writew(readw(ofsAddr + Page_txb) + C320p16tx_pgno, ofsAddr + EndPage_txb);
break;
case 24:
writew(C320p24rx_mask, ofsAddr + RX_mask);
writew(C320p24tx_mask, ofsAddr + TX_mask);
writew(C320p24rx_spage + i * C320p24buf_pgno, ofsAddr + Page_rxb);
writew(readw(ofsAddr + Page_rxb) + C320p24rx_pgno, ofsAddr + EndPage_rxb);
writew(C320p24tx_spage + i * C320p24buf_pgno, ofsAddr + Page_txb);
writew(readw(ofsAddr + Page_txb), ofsAddr + EndPage_txb);
break;
case 32:
writew(C320p32rx_mask, ofsAddr + RX_mask);
writew(C320p32tx_mask, ofsAddr + TX_mask);
writew(C320p32tx_ofs, ofsAddr + Ofs_txb);
writew(C320p32rx_spage + i * C320p32buf_pgno, ofsAddr + Page_rxb);
writew(readb(ofsAddr + Page_rxb), ofsAddr + EndPage_rxb);
writew(C320p32tx_spage + i * C320p32buf_pgno, ofsAddr + Page_txb);
writew(readw(ofsAddr + Page_txb), ofsAddr + EndPage_txb);
break;
}
}
break;
}
return 0;
}
static int moxa_load_fw(struct moxa_board_conf *brd, const struct firmware *fw)
{
const void *ptr = fw->data;
char rsn[64];
u16 lens[5];
size_t len;
unsigned int a, lenp, lencnt;
int ret = -EINVAL;
struct {
__le32 magic; /* 0x34303430 */
u8 reserved1[2];
u8 type; /* UNIX = 3 */
u8 model; /* C218T=1, C320T=2, CP204=3 */
u8 reserved2[8];
__le16 len[5];
} const *hdr = ptr;
BUILD_BUG_ON(ARRAY_SIZE(hdr->len) != ARRAY_SIZE(lens));
if (fw->size < MOXA_FW_HDRLEN) {
strcpy(rsn, "too short (even header won't fit)");
goto err;
}
if (hdr->magic != cpu_to_le32(0x30343034)) {
sprintf(rsn, "bad magic: %.8x", le32_to_cpu(hdr->magic));
goto err;
}
if (hdr->type != 3) {
sprintf(rsn, "not for linux, type is %u", hdr->type);
goto err;
}
if (moxa_check_fw_model(brd, hdr->model)) {
sprintf(rsn, "not for this card, model is %u", hdr->model);
goto err;
}
len = MOXA_FW_HDRLEN;
lencnt = hdr->model == 2 ? 5 : 3;
for (a = 0; a < ARRAY_SIZE(lens); a++) {
lens[a] = le16_to_cpu(hdr->len[a]);
if (lens[a] && len + lens[a] <= fw->size &&
moxa_check_fw(&fw->data[len]))
printk(KERN_WARNING "MOXA firmware: unexpected input "
"at offset %u, but going on\n", (u32)len);
if (!lens[a] && a < lencnt) {
sprintf(rsn, "too few entries in fw file");
goto err;
}
len += lens[a];
}
if (len != fw->size) {
sprintf(rsn, "bad length: %u (should be %u)", (u32)fw->size,
(u32)len);
goto err;
}
ptr += MOXA_FW_HDRLEN;
lenp = 0; /* bios */
strcpy(rsn, "read above");
ret = moxa_load_bios(brd, ptr, lens[lenp]);
if (ret)
goto err;
/* we skip the tty section (lens[1]), since we don't need it */
ptr += lens[lenp] + lens[lenp + 1];
lenp += 2; /* comm */
if (hdr->model == 2) {
ret = moxa_load_320b(brd, ptr, lens[lenp]);
if (ret)
goto err;
/* skip another tty */
ptr += lens[lenp] + lens[lenp + 1];
lenp += 2;
}
ret = moxa_load_code(brd, ptr, lens[lenp]);
if (ret)
goto err;
return 0;
err:
printk(KERN_ERR "firmware failed to load, reason: %s\n", rsn);
return ret;
}
static int moxa_init_board(struct moxa_board_conf *brd, struct device *dev)
{
const struct firmware *fw;
const char *file;
struct moxa_port *p;
unsigned int i;
int ret;
brd->ports = kcalloc(MAX_PORTS_PER_BOARD, sizeof(*brd->ports),
GFP_KERNEL);
if (brd->ports == NULL) {
printk(KERN_ERR "cannot allocate memory for ports\n");
ret = -ENOMEM;
goto err;
}
for (i = 0, p = brd->ports; i < MAX_PORTS_PER_BOARD; i++, p++) {
tty_port_init(&p->port);
p->port.ops = &moxa_port_ops;
p->type = PORT_16550A;
p->cflag = B9600 | CS8 | CREAD | CLOCAL | HUPCL;
}
switch (brd->boardType) {
case MOXA_BOARD_C218_ISA:
case MOXA_BOARD_C218_PCI:
file = "c218tunx.cod";
break;
case MOXA_BOARD_CP204J:
file = "cp204unx.cod";
break;
default:
file = "c320tunx.cod";
break;
}
ret = request_firmware(&fw, file, dev);
if (ret) {
printk(KERN_ERR "MOXA: request_firmware failed. Make sure "
"you've placed '%s' file into your firmware "
"loader directory (e.g. /lib/firmware)\n",
file);
goto err_free;
}
ret = moxa_load_fw(brd, fw);
release_firmware(fw);
if (ret)
goto err_free;
spin_lock_bh(&moxa_lock);
brd->ready = 1;
if (!timer_pending(&moxaTimer))
mod_timer(&moxaTimer, jiffies + HZ / 50);
spin_unlock_bh(&moxa_lock);
return 0;
err_free:
kfree(brd->ports);
err:
return ret;
}
static void moxa_board_deinit(struct moxa_board_conf *brd)
{
unsigned int a, opened;
mutex_lock(&moxa_openlock);
spin_lock_bh(&moxa_lock);
brd->ready = 0;
spin_unlock_bh(&moxa_lock);
/* pci hot-un-plug support */
for (a = 0; a < brd->numPorts; a++)
if (brd->ports[a].port.flags & ASYNC_INITIALIZED) {
struct tty_struct *tty = tty_port_tty_get(
&brd->ports[a].port);
if (tty) {
tty_hangup(tty);
tty_kref_put(tty);
}
}
while (1) {
opened = 0;
for (a = 0; a < brd->numPorts; a++)
if (brd->ports[a].port.flags & ASYNC_INITIALIZED)
opened++;
mutex_unlock(&moxa_openlock);
if (!opened)
break;
msleep(50);
mutex_lock(&moxa_openlock);
}
iounmap(brd->basemem);
brd->basemem = NULL;
kfree(brd->ports);
}
#ifdef CONFIG_PCI
static int __devinit moxa_pci_probe(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct moxa_board_conf *board;
unsigned int i;
int board_type = ent->driver_data;
int retval;
retval = pci_enable_device(pdev);
if (retval) {
dev_err(&pdev->dev, "can't enable pci device\n");
goto err;
}
for (i = 0; i < MAX_BOARDS; i++)
if (moxa_boards[i].basemem == NULL)
break;
retval = -ENODEV;
if (i >= MAX_BOARDS) {
dev_warn(&pdev->dev, "more than %u MOXA Intellio family boards "
"found. Board is ignored.\n", MAX_BOARDS);
goto err;
}
board = &moxa_boards[i];
retval = pci_request_region(pdev, 2, "moxa-base");
if (retval) {
dev_err(&pdev->dev, "can't request pci region 2\n");
goto err;
}
board->basemem = ioremap_nocache(pci_resource_start(pdev, 2), 0x4000);
if (board->basemem == NULL) {
dev_err(&pdev->dev, "can't remap io space 2\n");
goto err_reg;
}
board->boardType = board_type;
switch (board_type) {
case MOXA_BOARD_C218_ISA:
case MOXA_BOARD_C218_PCI:
board->numPorts = 8;
break;
case MOXA_BOARD_CP204J:
board->numPorts = 4;
break;
default:
board->numPorts = 0;
break;
}
board->busType = MOXA_BUS_TYPE_PCI;
retval = moxa_init_board(board, &pdev->dev);
if (retval)
goto err_base;
pci_set_drvdata(pdev, board);
dev_info(&pdev->dev, "board '%s' ready (%u ports, firmware loaded)\n",
moxa_brdname[board_type - 1], board->numPorts);
return 0;
err_base:
iounmap(board->basemem);
board->basemem = NULL;
err_reg:
pci_release_region(pdev, 2);
err:
return retval;
}
static void __devexit moxa_pci_remove(struct pci_dev *pdev)
{
struct moxa_board_conf *brd = pci_get_drvdata(pdev);
moxa_board_deinit(brd);
pci_release_region(pdev, 2);
}
static struct pci_driver moxa_pci_driver = {
.name = "moxa",
.id_table = moxa_pcibrds,
.probe = moxa_pci_probe,
.remove = __devexit_p(moxa_pci_remove)
};
#endif /* CONFIG_PCI */
static int __init moxa_init(void)
{
unsigned int isabrds = 0;
int retval = 0;
struct moxa_board_conf *brd = moxa_boards;
unsigned int i;
printk(KERN_INFO "MOXA Intellio family driver version %s\n",
MOXA_VERSION);
moxaDriver = alloc_tty_driver(MAX_PORTS + 1);
if (!moxaDriver)
return -ENOMEM;
moxaDriver->name = "ttyMX";
moxaDriver->major = ttymajor;
moxaDriver->minor_start = 0;
moxaDriver->type = TTY_DRIVER_TYPE_SERIAL;
moxaDriver->subtype = SERIAL_TYPE_NORMAL;
moxaDriver->init_termios = tty_std_termios;
moxaDriver->init_termios.c_cflag = B9600 | CS8 | CREAD | CLOCAL | HUPCL;
moxaDriver->init_termios.c_ispeed = 9600;
moxaDriver->init_termios.c_ospeed = 9600;
moxaDriver->flags = TTY_DRIVER_REAL_RAW;
tty_set_operations(moxaDriver, &moxa_ops);
if (tty_register_driver(moxaDriver)) {
printk(KERN_ERR "can't register MOXA Smartio tty driver!\n");
put_tty_driver(moxaDriver);
return -1;
}
/* Find the boards defined from module args. */
for (i = 0; i < MAX_BOARDS; i++) {
if (!baseaddr[i])
break;
if (type[i] == MOXA_BOARD_C218_ISA ||
type[i] == MOXA_BOARD_C320_ISA) {
pr_debug("Moxa board %2d: %s board(baseAddr=%lx)\n",
isabrds + 1, moxa_brdname[type[i] - 1],
baseaddr[i]);
brd->boardType = type[i];
brd->numPorts = type[i] == MOXA_BOARD_C218_ISA ? 8 :
numports[i];
brd->busType = MOXA_BUS_TYPE_ISA;
brd->basemem = ioremap_nocache(baseaddr[i], 0x4000);
if (!brd->basemem) {
printk(KERN_ERR "MOXA: can't remap %lx\n",
baseaddr[i]);
continue;
}
if (moxa_init_board(brd, NULL)) {
iounmap(brd->basemem);
brd->basemem = NULL;
continue;
}
printk(KERN_INFO "MOXA isa board found at 0x%.8lu and "
"ready (%u ports, firmware loaded)\n",
baseaddr[i], brd->numPorts);
brd++;
isabrds++;
}
}
#ifdef CONFIG_PCI
retval = pci_register_driver(&moxa_pci_driver);
if (retval) {
printk(KERN_ERR "Can't register MOXA pci driver!\n");
if (isabrds)
retval = 0;
}
#endif
return retval;
}
static void __exit moxa_exit(void)
{
unsigned int i;
#ifdef CONFIG_PCI
pci_unregister_driver(&moxa_pci_driver);
#endif
for (i = 0; i < MAX_BOARDS; i++) /* ISA boards */
if (moxa_boards[i].ready)
moxa_board_deinit(&moxa_boards[i]);
del_timer_sync(&moxaTimer);
if (tty_unregister_driver(moxaDriver))
printk(KERN_ERR "Couldn't unregister MOXA Intellio family "
"serial driver\n");
put_tty_driver(moxaDriver);
}
module_init(moxa_init);
module_exit(moxa_exit);
static void moxa_shutdown(struct tty_port *port)
{
struct moxa_port *ch = container_of(port, struct moxa_port, port);
MoxaPortDisable(ch);
MoxaPortFlushData(ch, 2);
}
static int moxa_carrier_raised(struct tty_port *port)
{
struct moxa_port *ch = container_of(port, struct moxa_port, port);
int dcd;
spin_lock_irq(&port->lock);
dcd = ch->DCDState;
spin_unlock_irq(&port->lock);
return dcd;
}
static void moxa_dtr_rts(struct tty_port *port, int onoff)
{
struct moxa_port *ch = container_of(port, struct moxa_port, port);
MoxaPortLineCtrl(ch, onoff, onoff);
}
static int moxa_open(struct tty_struct *tty, struct file *filp)
{
struct moxa_board_conf *brd;
struct moxa_port *ch;
int port;
port = tty->index;
if (port == MAX_PORTS) {
return capable(CAP_SYS_ADMIN) ? 0 : -EPERM;
}
if (mutex_lock_interruptible(&moxa_openlock))
return -ERESTARTSYS;
brd = &moxa_boards[port / MAX_PORTS_PER_BOARD];
if (!brd->ready) {
mutex_unlock(&moxa_openlock);
return -ENODEV;
}
if (port % MAX_PORTS_PER_BOARD >= brd->numPorts) {
mutex_unlock(&moxa_openlock);
return -ENODEV;
}
ch = &brd->ports[port % MAX_PORTS_PER_BOARD];
ch->port.count++;
tty->driver_data = ch;
tty_port_tty_set(&ch->port, tty);
mutex_lock(&ch->port.mutex);
if (!(ch->port.flags & ASYNC_INITIALIZED)) {
ch->statusflags = 0;
moxa_set_tty_param(tty, tty->termios);
MoxaPortLineCtrl(ch, 1, 1);
MoxaPortEnable(ch);
MoxaSetFifo(ch, ch->type == PORT_16550A);
ch->port.flags |= ASYNC_INITIALIZED;
}
mutex_unlock(&ch->port.mutex);
mutex_unlock(&moxa_openlock);
return tty_port_block_til_ready(&ch->port, tty, filp);
}
static void moxa_close(struct tty_struct *tty, struct file *filp)
{
struct moxa_port *ch = tty->driver_data;
ch->cflag = tty->termios->c_cflag;
tty_port_close(&ch->port, tty, filp);
}
static int moxa_write(struct tty_struct *tty,
const unsigned char *buf, int count)
{
struct moxa_port *ch = tty->driver_data;
unsigned long flags;
int len;
if (ch == NULL)
return 0;
spin_lock_irqsave(&moxa_lock, flags);
len = MoxaPortWriteData(tty, buf, count);
spin_unlock_irqrestore(&moxa_lock, flags);
set_bit(LOWWAIT, &ch->statusflags);
return len;
}
static int moxa_write_room(struct tty_struct *tty)
{
struct moxa_port *ch;
if (tty->stopped)
return 0;
ch = tty->driver_data;
if (ch == NULL)
return 0;
return MoxaPortTxFree(ch);
}
static void moxa_flush_buffer(struct tty_struct *tty)
{
struct moxa_port *ch = tty->driver_data;
if (ch == NULL)
return;
MoxaPortFlushData(ch, 1);
tty_wakeup(tty);
}
static int moxa_chars_in_buffer(struct tty_struct *tty)
{
struct moxa_port *ch = tty->driver_data;
int chars;
chars = MoxaPortTxQueue(ch);
if (chars)
/*
* Make it possible to wakeup anything waiting for output
* in tty_ioctl.c, etc.
*/
set_bit(EMPTYWAIT, &ch->statusflags);
return chars;
}
static int moxa_tiocmget(struct tty_struct *tty)
{
struct moxa_port *ch = tty->driver_data;
int flag = 0, dtr, rts;
MoxaPortGetLineOut(ch, &dtr, &rts);
if (dtr)
flag |= TIOCM_DTR;
if (rts)
flag |= TIOCM_RTS;
dtr = MoxaPortLineStatus(ch);
if (dtr & 1)
flag |= TIOCM_CTS;
if (dtr & 2)
flag |= TIOCM_DSR;
if (dtr & 4)
flag |= TIOCM_CD;
return flag;
}
static int moxa_tiocmset(struct tty_struct *tty,
unsigned int set, unsigned int clear)
{
struct moxa_port *ch;
int dtr, rts;
mutex_lock(&moxa_openlock);
ch = tty->driver_data;
if (!ch) {
mutex_unlock(&moxa_openlock);
return -EINVAL;
}
MoxaPortGetLineOut(ch, &dtr, &rts);
if (set & TIOCM_RTS)
rts = 1;
if (set & TIOCM_DTR)
dtr = 1;
if (clear & TIOCM_RTS)
rts = 0;
if (clear & TIOCM_DTR)
dtr = 0;
MoxaPortLineCtrl(ch, dtr, rts);
mutex_unlock(&moxa_openlock);
return 0;
}
static void moxa_set_termios(struct tty_struct *tty,
struct ktermios *old_termios)
{
struct moxa_port *ch = tty->driver_data;
if (ch == NULL)
return;
moxa_set_tty_param(tty, old_termios);
if (!(old_termios->c_cflag & CLOCAL) && C_CLOCAL(tty))
wake_up_interruptible(&ch->port.open_wait);
}
static void moxa_stop(struct tty_struct *tty)
{
struct moxa_port *ch = tty->driver_data;
if (ch == NULL)
return;
MoxaPortTxDisable(ch);
set_bit(TXSTOPPED, &ch->statusflags);
}
static void moxa_start(struct tty_struct *tty)
{
struct moxa_port *ch = tty->driver_data;
if (ch == NULL)
return;
if (!test_bit(TXSTOPPED, &ch->statusflags))
return;
MoxaPortTxEnable(ch);
clear_bit(TXSTOPPED, &ch->statusflags);
}
static void moxa_hangup(struct tty_struct *tty)
{
struct moxa_port *ch = tty->driver_data;
tty_port_hangup(&ch->port);
}
static void moxa_new_dcdstate(struct moxa_port *p, u8 dcd)
{
struct tty_struct *tty;
unsigned long flags;
dcd = !!dcd;
spin_lock_irqsave(&p->port.lock, flags);
if (dcd != p->DCDState) {
p->DCDState = dcd;
spin_unlock_irqrestore(&p->port.lock, flags);
tty = tty_port_tty_get(&p->port);
if (tty && C_CLOCAL(tty) && !dcd)
tty_hangup(tty);
tty_kref_put(tty);
}
else
spin_unlock_irqrestore(&p->port.lock, flags);
}
static int moxa_poll_port(struct moxa_port *p, unsigned int handle,
u16 __iomem *ip)
{
struct tty_struct *tty = tty_port_tty_get(&p->port);
void __iomem *ofsAddr;
unsigned int inited = p->port.flags & ASYNC_INITIALIZED;
u16 intr;
if (tty) {
if (test_bit(EMPTYWAIT, &p->statusflags) &&
MoxaPortTxQueue(p) == 0) {
clear_bit(EMPTYWAIT, &p->statusflags);
tty_wakeup(tty);
}
if (test_bit(LOWWAIT, &p->statusflags) && !tty->stopped &&
MoxaPortTxQueue(p) <= WAKEUP_CHARS) {
clear_bit(LOWWAIT, &p->statusflags);
tty_wakeup(tty);
}
if (inited && !test_bit(TTY_THROTTLED, &tty->flags) &&
MoxaPortRxQueue(p) > 0) { /* RX */
MoxaPortReadData(p);
tty_schedule_flip(tty);
}
} else {
clear_bit(EMPTYWAIT, &p->statusflags);
MoxaPortFlushData(p, 0); /* flush RX */
}
if (!handle) /* nothing else to do */
goto put;
intr = readw(ip); /* port irq status */
if (intr == 0)
goto put;
writew(0, ip); /* ACK port */
ofsAddr = p->tableAddr;
if (intr & IntrTx) /* disable tx intr */
writew(readw(ofsAddr + HostStat) & ~WakeupTx,
ofsAddr + HostStat);
if (!inited)
goto put;
if (tty && (intr & IntrBreak) && !I_IGNBRK(tty)) { /* BREAK */
tty_insert_flip_char(tty, 0, TTY_BREAK);
tty_schedule_flip(tty);
}
if (intr & IntrLine)
moxa_new_dcdstate(p, readb(ofsAddr + FlagStat) & DCD_state);
put:
tty_kref_put(tty);
return 0;
}
static void moxa_poll(unsigned long ignored)
{
struct moxa_board_conf *brd;
u16 __iomem *ip;
unsigned int card, port, served = 0;
spin_lock(&moxa_lock);
for (card = 0; card < MAX_BOARDS; card++) {
brd = &moxa_boards[card];
if (!brd->ready)
continue;
served++;
ip = NULL;
if (readb(brd->intPend) == 0xff)
ip = brd->intTable + readb(brd->intNdx);
for (port = 0; port < brd->numPorts; port++)
moxa_poll_port(&brd->ports[port], !!ip, ip + port);
if (ip)
writeb(0, brd->intPend); /* ACK */
if (moxaLowWaterChk) {
struct moxa_port *p = brd->ports;
for (port = 0; port < brd->numPorts; port++, p++)
if (p->lowChkFlag) {
p->lowChkFlag = 0;
moxa_low_water_check(p->tableAddr);
}
}
}
moxaLowWaterChk = 0;
if (served)
mod_timer(&moxaTimer, jiffies + HZ / 50);
spin_unlock(&moxa_lock);
}
/******************************************************************************/
static void moxa_set_tty_param(struct tty_struct *tty, struct ktermios *old_termios)
{
register struct ktermios *ts = tty->termios;
struct moxa_port *ch = tty->driver_data;
int rts, cts, txflow, rxflow, xany, baud;
rts = cts = txflow = rxflow = xany = 0;
if (ts->c_cflag & CRTSCTS)
rts = cts = 1;
if (ts->c_iflag & IXON)
txflow = 1;
if (ts->c_iflag & IXOFF)
rxflow = 1;
if (ts->c_iflag & IXANY)
xany = 1;
/* Clear the features we don't support */
ts->c_cflag &= ~CMSPAR;
MoxaPortFlowCtrl(ch, rts, cts, txflow, rxflow, xany);
baud = MoxaPortSetTermio(ch, ts, tty_get_baud_rate(tty));
if (baud == -1)
baud = tty_termios_baud_rate(old_termios);
/* Not put the baud rate into the termios data */
tty_encode_baud_rate(tty, baud, baud);
}
/*****************************************************************************
* Driver level functions: *
*****************************************************************************/
static void MoxaPortFlushData(struct moxa_port *port, int mode)
{
void __iomem *ofsAddr;
if (mode < 0 || mode > 2)
return;
ofsAddr = port->tableAddr;
moxafunc(ofsAddr, FC_FlushQueue, mode);
if (mode != 1) {
port->lowChkFlag = 0;
moxa_low_water_check(ofsAddr);
}
}
/*
* Moxa Port Number Description:
*
* MOXA serial driver supports up to 4 MOXA-C218/C320 boards. And,
* the port number using in MOXA driver functions will be 0 to 31 for
* first MOXA board, 32 to 63 for second, 64 to 95 for third and 96
* to 127 for fourth. For example, if you setup three MOXA boards,
* first board is C218, second board is C320-16 and third board is
* C320-32. The port number of first board (C218 - 8 ports) is from
* 0 to 7. The port number of second board (C320 - 16 ports) is form
* 32 to 47. The port number of third board (C320 - 32 ports) is from
* 64 to 95. And those port numbers form 8 to 31, 48 to 63 and 96 to
* 127 will be invalid.
*
*
* Moxa Functions Description:
*
* Function 1: Driver initialization routine, this routine must be
* called when initialized driver.
* Syntax:
* void MoxaDriverInit();
*
*
* Function 2: Moxa driver private IOCTL command processing.
* Syntax:
* int MoxaDriverIoctl(unsigned int cmd, unsigned long arg, int port);
*
* unsigned int cmd : IOCTL command
* unsigned long arg : IOCTL argument
* int port : port number (0 - 127)
*
* return: 0 (OK)
* -EINVAL
* -ENOIOCTLCMD
*
*
* Function 6: Enable this port to start Tx/Rx data.
* Syntax:
* void MoxaPortEnable(int port);
* int port : port number (0 - 127)
*
*
* Function 7: Disable this port
* Syntax:
* void MoxaPortDisable(int port);
* int port : port number (0 - 127)
*
*
* Function 10: Setting baud rate of this port.
* Syntax:
* speed_t MoxaPortSetBaud(int port, speed_t baud);
* int port : port number (0 - 127)
* long baud : baud rate (50 - 115200)
*
* return: 0 : this port is invalid or baud < 50
* 50 - 115200 : the real baud rate set to the port, if
* the argument baud is large than maximun
* available baud rate, the real setting
* baud rate will be the maximun baud rate.
*
*
* Function 12: Configure the port.
* Syntax:
* int MoxaPortSetTermio(int port, struct ktermios *termio, speed_t baud);
* int port : port number (0 - 127)
* struct ktermios * termio : termio structure pointer
* speed_t baud : baud rate
*
* return: -1 : this port is invalid or termio == NULL
* 0 : setting O.K.
*
*
* Function 13: Get the DTR/RTS state of this port.
* Syntax:
* int MoxaPortGetLineOut(int port, int *dtrState, int *rtsState);
* int port : port number (0 - 127)
* int * dtrState : pointer to INT to receive the current DTR
* state. (if NULL, this function will not
* write to this address)
* int * rtsState : pointer to INT to receive the current RTS
* state. (if NULL, this function will not
* write to this address)
*
* return: -1 : this port is invalid
* 0 : O.K.
*
*
* Function 14: Setting the DTR/RTS output state of this port.
* Syntax:
* void MoxaPortLineCtrl(int port, int dtrState, int rtsState);
* int port : port number (0 - 127)
* int dtrState : DTR output state (0: off, 1: on)
* int rtsState : RTS output state (0: off, 1: on)
*
*
* Function 15: Setting the flow control of this port.
* Syntax:
* void MoxaPortFlowCtrl(int port, int rtsFlow, int ctsFlow, int rxFlow,
* int txFlow,int xany);
* int port : port number (0 - 127)
* int rtsFlow : H/W RTS flow control (0: no, 1: yes)
* int ctsFlow : H/W CTS flow control (0: no, 1: yes)
* int rxFlow : S/W Rx XON/XOFF flow control (0: no, 1: yes)
* int txFlow : S/W Tx XON/XOFF flow control (0: no, 1: yes)
* int xany : S/W XANY flow control (0: no, 1: yes)
*
*
* Function 16: Get ths line status of this port
* Syntax:
* int MoxaPortLineStatus(int port);
* int port : port number (0 - 127)
*
* return: Bit 0 - CTS state (0: off, 1: on)
* Bit 1 - DSR state (0: off, 1: on)
* Bit 2 - DCD state (0: off, 1: on)
*
*
* Function 19: Flush the Rx/Tx buffer data of this port.
* Syntax:
* void MoxaPortFlushData(int port, int mode);
* int port : port number (0 - 127)
* int mode
* 0 : flush the Rx buffer
* 1 : flush the Tx buffer
* 2 : flush the Rx and Tx buffer
*
*
* Function 20: Write data.
* Syntax:
* int MoxaPortWriteData(int port, unsigned char * buffer, int length);
* int port : port number (0 - 127)
* unsigned char * buffer : pointer to write data buffer.
* int length : write data length
*
* return: 0 - length : real write data length
*
*
* Function 21: Read data.
* Syntax:
* int MoxaPortReadData(int port, struct tty_struct *tty);
* int port : port number (0 - 127)
* struct tty_struct *tty : tty for data
*
* return: 0 - length : real read data length
*
*
* Function 24: Get the Tx buffer current queued data bytes
* Syntax:
* int MoxaPortTxQueue(int port);
* int port : port number (0 - 127)
*
* return: .. : Tx buffer current queued data bytes
*
*
* Function 25: Get the Tx buffer current free space
* Syntax:
* int MoxaPortTxFree(int port);
* int port : port number (0 - 127)
*
* return: .. : Tx buffer current free space
*
*
* Function 26: Get the Rx buffer current queued data bytes
* Syntax:
* int MoxaPortRxQueue(int port);
* int port : port number (0 - 127)
*
* return: .. : Rx buffer current queued data bytes
*
*
* Function 28: Disable port data transmission.
* Syntax:
* void MoxaPortTxDisable(int port);
* int port : port number (0 - 127)
*
*
* Function 29: Enable port data transmission.
* Syntax:
* void MoxaPortTxEnable(int port);
* int port : port number (0 - 127)
*
*
* Function 31: Get the received BREAK signal count and reset it.
* Syntax:
* int MoxaPortResetBrkCnt(int port);
* int port : port number (0 - 127)
*
* return: 0 - .. : BREAK signal count
*
*
*/
static void MoxaPortEnable(struct moxa_port *port)
{
void __iomem *ofsAddr;
u16 lowwater = 512;
ofsAddr = port->tableAddr;
writew(lowwater, ofsAddr + Low_water);
if (MOXA_IS_320(port->board))
moxafunc(ofsAddr, FC_SetBreakIrq, 0);
else
writew(readw(ofsAddr + HostStat) | WakeupBreak,
ofsAddr + HostStat);
moxafunc(ofsAddr, FC_SetLineIrq, Magic_code);
moxafunc(ofsAddr, FC_FlushQueue, 2);
moxafunc(ofsAddr, FC_EnableCH, Magic_code);
MoxaPortLineStatus(port);
}
static void MoxaPortDisable(struct moxa_port *port)
{
void __iomem *ofsAddr = port->tableAddr;
moxafunc(ofsAddr, FC_SetFlowCtl, 0); /* disable flow control */
moxafunc(ofsAddr, FC_ClrLineIrq, Magic_code);
writew(0, ofsAddr + HostStat);
moxafunc(ofsAddr, FC_DisableCH, Magic_code);
}
static speed_t MoxaPortSetBaud(struct moxa_port *port, speed_t baud)
{
void __iomem *ofsAddr = port->tableAddr;
unsigned int clock, val;
speed_t max;
max = MOXA_IS_320(port->board) ? 460800 : 921600;
if (baud < 50)
return 0;
if (baud > max)
baud = max;
clock = 921600;
val = clock / baud;
moxafunc(ofsAddr, FC_SetBaud, val);
baud = clock / val;
return baud;
}
static int MoxaPortSetTermio(struct moxa_port *port, struct ktermios *termio,
speed_t baud)
{
void __iomem *ofsAddr;
tcflag_t mode = 0;
ofsAddr = port->tableAddr;
mode = termio->c_cflag & CSIZE;
if (mode == CS5)
mode = MX_CS5;
else if (mode == CS6)
mode = MX_CS6;
else if (mode == CS7)
mode = MX_CS7;
else if (mode == CS8)
mode = MX_CS8;
if (termio->c_cflag & CSTOPB) {
if (mode == MX_CS5)
mode |= MX_STOP15;
else
mode |= MX_STOP2;
} else
mode |= MX_STOP1;
if (termio->c_cflag & PARENB) {
if (termio->c_cflag & PARODD)
mode |= MX_PARODD;
else
mode |= MX_PAREVEN;
} else
mode |= MX_PARNONE;
moxafunc(ofsAddr, FC_SetDataMode, (u16)mode);
if (MOXA_IS_320(port->board) && baud >= 921600)
return -1;
baud = MoxaPortSetBaud(port, baud);
if (termio->c_iflag & (IXON | IXOFF | IXANY)) {
spin_lock_irq(&moxafunc_lock);
writeb(termio->c_cc[VSTART], ofsAddr + FuncArg);
writeb(termio->c_cc[VSTOP], ofsAddr + FuncArg1);
writeb(FC_SetXonXoff, ofsAddr + FuncCode);
moxa_wait_finish(ofsAddr);
spin_unlock_irq(&moxafunc_lock);
}
return baud;
}
static int MoxaPortGetLineOut(struct moxa_port *port, int *dtrState,
int *rtsState)
{
if (dtrState)
*dtrState = !!(port->lineCtrl & DTR_ON);
if (rtsState)
*rtsState = !!(port->lineCtrl & RTS_ON);
return 0;
}
static void MoxaPortLineCtrl(struct moxa_port *port, int dtr, int rts)
{
u8 mode = 0;
if (dtr)
mode |= DTR_ON;
if (rts)
mode |= RTS_ON;
port->lineCtrl = mode;
moxafunc(port->tableAddr, FC_LineControl, mode);
}
static void MoxaPortFlowCtrl(struct moxa_port *port, int rts, int cts,
int txflow, int rxflow, int txany)
{
int mode = 0;
if (rts)
mode |= RTS_FlowCtl;
if (cts)
mode |= CTS_FlowCtl;
if (txflow)
mode |= Tx_FlowCtl;
if (rxflow)
mode |= Rx_FlowCtl;
if (txany)
mode |= IXM_IXANY;
moxafunc(port->tableAddr, FC_SetFlowCtl, mode);
}
static int MoxaPortLineStatus(struct moxa_port *port)
{
void __iomem *ofsAddr;
int val;
ofsAddr = port->tableAddr;
if (MOXA_IS_320(port->board))
val = moxafuncret(ofsAddr, FC_LineStatus, 0);
else
val = readw(ofsAddr + FlagStat) >> 4;
val &= 0x0B;
if (val & 8)
val |= 4;
moxa_new_dcdstate(port, val & 8);
val &= 7;
return val;
}
static int MoxaPortWriteData(struct tty_struct *tty,
const unsigned char *buffer, int len)
{
struct moxa_port *port = tty->driver_data;
void __iomem *baseAddr, *ofsAddr, *ofs;
unsigned int c, total;
u16 head, tail, tx_mask, spage, epage;
u16 pageno, pageofs, bufhead;
ofsAddr = port->tableAddr;
baseAddr = port->board->basemem;
tx_mask = readw(ofsAddr + TX_mask);
spage = readw(ofsAddr + Page_txb);
epage = readw(ofsAddr + EndPage_txb);
tail = readw(ofsAddr + TXwptr);
head = readw(ofsAddr + TXrptr);
c = (head > tail) ? (head - tail - 1) : (head - tail + tx_mask);
if (c > len)
c = len;
moxaLog.txcnt[port->port.tty->index] += c;
total = c;
if (spage == epage) {
bufhead = readw(ofsAddr + Ofs_txb);
writew(spage, baseAddr + Control_reg);
while (c > 0) {
if (head > tail)
len = head - tail - 1;
else
len = tx_mask + 1 - tail;
len = (c > len) ? len : c;
ofs = baseAddr + DynPage_addr + bufhead + tail;
memcpy_toio(ofs, buffer, len);
buffer += len;
tail = (tail + len) & tx_mask;
c -= len;
}
} else {
pageno = spage + (tail >> 13);
pageofs = tail & Page_mask;
while (c > 0) {
len = Page_size - pageofs;
if (len > c)
len = c;
writeb(pageno, baseAddr + Control_reg);
ofs = baseAddr + DynPage_addr + pageofs;
memcpy_toio(ofs, buffer, len);
buffer += len;
if (++pageno == epage)
pageno = spage;
pageofs = 0;
c -= len;
}
tail = (tail + total) & tx_mask;
}
writew(tail, ofsAddr + TXwptr);
writeb(1, ofsAddr + CD180TXirq); /* start to send */
return total;
}
static int MoxaPortReadData(struct moxa_port *port)
{
struct tty_struct *tty = port->port.tty;
unsigned char *dst;
void __iomem *baseAddr, *ofsAddr, *ofs;
unsigned int count, len, total;
u16 tail, rx_mask, spage, epage;
u16 pageno, pageofs, bufhead, head;
ofsAddr = port->tableAddr;
baseAddr = port->board->basemem;
head = readw(ofsAddr + RXrptr);
tail = readw(ofsAddr + RXwptr);
rx_mask = readw(ofsAddr + RX_mask);
spage = readw(ofsAddr + Page_rxb);
epage = readw(ofsAddr + EndPage_rxb);
count = (tail >= head) ? (tail - head) : (tail - head + rx_mask + 1);
if (count == 0)
return 0;
total = count;
moxaLog.rxcnt[tty->index] += total;
if (spage == epage) {
bufhead = readw(ofsAddr + Ofs_rxb);
writew(spage, baseAddr + Control_reg);
while (count > 0) {
ofs = baseAddr + DynPage_addr + bufhead + head;
len = (tail >= head) ? (tail - head) :
(rx_mask + 1 - head);
len = tty_prepare_flip_string(tty, &dst,
min(len, count));
memcpy_fromio(dst, ofs, len);
head = (head + len) & rx_mask;
count -= len;
}
} else {
pageno = spage + (head >> 13);
pageofs = head & Page_mask;
while (count > 0) {
writew(pageno, baseAddr + Control_reg);
ofs = baseAddr + DynPage_addr + pageofs;
len = tty_prepare_flip_string(tty, &dst,
min(Page_size - pageofs, count));
memcpy_fromio(dst, ofs, len);
count -= len;
pageofs = (pageofs + len) & Page_mask;
if (pageofs == 0 && ++pageno == epage)
pageno = spage;
}
head = (head + total) & rx_mask;
}
writew(head, ofsAddr + RXrptr);
if (readb(ofsAddr + FlagStat) & Xoff_state) {
moxaLowWaterChk = 1;
port->lowChkFlag = 1;
}
return total;
}
static int MoxaPortTxQueue(struct moxa_port *port)
{
void __iomem *ofsAddr = port->tableAddr;
u16 rptr, wptr, mask;
rptr = readw(ofsAddr + TXrptr);
wptr = readw(ofsAddr + TXwptr);
mask = readw(ofsAddr + TX_mask);
return (wptr - rptr) & mask;
}
static int MoxaPortTxFree(struct moxa_port *port)
{
void __iomem *ofsAddr = port->tableAddr;
u16 rptr, wptr, mask;
rptr = readw(ofsAddr + TXrptr);
wptr = readw(ofsAddr + TXwptr);
mask = readw(ofsAddr + TX_mask);
return mask - ((wptr - rptr) & mask);
}
static int MoxaPortRxQueue(struct moxa_port *port)
{
void __iomem *ofsAddr = port->tableAddr;
u16 rptr, wptr, mask;
rptr = readw(ofsAddr + RXrptr);
wptr = readw(ofsAddr + RXwptr);
mask = readw(ofsAddr + RX_mask);
return (wptr - rptr) & mask;
}
static void MoxaPortTxDisable(struct moxa_port *port)
{
moxafunc(port->tableAddr, FC_SetXoffState, Magic_code);
}
static void MoxaPortTxEnable(struct moxa_port *port)
{
moxafunc(port->tableAddr, FC_SetXonState, Magic_code);
}
static int moxa_get_serial_info(struct moxa_port *info,
struct serial_struct __user *retinfo)
{
struct serial_struct tmp = {
.type = info->type,
.line = info->port.tty->index,
.flags = info->port.flags,
.baud_base = 921600,
.close_delay = info->port.close_delay
};
return copy_to_user(retinfo, &tmp, sizeof(*retinfo)) ? -EFAULT : 0;
}
static int moxa_set_serial_info(struct moxa_port *info,
struct serial_struct __user *new_info)
{
struct serial_struct new_serial;
if (copy_from_user(&new_serial, new_info, sizeof(new_serial)))
return -EFAULT;
if (new_serial.irq != 0 || new_serial.port != 0 ||
new_serial.custom_divisor != 0 ||
new_serial.baud_base != 921600)
return -EPERM;
if (!capable(CAP_SYS_ADMIN)) {
if (((new_serial.flags & ~ASYNC_USR_MASK) !=
(info->port.flags & ~ASYNC_USR_MASK)))
return -EPERM;
} else
info->port.close_delay = new_serial.close_delay * HZ / 100;
new_serial.flags = (new_serial.flags & ~ASYNC_FLAGS);
new_serial.flags |= (info->port.flags & ASYNC_FLAGS);
MoxaSetFifo(info, new_serial.type == PORT_16550A);
info->type = new_serial.type;
return 0;
}
/*****************************************************************************
* Static local functions: *
*****************************************************************************/
static void MoxaSetFifo(struct moxa_port *port, int enable)
{
void __iomem *ofsAddr = port->tableAddr;
if (!enable) {
moxafunc(ofsAddr, FC_SetRxFIFOTrig, 0);
moxafunc(ofsAddr, FC_SetTxFIFOCnt, 1);
} else {
moxafunc(ofsAddr, FC_SetRxFIFOTrig, 3);
moxafunc(ofsAddr, FC_SetTxFIFOCnt, 16);
}
}
| gpl-2.0 |
pranav01/android_kernel_xiaomi_armani | arch/mips/loongson/common/setup.c | 8770 | 1197 | /*
* Copyright (C) 2007 Lemote Inc. & Insititute of Computing Technology
* Author: Fuxin Zhang, zhangfx@lemote.com
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/module.h>
#include <asm/wbflush.h>
#include <loongson.h>
#ifdef CONFIG_VT
#include <linux/console.h>
#include <linux/screen_info.h>
#endif
void (*__wbflush)(void);
EXPORT_SYMBOL(__wbflush);
static void wbflush_loongson(void)
{
asm(".set\tpush\n\t"
".set\tnoreorder\n\t"
".set mips3\n\t"
"sync\n\t"
"nop\n\t"
".set\tpop\n\t"
".set mips0\n\t");
}
void __init plat_mem_setup(void)
{
__wbflush = wbflush_loongson;
#ifdef CONFIG_VT
#if defined(CONFIG_VGA_CONSOLE)
conswitchp = &vga_con;
screen_info = (struct screen_info) {
.orig_x = 0,
.orig_y = 25,
.orig_video_cols = 80,
.orig_video_lines = 25,
.orig_video_isVGA = VIDEO_TYPE_VGAC,
.orig_video_points = 16,
};
#elif defined(CONFIG_DUMMY_CONSOLE)
conswitchp = &dummy_con;
#endif
#endif
}
| gpl-2.0 |
jfairladyz/LGP925_Kernel | sound/aoa/core/alsa.c | 12610 | 2430 | /*
* Apple Onboard Audio Alsa helpers
*
* Copyright 2006 Johannes Berg <johannes@sipsolutions.net>
*
* GPL v2, can be found in COPYING.
*/
#include <linux/module.h>
#include "alsa.h"
static int index = -1;
module_param(index, int, 0444);
MODULE_PARM_DESC(index, "index for AOA sound card.");
static struct aoa_card *aoa_card;
int aoa_alsa_init(char *name, struct module *mod, struct device *dev)
{
struct snd_card *alsa_card;
int err;
if (aoa_card)
/* cannot be EEXIST due to usage in aoa_fabric_register */
return -EBUSY;
err = snd_card_create(index, name, mod, sizeof(struct aoa_card),
&alsa_card);
if (err < 0)
return err;
aoa_card = alsa_card->private_data;
aoa_card->alsa_card = alsa_card;
alsa_card->dev = dev;
strlcpy(alsa_card->driver, "AppleOnbdAudio", sizeof(alsa_card->driver));
strlcpy(alsa_card->shortname, name, sizeof(alsa_card->shortname));
strlcpy(alsa_card->longname, name, sizeof(alsa_card->longname));
strlcpy(alsa_card->mixername, name, sizeof(alsa_card->mixername));
err = snd_card_register(aoa_card->alsa_card);
if (err < 0) {
printk(KERN_ERR "snd-aoa: couldn't register alsa card\n");
snd_card_free(aoa_card->alsa_card);
aoa_card = NULL;
return err;
}
return 0;
}
struct snd_card *aoa_get_card(void)
{
if (aoa_card)
return aoa_card->alsa_card;
return NULL;
}
EXPORT_SYMBOL_GPL(aoa_get_card);
void aoa_alsa_cleanup(void)
{
if (aoa_card) {
snd_card_free(aoa_card->alsa_card);
aoa_card = NULL;
}
}
int aoa_snd_device_new(snd_device_type_t type,
void * device_data, struct snd_device_ops * ops)
{
struct snd_card *card = aoa_get_card();
int err;
if (!card) return -ENOMEM;
err = snd_device_new(card, type, device_data, ops);
if (err) {
printk(KERN_ERR "snd-aoa: failed to create snd device (%d)\n", err);
return err;
}
err = snd_device_register(card, device_data);
if (err) {
printk(KERN_ERR "snd-aoa: failed to register "
"snd device (%d)\n", err);
printk(KERN_ERR "snd-aoa: have you forgotten the "
"dev_register callback?\n");
snd_device_free(card, device_data);
}
return err;
}
EXPORT_SYMBOL_GPL(aoa_snd_device_new);
int aoa_snd_ctl_add(struct snd_kcontrol* control)
{
int err;
if (!aoa_card) return -ENODEV;
err = snd_ctl_add(aoa_card->alsa_card, control);
if (err)
printk(KERN_ERR "snd-aoa: failed to add alsa control (%d)\n",
err);
return err;
}
EXPORT_SYMBOL_GPL(aoa_snd_ctl_add);
| gpl-2.0 |
EnJens/kernel_tf201_stock | drivers/media/video/cx88/cx88-dsp.c | 12866 | 8938 | /*
*
* Stereo and SAP detection for cx88
*
* Copyright (c) 2009 Marton Balint <cus@fazekas.hu>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/jiffies.h>
#include <asm/div64.h>
#include "cx88.h"
#include "cx88-reg.h"
#define INT_PI ((s32)(3.141592653589 * 32768.0))
#define compat_remainder(a, b) \
((float)(((s32)((a)*100))%((s32)((b)*100)))/100.0)
#define baseband_freq(carrier, srate, tone) ((s32)( \
(compat_remainder(carrier + tone, srate)) / srate * 2 * INT_PI))
/* We calculate the baseband frequencies of the carrier and the pilot tones
* based on the the sampling rate of the audio rds fifo. */
#define FREQ_A2_CARRIER baseband_freq(54687.5, 2689.36, 0.0)
#define FREQ_A2_DUAL baseband_freq(54687.5, 2689.36, 274.1)
#define FREQ_A2_STEREO baseband_freq(54687.5, 2689.36, 117.5)
/* The frequencies below are from the reference driver. They probably need
* further adjustments, because they are not tested at all. You may even need
* to play a bit with the registers of the chip to select the proper signal
* for the input of the audio rds fifo, and measure it's sampling rate to
* calculate the proper baseband frequencies... */
#define FREQ_A2M_CARRIER ((s32)(2.114516 * 32768.0))
#define FREQ_A2M_DUAL ((s32)(2.754916 * 32768.0))
#define FREQ_A2M_STEREO ((s32)(2.462326 * 32768.0))
#define FREQ_EIAJ_CARRIER ((s32)(1.963495 * 32768.0)) /* 5pi/8 */
#define FREQ_EIAJ_DUAL ((s32)(2.562118 * 32768.0))
#define FREQ_EIAJ_STEREO ((s32)(2.601053 * 32768.0))
#define FREQ_BTSC_DUAL ((s32)(1.963495 * 32768.0)) /* 5pi/8 */
#define FREQ_BTSC_DUAL_REF ((s32)(1.374446 * 32768.0)) /* 7pi/16 */
#define FREQ_BTSC_SAP ((s32)(2.471532 * 32768.0))
#define FREQ_BTSC_SAP_REF ((s32)(1.730072 * 32768.0))
/* The spectrum of the signal should be empty between these frequencies. */
#define FREQ_NOISE_START ((s32)(0.100000 * 32768.0))
#define FREQ_NOISE_END ((s32)(1.200000 * 32768.0))
static unsigned int dsp_debug;
module_param(dsp_debug, int, 0644);
MODULE_PARM_DESC(dsp_debug, "enable audio dsp debug messages");
#define dprintk(level, fmt, arg...) if (dsp_debug >= level) \
printk(KERN_DEBUG "%s/0: " fmt, core->name , ## arg)
static s32 int_cos(u32 x)
{
u32 t2, t4, t6, t8;
s32 ret;
u16 period = x / INT_PI;
if (period % 2)
return -int_cos(x - INT_PI);
x = x % INT_PI;
if (x > INT_PI/2)
return -int_cos(INT_PI/2 - (x % (INT_PI/2)));
/* Now x is between 0 and INT_PI/2.
* To calculate cos(x) we use it's Taylor polinom. */
t2 = x*x/32768/2;
t4 = t2*x/32768*x/32768/3/4;
t6 = t4*x/32768*x/32768/5/6;
t8 = t6*x/32768*x/32768/7/8;
ret = 32768-t2+t4-t6+t8;
return ret;
}
static u32 int_goertzel(s16 x[], u32 N, u32 freq)
{
/* We use the Goertzel algorithm to determine the power of the
* given frequency in the signal */
s32 s_prev = 0;
s32 s_prev2 = 0;
s32 coeff = 2*int_cos(freq);
u32 i;
u64 tmp;
u32 divisor;
for (i = 0; i < N; i++) {
s32 s = x[i] + ((s64)coeff*s_prev/32768) - s_prev2;
s_prev2 = s_prev;
s_prev = s;
}
tmp = (s64)s_prev2 * s_prev2 + (s64)s_prev * s_prev -
(s64)coeff * s_prev2 * s_prev / 32768;
/* XXX: N must be low enough so that N*N fits in s32.
* Else we need two divisions. */
divisor = N * N;
do_div(tmp, divisor);
return (u32) tmp;
}
static u32 freq_magnitude(s16 x[], u32 N, u32 freq)
{
u32 sum = int_goertzel(x, N, freq);
return (u32)int_sqrt(sum);
}
static u32 noise_magnitude(s16 x[], u32 N, u32 freq_start, u32 freq_end)
{
int i;
u32 sum = 0;
u32 freq_step;
int samples = 5;
if (N > 192) {
/* The last 192 samples are enough for noise detection */
x += (N-192);
N = 192;
}
freq_step = (freq_end - freq_start) / (samples - 1);
for (i = 0; i < samples; i++) {
sum += int_goertzel(x, N, freq_start);
freq_start += freq_step;
}
return (u32)int_sqrt(sum / samples);
}
static s32 detect_a2_a2m_eiaj(struct cx88_core *core, s16 x[], u32 N)
{
s32 carrier, stereo, dual, noise;
s32 carrier_freq, stereo_freq, dual_freq;
s32 ret;
switch (core->tvaudio) {
case WW_BG:
case WW_DK:
carrier_freq = FREQ_A2_CARRIER;
stereo_freq = FREQ_A2_STEREO;
dual_freq = FREQ_A2_DUAL;
break;
case WW_M:
carrier_freq = FREQ_A2M_CARRIER;
stereo_freq = FREQ_A2M_STEREO;
dual_freq = FREQ_A2M_DUAL;
break;
case WW_EIAJ:
carrier_freq = FREQ_EIAJ_CARRIER;
stereo_freq = FREQ_EIAJ_STEREO;
dual_freq = FREQ_EIAJ_DUAL;
break;
default:
printk(KERN_WARNING "%s/0: unsupported audio mode %d for %s\n",
core->name, core->tvaudio, __func__);
return UNSET;
}
carrier = freq_magnitude(x, N, carrier_freq);
stereo = freq_magnitude(x, N, stereo_freq);
dual = freq_magnitude(x, N, dual_freq);
noise = noise_magnitude(x, N, FREQ_NOISE_START, FREQ_NOISE_END);
dprintk(1, "detect a2/a2m/eiaj: carrier=%d, stereo=%d, dual=%d, "
"noise=%d\n", carrier, stereo, dual, noise);
if (stereo > dual)
ret = V4L2_TUNER_SUB_STEREO;
else
ret = V4L2_TUNER_SUB_LANG1 | V4L2_TUNER_SUB_LANG2;
if (core->tvaudio == WW_EIAJ) {
/* EIAJ checks may need adjustments */
if ((carrier > max(stereo, dual)*2) &&
(carrier < max(stereo, dual)*6) &&
(carrier > 20 && carrier < 200) &&
(max(stereo, dual) > min(stereo, dual))) {
/* For EIAJ the carrier is always present,
so we probably don't need noise detection */
return ret;
}
} else {
if ((carrier > max(stereo, dual)*2) &&
(carrier < max(stereo, dual)*8) &&
(carrier > 20 && carrier < 200) &&
(noise < 10) &&
(max(stereo, dual) > min(stereo, dual)*2)) {
return ret;
}
}
return V4L2_TUNER_SUB_MONO;
}
static s32 detect_btsc(struct cx88_core *core, s16 x[], u32 N)
{
s32 sap_ref = freq_magnitude(x, N, FREQ_BTSC_SAP_REF);
s32 sap = freq_magnitude(x, N, FREQ_BTSC_SAP);
s32 dual_ref = freq_magnitude(x, N, FREQ_BTSC_DUAL_REF);
s32 dual = freq_magnitude(x, N, FREQ_BTSC_DUAL);
dprintk(1, "detect btsc: dual_ref=%d, dual=%d, sap_ref=%d, sap=%d"
"\n", dual_ref, dual, sap_ref, sap);
/* FIXME: Currently not supported */
return UNSET;
}
static s16 *read_rds_samples(struct cx88_core *core, u32 *N)
{
const struct sram_channel *srch = &cx88_sram_channels[SRAM_CH27];
s16 *samples;
unsigned int i;
unsigned int bpl = srch->fifo_size/AUD_RDS_LINES;
unsigned int spl = bpl/4;
unsigned int sample_count = spl*(AUD_RDS_LINES-1);
u32 current_address = cx_read(srch->ptr1_reg);
u32 offset = (current_address - srch->fifo_start + bpl);
dprintk(1, "read RDS samples: current_address=%08x (offset=%08x), "
"sample_count=%d, aud_intstat=%08x\n", current_address,
current_address - srch->fifo_start, sample_count,
cx_read(MO_AUD_INTSTAT));
samples = kmalloc(sizeof(s16)*sample_count, GFP_KERNEL);
if (!samples)
return NULL;
*N = sample_count;
for (i = 0; i < sample_count; i++) {
offset = offset % (AUD_RDS_LINES*bpl);
samples[i] = cx_read(srch->fifo_start + offset);
offset += 4;
}
if (dsp_debug >= 2) {
dprintk(2, "RDS samples dump: ");
for (i = 0; i < sample_count; i++)
printk("%hd ", samples[i]);
printk(".\n");
}
return samples;
}
s32 cx88_dsp_detect_stereo_sap(struct cx88_core *core)
{
s16 *samples;
u32 N = 0;
s32 ret = UNSET;
/* If audio RDS fifo is disabled, we can't read the samples */
if (!(cx_read(MO_AUD_DMACNTRL) & 0x04))
return ret;
if (!(cx_read(AUD_CTL) & EN_FMRADIO_EN_RDS))
return ret;
/* Wait at least 500 ms after an audio standard change */
if (time_before(jiffies, core->last_change + msecs_to_jiffies(500)))
return ret;
samples = read_rds_samples(core, &N);
if (!samples)
return ret;
switch (core->tvaudio) {
case WW_BG:
case WW_DK:
case WW_EIAJ:
case WW_M:
ret = detect_a2_a2m_eiaj(core, samples, N);
break;
case WW_BTSC:
ret = detect_btsc(core, samples, N);
break;
case WW_NONE:
case WW_I:
case WW_L:
case WW_I2SPT:
case WW_FM:
case WW_I2SADC:
break;
}
kfree(samples);
if (UNSET != ret)
dprintk(1, "stereo/sap detection result:%s%s%s\n",
(ret & V4L2_TUNER_SUB_MONO) ? " mono" : "",
(ret & V4L2_TUNER_SUB_STEREO) ? " stereo" : "",
(ret & V4L2_TUNER_SUB_LANG2) ? " dual" : "");
return ret;
}
EXPORT_SYMBOL(cx88_dsp_detect_stereo_sap);
| gpl-2.0 |
thecubed/android_kernel_lge_geefhd | arch/m32r/mm/cache.c | 13890 | 2672 | /*
* linux/arch/m32r/mm/cache.c
*
* Copyright (C) 2002-2005 Hirokazu Takata, Hayato Fujiwara
*/
#include <asm/pgtable.h>
#undef MCCR
#if defined(CONFIG_CHIP_XNUX2) || defined(CONFIG_CHIP_M32700) \
|| defined(CONFIG_CHIP_VDEC2) || defined(CONFIG_CHIP_OPSP)
/* Cache Control Register */
#define MCCR ((volatile unsigned long*)0xfffffffc)
#define MCCR_CC (1UL << 7) /* Cache mode modify bit */
#define MCCR_IIV (1UL << 6) /* I-cache invalidate */
#define MCCR_DIV (1UL << 5) /* D-cache invalidate */
#define MCCR_DCB (1UL << 4) /* D-cache copy back */
#define MCCR_ICM (1UL << 1) /* I-cache mode [0:off,1:on] */
#define MCCR_DCM (1UL << 0) /* D-cache mode [0:off,1:on] */
#define MCCR_ICACHE_INV (MCCR_CC|MCCR_IIV)
#define MCCR_DCACHE_CB (MCCR_CC|MCCR_DCB)
#define MCCR_DCACHE_CBINV (MCCR_CC|MCCR_DIV|MCCR_DCB)
#define CHECK_MCCR(mccr) (mccr = *MCCR)
#elif defined(CONFIG_CHIP_M32102)
#define MCCR ((volatile unsigned char*)0xfffffffe)
#define MCCR_IIV (1UL << 0) /* I-cache invalidate */
#define MCCR_ICACHE_INV MCCR_IIV
#elif defined(CONFIG_CHIP_M32104)
#define MCCR ((volatile unsigned short*)0xfffffffe)
#define MCCR_IIV (1UL << 8) /* I-cache invalidate */
#define MCCR_DIV (1UL << 9) /* D-cache invalidate */
#define MCCR_DCB (1UL << 10) /* D-cache copy back */
#define MCCR_ICM (1UL << 0) /* I-cache mode [0:off,1:on] */
#define MCCR_DCM (1UL << 1) /* D-cache mode [0:off,1:on] */
#define MCCR_ICACHE_INV MCCR_IIV
#define MCCR_DCACHE_CB MCCR_DCB
#define MCCR_DCACHE_CBINV (MCCR_DIV|MCCR_DCB)
#endif
#ifndef MCCR
#error Unknown cache type.
#endif
/* Copy back and invalidate D-cache and invalidate I-cache all */
void _flush_cache_all(void)
{
#if defined(CONFIG_CHIP_M32102)
unsigned char mccr;
*MCCR = MCCR_ICACHE_INV;
#elif defined(CONFIG_CHIP_M32104)
unsigned short mccr;
/* Copyback and invalidate D-cache */
/* Invalidate I-cache */
*MCCR |= (MCCR_ICACHE_INV | MCCR_DCACHE_CBINV);
#else
unsigned long mccr;
/* Copyback and invalidate D-cache */
/* Invalidate I-cache */
*MCCR = MCCR_ICACHE_INV | MCCR_DCACHE_CBINV;
#endif
while ((mccr = *MCCR) & MCCR_IIV); /* loop while invalidating... */
}
/* Copy back D-cache and invalidate I-cache all */
void _flush_cache_copyback_all(void)
{
#if defined(CONFIG_CHIP_M32102)
unsigned char mccr;
*MCCR = MCCR_ICACHE_INV;
#elif defined(CONFIG_CHIP_M32104)
unsigned short mccr;
/* Copyback and invalidate D-cache */
/* Invalidate I-cache */
*MCCR |= (MCCR_ICACHE_INV | MCCR_DCACHE_CB);
#else
unsigned long mccr;
/* Copyback D-cache */
/* Invalidate I-cache */
*MCCR = MCCR_ICACHE_INV | MCCR_DCACHE_CB;
#endif
while ((mccr = *MCCR) & MCCR_IIV); /* loop while invalidating... */
}
| gpl-2.0 |
wezzynl/qmk_firmware | keyboards/ergodox_ez/keymaps/hacker_dvorak/tap_dance/mod_tap_layer_dances/quot_dquot.c | 67 | 1054 | //instanalize an instance of 'tap' for the Quote - Double Quote tap dance.
static tap quot_dquot_state = {
.is_press_action = true,
.state = 0
};
void quot_dquot_finished(qk_tap_dance_state_t *state, void *user_data) {
quot_dquot_state.state = current_dance(state);
switch (quot_dquot_state.state) {
case SINGLE_TAP:
register_code(KC_QUOT);
break;
case SINGLE_HOLD:
register_code(KC_LCTL);
register_code(KC_LALT);
break;
case DOUBLE_TAP:
register_code16(KC_DQUO);
break;
}
}
void quot_dquot_reset(qk_tap_dance_state_t *state, void *user_data) {
switch (quot_dquot_state.state) {
case SINGLE_TAP:
unregister_code(KC_QUOT);
break;
case SINGLE_HOLD:
unregister_code(KC_LCTL);
unregister_code(KC_LALT);
break;
case DOUBLE_TAP:
unregister_code16(KC_DQUO);
break;
}
quot_dquot_state.state = 0;
}
| gpl-2.0 |
xFleury/crawl-0.13.0-fairplay | source/contrib/sdl/src/video/directfb/SDL_DirectFB_yuv.c | 67 | 7520 | /*
SDL - Simple DirectMedia Layer
Copyright (C) 1997-2009 Sam Lantinga
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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Sam Lantinga
slouken@libsdl.org
*/
#include "SDL_config.h"
/* This is the DirectFB implementation of YUV video overlays */
#include "SDL_video.h"
#include "SDL_DirectFB_yuv.h"
#include "../SDL_yuvfuncs.h"
/* The functions used to manipulate software video overlays */
static struct private_yuvhwfuncs directfb_yuvfuncs = {
DirectFB_LockYUVOverlay,
DirectFB_UnlockYUVOverlay,
DirectFB_DisplayYUVOverlay,
DirectFB_FreeYUVOverlay
};
struct private_yuvhwdata {
DFBDisplayLayerID layer_id;
IDirectFBDisplayLayer *layer;
IDirectFBSurface *surface;
/* These are just so we don't have to allocate them separately */
Uint16 pitches[3];
Uint8 *planes[3];
};
static DFBEnumerationResult
enum_layers_callback( DFBDisplayLayerID id,
DFBDisplayLayerDescription desc,
void *data )
{
struct private_yuvhwdata *hwdata = (struct private_yuvhwdata *) data;
/* we don't want the primary */
if (id == DLID_PRIMARY)
return DFENUM_OK;
/* take the one with a surface for video */
if ((desc.caps & DLCAPS_SURFACE) && (desc.type & DLTF_VIDEO))
{
hwdata->layer_id = id;
return DFENUM_CANCEL;
}
return DFENUM_OK;
}
static DFBResult CreateYUVSurface(_THIS, struct private_yuvhwdata *hwdata,
int width, int height, Uint32 format)
{
DFBResult ret;
IDirectFB *dfb = HIDDEN->dfb;
IDirectFBDisplayLayer *layer;
DFBDisplayLayerConfig conf;
ret = dfb->EnumDisplayLayers (dfb, enum_layers_callback, hwdata);
if (ret)
{
SetDirectFBerror("IDirectFB::EnumDisplayLayers", ret);
return ret;
}
if (!hwdata->layer_id)
return DFB_UNSUPPORTED;
ret = dfb->GetDisplayLayer (dfb, hwdata->layer_id, &layer);
if (ret)
{
SetDirectFBerror("IDirectFB::GetDisplayLayer", ret);
return ret;
}
conf.flags = DLCONF_WIDTH | DLCONF_HEIGHT | DLCONF_PIXELFORMAT;
conf.width = width;
conf.height = height;
switch (format)
{
case SDL_YV12_OVERLAY:
conf.pixelformat = DSPF_YV12;
break;
case SDL_IYUV_OVERLAY:
conf.pixelformat = DSPF_I420;
break;
case SDL_YUY2_OVERLAY:
conf.pixelformat = DSPF_YUY2;
break;
case SDL_UYVY_OVERLAY:
conf.pixelformat = DSPF_UYVY;
break;
default:
fprintf (stderr, "SDL_DirectFB: Unsupported YUV format (0x%08x)!\n", format);
break;
}
/* Need to set coop level or newer DirectFB versions will fail here. */
ret = layer->SetCooperativeLevel (layer, DLSCL_ADMINISTRATIVE);
if (ret)
{
SetDirectFBerror("IDirectFBDisplayLayer::SetCooperativeLevel() failed", ret);
layer->Release (layer);
return ret;
}
ret = layer->SetConfiguration (layer, &conf);
if (ret)
{
SetDirectFBerror("IDirectFBDisplayLayer::SetConfiguration", ret);
layer->Release (layer);
return ret;
}
ret = layer->GetSurface (layer, &hwdata->surface);
if (ret)
{
SetDirectFBerror("IDirectFBDisplayLayer::GetSurface", ret);
layer->Release (layer);
return ret;
}
hwdata->layer = layer;
return DFB_OK;
}
SDL_Overlay *DirectFB_CreateYUVOverlay(_THIS, int width, int height, Uint32 format, SDL_Surface *display)
{
SDL_Overlay *overlay;
struct private_yuvhwdata *hwdata;
/* Create the overlay structure */
overlay = SDL_calloc (1, sizeof(SDL_Overlay));
if (!overlay)
{
SDL_OutOfMemory();
return NULL;
}
/* Fill in the basic members */
overlay->format = format;
overlay->w = width;
overlay->h = height;
/* Set up the YUV surface function structure */
overlay->hwfuncs = &directfb_yuvfuncs;
/* Create the pixel data and lookup tables */
hwdata = SDL_calloc(1, sizeof(struct private_yuvhwdata));
overlay->hwdata = hwdata;
if (!hwdata)
{
SDL_OutOfMemory();
SDL_FreeYUVOverlay (overlay);
return NULL;
}
if (CreateYUVSurface (this, hwdata, width, height, format))
{
SDL_FreeYUVOverlay (overlay);
return NULL;
}
overlay->hw_overlay = 1;
/* Set up the plane pointers */
overlay->pitches = hwdata->pitches;
overlay->pixels = hwdata->planes;
switch (format)
{
case SDL_YV12_OVERLAY:
case SDL_IYUV_OVERLAY:
overlay->planes = 3;
break;
default:
overlay->planes = 1;
break;
}
/* We're all done.. */
return overlay;
}
int DirectFB_LockYUVOverlay(_THIS, SDL_Overlay *overlay)
{
DFBResult ret;
void *data;
int pitch;
IDirectFBSurface *surface = overlay->hwdata->surface;
ret = surface->Lock (surface, DSLF_READ | DSLF_WRITE, &data, &pitch);
if (ret)
{
SetDirectFBerror("IDirectFBSurface::Lock", ret);
return -1;
}
/* Find the pitch and offset values for the overlay */
overlay->pitches[0] = (Uint16) pitch;
overlay->pixels[0] = (Uint8*) data;
switch (overlay->format)
{
case SDL_YV12_OVERLAY:
case SDL_IYUV_OVERLAY:
/* Add the two extra planes */
overlay->pitches[1] = overlay->pitches[0] / 2;
overlay->pitches[2] = overlay->pitches[0] / 2;
overlay->pixels[1] = overlay->pixels[0] + overlay->pitches[0] * overlay->h;
overlay->pixels[2] = overlay->pixels[1] + overlay->pitches[1] * overlay->h / 2;
break;
default:
/* Only one plane, no worries */
break;
}
return 0;
}
void DirectFB_UnlockYUVOverlay(_THIS, SDL_Overlay *overlay)
{
IDirectFBSurface *surface = overlay->hwdata->surface;
overlay->pixels[0] = overlay->pixels[1] = overlay->pixels[2] = NULL;
surface->Unlock (surface);
}
int DirectFB_DisplayYUVOverlay(_THIS, SDL_Overlay *overlay, SDL_Rect *src, SDL_Rect *dst)
{
DFBResult ret;
DFBDisplayLayerConfig conf;
IDirectFBDisplayLayer *primary = HIDDEN->layer;
IDirectFBDisplayLayer *layer = overlay->hwdata->layer;
primary->GetConfiguration (primary, &conf);
ret = layer->SetScreenLocation (layer,
dst->x / (float) conf.width, dst->y / (float) conf.height,
dst->w / (float) conf.width, dst->h / (float) conf.height );
if (ret)
{
SetDirectFBerror("IDirectFBDisplayLayer::SetScreenLocation", ret);
return -1;
}
return 0;
}
void DirectFB_FreeYUVOverlay(_THIS, SDL_Overlay *overlay)
{
struct private_yuvhwdata *hwdata;
hwdata = overlay->hwdata;
if (hwdata)
{
if (hwdata->surface)
hwdata->surface->Release (hwdata->surface);
if (hwdata->layer)
hwdata->layer->Release (hwdata->layer);
free (hwdata);
}
}
| gpl-2.0 |
qubir/PhoenixA20_linux_sourcecode | drivers/acpi/acpica/hwgpe.c | 67 | 13411 |
/******************************************************************************
*
* Module Name: hwgpe - Low level GPE enable/disable/clear functions
*
*****************************************************************************/
/*
* Copyright (C) 2000 - 2012, Intel Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* NO WARRANTY
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*/
#include <acpi/acpi.h>
#include "accommon.h"
#include "acevents.h"
#define _COMPONENT ACPI_HARDWARE
ACPI_MODULE_NAME("hwgpe")
/* Local prototypes */
static acpi_status
acpi_hw_enable_wakeup_gpe_block(struct acpi_gpe_xrupt_info *gpe_xrupt_info,
struct acpi_gpe_block_info *gpe_block,
void *context);
/******************************************************************************
*
* FUNCTION: acpi_hw_get_gpe_register_bit
*
* PARAMETERS: gpe_event_info - Info block for the GPE
* gpe_register_info - Info block for the GPE register
*
* RETURN: Register mask with a one in the GPE bit position
*
* DESCRIPTION: Compute the register mask for this GPE. One bit is set in the
* correct position for the input GPE.
*
******************************************************************************/
u32 acpi_hw_get_gpe_register_bit(struct acpi_gpe_event_info *gpe_event_info,
struct acpi_gpe_register_info *gpe_register_info)
{
return (u32)1 << (gpe_event_info->gpe_number -
gpe_register_info->base_gpe_number);
}
/******************************************************************************
*
* FUNCTION: acpi_hw_low_set_gpe
*
* PARAMETERS: gpe_event_info - Info block for the GPE to be disabled
* action - Enable or disable
*
* RETURN: Status
*
* DESCRIPTION: Enable or disable a single GPE in the parent enable register.
*
******************************************************************************/
acpi_status
acpi_hw_low_set_gpe(struct acpi_gpe_event_info *gpe_event_info, u32 action)
{
struct acpi_gpe_register_info *gpe_register_info;
acpi_status status;
u32 enable_mask;
u32 register_bit;
ACPI_FUNCTION_ENTRY();
/* Get the info block for the entire GPE register */
gpe_register_info = gpe_event_info->register_info;
if (!gpe_register_info) {
return (AE_NOT_EXIST);
}
/* Get current value of the enable register that contains this GPE */
status = acpi_hw_read(&enable_mask, &gpe_register_info->enable_address);
if (ACPI_FAILURE(status)) {
return (status);
}
/* Set or clear just the bit that corresponds to this GPE */
register_bit = acpi_hw_get_gpe_register_bit(gpe_event_info,
gpe_register_info);
switch (action) {
case ACPI_GPE_CONDITIONAL_ENABLE:
/* Only enable if the enable_for_run bit is set */
if (!(register_bit & gpe_register_info->enable_for_run)) {
return (AE_BAD_PARAMETER);
}
/*lint -fallthrough */
case ACPI_GPE_ENABLE:
ACPI_SET_BIT(enable_mask, register_bit);
break;
case ACPI_GPE_DISABLE:
ACPI_CLEAR_BIT(enable_mask, register_bit);
break;
default:
ACPI_ERROR((AE_INFO, "Invalid GPE Action, %u\n", action));
return (AE_BAD_PARAMETER);
}
/* Write the updated enable mask */
status = acpi_hw_write(enable_mask, &gpe_register_info->enable_address);
return (status);
}
/******************************************************************************
*
* FUNCTION: acpi_hw_clear_gpe
*
* PARAMETERS: gpe_event_info - Info block for the GPE to be cleared
*
* RETURN: Status
*
* DESCRIPTION: Clear the status bit for a single GPE.
*
******************************************************************************/
acpi_status acpi_hw_clear_gpe(struct acpi_gpe_event_info * gpe_event_info)
{
struct acpi_gpe_register_info *gpe_register_info;
acpi_status status;
u32 register_bit;
ACPI_FUNCTION_ENTRY();
/* Get the info block for the entire GPE register */
gpe_register_info = gpe_event_info->register_info;
if (!gpe_register_info) {
return (AE_NOT_EXIST);
}
/*
* Write a one to the appropriate bit in the status register to
* clear this GPE.
*/
register_bit =
acpi_hw_get_gpe_register_bit(gpe_event_info, gpe_register_info);
status = acpi_hw_write(register_bit,
&gpe_register_info->status_address);
return (status);
}
/******************************************************************************
*
* FUNCTION: acpi_hw_get_gpe_status
*
* PARAMETERS: gpe_event_info - Info block for the GPE to queried
* event_status - Where the GPE status is returned
*
* RETURN: Status
*
* DESCRIPTION: Return the status of a single GPE.
*
******************************************************************************/
acpi_status
acpi_hw_get_gpe_status(struct acpi_gpe_event_info * gpe_event_info,
acpi_event_status * event_status)
{
u32 in_byte;
u32 register_bit;
struct acpi_gpe_register_info *gpe_register_info;
acpi_event_status local_event_status = 0;
acpi_status status;
ACPI_FUNCTION_ENTRY();
if (!event_status) {
return (AE_BAD_PARAMETER);
}
/* Get the info block for the entire GPE register */
gpe_register_info = gpe_event_info->register_info;
/* Get the register bitmask for this GPE */
register_bit = acpi_hw_get_gpe_register_bit(gpe_event_info,
gpe_register_info);
/* GPE currently enabled? (enabled for runtime?) */
if (register_bit & gpe_register_info->enable_for_run) {
local_event_status |= ACPI_EVENT_FLAG_ENABLED;
}
/* GPE enabled for wake? */
if (register_bit & gpe_register_info->enable_for_wake) {
local_event_status |= ACPI_EVENT_FLAG_WAKE_ENABLED;
}
/* GPE currently active (status bit == 1)? */
status = acpi_hw_read(&in_byte, &gpe_register_info->status_address);
if (ACPI_FAILURE(status)) {
return (status);
}
if (register_bit & in_byte) {
local_event_status |= ACPI_EVENT_FLAG_SET;
}
/* Set return value */
(*event_status) = local_event_status;
return (AE_OK);
}
/******************************************************************************
*
* FUNCTION: acpi_hw_disable_gpe_block
*
* PARAMETERS: gpe_xrupt_info - GPE Interrupt info
* gpe_block - Gpe Block info
*
* RETURN: Status
*
* DESCRIPTION: Disable all GPEs within a single GPE block
*
******************************************************************************/
acpi_status
acpi_hw_disable_gpe_block(struct acpi_gpe_xrupt_info *gpe_xrupt_info,
struct acpi_gpe_block_info *gpe_block, void *context)
{
u32 i;
acpi_status status;
/* Examine each GPE Register within the block */
for (i = 0; i < gpe_block->register_count; i++) {
/* Disable all GPEs in this register */
status =
acpi_hw_write(0x00,
&gpe_block->register_info[i].enable_address);
if (ACPI_FAILURE(status)) {
return (status);
}
}
return (AE_OK);
}
/******************************************************************************
*
* FUNCTION: acpi_hw_clear_gpe_block
*
* PARAMETERS: gpe_xrupt_info - GPE Interrupt info
* gpe_block - Gpe Block info
*
* RETURN: Status
*
* DESCRIPTION: Clear status bits for all GPEs within a single GPE block
*
******************************************************************************/
acpi_status
acpi_hw_clear_gpe_block(struct acpi_gpe_xrupt_info *gpe_xrupt_info,
struct acpi_gpe_block_info *gpe_block, void *context)
{
u32 i;
acpi_status status;
/* Examine each GPE Register within the block */
for (i = 0; i < gpe_block->register_count; i++) {
/* Clear status on all GPEs in this register */
status =
acpi_hw_write(0xFF,
&gpe_block->register_info[i].status_address);
if (ACPI_FAILURE(status)) {
return (status);
}
}
return (AE_OK);
}
/******************************************************************************
*
* FUNCTION: acpi_hw_enable_runtime_gpe_block
*
* PARAMETERS: gpe_xrupt_info - GPE Interrupt info
* gpe_block - Gpe Block info
*
* RETURN: Status
*
* DESCRIPTION: Enable all "runtime" GPEs within a single GPE block. Includes
* combination wake/run GPEs.
*
******************************************************************************/
acpi_status
acpi_hw_enable_runtime_gpe_block(struct acpi_gpe_xrupt_info *gpe_xrupt_info,
struct acpi_gpe_block_info *gpe_block, void *context)
{
u32 i;
acpi_status status;
/* NOTE: assumes that all GPEs are currently disabled */
/* Examine each GPE Register within the block */
for (i = 0; i < gpe_block->register_count; i++) {
if (!gpe_block->register_info[i].enable_for_run) {
continue;
}
/* Enable all "runtime" GPEs in this register */
status =
acpi_hw_write(gpe_block->register_info[i].enable_for_run,
&gpe_block->register_info[i].enable_address);
if (ACPI_FAILURE(status)) {
return (status);
}
}
return (AE_OK);
}
/******************************************************************************
*
* FUNCTION: acpi_hw_enable_wakeup_gpe_block
*
* PARAMETERS: gpe_xrupt_info - GPE Interrupt info
* gpe_block - Gpe Block info
*
* RETURN: Status
*
* DESCRIPTION: Enable all "wake" GPEs within a single GPE block. Includes
* combination wake/run GPEs.
*
******************************************************************************/
static acpi_status
acpi_hw_enable_wakeup_gpe_block(struct acpi_gpe_xrupt_info *gpe_xrupt_info,
struct acpi_gpe_block_info *gpe_block,
void *context)
{
u32 i;
acpi_status status;
/* Examine each GPE Register within the block */
for (i = 0; i < gpe_block->register_count; i++) {
if (!gpe_block->register_info[i].enable_for_wake) {
continue;
}
/* Enable all "wake" GPEs in this register */
status =
acpi_hw_write(gpe_block->register_info[i].enable_for_wake,
&gpe_block->register_info[i].enable_address);
if (ACPI_FAILURE(status)) {
return (status);
}
}
return (AE_OK);
}
/******************************************************************************
*
* FUNCTION: acpi_hw_disable_all_gpes
*
* PARAMETERS: None
*
* RETURN: Status
*
* DESCRIPTION: Disable and clear all GPEs in all GPE blocks
*
******************************************************************************/
acpi_status acpi_hw_disable_all_gpes(void)
{
acpi_status status;
ACPI_FUNCTION_TRACE(hw_disable_all_gpes);
status = acpi_ev_walk_gpe_list(acpi_hw_disable_gpe_block, NULL);
status = acpi_ev_walk_gpe_list(acpi_hw_clear_gpe_block, NULL);
return_ACPI_STATUS(status);
}
/******************************************************************************
*
* FUNCTION: acpi_hw_enable_all_runtime_gpes
*
* PARAMETERS: None
*
* RETURN: Status
*
* DESCRIPTION: Enable all "runtime" GPEs, in all GPE blocks
*
******************************************************************************/
acpi_status acpi_hw_enable_all_runtime_gpes(void)
{
acpi_status status;
ACPI_FUNCTION_TRACE(hw_enable_all_runtime_gpes);
status = acpi_ev_walk_gpe_list(acpi_hw_enable_runtime_gpe_block, NULL);
return_ACPI_STATUS(status);
}
/******************************************************************************
*
* FUNCTION: acpi_hw_enable_all_wakeup_gpes
*
* PARAMETERS: None
*
* RETURN: Status
*
* DESCRIPTION: Enable all "wakeup" GPEs, in all GPE blocks
*
******************************************************************************/
acpi_status acpi_hw_enable_all_wakeup_gpes(void)
{
acpi_status status;
ACPI_FUNCTION_TRACE(hw_enable_all_wakeup_gpes);
status = acpi_ev_walk_gpe_list(acpi_hw_enable_wakeup_gpe_block, NULL);
return_ACPI_STATUS(status);
}
| gpl-2.0 |
RasPlex/plex-home-theatre | lib/timidity/timidity/resample.c | 67 | 36762 | /*
TiMidity++ -- MIDI to WAVE converter and player
Copyright (C) 1999-2002 Masanao Izumo <mo@goice.co.jp>
Copyright (C) 1995 Tuukka Toivonen <tt@cgs.fi>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
resample.c
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif /* HAVE_CONFIG_H */
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#ifndef NO_STRING_H
#include <string.h>
#else
#include <strings.h>
#endif
#include "timidity.h"
#include "common.h"
#include "instrum.h"
#include "playmidi.h"
#include "output.h"
#include "controls.h"
#include "tables.h"
#include "resample.h"
#include "recache.h"
/* for start/end of samples */
static float newt_coeffs[58][58] = {
#include "newton_table.c"
};
int sample_bounds_min, sample_bounds_max; /* min/max bounds for sample data */
/* 4-point interpolation by cubic spline curve. */
static resample_t resample_cspline(sample_t *src, splen_t ofs, resample_rec_t *rec)
{
int32 ofsi, ofsf, v0, v1, v2, v3, temp;
ofsi = ofs >> FRACTION_BITS;
v1 = src[ofsi];
v2 = src[ofsi + 1];
if((ofs<rec->loop_start+(1L<<FRACTION_BITS))||
((ofs+(2L<<FRACTION_BITS))>rec->loop_end)){
return (v1 + ((resample_t)((v2 - v1) * (ofs & FRACTION_MASK)) >> FRACTION_BITS));
} else {
v0 = src[ofsi - 1];
v3 = src[ofsi + 2];
ofsf = ofs & FRACTION_MASK;
temp = v2;
v2 = (6 * v2 + ((((5 * v3 - 11 * v2 + 7 * v1 - v0) >> 2) *
(ofsf + (1L << FRACTION_BITS)) >> FRACTION_BITS) *
(ofsf - (1L << FRACTION_BITS)) >> FRACTION_BITS))
* ofsf;
v1 = (((6 * v1+((((5 * v0 - 11 * v1 + 7 * temp - v3) >> 2) *
ofsf >> FRACTION_BITS) * (ofsf - (2L << FRACTION_BITS))
>> FRACTION_BITS)) * ((1L << FRACTION_BITS) - ofsf)) + v2)
/ (6L << FRACTION_BITS);
return ((v1 > sample_bounds_max) ? sample_bounds_max :
((v1 < sample_bounds_min) ? sample_bounds_min : v1));
}
}
/* 4-point interpolation by Lagrange method.
Lagrange is now faster than C-spline. Both have about the same accuracy,
so choose Lagrange over C-spline, since it is faster. Technically, it is
really a 3rd order Newton polynomial (whereas the old Lagrange truely was
the Lagrange form of the polynomial). Both Newton and Lagrange forms
yield the same numerical results, but the Newton form is faster. Since
n'th order Newton interpolaiton is resample_newton(), it made sense to
just keep this labeled as resample_lagrange(), even if it really is the
Newton form of the polynomial. */
static resample_t resample_lagrange(sample_t *src, splen_t ofs, resample_rec_t *rec)
{
int32 ofsi, ofsf, v0, v1, v2, v3;
ofsi = ofs >> FRACTION_BITS;
v1 = (int32)src[ofsi];
v2 = (int32)src[ofsi + 1];
if((ofs<rec->loop_start+(1L<<FRACTION_BITS))||
((ofs+(2L<<FRACTION_BITS))>rec->loop_end)) {
return (v1 + ((resample_t)((v2 - v1) * (ofs & FRACTION_MASK)) >> FRACTION_BITS));
} else {
v0 = (int32)src[ofsi - 1];
v3 = (int32)src[ofsi + 2];
ofsf = (ofs & FRACTION_MASK) + (1<<FRACTION_BITS);
v3 += -3*v2 + 3*v1 - v0;
v3 *= (ofsf - (2<<FRACTION_BITS)) / 6;
v3 >>= FRACTION_BITS;
v3 += v2 - v1 - v1 + v0;
v3 *= (ofsf - (1<<FRACTION_BITS)) >> 1;
v3 >>= FRACTION_BITS;
v3 += v1 - v0;
v3 *= ofsf;
v3 >>= FRACTION_BITS;
v3 += v0;
return ((v3 > sample_bounds_max) ? sample_bounds_max :
((v3 < sample_bounds_min) ? sample_bounds_min : v3));
}
}
/* Very fast and accurate table based interpolation. Better speed and higher
accuracy than Newton. This isn't *quite* true Gauss interpolation; it's
more a slightly modified Gauss interpolation that I accidently stumbled
upon. Rather than normalize all x values in the window to be in the range
[0 to 2*PI], it simply divides them all by 2*PI instead. I don't know why
this works, but it does. Gauss should only work on periodic data with the
window spanning exactly one period, so it is no surprise that regular Gauss
interpolation doesn't work too well on general audio data. But dividing
the x values by 2*PI magically does. Any other scaling produces degraded
results or total garbage. If anyone can work out the theory behind why
this works so well (at first glance, it shouldn't ??), please contact me
(Eric A. Welsh, ewelsh@ccb.wustl.edu), as I would really like to have some
mathematical justification for doing this. Despite the lack of any sound
theoretical basis, this method DOES result in highly accurate interpolation
(or possibly approximaton, not sure yet if it truly interpolates, but it
looks like it does). -N 34 is as high as it can go before errors start
appearing. But even at -N 34, it is more accurate than Newton at -N 57.
-N 34 has no problem running in realtime on my system, but -N 25 is the
default, since that is the optimal compromise between speed and accuracy.
I strongly recommend using Gauss interpolation. It is the highest
quality interpolation option available, and is much faster than using
Newton polynomials. */
#define DEFAULT_GAUSS_ORDER 25
static float *gauss_table[(1<<FRACTION_BITS)] = {0}; /* don't need doubles */
static int gauss_n = DEFAULT_GAUSS_ORDER;
static resample_t resample_gauss(sample_t *src, splen_t ofs, resample_rec_t *rec)
{
sample_t *sptr;
int32 left, right, temp_n;
left = (ofs>>FRACTION_BITS);
right = (rec->data_length>>FRACTION_BITS) - left - 1;
temp_n = (right<<1)-1;
if (temp_n > (left<<1)+1)
temp_n = (left<<1)+1;
if (temp_n < gauss_n) {
int ii, jj;
float xd, y;
if (temp_n <= 0)
temp_n = 1;
xd = ofs & FRACTION_MASK;
xd /= (1L<<FRACTION_BITS);
xd += temp_n>>1;
y = 0;
sptr = src + (ofs>>FRACTION_BITS) - (temp_n>>1);
for (ii = temp_n; ii;) {
for (jj = 0; jj <= ii; jj++)
y += sptr[jj] * newt_coeffs[ii][jj];
y *= xd - --ii;
}
y += *sptr;
return ((y > sample_bounds_max) ? sample_bounds_max :
((y < sample_bounds_min) ? sample_bounds_min : y));
} else {
float *gptr, *gend;
float y;
y = 0;
sptr = src + left - (gauss_n>>1);
gptr = gauss_table[ofs&FRACTION_MASK];
if (gauss_n == DEFAULT_GAUSS_ORDER) {
/* expanding the loop for the default case.
* this will allow intensive optimization when compiled
* with SSE2 capability.
*/
#define do_gauss y += *(sptr++) * *(gptr++);
do_gauss;
do_gauss;
do_gauss;
do_gauss;
do_gauss;
do_gauss;
do_gauss;
do_gauss;
do_gauss;
do_gauss;
do_gauss;
do_gauss;
do_gauss;
do_gauss;
do_gauss;
do_gauss;
do_gauss;
do_gauss;
do_gauss;
do_gauss;
do_gauss;
do_gauss;
do_gauss;
do_gauss;
do_gauss;
y += *sptr * *gptr;
#undef do_gauss
} else {
gend = gptr + gauss_n;
do {
y += *(sptr++) * *(gptr++);
} while (gptr <= gend);
}
return ((y > sample_bounds_max) ? sample_bounds_max :
((y < sample_bounds_min) ? sample_bounds_min : y));
}
}
/* (at least) n+1 point interpolation using Newton polynomials.
n can be set with a command line option, and
must be an odd number from 1 to 57 (57 is as high as double precision
can go without precision errors). Default n = 11 is good for a 1.533 MHz
Athlon. Larger values for n require very fast processors for real time
playback. Some points will be interpolated at orders > n to both increase
accuracy and save CPU. */
static int newt_n = 11;
static int32 newt_old_trunc_x = -1;
static int newt_grow = -1;
static int newt_max = 13;
static double newt_divd[60][60];
static double newt_recip[60] = { 0, 1, 1.0/2, 1.0/3, 1.0/4, 1.0/5, 1.0/6, 1.0/7,
1.0/8, 1.0/9, 1.0/10, 1.0/11, 1.0/12, 1.0/13, 1.0/14,
1.0/15, 1.0/16, 1.0/17, 1.0/18, 1.0/19, 1.0/20, 1.0/21,
1.0/22, 1.0/23, 1.0/24, 1.0/25, 1.0/26, 1.0/27, 1.0/28,
1.0/29, 1.0/30, 1.0/31, 1.0/32, 1.0/33, 1.0/34, 1.0/35,
1.0/36, 1.0/37, 1.0/38, 1.0/39, 1.0/40, 1.0/41, 1.0/42,
1.0/43, 1.0/44, 1.0/45, 1.0/46, 1.0/47, 1.0/48, 1.0/49,
1.0/50, 1.0/51, 1.0/52, 1.0/53, 1.0/54, 1.0/55, 1.0/56,
1.0/57, 1.0/58, 1.0/59 };
static sample_t *newt_old_src = NULL;
static resample_t resample_newton(sample_t *src, splen_t ofs, resample_rec_t *rec)
{
int n_new, n_old;
int32 v1, v2, diff;
sample_t *sptr;
double y, xd;
int32 left, right, temp_n;
int ii, jj;
left = (ofs>>FRACTION_BITS);
right = (rec->data_length>>FRACTION_BITS)-(ofs>>FRACTION_BITS)-1;
temp_n = (right<<1)-1;
if (temp_n <= 0)
temp_n = 1;
if (temp_n > (left<<1)+1)
temp_n = (left<<1)+1;
if (temp_n < newt_n) {
xd = ofs & FRACTION_MASK;
xd /= (1L<<FRACTION_BITS);
xd += temp_n>>1;
y = 0;
sptr = src + (ofs>>FRACTION_BITS) - (temp_n>>1);
for (ii = temp_n; ii;) {
for (jj = 0; jj <= ii; jj++)
y += sptr[jj] * newt_coeffs[ii][jj];
y *= xd - --ii;
} y += *sptr;
}else{
if (newt_grow >= 0 && src == newt_old_src &&
(diff = (ofs>>FRACTION_BITS) - newt_old_trunc_x) > 0){
n_new = newt_n + ((newt_grow + diff)<<1);
if (n_new <= newt_max){
n_old = newt_n + (newt_grow<<1);
newt_grow += diff;
for (v1=(ofs>>FRACTION_BITS)+(n_new>>1)+1,v2=n_new;
v2 > n_old; --v1, --v2){
newt_divd[0][v2] = src[v1];
}for (v1 = 1; v1 <= n_new; v1++)
for (v2 = n_new; v2 > n_old; --v2)
newt_divd[v1][v2] = (newt_divd[v1-1][v2] -
newt_divd[v1-1][v2-1]) *
newt_recip[v1];
}else newt_grow = -1;
}
if (newt_grow < 0 || src != newt_old_src || diff < 0){
newt_grow = 0;
for (v1=(ofs>>FRACTION_BITS)-(newt_n>>1),v2=0;
v2 <= newt_n; v1++, v2++){
newt_divd[0][v2] = src[v1];
}for (v1 = 1; v1 <= newt_n; v1++)
for (v2 = newt_n; v2 >= v1; --v2)
newt_divd[v1][v2] = (newt_divd[v1-1][v2] -
newt_divd[v1-1][v2-1]) *
newt_recip[v1];
}
n_new = newt_n + (newt_grow<<1);
v2 = n_new;
y = newt_divd[v2][v2];
xd = (double)(ofs&FRACTION_MASK) / (1L<<FRACTION_BITS) +
(newt_n>>1) + newt_grow;
for (--v2; v2; --v2){
y *= xd - v2;
y += newt_divd[v2][v2];
}y = y*xd + **newt_divd;
newt_old_src = src;
newt_old_trunc_x = (ofs>>FRACTION_BITS);
}
return ((y > sample_bounds_max) ? sample_bounds_max :
((y < sample_bounds_min) ? sample_bounds_min : y));
}
/* Simple linear interpolation */
static resample_t resample_linear(sample_t *src, splen_t ofs, resample_rec_t *rec)
{
int32 v1, v2, ofsi;
ofsi = ofs >> FRACTION_BITS;
v1 = src[ofsi];
v2 = src[ofsi + 1];
#if defined(LOOKUP_HACK) && defined(LOOKUP_INTERPOLATION)
return (sample_t)(v1 + (iplookup[(((v2 - v1) << 5) & 0x03FE0) |
((ofs & FRACTION_MASK) >> (FRACTION_BITS-5))]));
#else
return (v1 + ((resample_t)((v2 - v1) * (ofs & FRACTION_MASK)) >> FRACTION_BITS));
#endif
}
/* No interpolation -- Earplugs recommended for maximum listening enjoyment */
static resample_t resample_none(sample_t *src, splen_t ofs, resample_rec_t *rec)
{
return src[ofs >> FRACTION_BITS];
}
/*
*/
typedef resample_t (*resampler_t)(sample_t*, splen_t, resample_rec_t *);
static resampler_t resamplers[] = {
resample_cspline,
resample_lagrange,
resample_gauss,
resample_newton,
resample_linear,
resample_none
};
#ifdef FIXED_RESAMPLATION
/* don't allow to change the resamplation algorighm.
* accessing directly to the given function.
* hope the compiler will optimize the overhead of function calls in this case.
*/
#define cur_resample DEFAULT_RESAMPLATION
#else
static resampler_t cur_resample = DEFAULT_RESAMPLATION;
#endif
#define RESAMPLATION *dest++ = cur_resample(src, ofs, &resrc);
/* exported for recache.c */
resample_t do_resamplation(sample_t *src, splen_t ofs, resample_rec_t *rec)
{
return cur_resample(src, ofs, rec);
}
/* return the current resampling algorithm */
int get_current_resampler(void)
{
int i;
for (i = 0; i < (int)(sizeof(resamplers)/sizeof(resamplers[0])); i++)
if (resamplers[i] == cur_resample)
return i;
return 0;
}
/* set the current resampling algorithm */
int set_current_resampler(int type)
{
#ifdef FIXED_RESAMPLATION
return -1;
#else
if (type < 0 || type > RESAMPLE_NONE)
return -1;
cur_resample = resamplers[type];
return 0;
#endif
}
/* #define FINALINTERP if (ofs < le) *dest++=src[(ofs>>FRACTION_BITS)-1]/2; */
#define FINALINTERP /* Nothing to do after TiMidity++ 2.9.0 */
/* So it isn't interpolation. At least it's final. */
static resample_t resample_buffer[AUDIO_BUFFER_SIZE];
static int resample_buffer_offset;
static resample_t *vib_resample_voice(int, int32 *, int);
static resample_t *normal_resample_voice(int, int32 *, int);
#ifdef PRECALC_LOOPS
#if SAMPLE_LENGTH_BITS == 32 && TIMIDITY_HAVE_INT64
#define PRECALC_LOOP_COUNT(start, end, incr) (int32)(((int64)((end) - (start) + (incr) - 1)) / (incr))
#else
#define PRECALC_LOOP_COUNT(start, end, incr) (int32)(((splen_t)((end) - (start) + (incr) - 1)) / (incr))
#endif
#endif /* PRECALC_LOOPS */
void initialize_gauss_table(int n)
{
int m, i, k, n_half = (n>>1);
double ck;
double x, x_inc, xz;
double z[35], zsin_[34 + 35], *zsin, xzsin[35];
float *gptr;
for (i = 0; i <= n; i++)
z[i] = i / (4*M_PI);
zsin = &zsin_[34];
for (i = -n; i <= n; i++)
zsin[i] = sin(i / (4*M_PI));
x_inc = 1.0 / (1<<FRACTION_BITS);
gptr = safe_realloc(gauss_table[0], (n+1)*sizeof(float)*(1<<FRACTION_BITS));
for (m = 0, x = 0.0; m < (1<<FRACTION_BITS); m++, x += x_inc)
{
xz = (x + n_half) / (4*M_PI);
for (i = 0; i <= n; i++)
xzsin[i] = sin(xz - z[i]);
gauss_table[m] = gptr;
for (k = 0; k <= n; k++)
{
ck = 1.0;
for (i = 0; i <= n; i++)
{
if (i == k)
continue;
ck *= xzsin[i] / zsin[k - i];
}
*gptr++ = ck;
}
}
}
#if 0 /* NOT USED */
/* the was calculated statically in newton_table.c */
static void initialize_newton_coeffs(void)
{
int i, j, n = 57;
int sign;
newt_coeffs[0][0] = 1;
for (i = 0; i <= n; i++)
{
newt_coeffs[i][0] = 1;
newt_coeffs[i][i] = 1;
if (i > 1)
{
newt_coeffs[i][0] = newt_coeffs[i-1][0] / i;
newt_coeffs[i][i] = newt_coeffs[i-1][0] / i;
}
for (j = 1; j < i; j++)
{
newt_coeffs[i][j] = newt_coeffs[i-1][j-1] + newt_coeffs[i-1][j];
if (i > 1)
newt_coeffs[i][j] /= i;
}
}
for (i = 0; i <= n; i++)
for (j = 0, sign = pow(-1, i); j <= i; j++, sign *= -1)
newt_coeffs[i][j] *= sign;
}
#endif /* NOT USED */
/* initialize the coefficients of the current resampling algorithm */
void initialize_resampler_coeffs(void)
{
/* initialize_newton_coeffs(); */
initialize_gauss_table(gauss_n);
/* we don't have to initialize newton table any more */
/* bounds checking values for the appropriate sample types */
/* this is as good a place as any to initialize them */
if (play_mode->encoding & PE_24BIT)
{
sample_bounds_min = -8388608;
sample_bounds_max = 8388607;
}
else /* 16-bit */
{
sample_bounds_min = -32768;
sample_bounds_max = 32767;
}
}
/* change the parameter for the current resampling algorithm */
int set_resampler_parm(int val)
{
if (cur_resample == resample_gauss) {
if (val < 1 || val > 34)
return -1;
else
gauss_n = val;
} else if (cur_resample == resample_newton) {
if (val < 1 || val > 57)
return -1;
else if (val % 2 == 0)
return -1;
else {
newt_n = val;
/* set optimal value for newt_max */
newt_max = newt_n * 1.57730263158 - 1.875328947;
if (newt_max < newt_n)
newt_max = newt_n;
if (newt_max > 57)
newt_max = 57;
}
}
return 0;
}
/*************** resampling with fixed increment *****************/
static resample_t *rs_plain_c(int v, int32 *countptr)
{
Voice *vp = &voice[v];
resample_t *dest = resample_buffer + resample_buffer_offset;
sample_t *src = vp->sample->data;
int32 ofs, count = *countptr, i, le;
le = (int32)(vp->sample->loop_end >> FRACTION_BITS);
ofs = (int32)(vp->sample_offset >> FRACTION_BITS);
i = ofs + count;
if(i > le)
i = le;
count = i - ofs;
for (i = 0; i < count; i++) {
dest[i] = src[i + ofs];
}
ofs += count;
if(ofs == le)
{
vp->timeout = 1;
*countptr = count;
}
vp->sample_offset = ((splen_t)ofs << FRACTION_BITS);
return resample_buffer + resample_buffer_offset;
}
static resample_t *rs_plain(int v, int32 *countptr)
{
/* Play sample until end, then free the voice. */
Voice *vp = &voice[v];
resample_t *dest = resample_buffer + resample_buffer_offset;
sample_t *src = vp->sample->data;
splen_t
ofs = vp->sample_offset,
ls = 0,
le = vp->sample->data_length;
resample_rec_t resrc;
int32 count = *countptr, incr = vp->sample_increment;
#ifdef PRECALC_LOOPS
int32 i, j;
#endif
if(vp->cache && incr == (1 << FRACTION_BITS))
return rs_plain_c(v, countptr);
resrc.loop_start = ls;
resrc.loop_end = le;
resrc.data_length = vp->sample->data_length;
#ifdef PRECALC_LOOPS
if (incr < 0) incr = -incr; /* In case we're coming out of a bidir loop */
/* Precalc how many times we should go through the loop.
NOTE: Assumes that incr > 0 and that ofs <= le */
i = PRECALC_LOOP_COUNT(ofs, le, incr);
if (i > count)
{
i = count;
count = 0;
}
else count -= i;
for(j = 0; j < i; j++)
{
RESAMPLATION;
ofs += incr;
}
if (ofs >= le)
{
FINALINTERP;
vp->timeout = 1;
*countptr -= count;
}
#else /* PRECALC_LOOPS */
while (count--)
{
RESAMPLATION;
ofs += incr;
if (ofs >= le)
{
FINALINTERP;
vp->timeout = 1;
*countptr -= count;
break;
}
}
#endif /* PRECALC_LOOPS */
vp->sample_offset = ofs; /* Update offset */
return resample_buffer + resample_buffer_offset;
}
static resample_t *rs_loop_c(Voice *vp, int32 count)
{
int32
ofs = (int32)(vp->sample_offset >> FRACTION_BITS),
le = (int32)(vp->sample->loop_end >> FRACTION_BITS),
ll = le - (int32)(vp->sample->loop_start >> FRACTION_BITS);
resample_t *dest = resample_buffer + resample_buffer_offset;
sample_t *src = vp->sample->data;
int32 i, j;
while(count)
{
while(ofs >= le)
ofs -= ll;
/* Precalc how many times we should go through the loop */
i = le - ofs;
if(i > count)
i = count;
count -= i;
for (j = 0; j < i; j++) {
dest[j] = src[j + ofs];
}
dest += i;
ofs += i;
}
vp->sample_offset = ((splen_t)ofs << FRACTION_BITS);
return resample_buffer + resample_buffer_offset;
}
static resample_t *rs_loop(Voice *vp, int32 count)
{
/* Play sample until end-of-loop, skip back and continue. */
splen_t
ofs = vp->sample_offset,
ls, le, ll;
resample_rec_t resrc;
resample_t *dest = resample_buffer + resample_buffer_offset;
sample_t *src = vp->sample->data;
#ifdef PRECALC_LOOPS
int32 i, j;
#endif
int32 incr = vp->sample_increment;
if(vp->cache && incr == (1 << FRACTION_BITS))
return rs_loop_c(vp, count);
resrc.loop_start = ls = vp->sample->loop_start;
resrc.loop_end = le = vp->sample->loop_end;
ll = le - ls;
resrc.data_length = vp->sample->data_length;
#ifdef PRECALC_LOOPS
while (count)
{
while (ofs >= le) {ofs -= ll;}
/* Precalc how many times we should go through the loop */
i = PRECALC_LOOP_COUNT(ofs, le, incr);
if (i > count) {
i = count;
count = 0;
} else {count -= i;}
for(j = 0; j < i; j++) {
RESAMPLATION;
ofs += incr;
}
}
#else
while (count--)
{
RESAMPLATION;
ofs += incr;
if (ofs >= le)
ofs -= ll; /* Hopefully the loop is longer than an increment. */
}
#endif
vp->sample_offset = ofs; /* Update offset */
return resample_buffer + resample_buffer_offset;
}
static resample_t *rs_bidir(Voice *vp, int32 count)
{
#if SAMPLE_LENGTH_BITS == 32
int32
#else
splen_t
#endif
ofs = vp->sample_offset,
le = vp->sample->loop_end,
ls = vp->sample->loop_start;
resample_t *dest = resample_buffer + resample_buffer_offset;
sample_t *src = vp->sample->data;
int32 incr = vp->sample_increment;
resample_rec_t resrc;
#ifdef PRECALC_LOOPS
#if SAMPLE_LENGTH_BITS == 32
int32
#else
splen_t
#endif
le2 = le << 1,
ls2 = ls << 1;
int32 i, j;
/* Play normally until inside the loop region */
resrc.loop_start = ls;
resrc.loop_end = le;
resrc.data_length = vp->sample->data_length;
if (incr > 0 && ofs < ls)
{
/* NOTE: Assumes that incr > 0, which is NOT always the case
when doing bidirectional looping. I have yet to see a case
where both ofs <= ls AND incr < 0, however. */
i = PRECALC_LOOP_COUNT(ofs, ls, incr);
if (i > count)
{
i = count;
count = 0;
}
else count -= i;
for(j = 0; j < i; j++)
{
RESAMPLATION;
ofs += incr;
}
}
/* Then do the bidirectional looping */
while(count)
{
/* Precalc how many times we should go through the loop */
i = PRECALC_LOOP_COUNT(ofs, incr > 0 ? le : ls, incr);
if (i > count)
{
i = count;
count = 0;
}
else count -= i;
for(j = 0; j < i; j++)
{
RESAMPLATION;
ofs += incr;
}
if(ofs >= 0 && ofs >= le)
{
/* fold the overshoot back in */
ofs = le2 - ofs;
incr *= -1;
}
else if (ofs <= 0 || ofs <= ls)
{
ofs = ls2 - ofs;
incr *= -1;
}
}
#else /* PRECALC_LOOPS */
/* Play normally until inside the loop region */
if (ofs < ls)
{
while (count--)
{
RESAMPLATION;
ofs += incr;
if (ofs >= ls)
break;
}
}
/* Then do the bidirectional looping */
if (count > 0)
while (count--)
{
RESAMPLATION;
ofs += incr;
if (ofs >= le)
{
/* fold the overshoot back in */
ofs = le - (ofs - le);
incr = -incr;
}
else if (ofs <= ls)
{
ofs = ls + (ls - ofs);
incr = -incr;
}
}
#endif /* PRECALC_LOOPS */
vp->sample_increment = incr;
vp->sample_offset = ofs; /* Update offset */
return resample_buffer + resample_buffer_offset;
}
/*********************** vibrato versions ***************************/
/* We only need to compute one half of the vibrato sine cycle */
static int vib_phase_to_inc_ptr(int phase)
{
if (phase < VIBRATO_SAMPLE_INCREMENTS / 2)
return VIBRATO_SAMPLE_INCREMENTS / 2 - 1 - phase;
else if (phase >= 3 * VIBRATO_SAMPLE_INCREMENTS / 2)
return 5 * VIBRATO_SAMPLE_INCREMENTS / 2 - 1 - phase;
else
return phase - VIBRATO_SAMPLE_INCREMENTS / 2;
}
static int32 update_vibrato(Voice *vp, int sign)
{
int32 depth;
int phase, pb;
double a;
int ch = vp->channel;
if(vp->vibrato_delay > 0)
{
vp->vibrato_delay -= vp->vibrato_control_ratio;
if(vp->vibrato_delay > 0)
return vp->sample_increment;
}
if (vp->vibrato_phase++ >= 2 * VIBRATO_SAMPLE_INCREMENTS - 1)
vp->vibrato_phase = 0;
phase = vib_phase_to_inc_ptr(vp->vibrato_phase);
if (vp->vibrato_sample_increment[phase])
{
if (sign)
return -vp->vibrato_sample_increment[phase];
else
return vp->vibrato_sample_increment[phase];
}
/* Need to compute this sample increment. */
depth = vp->vibrato_depth;
depth <<= 7;
if (vp->vibrato_sweep && !channel[ch].mod.val)
{
/* Need to update sweep */
vp->vibrato_sweep_position += vp->vibrato_sweep;
if (vp->vibrato_sweep_position >= (1 << SWEEP_SHIFT))
vp->vibrato_sweep=0;
else
{
/* Adjust depth */
depth *= vp->vibrato_sweep_position;
depth >>= SWEEP_SHIFT;
}
}
if(vp->sample->inst_type == INST_SF2) {
pb = (int)((lookup_triangular(vp->vibrato_phase *
(SINE_CYCLE_LENGTH / (2 * VIBRATO_SAMPLE_INCREMENTS)))
* (double)(depth) * VIBRATO_AMPLITUDE_TUNING));
} else {
pb = (int)((lookup_sine(vp->vibrato_phase *
(SINE_CYCLE_LENGTH / (2 * VIBRATO_SAMPLE_INCREMENTS)))
* (double)(depth) * VIBRATO_AMPLITUDE_TUNING));
}
a = TIM_FSCALE(((double)(vp->sample->sample_rate) *
(double)(vp->frequency)) /
((double)(vp->sample->root_freq) *
(double)(play_mode->rate)),
FRACTION_BITS);
if(pb < 0) {
pb = -pb;
a /= bend_fine[(pb >> 5) & 0xFF] * bend_coarse[pb >> 13];
pb = -pb;
} else {
a *= bend_fine[(pb >> 5) & 0xFF] * bend_coarse[pb >> 13];
}
a += 0.5;
/* If the sweep's over, we can store the newly computed sample_increment */
if (!vp->vibrato_sweep || channel[ch].mod.val)
vp->vibrato_sample_increment[phase] = (int32) a;
if (sign)
a = -a; /* need to preserve the loop direction */
return (int32) a;
}
static resample_t *rs_vib_plain(int v, int32 *countptr)
{
/* Play sample until end, then free the voice. */
Voice *vp = &voice[v];
resample_t *dest = resample_buffer + resample_buffer_offset;
sample_t *src = vp->sample->data;
splen_t
ls = 0,
le = vp->sample->data_length,
ofs = vp->sample_offset;
resample_rec_t resrc;
int32 count = *countptr, incr = vp->sample_increment;
int cc = vp->vibrato_control_counter;
resrc.loop_start = ls;
resrc.loop_end = le;
resrc.data_length = vp->sample->data_length;
/* This has never been tested */
if (incr < 0) incr = -incr; /* In case we're coming out of a bidir loop */
while (count--)
{
if (!cc--)
{
cc = vp->vibrato_control_ratio;
incr = update_vibrato(vp, 0);
}
RESAMPLATION;
ofs += incr;
if (ofs >= le)
{
FINALINTERP;
vp->timeout = 1;
*countptr -= count;
break;
}
}
vp->vibrato_control_counter = cc;
vp->sample_increment = incr;
vp->sample_offset = ofs; /* Update offset */
return resample_buffer + resample_buffer_offset;
}
static resample_t *rs_vib_loop(Voice *vp, int32 count)
{
/* Play sample until end-of-loop, skip back and continue. */
splen_t
ofs = vp->sample_offset,
ls = vp->sample->loop_start,
le = vp->sample->loop_end,
ll = le - vp->sample->loop_start;
resample_t *dest = resample_buffer + resample_buffer_offset;
sample_t *src = vp->sample->data;
int cc = vp->vibrato_control_counter;
int32 incr = vp->sample_increment;
resample_rec_t resrc;
#ifdef PRECALC_LOOPS
int32 i, j;
int vibflag=0;
#endif
resrc.loop_start = ls;
resrc.loop_end = le;
resrc.data_length =vp->sample->data_length;
#ifdef PRECALC_LOOPS
while (count)
{
/* Hopefully the loop is longer than an increment */
while(ofs >= le) {ofs -= ll;}
/* Precalc how many times to go through the loop, taking
the vibrato control ratio into account this time. */
i = PRECALC_LOOP_COUNT(ofs, le, incr);
if(i > count) {
i = count;
}
if(i > cc) {
i = cc;
vibflag = 1;
} else {cc -= i;}
count -= i;
if(vibflag) {
cc = vp->vibrato_control_ratio;
incr = update_vibrato(vp, 0);
vibflag = 0;
}
for(j = 0; j < i; j++) {
RESAMPLATION;
ofs += incr;
}
}
#else /* PRECALC_LOOPS */
while (count--)
{
if (!cc--)
{
cc=vp->vibrato_control_ratio;
incr=update_vibrato(vp, 0);
}
RESAMPLATION;
ofs += incr;
if (ofs >= le)
ofs -= ll; /* Hopefully the loop is longer than an increment. */
}
#endif /* PRECALC_LOOPS */
vp->vibrato_control_counter = cc;
vp->sample_increment = incr;
vp->sample_offset = ofs; /* Update offset */
return resample_buffer + resample_buffer_offset;
}
static resample_t *rs_vib_bidir(Voice *vp, int32 count)
{
#if SAMPLE_LENGTH_BITS == 32
int32
#else
splen_t
#endif
ofs = vp->sample_offset,
le = vp->sample->loop_end,
ls = vp->sample->loop_start;
resample_t *dest = resample_buffer + resample_buffer_offset;
sample_t *src = vp->sample->data;
int cc=vp->vibrato_control_counter;
int32 incr = vp->sample_increment;
resample_rec_t resrc;
#ifdef PRECALC_LOOPS
#if SAMPLE_LENGTH_BITS == 32
int32
#else
splen_t
#endif
le2 = le << 1,
ls2 = ls << 1;
int32 i, j;
int vibflag = 0;
resrc.loop_start = ls;
resrc.loop_end = le;
resrc.data_length = vp->sample->data_length;
/* Play normally until inside the loop region */
while (count && incr > 0 && ofs < ls)
{
i = PRECALC_LOOP_COUNT(ofs, ls, incr);
if (i > count) i = count;
if (i > cc)
{
i = cc;
vibflag = 1;
}
else cc -= i;
count -= i;
if (vibflag)
{
cc = vp->vibrato_control_ratio;
incr = update_vibrato(vp, 0);
vibflag = 0;
}
for(j = 0; j < i; j++)
{
RESAMPLATION;
ofs += incr;
}
}
/* Then do the bidirectional looping */
while (count)
{
/* Precalc how many times we should go through the loop */
i = PRECALC_LOOP_COUNT(ofs, incr > 0 ? le : ls, incr);
if(i > count) i = count;
if(i > cc)
{
i = cc;
vibflag = 1;
}
else cc -= i;
count -= i;
if (vibflag)
{
cc = vp->vibrato_control_ratio;
incr = update_vibrato(vp, (incr < 0));
vibflag = 0;
}
while (i--)
{
RESAMPLATION;
ofs += incr;
}
if (ofs >= 0 && ofs >= le)
{
/* fold the overshoot back in */
ofs = le2 - ofs;
incr *= -1;
}
else if (ofs <= 0 || ofs <= ls)
{
ofs = ls2 - ofs;
incr *= -1;
}
}
#else /* PRECALC_LOOPS */
resrc.loop_start = ls;
resrc.loop_end = le;
resrc.data_length = vp->sample->data_length;
/* Play normally until inside the loop region */
if (ofs < ls)
{
while (count--)
{
if (!cc--)
{
cc = vp->vibrato_control_ratio;
incr = update_vibrato(vp, 0);
}
RESAMPLATION;
ofs += incr;
if (ofs >= ls)
break;
}
}
/* Then do the bidirectional looping */
if (count > 0)
while (count--)
{
if (!cc--)
{
cc=vp->vibrato_control_ratio;
incr=update_vibrato(vp, (incr < 0));
}
RESAMPLATION;
ofs += incr;
if (ofs >= le)
{
/* fold the overshoot back in */
ofs = le - (ofs - le);
incr = -incr;
}
else if (ofs <= ls)
{
ofs = ls + (ls - ofs);
incr = -incr;
}
}
#endif /* PRECALC_LOOPS */
/* Update changed values */
vp->vibrato_control_counter = cc;
vp->sample_increment = incr;
vp->sample_offset = ofs;
return resample_buffer + resample_buffer_offset;
}
/*********************** portamento versions ***************************/
static int rs_update_porta(int v)
{
Voice *vp = &voice[v];
int32 d;
d = vp->porta_dpb;
if(vp->porta_pb < 0)
{
if(d > -vp->porta_pb)
d = -vp->porta_pb;
}
else
{
if(d > vp->porta_pb)
d = -vp->porta_pb;
else
d = -d;
}
vp->porta_pb += d;
if(vp->porta_pb == 0)
{
vp->porta_control_ratio = 0;
vp->porta_pb = 0;
}
recompute_freq(v);
return vp->porta_control_ratio;
}
static resample_t *porta_resample_voice(int v, int32 *countptr, int mode)
{
Voice *vp = &voice[v];
int32 n = *countptr, i;
resample_t *(* resampler)(int, int32 *, int);
int cc = vp->porta_control_counter;
int loop;
if(vp->vibrato_control_ratio)
resampler = vib_resample_voice;
else
resampler = normal_resample_voice;
if(mode != 1)
loop = 1;
else
loop = 0;
vp->cache = NULL;
resample_buffer_offset = 0;
while(resample_buffer_offset < n)
{
if(cc == 0)
{
if((cc = rs_update_porta(v)) == 0)
{
i = n - resample_buffer_offset;
resampler(v, &i, mode);
resample_buffer_offset += i;
break;
}
}
i = n - resample_buffer_offset;
if(i > cc)
i = cc;
resampler(v, &i, mode);
resample_buffer_offset += i;
if(!loop && (i == 0 || vp->status == VOICE_FREE))
break;
cc -= i;
}
*countptr = resample_buffer_offset;
resample_buffer_offset = 0;
vp->porta_control_counter = cc;
return resample_buffer;
}
/* interface function */
static resample_t *vib_resample_voice(int v, int32 *countptr, int mode)
{
Voice *vp = &voice[v];
vp->cache = NULL;
if(mode == 0)
return rs_vib_loop(vp, *countptr);
if(mode == 1)
return rs_vib_plain(v, countptr);
return rs_vib_bidir(vp, *countptr);
}
/* interface function */
static resample_t *normal_resample_voice(int v, int32 *countptr, int mode)
{
Voice *vp = &voice[v];
if(mode == 0)
return rs_loop(vp, *countptr);
if(mode == 1)
return rs_plain(v, countptr);
return rs_bidir(vp, *countptr);
}
/* interface function */
resample_t *resample_voice(int v, int32 *countptr)
{
Voice *vp = &voice[v];
int mode;
resample_t *result;
resampler_t saved_resample;
int32 i;
if(vp->sample->sample_rate == play_mode->rate &&
vp->sample->root_freq == get_note_freq(vp->sample, vp->sample->note_to_use) &&
vp->frequency == vp->orig_frequency)
{
int32 ofs;
/* Pre-resampled data -- just update the offset and check if
we're out of data. */
ofs = (int32)(vp->sample_offset >> FRACTION_BITS); /* Kind of silly to use
FRACTION_BITS here... */
if(*countptr >= (vp->sample->data_length >> FRACTION_BITS) - ofs)
{
/* Note finished. Free the voice. */
vp->timeout = 1;
/* Let the caller know how much data we had left */
*countptr = (int32)(vp->sample->data_length >> FRACTION_BITS) - ofs;
}
else
vp->sample_offset += *countptr << FRACTION_BITS;
for (i = 0; i < *countptr; i++) {
resample_buffer[i] = vp->sample->data[i + ofs];
}
return resample_buffer;
}
mode = vp->sample->modes;
if((mode & MODES_LOOPING) &&
((mode & MODES_ENVELOPE) ||
(vp->status & (VOICE_ON | VOICE_SUSTAINED))))
{
if(mode & MODES_PINGPONG)
{
vp->cache = NULL;
mode = 2; /* Bidir loop */
}
else
mode = 0; /* loop */
}
else
mode = 1; /* no loop */
saved_resample = cur_resample;
#ifndef FIXED_RESAMPLATION
if (reduce_quality_flag && cur_resample != resample_none)
cur_resample = resample_linear;
#endif
if(vp->porta_control_ratio)
result = porta_resample_voice(v, countptr, mode);
else if(vp->vibrato_control_ratio)
result = vib_resample_voice(v, countptr, mode);
else
result = normal_resample_voice(v, countptr, mode);
#ifndef FIXED_RESAMPLATION
cur_resample = saved_resample; /* get back */
#endif
return result;
}
void pre_resample(Sample * sp)
{
double a, b;
splen_t ofs, newlen;
sample_t *newdata, *dest, *src = (sample_t *)sp->data;
int32 i, count, incr, f, x;
resample_rec_t resrc;
ctl->cmsg(CMSG_INFO, VERB_DEBUG, " * pre-resampling for note %d (%s%d)",
sp->note_to_use,
note_name[sp->note_to_use % 12], (sp->note_to_use & 0x7F) / 12);
f = get_note_freq(sp, sp->note_to_use);
a = b = ((double) (sp->root_freq) * play_mode->rate) /
((double) (sp->sample_rate) * f);
if((int64)sp->data_length * a >= 0x7fffffffL)
{
/* Too large to compute */
ctl->cmsg(CMSG_INFO, VERB_DEBUG, " *** Can't pre-resampling for note %d",
sp->note_to_use);
return;
}
newlen = (splen_t)(sp->data_length * a);
count = (newlen >> FRACTION_BITS);
ofs = incr = (sp->data_length - 1) / (count - 1);
if((double)newlen + incr >= 0x7fffffffL)
{
/* Too large to compute */
ctl->cmsg(CMSG_INFO, VERB_DEBUG, " *** Can't pre-resampling for note %d",
sp->note_to_use);
return;
}
dest = newdata = (sample_t *)safe_malloc((int32)(newlen >> (FRACTION_BITS - 1)) + 2);
dest[newlen >> FRACTION_BITS] = 0;
*dest++ = src[0];
resrc.loop_start = 0;
resrc.loop_end = sp->data_length;
resrc.data_length = sp->data_length;
/* Since we're pre-processing and this doesn't have to be done in
real-time, we go ahead and do the higher order interpolation. */
for(i = 1; i < count; i++)
{
x = cur_resample(src, ofs, &resrc);
*dest++ = (int16)((x > 32767) ? 32767: ((x < -32768) ? -32768 : x));
ofs += incr;
}
sp->data_length = newlen;
sp->loop_start = (splen_t)(sp->loop_start * b);
sp->loop_end = (splen_t)(sp->loop_end * b);
free(sp->data);
sp->data = (sample_t *) newdata;
sp->root_freq = f;
sp->sample_rate = play_mode->rate;
sp->low_freq = freq_table[0];
sp->high_freq = freq_table[127];
}
void free_gauss_table()
{
free( gauss_table[0] );
gauss_table[0] = 0;
}
| gpl-2.0 |
ninjablocks/kernel-VAR-SOM-AMxx | fs/btrfs/inode.c | 67 | 242791 | /*
* Copyright (C) 2007 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/kernel.h>
#include <linux/bio.h>
#include <linux/buffer_head.h>
#include <linux/file.h>
#include <linux/fs.h>
#include <linux/pagemap.h>
#include <linux/highmem.h>
#include <linux/time.h>
#include <linux/init.h>
#include <linux/string.h>
#include <linux/backing-dev.h>
#include <linux/mpage.h>
#include <linux/swap.h>
#include <linux/writeback.h>
#include <linux/statfs.h>
#include <linux/compat.h>
#include <linux/aio.h>
#include <linux/bit_spinlock.h>
#include <linux/xattr.h>
#include <linux/posix_acl.h>
#include <linux/falloc.h>
#include <linux/slab.h>
#include <linux/ratelimit.h>
#include <linux/mount.h>
#include <linux/btrfs.h>
#include <linux/blkdev.h>
#include <linux/posix_acl_xattr.h>
#include "ctree.h"
#include "disk-io.h"
#include "transaction.h"
#include "btrfs_inode.h"
#include "print-tree.h"
#include "ordered-data.h"
#include "xattr.h"
#include "tree-log.h"
#include "volumes.h"
#include "compression.h"
#include "locking.h"
#include "free-space-cache.h"
#include "inode-map.h"
#include "backref.h"
#include "hash.h"
#include "props.h"
struct btrfs_iget_args {
struct btrfs_key *location;
struct btrfs_root *root;
};
static const struct inode_operations btrfs_dir_inode_operations;
static const struct inode_operations btrfs_symlink_inode_operations;
static const struct inode_operations btrfs_dir_ro_inode_operations;
static const struct inode_operations btrfs_special_inode_operations;
static const struct inode_operations btrfs_file_inode_operations;
static const struct address_space_operations btrfs_aops;
static const struct address_space_operations btrfs_symlink_aops;
static const struct file_operations btrfs_dir_file_operations;
static struct extent_io_ops btrfs_extent_io_ops;
static struct kmem_cache *btrfs_inode_cachep;
static struct kmem_cache *btrfs_delalloc_work_cachep;
struct kmem_cache *btrfs_trans_handle_cachep;
struct kmem_cache *btrfs_transaction_cachep;
struct kmem_cache *btrfs_path_cachep;
struct kmem_cache *btrfs_free_space_cachep;
#define S_SHIFT 12
static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
[S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
[S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
[S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
[S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
[S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
[S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
[S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
};
static int btrfs_setsize(struct inode *inode, struct iattr *attr);
static int btrfs_truncate(struct inode *inode);
static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
static noinline int cow_file_range(struct inode *inode,
struct page *locked_page,
u64 start, u64 end, int *page_started,
unsigned long *nr_written, int unlock);
static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
u64 len, u64 orig_start,
u64 block_start, u64 block_len,
u64 orig_block_len, u64 ram_bytes,
int type);
static int btrfs_dirty_inode(struct inode *inode);
static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
struct inode *inode, struct inode *dir,
const struct qstr *qstr)
{
int err;
err = btrfs_init_acl(trans, inode, dir);
if (!err)
err = btrfs_xattr_security_init(trans, inode, dir, qstr);
return err;
}
/*
* this does all the hard work for inserting an inline extent into
* the btree. The caller should have done a btrfs_drop_extents so that
* no overlapping inline items exist in the btree
*/
static noinline int insert_inline_extent(struct btrfs_trans_handle *trans,
struct btrfs_path *path, int extent_inserted,
struct btrfs_root *root, struct inode *inode,
u64 start, size_t size, size_t compressed_size,
int compress_type,
struct page **compressed_pages)
{
struct extent_buffer *leaf;
struct page *page = NULL;
char *kaddr;
unsigned long ptr;
struct btrfs_file_extent_item *ei;
int err = 0;
int ret;
size_t cur_size = size;
unsigned long offset;
if (compressed_size && compressed_pages)
cur_size = compressed_size;
inode_add_bytes(inode, size);
if (!extent_inserted) {
struct btrfs_key key;
size_t datasize;
key.objectid = btrfs_ino(inode);
key.offset = start;
btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
datasize = btrfs_file_extent_calc_inline_size(cur_size);
path->leave_spinning = 1;
ret = btrfs_insert_empty_item(trans, root, path, &key,
datasize);
if (ret) {
err = ret;
goto fail;
}
}
leaf = path->nodes[0];
ei = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_file_extent_item);
btrfs_set_file_extent_generation(leaf, ei, trans->transid);
btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
btrfs_set_file_extent_encryption(leaf, ei, 0);
btrfs_set_file_extent_other_encoding(leaf, ei, 0);
btrfs_set_file_extent_ram_bytes(leaf, ei, size);
ptr = btrfs_file_extent_inline_start(ei);
if (compress_type != BTRFS_COMPRESS_NONE) {
struct page *cpage;
int i = 0;
while (compressed_size > 0) {
cpage = compressed_pages[i];
cur_size = min_t(unsigned long, compressed_size,
PAGE_CACHE_SIZE);
kaddr = kmap_atomic(cpage);
write_extent_buffer(leaf, kaddr, ptr, cur_size);
kunmap_atomic(kaddr);
i++;
ptr += cur_size;
compressed_size -= cur_size;
}
btrfs_set_file_extent_compression(leaf, ei,
compress_type);
} else {
page = find_get_page(inode->i_mapping,
start >> PAGE_CACHE_SHIFT);
btrfs_set_file_extent_compression(leaf, ei, 0);
kaddr = kmap_atomic(page);
offset = start & (PAGE_CACHE_SIZE - 1);
write_extent_buffer(leaf, kaddr + offset, ptr, size);
kunmap_atomic(kaddr);
page_cache_release(page);
}
btrfs_mark_buffer_dirty(leaf);
btrfs_release_path(path);
/*
* we're an inline extent, so nobody can
* extend the file past i_size without locking
* a page we already have locked.
*
* We must do any isize and inode updates
* before we unlock the pages. Otherwise we
* could end up racing with unlink.
*/
BTRFS_I(inode)->disk_i_size = inode->i_size;
ret = btrfs_update_inode(trans, root, inode);
return ret;
fail:
return err;
}
/*
* conditionally insert an inline extent into the file. This
* does the checks required to make sure the data is small enough
* to fit as an inline extent.
*/
static noinline int cow_file_range_inline(struct btrfs_root *root,
struct inode *inode, u64 start,
u64 end, size_t compressed_size,
int compress_type,
struct page **compressed_pages)
{
struct btrfs_trans_handle *trans;
u64 isize = i_size_read(inode);
u64 actual_end = min(end + 1, isize);
u64 inline_len = actual_end - start;
u64 aligned_end = ALIGN(end, root->sectorsize);
u64 data_len = inline_len;
int ret;
struct btrfs_path *path;
int extent_inserted = 0;
u32 extent_item_size;
if (compressed_size)
data_len = compressed_size;
if (start > 0 ||
actual_end >= PAGE_CACHE_SIZE ||
data_len >= BTRFS_MAX_INLINE_DATA_SIZE(root) ||
(!compressed_size &&
(actual_end & (root->sectorsize - 1)) == 0) ||
end + 1 < isize ||
data_len > root->fs_info->max_inline) {
return 1;
}
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
trans = btrfs_join_transaction(root);
if (IS_ERR(trans)) {
btrfs_free_path(path);
return PTR_ERR(trans);
}
trans->block_rsv = &root->fs_info->delalloc_block_rsv;
if (compressed_size && compressed_pages)
extent_item_size = btrfs_file_extent_calc_inline_size(
compressed_size);
else
extent_item_size = btrfs_file_extent_calc_inline_size(
inline_len);
ret = __btrfs_drop_extents(trans, root, inode, path,
start, aligned_end, NULL,
1, 1, extent_item_size, &extent_inserted);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
goto out;
}
if (isize > actual_end)
inline_len = min_t(u64, isize, actual_end);
ret = insert_inline_extent(trans, path, extent_inserted,
root, inode, start,
inline_len, compressed_size,
compress_type, compressed_pages);
if (ret && ret != -ENOSPC) {
btrfs_abort_transaction(trans, root, ret);
goto out;
} else if (ret == -ENOSPC) {
ret = 1;
goto out;
}
set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
btrfs_delalloc_release_metadata(inode, end + 1 - start);
btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
out:
btrfs_free_path(path);
btrfs_end_transaction(trans, root);
return ret;
}
struct async_extent {
u64 start;
u64 ram_size;
u64 compressed_size;
struct page **pages;
unsigned long nr_pages;
int compress_type;
struct list_head list;
};
struct async_cow {
struct inode *inode;
struct btrfs_root *root;
struct page *locked_page;
u64 start;
u64 end;
struct list_head extents;
struct btrfs_work work;
};
static noinline int add_async_extent(struct async_cow *cow,
u64 start, u64 ram_size,
u64 compressed_size,
struct page **pages,
unsigned long nr_pages,
int compress_type)
{
struct async_extent *async_extent;
async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
BUG_ON(!async_extent); /* -ENOMEM */
async_extent->start = start;
async_extent->ram_size = ram_size;
async_extent->compressed_size = compressed_size;
async_extent->pages = pages;
async_extent->nr_pages = nr_pages;
async_extent->compress_type = compress_type;
list_add_tail(&async_extent->list, &cow->extents);
return 0;
}
/*
* we create compressed extents in two phases. The first
* phase compresses a range of pages that have already been
* locked (both pages and state bits are locked).
*
* This is done inside an ordered work queue, and the compression
* is spread across many cpus. The actual IO submission is step
* two, and the ordered work queue takes care of making sure that
* happens in the same order things were put onto the queue by
* writepages and friends.
*
* If this code finds it can't get good compression, it puts an
* entry onto the work queue to write the uncompressed bytes. This
* makes sure that both compressed inodes and uncompressed inodes
* are written in the same order that the flusher thread sent them
* down.
*/
static noinline int compress_file_range(struct inode *inode,
struct page *locked_page,
u64 start, u64 end,
struct async_cow *async_cow,
int *num_added)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
u64 num_bytes;
u64 blocksize = root->sectorsize;
u64 actual_end;
u64 isize = i_size_read(inode);
int ret = 0;
struct page **pages = NULL;
unsigned long nr_pages;
unsigned long nr_pages_ret = 0;
unsigned long total_compressed = 0;
unsigned long total_in = 0;
unsigned long max_compressed = 128 * 1024;
unsigned long max_uncompressed = 128 * 1024;
int i;
int will_compress;
int compress_type = root->fs_info->compress_type;
int redirty = 0;
/* if this is a small write inside eof, kick off a defrag */
if ((end - start + 1) < 16 * 1024 &&
(start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
btrfs_add_inode_defrag(NULL, inode);
actual_end = min_t(u64, isize, end + 1);
again:
will_compress = 0;
nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
/*
* we don't want to send crud past the end of i_size through
* compression, that's just a waste of CPU time. So, if the
* end of the file is before the start of our current
* requested range of bytes, we bail out to the uncompressed
* cleanup code that can deal with all of this.
*
* It isn't really the fastest way to fix things, but this is a
* very uncommon corner.
*/
if (actual_end <= start)
goto cleanup_and_bail_uncompressed;
total_compressed = actual_end - start;
/* we want to make sure that amount of ram required to uncompress
* an extent is reasonable, so we limit the total size in ram
* of a compressed extent to 128k. This is a crucial number
* because it also controls how easily we can spread reads across
* cpus for decompression.
*
* We also want to make sure the amount of IO required to do
* a random read is reasonably small, so we limit the size of
* a compressed extent to 128k.
*/
total_compressed = min(total_compressed, max_uncompressed);
num_bytes = ALIGN(end - start + 1, blocksize);
num_bytes = max(blocksize, num_bytes);
total_in = 0;
ret = 0;
/*
* we do compression for mount -o compress and when the
* inode has not been flagged as nocompress. This flag can
* change at any time if we discover bad compression ratios.
*/
if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) &&
(btrfs_test_opt(root, COMPRESS) ||
(BTRFS_I(inode)->force_compress) ||
(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))) {
WARN_ON(pages);
pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
if (!pages) {
/* just bail out to the uncompressed code */
goto cont;
}
if (BTRFS_I(inode)->force_compress)
compress_type = BTRFS_I(inode)->force_compress;
/*
* we need to call clear_page_dirty_for_io on each
* page in the range. Otherwise applications with the file
* mmap'd can wander in and change the page contents while
* we are compressing them.
*
* If the compression fails for any reason, we set the pages
* dirty again later on.
*/
extent_range_clear_dirty_for_io(inode, start, end);
redirty = 1;
ret = btrfs_compress_pages(compress_type,
inode->i_mapping, start,
total_compressed, pages,
nr_pages, &nr_pages_ret,
&total_in,
&total_compressed,
max_compressed);
if (!ret) {
unsigned long offset = total_compressed &
(PAGE_CACHE_SIZE - 1);
struct page *page = pages[nr_pages_ret - 1];
char *kaddr;
/* zero the tail end of the last page, we might be
* sending it down to disk
*/
if (offset) {
kaddr = kmap_atomic(page);
memset(kaddr + offset, 0,
PAGE_CACHE_SIZE - offset);
kunmap_atomic(kaddr);
}
will_compress = 1;
}
}
cont:
if (start == 0) {
/* lets try to make an inline extent */
if (ret || total_in < (actual_end - start)) {
/* we didn't compress the entire range, try
* to make an uncompressed inline extent.
*/
ret = cow_file_range_inline(root, inode, start, end,
0, 0, NULL);
} else {
/* try making a compressed inline extent */
ret = cow_file_range_inline(root, inode, start, end,
total_compressed,
compress_type, pages);
}
if (ret <= 0) {
unsigned long clear_flags = EXTENT_DELALLOC |
EXTENT_DEFRAG;
clear_flags |= (ret < 0) ? EXTENT_DO_ACCOUNTING : 0;
/*
* inline extent creation worked or returned error,
* we don't need to create any more async work items.
* Unlock and free up our temp pages.
*/
extent_clear_unlock_delalloc(inode, start, end, NULL,
clear_flags, PAGE_UNLOCK |
PAGE_CLEAR_DIRTY |
PAGE_SET_WRITEBACK |
PAGE_END_WRITEBACK);
goto free_pages_out;
}
}
if (will_compress) {
/*
* we aren't doing an inline extent round the compressed size
* up to a block size boundary so the allocator does sane
* things
*/
total_compressed = ALIGN(total_compressed, blocksize);
/*
* one last check to make sure the compression is really a
* win, compare the page count read with the blocks on disk
*/
total_in = ALIGN(total_in, PAGE_CACHE_SIZE);
if (total_compressed >= total_in) {
will_compress = 0;
} else {
num_bytes = total_in;
}
}
if (!will_compress && pages) {
/*
* the compression code ran but failed to make things smaller,
* free any pages it allocated and our page pointer array
*/
for (i = 0; i < nr_pages_ret; i++) {
WARN_ON(pages[i]->mapping);
page_cache_release(pages[i]);
}
kfree(pages);
pages = NULL;
total_compressed = 0;
nr_pages_ret = 0;
/* flag the file so we don't compress in the future */
if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
!(BTRFS_I(inode)->force_compress)) {
BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
}
}
if (will_compress) {
*num_added += 1;
/* the async work queues will take care of doing actual
* allocation on disk for these compressed pages,
* and will submit them to the elevator.
*/
add_async_extent(async_cow, start, num_bytes,
total_compressed, pages, nr_pages_ret,
compress_type);
if (start + num_bytes < end) {
start += num_bytes;
pages = NULL;
cond_resched();
goto again;
}
} else {
cleanup_and_bail_uncompressed:
/*
* No compression, but we still need to write the pages in
* the file we've been given so far. redirty the locked
* page if it corresponds to our extent and set things up
* for the async work queue to run cow_file_range to do
* the normal delalloc dance
*/
if (page_offset(locked_page) >= start &&
page_offset(locked_page) <= end) {
__set_page_dirty_nobuffers(locked_page);
/* unlocked later on in the async handlers */
}
if (redirty)
extent_range_redirty_for_io(inode, start, end);
add_async_extent(async_cow, start, end - start + 1,
0, NULL, 0, BTRFS_COMPRESS_NONE);
*num_added += 1;
}
out:
return ret;
free_pages_out:
for (i = 0; i < nr_pages_ret; i++) {
WARN_ON(pages[i]->mapping);
page_cache_release(pages[i]);
}
kfree(pages);
goto out;
}
/*
* phase two of compressed writeback. This is the ordered portion
* of the code, which only gets called in the order the work was
* queued. We walk all the async extents created by compress_file_range
* and send them down to the disk.
*/
static noinline int submit_compressed_extents(struct inode *inode,
struct async_cow *async_cow)
{
struct async_extent *async_extent;
u64 alloc_hint = 0;
struct btrfs_key ins;
struct extent_map *em;
struct btrfs_root *root = BTRFS_I(inode)->root;
struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
struct extent_io_tree *io_tree;
int ret = 0;
if (list_empty(&async_cow->extents))
return 0;
again:
while (!list_empty(&async_cow->extents)) {
async_extent = list_entry(async_cow->extents.next,
struct async_extent, list);
list_del(&async_extent->list);
io_tree = &BTRFS_I(inode)->io_tree;
retry:
/* did the compression code fall back to uncompressed IO? */
if (!async_extent->pages) {
int page_started = 0;
unsigned long nr_written = 0;
lock_extent(io_tree, async_extent->start,
async_extent->start +
async_extent->ram_size - 1);
/* allocate blocks */
ret = cow_file_range(inode, async_cow->locked_page,
async_extent->start,
async_extent->start +
async_extent->ram_size - 1,
&page_started, &nr_written, 0);
/* JDM XXX */
/*
* if page_started, cow_file_range inserted an
* inline extent and took care of all the unlocking
* and IO for us. Otherwise, we need to submit
* all those pages down to the drive.
*/
if (!page_started && !ret)
extent_write_locked_range(io_tree,
inode, async_extent->start,
async_extent->start +
async_extent->ram_size - 1,
btrfs_get_extent,
WB_SYNC_ALL);
else if (ret)
unlock_page(async_cow->locked_page);
kfree(async_extent);
cond_resched();
continue;
}
lock_extent(io_tree, async_extent->start,
async_extent->start + async_extent->ram_size - 1);
ret = btrfs_reserve_extent(root,
async_extent->compressed_size,
async_extent->compressed_size,
0, alloc_hint, &ins, 1);
if (ret) {
int i;
for (i = 0; i < async_extent->nr_pages; i++) {
WARN_ON(async_extent->pages[i]->mapping);
page_cache_release(async_extent->pages[i]);
}
kfree(async_extent->pages);
async_extent->nr_pages = 0;
async_extent->pages = NULL;
if (ret == -ENOSPC) {
unlock_extent(io_tree, async_extent->start,
async_extent->start +
async_extent->ram_size - 1);
/*
* we need to redirty the pages if we decide to
* fallback to uncompressed IO, otherwise we
* will not submit these pages down to lower
* layers.
*/
extent_range_redirty_for_io(inode,
async_extent->start,
async_extent->start +
async_extent->ram_size - 1);
goto retry;
}
goto out_free;
}
/*
* here we're doing allocation and writeback of the
* compressed pages
*/
btrfs_drop_extent_cache(inode, async_extent->start,
async_extent->start +
async_extent->ram_size - 1, 0);
em = alloc_extent_map();
if (!em) {
ret = -ENOMEM;
goto out_free_reserve;
}
em->start = async_extent->start;
em->len = async_extent->ram_size;
em->orig_start = em->start;
em->mod_start = em->start;
em->mod_len = em->len;
em->block_start = ins.objectid;
em->block_len = ins.offset;
em->orig_block_len = ins.offset;
em->ram_bytes = async_extent->ram_size;
em->bdev = root->fs_info->fs_devices->latest_bdev;
em->compress_type = async_extent->compress_type;
set_bit(EXTENT_FLAG_PINNED, &em->flags);
set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
em->generation = -1;
while (1) {
write_lock(&em_tree->lock);
ret = add_extent_mapping(em_tree, em, 1);
write_unlock(&em_tree->lock);
if (ret != -EEXIST) {
free_extent_map(em);
break;
}
btrfs_drop_extent_cache(inode, async_extent->start,
async_extent->start +
async_extent->ram_size - 1, 0);
}
if (ret)
goto out_free_reserve;
ret = btrfs_add_ordered_extent_compress(inode,
async_extent->start,
ins.objectid,
async_extent->ram_size,
ins.offset,
BTRFS_ORDERED_COMPRESSED,
async_extent->compress_type);
if (ret)
goto out_free_reserve;
/*
* clear dirty, set writeback and unlock the pages.
*/
extent_clear_unlock_delalloc(inode, async_extent->start,
async_extent->start +
async_extent->ram_size - 1,
NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
PAGE_SET_WRITEBACK);
ret = btrfs_submit_compressed_write(inode,
async_extent->start,
async_extent->ram_size,
ins.objectid,
ins.offset, async_extent->pages,
async_extent->nr_pages);
alloc_hint = ins.objectid + ins.offset;
kfree(async_extent);
if (ret)
goto out;
cond_resched();
}
ret = 0;
out:
return ret;
out_free_reserve:
btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
out_free:
extent_clear_unlock_delalloc(inode, async_extent->start,
async_extent->start +
async_extent->ram_size - 1,
NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
kfree(async_extent);
goto again;
}
static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
u64 num_bytes)
{
struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
struct extent_map *em;
u64 alloc_hint = 0;
read_lock(&em_tree->lock);
em = search_extent_mapping(em_tree, start, num_bytes);
if (em) {
/*
* if block start isn't an actual block number then find the
* first block in this inode and use that as a hint. If that
* block is also bogus then just don't worry about it.
*/
if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
free_extent_map(em);
em = search_extent_mapping(em_tree, 0, 0);
if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
alloc_hint = em->block_start;
if (em)
free_extent_map(em);
} else {
alloc_hint = em->block_start;
free_extent_map(em);
}
}
read_unlock(&em_tree->lock);
return alloc_hint;
}
/*
* when extent_io.c finds a delayed allocation range in the file,
* the call backs end up in this code. The basic idea is to
* allocate extents on disk for the range, and create ordered data structs
* in ram to track those extents.
*
* locked_page is the page that writepage had locked already. We use
* it to make sure we don't do extra locks or unlocks.
*
* *page_started is set to one if we unlock locked_page and do everything
* required to start IO on it. It may be clean and already done with
* IO when we return.
*/
static noinline int cow_file_range(struct inode *inode,
struct page *locked_page,
u64 start, u64 end, int *page_started,
unsigned long *nr_written,
int unlock)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
u64 alloc_hint = 0;
u64 num_bytes;
unsigned long ram_size;
u64 disk_num_bytes;
u64 cur_alloc_size;
u64 blocksize = root->sectorsize;
struct btrfs_key ins;
struct extent_map *em;
struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
int ret = 0;
if (btrfs_is_free_space_inode(inode)) {
WARN_ON_ONCE(1);
return -EINVAL;
}
num_bytes = ALIGN(end - start + 1, blocksize);
num_bytes = max(blocksize, num_bytes);
disk_num_bytes = num_bytes;
/* if this is a small write inside eof, kick off defrag */
if (num_bytes < 64 * 1024 &&
(start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
btrfs_add_inode_defrag(NULL, inode);
if (start == 0) {
/* lets try to make an inline extent */
ret = cow_file_range_inline(root, inode, start, end, 0, 0,
NULL);
if (ret == 0) {
extent_clear_unlock_delalloc(inode, start, end, NULL,
EXTENT_LOCKED | EXTENT_DELALLOC |
EXTENT_DEFRAG, PAGE_UNLOCK |
PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
PAGE_END_WRITEBACK);
*nr_written = *nr_written +
(end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
*page_started = 1;
goto out;
} else if (ret < 0) {
goto out_unlock;
}
}
BUG_ON(disk_num_bytes >
btrfs_super_total_bytes(root->fs_info->super_copy));
alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
while (disk_num_bytes > 0) {
unsigned long op;
cur_alloc_size = disk_num_bytes;
ret = btrfs_reserve_extent(root, cur_alloc_size,
root->sectorsize, 0, alloc_hint,
&ins, 1);
if (ret < 0)
goto out_unlock;
em = alloc_extent_map();
if (!em) {
ret = -ENOMEM;
goto out_reserve;
}
em->start = start;
em->orig_start = em->start;
ram_size = ins.offset;
em->len = ins.offset;
em->mod_start = em->start;
em->mod_len = em->len;
em->block_start = ins.objectid;
em->block_len = ins.offset;
em->orig_block_len = ins.offset;
em->ram_bytes = ram_size;
em->bdev = root->fs_info->fs_devices->latest_bdev;
set_bit(EXTENT_FLAG_PINNED, &em->flags);
em->generation = -1;
while (1) {
write_lock(&em_tree->lock);
ret = add_extent_mapping(em_tree, em, 1);
write_unlock(&em_tree->lock);
if (ret != -EEXIST) {
free_extent_map(em);
break;
}
btrfs_drop_extent_cache(inode, start,
start + ram_size - 1, 0);
}
if (ret)
goto out_reserve;
cur_alloc_size = ins.offset;
ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
ram_size, cur_alloc_size, 0);
if (ret)
goto out_reserve;
if (root->root_key.objectid ==
BTRFS_DATA_RELOC_TREE_OBJECTID) {
ret = btrfs_reloc_clone_csums(inode, start,
cur_alloc_size);
if (ret)
goto out_reserve;
}
if (disk_num_bytes < cur_alloc_size)
break;
/* we're not doing compressed IO, don't unlock the first
* page (which the caller expects to stay locked), don't
* clear any dirty bits and don't set any writeback bits
*
* Do set the Private2 bit so we know this page was properly
* setup for writepage
*/
op = unlock ? PAGE_UNLOCK : 0;
op |= PAGE_SET_PRIVATE2;
extent_clear_unlock_delalloc(inode, start,
start + ram_size - 1, locked_page,
EXTENT_LOCKED | EXTENT_DELALLOC,
op);
disk_num_bytes -= cur_alloc_size;
num_bytes -= cur_alloc_size;
alloc_hint = ins.objectid + ins.offset;
start += cur_alloc_size;
}
out:
return ret;
out_reserve:
btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
out_unlock:
extent_clear_unlock_delalloc(inode, start, end, locked_page,
EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
EXTENT_DELALLOC | EXTENT_DEFRAG,
PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
goto out;
}
/*
* work queue call back to started compression on a file and pages
*/
static noinline void async_cow_start(struct btrfs_work *work)
{
struct async_cow *async_cow;
int num_added = 0;
async_cow = container_of(work, struct async_cow, work);
compress_file_range(async_cow->inode, async_cow->locked_page,
async_cow->start, async_cow->end, async_cow,
&num_added);
if (num_added == 0) {
btrfs_add_delayed_iput(async_cow->inode);
async_cow->inode = NULL;
}
}
/*
* work queue call back to submit previously compressed pages
*/
static noinline void async_cow_submit(struct btrfs_work *work)
{
struct async_cow *async_cow;
struct btrfs_root *root;
unsigned long nr_pages;
async_cow = container_of(work, struct async_cow, work);
root = async_cow->root;
nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
PAGE_CACHE_SHIFT;
if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
5 * 1024 * 1024 &&
waitqueue_active(&root->fs_info->async_submit_wait))
wake_up(&root->fs_info->async_submit_wait);
if (async_cow->inode)
submit_compressed_extents(async_cow->inode, async_cow);
}
static noinline void async_cow_free(struct btrfs_work *work)
{
struct async_cow *async_cow;
async_cow = container_of(work, struct async_cow, work);
if (async_cow->inode)
btrfs_add_delayed_iput(async_cow->inode);
kfree(async_cow);
}
static int cow_file_range_async(struct inode *inode, struct page *locked_page,
u64 start, u64 end, int *page_started,
unsigned long *nr_written)
{
struct async_cow *async_cow;
struct btrfs_root *root = BTRFS_I(inode)->root;
unsigned long nr_pages;
u64 cur_end;
int limit = 10 * 1024 * 1024;
clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1, 0, NULL, GFP_NOFS);
while (start < end) {
async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
BUG_ON(!async_cow); /* -ENOMEM */
async_cow->inode = igrab(inode);
async_cow->root = root;
async_cow->locked_page = locked_page;
async_cow->start = start;
if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
cur_end = end;
else
cur_end = min(end, start + 512 * 1024 - 1);
async_cow->end = cur_end;
INIT_LIST_HEAD(&async_cow->extents);
async_cow->work.func = async_cow_start;
async_cow->work.ordered_func = async_cow_submit;
async_cow->work.ordered_free = async_cow_free;
async_cow->work.flags = 0;
nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
PAGE_CACHE_SHIFT;
atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
btrfs_queue_worker(&root->fs_info->delalloc_workers,
&async_cow->work);
if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
wait_event(root->fs_info->async_submit_wait,
(atomic_read(&root->fs_info->async_delalloc_pages) <
limit));
}
while (atomic_read(&root->fs_info->async_submit_draining) &&
atomic_read(&root->fs_info->async_delalloc_pages)) {
wait_event(root->fs_info->async_submit_wait,
(atomic_read(&root->fs_info->async_delalloc_pages) ==
0));
}
*nr_written += nr_pages;
start = cur_end + 1;
}
*page_started = 1;
return 0;
}
static noinline int csum_exist_in_range(struct btrfs_root *root,
u64 bytenr, u64 num_bytes)
{
int ret;
struct btrfs_ordered_sum *sums;
LIST_HEAD(list);
ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
bytenr + num_bytes - 1, &list, 0);
if (ret == 0 && list_empty(&list))
return 0;
while (!list_empty(&list)) {
sums = list_entry(list.next, struct btrfs_ordered_sum, list);
list_del(&sums->list);
kfree(sums);
}
return 1;
}
/*
* when nowcow writeback call back. This checks for snapshots or COW copies
* of the extents that exist in the file, and COWs the file as required.
*
* If no cow copies or snapshots exist, we write directly to the existing
* blocks on disk
*/
static noinline int run_delalloc_nocow(struct inode *inode,
struct page *locked_page,
u64 start, u64 end, int *page_started, int force,
unsigned long *nr_written)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_trans_handle *trans;
struct extent_buffer *leaf;
struct btrfs_path *path;
struct btrfs_file_extent_item *fi;
struct btrfs_key found_key;
u64 cow_start;
u64 cur_offset;
u64 extent_end;
u64 extent_offset;
u64 disk_bytenr;
u64 num_bytes;
u64 disk_num_bytes;
u64 ram_bytes;
int extent_type;
int ret, err;
int type;
int nocow;
int check_prev = 1;
bool nolock;
u64 ino = btrfs_ino(inode);
path = btrfs_alloc_path();
if (!path) {
extent_clear_unlock_delalloc(inode, start, end, locked_page,
EXTENT_LOCKED | EXTENT_DELALLOC |
EXTENT_DO_ACCOUNTING |
EXTENT_DEFRAG, PAGE_UNLOCK |
PAGE_CLEAR_DIRTY |
PAGE_SET_WRITEBACK |
PAGE_END_WRITEBACK);
return -ENOMEM;
}
nolock = btrfs_is_free_space_inode(inode);
if (nolock)
trans = btrfs_join_transaction_nolock(root);
else
trans = btrfs_join_transaction(root);
if (IS_ERR(trans)) {
extent_clear_unlock_delalloc(inode, start, end, locked_page,
EXTENT_LOCKED | EXTENT_DELALLOC |
EXTENT_DO_ACCOUNTING |
EXTENT_DEFRAG, PAGE_UNLOCK |
PAGE_CLEAR_DIRTY |
PAGE_SET_WRITEBACK |
PAGE_END_WRITEBACK);
btrfs_free_path(path);
return PTR_ERR(trans);
}
trans->block_rsv = &root->fs_info->delalloc_block_rsv;
cow_start = (u64)-1;
cur_offset = start;
while (1) {
ret = btrfs_lookup_file_extent(trans, root, path, ino,
cur_offset, 0);
if (ret < 0)
goto error;
if (ret > 0 && path->slots[0] > 0 && check_prev) {
leaf = path->nodes[0];
btrfs_item_key_to_cpu(leaf, &found_key,
path->slots[0] - 1);
if (found_key.objectid == ino &&
found_key.type == BTRFS_EXTENT_DATA_KEY)
path->slots[0]--;
}
check_prev = 0;
next_slot:
leaf = path->nodes[0];
if (path->slots[0] >= btrfs_header_nritems(leaf)) {
ret = btrfs_next_leaf(root, path);
if (ret < 0)
goto error;
if (ret > 0)
break;
leaf = path->nodes[0];
}
nocow = 0;
disk_bytenr = 0;
num_bytes = 0;
btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
if (found_key.objectid > ino ||
found_key.type > BTRFS_EXTENT_DATA_KEY ||
found_key.offset > end)
break;
if (found_key.offset > cur_offset) {
extent_end = found_key.offset;
extent_type = 0;
goto out_check;
}
fi = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_file_extent_item);
extent_type = btrfs_file_extent_type(leaf, fi);
ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
if (extent_type == BTRFS_FILE_EXTENT_REG ||
extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
extent_offset = btrfs_file_extent_offset(leaf, fi);
extent_end = found_key.offset +
btrfs_file_extent_num_bytes(leaf, fi);
disk_num_bytes =
btrfs_file_extent_disk_num_bytes(leaf, fi);
if (extent_end <= start) {
path->slots[0]++;
goto next_slot;
}
if (disk_bytenr == 0)
goto out_check;
if (btrfs_file_extent_compression(leaf, fi) ||
btrfs_file_extent_encryption(leaf, fi) ||
btrfs_file_extent_other_encoding(leaf, fi))
goto out_check;
if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
goto out_check;
if (btrfs_extent_readonly(root, disk_bytenr))
goto out_check;
if (btrfs_cross_ref_exist(trans, root, ino,
found_key.offset -
extent_offset, disk_bytenr))
goto out_check;
disk_bytenr += extent_offset;
disk_bytenr += cur_offset - found_key.offset;
num_bytes = min(end + 1, extent_end) - cur_offset;
/*
* force cow if csum exists in the range.
* this ensure that csum for a given extent are
* either valid or do not exist.
*/
if (csum_exist_in_range(root, disk_bytenr, num_bytes))
goto out_check;
nocow = 1;
} else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
extent_end = found_key.offset +
btrfs_file_extent_inline_len(leaf,
path->slots[0], fi);
extent_end = ALIGN(extent_end, root->sectorsize);
} else {
BUG_ON(1);
}
out_check:
if (extent_end <= start) {
path->slots[0]++;
goto next_slot;
}
if (!nocow) {
if (cow_start == (u64)-1)
cow_start = cur_offset;
cur_offset = extent_end;
if (cur_offset > end)
break;
path->slots[0]++;
goto next_slot;
}
btrfs_release_path(path);
if (cow_start != (u64)-1) {
ret = cow_file_range(inode, locked_page,
cow_start, found_key.offset - 1,
page_started, nr_written, 1);
if (ret)
goto error;
cow_start = (u64)-1;
}
if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
struct extent_map *em;
struct extent_map_tree *em_tree;
em_tree = &BTRFS_I(inode)->extent_tree;
em = alloc_extent_map();
BUG_ON(!em); /* -ENOMEM */
em->start = cur_offset;
em->orig_start = found_key.offset - extent_offset;
em->len = num_bytes;
em->block_len = num_bytes;
em->block_start = disk_bytenr;
em->orig_block_len = disk_num_bytes;
em->ram_bytes = ram_bytes;
em->bdev = root->fs_info->fs_devices->latest_bdev;
em->mod_start = em->start;
em->mod_len = em->len;
set_bit(EXTENT_FLAG_PINNED, &em->flags);
set_bit(EXTENT_FLAG_FILLING, &em->flags);
em->generation = -1;
while (1) {
write_lock(&em_tree->lock);
ret = add_extent_mapping(em_tree, em, 1);
write_unlock(&em_tree->lock);
if (ret != -EEXIST) {
free_extent_map(em);
break;
}
btrfs_drop_extent_cache(inode, em->start,
em->start + em->len - 1, 0);
}
type = BTRFS_ORDERED_PREALLOC;
} else {
type = BTRFS_ORDERED_NOCOW;
}
ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
num_bytes, num_bytes, type);
BUG_ON(ret); /* -ENOMEM */
if (root->root_key.objectid ==
BTRFS_DATA_RELOC_TREE_OBJECTID) {
ret = btrfs_reloc_clone_csums(inode, cur_offset,
num_bytes);
if (ret)
goto error;
}
extent_clear_unlock_delalloc(inode, cur_offset,
cur_offset + num_bytes - 1,
locked_page, EXTENT_LOCKED |
EXTENT_DELALLOC, PAGE_UNLOCK |
PAGE_SET_PRIVATE2);
cur_offset = extent_end;
if (cur_offset > end)
break;
}
btrfs_release_path(path);
if (cur_offset <= end && cow_start == (u64)-1) {
cow_start = cur_offset;
cur_offset = end;
}
if (cow_start != (u64)-1) {
ret = cow_file_range(inode, locked_page, cow_start, end,
page_started, nr_written, 1);
if (ret)
goto error;
}
error:
err = btrfs_end_transaction(trans, root);
if (!ret)
ret = err;
if (ret && cur_offset < end)
extent_clear_unlock_delalloc(inode, cur_offset, end,
locked_page, EXTENT_LOCKED |
EXTENT_DELALLOC | EXTENT_DEFRAG |
EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
PAGE_CLEAR_DIRTY |
PAGE_SET_WRITEBACK |
PAGE_END_WRITEBACK);
btrfs_free_path(path);
return ret;
}
/*
* extent_io.c call back to do delayed allocation processing
*/
static int run_delalloc_range(struct inode *inode, struct page *locked_page,
u64 start, u64 end, int *page_started,
unsigned long *nr_written)
{
int ret;
struct btrfs_root *root = BTRFS_I(inode)->root;
if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) {
ret = run_delalloc_nocow(inode, locked_page, start, end,
page_started, 1, nr_written);
} else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC) {
ret = run_delalloc_nocow(inode, locked_page, start, end,
page_started, 0, nr_written);
} else if (!btrfs_test_opt(root, COMPRESS) &&
!(BTRFS_I(inode)->force_compress) &&
!(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS)) {
ret = cow_file_range(inode, locked_page, start, end,
page_started, nr_written, 1);
} else {
set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
&BTRFS_I(inode)->runtime_flags);
ret = cow_file_range_async(inode, locked_page, start, end,
page_started, nr_written);
}
return ret;
}
static void btrfs_split_extent_hook(struct inode *inode,
struct extent_state *orig, u64 split)
{
/* not delalloc, ignore it */
if (!(orig->state & EXTENT_DELALLOC))
return;
spin_lock(&BTRFS_I(inode)->lock);
BTRFS_I(inode)->outstanding_extents++;
spin_unlock(&BTRFS_I(inode)->lock);
}
/*
* extent_io.c merge_extent_hook, used to track merged delayed allocation
* extents so we can keep track of new extents that are just merged onto old
* extents, such as when we are doing sequential writes, so we can properly
* account for the metadata space we'll need.
*/
static void btrfs_merge_extent_hook(struct inode *inode,
struct extent_state *new,
struct extent_state *other)
{
/* not delalloc, ignore it */
if (!(other->state & EXTENT_DELALLOC))
return;
spin_lock(&BTRFS_I(inode)->lock);
BTRFS_I(inode)->outstanding_extents--;
spin_unlock(&BTRFS_I(inode)->lock);
}
static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
struct inode *inode)
{
spin_lock(&root->delalloc_lock);
if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
&root->delalloc_inodes);
set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
&BTRFS_I(inode)->runtime_flags);
root->nr_delalloc_inodes++;
if (root->nr_delalloc_inodes == 1) {
spin_lock(&root->fs_info->delalloc_root_lock);
BUG_ON(!list_empty(&root->delalloc_root));
list_add_tail(&root->delalloc_root,
&root->fs_info->delalloc_roots);
spin_unlock(&root->fs_info->delalloc_root_lock);
}
}
spin_unlock(&root->delalloc_lock);
}
static void btrfs_del_delalloc_inode(struct btrfs_root *root,
struct inode *inode)
{
spin_lock(&root->delalloc_lock);
if (!list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
list_del_init(&BTRFS_I(inode)->delalloc_inodes);
clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
&BTRFS_I(inode)->runtime_flags);
root->nr_delalloc_inodes--;
if (!root->nr_delalloc_inodes) {
spin_lock(&root->fs_info->delalloc_root_lock);
BUG_ON(list_empty(&root->delalloc_root));
list_del_init(&root->delalloc_root);
spin_unlock(&root->fs_info->delalloc_root_lock);
}
}
spin_unlock(&root->delalloc_lock);
}
/*
* extent_io.c set_bit_hook, used to track delayed allocation
* bytes in this file, and to maintain the list of inodes that
* have pending delalloc work to be done.
*/
static void btrfs_set_bit_hook(struct inode *inode,
struct extent_state *state, unsigned long *bits)
{
/*
* set_bit and clear bit hooks normally require _irqsave/restore
* but in this case, we are only testing for the DELALLOC
* bit, which is only set or cleared with irqs on
*/
if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
struct btrfs_root *root = BTRFS_I(inode)->root;
u64 len = state->end + 1 - state->start;
bool do_list = !btrfs_is_free_space_inode(inode);
if (*bits & EXTENT_FIRST_DELALLOC) {
*bits &= ~EXTENT_FIRST_DELALLOC;
} else {
spin_lock(&BTRFS_I(inode)->lock);
BTRFS_I(inode)->outstanding_extents++;
spin_unlock(&BTRFS_I(inode)->lock);
}
__percpu_counter_add(&root->fs_info->delalloc_bytes, len,
root->fs_info->delalloc_batch);
spin_lock(&BTRFS_I(inode)->lock);
BTRFS_I(inode)->delalloc_bytes += len;
if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
&BTRFS_I(inode)->runtime_flags))
btrfs_add_delalloc_inodes(root, inode);
spin_unlock(&BTRFS_I(inode)->lock);
}
}
/*
* extent_io.c clear_bit_hook, see set_bit_hook for why
*/
static void btrfs_clear_bit_hook(struct inode *inode,
struct extent_state *state,
unsigned long *bits)
{
/*
* set_bit and clear bit hooks normally require _irqsave/restore
* but in this case, we are only testing for the DELALLOC
* bit, which is only set or cleared with irqs on
*/
if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
struct btrfs_root *root = BTRFS_I(inode)->root;
u64 len = state->end + 1 - state->start;
bool do_list = !btrfs_is_free_space_inode(inode);
if (*bits & EXTENT_FIRST_DELALLOC) {
*bits &= ~EXTENT_FIRST_DELALLOC;
} else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
spin_lock(&BTRFS_I(inode)->lock);
BTRFS_I(inode)->outstanding_extents--;
spin_unlock(&BTRFS_I(inode)->lock);
}
/*
* We don't reserve metadata space for space cache inodes so we
* don't need to call dellalloc_release_metadata if there is an
* error.
*/
if (*bits & EXTENT_DO_ACCOUNTING &&
root != root->fs_info->tree_root)
btrfs_delalloc_release_metadata(inode, len);
if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
&& do_list && !(state->state & EXTENT_NORESERVE))
btrfs_free_reserved_data_space(inode, len);
__percpu_counter_add(&root->fs_info->delalloc_bytes, -len,
root->fs_info->delalloc_batch);
spin_lock(&BTRFS_I(inode)->lock);
BTRFS_I(inode)->delalloc_bytes -= len;
if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
&BTRFS_I(inode)->runtime_flags))
btrfs_del_delalloc_inode(root, inode);
spin_unlock(&BTRFS_I(inode)->lock);
}
}
/*
* extent_io.c merge_bio_hook, this must check the chunk tree to make sure
* we don't create bios that span stripes or chunks
*/
int btrfs_merge_bio_hook(int rw, struct page *page, unsigned long offset,
size_t size, struct bio *bio,
unsigned long bio_flags)
{
struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
u64 logical = (u64)bio->bi_iter.bi_sector << 9;
u64 length = 0;
u64 map_length;
int ret;
if (bio_flags & EXTENT_BIO_COMPRESSED)
return 0;
length = bio->bi_iter.bi_size;
map_length = length;
ret = btrfs_map_block(root->fs_info, rw, logical,
&map_length, NULL, 0);
/* Will always return 0 with map_multi == NULL */
BUG_ON(ret < 0);
if (map_length < length + size)
return 1;
return 0;
}
/*
* in order to insert checksums into the metadata in large chunks,
* we wait until bio submission time. All the pages in the bio are
* checksummed and sums are attached onto the ordered extent record.
*
* At IO completion time the cums attached on the ordered extent record
* are inserted into the btree
*/
static int __btrfs_submit_bio_start(struct inode *inode, int rw,
struct bio *bio, int mirror_num,
unsigned long bio_flags,
u64 bio_offset)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
int ret = 0;
ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
BUG_ON(ret); /* -ENOMEM */
return 0;
}
/*
* in order to insert checksums into the metadata in large chunks,
* we wait until bio submission time. All the pages in the bio are
* checksummed and sums are attached onto the ordered extent record.
*
* At IO completion time the cums attached on the ordered extent record
* are inserted into the btree
*/
static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
int mirror_num, unsigned long bio_flags,
u64 bio_offset)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
int ret;
ret = btrfs_map_bio(root, rw, bio, mirror_num, 1);
if (ret)
bio_endio(bio, ret);
return ret;
}
/*
* extent_io.c submission hook. This does the right thing for csum calculation
* on write, or reading the csums from the tree before a read
*/
static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
int mirror_num, unsigned long bio_flags,
u64 bio_offset)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
int ret = 0;
int skip_sum;
int metadata = 0;
int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
if (btrfs_is_free_space_inode(inode))
metadata = 2;
if (!(rw & REQ_WRITE)) {
ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
if (ret)
goto out;
if (bio_flags & EXTENT_BIO_COMPRESSED) {
ret = btrfs_submit_compressed_read(inode, bio,
mirror_num,
bio_flags);
goto out;
} else if (!skip_sum) {
ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
if (ret)
goto out;
}
goto mapit;
} else if (async && !skip_sum) {
/* csum items have already been cloned */
if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
goto mapit;
/* we're doing a write, do the async checksumming */
ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
inode, rw, bio, mirror_num,
bio_flags, bio_offset,
__btrfs_submit_bio_start,
__btrfs_submit_bio_done);
goto out;
} else if (!skip_sum) {
ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
if (ret)
goto out;
}
mapit:
ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
out:
if (ret < 0)
bio_endio(bio, ret);
return ret;
}
/*
* given a list of ordered sums record them in the inode. This happens
* at IO completion time based on sums calculated at bio submission time.
*/
static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
struct inode *inode, u64 file_offset,
struct list_head *list)
{
struct btrfs_ordered_sum *sum;
list_for_each_entry(sum, list, list) {
trans->adding_csums = 1;
btrfs_csum_file_blocks(trans,
BTRFS_I(inode)->root->fs_info->csum_root, sum);
trans->adding_csums = 0;
}
return 0;
}
int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
struct extent_state **cached_state)
{
WARN_ON((end & (PAGE_CACHE_SIZE - 1)) == 0);
return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
cached_state, GFP_NOFS);
}
/* see btrfs_writepage_start_hook for details on why this is required */
struct btrfs_writepage_fixup {
struct page *page;
struct btrfs_work work;
};
static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
{
struct btrfs_writepage_fixup *fixup;
struct btrfs_ordered_extent *ordered;
struct extent_state *cached_state = NULL;
struct page *page;
struct inode *inode;
u64 page_start;
u64 page_end;
int ret;
fixup = container_of(work, struct btrfs_writepage_fixup, work);
page = fixup->page;
again:
lock_page(page);
if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
ClearPageChecked(page);
goto out_page;
}
inode = page->mapping->host;
page_start = page_offset(page);
page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
&cached_state);
/* already ordered? We're done */
if (PagePrivate2(page))
goto out;
ordered = btrfs_lookup_ordered_extent(inode, page_start);
if (ordered) {
unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
page_end, &cached_state, GFP_NOFS);
unlock_page(page);
btrfs_start_ordered_extent(inode, ordered, 1);
btrfs_put_ordered_extent(ordered);
goto again;
}
ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
if (ret) {
mapping_set_error(page->mapping, ret);
end_extent_writepage(page, ret, page_start, page_end);
ClearPageChecked(page);
goto out;
}
btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
ClearPageChecked(page);
set_page_dirty(page);
out:
unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
&cached_state, GFP_NOFS);
out_page:
unlock_page(page);
page_cache_release(page);
kfree(fixup);
}
/*
* There are a few paths in the higher layers of the kernel that directly
* set the page dirty bit without asking the filesystem if it is a
* good idea. This causes problems because we want to make sure COW
* properly happens and the data=ordered rules are followed.
*
* In our case any range that doesn't have the ORDERED bit set
* hasn't been properly setup for IO. We kick off an async process
* to fix it up. The async helper will wait for ordered extents, set
* the delalloc bit and make it safe to write the page.
*/
static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
{
struct inode *inode = page->mapping->host;
struct btrfs_writepage_fixup *fixup;
struct btrfs_root *root = BTRFS_I(inode)->root;
/* this page is properly in the ordered list */
if (TestClearPagePrivate2(page))
return 0;
if (PageChecked(page))
return -EAGAIN;
fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
if (!fixup)
return -EAGAIN;
SetPageChecked(page);
page_cache_get(page);
fixup->work.func = btrfs_writepage_fixup_worker;
fixup->page = page;
btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
return -EBUSY;
}
static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
struct inode *inode, u64 file_pos,
u64 disk_bytenr, u64 disk_num_bytes,
u64 num_bytes, u64 ram_bytes,
u8 compression, u8 encryption,
u16 other_encoding, int extent_type)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_file_extent_item *fi;
struct btrfs_path *path;
struct extent_buffer *leaf;
struct btrfs_key ins;
int extent_inserted = 0;
int ret;
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
/*
* we may be replacing one extent in the tree with another.
* The new extent is pinned in the extent map, and we don't want
* to drop it from the cache until it is completely in the btree.
*
* So, tell btrfs_drop_extents to leave this extent in the cache.
* the caller is expected to unpin it and allow it to be merged
* with the others.
*/
ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
file_pos + num_bytes, NULL, 0,
1, sizeof(*fi), &extent_inserted);
if (ret)
goto out;
if (!extent_inserted) {
ins.objectid = btrfs_ino(inode);
ins.offset = file_pos;
ins.type = BTRFS_EXTENT_DATA_KEY;
path->leave_spinning = 1;
ret = btrfs_insert_empty_item(trans, root, path, &ins,
sizeof(*fi));
if (ret)
goto out;
}
leaf = path->nodes[0];
fi = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_file_extent_item);
btrfs_set_file_extent_generation(leaf, fi, trans->transid);
btrfs_set_file_extent_type(leaf, fi, extent_type);
btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
btrfs_set_file_extent_offset(leaf, fi, 0);
btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
btrfs_set_file_extent_compression(leaf, fi, compression);
btrfs_set_file_extent_encryption(leaf, fi, encryption);
btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
btrfs_mark_buffer_dirty(leaf);
btrfs_release_path(path);
inode_add_bytes(inode, num_bytes);
ins.objectid = disk_bytenr;
ins.offset = disk_num_bytes;
ins.type = BTRFS_EXTENT_ITEM_KEY;
ret = btrfs_alloc_reserved_file_extent(trans, root,
root->root_key.objectid,
btrfs_ino(inode), file_pos, &ins);
out:
btrfs_free_path(path);
return ret;
}
/* snapshot-aware defrag */
struct sa_defrag_extent_backref {
struct rb_node node;
struct old_sa_defrag_extent *old;
u64 root_id;
u64 inum;
u64 file_pos;
u64 extent_offset;
u64 num_bytes;
u64 generation;
};
struct old_sa_defrag_extent {
struct list_head list;
struct new_sa_defrag_extent *new;
u64 extent_offset;
u64 bytenr;
u64 offset;
u64 len;
int count;
};
struct new_sa_defrag_extent {
struct rb_root root;
struct list_head head;
struct btrfs_path *path;
struct inode *inode;
u64 file_pos;
u64 len;
u64 bytenr;
u64 disk_len;
u8 compress_type;
};
static int backref_comp(struct sa_defrag_extent_backref *b1,
struct sa_defrag_extent_backref *b2)
{
if (b1->root_id < b2->root_id)
return -1;
else if (b1->root_id > b2->root_id)
return 1;
if (b1->inum < b2->inum)
return -1;
else if (b1->inum > b2->inum)
return 1;
if (b1->file_pos < b2->file_pos)
return -1;
else if (b1->file_pos > b2->file_pos)
return 1;
/*
* [------------------------------] ===> (a range of space)
* |<--->| |<---->| =============> (fs/file tree A)
* |<---------------------------->| ===> (fs/file tree B)
*
* A range of space can refer to two file extents in one tree while
* refer to only one file extent in another tree.
*
* So we may process a disk offset more than one time(two extents in A)
* and locate at the same extent(one extent in B), then insert two same
* backrefs(both refer to the extent in B).
*/
return 0;
}
static void backref_insert(struct rb_root *root,
struct sa_defrag_extent_backref *backref)
{
struct rb_node **p = &root->rb_node;
struct rb_node *parent = NULL;
struct sa_defrag_extent_backref *entry;
int ret;
while (*p) {
parent = *p;
entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
ret = backref_comp(backref, entry);
if (ret < 0)
p = &(*p)->rb_left;
else
p = &(*p)->rb_right;
}
rb_link_node(&backref->node, parent, p);
rb_insert_color(&backref->node, root);
}
/*
* Note the backref might has changed, and in this case we just return 0.
*/
static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
void *ctx)
{
struct btrfs_file_extent_item *extent;
struct btrfs_fs_info *fs_info;
struct old_sa_defrag_extent *old = ctx;
struct new_sa_defrag_extent *new = old->new;
struct btrfs_path *path = new->path;
struct btrfs_key key;
struct btrfs_root *root;
struct sa_defrag_extent_backref *backref;
struct extent_buffer *leaf;
struct inode *inode = new->inode;
int slot;
int ret;
u64 extent_offset;
u64 num_bytes;
if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
inum == btrfs_ino(inode))
return 0;
key.objectid = root_id;
key.type = BTRFS_ROOT_ITEM_KEY;
key.offset = (u64)-1;
fs_info = BTRFS_I(inode)->root->fs_info;
root = btrfs_read_fs_root_no_name(fs_info, &key);
if (IS_ERR(root)) {
if (PTR_ERR(root) == -ENOENT)
return 0;
WARN_ON(1);
pr_debug("inum=%llu, offset=%llu, root_id=%llu\n",
inum, offset, root_id);
return PTR_ERR(root);
}
key.objectid = inum;
key.type = BTRFS_EXTENT_DATA_KEY;
if (offset > (u64)-1 << 32)
key.offset = 0;
else
key.offset = offset;
ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
if (WARN_ON(ret < 0))
return ret;
ret = 0;
while (1) {
cond_resched();
leaf = path->nodes[0];
slot = path->slots[0];
if (slot >= btrfs_header_nritems(leaf)) {
ret = btrfs_next_leaf(root, path);
if (ret < 0) {
goto out;
} else if (ret > 0) {
ret = 0;
goto out;
}
continue;
}
path->slots[0]++;
btrfs_item_key_to_cpu(leaf, &key, slot);
if (key.objectid > inum)
goto out;
if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
continue;
extent = btrfs_item_ptr(leaf, slot,
struct btrfs_file_extent_item);
if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
continue;
/*
* 'offset' refers to the exact key.offset,
* NOT the 'offset' field in btrfs_extent_data_ref, ie.
* (key.offset - extent_offset).
*/
if (key.offset != offset)
continue;
extent_offset = btrfs_file_extent_offset(leaf, extent);
num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
if (extent_offset >= old->extent_offset + old->offset +
old->len || extent_offset + num_bytes <=
old->extent_offset + old->offset)
continue;
break;
}
backref = kmalloc(sizeof(*backref), GFP_NOFS);
if (!backref) {
ret = -ENOENT;
goto out;
}
backref->root_id = root_id;
backref->inum = inum;
backref->file_pos = offset;
backref->num_bytes = num_bytes;
backref->extent_offset = extent_offset;
backref->generation = btrfs_file_extent_generation(leaf, extent);
backref->old = old;
backref_insert(&new->root, backref);
old->count++;
out:
btrfs_release_path(path);
WARN_ON(ret);
return ret;
}
static noinline bool record_extent_backrefs(struct btrfs_path *path,
struct new_sa_defrag_extent *new)
{
struct btrfs_fs_info *fs_info = BTRFS_I(new->inode)->root->fs_info;
struct old_sa_defrag_extent *old, *tmp;
int ret;
new->path = path;
list_for_each_entry_safe(old, tmp, &new->head, list) {
ret = iterate_inodes_from_logical(old->bytenr +
old->extent_offset, fs_info,
path, record_one_backref,
old);
if (ret < 0 && ret != -ENOENT)
return false;
/* no backref to be processed for this extent */
if (!old->count) {
list_del(&old->list);
kfree(old);
}
}
if (list_empty(&new->head))
return false;
return true;
}
static int relink_is_mergable(struct extent_buffer *leaf,
struct btrfs_file_extent_item *fi,
struct new_sa_defrag_extent *new)
{
if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
return 0;
if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
return 0;
if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
return 0;
if (btrfs_file_extent_encryption(leaf, fi) ||
btrfs_file_extent_other_encoding(leaf, fi))
return 0;
return 1;
}
/*
* Note the backref might has changed, and in this case we just return 0.
*/
static noinline int relink_extent_backref(struct btrfs_path *path,
struct sa_defrag_extent_backref *prev,
struct sa_defrag_extent_backref *backref)
{
struct btrfs_file_extent_item *extent;
struct btrfs_file_extent_item *item;
struct btrfs_ordered_extent *ordered;
struct btrfs_trans_handle *trans;
struct btrfs_fs_info *fs_info;
struct btrfs_root *root;
struct btrfs_key key;
struct extent_buffer *leaf;
struct old_sa_defrag_extent *old = backref->old;
struct new_sa_defrag_extent *new = old->new;
struct inode *src_inode = new->inode;
struct inode *inode;
struct extent_state *cached = NULL;
int ret = 0;
u64 start;
u64 len;
u64 lock_start;
u64 lock_end;
bool merge = false;
int index;
if (prev && prev->root_id == backref->root_id &&
prev->inum == backref->inum &&
prev->file_pos + prev->num_bytes == backref->file_pos)
merge = true;
/* step 1: get root */
key.objectid = backref->root_id;
key.type = BTRFS_ROOT_ITEM_KEY;
key.offset = (u64)-1;
fs_info = BTRFS_I(src_inode)->root->fs_info;
index = srcu_read_lock(&fs_info->subvol_srcu);
root = btrfs_read_fs_root_no_name(fs_info, &key);
if (IS_ERR(root)) {
srcu_read_unlock(&fs_info->subvol_srcu, index);
if (PTR_ERR(root) == -ENOENT)
return 0;
return PTR_ERR(root);
}
/* step 2: get inode */
key.objectid = backref->inum;
key.type = BTRFS_INODE_ITEM_KEY;
key.offset = 0;
inode = btrfs_iget(fs_info->sb, &key, root, NULL);
if (IS_ERR(inode)) {
srcu_read_unlock(&fs_info->subvol_srcu, index);
return 0;
}
srcu_read_unlock(&fs_info->subvol_srcu, index);
/* step 3: relink backref */
lock_start = backref->file_pos;
lock_end = backref->file_pos + backref->num_bytes - 1;
lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
0, &cached);
ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
if (ordered) {
btrfs_put_ordered_extent(ordered);
goto out_unlock;
}
trans = btrfs_join_transaction(root);
if (IS_ERR(trans)) {
ret = PTR_ERR(trans);
goto out_unlock;
}
key.objectid = backref->inum;
key.type = BTRFS_EXTENT_DATA_KEY;
key.offset = backref->file_pos;
ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
if (ret < 0) {
goto out_free_path;
} else if (ret > 0) {
ret = 0;
goto out_free_path;
}
extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
struct btrfs_file_extent_item);
if (btrfs_file_extent_generation(path->nodes[0], extent) !=
backref->generation)
goto out_free_path;
btrfs_release_path(path);
start = backref->file_pos;
if (backref->extent_offset < old->extent_offset + old->offset)
start += old->extent_offset + old->offset -
backref->extent_offset;
len = min(backref->extent_offset + backref->num_bytes,
old->extent_offset + old->offset + old->len);
len -= max(backref->extent_offset, old->extent_offset + old->offset);
ret = btrfs_drop_extents(trans, root, inode, start,
start + len, 1);
if (ret)
goto out_free_path;
again:
key.objectid = btrfs_ino(inode);
key.type = BTRFS_EXTENT_DATA_KEY;
key.offset = start;
path->leave_spinning = 1;
if (merge) {
struct btrfs_file_extent_item *fi;
u64 extent_len;
struct btrfs_key found_key;
ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
if (ret < 0)
goto out_free_path;
path->slots[0]--;
leaf = path->nodes[0];
btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
fi = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_file_extent_item);
extent_len = btrfs_file_extent_num_bytes(leaf, fi);
if (extent_len + found_key.offset == start &&
relink_is_mergable(leaf, fi, new)) {
btrfs_set_file_extent_num_bytes(leaf, fi,
extent_len + len);
btrfs_mark_buffer_dirty(leaf);
inode_add_bytes(inode, len);
ret = 1;
goto out_free_path;
} else {
merge = false;
btrfs_release_path(path);
goto again;
}
}
ret = btrfs_insert_empty_item(trans, root, path, &key,
sizeof(*extent));
if (ret) {
btrfs_abort_transaction(trans, root, ret);
goto out_free_path;
}
leaf = path->nodes[0];
item = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_file_extent_item);
btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
btrfs_set_file_extent_num_bytes(leaf, item, len);
btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
btrfs_set_file_extent_generation(leaf, item, trans->transid);
btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
btrfs_set_file_extent_compression(leaf, item, new->compress_type);
btrfs_set_file_extent_encryption(leaf, item, 0);
btrfs_set_file_extent_other_encoding(leaf, item, 0);
btrfs_mark_buffer_dirty(leaf);
inode_add_bytes(inode, len);
btrfs_release_path(path);
ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
new->disk_len, 0,
backref->root_id, backref->inum,
new->file_pos, 0); /* start - extent_offset */
if (ret) {
btrfs_abort_transaction(trans, root, ret);
goto out_free_path;
}
ret = 1;
out_free_path:
btrfs_release_path(path);
path->leave_spinning = 0;
btrfs_end_transaction(trans, root);
out_unlock:
unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
&cached, GFP_NOFS);
iput(inode);
return ret;
}
static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
{
struct old_sa_defrag_extent *old, *tmp;
if (!new)
return;
list_for_each_entry_safe(old, tmp, &new->head, list) {
list_del(&old->list);
kfree(old);
}
kfree(new);
}
static void relink_file_extents(struct new_sa_defrag_extent *new)
{
struct btrfs_path *path;
struct sa_defrag_extent_backref *backref;
struct sa_defrag_extent_backref *prev = NULL;
struct inode *inode;
struct btrfs_root *root;
struct rb_node *node;
int ret;
inode = new->inode;
root = BTRFS_I(inode)->root;
path = btrfs_alloc_path();
if (!path)
return;
if (!record_extent_backrefs(path, new)) {
btrfs_free_path(path);
goto out;
}
btrfs_release_path(path);
while (1) {
node = rb_first(&new->root);
if (!node)
break;
rb_erase(node, &new->root);
backref = rb_entry(node, struct sa_defrag_extent_backref, node);
ret = relink_extent_backref(path, prev, backref);
WARN_ON(ret < 0);
kfree(prev);
if (ret == 1)
prev = backref;
else
prev = NULL;
cond_resched();
}
kfree(prev);
btrfs_free_path(path);
out:
free_sa_defrag_extent(new);
atomic_dec(&root->fs_info->defrag_running);
wake_up(&root->fs_info->transaction_wait);
}
static struct new_sa_defrag_extent *
record_old_file_extents(struct inode *inode,
struct btrfs_ordered_extent *ordered)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_path *path;
struct btrfs_key key;
struct old_sa_defrag_extent *old;
struct new_sa_defrag_extent *new;
int ret;
new = kmalloc(sizeof(*new), GFP_NOFS);
if (!new)
return NULL;
new->inode = inode;
new->file_pos = ordered->file_offset;
new->len = ordered->len;
new->bytenr = ordered->start;
new->disk_len = ordered->disk_len;
new->compress_type = ordered->compress_type;
new->root = RB_ROOT;
INIT_LIST_HEAD(&new->head);
path = btrfs_alloc_path();
if (!path)
goto out_kfree;
key.objectid = btrfs_ino(inode);
key.type = BTRFS_EXTENT_DATA_KEY;
key.offset = new->file_pos;
ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
if (ret < 0)
goto out_free_path;
if (ret > 0 && path->slots[0] > 0)
path->slots[0]--;
/* find out all the old extents for the file range */
while (1) {
struct btrfs_file_extent_item *extent;
struct extent_buffer *l;
int slot;
u64 num_bytes;
u64 offset;
u64 end;
u64 disk_bytenr;
u64 extent_offset;
l = path->nodes[0];
slot = path->slots[0];
if (slot >= btrfs_header_nritems(l)) {
ret = btrfs_next_leaf(root, path);
if (ret < 0)
goto out_free_path;
else if (ret > 0)
break;
continue;
}
btrfs_item_key_to_cpu(l, &key, slot);
if (key.objectid != btrfs_ino(inode))
break;
if (key.type != BTRFS_EXTENT_DATA_KEY)
break;
if (key.offset >= new->file_pos + new->len)
break;
extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
num_bytes = btrfs_file_extent_num_bytes(l, extent);
if (key.offset + num_bytes < new->file_pos)
goto next;
disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
if (!disk_bytenr)
goto next;
extent_offset = btrfs_file_extent_offset(l, extent);
old = kmalloc(sizeof(*old), GFP_NOFS);
if (!old)
goto out_free_path;
offset = max(new->file_pos, key.offset);
end = min(new->file_pos + new->len, key.offset + num_bytes);
old->bytenr = disk_bytenr;
old->extent_offset = extent_offset;
old->offset = offset - key.offset;
old->len = end - offset;
old->new = new;
old->count = 0;
list_add_tail(&old->list, &new->head);
next:
path->slots[0]++;
cond_resched();
}
btrfs_free_path(path);
atomic_inc(&root->fs_info->defrag_running);
return new;
out_free_path:
btrfs_free_path(path);
out_kfree:
free_sa_defrag_extent(new);
return NULL;
}
/* as ordered data IO finishes, this gets called so we can finish
* an ordered extent if the range of bytes in the file it covers are
* fully written.
*/
static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
{
struct inode *inode = ordered_extent->inode;
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_trans_handle *trans = NULL;
struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
struct extent_state *cached_state = NULL;
struct new_sa_defrag_extent *new = NULL;
int compress_type = 0;
int ret = 0;
u64 logical_len = ordered_extent->len;
bool nolock;
bool truncated = false;
nolock = btrfs_is_free_space_inode(inode);
if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
ret = -EIO;
goto out;
}
if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
truncated = true;
logical_len = ordered_extent->truncated_len;
/* Truncated the entire extent, don't bother adding */
if (!logical_len)
goto out;
}
if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
btrfs_ordered_update_i_size(inode, 0, ordered_extent);
if (nolock)
trans = btrfs_join_transaction_nolock(root);
else
trans = btrfs_join_transaction(root);
if (IS_ERR(trans)) {
ret = PTR_ERR(trans);
trans = NULL;
goto out;
}
trans->block_rsv = &root->fs_info->delalloc_block_rsv;
ret = btrfs_update_inode_fallback(trans, root, inode);
if (ret) /* -ENOMEM or corruption */
btrfs_abort_transaction(trans, root, ret);
goto out;
}
lock_extent_bits(io_tree, ordered_extent->file_offset,
ordered_extent->file_offset + ordered_extent->len - 1,
0, &cached_state);
ret = test_range_bit(io_tree, ordered_extent->file_offset,
ordered_extent->file_offset + ordered_extent->len - 1,
EXTENT_DEFRAG, 1, cached_state);
if (ret) {
u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
if (0 && last_snapshot >= BTRFS_I(inode)->generation)
/* the inode is shared */
new = record_old_file_extents(inode, ordered_extent);
clear_extent_bit(io_tree, ordered_extent->file_offset,
ordered_extent->file_offset + ordered_extent->len - 1,
EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
}
if (nolock)
trans = btrfs_join_transaction_nolock(root);
else
trans = btrfs_join_transaction(root);
if (IS_ERR(trans)) {
ret = PTR_ERR(trans);
trans = NULL;
goto out_unlock;
}
trans->block_rsv = &root->fs_info->delalloc_block_rsv;
if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
compress_type = ordered_extent->compress_type;
if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
BUG_ON(compress_type);
ret = btrfs_mark_extent_written(trans, inode,
ordered_extent->file_offset,
ordered_extent->file_offset +
logical_len);
} else {
BUG_ON(root == root->fs_info->tree_root);
ret = insert_reserved_file_extent(trans, inode,
ordered_extent->file_offset,
ordered_extent->start,
ordered_extent->disk_len,
logical_len, logical_len,
compress_type, 0, 0,
BTRFS_FILE_EXTENT_REG);
}
unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
ordered_extent->file_offset, ordered_extent->len,
trans->transid);
if (ret < 0) {
btrfs_abort_transaction(trans, root, ret);
goto out_unlock;
}
add_pending_csums(trans, inode, ordered_extent->file_offset,
&ordered_extent->list);
btrfs_ordered_update_i_size(inode, 0, ordered_extent);
ret = btrfs_update_inode_fallback(trans, root, inode);
if (ret) { /* -ENOMEM or corruption */
btrfs_abort_transaction(trans, root, ret);
goto out_unlock;
}
ret = 0;
out_unlock:
unlock_extent_cached(io_tree, ordered_extent->file_offset,
ordered_extent->file_offset +
ordered_extent->len - 1, &cached_state, GFP_NOFS);
out:
if (root != root->fs_info->tree_root)
btrfs_delalloc_release_metadata(inode, ordered_extent->len);
if (trans)
btrfs_end_transaction(trans, root);
if (ret || truncated) {
u64 start, end;
if (truncated)
start = ordered_extent->file_offset + logical_len;
else
start = ordered_extent->file_offset;
end = ordered_extent->file_offset + ordered_extent->len - 1;
clear_extent_uptodate(io_tree, start, end, NULL, GFP_NOFS);
/* Drop the cache for the part of the extent we didn't write. */
btrfs_drop_extent_cache(inode, start, end, 0);
/*
* If the ordered extent had an IOERR or something else went
* wrong we need to return the space for this ordered extent
* back to the allocator. We only free the extent in the
* truncated case if we didn't write out the extent at all.
*/
if ((ret || !logical_len) &&
!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
!test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
btrfs_free_reserved_extent(root, ordered_extent->start,
ordered_extent->disk_len);
}
/*
* This needs to be done to make sure anybody waiting knows we are done
* updating everything for this ordered extent.
*/
btrfs_remove_ordered_extent(inode, ordered_extent);
/* for snapshot-aware defrag */
if (new) {
if (ret) {
free_sa_defrag_extent(new);
atomic_dec(&root->fs_info->defrag_running);
} else {
relink_file_extents(new);
}
}
/* once for us */
btrfs_put_ordered_extent(ordered_extent);
/* once for the tree */
btrfs_put_ordered_extent(ordered_extent);
return ret;
}
static void finish_ordered_fn(struct btrfs_work *work)
{
struct btrfs_ordered_extent *ordered_extent;
ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
btrfs_finish_ordered_io(ordered_extent);
}
static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
struct extent_state *state, int uptodate)
{
struct inode *inode = page->mapping->host;
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_ordered_extent *ordered_extent = NULL;
struct btrfs_workers *workers;
trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
ClearPagePrivate2(page);
if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
end - start + 1, uptodate))
return 0;
ordered_extent->work.func = finish_ordered_fn;
ordered_extent->work.flags = 0;
if (btrfs_is_free_space_inode(inode))
workers = &root->fs_info->endio_freespace_worker;
else
workers = &root->fs_info->endio_write_workers;
btrfs_queue_worker(workers, &ordered_extent->work);
return 0;
}
/*
* when reads are done, we need to check csums to verify the data is correct
* if there's a match, we allow the bio to finish. If not, the code in
* extent_io.c will try to find good copies for us.
*/
static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
u64 phy_offset, struct page *page,
u64 start, u64 end, int mirror)
{
size_t offset = start - page_offset(page);
struct inode *inode = page->mapping->host;
struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
char *kaddr;
struct btrfs_root *root = BTRFS_I(inode)->root;
u32 csum_expected;
u32 csum = ~(u32)0;
static DEFINE_RATELIMIT_STATE(_rs, DEFAULT_RATELIMIT_INTERVAL,
DEFAULT_RATELIMIT_BURST);
if (PageChecked(page)) {
ClearPageChecked(page);
goto good;
}
if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
goto good;
if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
GFP_NOFS);
return 0;
}
phy_offset >>= inode->i_sb->s_blocksize_bits;
csum_expected = *(((u32 *)io_bio->csum) + phy_offset);
kaddr = kmap_atomic(page);
csum = btrfs_csum_data(kaddr + offset, csum, end - start + 1);
btrfs_csum_final(csum, (char *)&csum);
if (csum != csum_expected)
goto zeroit;
kunmap_atomic(kaddr);
good:
return 0;
zeroit:
if (__ratelimit(&_rs))
btrfs_info(root->fs_info, "csum failed ino %llu off %llu csum %u expected csum %u",
btrfs_ino(page->mapping->host), start, csum, csum_expected);
memset(kaddr + offset, 1, end - start + 1);
flush_dcache_page(page);
kunmap_atomic(kaddr);
if (csum_expected == 0)
return 0;
return -EIO;
}
struct delayed_iput {
struct list_head list;
struct inode *inode;
};
/* JDM: If this is fs-wide, why can't we add a pointer to
* btrfs_inode instead and avoid the allocation? */
void btrfs_add_delayed_iput(struct inode *inode)
{
struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
struct delayed_iput *delayed;
if (atomic_add_unless(&inode->i_count, -1, 1))
return;
delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
delayed->inode = inode;
spin_lock(&fs_info->delayed_iput_lock);
list_add_tail(&delayed->list, &fs_info->delayed_iputs);
spin_unlock(&fs_info->delayed_iput_lock);
}
void btrfs_run_delayed_iputs(struct btrfs_root *root)
{
LIST_HEAD(list);
struct btrfs_fs_info *fs_info = root->fs_info;
struct delayed_iput *delayed;
int empty;
spin_lock(&fs_info->delayed_iput_lock);
empty = list_empty(&fs_info->delayed_iputs);
spin_unlock(&fs_info->delayed_iput_lock);
if (empty)
return;
spin_lock(&fs_info->delayed_iput_lock);
list_splice_init(&fs_info->delayed_iputs, &list);
spin_unlock(&fs_info->delayed_iput_lock);
while (!list_empty(&list)) {
delayed = list_entry(list.next, struct delayed_iput, list);
list_del(&delayed->list);
iput(delayed->inode);
kfree(delayed);
}
}
/*
* This is called in transaction commit time. If there are no orphan
* files in the subvolume, it removes orphan item and frees block_rsv
* structure.
*/
void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
struct btrfs_root *root)
{
struct btrfs_block_rsv *block_rsv;
int ret;
if (atomic_read(&root->orphan_inodes) ||
root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
return;
spin_lock(&root->orphan_lock);
if (atomic_read(&root->orphan_inodes)) {
spin_unlock(&root->orphan_lock);
return;
}
if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
spin_unlock(&root->orphan_lock);
return;
}
block_rsv = root->orphan_block_rsv;
root->orphan_block_rsv = NULL;
spin_unlock(&root->orphan_lock);
if (root->orphan_item_inserted &&
btrfs_root_refs(&root->root_item) > 0) {
ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
root->root_key.objectid);
if (ret)
btrfs_abort_transaction(trans, root, ret);
else
root->orphan_item_inserted = 0;
}
if (block_rsv) {
WARN_ON(block_rsv->size > 0);
btrfs_free_block_rsv(root, block_rsv);
}
}
/*
* This creates an orphan entry for the given inode in case something goes
* wrong in the middle of an unlink/truncate.
*
* NOTE: caller of this function should reserve 5 units of metadata for
* this function.
*/
int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_block_rsv *block_rsv = NULL;
int reserve = 0;
int insert = 0;
int ret;
if (!root->orphan_block_rsv) {
block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
if (!block_rsv)
return -ENOMEM;
}
spin_lock(&root->orphan_lock);
if (!root->orphan_block_rsv) {
root->orphan_block_rsv = block_rsv;
} else if (block_rsv) {
btrfs_free_block_rsv(root, block_rsv);
block_rsv = NULL;
}
if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
&BTRFS_I(inode)->runtime_flags)) {
#if 0
/*
* For proper ENOSPC handling, we should do orphan
* cleanup when mounting. But this introduces backward
* compatibility issue.
*/
if (!xchg(&root->orphan_item_inserted, 1))
insert = 2;
else
insert = 1;
#endif
insert = 1;
atomic_inc(&root->orphan_inodes);
}
if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
&BTRFS_I(inode)->runtime_flags))
reserve = 1;
spin_unlock(&root->orphan_lock);
/* grab metadata reservation from transaction handle */
if (reserve) {
ret = btrfs_orphan_reserve_metadata(trans, inode);
BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
}
/* insert an orphan item to track this unlinked/truncated file */
if (insert >= 1) {
ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
if (ret) {
atomic_dec(&root->orphan_inodes);
if (reserve) {
clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
&BTRFS_I(inode)->runtime_flags);
btrfs_orphan_release_metadata(inode);
}
if (ret != -EEXIST) {
clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
&BTRFS_I(inode)->runtime_flags);
btrfs_abort_transaction(trans, root, ret);
return ret;
}
}
ret = 0;
}
/* insert an orphan item to track subvolume contains orphan files */
if (insert >= 2) {
ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
root->root_key.objectid);
if (ret && ret != -EEXIST) {
btrfs_abort_transaction(trans, root, ret);
return ret;
}
}
return 0;
}
/*
* We have done the truncate/delete so we can go ahead and remove the orphan
* item for this particular inode.
*/
static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
struct inode *inode)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
int delete_item = 0;
int release_rsv = 0;
int ret = 0;
spin_lock(&root->orphan_lock);
if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
&BTRFS_I(inode)->runtime_flags))
delete_item = 1;
if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
&BTRFS_I(inode)->runtime_flags))
release_rsv = 1;
spin_unlock(&root->orphan_lock);
if (delete_item) {
atomic_dec(&root->orphan_inodes);
if (trans)
ret = btrfs_del_orphan_item(trans, root,
btrfs_ino(inode));
}
if (release_rsv)
btrfs_orphan_release_metadata(inode);
return ret;
}
/*
* this cleans up any orphans that may be left on the list from the last use
* of this root.
*/
int btrfs_orphan_cleanup(struct btrfs_root *root)
{
struct btrfs_path *path;
struct extent_buffer *leaf;
struct btrfs_key key, found_key;
struct btrfs_trans_handle *trans;
struct inode *inode;
u64 last_objectid = 0;
int ret = 0, nr_unlink = 0, nr_truncate = 0;
if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
return 0;
path = btrfs_alloc_path();
if (!path) {
ret = -ENOMEM;
goto out;
}
path->reada = -1;
key.objectid = BTRFS_ORPHAN_OBJECTID;
btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
key.offset = (u64)-1;
while (1) {
ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
if (ret < 0)
goto out;
/*
* if ret == 0 means we found what we were searching for, which
* is weird, but possible, so only screw with path if we didn't
* find the key and see if we have stuff that matches
*/
if (ret > 0) {
ret = 0;
if (path->slots[0] == 0)
break;
path->slots[0]--;
}
/* pull out the item */
leaf = path->nodes[0];
btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
/* make sure the item matches what we want */
if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
break;
if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
break;
/* release the path since we're done with it */
btrfs_release_path(path);
/*
* this is where we are basically btrfs_lookup, without the
* crossing root thing. we store the inode number in the
* offset of the orphan item.
*/
if (found_key.offset == last_objectid) {
btrfs_err(root->fs_info,
"Error removing orphan entry, stopping orphan cleanup");
ret = -EINVAL;
goto out;
}
last_objectid = found_key.offset;
found_key.objectid = found_key.offset;
found_key.type = BTRFS_INODE_ITEM_KEY;
found_key.offset = 0;
inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
ret = PTR_ERR_OR_ZERO(inode);
if (ret && ret != -ESTALE)
goto out;
if (ret == -ESTALE && root == root->fs_info->tree_root) {
struct btrfs_root *dead_root;
struct btrfs_fs_info *fs_info = root->fs_info;
int is_dead_root = 0;
/*
* this is an orphan in the tree root. Currently these
* could come from 2 sources:
* a) a snapshot deletion in progress
* b) a free space cache inode
* We need to distinguish those two, as the snapshot
* orphan must not get deleted.
* find_dead_roots already ran before us, so if this
* is a snapshot deletion, we should find the root
* in the dead_roots list
*/
spin_lock(&fs_info->trans_lock);
list_for_each_entry(dead_root, &fs_info->dead_roots,
root_list) {
if (dead_root->root_key.objectid ==
found_key.objectid) {
is_dead_root = 1;
break;
}
}
spin_unlock(&fs_info->trans_lock);
if (is_dead_root) {
/* prevent this orphan from being found again */
key.offset = found_key.objectid - 1;
continue;
}
}
/*
* Inode is already gone but the orphan item is still there,
* kill the orphan item.
*/
if (ret == -ESTALE) {
trans = btrfs_start_transaction(root, 1);
if (IS_ERR(trans)) {
ret = PTR_ERR(trans);
goto out;
}
btrfs_debug(root->fs_info, "auto deleting %Lu",
found_key.objectid);
ret = btrfs_del_orphan_item(trans, root,
found_key.objectid);
btrfs_end_transaction(trans, root);
if (ret)
goto out;
continue;
}
/*
* add this inode to the orphan list so btrfs_orphan_del does
* the proper thing when we hit it
*/
set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
&BTRFS_I(inode)->runtime_flags);
atomic_inc(&root->orphan_inodes);
/* if we have links, this was a truncate, lets do that */
if (inode->i_nlink) {
if (WARN_ON(!S_ISREG(inode->i_mode))) {
iput(inode);
continue;
}
nr_truncate++;
/* 1 for the orphan item deletion. */
trans = btrfs_start_transaction(root, 1);
if (IS_ERR(trans)) {
iput(inode);
ret = PTR_ERR(trans);
goto out;
}
ret = btrfs_orphan_add(trans, inode);
btrfs_end_transaction(trans, root);
if (ret) {
iput(inode);
goto out;
}
ret = btrfs_truncate(inode);
if (ret)
btrfs_orphan_del(NULL, inode);
} else {
nr_unlink++;
}
/* this will do delete_inode and everything for us */
iput(inode);
if (ret)
goto out;
}
/* release the path since we're done with it */
btrfs_release_path(path);
root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
if (root->orphan_block_rsv)
btrfs_block_rsv_release(root, root->orphan_block_rsv,
(u64)-1);
if (root->orphan_block_rsv || root->orphan_item_inserted) {
trans = btrfs_join_transaction(root);
if (!IS_ERR(trans))
btrfs_end_transaction(trans, root);
}
if (nr_unlink)
btrfs_debug(root->fs_info, "unlinked %d orphans", nr_unlink);
if (nr_truncate)
btrfs_debug(root->fs_info, "truncated %d orphans", nr_truncate);
out:
if (ret)
btrfs_crit(root->fs_info,
"could not do orphan cleanup %d", ret);
btrfs_free_path(path);
return ret;
}
/*
* very simple check to peek ahead in the leaf looking for xattrs. If we
* don't find any xattrs, we know there can't be any acls.
*
* slot is the slot the inode is in, objectid is the objectid of the inode
*/
static noinline int acls_after_inode_item(struct extent_buffer *leaf,
int slot, u64 objectid,
int *first_xattr_slot)
{
u32 nritems = btrfs_header_nritems(leaf);
struct btrfs_key found_key;
static u64 xattr_access = 0;
static u64 xattr_default = 0;
int scanned = 0;
if (!xattr_access) {
xattr_access = btrfs_name_hash(POSIX_ACL_XATTR_ACCESS,
strlen(POSIX_ACL_XATTR_ACCESS));
xattr_default = btrfs_name_hash(POSIX_ACL_XATTR_DEFAULT,
strlen(POSIX_ACL_XATTR_DEFAULT));
}
slot++;
*first_xattr_slot = -1;
while (slot < nritems) {
btrfs_item_key_to_cpu(leaf, &found_key, slot);
/* we found a different objectid, there must not be acls */
if (found_key.objectid != objectid)
return 0;
/* we found an xattr, assume we've got an acl */
if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
if (*first_xattr_slot == -1)
*first_xattr_slot = slot;
if (found_key.offset == xattr_access ||
found_key.offset == xattr_default)
return 1;
}
/*
* we found a key greater than an xattr key, there can't
* be any acls later on
*/
if (found_key.type > BTRFS_XATTR_ITEM_KEY)
return 0;
slot++;
scanned++;
/*
* it goes inode, inode backrefs, xattrs, extents,
* so if there are a ton of hard links to an inode there can
* be a lot of backrefs. Don't waste time searching too hard,
* this is just an optimization
*/
if (scanned >= 8)
break;
}
/* we hit the end of the leaf before we found an xattr or
* something larger than an xattr. We have to assume the inode
* has acls
*/
if (*first_xattr_slot == -1)
*first_xattr_slot = slot;
return 1;
}
/*
* read an inode from the btree into the in-memory inode
*/
static void btrfs_read_locked_inode(struct inode *inode)
{
struct btrfs_path *path;
struct extent_buffer *leaf;
struct btrfs_inode_item *inode_item;
struct btrfs_timespec *tspec;
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_key location;
unsigned long ptr;
int maybe_acls;
u32 rdev;
int ret;
bool filled = false;
int first_xattr_slot;
ret = btrfs_fill_inode(inode, &rdev);
if (!ret)
filled = true;
path = btrfs_alloc_path();
if (!path)
goto make_bad;
memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
if (ret)
goto make_bad;
leaf = path->nodes[0];
if (filled)
goto cache_index;
inode_item = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_inode_item);
inode->i_mode = btrfs_inode_mode(leaf, inode_item);
set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
tspec = btrfs_inode_atime(inode_item);
inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
tspec = btrfs_inode_mtime(inode_item);
inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
tspec = btrfs_inode_ctime(inode_item);
inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
/*
* If we were modified in the current generation and evicted from memory
* and then re-read we need to do a full sync since we don't have any
* idea about which extents were modified before we were evicted from
* cache.
*/
if (BTRFS_I(inode)->last_trans == root->fs_info->generation)
set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
&BTRFS_I(inode)->runtime_flags);
inode->i_version = btrfs_inode_sequence(leaf, inode_item);
inode->i_generation = BTRFS_I(inode)->generation;
inode->i_rdev = 0;
rdev = btrfs_inode_rdev(leaf, inode_item);
BTRFS_I(inode)->index_cnt = (u64)-1;
BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
cache_index:
path->slots[0]++;
if (inode->i_nlink != 1 ||
path->slots[0] >= btrfs_header_nritems(leaf))
goto cache_acl;
btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
if (location.objectid != btrfs_ino(inode))
goto cache_acl;
ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
if (location.type == BTRFS_INODE_REF_KEY) {
struct btrfs_inode_ref *ref;
ref = (struct btrfs_inode_ref *)ptr;
BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
} else if (location.type == BTRFS_INODE_EXTREF_KEY) {
struct btrfs_inode_extref *extref;
extref = (struct btrfs_inode_extref *)ptr;
BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
extref);
}
cache_acl:
/*
* try to precache a NULL acl entry for files that don't have
* any xattrs or acls
*/
maybe_acls = acls_after_inode_item(leaf, path->slots[0],
btrfs_ino(inode), &first_xattr_slot);
if (first_xattr_slot != -1) {
path->slots[0] = first_xattr_slot;
ret = btrfs_load_inode_props(inode, path);
if (ret)
btrfs_err(root->fs_info,
"error loading props for ino %llu (root %llu): %d\n",
btrfs_ino(inode),
root->root_key.objectid, ret);
}
btrfs_free_path(path);
if (!maybe_acls)
cache_no_acl(inode);
switch (inode->i_mode & S_IFMT) {
case S_IFREG:
inode->i_mapping->a_ops = &btrfs_aops;
inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
inode->i_fop = &btrfs_file_operations;
inode->i_op = &btrfs_file_inode_operations;
break;
case S_IFDIR:
inode->i_fop = &btrfs_dir_file_operations;
if (root == root->fs_info->tree_root)
inode->i_op = &btrfs_dir_ro_inode_operations;
else
inode->i_op = &btrfs_dir_inode_operations;
break;
case S_IFLNK:
inode->i_op = &btrfs_symlink_inode_operations;
inode->i_mapping->a_ops = &btrfs_symlink_aops;
inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
break;
default:
inode->i_op = &btrfs_special_inode_operations;
init_special_inode(inode, inode->i_mode, rdev);
break;
}
btrfs_update_iflags(inode);
return;
make_bad:
btrfs_free_path(path);
make_bad_inode(inode);
}
/*
* given a leaf and an inode, copy the inode fields into the leaf
*/
static void fill_inode_item(struct btrfs_trans_handle *trans,
struct extent_buffer *leaf,
struct btrfs_inode_item *item,
struct inode *inode)
{
struct btrfs_map_token token;
btrfs_init_map_token(&token);
btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
&token);
btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
btrfs_set_token_timespec_sec(leaf, btrfs_inode_atime(item),
inode->i_atime.tv_sec, &token);
btrfs_set_token_timespec_nsec(leaf, btrfs_inode_atime(item),
inode->i_atime.tv_nsec, &token);
btrfs_set_token_timespec_sec(leaf, btrfs_inode_mtime(item),
inode->i_mtime.tv_sec, &token);
btrfs_set_token_timespec_nsec(leaf, btrfs_inode_mtime(item),
inode->i_mtime.tv_nsec, &token);
btrfs_set_token_timespec_sec(leaf, btrfs_inode_ctime(item),
inode->i_ctime.tv_sec, &token);
btrfs_set_token_timespec_nsec(leaf, btrfs_inode_ctime(item),
inode->i_ctime.tv_nsec, &token);
btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
&token);
btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
&token);
btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
btrfs_set_token_inode_block_group(leaf, item, 0, &token);
}
/*
* copy everything in the in-memory inode into the btree.
*/
static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
struct btrfs_root *root, struct inode *inode)
{
struct btrfs_inode_item *inode_item;
struct btrfs_path *path;
struct extent_buffer *leaf;
int ret;
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
path->leave_spinning = 1;
ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
1);
if (ret) {
if (ret > 0)
ret = -ENOENT;
goto failed;
}
leaf = path->nodes[0];
inode_item = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_inode_item);
fill_inode_item(trans, leaf, inode_item, inode);
btrfs_mark_buffer_dirty(leaf);
btrfs_set_inode_last_trans(trans, inode);
ret = 0;
failed:
btrfs_free_path(path);
return ret;
}
/*
* copy everything in the in-memory inode into the btree.
*/
noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
struct btrfs_root *root, struct inode *inode)
{
int ret;
/*
* If the inode is a free space inode, we can deadlock during commit
* if we put it into the delayed code.
*
* The data relocation inode should also be directly updated
* without delay
*/
if (!btrfs_is_free_space_inode(inode)
&& root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
&& !root->fs_info->log_root_recovering) {
btrfs_update_root_times(trans, root);
ret = btrfs_delayed_update_inode(trans, root, inode);
if (!ret)
btrfs_set_inode_last_trans(trans, inode);
return ret;
}
return btrfs_update_inode_item(trans, root, inode);
}
noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct inode *inode)
{
int ret;
ret = btrfs_update_inode(trans, root, inode);
if (ret == -ENOSPC)
return btrfs_update_inode_item(trans, root, inode);
return ret;
}
/*
* unlink helper that gets used here in inode.c and in the tree logging
* recovery code. It remove a link in a directory with a given name, and
* also drops the back refs in the inode to the directory
*/
static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct inode *dir, struct inode *inode,
const char *name, int name_len)
{
struct btrfs_path *path;
int ret = 0;
struct extent_buffer *leaf;
struct btrfs_dir_item *di;
struct btrfs_key key;
u64 index;
u64 ino = btrfs_ino(inode);
u64 dir_ino = btrfs_ino(dir);
path = btrfs_alloc_path();
if (!path) {
ret = -ENOMEM;
goto out;
}
path->leave_spinning = 1;
di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
name, name_len, -1);
if (IS_ERR(di)) {
ret = PTR_ERR(di);
goto err;
}
if (!di) {
ret = -ENOENT;
goto err;
}
leaf = path->nodes[0];
btrfs_dir_item_key_to_cpu(leaf, di, &key);
ret = btrfs_delete_one_dir_name(trans, root, path, di);
if (ret)
goto err;
btrfs_release_path(path);
/*
* If we don't have dir index, we have to get it by looking up
* the inode ref, since we get the inode ref, remove it directly,
* it is unnecessary to do delayed deletion.
*
* But if we have dir index, needn't search inode ref to get it.
* Since the inode ref is close to the inode item, it is better
* that we delay to delete it, and just do this deletion when
* we update the inode item.
*/
if (BTRFS_I(inode)->dir_index) {
ret = btrfs_delayed_delete_inode_ref(inode);
if (!ret) {
index = BTRFS_I(inode)->dir_index;
goto skip_backref;
}
}
ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
dir_ino, &index);
if (ret) {
btrfs_info(root->fs_info,
"failed to delete reference to %.*s, inode %llu parent %llu",
name_len, name, ino, dir_ino);
btrfs_abort_transaction(trans, root, ret);
goto err;
}
skip_backref:
ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
goto err;
}
ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
inode, dir_ino);
if (ret != 0 && ret != -ENOENT) {
btrfs_abort_transaction(trans, root, ret);
goto err;
}
ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
dir, index);
if (ret == -ENOENT)
ret = 0;
else if (ret)
btrfs_abort_transaction(trans, root, ret);
err:
btrfs_free_path(path);
if (ret)
goto out;
btrfs_i_size_write(dir, dir->i_size - name_len * 2);
inode_inc_iversion(inode);
inode_inc_iversion(dir);
inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
ret = btrfs_update_inode(trans, root, dir);
out:
return ret;
}
int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct inode *dir, struct inode *inode,
const char *name, int name_len)
{
int ret;
ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
if (!ret) {
drop_nlink(inode);
ret = btrfs_update_inode(trans, root, inode);
}
return ret;
}
/*
* helper to start transaction for unlink and rmdir.
*
* unlink and rmdir are special in btrfs, they do not always free space, so
* if we cannot make our reservations the normal way try and see if there is
* plenty of slack room in the global reserve to migrate, otherwise we cannot
* allow the unlink to occur.
*/
static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
{
struct btrfs_trans_handle *trans;
struct btrfs_root *root = BTRFS_I(dir)->root;
int ret;
/*
* 1 for the possible orphan item
* 1 for the dir item
* 1 for the dir index
* 1 for the inode ref
* 1 for the inode
*/
trans = btrfs_start_transaction(root, 5);
if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
return trans;
if (PTR_ERR(trans) == -ENOSPC) {
u64 num_bytes = btrfs_calc_trans_metadata_size(root, 5);
trans = btrfs_start_transaction(root, 0);
if (IS_ERR(trans))
return trans;
ret = btrfs_cond_migrate_bytes(root->fs_info,
&root->fs_info->trans_block_rsv,
num_bytes, 5);
if (ret) {
btrfs_end_transaction(trans, root);
return ERR_PTR(ret);
}
trans->block_rsv = &root->fs_info->trans_block_rsv;
trans->bytes_reserved = num_bytes;
}
return trans;
}
static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
{
struct btrfs_root *root = BTRFS_I(dir)->root;
struct btrfs_trans_handle *trans;
struct inode *inode = dentry->d_inode;
int ret;
trans = __unlink_start_trans(dir);
if (IS_ERR(trans))
return PTR_ERR(trans);
btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
dentry->d_name.name, dentry->d_name.len);
if (ret)
goto out;
if (inode->i_nlink == 0) {
ret = btrfs_orphan_add(trans, inode);
if (ret)
goto out;
}
out:
btrfs_end_transaction(trans, root);
btrfs_btree_balance_dirty(root);
return ret;
}
int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct inode *dir, u64 objectid,
const char *name, int name_len)
{
struct btrfs_path *path;
struct extent_buffer *leaf;
struct btrfs_dir_item *di;
struct btrfs_key key;
u64 index;
int ret;
u64 dir_ino = btrfs_ino(dir);
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
name, name_len, -1);
if (IS_ERR_OR_NULL(di)) {
if (!di)
ret = -ENOENT;
else
ret = PTR_ERR(di);
goto out;
}
leaf = path->nodes[0];
btrfs_dir_item_key_to_cpu(leaf, di, &key);
WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
ret = btrfs_delete_one_dir_name(trans, root, path, di);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
goto out;
}
btrfs_release_path(path);
ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
objectid, root->root_key.objectid,
dir_ino, &index, name, name_len);
if (ret < 0) {
if (ret != -ENOENT) {
btrfs_abort_transaction(trans, root, ret);
goto out;
}
di = btrfs_search_dir_index_item(root, path, dir_ino,
name, name_len);
if (IS_ERR_OR_NULL(di)) {
if (!di)
ret = -ENOENT;
else
ret = PTR_ERR(di);
btrfs_abort_transaction(trans, root, ret);
goto out;
}
leaf = path->nodes[0];
btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
btrfs_release_path(path);
index = key.offset;
}
btrfs_release_path(path);
ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
goto out;
}
btrfs_i_size_write(dir, dir->i_size - name_len * 2);
inode_inc_iversion(dir);
dir->i_mtime = dir->i_ctime = CURRENT_TIME;
ret = btrfs_update_inode_fallback(trans, root, dir);
if (ret)
btrfs_abort_transaction(trans, root, ret);
out:
btrfs_free_path(path);
return ret;
}
static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
{
struct inode *inode = dentry->d_inode;
int err = 0;
struct btrfs_root *root = BTRFS_I(dir)->root;
struct btrfs_trans_handle *trans;
if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
return -ENOTEMPTY;
if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
return -EPERM;
trans = __unlink_start_trans(dir);
if (IS_ERR(trans))
return PTR_ERR(trans);
if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
err = btrfs_unlink_subvol(trans, root, dir,
BTRFS_I(inode)->location.objectid,
dentry->d_name.name,
dentry->d_name.len);
goto out;
}
err = btrfs_orphan_add(trans, inode);
if (err)
goto out;
/* now the directory is empty */
err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
dentry->d_name.name, dentry->d_name.len);
if (!err)
btrfs_i_size_write(inode, 0);
out:
btrfs_end_transaction(trans, root);
btrfs_btree_balance_dirty(root);
return err;
}
/*
* this can truncate away extent items, csum items and directory items.
* It starts at a high offset and removes keys until it can't find
* any higher than new_size
*
* csum items that cross the new i_size are truncated to the new size
* as well.
*
* min_type is the minimum key type to truncate down to. If set to 0, this
* will kill all the items on this inode, including the INODE_ITEM_KEY.
*/
int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct inode *inode,
u64 new_size, u32 min_type)
{
struct btrfs_path *path;
struct extent_buffer *leaf;
struct btrfs_file_extent_item *fi;
struct btrfs_key key;
struct btrfs_key found_key;
u64 extent_start = 0;
u64 extent_num_bytes = 0;
u64 extent_offset = 0;
u64 item_end = 0;
u64 last_size = (u64)-1;
u32 found_type = (u8)-1;
int found_extent;
int del_item;
int pending_del_nr = 0;
int pending_del_slot = 0;
int extent_type = -1;
int ret;
int err = 0;
u64 ino = btrfs_ino(inode);
BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
path->reada = -1;
/*
* We want to drop from the next block forward in case this new size is
* not block aligned since we will be keeping the last block of the
* extent just the way it is.
*/
if (root->ref_cows || root == root->fs_info->tree_root)
btrfs_drop_extent_cache(inode, ALIGN(new_size,
root->sectorsize), (u64)-1, 0);
/*
* This function is also used to drop the items in the log tree before
* we relog the inode, so if root != BTRFS_I(inode)->root, it means
* it is used to drop the loged items. So we shouldn't kill the delayed
* items.
*/
if (min_type == 0 && root == BTRFS_I(inode)->root)
btrfs_kill_delayed_inode_items(inode);
key.objectid = ino;
key.offset = (u64)-1;
key.type = (u8)-1;
search_again:
path->leave_spinning = 1;
ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
if (ret < 0) {
err = ret;
goto out;
}
if (ret > 0) {
/* there are no items in the tree for us to truncate, we're
* done
*/
if (path->slots[0] == 0)
goto out;
path->slots[0]--;
}
while (1) {
fi = NULL;
leaf = path->nodes[0];
btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
found_type = btrfs_key_type(&found_key);
if (found_key.objectid != ino)
break;
if (found_type < min_type)
break;
item_end = found_key.offset;
if (found_type == BTRFS_EXTENT_DATA_KEY) {
fi = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_file_extent_item);
extent_type = btrfs_file_extent_type(leaf, fi);
if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
item_end +=
btrfs_file_extent_num_bytes(leaf, fi);
} else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
item_end += btrfs_file_extent_inline_len(leaf,
path->slots[0], fi);
}
item_end--;
}
if (found_type > min_type) {
del_item = 1;
} else {
if (item_end < new_size)
break;
if (found_key.offset >= new_size)
del_item = 1;
else
del_item = 0;
}
found_extent = 0;
/* FIXME, shrink the extent if the ref count is only 1 */
if (found_type != BTRFS_EXTENT_DATA_KEY)
goto delete;
if (del_item)
last_size = found_key.offset;
else
last_size = new_size;
if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
u64 num_dec;
extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
if (!del_item) {
u64 orig_num_bytes =
btrfs_file_extent_num_bytes(leaf, fi);
extent_num_bytes = ALIGN(new_size -
found_key.offset,
root->sectorsize);
btrfs_set_file_extent_num_bytes(leaf, fi,
extent_num_bytes);
num_dec = (orig_num_bytes -
extent_num_bytes);
if (root->ref_cows && extent_start != 0)
inode_sub_bytes(inode, num_dec);
btrfs_mark_buffer_dirty(leaf);
} else {
extent_num_bytes =
btrfs_file_extent_disk_num_bytes(leaf,
fi);
extent_offset = found_key.offset -
btrfs_file_extent_offset(leaf, fi);
/* FIXME blocksize != 4096 */
num_dec = btrfs_file_extent_num_bytes(leaf, fi);
if (extent_start != 0) {
found_extent = 1;
if (root->ref_cows)
inode_sub_bytes(inode, num_dec);
}
}
} else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
/*
* we can't truncate inline items that have had
* special encodings
*/
if (!del_item &&
btrfs_file_extent_compression(leaf, fi) == 0 &&
btrfs_file_extent_encryption(leaf, fi) == 0 &&
btrfs_file_extent_other_encoding(leaf, fi) == 0) {
u32 size = new_size - found_key.offset;
if (root->ref_cows) {
inode_sub_bytes(inode, item_end + 1 -
new_size);
}
/*
* update the ram bytes to properly reflect
* the new size of our item
*/
btrfs_set_file_extent_ram_bytes(leaf, fi, size);
size =
btrfs_file_extent_calc_inline_size(size);
btrfs_truncate_item(root, path, size, 1);
} else if (root->ref_cows) {
inode_sub_bytes(inode, item_end + 1 -
found_key.offset);
}
}
delete:
if (del_item) {
if (!pending_del_nr) {
/* no pending yet, add ourselves */
pending_del_slot = path->slots[0];
pending_del_nr = 1;
} else if (pending_del_nr &&
path->slots[0] + 1 == pending_del_slot) {
/* hop on the pending chunk */
pending_del_nr++;
pending_del_slot = path->slots[0];
} else {
BUG();
}
} else {
break;
}
if (found_extent && (root->ref_cows ||
root == root->fs_info->tree_root)) {
btrfs_set_path_blocking(path);
ret = btrfs_free_extent(trans, root, extent_start,
extent_num_bytes, 0,
btrfs_header_owner(leaf),
ino, extent_offset, 0);
BUG_ON(ret);
}
if (found_type == BTRFS_INODE_ITEM_KEY)
break;
if (path->slots[0] == 0 ||
path->slots[0] != pending_del_slot) {
if (pending_del_nr) {
ret = btrfs_del_items(trans, root, path,
pending_del_slot,
pending_del_nr);
if (ret) {
btrfs_abort_transaction(trans,
root, ret);
goto error;
}
pending_del_nr = 0;
}
btrfs_release_path(path);
goto search_again;
} else {
path->slots[0]--;
}
}
out:
if (pending_del_nr) {
ret = btrfs_del_items(trans, root, path, pending_del_slot,
pending_del_nr);
if (ret)
btrfs_abort_transaction(trans, root, ret);
}
error:
if (last_size != (u64)-1)
btrfs_ordered_update_i_size(inode, last_size, NULL);
btrfs_free_path(path);
return err;
}
/*
* btrfs_truncate_page - read, zero a chunk and write a page
* @inode - inode that we're zeroing
* @from - the offset to start zeroing
* @len - the length to zero, 0 to zero the entire range respective to the
* offset
* @front - zero up to the offset instead of from the offset on
*
* This will find the page for the "from" offset and cow the page and zero the
* part we want to zero. This is used with truncate and hole punching.
*/
int btrfs_truncate_page(struct inode *inode, loff_t from, loff_t len,
int front)
{
struct address_space *mapping = inode->i_mapping;
struct btrfs_root *root = BTRFS_I(inode)->root;
struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
struct btrfs_ordered_extent *ordered;
struct extent_state *cached_state = NULL;
char *kaddr;
u32 blocksize = root->sectorsize;
pgoff_t index = from >> PAGE_CACHE_SHIFT;
unsigned offset = from & (PAGE_CACHE_SIZE-1);
struct page *page;
gfp_t mask = btrfs_alloc_write_mask(mapping);
int ret = 0;
u64 page_start;
u64 page_end;
if ((offset & (blocksize - 1)) == 0 &&
(!len || ((len & (blocksize - 1)) == 0)))
goto out;
ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
if (ret)
goto out;
again:
page = find_or_create_page(mapping, index, mask);
if (!page) {
btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
ret = -ENOMEM;
goto out;
}
page_start = page_offset(page);
page_end = page_start + PAGE_CACHE_SIZE - 1;
if (!PageUptodate(page)) {
ret = btrfs_readpage(NULL, page);
lock_page(page);
if (page->mapping != mapping) {
unlock_page(page);
page_cache_release(page);
goto again;
}
if (!PageUptodate(page)) {
ret = -EIO;
goto out_unlock;
}
}
wait_on_page_writeback(page);
lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
set_page_extent_mapped(page);
ordered = btrfs_lookup_ordered_extent(inode, page_start);
if (ordered) {
unlock_extent_cached(io_tree, page_start, page_end,
&cached_state, GFP_NOFS);
unlock_page(page);
page_cache_release(page);
btrfs_start_ordered_extent(inode, ordered, 1);
btrfs_put_ordered_extent(ordered);
goto again;
}
clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
EXTENT_DIRTY | EXTENT_DELALLOC |
EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
0, 0, &cached_state, GFP_NOFS);
ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
&cached_state);
if (ret) {
unlock_extent_cached(io_tree, page_start, page_end,
&cached_state, GFP_NOFS);
goto out_unlock;
}
if (offset != PAGE_CACHE_SIZE) {
if (!len)
len = PAGE_CACHE_SIZE - offset;
kaddr = kmap(page);
if (front)
memset(kaddr, 0, offset);
else
memset(kaddr + offset, 0, len);
flush_dcache_page(page);
kunmap(page);
}
ClearPageChecked(page);
set_page_dirty(page);
unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
GFP_NOFS);
out_unlock:
if (ret)
btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
unlock_page(page);
page_cache_release(page);
out:
return ret;
}
static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
u64 offset, u64 len)
{
struct btrfs_trans_handle *trans;
int ret;
/*
* Still need to make sure the inode looks like it's been updated so
* that any holes get logged if we fsync.
*/
if (btrfs_fs_incompat(root->fs_info, NO_HOLES)) {
BTRFS_I(inode)->last_trans = root->fs_info->generation;
BTRFS_I(inode)->last_sub_trans = root->log_transid;
BTRFS_I(inode)->last_log_commit = root->last_log_commit;
return 0;
}
/*
* 1 - for the one we're dropping
* 1 - for the one we're adding
* 1 - for updating the inode.
*/
trans = btrfs_start_transaction(root, 3);
if (IS_ERR(trans))
return PTR_ERR(trans);
ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
btrfs_end_transaction(trans, root);
return ret;
}
ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode), offset,
0, 0, len, 0, len, 0, 0, 0);
if (ret)
btrfs_abort_transaction(trans, root, ret);
else
btrfs_update_inode(trans, root, inode);
btrfs_end_transaction(trans, root);
return ret;
}
/*
* This function puts in dummy file extents for the area we're creating a hole
* for. So if we are truncating this file to a larger size we need to insert
* these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
* the range between oldsize and size
*/
int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
struct extent_map *em = NULL;
struct extent_state *cached_state = NULL;
struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
u64 hole_start = ALIGN(oldsize, root->sectorsize);
u64 block_end = ALIGN(size, root->sectorsize);
u64 last_byte;
u64 cur_offset;
u64 hole_size;
int err = 0;
/*
* If our size started in the middle of a page we need to zero out the
* rest of the page before we expand the i_size, otherwise we could
* expose stale data.
*/
err = btrfs_truncate_page(inode, oldsize, 0, 0);
if (err)
return err;
if (size <= hole_start)
return 0;
while (1) {
struct btrfs_ordered_extent *ordered;
lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
&cached_state);
ordered = btrfs_lookup_ordered_range(inode, hole_start,
block_end - hole_start);
if (!ordered)
break;
unlock_extent_cached(io_tree, hole_start, block_end - 1,
&cached_state, GFP_NOFS);
btrfs_start_ordered_extent(inode, ordered, 1);
btrfs_put_ordered_extent(ordered);
}
cur_offset = hole_start;
while (1) {
em = btrfs_get_extent(inode, NULL, 0, cur_offset,
block_end - cur_offset, 0);
if (IS_ERR(em)) {
err = PTR_ERR(em);
em = NULL;
break;
}
last_byte = min(extent_map_end(em), block_end);
last_byte = ALIGN(last_byte , root->sectorsize);
if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
struct extent_map *hole_em;
hole_size = last_byte - cur_offset;
err = maybe_insert_hole(root, inode, cur_offset,
hole_size);
if (err)
break;
btrfs_drop_extent_cache(inode, cur_offset,
cur_offset + hole_size - 1, 0);
hole_em = alloc_extent_map();
if (!hole_em) {
set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
&BTRFS_I(inode)->runtime_flags);
goto next;
}
hole_em->start = cur_offset;
hole_em->len = hole_size;
hole_em->orig_start = cur_offset;
hole_em->block_start = EXTENT_MAP_HOLE;
hole_em->block_len = 0;
hole_em->orig_block_len = 0;
hole_em->ram_bytes = hole_size;
hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
hole_em->compress_type = BTRFS_COMPRESS_NONE;
hole_em->generation = root->fs_info->generation;
while (1) {
write_lock(&em_tree->lock);
err = add_extent_mapping(em_tree, hole_em, 1);
write_unlock(&em_tree->lock);
if (err != -EEXIST)
break;
btrfs_drop_extent_cache(inode, cur_offset,
cur_offset +
hole_size - 1, 0);
}
free_extent_map(hole_em);
}
next:
free_extent_map(em);
em = NULL;
cur_offset = last_byte;
if (cur_offset >= block_end)
break;
}
free_extent_map(em);
unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
GFP_NOFS);
return err;
}
static int btrfs_setsize(struct inode *inode, struct iattr *attr)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_trans_handle *trans;
loff_t oldsize = i_size_read(inode);
loff_t newsize = attr->ia_size;
int mask = attr->ia_valid;
int ret;
/*
* The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
* special case where we need to update the times despite not having
* these flags set. For all other operations the VFS set these flags
* explicitly if it wants a timestamp update.
*/
if (newsize != oldsize) {
inode_inc_iversion(inode);
if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
inode->i_ctime = inode->i_mtime =
current_fs_time(inode->i_sb);
}
if (newsize > oldsize) {
truncate_pagecache(inode, newsize);
ret = btrfs_cont_expand(inode, oldsize, newsize);
if (ret)
return ret;
trans = btrfs_start_transaction(root, 1);
if (IS_ERR(trans))
return PTR_ERR(trans);
i_size_write(inode, newsize);
btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
ret = btrfs_update_inode(trans, root, inode);
btrfs_end_transaction(trans, root);
} else {
/*
* We're truncating a file that used to have good data down to
* zero. Make sure it gets into the ordered flush list so that
* any new writes get down to disk quickly.
*/
if (newsize == 0)
set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
&BTRFS_I(inode)->runtime_flags);
/*
* 1 for the orphan item we're going to add
* 1 for the orphan item deletion.
*/
trans = btrfs_start_transaction(root, 2);
if (IS_ERR(trans))
return PTR_ERR(trans);
/*
* We need to do this in case we fail at _any_ point during the
* actual truncate. Once we do the truncate_setsize we could
* invalidate pages which forces any outstanding ordered io to
* be instantly completed which will give us extents that need
* to be truncated. If we fail to get an orphan inode down we
* could have left over extents that were never meant to live,
* so we need to garuntee from this point on that everything
* will be consistent.
*/
ret = btrfs_orphan_add(trans, inode);
btrfs_end_transaction(trans, root);
if (ret)
return ret;
/* we don't support swapfiles, so vmtruncate shouldn't fail */
truncate_setsize(inode, newsize);
/* Disable nonlocked read DIO to avoid the end less truncate */
btrfs_inode_block_unlocked_dio(inode);
inode_dio_wait(inode);
btrfs_inode_resume_unlocked_dio(inode);
ret = btrfs_truncate(inode);
if (ret && inode->i_nlink) {
int err;
/*
* failed to truncate, disk_i_size is only adjusted down
* as we remove extents, so it should represent the true
* size of the inode, so reset the in memory size and
* delete our orphan entry.
*/
trans = btrfs_join_transaction(root);
if (IS_ERR(trans)) {
btrfs_orphan_del(NULL, inode);
return ret;
}
i_size_write(inode, BTRFS_I(inode)->disk_i_size);
err = btrfs_orphan_del(trans, inode);
if (err)
btrfs_abort_transaction(trans, root, err);
btrfs_end_transaction(trans, root);
}
}
return ret;
}
static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
{
struct inode *inode = dentry->d_inode;
struct btrfs_root *root = BTRFS_I(inode)->root;
int err;
if (btrfs_root_readonly(root))
return -EROFS;
err = inode_change_ok(inode, attr);
if (err)
return err;
if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
err = btrfs_setsize(inode, attr);
if (err)
return err;
}
if (attr->ia_valid) {
setattr_copy(inode, attr);
inode_inc_iversion(inode);
err = btrfs_dirty_inode(inode);
if (!err && attr->ia_valid & ATTR_MODE)
err = posix_acl_chmod(inode, inode->i_mode);
}
return err;
}
/*
* While truncating the inode pages during eviction, we get the VFS calling
* btrfs_invalidatepage() against each page of the inode. This is slow because
* the calls to btrfs_invalidatepage() result in a huge amount of calls to
* lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
* extent_state structures over and over, wasting lots of time.
*
* Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
* those expensive operations on a per page basis and do only the ordered io
* finishing, while we release here the extent_map and extent_state structures,
* without the excessive merging and splitting.
*/
static void evict_inode_truncate_pages(struct inode *inode)
{
struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
struct rb_node *node;
ASSERT(inode->i_state & I_FREEING);
truncate_inode_pages(&inode->i_data, 0);
write_lock(&map_tree->lock);
while (!RB_EMPTY_ROOT(&map_tree->map)) {
struct extent_map *em;
node = rb_first(&map_tree->map);
em = rb_entry(node, struct extent_map, rb_node);
clear_bit(EXTENT_FLAG_PINNED, &em->flags);
clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
remove_extent_mapping(map_tree, em);
free_extent_map(em);
}
write_unlock(&map_tree->lock);
spin_lock(&io_tree->lock);
while (!RB_EMPTY_ROOT(&io_tree->state)) {
struct extent_state *state;
struct extent_state *cached_state = NULL;
node = rb_first(&io_tree->state);
state = rb_entry(node, struct extent_state, rb_node);
atomic_inc(&state->refs);
spin_unlock(&io_tree->lock);
lock_extent_bits(io_tree, state->start, state->end,
0, &cached_state);
clear_extent_bit(io_tree, state->start, state->end,
EXTENT_LOCKED | EXTENT_DIRTY |
EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
EXTENT_DEFRAG, 1, 1,
&cached_state, GFP_NOFS);
free_extent_state(state);
spin_lock(&io_tree->lock);
}
spin_unlock(&io_tree->lock);
}
void btrfs_evict_inode(struct inode *inode)
{
struct btrfs_trans_handle *trans;
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_block_rsv *rsv, *global_rsv;
u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
int ret;
trace_btrfs_inode_evict(inode);
evict_inode_truncate_pages(inode);
if (inode->i_nlink &&
((btrfs_root_refs(&root->root_item) != 0 &&
root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
btrfs_is_free_space_inode(inode)))
goto no_delete;
if (is_bad_inode(inode)) {
btrfs_orphan_del(NULL, inode);
goto no_delete;
}
/* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
btrfs_wait_ordered_range(inode, 0, (u64)-1);
if (root->fs_info->log_root_recovering) {
BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
&BTRFS_I(inode)->runtime_flags));
goto no_delete;
}
if (inode->i_nlink > 0) {
BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
goto no_delete;
}
ret = btrfs_commit_inode_delayed_inode(inode);
if (ret) {
btrfs_orphan_del(NULL, inode);
goto no_delete;
}
rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
if (!rsv) {
btrfs_orphan_del(NULL, inode);
goto no_delete;
}
rsv->size = min_size;
rsv->failfast = 1;
global_rsv = &root->fs_info->global_block_rsv;
btrfs_i_size_write(inode, 0);
/*
* This is a bit simpler than btrfs_truncate since we've already
* reserved our space for our orphan item in the unlink, so we just
* need to reserve some slack space in case we add bytes and update
* inode item when doing the truncate.
*/
while (1) {
ret = btrfs_block_rsv_refill(root, rsv, min_size,
BTRFS_RESERVE_FLUSH_LIMIT);
/*
* Try and steal from the global reserve since we will
* likely not use this space anyway, we want to try as
* hard as possible to get this to work.
*/
if (ret)
ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size);
if (ret) {
btrfs_warn(root->fs_info,
"Could not get space for a delete, will truncate on mount %d",
ret);
btrfs_orphan_del(NULL, inode);
btrfs_free_block_rsv(root, rsv);
goto no_delete;
}
trans = btrfs_join_transaction(root);
if (IS_ERR(trans)) {
btrfs_orphan_del(NULL, inode);
btrfs_free_block_rsv(root, rsv);
goto no_delete;
}
trans->block_rsv = rsv;
ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
if (ret != -ENOSPC)
break;
trans->block_rsv = &root->fs_info->trans_block_rsv;
btrfs_end_transaction(trans, root);
trans = NULL;
btrfs_btree_balance_dirty(root);
}
btrfs_free_block_rsv(root, rsv);
/*
* Errors here aren't a big deal, it just means we leave orphan items
* in the tree. They will be cleaned up on the next mount.
*/
if (ret == 0) {
trans->block_rsv = root->orphan_block_rsv;
btrfs_orphan_del(trans, inode);
} else {
btrfs_orphan_del(NULL, inode);
}
trans->block_rsv = &root->fs_info->trans_block_rsv;
if (!(root == root->fs_info->tree_root ||
root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
btrfs_return_ino(root, btrfs_ino(inode));
btrfs_end_transaction(trans, root);
btrfs_btree_balance_dirty(root);
no_delete:
btrfs_remove_delayed_node(inode);
clear_inode(inode);
return;
}
/*
* this returns the key found in the dir entry in the location pointer.
* If no dir entries were found, location->objectid is 0.
*/
static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
struct btrfs_key *location)
{
const char *name = dentry->d_name.name;
int namelen = dentry->d_name.len;
struct btrfs_dir_item *di;
struct btrfs_path *path;
struct btrfs_root *root = BTRFS_I(dir)->root;
int ret = 0;
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
namelen, 0);
if (IS_ERR(di))
ret = PTR_ERR(di);
if (IS_ERR_OR_NULL(di))
goto out_err;
btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
out:
btrfs_free_path(path);
return ret;
out_err:
location->objectid = 0;
goto out;
}
/*
* when we hit a tree root in a directory, the btrfs part of the inode
* needs to be changed to reflect the root directory of the tree root. This
* is kind of like crossing a mount point.
*/
static int fixup_tree_root_location(struct btrfs_root *root,
struct inode *dir,
struct dentry *dentry,
struct btrfs_key *location,
struct btrfs_root **sub_root)
{
struct btrfs_path *path;
struct btrfs_root *new_root;
struct btrfs_root_ref *ref;
struct extent_buffer *leaf;
int ret;
int err = 0;
path = btrfs_alloc_path();
if (!path) {
err = -ENOMEM;
goto out;
}
err = -ENOENT;
ret = btrfs_find_item(root->fs_info->tree_root, path,
BTRFS_I(dir)->root->root_key.objectid,
location->objectid, BTRFS_ROOT_REF_KEY, NULL);
if (ret) {
if (ret < 0)
err = ret;
goto out;
}
leaf = path->nodes[0];
ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
goto out;
ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
(unsigned long)(ref + 1),
dentry->d_name.len);
if (ret)
goto out;
btrfs_release_path(path);
new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
if (IS_ERR(new_root)) {
err = PTR_ERR(new_root);
goto out;
}
*sub_root = new_root;
location->objectid = btrfs_root_dirid(&new_root->root_item);
location->type = BTRFS_INODE_ITEM_KEY;
location->offset = 0;
err = 0;
out:
btrfs_free_path(path);
return err;
}
static void inode_tree_add(struct inode *inode)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_inode *entry;
struct rb_node **p;
struct rb_node *parent;
struct rb_node *new = &BTRFS_I(inode)->rb_node;
u64 ino = btrfs_ino(inode);
if (inode_unhashed(inode))
return;
parent = NULL;
spin_lock(&root->inode_lock);
p = &root->inode_tree.rb_node;
while (*p) {
parent = *p;
entry = rb_entry(parent, struct btrfs_inode, rb_node);
if (ino < btrfs_ino(&entry->vfs_inode))
p = &parent->rb_left;
else if (ino > btrfs_ino(&entry->vfs_inode))
p = &parent->rb_right;
else {
WARN_ON(!(entry->vfs_inode.i_state &
(I_WILL_FREE | I_FREEING)));
rb_replace_node(parent, new, &root->inode_tree);
RB_CLEAR_NODE(parent);
spin_unlock(&root->inode_lock);
return;
}
}
rb_link_node(new, parent, p);
rb_insert_color(new, &root->inode_tree);
spin_unlock(&root->inode_lock);
}
static void inode_tree_del(struct inode *inode)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
int empty = 0;
spin_lock(&root->inode_lock);
if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
empty = RB_EMPTY_ROOT(&root->inode_tree);
}
spin_unlock(&root->inode_lock);
if (empty && btrfs_root_refs(&root->root_item) == 0) {
synchronize_srcu(&root->fs_info->subvol_srcu);
spin_lock(&root->inode_lock);
empty = RB_EMPTY_ROOT(&root->inode_tree);
spin_unlock(&root->inode_lock);
if (empty)
btrfs_add_dead_root(root);
}
}
void btrfs_invalidate_inodes(struct btrfs_root *root)
{
struct rb_node *node;
struct rb_node *prev;
struct btrfs_inode *entry;
struct inode *inode;
u64 objectid = 0;
WARN_ON(btrfs_root_refs(&root->root_item) != 0);
spin_lock(&root->inode_lock);
again:
node = root->inode_tree.rb_node;
prev = NULL;
while (node) {
prev = node;
entry = rb_entry(node, struct btrfs_inode, rb_node);
if (objectid < btrfs_ino(&entry->vfs_inode))
node = node->rb_left;
else if (objectid > btrfs_ino(&entry->vfs_inode))
node = node->rb_right;
else
break;
}
if (!node) {
while (prev) {
entry = rb_entry(prev, struct btrfs_inode, rb_node);
if (objectid <= btrfs_ino(&entry->vfs_inode)) {
node = prev;
break;
}
prev = rb_next(prev);
}
}
while (node) {
entry = rb_entry(node, struct btrfs_inode, rb_node);
objectid = btrfs_ino(&entry->vfs_inode) + 1;
inode = igrab(&entry->vfs_inode);
if (inode) {
spin_unlock(&root->inode_lock);
if (atomic_read(&inode->i_count) > 1)
d_prune_aliases(inode);
/*
* btrfs_drop_inode will have it removed from
* the inode cache when its usage count
* hits zero.
*/
iput(inode);
cond_resched();
spin_lock(&root->inode_lock);
goto again;
}
if (cond_resched_lock(&root->inode_lock))
goto again;
node = rb_next(node);
}
spin_unlock(&root->inode_lock);
}
static int btrfs_init_locked_inode(struct inode *inode, void *p)
{
struct btrfs_iget_args *args = p;
inode->i_ino = args->location->objectid;
memcpy(&BTRFS_I(inode)->location, args->location,
sizeof(*args->location));
BTRFS_I(inode)->root = args->root;
return 0;
}
static int btrfs_find_actor(struct inode *inode, void *opaque)
{
struct btrfs_iget_args *args = opaque;
return args->location->objectid == BTRFS_I(inode)->location.objectid &&
args->root == BTRFS_I(inode)->root;
}
static struct inode *btrfs_iget_locked(struct super_block *s,
struct btrfs_key *location,
struct btrfs_root *root)
{
struct inode *inode;
struct btrfs_iget_args args;
unsigned long hashval = btrfs_inode_hash(location->objectid, root);
args.location = location;
args.root = root;
inode = iget5_locked(s, hashval, btrfs_find_actor,
btrfs_init_locked_inode,
(void *)&args);
return inode;
}
/* Get an inode object given its location and corresponding root.
* Returns in *is_new if the inode was read from disk
*/
struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
struct btrfs_root *root, int *new)
{
struct inode *inode;
inode = btrfs_iget_locked(s, location, root);
if (!inode)
return ERR_PTR(-ENOMEM);
if (inode->i_state & I_NEW) {
btrfs_read_locked_inode(inode);
if (!is_bad_inode(inode)) {
inode_tree_add(inode);
unlock_new_inode(inode);
if (new)
*new = 1;
} else {
unlock_new_inode(inode);
iput(inode);
inode = ERR_PTR(-ESTALE);
}
}
return inode;
}
static struct inode *new_simple_dir(struct super_block *s,
struct btrfs_key *key,
struct btrfs_root *root)
{
struct inode *inode = new_inode(s);
if (!inode)
return ERR_PTR(-ENOMEM);
BTRFS_I(inode)->root = root;
memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
inode->i_op = &btrfs_dir_ro_inode_operations;
inode->i_fop = &simple_dir_operations;
inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
return inode;
}
struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
{
struct inode *inode;
struct btrfs_root *root = BTRFS_I(dir)->root;
struct btrfs_root *sub_root = root;
struct btrfs_key location;
int index;
int ret = 0;
if (dentry->d_name.len > BTRFS_NAME_LEN)
return ERR_PTR(-ENAMETOOLONG);
ret = btrfs_inode_by_name(dir, dentry, &location);
if (ret < 0)
return ERR_PTR(ret);
if (location.objectid == 0)
return ERR_PTR(-ENOENT);
if (location.type == BTRFS_INODE_ITEM_KEY) {
inode = btrfs_iget(dir->i_sb, &location, root, NULL);
return inode;
}
BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
index = srcu_read_lock(&root->fs_info->subvol_srcu);
ret = fixup_tree_root_location(root, dir, dentry,
&location, &sub_root);
if (ret < 0) {
if (ret != -ENOENT)
inode = ERR_PTR(ret);
else
inode = new_simple_dir(dir->i_sb, &location, sub_root);
} else {
inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
}
srcu_read_unlock(&root->fs_info->subvol_srcu, index);
if (!IS_ERR(inode) && root != sub_root) {
down_read(&root->fs_info->cleanup_work_sem);
if (!(inode->i_sb->s_flags & MS_RDONLY))
ret = btrfs_orphan_cleanup(sub_root);
up_read(&root->fs_info->cleanup_work_sem);
if (ret) {
iput(inode);
inode = ERR_PTR(ret);
}
}
return inode;
}
static int btrfs_dentry_delete(const struct dentry *dentry)
{
struct btrfs_root *root;
struct inode *inode = dentry->d_inode;
if (!inode && !IS_ROOT(dentry))
inode = dentry->d_parent->d_inode;
if (inode) {
root = BTRFS_I(inode)->root;
if (btrfs_root_refs(&root->root_item) == 0)
return 1;
if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
return 1;
}
return 0;
}
static void btrfs_dentry_release(struct dentry *dentry)
{
if (dentry->d_fsdata)
kfree(dentry->d_fsdata);
}
static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
unsigned int flags)
{
struct inode *inode;
inode = btrfs_lookup_dentry(dir, dentry);
if (IS_ERR(inode)) {
if (PTR_ERR(inode) == -ENOENT)
inode = NULL;
else
return ERR_CAST(inode);
}
return d_materialise_unique(dentry, inode);
}
unsigned char btrfs_filetype_table[] = {
DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
};
static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
{
struct inode *inode = file_inode(file);
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_item *item;
struct btrfs_dir_item *di;
struct btrfs_key key;
struct btrfs_key found_key;
struct btrfs_path *path;
struct list_head ins_list;
struct list_head del_list;
int ret;
struct extent_buffer *leaf;
int slot;
unsigned char d_type;
int over = 0;
u32 di_cur;
u32 di_total;
u32 di_len;
int key_type = BTRFS_DIR_INDEX_KEY;
char tmp_name[32];
char *name_ptr;
int name_len;
int is_curr = 0; /* ctx->pos points to the current index? */
/* FIXME, use a real flag for deciding about the key type */
if (root->fs_info->tree_root == root)
key_type = BTRFS_DIR_ITEM_KEY;
if (!dir_emit_dots(file, ctx))
return 0;
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
path->reada = 1;
if (key_type == BTRFS_DIR_INDEX_KEY) {
INIT_LIST_HEAD(&ins_list);
INIT_LIST_HEAD(&del_list);
btrfs_get_delayed_items(inode, &ins_list, &del_list);
}
btrfs_set_key_type(&key, key_type);
key.offset = ctx->pos;
key.objectid = btrfs_ino(inode);
ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
if (ret < 0)
goto err;
while (1) {
leaf = path->nodes[0];
slot = path->slots[0];
if (slot >= btrfs_header_nritems(leaf)) {
ret = btrfs_next_leaf(root, path);
if (ret < 0)
goto err;
else if (ret > 0)
break;
continue;
}
item = btrfs_item_nr(slot);
btrfs_item_key_to_cpu(leaf, &found_key, slot);
if (found_key.objectid != key.objectid)
break;
if (btrfs_key_type(&found_key) != key_type)
break;
if (found_key.offset < ctx->pos)
goto next;
if (key_type == BTRFS_DIR_INDEX_KEY &&
btrfs_should_delete_dir_index(&del_list,
found_key.offset))
goto next;
ctx->pos = found_key.offset;
is_curr = 1;
di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
di_cur = 0;
di_total = btrfs_item_size(leaf, item);
while (di_cur < di_total) {
struct btrfs_key location;
if (verify_dir_item(root, leaf, di))
break;
name_len = btrfs_dir_name_len(leaf, di);
if (name_len <= sizeof(tmp_name)) {
name_ptr = tmp_name;
} else {
name_ptr = kmalloc(name_len, GFP_NOFS);
if (!name_ptr) {
ret = -ENOMEM;
goto err;
}
}
read_extent_buffer(leaf, name_ptr,
(unsigned long)(di + 1), name_len);
d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
btrfs_dir_item_key_to_cpu(leaf, di, &location);
/* is this a reference to our own snapshot? If so
* skip it.
*
* In contrast to old kernels, we insert the snapshot's
* dir item and dir index after it has been created, so
* we won't find a reference to our own snapshot. We
* still keep the following code for backward
* compatibility.
*/
if (location.type == BTRFS_ROOT_ITEM_KEY &&
location.objectid == root->root_key.objectid) {
over = 0;
goto skip;
}
over = !dir_emit(ctx, name_ptr, name_len,
location.objectid, d_type);
skip:
if (name_ptr != tmp_name)
kfree(name_ptr);
if (over)
goto nopos;
di_len = btrfs_dir_name_len(leaf, di) +
btrfs_dir_data_len(leaf, di) + sizeof(*di);
di_cur += di_len;
di = (struct btrfs_dir_item *)((char *)di + di_len);
}
next:
path->slots[0]++;
}
if (key_type == BTRFS_DIR_INDEX_KEY) {
if (is_curr)
ctx->pos++;
ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
if (ret)
goto nopos;
}
/* Reached end of directory/root. Bump pos past the last item. */
ctx->pos++;
/*
* Stop new entries from being returned after we return the last
* entry.
*
* New directory entries are assigned a strictly increasing
* offset. This means that new entries created during readdir
* are *guaranteed* to be seen in the future by that readdir.
* This has broken buggy programs which operate on names as
* they're returned by readdir. Until we re-use freed offsets
* we have this hack to stop new entries from being returned
* under the assumption that they'll never reach this huge
* offset.
*
* This is being careful not to overflow 32bit loff_t unless the
* last entry requires it because doing so has broken 32bit apps
* in the past.
*/
if (key_type == BTRFS_DIR_INDEX_KEY) {
if (ctx->pos >= INT_MAX)
ctx->pos = LLONG_MAX;
else
ctx->pos = INT_MAX;
}
nopos:
ret = 0;
err:
if (key_type == BTRFS_DIR_INDEX_KEY)
btrfs_put_delayed_items(&ins_list, &del_list);
btrfs_free_path(path);
return ret;
}
int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_trans_handle *trans;
int ret = 0;
bool nolock = false;
if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
return 0;
if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode))
nolock = true;
if (wbc->sync_mode == WB_SYNC_ALL) {
if (nolock)
trans = btrfs_join_transaction_nolock(root);
else
trans = btrfs_join_transaction(root);
if (IS_ERR(trans))
return PTR_ERR(trans);
ret = btrfs_commit_transaction(trans, root);
}
return ret;
}
/*
* This is somewhat expensive, updating the tree every time the
* inode changes. But, it is most likely to find the inode in cache.
* FIXME, needs more benchmarking...there are no reasons other than performance
* to keep or drop this code.
*/
static int btrfs_dirty_inode(struct inode *inode)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_trans_handle *trans;
int ret;
if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
return 0;
trans = btrfs_join_transaction(root);
if (IS_ERR(trans))
return PTR_ERR(trans);
ret = btrfs_update_inode(trans, root, inode);
if (ret && ret == -ENOSPC) {
/* whoops, lets try again with the full transaction */
btrfs_end_transaction(trans, root);
trans = btrfs_start_transaction(root, 1);
if (IS_ERR(trans))
return PTR_ERR(trans);
ret = btrfs_update_inode(trans, root, inode);
}
btrfs_end_transaction(trans, root);
if (BTRFS_I(inode)->delayed_node)
btrfs_balance_delayed_items(root);
return ret;
}
/*
* This is a copy of file_update_time. We need this so we can return error on
* ENOSPC for updating the inode in the case of file write and mmap writes.
*/
static int btrfs_update_time(struct inode *inode, struct timespec *now,
int flags)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
if (btrfs_root_readonly(root))
return -EROFS;
if (flags & S_VERSION)
inode_inc_iversion(inode);
if (flags & S_CTIME)
inode->i_ctime = *now;
if (flags & S_MTIME)
inode->i_mtime = *now;
if (flags & S_ATIME)
inode->i_atime = *now;
return btrfs_dirty_inode(inode);
}
/*
* find the highest existing sequence number in a directory
* and then set the in-memory index_cnt variable to reflect
* free sequence numbers
*/
static int btrfs_set_inode_index_count(struct inode *inode)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_key key, found_key;
struct btrfs_path *path;
struct extent_buffer *leaf;
int ret;
key.objectid = btrfs_ino(inode);
btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
key.offset = (u64)-1;
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
if (ret < 0)
goto out;
/* FIXME: we should be able to handle this */
if (ret == 0)
goto out;
ret = 0;
/*
* MAGIC NUMBER EXPLANATION:
* since we search a directory based on f_pos we have to start at 2
* since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
* else has to start at 2
*/
if (path->slots[0] == 0) {
BTRFS_I(inode)->index_cnt = 2;
goto out;
}
path->slots[0]--;
leaf = path->nodes[0];
btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
if (found_key.objectid != btrfs_ino(inode) ||
btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
BTRFS_I(inode)->index_cnt = 2;
goto out;
}
BTRFS_I(inode)->index_cnt = found_key.offset + 1;
out:
btrfs_free_path(path);
return ret;
}
/*
* helper to find a free sequence number in a given directory. This current
* code is very simple, later versions will do smarter things in the btree
*/
int btrfs_set_inode_index(struct inode *dir, u64 *index)
{
int ret = 0;
if (BTRFS_I(dir)->index_cnt == (u64)-1) {
ret = btrfs_inode_delayed_dir_index_count(dir);
if (ret) {
ret = btrfs_set_inode_index_count(dir);
if (ret)
return ret;
}
}
*index = BTRFS_I(dir)->index_cnt;
BTRFS_I(dir)->index_cnt++;
return ret;
}
static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
struct inode *dir,
const char *name, int name_len,
u64 ref_objectid, u64 objectid,
umode_t mode, u64 *index)
{
struct inode *inode;
struct btrfs_inode_item *inode_item;
struct btrfs_key *location;
struct btrfs_path *path;
struct btrfs_inode_ref *ref;
struct btrfs_key key[2];
u32 sizes[2];
unsigned long ptr;
int ret;
path = btrfs_alloc_path();
if (!path)
return ERR_PTR(-ENOMEM);
inode = new_inode(root->fs_info->sb);
if (!inode) {
btrfs_free_path(path);
return ERR_PTR(-ENOMEM);
}
/*
* we have to initialize this early, so we can reclaim the inode
* number if we fail afterwards in this function.
*/
inode->i_ino = objectid;
if (dir) {
trace_btrfs_inode_request(dir);
ret = btrfs_set_inode_index(dir, index);
if (ret) {
btrfs_free_path(path);
iput(inode);
return ERR_PTR(ret);
}
}
/*
* index_cnt is ignored for everything but a dir,
* btrfs_get_inode_index_count has an explanation for the magic
* number
*/
BTRFS_I(inode)->index_cnt = 2;
BTRFS_I(inode)->dir_index = *index;
BTRFS_I(inode)->root = root;
BTRFS_I(inode)->generation = trans->transid;
inode->i_generation = BTRFS_I(inode)->generation;
/*
* We could have gotten an inode number from somebody who was fsynced
* and then removed in this same transaction, so let's just set full
* sync since it will be a full sync anyway and this will blow away the
* old info in the log.
*/
set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
key[0].objectid = objectid;
btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
key[0].offset = 0;
/*
* Start new inodes with an inode_ref. This is slightly more
* efficient for small numbers of hard links since they will
* be packed into one item. Extended refs will kick in if we
* add more hard links than can fit in the ref item.
*/
key[1].objectid = objectid;
btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
key[1].offset = ref_objectid;
sizes[0] = sizeof(struct btrfs_inode_item);
sizes[1] = name_len + sizeof(*ref);
path->leave_spinning = 1;
ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
if (ret != 0)
goto fail;
inode_init_owner(inode, dir, mode);
inode_set_bytes(inode, 0);
inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
struct btrfs_inode_item);
memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item,
sizeof(*inode_item));
fill_inode_item(trans, path->nodes[0], inode_item, inode);
ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
struct btrfs_inode_ref);
btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
ptr = (unsigned long)(ref + 1);
write_extent_buffer(path->nodes[0], name, ptr, name_len);
btrfs_mark_buffer_dirty(path->nodes[0]);
btrfs_free_path(path);
location = &BTRFS_I(inode)->location;
location->objectid = objectid;
location->offset = 0;
btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
btrfs_inherit_iflags(inode, dir);
if (S_ISREG(mode)) {
if (btrfs_test_opt(root, NODATASUM))
BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
if (btrfs_test_opt(root, NODATACOW))
BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
BTRFS_INODE_NODATASUM;
}
btrfs_insert_inode_hash(inode);
inode_tree_add(inode);
trace_btrfs_inode_new(inode);
btrfs_set_inode_last_trans(trans, inode);
btrfs_update_root_times(trans, root);
ret = btrfs_inode_inherit_props(trans, inode, dir);
if (ret)
btrfs_err(root->fs_info,
"error inheriting props for ino %llu (root %llu): %d",
btrfs_ino(inode), root->root_key.objectid, ret);
return inode;
fail:
if (dir)
BTRFS_I(dir)->index_cnt--;
btrfs_free_path(path);
iput(inode);
return ERR_PTR(ret);
}
static inline u8 btrfs_inode_type(struct inode *inode)
{
return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
}
/*
* utility function to add 'inode' into 'parent_inode' with
* a give name and a given sequence number.
* if 'add_backref' is true, also insert a backref from the
* inode to the parent directory.
*/
int btrfs_add_link(struct btrfs_trans_handle *trans,
struct inode *parent_inode, struct inode *inode,
const char *name, int name_len, int add_backref, u64 index)
{
int ret = 0;
struct btrfs_key key;
struct btrfs_root *root = BTRFS_I(parent_inode)->root;
u64 ino = btrfs_ino(inode);
u64 parent_ino = btrfs_ino(parent_inode);
if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
} else {
key.objectid = ino;
btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
key.offset = 0;
}
if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
key.objectid, root->root_key.objectid,
parent_ino, index, name, name_len);
} else if (add_backref) {
ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
parent_ino, index);
}
/* Nothing to clean up yet */
if (ret)
return ret;
ret = btrfs_insert_dir_item(trans, root, name, name_len,
parent_inode, &key,
btrfs_inode_type(inode), index);
if (ret == -EEXIST || ret == -EOVERFLOW)
goto fail_dir_item;
else if (ret) {
btrfs_abort_transaction(trans, root, ret);
return ret;
}
btrfs_i_size_write(parent_inode, parent_inode->i_size +
name_len * 2);
inode_inc_iversion(parent_inode);
parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
ret = btrfs_update_inode(trans, root, parent_inode);
if (ret)
btrfs_abort_transaction(trans, root, ret);
return ret;
fail_dir_item:
if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
u64 local_index;
int err;
err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
key.objectid, root->root_key.objectid,
parent_ino, &local_index, name, name_len);
} else if (add_backref) {
u64 local_index;
int err;
err = btrfs_del_inode_ref(trans, root, name, name_len,
ino, parent_ino, &local_index);
}
return ret;
}
static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
struct inode *dir, struct dentry *dentry,
struct inode *inode, int backref, u64 index)
{
int err = btrfs_add_link(trans, dir, inode,
dentry->d_name.name, dentry->d_name.len,
backref, index);
if (err > 0)
err = -EEXIST;
return err;
}
static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
umode_t mode, dev_t rdev)
{
struct btrfs_trans_handle *trans;
struct btrfs_root *root = BTRFS_I(dir)->root;
struct inode *inode = NULL;
int err;
int drop_inode = 0;
u64 objectid;
u64 index = 0;
if (!new_valid_dev(rdev))
return -EINVAL;
/*
* 2 for inode item and ref
* 2 for dir items
* 1 for xattr if selinux is on
*/
trans = btrfs_start_transaction(root, 5);
if (IS_ERR(trans))
return PTR_ERR(trans);
err = btrfs_find_free_ino(root, &objectid);
if (err)
goto out_unlock;
inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
dentry->d_name.len, btrfs_ino(dir), objectid,
mode, &index);
if (IS_ERR(inode)) {
err = PTR_ERR(inode);
goto out_unlock;
}
err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
if (err) {
drop_inode = 1;
goto out_unlock;
}
/*
* If the active LSM wants to access the inode during
* d_instantiate it needs these. Smack checks to see
* if the filesystem supports xattrs by looking at the
* ops vector.
*/
inode->i_op = &btrfs_special_inode_operations;
err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
if (err)
drop_inode = 1;
else {
init_special_inode(inode, inode->i_mode, rdev);
btrfs_update_inode(trans, root, inode);
d_instantiate(dentry, inode);
}
out_unlock:
btrfs_end_transaction(trans, root);
btrfs_btree_balance_dirty(root);
if (drop_inode) {
inode_dec_link_count(inode);
iput(inode);
}
return err;
}
static int btrfs_create(struct inode *dir, struct dentry *dentry,
umode_t mode, bool excl)
{
struct btrfs_trans_handle *trans;
struct btrfs_root *root = BTRFS_I(dir)->root;
struct inode *inode = NULL;
int drop_inode_on_err = 0;
int err;
u64 objectid;
u64 index = 0;
/*
* 2 for inode item and ref
* 2 for dir items
* 1 for xattr if selinux is on
*/
trans = btrfs_start_transaction(root, 5);
if (IS_ERR(trans))
return PTR_ERR(trans);
err = btrfs_find_free_ino(root, &objectid);
if (err)
goto out_unlock;
inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
dentry->d_name.len, btrfs_ino(dir), objectid,
mode, &index);
if (IS_ERR(inode)) {
err = PTR_ERR(inode);
goto out_unlock;
}
drop_inode_on_err = 1;
err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
if (err)
goto out_unlock;
err = btrfs_update_inode(trans, root, inode);
if (err)
goto out_unlock;
/*
* If the active LSM wants to access the inode during
* d_instantiate it needs these. Smack checks to see
* if the filesystem supports xattrs by looking at the
* ops vector.
*/
inode->i_fop = &btrfs_file_operations;
inode->i_op = &btrfs_file_inode_operations;
err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
if (err)
goto out_unlock;
inode->i_mapping->a_ops = &btrfs_aops;
inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
d_instantiate(dentry, inode);
out_unlock:
btrfs_end_transaction(trans, root);
if (err && drop_inode_on_err) {
inode_dec_link_count(inode);
iput(inode);
}
btrfs_btree_balance_dirty(root);
return err;
}
static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
struct dentry *dentry)
{
struct btrfs_trans_handle *trans;
struct btrfs_root *root = BTRFS_I(dir)->root;
struct inode *inode = old_dentry->d_inode;
u64 index;
int err;
int drop_inode = 0;
/* do not allow sys_link's with other subvols of the same device */
if (root->objectid != BTRFS_I(inode)->root->objectid)
return -EXDEV;
if (inode->i_nlink >= BTRFS_LINK_MAX)
return -EMLINK;
err = btrfs_set_inode_index(dir, &index);
if (err)
goto fail;
/*
* 2 items for inode and inode ref
* 2 items for dir items
* 1 item for parent inode
*/
trans = btrfs_start_transaction(root, 5);
if (IS_ERR(trans)) {
err = PTR_ERR(trans);
goto fail;
}
/* There are several dir indexes for this inode, clear the cache. */
BTRFS_I(inode)->dir_index = 0ULL;
inc_nlink(inode);
inode_inc_iversion(inode);
inode->i_ctime = CURRENT_TIME;
ihold(inode);
set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
if (err) {
drop_inode = 1;
} else {
struct dentry *parent = dentry->d_parent;
err = btrfs_update_inode(trans, root, inode);
if (err)
goto fail;
d_instantiate(dentry, inode);
btrfs_log_new_name(trans, inode, NULL, parent);
}
btrfs_end_transaction(trans, root);
fail:
if (drop_inode) {
inode_dec_link_count(inode);
iput(inode);
}
btrfs_btree_balance_dirty(root);
return err;
}
static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
{
struct inode *inode = NULL;
struct btrfs_trans_handle *trans;
struct btrfs_root *root = BTRFS_I(dir)->root;
int err = 0;
int drop_on_err = 0;
u64 objectid = 0;
u64 index = 0;
/*
* 2 items for inode and ref
* 2 items for dir items
* 1 for xattr if selinux is on
*/
trans = btrfs_start_transaction(root, 5);
if (IS_ERR(trans))
return PTR_ERR(trans);
err = btrfs_find_free_ino(root, &objectid);
if (err)
goto out_fail;
inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
dentry->d_name.len, btrfs_ino(dir), objectid,
S_IFDIR | mode, &index);
if (IS_ERR(inode)) {
err = PTR_ERR(inode);
goto out_fail;
}
drop_on_err = 1;
err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
if (err)
goto out_fail;
inode->i_op = &btrfs_dir_inode_operations;
inode->i_fop = &btrfs_dir_file_operations;
btrfs_i_size_write(inode, 0);
err = btrfs_update_inode(trans, root, inode);
if (err)
goto out_fail;
err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
dentry->d_name.len, 0, index);
if (err)
goto out_fail;
d_instantiate(dentry, inode);
drop_on_err = 0;
out_fail:
btrfs_end_transaction(trans, root);
if (drop_on_err)
iput(inode);
btrfs_btree_balance_dirty(root);
return err;
}
/* helper for btfs_get_extent. Given an existing extent in the tree,
* and an extent that you want to insert, deal with overlap and insert
* the new extent into the tree.
*/
static int merge_extent_mapping(struct extent_map_tree *em_tree,
struct extent_map *existing,
struct extent_map *em,
u64 map_start, u64 map_len)
{
u64 start_diff;
BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
start_diff = map_start - em->start;
em->start = map_start;
em->len = map_len;
if (em->block_start < EXTENT_MAP_LAST_BYTE &&
!test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
em->block_start += start_diff;
em->block_len -= start_diff;
}
return add_extent_mapping(em_tree, em, 0);
}
static noinline int uncompress_inline(struct btrfs_path *path,
struct inode *inode, struct page *page,
size_t pg_offset, u64 extent_offset,
struct btrfs_file_extent_item *item)
{
int ret;
struct extent_buffer *leaf = path->nodes[0];
char *tmp;
size_t max_size;
unsigned long inline_size;
unsigned long ptr;
int compress_type;
WARN_ON(pg_offset != 0);
compress_type = btrfs_file_extent_compression(leaf, item);
max_size = btrfs_file_extent_ram_bytes(leaf, item);
inline_size = btrfs_file_extent_inline_item_len(leaf,
btrfs_item_nr(path->slots[0]));
tmp = kmalloc(inline_size, GFP_NOFS);
if (!tmp)
return -ENOMEM;
ptr = btrfs_file_extent_inline_start(item);
read_extent_buffer(leaf, tmp, ptr, inline_size);
max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
ret = btrfs_decompress(compress_type, tmp, page,
extent_offset, inline_size, max_size);
if (ret) {
char *kaddr = kmap_atomic(page);
unsigned long copy_size = min_t(u64,
PAGE_CACHE_SIZE - pg_offset,
max_size - extent_offset);
memset(kaddr + pg_offset, 0, copy_size);
kunmap_atomic(kaddr);
}
kfree(tmp);
return 0;
}
/*
* a bit scary, this does extent mapping from logical file offset to the disk.
* the ugly parts come from merging extents from the disk with the in-ram
* representation. This gets more complex because of the data=ordered code,
* where the in-ram extents might be locked pending data=ordered completion.
*
* This also copies inline extents directly into the page.
*/
struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
size_t pg_offset, u64 start, u64 len,
int create)
{
int ret;
int err = 0;
u64 bytenr;
u64 extent_start = 0;
u64 extent_end = 0;
u64 objectid = btrfs_ino(inode);
u32 found_type;
struct btrfs_path *path = NULL;
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_file_extent_item *item;
struct extent_buffer *leaf;
struct btrfs_key found_key;
struct extent_map *em = NULL;
struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
struct btrfs_trans_handle *trans = NULL;
int compress_type;
again:
read_lock(&em_tree->lock);
em = lookup_extent_mapping(em_tree, start, len);
if (em)
em->bdev = root->fs_info->fs_devices->latest_bdev;
read_unlock(&em_tree->lock);
if (em) {
if (em->start > start || em->start + em->len <= start)
free_extent_map(em);
else if (em->block_start == EXTENT_MAP_INLINE && page)
free_extent_map(em);
else
goto out;
}
em = alloc_extent_map();
if (!em) {
err = -ENOMEM;
goto out;
}
em->bdev = root->fs_info->fs_devices->latest_bdev;
em->start = EXTENT_MAP_HOLE;
em->orig_start = EXTENT_MAP_HOLE;
em->len = (u64)-1;
em->block_len = (u64)-1;
if (!path) {
path = btrfs_alloc_path();
if (!path) {
err = -ENOMEM;
goto out;
}
/*
* Chances are we'll be called again, so go ahead and do
* readahead
*/
path->reada = 1;
}
ret = btrfs_lookup_file_extent(trans, root, path,
objectid, start, trans != NULL);
if (ret < 0) {
err = ret;
goto out;
}
if (ret != 0) {
if (path->slots[0] == 0)
goto not_found;
path->slots[0]--;
}
leaf = path->nodes[0];
item = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_file_extent_item);
/* are we inside the extent that was found? */
btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
found_type = btrfs_key_type(&found_key);
if (found_key.objectid != objectid ||
found_type != BTRFS_EXTENT_DATA_KEY) {
/*
* If we backup past the first extent we want to move forward
* and see if there is an extent in front of us, otherwise we'll
* say there is a hole for our whole search range which can
* cause problems.
*/
extent_end = start;
goto next;
}
found_type = btrfs_file_extent_type(leaf, item);
extent_start = found_key.offset;
compress_type = btrfs_file_extent_compression(leaf, item);
if (found_type == BTRFS_FILE_EXTENT_REG ||
found_type == BTRFS_FILE_EXTENT_PREALLOC) {
extent_end = extent_start +
btrfs_file_extent_num_bytes(leaf, item);
} else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
size_t size;
size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
extent_end = ALIGN(extent_start + size, root->sectorsize);
}
next:
if (start >= extent_end) {
path->slots[0]++;
if (path->slots[0] >= btrfs_header_nritems(leaf)) {
ret = btrfs_next_leaf(root, path);
if (ret < 0) {
err = ret;
goto out;
}
if (ret > 0)
goto not_found;
leaf = path->nodes[0];
}
btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
if (found_key.objectid != objectid ||
found_key.type != BTRFS_EXTENT_DATA_KEY)
goto not_found;
if (start + len <= found_key.offset)
goto not_found;
em->start = start;
em->orig_start = start;
em->len = found_key.offset - start;
goto not_found_em;
}
em->ram_bytes = btrfs_file_extent_ram_bytes(leaf, item);
if (found_type == BTRFS_FILE_EXTENT_REG ||
found_type == BTRFS_FILE_EXTENT_PREALLOC) {
em->start = extent_start;
em->len = extent_end - extent_start;
em->orig_start = extent_start -
btrfs_file_extent_offset(leaf, item);
em->orig_block_len = btrfs_file_extent_disk_num_bytes(leaf,
item);
bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
if (bytenr == 0) {
em->block_start = EXTENT_MAP_HOLE;
goto insert;
}
if (compress_type != BTRFS_COMPRESS_NONE) {
set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
em->compress_type = compress_type;
em->block_start = bytenr;
em->block_len = em->orig_block_len;
} else {
bytenr += btrfs_file_extent_offset(leaf, item);
em->block_start = bytenr;
em->block_len = em->len;
if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
}
goto insert;
} else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
unsigned long ptr;
char *map;
size_t size;
size_t extent_offset;
size_t copy_size;
em->block_start = EXTENT_MAP_INLINE;
if (!page || create) {
em->start = extent_start;
em->len = extent_end - extent_start;
goto out;
}
size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
extent_offset = page_offset(page) + pg_offset - extent_start;
copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
size - extent_offset);
em->start = extent_start + extent_offset;
em->len = ALIGN(copy_size, root->sectorsize);
em->orig_block_len = em->len;
em->orig_start = em->start;
if (compress_type) {
set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
em->compress_type = compress_type;
}
ptr = btrfs_file_extent_inline_start(item) + extent_offset;
if (create == 0 && !PageUptodate(page)) {
if (btrfs_file_extent_compression(leaf, item) !=
BTRFS_COMPRESS_NONE) {
ret = uncompress_inline(path, inode, page,
pg_offset,
extent_offset, item);
BUG_ON(ret); /* -ENOMEM */
} else {
map = kmap(page);
read_extent_buffer(leaf, map + pg_offset, ptr,
copy_size);
if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
memset(map + pg_offset + copy_size, 0,
PAGE_CACHE_SIZE - pg_offset -
copy_size);
}
kunmap(page);
}
flush_dcache_page(page);
} else if (create && PageUptodate(page)) {
BUG();
if (!trans) {
kunmap(page);
free_extent_map(em);
em = NULL;
btrfs_release_path(path);
trans = btrfs_join_transaction(root);
if (IS_ERR(trans))
return ERR_CAST(trans);
goto again;
}
map = kmap(page);
write_extent_buffer(leaf, map + pg_offset, ptr,
copy_size);
kunmap(page);
btrfs_mark_buffer_dirty(leaf);
}
set_extent_uptodate(io_tree, em->start,
extent_map_end(em) - 1, NULL, GFP_NOFS);
goto insert;
} else {
WARN(1, KERN_ERR "btrfs unknown found_type %d\n", found_type);
}
not_found:
em->start = start;
em->orig_start = start;
em->len = len;
not_found_em:
em->block_start = EXTENT_MAP_HOLE;
set_bit(EXTENT_FLAG_VACANCY, &em->flags);
insert:
btrfs_release_path(path);
if (em->start > start || extent_map_end(em) <= start) {
btrfs_err(root->fs_info, "bad extent! em: [%llu %llu] passed [%llu %llu]",
em->start, em->len, start, len);
err = -EIO;
goto out;
}
err = 0;
write_lock(&em_tree->lock);
ret = add_extent_mapping(em_tree, em, 0);
/* it is possible that someone inserted the extent into the tree
* while we had the lock dropped. It is also possible that
* an overlapping map exists in the tree
*/
if (ret == -EEXIST) {
struct extent_map *existing;
ret = 0;
existing = lookup_extent_mapping(em_tree, start, len);
if (existing && (existing->start > start ||
existing->start + existing->len <= start)) {
free_extent_map(existing);
existing = NULL;
}
if (!existing) {
existing = lookup_extent_mapping(em_tree, em->start,
em->len);
if (existing) {
err = merge_extent_mapping(em_tree, existing,
em, start,
root->sectorsize);
free_extent_map(existing);
if (err) {
free_extent_map(em);
em = NULL;
}
} else {
err = -EIO;
free_extent_map(em);
em = NULL;
}
} else {
free_extent_map(em);
em = existing;
err = 0;
}
}
write_unlock(&em_tree->lock);
out:
trace_btrfs_get_extent(root, em);
if (path)
btrfs_free_path(path);
if (trans) {
ret = btrfs_end_transaction(trans, root);
if (!err)
err = ret;
}
if (err) {
free_extent_map(em);
return ERR_PTR(err);
}
BUG_ON(!em); /* Error is always set */
return em;
}
struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
size_t pg_offset, u64 start, u64 len,
int create)
{
struct extent_map *em;
struct extent_map *hole_em = NULL;
u64 range_start = start;
u64 end;
u64 found;
u64 found_end;
int err = 0;
em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
if (IS_ERR(em))
return em;
if (em) {
/*
* if our em maps to
* - a hole or
* - a pre-alloc extent,
* there might actually be delalloc bytes behind it.
*/
if (em->block_start != EXTENT_MAP_HOLE &&
!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
return em;
else
hole_em = em;
}
/* check to see if we've wrapped (len == -1 or similar) */
end = start + len;
if (end < start)
end = (u64)-1;
else
end -= 1;
em = NULL;
/* ok, we didn't find anything, lets look for delalloc */
found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
end, len, EXTENT_DELALLOC, 1);
found_end = range_start + found;
if (found_end < range_start)
found_end = (u64)-1;
/*
* we didn't find anything useful, return
* the original results from get_extent()
*/
if (range_start > end || found_end <= start) {
em = hole_em;
hole_em = NULL;
goto out;
}
/* adjust the range_start to make sure it doesn't
* go backwards from the start they passed in
*/
range_start = max(start, range_start);
found = found_end - range_start;
if (found > 0) {
u64 hole_start = start;
u64 hole_len = len;
em = alloc_extent_map();
if (!em) {
err = -ENOMEM;
goto out;
}
/*
* when btrfs_get_extent can't find anything it
* returns one huge hole
*
* make sure what it found really fits our range, and
* adjust to make sure it is based on the start from
* the caller
*/
if (hole_em) {
u64 calc_end = extent_map_end(hole_em);
if (calc_end <= start || (hole_em->start > end)) {
free_extent_map(hole_em);
hole_em = NULL;
} else {
hole_start = max(hole_em->start, start);
hole_len = calc_end - hole_start;
}
}
em->bdev = NULL;
if (hole_em && range_start > hole_start) {
/* our hole starts before our delalloc, so we
* have to return just the parts of the hole
* that go until the delalloc starts
*/
em->len = min(hole_len,
range_start - hole_start);
em->start = hole_start;
em->orig_start = hole_start;
/*
* don't adjust block start at all,
* it is fixed at EXTENT_MAP_HOLE
*/
em->block_start = hole_em->block_start;
em->block_len = hole_len;
if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
} else {
em->start = range_start;
em->len = found;
em->orig_start = range_start;
em->block_start = EXTENT_MAP_DELALLOC;
em->block_len = found;
}
} else if (hole_em) {
return hole_em;
}
out:
free_extent_map(hole_em);
if (err) {
free_extent_map(em);
return ERR_PTR(err);
}
return em;
}
static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
u64 start, u64 len)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
struct extent_map *em;
struct btrfs_key ins;
u64 alloc_hint;
int ret;
alloc_hint = get_extent_allocation_hint(inode, start, len);
ret = btrfs_reserve_extent(root, len, root->sectorsize, 0,
alloc_hint, &ins, 1);
if (ret)
return ERR_PTR(ret);
em = create_pinned_em(inode, start, ins.offset, start, ins.objectid,
ins.offset, ins.offset, ins.offset, 0);
if (IS_ERR(em)) {
btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
return em;
}
ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
ins.offset, ins.offset, 0);
if (ret) {
btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
free_extent_map(em);
return ERR_PTR(ret);
}
return em;
}
/*
* returns 1 when the nocow is safe, < 1 on error, 0 if the
* block must be cow'd
*/
noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
u64 *orig_start, u64 *orig_block_len,
u64 *ram_bytes)
{
struct btrfs_trans_handle *trans;
struct btrfs_path *path;
int ret;
struct extent_buffer *leaf;
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_file_extent_item *fi;
struct btrfs_key key;
u64 disk_bytenr;
u64 backref_offset;
u64 extent_end;
u64 num_bytes;
int slot;
int found_type;
bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
offset, 0);
if (ret < 0)
goto out;
slot = path->slots[0];
if (ret == 1) {
if (slot == 0) {
/* can't find the item, must cow */
ret = 0;
goto out;
}
slot--;
}
ret = 0;
leaf = path->nodes[0];
btrfs_item_key_to_cpu(leaf, &key, slot);
if (key.objectid != btrfs_ino(inode) ||
key.type != BTRFS_EXTENT_DATA_KEY) {
/* not our file or wrong item type, must cow */
goto out;
}
if (key.offset > offset) {
/* Wrong offset, must cow */
goto out;
}
fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
found_type = btrfs_file_extent_type(leaf, fi);
if (found_type != BTRFS_FILE_EXTENT_REG &&
found_type != BTRFS_FILE_EXTENT_PREALLOC) {
/* not a regular extent, must cow */
goto out;
}
if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
goto out;
extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
if (extent_end <= offset)
goto out;
disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
if (disk_bytenr == 0)
goto out;
if (btrfs_file_extent_compression(leaf, fi) ||
btrfs_file_extent_encryption(leaf, fi) ||
btrfs_file_extent_other_encoding(leaf, fi))
goto out;
backref_offset = btrfs_file_extent_offset(leaf, fi);
if (orig_start) {
*orig_start = key.offset - backref_offset;
*orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
*ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
}
if (btrfs_extent_readonly(root, disk_bytenr))
goto out;
btrfs_release_path(path);
/*
* look for other files referencing this extent, if we
* find any we must cow
*/
trans = btrfs_join_transaction(root);
if (IS_ERR(trans)) {
ret = 0;
goto out;
}
ret = btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
key.offset - backref_offset, disk_bytenr);
btrfs_end_transaction(trans, root);
if (ret) {
ret = 0;
goto out;
}
/*
* adjust disk_bytenr and num_bytes to cover just the bytes
* in this extent we are about to write. If there
* are any csums in that range we have to cow in order
* to keep the csums correct
*/
disk_bytenr += backref_offset;
disk_bytenr += offset - key.offset;
num_bytes = min(offset + *len, extent_end) - offset;
if (csum_exist_in_range(root, disk_bytenr, num_bytes))
goto out;
/*
* all of the above have passed, it is safe to overwrite this extent
* without cow
*/
*len = num_bytes;
ret = 1;
out:
btrfs_free_path(path);
return ret;
}
static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
struct extent_state **cached_state, int writing)
{
struct btrfs_ordered_extent *ordered;
int ret = 0;
while (1) {
lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
0, cached_state);
/*
* We're concerned with the entire range that we're going to be
* doing DIO to, so we need to make sure theres no ordered
* extents in this range.
*/
ordered = btrfs_lookup_ordered_range(inode, lockstart,
lockend - lockstart + 1);
/*
* We need to make sure there are no buffered pages in this
* range either, we could have raced between the invalidate in
* generic_file_direct_write and locking the extent. The
* invalidate needs to happen so that reads after a write do not
* get stale data.
*/
if (!ordered && (!writing ||
!test_range_bit(&BTRFS_I(inode)->io_tree,
lockstart, lockend, EXTENT_UPTODATE, 0,
*cached_state)))
break;
unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
cached_state, GFP_NOFS);
if (ordered) {
btrfs_start_ordered_extent(inode, ordered, 1);
btrfs_put_ordered_extent(ordered);
} else {
/* Screw you mmap */
ret = filemap_write_and_wait_range(inode->i_mapping,
lockstart,
lockend);
if (ret)
break;
/*
* If we found a page that couldn't be invalidated just
* fall back to buffered.
*/
ret = invalidate_inode_pages2_range(inode->i_mapping,
lockstart >> PAGE_CACHE_SHIFT,
lockend >> PAGE_CACHE_SHIFT);
if (ret)
break;
}
cond_resched();
}
return ret;
}
static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
u64 len, u64 orig_start,
u64 block_start, u64 block_len,
u64 orig_block_len, u64 ram_bytes,
int type)
{
struct extent_map_tree *em_tree;
struct extent_map *em;
struct btrfs_root *root = BTRFS_I(inode)->root;
int ret;
em_tree = &BTRFS_I(inode)->extent_tree;
em = alloc_extent_map();
if (!em)
return ERR_PTR(-ENOMEM);
em->start = start;
em->orig_start = orig_start;
em->mod_start = start;
em->mod_len = len;
em->len = len;
em->block_len = block_len;
em->block_start = block_start;
em->bdev = root->fs_info->fs_devices->latest_bdev;
em->orig_block_len = orig_block_len;
em->ram_bytes = ram_bytes;
em->generation = -1;
set_bit(EXTENT_FLAG_PINNED, &em->flags);
if (type == BTRFS_ORDERED_PREALLOC)
set_bit(EXTENT_FLAG_FILLING, &em->flags);
do {
btrfs_drop_extent_cache(inode, em->start,
em->start + em->len - 1, 0);
write_lock(&em_tree->lock);
ret = add_extent_mapping(em_tree, em, 1);
write_unlock(&em_tree->lock);
} while (ret == -EEXIST);
if (ret) {
free_extent_map(em);
return ERR_PTR(ret);
}
return em;
}
static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
struct buffer_head *bh_result, int create)
{
struct extent_map *em;
struct btrfs_root *root = BTRFS_I(inode)->root;
struct extent_state *cached_state = NULL;
u64 start = iblock << inode->i_blkbits;
u64 lockstart, lockend;
u64 len = bh_result->b_size;
int unlock_bits = EXTENT_LOCKED;
int ret = 0;
if (create)
unlock_bits |= EXTENT_DELALLOC | EXTENT_DIRTY;
else
len = min_t(u64, len, root->sectorsize);
lockstart = start;
lockend = start + len - 1;
/*
* If this errors out it's because we couldn't invalidate pagecache for
* this range and we need to fallback to buffered.
*/
if (lock_extent_direct(inode, lockstart, lockend, &cached_state, create))
return -ENOTBLK;
em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
if (IS_ERR(em)) {
ret = PTR_ERR(em);
goto unlock_err;
}
/*
* Ok for INLINE and COMPRESSED extents we need to fallback on buffered
* io. INLINE is special, and we could probably kludge it in here, but
* it's still buffered so for safety lets just fall back to the generic
* buffered path.
*
* For COMPRESSED we _have_ to read the entire extent in so we can
* decompress it, so there will be buffering required no matter what we
* do, so go ahead and fallback to buffered.
*
* We return -ENOTBLK because thats what makes DIO go ahead and go back
* to buffered IO. Don't blame me, this is the price we pay for using
* the generic code.
*/
if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
em->block_start == EXTENT_MAP_INLINE) {
free_extent_map(em);
ret = -ENOTBLK;
goto unlock_err;
}
/* Just a good old fashioned hole, return */
if (!create && (em->block_start == EXTENT_MAP_HOLE ||
test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
free_extent_map(em);
goto unlock_err;
}
/*
* We don't allocate a new extent in the following cases
*
* 1) The inode is marked as NODATACOW. In this case we'll just use the
* existing extent.
* 2) The extent is marked as PREALLOC. We're good to go here and can
* just use the extent.
*
*/
if (!create) {
len = min(len, em->len - (start - em->start));
lockstart = start + len;
goto unlock;
}
if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
em->block_start != EXTENT_MAP_HOLE)) {
int type;
int ret;
u64 block_start, orig_start, orig_block_len, ram_bytes;
if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
type = BTRFS_ORDERED_PREALLOC;
else
type = BTRFS_ORDERED_NOCOW;
len = min(len, em->len - (start - em->start));
block_start = em->block_start + (start - em->start);
if (can_nocow_extent(inode, start, &len, &orig_start,
&orig_block_len, &ram_bytes) == 1) {
if (type == BTRFS_ORDERED_PREALLOC) {
free_extent_map(em);
em = create_pinned_em(inode, start, len,
orig_start,
block_start, len,
orig_block_len,
ram_bytes, type);
if (IS_ERR(em))
goto unlock_err;
}
ret = btrfs_add_ordered_extent_dio(inode, start,
block_start, len, len, type);
if (ret) {
free_extent_map(em);
goto unlock_err;
}
goto unlock;
}
}
/*
* this will cow the extent, reset the len in case we changed
* it above
*/
len = bh_result->b_size;
free_extent_map(em);
em = btrfs_new_extent_direct(inode, start, len);
if (IS_ERR(em)) {
ret = PTR_ERR(em);
goto unlock_err;
}
len = min(len, em->len - (start - em->start));
unlock:
bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
inode->i_blkbits;
bh_result->b_size = len;
bh_result->b_bdev = em->bdev;
set_buffer_mapped(bh_result);
if (create) {
if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
set_buffer_new(bh_result);
/*
* Need to update the i_size under the extent lock so buffered
* readers will get the updated i_size when we unlock.
*/
if (start + len > i_size_read(inode))
i_size_write(inode, start + len);
spin_lock(&BTRFS_I(inode)->lock);
BTRFS_I(inode)->outstanding_extents++;
spin_unlock(&BTRFS_I(inode)->lock);
ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
lockstart + len - 1, EXTENT_DELALLOC, NULL,
&cached_state, GFP_NOFS);
BUG_ON(ret);
}
/*
* In the case of write we need to clear and unlock the entire range,
* in the case of read we need to unlock only the end area that we
* aren't using if there is any left over space.
*/
if (lockstart < lockend) {
clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
lockend, unlock_bits, 1, 0,
&cached_state, GFP_NOFS);
} else {
free_extent_state(cached_state);
}
free_extent_map(em);
return 0;
unlock_err:
clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
unlock_bits, 1, 0, &cached_state, GFP_NOFS);
return ret;
}
static void btrfs_endio_direct_read(struct bio *bio, int err)
{
struct btrfs_dio_private *dip = bio->bi_private;
struct bio_vec *bvec;
struct inode *inode = dip->inode;
struct btrfs_root *root = BTRFS_I(inode)->root;
struct bio *dio_bio;
u32 *csums = (u32 *)dip->csum;
u64 start;
int i;
start = dip->logical_offset;
bio_for_each_segment_all(bvec, bio, i) {
if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
struct page *page = bvec->bv_page;
char *kaddr;
u32 csum = ~(u32)0;
unsigned long flags;
local_irq_save(flags);
kaddr = kmap_atomic(page);
csum = btrfs_csum_data(kaddr + bvec->bv_offset,
csum, bvec->bv_len);
btrfs_csum_final(csum, (char *)&csum);
kunmap_atomic(kaddr);
local_irq_restore(flags);
flush_dcache_page(bvec->bv_page);
if (csum != csums[i]) {
btrfs_err(root->fs_info, "csum failed ino %llu off %llu csum %u expected csum %u",
btrfs_ino(inode), start, csum,
csums[i]);
err = -EIO;
}
}
start += bvec->bv_len;
}
unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
dip->logical_offset + dip->bytes - 1);
dio_bio = dip->dio_bio;
kfree(dip);
/* If we had a csum failure make sure to clear the uptodate flag */
if (err)
clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
dio_end_io(dio_bio, err);
bio_put(bio);
}
static void btrfs_endio_direct_write(struct bio *bio, int err)
{
struct btrfs_dio_private *dip = bio->bi_private;
struct inode *inode = dip->inode;
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_ordered_extent *ordered = NULL;
u64 ordered_offset = dip->logical_offset;
u64 ordered_bytes = dip->bytes;
struct bio *dio_bio;
int ret;
if (err)
goto out_done;
again:
ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
&ordered_offset,
ordered_bytes, !err);
if (!ret)
goto out_test;
ordered->work.func = finish_ordered_fn;
ordered->work.flags = 0;
btrfs_queue_worker(&root->fs_info->endio_write_workers,
&ordered->work);
out_test:
/*
* our bio might span multiple ordered extents. If we haven't
* completed the accounting for the whole dio, go back and try again
*/
if (ordered_offset < dip->logical_offset + dip->bytes) {
ordered_bytes = dip->logical_offset + dip->bytes -
ordered_offset;
ordered = NULL;
goto again;
}
out_done:
dio_bio = dip->dio_bio;
kfree(dip);
/* If we had an error make sure to clear the uptodate flag */
if (err)
clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
dio_end_io(dio_bio, err);
bio_put(bio);
}
static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
struct bio *bio, int mirror_num,
unsigned long bio_flags, u64 offset)
{
int ret;
struct btrfs_root *root = BTRFS_I(inode)->root;
ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
BUG_ON(ret); /* -ENOMEM */
return 0;
}
static void btrfs_end_dio_bio(struct bio *bio, int err)
{
struct btrfs_dio_private *dip = bio->bi_private;
if (err) {
btrfs_err(BTRFS_I(dip->inode)->root->fs_info,
"direct IO failed ino %llu rw %lu sector %#Lx len %u err no %d",
btrfs_ino(dip->inode), bio->bi_rw,
(unsigned long long)bio->bi_iter.bi_sector,
bio->bi_iter.bi_size, err);
dip->errors = 1;
/*
* before atomic variable goto zero, we must make sure
* dip->errors is perceived to be set.
*/
smp_mb__before_atomic_dec();
}
/* if there are more bios still pending for this dio, just exit */
if (!atomic_dec_and_test(&dip->pending_bios))
goto out;
if (dip->errors) {
bio_io_error(dip->orig_bio);
} else {
set_bit(BIO_UPTODATE, &dip->dio_bio->bi_flags);
bio_endio(dip->orig_bio, 0);
}
out:
bio_put(bio);
}
static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
u64 first_sector, gfp_t gfp_flags)
{
int nr_vecs = bio_get_nr_vecs(bdev);
return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
}
static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
int rw, u64 file_offset, int skip_sum,
int async_submit)
{
struct btrfs_dio_private *dip = bio->bi_private;
int write = rw & REQ_WRITE;
struct btrfs_root *root = BTRFS_I(inode)->root;
int ret;
if (async_submit)
async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
bio_get(bio);
if (!write) {
ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
if (ret)
goto err;
}
if (skip_sum)
goto map;
if (write && async_submit) {
ret = btrfs_wq_submit_bio(root->fs_info,
inode, rw, bio, 0, 0,
file_offset,
__btrfs_submit_bio_start_direct_io,
__btrfs_submit_bio_done);
goto err;
} else if (write) {
/*
* If we aren't doing async submit, calculate the csum of the
* bio now.
*/
ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
if (ret)
goto err;
} else if (!skip_sum) {
ret = btrfs_lookup_bio_sums_dio(root, inode, dip, bio,
file_offset);
if (ret)
goto err;
}
map:
ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
err:
bio_put(bio);
return ret;
}
static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
int skip_sum)
{
struct inode *inode = dip->inode;
struct btrfs_root *root = BTRFS_I(inode)->root;
struct bio *bio;
struct bio *orig_bio = dip->orig_bio;
struct bio_vec *bvec = orig_bio->bi_io_vec;
u64 start_sector = orig_bio->bi_iter.bi_sector;
u64 file_offset = dip->logical_offset;
u64 submit_len = 0;
u64 map_length;
int nr_pages = 0;
int ret = 0;
int async_submit = 0;
map_length = orig_bio->bi_iter.bi_size;
ret = btrfs_map_block(root->fs_info, rw, start_sector << 9,
&map_length, NULL, 0);
if (ret) {
bio_put(orig_bio);
return -EIO;
}
if (map_length >= orig_bio->bi_iter.bi_size) {
bio = orig_bio;
goto submit;
}
/* async crcs make it difficult to collect full stripe writes. */
if (btrfs_get_alloc_profile(root, 1) &
(BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6))
async_submit = 0;
else
async_submit = 1;
bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
if (!bio)
return -ENOMEM;
bio->bi_private = dip;
bio->bi_end_io = btrfs_end_dio_bio;
atomic_inc(&dip->pending_bios);
while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
if (unlikely(map_length < submit_len + bvec->bv_len ||
bio_add_page(bio, bvec->bv_page, bvec->bv_len,
bvec->bv_offset) < bvec->bv_len)) {
/*
* inc the count before we submit the bio so
* we know the end IO handler won't happen before
* we inc the count. Otherwise, the dip might get freed
* before we're done setting it up
*/
atomic_inc(&dip->pending_bios);
ret = __btrfs_submit_dio_bio(bio, inode, rw,
file_offset, skip_sum,
async_submit);
if (ret) {
bio_put(bio);
atomic_dec(&dip->pending_bios);
goto out_err;
}
start_sector += submit_len >> 9;
file_offset += submit_len;
submit_len = 0;
nr_pages = 0;
bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
start_sector, GFP_NOFS);
if (!bio)
goto out_err;
bio->bi_private = dip;
bio->bi_end_io = btrfs_end_dio_bio;
map_length = orig_bio->bi_iter.bi_size;
ret = btrfs_map_block(root->fs_info, rw,
start_sector << 9,
&map_length, NULL, 0);
if (ret) {
bio_put(bio);
goto out_err;
}
} else {
submit_len += bvec->bv_len;
nr_pages++;
bvec++;
}
}
submit:
ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
async_submit);
if (!ret)
return 0;
bio_put(bio);
out_err:
dip->errors = 1;
/*
* before atomic variable goto zero, we must
* make sure dip->errors is perceived to be set.
*/
smp_mb__before_atomic_dec();
if (atomic_dec_and_test(&dip->pending_bios))
bio_io_error(dip->orig_bio);
/* bio_end_io() will handle error, so we needn't return it */
return 0;
}
static void btrfs_submit_direct(int rw, struct bio *dio_bio,
struct inode *inode, loff_t file_offset)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_dio_private *dip;
struct bio *io_bio;
int skip_sum;
int sum_len;
int write = rw & REQ_WRITE;
int ret = 0;
u16 csum_size;
skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
io_bio = btrfs_bio_clone(dio_bio, GFP_NOFS);
if (!io_bio) {
ret = -ENOMEM;
goto free_ordered;
}
if (!skip_sum && !write) {
csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
sum_len = dio_bio->bi_iter.bi_size >>
inode->i_sb->s_blocksize_bits;
sum_len *= csum_size;
} else {
sum_len = 0;
}
dip = kmalloc(sizeof(*dip) + sum_len, GFP_NOFS);
if (!dip) {
ret = -ENOMEM;
goto free_io_bio;
}
dip->private = dio_bio->bi_private;
dip->inode = inode;
dip->logical_offset = file_offset;
dip->bytes = dio_bio->bi_iter.bi_size;
dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
io_bio->bi_private = dip;
dip->errors = 0;
dip->orig_bio = io_bio;
dip->dio_bio = dio_bio;
atomic_set(&dip->pending_bios, 0);
if (write)
io_bio->bi_end_io = btrfs_endio_direct_write;
else
io_bio->bi_end_io = btrfs_endio_direct_read;
ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
if (!ret)
return;
free_io_bio:
bio_put(io_bio);
free_ordered:
/*
* If this is a write, we need to clean up the reserved space and kill
* the ordered extent.
*/
if (write) {
struct btrfs_ordered_extent *ordered;
ordered = btrfs_lookup_ordered_extent(inode, file_offset);
if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
!test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
btrfs_free_reserved_extent(root, ordered->start,
ordered->disk_len);
btrfs_put_ordered_extent(ordered);
btrfs_put_ordered_extent(ordered);
}
bio_endio(dio_bio, ret);
}
static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
const struct iovec *iov, loff_t offset,
unsigned long nr_segs)
{
int seg;
int i;
size_t size;
unsigned long addr;
unsigned blocksize_mask = root->sectorsize - 1;
ssize_t retval = -EINVAL;
loff_t end = offset;
if (offset & blocksize_mask)
goto out;
/* Check the memory alignment. Blocks cannot straddle pages */
for (seg = 0; seg < nr_segs; seg++) {
addr = (unsigned long)iov[seg].iov_base;
size = iov[seg].iov_len;
end += size;
if ((addr & blocksize_mask) || (size & blocksize_mask))
goto out;
/* If this is a write we don't need to check anymore */
if (rw & WRITE)
continue;
/*
* Check to make sure we don't have duplicate iov_base's in this
* iovec, if so return EINVAL, otherwise we'll get csum errors
* when reading back.
*/
for (i = seg + 1; i < nr_segs; i++) {
if (iov[seg].iov_base == iov[i].iov_base)
goto out;
}
}
retval = 0;
out:
return retval;
}
static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
const struct iovec *iov, loff_t offset,
unsigned long nr_segs)
{
struct file *file = iocb->ki_filp;
struct inode *inode = file->f_mapping->host;
size_t count = 0;
int flags = 0;
bool wakeup = true;
bool relock = false;
ssize_t ret;
if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iov,
offset, nr_segs))
return 0;
atomic_inc(&inode->i_dio_count);
smp_mb__after_atomic_inc();
/*
* The generic stuff only does filemap_write_and_wait_range, which isn't
* enough if we've written compressed pages to this area, so we need to
* call btrfs_wait_ordered_range to make absolutely sure that any
* outstanding dirty pages are on disk.
*/
count = iov_length(iov, nr_segs);
ret = btrfs_wait_ordered_range(inode, offset, count);
if (ret)
return ret;
if (rw & WRITE) {
/*
* If the write DIO is beyond the EOF, we need update
* the isize, but it is protected by i_mutex. So we can
* not unlock the i_mutex at this case.
*/
if (offset + count <= inode->i_size) {
mutex_unlock(&inode->i_mutex);
relock = true;
}
ret = btrfs_delalloc_reserve_space(inode, count);
if (ret)
goto out;
} else if (unlikely(test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
&BTRFS_I(inode)->runtime_flags))) {
inode_dio_done(inode);
flags = DIO_LOCKING | DIO_SKIP_HOLES;
wakeup = false;
}
ret = __blockdev_direct_IO(rw, iocb, inode,
BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
iov, offset, nr_segs, btrfs_get_blocks_direct, NULL,
btrfs_submit_direct, flags);
if (rw & WRITE) {
if (ret < 0 && ret != -EIOCBQUEUED)
btrfs_delalloc_release_space(inode, count);
else if (ret >= 0 && (size_t)ret < count)
btrfs_delalloc_release_space(inode,
count - (size_t)ret);
else
btrfs_delalloc_release_metadata(inode, 0);
}
out:
if (wakeup)
inode_dio_done(inode);
if (relock)
mutex_lock(&inode->i_mutex);
return ret;
}
#define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
__u64 start, __u64 len)
{
int ret;
ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
if (ret)
return ret;
return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
}
int btrfs_readpage(struct file *file, struct page *page)
{
struct extent_io_tree *tree;
tree = &BTRFS_I(page->mapping->host)->io_tree;
return extent_read_full_page(tree, page, btrfs_get_extent, 0);
}
static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
{
struct extent_io_tree *tree;
if (current->flags & PF_MEMALLOC) {
redirty_page_for_writepage(wbc, page);
unlock_page(page);
return 0;
}
tree = &BTRFS_I(page->mapping->host)->io_tree;
return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
}
static int btrfs_writepages(struct address_space *mapping,
struct writeback_control *wbc)
{
struct extent_io_tree *tree;
tree = &BTRFS_I(mapping->host)->io_tree;
return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
}
static int
btrfs_readpages(struct file *file, struct address_space *mapping,
struct list_head *pages, unsigned nr_pages)
{
struct extent_io_tree *tree;
tree = &BTRFS_I(mapping->host)->io_tree;
return extent_readpages(tree, mapping, pages, nr_pages,
btrfs_get_extent);
}
static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
{
struct extent_io_tree *tree;
struct extent_map_tree *map;
int ret;
tree = &BTRFS_I(page->mapping->host)->io_tree;
map = &BTRFS_I(page->mapping->host)->extent_tree;
ret = try_release_extent_mapping(map, tree, page, gfp_flags);
if (ret == 1) {
ClearPagePrivate(page);
set_page_private(page, 0);
page_cache_release(page);
}
return ret;
}
static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
{
if (PageWriteback(page) || PageDirty(page))
return 0;
return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
}
static void btrfs_invalidatepage(struct page *page, unsigned int offset,
unsigned int length)
{
struct inode *inode = page->mapping->host;
struct extent_io_tree *tree;
struct btrfs_ordered_extent *ordered;
struct extent_state *cached_state = NULL;
u64 page_start = page_offset(page);
u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
int inode_evicting = inode->i_state & I_FREEING;
/*
* we have the page locked, so new writeback can't start,
* and the dirty bit won't be cleared while we are here.
*
* Wait for IO on this page so that we can safely clear
* the PagePrivate2 bit and do ordered accounting
*/
wait_on_page_writeback(page);
tree = &BTRFS_I(inode)->io_tree;
if (offset) {
btrfs_releasepage(page, GFP_NOFS);
return;
}
if (!inode_evicting)
lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
ordered = btrfs_lookup_ordered_extent(inode, page_start);
if (ordered) {
/*
* IO on this page will never be started, so we need
* to account for any ordered extents now
*/
if (!inode_evicting)
clear_extent_bit(tree, page_start, page_end,
EXTENT_DIRTY | EXTENT_DELALLOC |
EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
EXTENT_DEFRAG, 1, 0, &cached_state,
GFP_NOFS);
/*
* whoever cleared the private bit is responsible
* for the finish_ordered_io
*/
if (TestClearPagePrivate2(page)) {
struct btrfs_ordered_inode_tree *tree;
u64 new_len;
tree = &BTRFS_I(inode)->ordered_tree;
spin_lock_irq(&tree->lock);
set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
new_len = page_start - ordered->file_offset;
if (new_len < ordered->truncated_len)
ordered->truncated_len = new_len;
spin_unlock_irq(&tree->lock);
if (btrfs_dec_test_ordered_pending(inode, &ordered,
page_start,
PAGE_CACHE_SIZE, 1))
btrfs_finish_ordered_io(ordered);
}
btrfs_put_ordered_extent(ordered);
if (!inode_evicting) {
cached_state = NULL;
lock_extent_bits(tree, page_start, page_end, 0,
&cached_state);
}
}
if (!inode_evicting) {
clear_extent_bit(tree, page_start, page_end,
EXTENT_LOCKED | EXTENT_DIRTY |
EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
EXTENT_DEFRAG, 1, 1,
&cached_state, GFP_NOFS);
__btrfs_releasepage(page, GFP_NOFS);
}
ClearPageChecked(page);
if (PagePrivate(page)) {
ClearPagePrivate(page);
set_page_private(page, 0);
page_cache_release(page);
}
}
/*
* btrfs_page_mkwrite() is not allowed to change the file size as it gets
* called from a page fault handler when a page is first dirtied. Hence we must
* be careful to check for EOF conditions here. We set the page up correctly
* for a written page which means we get ENOSPC checking when writing into
* holes and correct delalloc and unwritten extent mapping on filesystems that
* support these features.
*
* We are not allowed to take the i_mutex here so we have to play games to
* protect against truncate races as the page could now be beyond EOF. Because
* vmtruncate() writes the inode size before removing pages, once we have the
* page lock we can determine safely if the page is beyond EOF. If it is not
* beyond EOF, then the page is guaranteed safe against truncation until we
* unlock the page.
*/
int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
{
struct page *page = vmf->page;
struct inode *inode = file_inode(vma->vm_file);
struct btrfs_root *root = BTRFS_I(inode)->root;
struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
struct btrfs_ordered_extent *ordered;
struct extent_state *cached_state = NULL;
char *kaddr;
unsigned long zero_start;
loff_t size;
int ret;
int reserved = 0;
u64 page_start;
u64 page_end;
sb_start_pagefault(inode->i_sb);
ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
if (!ret) {
ret = file_update_time(vma->vm_file);
reserved = 1;
}
if (ret) {
if (ret == -ENOMEM)
ret = VM_FAULT_OOM;
else /* -ENOSPC, -EIO, etc */
ret = VM_FAULT_SIGBUS;
if (reserved)
goto out;
goto out_noreserve;
}
ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
again:
lock_page(page);
size = i_size_read(inode);
page_start = page_offset(page);
page_end = page_start + PAGE_CACHE_SIZE - 1;
if ((page->mapping != inode->i_mapping) ||
(page_start >= size)) {
/* page got truncated out from underneath us */
goto out_unlock;
}
wait_on_page_writeback(page);
lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
set_page_extent_mapped(page);
/*
* we can't set the delalloc bits if there are pending ordered
* extents. Drop our locks and wait for them to finish
*/
ordered = btrfs_lookup_ordered_extent(inode, page_start);
if (ordered) {
unlock_extent_cached(io_tree, page_start, page_end,
&cached_state, GFP_NOFS);
unlock_page(page);
btrfs_start_ordered_extent(inode, ordered, 1);
btrfs_put_ordered_extent(ordered);
goto again;
}
/*
* XXX - page_mkwrite gets called every time the page is dirtied, even
* if it was already dirty, so for space accounting reasons we need to
* clear any delalloc bits for the range we are fixing to save. There
* is probably a better way to do this, but for now keep consistent with
* prepare_pages in the normal write path.
*/
clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
EXTENT_DIRTY | EXTENT_DELALLOC |
EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
0, 0, &cached_state, GFP_NOFS);
ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
&cached_state);
if (ret) {
unlock_extent_cached(io_tree, page_start, page_end,
&cached_state, GFP_NOFS);
ret = VM_FAULT_SIGBUS;
goto out_unlock;
}
ret = 0;
/* page is wholly or partially inside EOF */
if (page_start + PAGE_CACHE_SIZE > size)
zero_start = size & ~PAGE_CACHE_MASK;
else
zero_start = PAGE_CACHE_SIZE;
if (zero_start != PAGE_CACHE_SIZE) {
kaddr = kmap(page);
memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
flush_dcache_page(page);
kunmap(page);
}
ClearPageChecked(page);
set_page_dirty(page);
SetPageUptodate(page);
BTRFS_I(inode)->last_trans = root->fs_info->generation;
BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
out_unlock:
if (!ret) {
sb_end_pagefault(inode->i_sb);
return VM_FAULT_LOCKED;
}
unlock_page(page);
out:
btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
out_noreserve:
sb_end_pagefault(inode->i_sb);
return ret;
}
static int btrfs_truncate(struct inode *inode)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_block_rsv *rsv;
int ret = 0;
int err = 0;
struct btrfs_trans_handle *trans;
u64 mask = root->sectorsize - 1;
u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
(u64)-1);
if (ret)
return ret;
/*
* Yes ladies and gentelment, this is indeed ugly. The fact is we have
* 3 things going on here
*
* 1) We need to reserve space for our orphan item and the space to
* delete our orphan item. Lord knows we don't want to have a dangling
* orphan item because we didn't reserve space to remove it.
*
* 2) We need to reserve space to update our inode.
*
* 3) We need to have something to cache all the space that is going to
* be free'd up by the truncate operation, but also have some slack
* space reserved in case it uses space during the truncate (thank you
* very much snapshotting).
*
* And we need these to all be seperate. The fact is we can use alot of
* space doing the truncate, and we have no earthly idea how much space
* we will use, so we need the truncate reservation to be seperate so it
* doesn't end up using space reserved for updating the inode or
* removing the orphan item. We also need to be able to stop the
* transaction and start a new one, which means we need to be able to
* update the inode several times, and we have no idea of knowing how
* many times that will be, so we can't just reserve 1 item for the
* entirety of the opration, so that has to be done seperately as well.
* Then there is the orphan item, which does indeed need to be held on
* to for the whole operation, and we need nobody to touch this reserved
* space except the orphan code.
*
* So that leaves us with
*
* 1) root->orphan_block_rsv - for the orphan deletion.
* 2) rsv - for the truncate reservation, which we will steal from the
* transaction reservation.
* 3) fs_info->trans_block_rsv - this will have 1 items worth left for
* updating the inode.
*/
rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
if (!rsv)
return -ENOMEM;
rsv->size = min_size;
rsv->failfast = 1;
/*
* 1 for the truncate slack space
* 1 for updating the inode.
*/
trans = btrfs_start_transaction(root, 2);
if (IS_ERR(trans)) {
err = PTR_ERR(trans);
goto out;
}
/* Migrate the slack space for the truncate to our reserve */
ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
min_size);
BUG_ON(ret);
/*
* setattr is responsible for setting the ordered_data_close flag,
* but that is only tested during the last file release. That
* could happen well after the next commit, leaving a great big
* window where new writes may get lost if someone chooses to write
* to this file after truncating to zero
*
* The inode doesn't have any dirty data here, and so if we commit
* this is a noop. If someone immediately starts writing to the inode
* it is very likely we'll catch some of their writes in this
* transaction, and the commit will find this file on the ordered
* data list with good things to send down.
*
* This is a best effort solution, there is still a window where
* using truncate to replace the contents of the file will
* end up with a zero length file after a crash.
*/
if (inode->i_size == 0 && test_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
&BTRFS_I(inode)->runtime_flags))
btrfs_add_ordered_operation(trans, root, inode);
/*
* So if we truncate and then write and fsync we normally would just
* write the extents that changed, which is a problem if we need to
* first truncate that entire inode. So set this flag so we write out
* all of the extents in the inode to the sync log so we're completely
* safe.
*/
set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
trans->block_rsv = rsv;
while (1) {
ret = btrfs_truncate_inode_items(trans, root, inode,
inode->i_size,
BTRFS_EXTENT_DATA_KEY);
if (ret != -ENOSPC) {
err = ret;
break;
}
trans->block_rsv = &root->fs_info->trans_block_rsv;
ret = btrfs_update_inode(trans, root, inode);
if (ret) {
err = ret;
break;
}
btrfs_end_transaction(trans, root);
btrfs_btree_balance_dirty(root);
trans = btrfs_start_transaction(root, 2);
if (IS_ERR(trans)) {
ret = err = PTR_ERR(trans);
trans = NULL;
break;
}
ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
rsv, min_size);
BUG_ON(ret); /* shouldn't happen */
trans->block_rsv = rsv;
}
if (ret == 0 && inode->i_nlink > 0) {
trans->block_rsv = root->orphan_block_rsv;
ret = btrfs_orphan_del(trans, inode);
if (ret)
err = ret;
}
if (trans) {
trans->block_rsv = &root->fs_info->trans_block_rsv;
ret = btrfs_update_inode(trans, root, inode);
if (ret && !err)
err = ret;
ret = btrfs_end_transaction(trans, root);
btrfs_btree_balance_dirty(root);
}
out:
btrfs_free_block_rsv(root, rsv);
if (ret && !err)
err = ret;
return err;
}
/*
* create a new subvolume directory/inode (helper for the ioctl).
*/
int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
struct btrfs_root *new_root,
struct btrfs_root *parent_root,
u64 new_dirid)
{
struct inode *inode;
int err;
u64 index = 0;
inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
new_dirid, new_dirid,
S_IFDIR | (~current_umask() & S_IRWXUGO),
&index);
if (IS_ERR(inode))
return PTR_ERR(inode);
inode->i_op = &btrfs_dir_inode_operations;
inode->i_fop = &btrfs_dir_file_operations;
set_nlink(inode, 1);
btrfs_i_size_write(inode, 0);
err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
if (err)
btrfs_err(new_root->fs_info,
"error inheriting subvolume %llu properties: %d\n",
new_root->root_key.objectid, err);
err = btrfs_update_inode(trans, new_root, inode);
iput(inode);
return err;
}
struct inode *btrfs_alloc_inode(struct super_block *sb)
{
struct btrfs_inode *ei;
struct inode *inode;
ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
if (!ei)
return NULL;
ei->root = NULL;
ei->generation = 0;
ei->last_trans = 0;
ei->last_sub_trans = 0;
ei->logged_trans = 0;
ei->delalloc_bytes = 0;
ei->disk_i_size = 0;
ei->flags = 0;
ei->csum_bytes = 0;
ei->index_cnt = (u64)-1;
ei->dir_index = 0;
ei->last_unlink_trans = 0;
ei->last_log_commit = 0;
spin_lock_init(&ei->lock);
ei->outstanding_extents = 0;
ei->reserved_extents = 0;
ei->runtime_flags = 0;
ei->force_compress = BTRFS_COMPRESS_NONE;
ei->delayed_node = NULL;
inode = &ei->vfs_inode;
extent_map_tree_init(&ei->extent_tree);
extent_io_tree_init(&ei->io_tree, &inode->i_data);
extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
ei->io_tree.track_uptodate = 1;
ei->io_failure_tree.track_uptodate = 1;
atomic_set(&ei->sync_writers, 0);
mutex_init(&ei->log_mutex);
mutex_init(&ei->delalloc_mutex);
btrfs_ordered_inode_tree_init(&ei->ordered_tree);
INIT_LIST_HEAD(&ei->delalloc_inodes);
INIT_LIST_HEAD(&ei->ordered_operations);
RB_CLEAR_NODE(&ei->rb_node);
return inode;
}
#ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
void btrfs_test_destroy_inode(struct inode *inode)
{
btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
}
#endif
static void btrfs_i_callback(struct rcu_head *head)
{
struct inode *inode = container_of(head, struct inode, i_rcu);
kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
}
void btrfs_destroy_inode(struct inode *inode)
{
struct btrfs_ordered_extent *ordered;
struct btrfs_root *root = BTRFS_I(inode)->root;
WARN_ON(!hlist_empty(&inode->i_dentry));
WARN_ON(inode->i_data.nrpages);
WARN_ON(BTRFS_I(inode)->outstanding_extents);
WARN_ON(BTRFS_I(inode)->reserved_extents);
WARN_ON(BTRFS_I(inode)->delalloc_bytes);
WARN_ON(BTRFS_I(inode)->csum_bytes);
/*
* This can happen where we create an inode, but somebody else also
* created the same inode and we need to destroy the one we already
* created.
*/
if (!root)
goto free;
/*
* Make sure we're properly removed from the ordered operation
* lists.
*/
smp_mb();
if (!list_empty(&BTRFS_I(inode)->ordered_operations)) {
spin_lock(&root->fs_info->ordered_root_lock);
list_del_init(&BTRFS_I(inode)->ordered_operations);
spin_unlock(&root->fs_info->ordered_root_lock);
}
if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
&BTRFS_I(inode)->runtime_flags)) {
btrfs_info(root->fs_info, "inode %llu still on the orphan list",
btrfs_ino(inode));
atomic_dec(&root->orphan_inodes);
}
while (1) {
ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
if (!ordered)
break;
else {
btrfs_err(root->fs_info, "found ordered extent %llu %llu on inode cleanup",
ordered->file_offset, ordered->len);
btrfs_remove_ordered_extent(inode, ordered);
btrfs_put_ordered_extent(ordered);
btrfs_put_ordered_extent(ordered);
}
}
inode_tree_del(inode);
btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
free:
call_rcu(&inode->i_rcu, btrfs_i_callback);
}
int btrfs_drop_inode(struct inode *inode)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
if (root == NULL)
return 1;
/* the snap/subvol tree is on deleting */
if (btrfs_root_refs(&root->root_item) == 0)
return 1;
else
return generic_drop_inode(inode);
}
static void init_once(void *foo)
{
struct btrfs_inode *ei = (struct btrfs_inode *) foo;
inode_init_once(&ei->vfs_inode);
}
void btrfs_destroy_cachep(void)
{
/*
* Make sure all delayed rcu free inodes are flushed before we
* destroy cache.
*/
rcu_barrier();
if (btrfs_inode_cachep)
kmem_cache_destroy(btrfs_inode_cachep);
if (btrfs_trans_handle_cachep)
kmem_cache_destroy(btrfs_trans_handle_cachep);
if (btrfs_transaction_cachep)
kmem_cache_destroy(btrfs_transaction_cachep);
if (btrfs_path_cachep)
kmem_cache_destroy(btrfs_path_cachep);
if (btrfs_free_space_cachep)
kmem_cache_destroy(btrfs_free_space_cachep);
if (btrfs_delalloc_work_cachep)
kmem_cache_destroy(btrfs_delalloc_work_cachep);
}
int btrfs_init_cachep(void)
{
btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
sizeof(struct btrfs_inode), 0,
SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
if (!btrfs_inode_cachep)
goto fail;
btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
sizeof(struct btrfs_trans_handle), 0,
SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
if (!btrfs_trans_handle_cachep)
goto fail;
btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction",
sizeof(struct btrfs_transaction), 0,
SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
if (!btrfs_transaction_cachep)
goto fail;
btrfs_path_cachep = kmem_cache_create("btrfs_path",
sizeof(struct btrfs_path), 0,
SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
if (!btrfs_path_cachep)
goto fail;
btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
sizeof(struct btrfs_free_space), 0,
SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
if (!btrfs_free_space_cachep)
goto fail;
btrfs_delalloc_work_cachep = kmem_cache_create("btrfs_delalloc_work",
sizeof(struct btrfs_delalloc_work), 0,
SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
NULL);
if (!btrfs_delalloc_work_cachep)
goto fail;
return 0;
fail:
btrfs_destroy_cachep();
return -ENOMEM;
}
static int btrfs_getattr(struct vfsmount *mnt,
struct dentry *dentry, struct kstat *stat)
{
u64 delalloc_bytes;
struct inode *inode = dentry->d_inode;
u32 blocksize = inode->i_sb->s_blocksize;
generic_fillattr(inode, stat);
stat->dev = BTRFS_I(inode)->root->anon_dev;
stat->blksize = PAGE_CACHE_SIZE;
spin_lock(&BTRFS_I(inode)->lock);
delalloc_bytes = BTRFS_I(inode)->delalloc_bytes;
spin_unlock(&BTRFS_I(inode)->lock);
stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
ALIGN(delalloc_bytes, blocksize)) >> 9;
return 0;
}
static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry)
{
struct btrfs_trans_handle *trans;
struct btrfs_root *root = BTRFS_I(old_dir)->root;
struct btrfs_root *dest = BTRFS_I(new_dir)->root;
struct inode *new_inode = new_dentry->d_inode;
struct inode *old_inode = old_dentry->d_inode;
struct timespec ctime = CURRENT_TIME;
u64 index = 0;
u64 root_objectid;
int ret;
u64 old_ino = btrfs_ino(old_inode);
if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
return -EPERM;
/* we only allow rename subvolume link between subvolumes */
if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
return -EXDEV;
if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
(new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
return -ENOTEMPTY;
if (S_ISDIR(old_inode->i_mode) && new_inode &&
new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
return -ENOTEMPTY;
/* check for collisions, even if the name isn't there */
ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
new_dentry->d_name.name,
new_dentry->d_name.len);
if (ret) {
if (ret == -EEXIST) {
/* we shouldn't get
* eexist without a new_inode */
if (WARN_ON(!new_inode)) {
return ret;
}
} else {
/* maybe -EOVERFLOW */
return ret;
}
}
ret = 0;
/*
* we're using rename to replace one file with another.
* and the replacement file is large. Start IO on it now so
* we don't add too much work to the end of the transaction
*/
if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
filemap_flush(old_inode->i_mapping);
/* close the racy window with snapshot create/destroy ioctl */
if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
down_read(&root->fs_info->subvol_sem);
/*
* We want to reserve the absolute worst case amount of items. So if
* both inodes are subvols and we need to unlink them then that would
* require 4 item modifications, but if they are both normal inodes it
* would require 5 item modifications, so we'll assume their normal
* inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
* should cover the worst case number of items we'll modify.
*/
trans = btrfs_start_transaction(root, 11);
if (IS_ERR(trans)) {
ret = PTR_ERR(trans);
goto out_notrans;
}
if (dest != root)
btrfs_record_root_in_trans(trans, dest);
ret = btrfs_set_inode_index(new_dir, &index);
if (ret)
goto out_fail;
BTRFS_I(old_inode)->dir_index = 0ULL;
if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
/* force full log commit if subvolume involved. */
root->fs_info->last_trans_log_full_commit = trans->transid;
} else {
ret = btrfs_insert_inode_ref(trans, dest,
new_dentry->d_name.name,
new_dentry->d_name.len,
old_ino,
btrfs_ino(new_dir), index);
if (ret)
goto out_fail;
/*
* this is an ugly little race, but the rename is required
* to make sure that if we crash, the inode is either at the
* old name or the new one. pinning the log transaction lets
* us make sure we don't allow a log commit to come in after
* we unlink the name but before we add the new name back in.
*/
btrfs_pin_log_trans(root);
}
/*
* make sure the inode gets flushed if it is replacing
* something.
*/
if (new_inode && new_inode->i_size && S_ISREG(old_inode->i_mode))
btrfs_add_ordered_operation(trans, root, old_inode);
inode_inc_iversion(old_dir);
inode_inc_iversion(new_dir);
inode_inc_iversion(old_inode);
old_dir->i_ctime = old_dir->i_mtime = ctime;
new_dir->i_ctime = new_dir->i_mtime = ctime;
old_inode->i_ctime = ctime;
if (old_dentry->d_parent != new_dentry->d_parent)
btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
old_dentry->d_name.name,
old_dentry->d_name.len);
} else {
ret = __btrfs_unlink_inode(trans, root, old_dir,
old_dentry->d_inode,
old_dentry->d_name.name,
old_dentry->d_name.len);
if (!ret)
ret = btrfs_update_inode(trans, root, old_inode);
}
if (ret) {
btrfs_abort_transaction(trans, root, ret);
goto out_fail;
}
if (new_inode) {
inode_inc_iversion(new_inode);
new_inode->i_ctime = CURRENT_TIME;
if (unlikely(btrfs_ino(new_inode) ==
BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
root_objectid = BTRFS_I(new_inode)->location.objectid;
ret = btrfs_unlink_subvol(trans, dest, new_dir,
root_objectid,
new_dentry->d_name.name,
new_dentry->d_name.len);
BUG_ON(new_inode->i_nlink == 0);
} else {
ret = btrfs_unlink_inode(trans, dest, new_dir,
new_dentry->d_inode,
new_dentry->d_name.name,
new_dentry->d_name.len);
}
if (!ret && new_inode->i_nlink == 0)
ret = btrfs_orphan_add(trans, new_dentry->d_inode);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
goto out_fail;
}
}
ret = btrfs_add_link(trans, new_dir, old_inode,
new_dentry->d_name.name,
new_dentry->d_name.len, 0, index);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
goto out_fail;
}
if (old_inode->i_nlink == 1)
BTRFS_I(old_inode)->dir_index = index;
if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
struct dentry *parent = new_dentry->d_parent;
btrfs_log_new_name(trans, old_inode, old_dir, parent);
btrfs_end_log_trans(root);
}
out_fail:
btrfs_end_transaction(trans, root);
out_notrans:
if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
up_read(&root->fs_info->subvol_sem);
return ret;
}
static void btrfs_run_delalloc_work(struct btrfs_work *work)
{
struct btrfs_delalloc_work *delalloc_work;
struct inode *inode;
delalloc_work = container_of(work, struct btrfs_delalloc_work,
work);
inode = delalloc_work->inode;
if (delalloc_work->wait) {
btrfs_wait_ordered_range(inode, 0, (u64)-1);
} else {
filemap_flush(inode->i_mapping);
if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
&BTRFS_I(inode)->runtime_flags))
filemap_flush(inode->i_mapping);
}
if (delalloc_work->delay_iput)
btrfs_add_delayed_iput(inode);
else
iput(inode);
complete(&delalloc_work->completion);
}
struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
int wait, int delay_iput)
{
struct btrfs_delalloc_work *work;
work = kmem_cache_zalloc(btrfs_delalloc_work_cachep, GFP_NOFS);
if (!work)
return NULL;
init_completion(&work->completion);
INIT_LIST_HEAD(&work->list);
work->inode = inode;
work->wait = wait;
work->delay_iput = delay_iput;
work->work.func = btrfs_run_delalloc_work;
return work;
}
void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
{
wait_for_completion(&work->completion);
kmem_cache_free(btrfs_delalloc_work_cachep, work);
}
/*
* some fairly slow code that needs optimization. This walks the list
* of all the inodes with pending delalloc and forces them to disk.
*/
static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
{
struct btrfs_inode *binode;
struct inode *inode;
struct btrfs_delalloc_work *work, *next;
struct list_head works;
struct list_head splice;
int ret = 0;
INIT_LIST_HEAD(&works);
INIT_LIST_HEAD(&splice);
spin_lock(&root->delalloc_lock);
list_splice_init(&root->delalloc_inodes, &splice);
while (!list_empty(&splice)) {
binode = list_entry(splice.next, struct btrfs_inode,
delalloc_inodes);
list_move_tail(&binode->delalloc_inodes,
&root->delalloc_inodes);
inode = igrab(&binode->vfs_inode);
if (!inode) {
cond_resched_lock(&root->delalloc_lock);
continue;
}
spin_unlock(&root->delalloc_lock);
work = btrfs_alloc_delalloc_work(inode, 0, delay_iput);
if (unlikely(!work)) {
if (delay_iput)
btrfs_add_delayed_iput(inode);
else
iput(inode);
ret = -ENOMEM;
goto out;
}
list_add_tail(&work->list, &works);
btrfs_queue_worker(&root->fs_info->flush_workers,
&work->work);
cond_resched();
spin_lock(&root->delalloc_lock);
}
spin_unlock(&root->delalloc_lock);
list_for_each_entry_safe(work, next, &works, list) {
list_del_init(&work->list);
btrfs_wait_and_free_delalloc_work(work);
}
return 0;
out:
list_for_each_entry_safe(work, next, &works, list) {
list_del_init(&work->list);
btrfs_wait_and_free_delalloc_work(work);
}
if (!list_empty_careful(&splice)) {
spin_lock(&root->delalloc_lock);
list_splice_tail(&splice, &root->delalloc_inodes);
spin_unlock(&root->delalloc_lock);
}
return ret;
}
int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
{
int ret;
if (test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state))
return -EROFS;
ret = __start_delalloc_inodes(root, delay_iput);
/*
* the filemap_flush will queue IO into the worker threads, but
* we have to make sure the IO is actually started and that
* ordered extents get created before we return
*/
atomic_inc(&root->fs_info->async_submit_draining);
while (atomic_read(&root->fs_info->nr_async_submits) ||
atomic_read(&root->fs_info->async_delalloc_pages)) {
wait_event(root->fs_info->async_submit_wait,
(atomic_read(&root->fs_info->nr_async_submits) == 0 &&
atomic_read(&root->fs_info->async_delalloc_pages) == 0));
}
atomic_dec(&root->fs_info->async_submit_draining);
return ret;
}
int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int delay_iput)
{
struct btrfs_root *root;
struct list_head splice;
int ret;
if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
return -EROFS;
INIT_LIST_HEAD(&splice);
spin_lock(&fs_info->delalloc_root_lock);
list_splice_init(&fs_info->delalloc_roots, &splice);
while (!list_empty(&splice)) {
root = list_first_entry(&splice, struct btrfs_root,
delalloc_root);
root = btrfs_grab_fs_root(root);
BUG_ON(!root);
list_move_tail(&root->delalloc_root,
&fs_info->delalloc_roots);
spin_unlock(&fs_info->delalloc_root_lock);
ret = __start_delalloc_inodes(root, delay_iput);
btrfs_put_fs_root(root);
if (ret)
goto out;
spin_lock(&fs_info->delalloc_root_lock);
}
spin_unlock(&fs_info->delalloc_root_lock);
atomic_inc(&fs_info->async_submit_draining);
while (atomic_read(&fs_info->nr_async_submits) ||
atomic_read(&fs_info->async_delalloc_pages)) {
wait_event(fs_info->async_submit_wait,
(atomic_read(&fs_info->nr_async_submits) == 0 &&
atomic_read(&fs_info->async_delalloc_pages) == 0));
}
atomic_dec(&fs_info->async_submit_draining);
return 0;
out:
if (!list_empty_careful(&splice)) {
spin_lock(&fs_info->delalloc_root_lock);
list_splice_tail(&splice, &fs_info->delalloc_roots);
spin_unlock(&fs_info->delalloc_root_lock);
}
return ret;
}
static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
const char *symname)
{
struct btrfs_trans_handle *trans;
struct btrfs_root *root = BTRFS_I(dir)->root;
struct btrfs_path *path;
struct btrfs_key key;
struct inode *inode = NULL;
int err;
int drop_inode = 0;
u64 objectid;
u64 index = 0;
int name_len;
int datasize;
unsigned long ptr;
struct btrfs_file_extent_item *ei;
struct extent_buffer *leaf;
name_len = strlen(symname);
if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
return -ENAMETOOLONG;
/*
* 2 items for inode item and ref
* 2 items for dir items
* 1 item for xattr if selinux is on
*/
trans = btrfs_start_transaction(root, 5);
if (IS_ERR(trans))
return PTR_ERR(trans);
err = btrfs_find_free_ino(root, &objectid);
if (err)
goto out_unlock;
inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
dentry->d_name.len, btrfs_ino(dir), objectid,
S_IFLNK|S_IRWXUGO, &index);
if (IS_ERR(inode)) {
err = PTR_ERR(inode);
goto out_unlock;
}
err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
if (err) {
drop_inode = 1;
goto out_unlock;
}
/*
* If the active LSM wants to access the inode during
* d_instantiate it needs these. Smack checks to see
* if the filesystem supports xattrs by looking at the
* ops vector.
*/
inode->i_fop = &btrfs_file_operations;
inode->i_op = &btrfs_file_inode_operations;
err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
if (err)
drop_inode = 1;
else {
inode->i_mapping->a_ops = &btrfs_aops;
inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
}
if (drop_inode)
goto out_unlock;
path = btrfs_alloc_path();
if (!path) {
err = -ENOMEM;
drop_inode = 1;
goto out_unlock;
}
key.objectid = btrfs_ino(inode);
key.offset = 0;
btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
datasize = btrfs_file_extent_calc_inline_size(name_len);
err = btrfs_insert_empty_item(trans, root, path, &key,
datasize);
if (err) {
drop_inode = 1;
btrfs_free_path(path);
goto out_unlock;
}
leaf = path->nodes[0];
ei = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_file_extent_item);
btrfs_set_file_extent_generation(leaf, ei, trans->transid);
btrfs_set_file_extent_type(leaf, ei,
BTRFS_FILE_EXTENT_INLINE);
btrfs_set_file_extent_encryption(leaf, ei, 0);
btrfs_set_file_extent_compression(leaf, ei, 0);
btrfs_set_file_extent_other_encoding(leaf, ei, 0);
btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
ptr = btrfs_file_extent_inline_start(ei);
write_extent_buffer(leaf, symname, ptr, name_len);
btrfs_mark_buffer_dirty(leaf);
btrfs_free_path(path);
inode->i_op = &btrfs_symlink_inode_operations;
inode->i_mapping->a_ops = &btrfs_symlink_aops;
inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
inode_set_bytes(inode, name_len);
btrfs_i_size_write(inode, name_len);
err = btrfs_update_inode(trans, root, inode);
if (err)
drop_inode = 1;
out_unlock:
if (!err)
d_instantiate(dentry, inode);
btrfs_end_transaction(trans, root);
if (drop_inode) {
inode_dec_link_count(inode);
iput(inode);
}
btrfs_btree_balance_dirty(root);
return err;
}
static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
u64 start, u64 num_bytes, u64 min_size,
loff_t actual_len, u64 *alloc_hint,
struct btrfs_trans_handle *trans)
{
struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
struct extent_map *em;
struct btrfs_root *root = BTRFS_I(inode)->root;
struct btrfs_key ins;
u64 cur_offset = start;
u64 i_size;
u64 cur_bytes;
int ret = 0;
bool own_trans = true;
if (trans)
own_trans = false;
while (num_bytes > 0) {
if (own_trans) {
trans = btrfs_start_transaction(root, 3);
if (IS_ERR(trans)) {
ret = PTR_ERR(trans);
break;
}
}
cur_bytes = min(num_bytes, 256ULL * 1024 * 1024);
cur_bytes = max(cur_bytes, min_size);
ret = btrfs_reserve_extent(root, cur_bytes, min_size, 0,
*alloc_hint, &ins, 1);
if (ret) {
if (own_trans)
btrfs_end_transaction(trans, root);
break;
}
ret = insert_reserved_file_extent(trans, inode,
cur_offset, ins.objectid,
ins.offset, ins.offset,
ins.offset, 0, 0, 0,
BTRFS_FILE_EXTENT_PREALLOC);
if (ret) {
btrfs_free_reserved_extent(root, ins.objectid,
ins.offset);
btrfs_abort_transaction(trans, root, ret);
if (own_trans)
btrfs_end_transaction(trans, root);
break;
}
btrfs_drop_extent_cache(inode, cur_offset,
cur_offset + ins.offset -1, 0);
em = alloc_extent_map();
if (!em) {
set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
&BTRFS_I(inode)->runtime_flags);
goto next;
}
em->start = cur_offset;
em->orig_start = cur_offset;
em->len = ins.offset;
em->block_start = ins.objectid;
em->block_len = ins.offset;
em->orig_block_len = ins.offset;
em->ram_bytes = ins.offset;
em->bdev = root->fs_info->fs_devices->latest_bdev;
set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
em->generation = trans->transid;
while (1) {
write_lock(&em_tree->lock);
ret = add_extent_mapping(em_tree, em, 1);
write_unlock(&em_tree->lock);
if (ret != -EEXIST)
break;
btrfs_drop_extent_cache(inode, cur_offset,
cur_offset + ins.offset - 1,
0);
}
free_extent_map(em);
next:
num_bytes -= ins.offset;
cur_offset += ins.offset;
*alloc_hint = ins.objectid + ins.offset;
inode_inc_iversion(inode);
inode->i_ctime = CURRENT_TIME;
BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
if (!(mode & FALLOC_FL_KEEP_SIZE) &&
(actual_len > inode->i_size) &&
(cur_offset > inode->i_size)) {
if (cur_offset > actual_len)
i_size = actual_len;
else
i_size = cur_offset;
i_size_write(inode, i_size);
btrfs_ordered_update_i_size(inode, i_size, NULL);
}
ret = btrfs_update_inode(trans, root, inode);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
if (own_trans)
btrfs_end_transaction(trans, root);
break;
}
if (own_trans)
btrfs_end_transaction(trans, root);
}
return ret;
}
int btrfs_prealloc_file_range(struct inode *inode, int mode,
u64 start, u64 num_bytes, u64 min_size,
loff_t actual_len, u64 *alloc_hint)
{
return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
min_size, actual_len, alloc_hint,
NULL);
}
int btrfs_prealloc_file_range_trans(struct inode *inode,
struct btrfs_trans_handle *trans, int mode,
u64 start, u64 num_bytes, u64 min_size,
loff_t actual_len, u64 *alloc_hint)
{
return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
min_size, actual_len, alloc_hint, trans);
}
static int btrfs_set_page_dirty(struct page *page)
{
return __set_page_dirty_nobuffers(page);
}
static int btrfs_permission(struct inode *inode, int mask)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
umode_t mode = inode->i_mode;
if (mask & MAY_WRITE &&
(S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
if (btrfs_root_readonly(root))
return -EROFS;
if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
return -EACCES;
}
return generic_permission(inode, mask);
}
static const struct inode_operations btrfs_dir_inode_operations = {
.getattr = btrfs_getattr,
.lookup = btrfs_lookup,
.create = btrfs_create,
.unlink = btrfs_unlink,
.link = btrfs_link,
.mkdir = btrfs_mkdir,
.rmdir = btrfs_rmdir,
.rename = btrfs_rename,
.symlink = btrfs_symlink,
.setattr = btrfs_setattr,
.mknod = btrfs_mknod,
.setxattr = btrfs_setxattr,
.getxattr = btrfs_getxattr,
.listxattr = btrfs_listxattr,
.removexattr = btrfs_removexattr,
.permission = btrfs_permission,
.get_acl = btrfs_get_acl,
.set_acl = btrfs_set_acl,
.update_time = btrfs_update_time,
};
static const struct inode_operations btrfs_dir_ro_inode_operations = {
.lookup = btrfs_lookup,
.permission = btrfs_permission,
.get_acl = btrfs_get_acl,
.set_acl = btrfs_set_acl,
.update_time = btrfs_update_time,
};
static const struct file_operations btrfs_dir_file_operations = {
.llseek = generic_file_llseek,
.read = generic_read_dir,
.iterate = btrfs_real_readdir,
.unlocked_ioctl = btrfs_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = btrfs_ioctl,
#endif
.release = btrfs_release_file,
.fsync = btrfs_sync_file,
};
static struct extent_io_ops btrfs_extent_io_ops = {
.fill_delalloc = run_delalloc_range,
.submit_bio_hook = btrfs_submit_bio_hook,
.merge_bio_hook = btrfs_merge_bio_hook,
.readpage_end_io_hook = btrfs_readpage_end_io_hook,
.writepage_end_io_hook = btrfs_writepage_end_io_hook,
.writepage_start_hook = btrfs_writepage_start_hook,
.set_bit_hook = btrfs_set_bit_hook,
.clear_bit_hook = btrfs_clear_bit_hook,
.merge_extent_hook = btrfs_merge_extent_hook,
.split_extent_hook = btrfs_split_extent_hook,
};
/*
* btrfs doesn't support the bmap operation because swapfiles
* use bmap to make a mapping of extents in the file. They assume
* these extents won't change over the life of the file and they
* use the bmap result to do IO directly to the drive.
*
* the btrfs bmap call would return logical addresses that aren't
* suitable for IO and they also will change frequently as COW
* operations happen. So, swapfile + btrfs == corruption.
*
* For now we're avoiding this by dropping bmap.
*/
static const struct address_space_operations btrfs_aops = {
.readpage = btrfs_readpage,
.writepage = btrfs_writepage,
.writepages = btrfs_writepages,
.readpages = btrfs_readpages,
.direct_IO = btrfs_direct_IO,
.invalidatepage = btrfs_invalidatepage,
.releasepage = btrfs_releasepage,
.set_page_dirty = btrfs_set_page_dirty,
.error_remove_page = generic_error_remove_page,
};
static const struct address_space_operations btrfs_symlink_aops = {
.readpage = btrfs_readpage,
.writepage = btrfs_writepage,
.invalidatepage = btrfs_invalidatepage,
.releasepage = btrfs_releasepage,
};
static const struct inode_operations btrfs_file_inode_operations = {
.getattr = btrfs_getattr,
.setattr = btrfs_setattr,
.setxattr = btrfs_setxattr,
.getxattr = btrfs_getxattr,
.listxattr = btrfs_listxattr,
.removexattr = btrfs_removexattr,
.permission = btrfs_permission,
.fiemap = btrfs_fiemap,
.get_acl = btrfs_get_acl,
.set_acl = btrfs_set_acl,
.update_time = btrfs_update_time,
};
static const struct inode_operations btrfs_special_inode_operations = {
.getattr = btrfs_getattr,
.setattr = btrfs_setattr,
.permission = btrfs_permission,
.setxattr = btrfs_setxattr,
.getxattr = btrfs_getxattr,
.listxattr = btrfs_listxattr,
.removexattr = btrfs_removexattr,
.get_acl = btrfs_get_acl,
.set_acl = btrfs_set_acl,
.update_time = btrfs_update_time,
};
static const struct inode_operations btrfs_symlink_inode_operations = {
.readlink = generic_readlink,
.follow_link = page_follow_link_light,
.put_link = page_put_link,
.getattr = btrfs_getattr,
.setattr = btrfs_setattr,
.permission = btrfs_permission,
.setxattr = btrfs_setxattr,
.getxattr = btrfs_getxattr,
.listxattr = btrfs_listxattr,
.removexattr = btrfs_removexattr,
.update_time = btrfs_update_time,
};
const struct dentry_operations btrfs_dentry_operations = {
.d_delete = btrfs_dentry_delete,
.d_release = btrfs_dentry_release,
};
| gpl-2.0 |
Swordsman-Inaction/FFMpeg-Android-Command | FFMpeg-x264-Android/ffmpeg/libavcodec/ppc/lossless_audiodsp_altivec.c | 67 | 2819 | /*
* Copyright (c) 2007 Luca Barbato <lu_zero@gentoo.org>
*
* This file is part of FFmpeg.
*
* FFmpeg 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.
*
* FFmpeg 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 FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "config.h"
#if HAVE_ALTIVEC_H
#include <altivec.h>
#endif
#include "libavutil/attributes.h"
#include "libavutil/cpu.h"
#include "libavutil/ppc/cpu.h"
#include "libavutil/ppc/types_altivec.h"
#include "libavcodec/lossless_audiodsp.h"
#if HAVE_BIGENDIAN
#define GET_T(tt0,tt1,src,a,b){ \
a = vec_ld(16, src); \
tt0 = vec_perm(b, a, align); \
b = vec_ld(32, src); \
tt1 = vec_perm(a, b, align); \
}
#else
#define GET_T(tt0,tt1,src,a,b){ \
tt0 = vec_vsx_ld(0, src); \
tt1 = vec_vsx_ld(16, src); \
}
#endif
#if HAVE_ALTIVEC
static int32_t scalarproduct_and_madd_int16_altivec(int16_t *v1,
const int16_t *v2,
const int16_t *v3,
int order, int mul)
{
LOAD_ZERO;
vec_s16 *pv1 = (vec_s16 *) v1;
register vec_s16 muls = { mul, mul, mul, mul, mul, mul, mul, mul };
register vec_s16 t0, t1, i0, i1, i4, i2, i3;
register vec_s32 res = zero_s32v;
#if HAVE_BIGENDIAN
register vec_u8 align = vec_lvsl(0, v2);
i2 = vec_ld(0, v2);
i3 = vec_ld(0, v3);
#endif
int32_t ires;
order >>= 4;
do {
GET_T(t0,t1,v2,i1,i2);
i0 = pv1[0];
i1 = pv1[1];
res = vec_msum(t0, i0, res);
res = vec_msum(t1, i1, res);
GET_T(t0,t1,v3,i4,i3);
pv1[0] = vec_mladd(t0, muls, i0);
pv1[1] = vec_mladd(t1, muls, i1);
pv1 += 2;
v2 += 16;
v3 += 16;
} while (--order);
res = vec_splat(vec_sums(res, zero_s32v), 3);
vec_ste(res, 0, &ires);
return ires;
}
#endif /* HAVE_ALTIVEC */
av_cold void ff_llauddsp_init_ppc(LLAudDSPContext *c)
{
#if HAVE_ALTIVEC
if (!PPC_ALTIVEC(av_get_cpu_flags()))
return;
c->scalarproduct_and_madd_int16 = scalarproduct_and_madd_int16_altivec;
#endif /* HAVE_ALTIVEC */
}
| gpl-2.0 |
DayBreakZhang/Tesseract_Ocr | source/Tesseract3.02/leptonica/src/fmorphgenlow.1.c | 67 | 207030 | /*====================================================================*
- Copyright (C) 2001 Leptonica. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions
- are met:
- 1. Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
- 2. Redistributions in binary form must reproduce the above
- copyright notice, this list of conditions and the following
- disclaimer in the documentation and/or other materials
- provided with the distribution.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ANY
- CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*====================================================================*/
/*!
* Low-level fast binary morphology with auto-generated sels
*
* Dispatcher:
* l_int32 fmorphopgen_low_1()
*
* Static Low-level:
* void fdilate_1_*()
* void ferode_1_*()
*/
#include "allheaders.h"
static void fdilate_1_0(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_0(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_1(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_1(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_2(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_2(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_3(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_3(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_4(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_4(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_5(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_5(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_6(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_6(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_7(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_7(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_8(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_8(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_9(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_9(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_10(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_10(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_11(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_11(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_12(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_12(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_13(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_13(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_14(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_14(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_15(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_15(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_16(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_16(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_17(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_17(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_18(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_18(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_19(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_19(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_20(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_20(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_21(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_21(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_22(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_22(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_23(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_23(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_24(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_24(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_25(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_25(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_26(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_26(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_27(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_27(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_28(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_28(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_29(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_29(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_30(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_30(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_31(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_31(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_32(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_32(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_33(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_33(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_34(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_34(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_35(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_35(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_36(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_36(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_37(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_37(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_38(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_38(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_39(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_39(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_40(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_40(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_41(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_41(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_42(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_42(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_43(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_43(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_44(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_44(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_45(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_45(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_46(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_46(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_47(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_47(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_48(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_48(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_49(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_49(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_50(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_50(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_51(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_51(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_52(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_52(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_53(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_53(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_54(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_54(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_55(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_55(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_56(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_56(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void fdilate_1_57(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
static void ferode_1_57(l_uint32 *, l_int32, l_int32, l_int32, l_uint32 *, l_int32);
/*---------------------------------------------------------------------*
* Fast morph dispatcher *
*---------------------------------------------------------------------*/
/*!
* fmorphopgen_low_1()
*
* a dispatcher to appropriate low-level code
*/
l_int32
fmorphopgen_low_1(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls,
l_int32 index)
{
switch (index)
{
case 0:
fdilate_1_0(datad, w, h, wpld, datas, wpls);
break;
case 1:
ferode_1_0(datad, w, h, wpld, datas, wpls);
break;
case 2:
fdilate_1_1(datad, w, h, wpld, datas, wpls);
break;
case 3:
ferode_1_1(datad, w, h, wpld, datas, wpls);
break;
case 4:
fdilate_1_2(datad, w, h, wpld, datas, wpls);
break;
case 5:
ferode_1_2(datad, w, h, wpld, datas, wpls);
break;
case 6:
fdilate_1_3(datad, w, h, wpld, datas, wpls);
break;
case 7:
ferode_1_3(datad, w, h, wpld, datas, wpls);
break;
case 8:
fdilate_1_4(datad, w, h, wpld, datas, wpls);
break;
case 9:
ferode_1_4(datad, w, h, wpld, datas, wpls);
break;
case 10:
fdilate_1_5(datad, w, h, wpld, datas, wpls);
break;
case 11:
ferode_1_5(datad, w, h, wpld, datas, wpls);
break;
case 12:
fdilate_1_6(datad, w, h, wpld, datas, wpls);
break;
case 13:
ferode_1_6(datad, w, h, wpld, datas, wpls);
break;
case 14:
fdilate_1_7(datad, w, h, wpld, datas, wpls);
break;
case 15:
ferode_1_7(datad, w, h, wpld, datas, wpls);
break;
case 16:
fdilate_1_8(datad, w, h, wpld, datas, wpls);
break;
case 17:
ferode_1_8(datad, w, h, wpld, datas, wpls);
break;
case 18:
fdilate_1_9(datad, w, h, wpld, datas, wpls);
break;
case 19:
ferode_1_9(datad, w, h, wpld, datas, wpls);
break;
case 20:
fdilate_1_10(datad, w, h, wpld, datas, wpls);
break;
case 21:
ferode_1_10(datad, w, h, wpld, datas, wpls);
break;
case 22:
fdilate_1_11(datad, w, h, wpld, datas, wpls);
break;
case 23:
ferode_1_11(datad, w, h, wpld, datas, wpls);
break;
case 24:
fdilate_1_12(datad, w, h, wpld, datas, wpls);
break;
case 25:
ferode_1_12(datad, w, h, wpld, datas, wpls);
break;
case 26:
fdilate_1_13(datad, w, h, wpld, datas, wpls);
break;
case 27:
ferode_1_13(datad, w, h, wpld, datas, wpls);
break;
case 28:
fdilate_1_14(datad, w, h, wpld, datas, wpls);
break;
case 29:
ferode_1_14(datad, w, h, wpld, datas, wpls);
break;
case 30:
fdilate_1_15(datad, w, h, wpld, datas, wpls);
break;
case 31:
ferode_1_15(datad, w, h, wpld, datas, wpls);
break;
case 32:
fdilate_1_16(datad, w, h, wpld, datas, wpls);
break;
case 33:
ferode_1_16(datad, w, h, wpld, datas, wpls);
break;
case 34:
fdilate_1_17(datad, w, h, wpld, datas, wpls);
break;
case 35:
ferode_1_17(datad, w, h, wpld, datas, wpls);
break;
case 36:
fdilate_1_18(datad, w, h, wpld, datas, wpls);
break;
case 37:
ferode_1_18(datad, w, h, wpld, datas, wpls);
break;
case 38:
fdilate_1_19(datad, w, h, wpld, datas, wpls);
break;
case 39:
ferode_1_19(datad, w, h, wpld, datas, wpls);
break;
case 40:
fdilate_1_20(datad, w, h, wpld, datas, wpls);
break;
case 41:
ferode_1_20(datad, w, h, wpld, datas, wpls);
break;
case 42:
fdilate_1_21(datad, w, h, wpld, datas, wpls);
break;
case 43:
ferode_1_21(datad, w, h, wpld, datas, wpls);
break;
case 44:
fdilate_1_22(datad, w, h, wpld, datas, wpls);
break;
case 45:
ferode_1_22(datad, w, h, wpld, datas, wpls);
break;
case 46:
fdilate_1_23(datad, w, h, wpld, datas, wpls);
break;
case 47:
ferode_1_23(datad, w, h, wpld, datas, wpls);
break;
case 48:
fdilate_1_24(datad, w, h, wpld, datas, wpls);
break;
case 49:
ferode_1_24(datad, w, h, wpld, datas, wpls);
break;
case 50:
fdilate_1_25(datad, w, h, wpld, datas, wpls);
break;
case 51:
ferode_1_25(datad, w, h, wpld, datas, wpls);
break;
case 52:
fdilate_1_26(datad, w, h, wpld, datas, wpls);
break;
case 53:
ferode_1_26(datad, w, h, wpld, datas, wpls);
break;
case 54:
fdilate_1_27(datad, w, h, wpld, datas, wpls);
break;
case 55:
ferode_1_27(datad, w, h, wpld, datas, wpls);
break;
case 56:
fdilate_1_28(datad, w, h, wpld, datas, wpls);
break;
case 57:
ferode_1_28(datad, w, h, wpld, datas, wpls);
break;
case 58:
fdilate_1_29(datad, w, h, wpld, datas, wpls);
break;
case 59:
ferode_1_29(datad, w, h, wpld, datas, wpls);
break;
case 60:
fdilate_1_30(datad, w, h, wpld, datas, wpls);
break;
case 61:
ferode_1_30(datad, w, h, wpld, datas, wpls);
break;
case 62:
fdilate_1_31(datad, w, h, wpld, datas, wpls);
break;
case 63:
ferode_1_31(datad, w, h, wpld, datas, wpls);
break;
case 64:
fdilate_1_32(datad, w, h, wpld, datas, wpls);
break;
case 65:
ferode_1_32(datad, w, h, wpld, datas, wpls);
break;
case 66:
fdilate_1_33(datad, w, h, wpld, datas, wpls);
break;
case 67:
ferode_1_33(datad, w, h, wpld, datas, wpls);
break;
case 68:
fdilate_1_34(datad, w, h, wpld, datas, wpls);
break;
case 69:
ferode_1_34(datad, w, h, wpld, datas, wpls);
break;
case 70:
fdilate_1_35(datad, w, h, wpld, datas, wpls);
break;
case 71:
ferode_1_35(datad, w, h, wpld, datas, wpls);
break;
case 72:
fdilate_1_36(datad, w, h, wpld, datas, wpls);
break;
case 73:
ferode_1_36(datad, w, h, wpld, datas, wpls);
break;
case 74:
fdilate_1_37(datad, w, h, wpld, datas, wpls);
break;
case 75:
ferode_1_37(datad, w, h, wpld, datas, wpls);
break;
case 76:
fdilate_1_38(datad, w, h, wpld, datas, wpls);
break;
case 77:
ferode_1_38(datad, w, h, wpld, datas, wpls);
break;
case 78:
fdilate_1_39(datad, w, h, wpld, datas, wpls);
break;
case 79:
ferode_1_39(datad, w, h, wpld, datas, wpls);
break;
case 80:
fdilate_1_40(datad, w, h, wpld, datas, wpls);
break;
case 81:
ferode_1_40(datad, w, h, wpld, datas, wpls);
break;
case 82:
fdilate_1_41(datad, w, h, wpld, datas, wpls);
break;
case 83:
ferode_1_41(datad, w, h, wpld, datas, wpls);
break;
case 84:
fdilate_1_42(datad, w, h, wpld, datas, wpls);
break;
case 85:
ferode_1_42(datad, w, h, wpld, datas, wpls);
break;
case 86:
fdilate_1_43(datad, w, h, wpld, datas, wpls);
break;
case 87:
ferode_1_43(datad, w, h, wpld, datas, wpls);
break;
case 88:
fdilate_1_44(datad, w, h, wpld, datas, wpls);
break;
case 89:
ferode_1_44(datad, w, h, wpld, datas, wpls);
break;
case 90:
fdilate_1_45(datad, w, h, wpld, datas, wpls);
break;
case 91:
ferode_1_45(datad, w, h, wpld, datas, wpls);
break;
case 92:
fdilate_1_46(datad, w, h, wpld, datas, wpls);
break;
case 93:
ferode_1_46(datad, w, h, wpld, datas, wpls);
break;
case 94:
fdilate_1_47(datad, w, h, wpld, datas, wpls);
break;
case 95:
ferode_1_47(datad, w, h, wpld, datas, wpls);
break;
case 96:
fdilate_1_48(datad, w, h, wpld, datas, wpls);
break;
case 97:
ferode_1_48(datad, w, h, wpld, datas, wpls);
break;
case 98:
fdilate_1_49(datad, w, h, wpld, datas, wpls);
break;
case 99:
ferode_1_49(datad, w, h, wpld, datas, wpls);
break;
case 100:
fdilate_1_50(datad, w, h, wpld, datas, wpls);
break;
case 101:
ferode_1_50(datad, w, h, wpld, datas, wpls);
break;
case 102:
fdilate_1_51(datad, w, h, wpld, datas, wpls);
break;
case 103:
ferode_1_51(datad, w, h, wpld, datas, wpls);
break;
case 104:
fdilate_1_52(datad, w, h, wpld, datas, wpls);
break;
case 105:
ferode_1_52(datad, w, h, wpld, datas, wpls);
break;
case 106:
fdilate_1_53(datad, w, h, wpld, datas, wpls);
break;
case 107:
ferode_1_53(datad, w, h, wpld, datas, wpls);
break;
case 108:
fdilate_1_54(datad, w, h, wpld, datas, wpls);
break;
case 109:
ferode_1_54(datad, w, h, wpld, datas, wpls);
break;
case 110:
fdilate_1_55(datad, w, h, wpld, datas, wpls);
break;
case 111:
ferode_1_55(datad, w, h, wpld, datas, wpls);
break;
case 112:
fdilate_1_56(datad, w, h, wpld, datas, wpls);
break;
case 113:
ferode_1_56(datad, w, h, wpld, datas, wpls);
break;
case 114:
fdilate_1_57(datad, w, h, wpld, datas, wpls);
break;
case 115:
ferode_1_57(datad, w, h, wpld, datas, wpls);
break;
}
return 0;
}
/*--------------------------------------------------------------------------*
* Low-level auto-generated static routines *
*--------------------------------------------------------------------------*/
/*
* N.B. In all the low-level routines, the part of the image
* that is accessed has been clipped by 32 pixels on
* all four sides. This is done in the higher level
* code by redefining w and h smaller and by moving the
* start-of-image pointers up to the beginning of this
* interior rectangle.
*/
static void
fdilate_1_0(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) << 1) | (*(sptr + 1) >> 31)) |
(*sptr);
}
}
}
static void
ferode_1_0(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) >> 1) | (*(sptr - 1) << 31)) &
(*sptr);
}
}
}
static void
fdilate_1_1(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) << 1) | (*(sptr + 1) >> 31)) |
(*sptr) |
((*(sptr) >> 1) | (*(sptr - 1) << 31));
}
}
}
static void
ferode_1_1(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) >> 1) | (*(sptr - 1) << 31)) &
(*sptr) &
((*(sptr) << 1) | (*(sptr + 1) >> 31));
}
}
}
static void
fdilate_1_2(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) << 2) | (*(sptr + 1) >> 30)) |
((*(sptr) << 1) | (*(sptr + 1) >> 31)) |
(*sptr) |
((*(sptr) >> 1) | (*(sptr - 1) << 31));
}
}
}
static void
ferode_1_2(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) >> 2) | (*(sptr - 1) << 30)) &
((*(sptr) >> 1) | (*(sptr - 1) << 31)) &
(*sptr) &
((*(sptr) << 1) | (*(sptr + 1) >> 31));
}
}
}
static void
fdilate_1_3(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) << 2) | (*(sptr + 1) >> 30)) |
((*(sptr) << 1) | (*(sptr + 1) >> 31)) |
(*sptr) |
((*(sptr) >> 1) | (*(sptr - 1) << 31)) |
((*(sptr) >> 2) | (*(sptr - 1) << 30));
}
}
}
static void
ferode_1_3(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) >> 2) | (*(sptr - 1) << 30)) &
((*(sptr) >> 1) | (*(sptr - 1) << 31)) &
(*sptr) &
((*(sptr) << 1) | (*(sptr + 1) >> 31)) &
((*(sptr) << 2) | (*(sptr + 1) >> 30));
}
}
}
static void
fdilate_1_4(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) << 3) | (*(sptr + 1) >> 29)) |
((*(sptr) << 2) | (*(sptr + 1) >> 30)) |
((*(sptr) << 1) | (*(sptr + 1) >> 31)) |
(*sptr) |
((*(sptr) >> 1) | (*(sptr - 1) << 31)) |
((*(sptr) >> 2) | (*(sptr - 1) << 30));
}
}
}
static void
ferode_1_4(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) >> 3) | (*(sptr - 1) << 29)) &
((*(sptr) >> 2) | (*(sptr - 1) << 30)) &
((*(sptr) >> 1) | (*(sptr - 1) << 31)) &
(*sptr) &
((*(sptr) << 1) | (*(sptr + 1) >> 31)) &
((*(sptr) << 2) | (*(sptr + 1) >> 30));
}
}
}
static void
fdilate_1_5(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) << 3) | (*(sptr + 1) >> 29)) |
((*(sptr) << 2) | (*(sptr + 1) >> 30)) |
((*(sptr) << 1) | (*(sptr + 1) >> 31)) |
(*sptr) |
((*(sptr) >> 1) | (*(sptr - 1) << 31)) |
((*(sptr) >> 2) | (*(sptr - 1) << 30)) |
((*(sptr) >> 3) | (*(sptr - 1) << 29));
}
}
}
static void
ferode_1_5(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) >> 3) | (*(sptr - 1) << 29)) &
((*(sptr) >> 2) | (*(sptr - 1) << 30)) &
((*(sptr) >> 1) | (*(sptr - 1) << 31)) &
(*sptr) &
((*(sptr) << 1) | (*(sptr + 1) >> 31)) &
((*(sptr) << 2) | (*(sptr + 1) >> 30)) &
((*(sptr) << 3) | (*(sptr + 1) >> 29));
}
}
}
static void
fdilate_1_6(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) << 4) | (*(sptr + 1) >> 28)) |
((*(sptr) << 3) | (*(sptr + 1) >> 29)) |
((*(sptr) << 2) | (*(sptr + 1) >> 30)) |
((*(sptr) << 1) | (*(sptr + 1) >> 31)) |
(*sptr) |
((*(sptr) >> 1) | (*(sptr - 1) << 31)) |
((*(sptr) >> 2) | (*(sptr - 1) << 30)) |
((*(sptr) >> 3) | (*(sptr - 1) << 29));
}
}
}
static void
ferode_1_6(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) >> 4) | (*(sptr - 1) << 28)) &
((*(sptr) >> 3) | (*(sptr - 1) << 29)) &
((*(sptr) >> 2) | (*(sptr - 1) << 30)) &
((*(sptr) >> 1) | (*(sptr - 1) << 31)) &
(*sptr) &
((*(sptr) << 1) | (*(sptr + 1) >> 31)) &
((*(sptr) << 2) | (*(sptr + 1) >> 30)) &
((*(sptr) << 3) | (*(sptr + 1) >> 29));
}
}
}
static void
fdilate_1_7(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) << 4) | (*(sptr + 1) >> 28)) |
((*(sptr) << 3) | (*(sptr + 1) >> 29)) |
((*(sptr) << 2) | (*(sptr + 1) >> 30)) |
((*(sptr) << 1) | (*(sptr + 1) >> 31)) |
(*sptr) |
((*(sptr) >> 1) | (*(sptr - 1) << 31)) |
((*(sptr) >> 2) | (*(sptr - 1) << 30)) |
((*(sptr) >> 3) | (*(sptr - 1) << 29)) |
((*(sptr) >> 4) | (*(sptr - 1) << 28));
}
}
}
static void
ferode_1_7(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) >> 4) | (*(sptr - 1) << 28)) &
((*(sptr) >> 3) | (*(sptr - 1) << 29)) &
((*(sptr) >> 2) | (*(sptr - 1) << 30)) &
((*(sptr) >> 1) | (*(sptr - 1) << 31)) &
(*sptr) &
((*(sptr) << 1) | (*(sptr + 1) >> 31)) &
((*(sptr) << 2) | (*(sptr + 1) >> 30)) &
((*(sptr) << 3) | (*(sptr + 1) >> 29)) &
((*(sptr) << 4) | (*(sptr + 1) >> 28));
}
}
}
static void
fdilate_1_8(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) << 5) | (*(sptr + 1) >> 27)) |
((*(sptr) << 4) | (*(sptr + 1) >> 28)) |
((*(sptr) << 3) | (*(sptr + 1) >> 29)) |
((*(sptr) << 2) | (*(sptr + 1) >> 30)) |
((*(sptr) << 1) | (*(sptr + 1) >> 31)) |
(*sptr) |
((*(sptr) >> 1) | (*(sptr - 1) << 31)) |
((*(sptr) >> 2) | (*(sptr - 1) << 30)) |
((*(sptr) >> 3) | (*(sptr - 1) << 29)) |
((*(sptr) >> 4) | (*(sptr - 1) << 28));
}
}
}
static void
ferode_1_8(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) >> 5) | (*(sptr - 1) << 27)) &
((*(sptr) >> 4) | (*(sptr - 1) << 28)) &
((*(sptr) >> 3) | (*(sptr - 1) << 29)) &
((*(sptr) >> 2) | (*(sptr - 1) << 30)) &
((*(sptr) >> 1) | (*(sptr - 1) << 31)) &
(*sptr) &
((*(sptr) << 1) | (*(sptr + 1) >> 31)) &
((*(sptr) << 2) | (*(sptr + 1) >> 30)) &
((*(sptr) << 3) | (*(sptr + 1) >> 29)) &
((*(sptr) << 4) | (*(sptr + 1) >> 28));
}
}
}
static void
fdilate_1_9(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) << 5) | (*(sptr + 1) >> 27)) |
((*(sptr) << 4) | (*(sptr + 1) >> 28)) |
((*(sptr) << 3) | (*(sptr + 1) >> 29)) |
((*(sptr) << 2) | (*(sptr + 1) >> 30)) |
((*(sptr) << 1) | (*(sptr + 1) >> 31)) |
(*sptr) |
((*(sptr) >> 1) | (*(sptr - 1) << 31)) |
((*(sptr) >> 2) | (*(sptr - 1) << 30)) |
((*(sptr) >> 3) | (*(sptr - 1) << 29)) |
((*(sptr) >> 4) | (*(sptr - 1) << 28)) |
((*(sptr) >> 5) | (*(sptr - 1) << 27));
}
}
}
static void
ferode_1_9(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) >> 5) | (*(sptr - 1) << 27)) &
((*(sptr) >> 4) | (*(sptr - 1) << 28)) &
((*(sptr) >> 3) | (*(sptr - 1) << 29)) &
((*(sptr) >> 2) | (*(sptr - 1) << 30)) &
((*(sptr) >> 1) | (*(sptr - 1) << 31)) &
(*sptr) &
((*(sptr) << 1) | (*(sptr + 1) >> 31)) &
((*(sptr) << 2) | (*(sptr + 1) >> 30)) &
((*(sptr) << 3) | (*(sptr + 1) >> 29)) &
((*(sptr) << 4) | (*(sptr + 1) >> 28)) &
((*(sptr) << 5) | (*(sptr + 1) >> 27));
}
}
}
static void
fdilate_1_10(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) << 6) | (*(sptr + 1) >> 26)) |
((*(sptr) << 5) | (*(sptr + 1) >> 27)) |
((*(sptr) << 4) | (*(sptr + 1) >> 28)) |
((*(sptr) << 3) | (*(sptr + 1) >> 29)) |
((*(sptr) << 2) | (*(sptr + 1) >> 30)) |
((*(sptr) << 1) | (*(sptr + 1) >> 31)) |
(*sptr) |
((*(sptr) >> 1) | (*(sptr - 1) << 31)) |
((*(sptr) >> 2) | (*(sptr - 1) << 30)) |
((*(sptr) >> 3) | (*(sptr - 1) << 29)) |
((*(sptr) >> 4) | (*(sptr - 1) << 28)) |
((*(sptr) >> 5) | (*(sptr - 1) << 27));
}
}
}
static void
ferode_1_10(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) >> 6) | (*(sptr - 1) << 26)) &
((*(sptr) >> 5) | (*(sptr - 1) << 27)) &
((*(sptr) >> 4) | (*(sptr - 1) << 28)) &
((*(sptr) >> 3) | (*(sptr - 1) << 29)) &
((*(sptr) >> 2) | (*(sptr - 1) << 30)) &
((*(sptr) >> 1) | (*(sptr - 1) << 31)) &
(*sptr) &
((*(sptr) << 1) | (*(sptr + 1) >> 31)) &
((*(sptr) << 2) | (*(sptr + 1) >> 30)) &
((*(sptr) << 3) | (*(sptr + 1) >> 29)) &
((*(sptr) << 4) | (*(sptr + 1) >> 28)) &
((*(sptr) << 5) | (*(sptr + 1) >> 27));
}
}
}
static void
fdilate_1_11(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) << 6) | (*(sptr + 1) >> 26)) |
((*(sptr) << 5) | (*(sptr + 1) >> 27)) |
((*(sptr) << 4) | (*(sptr + 1) >> 28)) |
((*(sptr) << 3) | (*(sptr + 1) >> 29)) |
((*(sptr) << 2) | (*(sptr + 1) >> 30)) |
((*(sptr) << 1) | (*(sptr + 1) >> 31)) |
(*sptr) |
((*(sptr) >> 1) | (*(sptr - 1) << 31)) |
((*(sptr) >> 2) | (*(sptr - 1) << 30)) |
((*(sptr) >> 3) | (*(sptr - 1) << 29)) |
((*(sptr) >> 4) | (*(sptr - 1) << 28)) |
((*(sptr) >> 5) | (*(sptr - 1) << 27)) |
((*(sptr) >> 6) | (*(sptr - 1) << 26));
}
}
}
static void
ferode_1_11(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) >> 6) | (*(sptr - 1) << 26)) &
((*(sptr) >> 5) | (*(sptr - 1) << 27)) &
((*(sptr) >> 4) | (*(sptr - 1) << 28)) &
((*(sptr) >> 3) | (*(sptr - 1) << 29)) &
((*(sptr) >> 2) | (*(sptr - 1) << 30)) &
((*(sptr) >> 1) | (*(sptr - 1) << 31)) &
(*sptr) &
((*(sptr) << 1) | (*(sptr + 1) >> 31)) &
((*(sptr) << 2) | (*(sptr + 1) >> 30)) &
((*(sptr) << 3) | (*(sptr + 1) >> 29)) &
((*(sptr) << 4) | (*(sptr + 1) >> 28)) &
((*(sptr) << 5) | (*(sptr + 1) >> 27)) &
((*(sptr) << 6) | (*(sptr + 1) >> 26));
}
}
}
static void
fdilate_1_12(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) << 7) | (*(sptr + 1) >> 25)) |
((*(sptr) << 6) | (*(sptr + 1) >> 26)) |
((*(sptr) << 5) | (*(sptr + 1) >> 27)) |
((*(sptr) << 4) | (*(sptr + 1) >> 28)) |
((*(sptr) << 3) | (*(sptr + 1) >> 29)) |
((*(sptr) << 2) | (*(sptr + 1) >> 30)) |
((*(sptr) << 1) | (*(sptr + 1) >> 31)) |
(*sptr) |
((*(sptr) >> 1) | (*(sptr - 1) << 31)) |
((*(sptr) >> 2) | (*(sptr - 1) << 30)) |
((*(sptr) >> 3) | (*(sptr - 1) << 29)) |
((*(sptr) >> 4) | (*(sptr - 1) << 28)) |
((*(sptr) >> 5) | (*(sptr - 1) << 27)) |
((*(sptr) >> 6) | (*(sptr - 1) << 26));
}
}
}
static void
ferode_1_12(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) >> 7) | (*(sptr - 1) << 25)) &
((*(sptr) >> 6) | (*(sptr - 1) << 26)) &
((*(sptr) >> 5) | (*(sptr - 1) << 27)) &
((*(sptr) >> 4) | (*(sptr - 1) << 28)) &
((*(sptr) >> 3) | (*(sptr - 1) << 29)) &
((*(sptr) >> 2) | (*(sptr - 1) << 30)) &
((*(sptr) >> 1) | (*(sptr - 1) << 31)) &
(*sptr) &
((*(sptr) << 1) | (*(sptr + 1) >> 31)) &
((*(sptr) << 2) | (*(sptr + 1) >> 30)) &
((*(sptr) << 3) | (*(sptr + 1) >> 29)) &
((*(sptr) << 4) | (*(sptr + 1) >> 28)) &
((*(sptr) << 5) | (*(sptr + 1) >> 27)) &
((*(sptr) << 6) | (*(sptr + 1) >> 26));
}
}
}
static void
fdilate_1_13(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) << 7) | (*(sptr + 1) >> 25)) |
((*(sptr) << 6) | (*(sptr + 1) >> 26)) |
((*(sptr) << 5) | (*(sptr + 1) >> 27)) |
((*(sptr) << 4) | (*(sptr + 1) >> 28)) |
((*(sptr) << 3) | (*(sptr + 1) >> 29)) |
((*(sptr) << 2) | (*(sptr + 1) >> 30)) |
((*(sptr) << 1) | (*(sptr + 1) >> 31)) |
(*sptr) |
((*(sptr) >> 1) | (*(sptr - 1) << 31)) |
((*(sptr) >> 2) | (*(sptr - 1) << 30)) |
((*(sptr) >> 3) | (*(sptr - 1) << 29)) |
((*(sptr) >> 4) | (*(sptr - 1) << 28)) |
((*(sptr) >> 5) | (*(sptr - 1) << 27)) |
((*(sptr) >> 6) | (*(sptr - 1) << 26)) |
((*(sptr) >> 7) | (*(sptr - 1) << 25));
}
}
}
static void
ferode_1_13(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) >> 7) | (*(sptr - 1) << 25)) &
((*(sptr) >> 6) | (*(sptr - 1) << 26)) &
((*(sptr) >> 5) | (*(sptr - 1) << 27)) &
((*(sptr) >> 4) | (*(sptr - 1) << 28)) &
((*(sptr) >> 3) | (*(sptr - 1) << 29)) &
((*(sptr) >> 2) | (*(sptr - 1) << 30)) &
((*(sptr) >> 1) | (*(sptr - 1) << 31)) &
(*sptr) &
((*(sptr) << 1) | (*(sptr + 1) >> 31)) &
((*(sptr) << 2) | (*(sptr + 1) >> 30)) &
((*(sptr) << 3) | (*(sptr + 1) >> 29)) &
((*(sptr) << 4) | (*(sptr + 1) >> 28)) &
((*(sptr) << 5) | (*(sptr + 1) >> 27)) &
((*(sptr) << 6) | (*(sptr + 1) >> 26)) &
((*(sptr) << 7) | (*(sptr + 1) >> 25));
}
}
}
static void
fdilate_1_14(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) << 10) | (*(sptr + 1) >> 22)) |
((*(sptr) << 9) | (*(sptr + 1) >> 23)) |
((*(sptr) << 8) | (*(sptr + 1) >> 24)) |
((*(sptr) << 7) | (*(sptr + 1) >> 25)) |
((*(sptr) << 6) | (*(sptr + 1) >> 26)) |
((*(sptr) << 5) | (*(sptr + 1) >> 27)) |
((*(sptr) << 4) | (*(sptr + 1) >> 28)) |
((*(sptr) << 3) | (*(sptr + 1) >> 29)) |
((*(sptr) << 2) | (*(sptr + 1) >> 30)) |
((*(sptr) << 1) | (*(sptr + 1) >> 31)) |
(*sptr) |
((*(sptr) >> 1) | (*(sptr - 1) << 31)) |
((*(sptr) >> 2) | (*(sptr - 1) << 30)) |
((*(sptr) >> 3) | (*(sptr - 1) << 29)) |
((*(sptr) >> 4) | (*(sptr - 1) << 28)) |
((*(sptr) >> 5) | (*(sptr - 1) << 27)) |
((*(sptr) >> 6) | (*(sptr - 1) << 26)) |
((*(sptr) >> 7) | (*(sptr - 1) << 25)) |
((*(sptr) >> 8) | (*(sptr - 1) << 24)) |
((*(sptr) >> 9) | (*(sptr - 1) << 23));
}
}
}
static void
ferode_1_14(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) >> 10) | (*(sptr - 1) << 22)) &
((*(sptr) >> 9) | (*(sptr - 1) << 23)) &
((*(sptr) >> 8) | (*(sptr - 1) << 24)) &
((*(sptr) >> 7) | (*(sptr - 1) << 25)) &
((*(sptr) >> 6) | (*(sptr - 1) << 26)) &
((*(sptr) >> 5) | (*(sptr - 1) << 27)) &
((*(sptr) >> 4) | (*(sptr - 1) << 28)) &
((*(sptr) >> 3) | (*(sptr - 1) << 29)) &
((*(sptr) >> 2) | (*(sptr - 1) << 30)) &
((*(sptr) >> 1) | (*(sptr - 1) << 31)) &
(*sptr) &
((*(sptr) << 1) | (*(sptr + 1) >> 31)) &
((*(sptr) << 2) | (*(sptr + 1) >> 30)) &
((*(sptr) << 3) | (*(sptr + 1) >> 29)) &
((*(sptr) << 4) | (*(sptr + 1) >> 28)) &
((*(sptr) << 5) | (*(sptr + 1) >> 27)) &
((*(sptr) << 6) | (*(sptr + 1) >> 26)) &
((*(sptr) << 7) | (*(sptr + 1) >> 25)) &
((*(sptr) << 8) | (*(sptr + 1) >> 24)) &
((*(sptr) << 9) | (*(sptr + 1) >> 23));
}
}
}
static void
fdilate_1_15(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) << 10) | (*(sptr + 1) >> 22)) |
((*(sptr) << 9) | (*(sptr + 1) >> 23)) |
((*(sptr) << 8) | (*(sptr + 1) >> 24)) |
((*(sptr) << 7) | (*(sptr + 1) >> 25)) |
((*(sptr) << 6) | (*(sptr + 1) >> 26)) |
((*(sptr) << 5) | (*(sptr + 1) >> 27)) |
((*(sptr) << 4) | (*(sptr + 1) >> 28)) |
((*(sptr) << 3) | (*(sptr + 1) >> 29)) |
((*(sptr) << 2) | (*(sptr + 1) >> 30)) |
((*(sptr) << 1) | (*(sptr + 1) >> 31)) |
(*sptr) |
((*(sptr) >> 1) | (*(sptr - 1) << 31)) |
((*(sptr) >> 2) | (*(sptr - 1) << 30)) |
((*(sptr) >> 3) | (*(sptr - 1) << 29)) |
((*(sptr) >> 4) | (*(sptr - 1) << 28)) |
((*(sptr) >> 5) | (*(sptr - 1) << 27)) |
((*(sptr) >> 6) | (*(sptr - 1) << 26)) |
((*(sptr) >> 7) | (*(sptr - 1) << 25)) |
((*(sptr) >> 8) | (*(sptr - 1) << 24)) |
((*(sptr) >> 9) | (*(sptr - 1) << 23)) |
((*(sptr) >> 10) | (*(sptr - 1) << 22));
}
}
}
static void
ferode_1_15(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) >> 10) | (*(sptr - 1) << 22)) &
((*(sptr) >> 9) | (*(sptr - 1) << 23)) &
((*(sptr) >> 8) | (*(sptr - 1) << 24)) &
((*(sptr) >> 7) | (*(sptr - 1) << 25)) &
((*(sptr) >> 6) | (*(sptr - 1) << 26)) &
((*(sptr) >> 5) | (*(sptr - 1) << 27)) &
((*(sptr) >> 4) | (*(sptr - 1) << 28)) &
((*(sptr) >> 3) | (*(sptr - 1) << 29)) &
((*(sptr) >> 2) | (*(sptr - 1) << 30)) &
((*(sptr) >> 1) | (*(sptr - 1) << 31)) &
(*sptr) &
((*(sptr) << 1) | (*(sptr + 1) >> 31)) &
((*(sptr) << 2) | (*(sptr + 1) >> 30)) &
((*(sptr) << 3) | (*(sptr + 1) >> 29)) &
((*(sptr) << 4) | (*(sptr + 1) >> 28)) &
((*(sptr) << 5) | (*(sptr + 1) >> 27)) &
((*(sptr) << 6) | (*(sptr + 1) >> 26)) &
((*(sptr) << 7) | (*(sptr + 1) >> 25)) &
((*(sptr) << 8) | (*(sptr + 1) >> 24)) &
((*(sptr) << 9) | (*(sptr + 1) >> 23)) &
((*(sptr) << 10) | (*(sptr + 1) >> 22));
}
}
}
static void
fdilate_1_16(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) << 12) | (*(sptr + 1) >> 20)) |
((*(sptr) << 11) | (*(sptr + 1) >> 21)) |
((*(sptr) << 10) | (*(sptr + 1) >> 22)) |
((*(sptr) << 9) | (*(sptr + 1) >> 23)) |
((*(sptr) << 8) | (*(sptr + 1) >> 24)) |
((*(sptr) << 7) | (*(sptr + 1) >> 25)) |
((*(sptr) << 6) | (*(sptr + 1) >> 26)) |
((*(sptr) << 5) | (*(sptr + 1) >> 27)) |
((*(sptr) << 4) | (*(sptr + 1) >> 28)) |
((*(sptr) << 3) | (*(sptr + 1) >> 29)) |
((*(sptr) << 2) | (*(sptr + 1) >> 30)) |
((*(sptr) << 1) | (*(sptr + 1) >> 31)) |
(*sptr) |
((*(sptr) >> 1) | (*(sptr - 1) << 31)) |
((*(sptr) >> 2) | (*(sptr - 1) << 30)) |
((*(sptr) >> 3) | (*(sptr - 1) << 29)) |
((*(sptr) >> 4) | (*(sptr - 1) << 28)) |
((*(sptr) >> 5) | (*(sptr - 1) << 27)) |
((*(sptr) >> 6) | (*(sptr - 1) << 26)) |
((*(sptr) >> 7) | (*(sptr - 1) << 25)) |
((*(sptr) >> 8) | (*(sptr - 1) << 24)) |
((*(sptr) >> 9) | (*(sptr - 1) << 23)) |
((*(sptr) >> 10) | (*(sptr - 1) << 22)) |
((*(sptr) >> 11) | (*(sptr - 1) << 21)) |
((*(sptr) >> 12) | (*(sptr - 1) << 20));
}
}
}
static void
ferode_1_16(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) >> 12) | (*(sptr - 1) << 20)) &
((*(sptr) >> 11) | (*(sptr - 1) << 21)) &
((*(sptr) >> 10) | (*(sptr - 1) << 22)) &
((*(sptr) >> 9) | (*(sptr - 1) << 23)) &
((*(sptr) >> 8) | (*(sptr - 1) << 24)) &
((*(sptr) >> 7) | (*(sptr - 1) << 25)) &
((*(sptr) >> 6) | (*(sptr - 1) << 26)) &
((*(sptr) >> 5) | (*(sptr - 1) << 27)) &
((*(sptr) >> 4) | (*(sptr - 1) << 28)) &
((*(sptr) >> 3) | (*(sptr - 1) << 29)) &
((*(sptr) >> 2) | (*(sptr - 1) << 30)) &
((*(sptr) >> 1) | (*(sptr - 1) << 31)) &
(*sptr) &
((*(sptr) << 1) | (*(sptr + 1) >> 31)) &
((*(sptr) << 2) | (*(sptr + 1) >> 30)) &
((*(sptr) << 3) | (*(sptr + 1) >> 29)) &
((*(sptr) << 4) | (*(sptr + 1) >> 28)) &
((*(sptr) << 5) | (*(sptr + 1) >> 27)) &
((*(sptr) << 6) | (*(sptr + 1) >> 26)) &
((*(sptr) << 7) | (*(sptr + 1) >> 25)) &
((*(sptr) << 8) | (*(sptr + 1) >> 24)) &
((*(sptr) << 9) | (*(sptr + 1) >> 23)) &
((*(sptr) << 10) | (*(sptr + 1) >> 22)) &
((*(sptr) << 11) | (*(sptr + 1) >> 21)) &
((*(sptr) << 12) | (*(sptr + 1) >> 20));
}
}
}
static void
fdilate_1_17(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) << 15) | (*(sptr + 1) >> 17)) |
((*(sptr) << 14) | (*(sptr + 1) >> 18)) |
((*(sptr) << 13) | (*(sptr + 1) >> 19)) |
((*(sptr) << 12) | (*(sptr + 1) >> 20)) |
((*(sptr) << 11) | (*(sptr + 1) >> 21)) |
((*(sptr) << 10) | (*(sptr + 1) >> 22)) |
((*(sptr) << 9) | (*(sptr + 1) >> 23)) |
((*(sptr) << 8) | (*(sptr + 1) >> 24)) |
((*(sptr) << 7) | (*(sptr + 1) >> 25)) |
((*(sptr) << 6) | (*(sptr + 1) >> 26)) |
((*(sptr) << 5) | (*(sptr + 1) >> 27)) |
((*(sptr) << 4) | (*(sptr + 1) >> 28)) |
((*(sptr) << 3) | (*(sptr + 1) >> 29)) |
((*(sptr) << 2) | (*(sptr + 1) >> 30)) |
((*(sptr) << 1) | (*(sptr + 1) >> 31)) |
(*sptr) |
((*(sptr) >> 1) | (*(sptr - 1) << 31)) |
((*(sptr) >> 2) | (*(sptr - 1) << 30)) |
((*(sptr) >> 3) | (*(sptr - 1) << 29)) |
((*(sptr) >> 4) | (*(sptr - 1) << 28)) |
((*(sptr) >> 5) | (*(sptr - 1) << 27)) |
((*(sptr) >> 6) | (*(sptr - 1) << 26)) |
((*(sptr) >> 7) | (*(sptr - 1) << 25)) |
((*(sptr) >> 8) | (*(sptr - 1) << 24)) |
((*(sptr) >> 9) | (*(sptr - 1) << 23)) |
((*(sptr) >> 10) | (*(sptr - 1) << 22)) |
((*(sptr) >> 11) | (*(sptr - 1) << 21)) |
((*(sptr) >> 12) | (*(sptr - 1) << 20)) |
((*(sptr) >> 13) | (*(sptr - 1) << 19)) |
((*(sptr) >> 14) | (*(sptr - 1) << 18));
}
}
}
static void
ferode_1_17(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) >> 15) | (*(sptr - 1) << 17)) &
((*(sptr) >> 14) | (*(sptr - 1) << 18)) &
((*(sptr) >> 13) | (*(sptr - 1) << 19)) &
((*(sptr) >> 12) | (*(sptr - 1) << 20)) &
((*(sptr) >> 11) | (*(sptr - 1) << 21)) &
((*(sptr) >> 10) | (*(sptr - 1) << 22)) &
((*(sptr) >> 9) | (*(sptr - 1) << 23)) &
((*(sptr) >> 8) | (*(sptr - 1) << 24)) &
((*(sptr) >> 7) | (*(sptr - 1) << 25)) &
((*(sptr) >> 6) | (*(sptr - 1) << 26)) &
((*(sptr) >> 5) | (*(sptr - 1) << 27)) &
((*(sptr) >> 4) | (*(sptr - 1) << 28)) &
((*(sptr) >> 3) | (*(sptr - 1) << 29)) &
((*(sptr) >> 2) | (*(sptr - 1) << 30)) &
((*(sptr) >> 1) | (*(sptr - 1) << 31)) &
(*sptr) &
((*(sptr) << 1) | (*(sptr + 1) >> 31)) &
((*(sptr) << 2) | (*(sptr + 1) >> 30)) &
((*(sptr) << 3) | (*(sptr + 1) >> 29)) &
((*(sptr) << 4) | (*(sptr + 1) >> 28)) &
((*(sptr) << 5) | (*(sptr + 1) >> 27)) &
((*(sptr) << 6) | (*(sptr + 1) >> 26)) &
((*(sptr) << 7) | (*(sptr + 1) >> 25)) &
((*(sptr) << 8) | (*(sptr + 1) >> 24)) &
((*(sptr) << 9) | (*(sptr + 1) >> 23)) &
((*(sptr) << 10) | (*(sptr + 1) >> 22)) &
((*(sptr) << 11) | (*(sptr + 1) >> 21)) &
((*(sptr) << 12) | (*(sptr + 1) >> 20)) &
((*(sptr) << 13) | (*(sptr + 1) >> 19)) &
((*(sptr) << 14) | (*(sptr + 1) >> 18));
}
}
}
static void
fdilate_1_18(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) << 15) | (*(sptr + 1) >> 17)) |
((*(sptr) << 14) | (*(sptr + 1) >> 18)) |
((*(sptr) << 13) | (*(sptr + 1) >> 19)) |
((*(sptr) << 12) | (*(sptr + 1) >> 20)) |
((*(sptr) << 11) | (*(sptr + 1) >> 21)) |
((*(sptr) << 10) | (*(sptr + 1) >> 22)) |
((*(sptr) << 9) | (*(sptr + 1) >> 23)) |
((*(sptr) << 8) | (*(sptr + 1) >> 24)) |
((*(sptr) << 7) | (*(sptr + 1) >> 25)) |
((*(sptr) << 6) | (*(sptr + 1) >> 26)) |
((*(sptr) << 5) | (*(sptr + 1) >> 27)) |
((*(sptr) << 4) | (*(sptr + 1) >> 28)) |
((*(sptr) << 3) | (*(sptr + 1) >> 29)) |
((*(sptr) << 2) | (*(sptr + 1) >> 30)) |
((*(sptr) << 1) | (*(sptr + 1) >> 31)) |
(*sptr) |
((*(sptr) >> 1) | (*(sptr - 1) << 31)) |
((*(sptr) >> 2) | (*(sptr - 1) << 30)) |
((*(sptr) >> 3) | (*(sptr - 1) << 29)) |
((*(sptr) >> 4) | (*(sptr - 1) << 28)) |
((*(sptr) >> 5) | (*(sptr - 1) << 27)) |
((*(sptr) >> 6) | (*(sptr - 1) << 26)) |
((*(sptr) >> 7) | (*(sptr - 1) << 25)) |
((*(sptr) >> 8) | (*(sptr - 1) << 24)) |
((*(sptr) >> 9) | (*(sptr - 1) << 23)) |
((*(sptr) >> 10) | (*(sptr - 1) << 22)) |
((*(sptr) >> 11) | (*(sptr - 1) << 21)) |
((*(sptr) >> 12) | (*(sptr - 1) << 20)) |
((*(sptr) >> 13) | (*(sptr - 1) << 19)) |
((*(sptr) >> 14) | (*(sptr - 1) << 18)) |
((*(sptr) >> 15) | (*(sptr - 1) << 17));
}
}
}
static void
ferode_1_18(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) >> 15) | (*(sptr - 1) << 17)) &
((*(sptr) >> 14) | (*(sptr - 1) << 18)) &
((*(sptr) >> 13) | (*(sptr - 1) << 19)) &
((*(sptr) >> 12) | (*(sptr - 1) << 20)) &
((*(sptr) >> 11) | (*(sptr - 1) << 21)) &
((*(sptr) >> 10) | (*(sptr - 1) << 22)) &
((*(sptr) >> 9) | (*(sptr - 1) << 23)) &
((*(sptr) >> 8) | (*(sptr - 1) << 24)) &
((*(sptr) >> 7) | (*(sptr - 1) << 25)) &
((*(sptr) >> 6) | (*(sptr - 1) << 26)) &
((*(sptr) >> 5) | (*(sptr - 1) << 27)) &
((*(sptr) >> 4) | (*(sptr - 1) << 28)) &
((*(sptr) >> 3) | (*(sptr - 1) << 29)) &
((*(sptr) >> 2) | (*(sptr - 1) << 30)) &
((*(sptr) >> 1) | (*(sptr - 1) << 31)) &
(*sptr) &
((*(sptr) << 1) | (*(sptr + 1) >> 31)) &
((*(sptr) << 2) | (*(sptr + 1) >> 30)) &
((*(sptr) << 3) | (*(sptr + 1) >> 29)) &
((*(sptr) << 4) | (*(sptr + 1) >> 28)) &
((*(sptr) << 5) | (*(sptr + 1) >> 27)) &
((*(sptr) << 6) | (*(sptr + 1) >> 26)) &
((*(sptr) << 7) | (*(sptr + 1) >> 25)) &
((*(sptr) << 8) | (*(sptr + 1) >> 24)) &
((*(sptr) << 9) | (*(sptr + 1) >> 23)) &
((*(sptr) << 10) | (*(sptr + 1) >> 22)) &
((*(sptr) << 11) | (*(sptr + 1) >> 21)) &
((*(sptr) << 12) | (*(sptr + 1) >> 20)) &
((*(sptr) << 13) | (*(sptr + 1) >> 19)) &
((*(sptr) << 14) | (*(sptr + 1) >> 18)) &
((*(sptr) << 15) | (*(sptr + 1) >> 17));
}
}
}
static void
fdilate_1_19(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) << 17) | (*(sptr + 1) >> 15)) |
((*(sptr) << 16) | (*(sptr + 1) >> 16)) |
((*(sptr) << 15) | (*(sptr + 1) >> 17)) |
((*(sptr) << 14) | (*(sptr + 1) >> 18)) |
((*(sptr) << 13) | (*(sptr + 1) >> 19)) |
((*(sptr) << 12) | (*(sptr + 1) >> 20)) |
((*(sptr) << 11) | (*(sptr + 1) >> 21)) |
((*(sptr) << 10) | (*(sptr + 1) >> 22)) |
((*(sptr) << 9) | (*(sptr + 1) >> 23)) |
((*(sptr) << 8) | (*(sptr + 1) >> 24)) |
((*(sptr) << 7) | (*(sptr + 1) >> 25)) |
((*(sptr) << 6) | (*(sptr + 1) >> 26)) |
((*(sptr) << 5) | (*(sptr + 1) >> 27)) |
((*(sptr) << 4) | (*(sptr + 1) >> 28)) |
((*(sptr) << 3) | (*(sptr + 1) >> 29)) |
((*(sptr) << 2) | (*(sptr + 1) >> 30)) |
((*(sptr) << 1) | (*(sptr + 1) >> 31)) |
(*sptr) |
((*(sptr) >> 1) | (*(sptr - 1) << 31)) |
((*(sptr) >> 2) | (*(sptr - 1) << 30)) |
((*(sptr) >> 3) | (*(sptr - 1) << 29)) |
((*(sptr) >> 4) | (*(sptr - 1) << 28)) |
((*(sptr) >> 5) | (*(sptr - 1) << 27)) |
((*(sptr) >> 6) | (*(sptr - 1) << 26)) |
((*(sptr) >> 7) | (*(sptr - 1) << 25)) |
((*(sptr) >> 8) | (*(sptr - 1) << 24)) |
((*(sptr) >> 9) | (*(sptr - 1) << 23)) |
((*(sptr) >> 10) | (*(sptr - 1) << 22)) |
((*(sptr) >> 11) | (*(sptr - 1) << 21)) |
((*(sptr) >> 12) | (*(sptr - 1) << 20)) |
((*(sptr) >> 13) | (*(sptr - 1) << 19)) |
((*(sptr) >> 14) | (*(sptr - 1) << 18)) |
((*(sptr) >> 15) | (*(sptr - 1) << 17)) |
((*(sptr) >> 16) | (*(sptr - 1) << 16)) |
((*(sptr) >> 17) | (*(sptr - 1) << 15));
}
}
}
static void
ferode_1_19(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) >> 17) | (*(sptr - 1) << 15)) &
((*(sptr) >> 16) | (*(sptr - 1) << 16)) &
((*(sptr) >> 15) | (*(sptr - 1) << 17)) &
((*(sptr) >> 14) | (*(sptr - 1) << 18)) &
((*(sptr) >> 13) | (*(sptr - 1) << 19)) &
((*(sptr) >> 12) | (*(sptr - 1) << 20)) &
((*(sptr) >> 11) | (*(sptr - 1) << 21)) &
((*(sptr) >> 10) | (*(sptr - 1) << 22)) &
((*(sptr) >> 9) | (*(sptr - 1) << 23)) &
((*(sptr) >> 8) | (*(sptr - 1) << 24)) &
((*(sptr) >> 7) | (*(sptr - 1) << 25)) &
((*(sptr) >> 6) | (*(sptr - 1) << 26)) &
((*(sptr) >> 5) | (*(sptr - 1) << 27)) &
((*(sptr) >> 4) | (*(sptr - 1) << 28)) &
((*(sptr) >> 3) | (*(sptr - 1) << 29)) &
((*(sptr) >> 2) | (*(sptr - 1) << 30)) &
((*(sptr) >> 1) | (*(sptr - 1) << 31)) &
(*sptr) &
((*(sptr) << 1) | (*(sptr + 1) >> 31)) &
((*(sptr) << 2) | (*(sptr + 1) >> 30)) &
((*(sptr) << 3) | (*(sptr + 1) >> 29)) &
((*(sptr) << 4) | (*(sptr + 1) >> 28)) &
((*(sptr) << 5) | (*(sptr + 1) >> 27)) &
((*(sptr) << 6) | (*(sptr + 1) >> 26)) &
((*(sptr) << 7) | (*(sptr + 1) >> 25)) &
((*(sptr) << 8) | (*(sptr + 1) >> 24)) &
((*(sptr) << 9) | (*(sptr + 1) >> 23)) &
((*(sptr) << 10) | (*(sptr + 1) >> 22)) &
((*(sptr) << 11) | (*(sptr + 1) >> 21)) &
((*(sptr) << 12) | (*(sptr + 1) >> 20)) &
((*(sptr) << 13) | (*(sptr + 1) >> 19)) &
((*(sptr) << 14) | (*(sptr + 1) >> 18)) &
((*(sptr) << 15) | (*(sptr + 1) >> 17)) &
((*(sptr) << 16) | (*(sptr + 1) >> 16)) &
((*(sptr) << 17) | (*(sptr + 1) >> 15));
}
}
}
static void
fdilate_1_20(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) << 20) | (*(sptr + 1) >> 12)) |
((*(sptr) << 19) | (*(sptr + 1) >> 13)) |
((*(sptr) << 18) | (*(sptr + 1) >> 14)) |
((*(sptr) << 17) | (*(sptr + 1) >> 15)) |
((*(sptr) << 16) | (*(sptr + 1) >> 16)) |
((*(sptr) << 15) | (*(sptr + 1) >> 17)) |
((*(sptr) << 14) | (*(sptr + 1) >> 18)) |
((*(sptr) << 13) | (*(sptr + 1) >> 19)) |
((*(sptr) << 12) | (*(sptr + 1) >> 20)) |
((*(sptr) << 11) | (*(sptr + 1) >> 21)) |
((*(sptr) << 10) | (*(sptr + 1) >> 22)) |
((*(sptr) << 9) | (*(sptr + 1) >> 23)) |
((*(sptr) << 8) | (*(sptr + 1) >> 24)) |
((*(sptr) << 7) | (*(sptr + 1) >> 25)) |
((*(sptr) << 6) | (*(sptr + 1) >> 26)) |
((*(sptr) << 5) | (*(sptr + 1) >> 27)) |
((*(sptr) << 4) | (*(sptr + 1) >> 28)) |
((*(sptr) << 3) | (*(sptr + 1) >> 29)) |
((*(sptr) << 2) | (*(sptr + 1) >> 30)) |
((*(sptr) << 1) | (*(sptr + 1) >> 31)) |
(*sptr) |
((*(sptr) >> 1) | (*(sptr - 1) << 31)) |
((*(sptr) >> 2) | (*(sptr - 1) << 30)) |
((*(sptr) >> 3) | (*(sptr - 1) << 29)) |
((*(sptr) >> 4) | (*(sptr - 1) << 28)) |
((*(sptr) >> 5) | (*(sptr - 1) << 27)) |
((*(sptr) >> 6) | (*(sptr - 1) << 26)) |
((*(sptr) >> 7) | (*(sptr - 1) << 25)) |
((*(sptr) >> 8) | (*(sptr - 1) << 24)) |
((*(sptr) >> 9) | (*(sptr - 1) << 23)) |
((*(sptr) >> 10) | (*(sptr - 1) << 22)) |
((*(sptr) >> 11) | (*(sptr - 1) << 21)) |
((*(sptr) >> 12) | (*(sptr - 1) << 20)) |
((*(sptr) >> 13) | (*(sptr - 1) << 19)) |
((*(sptr) >> 14) | (*(sptr - 1) << 18)) |
((*(sptr) >> 15) | (*(sptr - 1) << 17)) |
((*(sptr) >> 16) | (*(sptr - 1) << 16)) |
((*(sptr) >> 17) | (*(sptr - 1) << 15)) |
((*(sptr) >> 18) | (*(sptr - 1) << 14)) |
((*(sptr) >> 19) | (*(sptr - 1) << 13));
}
}
}
static void
ferode_1_20(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) >> 20) | (*(sptr - 1) << 12)) &
((*(sptr) >> 19) | (*(sptr - 1) << 13)) &
((*(sptr) >> 18) | (*(sptr - 1) << 14)) &
((*(sptr) >> 17) | (*(sptr - 1) << 15)) &
((*(sptr) >> 16) | (*(sptr - 1) << 16)) &
((*(sptr) >> 15) | (*(sptr - 1) << 17)) &
((*(sptr) >> 14) | (*(sptr - 1) << 18)) &
((*(sptr) >> 13) | (*(sptr - 1) << 19)) &
((*(sptr) >> 12) | (*(sptr - 1) << 20)) &
((*(sptr) >> 11) | (*(sptr - 1) << 21)) &
((*(sptr) >> 10) | (*(sptr - 1) << 22)) &
((*(sptr) >> 9) | (*(sptr - 1) << 23)) &
((*(sptr) >> 8) | (*(sptr - 1) << 24)) &
((*(sptr) >> 7) | (*(sptr - 1) << 25)) &
((*(sptr) >> 6) | (*(sptr - 1) << 26)) &
((*(sptr) >> 5) | (*(sptr - 1) << 27)) &
((*(sptr) >> 4) | (*(sptr - 1) << 28)) &
((*(sptr) >> 3) | (*(sptr - 1) << 29)) &
((*(sptr) >> 2) | (*(sptr - 1) << 30)) &
((*(sptr) >> 1) | (*(sptr - 1) << 31)) &
(*sptr) &
((*(sptr) << 1) | (*(sptr + 1) >> 31)) &
((*(sptr) << 2) | (*(sptr + 1) >> 30)) &
((*(sptr) << 3) | (*(sptr + 1) >> 29)) &
((*(sptr) << 4) | (*(sptr + 1) >> 28)) &
((*(sptr) << 5) | (*(sptr + 1) >> 27)) &
((*(sptr) << 6) | (*(sptr + 1) >> 26)) &
((*(sptr) << 7) | (*(sptr + 1) >> 25)) &
((*(sptr) << 8) | (*(sptr + 1) >> 24)) &
((*(sptr) << 9) | (*(sptr + 1) >> 23)) &
((*(sptr) << 10) | (*(sptr + 1) >> 22)) &
((*(sptr) << 11) | (*(sptr + 1) >> 21)) &
((*(sptr) << 12) | (*(sptr + 1) >> 20)) &
((*(sptr) << 13) | (*(sptr + 1) >> 19)) &
((*(sptr) << 14) | (*(sptr + 1) >> 18)) &
((*(sptr) << 15) | (*(sptr + 1) >> 17)) &
((*(sptr) << 16) | (*(sptr + 1) >> 16)) &
((*(sptr) << 17) | (*(sptr + 1) >> 15)) &
((*(sptr) << 18) | (*(sptr + 1) >> 14)) &
((*(sptr) << 19) | (*(sptr + 1) >> 13));
}
}
}
static void
fdilate_1_21(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) << 20) | (*(sptr + 1) >> 12)) |
((*(sptr) << 19) | (*(sptr + 1) >> 13)) |
((*(sptr) << 18) | (*(sptr + 1) >> 14)) |
((*(sptr) << 17) | (*(sptr + 1) >> 15)) |
((*(sptr) << 16) | (*(sptr + 1) >> 16)) |
((*(sptr) << 15) | (*(sptr + 1) >> 17)) |
((*(sptr) << 14) | (*(sptr + 1) >> 18)) |
((*(sptr) << 13) | (*(sptr + 1) >> 19)) |
((*(sptr) << 12) | (*(sptr + 1) >> 20)) |
((*(sptr) << 11) | (*(sptr + 1) >> 21)) |
((*(sptr) << 10) | (*(sptr + 1) >> 22)) |
((*(sptr) << 9) | (*(sptr + 1) >> 23)) |
((*(sptr) << 8) | (*(sptr + 1) >> 24)) |
((*(sptr) << 7) | (*(sptr + 1) >> 25)) |
((*(sptr) << 6) | (*(sptr + 1) >> 26)) |
((*(sptr) << 5) | (*(sptr + 1) >> 27)) |
((*(sptr) << 4) | (*(sptr + 1) >> 28)) |
((*(sptr) << 3) | (*(sptr + 1) >> 29)) |
((*(sptr) << 2) | (*(sptr + 1) >> 30)) |
((*(sptr) << 1) | (*(sptr + 1) >> 31)) |
(*sptr) |
((*(sptr) >> 1) | (*(sptr - 1) << 31)) |
((*(sptr) >> 2) | (*(sptr - 1) << 30)) |
((*(sptr) >> 3) | (*(sptr - 1) << 29)) |
((*(sptr) >> 4) | (*(sptr - 1) << 28)) |
((*(sptr) >> 5) | (*(sptr - 1) << 27)) |
((*(sptr) >> 6) | (*(sptr - 1) << 26)) |
((*(sptr) >> 7) | (*(sptr - 1) << 25)) |
((*(sptr) >> 8) | (*(sptr - 1) << 24)) |
((*(sptr) >> 9) | (*(sptr - 1) << 23)) |
((*(sptr) >> 10) | (*(sptr - 1) << 22)) |
((*(sptr) >> 11) | (*(sptr - 1) << 21)) |
((*(sptr) >> 12) | (*(sptr - 1) << 20)) |
((*(sptr) >> 13) | (*(sptr - 1) << 19)) |
((*(sptr) >> 14) | (*(sptr - 1) << 18)) |
((*(sptr) >> 15) | (*(sptr - 1) << 17)) |
((*(sptr) >> 16) | (*(sptr - 1) << 16)) |
((*(sptr) >> 17) | (*(sptr - 1) << 15)) |
((*(sptr) >> 18) | (*(sptr - 1) << 14)) |
((*(sptr) >> 19) | (*(sptr - 1) << 13)) |
((*(sptr) >> 20) | (*(sptr - 1) << 12));
}
}
}
static void
ferode_1_21(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) >> 20) | (*(sptr - 1) << 12)) &
((*(sptr) >> 19) | (*(sptr - 1) << 13)) &
((*(sptr) >> 18) | (*(sptr - 1) << 14)) &
((*(sptr) >> 17) | (*(sptr - 1) << 15)) &
((*(sptr) >> 16) | (*(sptr - 1) << 16)) &
((*(sptr) >> 15) | (*(sptr - 1) << 17)) &
((*(sptr) >> 14) | (*(sptr - 1) << 18)) &
((*(sptr) >> 13) | (*(sptr - 1) << 19)) &
((*(sptr) >> 12) | (*(sptr - 1) << 20)) &
((*(sptr) >> 11) | (*(sptr - 1) << 21)) &
((*(sptr) >> 10) | (*(sptr - 1) << 22)) &
((*(sptr) >> 9) | (*(sptr - 1) << 23)) &
((*(sptr) >> 8) | (*(sptr - 1) << 24)) &
((*(sptr) >> 7) | (*(sptr - 1) << 25)) &
((*(sptr) >> 6) | (*(sptr - 1) << 26)) &
((*(sptr) >> 5) | (*(sptr - 1) << 27)) &
((*(sptr) >> 4) | (*(sptr - 1) << 28)) &
((*(sptr) >> 3) | (*(sptr - 1) << 29)) &
((*(sptr) >> 2) | (*(sptr - 1) << 30)) &
((*(sptr) >> 1) | (*(sptr - 1) << 31)) &
(*sptr) &
((*(sptr) << 1) | (*(sptr + 1) >> 31)) &
((*(sptr) << 2) | (*(sptr + 1) >> 30)) &
((*(sptr) << 3) | (*(sptr + 1) >> 29)) &
((*(sptr) << 4) | (*(sptr + 1) >> 28)) &
((*(sptr) << 5) | (*(sptr + 1) >> 27)) &
((*(sptr) << 6) | (*(sptr + 1) >> 26)) &
((*(sptr) << 7) | (*(sptr + 1) >> 25)) &
((*(sptr) << 8) | (*(sptr + 1) >> 24)) &
((*(sptr) << 9) | (*(sptr + 1) >> 23)) &
((*(sptr) << 10) | (*(sptr + 1) >> 22)) &
((*(sptr) << 11) | (*(sptr + 1) >> 21)) &
((*(sptr) << 12) | (*(sptr + 1) >> 20)) &
((*(sptr) << 13) | (*(sptr + 1) >> 19)) &
((*(sptr) << 14) | (*(sptr + 1) >> 18)) &
((*(sptr) << 15) | (*(sptr + 1) >> 17)) &
((*(sptr) << 16) | (*(sptr + 1) >> 16)) &
((*(sptr) << 17) | (*(sptr + 1) >> 15)) &
((*(sptr) << 18) | (*(sptr + 1) >> 14)) &
((*(sptr) << 19) | (*(sptr + 1) >> 13)) &
((*(sptr) << 20) | (*(sptr + 1) >> 12));
}
}
}
static void
fdilate_1_22(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) << 22) | (*(sptr + 1) >> 10)) |
((*(sptr) << 21) | (*(sptr + 1) >> 11)) |
((*(sptr) << 20) | (*(sptr + 1) >> 12)) |
((*(sptr) << 19) | (*(sptr + 1) >> 13)) |
((*(sptr) << 18) | (*(sptr + 1) >> 14)) |
((*(sptr) << 17) | (*(sptr + 1) >> 15)) |
((*(sptr) << 16) | (*(sptr + 1) >> 16)) |
((*(sptr) << 15) | (*(sptr + 1) >> 17)) |
((*(sptr) << 14) | (*(sptr + 1) >> 18)) |
((*(sptr) << 13) | (*(sptr + 1) >> 19)) |
((*(sptr) << 12) | (*(sptr + 1) >> 20)) |
((*(sptr) << 11) | (*(sptr + 1) >> 21)) |
((*(sptr) << 10) | (*(sptr + 1) >> 22)) |
((*(sptr) << 9) | (*(sptr + 1) >> 23)) |
((*(sptr) << 8) | (*(sptr + 1) >> 24)) |
((*(sptr) << 7) | (*(sptr + 1) >> 25)) |
((*(sptr) << 6) | (*(sptr + 1) >> 26)) |
((*(sptr) << 5) | (*(sptr + 1) >> 27)) |
((*(sptr) << 4) | (*(sptr + 1) >> 28)) |
((*(sptr) << 3) | (*(sptr + 1) >> 29)) |
((*(sptr) << 2) | (*(sptr + 1) >> 30)) |
((*(sptr) << 1) | (*(sptr + 1) >> 31)) |
(*sptr) |
((*(sptr) >> 1) | (*(sptr - 1) << 31)) |
((*(sptr) >> 2) | (*(sptr - 1) << 30)) |
((*(sptr) >> 3) | (*(sptr - 1) << 29)) |
((*(sptr) >> 4) | (*(sptr - 1) << 28)) |
((*(sptr) >> 5) | (*(sptr - 1) << 27)) |
((*(sptr) >> 6) | (*(sptr - 1) << 26)) |
((*(sptr) >> 7) | (*(sptr - 1) << 25)) |
((*(sptr) >> 8) | (*(sptr - 1) << 24)) |
((*(sptr) >> 9) | (*(sptr - 1) << 23)) |
((*(sptr) >> 10) | (*(sptr - 1) << 22)) |
((*(sptr) >> 11) | (*(sptr - 1) << 21)) |
((*(sptr) >> 12) | (*(sptr - 1) << 20)) |
((*(sptr) >> 13) | (*(sptr - 1) << 19)) |
((*(sptr) >> 14) | (*(sptr - 1) << 18)) |
((*(sptr) >> 15) | (*(sptr - 1) << 17)) |
((*(sptr) >> 16) | (*(sptr - 1) << 16)) |
((*(sptr) >> 17) | (*(sptr - 1) << 15)) |
((*(sptr) >> 18) | (*(sptr - 1) << 14)) |
((*(sptr) >> 19) | (*(sptr - 1) << 13)) |
((*(sptr) >> 20) | (*(sptr - 1) << 12)) |
((*(sptr) >> 21) | (*(sptr - 1) << 11)) |
((*(sptr) >> 22) | (*(sptr - 1) << 10));
}
}
}
static void
ferode_1_22(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) >> 22) | (*(sptr - 1) << 10)) &
((*(sptr) >> 21) | (*(sptr - 1) << 11)) &
((*(sptr) >> 20) | (*(sptr - 1) << 12)) &
((*(sptr) >> 19) | (*(sptr - 1) << 13)) &
((*(sptr) >> 18) | (*(sptr - 1) << 14)) &
((*(sptr) >> 17) | (*(sptr - 1) << 15)) &
((*(sptr) >> 16) | (*(sptr - 1) << 16)) &
((*(sptr) >> 15) | (*(sptr - 1) << 17)) &
((*(sptr) >> 14) | (*(sptr - 1) << 18)) &
((*(sptr) >> 13) | (*(sptr - 1) << 19)) &
((*(sptr) >> 12) | (*(sptr - 1) << 20)) &
((*(sptr) >> 11) | (*(sptr - 1) << 21)) &
((*(sptr) >> 10) | (*(sptr - 1) << 22)) &
((*(sptr) >> 9) | (*(sptr - 1) << 23)) &
((*(sptr) >> 8) | (*(sptr - 1) << 24)) &
((*(sptr) >> 7) | (*(sptr - 1) << 25)) &
((*(sptr) >> 6) | (*(sptr - 1) << 26)) &
((*(sptr) >> 5) | (*(sptr - 1) << 27)) &
((*(sptr) >> 4) | (*(sptr - 1) << 28)) &
((*(sptr) >> 3) | (*(sptr - 1) << 29)) &
((*(sptr) >> 2) | (*(sptr - 1) << 30)) &
((*(sptr) >> 1) | (*(sptr - 1) << 31)) &
(*sptr) &
((*(sptr) << 1) | (*(sptr + 1) >> 31)) &
((*(sptr) << 2) | (*(sptr + 1) >> 30)) &
((*(sptr) << 3) | (*(sptr + 1) >> 29)) &
((*(sptr) << 4) | (*(sptr + 1) >> 28)) &
((*(sptr) << 5) | (*(sptr + 1) >> 27)) &
((*(sptr) << 6) | (*(sptr + 1) >> 26)) &
((*(sptr) << 7) | (*(sptr + 1) >> 25)) &
((*(sptr) << 8) | (*(sptr + 1) >> 24)) &
((*(sptr) << 9) | (*(sptr + 1) >> 23)) &
((*(sptr) << 10) | (*(sptr + 1) >> 22)) &
((*(sptr) << 11) | (*(sptr + 1) >> 21)) &
((*(sptr) << 12) | (*(sptr + 1) >> 20)) &
((*(sptr) << 13) | (*(sptr + 1) >> 19)) &
((*(sptr) << 14) | (*(sptr + 1) >> 18)) &
((*(sptr) << 15) | (*(sptr + 1) >> 17)) &
((*(sptr) << 16) | (*(sptr + 1) >> 16)) &
((*(sptr) << 17) | (*(sptr + 1) >> 15)) &
((*(sptr) << 18) | (*(sptr + 1) >> 14)) &
((*(sptr) << 19) | (*(sptr + 1) >> 13)) &
((*(sptr) << 20) | (*(sptr + 1) >> 12)) &
((*(sptr) << 21) | (*(sptr + 1) >> 11)) &
((*(sptr) << 22) | (*(sptr + 1) >> 10));
}
}
}
static void
fdilate_1_23(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) << 25) | (*(sptr + 1) >> 7)) |
((*(sptr) << 24) | (*(sptr + 1) >> 8)) |
((*(sptr) << 23) | (*(sptr + 1) >> 9)) |
((*(sptr) << 22) | (*(sptr + 1) >> 10)) |
((*(sptr) << 21) | (*(sptr + 1) >> 11)) |
((*(sptr) << 20) | (*(sptr + 1) >> 12)) |
((*(sptr) << 19) | (*(sptr + 1) >> 13)) |
((*(sptr) << 18) | (*(sptr + 1) >> 14)) |
((*(sptr) << 17) | (*(sptr + 1) >> 15)) |
((*(sptr) << 16) | (*(sptr + 1) >> 16)) |
((*(sptr) << 15) | (*(sptr + 1) >> 17)) |
((*(sptr) << 14) | (*(sptr + 1) >> 18)) |
((*(sptr) << 13) | (*(sptr + 1) >> 19)) |
((*(sptr) << 12) | (*(sptr + 1) >> 20)) |
((*(sptr) << 11) | (*(sptr + 1) >> 21)) |
((*(sptr) << 10) | (*(sptr + 1) >> 22)) |
((*(sptr) << 9) | (*(sptr + 1) >> 23)) |
((*(sptr) << 8) | (*(sptr + 1) >> 24)) |
((*(sptr) << 7) | (*(sptr + 1) >> 25)) |
((*(sptr) << 6) | (*(sptr + 1) >> 26)) |
((*(sptr) << 5) | (*(sptr + 1) >> 27)) |
((*(sptr) << 4) | (*(sptr + 1) >> 28)) |
((*(sptr) << 3) | (*(sptr + 1) >> 29)) |
((*(sptr) << 2) | (*(sptr + 1) >> 30)) |
((*(sptr) << 1) | (*(sptr + 1) >> 31)) |
(*sptr) |
((*(sptr) >> 1) | (*(sptr - 1) << 31)) |
((*(sptr) >> 2) | (*(sptr - 1) << 30)) |
((*(sptr) >> 3) | (*(sptr - 1) << 29)) |
((*(sptr) >> 4) | (*(sptr - 1) << 28)) |
((*(sptr) >> 5) | (*(sptr - 1) << 27)) |
((*(sptr) >> 6) | (*(sptr - 1) << 26)) |
((*(sptr) >> 7) | (*(sptr - 1) << 25)) |
((*(sptr) >> 8) | (*(sptr - 1) << 24)) |
((*(sptr) >> 9) | (*(sptr - 1) << 23)) |
((*(sptr) >> 10) | (*(sptr - 1) << 22)) |
((*(sptr) >> 11) | (*(sptr - 1) << 21)) |
((*(sptr) >> 12) | (*(sptr - 1) << 20)) |
((*(sptr) >> 13) | (*(sptr - 1) << 19)) |
((*(sptr) >> 14) | (*(sptr - 1) << 18)) |
((*(sptr) >> 15) | (*(sptr - 1) << 17)) |
((*(sptr) >> 16) | (*(sptr - 1) << 16)) |
((*(sptr) >> 17) | (*(sptr - 1) << 15)) |
((*(sptr) >> 18) | (*(sptr - 1) << 14)) |
((*(sptr) >> 19) | (*(sptr - 1) << 13)) |
((*(sptr) >> 20) | (*(sptr - 1) << 12)) |
((*(sptr) >> 21) | (*(sptr - 1) << 11)) |
((*(sptr) >> 22) | (*(sptr - 1) << 10)) |
((*(sptr) >> 23) | (*(sptr - 1) << 9)) |
((*(sptr) >> 24) | (*(sptr - 1) << 8));
}
}
}
static void
ferode_1_23(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) >> 25) | (*(sptr - 1) << 7)) &
((*(sptr) >> 24) | (*(sptr - 1) << 8)) &
((*(sptr) >> 23) | (*(sptr - 1) << 9)) &
((*(sptr) >> 22) | (*(sptr - 1) << 10)) &
((*(sptr) >> 21) | (*(sptr - 1) << 11)) &
((*(sptr) >> 20) | (*(sptr - 1) << 12)) &
((*(sptr) >> 19) | (*(sptr - 1) << 13)) &
((*(sptr) >> 18) | (*(sptr - 1) << 14)) &
((*(sptr) >> 17) | (*(sptr - 1) << 15)) &
((*(sptr) >> 16) | (*(sptr - 1) << 16)) &
((*(sptr) >> 15) | (*(sptr - 1) << 17)) &
((*(sptr) >> 14) | (*(sptr - 1) << 18)) &
((*(sptr) >> 13) | (*(sptr - 1) << 19)) &
((*(sptr) >> 12) | (*(sptr - 1) << 20)) &
((*(sptr) >> 11) | (*(sptr - 1) << 21)) &
((*(sptr) >> 10) | (*(sptr - 1) << 22)) &
((*(sptr) >> 9) | (*(sptr - 1) << 23)) &
((*(sptr) >> 8) | (*(sptr - 1) << 24)) &
((*(sptr) >> 7) | (*(sptr - 1) << 25)) &
((*(sptr) >> 6) | (*(sptr - 1) << 26)) &
((*(sptr) >> 5) | (*(sptr - 1) << 27)) &
((*(sptr) >> 4) | (*(sptr - 1) << 28)) &
((*(sptr) >> 3) | (*(sptr - 1) << 29)) &
((*(sptr) >> 2) | (*(sptr - 1) << 30)) &
((*(sptr) >> 1) | (*(sptr - 1) << 31)) &
(*sptr) &
((*(sptr) << 1) | (*(sptr + 1) >> 31)) &
((*(sptr) << 2) | (*(sptr + 1) >> 30)) &
((*(sptr) << 3) | (*(sptr + 1) >> 29)) &
((*(sptr) << 4) | (*(sptr + 1) >> 28)) &
((*(sptr) << 5) | (*(sptr + 1) >> 27)) &
((*(sptr) << 6) | (*(sptr + 1) >> 26)) &
((*(sptr) << 7) | (*(sptr + 1) >> 25)) &
((*(sptr) << 8) | (*(sptr + 1) >> 24)) &
((*(sptr) << 9) | (*(sptr + 1) >> 23)) &
((*(sptr) << 10) | (*(sptr + 1) >> 22)) &
((*(sptr) << 11) | (*(sptr + 1) >> 21)) &
((*(sptr) << 12) | (*(sptr + 1) >> 20)) &
((*(sptr) << 13) | (*(sptr + 1) >> 19)) &
((*(sptr) << 14) | (*(sptr + 1) >> 18)) &
((*(sptr) << 15) | (*(sptr + 1) >> 17)) &
((*(sptr) << 16) | (*(sptr + 1) >> 16)) &
((*(sptr) << 17) | (*(sptr + 1) >> 15)) &
((*(sptr) << 18) | (*(sptr + 1) >> 14)) &
((*(sptr) << 19) | (*(sptr + 1) >> 13)) &
((*(sptr) << 20) | (*(sptr + 1) >> 12)) &
((*(sptr) << 21) | (*(sptr + 1) >> 11)) &
((*(sptr) << 22) | (*(sptr + 1) >> 10)) &
((*(sptr) << 23) | (*(sptr + 1) >> 9)) &
((*(sptr) << 24) | (*(sptr + 1) >> 8));
}
}
}
static void
fdilate_1_24(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) << 25) | (*(sptr + 1) >> 7)) |
((*(sptr) << 24) | (*(sptr + 1) >> 8)) |
((*(sptr) << 23) | (*(sptr + 1) >> 9)) |
((*(sptr) << 22) | (*(sptr + 1) >> 10)) |
((*(sptr) << 21) | (*(sptr + 1) >> 11)) |
((*(sptr) << 20) | (*(sptr + 1) >> 12)) |
((*(sptr) << 19) | (*(sptr + 1) >> 13)) |
((*(sptr) << 18) | (*(sptr + 1) >> 14)) |
((*(sptr) << 17) | (*(sptr + 1) >> 15)) |
((*(sptr) << 16) | (*(sptr + 1) >> 16)) |
((*(sptr) << 15) | (*(sptr + 1) >> 17)) |
((*(sptr) << 14) | (*(sptr + 1) >> 18)) |
((*(sptr) << 13) | (*(sptr + 1) >> 19)) |
((*(sptr) << 12) | (*(sptr + 1) >> 20)) |
((*(sptr) << 11) | (*(sptr + 1) >> 21)) |
((*(sptr) << 10) | (*(sptr + 1) >> 22)) |
((*(sptr) << 9) | (*(sptr + 1) >> 23)) |
((*(sptr) << 8) | (*(sptr + 1) >> 24)) |
((*(sptr) << 7) | (*(sptr + 1) >> 25)) |
((*(sptr) << 6) | (*(sptr + 1) >> 26)) |
((*(sptr) << 5) | (*(sptr + 1) >> 27)) |
((*(sptr) << 4) | (*(sptr + 1) >> 28)) |
((*(sptr) << 3) | (*(sptr + 1) >> 29)) |
((*(sptr) << 2) | (*(sptr + 1) >> 30)) |
((*(sptr) << 1) | (*(sptr + 1) >> 31)) |
(*sptr) |
((*(sptr) >> 1) | (*(sptr - 1) << 31)) |
((*(sptr) >> 2) | (*(sptr - 1) << 30)) |
((*(sptr) >> 3) | (*(sptr - 1) << 29)) |
((*(sptr) >> 4) | (*(sptr - 1) << 28)) |
((*(sptr) >> 5) | (*(sptr - 1) << 27)) |
((*(sptr) >> 6) | (*(sptr - 1) << 26)) |
((*(sptr) >> 7) | (*(sptr - 1) << 25)) |
((*(sptr) >> 8) | (*(sptr - 1) << 24)) |
((*(sptr) >> 9) | (*(sptr - 1) << 23)) |
((*(sptr) >> 10) | (*(sptr - 1) << 22)) |
((*(sptr) >> 11) | (*(sptr - 1) << 21)) |
((*(sptr) >> 12) | (*(sptr - 1) << 20)) |
((*(sptr) >> 13) | (*(sptr - 1) << 19)) |
((*(sptr) >> 14) | (*(sptr - 1) << 18)) |
((*(sptr) >> 15) | (*(sptr - 1) << 17)) |
((*(sptr) >> 16) | (*(sptr - 1) << 16)) |
((*(sptr) >> 17) | (*(sptr - 1) << 15)) |
((*(sptr) >> 18) | (*(sptr - 1) << 14)) |
((*(sptr) >> 19) | (*(sptr - 1) << 13)) |
((*(sptr) >> 20) | (*(sptr - 1) << 12)) |
((*(sptr) >> 21) | (*(sptr - 1) << 11)) |
((*(sptr) >> 22) | (*(sptr - 1) << 10)) |
((*(sptr) >> 23) | (*(sptr - 1) << 9)) |
((*(sptr) >> 24) | (*(sptr - 1) << 8)) |
((*(sptr) >> 25) | (*(sptr - 1) << 7));
}
}
}
static void
ferode_1_24(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) >> 25) | (*(sptr - 1) << 7)) &
((*(sptr) >> 24) | (*(sptr - 1) << 8)) &
((*(sptr) >> 23) | (*(sptr - 1) << 9)) &
((*(sptr) >> 22) | (*(sptr - 1) << 10)) &
((*(sptr) >> 21) | (*(sptr - 1) << 11)) &
((*(sptr) >> 20) | (*(sptr - 1) << 12)) &
((*(sptr) >> 19) | (*(sptr - 1) << 13)) &
((*(sptr) >> 18) | (*(sptr - 1) << 14)) &
((*(sptr) >> 17) | (*(sptr - 1) << 15)) &
((*(sptr) >> 16) | (*(sptr - 1) << 16)) &
((*(sptr) >> 15) | (*(sptr - 1) << 17)) &
((*(sptr) >> 14) | (*(sptr - 1) << 18)) &
((*(sptr) >> 13) | (*(sptr - 1) << 19)) &
((*(sptr) >> 12) | (*(sptr - 1) << 20)) &
((*(sptr) >> 11) | (*(sptr - 1) << 21)) &
((*(sptr) >> 10) | (*(sptr - 1) << 22)) &
((*(sptr) >> 9) | (*(sptr - 1) << 23)) &
((*(sptr) >> 8) | (*(sptr - 1) << 24)) &
((*(sptr) >> 7) | (*(sptr - 1) << 25)) &
((*(sptr) >> 6) | (*(sptr - 1) << 26)) &
((*(sptr) >> 5) | (*(sptr - 1) << 27)) &
((*(sptr) >> 4) | (*(sptr - 1) << 28)) &
((*(sptr) >> 3) | (*(sptr - 1) << 29)) &
((*(sptr) >> 2) | (*(sptr - 1) << 30)) &
((*(sptr) >> 1) | (*(sptr - 1) << 31)) &
(*sptr) &
((*(sptr) << 1) | (*(sptr + 1) >> 31)) &
((*(sptr) << 2) | (*(sptr + 1) >> 30)) &
((*(sptr) << 3) | (*(sptr + 1) >> 29)) &
((*(sptr) << 4) | (*(sptr + 1) >> 28)) &
((*(sptr) << 5) | (*(sptr + 1) >> 27)) &
((*(sptr) << 6) | (*(sptr + 1) >> 26)) &
((*(sptr) << 7) | (*(sptr + 1) >> 25)) &
((*(sptr) << 8) | (*(sptr + 1) >> 24)) &
((*(sptr) << 9) | (*(sptr + 1) >> 23)) &
((*(sptr) << 10) | (*(sptr + 1) >> 22)) &
((*(sptr) << 11) | (*(sptr + 1) >> 21)) &
((*(sptr) << 12) | (*(sptr + 1) >> 20)) &
((*(sptr) << 13) | (*(sptr + 1) >> 19)) &
((*(sptr) << 14) | (*(sptr + 1) >> 18)) &
((*(sptr) << 15) | (*(sptr + 1) >> 17)) &
((*(sptr) << 16) | (*(sptr + 1) >> 16)) &
((*(sptr) << 17) | (*(sptr + 1) >> 15)) &
((*(sptr) << 18) | (*(sptr + 1) >> 14)) &
((*(sptr) << 19) | (*(sptr + 1) >> 13)) &
((*(sptr) << 20) | (*(sptr + 1) >> 12)) &
((*(sptr) << 21) | (*(sptr + 1) >> 11)) &
((*(sptr) << 22) | (*(sptr + 1) >> 10)) &
((*(sptr) << 23) | (*(sptr + 1) >> 9)) &
((*(sptr) << 24) | (*(sptr + 1) >> 8)) &
((*(sptr) << 25) | (*(sptr + 1) >> 7));
}
}
}
static void
fdilate_1_25(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr + wpls)) |
(*sptr);
}
}
}
static void
ferode_1_25(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr - wpls)) &
(*sptr);
}
}
}
static void
fdilate_1_26(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr + wpls)) |
(*sptr) |
(*(sptr - wpls));
}
}
}
static void
ferode_1_26(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr - wpls)) &
(*sptr) &
(*(sptr + wpls));
}
}
}
static void
fdilate_1_27(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2;
wpls2 = 2 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr + wpls2)) |
(*(sptr + wpls)) |
(*sptr) |
(*(sptr - wpls));
}
}
}
static void
ferode_1_27(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2;
wpls2 = 2 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr - wpls2)) &
(*(sptr - wpls)) &
(*sptr) &
(*(sptr + wpls));
}
}
}
static void
fdilate_1_28(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2;
wpls2 = 2 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr + wpls2)) |
(*(sptr + wpls)) |
(*sptr) |
(*(sptr - wpls)) |
(*(sptr - wpls2));
}
}
}
static void
ferode_1_28(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2;
wpls2 = 2 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr - wpls2)) &
(*(sptr - wpls)) &
(*sptr) &
(*(sptr + wpls)) &
(*(sptr + wpls2));
}
}
}
static void
fdilate_1_29(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr + wpls3)) |
(*(sptr + wpls2)) |
(*(sptr + wpls)) |
(*sptr) |
(*(sptr - wpls)) |
(*(sptr - wpls2));
}
}
}
static void
ferode_1_29(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr - wpls3)) &
(*(sptr - wpls2)) &
(*(sptr - wpls)) &
(*sptr) &
(*(sptr + wpls)) &
(*(sptr + wpls2));
}
}
}
static void
fdilate_1_30(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr + wpls3)) |
(*(sptr + wpls2)) |
(*(sptr + wpls)) |
(*sptr) |
(*(sptr - wpls)) |
(*(sptr - wpls2)) |
(*(sptr - wpls3));
}
}
}
static void
ferode_1_30(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr - wpls3)) &
(*(sptr - wpls2)) &
(*(sptr - wpls)) &
(*sptr) &
(*(sptr + wpls)) &
(*(sptr + wpls2)) &
(*(sptr + wpls3));
}
}
}
static void
fdilate_1_31(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr + wpls4)) |
(*(sptr + wpls3)) |
(*(sptr + wpls2)) |
(*(sptr + wpls)) |
(*sptr) |
(*(sptr - wpls)) |
(*(sptr - wpls2)) |
(*(sptr - wpls3));
}
}
}
static void
ferode_1_31(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr - wpls4)) &
(*(sptr - wpls3)) &
(*(sptr - wpls2)) &
(*(sptr - wpls)) &
(*sptr) &
(*(sptr + wpls)) &
(*(sptr + wpls2)) &
(*(sptr + wpls3));
}
}
}
static void
fdilate_1_32(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr + wpls4)) |
(*(sptr + wpls3)) |
(*(sptr + wpls2)) |
(*(sptr + wpls)) |
(*sptr) |
(*(sptr - wpls)) |
(*(sptr - wpls2)) |
(*(sptr - wpls3)) |
(*(sptr - wpls4));
}
}
}
static void
ferode_1_32(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr - wpls4)) &
(*(sptr - wpls3)) &
(*(sptr - wpls2)) &
(*(sptr - wpls)) &
(*sptr) &
(*(sptr + wpls)) &
(*(sptr + wpls2)) &
(*(sptr + wpls3)) &
(*(sptr + wpls4));
}
}
}
static void
fdilate_1_33(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
l_int32 wpls5;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
wpls5 = 5 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr + wpls5)) |
(*(sptr + wpls4)) |
(*(sptr + wpls3)) |
(*(sptr + wpls2)) |
(*(sptr + wpls)) |
(*sptr) |
(*(sptr - wpls)) |
(*(sptr - wpls2)) |
(*(sptr - wpls3)) |
(*(sptr - wpls4));
}
}
}
static void
ferode_1_33(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
l_int32 wpls5;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
wpls5 = 5 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr - wpls5)) &
(*(sptr - wpls4)) &
(*(sptr - wpls3)) &
(*(sptr - wpls2)) &
(*(sptr - wpls)) &
(*sptr) &
(*(sptr + wpls)) &
(*(sptr + wpls2)) &
(*(sptr + wpls3)) &
(*(sptr + wpls4));
}
}
}
static void
fdilate_1_34(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
l_int32 wpls5;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
wpls5 = 5 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr + wpls5)) |
(*(sptr + wpls4)) |
(*(sptr + wpls3)) |
(*(sptr + wpls2)) |
(*(sptr + wpls)) |
(*sptr) |
(*(sptr - wpls)) |
(*(sptr - wpls2)) |
(*(sptr - wpls3)) |
(*(sptr - wpls4)) |
(*(sptr - wpls5));
}
}
}
static void
ferode_1_34(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
l_int32 wpls5;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
wpls5 = 5 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr - wpls5)) &
(*(sptr - wpls4)) &
(*(sptr - wpls3)) &
(*(sptr - wpls2)) &
(*(sptr - wpls)) &
(*sptr) &
(*(sptr + wpls)) &
(*(sptr + wpls2)) &
(*(sptr + wpls3)) &
(*(sptr + wpls4)) &
(*(sptr + wpls5));
}
}
}
static void
fdilate_1_35(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
l_int32 wpls5, wpls6;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
wpls5 = 5 * wpls;
wpls6 = 6 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr + wpls6)) |
(*(sptr + wpls5)) |
(*(sptr + wpls4)) |
(*(sptr + wpls3)) |
(*(sptr + wpls2)) |
(*(sptr + wpls)) |
(*sptr) |
(*(sptr - wpls)) |
(*(sptr - wpls2)) |
(*(sptr - wpls3)) |
(*(sptr - wpls4)) |
(*(sptr - wpls5));
}
}
}
static void
ferode_1_35(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
l_int32 wpls5, wpls6;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
wpls5 = 5 * wpls;
wpls6 = 6 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr - wpls6)) &
(*(sptr - wpls5)) &
(*(sptr - wpls4)) &
(*(sptr - wpls3)) &
(*(sptr - wpls2)) &
(*(sptr - wpls)) &
(*sptr) &
(*(sptr + wpls)) &
(*(sptr + wpls2)) &
(*(sptr + wpls3)) &
(*(sptr + wpls4)) &
(*(sptr + wpls5));
}
}
}
static void
fdilate_1_36(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
l_int32 wpls5, wpls6;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
wpls5 = 5 * wpls;
wpls6 = 6 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr + wpls6)) |
(*(sptr + wpls5)) |
(*(sptr + wpls4)) |
(*(sptr + wpls3)) |
(*(sptr + wpls2)) |
(*(sptr + wpls)) |
(*sptr) |
(*(sptr - wpls)) |
(*(sptr - wpls2)) |
(*(sptr - wpls3)) |
(*(sptr - wpls4)) |
(*(sptr - wpls5)) |
(*(sptr - wpls6));
}
}
}
static void
ferode_1_36(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
l_int32 wpls5, wpls6;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
wpls5 = 5 * wpls;
wpls6 = 6 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr - wpls6)) &
(*(sptr - wpls5)) &
(*(sptr - wpls4)) &
(*(sptr - wpls3)) &
(*(sptr - wpls2)) &
(*(sptr - wpls)) &
(*sptr) &
(*(sptr + wpls)) &
(*(sptr + wpls2)) &
(*(sptr + wpls3)) &
(*(sptr + wpls4)) &
(*(sptr + wpls5)) &
(*(sptr + wpls6));
}
}
}
static void
fdilate_1_37(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
l_int32 wpls5, wpls6, wpls7;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
wpls5 = 5 * wpls;
wpls6 = 6 * wpls;
wpls7 = 7 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr + wpls7)) |
(*(sptr + wpls6)) |
(*(sptr + wpls5)) |
(*(sptr + wpls4)) |
(*(sptr + wpls3)) |
(*(sptr + wpls2)) |
(*(sptr + wpls)) |
(*sptr) |
(*(sptr - wpls)) |
(*(sptr - wpls2)) |
(*(sptr - wpls3)) |
(*(sptr - wpls4)) |
(*(sptr - wpls5)) |
(*(sptr - wpls6));
}
}
}
static void
ferode_1_37(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
l_int32 wpls5, wpls6, wpls7;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
wpls5 = 5 * wpls;
wpls6 = 6 * wpls;
wpls7 = 7 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr - wpls7)) &
(*(sptr - wpls6)) &
(*(sptr - wpls5)) &
(*(sptr - wpls4)) &
(*(sptr - wpls3)) &
(*(sptr - wpls2)) &
(*(sptr - wpls)) &
(*sptr) &
(*(sptr + wpls)) &
(*(sptr + wpls2)) &
(*(sptr + wpls3)) &
(*(sptr + wpls4)) &
(*(sptr + wpls5)) &
(*(sptr + wpls6));
}
}
}
static void
fdilate_1_38(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
l_int32 wpls5, wpls6, wpls7;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
wpls5 = 5 * wpls;
wpls6 = 6 * wpls;
wpls7 = 7 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr + wpls7)) |
(*(sptr + wpls6)) |
(*(sptr + wpls5)) |
(*(sptr + wpls4)) |
(*(sptr + wpls3)) |
(*(sptr + wpls2)) |
(*(sptr + wpls)) |
(*sptr) |
(*(sptr - wpls)) |
(*(sptr - wpls2)) |
(*(sptr - wpls3)) |
(*(sptr - wpls4)) |
(*(sptr - wpls5)) |
(*(sptr - wpls6)) |
(*(sptr - wpls7));
}
}
}
static void
ferode_1_38(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
l_int32 wpls5, wpls6, wpls7;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
wpls5 = 5 * wpls;
wpls6 = 6 * wpls;
wpls7 = 7 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr - wpls7)) &
(*(sptr - wpls6)) &
(*(sptr - wpls5)) &
(*(sptr - wpls4)) &
(*(sptr - wpls3)) &
(*(sptr - wpls2)) &
(*(sptr - wpls)) &
(*sptr) &
(*(sptr + wpls)) &
(*(sptr + wpls2)) &
(*(sptr + wpls3)) &
(*(sptr + wpls4)) &
(*(sptr + wpls5)) &
(*(sptr + wpls6)) &
(*(sptr + wpls7));
}
}
}
static void
fdilate_1_39(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
l_int32 wpls5, wpls6, wpls7, wpls8;
l_int32 wpls9, wpls10;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
wpls5 = 5 * wpls;
wpls6 = 6 * wpls;
wpls7 = 7 * wpls;
wpls8 = 8 * wpls;
wpls9 = 9 * wpls;
wpls10 = 10 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr + wpls10)) |
(*(sptr + wpls9)) |
(*(sptr + wpls8)) |
(*(sptr + wpls7)) |
(*(sptr + wpls6)) |
(*(sptr + wpls5)) |
(*(sptr + wpls4)) |
(*(sptr + wpls3)) |
(*(sptr + wpls2)) |
(*(sptr + wpls)) |
(*sptr) |
(*(sptr - wpls)) |
(*(sptr - wpls2)) |
(*(sptr - wpls3)) |
(*(sptr - wpls4)) |
(*(sptr - wpls5)) |
(*(sptr - wpls6)) |
(*(sptr - wpls7)) |
(*(sptr - wpls8)) |
(*(sptr - wpls9));
}
}
}
static void
ferode_1_39(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
l_int32 wpls5, wpls6, wpls7, wpls8;
l_int32 wpls9, wpls10;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
wpls5 = 5 * wpls;
wpls6 = 6 * wpls;
wpls7 = 7 * wpls;
wpls8 = 8 * wpls;
wpls9 = 9 * wpls;
wpls10 = 10 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr - wpls10)) &
(*(sptr - wpls9)) &
(*(sptr - wpls8)) &
(*(sptr - wpls7)) &
(*(sptr - wpls6)) &
(*(sptr - wpls5)) &
(*(sptr - wpls4)) &
(*(sptr - wpls3)) &
(*(sptr - wpls2)) &
(*(sptr - wpls)) &
(*sptr) &
(*(sptr + wpls)) &
(*(sptr + wpls2)) &
(*(sptr + wpls3)) &
(*(sptr + wpls4)) &
(*(sptr + wpls5)) &
(*(sptr + wpls6)) &
(*(sptr + wpls7)) &
(*(sptr + wpls8)) &
(*(sptr + wpls9));
}
}
}
static void
fdilate_1_40(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
l_int32 wpls5, wpls6, wpls7, wpls8;
l_int32 wpls9, wpls10;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
wpls5 = 5 * wpls;
wpls6 = 6 * wpls;
wpls7 = 7 * wpls;
wpls8 = 8 * wpls;
wpls9 = 9 * wpls;
wpls10 = 10 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr + wpls10)) |
(*(sptr + wpls9)) |
(*(sptr + wpls8)) |
(*(sptr + wpls7)) |
(*(sptr + wpls6)) |
(*(sptr + wpls5)) |
(*(sptr + wpls4)) |
(*(sptr + wpls3)) |
(*(sptr + wpls2)) |
(*(sptr + wpls)) |
(*sptr) |
(*(sptr - wpls)) |
(*(sptr - wpls2)) |
(*(sptr - wpls3)) |
(*(sptr - wpls4)) |
(*(sptr - wpls5)) |
(*(sptr - wpls6)) |
(*(sptr - wpls7)) |
(*(sptr - wpls8)) |
(*(sptr - wpls9)) |
(*(sptr - wpls10));
}
}
}
static void
ferode_1_40(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
l_int32 wpls5, wpls6, wpls7, wpls8;
l_int32 wpls9, wpls10;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
wpls5 = 5 * wpls;
wpls6 = 6 * wpls;
wpls7 = 7 * wpls;
wpls8 = 8 * wpls;
wpls9 = 9 * wpls;
wpls10 = 10 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr - wpls10)) &
(*(sptr - wpls9)) &
(*(sptr - wpls8)) &
(*(sptr - wpls7)) &
(*(sptr - wpls6)) &
(*(sptr - wpls5)) &
(*(sptr - wpls4)) &
(*(sptr - wpls3)) &
(*(sptr - wpls2)) &
(*(sptr - wpls)) &
(*sptr) &
(*(sptr + wpls)) &
(*(sptr + wpls2)) &
(*(sptr + wpls3)) &
(*(sptr + wpls4)) &
(*(sptr + wpls5)) &
(*(sptr + wpls6)) &
(*(sptr + wpls7)) &
(*(sptr + wpls8)) &
(*(sptr + wpls9)) &
(*(sptr + wpls10));
}
}
}
static void
fdilate_1_41(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
l_int32 wpls5, wpls6, wpls7, wpls8;
l_int32 wpls9, wpls10, wpls11, wpls12;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
wpls5 = 5 * wpls;
wpls6 = 6 * wpls;
wpls7 = 7 * wpls;
wpls8 = 8 * wpls;
wpls9 = 9 * wpls;
wpls10 = 10 * wpls;
wpls11 = 11 * wpls;
wpls12 = 12 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr + wpls12)) |
(*(sptr + wpls11)) |
(*(sptr + wpls10)) |
(*(sptr + wpls9)) |
(*(sptr + wpls8)) |
(*(sptr + wpls7)) |
(*(sptr + wpls6)) |
(*(sptr + wpls5)) |
(*(sptr + wpls4)) |
(*(sptr + wpls3)) |
(*(sptr + wpls2)) |
(*(sptr + wpls)) |
(*sptr) |
(*(sptr - wpls)) |
(*(sptr - wpls2)) |
(*(sptr - wpls3)) |
(*(sptr - wpls4)) |
(*(sptr - wpls5)) |
(*(sptr - wpls6)) |
(*(sptr - wpls7)) |
(*(sptr - wpls8)) |
(*(sptr - wpls9)) |
(*(sptr - wpls10)) |
(*(sptr - wpls11)) |
(*(sptr - wpls12));
}
}
}
static void
ferode_1_41(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
l_int32 wpls5, wpls6, wpls7, wpls8;
l_int32 wpls9, wpls10, wpls11, wpls12;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
wpls5 = 5 * wpls;
wpls6 = 6 * wpls;
wpls7 = 7 * wpls;
wpls8 = 8 * wpls;
wpls9 = 9 * wpls;
wpls10 = 10 * wpls;
wpls11 = 11 * wpls;
wpls12 = 12 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr - wpls12)) &
(*(sptr - wpls11)) &
(*(sptr - wpls10)) &
(*(sptr - wpls9)) &
(*(sptr - wpls8)) &
(*(sptr - wpls7)) &
(*(sptr - wpls6)) &
(*(sptr - wpls5)) &
(*(sptr - wpls4)) &
(*(sptr - wpls3)) &
(*(sptr - wpls2)) &
(*(sptr - wpls)) &
(*sptr) &
(*(sptr + wpls)) &
(*(sptr + wpls2)) &
(*(sptr + wpls3)) &
(*(sptr + wpls4)) &
(*(sptr + wpls5)) &
(*(sptr + wpls6)) &
(*(sptr + wpls7)) &
(*(sptr + wpls8)) &
(*(sptr + wpls9)) &
(*(sptr + wpls10)) &
(*(sptr + wpls11)) &
(*(sptr + wpls12));
}
}
}
static void
fdilate_1_42(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
l_int32 wpls5, wpls6, wpls7, wpls8;
l_int32 wpls9, wpls10, wpls11, wpls12;
l_int32 wpls13, wpls14, wpls15;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
wpls5 = 5 * wpls;
wpls6 = 6 * wpls;
wpls7 = 7 * wpls;
wpls8 = 8 * wpls;
wpls9 = 9 * wpls;
wpls10 = 10 * wpls;
wpls11 = 11 * wpls;
wpls12 = 12 * wpls;
wpls13 = 13 * wpls;
wpls14 = 14 * wpls;
wpls15 = 15 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr + wpls15)) |
(*(sptr + wpls14)) |
(*(sptr + wpls13)) |
(*(sptr + wpls12)) |
(*(sptr + wpls11)) |
(*(sptr + wpls10)) |
(*(sptr + wpls9)) |
(*(sptr + wpls8)) |
(*(sptr + wpls7)) |
(*(sptr + wpls6)) |
(*(sptr + wpls5)) |
(*(sptr + wpls4)) |
(*(sptr + wpls3)) |
(*(sptr + wpls2)) |
(*(sptr + wpls)) |
(*sptr) |
(*(sptr - wpls)) |
(*(sptr - wpls2)) |
(*(sptr - wpls3)) |
(*(sptr - wpls4)) |
(*(sptr - wpls5)) |
(*(sptr - wpls6)) |
(*(sptr - wpls7)) |
(*(sptr - wpls8)) |
(*(sptr - wpls9)) |
(*(sptr - wpls10)) |
(*(sptr - wpls11)) |
(*(sptr - wpls12)) |
(*(sptr - wpls13)) |
(*(sptr - wpls14));
}
}
}
static void
ferode_1_42(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
l_int32 wpls5, wpls6, wpls7, wpls8;
l_int32 wpls9, wpls10, wpls11, wpls12;
l_int32 wpls13, wpls14, wpls15;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
wpls5 = 5 * wpls;
wpls6 = 6 * wpls;
wpls7 = 7 * wpls;
wpls8 = 8 * wpls;
wpls9 = 9 * wpls;
wpls10 = 10 * wpls;
wpls11 = 11 * wpls;
wpls12 = 12 * wpls;
wpls13 = 13 * wpls;
wpls14 = 14 * wpls;
wpls15 = 15 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr - wpls15)) &
(*(sptr - wpls14)) &
(*(sptr - wpls13)) &
(*(sptr - wpls12)) &
(*(sptr - wpls11)) &
(*(sptr - wpls10)) &
(*(sptr - wpls9)) &
(*(sptr - wpls8)) &
(*(sptr - wpls7)) &
(*(sptr - wpls6)) &
(*(sptr - wpls5)) &
(*(sptr - wpls4)) &
(*(sptr - wpls3)) &
(*(sptr - wpls2)) &
(*(sptr - wpls)) &
(*sptr) &
(*(sptr + wpls)) &
(*(sptr + wpls2)) &
(*(sptr + wpls3)) &
(*(sptr + wpls4)) &
(*(sptr + wpls5)) &
(*(sptr + wpls6)) &
(*(sptr + wpls7)) &
(*(sptr + wpls8)) &
(*(sptr + wpls9)) &
(*(sptr + wpls10)) &
(*(sptr + wpls11)) &
(*(sptr + wpls12)) &
(*(sptr + wpls13)) &
(*(sptr + wpls14));
}
}
}
static void
fdilate_1_43(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
l_int32 wpls5, wpls6, wpls7, wpls8;
l_int32 wpls9, wpls10, wpls11, wpls12;
l_int32 wpls13, wpls14, wpls15;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
wpls5 = 5 * wpls;
wpls6 = 6 * wpls;
wpls7 = 7 * wpls;
wpls8 = 8 * wpls;
wpls9 = 9 * wpls;
wpls10 = 10 * wpls;
wpls11 = 11 * wpls;
wpls12 = 12 * wpls;
wpls13 = 13 * wpls;
wpls14 = 14 * wpls;
wpls15 = 15 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr + wpls15)) |
(*(sptr + wpls14)) |
(*(sptr + wpls13)) |
(*(sptr + wpls12)) |
(*(sptr + wpls11)) |
(*(sptr + wpls10)) |
(*(sptr + wpls9)) |
(*(sptr + wpls8)) |
(*(sptr + wpls7)) |
(*(sptr + wpls6)) |
(*(sptr + wpls5)) |
(*(sptr + wpls4)) |
(*(sptr + wpls3)) |
(*(sptr + wpls2)) |
(*(sptr + wpls)) |
(*sptr) |
(*(sptr - wpls)) |
(*(sptr - wpls2)) |
(*(sptr - wpls3)) |
(*(sptr - wpls4)) |
(*(sptr - wpls5)) |
(*(sptr - wpls6)) |
(*(sptr - wpls7)) |
(*(sptr - wpls8)) |
(*(sptr - wpls9)) |
(*(sptr - wpls10)) |
(*(sptr - wpls11)) |
(*(sptr - wpls12)) |
(*(sptr - wpls13)) |
(*(sptr - wpls14)) |
(*(sptr - wpls15));
}
}
}
static void
ferode_1_43(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
l_int32 wpls5, wpls6, wpls7, wpls8;
l_int32 wpls9, wpls10, wpls11, wpls12;
l_int32 wpls13, wpls14, wpls15;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
wpls5 = 5 * wpls;
wpls6 = 6 * wpls;
wpls7 = 7 * wpls;
wpls8 = 8 * wpls;
wpls9 = 9 * wpls;
wpls10 = 10 * wpls;
wpls11 = 11 * wpls;
wpls12 = 12 * wpls;
wpls13 = 13 * wpls;
wpls14 = 14 * wpls;
wpls15 = 15 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr - wpls15)) &
(*(sptr - wpls14)) &
(*(sptr - wpls13)) &
(*(sptr - wpls12)) &
(*(sptr - wpls11)) &
(*(sptr - wpls10)) &
(*(sptr - wpls9)) &
(*(sptr - wpls8)) &
(*(sptr - wpls7)) &
(*(sptr - wpls6)) &
(*(sptr - wpls5)) &
(*(sptr - wpls4)) &
(*(sptr - wpls3)) &
(*(sptr - wpls2)) &
(*(sptr - wpls)) &
(*sptr) &
(*(sptr + wpls)) &
(*(sptr + wpls2)) &
(*(sptr + wpls3)) &
(*(sptr + wpls4)) &
(*(sptr + wpls5)) &
(*(sptr + wpls6)) &
(*(sptr + wpls7)) &
(*(sptr + wpls8)) &
(*(sptr + wpls9)) &
(*(sptr + wpls10)) &
(*(sptr + wpls11)) &
(*(sptr + wpls12)) &
(*(sptr + wpls13)) &
(*(sptr + wpls14)) &
(*(sptr + wpls15));
}
}
}
static void
fdilate_1_44(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
l_int32 wpls5, wpls6, wpls7, wpls8;
l_int32 wpls9, wpls10, wpls11, wpls12;
l_int32 wpls13, wpls14, wpls15, wpls16;
l_int32 wpls17;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
wpls5 = 5 * wpls;
wpls6 = 6 * wpls;
wpls7 = 7 * wpls;
wpls8 = 8 * wpls;
wpls9 = 9 * wpls;
wpls10 = 10 * wpls;
wpls11 = 11 * wpls;
wpls12 = 12 * wpls;
wpls13 = 13 * wpls;
wpls14 = 14 * wpls;
wpls15 = 15 * wpls;
wpls16 = 16 * wpls;
wpls17 = 17 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr + wpls17)) |
(*(sptr + wpls16)) |
(*(sptr + wpls15)) |
(*(sptr + wpls14)) |
(*(sptr + wpls13)) |
(*(sptr + wpls12)) |
(*(sptr + wpls11)) |
(*(sptr + wpls10)) |
(*(sptr + wpls9)) |
(*(sptr + wpls8)) |
(*(sptr + wpls7)) |
(*(sptr + wpls6)) |
(*(sptr + wpls5)) |
(*(sptr + wpls4)) |
(*(sptr + wpls3)) |
(*(sptr + wpls2)) |
(*(sptr + wpls)) |
(*sptr) |
(*(sptr - wpls)) |
(*(sptr - wpls2)) |
(*(sptr - wpls3)) |
(*(sptr - wpls4)) |
(*(sptr - wpls5)) |
(*(sptr - wpls6)) |
(*(sptr - wpls7)) |
(*(sptr - wpls8)) |
(*(sptr - wpls9)) |
(*(sptr - wpls10)) |
(*(sptr - wpls11)) |
(*(sptr - wpls12)) |
(*(sptr - wpls13)) |
(*(sptr - wpls14)) |
(*(sptr - wpls15)) |
(*(sptr - wpls16)) |
(*(sptr - wpls17));
}
}
}
static void
ferode_1_44(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
l_int32 wpls5, wpls6, wpls7, wpls8;
l_int32 wpls9, wpls10, wpls11, wpls12;
l_int32 wpls13, wpls14, wpls15, wpls16;
l_int32 wpls17;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
wpls5 = 5 * wpls;
wpls6 = 6 * wpls;
wpls7 = 7 * wpls;
wpls8 = 8 * wpls;
wpls9 = 9 * wpls;
wpls10 = 10 * wpls;
wpls11 = 11 * wpls;
wpls12 = 12 * wpls;
wpls13 = 13 * wpls;
wpls14 = 14 * wpls;
wpls15 = 15 * wpls;
wpls16 = 16 * wpls;
wpls17 = 17 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr - wpls17)) &
(*(sptr - wpls16)) &
(*(sptr - wpls15)) &
(*(sptr - wpls14)) &
(*(sptr - wpls13)) &
(*(sptr - wpls12)) &
(*(sptr - wpls11)) &
(*(sptr - wpls10)) &
(*(sptr - wpls9)) &
(*(sptr - wpls8)) &
(*(sptr - wpls7)) &
(*(sptr - wpls6)) &
(*(sptr - wpls5)) &
(*(sptr - wpls4)) &
(*(sptr - wpls3)) &
(*(sptr - wpls2)) &
(*(sptr - wpls)) &
(*sptr) &
(*(sptr + wpls)) &
(*(sptr + wpls2)) &
(*(sptr + wpls3)) &
(*(sptr + wpls4)) &
(*(sptr + wpls5)) &
(*(sptr + wpls6)) &
(*(sptr + wpls7)) &
(*(sptr + wpls8)) &
(*(sptr + wpls9)) &
(*(sptr + wpls10)) &
(*(sptr + wpls11)) &
(*(sptr + wpls12)) &
(*(sptr + wpls13)) &
(*(sptr + wpls14)) &
(*(sptr + wpls15)) &
(*(sptr + wpls16)) &
(*(sptr + wpls17));
}
}
}
static void
fdilate_1_45(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
l_int32 wpls5, wpls6, wpls7, wpls8;
l_int32 wpls9, wpls10, wpls11, wpls12;
l_int32 wpls13, wpls14, wpls15, wpls16;
l_int32 wpls17, wpls18, wpls19, wpls20;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
wpls5 = 5 * wpls;
wpls6 = 6 * wpls;
wpls7 = 7 * wpls;
wpls8 = 8 * wpls;
wpls9 = 9 * wpls;
wpls10 = 10 * wpls;
wpls11 = 11 * wpls;
wpls12 = 12 * wpls;
wpls13 = 13 * wpls;
wpls14 = 14 * wpls;
wpls15 = 15 * wpls;
wpls16 = 16 * wpls;
wpls17 = 17 * wpls;
wpls18 = 18 * wpls;
wpls19 = 19 * wpls;
wpls20 = 20 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr + wpls20)) |
(*(sptr + wpls19)) |
(*(sptr + wpls18)) |
(*(sptr + wpls17)) |
(*(sptr + wpls16)) |
(*(sptr + wpls15)) |
(*(sptr + wpls14)) |
(*(sptr + wpls13)) |
(*(sptr + wpls12)) |
(*(sptr + wpls11)) |
(*(sptr + wpls10)) |
(*(sptr + wpls9)) |
(*(sptr + wpls8)) |
(*(sptr + wpls7)) |
(*(sptr + wpls6)) |
(*(sptr + wpls5)) |
(*(sptr + wpls4)) |
(*(sptr + wpls3)) |
(*(sptr + wpls2)) |
(*(sptr + wpls)) |
(*sptr) |
(*(sptr - wpls)) |
(*(sptr - wpls2)) |
(*(sptr - wpls3)) |
(*(sptr - wpls4)) |
(*(sptr - wpls5)) |
(*(sptr - wpls6)) |
(*(sptr - wpls7)) |
(*(sptr - wpls8)) |
(*(sptr - wpls9)) |
(*(sptr - wpls10)) |
(*(sptr - wpls11)) |
(*(sptr - wpls12)) |
(*(sptr - wpls13)) |
(*(sptr - wpls14)) |
(*(sptr - wpls15)) |
(*(sptr - wpls16)) |
(*(sptr - wpls17)) |
(*(sptr - wpls18)) |
(*(sptr - wpls19));
}
}
}
static void
ferode_1_45(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
l_int32 wpls5, wpls6, wpls7, wpls8;
l_int32 wpls9, wpls10, wpls11, wpls12;
l_int32 wpls13, wpls14, wpls15, wpls16;
l_int32 wpls17, wpls18, wpls19, wpls20;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
wpls5 = 5 * wpls;
wpls6 = 6 * wpls;
wpls7 = 7 * wpls;
wpls8 = 8 * wpls;
wpls9 = 9 * wpls;
wpls10 = 10 * wpls;
wpls11 = 11 * wpls;
wpls12 = 12 * wpls;
wpls13 = 13 * wpls;
wpls14 = 14 * wpls;
wpls15 = 15 * wpls;
wpls16 = 16 * wpls;
wpls17 = 17 * wpls;
wpls18 = 18 * wpls;
wpls19 = 19 * wpls;
wpls20 = 20 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr - wpls20)) &
(*(sptr - wpls19)) &
(*(sptr - wpls18)) &
(*(sptr - wpls17)) &
(*(sptr - wpls16)) &
(*(sptr - wpls15)) &
(*(sptr - wpls14)) &
(*(sptr - wpls13)) &
(*(sptr - wpls12)) &
(*(sptr - wpls11)) &
(*(sptr - wpls10)) &
(*(sptr - wpls9)) &
(*(sptr - wpls8)) &
(*(sptr - wpls7)) &
(*(sptr - wpls6)) &
(*(sptr - wpls5)) &
(*(sptr - wpls4)) &
(*(sptr - wpls3)) &
(*(sptr - wpls2)) &
(*(sptr - wpls)) &
(*sptr) &
(*(sptr + wpls)) &
(*(sptr + wpls2)) &
(*(sptr + wpls3)) &
(*(sptr + wpls4)) &
(*(sptr + wpls5)) &
(*(sptr + wpls6)) &
(*(sptr + wpls7)) &
(*(sptr + wpls8)) &
(*(sptr + wpls9)) &
(*(sptr + wpls10)) &
(*(sptr + wpls11)) &
(*(sptr + wpls12)) &
(*(sptr + wpls13)) &
(*(sptr + wpls14)) &
(*(sptr + wpls15)) &
(*(sptr + wpls16)) &
(*(sptr + wpls17)) &
(*(sptr + wpls18)) &
(*(sptr + wpls19));
}
}
}
static void
fdilate_1_46(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
l_int32 wpls5, wpls6, wpls7, wpls8;
l_int32 wpls9, wpls10, wpls11, wpls12;
l_int32 wpls13, wpls14, wpls15, wpls16;
l_int32 wpls17, wpls18, wpls19, wpls20;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
wpls5 = 5 * wpls;
wpls6 = 6 * wpls;
wpls7 = 7 * wpls;
wpls8 = 8 * wpls;
wpls9 = 9 * wpls;
wpls10 = 10 * wpls;
wpls11 = 11 * wpls;
wpls12 = 12 * wpls;
wpls13 = 13 * wpls;
wpls14 = 14 * wpls;
wpls15 = 15 * wpls;
wpls16 = 16 * wpls;
wpls17 = 17 * wpls;
wpls18 = 18 * wpls;
wpls19 = 19 * wpls;
wpls20 = 20 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr + wpls20)) |
(*(sptr + wpls19)) |
(*(sptr + wpls18)) |
(*(sptr + wpls17)) |
(*(sptr + wpls16)) |
(*(sptr + wpls15)) |
(*(sptr + wpls14)) |
(*(sptr + wpls13)) |
(*(sptr + wpls12)) |
(*(sptr + wpls11)) |
(*(sptr + wpls10)) |
(*(sptr + wpls9)) |
(*(sptr + wpls8)) |
(*(sptr + wpls7)) |
(*(sptr + wpls6)) |
(*(sptr + wpls5)) |
(*(sptr + wpls4)) |
(*(sptr + wpls3)) |
(*(sptr + wpls2)) |
(*(sptr + wpls)) |
(*sptr) |
(*(sptr - wpls)) |
(*(sptr - wpls2)) |
(*(sptr - wpls3)) |
(*(sptr - wpls4)) |
(*(sptr - wpls5)) |
(*(sptr - wpls6)) |
(*(sptr - wpls7)) |
(*(sptr - wpls8)) |
(*(sptr - wpls9)) |
(*(sptr - wpls10)) |
(*(sptr - wpls11)) |
(*(sptr - wpls12)) |
(*(sptr - wpls13)) |
(*(sptr - wpls14)) |
(*(sptr - wpls15)) |
(*(sptr - wpls16)) |
(*(sptr - wpls17)) |
(*(sptr - wpls18)) |
(*(sptr - wpls19)) |
(*(sptr - wpls20));
}
}
}
static void
ferode_1_46(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
l_int32 wpls5, wpls6, wpls7, wpls8;
l_int32 wpls9, wpls10, wpls11, wpls12;
l_int32 wpls13, wpls14, wpls15, wpls16;
l_int32 wpls17, wpls18, wpls19, wpls20;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
wpls5 = 5 * wpls;
wpls6 = 6 * wpls;
wpls7 = 7 * wpls;
wpls8 = 8 * wpls;
wpls9 = 9 * wpls;
wpls10 = 10 * wpls;
wpls11 = 11 * wpls;
wpls12 = 12 * wpls;
wpls13 = 13 * wpls;
wpls14 = 14 * wpls;
wpls15 = 15 * wpls;
wpls16 = 16 * wpls;
wpls17 = 17 * wpls;
wpls18 = 18 * wpls;
wpls19 = 19 * wpls;
wpls20 = 20 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr - wpls20)) &
(*(sptr - wpls19)) &
(*(sptr - wpls18)) &
(*(sptr - wpls17)) &
(*(sptr - wpls16)) &
(*(sptr - wpls15)) &
(*(sptr - wpls14)) &
(*(sptr - wpls13)) &
(*(sptr - wpls12)) &
(*(sptr - wpls11)) &
(*(sptr - wpls10)) &
(*(sptr - wpls9)) &
(*(sptr - wpls8)) &
(*(sptr - wpls7)) &
(*(sptr - wpls6)) &
(*(sptr - wpls5)) &
(*(sptr - wpls4)) &
(*(sptr - wpls3)) &
(*(sptr - wpls2)) &
(*(sptr - wpls)) &
(*sptr) &
(*(sptr + wpls)) &
(*(sptr + wpls2)) &
(*(sptr + wpls3)) &
(*(sptr + wpls4)) &
(*(sptr + wpls5)) &
(*(sptr + wpls6)) &
(*(sptr + wpls7)) &
(*(sptr + wpls8)) &
(*(sptr + wpls9)) &
(*(sptr + wpls10)) &
(*(sptr + wpls11)) &
(*(sptr + wpls12)) &
(*(sptr + wpls13)) &
(*(sptr + wpls14)) &
(*(sptr + wpls15)) &
(*(sptr + wpls16)) &
(*(sptr + wpls17)) &
(*(sptr + wpls18)) &
(*(sptr + wpls19)) &
(*(sptr + wpls20));
}
}
}
static void
fdilate_1_47(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
l_int32 wpls5, wpls6, wpls7, wpls8;
l_int32 wpls9, wpls10, wpls11, wpls12;
l_int32 wpls13, wpls14, wpls15, wpls16;
l_int32 wpls17, wpls18, wpls19, wpls20;
l_int32 wpls21, wpls22;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
wpls5 = 5 * wpls;
wpls6 = 6 * wpls;
wpls7 = 7 * wpls;
wpls8 = 8 * wpls;
wpls9 = 9 * wpls;
wpls10 = 10 * wpls;
wpls11 = 11 * wpls;
wpls12 = 12 * wpls;
wpls13 = 13 * wpls;
wpls14 = 14 * wpls;
wpls15 = 15 * wpls;
wpls16 = 16 * wpls;
wpls17 = 17 * wpls;
wpls18 = 18 * wpls;
wpls19 = 19 * wpls;
wpls20 = 20 * wpls;
wpls21 = 21 * wpls;
wpls22 = 22 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr + wpls22)) |
(*(sptr + wpls21)) |
(*(sptr + wpls20)) |
(*(sptr + wpls19)) |
(*(sptr + wpls18)) |
(*(sptr + wpls17)) |
(*(sptr + wpls16)) |
(*(sptr + wpls15)) |
(*(sptr + wpls14)) |
(*(sptr + wpls13)) |
(*(sptr + wpls12)) |
(*(sptr + wpls11)) |
(*(sptr + wpls10)) |
(*(sptr + wpls9)) |
(*(sptr + wpls8)) |
(*(sptr + wpls7)) |
(*(sptr + wpls6)) |
(*(sptr + wpls5)) |
(*(sptr + wpls4)) |
(*(sptr + wpls3)) |
(*(sptr + wpls2)) |
(*(sptr + wpls)) |
(*sptr) |
(*(sptr - wpls)) |
(*(sptr - wpls2)) |
(*(sptr - wpls3)) |
(*(sptr - wpls4)) |
(*(sptr - wpls5)) |
(*(sptr - wpls6)) |
(*(sptr - wpls7)) |
(*(sptr - wpls8)) |
(*(sptr - wpls9)) |
(*(sptr - wpls10)) |
(*(sptr - wpls11)) |
(*(sptr - wpls12)) |
(*(sptr - wpls13)) |
(*(sptr - wpls14)) |
(*(sptr - wpls15)) |
(*(sptr - wpls16)) |
(*(sptr - wpls17)) |
(*(sptr - wpls18)) |
(*(sptr - wpls19)) |
(*(sptr - wpls20)) |
(*(sptr - wpls21)) |
(*(sptr - wpls22));
}
}
}
static void
ferode_1_47(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
l_int32 wpls5, wpls6, wpls7, wpls8;
l_int32 wpls9, wpls10, wpls11, wpls12;
l_int32 wpls13, wpls14, wpls15, wpls16;
l_int32 wpls17, wpls18, wpls19, wpls20;
l_int32 wpls21, wpls22;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
wpls5 = 5 * wpls;
wpls6 = 6 * wpls;
wpls7 = 7 * wpls;
wpls8 = 8 * wpls;
wpls9 = 9 * wpls;
wpls10 = 10 * wpls;
wpls11 = 11 * wpls;
wpls12 = 12 * wpls;
wpls13 = 13 * wpls;
wpls14 = 14 * wpls;
wpls15 = 15 * wpls;
wpls16 = 16 * wpls;
wpls17 = 17 * wpls;
wpls18 = 18 * wpls;
wpls19 = 19 * wpls;
wpls20 = 20 * wpls;
wpls21 = 21 * wpls;
wpls22 = 22 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr - wpls22)) &
(*(sptr - wpls21)) &
(*(sptr - wpls20)) &
(*(sptr - wpls19)) &
(*(sptr - wpls18)) &
(*(sptr - wpls17)) &
(*(sptr - wpls16)) &
(*(sptr - wpls15)) &
(*(sptr - wpls14)) &
(*(sptr - wpls13)) &
(*(sptr - wpls12)) &
(*(sptr - wpls11)) &
(*(sptr - wpls10)) &
(*(sptr - wpls9)) &
(*(sptr - wpls8)) &
(*(sptr - wpls7)) &
(*(sptr - wpls6)) &
(*(sptr - wpls5)) &
(*(sptr - wpls4)) &
(*(sptr - wpls3)) &
(*(sptr - wpls2)) &
(*(sptr - wpls)) &
(*sptr) &
(*(sptr + wpls)) &
(*(sptr + wpls2)) &
(*(sptr + wpls3)) &
(*(sptr + wpls4)) &
(*(sptr + wpls5)) &
(*(sptr + wpls6)) &
(*(sptr + wpls7)) &
(*(sptr + wpls8)) &
(*(sptr + wpls9)) &
(*(sptr + wpls10)) &
(*(sptr + wpls11)) &
(*(sptr + wpls12)) &
(*(sptr + wpls13)) &
(*(sptr + wpls14)) &
(*(sptr + wpls15)) &
(*(sptr + wpls16)) &
(*(sptr + wpls17)) &
(*(sptr + wpls18)) &
(*(sptr + wpls19)) &
(*(sptr + wpls20)) &
(*(sptr + wpls21)) &
(*(sptr + wpls22));
}
}
}
static void
fdilate_1_48(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
l_int32 wpls5, wpls6, wpls7, wpls8;
l_int32 wpls9, wpls10, wpls11, wpls12;
l_int32 wpls13, wpls14, wpls15, wpls16;
l_int32 wpls17, wpls18, wpls19, wpls20;
l_int32 wpls21, wpls22, wpls23, wpls24;
l_int32 wpls25;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
wpls5 = 5 * wpls;
wpls6 = 6 * wpls;
wpls7 = 7 * wpls;
wpls8 = 8 * wpls;
wpls9 = 9 * wpls;
wpls10 = 10 * wpls;
wpls11 = 11 * wpls;
wpls12 = 12 * wpls;
wpls13 = 13 * wpls;
wpls14 = 14 * wpls;
wpls15 = 15 * wpls;
wpls16 = 16 * wpls;
wpls17 = 17 * wpls;
wpls18 = 18 * wpls;
wpls19 = 19 * wpls;
wpls20 = 20 * wpls;
wpls21 = 21 * wpls;
wpls22 = 22 * wpls;
wpls23 = 23 * wpls;
wpls24 = 24 * wpls;
wpls25 = 25 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr + wpls25)) |
(*(sptr + wpls24)) |
(*(sptr + wpls23)) |
(*(sptr + wpls22)) |
(*(sptr + wpls21)) |
(*(sptr + wpls20)) |
(*(sptr + wpls19)) |
(*(sptr + wpls18)) |
(*(sptr + wpls17)) |
(*(sptr + wpls16)) |
(*(sptr + wpls15)) |
(*(sptr + wpls14)) |
(*(sptr + wpls13)) |
(*(sptr + wpls12)) |
(*(sptr + wpls11)) |
(*(sptr + wpls10)) |
(*(sptr + wpls9)) |
(*(sptr + wpls8)) |
(*(sptr + wpls7)) |
(*(sptr + wpls6)) |
(*(sptr + wpls5)) |
(*(sptr + wpls4)) |
(*(sptr + wpls3)) |
(*(sptr + wpls2)) |
(*(sptr + wpls)) |
(*sptr) |
(*(sptr - wpls)) |
(*(sptr - wpls2)) |
(*(sptr - wpls3)) |
(*(sptr - wpls4)) |
(*(sptr - wpls5)) |
(*(sptr - wpls6)) |
(*(sptr - wpls7)) |
(*(sptr - wpls8)) |
(*(sptr - wpls9)) |
(*(sptr - wpls10)) |
(*(sptr - wpls11)) |
(*(sptr - wpls12)) |
(*(sptr - wpls13)) |
(*(sptr - wpls14)) |
(*(sptr - wpls15)) |
(*(sptr - wpls16)) |
(*(sptr - wpls17)) |
(*(sptr - wpls18)) |
(*(sptr - wpls19)) |
(*(sptr - wpls20)) |
(*(sptr - wpls21)) |
(*(sptr - wpls22)) |
(*(sptr - wpls23)) |
(*(sptr - wpls24));
}
}
}
static void
ferode_1_48(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
l_int32 wpls5, wpls6, wpls7, wpls8;
l_int32 wpls9, wpls10, wpls11, wpls12;
l_int32 wpls13, wpls14, wpls15, wpls16;
l_int32 wpls17, wpls18, wpls19, wpls20;
l_int32 wpls21, wpls22, wpls23, wpls24;
l_int32 wpls25;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
wpls5 = 5 * wpls;
wpls6 = 6 * wpls;
wpls7 = 7 * wpls;
wpls8 = 8 * wpls;
wpls9 = 9 * wpls;
wpls10 = 10 * wpls;
wpls11 = 11 * wpls;
wpls12 = 12 * wpls;
wpls13 = 13 * wpls;
wpls14 = 14 * wpls;
wpls15 = 15 * wpls;
wpls16 = 16 * wpls;
wpls17 = 17 * wpls;
wpls18 = 18 * wpls;
wpls19 = 19 * wpls;
wpls20 = 20 * wpls;
wpls21 = 21 * wpls;
wpls22 = 22 * wpls;
wpls23 = 23 * wpls;
wpls24 = 24 * wpls;
wpls25 = 25 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr - wpls25)) &
(*(sptr - wpls24)) &
(*(sptr - wpls23)) &
(*(sptr - wpls22)) &
(*(sptr - wpls21)) &
(*(sptr - wpls20)) &
(*(sptr - wpls19)) &
(*(sptr - wpls18)) &
(*(sptr - wpls17)) &
(*(sptr - wpls16)) &
(*(sptr - wpls15)) &
(*(sptr - wpls14)) &
(*(sptr - wpls13)) &
(*(sptr - wpls12)) &
(*(sptr - wpls11)) &
(*(sptr - wpls10)) &
(*(sptr - wpls9)) &
(*(sptr - wpls8)) &
(*(sptr - wpls7)) &
(*(sptr - wpls6)) &
(*(sptr - wpls5)) &
(*(sptr - wpls4)) &
(*(sptr - wpls3)) &
(*(sptr - wpls2)) &
(*(sptr - wpls)) &
(*sptr) &
(*(sptr + wpls)) &
(*(sptr + wpls2)) &
(*(sptr + wpls3)) &
(*(sptr + wpls4)) &
(*(sptr + wpls5)) &
(*(sptr + wpls6)) &
(*(sptr + wpls7)) &
(*(sptr + wpls8)) &
(*(sptr + wpls9)) &
(*(sptr + wpls10)) &
(*(sptr + wpls11)) &
(*(sptr + wpls12)) &
(*(sptr + wpls13)) &
(*(sptr + wpls14)) &
(*(sptr + wpls15)) &
(*(sptr + wpls16)) &
(*(sptr + wpls17)) &
(*(sptr + wpls18)) &
(*(sptr + wpls19)) &
(*(sptr + wpls20)) &
(*(sptr + wpls21)) &
(*(sptr + wpls22)) &
(*(sptr + wpls23)) &
(*(sptr + wpls24));
}
}
}
static void
fdilate_1_49(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
l_int32 wpls5, wpls6, wpls7, wpls8;
l_int32 wpls9, wpls10, wpls11, wpls12;
l_int32 wpls13, wpls14, wpls15, wpls16;
l_int32 wpls17, wpls18, wpls19, wpls20;
l_int32 wpls21, wpls22, wpls23, wpls24;
l_int32 wpls25;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
wpls5 = 5 * wpls;
wpls6 = 6 * wpls;
wpls7 = 7 * wpls;
wpls8 = 8 * wpls;
wpls9 = 9 * wpls;
wpls10 = 10 * wpls;
wpls11 = 11 * wpls;
wpls12 = 12 * wpls;
wpls13 = 13 * wpls;
wpls14 = 14 * wpls;
wpls15 = 15 * wpls;
wpls16 = 16 * wpls;
wpls17 = 17 * wpls;
wpls18 = 18 * wpls;
wpls19 = 19 * wpls;
wpls20 = 20 * wpls;
wpls21 = 21 * wpls;
wpls22 = 22 * wpls;
wpls23 = 23 * wpls;
wpls24 = 24 * wpls;
wpls25 = 25 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr + wpls25)) |
(*(sptr + wpls24)) |
(*(sptr + wpls23)) |
(*(sptr + wpls22)) |
(*(sptr + wpls21)) |
(*(sptr + wpls20)) |
(*(sptr + wpls19)) |
(*(sptr + wpls18)) |
(*(sptr + wpls17)) |
(*(sptr + wpls16)) |
(*(sptr + wpls15)) |
(*(sptr + wpls14)) |
(*(sptr + wpls13)) |
(*(sptr + wpls12)) |
(*(sptr + wpls11)) |
(*(sptr + wpls10)) |
(*(sptr + wpls9)) |
(*(sptr + wpls8)) |
(*(sptr + wpls7)) |
(*(sptr + wpls6)) |
(*(sptr + wpls5)) |
(*(sptr + wpls4)) |
(*(sptr + wpls3)) |
(*(sptr + wpls2)) |
(*(sptr + wpls)) |
(*sptr) |
(*(sptr - wpls)) |
(*(sptr - wpls2)) |
(*(sptr - wpls3)) |
(*(sptr - wpls4)) |
(*(sptr - wpls5)) |
(*(sptr - wpls6)) |
(*(sptr - wpls7)) |
(*(sptr - wpls8)) |
(*(sptr - wpls9)) |
(*(sptr - wpls10)) |
(*(sptr - wpls11)) |
(*(sptr - wpls12)) |
(*(sptr - wpls13)) |
(*(sptr - wpls14)) |
(*(sptr - wpls15)) |
(*(sptr - wpls16)) |
(*(sptr - wpls17)) |
(*(sptr - wpls18)) |
(*(sptr - wpls19)) |
(*(sptr - wpls20)) |
(*(sptr - wpls21)) |
(*(sptr - wpls22)) |
(*(sptr - wpls23)) |
(*(sptr - wpls24)) |
(*(sptr - wpls25));
}
}
}
static void
ferode_1_49(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2, wpls3, wpls4;
l_int32 wpls5, wpls6, wpls7, wpls8;
l_int32 wpls9, wpls10, wpls11, wpls12;
l_int32 wpls13, wpls14, wpls15, wpls16;
l_int32 wpls17, wpls18, wpls19, wpls20;
l_int32 wpls21, wpls22, wpls23, wpls24;
l_int32 wpls25;
wpls2 = 2 * wpls;
wpls3 = 3 * wpls;
wpls4 = 4 * wpls;
wpls5 = 5 * wpls;
wpls6 = 6 * wpls;
wpls7 = 7 * wpls;
wpls8 = 8 * wpls;
wpls9 = 9 * wpls;
wpls10 = 10 * wpls;
wpls11 = 11 * wpls;
wpls12 = 12 * wpls;
wpls13 = 13 * wpls;
wpls14 = 14 * wpls;
wpls15 = 15 * wpls;
wpls16 = 16 * wpls;
wpls17 = 17 * wpls;
wpls18 = 18 * wpls;
wpls19 = 19 * wpls;
wpls20 = 20 * wpls;
wpls21 = 21 * wpls;
wpls22 = 22 * wpls;
wpls23 = 23 * wpls;
wpls24 = 24 * wpls;
wpls25 = 25 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*(sptr - wpls25)) &
(*(sptr - wpls24)) &
(*(sptr - wpls23)) &
(*(sptr - wpls22)) &
(*(sptr - wpls21)) &
(*(sptr - wpls20)) &
(*(sptr - wpls19)) &
(*(sptr - wpls18)) &
(*(sptr - wpls17)) &
(*(sptr - wpls16)) &
(*(sptr - wpls15)) &
(*(sptr - wpls14)) &
(*(sptr - wpls13)) &
(*(sptr - wpls12)) &
(*(sptr - wpls11)) &
(*(sptr - wpls10)) &
(*(sptr - wpls9)) &
(*(sptr - wpls8)) &
(*(sptr - wpls7)) &
(*(sptr - wpls6)) &
(*(sptr - wpls5)) &
(*(sptr - wpls4)) &
(*(sptr - wpls3)) &
(*(sptr - wpls2)) &
(*(sptr - wpls)) &
(*sptr) &
(*(sptr + wpls)) &
(*(sptr + wpls2)) &
(*(sptr + wpls3)) &
(*(sptr + wpls4)) &
(*(sptr + wpls5)) &
(*(sptr + wpls6)) &
(*(sptr + wpls7)) &
(*(sptr + wpls8)) &
(*(sptr + wpls9)) &
(*(sptr + wpls10)) &
(*(sptr + wpls11)) &
(*(sptr + wpls12)) &
(*(sptr + wpls13)) &
(*(sptr + wpls14)) &
(*(sptr + wpls15)) &
(*(sptr + wpls16)) &
(*(sptr + wpls17)) &
(*(sptr + wpls18)) &
(*(sptr + wpls19)) &
(*(sptr + wpls20)) &
(*(sptr + wpls21)) &
(*(sptr + wpls22)) &
(*(sptr + wpls23)) &
(*(sptr + wpls24)) &
(*(sptr + wpls25));
}
}
}
static void
fdilate_1_50(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr + wpls) << 1) | (*(sptr + wpls + 1) >> 31)) |
(*(sptr + wpls)) |
((*(sptr) << 1) | (*(sptr + 1) >> 31)) |
(*sptr);
}
}
}
static void
ferode_1_50(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr - wpls) >> 1) | (*(sptr - wpls - 1) << 31)) &
(*(sptr - wpls)) &
((*(sptr) >> 1) | (*(sptr - 1) << 31)) &
(*sptr);
}
}
}
static void
fdilate_1_51(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr + wpls) << 1) | (*(sptr + wpls + 1) >> 31)) |
(*(sptr + wpls)) |
((*(sptr + wpls) >> 1) | (*(sptr + wpls - 1) << 31)) |
((*(sptr) << 1) | (*(sptr + 1) >> 31)) |
(*sptr) |
((*(sptr) >> 1) | (*(sptr - 1) << 31)) |
((*(sptr - wpls) << 1) | (*(sptr - wpls + 1) >> 31)) |
(*(sptr - wpls)) |
((*(sptr - wpls) >> 1) | (*(sptr - wpls - 1) << 31));
}
}
}
static void
ferode_1_51(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr - wpls) >> 1) | (*(sptr - wpls - 1) << 31)) &
(*(sptr - wpls)) &
((*(sptr - wpls) << 1) | (*(sptr - wpls + 1) >> 31)) &
((*(sptr) >> 1) | (*(sptr - 1) << 31)) &
(*sptr) &
((*(sptr) << 1) | (*(sptr + 1) >> 31)) &
((*(sptr + wpls) >> 1) | (*(sptr + wpls - 1) << 31)) &
(*(sptr + wpls)) &
((*(sptr + wpls) << 1) | (*(sptr + wpls + 1) >> 31));
}
}
}
static void
fdilate_1_52(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2;
wpls2 = 2 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr + wpls2) << 2) | (*(sptr + wpls2 + 1) >> 30)) |
((*(sptr + wpls2) << 1) | (*(sptr + wpls2 + 1) >> 31)) |
(*(sptr + wpls2)) |
((*(sptr + wpls2) >> 1) | (*(sptr + wpls2 - 1) << 31)) |
((*(sptr + wpls) << 2) | (*(sptr + wpls + 1) >> 30)) |
((*(sptr + wpls) << 1) | (*(sptr + wpls + 1) >> 31)) |
(*(sptr + wpls)) |
((*(sptr + wpls) >> 1) | (*(sptr + wpls - 1) << 31)) |
((*(sptr) << 2) | (*(sptr + 1) >> 30)) |
((*(sptr) << 1) | (*(sptr + 1) >> 31)) |
(*sptr) |
((*(sptr) >> 1) | (*(sptr - 1) << 31)) |
((*(sptr - wpls) << 2) | (*(sptr - wpls + 1) >> 30)) |
((*(sptr - wpls) << 1) | (*(sptr - wpls + 1) >> 31)) |
(*(sptr - wpls)) |
((*(sptr - wpls) >> 1) | (*(sptr - wpls - 1) << 31));
}
}
}
static void
ferode_1_52(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2;
wpls2 = 2 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr - wpls2) >> 2) | (*(sptr - wpls2 - 1) << 30)) &
((*(sptr - wpls2) >> 1) | (*(sptr - wpls2 - 1) << 31)) &
(*(sptr - wpls2)) &
((*(sptr - wpls2) << 1) | (*(sptr - wpls2 + 1) >> 31)) &
((*(sptr - wpls) >> 2) | (*(sptr - wpls - 1) << 30)) &
((*(sptr - wpls) >> 1) | (*(sptr - wpls - 1) << 31)) &
(*(sptr - wpls)) &
((*(sptr - wpls) << 1) | (*(sptr - wpls + 1) >> 31)) &
((*(sptr) >> 2) | (*(sptr - 1) << 30)) &
((*(sptr) >> 1) | (*(sptr - 1) << 31)) &
(*sptr) &
((*(sptr) << 1) | (*(sptr + 1) >> 31)) &
((*(sptr + wpls) >> 2) | (*(sptr + wpls - 1) << 30)) &
((*(sptr + wpls) >> 1) | (*(sptr + wpls - 1) << 31)) &
(*(sptr + wpls)) &
((*(sptr + wpls) << 1) | (*(sptr + wpls + 1) >> 31));
}
}
}
static void
fdilate_1_53(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2;
wpls2 = 2 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr + wpls2) << 2) | (*(sptr + wpls2 + 1) >> 30)) |
((*(sptr + wpls2) << 1) | (*(sptr + wpls2 + 1) >> 31)) |
(*(sptr + wpls2)) |
((*(sptr + wpls2) >> 1) | (*(sptr + wpls2 - 1) << 31)) |
((*(sptr + wpls2) >> 2) | (*(sptr + wpls2 - 1) << 30)) |
((*(sptr + wpls) << 2) | (*(sptr + wpls + 1) >> 30)) |
((*(sptr + wpls) << 1) | (*(sptr + wpls + 1) >> 31)) |
(*(sptr + wpls)) |
((*(sptr + wpls) >> 1) | (*(sptr + wpls - 1) << 31)) |
((*(sptr + wpls) >> 2) | (*(sptr + wpls - 1) << 30)) |
((*(sptr) << 2) | (*(sptr + 1) >> 30)) |
((*(sptr) << 1) | (*(sptr + 1) >> 31)) |
(*sptr) |
((*(sptr) >> 1) | (*(sptr - 1) << 31)) |
((*(sptr) >> 2) | (*(sptr - 1) << 30)) |
((*(sptr - wpls) << 2) | (*(sptr - wpls + 1) >> 30)) |
((*(sptr - wpls) << 1) | (*(sptr - wpls + 1) >> 31)) |
(*(sptr - wpls)) |
((*(sptr - wpls) >> 1) | (*(sptr - wpls - 1) << 31)) |
((*(sptr - wpls) >> 2) | (*(sptr - wpls - 1) << 30)) |
((*(sptr - wpls2) << 2) | (*(sptr - wpls2 + 1) >> 30)) |
((*(sptr - wpls2) << 1) | (*(sptr - wpls2 + 1) >> 31)) |
(*(sptr - wpls2)) |
((*(sptr - wpls2) >> 1) | (*(sptr - wpls2 - 1) << 31)) |
((*(sptr - wpls2) >> 2) | (*(sptr - wpls2 - 1) << 30));
}
}
}
static void
ferode_1_53(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2;
wpls2 = 2 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr - wpls2) >> 2) | (*(sptr - wpls2 - 1) << 30)) &
((*(sptr - wpls2) >> 1) | (*(sptr - wpls2 - 1) << 31)) &
(*(sptr - wpls2)) &
((*(sptr - wpls2) << 1) | (*(sptr - wpls2 + 1) >> 31)) &
((*(sptr - wpls2) << 2) | (*(sptr - wpls2 + 1) >> 30)) &
((*(sptr - wpls) >> 2) | (*(sptr - wpls - 1) << 30)) &
((*(sptr - wpls) >> 1) | (*(sptr - wpls - 1) << 31)) &
(*(sptr - wpls)) &
((*(sptr - wpls) << 1) | (*(sptr - wpls + 1) >> 31)) &
((*(sptr - wpls) << 2) | (*(sptr - wpls + 1) >> 30)) &
((*(sptr) >> 2) | (*(sptr - 1) << 30)) &
((*(sptr) >> 1) | (*(sptr - 1) << 31)) &
(*sptr) &
((*(sptr) << 1) | (*(sptr + 1) >> 31)) &
((*(sptr) << 2) | (*(sptr + 1) >> 30)) &
((*(sptr + wpls) >> 2) | (*(sptr + wpls - 1) << 30)) &
((*(sptr + wpls) >> 1) | (*(sptr + wpls - 1) << 31)) &
(*(sptr + wpls)) &
((*(sptr + wpls) << 1) | (*(sptr + wpls + 1) >> 31)) &
((*(sptr + wpls) << 2) | (*(sptr + wpls + 1) >> 30)) &
((*(sptr + wpls2) >> 2) | (*(sptr + wpls2 - 1) << 30)) &
((*(sptr + wpls2) >> 1) | (*(sptr + wpls2 - 1) << 31)) &
(*(sptr + wpls2)) &
((*(sptr + wpls2) << 1) | (*(sptr + wpls2 + 1) >> 31)) &
((*(sptr + wpls2) << 2) | (*(sptr + wpls2 + 1) >> 30));
}
}
}
static void
fdilate_1_54(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) >> 1) | (*(sptr - 1) << 31)) |
(*(sptr - wpls));
}
}
}
static void
ferode_1_54(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr) << 1) | (*(sptr + 1) >> 31)) &
(*(sptr + wpls));
}
}
}
static void
fdilate_1_55(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*sptr) |
((*(sptr - wpls) >> 1) | (*(sptr - wpls - 1) << 31));
}
}
}
static void
ferode_1_55(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = (*sptr) &
((*(sptr + wpls) << 1) | (*(sptr + wpls + 1) >> 31));
}
}
}
static void
fdilate_1_56(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2;
wpls2 = 2 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr + wpls2) >> 2) | (*(sptr + wpls2 - 1) << 30)) |
((*(sptr + wpls) >> 1) | (*(sptr + wpls - 1) << 31)) |
(*sptr) |
((*(sptr - wpls) << 1) | (*(sptr - wpls + 1) >> 31)) |
((*(sptr - wpls2) << 2) | (*(sptr - wpls2 + 1) >> 30));
}
}
}
static void
ferode_1_56(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2;
wpls2 = 2 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr - wpls2) << 2) | (*(sptr - wpls2 + 1) >> 30)) &
((*(sptr - wpls) << 1) | (*(sptr - wpls + 1) >> 31)) &
(*sptr) &
((*(sptr + wpls) >> 1) | (*(sptr + wpls - 1) << 31)) &
((*(sptr + wpls2) >> 2) | (*(sptr + wpls2 - 1) << 30));
}
}
}
static void
fdilate_1_57(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2;
wpls2 = 2 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr + wpls2) << 2) | (*(sptr + wpls2 + 1) >> 30)) |
((*(sptr + wpls) << 1) | (*(sptr + wpls + 1) >> 31)) |
(*sptr) |
((*(sptr - wpls) >> 1) | (*(sptr - wpls - 1) << 31)) |
((*(sptr - wpls2) >> 2) | (*(sptr - wpls2 - 1) << 30));
}
}
}
static void
ferode_1_57(l_uint32 *datad,
l_int32 w,
l_int32 h,
l_int32 wpld,
l_uint32 *datas,
l_int32 wpls)
{
l_int32 i;
register l_int32 j, pwpls;
register l_uint32 *sptr, *dptr;
l_int32 wpls2;
wpls2 = 2 * wpls;
pwpls = (l_uint32)(w + 31) / 32; /* proper wpl of src */
for (i = 0; i < h; i++) {
sptr = datas + i * wpls;
dptr = datad + i * wpld;
for (j = 0; j < pwpls; j++, sptr++, dptr++) {
*dptr = ((*(sptr - wpls2) >> 2) | (*(sptr - wpls2 - 1) << 30)) &
((*(sptr - wpls) >> 1) | (*(sptr - wpls - 1) << 31)) &
(*sptr) &
((*(sptr + wpls) << 1) | (*(sptr + wpls + 1) >> 31)) &
((*(sptr + wpls2) << 2) | (*(sptr + wpls2 + 1) >> 30));
}
}
}
| gpl-2.0 |
kurikuri99/xen_study | tools/ioemu-qemu-xen/linux-user/arm/nwfpe/extended_cpdo.c | 67 | 6252 | /*
NetWinder Floating Point Emulator
(c) Rebel.COM, 1998,1999
Direct questions, comments to Scott Bambrough <scottb@netwinder.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "fpa11.h"
#include "softfloat.h"
#include "fpopcode.h"
floatx80 floatx80_exp(floatx80 Fm);
floatx80 floatx80_ln(floatx80 Fm);
floatx80 floatx80_sin(floatx80 rFm);
floatx80 floatx80_cos(floatx80 rFm);
floatx80 floatx80_arcsin(floatx80 rFm);
floatx80 floatx80_arctan(floatx80 rFm);
floatx80 floatx80_log(floatx80 rFm);
floatx80 floatx80_tan(floatx80 rFm);
floatx80 floatx80_arccos(floatx80 rFm);
floatx80 floatx80_pow(floatx80 rFn,floatx80 rFm);
floatx80 floatx80_pol(floatx80 rFn,floatx80 rFm);
unsigned int ExtendedCPDO(const unsigned int opcode)
{
FPA11 *fpa11 = GET_FPA11();
floatx80 rFm, rFn;
unsigned int Fd, Fm, Fn, nRc = 1;
//printk("ExtendedCPDO(0x%08x)\n",opcode);
Fm = getFm(opcode);
if (CONSTANT_FM(opcode))
{
rFm = getExtendedConstant(Fm);
}
else
{
switch (fpa11->fType[Fm])
{
case typeSingle:
rFm = float32_to_floatx80(fpa11->fpreg[Fm].fSingle, &fpa11->fp_status);
break;
case typeDouble:
rFm = float64_to_floatx80(fpa11->fpreg[Fm].fDouble, &fpa11->fp_status);
break;
case typeExtended:
rFm = fpa11->fpreg[Fm].fExtended;
break;
default: return 0;
}
}
if (!MONADIC_INSTRUCTION(opcode))
{
Fn = getFn(opcode);
switch (fpa11->fType[Fn])
{
case typeSingle:
rFn = float32_to_floatx80(fpa11->fpreg[Fn].fSingle, &fpa11->fp_status);
break;
case typeDouble:
rFn = float64_to_floatx80(fpa11->fpreg[Fn].fDouble, &fpa11->fp_status);
break;
case typeExtended:
rFn = fpa11->fpreg[Fn].fExtended;
break;
default: return 0;
}
}
Fd = getFd(opcode);
switch (opcode & MASK_ARITHMETIC_OPCODE)
{
/* dyadic opcodes */
case ADF_CODE:
fpa11->fpreg[Fd].fExtended = floatx80_add(rFn,rFm, &fpa11->fp_status);
break;
case MUF_CODE:
case FML_CODE:
fpa11->fpreg[Fd].fExtended = floatx80_mul(rFn,rFm, &fpa11->fp_status);
break;
case SUF_CODE:
fpa11->fpreg[Fd].fExtended = floatx80_sub(rFn,rFm, &fpa11->fp_status);
break;
case RSF_CODE:
fpa11->fpreg[Fd].fExtended = floatx80_sub(rFm,rFn, &fpa11->fp_status);
break;
case DVF_CODE:
case FDV_CODE:
fpa11->fpreg[Fd].fExtended = floatx80_div(rFn,rFm, &fpa11->fp_status);
break;
case RDF_CODE:
case FRD_CODE:
fpa11->fpreg[Fd].fExtended = floatx80_div(rFm,rFn, &fpa11->fp_status);
break;
#if 0
case POW_CODE:
fpa11->fpreg[Fd].fExtended = floatx80_pow(rFn,rFm);
break;
case RPW_CODE:
fpa11->fpreg[Fd].fExtended = floatx80_pow(rFm,rFn);
break;
#endif
case RMF_CODE:
fpa11->fpreg[Fd].fExtended = floatx80_rem(rFn,rFm, &fpa11->fp_status);
break;
#if 0
case POL_CODE:
fpa11->fpreg[Fd].fExtended = floatx80_pol(rFn,rFm);
break;
#endif
/* monadic opcodes */
case MVF_CODE:
fpa11->fpreg[Fd].fExtended = rFm;
break;
case MNF_CODE:
rFm.high ^= 0x8000;
fpa11->fpreg[Fd].fExtended = rFm;
break;
case ABS_CODE:
rFm.high &= 0x7fff;
fpa11->fpreg[Fd].fExtended = rFm;
break;
case RND_CODE:
case URD_CODE:
fpa11->fpreg[Fd].fExtended = floatx80_round_to_int(rFm, &fpa11->fp_status);
break;
case SQT_CODE:
fpa11->fpreg[Fd].fExtended = floatx80_sqrt(rFm, &fpa11->fp_status);
break;
#if 0
case LOG_CODE:
fpa11->fpreg[Fd].fExtended = floatx80_log(rFm);
break;
case LGN_CODE:
fpa11->fpreg[Fd].fExtended = floatx80_ln(rFm);
break;
case EXP_CODE:
fpa11->fpreg[Fd].fExtended = floatx80_exp(rFm);
break;
case SIN_CODE:
fpa11->fpreg[Fd].fExtended = floatx80_sin(rFm);
break;
case COS_CODE:
fpa11->fpreg[Fd].fExtended = floatx80_cos(rFm);
break;
case TAN_CODE:
fpa11->fpreg[Fd].fExtended = floatx80_tan(rFm);
break;
case ASN_CODE:
fpa11->fpreg[Fd].fExtended = floatx80_arcsin(rFm);
break;
case ACS_CODE:
fpa11->fpreg[Fd].fExtended = floatx80_arccos(rFm);
break;
case ATN_CODE:
fpa11->fpreg[Fd].fExtended = floatx80_arctan(rFm);
break;
#endif
case NRM_CODE:
break;
default:
{
nRc = 0;
}
}
if (0 != nRc) fpa11->fType[Fd] = typeExtended;
return nRc;
}
#if 0
floatx80 floatx80_exp(floatx80 Fm)
{
//series
}
floatx80 floatx80_ln(floatx80 Fm)
{
//series
}
floatx80 floatx80_sin(floatx80 rFm)
{
//series
}
floatx80 floatx80_cos(floatx80 rFm)
{
//series
}
floatx80 floatx80_arcsin(floatx80 rFm)
{
//series
}
floatx80 floatx80_arctan(floatx80 rFm)
{
//series
}
floatx80 floatx80_log(floatx80 rFm)
{
return floatx80_div(floatx80_ln(rFm),getExtendedConstant(7));
}
floatx80 floatx80_tan(floatx80 rFm)
{
return floatx80_div(floatx80_sin(rFm),floatx80_cos(rFm));
}
floatx80 floatx80_arccos(floatx80 rFm)
{
//return floatx80_sub(halfPi,floatx80_arcsin(rFm));
}
floatx80 floatx80_pow(floatx80 rFn,floatx80 rFm)
{
return floatx80_exp(floatx80_mul(rFm,floatx80_ln(rFn)));
}
floatx80 floatx80_pol(floatx80 rFn,floatx80 rFm)
{
return floatx80_arctan(floatx80_div(rFn,rFm));
}
#endif
| gpl-2.0 |
larks/linux-rcu | Documentation/networking/ifenslave.c | 835 | 29862 | /* Mode: C;
* ifenslave.c: Configure network interfaces for parallel routing.
*
* This program controls the Linux implementation of running multiple
* network interfaces in parallel.
*
* Author: Donald Becker <becker@cesdis.gsfc.nasa.gov>
* Copyright 1994-1996 Donald Becker
*
* 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.
*
* The author may be reached as becker@CESDIS.gsfc.nasa.gov, or C/O
* Center of Excellence in Space Data and Information Sciences
* Code 930.5, Goddard Space Flight Center, Greenbelt MD 20771
*
* Changes :
* - 2000/10/02 Willy Tarreau <willy at meta-x.org> :
* - few fixes. Master's MAC address is now correctly taken from
* the first device when not previously set ;
* - detach support : call BOND_RELEASE to detach an enslaved interface.
* - give a mini-howto from command-line help : # ifenslave -h
*
* - 2001/02/16 Chad N. Tindel <ctindel at ieee dot org> :
* - Master is now brought down before setting the MAC address. In
* the 2.4 kernel you can't change the MAC address while the device is
* up because you get EBUSY.
*
* - 2001/09/13 Takao Indoh <indou dot takao at jp dot fujitsu dot com>
* - Added the ability to change the active interface on a mode 1 bond
* at runtime.
*
* - 2001/10/23 Chad N. Tindel <ctindel at ieee dot org> :
* - No longer set the MAC address of the master. The bond device will
* take care of this itself
* - Try the SIOC*** versions of the bonding ioctls before using the
* old versions
* - 2002/02/18 Erik Habbinga <erik_habbinga @ hp dot com> :
* - ifr2.ifr_flags was not initialized in the hwaddr_notset case,
* SIOCGIFFLAGS now called before hwaddr_notset test
*
* - 2002/10/31 Tony Cureington <tony.cureington * hp_com> :
* - If the master does not have a hardware address when the first slave
* is enslaved, the master is assigned the hardware address of that
* slave - there is a comment in bonding.c stating "ifenslave takes
* care of this now." This corrects the problem of slaves having
* different hardware addresses in active-backup mode when
* multiple interfaces are specified on a single ifenslave command
* (ifenslave bond0 eth0 eth1).
*
* - 2003/03/18 - Tsippy Mendelson <tsippy.mendelson at intel dot com> and
* Shmulik Hen <shmulik.hen at intel dot com>
* - Moved setting the slave's mac address and openning it, from
* the application to the driver. This enables support of modes
* that need to use the unique mac address of each slave.
* The driver also takes care of closing the slave and restoring its
* original mac address upon release.
* In addition, block possibility of enslaving before the master is up.
* This prevents putting the system in an undefined state.
*
* - 2003/05/01 - Amir Noam <amir.noam at intel dot com>
* - Added ABI version control to restore compatibility between
* new/old ifenslave and new/old bonding.
* - Prevent adding an adapter that is already a slave.
* Fixes the problem of stalling the transmission and leaving
* the slave in a down state.
*
* - 2003/05/01 - Shmulik Hen <shmulik.hen at intel dot com>
* - Prevent enslaving if the bond device is down.
* Fixes the problem of leaving the system in unstable state and
* halting when trying to remove the module.
* - Close socket on all abnormal exists.
* - Add versioning scheme that follows that of the bonding driver.
* current version is 1.0.0 as a base line.
*
* - 2003/05/22 - Jay Vosburgh <fubar at us dot ibm dot com>
* - ifenslave -c was broken; it's now fixed
* - Fixed problem with routes vanishing from master during enslave
* processing.
*
* - 2003/05/27 - Amir Noam <amir.noam at intel dot com>
* - Fix backward compatibility issues:
* For drivers not using ABI versions, slave was set down while
* it should be left up before enslaving.
* Also, master was not set down and the default set_mac_address()
* would fail and generate an error message in the system log.
* - For opt_c: slave should not be set to the master's setting
* while it is running. It was already set during enslave. To
* simplify things, it is now handled separately.
*
* - 2003/12/01 - Shmulik Hen <shmulik.hen at intel dot com>
* - Code cleanup and style changes
* set version to 1.1.0
*/
#define APP_VERSION "1.1.0"
#define APP_RELDATE "December 1, 2003"
#define APP_NAME "ifenslave"
static char *version =
APP_NAME ".c:v" APP_VERSION " (" APP_RELDATE ")\n"
"o Donald Becker (becker@cesdis.gsfc.nasa.gov).\n"
"o Detach support added on 2000/10/02 by Willy Tarreau (willy at meta-x.org).\n"
"o 2.4 kernel support added on 2001/02/16 by Chad N. Tindel\n"
" (ctindel at ieee dot org).\n";
static const char *usage_msg =
"Usage: ifenslave [-f] <master-if> <slave-if> [<slave-if>...]\n"
" ifenslave -d <master-if> <slave-if> [<slave-if>...]\n"
" ifenslave -c <master-if> <slave-if>\n"
" ifenslave --help\n";
static const char *help_msg =
"\n"
" To create a bond device, simply follow these three steps :\n"
" - ensure that the required drivers are properly loaded :\n"
" # modprobe bonding ; modprobe <3c59x|eepro100|pcnet32|tulip|...>\n"
" - assign an IP address to the bond device :\n"
" # ifconfig bond0 <addr> netmask <mask> broadcast <bcast>\n"
" - attach all the interfaces you need to the bond device :\n"
" # ifenslave [{-f|--force}] bond0 eth0 [eth1 [eth2]...]\n"
" If bond0 didn't have a MAC address, it will take eth0's. Then, all\n"
" interfaces attached AFTER this assignment will get the same MAC addr.\n"
" (except for ALB/TLB modes)\n"
"\n"
" To set the bond device down and automatically release all the slaves :\n"
" # ifconfig bond0 down\n"
"\n"
" To detach a dead interface without setting the bond device down :\n"
" # ifenslave {-d|--detach} bond0 eth0 [eth1 [eth2]...]\n"
"\n"
" To change active slave :\n"
" # ifenslave {-c|--change-active} bond0 eth0\n"
"\n"
" To show master interface info\n"
" # ifenslave bond0\n"
"\n"
" To show all interfaces info\n"
" # ifenslave {-a|--all-interfaces}\n"
"\n"
" To be more verbose\n"
" # ifenslave {-v|--verbose} ...\n"
"\n"
" # ifenslave {-u|--usage} Show usage\n"
" # ifenslave {-V|--version} Show version\n"
" # ifenslave {-h|--help} This message\n"
"\n";
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <linux/if.h>
#include <net/if_arp.h>
#include <linux/if_ether.h>
#include <linux/if_bonding.h>
#include <linux/sockios.h>
typedef unsigned long long u64; /* hack, so we may include kernel's ethtool.h */
typedef __uint32_t u32; /* ditto */
typedef __uint16_t u16; /* ditto */
typedef __uint8_t u8; /* ditto */
#include <linux/ethtool.h>
struct option longopts[] = {
/* { name has_arg *flag val } */
{"all-interfaces", 0, 0, 'a'}, /* Show all interfaces. */
{"change-active", 0, 0, 'c'}, /* Change the active slave. */
{"detach", 0, 0, 'd'}, /* Detach a slave interface. */
{"force", 0, 0, 'f'}, /* Force the operation. */
{"help", 0, 0, 'h'}, /* Give help */
{"usage", 0, 0, 'u'}, /* Give usage */
{"verbose", 0, 0, 'v'}, /* Report each action taken. */
{"version", 0, 0, 'V'}, /* Emit version information. */
{ 0, 0, 0, 0}
};
/* Command-line flags. */
unsigned int
opt_a = 0, /* Show-all-interfaces flag. */
opt_c = 0, /* Change-active-slave flag. */
opt_d = 0, /* Detach a slave interface. */
opt_f = 0, /* Force the operation. */
opt_h = 0, /* Help */
opt_u = 0, /* Usage */
opt_v = 0, /* Verbose flag. */
opt_V = 0; /* Version */
int skfd = -1; /* AF_INET socket for ioctl() calls.*/
int abi_ver = 0; /* userland - kernel ABI version */
int hwaddr_set = 0; /* Master's hwaddr is set */
int saved_errno;
struct ifreq master_mtu, master_flags, master_hwaddr;
struct ifreq slave_mtu, slave_flags, slave_hwaddr;
struct dev_ifr {
struct ifreq *req_ifr;
char *req_name;
int req_type;
};
struct dev_ifr master_ifra[] = {
{&master_mtu, "SIOCGIFMTU", SIOCGIFMTU},
{&master_flags, "SIOCGIFFLAGS", SIOCGIFFLAGS},
{&master_hwaddr, "SIOCGIFHWADDR", SIOCGIFHWADDR},
{NULL, "", 0}
};
struct dev_ifr slave_ifra[] = {
{&slave_mtu, "SIOCGIFMTU", SIOCGIFMTU},
{&slave_flags, "SIOCGIFFLAGS", SIOCGIFFLAGS},
{&slave_hwaddr, "SIOCGIFHWADDR", SIOCGIFHWADDR},
{NULL, "", 0}
};
static void if_print(char *ifname);
static int get_drv_info(char *master_ifname);
static int get_if_settings(char *ifname, struct dev_ifr ifra[]);
static int get_slave_flags(char *slave_ifname);
static int set_master_hwaddr(char *master_ifname, struct sockaddr *hwaddr);
static int set_slave_hwaddr(char *slave_ifname, struct sockaddr *hwaddr);
static int set_slave_mtu(char *slave_ifname, int mtu);
static int set_if_flags(char *ifname, short flags);
static int set_if_up(char *ifname, short flags);
static int set_if_down(char *ifname, short flags);
static int clear_if_addr(char *ifname);
static int set_if_addr(char *master_ifname, char *slave_ifname);
static int change_active(char *master_ifname, char *slave_ifname);
static int enslave(char *master_ifname, char *slave_ifname);
static int release(char *master_ifname, char *slave_ifname);
#define v_print(fmt, args...) \
if (opt_v) \
fprintf(stderr, fmt, ## args )
int main(int argc, char *argv[])
{
char **spp, *master_ifname, *slave_ifname;
int c, i, rv;
int res = 0;
int exclusive = 0;
while ((c = getopt_long(argc, argv, "acdfhuvV", longopts, 0)) != EOF) {
switch (c) {
case 'a': opt_a++; exclusive++; break;
case 'c': opt_c++; exclusive++; break;
case 'd': opt_d++; exclusive++; break;
case 'f': opt_f++; exclusive++; break;
case 'h': opt_h++; exclusive++; break;
case 'u': opt_u++; exclusive++; break;
case 'v': opt_v++; break;
case 'V': opt_V++; exclusive++; break;
case '?':
fprintf(stderr, usage_msg);
res = 2;
goto out;
}
}
/* options check */
if (exclusive > 1) {
fprintf(stderr, usage_msg);
res = 2;
goto out;
}
if (opt_v || opt_V) {
printf(version);
if (opt_V) {
res = 0;
goto out;
}
}
if (opt_u) {
printf(usage_msg);
res = 0;
goto out;
}
if (opt_h) {
printf(usage_msg);
printf(help_msg);
res = 0;
goto out;
}
/* Open a basic socket */
if ((skfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("socket");
res = 1;
goto out;
}
if (opt_a) {
if (optind == argc) {
/* No remaining args */
/* show all interfaces */
if_print((char *)NULL);
goto out;
} else {
/* Just show usage */
fprintf(stderr, usage_msg);
res = 2;
goto out;
}
}
/* Copy the interface name */
spp = argv + optind;
master_ifname = *spp++;
if (master_ifname == NULL) {
fprintf(stderr, usage_msg);
res = 2;
goto out;
}
/* exchange abi version with bonding module */
res = get_drv_info(master_ifname);
if (res) {
fprintf(stderr,
"Master '%s': Error: handshake with driver failed. "
"Aborting\n",
master_ifname);
goto out;
}
slave_ifname = *spp++;
if (slave_ifname == NULL) {
if (opt_d || opt_c) {
fprintf(stderr, usage_msg);
res = 2;
goto out;
}
/* A single arg means show the
* configuration for this interface
*/
if_print(master_ifname);
goto out;
}
res = get_if_settings(master_ifname, master_ifra);
if (res) {
/* Probably a good reason not to go on */
fprintf(stderr,
"Master '%s': Error: get settings failed: %s. "
"Aborting\n",
master_ifname, strerror(res));
goto out;
}
/* check if master is indeed a master;
* if not then fail any operation
*/
if (!(master_flags.ifr_flags & IFF_MASTER)) {
fprintf(stderr,
"Illegal operation; the specified interface '%s' "
"is not a master. Aborting\n",
master_ifname);
res = 1;
goto out;
}
/* check if master is up; if not then fail any operation */
if (!(master_flags.ifr_flags & IFF_UP)) {
fprintf(stderr,
"Illegal operation; the specified master interface "
"'%s' is not up.\n",
master_ifname);
res = 1;
goto out;
}
/* Only for enslaving */
if (!opt_c && !opt_d) {
sa_family_t master_family = master_hwaddr.ifr_hwaddr.sa_family;
unsigned char *hwaddr =
(unsigned char *)master_hwaddr.ifr_hwaddr.sa_data;
/* The family '1' is ARPHRD_ETHER for ethernet. */
if (master_family != 1 && !opt_f) {
fprintf(stderr,
"Illegal operation: The specified master "
"interface '%s' is not ethernet-like.\n "
"This program is designed to work with "
"ethernet-like network interfaces.\n "
"Use the '-f' option to force the "
"operation.\n",
master_ifname);
res = 1;
goto out;
}
/* Check master's hw addr */
for (i = 0; i < 6; i++) {
if (hwaddr[i] != 0) {
hwaddr_set = 1;
break;
}
}
if (hwaddr_set) {
v_print("current hardware address of master '%s' "
"is %2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x, "
"type %d\n",
master_ifname,
hwaddr[0], hwaddr[1],
hwaddr[2], hwaddr[3],
hwaddr[4], hwaddr[5],
master_family);
}
}
/* Accepts only one slave */
if (opt_c) {
/* change active slave */
res = get_slave_flags(slave_ifname);
if (res) {
fprintf(stderr,
"Slave '%s': Error: get flags failed. "
"Aborting\n",
slave_ifname);
goto out;
}
res = change_active(master_ifname, slave_ifname);
if (res) {
fprintf(stderr,
"Master '%s', Slave '%s': Error: "
"Change active failed\n",
master_ifname, slave_ifname);
}
} else {
/* Accept multiple slaves */
do {
if (opt_d) {
/* detach a slave interface from the master */
rv = get_slave_flags(slave_ifname);
if (rv) {
/* Can't work with this slave. */
/* remember the error and skip it*/
fprintf(stderr,
"Slave '%s': Error: get flags "
"failed. Skipping\n",
slave_ifname);
res = rv;
continue;
}
rv = release(master_ifname, slave_ifname);
if (rv) {
fprintf(stderr,
"Master '%s', Slave '%s': Error: "
"Release failed\n",
master_ifname, slave_ifname);
res = rv;
}
} else {
/* attach a slave interface to the master */
rv = get_if_settings(slave_ifname, slave_ifra);
if (rv) {
/* Can't work with this slave. */
/* remember the error and skip it*/
fprintf(stderr,
"Slave '%s': Error: get "
"settings failed: %s. "
"Skipping\n",
slave_ifname, strerror(rv));
res = rv;
continue;
}
rv = enslave(master_ifname, slave_ifname);
if (rv) {
fprintf(stderr,
"Master '%s', Slave '%s': Error: "
"Enslave failed\n",
master_ifname, slave_ifname);
res = rv;
}
}
} while ((slave_ifname = *spp++) != NULL);
}
out:
if (skfd >= 0) {
close(skfd);
}
return res;
}
static short mif_flags;
/* Get the inteface configuration from the kernel. */
static int if_getconfig(char *ifname)
{
struct ifreq ifr;
int metric, mtu; /* Parameters of the master interface. */
struct sockaddr dstaddr, broadaddr, netmask;
unsigned char *hwaddr;
strcpy(ifr.ifr_name, ifname);
if (ioctl(skfd, SIOCGIFFLAGS, &ifr) < 0)
return -1;
mif_flags = ifr.ifr_flags;
printf("The result of SIOCGIFFLAGS on %s is %x.\n",
ifname, ifr.ifr_flags);
strcpy(ifr.ifr_name, ifname);
if (ioctl(skfd, SIOCGIFADDR, &ifr) < 0)
return -1;
printf("The result of SIOCGIFADDR is %2.2x.%2.2x.%2.2x.%2.2x.\n",
ifr.ifr_addr.sa_data[0], ifr.ifr_addr.sa_data[1],
ifr.ifr_addr.sa_data[2], ifr.ifr_addr.sa_data[3]);
strcpy(ifr.ifr_name, ifname);
if (ioctl(skfd, SIOCGIFHWADDR, &ifr) < 0)
return -1;
/* Gotta convert from 'char' to unsigned for printf(). */
hwaddr = (unsigned char *)ifr.ifr_hwaddr.sa_data;
printf("The result of SIOCGIFHWADDR is type %d "
"%2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x.\n",
ifr.ifr_hwaddr.sa_family, hwaddr[0], hwaddr[1],
hwaddr[2], hwaddr[3], hwaddr[4], hwaddr[5]);
strcpy(ifr.ifr_name, ifname);
if (ioctl(skfd, SIOCGIFMETRIC, &ifr) < 0) {
metric = 0;
} else
metric = ifr.ifr_metric;
strcpy(ifr.ifr_name, ifname);
if (ioctl(skfd, SIOCGIFMTU, &ifr) < 0)
mtu = 0;
else
mtu = ifr.ifr_mtu;
strcpy(ifr.ifr_name, ifname);
if (ioctl(skfd, SIOCGIFDSTADDR, &ifr) < 0) {
memset(&dstaddr, 0, sizeof(struct sockaddr));
} else
dstaddr = ifr.ifr_dstaddr;
strcpy(ifr.ifr_name, ifname);
if (ioctl(skfd, SIOCGIFBRDADDR, &ifr) < 0) {
memset(&broadaddr, 0, sizeof(struct sockaddr));
} else
broadaddr = ifr.ifr_broadaddr;
strcpy(ifr.ifr_name, ifname);
if (ioctl(skfd, SIOCGIFNETMASK, &ifr) < 0) {
memset(&netmask, 0, sizeof(struct sockaddr));
} else
netmask = ifr.ifr_netmask;
return 0;
}
static void if_print(char *ifname)
{
char buff[1024];
struct ifconf ifc;
struct ifreq *ifr;
int i;
if (ifname == (char *)NULL) {
ifc.ifc_len = sizeof(buff);
ifc.ifc_buf = buff;
if (ioctl(skfd, SIOCGIFCONF, &ifc) < 0) {
perror("SIOCGIFCONF failed");
return;
}
ifr = ifc.ifc_req;
for (i = ifc.ifc_len / sizeof(struct ifreq); --i >= 0; ifr++) {
if (if_getconfig(ifr->ifr_name) < 0) {
fprintf(stderr,
"%s: unknown interface.\n",
ifr->ifr_name);
continue;
}
if (((mif_flags & IFF_UP) == 0) && !opt_a) continue;
/*ife_print(&ife);*/
}
} else {
if (if_getconfig(ifname) < 0) {
fprintf(stderr,
"%s: unknown interface.\n", ifname);
}
}
}
static int get_drv_info(char *master_ifname)
{
struct ifreq ifr;
struct ethtool_drvinfo info;
char *endptr;
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, master_ifname, IFNAMSIZ);
ifr.ifr_data = (caddr_t)&info;
info.cmd = ETHTOOL_GDRVINFO;
strncpy(info.driver, "ifenslave", 32);
snprintf(info.fw_version, 32, "%d", BOND_ABI_VERSION);
if (ioctl(skfd, SIOCETHTOOL, &ifr) < 0) {
if (errno == EOPNOTSUPP) {
goto out;
}
saved_errno = errno;
v_print("Master '%s': Error: get bonding info failed %s\n",
master_ifname, strerror(saved_errno));
return 1;
}
abi_ver = strtoul(info.fw_version, &endptr, 0);
if (*endptr) {
v_print("Master '%s': Error: got invalid string as an ABI "
"version from the bonding module\n",
master_ifname);
return 1;
}
out:
v_print("ABI ver is %d\n", abi_ver);
return 0;
}
static int change_active(char *master_ifname, char *slave_ifname)
{
struct ifreq ifr;
int res = 0;
if (!(slave_flags.ifr_flags & IFF_SLAVE)) {
fprintf(stderr,
"Illegal operation: The specified slave interface "
"'%s' is not a slave\n",
slave_ifname);
return 1;
}
strncpy(ifr.ifr_name, master_ifname, IFNAMSIZ);
strncpy(ifr.ifr_slave, slave_ifname, IFNAMSIZ);
if ((ioctl(skfd, SIOCBONDCHANGEACTIVE, &ifr) < 0) &&
(ioctl(skfd, BOND_CHANGE_ACTIVE_OLD, &ifr) < 0)) {
saved_errno = errno;
v_print("Master '%s': Error: SIOCBONDCHANGEACTIVE failed: "
"%s\n",
master_ifname, strerror(saved_errno));
res = 1;
}
return res;
}
static int enslave(char *master_ifname, char *slave_ifname)
{
struct ifreq ifr;
int res = 0;
if (slave_flags.ifr_flags & IFF_SLAVE) {
fprintf(stderr,
"Illegal operation: The specified slave interface "
"'%s' is already a slave\n",
slave_ifname);
return 1;
}
res = set_if_down(slave_ifname, slave_flags.ifr_flags);
if (res) {
fprintf(stderr,
"Slave '%s': Error: bring interface down failed\n",
slave_ifname);
return res;
}
if (abi_ver < 2) {
/* Older bonding versions would panic if the slave has no IP
* address, so get the IP setting from the master.
*/
set_if_addr(master_ifname, slave_ifname);
} else {
res = clear_if_addr(slave_ifname);
if (res) {
fprintf(stderr,
"Slave '%s': Error: clear address failed\n",
slave_ifname);
return res;
}
}
if (master_mtu.ifr_mtu != slave_mtu.ifr_mtu) {
res = set_slave_mtu(slave_ifname, master_mtu.ifr_mtu);
if (res) {
fprintf(stderr,
"Slave '%s': Error: set MTU failed\n",
slave_ifname);
return res;
}
}
if (hwaddr_set) {
/* Master already has an hwaddr
* so set it's hwaddr to the slave
*/
if (abi_ver < 1) {
/* The driver is using an old ABI, so
* the application sets the slave's
* hwaddr
*/
res = set_slave_hwaddr(slave_ifname,
&(master_hwaddr.ifr_hwaddr));
if (res) {
fprintf(stderr,
"Slave '%s': Error: set hw address "
"failed\n",
slave_ifname);
goto undo_mtu;
}
/* For old ABI the application needs to bring the
* slave back up
*/
res = set_if_up(slave_ifname, slave_flags.ifr_flags);
if (res) {
fprintf(stderr,
"Slave '%s': Error: bring interface "
"down failed\n",
slave_ifname);
goto undo_slave_mac;
}
}
/* The driver is using a new ABI,
* so the driver takes care of setting
* the slave's hwaddr and bringing
* it up again
*/
} else {
/* No hwaddr for master yet, so
* set the slave's hwaddr to it
*/
if (abi_ver < 1) {
/* For old ABI, the master needs to be
* down before setting it's hwaddr
*/
res = set_if_down(master_ifname, master_flags.ifr_flags);
if (res) {
fprintf(stderr,
"Master '%s': Error: bring interface "
"down failed\n",
master_ifname);
goto undo_mtu;
}
}
res = set_master_hwaddr(master_ifname,
&(slave_hwaddr.ifr_hwaddr));
if (res) {
fprintf(stderr,
"Master '%s': Error: set hw address "
"failed\n",
master_ifname);
goto undo_mtu;
}
if (abi_ver < 1) {
/* For old ABI, bring the master
* back up
*/
res = set_if_up(master_ifname, master_flags.ifr_flags);
if (res) {
fprintf(stderr,
"Master '%s': Error: bring interface "
"up failed\n",
master_ifname);
goto undo_master_mac;
}
}
hwaddr_set = 1;
}
/* Do the real thing */
strncpy(ifr.ifr_name, master_ifname, IFNAMSIZ);
strncpy(ifr.ifr_slave, slave_ifname, IFNAMSIZ);
if ((ioctl(skfd, SIOCBONDENSLAVE, &ifr) < 0) &&
(ioctl(skfd, BOND_ENSLAVE_OLD, &ifr) < 0)) {
saved_errno = errno;
v_print("Master '%s': Error: SIOCBONDENSLAVE failed: %s\n",
master_ifname, strerror(saved_errno));
res = 1;
}
if (res) {
goto undo_master_mac;
}
return 0;
/* rollback (best effort) */
undo_master_mac:
set_master_hwaddr(master_ifname, &(master_hwaddr.ifr_hwaddr));
hwaddr_set = 0;
goto undo_mtu;
undo_slave_mac:
set_slave_hwaddr(slave_ifname, &(slave_hwaddr.ifr_hwaddr));
undo_mtu:
set_slave_mtu(slave_ifname, slave_mtu.ifr_mtu);
return res;
}
static int release(char *master_ifname, char *slave_ifname)
{
struct ifreq ifr;
int res = 0;
if (!(slave_flags.ifr_flags & IFF_SLAVE)) {
fprintf(stderr,
"Illegal operation: The specified slave interface "
"'%s' is not a slave\n",
slave_ifname);
return 1;
}
strncpy(ifr.ifr_name, master_ifname, IFNAMSIZ);
strncpy(ifr.ifr_slave, slave_ifname, IFNAMSIZ);
if ((ioctl(skfd, SIOCBONDRELEASE, &ifr) < 0) &&
(ioctl(skfd, BOND_RELEASE_OLD, &ifr) < 0)) {
saved_errno = errno;
v_print("Master '%s': Error: SIOCBONDRELEASE failed: %s\n",
master_ifname, strerror(saved_errno));
return 1;
} else if (abi_ver < 1) {
/* The driver is using an old ABI, so we'll set the interface
* down to avoid any conflicts due to same MAC/IP
*/
res = set_if_down(slave_ifname, slave_flags.ifr_flags);
if (res) {
fprintf(stderr,
"Slave '%s': Error: bring interface "
"down failed\n",
slave_ifname);
}
}
/* set to default mtu */
set_slave_mtu(slave_ifname, 1500);
return res;
}
static int get_if_settings(char *ifname, struct dev_ifr ifra[])
{
int i;
int res = 0;
for (i = 0; ifra[i].req_ifr; i++) {
strncpy(ifra[i].req_ifr->ifr_name, ifname, IFNAMSIZ);
res = ioctl(skfd, ifra[i].req_type, ifra[i].req_ifr);
if (res < 0) {
saved_errno = errno;
v_print("Interface '%s': Error: %s failed: %s\n",
ifname, ifra[i].req_name,
strerror(saved_errno));
return saved_errno;
}
}
return 0;
}
static int get_slave_flags(char *slave_ifname)
{
int res = 0;
strncpy(slave_flags.ifr_name, slave_ifname, IFNAMSIZ);
res = ioctl(skfd, SIOCGIFFLAGS, &slave_flags);
if (res < 0) {
saved_errno = errno;
v_print("Slave '%s': Error: SIOCGIFFLAGS failed: %s\n",
slave_ifname, strerror(saved_errno));
} else {
v_print("Slave %s: flags %04X.\n",
slave_ifname, slave_flags.ifr_flags);
}
return res;
}
static int set_master_hwaddr(char *master_ifname, struct sockaddr *hwaddr)
{
unsigned char *addr = (unsigned char *)hwaddr->sa_data;
struct ifreq ifr;
int res = 0;
strncpy(ifr.ifr_name, master_ifname, IFNAMSIZ);
memcpy(&(ifr.ifr_hwaddr), hwaddr, sizeof(struct sockaddr));
res = ioctl(skfd, SIOCSIFHWADDR, &ifr);
if (res < 0) {
saved_errno = errno;
v_print("Master '%s': Error: SIOCSIFHWADDR failed: %s\n",
master_ifname, strerror(saved_errno));
return res;
} else {
v_print("Master '%s': hardware address set to "
"%2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x.\n",
master_ifname, addr[0], addr[1], addr[2],
addr[3], addr[4], addr[5]);
}
return res;
}
static int set_slave_hwaddr(char *slave_ifname, struct sockaddr *hwaddr)
{
unsigned char *addr = (unsigned char *)hwaddr->sa_data;
struct ifreq ifr;
int res = 0;
strncpy(ifr.ifr_name, slave_ifname, IFNAMSIZ);
memcpy(&(ifr.ifr_hwaddr), hwaddr, sizeof(struct sockaddr));
res = ioctl(skfd, SIOCSIFHWADDR, &ifr);
if (res < 0) {
saved_errno = errno;
v_print("Slave '%s': Error: SIOCSIFHWADDR failed: %s\n",
slave_ifname, strerror(saved_errno));
if (saved_errno == EBUSY) {
v_print(" The device is busy: it must be idle "
"before running this command.\n");
} else if (saved_errno == EOPNOTSUPP) {
v_print(" The device does not support setting "
"the MAC address.\n"
" Your kernel likely does not support slave "
"devices.\n");
} else if (saved_errno == EINVAL) {
v_print(" The device's address type does not match "
"the master's address type.\n");
}
return res;
} else {
v_print("Slave '%s': hardware address set to "
"%2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x.\n",
slave_ifname, addr[0], addr[1], addr[2],
addr[3], addr[4], addr[5]);
}
return res;
}
static int set_slave_mtu(char *slave_ifname, int mtu)
{
struct ifreq ifr;
int res = 0;
ifr.ifr_mtu = mtu;
strncpy(ifr.ifr_name, slave_ifname, IFNAMSIZ);
res = ioctl(skfd, SIOCSIFMTU, &ifr);
if (res < 0) {
saved_errno = errno;
v_print("Slave '%s': Error: SIOCSIFMTU failed: %s\n",
slave_ifname, strerror(saved_errno));
} else {
v_print("Slave '%s': MTU set to %d.\n", slave_ifname, mtu);
}
return res;
}
static int set_if_flags(char *ifname, short flags)
{
struct ifreq ifr;
int res = 0;
ifr.ifr_flags = flags;
strncpy(ifr.ifr_name, ifname, IFNAMSIZ);
res = ioctl(skfd, SIOCSIFFLAGS, &ifr);
if (res < 0) {
saved_errno = errno;
v_print("Interface '%s': Error: SIOCSIFFLAGS failed: %s\n",
ifname, strerror(saved_errno));
} else {
v_print("Interface '%s': flags set to %04X.\n", ifname, flags);
}
return res;
}
static int set_if_up(char *ifname, short flags)
{
return set_if_flags(ifname, flags | IFF_UP);
}
static int set_if_down(char *ifname, short flags)
{
return set_if_flags(ifname, flags & ~IFF_UP);
}
static int clear_if_addr(char *ifname)
{
struct ifreq ifr;
int res = 0;
strncpy(ifr.ifr_name, ifname, IFNAMSIZ);
ifr.ifr_addr.sa_family = AF_INET;
memset(ifr.ifr_addr.sa_data, 0, sizeof(ifr.ifr_addr.sa_data));
res = ioctl(skfd, SIOCSIFADDR, &ifr);
if (res < 0) {
saved_errno = errno;
v_print("Interface '%s': Error: SIOCSIFADDR failed: %s\n",
ifname, strerror(saved_errno));
} else {
v_print("Interface '%s': address cleared\n", ifname);
}
return res;
}
static int set_if_addr(char *master_ifname, char *slave_ifname)
{
struct ifreq ifr;
int res;
unsigned char *ipaddr;
int i;
struct {
char *req_name;
char *desc;
int g_ioctl;
int s_ioctl;
} ifra[] = {
{"IFADDR", "addr", SIOCGIFADDR, SIOCSIFADDR},
{"DSTADDR", "destination addr", SIOCGIFDSTADDR, SIOCSIFDSTADDR},
{"BRDADDR", "broadcast addr", SIOCGIFBRDADDR, SIOCSIFBRDADDR},
{"NETMASK", "netmask", SIOCGIFNETMASK, SIOCSIFNETMASK},
{NULL, NULL, 0, 0},
};
for (i = 0; ifra[i].req_name; i++) {
strncpy(ifr.ifr_name, master_ifname, IFNAMSIZ);
res = ioctl(skfd, ifra[i].g_ioctl, &ifr);
if (res < 0) {
int saved_errno = errno;
v_print("Interface '%s': Error: SIOCG%s failed: %s\n",
master_ifname, ifra[i].req_name,
strerror(saved_errno));
ifr.ifr_addr.sa_family = AF_INET;
memset(ifr.ifr_addr.sa_data, 0,
sizeof(ifr.ifr_addr.sa_data));
}
strncpy(ifr.ifr_name, slave_ifname, IFNAMSIZ);
res = ioctl(skfd, ifra[i].s_ioctl, &ifr);
if (res < 0) {
int saved_errno = errno;
v_print("Interface '%s': Error: SIOCS%s failed: %s\n",
slave_ifname, ifra[i].req_name,
strerror(saved_errno));
}
ipaddr = (unsigned char *)ifr.ifr_addr.sa_data;
v_print("Interface '%s': set IP %s to %d.%d.%d.%d\n",
slave_ifname, ifra[i].desc,
ipaddr[0], ipaddr[1], ipaddr[2], ipaddr[3]);
}
return 0;
}
/*
* Local variables:
* version-control: t
* kept-new-versions: 5
* c-indent-level: 4
* c-basic-offset: 4
* tab-width: 4
* compile-command: "gcc -Wall -Wstrict-prototypes -O -I/usr/src/linux/include ifenslave.c -o ifenslave"
* End:
*/
| gpl-2.0 |
piskor/android_kernel_spica | sound/soc/sh/siu_dai.c | 835 | 20772 | /*
* siu_dai.c - ALSA SoC driver for Renesas SH7343, SH7722 SIU peripheral.
*
* Copyright (C) 2009-2010 Guennadi Liakhovetski <g.liakhovetski@gmx.de>
* Copyright (C) 2006 Carlos Munoz <carlos@kenati.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/delay.h>
#include <linux/firmware.h>
#include <linux/pm_runtime.h>
#include <linux/slab.h>
#include <asm/clock.h>
#include <asm/siu.h>
#include <sound/control.h>
#include <sound/soc-dai.h>
#include "siu.h"
/* Board specifics */
#if defined(CONFIG_CPU_SUBTYPE_SH7722)
# define SIU_MAX_VOLUME 0x1000
#else
# define SIU_MAX_VOLUME 0x7fff
#endif
#define PRAM_SIZE 0x2000
#define XRAM_SIZE 0x800
#define YRAM_SIZE 0x800
#define XRAM_OFFSET 0x4000
#define YRAM_OFFSET 0x6000
#define REG_OFFSET 0xc000
#define PLAYBACK_ENABLED 1
#define CAPTURE_ENABLED 2
#define VOLUME_CAPTURE 0
#define VOLUME_PLAYBACK 1
#define DFLT_VOLUME_LEVEL 0x08000800
/*
* SPDIF is only available on port A and on some SIU implementations it is only
* available for input. Due to the lack of hardware to test it, SPDIF is left
* disabled in this driver version
*/
struct format_flag {
u32 i2s;
u32 pcm;
u32 spdif;
u32 mask;
};
struct port_flag {
struct format_flag playback;
struct format_flag capture;
};
static struct port_flag siu_flags[SIU_PORT_NUM] = {
[SIU_PORT_A] = {
.playback = {
.i2s = 0x50000000,
.pcm = 0x40000000,
.spdif = 0x80000000, /* not on all SIU versions */
.mask = 0xd0000000,
},
.capture = {
.i2s = 0x05000000,
.pcm = 0x04000000,
.spdif = 0x08000000,
.mask = 0x0d000000,
},
},
[SIU_PORT_B] = {
.playback = {
.i2s = 0x00500000,
.pcm = 0x00400000,
.spdif = 0, /* impossible - turn off */
.mask = 0x00500000,
},
.capture = {
.i2s = 0x00050000,
.pcm = 0x00040000,
.spdif = 0, /* impossible - turn off */
.mask = 0x00050000,
},
},
};
static void siu_dai_start(struct siu_port *port_info)
{
struct siu_info *info = siu_i2s_dai.private_data;
u32 __iomem *base = info->reg;
dev_dbg(port_info->pcm->card->dev, "%s\n", __func__);
/* Turn on SIU clock */
pm_runtime_get_sync(siu_i2s_dai.dev);
/* Issue software reset to siu */
siu_write32(base + SIU_SRCTL, 0);
/* Wait for the reset to take effect */
udelay(1);
port_info->stfifo = 0;
port_info->trdat = 0;
/* portA, portB, SIU operate */
siu_write32(base + SIU_SRCTL, 0x301);
/* portA=256fs, portB=256fs */
siu_write32(base + SIU_CKCTL, 0x40400000);
/* portA's BRG does not divide SIUCKA */
siu_write32(base + SIU_BRGASEL, 0);
siu_write32(base + SIU_BRRA, 0);
/* portB's BRG divides SIUCKB by half */
siu_write32(base + SIU_BRGBSEL, 1);
siu_write32(base + SIU_BRRB, 0);
siu_write32(base + SIU_IFCTL, 0x44440000);
/* portA: 32 bit/fs, master; portB: 32 bit/fs, master */
siu_write32(base + SIU_SFORM, 0x0c0c0000);
/*
* Volume levels: looks like the DSP firmware implements volume controls
* differently from what's described in the datasheet
*/
siu_write32(base + SIU_SBDVCA, port_info->playback.volume);
siu_write32(base + SIU_SBDVCB, port_info->capture.volume);
}
static void siu_dai_stop(void)
{
struct siu_info *info = siu_i2s_dai.private_data;
u32 __iomem *base = info->reg;
/* SIU software reset */
siu_write32(base + SIU_SRCTL, 0);
/* Turn off SIU clock */
pm_runtime_put_sync(siu_i2s_dai.dev);
}
static void siu_dai_spbAselect(struct siu_port *port_info)
{
struct siu_info *info = siu_i2s_dai.private_data;
struct siu_firmware *fw = &info->fw;
u32 *ydef = fw->yram0;
u32 idx;
/* path A use */
if (!info->port_id)
idx = 1; /* portA */
else
idx = 2; /* portB */
ydef[0] = (fw->spbpar[idx].ab1a << 16) |
(fw->spbpar[idx].ab0a << 8) |
(fw->spbpar[idx].dir << 7) | 3;
ydef[1] = fw->yram0[1]; /* 0x03000300 */
ydef[2] = (16 / 2) << 24;
ydef[3] = fw->yram0[3]; /* 0 */
ydef[4] = fw->yram0[4]; /* 0 */
ydef[7] = fw->spbpar[idx].event;
port_info->stfifo |= fw->spbpar[idx].stfifo;
port_info->trdat |= fw->spbpar[idx].trdat;
}
static void siu_dai_spbBselect(struct siu_port *port_info)
{
struct siu_info *info = siu_i2s_dai.private_data;
struct siu_firmware *fw = &info->fw;
u32 *ydef = fw->yram0;
u32 idx;
/* path B use */
if (!info->port_id)
idx = 7; /* portA */
else
idx = 8; /* portB */
ydef[5] = (fw->spbpar[idx].ab1a << 16) |
(fw->spbpar[idx].ab0a << 8) | 1;
ydef[6] = fw->spbpar[idx].event;
port_info->stfifo |= fw->spbpar[idx].stfifo;
port_info->trdat |= fw->spbpar[idx].trdat;
}
static void siu_dai_open(struct siu_stream *siu_stream)
{
struct siu_info *info = siu_i2s_dai.private_data;
u32 __iomem *base = info->reg;
u32 srctl, ifctl;
srctl = siu_read32(base + SIU_SRCTL);
ifctl = siu_read32(base + SIU_IFCTL);
switch (info->port_id) {
case SIU_PORT_A:
/* portA operates */
srctl |= 0x200;
ifctl &= ~0xc2;
break;
case SIU_PORT_B:
/* portB operates */
srctl |= 0x100;
ifctl &= ~0x31;
break;
}
siu_write32(base + SIU_SRCTL, srctl);
/* Unmute and configure portA */
siu_write32(base + SIU_IFCTL, ifctl);
}
/*
* At the moment only fixed Left-upper, Left-lower, Right-upper, Right-lower
* packing is supported
*/
static void siu_dai_pcmdatapack(struct siu_stream *siu_stream)
{
struct siu_info *info = siu_i2s_dai.private_data;
u32 __iomem *base = info->reg;
u32 dpak;
dpak = siu_read32(base + SIU_DPAK);
switch (info->port_id) {
case SIU_PORT_A:
dpak &= ~0xc0000000;
break;
case SIU_PORT_B:
dpak &= ~0x00c00000;
break;
}
siu_write32(base + SIU_DPAK, dpak);
}
static int siu_dai_spbstart(struct siu_port *port_info)
{
struct siu_info *info = siu_i2s_dai.private_data;
u32 __iomem *base = info->reg;
struct siu_firmware *fw = &info->fw;
u32 *ydef = fw->yram0;
int cnt;
u32 __iomem *add;
u32 *ptr;
/* Load SPB Program in PRAM */
ptr = fw->pram0;
add = info->pram;
for (cnt = 0; cnt < PRAM0_SIZE; cnt++, add++, ptr++)
siu_write32(add, *ptr);
ptr = fw->pram1;
add = info->pram + (0x0100 / sizeof(u32));
for (cnt = 0; cnt < PRAM1_SIZE; cnt++, add++, ptr++)
siu_write32(add, *ptr);
/* XRAM initialization */
add = info->xram;
for (cnt = 0; cnt < XRAM0_SIZE + XRAM1_SIZE + XRAM2_SIZE; cnt++, add++)
siu_write32(add, 0);
/* YRAM variable area initialization */
add = info->yram;
for (cnt = 0; cnt < YRAM_DEF_SIZE; cnt++, add++)
siu_write32(add, ydef[cnt]);
/* YRAM FIR coefficient area initialization */
add = info->yram + (0x0200 / sizeof(u32));
for (cnt = 0; cnt < YRAM_FIR_SIZE; cnt++, add++)
siu_write32(add, fw->yram_fir_coeff[cnt]);
/* YRAM IIR coefficient area initialization */
add = info->yram + (0x0600 / sizeof(u32));
for (cnt = 0; cnt < YRAM_IIR_SIZE; cnt++, add++)
siu_write32(add, 0);
siu_write32(base + SIU_TRDAT, port_info->trdat);
port_info->trdat = 0x0;
/* SPB start condition: software */
siu_write32(base + SIU_SBACTIV, 0);
/* Start SPB */
siu_write32(base + SIU_SBCTL, 0xc0000000);
/* Wait for program to halt */
cnt = 0x10000;
while (--cnt && siu_read32(base + SIU_SBCTL) != 0x80000000)
cpu_relax();
if (!cnt)
return -EBUSY;
/* SPB program start address setting */
siu_write32(base + SIU_SBPSET, 0x00400000);
/* SPB hardware start(FIFOCTL source) */
siu_write32(base + SIU_SBACTIV, 0xc0000000);
return 0;
}
static void siu_dai_spbstop(struct siu_port *port_info)
{
struct siu_info *info = siu_i2s_dai.private_data;
u32 __iomem *base = info->reg;
siu_write32(base + SIU_SBACTIV, 0);
/* SPB stop */
siu_write32(base + SIU_SBCTL, 0);
port_info->stfifo = 0;
}
/* API functions */
/* Playback and capture hardware properties are identical */
static struct snd_pcm_hardware siu_dai_pcm_hw = {
.info = SNDRV_PCM_INFO_INTERLEAVED,
.formats = SNDRV_PCM_FMTBIT_S16,
.rates = SNDRV_PCM_RATE_8000_48000,
.rate_min = 8000,
.rate_max = 48000,
.channels_min = 2,
.channels_max = 2,
.buffer_bytes_max = SIU_BUFFER_BYTES_MAX,
.period_bytes_min = SIU_PERIOD_BYTES_MIN,
.period_bytes_max = SIU_PERIOD_BYTES_MAX,
.periods_min = SIU_PERIODS_MIN,
.periods_max = SIU_PERIODS_MAX,
};
static int siu_dai_info_volume(struct snd_kcontrol *kctrl,
struct snd_ctl_elem_info *uinfo)
{
struct siu_port *port_info = snd_kcontrol_chip(kctrl);
dev_dbg(port_info->pcm->card->dev, "%s\n", __func__);
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = SIU_MAX_VOLUME;
return 0;
}
static int siu_dai_get_volume(struct snd_kcontrol *kctrl,
struct snd_ctl_elem_value *ucontrol)
{
struct siu_port *port_info = snd_kcontrol_chip(kctrl);
struct device *dev = port_info->pcm->card->dev;
u32 vol;
dev_dbg(dev, "%s\n", __func__);
switch (kctrl->private_value) {
case VOLUME_PLAYBACK:
/* Playback is always on port 0 */
vol = port_info->playback.volume;
ucontrol->value.integer.value[0] = vol & 0xffff;
ucontrol->value.integer.value[1] = vol >> 16 & 0xffff;
break;
case VOLUME_CAPTURE:
/* Capture is always on port 1 */
vol = port_info->capture.volume;
ucontrol->value.integer.value[0] = vol & 0xffff;
ucontrol->value.integer.value[1] = vol >> 16 & 0xffff;
break;
default:
dev_err(dev, "%s() invalid private_value=%ld\n",
__func__, kctrl->private_value);
return -EINVAL;
}
return 0;
}
static int siu_dai_put_volume(struct snd_kcontrol *kctrl,
struct snd_ctl_elem_value *ucontrol)
{
struct siu_port *port_info = snd_kcontrol_chip(kctrl);
struct device *dev = port_info->pcm->card->dev;
struct siu_info *info = siu_i2s_dai.private_data;
u32 __iomem *base = info->reg;
u32 new_vol;
u32 cur_vol;
dev_dbg(dev, "%s\n", __func__);
if (ucontrol->value.integer.value[0] < 0 ||
ucontrol->value.integer.value[0] > SIU_MAX_VOLUME ||
ucontrol->value.integer.value[1] < 0 ||
ucontrol->value.integer.value[1] > SIU_MAX_VOLUME)
return -EINVAL;
new_vol = ucontrol->value.integer.value[0] |
ucontrol->value.integer.value[1] << 16;
/* See comment above - DSP firmware implementation */
switch (kctrl->private_value) {
case VOLUME_PLAYBACK:
/* Playback is always on port 0 */
cur_vol = port_info->playback.volume;
siu_write32(base + SIU_SBDVCA, new_vol);
port_info->playback.volume = new_vol;
break;
case VOLUME_CAPTURE:
/* Capture is always on port 1 */
cur_vol = port_info->capture.volume;
siu_write32(base + SIU_SBDVCB, new_vol);
port_info->capture.volume = new_vol;
break;
default:
dev_err(dev, "%s() invalid private_value=%ld\n",
__func__, kctrl->private_value);
return -EINVAL;
}
if (cur_vol != new_vol)
return 1;
return 0;
}
static struct snd_kcontrol_new playback_controls = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "PCM Playback Volume",
.index = 0,
.info = siu_dai_info_volume,
.get = siu_dai_get_volume,
.put = siu_dai_put_volume,
.private_value = VOLUME_PLAYBACK,
};
static struct snd_kcontrol_new capture_controls = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "PCM Capture Volume",
.index = 0,
.info = siu_dai_info_volume,
.get = siu_dai_get_volume,
.put = siu_dai_put_volume,
.private_value = VOLUME_CAPTURE,
};
int siu_init_port(int port, struct siu_port **port_info, struct snd_card *card)
{
struct device *dev = card->dev;
struct snd_kcontrol *kctrl;
int ret;
*port_info = kzalloc(sizeof(**port_info), GFP_KERNEL);
if (!*port_info)
return -ENOMEM;
dev_dbg(dev, "%s: port #%d@%p\n", __func__, port, *port_info);
(*port_info)->playback.volume = DFLT_VOLUME_LEVEL;
(*port_info)->capture.volume = DFLT_VOLUME_LEVEL;
/*
* Add mixer support. The SPB is used to change the volume. Both
* ports use the same SPB. Therefore, we only register one
* control instance since it will be used by both channels.
* In error case we continue without controls.
*/
kctrl = snd_ctl_new1(&playback_controls, *port_info);
ret = snd_ctl_add(card, kctrl);
if (ret < 0)
dev_err(dev,
"failed to add playback controls %p port=%d err=%d\n",
kctrl, port, ret);
kctrl = snd_ctl_new1(&capture_controls, *port_info);
ret = snd_ctl_add(card, kctrl);
if (ret < 0)
dev_err(dev,
"failed to add capture controls %p port=%d err=%d\n",
kctrl, port, ret);
return 0;
}
void siu_free_port(struct siu_port *port_info)
{
kfree(port_info);
}
static int siu_dai_startup(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct siu_info *info = siu_i2s_dai.private_data;
struct snd_pcm_runtime *rt = substream->runtime;
struct siu_port *port_info = siu_port_info(substream);
int ret;
dev_dbg(substream->pcm->card->dev, "%s: port=%d@%p\n", __func__,
info->port_id, port_info);
snd_soc_set_runtime_hwparams(substream, &siu_dai_pcm_hw);
ret = snd_pcm_hw_constraint_integer(rt, SNDRV_PCM_HW_PARAM_PERIODS);
if (unlikely(ret < 0))
return ret;
siu_dai_start(port_info);
return 0;
}
static void siu_dai_shutdown(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct siu_info *info = siu_i2s_dai.private_data;
struct siu_port *port_info = siu_port_info(substream);
dev_dbg(substream->pcm->card->dev, "%s: port=%d@%p\n", __func__,
info->port_id, port_info);
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
port_info->play_cap &= ~PLAYBACK_ENABLED;
else
port_info->play_cap &= ~CAPTURE_ENABLED;
/* Stop the siu if the other stream is not using it */
if (!port_info->play_cap) {
/* during stmread or stmwrite ? */
BUG_ON(port_info->playback.rw_flg || port_info->capture.rw_flg);
siu_dai_spbstop(port_info);
siu_dai_stop();
}
}
/* PCM part of siu_dai_playback_prepare() / siu_dai_capture_prepare() */
static int siu_dai_prepare(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct siu_info *info = siu_i2s_dai.private_data;
struct snd_pcm_runtime *rt = substream->runtime;
struct siu_port *port_info = siu_port_info(substream);
struct siu_stream *siu_stream;
int self, ret;
dev_dbg(substream->pcm->card->dev,
"%s: port %d, active streams %lx, %d channels\n",
__func__, info->port_id, port_info->play_cap, rt->channels);
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
self = PLAYBACK_ENABLED;
siu_stream = &port_info->playback;
} else {
self = CAPTURE_ENABLED;
siu_stream = &port_info->capture;
}
/* Set up the siu if not already done */
if (!port_info->play_cap) {
siu_stream->rw_flg = 0; /* stream-data transfer flag */
siu_dai_spbAselect(port_info);
siu_dai_spbBselect(port_info);
siu_dai_open(siu_stream);
siu_dai_pcmdatapack(siu_stream);
ret = siu_dai_spbstart(port_info);
if (ret < 0)
goto fail;
} else {
ret = 0;
}
port_info->play_cap |= self;
fail:
return ret;
}
/*
* SIU can set bus format to I2S / PCM / SPDIF independently for playback and
* capture, however, the current API sets the bus format globally for a DAI.
*/
static int siu_dai_set_fmt(struct snd_soc_dai *dai,
unsigned int fmt)
{
struct siu_info *info = siu_i2s_dai.private_data;
u32 __iomem *base = info->reg;
u32 ifctl;
dev_dbg(dai->dev, "%s: fmt 0x%x on port %d\n",
__func__, fmt, info->port_id);
if (info->port_id < 0)
return -ENODEV;
/* Here select between I2S / PCM / SPDIF */
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_I2S:
ifctl = siu_flags[info->port_id].playback.i2s |
siu_flags[info->port_id].capture.i2s;
break;
case SND_SOC_DAIFMT_LEFT_J:
ifctl = siu_flags[info->port_id].playback.pcm |
siu_flags[info->port_id].capture.pcm;
break;
/* SPDIF disabled - see comment at the top */
default:
return -EINVAL;
}
ifctl |= ~(siu_flags[info->port_id].playback.mask |
siu_flags[info->port_id].capture.mask) &
siu_read32(base + SIU_IFCTL);
siu_write32(base + SIU_IFCTL, ifctl);
return 0;
}
static int siu_dai_set_sysclk(struct snd_soc_dai *dai, int clk_id,
unsigned int freq, int dir)
{
struct clk *siu_clk, *parent_clk;
char *siu_name, *parent_name;
int ret;
if (dir != SND_SOC_CLOCK_IN)
return -EINVAL;
dev_dbg(dai->dev, "%s: using clock %d\n", __func__, clk_id);
switch (clk_id) {
case SIU_CLKA_PLL:
siu_name = "siua_clk";
parent_name = "pll_clk";
break;
case SIU_CLKA_EXT:
siu_name = "siua_clk";
parent_name = "siumcka_clk";
break;
case SIU_CLKB_PLL:
siu_name = "siub_clk";
parent_name = "pll_clk";
break;
case SIU_CLKB_EXT:
siu_name = "siub_clk";
parent_name = "siumckb_clk";
break;
default:
return -EINVAL;
}
siu_clk = clk_get(siu_i2s_dai.dev, siu_name);
if (IS_ERR(siu_clk))
return PTR_ERR(siu_clk);
parent_clk = clk_get(siu_i2s_dai.dev, parent_name);
if (!IS_ERR(parent_clk)) {
ret = clk_set_parent(siu_clk, parent_clk);
if (!ret)
clk_set_rate(siu_clk, freq);
clk_put(parent_clk);
}
clk_put(siu_clk);
return 0;
}
static struct snd_soc_dai_ops siu_dai_ops = {
.startup = siu_dai_startup,
.shutdown = siu_dai_shutdown,
.prepare = siu_dai_prepare,
.set_sysclk = siu_dai_set_sysclk,
.set_fmt = siu_dai_set_fmt,
};
struct snd_soc_dai siu_i2s_dai = {
.name = "sh-siu",
.id = 0,
.playback = {
.channels_min = 2,
.channels_max = 2,
.formats = SNDRV_PCM_FMTBIT_S16,
.rates = SNDRV_PCM_RATE_8000_48000,
},
.capture = {
.channels_min = 2,
.channels_max = 2,
.formats = SNDRV_PCM_FMTBIT_S16,
.rates = SNDRV_PCM_RATE_8000_48000,
},
.ops = &siu_dai_ops,
};
EXPORT_SYMBOL_GPL(siu_i2s_dai);
static int __devinit siu_probe(struct platform_device *pdev)
{
const struct firmware *fw_entry;
struct resource *res, *region;
struct siu_info *info;
int ret;
info = kmalloc(sizeof(*info), GFP_KERNEL);
if (!info)
return -ENOMEM;
ret = request_firmware(&fw_entry, "siu_spb.bin", &pdev->dev);
if (ret)
goto ereqfw;
/*
* Loaded firmware is "const" - read only, but we have to modify it in
* snd_siu_sh7343_spbAselect() and snd_siu_sh7343_spbBselect()
*/
memcpy(&info->fw, fw_entry->data, fw_entry->size);
release_firmware(fw_entry);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
ret = -ENODEV;
goto egetres;
}
region = request_mem_region(res->start, resource_size(res),
pdev->name);
if (!region) {
dev_err(&pdev->dev, "SIU region already claimed\n");
ret = -EBUSY;
goto ereqmemreg;
}
ret = -ENOMEM;
info->pram = ioremap(res->start, PRAM_SIZE);
if (!info->pram)
goto emappram;
info->xram = ioremap(res->start + XRAM_OFFSET, XRAM_SIZE);
if (!info->xram)
goto emapxram;
info->yram = ioremap(res->start + YRAM_OFFSET, YRAM_SIZE);
if (!info->yram)
goto emapyram;
info->reg = ioremap(res->start + REG_OFFSET, resource_size(res) -
REG_OFFSET);
if (!info->reg)
goto emapreg;
siu_i2s_dai.dev = &pdev->dev;
siu_i2s_dai.private_data = info;
ret = snd_soc_register_dais(&siu_i2s_dai, 1);
if (ret < 0)
goto edaiinit;
ret = snd_soc_register_platform(&siu_platform);
if (ret < 0)
goto esocregp;
pm_runtime_enable(&pdev->dev);
return ret;
esocregp:
snd_soc_unregister_dais(&siu_i2s_dai, 1);
edaiinit:
iounmap(info->reg);
emapreg:
iounmap(info->yram);
emapyram:
iounmap(info->xram);
emapxram:
iounmap(info->pram);
emappram:
release_mem_region(res->start, resource_size(res));
ereqmemreg:
egetres:
ereqfw:
kfree(info);
return ret;
}
static int __devexit siu_remove(struct platform_device *pdev)
{
struct siu_info *info = siu_i2s_dai.private_data;
struct resource *res;
pm_runtime_disable(&pdev->dev);
snd_soc_unregister_platform(&siu_platform);
snd_soc_unregister_dais(&siu_i2s_dai, 1);
iounmap(info->reg);
iounmap(info->yram);
iounmap(info->xram);
iounmap(info->pram);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (res)
release_mem_region(res->start, resource_size(res));
kfree(info);
return 0;
}
static struct platform_driver siu_driver = {
.driver = {
.name = "sh_siu",
},
.probe = siu_probe,
.remove = __devexit_p(siu_remove),
};
static int __init siu_init(void)
{
return platform_driver_register(&siu_driver);
}
static void __exit siu_exit(void)
{
platform_driver_unregister(&siu_driver);
}
module_init(siu_init)
module_exit(siu_exit)
MODULE_AUTHOR("Carlos Munoz <carlos@kenati.com>");
MODULE_DESCRIPTION("ALSA SoC SH7722 SIU driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
gauravds/linux | arch/powerpc/platforms/86xx/sbc8641d.c | 1347 | 2621 | /*
* SBC8641D board specific routines
*
* Copyright 2008 Wind River Systems Inc.
*
* By Paul Gortmaker (see MAINTAINERS for contact information)
*
* Based largely on the 8641 HPCN support by Freescale Semiconductor Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/stddef.h>
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/kdev_t.h>
#include <linux/delay.h>
#include <linux/seq_file.h>
#include <linux/of_platform.h>
#include <asm/time.h>
#include <asm/machdep.h>
#include <asm/pci-bridge.h>
#include <asm/prom.h>
#include <mm/mmu_decl.h>
#include <asm/udbg.h>
#include <asm/mpic.h>
#include <sysdev/fsl_pci.h>
#include <sysdev/fsl_soc.h>
#include "mpc86xx.h"
static void __init
sbc8641_setup_arch(void)
{
if (ppc_md.progress)
ppc_md.progress("sbc8641_setup_arch()", 0);
printk("SBC8641 board from Wind River\n");
#ifdef CONFIG_SMP
mpc86xx_smp_init();
#endif
fsl_pci_assign_primary();
}
static void
sbc8641_show_cpuinfo(struct seq_file *m)
{
uint svid = mfspr(SPRN_SVR);
seq_printf(m, "Vendor\t\t: Wind River Systems\n");
seq_printf(m, "SVR\t\t: 0x%x\n", svid);
}
/*
* Called very early, device-tree isn't unflattened
*/
static int __init sbc8641_probe(void)
{
unsigned long root = of_get_flat_dt_root();
if (of_flat_dt_is_compatible(root, "wind,sbc8641"))
return 1; /* Looks good */
return 0;
}
static long __init
mpc86xx_time_init(void)
{
unsigned int temp;
/* Set the time base to zero */
mtspr(SPRN_TBWL, 0);
mtspr(SPRN_TBWU, 0);
temp = mfspr(SPRN_HID0);
temp |= HID0_TBEN;
mtspr(SPRN_HID0, temp);
asm volatile("isync");
return 0;
}
static const struct of_device_id of_bus_ids[] __initconst = {
{ .compatible = "simple-bus", },
{ .compatible = "gianfar", },
{ .compatible = "fsl,mpc8641-pcie", },
{},
};
static int __init declare_of_platform_devices(void)
{
of_platform_bus_probe(NULL, of_bus_ids, NULL);
return 0;
}
machine_arch_initcall(sbc8641, declare_of_platform_devices);
define_machine(sbc8641) {
.name = "SBC8641D",
.probe = sbc8641_probe,
.setup_arch = sbc8641_setup_arch,
.init_IRQ = mpc86xx_init_irq,
.show_cpuinfo = sbc8641_show_cpuinfo,
.get_irq = mpic_get_irq,
.restart = fsl_rstcr_restart,
.time_init = mpc86xx_time_init,
.calibrate_decr = generic_calibrate_decr,
.progress = udbg_progress,
#ifdef CONFIG_PCI
.pcibios_fixup_bus = fsl_pcibios_fixup_bus,
#endif
};
| gpl-2.0 |
fullerdj/ceph-client | arch/cris/arch-v32/mach-a3/arbiter.c | 2115 | 17664 | /*
* Memory arbiter functions. Allocates bandwidth through the
* arbiter and sets up arbiter breakpoints.
*
* The algorithm first assigns slots to the clients that has specified
* bandwidth (e.g. ethernet) and then the remaining slots are divided
* on all the active clients.
*
* Copyright (c) 2004-2007 Axis Communications AB.
*
* The artpec-3 has two arbiters. The memory hierarchy looks like this:
*
*
* CPU DMAs
* | |
* | |
* -------------- ------------------
* | foo arbiter|----| Internal memory|
* -------------- ------------------
* |
* --------------
* | L2 cache |
* --------------
* |
* h264 etc |
* | |
* | |
* --------------
* | bar arbiter|
* --------------
* |
* ---------
* | SDRAM |
* ---------
*
*/
#include <hwregs/reg_map.h>
#include <hwregs/reg_rdwr.h>
#include <hwregs/marb_foo_defs.h>
#include <hwregs/marb_bar_defs.h>
#include <arbiter.h>
#include <hwregs/intr_vect.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/signal.h>
#include <linux/errno.h>
#include <linux/spinlock.h>
#include <asm/io.h>
#include <asm/irq_regs.h>
#define D(x)
struct crisv32_watch_entry {
unsigned long instance;
watch_callback *cb;
unsigned long start;
unsigned long end;
int used;
};
#define NUMBER_OF_BP 4
#define SDRAM_BANDWIDTH 400000000
#define INTMEM_BANDWIDTH 400000000
#define NBR_OF_SLOTS 64
#define NBR_OF_REGIONS 2
#define NBR_OF_CLIENTS 15
#define ARBITERS 2
#define UNASSIGNED 100
struct arbiter {
unsigned long instance;
int nbr_regions;
int nbr_clients;
int requested_slots[NBR_OF_REGIONS][NBR_OF_CLIENTS];
int active_clients[NBR_OF_REGIONS][NBR_OF_CLIENTS];
};
static struct crisv32_watch_entry watches[ARBITERS][NUMBER_OF_BP] =
{
{
{regi_marb_foo_bp0},
{regi_marb_foo_bp1},
{regi_marb_foo_bp2},
{regi_marb_foo_bp3}
},
{
{regi_marb_bar_bp0},
{regi_marb_bar_bp1},
{regi_marb_bar_bp2},
{regi_marb_bar_bp3}
}
};
struct arbiter arbiters[ARBITERS] =
{
{ /* L2 cache arbiter */
.instance = regi_marb_foo,
.nbr_regions = 2,
.nbr_clients = 15
},
{ /* DDR2 arbiter */
.instance = regi_marb_bar,
.nbr_regions = 1,
.nbr_clients = 9
}
};
static int max_bandwidth[NBR_OF_REGIONS] = {SDRAM_BANDWIDTH, INTMEM_BANDWIDTH};
DEFINE_SPINLOCK(arbiter_lock);
static irqreturn_t
crisv32_foo_arbiter_irq(int irq, void *dev_id);
static irqreturn_t
crisv32_bar_arbiter_irq(int irq, void *dev_id);
/*
* "I'm the arbiter, I know the score.
* From square one I'll be watching all 64."
* (memory arbiter slots, that is)
*
* Or in other words:
* Program the memory arbiter slots for "region" according to what's
* in requested_slots[] and active_clients[], while minimizing
* latency. A caller may pass a non-zero positive amount for
* "unused_slots", which must then be the unallocated, remaining
* number of slots, free to hand out to any client.
*/
static void crisv32_arbiter_config(int arbiter, int region, int unused_slots)
{
int slot;
int client;
int interval = 0;
/*
* This vector corresponds to the hardware arbiter slots (see
* the hardware documentation for semantics). We initialize
* each slot with a suitable sentinel value outside the valid
* range {0 .. NBR_OF_CLIENTS - 1} and replace them with
* client indexes. Then it's fed to the hardware.
*/
s8 val[NBR_OF_SLOTS];
for (slot = 0; slot < NBR_OF_SLOTS; slot++)
val[slot] = -1;
for (client = 0; client < arbiters[arbiter].nbr_clients; client++) {
int pos;
/* Allocate the requested non-zero number of slots, but
* also give clients with zero-requests one slot each
* while stocks last. We do the latter here, in client
* order. This makes sure zero-request clients are the
* first to get to any spare slots, else those slots
* could, when bandwidth is allocated close to the limit,
* all be allocated to low-index non-zero-request clients
* in the default-fill loop below. Another positive but
* secondary effect is a somewhat better spread of the
* zero-bandwidth clients in the vector, avoiding some of
* the latency that could otherwise be caused by the
* partitioning of non-zero-bandwidth clients at low
* indexes and zero-bandwidth clients at high
* indexes. (Note that this spreading can only affect the
* unallocated bandwidth.) All the above only matters for
* memory-intensive situations, of course.
*/
if (!arbiters[arbiter].requested_slots[region][client]) {
/*
* Skip inactive clients. Also skip zero-slot
* allocations in this pass when there are no known
* free slots.
*/
if (!arbiters[arbiter].active_clients[region][client] ||
unused_slots <= 0)
continue;
unused_slots--;
/* Only allocate one slot for this client. */
interval = NBR_OF_SLOTS;
} else
interval = NBR_OF_SLOTS /
arbiters[arbiter].requested_slots[region][client];
pos = 0;
while (pos < NBR_OF_SLOTS) {
if (val[pos] >= 0)
pos++;
else {
val[pos] = client;
pos += interval;
}
}
}
client = 0;
for (slot = 0; slot < NBR_OF_SLOTS; slot++) {
/*
* Allocate remaining slots in round-robin
* client-number order for active clients. For this
* pass, we ignore requested bandwidth and previous
* allocations.
*/
if (val[slot] < 0) {
int first = client;
while (!arbiters[arbiter].active_clients[region][client]) {
client = (client + 1) %
arbiters[arbiter].nbr_clients;
if (client == first)
break;
}
val[slot] = client;
client = (client + 1) % arbiters[arbiter].nbr_clients;
}
if (arbiter == 0) {
if (region == EXT_REGION)
REG_WR_INT_VECT(marb_foo, regi_marb_foo,
rw_l2_slots, slot, val[slot]);
else if (region == INT_REGION)
REG_WR_INT_VECT(marb_foo, regi_marb_foo,
rw_intm_slots, slot, val[slot]);
} else {
REG_WR_INT_VECT(marb_bar, regi_marb_bar,
rw_ddr2_slots, slot, val[slot]);
}
}
}
extern char _stext, _etext;
static void crisv32_arbiter_init(void)
{
static int initialized;
if (initialized)
return;
initialized = 1;
/*
* CPU caches are always set to active, but with zero
* bandwidth allocated. It should be ok to allocate zero
* bandwidth for the caches, because DMA for other channels
* will supposedly finish, once their programmed amount is
* done, and then the caches will get access according to the
* "fixed scheme" for unclaimed slots. Though, if for some
* use-case somewhere, there's a maximum CPU latency for
* e.g. some interrupt, we have to start allocating specific
* bandwidth for the CPU caches too.
*/
arbiters[0].active_clients[EXT_REGION][11] = 1;
arbiters[0].active_clients[EXT_REGION][12] = 1;
crisv32_arbiter_config(0, EXT_REGION, 0);
crisv32_arbiter_config(0, INT_REGION, 0);
crisv32_arbiter_config(1, EXT_REGION, 0);
if (request_irq(MEMARB_FOO_INTR_VECT, crisv32_foo_arbiter_irq,
0, "arbiter", NULL))
printk(KERN_ERR "Couldn't allocate arbiter IRQ\n");
if (request_irq(MEMARB_BAR_INTR_VECT, crisv32_bar_arbiter_irq,
0, "arbiter", NULL))
printk(KERN_ERR "Couldn't allocate arbiter IRQ\n");
#ifndef CONFIG_ETRAX_KGDB
/* Global watch for writes to kernel text segment. */
crisv32_arbiter_watch(virt_to_phys(&_stext), &_etext - &_stext,
MARB_CLIENTS(arbiter_all_clients, arbiter_bar_all_clients),
arbiter_all_write, NULL);
#endif
/* Set up max burst sizes by default */
REG_WR_INT(marb_bar, regi_marb_bar, rw_h264_rd_burst, 3);
REG_WR_INT(marb_bar, regi_marb_bar, rw_h264_wr_burst, 3);
REG_WR_INT(marb_bar, regi_marb_bar, rw_ccd_burst, 3);
REG_WR_INT(marb_bar, regi_marb_bar, rw_vin_wr_burst, 3);
REG_WR_INT(marb_bar, regi_marb_bar, rw_vin_rd_burst, 3);
REG_WR_INT(marb_bar, regi_marb_bar, rw_sclr_rd_burst, 3);
REG_WR_INT(marb_bar, regi_marb_bar, rw_vout_burst, 3);
REG_WR_INT(marb_bar, regi_marb_bar, rw_sclr_fifo_burst, 3);
REG_WR_INT(marb_bar, regi_marb_bar, rw_l2cache_burst, 3);
}
int crisv32_arbiter_allocate_bandwidth(int client, int region,
unsigned long bandwidth)
{
int i;
int total_assigned = 0;
int total_clients = 0;
int req;
int arbiter = 0;
crisv32_arbiter_init();
if (client & 0xffff0000) {
arbiter = 1;
client >>= 16;
}
for (i = 0; i < arbiters[arbiter].nbr_clients; i++) {
total_assigned += arbiters[arbiter].requested_slots[region][i];
total_clients += arbiters[arbiter].active_clients[region][i];
}
/* Avoid division by 0 for 0-bandwidth requests. */
req = bandwidth == 0
? 0 : NBR_OF_SLOTS / (max_bandwidth[region] / bandwidth);
/*
* We make sure that there are enough slots only for non-zero
* requests. Requesting 0 bandwidth *may* allocate slots,
* though if all bandwidth is allocated, such a client won't
* get any and will have to rely on getting memory access
* according to the fixed scheme that's the default when one
* of the slot-allocated clients doesn't claim their slot.
*/
if (total_assigned + req > NBR_OF_SLOTS)
return -ENOMEM;
arbiters[arbiter].active_clients[region][client] = 1;
arbiters[arbiter].requested_slots[region][client] = req;
crisv32_arbiter_config(arbiter, region, NBR_OF_SLOTS - total_assigned);
/* Propagate allocation from foo to bar */
if (arbiter == 0)
crisv32_arbiter_allocate_bandwidth(8 << 16,
EXT_REGION, bandwidth);
return 0;
}
/*
* Main entry for bandwidth deallocation.
*
* Strictly speaking, for a somewhat constant set of clients where
* each client gets a constant bandwidth and is just enabled or
* disabled (somewhat dynamically), no action is necessary here to
* avoid starvation for non-zero-allocation clients, as the allocated
* slots will just be unused. However, handing out those unused slots
* to active clients avoids needless latency if the "fixed scheme"
* would give unclaimed slots to an eager low-index client.
*/
void crisv32_arbiter_deallocate_bandwidth(int client, int region)
{
int i;
int total_assigned = 0;
int arbiter = 0;
if (client & 0xffff0000)
arbiter = 1;
arbiters[arbiter].requested_slots[region][client] = 0;
arbiters[arbiter].active_clients[region][client] = 0;
for (i = 0; i < arbiters[arbiter].nbr_clients; i++)
total_assigned += arbiters[arbiter].requested_slots[region][i];
crisv32_arbiter_config(arbiter, region, NBR_OF_SLOTS - total_assigned);
}
int crisv32_arbiter_watch(unsigned long start, unsigned long size,
unsigned long clients, unsigned long accesses,
watch_callback *cb)
{
int i;
int arbiter;
int used[2];
int ret = 0;
crisv32_arbiter_init();
if (start > 0x80000000) {
printk(KERN_ERR "Arbiter: %lX doesn't look like a "
"physical address", start);
return -EFAULT;
}
spin_lock(&arbiter_lock);
if (clients & 0xffff)
used[0] = 1;
if (clients & 0xffff0000)
used[1] = 1;
for (arbiter = 0; arbiter < ARBITERS; arbiter++) {
if (!used[arbiter])
continue;
for (i = 0; i < NUMBER_OF_BP; i++) {
if (!watches[arbiter][i].used) {
unsigned intr_mask;
if (arbiter)
intr_mask = REG_RD_INT(marb_bar,
regi_marb_bar, rw_intr_mask);
else
intr_mask = REG_RD_INT(marb_foo,
regi_marb_foo, rw_intr_mask);
watches[arbiter][i].used = 1;
watches[arbiter][i].start = start;
watches[arbiter][i].end = start + size;
watches[arbiter][i].cb = cb;
ret |= (i + 1) << (arbiter + 8);
if (arbiter) {
REG_WR_INT(marb_bar_bp,
watches[arbiter][i].instance,
rw_first_addr,
watches[arbiter][i].start);
REG_WR_INT(marb_bar_bp,
watches[arbiter][i].instance,
rw_last_addr,
watches[arbiter][i].end);
REG_WR_INT(marb_bar_bp,
watches[arbiter][i].instance,
rw_op, accesses);
REG_WR_INT(marb_bar_bp,
watches[arbiter][i].instance,
rw_clients,
clients & 0xffff);
} else {
REG_WR_INT(marb_foo_bp,
watches[arbiter][i].instance,
rw_first_addr,
watches[arbiter][i].start);
REG_WR_INT(marb_foo_bp,
watches[arbiter][i].instance,
rw_last_addr,
watches[arbiter][i].end);
REG_WR_INT(marb_foo_bp,
watches[arbiter][i].instance,
rw_op, accesses);
REG_WR_INT(marb_foo_bp,
watches[arbiter][i].instance,
rw_clients, clients >> 16);
}
if (i == 0)
intr_mask |= 1;
else if (i == 1)
intr_mask |= 2;
else if (i == 2)
intr_mask |= 4;
else if (i == 3)
intr_mask |= 8;
if (arbiter)
REG_WR_INT(marb_bar, regi_marb_bar,
rw_intr_mask, intr_mask);
else
REG_WR_INT(marb_foo, regi_marb_foo,
rw_intr_mask, intr_mask);
spin_unlock(&arbiter_lock);
break;
}
}
}
spin_unlock(&arbiter_lock);
if (ret)
return ret;
else
return -ENOMEM;
}
int crisv32_arbiter_unwatch(int id)
{
int arbiter;
int intr_mask;
crisv32_arbiter_init();
spin_lock(&arbiter_lock);
for (arbiter = 0; arbiter < ARBITERS; arbiter++) {
int id2;
if (arbiter)
intr_mask = REG_RD_INT(marb_bar, regi_marb_bar,
rw_intr_mask);
else
intr_mask = REG_RD_INT(marb_foo, regi_marb_foo,
rw_intr_mask);
id2 = (id & (0xff << (arbiter + 8))) >> (arbiter + 8);
if (id2 == 0)
continue;
id2--;
if ((id2 >= NUMBER_OF_BP) || (!watches[arbiter][id2].used)) {
spin_unlock(&arbiter_lock);
return -EINVAL;
}
memset(&watches[arbiter][id2], 0,
sizeof(struct crisv32_watch_entry));
if (id2 == 0)
intr_mask &= ~1;
else if (id2 == 1)
intr_mask &= ~2;
else if (id2 == 2)
intr_mask &= ~4;
else if (id2 == 3)
intr_mask &= ~8;
if (arbiter)
REG_WR_INT(marb_bar, regi_marb_bar, rw_intr_mask,
intr_mask);
else
REG_WR_INT(marb_foo, regi_marb_foo, rw_intr_mask,
intr_mask);
}
spin_unlock(&arbiter_lock);
return 0;
}
extern void show_registers(struct pt_regs *regs);
static irqreturn_t
crisv32_foo_arbiter_irq(int irq, void *dev_id)
{
reg_marb_foo_r_masked_intr masked_intr =
REG_RD(marb_foo, regi_marb_foo, r_masked_intr);
reg_marb_foo_bp_r_brk_clients r_clients;
reg_marb_foo_bp_r_brk_addr r_addr;
reg_marb_foo_bp_r_brk_op r_op;
reg_marb_foo_bp_r_brk_first_client r_first;
reg_marb_foo_bp_r_brk_size r_size;
reg_marb_foo_bp_rw_ack ack = {0};
reg_marb_foo_rw_ack_intr ack_intr = {
.bp0 = 1, .bp1 = 1, .bp2 = 1, .bp3 = 1
};
struct crisv32_watch_entry *watch;
unsigned arbiter = (unsigned)dev_id;
masked_intr = REG_RD(marb_foo, regi_marb_foo, r_masked_intr);
if (masked_intr.bp0)
watch = &watches[arbiter][0];
else if (masked_intr.bp1)
watch = &watches[arbiter][1];
else if (masked_intr.bp2)
watch = &watches[arbiter][2];
else if (masked_intr.bp3)
watch = &watches[arbiter][3];
else
return IRQ_NONE;
/* Retrieve all useful information and print it. */
r_clients = REG_RD(marb_foo_bp, watch->instance, r_brk_clients);
r_addr = REG_RD(marb_foo_bp, watch->instance, r_brk_addr);
r_op = REG_RD(marb_foo_bp, watch->instance, r_brk_op);
r_first = REG_RD(marb_foo_bp, watch->instance, r_brk_first_client);
r_size = REG_RD(marb_foo_bp, watch->instance, r_brk_size);
printk(KERN_DEBUG "Arbiter IRQ\n");
printk(KERN_DEBUG "Clients %X addr %X op %X first %X size %X\n",
REG_TYPE_CONV(int, reg_marb_foo_bp_r_brk_clients, r_clients),
REG_TYPE_CONV(int, reg_marb_foo_bp_r_brk_addr, r_addr),
REG_TYPE_CONV(int, reg_marb_foo_bp_r_brk_op, r_op),
REG_TYPE_CONV(int, reg_marb_foo_bp_r_brk_first_client, r_first),
REG_TYPE_CONV(int, reg_marb_foo_bp_r_brk_size, r_size));
REG_WR(marb_foo_bp, watch->instance, rw_ack, ack);
REG_WR(marb_foo, regi_marb_foo, rw_ack_intr, ack_intr);
printk(KERN_DEBUG "IRQ occurred at %X\n", (unsigned)get_irq_regs());
if (watch->cb)
watch->cb();
return IRQ_HANDLED;
}
static irqreturn_t
crisv32_bar_arbiter_irq(int irq, void *dev_id)
{
reg_marb_bar_r_masked_intr masked_intr =
REG_RD(marb_bar, regi_marb_bar, r_masked_intr);
reg_marb_bar_bp_r_brk_clients r_clients;
reg_marb_bar_bp_r_brk_addr r_addr;
reg_marb_bar_bp_r_brk_op r_op;
reg_marb_bar_bp_r_brk_first_client r_first;
reg_marb_bar_bp_r_brk_size r_size;
reg_marb_bar_bp_rw_ack ack = {0};
reg_marb_bar_rw_ack_intr ack_intr = {
.bp0 = 1, .bp1 = 1, .bp2 = 1, .bp3 = 1
};
struct crisv32_watch_entry *watch;
unsigned arbiter = (unsigned)dev_id;
masked_intr = REG_RD(marb_bar, regi_marb_bar, r_masked_intr);
if (masked_intr.bp0)
watch = &watches[arbiter][0];
else if (masked_intr.bp1)
watch = &watches[arbiter][1];
else if (masked_intr.bp2)
watch = &watches[arbiter][2];
else if (masked_intr.bp3)
watch = &watches[arbiter][3];
else
return IRQ_NONE;
/* Retrieve all useful information and print it. */
r_clients = REG_RD(marb_bar_bp, watch->instance, r_brk_clients);
r_addr = REG_RD(marb_bar_bp, watch->instance, r_brk_addr);
r_op = REG_RD(marb_bar_bp, watch->instance, r_brk_op);
r_first = REG_RD(marb_bar_bp, watch->instance, r_brk_first_client);
r_size = REG_RD(marb_bar_bp, watch->instance, r_brk_size);
printk(KERN_DEBUG "Arbiter IRQ\n");
printk(KERN_DEBUG "Clients %X addr %X op %X first %X size %X\n",
REG_TYPE_CONV(int, reg_marb_bar_bp_r_brk_clients, r_clients),
REG_TYPE_CONV(int, reg_marb_bar_bp_r_brk_addr, r_addr),
REG_TYPE_CONV(int, reg_marb_bar_bp_r_brk_op, r_op),
REG_TYPE_CONV(int, reg_marb_bar_bp_r_brk_first_client, r_first),
REG_TYPE_CONV(int, reg_marb_bar_bp_r_brk_size, r_size));
REG_WR(marb_bar_bp, watch->instance, rw_ack, ack);
REG_WR(marb_bar, regi_marb_bar, rw_ack_intr, ack_intr);
printk(KERN_DEBUG "IRQ occurred at %X\n", (unsigned)get_irq_regs()->erp);
if (watch->cb)
watch->cb();
return IRQ_HANDLED;
}
| gpl-2.0 |
The-Demon12/msm8916 | arch/arm/mach-kirkwood/board-ns2.c | 2115 | 1025 | /*
* Copyright 2012 (C), Simon Guinot <simon.guinot@sequanux.org>
*
* arch/arm/mach-kirkwood/board-ns2.c
*
* LaCie Network Space v2 board (and parents) initialization for drivers
* not converted to flattened device tree yet.
*
* 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/mv643xx_eth.h>
#include <linux/of.h>
#include "common.h"
static struct mv643xx_eth_platform_data ns2_ge00_data = {
.phy_addr = MV643XX_ETH_PHY_ADDR(8),
};
void __init ns2_init(void)
{
/*
* Basic setup. Needs to be called early.
*/
if (of_machine_is_compatible("lacie,cloudbox") ||
of_machine_is_compatible("lacie,netspace_lite_v2") ||
of_machine_is_compatible("lacie,netspace_mini_v2"))
ns2_ge00_data.phy_addr = MV643XX_ETH_PHY_ADDR(0);
kirkwood_ge00_init(&ns2_ge00_data);
}
| gpl-2.0 |
OneEducation/kernel-rk310-kitkat-firefly | drivers/i2c/busses/i2c-pmcmsp.c | 2371 | 17688 | /*
* Specific bus support for PMC-TWI compliant implementation on MSP71xx.
*
* Copyright 2005-2007 PMC-Sierra, Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/i2c.h>
#include <linux/interrupt.h>
#include <linux/completion.h>
#include <linux/mutex.h>
#include <linux/delay.h>
#include <linux/io.h>
#define DRV_NAME "pmcmsptwi"
#define MSP_TWI_SF_CLK_REG_OFFSET 0x00
#define MSP_TWI_HS_CLK_REG_OFFSET 0x04
#define MSP_TWI_CFG_REG_OFFSET 0x08
#define MSP_TWI_CMD_REG_OFFSET 0x0c
#define MSP_TWI_ADD_REG_OFFSET 0x10
#define MSP_TWI_DAT_0_REG_OFFSET 0x14
#define MSP_TWI_DAT_1_REG_OFFSET 0x18
#define MSP_TWI_INT_STS_REG_OFFSET 0x1c
#define MSP_TWI_INT_MSK_REG_OFFSET 0x20
#define MSP_TWI_BUSY_REG_OFFSET 0x24
#define MSP_TWI_INT_STS_DONE (1 << 0)
#define MSP_TWI_INT_STS_LOST_ARBITRATION (1 << 1)
#define MSP_TWI_INT_STS_NO_RESPONSE (1 << 2)
#define MSP_TWI_INT_STS_DATA_COLLISION (1 << 3)
#define MSP_TWI_INT_STS_BUSY (1 << 4)
#define MSP_TWI_INT_STS_ALL 0x1f
#define MSP_MAX_BYTES_PER_RW 8
#define MSP_MAX_POLL 5
#define MSP_POLL_DELAY 10
#define MSP_IRQ_TIMEOUT (MSP_MAX_POLL * MSP_POLL_DELAY)
/* IO Operation macros */
#define pmcmsptwi_readl __raw_readl
#define pmcmsptwi_writel __raw_writel
/* TWI command type */
enum pmcmsptwi_cmd_type {
MSP_TWI_CMD_WRITE = 0, /* Write only */
MSP_TWI_CMD_READ = 1, /* Read only */
MSP_TWI_CMD_WRITE_READ = 2, /* Write then Read */
};
/* The possible results of the xferCmd */
enum pmcmsptwi_xfer_result {
MSP_TWI_XFER_OK = 0,
MSP_TWI_XFER_TIMEOUT,
MSP_TWI_XFER_BUSY,
MSP_TWI_XFER_DATA_COLLISION,
MSP_TWI_XFER_NO_RESPONSE,
MSP_TWI_XFER_LOST_ARBITRATION,
};
/* Corresponds to a PMCTWI clock configuration register */
struct pmcmsptwi_clock {
u8 filter; /* Bits 15:12, default = 0x03 */
u16 clock; /* Bits 9:0, default = 0x001f */
};
struct pmcmsptwi_clockcfg {
struct pmcmsptwi_clock standard; /* The standard/fast clock config */
struct pmcmsptwi_clock highspeed; /* The highspeed clock config */
};
/* Corresponds to the main TWI configuration register */
struct pmcmsptwi_cfg {
u8 arbf; /* Bits 15:12, default=0x03 */
u8 nak; /* Bits 11:8, default=0x03 */
u8 add10; /* Bit 7, default=0x00 */
u8 mst_code; /* Bits 6:4, default=0x00 */
u8 arb; /* Bit 1, default=0x01 */
u8 highspeed; /* Bit 0, default=0x00 */
};
/* A single pmctwi command to issue */
struct pmcmsptwi_cmd {
u16 addr; /* The slave address (7 or 10 bits) */
enum pmcmsptwi_cmd_type type; /* The command type */
u8 write_len; /* Number of bytes in the write buffer */
u8 read_len; /* Number of bytes in the read buffer */
u8 *write_data; /* Buffer of characters to send */
u8 *read_data; /* Buffer to fill with incoming data */
};
/* The private data */
struct pmcmsptwi_data {
void __iomem *iobase; /* iomapped base for IO */
int irq; /* IRQ to use (0 disables) */
struct completion wait; /* Completion for xfer */
struct mutex lock; /* Used for threadsafeness */
enum pmcmsptwi_xfer_result last_result; /* result of last xfer */
};
/* The default settings */
static const struct pmcmsptwi_clockcfg pmcmsptwi_defclockcfg = {
.standard = {
.filter = 0x3,
.clock = 0x1f,
},
.highspeed = {
.filter = 0x3,
.clock = 0x1f,
},
};
static const struct pmcmsptwi_cfg pmcmsptwi_defcfg = {
.arbf = 0x03,
.nak = 0x03,
.add10 = 0x00,
.mst_code = 0x00,
.arb = 0x01,
.highspeed = 0x00,
};
static struct pmcmsptwi_data pmcmsptwi_data;
static struct i2c_adapter pmcmsptwi_adapter;
/* inline helper functions */
static inline u32 pmcmsptwi_clock_to_reg(
const struct pmcmsptwi_clock *clock)
{
return ((clock->filter & 0xf) << 12) | (clock->clock & 0x03ff);
}
static inline void pmcmsptwi_reg_to_clock(
u32 reg, struct pmcmsptwi_clock *clock)
{
clock->filter = (reg >> 12) & 0xf;
clock->clock = reg & 0x03ff;
}
static inline u32 pmcmsptwi_cfg_to_reg(const struct pmcmsptwi_cfg *cfg)
{
return ((cfg->arbf & 0xf) << 12) |
((cfg->nak & 0xf) << 8) |
((cfg->add10 & 0x1) << 7) |
((cfg->mst_code & 0x7) << 4) |
((cfg->arb & 0x1) << 1) |
(cfg->highspeed & 0x1);
}
static inline void pmcmsptwi_reg_to_cfg(u32 reg, struct pmcmsptwi_cfg *cfg)
{
cfg->arbf = (reg >> 12) & 0xf;
cfg->nak = (reg >> 8) & 0xf;
cfg->add10 = (reg >> 7) & 0x1;
cfg->mst_code = (reg >> 4) & 0x7;
cfg->arb = (reg >> 1) & 0x1;
cfg->highspeed = reg & 0x1;
}
/*
* Sets the current clock configuration
*/
static void pmcmsptwi_set_clock_config(const struct pmcmsptwi_clockcfg *cfg,
struct pmcmsptwi_data *data)
{
mutex_lock(&data->lock);
pmcmsptwi_writel(pmcmsptwi_clock_to_reg(&cfg->standard),
data->iobase + MSP_TWI_SF_CLK_REG_OFFSET);
pmcmsptwi_writel(pmcmsptwi_clock_to_reg(&cfg->highspeed),
data->iobase + MSP_TWI_HS_CLK_REG_OFFSET);
mutex_unlock(&data->lock);
}
/*
* Gets the current TWI bus configuration
*/
static void pmcmsptwi_get_twi_config(struct pmcmsptwi_cfg *cfg,
struct pmcmsptwi_data *data)
{
mutex_lock(&data->lock);
pmcmsptwi_reg_to_cfg(pmcmsptwi_readl(
data->iobase + MSP_TWI_CFG_REG_OFFSET), cfg);
mutex_unlock(&data->lock);
}
/*
* Sets the current TWI bus configuration
*/
static void pmcmsptwi_set_twi_config(const struct pmcmsptwi_cfg *cfg,
struct pmcmsptwi_data *data)
{
mutex_lock(&data->lock);
pmcmsptwi_writel(pmcmsptwi_cfg_to_reg(cfg),
data->iobase + MSP_TWI_CFG_REG_OFFSET);
mutex_unlock(&data->lock);
}
/*
* Parses the 'int_sts' register and returns a well-defined error code
*/
static enum pmcmsptwi_xfer_result pmcmsptwi_get_result(u32 reg)
{
if (reg & MSP_TWI_INT_STS_LOST_ARBITRATION) {
dev_dbg(&pmcmsptwi_adapter.dev,
"Result: Lost arbitration\n");
return MSP_TWI_XFER_LOST_ARBITRATION;
} else if (reg & MSP_TWI_INT_STS_NO_RESPONSE) {
dev_dbg(&pmcmsptwi_adapter.dev,
"Result: No response\n");
return MSP_TWI_XFER_NO_RESPONSE;
} else if (reg & MSP_TWI_INT_STS_DATA_COLLISION) {
dev_dbg(&pmcmsptwi_adapter.dev,
"Result: Data collision\n");
return MSP_TWI_XFER_DATA_COLLISION;
} else if (reg & MSP_TWI_INT_STS_BUSY) {
dev_dbg(&pmcmsptwi_adapter.dev,
"Result: Bus busy\n");
return MSP_TWI_XFER_BUSY;
}
dev_dbg(&pmcmsptwi_adapter.dev, "Result: Operation succeeded\n");
return MSP_TWI_XFER_OK;
}
/*
* In interrupt mode, handle the interrupt.
* NOTE: Assumes data->lock is held.
*/
static irqreturn_t pmcmsptwi_interrupt(int irq, void *ptr)
{
struct pmcmsptwi_data *data = ptr;
u32 reason = pmcmsptwi_readl(data->iobase +
MSP_TWI_INT_STS_REG_OFFSET);
pmcmsptwi_writel(reason, data->iobase + MSP_TWI_INT_STS_REG_OFFSET);
dev_dbg(&pmcmsptwi_adapter.dev, "Got interrupt 0x%08x\n", reason);
if (!(reason & MSP_TWI_INT_STS_DONE))
return IRQ_NONE;
data->last_result = pmcmsptwi_get_result(reason);
complete(&data->wait);
return IRQ_HANDLED;
}
/*
* Probe for and register the device and return 0 if there is one.
*/
static int pmcmsptwi_probe(struct platform_device *pldev)
{
struct resource *res;
int rc = -ENODEV;
/* get the static platform resources */
res = platform_get_resource(pldev, IORESOURCE_MEM, 0);
if (!res) {
dev_err(&pldev->dev, "IOMEM resource not found\n");
goto ret_err;
}
/* reserve the memory region */
if (!request_mem_region(res->start, resource_size(res),
pldev->name)) {
dev_err(&pldev->dev,
"Unable to get memory/io address region 0x%08x\n",
res->start);
rc = -EBUSY;
goto ret_err;
}
/* remap the memory */
pmcmsptwi_data.iobase = ioremap_nocache(res->start,
resource_size(res));
if (!pmcmsptwi_data.iobase) {
dev_err(&pldev->dev,
"Unable to ioremap address 0x%08x\n", res->start);
rc = -EIO;
goto ret_unreserve;
}
/* request the irq */
pmcmsptwi_data.irq = platform_get_irq(pldev, 0);
if (pmcmsptwi_data.irq) {
rc = request_irq(pmcmsptwi_data.irq, &pmcmsptwi_interrupt,
IRQF_SHARED, pldev->name, &pmcmsptwi_data);
if (rc == 0) {
/*
* Enable 'DONE' interrupt only.
*
* If you enable all interrupts, you will get one on
* error and another when the operation completes.
* This way you only have to handle one interrupt,
* but you can still check all result flags.
*/
pmcmsptwi_writel(MSP_TWI_INT_STS_DONE,
pmcmsptwi_data.iobase +
MSP_TWI_INT_MSK_REG_OFFSET);
} else {
dev_warn(&pldev->dev,
"Could not assign TWI IRQ handler "
"to irq %d (continuing with poll)\n",
pmcmsptwi_data.irq);
pmcmsptwi_data.irq = 0;
}
}
init_completion(&pmcmsptwi_data.wait);
mutex_init(&pmcmsptwi_data.lock);
pmcmsptwi_set_clock_config(&pmcmsptwi_defclockcfg, &pmcmsptwi_data);
pmcmsptwi_set_twi_config(&pmcmsptwi_defcfg, &pmcmsptwi_data);
printk(KERN_INFO DRV_NAME ": Registering MSP71xx I2C adapter\n");
pmcmsptwi_adapter.dev.parent = &pldev->dev;
platform_set_drvdata(pldev, &pmcmsptwi_adapter);
i2c_set_adapdata(&pmcmsptwi_adapter, &pmcmsptwi_data);
rc = i2c_add_adapter(&pmcmsptwi_adapter);
if (rc) {
dev_err(&pldev->dev, "Unable to register I2C adapter\n");
goto ret_unmap;
}
return 0;
ret_unmap:
if (pmcmsptwi_data.irq) {
pmcmsptwi_writel(0,
pmcmsptwi_data.iobase + MSP_TWI_INT_MSK_REG_OFFSET);
free_irq(pmcmsptwi_data.irq, &pmcmsptwi_data);
}
iounmap(pmcmsptwi_data.iobase);
ret_unreserve:
release_mem_region(res->start, resource_size(res));
ret_err:
return rc;
}
/*
* Release the device and return 0 if there is one.
*/
static int pmcmsptwi_remove(struct platform_device *pldev)
{
struct resource *res;
i2c_del_adapter(&pmcmsptwi_adapter);
if (pmcmsptwi_data.irq) {
pmcmsptwi_writel(0,
pmcmsptwi_data.iobase + MSP_TWI_INT_MSK_REG_OFFSET);
free_irq(pmcmsptwi_data.irq, &pmcmsptwi_data);
}
iounmap(pmcmsptwi_data.iobase);
res = platform_get_resource(pldev, IORESOURCE_MEM, 0);
release_mem_region(res->start, resource_size(res));
return 0;
}
/*
* Polls the 'busy' register until the command is complete.
* NOTE: Assumes data->lock is held.
*/
static void pmcmsptwi_poll_complete(struct pmcmsptwi_data *data)
{
int i;
for (i = 0; i < MSP_MAX_POLL; i++) {
u32 val = pmcmsptwi_readl(data->iobase +
MSP_TWI_BUSY_REG_OFFSET);
if (val == 0) {
u32 reason = pmcmsptwi_readl(data->iobase +
MSP_TWI_INT_STS_REG_OFFSET);
pmcmsptwi_writel(reason, data->iobase +
MSP_TWI_INT_STS_REG_OFFSET);
data->last_result = pmcmsptwi_get_result(reason);
return;
}
udelay(MSP_POLL_DELAY);
}
dev_dbg(&pmcmsptwi_adapter.dev, "Result: Poll timeout\n");
data->last_result = MSP_TWI_XFER_TIMEOUT;
}
/*
* Do the transfer (low level):
* May use interrupt-driven or polling, depending on if an IRQ is
* presently registered.
* NOTE: Assumes data->lock is held.
*/
static enum pmcmsptwi_xfer_result pmcmsptwi_do_xfer(
u32 reg, struct pmcmsptwi_data *data)
{
dev_dbg(&pmcmsptwi_adapter.dev, "Writing cmd reg 0x%08x\n", reg);
pmcmsptwi_writel(reg, data->iobase + MSP_TWI_CMD_REG_OFFSET);
if (data->irq) {
unsigned long timeleft = wait_for_completion_timeout(
&data->wait, MSP_IRQ_TIMEOUT);
if (timeleft == 0) {
dev_dbg(&pmcmsptwi_adapter.dev,
"Result: IRQ timeout\n");
complete(&data->wait);
data->last_result = MSP_TWI_XFER_TIMEOUT;
}
} else
pmcmsptwi_poll_complete(data);
return data->last_result;
}
/*
* Helper routine, converts 'pmctwi_cmd' struct to register format
*/
static inline u32 pmcmsptwi_cmd_to_reg(const struct pmcmsptwi_cmd *cmd)
{
return ((cmd->type & 0x3) << 8) |
(((cmd->write_len - 1) & 0x7) << 4) |
((cmd->read_len - 1) & 0x7);
}
/*
* Do the transfer (high level)
*/
static enum pmcmsptwi_xfer_result pmcmsptwi_xfer_cmd(
struct pmcmsptwi_cmd *cmd,
struct pmcmsptwi_data *data)
{
enum pmcmsptwi_xfer_result retval;
if ((cmd->type == MSP_TWI_CMD_WRITE && cmd->write_len == 0) ||
(cmd->type == MSP_TWI_CMD_READ && cmd->read_len == 0) ||
(cmd->type == MSP_TWI_CMD_WRITE_READ &&
(cmd->read_len == 0 || cmd->write_len == 0))) {
dev_err(&pmcmsptwi_adapter.dev,
"%s: Cannot transfer less than 1 byte\n",
__func__);
return -EINVAL;
}
if (cmd->read_len > MSP_MAX_BYTES_PER_RW ||
cmd->write_len > MSP_MAX_BYTES_PER_RW) {
dev_err(&pmcmsptwi_adapter.dev,
"%s: Cannot transfer more than %d bytes\n",
__func__, MSP_MAX_BYTES_PER_RW);
return -EINVAL;
}
mutex_lock(&data->lock);
dev_dbg(&pmcmsptwi_adapter.dev,
"Setting address to 0x%04x\n", cmd->addr);
pmcmsptwi_writel(cmd->addr, data->iobase + MSP_TWI_ADD_REG_OFFSET);
if (cmd->type == MSP_TWI_CMD_WRITE ||
cmd->type == MSP_TWI_CMD_WRITE_READ) {
u64 tmp = be64_to_cpup((__be64 *)cmd->write_data);
tmp >>= (MSP_MAX_BYTES_PER_RW - cmd->write_len) * 8;
dev_dbg(&pmcmsptwi_adapter.dev, "Writing 0x%016llx\n", tmp);
pmcmsptwi_writel(tmp & 0x00000000ffffffffLL,
data->iobase + MSP_TWI_DAT_0_REG_OFFSET);
if (cmd->write_len > 4)
pmcmsptwi_writel(tmp >> 32,
data->iobase + MSP_TWI_DAT_1_REG_OFFSET);
}
retval = pmcmsptwi_do_xfer(pmcmsptwi_cmd_to_reg(cmd), data);
if (retval != MSP_TWI_XFER_OK)
goto xfer_err;
if (cmd->type == MSP_TWI_CMD_READ ||
cmd->type == MSP_TWI_CMD_WRITE_READ) {
int i;
u64 rmsk = ~(0xffffffffffffffffLL << (cmd->read_len * 8));
u64 tmp = (u64)pmcmsptwi_readl(data->iobase +
MSP_TWI_DAT_0_REG_OFFSET);
if (cmd->read_len > 4)
tmp |= (u64)pmcmsptwi_readl(data->iobase +
MSP_TWI_DAT_1_REG_OFFSET) << 32;
tmp &= rmsk;
dev_dbg(&pmcmsptwi_adapter.dev, "Read 0x%016llx\n", tmp);
for (i = 0; i < cmd->read_len; i++)
cmd->read_data[i] = tmp >> i;
}
xfer_err:
mutex_unlock(&data->lock);
return retval;
}
/* -- Algorithm functions -- */
/*
* Sends an i2c command out on the adapter
*/
static int pmcmsptwi_master_xfer(struct i2c_adapter *adap,
struct i2c_msg *msg, int num)
{
struct pmcmsptwi_data *data = i2c_get_adapdata(adap);
struct pmcmsptwi_cmd cmd;
struct pmcmsptwi_cfg oldcfg, newcfg;
int ret;
if (num > 2) {
dev_dbg(&adap->dev, "%d messages unsupported\n", num);
return -EINVAL;
} else if (num == 2) {
/* Check for a dual write-then-read command */
struct i2c_msg *nextmsg = msg + 1;
if (!(msg->flags & I2C_M_RD) &&
(nextmsg->flags & I2C_M_RD) &&
msg->addr == nextmsg->addr) {
cmd.type = MSP_TWI_CMD_WRITE_READ;
cmd.write_len = msg->len;
cmd.write_data = msg->buf;
cmd.read_len = nextmsg->len;
cmd.read_data = nextmsg->buf;
} else {
dev_dbg(&adap->dev,
"Non write-read dual messages unsupported\n");
return -EINVAL;
}
} else if (msg->flags & I2C_M_RD) {
cmd.type = MSP_TWI_CMD_READ;
cmd.read_len = msg->len;
cmd.read_data = msg->buf;
cmd.write_len = 0;
cmd.write_data = NULL;
} else {
cmd.type = MSP_TWI_CMD_WRITE;
cmd.read_len = 0;
cmd.read_data = NULL;
cmd.write_len = msg->len;
cmd.write_data = msg->buf;
}
if (msg->len == 0) {
dev_err(&adap->dev, "Zero-byte messages unsupported\n");
return -EINVAL;
}
cmd.addr = msg->addr;
if (msg->flags & I2C_M_TEN) {
pmcmsptwi_get_twi_config(&newcfg, data);
memcpy(&oldcfg, &newcfg, sizeof(oldcfg));
/* Set the special 10-bit address flag */
newcfg.add10 = 1;
pmcmsptwi_set_twi_config(&newcfg, data);
}
/* Execute the command */
ret = pmcmsptwi_xfer_cmd(&cmd, data);
if (msg->flags & I2C_M_TEN)
pmcmsptwi_set_twi_config(&oldcfg, data);
dev_dbg(&adap->dev, "I2C %s of %d bytes %s\n",
(msg->flags & I2C_M_RD) ? "read" : "write", msg->len,
(ret == MSP_TWI_XFER_OK) ? "succeeded" : "failed");
if (ret != MSP_TWI_XFER_OK) {
/*
* TODO: We could potentially loop and retry in the case
* of MSP_TWI_XFER_TIMEOUT.
*/
return -1;
}
return 0;
}
static u32 pmcmsptwi_i2c_func(struct i2c_adapter *adapter)
{
return I2C_FUNC_I2C | I2C_FUNC_10BIT_ADDR |
I2C_FUNC_SMBUS_BYTE | I2C_FUNC_SMBUS_BYTE_DATA |
I2C_FUNC_SMBUS_WORD_DATA | I2C_FUNC_SMBUS_PROC_CALL;
}
/* -- Initialization -- */
static struct i2c_algorithm pmcmsptwi_algo = {
.master_xfer = pmcmsptwi_master_xfer,
.functionality = pmcmsptwi_i2c_func,
};
static struct i2c_adapter pmcmsptwi_adapter = {
.owner = THIS_MODULE,
.class = I2C_CLASS_HWMON | I2C_CLASS_SPD,
.algo = &pmcmsptwi_algo,
.name = DRV_NAME,
};
static struct platform_driver pmcmsptwi_driver = {
.probe = pmcmsptwi_probe,
.remove = pmcmsptwi_remove,
.driver = {
.name = DRV_NAME,
.owner = THIS_MODULE,
},
};
module_platform_driver(pmcmsptwi_driver);
MODULE_DESCRIPTION("PMC MSP TWI/SMBus/I2C driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:" DRV_NAME);
| gpl-2.0 |
lewonchik/q510_qumo_kernel | drivers/xen/mcelog.c | 2371 | 10397 | /******************************************************************************
* mcelog.c
* Driver for receiving and transferring machine check error infomation
*
* Copyright (c) 2012 Intel Corporation
* Author: Liu, Jinsong <jinsong.liu@intel.com>
* Author: Jiang, Yunhong <yunhong.jiang@intel.com>
* Author: Ke, Liping <liping.ke@intel.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation; or, when distributed
* separately from the Linux kernel or incorporated into other
* software packages, subject to the following license:
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this source file (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <linux/init.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/fs.h>
#include <linux/device.h>
#include <linux/miscdevice.h>
#include <linux/uaccess.h>
#include <linux/capability.h>
#include <linux/poll.h>
#include <linux/sched.h>
#include <xen/interface/xen.h>
#include <xen/events.h>
#include <xen/interface/vcpu.h>
#include <xen/xen.h>
#include <asm/xen/hypercall.h>
#include <asm/xen/hypervisor.h>
#define XEN_MCELOG "xen_mcelog: "
static struct mc_info g_mi;
static struct mcinfo_logical_cpu *g_physinfo;
static uint32_t ncpus;
static DEFINE_MUTEX(mcelog_lock);
static struct xen_mce_log xen_mcelog = {
.signature = XEN_MCE_LOG_SIGNATURE,
.len = XEN_MCE_LOG_LEN,
.recordlen = sizeof(struct xen_mce),
};
static DEFINE_SPINLOCK(xen_mce_chrdev_state_lock);
static int xen_mce_chrdev_open_count; /* #times opened */
static int xen_mce_chrdev_open_exclu; /* already open exclusive? */
static DECLARE_WAIT_QUEUE_HEAD(xen_mce_chrdev_wait);
static int xen_mce_chrdev_open(struct inode *inode, struct file *file)
{
spin_lock(&xen_mce_chrdev_state_lock);
if (xen_mce_chrdev_open_exclu ||
(xen_mce_chrdev_open_count && (file->f_flags & O_EXCL))) {
spin_unlock(&xen_mce_chrdev_state_lock);
return -EBUSY;
}
if (file->f_flags & O_EXCL)
xen_mce_chrdev_open_exclu = 1;
xen_mce_chrdev_open_count++;
spin_unlock(&xen_mce_chrdev_state_lock);
return nonseekable_open(inode, file);
}
static int xen_mce_chrdev_release(struct inode *inode, struct file *file)
{
spin_lock(&xen_mce_chrdev_state_lock);
xen_mce_chrdev_open_count--;
xen_mce_chrdev_open_exclu = 0;
spin_unlock(&xen_mce_chrdev_state_lock);
return 0;
}
static ssize_t xen_mce_chrdev_read(struct file *filp, char __user *ubuf,
size_t usize, loff_t *off)
{
char __user *buf = ubuf;
unsigned num;
int i, err;
mutex_lock(&mcelog_lock);
num = xen_mcelog.next;
/* Only supports full reads right now */
err = -EINVAL;
if (*off != 0 || usize < XEN_MCE_LOG_LEN*sizeof(struct xen_mce))
goto out;
err = 0;
for (i = 0; i < num; i++) {
struct xen_mce *m = &xen_mcelog.entry[i];
err |= copy_to_user(buf, m, sizeof(*m));
buf += sizeof(*m);
}
memset(xen_mcelog.entry, 0, num * sizeof(struct xen_mce));
xen_mcelog.next = 0;
if (err)
err = -EFAULT;
out:
mutex_unlock(&mcelog_lock);
return err ? err : buf - ubuf;
}
static unsigned int xen_mce_chrdev_poll(struct file *file, poll_table *wait)
{
poll_wait(file, &xen_mce_chrdev_wait, wait);
if (xen_mcelog.next)
return POLLIN | POLLRDNORM;
return 0;
}
static long xen_mce_chrdev_ioctl(struct file *f, unsigned int cmd,
unsigned long arg)
{
int __user *p = (int __user *)arg;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
switch (cmd) {
case MCE_GET_RECORD_LEN:
return put_user(sizeof(struct xen_mce), p);
case MCE_GET_LOG_LEN:
return put_user(XEN_MCE_LOG_LEN, p);
case MCE_GETCLEAR_FLAGS: {
unsigned flags;
do {
flags = xen_mcelog.flags;
} while (cmpxchg(&xen_mcelog.flags, flags, 0) != flags);
return put_user(flags, p);
}
default:
return -ENOTTY;
}
}
static const struct file_operations xen_mce_chrdev_ops = {
.open = xen_mce_chrdev_open,
.release = xen_mce_chrdev_release,
.read = xen_mce_chrdev_read,
.poll = xen_mce_chrdev_poll,
.unlocked_ioctl = xen_mce_chrdev_ioctl,
.llseek = no_llseek,
};
static struct miscdevice xen_mce_chrdev_device = {
MISC_MCELOG_MINOR,
"mcelog",
&xen_mce_chrdev_ops,
};
/*
* Caller should hold the mcelog_lock
*/
static void xen_mce_log(struct xen_mce *mce)
{
unsigned entry;
entry = xen_mcelog.next;
/*
* When the buffer fills up discard new entries.
* Assume that the earlier errors are the more
* interesting ones:
*/
if (entry >= XEN_MCE_LOG_LEN) {
set_bit(XEN_MCE_OVERFLOW,
(unsigned long *)&xen_mcelog.flags);
return;
}
memcpy(xen_mcelog.entry + entry, mce, sizeof(struct xen_mce));
xen_mcelog.next++;
}
static int convert_log(struct mc_info *mi)
{
struct mcinfo_common *mic;
struct mcinfo_global *mc_global;
struct mcinfo_bank *mc_bank;
struct xen_mce m;
uint32_t i;
mic = NULL;
x86_mcinfo_lookup(&mic, mi, MC_TYPE_GLOBAL);
if (unlikely(!mic)) {
pr_warning(XEN_MCELOG "Failed to find global error info\n");
return -ENODEV;
}
memset(&m, 0, sizeof(struct xen_mce));
mc_global = (struct mcinfo_global *)mic;
m.mcgstatus = mc_global->mc_gstatus;
m.apicid = mc_global->mc_apicid;
for (i = 0; i < ncpus; i++)
if (g_physinfo[i].mc_apicid == m.apicid)
break;
if (unlikely(i == ncpus)) {
pr_warning(XEN_MCELOG "Failed to match cpu with apicid %d\n",
m.apicid);
return -ENODEV;
}
m.socketid = g_physinfo[i].mc_chipid;
m.cpu = m.extcpu = g_physinfo[i].mc_cpunr;
m.cpuvendor = (__u8)g_physinfo[i].mc_vendor;
m.mcgcap = g_physinfo[i].mc_msrvalues[__MC_MSR_MCGCAP].value;
mic = NULL;
x86_mcinfo_lookup(&mic, mi, MC_TYPE_BANK);
if (unlikely(!mic)) {
pr_warning(XEN_MCELOG "Fail to find bank error info\n");
return -ENODEV;
}
do {
if ((!mic) || (mic->size == 0) ||
(mic->type != MC_TYPE_GLOBAL &&
mic->type != MC_TYPE_BANK &&
mic->type != MC_TYPE_EXTENDED &&
mic->type != MC_TYPE_RECOVERY))
break;
if (mic->type == MC_TYPE_BANK) {
mc_bank = (struct mcinfo_bank *)mic;
m.misc = mc_bank->mc_misc;
m.status = mc_bank->mc_status;
m.addr = mc_bank->mc_addr;
m.tsc = mc_bank->mc_tsc;
m.bank = mc_bank->mc_bank;
m.finished = 1;
/*log this record*/
xen_mce_log(&m);
}
mic = x86_mcinfo_next(mic);
} while (1);
return 0;
}
static int mc_queue_handle(uint32_t flags)
{
struct xen_mc mc_op;
int ret = 0;
mc_op.cmd = XEN_MC_fetch;
mc_op.interface_version = XEN_MCA_INTERFACE_VERSION;
set_xen_guest_handle(mc_op.u.mc_fetch.data, &g_mi);
do {
mc_op.u.mc_fetch.flags = flags;
ret = HYPERVISOR_mca(&mc_op);
if (ret) {
pr_err(XEN_MCELOG "Failed to fetch %s error log\n",
(flags == XEN_MC_URGENT) ?
"urgnet" : "nonurgent");
break;
}
if (mc_op.u.mc_fetch.flags & XEN_MC_NODATA ||
mc_op.u.mc_fetch.flags & XEN_MC_FETCHFAILED)
break;
else {
ret = convert_log(&g_mi);
if (ret)
pr_warning(XEN_MCELOG
"Failed to convert this error log, "
"continue acking it anyway\n");
mc_op.u.mc_fetch.flags = flags | XEN_MC_ACK;
ret = HYPERVISOR_mca(&mc_op);
if (ret) {
pr_err(XEN_MCELOG
"Failed to ack previous error log\n");
break;
}
}
} while (1);
return ret;
}
/* virq handler for machine check error info*/
static void xen_mce_work_fn(struct work_struct *work)
{
int err;
mutex_lock(&mcelog_lock);
/* urgent mc_info */
err = mc_queue_handle(XEN_MC_URGENT);
if (err)
pr_err(XEN_MCELOG
"Failed to handle urgent mc_info queue, "
"continue handling nonurgent mc_info queue anyway.\n");
/* nonurgent mc_info */
err = mc_queue_handle(XEN_MC_NONURGENT);
if (err)
pr_err(XEN_MCELOG
"Failed to handle nonurgent mc_info queue.\n");
/* wake processes polling /dev/mcelog */
wake_up_interruptible(&xen_mce_chrdev_wait);
mutex_unlock(&mcelog_lock);
}
static DECLARE_WORK(xen_mce_work, xen_mce_work_fn);
static irqreturn_t xen_mce_interrupt(int irq, void *dev_id)
{
schedule_work(&xen_mce_work);
return IRQ_HANDLED;
}
static int bind_virq_for_mce(void)
{
int ret;
struct xen_mc mc_op;
memset(&mc_op, 0, sizeof(struct xen_mc));
/* Fetch physical CPU Numbers */
mc_op.cmd = XEN_MC_physcpuinfo;
mc_op.interface_version = XEN_MCA_INTERFACE_VERSION;
set_xen_guest_handle(mc_op.u.mc_physcpuinfo.info, g_physinfo);
ret = HYPERVISOR_mca(&mc_op);
if (ret) {
pr_err(XEN_MCELOG "Failed to get CPU numbers\n");
return ret;
}
/* Fetch each CPU Physical Info for later reference*/
ncpus = mc_op.u.mc_physcpuinfo.ncpus;
g_physinfo = kcalloc(ncpus, sizeof(struct mcinfo_logical_cpu),
GFP_KERNEL);
if (!g_physinfo)
return -ENOMEM;
set_xen_guest_handle(mc_op.u.mc_physcpuinfo.info, g_physinfo);
ret = HYPERVISOR_mca(&mc_op);
if (ret) {
pr_err(XEN_MCELOG "Failed to get CPU info\n");
kfree(g_physinfo);
return ret;
}
ret = bind_virq_to_irqhandler(VIRQ_MCA, 0,
xen_mce_interrupt, 0, "mce", NULL);
if (ret < 0) {
pr_err(XEN_MCELOG "Failed to bind virq\n");
kfree(g_physinfo);
return ret;
}
return 0;
}
static int __init xen_late_init_mcelog(void)
{
/* Only DOM0 is responsible for MCE logging */
if (xen_initial_domain()) {
/* register character device /dev/mcelog for xen mcelog */
if (misc_register(&xen_mce_chrdev_device))
return -ENODEV;
return bind_virq_for_mce();
}
return -ENODEV;
}
device_initcall(xen_late_init_mcelog);
| gpl-2.0 |
rutvik95/android_kernel_frostbite | drivers/usb/musb/blackfin.c | 2371 | 14826 | /*
* MUSB OTG controller driver for Blackfin Processors
*
* Copyright 2006-2008 Analog Devices Inc.
*
* Enter bugs at http://blackfin.uclinux.org/
*
* Licensed under the GPL-2 or later.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <linux/list.h>
#include <linux/gpio.h>
#include <linux/io.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <asm/cacheflush.h>
#include "musb_core.h"
#include "musbhsdma.h"
#include "blackfin.h"
struct bfin_glue {
struct device *dev;
struct platform_device *musb;
};
#define glue_to_musb(g) platform_get_drvdata(g->musb)
/*
* Load an endpoint's FIFO
*/
void musb_write_fifo(struct musb_hw_ep *hw_ep, u16 len, const u8 *src)
{
struct musb *musb = hw_ep->musb;
void __iomem *fifo = hw_ep->fifo;
void __iomem *epio = hw_ep->regs;
u8 epnum = hw_ep->epnum;
prefetch((u8 *)src);
musb_writew(epio, MUSB_TXCOUNT, len);
dev_dbg(musb->controller, "TX ep%d fifo %p count %d buf %p, epio %p\n",
hw_ep->epnum, fifo, len, src, epio);
dump_fifo_data(src, len);
if (!ANOMALY_05000380 && epnum != 0) {
u16 dma_reg;
flush_dcache_range((unsigned long)src,
(unsigned long)(src + len));
/* Setup DMA address register */
dma_reg = (u32)src;
bfin_write16(USB_DMA_REG(epnum, USB_DMAx_ADDR_LOW), dma_reg);
SSYNC();
dma_reg = (u32)src >> 16;
bfin_write16(USB_DMA_REG(epnum, USB_DMAx_ADDR_HIGH), dma_reg);
SSYNC();
/* Setup DMA count register */
bfin_write16(USB_DMA_REG(epnum, USB_DMAx_COUNT_LOW), len);
bfin_write16(USB_DMA_REG(epnum, USB_DMAx_COUNT_HIGH), 0);
SSYNC();
/* Enable the DMA */
dma_reg = (epnum << 4) | DMA_ENA | INT_ENA | DIRECTION;
bfin_write16(USB_DMA_REG(epnum, USB_DMAx_CTRL), dma_reg);
SSYNC();
/* Wait for compelete */
while (!(bfin_read_USB_DMA_INTERRUPT() & (1 << epnum)))
cpu_relax();
/* acknowledge dma interrupt */
bfin_write_USB_DMA_INTERRUPT(1 << epnum);
SSYNC();
/* Reset DMA */
bfin_write16(USB_DMA_REG(epnum, USB_DMAx_CTRL), 0);
SSYNC();
} else {
SSYNC();
if (unlikely((unsigned long)src & 0x01))
outsw_8((unsigned long)fifo, src, (len + 1) >> 1);
else
outsw((unsigned long)fifo, src, (len + 1) >> 1);
}
}
/*
* Unload an endpoint's FIFO
*/
void musb_read_fifo(struct musb_hw_ep *hw_ep, u16 len, u8 *dst)
{
struct musb *musb = hw_ep->musb;
void __iomem *fifo = hw_ep->fifo;
u8 epnum = hw_ep->epnum;
if (ANOMALY_05000467 && epnum != 0) {
u16 dma_reg;
invalidate_dcache_range((unsigned long)dst,
(unsigned long)(dst + len));
/* Setup DMA address register */
dma_reg = (u32)dst;
bfin_write16(USB_DMA_REG(epnum, USB_DMAx_ADDR_LOW), dma_reg);
SSYNC();
dma_reg = (u32)dst >> 16;
bfin_write16(USB_DMA_REG(epnum, USB_DMAx_ADDR_HIGH), dma_reg);
SSYNC();
/* Setup DMA count register */
bfin_write16(USB_DMA_REG(epnum, USB_DMAx_COUNT_LOW), len);
bfin_write16(USB_DMA_REG(epnum, USB_DMAx_COUNT_HIGH), 0);
SSYNC();
/* Enable the DMA */
dma_reg = (epnum << 4) | DMA_ENA | INT_ENA;
bfin_write16(USB_DMA_REG(epnum, USB_DMAx_CTRL), dma_reg);
SSYNC();
/* Wait for compelete */
while (!(bfin_read_USB_DMA_INTERRUPT() & (1 << epnum)))
cpu_relax();
/* acknowledge dma interrupt */
bfin_write_USB_DMA_INTERRUPT(1 << epnum);
SSYNC();
/* Reset DMA */
bfin_write16(USB_DMA_REG(epnum, USB_DMAx_CTRL), 0);
SSYNC();
} else {
SSYNC();
/* Read the last byte of packet with odd size from address fifo + 4
* to trigger 1 byte access to EP0 FIFO.
*/
if (len == 1)
*dst = (u8)inw((unsigned long)fifo + 4);
else {
if (unlikely((unsigned long)dst & 0x01))
insw_8((unsigned long)fifo, dst, len >> 1);
else
insw((unsigned long)fifo, dst, len >> 1);
if (len & 0x01)
*(dst + len - 1) = (u8)inw((unsigned long)fifo + 4);
}
}
dev_dbg(musb->controller, "%cX ep%d fifo %p count %d buf %p\n",
'R', hw_ep->epnum, fifo, len, dst);
dump_fifo_data(dst, len);
}
static irqreturn_t blackfin_interrupt(int irq, void *__hci)
{
unsigned long flags;
irqreturn_t retval = IRQ_NONE;
struct musb *musb = __hci;
spin_lock_irqsave(&musb->lock, flags);
musb->int_usb = musb_readb(musb->mregs, MUSB_INTRUSB);
musb->int_tx = musb_readw(musb->mregs, MUSB_INTRTX);
musb->int_rx = musb_readw(musb->mregs, MUSB_INTRRX);
if (musb->int_usb || musb->int_tx || musb->int_rx) {
musb_writeb(musb->mregs, MUSB_INTRUSB, musb->int_usb);
musb_writew(musb->mregs, MUSB_INTRTX, musb->int_tx);
musb_writew(musb->mregs, MUSB_INTRRX, musb->int_rx);
retval = musb_interrupt(musb);
}
/* Start sampling ID pin, when plug is removed from MUSB */
if ((is_otg_enabled(musb) && (musb->xceiv->state == OTG_STATE_B_IDLE
|| musb->xceiv->state == OTG_STATE_A_WAIT_BCON)) ||
(musb->int_usb & MUSB_INTR_DISCONNECT && is_host_active(musb))) {
mod_timer(&musb_conn_timer, jiffies + TIMER_DELAY);
musb->a_wait_bcon = TIMER_DELAY;
}
spin_unlock_irqrestore(&musb->lock, flags);
return retval;
}
static void musb_conn_timer_handler(unsigned long _musb)
{
struct musb *musb = (void *)_musb;
unsigned long flags;
u16 val;
static u8 toggle;
spin_lock_irqsave(&musb->lock, flags);
switch (musb->xceiv->state) {
case OTG_STATE_A_IDLE:
case OTG_STATE_A_WAIT_BCON:
/* Start a new session */
val = musb_readw(musb->mregs, MUSB_DEVCTL);
val &= ~MUSB_DEVCTL_SESSION;
musb_writew(musb->mregs, MUSB_DEVCTL, val);
val |= MUSB_DEVCTL_SESSION;
musb_writew(musb->mregs, MUSB_DEVCTL, val);
/* Check if musb is host or peripheral. */
val = musb_readw(musb->mregs, MUSB_DEVCTL);
if (!(val & MUSB_DEVCTL_BDEVICE)) {
gpio_set_value(musb->config->gpio_vrsel, 1);
musb->xceiv->state = OTG_STATE_A_WAIT_BCON;
} else {
gpio_set_value(musb->config->gpio_vrsel, 0);
/* Ignore VBUSERROR and SUSPEND IRQ */
val = musb_readb(musb->mregs, MUSB_INTRUSBE);
val &= ~MUSB_INTR_VBUSERROR;
musb_writeb(musb->mregs, MUSB_INTRUSBE, val);
val = MUSB_INTR_SUSPEND | MUSB_INTR_VBUSERROR;
musb_writeb(musb->mregs, MUSB_INTRUSB, val);
if (is_otg_enabled(musb))
musb->xceiv->state = OTG_STATE_B_IDLE;
else
musb_writeb(musb->mregs, MUSB_POWER, MUSB_POWER_HSENAB);
}
mod_timer(&musb_conn_timer, jiffies + TIMER_DELAY);
break;
case OTG_STATE_B_IDLE:
if (!is_peripheral_enabled(musb))
break;
/* Start a new session. It seems that MUSB needs taking
* some time to recognize the type of the plug inserted?
*/
val = musb_readw(musb->mregs, MUSB_DEVCTL);
val |= MUSB_DEVCTL_SESSION;
musb_writew(musb->mregs, MUSB_DEVCTL, val);
val = musb_readw(musb->mregs, MUSB_DEVCTL);
if (!(val & MUSB_DEVCTL_BDEVICE)) {
gpio_set_value(musb->config->gpio_vrsel, 1);
musb->xceiv->state = OTG_STATE_A_WAIT_BCON;
} else {
gpio_set_value(musb->config->gpio_vrsel, 0);
/* Ignore VBUSERROR and SUSPEND IRQ */
val = musb_readb(musb->mregs, MUSB_INTRUSBE);
val &= ~MUSB_INTR_VBUSERROR;
musb_writeb(musb->mregs, MUSB_INTRUSBE, val);
val = MUSB_INTR_SUSPEND | MUSB_INTR_VBUSERROR;
musb_writeb(musb->mregs, MUSB_INTRUSB, val);
/* Toggle the Soft Conn bit, so that we can response to
* the inserting of either A-plug or B-plug.
*/
if (toggle) {
val = musb_readb(musb->mregs, MUSB_POWER);
val &= ~MUSB_POWER_SOFTCONN;
musb_writeb(musb->mregs, MUSB_POWER, val);
toggle = 0;
} else {
val = musb_readb(musb->mregs, MUSB_POWER);
val |= MUSB_POWER_SOFTCONN;
musb_writeb(musb->mregs, MUSB_POWER, val);
toggle = 1;
}
/* The delay time is set to 1/4 second by default,
* shortening it, if accelerating A-plug detection
* is needed in OTG mode.
*/
mod_timer(&musb_conn_timer, jiffies + TIMER_DELAY / 4);
}
break;
default:
dev_dbg(musb->controller, "%s state not handled\n",
otg_state_string(musb->xceiv->state));
break;
}
spin_unlock_irqrestore(&musb->lock, flags);
dev_dbg(musb->controller, "state is %s\n",
otg_state_string(musb->xceiv->state));
}
static void bfin_musb_enable(struct musb *musb)
{
if (!is_otg_enabled(musb) && is_host_enabled(musb)) {
mod_timer(&musb_conn_timer, jiffies + TIMER_DELAY);
musb->a_wait_bcon = TIMER_DELAY;
}
}
static void bfin_musb_disable(struct musb *musb)
{
}
static void bfin_musb_set_vbus(struct musb *musb, int is_on)
{
int value = musb->config->gpio_vrsel_active;
if (!is_on)
value = !value;
gpio_set_value(musb->config->gpio_vrsel, value);
dev_dbg(musb->controller, "VBUS %s, devctl %02x "
/* otg %3x conf %08x prcm %08x */ "\n",
otg_state_string(musb->xceiv->state),
musb_readb(musb->mregs, MUSB_DEVCTL));
}
static int bfin_musb_set_power(struct otg_transceiver *x, unsigned mA)
{
return 0;
}
static void bfin_musb_try_idle(struct musb *musb, unsigned long timeout)
{
if (!is_otg_enabled(musb) && is_host_enabled(musb))
mod_timer(&musb_conn_timer, jiffies + TIMER_DELAY);
}
static int bfin_musb_vbus_status(struct musb *musb)
{
return 0;
}
static int bfin_musb_set_mode(struct musb *musb, u8 musb_mode)
{
return -EIO;
}
static int bfin_musb_adjust_channel_params(struct dma_channel *channel,
u16 packet_sz, u8 *mode,
dma_addr_t *dma_addr, u32 *len)
{
struct musb_dma_channel *musb_channel = channel->private_data;
/*
* Anomaly 05000450 might cause data corruption when using DMA
* MODE 1 transmits with short packet. So to work around this,
* we truncate all MODE 1 transfers down to a multiple of the
* max packet size, and then do the last short packet transfer
* (if there is any) using MODE 0.
*/
if (ANOMALY_05000450) {
if (musb_channel->transmit && *mode == 1)
*len = *len - (*len % packet_sz);
}
return 0;
}
static void bfin_musb_reg_init(struct musb *musb)
{
if (ANOMALY_05000346) {
bfin_write_USB_APHY_CALIB(ANOMALY_05000346_value);
SSYNC();
}
if (ANOMALY_05000347) {
bfin_write_USB_APHY_CNTRL(0x0);
SSYNC();
}
/* Configure PLL oscillator register */
bfin_write_USB_PLLOSC_CTRL(0x3080 |
((480/musb->config->clkin) << 1));
SSYNC();
bfin_write_USB_SRP_CLKDIV((get_sclk()/1000) / 32 - 1);
SSYNC();
bfin_write_USB_EP_NI0_RXMAXP(64);
SSYNC();
bfin_write_USB_EP_NI0_TXMAXP(64);
SSYNC();
/* Route INTRUSB/INTR_RX/INTR_TX to USB_INT0*/
bfin_write_USB_GLOBINTR(0x7);
SSYNC();
bfin_write_USB_GLOBAL_CTL(GLOBAL_ENA | EP1_TX_ENA | EP2_TX_ENA |
EP3_TX_ENA | EP4_TX_ENA | EP5_TX_ENA |
EP6_TX_ENA | EP7_TX_ENA | EP1_RX_ENA |
EP2_RX_ENA | EP3_RX_ENA | EP4_RX_ENA |
EP5_RX_ENA | EP6_RX_ENA | EP7_RX_ENA);
SSYNC();
}
static int bfin_musb_init(struct musb *musb)
{
/*
* Rev 1.0 BF549 EZ-KITs require PE7 to be high for both DEVICE
* and OTG HOST modes, while rev 1.1 and greater require PE7 to
* be low for DEVICE mode and high for HOST mode. We set it high
* here because we are in host mode
*/
if (gpio_request(musb->config->gpio_vrsel, "USB_VRSEL")) {
printk(KERN_ERR "Failed ro request USB_VRSEL GPIO_%d\n",
musb->config->gpio_vrsel);
return -ENODEV;
}
gpio_direction_output(musb->config->gpio_vrsel, 0);
usb_nop_xceiv_register();
musb->xceiv = otg_get_transceiver();
if (!musb->xceiv) {
gpio_free(musb->config->gpio_vrsel);
return -ENODEV;
}
bfin_musb_reg_init(musb);
if (is_host_enabled(musb)) {
setup_timer(&musb_conn_timer,
musb_conn_timer_handler, (unsigned long) musb);
}
if (is_peripheral_enabled(musb))
musb->xceiv->set_power = bfin_musb_set_power;
musb->isr = blackfin_interrupt;
musb->double_buffer_not_ok = true;
return 0;
}
static int bfin_musb_exit(struct musb *musb)
{
gpio_free(musb->config->gpio_vrsel);
otg_put_transceiver(musb->xceiv);
usb_nop_xceiv_unregister();
return 0;
}
static const struct musb_platform_ops bfin_ops = {
.init = bfin_musb_init,
.exit = bfin_musb_exit,
.enable = bfin_musb_enable,
.disable = bfin_musb_disable,
.set_mode = bfin_musb_set_mode,
.try_idle = bfin_musb_try_idle,
.vbus_status = bfin_musb_vbus_status,
.set_vbus = bfin_musb_set_vbus,
.adjust_channel_params = bfin_musb_adjust_channel_params,
};
static u64 bfin_dmamask = DMA_BIT_MASK(32);
static int __init bfin_probe(struct platform_device *pdev)
{
struct musb_hdrc_platform_data *pdata = pdev->dev.platform_data;
struct platform_device *musb;
struct bfin_glue *glue;
int ret = -ENOMEM;
glue = kzalloc(sizeof(*glue), GFP_KERNEL);
if (!glue) {
dev_err(&pdev->dev, "failed to allocate glue context\n");
goto err0;
}
musb = platform_device_alloc("musb-hdrc", -1);
if (!musb) {
dev_err(&pdev->dev, "failed to allocate musb device\n");
goto err1;
}
musb->dev.parent = &pdev->dev;
musb->dev.dma_mask = &bfin_dmamask;
musb->dev.coherent_dma_mask = bfin_dmamask;
glue->dev = &pdev->dev;
glue->musb = musb;
pdata->platform_ops = &bfin_ops;
platform_set_drvdata(pdev, glue);
ret = platform_device_add_resources(musb, pdev->resource,
pdev->num_resources);
if (ret) {
dev_err(&pdev->dev, "failed to add resources\n");
goto err2;
}
ret = platform_device_add_data(musb, pdata, sizeof(*pdata));
if (ret) {
dev_err(&pdev->dev, "failed to add platform_data\n");
goto err2;
}
ret = platform_device_add(musb);
if (ret) {
dev_err(&pdev->dev, "failed to register musb device\n");
goto err2;
}
return 0;
err2:
platform_device_put(musb);
err1:
kfree(glue);
err0:
return ret;
}
static int __exit bfin_remove(struct platform_device *pdev)
{
struct bfin_glue *glue = platform_get_drvdata(pdev);
platform_device_del(glue->musb);
platform_device_put(glue->musb);
kfree(glue);
return 0;
}
#ifdef CONFIG_PM
static int bfin_suspend(struct device *dev)
{
struct bfin_glue *glue = dev_get_drvdata(dev);
struct musb *musb = glue_to_musb(glue);
if (is_host_active(musb))
/*
* During hibernate gpio_vrsel will change from high to low
* low which will generate wakeup event resume the system
* immediately. Set it to 0 before hibernate to avoid this
* wakeup event.
*/
gpio_set_value(musb->config->gpio_vrsel, 0);
return 0;
}
static int bfin_resume(struct device *dev)
{
struct bfin_glue *glue = dev_get_drvdata(dev);
struct musb *musb = glue_to_musb(glue);
bfin_musb_reg_init(musb);
return 0;
}
static struct dev_pm_ops bfin_pm_ops = {
.suspend = bfin_suspend,
.resume = bfin_resume,
};
#define DEV_PM_OPS &bfin_pm_ops
#else
#define DEV_PM_OPS NULL
#endif
static struct platform_driver bfin_driver = {
.remove = __exit_p(bfin_remove),
.driver = {
.name = "musb-blackfin",
.pm = DEV_PM_OPS,
},
};
MODULE_DESCRIPTION("Blackfin MUSB Glue Layer");
MODULE_AUTHOR("Bryan Wy <cooloney@kernel.org>");
MODULE_LICENSE("GPL v2");
static int __init bfin_init(void)
{
return platform_driver_probe(&bfin_driver, bfin_probe);
}
subsys_initcall(bfin_init);
static void __exit bfin_exit(void)
{
platform_driver_unregister(&bfin_driver);
}
module_exit(bfin_exit);
| gpl-2.0 |
OpenDesireProject/android_kernel_htc_msm7x30 | net/batman-adv/originator.c | 2371 | 16698 | /*
* Copyright (C) 2009-2011 B.A.T.M.A.N. contributors:
*
* Marek Lindner, Simon Wunderlich
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of version 2 of the GNU General Public
* License as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA
*
*/
#include "main.h"
#include "originator.h"
#include "hash.h"
#include "translation-table.h"
#include "routing.h"
#include "gateway_client.h"
#include "hard-interface.h"
#include "unicast.h"
#include "soft-interface.h"
static void purge_orig(struct work_struct *work);
static void start_purge_timer(struct bat_priv *bat_priv)
{
INIT_DELAYED_WORK(&bat_priv->orig_work, purge_orig);
queue_delayed_work(bat_event_workqueue, &bat_priv->orig_work, 1 * HZ);
}
int originator_init(struct bat_priv *bat_priv)
{
if (bat_priv->orig_hash)
return 1;
bat_priv->orig_hash = hash_new(1024);
if (!bat_priv->orig_hash)
goto err;
start_purge_timer(bat_priv);
return 1;
err:
return 0;
}
void neigh_node_free_ref(struct neigh_node *neigh_node)
{
if (atomic_dec_and_test(&neigh_node->refcount))
kfree_rcu(neigh_node, rcu);
}
/* increases the refcounter of a found router */
struct neigh_node *orig_node_get_router(struct orig_node *orig_node)
{
struct neigh_node *router;
rcu_read_lock();
router = rcu_dereference(orig_node->router);
if (router && !atomic_inc_not_zero(&router->refcount))
router = NULL;
rcu_read_unlock();
return router;
}
struct neigh_node *create_neighbor(struct orig_node *orig_node,
struct orig_node *orig_neigh_node,
uint8_t *neigh,
struct hard_iface *if_incoming)
{
struct bat_priv *bat_priv = netdev_priv(if_incoming->soft_iface);
struct neigh_node *neigh_node;
bat_dbg(DBG_BATMAN, bat_priv,
"Creating new last-hop neighbor of originator\n");
neigh_node = kzalloc(sizeof(struct neigh_node), GFP_ATOMIC);
if (!neigh_node)
return NULL;
INIT_HLIST_NODE(&neigh_node->list);
INIT_LIST_HEAD(&neigh_node->bonding_list);
spin_lock_init(&neigh_node->tq_lock);
memcpy(neigh_node->addr, neigh, ETH_ALEN);
neigh_node->orig_node = orig_neigh_node;
neigh_node->if_incoming = if_incoming;
/* extra reference for return */
atomic_set(&neigh_node->refcount, 2);
spin_lock_bh(&orig_node->neigh_list_lock);
hlist_add_head_rcu(&neigh_node->list, &orig_node->neigh_list);
spin_unlock_bh(&orig_node->neigh_list_lock);
return neigh_node;
}
static void orig_node_free_rcu(struct rcu_head *rcu)
{
struct hlist_node *node, *node_tmp;
struct neigh_node *neigh_node, *tmp_neigh_node;
struct orig_node *orig_node;
orig_node = container_of(rcu, struct orig_node, rcu);
spin_lock_bh(&orig_node->neigh_list_lock);
/* for all bonding members ... */
list_for_each_entry_safe(neigh_node, tmp_neigh_node,
&orig_node->bond_list, bonding_list) {
list_del_rcu(&neigh_node->bonding_list);
neigh_node_free_ref(neigh_node);
}
/* for all neighbors towards this originator ... */
hlist_for_each_entry_safe(neigh_node, node, node_tmp,
&orig_node->neigh_list, list) {
hlist_del_rcu(&neigh_node->list);
neigh_node_free_ref(neigh_node);
}
spin_unlock_bh(&orig_node->neigh_list_lock);
frag_list_free(&orig_node->frag_list);
tt_global_del_orig(orig_node->bat_priv, orig_node,
"originator timed out");
kfree(orig_node->bcast_own);
kfree(orig_node->bcast_own_sum);
kfree(orig_node);
}
void orig_node_free_ref(struct orig_node *orig_node)
{
if (atomic_dec_and_test(&orig_node->refcount))
call_rcu(&orig_node->rcu, orig_node_free_rcu);
}
void originator_free(struct bat_priv *bat_priv)
{
struct hashtable_t *hash = bat_priv->orig_hash;
struct hlist_node *node, *node_tmp;
struct hlist_head *head;
spinlock_t *list_lock; /* spinlock to protect write access */
struct orig_node *orig_node;
int i;
if (!hash)
return;
cancel_delayed_work_sync(&bat_priv->orig_work);
bat_priv->orig_hash = NULL;
for (i = 0; i < hash->size; i++) {
head = &hash->table[i];
list_lock = &hash->list_locks[i];
spin_lock_bh(list_lock);
hlist_for_each_entry_safe(orig_node, node, node_tmp,
head, hash_entry) {
hlist_del_rcu(node);
orig_node_free_ref(orig_node);
}
spin_unlock_bh(list_lock);
}
hash_destroy(hash);
}
/* this function finds or creates an originator entry for the given
* address if it does not exits */
struct orig_node *get_orig_node(struct bat_priv *bat_priv, uint8_t *addr)
{
struct orig_node *orig_node;
int size;
int hash_added;
orig_node = orig_hash_find(bat_priv, addr);
if (orig_node)
return orig_node;
bat_dbg(DBG_BATMAN, bat_priv,
"Creating new originator: %pM\n", addr);
orig_node = kzalloc(sizeof(struct orig_node), GFP_ATOMIC);
if (!orig_node)
return NULL;
INIT_HLIST_HEAD(&orig_node->neigh_list);
INIT_LIST_HEAD(&orig_node->bond_list);
spin_lock_init(&orig_node->ogm_cnt_lock);
spin_lock_init(&orig_node->bcast_seqno_lock);
spin_lock_init(&orig_node->neigh_list_lock);
/* extra reference for return */
atomic_set(&orig_node->refcount, 2);
orig_node->bat_priv = bat_priv;
memcpy(orig_node->orig, addr, ETH_ALEN);
orig_node->router = NULL;
orig_node->tt_buff = NULL;
orig_node->bcast_seqno_reset = jiffies - 1
- msecs_to_jiffies(RESET_PROTECTION_MS);
orig_node->batman_seqno_reset = jiffies - 1
- msecs_to_jiffies(RESET_PROTECTION_MS);
atomic_set(&orig_node->bond_candidates, 0);
size = bat_priv->num_ifaces * sizeof(unsigned long) * NUM_WORDS;
orig_node->bcast_own = kzalloc(size, GFP_ATOMIC);
if (!orig_node->bcast_own)
goto free_orig_node;
size = bat_priv->num_ifaces * sizeof(uint8_t);
orig_node->bcast_own_sum = kzalloc(size, GFP_ATOMIC);
INIT_LIST_HEAD(&orig_node->frag_list);
orig_node->last_frag_packet = 0;
if (!orig_node->bcast_own_sum)
goto free_bcast_own;
hash_added = hash_add(bat_priv->orig_hash, compare_orig,
choose_orig, orig_node, &orig_node->hash_entry);
if (hash_added < 0)
goto free_bcast_own_sum;
return orig_node;
free_bcast_own_sum:
kfree(orig_node->bcast_own_sum);
free_bcast_own:
kfree(orig_node->bcast_own);
free_orig_node:
kfree(orig_node);
return NULL;
}
static bool purge_orig_neighbors(struct bat_priv *bat_priv,
struct orig_node *orig_node,
struct neigh_node **best_neigh_node)
{
struct hlist_node *node, *node_tmp;
struct neigh_node *neigh_node;
bool neigh_purged = false;
*best_neigh_node = NULL;
spin_lock_bh(&orig_node->neigh_list_lock);
/* for all neighbors towards this originator ... */
hlist_for_each_entry_safe(neigh_node, node, node_tmp,
&orig_node->neigh_list, list) {
if ((time_after(jiffies,
neigh_node->last_valid + PURGE_TIMEOUT * HZ)) ||
(neigh_node->if_incoming->if_status == IF_INACTIVE) ||
(neigh_node->if_incoming->if_status == IF_NOT_IN_USE) ||
(neigh_node->if_incoming->if_status == IF_TO_BE_REMOVED)) {
if ((neigh_node->if_incoming->if_status ==
IF_INACTIVE) ||
(neigh_node->if_incoming->if_status ==
IF_NOT_IN_USE) ||
(neigh_node->if_incoming->if_status ==
IF_TO_BE_REMOVED))
bat_dbg(DBG_BATMAN, bat_priv,
"neighbor purge: originator %pM, "
"neighbor: %pM, iface: %s\n",
orig_node->orig, neigh_node->addr,
neigh_node->if_incoming->net_dev->name);
else
bat_dbg(DBG_BATMAN, bat_priv,
"neighbor timeout: originator %pM, "
"neighbor: %pM, last_valid: %lu\n",
orig_node->orig, neigh_node->addr,
(neigh_node->last_valid / HZ));
neigh_purged = true;
hlist_del_rcu(&neigh_node->list);
bonding_candidate_del(orig_node, neigh_node);
neigh_node_free_ref(neigh_node);
} else {
if ((!*best_neigh_node) ||
(neigh_node->tq_avg > (*best_neigh_node)->tq_avg))
*best_neigh_node = neigh_node;
}
}
spin_unlock_bh(&orig_node->neigh_list_lock);
return neigh_purged;
}
static bool purge_orig_node(struct bat_priv *bat_priv,
struct orig_node *orig_node)
{
struct neigh_node *best_neigh_node;
if (time_after(jiffies,
orig_node->last_valid + 2 * PURGE_TIMEOUT * HZ)) {
bat_dbg(DBG_BATMAN, bat_priv,
"Originator timeout: originator %pM, last_valid %lu\n",
orig_node->orig, (orig_node->last_valid / HZ));
return true;
} else {
if (purge_orig_neighbors(bat_priv, orig_node,
&best_neigh_node)) {
update_routes(bat_priv, orig_node,
best_neigh_node,
orig_node->tt_buff,
orig_node->tt_buff_len);
}
}
return false;
}
static void _purge_orig(struct bat_priv *bat_priv)
{
struct hashtable_t *hash = bat_priv->orig_hash;
struct hlist_node *node, *node_tmp;
struct hlist_head *head;
spinlock_t *list_lock; /* spinlock to protect write access */
struct orig_node *orig_node;
int i;
if (!hash)
return;
/* for all origins... */
for (i = 0; i < hash->size; i++) {
head = &hash->table[i];
list_lock = &hash->list_locks[i];
spin_lock_bh(list_lock);
hlist_for_each_entry_safe(orig_node, node, node_tmp,
head, hash_entry) {
if (purge_orig_node(bat_priv, orig_node)) {
if (orig_node->gw_flags)
gw_node_delete(bat_priv, orig_node);
hlist_del_rcu(node);
orig_node_free_ref(orig_node);
continue;
}
if (time_after(jiffies, orig_node->last_frag_packet +
msecs_to_jiffies(FRAG_TIMEOUT)))
frag_list_free(&orig_node->frag_list);
}
spin_unlock_bh(list_lock);
}
gw_node_purge(bat_priv);
gw_election(bat_priv);
softif_neigh_purge(bat_priv);
}
static void purge_orig(struct work_struct *work)
{
struct delayed_work *delayed_work =
container_of(work, struct delayed_work, work);
struct bat_priv *bat_priv =
container_of(delayed_work, struct bat_priv, orig_work);
_purge_orig(bat_priv);
start_purge_timer(bat_priv);
}
void purge_orig_ref(struct bat_priv *bat_priv)
{
_purge_orig(bat_priv);
}
int orig_seq_print_text(struct seq_file *seq, void *offset)
{
struct net_device *net_dev = (struct net_device *)seq->private;
struct bat_priv *bat_priv = netdev_priv(net_dev);
struct hashtable_t *hash = bat_priv->orig_hash;
struct hlist_node *node, *node_tmp;
struct hlist_head *head;
struct hard_iface *primary_if;
struct orig_node *orig_node;
struct neigh_node *neigh_node, *neigh_node_tmp;
int batman_count = 0;
int last_seen_secs;
int last_seen_msecs;
int i, ret = 0;
primary_if = primary_if_get_selected(bat_priv);
if (!primary_if) {
ret = seq_printf(seq, "BATMAN mesh %s disabled - "
"please specify interfaces to enable it\n",
net_dev->name);
goto out;
}
if (primary_if->if_status != IF_ACTIVE) {
ret = seq_printf(seq, "BATMAN mesh %s "
"disabled - primary interface not active\n",
net_dev->name);
goto out;
}
seq_printf(seq, "[B.A.T.M.A.N. adv %s%s, MainIF/MAC: %s/%pM (%s)]\n",
SOURCE_VERSION, REVISION_VERSION_STR,
primary_if->net_dev->name,
primary_if->net_dev->dev_addr, net_dev->name);
seq_printf(seq, " %-15s %s (%s/%i) %17s [%10s]: %20s ...\n",
"Originator", "last-seen", "#", TQ_MAX_VALUE, "Nexthop",
"outgoingIF", "Potential nexthops");
for (i = 0; i < hash->size; i++) {
head = &hash->table[i];
rcu_read_lock();
hlist_for_each_entry_rcu(orig_node, node, head, hash_entry) {
neigh_node = orig_node_get_router(orig_node);
if (!neigh_node)
continue;
if (neigh_node->tq_avg == 0)
goto next;
last_seen_secs = jiffies_to_msecs(jiffies -
orig_node->last_valid) / 1000;
last_seen_msecs = jiffies_to_msecs(jiffies -
orig_node->last_valid) % 1000;
seq_printf(seq, "%pM %4i.%03is (%3i) %pM [%10s]:",
orig_node->orig, last_seen_secs,
last_seen_msecs, neigh_node->tq_avg,
neigh_node->addr,
neigh_node->if_incoming->net_dev->name);
hlist_for_each_entry_rcu(neigh_node_tmp, node_tmp,
&orig_node->neigh_list, list) {
seq_printf(seq, " %pM (%3i)",
neigh_node_tmp->addr,
neigh_node_tmp->tq_avg);
}
seq_printf(seq, "\n");
batman_count++;
next:
neigh_node_free_ref(neigh_node);
}
rcu_read_unlock();
}
if (batman_count == 0)
seq_printf(seq, "No batman nodes in range ...\n");
out:
if (primary_if)
hardif_free_ref(primary_if);
return ret;
}
static int orig_node_add_if(struct orig_node *orig_node, int max_if_num)
{
void *data_ptr;
data_ptr = kmalloc(max_if_num * sizeof(unsigned long) * NUM_WORDS,
GFP_ATOMIC);
if (!data_ptr) {
pr_err("Can't resize orig: out of memory\n");
return -1;
}
memcpy(data_ptr, orig_node->bcast_own,
(max_if_num - 1) * sizeof(unsigned long) * NUM_WORDS);
kfree(orig_node->bcast_own);
orig_node->bcast_own = data_ptr;
data_ptr = kmalloc(max_if_num * sizeof(uint8_t), GFP_ATOMIC);
if (!data_ptr) {
pr_err("Can't resize orig: out of memory\n");
return -1;
}
memcpy(data_ptr, orig_node->bcast_own_sum,
(max_if_num - 1) * sizeof(uint8_t));
kfree(orig_node->bcast_own_sum);
orig_node->bcast_own_sum = data_ptr;
return 0;
}
int orig_hash_add_if(struct hard_iface *hard_iface, int max_if_num)
{
struct bat_priv *bat_priv = netdev_priv(hard_iface->soft_iface);
struct hashtable_t *hash = bat_priv->orig_hash;
struct hlist_node *node;
struct hlist_head *head;
struct orig_node *orig_node;
int i, ret;
/* resize all orig nodes because orig_node->bcast_own(_sum) depend on
* if_num */
for (i = 0; i < hash->size; i++) {
head = &hash->table[i];
rcu_read_lock();
hlist_for_each_entry_rcu(orig_node, node, head, hash_entry) {
spin_lock_bh(&orig_node->ogm_cnt_lock);
ret = orig_node_add_if(orig_node, max_if_num);
spin_unlock_bh(&orig_node->ogm_cnt_lock);
if (ret == -1)
goto err;
}
rcu_read_unlock();
}
return 0;
err:
rcu_read_unlock();
return -ENOMEM;
}
static int orig_node_del_if(struct orig_node *orig_node,
int max_if_num, int del_if_num)
{
void *data_ptr = NULL;
int chunk_size;
/* last interface was removed */
if (max_if_num == 0)
goto free_bcast_own;
chunk_size = sizeof(unsigned long) * NUM_WORDS;
data_ptr = kmalloc(max_if_num * chunk_size, GFP_ATOMIC);
if (!data_ptr) {
pr_err("Can't resize orig: out of memory\n");
return -1;
}
/* copy first part */
memcpy(data_ptr, orig_node->bcast_own, del_if_num * chunk_size);
/* copy second part */
memcpy(data_ptr + del_if_num * chunk_size,
orig_node->bcast_own + ((del_if_num + 1) * chunk_size),
(max_if_num - del_if_num) * chunk_size);
free_bcast_own:
kfree(orig_node->bcast_own);
orig_node->bcast_own = data_ptr;
if (max_if_num == 0)
goto free_own_sum;
data_ptr = kmalloc(max_if_num * sizeof(uint8_t), GFP_ATOMIC);
if (!data_ptr) {
pr_err("Can't resize orig: out of memory\n");
return -1;
}
memcpy(data_ptr, orig_node->bcast_own_sum,
del_if_num * sizeof(uint8_t));
memcpy(data_ptr + del_if_num * sizeof(uint8_t),
orig_node->bcast_own_sum + ((del_if_num + 1) * sizeof(uint8_t)),
(max_if_num - del_if_num) * sizeof(uint8_t));
free_own_sum:
kfree(orig_node->bcast_own_sum);
orig_node->bcast_own_sum = data_ptr;
return 0;
}
int orig_hash_del_if(struct hard_iface *hard_iface, int max_if_num)
{
struct bat_priv *bat_priv = netdev_priv(hard_iface->soft_iface);
struct hashtable_t *hash = bat_priv->orig_hash;
struct hlist_node *node;
struct hlist_head *head;
struct hard_iface *hard_iface_tmp;
struct orig_node *orig_node;
int i, ret;
/* resize all orig nodes because orig_node->bcast_own(_sum) depend on
* if_num */
for (i = 0; i < hash->size; i++) {
head = &hash->table[i];
rcu_read_lock();
hlist_for_each_entry_rcu(orig_node, node, head, hash_entry) {
spin_lock_bh(&orig_node->ogm_cnt_lock);
ret = orig_node_del_if(orig_node, max_if_num,
hard_iface->if_num);
spin_unlock_bh(&orig_node->ogm_cnt_lock);
if (ret == -1)
goto err;
}
rcu_read_unlock();
}
/* renumber remaining batman interfaces _inside_ of orig_hash_lock */
rcu_read_lock();
list_for_each_entry_rcu(hard_iface_tmp, &hardif_list, list) {
if (hard_iface_tmp->if_status == IF_NOT_IN_USE)
continue;
if (hard_iface == hard_iface_tmp)
continue;
if (hard_iface->soft_iface != hard_iface_tmp->soft_iface)
continue;
if (hard_iface_tmp->if_num > hard_iface->if_num)
hard_iface_tmp->if_num--;
}
rcu_read_unlock();
hard_iface->if_num = -1;
return 0;
err:
rcu_read_unlock();
return -ENOMEM;
}
| gpl-2.0 |
davidmueller13/lt03lte_tw_kernel_5.1.1 | drivers/net/ethernet/broadcom/tg3.c | 2627 | 428638 | /*
* tg3.c: Broadcom Tigon3 ethernet driver.
*
* Copyright (C) 2001, 2002, 2003, 2004 David S. Miller (davem@redhat.com)
* Copyright (C) 2001, 2002, 2003 Jeff Garzik (jgarzik@pobox.com)
* Copyright (C) 2004 Sun Microsystems Inc.
* Copyright (C) 2005-2012 Broadcom Corporation.
*
* Firmware is:
* Derived from proprietary unpublished source code,
* Copyright (C) 2000-2003 Broadcom Corporation.
*
* Permission is hereby granted for the distribution of this firmware
* data in hexadecimal or equivalent format, provided this copyright
* notice is accompanying it.
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/stringify.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/compiler.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/in.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/pci.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/ethtool.h>
#include <linux/mdio.h>
#include <linux/mii.h>
#include <linux/phy.h>
#include <linux/brcmphy.h>
#include <linux/if_vlan.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/workqueue.h>
#include <linux/prefetch.h>
#include <linux/dma-mapping.h>
#include <linux/firmware.h>
#include <net/checksum.h>
#include <net/ip.h>
#include <linux/io.h>
#include <asm/byteorder.h>
#include <linux/uaccess.h>
#ifdef CONFIG_SPARC
#include <asm/idprom.h>
#include <asm/prom.h>
#endif
#define BAR_0 0
#define BAR_2 2
#include "tg3.h"
/* Functions & macros to verify TG3_FLAGS types */
static inline int _tg3_flag(enum TG3_FLAGS flag, unsigned long *bits)
{
return test_bit(flag, bits);
}
static inline void _tg3_flag_set(enum TG3_FLAGS flag, unsigned long *bits)
{
set_bit(flag, bits);
}
static inline void _tg3_flag_clear(enum TG3_FLAGS flag, unsigned long *bits)
{
clear_bit(flag, bits);
}
#define tg3_flag(tp, flag) \
_tg3_flag(TG3_FLAG_##flag, (tp)->tg3_flags)
#define tg3_flag_set(tp, flag) \
_tg3_flag_set(TG3_FLAG_##flag, (tp)->tg3_flags)
#define tg3_flag_clear(tp, flag) \
_tg3_flag_clear(TG3_FLAG_##flag, (tp)->tg3_flags)
#define DRV_MODULE_NAME "tg3"
#define TG3_MAJ_NUM 3
#define TG3_MIN_NUM 123
#define DRV_MODULE_VERSION \
__stringify(TG3_MAJ_NUM) "." __stringify(TG3_MIN_NUM)
#define DRV_MODULE_RELDATE "March 21, 2012"
#define RESET_KIND_SHUTDOWN 0
#define RESET_KIND_INIT 1
#define RESET_KIND_SUSPEND 2
#define TG3_DEF_RX_MODE 0
#define TG3_DEF_TX_MODE 0
#define TG3_DEF_MSG_ENABLE \
(NETIF_MSG_DRV | \
NETIF_MSG_PROBE | \
NETIF_MSG_LINK | \
NETIF_MSG_TIMER | \
NETIF_MSG_IFDOWN | \
NETIF_MSG_IFUP | \
NETIF_MSG_RX_ERR | \
NETIF_MSG_TX_ERR)
#define TG3_GRC_LCLCTL_PWRSW_DELAY 100
/* length of time before we decide the hardware is borked,
* and dev->tx_timeout() should be called to fix the problem
*/
#define TG3_TX_TIMEOUT (5 * HZ)
/* hardware minimum and maximum for a single frame's data payload */
#define TG3_MIN_MTU 60
#define TG3_MAX_MTU(tp) \
(tg3_flag(tp, JUMBO_CAPABLE) ? 9000 : 1500)
/* These numbers seem to be hard coded in the NIC firmware somehow.
* You can't change the ring sizes, but you can change where you place
* them in the NIC onboard memory.
*/
#define TG3_RX_STD_RING_SIZE(tp) \
(tg3_flag(tp, LRG_PROD_RING_CAP) ? \
TG3_RX_STD_MAX_SIZE_5717 : TG3_RX_STD_MAX_SIZE_5700)
#define TG3_DEF_RX_RING_PENDING 200
#define TG3_RX_JMB_RING_SIZE(tp) \
(tg3_flag(tp, LRG_PROD_RING_CAP) ? \
TG3_RX_JMB_MAX_SIZE_5717 : TG3_RX_JMB_MAX_SIZE_5700)
#define TG3_DEF_RX_JUMBO_RING_PENDING 100
/* Do not place this n-ring entries value into the tp struct itself,
* we really want to expose these constants to GCC so that modulo et
* al. operations are done with shifts and masks instead of with
* hw multiply/modulo instructions. Another solution would be to
* replace things like '% foo' with '& (foo - 1)'.
*/
#define TG3_TX_RING_SIZE 512
#define TG3_DEF_TX_RING_PENDING (TG3_TX_RING_SIZE - 1)
#define TG3_RX_STD_RING_BYTES(tp) \
(sizeof(struct tg3_rx_buffer_desc) * TG3_RX_STD_RING_SIZE(tp))
#define TG3_RX_JMB_RING_BYTES(tp) \
(sizeof(struct tg3_ext_rx_buffer_desc) * TG3_RX_JMB_RING_SIZE(tp))
#define TG3_RX_RCB_RING_BYTES(tp) \
(sizeof(struct tg3_rx_buffer_desc) * (tp->rx_ret_ring_mask + 1))
#define TG3_TX_RING_BYTES (sizeof(struct tg3_tx_buffer_desc) * \
TG3_TX_RING_SIZE)
#define NEXT_TX(N) (((N) + 1) & (TG3_TX_RING_SIZE - 1))
#define TG3_DMA_BYTE_ENAB 64
#define TG3_RX_STD_DMA_SZ 1536
#define TG3_RX_JMB_DMA_SZ 9046
#define TG3_RX_DMA_TO_MAP_SZ(x) ((x) + TG3_DMA_BYTE_ENAB)
#define TG3_RX_STD_MAP_SZ TG3_RX_DMA_TO_MAP_SZ(TG3_RX_STD_DMA_SZ)
#define TG3_RX_JMB_MAP_SZ TG3_RX_DMA_TO_MAP_SZ(TG3_RX_JMB_DMA_SZ)
#define TG3_RX_STD_BUFF_RING_SIZE(tp) \
(sizeof(struct ring_info) * TG3_RX_STD_RING_SIZE(tp))
#define TG3_RX_JMB_BUFF_RING_SIZE(tp) \
(sizeof(struct ring_info) * TG3_RX_JMB_RING_SIZE(tp))
/* Due to a hardware bug, the 5701 can only DMA to memory addresses
* that are at least dword aligned when used in PCIX mode. The driver
* works around this bug by double copying the packet. This workaround
* is built into the normal double copy length check for efficiency.
*
* However, the double copy is only necessary on those architectures
* where unaligned memory accesses are inefficient. For those architectures
* where unaligned memory accesses incur little penalty, we can reintegrate
* the 5701 in the normal rx path. Doing so saves a device structure
* dereference by hardcoding the double copy threshold in place.
*/
#define TG3_RX_COPY_THRESHOLD 256
#if NET_IP_ALIGN == 0 || defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)
#define TG3_RX_COPY_THRESH(tp) TG3_RX_COPY_THRESHOLD
#else
#define TG3_RX_COPY_THRESH(tp) ((tp)->rx_copy_thresh)
#endif
#if (NET_IP_ALIGN != 0)
#define TG3_RX_OFFSET(tp) ((tp)->rx_offset)
#else
#define TG3_RX_OFFSET(tp) (NET_SKB_PAD)
#endif
/* minimum number of free TX descriptors required to wake up TX process */
#define TG3_TX_WAKEUP_THRESH(tnapi) ((tnapi)->tx_pending / 4)
#define TG3_TX_BD_DMA_MAX_2K 2048
#define TG3_TX_BD_DMA_MAX_4K 4096
#define TG3_RAW_IP_ALIGN 2
#define TG3_FW_UPDATE_TIMEOUT_SEC 5
#define TG3_FW_UPDATE_FREQ_SEC (TG3_FW_UPDATE_TIMEOUT_SEC / 2)
#define FIRMWARE_TG3 "tigon/tg3.bin"
#define FIRMWARE_TG3TSO "tigon/tg3_tso.bin"
#define FIRMWARE_TG3TSO5 "tigon/tg3_tso5.bin"
static char version[] __devinitdata =
DRV_MODULE_NAME ".c:v" DRV_MODULE_VERSION " (" DRV_MODULE_RELDATE ")";
MODULE_AUTHOR("David S. Miller (davem@redhat.com) and Jeff Garzik (jgarzik@pobox.com)");
MODULE_DESCRIPTION("Broadcom Tigon3 ethernet driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_MODULE_VERSION);
MODULE_FIRMWARE(FIRMWARE_TG3);
MODULE_FIRMWARE(FIRMWARE_TG3TSO);
MODULE_FIRMWARE(FIRMWARE_TG3TSO5);
static int tg3_debug = -1; /* -1 == use TG3_DEF_MSG_ENABLE as value */
module_param(tg3_debug, int, 0);
MODULE_PARM_DESC(tg3_debug, "Tigon3 bitmapped debugging message enable value");
static DEFINE_PCI_DEVICE_TABLE(tg3_pci_tbl) = {
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5700)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5701)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5702)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5703)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5704)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5702FE)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5705)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5705_2)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5705M)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5705M_2)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5702X)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5703X)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5704S)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5702A3)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5703A3)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5782)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5788)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5789)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5901)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5901_2)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5704S_2)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5705F)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5721)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5722)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5751)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5751M)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5751F)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5752)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5752M)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5753)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5753M)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5753F)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5754)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5754M)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5755)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5755M)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5756)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5786)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5787)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5787M)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5787F)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5714)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5714S)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5715)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5715S)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5780)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5780S)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5781)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5906)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5906M)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5784)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5764)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5723)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5761)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_TIGON3_5761E)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_5761S)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_5761SE)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_5785_G)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_5785_F)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57780)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57760)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57790)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57788)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_5717)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_5718)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57781)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57785)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57761)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57765)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57791)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_57795)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_5719)},
{PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, TG3PCI_DEVICE_TIGON3_5720)},
{PCI_DEVICE(PCI_VENDOR_ID_SYSKONNECT, PCI_DEVICE_ID_SYSKONNECT_9DXX)},
{PCI_DEVICE(PCI_VENDOR_ID_SYSKONNECT, PCI_DEVICE_ID_SYSKONNECT_9MXX)},
{PCI_DEVICE(PCI_VENDOR_ID_ALTIMA, PCI_DEVICE_ID_ALTIMA_AC1000)},
{PCI_DEVICE(PCI_VENDOR_ID_ALTIMA, PCI_DEVICE_ID_ALTIMA_AC1001)},
{PCI_DEVICE(PCI_VENDOR_ID_ALTIMA, PCI_DEVICE_ID_ALTIMA_AC1003)},
{PCI_DEVICE(PCI_VENDOR_ID_ALTIMA, PCI_DEVICE_ID_ALTIMA_AC9100)},
{PCI_DEVICE(PCI_VENDOR_ID_APPLE, PCI_DEVICE_ID_APPLE_TIGON3)},
{PCI_DEVICE(0x10cf, 0x11a2)}, /* Fujitsu 1000base-SX with BCM5703SKHB */
{}
};
MODULE_DEVICE_TABLE(pci, tg3_pci_tbl);
static const struct {
const char string[ETH_GSTRING_LEN];
} ethtool_stats_keys[] = {
{ "rx_octets" },
{ "rx_fragments" },
{ "rx_ucast_packets" },
{ "rx_mcast_packets" },
{ "rx_bcast_packets" },
{ "rx_fcs_errors" },
{ "rx_align_errors" },
{ "rx_xon_pause_rcvd" },
{ "rx_xoff_pause_rcvd" },
{ "rx_mac_ctrl_rcvd" },
{ "rx_xoff_entered" },
{ "rx_frame_too_long_errors" },
{ "rx_jabbers" },
{ "rx_undersize_packets" },
{ "rx_in_length_errors" },
{ "rx_out_length_errors" },
{ "rx_64_or_less_octet_packets" },
{ "rx_65_to_127_octet_packets" },
{ "rx_128_to_255_octet_packets" },
{ "rx_256_to_511_octet_packets" },
{ "rx_512_to_1023_octet_packets" },
{ "rx_1024_to_1522_octet_packets" },
{ "rx_1523_to_2047_octet_packets" },
{ "rx_2048_to_4095_octet_packets" },
{ "rx_4096_to_8191_octet_packets" },
{ "rx_8192_to_9022_octet_packets" },
{ "tx_octets" },
{ "tx_collisions" },
{ "tx_xon_sent" },
{ "tx_xoff_sent" },
{ "tx_flow_control" },
{ "tx_mac_errors" },
{ "tx_single_collisions" },
{ "tx_mult_collisions" },
{ "tx_deferred" },
{ "tx_excessive_collisions" },
{ "tx_late_collisions" },
{ "tx_collide_2times" },
{ "tx_collide_3times" },
{ "tx_collide_4times" },
{ "tx_collide_5times" },
{ "tx_collide_6times" },
{ "tx_collide_7times" },
{ "tx_collide_8times" },
{ "tx_collide_9times" },
{ "tx_collide_10times" },
{ "tx_collide_11times" },
{ "tx_collide_12times" },
{ "tx_collide_13times" },
{ "tx_collide_14times" },
{ "tx_collide_15times" },
{ "tx_ucast_packets" },
{ "tx_mcast_packets" },
{ "tx_bcast_packets" },
{ "tx_carrier_sense_errors" },
{ "tx_discards" },
{ "tx_errors" },
{ "dma_writeq_full" },
{ "dma_write_prioq_full" },
{ "rxbds_empty" },
{ "rx_discards" },
{ "rx_errors" },
{ "rx_threshold_hit" },
{ "dma_readq_full" },
{ "dma_read_prioq_full" },
{ "tx_comp_queue_full" },
{ "ring_set_send_prod_index" },
{ "ring_status_update" },
{ "nic_irqs" },
{ "nic_avoided_irqs" },
{ "nic_tx_threshold_hit" },
{ "mbuf_lwm_thresh_hit" },
};
#define TG3_NUM_STATS ARRAY_SIZE(ethtool_stats_keys)
static const struct {
const char string[ETH_GSTRING_LEN];
} ethtool_test_keys[] = {
{ "nvram test (online) " },
{ "link test (online) " },
{ "register test (offline)" },
{ "memory test (offline)" },
{ "mac loopback test (offline)" },
{ "phy loopback test (offline)" },
{ "ext loopback test (offline)" },
{ "interrupt test (offline)" },
};
#define TG3_NUM_TEST ARRAY_SIZE(ethtool_test_keys)
static void tg3_write32(struct tg3 *tp, u32 off, u32 val)
{
writel(val, tp->regs + off);
}
static u32 tg3_read32(struct tg3 *tp, u32 off)
{
return readl(tp->regs + off);
}
static void tg3_ape_write32(struct tg3 *tp, u32 off, u32 val)
{
writel(val, tp->aperegs + off);
}
static u32 tg3_ape_read32(struct tg3 *tp, u32 off)
{
return readl(tp->aperegs + off);
}
static void tg3_write_indirect_reg32(struct tg3 *tp, u32 off, u32 val)
{
unsigned long flags;
spin_lock_irqsave(&tp->indirect_lock, flags);
pci_write_config_dword(tp->pdev, TG3PCI_REG_BASE_ADDR, off);
pci_write_config_dword(tp->pdev, TG3PCI_REG_DATA, val);
spin_unlock_irqrestore(&tp->indirect_lock, flags);
}
static void tg3_write_flush_reg32(struct tg3 *tp, u32 off, u32 val)
{
writel(val, tp->regs + off);
readl(tp->regs + off);
}
static u32 tg3_read_indirect_reg32(struct tg3 *tp, u32 off)
{
unsigned long flags;
u32 val;
spin_lock_irqsave(&tp->indirect_lock, flags);
pci_write_config_dword(tp->pdev, TG3PCI_REG_BASE_ADDR, off);
pci_read_config_dword(tp->pdev, TG3PCI_REG_DATA, &val);
spin_unlock_irqrestore(&tp->indirect_lock, flags);
return val;
}
static void tg3_write_indirect_mbox(struct tg3 *tp, u32 off, u32 val)
{
unsigned long flags;
if (off == (MAILBOX_RCVRET_CON_IDX_0 + TG3_64BIT_REG_LOW)) {
pci_write_config_dword(tp->pdev, TG3PCI_RCV_RET_RING_CON_IDX +
TG3_64BIT_REG_LOW, val);
return;
}
if (off == TG3_RX_STD_PROD_IDX_REG) {
pci_write_config_dword(tp->pdev, TG3PCI_STD_RING_PROD_IDX +
TG3_64BIT_REG_LOW, val);
return;
}
spin_lock_irqsave(&tp->indirect_lock, flags);
pci_write_config_dword(tp->pdev, TG3PCI_REG_BASE_ADDR, off + 0x5600);
pci_write_config_dword(tp->pdev, TG3PCI_REG_DATA, val);
spin_unlock_irqrestore(&tp->indirect_lock, flags);
/* In indirect mode when disabling interrupts, we also need
* to clear the interrupt bit in the GRC local ctrl register.
*/
if ((off == (MAILBOX_INTERRUPT_0 + TG3_64BIT_REG_LOW)) &&
(val == 0x1)) {
pci_write_config_dword(tp->pdev, TG3PCI_MISC_LOCAL_CTRL,
tp->grc_local_ctrl|GRC_LCLCTRL_CLEARINT);
}
}
static u32 tg3_read_indirect_mbox(struct tg3 *tp, u32 off)
{
unsigned long flags;
u32 val;
spin_lock_irqsave(&tp->indirect_lock, flags);
pci_write_config_dword(tp->pdev, TG3PCI_REG_BASE_ADDR, off + 0x5600);
pci_read_config_dword(tp->pdev, TG3PCI_REG_DATA, &val);
spin_unlock_irqrestore(&tp->indirect_lock, flags);
return val;
}
/* usec_wait specifies the wait time in usec when writing to certain registers
* where it is unsafe to read back the register without some delay.
* GRC_LOCAL_CTRL is one example if the GPIOs are toggled to switch power.
* TG3PCI_CLOCK_CTRL is another example if the clock frequencies are changed.
*/
static void _tw32_flush(struct tg3 *tp, u32 off, u32 val, u32 usec_wait)
{
if (tg3_flag(tp, PCIX_TARGET_HWBUG) || tg3_flag(tp, ICH_WORKAROUND))
/* Non-posted methods */
tp->write32(tp, off, val);
else {
/* Posted method */
tg3_write32(tp, off, val);
if (usec_wait)
udelay(usec_wait);
tp->read32(tp, off);
}
/* Wait again after the read for the posted method to guarantee that
* the wait time is met.
*/
if (usec_wait)
udelay(usec_wait);
}
static inline void tw32_mailbox_flush(struct tg3 *tp, u32 off, u32 val)
{
tp->write32_mbox(tp, off, val);
if (!tg3_flag(tp, MBOX_WRITE_REORDER) && !tg3_flag(tp, ICH_WORKAROUND))
tp->read32_mbox(tp, off);
}
static void tg3_write32_tx_mbox(struct tg3 *tp, u32 off, u32 val)
{
void __iomem *mbox = tp->regs + off;
writel(val, mbox);
if (tg3_flag(tp, TXD_MBOX_HWBUG))
writel(val, mbox);
if (tg3_flag(tp, MBOX_WRITE_REORDER))
readl(mbox);
}
static u32 tg3_read32_mbox_5906(struct tg3 *tp, u32 off)
{
return readl(tp->regs + off + GRCMBOX_BASE);
}
static void tg3_write32_mbox_5906(struct tg3 *tp, u32 off, u32 val)
{
writel(val, tp->regs + off + GRCMBOX_BASE);
}
#define tw32_mailbox(reg, val) tp->write32_mbox(tp, reg, val)
#define tw32_mailbox_f(reg, val) tw32_mailbox_flush(tp, (reg), (val))
#define tw32_rx_mbox(reg, val) tp->write32_rx_mbox(tp, reg, val)
#define tw32_tx_mbox(reg, val) tp->write32_tx_mbox(tp, reg, val)
#define tr32_mailbox(reg) tp->read32_mbox(tp, reg)
#define tw32(reg, val) tp->write32(tp, reg, val)
#define tw32_f(reg, val) _tw32_flush(tp, (reg), (val), 0)
#define tw32_wait_f(reg, val, us) _tw32_flush(tp, (reg), (val), (us))
#define tr32(reg) tp->read32(tp, reg)
static void tg3_write_mem(struct tg3 *tp, u32 off, u32 val)
{
unsigned long flags;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5906 &&
(off >= NIC_SRAM_STATS_BLK) && (off < NIC_SRAM_TX_BUFFER_DESC))
return;
spin_lock_irqsave(&tp->indirect_lock, flags);
if (tg3_flag(tp, SRAM_USE_CONFIG)) {
pci_write_config_dword(tp->pdev, TG3PCI_MEM_WIN_BASE_ADDR, off);
pci_write_config_dword(tp->pdev, TG3PCI_MEM_WIN_DATA, val);
/* Always leave this as zero. */
pci_write_config_dword(tp->pdev, TG3PCI_MEM_WIN_BASE_ADDR, 0);
} else {
tw32_f(TG3PCI_MEM_WIN_BASE_ADDR, off);
tw32_f(TG3PCI_MEM_WIN_DATA, val);
/* Always leave this as zero. */
tw32_f(TG3PCI_MEM_WIN_BASE_ADDR, 0);
}
spin_unlock_irqrestore(&tp->indirect_lock, flags);
}
static void tg3_read_mem(struct tg3 *tp, u32 off, u32 *val)
{
unsigned long flags;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5906 &&
(off >= NIC_SRAM_STATS_BLK) && (off < NIC_SRAM_TX_BUFFER_DESC)) {
*val = 0;
return;
}
spin_lock_irqsave(&tp->indirect_lock, flags);
if (tg3_flag(tp, SRAM_USE_CONFIG)) {
pci_write_config_dword(tp->pdev, TG3PCI_MEM_WIN_BASE_ADDR, off);
pci_read_config_dword(tp->pdev, TG3PCI_MEM_WIN_DATA, val);
/* Always leave this as zero. */
pci_write_config_dword(tp->pdev, TG3PCI_MEM_WIN_BASE_ADDR, 0);
} else {
tw32_f(TG3PCI_MEM_WIN_BASE_ADDR, off);
*val = tr32(TG3PCI_MEM_WIN_DATA);
/* Always leave this as zero. */
tw32_f(TG3PCI_MEM_WIN_BASE_ADDR, 0);
}
spin_unlock_irqrestore(&tp->indirect_lock, flags);
}
static void tg3_ape_lock_init(struct tg3 *tp)
{
int i;
u32 regbase, bit;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5761)
regbase = TG3_APE_LOCK_GRANT;
else
regbase = TG3_APE_PER_LOCK_GRANT;
/* Make sure the driver hasn't any stale locks. */
for (i = TG3_APE_LOCK_PHY0; i <= TG3_APE_LOCK_GPIO; i++) {
switch (i) {
case TG3_APE_LOCK_PHY0:
case TG3_APE_LOCK_PHY1:
case TG3_APE_LOCK_PHY2:
case TG3_APE_LOCK_PHY3:
bit = APE_LOCK_GRANT_DRIVER;
break;
default:
if (!tp->pci_fn)
bit = APE_LOCK_GRANT_DRIVER;
else
bit = 1 << tp->pci_fn;
}
tg3_ape_write32(tp, regbase + 4 * i, bit);
}
}
static int tg3_ape_lock(struct tg3 *tp, int locknum)
{
int i, off;
int ret = 0;
u32 status, req, gnt, bit;
if (!tg3_flag(tp, ENABLE_APE))
return 0;
switch (locknum) {
case TG3_APE_LOCK_GPIO:
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5761)
return 0;
case TG3_APE_LOCK_GRC:
case TG3_APE_LOCK_MEM:
if (!tp->pci_fn)
bit = APE_LOCK_REQ_DRIVER;
else
bit = 1 << tp->pci_fn;
break;
default:
return -EINVAL;
}
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5761) {
req = TG3_APE_LOCK_REQ;
gnt = TG3_APE_LOCK_GRANT;
} else {
req = TG3_APE_PER_LOCK_REQ;
gnt = TG3_APE_PER_LOCK_GRANT;
}
off = 4 * locknum;
tg3_ape_write32(tp, req + off, bit);
/* Wait for up to 1 millisecond to acquire lock. */
for (i = 0; i < 100; i++) {
status = tg3_ape_read32(tp, gnt + off);
if (status == bit)
break;
udelay(10);
}
if (status != bit) {
/* Revoke the lock request. */
tg3_ape_write32(tp, gnt + off, bit);
ret = -EBUSY;
}
return ret;
}
static void tg3_ape_unlock(struct tg3 *tp, int locknum)
{
u32 gnt, bit;
if (!tg3_flag(tp, ENABLE_APE))
return;
switch (locknum) {
case TG3_APE_LOCK_GPIO:
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5761)
return;
case TG3_APE_LOCK_GRC:
case TG3_APE_LOCK_MEM:
if (!tp->pci_fn)
bit = APE_LOCK_GRANT_DRIVER;
else
bit = 1 << tp->pci_fn;
break;
default:
return;
}
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5761)
gnt = TG3_APE_LOCK_GRANT;
else
gnt = TG3_APE_PER_LOCK_GRANT;
tg3_ape_write32(tp, gnt + 4 * locknum, bit);
}
static void tg3_ape_send_event(struct tg3 *tp, u32 event)
{
int i;
u32 apedata;
/* NCSI does not support APE events */
if (tg3_flag(tp, APE_HAS_NCSI))
return;
apedata = tg3_ape_read32(tp, TG3_APE_SEG_SIG);
if (apedata != APE_SEG_SIG_MAGIC)
return;
apedata = tg3_ape_read32(tp, TG3_APE_FW_STATUS);
if (!(apedata & APE_FW_STATUS_READY))
return;
/* Wait for up to 1 millisecond for APE to service previous event. */
for (i = 0; i < 10; i++) {
if (tg3_ape_lock(tp, TG3_APE_LOCK_MEM))
return;
apedata = tg3_ape_read32(tp, TG3_APE_EVENT_STATUS);
if (!(apedata & APE_EVENT_STATUS_EVENT_PENDING))
tg3_ape_write32(tp, TG3_APE_EVENT_STATUS,
event | APE_EVENT_STATUS_EVENT_PENDING);
tg3_ape_unlock(tp, TG3_APE_LOCK_MEM);
if (!(apedata & APE_EVENT_STATUS_EVENT_PENDING))
break;
udelay(100);
}
if (!(apedata & APE_EVENT_STATUS_EVENT_PENDING))
tg3_ape_write32(tp, TG3_APE_EVENT, APE_EVENT_1);
}
static void tg3_ape_driver_state_change(struct tg3 *tp, int kind)
{
u32 event;
u32 apedata;
if (!tg3_flag(tp, ENABLE_APE))
return;
switch (kind) {
case RESET_KIND_INIT:
tg3_ape_write32(tp, TG3_APE_HOST_SEG_SIG,
APE_HOST_SEG_SIG_MAGIC);
tg3_ape_write32(tp, TG3_APE_HOST_SEG_LEN,
APE_HOST_SEG_LEN_MAGIC);
apedata = tg3_ape_read32(tp, TG3_APE_HOST_INIT_COUNT);
tg3_ape_write32(tp, TG3_APE_HOST_INIT_COUNT, ++apedata);
tg3_ape_write32(tp, TG3_APE_HOST_DRIVER_ID,
APE_HOST_DRIVER_ID_MAGIC(TG3_MAJ_NUM, TG3_MIN_NUM));
tg3_ape_write32(tp, TG3_APE_HOST_BEHAVIOR,
APE_HOST_BEHAV_NO_PHYLOCK);
tg3_ape_write32(tp, TG3_APE_HOST_DRVR_STATE,
TG3_APE_HOST_DRVR_STATE_START);
event = APE_EVENT_STATUS_STATE_START;
break;
case RESET_KIND_SHUTDOWN:
/* With the interface we are currently using,
* APE does not track driver state. Wiping
* out the HOST SEGMENT SIGNATURE forces
* the APE to assume OS absent status.
*/
tg3_ape_write32(tp, TG3_APE_HOST_SEG_SIG, 0x0);
if (device_may_wakeup(&tp->pdev->dev) &&
tg3_flag(tp, WOL_ENABLE)) {
tg3_ape_write32(tp, TG3_APE_HOST_WOL_SPEED,
TG3_APE_HOST_WOL_SPEED_AUTO);
apedata = TG3_APE_HOST_DRVR_STATE_WOL;
} else
apedata = TG3_APE_HOST_DRVR_STATE_UNLOAD;
tg3_ape_write32(tp, TG3_APE_HOST_DRVR_STATE, apedata);
event = APE_EVENT_STATUS_STATE_UNLOAD;
break;
case RESET_KIND_SUSPEND:
event = APE_EVENT_STATUS_STATE_SUSPEND;
break;
default:
return;
}
event |= APE_EVENT_STATUS_DRIVER_EVNT | APE_EVENT_STATUS_STATE_CHNGE;
tg3_ape_send_event(tp, event);
}
static void tg3_disable_ints(struct tg3 *tp)
{
int i;
tw32(TG3PCI_MISC_HOST_CTRL,
(tp->misc_host_ctrl | MISC_HOST_CTRL_MASK_PCI_INT));
for (i = 0; i < tp->irq_max; i++)
tw32_mailbox_f(tp->napi[i].int_mbox, 0x00000001);
}
static void tg3_enable_ints(struct tg3 *tp)
{
int i;
tp->irq_sync = 0;
wmb();
tw32(TG3PCI_MISC_HOST_CTRL,
(tp->misc_host_ctrl & ~MISC_HOST_CTRL_MASK_PCI_INT));
tp->coal_now = tp->coalesce_mode | HOSTCC_MODE_ENABLE;
for (i = 0; i < tp->irq_cnt; i++) {
struct tg3_napi *tnapi = &tp->napi[i];
tw32_mailbox_f(tnapi->int_mbox, tnapi->last_tag << 24);
if (tg3_flag(tp, 1SHOT_MSI))
tw32_mailbox_f(tnapi->int_mbox, tnapi->last_tag << 24);
tp->coal_now |= tnapi->coal_now;
}
/* Force an initial interrupt */
if (!tg3_flag(tp, TAGGED_STATUS) &&
(tp->napi[0].hw_status->status & SD_STATUS_UPDATED))
tw32(GRC_LOCAL_CTRL, tp->grc_local_ctrl | GRC_LCLCTRL_SETINT);
else
tw32(HOSTCC_MODE, tp->coal_now);
tp->coal_now &= ~(tp->napi[0].coal_now | tp->napi[1].coal_now);
}
static inline unsigned int tg3_has_work(struct tg3_napi *tnapi)
{
struct tg3 *tp = tnapi->tp;
struct tg3_hw_status *sblk = tnapi->hw_status;
unsigned int work_exists = 0;
/* check for phy events */
if (!(tg3_flag(tp, USE_LINKCHG_REG) || tg3_flag(tp, POLL_SERDES))) {
if (sblk->status & SD_STATUS_LINK_CHG)
work_exists = 1;
}
/* check for TX work to do */
if (sblk->idx[0].tx_consumer != tnapi->tx_cons)
work_exists = 1;
/* check for RX work to do */
if (tnapi->rx_rcb_prod_idx &&
*(tnapi->rx_rcb_prod_idx) != tnapi->rx_rcb_ptr)
work_exists = 1;
return work_exists;
}
/* tg3_int_reenable
* similar to tg3_enable_ints, but it accurately determines whether there
* is new work pending and can return without flushing the PIO write
* which reenables interrupts
*/
static void tg3_int_reenable(struct tg3_napi *tnapi)
{
struct tg3 *tp = tnapi->tp;
tw32_mailbox(tnapi->int_mbox, tnapi->last_tag << 24);
mmiowb();
/* When doing tagged status, this work check is unnecessary.
* The last_tag we write above tells the chip which piece of
* work we've completed.
*/
if (!tg3_flag(tp, TAGGED_STATUS) && tg3_has_work(tnapi))
tw32(HOSTCC_MODE, tp->coalesce_mode |
HOSTCC_MODE_ENABLE | tnapi->coal_now);
}
static void tg3_switch_clocks(struct tg3 *tp)
{
u32 clock_ctrl;
u32 orig_clock_ctrl;
if (tg3_flag(tp, CPMU_PRESENT) || tg3_flag(tp, 5780_CLASS))
return;
clock_ctrl = tr32(TG3PCI_CLOCK_CTRL);
orig_clock_ctrl = clock_ctrl;
clock_ctrl &= (CLOCK_CTRL_FORCE_CLKRUN |
CLOCK_CTRL_CLKRUN_OENABLE |
0x1f);
tp->pci_clock_ctrl = clock_ctrl;
if (tg3_flag(tp, 5705_PLUS)) {
if (orig_clock_ctrl & CLOCK_CTRL_625_CORE) {
tw32_wait_f(TG3PCI_CLOCK_CTRL,
clock_ctrl | CLOCK_CTRL_625_CORE, 40);
}
} else if ((orig_clock_ctrl & CLOCK_CTRL_44MHZ_CORE) != 0) {
tw32_wait_f(TG3PCI_CLOCK_CTRL,
clock_ctrl |
(CLOCK_CTRL_44MHZ_CORE | CLOCK_CTRL_ALTCLK),
40);
tw32_wait_f(TG3PCI_CLOCK_CTRL,
clock_ctrl | (CLOCK_CTRL_ALTCLK),
40);
}
tw32_wait_f(TG3PCI_CLOCK_CTRL, clock_ctrl, 40);
}
#define PHY_BUSY_LOOPS 5000
static int tg3_readphy(struct tg3 *tp, int reg, u32 *val)
{
u32 frame_val;
unsigned int loops;
int ret;
if ((tp->mi_mode & MAC_MI_MODE_AUTO_POLL) != 0) {
tw32_f(MAC_MI_MODE,
(tp->mi_mode & ~MAC_MI_MODE_AUTO_POLL));
udelay(80);
}
*val = 0x0;
frame_val = ((tp->phy_addr << MI_COM_PHY_ADDR_SHIFT) &
MI_COM_PHY_ADDR_MASK);
frame_val |= ((reg << MI_COM_REG_ADDR_SHIFT) &
MI_COM_REG_ADDR_MASK);
frame_val |= (MI_COM_CMD_READ | MI_COM_START);
tw32_f(MAC_MI_COM, frame_val);
loops = PHY_BUSY_LOOPS;
while (loops != 0) {
udelay(10);
frame_val = tr32(MAC_MI_COM);
if ((frame_val & MI_COM_BUSY) == 0) {
udelay(5);
frame_val = tr32(MAC_MI_COM);
break;
}
loops -= 1;
}
ret = -EBUSY;
if (loops != 0) {
*val = frame_val & MI_COM_DATA_MASK;
ret = 0;
}
if ((tp->mi_mode & MAC_MI_MODE_AUTO_POLL) != 0) {
tw32_f(MAC_MI_MODE, tp->mi_mode);
udelay(80);
}
return ret;
}
static int tg3_writephy(struct tg3 *tp, int reg, u32 val)
{
u32 frame_val;
unsigned int loops;
int ret;
if ((tp->phy_flags & TG3_PHYFLG_IS_FET) &&
(reg == MII_CTRL1000 || reg == MII_TG3_AUX_CTRL))
return 0;
if ((tp->mi_mode & MAC_MI_MODE_AUTO_POLL) != 0) {
tw32_f(MAC_MI_MODE,
(tp->mi_mode & ~MAC_MI_MODE_AUTO_POLL));
udelay(80);
}
frame_val = ((tp->phy_addr << MI_COM_PHY_ADDR_SHIFT) &
MI_COM_PHY_ADDR_MASK);
frame_val |= ((reg << MI_COM_REG_ADDR_SHIFT) &
MI_COM_REG_ADDR_MASK);
frame_val |= (val & MI_COM_DATA_MASK);
frame_val |= (MI_COM_CMD_WRITE | MI_COM_START);
tw32_f(MAC_MI_COM, frame_val);
loops = PHY_BUSY_LOOPS;
while (loops != 0) {
udelay(10);
frame_val = tr32(MAC_MI_COM);
if ((frame_val & MI_COM_BUSY) == 0) {
udelay(5);
frame_val = tr32(MAC_MI_COM);
break;
}
loops -= 1;
}
ret = -EBUSY;
if (loops != 0)
ret = 0;
if ((tp->mi_mode & MAC_MI_MODE_AUTO_POLL) != 0) {
tw32_f(MAC_MI_MODE, tp->mi_mode);
udelay(80);
}
return ret;
}
static int tg3_phy_cl45_write(struct tg3 *tp, u32 devad, u32 addr, u32 val)
{
int err;
err = tg3_writephy(tp, MII_TG3_MMD_CTRL, devad);
if (err)
goto done;
err = tg3_writephy(tp, MII_TG3_MMD_ADDRESS, addr);
if (err)
goto done;
err = tg3_writephy(tp, MII_TG3_MMD_CTRL,
MII_TG3_MMD_CTRL_DATA_NOINC | devad);
if (err)
goto done;
err = tg3_writephy(tp, MII_TG3_MMD_ADDRESS, val);
done:
return err;
}
static int tg3_phy_cl45_read(struct tg3 *tp, u32 devad, u32 addr, u32 *val)
{
int err;
err = tg3_writephy(tp, MII_TG3_MMD_CTRL, devad);
if (err)
goto done;
err = tg3_writephy(tp, MII_TG3_MMD_ADDRESS, addr);
if (err)
goto done;
err = tg3_writephy(tp, MII_TG3_MMD_CTRL,
MII_TG3_MMD_CTRL_DATA_NOINC | devad);
if (err)
goto done;
err = tg3_readphy(tp, MII_TG3_MMD_ADDRESS, val);
done:
return err;
}
static int tg3_phydsp_read(struct tg3 *tp, u32 reg, u32 *val)
{
int err;
err = tg3_writephy(tp, MII_TG3_DSP_ADDRESS, reg);
if (!err)
err = tg3_readphy(tp, MII_TG3_DSP_RW_PORT, val);
return err;
}
static int tg3_phydsp_write(struct tg3 *tp, u32 reg, u32 val)
{
int err;
err = tg3_writephy(tp, MII_TG3_DSP_ADDRESS, reg);
if (!err)
err = tg3_writephy(tp, MII_TG3_DSP_RW_PORT, val);
return err;
}
static int tg3_phy_auxctl_read(struct tg3 *tp, int reg, u32 *val)
{
int err;
err = tg3_writephy(tp, MII_TG3_AUX_CTRL,
(reg << MII_TG3_AUXCTL_MISC_RDSEL_SHIFT) |
MII_TG3_AUXCTL_SHDWSEL_MISC);
if (!err)
err = tg3_readphy(tp, MII_TG3_AUX_CTRL, val);
return err;
}
static int tg3_phy_auxctl_write(struct tg3 *tp, int reg, u32 set)
{
if (reg == MII_TG3_AUXCTL_SHDWSEL_MISC)
set |= MII_TG3_AUXCTL_MISC_WREN;
return tg3_writephy(tp, MII_TG3_AUX_CTRL, set | reg);
}
#define TG3_PHY_AUXCTL_SMDSP_ENABLE(tp) \
tg3_phy_auxctl_write((tp), MII_TG3_AUXCTL_SHDWSEL_AUXCTL, \
MII_TG3_AUXCTL_ACTL_SMDSP_ENA | \
MII_TG3_AUXCTL_ACTL_TX_6DB)
#define TG3_PHY_AUXCTL_SMDSP_DISABLE(tp) \
tg3_phy_auxctl_write((tp), MII_TG3_AUXCTL_SHDWSEL_AUXCTL, \
MII_TG3_AUXCTL_ACTL_TX_6DB);
static int tg3_bmcr_reset(struct tg3 *tp)
{
u32 phy_control;
int limit, err;
/* OK, reset it, and poll the BMCR_RESET bit until it
* clears or we time out.
*/
phy_control = BMCR_RESET;
err = tg3_writephy(tp, MII_BMCR, phy_control);
if (err != 0)
return -EBUSY;
limit = 5000;
while (limit--) {
err = tg3_readphy(tp, MII_BMCR, &phy_control);
if (err != 0)
return -EBUSY;
if ((phy_control & BMCR_RESET) == 0) {
udelay(40);
break;
}
udelay(10);
}
if (limit < 0)
return -EBUSY;
return 0;
}
static int tg3_mdio_read(struct mii_bus *bp, int mii_id, int reg)
{
struct tg3 *tp = bp->priv;
u32 val;
spin_lock_bh(&tp->lock);
if (tg3_readphy(tp, reg, &val))
val = -EIO;
spin_unlock_bh(&tp->lock);
return val;
}
static int tg3_mdio_write(struct mii_bus *bp, int mii_id, int reg, u16 val)
{
struct tg3 *tp = bp->priv;
u32 ret = 0;
spin_lock_bh(&tp->lock);
if (tg3_writephy(tp, reg, val))
ret = -EIO;
spin_unlock_bh(&tp->lock);
return ret;
}
static int tg3_mdio_reset(struct mii_bus *bp)
{
return 0;
}
static void tg3_mdio_config_5785(struct tg3 *tp)
{
u32 val;
struct phy_device *phydev;
phydev = tp->mdio_bus->phy_map[TG3_PHY_MII_ADDR];
switch (phydev->drv->phy_id & phydev->drv->phy_id_mask) {
case PHY_ID_BCM50610:
case PHY_ID_BCM50610M:
val = MAC_PHYCFG2_50610_LED_MODES;
break;
case PHY_ID_BCMAC131:
val = MAC_PHYCFG2_AC131_LED_MODES;
break;
case PHY_ID_RTL8211C:
val = MAC_PHYCFG2_RTL8211C_LED_MODES;
break;
case PHY_ID_RTL8201E:
val = MAC_PHYCFG2_RTL8201E_LED_MODES;
break;
default:
return;
}
if (phydev->interface != PHY_INTERFACE_MODE_RGMII) {
tw32(MAC_PHYCFG2, val);
val = tr32(MAC_PHYCFG1);
val &= ~(MAC_PHYCFG1_RGMII_INT |
MAC_PHYCFG1_RXCLK_TO_MASK | MAC_PHYCFG1_TXCLK_TO_MASK);
val |= MAC_PHYCFG1_RXCLK_TIMEOUT | MAC_PHYCFG1_TXCLK_TIMEOUT;
tw32(MAC_PHYCFG1, val);
return;
}
if (!tg3_flag(tp, RGMII_INBAND_DISABLE))
val |= MAC_PHYCFG2_EMODE_MASK_MASK |
MAC_PHYCFG2_FMODE_MASK_MASK |
MAC_PHYCFG2_GMODE_MASK_MASK |
MAC_PHYCFG2_ACT_MASK_MASK |
MAC_PHYCFG2_QUAL_MASK_MASK |
MAC_PHYCFG2_INBAND_ENABLE;
tw32(MAC_PHYCFG2, val);
val = tr32(MAC_PHYCFG1);
val &= ~(MAC_PHYCFG1_RXCLK_TO_MASK | MAC_PHYCFG1_TXCLK_TO_MASK |
MAC_PHYCFG1_RGMII_EXT_RX_DEC | MAC_PHYCFG1_RGMII_SND_STAT_EN);
if (!tg3_flag(tp, RGMII_INBAND_DISABLE)) {
if (tg3_flag(tp, RGMII_EXT_IBND_RX_EN))
val |= MAC_PHYCFG1_RGMII_EXT_RX_DEC;
if (tg3_flag(tp, RGMII_EXT_IBND_TX_EN))
val |= MAC_PHYCFG1_RGMII_SND_STAT_EN;
}
val |= MAC_PHYCFG1_RXCLK_TIMEOUT | MAC_PHYCFG1_TXCLK_TIMEOUT |
MAC_PHYCFG1_RGMII_INT | MAC_PHYCFG1_TXC_DRV;
tw32(MAC_PHYCFG1, val);
val = tr32(MAC_EXT_RGMII_MODE);
val &= ~(MAC_RGMII_MODE_RX_INT_B |
MAC_RGMII_MODE_RX_QUALITY |
MAC_RGMII_MODE_RX_ACTIVITY |
MAC_RGMII_MODE_RX_ENG_DET |
MAC_RGMII_MODE_TX_ENABLE |
MAC_RGMII_MODE_TX_LOWPWR |
MAC_RGMII_MODE_TX_RESET);
if (!tg3_flag(tp, RGMII_INBAND_DISABLE)) {
if (tg3_flag(tp, RGMII_EXT_IBND_RX_EN))
val |= MAC_RGMII_MODE_RX_INT_B |
MAC_RGMII_MODE_RX_QUALITY |
MAC_RGMII_MODE_RX_ACTIVITY |
MAC_RGMII_MODE_RX_ENG_DET;
if (tg3_flag(tp, RGMII_EXT_IBND_TX_EN))
val |= MAC_RGMII_MODE_TX_ENABLE |
MAC_RGMII_MODE_TX_LOWPWR |
MAC_RGMII_MODE_TX_RESET;
}
tw32(MAC_EXT_RGMII_MODE, val);
}
static void tg3_mdio_start(struct tg3 *tp)
{
tp->mi_mode &= ~MAC_MI_MODE_AUTO_POLL;
tw32_f(MAC_MI_MODE, tp->mi_mode);
udelay(80);
if (tg3_flag(tp, MDIOBUS_INITED) &&
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5785)
tg3_mdio_config_5785(tp);
}
static int tg3_mdio_init(struct tg3 *tp)
{
int i;
u32 reg;
struct phy_device *phydev;
if (tg3_flag(tp, 5717_PLUS)) {
u32 is_serdes;
tp->phy_addr = tp->pci_fn + 1;
if (tp->pci_chip_rev_id != CHIPREV_ID_5717_A0)
is_serdes = tr32(SG_DIG_STATUS) & SG_DIG_IS_SERDES;
else
is_serdes = tr32(TG3_CPMU_PHY_STRAP) &
TG3_CPMU_PHY_STRAP_IS_SERDES;
if (is_serdes)
tp->phy_addr += 7;
} else
tp->phy_addr = TG3_PHY_MII_ADDR;
tg3_mdio_start(tp);
if (!tg3_flag(tp, USE_PHYLIB) || tg3_flag(tp, MDIOBUS_INITED))
return 0;
tp->mdio_bus = mdiobus_alloc();
if (tp->mdio_bus == NULL)
return -ENOMEM;
tp->mdio_bus->name = "tg3 mdio bus";
snprintf(tp->mdio_bus->id, MII_BUS_ID_SIZE, "%x",
(tp->pdev->bus->number << 8) | tp->pdev->devfn);
tp->mdio_bus->priv = tp;
tp->mdio_bus->parent = &tp->pdev->dev;
tp->mdio_bus->read = &tg3_mdio_read;
tp->mdio_bus->write = &tg3_mdio_write;
tp->mdio_bus->reset = &tg3_mdio_reset;
tp->mdio_bus->phy_mask = ~(1 << TG3_PHY_MII_ADDR);
tp->mdio_bus->irq = &tp->mdio_irq[0];
for (i = 0; i < PHY_MAX_ADDR; i++)
tp->mdio_bus->irq[i] = PHY_POLL;
/* The bus registration will look for all the PHYs on the mdio bus.
* Unfortunately, it does not ensure the PHY is powered up before
* accessing the PHY ID registers. A chip reset is the
* quickest way to bring the device back to an operational state..
*/
if (tg3_readphy(tp, MII_BMCR, ®) || (reg & BMCR_PDOWN))
tg3_bmcr_reset(tp);
i = mdiobus_register(tp->mdio_bus);
if (i) {
dev_warn(&tp->pdev->dev, "mdiobus_reg failed (0x%x)\n", i);
mdiobus_free(tp->mdio_bus);
return i;
}
phydev = tp->mdio_bus->phy_map[TG3_PHY_MII_ADDR];
if (!phydev || !phydev->drv) {
dev_warn(&tp->pdev->dev, "No PHY devices\n");
mdiobus_unregister(tp->mdio_bus);
mdiobus_free(tp->mdio_bus);
return -ENODEV;
}
switch (phydev->drv->phy_id & phydev->drv->phy_id_mask) {
case PHY_ID_BCM57780:
phydev->interface = PHY_INTERFACE_MODE_GMII;
phydev->dev_flags |= PHY_BRCM_AUTO_PWRDWN_ENABLE;
break;
case PHY_ID_BCM50610:
case PHY_ID_BCM50610M:
phydev->dev_flags |= PHY_BRCM_CLEAR_RGMII_MODE |
PHY_BRCM_RX_REFCLK_UNUSED |
PHY_BRCM_DIS_TXCRXC_NOENRGY |
PHY_BRCM_AUTO_PWRDWN_ENABLE;
if (tg3_flag(tp, RGMII_INBAND_DISABLE))
phydev->dev_flags |= PHY_BRCM_STD_IBND_DISABLE;
if (tg3_flag(tp, RGMII_EXT_IBND_RX_EN))
phydev->dev_flags |= PHY_BRCM_EXT_IBND_RX_ENABLE;
if (tg3_flag(tp, RGMII_EXT_IBND_TX_EN))
phydev->dev_flags |= PHY_BRCM_EXT_IBND_TX_ENABLE;
/* fallthru */
case PHY_ID_RTL8211C:
phydev->interface = PHY_INTERFACE_MODE_RGMII;
break;
case PHY_ID_RTL8201E:
case PHY_ID_BCMAC131:
phydev->interface = PHY_INTERFACE_MODE_MII;
phydev->dev_flags |= PHY_BRCM_AUTO_PWRDWN_ENABLE;
tp->phy_flags |= TG3_PHYFLG_IS_FET;
break;
}
tg3_flag_set(tp, MDIOBUS_INITED);
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5785)
tg3_mdio_config_5785(tp);
return 0;
}
static void tg3_mdio_fini(struct tg3 *tp)
{
if (tg3_flag(tp, MDIOBUS_INITED)) {
tg3_flag_clear(tp, MDIOBUS_INITED);
mdiobus_unregister(tp->mdio_bus);
mdiobus_free(tp->mdio_bus);
}
}
/* tp->lock is held. */
static inline void tg3_generate_fw_event(struct tg3 *tp)
{
u32 val;
val = tr32(GRC_RX_CPU_EVENT);
val |= GRC_RX_CPU_DRIVER_EVENT;
tw32_f(GRC_RX_CPU_EVENT, val);
tp->last_event_jiffies = jiffies;
}
#define TG3_FW_EVENT_TIMEOUT_USEC 2500
/* tp->lock is held. */
static void tg3_wait_for_event_ack(struct tg3 *tp)
{
int i;
unsigned int delay_cnt;
long time_remain;
/* If enough time has passed, no wait is necessary. */
time_remain = (long)(tp->last_event_jiffies + 1 +
usecs_to_jiffies(TG3_FW_EVENT_TIMEOUT_USEC)) -
(long)jiffies;
if (time_remain < 0)
return;
/* Check if we can shorten the wait time. */
delay_cnt = jiffies_to_usecs(time_remain);
if (delay_cnt > TG3_FW_EVENT_TIMEOUT_USEC)
delay_cnt = TG3_FW_EVENT_TIMEOUT_USEC;
delay_cnt = (delay_cnt >> 3) + 1;
for (i = 0; i < delay_cnt; i++) {
if (!(tr32(GRC_RX_CPU_EVENT) & GRC_RX_CPU_DRIVER_EVENT))
break;
udelay(8);
}
}
/* tp->lock is held. */
static void tg3_phy_gather_ump_data(struct tg3 *tp, u32 *data)
{
u32 reg, val;
val = 0;
if (!tg3_readphy(tp, MII_BMCR, ®))
val = reg << 16;
if (!tg3_readphy(tp, MII_BMSR, ®))
val |= (reg & 0xffff);
*data++ = val;
val = 0;
if (!tg3_readphy(tp, MII_ADVERTISE, ®))
val = reg << 16;
if (!tg3_readphy(tp, MII_LPA, ®))
val |= (reg & 0xffff);
*data++ = val;
val = 0;
if (!(tp->phy_flags & TG3_PHYFLG_MII_SERDES)) {
if (!tg3_readphy(tp, MII_CTRL1000, ®))
val = reg << 16;
if (!tg3_readphy(tp, MII_STAT1000, ®))
val |= (reg & 0xffff);
}
*data++ = val;
if (!tg3_readphy(tp, MII_PHYADDR, ®))
val = reg << 16;
else
val = 0;
*data++ = val;
}
/* tp->lock is held. */
static void tg3_ump_link_report(struct tg3 *tp)
{
u32 data[4];
if (!tg3_flag(tp, 5780_CLASS) || !tg3_flag(tp, ENABLE_ASF))
return;
tg3_phy_gather_ump_data(tp, data);
tg3_wait_for_event_ack(tp);
tg3_write_mem(tp, NIC_SRAM_FW_CMD_MBOX, FWCMD_NICDRV_LINK_UPDATE);
tg3_write_mem(tp, NIC_SRAM_FW_CMD_LEN_MBOX, 14);
tg3_write_mem(tp, NIC_SRAM_FW_CMD_DATA_MBOX + 0x0, data[0]);
tg3_write_mem(tp, NIC_SRAM_FW_CMD_DATA_MBOX + 0x4, data[1]);
tg3_write_mem(tp, NIC_SRAM_FW_CMD_DATA_MBOX + 0x8, data[2]);
tg3_write_mem(tp, NIC_SRAM_FW_CMD_DATA_MBOX + 0xc, data[3]);
tg3_generate_fw_event(tp);
}
/* tp->lock is held. */
static void tg3_stop_fw(struct tg3 *tp)
{
if (tg3_flag(tp, ENABLE_ASF) && !tg3_flag(tp, ENABLE_APE)) {
/* Wait for RX cpu to ACK the previous event. */
tg3_wait_for_event_ack(tp);
tg3_write_mem(tp, NIC_SRAM_FW_CMD_MBOX, FWCMD_NICDRV_PAUSE_FW);
tg3_generate_fw_event(tp);
/* Wait for RX cpu to ACK this event. */
tg3_wait_for_event_ack(tp);
}
}
/* tp->lock is held. */
static void tg3_write_sig_pre_reset(struct tg3 *tp, int kind)
{
tg3_write_mem(tp, NIC_SRAM_FIRMWARE_MBOX,
NIC_SRAM_FIRMWARE_MBOX_MAGIC1);
if (tg3_flag(tp, ASF_NEW_HANDSHAKE)) {
switch (kind) {
case RESET_KIND_INIT:
tg3_write_mem(tp, NIC_SRAM_FW_DRV_STATE_MBOX,
DRV_STATE_START);
break;
case RESET_KIND_SHUTDOWN:
tg3_write_mem(tp, NIC_SRAM_FW_DRV_STATE_MBOX,
DRV_STATE_UNLOAD);
break;
case RESET_KIND_SUSPEND:
tg3_write_mem(tp, NIC_SRAM_FW_DRV_STATE_MBOX,
DRV_STATE_SUSPEND);
break;
default:
break;
}
}
if (kind == RESET_KIND_INIT ||
kind == RESET_KIND_SUSPEND)
tg3_ape_driver_state_change(tp, kind);
}
/* tp->lock is held. */
static void tg3_write_sig_post_reset(struct tg3 *tp, int kind)
{
if (tg3_flag(tp, ASF_NEW_HANDSHAKE)) {
switch (kind) {
case RESET_KIND_INIT:
tg3_write_mem(tp, NIC_SRAM_FW_DRV_STATE_MBOX,
DRV_STATE_START_DONE);
break;
case RESET_KIND_SHUTDOWN:
tg3_write_mem(tp, NIC_SRAM_FW_DRV_STATE_MBOX,
DRV_STATE_UNLOAD_DONE);
break;
default:
break;
}
}
if (kind == RESET_KIND_SHUTDOWN)
tg3_ape_driver_state_change(tp, kind);
}
/* tp->lock is held. */
static void tg3_write_sig_legacy(struct tg3 *tp, int kind)
{
if (tg3_flag(tp, ENABLE_ASF)) {
switch (kind) {
case RESET_KIND_INIT:
tg3_write_mem(tp, NIC_SRAM_FW_DRV_STATE_MBOX,
DRV_STATE_START);
break;
case RESET_KIND_SHUTDOWN:
tg3_write_mem(tp, NIC_SRAM_FW_DRV_STATE_MBOX,
DRV_STATE_UNLOAD);
break;
case RESET_KIND_SUSPEND:
tg3_write_mem(tp, NIC_SRAM_FW_DRV_STATE_MBOX,
DRV_STATE_SUSPEND);
break;
default:
break;
}
}
}
static int tg3_poll_fw(struct tg3 *tp)
{
int i;
u32 val;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5906) {
/* Wait up to 20ms for init done. */
for (i = 0; i < 200; i++) {
if (tr32(VCPU_STATUS) & VCPU_STATUS_INIT_DONE)
return 0;
udelay(100);
}
return -ENODEV;
}
/* Wait for firmware initialization to complete. */
for (i = 0; i < 100000; i++) {
tg3_read_mem(tp, NIC_SRAM_FIRMWARE_MBOX, &val);
if (val == ~NIC_SRAM_FIRMWARE_MBOX_MAGIC1)
break;
udelay(10);
}
/* Chip might not be fitted with firmware. Some Sun onboard
* parts are configured like that. So don't signal the timeout
* of the above loop as an error, but do report the lack of
* running firmware once.
*/
if (i >= 100000 && !tg3_flag(tp, NO_FWARE_REPORTED)) {
tg3_flag_set(tp, NO_FWARE_REPORTED);
netdev_info(tp->dev, "No firmware running\n");
}
if (tp->pci_chip_rev_id == CHIPREV_ID_57765_A0) {
/* The 57765 A0 needs a little more
* time to do some important work.
*/
mdelay(10);
}
return 0;
}
static void tg3_link_report(struct tg3 *tp)
{
if (!netif_carrier_ok(tp->dev)) {
netif_info(tp, link, tp->dev, "Link is down\n");
tg3_ump_link_report(tp);
} else if (netif_msg_link(tp)) {
netdev_info(tp->dev, "Link is up at %d Mbps, %s duplex\n",
(tp->link_config.active_speed == SPEED_1000 ?
1000 :
(tp->link_config.active_speed == SPEED_100 ?
100 : 10)),
(tp->link_config.active_duplex == DUPLEX_FULL ?
"full" : "half"));
netdev_info(tp->dev, "Flow control is %s for TX and %s for RX\n",
(tp->link_config.active_flowctrl & FLOW_CTRL_TX) ?
"on" : "off",
(tp->link_config.active_flowctrl & FLOW_CTRL_RX) ?
"on" : "off");
if (tp->phy_flags & TG3_PHYFLG_EEE_CAP)
netdev_info(tp->dev, "EEE is %s\n",
tp->setlpicnt ? "enabled" : "disabled");
tg3_ump_link_report(tp);
}
}
static u16 tg3_advert_flowctrl_1000X(u8 flow_ctrl)
{
u16 miireg;
if ((flow_ctrl & FLOW_CTRL_TX) && (flow_ctrl & FLOW_CTRL_RX))
miireg = ADVERTISE_1000XPAUSE;
else if (flow_ctrl & FLOW_CTRL_TX)
miireg = ADVERTISE_1000XPSE_ASYM;
else if (flow_ctrl & FLOW_CTRL_RX)
miireg = ADVERTISE_1000XPAUSE | ADVERTISE_1000XPSE_ASYM;
else
miireg = 0;
return miireg;
}
static u8 tg3_resolve_flowctrl_1000X(u16 lcladv, u16 rmtadv)
{
u8 cap = 0;
if (lcladv & rmtadv & ADVERTISE_1000XPAUSE) {
cap = FLOW_CTRL_TX | FLOW_CTRL_RX;
} else if (lcladv & rmtadv & ADVERTISE_1000XPSE_ASYM) {
if (lcladv & ADVERTISE_1000XPAUSE)
cap = FLOW_CTRL_RX;
if (rmtadv & ADVERTISE_1000XPAUSE)
cap = FLOW_CTRL_TX;
}
return cap;
}
static void tg3_setup_flow_control(struct tg3 *tp, u32 lcladv, u32 rmtadv)
{
u8 autoneg;
u8 flowctrl = 0;
u32 old_rx_mode = tp->rx_mode;
u32 old_tx_mode = tp->tx_mode;
if (tg3_flag(tp, USE_PHYLIB))
autoneg = tp->mdio_bus->phy_map[TG3_PHY_MII_ADDR]->autoneg;
else
autoneg = tp->link_config.autoneg;
if (autoneg == AUTONEG_ENABLE && tg3_flag(tp, PAUSE_AUTONEG)) {
if (tp->phy_flags & TG3_PHYFLG_ANY_SERDES)
flowctrl = tg3_resolve_flowctrl_1000X(lcladv, rmtadv);
else
flowctrl = mii_resolve_flowctrl_fdx(lcladv, rmtadv);
} else
flowctrl = tp->link_config.flowctrl;
tp->link_config.active_flowctrl = flowctrl;
if (flowctrl & FLOW_CTRL_RX)
tp->rx_mode |= RX_MODE_FLOW_CTRL_ENABLE;
else
tp->rx_mode &= ~RX_MODE_FLOW_CTRL_ENABLE;
if (old_rx_mode != tp->rx_mode)
tw32_f(MAC_RX_MODE, tp->rx_mode);
if (flowctrl & FLOW_CTRL_TX)
tp->tx_mode |= TX_MODE_FLOW_CTRL_ENABLE;
else
tp->tx_mode &= ~TX_MODE_FLOW_CTRL_ENABLE;
if (old_tx_mode != tp->tx_mode)
tw32_f(MAC_TX_MODE, tp->tx_mode);
}
static void tg3_adjust_link(struct net_device *dev)
{
u8 oldflowctrl, linkmesg = 0;
u32 mac_mode, lcl_adv, rmt_adv;
struct tg3 *tp = netdev_priv(dev);
struct phy_device *phydev = tp->mdio_bus->phy_map[TG3_PHY_MII_ADDR];
spin_lock_bh(&tp->lock);
mac_mode = tp->mac_mode & ~(MAC_MODE_PORT_MODE_MASK |
MAC_MODE_HALF_DUPLEX);
oldflowctrl = tp->link_config.active_flowctrl;
if (phydev->link) {
lcl_adv = 0;
rmt_adv = 0;
if (phydev->speed == SPEED_100 || phydev->speed == SPEED_10)
mac_mode |= MAC_MODE_PORT_MODE_MII;
else if (phydev->speed == SPEED_1000 ||
GET_ASIC_REV(tp->pci_chip_rev_id) != ASIC_REV_5785)
mac_mode |= MAC_MODE_PORT_MODE_GMII;
else
mac_mode |= MAC_MODE_PORT_MODE_MII;
if (phydev->duplex == DUPLEX_HALF)
mac_mode |= MAC_MODE_HALF_DUPLEX;
else {
lcl_adv = mii_advertise_flowctrl(
tp->link_config.flowctrl);
if (phydev->pause)
rmt_adv = LPA_PAUSE_CAP;
if (phydev->asym_pause)
rmt_adv |= LPA_PAUSE_ASYM;
}
tg3_setup_flow_control(tp, lcl_adv, rmt_adv);
} else
mac_mode |= MAC_MODE_PORT_MODE_GMII;
if (mac_mode != tp->mac_mode) {
tp->mac_mode = mac_mode;
tw32_f(MAC_MODE, tp->mac_mode);
udelay(40);
}
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5785) {
if (phydev->speed == SPEED_10)
tw32(MAC_MI_STAT,
MAC_MI_STAT_10MBPS_MODE |
MAC_MI_STAT_LNKSTAT_ATTN_ENAB);
else
tw32(MAC_MI_STAT, MAC_MI_STAT_LNKSTAT_ATTN_ENAB);
}
if (phydev->speed == SPEED_1000 && phydev->duplex == DUPLEX_HALF)
tw32(MAC_TX_LENGTHS,
((2 << TX_LENGTHS_IPG_CRS_SHIFT) |
(6 << TX_LENGTHS_IPG_SHIFT) |
(0xff << TX_LENGTHS_SLOT_TIME_SHIFT)));
else
tw32(MAC_TX_LENGTHS,
((2 << TX_LENGTHS_IPG_CRS_SHIFT) |
(6 << TX_LENGTHS_IPG_SHIFT) |
(32 << TX_LENGTHS_SLOT_TIME_SHIFT)));
if (phydev->link != tp->old_link ||
phydev->speed != tp->link_config.active_speed ||
phydev->duplex != tp->link_config.active_duplex ||
oldflowctrl != tp->link_config.active_flowctrl)
linkmesg = 1;
tp->old_link = phydev->link;
tp->link_config.active_speed = phydev->speed;
tp->link_config.active_duplex = phydev->duplex;
spin_unlock_bh(&tp->lock);
if (linkmesg)
tg3_link_report(tp);
}
static int tg3_phy_init(struct tg3 *tp)
{
struct phy_device *phydev;
if (tp->phy_flags & TG3_PHYFLG_IS_CONNECTED)
return 0;
/* Bring the PHY back to a known state. */
tg3_bmcr_reset(tp);
phydev = tp->mdio_bus->phy_map[TG3_PHY_MII_ADDR];
/* Attach the MAC to the PHY. */
phydev = phy_connect(tp->dev, dev_name(&phydev->dev), tg3_adjust_link,
phydev->dev_flags, phydev->interface);
if (IS_ERR(phydev)) {
dev_err(&tp->pdev->dev, "Could not attach to PHY\n");
return PTR_ERR(phydev);
}
/* Mask with MAC supported features. */
switch (phydev->interface) {
case PHY_INTERFACE_MODE_GMII:
case PHY_INTERFACE_MODE_RGMII:
if (!(tp->phy_flags & TG3_PHYFLG_10_100_ONLY)) {
phydev->supported &= (PHY_GBIT_FEATURES |
SUPPORTED_Pause |
SUPPORTED_Asym_Pause);
break;
}
/* fallthru */
case PHY_INTERFACE_MODE_MII:
phydev->supported &= (PHY_BASIC_FEATURES |
SUPPORTED_Pause |
SUPPORTED_Asym_Pause);
break;
default:
phy_disconnect(tp->mdio_bus->phy_map[TG3_PHY_MII_ADDR]);
return -EINVAL;
}
tp->phy_flags |= TG3_PHYFLG_IS_CONNECTED;
phydev->advertising = phydev->supported;
return 0;
}
static void tg3_phy_start(struct tg3 *tp)
{
struct phy_device *phydev;
if (!(tp->phy_flags & TG3_PHYFLG_IS_CONNECTED))
return;
phydev = tp->mdio_bus->phy_map[TG3_PHY_MII_ADDR];
if (tp->phy_flags & TG3_PHYFLG_IS_LOW_POWER) {
tp->phy_flags &= ~TG3_PHYFLG_IS_LOW_POWER;
phydev->speed = tp->link_config.speed;
phydev->duplex = tp->link_config.duplex;
phydev->autoneg = tp->link_config.autoneg;
phydev->advertising = tp->link_config.advertising;
}
phy_start(phydev);
phy_start_aneg(phydev);
}
static void tg3_phy_stop(struct tg3 *tp)
{
if (!(tp->phy_flags & TG3_PHYFLG_IS_CONNECTED))
return;
phy_stop(tp->mdio_bus->phy_map[TG3_PHY_MII_ADDR]);
}
static void tg3_phy_fini(struct tg3 *tp)
{
if (tp->phy_flags & TG3_PHYFLG_IS_CONNECTED) {
phy_disconnect(tp->mdio_bus->phy_map[TG3_PHY_MII_ADDR]);
tp->phy_flags &= ~TG3_PHYFLG_IS_CONNECTED;
}
}
static int tg3_phy_set_extloopbk(struct tg3 *tp)
{
int err;
u32 val;
if (tp->phy_flags & TG3_PHYFLG_IS_FET)
return 0;
if ((tp->phy_id & TG3_PHY_ID_MASK) == TG3_PHY_ID_BCM5401) {
/* Cannot do read-modify-write on 5401 */
err = tg3_phy_auxctl_write(tp,
MII_TG3_AUXCTL_SHDWSEL_AUXCTL,
MII_TG3_AUXCTL_ACTL_EXTLOOPBK |
0x4c20);
goto done;
}
err = tg3_phy_auxctl_read(tp,
MII_TG3_AUXCTL_SHDWSEL_AUXCTL, &val);
if (err)
return err;
val |= MII_TG3_AUXCTL_ACTL_EXTLOOPBK;
err = tg3_phy_auxctl_write(tp,
MII_TG3_AUXCTL_SHDWSEL_AUXCTL, val);
done:
return err;
}
static void tg3_phy_fet_toggle_apd(struct tg3 *tp, bool enable)
{
u32 phytest;
if (!tg3_readphy(tp, MII_TG3_FET_TEST, &phytest)) {
u32 phy;
tg3_writephy(tp, MII_TG3_FET_TEST,
phytest | MII_TG3_FET_SHADOW_EN);
if (!tg3_readphy(tp, MII_TG3_FET_SHDW_AUXSTAT2, &phy)) {
if (enable)
phy |= MII_TG3_FET_SHDW_AUXSTAT2_APD;
else
phy &= ~MII_TG3_FET_SHDW_AUXSTAT2_APD;
tg3_writephy(tp, MII_TG3_FET_SHDW_AUXSTAT2, phy);
}
tg3_writephy(tp, MII_TG3_FET_TEST, phytest);
}
}
static void tg3_phy_toggle_apd(struct tg3 *tp, bool enable)
{
u32 reg;
if (!tg3_flag(tp, 5705_PLUS) ||
(tg3_flag(tp, 5717_PLUS) &&
(tp->phy_flags & TG3_PHYFLG_MII_SERDES)))
return;
if (tp->phy_flags & TG3_PHYFLG_IS_FET) {
tg3_phy_fet_toggle_apd(tp, enable);
return;
}
reg = MII_TG3_MISC_SHDW_WREN |
MII_TG3_MISC_SHDW_SCR5_SEL |
MII_TG3_MISC_SHDW_SCR5_LPED |
MII_TG3_MISC_SHDW_SCR5_DLPTLM |
MII_TG3_MISC_SHDW_SCR5_SDTL |
MII_TG3_MISC_SHDW_SCR5_C125OE;
if (GET_ASIC_REV(tp->pci_chip_rev_id) != ASIC_REV_5784 || !enable)
reg |= MII_TG3_MISC_SHDW_SCR5_DLLAPD;
tg3_writephy(tp, MII_TG3_MISC_SHDW, reg);
reg = MII_TG3_MISC_SHDW_WREN |
MII_TG3_MISC_SHDW_APD_SEL |
MII_TG3_MISC_SHDW_APD_WKTM_84MS;
if (enable)
reg |= MII_TG3_MISC_SHDW_APD_ENABLE;
tg3_writephy(tp, MII_TG3_MISC_SHDW, reg);
}
static void tg3_phy_toggle_automdix(struct tg3 *tp, int enable)
{
u32 phy;
if (!tg3_flag(tp, 5705_PLUS) ||
(tp->phy_flags & TG3_PHYFLG_ANY_SERDES))
return;
if (tp->phy_flags & TG3_PHYFLG_IS_FET) {
u32 ephy;
if (!tg3_readphy(tp, MII_TG3_FET_TEST, &ephy)) {
u32 reg = MII_TG3_FET_SHDW_MISCCTRL;
tg3_writephy(tp, MII_TG3_FET_TEST,
ephy | MII_TG3_FET_SHADOW_EN);
if (!tg3_readphy(tp, reg, &phy)) {
if (enable)
phy |= MII_TG3_FET_SHDW_MISCCTRL_MDIX;
else
phy &= ~MII_TG3_FET_SHDW_MISCCTRL_MDIX;
tg3_writephy(tp, reg, phy);
}
tg3_writephy(tp, MII_TG3_FET_TEST, ephy);
}
} else {
int ret;
ret = tg3_phy_auxctl_read(tp,
MII_TG3_AUXCTL_SHDWSEL_MISC, &phy);
if (!ret) {
if (enable)
phy |= MII_TG3_AUXCTL_MISC_FORCE_AMDIX;
else
phy &= ~MII_TG3_AUXCTL_MISC_FORCE_AMDIX;
tg3_phy_auxctl_write(tp,
MII_TG3_AUXCTL_SHDWSEL_MISC, phy);
}
}
}
static void tg3_phy_set_wirespeed(struct tg3 *tp)
{
int ret;
u32 val;
if (tp->phy_flags & TG3_PHYFLG_NO_ETH_WIRE_SPEED)
return;
ret = tg3_phy_auxctl_read(tp, MII_TG3_AUXCTL_SHDWSEL_MISC, &val);
if (!ret)
tg3_phy_auxctl_write(tp, MII_TG3_AUXCTL_SHDWSEL_MISC,
val | MII_TG3_AUXCTL_MISC_WIRESPD_EN);
}
static void tg3_phy_apply_otp(struct tg3 *tp)
{
u32 otp, phy;
if (!tp->phy_otp)
return;
otp = tp->phy_otp;
if (TG3_PHY_AUXCTL_SMDSP_ENABLE(tp))
return;
phy = ((otp & TG3_OTP_AGCTGT_MASK) >> TG3_OTP_AGCTGT_SHIFT);
phy |= MII_TG3_DSP_TAP1_AGCTGT_DFLT;
tg3_phydsp_write(tp, MII_TG3_DSP_TAP1, phy);
phy = ((otp & TG3_OTP_HPFFLTR_MASK) >> TG3_OTP_HPFFLTR_SHIFT) |
((otp & TG3_OTP_HPFOVER_MASK) >> TG3_OTP_HPFOVER_SHIFT);
tg3_phydsp_write(tp, MII_TG3_DSP_AADJ1CH0, phy);
phy = ((otp & TG3_OTP_LPFDIS_MASK) >> TG3_OTP_LPFDIS_SHIFT);
phy |= MII_TG3_DSP_AADJ1CH3_ADCCKADJ;
tg3_phydsp_write(tp, MII_TG3_DSP_AADJ1CH3, phy);
phy = ((otp & TG3_OTP_VDAC_MASK) >> TG3_OTP_VDAC_SHIFT);
tg3_phydsp_write(tp, MII_TG3_DSP_EXP75, phy);
phy = ((otp & TG3_OTP_10BTAMP_MASK) >> TG3_OTP_10BTAMP_SHIFT);
tg3_phydsp_write(tp, MII_TG3_DSP_EXP96, phy);
phy = ((otp & TG3_OTP_ROFF_MASK) >> TG3_OTP_ROFF_SHIFT) |
((otp & TG3_OTP_RCOFF_MASK) >> TG3_OTP_RCOFF_SHIFT);
tg3_phydsp_write(tp, MII_TG3_DSP_EXP97, phy);
TG3_PHY_AUXCTL_SMDSP_DISABLE(tp);
}
static void tg3_phy_eee_adjust(struct tg3 *tp, u32 current_link_up)
{
u32 val;
if (!(tp->phy_flags & TG3_PHYFLG_EEE_CAP))
return;
tp->setlpicnt = 0;
if (tp->link_config.autoneg == AUTONEG_ENABLE &&
current_link_up == 1 &&
tp->link_config.active_duplex == DUPLEX_FULL &&
(tp->link_config.active_speed == SPEED_100 ||
tp->link_config.active_speed == SPEED_1000)) {
u32 eeectl;
if (tp->link_config.active_speed == SPEED_1000)
eeectl = TG3_CPMU_EEE_CTRL_EXIT_16_5_US;
else
eeectl = TG3_CPMU_EEE_CTRL_EXIT_36_US;
tw32(TG3_CPMU_EEE_CTRL, eeectl);
tg3_phy_cl45_read(tp, MDIO_MMD_AN,
TG3_CL45_D7_EEERES_STAT, &val);
if (val == TG3_CL45_D7_EEERES_STAT_LP_1000T ||
val == TG3_CL45_D7_EEERES_STAT_LP_100TX)
tp->setlpicnt = 2;
}
if (!tp->setlpicnt) {
if (current_link_up == 1 &&
!TG3_PHY_AUXCTL_SMDSP_ENABLE(tp)) {
tg3_phydsp_write(tp, MII_TG3_DSP_TAP26, 0x0000);
TG3_PHY_AUXCTL_SMDSP_DISABLE(tp);
}
val = tr32(TG3_CPMU_EEE_MODE);
tw32(TG3_CPMU_EEE_MODE, val & ~TG3_CPMU_EEEMD_LPI_ENABLE);
}
}
static void tg3_phy_eee_enable(struct tg3 *tp)
{
u32 val;
if (tp->link_config.active_speed == SPEED_1000 &&
(GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5717 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5719 ||
tg3_flag(tp, 57765_CLASS)) &&
!TG3_PHY_AUXCTL_SMDSP_ENABLE(tp)) {
val = MII_TG3_DSP_TAP26_ALNOKO |
MII_TG3_DSP_TAP26_RMRXSTO;
tg3_phydsp_write(tp, MII_TG3_DSP_TAP26, val);
TG3_PHY_AUXCTL_SMDSP_DISABLE(tp);
}
val = tr32(TG3_CPMU_EEE_MODE);
tw32(TG3_CPMU_EEE_MODE, val | TG3_CPMU_EEEMD_LPI_ENABLE);
}
static int tg3_wait_macro_done(struct tg3 *tp)
{
int limit = 100;
while (limit--) {
u32 tmp32;
if (!tg3_readphy(tp, MII_TG3_DSP_CONTROL, &tmp32)) {
if ((tmp32 & 0x1000) == 0)
break;
}
}
if (limit < 0)
return -EBUSY;
return 0;
}
static int tg3_phy_write_and_check_testpat(struct tg3 *tp, int *resetp)
{
static const u32 test_pat[4][6] = {
{ 0x00005555, 0x00000005, 0x00002aaa, 0x0000000a, 0x00003456, 0x00000003 },
{ 0x00002aaa, 0x0000000a, 0x00003333, 0x00000003, 0x0000789a, 0x00000005 },
{ 0x00005a5a, 0x00000005, 0x00002a6a, 0x0000000a, 0x00001bcd, 0x00000003 },
{ 0x00002a5a, 0x0000000a, 0x000033c3, 0x00000003, 0x00002ef1, 0x00000005 }
};
int chan;
for (chan = 0; chan < 4; chan++) {
int i;
tg3_writephy(tp, MII_TG3_DSP_ADDRESS,
(chan * 0x2000) | 0x0200);
tg3_writephy(tp, MII_TG3_DSP_CONTROL, 0x0002);
for (i = 0; i < 6; i++)
tg3_writephy(tp, MII_TG3_DSP_RW_PORT,
test_pat[chan][i]);
tg3_writephy(tp, MII_TG3_DSP_CONTROL, 0x0202);
if (tg3_wait_macro_done(tp)) {
*resetp = 1;
return -EBUSY;
}
tg3_writephy(tp, MII_TG3_DSP_ADDRESS,
(chan * 0x2000) | 0x0200);
tg3_writephy(tp, MII_TG3_DSP_CONTROL, 0x0082);
if (tg3_wait_macro_done(tp)) {
*resetp = 1;
return -EBUSY;
}
tg3_writephy(tp, MII_TG3_DSP_CONTROL, 0x0802);
if (tg3_wait_macro_done(tp)) {
*resetp = 1;
return -EBUSY;
}
for (i = 0; i < 6; i += 2) {
u32 low, high;
if (tg3_readphy(tp, MII_TG3_DSP_RW_PORT, &low) ||
tg3_readphy(tp, MII_TG3_DSP_RW_PORT, &high) ||
tg3_wait_macro_done(tp)) {
*resetp = 1;
return -EBUSY;
}
low &= 0x7fff;
high &= 0x000f;
if (low != test_pat[chan][i] ||
high != test_pat[chan][i+1]) {
tg3_writephy(tp, MII_TG3_DSP_ADDRESS, 0x000b);
tg3_writephy(tp, MII_TG3_DSP_RW_PORT, 0x4001);
tg3_writephy(tp, MII_TG3_DSP_RW_PORT, 0x4005);
return -EBUSY;
}
}
}
return 0;
}
static int tg3_phy_reset_chanpat(struct tg3 *tp)
{
int chan;
for (chan = 0; chan < 4; chan++) {
int i;
tg3_writephy(tp, MII_TG3_DSP_ADDRESS,
(chan * 0x2000) | 0x0200);
tg3_writephy(tp, MII_TG3_DSP_CONTROL, 0x0002);
for (i = 0; i < 6; i++)
tg3_writephy(tp, MII_TG3_DSP_RW_PORT, 0x000);
tg3_writephy(tp, MII_TG3_DSP_CONTROL, 0x0202);
if (tg3_wait_macro_done(tp))
return -EBUSY;
}
return 0;
}
static int tg3_phy_reset_5703_4_5(struct tg3 *tp)
{
u32 reg32, phy9_orig;
int retries, do_phy_reset, err;
retries = 10;
do_phy_reset = 1;
do {
if (do_phy_reset) {
err = tg3_bmcr_reset(tp);
if (err)
return err;
do_phy_reset = 0;
}
/* Disable transmitter and interrupt. */
if (tg3_readphy(tp, MII_TG3_EXT_CTRL, ®32))
continue;
reg32 |= 0x3000;
tg3_writephy(tp, MII_TG3_EXT_CTRL, reg32);
/* Set full-duplex, 1000 mbps. */
tg3_writephy(tp, MII_BMCR,
BMCR_FULLDPLX | BMCR_SPEED1000);
/* Set to master mode. */
if (tg3_readphy(tp, MII_CTRL1000, &phy9_orig))
continue;
tg3_writephy(tp, MII_CTRL1000,
CTL1000_AS_MASTER | CTL1000_ENABLE_MASTER);
err = TG3_PHY_AUXCTL_SMDSP_ENABLE(tp);
if (err)
return err;
/* Block the PHY control access. */
tg3_phydsp_write(tp, 0x8005, 0x0800);
err = tg3_phy_write_and_check_testpat(tp, &do_phy_reset);
if (!err)
break;
} while (--retries);
err = tg3_phy_reset_chanpat(tp);
if (err)
return err;
tg3_phydsp_write(tp, 0x8005, 0x0000);
tg3_writephy(tp, MII_TG3_DSP_ADDRESS, 0x8200);
tg3_writephy(tp, MII_TG3_DSP_CONTROL, 0x0000);
TG3_PHY_AUXCTL_SMDSP_DISABLE(tp);
tg3_writephy(tp, MII_CTRL1000, phy9_orig);
if (!tg3_readphy(tp, MII_TG3_EXT_CTRL, ®32)) {
reg32 &= ~0x3000;
tg3_writephy(tp, MII_TG3_EXT_CTRL, reg32);
} else if (!err)
err = -EBUSY;
return err;
}
/* This will reset the tigon3 PHY if there is no valid
* link unless the FORCE argument is non-zero.
*/
static int tg3_phy_reset(struct tg3 *tp)
{
u32 val, cpmuctrl;
int err;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5906) {
val = tr32(GRC_MISC_CFG);
tw32_f(GRC_MISC_CFG, val & ~GRC_MISC_CFG_EPHY_IDDQ);
udelay(40);
}
err = tg3_readphy(tp, MII_BMSR, &val);
err |= tg3_readphy(tp, MII_BMSR, &val);
if (err != 0)
return -EBUSY;
if (netif_running(tp->dev) && netif_carrier_ok(tp->dev)) {
netif_carrier_off(tp->dev);
tg3_link_report(tp);
}
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5703 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5704 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5705) {
err = tg3_phy_reset_5703_4_5(tp);
if (err)
return err;
goto out;
}
cpmuctrl = 0;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5784 &&
GET_CHIP_REV(tp->pci_chip_rev_id) != CHIPREV_5784_AX) {
cpmuctrl = tr32(TG3_CPMU_CTRL);
if (cpmuctrl & CPMU_CTRL_GPHY_10MB_RXONLY)
tw32(TG3_CPMU_CTRL,
cpmuctrl & ~CPMU_CTRL_GPHY_10MB_RXONLY);
}
err = tg3_bmcr_reset(tp);
if (err)
return err;
if (cpmuctrl & CPMU_CTRL_GPHY_10MB_RXONLY) {
val = MII_TG3_DSP_EXP8_AEDW | MII_TG3_DSP_EXP8_REJ2MHz;
tg3_phydsp_write(tp, MII_TG3_DSP_EXP8, val);
tw32(TG3_CPMU_CTRL, cpmuctrl);
}
if (GET_CHIP_REV(tp->pci_chip_rev_id) == CHIPREV_5784_AX ||
GET_CHIP_REV(tp->pci_chip_rev_id) == CHIPREV_5761_AX) {
val = tr32(TG3_CPMU_LSPD_1000MB_CLK);
if ((val & CPMU_LSPD_1000MB_MACCLK_MASK) ==
CPMU_LSPD_1000MB_MACCLK_12_5) {
val &= ~CPMU_LSPD_1000MB_MACCLK_MASK;
udelay(40);
tw32_f(TG3_CPMU_LSPD_1000MB_CLK, val);
}
}
if (tg3_flag(tp, 5717_PLUS) &&
(tp->phy_flags & TG3_PHYFLG_MII_SERDES))
return 0;
tg3_phy_apply_otp(tp);
if (tp->phy_flags & TG3_PHYFLG_ENABLE_APD)
tg3_phy_toggle_apd(tp, true);
else
tg3_phy_toggle_apd(tp, false);
out:
if ((tp->phy_flags & TG3_PHYFLG_ADC_BUG) &&
!TG3_PHY_AUXCTL_SMDSP_ENABLE(tp)) {
tg3_phydsp_write(tp, 0x201f, 0x2aaa);
tg3_phydsp_write(tp, 0x000a, 0x0323);
TG3_PHY_AUXCTL_SMDSP_DISABLE(tp);
}
if (tp->phy_flags & TG3_PHYFLG_5704_A0_BUG) {
tg3_writephy(tp, MII_TG3_MISC_SHDW, 0x8d68);
tg3_writephy(tp, MII_TG3_MISC_SHDW, 0x8d68);
}
if (tp->phy_flags & TG3_PHYFLG_BER_BUG) {
if (!TG3_PHY_AUXCTL_SMDSP_ENABLE(tp)) {
tg3_phydsp_write(tp, 0x000a, 0x310b);
tg3_phydsp_write(tp, 0x201f, 0x9506);
tg3_phydsp_write(tp, 0x401f, 0x14e2);
TG3_PHY_AUXCTL_SMDSP_DISABLE(tp);
}
} else if (tp->phy_flags & TG3_PHYFLG_JITTER_BUG) {
if (!TG3_PHY_AUXCTL_SMDSP_ENABLE(tp)) {
tg3_writephy(tp, MII_TG3_DSP_ADDRESS, 0x000a);
if (tp->phy_flags & TG3_PHYFLG_ADJUST_TRIM) {
tg3_writephy(tp, MII_TG3_DSP_RW_PORT, 0x110b);
tg3_writephy(tp, MII_TG3_TEST1,
MII_TG3_TEST1_TRIM_EN | 0x4);
} else
tg3_writephy(tp, MII_TG3_DSP_RW_PORT, 0x010b);
TG3_PHY_AUXCTL_SMDSP_DISABLE(tp);
}
}
/* Set Extended packet length bit (bit 14) on all chips that */
/* support jumbo frames */
if ((tp->phy_id & TG3_PHY_ID_MASK) == TG3_PHY_ID_BCM5401) {
/* Cannot do read-modify-write on 5401 */
tg3_phy_auxctl_write(tp, MII_TG3_AUXCTL_SHDWSEL_AUXCTL, 0x4c20);
} else if (tg3_flag(tp, JUMBO_CAPABLE)) {
/* Set bit 14 with read-modify-write to preserve other bits */
err = tg3_phy_auxctl_read(tp,
MII_TG3_AUXCTL_SHDWSEL_AUXCTL, &val);
if (!err)
tg3_phy_auxctl_write(tp, MII_TG3_AUXCTL_SHDWSEL_AUXCTL,
val | MII_TG3_AUXCTL_ACTL_EXTPKTLEN);
}
/* Set phy register 0x10 bit 0 to high fifo elasticity to support
* jumbo frames transmission.
*/
if (tg3_flag(tp, JUMBO_CAPABLE)) {
if (!tg3_readphy(tp, MII_TG3_EXT_CTRL, &val))
tg3_writephy(tp, MII_TG3_EXT_CTRL,
val | MII_TG3_EXT_CTRL_FIFO_ELASTIC);
}
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5906) {
/* adjust output voltage */
tg3_writephy(tp, MII_TG3_FET_PTEST, 0x12);
}
tg3_phy_toggle_automdix(tp, 1);
tg3_phy_set_wirespeed(tp);
return 0;
}
#define TG3_GPIO_MSG_DRVR_PRES 0x00000001
#define TG3_GPIO_MSG_NEED_VAUX 0x00000002
#define TG3_GPIO_MSG_MASK (TG3_GPIO_MSG_DRVR_PRES | \
TG3_GPIO_MSG_NEED_VAUX)
#define TG3_GPIO_MSG_ALL_DRVR_PRES_MASK \
((TG3_GPIO_MSG_DRVR_PRES << 0) | \
(TG3_GPIO_MSG_DRVR_PRES << 4) | \
(TG3_GPIO_MSG_DRVR_PRES << 8) | \
(TG3_GPIO_MSG_DRVR_PRES << 12))
#define TG3_GPIO_MSG_ALL_NEED_VAUX_MASK \
((TG3_GPIO_MSG_NEED_VAUX << 0) | \
(TG3_GPIO_MSG_NEED_VAUX << 4) | \
(TG3_GPIO_MSG_NEED_VAUX << 8) | \
(TG3_GPIO_MSG_NEED_VAUX << 12))
static inline u32 tg3_set_function_status(struct tg3 *tp, u32 newstat)
{
u32 status, shift;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5717 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5719)
status = tg3_ape_read32(tp, TG3_APE_GPIO_MSG);
else
status = tr32(TG3_CPMU_DRV_STATUS);
shift = TG3_APE_GPIO_MSG_SHIFT + 4 * tp->pci_fn;
status &= ~(TG3_GPIO_MSG_MASK << shift);
status |= (newstat << shift);
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5717 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5719)
tg3_ape_write32(tp, TG3_APE_GPIO_MSG, status);
else
tw32(TG3_CPMU_DRV_STATUS, status);
return status >> TG3_APE_GPIO_MSG_SHIFT;
}
static inline int tg3_pwrsrc_switch_to_vmain(struct tg3 *tp)
{
if (!tg3_flag(tp, IS_NIC))
return 0;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5717 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5719 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5720) {
if (tg3_ape_lock(tp, TG3_APE_LOCK_GPIO))
return -EIO;
tg3_set_function_status(tp, TG3_GPIO_MSG_DRVR_PRES);
tw32_wait_f(GRC_LOCAL_CTRL, tp->grc_local_ctrl,
TG3_GRC_LCLCTL_PWRSW_DELAY);
tg3_ape_unlock(tp, TG3_APE_LOCK_GPIO);
} else {
tw32_wait_f(GRC_LOCAL_CTRL, tp->grc_local_ctrl,
TG3_GRC_LCLCTL_PWRSW_DELAY);
}
return 0;
}
static void tg3_pwrsrc_die_with_vmain(struct tg3 *tp)
{
u32 grc_local_ctrl;
if (!tg3_flag(tp, IS_NIC) ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5700 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5701)
return;
grc_local_ctrl = tp->grc_local_ctrl | GRC_LCLCTRL_GPIO_OE1;
tw32_wait_f(GRC_LOCAL_CTRL,
grc_local_ctrl | GRC_LCLCTRL_GPIO_OUTPUT1,
TG3_GRC_LCLCTL_PWRSW_DELAY);
tw32_wait_f(GRC_LOCAL_CTRL,
grc_local_ctrl,
TG3_GRC_LCLCTL_PWRSW_DELAY);
tw32_wait_f(GRC_LOCAL_CTRL,
grc_local_ctrl | GRC_LCLCTRL_GPIO_OUTPUT1,
TG3_GRC_LCLCTL_PWRSW_DELAY);
}
static void tg3_pwrsrc_switch_to_vaux(struct tg3 *tp)
{
if (!tg3_flag(tp, IS_NIC))
return;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5700 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5701) {
tw32_wait_f(GRC_LOCAL_CTRL, tp->grc_local_ctrl |
(GRC_LCLCTRL_GPIO_OE0 |
GRC_LCLCTRL_GPIO_OE1 |
GRC_LCLCTRL_GPIO_OE2 |
GRC_LCLCTRL_GPIO_OUTPUT0 |
GRC_LCLCTRL_GPIO_OUTPUT1),
TG3_GRC_LCLCTL_PWRSW_DELAY);
} else if (tp->pdev->device == PCI_DEVICE_ID_TIGON3_5761 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_5761S) {
/* The 5761 non-e device swaps GPIO 0 and GPIO 2. */
u32 grc_local_ctrl = GRC_LCLCTRL_GPIO_OE0 |
GRC_LCLCTRL_GPIO_OE1 |
GRC_LCLCTRL_GPIO_OE2 |
GRC_LCLCTRL_GPIO_OUTPUT0 |
GRC_LCLCTRL_GPIO_OUTPUT1 |
tp->grc_local_ctrl;
tw32_wait_f(GRC_LOCAL_CTRL, grc_local_ctrl,
TG3_GRC_LCLCTL_PWRSW_DELAY);
grc_local_ctrl |= GRC_LCLCTRL_GPIO_OUTPUT2;
tw32_wait_f(GRC_LOCAL_CTRL, grc_local_ctrl,
TG3_GRC_LCLCTL_PWRSW_DELAY);
grc_local_ctrl &= ~GRC_LCLCTRL_GPIO_OUTPUT0;
tw32_wait_f(GRC_LOCAL_CTRL, grc_local_ctrl,
TG3_GRC_LCLCTL_PWRSW_DELAY);
} else {
u32 no_gpio2;
u32 grc_local_ctrl = 0;
/* Workaround to prevent overdrawing Amps. */
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5714) {
grc_local_ctrl |= GRC_LCLCTRL_GPIO_OE3;
tw32_wait_f(GRC_LOCAL_CTRL, tp->grc_local_ctrl |
grc_local_ctrl,
TG3_GRC_LCLCTL_PWRSW_DELAY);
}
/* On 5753 and variants, GPIO2 cannot be used. */
no_gpio2 = tp->nic_sram_data_cfg &
NIC_SRAM_DATA_CFG_NO_GPIO2;
grc_local_ctrl |= GRC_LCLCTRL_GPIO_OE0 |
GRC_LCLCTRL_GPIO_OE1 |
GRC_LCLCTRL_GPIO_OE2 |
GRC_LCLCTRL_GPIO_OUTPUT1 |
GRC_LCLCTRL_GPIO_OUTPUT2;
if (no_gpio2) {
grc_local_ctrl &= ~(GRC_LCLCTRL_GPIO_OE2 |
GRC_LCLCTRL_GPIO_OUTPUT2);
}
tw32_wait_f(GRC_LOCAL_CTRL,
tp->grc_local_ctrl | grc_local_ctrl,
TG3_GRC_LCLCTL_PWRSW_DELAY);
grc_local_ctrl |= GRC_LCLCTRL_GPIO_OUTPUT0;
tw32_wait_f(GRC_LOCAL_CTRL,
tp->grc_local_ctrl | grc_local_ctrl,
TG3_GRC_LCLCTL_PWRSW_DELAY);
if (!no_gpio2) {
grc_local_ctrl &= ~GRC_LCLCTRL_GPIO_OUTPUT2;
tw32_wait_f(GRC_LOCAL_CTRL,
tp->grc_local_ctrl | grc_local_ctrl,
TG3_GRC_LCLCTL_PWRSW_DELAY);
}
}
}
static void tg3_frob_aux_power_5717(struct tg3 *tp, bool wol_enable)
{
u32 msg = 0;
/* Serialize power state transitions */
if (tg3_ape_lock(tp, TG3_APE_LOCK_GPIO))
return;
if (tg3_flag(tp, ENABLE_ASF) || tg3_flag(tp, ENABLE_APE) || wol_enable)
msg = TG3_GPIO_MSG_NEED_VAUX;
msg = tg3_set_function_status(tp, msg);
if (msg & TG3_GPIO_MSG_ALL_DRVR_PRES_MASK)
goto done;
if (msg & TG3_GPIO_MSG_ALL_NEED_VAUX_MASK)
tg3_pwrsrc_switch_to_vaux(tp);
else
tg3_pwrsrc_die_with_vmain(tp);
done:
tg3_ape_unlock(tp, TG3_APE_LOCK_GPIO);
}
static void tg3_frob_aux_power(struct tg3 *tp, bool include_wol)
{
bool need_vaux = false;
/* The GPIOs do something completely different on 57765. */
if (!tg3_flag(tp, IS_NIC) || tg3_flag(tp, 57765_CLASS))
return;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5717 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5719 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5720) {
tg3_frob_aux_power_5717(tp, include_wol ?
tg3_flag(tp, WOL_ENABLE) != 0 : 0);
return;
}
if (tp->pdev_peer && tp->pdev_peer != tp->pdev) {
struct net_device *dev_peer;
dev_peer = pci_get_drvdata(tp->pdev_peer);
/* remove_one() may have been run on the peer. */
if (dev_peer) {
struct tg3 *tp_peer = netdev_priv(dev_peer);
if (tg3_flag(tp_peer, INIT_COMPLETE))
return;
if ((include_wol && tg3_flag(tp_peer, WOL_ENABLE)) ||
tg3_flag(tp_peer, ENABLE_ASF))
need_vaux = true;
}
}
if ((include_wol && tg3_flag(tp, WOL_ENABLE)) ||
tg3_flag(tp, ENABLE_ASF))
need_vaux = true;
if (need_vaux)
tg3_pwrsrc_switch_to_vaux(tp);
else
tg3_pwrsrc_die_with_vmain(tp);
}
static int tg3_5700_link_polarity(struct tg3 *tp, u32 speed)
{
if (tp->led_ctrl == LED_CTRL_MODE_PHY_2)
return 1;
else if ((tp->phy_id & TG3_PHY_ID_MASK) == TG3_PHY_ID_BCM5411) {
if (speed != SPEED_10)
return 1;
} else if (speed == SPEED_10)
return 1;
return 0;
}
static void tg3_power_down_phy(struct tg3 *tp, bool do_low_power)
{
u32 val;
if (tp->phy_flags & TG3_PHYFLG_PHY_SERDES) {
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5704) {
u32 sg_dig_ctrl = tr32(SG_DIG_CTRL);
u32 serdes_cfg = tr32(MAC_SERDES_CFG);
sg_dig_ctrl |=
SG_DIG_USING_HW_AUTONEG | SG_DIG_SOFT_RESET;
tw32(SG_DIG_CTRL, sg_dig_ctrl);
tw32(MAC_SERDES_CFG, serdes_cfg | (1 << 15));
}
return;
}
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5906) {
tg3_bmcr_reset(tp);
val = tr32(GRC_MISC_CFG);
tw32_f(GRC_MISC_CFG, val | GRC_MISC_CFG_EPHY_IDDQ);
udelay(40);
return;
} else if (tp->phy_flags & TG3_PHYFLG_IS_FET) {
u32 phytest;
if (!tg3_readphy(tp, MII_TG3_FET_TEST, &phytest)) {
u32 phy;
tg3_writephy(tp, MII_ADVERTISE, 0);
tg3_writephy(tp, MII_BMCR,
BMCR_ANENABLE | BMCR_ANRESTART);
tg3_writephy(tp, MII_TG3_FET_TEST,
phytest | MII_TG3_FET_SHADOW_EN);
if (!tg3_readphy(tp, MII_TG3_FET_SHDW_AUXMODE4, &phy)) {
phy |= MII_TG3_FET_SHDW_AUXMODE4_SBPD;
tg3_writephy(tp,
MII_TG3_FET_SHDW_AUXMODE4,
phy);
}
tg3_writephy(tp, MII_TG3_FET_TEST, phytest);
}
return;
} else if (do_low_power) {
tg3_writephy(tp, MII_TG3_EXT_CTRL,
MII_TG3_EXT_CTRL_FORCE_LED_OFF);
val = MII_TG3_AUXCTL_PCTL_100TX_LPWR |
MII_TG3_AUXCTL_PCTL_SPR_ISOLATE |
MII_TG3_AUXCTL_PCTL_VREG_11V;
tg3_phy_auxctl_write(tp, MII_TG3_AUXCTL_SHDWSEL_PWRCTL, val);
}
/* The PHY should not be powered down on some chips because
* of bugs.
*/
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5700 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5704 ||
(GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5780 &&
(tp->phy_flags & TG3_PHYFLG_MII_SERDES)) ||
(GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5717 &&
!tp->pci_fn))
return;
if (GET_CHIP_REV(tp->pci_chip_rev_id) == CHIPREV_5784_AX ||
GET_CHIP_REV(tp->pci_chip_rev_id) == CHIPREV_5761_AX) {
val = tr32(TG3_CPMU_LSPD_1000MB_CLK);
val &= ~CPMU_LSPD_1000MB_MACCLK_MASK;
val |= CPMU_LSPD_1000MB_MACCLK_12_5;
tw32_f(TG3_CPMU_LSPD_1000MB_CLK, val);
}
tg3_writephy(tp, MII_BMCR, BMCR_PDOWN);
}
/* tp->lock is held. */
static int tg3_nvram_lock(struct tg3 *tp)
{
if (tg3_flag(tp, NVRAM)) {
int i;
if (tp->nvram_lock_cnt == 0) {
tw32(NVRAM_SWARB, SWARB_REQ_SET1);
for (i = 0; i < 8000; i++) {
if (tr32(NVRAM_SWARB) & SWARB_GNT1)
break;
udelay(20);
}
if (i == 8000) {
tw32(NVRAM_SWARB, SWARB_REQ_CLR1);
return -ENODEV;
}
}
tp->nvram_lock_cnt++;
}
return 0;
}
/* tp->lock is held. */
static void tg3_nvram_unlock(struct tg3 *tp)
{
if (tg3_flag(tp, NVRAM)) {
if (tp->nvram_lock_cnt > 0)
tp->nvram_lock_cnt--;
if (tp->nvram_lock_cnt == 0)
tw32_f(NVRAM_SWARB, SWARB_REQ_CLR1);
}
}
/* tp->lock is held. */
static void tg3_enable_nvram_access(struct tg3 *tp)
{
if (tg3_flag(tp, 5750_PLUS) && !tg3_flag(tp, PROTECTED_NVRAM)) {
u32 nvaccess = tr32(NVRAM_ACCESS);
tw32(NVRAM_ACCESS, nvaccess | ACCESS_ENABLE);
}
}
/* tp->lock is held. */
static void tg3_disable_nvram_access(struct tg3 *tp)
{
if (tg3_flag(tp, 5750_PLUS) && !tg3_flag(tp, PROTECTED_NVRAM)) {
u32 nvaccess = tr32(NVRAM_ACCESS);
tw32(NVRAM_ACCESS, nvaccess & ~ACCESS_ENABLE);
}
}
static int tg3_nvram_read_using_eeprom(struct tg3 *tp,
u32 offset, u32 *val)
{
u32 tmp;
int i;
if (offset > EEPROM_ADDR_ADDR_MASK || (offset % 4) != 0)
return -EINVAL;
tmp = tr32(GRC_EEPROM_ADDR) & ~(EEPROM_ADDR_ADDR_MASK |
EEPROM_ADDR_DEVID_MASK |
EEPROM_ADDR_READ);
tw32(GRC_EEPROM_ADDR,
tmp |
(0 << EEPROM_ADDR_DEVID_SHIFT) |
((offset << EEPROM_ADDR_ADDR_SHIFT) &
EEPROM_ADDR_ADDR_MASK) |
EEPROM_ADDR_READ | EEPROM_ADDR_START);
for (i = 0; i < 1000; i++) {
tmp = tr32(GRC_EEPROM_ADDR);
if (tmp & EEPROM_ADDR_COMPLETE)
break;
msleep(1);
}
if (!(tmp & EEPROM_ADDR_COMPLETE))
return -EBUSY;
tmp = tr32(GRC_EEPROM_DATA);
/*
* The data will always be opposite the native endian
* format. Perform a blind byteswap to compensate.
*/
*val = swab32(tmp);
return 0;
}
#define NVRAM_CMD_TIMEOUT 10000
static int tg3_nvram_exec_cmd(struct tg3 *tp, u32 nvram_cmd)
{
int i;
tw32(NVRAM_CMD, nvram_cmd);
for (i = 0; i < NVRAM_CMD_TIMEOUT; i++) {
udelay(10);
if (tr32(NVRAM_CMD) & NVRAM_CMD_DONE) {
udelay(10);
break;
}
}
if (i == NVRAM_CMD_TIMEOUT)
return -EBUSY;
return 0;
}
static u32 tg3_nvram_phys_addr(struct tg3 *tp, u32 addr)
{
if (tg3_flag(tp, NVRAM) &&
tg3_flag(tp, NVRAM_BUFFERED) &&
tg3_flag(tp, FLASH) &&
!tg3_flag(tp, NO_NVRAM_ADDR_TRANS) &&
(tp->nvram_jedecnum == JEDEC_ATMEL))
addr = ((addr / tp->nvram_pagesize) <<
ATMEL_AT45DB0X1B_PAGE_POS) +
(addr % tp->nvram_pagesize);
return addr;
}
static u32 tg3_nvram_logical_addr(struct tg3 *tp, u32 addr)
{
if (tg3_flag(tp, NVRAM) &&
tg3_flag(tp, NVRAM_BUFFERED) &&
tg3_flag(tp, FLASH) &&
!tg3_flag(tp, NO_NVRAM_ADDR_TRANS) &&
(tp->nvram_jedecnum == JEDEC_ATMEL))
addr = ((addr >> ATMEL_AT45DB0X1B_PAGE_POS) *
tp->nvram_pagesize) +
(addr & ((1 << ATMEL_AT45DB0X1B_PAGE_POS) - 1));
return addr;
}
/* NOTE: Data read in from NVRAM is byteswapped according to
* the byteswapping settings for all other register accesses.
* tg3 devices are BE devices, so on a BE machine, the data
* returned will be exactly as it is seen in NVRAM. On a LE
* machine, the 32-bit value will be byteswapped.
*/
static int tg3_nvram_read(struct tg3 *tp, u32 offset, u32 *val)
{
int ret;
if (!tg3_flag(tp, NVRAM))
return tg3_nvram_read_using_eeprom(tp, offset, val);
offset = tg3_nvram_phys_addr(tp, offset);
if (offset > NVRAM_ADDR_MSK)
return -EINVAL;
ret = tg3_nvram_lock(tp);
if (ret)
return ret;
tg3_enable_nvram_access(tp);
tw32(NVRAM_ADDR, offset);
ret = tg3_nvram_exec_cmd(tp, NVRAM_CMD_RD | NVRAM_CMD_GO |
NVRAM_CMD_FIRST | NVRAM_CMD_LAST | NVRAM_CMD_DONE);
if (ret == 0)
*val = tr32(NVRAM_RDDATA);
tg3_disable_nvram_access(tp);
tg3_nvram_unlock(tp);
return ret;
}
/* Ensures NVRAM data is in bytestream format. */
static int tg3_nvram_read_be32(struct tg3 *tp, u32 offset, __be32 *val)
{
u32 v;
int res = tg3_nvram_read(tp, offset, &v);
if (!res)
*val = cpu_to_be32(v);
return res;
}
static int tg3_nvram_write_block_using_eeprom(struct tg3 *tp,
u32 offset, u32 len, u8 *buf)
{
int i, j, rc = 0;
u32 val;
for (i = 0; i < len; i += 4) {
u32 addr;
__be32 data;
addr = offset + i;
memcpy(&data, buf + i, 4);
/*
* The SEEPROM interface expects the data to always be opposite
* the native endian format. We accomplish this by reversing
* all the operations that would have been performed on the
* data from a call to tg3_nvram_read_be32().
*/
tw32(GRC_EEPROM_DATA, swab32(be32_to_cpu(data)));
val = tr32(GRC_EEPROM_ADDR);
tw32(GRC_EEPROM_ADDR, val | EEPROM_ADDR_COMPLETE);
val &= ~(EEPROM_ADDR_ADDR_MASK | EEPROM_ADDR_DEVID_MASK |
EEPROM_ADDR_READ);
tw32(GRC_EEPROM_ADDR, val |
(0 << EEPROM_ADDR_DEVID_SHIFT) |
(addr & EEPROM_ADDR_ADDR_MASK) |
EEPROM_ADDR_START |
EEPROM_ADDR_WRITE);
for (j = 0; j < 1000; j++) {
val = tr32(GRC_EEPROM_ADDR);
if (val & EEPROM_ADDR_COMPLETE)
break;
msleep(1);
}
if (!(val & EEPROM_ADDR_COMPLETE)) {
rc = -EBUSY;
break;
}
}
return rc;
}
/* offset and length are dword aligned */
static int tg3_nvram_write_block_unbuffered(struct tg3 *tp, u32 offset, u32 len,
u8 *buf)
{
int ret = 0;
u32 pagesize = tp->nvram_pagesize;
u32 pagemask = pagesize - 1;
u32 nvram_cmd;
u8 *tmp;
tmp = kmalloc(pagesize, GFP_KERNEL);
if (tmp == NULL)
return -ENOMEM;
while (len) {
int j;
u32 phy_addr, page_off, size;
phy_addr = offset & ~pagemask;
for (j = 0; j < pagesize; j += 4) {
ret = tg3_nvram_read_be32(tp, phy_addr + j,
(__be32 *) (tmp + j));
if (ret)
break;
}
if (ret)
break;
page_off = offset & pagemask;
size = pagesize;
if (len < size)
size = len;
len -= size;
memcpy(tmp + page_off, buf, size);
offset = offset + (pagesize - page_off);
tg3_enable_nvram_access(tp);
/*
* Before we can erase the flash page, we need
* to issue a special "write enable" command.
*/
nvram_cmd = NVRAM_CMD_WREN | NVRAM_CMD_GO | NVRAM_CMD_DONE;
if (tg3_nvram_exec_cmd(tp, nvram_cmd))
break;
/* Erase the target page */
tw32(NVRAM_ADDR, phy_addr);
nvram_cmd = NVRAM_CMD_GO | NVRAM_CMD_DONE | NVRAM_CMD_WR |
NVRAM_CMD_FIRST | NVRAM_CMD_LAST | NVRAM_CMD_ERASE;
if (tg3_nvram_exec_cmd(tp, nvram_cmd))
break;
/* Issue another write enable to start the write. */
nvram_cmd = NVRAM_CMD_WREN | NVRAM_CMD_GO | NVRAM_CMD_DONE;
if (tg3_nvram_exec_cmd(tp, nvram_cmd))
break;
for (j = 0; j < pagesize; j += 4) {
__be32 data;
data = *((__be32 *) (tmp + j));
tw32(NVRAM_WRDATA, be32_to_cpu(data));
tw32(NVRAM_ADDR, phy_addr + j);
nvram_cmd = NVRAM_CMD_GO | NVRAM_CMD_DONE |
NVRAM_CMD_WR;
if (j == 0)
nvram_cmd |= NVRAM_CMD_FIRST;
else if (j == (pagesize - 4))
nvram_cmd |= NVRAM_CMD_LAST;
ret = tg3_nvram_exec_cmd(tp, nvram_cmd);
if (ret)
break;
}
if (ret)
break;
}
nvram_cmd = NVRAM_CMD_WRDI | NVRAM_CMD_GO | NVRAM_CMD_DONE;
tg3_nvram_exec_cmd(tp, nvram_cmd);
kfree(tmp);
return ret;
}
/* offset and length are dword aligned */
static int tg3_nvram_write_block_buffered(struct tg3 *tp, u32 offset, u32 len,
u8 *buf)
{
int i, ret = 0;
for (i = 0; i < len; i += 4, offset += 4) {
u32 page_off, phy_addr, nvram_cmd;
__be32 data;
memcpy(&data, buf + i, 4);
tw32(NVRAM_WRDATA, be32_to_cpu(data));
page_off = offset % tp->nvram_pagesize;
phy_addr = tg3_nvram_phys_addr(tp, offset);
nvram_cmd = NVRAM_CMD_GO | NVRAM_CMD_DONE | NVRAM_CMD_WR;
if (page_off == 0 || i == 0)
nvram_cmd |= NVRAM_CMD_FIRST;
if (page_off == (tp->nvram_pagesize - 4))
nvram_cmd |= NVRAM_CMD_LAST;
if (i == (len - 4))
nvram_cmd |= NVRAM_CMD_LAST;
if ((nvram_cmd & NVRAM_CMD_FIRST) ||
!tg3_flag(tp, FLASH) ||
!tg3_flag(tp, 57765_PLUS))
tw32(NVRAM_ADDR, phy_addr);
if (GET_ASIC_REV(tp->pci_chip_rev_id) != ASIC_REV_5752 &&
!tg3_flag(tp, 5755_PLUS) &&
(tp->nvram_jedecnum == JEDEC_ST) &&
(nvram_cmd & NVRAM_CMD_FIRST)) {
u32 cmd;
cmd = NVRAM_CMD_WREN | NVRAM_CMD_GO | NVRAM_CMD_DONE;
ret = tg3_nvram_exec_cmd(tp, cmd);
if (ret)
break;
}
if (!tg3_flag(tp, FLASH)) {
/* We always do complete word writes to eeprom. */
nvram_cmd |= (NVRAM_CMD_FIRST | NVRAM_CMD_LAST);
}
ret = tg3_nvram_exec_cmd(tp, nvram_cmd);
if (ret)
break;
}
return ret;
}
/* offset and length are dword aligned */
static int tg3_nvram_write_block(struct tg3 *tp, u32 offset, u32 len, u8 *buf)
{
int ret;
if (tg3_flag(tp, EEPROM_WRITE_PROT)) {
tw32_f(GRC_LOCAL_CTRL, tp->grc_local_ctrl &
~GRC_LCLCTRL_GPIO_OUTPUT1);
udelay(40);
}
if (!tg3_flag(tp, NVRAM)) {
ret = tg3_nvram_write_block_using_eeprom(tp, offset, len, buf);
} else {
u32 grc_mode;
ret = tg3_nvram_lock(tp);
if (ret)
return ret;
tg3_enable_nvram_access(tp);
if (tg3_flag(tp, 5750_PLUS) && !tg3_flag(tp, PROTECTED_NVRAM))
tw32(NVRAM_WRITE1, 0x406);
grc_mode = tr32(GRC_MODE);
tw32(GRC_MODE, grc_mode | GRC_MODE_NVRAM_WR_ENABLE);
if (tg3_flag(tp, NVRAM_BUFFERED) || !tg3_flag(tp, FLASH)) {
ret = tg3_nvram_write_block_buffered(tp, offset, len,
buf);
} else {
ret = tg3_nvram_write_block_unbuffered(tp, offset, len,
buf);
}
grc_mode = tr32(GRC_MODE);
tw32(GRC_MODE, grc_mode & ~GRC_MODE_NVRAM_WR_ENABLE);
tg3_disable_nvram_access(tp);
tg3_nvram_unlock(tp);
}
if (tg3_flag(tp, EEPROM_WRITE_PROT)) {
tw32_f(GRC_LOCAL_CTRL, tp->grc_local_ctrl);
udelay(40);
}
return ret;
}
#define RX_CPU_SCRATCH_BASE 0x30000
#define RX_CPU_SCRATCH_SIZE 0x04000
#define TX_CPU_SCRATCH_BASE 0x34000
#define TX_CPU_SCRATCH_SIZE 0x04000
/* tp->lock is held. */
static int tg3_halt_cpu(struct tg3 *tp, u32 offset)
{
int i;
BUG_ON(offset == TX_CPU_BASE && tg3_flag(tp, 5705_PLUS));
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5906) {
u32 val = tr32(GRC_VCPU_EXT_CTRL);
tw32(GRC_VCPU_EXT_CTRL, val | GRC_VCPU_EXT_CTRL_HALT_CPU);
return 0;
}
if (offset == RX_CPU_BASE) {
for (i = 0; i < 10000; i++) {
tw32(offset + CPU_STATE, 0xffffffff);
tw32(offset + CPU_MODE, CPU_MODE_HALT);
if (tr32(offset + CPU_MODE) & CPU_MODE_HALT)
break;
}
tw32(offset + CPU_STATE, 0xffffffff);
tw32_f(offset + CPU_MODE, CPU_MODE_HALT);
udelay(10);
} else {
for (i = 0; i < 10000; i++) {
tw32(offset + CPU_STATE, 0xffffffff);
tw32(offset + CPU_MODE, CPU_MODE_HALT);
if (tr32(offset + CPU_MODE) & CPU_MODE_HALT)
break;
}
}
if (i >= 10000) {
netdev_err(tp->dev, "%s timed out, %s CPU\n",
__func__, offset == RX_CPU_BASE ? "RX" : "TX");
return -ENODEV;
}
/* Clear firmware's nvram arbitration. */
if (tg3_flag(tp, NVRAM))
tw32(NVRAM_SWARB, SWARB_REQ_CLR0);
return 0;
}
struct fw_info {
unsigned int fw_base;
unsigned int fw_len;
const __be32 *fw_data;
};
/* tp->lock is held. */
static int tg3_load_firmware_cpu(struct tg3 *tp, u32 cpu_base,
u32 cpu_scratch_base, int cpu_scratch_size,
struct fw_info *info)
{
int err, lock_err, i;
void (*write_op)(struct tg3 *, u32, u32);
if (cpu_base == TX_CPU_BASE && tg3_flag(tp, 5705_PLUS)) {
netdev_err(tp->dev,
"%s: Trying to load TX cpu firmware which is 5705\n",
__func__);
return -EINVAL;
}
if (tg3_flag(tp, 5705_PLUS))
write_op = tg3_write_mem;
else
write_op = tg3_write_indirect_reg32;
/* It is possible that bootcode is still loading at this point.
* Get the nvram lock first before halting the cpu.
*/
lock_err = tg3_nvram_lock(tp);
err = tg3_halt_cpu(tp, cpu_base);
if (!lock_err)
tg3_nvram_unlock(tp);
if (err)
goto out;
for (i = 0; i < cpu_scratch_size; i += sizeof(u32))
write_op(tp, cpu_scratch_base + i, 0);
tw32(cpu_base + CPU_STATE, 0xffffffff);
tw32(cpu_base + CPU_MODE, tr32(cpu_base+CPU_MODE)|CPU_MODE_HALT);
for (i = 0; i < (info->fw_len / sizeof(u32)); i++)
write_op(tp, (cpu_scratch_base +
(info->fw_base & 0xffff) +
(i * sizeof(u32))),
be32_to_cpu(info->fw_data[i]));
err = 0;
out:
return err;
}
/* tp->lock is held. */
static int tg3_load_5701_a0_firmware_fix(struct tg3 *tp)
{
struct fw_info info;
const __be32 *fw_data;
int err, i;
fw_data = (void *)tp->fw->data;
/* Firmware blob starts with version numbers, followed by
start address and length. We are setting complete length.
length = end_address_of_bss - start_address_of_text.
Remainder is the blob to be loaded contiguously
from start address. */
info.fw_base = be32_to_cpu(fw_data[1]);
info.fw_len = tp->fw->size - 12;
info.fw_data = &fw_data[3];
err = tg3_load_firmware_cpu(tp, RX_CPU_BASE,
RX_CPU_SCRATCH_BASE, RX_CPU_SCRATCH_SIZE,
&info);
if (err)
return err;
err = tg3_load_firmware_cpu(tp, TX_CPU_BASE,
TX_CPU_SCRATCH_BASE, TX_CPU_SCRATCH_SIZE,
&info);
if (err)
return err;
/* Now startup only the RX cpu. */
tw32(RX_CPU_BASE + CPU_STATE, 0xffffffff);
tw32_f(RX_CPU_BASE + CPU_PC, info.fw_base);
for (i = 0; i < 5; i++) {
if (tr32(RX_CPU_BASE + CPU_PC) == info.fw_base)
break;
tw32(RX_CPU_BASE + CPU_STATE, 0xffffffff);
tw32(RX_CPU_BASE + CPU_MODE, CPU_MODE_HALT);
tw32_f(RX_CPU_BASE + CPU_PC, info.fw_base);
udelay(1000);
}
if (i >= 5) {
netdev_err(tp->dev, "%s fails to set RX CPU PC, is %08x "
"should be %08x\n", __func__,
tr32(RX_CPU_BASE + CPU_PC), info.fw_base);
return -ENODEV;
}
tw32(RX_CPU_BASE + CPU_STATE, 0xffffffff);
tw32_f(RX_CPU_BASE + CPU_MODE, 0x00000000);
return 0;
}
/* tp->lock is held. */
static int tg3_load_tso_firmware(struct tg3 *tp)
{
struct fw_info info;
const __be32 *fw_data;
unsigned long cpu_base, cpu_scratch_base, cpu_scratch_size;
int err, i;
if (tg3_flag(tp, HW_TSO_1) ||
tg3_flag(tp, HW_TSO_2) ||
tg3_flag(tp, HW_TSO_3))
return 0;
fw_data = (void *)tp->fw->data;
/* Firmware blob starts with version numbers, followed by
start address and length. We are setting complete length.
length = end_address_of_bss - start_address_of_text.
Remainder is the blob to be loaded contiguously
from start address. */
info.fw_base = be32_to_cpu(fw_data[1]);
cpu_scratch_size = tp->fw_len;
info.fw_len = tp->fw->size - 12;
info.fw_data = &fw_data[3];
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5705) {
cpu_base = RX_CPU_BASE;
cpu_scratch_base = NIC_SRAM_MBUF_POOL_BASE5705;
} else {
cpu_base = TX_CPU_BASE;
cpu_scratch_base = TX_CPU_SCRATCH_BASE;
cpu_scratch_size = TX_CPU_SCRATCH_SIZE;
}
err = tg3_load_firmware_cpu(tp, cpu_base,
cpu_scratch_base, cpu_scratch_size,
&info);
if (err)
return err;
/* Now startup the cpu. */
tw32(cpu_base + CPU_STATE, 0xffffffff);
tw32_f(cpu_base + CPU_PC, info.fw_base);
for (i = 0; i < 5; i++) {
if (tr32(cpu_base + CPU_PC) == info.fw_base)
break;
tw32(cpu_base + CPU_STATE, 0xffffffff);
tw32(cpu_base + CPU_MODE, CPU_MODE_HALT);
tw32_f(cpu_base + CPU_PC, info.fw_base);
udelay(1000);
}
if (i >= 5) {
netdev_err(tp->dev,
"%s fails to set CPU PC, is %08x should be %08x\n",
__func__, tr32(cpu_base + CPU_PC), info.fw_base);
return -ENODEV;
}
tw32(cpu_base + CPU_STATE, 0xffffffff);
tw32_f(cpu_base + CPU_MODE, 0x00000000);
return 0;
}
/* tp->lock is held. */
static void __tg3_set_mac_addr(struct tg3 *tp, int skip_mac_1)
{
u32 addr_high, addr_low;
int i;
addr_high = ((tp->dev->dev_addr[0] << 8) |
tp->dev->dev_addr[1]);
addr_low = ((tp->dev->dev_addr[2] << 24) |
(tp->dev->dev_addr[3] << 16) |
(tp->dev->dev_addr[4] << 8) |
(tp->dev->dev_addr[5] << 0));
for (i = 0; i < 4; i++) {
if (i == 1 && skip_mac_1)
continue;
tw32(MAC_ADDR_0_HIGH + (i * 8), addr_high);
tw32(MAC_ADDR_0_LOW + (i * 8), addr_low);
}
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5703 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5704) {
for (i = 0; i < 12; i++) {
tw32(MAC_EXTADDR_0_HIGH + (i * 8), addr_high);
tw32(MAC_EXTADDR_0_LOW + (i * 8), addr_low);
}
}
addr_high = (tp->dev->dev_addr[0] +
tp->dev->dev_addr[1] +
tp->dev->dev_addr[2] +
tp->dev->dev_addr[3] +
tp->dev->dev_addr[4] +
tp->dev->dev_addr[5]) &
TX_BACKOFF_SEED_MASK;
tw32(MAC_TX_BACKOFF_SEED, addr_high);
}
static void tg3_enable_register_access(struct tg3 *tp)
{
/*
* Make sure register accesses (indirect or otherwise) will function
* correctly.
*/
pci_write_config_dword(tp->pdev,
TG3PCI_MISC_HOST_CTRL, tp->misc_host_ctrl);
}
static int tg3_power_up(struct tg3 *tp)
{
int err;
tg3_enable_register_access(tp);
err = pci_set_power_state(tp->pdev, PCI_D0);
if (!err) {
/* Switch out of Vaux if it is a NIC */
tg3_pwrsrc_switch_to_vmain(tp);
} else {
netdev_err(tp->dev, "Transition to D0 failed\n");
}
return err;
}
static int tg3_setup_phy(struct tg3 *, int);
static int tg3_power_down_prepare(struct tg3 *tp)
{
u32 misc_host_ctrl;
bool device_should_wake, do_low_power;
tg3_enable_register_access(tp);
/* Restore the CLKREQ setting. */
if (tg3_flag(tp, CLKREQ_BUG)) {
u16 lnkctl;
pci_read_config_word(tp->pdev,
pci_pcie_cap(tp->pdev) + PCI_EXP_LNKCTL,
&lnkctl);
lnkctl |= PCI_EXP_LNKCTL_CLKREQ_EN;
pci_write_config_word(tp->pdev,
pci_pcie_cap(tp->pdev) + PCI_EXP_LNKCTL,
lnkctl);
}
misc_host_ctrl = tr32(TG3PCI_MISC_HOST_CTRL);
tw32(TG3PCI_MISC_HOST_CTRL,
misc_host_ctrl | MISC_HOST_CTRL_MASK_PCI_INT);
device_should_wake = device_may_wakeup(&tp->pdev->dev) &&
tg3_flag(tp, WOL_ENABLE);
if (tg3_flag(tp, USE_PHYLIB)) {
do_low_power = false;
if ((tp->phy_flags & TG3_PHYFLG_IS_CONNECTED) &&
!(tp->phy_flags & TG3_PHYFLG_IS_LOW_POWER)) {
struct phy_device *phydev;
u32 phyid, advertising;
phydev = tp->mdio_bus->phy_map[TG3_PHY_MII_ADDR];
tp->phy_flags |= TG3_PHYFLG_IS_LOW_POWER;
tp->link_config.speed = phydev->speed;
tp->link_config.duplex = phydev->duplex;
tp->link_config.autoneg = phydev->autoneg;
tp->link_config.advertising = phydev->advertising;
advertising = ADVERTISED_TP |
ADVERTISED_Pause |
ADVERTISED_Autoneg |
ADVERTISED_10baseT_Half;
if (tg3_flag(tp, ENABLE_ASF) || device_should_wake) {
if (tg3_flag(tp, WOL_SPEED_100MB))
advertising |=
ADVERTISED_100baseT_Half |
ADVERTISED_100baseT_Full |
ADVERTISED_10baseT_Full;
else
advertising |= ADVERTISED_10baseT_Full;
}
phydev->advertising = advertising;
phy_start_aneg(phydev);
phyid = phydev->drv->phy_id & phydev->drv->phy_id_mask;
if (phyid != PHY_ID_BCMAC131) {
phyid &= PHY_BCM_OUI_MASK;
if (phyid == PHY_BCM_OUI_1 ||
phyid == PHY_BCM_OUI_2 ||
phyid == PHY_BCM_OUI_3)
do_low_power = true;
}
}
} else {
do_low_power = true;
if (!(tp->phy_flags & TG3_PHYFLG_IS_LOW_POWER))
tp->phy_flags |= TG3_PHYFLG_IS_LOW_POWER;
if (!(tp->phy_flags & TG3_PHYFLG_ANY_SERDES))
tg3_setup_phy(tp, 0);
}
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5906) {
u32 val;
val = tr32(GRC_VCPU_EXT_CTRL);
tw32(GRC_VCPU_EXT_CTRL, val | GRC_VCPU_EXT_CTRL_DISABLE_WOL);
} else if (!tg3_flag(tp, ENABLE_ASF)) {
int i;
u32 val;
for (i = 0; i < 200; i++) {
tg3_read_mem(tp, NIC_SRAM_FW_ASF_STATUS_MBOX, &val);
if (val == ~NIC_SRAM_FIRMWARE_MBOX_MAGIC1)
break;
msleep(1);
}
}
if (tg3_flag(tp, WOL_CAP))
tg3_write_mem(tp, NIC_SRAM_WOL_MBOX, WOL_SIGNATURE |
WOL_DRV_STATE_SHUTDOWN |
WOL_DRV_WOL |
WOL_SET_MAGIC_PKT);
if (device_should_wake) {
u32 mac_mode;
if (!(tp->phy_flags & TG3_PHYFLG_PHY_SERDES)) {
if (do_low_power &&
!(tp->phy_flags & TG3_PHYFLG_IS_FET)) {
tg3_phy_auxctl_write(tp,
MII_TG3_AUXCTL_SHDWSEL_PWRCTL,
MII_TG3_AUXCTL_PCTL_WOL_EN |
MII_TG3_AUXCTL_PCTL_100TX_LPWR |
MII_TG3_AUXCTL_PCTL_CL_AB_TXDAC);
udelay(40);
}
if (tp->phy_flags & TG3_PHYFLG_MII_SERDES)
mac_mode = MAC_MODE_PORT_MODE_GMII;
else
mac_mode = MAC_MODE_PORT_MODE_MII;
mac_mode |= tp->mac_mode & MAC_MODE_LINK_POLARITY;
if (GET_ASIC_REV(tp->pci_chip_rev_id) ==
ASIC_REV_5700) {
u32 speed = tg3_flag(tp, WOL_SPEED_100MB) ?
SPEED_100 : SPEED_10;
if (tg3_5700_link_polarity(tp, speed))
mac_mode |= MAC_MODE_LINK_POLARITY;
else
mac_mode &= ~MAC_MODE_LINK_POLARITY;
}
} else {
mac_mode = MAC_MODE_PORT_MODE_TBI;
}
if (!tg3_flag(tp, 5750_PLUS))
tw32(MAC_LED_CTRL, tp->led_ctrl);
mac_mode |= MAC_MODE_MAGIC_PKT_ENABLE;
if ((tg3_flag(tp, 5705_PLUS) && !tg3_flag(tp, 5780_CLASS)) &&
(tg3_flag(tp, ENABLE_ASF) || tg3_flag(tp, ENABLE_APE)))
mac_mode |= MAC_MODE_KEEP_FRAME_IN_WOL;
if (tg3_flag(tp, ENABLE_APE))
mac_mode |= MAC_MODE_APE_TX_EN |
MAC_MODE_APE_RX_EN |
MAC_MODE_TDE_ENABLE;
tw32_f(MAC_MODE, mac_mode);
udelay(100);
tw32_f(MAC_RX_MODE, RX_MODE_ENABLE);
udelay(10);
}
if (!tg3_flag(tp, WOL_SPEED_100MB) &&
(GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5700 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5701)) {
u32 base_val;
base_val = tp->pci_clock_ctrl;
base_val |= (CLOCK_CTRL_RXCLK_DISABLE |
CLOCK_CTRL_TXCLK_DISABLE);
tw32_wait_f(TG3PCI_CLOCK_CTRL, base_val | CLOCK_CTRL_ALTCLK |
CLOCK_CTRL_PWRDOWN_PLL133, 40);
} else if (tg3_flag(tp, 5780_CLASS) ||
tg3_flag(tp, CPMU_PRESENT) ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5906) {
/* do nothing */
} else if (!(tg3_flag(tp, 5750_PLUS) && tg3_flag(tp, ENABLE_ASF))) {
u32 newbits1, newbits2;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5700 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5701) {
newbits1 = (CLOCK_CTRL_RXCLK_DISABLE |
CLOCK_CTRL_TXCLK_DISABLE |
CLOCK_CTRL_ALTCLK);
newbits2 = newbits1 | CLOCK_CTRL_44MHZ_CORE;
} else if (tg3_flag(tp, 5705_PLUS)) {
newbits1 = CLOCK_CTRL_625_CORE;
newbits2 = newbits1 | CLOCK_CTRL_ALTCLK;
} else {
newbits1 = CLOCK_CTRL_ALTCLK;
newbits2 = newbits1 | CLOCK_CTRL_44MHZ_CORE;
}
tw32_wait_f(TG3PCI_CLOCK_CTRL, tp->pci_clock_ctrl | newbits1,
40);
tw32_wait_f(TG3PCI_CLOCK_CTRL, tp->pci_clock_ctrl | newbits2,
40);
if (!tg3_flag(tp, 5705_PLUS)) {
u32 newbits3;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5700 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5701) {
newbits3 = (CLOCK_CTRL_RXCLK_DISABLE |
CLOCK_CTRL_TXCLK_DISABLE |
CLOCK_CTRL_44MHZ_CORE);
} else {
newbits3 = CLOCK_CTRL_44MHZ_CORE;
}
tw32_wait_f(TG3PCI_CLOCK_CTRL,
tp->pci_clock_ctrl | newbits3, 40);
}
}
if (!(device_should_wake) && !tg3_flag(tp, ENABLE_ASF))
tg3_power_down_phy(tp, do_low_power);
tg3_frob_aux_power(tp, true);
/* Workaround for unstable PLL clock */
if ((GET_CHIP_REV(tp->pci_chip_rev_id) == CHIPREV_5750_AX) ||
(GET_CHIP_REV(tp->pci_chip_rev_id) == CHIPREV_5750_BX)) {
u32 val = tr32(0x7d00);
val &= ~((1 << 16) | (1 << 4) | (1 << 2) | (1 << 1) | 1);
tw32(0x7d00, val);
if (!tg3_flag(tp, ENABLE_ASF)) {
int err;
err = tg3_nvram_lock(tp);
tg3_halt_cpu(tp, RX_CPU_BASE);
if (!err)
tg3_nvram_unlock(tp);
}
}
tg3_write_sig_post_reset(tp, RESET_KIND_SHUTDOWN);
return 0;
}
static void tg3_power_down(struct tg3 *tp)
{
tg3_power_down_prepare(tp);
pci_wake_from_d3(tp->pdev, tg3_flag(tp, WOL_ENABLE));
pci_set_power_state(tp->pdev, PCI_D3hot);
}
static void tg3_aux_stat_to_speed_duplex(struct tg3 *tp, u32 val, u16 *speed, u8 *duplex)
{
switch (val & MII_TG3_AUX_STAT_SPDMASK) {
case MII_TG3_AUX_STAT_10HALF:
*speed = SPEED_10;
*duplex = DUPLEX_HALF;
break;
case MII_TG3_AUX_STAT_10FULL:
*speed = SPEED_10;
*duplex = DUPLEX_FULL;
break;
case MII_TG3_AUX_STAT_100HALF:
*speed = SPEED_100;
*duplex = DUPLEX_HALF;
break;
case MII_TG3_AUX_STAT_100FULL:
*speed = SPEED_100;
*duplex = DUPLEX_FULL;
break;
case MII_TG3_AUX_STAT_1000HALF:
*speed = SPEED_1000;
*duplex = DUPLEX_HALF;
break;
case MII_TG3_AUX_STAT_1000FULL:
*speed = SPEED_1000;
*duplex = DUPLEX_FULL;
break;
default:
if (tp->phy_flags & TG3_PHYFLG_IS_FET) {
*speed = (val & MII_TG3_AUX_STAT_100) ? SPEED_100 :
SPEED_10;
*duplex = (val & MII_TG3_AUX_STAT_FULL) ? DUPLEX_FULL :
DUPLEX_HALF;
break;
}
*speed = SPEED_UNKNOWN;
*duplex = DUPLEX_UNKNOWN;
break;
}
}
static int tg3_phy_autoneg_cfg(struct tg3 *tp, u32 advertise, u32 flowctrl)
{
int err = 0;
u32 val, new_adv;
new_adv = ADVERTISE_CSMA;
new_adv |= ethtool_adv_to_mii_adv_t(advertise) & ADVERTISE_ALL;
new_adv |= mii_advertise_flowctrl(flowctrl);
err = tg3_writephy(tp, MII_ADVERTISE, new_adv);
if (err)
goto done;
if (!(tp->phy_flags & TG3_PHYFLG_10_100_ONLY)) {
new_adv = ethtool_adv_to_mii_ctrl1000_t(advertise);
if (tp->pci_chip_rev_id == CHIPREV_ID_5701_A0 ||
tp->pci_chip_rev_id == CHIPREV_ID_5701_B0)
new_adv |= CTL1000_AS_MASTER | CTL1000_ENABLE_MASTER;
err = tg3_writephy(tp, MII_CTRL1000, new_adv);
if (err)
goto done;
}
if (!(tp->phy_flags & TG3_PHYFLG_EEE_CAP))
goto done;
tw32(TG3_CPMU_EEE_MODE,
tr32(TG3_CPMU_EEE_MODE) & ~TG3_CPMU_EEEMD_LPI_ENABLE);
err = TG3_PHY_AUXCTL_SMDSP_ENABLE(tp);
if (!err) {
u32 err2;
val = 0;
/* Advertise 100-BaseTX EEE ability */
if (advertise & ADVERTISED_100baseT_Full)
val |= MDIO_AN_EEE_ADV_100TX;
/* Advertise 1000-BaseT EEE ability */
if (advertise & ADVERTISED_1000baseT_Full)
val |= MDIO_AN_EEE_ADV_1000T;
err = tg3_phy_cl45_write(tp, MDIO_MMD_AN, MDIO_AN_EEE_ADV, val);
if (err)
val = 0;
switch (GET_ASIC_REV(tp->pci_chip_rev_id)) {
case ASIC_REV_5717:
case ASIC_REV_57765:
case ASIC_REV_57766:
case ASIC_REV_5719:
/* If we advertised any eee advertisements above... */
if (val)
val = MII_TG3_DSP_TAP26_ALNOKO |
MII_TG3_DSP_TAP26_RMRXSTO |
MII_TG3_DSP_TAP26_OPCSINPT;
tg3_phydsp_write(tp, MII_TG3_DSP_TAP26, val);
/* Fall through */
case ASIC_REV_5720:
if (!tg3_phydsp_read(tp, MII_TG3_DSP_CH34TP2, &val))
tg3_phydsp_write(tp, MII_TG3_DSP_CH34TP2, val |
MII_TG3_DSP_CH34TP2_HIBW01);
}
err2 = TG3_PHY_AUXCTL_SMDSP_DISABLE(tp);
if (!err)
err = err2;
}
done:
return err;
}
static void tg3_phy_copper_begin(struct tg3 *tp)
{
if (tp->link_config.autoneg == AUTONEG_ENABLE ||
(tp->phy_flags & TG3_PHYFLG_IS_LOW_POWER)) {
u32 adv, fc;
if (tp->phy_flags & TG3_PHYFLG_IS_LOW_POWER) {
adv = ADVERTISED_10baseT_Half |
ADVERTISED_10baseT_Full;
if (tg3_flag(tp, WOL_SPEED_100MB))
adv |= ADVERTISED_100baseT_Half |
ADVERTISED_100baseT_Full;
fc = FLOW_CTRL_TX | FLOW_CTRL_RX;
} else {
adv = tp->link_config.advertising;
if (tp->phy_flags & TG3_PHYFLG_10_100_ONLY)
adv &= ~(ADVERTISED_1000baseT_Half |
ADVERTISED_1000baseT_Full);
fc = tp->link_config.flowctrl;
}
tg3_phy_autoneg_cfg(tp, adv, fc);
tg3_writephy(tp, MII_BMCR,
BMCR_ANENABLE | BMCR_ANRESTART);
} else {
int i;
u32 bmcr, orig_bmcr;
tp->link_config.active_speed = tp->link_config.speed;
tp->link_config.active_duplex = tp->link_config.duplex;
bmcr = 0;
switch (tp->link_config.speed) {
default:
case SPEED_10:
break;
case SPEED_100:
bmcr |= BMCR_SPEED100;
break;
case SPEED_1000:
bmcr |= BMCR_SPEED1000;
break;
}
if (tp->link_config.duplex == DUPLEX_FULL)
bmcr |= BMCR_FULLDPLX;
if (!tg3_readphy(tp, MII_BMCR, &orig_bmcr) &&
(bmcr != orig_bmcr)) {
tg3_writephy(tp, MII_BMCR, BMCR_LOOPBACK);
for (i = 0; i < 1500; i++) {
u32 tmp;
udelay(10);
if (tg3_readphy(tp, MII_BMSR, &tmp) ||
tg3_readphy(tp, MII_BMSR, &tmp))
continue;
if (!(tmp & BMSR_LSTATUS)) {
udelay(40);
break;
}
}
tg3_writephy(tp, MII_BMCR, bmcr);
udelay(40);
}
}
}
static int tg3_init_5401phy_dsp(struct tg3 *tp)
{
int err;
/* Turn off tap power management. */
/* Set Extended packet length bit */
err = tg3_phy_auxctl_write(tp, MII_TG3_AUXCTL_SHDWSEL_AUXCTL, 0x4c20);
err |= tg3_phydsp_write(tp, 0x0012, 0x1804);
err |= tg3_phydsp_write(tp, 0x0013, 0x1204);
err |= tg3_phydsp_write(tp, 0x8006, 0x0132);
err |= tg3_phydsp_write(tp, 0x8006, 0x0232);
err |= tg3_phydsp_write(tp, 0x201f, 0x0a20);
udelay(40);
return err;
}
static bool tg3_phy_copper_an_config_ok(struct tg3 *tp, u32 *lcladv)
{
u32 advmsk, tgtadv, advertising;
advertising = tp->link_config.advertising;
tgtadv = ethtool_adv_to_mii_adv_t(advertising) & ADVERTISE_ALL;
advmsk = ADVERTISE_ALL;
if (tp->link_config.active_duplex == DUPLEX_FULL) {
tgtadv |= mii_advertise_flowctrl(tp->link_config.flowctrl);
advmsk |= ADVERTISE_PAUSE_CAP | ADVERTISE_PAUSE_ASYM;
}
if (tg3_readphy(tp, MII_ADVERTISE, lcladv))
return false;
if ((*lcladv & advmsk) != tgtadv)
return false;
if (!(tp->phy_flags & TG3_PHYFLG_10_100_ONLY)) {
u32 tg3_ctrl;
tgtadv = ethtool_adv_to_mii_ctrl1000_t(advertising);
if (tg3_readphy(tp, MII_CTRL1000, &tg3_ctrl))
return false;
if (tgtadv &&
(tp->pci_chip_rev_id == CHIPREV_ID_5701_A0 ||
tp->pci_chip_rev_id == CHIPREV_ID_5701_B0)) {
tgtadv |= CTL1000_AS_MASTER | CTL1000_ENABLE_MASTER;
tg3_ctrl &= (ADVERTISE_1000HALF | ADVERTISE_1000FULL |
CTL1000_AS_MASTER | CTL1000_ENABLE_MASTER);
} else {
tg3_ctrl &= (ADVERTISE_1000HALF | ADVERTISE_1000FULL);
}
if (tg3_ctrl != tgtadv)
return false;
}
return true;
}
static bool tg3_phy_copper_fetch_rmtadv(struct tg3 *tp, u32 *rmtadv)
{
u32 lpeth = 0;
if (!(tp->phy_flags & TG3_PHYFLG_10_100_ONLY)) {
u32 val;
if (tg3_readphy(tp, MII_STAT1000, &val))
return false;
lpeth = mii_stat1000_to_ethtool_lpa_t(val);
}
if (tg3_readphy(tp, MII_LPA, rmtadv))
return false;
lpeth |= mii_lpa_to_ethtool_lpa_t(*rmtadv);
tp->link_config.rmt_adv = lpeth;
return true;
}
static int tg3_setup_copper_phy(struct tg3 *tp, int force_reset)
{
int current_link_up;
u32 bmsr, val;
u32 lcl_adv, rmt_adv;
u16 current_speed;
u8 current_duplex;
int i, err;
tw32(MAC_EVENT, 0);
tw32_f(MAC_STATUS,
(MAC_STATUS_SYNC_CHANGED |
MAC_STATUS_CFG_CHANGED |
MAC_STATUS_MI_COMPLETION |
MAC_STATUS_LNKSTATE_CHANGED));
udelay(40);
if ((tp->mi_mode & MAC_MI_MODE_AUTO_POLL) != 0) {
tw32_f(MAC_MI_MODE,
(tp->mi_mode & ~MAC_MI_MODE_AUTO_POLL));
udelay(80);
}
tg3_phy_auxctl_write(tp, MII_TG3_AUXCTL_SHDWSEL_PWRCTL, 0);
/* Some third-party PHYs need to be reset on link going
* down.
*/
if ((GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5703 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5704 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5705) &&
netif_carrier_ok(tp->dev)) {
tg3_readphy(tp, MII_BMSR, &bmsr);
if (!tg3_readphy(tp, MII_BMSR, &bmsr) &&
!(bmsr & BMSR_LSTATUS))
force_reset = 1;
}
if (force_reset)
tg3_phy_reset(tp);
if ((tp->phy_id & TG3_PHY_ID_MASK) == TG3_PHY_ID_BCM5401) {
tg3_readphy(tp, MII_BMSR, &bmsr);
if (tg3_readphy(tp, MII_BMSR, &bmsr) ||
!tg3_flag(tp, INIT_COMPLETE))
bmsr = 0;
if (!(bmsr & BMSR_LSTATUS)) {
err = tg3_init_5401phy_dsp(tp);
if (err)
return err;
tg3_readphy(tp, MII_BMSR, &bmsr);
for (i = 0; i < 1000; i++) {
udelay(10);
if (!tg3_readphy(tp, MII_BMSR, &bmsr) &&
(bmsr & BMSR_LSTATUS)) {
udelay(40);
break;
}
}
if ((tp->phy_id & TG3_PHY_ID_REV_MASK) ==
TG3_PHY_REV_BCM5401_B0 &&
!(bmsr & BMSR_LSTATUS) &&
tp->link_config.active_speed == SPEED_1000) {
err = tg3_phy_reset(tp);
if (!err)
err = tg3_init_5401phy_dsp(tp);
if (err)
return err;
}
}
} else if (tp->pci_chip_rev_id == CHIPREV_ID_5701_A0 ||
tp->pci_chip_rev_id == CHIPREV_ID_5701_B0) {
/* 5701 {A0,B0} CRC bug workaround */
tg3_writephy(tp, 0x15, 0x0a75);
tg3_writephy(tp, MII_TG3_MISC_SHDW, 0x8c68);
tg3_writephy(tp, MII_TG3_MISC_SHDW, 0x8d68);
tg3_writephy(tp, MII_TG3_MISC_SHDW, 0x8c68);
}
/* Clear pending interrupts... */
tg3_readphy(tp, MII_TG3_ISTAT, &val);
tg3_readphy(tp, MII_TG3_ISTAT, &val);
if (tp->phy_flags & TG3_PHYFLG_USE_MI_INTERRUPT)
tg3_writephy(tp, MII_TG3_IMASK, ~MII_TG3_INT_LINKCHG);
else if (!(tp->phy_flags & TG3_PHYFLG_IS_FET))
tg3_writephy(tp, MII_TG3_IMASK, ~0);
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5700 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5701) {
if (tp->led_ctrl == LED_CTRL_MODE_PHY_1)
tg3_writephy(tp, MII_TG3_EXT_CTRL,
MII_TG3_EXT_CTRL_LNK3_LED_MODE);
else
tg3_writephy(tp, MII_TG3_EXT_CTRL, 0);
}
current_link_up = 0;
current_speed = SPEED_UNKNOWN;
current_duplex = DUPLEX_UNKNOWN;
tp->phy_flags &= ~TG3_PHYFLG_MDIX_STATE;
tp->link_config.rmt_adv = 0;
if (tp->phy_flags & TG3_PHYFLG_CAPACITIVE_COUPLING) {
err = tg3_phy_auxctl_read(tp,
MII_TG3_AUXCTL_SHDWSEL_MISCTEST,
&val);
if (!err && !(val & (1 << 10))) {
tg3_phy_auxctl_write(tp,
MII_TG3_AUXCTL_SHDWSEL_MISCTEST,
val | (1 << 10));
goto relink;
}
}
bmsr = 0;
for (i = 0; i < 100; i++) {
tg3_readphy(tp, MII_BMSR, &bmsr);
if (!tg3_readphy(tp, MII_BMSR, &bmsr) &&
(bmsr & BMSR_LSTATUS))
break;
udelay(40);
}
if (bmsr & BMSR_LSTATUS) {
u32 aux_stat, bmcr;
tg3_readphy(tp, MII_TG3_AUX_STAT, &aux_stat);
for (i = 0; i < 2000; i++) {
udelay(10);
if (!tg3_readphy(tp, MII_TG3_AUX_STAT, &aux_stat) &&
aux_stat)
break;
}
tg3_aux_stat_to_speed_duplex(tp, aux_stat,
¤t_speed,
¤t_duplex);
bmcr = 0;
for (i = 0; i < 200; i++) {
tg3_readphy(tp, MII_BMCR, &bmcr);
if (tg3_readphy(tp, MII_BMCR, &bmcr))
continue;
if (bmcr && bmcr != 0x7fff)
break;
udelay(10);
}
lcl_adv = 0;
rmt_adv = 0;
tp->link_config.active_speed = current_speed;
tp->link_config.active_duplex = current_duplex;
if (tp->link_config.autoneg == AUTONEG_ENABLE) {
if ((bmcr & BMCR_ANENABLE) &&
tg3_phy_copper_an_config_ok(tp, &lcl_adv) &&
tg3_phy_copper_fetch_rmtadv(tp, &rmt_adv))
current_link_up = 1;
} else {
if (!(bmcr & BMCR_ANENABLE) &&
tp->link_config.speed == current_speed &&
tp->link_config.duplex == current_duplex &&
tp->link_config.flowctrl ==
tp->link_config.active_flowctrl) {
current_link_up = 1;
}
}
if (current_link_up == 1 &&
tp->link_config.active_duplex == DUPLEX_FULL) {
u32 reg, bit;
if (tp->phy_flags & TG3_PHYFLG_IS_FET) {
reg = MII_TG3_FET_GEN_STAT;
bit = MII_TG3_FET_GEN_STAT_MDIXSTAT;
} else {
reg = MII_TG3_EXT_STAT;
bit = MII_TG3_EXT_STAT_MDIX;
}
if (!tg3_readphy(tp, reg, &val) && (val & bit))
tp->phy_flags |= TG3_PHYFLG_MDIX_STATE;
tg3_setup_flow_control(tp, lcl_adv, rmt_adv);
}
}
relink:
if (current_link_up == 0 || (tp->phy_flags & TG3_PHYFLG_IS_LOW_POWER)) {
tg3_phy_copper_begin(tp);
tg3_readphy(tp, MII_BMSR, &bmsr);
if ((!tg3_readphy(tp, MII_BMSR, &bmsr) && (bmsr & BMSR_LSTATUS)) ||
(tp->mac_mode & MAC_MODE_PORT_INT_LPBACK))
current_link_up = 1;
}
tp->mac_mode &= ~MAC_MODE_PORT_MODE_MASK;
if (current_link_up == 1) {
if (tp->link_config.active_speed == SPEED_100 ||
tp->link_config.active_speed == SPEED_10)
tp->mac_mode |= MAC_MODE_PORT_MODE_MII;
else
tp->mac_mode |= MAC_MODE_PORT_MODE_GMII;
} else if (tp->phy_flags & TG3_PHYFLG_IS_FET)
tp->mac_mode |= MAC_MODE_PORT_MODE_MII;
else
tp->mac_mode |= MAC_MODE_PORT_MODE_GMII;
tp->mac_mode &= ~MAC_MODE_HALF_DUPLEX;
if (tp->link_config.active_duplex == DUPLEX_HALF)
tp->mac_mode |= MAC_MODE_HALF_DUPLEX;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5700) {
if (current_link_up == 1 &&
tg3_5700_link_polarity(tp, tp->link_config.active_speed))
tp->mac_mode |= MAC_MODE_LINK_POLARITY;
else
tp->mac_mode &= ~MAC_MODE_LINK_POLARITY;
}
/* ??? Without this setting Netgear GA302T PHY does not
* ??? send/receive packets...
*/
if ((tp->phy_id & TG3_PHY_ID_MASK) == TG3_PHY_ID_BCM5411 &&
tp->pci_chip_rev_id == CHIPREV_ID_5700_ALTIMA) {
tp->mi_mode |= MAC_MI_MODE_AUTO_POLL;
tw32_f(MAC_MI_MODE, tp->mi_mode);
udelay(80);
}
tw32_f(MAC_MODE, tp->mac_mode);
udelay(40);
tg3_phy_eee_adjust(tp, current_link_up);
if (tg3_flag(tp, USE_LINKCHG_REG)) {
/* Polled via timer. */
tw32_f(MAC_EVENT, 0);
} else {
tw32_f(MAC_EVENT, MAC_EVENT_LNKSTATE_CHANGED);
}
udelay(40);
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5700 &&
current_link_up == 1 &&
tp->link_config.active_speed == SPEED_1000 &&
(tg3_flag(tp, PCIX_MODE) || tg3_flag(tp, PCI_HIGH_SPEED))) {
udelay(120);
tw32_f(MAC_STATUS,
(MAC_STATUS_SYNC_CHANGED |
MAC_STATUS_CFG_CHANGED));
udelay(40);
tg3_write_mem(tp,
NIC_SRAM_FIRMWARE_MBOX,
NIC_SRAM_FIRMWARE_MBOX_MAGIC2);
}
/* Prevent send BD corruption. */
if (tg3_flag(tp, CLKREQ_BUG)) {
u16 oldlnkctl, newlnkctl;
pci_read_config_word(tp->pdev,
pci_pcie_cap(tp->pdev) + PCI_EXP_LNKCTL,
&oldlnkctl);
if (tp->link_config.active_speed == SPEED_100 ||
tp->link_config.active_speed == SPEED_10)
newlnkctl = oldlnkctl & ~PCI_EXP_LNKCTL_CLKREQ_EN;
else
newlnkctl = oldlnkctl | PCI_EXP_LNKCTL_CLKREQ_EN;
if (newlnkctl != oldlnkctl)
pci_write_config_word(tp->pdev,
pci_pcie_cap(tp->pdev) +
PCI_EXP_LNKCTL, newlnkctl);
}
if (current_link_up != netif_carrier_ok(tp->dev)) {
if (current_link_up)
netif_carrier_on(tp->dev);
else
netif_carrier_off(tp->dev);
tg3_link_report(tp);
}
return 0;
}
struct tg3_fiber_aneginfo {
int state;
#define ANEG_STATE_UNKNOWN 0
#define ANEG_STATE_AN_ENABLE 1
#define ANEG_STATE_RESTART_INIT 2
#define ANEG_STATE_RESTART 3
#define ANEG_STATE_DISABLE_LINK_OK 4
#define ANEG_STATE_ABILITY_DETECT_INIT 5
#define ANEG_STATE_ABILITY_DETECT 6
#define ANEG_STATE_ACK_DETECT_INIT 7
#define ANEG_STATE_ACK_DETECT 8
#define ANEG_STATE_COMPLETE_ACK_INIT 9
#define ANEG_STATE_COMPLETE_ACK 10
#define ANEG_STATE_IDLE_DETECT_INIT 11
#define ANEG_STATE_IDLE_DETECT 12
#define ANEG_STATE_LINK_OK 13
#define ANEG_STATE_NEXT_PAGE_WAIT_INIT 14
#define ANEG_STATE_NEXT_PAGE_WAIT 15
u32 flags;
#define MR_AN_ENABLE 0x00000001
#define MR_RESTART_AN 0x00000002
#define MR_AN_COMPLETE 0x00000004
#define MR_PAGE_RX 0x00000008
#define MR_NP_LOADED 0x00000010
#define MR_TOGGLE_TX 0x00000020
#define MR_LP_ADV_FULL_DUPLEX 0x00000040
#define MR_LP_ADV_HALF_DUPLEX 0x00000080
#define MR_LP_ADV_SYM_PAUSE 0x00000100
#define MR_LP_ADV_ASYM_PAUSE 0x00000200
#define MR_LP_ADV_REMOTE_FAULT1 0x00000400
#define MR_LP_ADV_REMOTE_FAULT2 0x00000800
#define MR_LP_ADV_NEXT_PAGE 0x00001000
#define MR_TOGGLE_RX 0x00002000
#define MR_NP_RX 0x00004000
#define MR_LINK_OK 0x80000000
unsigned long link_time, cur_time;
u32 ability_match_cfg;
int ability_match_count;
char ability_match, idle_match, ack_match;
u32 txconfig, rxconfig;
#define ANEG_CFG_NP 0x00000080
#define ANEG_CFG_ACK 0x00000040
#define ANEG_CFG_RF2 0x00000020
#define ANEG_CFG_RF1 0x00000010
#define ANEG_CFG_PS2 0x00000001
#define ANEG_CFG_PS1 0x00008000
#define ANEG_CFG_HD 0x00004000
#define ANEG_CFG_FD 0x00002000
#define ANEG_CFG_INVAL 0x00001f06
};
#define ANEG_OK 0
#define ANEG_DONE 1
#define ANEG_TIMER_ENAB 2
#define ANEG_FAILED -1
#define ANEG_STATE_SETTLE_TIME 10000
static int tg3_fiber_aneg_smachine(struct tg3 *tp,
struct tg3_fiber_aneginfo *ap)
{
u16 flowctrl;
unsigned long delta;
u32 rx_cfg_reg;
int ret;
if (ap->state == ANEG_STATE_UNKNOWN) {
ap->rxconfig = 0;
ap->link_time = 0;
ap->cur_time = 0;
ap->ability_match_cfg = 0;
ap->ability_match_count = 0;
ap->ability_match = 0;
ap->idle_match = 0;
ap->ack_match = 0;
}
ap->cur_time++;
if (tr32(MAC_STATUS) & MAC_STATUS_RCVD_CFG) {
rx_cfg_reg = tr32(MAC_RX_AUTO_NEG);
if (rx_cfg_reg != ap->ability_match_cfg) {
ap->ability_match_cfg = rx_cfg_reg;
ap->ability_match = 0;
ap->ability_match_count = 0;
} else {
if (++ap->ability_match_count > 1) {
ap->ability_match = 1;
ap->ability_match_cfg = rx_cfg_reg;
}
}
if (rx_cfg_reg & ANEG_CFG_ACK)
ap->ack_match = 1;
else
ap->ack_match = 0;
ap->idle_match = 0;
} else {
ap->idle_match = 1;
ap->ability_match_cfg = 0;
ap->ability_match_count = 0;
ap->ability_match = 0;
ap->ack_match = 0;
rx_cfg_reg = 0;
}
ap->rxconfig = rx_cfg_reg;
ret = ANEG_OK;
switch (ap->state) {
case ANEG_STATE_UNKNOWN:
if (ap->flags & (MR_AN_ENABLE | MR_RESTART_AN))
ap->state = ANEG_STATE_AN_ENABLE;
/* fallthru */
case ANEG_STATE_AN_ENABLE:
ap->flags &= ~(MR_AN_COMPLETE | MR_PAGE_RX);
if (ap->flags & MR_AN_ENABLE) {
ap->link_time = 0;
ap->cur_time = 0;
ap->ability_match_cfg = 0;
ap->ability_match_count = 0;
ap->ability_match = 0;
ap->idle_match = 0;
ap->ack_match = 0;
ap->state = ANEG_STATE_RESTART_INIT;
} else {
ap->state = ANEG_STATE_DISABLE_LINK_OK;
}
break;
case ANEG_STATE_RESTART_INIT:
ap->link_time = ap->cur_time;
ap->flags &= ~(MR_NP_LOADED);
ap->txconfig = 0;
tw32(MAC_TX_AUTO_NEG, 0);
tp->mac_mode |= MAC_MODE_SEND_CONFIGS;
tw32_f(MAC_MODE, tp->mac_mode);
udelay(40);
ret = ANEG_TIMER_ENAB;
ap->state = ANEG_STATE_RESTART;
/* fallthru */
case ANEG_STATE_RESTART:
delta = ap->cur_time - ap->link_time;
if (delta > ANEG_STATE_SETTLE_TIME)
ap->state = ANEG_STATE_ABILITY_DETECT_INIT;
else
ret = ANEG_TIMER_ENAB;
break;
case ANEG_STATE_DISABLE_LINK_OK:
ret = ANEG_DONE;
break;
case ANEG_STATE_ABILITY_DETECT_INIT:
ap->flags &= ~(MR_TOGGLE_TX);
ap->txconfig = ANEG_CFG_FD;
flowctrl = tg3_advert_flowctrl_1000X(tp->link_config.flowctrl);
if (flowctrl & ADVERTISE_1000XPAUSE)
ap->txconfig |= ANEG_CFG_PS1;
if (flowctrl & ADVERTISE_1000XPSE_ASYM)
ap->txconfig |= ANEG_CFG_PS2;
tw32(MAC_TX_AUTO_NEG, ap->txconfig);
tp->mac_mode |= MAC_MODE_SEND_CONFIGS;
tw32_f(MAC_MODE, tp->mac_mode);
udelay(40);
ap->state = ANEG_STATE_ABILITY_DETECT;
break;
case ANEG_STATE_ABILITY_DETECT:
if (ap->ability_match != 0 && ap->rxconfig != 0)
ap->state = ANEG_STATE_ACK_DETECT_INIT;
break;
case ANEG_STATE_ACK_DETECT_INIT:
ap->txconfig |= ANEG_CFG_ACK;
tw32(MAC_TX_AUTO_NEG, ap->txconfig);
tp->mac_mode |= MAC_MODE_SEND_CONFIGS;
tw32_f(MAC_MODE, tp->mac_mode);
udelay(40);
ap->state = ANEG_STATE_ACK_DETECT;
/* fallthru */
case ANEG_STATE_ACK_DETECT:
if (ap->ack_match != 0) {
if ((ap->rxconfig & ~ANEG_CFG_ACK) ==
(ap->ability_match_cfg & ~ANEG_CFG_ACK)) {
ap->state = ANEG_STATE_COMPLETE_ACK_INIT;
} else {
ap->state = ANEG_STATE_AN_ENABLE;
}
} else if (ap->ability_match != 0 &&
ap->rxconfig == 0) {
ap->state = ANEG_STATE_AN_ENABLE;
}
break;
case ANEG_STATE_COMPLETE_ACK_INIT:
if (ap->rxconfig & ANEG_CFG_INVAL) {
ret = ANEG_FAILED;
break;
}
ap->flags &= ~(MR_LP_ADV_FULL_DUPLEX |
MR_LP_ADV_HALF_DUPLEX |
MR_LP_ADV_SYM_PAUSE |
MR_LP_ADV_ASYM_PAUSE |
MR_LP_ADV_REMOTE_FAULT1 |
MR_LP_ADV_REMOTE_FAULT2 |
MR_LP_ADV_NEXT_PAGE |
MR_TOGGLE_RX |
MR_NP_RX);
if (ap->rxconfig & ANEG_CFG_FD)
ap->flags |= MR_LP_ADV_FULL_DUPLEX;
if (ap->rxconfig & ANEG_CFG_HD)
ap->flags |= MR_LP_ADV_HALF_DUPLEX;
if (ap->rxconfig & ANEG_CFG_PS1)
ap->flags |= MR_LP_ADV_SYM_PAUSE;
if (ap->rxconfig & ANEG_CFG_PS2)
ap->flags |= MR_LP_ADV_ASYM_PAUSE;
if (ap->rxconfig & ANEG_CFG_RF1)
ap->flags |= MR_LP_ADV_REMOTE_FAULT1;
if (ap->rxconfig & ANEG_CFG_RF2)
ap->flags |= MR_LP_ADV_REMOTE_FAULT2;
if (ap->rxconfig & ANEG_CFG_NP)
ap->flags |= MR_LP_ADV_NEXT_PAGE;
ap->link_time = ap->cur_time;
ap->flags ^= (MR_TOGGLE_TX);
if (ap->rxconfig & 0x0008)
ap->flags |= MR_TOGGLE_RX;
if (ap->rxconfig & ANEG_CFG_NP)
ap->flags |= MR_NP_RX;
ap->flags |= MR_PAGE_RX;
ap->state = ANEG_STATE_COMPLETE_ACK;
ret = ANEG_TIMER_ENAB;
break;
case ANEG_STATE_COMPLETE_ACK:
if (ap->ability_match != 0 &&
ap->rxconfig == 0) {
ap->state = ANEG_STATE_AN_ENABLE;
break;
}
delta = ap->cur_time - ap->link_time;
if (delta > ANEG_STATE_SETTLE_TIME) {
if (!(ap->flags & (MR_LP_ADV_NEXT_PAGE))) {
ap->state = ANEG_STATE_IDLE_DETECT_INIT;
} else {
if ((ap->txconfig & ANEG_CFG_NP) == 0 &&
!(ap->flags & MR_NP_RX)) {
ap->state = ANEG_STATE_IDLE_DETECT_INIT;
} else {
ret = ANEG_FAILED;
}
}
}
break;
case ANEG_STATE_IDLE_DETECT_INIT:
ap->link_time = ap->cur_time;
tp->mac_mode &= ~MAC_MODE_SEND_CONFIGS;
tw32_f(MAC_MODE, tp->mac_mode);
udelay(40);
ap->state = ANEG_STATE_IDLE_DETECT;
ret = ANEG_TIMER_ENAB;
break;
case ANEG_STATE_IDLE_DETECT:
if (ap->ability_match != 0 &&
ap->rxconfig == 0) {
ap->state = ANEG_STATE_AN_ENABLE;
break;
}
delta = ap->cur_time - ap->link_time;
if (delta > ANEG_STATE_SETTLE_TIME) {
/* XXX another gem from the Broadcom driver :( */
ap->state = ANEG_STATE_LINK_OK;
}
break;
case ANEG_STATE_LINK_OK:
ap->flags |= (MR_AN_COMPLETE | MR_LINK_OK);
ret = ANEG_DONE;
break;
case ANEG_STATE_NEXT_PAGE_WAIT_INIT:
/* ??? unimplemented */
break;
case ANEG_STATE_NEXT_PAGE_WAIT:
/* ??? unimplemented */
break;
default:
ret = ANEG_FAILED;
break;
}
return ret;
}
static int fiber_autoneg(struct tg3 *tp, u32 *txflags, u32 *rxflags)
{
int res = 0;
struct tg3_fiber_aneginfo aninfo;
int status = ANEG_FAILED;
unsigned int tick;
u32 tmp;
tw32_f(MAC_TX_AUTO_NEG, 0);
tmp = tp->mac_mode & ~MAC_MODE_PORT_MODE_MASK;
tw32_f(MAC_MODE, tmp | MAC_MODE_PORT_MODE_GMII);
udelay(40);
tw32_f(MAC_MODE, tp->mac_mode | MAC_MODE_SEND_CONFIGS);
udelay(40);
memset(&aninfo, 0, sizeof(aninfo));
aninfo.flags |= MR_AN_ENABLE;
aninfo.state = ANEG_STATE_UNKNOWN;
aninfo.cur_time = 0;
tick = 0;
while (++tick < 195000) {
status = tg3_fiber_aneg_smachine(tp, &aninfo);
if (status == ANEG_DONE || status == ANEG_FAILED)
break;
udelay(1);
}
tp->mac_mode &= ~MAC_MODE_SEND_CONFIGS;
tw32_f(MAC_MODE, tp->mac_mode);
udelay(40);
*txflags = aninfo.txconfig;
*rxflags = aninfo.flags;
if (status == ANEG_DONE &&
(aninfo.flags & (MR_AN_COMPLETE | MR_LINK_OK |
MR_LP_ADV_FULL_DUPLEX)))
res = 1;
return res;
}
static void tg3_init_bcm8002(struct tg3 *tp)
{
u32 mac_status = tr32(MAC_STATUS);
int i;
/* Reset when initting first time or we have a link. */
if (tg3_flag(tp, INIT_COMPLETE) &&
!(mac_status & MAC_STATUS_PCS_SYNCED))
return;
/* Set PLL lock range. */
tg3_writephy(tp, 0x16, 0x8007);
/* SW reset */
tg3_writephy(tp, MII_BMCR, BMCR_RESET);
/* Wait for reset to complete. */
/* XXX schedule_timeout() ... */
for (i = 0; i < 500; i++)
udelay(10);
/* Config mode; select PMA/Ch 1 regs. */
tg3_writephy(tp, 0x10, 0x8411);
/* Enable auto-lock and comdet, select txclk for tx. */
tg3_writephy(tp, 0x11, 0x0a10);
tg3_writephy(tp, 0x18, 0x00a0);
tg3_writephy(tp, 0x16, 0x41ff);
/* Assert and deassert POR. */
tg3_writephy(tp, 0x13, 0x0400);
udelay(40);
tg3_writephy(tp, 0x13, 0x0000);
tg3_writephy(tp, 0x11, 0x0a50);
udelay(40);
tg3_writephy(tp, 0x11, 0x0a10);
/* Wait for signal to stabilize */
/* XXX schedule_timeout() ... */
for (i = 0; i < 15000; i++)
udelay(10);
/* Deselect the channel register so we can read the PHYID
* later.
*/
tg3_writephy(tp, 0x10, 0x8011);
}
static int tg3_setup_fiber_hw_autoneg(struct tg3 *tp, u32 mac_status)
{
u16 flowctrl;
u32 sg_dig_ctrl, sg_dig_status;
u32 serdes_cfg, expected_sg_dig_ctrl;
int workaround, port_a;
int current_link_up;
serdes_cfg = 0;
expected_sg_dig_ctrl = 0;
workaround = 0;
port_a = 1;
current_link_up = 0;
if (tp->pci_chip_rev_id != CHIPREV_ID_5704_A0 &&
tp->pci_chip_rev_id != CHIPREV_ID_5704_A1) {
workaround = 1;
if (tr32(TG3PCI_DUAL_MAC_CTRL) & DUAL_MAC_CTRL_ID)
port_a = 0;
/* preserve bits 0-11,13,14 for signal pre-emphasis */
/* preserve bits 20-23 for voltage regulator */
serdes_cfg = tr32(MAC_SERDES_CFG) & 0x00f06fff;
}
sg_dig_ctrl = tr32(SG_DIG_CTRL);
if (tp->link_config.autoneg != AUTONEG_ENABLE) {
if (sg_dig_ctrl & SG_DIG_USING_HW_AUTONEG) {
if (workaround) {
u32 val = serdes_cfg;
if (port_a)
val |= 0xc010000;
else
val |= 0x4010000;
tw32_f(MAC_SERDES_CFG, val);
}
tw32_f(SG_DIG_CTRL, SG_DIG_COMMON_SETUP);
}
if (mac_status & MAC_STATUS_PCS_SYNCED) {
tg3_setup_flow_control(tp, 0, 0);
current_link_up = 1;
}
goto out;
}
/* Want auto-negotiation. */
expected_sg_dig_ctrl = SG_DIG_USING_HW_AUTONEG | SG_DIG_COMMON_SETUP;
flowctrl = tg3_advert_flowctrl_1000X(tp->link_config.flowctrl);
if (flowctrl & ADVERTISE_1000XPAUSE)
expected_sg_dig_ctrl |= SG_DIG_PAUSE_CAP;
if (flowctrl & ADVERTISE_1000XPSE_ASYM)
expected_sg_dig_ctrl |= SG_DIG_ASYM_PAUSE;
if (sg_dig_ctrl != expected_sg_dig_ctrl) {
if ((tp->phy_flags & TG3_PHYFLG_PARALLEL_DETECT) &&
tp->serdes_counter &&
((mac_status & (MAC_STATUS_PCS_SYNCED |
MAC_STATUS_RCVD_CFG)) ==
MAC_STATUS_PCS_SYNCED)) {
tp->serdes_counter--;
current_link_up = 1;
goto out;
}
restart_autoneg:
if (workaround)
tw32_f(MAC_SERDES_CFG, serdes_cfg | 0xc011000);
tw32_f(SG_DIG_CTRL, expected_sg_dig_ctrl | SG_DIG_SOFT_RESET);
udelay(5);
tw32_f(SG_DIG_CTRL, expected_sg_dig_ctrl);
tp->serdes_counter = SERDES_AN_TIMEOUT_5704S;
tp->phy_flags &= ~TG3_PHYFLG_PARALLEL_DETECT;
} else if (mac_status & (MAC_STATUS_PCS_SYNCED |
MAC_STATUS_SIGNAL_DET)) {
sg_dig_status = tr32(SG_DIG_STATUS);
mac_status = tr32(MAC_STATUS);
if ((sg_dig_status & SG_DIG_AUTONEG_COMPLETE) &&
(mac_status & MAC_STATUS_PCS_SYNCED)) {
u32 local_adv = 0, remote_adv = 0;
if (sg_dig_ctrl & SG_DIG_PAUSE_CAP)
local_adv |= ADVERTISE_1000XPAUSE;
if (sg_dig_ctrl & SG_DIG_ASYM_PAUSE)
local_adv |= ADVERTISE_1000XPSE_ASYM;
if (sg_dig_status & SG_DIG_PARTNER_PAUSE_CAPABLE)
remote_adv |= LPA_1000XPAUSE;
if (sg_dig_status & SG_DIG_PARTNER_ASYM_PAUSE)
remote_adv |= LPA_1000XPAUSE_ASYM;
tp->link_config.rmt_adv =
mii_adv_to_ethtool_adv_x(remote_adv);
tg3_setup_flow_control(tp, local_adv, remote_adv);
current_link_up = 1;
tp->serdes_counter = 0;
tp->phy_flags &= ~TG3_PHYFLG_PARALLEL_DETECT;
} else if (!(sg_dig_status & SG_DIG_AUTONEG_COMPLETE)) {
if (tp->serdes_counter)
tp->serdes_counter--;
else {
if (workaround) {
u32 val = serdes_cfg;
if (port_a)
val |= 0xc010000;
else
val |= 0x4010000;
tw32_f(MAC_SERDES_CFG, val);
}
tw32_f(SG_DIG_CTRL, SG_DIG_COMMON_SETUP);
udelay(40);
/* Link parallel detection - link is up */
/* only if we have PCS_SYNC and not */
/* receiving config code words */
mac_status = tr32(MAC_STATUS);
if ((mac_status & MAC_STATUS_PCS_SYNCED) &&
!(mac_status & MAC_STATUS_RCVD_CFG)) {
tg3_setup_flow_control(tp, 0, 0);
current_link_up = 1;
tp->phy_flags |=
TG3_PHYFLG_PARALLEL_DETECT;
tp->serdes_counter =
SERDES_PARALLEL_DET_TIMEOUT;
} else
goto restart_autoneg;
}
}
} else {
tp->serdes_counter = SERDES_AN_TIMEOUT_5704S;
tp->phy_flags &= ~TG3_PHYFLG_PARALLEL_DETECT;
}
out:
return current_link_up;
}
static int tg3_setup_fiber_by_hand(struct tg3 *tp, u32 mac_status)
{
int current_link_up = 0;
if (!(mac_status & MAC_STATUS_PCS_SYNCED))
goto out;
if (tp->link_config.autoneg == AUTONEG_ENABLE) {
u32 txflags, rxflags;
int i;
if (fiber_autoneg(tp, &txflags, &rxflags)) {
u32 local_adv = 0, remote_adv = 0;
if (txflags & ANEG_CFG_PS1)
local_adv |= ADVERTISE_1000XPAUSE;
if (txflags & ANEG_CFG_PS2)
local_adv |= ADVERTISE_1000XPSE_ASYM;
if (rxflags & MR_LP_ADV_SYM_PAUSE)
remote_adv |= LPA_1000XPAUSE;
if (rxflags & MR_LP_ADV_ASYM_PAUSE)
remote_adv |= LPA_1000XPAUSE_ASYM;
tp->link_config.rmt_adv =
mii_adv_to_ethtool_adv_x(remote_adv);
tg3_setup_flow_control(tp, local_adv, remote_adv);
current_link_up = 1;
}
for (i = 0; i < 30; i++) {
udelay(20);
tw32_f(MAC_STATUS,
(MAC_STATUS_SYNC_CHANGED |
MAC_STATUS_CFG_CHANGED));
udelay(40);
if ((tr32(MAC_STATUS) &
(MAC_STATUS_SYNC_CHANGED |
MAC_STATUS_CFG_CHANGED)) == 0)
break;
}
mac_status = tr32(MAC_STATUS);
if (current_link_up == 0 &&
(mac_status & MAC_STATUS_PCS_SYNCED) &&
!(mac_status & MAC_STATUS_RCVD_CFG))
current_link_up = 1;
} else {
tg3_setup_flow_control(tp, 0, 0);
/* Forcing 1000FD link up. */
current_link_up = 1;
tw32_f(MAC_MODE, (tp->mac_mode | MAC_MODE_SEND_CONFIGS));
udelay(40);
tw32_f(MAC_MODE, tp->mac_mode);
udelay(40);
}
out:
return current_link_up;
}
static int tg3_setup_fiber_phy(struct tg3 *tp, int force_reset)
{
u32 orig_pause_cfg;
u16 orig_active_speed;
u8 orig_active_duplex;
u32 mac_status;
int current_link_up;
int i;
orig_pause_cfg = tp->link_config.active_flowctrl;
orig_active_speed = tp->link_config.active_speed;
orig_active_duplex = tp->link_config.active_duplex;
if (!tg3_flag(tp, HW_AUTONEG) &&
netif_carrier_ok(tp->dev) &&
tg3_flag(tp, INIT_COMPLETE)) {
mac_status = tr32(MAC_STATUS);
mac_status &= (MAC_STATUS_PCS_SYNCED |
MAC_STATUS_SIGNAL_DET |
MAC_STATUS_CFG_CHANGED |
MAC_STATUS_RCVD_CFG);
if (mac_status == (MAC_STATUS_PCS_SYNCED |
MAC_STATUS_SIGNAL_DET)) {
tw32_f(MAC_STATUS, (MAC_STATUS_SYNC_CHANGED |
MAC_STATUS_CFG_CHANGED));
return 0;
}
}
tw32_f(MAC_TX_AUTO_NEG, 0);
tp->mac_mode &= ~(MAC_MODE_PORT_MODE_MASK | MAC_MODE_HALF_DUPLEX);
tp->mac_mode |= MAC_MODE_PORT_MODE_TBI;
tw32_f(MAC_MODE, tp->mac_mode);
udelay(40);
if (tp->phy_id == TG3_PHY_ID_BCM8002)
tg3_init_bcm8002(tp);
/* Enable link change event even when serdes polling. */
tw32_f(MAC_EVENT, MAC_EVENT_LNKSTATE_CHANGED);
udelay(40);
current_link_up = 0;
tp->link_config.rmt_adv = 0;
mac_status = tr32(MAC_STATUS);
if (tg3_flag(tp, HW_AUTONEG))
current_link_up = tg3_setup_fiber_hw_autoneg(tp, mac_status);
else
current_link_up = tg3_setup_fiber_by_hand(tp, mac_status);
tp->napi[0].hw_status->status =
(SD_STATUS_UPDATED |
(tp->napi[0].hw_status->status & ~SD_STATUS_LINK_CHG));
for (i = 0; i < 100; i++) {
tw32_f(MAC_STATUS, (MAC_STATUS_SYNC_CHANGED |
MAC_STATUS_CFG_CHANGED));
udelay(5);
if ((tr32(MAC_STATUS) & (MAC_STATUS_SYNC_CHANGED |
MAC_STATUS_CFG_CHANGED |
MAC_STATUS_LNKSTATE_CHANGED)) == 0)
break;
}
mac_status = tr32(MAC_STATUS);
if ((mac_status & MAC_STATUS_PCS_SYNCED) == 0) {
current_link_up = 0;
if (tp->link_config.autoneg == AUTONEG_ENABLE &&
tp->serdes_counter == 0) {
tw32_f(MAC_MODE, (tp->mac_mode |
MAC_MODE_SEND_CONFIGS));
udelay(1);
tw32_f(MAC_MODE, tp->mac_mode);
}
}
if (current_link_up == 1) {
tp->link_config.active_speed = SPEED_1000;
tp->link_config.active_duplex = DUPLEX_FULL;
tw32(MAC_LED_CTRL, (tp->led_ctrl |
LED_CTRL_LNKLED_OVERRIDE |
LED_CTRL_1000MBPS_ON));
} else {
tp->link_config.active_speed = SPEED_UNKNOWN;
tp->link_config.active_duplex = DUPLEX_UNKNOWN;
tw32(MAC_LED_CTRL, (tp->led_ctrl |
LED_CTRL_LNKLED_OVERRIDE |
LED_CTRL_TRAFFIC_OVERRIDE));
}
if (current_link_up != netif_carrier_ok(tp->dev)) {
if (current_link_up)
netif_carrier_on(tp->dev);
else
netif_carrier_off(tp->dev);
tg3_link_report(tp);
} else {
u32 now_pause_cfg = tp->link_config.active_flowctrl;
if (orig_pause_cfg != now_pause_cfg ||
orig_active_speed != tp->link_config.active_speed ||
orig_active_duplex != tp->link_config.active_duplex)
tg3_link_report(tp);
}
return 0;
}
static int tg3_setup_fiber_mii_phy(struct tg3 *tp, int force_reset)
{
int current_link_up, err = 0;
u32 bmsr, bmcr;
u16 current_speed;
u8 current_duplex;
u32 local_adv, remote_adv;
tp->mac_mode |= MAC_MODE_PORT_MODE_GMII;
tw32_f(MAC_MODE, tp->mac_mode);
udelay(40);
tw32(MAC_EVENT, 0);
tw32_f(MAC_STATUS,
(MAC_STATUS_SYNC_CHANGED |
MAC_STATUS_CFG_CHANGED |
MAC_STATUS_MI_COMPLETION |
MAC_STATUS_LNKSTATE_CHANGED));
udelay(40);
if (force_reset)
tg3_phy_reset(tp);
current_link_up = 0;
current_speed = SPEED_UNKNOWN;
current_duplex = DUPLEX_UNKNOWN;
tp->link_config.rmt_adv = 0;
err |= tg3_readphy(tp, MII_BMSR, &bmsr);
err |= tg3_readphy(tp, MII_BMSR, &bmsr);
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5714) {
if (tr32(MAC_TX_STATUS) & TX_STATUS_LINK_UP)
bmsr |= BMSR_LSTATUS;
else
bmsr &= ~BMSR_LSTATUS;
}
err |= tg3_readphy(tp, MII_BMCR, &bmcr);
if ((tp->link_config.autoneg == AUTONEG_ENABLE) && !force_reset &&
(tp->phy_flags & TG3_PHYFLG_PARALLEL_DETECT)) {
/* do nothing, just check for link up at the end */
} else if (tp->link_config.autoneg == AUTONEG_ENABLE) {
u32 adv, newadv;
err |= tg3_readphy(tp, MII_ADVERTISE, &adv);
newadv = adv & ~(ADVERTISE_1000XFULL | ADVERTISE_1000XHALF |
ADVERTISE_1000XPAUSE |
ADVERTISE_1000XPSE_ASYM |
ADVERTISE_SLCT);
newadv |= tg3_advert_flowctrl_1000X(tp->link_config.flowctrl);
newadv |= ethtool_adv_to_mii_adv_x(tp->link_config.advertising);
if ((newadv != adv) || !(bmcr & BMCR_ANENABLE)) {
tg3_writephy(tp, MII_ADVERTISE, newadv);
bmcr |= BMCR_ANENABLE | BMCR_ANRESTART;
tg3_writephy(tp, MII_BMCR, bmcr);
tw32_f(MAC_EVENT, MAC_EVENT_LNKSTATE_CHANGED);
tp->serdes_counter = SERDES_AN_TIMEOUT_5714S;
tp->phy_flags &= ~TG3_PHYFLG_PARALLEL_DETECT;
return err;
}
} else {
u32 new_bmcr;
bmcr &= ~BMCR_SPEED1000;
new_bmcr = bmcr & ~(BMCR_ANENABLE | BMCR_FULLDPLX);
if (tp->link_config.duplex == DUPLEX_FULL)
new_bmcr |= BMCR_FULLDPLX;
if (new_bmcr != bmcr) {
/* BMCR_SPEED1000 is a reserved bit that needs
* to be set on write.
*/
new_bmcr |= BMCR_SPEED1000;
/* Force a linkdown */
if (netif_carrier_ok(tp->dev)) {
u32 adv;
err |= tg3_readphy(tp, MII_ADVERTISE, &adv);
adv &= ~(ADVERTISE_1000XFULL |
ADVERTISE_1000XHALF |
ADVERTISE_SLCT);
tg3_writephy(tp, MII_ADVERTISE, adv);
tg3_writephy(tp, MII_BMCR, bmcr |
BMCR_ANRESTART |
BMCR_ANENABLE);
udelay(10);
netif_carrier_off(tp->dev);
}
tg3_writephy(tp, MII_BMCR, new_bmcr);
bmcr = new_bmcr;
err |= tg3_readphy(tp, MII_BMSR, &bmsr);
err |= tg3_readphy(tp, MII_BMSR, &bmsr);
if (GET_ASIC_REV(tp->pci_chip_rev_id) ==
ASIC_REV_5714) {
if (tr32(MAC_TX_STATUS) & TX_STATUS_LINK_UP)
bmsr |= BMSR_LSTATUS;
else
bmsr &= ~BMSR_LSTATUS;
}
tp->phy_flags &= ~TG3_PHYFLG_PARALLEL_DETECT;
}
}
if (bmsr & BMSR_LSTATUS) {
current_speed = SPEED_1000;
current_link_up = 1;
if (bmcr & BMCR_FULLDPLX)
current_duplex = DUPLEX_FULL;
else
current_duplex = DUPLEX_HALF;
local_adv = 0;
remote_adv = 0;
if (bmcr & BMCR_ANENABLE) {
u32 common;
err |= tg3_readphy(tp, MII_ADVERTISE, &local_adv);
err |= tg3_readphy(tp, MII_LPA, &remote_adv);
common = local_adv & remote_adv;
if (common & (ADVERTISE_1000XHALF |
ADVERTISE_1000XFULL)) {
if (common & ADVERTISE_1000XFULL)
current_duplex = DUPLEX_FULL;
else
current_duplex = DUPLEX_HALF;
tp->link_config.rmt_adv =
mii_adv_to_ethtool_adv_x(remote_adv);
} else if (!tg3_flag(tp, 5780_CLASS)) {
/* Link is up via parallel detect */
} else {
current_link_up = 0;
}
}
}
if (current_link_up == 1 && current_duplex == DUPLEX_FULL)
tg3_setup_flow_control(tp, local_adv, remote_adv);
tp->mac_mode &= ~MAC_MODE_HALF_DUPLEX;
if (tp->link_config.active_duplex == DUPLEX_HALF)
tp->mac_mode |= MAC_MODE_HALF_DUPLEX;
tw32_f(MAC_MODE, tp->mac_mode);
udelay(40);
tw32_f(MAC_EVENT, MAC_EVENT_LNKSTATE_CHANGED);
tp->link_config.active_speed = current_speed;
tp->link_config.active_duplex = current_duplex;
if (current_link_up != netif_carrier_ok(tp->dev)) {
if (current_link_up)
netif_carrier_on(tp->dev);
else {
netif_carrier_off(tp->dev);
tp->phy_flags &= ~TG3_PHYFLG_PARALLEL_DETECT;
}
tg3_link_report(tp);
}
return err;
}
static void tg3_serdes_parallel_detect(struct tg3 *tp)
{
if (tp->serdes_counter) {
/* Give autoneg time to complete. */
tp->serdes_counter--;
return;
}
if (!netif_carrier_ok(tp->dev) &&
(tp->link_config.autoneg == AUTONEG_ENABLE)) {
u32 bmcr;
tg3_readphy(tp, MII_BMCR, &bmcr);
if (bmcr & BMCR_ANENABLE) {
u32 phy1, phy2;
/* Select shadow register 0x1f */
tg3_writephy(tp, MII_TG3_MISC_SHDW, 0x7c00);
tg3_readphy(tp, MII_TG3_MISC_SHDW, &phy1);
/* Select expansion interrupt status register */
tg3_writephy(tp, MII_TG3_DSP_ADDRESS,
MII_TG3_DSP_EXP1_INT_STAT);
tg3_readphy(tp, MII_TG3_DSP_RW_PORT, &phy2);
tg3_readphy(tp, MII_TG3_DSP_RW_PORT, &phy2);
if ((phy1 & 0x10) && !(phy2 & 0x20)) {
/* We have signal detect and not receiving
* config code words, link is up by parallel
* detection.
*/
bmcr &= ~BMCR_ANENABLE;
bmcr |= BMCR_SPEED1000 | BMCR_FULLDPLX;
tg3_writephy(tp, MII_BMCR, bmcr);
tp->phy_flags |= TG3_PHYFLG_PARALLEL_DETECT;
}
}
} else if (netif_carrier_ok(tp->dev) &&
(tp->link_config.autoneg == AUTONEG_ENABLE) &&
(tp->phy_flags & TG3_PHYFLG_PARALLEL_DETECT)) {
u32 phy2;
/* Select expansion interrupt status register */
tg3_writephy(tp, MII_TG3_DSP_ADDRESS,
MII_TG3_DSP_EXP1_INT_STAT);
tg3_readphy(tp, MII_TG3_DSP_RW_PORT, &phy2);
if (phy2 & 0x20) {
u32 bmcr;
/* Config code words received, turn on autoneg. */
tg3_readphy(tp, MII_BMCR, &bmcr);
tg3_writephy(tp, MII_BMCR, bmcr | BMCR_ANENABLE);
tp->phy_flags &= ~TG3_PHYFLG_PARALLEL_DETECT;
}
}
}
static int tg3_setup_phy(struct tg3 *tp, int force_reset)
{
u32 val;
int err;
if (tp->phy_flags & TG3_PHYFLG_PHY_SERDES)
err = tg3_setup_fiber_phy(tp, force_reset);
else if (tp->phy_flags & TG3_PHYFLG_MII_SERDES)
err = tg3_setup_fiber_mii_phy(tp, force_reset);
else
err = tg3_setup_copper_phy(tp, force_reset);
if (GET_CHIP_REV(tp->pci_chip_rev_id) == CHIPREV_5784_AX) {
u32 scale;
val = tr32(TG3_CPMU_CLCK_STAT) & CPMU_CLCK_STAT_MAC_CLCK_MASK;
if (val == CPMU_CLCK_STAT_MAC_CLCK_62_5)
scale = 65;
else if (val == CPMU_CLCK_STAT_MAC_CLCK_6_25)
scale = 6;
else
scale = 12;
val = tr32(GRC_MISC_CFG) & ~GRC_MISC_CFG_PRESCALAR_MASK;
val |= (scale << GRC_MISC_CFG_PRESCALAR_SHIFT);
tw32(GRC_MISC_CFG, val);
}
val = (2 << TX_LENGTHS_IPG_CRS_SHIFT) |
(6 << TX_LENGTHS_IPG_SHIFT);
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5720)
val |= tr32(MAC_TX_LENGTHS) &
(TX_LENGTHS_JMB_FRM_LEN_MSK |
TX_LENGTHS_CNT_DWN_VAL_MSK);
if (tp->link_config.active_speed == SPEED_1000 &&
tp->link_config.active_duplex == DUPLEX_HALF)
tw32(MAC_TX_LENGTHS, val |
(0xff << TX_LENGTHS_SLOT_TIME_SHIFT));
else
tw32(MAC_TX_LENGTHS, val |
(32 << TX_LENGTHS_SLOT_TIME_SHIFT));
if (!tg3_flag(tp, 5705_PLUS)) {
if (netif_carrier_ok(tp->dev)) {
tw32(HOSTCC_STAT_COAL_TICKS,
tp->coal.stats_block_coalesce_usecs);
} else {
tw32(HOSTCC_STAT_COAL_TICKS, 0);
}
}
if (tg3_flag(tp, ASPM_WORKAROUND)) {
val = tr32(PCIE_PWR_MGMT_THRESH);
if (!netif_carrier_ok(tp->dev))
val = (val & ~PCIE_PWR_MGMT_L1_THRESH_MSK) |
tp->pwrmgmt_thresh;
else
val |= PCIE_PWR_MGMT_L1_THRESH_MSK;
tw32(PCIE_PWR_MGMT_THRESH, val);
}
return err;
}
static inline int tg3_irq_sync(struct tg3 *tp)
{
return tp->irq_sync;
}
static inline void tg3_rd32_loop(struct tg3 *tp, u32 *dst, u32 off, u32 len)
{
int i;
dst = (u32 *)((u8 *)dst + off);
for (i = 0; i < len; i += sizeof(u32))
*dst++ = tr32(off + i);
}
static void tg3_dump_legacy_regs(struct tg3 *tp, u32 *regs)
{
tg3_rd32_loop(tp, regs, TG3PCI_VENDOR, 0xb0);
tg3_rd32_loop(tp, regs, MAILBOX_INTERRUPT_0, 0x200);
tg3_rd32_loop(tp, regs, MAC_MODE, 0x4f0);
tg3_rd32_loop(tp, regs, SNDDATAI_MODE, 0xe0);
tg3_rd32_loop(tp, regs, SNDDATAC_MODE, 0x04);
tg3_rd32_loop(tp, regs, SNDBDS_MODE, 0x80);
tg3_rd32_loop(tp, regs, SNDBDI_MODE, 0x48);
tg3_rd32_loop(tp, regs, SNDBDC_MODE, 0x04);
tg3_rd32_loop(tp, regs, RCVLPC_MODE, 0x20);
tg3_rd32_loop(tp, regs, RCVLPC_SELLST_BASE, 0x15c);
tg3_rd32_loop(tp, regs, RCVDBDI_MODE, 0x0c);
tg3_rd32_loop(tp, regs, RCVDBDI_JUMBO_BD, 0x3c);
tg3_rd32_loop(tp, regs, RCVDBDI_BD_PROD_IDX_0, 0x44);
tg3_rd32_loop(tp, regs, RCVDCC_MODE, 0x04);
tg3_rd32_loop(tp, regs, RCVBDI_MODE, 0x20);
tg3_rd32_loop(tp, regs, RCVCC_MODE, 0x14);
tg3_rd32_loop(tp, regs, RCVLSC_MODE, 0x08);
tg3_rd32_loop(tp, regs, MBFREE_MODE, 0x08);
tg3_rd32_loop(tp, regs, HOSTCC_MODE, 0x100);
if (tg3_flag(tp, SUPPORT_MSIX))
tg3_rd32_loop(tp, regs, HOSTCC_RXCOL_TICKS_VEC1, 0x180);
tg3_rd32_loop(tp, regs, MEMARB_MODE, 0x10);
tg3_rd32_loop(tp, regs, BUFMGR_MODE, 0x58);
tg3_rd32_loop(tp, regs, RDMAC_MODE, 0x08);
tg3_rd32_loop(tp, regs, WDMAC_MODE, 0x08);
tg3_rd32_loop(tp, regs, RX_CPU_MODE, 0x04);
tg3_rd32_loop(tp, regs, RX_CPU_STATE, 0x04);
tg3_rd32_loop(tp, regs, RX_CPU_PGMCTR, 0x04);
tg3_rd32_loop(tp, regs, RX_CPU_HWBKPT, 0x04);
if (!tg3_flag(tp, 5705_PLUS)) {
tg3_rd32_loop(tp, regs, TX_CPU_MODE, 0x04);
tg3_rd32_loop(tp, regs, TX_CPU_STATE, 0x04);
tg3_rd32_loop(tp, regs, TX_CPU_PGMCTR, 0x04);
}
tg3_rd32_loop(tp, regs, GRCMBOX_INTERRUPT_0, 0x110);
tg3_rd32_loop(tp, regs, FTQ_RESET, 0x120);
tg3_rd32_loop(tp, regs, MSGINT_MODE, 0x0c);
tg3_rd32_loop(tp, regs, DMAC_MODE, 0x04);
tg3_rd32_loop(tp, regs, GRC_MODE, 0x4c);
if (tg3_flag(tp, NVRAM))
tg3_rd32_loop(tp, regs, NVRAM_CMD, 0x24);
}
static void tg3_dump_state(struct tg3 *tp)
{
int i;
u32 *regs;
regs = kzalloc(TG3_REG_BLK_SIZE, GFP_ATOMIC);
if (!regs) {
netdev_err(tp->dev, "Failed allocating register dump buffer\n");
return;
}
if (tg3_flag(tp, PCI_EXPRESS)) {
/* Read up to but not including private PCI registers */
for (i = 0; i < TG3_PCIE_TLDLPL_PORT; i += sizeof(u32))
regs[i / sizeof(u32)] = tr32(i);
} else
tg3_dump_legacy_regs(tp, regs);
for (i = 0; i < TG3_REG_BLK_SIZE / sizeof(u32); i += 4) {
if (!regs[i + 0] && !regs[i + 1] &&
!regs[i + 2] && !regs[i + 3])
continue;
netdev_err(tp->dev, "0x%08x: 0x%08x, 0x%08x, 0x%08x, 0x%08x\n",
i * 4,
regs[i + 0], regs[i + 1], regs[i + 2], regs[i + 3]);
}
kfree(regs);
for (i = 0; i < tp->irq_cnt; i++) {
struct tg3_napi *tnapi = &tp->napi[i];
/* SW status block */
netdev_err(tp->dev,
"%d: Host status block [%08x:%08x:(%04x:%04x:%04x):(%04x:%04x)]\n",
i,
tnapi->hw_status->status,
tnapi->hw_status->status_tag,
tnapi->hw_status->rx_jumbo_consumer,
tnapi->hw_status->rx_consumer,
tnapi->hw_status->rx_mini_consumer,
tnapi->hw_status->idx[0].rx_producer,
tnapi->hw_status->idx[0].tx_consumer);
netdev_err(tp->dev,
"%d: NAPI info [%08x:%08x:(%04x:%04x:%04x):%04x:(%04x:%04x:%04x:%04x)]\n",
i,
tnapi->last_tag, tnapi->last_irq_tag,
tnapi->tx_prod, tnapi->tx_cons, tnapi->tx_pending,
tnapi->rx_rcb_ptr,
tnapi->prodring.rx_std_prod_idx,
tnapi->prodring.rx_std_cons_idx,
tnapi->prodring.rx_jmb_prod_idx,
tnapi->prodring.rx_jmb_cons_idx);
}
}
/* This is called whenever we suspect that the system chipset is re-
* ordering the sequence of MMIO to the tx send mailbox. The symptom
* is bogus tx completions. We try to recover by setting the
* TG3_FLAG_MBOX_WRITE_REORDER flag and resetting the chip later
* in the workqueue.
*/
static void tg3_tx_recover(struct tg3 *tp)
{
BUG_ON(tg3_flag(tp, MBOX_WRITE_REORDER) ||
tp->write32_tx_mbox == tg3_write_indirect_mbox);
netdev_warn(tp->dev,
"The system may be re-ordering memory-mapped I/O "
"cycles to the network device, attempting to recover. "
"Please report the problem to the driver maintainer "
"and include system chipset information.\n");
spin_lock(&tp->lock);
tg3_flag_set(tp, TX_RECOVERY_PENDING);
spin_unlock(&tp->lock);
}
static inline u32 tg3_tx_avail(struct tg3_napi *tnapi)
{
/* Tell compiler to fetch tx indices from memory. */
barrier();
return tnapi->tx_pending -
((tnapi->tx_prod - tnapi->tx_cons) & (TG3_TX_RING_SIZE - 1));
}
/* Tigon3 never reports partial packet sends. So we do not
* need special logic to handle SKBs that have not had all
* of their frags sent yet, like SunGEM does.
*/
static void tg3_tx(struct tg3_napi *tnapi)
{
struct tg3 *tp = tnapi->tp;
u32 hw_idx = tnapi->hw_status->idx[0].tx_consumer;
u32 sw_idx = tnapi->tx_cons;
struct netdev_queue *txq;
int index = tnapi - tp->napi;
unsigned int pkts_compl = 0, bytes_compl = 0;
if (tg3_flag(tp, ENABLE_TSS))
index--;
txq = netdev_get_tx_queue(tp->dev, index);
while (sw_idx != hw_idx) {
struct tg3_tx_ring_info *ri = &tnapi->tx_buffers[sw_idx];
struct sk_buff *skb = ri->skb;
int i, tx_bug = 0;
if (unlikely(skb == NULL)) {
tg3_tx_recover(tp);
return;
}
pci_unmap_single(tp->pdev,
dma_unmap_addr(ri, mapping),
skb_headlen(skb),
PCI_DMA_TODEVICE);
ri->skb = NULL;
while (ri->fragmented) {
ri->fragmented = false;
sw_idx = NEXT_TX(sw_idx);
ri = &tnapi->tx_buffers[sw_idx];
}
sw_idx = NEXT_TX(sw_idx);
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
ri = &tnapi->tx_buffers[sw_idx];
if (unlikely(ri->skb != NULL || sw_idx == hw_idx))
tx_bug = 1;
pci_unmap_page(tp->pdev,
dma_unmap_addr(ri, mapping),
skb_frag_size(&skb_shinfo(skb)->frags[i]),
PCI_DMA_TODEVICE);
while (ri->fragmented) {
ri->fragmented = false;
sw_idx = NEXT_TX(sw_idx);
ri = &tnapi->tx_buffers[sw_idx];
}
sw_idx = NEXT_TX(sw_idx);
}
pkts_compl++;
bytes_compl += skb->len;
dev_kfree_skb(skb);
if (unlikely(tx_bug)) {
tg3_tx_recover(tp);
return;
}
}
netdev_tx_completed_queue(txq, pkts_compl, bytes_compl);
tnapi->tx_cons = sw_idx;
/* Need to make the tx_cons update visible to tg3_start_xmit()
* before checking for netif_queue_stopped(). Without the
* memory barrier, there is a small possibility that tg3_start_xmit()
* will miss it and cause the queue to be stopped forever.
*/
smp_mb();
if (unlikely(netif_tx_queue_stopped(txq) &&
(tg3_tx_avail(tnapi) > TG3_TX_WAKEUP_THRESH(tnapi)))) {
__netif_tx_lock(txq, smp_processor_id());
if (netif_tx_queue_stopped(txq) &&
(tg3_tx_avail(tnapi) > TG3_TX_WAKEUP_THRESH(tnapi)))
netif_tx_wake_queue(txq);
__netif_tx_unlock(txq);
}
}
static void tg3_rx_data_free(struct tg3 *tp, struct ring_info *ri, u32 map_sz)
{
if (!ri->data)
return;
pci_unmap_single(tp->pdev, dma_unmap_addr(ri, mapping),
map_sz, PCI_DMA_FROMDEVICE);
kfree(ri->data);
ri->data = NULL;
}
/* Returns size of skb allocated or < 0 on error.
*
* We only need to fill in the address because the other members
* of the RX descriptor are invariant, see tg3_init_rings.
*
* Note the purposeful assymetry of cpu vs. chip accesses. For
* posting buffers we only dirty the first cache line of the RX
* descriptor (containing the address). Whereas for the RX status
* buffers the cpu only reads the last cacheline of the RX descriptor
* (to fetch the error flags, vlan tag, checksum, and opaque cookie).
*/
static int tg3_alloc_rx_data(struct tg3 *tp, struct tg3_rx_prodring_set *tpr,
u32 opaque_key, u32 dest_idx_unmasked)
{
struct tg3_rx_buffer_desc *desc;
struct ring_info *map;
u8 *data;
dma_addr_t mapping;
int skb_size, data_size, dest_idx;
switch (opaque_key) {
case RXD_OPAQUE_RING_STD:
dest_idx = dest_idx_unmasked & tp->rx_std_ring_mask;
desc = &tpr->rx_std[dest_idx];
map = &tpr->rx_std_buffers[dest_idx];
data_size = tp->rx_pkt_map_sz;
break;
case RXD_OPAQUE_RING_JUMBO:
dest_idx = dest_idx_unmasked & tp->rx_jmb_ring_mask;
desc = &tpr->rx_jmb[dest_idx].std;
map = &tpr->rx_jmb_buffers[dest_idx];
data_size = TG3_RX_JMB_MAP_SZ;
break;
default:
return -EINVAL;
}
/* Do not overwrite any of the map or rp information
* until we are sure we can commit to a new buffer.
*
* Callers depend upon this behavior and assume that
* we leave everything unchanged if we fail.
*/
skb_size = SKB_DATA_ALIGN(data_size + TG3_RX_OFFSET(tp)) +
SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
data = kmalloc(skb_size, GFP_ATOMIC);
if (!data)
return -ENOMEM;
mapping = pci_map_single(tp->pdev,
data + TG3_RX_OFFSET(tp),
data_size,
PCI_DMA_FROMDEVICE);
if (pci_dma_mapping_error(tp->pdev, mapping)) {
kfree(data);
return -EIO;
}
map->data = data;
dma_unmap_addr_set(map, mapping, mapping);
desc->addr_hi = ((u64)mapping >> 32);
desc->addr_lo = ((u64)mapping & 0xffffffff);
return data_size;
}
/* We only need to move over in the address because the other
* members of the RX descriptor are invariant. See notes above
* tg3_alloc_rx_data for full details.
*/
static void tg3_recycle_rx(struct tg3_napi *tnapi,
struct tg3_rx_prodring_set *dpr,
u32 opaque_key, int src_idx,
u32 dest_idx_unmasked)
{
struct tg3 *tp = tnapi->tp;
struct tg3_rx_buffer_desc *src_desc, *dest_desc;
struct ring_info *src_map, *dest_map;
struct tg3_rx_prodring_set *spr = &tp->napi[0].prodring;
int dest_idx;
switch (opaque_key) {
case RXD_OPAQUE_RING_STD:
dest_idx = dest_idx_unmasked & tp->rx_std_ring_mask;
dest_desc = &dpr->rx_std[dest_idx];
dest_map = &dpr->rx_std_buffers[dest_idx];
src_desc = &spr->rx_std[src_idx];
src_map = &spr->rx_std_buffers[src_idx];
break;
case RXD_OPAQUE_RING_JUMBO:
dest_idx = dest_idx_unmasked & tp->rx_jmb_ring_mask;
dest_desc = &dpr->rx_jmb[dest_idx].std;
dest_map = &dpr->rx_jmb_buffers[dest_idx];
src_desc = &spr->rx_jmb[src_idx].std;
src_map = &spr->rx_jmb_buffers[src_idx];
break;
default:
return;
}
dest_map->data = src_map->data;
dma_unmap_addr_set(dest_map, mapping,
dma_unmap_addr(src_map, mapping));
dest_desc->addr_hi = src_desc->addr_hi;
dest_desc->addr_lo = src_desc->addr_lo;
/* Ensure that the update to the skb happens after the physical
* addresses have been transferred to the new BD location.
*/
smp_wmb();
src_map->data = NULL;
}
/* The RX ring scheme is composed of multiple rings which post fresh
* buffers to the chip, and one special ring the chip uses to report
* status back to the host.
*
* The special ring reports the status of received packets to the
* host. The chip does not write into the original descriptor the
* RX buffer was obtained from. The chip simply takes the original
* descriptor as provided by the host, updates the status and length
* field, then writes this into the next status ring entry.
*
* Each ring the host uses to post buffers to the chip is described
* by a TG3_BDINFO entry in the chips SRAM area. When a packet arrives,
* it is first placed into the on-chip ram. When the packet's length
* is known, it walks down the TG3_BDINFO entries to select the ring.
* Each TG3_BDINFO specifies a MAXLEN field and the first TG3_BDINFO
* which is within the range of the new packet's length is chosen.
*
* The "separate ring for rx status" scheme may sound queer, but it makes
* sense from a cache coherency perspective. If only the host writes
* to the buffer post rings, and only the chip writes to the rx status
* rings, then cache lines never move beyond shared-modified state.
* If both the host and chip were to write into the same ring, cache line
* eviction could occur since both entities want it in an exclusive state.
*/
static int tg3_rx(struct tg3_napi *tnapi, int budget)
{
struct tg3 *tp = tnapi->tp;
u32 work_mask, rx_std_posted = 0;
u32 std_prod_idx, jmb_prod_idx;
u32 sw_idx = tnapi->rx_rcb_ptr;
u16 hw_idx;
int received;
struct tg3_rx_prodring_set *tpr = &tnapi->prodring;
hw_idx = *(tnapi->rx_rcb_prod_idx);
/*
* We need to order the read of hw_idx and the read of
* the opaque cookie.
*/
rmb();
work_mask = 0;
received = 0;
std_prod_idx = tpr->rx_std_prod_idx;
jmb_prod_idx = tpr->rx_jmb_prod_idx;
while (sw_idx != hw_idx && budget > 0) {
struct ring_info *ri;
struct tg3_rx_buffer_desc *desc = &tnapi->rx_rcb[sw_idx];
unsigned int len;
struct sk_buff *skb;
dma_addr_t dma_addr;
u32 opaque_key, desc_idx, *post_ptr;
u8 *data;
desc_idx = desc->opaque & RXD_OPAQUE_INDEX_MASK;
opaque_key = desc->opaque & RXD_OPAQUE_RING_MASK;
if (opaque_key == RXD_OPAQUE_RING_STD) {
ri = &tp->napi[0].prodring.rx_std_buffers[desc_idx];
dma_addr = dma_unmap_addr(ri, mapping);
data = ri->data;
post_ptr = &std_prod_idx;
rx_std_posted++;
} else if (opaque_key == RXD_OPAQUE_RING_JUMBO) {
ri = &tp->napi[0].prodring.rx_jmb_buffers[desc_idx];
dma_addr = dma_unmap_addr(ri, mapping);
data = ri->data;
post_ptr = &jmb_prod_idx;
} else
goto next_pkt_nopost;
work_mask |= opaque_key;
if ((desc->err_vlan & RXD_ERR_MASK) != 0 &&
(desc->err_vlan != RXD_ERR_ODD_NIBBLE_RCVD_MII)) {
drop_it:
tg3_recycle_rx(tnapi, tpr, opaque_key,
desc_idx, *post_ptr);
drop_it_no_recycle:
/* Other statistics kept track of by card. */
tp->rx_dropped++;
goto next_pkt;
}
prefetch(data + TG3_RX_OFFSET(tp));
len = ((desc->idx_len & RXD_LEN_MASK) >> RXD_LEN_SHIFT) -
ETH_FCS_LEN;
if (len > TG3_RX_COPY_THRESH(tp)) {
int skb_size;
skb_size = tg3_alloc_rx_data(tp, tpr, opaque_key,
*post_ptr);
if (skb_size < 0)
goto drop_it;
pci_unmap_single(tp->pdev, dma_addr, skb_size,
PCI_DMA_FROMDEVICE);
skb = build_skb(data);
if (!skb) {
kfree(data);
goto drop_it_no_recycle;
}
skb_reserve(skb, TG3_RX_OFFSET(tp));
/* Ensure that the update to the data happens
* after the usage of the old DMA mapping.
*/
smp_wmb();
ri->data = NULL;
} else {
tg3_recycle_rx(tnapi, tpr, opaque_key,
desc_idx, *post_ptr);
skb = netdev_alloc_skb(tp->dev,
len + TG3_RAW_IP_ALIGN);
if (skb == NULL)
goto drop_it_no_recycle;
skb_reserve(skb, TG3_RAW_IP_ALIGN);
pci_dma_sync_single_for_cpu(tp->pdev, dma_addr, len, PCI_DMA_FROMDEVICE);
memcpy(skb->data,
data + TG3_RX_OFFSET(tp),
len);
pci_dma_sync_single_for_device(tp->pdev, dma_addr, len, PCI_DMA_FROMDEVICE);
}
skb_put(skb, len);
if ((tp->dev->features & NETIF_F_RXCSUM) &&
(desc->type_flags & RXD_FLAG_TCPUDP_CSUM) &&
(((desc->ip_tcp_csum & RXD_TCPCSUM_MASK)
>> RXD_TCPCSUM_SHIFT) == 0xffff))
skb->ip_summed = CHECKSUM_UNNECESSARY;
else
skb_checksum_none_assert(skb);
skb->protocol = eth_type_trans(skb, tp->dev);
if (len > (tp->dev->mtu + ETH_HLEN) &&
skb->protocol != htons(ETH_P_8021Q)) {
dev_kfree_skb(skb);
goto drop_it_no_recycle;
}
if (desc->type_flags & RXD_FLAG_VLAN &&
!(tp->rx_mode & RX_MODE_KEEP_VLAN_TAG))
__vlan_hwaccel_put_tag(skb,
desc->err_vlan & RXD_VLAN_MASK);
napi_gro_receive(&tnapi->napi, skb);
received++;
budget--;
next_pkt:
(*post_ptr)++;
if (unlikely(rx_std_posted >= tp->rx_std_max_post)) {
tpr->rx_std_prod_idx = std_prod_idx &
tp->rx_std_ring_mask;
tw32_rx_mbox(TG3_RX_STD_PROD_IDX_REG,
tpr->rx_std_prod_idx);
work_mask &= ~RXD_OPAQUE_RING_STD;
rx_std_posted = 0;
}
next_pkt_nopost:
sw_idx++;
sw_idx &= tp->rx_ret_ring_mask;
/* Refresh hw_idx to see if there is new work */
if (sw_idx == hw_idx) {
hw_idx = *(tnapi->rx_rcb_prod_idx);
rmb();
}
}
/* ACK the status ring. */
tnapi->rx_rcb_ptr = sw_idx;
tw32_rx_mbox(tnapi->consmbox, sw_idx);
/* Refill RX ring(s). */
if (!tg3_flag(tp, ENABLE_RSS)) {
/* Sync BD data before updating mailbox */
wmb();
if (work_mask & RXD_OPAQUE_RING_STD) {
tpr->rx_std_prod_idx = std_prod_idx &
tp->rx_std_ring_mask;
tw32_rx_mbox(TG3_RX_STD_PROD_IDX_REG,
tpr->rx_std_prod_idx);
}
if (work_mask & RXD_OPAQUE_RING_JUMBO) {
tpr->rx_jmb_prod_idx = jmb_prod_idx &
tp->rx_jmb_ring_mask;
tw32_rx_mbox(TG3_RX_JMB_PROD_IDX_REG,
tpr->rx_jmb_prod_idx);
}
mmiowb();
} else if (work_mask) {
/* rx_std_buffers[] and rx_jmb_buffers[] entries must be
* updated before the producer indices can be updated.
*/
smp_wmb();
tpr->rx_std_prod_idx = std_prod_idx & tp->rx_std_ring_mask;
tpr->rx_jmb_prod_idx = jmb_prod_idx & tp->rx_jmb_ring_mask;
if (tnapi != &tp->napi[1]) {
tp->rx_refill = true;
napi_schedule(&tp->napi[1].napi);
}
}
return received;
}
static void tg3_poll_link(struct tg3 *tp)
{
/* handle link change and other phy events */
if (!(tg3_flag(tp, USE_LINKCHG_REG) || tg3_flag(tp, POLL_SERDES))) {
struct tg3_hw_status *sblk = tp->napi[0].hw_status;
if (sblk->status & SD_STATUS_LINK_CHG) {
sblk->status = SD_STATUS_UPDATED |
(sblk->status & ~SD_STATUS_LINK_CHG);
spin_lock(&tp->lock);
if (tg3_flag(tp, USE_PHYLIB)) {
tw32_f(MAC_STATUS,
(MAC_STATUS_SYNC_CHANGED |
MAC_STATUS_CFG_CHANGED |
MAC_STATUS_MI_COMPLETION |
MAC_STATUS_LNKSTATE_CHANGED));
udelay(40);
} else
tg3_setup_phy(tp, 0);
spin_unlock(&tp->lock);
}
}
}
static int tg3_rx_prodring_xfer(struct tg3 *tp,
struct tg3_rx_prodring_set *dpr,
struct tg3_rx_prodring_set *spr)
{
u32 si, di, cpycnt, src_prod_idx;
int i, err = 0;
while (1) {
src_prod_idx = spr->rx_std_prod_idx;
/* Make sure updates to the rx_std_buffers[] entries and the
* standard producer index are seen in the correct order.
*/
smp_rmb();
if (spr->rx_std_cons_idx == src_prod_idx)
break;
if (spr->rx_std_cons_idx < src_prod_idx)
cpycnt = src_prod_idx - spr->rx_std_cons_idx;
else
cpycnt = tp->rx_std_ring_mask + 1 -
spr->rx_std_cons_idx;
cpycnt = min(cpycnt,
tp->rx_std_ring_mask + 1 - dpr->rx_std_prod_idx);
si = spr->rx_std_cons_idx;
di = dpr->rx_std_prod_idx;
for (i = di; i < di + cpycnt; i++) {
if (dpr->rx_std_buffers[i].data) {
cpycnt = i - di;
err = -ENOSPC;
break;
}
}
if (!cpycnt)
break;
/* Ensure that updates to the rx_std_buffers ring and the
* shadowed hardware producer ring from tg3_recycle_skb() are
* ordered correctly WRT the skb check above.
*/
smp_rmb();
memcpy(&dpr->rx_std_buffers[di],
&spr->rx_std_buffers[si],
cpycnt * sizeof(struct ring_info));
for (i = 0; i < cpycnt; i++, di++, si++) {
struct tg3_rx_buffer_desc *sbd, *dbd;
sbd = &spr->rx_std[si];
dbd = &dpr->rx_std[di];
dbd->addr_hi = sbd->addr_hi;
dbd->addr_lo = sbd->addr_lo;
}
spr->rx_std_cons_idx = (spr->rx_std_cons_idx + cpycnt) &
tp->rx_std_ring_mask;
dpr->rx_std_prod_idx = (dpr->rx_std_prod_idx + cpycnt) &
tp->rx_std_ring_mask;
}
while (1) {
src_prod_idx = spr->rx_jmb_prod_idx;
/* Make sure updates to the rx_jmb_buffers[] entries and
* the jumbo producer index are seen in the correct order.
*/
smp_rmb();
if (spr->rx_jmb_cons_idx == src_prod_idx)
break;
if (spr->rx_jmb_cons_idx < src_prod_idx)
cpycnt = src_prod_idx - spr->rx_jmb_cons_idx;
else
cpycnt = tp->rx_jmb_ring_mask + 1 -
spr->rx_jmb_cons_idx;
cpycnt = min(cpycnt,
tp->rx_jmb_ring_mask + 1 - dpr->rx_jmb_prod_idx);
si = spr->rx_jmb_cons_idx;
di = dpr->rx_jmb_prod_idx;
for (i = di; i < di + cpycnt; i++) {
if (dpr->rx_jmb_buffers[i].data) {
cpycnt = i - di;
err = -ENOSPC;
break;
}
}
if (!cpycnt)
break;
/* Ensure that updates to the rx_jmb_buffers ring and the
* shadowed hardware producer ring from tg3_recycle_skb() are
* ordered correctly WRT the skb check above.
*/
smp_rmb();
memcpy(&dpr->rx_jmb_buffers[di],
&spr->rx_jmb_buffers[si],
cpycnt * sizeof(struct ring_info));
for (i = 0; i < cpycnt; i++, di++, si++) {
struct tg3_rx_buffer_desc *sbd, *dbd;
sbd = &spr->rx_jmb[si].std;
dbd = &dpr->rx_jmb[di].std;
dbd->addr_hi = sbd->addr_hi;
dbd->addr_lo = sbd->addr_lo;
}
spr->rx_jmb_cons_idx = (spr->rx_jmb_cons_idx + cpycnt) &
tp->rx_jmb_ring_mask;
dpr->rx_jmb_prod_idx = (dpr->rx_jmb_prod_idx + cpycnt) &
tp->rx_jmb_ring_mask;
}
return err;
}
static int tg3_poll_work(struct tg3_napi *tnapi, int work_done, int budget)
{
struct tg3 *tp = tnapi->tp;
/* run TX completion thread */
if (tnapi->hw_status->idx[0].tx_consumer != tnapi->tx_cons) {
tg3_tx(tnapi);
if (unlikely(tg3_flag(tp, TX_RECOVERY_PENDING)))
return work_done;
}
if (!tnapi->rx_rcb_prod_idx)
return work_done;
/* run RX thread, within the bounds set by NAPI.
* All RX "locking" is done by ensuring outside
* code synchronizes with tg3->napi.poll()
*/
if (*(tnapi->rx_rcb_prod_idx) != tnapi->rx_rcb_ptr)
work_done += tg3_rx(tnapi, budget - work_done);
if (tg3_flag(tp, ENABLE_RSS) && tnapi == &tp->napi[1]) {
struct tg3_rx_prodring_set *dpr = &tp->napi[0].prodring;
int i, err = 0;
u32 std_prod_idx = dpr->rx_std_prod_idx;
u32 jmb_prod_idx = dpr->rx_jmb_prod_idx;
tp->rx_refill = false;
for (i = 1; i < tp->irq_cnt; i++)
err |= tg3_rx_prodring_xfer(tp, dpr,
&tp->napi[i].prodring);
wmb();
if (std_prod_idx != dpr->rx_std_prod_idx)
tw32_rx_mbox(TG3_RX_STD_PROD_IDX_REG,
dpr->rx_std_prod_idx);
if (jmb_prod_idx != dpr->rx_jmb_prod_idx)
tw32_rx_mbox(TG3_RX_JMB_PROD_IDX_REG,
dpr->rx_jmb_prod_idx);
mmiowb();
if (err)
tw32_f(HOSTCC_MODE, tp->coal_now);
}
return work_done;
}
static inline void tg3_reset_task_schedule(struct tg3 *tp)
{
if (!test_and_set_bit(TG3_FLAG_RESET_TASK_PENDING, tp->tg3_flags))
schedule_work(&tp->reset_task);
}
static inline void tg3_reset_task_cancel(struct tg3 *tp)
{
cancel_work_sync(&tp->reset_task);
tg3_flag_clear(tp, RESET_TASK_PENDING);
tg3_flag_clear(tp, TX_RECOVERY_PENDING);
}
static int tg3_poll_msix(struct napi_struct *napi, int budget)
{
struct tg3_napi *tnapi = container_of(napi, struct tg3_napi, napi);
struct tg3 *tp = tnapi->tp;
int work_done = 0;
struct tg3_hw_status *sblk = tnapi->hw_status;
while (1) {
work_done = tg3_poll_work(tnapi, work_done, budget);
if (unlikely(tg3_flag(tp, TX_RECOVERY_PENDING)))
goto tx_recovery;
if (unlikely(work_done >= budget))
break;
/* tp->last_tag is used in tg3_int_reenable() below
* to tell the hw how much work has been processed,
* so we must read it before checking for more work.
*/
tnapi->last_tag = sblk->status_tag;
tnapi->last_irq_tag = tnapi->last_tag;
rmb();
/* check for RX/TX work to do */
if (likely(sblk->idx[0].tx_consumer == tnapi->tx_cons &&
*(tnapi->rx_rcb_prod_idx) == tnapi->rx_rcb_ptr)) {
/* This test here is not race free, but will reduce
* the number of interrupts by looping again.
*/
if (tnapi == &tp->napi[1] && tp->rx_refill)
continue;
napi_complete(napi);
/* Reenable interrupts. */
tw32_mailbox(tnapi->int_mbox, tnapi->last_tag << 24);
/* This test here is synchronized by napi_schedule()
* and napi_complete() to close the race condition.
*/
if (unlikely(tnapi == &tp->napi[1] && tp->rx_refill)) {
tw32(HOSTCC_MODE, tp->coalesce_mode |
HOSTCC_MODE_ENABLE |
tnapi->coal_now);
}
mmiowb();
break;
}
}
return work_done;
tx_recovery:
/* work_done is guaranteed to be less than budget. */
napi_complete(napi);
tg3_reset_task_schedule(tp);
return work_done;
}
static void tg3_process_error(struct tg3 *tp)
{
u32 val;
bool real_error = false;
if (tg3_flag(tp, ERROR_PROCESSED))
return;
/* Check Flow Attention register */
val = tr32(HOSTCC_FLOW_ATTN);
if (val & ~HOSTCC_FLOW_ATTN_MBUF_LWM) {
netdev_err(tp->dev, "FLOW Attention error. Resetting chip.\n");
real_error = true;
}
if (tr32(MSGINT_STATUS) & ~MSGINT_STATUS_MSI_REQ) {
netdev_err(tp->dev, "MSI Status error. Resetting chip.\n");
real_error = true;
}
if (tr32(RDMAC_STATUS) || tr32(WDMAC_STATUS)) {
netdev_err(tp->dev, "DMA Status error. Resetting chip.\n");
real_error = true;
}
if (!real_error)
return;
tg3_dump_state(tp);
tg3_flag_set(tp, ERROR_PROCESSED);
tg3_reset_task_schedule(tp);
}
static int tg3_poll(struct napi_struct *napi, int budget)
{
struct tg3_napi *tnapi = container_of(napi, struct tg3_napi, napi);
struct tg3 *tp = tnapi->tp;
int work_done = 0;
struct tg3_hw_status *sblk = tnapi->hw_status;
while (1) {
if (sblk->status & SD_STATUS_ERROR)
tg3_process_error(tp);
tg3_poll_link(tp);
work_done = tg3_poll_work(tnapi, work_done, budget);
if (unlikely(tg3_flag(tp, TX_RECOVERY_PENDING)))
goto tx_recovery;
if (unlikely(work_done >= budget))
break;
if (tg3_flag(tp, TAGGED_STATUS)) {
/* tp->last_tag is used in tg3_int_reenable() below
* to tell the hw how much work has been processed,
* so we must read it before checking for more work.
*/
tnapi->last_tag = sblk->status_tag;
tnapi->last_irq_tag = tnapi->last_tag;
rmb();
} else
sblk->status &= ~SD_STATUS_UPDATED;
if (likely(!tg3_has_work(tnapi))) {
napi_complete(napi);
tg3_int_reenable(tnapi);
break;
}
}
return work_done;
tx_recovery:
/* work_done is guaranteed to be less than budget. */
napi_complete(napi);
tg3_reset_task_schedule(tp);
return work_done;
}
static void tg3_napi_disable(struct tg3 *tp)
{
int i;
for (i = tp->irq_cnt - 1; i >= 0; i--)
napi_disable(&tp->napi[i].napi);
}
static void tg3_napi_enable(struct tg3 *tp)
{
int i;
for (i = 0; i < tp->irq_cnt; i++)
napi_enable(&tp->napi[i].napi);
}
static void tg3_napi_init(struct tg3 *tp)
{
int i;
netif_napi_add(tp->dev, &tp->napi[0].napi, tg3_poll, 64);
for (i = 1; i < tp->irq_cnt; i++)
netif_napi_add(tp->dev, &tp->napi[i].napi, tg3_poll_msix, 64);
}
static void tg3_napi_fini(struct tg3 *tp)
{
int i;
for (i = 0; i < tp->irq_cnt; i++)
netif_napi_del(&tp->napi[i].napi);
}
static inline void tg3_netif_stop(struct tg3 *tp)
{
tp->dev->trans_start = jiffies; /* prevent tx timeout */
tg3_napi_disable(tp);
netif_tx_disable(tp->dev);
}
static inline void tg3_netif_start(struct tg3 *tp)
{
/* NOTE: unconditional netif_tx_wake_all_queues is only
* appropriate so long as all callers are assured to
* have free tx slots (such as after tg3_init_hw)
*/
netif_tx_wake_all_queues(tp->dev);
tg3_napi_enable(tp);
tp->napi[0].hw_status->status |= SD_STATUS_UPDATED;
tg3_enable_ints(tp);
}
static void tg3_irq_quiesce(struct tg3 *tp)
{
int i;
BUG_ON(tp->irq_sync);
tp->irq_sync = 1;
smp_mb();
for (i = 0; i < tp->irq_cnt; i++)
synchronize_irq(tp->napi[i].irq_vec);
}
/* Fully shutdown all tg3 driver activity elsewhere in the system.
* If irq_sync is non-zero, then the IRQ handler must be synchronized
* with as well. Most of the time, this is not necessary except when
* shutting down the device.
*/
static inline void tg3_full_lock(struct tg3 *tp, int irq_sync)
{
spin_lock_bh(&tp->lock);
if (irq_sync)
tg3_irq_quiesce(tp);
}
static inline void tg3_full_unlock(struct tg3 *tp)
{
spin_unlock_bh(&tp->lock);
}
/* One-shot MSI handler - Chip automatically disables interrupt
* after sending MSI so driver doesn't have to do it.
*/
static irqreturn_t tg3_msi_1shot(int irq, void *dev_id)
{
struct tg3_napi *tnapi = dev_id;
struct tg3 *tp = tnapi->tp;
prefetch(tnapi->hw_status);
if (tnapi->rx_rcb)
prefetch(&tnapi->rx_rcb[tnapi->rx_rcb_ptr]);
if (likely(!tg3_irq_sync(tp)))
napi_schedule(&tnapi->napi);
return IRQ_HANDLED;
}
/* MSI ISR - No need to check for interrupt sharing and no need to
* flush status block and interrupt mailbox. PCI ordering rules
* guarantee that MSI will arrive after the status block.
*/
static irqreturn_t tg3_msi(int irq, void *dev_id)
{
struct tg3_napi *tnapi = dev_id;
struct tg3 *tp = tnapi->tp;
prefetch(tnapi->hw_status);
if (tnapi->rx_rcb)
prefetch(&tnapi->rx_rcb[tnapi->rx_rcb_ptr]);
/*
* Writing any value to intr-mbox-0 clears PCI INTA# and
* chip-internal interrupt pending events.
* Writing non-zero to intr-mbox-0 additional tells the
* NIC to stop sending us irqs, engaging "in-intr-handler"
* event coalescing.
*/
tw32_mailbox(tnapi->int_mbox, 0x00000001);
if (likely(!tg3_irq_sync(tp)))
napi_schedule(&tnapi->napi);
return IRQ_RETVAL(1);
}
static irqreturn_t tg3_interrupt(int irq, void *dev_id)
{
struct tg3_napi *tnapi = dev_id;
struct tg3 *tp = tnapi->tp;
struct tg3_hw_status *sblk = tnapi->hw_status;
unsigned int handled = 1;
/* In INTx mode, it is possible for the interrupt to arrive at
* the CPU before the status block posted prior to the interrupt.
* Reading the PCI State register will confirm whether the
* interrupt is ours and will flush the status block.
*/
if (unlikely(!(sblk->status & SD_STATUS_UPDATED))) {
if (tg3_flag(tp, CHIP_RESETTING) ||
(tr32(TG3PCI_PCISTATE) & PCISTATE_INT_NOT_ACTIVE)) {
handled = 0;
goto out;
}
}
/*
* Writing any value to intr-mbox-0 clears PCI INTA# and
* chip-internal interrupt pending events.
* Writing non-zero to intr-mbox-0 additional tells the
* NIC to stop sending us irqs, engaging "in-intr-handler"
* event coalescing.
*
* Flush the mailbox to de-assert the IRQ immediately to prevent
* spurious interrupts. The flush impacts performance but
* excessive spurious interrupts can be worse in some cases.
*/
tw32_mailbox_f(MAILBOX_INTERRUPT_0 + TG3_64BIT_REG_LOW, 0x00000001);
if (tg3_irq_sync(tp))
goto out;
sblk->status &= ~SD_STATUS_UPDATED;
if (likely(tg3_has_work(tnapi))) {
prefetch(&tnapi->rx_rcb[tnapi->rx_rcb_ptr]);
napi_schedule(&tnapi->napi);
} else {
/* No work, shared interrupt perhaps? re-enable
* interrupts, and flush that PCI write
*/
tw32_mailbox_f(MAILBOX_INTERRUPT_0 + TG3_64BIT_REG_LOW,
0x00000000);
}
out:
return IRQ_RETVAL(handled);
}
static irqreturn_t tg3_interrupt_tagged(int irq, void *dev_id)
{
struct tg3_napi *tnapi = dev_id;
struct tg3 *tp = tnapi->tp;
struct tg3_hw_status *sblk = tnapi->hw_status;
unsigned int handled = 1;
/* In INTx mode, it is possible for the interrupt to arrive at
* the CPU before the status block posted prior to the interrupt.
* Reading the PCI State register will confirm whether the
* interrupt is ours and will flush the status block.
*/
if (unlikely(sblk->status_tag == tnapi->last_irq_tag)) {
if (tg3_flag(tp, CHIP_RESETTING) ||
(tr32(TG3PCI_PCISTATE) & PCISTATE_INT_NOT_ACTIVE)) {
handled = 0;
goto out;
}
}
/*
* writing any value to intr-mbox-0 clears PCI INTA# and
* chip-internal interrupt pending events.
* writing non-zero to intr-mbox-0 additional tells the
* NIC to stop sending us irqs, engaging "in-intr-handler"
* event coalescing.
*
* Flush the mailbox to de-assert the IRQ immediately to prevent
* spurious interrupts. The flush impacts performance but
* excessive spurious interrupts can be worse in some cases.
*/
tw32_mailbox_f(MAILBOX_INTERRUPT_0 + TG3_64BIT_REG_LOW, 0x00000001);
/*
* In a shared interrupt configuration, sometimes other devices'
* interrupts will scream. We record the current status tag here
* so that the above check can report that the screaming interrupts
* are unhandled. Eventually they will be silenced.
*/
tnapi->last_irq_tag = sblk->status_tag;
if (tg3_irq_sync(tp))
goto out;
prefetch(&tnapi->rx_rcb[tnapi->rx_rcb_ptr]);
napi_schedule(&tnapi->napi);
out:
return IRQ_RETVAL(handled);
}
/* ISR for interrupt test */
static irqreturn_t tg3_test_isr(int irq, void *dev_id)
{
struct tg3_napi *tnapi = dev_id;
struct tg3 *tp = tnapi->tp;
struct tg3_hw_status *sblk = tnapi->hw_status;
if ((sblk->status & SD_STATUS_UPDATED) ||
!(tr32(TG3PCI_PCISTATE) & PCISTATE_INT_NOT_ACTIVE)) {
tg3_disable_ints(tp);
return IRQ_RETVAL(1);
}
return IRQ_RETVAL(0);
}
#ifdef CONFIG_NET_POLL_CONTROLLER
static void tg3_poll_controller(struct net_device *dev)
{
int i;
struct tg3 *tp = netdev_priv(dev);
for (i = 0; i < tp->irq_cnt; i++)
tg3_interrupt(tp->napi[i].irq_vec, &tp->napi[i]);
}
#endif
static void tg3_tx_timeout(struct net_device *dev)
{
struct tg3 *tp = netdev_priv(dev);
if (netif_msg_tx_err(tp)) {
netdev_err(dev, "transmit timed out, resetting\n");
tg3_dump_state(tp);
}
tg3_reset_task_schedule(tp);
}
/* Test for DMA buffers crossing any 4GB boundaries: 4G, 8G, etc */
static inline int tg3_4g_overflow_test(dma_addr_t mapping, int len)
{
u32 base = (u32) mapping & 0xffffffff;
return (base > 0xffffdcc0) && (base + len + 8 < base);
}
/* Test for DMA addresses > 40-bit */
static inline int tg3_40bit_overflow_test(struct tg3 *tp, dma_addr_t mapping,
int len)
{
#if defined(CONFIG_HIGHMEM) && (BITS_PER_LONG == 64)
if (tg3_flag(tp, 40BIT_DMA_BUG))
return ((u64) mapping + len) > DMA_BIT_MASK(40);
return 0;
#else
return 0;
#endif
}
static inline void tg3_tx_set_bd(struct tg3_tx_buffer_desc *txbd,
dma_addr_t mapping, u32 len, u32 flags,
u32 mss, u32 vlan)
{
txbd->addr_hi = ((u64) mapping >> 32);
txbd->addr_lo = ((u64) mapping & 0xffffffff);
txbd->len_flags = (len << TXD_LEN_SHIFT) | (flags & 0x0000ffff);
txbd->vlan_tag = (mss << TXD_MSS_SHIFT) | (vlan << TXD_VLAN_TAG_SHIFT);
}
static bool tg3_tx_frag_set(struct tg3_napi *tnapi, u32 *entry, u32 *budget,
dma_addr_t map, u32 len, u32 flags,
u32 mss, u32 vlan)
{
struct tg3 *tp = tnapi->tp;
bool hwbug = false;
if (tg3_flag(tp, SHORT_DMA_BUG) && len <= 8)
hwbug = true;
if (tg3_4g_overflow_test(map, len))
hwbug = true;
if (tg3_40bit_overflow_test(tp, map, len))
hwbug = true;
if (tp->dma_limit) {
u32 prvidx = *entry;
u32 tmp_flag = flags & ~TXD_FLAG_END;
while (len > tp->dma_limit && *budget) {
u32 frag_len = tp->dma_limit;
len -= tp->dma_limit;
/* Avoid the 8byte DMA problem */
if (len <= 8) {
len += tp->dma_limit / 2;
frag_len = tp->dma_limit / 2;
}
tnapi->tx_buffers[*entry].fragmented = true;
tg3_tx_set_bd(&tnapi->tx_ring[*entry], map,
frag_len, tmp_flag, mss, vlan);
*budget -= 1;
prvidx = *entry;
*entry = NEXT_TX(*entry);
map += frag_len;
}
if (len) {
if (*budget) {
tg3_tx_set_bd(&tnapi->tx_ring[*entry], map,
len, flags, mss, vlan);
*budget -= 1;
*entry = NEXT_TX(*entry);
} else {
hwbug = true;
tnapi->tx_buffers[prvidx].fragmented = false;
}
}
} else {
tg3_tx_set_bd(&tnapi->tx_ring[*entry], map,
len, flags, mss, vlan);
*entry = NEXT_TX(*entry);
}
return hwbug;
}
static void tg3_tx_skb_unmap(struct tg3_napi *tnapi, u32 entry, int last)
{
int i;
struct sk_buff *skb;
struct tg3_tx_ring_info *txb = &tnapi->tx_buffers[entry];
skb = txb->skb;
txb->skb = NULL;
pci_unmap_single(tnapi->tp->pdev,
dma_unmap_addr(txb, mapping),
skb_headlen(skb),
PCI_DMA_TODEVICE);
while (txb->fragmented) {
txb->fragmented = false;
entry = NEXT_TX(entry);
txb = &tnapi->tx_buffers[entry];
}
for (i = 0; i <= last; i++) {
const skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
entry = NEXT_TX(entry);
txb = &tnapi->tx_buffers[entry];
pci_unmap_page(tnapi->tp->pdev,
dma_unmap_addr(txb, mapping),
skb_frag_size(frag), PCI_DMA_TODEVICE);
while (txb->fragmented) {
txb->fragmented = false;
entry = NEXT_TX(entry);
txb = &tnapi->tx_buffers[entry];
}
}
}
/* Workaround 4GB and 40-bit hardware DMA bugs. */
static int tigon3_dma_hwbug_workaround(struct tg3_napi *tnapi,
struct sk_buff **pskb,
u32 *entry, u32 *budget,
u32 base_flags, u32 mss, u32 vlan)
{
struct tg3 *tp = tnapi->tp;
struct sk_buff *new_skb, *skb = *pskb;
dma_addr_t new_addr = 0;
int ret = 0;
if (GET_ASIC_REV(tp->pci_chip_rev_id) != ASIC_REV_5701)
new_skb = skb_copy(skb, GFP_ATOMIC);
else {
int more_headroom = 4 - ((unsigned long)skb->data & 3);
new_skb = skb_copy_expand(skb,
skb_headroom(skb) + more_headroom,
skb_tailroom(skb), GFP_ATOMIC);
}
if (!new_skb) {
ret = -1;
} else {
/* New SKB is guaranteed to be linear. */
new_addr = pci_map_single(tp->pdev, new_skb->data, new_skb->len,
PCI_DMA_TODEVICE);
/* Make sure the mapping succeeded */
if (pci_dma_mapping_error(tp->pdev, new_addr)) {
dev_kfree_skb(new_skb);
ret = -1;
} else {
u32 save_entry = *entry;
base_flags |= TXD_FLAG_END;
tnapi->tx_buffers[*entry].skb = new_skb;
dma_unmap_addr_set(&tnapi->tx_buffers[*entry],
mapping, new_addr);
if (tg3_tx_frag_set(tnapi, entry, budget, new_addr,
new_skb->len, base_flags,
mss, vlan)) {
tg3_tx_skb_unmap(tnapi, save_entry, -1);
dev_kfree_skb(new_skb);
ret = -1;
}
}
}
dev_kfree_skb(skb);
*pskb = new_skb;
return ret;
}
static netdev_tx_t tg3_start_xmit(struct sk_buff *, struct net_device *);
/* Use GSO to workaround a rare TSO bug that may be triggered when the
* TSO header is greater than 80 bytes.
*/
static int tg3_tso_bug(struct tg3 *tp, struct sk_buff *skb)
{
struct sk_buff *segs, *nskb;
u32 frag_cnt_est = skb_shinfo(skb)->gso_segs * 3;
/* Estimate the number of fragments in the worst case */
if (unlikely(tg3_tx_avail(&tp->napi[0]) <= frag_cnt_est)) {
netif_stop_queue(tp->dev);
/* netif_tx_stop_queue() must be done before checking
* checking tx index in tg3_tx_avail() below, because in
* tg3_tx(), we update tx index before checking for
* netif_tx_queue_stopped().
*/
smp_mb();
if (tg3_tx_avail(&tp->napi[0]) <= frag_cnt_est)
return NETDEV_TX_BUSY;
netif_wake_queue(tp->dev);
}
segs = skb_gso_segment(skb, tp->dev->features & ~NETIF_F_TSO);
if (IS_ERR(segs))
goto tg3_tso_bug_end;
do {
nskb = segs;
segs = segs->next;
nskb->next = NULL;
tg3_start_xmit(nskb, tp->dev);
} while (segs);
tg3_tso_bug_end:
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
/* hard_start_xmit for devices that have the 4G bug and/or 40-bit bug and
* support TG3_FLAG_HW_TSO_1 or firmware TSO only.
*/
static netdev_tx_t tg3_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct tg3 *tp = netdev_priv(dev);
u32 len, entry, base_flags, mss, vlan = 0;
u32 budget;
int i = -1, would_hit_hwbug;
dma_addr_t mapping;
struct tg3_napi *tnapi;
struct netdev_queue *txq;
unsigned int last;
txq = netdev_get_tx_queue(dev, skb_get_queue_mapping(skb));
tnapi = &tp->napi[skb_get_queue_mapping(skb)];
if (tg3_flag(tp, ENABLE_TSS))
tnapi++;
budget = tg3_tx_avail(tnapi);
/* We are running in BH disabled context with netif_tx_lock
* and TX reclaim runs via tp->napi.poll inside of a software
* interrupt. Furthermore, IRQ processing runs lockless so we have
* no IRQ context deadlocks to worry about either. Rejoice!
*/
if (unlikely(budget <= (skb_shinfo(skb)->nr_frags + 1))) {
if (!netif_tx_queue_stopped(txq)) {
netif_tx_stop_queue(txq);
/* This is a hard error, log it. */
netdev_err(dev,
"BUG! Tx Ring full when queue awake!\n");
}
return NETDEV_TX_BUSY;
}
entry = tnapi->tx_prod;
base_flags = 0;
if (skb->ip_summed == CHECKSUM_PARTIAL)
base_flags |= TXD_FLAG_TCPUDP_CSUM;
mss = skb_shinfo(skb)->gso_size;
if (mss) {
struct iphdr *iph;
u32 tcp_opt_len, hdr_len;
if (skb_header_cloned(skb) &&
pskb_expand_head(skb, 0, 0, GFP_ATOMIC))
goto drop;
iph = ip_hdr(skb);
tcp_opt_len = tcp_optlen(skb);
hdr_len = skb_transport_offset(skb) + tcp_hdrlen(skb) - ETH_HLEN;
if (!skb_is_gso_v6(skb)) {
iph->check = 0;
iph->tot_len = htons(mss + hdr_len);
}
if (unlikely((ETH_HLEN + hdr_len) > 80) &&
tg3_flag(tp, TSO_BUG))
return tg3_tso_bug(tp, skb);
base_flags |= (TXD_FLAG_CPU_PRE_DMA |
TXD_FLAG_CPU_POST_DMA);
if (tg3_flag(tp, HW_TSO_1) ||
tg3_flag(tp, HW_TSO_2) ||
tg3_flag(tp, HW_TSO_3)) {
tcp_hdr(skb)->check = 0;
base_flags &= ~TXD_FLAG_TCPUDP_CSUM;
} else
tcp_hdr(skb)->check = ~csum_tcpudp_magic(iph->saddr,
iph->daddr, 0,
IPPROTO_TCP,
0);
if (tg3_flag(tp, HW_TSO_3)) {
mss |= (hdr_len & 0xc) << 12;
if (hdr_len & 0x10)
base_flags |= 0x00000010;
base_flags |= (hdr_len & 0x3e0) << 5;
} else if (tg3_flag(tp, HW_TSO_2))
mss |= hdr_len << 9;
else if (tg3_flag(tp, HW_TSO_1) ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5705) {
if (tcp_opt_len || iph->ihl > 5) {
int tsflags;
tsflags = (iph->ihl - 5) + (tcp_opt_len >> 2);
mss |= (tsflags << 11);
}
} else {
if (tcp_opt_len || iph->ihl > 5) {
int tsflags;
tsflags = (iph->ihl - 5) + (tcp_opt_len >> 2);
base_flags |= tsflags << 12;
}
}
}
if (tg3_flag(tp, USE_JUMBO_BDFLAG) &&
!mss && skb->len > VLAN_ETH_FRAME_LEN)
base_flags |= TXD_FLAG_JMB_PKT;
if (vlan_tx_tag_present(skb)) {
base_flags |= TXD_FLAG_VLAN;
vlan = vlan_tx_tag_get(skb);
}
len = skb_headlen(skb);
mapping = pci_map_single(tp->pdev, skb->data, len, PCI_DMA_TODEVICE);
if (pci_dma_mapping_error(tp->pdev, mapping))
goto drop;
tnapi->tx_buffers[entry].skb = skb;
dma_unmap_addr_set(&tnapi->tx_buffers[entry], mapping, mapping);
would_hit_hwbug = 0;
if (tg3_flag(tp, 5701_DMA_BUG))
would_hit_hwbug = 1;
if (tg3_tx_frag_set(tnapi, &entry, &budget, mapping, len, base_flags |
((skb_shinfo(skb)->nr_frags == 0) ? TXD_FLAG_END : 0),
mss, vlan)) {
would_hit_hwbug = 1;
} else if (skb_shinfo(skb)->nr_frags > 0) {
u32 tmp_mss = mss;
if (!tg3_flag(tp, HW_TSO_1) &&
!tg3_flag(tp, HW_TSO_2) &&
!tg3_flag(tp, HW_TSO_3))
tmp_mss = 0;
/* Now loop through additional data
* fragments, and queue them.
*/
last = skb_shinfo(skb)->nr_frags - 1;
for (i = 0; i <= last; i++) {
skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
len = skb_frag_size(frag);
mapping = skb_frag_dma_map(&tp->pdev->dev, frag, 0,
len, DMA_TO_DEVICE);
tnapi->tx_buffers[entry].skb = NULL;
dma_unmap_addr_set(&tnapi->tx_buffers[entry], mapping,
mapping);
if (dma_mapping_error(&tp->pdev->dev, mapping))
goto dma_error;
if (!budget ||
tg3_tx_frag_set(tnapi, &entry, &budget, mapping,
len, base_flags |
((i == last) ? TXD_FLAG_END : 0),
tmp_mss, vlan)) {
would_hit_hwbug = 1;
break;
}
}
}
if (would_hit_hwbug) {
tg3_tx_skb_unmap(tnapi, tnapi->tx_prod, i);
/* If the workaround fails due to memory/mapping
* failure, silently drop this packet.
*/
entry = tnapi->tx_prod;
budget = tg3_tx_avail(tnapi);
if (tigon3_dma_hwbug_workaround(tnapi, &skb, &entry, &budget,
base_flags, mss, vlan))
goto drop_nofree;
}
skb_tx_timestamp(skb);
netdev_tx_sent_queue(txq, skb->len);
/* Sync BD data before updating mailbox */
wmb();
/* Packets are ready, update Tx producer idx local and on card. */
tw32_tx_mbox(tnapi->prodmbox, entry);
tnapi->tx_prod = entry;
if (unlikely(tg3_tx_avail(tnapi) <= (MAX_SKB_FRAGS + 1))) {
netif_tx_stop_queue(txq);
/* netif_tx_stop_queue() must be done before checking
* checking tx index in tg3_tx_avail() below, because in
* tg3_tx(), we update tx index before checking for
* netif_tx_queue_stopped().
*/
smp_mb();
if (tg3_tx_avail(tnapi) > TG3_TX_WAKEUP_THRESH(tnapi))
netif_tx_wake_queue(txq);
}
mmiowb();
return NETDEV_TX_OK;
dma_error:
tg3_tx_skb_unmap(tnapi, tnapi->tx_prod, --i);
tnapi->tx_buffers[tnapi->tx_prod].skb = NULL;
drop:
dev_kfree_skb(skb);
drop_nofree:
tp->tx_dropped++;
return NETDEV_TX_OK;
}
static void tg3_mac_loopback(struct tg3 *tp, bool enable)
{
if (enable) {
tp->mac_mode &= ~(MAC_MODE_HALF_DUPLEX |
MAC_MODE_PORT_MODE_MASK);
tp->mac_mode |= MAC_MODE_PORT_INT_LPBACK;
if (!tg3_flag(tp, 5705_PLUS))
tp->mac_mode |= MAC_MODE_LINK_POLARITY;
if (tp->phy_flags & TG3_PHYFLG_10_100_ONLY)
tp->mac_mode |= MAC_MODE_PORT_MODE_MII;
else
tp->mac_mode |= MAC_MODE_PORT_MODE_GMII;
} else {
tp->mac_mode &= ~MAC_MODE_PORT_INT_LPBACK;
if (tg3_flag(tp, 5705_PLUS) ||
(tp->phy_flags & TG3_PHYFLG_PHY_SERDES) ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5700)
tp->mac_mode &= ~MAC_MODE_LINK_POLARITY;
}
tw32(MAC_MODE, tp->mac_mode);
udelay(40);
}
static int tg3_phy_lpbk_set(struct tg3 *tp, u32 speed, bool extlpbk)
{
u32 val, bmcr, mac_mode, ptest = 0;
tg3_phy_toggle_apd(tp, false);
tg3_phy_toggle_automdix(tp, 0);
if (extlpbk && tg3_phy_set_extloopbk(tp))
return -EIO;
bmcr = BMCR_FULLDPLX;
switch (speed) {
case SPEED_10:
break;
case SPEED_100:
bmcr |= BMCR_SPEED100;
break;
case SPEED_1000:
default:
if (tp->phy_flags & TG3_PHYFLG_IS_FET) {
speed = SPEED_100;
bmcr |= BMCR_SPEED100;
} else {
speed = SPEED_1000;
bmcr |= BMCR_SPEED1000;
}
}
if (extlpbk) {
if (!(tp->phy_flags & TG3_PHYFLG_IS_FET)) {
tg3_readphy(tp, MII_CTRL1000, &val);
val |= CTL1000_AS_MASTER |
CTL1000_ENABLE_MASTER;
tg3_writephy(tp, MII_CTRL1000, val);
} else {
ptest = MII_TG3_FET_PTEST_TRIM_SEL |
MII_TG3_FET_PTEST_TRIM_2;
tg3_writephy(tp, MII_TG3_FET_PTEST, ptest);
}
} else
bmcr |= BMCR_LOOPBACK;
tg3_writephy(tp, MII_BMCR, bmcr);
/* The write needs to be flushed for the FETs */
if (tp->phy_flags & TG3_PHYFLG_IS_FET)
tg3_readphy(tp, MII_BMCR, &bmcr);
udelay(40);
if ((tp->phy_flags & TG3_PHYFLG_IS_FET) &&
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5785) {
tg3_writephy(tp, MII_TG3_FET_PTEST, ptest |
MII_TG3_FET_PTEST_FRC_TX_LINK |
MII_TG3_FET_PTEST_FRC_TX_LOCK);
/* The write needs to be flushed for the AC131 */
tg3_readphy(tp, MII_TG3_FET_PTEST, &val);
}
/* Reset to prevent losing 1st rx packet intermittently */
if ((tp->phy_flags & TG3_PHYFLG_MII_SERDES) &&
tg3_flag(tp, 5780_CLASS)) {
tw32_f(MAC_RX_MODE, RX_MODE_RESET);
udelay(10);
tw32_f(MAC_RX_MODE, tp->rx_mode);
}
mac_mode = tp->mac_mode &
~(MAC_MODE_PORT_MODE_MASK | MAC_MODE_HALF_DUPLEX);
if (speed == SPEED_1000)
mac_mode |= MAC_MODE_PORT_MODE_GMII;
else
mac_mode |= MAC_MODE_PORT_MODE_MII;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5700) {
u32 masked_phy_id = tp->phy_id & TG3_PHY_ID_MASK;
if (masked_phy_id == TG3_PHY_ID_BCM5401)
mac_mode &= ~MAC_MODE_LINK_POLARITY;
else if (masked_phy_id == TG3_PHY_ID_BCM5411)
mac_mode |= MAC_MODE_LINK_POLARITY;
tg3_writephy(tp, MII_TG3_EXT_CTRL,
MII_TG3_EXT_CTRL_LNK3_LED_MODE);
}
tw32(MAC_MODE, mac_mode);
udelay(40);
return 0;
}
static void tg3_set_loopback(struct net_device *dev, netdev_features_t features)
{
struct tg3 *tp = netdev_priv(dev);
if (features & NETIF_F_LOOPBACK) {
if (tp->mac_mode & MAC_MODE_PORT_INT_LPBACK)
return;
spin_lock_bh(&tp->lock);
tg3_mac_loopback(tp, true);
netif_carrier_on(tp->dev);
spin_unlock_bh(&tp->lock);
netdev_info(dev, "Internal MAC loopback mode enabled.\n");
} else {
if (!(tp->mac_mode & MAC_MODE_PORT_INT_LPBACK))
return;
spin_lock_bh(&tp->lock);
tg3_mac_loopback(tp, false);
/* Force link status check */
tg3_setup_phy(tp, 1);
spin_unlock_bh(&tp->lock);
netdev_info(dev, "Internal MAC loopback mode disabled.\n");
}
}
static netdev_features_t tg3_fix_features(struct net_device *dev,
netdev_features_t features)
{
struct tg3 *tp = netdev_priv(dev);
if (dev->mtu > ETH_DATA_LEN && tg3_flag(tp, 5780_CLASS))
features &= ~NETIF_F_ALL_TSO;
return features;
}
static int tg3_set_features(struct net_device *dev, netdev_features_t features)
{
netdev_features_t changed = dev->features ^ features;
if ((changed & NETIF_F_LOOPBACK) && netif_running(dev))
tg3_set_loopback(dev, features);
return 0;
}
static void tg3_rx_prodring_free(struct tg3 *tp,
struct tg3_rx_prodring_set *tpr)
{
int i;
if (tpr != &tp->napi[0].prodring) {
for (i = tpr->rx_std_cons_idx; i != tpr->rx_std_prod_idx;
i = (i + 1) & tp->rx_std_ring_mask)
tg3_rx_data_free(tp, &tpr->rx_std_buffers[i],
tp->rx_pkt_map_sz);
if (tg3_flag(tp, JUMBO_CAPABLE)) {
for (i = tpr->rx_jmb_cons_idx;
i != tpr->rx_jmb_prod_idx;
i = (i + 1) & tp->rx_jmb_ring_mask) {
tg3_rx_data_free(tp, &tpr->rx_jmb_buffers[i],
TG3_RX_JMB_MAP_SZ);
}
}
return;
}
for (i = 0; i <= tp->rx_std_ring_mask; i++)
tg3_rx_data_free(tp, &tpr->rx_std_buffers[i],
tp->rx_pkt_map_sz);
if (tg3_flag(tp, JUMBO_CAPABLE) && !tg3_flag(tp, 5780_CLASS)) {
for (i = 0; i <= tp->rx_jmb_ring_mask; i++)
tg3_rx_data_free(tp, &tpr->rx_jmb_buffers[i],
TG3_RX_JMB_MAP_SZ);
}
}
/* Initialize rx rings for packet processing.
*
* The chip has been shut down and the driver detached from
* the networking, so no interrupts or new tx packets will
* end up in the driver. tp->{tx,}lock are held and thus
* we may not sleep.
*/
static int tg3_rx_prodring_alloc(struct tg3 *tp,
struct tg3_rx_prodring_set *tpr)
{
u32 i, rx_pkt_dma_sz;
tpr->rx_std_cons_idx = 0;
tpr->rx_std_prod_idx = 0;
tpr->rx_jmb_cons_idx = 0;
tpr->rx_jmb_prod_idx = 0;
if (tpr != &tp->napi[0].prodring) {
memset(&tpr->rx_std_buffers[0], 0,
TG3_RX_STD_BUFF_RING_SIZE(tp));
if (tpr->rx_jmb_buffers)
memset(&tpr->rx_jmb_buffers[0], 0,
TG3_RX_JMB_BUFF_RING_SIZE(tp));
goto done;
}
/* Zero out all descriptors. */
memset(tpr->rx_std, 0, TG3_RX_STD_RING_BYTES(tp));
rx_pkt_dma_sz = TG3_RX_STD_DMA_SZ;
if (tg3_flag(tp, 5780_CLASS) &&
tp->dev->mtu > ETH_DATA_LEN)
rx_pkt_dma_sz = TG3_RX_JMB_DMA_SZ;
tp->rx_pkt_map_sz = TG3_RX_DMA_TO_MAP_SZ(rx_pkt_dma_sz);
/* Initialize invariants of the rings, we only set this
* stuff once. This works because the card does not
* write into the rx buffer posting rings.
*/
for (i = 0; i <= tp->rx_std_ring_mask; i++) {
struct tg3_rx_buffer_desc *rxd;
rxd = &tpr->rx_std[i];
rxd->idx_len = rx_pkt_dma_sz << RXD_LEN_SHIFT;
rxd->type_flags = (RXD_FLAG_END << RXD_FLAGS_SHIFT);
rxd->opaque = (RXD_OPAQUE_RING_STD |
(i << RXD_OPAQUE_INDEX_SHIFT));
}
/* Now allocate fresh SKBs for each rx ring. */
for (i = 0; i < tp->rx_pending; i++) {
if (tg3_alloc_rx_data(tp, tpr, RXD_OPAQUE_RING_STD, i) < 0) {
netdev_warn(tp->dev,
"Using a smaller RX standard ring. Only "
"%d out of %d buffers were allocated "
"successfully\n", i, tp->rx_pending);
if (i == 0)
goto initfail;
tp->rx_pending = i;
break;
}
}
if (!tg3_flag(tp, JUMBO_CAPABLE) || tg3_flag(tp, 5780_CLASS))
goto done;
memset(tpr->rx_jmb, 0, TG3_RX_JMB_RING_BYTES(tp));
if (!tg3_flag(tp, JUMBO_RING_ENABLE))
goto done;
for (i = 0; i <= tp->rx_jmb_ring_mask; i++) {
struct tg3_rx_buffer_desc *rxd;
rxd = &tpr->rx_jmb[i].std;
rxd->idx_len = TG3_RX_JMB_DMA_SZ << RXD_LEN_SHIFT;
rxd->type_flags = (RXD_FLAG_END << RXD_FLAGS_SHIFT) |
RXD_FLAG_JUMBO;
rxd->opaque = (RXD_OPAQUE_RING_JUMBO |
(i << RXD_OPAQUE_INDEX_SHIFT));
}
for (i = 0; i < tp->rx_jumbo_pending; i++) {
if (tg3_alloc_rx_data(tp, tpr, RXD_OPAQUE_RING_JUMBO, i) < 0) {
netdev_warn(tp->dev,
"Using a smaller RX jumbo ring. Only %d "
"out of %d buffers were allocated "
"successfully\n", i, tp->rx_jumbo_pending);
if (i == 0)
goto initfail;
tp->rx_jumbo_pending = i;
break;
}
}
done:
return 0;
initfail:
tg3_rx_prodring_free(tp, tpr);
return -ENOMEM;
}
static void tg3_rx_prodring_fini(struct tg3 *tp,
struct tg3_rx_prodring_set *tpr)
{
kfree(tpr->rx_std_buffers);
tpr->rx_std_buffers = NULL;
kfree(tpr->rx_jmb_buffers);
tpr->rx_jmb_buffers = NULL;
if (tpr->rx_std) {
dma_free_coherent(&tp->pdev->dev, TG3_RX_STD_RING_BYTES(tp),
tpr->rx_std, tpr->rx_std_mapping);
tpr->rx_std = NULL;
}
if (tpr->rx_jmb) {
dma_free_coherent(&tp->pdev->dev, TG3_RX_JMB_RING_BYTES(tp),
tpr->rx_jmb, tpr->rx_jmb_mapping);
tpr->rx_jmb = NULL;
}
}
static int tg3_rx_prodring_init(struct tg3 *tp,
struct tg3_rx_prodring_set *tpr)
{
tpr->rx_std_buffers = kzalloc(TG3_RX_STD_BUFF_RING_SIZE(tp),
GFP_KERNEL);
if (!tpr->rx_std_buffers)
return -ENOMEM;
tpr->rx_std = dma_alloc_coherent(&tp->pdev->dev,
TG3_RX_STD_RING_BYTES(tp),
&tpr->rx_std_mapping,
GFP_KERNEL);
if (!tpr->rx_std)
goto err_out;
if (tg3_flag(tp, JUMBO_CAPABLE) && !tg3_flag(tp, 5780_CLASS)) {
tpr->rx_jmb_buffers = kzalloc(TG3_RX_JMB_BUFF_RING_SIZE(tp),
GFP_KERNEL);
if (!tpr->rx_jmb_buffers)
goto err_out;
tpr->rx_jmb = dma_alloc_coherent(&tp->pdev->dev,
TG3_RX_JMB_RING_BYTES(tp),
&tpr->rx_jmb_mapping,
GFP_KERNEL);
if (!tpr->rx_jmb)
goto err_out;
}
return 0;
err_out:
tg3_rx_prodring_fini(tp, tpr);
return -ENOMEM;
}
/* Free up pending packets in all rx/tx rings.
*
* The chip has been shut down and the driver detached from
* the networking, so no interrupts or new tx packets will
* end up in the driver. tp->{tx,}lock is not held and we are not
* in an interrupt context and thus may sleep.
*/
static void tg3_free_rings(struct tg3 *tp)
{
int i, j;
for (j = 0; j < tp->irq_cnt; j++) {
struct tg3_napi *tnapi = &tp->napi[j];
tg3_rx_prodring_free(tp, &tnapi->prodring);
if (!tnapi->tx_buffers)
continue;
for (i = 0; i < TG3_TX_RING_SIZE; i++) {
struct sk_buff *skb = tnapi->tx_buffers[i].skb;
if (!skb)
continue;
tg3_tx_skb_unmap(tnapi, i,
skb_shinfo(skb)->nr_frags - 1);
dev_kfree_skb_any(skb);
}
netdev_tx_reset_queue(netdev_get_tx_queue(tp->dev, j));
}
}
/* Initialize tx/rx rings for packet processing.
*
* The chip has been shut down and the driver detached from
* the networking, so no interrupts or new tx packets will
* end up in the driver. tp->{tx,}lock are held and thus
* we may not sleep.
*/
static int tg3_init_rings(struct tg3 *tp)
{
int i;
/* Free up all the SKBs. */
tg3_free_rings(tp);
for (i = 0; i < tp->irq_cnt; i++) {
struct tg3_napi *tnapi = &tp->napi[i];
tnapi->last_tag = 0;
tnapi->last_irq_tag = 0;
tnapi->hw_status->status = 0;
tnapi->hw_status->status_tag = 0;
memset(tnapi->hw_status, 0, TG3_HW_STATUS_SIZE);
tnapi->tx_prod = 0;
tnapi->tx_cons = 0;
if (tnapi->tx_ring)
memset(tnapi->tx_ring, 0, TG3_TX_RING_BYTES);
tnapi->rx_rcb_ptr = 0;
if (tnapi->rx_rcb)
memset(tnapi->rx_rcb, 0, TG3_RX_RCB_RING_BYTES(tp));
if (tg3_rx_prodring_alloc(tp, &tnapi->prodring)) {
tg3_free_rings(tp);
return -ENOMEM;
}
}
return 0;
}
/*
* Must not be invoked with interrupt sources disabled and
* the hardware shutdown down.
*/
static void tg3_free_consistent(struct tg3 *tp)
{
int i;
for (i = 0; i < tp->irq_cnt; i++) {
struct tg3_napi *tnapi = &tp->napi[i];
if (tnapi->tx_ring) {
dma_free_coherent(&tp->pdev->dev, TG3_TX_RING_BYTES,
tnapi->tx_ring, tnapi->tx_desc_mapping);
tnapi->tx_ring = NULL;
}
kfree(tnapi->tx_buffers);
tnapi->tx_buffers = NULL;
if (tnapi->rx_rcb) {
dma_free_coherent(&tp->pdev->dev,
TG3_RX_RCB_RING_BYTES(tp),
tnapi->rx_rcb,
tnapi->rx_rcb_mapping);
tnapi->rx_rcb = NULL;
}
tg3_rx_prodring_fini(tp, &tnapi->prodring);
if (tnapi->hw_status) {
dma_free_coherent(&tp->pdev->dev, TG3_HW_STATUS_SIZE,
tnapi->hw_status,
tnapi->status_mapping);
tnapi->hw_status = NULL;
}
}
if (tp->hw_stats) {
dma_free_coherent(&tp->pdev->dev, sizeof(struct tg3_hw_stats),
tp->hw_stats, tp->stats_mapping);
tp->hw_stats = NULL;
}
}
/*
* Must not be invoked with interrupt sources disabled and
* the hardware shutdown down. Can sleep.
*/
static int tg3_alloc_consistent(struct tg3 *tp)
{
int i;
tp->hw_stats = dma_alloc_coherent(&tp->pdev->dev,
sizeof(struct tg3_hw_stats),
&tp->stats_mapping,
GFP_KERNEL);
if (!tp->hw_stats)
goto err_out;
memset(tp->hw_stats, 0, sizeof(struct tg3_hw_stats));
for (i = 0; i < tp->irq_cnt; i++) {
struct tg3_napi *tnapi = &tp->napi[i];
struct tg3_hw_status *sblk;
tnapi->hw_status = dma_alloc_coherent(&tp->pdev->dev,
TG3_HW_STATUS_SIZE,
&tnapi->status_mapping,
GFP_KERNEL);
if (!tnapi->hw_status)
goto err_out;
memset(tnapi->hw_status, 0, TG3_HW_STATUS_SIZE);
sblk = tnapi->hw_status;
if (tg3_rx_prodring_init(tp, &tnapi->prodring))
goto err_out;
/* If multivector TSS is enabled, vector 0 does not handle
* tx interrupts. Don't allocate any resources for it.
*/
if ((!i && !tg3_flag(tp, ENABLE_TSS)) ||
(i && tg3_flag(tp, ENABLE_TSS))) {
tnapi->tx_buffers = kzalloc(
sizeof(struct tg3_tx_ring_info) *
TG3_TX_RING_SIZE, GFP_KERNEL);
if (!tnapi->tx_buffers)
goto err_out;
tnapi->tx_ring = dma_alloc_coherent(&tp->pdev->dev,
TG3_TX_RING_BYTES,
&tnapi->tx_desc_mapping,
GFP_KERNEL);
if (!tnapi->tx_ring)
goto err_out;
}
/*
* When RSS is enabled, the status block format changes
* slightly. The "rx_jumbo_consumer", "reserved",
* and "rx_mini_consumer" members get mapped to the
* other three rx return ring producer indexes.
*/
switch (i) {
default:
if (tg3_flag(tp, ENABLE_RSS)) {
tnapi->rx_rcb_prod_idx = NULL;
break;
}
/* Fall through */
case 1:
tnapi->rx_rcb_prod_idx = &sblk->idx[0].rx_producer;
break;
case 2:
tnapi->rx_rcb_prod_idx = &sblk->rx_jumbo_consumer;
break;
case 3:
tnapi->rx_rcb_prod_idx = &sblk->reserved;
break;
case 4:
tnapi->rx_rcb_prod_idx = &sblk->rx_mini_consumer;
break;
}
/*
* If multivector RSS is enabled, vector 0 does not handle
* rx or tx interrupts. Don't allocate any resources for it.
*/
if (!i && tg3_flag(tp, ENABLE_RSS))
continue;
tnapi->rx_rcb = dma_alloc_coherent(&tp->pdev->dev,
TG3_RX_RCB_RING_BYTES(tp),
&tnapi->rx_rcb_mapping,
GFP_KERNEL);
if (!tnapi->rx_rcb)
goto err_out;
memset(tnapi->rx_rcb, 0, TG3_RX_RCB_RING_BYTES(tp));
}
return 0;
err_out:
tg3_free_consistent(tp);
return -ENOMEM;
}
#define MAX_WAIT_CNT 1000
/* To stop a block, clear the enable bit and poll till it
* clears. tp->lock is held.
*/
static int tg3_stop_block(struct tg3 *tp, unsigned long ofs, u32 enable_bit, int silent)
{
unsigned int i;
u32 val;
if (tg3_flag(tp, 5705_PLUS)) {
switch (ofs) {
case RCVLSC_MODE:
case DMAC_MODE:
case MBFREE_MODE:
case BUFMGR_MODE:
case MEMARB_MODE:
/* We can't enable/disable these bits of the
* 5705/5750, just say success.
*/
return 0;
default:
break;
}
}
val = tr32(ofs);
val &= ~enable_bit;
tw32_f(ofs, val);
for (i = 0; i < MAX_WAIT_CNT; i++) {
udelay(100);
val = tr32(ofs);
if ((val & enable_bit) == 0)
break;
}
if (i == MAX_WAIT_CNT && !silent) {
dev_err(&tp->pdev->dev,
"tg3_stop_block timed out, ofs=%lx enable_bit=%x\n",
ofs, enable_bit);
return -ENODEV;
}
return 0;
}
/* tp->lock is held. */
static int tg3_abort_hw(struct tg3 *tp, int silent)
{
int i, err;
tg3_disable_ints(tp);
tp->rx_mode &= ~RX_MODE_ENABLE;
tw32_f(MAC_RX_MODE, tp->rx_mode);
udelay(10);
err = tg3_stop_block(tp, RCVBDI_MODE, RCVBDI_MODE_ENABLE, silent);
err |= tg3_stop_block(tp, RCVLPC_MODE, RCVLPC_MODE_ENABLE, silent);
err |= tg3_stop_block(tp, RCVLSC_MODE, RCVLSC_MODE_ENABLE, silent);
err |= tg3_stop_block(tp, RCVDBDI_MODE, RCVDBDI_MODE_ENABLE, silent);
err |= tg3_stop_block(tp, RCVDCC_MODE, RCVDCC_MODE_ENABLE, silent);
err |= tg3_stop_block(tp, RCVCC_MODE, RCVCC_MODE_ENABLE, silent);
err |= tg3_stop_block(tp, SNDBDS_MODE, SNDBDS_MODE_ENABLE, silent);
err |= tg3_stop_block(tp, SNDBDI_MODE, SNDBDI_MODE_ENABLE, silent);
err |= tg3_stop_block(tp, SNDDATAI_MODE, SNDDATAI_MODE_ENABLE, silent);
err |= tg3_stop_block(tp, RDMAC_MODE, RDMAC_MODE_ENABLE, silent);
err |= tg3_stop_block(tp, SNDDATAC_MODE, SNDDATAC_MODE_ENABLE, silent);
err |= tg3_stop_block(tp, DMAC_MODE, DMAC_MODE_ENABLE, silent);
err |= tg3_stop_block(tp, SNDBDC_MODE, SNDBDC_MODE_ENABLE, silent);
tp->mac_mode &= ~MAC_MODE_TDE_ENABLE;
tw32_f(MAC_MODE, tp->mac_mode);
udelay(40);
tp->tx_mode &= ~TX_MODE_ENABLE;
tw32_f(MAC_TX_MODE, tp->tx_mode);
for (i = 0; i < MAX_WAIT_CNT; i++) {
udelay(100);
if (!(tr32(MAC_TX_MODE) & TX_MODE_ENABLE))
break;
}
if (i >= MAX_WAIT_CNT) {
dev_err(&tp->pdev->dev,
"%s timed out, TX_MODE_ENABLE will not clear "
"MAC_TX_MODE=%08x\n", __func__, tr32(MAC_TX_MODE));
err |= -ENODEV;
}
err |= tg3_stop_block(tp, HOSTCC_MODE, HOSTCC_MODE_ENABLE, silent);
err |= tg3_stop_block(tp, WDMAC_MODE, WDMAC_MODE_ENABLE, silent);
err |= tg3_stop_block(tp, MBFREE_MODE, MBFREE_MODE_ENABLE, silent);
tw32(FTQ_RESET, 0xffffffff);
tw32(FTQ_RESET, 0x00000000);
err |= tg3_stop_block(tp, BUFMGR_MODE, BUFMGR_MODE_ENABLE, silent);
err |= tg3_stop_block(tp, MEMARB_MODE, MEMARB_MODE_ENABLE, silent);
for (i = 0; i < tp->irq_cnt; i++) {
struct tg3_napi *tnapi = &tp->napi[i];
if (tnapi->hw_status)
memset(tnapi->hw_status, 0, TG3_HW_STATUS_SIZE);
}
return err;
}
/* Save PCI command register before chip reset */
static void tg3_save_pci_state(struct tg3 *tp)
{
pci_read_config_word(tp->pdev, PCI_COMMAND, &tp->pci_cmd);
}
/* Restore PCI state after chip reset */
static void tg3_restore_pci_state(struct tg3 *tp)
{
u32 val;
/* Re-enable indirect register accesses. */
pci_write_config_dword(tp->pdev, TG3PCI_MISC_HOST_CTRL,
tp->misc_host_ctrl);
/* Set MAX PCI retry to zero. */
val = (PCISTATE_ROM_ENABLE | PCISTATE_ROM_RETRY_ENABLE);
if (tp->pci_chip_rev_id == CHIPREV_ID_5704_A0 &&
tg3_flag(tp, PCIX_MODE))
val |= PCISTATE_RETRY_SAME_DMA;
/* Allow reads and writes to the APE register and memory space. */
if (tg3_flag(tp, ENABLE_APE))
val |= PCISTATE_ALLOW_APE_CTLSPC_WR |
PCISTATE_ALLOW_APE_SHMEM_WR |
PCISTATE_ALLOW_APE_PSPACE_WR;
pci_write_config_dword(tp->pdev, TG3PCI_PCISTATE, val);
pci_write_config_word(tp->pdev, PCI_COMMAND, tp->pci_cmd);
if (!tg3_flag(tp, PCI_EXPRESS)) {
pci_write_config_byte(tp->pdev, PCI_CACHE_LINE_SIZE,
tp->pci_cacheline_sz);
pci_write_config_byte(tp->pdev, PCI_LATENCY_TIMER,
tp->pci_lat_timer);
}
/* Make sure PCI-X relaxed ordering bit is clear. */
if (tg3_flag(tp, PCIX_MODE)) {
u16 pcix_cmd;
pci_read_config_word(tp->pdev, tp->pcix_cap + PCI_X_CMD,
&pcix_cmd);
pcix_cmd &= ~PCI_X_CMD_ERO;
pci_write_config_word(tp->pdev, tp->pcix_cap + PCI_X_CMD,
pcix_cmd);
}
if (tg3_flag(tp, 5780_CLASS)) {
/* Chip reset on 5780 will reset MSI enable bit,
* so need to restore it.
*/
if (tg3_flag(tp, USING_MSI)) {
u16 ctrl;
pci_read_config_word(tp->pdev,
tp->msi_cap + PCI_MSI_FLAGS,
&ctrl);
pci_write_config_word(tp->pdev,
tp->msi_cap + PCI_MSI_FLAGS,
ctrl | PCI_MSI_FLAGS_ENABLE);
val = tr32(MSGINT_MODE);
tw32(MSGINT_MODE, val | MSGINT_MODE_ENABLE);
}
}
}
/* tp->lock is held. */
static int tg3_chip_reset(struct tg3 *tp)
{
u32 val;
void (*write_op)(struct tg3 *, u32, u32);
int i, err;
tg3_nvram_lock(tp);
tg3_ape_lock(tp, TG3_APE_LOCK_GRC);
/* No matching tg3_nvram_unlock() after this because
* chip reset below will undo the nvram lock.
*/
tp->nvram_lock_cnt = 0;
/* GRC_MISC_CFG core clock reset will clear the memory
* enable bit in PCI register 4 and the MSI enable bit
* on some chips, so we save relevant registers here.
*/
tg3_save_pci_state(tp);
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5752 ||
tg3_flag(tp, 5755_PLUS))
tw32(GRC_FASTBOOT_PC, 0);
/*
* We must avoid the readl() that normally takes place.
* It locks machines, causes machine checks, and other
* fun things. So, temporarily disable the 5701
* hardware workaround, while we do the reset.
*/
write_op = tp->write32;
if (write_op == tg3_write_flush_reg32)
tp->write32 = tg3_write32;
/* Prevent the irq handler from reading or writing PCI registers
* during chip reset when the memory enable bit in the PCI command
* register may be cleared. The chip does not generate interrupt
* at this time, but the irq handler may still be called due to irq
* sharing or irqpoll.
*/
tg3_flag_set(tp, CHIP_RESETTING);
for (i = 0; i < tp->irq_cnt; i++) {
struct tg3_napi *tnapi = &tp->napi[i];
if (tnapi->hw_status) {
tnapi->hw_status->status = 0;
tnapi->hw_status->status_tag = 0;
}
tnapi->last_tag = 0;
tnapi->last_irq_tag = 0;
}
smp_mb();
for (i = 0; i < tp->irq_cnt; i++)
synchronize_irq(tp->napi[i].irq_vec);
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_57780) {
val = tr32(TG3_PCIE_LNKCTL) & ~TG3_PCIE_LNKCTL_L1_PLL_PD_EN;
tw32(TG3_PCIE_LNKCTL, val | TG3_PCIE_LNKCTL_L1_PLL_PD_DIS);
}
/* do the reset */
val = GRC_MISC_CFG_CORECLK_RESET;
if (tg3_flag(tp, PCI_EXPRESS)) {
/* Force PCIe 1.0a mode */
if (GET_ASIC_REV(tp->pci_chip_rev_id) != ASIC_REV_5785 &&
!tg3_flag(tp, 57765_PLUS) &&
tr32(TG3_PCIE_PHY_TSTCTL) ==
(TG3_PCIE_PHY_TSTCTL_PCIE10 | TG3_PCIE_PHY_TSTCTL_PSCRAM))
tw32(TG3_PCIE_PHY_TSTCTL, TG3_PCIE_PHY_TSTCTL_PSCRAM);
if (tp->pci_chip_rev_id != CHIPREV_ID_5750_A0) {
tw32(GRC_MISC_CFG, (1 << 29));
val |= (1 << 29);
}
}
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5906) {
tw32(VCPU_STATUS, tr32(VCPU_STATUS) | VCPU_STATUS_DRV_RESET);
tw32(GRC_VCPU_EXT_CTRL,
tr32(GRC_VCPU_EXT_CTRL) & ~GRC_VCPU_EXT_CTRL_HALT_CPU);
}
/* Manage gphy power for all CPMU absent PCIe devices. */
if (tg3_flag(tp, 5705_PLUS) && !tg3_flag(tp, CPMU_PRESENT))
val |= GRC_MISC_CFG_KEEP_GPHY_POWER;
tw32(GRC_MISC_CFG, val);
/* restore 5701 hardware bug workaround write method */
tp->write32 = write_op;
/* Unfortunately, we have to delay before the PCI read back.
* Some 575X chips even will not respond to a PCI cfg access
* when the reset command is given to the chip.
*
* How do these hardware designers expect things to work
* properly if the PCI write is posted for a long period
* of time? It is always necessary to have some method by
* which a register read back can occur to push the write
* out which does the reset.
*
* For most tg3 variants the trick below was working.
* Ho hum...
*/
udelay(120);
/* Flush PCI posted writes. The normal MMIO registers
* are inaccessible at this time so this is the only
* way to make this reliably (actually, this is no longer
* the case, see above). I tried to use indirect
* register read/write but this upset some 5701 variants.
*/
pci_read_config_dword(tp->pdev, PCI_COMMAND, &val);
udelay(120);
if (tg3_flag(tp, PCI_EXPRESS) && pci_pcie_cap(tp->pdev)) {
u16 val16;
if (tp->pci_chip_rev_id == CHIPREV_ID_5750_A0) {
int i;
u32 cfg_val;
/* Wait for link training to complete. */
for (i = 0; i < 5000; i++)
udelay(100);
pci_read_config_dword(tp->pdev, 0xc4, &cfg_val);
pci_write_config_dword(tp->pdev, 0xc4,
cfg_val | (1 << 15));
}
/* Clear the "no snoop" and "relaxed ordering" bits. */
pci_read_config_word(tp->pdev,
pci_pcie_cap(tp->pdev) + PCI_EXP_DEVCTL,
&val16);
val16 &= ~(PCI_EXP_DEVCTL_RELAX_EN |
PCI_EXP_DEVCTL_NOSNOOP_EN);
/*
* Older PCIe devices only support the 128 byte
* MPS setting. Enforce the restriction.
*/
if (!tg3_flag(tp, CPMU_PRESENT))
val16 &= ~PCI_EXP_DEVCTL_PAYLOAD;
pci_write_config_word(tp->pdev,
pci_pcie_cap(tp->pdev) + PCI_EXP_DEVCTL,
val16);
/* Clear error status */
pci_write_config_word(tp->pdev,
pci_pcie_cap(tp->pdev) + PCI_EXP_DEVSTA,
PCI_EXP_DEVSTA_CED |
PCI_EXP_DEVSTA_NFED |
PCI_EXP_DEVSTA_FED |
PCI_EXP_DEVSTA_URD);
}
tg3_restore_pci_state(tp);
tg3_flag_clear(tp, CHIP_RESETTING);
tg3_flag_clear(tp, ERROR_PROCESSED);
val = 0;
if (tg3_flag(tp, 5780_CLASS))
val = tr32(MEMARB_MODE);
tw32(MEMARB_MODE, val | MEMARB_MODE_ENABLE);
if (tp->pci_chip_rev_id == CHIPREV_ID_5750_A3) {
tg3_stop_fw(tp);
tw32(0x5000, 0x400);
}
tw32(GRC_MODE, tp->grc_mode);
if (tp->pci_chip_rev_id == CHIPREV_ID_5705_A0) {
val = tr32(0xc4);
tw32(0xc4, val | (1 << 15));
}
if ((tp->nic_sram_data_cfg & NIC_SRAM_DATA_CFG_MINI_PCI) != 0 &&
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5705) {
tp->pci_clock_ctrl |= CLOCK_CTRL_CLKRUN_OENABLE;
if (tp->pci_chip_rev_id == CHIPREV_ID_5705_A0)
tp->pci_clock_ctrl |= CLOCK_CTRL_FORCE_CLKRUN;
tw32(TG3PCI_CLOCK_CTRL, tp->pci_clock_ctrl);
}
if (tp->phy_flags & TG3_PHYFLG_PHY_SERDES) {
tp->mac_mode = MAC_MODE_PORT_MODE_TBI;
val = tp->mac_mode;
} else if (tp->phy_flags & TG3_PHYFLG_MII_SERDES) {
tp->mac_mode = MAC_MODE_PORT_MODE_GMII;
val = tp->mac_mode;
} else
val = 0;
tw32_f(MAC_MODE, val);
udelay(40);
tg3_ape_unlock(tp, TG3_APE_LOCK_GRC);
err = tg3_poll_fw(tp);
if (err)
return err;
tg3_mdio_start(tp);
if (tg3_flag(tp, PCI_EXPRESS) &&
tp->pci_chip_rev_id != CHIPREV_ID_5750_A0 &&
GET_ASIC_REV(tp->pci_chip_rev_id) != ASIC_REV_5785 &&
!tg3_flag(tp, 57765_PLUS)) {
val = tr32(0x7c00);
tw32(0x7c00, val | (1 << 25));
}
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5720) {
val = tr32(TG3_CPMU_CLCK_ORIDE);
tw32(TG3_CPMU_CLCK_ORIDE, val & ~CPMU_CLCK_ORIDE_MAC_ORIDE_EN);
}
/* Reprobe ASF enable state. */
tg3_flag_clear(tp, ENABLE_ASF);
tg3_flag_clear(tp, ASF_NEW_HANDSHAKE);
tg3_read_mem(tp, NIC_SRAM_DATA_SIG, &val);
if (val == NIC_SRAM_DATA_SIG_MAGIC) {
u32 nic_cfg;
tg3_read_mem(tp, NIC_SRAM_DATA_CFG, &nic_cfg);
if (nic_cfg & NIC_SRAM_DATA_CFG_ASF_ENABLE) {
tg3_flag_set(tp, ENABLE_ASF);
tp->last_event_jiffies = jiffies;
if (tg3_flag(tp, 5750_PLUS))
tg3_flag_set(tp, ASF_NEW_HANDSHAKE);
}
}
return 0;
}
static void tg3_get_nstats(struct tg3 *, struct rtnl_link_stats64 *);
static void tg3_get_estats(struct tg3 *, struct tg3_ethtool_stats *);
/* tp->lock is held. */
static int tg3_halt(struct tg3 *tp, int kind, int silent)
{
int err;
tg3_stop_fw(tp);
tg3_write_sig_pre_reset(tp, kind);
tg3_abort_hw(tp, silent);
err = tg3_chip_reset(tp);
__tg3_set_mac_addr(tp, 0);
tg3_write_sig_legacy(tp, kind);
tg3_write_sig_post_reset(tp, kind);
if (tp->hw_stats) {
/* Save the stats across chip resets... */
tg3_get_nstats(tp, &tp->net_stats_prev);
tg3_get_estats(tp, &tp->estats_prev);
/* And make sure the next sample is new data */
memset(tp->hw_stats, 0, sizeof(struct tg3_hw_stats));
}
if (err)
return err;
return 0;
}
static int tg3_set_mac_addr(struct net_device *dev, void *p)
{
struct tg3 *tp = netdev_priv(dev);
struct sockaddr *addr = p;
int err = 0, skip_mac_1 = 0;
if (!is_valid_ether_addr(addr->sa_data))
return -EADDRNOTAVAIL;
memcpy(dev->dev_addr, addr->sa_data, dev->addr_len);
if (!netif_running(dev))
return 0;
if (tg3_flag(tp, ENABLE_ASF)) {
u32 addr0_high, addr0_low, addr1_high, addr1_low;
addr0_high = tr32(MAC_ADDR_0_HIGH);
addr0_low = tr32(MAC_ADDR_0_LOW);
addr1_high = tr32(MAC_ADDR_1_HIGH);
addr1_low = tr32(MAC_ADDR_1_LOW);
/* Skip MAC addr 1 if ASF is using it. */
if ((addr0_high != addr1_high || addr0_low != addr1_low) &&
!(addr1_high == 0 && addr1_low == 0))
skip_mac_1 = 1;
}
spin_lock_bh(&tp->lock);
__tg3_set_mac_addr(tp, skip_mac_1);
spin_unlock_bh(&tp->lock);
return err;
}
/* tp->lock is held. */
static void tg3_set_bdinfo(struct tg3 *tp, u32 bdinfo_addr,
dma_addr_t mapping, u32 maxlen_flags,
u32 nic_addr)
{
tg3_write_mem(tp,
(bdinfo_addr + TG3_BDINFO_HOST_ADDR + TG3_64BIT_REG_HIGH),
((u64) mapping >> 32));
tg3_write_mem(tp,
(bdinfo_addr + TG3_BDINFO_HOST_ADDR + TG3_64BIT_REG_LOW),
((u64) mapping & 0xffffffff));
tg3_write_mem(tp,
(bdinfo_addr + TG3_BDINFO_MAXLEN_FLAGS),
maxlen_flags);
if (!tg3_flag(tp, 5705_PLUS))
tg3_write_mem(tp,
(bdinfo_addr + TG3_BDINFO_NIC_ADDR),
nic_addr);
}
static void __tg3_set_coalesce(struct tg3 *tp, struct ethtool_coalesce *ec)
{
int i;
if (!tg3_flag(tp, ENABLE_TSS)) {
tw32(HOSTCC_TXCOL_TICKS, ec->tx_coalesce_usecs);
tw32(HOSTCC_TXMAX_FRAMES, ec->tx_max_coalesced_frames);
tw32(HOSTCC_TXCOAL_MAXF_INT, ec->tx_max_coalesced_frames_irq);
} else {
tw32(HOSTCC_TXCOL_TICKS, 0);
tw32(HOSTCC_TXMAX_FRAMES, 0);
tw32(HOSTCC_TXCOAL_MAXF_INT, 0);
}
if (!tg3_flag(tp, ENABLE_RSS)) {
tw32(HOSTCC_RXCOL_TICKS, ec->rx_coalesce_usecs);
tw32(HOSTCC_RXMAX_FRAMES, ec->rx_max_coalesced_frames);
tw32(HOSTCC_RXCOAL_MAXF_INT, ec->rx_max_coalesced_frames_irq);
} else {
tw32(HOSTCC_RXCOL_TICKS, 0);
tw32(HOSTCC_RXMAX_FRAMES, 0);
tw32(HOSTCC_RXCOAL_MAXF_INT, 0);
}
if (!tg3_flag(tp, 5705_PLUS)) {
u32 val = ec->stats_block_coalesce_usecs;
tw32(HOSTCC_RXCOAL_TICK_INT, ec->rx_coalesce_usecs_irq);
tw32(HOSTCC_TXCOAL_TICK_INT, ec->tx_coalesce_usecs_irq);
if (!netif_carrier_ok(tp->dev))
val = 0;
tw32(HOSTCC_STAT_COAL_TICKS, val);
}
for (i = 0; i < tp->irq_cnt - 1; i++) {
u32 reg;
reg = HOSTCC_RXCOL_TICKS_VEC1 + i * 0x18;
tw32(reg, ec->rx_coalesce_usecs);
reg = HOSTCC_RXMAX_FRAMES_VEC1 + i * 0x18;
tw32(reg, ec->rx_max_coalesced_frames);
reg = HOSTCC_RXCOAL_MAXF_INT_VEC1 + i * 0x18;
tw32(reg, ec->rx_max_coalesced_frames_irq);
if (tg3_flag(tp, ENABLE_TSS)) {
reg = HOSTCC_TXCOL_TICKS_VEC1 + i * 0x18;
tw32(reg, ec->tx_coalesce_usecs);
reg = HOSTCC_TXMAX_FRAMES_VEC1 + i * 0x18;
tw32(reg, ec->tx_max_coalesced_frames);
reg = HOSTCC_TXCOAL_MAXF_INT_VEC1 + i * 0x18;
tw32(reg, ec->tx_max_coalesced_frames_irq);
}
}
for (; i < tp->irq_max - 1; i++) {
tw32(HOSTCC_RXCOL_TICKS_VEC1 + i * 0x18, 0);
tw32(HOSTCC_RXMAX_FRAMES_VEC1 + i * 0x18, 0);
tw32(HOSTCC_RXCOAL_MAXF_INT_VEC1 + i * 0x18, 0);
if (tg3_flag(tp, ENABLE_TSS)) {
tw32(HOSTCC_TXCOL_TICKS_VEC1 + i * 0x18, 0);
tw32(HOSTCC_TXMAX_FRAMES_VEC1 + i * 0x18, 0);
tw32(HOSTCC_TXCOAL_MAXF_INT_VEC1 + i * 0x18, 0);
}
}
}
/* tp->lock is held. */
static void tg3_rings_reset(struct tg3 *tp)
{
int i;
u32 stblk, txrcb, rxrcb, limit;
struct tg3_napi *tnapi = &tp->napi[0];
/* Disable all transmit rings but the first. */
if (!tg3_flag(tp, 5705_PLUS))
limit = NIC_SRAM_SEND_RCB + TG3_BDINFO_SIZE * 16;
else if (tg3_flag(tp, 5717_PLUS))
limit = NIC_SRAM_SEND_RCB + TG3_BDINFO_SIZE * 4;
else if (tg3_flag(tp, 57765_CLASS))
limit = NIC_SRAM_SEND_RCB + TG3_BDINFO_SIZE * 2;
else
limit = NIC_SRAM_SEND_RCB + TG3_BDINFO_SIZE;
for (txrcb = NIC_SRAM_SEND_RCB + TG3_BDINFO_SIZE;
txrcb < limit; txrcb += TG3_BDINFO_SIZE)
tg3_write_mem(tp, txrcb + TG3_BDINFO_MAXLEN_FLAGS,
BDINFO_FLAGS_DISABLED);
/* Disable all receive return rings but the first. */
if (tg3_flag(tp, 5717_PLUS))
limit = NIC_SRAM_RCV_RET_RCB + TG3_BDINFO_SIZE * 17;
else if (!tg3_flag(tp, 5705_PLUS))
limit = NIC_SRAM_RCV_RET_RCB + TG3_BDINFO_SIZE * 16;
else if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5755 ||
tg3_flag(tp, 57765_CLASS))
limit = NIC_SRAM_RCV_RET_RCB + TG3_BDINFO_SIZE * 4;
else
limit = NIC_SRAM_RCV_RET_RCB + TG3_BDINFO_SIZE;
for (rxrcb = NIC_SRAM_RCV_RET_RCB + TG3_BDINFO_SIZE;
rxrcb < limit; rxrcb += TG3_BDINFO_SIZE)
tg3_write_mem(tp, rxrcb + TG3_BDINFO_MAXLEN_FLAGS,
BDINFO_FLAGS_DISABLED);
/* Disable interrupts */
tw32_mailbox_f(tp->napi[0].int_mbox, 1);
tp->napi[0].chk_msi_cnt = 0;
tp->napi[0].last_rx_cons = 0;
tp->napi[0].last_tx_cons = 0;
/* Zero mailbox registers. */
if (tg3_flag(tp, SUPPORT_MSIX)) {
for (i = 1; i < tp->irq_max; i++) {
tp->napi[i].tx_prod = 0;
tp->napi[i].tx_cons = 0;
if (tg3_flag(tp, ENABLE_TSS))
tw32_mailbox(tp->napi[i].prodmbox, 0);
tw32_rx_mbox(tp->napi[i].consmbox, 0);
tw32_mailbox_f(tp->napi[i].int_mbox, 1);
tp->napi[i].chk_msi_cnt = 0;
tp->napi[i].last_rx_cons = 0;
tp->napi[i].last_tx_cons = 0;
}
if (!tg3_flag(tp, ENABLE_TSS))
tw32_mailbox(tp->napi[0].prodmbox, 0);
} else {
tp->napi[0].tx_prod = 0;
tp->napi[0].tx_cons = 0;
tw32_mailbox(tp->napi[0].prodmbox, 0);
tw32_rx_mbox(tp->napi[0].consmbox, 0);
}
/* Make sure the NIC-based send BD rings are disabled. */
if (!tg3_flag(tp, 5705_PLUS)) {
u32 mbox = MAILBOX_SNDNIC_PROD_IDX_0 + TG3_64BIT_REG_LOW;
for (i = 0; i < 16; i++)
tw32_tx_mbox(mbox + i * 8, 0);
}
txrcb = NIC_SRAM_SEND_RCB;
rxrcb = NIC_SRAM_RCV_RET_RCB;
/* Clear status block in ram. */
memset(tnapi->hw_status, 0, TG3_HW_STATUS_SIZE);
/* Set status block DMA address */
tw32(HOSTCC_STATUS_BLK_HOST_ADDR + TG3_64BIT_REG_HIGH,
((u64) tnapi->status_mapping >> 32));
tw32(HOSTCC_STATUS_BLK_HOST_ADDR + TG3_64BIT_REG_LOW,
((u64) tnapi->status_mapping & 0xffffffff));
if (tnapi->tx_ring) {
tg3_set_bdinfo(tp, txrcb, tnapi->tx_desc_mapping,
(TG3_TX_RING_SIZE <<
BDINFO_FLAGS_MAXLEN_SHIFT),
NIC_SRAM_TX_BUFFER_DESC);
txrcb += TG3_BDINFO_SIZE;
}
if (tnapi->rx_rcb) {
tg3_set_bdinfo(tp, rxrcb, tnapi->rx_rcb_mapping,
(tp->rx_ret_ring_mask + 1) <<
BDINFO_FLAGS_MAXLEN_SHIFT, 0);
rxrcb += TG3_BDINFO_SIZE;
}
stblk = HOSTCC_STATBLCK_RING1;
for (i = 1, tnapi++; i < tp->irq_cnt; i++, tnapi++) {
u64 mapping = (u64)tnapi->status_mapping;
tw32(stblk + TG3_64BIT_REG_HIGH, mapping >> 32);
tw32(stblk + TG3_64BIT_REG_LOW, mapping & 0xffffffff);
/* Clear status block in ram. */
memset(tnapi->hw_status, 0, TG3_HW_STATUS_SIZE);
if (tnapi->tx_ring) {
tg3_set_bdinfo(tp, txrcb, tnapi->tx_desc_mapping,
(TG3_TX_RING_SIZE <<
BDINFO_FLAGS_MAXLEN_SHIFT),
NIC_SRAM_TX_BUFFER_DESC);
txrcb += TG3_BDINFO_SIZE;
}
tg3_set_bdinfo(tp, rxrcb, tnapi->rx_rcb_mapping,
((tp->rx_ret_ring_mask + 1) <<
BDINFO_FLAGS_MAXLEN_SHIFT), 0);
stblk += 8;
rxrcb += TG3_BDINFO_SIZE;
}
}
static void tg3_setup_rxbd_thresholds(struct tg3 *tp)
{
u32 val, bdcache_maxcnt, host_rep_thresh, nic_rep_thresh;
if (!tg3_flag(tp, 5750_PLUS) ||
tg3_flag(tp, 5780_CLASS) ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5750 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5752 ||
tg3_flag(tp, 57765_PLUS))
bdcache_maxcnt = TG3_SRAM_RX_STD_BDCACHE_SIZE_5700;
else if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5755 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5787)
bdcache_maxcnt = TG3_SRAM_RX_STD_BDCACHE_SIZE_5755;
else
bdcache_maxcnt = TG3_SRAM_RX_STD_BDCACHE_SIZE_5906;
nic_rep_thresh = min(bdcache_maxcnt / 2, tp->rx_std_max_post);
host_rep_thresh = max_t(u32, tp->rx_pending / 8, 1);
val = min(nic_rep_thresh, host_rep_thresh);
tw32(RCVBDI_STD_THRESH, val);
if (tg3_flag(tp, 57765_PLUS))
tw32(STD_REPLENISH_LWM, bdcache_maxcnt);
if (!tg3_flag(tp, JUMBO_CAPABLE) || tg3_flag(tp, 5780_CLASS))
return;
bdcache_maxcnt = TG3_SRAM_RX_JMB_BDCACHE_SIZE_5700;
host_rep_thresh = max_t(u32, tp->rx_jumbo_pending / 8, 1);
val = min(bdcache_maxcnt / 2, host_rep_thresh);
tw32(RCVBDI_JUMBO_THRESH, val);
if (tg3_flag(tp, 57765_PLUS))
tw32(JMB_REPLENISH_LWM, bdcache_maxcnt);
}
static inline u32 calc_crc(unsigned char *buf, int len)
{
u32 reg;
u32 tmp;
int j, k;
reg = 0xffffffff;
for (j = 0; j < len; j++) {
reg ^= buf[j];
for (k = 0; k < 8; k++) {
tmp = reg & 0x01;
reg >>= 1;
if (tmp)
reg ^= 0xedb88320;
}
}
return ~reg;
}
static void tg3_set_multi(struct tg3 *tp, unsigned int accept_all)
{
/* accept or reject all multicast frames */
tw32(MAC_HASH_REG_0, accept_all ? 0xffffffff : 0);
tw32(MAC_HASH_REG_1, accept_all ? 0xffffffff : 0);
tw32(MAC_HASH_REG_2, accept_all ? 0xffffffff : 0);
tw32(MAC_HASH_REG_3, accept_all ? 0xffffffff : 0);
}
static void __tg3_set_rx_mode(struct net_device *dev)
{
struct tg3 *tp = netdev_priv(dev);
u32 rx_mode;
rx_mode = tp->rx_mode & ~(RX_MODE_PROMISC |
RX_MODE_KEEP_VLAN_TAG);
#if !defined(CONFIG_VLAN_8021Q) && !defined(CONFIG_VLAN_8021Q_MODULE)
/* When ASF is in use, we always keep the RX_MODE_KEEP_VLAN_TAG
* flag clear.
*/
if (!tg3_flag(tp, ENABLE_ASF))
rx_mode |= RX_MODE_KEEP_VLAN_TAG;
#endif
if (dev->flags & IFF_PROMISC) {
/* Promiscuous mode. */
rx_mode |= RX_MODE_PROMISC;
} else if (dev->flags & IFF_ALLMULTI) {
/* Accept all multicast. */
tg3_set_multi(tp, 1);
} else if (netdev_mc_empty(dev)) {
/* Reject all multicast. */
tg3_set_multi(tp, 0);
} else {
/* Accept one or more multicast(s). */
struct netdev_hw_addr *ha;
u32 mc_filter[4] = { 0, };
u32 regidx;
u32 bit;
u32 crc;
netdev_for_each_mc_addr(ha, dev) {
crc = calc_crc(ha->addr, ETH_ALEN);
bit = ~crc & 0x7f;
regidx = (bit & 0x60) >> 5;
bit &= 0x1f;
mc_filter[regidx] |= (1 << bit);
}
tw32(MAC_HASH_REG_0, mc_filter[0]);
tw32(MAC_HASH_REG_1, mc_filter[1]);
tw32(MAC_HASH_REG_2, mc_filter[2]);
tw32(MAC_HASH_REG_3, mc_filter[3]);
}
if (rx_mode != tp->rx_mode) {
tp->rx_mode = rx_mode;
tw32_f(MAC_RX_MODE, rx_mode);
udelay(10);
}
}
static void tg3_rss_init_dflt_indir_tbl(struct tg3 *tp)
{
int i;
for (i = 0; i < TG3_RSS_INDIR_TBL_SIZE; i++)
tp->rss_ind_tbl[i] =
ethtool_rxfh_indir_default(i, tp->irq_cnt - 1);
}
static void tg3_rss_check_indir_tbl(struct tg3 *tp)
{
int i;
if (!tg3_flag(tp, SUPPORT_MSIX))
return;
if (tp->irq_cnt <= 2) {
memset(&tp->rss_ind_tbl[0], 0, sizeof(tp->rss_ind_tbl));
return;
}
/* Validate table against current IRQ count */
for (i = 0; i < TG3_RSS_INDIR_TBL_SIZE; i++) {
if (tp->rss_ind_tbl[i] >= tp->irq_cnt - 1)
break;
}
if (i != TG3_RSS_INDIR_TBL_SIZE)
tg3_rss_init_dflt_indir_tbl(tp);
}
static void tg3_rss_write_indir_tbl(struct tg3 *tp)
{
int i = 0;
u32 reg = MAC_RSS_INDIR_TBL_0;
while (i < TG3_RSS_INDIR_TBL_SIZE) {
u32 val = tp->rss_ind_tbl[i];
i++;
for (; i % 8; i++) {
val <<= 4;
val |= tp->rss_ind_tbl[i];
}
tw32(reg, val);
reg += 4;
}
}
/* tp->lock is held. */
static int tg3_reset_hw(struct tg3 *tp, int reset_phy)
{
u32 val, rdmac_mode;
int i, err, limit;
struct tg3_rx_prodring_set *tpr = &tp->napi[0].prodring;
tg3_disable_ints(tp);
tg3_stop_fw(tp);
tg3_write_sig_pre_reset(tp, RESET_KIND_INIT);
if (tg3_flag(tp, INIT_COMPLETE))
tg3_abort_hw(tp, 1);
/* Enable MAC control of LPI */
if (tp->phy_flags & TG3_PHYFLG_EEE_CAP) {
tw32_f(TG3_CPMU_EEE_LNKIDL_CTRL,
TG3_CPMU_EEE_LNKIDL_PCIE_NL0 |
TG3_CPMU_EEE_LNKIDL_UART_IDL);
tw32_f(TG3_CPMU_EEE_CTRL,
TG3_CPMU_EEE_CTRL_EXIT_20_1_US);
val = TG3_CPMU_EEEMD_ERLY_L1_XIT_DET |
TG3_CPMU_EEEMD_LPI_IN_TX |
TG3_CPMU_EEEMD_LPI_IN_RX |
TG3_CPMU_EEEMD_EEE_ENABLE;
if (GET_ASIC_REV(tp->pci_chip_rev_id) != ASIC_REV_5717)
val |= TG3_CPMU_EEEMD_SND_IDX_DET_EN;
if (tg3_flag(tp, ENABLE_APE))
val |= TG3_CPMU_EEEMD_APE_TX_DET_EN;
tw32_f(TG3_CPMU_EEE_MODE, val);
tw32_f(TG3_CPMU_EEE_DBTMR1,
TG3_CPMU_DBTMR1_PCIEXIT_2047US |
TG3_CPMU_DBTMR1_LNKIDLE_2047US);
tw32_f(TG3_CPMU_EEE_DBTMR2,
TG3_CPMU_DBTMR2_APE_TX_2047US |
TG3_CPMU_DBTMR2_TXIDXEQ_2047US);
}
if (reset_phy)
tg3_phy_reset(tp);
err = tg3_chip_reset(tp);
if (err)
return err;
tg3_write_sig_legacy(tp, RESET_KIND_INIT);
if (GET_CHIP_REV(tp->pci_chip_rev_id) == CHIPREV_5784_AX) {
val = tr32(TG3_CPMU_CTRL);
val &= ~(CPMU_CTRL_LINK_AWARE_MODE | CPMU_CTRL_LINK_IDLE_MODE);
tw32(TG3_CPMU_CTRL, val);
val = tr32(TG3_CPMU_LSPD_10MB_CLK);
val &= ~CPMU_LSPD_10MB_MACCLK_MASK;
val |= CPMU_LSPD_10MB_MACCLK_6_25;
tw32(TG3_CPMU_LSPD_10MB_CLK, val);
val = tr32(TG3_CPMU_LNK_AWARE_PWRMD);
val &= ~CPMU_LNK_AWARE_MACCLK_MASK;
val |= CPMU_LNK_AWARE_MACCLK_6_25;
tw32(TG3_CPMU_LNK_AWARE_PWRMD, val);
val = tr32(TG3_CPMU_HST_ACC);
val &= ~CPMU_HST_ACC_MACCLK_MASK;
val |= CPMU_HST_ACC_MACCLK_6_25;
tw32(TG3_CPMU_HST_ACC, val);
}
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_57780) {
val = tr32(PCIE_PWR_MGMT_THRESH) & ~PCIE_PWR_MGMT_L1_THRESH_MSK;
val |= PCIE_PWR_MGMT_EXT_ASPM_TMR_EN |
PCIE_PWR_MGMT_L1_THRESH_4MS;
tw32(PCIE_PWR_MGMT_THRESH, val);
val = tr32(TG3_PCIE_EIDLE_DELAY) & ~TG3_PCIE_EIDLE_DELAY_MASK;
tw32(TG3_PCIE_EIDLE_DELAY, val | TG3_PCIE_EIDLE_DELAY_13_CLKS);
tw32(TG3_CORR_ERR_STAT, TG3_CORR_ERR_STAT_CLEAR);
val = tr32(TG3_PCIE_LNKCTL) & ~TG3_PCIE_LNKCTL_L1_PLL_PD_EN;
tw32(TG3_PCIE_LNKCTL, val | TG3_PCIE_LNKCTL_L1_PLL_PD_DIS);
}
if (tg3_flag(tp, L1PLLPD_EN)) {
u32 grc_mode = tr32(GRC_MODE);
/* Access the lower 1K of PL PCIE block registers. */
val = grc_mode & ~GRC_MODE_PCIE_PORT_MASK;
tw32(GRC_MODE, val | GRC_MODE_PCIE_PL_SEL);
val = tr32(TG3_PCIE_TLDLPL_PORT + TG3_PCIE_PL_LO_PHYCTL1);
tw32(TG3_PCIE_TLDLPL_PORT + TG3_PCIE_PL_LO_PHYCTL1,
val | TG3_PCIE_PL_LO_PHYCTL1_L1PLLPD_EN);
tw32(GRC_MODE, grc_mode);
}
if (tg3_flag(tp, 57765_CLASS)) {
if (tp->pci_chip_rev_id == CHIPREV_ID_57765_A0) {
u32 grc_mode = tr32(GRC_MODE);
/* Access the lower 1K of PL PCIE block registers. */
val = grc_mode & ~GRC_MODE_PCIE_PORT_MASK;
tw32(GRC_MODE, val | GRC_MODE_PCIE_PL_SEL);
val = tr32(TG3_PCIE_TLDLPL_PORT +
TG3_PCIE_PL_LO_PHYCTL5);
tw32(TG3_PCIE_TLDLPL_PORT + TG3_PCIE_PL_LO_PHYCTL5,
val | TG3_PCIE_PL_LO_PHYCTL5_DIS_L2CLKREQ);
tw32(GRC_MODE, grc_mode);
}
if (GET_CHIP_REV(tp->pci_chip_rev_id) != CHIPREV_57765_AX) {
u32 grc_mode = tr32(GRC_MODE);
/* Access the lower 1K of DL PCIE block registers. */
val = grc_mode & ~GRC_MODE_PCIE_PORT_MASK;
tw32(GRC_MODE, val | GRC_MODE_PCIE_DL_SEL);
val = tr32(TG3_PCIE_TLDLPL_PORT +
TG3_PCIE_DL_LO_FTSMAX);
val &= ~TG3_PCIE_DL_LO_FTSMAX_MSK;
tw32(TG3_PCIE_TLDLPL_PORT + TG3_PCIE_DL_LO_FTSMAX,
val | TG3_PCIE_DL_LO_FTSMAX_VAL);
tw32(GRC_MODE, grc_mode);
}
val = tr32(TG3_CPMU_LSPD_10MB_CLK);
val &= ~CPMU_LSPD_10MB_MACCLK_MASK;
val |= CPMU_LSPD_10MB_MACCLK_6_25;
tw32(TG3_CPMU_LSPD_10MB_CLK, val);
}
/* This works around an issue with Athlon chipsets on
* B3 tigon3 silicon. This bit has no effect on any
* other revision. But do not set this on PCI Express
* chips and don't even touch the clocks if the CPMU is present.
*/
if (!tg3_flag(tp, CPMU_PRESENT)) {
if (!tg3_flag(tp, PCI_EXPRESS))
tp->pci_clock_ctrl |= CLOCK_CTRL_DELAY_PCI_GRANT;
tw32_f(TG3PCI_CLOCK_CTRL, tp->pci_clock_ctrl);
}
if (tp->pci_chip_rev_id == CHIPREV_ID_5704_A0 &&
tg3_flag(tp, PCIX_MODE)) {
val = tr32(TG3PCI_PCISTATE);
val |= PCISTATE_RETRY_SAME_DMA;
tw32(TG3PCI_PCISTATE, val);
}
if (tg3_flag(tp, ENABLE_APE)) {
/* Allow reads and writes to the
* APE register and memory space.
*/
val = tr32(TG3PCI_PCISTATE);
val |= PCISTATE_ALLOW_APE_CTLSPC_WR |
PCISTATE_ALLOW_APE_SHMEM_WR |
PCISTATE_ALLOW_APE_PSPACE_WR;
tw32(TG3PCI_PCISTATE, val);
}
if (GET_CHIP_REV(tp->pci_chip_rev_id) == CHIPREV_5704_BX) {
/* Enable some hw fixes. */
val = tr32(TG3PCI_MSI_DATA);
val |= (1 << 26) | (1 << 28) | (1 << 29);
tw32(TG3PCI_MSI_DATA, val);
}
/* Descriptor ring init may make accesses to the
* NIC SRAM area to setup the TX descriptors, so we
* can only do this after the hardware has been
* successfully reset.
*/
err = tg3_init_rings(tp);
if (err)
return err;
if (tg3_flag(tp, 57765_PLUS)) {
val = tr32(TG3PCI_DMA_RW_CTRL) &
~DMA_RWCTRL_DIS_CACHE_ALIGNMENT;
if (tp->pci_chip_rev_id == CHIPREV_ID_57765_A0)
val &= ~DMA_RWCTRL_CRDRDR_RDMA_MRRS_MSK;
if (!tg3_flag(tp, 57765_CLASS) &&
GET_ASIC_REV(tp->pci_chip_rev_id) != ASIC_REV_5717)
val |= DMA_RWCTRL_TAGGED_STAT_WA;
tw32(TG3PCI_DMA_RW_CTRL, val | tp->dma_rwctrl);
} else if (GET_ASIC_REV(tp->pci_chip_rev_id) != ASIC_REV_5784 &&
GET_ASIC_REV(tp->pci_chip_rev_id) != ASIC_REV_5761) {
/* This value is determined during the probe time DMA
* engine test, tg3_test_dma.
*/
tw32(TG3PCI_DMA_RW_CTRL, tp->dma_rwctrl);
}
tp->grc_mode &= ~(GRC_MODE_HOST_SENDBDS |
GRC_MODE_4X_NIC_SEND_RINGS |
GRC_MODE_NO_TX_PHDR_CSUM |
GRC_MODE_NO_RX_PHDR_CSUM);
tp->grc_mode |= GRC_MODE_HOST_SENDBDS;
/* Pseudo-header checksum is done by hardware logic and not
* the offload processers, so make the chip do the pseudo-
* header checksums on receive. For transmit it is more
* convenient to do the pseudo-header checksum in software
* as Linux does that on transmit for us in all cases.
*/
tp->grc_mode |= GRC_MODE_NO_TX_PHDR_CSUM;
tw32(GRC_MODE,
tp->grc_mode |
(GRC_MODE_IRQ_ON_MAC_ATTN | GRC_MODE_HOST_STACKUP));
/* Setup the timer prescalar register. Clock is always 66Mhz. */
val = tr32(GRC_MISC_CFG);
val &= ~0xff;
val |= (65 << GRC_MISC_CFG_PRESCALAR_SHIFT);
tw32(GRC_MISC_CFG, val);
/* Initialize MBUF/DESC pool. */
if (tg3_flag(tp, 5750_PLUS)) {
/* Do nothing. */
} else if (GET_ASIC_REV(tp->pci_chip_rev_id) != ASIC_REV_5705) {
tw32(BUFMGR_MB_POOL_ADDR, NIC_SRAM_MBUF_POOL_BASE);
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5704)
tw32(BUFMGR_MB_POOL_SIZE, NIC_SRAM_MBUF_POOL_SIZE64);
else
tw32(BUFMGR_MB_POOL_SIZE, NIC_SRAM_MBUF_POOL_SIZE96);
tw32(BUFMGR_DMA_DESC_POOL_ADDR, NIC_SRAM_DMA_DESC_POOL_BASE);
tw32(BUFMGR_DMA_DESC_POOL_SIZE, NIC_SRAM_DMA_DESC_POOL_SIZE);
} else if (tg3_flag(tp, TSO_CAPABLE)) {
int fw_len;
fw_len = tp->fw_len;
fw_len = (fw_len + (0x80 - 1)) & ~(0x80 - 1);
tw32(BUFMGR_MB_POOL_ADDR,
NIC_SRAM_MBUF_POOL_BASE5705 + fw_len);
tw32(BUFMGR_MB_POOL_SIZE,
NIC_SRAM_MBUF_POOL_SIZE5705 - fw_len - 0xa00);
}
if (tp->dev->mtu <= ETH_DATA_LEN) {
tw32(BUFMGR_MB_RDMA_LOW_WATER,
tp->bufmgr_config.mbuf_read_dma_low_water);
tw32(BUFMGR_MB_MACRX_LOW_WATER,
tp->bufmgr_config.mbuf_mac_rx_low_water);
tw32(BUFMGR_MB_HIGH_WATER,
tp->bufmgr_config.mbuf_high_water);
} else {
tw32(BUFMGR_MB_RDMA_LOW_WATER,
tp->bufmgr_config.mbuf_read_dma_low_water_jumbo);
tw32(BUFMGR_MB_MACRX_LOW_WATER,
tp->bufmgr_config.mbuf_mac_rx_low_water_jumbo);
tw32(BUFMGR_MB_HIGH_WATER,
tp->bufmgr_config.mbuf_high_water_jumbo);
}
tw32(BUFMGR_DMA_LOW_WATER,
tp->bufmgr_config.dma_low_water);
tw32(BUFMGR_DMA_HIGH_WATER,
tp->bufmgr_config.dma_high_water);
val = BUFMGR_MODE_ENABLE | BUFMGR_MODE_ATTN_ENABLE;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5719)
val |= BUFMGR_MODE_NO_TX_UNDERRUN;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5717 ||
tp->pci_chip_rev_id == CHIPREV_ID_5719_A0 ||
tp->pci_chip_rev_id == CHIPREV_ID_5720_A0)
val |= BUFMGR_MODE_MBLOW_ATTN_ENAB;
tw32(BUFMGR_MODE, val);
for (i = 0; i < 2000; i++) {
if (tr32(BUFMGR_MODE) & BUFMGR_MODE_ENABLE)
break;
udelay(10);
}
if (i >= 2000) {
netdev_err(tp->dev, "%s cannot enable BUFMGR\n", __func__);
return -ENODEV;
}
if (tp->pci_chip_rev_id == CHIPREV_ID_5906_A1)
tw32(ISO_PKT_TX, (tr32(ISO_PKT_TX) & ~0x3) | 0x2);
tg3_setup_rxbd_thresholds(tp);
/* Initialize TG3_BDINFO's at:
* RCVDBDI_STD_BD: standard eth size rx ring
* RCVDBDI_JUMBO_BD: jumbo frame rx ring
* RCVDBDI_MINI_BD: small frame rx ring (??? does not work)
*
* like so:
* TG3_BDINFO_HOST_ADDR: high/low parts of DMA address of ring
* TG3_BDINFO_MAXLEN_FLAGS: (rx max buffer size << 16) |
* ring attribute flags
* TG3_BDINFO_NIC_ADDR: location of descriptors in nic SRAM
*
* Standard receive ring @ NIC_SRAM_RX_BUFFER_DESC, 512 entries.
* Jumbo receive ring @ NIC_SRAM_RX_JUMBO_BUFFER_DESC, 256 entries.
*
* The size of each ring is fixed in the firmware, but the location is
* configurable.
*/
tw32(RCVDBDI_STD_BD + TG3_BDINFO_HOST_ADDR + TG3_64BIT_REG_HIGH,
((u64) tpr->rx_std_mapping >> 32));
tw32(RCVDBDI_STD_BD + TG3_BDINFO_HOST_ADDR + TG3_64BIT_REG_LOW,
((u64) tpr->rx_std_mapping & 0xffffffff));
if (!tg3_flag(tp, 5717_PLUS))
tw32(RCVDBDI_STD_BD + TG3_BDINFO_NIC_ADDR,
NIC_SRAM_RX_BUFFER_DESC);
/* Disable the mini ring */
if (!tg3_flag(tp, 5705_PLUS))
tw32(RCVDBDI_MINI_BD + TG3_BDINFO_MAXLEN_FLAGS,
BDINFO_FLAGS_DISABLED);
/* Program the jumbo buffer descriptor ring control
* blocks on those devices that have them.
*/
if (tp->pci_chip_rev_id == CHIPREV_ID_5719_A0 ||
(tg3_flag(tp, JUMBO_CAPABLE) && !tg3_flag(tp, 5780_CLASS))) {
if (tg3_flag(tp, JUMBO_RING_ENABLE)) {
tw32(RCVDBDI_JUMBO_BD + TG3_BDINFO_HOST_ADDR + TG3_64BIT_REG_HIGH,
((u64) tpr->rx_jmb_mapping >> 32));
tw32(RCVDBDI_JUMBO_BD + TG3_BDINFO_HOST_ADDR + TG3_64BIT_REG_LOW,
((u64) tpr->rx_jmb_mapping & 0xffffffff));
val = TG3_RX_JMB_RING_SIZE(tp) <<
BDINFO_FLAGS_MAXLEN_SHIFT;
tw32(RCVDBDI_JUMBO_BD + TG3_BDINFO_MAXLEN_FLAGS,
val | BDINFO_FLAGS_USE_EXT_RECV);
if (!tg3_flag(tp, USE_JUMBO_BDFLAG) ||
tg3_flag(tp, 57765_CLASS))
tw32(RCVDBDI_JUMBO_BD + TG3_BDINFO_NIC_ADDR,
NIC_SRAM_RX_JUMBO_BUFFER_DESC);
} else {
tw32(RCVDBDI_JUMBO_BD + TG3_BDINFO_MAXLEN_FLAGS,
BDINFO_FLAGS_DISABLED);
}
if (tg3_flag(tp, 57765_PLUS)) {
val = TG3_RX_STD_RING_SIZE(tp);
val <<= BDINFO_FLAGS_MAXLEN_SHIFT;
val |= (TG3_RX_STD_DMA_SZ << 2);
} else
val = TG3_RX_STD_DMA_SZ << BDINFO_FLAGS_MAXLEN_SHIFT;
} else
val = TG3_RX_STD_MAX_SIZE_5700 << BDINFO_FLAGS_MAXLEN_SHIFT;
tw32(RCVDBDI_STD_BD + TG3_BDINFO_MAXLEN_FLAGS, val);
tpr->rx_std_prod_idx = tp->rx_pending;
tw32_rx_mbox(TG3_RX_STD_PROD_IDX_REG, tpr->rx_std_prod_idx);
tpr->rx_jmb_prod_idx =
tg3_flag(tp, JUMBO_RING_ENABLE) ? tp->rx_jumbo_pending : 0;
tw32_rx_mbox(TG3_RX_JMB_PROD_IDX_REG, tpr->rx_jmb_prod_idx);
tg3_rings_reset(tp);
/* Initialize MAC address and backoff seed. */
__tg3_set_mac_addr(tp, 0);
/* MTU + ethernet header + FCS + optional VLAN tag */
tw32(MAC_RX_MTU_SIZE,
tp->dev->mtu + ETH_HLEN + ETH_FCS_LEN + VLAN_HLEN);
/* The slot time is changed by tg3_setup_phy if we
* run at gigabit with half duplex.
*/
val = (2 << TX_LENGTHS_IPG_CRS_SHIFT) |
(6 << TX_LENGTHS_IPG_SHIFT) |
(32 << TX_LENGTHS_SLOT_TIME_SHIFT);
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5720)
val |= tr32(MAC_TX_LENGTHS) &
(TX_LENGTHS_JMB_FRM_LEN_MSK |
TX_LENGTHS_CNT_DWN_VAL_MSK);
tw32(MAC_TX_LENGTHS, val);
/* Receive rules. */
tw32(MAC_RCV_RULE_CFG, RCV_RULE_CFG_DEFAULT_CLASS);
tw32(RCVLPC_CONFIG, 0x0181);
/* Calculate RDMAC_MODE setting early, we need it to determine
* the RCVLPC_STATE_ENABLE mask.
*/
rdmac_mode = (RDMAC_MODE_ENABLE | RDMAC_MODE_TGTABORT_ENAB |
RDMAC_MODE_MSTABORT_ENAB | RDMAC_MODE_PARITYERR_ENAB |
RDMAC_MODE_ADDROFLOW_ENAB | RDMAC_MODE_FIFOOFLOW_ENAB |
RDMAC_MODE_FIFOURUN_ENAB | RDMAC_MODE_FIFOOREAD_ENAB |
RDMAC_MODE_LNGREAD_ENAB);
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5717)
rdmac_mode |= RDMAC_MODE_MULT_DMA_RD_DIS;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5784 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5785 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_57780)
rdmac_mode |= RDMAC_MODE_BD_SBD_CRPT_ENAB |
RDMAC_MODE_MBUF_RBD_CRPT_ENAB |
RDMAC_MODE_MBUF_SBD_CRPT_ENAB;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5705 &&
tp->pci_chip_rev_id != CHIPREV_ID_5705_A0) {
if (tg3_flag(tp, TSO_CAPABLE) &&
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5705) {
rdmac_mode |= RDMAC_MODE_FIFO_SIZE_128;
} else if (!(tr32(TG3PCI_PCISTATE) & PCISTATE_BUS_SPEED_HIGH) &&
!tg3_flag(tp, IS_5788)) {
rdmac_mode |= RDMAC_MODE_FIFO_LONG_BURST;
}
}
if (tg3_flag(tp, PCI_EXPRESS))
rdmac_mode |= RDMAC_MODE_FIFO_LONG_BURST;
if (tg3_flag(tp, HW_TSO_1) ||
tg3_flag(tp, HW_TSO_2) ||
tg3_flag(tp, HW_TSO_3))
rdmac_mode |= RDMAC_MODE_IPV4_LSO_EN;
if (tg3_flag(tp, 57765_PLUS) ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5785 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_57780)
rdmac_mode |= RDMAC_MODE_IPV6_LSO_EN;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5720)
rdmac_mode |= tr32(RDMAC_MODE) & RDMAC_MODE_H2BNC_VLAN_DET;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5761 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5784 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5785 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_57780 ||
tg3_flag(tp, 57765_PLUS)) {
val = tr32(TG3_RDMA_RSRVCTRL_REG);
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5719 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5720) {
val &= ~(TG3_RDMA_RSRVCTRL_TXMRGN_MASK |
TG3_RDMA_RSRVCTRL_FIFO_LWM_MASK |
TG3_RDMA_RSRVCTRL_FIFO_HWM_MASK);
val |= TG3_RDMA_RSRVCTRL_TXMRGN_320B |
TG3_RDMA_RSRVCTRL_FIFO_LWM_1_5K |
TG3_RDMA_RSRVCTRL_FIFO_HWM_1_5K;
}
tw32(TG3_RDMA_RSRVCTRL_REG,
val | TG3_RDMA_RSRVCTRL_FIFO_OFLW_FIX);
}
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5719 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5720) {
val = tr32(TG3_LSO_RD_DMA_CRPTEN_CTRL);
tw32(TG3_LSO_RD_DMA_CRPTEN_CTRL, val |
TG3_LSO_RD_DMA_CRPTEN_CTRL_BLEN_BD_4K |
TG3_LSO_RD_DMA_CRPTEN_CTRL_BLEN_LSO_4K);
}
/* Receive/send statistics. */
if (tg3_flag(tp, 5750_PLUS)) {
val = tr32(RCVLPC_STATS_ENABLE);
val &= ~RCVLPC_STATSENAB_DACK_FIX;
tw32(RCVLPC_STATS_ENABLE, val);
} else if ((rdmac_mode & RDMAC_MODE_FIFO_SIZE_128) &&
tg3_flag(tp, TSO_CAPABLE)) {
val = tr32(RCVLPC_STATS_ENABLE);
val &= ~RCVLPC_STATSENAB_LNGBRST_RFIX;
tw32(RCVLPC_STATS_ENABLE, val);
} else {
tw32(RCVLPC_STATS_ENABLE, 0xffffff);
}
tw32(RCVLPC_STATSCTRL, RCVLPC_STATSCTRL_ENABLE);
tw32(SNDDATAI_STATSENAB, 0xffffff);
tw32(SNDDATAI_STATSCTRL,
(SNDDATAI_SCTRL_ENABLE |
SNDDATAI_SCTRL_FASTUPD));
/* Setup host coalescing engine. */
tw32(HOSTCC_MODE, 0);
for (i = 0; i < 2000; i++) {
if (!(tr32(HOSTCC_MODE) & HOSTCC_MODE_ENABLE))
break;
udelay(10);
}
__tg3_set_coalesce(tp, &tp->coal);
if (!tg3_flag(tp, 5705_PLUS)) {
/* Status/statistics block address. See tg3_timer,
* the tg3_periodic_fetch_stats call there, and
* tg3_get_stats to see how this works for 5705/5750 chips.
*/
tw32(HOSTCC_STATS_BLK_HOST_ADDR + TG3_64BIT_REG_HIGH,
((u64) tp->stats_mapping >> 32));
tw32(HOSTCC_STATS_BLK_HOST_ADDR + TG3_64BIT_REG_LOW,
((u64) tp->stats_mapping & 0xffffffff));
tw32(HOSTCC_STATS_BLK_NIC_ADDR, NIC_SRAM_STATS_BLK);
tw32(HOSTCC_STATUS_BLK_NIC_ADDR, NIC_SRAM_STATUS_BLK);
/* Clear statistics and status block memory areas */
for (i = NIC_SRAM_STATS_BLK;
i < NIC_SRAM_STATUS_BLK + TG3_HW_STATUS_SIZE;
i += sizeof(u32)) {
tg3_write_mem(tp, i, 0);
udelay(40);
}
}
tw32(HOSTCC_MODE, HOSTCC_MODE_ENABLE | tp->coalesce_mode);
tw32(RCVCC_MODE, RCVCC_MODE_ENABLE | RCVCC_MODE_ATTN_ENABLE);
tw32(RCVLPC_MODE, RCVLPC_MODE_ENABLE);
if (!tg3_flag(tp, 5705_PLUS))
tw32(RCVLSC_MODE, RCVLSC_MODE_ENABLE | RCVLSC_MODE_ATTN_ENABLE);
if (tp->phy_flags & TG3_PHYFLG_MII_SERDES) {
tp->phy_flags &= ~TG3_PHYFLG_PARALLEL_DETECT;
/* reset to prevent losing 1st rx packet intermittently */
tw32_f(MAC_RX_MODE, RX_MODE_RESET);
udelay(10);
}
tp->mac_mode |= MAC_MODE_TXSTAT_ENABLE | MAC_MODE_RXSTAT_ENABLE |
MAC_MODE_TDE_ENABLE | MAC_MODE_RDE_ENABLE |
MAC_MODE_FHDE_ENABLE;
if (tg3_flag(tp, ENABLE_APE))
tp->mac_mode |= MAC_MODE_APE_TX_EN | MAC_MODE_APE_RX_EN;
if (!tg3_flag(tp, 5705_PLUS) &&
!(tp->phy_flags & TG3_PHYFLG_PHY_SERDES) &&
GET_ASIC_REV(tp->pci_chip_rev_id) != ASIC_REV_5700)
tp->mac_mode |= MAC_MODE_LINK_POLARITY;
tw32_f(MAC_MODE, tp->mac_mode | MAC_MODE_RXSTAT_CLEAR | MAC_MODE_TXSTAT_CLEAR);
udelay(40);
/* tp->grc_local_ctrl is partially set up during tg3_get_invariants().
* If TG3_FLAG_IS_NIC is zero, we should read the
* register to preserve the GPIO settings for LOMs. The GPIOs,
* whether used as inputs or outputs, are set by boot code after
* reset.
*/
if (!tg3_flag(tp, IS_NIC)) {
u32 gpio_mask;
gpio_mask = GRC_LCLCTRL_GPIO_OE0 | GRC_LCLCTRL_GPIO_OE1 |
GRC_LCLCTRL_GPIO_OE2 | GRC_LCLCTRL_GPIO_OUTPUT0 |
GRC_LCLCTRL_GPIO_OUTPUT1 | GRC_LCLCTRL_GPIO_OUTPUT2;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5752)
gpio_mask |= GRC_LCLCTRL_GPIO_OE3 |
GRC_LCLCTRL_GPIO_OUTPUT3;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5755)
gpio_mask |= GRC_LCLCTRL_GPIO_UART_SEL;
tp->grc_local_ctrl &= ~gpio_mask;
tp->grc_local_ctrl |= tr32(GRC_LOCAL_CTRL) & gpio_mask;
/* GPIO1 must be driven high for eeprom write protect */
if (tg3_flag(tp, EEPROM_WRITE_PROT))
tp->grc_local_ctrl |= (GRC_LCLCTRL_GPIO_OE1 |
GRC_LCLCTRL_GPIO_OUTPUT1);
}
tw32_f(GRC_LOCAL_CTRL, tp->grc_local_ctrl);
udelay(100);
if (tg3_flag(tp, USING_MSIX)) {
val = tr32(MSGINT_MODE);
val |= MSGINT_MODE_ENABLE;
if (tp->irq_cnt > 1)
val |= MSGINT_MODE_MULTIVEC_EN;
if (!tg3_flag(tp, 1SHOT_MSI))
val |= MSGINT_MODE_ONE_SHOT_DISABLE;
tw32(MSGINT_MODE, val);
}
if (!tg3_flag(tp, 5705_PLUS)) {
tw32_f(DMAC_MODE, DMAC_MODE_ENABLE);
udelay(40);
}
val = (WDMAC_MODE_ENABLE | WDMAC_MODE_TGTABORT_ENAB |
WDMAC_MODE_MSTABORT_ENAB | WDMAC_MODE_PARITYERR_ENAB |
WDMAC_MODE_ADDROFLOW_ENAB | WDMAC_MODE_FIFOOFLOW_ENAB |
WDMAC_MODE_FIFOURUN_ENAB | WDMAC_MODE_FIFOOREAD_ENAB |
WDMAC_MODE_LNGREAD_ENAB);
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5705 &&
tp->pci_chip_rev_id != CHIPREV_ID_5705_A0) {
if (tg3_flag(tp, TSO_CAPABLE) &&
(tp->pci_chip_rev_id == CHIPREV_ID_5705_A1 ||
tp->pci_chip_rev_id == CHIPREV_ID_5705_A2)) {
/* nothing */
} else if (!(tr32(TG3PCI_PCISTATE) & PCISTATE_BUS_SPEED_HIGH) &&
!tg3_flag(tp, IS_5788)) {
val |= WDMAC_MODE_RX_ACCEL;
}
}
/* Enable host coalescing bug fix */
if (tg3_flag(tp, 5755_PLUS))
val |= WDMAC_MODE_STATUS_TAG_FIX;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5785)
val |= WDMAC_MODE_BURST_ALL_DATA;
tw32_f(WDMAC_MODE, val);
udelay(40);
if (tg3_flag(tp, PCIX_MODE)) {
u16 pcix_cmd;
pci_read_config_word(tp->pdev, tp->pcix_cap + PCI_X_CMD,
&pcix_cmd);
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5703) {
pcix_cmd &= ~PCI_X_CMD_MAX_READ;
pcix_cmd |= PCI_X_CMD_READ_2K;
} else if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5704) {
pcix_cmd &= ~(PCI_X_CMD_MAX_SPLIT | PCI_X_CMD_MAX_READ);
pcix_cmd |= PCI_X_CMD_READ_2K;
}
pci_write_config_word(tp->pdev, tp->pcix_cap + PCI_X_CMD,
pcix_cmd);
}
tw32_f(RDMAC_MODE, rdmac_mode);
udelay(40);
tw32(RCVDCC_MODE, RCVDCC_MODE_ENABLE | RCVDCC_MODE_ATTN_ENABLE);
if (!tg3_flag(tp, 5705_PLUS))
tw32(MBFREE_MODE, MBFREE_MODE_ENABLE);
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5761)
tw32(SNDDATAC_MODE,
SNDDATAC_MODE_ENABLE | SNDDATAC_MODE_CDELAY);
else
tw32(SNDDATAC_MODE, SNDDATAC_MODE_ENABLE);
tw32(SNDBDC_MODE, SNDBDC_MODE_ENABLE | SNDBDC_MODE_ATTN_ENABLE);
tw32(RCVBDI_MODE, RCVBDI_MODE_ENABLE | RCVBDI_MODE_RCB_ATTN_ENAB);
val = RCVDBDI_MODE_ENABLE | RCVDBDI_MODE_INV_RING_SZ;
if (tg3_flag(tp, LRG_PROD_RING_CAP))
val |= RCVDBDI_MODE_LRG_RING_SZ;
tw32(RCVDBDI_MODE, val);
tw32(SNDDATAI_MODE, SNDDATAI_MODE_ENABLE);
if (tg3_flag(tp, HW_TSO_1) ||
tg3_flag(tp, HW_TSO_2) ||
tg3_flag(tp, HW_TSO_3))
tw32(SNDDATAI_MODE, SNDDATAI_MODE_ENABLE | 0x8);
val = SNDBDI_MODE_ENABLE | SNDBDI_MODE_ATTN_ENABLE;
if (tg3_flag(tp, ENABLE_TSS))
val |= SNDBDI_MODE_MULTI_TXQ_EN;
tw32(SNDBDI_MODE, val);
tw32(SNDBDS_MODE, SNDBDS_MODE_ENABLE | SNDBDS_MODE_ATTN_ENABLE);
if (tp->pci_chip_rev_id == CHIPREV_ID_5701_A0) {
err = tg3_load_5701_a0_firmware_fix(tp);
if (err)
return err;
}
if (tg3_flag(tp, TSO_CAPABLE)) {
err = tg3_load_tso_firmware(tp);
if (err)
return err;
}
tp->tx_mode = TX_MODE_ENABLE;
if (tg3_flag(tp, 5755_PLUS) ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5906)
tp->tx_mode |= TX_MODE_MBUF_LOCKUP_FIX;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5720) {
val = TX_MODE_JMB_FRM_LEN | TX_MODE_CNT_DN_MODE;
tp->tx_mode &= ~val;
tp->tx_mode |= tr32(MAC_TX_MODE) & val;
}
tw32_f(MAC_TX_MODE, tp->tx_mode);
udelay(100);
if (tg3_flag(tp, ENABLE_RSS)) {
tg3_rss_write_indir_tbl(tp);
/* Setup the "secret" hash key. */
tw32(MAC_RSS_HASH_KEY_0, 0x5f865437);
tw32(MAC_RSS_HASH_KEY_1, 0xe4ac62cc);
tw32(MAC_RSS_HASH_KEY_2, 0x50103a45);
tw32(MAC_RSS_HASH_KEY_3, 0x36621985);
tw32(MAC_RSS_HASH_KEY_4, 0xbf14c0e8);
tw32(MAC_RSS_HASH_KEY_5, 0x1bc27a1e);
tw32(MAC_RSS_HASH_KEY_6, 0x84f4b556);
tw32(MAC_RSS_HASH_KEY_7, 0x094ea6fe);
tw32(MAC_RSS_HASH_KEY_8, 0x7dda01e7);
tw32(MAC_RSS_HASH_KEY_9, 0xc04d7481);
}
tp->rx_mode = RX_MODE_ENABLE;
if (tg3_flag(tp, 5755_PLUS))
tp->rx_mode |= RX_MODE_IPV6_CSUM_ENABLE;
if (tg3_flag(tp, ENABLE_RSS))
tp->rx_mode |= RX_MODE_RSS_ENABLE |
RX_MODE_RSS_ITBL_HASH_BITS_7 |
RX_MODE_RSS_IPV6_HASH_EN |
RX_MODE_RSS_TCP_IPV6_HASH_EN |
RX_MODE_RSS_IPV4_HASH_EN |
RX_MODE_RSS_TCP_IPV4_HASH_EN;
tw32_f(MAC_RX_MODE, tp->rx_mode);
udelay(10);
tw32(MAC_LED_CTRL, tp->led_ctrl);
tw32(MAC_MI_STAT, MAC_MI_STAT_LNKSTAT_ATTN_ENAB);
if (tp->phy_flags & TG3_PHYFLG_PHY_SERDES) {
tw32_f(MAC_RX_MODE, RX_MODE_RESET);
udelay(10);
}
tw32_f(MAC_RX_MODE, tp->rx_mode);
udelay(10);
if (tp->phy_flags & TG3_PHYFLG_PHY_SERDES) {
if ((GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5704) &&
!(tp->phy_flags & TG3_PHYFLG_SERDES_PREEMPHASIS)) {
/* Set drive transmission level to 1.2V */
/* only if the signal pre-emphasis bit is not set */
val = tr32(MAC_SERDES_CFG);
val &= 0xfffff000;
val |= 0x880;
tw32(MAC_SERDES_CFG, val);
}
if (tp->pci_chip_rev_id == CHIPREV_ID_5703_A1)
tw32(MAC_SERDES_CFG, 0x616000);
}
/* Prevent chip from dropping frames when flow control
* is enabled.
*/
if (tg3_flag(tp, 57765_CLASS))
val = 1;
else
val = 2;
tw32_f(MAC_LOW_WMARK_MAX_RX_FRAME, val);
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5704 &&
(tp->phy_flags & TG3_PHYFLG_PHY_SERDES)) {
/* Use hardware link auto-negotiation */
tg3_flag_set(tp, HW_AUTONEG);
}
if ((tp->phy_flags & TG3_PHYFLG_MII_SERDES) &&
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5714) {
u32 tmp;
tmp = tr32(SERDES_RX_CTRL);
tw32(SERDES_RX_CTRL, tmp | SERDES_RX_SIG_DETECT);
tp->grc_local_ctrl &= ~GRC_LCLCTRL_USE_EXT_SIG_DETECT;
tp->grc_local_ctrl |= GRC_LCLCTRL_USE_SIG_DETECT;
tw32(GRC_LOCAL_CTRL, tp->grc_local_ctrl);
}
if (!tg3_flag(tp, USE_PHYLIB)) {
if (tp->phy_flags & TG3_PHYFLG_IS_LOW_POWER)
tp->phy_flags &= ~TG3_PHYFLG_IS_LOW_POWER;
err = tg3_setup_phy(tp, 0);
if (err)
return err;
if (!(tp->phy_flags & TG3_PHYFLG_PHY_SERDES) &&
!(tp->phy_flags & TG3_PHYFLG_IS_FET)) {
u32 tmp;
/* Clear CRC stats. */
if (!tg3_readphy(tp, MII_TG3_TEST1, &tmp)) {
tg3_writephy(tp, MII_TG3_TEST1,
tmp | MII_TG3_TEST1_CRC_EN);
tg3_readphy(tp, MII_TG3_RXR_COUNTERS, &tmp);
}
}
}
__tg3_set_rx_mode(tp->dev);
/* Initialize receive rules. */
tw32(MAC_RCV_RULE_0, 0xc2000000 & RCV_RULE_DISABLE_MASK);
tw32(MAC_RCV_VALUE_0, 0xffffffff & RCV_RULE_DISABLE_MASK);
tw32(MAC_RCV_RULE_1, 0x86000004 & RCV_RULE_DISABLE_MASK);
tw32(MAC_RCV_VALUE_1, 0xffffffff & RCV_RULE_DISABLE_MASK);
if (tg3_flag(tp, 5705_PLUS) && !tg3_flag(tp, 5780_CLASS))
limit = 8;
else
limit = 16;
if (tg3_flag(tp, ENABLE_ASF))
limit -= 4;
switch (limit) {
case 16:
tw32(MAC_RCV_RULE_15, 0); tw32(MAC_RCV_VALUE_15, 0);
case 15:
tw32(MAC_RCV_RULE_14, 0); tw32(MAC_RCV_VALUE_14, 0);
case 14:
tw32(MAC_RCV_RULE_13, 0); tw32(MAC_RCV_VALUE_13, 0);
case 13:
tw32(MAC_RCV_RULE_12, 0); tw32(MAC_RCV_VALUE_12, 0);
case 12:
tw32(MAC_RCV_RULE_11, 0); tw32(MAC_RCV_VALUE_11, 0);
case 11:
tw32(MAC_RCV_RULE_10, 0); tw32(MAC_RCV_VALUE_10, 0);
case 10:
tw32(MAC_RCV_RULE_9, 0); tw32(MAC_RCV_VALUE_9, 0);
case 9:
tw32(MAC_RCV_RULE_8, 0); tw32(MAC_RCV_VALUE_8, 0);
case 8:
tw32(MAC_RCV_RULE_7, 0); tw32(MAC_RCV_VALUE_7, 0);
case 7:
tw32(MAC_RCV_RULE_6, 0); tw32(MAC_RCV_VALUE_6, 0);
case 6:
tw32(MAC_RCV_RULE_5, 0); tw32(MAC_RCV_VALUE_5, 0);
case 5:
tw32(MAC_RCV_RULE_4, 0); tw32(MAC_RCV_VALUE_4, 0);
case 4:
/* tw32(MAC_RCV_RULE_3, 0); tw32(MAC_RCV_VALUE_3, 0); */
case 3:
/* tw32(MAC_RCV_RULE_2, 0); tw32(MAC_RCV_VALUE_2, 0); */
case 2:
case 1:
default:
break;
}
if (tg3_flag(tp, ENABLE_APE))
/* Write our heartbeat update interval to APE. */
tg3_ape_write32(tp, TG3_APE_HOST_HEARTBEAT_INT_MS,
APE_HOST_HEARTBEAT_INT_DISABLE);
tg3_write_sig_post_reset(tp, RESET_KIND_INIT);
return 0;
}
/* Called at device open time to get the chip ready for
* packet processing. Invoked with tp->lock held.
*/
static int tg3_init_hw(struct tg3 *tp, int reset_phy)
{
tg3_switch_clocks(tp);
tw32(TG3PCI_MEM_WIN_BASE_ADDR, 0);
return tg3_reset_hw(tp, reset_phy);
}
#define TG3_STAT_ADD32(PSTAT, REG) \
do { u32 __val = tr32(REG); \
(PSTAT)->low += __val; \
if ((PSTAT)->low < __val) \
(PSTAT)->high += 1; \
} while (0)
static void tg3_periodic_fetch_stats(struct tg3 *tp)
{
struct tg3_hw_stats *sp = tp->hw_stats;
if (!netif_carrier_ok(tp->dev))
return;
TG3_STAT_ADD32(&sp->tx_octets, MAC_TX_STATS_OCTETS);
TG3_STAT_ADD32(&sp->tx_collisions, MAC_TX_STATS_COLLISIONS);
TG3_STAT_ADD32(&sp->tx_xon_sent, MAC_TX_STATS_XON_SENT);
TG3_STAT_ADD32(&sp->tx_xoff_sent, MAC_TX_STATS_XOFF_SENT);
TG3_STAT_ADD32(&sp->tx_mac_errors, MAC_TX_STATS_MAC_ERRORS);
TG3_STAT_ADD32(&sp->tx_single_collisions, MAC_TX_STATS_SINGLE_COLLISIONS);
TG3_STAT_ADD32(&sp->tx_mult_collisions, MAC_TX_STATS_MULT_COLLISIONS);
TG3_STAT_ADD32(&sp->tx_deferred, MAC_TX_STATS_DEFERRED);
TG3_STAT_ADD32(&sp->tx_excessive_collisions, MAC_TX_STATS_EXCESSIVE_COL);
TG3_STAT_ADD32(&sp->tx_late_collisions, MAC_TX_STATS_LATE_COL);
TG3_STAT_ADD32(&sp->tx_ucast_packets, MAC_TX_STATS_UCAST);
TG3_STAT_ADD32(&sp->tx_mcast_packets, MAC_TX_STATS_MCAST);
TG3_STAT_ADD32(&sp->tx_bcast_packets, MAC_TX_STATS_BCAST);
TG3_STAT_ADD32(&sp->rx_octets, MAC_RX_STATS_OCTETS);
TG3_STAT_ADD32(&sp->rx_fragments, MAC_RX_STATS_FRAGMENTS);
TG3_STAT_ADD32(&sp->rx_ucast_packets, MAC_RX_STATS_UCAST);
TG3_STAT_ADD32(&sp->rx_mcast_packets, MAC_RX_STATS_MCAST);
TG3_STAT_ADD32(&sp->rx_bcast_packets, MAC_RX_STATS_BCAST);
TG3_STAT_ADD32(&sp->rx_fcs_errors, MAC_RX_STATS_FCS_ERRORS);
TG3_STAT_ADD32(&sp->rx_align_errors, MAC_RX_STATS_ALIGN_ERRORS);
TG3_STAT_ADD32(&sp->rx_xon_pause_rcvd, MAC_RX_STATS_XON_PAUSE_RECVD);
TG3_STAT_ADD32(&sp->rx_xoff_pause_rcvd, MAC_RX_STATS_XOFF_PAUSE_RECVD);
TG3_STAT_ADD32(&sp->rx_mac_ctrl_rcvd, MAC_RX_STATS_MAC_CTRL_RECVD);
TG3_STAT_ADD32(&sp->rx_xoff_entered, MAC_RX_STATS_XOFF_ENTERED);
TG3_STAT_ADD32(&sp->rx_frame_too_long_errors, MAC_RX_STATS_FRAME_TOO_LONG);
TG3_STAT_ADD32(&sp->rx_jabbers, MAC_RX_STATS_JABBERS);
TG3_STAT_ADD32(&sp->rx_undersize_packets, MAC_RX_STATS_UNDERSIZE);
TG3_STAT_ADD32(&sp->rxbds_empty, RCVLPC_NO_RCV_BD_CNT);
if (GET_ASIC_REV(tp->pci_chip_rev_id) != ASIC_REV_5717 &&
tp->pci_chip_rev_id != CHIPREV_ID_5719_A0 &&
tp->pci_chip_rev_id != CHIPREV_ID_5720_A0) {
TG3_STAT_ADD32(&sp->rx_discards, RCVLPC_IN_DISCARDS_CNT);
} else {
u32 val = tr32(HOSTCC_FLOW_ATTN);
val = (val & HOSTCC_FLOW_ATTN_MBUF_LWM) ? 1 : 0;
if (val) {
tw32(HOSTCC_FLOW_ATTN, HOSTCC_FLOW_ATTN_MBUF_LWM);
sp->rx_discards.low += val;
if (sp->rx_discards.low < val)
sp->rx_discards.high += 1;
}
sp->mbuf_lwm_thresh_hit = sp->rx_discards;
}
TG3_STAT_ADD32(&sp->rx_errors, RCVLPC_IN_ERRORS_CNT);
}
static void tg3_chk_missed_msi(struct tg3 *tp)
{
u32 i;
for (i = 0; i < tp->irq_cnt; i++) {
struct tg3_napi *tnapi = &tp->napi[i];
if (tg3_has_work(tnapi)) {
if (tnapi->last_rx_cons == tnapi->rx_rcb_ptr &&
tnapi->last_tx_cons == tnapi->tx_cons) {
if (tnapi->chk_msi_cnt < 1) {
tnapi->chk_msi_cnt++;
return;
}
tg3_msi(0, tnapi);
}
}
tnapi->chk_msi_cnt = 0;
tnapi->last_rx_cons = tnapi->rx_rcb_ptr;
tnapi->last_tx_cons = tnapi->tx_cons;
}
}
static void tg3_timer(unsigned long __opaque)
{
struct tg3 *tp = (struct tg3 *) __opaque;
if (tp->irq_sync || tg3_flag(tp, RESET_TASK_PENDING))
goto restart_timer;
spin_lock(&tp->lock);
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5717 ||
tg3_flag(tp, 57765_CLASS))
tg3_chk_missed_msi(tp);
if (!tg3_flag(tp, TAGGED_STATUS)) {
/* All of this garbage is because when using non-tagged
* IRQ status the mailbox/status_block protocol the chip
* uses with the cpu is race prone.
*/
if (tp->napi[0].hw_status->status & SD_STATUS_UPDATED) {
tw32(GRC_LOCAL_CTRL,
tp->grc_local_ctrl | GRC_LCLCTRL_SETINT);
} else {
tw32(HOSTCC_MODE, tp->coalesce_mode |
HOSTCC_MODE_ENABLE | HOSTCC_MODE_NOW);
}
if (!(tr32(WDMAC_MODE) & WDMAC_MODE_ENABLE)) {
spin_unlock(&tp->lock);
tg3_reset_task_schedule(tp);
goto restart_timer;
}
}
/* This part only runs once per second. */
if (!--tp->timer_counter) {
if (tg3_flag(tp, 5705_PLUS))
tg3_periodic_fetch_stats(tp);
if (tp->setlpicnt && !--tp->setlpicnt)
tg3_phy_eee_enable(tp);
if (tg3_flag(tp, USE_LINKCHG_REG)) {
u32 mac_stat;
int phy_event;
mac_stat = tr32(MAC_STATUS);
phy_event = 0;
if (tp->phy_flags & TG3_PHYFLG_USE_MI_INTERRUPT) {
if (mac_stat & MAC_STATUS_MI_INTERRUPT)
phy_event = 1;
} else if (mac_stat & MAC_STATUS_LNKSTATE_CHANGED)
phy_event = 1;
if (phy_event)
tg3_setup_phy(tp, 0);
} else if (tg3_flag(tp, POLL_SERDES)) {
u32 mac_stat = tr32(MAC_STATUS);
int need_setup = 0;
if (netif_carrier_ok(tp->dev) &&
(mac_stat & MAC_STATUS_LNKSTATE_CHANGED)) {
need_setup = 1;
}
if (!netif_carrier_ok(tp->dev) &&
(mac_stat & (MAC_STATUS_PCS_SYNCED |
MAC_STATUS_SIGNAL_DET))) {
need_setup = 1;
}
if (need_setup) {
if (!tp->serdes_counter) {
tw32_f(MAC_MODE,
(tp->mac_mode &
~MAC_MODE_PORT_MODE_MASK));
udelay(40);
tw32_f(MAC_MODE, tp->mac_mode);
udelay(40);
}
tg3_setup_phy(tp, 0);
}
} else if ((tp->phy_flags & TG3_PHYFLG_MII_SERDES) &&
tg3_flag(tp, 5780_CLASS)) {
tg3_serdes_parallel_detect(tp);
}
tp->timer_counter = tp->timer_multiplier;
}
/* Heartbeat is only sent once every 2 seconds.
*
* The heartbeat is to tell the ASF firmware that the host
* driver is still alive. In the event that the OS crashes,
* ASF needs to reset the hardware to free up the FIFO space
* that may be filled with rx packets destined for the host.
* If the FIFO is full, ASF will no longer function properly.
*
* Unintended resets have been reported on real time kernels
* where the timer doesn't run on time. Netpoll will also have
* same problem.
*
* The new FWCMD_NICDRV_ALIVE3 command tells the ASF firmware
* to check the ring condition when the heartbeat is expiring
* before doing the reset. This will prevent most unintended
* resets.
*/
if (!--tp->asf_counter) {
if (tg3_flag(tp, ENABLE_ASF) && !tg3_flag(tp, ENABLE_APE)) {
tg3_wait_for_event_ack(tp);
tg3_write_mem(tp, NIC_SRAM_FW_CMD_MBOX,
FWCMD_NICDRV_ALIVE3);
tg3_write_mem(tp, NIC_SRAM_FW_CMD_LEN_MBOX, 4);
tg3_write_mem(tp, NIC_SRAM_FW_CMD_DATA_MBOX,
TG3_FW_UPDATE_TIMEOUT_SEC);
tg3_generate_fw_event(tp);
}
tp->asf_counter = tp->asf_multiplier;
}
spin_unlock(&tp->lock);
restart_timer:
tp->timer.expires = jiffies + tp->timer_offset;
add_timer(&tp->timer);
}
static void __devinit tg3_timer_init(struct tg3 *tp)
{
if (tg3_flag(tp, TAGGED_STATUS) &&
GET_ASIC_REV(tp->pci_chip_rev_id) != ASIC_REV_5717 &&
!tg3_flag(tp, 57765_CLASS))
tp->timer_offset = HZ;
else
tp->timer_offset = HZ / 10;
BUG_ON(tp->timer_offset > HZ);
tp->timer_multiplier = (HZ / tp->timer_offset);
tp->asf_multiplier = (HZ / tp->timer_offset) *
TG3_FW_UPDATE_FREQ_SEC;
init_timer(&tp->timer);
tp->timer.data = (unsigned long) tp;
tp->timer.function = tg3_timer;
}
static void tg3_timer_start(struct tg3 *tp)
{
tp->asf_counter = tp->asf_multiplier;
tp->timer_counter = tp->timer_multiplier;
tp->timer.expires = jiffies + tp->timer_offset;
add_timer(&tp->timer);
}
static void tg3_timer_stop(struct tg3 *tp)
{
del_timer_sync(&tp->timer);
}
/* Restart hardware after configuration changes, self-test, etc.
* Invoked with tp->lock held.
*/
static int tg3_restart_hw(struct tg3 *tp, int reset_phy)
__releases(tp->lock)
__acquires(tp->lock)
{
int err;
err = tg3_init_hw(tp, reset_phy);
if (err) {
netdev_err(tp->dev,
"Failed to re-initialize device, aborting\n");
tg3_halt(tp, RESET_KIND_SHUTDOWN, 1);
tg3_full_unlock(tp);
tg3_timer_stop(tp);
tp->irq_sync = 0;
tg3_napi_enable(tp);
dev_close(tp->dev);
tg3_full_lock(tp, 0);
}
return err;
}
static void tg3_reset_task(struct work_struct *work)
{
struct tg3 *tp = container_of(work, struct tg3, reset_task);
int err;
tg3_full_lock(tp, 0);
if (!netif_running(tp->dev)) {
tg3_flag_clear(tp, RESET_TASK_PENDING);
tg3_full_unlock(tp);
return;
}
tg3_full_unlock(tp);
tg3_phy_stop(tp);
tg3_netif_stop(tp);
tg3_full_lock(tp, 1);
if (tg3_flag(tp, TX_RECOVERY_PENDING)) {
tp->write32_tx_mbox = tg3_write32_tx_mbox;
tp->write32_rx_mbox = tg3_write_flush_reg32;
tg3_flag_set(tp, MBOX_WRITE_REORDER);
tg3_flag_clear(tp, TX_RECOVERY_PENDING);
}
tg3_halt(tp, RESET_KIND_SHUTDOWN, 0);
err = tg3_init_hw(tp, 1);
if (err)
goto out;
tg3_netif_start(tp);
out:
tg3_full_unlock(tp);
if (!err)
tg3_phy_start(tp);
tg3_flag_clear(tp, RESET_TASK_PENDING);
}
static int tg3_request_irq(struct tg3 *tp, int irq_num)
{
irq_handler_t fn;
unsigned long flags;
char *name;
struct tg3_napi *tnapi = &tp->napi[irq_num];
if (tp->irq_cnt == 1)
name = tp->dev->name;
else {
name = &tnapi->irq_lbl[0];
snprintf(name, IFNAMSIZ, "%s-%d", tp->dev->name, irq_num);
name[IFNAMSIZ-1] = 0;
}
if (tg3_flag(tp, USING_MSI) || tg3_flag(tp, USING_MSIX)) {
fn = tg3_msi;
if (tg3_flag(tp, 1SHOT_MSI))
fn = tg3_msi_1shot;
flags = 0;
} else {
fn = tg3_interrupt;
if (tg3_flag(tp, TAGGED_STATUS))
fn = tg3_interrupt_tagged;
flags = IRQF_SHARED;
}
return request_irq(tnapi->irq_vec, fn, flags, name, tnapi);
}
static int tg3_test_interrupt(struct tg3 *tp)
{
struct tg3_napi *tnapi = &tp->napi[0];
struct net_device *dev = tp->dev;
int err, i, intr_ok = 0;
u32 val;
if (!netif_running(dev))
return -ENODEV;
tg3_disable_ints(tp);
free_irq(tnapi->irq_vec, tnapi);
/*
* Turn off MSI one shot mode. Otherwise this test has no
* observable way to know whether the interrupt was delivered.
*/
if (tg3_flag(tp, 57765_PLUS)) {
val = tr32(MSGINT_MODE) | MSGINT_MODE_ONE_SHOT_DISABLE;
tw32(MSGINT_MODE, val);
}
err = request_irq(tnapi->irq_vec, tg3_test_isr,
IRQF_SHARED, dev->name, tnapi);
if (err)
return err;
tnapi->hw_status->status &= ~SD_STATUS_UPDATED;
tg3_enable_ints(tp);
tw32_f(HOSTCC_MODE, tp->coalesce_mode | HOSTCC_MODE_ENABLE |
tnapi->coal_now);
for (i = 0; i < 5; i++) {
u32 int_mbox, misc_host_ctrl;
int_mbox = tr32_mailbox(tnapi->int_mbox);
misc_host_ctrl = tr32(TG3PCI_MISC_HOST_CTRL);
if ((int_mbox != 0) ||
(misc_host_ctrl & MISC_HOST_CTRL_MASK_PCI_INT)) {
intr_ok = 1;
break;
}
if (tg3_flag(tp, 57765_PLUS) &&
tnapi->hw_status->status_tag != tnapi->last_tag)
tw32_mailbox_f(tnapi->int_mbox, tnapi->last_tag << 24);
msleep(10);
}
tg3_disable_ints(tp);
free_irq(tnapi->irq_vec, tnapi);
err = tg3_request_irq(tp, 0);
if (err)
return err;
if (intr_ok) {
/* Reenable MSI one shot mode. */
if (tg3_flag(tp, 57765_PLUS) && tg3_flag(tp, 1SHOT_MSI)) {
val = tr32(MSGINT_MODE) & ~MSGINT_MODE_ONE_SHOT_DISABLE;
tw32(MSGINT_MODE, val);
}
return 0;
}
return -EIO;
}
/* Returns 0 if MSI test succeeds or MSI test fails and INTx mode is
* successfully restored
*/
static int tg3_test_msi(struct tg3 *tp)
{
int err;
u16 pci_cmd;
if (!tg3_flag(tp, USING_MSI))
return 0;
/* Turn off SERR reporting in case MSI terminates with Master
* Abort.
*/
pci_read_config_word(tp->pdev, PCI_COMMAND, &pci_cmd);
pci_write_config_word(tp->pdev, PCI_COMMAND,
pci_cmd & ~PCI_COMMAND_SERR);
err = tg3_test_interrupt(tp);
pci_write_config_word(tp->pdev, PCI_COMMAND, pci_cmd);
if (!err)
return 0;
/* other failures */
if (err != -EIO)
return err;
/* MSI test failed, go back to INTx mode */
netdev_warn(tp->dev, "No interrupt was generated using MSI. Switching "
"to INTx mode. Please report this failure to the PCI "
"maintainer and include system chipset information\n");
free_irq(tp->napi[0].irq_vec, &tp->napi[0]);
pci_disable_msi(tp->pdev);
tg3_flag_clear(tp, USING_MSI);
tp->napi[0].irq_vec = tp->pdev->irq;
err = tg3_request_irq(tp, 0);
if (err)
return err;
/* Need to reset the chip because the MSI cycle may have terminated
* with Master Abort.
*/
tg3_full_lock(tp, 1);
tg3_halt(tp, RESET_KIND_SHUTDOWN, 1);
err = tg3_init_hw(tp, 1);
tg3_full_unlock(tp);
if (err)
free_irq(tp->napi[0].irq_vec, &tp->napi[0]);
return err;
}
static int tg3_request_firmware(struct tg3 *tp)
{
const __be32 *fw_data;
if (request_firmware(&tp->fw, tp->fw_needed, &tp->pdev->dev)) {
netdev_err(tp->dev, "Failed to load firmware \"%s\"\n",
tp->fw_needed);
return -ENOENT;
}
fw_data = (void *)tp->fw->data;
/* Firmware blob starts with version numbers, followed by
* start address and _full_ length including BSS sections
* (which must be longer than the actual data, of course
*/
tp->fw_len = be32_to_cpu(fw_data[2]); /* includes bss */
if (tp->fw_len < (tp->fw->size - 12)) {
netdev_err(tp->dev, "bogus length %d in \"%s\"\n",
tp->fw_len, tp->fw_needed);
release_firmware(tp->fw);
tp->fw = NULL;
return -EINVAL;
}
/* We no longer need firmware; we have it. */
tp->fw_needed = NULL;
return 0;
}
static bool tg3_enable_msix(struct tg3 *tp)
{
int i, rc;
struct msix_entry msix_ent[tp->irq_max];
tp->irq_cnt = num_online_cpus();
if (tp->irq_cnt > 1) {
/* We want as many rx rings enabled as there are cpus.
* In multiqueue MSI-X mode, the first MSI-X vector
* only deals with link interrupts, etc, so we add
* one to the number of vectors we are requesting.
*/
tp->irq_cnt = min_t(unsigned, tp->irq_cnt + 1, tp->irq_max);
}
for (i = 0; i < tp->irq_max; i++) {
msix_ent[i].entry = i;
msix_ent[i].vector = 0;
}
rc = pci_enable_msix(tp->pdev, msix_ent, tp->irq_cnt);
if (rc < 0) {
return false;
} else if (rc != 0) {
if (pci_enable_msix(tp->pdev, msix_ent, rc))
return false;
netdev_notice(tp->dev, "Requested %d MSI-X vectors, received %d\n",
tp->irq_cnt, rc);
tp->irq_cnt = rc;
}
for (i = 0; i < tp->irq_max; i++)
tp->napi[i].irq_vec = msix_ent[i].vector;
netif_set_real_num_tx_queues(tp->dev, 1);
rc = tp->irq_cnt > 1 ? tp->irq_cnt - 1 : 1;
if (netif_set_real_num_rx_queues(tp->dev, rc)) {
pci_disable_msix(tp->pdev);
return false;
}
if (tp->irq_cnt > 1) {
tg3_flag_set(tp, ENABLE_RSS);
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5719 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5720) {
tg3_flag_set(tp, ENABLE_TSS);
netif_set_real_num_tx_queues(tp->dev, tp->irq_cnt - 1);
}
}
return true;
}
static void tg3_ints_init(struct tg3 *tp)
{
if ((tg3_flag(tp, SUPPORT_MSI) || tg3_flag(tp, SUPPORT_MSIX)) &&
!tg3_flag(tp, TAGGED_STATUS)) {
/* All MSI supporting chips should support tagged
* status. Assert that this is the case.
*/
netdev_warn(tp->dev,
"MSI without TAGGED_STATUS? Not using MSI\n");
goto defcfg;
}
if (tg3_flag(tp, SUPPORT_MSIX) && tg3_enable_msix(tp))
tg3_flag_set(tp, USING_MSIX);
else if (tg3_flag(tp, SUPPORT_MSI) && pci_enable_msi(tp->pdev) == 0)
tg3_flag_set(tp, USING_MSI);
if (tg3_flag(tp, USING_MSI) || tg3_flag(tp, USING_MSIX)) {
u32 msi_mode = tr32(MSGINT_MODE);
if (tg3_flag(tp, USING_MSIX) && tp->irq_cnt > 1)
msi_mode |= MSGINT_MODE_MULTIVEC_EN;
if (!tg3_flag(tp, 1SHOT_MSI))
msi_mode |= MSGINT_MODE_ONE_SHOT_DISABLE;
tw32(MSGINT_MODE, msi_mode | MSGINT_MODE_ENABLE);
}
defcfg:
if (!tg3_flag(tp, USING_MSIX)) {
tp->irq_cnt = 1;
tp->napi[0].irq_vec = tp->pdev->irq;
netif_set_real_num_tx_queues(tp->dev, 1);
netif_set_real_num_rx_queues(tp->dev, 1);
}
}
static void tg3_ints_fini(struct tg3 *tp)
{
if (tg3_flag(tp, USING_MSIX))
pci_disable_msix(tp->pdev);
else if (tg3_flag(tp, USING_MSI))
pci_disable_msi(tp->pdev);
tg3_flag_clear(tp, USING_MSI);
tg3_flag_clear(tp, USING_MSIX);
tg3_flag_clear(tp, ENABLE_RSS);
tg3_flag_clear(tp, ENABLE_TSS);
}
static int tg3_open(struct net_device *dev)
{
struct tg3 *tp = netdev_priv(dev);
int i, err;
if (tp->fw_needed) {
err = tg3_request_firmware(tp);
if (tp->pci_chip_rev_id == CHIPREV_ID_5701_A0) {
if (err)
return err;
} else if (err) {
netdev_warn(tp->dev, "TSO capability disabled\n");
tg3_flag_clear(tp, TSO_CAPABLE);
} else if (!tg3_flag(tp, TSO_CAPABLE)) {
netdev_notice(tp->dev, "TSO capability restored\n");
tg3_flag_set(tp, TSO_CAPABLE);
}
}
netif_carrier_off(tp->dev);
err = tg3_power_up(tp);
if (err)
return err;
tg3_full_lock(tp, 0);
tg3_disable_ints(tp);
tg3_flag_clear(tp, INIT_COMPLETE);
tg3_full_unlock(tp);
/*
* Setup interrupts first so we know how
* many NAPI resources to allocate
*/
tg3_ints_init(tp);
tg3_rss_check_indir_tbl(tp);
/* The placement of this call is tied
* to the setup and use of Host TX descriptors.
*/
err = tg3_alloc_consistent(tp);
if (err)
goto err_out1;
tg3_napi_init(tp);
tg3_napi_enable(tp);
for (i = 0; i < tp->irq_cnt; i++) {
struct tg3_napi *tnapi = &tp->napi[i];
err = tg3_request_irq(tp, i);
if (err) {
for (i--; i >= 0; i--) {
tnapi = &tp->napi[i];
free_irq(tnapi->irq_vec, tnapi);
}
goto err_out2;
}
}
tg3_full_lock(tp, 0);
err = tg3_init_hw(tp, 1);
if (err) {
tg3_halt(tp, RESET_KIND_SHUTDOWN, 1);
tg3_free_rings(tp);
}
tg3_full_unlock(tp);
if (err)
goto err_out3;
if (tg3_flag(tp, USING_MSI)) {
err = tg3_test_msi(tp);
if (err) {
tg3_full_lock(tp, 0);
tg3_halt(tp, RESET_KIND_SHUTDOWN, 1);
tg3_free_rings(tp);
tg3_full_unlock(tp);
goto err_out2;
}
if (!tg3_flag(tp, 57765_PLUS) && tg3_flag(tp, USING_MSI)) {
u32 val = tr32(PCIE_TRANSACTION_CFG);
tw32(PCIE_TRANSACTION_CFG,
val | PCIE_TRANS_CFG_1SHOT_MSI);
}
}
tg3_phy_start(tp);
tg3_full_lock(tp, 0);
tg3_timer_start(tp);
tg3_flag_set(tp, INIT_COMPLETE);
tg3_enable_ints(tp);
tg3_full_unlock(tp);
netif_tx_start_all_queues(dev);
/*
* Reset loopback feature if it was turned on while the device was down
* make sure that it's installed properly now.
*/
if (dev->features & NETIF_F_LOOPBACK)
tg3_set_loopback(dev, dev->features);
return 0;
err_out3:
for (i = tp->irq_cnt - 1; i >= 0; i--) {
struct tg3_napi *tnapi = &tp->napi[i];
free_irq(tnapi->irq_vec, tnapi);
}
err_out2:
tg3_napi_disable(tp);
tg3_napi_fini(tp);
tg3_free_consistent(tp);
err_out1:
tg3_ints_fini(tp);
tg3_frob_aux_power(tp, false);
pci_set_power_state(tp->pdev, PCI_D3hot);
return err;
}
static int tg3_close(struct net_device *dev)
{
int i;
struct tg3 *tp = netdev_priv(dev);
tg3_napi_disable(tp);
tg3_reset_task_cancel(tp);
netif_tx_stop_all_queues(dev);
tg3_timer_stop(tp);
tg3_phy_stop(tp);
tg3_full_lock(tp, 1);
tg3_disable_ints(tp);
tg3_halt(tp, RESET_KIND_SHUTDOWN, 1);
tg3_free_rings(tp);
tg3_flag_clear(tp, INIT_COMPLETE);
tg3_full_unlock(tp);
for (i = tp->irq_cnt - 1; i >= 0; i--) {
struct tg3_napi *tnapi = &tp->napi[i];
free_irq(tnapi->irq_vec, tnapi);
}
tg3_ints_fini(tp);
/* Clear stats across close / open calls */
memset(&tp->net_stats_prev, 0, sizeof(tp->net_stats_prev));
memset(&tp->estats_prev, 0, sizeof(tp->estats_prev));
tg3_napi_fini(tp);
tg3_free_consistent(tp);
tg3_power_down(tp);
netif_carrier_off(tp->dev);
return 0;
}
static inline u64 get_stat64(tg3_stat64_t *val)
{
return ((u64)val->high << 32) | ((u64)val->low);
}
static u64 tg3_calc_crc_errors(struct tg3 *tp)
{
struct tg3_hw_stats *hw_stats = tp->hw_stats;
if (!(tp->phy_flags & TG3_PHYFLG_PHY_SERDES) &&
(GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5700 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5701)) {
u32 val;
if (!tg3_readphy(tp, MII_TG3_TEST1, &val)) {
tg3_writephy(tp, MII_TG3_TEST1,
val | MII_TG3_TEST1_CRC_EN);
tg3_readphy(tp, MII_TG3_RXR_COUNTERS, &val);
} else
val = 0;
tp->phy_crc_errors += val;
return tp->phy_crc_errors;
}
return get_stat64(&hw_stats->rx_fcs_errors);
}
#define ESTAT_ADD(member) \
estats->member = old_estats->member + \
get_stat64(&hw_stats->member)
static void tg3_get_estats(struct tg3 *tp, struct tg3_ethtool_stats *estats)
{
struct tg3_ethtool_stats *old_estats = &tp->estats_prev;
struct tg3_hw_stats *hw_stats = tp->hw_stats;
ESTAT_ADD(rx_octets);
ESTAT_ADD(rx_fragments);
ESTAT_ADD(rx_ucast_packets);
ESTAT_ADD(rx_mcast_packets);
ESTAT_ADD(rx_bcast_packets);
ESTAT_ADD(rx_fcs_errors);
ESTAT_ADD(rx_align_errors);
ESTAT_ADD(rx_xon_pause_rcvd);
ESTAT_ADD(rx_xoff_pause_rcvd);
ESTAT_ADD(rx_mac_ctrl_rcvd);
ESTAT_ADD(rx_xoff_entered);
ESTAT_ADD(rx_frame_too_long_errors);
ESTAT_ADD(rx_jabbers);
ESTAT_ADD(rx_undersize_packets);
ESTAT_ADD(rx_in_length_errors);
ESTAT_ADD(rx_out_length_errors);
ESTAT_ADD(rx_64_or_less_octet_packets);
ESTAT_ADD(rx_65_to_127_octet_packets);
ESTAT_ADD(rx_128_to_255_octet_packets);
ESTAT_ADD(rx_256_to_511_octet_packets);
ESTAT_ADD(rx_512_to_1023_octet_packets);
ESTAT_ADD(rx_1024_to_1522_octet_packets);
ESTAT_ADD(rx_1523_to_2047_octet_packets);
ESTAT_ADD(rx_2048_to_4095_octet_packets);
ESTAT_ADD(rx_4096_to_8191_octet_packets);
ESTAT_ADD(rx_8192_to_9022_octet_packets);
ESTAT_ADD(tx_octets);
ESTAT_ADD(tx_collisions);
ESTAT_ADD(tx_xon_sent);
ESTAT_ADD(tx_xoff_sent);
ESTAT_ADD(tx_flow_control);
ESTAT_ADD(tx_mac_errors);
ESTAT_ADD(tx_single_collisions);
ESTAT_ADD(tx_mult_collisions);
ESTAT_ADD(tx_deferred);
ESTAT_ADD(tx_excessive_collisions);
ESTAT_ADD(tx_late_collisions);
ESTAT_ADD(tx_collide_2times);
ESTAT_ADD(tx_collide_3times);
ESTAT_ADD(tx_collide_4times);
ESTAT_ADD(tx_collide_5times);
ESTAT_ADD(tx_collide_6times);
ESTAT_ADD(tx_collide_7times);
ESTAT_ADD(tx_collide_8times);
ESTAT_ADD(tx_collide_9times);
ESTAT_ADD(tx_collide_10times);
ESTAT_ADD(tx_collide_11times);
ESTAT_ADD(tx_collide_12times);
ESTAT_ADD(tx_collide_13times);
ESTAT_ADD(tx_collide_14times);
ESTAT_ADD(tx_collide_15times);
ESTAT_ADD(tx_ucast_packets);
ESTAT_ADD(tx_mcast_packets);
ESTAT_ADD(tx_bcast_packets);
ESTAT_ADD(tx_carrier_sense_errors);
ESTAT_ADD(tx_discards);
ESTAT_ADD(tx_errors);
ESTAT_ADD(dma_writeq_full);
ESTAT_ADD(dma_write_prioq_full);
ESTAT_ADD(rxbds_empty);
ESTAT_ADD(rx_discards);
ESTAT_ADD(rx_errors);
ESTAT_ADD(rx_threshold_hit);
ESTAT_ADD(dma_readq_full);
ESTAT_ADD(dma_read_prioq_full);
ESTAT_ADD(tx_comp_queue_full);
ESTAT_ADD(ring_set_send_prod_index);
ESTAT_ADD(ring_status_update);
ESTAT_ADD(nic_irqs);
ESTAT_ADD(nic_avoided_irqs);
ESTAT_ADD(nic_tx_threshold_hit);
ESTAT_ADD(mbuf_lwm_thresh_hit);
}
static void tg3_get_nstats(struct tg3 *tp, struct rtnl_link_stats64 *stats)
{
struct rtnl_link_stats64 *old_stats = &tp->net_stats_prev;
struct tg3_hw_stats *hw_stats = tp->hw_stats;
stats->rx_packets = old_stats->rx_packets +
get_stat64(&hw_stats->rx_ucast_packets) +
get_stat64(&hw_stats->rx_mcast_packets) +
get_stat64(&hw_stats->rx_bcast_packets);
stats->tx_packets = old_stats->tx_packets +
get_stat64(&hw_stats->tx_ucast_packets) +
get_stat64(&hw_stats->tx_mcast_packets) +
get_stat64(&hw_stats->tx_bcast_packets);
stats->rx_bytes = old_stats->rx_bytes +
get_stat64(&hw_stats->rx_octets);
stats->tx_bytes = old_stats->tx_bytes +
get_stat64(&hw_stats->tx_octets);
stats->rx_errors = old_stats->rx_errors +
get_stat64(&hw_stats->rx_errors);
stats->tx_errors = old_stats->tx_errors +
get_stat64(&hw_stats->tx_errors) +
get_stat64(&hw_stats->tx_mac_errors) +
get_stat64(&hw_stats->tx_carrier_sense_errors) +
get_stat64(&hw_stats->tx_discards);
stats->multicast = old_stats->multicast +
get_stat64(&hw_stats->rx_mcast_packets);
stats->collisions = old_stats->collisions +
get_stat64(&hw_stats->tx_collisions);
stats->rx_length_errors = old_stats->rx_length_errors +
get_stat64(&hw_stats->rx_frame_too_long_errors) +
get_stat64(&hw_stats->rx_undersize_packets);
stats->rx_over_errors = old_stats->rx_over_errors +
get_stat64(&hw_stats->rxbds_empty);
stats->rx_frame_errors = old_stats->rx_frame_errors +
get_stat64(&hw_stats->rx_align_errors);
stats->tx_aborted_errors = old_stats->tx_aborted_errors +
get_stat64(&hw_stats->tx_discards);
stats->tx_carrier_errors = old_stats->tx_carrier_errors +
get_stat64(&hw_stats->tx_carrier_sense_errors);
stats->rx_crc_errors = old_stats->rx_crc_errors +
tg3_calc_crc_errors(tp);
stats->rx_missed_errors = old_stats->rx_missed_errors +
get_stat64(&hw_stats->rx_discards);
stats->rx_dropped = tp->rx_dropped;
stats->tx_dropped = tp->tx_dropped;
}
static int tg3_get_regs_len(struct net_device *dev)
{
return TG3_REG_BLK_SIZE;
}
static void tg3_get_regs(struct net_device *dev,
struct ethtool_regs *regs, void *_p)
{
struct tg3 *tp = netdev_priv(dev);
regs->version = 0;
memset(_p, 0, TG3_REG_BLK_SIZE);
if (tp->phy_flags & TG3_PHYFLG_IS_LOW_POWER)
return;
tg3_full_lock(tp, 0);
tg3_dump_legacy_regs(tp, (u32 *)_p);
tg3_full_unlock(tp);
}
static int tg3_get_eeprom_len(struct net_device *dev)
{
struct tg3 *tp = netdev_priv(dev);
return tp->nvram_size;
}
static int tg3_get_eeprom(struct net_device *dev, struct ethtool_eeprom *eeprom, u8 *data)
{
struct tg3 *tp = netdev_priv(dev);
int ret;
u8 *pd;
u32 i, offset, len, b_offset, b_count;
__be32 val;
if (tg3_flag(tp, NO_NVRAM))
return -EINVAL;
if (tp->phy_flags & TG3_PHYFLG_IS_LOW_POWER)
return -EAGAIN;
offset = eeprom->offset;
len = eeprom->len;
eeprom->len = 0;
eeprom->magic = TG3_EEPROM_MAGIC;
if (offset & 3) {
/* adjustments to start on required 4 byte boundary */
b_offset = offset & 3;
b_count = 4 - b_offset;
if (b_count > len) {
/* i.e. offset=1 len=2 */
b_count = len;
}
ret = tg3_nvram_read_be32(tp, offset-b_offset, &val);
if (ret)
return ret;
memcpy(data, ((char *)&val) + b_offset, b_count);
len -= b_count;
offset += b_count;
eeprom->len += b_count;
}
/* read bytes up to the last 4 byte boundary */
pd = &data[eeprom->len];
for (i = 0; i < (len - (len & 3)); i += 4) {
ret = tg3_nvram_read_be32(tp, offset + i, &val);
if (ret) {
eeprom->len += i;
return ret;
}
memcpy(pd + i, &val, 4);
}
eeprom->len += i;
if (len & 3) {
/* read last bytes not ending on 4 byte boundary */
pd = &data[eeprom->len];
b_count = len & 3;
b_offset = offset + len - b_count;
ret = tg3_nvram_read_be32(tp, b_offset, &val);
if (ret)
return ret;
memcpy(pd, &val, b_count);
eeprom->len += b_count;
}
return 0;
}
static int tg3_set_eeprom(struct net_device *dev, struct ethtool_eeprom *eeprom, u8 *data)
{
struct tg3 *tp = netdev_priv(dev);
int ret;
u32 offset, len, b_offset, odd_len;
u8 *buf;
__be32 start, end;
if (tp->phy_flags & TG3_PHYFLG_IS_LOW_POWER)
return -EAGAIN;
if (tg3_flag(tp, NO_NVRAM) ||
eeprom->magic != TG3_EEPROM_MAGIC)
return -EINVAL;
offset = eeprom->offset;
len = eeprom->len;
if ((b_offset = (offset & 3))) {
/* adjustments to start on required 4 byte boundary */
ret = tg3_nvram_read_be32(tp, offset-b_offset, &start);
if (ret)
return ret;
len += b_offset;
offset &= ~3;
if (len < 4)
len = 4;
}
odd_len = 0;
if (len & 3) {
/* adjustments to end on required 4 byte boundary */
odd_len = 1;
len = (len + 3) & ~3;
ret = tg3_nvram_read_be32(tp, offset+len-4, &end);
if (ret)
return ret;
}
buf = data;
if (b_offset || odd_len) {
buf = kmalloc(len, GFP_KERNEL);
if (!buf)
return -ENOMEM;
if (b_offset)
memcpy(buf, &start, 4);
if (odd_len)
memcpy(buf+len-4, &end, 4);
memcpy(buf + b_offset, data, eeprom->len);
}
ret = tg3_nvram_write_block(tp, offset, len, buf);
if (buf != data)
kfree(buf);
return ret;
}
static int tg3_get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct tg3 *tp = netdev_priv(dev);
if (tg3_flag(tp, USE_PHYLIB)) {
struct phy_device *phydev;
if (!(tp->phy_flags & TG3_PHYFLG_IS_CONNECTED))
return -EAGAIN;
phydev = tp->mdio_bus->phy_map[TG3_PHY_MII_ADDR];
return phy_ethtool_gset(phydev, cmd);
}
cmd->supported = (SUPPORTED_Autoneg);
if (!(tp->phy_flags & TG3_PHYFLG_10_100_ONLY))
cmd->supported |= (SUPPORTED_1000baseT_Half |
SUPPORTED_1000baseT_Full);
if (!(tp->phy_flags & TG3_PHYFLG_ANY_SERDES)) {
cmd->supported |= (SUPPORTED_100baseT_Half |
SUPPORTED_100baseT_Full |
SUPPORTED_10baseT_Half |
SUPPORTED_10baseT_Full |
SUPPORTED_TP);
cmd->port = PORT_TP;
} else {
cmd->supported |= SUPPORTED_FIBRE;
cmd->port = PORT_FIBRE;
}
cmd->advertising = tp->link_config.advertising;
if (tg3_flag(tp, PAUSE_AUTONEG)) {
if (tp->link_config.flowctrl & FLOW_CTRL_RX) {
if (tp->link_config.flowctrl & FLOW_CTRL_TX) {
cmd->advertising |= ADVERTISED_Pause;
} else {
cmd->advertising |= ADVERTISED_Pause |
ADVERTISED_Asym_Pause;
}
} else if (tp->link_config.flowctrl & FLOW_CTRL_TX) {
cmd->advertising |= ADVERTISED_Asym_Pause;
}
}
if (netif_running(dev) && netif_carrier_ok(dev)) {
ethtool_cmd_speed_set(cmd, tp->link_config.active_speed);
cmd->duplex = tp->link_config.active_duplex;
cmd->lp_advertising = tp->link_config.rmt_adv;
if (!(tp->phy_flags & TG3_PHYFLG_ANY_SERDES)) {
if (tp->phy_flags & TG3_PHYFLG_MDIX_STATE)
cmd->eth_tp_mdix = ETH_TP_MDI_X;
else
cmd->eth_tp_mdix = ETH_TP_MDI;
}
} else {
ethtool_cmd_speed_set(cmd, SPEED_UNKNOWN);
cmd->duplex = DUPLEX_UNKNOWN;
cmd->eth_tp_mdix = ETH_TP_MDI_INVALID;
}
cmd->phy_address = tp->phy_addr;
cmd->transceiver = XCVR_INTERNAL;
cmd->autoneg = tp->link_config.autoneg;
cmd->maxtxpkt = 0;
cmd->maxrxpkt = 0;
return 0;
}
static int tg3_set_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct tg3 *tp = netdev_priv(dev);
u32 speed = ethtool_cmd_speed(cmd);
if (tg3_flag(tp, USE_PHYLIB)) {
struct phy_device *phydev;
if (!(tp->phy_flags & TG3_PHYFLG_IS_CONNECTED))
return -EAGAIN;
phydev = tp->mdio_bus->phy_map[TG3_PHY_MII_ADDR];
return phy_ethtool_sset(phydev, cmd);
}
if (cmd->autoneg != AUTONEG_ENABLE &&
cmd->autoneg != AUTONEG_DISABLE)
return -EINVAL;
if (cmd->autoneg == AUTONEG_DISABLE &&
cmd->duplex != DUPLEX_FULL &&
cmd->duplex != DUPLEX_HALF)
return -EINVAL;
if (cmd->autoneg == AUTONEG_ENABLE) {
u32 mask = ADVERTISED_Autoneg |
ADVERTISED_Pause |
ADVERTISED_Asym_Pause;
if (!(tp->phy_flags & TG3_PHYFLG_10_100_ONLY))
mask |= ADVERTISED_1000baseT_Half |
ADVERTISED_1000baseT_Full;
if (!(tp->phy_flags & TG3_PHYFLG_ANY_SERDES))
mask |= ADVERTISED_100baseT_Half |
ADVERTISED_100baseT_Full |
ADVERTISED_10baseT_Half |
ADVERTISED_10baseT_Full |
ADVERTISED_TP;
else
mask |= ADVERTISED_FIBRE;
if (cmd->advertising & ~mask)
return -EINVAL;
mask &= (ADVERTISED_1000baseT_Half |
ADVERTISED_1000baseT_Full |
ADVERTISED_100baseT_Half |
ADVERTISED_100baseT_Full |
ADVERTISED_10baseT_Half |
ADVERTISED_10baseT_Full);
cmd->advertising &= mask;
} else {
if (tp->phy_flags & TG3_PHYFLG_ANY_SERDES) {
if (speed != SPEED_1000)
return -EINVAL;
if (cmd->duplex != DUPLEX_FULL)
return -EINVAL;
} else {
if (speed != SPEED_100 &&
speed != SPEED_10)
return -EINVAL;
}
}
tg3_full_lock(tp, 0);
tp->link_config.autoneg = cmd->autoneg;
if (cmd->autoneg == AUTONEG_ENABLE) {
tp->link_config.advertising = (cmd->advertising |
ADVERTISED_Autoneg);
tp->link_config.speed = SPEED_UNKNOWN;
tp->link_config.duplex = DUPLEX_UNKNOWN;
} else {
tp->link_config.advertising = 0;
tp->link_config.speed = speed;
tp->link_config.duplex = cmd->duplex;
}
if (netif_running(dev))
tg3_setup_phy(tp, 1);
tg3_full_unlock(tp);
return 0;
}
static void tg3_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
{
struct tg3 *tp = netdev_priv(dev);
strlcpy(info->driver, DRV_MODULE_NAME, sizeof(info->driver));
strlcpy(info->version, DRV_MODULE_VERSION, sizeof(info->version));
strlcpy(info->fw_version, tp->fw_ver, sizeof(info->fw_version));
strlcpy(info->bus_info, pci_name(tp->pdev), sizeof(info->bus_info));
}
static void tg3_get_wol(struct net_device *dev, struct ethtool_wolinfo *wol)
{
struct tg3 *tp = netdev_priv(dev);
if (tg3_flag(tp, WOL_CAP) && device_can_wakeup(&tp->pdev->dev))
wol->supported = WAKE_MAGIC;
else
wol->supported = 0;
wol->wolopts = 0;
if (tg3_flag(tp, WOL_ENABLE) && device_can_wakeup(&tp->pdev->dev))
wol->wolopts = WAKE_MAGIC;
memset(&wol->sopass, 0, sizeof(wol->sopass));
}
static int tg3_set_wol(struct net_device *dev, struct ethtool_wolinfo *wol)
{
struct tg3 *tp = netdev_priv(dev);
struct device *dp = &tp->pdev->dev;
if (wol->wolopts & ~WAKE_MAGIC)
return -EINVAL;
if ((wol->wolopts & WAKE_MAGIC) &&
!(tg3_flag(tp, WOL_CAP) && device_can_wakeup(dp)))
return -EINVAL;
device_set_wakeup_enable(dp, wol->wolopts & WAKE_MAGIC);
spin_lock_bh(&tp->lock);
if (device_may_wakeup(dp))
tg3_flag_set(tp, WOL_ENABLE);
else
tg3_flag_clear(tp, WOL_ENABLE);
spin_unlock_bh(&tp->lock);
return 0;
}
static u32 tg3_get_msglevel(struct net_device *dev)
{
struct tg3 *tp = netdev_priv(dev);
return tp->msg_enable;
}
static void tg3_set_msglevel(struct net_device *dev, u32 value)
{
struct tg3 *tp = netdev_priv(dev);
tp->msg_enable = value;
}
static int tg3_nway_reset(struct net_device *dev)
{
struct tg3 *tp = netdev_priv(dev);
int r;
if (!netif_running(dev))
return -EAGAIN;
if (tp->phy_flags & TG3_PHYFLG_PHY_SERDES)
return -EINVAL;
if (tg3_flag(tp, USE_PHYLIB)) {
if (!(tp->phy_flags & TG3_PHYFLG_IS_CONNECTED))
return -EAGAIN;
r = phy_start_aneg(tp->mdio_bus->phy_map[TG3_PHY_MII_ADDR]);
} else {
u32 bmcr;
spin_lock_bh(&tp->lock);
r = -EINVAL;
tg3_readphy(tp, MII_BMCR, &bmcr);
if (!tg3_readphy(tp, MII_BMCR, &bmcr) &&
((bmcr & BMCR_ANENABLE) ||
(tp->phy_flags & TG3_PHYFLG_PARALLEL_DETECT))) {
tg3_writephy(tp, MII_BMCR, bmcr | BMCR_ANRESTART |
BMCR_ANENABLE);
r = 0;
}
spin_unlock_bh(&tp->lock);
}
return r;
}
static void tg3_get_ringparam(struct net_device *dev, struct ethtool_ringparam *ering)
{
struct tg3 *tp = netdev_priv(dev);
ering->rx_max_pending = tp->rx_std_ring_mask;
if (tg3_flag(tp, JUMBO_RING_ENABLE))
ering->rx_jumbo_max_pending = tp->rx_jmb_ring_mask;
else
ering->rx_jumbo_max_pending = 0;
ering->tx_max_pending = TG3_TX_RING_SIZE - 1;
ering->rx_pending = tp->rx_pending;
if (tg3_flag(tp, JUMBO_RING_ENABLE))
ering->rx_jumbo_pending = tp->rx_jumbo_pending;
else
ering->rx_jumbo_pending = 0;
ering->tx_pending = tp->napi[0].tx_pending;
}
static int tg3_set_ringparam(struct net_device *dev, struct ethtool_ringparam *ering)
{
struct tg3 *tp = netdev_priv(dev);
int i, irq_sync = 0, err = 0;
if ((ering->rx_pending > tp->rx_std_ring_mask) ||
(ering->rx_jumbo_pending > tp->rx_jmb_ring_mask) ||
(ering->tx_pending > TG3_TX_RING_SIZE - 1) ||
(ering->tx_pending <= MAX_SKB_FRAGS) ||
(tg3_flag(tp, TSO_BUG) &&
(ering->tx_pending <= (MAX_SKB_FRAGS * 3))))
return -EINVAL;
if (netif_running(dev)) {
tg3_phy_stop(tp);
tg3_netif_stop(tp);
irq_sync = 1;
}
tg3_full_lock(tp, irq_sync);
tp->rx_pending = ering->rx_pending;
if (tg3_flag(tp, MAX_RXPEND_64) &&
tp->rx_pending > 63)
tp->rx_pending = 63;
tp->rx_jumbo_pending = ering->rx_jumbo_pending;
for (i = 0; i < tp->irq_max; i++)
tp->napi[i].tx_pending = ering->tx_pending;
if (netif_running(dev)) {
tg3_halt(tp, RESET_KIND_SHUTDOWN, 1);
err = tg3_restart_hw(tp, 1);
if (!err)
tg3_netif_start(tp);
}
tg3_full_unlock(tp);
if (irq_sync && !err)
tg3_phy_start(tp);
return err;
}
static void tg3_get_pauseparam(struct net_device *dev, struct ethtool_pauseparam *epause)
{
struct tg3 *tp = netdev_priv(dev);
epause->autoneg = !!tg3_flag(tp, PAUSE_AUTONEG);
if (tp->link_config.flowctrl & FLOW_CTRL_RX)
epause->rx_pause = 1;
else
epause->rx_pause = 0;
if (tp->link_config.flowctrl & FLOW_CTRL_TX)
epause->tx_pause = 1;
else
epause->tx_pause = 0;
}
static int tg3_set_pauseparam(struct net_device *dev, struct ethtool_pauseparam *epause)
{
struct tg3 *tp = netdev_priv(dev);
int err = 0;
if (tg3_flag(tp, USE_PHYLIB)) {
u32 newadv;
struct phy_device *phydev;
phydev = tp->mdio_bus->phy_map[TG3_PHY_MII_ADDR];
if (!(phydev->supported & SUPPORTED_Pause) ||
(!(phydev->supported & SUPPORTED_Asym_Pause) &&
(epause->rx_pause != epause->tx_pause)))
return -EINVAL;
tp->link_config.flowctrl = 0;
if (epause->rx_pause) {
tp->link_config.flowctrl |= FLOW_CTRL_RX;
if (epause->tx_pause) {
tp->link_config.flowctrl |= FLOW_CTRL_TX;
newadv = ADVERTISED_Pause;
} else
newadv = ADVERTISED_Pause |
ADVERTISED_Asym_Pause;
} else if (epause->tx_pause) {
tp->link_config.flowctrl |= FLOW_CTRL_TX;
newadv = ADVERTISED_Asym_Pause;
} else
newadv = 0;
if (epause->autoneg)
tg3_flag_set(tp, PAUSE_AUTONEG);
else
tg3_flag_clear(tp, PAUSE_AUTONEG);
if (tp->phy_flags & TG3_PHYFLG_IS_CONNECTED) {
u32 oldadv = phydev->advertising &
(ADVERTISED_Pause | ADVERTISED_Asym_Pause);
if (oldadv != newadv) {
phydev->advertising &=
~(ADVERTISED_Pause |
ADVERTISED_Asym_Pause);
phydev->advertising |= newadv;
if (phydev->autoneg) {
/*
* Always renegotiate the link to
* inform our link partner of our
* flow control settings, even if the
* flow control is forced. Let
* tg3_adjust_link() do the final
* flow control setup.
*/
return phy_start_aneg(phydev);
}
}
if (!epause->autoneg)
tg3_setup_flow_control(tp, 0, 0);
} else {
tp->link_config.advertising &=
~(ADVERTISED_Pause |
ADVERTISED_Asym_Pause);
tp->link_config.advertising |= newadv;
}
} else {
int irq_sync = 0;
if (netif_running(dev)) {
tg3_netif_stop(tp);
irq_sync = 1;
}
tg3_full_lock(tp, irq_sync);
if (epause->autoneg)
tg3_flag_set(tp, PAUSE_AUTONEG);
else
tg3_flag_clear(tp, PAUSE_AUTONEG);
if (epause->rx_pause)
tp->link_config.flowctrl |= FLOW_CTRL_RX;
else
tp->link_config.flowctrl &= ~FLOW_CTRL_RX;
if (epause->tx_pause)
tp->link_config.flowctrl |= FLOW_CTRL_TX;
else
tp->link_config.flowctrl &= ~FLOW_CTRL_TX;
if (netif_running(dev)) {
tg3_halt(tp, RESET_KIND_SHUTDOWN, 1);
err = tg3_restart_hw(tp, 1);
if (!err)
tg3_netif_start(tp);
}
tg3_full_unlock(tp);
}
return err;
}
static int tg3_get_sset_count(struct net_device *dev, int sset)
{
switch (sset) {
case ETH_SS_TEST:
return TG3_NUM_TEST;
case ETH_SS_STATS:
return TG3_NUM_STATS;
default:
return -EOPNOTSUPP;
}
}
static int tg3_get_rxnfc(struct net_device *dev, struct ethtool_rxnfc *info,
u32 *rules __always_unused)
{
struct tg3 *tp = netdev_priv(dev);
if (!tg3_flag(tp, SUPPORT_MSIX))
return -EOPNOTSUPP;
switch (info->cmd) {
case ETHTOOL_GRXRINGS:
if (netif_running(tp->dev))
info->data = tp->irq_cnt;
else {
info->data = num_online_cpus();
if (info->data > TG3_IRQ_MAX_VECS_RSS)
info->data = TG3_IRQ_MAX_VECS_RSS;
}
/* The first interrupt vector only
* handles link interrupts.
*/
info->data -= 1;
return 0;
default:
return -EOPNOTSUPP;
}
}
static u32 tg3_get_rxfh_indir_size(struct net_device *dev)
{
u32 size = 0;
struct tg3 *tp = netdev_priv(dev);
if (tg3_flag(tp, SUPPORT_MSIX))
size = TG3_RSS_INDIR_TBL_SIZE;
return size;
}
static int tg3_get_rxfh_indir(struct net_device *dev, u32 *indir)
{
struct tg3 *tp = netdev_priv(dev);
int i;
for (i = 0; i < TG3_RSS_INDIR_TBL_SIZE; i++)
indir[i] = tp->rss_ind_tbl[i];
return 0;
}
static int tg3_set_rxfh_indir(struct net_device *dev, const u32 *indir)
{
struct tg3 *tp = netdev_priv(dev);
size_t i;
for (i = 0; i < TG3_RSS_INDIR_TBL_SIZE; i++)
tp->rss_ind_tbl[i] = indir[i];
if (!netif_running(dev) || !tg3_flag(tp, ENABLE_RSS))
return 0;
/* It is legal to write the indirection
* table while the device is running.
*/
tg3_full_lock(tp, 0);
tg3_rss_write_indir_tbl(tp);
tg3_full_unlock(tp);
return 0;
}
static void tg3_get_strings(struct net_device *dev, u32 stringset, u8 *buf)
{
switch (stringset) {
case ETH_SS_STATS:
memcpy(buf, ðtool_stats_keys, sizeof(ethtool_stats_keys));
break;
case ETH_SS_TEST:
memcpy(buf, ðtool_test_keys, sizeof(ethtool_test_keys));
break;
default:
WARN_ON(1); /* we need a WARN() */
break;
}
}
static int tg3_set_phys_id(struct net_device *dev,
enum ethtool_phys_id_state state)
{
struct tg3 *tp = netdev_priv(dev);
if (!netif_running(tp->dev))
return -EAGAIN;
switch (state) {
case ETHTOOL_ID_ACTIVE:
return 1; /* cycle on/off once per second */
case ETHTOOL_ID_ON:
tw32(MAC_LED_CTRL, LED_CTRL_LNKLED_OVERRIDE |
LED_CTRL_1000MBPS_ON |
LED_CTRL_100MBPS_ON |
LED_CTRL_10MBPS_ON |
LED_CTRL_TRAFFIC_OVERRIDE |
LED_CTRL_TRAFFIC_BLINK |
LED_CTRL_TRAFFIC_LED);
break;
case ETHTOOL_ID_OFF:
tw32(MAC_LED_CTRL, LED_CTRL_LNKLED_OVERRIDE |
LED_CTRL_TRAFFIC_OVERRIDE);
break;
case ETHTOOL_ID_INACTIVE:
tw32(MAC_LED_CTRL, tp->led_ctrl);
break;
}
return 0;
}
static void tg3_get_ethtool_stats(struct net_device *dev,
struct ethtool_stats *estats, u64 *tmp_stats)
{
struct tg3 *tp = netdev_priv(dev);
if (tp->hw_stats)
tg3_get_estats(tp, (struct tg3_ethtool_stats *)tmp_stats);
else
memset(tmp_stats, 0, sizeof(struct tg3_ethtool_stats));
}
static __be32 *tg3_vpd_readblock(struct tg3 *tp, u32 *vpdlen)
{
int i;
__be32 *buf;
u32 offset = 0, len = 0;
u32 magic, val;
if (tg3_flag(tp, NO_NVRAM) || tg3_nvram_read(tp, 0, &magic))
return NULL;
if (magic == TG3_EEPROM_MAGIC) {
for (offset = TG3_NVM_DIR_START;
offset < TG3_NVM_DIR_END;
offset += TG3_NVM_DIRENT_SIZE) {
if (tg3_nvram_read(tp, offset, &val))
return NULL;
if ((val >> TG3_NVM_DIRTYPE_SHIFT) ==
TG3_NVM_DIRTYPE_EXTVPD)
break;
}
if (offset != TG3_NVM_DIR_END) {
len = (val & TG3_NVM_DIRTYPE_LENMSK) * 4;
if (tg3_nvram_read(tp, offset + 4, &offset))
return NULL;
offset = tg3_nvram_logical_addr(tp, offset);
}
}
if (!offset || !len) {
offset = TG3_NVM_VPD_OFF;
len = TG3_NVM_VPD_LEN;
}
buf = kmalloc(len, GFP_KERNEL);
if (buf == NULL)
return NULL;
if (magic == TG3_EEPROM_MAGIC) {
for (i = 0; i < len; i += 4) {
/* The data is in little-endian format in NVRAM.
* Use the big-endian read routines to preserve
* the byte order as it exists in NVRAM.
*/
if (tg3_nvram_read_be32(tp, offset + i, &buf[i/4]))
goto error;
}
} else {
u8 *ptr;
ssize_t cnt;
unsigned int pos = 0;
ptr = (u8 *)&buf[0];
for (i = 0; pos < len && i < 3; i++, pos += cnt, ptr += cnt) {
cnt = pci_read_vpd(tp->pdev, pos,
len - pos, ptr);
if (cnt == -ETIMEDOUT || cnt == -EINTR)
cnt = 0;
else if (cnt < 0)
goto error;
}
if (pos != len)
goto error;
}
*vpdlen = len;
return buf;
error:
kfree(buf);
return NULL;
}
#define NVRAM_TEST_SIZE 0x100
#define NVRAM_SELFBOOT_FORMAT1_0_SIZE 0x14
#define NVRAM_SELFBOOT_FORMAT1_2_SIZE 0x18
#define NVRAM_SELFBOOT_FORMAT1_3_SIZE 0x1c
#define NVRAM_SELFBOOT_FORMAT1_4_SIZE 0x20
#define NVRAM_SELFBOOT_FORMAT1_5_SIZE 0x24
#define NVRAM_SELFBOOT_FORMAT1_6_SIZE 0x50
#define NVRAM_SELFBOOT_HW_SIZE 0x20
#define NVRAM_SELFBOOT_DATA_SIZE 0x1c
static int tg3_test_nvram(struct tg3 *tp)
{
u32 csum, magic, len;
__be32 *buf;
int i, j, k, err = 0, size;
if (tg3_flag(tp, NO_NVRAM))
return 0;
if (tg3_nvram_read(tp, 0, &magic) != 0)
return -EIO;
if (magic == TG3_EEPROM_MAGIC)
size = NVRAM_TEST_SIZE;
else if ((magic & TG3_EEPROM_MAGIC_FW_MSK) == TG3_EEPROM_MAGIC_FW) {
if ((magic & TG3_EEPROM_SB_FORMAT_MASK) ==
TG3_EEPROM_SB_FORMAT_1) {
switch (magic & TG3_EEPROM_SB_REVISION_MASK) {
case TG3_EEPROM_SB_REVISION_0:
size = NVRAM_SELFBOOT_FORMAT1_0_SIZE;
break;
case TG3_EEPROM_SB_REVISION_2:
size = NVRAM_SELFBOOT_FORMAT1_2_SIZE;
break;
case TG3_EEPROM_SB_REVISION_3:
size = NVRAM_SELFBOOT_FORMAT1_3_SIZE;
break;
case TG3_EEPROM_SB_REVISION_4:
size = NVRAM_SELFBOOT_FORMAT1_4_SIZE;
break;
case TG3_EEPROM_SB_REVISION_5:
size = NVRAM_SELFBOOT_FORMAT1_5_SIZE;
break;
case TG3_EEPROM_SB_REVISION_6:
size = NVRAM_SELFBOOT_FORMAT1_6_SIZE;
break;
default:
return -EIO;
}
} else
return 0;
} else if ((magic & TG3_EEPROM_MAGIC_HW_MSK) == TG3_EEPROM_MAGIC_HW)
size = NVRAM_SELFBOOT_HW_SIZE;
else
return -EIO;
buf = kmalloc(size, GFP_KERNEL);
if (buf == NULL)
return -ENOMEM;
err = -EIO;
for (i = 0, j = 0; i < size; i += 4, j++) {
err = tg3_nvram_read_be32(tp, i, &buf[j]);
if (err)
break;
}
if (i < size)
goto out;
/* Selfboot format */
magic = be32_to_cpu(buf[0]);
if ((magic & TG3_EEPROM_MAGIC_FW_MSK) ==
TG3_EEPROM_MAGIC_FW) {
u8 *buf8 = (u8 *) buf, csum8 = 0;
if ((magic & TG3_EEPROM_SB_REVISION_MASK) ==
TG3_EEPROM_SB_REVISION_2) {
/* For rev 2, the csum doesn't include the MBA. */
for (i = 0; i < TG3_EEPROM_SB_F1R2_MBA_OFF; i++)
csum8 += buf8[i];
for (i = TG3_EEPROM_SB_F1R2_MBA_OFF + 4; i < size; i++)
csum8 += buf8[i];
} else {
for (i = 0; i < size; i++)
csum8 += buf8[i];
}
if (csum8 == 0) {
err = 0;
goto out;
}
err = -EIO;
goto out;
}
if ((magic & TG3_EEPROM_MAGIC_HW_MSK) ==
TG3_EEPROM_MAGIC_HW) {
u8 data[NVRAM_SELFBOOT_DATA_SIZE];
u8 parity[NVRAM_SELFBOOT_DATA_SIZE];
u8 *buf8 = (u8 *) buf;
/* Separate the parity bits and the data bytes. */
for (i = 0, j = 0, k = 0; i < NVRAM_SELFBOOT_HW_SIZE; i++) {
if ((i == 0) || (i == 8)) {
int l;
u8 msk;
for (l = 0, msk = 0x80; l < 7; l++, msk >>= 1)
parity[k++] = buf8[i] & msk;
i++;
} else if (i == 16) {
int l;
u8 msk;
for (l = 0, msk = 0x20; l < 6; l++, msk >>= 1)
parity[k++] = buf8[i] & msk;
i++;
for (l = 0, msk = 0x80; l < 8; l++, msk >>= 1)
parity[k++] = buf8[i] & msk;
i++;
}
data[j++] = buf8[i];
}
err = -EIO;
for (i = 0; i < NVRAM_SELFBOOT_DATA_SIZE; i++) {
u8 hw8 = hweight8(data[i]);
if ((hw8 & 0x1) && parity[i])
goto out;
else if (!(hw8 & 0x1) && !parity[i])
goto out;
}
err = 0;
goto out;
}
err = -EIO;
/* Bootstrap checksum at offset 0x10 */
csum = calc_crc((unsigned char *) buf, 0x10);
if (csum != le32_to_cpu(buf[0x10/4]))
goto out;
/* Manufacturing block starts at offset 0x74, checksum at 0xfc */
csum = calc_crc((unsigned char *) &buf[0x74/4], 0x88);
if (csum != le32_to_cpu(buf[0xfc/4]))
goto out;
kfree(buf);
buf = tg3_vpd_readblock(tp, &len);
if (!buf)
return -ENOMEM;
i = pci_vpd_find_tag((u8 *)buf, 0, len, PCI_VPD_LRDT_RO_DATA);
if (i > 0) {
j = pci_vpd_lrdt_size(&((u8 *)buf)[i]);
if (j < 0)
goto out;
if (i + PCI_VPD_LRDT_TAG_SIZE + j > len)
goto out;
i += PCI_VPD_LRDT_TAG_SIZE;
j = pci_vpd_find_info_keyword((u8 *)buf, i, j,
PCI_VPD_RO_KEYWORD_CHKSUM);
if (j > 0) {
u8 csum8 = 0;
j += PCI_VPD_INFO_FLD_HDR_SIZE;
for (i = 0; i <= j; i++)
csum8 += ((u8 *)buf)[i];
if (csum8)
goto out;
}
}
err = 0;
out:
kfree(buf);
return err;
}
#define TG3_SERDES_TIMEOUT_SEC 2
#define TG3_COPPER_TIMEOUT_SEC 6
static int tg3_test_link(struct tg3 *tp)
{
int i, max;
if (!netif_running(tp->dev))
return -ENODEV;
if (tp->phy_flags & TG3_PHYFLG_ANY_SERDES)
max = TG3_SERDES_TIMEOUT_SEC;
else
max = TG3_COPPER_TIMEOUT_SEC;
for (i = 0; i < max; i++) {
if (netif_carrier_ok(tp->dev))
return 0;
if (msleep_interruptible(1000))
break;
}
return -EIO;
}
/* Only test the commonly used registers */
static int tg3_test_registers(struct tg3 *tp)
{
int i, is_5705, is_5750;
u32 offset, read_mask, write_mask, val, save_val, read_val;
static struct {
u16 offset;
u16 flags;
#define TG3_FL_5705 0x1
#define TG3_FL_NOT_5705 0x2
#define TG3_FL_NOT_5788 0x4
#define TG3_FL_NOT_5750 0x8
u32 read_mask;
u32 write_mask;
} reg_tbl[] = {
/* MAC Control Registers */
{ MAC_MODE, TG3_FL_NOT_5705,
0x00000000, 0x00ef6f8c },
{ MAC_MODE, TG3_FL_5705,
0x00000000, 0x01ef6b8c },
{ MAC_STATUS, TG3_FL_NOT_5705,
0x03800107, 0x00000000 },
{ MAC_STATUS, TG3_FL_5705,
0x03800100, 0x00000000 },
{ MAC_ADDR_0_HIGH, 0x0000,
0x00000000, 0x0000ffff },
{ MAC_ADDR_0_LOW, 0x0000,
0x00000000, 0xffffffff },
{ MAC_RX_MTU_SIZE, 0x0000,
0x00000000, 0x0000ffff },
{ MAC_TX_MODE, 0x0000,
0x00000000, 0x00000070 },
{ MAC_TX_LENGTHS, 0x0000,
0x00000000, 0x00003fff },
{ MAC_RX_MODE, TG3_FL_NOT_5705,
0x00000000, 0x000007fc },
{ MAC_RX_MODE, TG3_FL_5705,
0x00000000, 0x000007dc },
{ MAC_HASH_REG_0, 0x0000,
0x00000000, 0xffffffff },
{ MAC_HASH_REG_1, 0x0000,
0x00000000, 0xffffffff },
{ MAC_HASH_REG_2, 0x0000,
0x00000000, 0xffffffff },
{ MAC_HASH_REG_3, 0x0000,
0x00000000, 0xffffffff },
/* Receive Data and Receive BD Initiator Control Registers. */
{ RCVDBDI_JUMBO_BD+0, TG3_FL_NOT_5705,
0x00000000, 0xffffffff },
{ RCVDBDI_JUMBO_BD+4, TG3_FL_NOT_5705,
0x00000000, 0xffffffff },
{ RCVDBDI_JUMBO_BD+8, TG3_FL_NOT_5705,
0x00000000, 0x00000003 },
{ RCVDBDI_JUMBO_BD+0xc, TG3_FL_NOT_5705,
0x00000000, 0xffffffff },
{ RCVDBDI_STD_BD+0, 0x0000,
0x00000000, 0xffffffff },
{ RCVDBDI_STD_BD+4, 0x0000,
0x00000000, 0xffffffff },
{ RCVDBDI_STD_BD+8, 0x0000,
0x00000000, 0xffff0002 },
{ RCVDBDI_STD_BD+0xc, 0x0000,
0x00000000, 0xffffffff },
/* Receive BD Initiator Control Registers. */
{ RCVBDI_STD_THRESH, TG3_FL_NOT_5705,
0x00000000, 0xffffffff },
{ RCVBDI_STD_THRESH, TG3_FL_5705,
0x00000000, 0x000003ff },
{ RCVBDI_JUMBO_THRESH, TG3_FL_NOT_5705,
0x00000000, 0xffffffff },
/* Host Coalescing Control Registers. */
{ HOSTCC_MODE, TG3_FL_NOT_5705,
0x00000000, 0x00000004 },
{ HOSTCC_MODE, TG3_FL_5705,
0x00000000, 0x000000f6 },
{ HOSTCC_RXCOL_TICKS, TG3_FL_NOT_5705,
0x00000000, 0xffffffff },
{ HOSTCC_RXCOL_TICKS, TG3_FL_5705,
0x00000000, 0x000003ff },
{ HOSTCC_TXCOL_TICKS, TG3_FL_NOT_5705,
0x00000000, 0xffffffff },
{ HOSTCC_TXCOL_TICKS, TG3_FL_5705,
0x00000000, 0x000003ff },
{ HOSTCC_RXMAX_FRAMES, TG3_FL_NOT_5705,
0x00000000, 0xffffffff },
{ HOSTCC_RXMAX_FRAMES, TG3_FL_5705 | TG3_FL_NOT_5788,
0x00000000, 0x000000ff },
{ HOSTCC_TXMAX_FRAMES, TG3_FL_NOT_5705,
0x00000000, 0xffffffff },
{ HOSTCC_TXMAX_FRAMES, TG3_FL_5705 | TG3_FL_NOT_5788,
0x00000000, 0x000000ff },
{ HOSTCC_RXCOAL_TICK_INT, TG3_FL_NOT_5705,
0x00000000, 0xffffffff },
{ HOSTCC_TXCOAL_TICK_INT, TG3_FL_NOT_5705,
0x00000000, 0xffffffff },
{ HOSTCC_RXCOAL_MAXF_INT, TG3_FL_NOT_5705,
0x00000000, 0xffffffff },
{ HOSTCC_RXCOAL_MAXF_INT, TG3_FL_5705 | TG3_FL_NOT_5788,
0x00000000, 0x000000ff },
{ HOSTCC_TXCOAL_MAXF_INT, TG3_FL_NOT_5705,
0x00000000, 0xffffffff },
{ HOSTCC_TXCOAL_MAXF_INT, TG3_FL_5705 | TG3_FL_NOT_5788,
0x00000000, 0x000000ff },
{ HOSTCC_STAT_COAL_TICKS, TG3_FL_NOT_5705,
0x00000000, 0xffffffff },
{ HOSTCC_STATS_BLK_HOST_ADDR, TG3_FL_NOT_5705,
0x00000000, 0xffffffff },
{ HOSTCC_STATS_BLK_HOST_ADDR+4, TG3_FL_NOT_5705,
0x00000000, 0xffffffff },
{ HOSTCC_STATUS_BLK_HOST_ADDR, 0x0000,
0x00000000, 0xffffffff },
{ HOSTCC_STATUS_BLK_HOST_ADDR+4, 0x0000,
0x00000000, 0xffffffff },
{ HOSTCC_STATS_BLK_NIC_ADDR, 0x0000,
0xffffffff, 0x00000000 },
{ HOSTCC_STATUS_BLK_NIC_ADDR, 0x0000,
0xffffffff, 0x00000000 },
/* Buffer Manager Control Registers. */
{ BUFMGR_MB_POOL_ADDR, TG3_FL_NOT_5750,
0x00000000, 0x007fff80 },
{ BUFMGR_MB_POOL_SIZE, TG3_FL_NOT_5750,
0x00000000, 0x007fffff },
{ BUFMGR_MB_RDMA_LOW_WATER, 0x0000,
0x00000000, 0x0000003f },
{ BUFMGR_MB_MACRX_LOW_WATER, 0x0000,
0x00000000, 0x000001ff },
{ BUFMGR_MB_HIGH_WATER, 0x0000,
0x00000000, 0x000001ff },
{ BUFMGR_DMA_DESC_POOL_ADDR, TG3_FL_NOT_5705,
0xffffffff, 0x00000000 },
{ BUFMGR_DMA_DESC_POOL_SIZE, TG3_FL_NOT_5705,
0xffffffff, 0x00000000 },
/* Mailbox Registers */
{ GRCMBOX_RCVSTD_PROD_IDX+4, 0x0000,
0x00000000, 0x000001ff },
{ GRCMBOX_RCVJUMBO_PROD_IDX+4, TG3_FL_NOT_5705,
0x00000000, 0x000001ff },
{ GRCMBOX_RCVRET_CON_IDX_0+4, 0x0000,
0x00000000, 0x000007ff },
{ GRCMBOX_SNDHOST_PROD_IDX_0+4, 0x0000,
0x00000000, 0x000001ff },
{ 0xffff, 0x0000, 0x00000000, 0x00000000 },
};
is_5705 = is_5750 = 0;
if (tg3_flag(tp, 5705_PLUS)) {
is_5705 = 1;
if (tg3_flag(tp, 5750_PLUS))
is_5750 = 1;
}
for (i = 0; reg_tbl[i].offset != 0xffff; i++) {
if (is_5705 && (reg_tbl[i].flags & TG3_FL_NOT_5705))
continue;
if (!is_5705 && (reg_tbl[i].flags & TG3_FL_5705))
continue;
if (tg3_flag(tp, IS_5788) &&
(reg_tbl[i].flags & TG3_FL_NOT_5788))
continue;
if (is_5750 && (reg_tbl[i].flags & TG3_FL_NOT_5750))
continue;
offset = (u32) reg_tbl[i].offset;
read_mask = reg_tbl[i].read_mask;
write_mask = reg_tbl[i].write_mask;
/* Save the original register content */
save_val = tr32(offset);
/* Determine the read-only value. */
read_val = save_val & read_mask;
/* Write zero to the register, then make sure the read-only bits
* are not changed and the read/write bits are all zeros.
*/
tw32(offset, 0);
val = tr32(offset);
/* Test the read-only and read/write bits. */
if (((val & read_mask) != read_val) || (val & write_mask))
goto out;
/* Write ones to all the bits defined by RdMask and WrMask, then
* make sure the read-only bits are not changed and the
* read/write bits are all ones.
*/
tw32(offset, read_mask | write_mask);
val = tr32(offset);
/* Test the read-only bits. */
if ((val & read_mask) != read_val)
goto out;
/* Test the read/write bits. */
if ((val & write_mask) != write_mask)
goto out;
tw32(offset, save_val);
}
return 0;
out:
if (netif_msg_hw(tp))
netdev_err(tp->dev,
"Register test failed at offset %x\n", offset);
tw32(offset, save_val);
return -EIO;
}
static int tg3_do_mem_test(struct tg3 *tp, u32 offset, u32 len)
{
static const u32 test_pattern[] = { 0x00000000, 0xffffffff, 0xaa55a55a };
int i;
u32 j;
for (i = 0; i < ARRAY_SIZE(test_pattern); i++) {
for (j = 0; j < len; j += 4) {
u32 val;
tg3_write_mem(tp, offset + j, test_pattern[i]);
tg3_read_mem(tp, offset + j, &val);
if (val != test_pattern[i])
return -EIO;
}
}
return 0;
}
static int tg3_test_memory(struct tg3 *tp)
{
static struct mem_entry {
u32 offset;
u32 len;
} mem_tbl_570x[] = {
{ 0x00000000, 0x00b50},
{ 0x00002000, 0x1c000},
{ 0xffffffff, 0x00000}
}, mem_tbl_5705[] = {
{ 0x00000100, 0x0000c},
{ 0x00000200, 0x00008},
{ 0x00004000, 0x00800},
{ 0x00006000, 0x01000},
{ 0x00008000, 0x02000},
{ 0x00010000, 0x0e000},
{ 0xffffffff, 0x00000}
}, mem_tbl_5755[] = {
{ 0x00000200, 0x00008},
{ 0x00004000, 0x00800},
{ 0x00006000, 0x00800},
{ 0x00008000, 0x02000},
{ 0x00010000, 0x0c000},
{ 0xffffffff, 0x00000}
}, mem_tbl_5906[] = {
{ 0x00000200, 0x00008},
{ 0x00004000, 0x00400},
{ 0x00006000, 0x00400},
{ 0x00008000, 0x01000},
{ 0x00010000, 0x01000},
{ 0xffffffff, 0x00000}
}, mem_tbl_5717[] = {
{ 0x00000200, 0x00008},
{ 0x00010000, 0x0a000},
{ 0x00020000, 0x13c00},
{ 0xffffffff, 0x00000}
}, mem_tbl_57765[] = {
{ 0x00000200, 0x00008},
{ 0x00004000, 0x00800},
{ 0x00006000, 0x09800},
{ 0x00010000, 0x0a000},
{ 0xffffffff, 0x00000}
};
struct mem_entry *mem_tbl;
int err = 0;
int i;
if (tg3_flag(tp, 5717_PLUS))
mem_tbl = mem_tbl_5717;
else if (tg3_flag(tp, 57765_CLASS))
mem_tbl = mem_tbl_57765;
else if (tg3_flag(tp, 5755_PLUS))
mem_tbl = mem_tbl_5755;
else if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5906)
mem_tbl = mem_tbl_5906;
else if (tg3_flag(tp, 5705_PLUS))
mem_tbl = mem_tbl_5705;
else
mem_tbl = mem_tbl_570x;
for (i = 0; mem_tbl[i].offset != 0xffffffff; i++) {
err = tg3_do_mem_test(tp, mem_tbl[i].offset, mem_tbl[i].len);
if (err)
break;
}
return err;
}
#define TG3_TSO_MSS 500
#define TG3_TSO_IP_HDR_LEN 20
#define TG3_TSO_TCP_HDR_LEN 20
#define TG3_TSO_TCP_OPT_LEN 12
static const u8 tg3_tso_header[] = {
0x08, 0x00,
0x45, 0x00, 0x00, 0x00,
0x00, 0x00, 0x40, 0x00,
0x40, 0x06, 0x00, 0x00,
0x0a, 0x00, 0x00, 0x01,
0x0a, 0x00, 0x00, 0x02,
0x0d, 0x00, 0xe0, 0x00,
0x00, 0x00, 0x01, 0x00,
0x00, 0x00, 0x02, 0x00,
0x80, 0x10, 0x10, 0x00,
0x14, 0x09, 0x00, 0x00,
0x01, 0x01, 0x08, 0x0a,
0x11, 0x11, 0x11, 0x11,
0x11, 0x11, 0x11, 0x11,
};
static int tg3_run_loopback(struct tg3 *tp, u32 pktsz, bool tso_loopback)
{
u32 rx_start_idx, rx_idx, tx_idx, opaque_key;
u32 base_flags = 0, mss = 0, desc_idx, coal_now, data_off, val;
u32 budget;
struct sk_buff *skb;
u8 *tx_data, *rx_data;
dma_addr_t map;
int num_pkts, tx_len, rx_len, i, err;
struct tg3_rx_buffer_desc *desc;
struct tg3_napi *tnapi, *rnapi;
struct tg3_rx_prodring_set *tpr = &tp->napi[0].prodring;
tnapi = &tp->napi[0];
rnapi = &tp->napi[0];
if (tp->irq_cnt > 1) {
if (tg3_flag(tp, ENABLE_RSS))
rnapi = &tp->napi[1];
if (tg3_flag(tp, ENABLE_TSS))
tnapi = &tp->napi[1];
}
coal_now = tnapi->coal_now | rnapi->coal_now;
err = -EIO;
tx_len = pktsz;
skb = netdev_alloc_skb(tp->dev, tx_len);
if (!skb)
return -ENOMEM;
tx_data = skb_put(skb, tx_len);
memcpy(tx_data, tp->dev->dev_addr, 6);
memset(tx_data + 6, 0x0, 8);
tw32(MAC_RX_MTU_SIZE, tx_len + ETH_FCS_LEN);
if (tso_loopback) {
struct iphdr *iph = (struct iphdr *)&tx_data[ETH_HLEN];
u32 hdr_len = TG3_TSO_IP_HDR_LEN + TG3_TSO_TCP_HDR_LEN +
TG3_TSO_TCP_OPT_LEN;
memcpy(tx_data + ETH_ALEN * 2, tg3_tso_header,
sizeof(tg3_tso_header));
mss = TG3_TSO_MSS;
val = tx_len - ETH_ALEN * 2 - sizeof(tg3_tso_header);
num_pkts = DIV_ROUND_UP(val, TG3_TSO_MSS);
/* Set the total length field in the IP header */
iph->tot_len = htons((u16)(mss + hdr_len));
base_flags = (TXD_FLAG_CPU_PRE_DMA |
TXD_FLAG_CPU_POST_DMA);
if (tg3_flag(tp, HW_TSO_1) ||
tg3_flag(tp, HW_TSO_2) ||
tg3_flag(tp, HW_TSO_3)) {
struct tcphdr *th;
val = ETH_HLEN + TG3_TSO_IP_HDR_LEN;
th = (struct tcphdr *)&tx_data[val];
th->check = 0;
} else
base_flags |= TXD_FLAG_TCPUDP_CSUM;
if (tg3_flag(tp, HW_TSO_3)) {
mss |= (hdr_len & 0xc) << 12;
if (hdr_len & 0x10)
base_flags |= 0x00000010;
base_flags |= (hdr_len & 0x3e0) << 5;
} else if (tg3_flag(tp, HW_TSO_2))
mss |= hdr_len << 9;
else if (tg3_flag(tp, HW_TSO_1) ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5705) {
mss |= (TG3_TSO_TCP_OPT_LEN << 9);
} else {
base_flags |= (TG3_TSO_TCP_OPT_LEN << 10);
}
data_off = ETH_ALEN * 2 + sizeof(tg3_tso_header);
} else {
num_pkts = 1;
data_off = ETH_HLEN;
if (tg3_flag(tp, USE_JUMBO_BDFLAG) &&
tx_len > VLAN_ETH_FRAME_LEN)
base_flags |= TXD_FLAG_JMB_PKT;
}
for (i = data_off; i < tx_len; i++)
tx_data[i] = (u8) (i & 0xff);
map = pci_map_single(tp->pdev, skb->data, tx_len, PCI_DMA_TODEVICE);
if (pci_dma_mapping_error(tp->pdev, map)) {
dev_kfree_skb(skb);
return -EIO;
}
val = tnapi->tx_prod;
tnapi->tx_buffers[val].skb = skb;
dma_unmap_addr_set(&tnapi->tx_buffers[val], mapping, map);
tw32_f(HOSTCC_MODE, tp->coalesce_mode | HOSTCC_MODE_ENABLE |
rnapi->coal_now);
udelay(10);
rx_start_idx = rnapi->hw_status->idx[0].rx_producer;
budget = tg3_tx_avail(tnapi);
if (tg3_tx_frag_set(tnapi, &val, &budget, map, tx_len,
base_flags | TXD_FLAG_END, mss, 0)) {
tnapi->tx_buffers[val].skb = NULL;
dev_kfree_skb(skb);
return -EIO;
}
tnapi->tx_prod++;
/* Sync BD data before updating mailbox */
wmb();
tw32_tx_mbox(tnapi->prodmbox, tnapi->tx_prod);
tr32_mailbox(tnapi->prodmbox);
udelay(10);
/* 350 usec to allow enough time on some 10/100 Mbps devices. */
for (i = 0; i < 35; i++) {
tw32_f(HOSTCC_MODE, tp->coalesce_mode | HOSTCC_MODE_ENABLE |
coal_now);
udelay(10);
tx_idx = tnapi->hw_status->idx[0].tx_consumer;
rx_idx = rnapi->hw_status->idx[0].rx_producer;
if ((tx_idx == tnapi->tx_prod) &&
(rx_idx == (rx_start_idx + num_pkts)))
break;
}
tg3_tx_skb_unmap(tnapi, tnapi->tx_prod - 1, -1);
dev_kfree_skb(skb);
if (tx_idx != tnapi->tx_prod)
goto out;
if (rx_idx != rx_start_idx + num_pkts)
goto out;
val = data_off;
while (rx_idx != rx_start_idx) {
desc = &rnapi->rx_rcb[rx_start_idx++];
desc_idx = desc->opaque & RXD_OPAQUE_INDEX_MASK;
opaque_key = desc->opaque & RXD_OPAQUE_RING_MASK;
if ((desc->err_vlan & RXD_ERR_MASK) != 0 &&
(desc->err_vlan != RXD_ERR_ODD_NIBBLE_RCVD_MII))
goto out;
rx_len = ((desc->idx_len & RXD_LEN_MASK) >> RXD_LEN_SHIFT)
- ETH_FCS_LEN;
if (!tso_loopback) {
if (rx_len != tx_len)
goto out;
if (pktsz <= TG3_RX_STD_DMA_SZ - ETH_FCS_LEN) {
if (opaque_key != RXD_OPAQUE_RING_STD)
goto out;
} else {
if (opaque_key != RXD_OPAQUE_RING_JUMBO)
goto out;
}
} else if ((desc->type_flags & RXD_FLAG_TCPUDP_CSUM) &&
(desc->ip_tcp_csum & RXD_TCPCSUM_MASK)
>> RXD_TCPCSUM_SHIFT != 0xffff) {
goto out;
}
if (opaque_key == RXD_OPAQUE_RING_STD) {
rx_data = tpr->rx_std_buffers[desc_idx].data;
map = dma_unmap_addr(&tpr->rx_std_buffers[desc_idx],
mapping);
} else if (opaque_key == RXD_OPAQUE_RING_JUMBO) {
rx_data = tpr->rx_jmb_buffers[desc_idx].data;
map = dma_unmap_addr(&tpr->rx_jmb_buffers[desc_idx],
mapping);
} else
goto out;
pci_dma_sync_single_for_cpu(tp->pdev, map, rx_len,
PCI_DMA_FROMDEVICE);
rx_data += TG3_RX_OFFSET(tp);
for (i = data_off; i < rx_len; i++, val++) {
if (*(rx_data + i) != (u8) (val & 0xff))
goto out;
}
}
err = 0;
/* tg3_free_rings will unmap and free the rx_data */
out:
return err;
}
#define TG3_STD_LOOPBACK_FAILED 1
#define TG3_JMB_LOOPBACK_FAILED 2
#define TG3_TSO_LOOPBACK_FAILED 4
#define TG3_LOOPBACK_FAILED \
(TG3_STD_LOOPBACK_FAILED | \
TG3_JMB_LOOPBACK_FAILED | \
TG3_TSO_LOOPBACK_FAILED)
static int tg3_test_loopback(struct tg3 *tp, u64 *data, bool do_extlpbk)
{
int err = -EIO;
u32 eee_cap;
u32 jmb_pkt_sz = 9000;
if (tp->dma_limit)
jmb_pkt_sz = tp->dma_limit - ETH_HLEN;
eee_cap = tp->phy_flags & TG3_PHYFLG_EEE_CAP;
tp->phy_flags &= ~TG3_PHYFLG_EEE_CAP;
if (!netif_running(tp->dev)) {
data[0] = TG3_LOOPBACK_FAILED;
data[1] = TG3_LOOPBACK_FAILED;
if (do_extlpbk)
data[2] = TG3_LOOPBACK_FAILED;
goto done;
}
err = tg3_reset_hw(tp, 1);
if (err) {
data[0] = TG3_LOOPBACK_FAILED;
data[1] = TG3_LOOPBACK_FAILED;
if (do_extlpbk)
data[2] = TG3_LOOPBACK_FAILED;
goto done;
}
if (tg3_flag(tp, ENABLE_RSS)) {
int i;
/* Reroute all rx packets to the 1st queue */
for (i = MAC_RSS_INDIR_TBL_0;
i < MAC_RSS_INDIR_TBL_0 + TG3_RSS_INDIR_TBL_SIZE; i += 4)
tw32(i, 0x0);
}
/* HW errata - mac loopback fails in some cases on 5780.
* Normal traffic and PHY loopback are not affected by
* errata. Also, the MAC loopback test is deprecated for
* all newer ASIC revisions.
*/
if (GET_ASIC_REV(tp->pci_chip_rev_id) != ASIC_REV_5780 &&
!tg3_flag(tp, CPMU_PRESENT)) {
tg3_mac_loopback(tp, true);
if (tg3_run_loopback(tp, ETH_FRAME_LEN, false))
data[0] |= TG3_STD_LOOPBACK_FAILED;
if (tg3_flag(tp, JUMBO_RING_ENABLE) &&
tg3_run_loopback(tp, jmb_pkt_sz + ETH_HLEN, false))
data[0] |= TG3_JMB_LOOPBACK_FAILED;
tg3_mac_loopback(tp, false);
}
if (!(tp->phy_flags & TG3_PHYFLG_PHY_SERDES) &&
!tg3_flag(tp, USE_PHYLIB)) {
int i;
tg3_phy_lpbk_set(tp, 0, false);
/* Wait for link */
for (i = 0; i < 100; i++) {
if (tr32(MAC_TX_STATUS) & TX_STATUS_LINK_UP)
break;
mdelay(1);
}
if (tg3_run_loopback(tp, ETH_FRAME_LEN, false))
data[1] |= TG3_STD_LOOPBACK_FAILED;
if (tg3_flag(tp, TSO_CAPABLE) &&
tg3_run_loopback(tp, ETH_FRAME_LEN, true))
data[1] |= TG3_TSO_LOOPBACK_FAILED;
if (tg3_flag(tp, JUMBO_RING_ENABLE) &&
tg3_run_loopback(tp, jmb_pkt_sz + ETH_HLEN, false))
data[1] |= TG3_JMB_LOOPBACK_FAILED;
if (do_extlpbk) {
tg3_phy_lpbk_set(tp, 0, true);
/* All link indications report up, but the hardware
* isn't really ready for about 20 msec. Double it
* to be sure.
*/
mdelay(40);
if (tg3_run_loopback(tp, ETH_FRAME_LEN, false))
data[2] |= TG3_STD_LOOPBACK_FAILED;
if (tg3_flag(tp, TSO_CAPABLE) &&
tg3_run_loopback(tp, ETH_FRAME_LEN, true))
data[2] |= TG3_TSO_LOOPBACK_FAILED;
if (tg3_flag(tp, JUMBO_RING_ENABLE) &&
tg3_run_loopback(tp, jmb_pkt_sz + ETH_HLEN, false))
data[2] |= TG3_JMB_LOOPBACK_FAILED;
}
/* Re-enable gphy autopowerdown. */
if (tp->phy_flags & TG3_PHYFLG_ENABLE_APD)
tg3_phy_toggle_apd(tp, true);
}
err = (data[0] | data[1] | data[2]) ? -EIO : 0;
done:
tp->phy_flags |= eee_cap;
return err;
}
static void tg3_self_test(struct net_device *dev, struct ethtool_test *etest,
u64 *data)
{
struct tg3 *tp = netdev_priv(dev);
bool doextlpbk = etest->flags & ETH_TEST_FL_EXTERNAL_LB;
if ((tp->phy_flags & TG3_PHYFLG_IS_LOW_POWER) &&
tg3_power_up(tp)) {
etest->flags |= ETH_TEST_FL_FAILED;
memset(data, 1, sizeof(u64) * TG3_NUM_TEST);
return;
}
memset(data, 0, sizeof(u64) * TG3_NUM_TEST);
if (tg3_test_nvram(tp) != 0) {
etest->flags |= ETH_TEST_FL_FAILED;
data[0] = 1;
}
if (!doextlpbk && tg3_test_link(tp)) {
etest->flags |= ETH_TEST_FL_FAILED;
data[1] = 1;
}
if (etest->flags & ETH_TEST_FL_OFFLINE) {
int err, err2 = 0, irq_sync = 0;
if (netif_running(dev)) {
tg3_phy_stop(tp);
tg3_netif_stop(tp);
irq_sync = 1;
}
tg3_full_lock(tp, irq_sync);
tg3_halt(tp, RESET_KIND_SUSPEND, 1);
err = tg3_nvram_lock(tp);
tg3_halt_cpu(tp, RX_CPU_BASE);
if (!tg3_flag(tp, 5705_PLUS))
tg3_halt_cpu(tp, TX_CPU_BASE);
if (!err)
tg3_nvram_unlock(tp);
if (tp->phy_flags & TG3_PHYFLG_MII_SERDES)
tg3_phy_reset(tp);
if (tg3_test_registers(tp) != 0) {
etest->flags |= ETH_TEST_FL_FAILED;
data[2] = 1;
}
if (tg3_test_memory(tp) != 0) {
etest->flags |= ETH_TEST_FL_FAILED;
data[3] = 1;
}
if (doextlpbk)
etest->flags |= ETH_TEST_FL_EXTERNAL_LB_DONE;
if (tg3_test_loopback(tp, &data[4], doextlpbk))
etest->flags |= ETH_TEST_FL_FAILED;
tg3_full_unlock(tp);
if (tg3_test_interrupt(tp) != 0) {
etest->flags |= ETH_TEST_FL_FAILED;
data[7] = 1;
}
tg3_full_lock(tp, 0);
tg3_halt(tp, RESET_KIND_SHUTDOWN, 1);
if (netif_running(dev)) {
tg3_flag_set(tp, INIT_COMPLETE);
err2 = tg3_restart_hw(tp, 1);
if (!err2)
tg3_netif_start(tp);
}
tg3_full_unlock(tp);
if (irq_sync && !err2)
tg3_phy_start(tp);
}
if (tp->phy_flags & TG3_PHYFLG_IS_LOW_POWER)
tg3_power_down(tp);
}
static int tg3_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
{
struct mii_ioctl_data *data = if_mii(ifr);
struct tg3 *tp = netdev_priv(dev);
int err;
if (tg3_flag(tp, USE_PHYLIB)) {
struct phy_device *phydev;
if (!(tp->phy_flags & TG3_PHYFLG_IS_CONNECTED))
return -EAGAIN;
phydev = tp->mdio_bus->phy_map[TG3_PHY_MII_ADDR];
return phy_mii_ioctl(phydev, ifr, cmd);
}
switch (cmd) {
case SIOCGMIIPHY:
data->phy_id = tp->phy_addr;
/* fallthru */
case SIOCGMIIREG: {
u32 mii_regval;
if (tp->phy_flags & TG3_PHYFLG_PHY_SERDES)
break; /* We have no PHY */
if (!netif_running(dev))
return -EAGAIN;
spin_lock_bh(&tp->lock);
err = tg3_readphy(tp, data->reg_num & 0x1f, &mii_regval);
spin_unlock_bh(&tp->lock);
data->val_out = mii_regval;
return err;
}
case SIOCSMIIREG:
if (tp->phy_flags & TG3_PHYFLG_PHY_SERDES)
break; /* We have no PHY */
if (!netif_running(dev))
return -EAGAIN;
spin_lock_bh(&tp->lock);
err = tg3_writephy(tp, data->reg_num & 0x1f, data->val_in);
spin_unlock_bh(&tp->lock);
return err;
default:
/* do nothing */
break;
}
return -EOPNOTSUPP;
}
static int tg3_get_coalesce(struct net_device *dev, struct ethtool_coalesce *ec)
{
struct tg3 *tp = netdev_priv(dev);
memcpy(ec, &tp->coal, sizeof(*ec));
return 0;
}
static int tg3_set_coalesce(struct net_device *dev, struct ethtool_coalesce *ec)
{
struct tg3 *tp = netdev_priv(dev);
u32 max_rxcoal_tick_int = 0, max_txcoal_tick_int = 0;
u32 max_stat_coal_ticks = 0, min_stat_coal_ticks = 0;
if (!tg3_flag(tp, 5705_PLUS)) {
max_rxcoal_tick_int = MAX_RXCOAL_TICK_INT;
max_txcoal_tick_int = MAX_TXCOAL_TICK_INT;
max_stat_coal_ticks = MAX_STAT_COAL_TICKS;
min_stat_coal_ticks = MIN_STAT_COAL_TICKS;
}
if ((ec->rx_coalesce_usecs > MAX_RXCOL_TICKS) ||
(ec->tx_coalesce_usecs > MAX_TXCOL_TICKS) ||
(ec->rx_max_coalesced_frames > MAX_RXMAX_FRAMES) ||
(ec->tx_max_coalesced_frames > MAX_TXMAX_FRAMES) ||
(ec->rx_coalesce_usecs_irq > max_rxcoal_tick_int) ||
(ec->tx_coalesce_usecs_irq > max_txcoal_tick_int) ||
(ec->rx_max_coalesced_frames_irq > MAX_RXCOAL_MAXF_INT) ||
(ec->tx_max_coalesced_frames_irq > MAX_TXCOAL_MAXF_INT) ||
(ec->stats_block_coalesce_usecs > max_stat_coal_ticks) ||
(ec->stats_block_coalesce_usecs < min_stat_coal_ticks))
return -EINVAL;
/* No rx interrupts will be generated if both are zero */
if ((ec->rx_coalesce_usecs == 0) &&
(ec->rx_max_coalesced_frames == 0))
return -EINVAL;
/* No tx interrupts will be generated if both are zero */
if ((ec->tx_coalesce_usecs == 0) &&
(ec->tx_max_coalesced_frames == 0))
return -EINVAL;
/* Only copy relevant parameters, ignore all others. */
tp->coal.rx_coalesce_usecs = ec->rx_coalesce_usecs;
tp->coal.tx_coalesce_usecs = ec->tx_coalesce_usecs;
tp->coal.rx_max_coalesced_frames = ec->rx_max_coalesced_frames;
tp->coal.tx_max_coalesced_frames = ec->tx_max_coalesced_frames;
tp->coal.rx_coalesce_usecs_irq = ec->rx_coalesce_usecs_irq;
tp->coal.tx_coalesce_usecs_irq = ec->tx_coalesce_usecs_irq;
tp->coal.rx_max_coalesced_frames_irq = ec->rx_max_coalesced_frames_irq;
tp->coal.tx_max_coalesced_frames_irq = ec->tx_max_coalesced_frames_irq;
tp->coal.stats_block_coalesce_usecs = ec->stats_block_coalesce_usecs;
if (netif_running(dev)) {
tg3_full_lock(tp, 0);
__tg3_set_coalesce(tp, &tp->coal);
tg3_full_unlock(tp);
}
return 0;
}
static const struct ethtool_ops tg3_ethtool_ops = {
.get_settings = tg3_get_settings,
.set_settings = tg3_set_settings,
.get_drvinfo = tg3_get_drvinfo,
.get_regs_len = tg3_get_regs_len,
.get_regs = tg3_get_regs,
.get_wol = tg3_get_wol,
.set_wol = tg3_set_wol,
.get_msglevel = tg3_get_msglevel,
.set_msglevel = tg3_set_msglevel,
.nway_reset = tg3_nway_reset,
.get_link = ethtool_op_get_link,
.get_eeprom_len = tg3_get_eeprom_len,
.get_eeprom = tg3_get_eeprom,
.set_eeprom = tg3_set_eeprom,
.get_ringparam = tg3_get_ringparam,
.set_ringparam = tg3_set_ringparam,
.get_pauseparam = tg3_get_pauseparam,
.set_pauseparam = tg3_set_pauseparam,
.self_test = tg3_self_test,
.get_strings = tg3_get_strings,
.set_phys_id = tg3_set_phys_id,
.get_ethtool_stats = tg3_get_ethtool_stats,
.get_coalesce = tg3_get_coalesce,
.set_coalesce = tg3_set_coalesce,
.get_sset_count = tg3_get_sset_count,
.get_rxnfc = tg3_get_rxnfc,
.get_rxfh_indir_size = tg3_get_rxfh_indir_size,
.get_rxfh_indir = tg3_get_rxfh_indir,
.set_rxfh_indir = tg3_set_rxfh_indir,
};
static struct rtnl_link_stats64 *tg3_get_stats64(struct net_device *dev,
struct rtnl_link_stats64 *stats)
{
struct tg3 *tp = netdev_priv(dev);
if (!tp->hw_stats)
return &tp->net_stats_prev;
spin_lock_bh(&tp->lock);
tg3_get_nstats(tp, stats);
spin_unlock_bh(&tp->lock);
return stats;
}
static void tg3_set_rx_mode(struct net_device *dev)
{
struct tg3 *tp = netdev_priv(dev);
if (!netif_running(dev))
return;
tg3_full_lock(tp, 0);
__tg3_set_rx_mode(dev);
tg3_full_unlock(tp);
}
static inline void tg3_set_mtu(struct net_device *dev, struct tg3 *tp,
int new_mtu)
{
dev->mtu = new_mtu;
if (new_mtu > ETH_DATA_LEN) {
if (tg3_flag(tp, 5780_CLASS)) {
netdev_update_features(dev);
tg3_flag_clear(tp, TSO_CAPABLE);
} else {
tg3_flag_set(tp, JUMBO_RING_ENABLE);
}
} else {
if (tg3_flag(tp, 5780_CLASS)) {
tg3_flag_set(tp, TSO_CAPABLE);
netdev_update_features(dev);
}
tg3_flag_clear(tp, JUMBO_RING_ENABLE);
}
}
static int tg3_change_mtu(struct net_device *dev, int new_mtu)
{
struct tg3 *tp = netdev_priv(dev);
int err, reset_phy = 0;
if (new_mtu < TG3_MIN_MTU || new_mtu > TG3_MAX_MTU(tp))
return -EINVAL;
if (!netif_running(dev)) {
/* We'll just catch it later when the
* device is up'd.
*/
tg3_set_mtu(dev, tp, new_mtu);
return 0;
}
tg3_phy_stop(tp);
tg3_netif_stop(tp);
tg3_full_lock(tp, 1);
tg3_halt(tp, RESET_KIND_SHUTDOWN, 1);
tg3_set_mtu(dev, tp, new_mtu);
/* Reset PHY, otherwise the read DMA engine will be in a mode that
* breaks all requests to 256 bytes.
*/
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_57766)
reset_phy = 1;
err = tg3_restart_hw(tp, reset_phy);
if (!err)
tg3_netif_start(tp);
tg3_full_unlock(tp);
if (!err)
tg3_phy_start(tp);
return err;
}
static const struct net_device_ops tg3_netdev_ops = {
.ndo_open = tg3_open,
.ndo_stop = tg3_close,
.ndo_start_xmit = tg3_start_xmit,
.ndo_get_stats64 = tg3_get_stats64,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_rx_mode = tg3_set_rx_mode,
.ndo_set_mac_address = tg3_set_mac_addr,
.ndo_do_ioctl = tg3_ioctl,
.ndo_tx_timeout = tg3_tx_timeout,
.ndo_change_mtu = tg3_change_mtu,
.ndo_fix_features = tg3_fix_features,
.ndo_set_features = tg3_set_features,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = tg3_poll_controller,
#endif
};
static void __devinit tg3_get_eeprom_size(struct tg3 *tp)
{
u32 cursize, val, magic;
tp->nvram_size = EEPROM_CHIP_SIZE;
if (tg3_nvram_read(tp, 0, &magic) != 0)
return;
if ((magic != TG3_EEPROM_MAGIC) &&
((magic & TG3_EEPROM_MAGIC_FW_MSK) != TG3_EEPROM_MAGIC_FW) &&
((magic & TG3_EEPROM_MAGIC_HW_MSK) != TG3_EEPROM_MAGIC_HW))
return;
/*
* Size the chip by reading offsets at increasing powers of two.
* When we encounter our validation signature, we know the addressing
* has wrapped around, and thus have our chip size.
*/
cursize = 0x10;
while (cursize < tp->nvram_size) {
if (tg3_nvram_read(tp, cursize, &val) != 0)
return;
if (val == magic)
break;
cursize <<= 1;
}
tp->nvram_size = cursize;
}
static void __devinit tg3_get_nvram_size(struct tg3 *tp)
{
u32 val;
if (tg3_flag(tp, NO_NVRAM) || tg3_nvram_read(tp, 0, &val) != 0)
return;
/* Selfboot format */
if (val != TG3_EEPROM_MAGIC) {
tg3_get_eeprom_size(tp);
return;
}
if (tg3_nvram_read(tp, 0xf0, &val) == 0) {
if (val != 0) {
/* This is confusing. We want to operate on the
* 16-bit value at offset 0xf2. The tg3_nvram_read()
* call will read from NVRAM and byteswap the data
* according to the byteswapping settings for all
* other register accesses. This ensures the data we
* want will always reside in the lower 16-bits.
* However, the data in NVRAM is in LE format, which
* means the data from the NVRAM read will always be
* opposite the endianness of the CPU. The 16-bit
* byteswap then brings the data to CPU endianness.
*/
tp->nvram_size = swab16((u16)(val & 0x0000ffff)) * 1024;
return;
}
}
tp->nvram_size = TG3_NVRAM_SIZE_512KB;
}
static void __devinit tg3_get_nvram_info(struct tg3 *tp)
{
u32 nvcfg1;
nvcfg1 = tr32(NVRAM_CFG1);
if (nvcfg1 & NVRAM_CFG1_FLASHIF_ENAB) {
tg3_flag_set(tp, FLASH);
} else {
nvcfg1 &= ~NVRAM_CFG1_COMPAT_BYPASS;
tw32(NVRAM_CFG1, nvcfg1);
}
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5750 ||
tg3_flag(tp, 5780_CLASS)) {
switch (nvcfg1 & NVRAM_CFG1_VENDOR_MASK) {
case FLASH_VENDOR_ATMEL_FLASH_BUFFERED:
tp->nvram_jedecnum = JEDEC_ATMEL;
tp->nvram_pagesize = ATMEL_AT45DB0X1B_PAGE_SIZE;
tg3_flag_set(tp, NVRAM_BUFFERED);
break;
case FLASH_VENDOR_ATMEL_FLASH_UNBUFFERED:
tp->nvram_jedecnum = JEDEC_ATMEL;
tp->nvram_pagesize = ATMEL_AT25F512_PAGE_SIZE;
break;
case FLASH_VENDOR_ATMEL_EEPROM:
tp->nvram_jedecnum = JEDEC_ATMEL;
tp->nvram_pagesize = ATMEL_AT24C512_CHIP_SIZE;
tg3_flag_set(tp, NVRAM_BUFFERED);
break;
case FLASH_VENDOR_ST:
tp->nvram_jedecnum = JEDEC_ST;
tp->nvram_pagesize = ST_M45PEX0_PAGE_SIZE;
tg3_flag_set(tp, NVRAM_BUFFERED);
break;
case FLASH_VENDOR_SAIFUN:
tp->nvram_jedecnum = JEDEC_SAIFUN;
tp->nvram_pagesize = SAIFUN_SA25F0XX_PAGE_SIZE;
break;
case FLASH_VENDOR_SST_SMALL:
case FLASH_VENDOR_SST_LARGE:
tp->nvram_jedecnum = JEDEC_SST;
tp->nvram_pagesize = SST_25VF0X0_PAGE_SIZE;
break;
}
} else {
tp->nvram_jedecnum = JEDEC_ATMEL;
tp->nvram_pagesize = ATMEL_AT45DB0X1B_PAGE_SIZE;
tg3_flag_set(tp, NVRAM_BUFFERED);
}
}
static void __devinit tg3_nvram_get_pagesize(struct tg3 *tp, u32 nvmcfg1)
{
switch (nvmcfg1 & NVRAM_CFG1_5752PAGE_SIZE_MASK) {
case FLASH_5752PAGE_SIZE_256:
tp->nvram_pagesize = 256;
break;
case FLASH_5752PAGE_SIZE_512:
tp->nvram_pagesize = 512;
break;
case FLASH_5752PAGE_SIZE_1K:
tp->nvram_pagesize = 1024;
break;
case FLASH_5752PAGE_SIZE_2K:
tp->nvram_pagesize = 2048;
break;
case FLASH_5752PAGE_SIZE_4K:
tp->nvram_pagesize = 4096;
break;
case FLASH_5752PAGE_SIZE_264:
tp->nvram_pagesize = 264;
break;
case FLASH_5752PAGE_SIZE_528:
tp->nvram_pagesize = 528;
break;
}
}
static void __devinit tg3_get_5752_nvram_info(struct tg3 *tp)
{
u32 nvcfg1;
nvcfg1 = tr32(NVRAM_CFG1);
/* NVRAM protection for TPM */
if (nvcfg1 & (1 << 27))
tg3_flag_set(tp, PROTECTED_NVRAM);
switch (nvcfg1 & NVRAM_CFG1_5752VENDOR_MASK) {
case FLASH_5752VENDOR_ATMEL_EEPROM_64KHZ:
case FLASH_5752VENDOR_ATMEL_EEPROM_376KHZ:
tp->nvram_jedecnum = JEDEC_ATMEL;
tg3_flag_set(tp, NVRAM_BUFFERED);
break;
case FLASH_5752VENDOR_ATMEL_FLASH_BUFFERED:
tp->nvram_jedecnum = JEDEC_ATMEL;
tg3_flag_set(tp, NVRAM_BUFFERED);
tg3_flag_set(tp, FLASH);
break;
case FLASH_5752VENDOR_ST_M45PE10:
case FLASH_5752VENDOR_ST_M45PE20:
case FLASH_5752VENDOR_ST_M45PE40:
tp->nvram_jedecnum = JEDEC_ST;
tg3_flag_set(tp, NVRAM_BUFFERED);
tg3_flag_set(tp, FLASH);
break;
}
if (tg3_flag(tp, FLASH)) {
tg3_nvram_get_pagesize(tp, nvcfg1);
} else {
/* For eeprom, set pagesize to maximum eeprom size */
tp->nvram_pagesize = ATMEL_AT24C512_CHIP_SIZE;
nvcfg1 &= ~NVRAM_CFG1_COMPAT_BYPASS;
tw32(NVRAM_CFG1, nvcfg1);
}
}
static void __devinit tg3_get_5755_nvram_info(struct tg3 *tp)
{
u32 nvcfg1, protect = 0;
nvcfg1 = tr32(NVRAM_CFG1);
/* NVRAM protection for TPM */
if (nvcfg1 & (1 << 27)) {
tg3_flag_set(tp, PROTECTED_NVRAM);
protect = 1;
}
nvcfg1 &= NVRAM_CFG1_5752VENDOR_MASK;
switch (nvcfg1) {
case FLASH_5755VENDOR_ATMEL_FLASH_1:
case FLASH_5755VENDOR_ATMEL_FLASH_2:
case FLASH_5755VENDOR_ATMEL_FLASH_3:
case FLASH_5755VENDOR_ATMEL_FLASH_5:
tp->nvram_jedecnum = JEDEC_ATMEL;
tg3_flag_set(tp, NVRAM_BUFFERED);
tg3_flag_set(tp, FLASH);
tp->nvram_pagesize = 264;
if (nvcfg1 == FLASH_5755VENDOR_ATMEL_FLASH_1 ||
nvcfg1 == FLASH_5755VENDOR_ATMEL_FLASH_5)
tp->nvram_size = (protect ? 0x3e200 :
TG3_NVRAM_SIZE_512KB);
else if (nvcfg1 == FLASH_5755VENDOR_ATMEL_FLASH_2)
tp->nvram_size = (protect ? 0x1f200 :
TG3_NVRAM_SIZE_256KB);
else
tp->nvram_size = (protect ? 0x1f200 :
TG3_NVRAM_SIZE_128KB);
break;
case FLASH_5752VENDOR_ST_M45PE10:
case FLASH_5752VENDOR_ST_M45PE20:
case FLASH_5752VENDOR_ST_M45PE40:
tp->nvram_jedecnum = JEDEC_ST;
tg3_flag_set(tp, NVRAM_BUFFERED);
tg3_flag_set(tp, FLASH);
tp->nvram_pagesize = 256;
if (nvcfg1 == FLASH_5752VENDOR_ST_M45PE10)
tp->nvram_size = (protect ?
TG3_NVRAM_SIZE_64KB :
TG3_NVRAM_SIZE_128KB);
else if (nvcfg1 == FLASH_5752VENDOR_ST_M45PE20)
tp->nvram_size = (protect ?
TG3_NVRAM_SIZE_64KB :
TG3_NVRAM_SIZE_256KB);
else
tp->nvram_size = (protect ?
TG3_NVRAM_SIZE_128KB :
TG3_NVRAM_SIZE_512KB);
break;
}
}
static void __devinit tg3_get_5787_nvram_info(struct tg3 *tp)
{
u32 nvcfg1;
nvcfg1 = tr32(NVRAM_CFG1);
switch (nvcfg1 & NVRAM_CFG1_5752VENDOR_MASK) {
case FLASH_5787VENDOR_ATMEL_EEPROM_64KHZ:
case FLASH_5787VENDOR_ATMEL_EEPROM_376KHZ:
case FLASH_5787VENDOR_MICRO_EEPROM_64KHZ:
case FLASH_5787VENDOR_MICRO_EEPROM_376KHZ:
tp->nvram_jedecnum = JEDEC_ATMEL;
tg3_flag_set(tp, NVRAM_BUFFERED);
tp->nvram_pagesize = ATMEL_AT24C512_CHIP_SIZE;
nvcfg1 &= ~NVRAM_CFG1_COMPAT_BYPASS;
tw32(NVRAM_CFG1, nvcfg1);
break;
case FLASH_5752VENDOR_ATMEL_FLASH_BUFFERED:
case FLASH_5755VENDOR_ATMEL_FLASH_1:
case FLASH_5755VENDOR_ATMEL_FLASH_2:
case FLASH_5755VENDOR_ATMEL_FLASH_3:
tp->nvram_jedecnum = JEDEC_ATMEL;
tg3_flag_set(tp, NVRAM_BUFFERED);
tg3_flag_set(tp, FLASH);
tp->nvram_pagesize = 264;
break;
case FLASH_5752VENDOR_ST_M45PE10:
case FLASH_5752VENDOR_ST_M45PE20:
case FLASH_5752VENDOR_ST_M45PE40:
tp->nvram_jedecnum = JEDEC_ST;
tg3_flag_set(tp, NVRAM_BUFFERED);
tg3_flag_set(tp, FLASH);
tp->nvram_pagesize = 256;
break;
}
}
static void __devinit tg3_get_5761_nvram_info(struct tg3 *tp)
{
u32 nvcfg1, protect = 0;
nvcfg1 = tr32(NVRAM_CFG1);
/* NVRAM protection for TPM */
if (nvcfg1 & (1 << 27)) {
tg3_flag_set(tp, PROTECTED_NVRAM);
protect = 1;
}
nvcfg1 &= NVRAM_CFG1_5752VENDOR_MASK;
switch (nvcfg1) {
case FLASH_5761VENDOR_ATMEL_ADB021D:
case FLASH_5761VENDOR_ATMEL_ADB041D:
case FLASH_5761VENDOR_ATMEL_ADB081D:
case FLASH_5761VENDOR_ATMEL_ADB161D:
case FLASH_5761VENDOR_ATMEL_MDB021D:
case FLASH_5761VENDOR_ATMEL_MDB041D:
case FLASH_5761VENDOR_ATMEL_MDB081D:
case FLASH_5761VENDOR_ATMEL_MDB161D:
tp->nvram_jedecnum = JEDEC_ATMEL;
tg3_flag_set(tp, NVRAM_BUFFERED);
tg3_flag_set(tp, FLASH);
tg3_flag_set(tp, NO_NVRAM_ADDR_TRANS);
tp->nvram_pagesize = 256;
break;
case FLASH_5761VENDOR_ST_A_M45PE20:
case FLASH_5761VENDOR_ST_A_M45PE40:
case FLASH_5761VENDOR_ST_A_M45PE80:
case FLASH_5761VENDOR_ST_A_M45PE16:
case FLASH_5761VENDOR_ST_M_M45PE20:
case FLASH_5761VENDOR_ST_M_M45PE40:
case FLASH_5761VENDOR_ST_M_M45PE80:
case FLASH_5761VENDOR_ST_M_M45PE16:
tp->nvram_jedecnum = JEDEC_ST;
tg3_flag_set(tp, NVRAM_BUFFERED);
tg3_flag_set(tp, FLASH);
tp->nvram_pagesize = 256;
break;
}
if (protect) {
tp->nvram_size = tr32(NVRAM_ADDR_LOCKOUT);
} else {
switch (nvcfg1) {
case FLASH_5761VENDOR_ATMEL_ADB161D:
case FLASH_5761VENDOR_ATMEL_MDB161D:
case FLASH_5761VENDOR_ST_A_M45PE16:
case FLASH_5761VENDOR_ST_M_M45PE16:
tp->nvram_size = TG3_NVRAM_SIZE_2MB;
break;
case FLASH_5761VENDOR_ATMEL_ADB081D:
case FLASH_5761VENDOR_ATMEL_MDB081D:
case FLASH_5761VENDOR_ST_A_M45PE80:
case FLASH_5761VENDOR_ST_M_M45PE80:
tp->nvram_size = TG3_NVRAM_SIZE_1MB;
break;
case FLASH_5761VENDOR_ATMEL_ADB041D:
case FLASH_5761VENDOR_ATMEL_MDB041D:
case FLASH_5761VENDOR_ST_A_M45PE40:
case FLASH_5761VENDOR_ST_M_M45PE40:
tp->nvram_size = TG3_NVRAM_SIZE_512KB;
break;
case FLASH_5761VENDOR_ATMEL_ADB021D:
case FLASH_5761VENDOR_ATMEL_MDB021D:
case FLASH_5761VENDOR_ST_A_M45PE20:
case FLASH_5761VENDOR_ST_M_M45PE20:
tp->nvram_size = TG3_NVRAM_SIZE_256KB;
break;
}
}
}
static void __devinit tg3_get_5906_nvram_info(struct tg3 *tp)
{
tp->nvram_jedecnum = JEDEC_ATMEL;
tg3_flag_set(tp, NVRAM_BUFFERED);
tp->nvram_pagesize = ATMEL_AT24C512_CHIP_SIZE;
}
static void __devinit tg3_get_57780_nvram_info(struct tg3 *tp)
{
u32 nvcfg1;
nvcfg1 = tr32(NVRAM_CFG1);
switch (nvcfg1 & NVRAM_CFG1_5752VENDOR_MASK) {
case FLASH_5787VENDOR_ATMEL_EEPROM_376KHZ:
case FLASH_5787VENDOR_MICRO_EEPROM_376KHZ:
tp->nvram_jedecnum = JEDEC_ATMEL;
tg3_flag_set(tp, NVRAM_BUFFERED);
tp->nvram_pagesize = ATMEL_AT24C512_CHIP_SIZE;
nvcfg1 &= ~NVRAM_CFG1_COMPAT_BYPASS;
tw32(NVRAM_CFG1, nvcfg1);
return;
case FLASH_5752VENDOR_ATMEL_FLASH_BUFFERED:
case FLASH_57780VENDOR_ATMEL_AT45DB011D:
case FLASH_57780VENDOR_ATMEL_AT45DB011B:
case FLASH_57780VENDOR_ATMEL_AT45DB021D:
case FLASH_57780VENDOR_ATMEL_AT45DB021B:
case FLASH_57780VENDOR_ATMEL_AT45DB041D:
case FLASH_57780VENDOR_ATMEL_AT45DB041B:
tp->nvram_jedecnum = JEDEC_ATMEL;
tg3_flag_set(tp, NVRAM_BUFFERED);
tg3_flag_set(tp, FLASH);
switch (nvcfg1 & NVRAM_CFG1_5752VENDOR_MASK) {
case FLASH_5752VENDOR_ATMEL_FLASH_BUFFERED:
case FLASH_57780VENDOR_ATMEL_AT45DB011D:
case FLASH_57780VENDOR_ATMEL_AT45DB011B:
tp->nvram_size = TG3_NVRAM_SIZE_128KB;
break;
case FLASH_57780VENDOR_ATMEL_AT45DB021D:
case FLASH_57780VENDOR_ATMEL_AT45DB021B:
tp->nvram_size = TG3_NVRAM_SIZE_256KB;
break;
case FLASH_57780VENDOR_ATMEL_AT45DB041D:
case FLASH_57780VENDOR_ATMEL_AT45DB041B:
tp->nvram_size = TG3_NVRAM_SIZE_512KB;
break;
}
break;
case FLASH_5752VENDOR_ST_M45PE10:
case FLASH_5752VENDOR_ST_M45PE20:
case FLASH_5752VENDOR_ST_M45PE40:
tp->nvram_jedecnum = JEDEC_ST;
tg3_flag_set(tp, NVRAM_BUFFERED);
tg3_flag_set(tp, FLASH);
switch (nvcfg1 & NVRAM_CFG1_5752VENDOR_MASK) {
case FLASH_5752VENDOR_ST_M45PE10:
tp->nvram_size = TG3_NVRAM_SIZE_128KB;
break;
case FLASH_5752VENDOR_ST_M45PE20:
tp->nvram_size = TG3_NVRAM_SIZE_256KB;
break;
case FLASH_5752VENDOR_ST_M45PE40:
tp->nvram_size = TG3_NVRAM_SIZE_512KB;
break;
}
break;
default:
tg3_flag_set(tp, NO_NVRAM);
return;
}
tg3_nvram_get_pagesize(tp, nvcfg1);
if (tp->nvram_pagesize != 264 && tp->nvram_pagesize != 528)
tg3_flag_set(tp, NO_NVRAM_ADDR_TRANS);
}
static void __devinit tg3_get_5717_nvram_info(struct tg3 *tp)
{
u32 nvcfg1;
nvcfg1 = tr32(NVRAM_CFG1);
switch (nvcfg1 & NVRAM_CFG1_5752VENDOR_MASK) {
case FLASH_5717VENDOR_ATMEL_EEPROM:
case FLASH_5717VENDOR_MICRO_EEPROM:
tp->nvram_jedecnum = JEDEC_ATMEL;
tg3_flag_set(tp, NVRAM_BUFFERED);
tp->nvram_pagesize = ATMEL_AT24C512_CHIP_SIZE;
nvcfg1 &= ~NVRAM_CFG1_COMPAT_BYPASS;
tw32(NVRAM_CFG1, nvcfg1);
return;
case FLASH_5717VENDOR_ATMEL_MDB011D:
case FLASH_5717VENDOR_ATMEL_ADB011B:
case FLASH_5717VENDOR_ATMEL_ADB011D:
case FLASH_5717VENDOR_ATMEL_MDB021D:
case FLASH_5717VENDOR_ATMEL_ADB021B:
case FLASH_5717VENDOR_ATMEL_ADB021D:
case FLASH_5717VENDOR_ATMEL_45USPT:
tp->nvram_jedecnum = JEDEC_ATMEL;
tg3_flag_set(tp, NVRAM_BUFFERED);
tg3_flag_set(tp, FLASH);
switch (nvcfg1 & NVRAM_CFG1_5752VENDOR_MASK) {
case FLASH_5717VENDOR_ATMEL_MDB021D:
/* Detect size with tg3_nvram_get_size() */
break;
case FLASH_5717VENDOR_ATMEL_ADB021B:
case FLASH_5717VENDOR_ATMEL_ADB021D:
tp->nvram_size = TG3_NVRAM_SIZE_256KB;
break;
default:
tp->nvram_size = TG3_NVRAM_SIZE_128KB;
break;
}
break;
case FLASH_5717VENDOR_ST_M_M25PE10:
case FLASH_5717VENDOR_ST_A_M25PE10:
case FLASH_5717VENDOR_ST_M_M45PE10:
case FLASH_5717VENDOR_ST_A_M45PE10:
case FLASH_5717VENDOR_ST_M_M25PE20:
case FLASH_5717VENDOR_ST_A_M25PE20:
case FLASH_5717VENDOR_ST_M_M45PE20:
case FLASH_5717VENDOR_ST_A_M45PE20:
case FLASH_5717VENDOR_ST_25USPT:
case FLASH_5717VENDOR_ST_45USPT:
tp->nvram_jedecnum = JEDEC_ST;
tg3_flag_set(tp, NVRAM_BUFFERED);
tg3_flag_set(tp, FLASH);
switch (nvcfg1 & NVRAM_CFG1_5752VENDOR_MASK) {
case FLASH_5717VENDOR_ST_M_M25PE20:
case FLASH_5717VENDOR_ST_M_M45PE20:
/* Detect size with tg3_nvram_get_size() */
break;
case FLASH_5717VENDOR_ST_A_M25PE20:
case FLASH_5717VENDOR_ST_A_M45PE20:
tp->nvram_size = TG3_NVRAM_SIZE_256KB;
break;
default:
tp->nvram_size = TG3_NVRAM_SIZE_128KB;
break;
}
break;
default:
tg3_flag_set(tp, NO_NVRAM);
return;
}
tg3_nvram_get_pagesize(tp, nvcfg1);
if (tp->nvram_pagesize != 264 && tp->nvram_pagesize != 528)
tg3_flag_set(tp, NO_NVRAM_ADDR_TRANS);
}
static void __devinit tg3_get_5720_nvram_info(struct tg3 *tp)
{
u32 nvcfg1, nvmpinstrp;
nvcfg1 = tr32(NVRAM_CFG1);
nvmpinstrp = nvcfg1 & NVRAM_CFG1_5752VENDOR_MASK;
switch (nvmpinstrp) {
case FLASH_5720_EEPROM_HD:
case FLASH_5720_EEPROM_LD:
tp->nvram_jedecnum = JEDEC_ATMEL;
tg3_flag_set(tp, NVRAM_BUFFERED);
nvcfg1 &= ~NVRAM_CFG1_COMPAT_BYPASS;
tw32(NVRAM_CFG1, nvcfg1);
if (nvmpinstrp == FLASH_5720_EEPROM_HD)
tp->nvram_pagesize = ATMEL_AT24C512_CHIP_SIZE;
else
tp->nvram_pagesize = ATMEL_AT24C02_CHIP_SIZE;
return;
case FLASH_5720VENDOR_M_ATMEL_DB011D:
case FLASH_5720VENDOR_A_ATMEL_DB011B:
case FLASH_5720VENDOR_A_ATMEL_DB011D:
case FLASH_5720VENDOR_M_ATMEL_DB021D:
case FLASH_5720VENDOR_A_ATMEL_DB021B:
case FLASH_5720VENDOR_A_ATMEL_DB021D:
case FLASH_5720VENDOR_M_ATMEL_DB041D:
case FLASH_5720VENDOR_A_ATMEL_DB041B:
case FLASH_5720VENDOR_A_ATMEL_DB041D:
case FLASH_5720VENDOR_M_ATMEL_DB081D:
case FLASH_5720VENDOR_A_ATMEL_DB081D:
case FLASH_5720VENDOR_ATMEL_45USPT:
tp->nvram_jedecnum = JEDEC_ATMEL;
tg3_flag_set(tp, NVRAM_BUFFERED);
tg3_flag_set(tp, FLASH);
switch (nvmpinstrp) {
case FLASH_5720VENDOR_M_ATMEL_DB021D:
case FLASH_5720VENDOR_A_ATMEL_DB021B:
case FLASH_5720VENDOR_A_ATMEL_DB021D:
tp->nvram_size = TG3_NVRAM_SIZE_256KB;
break;
case FLASH_5720VENDOR_M_ATMEL_DB041D:
case FLASH_5720VENDOR_A_ATMEL_DB041B:
case FLASH_5720VENDOR_A_ATMEL_DB041D:
tp->nvram_size = TG3_NVRAM_SIZE_512KB;
break;
case FLASH_5720VENDOR_M_ATMEL_DB081D:
case FLASH_5720VENDOR_A_ATMEL_DB081D:
tp->nvram_size = TG3_NVRAM_SIZE_1MB;
break;
default:
tp->nvram_size = TG3_NVRAM_SIZE_128KB;
break;
}
break;
case FLASH_5720VENDOR_M_ST_M25PE10:
case FLASH_5720VENDOR_M_ST_M45PE10:
case FLASH_5720VENDOR_A_ST_M25PE10:
case FLASH_5720VENDOR_A_ST_M45PE10:
case FLASH_5720VENDOR_M_ST_M25PE20:
case FLASH_5720VENDOR_M_ST_M45PE20:
case FLASH_5720VENDOR_A_ST_M25PE20:
case FLASH_5720VENDOR_A_ST_M45PE20:
case FLASH_5720VENDOR_M_ST_M25PE40:
case FLASH_5720VENDOR_M_ST_M45PE40:
case FLASH_5720VENDOR_A_ST_M25PE40:
case FLASH_5720VENDOR_A_ST_M45PE40:
case FLASH_5720VENDOR_M_ST_M25PE80:
case FLASH_5720VENDOR_M_ST_M45PE80:
case FLASH_5720VENDOR_A_ST_M25PE80:
case FLASH_5720VENDOR_A_ST_M45PE80:
case FLASH_5720VENDOR_ST_25USPT:
case FLASH_5720VENDOR_ST_45USPT:
tp->nvram_jedecnum = JEDEC_ST;
tg3_flag_set(tp, NVRAM_BUFFERED);
tg3_flag_set(tp, FLASH);
switch (nvmpinstrp) {
case FLASH_5720VENDOR_M_ST_M25PE20:
case FLASH_5720VENDOR_M_ST_M45PE20:
case FLASH_5720VENDOR_A_ST_M25PE20:
case FLASH_5720VENDOR_A_ST_M45PE20:
tp->nvram_size = TG3_NVRAM_SIZE_256KB;
break;
case FLASH_5720VENDOR_M_ST_M25PE40:
case FLASH_5720VENDOR_M_ST_M45PE40:
case FLASH_5720VENDOR_A_ST_M25PE40:
case FLASH_5720VENDOR_A_ST_M45PE40:
tp->nvram_size = TG3_NVRAM_SIZE_512KB;
break;
case FLASH_5720VENDOR_M_ST_M25PE80:
case FLASH_5720VENDOR_M_ST_M45PE80:
case FLASH_5720VENDOR_A_ST_M25PE80:
case FLASH_5720VENDOR_A_ST_M45PE80:
tp->nvram_size = TG3_NVRAM_SIZE_1MB;
break;
default:
tp->nvram_size = TG3_NVRAM_SIZE_128KB;
break;
}
break;
default:
tg3_flag_set(tp, NO_NVRAM);
return;
}
tg3_nvram_get_pagesize(tp, nvcfg1);
if (tp->nvram_pagesize != 264 && tp->nvram_pagesize != 528)
tg3_flag_set(tp, NO_NVRAM_ADDR_TRANS);
}
/* Chips other than 5700/5701 use the NVRAM for fetching info. */
static void __devinit tg3_nvram_init(struct tg3 *tp)
{
tw32_f(GRC_EEPROM_ADDR,
(EEPROM_ADDR_FSM_RESET |
(EEPROM_DEFAULT_CLOCK_PERIOD <<
EEPROM_ADDR_CLKPERD_SHIFT)));
msleep(1);
/* Enable seeprom accesses. */
tw32_f(GRC_LOCAL_CTRL,
tr32(GRC_LOCAL_CTRL) | GRC_LCLCTRL_AUTO_SEEPROM);
udelay(100);
if (GET_ASIC_REV(tp->pci_chip_rev_id) != ASIC_REV_5700 &&
GET_ASIC_REV(tp->pci_chip_rev_id) != ASIC_REV_5701) {
tg3_flag_set(tp, NVRAM);
if (tg3_nvram_lock(tp)) {
netdev_warn(tp->dev,
"Cannot get nvram lock, %s failed\n",
__func__);
return;
}
tg3_enable_nvram_access(tp);
tp->nvram_size = 0;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5752)
tg3_get_5752_nvram_info(tp);
else if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5755)
tg3_get_5755_nvram_info(tp);
else if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5787 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5784 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5785)
tg3_get_5787_nvram_info(tp);
else if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5761)
tg3_get_5761_nvram_info(tp);
else if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5906)
tg3_get_5906_nvram_info(tp);
else if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_57780 ||
tg3_flag(tp, 57765_CLASS))
tg3_get_57780_nvram_info(tp);
else if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5717 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5719)
tg3_get_5717_nvram_info(tp);
else if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5720)
tg3_get_5720_nvram_info(tp);
else
tg3_get_nvram_info(tp);
if (tp->nvram_size == 0)
tg3_get_nvram_size(tp);
tg3_disable_nvram_access(tp);
tg3_nvram_unlock(tp);
} else {
tg3_flag_clear(tp, NVRAM);
tg3_flag_clear(tp, NVRAM_BUFFERED);
tg3_get_eeprom_size(tp);
}
}
struct subsys_tbl_ent {
u16 subsys_vendor, subsys_devid;
u32 phy_id;
};
static struct subsys_tbl_ent subsys_id_to_phy_id[] __devinitdata = {
/* Broadcom boards. */
{ TG3PCI_SUBVENDOR_ID_BROADCOM,
TG3PCI_SUBDEVICE_ID_BROADCOM_95700A6, TG3_PHY_ID_BCM5401 },
{ TG3PCI_SUBVENDOR_ID_BROADCOM,
TG3PCI_SUBDEVICE_ID_BROADCOM_95701A5, TG3_PHY_ID_BCM5701 },
{ TG3PCI_SUBVENDOR_ID_BROADCOM,
TG3PCI_SUBDEVICE_ID_BROADCOM_95700T6, TG3_PHY_ID_BCM8002 },
{ TG3PCI_SUBVENDOR_ID_BROADCOM,
TG3PCI_SUBDEVICE_ID_BROADCOM_95700A9, 0 },
{ TG3PCI_SUBVENDOR_ID_BROADCOM,
TG3PCI_SUBDEVICE_ID_BROADCOM_95701T1, TG3_PHY_ID_BCM5701 },
{ TG3PCI_SUBVENDOR_ID_BROADCOM,
TG3PCI_SUBDEVICE_ID_BROADCOM_95701T8, TG3_PHY_ID_BCM5701 },
{ TG3PCI_SUBVENDOR_ID_BROADCOM,
TG3PCI_SUBDEVICE_ID_BROADCOM_95701A7, 0 },
{ TG3PCI_SUBVENDOR_ID_BROADCOM,
TG3PCI_SUBDEVICE_ID_BROADCOM_95701A10, TG3_PHY_ID_BCM5701 },
{ TG3PCI_SUBVENDOR_ID_BROADCOM,
TG3PCI_SUBDEVICE_ID_BROADCOM_95701A12, TG3_PHY_ID_BCM5701 },
{ TG3PCI_SUBVENDOR_ID_BROADCOM,
TG3PCI_SUBDEVICE_ID_BROADCOM_95703AX1, TG3_PHY_ID_BCM5703 },
{ TG3PCI_SUBVENDOR_ID_BROADCOM,
TG3PCI_SUBDEVICE_ID_BROADCOM_95703AX2, TG3_PHY_ID_BCM5703 },
/* 3com boards. */
{ TG3PCI_SUBVENDOR_ID_3COM,
TG3PCI_SUBDEVICE_ID_3COM_3C996T, TG3_PHY_ID_BCM5401 },
{ TG3PCI_SUBVENDOR_ID_3COM,
TG3PCI_SUBDEVICE_ID_3COM_3C996BT, TG3_PHY_ID_BCM5701 },
{ TG3PCI_SUBVENDOR_ID_3COM,
TG3PCI_SUBDEVICE_ID_3COM_3C996SX, 0 },
{ TG3PCI_SUBVENDOR_ID_3COM,
TG3PCI_SUBDEVICE_ID_3COM_3C1000T, TG3_PHY_ID_BCM5701 },
{ TG3PCI_SUBVENDOR_ID_3COM,
TG3PCI_SUBDEVICE_ID_3COM_3C940BR01, TG3_PHY_ID_BCM5701 },
/* DELL boards. */
{ TG3PCI_SUBVENDOR_ID_DELL,
TG3PCI_SUBDEVICE_ID_DELL_VIPER, TG3_PHY_ID_BCM5401 },
{ TG3PCI_SUBVENDOR_ID_DELL,
TG3PCI_SUBDEVICE_ID_DELL_JAGUAR, TG3_PHY_ID_BCM5401 },
{ TG3PCI_SUBVENDOR_ID_DELL,
TG3PCI_SUBDEVICE_ID_DELL_MERLOT, TG3_PHY_ID_BCM5411 },
{ TG3PCI_SUBVENDOR_ID_DELL,
TG3PCI_SUBDEVICE_ID_DELL_SLIM_MERLOT, TG3_PHY_ID_BCM5411 },
/* Compaq boards. */
{ TG3PCI_SUBVENDOR_ID_COMPAQ,
TG3PCI_SUBDEVICE_ID_COMPAQ_BANSHEE, TG3_PHY_ID_BCM5701 },
{ TG3PCI_SUBVENDOR_ID_COMPAQ,
TG3PCI_SUBDEVICE_ID_COMPAQ_BANSHEE_2, TG3_PHY_ID_BCM5701 },
{ TG3PCI_SUBVENDOR_ID_COMPAQ,
TG3PCI_SUBDEVICE_ID_COMPAQ_CHANGELING, 0 },
{ TG3PCI_SUBVENDOR_ID_COMPAQ,
TG3PCI_SUBDEVICE_ID_COMPAQ_NC7780, TG3_PHY_ID_BCM5701 },
{ TG3PCI_SUBVENDOR_ID_COMPAQ,
TG3PCI_SUBDEVICE_ID_COMPAQ_NC7780_2, TG3_PHY_ID_BCM5701 },
/* IBM boards. */
{ TG3PCI_SUBVENDOR_ID_IBM,
TG3PCI_SUBDEVICE_ID_IBM_5703SAX2, 0 }
};
static struct subsys_tbl_ent * __devinit tg3_lookup_by_subsys(struct tg3 *tp)
{
int i;
for (i = 0; i < ARRAY_SIZE(subsys_id_to_phy_id); i++) {
if ((subsys_id_to_phy_id[i].subsys_vendor ==
tp->pdev->subsystem_vendor) &&
(subsys_id_to_phy_id[i].subsys_devid ==
tp->pdev->subsystem_device))
return &subsys_id_to_phy_id[i];
}
return NULL;
}
static void __devinit tg3_get_eeprom_hw_cfg(struct tg3 *tp)
{
u32 val;
tp->phy_id = TG3_PHY_ID_INVALID;
tp->led_ctrl = LED_CTRL_MODE_PHY_1;
/* Assume an onboard device and WOL capable by default. */
tg3_flag_set(tp, EEPROM_WRITE_PROT);
tg3_flag_set(tp, WOL_CAP);
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5906) {
if (!(tr32(PCIE_TRANSACTION_CFG) & PCIE_TRANS_CFG_LOM)) {
tg3_flag_clear(tp, EEPROM_WRITE_PROT);
tg3_flag_set(tp, IS_NIC);
}
val = tr32(VCPU_CFGSHDW);
if (val & VCPU_CFGSHDW_ASPM_DBNC)
tg3_flag_set(tp, ASPM_WORKAROUND);
if ((val & VCPU_CFGSHDW_WOL_ENABLE) &&
(val & VCPU_CFGSHDW_WOL_MAGPKT)) {
tg3_flag_set(tp, WOL_ENABLE);
device_set_wakeup_enable(&tp->pdev->dev, true);
}
goto done;
}
tg3_read_mem(tp, NIC_SRAM_DATA_SIG, &val);
if (val == NIC_SRAM_DATA_SIG_MAGIC) {
u32 nic_cfg, led_cfg;
u32 nic_phy_id, ver, cfg2 = 0, cfg4 = 0, eeprom_phy_id;
int eeprom_phy_serdes = 0;
tg3_read_mem(tp, NIC_SRAM_DATA_CFG, &nic_cfg);
tp->nic_sram_data_cfg = nic_cfg;
tg3_read_mem(tp, NIC_SRAM_DATA_VER, &ver);
ver >>= NIC_SRAM_DATA_VER_SHIFT;
if (GET_ASIC_REV(tp->pci_chip_rev_id) != ASIC_REV_5700 &&
GET_ASIC_REV(tp->pci_chip_rev_id) != ASIC_REV_5701 &&
GET_ASIC_REV(tp->pci_chip_rev_id) != ASIC_REV_5703 &&
(ver > 0) && (ver < 0x100))
tg3_read_mem(tp, NIC_SRAM_DATA_CFG_2, &cfg2);
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5785)
tg3_read_mem(tp, NIC_SRAM_DATA_CFG_4, &cfg4);
if ((nic_cfg & NIC_SRAM_DATA_CFG_PHY_TYPE_MASK) ==
NIC_SRAM_DATA_CFG_PHY_TYPE_FIBER)
eeprom_phy_serdes = 1;
tg3_read_mem(tp, NIC_SRAM_DATA_PHY_ID, &nic_phy_id);
if (nic_phy_id != 0) {
u32 id1 = nic_phy_id & NIC_SRAM_DATA_PHY_ID1_MASK;
u32 id2 = nic_phy_id & NIC_SRAM_DATA_PHY_ID2_MASK;
eeprom_phy_id = (id1 >> 16) << 10;
eeprom_phy_id |= (id2 & 0xfc00) << 16;
eeprom_phy_id |= (id2 & 0x03ff) << 0;
} else
eeprom_phy_id = 0;
tp->phy_id = eeprom_phy_id;
if (eeprom_phy_serdes) {
if (!tg3_flag(tp, 5705_PLUS))
tp->phy_flags |= TG3_PHYFLG_PHY_SERDES;
else
tp->phy_flags |= TG3_PHYFLG_MII_SERDES;
}
if (tg3_flag(tp, 5750_PLUS))
led_cfg = cfg2 & (NIC_SRAM_DATA_CFG_LED_MODE_MASK |
SHASTA_EXT_LED_MODE_MASK);
else
led_cfg = nic_cfg & NIC_SRAM_DATA_CFG_LED_MODE_MASK;
switch (led_cfg) {
default:
case NIC_SRAM_DATA_CFG_LED_MODE_PHY_1:
tp->led_ctrl = LED_CTRL_MODE_PHY_1;
break;
case NIC_SRAM_DATA_CFG_LED_MODE_PHY_2:
tp->led_ctrl = LED_CTRL_MODE_PHY_2;
break;
case NIC_SRAM_DATA_CFG_LED_MODE_MAC:
tp->led_ctrl = LED_CTRL_MODE_MAC;
/* Default to PHY_1_MODE if 0 (MAC_MODE) is
* read on some older 5700/5701 bootcode.
*/
if (GET_ASIC_REV(tp->pci_chip_rev_id) ==
ASIC_REV_5700 ||
GET_ASIC_REV(tp->pci_chip_rev_id) ==
ASIC_REV_5701)
tp->led_ctrl = LED_CTRL_MODE_PHY_1;
break;
case SHASTA_EXT_LED_SHARED:
tp->led_ctrl = LED_CTRL_MODE_SHARED;
if (tp->pci_chip_rev_id != CHIPREV_ID_5750_A0 &&
tp->pci_chip_rev_id != CHIPREV_ID_5750_A1)
tp->led_ctrl |= (LED_CTRL_MODE_PHY_1 |
LED_CTRL_MODE_PHY_2);
break;
case SHASTA_EXT_LED_MAC:
tp->led_ctrl = LED_CTRL_MODE_SHASTA_MAC;
break;
case SHASTA_EXT_LED_COMBO:
tp->led_ctrl = LED_CTRL_MODE_COMBO;
if (tp->pci_chip_rev_id != CHIPREV_ID_5750_A0)
tp->led_ctrl |= (LED_CTRL_MODE_PHY_1 |
LED_CTRL_MODE_PHY_2);
break;
}
if ((GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5700 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5701) &&
tp->pdev->subsystem_vendor == PCI_VENDOR_ID_DELL)
tp->led_ctrl = LED_CTRL_MODE_PHY_2;
if (GET_CHIP_REV(tp->pci_chip_rev_id) == CHIPREV_5784_AX)
tp->led_ctrl = LED_CTRL_MODE_PHY_1;
if (nic_cfg & NIC_SRAM_DATA_CFG_EEPROM_WP) {
tg3_flag_set(tp, EEPROM_WRITE_PROT);
if ((tp->pdev->subsystem_vendor ==
PCI_VENDOR_ID_ARIMA) &&
(tp->pdev->subsystem_device == 0x205a ||
tp->pdev->subsystem_device == 0x2063))
tg3_flag_clear(tp, EEPROM_WRITE_PROT);
} else {
tg3_flag_clear(tp, EEPROM_WRITE_PROT);
tg3_flag_set(tp, IS_NIC);
}
if (nic_cfg & NIC_SRAM_DATA_CFG_ASF_ENABLE) {
tg3_flag_set(tp, ENABLE_ASF);
if (tg3_flag(tp, 5750_PLUS))
tg3_flag_set(tp, ASF_NEW_HANDSHAKE);
}
if ((nic_cfg & NIC_SRAM_DATA_CFG_APE_ENABLE) &&
tg3_flag(tp, 5750_PLUS))
tg3_flag_set(tp, ENABLE_APE);
if (tp->phy_flags & TG3_PHYFLG_ANY_SERDES &&
!(nic_cfg & NIC_SRAM_DATA_CFG_FIBER_WOL))
tg3_flag_clear(tp, WOL_CAP);
if (tg3_flag(tp, WOL_CAP) &&
(nic_cfg & NIC_SRAM_DATA_CFG_WOL_ENABLE)) {
tg3_flag_set(tp, WOL_ENABLE);
device_set_wakeup_enable(&tp->pdev->dev, true);
}
if (cfg2 & (1 << 17))
tp->phy_flags |= TG3_PHYFLG_CAPACITIVE_COUPLING;
/* serdes signal pre-emphasis in register 0x590 set by */
/* bootcode if bit 18 is set */
if (cfg2 & (1 << 18))
tp->phy_flags |= TG3_PHYFLG_SERDES_PREEMPHASIS;
if ((tg3_flag(tp, 57765_PLUS) ||
(GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5784 &&
GET_CHIP_REV(tp->pci_chip_rev_id) != CHIPREV_5784_AX)) &&
(cfg2 & NIC_SRAM_DATA_CFG_2_APD_EN))
tp->phy_flags |= TG3_PHYFLG_ENABLE_APD;
if (tg3_flag(tp, PCI_EXPRESS) &&
GET_ASIC_REV(tp->pci_chip_rev_id) != ASIC_REV_5785 &&
!tg3_flag(tp, 57765_PLUS)) {
u32 cfg3;
tg3_read_mem(tp, NIC_SRAM_DATA_CFG_3, &cfg3);
if (cfg3 & NIC_SRAM_ASPM_DEBOUNCE)
tg3_flag_set(tp, ASPM_WORKAROUND);
}
if (cfg4 & NIC_SRAM_RGMII_INBAND_DISABLE)
tg3_flag_set(tp, RGMII_INBAND_DISABLE);
if (cfg4 & NIC_SRAM_RGMII_EXT_IBND_RX_EN)
tg3_flag_set(tp, RGMII_EXT_IBND_RX_EN);
if (cfg4 & NIC_SRAM_RGMII_EXT_IBND_TX_EN)
tg3_flag_set(tp, RGMII_EXT_IBND_TX_EN);
}
done:
if (tg3_flag(tp, WOL_CAP))
device_set_wakeup_enable(&tp->pdev->dev,
tg3_flag(tp, WOL_ENABLE));
else
device_set_wakeup_capable(&tp->pdev->dev, false);
}
static int __devinit tg3_issue_otp_command(struct tg3 *tp, u32 cmd)
{
int i;
u32 val;
tw32(OTP_CTRL, cmd | OTP_CTRL_OTP_CMD_START);
tw32(OTP_CTRL, cmd);
/* Wait for up to 1 ms for command to execute. */
for (i = 0; i < 100; i++) {
val = tr32(OTP_STATUS);
if (val & OTP_STATUS_CMD_DONE)
break;
udelay(10);
}
return (val & OTP_STATUS_CMD_DONE) ? 0 : -EBUSY;
}
/* Read the gphy configuration from the OTP region of the chip. The gphy
* configuration is a 32-bit value that straddles the alignment boundary.
* We do two 32-bit reads and then shift and merge the results.
*/
static u32 __devinit tg3_read_otp_phycfg(struct tg3 *tp)
{
u32 bhalf_otp, thalf_otp;
tw32(OTP_MODE, OTP_MODE_OTP_THRU_GRC);
if (tg3_issue_otp_command(tp, OTP_CTRL_OTP_CMD_INIT))
return 0;
tw32(OTP_ADDRESS, OTP_ADDRESS_MAGIC1);
if (tg3_issue_otp_command(tp, OTP_CTRL_OTP_CMD_READ))
return 0;
thalf_otp = tr32(OTP_READ_DATA);
tw32(OTP_ADDRESS, OTP_ADDRESS_MAGIC2);
if (tg3_issue_otp_command(tp, OTP_CTRL_OTP_CMD_READ))
return 0;
bhalf_otp = tr32(OTP_READ_DATA);
return ((thalf_otp & 0x0000ffff) << 16) | (bhalf_otp >> 16);
}
static void __devinit tg3_phy_init_link_config(struct tg3 *tp)
{
u32 adv = ADVERTISED_Autoneg;
if (!(tp->phy_flags & TG3_PHYFLG_10_100_ONLY))
adv |= ADVERTISED_1000baseT_Half |
ADVERTISED_1000baseT_Full;
if (!(tp->phy_flags & TG3_PHYFLG_ANY_SERDES))
adv |= ADVERTISED_100baseT_Half |
ADVERTISED_100baseT_Full |
ADVERTISED_10baseT_Half |
ADVERTISED_10baseT_Full |
ADVERTISED_TP;
else
adv |= ADVERTISED_FIBRE;
tp->link_config.advertising = adv;
tp->link_config.speed = SPEED_UNKNOWN;
tp->link_config.duplex = DUPLEX_UNKNOWN;
tp->link_config.autoneg = AUTONEG_ENABLE;
tp->link_config.active_speed = SPEED_UNKNOWN;
tp->link_config.active_duplex = DUPLEX_UNKNOWN;
tp->old_link = -1;
}
static int __devinit tg3_phy_probe(struct tg3 *tp)
{
u32 hw_phy_id_1, hw_phy_id_2;
u32 hw_phy_id, hw_phy_id_masked;
int err;
/* flow control autonegotiation is default behavior */
tg3_flag_set(tp, PAUSE_AUTONEG);
tp->link_config.flowctrl = FLOW_CTRL_TX | FLOW_CTRL_RX;
if (tg3_flag(tp, USE_PHYLIB))
return tg3_phy_init(tp);
/* Reading the PHY ID register can conflict with ASF
* firmware access to the PHY hardware.
*/
err = 0;
if (tg3_flag(tp, ENABLE_ASF) || tg3_flag(tp, ENABLE_APE)) {
hw_phy_id = hw_phy_id_masked = TG3_PHY_ID_INVALID;
} else {
/* Now read the physical PHY_ID from the chip and verify
* that it is sane. If it doesn't look good, we fall back
* to either the hard-coded table based PHY_ID and failing
* that the value found in the eeprom area.
*/
err |= tg3_readphy(tp, MII_PHYSID1, &hw_phy_id_1);
err |= tg3_readphy(tp, MII_PHYSID2, &hw_phy_id_2);
hw_phy_id = (hw_phy_id_1 & 0xffff) << 10;
hw_phy_id |= (hw_phy_id_2 & 0xfc00) << 16;
hw_phy_id |= (hw_phy_id_2 & 0x03ff) << 0;
hw_phy_id_masked = hw_phy_id & TG3_PHY_ID_MASK;
}
if (!err && TG3_KNOWN_PHY_ID(hw_phy_id_masked)) {
tp->phy_id = hw_phy_id;
if (hw_phy_id_masked == TG3_PHY_ID_BCM8002)
tp->phy_flags |= TG3_PHYFLG_PHY_SERDES;
else
tp->phy_flags &= ~TG3_PHYFLG_PHY_SERDES;
} else {
if (tp->phy_id != TG3_PHY_ID_INVALID) {
/* Do nothing, phy ID already set up in
* tg3_get_eeprom_hw_cfg().
*/
} else {
struct subsys_tbl_ent *p;
/* No eeprom signature? Try the hardcoded
* subsys device table.
*/
p = tg3_lookup_by_subsys(tp);
if (!p)
return -ENODEV;
tp->phy_id = p->phy_id;
if (!tp->phy_id ||
tp->phy_id == TG3_PHY_ID_BCM8002)
tp->phy_flags |= TG3_PHYFLG_PHY_SERDES;
}
}
if (!(tp->phy_flags & TG3_PHYFLG_ANY_SERDES) &&
(GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5719 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5720 ||
(tp->pdev->device == TG3PCI_DEVICE_TIGON3_5718 &&
tp->pci_chip_rev_id != CHIPREV_ID_5717_A0) ||
(GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_57765 &&
tp->pci_chip_rev_id != CHIPREV_ID_57765_A0)))
tp->phy_flags |= TG3_PHYFLG_EEE_CAP;
tg3_phy_init_link_config(tp);
if (!(tp->phy_flags & TG3_PHYFLG_ANY_SERDES) &&
!tg3_flag(tp, ENABLE_APE) &&
!tg3_flag(tp, ENABLE_ASF)) {
u32 bmsr, dummy;
tg3_readphy(tp, MII_BMSR, &bmsr);
if (!tg3_readphy(tp, MII_BMSR, &bmsr) &&
(bmsr & BMSR_LSTATUS))
goto skip_phy_reset;
err = tg3_phy_reset(tp);
if (err)
return err;
tg3_phy_set_wirespeed(tp);
if (!tg3_phy_copper_an_config_ok(tp, &dummy)) {
tg3_phy_autoneg_cfg(tp, tp->link_config.advertising,
tp->link_config.flowctrl);
tg3_writephy(tp, MII_BMCR,
BMCR_ANENABLE | BMCR_ANRESTART);
}
}
skip_phy_reset:
if ((tp->phy_id & TG3_PHY_ID_MASK) == TG3_PHY_ID_BCM5401) {
err = tg3_init_5401phy_dsp(tp);
if (err)
return err;
err = tg3_init_5401phy_dsp(tp);
}
return err;
}
static void __devinit tg3_read_vpd(struct tg3 *tp)
{
u8 *vpd_data;
unsigned int block_end, rosize, len;
u32 vpdlen;
int j, i = 0;
vpd_data = (u8 *)tg3_vpd_readblock(tp, &vpdlen);
if (!vpd_data)
goto out_no_vpd;
i = pci_vpd_find_tag(vpd_data, 0, vpdlen, PCI_VPD_LRDT_RO_DATA);
if (i < 0)
goto out_not_found;
rosize = pci_vpd_lrdt_size(&vpd_data[i]);
block_end = i + PCI_VPD_LRDT_TAG_SIZE + rosize;
i += PCI_VPD_LRDT_TAG_SIZE;
if (block_end > vpdlen)
goto out_not_found;
j = pci_vpd_find_info_keyword(vpd_data, i, rosize,
PCI_VPD_RO_KEYWORD_MFR_ID);
if (j > 0) {
len = pci_vpd_info_field_size(&vpd_data[j]);
j += PCI_VPD_INFO_FLD_HDR_SIZE;
if (j + len > block_end || len != 4 ||
memcmp(&vpd_data[j], "1028", 4))
goto partno;
j = pci_vpd_find_info_keyword(vpd_data, i, rosize,
PCI_VPD_RO_KEYWORD_VENDOR0);
if (j < 0)
goto partno;
len = pci_vpd_info_field_size(&vpd_data[j]);
j += PCI_VPD_INFO_FLD_HDR_SIZE;
if (j + len > block_end)
goto partno;
memcpy(tp->fw_ver, &vpd_data[j], len);
strncat(tp->fw_ver, " bc ", vpdlen - len - 1);
}
partno:
i = pci_vpd_find_info_keyword(vpd_data, i, rosize,
PCI_VPD_RO_KEYWORD_PARTNO);
if (i < 0)
goto out_not_found;
len = pci_vpd_info_field_size(&vpd_data[i]);
i += PCI_VPD_INFO_FLD_HDR_SIZE;
if (len > TG3_BPN_SIZE ||
(len + i) > vpdlen)
goto out_not_found;
memcpy(tp->board_part_number, &vpd_data[i], len);
out_not_found:
kfree(vpd_data);
if (tp->board_part_number[0])
return;
out_no_vpd:
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5717) {
if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_5717)
strcpy(tp->board_part_number, "BCM5717");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_5718)
strcpy(tp->board_part_number, "BCM5718");
else
goto nomatch;
} else if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_57780) {
if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57780)
strcpy(tp->board_part_number, "BCM57780");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57760)
strcpy(tp->board_part_number, "BCM57760");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57790)
strcpy(tp->board_part_number, "BCM57790");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57788)
strcpy(tp->board_part_number, "BCM57788");
else
goto nomatch;
} else if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_57765) {
if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57761)
strcpy(tp->board_part_number, "BCM57761");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57765)
strcpy(tp->board_part_number, "BCM57765");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57781)
strcpy(tp->board_part_number, "BCM57781");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57785)
strcpy(tp->board_part_number, "BCM57785");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57791)
strcpy(tp->board_part_number, "BCM57791");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57795)
strcpy(tp->board_part_number, "BCM57795");
else
goto nomatch;
} else if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_57766) {
if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57762)
strcpy(tp->board_part_number, "BCM57762");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57766)
strcpy(tp->board_part_number, "BCM57766");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57782)
strcpy(tp->board_part_number, "BCM57782");
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57786)
strcpy(tp->board_part_number, "BCM57786");
else
goto nomatch;
} else if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5906) {
strcpy(tp->board_part_number, "BCM95906");
} else {
nomatch:
strcpy(tp->board_part_number, "none");
}
}
static int __devinit tg3_fw_img_is_valid(struct tg3 *tp, u32 offset)
{
u32 val;
if (tg3_nvram_read(tp, offset, &val) ||
(val & 0xfc000000) != 0x0c000000 ||
tg3_nvram_read(tp, offset + 4, &val) ||
val != 0)
return 0;
return 1;
}
static void __devinit tg3_read_bc_ver(struct tg3 *tp)
{
u32 val, offset, start, ver_offset;
int i, dst_off;
bool newver = false;
if (tg3_nvram_read(tp, 0xc, &offset) ||
tg3_nvram_read(tp, 0x4, &start))
return;
offset = tg3_nvram_logical_addr(tp, offset);
if (tg3_nvram_read(tp, offset, &val))
return;
if ((val & 0xfc000000) == 0x0c000000) {
if (tg3_nvram_read(tp, offset + 4, &val))
return;
if (val == 0)
newver = true;
}
dst_off = strlen(tp->fw_ver);
if (newver) {
if (TG3_VER_SIZE - dst_off < 16 ||
tg3_nvram_read(tp, offset + 8, &ver_offset))
return;
offset = offset + ver_offset - start;
for (i = 0; i < 16; i += 4) {
__be32 v;
if (tg3_nvram_read_be32(tp, offset + i, &v))
return;
memcpy(tp->fw_ver + dst_off + i, &v, sizeof(v));
}
} else {
u32 major, minor;
if (tg3_nvram_read(tp, TG3_NVM_PTREV_BCVER, &ver_offset))
return;
major = (ver_offset & TG3_NVM_BCVER_MAJMSK) >>
TG3_NVM_BCVER_MAJSFT;
minor = ver_offset & TG3_NVM_BCVER_MINMSK;
snprintf(&tp->fw_ver[dst_off], TG3_VER_SIZE - dst_off,
"v%d.%02d", major, minor);
}
}
static void __devinit tg3_read_hwsb_ver(struct tg3 *tp)
{
u32 val, major, minor;
/* Use native endian representation */
if (tg3_nvram_read(tp, TG3_NVM_HWSB_CFG1, &val))
return;
major = (val & TG3_NVM_HWSB_CFG1_MAJMSK) >>
TG3_NVM_HWSB_CFG1_MAJSFT;
minor = (val & TG3_NVM_HWSB_CFG1_MINMSK) >>
TG3_NVM_HWSB_CFG1_MINSFT;
snprintf(&tp->fw_ver[0], 32, "sb v%d.%02d", major, minor);
}
static void __devinit tg3_read_sb_ver(struct tg3 *tp, u32 val)
{
u32 offset, major, minor, build;
strncat(tp->fw_ver, "sb", TG3_VER_SIZE - strlen(tp->fw_ver) - 1);
if ((val & TG3_EEPROM_SB_FORMAT_MASK) != TG3_EEPROM_SB_FORMAT_1)
return;
switch (val & TG3_EEPROM_SB_REVISION_MASK) {
case TG3_EEPROM_SB_REVISION_0:
offset = TG3_EEPROM_SB_F1R0_EDH_OFF;
break;
case TG3_EEPROM_SB_REVISION_2:
offset = TG3_EEPROM_SB_F1R2_EDH_OFF;
break;
case TG3_EEPROM_SB_REVISION_3:
offset = TG3_EEPROM_SB_F1R3_EDH_OFF;
break;
case TG3_EEPROM_SB_REVISION_4:
offset = TG3_EEPROM_SB_F1R4_EDH_OFF;
break;
case TG3_EEPROM_SB_REVISION_5:
offset = TG3_EEPROM_SB_F1R5_EDH_OFF;
break;
case TG3_EEPROM_SB_REVISION_6:
offset = TG3_EEPROM_SB_F1R6_EDH_OFF;
break;
default:
return;
}
if (tg3_nvram_read(tp, offset, &val))
return;
build = (val & TG3_EEPROM_SB_EDH_BLD_MASK) >>
TG3_EEPROM_SB_EDH_BLD_SHFT;
major = (val & TG3_EEPROM_SB_EDH_MAJ_MASK) >>
TG3_EEPROM_SB_EDH_MAJ_SHFT;
minor = val & TG3_EEPROM_SB_EDH_MIN_MASK;
if (minor > 99 || build > 26)
return;
offset = strlen(tp->fw_ver);
snprintf(&tp->fw_ver[offset], TG3_VER_SIZE - offset,
" v%d.%02d", major, minor);
if (build > 0) {
offset = strlen(tp->fw_ver);
if (offset < TG3_VER_SIZE - 1)
tp->fw_ver[offset] = 'a' + build - 1;
}
}
static void __devinit tg3_read_mgmtfw_ver(struct tg3 *tp)
{
u32 val, offset, start;
int i, vlen;
for (offset = TG3_NVM_DIR_START;
offset < TG3_NVM_DIR_END;
offset += TG3_NVM_DIRENT_SIZE) {
if (tg3_nvram_read(tp, offset, &val))
return;
if ((val >> TG3_NVM_DIRTYPE_SHIFT) == TG3_NVM_DIRTYPE_ASFINI)
break;
}
if (offset == TG3_NVM_DIR_END)
return;
if (!tg3_flag(tp, 5705_PLUS))
start = 0x08000000;
else if (tg3_nvram_read(tp, offset - 4, &start))
return;
if (tg3_nvram_read(tp, offset + 4, &offset) ||
!tg3_fw_img_is_valid(tp, offset) ||
tg3_nvram_read(tp, offset + 8, &val))
return;
offset += val - start;
vlen = strlen(tp->fw_ver);
tp->fw_ver[vlen++] = ',';
tp->fw_ver[vlen++] = ' ';
for (i = 0; i < 4; i++) {
__be32 v;
if (tg3_nvram_read_be32(tp, offset, &v))
return;
offset += sizeof(v);
if (vlen > TG3_VER_SIZE - sizeof(v)) {
memcpy(&tp->fw_ver[vlen], &v, TG3_VER_SIZE - vlen);
break;
}
memcpy(&tp->fw_ver[vlen], &v, sizeof(v));
vlen += sizeof(v);
}
}
static void __devinit tg3_read_dash_ver(struct tg3 *tp)
{
int vlen;
u32 apedata;
char *fwtype;
if (!tg3_flag(tp, ENABLE_APE) || !tg3_flag(tp, ENABLE_ASF))
return;
apedata = tg3_ape_read32(tp, TG3_APE_SEG_SIG);
if (apedata != APE_SEG_SIG_MAGIC)
return;
apedata = tg3_ape_read32(tp, TG3_APE_FW_STATUS);
if (!(apedata & APE_FW_STATUS_READY))
return;
apedata = tg3_ape_read32(tp, TG3_APE_FW_VERSION);
if (tg3_ape_read32(tp, TG3_APE_FW_FEATURES) & TG3_APE_FW_FEATURE_NCSI) {
tg3_flag_set(tp, APE_HAS_NCSI);
fwtype = "NCSI";
} else {
fwtype = "DASH";
}
vlen = strlen(tp->fw_ver);
snprintf(&tp->fw_ver[vlen], TG3_VER_SIZE - vlen, " %s v%d.%d.%d.%d",
fwtype,
(apedata & APE_FW_VERSION_MAJMSK) >> APE_FW_VERSION_MAJSFT,
(apedata & APE_FW_VERSION_MINMSK) >> APE_FW_VERSION_MINSFT,
(apedata & APE_FW_VERSION_REVMSK) >> APE_FW_VERSION_REVSFT,
(apedata & APE_FW_VERSION_BLDMSK));
}
static void __devinit tg3_read_fw_ver(struct tg3 *tp)
{
u32 val;
bool vpd_vers = false;
if (tp->fw_ver[0] != 0)
vpd_vers = true;
if (tg3_flag(tp, NO_NVRAM)) {
strcat(tp->fw_ver, "sb");
return;
}
if (tg3_nvram_read(tp, 0, &val))
return;
if (val == TG3_EEPROM_MAGIC)
tg3_read_bc_ver(tp);
else if ((val & TG3_EEPROM_MAGIC_FW_MSK) == TG3_EEPROM_MAGIC_FW)
tg3_read_sb_ver(tp, val);
else if ((val & TG3_EEPROM_MAGIC_HW_MSK) == TG3_EEPROM_MAGIC_HW)
tg3_read_hwsb_ver(tp);
else
return;
if (vpd_vers)
goto done;
if (tg3_flag(tp, ENABLE_APE)) {
if (tg3_flag(tp, ENABLE_ASF))
tg3_read_dash_ver(tp);
} else if (tg3_flag(tp, ENABLE_ASF)) {
tg3_read_mgmtfw_ver(tp);
}
done:
tp->fw_ver[TG3_VER_SIZE - 1] = 0;
}
static inline u32 tg3_rx_ret_ring_size(struct tg3 *tp)
{
if (tg3_flag(tp, LRG_PROD_RING_CAP))
return TG3_RX_RET_MAX_SIZE_5717;
else if (tg3_flag(tp, JUMBO_CAPABLE) && !tg3_flag(tp, 5780_CLASS))
return TG3_RX_RET_MAX_SIZE_5700;
else
return TG3_RX_RET_MAX_SIZE_5705;
}
static DEFINE_PCI_DEVICE_TABLE(tg3_write_reorder_chipsets) = {
{ PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_FE_GATE_700C) },
{ PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_8131_BRIDGE) },
{ PCI_DEVICE(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8385_0) },
{ },
};
static struct pci_dev * __devinit tg3_find_peer(struct tg3 *tp)
{
struct pci_dev *peer;
unsigned int func, devnr = tp->pdev->devfn & ~7;
for (func = 0; func < 8; func++) {
peer = pci_get_slot(tp->pdev->bus, devnr | func);
if (peer && peer != tp->pdev)
break;
pci_dev_put(peer);
}
/* 5704 can be configured in single-port mode, set peer to
* tp->pdev in that case.
*/
if (!peer) {
peer = tp->pdev;
return peer;
}
/*
* We don't need to keep the refcount elevated; there's no way
* to remove one half of this device without removing the other
*/
pci_dev_put(peer);
return peer;
}
static void __devinit tg3_detect_asic_rev(struct tg3 *tp, u32 misc_ctrl_reg)
{
tp->pci_chip_rev_id = misc_ctrl_reg >> MISC_HOST_CTRL_CHIPREV_SHIFT;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_USE_PROD_ID_REG) {
u32 reg;
/* All devices that use the alternate
* ASIC REV location have a CPMU.
*/
tg3_flag_set(tp, CPMU_PRESENT);
if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_5717 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_5718 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_5719 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_5720)
reg = TG3PCI_GEN2_PRODID_ASICREV;
else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57781 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_57785 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_57761 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_57765 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_57791 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_57795 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_57762 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_57766 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_57782 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_57786)
reg = TG3PCI_GEN15_PRODID_ASICREV;
else
reg = TG3PCI_PRODID_ASICREV;
pci_read_config_dword(tp->pdev, reg, &tp->pci_chip_rev_id);
}
/* Wrong chip ID in 5752 A0. This code can be removed later
* as A0 is not in production.
*/
if (tp->pci_chip_rev_id == CHIPREV_ID_5752_A0_HW)
tp->pci_chip_rev_id = CHIPREV_ID_5752_A0;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5717 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5719 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5720)
tg3_flag_set(tp, 5717_PLUS);
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_57765 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_57766)
tg3_flag_set(tp, 57765_CLASS);
if (tg3_flag(tp, 57765_CLASS) || tg3_flag(tp, 5717_PLUS))
tg3_flag_set(tp, 57765_PLUS);
/* Intentionally exclude ASIC_REV_5906 */
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5755 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5787 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5784 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5761 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5785 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_57780 ||
tg3_flag(tp, 57765_PLUS))
tg3_flag_set(tp, 5755_PLUS);
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5780 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5714)
tg3_flag_set(tp, 5780_CLASS);
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5750 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5752 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5906 ||
tg3_flag(tp, 5755_PLUS) ||
tg3_flag(tp, 5780_CLASS))
tg3_flag_set(tp, 5750_PLUS);
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5705 ||
tg3_flag(tp, 5750_PLUS))
tg3_flag_set(tp, 5705_PLUS);
}
static int __devinit tg3_get_invariants(struct tg3 *tp)
{
u32 misc_ctrl_reg;
u32 pci_state_reg, grc_misc_cfg;
u32 val;
u16 pci_cmd;
int err;
/* Force memory write invalidate off. If we leave it on,
* then on 5700_BX chips we have to enable a workaround.
* The workaround is to set the TG3PCI_DMA_RW_CTRL boundary
* to match the cacheline size. The Broadcom driver have this
* workaround but turns MWI off all the times so never uses
* it. This seems to suggest that the workaround is insufficient.
*/
pci_read_config_word(tp->pdev, PCI_COMMAND, &pci_cmd);
pci_cmd &= ~PCI_COMMAND_INVALIDATE;
pci_write_config_word(tp->pdev, PCI_COMMAND, pci_cmd);
/* Important! -- Make sure register accesses are byteswapped
* correctly. Also, for those chips that require it, make
* sure that indirect register accesses are enabled before
* the first operation.
*/
pci_read_config_dword(tp->pdev, TG3PCI_MISC_HOST_CTRL,
&misc_ctrl_reg);
tp->misc_host_ctrl |= (misc_ctrl_reg &
MISC_HOST_CTRL_CHIPREV);
pci_write_config_dword(tp->pdev, TG3PCI_MISC_HOST_CTRL,
tp->misc_host_ctrl);
tg3_detect_asic_rev(tp, misc_ctrl_reg);
/* If we have 5702/03 A1 or A2 on certain ICH chipsets,
* we need to disable memory and use config. cycles
* only to access all registers. The 5702/03 chips
* can mistakenly decode the special cycles from the
* ICH chipsets as memory write cycles, causing corruption
* of register and memory space. Only certain ICH bridges
* will drive special cycles with non-zero data during the
* address phase which can fall within the 5703's address
* range. This is not an ICH bug as the PCI spec allows
* non-zero address during special cycles. However, only
* these ICH bridges are known to drive non-zero addresses
* during special cycles.
*
* Since special cycles do not cross PCI bridges, we only
* enable this workaround if the 5703 is on the secondary
* bus of these ICH bridges.
*/
if ((tp->pci_chip_rev_id == CHIPREV_ID_5703_A1) ||
(tp->pci_chip_rev_id == CHIPREV_ID_5703_A2)) {
static struct tg3_dev_id {
u32 vendor;
u32 device;
u32 rev;
} ich_chipsets[] = {
{ PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801AA_8,
PCI_ANY_ID },
{ PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801AB_8,
PCI_ANY_ID },
{ PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801BA_11,
0xa },
{ PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801BA_6,
PCI_ANY_ID },
{ },
};
struct tg3_dev_id *pci_id = &ich_chipsets[0];
struct pci_dev *bridge = NULL;
while (pci_id->vendor != 0) {
bridge = pci_get_device(pci_id->vendor, pci_id->device,
bridge);
if (!bridge) {
pci_id++;
continue;
}
if (pci_id->rev != PCI_ANY_ID) {
if (bridge->revision > pci_id->rev)
continue;
}
if (bridge->subordinate &&
(bridge->subordinate->number ==
tp->pdev->bus->number)) {
tg3_flag_set(tp, ICH_WORKAROUND);
pci_dev_put(bridge);
break;
}
}
}
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5701) {
static struct tg3_dev_id {
u32 vendor;
u32 device;
} bridge_chipsets[] = {
{ PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_PXH_0 },
{ PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_PXH_1 },
{ },
};
struct tg3_dev_id *pci_id = &bridge_chipsets[0];
struct pci_dev *bridge = NULL;
while (pci_id->vendor != 0) {
bridge = pci_get_device(pci_id->vendor,
pci_id->device,
bridge);
if (!bridge) {
pci_id++;
continue;
}
if (bridge->subordinate &&
(bridge->subordinate->number <=
tp->pdev->bus->number) &&
(bridge->subordinate->subordinate >=
tp->pdev->bus->number)) {
tg3_flag_set(tp, 5701_DMA_BUG);
pci_dev_put(bridge);
break;
}
}
}
/* The EPB bridge inside 5714, 5715, and 5780 cannot support
* DMA addresses > 40-bit. This bridge may have other additional
* 57xx devices behind it in some 4-port NIC designs for example.
* Any tg3 device found behind the bridge will also need the 40-bit
* DMA workaround.
*/
if (tg3_flag(tp, 5780_CLASS)) {
tg3_flag_set(tp, 40BIT_DMA_BUG);
tp->msi_cap = pci_find_capability(tp->pdev, PCI_CAP_ID_MSI);
} else {
struct pci_dev *bridge = NULL;
do {
bridge = pci_get_device(PCI_VENDOR_ID_SERVERWORKS,
PCI_DEVICE_ID_SERVERWORKS_EPB,
bridge);
if (bridge && bridge->subordinate &&
(bridge->subordinate->number <=
tp->pdev->bus->number) &&
(bridge->subordinate->subordinate >=
tp->pdev->bus->number)) {
tg3_flag_set(tp, 40BIT_DMA_BUG);
pci_dev_put(bridge);
break;
}
} while (bridge);
}
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5704 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5714)
tp->pdev_peer = tg3_find_peer(tp);
/* Determine TSO capabilities */
if (tp->pci_chip_rev_id == CHIPREV_ID_5719_A0)
; /* Do nothing. HW bug. */
else if (tg3_flag(tp, 57765_PLUS))
tg3_flag_set(tp, HW_TSO_3);
else if (tg3_flag(tp, 5755_PLUS) ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5906)
tg3_flag_set(tp, HW_TSO_2);
else if (tg3_flag(tp, 5750_PLUS)) {
tg3_flag_set(tp, HW_TSO_1);
tg3_flag_set(tp, TSO_BUG);
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5750 &&
tp->pci_chip_rev_id >= CHIPREV_ID_5750_C2)
tg3_flag_clear(tp, TSO_BUG);
} else if (GET_ASIC_REV(tp->pci_chip_rev_id) != ASIC_REV_5700 &&
GET_ASIC_REV(tp->pci_chip_rev_id) != ASIC_REV_5701 &&
tp->pci_chip_rev_id != CHIPREV_ID_5705_A0) {
tg3_flag_set(tp, TSO_BUG);
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5705)
tp->fw_needed = FIRMWARE_TG3TSO5;
else
tp->fw_needed = FIRMWARE_TG3TSO;
}
/* Selectively allow TSO based on operating conditions */
if (tg3_flag(tp, HW_TSO_1) ||
tg3_flag(tp, HW_TSO_2) ||
tg3_flag(tp, HW_TSO_3) ||
tp->fw_needed) {
/* For firmware TSO, assume ASF is disabled.
* We'll disable TSO later if we discover ASF
* is enabled in tg3_get_eeprom_hw_cfg().
*/
tg3_flag_set(tp, TSO_CAPABLE);
} else {
tg3_flag_clear(tp, TSO_CAPABLE);
tg3_flag_clear(tp, TSO_BUG);
tp->fw_needed = NULL;
}
if (tp->pci_chip_rev_id == CHIPREV_ID_5701_A0)
tp->fw_needed = FIRMWARE_TG3;
tp->irq_max = 1;
if (tg3_flag(tp, 5750_PLUS)) {
tg3_flag_set(tp, SUPPORT_MSI);
if (GET_CHIP_REV(tp->pci_chip_rev_id) == CHIPREV_5750_AX ||
GET_CHIP_REV(tp->pci_chip_rev_id) == CHIPREV_5750_BX ||
(GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5714 &&
tp->pci_chip_rev_id <= CHIPREV_ID_5714_A2 &&
tp->pdev_peer == tp->pdev))
tg3_flag_clear(tp, SUPPORT_MSI);
if (tg3_flag(tp, 5755_PLUS) ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5906) {
tg3_flag_set(tp, 1SHOT_MSI);
}
if (tg3_flag(tp, 57765_PLUS)) {
tg3_flag_set(tp, SUPPORT_MSIX);
tp->irq_max = TG3_IRQ_MAX_VECS;
tg3_rss_init_dflt_indir_tbl(tp);
}
}
if (tg3_flag(tp, 5755_PLUS))
tg3_flag_set(tp, SHORT_DMA_BUG);
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5719)
tp->dma_limit = TG3_TX_BD_DMA_MAX_4K;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5717 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5719 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5720)
tg3_flag_set(tp, LRG_PROD_RING_CAP);
if (tg3_flag(tp, 57765_PLUS) &&
tp->pci_chip_rev_id != CHIPREV_ID_5719_A0)
tg3_flag_set(tp, USE_JUMBO_BDFLAG);
if (!tg3_flag(tp, 5705_PLUS) ||
tg3_flag(tp, 5780_CLASS) ||
tg3_flag(tp, USE_JUMBO_BDFLAG))
tg3_flag_set(tp, JUMBO_CAPABLE);
pci_read_config_dword(tp->pdev, TG3PCI_PCISTATE,
&pci_state_reg);
if (pci_is_pcie(tp->pdev)) {
u16 lnkctl;
tg3_flag_set(tp, PCI_EXPRESS);
pci_read_config_word(tp->pdev,
pci_pcie_cap(tp->pdev) + PCI_EXP_LNKCTL,
&lnkctl);
if (lnkctl & PCI_EXP_LNKCTL_CLKREQ_EN) {
if (GET_ASIC_REV(tp->pci_chip_rev_id) ==
ASIC_REV_5906) {
tg3_flag_clear(tp, HW_TSO_2);
tg3_flag_clear(tp, TSO_CAPABLE);
}
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5784 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5761 ||
tp->pci_chip_rev_id == CHIPREV_ID_57780_A0 ||
tp->pci_chip_rev_id == CHIPREV_ID_57780_A1)
tg3_flag_set(tp, CLKREQ_BUG);
} else if (tp->pci_chip_rev_id == CHIPREV_ID_5717_A0) {
tg3_flag_set(tp, L1PLLPD_EN);
}
} else if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5785) {
/* BCM5785 devices are effectively PCIe devices, and should
* follow PCIe codepaths, but do not have a PCIe capabilities
* section.
*/
tg3_flag_set(tp, PCI_EXPRESS);
} else if (!tg3_flag(tp, 5705_PLUS) ||
tg3_flag(tp, 5780_CLASS)) {
tp->pcix_cap = pci_find_capability(tp->pdev, PCI_CAP_ID_PCIX);
if (!tp->pcix_cap) {
dev_err(&tp->pdev->dev,
"Cannot find PCI-X capability, aborting\n");
return -EIO;
}
if (!(pci_state_reg & PCISTATE_CONV_PCI_MODE))
tg3_flag_set(tp, PCIX_MODE);
}
/* If we have an AMD 762 or VIA K8T800 chipset, write
* reordering to the mailbox registers done by the host
* controller can cause major troubles. We read back from
* every mailbox register write to force the writes to be
* posted to the chip in order.
*/
if (pci_dev_present(tg3_write_reorder_chipsets) &&
!tg3_flag(tp, PCI_EXPRESS))
tg3_flag_set(tp, MBOX_WRITE_REORDER);
pci_read_config_byte(tp->pdev, PCI_CACHE_LINE_SIZE,
&tp->pci_cacheline_sz);
pci_read_config_byte(tp->pdev, PCI_LATENCY_TIMER,
&tp->pci_lat_timer);
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5703 &&
tp->pci_lat_timer < 64) {
tp->pci_lat_timer = 64;
pci_write_config_byte(tp->pdev, PCI_LATENCY_TIMER,
tp->pci_lat_timer);
}
/* Important! -- It is critical that the PCI-X hw workaround
* situation is decided before the first MMIO register access.
*/
if (GET_CHIP_REV(tp->pci_chip_rev_id) == CHIPREV_5700_BX) {
/* 5700 BX chips need to have their TX producer index
* mailboxes written twice to workaround a bug.
*/
tg3_flag_set(tp, TXD_MBOX_HWBUG);
/* If we are in PCI-X mode, enable register write workaround.
*
* The workaround is to use indirect register accesses
* for all chip writes not to mailbox registers.
*/
if (tg3_flag(tp, PCIX_MODE)) {
u32 pm_reg;
tg3_flag_set(tp, PCIX_TARGET_HWBUG);
/* The chip can have it's power management PCI config
* space registers clobbered due to this bug.
* So explicitly force the chip into D0 here.
*/
pci_read_config_dword(tp->pdev,
tp->pm_cap + PCI_PM_CTRL,
&pm_reg);
pm_reg &= ~PCI_PM_CTRL_STATE_MASK;
pm_reg |= PCI_PM_CTRL_PME_ENABLE | 0 /* D0 */;
pci_write_config_dword(tp->pdev,
tp->pm_cap + PCI_PM_CTRL,
pm_reg);
/* Also, force SERR#/PERR# in PCI command. */
pci_read_config_word(tp->pdev, PCI_COMMAND, &pci_cmd);
pci_cmd |= PCI_COMMAND_PARITY | PCI_COMMAND_SERR;
pci_write_config_word(tp->pdev, PCI_COMMAND, pci_cmd);
}
}
if ((pci_state_reg & PCISTATE_BUS_SPEED_HIGH) != 0)
tg3_flag_set(tp, PCI_HIGH_SPEED);
if ((pci_state_reg & PCISTATE_BUS_32BIT) != 0)
tg3_flag_set(tp, PCI_32BIT);
/* Chip-specific fixup from Broadcom driver */
if ((tp->pci_chip_rev_id == CHIPREV_ID_5704_A0) &&
(!(pci_state_reg & PCISTATE_RETRY_SAME_DMA))) {
pci_state_reg |= PCISTATE_RETRY_SAME_DMA;
pci_write_config_dword(tp->pdev, TG3PCI_PCISTATE, pci_state_reg);
}
/* Default fast path register access methods */
tp->read32 = tg3_read32;
tp->write32 = tg3_write32;
tp->read32_mbox = tg3_read32;
tp->write32_mbox = tg3_write32;
tp->write32_tx_mbox = tg3_write32;
tp->write32_rx_mbox = tg3_write32;
/* Various workaround register access methods */
if (tg3_flag(tp, PCIX_TARGET_HWBUG))
tp->write32 = tg3_write_indirect_reg32;
else if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5701 ||
(tg3_flag(tp, PCI_EXPRESS) &&
tp->pci_chip_rev_id == CHIPREV_ID_5750_A0)) {
/*
* Back to back register writes can cause problems on these
* chips, the workaround is to read back all reg writes
* except those to mailbox regs.
*
* See tg3_write_indirect_reg32().
*/
tp->write32 = tg3_write_flush_reg32;
}
if (tg3_flag(tp, TXD_MBOX_HWBUG) || tg3_flag(tp, MBOX_WRITE_REORDER)) {
tp->write32_tx_mbox = tg3_write32_tx_mbox;
if (tg3_flag(tp, MBOX_WRITE_REORDER))
tp->write32_rx_mbox = tg3_write_flush_reg32;
}
if (tg3_flag(tp, ICH_WORKAROUND)) {
tp->read32 = tg3_read_indirect_reg32;
tp->write32 = tg3_write_indirect_reg32;
tp->read32_mbox = tg3_read_indirect_mbox;
tp->write32_mbox = tg3_write_indirect_mbox;
tp->write32_tx_mbox = tg3_write_indirect_mbox;
tp->write32_rx_mbox = tg3_write_indirect_mbox;
iounmap(tp->regs);
tp->regs = NULL;
pci_read_config_word(tp->pdev, PCI_COMMAND, &pci_cmd);
pci_cmd &= ~PCI_COMMAND_MEMORY;
pci_write_config_word(tp->pdev, PCI_COMMAND, pci_cmd);
}
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5906) {
tp->read32_mbox = tg3_read32_mbox_5906;
tp->write32_mbox = tg3_write32_mbox_5906;
tp->write32_tx_mbox = tg3_write32_mbox_5906;
tp->write32_rx_mbox = tg3_write32_mbox_5906;
}
if (tp->write32 == tg3_write_indirect_reg32 ||
(tg3_flag(tp, PCIX_MODE) &&
(GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5700 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5701)))
tg3_flag_set(tp, SRAM_USE_CONFIG);
/* The memory arbiter has to be enabled in order for SRAM accesses
* to succeed. Normally on powerup the tg3 chip firmware will make
* sure it is enabled, but other entities such as system netboot
* code might disable it.
*/
val = tr32(MEMARB_MODE);
tw32(MEMARB_MODE, val | MEMARB_MODE_ENABLE);
tp->pci_fn = PCI_FUNC(tp->pdev->devfn) & 3;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5704 ||
tg3_flag(tp, 5780_CLASS)) {
if (tg3_flag(tp, PCIX_MODE)) {
pci_read_config_dword(tp->pdev,
tp->pcix_cap + PCI_X_STATUS,
&val);
tp->pci_fn = val & 0x7;
}
} else if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5717) {
tg3_read_mem(tp, NIC_SRAM_CPMU_STATUS, &val);
if ((val & NIC_SRAM_CPMUSTAT_SIG_MSK) ==
NIC_SRAM_CPMUSTAT_SIG) {
tp->pci_fn = val & TG3_CPMU_STATUS_FMSK_5717;
tp->pci_fn = tp->pci_fn ? 1 : 0;
}
} else if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5719 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5720) {
tg3_read_mem(tp, NIC_SRAM_CPMU_STATUS, &val);
if ((val & NIC_SRAM_CPMUSTAT_SIG_MSK) ==
NIC_SRAM_CPMUSTAT_SIG) {
tp->pci_fn = (val & TG3_CPMU_STATUS_FMSK_5719) >>
TG3_CPMU_STATUS_FSHFT_5719;
}
}
/* Get eeprom hw config before calling tg3_set_power_state().
* In particular, the TG3_FLAG_IS_NIC flag must be
* determined before calling tg3_set_power_state() so that
* we know whether or not to switch out of Vaux power.
* When the flag is set, it means that GPIO1 is used for eeprom
* write protect and also implies that it is a LOM where GPIOs
* are not used to switch power.
*/
tg3_get_eeprom_hw_cfg(tp);
if (tp->fw_needed && tg3_flag(tp, ENABLE_ASF)) {
tg3_flag_clear(tp, TSO_CAPABLE);
tg3_flag_clear(tp, TSO_BUG);
tp->fw_needed = NULL;
}
if (tg3_flag(tp, ENABLE_APE)) {
/* Allow reads and writes to the
* APE register and memory space.
*/
pci_state_reg |= PCISTATE_ALLOW_APE_CTLSPC_WR |
PCISTATE_ALLOW_APE_SHMEM_WR |
PCISTATE_ALLOW_APE_PSPACE_WR;
pci_write_config_dword(tp->pdev, TG3PCI_PCISTATE,
pci_state_reg);
tg3_ape_lock_init(tp);
}
/* Set up tp->grc_local_ctrl before calling
* tg3_pwrsrc_switch_to_vmain(). GPIO1 driven high
* will bring 5700's external PHY out of reset.
* It is also used as eeprom write protect on LOMs.
*/
tp->grc_local_ctrl = GRC_LCLCTRL_INT_ON_ATTN | GRC_LCLCTRL_AUTO_SEEPROM;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5700 ||
tg3_flag(tp, EEPROM_WRITE_PROT))
tp->grc_local_ctrl |= (GRC_LCLCTRL_GPIO_OE1 |
GRC_LCLCTRL_GPIO_OUTPUT1);
/* Unused GPIO3 must be driven as output on 5752 because there
* are no pull-up resistors on unused GPIO pins.
*/
else if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5752)
tp->grc_local_ctrl |= GRC_LCLCTRL_GPIO_OE3;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5755 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_57780 ||
tg3_flag(tp, 57765_CLASS))
tp->grc_local_ctrl |= GRC_LCLCTRL_GPIO_UART_SEL;
if (tp->pdev->device == PCI_DEVICE_ID_TIGON3_5761 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_5761S) {
/* Turn off the debug UART. */
tp->grc_local_ctrl |= GRC_LCLCTRL_GPIO_UART_SEL;
if (tg3_flag(tp, IS_NIC))
/* Keep VMain power. */
tp->grc_local_ctrl |= GRC_LCLCTRL_GPIO_OE0 |
GRC_LCLCTRL_GPIO_OUTPUT0;
}
/* Switch out of Vaux if it is a NIC */
tg3_pwrsrc_switch_to_vmain(tp);
/* Derive initial jumbo mode from MTU assigned in
* ether_setup() via the alloc_etherdev() call
*/
if (tp->dev->mtu > ETH_DATA_LEN && !tg3_flag(tp, 5780_CLASS))
tg3_flag_set(tp, JUMBO_RING_ENABLE);
/* Determine WakeOnLan speed to use. */
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5700 ||
tp->pci_chip_rev_id == CHIPREV_ID_5701_A0 ||
tp->pci_chip_rev_id == CHIPREV_ID_5701_B0 ||
tp->pci_chip_rev_id == CHIPREV_ID_5701_B2) {
tg3_flag_clear(tp, WOL_SPEED_100MB);
} else {
tg3_flag_set(tp, WOL_SPEED_100MB);
}
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5906)
tp->phy_flags |= TG3_PHYFLG_IS_FET;
/* A few boards don't want Ethernet@WireSpeed phy feature */
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5700 ||
(GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5705 &&
(tp->pci_chip_rev_id != CHIPREV_ID_5705_A0) &&
(tp->pci_chip_rev_id != CHIPREV_ID_5705_A1)) ||
(tp->phy_flags & TG3_PHYFLG_IS_FET) ||
(tp->phy_flags & TG3_PHYFLG_ANY_SERDES))
tp->phy_flags |= TG3_PHYFLG_NO_ETH_WIRE_SPEED;
if (GET_CHIP_REV(tp->pci_chip_rev_id) == CHIPREV_5703_AX ||
GET_CHIP_REV(tp->pci_chip_rev_id) == CHIPREV_5704_AX)
tp->phy_flags |= TG3_PHYFLG_ADC_BUG;
if (tp->pci_chip_rev_id == CHIPREV_ID_5704_A0)
tp->phy_flags |= TG3_PHYFLG_5704_A0_BUG;
if (tg3_flag(tp, 5705_PLUS) &&
!(tp->phy_flags & TG3_PHYFLG_IS_FET) &&
GET_ASIC_REV(tp->pci_chip_rev_id) != ASIC_REV_5785 &&
GET_ASIC_REV(tp->pci_chip_rev_id) != ASIC_REV_57780 &&
!tg3_flag(tp, 57765_PLUS)) {
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5755 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5787 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5784 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5761) {
if (tp->pdev->device != PCI_DEVICE_ID_TIGON3_5756 &&
tp->pdev->device != PCI_DEVICE_ID_TIGON3_5722)
tp->phy_flags |= TG3_PHYFLG_JITTER_BUG;
if (tp->pdev->device == PCI_DEVICE_ID_TIGON3_5755M)
tp->phy_flags |= TG3_PHYFLG_ADJUST_TRIM;
} else
tp->phy_flags |= TG3_PHYFLG_BER_BUG;
}
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5784 &&
GET_CHIP_REV(tp->pci_chip_rev_id) != CHIPREV_5784_AX) {
tp->phy_otp = tg3_read_otp_phycfg(tp);
if (tp->phy_otp == 0)
tp->phy_otp = TG3_OTP_DEFAULT;
}
if (tg3_flag(tp, CPMU_PRESENT))
tp->mi_mode = MAC_MI_MODE_500KHZ_CONST;
else
tp->mi_mode = MAC_MI_MODE_BASE;
tp->coalesce_mode = 0;
if (GET_CHIP_REV(tp->pci_chip_rev_id) != CHIPREV_5700_AX &&
GET_CHIP_REV(tp->pci_chip_rev_id) != CHIPREV_5700_BX)
tp->coalesce_mode |= HOSTCC_MODE_32BYTE;
/* Set these bits to enable statistics workaround. */
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5717 ||
tp->pci_chip_rev_id == CHIPREV_ID_5719_A0 ||
tp->pci_chip_rev_id == CHIPREV_ID_5720_A0) {
tp->coalesce_mode |= HOSTCC_MODE_ATTN;
tp->grc_mode |= GRC_MODE_IRQ_ON_FLOW_ATTN;
}
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5785 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_57780)
tg3_flag_set(tp, USE_PHYLIB);
err = tg3_mdio_init(tp);
if (err)
return err;
/* Initialize data/descriptor byte/word swapping. */
val = tr32(GRC_MODE);
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5720)
val &= (GRC_MODE_BYTE_SWAP_B2HRX_DATA |
GRC_MODE_WORD_SWAP_B2HRX_DATA |
GRC_MODE_B2HRX_ENABLE |
GRC_MODE_HTX2B_ENABLE |
GRC_MODE_HOST_STACKUP);
else
val &= GRC_MODE_HOST_STACKUP;
tw32(GRC_MODE, val | tp->grc_mode);
tg3_switch_clocks(tp);
/* Clear this out for sanity. */
tw32(TG3PCI_MEM_WIN_BASE_ADDR, 0);
pci_read_config_dword(tp->pdev, TG3PCI_PCISTATE,
&pci_state_reg);
if ((pci_state_reg & PCISTATE_CONV_PCI_MODE) == 0 &&
!tg3_flag(tp, PCIX_TARGET_HWBUG)) {
u32 chiprevid = GET_CHIP_REV_ID(tp->misc_host_ctrl);
if (chiprevid == CHIPREV_ID_5701_A0 ||
chiprevid == CHIPREV_ID_5701_B0 ||
chiprevid == CHIPREV_ID_5701_B2 ||
chiprevid == CHIPREV_ID_5701_B5) {
void __iomem *sram_base;
/* Write some dummy words into the SRAM status block
* area, see if it reads back correctly. If the return
* value is bad, force enable the PCIX workaround.
*/
sram_base = tp->regs + NIC_SRAM_WIN_BASE + NIC_SRAM_STATS_BLK;
writel(0x00000000, sram_base);
writel(0x00000000, sram_base + 4);
writel(0xffffffff, sram_base + 4);
if (readl(sram_base) != 0x00000000)
tg3_flag_set(tp, PCIX_TARGET_HWBUG);
}
}
udelay(50);
tg3_nvram_init(tp);
grc_misc_cfg = tr32(GRC_MISC_CFG);
grc_misc_cfg &= GRC_MISC_CFG_BOARD_ID_MASK;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5705 &&
(grc_misc_cfg == GRC_MISC_CFG_BOARD_ID_5788 ||
grc_misc_cfg == GRC_MISC_CFG_BOARD_ID_5788M))
tg3_flag_set(tp, IS_5788);
if (!tg3_flag(tp, IS_5788) &&
GET_ASIC_REV(tp->pci_chip_rev_id) != ASIC_REV_5700)
tg3_flag_set(tp, TAGGED_STATUS);
if (tg3_flag(tp, TAGGED_STATUS)) {
tp->coalesce_mode |= (HOSTCC_MODE_CLRTICK_RXBD |
HOSTCC_MODE_CLRTICK_TXBD);
tp->misc_host_ctrl |= MISC_HOST_CTRL_TAGGED_STATUS;
pci_write_config_dword(tp->pdev, TG3PCI_MISC_HOST_CTRL,
tp->misc_host_ctrl);
}
/* Preserve the APE MAC_MODE bits */
if (tg3_flag(tp, ENABLE_APE))
tp->mac_mode = MAC_MODE_APE_TX_EN | MAC_MODE_APE_RX_EN;
else
tp->mac_mode = 0;
/* these are limited to 10/100 only */
if ((GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5703 &&
(grc_misc_cfg == 0x8000 || grc_misc_cfg == 0x4000)) ||
(GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5705 &&
tp->pdev->vendor == PCI_VENDOR_ID_BROADCOM &&
(tp->pdev->device == PCI_DEVICE_ID_TIGON3_5901 ||
tp->pdev->device == PCI_DEVICE_ID_TIGON3_5901_2 ||
tp->pdev->device == PCI_DEVICE_ID_TIGON3_5705F)) ||
(tp->pdev->vendor == PCI_VENDOR_ID_BROADCOM &&
(tp->pdev->device == PCI_DEVICE_ID_TIGON3_5751F ||
tp->pdev->device == PCI_DEVICE_ID_TIGON3_5753F ||
tp->pdev->device == PCI_DEVICE_ID_TIGON3_5787F)) ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_57790 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_57791 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_57795 ||
(tp->phy_flags & TG3_PHYFLG_IS_FET))
tp->phy_flags |= TG3_PHYFLG_10_100_ONLY;
err = tg3_phy_probe(tp);
if (err) {
dev_err(&tp->pdev->dev, "phy probe failed, err %d\n", err);
/* ... but do not return immediately ... */
tg3_mdio_fini(tp);
}
tg3_read_vpd(tp);
tg3_read_fw_ver(tp);
if (tp->phy_flags & TG3_PHYFLG_PHY_SERDES) {
tp->phy_flags &= ~TG3_PHYFLG_USE_MI_INTERRUPT;
} else {
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5700)
tp->phy_flags |= TG3_PHYFLG_USE_MI_INTERRUPT;
else
tp->phy_flags &= ~TG3_PHYFLG_USE_MI_INTERRUPT;
}
/* 5700 {AX,BX} chips have a broken status block link
* change bit implementation, so we must use the
* status register in those cases.
*/
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5700)
tg3_flag_set(tp, USE_LINKCHG_REG);
else
tg3_flag_clear(tp, USE_LINKCHG_REG);
/* The led_ctrl is set during tg3_phy_probe, here we might
* have to force the link status polling mechanism based
* upon subsystem IDs.
*/
if (tp->pdev->subsystem_vendor == PCI_VENDOR_ID_DELL &&
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5701 &&
!(tp->phy_flags & TG3_PHYFLG_PHY_SERDES)) {
tp->phy_flags |= TG3_PHYFLG_USE_MI_INTERRUPT;
tg3_flag_set(tp, USE_LINKCHG_REG);
}
/* For all SERDES we poll the MAC status register. */
if (tp->phy_flags & TG3_PHYFLG_PHY_SERDES)
tg3_flag_set(tp, POLL_SERDES);
else
tg3_flag_clear(tp, POLL_SERDES);
tp->rx_offset = NET_SKB_PAD + NET_IP_ALIGN;
tp->rx_copy_thresh = TG3_RX_COPY_THRESHOLD;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5701 &&
tg3_flag(tp, PCIX_MODE)) {
tp->rx_offset = NET_SKB_PAD;
#ifndef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
tp->rx_copy_thresh = ~(u16)0;
#endif
}
tp->rx_std_ring_mask = TG3_RX_STD_RING_SIZE(tp) - 1;
tp->rx_jmb_ring_mask = TG3_RX_JMB_RING_SIZE(tp) - 1;
tp->rx_ret_ring_mask = tg3_rx_ret_ring_size(tp) - 1;
tp->rx_std_max_post = tp->rx_std_ring_mask + 1;
/* Increment the rx prod index on the rx std ring by at most
* 8 for these chips to workaround hw errata.
*/
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5750 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5752 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5755)
tp->rx_std_max_post = 8;
if (tg3_flag(tp, ASPM_WORKAROUND))
tp->pwrmgmt_thresh = tr32(PCIE_PWR_MGMT_THRESH) &
PCIE_PWR_MGMT_L1_THRESH_MSK;
return err;
}
#ifdef CONFIG_SPARC
static int __devinit tg3_get_macaddr_sparc(struct tg3 *tp)
{
struct net_device *dev = tp->dev;
struct pci_dev *pdev = tp->pdev;
struct device_node *dp = pci_device_to_OF_node(pdev);
const unsigned char *addr;
int len;
addr = of_get_property(dp, "local-mac-address", &len);
if (addr && len == 6) {
memcpy(dev->dev_addr, addr, 6);
memcpy(dev->perm_addr, dev->dev_addr, 6);
return 0;
}
return -ENODEV;
}
static int __devinit tg3_get_default_macaddr_sparc(struct tg3 *tp)
{
struct net_device *dev = tp->dev;
memcpy(dev->dev_addr, idprom->id_ethaddr, 6);
memcpy(dev->perm_addr, idprom->id_ethaddr, 6);
return 0;
}
#endif
static int __devinit tg3_get_device_address(struct tg3 *tp)
{
struct net_device *dev = tp->dev;
u32 hi, lo, mac_offset;
int addr_ok = 0;
#ifdef CONFIG_SPARC
if (!tg3_get_macaddr_sparc(tp))
return 0;
#endif
mac_offset = 0x7c;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5704 ||
tg3_flag(tp, 5780_CLASS)) {
if (tr32(TG3PCI_DUAL_MAC_CTRL) & DUAL_MAC_CTRL_ID)
mac_offset = 0xcc;
if (tg3_nvram_lock(tp))
tw32_f(NVRAM_CMD, NVRAM_CMD_RESET);
else
tg3_nvram_unlock(tp);
} else if (tg3_flag(tp, 5717_PLUS)) {
if (tp->pci_fn & 1)
mac_offset = 0xcc;
if (tp->pci_fn > 1)
mac_offset += 0x18c;
} else if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5906)
mac_offset = 0x10;
/* First try to get it from MAC address mailbox. */
tg3_read_mem(tp, NIC_SRAM_MAC_ADDR_HIGH_MBOX, &hi);
if ((hi >> 16) == 0x484b) {
dev->dev_addr[0] = (hi >> 8) & 0xff;
dev->dev_addr[1] = (hi >> 0) & 0xff;
tg3_read_mem(tp, NIC_SRAM_MAC_ADDR_LOW_MBOX, &lo);
dev->dev_addr[2] = (lo >> 24) & 0xff;
dev->dev_addr[3] = (lo >> 16) & 0xff;
dev->dev_addr[4] = (lo >> 8) & 0xff;
dev->dev_addr[5] = (lo >> 0) & 0xff;
/* Some old bootcode may report a 0 MAC address in SRAM */
addr_ok = is_valid_ether_addr(&dev->dev_addr[0]);
}
if (!addr_ok) {
/* Next, try NVRAM. */
if (!tg3_flag(tp, NO_NVRAM) &&
!tg3_nvram_read_be32(tp, mac_offset + 0, &hi) &&
!tg3_nvram_read_be32(tp, mac_offset + 4, &lo)) {
memcpy(&dev->dev_addr[0], ((char *)&hi) + 2, 2);
memcpy(&dev->dev_addr[2], (char *)&lo, sizeof(lo));
}
/* Finally just fetch it out of the MAC control regs. */
else {
hi = tr32(MAC_ADDR_0_HIGH);
lo = tr32(MAC_ADDR_0_LOW);
dev->dev_addr[5] = lo & 0xff;
dev->dev_addr[4] = (lo >> 8) & 0xff;
dev->dev_addr[3] = (lo >> 16) & 0xff;
dev->dev_addr[2] = (lo >> 24) & 0xff;
dev->dev_addr[1] = hi & 0xff;
dev->dev_addr[0] = (hi >> 8) & 0xff;
}
}
if (!is_valid_ether_addr(&dev->dev_addr[0])) {
#ifdef CONFIG_SPARC
if (!tg3_get_default_macaddr_sparc(tp))
return 0;
#endif
return -EINVAL;
}
memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len);
return 0;
}
#define BOUNDARY_SINGLE_CACHELINE 1
#define BOUNDARY_MULTI_CACHELINE 2
static u32 __devinit tg3_calc_dma_bndry(struct tg3 *tp, u32 val)
{
int cacheline_size;
u8 byte;
int goal;
pci_read_config_byte(tp->pdev, PCI_CACHE_LINE_SIZE, &byte);
if (byte == 0)
cacheline_size = 1024;
else
cacheline_size = (int) byte * 4;
/* On 5703 and later chips, the boundary bits have no
* effect.
*/
if (GET_ASIC_REV(tp->pci_chip_rev_id) != ASIC_REV_5700 &&
GET_ASIC_REV(tp->pci_chip_rev_id) != ASIC_REV_5701 &&
!tg3_flag(tp, PCI_EXPRESS))
goto out;
#if defined(CONFIG_PPC64) || defined(CONFIG_IA64) || defined(CONFIG_PARISC)
goal = BOUNDARY_MULTI_CACHELINE;
#else
#if defined(CONFIG_SPARC64) || defined(CONFIG_ALPHA)
goal = BOUNDARY_SINGLE_CACHELINE;
#else
goal = 0;
#endif
#endif
if (tg3_flag(tp, 57765_PLUS)) {
val = goal ? 0 : DMA_RWCTRL_DIS_CACHE_ALIGNMENT;
goto out;
}
if (!goal)
goto out;
/* PCI controllers on most RISC systems tend to disconnect
* when a device tries to burst across a cache-line boundary.
* Therefore, letting tg3 do so just wastes PCI bandwidth.
*
* Unfortunately, for PCI-E there are only limited
* write-side controls for this, and thus for reads
* we will still get the disconnects. We'll also waste
* these PCI cycles for both read and write for chips
* other than 5700 and 5701 which do not implement the
* boundary bits.
*/
if (tg3_flag(tp, PCIX_MODE) && !tg3_flag(tp, PCI_EXPRESS)) {
switch (cacheline_size) {
case 16:
case 32:
case 64:
case 128:
if (goal == BOUNDARY_SINGLE_CACHELINE) {
val |= (DMA_RWCTRL_READ_BNDRY_128_PCIX |
DMA_RWCTRL_WRITE_BNDRY_128_PCIX);
} else {
val |= (DMA_RWCTRL_READ_BNDRY_384_PCIX |
DMA_RWCTRL_WRITE_BNDRY_384_PCIX);
}
break;
case 256:
val |= (DMA_RWCTRL_READ_BNDRY_256_PCIX |
DMA_RWCTRL_WRITE_BNDRY_256_PCIX);
break;
default:
val |= (DMA_RWCTRL_READ_BNDRY_384_PCIX |
DMA_RWCTRL_WRITE_BNDRY_384_PCIX);
break;
}
} else if (tg3_flag(tp, PCI_EXPRESS)) {
switch (cacheline_size) {
case 16:
case 32:
case 64:
if (goal == BOUNDARY_SINGLE_CACHELINE) {
val &= ~DMA_RWCTRL_WRITE_BNDRY_DISAB_PCIE;
val |= DMA_RWCTRL_WRITE_BNDRY_64_PCIE;
break;
}
/* fallthrough */
case 128:
default:
val &= ~DMA_RWCTRL_WRITE_BNDRY_DISAB_PCIE;
val |= DMA_RWCTRL_WRITE_BNDRY_128_PCIE;
break;
}
} else {
switch (cacheline_size) {
case 16:
if (goal == BOUNDARY_SINGLE_CACHELINE) {
val |= (DMA_RWCTRL_READ_BNDRY_16 |
DMA_RWCTRL_WRITE_BNDRY_16);
break;
}
/* fallthrough */
case 32:
if (goal == BOUNDARY_SINGLE_CACHELINE) {
val |= (DMA_RWCTRL_READ_BNDRY_32 |
DMA_RWCTRL_WRITE_BNDRY_32);
break;
}
/* fallthrough */
case 64:
if (goal == BOUNDARY_SINGLE_CACHELINE) {
val |= (DMA_RWCTRL_READ_BNDRY_64 |
DMA_RWCTRL_WRITE_BNDRY_64);
break;
}
/* fallthrough */
case 128:
if (goal == BOUNDARY_SINGLE_CACHELINE) {
val |= (DMA_RWCTRL_READ_BNDRY_128 |
DMA_RWCTRL_WRITE_BNDRY_128);
break;
}
/* fallthrough */
case 256:
val |= (DMA_RWCTRL_READ_BNDRY_256 |
DMA_RWCTRL_WRITE_BNDRY_256);
break;
case 512:
val |= (DMA_RWCTRL_READ_BNDRY_512 |
DMA_RWCTRL_WRITE_BNDRY_512);
break;
case 1024:
default:
val |= (DMA_RWCTRL_READ_BNDRY_1024 |
DMA_RWCTRL_WRITE_BNDRY_1024);
break;
}
}
out:
return val;
}
static int __devinit tg3_do_test_dma(struct tg3 *tp, u32 *buf, dma_addr_t buf_dma, int size, int to_device)
{
struct tg3_internal_buffer_desc test_desc;
u32 sram_dma_descs;
int i, ret;
sram_dma_descs = NIC_SRAM_DMA_DESC_POOL_BASE;
tw32(FTQ_RCVBD_COMP_FIFO_ENQDEQ, 0);
tw32(FTQ_RCVDATA_COMP_FIFO_ENQDEQ, 0);
tw32(RDMAC_STATUS, 0);
tw32(WDMAC_STATUS, 0);
tw32(BUFMGR_MODE, 0);
tw32(FTQ_RESET, 0);
test_desc.addr_hi = ((u64) buf_dma) >> 32;
test_desc.addr_lo = buf_dma & 0xffffffff;
test_desc.nic_mbuf = 0x00002100;
test_desc.len = size;
/*
* HP ZX1 was seeing test failures for 5701 cards running at 33Mhz
* the *second* time the tg3 driver was getting loaded after an
* initial scan.
*
* Broadcom tells me:
* ...the DMA engine is connected to the GRC block and a DMA
* reset may affect the GRC block in some unpredictable way...
* The behavior of resets to individual blocks has not been tested.
*
* Broadcom noted the GRC reset will also reset all sub-components.
*/
if (to_device) {
test_desc.cqid_sqid = (13 << 8) | 2;
tw32_f(RDMAC_MODE, RDMAC_MODE_ENABLE);
udelay(40);
} else {
test_desc.cqid_sqid = (16 << 8) | 7;
tw32_f(WDMAC_MODE, WDMAC_MODE_ENABLE);
udelay(40);
}
test_desc.flags = 0x00000005;
for (i = 0; i < (sizeof(test_desc) / sizeof(u32)); i++) {
u32 val;
val = *(((u32 *)&test_desc) + i);
pci_write_config_dword(tp->pdev, TG3PCI_MEM_WIN_BASE_ADDR,
sram_dma_descs + (i * sizeof(u32)));
pci_write_config_dword(tp->pdev, TG3PCI_MEM_WIN_DATA, val);
}
pci_write_config_dword(tp->pdev, TG3PCI_MEM_WIN_BASE_ADDR, 0);
if (to_device)
tw32(FTQ_DMA_HIGH_READ_FIFO_ENQDEQ, sram_dma_descs);
else
tw32(FTQ_DMA_HIGH_WRITE_FIFO_ENQDEQ, sram_dma_descs);
ret = -ENODEV;
for (i = 0; i < 40; i++) {
u32 val;
if (to_device)
val = tr32(FTQ_RCVBD_COMP_FIFO_ENQDEQ);
else
val = tr32(FTQ_RCVDATA_COMP_FIFO_ENQDEQ);
if ((val & 0xffff) == sram_dma_descs) {
ret = 0;
break;
}
udelay(100);
}
return ret;
}
#define TEST_BUFFER_SIZE 0x2000
static DEFINE_PCI_DEVICE_TABLE(tg3_dma_wait_state_chipsets) = {
{ PCI_DEVICE(PCI_VENDOR_ID_APPLE, PCI_DEVICE_ID_APPLE_UNI_N_PCI15) },
{ },
};
static int __devinit tg3_test_dma(struct tg3 *tp)
{
dma_addr_t buf_dma;
u32 *buf, saved_dma_rwctrl;
int ret = 0;
buf = dma_alloc_coherent(&tp->pdev->dev, TEST_BUFFER_SIZE,
&buf_dma, GFP_KERNEL);
if (!buf) {
ret = -ENOMEM;
goto out_nofree;
}
tp->dma_rwctrl = ((0x7 << DMA_RWCTRL_PCI_WRITE_CMD_SHIFT) |
(0x6 << DMA_RWCTRL_PCI_READ_CMD_SHIFT));
tp->dma_rwctrl = tg3_calc_dma_bndry(tp, tp->dma_rwctrl);
if (tg3_flag(tp, 57765_PLUS))
goto out;
if (tg3_flag(tp, PCI_EXPRESS)) {
/* DMA read watermark not used on PCIE */
tp->dma_rwctrl |= 0x00180000;
} else if (!tg3_flag(tp, PCIX_MODE)) {
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5705 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5750)
tp->dma_rwctrl |= 0x003f0000;
else
tp->dma_rwctrl |= 0x003f000f;
} else {
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5703 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5704) {
u32 ccval = (tr32(TG3PCI_CLOCK_CTRL) & 0x1f);
u32 read_water = 0x7;
/* If the 5704 is behind the EPB bridge, we can
* do the less restrictive ONE_DMA workaround for
* better performance.
*/
if (tg3_flag(tp, 40BIT_DMA_BUG) &&
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5704)
tp->dma_rwctrl |= 0x8000;
else if (ccval == 0x6 || ccval == 0x7)
tp->dma_rwctrl |= DMA_RWCTRL_ONE_DMA;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5703)
read_water = 4;
/* Set bit 23 to enable PCIX hw bug fix */
tp->dma_rwctrl |=
(read_water << DMA_RWCTRL_READ_WATER_SHIFT) |
(0x3 << DMA_RWCTRL_WRITE_WATER_SHIFT) |
(1 << 23);
} else if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5780) {
/* 5780 always in PCIX mode */
tp->dma_rwctrl |= 0x00144000;
} else if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5714) {
/* 5714 always in PCIX mode */
tp->dma_rwctrl |= 0x00148000;
} else {
tp->dma_rwctrl |= 0x001b000f;
}
}
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5703 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5704)
tp->dma_rwctrl &= 0xfffffff0;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5700 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5701) {
/* Remove this if it causes problems for some boards. */
tp->dma_rwctrl |= DMA_RWCTRL_USE_MEM_READ_MULT;
/* On 5700/5701 chips, we need to set this bit.
* Otherwise the chip will issue cacheline transactions
* to streamable DMA memory with not all the byte
* enables turned on. This is an error on several
* RISC PCI controllers, in particular sparc64.
*
* On 5703/5704 chips, this bit has been reassigned
* a different meaning. In particular, it is used
* on those chips to enable a PCI-X workaround.
*/
tp->dma_rwctrl |= DMA_RWCTRL_ASSERT_ALL_BE;
}
tw32(TG3PCI_DMA_RW_CTRL, tp->dma_rwctrl);
#if 0
/* Unneeded, already done by tg3_get_invariants. */
tg3_switch_clocks(tp);
#endif
if (GET_ASIC_REV(tp->pci_chip_rev_id) != ASIC_REV_5700 &&
GET_ASIC_REV(tp->pci_chip_rev_id) != ASIC_REV_5701)
goto out;
/* It is best to perform DMA test with maximum write burst size
* to expose the 5700/5701 write DMA bug.
*/
saved_dma_rwctrl = tp->dma_rwctrl;
tp->dma_rwctrl &= ~DMA_RWCTRL_WRITE_BNDRY_MASK;
tw32(TG3PCI_DMA_RW_CTRL, tp->dma_rwctrl);
while (1) {
u32 *p = buf, i;
for (i = 0; i < TEST_BUFFER_SIZE / sizeof(u32); i++)
p[i] = i;
/* Send the buffer to the chip. */
ret = tg3_do_test_dma(tp, buf, buf_dma, TEST_BUFFER_SIZE, 1);
if (ret) {
dev_err(&tp->pdev->dev,
"%s: Buffer write failed. err = %d\n",
__func__, ret);
break;
}
#if 0
/* validate data reached card RAM correctly. */
for (i = 0; i < TEST_BUFFER_SIZE / sizeof(u32); i++) {
u32 val;
tg3_read_mem(tp, 0x2100 + (i*4), &val);
if (le32_to_cpu(val) != p[i]) {
dev_err(&tp->pdev->dev,
"%s: Buffer corrupted on device! "
"(%d != %d)\n", __func__, val, i);
/* ret = -ENODEV here? */
}
p[i] = 0;
}
#endif
/* Now read it back. */
ret = tg3_do_test_dma(tp, buf, buf_dma, TEST_BUFFER_SIZE, 0);
if (ret) {
dev_err(&tp->pdev->dev, "%s: Buffer read failed. "
"err = %d\n", __func__, ret);
break;
}
/* Verify it. */
for (i = 0; i < TEST_BUFFER_SIZE / sizeof(u32); i++) {
if (p[i] == i)
continue;
if ((tp->dma_rwctrl & DMA_RWCTRL_WRITE_BNDRY_MASK) !=
DMA_RWCTRL_WRITE_BNDRY_16) {
tp->dma_rwctrl &= ~DMA_RWCTRL_WRITE_BNDRY_MASK;
tp->dma_rwctrl |= DMA_RWCTRL_WRITE_BNDRY_16;
tw32(TG3PCI_DMA_RW_CTRL, tp->dma_rwctrl);
break;
} else {
dev_err(&tp->pdev->dev,
"%s: Buffer corrupted on read back! "
"(%d != %d)\n", __func__, p[i], i);
ret = -ENODEV;
goto out;
}
}
if (i == (TEST_BUFFER_SIZE / sizeof(u32))) {
/* Success. */
ret = 0;
break;
}
}
if ((tp->dma_rwctrl & DMA_RWCTRL_WRITE_BNDRY_MASK) !=
DMA_RWCTRL_WRITE_BNDRY_16) {
/* DMA test passed without adjusting DMA boundary,
* now look for chipsets that are known to expose the
* DMA bug without failing the test.
*/
if (pci_dev_present(tg3_dma_wait_state_chipsets)) {
tp->dma_rwctrl &= ~DMA_RWCTRL_WRITE_BNDRY_MASK;
tp->dma_rwctrl |= DMA_RWCTRL_WRITE_BNDRY_16;
} else {
/* Safe to use the calculated DMA boundary. */
tp->dma_rwctrl = saved_dma_rwctrl;
}
tw32(TG3PCI_DMA_RW_CTRL, tp->dma_rwctrl);
}
out:
dma_free_coherent(&tp->pdev->dev, TEST_BUFFER_SIZE, buf, buf_dma);
out_nofree:
return ret;
}
static void __devinit tg3_init_bufmgr_config(struct tg3 *tp)
{
if (tg3_flag(tp, 57765_PLUS)) {
tp->bufmgr_config.mbuf_read_dma_low_water =
DEFAULT_MB_RDMA_LOW_WATER_5705;
tp->bufmgr_config.mbuf_mac_rx_low_water =
DEFAULT_MB_MACRX_LOW_WATER_57765;
tp->bufmgr_config.mbuf_high_water =
DEFAULT_MB_HIGH_WATER_57765;
tp->bufmgr_config.mbuf_read_dma_low_water_jumbo =
DEFAULT_MB_RDMA_LOW_WATER_5705;
tp->bufmgr_config.mbuf_mac_rx_low_water_jumbo =
DEFAULT_MB_MACRX_LOW_WATER_JUMBO_57765;
tp->bufmgr_config.mbuf_high_water_jumbo =
DEFAULT_MB_HIGH_WATER_JUMBO_57765;
} else if (tg3_flag(tp, 5705_PLUS)) {
tp->bufmgr_config.mbuf_read_dma_low_water =
DEFAULT_MB_RDMA_LOW_WATER_5705;
tp->bufmgr_config.mbuf_mac_rx_low_water =
DEFAULT_MB_MACRX_LOW_WATER_5705;
tp->bufmgr_config.mbuf_high_water =
DEFAULT_MB_HIGH_WATER_5705;
if (GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5906) {
tp->bufmgr_config.mbuf_mac_rx_low_water =
DEFAULT_MB_MACRX_LOW_WATER_5906;
tp->bufmgr_config.mbuf_high_water =
DEFAULT_MB_HIGH_WATER_5906;
}
tp->bufmgr_config.mbuf_read_dma_low_water_jumbo =
DEFAULT_MB_RDMA_LOW_WATER_JUMBO_5780;
tp->bufmgr_config.mbuf_mac_rx_low_water_jumbo =
DEFAULT_MB_MACRX_LOW_WATER_JUMBO_5780;
tp->bufmgr_config.mbuf_high_water_jumbo =
DEFAULT_MB_HIGH_WATER_JUMBO_5780;
} else {
tp->bufmgr_config.mbuf_read_dma_low_water =
DEFAULT_MB_RDMA_LOW_WATER;
tp->bufmgr_config.mbuf_mac_rx_low_water =
DEFAULT_MB_MACRX_LOW_WATER;
tp->bufmgr_config.mbuf_high_water =
DEFAULT_MB_HIGH_WATER;
tp->bufmgr_config.mbuf_read_dma_low_water_jumbo =
DEFAULT_MB_RDMA_LOW_WATER_JUMBO;
tp->bufmgr_config.mbuf_mac_rx_low_water_jumbo =
DEFAULT_MB_MACRX_LOW_WATER_JUMBO;
tp->bufmgr_config.mbuf_high_water_jumbo =
DEFAULT_MB_HIGH_WATER_JUMBO;
}
tp->bufmgr_config.dma_low_water = DEFAULT_DMA_LOW_WATER;
tp->bufmgr_config.dma_high_water = DEFAULT_DMA_HIGH_WATER;
}
static char * __devinit tg3_phy_string(struct tg3 *tp)
{
switch (tp->phy_id & TG3_PHY_ID_MASK) {
case TG3_PHY_ID_BCM5400: return "5400";
case TG3_PHY_ID_BCM5401: return "5401";
case TG3_PHY_ID_BCM5411: return "5411";
case TG3_PHY_ID_BCM5701: return "5701";
case TG3_PHY_ID_BCM5703: return "5703";
case TG3_PHY_ID_BCM5704: return "5704";
case TG3_PHY_ID_BCM5705: return "5705";
case TG3_PHY_ID_BCM5750: return "5750";
case TG3_PHY_ID_BCM5752: return "5752";
case TG3_PHY_ID_BCM5714: return "5714";
case TG3_PHY_ID_BCM5780: return "5780";
case TG3_PHY_ID_BCM5755: return "5755";
case TG3_PHY_ID_BCM5787: return "5787";
case TG3_PHY_ID_BCM5784: return "5784";
case TG3_PHY_ID_BCM5756: return "5722/5756";
case TG3_PHY_ID_BCM5906: return "5906";
case TG3_PHY_ID_BCM5761: return "5761";
case TG3_PHY_ID_BCM5718C: return "5718C";
case TG3_PHY_ID_BCM5718S: return "5718S";
case TG3_PHY_ID_BCM57765: return "57765";
case TG3_PHY_ID_BCM5719C: return "5719C";
case TG3_PHY_ID_BCM5720C: return "5720C";
case TG3_PHY_ID_BCM8002: return "8002/serdes";
case 0: return "serdes";
default: return "unknown";
}
}
static char * __devinit tg3_bus_string(struct tg3 *tp, char *str)
{
if (tg3_flag(tp, PCI_EXPRESS)) {
strcpy(str, "PCI Express");
return str;
} else if (tg3_flag(tp, PCIX_MODE)) {
u32 clock_ctrl = tr32(TG3PCI_CLOCK_CTRL) & 0x1f;
strcpy(str, "PCIX:");
if ((clock_ctrl == 7) ||
((tr32(GRC_MISC_CFG) & GRC_MISC_CFG_BOARD_ID_MASK) ==
GRC_MISC_CFG_BOARD_ID_5704CIOBE))
strcat(str, "133MHz");
else if (clock_ctrl == 0)
strcat(str, "33MHz");
else if (clock_ctrl == 2)
strcat(str, "50MHz");
else if (clock_ctrl == 4)
strcat(str, "66MHz");
else if (clock_ctrl == 6)
strcat(str, "100MHz");
} else {
strcpy(str, "PCI:");
if (tg3_flag(tp, PCI_HIGH_SPEED))
strcat(str, "66MHz");
else
strcat(str, "33MHz");
}
if (tg3_flag(tp, PCI_32BIT))
strcat(str, ":32-bit");
else
strcat(str, ":64-bit");
return str;
}
static void __devinit tg3_init_coal(struct tg3 *tp)
{
struct ethtool_coalesce *ec = &tp->coal;
memset(ec, 0, sizeof(*ec));
ec->cmd = ETHTOOL_GCOALESCE;
ec->rx_coalesce_usecs = LOW_RXCOL_TICKS;
ec->tx_coalesce_usecs = LOW_TXCOL_TICKS;
ec->rx_max_coalesced_frames = LOW_RXMAX_FRAMES;
ec->tx_max_coalesced_frames = LOW_TXMAX_FRAMES;
ec->rx_coalesce_usecs_irq = DEFAULT_RXCOAL_TICK_INT;
ec->tx_coalesce_usecs_irq = DEFAULT_TXCOAL_TICK_INT;
ec->rx_max_coalesced_frames_irq = DEFAULT_RXCOAL_MAXF_INT;
ec->tx_max_coalesced_frames_irq = DEFAULT_TXCOAL_MAXF_INT;
ec->stats_block_coalesce_usecs = DEFAULT_STAT_COAL_TICKS;
if (tp->coalesce_mode & (HOSTCC_MODE_CLRTICK_RXBD |
HOSTCC_MODE_CLRTICK_TXBD)) {
ec->rx_coalesce_usecs = LOW_RXCOL_TICKS_CLRTCKS;
ec->rx_coalesce_usecs_irq = DEFAULT_RXCOAL_TICK_INT_CLRTCKS;
ec->tx_coalesce_usecs = LOW_TXCOL_TICKS_CLRTCKS;
ec->tx_coalesce_usecs_irq = DEFAULT_TXCOAL_TICK_INT_CLRTCKS;
}
if (tg3_flag(tp, 5705_PLUS)) {
ec->rx_coalesce_usecs_irq = 0;
ec->tx_coalesce_usecs_irq = 0;
ec->stats_block_coalesce_usecs = 0;
}
}
static int __devinit tg3_init_one(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct net_device *dev;
struct tg3 *tp;
int i, err, pm_cap;
u32 sndmbx, rcvmbx, intmbx;
char str[40];
u64 dma_mask, persist_dma_mask;
netdev_features_t features = 0;
printk_once(KERN_INFO "%s\n", version);
err = pci_enable_device(pdev);
if (err) {
dev_err(&pdev->dev, "Cannot enable PCI device, aborting\n");
return err;
}
err = pci_request_regions(pdev, DRV_MODULE_NAME);
if (err) {
dev_err(&pdev->dev, "Cannot obtain PCI resources, aborting\n");
goto err_out_disable_pdev;
}
pci_set_master(pdev);
/* Find power-management capability. */
pm_cap = pci_find_capability(pdev, PCI_CAP_ID_PM);
if (pm_cap == 0) {
dev_err(&pdev->dev,
"Cannot find Power Management capability, aborting\n");
err = -EIO;
goto err_out_free_res;
}
err = pci_set_power_state(pdev, PCI_D0);
if (err) {
dev_err(&pdev->dev, "Transition to D0 failed, aborting\n");
goto err_out_free_res;
}
dev = alloc_etherdev_mq(sizeof(*tp), TG3_IRQ_MAX_VECS);
if (!dev) {
err = -ENOMEM;
goto err_out_power_down;
}
SET_NETDEV_DEV(dev, &pdev->dev);
tp = netdev_priv(dev);
tp->pdev = pdev;
tp->dev = dev;
tp->pm_cap = pm_cap;
tp->rx_mode = TG3_DEF_RX_MODE;
tp->tx_mode = TG3_DEF_TX_MODE;
if (tg3_debug > 0)
tp->msg_enable = tg3_debug;
else
tp->msg_enable = TG3_DEF_MSG_ENABLE;
/* The word/byte swap controls here control register access byte
* swapping. DMA data byte swapping is controlled in the GRC_MODE
* setting below.
*/
tp->misc_host_ctrl =
MISC_HOST_CTRL_MASK_PCI_INT |
MISC_HOST_CTRL_WORD_SWAP |
MISC_HOST_CTRL_INDIR_ACCESS |
MISC_HOST_CTRL_PCISTATE_RW;
/* The NONFRM (non-frame) byte/word swap controls take effect
* on descriptor entries, anything which isn't packet data.
*
* The StrongARM chips on the board (one for tx, one for rx)
* are running in big-endian mode.
*/
tp->grc_mode = (GRC_MODE_WSWAP_DATA | GRC_MODE_BSWAP_DATA |
GRC_MODE_WSWAP_NONFRM_DATA);
#ifdef __BIG_ENDIAN
tp->grc_mode |= GRC_MODE_BSWAP_NONFRM_DATA;
#endif
spin_lock_init(&tp->lock);
spin_lock_init(&tp->indirect_lock);
INIT_WORK(&tp->reset_task, tg3_reset_task);
tp->regs = pci_ioremap_bar(pdev, BAR_0);
if (!tp->regs) {
dev_err(&pdev->dev, "Cannot map device registers, aborting\n");
err = -ENOMEM;
goto err_out_free_dev;
}
if (tp->pdev->device == PCI_DEVICE_ID_TIGON3_5761 ||
tp->pdev->device == PCI_DEVICE_ID_TIGON3_5761E ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_5761S ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_5761SE ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_5717 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_5718 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_5719 ||
tp->pdev->device == TG3PCI_DEVICE_TIGON3_5720) {
tg3_flag_set(tp, ENABLE_APE);
tp->aperegs = pci_ioremap_bar(pdev, BAR_2);
if (!tp->aperegs) {
dev_err(&pdev->dev,
"Cannot map APE registers, aborting\n");
err = -ENOMEM;
goto err_out_iounmap;
}
}
tp->rx_pending = TG3_DEF_RX_RING_PENDING;
tp->rx_jumbo_pending = TG3_DEF_RX_JUMBO_RING_PENDING;
dev->ethtool_ops = &tg3_ethtool_ops;
dev->watchdog_timeo = TG3_TX_TIMEOUT;
dev->netdev_ops = &tg3_netdev_ops;
dev->irq = pdev->irq;
err = tg3_get_invariants(tp);
if (err) {
dev_err(&pdev->dev,
"Problem fetching invariants of chip, aborting\n");
goto err_out_apeunmap;
}
/* The EPB bridge inside 5714, 5715, and 5780 and any
* device behind the EPB cannot support DMA addresses > 40-bit.
* On 64-bit systems with IOMMU, use 40-bit dma_mask.
* On 64-bit systems without IOMMU, use 64-bit dma_mask and
* do DMA address check in tg3_start_xmit().
*/
if (tg3_flag(tp, IS_5788))
persist_dma_mask = dma_mask = DMA_BIT_MASK(32);
else if (tg3_flag(tp, 40BIT_DMA_BUG)) {
persist_dma_mask = dma_mask = DMA_BIT_MASK(40);
#ifdef CONFIG_HIGHMEM
dma_mask = DMA_BIT_MASK(64);
#endif
} else
persist_dma_mask = dma_mask = DMA_BIT_MASK(64);
/* Configure DMA attributes. */
if (dma_mask > DMA_BIT_MASK(32)) {
err = pci_set_dma_mask(pdev, dma_mask);
if (!err) {
features |= NETIF_F_HIGHDMA;
err = pci_set_consistent_dma_mask(pdev,
persist_dma_mask);
if (err < 0) {
dev_err(&pdev->dev, "Unable to obtain 64 bit "
"DMA for consistent allocations\n");
goto err_out_apeunmap;
}
}
}
if (err || dma_mask == DMA_BIT_MASK(32)) {
err = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
if (err) {
dev_err(&pdev->dev,
"No usable DMA configuration, aborting\n");
goto err_out_apeunmap;
}
}
tg3_init_bufmgr_config(tp);
features |= NETIF_F_HW_VLAN_TX | NETIF_F_HW_VLAN_RX;
/* 5700 B0 chips do not support checksumming correctly due
* to hardware bugs.
*/
if (tp->pci_chip_rev_id != CHIPREV_ID_5700_B0) {
features |= NETIF_F_SG | NETIF_F_IP_CSUM | NETIF_F_RXCSUM;
if (tg3_flag(tp, 5755_PLUS))
features |= NETIF_F_IPV6_CSUM;
}
/* TSO is on by default on chips that support hardware TSO.
* Firmware TSO on older chips gives lower performance, so it
* is off by default, but can be enabled using ethtool.
*/
if ((tg3_flag(tp, HW_TSO_1) ||
tg3_flag(tp, HW_TSO_2) ||
tg3_flag(tp, HW_TSO_3)) &&
(features & NETIF_F_IP_CSUM))
features |= NETIF_F_TSO;
if (tg3_flag(tp, HW_TSO_2) || tg3_flag(tp, HW_TSO_3)) {
if (features & NETIF_F_IPV6_CSUM)
features |= NETIF_F_TSO6;
if (tg3_flag(tp, HW_TSO_3) ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5761 ||
(GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5784 &&
GET_CHIP_REV(tp->pci_chip_rev_id) != CHIPREV_5784_AX) ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_5785 ||
GET_ASIC_REV(tp->pci_chip_rev_id) == ASIC_REV_57780)
features |= NETIF_F_TSO_ECN;
}
dev->features |= features;
dev->vlan_features |= features;
/*
* Add loopback capability only for a subset of devices that support
* MAC-LOOPBACK. Eventually this need to be enhanced to allow INT-PHY
* loopback for the remaining devices.
*/
if (GET_ASIC_REV(tp->pci_chip_rev_id) != ASIC_REV_5780 &&
!tg3_flag(tp, CPMU_PRESENT))
/* Add the loopback capability */
features |= NETIF_F_LOOPBACK;
dev->hw_features |= features;
if (tp->pci_chip_rev_id == CHIPREV_ID_5705_A1 &&
!tg3_flag(tp, TSO_CAPABLE) &&
!(tr32(TG3PCI_PCISTATE) & PCISTATE_BUS_SPEED_HIGH)) {
tg3_flag_set(tp, MAX_RXPEND_64);
tp->rx_pending = 63;
}
err = tg3_get_device_address(tp);
if (err) {
dev_err(&pdev->dev,
"Could not obtain valid ethernet address, aborting\n");
goto err_out_apeunmap;
}
/*
* Reset chip in case UNDI or EFI driver did not shutdown
* DMA self test will enable WDMAC and we'll see (spurious)
* pending DMA on the PCI bus at that point.
*/
if ((tr32(HOSTCC_MODE) & HOSTCC_MODE_ENABLE) ||
(tr32(WDMAC_MODE) & WDMAC_MODE_ENABLE)) {
tw32(MEMARB_MODE, MEMARB_MODE_ENABLE);
tg3_halt(tp, RESET_KIND_SHUTDOWN, 1);
}
err = tg3_test_dma(tp);
if (err) {
dev_err(&pdev->dev, "DMA engine test failed, aborting\n");
goto err_out_apeunmap;
}
intmbx = MAILBOX_INTERRUPT_0 + TG3_64BIT_REG_LOW;
rcvmbx = MAILBOX_RCVRET_CON_IDX_0 + TG3_64BIT_REG_LOW;
sndmbx = MAILBOX_SNDHOST_PROD_IDX_0 + TG3_64BIT_REG_LOW;
for (i = 0; i < tp->irq_max; i++) {
struct tg3_napi *tnapi = &tp->napi[i];
tnapi->tp = tp;
tnapi->tx_pending = TG3_DEF_TX_RING_PENDING;
tnapi->int_mbox = intmbx;
if (i <= 4)
intmbx += 0x8;
else
intmbx += 0x4;
tnapi->consmbox = rcvmbx;
tnapi->prodmbox = sndmbx;
if (i)
tnapi->coal_now = HOSTCC_MODE_COAL_VEC1_NOW << (i - 1);
else
tnapi->coal_now = HOSTCC_MODE_NOW;
if (!tg3_flag(tp, SUPPORT_MSIX))
break;
/*
* If we support MSIX, we'll be using RSS. If we're using
* RSS, the first vector only handles link interrupts and the
* remaining vectors handle rx and tx interrupts. Reuse the
* mailbox values for the next iteration. The values we setup
* above are still useful for the single vectored mode.
*/
if (!i)
continue;
rcvmbx += 0x8;
if (sndmbx & 0x4)
sndmbx -= 0x4;
else
sndmbx += 0xc;
}
tg3_init_coal(tp);
pci_set_drvdata(pdev, dev);
if (tg3_flag(tp, 5717_PLUS)) {
/* Resume a low-power mode */
tg3_frob_aux_power(tp, false);
}
tg3_timer_init(tp);
err = register_netdev(dev);
if (err) {
dev_err(&pdev->dev, "Cannot register net device, aborting\n");
goto err_out_apeunmap;
}
netdev_info(dev, "Tigon3 [partno(%s) rev %04x] (%s) MAC address %pM\n",
tp->board_part_number,
tp->pci_chip_rev_id,
tg3_bus_string(tp, str),
dev->dev_addr);
if (tp->phy_flags & TG3_PHYFLG_IS_CONNECTED) {
struct phy_device *phydev;
phydev = tp->mdio_bus->phy_map[TG3_PHY_MII_ADDR];
netdev_info(dev,
"attached PHY driver [%s] (mii_bus:phy_addr=%s)\n",
phydev->drv->name, dev_name(&phydev->dev));
} else {
char *ethtype;
if (tp->phy_flags & TG3_PHYFLG_10_100_ONLY)
ethtype = "10/100Base-TX";
else if (tp->phy_flags & TG3_PHYFLG_ANY_SERDES)
ethtype = "1000Base-SX";
else
ethtype = "10/100/1000Base-T";
netdev_info(dev, "attached PHY is %s (%s Ethernet) "
"(WireSpeed[%d], EEE[%d])\n",
tg3_phy_string(tp), ethtype,
(tp->phy_flags & TG3_PHYFLG_NO_ETH_WIRE_SPEED) == 0,
(tp->phy_flags & TG3_PHYFLG_EEE_CAP) != 0);
}
netdev_info(dev, "RXcsums[%d] LinkChgREG[%d] MIirq[%d] ASF[%d] TSOcap[%d]\n",
(dev->features & NETIF_F_RXCSUM) != 0,
tg3_flag(tp, USE_LINKCHG_REG) != 0,
(tp->phy_flags & TG3_PHYFLG_USE_MI_INTERRUPT) != 0,
tg3_flag(tp, ENABLE_ASF) != 0,
tg3_flag(tp, TSO_CAPABLE) != 0);
netdev_info(dev, "dma_rwctrl[%08x] dma_mask[%d-bit]\n",
tp->dma_rwctrl,
pdev->dma_mask == DMA_BIT_MASK(32) ? 32 :
((u64)pdev->dma_mask) == DMA_BIT_MASK(40) ? 40 : 64);
pci_save_state(pdev);
return 0;
err_out_apeunmap:
if (tp->aperegs) {
iounmap(tp->aperegs);
tp->aperegs = NULL;
}
err_out_iounmap:
if (tp->regs) {
iounmap(tp->regs);
tp->regs = NULL;
}
err_out_free_dev:
free_netdev(dev);
err_out_power_down:
pci_set_power_state(pdev, PCI_D3hot);
err_out_free_res:
pci_release_regions(pdev);
err_out_disable_pdev:
pci_disable_device(pdev);
pci_set_drvdata(pdev, NULL);
return err;
}
static void __devexit tg3_remove_one(struct pci_dev *pdev)
{
struct net_device *dev = pci_get_drvdata(pdev);
if (dev) {
struct tg3 *tp = netdev_priv(dev);
if (tp->fw)
release_firmware(tp->fw);
tg3_reset_task_cancel(tp);
if (tg3_flag(tp, USE_PHYLIB)) {
tg3_phy_fini(tp);
tg3_mdio_fini(tp);
}
unregister_netdev(dev);
if (tp->aperegs) {
iounmap(tp->aperegs);
tp->aperegs = NULL;
}
if (tp->regs) {
iounmap(tp->regs);
tp->regs = NULL;
}
free_netdev(dev);
pci_release_regions(pdev);
pci_disable_device(pdev);
pci_set_drvdata(pdev, NULL);
}
}
#ifdef CONFIG_PM_SLEEP
static int tg3_suspend(struct device *device)
{
struct pci_dev *pdev = to_pci_dev(device);
struct net_device *dev = pci_get_drvdata(pdev);
struct tg3 *tp = netdev_priv(dev);
int err;
if (!netif_running(dev))
return 0;
tg3_reset_task_cancel(tp);
tg3_phy_stop(tp);
tg3_netif_stop(tp);
tg3_timer_stop(tp);
tg3_full_lock(tp, 1);
tg3_disable_ints(tp);
tg3_full_unlock(tp);
netif_device_detach(dev);
tg3_full_lock(tp, 0);
tg3_halt(tp, RESET_KIND_SHUTDOWN, 1);
tg3_flag_clear(tp, INIT_COMPLETE);
tg3_full_unlock(tp);
err = tg3_power_down_prepare(tp);
if (err) {
int err2;
tg3_full_lock(tp, 0);
tg3_flag_set(tp, INIT_COMPLETE);
err2 = tg3_restart_hw(tp, 1);
if (err2)
goto out;
tg3_timer_start(tp);
netif_device_attach(dev);
tg3_netif_start(tp);
out:
tg3_full_unlock(tp);
if (!err2)
tg3_phy_start(tp);
}
return err;
}
static int tg3_resume(struct device *device)
{
struct pci_dev *pdev = to_pci_dev(device);
struct net_device *dev = pci_get_drvdata(pdev);
struct tg3 *tp = netdev_priv(dev);
int err;
if (!netif_running(dev))
return 0;
netif_device_attach(dev);
tg3_full_lock(tp, 0);
tg3_flag_set(tp, INIT_COMPLETE);
err = tg3_restart_hw(tp, 1);
if (err)
goto out;
tg3_timer_start(tp);
tg3_netif_start(tp);
out:
tg3_full_unlock(tp);
if (!err)
tg3_phy_start(tp);
return err;
}
static SIMPLE_DEV_PM_OPS(tg3_pm_ops, tg3_suspend, tg3_resume);
#define TG3_PM_OPS (&tg3_pm_ops)
#else
#define TG3_PM_OPS NULL
#endif /* CONFIG_PM_SLEEP */
/**
* tg3_io_error_detected - called when PCI error is detected
* @pdev: Pointer to PCI device
* @state: The current pci connection state
*
* This function is called after a PCI bus error affecting
* this device has been detected.
*/
static pci_ers_result_t tg3_io_error_detected(struct pci_dev *pdev,
pci_channel_state_t state)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct tg3 *tp = netdev_priv(netdev);
pci_ers_result_t err = PCI_ERS_RESULT_NEED_RESET;
netdev_info(netdev, "PCI I/O error detected\n");
rtnl_lock();
if (!netif_running(netdev))
goto done;
tg3_phy_stop(tp);
tg3_netif_stop(tp);
tg3_timer_stop(tp);
/* Want to make sure that the reset task doesn't run */
tg3_reset_task_cancel(tp);
netif_device_detach(netdev);
/* Clean up software state, even if MMIO is blocked */
tg3_full_lock(tp, 0);
tg3_halt(tp, RESET_KIND_SHUTDOWN, 0);
tg3_full_unlock(tp);
done:
if (state == pci_channel_io_perm_failure)
err = PCI_ERS_RESULT_DISCONNECT;
else
pci_disable_device(pdev);
rtnl_unlock();
return err;
}
/**
* tg3_io_slot_reset - called after the pci bus has been reset.
* @pdev: Pointer to PCI device
*
* Restart the card from scratch, as if from a cold-boot.
* At this point, the card has exprienced a hard reset,
* followed by fixups by BIOS, and has its config space
* set up identically to what it was at cold boot.
*/
static pci_ers_result_t tg3_io_slot_reset(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct tg3 *tp = netdev_priv(netdev);
pci_ers_result_t rc = PCI_ERS_RESULT_DISCONNECT;
int err;
rtnl_lock();
if (pci_enable_device(pdev)) {
netdev_err(netdev, "Cannot re-enable PCI device after reset.\n");
goto done;
}
pci_set_master(pdev);
pci_restore_state(pdev);
pci_save_state(pdev);
if (!netif_running(netdev)) {
rc = PCI_ERS_RESULT_RECOVERED;
goto done;
}
err = tg3_power_up(tp);
if (err)
goto done;
rc = PCI_ERS_RESULT_RECOVERED;
done:
rtnl_unlock();
return rc;
}
/**
* tg3_io_resume - called when traffic can start flowing again.
* @pdev: Pointer to PCI device
*
* This callback is called when the error recovery driver tells
* us that its OK to resume normal operation.
*/
static void tg3_io_resume(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct tg3 *tp = netdev_priv(netdev);
int err;
rtnl_lock();
if (!netif_running(netdev))
goto done;
tg3_full_lock(tp, 0);
tg3_flag_set(tp, INIT_COMPLETE);
err = tg3_restart_hw(tp, 1);
tg3_full_unlock(tp);
if (err) {
netdev_err(netdev, "Cannot restart hardware after reset.\n");
goto done;
}
netif_device_attach(netdev);
tg3_timer_start(tp);
tg3_netif_start(tp);
tg3_phy_start(tp);
done:
rtnl_unlock();
}
static struct pci_error_handlers tg3_err_handler = {
.error_detected = tg3_io_error_detected,
.slot_reset = tg3_io_slot_reset,
.resume = tg3_io_resume
};
static struct pci_driver tg3_driver = {
.name = DRV_MODULE_NAME,
.id_table = tg3_pci_tbl,
.probe = tg3_init_one,
.remove = __devexit_p(tg3_remove_one),
.err_handler = &tg3_err_handler,
.driver.pm = TG3_PM_OPS,
};
static int __init tg3_init(void)
{
return pci_register_driver(&tg3_driver);
}
static void __exit tg3_cleanup(void)
{
pci_unregister_driver(&tg3_driver);
}
module_init(tg3_init);
module_exit(tg3_cleanup);
| gpl-2.0 |
aatjitra/7105u1 | sound/pci/ymfpci/ymfpci_main.c | 2627 | 72343 | /*
* Copyright (c) by Jaroslav Kysela <perex@perex.cz>
* Routines for control of YMF724/740/744/754 chips
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/delay.h>
#include <linux/firmware.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/pci.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <linux/mutex.h>
#include <sound/core.h>
#include <sound/control.h>
#include <sound/info.h>
#include <sound/tlv.h>
#include <sound/ymfpci.h>
#include <sound/asoundef.h>
#include <sound/mpu401.h>
#include <asm/io.h>
#include <asm/byteorder.h>
/*
* common I/O routines
*/
static void snd_ymfpci_irq_wait(struct snd_ymfpci *chip);
static inline u8 snd_ymfpci_readb(struct snd_ymfpci *chip, u32 offset)
{
return readb(chip->reg_area_virt + offset);
}
static inline void snd_ymfpci_writeb(struct snd_ymfpci *chip, u32 offset, u8 val)
{
writeb(val, chip->reg_area_virt + offset);
}
static inline u16 snd_ymfpci_readw(struct snd_ymfpci *chip, u32 offset)
{
return readw(chip->reg_area_virt + offset);
}
static inline void snd_ymfpci_writew(struct snd_ymfpci *chip, u32 offset, u16 val)
{
writew(val, chip->reg_area_virt + offset);
}
static inline u32 snd_ymfpci_readl(struct snd_ymfpci *chip, u32 offset)
{
return readl(chip->reg_area_virt + offset);
}
static inline void snd_ymfpci_writel(struct snd_ymfpci *chip, u32 offset, u32 val)
{
writel(val, chip->reg_area_virt + offset);
}
static int snd_ymfpci_codec_ready(struct snd_ymfpci *chip, int secondary)
{
unsigned long end_time;
u32 reg = secondary ? YDSXGR_SECSTATUSADR : YDSXGR_PRISTATUSADR;
end_time = jiffies + msecs_to_jiffies(750);
do {
if ((snd_ymfpci_readw(chip, reg) & 0x8000) == 0)
return 0;
schedule_timeout_uninterruptible(1);
} while (time_before(jiffies, end_time));
snd_printk(KERN_ERR "codec_ready: codec %i is not ready [0x%x]\n", secondary, snd_ymfpci_readw(chip, reg));
return -EBUSY;
}
static void snd_ymfpci_codec_write(struct snd_ac97 *ac97, u16 reg, u16 val)
{
struct snd_ymfpci *chip = ac97->private_data;
u32 cmd;
snd_ymfpci_codec_ready(chip, 0);
cmd = ((YDSXG_AC97WRITECMD | reg) << 16) | val;
snd_ymfpci_writel(chip, YDSXGR_AC97CMDDATA, cmd);
}
static u16 snd_ymfpci_codec_read(struct snd_ac97 *ac97, u16 reg)
{
struct snd_ymfpci *chip = ac97->private_data;
if (snd_ymfpci_codec_ready(chip, 0))
return ~0;
snd_ymfpci_writew(chip, YDSXGR_AC97CMDADR, YDSXG_AC97READCMD | reg);
if (snd_ymfpci_codec_ready(chip, 0))
return ~0;
if (chip->device_id == PCI_DEVICE_ID_YAMAHA_744 && chip->rev < 2) {
int i;
for (i = 0; i < 600; i++)
snd_ymfpci_readw(chip, YDSXGR_PRISTATUSDATA);
}
return snd_ymfpci_readw(chip, YDSXGR_PRISTATUSDATA);
}
/*
* Misc routines
*/
static u32 snd_ymfpci_calc_delta(u32 rate)
{
switch (rate) {
case 8000: return 0x02aaab00;
case 11025: return 0x03accd00;
case 16000: return 0x05555500;
case 22050: return 0x07599a00;
case 32000: return 0x0aaaab00;
case 44100: return 0x0eb33300;
default: return ((rate << 16) / 375) << 5;
}
}
static u32 def_rate[8] = {
100, 2000, 8000, 11025, 16000, 22050, 32000, 48000
};
static u32 snd_ymfpci_calc_lpfK(u32 rate)
{
u32 i;
static u32 val[8] = {
0x00570000, 0x06AA0000, 0x18B20000, 0x20930000,
0x2B9A0000, 0x35A10000, 0x3EAA0000, 0x40000000
};
if (rate == 44100)
return 0x40000000; /* FIXME: What's the right value? */
for (i = 0; i < 8; i++)
if (rate <= def_rate[i])
return val[i];
return val[0];
}
static u32 snd_ymfpci_calc_lpfQ(u32 rate)
{
u32 i;
static u32 val[8] = {
0x35280000, 0x34A70000, 0x32020000, 0x31770000,
0x31390000, 0x31C90000, 0x33D00000, 0x40000000
};
if (rate == 44100)
return 0x370A0000;
for (i = 0; i < 8; i++)
if (rate <= def_rate[i])
return val[i];
return val[0];
}
/*
* Hardware start management
*/
static void snd_ymfpci_hw_start(struct snd_ymfpci *chip)
{
unsigned long flags;
spin_lock_irqsave(&chip->reg_lock, flags);
if (chip->start_count++ > 0)
goto __end;
snd_ymfpci_writel(chip, YDSXGR_MODE,
snd_ymfpci_readl(chip, YDSXGR_MODE) | 3);
chip->active_bank = snd_ymfpci_readl(chip, YDSXGR_CTRLSELECT) & 1;
__end:
spin_unlock_irqrestore(&chip->reg_lock, flags);
}
static void snd_ymfpci_hw_stop(struct snd_ymfpci *chip)
{
unsigned long flags;
long timeout = 1000;
spin_lock_irqsave(&chip->reg_lock, flags);
if (--chip->start_count > 0)
goto __end;
snd_ymfpci_writel(chip, YDSXGR_MODE,
snd_ymfpci_readl(chip, YDSXGR_MODE) & ~3);
while (timeout-- > 0) {
if ((snd_ymfpci_readl(chip, YDSXGR_STATUS) & 2) == 0)
break;
}
if (atomic_read(&chip->interrupt_sleep_count)) {
atomic_set(&chip->interrupt_sleep_count, 0);
wake_up(&chip->interrupt_sleep);
}
__end:
spin_unlock_irqrestore(&chip->reg_lock, flags);
}
/*
* Playback voice management
*/
static int voice_alloc(struct snd_ymfpci *chip,
enum snd_ymfpci_voice_type type, int pair,
struct snd_ymfpci_voice **rvoice)
{
struct snd_ymfpci_voice *voice, *voice2;
int idx;
*rvoice = NULL;
for (idx = 0; idx < YDSXG_PLAYBACK_VOICES; idx += pair ? 2 : 1) {
voice = &chip->voices[idx];
voice2 = pair ? &chip->voices[idx+1] : NULL;
if (voice->use || (voice2 && voice2->use))
continue;
voice->use = 1;
if (voice2)
voice2->use = 1;
switch (type) {
case YMFPCI_PCM:
voice->pcm = 1;
if (voice2)
voice2->pcm = 1;
break;
case YMFPCI_SYNTH:
voice->synth = 1;
break;
case YMFPCI_MIDI:
voice->midi = 1;
break;
}
snd_ymfpci_hw_start(chip);
if (voice2)
snd_ymfpci_hw_start(chip);
*rvoice = voice;
return 0;
}
return -ENOMEM;
}
static int snd_ymfpci_voice_alloc(struct snd_ymfpci *chip,
enum snd_ymfpci_voice_type type, int pair,
struct snd_ymfpci_voice **rvoice)
{
unsigned long flags;
int result;
if (snd_BUG_ON(!rvoice))
return -EINVAL;
if (snd_BUG_ON(pair && type != YMFPCI_PCM))
return -EINVAL;
spin_lock_irqsave(&chip->voice_lock, flags);
for (;;) {
result = voice_alloc(chip, type, pair, rvoice);
if (result == 0 || type != YMFPCI_PCM)
break;
/* TODO: synth/midi voice deallocation */
break;
}
spin_unlock_irqrestore(&chip->voice_lock, flags);
return result;
}
static int snd_ymfpci_voice_free(struct snd_ymfpci *chip, struct snd_ymfpci_voice *pvoice)
{
unsigned long flags;
if (snd_BUG_ON(!pvoice))
return -EINVAL;
snd_ymfpci_hw_stop(chip);
spin_lock_irqsave(&chip->voice_lock, flags);
if (pvoice->number == chip->src441_used) {
chip->src441_used = -1;
pvoice->ypcm->use_441_slot = 0;
}
pvoice->use = pvoice->pcm = pvoice->synth = pvoice->midi = 0;
pvoice->ypcm = NULL;
pvoice->interrupt = NULL;
spin_unlock_irqrestore(&chip->voice_lock, flags);
return 0;
}
/*
* PCM part
*/
static void snd_ymfpci_pcm_interrupt(struct snd_ymfpci *chip, struct snd_ymfpci_voice *voice)
{
struct snd_ymfpci_pcm *ypcm;
u32 pos, delta;
if ((ypcm = voice->ypcm) == NULL)
return;
if (ypcm->substream == NULL)
return;
spin_lock(&chip->reg_lock);
if (ypcm->running) {
pos = le32_to_cpu(voice->bank[chip->active_bank].start);
if (pos < ypcm->last_pos)
delta = pos + (ypcm->buffer_size - ypcm->last_pos);
else
delta = pos - ypcm->last_pos;
ypcm->period_pos += delta;
ypcm->last_pos = pos;
if (ypcm->period_pos >= ypcm->period_size) {
/*
printk(KERN_DEBUG
"done - active_bank = 0x%x, start = 0x%x\n",
chip->active_bank,
voice->bank[chip->active_bank].start);
*/
ypcm->period_pos %= ypcm->period_size;
spin_unlock(&chip->reg_lock);
snd_pcm_period_elapsed(ypcm->substream);
spin_lock(&chip->reg_lock);
}
if (unlikely(ypcm->update_pcm_vol)) {
unsigned int subs = ypcm->substream->number;
unsigned int next_bank = 1 - chip->active_bank;
struct snd_ymfpci_playback_bank *bank;
u32 volume;
bank = &voice->bank[next_bank];
volume = cpu_to_le32(chip->pcm_mixer[subs].left << 15);
bank->left_gain_end = volume;
if (ypcm->output_rear)
bank->eff2_gain_end = volume;
if (ypcm->voices[1])
bank = &ypcm->voices[1]->bank[next_bank];
volume = cpu_to_le32(chip->pcm_mixer[subs].right << 15);
bank->right_gain_end = volume;
if (ypcm->output_rear)
bank->eff3_gain_end = volume;
ypcm->update_pcm_vol--;
}
}
spin_unlock(&chip->reg_lock);
}
static void snd_ymfpci_pcm_capture_interrupt(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm = runtime->private_data;
struct snd_ymfpci *chip = ypcm->chip;
u32 pos, delta;
spin_lock(&chip->reg_lock);
if (ypcm->running) {
pos = le32_to_cpu(chip->bank_capture[ypcm->capture_bank_number][chip->active_bank]->start) >> ypcm->shift;
if (pos < ypcm->last_pos)
delta = pos + (ypcm->buffer_size - ypcm->last_pos);
else
delta = pos - ypcm->last_pos;
ypcm->period_pos += delta;
ypcm->last_pos = pos;
if (ypcm->period_pos >= ypcm->period_size) {
ypcm->period_pos %= ypcm->period_size;
/*
printk(KERN_DEBUG
"done - active_bank = 0x%x, start = 0x%x\n",
chip->active_bank,
voice->bank[chip->active_bank].start);
*/
spin_unlock(&chip->reg_lock);
snd_pcm_period_elapsed(substream);
spin_lock(&chip->reg_lock);
}
}
spin_unlock(&chip->reg_lock);
}
static int snd_ymfpci_playback_trigger(struct snd_pcm_substream *substream,
int cmd)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_ymfpci_pcm *ypcm = substream->runtime->private_data;
struct snd_kcontrol *kctl = NULL;
int result = 0;
spin_lock(&chip->reg_lock);
if (ypcm->voices[0] == NULL) {
result = -EINVAL;
goto __unlock;
}
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
case SNDRV_PCM_TRIGGER_RESUME:
chip->ctrl_playback[ypcm->voices[0]->number + 1] = cpu_to_le32(ypcm->voices[0]->bank_addr);
if (ypcm->voices[1] != NULL && !ypcm->use_441_slot)
chip->ctrl_playback[ypcm->voices[1]->number + 1] = cpu_to_le32(ypcm->voices[1]->bank_addr);
ypcm->running = 1;
break;
case SNDRV_PCM_TRIGGER_STOP:
if (substream->pcm == chip->pcm && !ypcm->use_441_slot) {
kctl = chip->pcm_mixer[substream->number].ctl;
kctl->vd[0].access |= SNDRV_CTL_ELEM_ACCESS_INACTIVE;
}
/* fall through */
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
case SNDRV_PCM_TRIGGER_SUSPEND:
chip->ctrl_playback[ypcm->voices[0]->number + 1] = 0;
if (ypcm->voices[1] != NULL && !ypcm->use_441_slot)
chip->ctrl_playback[ypcm->voices[1]->number + 1] = 0;
ypcm->running = 0;
break;
default:
result = -EINVAL;
break;
}
__unlock:
spin_unlock(&chip->reg_lock);
if (kctl)
snd_ctl_notify(chip->card, SNDRV_CTL_EVENT_MASK_INFO, &kctl->id);
return result;
}
static int snd_ymfpci_capture_trigger(struct snd_pcm_substream *substream,
int cmd)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_ymfpci_pcm *ypcm = substream->runtime->private_data;
int result = 0;
u32 tmp;
spin_lock(&chip->reg_lock);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
case SNDRV_PCM_TRIGGER_RESUME:
tmp = snd_ymfpci_readl(chip, YDSXGR_MAPOFREC) | (1 << ypcm->capture_bank_number);
snd_ymfpci_writel(chip, YDSXGR_MAPOFREC, tmp);
ypcm->running = 1;
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
case SNDRV_PCM_TRIGGER_SUSPEND:
tmp = snd_ymfpci_readl(chip, YDSXGR_MAPOFREC) & ~(1 << ypcm->capture_bank_number);
snd_ymfpci_writel(chip, YDSXGR_MAPOFREC, tmp);
ypcm->running = 0;
break;
default:
result = -EINVAL;
break;
}
spin_unlock(&chip->reg_lock);
return result;
}
static int snd_ymfpci_pcm_voice_alloc(struct snd_ymfpci_pcm *ypcm, int voices)
{
int err;
if (ypcm->voices[1] != NULL && voices < 2) {
snd_ymfpci_voice_free(ypcm->chip, ypcm->voices[1]);
ypcm->voices[1] = NULL;
}
if (voices == 1 && ypcm->voices[0] != NULL)
return 0; /* already allocated */
if (voices == 2 && ypcm->voices[0] != NULL && ypcm->voices[1] != NULL)
return 0; /* already allocated */
if (voices > 1) {
if (ypcm->voices[0] != NULL && ypcm->voices[1] == NULL) {
snd_ymfpci_voice_free(ypcm->chip, ypcm->voices[0]);
ypcm->voices[0] = NULL;
}
}
err = snd_ymfpci_voice_alloc(ypcm->chip, YMFPCI_PCM, voices > 1, &ypcm->voices[0]);
if (err < 0)
return err;
ypcm->voices[0]->ypcm = ypcm;
ypcm->voices[0]->interrupt = snd_ymfpci_pcm_interrupt;
if (voices > 1) {
ypcm->voices[1] = &ypcm->chip->voices[ypcm->voices[0]->number + 1];
ypcm->voices[1]->ypcm = ypcm;
}
return 0;
}
static void snd_ymfpci_pcm_init_voice(struct snd_ymfpci_pcm *ypcm, unsigned int voiceidx,
struct snd_pcm_runtime *runtime,
int has_pcm_volume)
{
struct snd_ymfpci_voice *voice = ypcm->voices[voiceidx];
u32 format;
u32 delta = snd_ymfpci_calc_delta(runtime->rate);
u32 lpfQ = snd_ymfpci_calc_lpfQ(runtime->rate);
u32 lpfK = snd_ymfpci_calc_lpfK(runtime->rate);
struct snd_ymfpci_playback_bank *bank;
unsigned int nbank;
u32 vol_left, vol_right;
u8 use_left, use_right;
unsigned long flags;
if (snd_BUG_ON(!voice))
return;
if (runtime->channels == 1) {
use_left = 1;
use_right = 1;
} else {
use_left = (voiceidx & 1) == 0;
use_right = !use_left;
}
if (has_pcm_volume) {
vol_left = cpu_to_le32(ypcm->chip->pcm_mixer
[ypcm->substream->number].left << 15);
vol_right = cpu_to_le32(ypcm->chip->pcm_mixer
[ypcm->substream->number].right << 15);
} else {
vol_left = cpu_to_le32(0x40000000);
vol_right = cpu_to_le32(0x40000000);
}
spin_lock_irqsave(&ypcm->chip->voice_lock, flags);
format = runtime->channels == 2 ? 0x00010000 : 0;
if (snd_pcm_format_width(runtime->format) == 8)
format |= 0x80000000;
else if (ypcm->chip->device_id == PCI_DEVICE_ID_YAMAHA_754 &&
runtime->rate == 44100 && runtime->channels == 2 &&
voiceidx == 0 && (ypcm->chip->src441_used == -1 ||
ypcm->chip->src441_used == voice->number)) {
ypcm->chip->src441_used = voice->number;
ypcm->use_441_slot = 1;
format |= 0x10000000;
}
if (ypcm->chip->src441_used == voice->number &&
(format & 0x10000000) == 0) {
ypcm->chip->src441_used = -1;
ypcm->use_441_slot = 0;
}
if (runtime->channels == 2 && (voiceidx & 1) != 0)
format |= 1;
spin_unlock_irqrestore(&ypcm->chip->voice_lock, flags);
for (nbank = 0; nbank < 2; nbank++) {
bank = &voice->bank[nbank];
memset(bank, 0, sizeof(*bank));
bank->format = cpu_to_le32(format);
bank->base = cpu_to_le32(runtime->dma_addr);
bank->loop_end = cpu_to_le32(ypcm->buffer_size);
bank->lpfQ = cpu_to_le32(lpfQ);
bank->delta =
bank->delta_end = cpu_to_le32(delta);
bank->lpfK =
bank->lpfK_end = cpu_to_le32(lpfK);
bank->eg_gain =
bank->eg_gain_end = cpu_to_le32(0x40000000);
if (ypcm->output_front) {
if (use_left) {
bank->left_gain =
bank->left_gain_end = vol_left;
}
if (use_right) {
bank->right_gain =
bank->right_gain_end = vol_right;
}
}
if (ypcm->output_rear) {
if (!ypcm->swap_rear) {
if (use_left) {
bank->eff2_gain =
bank->eff2_gain_end = vol_left;
}
if (use_right) {
bank->eff3_gain =
bank->eff3_gain_end = vol_right;
}
} else {
/* The SPDIF out channels seem to be swapped, so we have
* to swap them here, too. The rear analog out channels
* will be wrong, but otherwise AC3 would not work.
*/
if (use_left) {
bank->eff3_gain =
bank->eff3_gain_end = vol_left;
}
if (use_right) {
bank->eff2_gain =
bank->eff2_gain_end = vol_right;
}
}
}
}
}
static int __devinit snd_ymfpci_ac3_init(struct snd_ymfpci *chip)
{
if (snd_dma_alloc_pages(SNDRV_DMA_TYPE_DEV, snd_dma_pci_data(chip->pci),
4096, &chip->ac3_tmp_base) < 0)
return -ENOMEM;
chip->bank_effect[3][0]->base =
chip->bank_effect[3][1]->base = cpu_to_le32(chip->ac3_tmp_base.addr);
chip->bank_effect[3][0]->loop_end =
chip->bank_effect[3][1]->loop_end = cpu_to_le32(1024);
chip->bank_effect[4][0]->base =
chip->bank_effect[4][1]->base = cpu_to_le32(chip->ac3_tmp_base.addr + 2048);
chip->bank_effect[4][0]->loop_end =
chip->bank_effect[4][1]->loop_end = cpu_to_le32(1024);
spin_lock_irq(&chip->reg_lock);
snd_ymfpci_writel(chip, YDSXGR_MAPOFEFFECT,
snd_ymfpci_readl(chip, YDSXGR_MAPOFEFFECT) | 3 << 3);
spin_unlock_irq(&chip->reg_lock);
return 0;
}
static int snd_ymfpci_ac3_done(struct snd_ymfpci *chip)
{
spin_lock_irq(&chip->reg_lock);
snd_ymfpci_writel(chip, YDSXGR_MAPOFEFFECT,
snd_ymfpci_readl(chip, YDSXGR_MAPOFEFFECT) & ~(3 << 3));
spin_unlock_irq(&chip->reg_lock);
// snd_ymfpci_irq_wait(chip);
if (chip->ac3_tmp_base.area) {
snd_dma_free_pages(&chip->ac3_tmp_base);
chip->ac3_tmp_base.area = NULL;
}
return 0;
}
static int snd_ymfpci_playback_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm = runtime->private_data;
int err;
if ((err = snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params))) < 0)
return err;
if ((err = snd_ymfpci_pcm_voice_alloc(ypcm, params_channels(hw_params))) < 0)
return err;
return 0;
}
static int snd_ymfpci_playback_hw_free(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm;
if (runtime->private_data == NULL)
return 0;
ypcm = runtime->private_data;
/* wait, until the PCI operations are not finished */
snd_ymfpci_irq_wait(chip);
snd_pcm_lib_free_pages(substream);
if (ypcm->voices[1]) {
snd_ymfpci_voice_free(chip, ypcm->voices[1]);
ypcm->voices[1] = NULL;
}
if (ypcm->voices[0]) {
snd_ymfpci_voice_free(chip, ypcm->voices[0]);
ypcm->voices[0] = NULL;
}
return 0;
}
static int snd_ymfpci_playback_prepare(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm = runtime->private_data;
struct snd_kcontrol *kctl;
unsigned int nvoice;
ypcm->period_size = runtime->period_size;
ypcm->buffer_size = runtime->buffer_size;
ypcm->period_pos = 0;
ypcm->last_pos = 0;
for (nvoice = 0; nvoice < runtime->channels; nvoice++)
snd_ymfpci_pcm_init_voice(ypcm, nvoice, runtime,
substream->pcm == chip->pcm);
if (substream->pcm == chip->pcm && !ypcm->use_441_slot) {
kctl = chip->pcm_mixer[substream->number].ctl;
kctl->vd[0].access &= ~SNDRV_CTL_ELEM_ACCESS_INACTIVE;
snd_ctl_notify(chip->card, SNDRV_CTL_EVENT_MASK_INFO, &kctl->id);
}
return 0;
}
static int snd_ymfpci_capture_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
return snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params));
}
static int snd_ymfpci_capture_hw_free(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
/* wait, until the PCI operations are not finished */
snd_ymfpci_irq_wait(chip);
return snd_pcm_lib_free_pages(substream);
}
static int snd_ymfpci_capture_prepare(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm = runtime->private_data;
struct snd_ymfpci_capture_bank * bank;
int nbank;
u32 rate, format;
ypcm->period_size = runtime->period_size;
ypcm->buffer_size = runtime->buffer_size;
ypcm->period_pos = 0;
ypcm->last_pos = 0;
ypcm->shift = 0;
rate = ((48000 * 4096) / runtime->rate) - 1;
format = 0;
if (runtime->channels == 2) {
format |= 2;
ypcm->shift++;
}
if (snd_pcm_format_width(runtime->format) == 8)
format |= 1;
else
ypcm->shift++;
switch (ypcm->capture_bank_number) {
case 0:
snd_ymfpci_writel(chip, YDSXGR_RECFORMAT, format);
snd_ymfpci_writel(chip, YDSXGR_RECSLOTSR, rate);
break;
case 1:
snd_ymfpci_writel(chip, YDSXGR_ADCFORMAT, format);
snd_ymfpci_writel(chip, YDSXGR_ADCSLOTSR, rate);
break;
}
for (nbank = 0; nbank < 2; nbank++) {
bank = chip->bank_capture[ypcm->capture_bank_number][nbank];
bank->base = cpu_to_le32(runtime->dma_addr);
bank->loop_end = cpu_to_le32(ypcm->buffer_size << ypcm->shift);
bank->start = 0;
bank->num_of_loops = 0;
}
return 0;
}
static snd_pcm_uframes_t snd_ymfpci_playback_pointer(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm = runtime->private_data;
struct snd_ymfpci_voice *voice = ypcm->voices[0];
if (!(ypcm->running && voice))
return 0;
return le32_to_cpu(voice->bank[chip->active_bank].start);
}
static snd_pcm_uframes_t snd_ymfpci_capture_pointer(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm = runtime->private_data;
if (!ypcm->running)
return 0;
return le32_to_cpu(chip->bank_capture[ypcm->capture_bank_number][chip->active_bank]->start) >> ypcm->shift;
}
static void snd_ymfpci_irq_wait(struct snd_ymfpci *chip)
{
wait_queue_t wait;
int loops = 4;
while (loops-- > 0) {
if ((snd_ymfpci_readl(chip, YDSXGR_MODE) & 3) == 0)
continue;
init_waitqueue_entry(&wait, current);
add_wait_queue(&chip->interrupt_sleep, &wait);
atomic_inc(&chip->interrupt_sleep_count);
schedule_timeout_uninterruptible(msecs_to_jiffies(50));
remove_wait_queue(&chip->interrupt_sleep, &wait);
}
}
static irqreturn_t snd_ymfpci_interrupt(int irq, void *dev_id)
{
struct snd_ymfpci *chip = dev_id;
u32 status, nvoice, mode;
struct snd_ymfpci_voice *voice;
status = snd_ymfpci_readl(chip, YDSXGR_STATUS);
if (status & 0x80000000) {
chip->active_bank = snd_ymfpci_readl(chip, YDSXGR_CTRLSELECT) & 1;
spin_lock(&chip->voice_lock);
for (nvoice = 0; nvoice < YDSXG_PLAYBACK_VOICES; nvoice++) {
voice = &chip->voices[nvoice];
if (voice->interrupt)
voice->interrupt(chip, voice);
}
for (nvoice = 0; nvoice < YDSXG_CAPTURE_VOICES; nvoice++) {
if (chip->capture_substream[nvoice])
snd_ymfpci_pcm_capture_interrupt(chip->capture_substream[nvoice]);
}
#if 0
for (nvoice = 0; nvoice < YDSXG_EFFECT_VOICES; nvoice++) {
if (chip->effect_substream[nvoice])
snd_ymfpci_pcm_effect_interrupt(chip->effect_substream[nvoice]);
}
#endif
spin_unlock(&chip->voice_lock);
spin_lock(&chip->reg_lock);
snd_ymfpci_writel(chip, YDSXGR_STATUS, 0x80000000);
mode = snd_ymfpci_readl(chip, YDSXGR_MODE) | 2;
snd_ymfpci_writel(chip, YDSXGR_MODE, mode);
spin_unlock(&chip->reg_lock);
if (atomic_read(&chip->interrupt_sleep_count)) {
atomic_set(&chip->interrupt_sleep_count, 0);
wake_up(&chip->interrupt_sleep);
}
}
status = snd_ymfpci_readw(chip, YDSXGR_INTFLAG);
if (status & 1) {
if (chip->timer)
snd_timer_interrupt(chip->timer, chip->timer_ticks);
}
snd_ymfpci_writew(chip, YDSXGR_INTFLAG, status);
if (chip->rawmidi)
snd_mpu401_uart_interrupt(irq, chip->rawmidi->private_data);
return IRQ_HANDLED;
}
static struct snd_pcm_hardware snd_ymfpci_playback =
{
.info = (SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_PAUSE |
SNDRV_PCM_INFO_RESUME),
.formats = SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_S16_LE,
.rates = SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_8000_48000,
.rate_min = 8000,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = 256 * 1024, /* FIXME: enough? */
.period_bytes_min = 64,
.period_bytes_max = 256 * 1024, /* FIXME: enough? */
.periods_min = 3,
.periods_max = 1024,
.fifo_size = 0,
};
static struct snd_pcm_hardware snd_ymfpci_capture =
{
.info = (SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_PAUSE |
SNDRV_PCM_INFO_RESUME),
.formats = SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_S16_LE,
.rates = SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_8000_48000,
.rate_min = 8000,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = 256 * 1024, /* FIXME: enough? */
.period_bytes_min = 64,
.period_bytes_max = 256 * 1024, /* FIXME: enough? */
.periods_min = 3,
.periods_max = 1024,
.fifo_size = 0,
};
static void snd_ymfpci_pcm_free_substream(struct snd_pcm_runtime *runtime)
{
kfree(runtime->private_data);
}
static int snd_ymfpci_playback_open_1(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm;
ypcm = kzalloc(sizeof(*ypcm), GFP_KERNEL);
if (ypcm == NULL)
return -ENOMEM;
ypcm->chip = chip;
ypcm->type = PLAYBACK_VOICE;
ypcm->substream = substream;
runtime->hw = snd_ymfpci_playback;
runtime->private_data = ypcm;
runtime->private_free = snd_ymfpci_pcm_free_substream;
/* FIXME? True value is 256/48 = 5.33333 ms */
snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_PERIOD_TIME, 5333, UINT_MAX);
return 0;
}
/* call with spinlock held */
static void ymfpci_open_extension(struct snd_ymfpci *chip)
{
if (! chip->rear_opened) {
if (! chip->spdif_opened) /* set AC3 */
snd_ymfpci_writel(chip, YDSXGR_MODE,
snd_ymfpci_readl(chip, YDSXGR_MODE) | (1 << 30));
/* enable second codec (4CHEN) */
snd_ymfpci_writew(chip, YDSXGR_SECCONFIG,
(snd_ymfpci_readw(chip, YDSXGR_SECCONFIG) & ~0x0330) | 0x0010);
}
}
/* call with spinlock held */
static void ymfpci_close_extension(struct snd_ymfpci *chip)
{
if (! chip->rear_opened) {
if (! chip->spdif_opened)
snd_ymfpci_writel(chip, YDSXGR_MODE,
snd_ymfpci_readl(chip, YDSXGR_MODE) & ~(1 << 30));
snd_ymfpci_writew(chip, YDSXGR_SECCONFIG,
(snd_ymfpci_readw(chip, YDSXGR_SECCONFIG) & ~0x0330) & ~0x0010);
}
}
static int snd_ymfpci_playback_open(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm;
int err;
if ((err = snd_ymfpci_playback_open_1(substream)) < 0)
return err;
ypcm = runtime->private_data;
ypcm->output_front = 1;
ypcm->output_rear = chip->mode_dup4ch ? 1 : 0;
ypcm->swap_rear = 0;
spin_lock_irq(&chip->reg_lock);
if (ypcm->output_rear) {
ymfpci_open_extension(chip);
chip->rear_opened++;
}
spin_unlock_irq(&chip->reg_lock);
return 0;
}
static int snd_ymfpci_playback_spdif_open(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm;
int err;
if ((err = snd_ymfpci_playback_open_1(substream)) < 0)
return err;
ypcm = runtime->private_data;
ypcm->output_front = 0;
ypcm->output_rear = 1;
ypcm->swap_rear = 1;
spin_lock_irq(&chip->reg_lock);
snd_ymfpci_writew(chip, YDSXGR_SPDIFOUTCTRL,
snd_ymfpci_readw(chip, YDSXGR_SPDIFOUTCTRL) | 2);
ymfpci_open_extension(chip);
chip->spdif_pcm_bits = chip->spdif_bits;
snd_ymfpci_writew(chip, YDSXGR_SPDIFOUTSTATUS, chip->spdif_pcm_bits);
chip->spdif_opened++;
spin_unlock_irq(&chip->reg_lock);
chip->spdif_pcm_ctl->vd[0].access &= ~SNDRV_CTL_ELEM_ACCESS_INACTIVE;
snd_ctl_notify(chip->card, SNDRV_CTL_EVENT_MASK_VALUE |
SNDRV_CTL_EVENT_MASK_INFO, &chip->spdif_pcm_ctl->id);
return 0;
}
static int snd_ymfpci_playback_4ch_open(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm;
int err;
if ((err = snd_ymfpci_playback_open_1(substream)) < 0)
return err;
ypcm = runtime->private_data;
ypcm->output_front = 0;
ypcm->output_rear = 1;
ypcm->swap_rear = 0;
spin_lock_irq(&chip->reg_lock);
ymfpci_open_extension(chip);
chip->rear_opened++;
spin_unlock_irq(&chip->reg_lock);
return 0;
}
static int snd_ymfpci_capture_open(struct snd_pcm_substream *substream,
u32 capture_bank_number)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm;
ypcm = kzalloc(sizeof(*ypcm), GFP_KERNEL);
if (ypcm == NULL)
return -ENOMEM;
ypcm->chip = chip;
ypcm->type = capture_bank_number + CAPTURE_REC;
ypcm->substream = substream;
ypcm->capture_bank_number = capture_bank_number;
chip->capture_substream[capture_bank_number] = substream;
runtime->hw = snd_ymfpci_capture;
/* FIXME? True value is 256/48 = 5.33333 ms */
snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_PERIOD_TIME, 5333, UINT_MAX);
runtime->private_data = ypcm;
runtime->private_free = snd_ymfpci_pcm_free_substream;
snd_ymfpci_hw_start(chip);
return 0;
}
static int snd_ymfpci_capture_rec_open(struct snd_pcm_substream *substream)
{
return snd_ymfpci_capture_open(substream, 0);
}
static int snd_ymfpci_capture_ac97_open(struct snd_pcm_substream *substream)
{
return snd_ymfpci_capture_open(substream, 1);
}
static int snd_ymfpci_playback_close_1(struct snd_pcm_substream *substream)
{
return 0;
}
static int snd_ymfpci_playback_close(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_ymfpci_pcm *ypcm = substream->runtime->private_data;
spin_lock_irq(&chip->reg_lock);
if (ypcm->output_rear && chip->rear_opened > 0) {
chip->rear_opened--;
ymfpci_close_extension(chip);
}
spin_unlock_irq(&chip->reg_lock);
return snd_ymfpci_playback_close_1(substream);
}
static int snd_ymfpci_playback_spdif_close(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
spin_lock_irq(&chip->reg_lock);
chip->spdif_opened = 0;
ymfpci_close_extension(chip);
snd_ymfpci_writew(chip, YDSXGR_SPDIFOUTCTRL,
snd_ymfpci_readw(chip, YDSXGR_SPDIFOUTCTRL) & ~2);
snd_ymfpci_writew(chip, YDSXGR_SPDIFOUTSTATUS, chip->spdif_bits);
spin_unlock_irq(&chip->reg_lock);
chip->spdif_pcm_ctl->vd[0].access |= SNDRV_CTL_ELEM_ACCESS_INACTIVE;
snd_ctl_notify(chip->card, SNDRV_CTL_EVENT_MASK_VALUE |
SNDRV_CTL_EVENT_MASK_INFO, &chip->spdif_pcm_ctl->id);
return snd_ymfpci_playback_close_1(substream);
}
static int snd_ymfpci_playback_4ch_close(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
spin_lock_irq(&chip->reg_lock);
if (chip->rear_opened > 0) {
chip->rear_opened--;
ymfpci_close_extension(chip);
}
spin_unlock_irq(&chip->reg_lock);
return snd_ymfpci_playback_close_1(substream);
}
static int snd_ymfpci_capture_close(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm = runtime->private_data;
if (ypcm != NULL) {
chip->capture_substream[ypcm->capture_bank_number] = NULL;
snd_ymfpci_hw_stop(chip);
}
return 0;
}
static struct snd_pcm_ops snd_ymfpci_playback_ops = {
.open = snd_ymfpci_playback_open,
.close = snd_ymfpci_playback_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_ymfpci_playback_hw_params,
.hw_free = snd_ymfpci_playback_hw_free,
.prepare = snd_ymfpci_playback_prepare,
.trigger = snd_ymfpci_playback_trigger,
.pointer = snd_ymfpci_playback_pointer,
};
static struct snd_pcm_ops snd_ymfpci_capture_rec_ops = {
.open = snd_ymfpci_capture_rec_open,
.close = snd_ymfpci_capture_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_ymfpci_capture_hw_params,
.hw_free = snd_ymfpci_capture_hw_free,
.prepare = snd_ymfpci_capture_prepare,
.trigger = snd_ymfpci_capture_trigger,
.pointer = snd_ymfpci_capture_pointer,
};
int __devinit snd_ymfpci_pcm(struct snd_ymfpci *chip, int device, struct snd_pcm ** rpcm)
{
struct snd_pcm *pcm;
int err;
if (rpcm)
*rpcm = NULL;
if ((err = snd_pcm_new(chip->card, "YMFPCI", device, 32, 1, &pcm)) < 0)
return err;
pcm->private_data = chip;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_ymfpci_playback_ops);
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_ymfpci_capture_rec_ops);
/* global setup */
pcm->info_flags = 0;
strcpy(pcm->name, "YMFPCI");
chip->pcm = pcm;
snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
snd_dma_pci_data(chip->pci), 64*1024, 256*1024);
if (rpcm)
*rpcm = pcm;
return 0;
}
static struct snd_pcm_ops snd_ymfpci_capture_ac97_ops = {
.open = snd_ymfpci_capture_ac97_open,
.close = snd_ymfpci_capture_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_ymfpci_capture_hw_params,
.hw_free = snd_ymfpci_capture_hw_free,
.prepare = snd_ymfpci_capture_prepare,
.trigger = snd_ymfpci_capture_trigger,
.pointer = snd_ymfpci_capture_pointer,
};
int __devinit snd_ymfpci_pcm2(struct snd_ymfpci *chip, int device, struct snd_pcm ** rpcm)
{
struct snd_pcm *pcm;
int err;
if (rpcm)
*rpcm = NULL;
if ((err = snd_pcm_new(chip->card, "YMFPCI - PCM2", device, 0, 1, &pcm)) < 0)
return err;
pcm->private_data = chip;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_ymfpci_capture_ac97_ops);
/* global setup */
pcm->info_flags = 0;
sprintf(pcm->name, "YMFPCI - %s",
chip->device_id == PCI_DEVICE_ID_YAMAHA_754 ? "Direct Recording" : "AC'97");
chip->pcm2 = pcm;
snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
snd_dma_pci_data(chip->pci), 64*1024, 256*1024);
if (rpcm)
*rpcm = pcm;
return 0;
}
static struct snd_pcm_ops snd_ymfpci_playback_spdif_ops = {
.open = snd_ymfpci_playback_spdif_open,
.close = snd_ymfpci_playback_spdif_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_ymfpci_playback_hw_params,
.hw_free = snd_ymfpci_playback_hw_free,
.prepare = snd_ymfpci_playback_prepare,
.trigger = snd_ymfpci_playback_trigger,
.pointer = snd_ymfpci_playback_pointer,
};
int __devinit snd_ymfpci_pcm_spdif(struct snd_ymfpci *chip, int device, struct snd_pcm ** rpcm)
{
struct snd_pcm *pcm;
int err;
if (rpcm)
*rpcm = NULL;
if ((err = snd_pcm_new(chip->card, "YMFPCI - IEC958", device, 1, 0, &pcm)) < 0)
return err;
pcm->private_data = chip;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_ymfpci_playback_spdif_ops);
/* global setup */
pcm->info_flags = 0;
strcpy(pcm->name, "YMFPCI - IEC958");
chip->pcm_spdif = pcm;
snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
snd_dma_pci_data(chip->pci), 64*1024, 256*1024);
if (rpcm)
*rpcm = pcm;
return 0;
}
static struct snd_pcm_ops snd_ymfpci_playback_4ch_ops = {
.open = snd_ymfpci_playback_4ch_open,
.close = snd_ymfpci_playback_4ch_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_ymfpci_playback_hw_params,
.hw_free = snd_ymfpci_playback_hw_free,
.prepare = snd_ymfpci_playback_prepare,
.trigger = snd_ymfpci_playback_trigger,
.pointer = snd_ymfpci_playback_pointer,
};
int __devinit snd_ymfpci_pcm_4ch(struct snd_ymfpci *chip, int device, struct snd_pcm ** rpcm)
{
struct snd_pcm *pcm;
int err;
if (rpcm)
*rpcm = NULL;
if ((err = snd_pcm_new(chip->card, "YMFPCI - Rear", device, 1, 0, &pcm)) < 0)
return err;
pcm->private_data = chip;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_ymfpci_playback_4ch_ops);
/* global setup */
pcm->info_flags = 0;
strcpy(pcm->name, "YMFPCI - Rear PCM");
chip->pcm_4ch = pcm;
snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
snd_dma_pci_data(chip->pci), 64*1024, 256*1024);
if (rpcm)
*rpcm = pcm;
return 0;
}
static int snd_ymfpci_spdif_default_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958;
uinfo->count = 1;
return 0;
}
static int snd_ymfpci_spdif_default_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
spin_lock_irq(&chip->reg_lock);
ucontrol->value.iec958.status[0] = (chip->spdif_bits >> 0) & 0xff;
ucontrol->value.iec958.status[1] = (chip->spdif_bits >> 8) & 0xff;
ucontrol->value.iec958.status[3] = IEC958_AES3_CON_FS_48000;
spin_unlock_irq(&chip->reg_lock);
return 0;
}
static int snd_ymfpci_spdif_default_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
unsigned int val;
int change;
val = ((ucontrol->value.iec958.status[0] & 0x3e) << 0) |
(ucontrol->value.iec958.status[1] << 8);
spin_lock_irq(&chip->reg_lock);
change = chip->spdif_bits != val;
chip->spdif_bits = val;
if ((snd_ymfpci_readw(chip, YDSXGR_SPDIFOUTCTRL) & 1) && chip->pcm_spdif == NULL)
snd_ymfpci_writew(chip, YDSXGR_SPDIFOUTSTATUS, chip->spdif_bits);
spin_unlock_irq(&chip->reg_lock);
return change;
}
static struct snd_kcontrol_new snd_ymfpci_spdif_default __devinitdata =
{
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,DEFAULT),
.info = snd_ymfpci_spdif_default_info,
.get = snd_ymfpci_spdif_default_get,
.put = snd_ymfpci_spdif_default_put
};
static int snd_ymfpci_spdif_mask_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958;
uinfo->count = 1;
return 0;
}
static int snd_ymfpci_spdif_mask_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
spin_lock_irq(&chip->reg_lock);
ucontrol->value.iec958.status[0] = 0x3e;
ucontrol->value.iec958.status[1] = 0xff;
spin_unlock_irq(&chip->reg_lock);
return 0;
}
static struct snd_kcontrol_new snd_ymfpci_spdif_mask __devinitdata =
{
.access = SNDRV_CTL_ELEM_ACCESS_READ,
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,CON_MASK),
.info = snd_ymfpci_spdif_mask_info,
.get = snd_ymfpci_spdif_mask_get,
};
static int snd_ymfpci_spdif_stream_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958;
uinfo->count = 1;
return 0;
}
static int snd_ymfpci_spdif_stream_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
spin_lock_irq(&chip->reg_lock);
ucontrol->value.iec958.status[0] = (chip->spdif_pcm_bits >> 0) & 0xff;
ucontrol->value.iec958.status[1] = (chip->spdif_pcm_bits >> 8) & 0xff;
ucontrol->value.iec958.status[3] = IEC958_AES3_CON_FS_48000;
spin_unlock_irq(&chip->reg_lock);
return 0;
}
static int snd_ymfpci_spdif_stream_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
unsigned int val;
int change;
val = ((ucontrol->value.iec958.status[0] & 0x3e) << 0) |
(ucontrol->value.iec958.status[1] << 8);
spin_lock_irq(&chip->reg_lock);
change = chip->spdif_pcm_bits != val;
chip->spdif_pcm_bits = val;
if ((snd_ymfpci_readw(chip, YDSXGR_SPDIFOUTCTRL) & 2))
snd_ymfpci_writew(chip, YDSXGR_SPDIFOUTSTATUS, chip->spdif_pcm_bits);
spin_unlock_irq(&chip->reg_lock);
return change;
}
static struct snd_kcontrol_new snd_ymfpci_spdif_stream __devinitdata =
{
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE | SNDRV_CTL_ELEM_ACCESS_INACTIVE,
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,PCM_STREAM),
.info = snd_ymfpci_spdif_stream_info,
.get = snd_ymfpci_spdif_stream_get,
.put = snd_ymfpci_spdif_stream_put
};
static int snd_ymfpci_drec_source_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *info)
{
static const char *const texts[3] = {"AC'97", "IEC958", "ZV Port"};
return snd_ctl_enum_info(info, 1, 3, texts);
}
static int snd_ymfpci_drec_source_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *value)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
u16 reg;
spin_lock_irq(&chip->reg_lock);
reg = snd_ymfpci_readw(chip, YDSXGR_GLOBALCTRL);
spin_unlock_irq(&chip->reg_lock);
if (!(reg & 0x100))
value->value.enumerated.item[0] = 0;
else
value->value.enumerated.item[0] = 1 + ((reg & 0x200) != 0);
return 0;
}
static int snd_ymfpci_drec_source_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *value)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
u16 reg, old_reg;
spin_lock_irq(&chip->reg_lock);
old_reg = snd_ymfpci_readw(chip, YDSXGR_GLOBALCTRL);
if (value->value.enumerated.item[0] == 0)
reg = old_reg & ~0x100;
else
reg = (old_reg & ~0x300) | 0x100 | ((value->value.enumerated.item[0] == 2) << 9);
snd_ymfpci_writew(chip, YDSXGR_GLOBALCTRL, reg);
spin_unlock_irq(&chip->reg_lock);
return reg != old_reg;
}
static struct snd_kcontrol_new snd_ymfpci_drec_source __devinitdata = {
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Direct Recording Source",
.info = snd_ymfpci_drec_source_info,
.get = snd_ymfpci_drec_source_get,
.put = snd_ymfpci_drec_source_put
};
/*
* Mixer controls
*/
#define YMFPCI_SINGLE(xname, xindex, reg, shift) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, .index = xindex, \
.info = snd_ymfpci_info_single, \
.get = snd_ymfpci_get_single, .put = snd_ymfpci_put_single, \
.private_value = ((reg) | ((shift) << 16)) }
#define snd_ymfpci_info_single snd_ctl_boolean_mono_info
static int snd_ymfpci_get_single(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
int reg = kcontrol->private_value & 0xffff;
unsigned int shift = (kcontrol->private_value >> 16) & 0xff;
unsigned int mask = 1;
switch (reg) {
case YDSXGR_SPDIFOUTCTRL: break;
case YDSXGR_SPDIFINCTRL: break;
default: return -EINVAL;
}
ucontrol->value.integer.value[0] =
(snd_ymfpci_readl(chip, reg) >> shift) & mask;
return 0;
}
static int snd_ymfpci_put_single(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
int reg = kcontrol->private_value & 0xffff;
unsigned int shift = (kcontrol->private_value >> 16) & 0xff;
unsigned int mask = 1;
int change;
unsigned int val, oval;
switch (reg) {
case YDSXGR_SPDIFOUTCTRL: break;
case YDSXGR_SPDIFINCTRL: break;
default: return -EINVAL;
}
val = (ucontrol->value.integer.value[0] & mask);
val <<= shift;
spin_lock_irq(&chip->reg_lock);
oval = snd_ymfpci_readl(chip, reg);
val = (oval & ~(mask << shift)) | val;
change = val != oval;
snd_ymfpci_writel(chip, reg, val);
spin_unlock_irq(&chip->reg_lock);
return change;
}
static const DECLARE_TLV_DB_LINEAR(db_scale_native, TLV_DB_GAIN_MUTE, 0);
#define YMFPCI_DOUBLE(xname, xindex, reg) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, .index = xindex, \
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE | SNDRV_CTL_ELEM_ACCESS_TLV_READ, \
.info = snd_ymfpci_info_double, \
.get = snd_ymfpci_get_double, .put = snd_ymfpci_put_double, \
.private_value = reg, \
.tlv = { .p = db_scale_native } }
static int snd_ymfpci_info_double(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
unsigned int reg = kcontrol->private_value;
if (reg < 0x80 || reg >= 0xc0)
return -EINVAL;
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = 16383;
return 0;
}
static int snd_ymfpci_get_double(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
unsigned int reg = kcontrol->private_value;
unsigned int shift_left = 0, shift_right = 16, mask = 16383;
unsigned int val;
if (reg < 0x80 || reg >= 0xc0)
return -EINVAL;
spin_lock_irq(&chip->reg_lock);
val = snd_ymfpci_readl(chip, reg);
spin_unlock_irq(&chip->reg_lock);
ucontrol->value.integer.value[0] = (val >> shift_left) & mask;
ucontrol->value.integer.value[1] = (val >> shift_right) & mask;
return 0;
}
static int snd_ymfpci_put_double(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
unsigned int reg = kcontrol->private_value;
unsigned int shift_left = 0, shift_right = 16, mask = 16383;
int change;
unsigned int val1, val2, oval;
if (reg < 0x80 || reg >= 0xc0)
return -EINVAL;
val1 = ucontrol->value.integer.value[0] & mask;
val2 = ucontrol->value.integer.value[1] & mask;
val1 <<= shift_left;
val2 <<= shift_right;
spin_lock_irq(&chip->reg_lock);
oval = snd_ymfpci_readl(chip, reg);
val1 = (oval & ~((mask << shift_left) | (mask << shift_right))) | val1 | val2;
change = val1 != oval;
snd_ymfpci_writel(chip, reg, val1);
spin_unlock_irq(&chip->reg_lock);
return change;
}
static int snd_ymfpci_put_nativedacvol(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
unsigned int reg = YDSXGR_NATIVEDACOUTVOL;
unsigned int reg2 = YDSXGR_BUF441OUTVOL;
int change;
unsigned int value, oval;
value = ucontrol->value.integer.value[0] & 0x3fff;
value |= (ucontrol->value.integer.value[1] & 0x3fff) << 16;
spin_lock_irq(&chip->reg_lock);
oval = snd_ymfpci_readl(chip, reg);
change = value != oval;
snd_ymfpci_writel(chip, reg, value);
snd_ymfpci_writel(chip, reg2, value);
spin_unlock_irq(&chip->reg_lock);
return change;
}
/*
* 4ch duplication
*/
#define snd_ymfpci_info_dup4ch snd_ctl_boolean_mono_info
static int snd_ymfpci_get_dup4ch(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
ucontrol->value.integer.value[0] = chip->mode_dup4ch;
return 0;
}
static int snd_ymfpci_put_dup4ch(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
int change;
change = (ucontrol->value.integer.value[0] != chip->mode_dup4ch);
if (change)
chip->mode_dup4ch = !!ucontrol->value.integer.value[0];
return change;
}
static struct snd_kcontrol_new snd_ymfpci_controls[] __devinitdata = {
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Wave Playback Volume",
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE |
SNDRV_CTL_ELEM_ACCESS_TLV_READ,
.info = snd_ymfpci_info_double,
.get = snd_ymfpci_get_double,
.put = snd_ymfpci_put_nativedacvol,
.private_value = YDSXGR_NATIVEDACOUTVOL,
.tlv = { .p = db_scale_native },
},
YMFPCI_DOUBLE("Wave Capture Volume", 0, YDSXGR_NATIVEDACLOOPVOL),
YMFPCI_DOUBLE("Digital Capture Volume", 0, YDSXGR_NATIVEDACINVOL),
YMFPCI_DOUBLE("Digital Capture Volume", 1, YDSXGR_NATIVEADCINVOL),
YMFPCI_DOUBLE("ADC Playback Volume", 0, YDSXGR_PRIADCOUTVOL),
YMFPCI_DOUBLE("ADC Capture Volume", 0, YDSXGR_PRIADCLOOPVOL),
YMFPCI_DOUBLE("ADC Playback Volume", 1, YDSXGR_SECADCOUTVOL),
YMFPCI_DOUBLE("ADC Capture Volume", 1, YDSXGR_SECADCLOOPVOL),
YMFPCI_DOUBLE("FM Legacy Volume", 0, YDSXGR_LEGACYOUTVOL),
YMFPCI_DOUBLE(SNDRV_CTL_NAME_IEC958("AC97 ", PLAYBACK,VOLUME), 0, YDSXGR_ZVOUTVOL),
YMFPCI_DOUBLE(SNDRV_CTL_NAME_IEC958("", CAPTURE,VOLUME), 0, YDSXGR_ZVLOOPVOL),
YMFPCI_DOUBLE(SNDRV_CTL_NAME_IEC958("AC97 ",PLAYBACK,VOLUME), 1, YDSXGR_SPDIFOUTVOL),
YMFPCI_DOUBLE(SNDRV_CTL_NAME_IEC958("",CAPTURE,VOLUME), 1, YDSXGR_SPDIFLOOPVOL),
YMFPCI_SINGLE(SNDRV_CTL_NAME_IEC958("",PLAYBACK,SWITCH), 0, YDSXGR_SPDIFOUTCTRL, 0),
YMFPCI_SINGLE(SNDRV_CTL_NAME_IEC958("",CAPTURE,SWITCH), 0, YDSXGR_SPDIFINCTRL, 0),
YMFPCI_SINGLE(SNDRV_CTL_NAME_IEC958("Loop",NONE,NONE), 0, YDSXGR_SPDIFINCTRL, 4),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "4ch Duplication",
.info = snd_ymfpci_info_dup4ch,
.get = snd_ymfpci_get_dup4ch,
.put = snd_ymfpci_put_dup4ch,
},
};
/*
* GPIO
*/
static int snd_ymfpci_get_gpio_out(struct snd_ymfpci *chip, int pin)
{
u16 reg, mode;
unsigned long flags;
spin_lock_irqsave(&chip->reg_lock, flags);
reg = snd_ymfpci_readw(chip, YDSXGR_GPIOFUNCENABLE);
reg &= ~(1 << (pin + 8));
reg |= (1 << pin);
snd_ymfpci_writew(chip, YDSXGR_GPIOFUNCENABLE, reg);
/* set the level mode for input line */
mode = snd_ymfpci_readw(chip, YDSXGR_GPIOTYPECONFIG);
mode &= ~(3 << (pin * 2));
snd_ymfpci_writew(chip, YDSXGR_GPIOTYPECONFIG, mode);
snd_ymfpci_writew(chip, YDSXGR_GPIOFUNCENABLE, reg | (1 << (pin + 8)));
mode = snd_ymfpci_readw(chip, YDSXGR_GPIOINSTATUS);
spin_unlock_irqrestore(&chip->reg_lock, flags);
return (mode >> pin) & 1;
}
static int snd_ymfpci_set_gpio_out(struct snd_ymfpci *chip, int pin, int enable)
{
u16 reg;
unsigned long flags;
spin_lock_irqsave(&chip->reg_lock, flags);
reg = snd_ymfpci_readw(chip, YDSXGR_GPIOFUNCENABLE);
reg &= ~(1 << pin);
reg &= ~(1 << (pin + 8));
snd_ymfpci_writew(chip, YDSXGR_GPIOFUNCENABLE, reg);
snd_ymfpci_writew(chip, YDSXGR_GPIOOUTCTRL, enable << pin);
snd_ymfpci_writew(chip, YDSXGR_GPIOFUNCENABLE, reg | (1 << (pin + 8)));
spin_unlock_irqrestore(&chip->reg_lock, flags);
return 0;
}
#define snd_ymfpci_gpio_sw_info snd_ctl_boolean_mono_info
static int snd_ymfpci_gpio_sw_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
int pin = (int)kcontrol->private_value;
ucontrol->value.integer.value[0] = snd_ymfpci_get_gpio_out(chip, pin);
return 0;
}
static int snd_ymfpci_gpio_sw_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
int pin = (int)kcontrol->private_value;
if (snd_ymfpci_get_gpio_out(chip, pin) != ucontrol->value.integer.value[0]) {
snd_ymfpci_set_gpio_out(chip, pin, !!ucontrol->value.integer.value[0]);
ucontrol->value.integer.value[0] = snd_ymfpci_get_gpio_out(chip, pin);
return 1;
}
return 0;
}
static struct snd_kcontrol_new snd_ymfpci_rear_shared __devinitdata = {
.name = "Shared Rear/Line-In Switch",
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.info = snd_ymfpci_gpio_sw_info,
.get = snd_ymfpci_gpio_sw_get,
.put = snd_ymfpci_gpio_sw_put,
.private_value = 2,
};
/*
* PCM voice volume
*/
static int snd_ymfpci_pcm_vol_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = 0x8000;
return 0;
}
static int snd_ymfpci_pcm_vol_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
unsigned int subs = kcontrol->id.subdevice;
ucontrol->value.integer.value[0] = chip->pcm_mixer[subs].left;
ucontrol->value.integer.value[1] = chip->pcm_mixer[subs].right;
return 0;
}
static int snd_ymfpci_pcm_vol_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
unsigned int subs = kcontrol->id.subdevice;
struct snd_pcm_substream *substream;
unsigned long flags;
if (ucontrol->value.integer.value[0] != chip->pcm_mixer[subs].left ||
ucontrol->value.integer.value[1] != chip->pcm_mixer[subs].right) {
chip->pcm_mixer[subs].left = ucontrol->value.integer.value[0];
chip->pcm_mixer[subs].right = ucontrol->value.integer.value[1];
if (chip->pcm_mixer[subs].left > 0x8000)
chip->pcm_mixer[subs].left = 0x8000;
if (chip->pcm_mixer[subs].right > 0x8000)
chip->pcm_mixer[subs].right = 0x8000;
substream = (struct snd_pcm_substream *)kcontrol->private_value;
spin_lock_irqsave(&chip->voice_lock, flags);
if (substream->runtime && substream->runtime->private_data) {
struct snd_ymfpci_pcm *ypcm = substream->runtime->private_data;
if (!ypcm->use_441_slot)
ypcm->update_pcm_vol = 2;
}
spin_unlock_irqrestore(&chip->voice_lock, flags);
return 1;
}
return 0;
}
static struct snd_kcontrol_new snd_ymfpci_pcm_volume __devinitdata = {
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.name = "PCM Playback Volume",
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE |
SNDRV_CTL_ELEM_ACCESS_INACTIVE,
.info = snd_ymfpci_pcm_vol_info,
.get = snd_ymfpci_pcm_vol_get,
.put = snd_ymfpci_pcm_vol_put,
};
/*
* Mixer routines
*/
static void snd_ymfpci_mixer_free_ac97_bus(struct snd_ac97_bus *bus)
{
struct snd_ymfpci *chip = bus->private_data;
chip->ac97_bus = NULL;
}
static void snd_ymfpci_mixer_free_ac97(struct snd_ac97 *ac97)
{
struct snd_ymfpci *chip = ac97->private_data;
chip->ac97 = NULL;
}
int __devinit snd_ymfpci_mixer(struct snd_ymfpci *chip, int rear_switch)
{
struct snd_ac97_template ac97;
struct snd_kcontrol *kctl;
struct snd_pcm_substream *substream;
unsigned int idx;
int err;
static struct snd_ac97_bus_ops ops = {
.write = snd_ymfpci_codec_write,
.read = snd_ymfpci_codec_read,
};
if ((err = snd_ac97_bus(chip->card, 0, &ops, chip, &chip->ac97_bus)) < 0)
return err;
chip->ac97_bus->private_free = snd_ymfpci_mixer_free_ac97_bus;
chip->ac97_bus->no_vra = 1; /* YMFPCI doesn't need VRA */
memset(&ac97, 0, sizeof(ac97));
ac97.private_data = chip;
ac97.private_free = snd_ymfpci_mixer_free_ac97;
if ((err = snd_ac97_mixer(chip->ac97_bus, &ac97, &chip->ac97)) < 0)
return err;
/* to be sure */
snd_ac97_update_bits(chip->ac97, AC97_EXTENDED_STATUS,
AC97_EA_VRA|AC97_EA_VRM, 0);
for (idx = 0; idx < ARRAY_SIZE(snd_ymfpci_controls); idx++) {
if ((err = snd_ctl_add(chip->card, snd_ctl_new1(&snd_ymfpci_controls[idx], chip))) < 0)
return err;
}
/* add S/PDIF control */
if (snd_BUG_ON(!chip->pcm_spdif))
return -ENXIO;
if ((err = snd_ctl_add(chip->card, kctl = snd_ctl_new1(&snd_ymfpci_spdif_default, chip))) < 0)
return err;
kctl->id.device = chip->pcm_spdif->device;
if ((err = snd_ctl_add(chip->card, kctl = snd_ctl_new1(&snd_ymfpci_spdif_mask, chip))) < 0)
return err;
kctl->id.device = chip->pcm_spdif->device;
if ((err = snd_ctl_add(chip->card, kctl = snd_ctl_new1(&snd_ymfpci_spdif_stream, chip))) < 0)
return err;
kctl->id.device = chip->pcm_spdif->device;
chip->spdif_pcm_ctl = kctl;
/* direct recording source */
if (chip->device_id == PCI_DEVICE_ID_YAMAHA_754 &&
(err = snd_ctl_add(chip->card, kctl = snd_ctl_new1(&snd_ymfpci_drec_source, chip))) < 0)
return err;
/*
* shared rear/line-in
*/
if (rear_switch) {
if ((err = snd_ctl_add(chip->card, snd_ctl_new1(&snd_ymfpci_rear_shared, chip))) < 0)
return err;
}
/* per-voice volume */
substream = chip->pcm->streams[SNDRV_PCM_STREAM_PLAYBACK].substream;
for (idx = 0; idx < 32; ++idx) {
kctl = snd_ctl_new1(&snd_ymfpci_pcm_volume, chip);
if (!kctl)
return -ENOMEM;
kctl->id.device = chip->pcm->device;
kctl->id.subdevice = idx;
kctl->private_value = (unsigned long)substream;
if ((err = snd_ctl_add(chip->card, kctl)) < 0)
return err;
chip->pcm_mixer[idx].left = 0x8000;
chip->pcm_mixer[idx].right = 0x8000;
chip->pcm_mixer[idx].ctl = kctl;
substream = substream->next;
}
return 0;
}
/*
* timer
*/
static int snd_ymfpci_timer_start(struct snd_timer *timer)
{
struct snd_ymfpci *chip;
unsigned long flags;
unsigned int count;
chip = snd_timer_chip(timer);
spin_lock_irqsave(&chip->reg_lock, flags);
if (timer->sticks > 1) {
chip->timer_ticks = timer->sticks;
count = timer->sticks - 1;
} else {
/*
* Divisor 1 is not allowed; fake it by using divisor 2 and
* counting two ticks for each interrupt.
*/
chip->timer_ticks = 2;
count = 2 - 1;
}
snd_ymfpci_writew(chip, YDSXGR_TIMERCOUNT, count);
snd_ymfpci_writeb(chip, YDSXGR_TIMERCTRL, 0x03);
spin_unlock_irqrestore(&chip->reg_lock, flags);
return 0;
}
static int snd_ymfpci_timer_stop(struct snd_timer *timer)
{
struct snd_ymfpci *chip;
unsigned long flags;
chip = snd_timer_chip(timer);
spin_lock_irqsave(&chip->reg_lock, flags);
snd_ymfpci_writeb(chip, YDSXGR_TIMERCTRL, 0x00);
spin_unlock_irqrestore(&chip->reg_lock, flags);
return 0;
}
static int snd_ymfpci_timer_precise_resolution(struct snd_timer *timer,
unsigned long *num, unsigned long *den)
{
*num = 1;
*den = 96000;
return 0;
}
static struct snd_timer_hardware snd_ymfpci_timer_hw = {
.flags = SNDRV_TIMER_HW_AUTO,
.resolution = 10417, /* 1 / 96 kHz = 10.41666...us */
.ticks = 0x10000,
.start = snd_ymfpci_timer_start,
.stop = snd_ymfpci_timer_stop,
.precise_resolution = snd_ymfpci_timer_precise_resolution,
};
int __devinit snd_ymfpci_timer(struct snd_ymfpci *chip, int device)
{
struct snd_timer *timer = NULL;
struct snd_timer_id tid;
int err;
tid.dev_class = SNDRV_TIMER_CLASS_CARD;
tid.dev_sclass = SNDRV_TIMER_SCLASS_NONE;
tid.card = chip->card->number;
tid.device = device;
tid.subdevice = 0;
if ((err = snd_timer_new(chip->card, "YMFPCI", &tid, &timer)) >= 0) {
strcpy(timer->name, "YMFPCI timer");
timer->private_data = chip;
timer->hw = snd_ymfpci_timer_hw;
}
chip->timer = timer;
return err;
}
/*
* proc interface
*/
static void snd_ymfpci_proc_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_ymfpci *chip = entry->private_data;
int i;
snd_iprintf(buffer, "YMFPCI\n\n");
for (i = 0; i <= YDSXGR_WORKBASE; i += 4)
snd_iprintf(buffer, "%04x: %04x\n", i, snd_ymfpci_readl(chip, i));
}
static int __devinit snd_ymfpci_proc_init(struct snd_card *card, struct snd_ymfpci *chip)
{
struct snd_info_entry *entry;
if (! snd_card_proc_new(card, "ymfpci", &entry))
snd_info_set_text_ops(entry, chip, snd_ymfpci_proc_read);
return 0;
}
/*
* initialization routines
*/
static void snd_ymfpci_aclink_reset(struct pci_dev * pci)
{
u8 cmd;
pci_read_config_byte(pci, PCIR_DSXG_CTRL, &cmd);
#if 0 // force to reset
if (cmd & 0x03) {
#endif
pci_write_config_byte(pci, PCIR_DSXG_CTRL, cmd & 0xfc);
pci_write_config_byte(pci, PCIR_DSXG_CTRL, cmd | 0x03);
pci_write_config_byte(pci, PCIR_DSXG_CTRL, cmd & 0xfc);
pci_write_config_word(pci, PCIR_DSXG_PWRCTRL1, 0);
pci_write_config_word(pci, PCIR_DSXG_PWRCTRL2, 0);
#if 0
}
#endif
}
static void snd_ymfpci_enable_dsp(struct snd_ymfpci *chip)
{
snd_ymfpci_writel(chip, YDSXGR_CONFIG, 0x00000001);
}
static void snd_ymfpci_disable_dsp(struct snd_ymfpci *chip)
{
u32 val;
int timeout = 1000;
val = snd_ymfpci_readl(chip, YDSXGR_CONFIG);
if (val)
snd_ymfpci_writel(chip, YDSXGR_CONFIG, 0x00000000);
while (timeout-- > 0) {
val = snd_ymfpci_readl(chip, YDSXGR_STATUS);
if ((val & 0x00000002) == 0)
break;
}
}
static int snd_ymfpci_request_firmware(struct snd_ymfpci *chip)
{
int err, is_1e;
const char *name;
err = request_firmware(&chip->dsp_microcode, "yamaha/ds1_dsp.fw",
&chip->pci->dev);
if (err >= 0) {
if (chip->dsp_microcode->size != YDSXG_DSPLENGTH) {
snd_printk(KERN_ERR "DSP microcode has wrong size\n");
err = -EINVAL;
}
}
if (err < 0)
return err;
is_1e = chip->device_id == PCI_DEVICE_ID_YAMAHA_724F ||
chip->device_id == PCI_DEVICE_ID_YAMAHA_740C ||
chip->device_id == PCI_DEVICE_ID_YAMAHA_744 ||
chip->device_id == PCI_DEVICE_ID_YAMAHA_754;
name = is_1e ? "yamaha/ds1e_ctrl.fw" : "yamaha/ds1_ctrl.fw";
err = request_firmware(&chip->controller_microcode, name,
&chip->pci->dev);
if (err >= 0) {
if (chip->controller_microcode->size != YDSXG_CTRLLENGTH) {
snd_printk(KERN_ERR "controller microcode"
" has wrong size\n");
err = -EINVAL;
}
}
if (err < 0)
return err;
return 0;
}
MODULE_FIRMWARE("yamaha/ds1_dsp.fw");
MODULE_FIRMWARE("yamaha/ds1_ctrl.fw");
MODULE_FIRMWARE("yamaha/ds1e_ctrl.fw");
static void snd_ymfpci_download_image(struct snd_ymfpci *chip)
{
int i;
u16 ctrl;
const __le32 *inst;
snd_ymfpci_writel(chip, YDSXGR_NATIVEDACOUTVOL, 0x00000000);
snd_ymfpci_disable_dsp(chip);
snd_ymfpci_writel(chip, YDSXGR_MODE, 0x00010000);
snd_ymfpci_writel(chip, YDSXGR_MODE, 0x00000000);
snd_ymfpci_writel(chip, YDSXGR_MAPOFREC, 0x00000000);
snd_ymfpci_writel(chip, YDSXGR_MAPOFEFFECT, 0x00000000);
snd_ymfpci_writel(chip, YDSXGR_PLAYCTRLBASE, 0x00000000);
snd_ymfpci_writel(chip, YDSXGR_RECCTRLBASE, 0x00000000);
snd_ymfpci_writel(chip, YDSXGR_EFFCTRLBASE, 0x00000000);
ctrl = snd_ymfpci_readw(chip, YDSXGR_GLOBALCTRL);
snd_ymfpci_writew(chip, YDSXGR_GLOBALCTRL, ctrl & ~0x0007);
/* setup DSP instruction code */
inst = (const __le32 *)chip->dsp_microcode->data;
for (i = 0; i < YDSXG_DSPLENGTH / 4; i++)
snd_ymfpci_writel(chip, YDSXGR_DSPINSTRAM + (i << 2),
le32_to_cpu(inst[i]));
/* setup control instruction code */
inst = (const __le32 *)chip->controller_microcode->data;
for (i = 0; i < YDSXG_CTRLLENGTH / 4; i++)
snd_ymfpci_writel(chip, YDSXGR_CTRLINSTRAM + (i << 2),
le32_to_cpu(inst[i]));
snd_ymfpci_enable_dsp(chip);
}
static int __devinit snd_ymfpci_memalloc(struct snd_ymfpci *chip)
{
long size, playback_ctrl_size;
int voice, bank, reg;
u8 *ptr;
dma_addr_t ptr_addr;
playback_ctrl_size = 4 + 4 * YDSXG_PLAYBACK_VOICES;
chip->bank_size_playback = snd_ymfpci_readl(chip, YDSXGR_PLAYCTRLSIZE) << 2;
chip->bank_size_capture = snd_ymfpci_readl(chip, YDSXGR_RECCTRLSIZE) << 2;
chip->bank_size_effect = snd_ymfpci_readl(chip, YDSXGR_EFFCTRLSIZE) << 2;
chip->work_size = YDSXG_DEFAULT_WORK_SIZE;
size = ALIGN(playback_ctrl_size, 0x100) +
ALIGN(chip->bank_size_playback * 2 * YDSXG_PLAYBACK_VOICES, 0x100) +
ALIGN(chip->bank_size_capture * 2 * YDSXG_CAPTURE_VOICES, 0x100) +
ALIGN(chip->bank_size_effect * 2 * YDSXG_EFFECT_VOICES, 0x100) +
chip->work_size;
/* work_ptr must be aligned to 256 bytes, but it's already
covered with the kernel page allocation mechanism */
if (snd_dma_alloc_pages(SNDRV_DMA_TYPE_DEV, snd_dma_pci_data(chip->pci),
size, &chip->work_ptr) < 0)
return -ENOMEM;
ptr = chip->work_ptr.area;
ptr_addr = chip->work_ptr.addr;
memset(ptr, 0, size); /* for sure */
chip->bank_base_playback = ptr;
chip->bank_base_playback_addr = ptr_addr;
chip->ctrl_playback = (u32 *)ptr;
chip->ctrl_playback[0] = cpu_to_le32(YDSXG_PLAYBACK_VOICES);
ptr += ALIGN(playback_ctrl_size, 0x100);
ptr_addr += ALIGN(playback_ctrl_size, 0x100);
for (voice = 0; voice < YDSXG_PLAYBACK_VOICES; voice++) {
chip->voices[voice].number = voice;
chip->voices[voice].bank = (struct snd_ymfpci_playback_bank *)ptr;
chip->voices[voice].bank_addr = ptr_addr;
for (bank = 0; bank < 2; bank++) {
chip->bank_playback[voice][bank] = (struct snd_ymfpci_playback_bank *)ptr;
ptr += chip->bank_size_playback;
ptr_addr += chip->bank_size_playback;
}
}
ptr = (char *)ALIGN((unsigned long)ptr, 0x100);
ptr_addr = ALIGN(ptr_addr, 0x100);
chip->bank_base_capture = ptr;
chip->bank_base_capture_addr = ptr_addr;
for (voice = 0; voice < YDSXG_CAPTURE_VOICES; voice++)
for (bank = 0; bank < 2; bank++) {
chip->bank_capture[voice][bank] = (struct snd_ymfpci_capture_bank *)ptr;
ptr += chip->bank_size_capture;
ptr_addr += chip->bank_size_capture;
}
ptr = (char *)ALIGN((unsigned long)ptr, 0x100);
ptr_addr = ALIGN(ptr_addr, 0x100);
chip->bank_base_effect = ptr;
chip->bank_base_effect_addr = ptr_addr;
for (voice = 0; voice < YDSXG_EFFECT_VOICES; voice++)
for (bank = 0; bank < 2; bank++) {
chip->bank_effect[voice][bank] = (struct snd_ymfpci_effect_bank *)ptr;
ptr += chip->bank_size_effect;
ptr_addr += chip->bank_size_effect;
}
ptr = (char *)ALIGN((unsigned long)ptr, 0x100);
ptr_addr = ALIGN(ptr_addr, 0x100);
chip->work_base = ptr;
chip->work_base_addr = ptr_addr;
snd_BUG_ON(ptr + chip->work_size !=
chip->work_ptr.area + chip->work_ptr.bytes);
snd_ymfpci_writel(chip, YDSXGR_PLAYCTRLBASE, chip->bank_base_playback_addr);
snd_ymfpci_writel(chip, YDSXGR_RECCTRLBASE, chip->bank_base_capture_addr);
snd_ymfpci_writel(chip, YDSXGR_EFFCTRLBASE, chip->bank_base_effect_addr);
snd_ymfpci_writel(chip, YDSXGR_WORKBASE, chip->work_base_addr);
snd_ymfpci_writel(chip, YDSXGR_WORKSIZE, chip->work_size >> 2);
/* S/PDIF output initialization */
chip->spdif_bits = chip->spdif_pcm_bits = SNDRV_PCM_DEFAULT_CON_SPDIF & 0xffff;
snd_ymfpci_writew(chip, YDSXGR_SPDIFOUTCTRL, 0);
snd_ymfpci_writew(chip, YDSXGR_SPDIFOUTSTATUS, chip->spdif_bits);
/* S/PDIF input initialization */
snd_ymfpci_writew(chip, YDSXGR_SPDIFINCTRL, 0);
/* digital mixer setup */
for (reg = 0x80; reg < 0xc0; reg += 4)
snd_ymfpci_writel(chip, reg, 0);
snd_ymfpci_writel(chip, YDSXGR_NATIVEDACOUTVOL, 0x3fff3fff);
snd_ymfpci_writel(chip, YDSXGR_BUF441OUTVOL, 0x3fff3fff);
snd_ymfpci_writel(chip, YDSXGR_ZVOUTVOL, 0x3fff3fff);
snd_ymfpci_writel(chip, YDSXGR_SPDIFOUTVOL, 0x3fff3fff);
snd_ymfpci_writel(chip, YDSXGR_NATIVEADCINVOL, 0x3fff3fff);
snd_ymfpci_writel(chip, YDSXGR_NATIVEDACINVOL, 0x3fff3fff);
snd_ymfpci_writel(chip, YDSXGR_PRIADCLOOPVOL, 0x3fff3fff);
snd_ymfpci_writel(chip, YDSXGR_LEGACYOUTVOL, 0x3fff3fff);
return 0;
}
static int snd_ymfpci_free(struct snd_ymfpci *chip)
{
u16 ctrl;
if (snd_BUG_ON(!chip))
return -EINVAL;
if (chip->res_reg_area) { /* don't touch busy hardware */
snd_ymfpci_writel(chip, YDSXGR_NATIVEDACOUTVOL, 0);
snd_ymfpci_writel(chip, YDSXGR_BUF441OUTVOL, 0);
snd_ymfpci_writel(chip, YDSXGR_LEGACYOUTVOL, 0);
snd_ymfpci_writel(chip, YDSXGR_STATUS, ~0);
snd_ymfpci_disable_dsp(chip);
snd_ymfpci_writel(chip, YDSXGR_PLAYCTRLBASE, 0);
snd_ymfpci_writel(chip, YDSXGR_RECCTRLBASE, 0);
snd_ymfpci_writel(chip, YDSXGR_EFFCTRLBASE, 0);
snd_ymfpci_writel(chip, YDSXGR_WORKBASE, 0);
snd_ymfpci_writel(chip, YDSXGR_WORKSIZE, 0);
ctrl = snd_ymfpci_readw(chip, YDSXGR_GLOBALCTRL);
snd_ymfpci_writew(chip, YDSXGR_GLOBALCTRL, ctrl & ~0x0007);
}
snd_ymfpci_ac3_done(chip);
/* Set PCI device to D3 state */
#if 0
/* FIXME: temporarily disabled, otherwise we cannot fire up
* the chip again unless reboot. ACPI bug?
*/
pci_set_power_state(chip->pci, 3);
#endif
#ifdef CONFIG_PM
vfree(chip->saved_regs);
#endif
if (chip->irq >= 0)
free_irq(chip->irq, chip);
release_and_free_resource(chip->mpu_res);
release_and_free_resource(chip->fm_res);
snd_ymfpci_free_gameport(chip);
if (chip->reg_area_virt)
iounmap(chip->reg_area_virt);
if (chip->work_ptr.area)
snd_dma_free_pages(&chip->work_ptr);
release_and_free_resource(chip->res_reg_area);
pci_write_config_word(chip->pci, 0x40, chip->old_legacy_ctrl);
pci_disable_device(chip->pci);
release_firmware(chip->dsp_microcode);
release_firmware(chip->controller_microcode);
kfree(chip);
return 0;
}
static int snd_ymfpci_dev_free(struct snd_device *device)
{
struct snd_ymfpci *chip = device->device_data;
return snd_ymfpci_free(chip);
}
#ifdef CONFIG_PM
static int saved_regs_index[] = {
/* spdif */
YDSXGR_SPDIFOUTCTRL,
YDSXGR_SPDIFOUTSTATUS,
YDSXGR_SPDIFINCTRL,
/* volumes */
YDSXGR_PRIADCLOOPVOL,
YDSXGR_NATIVEDACINVOL,
YDSXGR_NATIVEDACOUTVOL,
YDSXGR_BUF441OUTVOL,
YDSXGR_NATIVEADCINVOL,
YDSXGR_SPDIFLOOPVOL,
YDSXGR_SPDIFOUTVOL,
YDSXGR_ZVOUTVOL,
YDSXGR_LEGACYOUTVOL,
/* address bases */
YDSXGR_PLAYCTRLBASE,
YDSXGR_RECCTRLBASE,
YDSXGR_EFFCTRLBASE,
YDSXGR_WORKBASE,
/* capture set up */
YDSXGR_MAPOFREC,
YDSXGR_RECFORMAT,
YDSXGR_RECSLOTSR,
YDSXGR_ADCFORMAT,
YDSXGR_ADCSLOTSR,
};
#define YDSXGR_NUM_SAVED_REGS ARRAY_SIZE(saved_regs_index)
int snd_ymfpci_suspend(struct pci_dev *pci, pm_message_t state)
{
struct snd_card *card = pci_get_drvdata(pci);
struct snd_ymfpci *chip = card->private_data;
unsigned int i;
snd_power_change_state(card, SNDRV_CTL_POWER_D3hot);
snd_pcm_suspend_all(chip->pcm);
snd_pcm_suspend_all(chip->pcm2);
snd_pcm_suspend_all(chip->pcm_spdif);
snd_pcm_suspend_all(chip->pcm_4ch);
snd_ac97_suspend(chip->ac97);
for (i = 0; i < YDSXGR_NUM_SAVED_REGS; i++)
chip->saved_regs[i] = snd_ymfpci_readl(chip, saved_regs_index[i]);
chip->saved_ydsxgr_mode = snd_ymfpci_readl(chip, YDSXGR_MODE);
snd_ymfpci_writel(chip, YDSXGR_NATIVEDACOUTVOL, 0);
snd_ymfpci_writel(chip, YDSXGR_BUF441OUTVOL, 0);
snd_ymfpci_disable_dsp(chip);
pci_disable_device(pci);
pci_save_state(pci);
pci_set_power_state(pci, pci_choose_state(pci, state));
return 0;
}
int snd_ymfpci_resume(struct pci_dev *pci)
{
struct snd_card *card = pci_get_drvdata(pci);
struct snd_ymfpci *chip = card->private_data;
unsigned int i;
pci_set_power_state(pci, PCI_D0);
pci_restore_state(pci);
if (pci_enable_device(pci) < 0) {
printk(KERN_ERR "ymfpci: pci_enable_device failed, "
"disabling device\n");
snd_card_disconnect(card);
return -EIO;
}
pci_set_master(pci);
snd_ymfpci_aclink_reset(pci);
snd_ymfpci_codec_ready(chip, 0);
snd_ymfpci_download_image(chip);
udelay(100);
for (i = 0; i < YDSXGR_NUM_SAVED_REGS; i++)
snd_ymfpci_writel(chip, saved_regs_index[i], chip->saved_regs[i]);
snd_ac97_resume(chip->ac97);
/* start hw again */
if (chip->start_count > 0) {
spin_lock_irq(&chip->reg_lock);
snd_ymfpci_writel(chip, YDSXGR_MODE, chip->saved_ydsxgr_mode);
chip->active_bank = snd_ymfpci_readl(chip, YDSXGR_CTRLSELECT);
spin_unlock_irq(&chip->reg_lock);
}
snd_power_change_state(card, SNDRV_CTL_POWER_D0);
return 0;
}
#endif /* CONFIG_PM */
int __devinit snd_ymfpci_create(struct snd_card *card,
struct pci_dev * pci,
unsigned short old_legacy_ctrl,
struct snd_ymfpci ** rchip)
{
struct snd_ymfpci *chip;
int err;
static struct snd_device_ops ops = {
.dev_free = snd_ymfpci_dev_free,
};
*rchip = NULL;
/* enable PCI device */
if ((err = pci_enable_device(pci)) < 0)
return err;
chip = kzalloc(sizeof(*chip), GFP_KERNEL);
if (chip == NULL) {
pci_disable_device(pci);
return -ENOMEM;
}
chip->old_legacy_ctrl = old_legacy_ctrl;
spin_lock_init(&chip->reg_lock);
spin_lock_init(&chip->voice_lock);
init_waitqueue_head(&chip->interrupt_sleep);
atomic_set(&chip->interrupt_sleep_count, 0);
chip->card = card;
chip->pci = pci;
chip->irq = -1;
chip->device_id = pci->device;
chip->rev = pci->revision;
chip->reg_area_phys = pci_resource_start(pci, 0);
chip->reg_area_virt = ioremap_nocache(chip->reg_area_phys, 0x8000);
pci_set_master(pci);
chip->src441_used = -1;
if ((chip->res_reg_area = request_mem_region(chip->reg_area_phys, 0x8000, "YMFPCI")) == NULL) {
snd_printk(KERN_ERR "unable to grab memory region 0x%lx-0x%lx\n", chip->reg_area_phys, chip->reg_area_phys + 0x8000 - 1);
snd_ymfpci_free(chip);
return -EBUSY;
}
if (request_irq(pci->irq, snd_ymfpci_interrupt, IRQF_SHARED,
"YMFPCI", chip)) {
snd_printk(KERN_ERR "unable to grab IRQ %d\n", pci->irq);
snd_ymfpci_free(chip);
return -EBUSY;
}
chip->irq = pci->irq;
snd_ymfpci_aclink_reset(pci);
if (snd_ymfpci_codec_ready(chip, 0) < 0) {
snd_ymfpci_free(chip);
return -EIO;
}
err = snd_ymfpci_request_firmware(chip);
if (err < 0) {
snd_printk(KERN_ERR "firmware request failed: %d\n", err);
snd_ymfpci_free(chip);
return err;
}
snd_ymfpci_download_image(chip);
udelay(100); /* seems we need a delay after downloading image.. */
if (snd_ymfpci_memalloc(chip) < 0) {
snd_ymfpci_free(chip);
return -EIO;
}
if ((err = snd_ymfpci_ac3_init(chip)) < 0) {
snd_ymfpci_free(chip);
return err;
}
#ifdef CONFIG_PM
chip->saved_regs = vmalloc(YDSXGR_NUM_SAVED_REGS * sizeof(u32));
if (chip->saved_regs == NULL) {
snd_ymfpci_free(chip);
return -ENOMEM;
}
#endif
if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops)) < 0) {
snd_ymfpci_free(chip);
return err;
}
snd_ymfpci_proc_init(card, chip);
snd_card_set_dev(card, &pci->dev);
*rchip = chip;
return 0;
}
| gpl-2.0 |
edoko/AIR-Kernel_ICS | drivers/s390/block/dasd_eer.c | 2627 | 20443 | /*
* Character device driver for extended error reporting.
*
* Copyright (C) 2005 IBM Corporation
* extended error reporting for DASD ECKD devices
* Author(s): Stefan Weinhuber <wein@de.ibm.com>
*/
#define KMSG_COMPONENT "dasd-eckd"
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/miscdevice.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/device.h>
#include <linux/poll.h>
#include <linux/mutex.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
#include <asm/atomic.h>
#include <asm/ebcdic.h>
#include "dasd_int.h"
#include "dasd_eckd.h"
#ifdef PRINTK_HEADER
#undef PRINTK_HEADER
#endif /* PRINTK_HEADER */
#define PRINTK_HEADER "dasd(eer):"
/*
* SECTION: the internal buffer
*/
/*
* The internal buffer is meant to store obaque blobs of data, so it does
* not know of higher level concepts like triggers.
* It consists of a number of pages that are used as a ringbuffer. Each data
* blob is stored in a simple record that consists of an integer, which
* contains the size of the following data, and the data bytes themselfes.
*
* To allow for multiple independent readers we create one internal buffer
* each time the device is opened and destroy the buffer when the file is
* closed again. The number of pages used for this buffer is determined by
* the module parmeter eer_pages.
*
* One record can be written to a buffer by using the functions
* - dasd_eer_start_record (one time per record to write the size to the
* buffer and reserve the space for the data)
* - dasd_eer_write_buffer (one or more times per record to write the data)
* The data can be written in several steps but you will have to compute
* the total size up front for the invocation of dasd_eer_start_record.
* If the ringbuffer is full, dasd_eer_start_record will remove the required
* number of old records.
*
* A record is typically read in two steps, first read the integer that
* specifies the size of the following data, then read the data.
* Both can be done by
* - dasd_eer_read_buffer
*
* For all mentioned functions you need to get the bufferlock first and keep
* it until a complete record is written or read.
*
* All information necessary to keep track of an internal buffer is kept in
* a struct eerbuffer. The buffer specific to a file pointer is strored in
* the private_data field of that file. To be able to write data to all
* existing buffers, each buffer is also added to the bufferlist.
* If the user does not want to read a complete record in one go, we have to
* keep track of the rest of the record. residual stores the number of bytes
* that are still to deliver. If the rest of the record is invalidated between
* two reads then residual will be set to -1 so that the next read will fail.
* All entries in the eerbuffer structure are protected with the bufferlock.
* To avoid races between writing to a buffer on the one side and creating
* and destroying buffers on the other side, the bufferlock must also be used
* to protect the bufferlist.
*/
static int eer_pages = 5;
module_param(eer_pages, int, S_IRUGO|S_IWUSR);
struct eerbuffer {
struct list_head list;
char **buffer;
int buffersize;
int buffer_page_count;
int head;
int tail;
int residual;
};
static LIST_HEAD(bufferlist);
static DEFINE_SPINLOCK(bufferlock);
static DECLARE_WAIT_QUEUE_HEAD(dasd_eer_read_wait_queue);
/*
* How many free bytes are available on the buffer.
* Needs to be called with bufferlock held.
*/
static int dasd_eer_get_free_bytes(struct eerbuffer *eerb)
{
if (eerb->head < eerb->tail)
return eerb->tail - eerb->head - 1;
return eerb->buffersize - eerb->head + eerb->tail -1;
}
/*
* How many bytes of buffer space are used.
* Needs to be called with bufferlock held.
*/
static int dasd_eer_get_filled_bytes(struct eerbuffer *eerb)
{
if (eerb->head >= eerb->tail)
return eerb->head - eerb->tail;
return eerb->buffersize - eerb->tail + eerb->head;
}
/*
* The dasd_eer_write_buffer function just copies count bytes of data
* to the buffer. Make sure to call dasd_eer_start_record first, to
* make sure that enough free space is available.
* Needs to be called with bufferlock held.
*/
static void dasd_eer_write_buffer(struct eerbuffer *eerb,
char *data, int count)
{
unsigned long headindex,localhead;
unsigned long rest, len;
char *nextdata;
nextdata = data;
rest = count;
while (rest > 0) {
headindex = eerb->head / PAGE_SIZE;
localhead = eerb->head % PAGE_SIZE;
len = min(rest, PAGE_SIZE - localhead);
memcpy(eerb->buffer[headindex]+localhead, nextdata, len);
nextdata += len;
rest -= len;
eerb->head += len;
if (eerb->head == eerb->buffersize)
eerb->head = 0; /* wrap around */
BUG_ON(eerb->head > eerb->buffersize);
}
}
/*
* Needs to be called with bufferlock held.
*/
static int dasd_eer_read_buffer(struct eerbuffer *eerb, char *data, int count)
{
unsigned long tailindex,localtail;
unsigned long rest, len, finalcount;
char *nextdata;
finalcount = min(count, dasd_eer_get_filled_bytes(eerb));
nextdata = data;
rest = finalcount;
while (rest > 0) {
tailindex = eerb->tail / PAGE_SIZE;
localtail = eerb->tail % PAGE_SIZE;
len = min(rest, PAGE_SIZE - localtail);
memcpy(nextdata, eerb->buffer[tailindex] + localtail, len);
nextdata += len;
rest -= len;
eerb->tail += len;
if (eerb->tail == eerb->buffersize)
eerb->tail = 0; /* wrap around */
BUG_ON(eerb->tail > eerb->buffersize);
}
return finalcount;
}
/*
* Whenever you want to write a blob of data to the internal buffer you
* have to start by using this function first. It will write the number
* of bytes that will be written to the buffer. If necessary it will remove
* old records to make room for the new one.
* Needs to be called with bufferlock held.
*/
static int dasd_eer_start_record(struct eerbuffer *eerb, int count)
{
int tailcount;
if (count + sizeof(count) > eerb->buffersize)
return -ENOMEM;
while (dasd_eer_get_free_bytes(eerb) < count + sizeof(count)) {
if (eerb->residual > 0) {
eerb->tail += eerb->residual;
if (eerb->tail >= eerb->buffersize)
eerb->tail -= eerb->buffersize;
eerb->residual = -1;
}
dasd_eer_read_buffer(eerb, (char *) &tailcount,
sizeof(tailcount));
eerb->tail += tailcount;
if (eerb->tail >= eerb->buffersize)
eerb->tail -= eerb->buffersize;
}
dasd_eer_write_buffer(eerb, (char*) &count, sizeof(count));
return 0;
};
/*
* Release pages that are not used anymore.
*/
static void dasd_eer_free_buffer_pages(char **buf, int no_pages)
{
int i;
for (i = 0; i < no_pages; i++)
free_page((unsigned long) buf[i]);
}
/*
* Allocate a new set of memory pages.
*/
static int dasd_eer_allocate_buffer_pages(char **buf, int no_pages)
{
int i;
for (i = 0; i < no_pages; i++) {
buf[i] = (char *) get_zeroed_page(GFP_KERNEL);
if (!buf[i]) {
dasd_eer_free_buffer_pages(buf, i);
return -ENOMEM;
}
}
return 0;
}
/*
* SECTION: The extended error reporting functionality
*/
/*
* When a DASD device driver wants to report an error, it calls the
* function dasd_eer_write and gives the respective trigger ID as
* parameter. Currently there are four kinds of triggers:
*
* DASD_EER_FATALERROR: all kinds of unrecoverable I/O problems
* DASD_EER_PPRCSUSPEND: PPRC was suspended
* DASD_EER_NOPATH: There is no path to the device left.
* DASD_EER_STATECHANGE: The state of the device has changed.
*
* For the first three triggers all required information can be supplied by
* the caller. For these triggers a record is written by the function
* dasd_eer_write_standard_trigger.
*
* The DASD_EER_STATECHANGE trigger is special since a sense subsystem
* status ccw need to be executed to gather the necessary sense data first.
* The dasd_eer_snss function will queue the SNSS request and the request
* callback will then call dasd_eer_write with the DASD_EER_STATCHANGE
* trigger.
*
* To avoid memory allocations at runtime, the necessary memory is allocated
* when the extended error reporting is enabled for a device (by
* dasd_eer_probe). There is one sense subsystem status request for each
* eer enabled DASD device. The presence of the cqr in device->eer_cqr
* indicates that eer is enable for the device. The use of the snss request
* is protected by the DASD_FLAG_EER_IN_USE bit. When this flag indicates
* that the cqr is currently in use, dasd_eer_snss cannot start a second
* request but sets the DASD_FLAG_EER_SNSS flag instead. The callback of
* the SNSS request will check the bit and call dasd_eer_snss again.
*/
#define SNSS_DATA_SIZE 44
#define DASD_EER_BUSID_SIZE 10
struct dasd_eer_header {
__u32 total_size;
__u32 trigger;
__u64 tv_sec;
__u64 tv_usec;
char busid[DASD_EER_BUSID_SIZE];
} __attribute__ ((packed));
/*
* The following function can be used for those triggers that have
* all necessary data available when the function is called.
* If the parameter cqr is not NULL, the chain of requests will be searched
* for valid sense data, and all valid sense data sets will be added to
* the triggers data.
*/
static void dasd_eer_write_standard_trigger(struct dasd_device *device,
struct dasd_ccw_req *cqr,
int trigger)
{
struct dasd_ccw_req *temp_cqr;
int data_size;
struct timeval tv;
struct dasd_eer_header header;
unsigned long flags;
struct eerbuffer *eerb;
char *sense;
/* go through cqr chain and count the valid sense data sets */
data_size = 0;
for (temp_cqr = cqr; temp_cqr; temp_cqr = temp_cqr->refers)
if (dasd_get_sense(&temp_cqr->irb))
data_size += 32;
header.total_size = sizeof(header) + data_size + 4; /* "EOR" */
header.trigger = trigger;
do_gettimeofday(&tv);
header.tv_sec = tv.tv_sec;
header.tv_usec = tv.tv_usec;
strncpy(header.busid, dev_name(&device->cdev->dev),
DASD_EER_BUSID_SIZE);
spin_lock_irqsave(&bufferlock, flags);
list_for_each_entry(eerb, &bufferlist, list) {
dasd_eer_start_record(eerb, header.total_size);
dasd_eer_write_buffer(eerb, (char *) &header, sizeof(header));
for (temp_cqr = cqr; temp_cqr; temp_cqr = temp_cqr->refers) {
sense = dasd_get_sense(&temp_cqr->irb);
if (sense)
dasd_eer_write_buffer(eerb, sense, 32);
}
dasd_eer_write_buffer(eerb, "EOR", 4);
}
spin_unlock_irqrestore(&bufferlock, flags);
wake_up_interruptible(&dasd_eer_read_wait_queue);
}
/*
* This function writes a DASD_EER_STATECHANGE trigger.
*/
static void dasd_eer_write_snss_trigger(struct dasd_device *device,
struct dasd_ccw_req *cqr,
int trigger)
{
int data_size;
int snss_rc;
struct timeval tv;
struct dasd_eer_header header;
unsigned long flags;
struct eerbuffer *eerb;
snss_rc = (cqr->status == DASD_CQR_DONE) ? 0 : -EIO;
if (snss_rc)
data_size = 0;
else
data_size = SNSS_DATA_SIZE;
header.total_size = sizeof(header) + data_size + 4; /* "EOR" */
header.trigger = DASD_EER_STATECHANGE;
do_gettimeofday(&tv);
header.tv_sec = tv.tv_sec;
header.tv_usec = tv.tv_usec;
strncpy(header.busid, dev_name(&device->cdev->dev),
DASD_EER_BUSID_SIZE);
spin_lock_irqsave(&bufferlock, flags);
list_for_each_entry(eerb, &bufferlist, list) {
dasd_eer_start_record(eerb, header.total_size);
dasd_eer_write_buffer(eerb, (char *) &header , sizeof(header));
if (!snss_rc)
dasd_eer_write_buffer(eerb, cqr->data, SNSS_DATA_SIZE);
dasd_eer_write_buffer(eerb, "EOR", 4);
}
spin_unlock_irqrestore(&bufferlock, flags);
wake_up_interruptible(&dasd_eer_read_wait_queue);
}
/*
* This function is called for all triggers. It calls the appropriate
* function that writes the actual trigger records.
*/
void dasd_eer_write(struct dasd_device *device, struct dasd_ccw_req *cqr,
unsigned int id)
{
if (!device->eer_cqr)
return;
switch (id) {
case DASD_EER_FATALERROR:
case DASD_EER_PPRCSUSPEND:
dasd_eer_write_standard_trigger(device, cqr, id);
break;
case DASD_EER_NOPATH:
dasd_eer_write_standard_trigger(device, NULL, id);
break;
case DASD_EER_STATECHANGE:
dasd_eer_write_snss_trigger(device, cqr, id);
break;
default: /* unknown trigger, so we write it without any sense data */
dasd_eer_write_standard_trigger(device, NULL, id);
break;
}
}
EXPORT_SYMBOL(dasd_eer_write);
/*
* Start a sense subsystem status request.
* Needs to be called with the device held.
*/
void dasd_eer_snss(struct dasd_device *device)
{
struct dasd_ccw_req *cqr;
cqr = device->eer_cqr;
if (!cqr) /* Device not eer enabled. */
return;
if (test_and_set_bit(DASD_FLAG_EER_IN_USE, &device->flags)) {
/* Sense subsystem status request in use. */
set_bit(DASD_FLAG_EER_SNSS, &device->flags);
return;
}
/* cdev is already locked, can't use dasd_add_request_head */
clear_bit(DASD_FLAG_EER_SNSS, &device->flags);
cqr->status = DASD_CQR_QUEUED;
list_add(&cqr->devlist, &device->ccw_queue);
dasd_schedule_device_bh(device);
}
/*
* Callback function for use with sense subsystem status request.
*/
static void dasd_eer_snss_cb(struct dasd_ccw_req *cqr, void *data)
{
struct dasd_device *device = cqr->startdev;
unsigned long flags;
dasd_eer_write(device, cqr, DASD_EER_STATECHANGE);
spin_lock_irqsave(get_ccwdev_lock(device->cdev), flags);
if (device->eer_cqr == cqr) {
clear_bit(DASD_FLAG_EER_IN_USE, &device->flags);
if (test_bit(DASD_FLAG_EER_SNSS, &device->flags))
/* Another SNSS has been requested in the meantime. */
dasd_eer_snss(device);
cqr = NULL;
}
spin_unlock_irqrestore(get_ccwdev_lock(device->cdev), flags);
if (cqr)
/*
* Extended error recovery has been switched off while
* the SNSS request was running. It could even have
* been switched off and on again in which case there
* is a new ccw in device->eer_cqr. Free the "old"
* snss request now.
*/
dasd_kfree_request(cqr, device);
}
/*
* Enable error reporting on a given device.
*/
int dasd_eer_enable(struct dasd_device *device)
{
struct dasd_ccw_req *cqr;
unsigned long flags;
struct ccw1 *ccw;
if (device->eer_cqr)
return 0;
if (!device->discipline || strcmp(device->discipline->name, "ECKD"))
return -EPERM; /* FIXME: -EMEDIUMTYPE ? */
cqr = dasd_kmalloc_request(DASD_ECKD_MAGIC, 1 /* SNSS */,
SNSS_DATA_SIZE, device);
if (IS_ERR(cqr))
return -ENOMEM;
cqr->startdev = device;
cqr->retries = 255;
cqr->expires = 10 * HZ;
clear_bit(DASD_CQR_FLAGS_USE_ERP, &cqr->flags);
set_bit(DASD_CQR_ALLOW_SLOCK, &cqr->flags);
ccw = cqr->cpaddr;
ccw->cmd_code = DASD_ECKD_CCW_SNSS;
ccw->count = SNSS_DATA_SIZE;
ccw->flags = 0;
ccw->cda = (__u32)(addr_t) cqr->data;
cqr->buildclk = get_clock();
cqr->status = DASD_CQR_FILLED;
cqr->callback = dasd_eer_snss_cb;
spin_lock_irqsave(get_ccwdev_lock(device->cdev), flags);
if (!device->eer_cqr) {
device->eer_cqr = cqr;
cqr = NULL;
}
spin_unlock_irqrestore(get_ccwdev_lock(device->cdev), flags);
if (cqr)
dasd_kfree_request(cqr, device);
return 0;
}
/*
* Disable error reporting on a given device.
*/
void dasd_eer_disable(struct dasd_device *device)
{
struct dasd_ccw_req *cqr;
unsigned long flags;
int in_use;
if (!device->eer_cqr)
return;
spin_lock_irqsave(get_ccwdev_lock(device->cdev), flags);
cqr = device->eer_cqr;
device->eer_cqr = NULL;
clear_bit(DASD_FLAG_EER_SNSS, &device->flags);
in_use = test_and_clear_bit(DASD_FLAG_EER_IN_USE, &device->flags);
spin_unlock_irqrestore(get_ccwdev_lock(device->cdev), flags);
if (cqr && !in_use)
dasd_kfree_request(cqr, device);
}
/*
* SECTION: the device operations
*/
/*
* On the one side we need a lock to access our internal buffer, on the
* other side a copy_to_user can sleep. So we need to copy the data we have
* to transfer in a readbuffer, which is protected by the readbuffer_mutex.
*/
static char readbuffer[PAGE_SIZE];
static DEFINE_MUTEX(readbuffer_mutex);
static int dasd_eer_open(struct inode *inp, struct file *filp)
{
struct eerbuffer *eerb;
unsigned long flags;
eerb = kzalloc(sizeof(struct eerbuffer), GFP_KERNEL);
if (!eerb)
return -ENOMEM;
eerb->buffer_page_count = eer_pages;
if (eerb->buffer_page_count < 1 ||
eerb->buffer_page_count > INT_MAX / PAGE_SIZE) {
kfree(eerb);
DBF_EVENT(DBF_WARNING, "can't open device since module "
"parameter eer_pages is smaller than 1 or"
" bigger than %d", (int)(INT_MAX / PAGE_SIZE));
return -EINVAL;
}
eerb->buffersize = eerb->buffer_page_count * PAGE_SIZE;
eerb->buffer = kmalloc(eerb->buffer_page_count * sizeof(char *),
GFP_KERNEL);
if (!eerb->buffer) {
kfree(eerb);
return -ENOMEM;
}
if (dasd_eer_allocate_buffer_pages(eerb->buffer,
eerb->buffer_page_count)) {
kfree(eerb->buffer);
kfree(eerb);
return -ENOMEM;
}
filp->private_data = eerb;
spin_lock_irqsave(&bufferlock, flags);
list_add(&eerb->list, &bufferlist);
spin_unlock_irqrestore(&bufferlock, flags);
return nonseekable_open(inp,filp);
}
static int dasd_eer_close(struct inode *inp, struct file *filp)
{
struct eerbuffer *eerb;
unsigned long flags;
eerb = (struct eerbuffer *) filp->private_data;
spin_lock_irqsave(&bufferlock, flags);
list_del(&eerb->list);
spin_unlock_irqrestore(&bufferlock, flags);
dasd_eer_free_buffer_pages(eerb->buffer, eerb->buffer_page_count);
kfree(eerb->buffer);
kfree(eerb);
return 0;
}
static ssize_t dasd_eer_read(struct file *filp, char __user *buf,
size_t count, loff_t *ppos)
{
int tc,rc;
int tailcount,effective_count;
unsigned long flags;
struct eerbuffer *eerb;
eerb = (struct eerbuffer *) filp->private_data;
if (mutex_lock_interruptible(&readbuffer_mutex))
return -ERESTARTSYS;
spin_lock_irqsave(&bufferlock, flags);
if (eerb->residual < 0) { /* the remainder of this record */
/* has been deleted */
eerb->residual = 0;
spin_unlock_irqrestore(&bufferlock, flags);
mutex_unlock(&readbuffer_mutex);
return -EIO;
} else if (eerb->residual > 0) {
/* OK we still have a second half of a record to deliver */
effective_count = min(eerb->residual, (int) count);
eerb->residual -= effective_count;
} else {
tc = 0;
while (!tc) {
tc = dasd_eer_read_buffer(eerb, (char *) &tailcount,
sizeof(tailcount));
if (!tc) {
/* no data available */
spin_unlock_irqrestore(&bufferlock, flags);
mutex_unlock(&readbuffer_mutex);
if (filp->f_flags & O_NONBLOCK)
return -EAGAIN;
rc = wait_event_interruptible(
dasd_eer_read_wait_queue,
eerb->head != eerb->tail);
if (rc)
return rc;
if (mutex_lock_interruptible(&readbuffer_mutex))
return -ERESTARTSYS;
spin_lock_irqsave(&bufferlock, flags);
}
}
WARN_ON(tc != sizeof(tailcount));
effective_count = min(tailcount,(int)count);
eerb->residual = tailcount - effective_count;
}
tc = dasd_eer_read_buffer(eerb, readbuffer, effective_count);
WARN_ON(tc != effective_count);
spin_unlock_irqrestore(&bufferlock, flags);
if (copy_to_user(buf, readbuffer, effective_count)) {
mutex_unlock(&readbuffer_mutex);
return -EFAULT;
}
mutex_unlock(&readbuffer_mutex);
return effective_count;
}
static unsigned int dasd_eer_poll(struct file *filp, poll_table *ptable)
{
unsigned int mask;
unsigned long flags;
struct eerbuffer *eerb;
eerb = (struct eerbuffer *) filp->private_data;
poll_wait(filp, &dasd_eer_read_wait_queue, ptable);
spin_lock_irqsave(&bufferlock, flags);
if (eerb->head != eerb->tail)
mask = POLLIN | POLLRDNORM ;
else
mask = 0;
spin_unlock_irqrestore(&bufferlock, flags);
return mask;
}
static const struct file_operations dasd_eer_fops = {
.open = &dasd_eer_open,
.release = &dasd_eer_close,
.read = &dasd_eer_read,
.poll = &dasd_eer_poll,
.owner = THIS_MODULE,
.llseek = noop_llseek,
};
static struct miscdevice *dasd_eer_dev = NULL;
int __init dasd_eer_init(void)
{
int rc;
dasd_eer_dev = kzalloc(sizeof(*dasd_eer_dev), GFP_KERNEL);
if (!dasd_eer_dev)
return -ENOMEM;
dasd_eer_dev->minor = MISC_DYNAMIC_MINOR;
dasd_eer_dev->name = "dasd_eer";
dasd_eer_dev->fops = &dasd_eer_fops;
rc = misc_register(dasd_eer_dev);
if (rc) {
kfree(dasd_eer_dev);
dasd_eer_dev = NULL;
DBF_EVENT(DBF_ERR, "%s", "dasd_eer_init could not "
"register misc device");
return rc;
}
return 0;
}
void dasd_eer_exit(void)
{
if (dasd_eer_dev) {
misc_deregister(dasd_eer_dev);
kfree(dasd_eer_dev);
dasd_eer_dev = NULL;
}
}
| gpl-2.0 |
NX511J-dev/kernel_nubia_nx511j | arch/x86/pci/broadcom_bus.c | 2883 | 3298 | /*
* Read address ranges from a Broadcom CNB20LE Host Bridge
*
* 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/acpi.h>
#include <linux/delay.h>
#include <linux/dmi.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <asm/pci_x86.h>
#include <asm/pci-direct.h>
#include "bus_numa.h"
static void __init cnb20le_res(u8 bus, u8 slot, u8 func)
{
struct pci_root_info *info;
struct pci_root_res *root_res;
struct resource res;
u16 word1, word2;
u8 fbus, lbus;
/* read the PCI bus numbers */
fbus = read_pci_config_byte(bus, slot, func, 0x44);
lbus = read_pci_config_byte(bus, slot, func, 0x45);
info = alloc_pci_root_info(fbus, lbus, 0, 0);
/*
* Add the legacy IDE ports on bus 0
*
* These do not exist anywhere in the bridge registers, AFAICT. I do
* not have the datasheet, so this is the best I can do.
*/
if (fbus == 0) {
update_res(info, 0x01f0, 0x01f7, IORESOURCE_IO, 0);
update_res(info, 0x03f6, 0x03f6, IORESOURCE_IO, 0);
update_res(info, 0x0170, 0x0177, IORESOURCE_IO, 0);
update_res(info, 0x0376, 0x0376, IORESOURCE_IO, 0);
update_res(info, 0xffa0, 0xffaf, IORESOURCE_IO, 0);
}
/* read the non-prefetchable memory window */
word1 = read_pci_config_16(bus, slot, func, 0xc0);
word2 = read_pci_config_16(bus, slot, func, 0xc2);
if (word1 != word2) {
res.start = (word1 << 16) | 0x0000;
res.end = (word2 << 16) | 0xffff;
res.flags = IORESOURCE_MEM;
update_res(info, res.start, res.end, res.flags, 0);
}
/* read the prefetchable memory window */
word1 = read_pci_config_16(bus, slot, func, 0xc4);
word2 = read_pci_config_16(bus, slot, func, 0xc6);
if (word1 != word2) {
res.start = (word1 << 16) | 0x0000;
res.end = (word2 << 16) | 0xffff;
res.flags = IORESOURCE_MEM | IORESOURCE_PREFETCH;
update_res(info, res.start, res.end, res.flags, 0);
}
/* read the IO port window */
word1 = read_pci_config_16(bus, slot, func, 0xd0);
word2 = read_pci_config_16(bus, slot, func, 0xd2);
if (word1 != word2) {
res.start = word1;
res.end = word2;
res.flags = IORESOURCE_IO;
update_res(info, res.start, res.end, res.flags, 0);
}
/* print information about this host bridge */
res.start = fbus;
res.end = lbus;
res.flags = IORESOURCE_BUS;
printk(KERN_INFO "CNB20LE PCI Host Bridge (domain 0000 %pR)\n", &res);
list_for_each_entry(root_res, &info->resources, list)
printk(KERN_INFO "host bridge window %pR\n", &root_res->res);
}
static int __init broadcom_postcore_init(void)
{
u8 bus = 0, slot = 0;
u32 id;
u16 vendor, device;
#ifdef CONFIG_ACPI
/*
* We should get host bridge information from ACPI unless the BIOS
* doesn't support it.
*/
if (acpi_os_get_root_pointer())
return 0;
#endif
id = read_pci_config(bus, slot, 0, PCI_VENDOR_ID);
vendor = id & 0xffff;
device = (id >> 16) & 0xffff;
if (vendor == PCI_VENDOR_ID_SERVERWORKS &&
device == PCI_DEVICE_ID_SERVERWORKS_LE) {
cnb20le_res(bus, slot, 0);
cnb20le_res(bus, slot, 1);
}
return 0;
}
postcore_initcall(broadcom_postcore_init);
| gpl-2.0 |
bilalliberty/android_kernel_htc_memul | arch/arm/mach-tegra/board-harmony.c | 4675 | 4936 | /*
* arch/arm/mach-tegra/board-harmony.c
*
* Copyright (C) 2010 Google, Inc.
* Copyright (C) 2011 NVIDIA, Inc.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/serial_8250.h>
#include <linux/clk.h>
#include <linux/dma-mapping.h>
#include <linux/pda_power.h>
#include <linux/io.h>
#include <linux/gpio.h>
#include <linux/i2c.h>
#include <sound/wm8903.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/time.h>
#include <asm/hardware/gic.h>
#include <asm/setup.h>
#include <mach/tegra_wm8903_pdata.h>
#include <mach/iomap.h>
#include <mach/irqs.h>
#include <mach/sdhci.h>
#include "board.h"
#include "board-harmony.h"
#include "clock.h"
#include "devices.h"
#include "gpio-names.h"
static struct plat_serial8250_port debug_uart_platform_data[] = {
{
.membase = IO_ADDRESS(TEGRA_UARTD_BASE),
.mapbase = TEGRA_UARTD_BASE,
.irq = INT_UARTD,
.flags = UPF_BOOT_AUTOCONF | UPF_FIXED_TYPE,
.type = PORT_TEGRA,
.iotype = UPIO_MEM,
.regshift = 2,
.uartclk = 216000000,
}, {
.flags = 0
}
};
static struct platform_device debug_uart = {
.name = "serial8250",
.id = PLAT8250_DEV_PLATFORM,
.dev = {
.platform_data = debug_uart_platform_data,
},
};
static struct tegra_wm8903_platform_data harmony_audio_pdata = {
.gpio_spkr_en = TEGRA_GPIO_SPKR_EN,
.gpio_hp_det = TEGRA_GPIO_HP_DET,
.gpio_hp_mute = -1,
.gpio_int_mic_en = TEGRA_GPIO_INT_MIC_EN,
.gpio_ext_mic_en = TEGRA_GPIO_EXT_MIC_EN,
};
static struct platform_device harmony_audio_device = {
.name = "tegra-snd-wm8903",
.id = 0,
.dev = {
.platform_data = &harmony_audio_pdata,
},
};
static struct wm8903_platform_data harmony_wm8903_pdata = {
.irq_active_low = 0,
.micdet_cfg = 0,
.micdet_delay = 100,
.gpio_base = HARMONY_GPIO_WM8903(0),
.gpio_cfg = {
0,
0,
WM8903_GPIO_CONFIG_ZERO,
0,
0,
},
};
static struct i2c_board_info __initdata wm8903_board_info = {
I2C_BOARD_INFO("wm8903", 0x1a),
.platform_data = &harmony_wm8903_pdata,
};
static void __init harmony_i2c_init(void)
{
platform_device_register(&tegra_i2c_device1);
platform_device_register(&tegra_i2c_device2);
platform_device_register(&tegra_i2c_device3);
platform_device_register(&tegra_i2c_device4);
wm8903_board_info.irq = gpio_to_irq(TEGRA_GPIO_CDC_IRQ);
i2c_register_board_info(0, &wm8903_board_info, 1);
}
static struct platform_device *harmony_devices[] __initdata = {
&debug_uart,
&tegra_sdhci_device1,
&tegra_sdhci_device2,
&tegra_sdhci_device4,
&tegra_ehci3_device,
&tegra_i2s_device1,
&tegra_das_device,
&tegra_pcm_device,
&harmony_audio_device,
};
static void __init tegra_harmony_fixup(struct tag *tags, char **cmdline,
struct meminfo *mi)
{
mi->nr_banks = 2;
mi->bank[0].start = PHYS_OFFSET;
mi->bank[0].size = 448 * SZ_1M;
mi->bank[1].start = SZ_512M;
mi->bank[1].size = SZ_512M;
}
static __initdata struct tegra_clk_init_table harmony_clk_init_table[] = {
/* name parent rate enabled */
{ "uartd", "pll_p", 216000000, true },
{ "pll_a", "pll_p_out1", 56448000, true },
{ "pll_a_out0", "pll_a", 11289600, true },
{ "cdev1", NULL, 0, true },
{ "i2s1", "pll_a_out0", 11289600, false},
{ "usb3", "clk_m", 12000000, true },
{ NULL, NULL, 0, 0},
};
static struct tegra_sdhci_platform_data sdhci_pdata1 = {
.cd_gpio = -1,
.wp_gpio = -1,
.power_gpio = -1,
};
static struct tegra_sdhci_platform_data sdhci_pdata2 = {
.cd_gpio = TEGRA_GPIO_SD2_CD,
.wp_gpio = TEGRA_GPIO_SD2_WP,
.power_gpio = TEGRA_GPIO_SD2_POWER,
};
static struct tegra_sdhci_platform_data sdhci_pdata4 = {
.cd_gpio = TEGRA_GPIO_SD4_CD,
.wp_gpio = TEGRA_GPIO_SD4_WP,
.power_gpio = TEGRA_GPIO_SD4_POWER,
.is_8bit = 1,
};
static void __init tegra_harmony_init(void)
{
tegra_clk_init_from_table(harmony_clk_init_table);
harmony_pinmux_init();
tegra_sdhci_device1.dev.platform_data = &sdhci_pdata1;
tegra_sdhci_device2.dev.platform_data = &sdhci_pdata2;
tegra_sdhci_device4.dev.platform_data = &sdhci_pdata4;
platform_add_devices(harmony_devices, ARRAY_SIZE(harmony_devices));
harmony_i2c_init();
harmony_regulator_init();
}
MACHINE_START(HARMONY, "harmony")
.atag_offset = 0x100,
.fixup = tegra_harmony_fixup,
.map_io = tegra_map_common_io,
.init_early = tegra20_init_early,
.init_irq = tegra_init_irq,
.handle_irq = gic_handle_irq,
.timer = &tegra_timer,
.init_machine = tegra_harmony_init,
.restart = tegra_assert_system_reset,
MACHINE_END
| gpl-2.0 |
NormandyEGY/android_kernel_nokia_normandy | sound/pci/hda/hda_generic.c | 5187 | 28446 | /*
* Universal Interface for Intel High Definition Audio Codec
*
* Generic widget tree parser
*
* Copyright (c) 2004 Takashi Iwai <tiwai@suse.de>
*
* This driver is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This driver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/export.h>
#include <sound/core.h>
#include "hda_codec.h"
#include "hda_local.h"
/* widget node for parsing */
struct hda_gnode {
hda_nid_t nid; /* NID of this widget */
unsigned short nconns; /* number of input connections */
hda_nid_t *conn_list;
hda_nid_t slist[2]; /* temporay list */
unsigned int wid_caps; /* widget capabilities */
unsigned char type; /* widget type */
unsigned char pin_ctl; /* pin controls */
unsigned char checked; /* the flag indicates that the node is already parsed */
unsigned int pin_caps; /* pin widget capabilities */
unsigned int def_cfg; /* default configuration */
unsigned int amp_out_caps; /* AMP out capabilities */
unsigned int amp_in_caps; /* AMP in capabilities */
struct list_head list;
};
/* patch-specific record */
#define MAX_PCM_VOLS 2
struct pcm_vol {
struct hda_gnode *node; /* Node for PCM volume */
unsigned int index; /* connection of PCM volume */
};
struct hda_gspec {
struct hda_gnode *dac_node[2]; /* DAC node */
struct hda_gnode *out_pin_node[2]; /* Output pin (Line-Out) node */
struct pcm_vol pcm_vol[MAX_PCM_VOLS]; /* PCM volumes */
unsigned int pcm_vol_nodes; /* number of PCM volumes */
struct hda_gnode *adc_node; /* ADC node */
struct hda_gnode *cap_vol_node; /* Node for capture volume */
unsigned int cur_cap_src; /* current capture source */
struct hda_input_mux input_mux;
unsigned int def_amp_in_caps;
unsigned int def_amp_out_caps;
struct hda_pcm pcm_rec; /* PCM information */
struct list_head nid_list; /* list of widgets */
#ifdef CONFIG_SND_HDA_POWER_SAVE
#define MAX_LOOPBACK_AMPS 7
struct hda_loopback_check loopback;
int num_loopbacks;
struct hda_amp_list loopback_list[MAX_LOOPBACK_AMPS + 1];
#endif
};
/*
* retrieve the default device type from the default config value
*/
#define defcfg_type(node) (((node)->def_cfg & AC_DEFCFG_DEVICE) >> \
AC_DEFCFG_DEVICE_SHIFT)
#define defcfg_location(node) (((node)->def_cfg & AC_DEFCFG_LOCATION) >> \
AC_DEFCFG_LOCATION_SHIFT)
#define defcfg_port_conn(node) (((node)->def_cfg & AC_DEFCFG_PORT_CONN) >> \
AC_DEFCFG_PORT_CONN_SHIFT)
/*
* destructor
*/
static void snd_hda_generic_free(struct hda_codec *codec)
{
struct hda_gspec *spec = codec->spec;
struct hda_gnode *node, *n;
if (! spec)
return;
/* free all widgets */
list_for_each_entry_safe(node, n, &spec->nid_list, list) {
if (node->conn_list != node->slist)
kfree(node->conn_list);
kfree(node);
}
kfree(spec);
}
/*
* add a new widget node and read its attributes
*/
static int add_new_node(struct hda_codec *codec, struct hda_gspec *spec, hda_nid_t nid)
{
struct hda_gnode *node;
int nconns;
hda_nid_t conn_list[HDA_MAX_CONNECTIONS];
node = kzalloc(sizeof(*node), GFP_KERNEL);
if (node == NULL)
return -ENOMEM;
node->nid = nid;
node->wid_caps = get_wcaps(codec, nid);
node->type = get_wcaps_type(node->wid_caps);
if (node->wid_caps & AC_WCAP_CONN_LIST) {
nconns = snd_hda_get_connections(codec, nid, conn_list,
HDA_MAX_CONNECTIONS);
if (nconns < 0) {
kfree(node);
return nconns;
}
} else {
nconns = 0;
}
if (nconns <= ARRAY_SIZE(node->slist))
node->conn_list = node->slist;
else {
node->conn_list = kmalloc(sizeof(hda_nid_t) * nconns,
GFP_KERNEL);
if (! node->conn_list) {
snd_printk(KERN_ERR "hda-generic: cannot malloc\n");
kfree(node);
return -ENOMEM;
}
}
memcpy(node->conn_list, conn_list, nconns * sizeof(hda_nid_t));
node->nconns = nconns;
if (node->type == AC_WID_PIN) {
node->pin_caps = snd_hda_query_pin_caps(codec, node->nid);
node->pin_ctl = snd_hda_codec_read(codec, node->nid, 0, AC_VERB_GET_PIN_WIDGET_CONTROL, 0);
node->def_cfg = snd_hda_codec_get_pincfg(codec, node->nid);
}
if (node->wid_caps & AC_WCAP_OUT_AMP) {
if (node->wid_caps & AC_WCAP_AMP_OVRD)
node->amp_out_caps = snd_hda_param_read(codec, node->nid, AC_PAR_AMP_OUT_CAP);
if (! node->amp_out_caps)
node->amp_out_caps = spec->def_amp_out_caps;
}
if (node->wid_caps & AC_WCAP_IN_AMP) {
if (node->wid_caps & AC_WCAP_AMP_OVRD)
node->amp_in_caps = snd_hda_param_read(codec, node->nid, AC_PAR_AMP_IN_CAP);
if (! node->amp_in_caps)
node->amp_in_caps = spec->def_amp_in_caps;
}
list_add_tail(&node->list, &spec->nid_list);
return 0;
}
/*
* build the AFG subtree
*/
static int build_afg_tree(struct hda_codec *codec)
{
struct hda_gspec *spec = codec->spec;
int i, nodes, err;
hda_nid_t nid;
if (snd_BUG_ON(!spec))
return -EINVAL;
spec->def_amp_out_caps = snd_hda_param_read(codec, codec->afg, AC_PAR_AMP_OUT_CAP);
spec->def_amp_in_caps = snd_hda_param_read(codec, codec->afg, AC_PAR_AMP_IN_CAP);
nodes = snd_hda_get_sub_nodes(codec, codec->afg, &nid);
if (! nid || nodes < 0) {
printk(KERN_ERR "Invalid AFG subtree\n");
return -EINVAL;
}
/* parse all nodes belonging to the AFG */
for (i = 0; i < nodes; i++, nid++) {
if ((err = add_new_node(codec, spec, nid)) < 0)
return err;
}
return 0;
}
/*
* look for the node record for the given NID
*/
/* FIXME: should avoid the braindead linear search */
static struct hda_gnode *hda_get_node(struct hda_gspec *spec, hda_nid_t nid)
{
struct hda_gnode *node;
list_for_each_entry(node, &spec->nid_list, list) {
if (node->nid == nid)
return node;
}
return NULL;
}
/*
* unmute (and set max vol) the output amplifier
*/
static int unmute_output(struct hda_codec *codec, struct hda_gnode *node)
{
unsigned int val, ofs;
snd_printdd("UNMUTE OUT: NID=0x%x\n", node->nid);
val = (node->amp_out_caps & AC_AMPCAP_NUM_STEPS) >> AC_AMPCAP_NUM_STEPS_SHIFT;
ofs = (node->amp_out_caps & AC_AMPCAP_OFFSET) >> AC_AMPCAP_OFFSET_SHIFT;
if (val >= ofs)
val -= ofs;
snd_hda_codec_amp_stereo(codec, node->nid, HDA_OUTPUT, 0, 0xff, val);
return 0;
}
/*
* unmute (and set max vol) the input amplifier
*/
static int unmute_input(struct hda_codec *codec, struct hda_gnode *node, unsigned int index)
{
unsigned int val, ofs;
snd_printdd("UNMUTE IN: NID=0x%x IDX=0x%x\n", node->nid, index);
val = (node->amp_in_caps & AC_AMPCAP_NUM_STEPS) >> AC_AMPCAP_NUM_STEPS_SHIFT;
ofs = (node->amp_in_caps & AC_AMPCAP_OFFSET) >> AC_AMPCAP_OFFSET_SHIFT;
if (val >= ofs)
val -= ofs;
snd_hda_codec_amp_stereo(codec, node->nid, HDA_INPUT, index, 0xff, val);
return 0;
}
/*
* select the input connection of the given node.
*/
static int select_input_connection(struct hda_codec *codec, struct hda_gnode *node,
unsigned int index)
{
snd_printdd("CONNECT: NID=0x%x IDX=0x%x\n", node->nid, index);
return snd_hda_codec_write_cache(codec, node->nid, 0,
AC_VERB_SET_CONNECT_SEL, index);
}
/*
* clear checked flag of each node in the node list
*/
static void clear_check_flags(struct hda_gspec *spec)
{
struct hda_gnode *node;
list_for_each_entry(node, &spec->nid_list, list) {
node->checked = 0;
}
}
/*
* parse the output path recursively until reach to an audio output widget
*
* returns 0 if not found, 1 if found, or a negative error code.
*/
static int parse_output_path(struct hda_codec *codec, struct hda_gspec *spec,
struct hda_gnode *node, int dac_idx)
{
int i, err;
struct hda_gnode *child;
if (node->checked)
return 0;
node->checked = 1;
if (node->type == AC_WID_AUD_OUT) {
if (node->wid_caps & AC_WCAP_DIGITAL) {
snd_printdd("Skip Digital OUT node %x\n", node->nid);
return 0;
}
snd_printdd("AUD_OUT found %x\n", node->nid);
if (spec->dac_node[dac_idx]) {
/* already DAC node is assigned, just unmute & connect */
return node == spec->dac_node[dac_idx];
}
spec->dac_node[dac_idx] = node;
if ((node->wid_caps & AC_WCAP_OUT_AMP) &&
spec->pcm_vol_nodes < MAX_PCM_VOLS) {
spec->pcm_vol[spec->pcm_vol_nodes].node = node;
spec->pcm_vol[spec->pcm_vol_nodes].index = 0;
spec->pcm_vol_nodes++;
}
return 1; /* found */
}
for (i = 0; i < node->nconns; i++) {
child = hda_get_node(spec, node->conn_list[i]);
if (! child)
continue;
err = parse_output_path(codec, spec, child, dac_idx);
if (err < 0)
return err;
else if (err > 0) {
/* found one,
* select the path, unmute both input and output
*/
if (node->nconns > 1)
select_input_connection(codec, node, i);
unmute_input(codec, node, i);
unmute_output(codec, node);
if (spec->dac_node[dac_idx] &&
spec->pcm_vol_nodes < MAX_PCM_VOLS &&
!(spec->dac_node[dac_idx]->wid_caps &
AC_WCAP_OUT_AMP)) {
if ((node->wid_caps & AC_WCAP_IN_AMP) ||
(node->wid_caps & AC_WCAP_OUT_AMP)) {
int n = spec->pcm_vol_nodes;
spec->pcm_vol[n].node = node;
spec->pcm_vol[n].index = i;
spec->pcm_vol_nodes++;
}
}
return 1;
}
}
return 0;
}
/*
* Look for the output PIN widget with the given jack type
* and parse the output path to that PIN.
*
* Returns the PIN node when the path to DAC is established.
*/
static struct hda_gnode *parse_output_jack(struct hda_codec *codec,
struct hda_gspec *spec,
int jack_type)
{
struct hda_gnode *node;
int err;
list_for_each_entry(node, &spec->nid_list, list) {
if (node->type != AC_WID_PIN)
continue;
/* output capable? */
if (! (node->pin_caps & AC_PINCAP_OUT))
continue;
if (defcfg_port_conn(node) == AC_JACK_PORT_NONE)
continue; /* unconnected */
if (jack_type >= 0) {
if (jack_type != defcfg_type(node))
continue;
if (node->wid_caps & AC_WCAP_DIGITAL)
continue; /* skip SPDIF */
} else {
/* output as default? */
if (! (node->pin_ctl & AC_PINCTL_OUT_EN))
continue;
}
clear_check_flags(spec);
err = parse_output_path(codec, spec, node, 0);
if (err < 0)
return NULL;
if (! err && spec->out_pin_node[0]) {
err = parse_output_path(codec, spec, node, 1);
if (err < 0)
return NULL;
}
if (err > 0) {
/* unmute the PIN output */
unmute_output(codec, node);
/* set PIN-Out enable */
snd_hda_codec_write_cache(codec, node->nid, 0,
AC_VERB_SET_PIN_WIDGET_CONTROL,
AC_PINCTL_OUT_EN |
((node->pin_caps & AC_PINCAP_HP_DRV) ?
AC_PINCTL_HP_EN : 0));
return node;
}
}
return NULL;
}
/*
* parse outputs
*/
static int parse_output(struct hda_codec *codec)
{
struct hda_gspec *spec = codec->spec;
struct hda_gnode *node;
/*
* Look for the output PIN widget
*/
/* first, look for the line-out pin */
node = parse_output_jack(codec, spec, AC_JACK_LINE_OUT);
if (node) /* found, remember the PIN node */
spec->out_pin_node[0] = node;
else {
/* if no line-out is found, try speaker out */
node = parse_output_jack(codec, spec, AC_JACK_SPEAKER);
if (node)
spec->out_pin_node[0] = node;
}
/* look for the HP-out pin */
node = parse_output_jack(codec, spec, AC_JACK_HP_OUT);
if (node) {
if (! spec->out_pin_node[0])
spec->out_pin_node[0] = node;
else
spec->out_pin_node[1] = node;
}
if (! spec->out_pin_node[0]) {
/* no line-out or HP pins found,
* then choose for the first output pin
*/
spec->out_pin_node[0] = parse_output_jack(codec, spec, -1);
if (! spec->out_pin_node[0])
snd_printd("hda_generic: no proper output path found\n");
}
return 0;
}
/*
* input MUX
*/
/* control callbacks */
static int capture_source_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct hda_gspec *spec = codec->spec;
return snd_hda_input_mux_info(&spec->input_mux, uinfo);
}
static int capture_source_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct hda_gspec *spec = codec->spec;
ucontrol->value.enumerated.item[0] = spec->cur_cap_src;
return 0;
}
static int capture_source_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct hda_gspec *spec = codec->spec;
return snd_hda_input_mux_put(codec, &spec->input_mux, ucontrol,
spec->adc_node->nid, &spec->cur_cap_src);
}
/*
* return the string name of the given input PIN widget
*/
static const char *get_input_type(struct hda_gnode *node, unsigned int *pinctl)
{
unsigned int location = defcfg_location(node);
switch (defcfg_type(node)) {
case AC_JACK_LINE_IN:
if ((location & 0x0f) == AC_JACK_LOC_FRONT)
return "Front Line";
return "Line";
case AC_JACK_CD:
#if 0
if (pinctl)
*pinctl |= AC_PINCTL_VREF_GRD;
#endif
return "CD";
case AC_JACK_AUX:
if ((location & 0x0f) == AC_JACK_LOC_FRONT)
return "Front Aux";
return "Aux";
case AC_JACK_MIC_IN:
if (pinctl &&
(node->pin_caps &
(AC_PINCAP_VREF_80 << AC_PINCAP_VREF_SHIFT)))
*pinctl |= AC_PINCTL_VREF_80;
if ((location & 0x0f) == AC_JACK_LOC_FRONT)
return "Front Mic";
return "Mic";
case AC_JACK_SPDIF_IN:
return "SPDIF";
case AC_JACK_DIG_OTHER_IN:
return "Digital";
}
return NULL;
}
/*
* parse the nodes recursively until reach to the input PIN
*
* returns 0 if not found, 1 if found, or a negative error code.
*/
static int parse_adc_sub_nodes(struct hda_codec *codec, struct hda_gspec *spec,
struct hda_gnode *node, int idx)
{
int i, err;
unsigned int pinctl;
const char *type;
if (node->checked)
return 0;
node->checked = 1;
if (node->type != AC_WID_PIN) {
for (i = 0; i < node->nconns; i++) {
struct hda_gnode *child;
child = hda_get_node(spec, node->conn_list[i]);
if (! child)
continue;
err = parse_adc_sub_nodes(codec, spec, child, idx);
if (err < 0)
return err;
if (err > 0) {
/* found one,
* select the path, unmute both input and output
*/
if (node->nconns > 1)
select_input_connection(codec, node, i);
unmute_input(codec, node, i);
unmute_output(codec, node);
return err;
}
}
return 0;
}
/* input capable? */
if (! (node->pin_caps & AC_PINCAP_IN))
return 0;
if (defcfg_port_conn(node) == AC_JACK_PORT_NONE)
return 0; /* unconnected */
if (node->wid_caps & AC_WCAP_DIGITAL)
return 0; /* skip SPDIF */
if (spec->input_mux.num_items >= HDA_MAX_NUM_INPUTS) {
snd_printk(KERN_ERR "hda_generic: Too many items for capture\n");
return -EINVAL;
}
pinctl = AC_PINCTL_IN_EN;
/* create a proper capture source label */
type = get_input_type(node, &pinctl);
if (! type) {
/* input as default? */
if (! (node->pin_ctl & AC_PINCTL_IN_EN))
return 0;
type = "Input";
}
snd_hda_add_imux_item(&spec->input_mux, type, idx, NULL);
/* unmute the PIN external input */
unmute_input(codec, node, 0); /* index = 0? */
/* set PIN-In enable */
snd_hda_codec_write_cache(codec, node->nid, 0,
AC_VERB_SET_PIN_WIDGET_CONTROL, pinctl);
return 1; /* found */
}
/*
* parse input
*/
static int parse_input_path(struct hda_codec *codec, struct hda_gnode *adc_node)
{
struct hda_gspec *spec = codec->spec;
struct hda_gnode *node;
int i, err;
snd_printdd("AUD_IN = %x\n", adc_node->nid);
clear_check_flags(spec);
// awk added - fixed no recording due to muted widget
unmute_input(codec, adc_node, 0);
/*
* check each connection of the ADC
* if it reaches to a proper input PIN, add the path as the
* input path.
*/
/* first, check the direct connections to PIN widgets */
for (i = 0; i < adc_node->nconns; i++) {
node = hda_get_node(spec, adc_node->conn_list[i]);
if (node && node->type == AC_WID_PIN) {
err = parse_adc_sub_nodes(codec, spec, node, i);
if (err < 0)
return err;
}
}
/* ... then check the rests, more complicated connections */
for (i = 0; i < adc_node->nconns; i++) {
node = hda_get_node(spec, adc_node->conn_list[i]);
if (node && node->type != AC_WID_PIN) {
err = parse_adc_sub_nodes(codec, spec, node, i);
if (err < 0)
return err;
}
}
if (! spec->input_mux.num_items)
return 0; /* no input path found... */
snd_printdd("[Capture Source] NID=0x%x, #SRC=%d\n", adc_node->nid, spec->input_mux.num_items);
for (i = 0; i < spec->input_mux.num_items; i++)
snd_printdd(" [%s] IDX=0x%x\n", spec->input_mux.items[i].label,
spec->input_mux.items[i].index);
spec->adc_node = adc_node;
return 1;
}
/*
* parse input
*/
static int parse_input(struct hda_codec *codec)
{
struct hda_gspec *spec = codec->spec;
struct hda_gnode *node;
int err;
/*
* At first we look for an audio input widget.
* If it reaches to certain input PINs, we take it as the
* input path.
*/
list_for_each_entry(node, &spec->nid_list, list) {
if (node->wid_caps & AC_WCAP_DIGITAL)
continue; /* skip SPDIF */
if (node->type == AC_WID_AUD_IN) {
err = parse_input_path(codec, node);
if (err < 0)
return err;
else if (err > 0)
return 0;
}
}
snd_printd("hda_generic: no proper input path found\n");
return 0;
}
#ifdef CONFIG_SND_HDA_POWER_SAVE
static void add_input_loopback(struct hda_codec *codec, hda_nid_t nid,
int dir, int idx)
{
struct hda_gspec *spec = codec->spec;
struct hda_amp_list *p;
if (spec->num_loopbacks >= MAX_LOOPBACK_AMPS) {
snd_printk(KERN_ERR "hda_generic: Too many loopback ctls\n");
return;
}
p = &spec->loopback_list[spec->num_loopbacks++];
p->nid = nid;
p->dir = dir;
p->idx = idx;
spec->loopback.amplist = spec->loopback_list;
}
#else
#define add_input_loopback(codec,nid,dir,idx)
#endif
/*
* create mixer controls if possible
*/
static int create_mixer(struct hda_codec *codec, struct hda_gnode *node,
unsigned int index, const char *type,
const char *dir_sfx, int is_loopback)
{
char name[32];
int err;
int created = 0;
struct snd_kcontrol_new knew;
if (type)
sprintf(name, "%s %s Switch", type, dir_sfx);
else
sprintf(name, "%s Switch", dir_sfx);
if ((node->wid_caps & AC_WCAP_IN_AMP) &&
(node->amp_in_caps & AC_AMPCAP_MUTE)) {
knew = (struct snd_kcontrol_new)HDA_CODEC_MUTE(name, node->nid, index, HDA_INPUT);
if (is_loopback)
add_input_loopback(codec, node->nid, HDA_INPUT, index);
snd_printdd("[%s] NID=0x%x, DIR=IN, IDX=0x%x\n", name, node->nid, index);
err = snd_hda_ctl_add(codec, node->nid,
snd_ctl_new1(&knew, codec));
if (err < 0)
return err;
created = 1;
} else if ((node->wid_caps & AC_WCAP_OUT_AMP) &&
(node->amp_out_caps & AC_AMPCAP_MUTE)) {
knew = (struct snd_kcontrol_new)HDA_CODEC_MUTE(name, node->nid, 0, HDA_OUTPUT);
if (is_loopback)
add_input_loopback(codec, node->nid, HDA_OUTPUT, 0);
snd_printdd("[%s] NID=0x%x, DIR=OUT\n", name, node->nid);
err = snd_hda_ctl_add(codec, node->nid,
snd_ctl_new1(&knew, codec));
if (err < 0)
return err;
created = 1;
}
if (type)
sprintf(name, "%s %s Volume", type, dir_sfx);
else
sprintf(name, "%s Volume", dir_sfx);
if ((node->wid_caps & AC_WCAP_IN_AMP) &&
(node->amp_in_caps & AC_AMPCAP_NUM_STEPS)) {
knew = (struct snd_kcontrol_new)HDA_CODEC_VOLUME(name, node->nid, index, HDA_INPUT);
snd_printdd("[%s] NID=0x%x, DIR=IN, IDX=0x%x\n", name, node->nid, index);
err = snd_hda_ctl_add(codec, node->nid,
snd_ctl_new1(&knew, codec));
if (err < 0)
return err;
created = 1;
} else if ((node->wid_caps & AC_WCAP_OUT_AMP) &&
(node->amp_out_caps & AC_AMPCAP_NUM_STEPS)) {
knew = (struct snd_kcontrol_new)HDA_CODEC_VOLUME(name, node->nid, 0, HDA_OUTPUT);
snd_printdd("[%s] NID=0x%x, DIR=OUT\n", name, node->nid);
err = snd_hda_ctl_add(codec, node->nid,
snd_ctl_new1(&knew, codec));
if (err < 0)
return err;
created = 1;
}
return created;
}
/*
* check whether the controls with the given name and direction suffix already exist
*/
static int check_existing_control(struct hda_codec *codec, const char *type, const char *dir)
{
struct snd_ctl_elem_id id;
memset(&id, 0, sizeof(id));
sprintf(id.name, "%s %s Volume", type, dir);
id.iface = SNDRV_CTL_ELEM_IFACE_MIXER;
if (snd_ctl_find_id(codec->bus->card, &id))
return 1;
sprintf(id.name, "%s %s Switch", type, dir);
id.iface = SNDRV_CTL_ELEM_IFACE_MIXER;
if (snd_ctl_find_id(codec->bus->card, &id))
return 1;
return 0;
}
/*
* build output mixer controls
*/
static int create_output_mixers(struct hda_codec *codec,
const char * const *names)
{
struct hda_gspec *spec = codec->spec;
int i, err;
for (i = 0; i < spec->pcm_vol_nodes; i++) {
err = create_mixer(codec, spec->pcm_vol[i].node,
spec->pcm_vol[i].index,
names[i], "Playback", 0);
if (err < 0)
return err;
}
return 0;
}
static int build_output_controls(struct hda_codec *codec)
{
struct hda_gspec *spec = codec->spec;
static const char * const types_speaker[] = { "Speaker", "Headphone" };
static const char * const types_line[] = { "Front", "Headphone" };
switch (spec->pcm_vol_nodes) {
case 1:
return create_mixer(codec, spec->pcm_vol[0].node,
spec->pcm_vol[0].index,
"Master", "Playback", 0);
case 2:
if (defcfg_type(spec->out_pin_node[0]) == AC_JACK_SPEAKER)
return create_output_mixers(codec, types_speaker);
else
return create_output_mixers(codec, types_line);
}
return 0;
}
/* create capture volume/switch */
static int build_input_controls(struct hda_codec *codec)
{
struct hda_gspec *spec = codec->spec;
struct hda_gnode *adc_node = spec->adc_node;
int i, err;
static struct snd_kcontrol_new cap_sel = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Capture Source",
.info = capture_source_info,
.get = capture_source_get,
.put = capture_source_put,
};
if (! adc_node || ! spec->input_mux.num_items)
return 0; /* not found */
spec->cur_cap_src = 0;
select_input_connection(codec, adc_node,
spec->input_mux.items[0].index);
/* create capture volume and switch controls if the ADC has an amp */
/* do we have only a single item? */
if (spec->input_mux.num_items == 1) {
err = create_mixer(codec, adc_node,
spec->input_mux.items[0].index,
NULL, "Capture", 0);
if (err < 0)
return err;
return 0;
}
/* create input MUX if multiple sources are available */
err = snd_hda_ctl_add(codec, spec->adc_node->nid,
snd_ctl_new1(&cap_sel, codec));
if (err < 0)
return err;
/* no volume control? */
if (! (adc_node->wid_caps & AC_WCAP_IN_AMP) ||
! (adc_node->amp_in_caps & AC_AMPCAP_NUM_STEPS))
return 0;
for (i = 0; i < spec->input_mux.num_items; i++) {
struct snd_kcontrol_new knew;
char name[32];
sprintf(name, "%s Capture Volume",
spec->input_mux.items[i].label);
knew = (struct snd_kcontrol_new)
HDA_CODEC_VOLUME(name, adc_node->nid,
spec->input_mux.items[i].index,
HDA_INPUT);
err = snd_hda_ctl_add(codec, adc_node->nid,
snd_ctl_new1(&knew, codec));
if (err < 0)
return err;
}
return 0;
}
/*
* parse the nodes recursively until reach to the output PIN.
*
* returns 0 - if not found,
* 1 - if found, but no mixer is created
* 2 - if found and mixer was already created, (just skip)
* a negative error code
*/
static int parse_loopback_path(struct hda_codec *codec, struct hda_gspec *spec,
struct hda_gnode *node, struct hda_gnode *dest_node,
const char *type)
{
int i, err;
if (node->checked)
return 0;
node->checked = 1;
if (node == dest_node) {
/* loopback connection found */
return 1;
}
for (i = 0; i < node->nconns; i++) {
struct hda_gnode *child = hda_get_node(spec, node->conn_list[i]);
if (! child)
continue;
err = parse_loopback_path(codec, spec, child, dest_node, type);
if (err < 0)
return err;
else if (err >= 1) {
if (err == 1) {
err = create_mixer(codec, node, i, type,
"Playback", 1);
if (err < 0)
return err;
if (err > 0)
return 2; /* ok, created */
/* not created, maybe in the lower path */
err = 1;
}
/* connect and unmute */
if (node->nconns > 1)
select_input_connection(codec, node, i);
unmute_input(codec, node, i);
unmute_output(codec, node);
return err;
}
}
return 0;
}
/*
* parse the tree and build the loopback controls
*/
static int build_loopback_controls(struct hda_codec *codec)
{
struct hda_gspec *spec = codec->spec;
struct hda_gnode *node;
int err;
const char *type;
if (! spec->out_pin_node[0])
return 0;
list_for_each_entry(node, &spec->nid_list, list) {
if (node->type != AC_WID_PIN)
continue;
/* input capable? */
if (! (node->pin_caps & AC_PINCAP_IN))
return 0;
type = get_input_type(node, NULL);
if (type) {
if (check_existing_control(codec, type, "Playback"))
continue;
clear_check_flags(spec);
err = parse_loopback_path(codec, spec,
spec->out_pin_node[0],
node, type);
if (err < 0)
return err;
if (! err)
continue;
}
}
return 0;
}
/*
* build mixer controls
*/
static int build_generic_controls(struct hda_codec *codec)
{
int err;
if ((err = build_input_controls(codec)) < 0 ||
(err = build_output_controls(codec)) < 0 ||
(err = build_loopback_controls(codec)) < 0)
return err;
return 0;
}
/*
* PCM
*/
static struct hda_pcm_stream generic_pcm_playback = {
.substreams = 1,
.channels_min = 2,
.channels_max = 2,
};
static int generic_pcm2_prepare(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
unsigned int stream_tag,
unsigned int format,
struct snd_pcm_substream *substream)
{
struct hda_gspec *spec = codec->spec;
snd_hda_codec_setup_stream(codec, hinfo->nid, stream_tag, 0, format);
snd_hda_codec_setup_stream(codec, spec->dac_node[1]->nid,
stream_tag, 0, format);
return 0;
}
static int generic_pcm2_cleanup(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
struct snd_pcm_substream *substream)
{
struct hda_gspec *spec = codec->spec;
snd_hda_codec_cleanup_stream(codec, hinfo->nid);
snd_hda_codec_cleanup_stream(codec, spec->dac_node[1]->nid);
return 0;
}
static int build_generic_pcms(struct hda_codec *codec)
{
struct hda_gspec *spec = codec->spec;
struct hda_pcm *info = &spec->pcm_rec;
if (! spec->dac_node[0] && ! spec->adc_node) {
snd_printd("hda_generic: no PCM found\n");
return 0;
}
codec->num_pcms = 1;
codec->pcm_info = info;
info->name = "HDA Generic";
if (spec->dac_node[0]) {
info->stream[0] = generic_pcm_playback;
info->stream[0].nid = spec->dac_node[0]->nid;
if (spec->dac_node[1]) {
info->stream[0].ops.prepare = generic_pcm2_prepare;
info->stream[0].ops.cleanup = generic_pcm2_cleanup;
}
}
if (spec->adc_node) {
info->stream[1] = generic_pcm_playback;
info->stream[1].nid = spec->adc_node->nid;
}
return 0;
}
#ifdef CONFIG_SND_HDA_POWER_SAVE
static int generic_check_power_status(struct hda_codec *codec, hda_nid_t nid)
{
struct hda_gspec *spec = codec->spec;
return snd_hda_check_amp_list_power(codec, &spec->loopback, nid);
}
#endif
/*
*/
static struct hda_codec_ops generic_patch_ops = {
.build_controls = build_generic_controls,
.build_pcms = build_generic_pcms,
.free = snd_hda_generic_free,
#ifdef CONFIG_SND_HDA_POWER_SAVE
.check_power_status = generic_check_power_status,
#endif
};
/*
* the generic parser
*/
int snd_hda_parse_generic_codec(struct hda_codec *codec)
{
struct hda_gspec *spec;
int err;
if(!codec->afg)
return 0;
spec = kzalloc(sizeof(*spec), GFP_KERNEL);
if (spec == NULL) {
printk(KERN_ERR "hda_generic: can't allocate spec\n");
return -ENOMEM;
}
codec->spec = spec;
INIT_LIST_HEAD(&spec->nid_list);
if ((err = build_afg_tree(codec)) < 0)
goto error;
if ((err = parse_input(codec)) < 0 ||
(err = parse_output(codec)) < 0)
goto error;
codec->patch_ops = generic_patch_ops;
return 0;
error:
snd_hda_generic_free(codec);
return err;
}
EXPORT_SYMBOL(snd_hda_parse_generic_codec);
| gpl-2.0 |
jmztaylor/android_kernel_htc_a3ul_new | drivers/gpu/drm/nouveau/nv50_gpio.c | 5443 | 3692 | /*
* Copyright 2010 Red Hat Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors: Ben Skeggs
*/
#include "drmP.h"
#include "nouveau_drv.h"
#include "nouveau_hw.h"
#include "nouveau_gpio.h"
#include "nv50_display.h"
static int
nv50_gpio_location(int line, u32 *reg, u32 *shift)
{
const uint32_t nv50_gpio_reg[4] = { 0xe104, 0xe108, 0xe280, 0xe284 };
if (line >= 32)
return -EINVAL;
*reg = nv50_gpio_reg[line >> 3];
*shift = (line & 7) << 2;
return 0;
}
int
nv50_gpio_drive(struct drm_device *dev, int line, int dir, int out)
{
u32 reg, shift;
if (nv50_gpio_location(line, ®, &shift))
return -EINVAL;
nv_mask(dev, reg, 7 << shift, (((dir ^ 1) << 1) | out) << shift);
return 0;
}
int
nv50_gpio_sense(struct drm_device *dev, int line)
{
u32 reg, shift;
if (nv50_gpio_location(line, ®, &shift))
return -EINVAL;
return !!(nv_rd32(dev, reg) & (4 << shift));
}
void
nv50_gpio_irq_enable(struct drm_device *dev, int line, bool on)
{
u32 reg = line < 16 ? 0xe050 : 0xe070;
u32 mask = 0x00010001 << (line & 0xf);
nv_wr32(dev, reg + 4, mask);
nv_mask(dev, reg + 0, mask, on ? mask : 0);
}
int
nvd0_gpio_drive(struct drm_device *dev, int line, int dir, int out)
{
u32 data = ((dir ^ 1) << 13) | (out << 12);
nv_mask(dev, 0x00d610 + (line * 4), 0x00003000, data);
nv_mask(dev, 0x00d604, 0x00000001, 0x00000001); /* update? */
return 0;
}
int
nvd0_gpio_sense(struct drm_device *dev, int line)
{
return !!(nv_rd32(dev, 0x00d610 + (line * 4)) & 0x00004000);
}
static void
nv50_gpio_isr(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
u32 intr0, intr1 = 0;
u32 hi, lo;
intr0 = nv_rd32(dev, 0xe054) & nv_rd32(dev, 0xe050);
if (dev_priv->chipset >= 0x90)
intr1 = nv_rd32(dev, 0xe074) & nv_rd32(dev, 0xe070);
hi = (intr0 & 0x0000ffff) | (intr1 << 16);
lo = (intr0 >> 16) | (intr1 & 0xffff0000);
nouveau_gpio_isr(dev, 0, hi | lo);
nv_wr32(dev, 0xe054, intr0);
if (dev_priv->chipset >= 0x90)
nv_wr32(dev, 0xe074, intr1);
}
int
nv50_gpio_init(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
/* disable, and ack any pending gpio interrupts */
nv_wr32(dev, 0xe050, 0x00000000);
nv_wr32(dev, 0xe054, 0xffffffff);
if (dev_priv->chipset >= 0x90) {
nv_wr32(dev, 0xe070, 0x00000000);
nv_wr32(dev, 0xe074, 0xffffffff);
}
nouveau_irq_register(dev, 21, nv50_gpio_isr);
return 0;
}
void
nv50_gpio_fini(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
nv_wr32(dev, 0xe050, 0x00000000);
if (dev_priv->chipset >= 0x90)
nv_wr32(dev, 0xe070, 0x00000000);
nouveau_irq_unregister(dev, 21);
}
| gpl-2.0 |
CyanHacker-Lollipop/kernel_sony_msm8974pro | drivers/gpu/drm/nouveau/nouveau_irq.c | 5955 | 3995 | /*
* Copyright (C) 2006 Ben Skeggs.
*
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
/*
* Authors:
* Ben Skeggs <darktama@iinet.net.au>
*/
#include "drmP.h"
#include "drm.h"
#include "nouveau_drm.h"
#include "nouveau_drv.h"
#include "nouveau_reg.h"
#include "nouveau_ramht.h"
#include "nouveau_util.h"
void
nouveau_irq_preinstall(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
/* Master disable */
nv_wr32(dev, NV03_PMC_INTR_EN_0, 0);
INIT_LIST_HEAD(&dev_priv->vbl_waiting);
}
int
nouveau_irq_postinstall(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
/* Master enable */
nv_wr32(dev, NV03_PMC_INTR_EN_0, NV_PMC_INTR_EN_0_MASTER_ENABLE);
if (dev_priv->msi_enabled)
nv_wr08(dev, 0x00088068, 0xff);
return 0;
}
void
nouveau_irq_uninstall(struct drm_device *dev)
{
/* Master disable */
nv_wr32(dev, NV03_PMC_INTR_EN_0, 0);
}
irqreturn_t
nouveau_irq_handler(DRM_IRQ_ARGS)
{
struct drm_device *dev = (struct drm_device *)arg;
struct drm_nouveau_private *dev_priv = dev->dev_private;
unsigned long flags;
u32 stat;
int i;
stat = nv_rd32(dev, NV03_PMC_INTR_0);
if (stat == 0 || stat == ~0)
return IRQ_NONE;
spin_lock_irqsave(&dev_priv->context_switch_lock, flags);
for (i = 0; i < 32 && stat; i++) {
if (!(stat & (1 << i)) || !dev_priv->irq_handler[i])
continue;
dev_priv->irq_handler[i](dev);
stat &= ~(1 << i);
}
if (dev_priv->msi_enabled)
nv_wr08(dev, 0x00088068, 0xff);
spin_unlock_irqrestore(&dev_priv->context_switch_lock, flags);
if (stat && nouveau_ratelimit())
NV_ERROR(dev, "PMC - unhandled INTR 0x%08x\n", stat);
return IRQ_HANDLED;
}
int
nouveau_irq_init(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
int ret;
if (nouveau_msi != 0 && dev_priv->card_type >= NV_50) {
ret = pci_enable_msi(dev->pdev);
if (ret == 0) {
NV_INFO(dev, "enabled MSI\n");
dev_priv->msi_enabled = true;
}
}
return drm_irq_install(dev);
}
void
nouveau_irq_fini(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
drm_irq_uninstall(dev);
if (dev_priv->msi_enabled)
pci_disable_msi(dev->pdev);
}
void
nouveau_irq_register(struct drm_device *dev, int status_bit,
void (*handler)(struct drm_device *))
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
unsigned long flags;
spin_lock_irqsave(&dev_priv->context_switch_lock, flags);
dev_priv->irq_handler[status_bit] = handler;
spin_unlock_irqrestore(&dev_priv->context_switch_lock, flags);
}
void
nouveau_irq_unregister(struct drm_device *dev, int status_bit)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
unsigned long flags;
spin_lock_irqsave(&dev_priv->context_switch_lock, flags);
dev_priv->irq_handler[status_bit] = NULL;
spin_unlock_irqrestore(&dev_priv->context_switch_lock, flags);
}
| gpl-2.0 |
qkdxorjs1002/android_kernel_samsung_slteskt | drivers/net/mdio.c | 7491 | 13088 | /*
* mdio.c: Generic support for MDIO-compatible transceivers
* Copyright 2006-2009 Solarflare Communications Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation, incorporated herein by reference.
*/
#include <linux/kernel.h>
#include <linux/capability.h>
#include <linux/errno.h>
#include <linux/ethtool.h>
#include <linux/mdio.h>
#include <linux/module.h>
MODULE_DESCRIPTION("Generic support for MDIO-compatible transceivers");
MODULE_AUTHOR("Copyright 2006-2009 Solarflare Communications Inc.");
MODULE_LICENSE("GPL");
/**
* mdio45_probe - probe for an MDIO (clause 45) device
* @mdio: MDIO interface
* @prtad: Expected PHY address
*
* This sets @prtad and @mmds in the MDIO interface if successful.
* Returns 0 on success, negative on error.
*/
int mdio45_probe(struct mdio_if_info *mdio, int prtad)
{
int mmd, stat2, devs1, devs2;
/* Assume PHY must have at least one of PMA/PMD, WIS, PCS, PHY
* XS or DTE XS; give up if none is present. */
for (mmd = 1; mmd <= 5; mmd++) {
/* Is this MMD present? */
stat2 = mdio->mdio_read(mdio->dev, prtad, mmd, MDIO_STAT2);
if (stat2 < 0 ||
(stat2 & MDIO_STAT2_DEVPRST) != MDIO_STAT2_DEVPRST_VAL)
continue;
/* It should tell us about all the other MMDs */
devs1 = mdio->mdio_read(mdio->dev, prtad, mmd, MDIO_DEVS1);
devs2 = mdio->mdio_read(mdio->dev, prtad, mmd, MDIO_DEVS2);
if (devs1 < 0 || devs2 < 0)
continue;
mdio->prtad = prtad;
mdio->mmds = devs1 | (devs2 << 16);
return 0;
}
return -ENODEV;
}
EXPORT_SYMBOL(mdio45_probe);
/**
* mdio_set_flag - set or clear flag in an MDIO register
* @mdio: MDIO interface
* @prtad: PHY address
* @devad: MMD address
* @addr: Register address
* @mask: Mask for flag (single bit set)
* @sense: New value of flag
*
* This debounces changes: it does not write the register if the flag
* already has the proper value. Returns 0 on success, negative on error.
*/
int mdio_set_flag(const struct mdio_if_info *mdio,
int prtad, int devad, u16 addr, int mask,
bool sense)
{
int old_val = mdio->mdio_read(mdio->dev, prtad, devad, addr);
int new_val;
if (old_val < 0)
return old_val;
if (sense)
new_val = old_val | mask;
else
new_val = old_val & ~mask;
if (old_val == new_val)
return 0;
return mdio->mdio_write(mdio->dev, prtad, devad, addr, new_val);
}
EXPORT_SYMBOL(mdio_set_flag);
/**
* mdio_link_ok - is link status up/OK
* @mdio: MDIO interface
* @mmd_mask: Mask for MMDs to check
*
* Returns 1 if the PHY reports link status up/OK, 0 otherwise.
* @mmd_mask is normally @mdio->mmds, but if loopback is enabled
* the MMDs being bypassed should be excluded from the mask.
*/
int mdio45_links_ok(const struct mdio_if_info *mdio, u32 mmd_mask)
{
int devad, reg;
if (!mmd_mask) {
/* Use absence of XGMII faults in lieu of link state */
reg = mdio->mdio_read(mdio->dev, mdio->prtad,
MDIO_MMD_PHYXS, MDIO_STAT2);
return reg >= 0 && !(reg & MDIO_STAT2_RXFAULT);
}
for (devad = 0; mmd_mask; devad++) {
if (mmd_mask & (1 << devad)) {
mmd_mask &= ~(1 << devad);
/* Reset the latched status and fault flags */
mdio->mdio_read(mdio->dev, mdio->prtad,
devad, MDIO_STAT1);
if (devad == MDIO_MMD_PMAPMD || devad == MDIO_MMD_PCS ||
devad == MDIO_MMD_PHYXS || devad == MDIO_MMD_DTEXS)
mdio->mdio_read(mdio->dev, mdio->prtad,
devad, MDIO_STAT2);
/* Check the current status and fault flags */
reg = mdio->mdio_read(mdio->dev, mdio->prtad,
devad, MDIO_STAT1);
if (reg < 0 ||
(reg & (MDIO_STAT1_FAULT | MDIO_STAT1_LSTATUS)) !=
MDIO_STAT1_LSTATUS)
return false;
}
}
return true;
}
EXPORT_SYMBOL(mdio45_links_ok);
/**
* mdio45_nway_restart - restart auto-negotiation for this interface
* @mdio: MDIO interface
*
* Returns 0 on success, negative on error.
*/
int mdio45_nway_restart(const struct mdio_if_info *mdio)
{
if (!(mdio->mmds & MDIO_DEVS_AN))
return -EOPNOTSUPP;
mdio_set_flag(mdio, mdio->prtad, MDIO_MMD_AN, MDIO_CTRL1,
MDIO_AN_CTRL1_RESTART, true);
return 0;
}
EXPORT_SYMBOL(mdio45_nway_restart);
static u32 mdio45_get_an(const struct mdio_if_info *mdio, u16 addr)
{
u32 result = 0;
int reg;
reg = mdio->mdio_read(mdio->dev, mdio->prtad, MDIO_MMD_AN, addr);
if (reg & ADVERTISE_10HALF)
result |= ADVERTISED_10baseT_Half;
if (reg & ADVERTISE_10FULL)
result |= ADVERTISED_10baseT_Full;
if (reg & ADVERTISE_100HALF)
result |= ADVERTISED_100baseT_Half;
if (reg & ADVERTISE_100FULL)
result |= ADVERTISED_100baseT_Full;
if (reg & ADVERTISE_PAUSE_CAP)
result |= ADVERTISED_Pause;
if (reg & ADVERTISE_PAUSE_ASYM)
result |= ADVERTISED_Asym_Pause;
return result;
}
/**
* mdio45_ethtool_gset_npage - get settings for ETHTOOL_GSET
* @mdio: MDIO interface
* @ecmd: Ethtool request structure
* @npage_adv: Modes currently advertised on next pages
* @npage_lpa: Modes advertised by link partner on next pages
*
* The @ecmd parameter is expected to have been cleared before calling
* mdio45_ethtool_gset_npage().
*
* Since the CSRs for auto-negotiation using next pages are not fully
* standardised, this function does not attempt to decode them. The
* caller must pass them in.
*/
void mdio45_ethtool_gset_npage(const struct mdio_if_info *mdio,
struct ethtool_cmd *ecmd,
u32 npage_adv, u32 npage_lpa)
{
int reg;
u32 speed;
BUILD_BUG_ON(MDIO_SUPPORTS_C22 != ETH_MDIO_SUPPORTS_C22);
BUILD_BUG_ON(MDIO_SUPPORTS_C45 != ETH_MDIO_SUPPORTS_C45);
ecmd->transceiver = XCVR_INTERNAL;
ecmd->phy_address = mdio->prtad;
ecmd->mdio_support =
mdio->mode_support & (MDIO_SUPPORTS_C45 | MDIO_SUPPORTS_C22);
reg = mdio->mdio_read(mdio->dev, mdio->prtad, MDIO_MMD_PMAPMD,
MDIO_CTRL2);
switch (reg & MDIO_PMA_CTRL2_TYPE) {
case MDIO_PMA_CTRL2_10GBT:
case MDIO_PMA_CTRL2_1000BT:
case MDIO_PMA_CTRL2_100BTX:
case MDIO_PMA_CTRL2_10BT:
ecmd->port = PORT_TP;
ecmd->supported = SUPPORTED_TP;
reg = mdio->mdio_read(mdio->dev, mdio->prtad, MDIO_MMD_PMAPMD,
MDIO_SPEED);
if (reg & MDIO_SPEED_10G)
ecmd->supported |= SUPPORTED_10000baseT_Full;
if (reg & MDIO_PMA_SPEED_1000)
ecmd->supported |= (SUPPORTED_1000baseT_Full |
SUPPORTED_1000baseT_Half);
if (reg & MDIO_PMA_SPEED_100)
ecmd->supported |= (SUPPORTED_100baseT_Full |
SUPPORTED_100baseT_Half);
if (reg & MDIO_PMA_SPEED_10)
ecmd->supported |= (SUPPORTED_10baseT_Full |
SUPPORTED_10baseT_Half);
ecmd->advertising = ADVERTISED_TP;
break;
case MDIO_PMA_CTRL2_10GBCX4:
ecmd->port = PORT_OTHER;
ecmd->supported = 0;
ecmd->advertising = 0;
break;
case MDIO_PMA_CTRL2_10GBKX4:
case MDIO_PMA_CTRL2_10GBKR:
case MDIO_PMA_CTRL2_1000BKX:
ecmd->port = PORT_OTHER;
ecmd->supported = SUPPORTED_Backplane;
reg = mdio->mdio_read(mdio->dev, mdio->prtad, MDIO_MMD_PMAPMD,
MDIO_PMA_EXTABLE);
if (reg & MDIO_PMA_EXTABLE_10GBKX4)
ecmd->supported |= SUPPORTED_10000baseKX4_Full;
if (reg & MDIO_PMA_EXTABLE_10GBKR)
ecmd->supported |= SUPPORTED_10000baseKR_Full;
if (reg & MDIO_PMA_EXTABLE_1000BKX)
ecmd->supported |= SUPPORTED_1000baseKX_Full;
reg = mdio->mdio_read(mdio->dev, mdio->prtad, MDIO_MMD_PMAPMD,
MDIO_PMA_10GBR_FECABLE);
if (reg & MDIO_PMA_10GBR_FECABLE_ABLE)
ecmd->supported |= SUPPORTED_10000baseR_FEC;
ecmd->advertising = ADVERTISED_Backplane;
break;
/* All the other defined modes are flavours of optical */
default:
ecmd->port = PORT_FIBRE;
ecmd->supported = SUPPORTED_FIBRE;
ecmd->advertising = ADVERTISED_FIBRE;
break;
}
if (mdio->mmds & MDIO_DEVS_AN) {
ecmd->supported |= SUPPORTED_Autoneg;
reg = mdio->mdio_read(mdio->dev, mdio->prtad, MDIO_MMD_AN,
MDIO_CTRL1);
if (reg & MDIO_AN_CTRL1_ENABLE) {
ecmd->autoneg = AUTONEG_ENABLE;
ecmd->advertising |=
ADVERTISED_Autoneg |
mdio45_get_an(mdio, MDIO_AN_ADVERTISE) |
npage_adv;
} else {
ecmd->autoneg = AUTONEG_DISABLE;
}
} else {
ecmd->autoneg = AUTONEG_DISABLE;
}
if (ecmd->autoneg) {
u32 modes = 0;
int an_stat = mdio->mdio_read(mdio->dev, mdio->prtad,
MDIO_MMD_AN, MDIO_STAT1);
/* If AN is complete and successful, report best common
* mode, otherwise report best advertised mode. */
if (an_stat & MDIO_AN_STAT1_COMPLETE) {
ecmd->lp_advertising =
mdio45_get_an(mdio, MDIO_AN_LPA) | npage_lpa;
if (an_stat & MDIO_AN_STAT1_LPABLE)
ecmd->lp_advertising |= ADVERTISED_Autoneg;
modes = ecmd->advertising & ecmd->lp_advertising;
}
if ((modes & ~ADVERTISED_Autoneg) == 0)
modes = ecmd->advertising;
if (modes & (ADVERTISED_10000baseT_Full |
ADVERTISED_10000baseKX4_Full |
ADVERTISED_10000baseKR_Full)) {
speed = SPEED_10000;
ecmd->duplex = DUPLEX_FULL;
} else if (modes & (ADVERTISED_1000baseT_Full |
ADVERTISED_1000baseT_Half |
ADVERTISED_1000baseKX_Full)) {
speed = SPEED_1000;
ecmd->duplex = !(modes & ADVERTISED_1000baseT_Half);
} else if (modes & (ADVERTISED_100baseT_Full |
ADVERTISED_100baseT_Half)) {
speed = SPEED_100;
ecmd->duplex = !!(modes & ADVERTISED_100baseT_Full);
} else {
speed = SPEED_10;
ecmd->duplex = !!(modes & ADVERTISED_10baseT_Full);
}
} else {
/* Report forced settings */
reg = mdio->mdio_read(mdio->dev, mdio->prtad, MDIO_MMD_PMAPMD,
MDIO_CTRL1);
speed = (((reg & MDIO_PMA_CTRL1_SPEED1000) ? 100 : 1)
* ((reg & MDIO_PMA_CTRL1_SPEED100) ? 100 : 10));
ecmd->duplex = (reg & MDIO_CTRL1_FULLDPLX ||
speed == SPEED_10000);
}
ethtool_cmd_speed_set(ecmd, speed);
/* 10GBASE-T MDI/MDI-X */
if (ecmd->port == PORT_TP
&& (ethtool_cmd_speed(ecmd) == SPEED_10000)) {
switch (mdio->mdio_read(mdio->dev, mdio->prtad, MDIO_MMD_PMAPMD,
MDIO_PMA_10GBT_SWAPPOL)) {
case MDIO_PMA_10GBT_SWAPPOL_ABNX | MDIO_PMA_10GBT_SWAPPOL_CDNX:
ecmd->eth_tp_mdix = ETH_TP_MDI;
break;
case 0:
ecmd->eth_tp_mdix = ETH_TP_MDI_X;
break;
default:
/* It's complicated... */
ecmd->eth_tp_mdix = ETH_TP_MDI_INVALID;
break;
}
}
}
EXPORT_SYMBOL(mdio45_ethtool_gset_npage);
/**
* mdio45_ethtool_spauseparam_an - set auto-negotiated pause parameters
* @mdio: MDIO interface
* @ecmd: Ethtool request structure
*
* This function assumes that the PHY has an auto-negotiation MMD. It
* will enable and disable advertising of flow control as appropriate.
*/
void mdio45_ethtool_spauseparam_an(const struct mdio_if_info *mdio,
const struct ethtool_pauseparam *ecmd)
{
int adv, old_adv;
WARN_ON(!(mdio->mmds & MDIO_DEVS_AN));
old_adv = mdio->mdio_read(mdio->dev, mdio->prtad, MDIO_MMD_AN,
MDIO_AN_ADVERTISE);
adv = ((old_adv & ~(ADVERTISE_PAUSE_CAP | ADVERTISE_PAUSE_ASYM)) |
mii_advertise_flowctrl((ecmd->rx_pause ? FLOW_CTRL_RX : 0) |
(ecmd->tx_pause ? FLOW_CTRL_TX : 0)));
if (adv != old_adv) {
mdio->mdio_write(mdio->dev, mdio->prtad, MDIO_MMD_AN,
MDIO_AN_ADVERTISE, adv);
mdio45_nway_restart(mdio);
}
}
EXPORT_SYMBOL(mdio45_ethtool_spauseparam_an);
/**
* mdio_mii_ioctl - MII ioctl interface for MDIO (clause 22 or 45) PHYs
* @mdio: MDIO interface
* @mii_data: MII ioctl data structure
* @cmd: MII ioctl command
*
* Returns 0 on success, negative on error.
*/
int mdio_mii_ioctl(const struct mdio_if_info *mdio,
struct mii_ioctl_data *mii_data, int cmd)
{
int prtad, devad;
u16 addr = mii_data->reg_num;
/* Validate/convert cmd to one of SIOC{G,S}MIIREG */
switch (cmd) {
case SIOCGMIIPHY:
if (mdio->prtad == MDIO_PRTAD_NONE)
return -EOPNOTSUPP;
mii_data->phy_id = mdio->prtad;
cmd = SIOCGMIIREG;
break;
case SIOCGMIIREG:
case SIOCSMIIREG:
break;
default:
return -EOPNOTSUPP;
}
/* Validate/convert phy_id */
if ((mdio->mode_support & MDIO_SUPPORTS_C45) &&
mdio_phy_id_is_c45(mii_data->phy_id)) {
prtad = mdio_phy_id_prtad(mii_data->phy_id);
devad = mdio_phy_id_devad(mii_data->phy_id);
} else if ((mdio->mode_support & MDIO_SUPPORTS_C22) &&
mii_data->phy_id < 0x20) {
prtad = mii_data->phy_id;
devad = MDIO_DEVAD_NONE;
addr &= 0x1f;
} else if ((mdio->mode_support & MDIO_EMULATE_C22) &&
mdio->prtad != MDIO_PRTAD_NONE &&
mii_data->phy_id == mdio->prtad) {
/* Remap commonly-used MII registers. */
prtad = mdio->prtad;
switch (addr) {
case MII_BMCR:
case MII_BMSR:
case MII_PHYSID1:
case MII_PHYSID2:
devad = __ffs(mdio->mmds);
break;
case MII_ADVERTISE:
case MII_LPA:
if (!(mdio->mmds & MDIO_DEVS_AN))
return -EINVAL;
devad = MDIO_MMD_AN;
if (addr == MII_ADVERTISE)
addr = MDIO_AN_ADVERTISE;
else
addr = MDIO_AN_LPA;
break;
default:
return -EINVAL;
}
} else {
return -EINVAL;
}
if (cmd == SIOCGMIIREG) {
int rc = mdio->mdio_read(mdio->dev, prtad, devad, addr);
if (rc < 0)
return rc;
mii_data->val_out = rc;
return 0;
} else {
return mdio->mdio_write(mdio->dev, prtad, devad, addr,
mii_data->val_in);
}
}
EXPORT_SYMBOL(mdio_mii_ioctl);
| gpl-2.0 |
moddingg33k/android_kernel_huawai_Y300-J1 | drivers/infiniband/hw/ipath/ipath_mad.c | 8515 | 42537 | /*
* Copyright (c) 2006, 2007, 2008 QLogic Corporation. All rights reserved.
* Copyright (c) 2005, 2006 PathScale, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <rdma/ib_smi.h>
#include <rdma/ib_pma.h>
#include "ipath_kernel.h"
#include "ipath_verbs.h"
#include "ipath_common.h"
#define IB_SMP_UNSUP_VERSION cpu_to_be16(0x0004)
#define IB_SMP_UNSUP_METHOD cpu_to_be16(0x0008)
#define IB_SMP_UNSUP_METH_ATTR cpu_to_be16(0x000C)
#define IB_SMP_INVALID_FIELD cpu_to_be16(0x001C)
static int reply(struct ib_smp *smp)
{
/*
* The verbs framework will handle the directed/LID route
* packet changes.
*/
smp->method = IB_MGMT_METHOD_GET_RESP;
if (smp->mgmt_class == IB_MGMT_CLASS_SUBN_DIRECTED_ROUTE)
smp->status |= IB_SMP_DIRECTION;
return IB_MAD_RESULT_SUCCESS | IB_MAD_RESULT_REPLY;
}
static int recv_subn_get_nodedescription(struct ib_smp *smp,
struct ib_device *ibdev)
{
if (smp->attr_mod)
smp->status |= IB_SMP_INVALID_FIELD;
memcpy(smp->data, ibdev->node_desc, sizeof(smp->data));
return reply(smp);
}
struct nodeinfo {
u8 base_version;
u8 class_version;
u8 node_type;
u8 num_ports;
__be64 sys_guid;
__be64 node_guid;
__be64 port_guid;
__be16 partition_cap;
__be16 device_id;
__be32 revision;
u8 local_port_num;
u8 vendor_id[3];
} __attribute__ ((packed));
static int recv_subn_get_nodeinfo(struct ib_smp *smp,
struct ib_device *ibdev, u8 port)
{
struct nodeinfo *nip = (struct nodeinfo *)&smp->data;
struct ipath_devdata *dd = to_idev(ibdev)->dd;
u32 vendor, majrev, minrev;
/* GUID 0 is illegal */
if (smp->attr_mod || (dd->ipath_guid == 0))
smp->status |= IB_SMP_INVALID_FIELD;
nip->base_version = 1;
nip->class_version = 1;
nip->node_type = 1; /* channel adapter */
/*
* XXX The num_ports value will need a layer function to get
* the value if we ever have more than one IB port on a chip.
* We will also need to get the GUID for the port.
*/
nip->num_ports = ibdev->phys_port_cnt;
/* This is already in network order */
nip->sys_guid = to_idev(ibdev)->sys_image_guid;
nip->node_guid = dd->ipath_guid;
nip->port_guid = dd->ipath_guid;
nip->partition_cap = cpu_to_be16(ipath_get_npkeys(dd));
nip->device_id = cpu_to_be16(dd->ipath_deviceid);
majrev = dd->ipath_majrev;
minrev = dd->ipath_minrev;
nip->revision = cpu_to_be32((majrev << 16) | minrev);
nip->local_port_num = port;
vendor = dd->ipath_vendorid;
nip->vendor_id[0] = IPATH_SRC_OUI_1;
nip->vendor_id[1] = IPATH_SRC_OUI_2;
nip->vendor_id[2] = IPATH_SRC_OUI_3;
return reply(smp);
}
static int recv_subn_get_guidinfo(struct ib_smp *smp,
struct ib_device *ibdev)
{
u32 startgx = 8 * be32_to_cpu(smp->attr_mod);
__be64 *p = (__be64 *) smp->data;
/* 32 blocks of 8 64-bit GUIDs per block */
memset(smp->data, 0, sizeof(smp->data));
/*
* We only support one GUID for now. If this changes, the
* portinfo.guid_cap field needs to be updated too.
*/
if (startgx == 0) {
__be64 g = to_idev(ibdev)->dd->ipath_guid;
if (g == 0)
/* GUID 0 is illegal */
smp->status |= IB_SMP_INVALID_FIELD;
else
/* The first is a copy of the read-only HW GUID. */
*p = g;
} else
smp->status |= IB_SMP_INVALID_FIELD;
return reply(smp);
}
static void set_link_width_enabled(struct ipath_devdata *dd, u32 w)
{
(void) dd->ipath_f_set_ib_cfg(dd, IPATH_IB_CFG_LWID_ENB, w);
}
static void set_link_speed_enabled(struct ipath_devdata *dd, u32 s)
{
(void) dd->ipath_f_set_ib_cfg(dd, IPATH_IB_CFG_SPD_ENB, s);
}
static int get_overrunthreshold(struct ipath_devdata *dd)
{
return (dd->ipath_ibcctrl >>
INFINIPATH_IBCC_OVERRUNTHRESHOLD_SHIFT) &
INFINIPATH_IBCC_OVERRUNTHRESHOLD_MASK;
}
/**
* set_overrunthreshold - set the overrun threshold
* @dd: the infinipath device
* @n: the new threshold
*
* Note that this will only take effect when the link state changes.
*/
static int set_overrunthreshold(struct ipath_devdata *dd, unsigned n)
{
unsigned v;
v = (dd->ipath_ibcctrl >> INFINIPATH_IBCC_OVERRUNTHRESHOLD_SHIFT) &
INFINIPATH_IBCC_OVERRUNTHRESHOLD_MASK;
if (v != n) {
dd->ipath_ibcctrl &=
~(INFINIPATH_IBCC_OVERRUNTHRESHOLD_MASK <<
INFINIPATH_IBCC_OVERRUNTHRESHOLD_SHIFT);
dd->ipath_ibcctrl |=
(u64) n << INFINIPATH_IBCC_OVERRUNTHRESHOLD_SHIFT;
ipath_write_kreg(dd, dd->ipath_kregs->kr_ibcctrl,
dd->ipath_ibcctrl);
}
return 0;
}
static int get_phyerrthreshold(struct ipath_devdata *dd)
{
return (dd->ipath_ibcctrl >>
INFINIPATH_IBCC_PHYERRTHRESHOLD_SHIFT) &
INFINIPATH_IBCC_PHYERRTHRESHOLD_MASK;
}
/**
* set_phyerrthreshold - set the physical error threshold
* @dd: the infinipath device
* @n: the new threshold
*
* Note that this will only take effect when the link state changes.
*/
static int set_phyerrthreshold(struct ipath_devdata *dd, unsigned n)
{
unsigned v;
v = (dd->ipath_ibcctrl >> INFINIPATH_IBCC_PHYERRTHRESHOLD_SHIFT) &
INFINIPATH_IBCC_PHYERRTHRESHOLD_MASK;
if (v != n) {
dd->ipath_ibcctrl &=
~(INFINIPATH_IBCC_PHYERRTHRESHOLD_MASK <<
INFINIPATH_IBCC_PHYERRTHRESHOLD_SHIFT);
dd->ipath_ibcctrl |=
(u64) n << INFINIPATH_IBCC_PHYERRTHRESHOLD_SHIFT;
ipath_write_kreg(dd, dd->ipath_kregs->kr_ibcctrl,
dd->ipath_ibcctrl);
}
return 0;
}
/**
* get_linkdowndefaultstate - get the default linkdown state
* @dd: the infinipath device
*
* Returns zero if the default is POLL, 1 if the default is SLEEP.
*/
static int get_linkdowndefaultstate(struct ipath_devdata *dd)
{
return !!(dd->ipath_ibcctrl & INFINIPATH_IBCC_LINKDOWNDEFAULTSTATE);
}
static int recv_subn_get_portinfo(struct ib_smp *smp,
struct ib_device *ibdev, u8 port)
{
struct ipath_ibdev *dev;
struct ipath_devdata *dd;
struct ib_port_info *pip = (struct ib_port_info *)smp->data;
u16 lid;
u8 ibcstat;
u8 mtu;
int ret;
if (be32_to_cpu(smp->attr_mod) > ibdev->phys_port_cnt) {
smp->status |= IB_SMP_INVALID_FIELD;
ret = reply(smp);
goto bail;
}
dev = to_idev(ibdev);
dd = dev->dd;
/* Clear all fields. Only set the non-zero fields. */
memset(smp->data, 0, sizeof(smp->data));
/* Only return the mkey if the protection field allows it. */
if (smp->method == IB_MGMT_METHOD_SET || dev->mkey == smp->mkey ||
dev->mkeyprot == 0)
pip->mkey = dev->mkey;
pip->gid_prefix = dev->gid_prefix;
lid = dd->ipath_lid;
pip->lid = lid ? cpu_to_be16(lid) : IB_LID_PERMISSIVE;
pip->sm_lid = cpu_to_be16(dev->sm_lid);
pip->cap_mask = cpu_to_be32(dev->port_cap_flags);
/* pip->diag_code; */
pip->mkey_lease_period = cpu_to_be16(dev->mkey_lease_period);
pip->local_port_num = port;
pip->link_width_enabled = dd->ipath_link_width_enabled;
pip->link_width_supported = dd->ipath_link_width_supported;
pip->link_width_active = dd->ipath_link_width_active;
pip->linkspeed_portstate = dd->ipath_link_speed_supported << 4;
ibcstat = dd->ipath_lastibcstat;
/* map LinkState to IB portinfo values. */
pip->linkspeed_portstate |= ipath_ib_linkstate(dd, ibcstat) + 1;
pip->portphysstate_linkdown =
(ipath_cvt_physportstate[ibcstat & dd->ibcs_lts_mask] << 4) |
(get_linkdowndefaultstate(dd) ? 1 : 2);
pip->mkeyprot_resv_lmc = (dev->mkeyprot << 6) | dd->ipath_lmc;
pip->linkspeedactive_enabled = (dd->ipath_link_speed_active << 4) |
dd->ipath_link_speed_enabled;
switch (dd->ipath_ibmtu) {
case 4096:
mtu = IB_MTU_4096;
break;
case 2048:
mtu = IB_MTU_2048;
break;
case 1024:
mtu = IB_MTU_1024;
break;
case 512:
mtu = IB_MTU_512;
break;
case 256:
mtu = IB_MTU_256;
break;
default: /* oops, something is wrong */
mtu = IB_MTU_2048;
break;
}
pip->neighbormtu_mastersmsl = (mtu << 4) | dev->sm_sl;
pip->vlcap_inittype = 0x10; /* VLCap = VL0, InitType = 0 */
pip->vl_high_limit = dev->vl_high_limit;
/* pip->vl_arb_high_cap; // only one VL */
/* pip->vl_arb_low_cap; // only one VL */
/* InitTypeReply = 0 */
/* our mtu cap depends on whether 4K MTU enabled or not */
pip->inittypereply_mtucap = ipath_mtu4096 ? IB_MTU_4096 : IB_MTU_2048;
/* HCAs ignore VLStallCount and HOQLife */
/* pip->vlstallcnt_hoqlife; */
pip->operationalvl_pei_peo_fpi_fpo = 0x10; /* OVLs = 1 */
pip->mkey_violations = cpu_to_be16(dev->mkey_violations);
/* P_KeyViolations are counted by hardware. */
pip->pkey_violations =
cpu_to_be16((ipath_get_cr_errpkey(dd) -
dev->z_pkey_violations) & 0xFFFF);
pip->qkey_violations = cpu_to_be16(dev->qkey_violations);
/* Only the hardware GUID is supported for now */
pip->guid_cap = 1;
pip->clientrereg_resv_subnetto = dev->subnet_timeout;
/* 32.768 usec. response time (guessing) */
pip->resv_resptimevalue = 3;
pip->localphyerrors_overrunerrors =
(get_phyerrthreshold(dd) << 4) |
get_overrunthreshold(dd);
/* pip->max_credit_hint; */
if (dev->port_cap_flags & IB_PORT_LINK_LATENCY_SUP) {
u32 v;
v = dd->ipath_f_get_ib_cfg(dd, IPATH_IB_CFG_LINKLATENCY);
pip->link_roundtrip_latency[0] = v >> 16;
pip->link_roundtrip_latency[1] = v >> 8;
pip->link_roundtrip_latency[2] = v;
}
ret = reply(smp);
bail:
return ret;
}
/**
* get_pkeys - return the PKEY table for port 0
* @dd: the infinipath device
* @pkeys: the pkey table is placed here
*/
static int get_pkeys(struct ipath_devdata *dd, u16 * pkeys)
{
/* always a kernel port, no locking needed */
struct ipath_portdata *pd = dd->ipath_pd[0];
memcpy(pkeys, pd->port_pkeys, sizeof(pd->port_pkeys));
return 0;
}
static int recv_subn_get_pkeytable(struct ib_smp *smp,
struct ib_device *ibdev)
{
u32 startpx = 32 * (be32_to_cpu(smp->attr_mod) & 0xffff);
u16 *p = (u16 *) smp->data;
__be16 *q = (__be16 *) smp->data;
/* 64 blocks of 32 16-bit P_Key entries */
memset(smp->data, 0, sizeof(smp->data));
if (startpx == 0) {
struct ipath_ibdev *dev = to_idev(ibdev);
unsigned i, n = ipath_get_npkeys(dev->dd);
get_pkeys(dev->dd, p);
for (i = 0; i < n; i++)
q[i] = cpu_to_be16(p[i]);
} else
smp->status |= IB_SMP_INVALID_FIELD;
return reply(smp);
}
static int recv_subn_set_guidinfo(struct ib_smp *smp,
struct ib_device *ibdev)
{
/* The only GUID we support is the first read-only entry. */
return recv_subn_get_guidinfo(smp, ibdev);
}
/**
* set_linkdowndefaultstate - set the default linkdown state
* @dd: the infinipath device
* @sleep: the new state
*
* Note that this will only take effect when the link state changes.
*/
static int set_linkdowndefaultstate(struct ipath_devdata *dd, int sleep)
{
if (sleep)
dd->ipath_ibcctrl |= INFINIPATH_IBCC_LINKDOWNDEFAULTSTATE;
else
dd->ipath_ibcctrl &= ~INFINIPATH_IBCC_LINKDOWNDEFAULTSTATE;
ipath_write_kreg(dd, dd->ipath_kregs->kr_ibcctrl,
dd->ipath_ibcctrl);
return 0;
}
/**
* recv_subn_set_portinfo - set port information
* @smp: the incoming SM packet
* @ibdev: the infiniband device
* @port: the port on the device
*
* Set Portinfo (see ch. 14.2.5.6).
*/
static int recv_subn_set_portinfo(struct ib_smp *smp,
struct ib_device *ibdev, u8 port)
{
struct ib_port_info *pip = (struct ib_port_info *)smp->data;
struct ib_event event;
struct ipath_ibdev *dev;
struct ipath_devdata *dd;
char clientrereg = 0;
u16 lid, smlid;
u8 lwe;
u8 lse;
u8 state;
u16 lstate;
u32 mtu;
int ret, ore;
if (be32_to_cpu(smp->attr_mod) > ibdev->phys_port_cnt)
goto err;
dev = to_idev(ibdev);
dd = dev->dd;
event.device = ibdev;
event.element.port_num = port;
dev->mkey = pip->mkey;
dev->gid_prefix = pip->gid_prefix;
dev->mkey_lease_period = be16_to_cpu(pip->mkey_lease_period);
lid = be16_to_cpu(pip->lid);
if (dd->ipath_lid != lid ||
dd->ipath_lmc != (pip->mkeyprot_resv_lmc & 7)) {
/* Must be a valid unicast LID address. */
if (lid == 0 || lid >= IPATH_MULTICAST_LID_BASE)
goto err;
ipath_set_lid(dd, lid, pip->mkeyprot_resv_lmc & 7);
event.event = IB_EVENT_LID_CHANGE;
ib_dispatch_event(&event);
}
smlid = be16_to_cpu(pip->sm_lid);
if (smlid != dev->sm_lid) {
/* Must be a valid unicast LID address. */
if (smlid == 0 || smlid >= IPATH_MULTICAST_LID_BASE)
goto err;
dev->sm_lid = smlid;
event.event = IB_EVENT_SM_CHANGE;
ib_dispatch_event(&event);
}
/* Allow 1x or 4x to be set (see 14.2.6.6). */
lwe = pip->link_width_enabled;
if (lwe) {
if (lwe == 0xFF)
lwe = dd->ipath_link_width_supported;
else if (lwe >= 16 || (lwe & ~dd->ipath_link_width_supported))
goto err;
set_link_width_enabled(dd, lwe);
}
/* Allow 2.5 or 5.0 Gbs. */
lse = pip->linkspeedactive_enabled & 0xF;
if (lse) {
if (lse == 15)
lse = dd->ipath_link_speed_supported;
else if (lse >= 8 || (lse & ~dd->ipath_link_speed_supported))
goto err;
set_link_speed_enabled(dd, lse);
}
/* Set link down default state. */
switch (pip->portphysstate_linkdown & 0xF) {
case 0: /* NOP */
break;
case 1: /* SLEEP */
if (set_linkdowndefaultstate(dd, 1))
goto err;
break;
case 2: /* POLL */
if (set_linkdowndefaultstate(dd, 0))
goto err;
break;
default:
goto err;
}
dev->mkeyprot = pip->mkeyprot_resv_lmc >> 6;
dev->vl_high_limit = pip->vl_high_limit;
switch ((pip->neighbormtu_mastersmsl >> 4) & 0xF) {
case IB_MTU_256:
mtu = 256;
break;
case IB_MTU_512:
mtu = 512;
break;
case IB_MTU_1024:
mtu = 1024;
break;
case IB_MTU_2048:
mtu = 2048;
break;
case IB_MTU_4096:
if (!ipath_mtu4096)
goto err;
mtu = 4096;
break;
default:
/* XXX We have already partially updated our state! */
goto err;
}
ipath_set_mtu(dd, mtu);
dev->sm_sl = pip->neighbormtu_mastersmsl & 0xF;
/* We only support VL0 */
if (((pip->operationalvl_pei_peo_fpi_fpo >> 4) & 0xF) > 1)
goto err;
if (pip->mkey_violations == 0)
dev->mkey_violations = 0;
/*
* Hardware counter can't be reset so snapshot and subtract
* later.
*/
if (pip->pkey_violations == 0)
dev->z_pkey_violations = ipath_get_cr_errpkey(dd);
if (pip->qkey_violations == 0)
dev->qkey_violations = 0;
ore = pip->localphyerrors_overrunerrors;
if (set_phyerrthreshold(dd, (ore >> 4) & 0xF))
goto err;
if (set_overrunthreshold(dd, (ore & 0xF)))
goto err;
dev->subnet_timeout = pip->clientrereg_resv_subnetto & 0x1F;
if (pip->clientrereg_resv_subnetto & 0x80) {
clientrereg = 1;
event.event = IB_EVENT_CLIENT_REREGISTER;
ib_dispatch_event(&event);
}
/*
* Do the port state change now that the other link parameters
* have been set.
* Changing the port physical state only makes sense if the link
* is down or is being set to down.
*/
state = pip->linkspeed_portstate & 0xF;
lstate = (pip->portphysstate_linkdown >> 4) & 0xF;
if (lstate && !(state == IB_PORT_DOWN || state == IB_PORT_NOP))
goto err;
/*
* Only state changes of DOWN, ARM, and ACTIVE are valid
* and must be in the correct state to take effect (see 7.2.6).
*/
switch (state) {
case IB_PORT_NOP:
if (lstate == 0)
break;
/* FALLTHROUGH */
case IB_PORT_DOWN:
if (lstate == 0)
lstate = IPATH_IB_LINKDOWN_ONLY;
else if (lstate == 1)
lstate = IPATH_IB_LINKDOWN_SLEEP;
else if (lstate == 2)
lstate = IPATH_IB_LINKDOWN;
else if (lstate == 3)
lstate = IPATH_IB_LINKDOWN_DISABLE;
else
goto err;
ipath_set_linkstate(dd, lstate);
if (lstate == IPATH_IB_LINKDOWN_DISABLE) {
ret = IB_MAD_RESULT_SUCCESS | IB_MAD_RESULT_CONSUMED;
goto done;
}
ipath_wait_linkstate(dd, IPATH_LINKINIT | IPATH_LINKARMED |
IPATH_LINKACTIVE, 1000);
break;
case IB_PORT_ARMED:
ipath_set_linkstate(dd, IPATH_IB_LINKARM);
break;
case IB_PORT_ACTIVE:
ipath_set_linkstate(dd, IPATH_IB_LINKACTIVE);
break;
default:
/* XXX We have already partially updated our state! */
goto err;
}
ret = recv_subn_get_portinfo(smp, ibdev, port);
if (clientrereg)
pip->clientrereg_resv_subnetto |= 0x80;
goto done;
err:
smp->status |= IB_SMP_INVALID_FIELD;
ret = recv_subn_get_portinfo(smp, ibdev, port);
done:
return ret;
}
/**
* rm_pkey - decrecment the reference count for the given PKEY
* @dd: the infinipath device
* @key: the PKEY index
*
* Return true if this was the last reference and the hardware table entry
* needs to be changed.
*/
static int rm_pkey(struct ipath_devdata *dd, u16 key)
{
int i;
int ret;
for (i = 0; i < ARRAY_SIZE(dd->ipath_pkeys); i++) {
if (dd->ipath_pkeys[i] != key)
continue;
if (atomic_dec_and_test(&dd->ipath_pkeyrefs[i])) {
dd->ipath_pkeys[i] = 0;
ret = 1;
goto bail;
}
break;
}
ret = 0;
bail:
return ret;
}
/**
* add_pkey - add the given PKEY to the hardware table
* @dd: the infinipath device
* @key: the PKEY
*
* Return an error code if unable to add the entry, zero if no change,
* or 1 if the hardware PKEY register needs to be updated.
*/
static int add_pkey(struct ipath_devdata *dd, u16 key)
{
int i;
u16 lkey = key & 0x7FFF;
int any = 0;
int ret;
if (lkey == 0x7FFF) {
ret = 0;
goto bail;
}
/* Look for an empty slot or a matching PKEY. */
for (i = 0; i < ARRAY_SIZE(dd->ipath_pkeys); i++) {
if (!dd->ipath_pkeys[i]) {
any++;
continue;
}
/* If it matches exactly, try to increment the ref count */
if (dd->ipath_pkeys[i] == key) {
if (atomic_inc_return(&dd->ipath_pkeyrefs[i]) > 1) {
ret = 0;
goto bail;
}
/* Lost the race. Look for an empty slot below. */
atomic_dec(&dd->ipath_pkeyrefs[i]);
any++;
}
/*
* It makes no sense to have both the limited and unlimited
* PKEY set at the same time since the unlimited one will
* disable the limited one.
*/
if ((dd->ipath_pkeys[i] & 0x7FFF) == lkey) {
ret = -EEXIST;
goto bail;
}
}
if (!any) {
ret = -EBUSY;
goto bail;
}
for (i = 0; i < ARRAY_SIZE(dd->ipath_pkeys); i++) {
if (!dd->ipath_pkeys[i] &&
atomic_inc_return(&dd->ipath_pkeyrefs[i]) == 1) {
/* for ipathstats, etc. */
ipath_stats.sps_pkeys[i] = lkey;
dd->ipath_pkeys[i] = key;
ret = 1;
goto bail;
}
}
ret = -EBUSY;
bail:
return ret;
}
/**
* set_pkeys - set the PKEY table for port 0
* @dd: the infinipath device
* @pkeys: the PKEY table
*/
static int set_pkeys(struct ipath_devdata *dd, u16 *pkeys)
{
struct ipath_portdata *pd;
int i;
int changed = 0;
/* always a kernel port, no locking needed */
pd = dd->ipath_pd[0];
for (i = 0; i < ARRAY_SIZE(pd->port_pkeys); i++) {
u16 key = pkeys[i];
u16 okey = pd->port_pkeys[i];
if (key == okey)
continue;
/*
* The value of this PKEY table entry is changing.
* Remove the old entry in the hardware's array of PKEYs.
*/
if (okey & 0x7FFF)
changed |= rm_pkey(dd, okey);
if (key & 0x7FFF) {
int ret = add_pkey(dd, key);
if (ret < 0)
key = 0;
else
changed |= ret;
}
pd->port_pkeys[i] = key;
}
if (changed) {
u64 pkey;
pkey = (u64) dd->ipath_pkeys[0] |
((u64) dd->ipath_pkeys[1] << 16) |
((u64) dd->ipath_pkeys[2] << 32) |
((u64) dd->ipath_pkeys[3] << 48);
ipath_cdbg(VERBOSE, "p0 new pkey reg %llx\n",
(unsigned long long) pkey);
ipath_write_kreg(dd, dd->ipath_kregs->kr_partitionkey,
pkey);
}
return 0;
}
static int recv_subn_set_pkeytable(struct ib_smp *smp,
struct ib_device *ibdev)
{
u32 startpx = 32 * (be32_to_cpu(smp->attr_mod) & 0xffff);
__be16 *p = (__be16 *) smp->data;
u16 *q = (u16 *) smp->data;
struct ipath_ibdev *dev = to_idev(ibdev);
unsigned i, n = ipath_get_npkeys(dev->dd);
for (i = 0; i < n; i++)
q[i] = be16_to_cpu(p[i]);
if (startpx != 0 || set_pkeys(dev->dd, q) != 0)
smp->status |= IB_SMP_INVALID_FIELD;
return recv_subn_get_pkeytable(smp, ibdev);
}
static int recv_pma_get_classportinfo(struct ib_pma_mad *pmp)
{
struct ib_class_port_info *p =
(struct ib_class_port_info *)pmp->data;
memset(pmp->data, 0, sizeof(pmp->data));
if (pmp->mad_hdr.attr_mod != 0)
pmp->mad_hdr.status |= IB_SMP_INVALID_FIELD;
/* Indicate AllPortSelect is valid (only one port anyway) */
p->capability_mask = cpu_to_be16(1 << 8);
p->base_version = 1;
p->class_version = 1;
/*
* Expected response time is 4.096 usec. * 2^18 == 1.073741824
* sec.
*/
p->resp_time_value = 18;
return reply((struct ib_smp *) pmp);
}
/*
* The PortSamplesControl.CounterMasks field is an array of 3 bit fields
* which specify the N'th counter's capabilities. See ch. 16.1.3.2.
* We support 5 counters which only count the mandatory quantities.
*/
#define COUNTER_MASK(q, n) (q << ((9 - n) * 3))
#define COUNTER_MASK0_9 cpu_to_be32(COUNTER_MASK(1, 0) | \
COUNTER_MASK(1, 1) | \
COUNTER_MASK(1, 2) | \
COUNTER_MASK(1, 3) | \
COUNTER_MASK(1, 4))
static int recv_pma_get_portsamplescontrol(struct ib_pma_mad *pmp,
struct ib_device *ibdev, u8 port)
{
struct ib_pma_portsamplescontrol *p =
(struct ib_pma_portsamplescontrol *)pmp->data;
struct ipath_ibdev *dev = to_idev(ibdev);
struct ipath_cregs const *crp = dev->dd->ipath_cregs;
unsigned long flags;
u8 port_select = p->port_select;
memset(pmp->data, 0, sizeof(pmp->data));
p->port_select = port_select;
if (pmp->mad_hdr.attr_mod != 0 ||
(port_select != port && port_select != 0xFF))
pmp->mad_hdr.status |= IB_SMP_INVALID_FIELD;
/*
* Ticks are 10x the link transfer period which for 2.5Gbs is 4
* nsec. 0 == 4 nsec., 1 == 8 nsec., ..., 255 == 1020 nsec. Sample
* intervals are counted in ticks. Since we use Linux timers, that
* count in jiffies, we can't sample for less than 1000 ticks if HZ
* == 1000 (4000 ticks if HZ is 250). link_speed_active returns 2 for
* DDR, 1 for SDR, set the tick to 1 for DDR, 0 for SDR on chips that
* have hardware support for delaying packets.
*/
if (crp->cr_psstat)
p->tick = dev->dd->ipath_link_speed_active - 1;
else
p->tick = 250; /* 1 usec. */
p->counter_width = 4; /* 32 bit counters */
p->counter_mask0_9 = COUNTER_MASK0_9;
spin_lock_irqsave(&dev->pending_lock, flags);
if (crp->cr_psstat)
p->sample_status = ipath_read_creg32(dev->dd, crp->cr_psstat);
else
p->sample_status = dev->pma_sample_status;
p->sample_start = cpu_to_be32(dev->pma_sample_start);
p->sample_interval = cpu_to_be32(dev->pma_sample_interval);
p->tag = cpu_to_be16(dev->pma_tag);
p->counter_select[0] = dev->pma_counter_select[0];
p->counter_select[1] = dev->pma_counter_select[1];
p->counter_select[2] = dev->pma_counter_select[2];
p->counter_select[3] = dev->pma_counter_select[3];
p->counter_select[4] = dev->pma_counter_select[4];
spin_unlock_irqrestore(&dev->pending_lock, flags);
return reply((struct ib_smp *) pmp);
}
static int recv_pma_set_portsamplescontrol(struct ib_pma_mad *pmp,
struct ib_device *ibdev, u8 port)
{
struct ib_pma_portsamplescontrol *p =
(struct ib_pma_portsamplescontrol *)pmp->data;
struct ipath_ibdev *dev = to_idev(ibdev);
struct ipath_cregs const *crp = dev->dd->ipath_cregs;
unsigned long flags;
u8 status;
int ret;
if (pmp->mad_hdr.attr_mod != 0 ||
(p->port_select != port && p->port_select != 0xFF)) {
pmp->mad_hdr.status |= IB_SMP_INVALID_FIELD;
ret = reply((struct ib_smp *) pmp);
goto bail;
}
spin_lock_irqsave(&dev->pending_lock, flags);
if (crp->cr_psstat)
status = ipath_read_creg32(dev->dd, crp->cr_psstat);
else
status = dev->pma_sample_status;
if (status == IB_PMA_SAMPLE_STATUS_DONE) {
dev->pma_sample_start = be32_to_cpu(p->sample_start);
dev->pma_sample_interval = be32_to_cpu(p->sample_interval);
dev->pma_tag = be16_to_cpu(p->tag);
dev->pma_counter_select[0] = p->counter_select[0];
dev->pma_counter_select[1] = p->counter_select[1];
dev->pma_counter_select[2] = p->counter_select[2];
dev->pma_counter_select[3] = p->counter_select[3];
dev->pma_counter_select[4] = p->counter_select[4];
if (crp->cr_psstat) {
ipath_write_creg(dev->dd, crp->cr_psinterval,
dev->pma_sample_interval);
ipath_write_creg(dev->dd, crp->cr_psstart,
dev->pma_sample_start);
} else
dev->pma_sample_status = IB_PMA_SAMPLE_STATUS_STARTED;
}
spin_unlock_irqrestore(&dev->pending_lock, flags);
ret = recv_pma_get_portsamplescontrol(pmp, ibdev, port);
bail:
return ret;
}
static u64 get_counter(struct ipath_ibdev *dev,
struct ipath_cregs const *crp,
__be16 sel)
{
u64 ret;
switch (sel) {
case IB_PMA_PORT_XMIT_DATA:
ret = (crp->cr_psxmitdatacount) ?
ipath_read_creg32(dev->dd, crp->cr_psxmitdatacount) :
dev->ipath_sword;
break;
case IB_PMA_PORT_RCV_DATA:
ret = (crp->cr_psrcvdatacount) ?
ipath_read_creg32(dev->dd, crp->cr_psrcvdatacount) :
dev->ipath_rword;
break;
case IB_PMA_PORT_XMIT_PKTS:
ret = (crp->cr_psxmitpktscount) ?
ipath_read_creg32(dev->dd, crp->cr_psxmitpktscount) :
dev->ipath_spkts;
break;
case IB_PMA_PORT_RCV_PKTS:
ret = (crp->cr_psrcvpktscount) ?
ipath_read_creg32(dev->dd, crp->cr_psrcvpktscount) :
dev->ipath_rpkts;
break;
case IB_PMA_PORT_XMIT_WAIT:
ret = (crp->cr_psxmitwaitcount) ?
ipath_read_creg32(dev->dd, crp->cr_psxmitwaitcount) :
dev->ipath_xmit_wait;
break;
default:
ret = 0;
}
return ret;
}
static int recv_pma_get_portsamplesresult(struct ib_pma_mad *pmp,
struct ib_device *ibdev)
{
struct ib_pma_portsamplesresult *p =
(struct ib_pma_portsamplesresult *)pmp->data;
struct ipath_ibdev *dev = to_idev(ibdev);
struct ipath_cregs const *crp = dev->dd->ipath_cregs;
u8 status;
int i;
memset(pmp->data, 0, sizeof(pmp->data));
p->tag = cpu_to_be16(dev->pma_tag);
if (crp->cr_psstat)
status = ipath_read_creg32(dev->dd, crp->cr_psstat);
else
status = dev->pma_sample_status;
p->sample_status = cpu_to_be16(status);
for (i = 0; i < ARRAY_SIZE(dev->pma_counter_select); i++)
p->counter[i] = (status != IB_PMA_SAMPLE_STATUS_DONE) ? 0 :
cpu_to_be32(
get_counter(dev, crp, dev->pma_counter_select[i]));
return reply((struct ib_smp *) pmp);
}
static int recv_pma_get_portsamplesresult_ext(struct ib_pma_mad *pmp,
struct ib_device *ibdev)
{
struct ib_pma_portsamplesresult_ext *p =
(struct ib_pma_portsamplesresult_ext *)pmp->data;
struct ipath_ibdev *dev = to_idev(ibdev);
struct ipath_cregs const *crp = dev->dd->ipath_cregs;
u8 status;
int i;
memset(pmp->data, 0, sizeof(pmp->data));
p->tag = cpu_to_be16(dev->pma_tag);
if (crp->cr_psstat)
status = ipath_read_creg32(dev->dd, crp->cr_psstat);
else
status = dev->pma_sample_status;
p->sample_status = cpu_to_be16(status);
/* 64 bits */
p->extended_width = cpu_to_be32(0x80000000);
for (i = 0; i < ARRAY_SIZE(dev->pma_counter_select); i++)
p->counter[i] = (status != IB_PMA_SAMPLE_STATUS_DONE) ? 0 :
cpu_to_be64(
get_counter(dev, crp, dev->pma_counter_select[i]));
return reply((struct ib_smp *) pmp);
}
static int recv_pma_get_portcounters(struct ib_pma_mad *pmp,
struct ib_device *ibdev, u8 port)
{
struct ib_pma_portcounters *p = (struct ib_pma_portcounters *)
pmp->data;
struct ipath_ibdev *dev = to_idev(ibdev);
struct ipath_verbs_counters cntrs;
u8 port_select = p->port_select;
ipath_get_counters(dev->dd, &cntrs);
/* Adjust counters for any resets done. */
cntrs.symbol_error_counter -= dev->z_symbol_error_counter;
cntrs.link_error_recovery_counter -=
dev->z_link_error_recovery_counter;
cntrs.link_downed_counter -= dev->z_link_downed_counter;
cntrs.port_rcv_errors += dev->rcv_errors;
cntrs.port_rcv_errors -= dev->z_port_rcv_errors;
cntrs.port_rcv_remphys_errors -= dev->z_port_rcv_remphys_errors;
cntrs.port_xmit_discards -= dev->z_port_xmit_discards;
cntrs.port_xmit_data -= dev->z_port_xmit_data;
cntrs.port_rcv_data -= dev->z_port_rcv_data;
cntrs.port_xmit_packets -= dev->z_port_xmit_packets;
cntrs.port_rcv_packets -= dev->z_port_rcv_packets;
cntrs.local_link_integrity_errors -=
dev->z_local_link_integrity_errors;
cntrs.excessive_buffer_overrun_errors -=
dev->z_excessive_buffer_overrun_errors;
cntrs.vl15_dropped -= dev->z_vl15_dropped;
cntrs.vl15_dropped += dev->n_vl15_dropped;
memset(pmp->data, 0, sizeof(pmp->data));
p->port_select = port_select;
if (pmp->mad_hdr.attr_mod != 0 ||
(port_select != port && port_select != 0xFF))
pmp->mad_hdr.status |= IB_SMP_INVALID_FIELD;
if (cntrs.symbol_error_counter > 0xFFFFUL)
p->symbol_error_counter = cpu_to_be16(0xFFFF);
else
p->symbol_error_counter =
cpu_to_be16((u16)cntrs.symbol_error_counter);
if (cntrs.link_error_recovery_counter > 0xFFUL)
p->link_error_recovery_counter = 0xFF;
else
p->link_error_recovery_counter =
(u8)cntrs.link_error_recovery_counter;
if (cntrs.link_downed_counter > 0xFFUL)
p->link_downed_counter = 0xFF;
else
p->link_downed_counter = (u8)cntrs.link_downed_counter;
if (cntrs.port_rcv_errors > 0xFFFFUL)
p->port_rcv_errors = cpu_to_be16(0xFFFF);
else
p->port_rcv_errors =
cpu_to_be16((u16) cntrs.port_rcv_errors);
if (cntrs.port_rcv_remphys_errors > 0xFFFFUL)
p->port_rcv_remphys_errors = cpu_to_be16(0xFFFF);
else
p->port_rcv_remphys_errors =
cpu_to_be16((u16)cntrs.port_rcv_remphys_errors);
if (cntrs.port_xmit_discards > 0xFFFFUL)
p->port_xmit_discards = cpu_to_be16(0xFFFF);
else
p->port_xmit_discards =
cpu_to_be16((u16)cntrs.port_xmit_discards);
if (cntrs.local_link_integrity_errors > 0xFUL)
cntrs.local_link_integrity_errors = 0xFUL;
if (cntrs.excessive_buffer_overrun_errors > 0xFUL)
cntrs.excessive_buffer_overrun_errors = 0xFUL;
p->link_overrun_errors = (cntrs.local_link_integrity_errors << 4) |
cntrs.excessive_buffer_overrun_errors;
if (cntrs.vl15_dropped > 0xFFFFUL)
p->vl15_dropped = cpu_to_be16(0xFFFF);
else
p->vl15_dropped = cpu_to_be16((u16)cntrs.vl15_dropped);
if (cntrs.port_xmit_data > 0xFFFFFFFFUL)
p->port_xmit_data = cpu_to_be32(0xFFFFFFFF);
else
p->port_xmit_data = cpu_to_be32((u32)cntrs.port_xmit_data);
if (cntrs.port_rcv_data > 0xFFFFFFFFUL)
p->port_rcv_data = cpu_to_be32(0xFFFFFFFF);
else
p->port_rcv_data = cpu_to_be32((u32)cntrs.port_rcv_data);
if (cntrs.port_xmit_packets > 0xFFFFFFFFUL)
p->port_xmit_packets = cpu_to_be32(0xFFFFFFFF);
else
p->port_xmit_packets =
cpu_to_be32((u32)cntrs.port_xmit_packets);
if (cntrs.port_rcv_packets > 0xFFFFFFFFUL)
p->port_rcv_packets = cpu_to_be32(0xFFFFFFFF);
else
p->port_rcv_packets =
cpu_to_be32((u32) cntrs.port_rcv_packets);
return reply((struct ib_smp *) pmp);
}
static int recv_pma_get_portcounters_ext(struct ib_pma_mad *pmp,
struct ib_device *ibdev, u8 port)
{
struct ib_pma_portcounters_ext *p =
(struct ib_pma_portcounters_ext *)pmp->data;
struct ipath_ibdev *dev = to_idev(ibdev);
u64 swords, rwords, spkts, rpkts, xwait;
u8 port_select = p->port_select;
ipath_snapshot_counters(dev->dd, &swords, &rwords, &spkts,
&rpkts, &xwait);
/* Adjust counters for any resets done. */
swords -= dev->z_port_xmit_data;
rwords -= dev->z_port_rcv_data;
spkts -= dev->z_port_xmit_packets;
rpkts -= dev->z_port_rcv_packets;
memset(pmp->data, 0, sizeof(pmp->data));
p->port_select = port_select;
if (pmp->mad_hdr.attr_mod != 0 ||
(port_select != port && port_select != 0xFF))
pmp->mad_hdr.status |= IB_SMP_INVALID_FIELD;
p->port_xmit_data = cpu_to_be64(swords);
p->port_rcv_data = cpu_to_be64(rwords);
p->port_xmit_packets = cpu_to_be64(spkts);
p->port_rcv_packets = cpu_to_be64(rpkts);
p->port_unicast_xmit_packets = cpu_to_be64(dev->n_unicast_xmit);
p->port_unicast_rcv_packets = cpu_to_be64(dev->n_unicast_rcv);
p->port_multicast_xmit_packets = cpu_to_be64(dev->n_multicast_xmit);
p->port_multicast_rcv_packets = cpu_to_be64(dev->n_multicast_rcv);
return reply((struct ib_smp *) pmp);
}
static int recv_pma_set_portcounters(struct ib_pma_mad *pmp,
struct ib_device *ibdev, u8 port)
{
struct ib_pma_portcounters *p = (struct ib_pma_portcounters *)
pmp->data;
struct ipath_ibdev *dev = to_idev(ibdev);
struct ipath_verbs_counters cntrs;
/*
* Since the HW doesn't support clearing counters, we save the
* current count and subtract it from future responses.
*/
ipath_get_counters(dev->dd, &cntrs);
if (p->counter_select & IB_PMA_SEL_SYMBOL_ERROR)
dev->z_symbol_error_counter = cntrs.symbol_error_counter;
if (p->counter_select & IB_PMA_SEL_LINK_ERROR_RECOVERY)
dev->z_link_error_recovery_counter =
cntrs.link_error_recovery_counter;
if (p->counter_select & IB_PMA_SEL_LINK_DOWNED)
dev->z_link_downed_counter = cntrs.link_downed_counter;
if (p->counter_select & IB_PMA_SEL_PORT_RCV_ERRORS)
dev->z_port_rcv_errors =
cntrs.port_rcv_errors + dev->rcv_errors;
if (p->counter_select & IB_PMA_SEL_PORT_RCV_REMPHYS_ERRORS)
dev->z_port_rcv_remphys_errors =
cntrs.port_rcv_remphys_errors;
if (p->counter_select & IB_PMA_SEL_PORT_XMIT_DISCARDS)
dev->z_port_xmit_discards = cntrs.port_xmit_discards;
if (p->counter_select & IB_PMA_SEL_LOCAL_LINK_INTEGRITY_ERRORS)
dev->z_local_link_integrity_errors =
cntrs.local_link_integrity_errors;
if (p->counter_select & IB_PMA_SEL_EXCESSIVE_BUFFER_OVERRUNS)
dev->z_excessive_buffer_overrun_errors =
cntrs.excessive_buffer_overrun_errors;
if (p->counter_select & IB_PMA_SEL_PORT_VL15_DROPPED) {
dev->n_vl15_dropped = 0;
dev->z_vl15_dropped = cntrs.vl15_dropped;
}
if (p->counter_select & IB_PMA_SEL_PORT_XMIT_DATA)
dev->z_port_xmit_data = cntrs.port_xmit_data;
if (p->counter_select & IB_PMA_SEL_PORT_RCV_DATA)
dev->z_port_rcv_data = cntrs.port_rcv_data;
if (p->counter_select & IB_PMA_SEL_PORT_XMIT_PACKETS)
dev->z_port_xmit_packets = cntrs.port_xmit_packets;
if (p->counter_select & IB_PMA_SEL_PORT_RCV_PACKETS)
dev->z_port_rcv_packets = cntrs.port_rcv_packets;
return recv_pma_get_portcounters(pmp, ibdev, port);
}
static int recv_pma_set_portcounters_ext(struct ib_pma_mad *pmp,
struct ib_device *ibdev, u8 port)
{
struct ib_pma_portcounters *p = (struct ib_pma_portcounters *)
pmp->data;
struct ipath_ibdev *dev = to_idev(ibdev);
u64 swords, rwords, spkts, rpkts, xwait;
ipath_snapshot_counters(dev->dd, &swords, &rwords, &spkts,
&rpkts, &xwait);
if (p->counter_select & IB_PMA_SELX_PORT_XMIT_DATA)
dev->z_port_xmit_data = swords;
if (p->counter_select & IB_PMA_SELX_PORT_RCV_DATA)
dev->z_port_rcv_data = rwords;
if (p->counter_select & IB_PMA_SELX_PORT_XMIT_PACKETS)
dev->z_port_xmit_packets = spkts;
if (p->counter_select & IB_PMA_SELX_PORT_RCV_PACKETS)
dev->z_port_rcv_packets = rpkts;
if (p->counter_select & IB_PMA_SELX_PORT_UNI_XMIT_PACKETS)
dev->n_unicast_xmit = 0;
if (p->counter_select & IB_PMA_SELX_PORT_UNI_RCV_PACKETS)
dev->n_unicast_rcv = 0;
if (p->counter_select & IB_PMA_SELX_PORT_MULTI_XMIT_PACKETS)
dev->n_multicast_xmit = 0;
if (p->counter_select & IB_PMA_SELX_PORT_MULTI_RCV_PACKETS)
dev->n_multicast_rcv = 0;
return recv_pma_get_portcounters_ext(pmp, ibdev, port);
}
static int process_subn(struct ib_device *ibdev, int mad_flags,
u8 port_num, struct ib_mad *in_mad,
struct ib_mad *out_mad)
{
struct ib_smp *smp = (struct ib_smp *)out_mad;
struct ipath_ibdev *dev = to_idev(ibdev);
int ret;
*out_mad = *in_mad;
if (smp->class_version != 1) {
smp->status |= IB_SMP_UNSUP_VERSION;
ret = reply(smp);
goto bail;
}
/* Is the mkey in the process of expiring? */
if (dev->mkey_lease_timeout &&
time_after_eq(jiffies, dev->mkey_lease_timeout)) {
/* Clear timeout and mkey protection field. */
dev->mkey_lease_timeout = 0;
dev->mkeyprot = 0;
}
/*
* M_Key checking depends on
* Portinfo:M_Key_protect_bits
*/
if ((mad_flags & IB_MAD_IGNORE_MKEY) == 0 && dev->mkey != 0 &&
dev->mkey != smp->mkey &&
(smp->method == IB_MGMT_METHOD_SET ||
(smp->method == IB_MGMT_METHOD_GET &&
dev->mkeyprot >= 2))) {
if (dev->mkey_violations != 0xFFFF)
++dev->mkey_violations;
if (dev->mkey_lease_timeout ||
dev->mkey_lease_period == 0) {
ret = IB_MAD_RESULT_SUCCESS |
IB_MAD_RESULT_CONSUMED;
goto bail;
}
dev->mkey_lease_timeout = jiffies +
dev->mkey_lease_period * HZ;
/* Future: Generate a trap notice. */
ret = IB_MAD_RESULT_SUCCESS | IB_MAD_RESULT_CONSUMED;
goto bail;
} else if (dev->mkey_lease_timeout)
dev->mkey_lease_timeout = 0;
switch (smp->method) {
case IB_MGMT_METHOD_GET:
switch (smp->attr_id) {
case IB_SMP_ATTR_NODE_DESC:
ret = recv_subn_get_nodedescription(smp, ibdev);
goto bail;
case IB_SMP_ATTR_NODE_INFO:
ret = recv_subn_get_nodeinfo(smp, ibdev, port_num);
goto bail;
case IB_SMP_ATTR_GUID_INFO:
ret = recv_subn_get_guidinfo(smp, ibdev);
goto bail;
case IB_SMP_ATTR_PORT_INFO:
ret = recv_subn_get_portinfo(smp, ibdev, port_num);
goto bail;
case IB_SMP_ATTR_PKEY_TABLE:
ret = recv_subn_get_pkeytable(smp, ibdev);
goto bail;
case IB_SMP_ATTR_SM_INFO:
if (dev->port_cap_flags & IB_PORT_SM_DISABLED) {
ret = IB_MAD_RESULT_SUCCESS |
IB_MAD_RESULT_CONSUMED;
goto bail;
}
if (dev->port_cap_flags & IB_PORT_SM) {
ret = IB_MAD_RESULT_SUCCESS;
goto bail;
}
/* FALLTHROUGH */
default:
smp->status |= IB_SMP_UNSUP_METH_ATTR;
ret = reply(smp);
goto bail;
}
case IB_MGMT_METHOD_SET:
switch (smp->attr_id) {
case IB_SMP_ATTR_GUID_INFO:
ret = recv_subn_set_guidinfo(smp, ibdev);
goto bail;
case IB_SMP_ATTR_PORT_INFO:
ret = recv_subn_set_portinfo(smp, ibdev, port_num);
goto bail;
case IB_SMP_ATTR_PKEY_TABLE:
ret = recv_subn_set_pkeytable(smp, ibdev);
goto bail;
case IB_SMP_ATTR_SM_INFO:
if (dev->port_cap_flags & IB_PORT_SM_DISABLED) {
ret = IB_MAD_RESULT_SUCCESS |
IB_MAD_RESULT_CONSUMED;
goto bail;
}
if (dev->port_cap_flags & IB_PORT_SM) {
ret = IB_MAD_RESULT_SUCCESS;
goto bail;
}
/* FALLTHROUGH */
default:
smp->status |= IB_SMP_UNSUP_METH_ATTR;
ret = reply(smp);
goto bail;
}
case IB_MGMT_METHOD_TRAP:
case IB_MGMT_METHOD_REPORT:
case IB_MGMT_METHOD_REPORT_RESP:
case IB_MGMT_METHOD_TRAP_REPRESS:
case IB_MGMT_METHOD_GET_RESP:
/*
* The ib_mad module will call us to process responses
* before checking for other consumers.
* Just tell the caller to process it normally.
*/
ret = IB_MAD_RESULT_SUCCESS;
goto bail;
default:
smp->status |= IB_SMP_UNSUP_METHOD;
ret = reply(smp);
}
bail:
return ret;
}
static int process_perf(struct ib_device *ibdev, u8 port_num,
struct ib_mad *in_mad,
struct ib_mad *out_mad)
{
struct ib_pma_mad *pmp = (struct ib_pma_mad *)out_mad;
int ret;
*out_mad = *in_mad;
if (pmp->mad_hdr.class_version != 1) {
pmp->mad_hdr.status |= IB_SMP_UNSUP_VERSION;
ret = reply((struct ib_smp *) pmp);
goto bail;
}
switch (pmp->mad_hdr.method) {
case IB_MGMT_METHOD_GET:
switch (pmp->mad_hdr.attr_id) {
case IB_PMA_CLASS_PORT_INFO:
ret = recv_pma_get_classportinfo(pmp);
goto bail;
case IB_PMA_PORT_SAMPLES_CONTROL:
ret = recv_pma_get_portsamplescontrol(pmp, ibdev,
port_num);
goto bail;
case IB_PMA_PORT_SAMPLES_RESULT:
ret = recv_pma_get_portsamplesresult(pmp, ibdev);
goto bail;
case IB_PMA_PORT_SAMPLES_RESULT_EXT:
ret = recv_pma_get_portsamplesresult_ext(pmp,
ibdev);
goto bail;
case IB_PMA_PORT_COUNTERS:
ret = recv_pma_get_portcounters(pmp, ibdev,
port_num);
goto bail;
case IB_PMA_PORT_COUNTERS_EXT:
ret = recv_pma_get_portcounters_ext(pmp, ibdev,
port_num);
goto bail;
default:
pmp->mad_hdr.status |= IB_SMP_UNSUP_METH_ATTR;
ret = reply((struct ib_smp *) pmp);
goto bail;
}
case IB_MGMT_METHOD_SET:
switch (pmp->mad_hdr.attr_id) {
case IB_PMA_PORT_SAMPLES_CONTROL:
ret = recv_pma_set_portsamplescontrol(pmp, ibdev,
port_num);
goto bail;
case IB_PMA_PORT_COUNTERS:
ret = recv_pma_set_portcounters(pmp, ibdev,
port_num);
goto bail;
case IB_PMA_PORT_COUNTERS_EXT:
ret = recv_pma_set_portcounters_ext(pmp, ibdev,
port_num);
goto bail;
default:
pmp->mad_hdr.status |= IB_SMP_UNSUP_METH_ATTR;
ret = reply((struct ib_smp *) pmp);
goto bail;
}
case IB_MGMT_METHOD_GET_RESP:
/*
* The ib_mad module will call us to process responses
* before checking for other consumers.
* Just tell the caller to process it normally.
*/
ret = IB_MAD_RESULT_SUCCESS;
goto bail;
default:
pmp->mad_hdr.status |= IB_SMP_UNSUP_METHOD;
ret = reply((struct ib_smp *) pmp);
}
bail:
return ret;
}
/**
* ipath_process_mad - process an incoming MAD packet
* @ibdev: the infiniband device this packet came in on
* @mad_flags: MAD flags
* @port_num: the port number this packet came in on
* @in_wc: the work completion entry for this packet
* @in_grh: the global route header for this packet
* @in_mad: the incoming MAD
* @out_mad: any outgoing MAD reply
*
* Returns IB_MAD_RESULT_SUCCESS if this is a MAD that we are not
* interested in processing.
*
* Note that the verbs framework has already done the MAD sanity checks,
* and hop count/pointer updating for IB_MGMT_CLASS_SUBN_DIRECTED_ROUTE
* MADs.
*
* This is called by the ib_mad module.
*/
int ipath_process_mad(struct ib_device *ibdev, int mad_flags, u8 port_num,
struct ib_wc *in_wc, struct ib_grh *in_grh,
struct ib_mad *in_mad, struct ib_mad *out_mad)
{
int ret;
switch (in_mad->mad_hdr.mgmt_class) {
case IB_MGMT_CLASS_SUBN_DIRECTED_ROUTE:
case IB_MGMT_CLASS_SUBN_LID_ROUTED:
ret = process_subn(ibdev, mad_flags, port_num,
in_mad, out_mad);
goto bail;
case IB_MGMT_CLASS_PERF_MGMT:
ret = process_perf(ibdev, port_num, in_mad, out_mad);
goto bail;
default:
ret = IB_MAD_RESULT_SUCCESS;
}
bail:
return ret;
}
| gpl-2.0 |
zjh3123629/qt210-linux | arch/mn10300/unit-asb2305/pci-irq.c | 8771 | 1300 | /* PCI IRQ routing on the MN103E010 based ASB2305
*
* Copyright (C) 2007 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public Licence
* as published by the Free Software Foundation; either version
* 2 of the Licence, or (at your option) any later version.
*
* This is simple: All PCI interrupts route through the CPU's XIRQ1 pin [IRQ 35]
*/
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <asm/io.h>
#include <asm/smp.h>
#include "pci-asb2305.h"
void __init pcibios_irq_init(void)
{
}
void __init pcibios_fixup_irqs(void)
{
struct pci_dev *dev = NULL;
u8 line, pin;
while ((dev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, dev)) != NULL) {
pci_read_config_byte(dev, PCI_INTERRUPT_PIN, &pin);
if (pin) {
dev->irq = XIRQ1;
pci_write_config_byte(dev, PCI_INTERRUPT_LINE,
dev->irq);
}
pci_read_config_byte(dev, PCI_INTERRUPT_LINE, &line);
}
}
void __init pcibios_penalize_isa_irq(int irq)
{
}
void pcibios_enable_irq(struct pci_dev *dev)
{
pci_write_config_byte(dev, PCI_INTERRUPT_LINE, dev->irq);
}
| gpl-2.0 |
CyanogenMod-E1/android_kernel_sony_msm8610 | arch/mips/kernel/spinlock_test.c | 8771 | 2381 | #include <linux/init.h>
#include <linux/kthread.h>
#include <linux/hrtimer.h>
#include <linux/fs.h>
#include <linux/debugfs.h>
#include <linux/export.h>
#include <linux/spinlock.h>
static int ss_get(void *data, u64 *val)
{
ktime_t start, finish;
int loops;
int cont;
DEFINE_RAW_SPINLOCK(ss_spin);
loops = 1000000;
cont = 1;
start = ktime_get();
while (cont) {
raw_spin_lock(&ss_spin);
loops--;
if (loops == 0)
cont = 0;
raw_spin_unlock(&ss_spin);
}
finish = ktime_get();
*val = ktime_us_delta(finish, start);
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(fops_ss, ss_get, NULL, "%llu\n");
struct spin_multi_state {
raw_spinlock_t lock;
atomic_t start_wait;
atomic_t enter_wait;
atomic_t exit_wait;
int loops;
};
struct spin_multi_per_thread {
struct spin_multi_state *state;
ktime_t start;
};
static int multi_other(void *data)
{
int loops;
int cont;
struct spin_multi_per_thread *pt = data;
struct spin_multi_state *s = pt->state;
loops = s->loops;
cont = 1;
atomic_dec(&s->enter_wait);
while (atomic_read(&s->enter_wait))
; /* spin */
pt->start = ktime_get();
atomic_dec(&s->start_wait);
while (atomic_read(&s->start_wait))
; /* spin */
while (cont) {
raw_spin_lock(&s->lock);
loops--;
if (loops == 0)
cont = 0;
raw_spin_unlock(&s->lock);
}
atomic_dec(&s->exit_wait);
while (atomic_read(&s->exit_wait))
; /* spin */
return 0;
}
static int multi_get(void *data, u64 *val)
{
ktime_t finish;
struct spin_multi_state ms;
struct spin_multi_per_thread t1, t2;
ms.lock = __RAW_SPIN_LOCK_UNLOCKED("multi_get");
ms.loops = 1000000;
atomic_set(&ms.start_wait, 2);
atomic_set(&ms.enter_wait, 2);
atomic_set(&ms.exit_wait, 2);
t1.state = &ms;
t2.state = &ms;
kthread_run(multi_other, &t2, "multi_get");
multi_other(&t1);
finish = ktime_get();
*val = ktime_us_delta(finish, t1.start);
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(fops_multi, multi_get, NULL, "%llu\n");
extern struct dentry *mips_debugfs_dir;
static int __init spinlock_test(void)
{
struct dentry *d;
if (!mips_debugfs_dir)
return -ENODEV;
d = debugfs_create_file("spin_single", S_IRUGO,
mips_debugfs_dir, NULL,
&fops_ss);
if (!d)
return -ENOMEM;
d = debugfs_create_file("spin_multi", S_IRUGO,
mips_debugfs_dir, NULL,
&fops_multi);
if (!d)
return -ENOMEM;
return 0;
}
device_initcall(spinlock_test);
| gpl-2.0 |
dmitrysmagin/xz0032-linux | sound/soc/s3c24xx/s3c24xx_uda134x.c | 68 | 9543 | /*
* Modifications by Christian Pellegrin <chripell@evolware.org>
*
* s3c24xx_uda134x.c -- S3C24XX_UDA134X ALSA SoC Audio board driver
*
* Copyright 2007 Dension Audio Systems Ltd.
* Author: Zoltan Devai
*
* 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/clk.h>
#include <linux/mutex.h>
#include <linux/gpio.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include <sound/soc-dapm.h>
#include <sound/s3c24xx_uda134x.h>
#include <sound/uda134x.h>
#include <plat/regs-iis.h>
#include "s3c-dma.h"
#include "s3c24xx-i2s.h"
#include "../codecs/uda134x.h"
/* #define ENFORCE_RATES 1 */
/*
Unfortunately the S3C24XX in master mode has a limited capacity of
generating the clock for the codec. If you define this only rates
that are really available will be enforced. But be careful, most
user level application just want the usual sampling frequencies (8,
11.025, 22.050, 44.1 kHz) and anyway resampling is a costly
operation for embedded systems. So if you aren't very lucky or your
hardware engineer wasn't very forward-looking it's better to leave
this undefined. If you do so an approximate value for the requested
sampling rate in the range -/+ 5% will be chosen. If this in not
possible an error will be returned.
*/
static struct clk *xtal;
static struct clk *pclk;
/* this is need because we don't have a place where to keep the
* pointers to the clocks in each substream. We get the clocks only
* when we are actually using them so we don't block stuff like
* frequency change or oscillator power-off */
static int clk_users;
static DEFINE_MUTEX(clk_lock);
static unsigned int rates[33 * 2];
#ifdef ENFORCE_RATES
static struct snd_pcm_hw_constraint_list hw_constraints_rates = {
.count = ARRAY_SIZE(rates),
.list = rates,
.mask = 0,
};
#endif
static struct platform_device *s3c24xx_uda134x_snd_device;
static int s3c24xx_uda134x_startup(struct snd_pcm_substream *substream)
{
int ret = 0;
#ifdef ENFORCE_RATES
struct snd_pcm_runtime *runtime = substream->runtime;
#endif
mutex_lock(&clk_lock);
pr_debug("%s %d\n", __func__, clk_users);
if (clk_users == 0) {
xtal = clk_get(&s3c24xx_uda134x_snd_device->dev, "xtal");
if (!xtal) {
printk(KERN_ERR "%s cannot get xtal\n", __func__);
ret = -EBUSY;
} else {
pclk = clk_get(&s3c24xx_uda134x_snd_device->dev,
"pclk");
if (!pclk) {
printk(KERN_ERR "%s cannot get pclk\n",
__func__);
clk_put(xtal);
ret = -EBUSY;
}
}
if (!ret) {
int i, j;
for (i = 0; i < 2; i++) {
int fs = i ? 256 : 384;
rates[i*33] = clk_get_rate(xtal) / fs;
for (j = 1; j < 33; j++)
rates[i*33 + j] = clk_get_rate(pclk) /
(j * fs);
}
}
}
clk_users += 1;
mutex_unlock(&clk_lock);
if (!ret) {
#ifdef ENFORCE_RATES
ret = snd_pcm_hw_constraint_list(runtime, 0,
SNDRV_PCM_HW_PARAM_RATE,
&hw_constraints_rates);
if (ret < 0)
printk(KERN_ERR "%s cannot set constraints\n",
__func__);
#endif
}
return ret;
}
static void s3c24xx_uda134x_shutdown(struct snd_pcm_substream *substream)
{
mutex_lock(&clk_lock);
pr_debug("%s %d\n", __func__, clk_users);
clk_users -= 1;
if (clk_users == 0) {
clk_put(xtal);
xtal = NULL;
clk_put(pclk);
pclk = NULL;
}
mutex_unlock(&clk_lock);
}
static int s3c24xx_uda134x_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;
unsigned int clk = 0;
int ret = 0;
int clk_source, fs_mode;
unsigned long rate = params_rate(params);
long err, cerr;
unsigned int div;
int i, bi;
err = 999999;
bi = 0;
for (i = 0; i < 2*33; i++) {
cerr = rates[i] - rate;
if (cerr < 0)
cerr = -cerr;
if (cerr < err) {
err = cerr;
bi = i;
}
}
if (bi / 33 == 1)
fs_mode = S3C2410_IISMOD_256FS;
else
fs_mode = S3C2410_IISMOD_384FS;
if (bi % 33 == 0) {
clk_source = S3C24XX_CLKSRC_MPLL;
div = 1;
} else {
clk_source = S3C24XX_CLKSRC_PCLK;
div = bi % 33;
}
pr_debug("%s desired rate %lu, %d\n", __func__, rate, bi);
clk = (fs_mode == S3C2410_IISMOD_384FS ? 384 : 256) * rate;
pr_debug("%s will use: %s %s %d sysclk %d err %ld\n", __func__,
fs_mode == S3C2410_IISMOD_384FS ? "384FS" : "256FS",
clk_source == S3C24XX_CLKSRC_MPLL ? "MPLLin" : "PCLK",
div, clk, err);
if ((err * 100 / rate) > 5) {
printk(KERN_ERR "S3C24XX_UDA134X: effective frequency "
"too different from desired (%ld%%)\n",
err * 100 / rate);
return -EINVAL;
}
ret = snd_soc_dai_set_fmt(codec_dai, SND_SOC_DAIFMT_I2S |
SND_SOC_DAIFMT_NB_NF | SND_SOC_DAIFMT_CBS_CFS);
if (ret < 0)
return ret;
ret = snd_soc_dai_set_fmt(cpu_dai, SND_SOC_DAIFMT_I2S |
SND_SOC_DAIFMT_NB_NF | SND_SOC_DAIFMT_CBS_CFS);
if (ret < 0)
return ret;
ret = snd_soc_dai_set_sysclk(cpu_dai, clk_source , clk,
SND_SOC_CLOCK_IN);
if (ret < 0)
return ret;
ret = snd_soc_dai_set_clkdiv(cpu_dai, S3C24XX_DIV_MCLK, fs_mode);
if (ret < 0)
return ret;
ret = snd_soc_dai_set_clkdiv(cpu_dai, S3C24XX_DIV_BCLK,
S3C2410_IISMOD_32FS);
if (ret < 0)
return ret;
ret = snd_soc_dai_set_clkdiv(cpu_dai, S3C24XX_DIV_PRESCALER,
S3C24XX_PRESCALE(div, div));
if (ret < 0)
return ret;
/* set the codec system clock for DAC and ADC */
ret = snd_soc_dai_set_sysclk(codec_dai, 0, clk,
SND_SOC_CLOCK_OUT);
if (ret < 0)
return ret;
return 0;
}
static struct snd_soc_ops s3c24xx_uda134x_ops = {
.startup = s3c24xx_uda134x_startup,
.shutdown = s3c24xx_uda134x_shutdown,
.hw_params = s3c24xx_uda134x_hw_params,
};
static struct snd_soc_dai_link s3c24xx_uda134x_dai_link = {
.name = "UDA134X",
.stream_name = "UDA134X",
.codec_name = "uda134x-hifi",
.codec_dai_name = "uda134x-hifi",
.cpu_dai_name = "s3c24xx-i2s",
.ops = &s3c24xx_uda134x_ops,
.platform_name = "s3c24xx-pcm-audio",
};
static struct snd_soc_card snd_soc_s3c24xx_uda134x = {
.name = "S3C24XX_UDA134X",
.dai_link = &s3c24xx_uda134x_dai_link,
.num_links = 1,
};
static struct s3c24xx_uda134x_platform_data *s3c24xx_uda134x_l3_pins;
static void setdat(int v)
{
gpio_set_value(s3c24xx_uda134x_l3_pins->l3_data, v > 0);
}
static void setclk(int v)
{
gpio_set_value(s3c24xx_uda134x_l3_pins->l3_clk, v > 0);
}
static void setmode(int v)
{
gpio_set_value(s3c24xx_uda134x_l3_pins->l3_mode, v > 0);
}
/* FIXME - This must be codec platform data but in which board file ?? */
static struct uda134x_platform_data s3c24xx_uda134x = {
.l3 = {
.setdat = setdat,
.setclk = setclk,
.setmode = setmode,
.data_hold = 1,
.data_setup = 1,
.clock_high = 1,
.mode_hold = 1,
.mode = 1,
.mode_setup = 1,
},
};
static int s3c24xx_uda134x_setup_pin(int pin, char *fun)
{
if (gpio_request(pin, "s3c24xx_uda134x") < 0) {
printk(KERN_ERR "S3C24XX_UDA134X SoC Audio: "
"l3 %s pin already in use", fun);
return -EBUSY;
}
gpio_direction_output(pin, 0);
return 0;
}
static int s3c24xx_uda134x_probe(struct platform_device *pdev)
{
int ret;
printk(KERN_INFO "S3C24XX_UDA134X SoC Audio driver\n");
s3c24xx_uda134x_l3_pins = pdev->dev.platform_data;
if (s3c24xx_uda134x_l3_pins == NULL) {
printk(KERN_ERR "S3C24XX_UDA134X SoC Audio: "
"unable to find platform data\n");
return -ENODEV;
}
s3c24xx_uda134x.power = s3c24xx_uda134x_l3_pins->power;
s3c24xx_uda134x.model = s3c24xx_uda134x_l3_pins->model;
if (s3c24xx_uda134x_setup_pin(s3c24xx_uda134x_l3_pins->l3_data,
"data") < 0)
return -EBUSY;
if (s3c24xx_uda134x_setup_pin(s3c24xx_uda134x_l3_pins->l3_clk,
"clk") < 0) {
gpio_free(s3c24xx_uda134x_l3_pins->l3_data);
return -EBUSY;
}
if (s3c24xx_uda134x_setup_pin(s3c24xx_uda134x_l3_pins->l3_mode,
"mode") < 0) {
gpio_free(s3c24xx_uda134x_l3_pins->l3_data);
gpio_free(s3c24xx_uda134x_l3_pins->l3_clk);
return -EBUSY;
}
s3c24xx_uda134x_snd_device = platform_device_alloc("soc-audio", -1);
if (!s3c24xx_uda134x_snd_device) {
printk(KERN_ERR "S3C24XX_UDA134X SoC Audio: "
"Unable to register\n");
return -ENOMEM;
}
platform_set_drvdata(s3c24xx_uda134x_snd_device,
&snd_soc_s3c24xx_uda134x);
ret = platform_device_add(s3c24xx_uda134x_snd_device);
if (ret) {
printk(KERN_ERR "S3C24XX_UDA134X SoC Audio: Unable to add\n");
platform_device_put(s3c24xx_uda134x_snd_device);
}
return ret;
}
static int s3c24xx_uda134x_remove(struct platform_device *pdev)
{
platform_device_unregister(s3c24xx_uda134x_snd_device);
gpio_free(s3c24xx_uda134x_l3_pins->l3_data);
gpio_free(s3c24xx_uda134x_l3_pins->l3_clk);
gpio_free(s3c24xx_uda134x_l3_pins->l3_mode);
return 0;
}
static struct platform_driver s3c24xx_uda134x_driver = {
.probe = s3c24xx_uda134x_probe,
.remove = s3c24xx_uda134x_remove,
.driver = {
.name = "s3c24xx_uda134x",
.owner = THIS_MODULE,
},
};
static int __init s3c24xx_uda134x_init(void)
{
return platform_driver_register(&s3c24xx_uda134x_driver);
}
static void __exit s3c24xx_uda134x_exit(void)
{
platform_driver_unregister(&s3c24xx_uda134x_driver);
}
module_init(s3c24xx_uda134x_init);
module_exit(s3c24xx_uda134x_exit);
MODULE_AUTHOR("Zoltan Devai, Christian Pellegrin <chripell@evolware.org>");
MODULE_DESCRIPTION("S3C24XX_UDA134X ALSA SoC audio driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
GalaxyTab101/samsung-kernel-galaxytab101 | drivers/gpu/drm/i915/intel_lvds.c | 68 | 29182 | /*
* Copyright © 2006-2007 Intel Corporation
* Copyright (c) 2006 Dave Airlie <airlied@linux.ie>
*
* 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>
* Dave Airlie <airlied@linux.ie>
* Jesse Barnes <jesse.barnes@intel.com>
*/
#include <acpi/button.h>
#include <linux/dmi.h>
#include <linux/i2c.h>
#include <linux/slab.h>
#include "drmP.h"
#include "drm.h"
#include "drm_crtc.h"
#include "drm_edid.h"
#include "intel_drv.h"
#include "i915_drm.h"
#include "i915_drv.h"
#include <linux/acpi.h>
/* Private structure for the integrated LVDS support */
struct intel_lvds {
struct intel_encoder base;
int fitting_mode;
u32 pfit_control;
u32 pfit_pgm_ratios;
};
static struct intel_lvds *enc_to_intel_lvds(struct drm_encoder *encoder)
{
return container_of(enc_to_intel_encoder(encoder), struct intel_lvds, base);
}
/**
* Sets the backlight level.
*
* \param level backlight level, from 0 to intel_lvds_get_max_backlight().
*/
static void intel_lvds_set_backlight(struct drm_device *dev, int level)
{
struct drm_i915_private *dev_priv = dev->dev_private;
u32 blc_pwm_ctl, reg;
if (HAS_PCH_SPLIT(dev))
reg = BLC_PWM_CPU_CTL;
else
reg = BLC_PWM_CTL;
blc_pwm_ctl = I915_READ(reg) & ~BACKLIGHT_DUTY_CYCLE_MASK;
I915_WRITE(reg, (blc_pwm_ctl |
(level << BACKLIGHT_DUTY_CYCLE_SHIFT)));
}
/**
* Returns the maximum level of the backlight duty cycle field.
*/
static u32 intel_lvds_get_max_backlight(struct drm_device *dev)
{
struct drm_i915_private *dev_priv = dev->dev_private;
u32 reg;
if (HAS_PCH_SPLIT(dev))
reg = BLC_PWM_PCH_CTL2;
else
reg = BLC_PWM_CTL;
return ((I915_READ(reg) & BACKLIGHT_MODULATION_FREQ_MASK) >>
BACKLIGHT_MODULATION_FREQ_SHIFT) * 2;
}
/**
* Sets the power state for the panel.
*/
static void intel_lvds_set_power(struct drm_device *dev, bool on)
{
struct drm_i915_private *dev_priv = dev->dev_private;
u32 ctl_reg, status_reg, lvds_reg;
if (HAS_PCH_SPLIT(dev)) {
ctl_reg = PCH_PP_CONTROL;
status_reg = PCH_PP_STATUS;
lvds_reg = PCH_LVDS;
} else {
ctl_reg = PP_CONTROL;
status_reg = PP_STATUS;
lvds_reg = LVDS;
}
if (on) {
I915_WRITE(lvds_reg, I915_READ(lvds_reg) | LVDS_PORT_EN);
POSTING_READ(lvds_reg);
I915_WRITE(ctl_reg, I915_READ(ctl_reg) |
POWER_TARGET_ON);
if (wait_for(I915_READ(status_reg) & PP_ON, 1000, 0))
DRM_ERROR("timed out waiting to enable LVDS pipe");
intel_lvds_set_backlight(dev, dev_priv->backlight_duty_cycle);
} else {
intel_lvds_set_backlight(dev, 0);
I915_WRITE(ctl_reg, I915_READ(ctl_reg) &
~POWER_TARGET_ON);
if (wait_for((I915_READ(status_reg) & PP_ON) == 0, 1000, 0))
DRM_ERROR("timed out waiting for LVDS pipe to turn off");
I915_WRITE(lvds_reg, I915_READ(lvds_reg) & ~LVDS_PORT_EN);
POSTING_READ(lvds_reg);
}
}
static void intel_lvds_dpms(struct drm_encoder *encoder, int mode)
{
struct drm_device *dev = encoder->dev;
if (mode == DRM_MODE_DPMS_ON)
intel_lvds_set_power(dev, true);
else
intel_lvds_set_power(dev, false);
/* XXX: We never power down the LVDS pairs. */
}
static int intel_lvds_mode_valid(struct drm_connector *connector,
struct drm_display_mode *mode)
{
struct drm_device *dev = connector->dev;
struct drm_i915_private *dev_priv = dev->dev_private;
struct drm_display_mode *fixed_mode = dev_priv->panel_fixed_mode;
if (fixed_mode) {
if (mode->hdisplay > fixed_mode->hdisplay)
return MODE_PANEL;
if (mode->vdisplay > fixed_mode->vdisplay)
return MODE_PANEL;
}
return MODE_OK;
}
static void
centre_horizontally(struct drm_display_mode *mode,
int width)
{
u32 border, sync_pos, blank_width, sync_width;
/* keep the hsync and hblank widths constant */
sync_width = mode->crtc_hsync_end - mode->crtc_hsync_start;
blank_width = mode->crtc_hblank_end - mode->crtc_hblank_start;
sync_pos = (blank_width - sync_width + 1) / 2;
border = (mode->hdisplay - width + 1) / 2;
border += border & 1; /* make the border even */
mode->crtc_hdisplay = width;
mode->crtc_hblank_start = width + border;
mode->crtc_hblank_end = mode->crtc_hblank_start + blank_width;
mode->crtc_hsync_start = mode->crtc_hblank_start + sync_pos;
mode->crtc_hsync_end = mode->crtc_hsync_start + sync_width;
}
static void
centre_vertically(struct drm_display_mode *mode,
int height)
{
u32 border, sync_pos, blank_width, sync_width;
/* keep the vsync and vblank widths constant */
sync_width = mode->crtc_vsync_end - mode->crtc_vsync_start;
blank_width = mode->crtc_vblank_end - mode->crtc_vblank_start;
sync_pos = (blank_width - sync_width + 1) / 2;
border = (mode->vdisplay - height + 1) / 2;
mode->crtc_vdisplay = height;
mode->crtc_vblank_start = height + border;
mode->crtc_vblank_end = mode->crtc_vblank_start + blank_width;
mode->crtc_vsync_start = mode->crtc_vblank_start + sync_pos;
mode->crtc_vsync_end = mode->crtc_vsync_start + sync_width;
}
static inline u32 panel_fitter_scaling(u32 source, u32 target)
{
/*
* Floating point operation is not supported. So the FACTOR
* is defined, which can avoid the floating point computation
* when calculating the panel ratio.
*/
#define ACCURACY 12
#define FACTOR (1 << ACCURACY)
u32 ratio = source * FACTOR / target;
return (FACTOR * ratio + FACTOR/2) / FACTOR;
}
static bool intel_lvds_mode_fixup(struct drm_encoder *encoder,
struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
struct drm_device *dev = encoder->dev;
struct drm_i915_private *dev_priv = dev->dev_private;
struct intel_crtc *intel_crtc = to_intel_crtc(encoder->crtc);
struct intel_lvds *intel_lvds = enc_to_intel_lvds(encoder);
struct drm_encoder *tmp_encoder;
u32 pfit_control = 0, pfit_pgm_ratios = 0, border = 0;
/* Should never happen!! */
if (!IS_I965G(dev) && intel_crtc->pipe == 0) {
DRM_ERROR("Can't support LVDS on pipe A\n");
return false;
}
/* Should never happen!! */
list_for_each_entry(tmp_encoder, &dev->mode_config.encoder_list, head) {
if (tmp_encoder != encoder && tmp_encoder->crtc == encoder->crtc) {
DRM_ERROR("Can't enable LVDS and another "
"encoder on the same pipe\n");
return false;
}
}
/* If we don't have a panel mode, there is nothing we can do */
if (dev_priv->panel_fixed_mode == NULL)
return true;
/*
* We have timings from the BIOS for the panel, put them in
* to the adjusted mode. The CRTC will be set up for this mode,
* with the panel scaling set up to source from the H/VDisplay
* of the original mode.
*/
intel_fixed_panel_mode(dev_priv->panel_fixed_mode, adjusted_mode);
if (HAS_PCH_SPLIT(dev)) {
intel_pch_panel_fitting(dev, intel_lvds->fitting_mode,
mode, adjusted_mode);
return true;
}
/* Make sure pre-965s set dither correctly */
if (!IS_I965G(dev)) {
if (dev_priv->panel_wants_dither || dev_priv->lvds_dither)
pfit_control |= PANEL_8TO6_DITHER_ENABLE;
}
/* Native modes don't need fitting */
if (adjusted_mode->hdisplay == mode->hdisplay &&
adjusted_mode->vdisplay == mode->vdisplay)
goto out;
/* 965+ wants fuzzy fitting */
if (IS_I965G(dev))
pfit_control |= ((intel_crtc->pipe << PFIT_PIPE_SHIFT) |
PFIT_FILTER_FUZZY);
/*
* Enable automatic panel scaling for non-native modes so that they fill
* the screen. Should be enabled before the pipe is enabled, according
* to register description and PRM.
* Change the value here to see the borders for debugging
*/
I915_WRITE(BCLRPAT_A, 0);
I915_WRITE(BCLRPAT_B, 0);
switch (intel_lvds->fitting_mode) {
case DRM_MODE_SCALE_CENTER:
/*
* For centered modes, we have to calculate border widths &
* heights and modify the values programmed into the CRTC.
*/
centre_horizontally(adjusted_mode, mode->hdisplay);
centre_vertically(adjusted_mode, mode->vdisplay);
border = LVDS_BORDER_ENABLE;
break;
case DRM_MODE_SCALE_ASPECT:
/* Scale but preserve the aspect ratio */
if (IS_I965G(dev)) {
u32 scaled_width = adjusted_mode->hdisplay * mode->vdisplay;
u32 scaled_height = mode->hdisplay * adjusted_mode->vdisplay;
pfit_control |= PFIT_ENABLE;
/* 965+ is easy, it does everything in hw */
if (scaled_width > scaled_height)
pfit_control |= PFIT_SCALING_PILLAR;
else if (scaled_width < scaled_height)
pfit_control |= PFIT_SCALING_LETTER;
else
pfit_control |= PFIT_SCALING_AUTO;
} else {
u32 scaled_width = adjusted_mode->hdisplay * mode->vdisplay;
u32 scaled_height = mode->hdisplay * adjusted_mode->vdisplay;
/*
* For earlier chips we have to calculate the scaling
* ratio by hand and program it into the
* PFIT_PGM_RATIO register
*/
if (scaled_width > scaled_height) { /* pillar */
centre_horizontally(adjusted_mode, scaled_height / mode->vdisplay);
border = LVDS_BORDER_ENABLE;
if (mode->vdisplay != adjusted_mode->vdisplay) {
u32 bits = panel_fitter_scaling(mode->vdisplay, adjusted_mode->vdisplay);
pfit_pgm_ratios |= (bits << PFIT_HORIZ_SCALE_SHIFT |
bits << PFIT_VERT_SCALE_SHIFT);
pfit_control |= (PFIT_ENABLE |
VERT_INTERP_BILINEAR |
HORIZ_INTERP_BILINEAR);
}
} else if (scaled_width < scaled_height) { /* letter */
centre_vertically(adjusted_mode, scaled_width / mode->hdisplay);
border = LVDS_BORDER_ENABLE;
if (mode->hdisplay != adjusted_mode->hdisplay) {
u32 bits = panel_fitter_scaling(mode->hdisplay, adjusted_mode->hdisplay);
pfit_pgm_ratios |= (bits << PFIT_HORIZ_SCALE_SHIFT |
bits << PFIT_VERT_SCALE_SHIFT);
pfit_control |= (PFIT_ENABLE |
VERT_INTERP_BILINEAR |
HORIZ_INTERP_BILINEAR);
}
} else
/* Aspects match, Let hw scale both directions */
pfit_control |= (PFIT_ENABLE |
VERT_AUTO_SCALE | HORIZ_AUTO_SCALE |
VERT_INTERP_BILINEAR |
HORIZ_INTERP_BILINEAR);
}
break;
case DRM_MODE_SCALE_FULLSCREEN:
/*
* Full scaling, even if it changes the aspect ratio.
* Fortunately this is all done for us in hw.
*/
pfit_control |= PFIT_ENABLE;
if (IS_I965G(dev))
pfit_control |= PFIT_SCALING_AUTO;
else
pfit_control |= (VERT_AUTO_SCALE | HORIZ_AUTO_SCALE |
VERT_INTERP_BILINEAR |
HORIZ_INTERP_BILINEAR);
break;
default:
break;
}
out:
intel_lvds->pfit_control = pfit_control;
intel_lvds->pfit_pgm_ratios = pfit_pgm_ratios;
dev_priv->lvds_border_bits = border;
/*
* XXX: It would be nice to support lower refresh rates on the
* panels to reduce power consumption, and perhaps match the
* user's requested refresh rate.
*/
return true;
}
static void intel_lvds_prepare(struct drm_encoder *encoder)
{
struct drm_device *dev = encoder->dev;
struct drm_i915_private *dev_priv = dev->dev_private;
u32 reg;
if (HAS_PCH_SPLIT(dev))
reg = BLC_PWM_CPU_CTL;
else
reg = BLC_PWM_CTL;
dev_priv->saveBLC_PWM_CTL = I915_READ(reg);
dev_priv->backlight_duty_cycle = (dev_priv->saveBLC_PWM_CTL &
BACKLIGHT_DUTY_CYCLE_MASK);
intel_lvds_set_power(dev, false);
}
static void intel_lvds_commit( struct drm_encoder *encoder)
{
struct drm_device *dev = encoder->dev;
struct drm_i915_private *dev_priv = dev->dev_private;
if (dev_priv->backlight_duty_cycle == 0)
dev_priv->backlight_duty_cycle =
intel_lvds_get_max_backlight(dev);
intel_lvds_set_power(dev, true);
}
static void intel_lvds_mode_set(struct drm_encoder *encoder,
struct drm_display_mode *mode,
struct drm_display_mode *adjusted_mode)
{
struct drm_device *dev = encoder->dev;
struct drm_i915_private *dev_priv = dev->dev_private;
struct intel_lvds *intel_lvds = enc_to_intel_lvds(encoder);
/*
* The LVDS pin pair will already have been turned on in the
* intel_crtc_mode_set since it has a large impact on the DPLL
* settings.
*/
if (HAS_PCH_SPLIT(dev))
return;
/*
* Enable automatic panel scaling so that non-native modes fill the
* screen. Should be enabled before the pipe is enabled, according to
* register description and PRM.
*/
I915_WRITE(PFIT_PGM_RATIOS, intel_lvds->pfit_pgm_ratios);
I915_WRITE(PFIT_CONTROL, intel_lvds->pfit_control);
}
/**
* Detect the LVDS connection.
*
* Since LVDS doesn't have hotlug, we use the lid as a proxy. Open means
* connected and closed means disconnected. We also send hotplug events as
* needed, using lid status notification from the input layer.
*/
static enum drm_connector_status
intel_lvds_detect(struct drm_connector *connector, bool force)
{
struct drm_device *dev = connector->dev;
enum drm_connector_status status = connector_status_connected;
/* ACPI lid methods were generally unreliable in this generation, so
* don't even bother.
*/
if (IS_GEN2(dev) || IS_GEN3(dev))
return connector_status_connected;
return status;
}
/**
* Return the list of DDC modes if available, or the BIOS fixed mode otherwise.
*/
static int intel_lvds_get_modes(struct drm_connector *connector)
{
struct drm_device *dev = connector->dev;
struct drm_encoder *encoder = intel_attached_encoder(connector);
struct intel_encoder *intel_encoder = enc_to_intel_encoder(encoder);
struct drm_i915_private *dev_priv = dev->dev_private;
int ret = 0;
if (dev_priv->lvds_edid_good) {
ret = intel_ddc_get_modes(connector, intel_encoder->ddc_bus);
if (ret)
return ret;
}
/* Didn't get an EDID, so
* Set wide sync ranges so we get all modes
* handed to valid_mode for checking
*/
connector->display_info.min_vfreq = 0;
connector->display_info.max_vfreq = 200;
connector->display_info.min_hfreq = 0;
connector->display_info.max_hfreq = 200;
if (dev_priv->panel_fixed_mode != NULL) {
struct drm_display_mode *mode;
mode = drm_mode_duplicate(dev, dev_priv->panel_fixed_mode);
drm_mode_probed_add(connector, mode);
return 1;
}
return 0;
}
static int intel_no_modeset_on_lid_dmi_callback(const struct dmi_system_id *id)
{
DRM_DEBUG_KMS("Skipping forced modeset for %s\n", id->ident);
return 1;
}
/* The GPU hangs up on these systems if modeset is performed on LID open */
static const struct dmi_system_id intel_no_modeset_on_lid[] = {
{
.callback = intel_no_modeset_on_lid_dmi_callback,
.ident = "Toshiba Tecra A11",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "TOSHIBA"),
DMI_MATCH(DMI_PRODUCT_NAME, "TECRA A11"),
},
},
{ } /* terminating entry */
};
/*
* Lid events. Note the use of 'modeset_on_lid':
* - we set it on lid close, and reset it on open
* - we use it as a "only once" bit (ie we ignore
* duplicate events where it was already properly
* set/reset)
* - the suspend/resume paths will also set it to
* zero, since they restore the mode ("lid open").
*/
static int intel_lid_notify(struct notifier_block *nb, unsigned long val,
void *unused)
{
struct drm_i915_private *dev_priv =
container_of(nb, struct drm_i915_private, lid_notifier);
struct drm_device *dev = dev_priv->dev;
struct drm_connector *connector = dev_priv->int_lvds_connector;
/*
* check and update the status of LVDS connector after receiving
* the LID nofication event.
*/
if (connector)
connector->status = connector->funcs->detect(connector,
false);
/* Don't force modeset on machines where it causes a GPU lockup */
if (dmi_check_system(intel_no_modeset_on_lid))
return NOTIFY_OK;
if (!acpi_lid_open()) {
dev_priv->modeset_on_lid = 1;
return NOTIFY_OK;
}
if (!dev_priv->modeset_on_lid)
return NOTIFY_OK;
dev_priv->modeset_on_lid = 0;
mutex_lock(&dev->mode_config.mutex);
drm_helper_resume_force_mode(dev);
mutex_unlock(&dev->mode_config.mutex);
return NOTIFY_OK;
}
/**
* intel_lvds_destroy - unregister and free LVDS structures
* @connector: connector to free
*
* Unregister the DDC bus for this connector then free the driver private
* structure.
*/
static void intel_lvds_destroy(struct drm_connector *connector)
{
struct drm_device *dev = connector->dev;
struct drm_i915_private *dev_priv = dev->dev_private;
if (dev_priv->lid_notifier.notifier_call)
acpi_lid_notifier_unregister(&dev_priv->lid_notifier);
drm_sysfs_connector_remove(connector);
drm_connector_cleanup(connector);
kfree(connector);
}
static int intel_lvds_set_property(struct drm_connector *connector,
struct drm_property *property,
uint64_t value)
{
struct drm_device *dev = connector->dev;
if (property == dev->mode_config.scaling_mode_property &&
connector->encoder) {
struct drm_crtc *crtc = connector->encoder->crtc;
struct drm_encoder *encoder = connector->encoder;
struct intel_lvds *intel_lvds = enc_to_intel_lvds(encoder);
if (value == DRM_MODE_SCALE_NONE) {
DRM_DEBUG_KMS("no scaling not supported\n");
return 0;
}
if (intel_lvds->fitting_mode == value) {
/* the LVDS scaling property is not changed */
return 0;
}
intel_lvds->fitting_mode = value;
if (crtc && crtc->enabled) {
/*
* If the CRTC is enabled, the display will be changed
* according to the new panel fitting mode.
*/
drm_crtc_helper_set_mode(crtc, &crtc->mode,
crtc->x, crtc->y, crtc->fb);
}
}
return 0;
}
static const struct drm_encoder_helper_funcs intel_lvds_helper_funcs = {
.dpms = intel_lvds_dpms,
.mode_fixup = intel_lvds_mode_fixup,
.prepare = intel_lvds_prepare,
.mode_set = intel_lvds_mode_set,
.commit = intel_lvds_commit,
};
static const struct drm_connector_helper_funcs intel_lvds_connector_helper_funcs = {
.get_modes = intel_lvds_get_modes,
.mode_valid = intel_lvds_mode_valid,
.best_encoder = intel_attached_encoder,
};
static const struct drm_connector_funcs intel_lvds_connector_funcs = {
.dpms = drm_helper_connector_dpms,
.detect = intel_lvds_detect,
.fill_modes = drm_helper_probe_single_connector_modes,
.set_property = intel_lvds_set_property,
.destroy = intel_lvds_destroy,
};
static const struct drm_encoder_funcs intel_lvds_enc_funcs = {
.destroy = intel_encoder_destroy,
};
static int __init intel_no_lvds_dmi_callback(const struct dmi_system_id *id)
{
DRM_DEBUG_KMS("Skipping LVDS initialization for %s\n", id->ident);
return 1;
}
/* These systems claim to have LVDS, but really don't */
static const struct dmi_system_id intel_no_lvds[] = {
{
.callback = intel_no_lvds_dmi_callback,
.ident = "Apple Mac Mini (Core series)",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Apple"),
DMI_MATCH(DMI_PRODUCT_NAME, "Macmini1,1"),
},
},
{
.callback = intel_no_lvds_dmi_callback,
.ident = "Apple Mac Mini (Core 2 series)",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Apple"),
DMI_MATCH(DMI_PRODUCT_NAME, "Macmini2,1"),
},
},
{
.callback = intel_no_lvds_dmi_callback,
.ident = "MSI IM-945GSE-A",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "MSI"),
DMI_MATCH(DMI_PRODUCT_NAME, "A9830IMS"),
},
},
{
.callback = intel_no_lvds_dmi_callback,
.ident = "Dell Studio Hybrid",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
DMI_MATCH(DMI_PRODUCT_NAME, "Studio Hybrid 140g"),
},
},
{
.callback = intel_no_lvds_dmi_callback,
.ident = "AOpen Mini PC",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "AOpen"),
DMI_MATCH(DMI_PRODUCT_NAME, "i965GMx-IF"),
},
},
{
.callback = intel_no_lvds_dmi_callback,
.ident = "AOpen Mini PC MP915",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "AOpen"),
DMI_MATCH(DMI_BOARD_NAME, "i915GMx-F"),
},
},
{
.callback = intel_no_lvds_dmi_callback,
.ident = "Aopen i945GTt-VFA",
.matches = {
DMI_MATCH(DMI_PRODUCT_VERSION, "AO00001JW"),
},
},
{
.callback = intel_no_lvds_dmi_callback,
.ident = "Clientron U800",
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Clientron"),
DMI_MATCH(DMI_PRODUCT_NAME, "U800"),
},
},
{ } /* terminating entry */
};
/**
* intel_find_lvds_downclock - find the reduced downclock for LVDS in EDID
* @dev: drm device
* @connector: LVDS connector
*
* Find the reduced downclock for LVDS in EDID.
*/
static void intel_find_lvds_downclock(struct drm_device *dev,
struct drm_connector *connector)
{
struct drm_i915_private *dev_priv = dev->dev_private;
struct drm_display_mode *scan, *panel_fixed_mode;
int temp_downclock;
panel_fixed_mode = dev_priv->panel_fixed_mode;
temp_downclock = panel_fixed_mode->clock;
mutex_lock(&dev->mode_config.mutex);
list_for_each_entry(scan, &connector->probed_modes, head) {
/*
* If one mode has the same resolution with the fixed_panel
* mode while they have the different refresh rate, it means
* that the reduced downclock is found for the LVDS. In such
* case we can set the different FPx0/1 to dynamically select
* between low and high frequency.
*/
if (scan->hdisplay == panel_fixed_mode->hdisplay &&
scan->hsync_start == panel_fixed_mode->hsync_start &&
scan->hsync_end == panel_fixed_mode->hsync_end &&
scan->htotal == panel_fixed_mode->htotal &&
scan->vdisplay == panel_fixed_mode->vdisplay &&
scan->vsync_start == panel_fixed_mode->vsync_start &&
scan->vsync_end == panel_fixed_mode->vsync_end &&
scan->vtotal == panel_fixed_mode->vtotal) {
if (scan->clock < temp_downclock) {
/*
* The downclock is already found. But we
* expect to find the lower downclock.
*/
temp_downclock = scan->clock;
}
}
}
mutex_unlock(&dev->mode_config.mutex);
if (temp_downclock < panel_fixed_mode->clock &&
i915_lvds_downclock) {
/* We found the downclock for LVDS. */
dev_priv->lvds_downclock_avail = 1;
dev_priv->lvds_downclock = temp_downclock;
DRM_DEBUG_KMS("LVDS downclock is found in EDID. "
"Normal clock %dKhz, downclock %dKhz\n",
panel_fixed_mode->clock, temp_downclock);
}
return;
}
/*
* Enumerate the child dev array parsed from VBT to check whether
* the LVDS is present.
* If it is present, return 1.
* If it is not present, return false.
* If no child dev is parsed from VBT, it assumes that the LVDS is present.
* Note: The addin_offset should also be checked for LVDS panel.
* Only when it is non-zero, it is assumed that it is present.
*/
static int lvds_is_present_in_vbt(struct drm_device *dev)
{
struct drm_i915_private *dev_priv = dev->dev_private;
struct child_device_config *p_child;
int i, ret;
if (!dev_priv->child_dev_num)
return 1;
ret = 0;
for (i = 0; i < dev_priv->child_dev_num; i++) {
p_child = dev_priv->child_dev + i;
/*
* If the device type is not LFP, continue.
* If the device type is 0x22, it is also regarded as LFP.
*/
if (p_child->device_type != DEVICE_TYPE_INT_LFP &&
p_child->device_type != DEVICE_TYPE_LFP)
continue;
/* The addin_offset should be checked. Only when it is
* non-zero, it is regarded as present.
*/
if (p_child->addin_offset) {
ret = 1;
break;
}
}
return ret;
}
/**
* intel_lvds_init - setup LVDS connectors on this device
* @dev: drm device
*
* Create the connector, register the LVDS DDC bus, and try to figure out what
* modes we can display on the LVDS panel (if present).
*/
void intel_lvds_init(struct drm_device *dev)
{
struct drm_i915_private *dev_priv = dev->dev_private;
struct intel_lvds *intel_lvds;
struct intel_encoder *intel_encoder;
struct intel_connector *intel_connector;
struct drm_connector *connector;
struct drm_encoder *encoder;
struct drm_display_mode *scan; /* *modes, *bios_mode; */
struct drm_crtc *crtc;
u32 lvds;
int pipe, gpio = GPIOC;
/* Skip init on machines we know falsely report LVDS */
if (dmi_check_system(intel_no_lvds))
return;
if (!lvds_is_present_in_vbt(dev)) {
DRM_DEBUG_KMS("LVDS is not present in VBT\n");
return;
}
if (HAS_PCH_SPLIT(dev)) {
if ((I915_READ(PCH_LVDS) & LVDS_DETECTED) == 0)
return;
if (dev_priv->edp_support) {
DRM_DEBUG_KMS("disable LVDS for eDP support\n");
return;
}
gpio = PCH_GPIOC;
}
intel_lvds = kzalloc(sizeof(struct intel_lvds), GFP_KERNEL);
if (!intel_lvds) {
return;
}
intel_connector = kzalloc(sizeof(struct intel_connector), GFP_KERNEL);
if (!intel_connector) {
kfree(intel_lvds);
return;
}
intel_encoder = &intel_lvds->base;
encoder = &intel_encoder->enc;
connector = &intel_connector->base;
drm_connector_init(dev, &intel_connector->base, &intel_lvds_connector_funcs,
DRM_MODE_CONNECTOR_LVDS);
drm_encoder_init(dev, &intel_encoder->enc, &intel_lvds_enc_funcs,
DRM_MODE_ENCODER_LVDS);
drm_mode_connector_attach_encoder(&intel_connector->base, &intel_encoder->enc);
intel_encoder->type = INTEL_OUTPUT_LVDS;
intel_encoder->clone_mask = (1 << INTEL_LVDS_CLONE_BIT);
intel_encoder->crtc_mask = (1 << 1);
drm_encoder_helper_add(encoder, &intel_lvds_helper_funcs);
drm_connector_helper_add(connector, &intel_lvds_connector_helper_funcs);
connector->display_info.subpixel_order = SubPixelHorizontalRGB;
connector->interlace_allowed = false;
connector->doublescan_allowed = false;
/* create the scaling mode property */
drm_mode_create_scaling_mode_property(dev);
/*
* the initial panel fitting mode will be FULL_SCREEN.
*/
drm_connector_attach_property(&intel_connector->base,
dev->mode_config.scaling_mode_property,
DRM_MODE_SCALE_ASPECT);
intel_lvds->fitting_mode = DRM_MODE_SCALE_ASPECT;
/*
* LVDS discovery:
* 1) check for EDID on DDC
* 2) check for VBT data
* 3) check to see if LVDS is already on
* if none of the above, no panel
* 4) make sure lid is open
* if closed, act like it's not there for now
*/
/* Set up the DDC bus. */
intel_encoder->ddc_bus = intel_i2c_create(dev, gpio, "LVDSDDC_C");
if (!intel_encoder->ddc_bus) {
dev_printk(KERN_ERR, &dev->pdev->dev, "DDC bus registration "
"failed.\n");
goto failed;
}
/*
* Attempt to get the fixed panel mode from DDC. Assume that the
* preferred mode is the right one.
*/
dev_priv->lvds_edid_good = true;
if (!intel_ddc_get_modes(connector, intel_encoder->ddc_bus))
dev_priv->lvds_edid_good = false;
list_for_each_entry(scan, &connector->probed_modes, head) {
mutex_lock(&dev->mode_config.mutex);
if (scan->type & DRM_MODE_TYPE_PREFERRED) {
dev_priv->panel_fixed_mode =
drm_mode_duplicate(dev, scan);
mutex_unlock(&dev->mode_config.mutex);
intel_find_lvds_downclock(dev, connector);
goto out;
}
mutex_unlock(&dev->mode_config.mutex);
}
/* Failed to get EDID, what about VBT? */
if (dev_priv->lfp_lvds_vbt_mode) {
mutex_lock(&dev->mode_config.mutex);
dev_priv->panel_fixed_mode =
drm_mode_duplicate(dev, dev_priv->lfp_lvds_vbt_mode);
mutex_unlock(&dev->mode_config.mutex);
if (dev_priv->panel_fixed_mode) {
dev_priv->panel_fixed_mode->type |=
DRM_MODE_TYPE_PREFERRED;
goto out;
}
}
/*
* If we didn't get EDID, try checking if the panel is already turned
* on. If so, assume that whatever is currently programmed is the
* correct mode.
*/
/* Ironlake: FIXME if still fail, not try pipe mode now */
if (HAS_PCH_SPLIT(dev))
goto failed;
lvds = I915_READ(LVDS);
pipe = (lvds & LVDS_PIPEB_SELECT) ? 1 : 0;
crtc = intel_get_crtc_from_pipe(dev, pipe);
if (crtc && (lvds & LVDS_PORT_EN)) {
dev_priv->panel_fixed_mode = intel_crtc_mode_get(dev, crtc);
if (dev_priv->panel_fixed_mode) {
dev_priv->panel_fixed_mode->type |=
DRM_MODE_TYPE_PREFERRED;
goto out;
}
}
/* If we still don't have a mode after all that, give up. */
if (!dev_priv->panel_fixed_mode)
goto failed;
out:
if (HAS_PCH_SPLIT(dev)) {
u32 pwm;
/* make sure PWM is enabled */
pwm = I915_READ(BLC_PWM_CPU_CTL2);
pwm |= (PWM_ENABLE | PWM_PIPE_B);
I915_WRITE(BLC_PWM_CPU_CTL2, pwm);
pwm = I915_READ(BLC_PWM_PCH_CTL1);
pwm |= PWM_PCH_ENABLE;
I915_WRITE(BLC_PWM_PCH_CTL1, pwm);
}
dev_priv->lid_notifier.notifier_call = intel_lid_notify;
if (acpi_lid_notifier_register(&dev_priv->lid_notifier)) {
DRM_DEBUG_KMS("lid notifier registration failed\n");
dev_priv->lid_notifier.notifier_call = NULL;
}
/* keep the LVDS connector */
dev_priv->int_lvds_connector = connector;
drm_sysfs_connector_add(connector);
return;
failed:
DRM_DEBUG_KMS("No LVDS modes found, disabling.\n");
if (intel_encoder->ddc_bus)
intel_i2c_destroy(intel_encoder->ddc_bus);
drm_connector_cleanup(connector);
drm_encoder_cleanup(encoder);
kfree(intel_lvds);
kfree(intel_connector);
}
| gpl-2.0 |
Evervolv/android_kernel_htc_msm8974 | arch/cris/arch-v32/lib/memset.c | 68 | 6045 | /* A memset for CRIS.
Copyright (C) 1999-2005 Axis Communications.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Neither the name of Axis Communications nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY AXIS COMMUNICATIONS AND ITS CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL AXIS
COMMUNICATIONS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE. */
/* Assuming one cycle per dword written or read (ok, not really true; the
world is not ideal), and one cycle per instruction, then 43+3*(n/48-1)
<= 24+24*(n/48-1) so n >= 45.7; n >= 0.9; we win on the first full
48-byte block to set. */
#define MEMSET_BY_BLOCK_THRESHOLD (1 * 48)
__asm__ (".syntax no_register_prefix");
void *memset(void *pdst, int c, unsigned int plen)
{
register char *return_dst __asm__ ("r10") = pdst;
register int n __asm__ ("r12") = plen;
register int lc __asm__ ("r11") = c;
__asm__("movu.b %0,r13 \n\
lslq 8,r13 \n\
move.b %0,r13 \n\
move.d r13,%0 \n\
lslq 16,r13 \n\
or.d r13,%0"
: "=r" (lc)
: "0" (lc)
: "r13");
{
register char *dst __asm__ ("r13") = pdst;
if (((unsigned long) pdst & 3) != 0
&& n >= 3)
{
if ((unsigned long) dst & 1)
{
*dst = (char) lc;
n--;
dst++;
}
if ((unsigned long) dst & 2)
{
*(short *) dst = lc;
n -= 2;
dst += 2;
}
}
if (n >= MEMSET_BY_BLOCK_THRESHOLD)
{
__asm__ volatile
("\
;; GCC does promise correct register allocations, but let's \n\
;; make sure it keeps its promises. \n\
.ifnc %0-%1-%4,$r13-$r12-$r11 \n\
.error \"GCC reg alloc bug: %0-%1-%4 != $r13-$r12-$r11\" \n\
.endif \n\
\n\
;; Save the registers we'll clobber in the movem process \n\
;; on the stack. Don't mention them to gcc, it will only be \n\
;; upset. \n\
subq 11*4,sp \n\
movem r10,[sp] \n\
\n\
move.d r11,r0 \n\
move.d r11,r1 \n\
move.d r11,r2 \n\
move.d r11,r3 \n\
move.d r11,r4 \n\
move.d r11,r5 \n\
move.d r11,r6 \n\
move.d r11,r7 \n\
move.d r11,r8 \n\
move.d r11,r9 \n\
move.d r11,r10 \n\
\n\
;; Now we've got this: \n\
;; r13 - dst \n\
;; r12 - n \n\
\n\
;; Update n for the first loop \n\
subq 12*4,r12 \n\
0: \n\
"
#ifdef __arch_common_v10_v32
" setf\n"
#endif
" subq 12*4,r12 \n\
bge 0b \n\
movem r11,[r13+] \n\
\n\
;; Compensate for last loop underflowing n. \n\
addq 12*4,r12 \n\
\n\
;; Restore registers from stack. \n\
movem [sp+],r10"
: "=r" (dst), "=r" (n)
: "0" (dst), "1" (n), "r" (lc));
}
while (n >= 16)
{
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
n -= 16;
}
switch (n)
{
case 0:
break;
case 1:
*dst = (char) lc;
break;
case 2:
*(short *) dst = (short) lc;
break;
case 3:
*(short *) dst = (short) lc; dst += 2;
*dst = (char) lc;
break;
case 4:
*(long *) dst = lc;
break;
case 5:
*(long *) dst = lc; dst += 4;
*dst = (char) lc;
break;
case 6:
*(long *) dst = lc; dst += 4;
*(short *) dst = (short) lc;
break;
case 7:
*(long *) dst = lc; dst += 4;
*(short *) dst = (short) lc; dst += 2;
*dst = (char) lc;
break;
case 8:
*(long *) dst = lc; dst += 4;
*(long *) dst = lc;
break;
case 9:
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*dst = (char) lc;
break;
case 10:
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*(short *) dst = (short) lc;
break;
case 11:
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*(short *) dst = (short) lc; dst += 2;
*dst = (char) lc;
break;
case 12:
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*(long *) dst = lc;
break;
case 13:
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*dst = (char) lc;
break;
case 14:
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*(short *) dst = (short) lc;
break;
case 15:
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*(long *) dst = lc; dst += 4;
*(short *) dst = (short) lc; dst += 2;
*dst = (char) lc;
break;
}
}
return return_dst;
}
| gpl-2.0 |
ygpark/iamroot-linux-arm10c | drivers/i2c/busses/i2c-rcar.c | 68 | 15613 | /*
* drivers/i2c/busses/i2c-rcar.c
*
* Copyright (C) 2012 Renesas Solutions Corp.
* Kuninori Morimoto <kuninori.morimoto.gx@renesas.com>
*
* This file is based on the drivers/i2c/busses/i2c-sh7760.c
* (c) 2005-2008 MSC Vertriebsges.m.b.H, Manuel Lauss <mlau@msc-ge.com>
*
* This file used out-of-tree driver i2c-rcar.c
* Copyright (C) 2011-2012 Renesas Electronics Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License
*
* 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/clk.h>
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/i2c.h>
#include <linux/i2c/i2c-rcar.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/pm_runtime.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
/* register offsets */
#define ICSCR 0x00 /* slave ctrl */
#define ICMCR 0x04 /* master ctrl */
#define ICSSR 0x08 /* slave status */
#define ICMSR 0x0C /* master status */
#define ICSIER 0x10 /* slave irq enable */
#define ICMIER 0x14 /* master irq enable */
#define ICCCR 0x18 /* clock dividers */
#define ICSAR 0x1C /* slave address */
#define ICMAR 0x20 /* master address */
#define ICRXTX 0x24 /* data port */
/* ICMCR */
#define MDBS (1 << 7) /* non-fifo mode switch */
#define FSCL (1 << 6) /* override SCL pin */
#define FSDA (1 << 5) /* override SDA pin */
#define OBPC (1 << 4) /* override pins */
#define MIE (1 << 3) /* master if enable */
#define TSBE (1 << 2)
#define FSB (1 << 1) /* force stop bit */
#define ESG (1 << 0) /* en startbit gen */
/* ICMSR */
#define MNR (1 << 6) /* nack received */
#define MAL (1 << 5) /* arbitration lost */
#define MST (1 << 4) /* sent a stop */
#define MDE (1 << 3)
#define MDT (1 << 2)
#define MDR (1 << 1)
#define MAT (1 << 0) /* slave addr xfer done */
/* ICMIE */
#define MNRE (1 << 6) /* nack irq en */
#define MALE (1 << 5) /* arblos irq en */
#define MSTE (1 << 4) /* stop irq en */
#define MDEE (1 << 3)
#define MDTE (1 << 2)
#define MDRE (1 << 1)
#define MATE (1 << 0) /* address sent irq en */
enum {
RCAR_BUS_PHASE_ADDR,
RCAR_BUS_PHASE_DATA,
RCAR_BUS_PHASE_STOP,
};
enum {
RCAR_IRQ_CLOSE,
RCAR_IRQ_OPEN_FOR_SEND,
RCAR_IRQ_OPEN_FOR_RECV,
RCAR_IRQ_OPEN_FOR_STOP,
};
/*
* flags
*/
#define ID_LAST_MSG (1 << 0)
#define ID_IOERROR (1 << 1)
#define ID_DONE (1 << 2)
#define ID_ARBLOST (1 << 3)
#define ID_NACK (1 << 4)
struct rcar_i2c_priv {
void __iomem *io;
struct i2c_adapter adap;
struct i2c_msg *msg;
spinlock_t lock;
wait_queue_head_t wait;
int pos;
int irq;
u32 icccr;
u32 flags;
};
#define rcar_i2c_priv_to_dev(p) ((p)->adap.dev.parent)
#define rcar_i2c_is_recv(p) ((p)->msg->flags & I2C_M_RD)
#define rcar_i2c_flags_set(p, f) ((p)->flags |= (f))
#define rcar_i2c_flags_has(p, f) ((p)->flags & (f))
#define LOOP_TIMEOUT 1024
/*
* basic functions
*/
static void rcar_i2c_write(struct rcar_i2c_priv *priv, int reg, u32 val)
{
writel(val, priv->io + reg);
}
static u32 rcar_i2c_read(struct rcar_i2c_priv *priv, int reg)
{
return readl(priv->io + reg);
}
static void rcar_i2c_init(struct rcar_i2c_priv *priv)
{
/*
* reset slave mode.
* slave mode is not used on this driver
*/
rcar_i2c_write(priv, ICSIER, 0);
rcar_i2c_write(priv, ICSAR, 0);
rcar_i2c_write(priv, ICSCR, 0);
rcar_i2c_write(priv, ICSSR, 0);
/* reset master mode */
rcar_i2c_write(priv, ICMIER, 0);
rcar_i2c_write(priv, ICMCR, 0);
rcar_i2c_write(priv, ICMSR, 0);
rcar_i2c_write(priv, ICMAR, 0);
}
static void rcar_i2c_irq_mask(struct rcar_i2c_priv *priv, int open)
{
u32 val = MNRE | MALE | MSTE | MATE; /* default */
switch (open) {
case RCAR_IRQ_OPEN_FOR_SEND:
val |= MDEE; /* default + send */
break;
case RCAR_IRQ_OPEN_FOR_RECV:
val |= MDRE; /* default + read */
break;
case RCAR_IRQ_OPEN_FOR_STOP:
val = MSTE; /* stop irq only */
break;
case RCAR_IRQ_CLOSE:
default:
val = 0; /* all close */
break;
}
rcar_i2c_write(priv, ICMIER, val);
}
static void rcar_i2c_set_addr(struct rcar_i2c_priv *priv, u32 recv)
{
rcar_i2c_write(priv, ICMAR, (priv->msg->addr << 1) | recv);
}
/*
* bus control functions
*/
static int rcar_i2c_bus_barrier(struct rcar_i2c_priv *priv)
{
int i;
for (i = 0; i < LOOP_TIMEOUT; i++) {
/* make sure that bus is not busy */
if (!(rcar_i2c_read(priv, ICMCR) & FSDA))
return 0;
udelay(1);
}
return -EBUSY;
}
static void rcar_i2c_bus_phase(struct rcar_i2c_priv *priv, int phase)
{
switch (phase) {
case RCAR_BUS_PHASE_ADDR:
rcar_i2c_write(priv, ICMCR, MDBS | MIE | ESG);
break;
case RCAR_BUS_PHASE_DATA:
rcar_i2c_write(priv, ICMCR, MDBS | MIE);
break;
case RCAR_BUS_PHASE_STOP:
rcar_i2c_write(priv, ICMCR, MDBS | MIE | FSB);
break;
}
}
/*
* clock function
*/
static int rcar_i2c_clock_calculate(struct rcar_i2c_priv *priv,
u32 bus_speed,
struct device *dev)
{
struct clk *clkp = clk_get(NULL, "peripheral_clk");
u32 scgd, cdf;
u32 round, ick;
u32 scl;
if (!clkp) {
dev_err(dev, "there is no peripheral_clk\n");
return -EIO;
}
/*
* calculate SCL clock
* see
* ICCCR
*
* ick = clkp / (1 + CDF)
* SCL = ick / (20 + SCGD * 8 + F[(ticf + tr + intd) * ick])
*
* ick : I2C internal clock < 20 MHz
* ticf : I2C SCL falling time = 35 ns here
* tr : I2C SCL rising time = 200 ns here
* intd : LSI internal delay = 50 ns here
* clkp : peripheral_clk
* F[] : integer up-valuation
*/
for (cdf = 0; cdf < 4; cdf++) {
ick = clk_get_rate(clkp) / (1 + cdf);
if (ick < 20000000)
goto ick_find;
}
dev_err(dev, "there is no best CDF\n");
return -EIO;
ick_find:
/*
* it is impossible to calculate large scale
* number on u32. separate it
*
* F[(ticf + tr + intd) * ick]
* = F[(35 + 200 + 50)ns * ick]
* = F[285 * ick / 1000000000]
* = F[(ick / 1000000) * 285 / 1000]
*/
round = (ick + 500000) / 1000000 * 285;
round = (round + 500) / 1000;
/*
* SCL = ick / (20 + SCGD * 8 + F[(ticf + tr + intd) * ick])
*
* Calculation result (= SCL) should be less than
* bus_speed for hardware safety
*/
for (scgd = 0; scgd < 0x40; scgd++) {
scl = ick / (20 + (scgd * 8) + round);
if (scl <= bus_speed)
goto scgd_find;
}
dev_err(dev, "it is impossible to calculate best SCL\n");
return -EIO;
scgd_find:
dev_dbg(dev, "clk %d/%d(%lu), round %u, CDF:0x%x, SCGD: 0x%x\n",
scl, bus_speed, clk_get_rate(clkp), round, cdf, scgd);
/*
* keep icccr value
*/
priv->icccr = (scgd << 2 | cdf);
return 0;
}
static void rcar_i2c_clock_start(struct rcar_i2c_priv *priv)
{
rcar_i2c_write(priv, ICCCR, priv->icccr);
}
/*
* status functions
*/
static u32 rcar_i2c_status_get(struct rcar_i2c_priv *priv)
{
return rcar_i2c_read(priv, ICMSR);
}
#define rcar_i2c_status_clear(priv) rcar_i2c_status_bit_clear(priv, 0xffffffff)
static void rcar_i2c_status_bit_clear(struct rcar_i2c_priv *priv, u32 bit)
{
rcar_i2c_write(priv, ICMSR, ~bit);
}
/*
* recv/send functions
*/
static int rcar_i2c_recv(struct rcar_i2c_priv *priv)
{
rcar_i2c_set_addr(priv, 1);
rcar_i2c_status_clear(priv);
rcar_i2c_bus_phase(priv, RCAR_BUS_PHASE_ADDR);
rcar_i2c_irq_mask(priv, RCAR_IRQ_OPEN_FOR_RECV);
return 0;
}
static int rcar_i2c_send(struct rcar_i2c_priv *priv)
{
int ret;
/*
* It should check bus status when send case
*/
ret = rcar_i2c_bus_barrier(priv);
if (ret < 0)
return ret;
rcar_i2c_set_addr(priv, 0);
rcar_i2c_status_clear(priv);
rcar_i2c_bus_phase(priv, RCAR_BUS_PHASE_ADDR);
rcar_i2c_irq_mask(priv, RCAR_IRQ_OPEN_FOR_SEND);
return 0;
}
#define rcar_i2c_send_restart(priv) rcar_i2c_status_bit_clear(priv, (MAT | MDE))
#define rcar_i2c_recv_restart(priv) rcar_i2c_status_bit_clear(priv, (MAT | MDR))
/*
* interrupt functions
*/
static int rcar_i2c_irq_send(struct rcar_i2c_priv *priv, u32 msr)
{
struct i2c_msg *msg = priv->msg;
/*
* FIXME
* sometimes, unknown interrupt happened.
* Do nothing
*/
if (!(msr & MDE))
return 0;
/*
* If address transfer phase finished,
* goto data phase.
*/
if (msr & MAT)
rcar_i2c_bus_phase(priv, RCAR_BUS_PHASE_DATA);
if (priv->pos < msg->len) {
/*
* Prepare next data to ICRXTX register.
* This data will go to _SHIFT_ register.
*
* *
* [ICRXTX] -> [SHIFT] -> [I2C bus]
*/
rcar_i2c_write(priv, ICRXTX, msg->buf[priv->pos]);
priv->pos++;
} else {
/*
* The last data was pushed to ICRXTX on _PREV_ empty irq.
* It is on _SHIFT_ register, and will sent to I2C bus.
*
* *
* [ICRXTX] -> [SHIFT] -> [I2C bus]
*/
if (priv->flags & ID_LAST_MSG)
/*
* If current msg is the _LAST_ msg,
* prepare stop condition here.
* ID_DONE will be set on STOP irq.
*/
rcar_i2c_bus_phase(priv, RCAR_BUS_PHASE_STOP);
else
/*
* If current msg is _NOT_ last msg,
* it doesn't call stop phase.
* thus, there is no STOP irq.
* return ID_DONE here.
*/
return ID_DONE;
}
rcar_i2c_send_restart(priv);
return 0;
}
static int rcar_i2c_irq_recv(struct rcar_i2c_priv *priv, u32 msr)
{
struct i2c_msg *msg = priv->msg;
/*
* FIXME
* sometimes, unknown interrupt happened.
* Do nothing
*/
if (!(msr & MDR))
return 0;
if (msr & MAT) {
/*
* Address transfer phase finished,
* but, there is no data at this point.
* Do nothing.
*/
} else if (priv->pos < msg->len) {
/*
* get received data
*/
msg->buf[priv->pos] = rcar_i2c_read(priv, ICRXTX);
priv->pos++;
}
/*
* If next received data is the _LAST_,
* go to STOP phase,
* otherwise, go to DATA phase.
*/
if (priv->pos + 1 >= msg->len)
rcar_i2c_bus_phase(priv, RCAR_BUS_PHASE_STOP);
else
rcar_i2c_bus_phase(priv, RCAR_BUS_PHASE_DATA);
rcar_i2c_recv_restart(priv);
return 0;
}
static irqreturn_t rcar_i2c_irq(int irq, void *ptr)
{
struct rcar_i2c_priv *priv = ptr;
struct device *dev = rcar_i2c_priv_to_dev(priv);
u32 msr;
/*-------------- spin lock -----------------*/
spin_lock(&priv->lock);
msr = rcar_i2c_status_get(priv);
/*
* Arbitration lost
*/
if (msr & MAL) {
/*
* CAUTION
*
* When arbitration lost, device become _slave_ mode.
*/
dev_dbg(dev, "Arbitration Lost\n");
rcar_i2c_flags_set(priv, (ID_DONE | ID_ARBLOST));
goto out;
}
/*
* Stop
*/
if (msr & MST) {
dev_dbg(dev, "Stop\n");
rcar_i2c_flags_set(priv, ID_DONE);
goto out;
}
/*
* Nack
*/
if (msr & MNR) {
dev_dbg(dev, "Nack\n");
/* go to stop phase */
rcar_i2c_bus_phase(priv, RCAR_BUS_PHASE_STOP);
rcar_i2c_irq_mask(priv, RCAR_IRQ_OPEN_FOR_STOP);
rcar_i2c_flags_set(priv, ID_NACK);
goto out;
}
/*
* recv/send
*/
if (rcar_i2c_is_recv(priv))
rcar_i2c_flags_set(priv, rcar_i2c_irq_recv(priv, msr));
else
rcar_i2c_flags_set(priv, rcar_i2c_irq_send(priv, msr));
out:
if (rcar_i2c_flags_has(priv, ID_DONE)) {
rcar_i2c_irq_mask(priv, RCAR_IRQ_CLOSE);
rcar_i2c_status_clear(priv);
wake_up(&priv->wait);
}
spin_unlock(&priv->lock);
/*-------------- spin unlock -----------------*/
return IRQ_HANDLED;
}
static int rcar_i2c_master_xfer(struct i2c_adapter *adap,
struct i2c_msg *msgs,
int num)
{
struct rcar_i2c_priv *priv = i2c_get_adapdata(adap);
struct device *dev = rcar_i2c_priv_to_dev(priv);
unsigned long flags;
int i, ret, timeout;
pm_runtime_get_sync(dev);
/*-------------- spin lock -----------------*/
spin_lock_irqsave(&priv->lock, flags);
rcar_i2c_init(priv);
rcar_i2c_clock_start(priv);
spin_unlock_irqrestore(&priv->lock, flags);
/*-------------- spin unlock -----------------*/
ret = -EINVAL;
for (i = 0; i < num; i++) {
/*-------------- spin lock -----------------*/
spin_lock_irqsave(&priv->lock, flags);
/* init each data */
priv->msg = &msgs[i];
priv->pos = 0;
priv->flags = 0;
if (priv->msg == &msgs[num - 1])
rcar_i2c_flags_set(priv, ID_LAST_MSG);
/* start send/recv */
if (rcar_i2c_is_recv(priv))
ret = rcar_i2c_recv(priv);
else
ret = rcar_i2c_send(priv);
spin_unlock_irqrestore(&priv->lock, flags);
/*-------------- spin unlock -----------------*/
if (ret < 0)
break;
/*
* wait result
*/
timeout = wait_event_timeout(priv->wait,
rcar_i2c_flags_has(priv, ID_DONE),
5 * HZ);
if (!timeout) {
ret = -ETIMEDOUT;
break;
}
/*
* error handling
*/
if (rcar_i2c_flags_has(priv, ID_NACK)) {
ret = -EREMOTEIO;
break;
}
if (rcar_i2c_flags_has(priv, ID_ARBLOST)) {
ret = -EAGAIN;
break;
}
if (rcar_i2c_flags_has(priv, ID_IOERROR)) {
ret = -EIO;
break;
}
ret = i + 1; /* The number of transfer */
}
pm_runtime_put(dev);
if (ret < 0)
dev_err(dev, "error %d : %x\n", ret, priv->flags);
return ret;
}
static u32 rcar_i2c_func(struct i2c_adapter *adap)
{
return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
}
static const struct i2c_algorithm rcar_i2c_algo = {
.master_xfer = rcar_i2c_master_xfer,
.functionality = rcar_i2c_func,
};
static int rcar_i2c_probe(struct platform_device *pdev)
{
struct i2c_rcar_platform_data *pdata = pdev->dev.platform_data;
struct rcar_i2c_priv *priv;
struct i2c_adapter *adap;
struct resource *res;
struct device *dev = &pdev->dev;
u32 bus_speed;
int ret;
priv = devm_kzalloc(dev, sizeof(struct rcar_i2c_priv), GFP_KERNEL);
if (!priv) {
dev_err(dev, "no mem for private data\n");
return -ENOMEM;
}
bus_speed = 100000; /* default 100 kHz */
if (pdata && pdata->bus_speed)
bus_speed = pdata->bus_speed;
ret = rcar_i2c_clock_calculate(priv, bus_speed, dev);
if (ret < 0)
return ret;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
priv->io = devm_ioremap_resource(dev, res);
if (IS_ERR(priv->io))
return PTR_ERR(priv->io);
priv->irq = platform_get_irq(pdev, 0);
init_waitqueue_head(&priv->wait);
spin_lock_init(&priv->lock);
adap = &priv->adap;
adap->nr = pdev->id;
adap->algo = &rcar_i2c_algo;
adap->class = I2C_CLASS_HWMON | I2C_CLASS_SPD;
adap->retries = 3;
adap->dev.parent = dev;
i2c_set_adapdata(adap, priv);
strlcpy(adap->name, pdev->name, sizeof(adap->name));
ret = devm_request_irq(dev, priv->irq, rcar_i2c_irq, 0,
dev_name(dev), priv);
if (ret < 0) {
dev_err(dev, "cannot get irq %d\n", priv->irq);
return ret;
}
ret = i2c_add_numbered_adapter(adap);
if (ret < 0) {
dev_err(dev, "reg adap failed: %d\n", ret);
return ret;
}
pm_runtime_enable(dev);
platform_set_drvdata(pdev, priv);
dev_info(dev, "probed\n");
return 0;
}
static int rcar_i2c_remove(struct platform_device *pdev)
{
struct rcar_i2c_priv *priv = platform_get_drvdata(pdev);
struct device *dev = &pdev->dev;
i2c_del_adapter(&priv->adap);
pm_runtime_disable(dev);
return 0;
}
static struct platform_driver rcar_i2c_driver = {
.driver = {
.name = "i2c-rcar",
.owner = THIS_MODULE,
},
.probe = rcar_i2c_probe,
.remove = rcar_i2c_remove,
};
module_platform_driver(rcar_i2c_driver);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Renesas R-Car I2C bus driver");
MODULE_AUTHOR("Kuninori Morimoto <kuninori.morimoto.gx@renesas.com>");
| gpl-2.0 |
y-sensei/phyLinux | drivers/acpi/pci_root.c | 68 | 18158 | /*
* pci_root.c - ACPI PCI Root Bridge Driver ($Revision: 40 $)
*
* Copyright (C) 2001, 2002 Andy Grover <andrew.grover@intel.com>
* Copyright (C) 2001, 2002 Paul Diefenbaugh <paul.s.diefenbaugh@intel.com>
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/mutex.h>
#include <linux/pm.h>
#include <linux/pm_runtime.h>
#include <linux/pci.h>
#include <linux/pci-acpi.h>
#include <linux/pci-aspm.h>
#include <linux/dmar.h>
#include <linux/acpi.h>
#include <linux/slab.h>
#include <linux/dmi.h>
#include <acpi/apei.h> /* for acpi_hest_init() */
#include "internal.h"
#define _COMPONENT ACPI_PCI_COMPONENT
ACPI_MODULE_NAME("pci_root");
#define ACPI_PCI_ROOT_CLASS "pci_bridge"
#define ACPI_PCI_ROOT_DEVICE_NAME "PCI Root Bridge"
static int acpi_pci_root_add(struct acpi_device *device,
const struct acpi_device_id *not_used);
static void acpi_pci_root_remove(struct acpi_device *device);
static int acpi_pci_root_scan_dependent(struct acpi_device *adev)
{
acpiphp_check_host_bridge(adev);
return 0;
}
#define ACPI_PCIE_REQ_SUPPORT (OSC_PCI_EXT_CONFIG_SUPPORT \
| OSC_PCI_ASPM_SUPPORT \
| OSC_PCI_CLOCK_PM_SUPPORT \
| OSC_PCI_MSI_SUPPORT)
static const struct acpi_device_id root_device_ids[] = {
{"PNP0A03", 0},
{"", 0},
};
static struct acpi_scan_handler pci_root_handler = {
.ids = root_device_ids,
.attach = acpi_pci_root_add,
.detach = acpi_pci_root_remove,
.hotplug = {
.enabled = true,
.scan_dependent = acpi_pci_root_scan_dependent,
},
};
static DEFINE_MUTEX(osc_lock);
/**
* acpi_is_root_bridge - determine whether an ACPI CA node is a PCI root bridge
* @handle - the ACPI CA node in question.
*
* Note: we could make this API take a struct acpi_device * instead, but
* for now, it's more convenient to operate on an acpi_handle.
*/
int acpi_is_root_bridge(acpi_handle handle)
{
int ret;
struct acpi_device *device;
ret = acpi_bus_get_device(handle, &device);
if (ret)
return 0;
ret = acpi_match_device_ids(device, root_device_ids);
if (ret)
return 0;
else
return 1;
}
EXPORT_SYMBOL_GPL(acpi_is_root_bridge);
static acpi_status
get_root_bridge_busnr_callback(struct acpi_resource *resource, void *data)
{
struct resource *res = data;
struct acpi_resource_address64 address;
acpi_status status;
status = acpi_resource_to_address64(resource, &address);
if (ACPI_FAILURE(status))
return AE_OK;
if ((address.address_length > 0) &&
(address.resource_type == ACPI_BUS_NUMBER_RANGE)) {
res->start = address.minimum;
res->end = address.minimum + address.address_length - 1;
}
return AE_OK;
}
static acpi_status try_get_root_bridge_busnr(acpi_handle handle,
struct resource *res)
{
acpi_status status;
res->start = -1;
status =
acpi_walk_resources(handle, METHOD_NAME__CRS,
get_root_bridge_busnr_callback, res);
if (ACPI_FAILURE(status))
return status;
if (res->start == -1)
return AE_ERROR;
return AE_OK;
}
struct pci_osc_bit_struct {
u32 bit;
char *desc;
};
static struct pci_osc_bit_struct pci_osc_support_bit[] = {
{ OSC_PCI_EXT_CONFIG_SUPPORT, "ExtendedConfig" },
{ OSC_PCI_ASPM_SUPPORT, "ASPM" },
{ OSC_PCI_CLOCK_PM_SUPPORT, "ClockPM" },
{ OSC_PCI_SEGMENT_GROUPS_SUPPORT, "Segments" },
{ OSC_PCI_MSI_SUPPORT, "MSI" },
};
static struct pci_osc_bit_struct pci_osc_control_bit[] = {
{ OSC_PCI_EXPRESS_NATIVE_HP_CONTROL, "PCIeHotplug" },
{ OSC_PCI_SHPC_NATIVE_HP_CONTROL, "SHPCHotplug" },
{ OSC_PCI_EXPRESS_PME_CONTROL, "PME" },
{ OSC_PCI_EXPRESS_AER_CONTROL, "AER" },
{ OSC_PCI_EXPRESS_CAPABILITY_CONTROL, "PCIeCapability" },
};
static void decode_osc_bits(struct acpi_pci_root *root, char *msg, u32 word,
struct pci_osc_bit_struct *table, int size)
{
char buf[80];
int i, len = 0;
struct pci_osc_bit_struct *entry;
buf[0] = '\0';
for (i = 0, entry = table; i < size; i++, entry++)
if (word & entry->bit)
len += snprintf(buf + len, sizeof(buf) - len, "%s%s",
len ? " " : "", entry->desc);
dev_info(&root->device->dev, "_OSC: %s [%s]\n", msg, buf);
}
static void decode_osc_support(struct acpi_pci_root *root, char *msg, u32 word)
{
decode_osc_bits(root, msg, word, pci_osc_support_bit,
ARRAY_SIZE(pci_osc_support_bit));
}
static void decode_osc_control(struct acpi_pci_root *root, char *msg, u32 word)
{
decode_osc_bits(root, msg, word, pci_osc_control_bit,
ARRAY_SIZE(pci_osc_control_bit));
}
static u8 pci_osc_uuid_str[] = "33DB4D5B-1FF7-401C-9657-7441C03DD766";
static acpi_status acpi_pci_run_osc(acpi_handle handle,
const u32 *capbuf, u32 *retval)
{
struct acpi_osc_context context = {
.uuid_str = pci_osc_uuid_str,
.rev = 1,
.cap.length = 12,
.cap.pointer = (void *)capbuf,
};
acpi_status status;
status = acpi_run_osc(handle, &context);
if (ACPI_SUCCESS(status)) {
*retval = *((u32 *)(context.ret.pointer + 8));
kfree(context.ret.pointer);
}
return status;
}
static acpi_status acpi_pci_query_osc(struct acpi_pci_root *root,
u32 support,
u32 *control)
{
acpi_status status;
u32 result, capbuf[3];
support &= OSC_PCI_SUPPORT_MASKS;
support |= root->osc_support_set;
capbuf[OSC_QUERY_DWORD] = OSC_QUERY_ENABLE;
capbuf[OSC_SUPPORT_DWORD] = support;
if (control) {
*control &= OSC_PCI_CONTROL_MASKS;
capbuf[OSC_CONTROL_DWORD] = *control | root->osc_control_set;
} else {
/* Run _OSC query only with existing controls. */
capbuf[OSC_CONTROL_DWORD] = root->osc_control_set;
}
status = acpi_pci_run_osc(root->device->handle, capbuf, &result);
if (ACPI_SUCCESS(status)) {
root->osc_support_set = support;
if (control)
*control = result;
}
return status;
}
static acpi_status acpi_pci_osc_support(struct acpi_pci_root *root, u32 flags)
{
acpi_status status;
mutex_lock(&osc_lock);
status = acpi_pci_query_osc(root, flags, NULL);
mutex_unlock(&osc_lock);
return status;
}
struct acpi_pci_root *acpi_pci_find_root(acpi_handle handle)
{
struct acpi_pci_root *root;
struct acpi_device *device;
if (acpi_bus_get_device(handle, &device) ||
acpi_match_device_ids(device, root_device_ids))
return NULL;
root = acpi_driver_data(device);
return root;
}
EXPORT_SYMBOL_GPL(acpi_pci_find_root);
struct acpi_handle_node {
struct list_head node;
acpi_handle handle;
};
/**
* acpi_get_pci_dev - convert ACPI CA handle to struct pci_dev
* @handle: the handle in question
*
* Given an ACPI CA handle, the desired PCI device is located in the
* list of PCI devices.
*
* If the device is found, its reference count is increased and this
* function returns a pointer to its data structure. The caller must
* decrement the reference count by calling pci_dev_put().
* If no device is found, %NULL is returned.
*/
struct pci_dev *acpi_get_pci_dev(acpi_handle handle)
{
int dev, fn;
unsigned long long adr;
acpi_status status;
acpi_handle phandle;
struct pci_bus *pbus;
struct pci_dev *pdev = NULL;
struct acpi_handle_node *node, *tmp;
struct acpi_pci_root *root;
LIST_HEAD(device_list);
/*
* Walk up the ACPI CA namespace until we reach a PCI root bridge.
*/
phandle = handle;
while (!acpi_is_root_bridge(phandle)) {
node = kzalloc(sizeof(struct acpi_handle_node), GFP_KERNEL);
if (!node)
goto out;
INIT_LIST_HEAD(&node->node);
node->handle = phandle;
list_add(&node->node, &device_list);
status = acpi_get_parent(phandle, &phandle);
if (ACPI_FAILURE(status))
goto out;
}
root = acpi_pci_find_root(phandle);
if (!root)
goto out;
pbus = root->bus;
/*
* Now, walk back down the PCI device tree until we return to our
* original handle. Assumes that everything between the PCI root
* bridge and the device we're looking for must be a P2P bridge.
*/
list_for_each_entry(node, &device_list, node) {
acpi_handle hnd = node->handle;
status = acpi_evaluate_integer(hnd, "_ADR", NULL, &adr);
if (ACPI_FAILURE(status))
goto out;
dev = (adr >> 16) & 0xffff;
fn = adr & 0xffff;
pdev = pci_get_slot(pbus, PCI_DEVFN(dev, fn));
if (!pdev || hnd == handle)
break;
pbus = pdev->subordinate;
pci_dev_put(pdev);
/*
* This function may be called for a non-PCI device that has a
* PCI parent (eg. a disk under a PCI SATA controller). In that
* case pdev->subordinate will be NULL for the parent.
*/
if (!pbus) {
dev_dbg(&pdev->dev, "Not a PCI-to-PCI bridge\n");
pdev = NULL;
break;
}
}
out:
list_for_each_entry_safe(node, tmp, &device_list, node)
kfree(node);
return pdev;
}
EXPORT_SYMBOL_GPL(acpi_get_pci_dev);
/**
* acpi_pci_osc_control_set - Request control of PCI root _OSC features.
* @handle: ACPI handle of a PCI root bridge (or PCIe Root Complex).
* @mask: Mask of _OSC bits to request control of, place to store control mask.
* @req: Mask of _OSC bits the control of is essential to the caller.
*
* Run _OSC query for @mask and if that is successful, compare the returned
* mask of control bits with @req. If all of the @req bits are set in the
* returned mask, run _OSC request for it.
*
* The variable at the @mask address may be modified regardless of whether or
* not the function returns success. On success it will contain the mask of
* _OSC bits the BIOS has granted control of, but its contents are meaningless
* on failure.
**/
acpi_status acpi_pci_osc_control_set(acpi_handle handle, u32 *mask, u32 req)
{
struct acpi_pci_root *root;
acpi_status status = AE_OK;
u32 ctrl, capbuf[3];
if (!mask)
return AE_BAD_PARAMETER;
ctrl = *mask & OSC_PCI_CONTROL_MASKS;
if ((ctrl & req) != req)
return AE_TYPE;
root = acpi_pci_find_root(handle);
if (!root)
return AE_NOT_EXIST;
mutex_lock(&osc_lock);
*mask = ctrl | root->osc_control_set;
/* No need to evaluate _OSC if the control was already granted. */
if ((root->osc_control_set & ctrl) == ctrl)
goto out;
/* Need to check the available controls bits before requesting them. */
while (*mask) {
status = acpi_pci_query_osc(root, root->osc_support_set, mask);
if (ACPI_FAILURE(status))
goto out;
if (ctrl == *mask)
break;
decode_osc_control(root, "platform does not support",
ctrl & ~(*mask));
ctrl = *mask;
}
if ((ctrl & req) != req) {
decode_osc_control(root, "not requesting control; platform does not support",
req & ~(ctrl));
status = AE_SUPPORT;
goto out;
}
capbuf[OSC_QUERY_DWORD] = 0;
capbuf[OSC_SUPPORT_DWORD] = root->osc_support_set;
capbuf[OSC_CONTROL_DWORD] = ctrl;
status = acpi_pci_run_osc(handle, capbuf, mask);
if (ACPI_SUCCESS(status))
root->osc_control_set = *mask;
out:
mutex_unlock(&osc_lock);
return status;
}
EXPORT_SYMBOL(acpi_pci_osc_control_set);
static void negotiate_os_control(struct acpi_pci_root *root, int *no_aspm,
int *clear_aspm)
{
u32 support, control, requested;
acpi_status status;
struct acpi_device *device = root->device;
acpi_handle handle = device->handle;
/*
* Apple always return failure on _OSC calls when _OSI("Darwin") has
* been called successfully. We know the feature set supported by the
* platform, so avoid calling _OSC at all
*/
if (dmi_match(DMI_SYS_VENDOR, "Apple Inc.")) {
root->osc_control_set = ~OSC_PCI_EXPRESS_PME_CONTROL;
decode_osc_control(root, "OS assumes control of",
root->osc_control_set);
return;
}
/*
* All supported architectures that use ACPI have support for
* PCI domains, so we indicate this in _OSC support capabilities.
*/
support = OSC_PCI_SEGMENT_GROUPS_SUPPORT;
if (pci_ext_cfg_avail())
support |= OSC_PCI_EXT_CONFIG_SUPPORT;
if (pcie_aspm_support_enabled())
support |= OSC_PCI_ASPM_SUPPORT | OSC_PCI_CLOCK_PM_SUPPORT;
if (pci_msi_enabled())
support |= OSC_PCI_MSI_SUPPORT;
decode_osc_support(root, "OS supports", support);
status = acpi_pci_osc_support(root, support);
if (ACPI_FAILURE(status)) {
dev_info(&device->dev, "_OSC failed (%s); disabling ASPM\n",
acpi_format_exception(status));
*no_aspm = 1;
return;
}
if (pcie_ports_disabled) {
dev_info(&device->dev, "PCIe port services disabled; not requesting _OSC control\n");
return;
}
if ((support & ACPI_PCIE_REQ_SUPPORT) != ACPI_PCIE_REQ_SUPPORT) {
decode_osc_support(root, "not requesting OS control; OS requires",
ACPI_PCIE_REQ_SUPPORT);
return;
}
control = OSC_PCI_EXPRESS_CAPABILITY_CONTROL
| OSC_PCI_EXPRESS_NATIVE_HP_CONTROL
| OSC_PCI_EXPRESS_PME_CONTROL;
if (pci_aer_available()) {
if (aer_acpi_firmware_first())
dev_info(&device->dev,
"PCIe AER handled by firmware\n");
else
control |= OSC_PCI_EXPRESS_AER_CONTROL;
}
requested = control;
status = acpi_pci_osc_control_set(handle, &control,
OSC_PCI_EXPRESS_CAPABILITY_CONTROL);
if (ACPI_SUCCESS(status)) {
decode_osc_control(root, "OS now controls", control);
if (acpi_gbl_FADT.boot_flags & ACPI_FADT_NO_ASPM) {
/*
* We have ASPM control, but the FADT indicates
* that it's unsupported. Clear it.
*/
*clear_aspm = 1;
}
} else {
decode_osc_control(root, "OS requested", requested);
decode_osc_control(root, "platform willing to grant", control);
dev_info(&device->dev, "_OSC failed (%s); disabling ASPM\n",
acpi_format_exception(status));
/*
* We want to disable ASPM here, but aspm_disabled
* needs to remain in its state from boot so that we
* properly handle PCIe 1.1 devices. So we set this
* flag here, to defer the action until after the ACPI
* root scan.
*/
*no_aspm = 1;
}
}
static int acpi_pci_root_add(struct acpi_device *device,
const struct acpi_device_id *not_used)
{
unsigned long long segment, bus;
acpi_status status;
int result;
struct acpi_pci_root *root;
acpi_handle handle = device->handle;
int no_aspm = 0, clear_aspm = 0;
bool hotadd = system_state != SYSTEM_BOOTING;
root = kzalloc(sizeof(struct acpi_pci_root), GFP_KERNEL);
if (!root)
return -ENOMEM;
segment = 0;
status = acpi_evaluate_integer(handle, METHOD_NAME__SEG, NULL,
&segment);
if (ACPI_FAILURE(status) && status != AE_NOT_FOUND) {
dev_err(&device->dev, "can't evaluate _SEG\n");
result = -ENODEV;
goto end;
}
/* Check _CRS first, then _BBN. If no _BBN, default to zero. */
root->secondary.flags = IORESOURCE_BUS;
status = try_get_root_bridge_busnr(handle, &root->secondary);
if (ACPI_FAILURE(status)) {
/*
* We need both the start and end of the downstream bus range
* to interpret _CBA (MMCONFIG base address), so it really is
* supposed to be in _CRS. If we don't find it there, all we
* can do is assume [_BBN-0xFF] or [0-0xFF].
*/
root->secondary.end = 0xFF;
dev_warn(&device->dev,
FW_BUG "no secondary bus range in _CRS\n");
status = acpi_evaluate_integer(handle, METHOD_NAME__BBN,
NULL, &bus);
if (ACPI_SUCCESS(status))
root->secondary.start = bus;
else if (status == AE_NOT_FOUND)
root->secondary.start = 0;
else {
dev_err(&device->dev, "can't evaluate _BBN\n");
result = -ENODEV;
goto end;
}
}
root->device = device;
root->segment = segment & 0xFFFF;
strcpy(acpi_device_name(device), ACPI_PCI_ROOT_DEVICE_NAME);
strcpy(acpi_device_class(device), ACPI_PCI_ROOT_CLASS);
device->driver_data = root;
if (hotadd && dmar_device_add(handle)) {
result = -ENXIO;
goto end;
}
pr_info(PREFIX "%s [%s] (domain %04x %pR)\n",
acpi_device_name(device), acpi_device_bid(device),
root->segment, &root->secondary);
root->mcfg_addr = acpi_pci_root_get_mcfg_addr(handle);
negotiate_os_control(root, &no_aspm, &clear_aspm);
/*
* TBD: Need PCI interface for enumeration/configuration of roots.
*/
/*
* Scan the Root Bridge
* --------------------
* Must do this prior to any attempt to bind the root device, as the
* PCI namespace does not get created until this call is made (and
* thus the root bridge's pci_dev does not exist).
*/
root->bus = pci_acpi_scan_root(root);
if (!root->bus) {
dev_err(&device->dev,
"Bus %04x:%02x not present in PCI namespace\n",
root->segment, (unsigned int)root->secondary.start);
device->driver_data = NULL;
result = -ENODEV;
goto remove_dmar;
}
if (clear_aspm) {
dev_info(&device->dev, "Disabling ASPM (FADT indicates it is unsupported)\n");
pcie_clear_aspm(root->bus);
}
if (no_aspm)
pcie_no_aspm();
pci_acpi_add_bus_pm_notifier(device);
if (device->wakeup.flags.run_wake)
device_set_run_wake(root->bus->bridge, true);
if (hotadd) {
pcibios_resource_survey_bus(root->bus);
pci_assign_unassigned_root_bus_resources(root->bus);
}
pci_lock_rescan_remove();
pci_bus_add_devices(root->bus);
pci_unlock_rescan_remove();
return 1;
remove_dmar:
if (hotadd)
dmar_device_remove(handle);
end:
kfree(root);
return result;
}
static void acpi_pci_root_remove(struct acpi_device *device)
{
struct acpi_pci_root *root = acpi_driver_data(device);
pci_lock_rescan_remove();
pci_stop_root_bus(root->bus);
device_set_run_wake(root->bus->bridge, false);
pci_acpi_remove_bus_pm_notifier(device);
pci_remove_root_bus(root->bus);
dmar_device_remove(device->handle);
pci_unlock_rescan_remove();
kfree(root);
}
void __init acpi_pci_root_init(void)
{
acpi_hest_init();
if (acpi_pci_disabled)
return;
pci_acpi_crs_quirks();
acpi_scan_add_handler_with_hotplug(&pci_root_handler, "pci_root");
}
| gpl-2.0 |
ghmajx/asuswrt-merlin | release/src-rt/linux/linux-2.6/arch/i386/kernel/scx200.c | 68 | 3399 | /* linux/arch/i386/kernel/scx200.c
Copyright (c) 2001,2002 Christer Weinigel <wingel@nano-system.com>
National Semiconductor SCx200 support. */
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/mutex.h>
#include <linux/pci.h>
#include <linux/scx200.h>
#include <linux/scx200_gpio.h>
/* Verify that the configuration block really is there */
#define scx200_cb_probe(base) (inw((base) + SCx200_CBA) == (base))
#define NAME "scx200"
MODULE_AUTHOR("Christer Weinigel <wingel@nano-system.com>");
MODULE_DESCRIPTION("NatSemi SCx200 Driver");
MODULE_LICENSE("GPL");
unsigned scx200_gpio_base = 0;
long scx200_gpio_shadow[2];
unsigned scx200_cb_base = 0;
static struct pci_device_id scx200_tbl[] = {
{ PCI_DEVICE(PCI_VENDOR_ID_NS, PCI_DEVICE_ID_NS_SCx200_BRIDGE) },
{ PCI_DEVICE(PCI_VENDOR_ID_NS, PCI_DEVICE_ID_NS_SC1100_BRIDGE) },
{ PCI_DEVICE(PCI_VENDOR_ID_NS, PCI_DEVICE_ID_NS_SCx200_XBUS) },
{ PCI_DEVICE(PCI_VENDOR_ID_NS, PCI_DEVICE_ID_NS_SC1100_XBUS) },
{ },
};
MODULE_DEVICE_TABLE(pci,scx200_tbl);
static int __devinit scx200_probe(struct pci_dev *, const struct pci_device_id *);
static struct pci_driver scx200_pci_driver = {
.name = "scx200",
.id_table = scx200_tbl,
.probe = scx200_probe,
};
static DEFINE_MUTEX(scx200_gpio_config_lock);
static void __devinit scx200_init_shadow(void)
{
int bank;
/* read the current values driven on the GPIO signals */
for (bank = 0; bank < 2; ++bank)
scx200_gpio_shadow[bank] = inl(scx200_gpio_base + 0x10 * bank);
}
static int __devinit scx200_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
{
unsigned base;
if (pdev->device == PCI_DEVICE_ID_NS_SCx200_BRIDGE ||
pdev->device == PCI_DEVICE_ID_NS_SC1100_BRIDGE) {
base = pci_resource_start(pdev, 0);
printk(KERN_INFO NAME ": GPIO base 0x%x\n", base);
if (request_region(base, SCx200_GPIO_SIZE, "NatSemi SCx200 GPIO") == 0) {
printk(KERN_ERR NAME ": can't allocate I/O for GPIOs\n");
return -EBUSY;
}
scx200_gpio_base = base;
scx200_init_shadow();
} else {
/* find the base of the Configuration Block */
if (scx200_cb_probe(SCx200_CB_BASE_FIXED)) {
scx200_cb_base = SCx200_CB_BASE_FIXED;
} else {
pci_read_config_dword(pdev, SCx200_CBA_SCRATCH, &base);
if (scx200_cb_probe(base)) {
scx200_cb_base = base;
} else {
printk(KERN_WARNING NAME ": Configuration Block not found\n");
return -ENODEV;
}
}
printk(KERN_INFO NAME ": Configuration Block base 0x%x\n", scx200_cb_base);
}
return 0;
}
u32 scx200_gpio_configure(unsigned index, u32 mask, u32 bits)
{
u32 config, new_config;
mutex_lock(&scx200_gpio_config_lock);
outl(index, scx200_gpio_base + 0x20);
config = inl(scx200_gpio_base + 0x24);
new_config = (config & mask) | bits;
outl(new_config, scx200_gpio_base + 0x24);
mutex_unlock(&scx200_gpio_config_lock);
return config;
}
static int __init scx200_init(void)
{
printk(KERN_INFO NAME ": NatSemi SCx200 Driver\n");
return pci_register_driver(&scx200_pci_driver);
}
static void __exit scx200_cleanup(void)
{
pci_unregister_driver(&scx200_pci_driver);
release_region(scx200_gpio_base, SCx200_GPIO_SIZE);
}
module_init(scx200_init);
module_exit(scx200_cleanup);
EXPORT_SYMBOL(scx200_gpio_base);
EXPORT_SYMBOL(scx200_gpio_shadow);
EXPORT_SYMBOL(scx200_gpio_configure);
EXPORT_SYMBOL(scx200_cb_base);
| gpl-2.0 |
gripped/xbmc | lib/libmicrohttpd/src/daemon/https/tls/gnutls_cipher_int.c | 68 | 3010 | /*
* Copyright (C) 2000, 2004, 2005 Free Software Foundation
*
* Author: Nikos Mavrogiannopoulos
*
* This file is part of GNUTLS.
*
* The GNUTLS 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA
*
*/
#include <gnutls_int.h>
#include <gnutls_errors.h>
#include <gnutls_cipher_int.h>
#include <gnutls_datum.h>
cipher_hd_t
MHD_gtls_cipher_init (enum MHD_GNUTLS_CipherAlgorithm cipher,
const MHD_gnutls_datum_t * key,
const MHD_gnutls_datum_t * iv)
{
cipher_hd_t ret = NULL;
int err = GC_INVALID_CIPHER; /* doesn't matter */
switch (cipher)
{
case MHD_GNUTLS_CIPHER_AES_128_CBC:
err = MHD_gc_cipher_open (GC_AES128, GC_CBC, &ret);
break;
case MHD_GNUTLS_CIPHER_AES_256_CBC:
err = MHD_gc_cipher_open (GC_AES256, GC_CBC, &ret);
break;
case MHD_GNUTLS_CIPHER_3DES_CBC:
err = MHD_gc_cipher_open (GC_3DES, GC_CBC, &ret);
break;
case MHD_GNUTLS_CIPHER_ARCFOUR_128:
err = MHD_gc_cipher_open (GC_ARCFOUR128, GC_STREAM, &ret);
break;
default:
return NULL;
}
if (err == 0)
{
MHD_gc_cipher_setkey (ret, key->size, (const char *) key->data);
if (iv->data != NULL && iv->size > 0)
MHD_gc_cipher_setiv (ret, iv->size, (const char *) iv->data);
}
else if (cipher != MHD_GNUTLS_CIPHER_NULL)
{
MHD_gnutls_assert ();
MHD__gnutls_x509_log ("Crypto cipher[%d] error: %d\n", cipher, err);
/* FIXME: MHD_gc_strerror */
}
return ret;
}
int
MHD_gtls_cipher_encrypt (cipher_hd_t handle, void *text, int textlen)
{
if (handle != GNUTLS_CIPHER_FAILED)
{
if (MHD_gc_cipher_encrypt_inline (handle, textlen, text) != 0)
{
MHD_gnutls_assert ();
return GNUTLS_E_INTERNAL_ERROR;
}
}
return 0;
}
int
MHD_gtls_cipher_decrypt (cipher_hd_t handle, void *ciphertext,
int ciphertextlen)
{
if (handle != GNUTLS_CIPHER_FAILED)
{
if (MHD_gc_cipher_decrypt_inline (handle, ciphertextlen, ciphertext) !=
0)
{
MHD_gnutls_assert ();
return GNUTLS_E_INTERNAL_ERROR;
}
}
return 0;
}
void
MHD_gnutls_cipher_deinit (cipher_hd_t handle)
{
if (handle != GNUTLS_CIPHER_FAILED)
{
MHD_gc_cipher_close (handle);
}
}
| gpl-2.0 |
crseanpaul/exynos-drm-next | drivers/staging/lustre/lustre/ptlrpc/llog_client.c | 68 | 9862 | /*
* 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) 2003, 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.
*
* lustre/ptlrpc/llog_client.c
*
* remote api for llog - client side
*
* Author: Andreas Dilger <adilger@clusterfs.com>
*/
#define DEBUG_SUBSYSTEM S_LOG
#include <linux/libcfs/libcfs.h>
#include <obd_class.h>
#include <lustre_log.h>
#include <lustre_net.h>
#include <linux/list.h>
#define LLOG_CLIENT_ENTRY(ctxt, imp) do { \
mutex_lock(&ctxt->loc_mutex); \
if (ctxt->loc_imp) { \
imp = class_import_get(ctxt->loc_imp); \
} else { \
CERROR("ctxt->loc_imp == NULL for context idx %d." \
"Unable to complete MDS/OSS recovery," \
"but I'll try again next time. Not fatal.\n", \
ctxt->loc_idx); \
imp = NULL; \
mutex_unlock(&ctxt->loc_mutex); \
return (-EINVAL); \
} \
mutex_unlock(&ctxt->loc_mutex); \
} while(0)
#define LLOG_CLIENT_EXIT(ctxt, imp) do { \
mutex_lock(&ctxt->loc_mutex); \
if (ctxt->loc_imp != imp) \
CWARN("loc_imp has changed from %p to %p\n", \
ctxt->loc_imp, imp); \
class_import_put(imp); \
mutex_unlock(&ctxt->loc_mutex); \
} while(0)
/* This is a callback from the llog_* functions.
* Assumes caller has already pushed us into the kernel context. */
static int llog_client_open(const struct lu_env *env,
struct llog_handle *lgh, struct llog_logid *logid,
char *name, enum llog_open_param open_param)
{
struct obd_import *imp;
struct llogd_body *body;
struct llog_ctxt *ctxt = lgh->lgh_ctxt;
struct ptlrpc_request *req = NULL;
int rc;
ENTRY;
LLOG_CLIENT_ENTRY(ctxt, imp);
/* client cannot create llog */
LASSERTF(open_param != LLOG_OPEN_NEW, "%#x\n", open_param);
LASSERT(lgh);
req = ptlrpc_request_alloc(imp, &RQF_LLOG_ORIGIN_HANDLE_CREATE);
if (req == NULL)
GOTO(out, rc = -ENOMEM);
if (name)
req_capsule_set_size(&req->rq_pill, &RMF_NAME, RCL_CLIENT,
strlen(name) + 1);
rc = ptlrpc_request_pack(req, LUSTRE_LOG_VERSION,
LLOG_ORIGIN_HANDLE_CREATE);
if (rc) {
ptlrpc_request_free(req);
req = NULL;
GOTO(out, rc);
}
ptlrpc_request_set_replen(req);
body = req_capsule_client_get(&req->rq_pill, &RMF_LLOGD_BODY);
if (logid)
body->lgd_logid = *logid;
body->lgd_ctxt_idx = ctxt->loc_idx - 1;
if (name) {
char *tmp;
tmp = req_capsule_client_sized_get(&req->rq_pill, &RMF_NAME,
strlen(name) + 1);
LASSERT(tmp);
strcpy(tmp, name);
}
rc = ptlrpc_queue_wait(req);
if (rc)
GOTO(out, rc);
body = req_capsule_server_get(&req->rq_pill, &RMF_LLOGD_BODY);
if (body == NULL)
GOTO(out, rc = -EFAULT);
lgh->lgh_id = body->lgd_logid;
lgh->lgh_ctxt = ctxt;
EXIT;
out:
LLOG_CLIENT_EXIT(ctxt, imp);
ptlrpc_req_finished(req);
return rc;
}
static int llog_client_destroy(const struct lu_env *env,
struct llog_handle *loghandle)
{
struct obd_import *imp;
struct ptlrpc_request *req = NULL;
struct llogd_body *body;
int rc;
ENTRY;
LLOG_CLIENT_ENTRY(loghandle->lgh_ctxt, imp);
req = ptlrpc_request_alloc_pack(imp, &RQF_LLOG_ORIGIN_HANDLE_DESTROY,
LUSTRE_LOG_VERSION,
LLOG_ORIGIN_HANDLE_DESTROY);
if (req == NULL)
GOTO(err_exit, rc =-ENOMEM);
body = req_capsule_client_get(&req->rq_pill, &RMF_LLOGD_BODY);
body->lgd_logid = loghandle->lgh_id;
body->lgd_llh_flags = loghandle->lgh_hdr->llh_flags;
if (!(body->lgd_llh_flags & LLOG_F_IS_PLAIN))
CERROR("%s: wrong llog flags %x\n", imp->imp_obd->obd_name,
body->lgd_llh_flags);
ptlrpc_request_set_replen(req);
rc = ptlrpc_queue_wait(req);
ptlrpc_req_finished(req);
err_exit:
LLOG_CLIENT_EXIT(loghandle->lgh_ctxt, imp);
RETURN(rc);
}
static int llog_client_next_block(const struct lu_env *env,
struct llog_handle *loghandle,
int *cur_idx, int next_idx,
__u64 *cur_offset, void *buf, int len)
{
struct obd_import *imp;
struct ptlrpc_request *req = NULL;
struct llogd_body *body;
void *ptr;
int rc;
ENTRY;
LLOG_CLIENT_ENTRY(loghandle->lgh_ctxt, imp);
req = ptlrpc_request_alloc_pack(imp, &RQF_LLOG_ORIGIN_HANDLE_NEXT_BLOCK,
LUSTRE_LOG_VERSION,
LLOG_ORIGIN_HANDLE_NEXT_BLOCK);
if (req == NULL)
GOTO(err_exit, rc =-ENOMEM);
body = req_capsule_client_get(&req->rq_pill, &RMF_LLOGD_BODY);
body->lgd_logid = loghandle->lgh_id;
body->lgd_ctxt_idx = loghandle->lgh_ctxt->loc_idx - 1;
body->lgd_llh_flags = loghandle->lgh_hdr->llh_flags;
body->lgd_index = next_idx;
body->lgd_saved_index = *cur_idx;
body->lgd_len = len;
body->lgd_cur_offset = *cur_offset;
req_capsule_set_size(&req->rq_pill, &RMF_EADATA, RCL_SERVER, len);
ptlrpc_request_set_replen(req);
rc = ptlrpc_queue_wait(req);
if (rc)
GOTO(out, rc);
body = req_capsule_server_get(&req->rq_pill, &RMF_LLOGD_BODY);
if (body == NULL)
GOTO(out, rc =-EFAULT);
/* The log records are swabbed as they are processed */
ptr = req_capsule_server_get(&req->rq_pill, &RMF_EADATA);
if (ptr == NULL)
GOTO(out, rc =-EFAULT);
*cur_idx = body->lgd_saved_index;
*cur_offset = body->lgd_cur_offset;
memcpy(buf, ptr, len);
EXIT;
out:
ptlrpc_req_finished(req);
err_exit:
LLOG_CLIENT_EXIT(loghandle->lgh_ctxt, imp);
return rc;
}
static int llog_client_prev_block(const struct lu_env *env,
struct llog_handle *loghandle,
int prev_idx, void *buf, int len)
{
struct obd_import *imp;
struct ptlrpc_request *req = NULL;
struct llogd_body *body;
void *ptr;
int rc;
ENTRY;
LLOG_CLIENT_ENTRY(loghandle->lgh_ctxt, imp);
req = ptlrpc_request_alloc_pack(imp, &RQF_LLOG_ORIGIN_HANDLE_PREV_BLOCK,
LUSTRE_LOG_VERSION,
LLOG_ORIGIN_HANDLE_PREV_BLOCK);
if (req == NULL)
GOTO(err_exit, rc = -ENOMEM);
body = req_capsule_client_get(&req->rq_pill, &RMF_LLOGD_BODY);
body->lgd_logid = loghandle->lgh_id;
body->lgd_ctxt_idx = loghandle->lgh_ctxt->loc_idx - 1;
body->lgd_llh_flags = loghandle->lgh_hdr->llh_flags;
body->lgd_index = prev_idx;
body->lgd_len = len;
req_capsule_set_size(&req->rq_pill, &RMF_EADATA, RCL_SERVER, len);
ptlrpc_request_set_replen(req);
rc = ptlrpc_queue_wait(req);
if (rc)
GOTO(out, rc);
body = req_capsule_server_get(&req->rq_pill, &RMF_LLOGD_BODY);
if (body == NULL)
GOTO(out, rc =-EFAULT);
ptr = req_capsule_server_get(&req->rq_pill, &RMF_EADATA);
if (ptr == NULL)
GOTO(out, rc =-EFAULT);
memcpy(buf, ptr, len);
EXIT;
out:
ptlrpc_req_finished(req);
err_exit:
LLOG_CLIENT_EXIT(loghandle->lgh_ctxt, imp);
return rc;
}
static int llog_client_read_header(const struct lu_env *env,
struct llog_handle *handle)
{
struct obd_import *imp;
struct ptlrpc_request *req = NULL;
struct llogd_body *body;
struct llog_log_hdr *hdr;
struct llog_rec_hdr *llh_hdr;
int rc;
ENTRY;
LLOG_CLIENT_ENTRY(handle->lgh_ctxt, imp);
req = ptlrpc_request_alloc_pack(imp,&RQF_LLOG_ORIGIN_HANDLE_READ_HEADER,
LUSTRE_LOG_VERSION,
LLOG_ORIGIN_HANDLE_READ_HEADER);
if (req == NULL)
GOTO(err_exit, rc = -ENOMEM);
body = req_capsule_client_get(&req->rq_pill, &RMF_LLOGD_BODY);
body->lgd_logid = handle->lgh_id;
body->lgd_ctxt_idx = handle->lgh_ctxt->loc_idx - 1;
body->lgd_llh_flags = handle->lgh_hdr->llh_flags;
ptlrpc_request_set_replen(req);
rc = ptlrpc_queue_wait(req);
if (rc)
GOTO(out, rc);
hdr = req_capsule_server_get(&req->rq_pill, &RMF_LLOG_LOG_HDR);
if (hdr == NULL)
GOTO(out, rc =-EFAULT);
memcpy(handle->lgh_hdr, hdr, sizeof (*hdr));
handle->lgh_last_idx = handle->lgh_hdr->llh_tail.lrt_index;
/* sanity checks */
llh_hdr = &handle->lgh_hdr->llh_hdr;
if (llh_hdr->lrh_type != LLOG_HDR_MAGIC) {
CERROR("bad log header magic: %#x (expecting %#x)\n",
llh_hdr->lrh_type, LLOG_HDR_MAGIC);
rc = -EIO;
} else if (llh_hdr->lrh_len != LLOG_CHUNK_SIZE) {
CERROR("incorrectly sized log header: %#x "
"(expecting %#x)\n",
llh_hdr->lrh_len, LLOG_CHUNK_SIZE);
CERROR("you may need to re-run lconf --write_conf.\n");
rc = -EIO;
}
EXIT;
out:
ptlrpc_req_finished(req);
err_exit:
LLOG_CLIENT_EXIT(handle->lgh_ctxt, imp);
return rc;
}
static int llog_client_close(const struct lu_env *env,
struct llog_handle *handle)
{
/* this doesn't call LLOG_ORIGIN_HANDLE_CLOSE because
the servers all close the file at the end of every
other LLOG_ RPC. */
return(0);
}
struct llog_operations llog_client_ops = {
.lop_next_block = llog_client_next_block,
.lop_prev_block = llog_client_prev_block,
.lop_read_header = llog_client_read_header,
.lop_open = llog_client_open,
.lop_destroy = llog_client_destroy,
.lop_close = llog_client_close,
};
EXPORT_SYMBOL(llog_client_ops);
| gpl-2.0 |
cheehieu/linux | drivers/pinctrl/sunxi/pinctrl-sun5i-a10s.c | 580 | 26877 | /*
* Allwinner A10s SoCs pinctrl driver.
*
* Copyright (C) 2014 Maxime Ripard
*
* Maxime Ripard <maxime.ripard@free-electrons.com>
*
* This file is licensed under the terms of the GNU General Public
* License version 2. This program is licensed "as is" without any
* warranty of any kind, whether express or implied.
*/
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/pinctrl/pinctrl.h>
#include "pinctrl-sunxi.h"
static const struct sunxi_desc_pin sun5i_a10s_pins[] = {
SUNXI_PIN(SUNXI_PINCTRL_PIN(A, 0),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "emac"), /* ERXD3 */
SUNXI_FUNCTION(0x3, "ts0"), /* CLK */
SUNXI_FUNCTION(0x5, "keypad")), /* IN0 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(A, 1),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "emac"), /* ERXD2 */
SUNXI_FUNCTION(0x3, "ts0"), /* ERR */
SUNXI_FUNCTION(0x5, "keypad")), /* IN1 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(A, 2),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "emac"), /* ERXD1 */
SUNXI_FUNCTION(0x3, "ts0"), /* SYNC */
SUNXI_FUNCTION(0x5, "keypad")), /* IN2 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(A, 3),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "emac"), /* ERXD0 */
SUNXI_FUNCTION(0x3, "ts0"), /* DLVD */
SUNXI_FUNCTION(0x5, "keypad")), /* IN3 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(A, 4),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "emac"), /* ETXD3 */
SUNXI_FUNCTION(0x3, "ts0"), /* D0 */
SUNXI_FUNCTION(0x5, "keypad")), /* IN4 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(A, 5),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "emac"), /* ETXD2 */
SUNXI_FUNCTION(0x3, "ts0"), /* D1 */
SUNXI_FUNCTION(0x5, "keypad")), /* IN5 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(A, 6),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "emac"), /* ETXD1 */
SUNXI_FUNCTION(0x3, "ts0"), /* D2 */
SUNXI_FUNCTION(0x5, "keypad")), /* IN6 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(A, 7),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "emac"), /* ETXD0 */
SUNXI_FUNCTION(0x3, "ts0"), /* D3 */
SUNXI_FUNCTION(0x5, "keypad")), /* IN7 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(A, 8),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "emac"), /* ERXCK */
SUNXI_FUNCTION(0x3, "ts0"), /* D4 */
SUNXI_FUNCTION(0x4, "uart1"), /* DTR */
SUNXI_FUNCTION(0x5, "keypad")), /* OUT0 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(A, 9),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "emac"), /* ERXERR */
SUNXI_FUNCTION(0x3, "ts0"), /* D5 */
SUNXI_FUNCTION(0x4, "uart1"), /* DSR */
SUNXI_FUNCTION(0x5, "keypad")), /* OUT1 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(A, 10),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "emac"), /* ERXDV */
SUNXI_FUNCTION(0x3, "ts0"), /* D6 */
SUNXI_FUNCTION(0x4, "uart1"), /* DCD */
SUNXI_FUNCTION(0x5, "keypad")), /* OUT2 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(A, 11),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "emac"), /* EMDC */
SUNXI_FUNCTION(0x3, "ts0"), /* D7 */
SUNXI_FUNCTION(0x4, "uart1"), /* RING */
SUNXI_FUNCTION(0x5, "keypad")), /* OUT3 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(A, 12),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "emac"), /* EMDIO */
SUNXI_FUNCTION(0x3, "uart1"), /* TX */
SUNXI_FUNCTION(0x5, "keypad")), /* OUT4 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(A, 13),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "emac"), /* ETXEN */
SUNXI_FUNCTION(0x3, "uart1"), /* RX */
SUNXI_FUNCTION(0x5, "keypad")), /* OUT5 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(A, 14),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "emac"), /* ETXCK */
SUNXI_FUNCTION(0x3, "uart1"), /* CTS */
SUNXI_FUNCTION(0x4, "uart3"), /* TX */
SUNXI_FUNCTION(0x5, "keypad")), /* OUT6 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(A, 15),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "emac"), /* ECRS */
SUNXI_FUNCTION(0x3, "uart1"), /* RTS */
SUNXI_FUNCTION(0x4, "uart3"), /* RX */
SUNXI_FUNCTION(0x5, "keypad")), /* OUT7 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(A, 16),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "emac"), /* ECOL */
SUNXI_FUNCTION(0x3, "uart2")), /* TX */
SUNXI_PIN(SUNXI_PINCTRL_PIN(A, 17),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "emac"), /* ETXERR */
SUNXI_FUNCTION(0x3, "uart2"), /* RX */
SUNXI_FUNCTION_IRQ(0x6, 31)), /* EINT31 */
/* Hole */
SUNXI_PIN(SUNXI_PINCTRL_PIN(B, 0),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "i2c0")), /* SCK */
SUNXI_PIN(SUNXI_PINCTRL_PIN(B, 1),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "i2c0")), /* SDA */
SUNXI_PIN(SUNXI_PINCTRL_PIN(B, 2),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "pwm"), /* PWM0 */
SUNXI_FUNCTION_IRQ(0x6, 16)), /* EINT16 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(B, 3),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "ir0"), /* TX */
SUNXI_FUNCTION_IRQ(0x6, 17)), /* EINT17 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(B, 4),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "ir0"), /* RX */
SUNXI_FUNCTION_IRQ(0x6, 18)), /* EINT18 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(B, 5),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "i2s"), /* MCLK */
SUNXI_FUNCTION_IRQ(0x6, 19)), /* EINT19 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(B, 6),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "i2s"), /* BCLK */
SUNXI_FUNCTION_IRQ(0x6, 20)), /* EINT20 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(B, 7),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "i2s"), /* LRCK */
SUNXI_FUNCTION_IRQ(0x6, 21)), /* EINT21 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(B, 8),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "i2s"), /* DO */
SUNXI_FUNCTION_IRQ(0x6, 22)), /* EINT22 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(B, 9),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "i2s"), /* DI */
SUNXI_FUNCTION_IRQ(0x6, 23)), /* EINT23 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(B, 10),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "spi2"), /* CS1 */
SUNXI_FUNCTION_IRQ(0x6, 24)), /* EINT24 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(B, 11),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "spi2"), /* CS0 */
SUNXI_FUNCTION(0x3, "jtag"), /* MS0 */
SUNXI_FUNCTION_IRQ(0x6, 25)), /* EINT25 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(B, 12),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "spi2"), /* CLK */
SUNXI_FUNCTION(0x3, "jtag"), /* CK0 */
SUNXI_FUNCTION_IRQ(0x6, 26)), /* EINT26 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(B, 13),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "spi2"), /* MOSI */
SUNXI_FUNCTION(0x3, "jtag"), /* DO0 */
SUNXI_FUNCTION_IRQ(0x6, 27)), /* EINT27 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(B, 14),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "spi2"), /* MISO */
SUNXI_FUNCTION(0x3, "jtag"), /* DI0 */
SUNXI_FUNCTION_IRQ(0x6, 28)), /* EINT28 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(B, 15),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "i2c1")), /* SCK */
SUNXI_PIN(SUNXI_PINCTRL_PIN(B, 16),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "i2c1")), /* SDA */
SUNXI_PIN(SUNXI_PINCTRL_PIN(B, 17),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "i2c2")), /* SCK */
SUNXI_PIN(SUNXI_PINCTRL_PIN(B, 18),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "i2c2")), /* SDA */
SUNXI_PIN(SUNXI_PINCTRL_PIN(B, 19),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "uart0"), /* TX */
SUNXI_FUNCTION_IRQ(0x6, 29)), /* EINT29 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(B, 20),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "uart0"), /* RX */
SUNXI_FUNCTION_IRQ(0x6, 30)), /* EINT30 */
/* Hole */
SUNXI_PIN(SUNXI_PINCTRL_PIN(C, 0),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "nand0"), /* NWE */
SUNXI_FUNCTION(0x3, "spi0")), /* MOSI */
SUNXI_PIN(SUNXI_PINCTRL_PIN(C, 1),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "nand0"), /* NALE */
SUNXI_FUNCTION(0x3, "spi0")), /* MISO */
SUNXI_PIN(SUNXI_PINCTRL_PIN(C, 2),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "nand0"), /* NCLE */
SUNXI_FUNCTION(0x3, "spi0")), /* SCK */
SUNXI_PIN(SUNXI_PINCTRL_PIN(C, 3),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "nand0"), /* NCE1 */
SUNXI_FUNCTION(0x3, "spi0")), /* CS0 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(C, 4),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "nand0")), /* NCE0 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(C, 5),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "nand0")), /* NRE */
SUNXI_PIN(SUNXI_PINCTRL_PIN(C, 6),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "nand0"), /* NRB0 */
SUNXI_FUNCTION(0x3, "mmc2")), /* CMD */
SUNXI_PIN(SUNXI_PINCTRL_PIN(C, 7),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "nand0"), /* NRB1 */
SUNXI_FUNCTION(0x3, "mmc2")), /* CLK */
SUNXI_PIN(SUNXI_PINCTRL_PIN(C, 8),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "nand0"), /* NDQ0 */
SUNXI_FUNCTION(0x3, "mmc2")), /* D0 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(C, 9),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "nand0"), /* NDQ1 */
SUNXI_FUNCTION(0x3, "mmc2")), /* D1 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(C, 10),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "nand0"), /* NDQ2 */
SUNXI_FUNCTION(0x3, "mmc2")), /* D2 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(C, 11),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "nand0"), /* NDQ3 */
SUNXI_FUNCTION(0x3, "mmc2")), /* D3 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(C, 12),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "nand0"), /* NDQ4 */
SUNXI_FUNCTION(0x3, "mmc2")), /* D4 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(C, 13),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "nand0"), /* NDQ5 */
SUNXI_FUNCTION(0x3, "mmc2")), /* D5 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(C, 14),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "nand0"), /* NDQ6 */
SUNXI_FUNCTION(0x3, "mmc2")), /* D6 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(C, 15),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "nand0"), /* NDQ7 */
SUNXI_FUNCTION(0x3, "mmc2")), /* D7 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(C, 16),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "nand0"), /* NWP */
SUNXI_FUNCTION(0x4, "uart3")), /* TX */
SUNXI_PIN(SUNXI_PINCTRL_PIN(C, 17),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "nand0"), /* NCE2 */
SUNXI_FUNCTION(0x4, "uart3")), /* RX */
SUNXI_PIN(SUNXI_PINCTRL_PIN(C, 18),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "nand0"), /* NCE3 */
SUNXI_FUNCTION(0x3, "uart2"), /* TX */
SUNXI_FUNCTION(0x4, "uart3")), /* CTS */
SUNXI_PIN(SUNXI_PINCTRL_PIN(C, 19),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "nand0"), /* NCE4 */
SUNXI_FUNCTION(0x3, "uart2"), /* RX */
SUNXI_FUNCTION(0x4, "uart3")), /* RTS */
/* Hole */
SUNXI_PIN(SUNXI_PINCTRL_PIN(D, 0),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "lcd0")), /* D0 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(D, 1),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "lcd0")), /* D1 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(D, 2),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "lcd0"), /* D2 */
SUNXI_FUNCTION(0x3, "uart2")), /* TX */
SUNXI_PIN(SUNXI_PINCTRL_PIN(D, 3),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "lcd0"), /* D3 */
SUNXI_FUNCTION(0x3, "uart2")), /* RX */
SUNXI_PIN(SUNXI_PINCTRL_PIN(D, 4),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "lcd0"), /* D4 */
SUNXI_FUNCTION(0x3, "uart2")), /* CTS */
SUNXI_PIN(SUNXI_PINCTRL_PIN(D, 5),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "lcd0"), /* D5 */
SUNXI_FUNCTION(0x3, "uart2")), /* RTS */
SUNXI_PIN(SUNXI_PINCTRL_PIN(D, 6),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "lcd0"), /* D6 */
SUNXI_FUNCTION(0x3, "emac")), /* ECRS */
SUNXI_PIN(SUNXI_PINCTRL_PIN(D, 7),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "lcd0"), /* D7 */
SUNXI_FUNCTION(0x3, "emac")), /* ECOL */
SUNXI_PIN(SUNXI_PINCTRL_PIN(D, 8),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "lcd0")), /* D8 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(D, 9),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "lcd0")), /* D9 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(D, 10),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "lcd0"), /* D10 */
SUNXI_FUNCTION(0x3, "emac")), /* ERXD0 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(D, 11),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "lcd0"), /* D11 */
SUNXI_FUNCTION(0x3, "emac")), /* ERXD1 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(D, 12),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "lcd0"), /* D12 */
SUNXI_FUNCTION(0x3, "emac")), /* ERXD2 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(D, 13),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "lcd0"), /* D13 */
SUNXI_FUNCTION(0x3, "emac")), /* ERXD3 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(D, 14),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "lcd0"), /* D14 */
SUNXI_FUNCTION(0x3, "emac")), /* ERXCK */
SUNXI_PIN(SUNXI_PINCTRL_PIN(D, 15),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "lcd0"), /* D15 */
SUNXI_FUNCTION(0x3, "emac")), /* ERXERR */
SUNXI_PIN(SUNXI_PINCTRL_PIN(D, 16),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "lcd0")), /* D16 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(D, 17),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "lcd0")), /* D17 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(D, 18),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "lcd0"), /* D18 */
SUNXI_FUNCTION(0x3, "emac")), /* ERXDV */
SUNXI_PIN(SUNXI_PINCTRL_PIN(D, 19),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "lcd0"), /* D19 */
SUNXI_FUNCTION(0x3, "emac")), /* ETXD0 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(D, 20),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "lcd0"), /* D20 */
SUNXI_FUNCTION(0x3, "emac")), /* ETXD1 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(D, 21),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "lcd0"), /* D21 */
SUNXI_FUNCTION(0x3, "emac")), /* ETXD2 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(D, 22),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "lcd0"), /* D22 */
SUNXI_FUNCTION(0x3, "emac")), /* ETXD3 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(D, 23),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "lcd0"), /* D23 */
SUNXI_FUNCTION(0x3, "emac")), /* ETXEN */
SUNXI_PIN(SUNXI_PINCTRL_PIN(D, 24),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "lcd0"), /* CLK */
SUNXI_FUNCTION(0x3, "emac")), /* ETXCK */
SUNXI_PIN(SUNXI_PINCTRL_PIN(D, 25),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "lcd0"), /* DE */
SUNXI_FUNCTION(0x3, "emac")), /* ETXERR */
SUNXI_PIN(SUNXI_PINCTRL_PIN(D, 26),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "lcd0"), /* HSYNC */
SUNXI_FUNCTION(0x3, "emac")), /* EMDC */
SUNXI_PIN(SUNXI_PINCTRL_PIN(D, 27),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "lcd0"), /* VSYNC */
SUNXI_FUNCTION(0x3, "emac")), /* EMDIO */
/* Hole */
SUNXI_PIN(SUNXI_PINCTRL_PIN(E, 0),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x2, "ts0"), /* CLK */
SUNXI_FUNCTION(0x3, "csi0"), /* PCK */
SUNXI_FUNCTION(0x4, "spi2"), /* CS0 */
SUNXI_FUNCTION_IRQ(0x6, 14)), /* EINT14 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(E, 1),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x2, "ts0"), /* ERR */
SUNXI_FUNCTION(0x3, "csi0"), /* CK */
SUNXI_FUNCTION(0x4, "spi2"), /* CLK */
SUNXI_FUNCTION_IRQ(0x6, 15)), /* EINT15 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(E, 2),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x2, "ts0"), /* SYNC */
SUNXI_FUNCTION(0x3, "csi0"), /* HSYNC */
SUNXI_FUNCTION(0x4, "spi2")), /* MOSI */
SUNXI_PIN(SUNXI_PINCTRL_PIN(E, 3),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "ts0"), /* DVLD */
SUNXI_FUNCTION(0x3, "csi0"), /* VSYNC */
SUNXI_FUNCTION(0x4, "spi2")), /* MISO */
SUNXI_PIN(SUNXI_PINCTRL_PIN(E, 4),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "ts0"), /* D0 */
SUNXI_FUNCTION(0x3, "csi0"), /* D0 */
SUNXI_FUNCTION(0x4, "mmc2")), /* D0 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(E, 5),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "ts0"), /* D1 */
SUNXI_FUNCTION(0x3, "csi0"), /* D1 */
SUNXI_FUNCTION(0x4, "mmc2")), /* D1 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(E, 6),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "ts0"), /* D2 */
SUNXI_FUNCTION(0x3, "csi0"), /* D2 */
SUNXI_FUNCTION(0x4, "mmc2")), /* D2 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(E, 7),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "ts0"), /* D3 */
SUNXI_FUNCTION(0x3, "csi0"), /* D3 */
SUNXI_FUNCTION(0x4, "mmc2")), /* D3 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(E, 8),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "ts0"), /* D4 */
SUNXI_FUNCTION(0x3, "csi0"), /* D4 */
SUNXI_FUNCTION(0x4, "mmc2")), /* CMD */
SUNXI_PIN(SUNXI_PINCTRL_PIN(E, 9),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "ts0"), /* D5 */
SUNXI_FUNCTION(0x3, "csi0"), /* D5 */
SUNXI_FUNCTION(0x4, "mmc2")), /* CLK */
SUNXI_PIN(SUNXI_PINCTRL_PIN(E, 10),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "ts0"), /* D6 */
SUNXI_FUNCTION(0x3, "csi0"), /* D6 */
SUNXI_FUNCTION(0x4, "uart1")), /* TX */
SUNXI_PIN(SUNXI_PINCTRL_PIN(E, 11),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "ts0"), /* D7 */
SUNXI_FUNCTION(0x3, "csi0"), /* D7 */
SUNXI_FUNCTION(0x4, "uart1")), /* RX */
/* Hole */
SUNXI_PIN(SUNXI_PINCTRL_PIN(F, 0),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "mmc0"), /* D1 */
SUNXI_FUNCTION(0x4, "jtag")), /* MS1 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(F, 1),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "mmc0"), /* D0 */
SUNXI_FUNCTION(0x4, "jtag")), /* DI1 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(F, 2),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "mmc0"), /* CLK */
SUNXI_FUNCTION(0x4, "uart0")), /* TX */
SUNXI_PIN(SUNXI_PINCTRL_PIN(F, 3),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "mmc0"), /* CMD */
SUNXI_FUNCTION(0x4, "jtag")), /* DO1 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(F, 4),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "mmc0"), /* D3 */
SUNXI_FUNCTION(0x4, "uart0")), /* RX */
SUNXI_PIN(SUNXI_PINCTRL_PIN(F, 5),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "mmc0"), /* D2 */
SUNXI_FUNCTION(0x4, "jtag")), /* CK1 */
/* Hole */
SUNXI_PIN(SUNXI_PINCTRL_PIN(G, 0),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x2, "gps"), /* CLK */
SUNXI_FUNCTION_IRQ(0x6, 0)), /* EINT0 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(G, 1),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x2, "gps"), /* SIGN */
SUNXI_FUNCTION_IRQ(0x6, 1)), /* EINT1 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(G, 2),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x2, "gps"), /* MAG */
SUNXI_FUNCTION_IRQ(0x6, 2)), /* EINT2 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(G, 3),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "mmc1"), /* CMD */
SUNXI_FUNCTION(0x4, "uart1"), /* TX */
SUNXI_FUNCTION_IRQ(0x6, 3)), /* EINT3 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(G, 4),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "mmc1"), /* CLK */
SUNXI_FUNCTION(0x4, "uart1"), /* RX */
SUNXI_FUNCTION_IRQ(0x6, 4)), /* EINT4 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(G, 5),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "mmc1"), /* DO */
SUNXI_FUNCTION(0x4, "uart1"), /* CTS */
SUNXI_FUNCTION_IRQ(0x6, 5)), /* EINT5 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(G, 6),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "mmc1"), /* D1 */
SUNXI_FUNCTION(0x4, "uart1"), /* RTS */
SUNXI_FUNCTION(0x5, "uart2"), /* RTS */
SUNXI_FUNCTION_IRQ(0x6, 6)), /* EINT6 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(G, 7),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "mmc1"), /* D2 */
SUNXI_FUNCTION(0x5, "uart2"), /* TX */
SUNXI_FUNCTION_IRQ(0x6, 7)), /* EINT7 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(G, 8),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "mmc1"), /* D3 */
SUNXI_FUNCTION(0x5, "uart2"), /* RX */
SUNXI_FUNCTION_IRQ(0x6, 8)), /* EINT8 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(G, 9),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "spi1"), /* CS0 */
SUNXI_FUNCTION(0x3, "uart3"), /* TX */
SUNXI_FUNCTION_IRQ(0x6, 9)), /* EINT9 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(G, 10),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "spi1"), /* CLK */
SUNXI_FUNCTION(0x3, "uart3"), /* RX */
SUNXI_FUNCTION_IRQ(0x6, 10)), /* EINT10 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(G, 11),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "spi1"), /* MOSI */
SUNXI_FUNCTION(0x3, "uart3"), /* CTS */
SUNXI_FUNCTION_IRQ(0x6, 11)), /* EINT11 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(G, 12),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "spi1"), /* MISO */
SUNXI_FUNCTION(0x3, "uart3"), /* RTS */
SUNXI_FUNCTION_IRQ(0x6, 12)), /* EINT12 */
SUNXI_PIN(SUNXI_PINCTRL_PIN(G, 13),
SUNXI_FUNCTION(0x0, "gpio_in"),
SUNXI_FUNCTION(0x1, "gpio_out"),
SUNXI_FUNCTION(0x2, "spi1"), /* CS1 */
SUNXI_FUNCTION(0x3, "uart3"), /* PWM1 */
SUNXI_FUNCTION(0x5, "uart2"), /* CTS */
SUNXI_FUNCTION_IRQ(0x6, 13)), /* EINT13 */
};
static const struct sunxi_pinctrl_desc sun5i_a10s_pinctrl_data = {
.pins = sun5i_a10s_pins,
.npins = ARRAY_SIZE(sun5i_a10s_pins),
.irq_banks = 1,
};
static int sun5i_a10s_pinctrl_probe(struct platform_device *pdev)
{
return sunxi_pinctrl_init(pdev,
&sun5i_a10s_pinctrl_data);
}
static const struct of_device_id sun5i_a10s_pinctrl_match[] = {
{ .compatible = "allwinner,sun5i-a10s-pinctrl", },
{}
};
MODULE_DEVICE_TABLE(of, sun5i_a10s_pinctrl_match);
static struct platform_driver sun5i_a10s_pinctrl_driver = {
.probe = sun5i_a10s_pinctrl_probe,
.driver = {
.name = "sun5i-a10s-pinctrl",
.of_match_table = sun5i_a10s_pinctrl_match,
},
};
module_platform_driver(sun5i_a10s_pinctrl_driver);
MODULE_AUTHOR("Maxime Ripard <maxime.ripard@free-electrons.com");
MODULE_DESCRIPTION("Allwinner A10s pinctrl driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
wkritzinger/asuswrt-merlin | release/src-rt-7.14.114.x/src/linux/linux-2.6.36/drivers/net/phy/smsc.c | 836 | 6758 | /*
* drivers/net/phy/smsc.c
*
* Driver for SMSC PHYs
*
* Author: Herbert Valerio Riedel
*
* Copyright (c) 2006 Herbert Valerio Riedel <hvr@gnu.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.
*
* Support added for SMSC LAN8187 and LAN8700 by steve.glendinning@smsc.com
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/mii.h>
#include <linux/ethtool.h>
#include <linux/phy.h>
#include <linux/netdevice.h>
#define MII_LAN83C185_ISF 29 /* Interrupt Source Flags */
#define MII_LAN83C185_IM 30 /* Interrupt Mask */
#define MII_LAN83C185_CTRL_STATUS 17 /* Mode/Status Register */
#define MII_LAN83C185_ISF_INT1 (1<<1) /* Auto-Negotiation Page Received */
#define MII_LAN83C185_ISF_INT2 (1<<2) /* Parallel Detection Fault */
#define MII_LAN83C185_ISF_INT3 (1<<3) /* Auto-Negotiation LP Ack */
#define MII_LAN83C185_ISF_INT4 (1<<4) /* Link Down */
#define MII_LAN83C185_ISF_INT5 (1<<5) /* Remote Fault Detected */
#define MII_LAN83C185_ISF_INT6 (1<<6) /* Auto-Negotiation complete */
#define MII_LAN83C185_ISF_INT7 (1<<7) /* ENERGYON */
#define MII_LAN83C185_ISF_INT_ALL (0x0e)
#define MII_LAN83C185_ISF_INT_PHYLIB_EVENTS \
(MII_LAN83C185_ISF_INT6 | MII_LAN83C185_ISF_INT4 | \
MII_LAN83C185_ISF_INT7)
#define MII_LAN83C185_EDPWRDOWN (1 << 13) /* EDPWRDOWN */
static int smsc_phy_config_intr(struct phy_device *phydev)
{
int rc = phy_write (phydev, MII_LAN83C185_IM,
((PHY_INTERRUPT_ENABLED == phydev->interrupts)
? MII_LAN83C185_ISF_INT_PHYLIB_EVENTS
: 0));
return rc < 0 ? rc : 0;
}
static int smsc_phy_ack_interrupt(struct phy_device *phydev)
{
int rc = phy_read (phydev, MII_LAN83C185_ISF);
return rc < 0 ? rc : 0;
}
static int smsc_phy_config_init(struct phy_device *phydev)
{
int rc = phy_read(phydev, MII_LAN83C185_CTRL_STATUS);
if (rc < 0)
return rc;
/* Enable energy detect mode for this SMSC Transceivers */
rc = phy_write(phydev, MII_LAN83C185_CTRL_STATUS,
rc | MII_LAN83C185_EDPWRDOWN);
if (rc < 0)
return rc;
return smsc_phy_ack_interrupt (phydev);
}
static int lan911x_config_init(struct phy_device *phydev)
{
return smsc_phy_ack_interrupt(phydev);
}
static struct phy_driver lan83c185_driver = {
.phy_id = 0x0007c0a0, /* OUI=0x00800f, Model#=0x0a */
.phy_id_mask = 0xfffffff0,
.name = "SMSC LAN83C185",
.features = (PHY_BASIC_FEATURES | SUPPORTED_Pause
| SUPPORTED_Asym_Pause),
.flags = PHY_HAS_INTERRUPT | PHY_HAS_MAGICANEG,
/* basic functions */
.config_aneg = genphy_config_aneg,
.read_status = genphy_read_status,
.config_init = smsc_phy_config_init,
/* IRQ related */
.ack_interrupt = smsc_phy_ack_interrupt,
.config_intr = smsc_phy_config_intr,
.suspend = genphy_suspend,
.resume = genphy_resume,
.driver = { .owner = THIS_MODULE, }
};
static struct phy_driver lan8187_driver = {
.phy_id = 0x0007c0b0, /* OUI=0x00800f, Model#=0x0b */
.phy_id_mask = 0xfffffff0,
.name = "SMSC LAN8187",
.features = (PHY_BASIC_FEATURES | SUPPORTED_Pause
| SUPPORTED_Asym_Pause),
.flags = PHY_HAS_INTERRUPT | PHY_HAS_MAGICANEG,
/* basic functions */
.config_aneg = genphy_config_aneg,
.read_status = genphy_read_status,
.config_init = smsc_phy_config_init,
/* IRQ related */
.ack_interrupt = smsc_phy_ack_interrupt,
.config_intr = smsc_phy_config_intr,
.suspend = genphy_suspend,
.resume = genphy_resume,
.driver = { .owner = THIS_MODULE, }
};
static struct phy_driver lan8700_driver = {
.phy_id = 0x0007c0c0, /* OUI=0x00800f, Model#=0x0c */
.phy_id_mask = 0xfffffff0,
.name = "SMSC LAN8700",
.features = (PHY_BASIC_FEATURES | SUPPORTED_Pause
| SUPPORTED_Asym_Pause),
.flags = PHY_HAS_INTERRUPT | PHY_HAS_MAGICANEG,
/* basic functions */
.config_aneg = genphy_config_aneg,
.read_status = genphy_read_status,
.config_init = smsc_phy_config_init,
/* IRQ related */
.ack_interrupt = smsc_phy_ack_interrupt,
.config_intr = smsc_phy_config_intr,
.suspend = genphy_suspend,
.resume = genphy_resume,
.driver = { .owner = THIS_MODULE, }
};
static struct phy_driver lan911x_int_driver = {
.phy_id = 0x0007c0d0, /* OUI=0x00800f, Model#=0x0d */
.phy_id_mask = 0xfffffff0,
.name = "SMSC LAN911x Internal PHY",
.features = (PHY_BASIC_FEATURES | SUPPORTED_Pause
| SUPPORTED_Asym_Pause),
.flags = PHY_HAS_INTERRUPT | PHY_HAS_MAGICANEG,
/* basic functions */
.config_aneg = genphy_config_aneg,
.read_status = genphy_read_status,
.config_init = lan911x_config_init,
/* IRQ related */
.ack_interrupt = smsc_phy_ack_interrupt,
.config_intr = smsc_phy_config_intr,
.suspend = genphy_suspend,
.resume = genphy_resume,
.driver = { .owner = THIS_MODULE, }
};
static struct phy_driver lan8710_driver = {
.phy_id = 0x0007c0f0, /* OUI=0x00800f, Model#=0x0f */
.phy_id_mask = 0xfffffff0,
.name = "SMSC LAN8710/LAN8720",
.features = (PHY_BASIC_FEATURES | SUPPORTED_Pause
| SUPPORTED_Asym_Pause),
.flags = PHY_HAS_INTERRUPT | PHY_HAS_MAGICANEG,
/* basic functions */
.config_aneg = genphy_config_aneg,
.read_status = genphy_read_status,
.config_init = smsc_phy_config_init,
/* IRQ related */
.ack_interrupt = smsc_phy_ack_interrupt,
.config_intr = smsc_phy_config_intr,
.suspend = genphy_suspend,
.resume = genphy_resume,
.driver = { .owner = THIS_MODULE, }
};
static int __init smsc_init(void)
{
int ret;
ret = phy_driver_register (&lan83c185_driver);
if (ret)
goto err1;
ret = phy_driver_register (&lan8187_driver);
if (ret)
goto err2;
ret = phy_driver_register (&lan8700_driver);
if (ret)
goto err3;
ret = phy_driver_register (&lan911x_int_driver);
if (ret)
goto err4;
ret = phy_driver_register (&lan8710_driver);
if (ret)
goto err5;
return 0;
err5:
phy_driver_unregister (&lan911x_int_driver);
err4:
phy_driver_unregister (&lan8700_driver);
err3:
phy_driver_unregister (&lan8187_driver);
err2:
phy_driver_unregister (&lan83c185_driver);
err1:
return ret;
}
static void __exit smsc_exit(void)
{
phy_driver_unregister (&lan8710_driver);
phy_driver_unregister (&lan911x_int_driver);
phy_driver_unregister (&lan8700_driver);
phy_driver_unregister (&lan8187_driver);
phy_driver_unregister (&lan83c185_driver);
}
MODULE_DESCRIPTION("SMSC PHY driver");
MODULE_AUTHOR("Herbert Valerio Riedel");
MODULE_LICENSE("GPL");
module_init(smsc_init);
module_exit(smsc_exit);
static struct mdio_device_id smsc_tbl[] = {
{ 0x0007c0a0, 0xfffffff0 },
{ 0x0007c0b0, 0xfffffff0 },
{ 0x0007c0c0, 0xfffffff0 },
{ 0x0007c0d0, 0xfffffff0 },
{ 0x0007c0f0, 0xfffffff0 },
{ }
};
MODULE_DEVICE_TABLE(mdio, smsc_tbl);
| gpl-2.0 |
spairal/linux-for-lobster | drivers/mmc/host/bfin_sdh.c | 836 | 16267 | /*
* bfin_sdh.c - Analog Devices Blackfin SDH Controller
*
* Copyright (C) 2007-2009 Analog Device Inc.
*
* Licensed under the GPL-2 or later.
*/
#define DRIVER_NAME "bfin-sdh"
#include <linux/module.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/platform_device.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/dma-mapping.h>
#include <linux/mmc/host.h>
#include <linux/proc_fs.h>
#include <linux/gfp.h>
#include <asm/cacheflush.h>
#include <asm/dma.h>
#include <asm/portmux.h>
#include <asm/bfin_sdh.h>
#if defined(CONFIG_BF51x)
#define bfin_read_SDH_PWR_CTL bfin_read_RSI_PWR_CTL
#define bfin_write_SDH_PWR_CTL bfin_write_RSI_PWR_CTL
#define bfin_read_SDH_CLK_CTL bfin_read_RSI_CLK_CTL
#define bfin_write_SDH_CLK_CTL bfin_write_RSI_CLK_CTL
#define bfin_write_SDH_ARGUMENT bfin_write_RSI_ARGUMENT
#define bfin_write_SDH_COMMAND bfin_write_RSI_COMMAND
#define bfin_write_SDH_DATA_TIMER bfin_write_RSI_DATA_TIMER
#define bfin_read_SDH_RESPONSE0 bfin_read_RSI_RESPONSE0
#define bfin_read_SDH_RESPONSE1 bfin_read_RSI_RESPONSE1
#define bfin_read_SDH_RESPONSE2 bfin_read_RSI_RESPONSE2
#define bfin_read_SDH_RESPONSE3 bfin_read_RSI_RESPONSE3
#define bfin_write_SDH_DATA_LGTH bfin_write_RSI_DATA_LGTH
#define bfin_read_SDH_DATA_CTL bfin_read_RSI_DATA_CTL
#define bfin_write_SDH_DATA_CTL bfin_write_RSI_DATA_CTL
#define bfin_read_SDH_DATA_CNT bfin_read_RSI_DATA_CNT
#define bfin_write_SDH_STATUS_CLR bfin_write_RSI_STATUS_CLR
#define bfin_read_SDH_E_STATUS bfin_read_RSI_E_STATUS
#define bfin_write_SDH_E_STATUS bfin_write_RSI_E_STATUS
#define bfin_read_SDH_STATUS bfin_read_RSI_STATUS
#define bfin_write_SDH_MASK0 bfin_write_RSI_MASK0
#define bfin_read_SDH_CFG bfin_read_RSI_CFG
#define bfin_write_SDH_CFG bfin_write_RSI_CFG
#endif
struct dma_desc_array {
unsigned long start_addr;
unsigned short cfg;
unsigned short x_count;
short x_modify;
} __packed;
struct sdh_host {
struct mmc_host *mmc;
spinlock_t lock;
struct resource *res;
void __iomem *base;
int irq;
int stat_irq;
int dma_ch;
int dma_dir;
struct dma_desc_array *sg_cpu;
dma_addr_t sg_dma;
int dma_len;
unsigned int imask;
unsigned int power_mode;
unsigned int clk_div;
struct mmc_request *mrq;
struct mmc_command *cmd;
struct mmc_data *data;
};
static struct bfin_sd_host *get_sdh_data(struct platform_device *pdev)
{
return pdev->dev.platform_data;
}
static void sdh_stop_clock(struct sdh_host *host)
{
bfin_write_SDH_CLK_CTL(bfin_read_SDH_CLK_CTL() & ~CLK_E);
SSYNC();
}
static void sdh_enable_stat_irq(struct sdh_host *host, unsigned int mask)
{
unsigned long flags;
spin_lock_irqsave(&host->lock, flags);
host->imask |= mask;
bfin_write_SDH_MASK0(mask);
SSYNC();
spin_unlock_irqrestore(&host->lock, flags);
}
static void sdh_disable_stat_irq(struct sdh_host *host, unsigned int mask)
{
unsigned long flags;
spin_lock_irqsave(&host->lock, flags);
host->imask &= ~mask;
bfin_write_SDH_MASK0(host->imask);
SSYNC();
spin_unlock_irqrestore(&host->lock, flags);
}
static int sdh_setup_data(struct sdh_host *host, struct mmc_data *data)
{
unsigned int length;
unsigned int data_ctl;
unsigned int dma_cfg;
unsigned int cycle_ns, timeout;
dev_dbg(mmc_dev(host->mmc), "%s enter flags: 0x%x\n", __func__, data->flags);
host->data = data;
data_ctl = 0;
dma_cfg = 0;
length = data->blksz * data->blocks;
bfin_write_SDH_DATA_LGTH(length);
if (data->flags & MMC_DATA_STREAM)
data_ctl |= DTX_MODE;
if (data->flags & MMC_DATA_READ)
data_ctl |= DTX_DIR;
/* Only supports power-of-2 block size */
if (data->blksz & (data->blksz - 1))
return -EINVAL;
data_ctl |= ((ffs(data->blksz) - 1) << 4);
bfin_write_SDH_DATA_CTL(data_ctl);
/* the time of a host clock period in ns */
cycle_ns = 1000000000 / (get_sclk() / (2 * (host->clk_div + 1)));
timeout = data->timeout_ns / cycle_ns;
timeout += data->timeout_clks;
bfin_write_SDH_DATA_TIMER(timeout);
SSYNC();
if (data->flags & MMC_DATA_READ) {
host->dma_dir = DMA_FROM_DEVICE;
dma_cfg |= WNR;
} else
host->dma_dir = DMA_TO_DEVICE;
sdh_enable_stat_irq(host, (DAT_CRC_FAIL | DAT_TIME_OUT | DAT_END));
host->dma_len = dma_map_sg(mmc_dev(host->mmc), data->sg, data->sg_len, host->dma_dir);
#if defined(CONFIG_BF54x)
dma_cfg |= DMAFLOW_ARRAY | NDSIZE_5 | RESTART | WDSIZE_32 | DMAEN;
{
struct scatterlist *sg;
int i;
for_each_sg(data->sg, sg, host->dma_len, i) {
host->sg_cpu[i].start_addr = sg_dma_address(sg);
host->sg_cpu[i].cfg = dma_cfg;
host->sg_cpu[i].x_count = sg_dma_len(sg) / 4;
host->sg_cpu[i].x_modify = 4;
dev_dbg(mmc_dev(host->mmc), "%d: start_addr:0x%lx, "
"cfg:0x%x, x_count:0x%x, x_modify:0x%x\n",
i, host->sg_cpu[i].start_addr,
host->sg_cpu[i].cfg, host->sg_cpu[i].x_count,
host->sg_cpu[i].x_modify);
}
}
flush_dcache_range((unsigned int)host->sg_cpu,
(unsigned int)host->sg_cpu +
host->dma_len * sizeof(struct dma_desc_array));
/* Set the last descriptor to stop mode */
host->sg_cpu[host->dma_len - 1].cfg &= ~(DMAFLOW | NDSIZE);
host->sg_cpu[host->dma_len - 1].cfg |= DI_EN;
set_dma_curr_desc_addr(host->dma_ch, (unsigned long *)host->sg_dma);
set_dma_x_count(host->dma_ch, 0);
set_dma_x_modify(host->dma_ch, 0);
set_dma_config(host->dma_ch, dma_cfg);
#elif defined(CONFIG_BF51x)
/* RSI DMA doesn't work in array mode */
dma_cfg |= WDSIZE_32 | DMAEN;
set_dma_start_addr(host->dma_ch, sg_dma_address(&data->sg[0]));
set_dma_x_count(host->dma_ch, length / 4);
set_dma_x_modify(host->dma_ch, 4);
set_dma_config(host->dma_ch, dma_cfg);
#endif
bfin_write_SDH_DATA_CTL(bfin_read_SDH_DATA_CTL() | DTX_DMA_E | DTX_E);
SSYNC();
dev_dbg(mmc_dev(host->mmc), "%s exit\n", __func__);
return 0;
}
static void sdh_start_cmd(struct sdh_host *host, struct mmc_command *cmd)
{
unsigned int sdh_cmd;
unsigned int stat_mask;
dev_dbg(mmc_dev(host->mmc), "%s enter cmd: 0x%p\n", __func__, cmd);
WARN_ON(host->cmd != NULL);
host->cmd = cmd;
sdh_cmd = 0;
stat_mask = 0;
sdh_cmd |= cmd->opcode;
if (cmd->flags & MMC_RSP_PRESENT) {
sdh_cmd |= CMD_RSP;
stat_mask |= CMD_RESP_END;
} else {
stat_mask |= CMD_SENT;
}
if (cmd->flags & MMC_RSP_136)
sdh_cmd |= CMD_L_RSP;
stat_mask |= CMD_CRC_FAIL | CMD_TIME_OUT;
sdh_enable_stat_irq(host, stat_mask);
bfin_write_SDH_ARGUMENT(cmd->arg);
bfin_write_SDH_COMMAND(sdh_cmd | CMD_E);
bfin_write_SDH_CLK_CTL(bfin_read_SDH_CLK_CTL() | CLK_E);
SSYNC();
}
static void sdh_finish_request(struct sdh_host *host, struct mmc_request *mrq)
{
dev_dbg(mmc_dev(host->mmc), "%s enter\n", __func__);
host->mrq = NULL;
host->cmd = NULL;
host->data = NULL;
mmc_request_done(host->mmc, mrq);
}
static int sdh_cmd_done(struct sdh_host *host, unsigned int stat)
{
struct mmc_command *cmd = host->cmd;
int ret = 0;
dev_dbg(mmc_dev(host->mmc), "%s enter cmd: %p\n", __func__, cmd);
if (!cmd)
return 0;
host->cmd = NULL;
if (cmd->flags & MMC_RSP_PRESENT) {
cmd->resp[0] = bfin_read_SDH_RESPONSE0();
if (cmd->flags & MMC_RSP_136) {
cmd->resp[1] = bfin_read_SDH_RESPONSE1();
cmd->resp[2] = bfin_read_SDH_RESPONSE2();
cmd->resp[3] = bfin_read_SDH_RESPONSE3();
}
}
if (stat & CMD_TIME_OUT)
cmd->error = -ETIMEDOUT;
else if (stat & CMD_CRC_FAIL && cmd->flags & MMC_RSP_CRC)
cmd->error = -EILSEQ;
sdh_disable_stat_irq(host, (CMD_SENT | CMD_RESP_END | CMD_TIME_OUT | CMD_CRC_FAIL));
if (host->data && !cmd->error) {
if (host->data->flags & MMC_DATA_WRITE) {
ret = sdh_setup_data(host, host->data);
if (ret)
return 0;
}
sdh_enable_stat_irq(host, DAT_END | RX_OVERRUN | TX_UNDERRUN | DAT_TIME_OUT);
} else
sdh_finish_request(host, host->mrq);
return 1;
}
static int sdh_data_done(struct sdh_host *host, unsigned int stat)
{
struct mmc_data *data = host->data;
dev_dbg(mmc_dev(host->mmc), "%s enter stat: 0x%x\n", __func__, stat);
if (!data)
return 0;
disable_dma(host->dma_ch);
dma_unmap_sg(mmc_dev(host->mmc), data->sg, data->sg_len,
host->dma_dir);
if (stat & DAT_TIME_OUT)
data->error = -ETIMEDOUT;
else if (stat & DAT_CRC_FAIL)
data->error = -EILSEQ;
else if (stat & (RX_OVERRUN | TX_UNDERRUN))
data->error = -EIO;
if (!data->error)
data->bytes_xfered = data->blocks * data->blksz;
else
data->bytes_xfered = 0;
sdh_disable_stat_irq(host, DAT_END | DAT_TIME_OUT | DAT_CRC_FAIL | RX_OVERRUN | TX_UNDERRUN);
bfin_write_SDH_STATUS_CLR(DAT_END_STAT | DAT_TIMEOUT_STAT | \
DAT_CRC_FAIL_STAT | DAT_BLK_END_STAT | RX_OVERRUN | TX_UNDERRUN);
bfin_write_SDH_DATA_CTL(0);
SSYNC();
host->data = NULL;
if (host->mrq->stop) {
sdh_stop_clock(host);
sdh_start_cmd(host, host->mrq->stop);
} else {
sdh_finish_request(host, host->mrq);
}
return 1;
}
static void sdh_request(struct mmc_host *mmc, struct mmc_request *mrq)
{
struct sdh_host *host = mmc_priv(mmc);
int ret = 0;
dev_dbg(mmc_dev(host->mmc), "%s enter, mrp:%p, cmd:%p\n", __func__, mrq, mrq->cmd);
WARN_ON(host->mrq != NULL);
host->mrq = mrq;
host->data = mrq->data;
if (mrq->data && mrq->data->flags & MMC_DATA_READ) {
ret = sdh_setup_data(host, mrq->data);
if (ret)
return;
}
sdh_start_cmd(host, mrq->cmd);
}
static void sdh_set_ios(struct mmc_host *mmc, struct mmc_ios *ios)
{
struct sdh_host *host;
unsigned long flags;
u16 clk_ctl = 0;
u16 pwr_ctl = 0;
u16 cfg;
host = mmc_priv(mmc);
spin_lock_irqsave(&host->lock, flags);
if (ios->clock) {
unsigned long sys_clk, ios_clk;
unsigned char clk_div;
ios_clk = 2 * ios->clock;
sys_clk = get_sclk();
clk_div = sys_clk / ios_clk;
if (sys_clk % ios_clk == 0)
clk_div -= 1;
clk_div = min_t(unsigned char, clk_div, 0xFF);
clk_ctl |= clk_div;
clk_ctl |= CLK_E;
host->clk_div = clk_div;
} else
sdh_stop_clock(host);
if (ios->bus_mode == MMC_BUSMODE_OPENDRAIN)
#ifdef CONFIG_SDH_BFIN_MISSING_CMD_PULLUP_WORKAROUND
pwr_ctl |= ROD_CTL;
#else
pwr_ctl |= SD_CMD_OD | ROD_CTL;
#endif
if (ios->bus_width == MMC_BUS_WIDTH_4) {
cfg = bfin_read_SDH_CFG();
cfg &= ~PD_SDDAT3;
cfg |= PUP_SDDAT3;
/* Enable 4 bit SDIO */
cfg |= (SD4E | MWE);
bfin_write_SDH_CFG(cfg);
clk_ctl |= WIDE_BUS;
} else {
cfg = bfin_read_SDH_CFG();
cfg |= MWE;
bfin_write_SDH_CFG(cfg);
}
bfin_write_SDH_CLK_CTL(clk_ctl);
host->power_mode = ios->power_mode;
if (ios->power_mode == MMC_POWER_ON)
pwr_ctl |= PWR_ON;
bfin_write_SDH_PWR_CTL(pwr_ctl);
SSYNC();
spin_unlock_irqrestore(&host->lock, flags);
dev_dbg(mmc_dev(host->mmc), "SDH: clk_div = 0x%x actual clock:%ld expected clock:%d\n",
host->clk_div,
host->clk_div ? get_sclk() / (2 * (host->clk_div + 1)) : 0,
ios->clock);
}
static const struct mmc_host_ops sdh_ops = {
.request = sdh_request,
.set_ios = sdh_set_ios,
};
static irqreturn_t sdh_dma_irq(int irq, void *devid)
{
struct sdh_host *host = devid;
dev_dbg(mmc_dev(host->mmc), "%s enter, irq_stat: 0x%04x\n", __func__,
get_dma_curr_irqstat(host->dma_ch));
clear_dma_irqstat(host->dma_ch);
SSYNC();
return IRQ_HANDLED;
}
static irqreturn_t sdh_stat_irq(int irq, void *devid)
{
struct sdh_host *host = devid;
unsigned int status;
int handled = 0;
dev_dbg(mmc_dev(host->mmc), "%s enter\n", __func__);
status = bfin_read_SDH_E_STATUS();
if (status & SD_CARD_DET) {
mmc_detect_change(host->mmc, 0);
bfin_write_SDH_E_STATUS(SD_CARD_DET);
}
status = bfin_read_SDH_STATUS();
if (status & (CMD_SENT | CMD_RESP_END | CMD_TIME_OUT | CMD_CRC_FAIL)) {
handled |= sdh_cmd_done(host, status);
bfin_write_SDH_STATUS_CLR(CMD_SENT_STAT | CMD_RESP_END_STAT | \
CMD_TIMEOUT_STAT | CMD_CRC_FAIL_STAT);
SSYNC();
}
status = bfin_read_SDH_STATUS();
if (status & (DAT_END | DAT_TIME_OUT | DAT_CRC_FAIL | RX_OVERRUN | TX_UNDERRUN))
handled |= sdh_data_done(host, status);
dev_dbg(mmc_dev(host->mmc), "%s exit\n\n", __func__);
return IRQ_RETVAL(handled);
}
static int __devinit sdh_probe(struct platform_device *pdev)
{
struct mmc_host *mmc;
struct sdh_host *host;
struct bfin_sd_host *drv_data = get_sdh_data(pdev);
int ret;
if (!drv_data) {
dev_err(&pdev->dev, "missing platform driver data\n");
ret = -EINVAL;
goto out;
}
mmc = mmc_alloc_host(sizeof(*mmc), &pdev->dev);
if (!mmc) {
ret = -ENOMEM;
goto out;
}
mmc->ops = &sdh_ops;
mmc->max_phys_segs = 32;
mmc->max_seg_size = 1 << 16;
mmc->max_blk_size = 1 << 11;
mmc->max_blk_count = 1 << 11;
mmc->max_req_size = PAGE_SIZE;
mmc->ocr_avail = MMC_VDD_32_33 | MMC_VDD_33_34;
mmc->f_max = get_sclk();
mmc->f_min = mmc->f_max >> 9;
mmc->caps = MMC_CAP_4_BIT_DATA | MMC_CAP_NEEDS_POLL;
host = mmc_priv(mmc);
host->mmc = mmc;
spin_lock_init(&host->lock);
host->irq = drv_data->irq_int0;
host->dma_ch = drv_data->dma_chan;
ret = request_dma(host->dma_ch, DRIVER_NAME "DMA");
if (ret) {
dev_err(&pdev->dev, "unable to request DMA channel\n");
goto out1;
}
ret = set_dma_callback(host->dma_ch, sdh_dma_irq, host);
if (ret) {
dev_err(&pdev->dev, "unable to request DMA irq\n");
goto out2;
}
host->sg_cpu = dma_alloc_coherent(&pdev->dev, PAGE_SIZE, &host->sg_dma, GFP_KERNEL);
if (host->sg_cpu == NULL) {
ret = -ENOMEM;
goto out2;
}
platform_set_drvdata(pdev, mmc);
mmc_add_host(mmc);
ret = request_irq(host->irq, sdh_stat_irq, 0, "SDH Status IRQ", host);
if (ret) {
dev_err(&pdev->dev, "unable to request status irq\n");
goto out3;
}
ret = peripheral_request_list(drv_data->pin_req, DRIVER_NAME);
if (ret) {
dev_err(&pdev->dev, "unable to request peripheral pins\n");
goto out4;
}
#if defined(CONFIG_BF54x)
/* Secure Digital Host shares DMA with Nand controller */
bfin_write_DMAC1_PERIMUX(bfin_read_DMAC1_PERIMUX() | 0x1);
#endif
bfin_write_SDH_CFG(bfin_read_SDH_CFG() | CLKS_EN);
SSYNC();
/* Disable card inserting detection pin. set MMC_CAP_NEES_POLL, and
* mmc stack will do the detection.
*/
bfin_write_SDH_CFG((bfin_read_SDH_CFG() & 0x1F) | (PUP_SDDAT | PUP_SDDAT3));
SSYNC();
return 0;
out4:
free_irq(host->irq, host);
out3:
mmc_remove_host(mmc);
dma_free_coherent(&pdev->dev, PAGE_SIZE, host->sg_cpu, host->sg_dma);
out2:
free_dma(host->dma_ch);
out1:
mmc_free_host(mmc);
out:
return ret;
}
static int __devexit sdh_remove(struct platform_device *pdev)
{
struct mmc_host *mmc = platform_get_drvdata(pdev);
platform_set_drvdata(pdev, NULL);
if (mmc) {
struct sdh_host *host = mmc_priv(mmc);
mmc_remove_host(mmc);
sdh_stop_clock(host);
free_irq(host->irq, host);
free_dma(host->dma_ch);
dma_free_coherent(&pdev->dev, PAGE_SIZE, host->sg_cpu, host->sg_dma);
mmc_free_host(mmc);
}
return 0;
}
#ifdef CONFIG_PM
static int sdh_suspend(struct platform_device *dev, pm_message_t state)
{
struct mmc_host *mmc = platform_get_drvdata(dev);
struct bfin_sd_host *drv_data = get_sdh_data(dev);
int ret = 0;
if (mmc)
ret = mmc_suspend_host(mmc);
bfin_write_SDH_PWR_CTL(bfin_read_SDH_PWR_CTL() & ~PWR_ON);
peripheral_free_list(drv_data->pin_req);
return ret;
}
static int sdh_resume(struct platform_device *dev)
{
struct mmc_host *mmc = platform_get_drvdata(dev);
struct bfin_sd_host *drv_data = get_sdh_data(dev);
int ret = 0;
ret = peripheral_request_list(drv_data->pin_req, DRIVER_NAME);
if (ret) {
dev_err(&dev->dev, "unable to request peripheral pins\n");
return ret;
}
bfin_write_SDH_PWR_CTL(bfin_read_SDH_PWR_CTL() | PWR_ON);
#if defined(CONFIG_BF54x)
/* Secure Digital Host shares DMA with Nand controller */
bfin_write_DMAC1_PERIMUX(bfin_read_DMAC1_PERIMUX() | 0x1);
#endif
bfin_write_SDH_CFG(bfin_read_SDH_CFG() | CLKS_EN);
SSYNC();
bfin_write_SDH_CFG((bfin_read_SDH_CFG() & 0x1F) | (PUP_SDDAT | PUP_SDDAT3));
SSYNC();
if (mmc)
ret = mmc_resume_host(mmc);
return ret;
}
#else
# define sdh_suspend NULL
# define sdh_resume NULL
#endif
static struct platform_driver sdh_driver = {
.probe = sdh_probe,
.remove = __devexit_p(sdh_remove),
.suspend = sdh_suspend,
.resume = sdh_resume,
.driver = {
.name = DRIVER_NAME,
},
};
static int __init sdh_init(void)
{
return platform_driver_register(&sdh_driver);
}
module_init(sdh_init);
static void __exit sdh_exit(void)
{
platform_driver_unregister(&sdh_driver);
}
module_exit(sdh_exit);
MODULE_DESCRIPTION("Blackfin Secure Digital Host Driver");
MODULE_AUTHOR("Cliff Cai, Roy Huang");
MODULE_LICENSE("GPL");
| gpl-2.0 |
ricardon/efi | arch/powerpc/platforms/powermac/feature.c | 1348 | 82090 | /*
* 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_PPC64
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_PPC64 */
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_PPC64
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_PPC64 */
#ifndef CONFIG_PPC64
#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_PPC64 */
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_PPC64
/* 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_PPC64 */
/* 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_PPC64 */
static struct pmac_mb_def pmac_mb_defs[] = {
#ifndef CONFIG_PPC64
/*
* 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_PPC64 */
{ "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_PPC64 */
};
/*
* 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_PPC64
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_PPC64 */
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_PPC64 */
default:
ret = -ENODEV;
goto done;
}
found:
#ifndef CONFIG_PPC64
/* 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_PPC64 */
powersave_nap = 1;
#endif /* CONFIG_PPC64 */
/* 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_PPC64
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
*/
for_each_node_by_name(np, "ethernet")
if (of_device_is_compatible(np, "K2-GMAC"))
g5_gmac_enable(np, 0, 1);
/* 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.
*/
for_each_node_by_name(np, "firewire") {
if (of_device_is_compatible(np, "pci106b,5811")) {
macio_chips[0].flags |= MACIO_FLAG_FW_SUPPORTED;
g5_fw_enable(np, 0, 1);
}
}
}
#else /* CONFIG_PPC64 */
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
*/
for_each_node_by_name(np, "ethernet") {
if (np->parent
&& of_device_is_compatible(np->parent, "uni-north")
&& of_device_is_compatible(np, "gmac"))
core99_gmac_enable(np, 0, 1);
}
/* 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.
*/
for_each_node_by_name(np, "firewire") {
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);
}
}
/* Enable ATA-100 before PCI probe. */
np = of_find_node_by_name(NULL, "ata-6");
for_each_node_by_name(np, "ata-6") {
if (np->parent
&& of_device_is_compatible(np->parent, "uni-north")
&& of_device_is_compatible(np, "kauai-ata")) {
core99_ata100_enable(np, 1);
}
}
/* 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_PPC64 */
/* 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 |
endocode/linux | drivers/media/platform/exynos4-is/fimc-is-errno.c | 1860 | 10004 | /*
* Samsung Exynos4 SoC series FIMC-IS slave interface driver
*
* Error log interface functions
*
* Copyright (C) 2011 - 2013 Samsung Electronics Co., Ltd.
*
* Authors: Younghwan Joo <yhwan.joo@samsung.com>
* Sylwester Nawrocki <s.nawrocki@samsung.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include "fimc-is-errno.h"
const char *fimc_is_param_strerr(unsigned int error)
{
switch (error) {
case ERROR_COMMON_CMD:
return "ERROR_COMMON_CMD: Invalid Command";
case ERROR_COMMON_PARAMETER:
return "ERROR_COMMON_PARAMETER: Invalid Parameter";
case ERROR_COMMON_SETFILE_LOAD:
return "ERROR_COMMON_SETFILE_LOAD: Illegal Setfile Loading";
case ERROR_COMMON_SETFILE_ADJUST:
return "ERROR_COMMON_SETFILE_ADJUST: Setfile isn't adjusted";
case ERROR_COMMON_SETFILE_INDEX:
return "ERROR_COMMON_SETFILE_INDEX: Invalid setfile index";
case ERROR_COMMON_INPUT_PATH:
return "ERROR_COMMON_INPUT_PATH: Input path can be changed in ready state";
case ERROR_COMMON_INPUT_INIT:
return "ERROR_COMMON_INPUT_INIT: IP can not start if input path is not set";
case ERROR_COMMON_OUTPUT_PATH:
return "ERROR_COMMON_OUTPUT_PATH: Output path can be changed in ready state (stop)";
case ERROR_COMMON_OUTPUT_INIT:
return "ERROR_COMMON_OUTPUT_INIT: IP can not start if output path is not set";
case ERROR_CONTROL_BYPASS:
return "ERROR_CONTROL_BYPASS";
case ERROR_OTF_INPUT_FORMAT:
return "ERROR_OTF_INPUT_FORMAT: Invalid format (DRC: YUV444, FD: YUV444, 422, 420)";
case ERROR_OTF_INPUT_WIDTH:
return "ERROR_OTF_INPUT_WIDTH: Invalid width (DRC: 128~8192, FD: 32~8190)";
case ERROR_OTF_INPUT_HEIGHT:
return "ERROR_OTF_INPUT_HEIGHT: Invalid bit-width (DRC: 8~12bits, FD: 8bit)";
case ERROR_OTF_INPUT_BIT_WIDTH:
return "ERROR_OTF_INPUT_BIT_WIDTH: Invalid bit-width (DRC: 8~12bits, FD: 8bit)";
case ERROR_DMA_INPUT_WIDTH:
return "ERROR_DMA_INPUT_WIDTH: Invalid width (DRC: 128~8192, FD: 32~8190)";
case ERROR_DMA_INPUT_HEIGHT:
return "ERROR_DMA_INPUT_HEIGHT: Invalid height (DRC: 64~8192, FD: 16~8190)";
case ERROR_DMA_INPUT_FORMAT:
return "ERROR_DMA_INPUT_FORMAT: Invalid format (DRC: YUV444 or YUV422, FD: YUV444,422,420)";
case ERROR_DMA_INPUT_BIT_WIDTH:
return "ERROR_DMA_INPUT_BIT_WIDTH: Invalid bit-width (DRC: 8~12bits, FD: 8bit)";
case ERROR_DMA_INPUT_ORDER:
return "ERROR_DMA_INPUT_ORDER: Invalid order(DRC: YYCbCr,YCbYCr,FD:NO,YYCbCr,YCbYCr,CbCr,CrCb)";
case ERROR_DMA_INPUT_PLANE:
return "ERROR_DMA_INPUT_PLANE: Invalid palne (DRC: 3, FD: 1, 2, 3)";
case ERROR_OTF_OUTPUT_WIDTH:
return "ERROR_OTF_OUTPUT_WIDTH: Invalid width (DRC: 128~8192)";
case ERROR_OTF_OUTPUT_HEIGHT:
return "ERROR_OTF_OUTPUT_HEIGHT: Invalid height (DRC: 64~8192)";
case ERROR_OTF_OUTPUT_FORMAT:
return "ERROR_OTF_OUTPUT_FORMAT: Invalid format (DRC: YUV444)";
case ERROR_OTF_OUTPUT_BIT_WIDTH:
return "ERROR_OTF_OUTPUT_BIT_WIDTH: Invalid bit-width (DRC: 8~12bits, FD: 8bit)";
case ERROR_DMA_OUTPUT_WIDTH:
return "ERROR_DMA_OUTPUT_WIDTH";
case ERROR_DMA_OUTPUT_HEIGHT:
return "ERROR_DMA_OUTPUT_HEIGHT";
case ERROR_DMA_OUTPUT_FORMAT:
return "ERROR_DMA_OUTPUT_FORMAT";
case ERROR_DMA_OUTPUT_BIT_WIDTH:
return "ERROR_DMA_OUTPUT_BIT_WIDTH";
case ERROR_DMA_OUTPUT_PLANE:
return "ERROR_DMA_OUTPUT_PLANE";
case ERROR_DMA_OUTPUT_ORDER:
return "ERROR_DMA_OUTPUT_ORDER";
/* Sensor Error(100~199) */
case ERROR_SENSOR_I2C_FAIL:
return "ERROR_SENSOR_I2C_FAIL";
case ERROR_SENSOR_INVALID_FRAMERATE:
return "ERROR_SENSOR_INVALID_FRAMERATE";
case ERROR_SENSOR_INVALID_EXPOSURETIME:
return "ERROR_SENSOR_INVALID_EXPOSURETIME";
case ERROR_SENSOR_INVALID_SIZE:
return "ERROR_SENSOR_INVALID_SIZE";
case ERROR_SENSOR_INVALID_SETTING:
return "ERROR_SENSOR_INVALID_SETTING";
case ERROR_SENSOR_ACTURATOR_INIT_FAIL:
return "ERROR_SENSOR_ACTURATOR_INIT_FAIL";
case ERROR_SENSOR_INVALID_AF_POS:
return "ERROR_SENSOR_INVALID_AF_POS";
case ERROR_SENSOR_UNSUPPORT_FUNC:
return "ERROR_SENSOR_UNSUPPORT_FUNC";
case ERROR_SENSOR_UNSUPPORT_PERI:
return "ERROR_SENSOR_UNSUPPORT_PERI";
case ERROR_SENSOR_UNSUPPORT_AF:
return "ERROR_SENSOR_UNSUPPORT_AF";
/* ISP Error (200~299) */
case ERROR_ISP_AF_BUSY:
return "ERROR_ISP_AF_BUSY";
case ERROR_ISP_AF_INVALID_COMMAND:
return "ERROR_ISP_AF_INVALID_COMMAND";
case ERROR_ISP_AF_INVALID_MODE:
return "ERROR_ISP_AF_INVALID_MODE";
/* DRC Error (300~399) */
/* FD Error (400~499) */
case ERROR_FD_CONFIG_MAX_NUMBER_STATE:
return "ERROR_FD_CONFIG_MAX_NUMBER_STATE";
case ERROR_FD_CONFIG_MAX_NUMBER_INVALID:
return "ERROR_FD_CONFIG_MAX_NUMBER_INVALID";
case ERROR_FD_CONFIG_YAW_ANGLE_STATE:
return "ERROR_FD_CONFIG_YAW_ANGLE_STATE";
case ERROR_FD_CONFIG_YAW_ANGLE_INVALID:
return "ERROR_FD_CONFIG_YAW_ANGLE_INVALID\n";
case ERROR_FD_CONFIG_ROLL_ANGLE_STATE:
return "ERROR_FD_CONFIG_ROLL_ANGLE_STATE";
case ERROR_FD_CONFIG_ROLL_ANGLE_INVALID:
return "ERROR_FD_CONFIG_ROLL_ANGLE_INVALID";
case ERROR_FD_CONFIG_SMILE_MODE_INVALID:
return "ERROR_FD_CONFIG_SMILE_MODE_INVALID";
case ERROR_FD_CONFIG_BLINK_MODE_INVALID:
return "ERROR_FD_CONFIG_BLINK_MODE_INVALID";
case ERROR_FD_CONFIG_EYES_DETECT_INVALID:
return "ERROR_FD_CONFIG_EYES_DETECT_INVALID";
case ERROR_FD_CONFIG_MOUTH_DETECT_INVALID:
return "ERROR_FD_CONFIG_MOUTH_DETECT_INVALID";
case ERROR_FD_CONFIG_ORIENTATION_STATE:
return "ERROR_FD_CONFIG_ORIENTATION_STATE";
case ERROR_FD_CONFIG_ORIENTATION_INVALID:
return "ERROR_FD_CONFIG_ORIENTATION_INVALID";
case ERROR_FD_CONFIG_ORIENTATION_VALUE_INVALID:
return "ERROR_FD_CONFIG_ORIENTATION_VALUE_INVALID";
case ERROR_FD_RESULT:
return "ERROR_FD_RESULT";
case ERROR_FD_MODE:
return "ERROR_FD_MODE";
default:
return "Unknown";
}
}
const char *fimc_is_strerr(unsigned int error)
{
error &= ~IS_ERROR_TIME_OUT_FLAG;
switch (error) {
/* General */
case IS_ERROR_INVALID_COMMAND:
return "IS_ERROR_INVALID_COMMAND";
case IS_ERROR_REQUEST_FAIL:
return "IS_ERROR_REQUEST_FAIL";
case IS_ERROR_INVALID_SCENARIO:
return "IS_ERROR_INVALID_SCENARIO";
case IS_ERROR_INVALID_SENSORID:
return "IS_ERROR_INVALID_SENSORID";
case IS_ERROR_INVALID_MODE_CHANGE:
return "IS_ERROR_INVALID_MODE_CHANGE";
case IS_ERROR_INVALID_MAGIC_NUMBER:
return "IS_ERROR_INVALID_MAGIC_NUMBER";
case IS_ERROR_INVALID_SETFILE_HDR:
return "IS_ERROR_INVALID_SETFILE_HDR";
case IS_ERROR_BUSY:
return "IS_ERROR_BUSY";
case IS_ERROR_SET_PARAMETER:
return "IS_ERROR_SET_PARAMETER";
case IS_ERROR_INVALID_PATH:
return "IS_ERROR_INVALID_PATH";
case IS_ERROR_OPEN_SENSOR_FAIL:
return "IS_ERROR_OPEN_SENSOR_FAIL";
case IS_ERROR_ENTRY_MSG_THREAD_DOWN:
return "IS_ERROR_ENTRY_MSG_THREAD_DOWN";
case IS_ERROR_ISP_FRAME_END_NOT_DONE:
return "IS_ERROR_ISP_FRAME_END_NOT_DONE";
case IS_ERROR_DRC_FRAME_END_NOT_DONE:
return "IS_ERROR_DRC_FRAME_END_NOT_DONE";
case IS_ERROR_SCALERC_FRAME_END_NOT_DONE:
return "IS_ERROR_SCALERC_FRAME_END_NOT_DONE";
case IS_ERROR_ODC_FRAME_END_NOT_DONE:
return "IS_ERROR_ODC_FRAME_END_NOT_DONE";
case IS_ERROR_DIS_FRAME_END_NOT_DONE:
return "IS_ERROR_DIS_FRAME_END_NOT_DONE";
case IS_ERROR_TDNR_FRAME_END_NOT_DONE:
return "IS_ERROR_TDNR_FRAME_END_NOT_DONE";
case IS_ERROR_SCALERP_FRAME_END_NOT_DONE:
return "IS_ERROR_SCALERP_FRAME_END_NOT_DONE";
case IS_ERROR_WAIT_STREAM_OFF_NOT_DONE:
return "IS_ERROR_WAIT_STREAM_OFF_NOT_DONE";
case IS_ERROR_NO_MSG_IS_RECEIVED:
return "IS_ERROR_NO_MSG_IS_RECEIVED";
case IS_ERROR_SENSOR_MSG_FAIL:
return "IS_ERROR_SENSOR_MSG_FAIL";
case IS_ERROR_ISP_MSG_FAIL:
return "IS_ERROR_ISP_MSG_FAIL";
case IS_ERROR_DRC_MSG_FAIL:
return "IS_ERROR_DRC_MSG_FAIL";
case IS_ERROR_LHFD_MSG_FAIL:
return "IS_ERROR_LHFD_MSG_FAIL";
case IS_ERROR_UNKNOWN:
return "IS_ERROR_UNKNOWN";
/* Sensor */
case IS_ERROR_SENSOR_PWRDN_FAIL:
return "IS_ERROR_SENSOR_PWRDN_FAIL";
/* ISP */
case IS_ERROR_ISP_PWRDN_FAIL:
return "IS_ERROR_ISP_PWRDN_FAIL";
case IS_ERROR_ISP_MULTIPLE_INPUT:
return "IS_ERROR_ISP_MULTIPLE_INPUT";
case IS_ERROR_ISP_ABSENT_INPUT:
return "IS_ERROR_ISP_ABSENT_INPUT";
case IS_ERROR_ISP_ABSENT_OUTPUT:
return "IS_ERROR_ISP_ABSENT_OUTPUT";
case IS_ERROR_ISP_NONADJACENT_OUTPUT:
return "IS_ERROR_ISP_NONADJACENT_OUTPUT";
case IS_ERROR_ISP_FORMAT_MISMATCH:
return "IS_ERROR_ISP_FORMAT_MISMATCH";
case IS_ERROR_ISP_WIDTH_MISMATCH:
return "IS_ERROR_ISP_WIDTH_MISMATCH";
case IS_ERROR_ISP_HEIGHT_MISMATCH:
return "IS_ERROR_ISP_HEIGHT_MISMATCH";
case IS_ERROR_ISP_BITWIDTH_MISMATCH:
return "IS_ERROR_ISP_BITWIDTH_MISMATCH";
case IS_ERROR_ISP_FRAME_END_TIME_OUT:
return "IS_ERROR_ISP_FRAME_END_TIME_OUT";
/* DRC */
case IS_ERROR_DRC_PWRDN_FAIL:
return "IS_ERROR_DRC_PWRDN_FAIL";
case IS_ERROR_DRC_MULTIPLE_INPUT:
return "IS_ERROR_DRC_MULTIPLE_INPUT";
case IS_ERROR_DRC_ABSENT_INPUT:
return "IS_ERROR_DRC_ABSENT_INPUT";
case IS_ERROR_DRC_NONADJACENT_INPUT:
return "IS_ERROR_DRC_NONADJACENT_INPUT";
case IS_ERROR_DRC_ABSENT_OUTPUT:
return "IS_ERROR_DRC_ABSENT_OUTPUT";
case IS_ERROR_DRC_NONADJACENT_OUTPUT:
return "IS_ERROR_DRC_NONADJACENT_OUTPUT";
case IS_ERROR_DRC_FORMAT_MISMATCH:
return "IS_ERROR_DRC_FORMAT_MISMATCH";
case IS_ERROR_DRC_WIDTH_MISMATCH:
return "IS_ERROR_DRC_WIDTH_MISMATCH";
case IS_ERROR_DRC_HEIGHT_MISMATCH:
return "IS_ERROR_DRC_HEIGHT_MISMATCH";
case IS_ERROR_DRC_BITWIDTH_MISMATCH:
return "IS_ERROR_DRC_BITWIDTH_MISMATCH";
case IS_ERROR_DRC_FRAME_END_TIME_OUT:
return "IS_ERROR_DRC_FRAME_END_TIME_OUT";
/* FD */
case IS_ERROR_FD_PWRDN_FAIL:
return "IS_ERROR_FD_PWRDN_FAIL";
case IS_ERROR_FD_MULTIPLE_INPUT:
return "IS_ERROR_FD_MULTIPLE_INPUT";
case IS_ERROR_FD_ABSENT_INPUT:
return "IS_ERROR_FD_ABSENT_INPUT";
case IS_ERROR_FD_NONADJACENT_INPUT:
return "IS_ERROR_FD_NONADJACENT_INPUT";
case IS_ERROR_LHFD_FRAME_END_TIME_OUT:
return "IS_ERROR_LHFD_FRAME_END_TIME_OUT";
default:
return "Unknown";
}
}
| gpl-2.0 |
robin-banks/android_kernel_htc_msm8974 | arch/arm/mach-msm/msm_watchdog.c | 2116 | 12247 | /* Copyright (c) 2010-2013, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/delay.h>
#include <linux/workqueue.h>
#include <linux/pm.h>
#include <linux/mfd/pmic8058.h>
#include <linux/jiffies.h>
#include <linux/suspend.h>
#include <linux/percpu.h>
#include <linux/interrupt.h>
#include <linux/reboot.h>
#include <asm/fiq.h>
#include <asm/hardware/gic.h>
#include <mach/msm_iomap.h>
#include <asm/mach-types.h>
#include <asm/cacheflush.h>
#include <mach/scm.h>
#include <mach/socinfo.h>
#include "msm_watchdog.h"
#include "timer.h"
#define MODULE_NAME "msm_watchdog"
#define TCSR_WDT_CFG 0x30
#define WDT_RST 0x0
#define WDT_EN 0x8
#define WDT_STS 0xC
#define WDT_BARK_TIME 0x14
#define WDT_BITE_TIME 0x24
#define WDT_HZ 32768
struct msm_watchdog_dump msm_dump_cpu_ctx;
static void __iomem *msm_wdt_base;
static unsigned long delay_time;
static unsigned long bark_time;
static unsigned long long last_pet;
static bool has_vic;
static unsigned int msm_wdog_irq;
/*
* On the kernel command line specify
* msm_watchdog.enable=1 to enable the watchdog
* By default watchdog is turned on
*/
static int enable = 1;
module_param(enable, int, 0);
/*
* Watchdog bark reboot timeout in seconds.
* Can be specified in kernel command line.
*/
static int reboot_bark_timeout = 22;
module_param(reboot_bark_timeout, int, 0644);
/*
* If the watchdog is enabled at bootup (enable=1),
* the runtime_disable sysfs node at
* /sys/module/msm_watchdog/runtime_disable
* can be used to deactivate the watchdog.
* This is a one-time setting. The watchdog
* cannot be re-enabled once it is disabled.
*/
static int runtime_disable;
static DEFINE_MUTEX(disable_lock);
static int wdog_enable_set(const char *val, struct kernel_param *kp);
module_param_call(runtime_disable, wdog_enable_set, param_get_int,
&runtime_disable, 0644);
/*
* On the kernel command line specify msm_watchdog.appsbark=1 to handle
* watchdog barks in Linux. By default barks are processed by the secure side.
*/
static int appsbark;
module_param(appsbark, int, 0);
static int appsbark_fiq;
/*
* Use /sys/module/msm_watchdog/parameters/print_all_stacks
* to control whether stacks of all running
* processes are printed when a wdog bark is received.
*/
static int print_all_stacks = 1;
module_param(print_all_stacks, int, S_IRUGO | S_IWUSR);
/* Area for context dump in secure mode */
static void *scm_regsave;
static struct msm_watchdog_pdata __percpu **percpu_pdata;
static void pet_watchdog_work(struct work_struct *work);
static void init_watchdog_work(struct work_struct *work);
static DECLARE_DELAYED_WORK(dogwork_struct, pet_watchdog_work);
static DECLARE_WORK(init_dogwork_struct, init_watchdog_work);
/* Called from the FIQ bark handler */
void msm_wdog_bark_fin(void)
{
flush_cache_all();
pr_crit("\nApps Watchdog bark received - Calling Panic\n");
panic("Apps Watchdog Bark received\n");
}
static int msm_watchdog_suspend(struct device *dev)
{
if (!enable)
return 0;
__raw_writel(1, msm_wdt_base + WDT_RST);
__raw_writel(0, msm_wdt_base + WDT_EN);
mb();
return 0;
}
static int msm_watchdog_resume(struct device *dev)
{
if (!enable)
return 0;
__raw_writel(1, msm_wdt_base + WDT_EN);
__raw_writel(1, msm_wdt_base + WDT_RST);
mb();
return 0;
}
static int panic_wdog_handler(struct notifier_block *this,
unsigned long event, void *ptr)
{
if (panic_timeout == 0) {
__raw_writel(0, msm_wdt_base + WDT_EN);
mb();
} else {
__raw_writel(WDT_HZ * (panic_timeout + 4),
msm_wdt_base + WDT_BARK_TIME);
__raw_writel(WDT_HZ * (panic_timeout + 4),
msm_wdt_base + WDT_BITE_TIME);
__raw_writel(1, msm_wdt_base + WDT_RST);
}
return NOTIFY_DONE;
}
static struct notifier_block panic_blk = {
.notifier_call = panic_wdog_handler,
};
#define get_sclk_hz(t_ms) ((t_ms / 1000) * WDT_HZ)
#define get_reboot_bark_timeout(t_s) ((t_s * MSEC_PER_SEC) < bark_time ? \
get_sclk_hz(bark_time) : get_sclk_hz(t_s * MSEC_PER_SEC))
static int msm_watchdog_reboot_notifier(struct notifier_block *this,
unsigned long code, void *unused)
{
u64 timeout = get_reboot_bark_timeout(reboot_bark_timeout);
__raw_writel(timeout, msm_wdt_base + WDT_BARK_TIME);
__raw_writel(timeout + 3 * WDT_HZ,
msm_wdt_base + WDT_BITE_TIME);
__raw_writel(1, msm_wdt_base + WDT_RST);
return NOTIFY_DONE;
}
static struct notifier_block msm_reboot_notifier = {
.notifier_call = msm_watchdog_reboot_notifier,
};
struct wdog_disable_work_data {
struct work_struct work;
struct completion complete;
};
static void wdog_disable_work(struct work_struct *work)
{
struct wdog_disable_work_data *work_data =
container_of(work, struct wdog_disable_work_data, work);
__raw_writel(0, msm_wdt_base + WDT_EN);
mb();
if (has_vic) {
free_irq(msm_wdog_irq, 0);
} else {
disable_percpu_irq(msm_wdog_irq);
if (!appsbark_fiq) {
free_percpu_irq(msm_wdog_irq,
percpu_pdata);
free_percpu(percpu_pdata);
}
}
enable = 0;
atomic_notifier_chain_unregister(&panic_notifier_list, &panic_blk);
unregister_reboot_notifier(&msm_reboot_notifier);
cancel_delayed_work(&dogwork_struct);
/* may be suspended after the first write above */
__raw_writel(0, msm_wdt_base + WDT_EN);
complete(&work_data->complete);
pr_info("MSM Watchdog deactivated.\n");
}
static int wdog_enable_set(const char *val, struct kernel_param *kp)
{
int ret = 0;
int old_val = runtime_disable;
struct wdog_disable_work_data work_data;
mutex_lock(&disable_lock);
if (!enable) {
printk(KERN_INFO "MSM Watchdog is not active.\n");
ret = -EINVAL;
goto done;
}
ret = param_set_int(val, kp);
if (ret)
goto done;
if (runtime_disable == 1) {
if (old_val)
goto done;
init_completion(&work_data.complete);
INIT_WORK_ONSTACK(&work_data.work, wdog_disable_work);
schedule_work_on(0, &work_data.work);
wait_for_completion(&work_data.complete);
} else {
runtime_disable = old_val;
ret = -EINVAL;
}
done:
mutex_unlock(&disable_lock);
return ret;
}
unsigned min_slack_ticks = UINT_MAX;
unsigned long long min_slack_ns = ULLONG_MAX;
void pet_watchdog(void)
{
int slack;
unsigned long long time_ns;
unsigned long long slack_ns;
unsigned long long bark_time_ns = bark_time * 1000000ULL;
if (!enable)
return;
slack = __raw_readl(msm_wdt_base + WDT_STS) >> 3;
slack = ((bark_time*WDT_HZ)/1000) - slack;
if (slack < min_slack_ticks)
min_slack_ticks = slack;
__raw_writel(1, msm_wdt_base + WDT_RST);
time_ns = sched_clock();
slack_ns = (last_pet + bark_time_ns) - time_ns;
if (slack_ns < min_slack_ns)
min_slack_ns = slack_ns;
last_pet = time_ns;
}
static void pet_watchdog_work(struct work_struct *work)
{
pet_watchdog();
if (enable)
schedule_delayed_work_on(0, &dogwork_struct, delay_time);
}
static irqreturn_t wdog_bark_handler(int irq, void *dev_id)
{
unsigned long nanosec_rem;
unsigned long long t = sched_clock();
struct task_struct *tsk;
nanosec_rem = do_div(t, 1000000000);
printk(KERN_INFO "Watchdog bark! Now = %lu.%06lu\n", (unsigned long) t,
nanosec_rem / 1000);
nanosec_rem = do_div(last_pet, 1000000000);
printk(KERN_INFO "Watchdog last pet at %lu.%06lu\n", (unsigned long)
last_pet, nanosec_rem / 1000);
if (print_all_stacks) {
/* Suspend wdog until all stacks are printed */
msm_watchdog_suspend(NULL);
printk(KERN_INFO "Stack trace dump:\n");
for_each_process(tsk) {
printk(KERN_INFO "\nPID: %d, Name: %s\n",
tsk->pid, tsk->comm);
show_stack(tsk, NULL);
}
msm_watchdog_resume(NULL);
}
panic("Apps watchdog bark received!");
return IRQ_HANDLED;
}
#define SCM_SET_REGSAVE_CMD 0x2
static void configure_bark_dump(void)
{
int ret;
struct {
unsigned addr;
int len;
} cmd_buf;
if (!appsbark) {
scm_regsave = (void *)__get_free_page(GFP_KERNEL);
if (scm_regsave) {
cmd_buf.addr = __pa(scm_regsave);
cmd_buf.len = PAGE_SIZE;
ret = scm_call(SCM_SVC_UTIL, SCM_SET_REGSAVE_CMD,
&cmd_buf, sizeof(cmd_buf), NULL, 0);
if (ret)
pr_err("Setting register save address failed.\n"
"Registers won't be dumped on a dog "
"bite\n");
} else {
pr_err("Allocating register save space failed\n"
"Registers won't be dumped on a dog bite\n");
/*
* No need to bail if allocation fails. Simply don't
* send the command, and the secure side will reset
* without saving registers.
*/
}
}
}
struct fiq_handler wdog_fh = {
.name = MODULE_NAME,
};
static void init_watchdog_work(struct work_struct *work)
{
u64 timeout = (bark_time * WDT_HZ)/1000;
void *stack;
int ret;
if (has_vic) {
ret = request_irq(msm_wdog_irq, wdog_bark_handler, 0,
"apps_wdog_bark", NULL);
if (ret)
return;
} else if (appsbark_fiq) {
claim_fiq(&wdog_fh);
set_fiq_handler(&msm_wdog_fiq_start, msm_wdog_fiq_length);
stack = (void *)__get_free_pages(GFP_KERNEL, THREAD_SIZE_ORDER);
if (!stack) {
pr_info("No free pages available - %s fails\n",
__func__);
return;
}
msm_wdog_fiq_setup(stack);
gic_set_irq_secure(msm_wdog_irq);
} else {
percpu_pdata = alloc_percpu(struct msm_watchdog_pdata *);
if (!percpu_pdata) {
pr_err("%s: memory allocation failed for percpu data\n",
__func__);
return;
}
/* Must request irq before sending scm command */
ret = request_percpu_irq(msm_wdog_irq,
wdog_bark_handler, "apps_wdog_bark", percpu_pdata);
if (ret) {
free_percpu(percpu_pdata);
return;
}
}
configure_bark_dump();
__raw_writel(timeout, msm_wdt_base + WDT_BARK_TIME);
__raw_writel(timeout + 3*WDT_HZ, msm_wdt_base + WDT_BITE_TIME);
schedule_delayed_work_on(0, &dogwork_struct, delay_time);
atomic_notifier_chain_register(&panic_notifier_list,
&panic_blk);
ret = register_reboot_notifier(&msm_reboot_notifier);
if (ret)
pr_err("Failed to register reboot notifier\n");
__raw_writel(1, msm_wdt_base + WDT_EN);
__raw_writel(1, msm_wdt_base + WDT_RST);
last_pet = sched_clock();
if (!has_vic)
enable_percpu_irq(msm_wdog_irq, IRQ_TYPE_EDGE_RISING);
printk(KERN_INFO "MSM Watchdog Initialized\n");
return;
}
static int msm_watchdog_probe(struct platform_device *pdev)
{
struct msm_watchdog_pdata *pdata = pdev->dev.platform_data;
if (!enable || !pdata || !pdata->pet_time || !pdata->bark_time) {
printk(KERN_INFO "MSM Watchdog Not Initialized\n");
return -ENODEV;
}
bark_time = pdata->bark_time;
/* reboot_bark_timeout (in seconds) might have been supplied as
* module parameter.
*/
if ((reboot_bark_timeout * MSEC_PER_SEC) < bark_time)
reboot_bark_timeout = (bark_time / MSEC_PER_SEC);
has_vic = pdata->has_vic;
if (!pdata->has_secure) {
appsbark = 1;
appsbark_fiq = pdata->use_kernel_fiq;
}
msm_wdt_base = pdata->base;
msm_wdog_irq = platform_get_irq(pdev, 0);
/*
* This is only temporary till SBLs turn on the XPUs
* This initialization will be done in SBLs on a later releases
*/
if (cpu_is_msm9615())
__raw_writel(0xF, MSM_TCSR_BASE + TCSR_WDT_CFG);
if (pdata->needs_expired_enable)
__raw_writel(0x1, MSM_CLK_CTL_BASE + 0x3820);
delay_time = msecs_to_jiffies(pdata->pet_time);
schedule_work_on(0, &init_dogwork_struct);
return 0;
}
static const struct dev_pm_ops msm_watchdog_dev_pm_ops = {
.suspend_noirq = msm_watchdog_suspend,
.resume_noirq = msm_watchdog_resume,
};
static struct platform_driver msm_watchdog_driver = {
.probe = msm_watchdog_probe,
.driver = {
.name = MODULE_NAME,
.owner = THIS_MODULE,
.pm = &msm_watchdog_dev_pm_ops,
},
};
static int init_watchdog(void)
{
return platform_driver_register(&msm_watchdog_driver);
}
late_initcall(init_watchdog);
MODULE_DESCRIPTION("MSM Watchdog Driver");
MODULE_VERSION("1.0");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
emceethemouth/kernel_androidone | drivers/infiniband/hw/qib/qib_sdma.c | 2372 | 26451 | /*
* Copyright (c) 2012 Intel Corporation. All rights reserved.
* Copyright (c) 2007 - 2012 QLogic Corporation. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/spinlock.h>
#include <linux/netdevice.h>
#include <linux/moduleparam.h>
#include "qib.h"
#include "qib_common.h"
/* default pio off, sdma on */
static ushort sdma_descq_cnt = 256;
module_param_named(sdma_descq_cnt, sdma_descq_cnt, ushort, S_IRUGO);
MODULE_PARM_DESC(sdma_descq_cnt, "Number of SDMA descq entries");
/*
* Bits defined in the send DMA descriptor.
*/
#define SDMA_DESC_LAST (1ULL << 11)
#define SDMA_DESC_FIRST (1ULL << 12)
#define SDMA_DESC_DMA_HEAD (1ULL << 13)
#define SDMA_DESC_USE_LARGE_BUF (1ULL << 14)
#define SDMA_DESC_INTR (1ULL << 15)
#define SDMA_DESC_COUNT_LSB 16
#define SDMA_DESC_GEN_LSB 30
char *qib_sdma_state_names[] = {
[qib_sdma_state_s00_hw_down] = "s00_HwDown",
[qib_sdma_state_s10_hw_start_up_wait] = "s10_HwStartUpWait",
[qib_sdma_state_s20_idle] = "s20_Idle",
[qib_sdma_state_s30_sw_clean_up_wait] = "s30_SwCleanUpWait",
[qib_sdma_state_s40_hw_clean_up_wait] = "s40_HwCleanUpWait",
[qib_sdma_state_s50_hw_halt_wait] = "s50_HwHaltWait",
[qib_sdma_state_s99_running] = "s99_Running",
};
char *qib_sdma_event_names[] = {
[qib_sdma_event_e00_go_hw_down] = "e00_GoHwDown",
[qib_sdma_event_e10_go_hw_start] = "e10_GoHwStart",
[qib_sdma_event_e20_hw_started] = "e20_HwStarted",
[qib_sdma_event_e30_go_running] = "e30_GoRunning",
[qib_sdma_event_e40_sw_cleaned] = "e40_SwCleaned",
[qib_sdma_event_e50_hw_cleaned] = "e50_HwCleaned",
[qib_sdma_event_e60_hw_halted] = "e60_HwHalted",
[qib_sdma_event_e70_go_idle] = "e70_GoIdle",
[qib_sdma_event_e7220_err_halted] = "e7220_ErrHalted",
[qib_sdma_event_e7322_err_halted] = "e7322_ErrHalted",
[qib_sdma_event_e90_timer_tick] = "e90_TimerTick",
};
/* declare all statics here rather than keep sorting */
static int alloc_sdma(struct qib_pportdata *);
static void sdma_complete(struct kref *);
static void sdma_finalput(struct qib_sdma_state *);
static void sdma_get(struct qib_sdma_state *);
static void sdma_put(struct qib_sdma_state *);
static void sdma_set_state(struct qib_pportdata *, enum qib_sdma_states);
static void sdma_start_sw_clean_up(struct qib_pportdata *);
static void sdma_sw_clean_up_task(unsigned long);
static void unmap_desc(struct qib_pportdata *, unsigned);
static void sdma_get(struct qib_sdma_state *ss)
{
kref_get(&ss->kref);
}
static void sdma_complete(struct kref *kref)
{
struct qib_sdma_state *ss =
container_of(kref, struct qib_sdma_state, kref);
complete(&ss->comp);
}
static void sdma_put(struct qib_sdma_state *ss)
{
kref_put(&ss->kref, sdma_complete);
}
static void sdma_finalput(struct qib_sdma_state *ss)
{
sdma_put(ss);
wait_for_completion(&ss->comp);
}
/*
* Complete all the sdma requests on the active list, in the correct
* order, and with appropriate processing. Called when cleaning up
* after sdma shutdown, and when new sdma requests are submitted for
* a link that is down. This matches what is done for requests
* that complete normally, it's just the full list.
*
* Must be called with sdma_lock held
*/
static void clear_sdma_activelist(struct qib_pportdata *ppd)
{
struct qib_sdma_txreq *txp, *txp_next;
list_for_each_entry_safe(txp, txp_next, &ppd->sdma_activelist, list) {
list_del_init(&txp->list);
if (txp->flags & QIB_SDMA_TXREQ_F_FREEDESC) {
unsigned idx;
idx = txp->start_idx;
while (idx != txp->next_descq_idx) {
unmap_desc(ppd, idx);
if (++idx == ppd->sdma_descq_cnt)
idx = 0;
}
}
if (txp->callback)
(*txp->callback)(txp, QIB_SDMA_TXREQ_S_ABORTED);
}
}
static void sdma_sw_clean_up_task(unsigned long opaque)
{
struct qib_pportdata *ppd = (struct qib_pportdata *) opaque;
unsigned long flags;
spin_lock_irqsave(&ppd->sdma_lock, flags);
/*
* At this point, the following should always be true:
* - We are halted, so no more descriptors are getting retired.
* - We are not running, so no one is submitting new work.
* - Only we can send the e40_sw_cleaned, so we can't start
* running again until we say so. So, the active list and
* descq are ours to play with.
*/
/* Process all retired requests. */
qib_sdma_make_progress(ppd);
clear_sdma_activelist(ppd);
/*
* Resync count of added and removed. It is VERY important that
* sdma_descq_removed NEVER decrement - user_sdma depends on it.
*/
ppd->sdma_descq_removed = ppd->sdma_descq_added;
/*
* Reset our notion of head and tail.
* Note that the HW registers will be reset when switching states
* due to calling __qib_sdma_process_event() below.
*/
ppd->sdma_descq_tail = 0;
ppd->sdma_descq_head = 0;
ppd->sdma_head_dma[0] = 0;
ppd->sdma_generation = 0;
__qib_sdma_process_event(ppd, qib_sdma_event_e40_sw_cleaned);
spin_unlock_irqrestore(&ppd->sdma_lock, flags);
}
/*
* This is called when changing to state qib_sdma_state_s10_hw_start_up_wait
* as a result of send buffer errors or send DMA descriptor errors.
* We want to disarm the buffers in these cases.
*/
static void sdma_hw_start_up(struct qib_pportdata *ppd)
{
struct qib_sdma_state *ss = &ppd->sdma_state;
unsigned bufno;
for (bufno = ss->first_sendbuf; bufno < ss->last_sendbuf; ++bufno)
ppd->dd->f_sendctrl(ppd, QIB_SENDCTRL_DISARM_BUF(bufno));
ppd->dd->f_sdma_hw_start_up(ppd);
}
static void sdma_sw_tear_down(struct qib_pportdata *ppd)
{
struct qib_sdma_state *ss = &ppd->sdma_state;
/* Releasing this reference means the state machine has stopped. */
sdma_put(ss);
}
static void sdma_start_sw_clean_up(struct qib_pportdata *ppd)
{
tasklet_hi_schedule(&ppd->sdma_sw_clean_up_task);
}
static void sdma_set_state(struct qib_pportdata *ppd,
enum qib_sdma_states next_state)
{
struct qib_sdma_state *ss = &ppd->sdma_state;
struct sdma_set_state_action *action = ss->set_state_action;
unsigned op = 0;
/* debugging bookkeeping */
ss->previous_state = ss->current_state;
ss->previous_op = ss->current_op;
ss->current_state = next_state;
if (action[next_state].op_enable)
op |= QIB_SDMA_SENDCTRL_OP_ENABLE;
if (action[next_state].op_intenable)
op |= QIB_SDMA_SENDCTRL_OP_INTENABLE;
if (action[next_state].op_halt)
op |= QIB_SDMA_SENDCTRL_OP_HALT;
if (action[next_state].op_drain)
op |= QIB_SDMA_SENDCTRL_OP_DRAIN;
if (action[next_state].go_s99_running_tofalse)
ss->go_s99_running = 0;
if (action[next_state].go_s99_running_totrue)
ss->go_s99_running = 1;
ss->current_op = op;
ppd->dd->f_sdma_sendctrl(ppd, ss->current_op);
}
static void unmap_desc(struct qib_pportdata *ppd, unsigned head)
{
__le64 *descqp = &ppd->sdma_descq[head].qw[0];
u64 desc[2];
dma_addr_t addr;
size_t len;
desc[0] = le64_to_cpu(descqp[0]);
desc[1] = le64_to_cpu(descqp[1]);
addr = (desc[1] << 32) | (desc[0] >> 32);
len = (desc[0] >> 14) & (0x7ffULL << 2);
dma_unmap_single(&ppd->dd->pcidev->dev, addr, len, DMA_TO_DEVICE);
}
static int alloc_sdma(struct qib_pportdata *ppd)
{
ppd->sdma_descq_cnt = sdma_descq_cnt;
if (!ppd->sdma_descq_cnt)
ppd->sdma_descq_cnt = 256;
/* Allocate memory for SendDMA descriptor FIFO */
ppd->sdma_descq = dma_alloc_coherent(&ppd->dd->pcidev->dev,
ppd->sdma_descq_cnt * sizeof(u64[2]), &ppd->sdma_descq_phys,
GFP_KERNEL);
if (!ppd->sdma_descq) {
qib_dev_err(ppd->dd,
"failed to allocate SendDMA descriptor FIFO memory\n");
goto bail;
}
/* Allocate memory for DMA of head register to memory */
ppd->sdma_head_dma = dma_alloc_coherent(&ppd->dd->pcidev->dev,
PAGE_SIZE, &ppd->sdma_head_phys, GFP_KERNEL);
if (!ppd->sdma_head_dma) {
qib_dev_err(ppd->dd,
"failed to allocate SendDMA head memory\n");
goto cleanup_descq;
}
ppd->sdma_head_dma[0] = 0;
return 0;
cleanup_descq:
dma_free_coherent(&ppd->dd->pcidev->dev,
ppd->sdma_descq_cnt * sizeof(u64[2]), (void *)ppd->sdma_descq,
ppd->sdma_descq_phys);
ppd->sdma_descq = NULL;
ppd->sdma_descq_phys = 0;
bail:
ppd->sdma_descq_cnt = 0;
return -ENOMEM;
}
static void free_sdma(struct qib_pportdata *ppd)
{
struct qib_devdata *dd = ppd->dd;
if (ppd->sdma_head_dma) {
dma_free_coherent(&dd->pcidev->dev, PAGE_SIZE,
(void *)ppd->sdma_head_dma,
ppd->sdma_head_phys);
ppd->sdma_head_dma = NULL;
ppd->sdma_head_phys = 0;
}
if (ppd->sdma_descq) {
dma_free_coherent(&dd->pcidev->dev,
ppd->sdma_descq_cnt * sizeof(u64[2]),
ppd->sdma_descq, ppd->sdma_descq_phys);
ppd->sdma_descq = NULL;
ppd->sdma_descq_phys = 0;
}
}
static inline void make_sdma_desc(struct qib_pportdata *ppd,
u64 *sdmadesc, u64 addr, u64 dwlen,
u64 dwoffset)
{
WARN_ON(addr & 3);
/* SDmaPhyAddr[47:32] */
sdmadesc[1] = addr >> 32;
/* SDmaPhyAddr[31:0] */
sdmadesc[0] = (addr & 0xfffffffcULL) << 32;
/* SDmaGeneration[1:0] */
sdmadesc[0] |= (ppd->sdma_generation & 3ULL) <<
SDMA_DESC_GEN_LSB;
/* SDmaDwordCount[10:0] */
sdmadesc[0] |= (dwlen & 0x7ffULL) << SDMA_DESC_COUNT_LSB;
/* SDmaBufOffset[12:2] */
sdmadesc[0] |= dwoffset & 0x7ffULL;
}
/* sdma_lock must be held */
int qib_sdma_make_progress(struct qib_pportdata *ppd)
{
struct list_head *lp = NULL;
struct qib_sdma_txreq *txp = NULL;
struct qib_devdata *dd = ppd->dd;
int progress = 0;
u16 hwhead;
u16 idx = 0;
hwhead = dd->f_sdma_gethead(ppd);
/* The reason for some of the complexity of this code is that
* not all descriptors have corresponding txps. So, we have to
* be able to skip over descs until we wander into the range of
* the next txp on the list.
*/
if (!list_empty(&ppd->sdma_activelist)) {
lp = ppd->sdma_activelist.next;
txp = list_entry(lp, struct qib_sdma_txreq, list);
idx = txp->start_idx;
}
while (ppd->sdma_descq_head != hwhead) {
/* if desc is part of this txp, unmap if needed */
if (txp && (txp->flags & QIB_SDMA_TXREQ_F_FREEDESC) &&
(idx == ppd->sdma_descq_head)) {
unmap_desc(ppd, ppd->sdma_descq_head);
if (++idx == ppd->sdma_descq_cnt)
idx = 0;
}
/* increment dequed desc count */
ppd->sdma_descq_removed++;
/* advance head, wrap if needed */
if (++ppd->sdma_descq_head == ppd->sdma_descq_cnt)
ppd->sdma_descq_head = 0;
/* if now past this txp's descs, do the callback */
if (txp && txp->next_descq_idx == ppd->sdma_descq_head) {
/* remove from active list */
list_del_init(&txp->list);
if (txp->callback)
(*txp->callback)(txp, QIB_SDMA_TXREQ_S_OK);
/* see if there is another txp */
if (list_empty(&ppd->sdma_activelist))
txp = NULL;
else {
lp = ppd->sdma_activelist.next;
txp = list_entry(lp, struct qib_sdma_txreq,
list);
idx = txp->start_idx;
}
}
progress = 1;
}
if (progress)
qib_verbs_sdma_desc_avail(ppd, qib_sdma_descq_freecnt(ppd));
return progress;
}
/*
* This is called from interrupt context.
*/
void qib_sdma_intr(struct qib_pportdata *ppd)
{
unsigned long flags;
spin_lock_irqsave(&ppd->sdma_lock, flags);
__qib_sdma_intr(ppd);
spin_unlock_irqrestore(&ppd->sdma_lock, flags);
}
void __qib_sdma_intr(struct qib_pportdata *ppd)
{
if (__qib_sdma_running(ppd))
qib_sdma_make_progress(ppd);
}
int qib_setup_sdma(struct qib_pportdata *ppd)
{
struct qib_devdata *dd = ppd->dd;
unsigned long flags;
int ret = 0;
ret = alloc_sdma(ppd);
if (ret)
goto bail;
/* set consistent sdma state */
ppd->dd->f_sdma_init_early(ppd);
spin_lock_irqsave(&ppd->sdma_lock, flags);
sdma_set_state(ppd, qib_sdma_state_s00_hw_down);
spin_unlock_irqrestore(&ppd->sdma_lock, flags);
/* set up reference counting */
kref_init(&ppd->sdma_state.kref);
init_completion(&ppd->sdma_state.comp);
ppd->sdma_generation = 0;
ppd->sdma_descq_head = 0;
ppd->sdma_descq_removed = 0;
ppd->sdma_descq_added = 0;
INIT_LIST_HEAD(&ppd->sdma_activelist);
tasklet_init(&ppd->sdma_sw_clean_up_task, sdma_sw_clean_up_task,
(unsigned long)ppd);
ret = dd->f_init_sdma_regs(ppd);
if (ret)
goto bail_alloc;
qib_sdma_process_event(ppd, qib_sdma_event_e10_go_hw_start);
return 0;
bail_alloc:
qib_teardown_sdma(ppd);
bail:
return ret;
}
void qib_teardown_sdma(struct qib_pportdata *ppd)
{
qib_sdma_process_event(ppd, qib_sdma_event_e00_go_hw_down);
/*
* This waits for the state machine to exit so it is not
* necessary to kill the sdma_sw_clean_up_task to make sure
* it is not running.
*/
sdma_finalput(&ppd->sdma_state);
free_sdma(ppd);
}
int qib_sdma_running(struct qib_pportdata *ppd)
{
unsigned long flags;
int ret;
spin_lock_irqsave(&ppd->sdma_lock, flags);
ret = __qib_sdma_running(ppd);
spin_unlock_irqrestore(&ppd->sdma_lock, flags);
return ret;
}
/*
* Complete a request when sdma not running; likely only request
* but to simplify the code, always queue it, then process the full
* activelist. We process the entire list to ensure that this particular
* request does get it's callback, but in the correct order.
* Must be called with sdma_lock held
*/
static void complete_sdma_err_req(struct qib_pportdata *ppd,
struct qib_verbs_txreq *tx)
{
atomic_inc(&tx->qp->s_dma_busy);
/* no sdma descriptors, so no unmap_desc */
tx->txreq.start_idx = 0;
tx->txreq.next_descq_idx = 0;
list_add_tail(&tx->txreq.list, &ppd->sdma_activelist);
clear_sdma_activelist(ppd);
}
/*
* This function queues one IB packet onto the send DMA queue per call.
* The caller is responsible for checking:
* 1) The number of send DMA descriptor entries is less than the size of
* the descriptor queue.
* 2) The IB SGE addresses and lengths are 32-bit aligned
* (except possibly the last SGE's length)
* 3) The SGE addresses are suitable for passing to dma_map_single().
*/
int qib_sdma_verbs_send(struct qib_pportdata *ppd,
struct qib_sge_state *ss, u32 dwords,
struct qib_verbs_txreq *tx)
{
unsigned long flags;
struct qib_sge *sge;
struct qib_qp *qp;
int ret = 0;
u16 tail;
__le64 *descqp;
u64 sdmadesc[2];
u32 dwoffset;
dma_addr_t addr;
spin_lock_irqsave(&ppd->sdma_lock, flags);
retry:
if (unlikely(!__qib_sdma_running(ppd))) {
complete_sdma_err_req(ppd, tx);
goto unlock;
}
if (tx->txreq.sg_count > qib_sdma_descq_freecnt(ppd)) {
if (qib_sdma_make_progress(ppd))
goto retry;
if (ppd->dd->flags & QIB_HAS_SDMA_TIMEOUT)
ppd->dd->f_sdma_set_desc_cnt(ppd,
ppd->sdma_descq_cnt / 2);
goto busy;
}
dwoffset = tx->hdr_dwords;
make_sdma_desc(ppd, sdmadesc, (u64) tx->txreq.addr, dwoffset, 0);
sdmadesc[0] |= SDMA_DESC_FIRST;
if (tx->txreq.flags & QIB_SDMA_TXREQ_F_USELARGEBUF)
sdmadesc[0] |= SDMA_DESC_USE_LARGE_BUF;
/* write to the descq */
tail = ppd->sdma_descq_tail;
descqp = &ppd->sdma_descq[tail].qw[0];
*descqp++ = cpu_to_le64(sdmadesc[0]);
*descqp++ = cpu_to_le64(sdmadesc[1]);
/* increment the tail */
if (++tail == ppd->sdma_descq_cnt) {
tail = 0;
descqp = &ppd->sdma_descq[0].qw[0];
++ppd->sdma_generation;
}
tx->txreq.start_idx = tail;
sge = &ss->sge;
while (dwords) {
u32 dw;
u32 len;
len = dwords << 2;
if (len > sge->length)
len = sge->length;
if (len > sge->sge_length)
len = sge->sge_length;
BUG_ON(len == 0);
dw = (len + 3) >> 2;
addr = dma_map_single(&ppd->dd->pcidev->dev, sge->vaddr,
dw << 2, DMA_TO_DEVICE);
if (dma_mapping_error(&ppd->dd->pcidev->dev, addr))
goto unmap;
sdmadesc[0] = 0;
make_sdma_desc(ppd, sdmadesc, (u64) addr, dw, dwoffset);
/* SDmaUseLargeBuf has to be set in every descriptor */
if (tx->txreq.flags & QIB_SDMA_TXREQ_F_USELARGEBUF)
sdmadesc[0] |= SDMA_DESC_USE_LARGE_BUF;
/* write to the descq */
*descqp++ = cpu_to_le64(sdmadesc[0]);
*descqp++ = cpu_to_le64(sdmadesc[1]);
/* increment the tail */
if (++tail == ppd->sdma_descq_cnt) {
tail = 0;
descqp = &ppd->sdma_descq[0].qw[0];
++ppd->sdma_generation;
}
sge->vaddr += len;
sge->length -= len;
sge->sge_length -= len;
if (sge->sge_length == 0) {
if (--ss->num_sge)
*sge = *ss->sg_list++;
} else if (sge->length == 0 && sge->mr->lkey) {
if (++sge->n >= QIB_SEGSZ) {
if (++sge->m >= sge->mr->mapsz)
break;
sge->n = 0;
}
sge->vaddr =
sge->mr->map[sge->m]->segs[sge->n].vaddr;
sge->length =
sge->mr->map[sge->m]->segs[sge->n].length;
}
dwoffset += dw;
dwords -= dw;
}
if (!tail)
descqp = &ppd->sdma_descq[ppd->sdma_descq_cnt].qw[0];
descqp -= 2;
descqp[0] |= cpu_to_le64(SDMA_DESC_LAST);
if (tx->txreq.flags & QIB_SDMA_TXREQ_F_HEADTOHOST)
descqp[0] |= cpu_to_le64(SDMA_DESC_DMA_HEAD);
if (tx->txreq.flags & QIB_SDMA_TXREQ_F_INTREQ)
descqp[0] |= cpu_to_le64(SDMA_DESC_INTR);
atomic_inc(&tx->qp->s_dma_busy);
tx->txreq.next_descq_idx = tail;
ppd->dd->f_sdma_update_tail(ppd, tail);
ppd->sdma_descq_added += tx->txreq.sg_count;
list_add_tail(&tx->txreq.list, &ppd->sdma_activelist);
goto unlock;
unmap:
for (;;) {
if (!tail)
tail = ppd->sdma_descq_cnt - 1;
else
tail--;
if (tail == ppd->sdma_descq_tail)
break;
unmap_desc(ppd, tail);
}
qp = tx->qp;
qib_put_txreq(tx);
spin_lock(&qp->r_lock);
spin_lock(&qp->s_lock);
if (qp->ibqp.qp_type == IB_QPT_RC) {
/* XXX what about error sending RDMA read responses? */
if (ib_qib_state_ops[qp->state] & QIB_PROCESS_RECV_OK)
qib_error_qp(qp, IB_WC_GENERAL_ERR);
} else if (qp->s_wqe)
qib_send_complete(qp, qp->s_wqe, IB_WC_GENERAL_ERR);
spin_unlock(&qp->s_lock);
spin_unlock(&qp->r_lock);
/* return zero to process the next send work request */
goto unlock;
busy:
qp = tx->qp;
spin_lock(&qp->s_lock);
if (ib_qib_state_ops[qp->state] & QIB_PROCESS_RECV_OK) {
struct qib_ibdev *dev;
/*
* If we couldn't queue the DMA request, save the info
* and try again later rather than destroying the
* buffer and undoing the side effects of the copy.
*/
tx->ss = ss;
tx->dwords = dwords;
qp->s_tx = tx;
dev = &ppd->dd->verbs_dev;
spin_lock(&dev->pending_lock);
if (list_empty(&qp->iowait)) {
struct qib_ibport *ibp;
ibp = &ppd->ibport_data;
ibp->n_dmawait++;
qp->s_flags |= QIB_S_WAIT_DMA_DESC;
list_add_tail(&qp->iowait, &dev->dmawait);
}
spin_unlock(&dev->pending_lock);
qp->s_flags &= ~QIB_S_BUSY;
spin_unlock(&qp->s_lock);
ret = -EBUSY;
} else {
spin_unlock(&qp->s_lock);
qib_put_txreq(tx);
}
unlock:
spin_unlock_irqrestore(&ppd->sdma_lock, flags);
return ret;
}
void qib_sdma_process_event(struct qib_pportdata *ppd,
enum qib_sdma_events event)
{
unsigned long flags;
spin_lock_irqsave(&ppd->sdma_lock, flags);
__qib_sdma_process_event(ppd, event);
if (ppd->sdma_state.current_state == qib_sdma_state_s99_running)
qib_verbs_sdma_desc_avail(ppd, qib_sdma_descq_freecnt(ppd));
spin_unlock_irqrestore(&ppd->sdma_lock, flags);
}
void __qib_sdma_process_event(struct qib_pportdata *ppd,
enum qib_sdma_events event)
{
struct qib_sdma_state *ss = &ppd->sdma_state;
switch (ss->current_state) {
case qib_sdma_state_s00_hw_down:
switch (event) {
case qib_sdma_event_e00_go_hw_down:
break;
case qib_sdma_event_e30_go_running:
/*
* If down, but running requested (usually result
* of link up, then we need to start up.
* This can happen when hw down is requested while
* bringing the link up with traffic active on
* 7220, e.g. */
ss->go_s99_running = 1;
/* fall through and start dma engine */
case qib_sdma_event_e10_go_hw_start:
/* This reference means the state machine is started */
sdma_get(&ppd->sdma_state);
sdma_set_state(ppd,
qib_sdma_state_s10_hw_start_up_wait);
break;
case qib_sdma_event_e20_hw_started:
break;
case qib_sdma_event_e40_sw_cleaned:
sdma_sw_tear_down(ppd);
break;
case qib_sdma_event_e50_hw_cleaned:
break;
case qib_sdma_event_e60_hw_halted:
break;
case qib_sdma_event_e70_go_idle:
break;
case qib_sdma_event_e7220_err_halted:
break;
case qib_sdma_event_e7322_err_halted:
break;
case qib_sdma_event_e90_timer_tick:
break;
}
break;
case qib_sdma_state_s10_hw_start_up_wait:
switch (event) {
case qib_sdma_event_e00_go_hw_down:
sdma_set_state(ppd, qib_sdma_state_s00_hw_down);
sdma_sw_tear_down(ppd);
break;
case qib_sdma_event_e10_go_hw_start:
break;
case qib_sdma_event_e20_hw_started:
sdma_set_state(ppd, ss->go_s99_running ?
qib_sdma_state_s99_running :
qib_sdma_state_s20_idle);
break;
case qib_sdma_event_e30_go_running:
ss->go_s99_running = 1;
break;
case qib_sdma_event_e40_sw_cleaned:
break;
case qib_sdma_event_e50_hw_cleaned:
break;
case qib_sdma_event_e60_hw_halted:
break;
case qib_sdma_event_e70_go_idle:
ss->go_s99_running = 0;
break;
case qib_sdma_event_e7220_err_halted:
break;
case qib_sdma_event_e7322_err_halted:
break;
case qib_sdma_event_e90_timer_tick:
break;
}
break;
case qib_sdma_state_s20_idle:
switch (event) {
case qib_sdma_event_e00_go_hw_down:
sdma_set_state(ppd, qib_sdma_state_s00_hw_down);
sdma_sw_tear_down(ppd);
break;
case qib_sdma_event_e10_go_hw_start:
break;
case qib_sdma_event_e20_hw_started:
break;
case qib_sdma_event_e30_go_running:
sdma_set_state(ppd, qib_sdma_state_s99_running);
ss->go_s99_running = 1;
break;
case qib_sdma_event_e40_sw_cleaned:
break;
case qib_sdma_event_e50_hw_cleaned:
break;
case qib_sdma_event_e60_hw_halted:
break;
case qib_sdma_event_e70_go_idle:
break;
case qib_sdma_event_e7220_err_halted:
break;
case qib_sdma_event_e7322_err_halted:
break;
case qib_sdma_event_e90_timer_tick:
break;
}
break;
case qib_sdma_state_s30_sw_clean_up_wait:
switch (event) {
case qib_sdma_event_e00_go_hw_down:
sdma_set_state(ppd, qib_sdma_state_s00_hw_down);
break;
case qib_sdma_event_e10_go_hw_start:
break;
case qib_sdma_event_e20_hw_started:
break;
case qib_sdma_event_e30_go_running:
ss->go_s99_running = 1;
break;
case qib_sdma_event_e40_sw_cleaned:
sdma_set_state(ppd,
qib_sdma_state_s10_hw_start_up_wait);
sdma_hw_start_up(ppd);
break;
case qib_sdma_event_e50_hw_cleaned:
break;
case qib_sdma_event_e60_hw_halted:
break;
case qib_sdma_event_e70_go_idle:
ss->go_s99_running = 0;
break;
case qib_sdma_event_e7220_err_halted:
break;
case qib_sdma_event_e7322_err_halted:
break;
case qib_sdma_event_e90_timer_tick:
break;
}
break;
case qib_sdma_state_s40_hw_clean_up_wait:
switch (event) {
case qib_sdma_event_e00_go_hw_down:
sdma_set_state(ppd, qib_sdma_state_s00_hw_down);
sdma_start_sw_clean_up(ppd);
break;
case qib_sdma_event_e10_go_hw_start:
break;
case qib_sdma_event_e20_hw_started:
break;
case qib_sdma_event_e30_go_running:
ss->go_s99_running = 1;
break;
case qib_sdma_event_e40_sw_cleaned:
break;
case qib_sdma_event_e50_hw_cleaned:
sdma_set_state(ppd,
qib_sdma_state_s30_sw_clean_up_wait);
sdma_start_sw_clean_up(ppd);
break;
case qib_sdma_event_e60_hw_halted:
break;
case qib_sdma_event_e70_go_idle:
ss->go_s99_running = 0;
break;
case qib_sdma_event_e7220_err_halted:
break;
case qib_sdma_event_e7322_err_halted:
break;
case qib_sdma_event_e90_timer_tick:
break;
}
break;
case qib_sdma_state_s50_hw_halt_wait:
switch (event) {
case qib_sdma_event_e00_go_hw_down:
sdma_set_state(ppd, qib_sdma_state_s00_hw_down);
sdma_start_sw_clean_up(ppd);
break;
case qib_sdma_event_e10_go_hw_start:
break;
case qib_sdma_event_e20_hw_started:
break;
case qib_sdma_event_e30_go_running:
ss->go_s99_running = 1;
break;
case qib_sdma_event_e40_sw_cleaned:
break;
case qib_sdma_event_e50_hw_cleaned:
break;
case qib_sdma_event_e60_hw_halted:
sdma_set_state(ppd,
qib_sdma_state_s40_hw_clean_up_wait);
ppd->dd->f_sdma_hw_clean_up(ppd);
break;
case qib_sdma_event_e70_go_idle:
ss->go_s99_running = 0;
break;
case qib_sdma_event_e7220_err_halted:
break;
case qib_sdma_event_e7322_err_halted:
break;
case qib_sdma_event_e90_timer_tick:
break;
}
break;
case qib_sdma_state_s99_running:
switch (event) {
case qib_sdma_event_e00_go_hw_down:
sdma_set_state(ppd, qib_sdma_state_s00_hw_down);
sdma_start_sw_clean_up(ppd);
break;
case qib_sdma_event_e10_go_hw_start:
break;
case qib_sdma_event_e20_hw_started:
break;
case qib_sdma_event_e30_go_running:
break;
case qib_sdma_event_e40_sw_cleaned:
break;
case qib_sdma_event_e50_hw_cleaned:
break;
case qib_sdma_event_e60_hw_halted:
sdma_set_state(ppd,
qib_sdma_state_s30_sw_clean_up_wait);
sdma_start_sw_clean_up(ppd);
break;
case qib_sdma_event_e70_go_idle:
sdma_set_state(ppd, qib_sdma_state_s50_hw_halt_wait);
ss->go_s99_running = 0;
break;
case qib_sdma_event_e7220_err_halted:
sdma_set_state(ppd,
qib_sdma_state_s30_sw_clean_up_wait);
sdma_start_sw_clean_up(ppd);
break;
case qib_sdma_event_e7322_err_halted:
sdma_set_state(ppd, qib_sdma_state_s50_hw_halt_wait);
break;
case qib_sdma_event_e90_timer_tick:
break;
}
break;
}
ss->last_event = event;
}
| gpl-2.0 |
brieuwers/N8000Kernel | arch/mips/kernel/mips-mt-fpaff.c | 3140 | 5123 | /*
* General MIPS MT support routines, usable in AP/SP, SMVP, or SMTC kernels
* Copyright (C) 2005 Mips Technologies, Inc
*/
#include <linux/cpu.h>
#include <linux/cpuset.h>
#include <linux/cpumask.h>
#include <linux/delay.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/security.h>
#include <linux/types.h>
#include <asm/uaccess.h>
/*
* CPU mask used to set process affinity for MT VPEs/TCs with FPUs
*/
cpumask_t mt_fpu_cpumask;
static int fpaff_threshold = -1;
unsigned long mt_fpemul_threshold;
/*
* Replacement functions for the sys_sched_setaffinity() and
* sys_sched_getaffinity() system calls, so that we can integrate
* FPU affinity with the user's requested processor affinity.
* This code is 98% identical with the sys_sched_setaffinity()
* and sys_sched_getaffinity() system calls, and should be
* updated when kernel/sched.c changes.
*/
/*
* find_process_by_pid - find a process with a matching PID value.
* used in sys_sched_set/getaffinity() in kernel/sched.c, so
* cloned here.
*/
static inline struct task_struct *find_process_by_pid(pid_t pid)
{
return pid ? find_task_by_vpid(pid) : current;
}
/*
* check the target process has a UID that matches the current process's
*/
static bool check_same_owner(struct task_struct *p)
{
const struct cred *cred = current_cred(), *pcred;
bool match;
rcu_read_lock();
pcred = __task_cred(p);
match = (cred->euid == pcred->euid ||
cred->euid == pcred->uid);
rcu_read_unlock();
return match;
}
/*
* mipsmt_sys_sched_setaffinity - set the cpu affinity of a process
*/
asmlinkage long mipsmt_sys_sched_setaffinity(pid_t pid, unsigned int len,
unsigned long __user *user_mask_ptr)
{
cpumask_var_t cpus_allowed, new_mask, effective_mask;
struct thread_info *ti;
struct task_struct *p;
int retval;
if (len < sizeof(new_mask))
return -EINVAL;
if (copy_from_user(&new_mask, user_mask_ptr, sizeof(new_mask)))
return -EFAULT;
get_online_cpus();
rcu_read_lock();
p = find_process_by_pid(pid);
if (!p) {
rcu_read_unlock();
put_online_cpus();
return -ESRCH;
}
/* Prevent p going away */
get_task_struct(p);
rcu_read_unlock();
if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
retval = -ENOMEM;
goto out_put_task;
}
if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
retval = -ENOMEM;
goto out_free_cpus_allowed;
}
if (!alloc_cpumask_var(&effective_mask, GFP_KERNEL)) {
retval = -ENOMEM;
goto out_free_new_mask;
}
retval = -EPERM;
if (!check_same_owner(p) && !capable(CAP_SYS_NICE))
goto out_unlock;
retval = security_task_setscheduler(p);
if (retval)
goto out_unlock;
/* Record new user-specified CPU set for future reference */
cpumask_copy(&p->thread.user_cpus_allowed, new_mask);
again:
/* Compute new global allowed CPU set if necessary */
ti = task_thread_info(p);
if (test_ti_thread_flag(ti, TIF_FPUBOUND) &&
cpus_intersects(*new_mask, mt_fpu_cpumask)) {
cpus_and(*effective_mask, *new_mask, mt_fpu_cpumask);
retval = set_cpus_allowed_ptr(p, effective_mask);
} else {
cpumask_copy(effective_mask, new_mask);
clear_ti_thread_flag(ti, TIF_FPUBOUND);
retval = set_cpus_allowed_ptr(p, new_mask);
}
if (!retval) {
cpuset_cpus_allowed(p, cpus_allowed);
if (!cpumask_subset(effective_mask, cpus_allowed)) {
/*
* We must have raced with a concurrent cpuset
* update. Just reset the cpus_allowed to the
* cpuset's cpus_allowed
*/
cpumask_copy(new_mask, cpus_allowed);
goto again;
}
}
out_unlock:
free_cpumask_var(effective_mask);
out_free_new_mask:
free_cpumask_var(new_mask);
out_free_cpus_allowed:
free_cpumask_var(cpus_allowed);
out_put_task:
put_task_struct(p);
put_online_cpus();
return retval;
}
/*
* mipsmt_sys_sched_getaffinity - get the cpu affinity of a process
*/
asmlinkage long mipsmt_sys_sched_getaffinity(pid_t pid, unsigned int len,
unsigned long __user *user_mask_ptr)
{
unsigned int real_len;
cpumask_t mask;
int retval;
struct task_struct *p;
real_len = sizeof(mask);
if (len < real_len)
return -EINVAL;
get_online_cpus();
read_lock(&tasklist_lock);
retval = -ESRCH;
p = find_process_by_pid(pid);
if (!p)
goto out_unlock;
retval = security_task_getscheduler(p);
if (retval)
goto out_unlock;
cpus_and(mask, p->thread.user_cpus_allowed, cpu_possible_map);
out_unlock:
read_unlock(&tasklist_lock);
put_online_cpus();
if (retval)
return retval;
if (copy_to_user(user_mask_ptr, &mask, real_len))
return -EFAULT;
return real_len;
}
static int __init fpaff_thresh(char *str)
{
get_option(&str, &fpaff_threshold);
return 1;
}
__setup("fpaff=", fpaff_thresh);
/*
* FPU Use Factor empirically derived from experiments on 34K
*/
#define FPUSEFACTOR 2000
static __init int mt_fp_affinity_init(void)
{
if (fpaff_threshold >= 0) {
mt_fpemul_threshold = fpaff_threshold;
} else {
mt_fpemul_threshold =
(FPUSEFACTOR * (loops_per_jiffy/(500000/HZ))) / HZ;
}
printk(KERN_DEBUG "FPU Affinity set after %ld emulations\n",
mt_fpemul_threshold);
return 0;
}
arch_initcall(mt_fp_affinity_init);
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.